tods-competition-factory 2.0.10 → 2.0.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,2 +1,24 @@
1
- import{removeTournamentExtension as e,addTournamentExtension as t,addEventExtension as r}from"@Mutate/extensions/addRemoveExtensions";import{getTournamentIds as n}from"@Query/tournaments/getTournamentIds";import{removeExtension as i}from"@Mutate/extensions/removeExtension";import{decorateResult as a}from"@Functions/global/decorateResult";import{addExtension as o}from"@Mutate/extensions/addExtension";import{findExtension as s}from"@Acquire/findExtension";import{intersection as c,unique as u,overlap as d,chunkArray as p,generateRange as l,groupConsecutiveNumbers as m,shuffleArray as f,numericSortValue as h,randomPop as g,uniqueValues as I,instanceCount as U}from"@Tools/arrays";import{checkRequiredParameters as y}from"@Helpers/parameters/checkRequiredParameters";import{definedAttributes as S}from"@Tools/definedAttributes";import{getParticipantId as v,getMatchUpId as T,getDrawId as P,getMatchUpIds as D}from"@Functions/global/extractors";import{findStructure as w,getDrawStructures as b}from"@Acquire/findStructure";import{assignDrawPositionBye as R}from"@Mutate/matchUps/drawPositions/assignDrawPositionBye";import{clearDrawPosition as N}from"@Mutate/matchUps/drawPositions/positionClear";import{findTournamentParticipant as M}from"@Acquire/findTournamentParticipant";import{modifyEntriesStatus as A}from"@Mutate/entries/modifyEntriesStatus";import{destroyPairEntry as E}from"@Mutate/entries/destroyPairEntry";import{addParticipantGroupings as C}from"@Mutate/drawDefinitions/positionGovernor/avoidance/addParticipantGroupings";import{addUpcomingMatchUps as O}from"@Mutate/drawDefinitions/matchUpGovernor/addUpcomingMatchUps";import{getStructureMatchUps as F}from"@Query/structure/getStructureMatchUps";import{getContextContent as k}from"@Query/hierarchical/getContextContent";import{getExitProfiles as _}from"@Query/drawDefinition/getExitProfile";import{filterMatchUps as x}from"@Query/filterMatchUps";import{makeDeepCopy as L}from"@Tools/makeDeepCopy";import{structureSort as V}from"@Functions/sorters/structureSort";import{modifyRoundRobinMatchUpsStatus as B}from"@Mutate/matchUps/matchUpStatus/modifyRoundRobinMatchUpsStatus";import{getStructureDrawPositionProfiles as j}from"@Query/structure/getStructureDrawPositionProfiles";import{modifyPositionAssignmentsNotice as G,modifyMatchUpNotice as q,modifyDrawNotice as $,addMatchUpsNotice as W,deleteMatchUpsNotice as H,addDrawNotice as z}from"@Mutate/notifications/drawNotifications";import{getStructureSeedAssignments as Y}from"@Query/structure/getStructureSeedAssignments";import{getPositionAssignments as Q,structureAssignedDrawPositions as K}from"@Query/drawDefinition/positionsGetter";import{getAllStructureMatchUps as J}from"@Query/matchUps/getAllStructureMatchUps";import{assignSeed as Z}from"@Mutate/drawDefinitions/entryGovernor/seedAssignment";import{getInitialRoundNumber as X}from"@Query/matchUps/getInitialRoundNumber";import{updateSideLineUp as ee}from"@Mutate/matchUps/lineUps/updateSideLineUp";import{getAppliedPolicies as te,getPolicyDefinitions as re}from"@Query/extensions/getAppliedPolicies";import{getPairedPreviousMatchUpIsDoubleExit as ne}from"@Mutate/drawDefinitions/positionGovernor/getPairedPreviousMatchUpIsDoubleExit";import{getUpdatedDrawPositions as ie}from"@Mutate/drawDefinitions/matchUpGovernor/getUpdatedDrawPositions";import{updateMatchUpStatusCodes as ae}from"@Mutate/drawDefinitions/matchUpGovernor/matchUpStatusCodes";import{getExitWinningSide as oe}from"@Mutate/drawDefinitions/matchUpGovernor/getExitWinningSide";import{getMatchUpsMap as se,getMappedStructureMatchUps as ce}from"@Query/matchUps/getMatchUpsMap";import{getAllDrawMatchUps as ue}from"@Query/matchUps/drawMatchUps";import{positionTargets as de}from"@Query/matchUp/positionTargets";import{addPositionActionTelemetry as pe}from"@Mutate/drawDefinitions/positionGovernor/addPositionActionTelemetry";import{getRoundMatchUps as le}from"@Query/matchUps/getRoundMatchUps";import{pushGlobalLog as me}from"@Functions/global/globalLog";import{numericSort as fe}from"@Tools/sorting";import{getTargetMatchUps as he}from"@Query/matchUps/getTargetMatchUps";import{isValidSeedPosition as ge,getValidSeedBlocks as Ie,getSeedPattern as Ue}from"@Query/drawDefinition/seedGetter";import{resetLineUps as ye}from"@Mutate/matchUps/lineUps/resetLineUps";import{isAdHoc as Se}from"@Query/drawDefinition/isAdHoc";import{ensureInt as ve}from"@Tools/ensureInt";import{getMatchUpCompetitiveProfile as Te}from"@Query/matchUp/getMatchUpCompetitiveProfile";import{getCheckedInParticipantIds as Pe}from"@Query/matchUp/getCheckedInParticipantIds";import{getMatchUpScheduleDetails as De}from"@Query/matchUp/getMatchUpScheduleDetails";import{resolveTieFormat as we}from"@Query/hierarchical/tieFormats/resolveTieFormat";import{parse as be}from"@Assemblies/generators/matchUpFormatCode/parse";import{getCollectionPositionAssignments as Re}from"@Query/hierarchical/tieFormats/getCollectionPositionAssignments";import{getPairedParticipant as Ne}from"@Query/participant/getPairedParticipant";import{getTeamLineUp as Me}from"@Query/drawDefinition/getTeamLineUp";import{isLucky as Ae}from"@Query/drawDefinition/isLucky";import{getMatchUpType as Ee}from"@Query/matchUp/getMatchUpType";import{attributeFilter as Ce}from"@Tools/attributeFilter";import{findParticipant as Oe}from"@Acquire/findParticipant";import{isConvertableInteger as Fe,isPowerOf2 as ke,deriveExponent as _e,nearestPowerOf2 as xe,nextPowerOf2 as Le,coerceEven as Ve,median as Be,isNumeric as je}from"@Tools/math";import{updateTeamLineUp as Ge}from"@Mutate/drawDefinitions/updateTeamLineUp";import{checkMatchUpIsComplete as qe}from"@Query/matchUp/checkMatchUpIsComplete";import{assignDrawPosition as $e}from"@Mutate/matchUps/drawPositions/positionAssignment";import{getAttributeGroupings as We}from"@Query/participants/getAttributeGrouping";import{processAccessors as He}from"@Query/drawDefinition/processAccessors";import{positionQualifiers as ze}from"@Mutate/matchUps/drawPositions/positionQualifiers";import{getDevContext as Ye,disableNotifications as Qe,enableNotifications as Ke,addNotice as Je,getTopics as Ze,setTournamentId as Xe,setTournamentRecords as et,getTournamentRecords as tt,getTournamentId as rt,getTournamentRecord as nt,setTournamentRecord as it,setMethods as at,handleCaughtError as ot}from"@Global/state/globalState";import{positionSeedBlocks as st}from"@Mutate/matchUps/drawPositions/positionSeeds";import{getValidGroupSizes as ct}from"@Assemblies/generators/drawDefinitions/drawTypes/roundRobin/roundRobin";import{getByesData as ut}from"@Query/drawDefinition/getByesData";import{getQualifiersCount as dt}from"@Query/drawDefinition/getQualifiersCount";import{getParticipants as pt}from"@Query/participants/getParticipants";import{getStageEntries as lt}from"@Query/drawDefinition/stageGetter";import{isObject as mt,xa as ft,isFunction as ht,isString as gt,objShallowEqual as It}from"@Tools/objects";import Ut,{structureTemplate as yt}from"@Generators/templates/structureTemplate";import{constantToString as St}from"@Tools/strings";import{UUID as vt}from"@Tools/UUID";import{generatePlayoffStructures as Tt}from"@Generators/drawDefinitions/drawTypes/playoffStructures";import{getPositionRangeMap as Pt}from"@Query/drawDefinition/getPositionRangeMap";import{getAvailablePlayoffProfiles as Dt}from"@Query/drawDefinition/getAvailablePlayoffProfiles";import{directParticipants as wt}from"@Mutate/matchUps/drawPositions/directParticipants";import{addGoesTo as bt}from"@Mutate/drawDefinitions/matchUpGovernor/addGoesTo";import{getSourceRounds as Rt}from"@Query/drawDefinition/getSourceRounds";import{addTimeItem as Nt,addEventTimeItem as Mt,addTournamentTimeItem as At}from"@Mutate/timeItems/addTimeItem";import{addFinishingRounds as Et}from"@Assemblies/generators/drawDefinitions/addFinishingRounds";import{attachPolicies as Ct}from"@Mutate/extensions/policies/attachPolicies";import{getFlightProfile as Ot}from"@Query/event/getFlightProfile";import{getContainedStructures as Ft}from"@Query/drawDefinition/getContainedStructures";import{getMatchUpDependencies as kt}from"@Query/matchUps/getMatchUpDependencies";import{isActiveMatchUp as _t}from"@Query/matchUp/activeMatchUp";import{validMatchUps as xt}from"@Validators/validMatchUp";import{allTournamentMatchUps as Lt}from"@Query/matchUps/getAllTournamentMatchUps";import{mustBeAnArray as Vt}from"@Tools/mustBeAnArray";import{updateAssignmentParticipantResults as Bt}from"@Mutate/drawDefinitions/matchUpGovernor/updateAssignmentParticipantResults";import{getEliminationDrawSize as jt}from"@Query/participants/getEliminationDrawSize";import{getAccessorValue as Gt}from"@Tools/getAccessorValue";import{roundValueRanges as qt}from"@Mutate/drawDefinitions/structureGovernor/structureUtils";import{getStructureRoundProfile as $t}from"@Query/structure/getStructureRoundProfile";import{getSourceStructureIdsAndRelevantLinks as Wt}from"@Query/structure/getSourceStructureIdsAndRelevantLinks";import{getAssignedParticipantIds as Ht}from"@Query/drawDefinition/getAssignedParticipantIds";import{isCompletedStructure as zt}from"@Query/drawDefinition/structureActions";import{isActiveDownstream as Yt}from"@Query/drawDefinition/isActiveDownstream";import{isDirectingMatchUpStatus as Qt,isNonDirectingMatchUpStatus as Kt}from"@Query/matchUp/checkStatusType";import{findDrawMatchUp as Jt}from"@Acquire/findDrawMatchUp";import{hydrateParticipants as Zt}from"@Query/participants/hydrateParticipants";import{getTournamentPublishStatus as Xt}from"@Query/tournaments/getTournamentPublishStatus";import{getEventPublishStatus as er}from"@Query/event/getEventPublishStatus";import{getDrawPublishStatus as tr}from"@Query/event/getDrawPublishStatus";import{getStageDrawPositionsCount as rr}from"@Query/drawDefinition/getStageDrawPositions";import{generateQualifyingLink as nr}from"@Generators/drawDefinitions/links/generateQualifyingLink";import{copyTieFormat as ir}from"@Query/hierarchical/tieFormats/copyTieFormat";import{validateTieFormat as ar}from"@Validators/validateTieFormat";import{generateTieMatchUps as or}from"@Generators/drawDefinitions/tieMatchUps";import{stringSort as sr}from"@Functions/sorters/stringSort";import{addVoluntaryConsolationStructure as cr}from"@Mutate/drawDefinitions/addVoluntaryConsolationStructure";import{validateAndDeriveDrawValues as ur}from"@Generators/drawDefinitions/validateAndDeriveDrawValues";import{getDrawFormat as dr}from"@Generators/drawDefinitions/getDrawFormat";import{setStageQualifiersCount as pr,setStageDrawSize as lr}from"@Mutate/drawDefinitions/entryGovernor/stageEntryCounts";import{generateQualifyingStructures as mr}from"@Generators/drawDefinitions/drawTypes/generateQualifyingStructures";import{addDrawEntry as fr}from"@Mutate/drawDefinitions/entryGovernor/addDrawEntries";import{generateDrawTypeAndModifyDrawDefinition as hr}from"@Generators/drawDefinitions/generateDrawTypeAndModifyDrawDefinition";import{addAdHocMatchUps as gr}from"@Mutate/structures/addAdHocMatchUps";import{participantScaleItem as Ir}from"@Query/participant/participantScaleItem";import{initializeStructureSeedAssignments as Ur}from"@Mutate/drawDefinitions/positionGovernor/initializeSeedAssignments";import{automatedPositioning as yr}from"@Mutate/drawDefinitions/automatedPositioning";import{getScaledEntries as Sr}from"@Query/event/getScaledEntries";import{newDrawDefinition as vr}from"@Generators/drawDefinitions/newDrawDefinition";import{getMatchUp as Tr}from"@Query/matchUps/getMatchUpFromMatchUps";import{checkScoreHasValue as Pr}from"@Query/matchUp/checkScoreHasValue";import{allDrawMatchUps as Dr}from"@Query/matchUps/getAllDrawMatchUps";import{addEventEntries as wr}from"@Mutate/entries/addEventEntries";import{addDrawEntries as br}from"@Mutate/drawDefinitions/addDrawEntries";import{isValidExtension as Rr}from"@Validators/isValidExtension";import{isUngrouped as Nr}from"@Query/entries/isUngrouped";import{getDisabledStatus as Mr}from"@Query/extensions/getDisabledStatus";import{getTournamentInfo as Ar}from"@Query/tournaments/getTournamentInfo";import{getPublishState as Er}from"@Query/publishing/getPublishState";import{getDrawData as Cr}from"@Query/drawDefinition/getDrawData";import{getVenueData as Or}from"@Query/venues/getVenueData";import{findMatchupFormatAverageTimes as Fr,findMatchupFormatRecoveryTimes as kr}from"@Acquire/findMatchUpFormatTimes";import{isValidMatchUpFormat as _r}from"@Validators/isValidMatchUpFormat";import{dateValidation as xr,validTimeString as Lr}from"@Validators/regex";import{extractDate as Vr,isValidDateString as Br,isTimeString as jr,generateDateRange as Gr,timeToDate as qr,tidyTime as $r,extractTime as Wr,addMinutes as Hr,getUTCdateString as zr,timeStringMinutes as Yr,dayMinutesToTimeString as Qr,formatDate as Kr}from"@Tools/dateTime";import{addParticipant as Jr}from"@Mutate/participants/addParticipant";import{generateVirtualCourts as Zr}from"@Mutate/matchUps/schedule/schedulers/utils/generateVirtualCourts";import{calculatePeriodLength as Xr}from"@Mutate/matchUps/schedule/schedulers/utils/calculatePeriodLength";import{courtGenerator as en}from"@Assemblies/generators/scheduling/courtGenerator";import{getTieMatchUpContext as tn}from"@Query/hierarchical/tieFormats/getTieMatchUpContext";import{deleteParticipants as rn}from"@Mutate/participants/deleteParticipants";import{removeCollectionAssignments as nn}from"@Mutate/events/removeCollectionAssignments";import{modifyParticipant as an}from"@Mutate/participants/modifyParticipant";import{getProjectedDualWinningSide as on}from"@Mutate/drawDefinitions/matchUpGovernor/getProjectedDualWinningSide";import{noDownstreamDependencies as sn}from"@Mutate/drawDefinitions/matchUpGovernor/noDownstreamDependencies";import{generateTieMatchUpScore as cn}from"@Assemblies/generators/tieMatchUpScore/generateTieMatchUpScore";import{addMatchUpScheduleItems as un}from"@Mutate/matchUps/schedule/scheduleItems";import{swapWinnerLoser as dn}from"@Mutate/matchUps/drawPositions/swapWinnerLoser";import{updateTieMatchUpScore as pn}from"@Mutate/matchUps/score/tieMatchUpScore";import{modifyMatchUpScore as ln}from"@Mutate/matchUps/score/modifyMatchUpScore";import{ensureSideLineUps as mn}from"@Mutate/matchUps/lineUps/ensureSideLineUps";import{analyzeScore as fn}from"@Query/matchUp/analyzeScore";import{findTournamentId as hn}from"@Acquire/findTournamentId";import{generateCollectionMatchUps as gn}from"@Assemblies/generators/drawDefinitions/tieMatchUps";import{resolveFromParameters as In}from"@Helpers/parameters/resolveFromParameters";import{compareTieFormats as Un}from"@Query/hierarchical/tieFormats/compareTieFormats";import{getRoundLinks as yn,getTargetLink as Sn}from"@Query/drawDefinition/linkGetter";import{getNextRoundMatchUp as vn}from"@Query/matchUps/getNextRoundMatchUp";import{getTargetMatchUp as Tn}from"@Query/matchUps/getTargetMatchUp";import{resetTieFormat as Pn}from"@Mutate/tieFormat/resetTieFormat";import{getGroupValueGroups as Dn}from"@Query/hierarchical/tieFormats/getGroupValueGroups";import{scheduledMatchUpDate as wn}from"@Query/matchUp/scheduledMatchUpDate";import{resolveTournamentRecords as bn}from"@Helpers/parameters/resolveTournamentRecords";import Rn,{courtTemplate as Nn}from"@Assemblies/generators/templates/courtTemplate";import{validDateAvailability as Mn}from"@Validators/validateDateAvailability";import{addDrawDefinitionTimeItem as An}from"@Mutate/drawDefinitions/addDrawDefinitionTimeItem";import{findEvent as En}from"@Acquire/findEvent";import{createSubOrderMap as Cn}from"@Mutate/drawDefinitions/matchUpGovernor/createSubOrderMap";import{tallyParticipantResults as On}from"@Assemblies/governors/queryGovernor";import{getStructureGroups as Fn}from"@Query/structure/getStructureGroups";import{countSets as kn,countGames as _n,countPoints as xn}from"@Query/matchUps/roundRobinTally/scoreCounters";import{findDrawDefinition as Ln}from"@Acquire/findDrawDefinition";import{tallyParticipantResults as Vn}from"@Query/matchUps/roundRobinTally/roundRobinTally";import{validateCollectionValueProfiles as Bn}from"@Validators/validateCollectionValueProfiles";import{calculateWinCriteria as jn}from"@Query/matchUp/calculateWinCriteria";import{getTieFormat as Gn}from"@Query/hierarchical/tieFormats/getTieFormat";import{updateTieFormat as qn}from"@Mutate/tieFormat/updateTieFormat";import{tieFormatTelemetry as $n}from"@Mutate/matchUps/tieFormat/tieFormatTelemetry";import{setMatchUpState as Wn}from"@Mutate/matchUps/matchUpStatus/setMatchUpState";import{allEventMatchUps as Hn}from"@Query/matchUps/getAllEventMatchUps";import{validateCollectionDefinition as zn}from"@Validators/validateCollectionDefinition";import{validUpdate as Yn}from"@Validators/validUpdate";import{modifyCollectionDefinition as Qn}from"@Mutate/matchUps/tieFormat/modifyCollectionDefinition";import{removeCollectionDefinition as Kn}from"@Mutate/tieFormat/removeCollectionDefinition";import{addCollectionDefinition as Jn}from"@Mutate/tieFormat/addCollectionDefinition";import{scheduledSortedMatchUps as Zn}from"@Functions/sorters/scheduledSortedMatchUps";import{getSchedulingProfile as Xn}from"@Mutate/tournaments/schedulingProfile";import{engineLogging as ei}from"@Global/state/engineLogging";function ti(){return"2.0.10"}const ri="appliedPolicies",ni="positionActions",ii="context",ai="delegatedOutcome",oi="disabled",si="disableLinks",ci="disableAutoCalc",ui="drawDeletions",di="entryProfile",pi="flightProfile",li="groupingAttribute",mi="lineUps",fi="linkedTournamentsIds",hi="matchUpHistory",gi="participantRepresentatives",Ii="personRequests",Ui="rankingPoints",yi="roundTarget",Si="scheduleLimits",vi="scheduleTiming",Ti="schedulingProfile",Pi="subOrder",Di="tally",wi="tieFormatModification",bi={ACTIVE_SUSPENSION:"activeSuspension",APPLIED_POLICIES:ri,AUDIT_POSITION_ACTIONS:ni,CONTEXT:ii,DELEGATED_OUTCOME:ai,DISABLED:oi,DISABLE_LINKS:si,DISABLE_AUTO_CALC:ci,DRAW_DELETIONS:ui,DRAW_PROFILE:"drawProfile",ENTRY_PROFILE:di,EVENT_PROFILE:"eventProfile",EVENT_WITHDRAWAL_REQUESTS:"eventWithdrawalRequests",FLIGHT_PROFILE:pi,GROUPING_ATTRIBUTE:li,LINEUPS:mi,LINKED_TOURNAMENTS:fi,MATCHUP_HISTORY:hi,PARTICIPANT_REPRESENTATIVES:gi,PERSON_REQUESTS:Ii,RANKING_POINTS:Ui,ROUND_TARGET:yi,SCHEDULE_LIMITS:Si,SCHEDULE_TIMING:vi,SCHEDULING_PROFILE:Ti,STATUS_DETAIL:"statusDetail",SUB_ORDER:Pi,TALLY:Di,TIE_FORMAT_MODIFICATIONS:wi,FACTORY:"factory"},Ri=[ai,oi,si,pi,mi,hi,gi,Ii,yi,Si,vi,Ti,Pi,Di],Ni={success:!0},Mi={SUCCESS:Ni,ERROR:"error"},Ai={message:"Chronological error; time violation.",code:"ANACHRONISM"},Ei={message:"Cannot remove main structure",code:"ERR_CANNOT_REMOVE_MAIN_STRUCTURE"},Ci={message:"records must be an object with tournamentId keys",code:"ERR_INVALID_TOURNAMENTS"},Oi={message:"Missing tournamentRecords",code:"ERR_MISSING_TOURNAMENTS"},Fi={message:"Missing tournamentRecord",code:"ERR_MISSING_TOURNAMENT"},ki={message:"Invalid tournamentRecord",code:"ERR_INVALID_TOURNAMENT"},_i={message:"Missing tournamentId",code:"ERR_MISSING_TOURNAMENT_ID"},xi={message:"Invalid drawDefinition",code:"ERR_INVALID_DRAWDEF"},Li={message:"Missing drawDefinition",code:"ERR_MISSING_DRAWDEF"},Vi={message:"Existing drawDefinition(s)",code:"ERR_EXISTING_DRAWDEFS"},Bi={message:"drawDefinition not found",code:"ERR_NOT_FOUND_DRAWDEF"},ji={message:"Invalid structure",code:"ERR_INVALID_STRUCTURE"},Gi={message:"Incomplete source structure",code:"ERR_INCOMPLETE_STRUCTURE"},qi={message:"Invalid drawPosition for seedAssignment",code:"ERR_INVALID_SEEDING_POSITION"},$i={message:"drawPosition already assigned",code:"ERR_EXISTING_POSITION_ASSIGNMENT"},Wi={message:"Schedule not cleared",code:"ERR_UNCHANGED_SCHEDULE_NOT_CLEARED"},Hi={message:"drawPosition not cleared",code:"ERR_FAILURE_POSITION_NOT_CLEARED"},zi={message:"Unrecognized drawType",code:"ERR_UNRECOGNIZED_DRAW_TYPE"},Yi={message:"Missing drawPositions",code:"ERR_MISSING_DRAW_POSITIONS"},Qi={message:"drawPosition is active",code:"ERR_ACTIVE_DRAW_POSITION"},Ki={message:"Invlid drawPosition",code:"ERR_INVALID_DRAW_POSITION"},Ji={message:"Missing drawPosition",code:"ERR_MISSING_DRAW_POSITION"},Zi={message:"Invalid drawType",code:"ERR_INVALID_DRAW_TYPE"},Xi={message:"Invalid drawSize",code:"ERR_INVALID_DRAW_SIZE"},ea={message:"Cannot set drawSize to be less than existing entries",code:"ERR_INVALID_DRAW_SIZE_MISMATCH"},ta={message:"Missing drawSize",code:"ERR_MISSING_DRAW_SIZE"},ra={message:"Missing drawId",code:"ERR_MISSING_DRAW_ID"},na={message:"drawId exists",code:"ERR_EXISTING_DRAW_ID"},ia={message:"participantId cannot be assigned to multiple seedNumbers",code:"INVALID_PARTICIPANT_SEEDING"},aa={message:"Missing seedCountThresholds",code:"ERR_MISSING_SEED_COUNT_THRESHOLD"},oa={message:"Invalid action",code:"ERR_INVALID_ACTION"},sa={message:"Invalid assignment",code:"ERR_INVALID_ASSIGNMENT"},ca={message:"Missing seedAssignments",code:"ERR_MISSING_SEED_ASSIGNMENTS"},ua={message:"Invalid seedPosition",code:"ERR_INVALID_SEED_POSITION"},da={message:"Missing targetLink",code:"ERR_MISSING_LINK_TARGET"},pa={message:"Existing round",code:"ERR_EXISTING_ROUND"},la={message:"Missing structureId",code:"ERR_MISSING_STRUCTURE_ID"},ma={message:"structure not found",code:"ERR_NOT_FOUND_STRUCTURE"},fa={message:"Missing structures",code:"ERR_MISSING_STRUCTURES"},ha={message:"Missing structure",code:"ERR_MISSING_STRUCTURE"},ga={message:"drawDefinition contains unlinked structures",code:"ERR_MISSING_STRUCTURE_LINKS"},Ia={message:"Invalid eventType",code:"ERR_INVALID_EVENT_TYPE"},Ua={message:"Missing event / eventId",code:"ERR_MISSING_EVENT_ID"},ya={message:"Event not found",code:"ERR_NOT_FOUND_EVENT"},Sa={message:"Event exists",code:"ERR_EXISTING_EVENT"},va={message:"Missing entries",code:"ERR_MISSING_ENTRIES"},Ta={message:"Invalid entries",code:"ERR_INVALID_ENTRIES"},Pa={message:"Missing assignments",code:"ERR_MISSING_ASSIGNMENTS"},Da={message:"Missing stage",code:"ERR_MISSING_STAGE"},wa={message:"Invalid stage",code:"ERR_INVALID_STAGE"},ba={message:"stageSequence limit",code:"ERR_LIMIT_STAGE_SEQUENCE"},Ra={message:"Missing positionAssignments",code:"ERR_MISSING_POSITION_ASSIGNMENTS"},Na={message:"Unrecognized matchUpFormat",code:"ERR_UNRECOGNIZED_MATCHUP_FORMAT"},Ma={message:"Incompatible matchUpStatus",code:"ERR_INCOMPATIBLE_MATCHUP_STATUS"},Aa={message:"Invalid matchUpStatus",code:"ERR_INVALID_MATCHUP_STATUS"},Ea={message:"Invalid tieFormat",code:"ERR_INVALID_TIE_FORMAT"},Ca={message:"Invalid matchUpFormat",code:"ERR_INVALID_MATCHUP_FORMAT"},Oa={message:"Missing matchUpFormat",code:"ERR_MISSING_MATCHUP_FORMAT"},Fa={message:"Missing collectionDefinition",code:"ERR_MISSING_COLLECTION_DEFINITION"},ka={message:"Missing tieFormat",code:"ERR_MISSING_TIE_FORMAT"},_a={message:"Missing matchUpId",code:"ERR_MISSING_MATCHUP_ID"},xa={message:"Missing matchUpIds",code:"ERR_MISSING_MATCHUP_IDS"},La={message:"matchUp not found",code:"ERR_NOT_FOUND_MATCHUP"},Va={message:"Missing matchUps",code:"ERR_MISSING_MATCHUPS"},Ba={message:"Missing matchUp",code:"ERR_MISSING_MATCHUP"},ja={message:"Invalid matchUp",code:"ERR_INVALID_MATCHUP"},Ga={message:"Missing policyType",code:"ERR_MISSING_POLICY_TYPE"},qa={message:"Missing policyDefinitions",code:"ERR_MISSING_POLICY_DEFINITIONS"},$a={message:"Missing avoidance policy",code:"ERR_MISSING_POLICY_AVOIDANCE"},Wa={message:"Missing policy attributes",code:"ERR_MISSING_POLICY_ATTRIBUTES"},Ha={message:"Invalid policyDefinitions",code:"ERR_INVALID_POLICY_DEFINITIONS"},za={message:"existing policyType",code:"ERR_EXISTING_POLICY_TYPE"},Ya={message:"Policy not found",code:"ERR_NOT_FOUND_POLICY"},Qa={message:"Invalid sideNumber",code:"ERR_INVALID_SIDE_NUMBER"},Ka={message:"Missing setObject",code:"ERR_MISSING_SET_ATTRIBUTE"},Ja={message:"Missing courtId",code:"ERR_MISSING_COURT_ID"},Za={message:"Missing value",code:"ERR_MISSING_VALUE"},Xa={message:"Missing date",code:"ERR_MISSING_DATE"},eo={message:"No valid dates",code:"ERR_NO_VALID_DATES"},to={message:"Invalid bookings",code:"ERR_INVALID_BOOKINGS"},ro={message:"Invalid dateAvailability",code:"ERR_INVALID_DATE_AVAILABILITY"},no={message:"Missing dateAvailability",code:"ERR_MISSING_DATE_AVAILABILITY"},io={message:"Invalid Date",code:"ERR_INVALID_DATE"},ao={message:"Invalid time",code:"ERR_INVALID_TIME"},oo={message:"Invalid tournament dates",code:"ERR_INVALID_DATES_TOURNAMENT"},so={message:"Invalid game scores",code:"ERR_INVALID_SCORES_GAME"},co={message:"Invalid score",code:"ERR_INVALID_SCORE"},uo={message:"Invalid winningSide",code:"ERR_INVALID_WINNING_SIDE"},po={message:"No participants generated",code:"ERR_NO_PARTICIPANTS_GENERATED"},lo={message:"Cannot modify tieFormat",code:"ERR_UNCHANGED_CANNOT_MODIFY_TIEFORMAT"},mo={message:"Cannot modify participantType",code:"ERR_UNCHANGED_CANNOT_MODIFY_PARTICIPANT_TYPE"},fo={message:"Cannot remove participants",code:"ERR_UNCHANGED_CANNOT_REMOVE_PARTICIPANTS"},ho={message:"Cannot change winningSide",code:"ERR_UNCHANGED_CANNOT_CHANGE_WINNING_SIDE"},go={message:"Invalid participant",code:"ERR_INVALID_PARTICIPANT"},Io={message:"Invalid participantId",code:"ERR_INVALID_PARTICIPANT_ID"},Uo={message:"Invalid participantIds",code:"ERR_INVALID_PARTICIPANT_IDS"},yo={message:"Invalid participantRole",code:"ERR_INVALID_PARTICIPANT_ROLE"},So={message:"Invalid participantType",code:"ERR_INVALID_PARTICIPANT_TYPE"},vo={message:"Missing participantRole",code:"ERR_MISSING_PARTICIPANT_ROLE"},To={message:"Missing participant",code:"ERR_MISSING_PARTICIPANT"},Po={message:"Missing participants",code:"ERR_MISSING_PARTICIPANTS"},Do={message:"Missing participantId",code:"ERR_MISSING_PARTICIPANT_ID"},wo={message:"Participant Not Found",code:"ERR_NOT_FOUND_PARTICIPANT"},bo={message:"participantId exists",code:"ERR_EXISTING_PARTICIPANT_ID"},Ro={message:"No participant removed",code:"ERR_UNCHANGED_NO_PARTICIPANT_REMOVED"},No={message:"Missing participantIds",code:"ERR_MISSING_PARTICIPANT_IDS"},Mo={message:"Missing participantsCount",code:"ERR_MISSING_PARTICIPANT_COUNT"},Ao={message:"Participant not checked in",code:"ERR_UNCHANGED_PARTICIPANT_NOT_CHECKED_IN"},Eo={message:"Missing person details",code:"ERR_MISSING_PERSON_DETAILS"},Co={message:"Existing participant drawPosition assignment",code:"ERR_EXISTING_PARTICIPANT_DRAW_POSITION_ASSIGNMENT"},Oo={message:"Existing participant",code:"ERR_EXISTING_PARTICIPANT"},Fo={message:"participantsCount exceeds drawSize",code:"ERR_INVALID_PARTICIPANT_COUNT"},ko={message:"Invalid entry status",code:"ERR_INVALID_ENTRY_STATUS"},_o={message:"Participant Entry Not Found",code:"ERR_NOT_FOUND_PARTICIPANT_ENTRY"},xo={message:"Participant not entered in stage",code:"ERR_UNCHANGED_PARTICIPANT_NOT_ENTERED"},Lo={message:"Participant not found in stageSequence",code:"ERR_NOT_FOUND_PARTICIPANT_IN_STAGE"},Vo={message:"entryStatus not allowed in stage",code:"ERR_INVALID_ENTRY_STATUS_IN_STAGE"},Bo={message:"entryStatus not allowed for event",code:"ERR_INVALID_ENTRY_STATUS_IN_EVENT"},jo={message:"No stage space available for entryStatus",code:"ERR_UNCHANGED_NO_AVAILABLE_STAGE_SPACE"},Go={message:"Insufficient drawPositions to accommodate entries",code:"ERR_INSUFFICIENT_DRAW_POSITIONS"},qo={message:"Missing penaltyType",code:"ERR_MISSING_PENALTY_TYPE"},$o={message:"Missing penaltyId",code:"ERR_MISSING_PENALTY_ID"},Wo={message:"Penalty not found",code:"ERR_NOT_FOUND_PENALTY"},Ho={message:"Missing courtsCount/courtNames",code:"ERR_MISSING_COURTS_INFO"},zo={message:"Court not found",code:"ERR_NOT_FOUND_COURT"},Yo={message:"Court exists",code:"ERR_EXISTING_COURT"},Qo={message:"Venue exists",code:"ERR_EXISTING_VENUE"},Ko={message:"Venue not found",code:"ERR_NOT_FOUND_VENUE"},Jo={message:"Missing venueId",code:"ERR_MISSING_VENUE_ID"},Zo={message:"Invalid endTime",code:"ERR_INVALID_END_TIME"},Xo={message:"Existing endTime",code:"ERR_EXISTING_END_TIME"},es={message:"Invalid stopTime",code:"ERR_INVALID_STOP_TIME"},ts={message:"Invalid startTime",code:"ERR_INVALID_START_TIME"},rs={message:"Invalid resumeTime",code:"ERR_INVALID_RESUME_TIME"},ns={message:"Invalid timeItem",code:"ERR_INVALID_TIME_ITEMS"},is={message:"Missing async state provider",code:"ERR_MISSING_ASYNC_STATE_PROVIDER"},as={message:"Missing timeItem",code:"ERR_MISSING_TIME_ITEM"},os={message:"Missing timeItems",code:"ERR_MISSING_TIME_ITEMS"},ss={message:"Missing context",code:"ERR_MISSING_CONTEXT"},cs={message:"Missing schedule",code:"ERR_MISSING_SCHEDULE"},us={message:"Invalid scaleItem",code:"ERR_INVALID_SCALE_ITEM"},ds={message:"Modifications failed",code:"ERR_FAILURE_MODIFICATIONS"},ps={message:"No modifications applied",code:"ERR_UNCHANGED_NO_MODIFICATIONS_APPLIED"},ls={message:"Unable to assign court",code:"ERR_UNCHANGED_COURT_NOT_ASSIGNED"},ms={message:"No Candidates",code:"ERR_UNCHANGED_NO_CANDIDATES"},fs={message:"Invalid configuration",code:"ERR_INVALID_CONFIG"},hs={message:"Invalid collectionDefinition",code:"ERR_INVALID_COLLECTION_DEFINITION"},gs={message:"Invalid object",code:"ERR_INVALID_OBJECT"},Is={message:"Invalid gender",code:"ERR_INVALID_GENDER"},Us={message:"Invalid category",code:"ERR_INVALID_CATEGORY"},ys={message:"Invalid values",code:"ERR_INVALID_VALUES"},Ss={message:"Duplicate value",code:"ERR_DUPLICATE_VALUE"},vs={message:"Team not found",code:"ERR_NOT_FOUND_TEAM"},Ts={message:"No valid actions",code:"ERR_NO_VALID_ACTIONS"},Ps={message:"No valid attributes",code:"ERR_NO_VALID_ATTRIBUTES"},Ds={message:"Value unchanged",code:"ABORT_UNCHANGED"},ws={message:"Not found",code:"ERR_NOT_FOUND"},bs={message:"Not implemented",code:"ERR_NOT_IMPLEMENTED"},Rs={message:"Existing flight",code:"ERR_EXISTING_FLIGHT"},Ns={message:"Existing flight profile",code:"ERR_EXISTING_FLIGHT_PROFILE"},Ms={message:"Existing outcome",code:"ERR_EXISTING_OUTCOME"},As={message:"Existing matchUpId",code:"ERR_EXISTING_MATCHUP_ID"},Es={message:"Existing stage",code:"ERR_EXISTING_STAGE"},Cs={message:"Existing structure",code:"ERR_EXISTING_STRUCTURE"},Os={message:"Method not found",code:"ERR_NOT_FOUND_METHOD"},Fs={message:"Scheduled matchUps",code:"ERR_SCHEDULED_MATCHUPS"},ks={message:"Scores present",code:"ERR_SCORES_PRESENT"},_s={ANACHRONISM:Ai,CANNOT_CHANGE_WINNING_SIDE:ho,CANNOT_MODIFY_TIEFORMAT:lo,CANNOT_MODIFY_PARTICIPANT_TYPE:mo,CANNOT_REMOVE_MAIN_STRUCTURE:Ei,CANNOT_REMOVE_PARTICIPANTS:fo,COURT_EXISTS:Yo,COURT_NOT_FOUND:zo,DRAW_DEFINITION_NOT_FOUND:Bi,DRAW_ID_EXISTS:na,DRAW_POSITION_ACTIVE:Qi,DRAW_POSITION_ASSIGNED:$i,DRAW_POSITION_NOT_CLEARED:Hi,DRAW_POSITION_NOT_FOUND:{message:"drawPosition not found",code:"ERR_NOT_FOUND_DRAW_POSITION"},DRAW_SIZE_MISMATCH:ea,DUPLICATE_VALUE:Ss,ENTRY_STATUS_NOT_ALLOWED_FOR_EVENT:Bo,ENTRY_STATUS_NOT_ALLOWED_IN_STAGE:Vo,EVENT_EXISTS:Sa,EVENT_NOT_FOUND:ya,EXISTING_DRAW_DEFINITIONS:Vi,EXISTING_END_TIME:Xo,EXISTING_FLIGHT:Rs,EXISTING_MATCHUP_ID:As,EXISTING_OUTCOME:Ms,EXISTING_PARTICIPANT_DRAW_POSITION_ASSIGNMENT:Co,EXISTING_PARTICIPANT:Oo,EXISTING_POLICY_TYPE:za,EXISTING_PROFILE:Ns,EXISTING_ROUND:pa,EXISTING_STAGE:Es,EXISTING_STRUCTURE:Cs,INCOMPATIBLE_MATCHUP_STATUS:Ma,INCOMPLETE_SOURCE_STRUCTURE:Gi,INSUFFICIENT_DRAW_POSITIONS:Go,INVALID_ACTION:oa,INVALID_ASSIGNMENT:sa,INVALID_BOOKINGS:to,INVALID_CATEGORY:Us,INVALID_COLLECTION_DEFINITION:hs,INVALID_CONFIGURATION:fs,INVALID_DATE_AVAILABILITY:ro,INVALID_DATE:io,INVALID_DRAW_DEFINITION:xi,INVALID_DRAW_POSITION_FOR_SEEDING:qi,INVALID_DRAW_POSITION:Ki,INVALID_DRAW_SIZE:Xi,INVALID_END_TIME:Zo,INVALID_ENTRIES:Ta,INVALID_EVENT_TYPE:Ia,INVALID_GAME_SCORES:so,INVALID_GENDER:Is,INVALID_MATCHUP_FORMAT:Ca,INVALID_MATCHUP_STATUS:Aa,INVALID_MATCHUP_STATUS_BYE:{message:"Cannot Assign BYE status if no assignment: { bye: true }",code:"ERR_UNCHANGED_CANNOT_ASSIGN_BYE"},INVALID_MATCHUP:ja,INVALID_OBJECT:gs,INVALID_PARTICIPANT_ID:Io,INVALID_PARTICIPANT_IDS:Uo,INVALID_PARTICIPANT_ROLE:yo,INVALID_PARTICIPANT_SEEDING:ia,INVALID_PARTICIPANT_TYPE:So,INVALID_PARTICIPANT:go,INVALID_POLICY_DEFINITION:Ha,INVALID_RECORDS:Ci,INVALID_SCALE_ITEM:us,INVALID_SEED_NUMBER:{message:"Invalid seedNumber",code:"ERR_INVALID_SEED_NUMBER"},INVALID_SEED_POSITION:ua,INVALID_SET_NUMBER:{message:"Invalid setNumber",code:"ERR_INVALID_SET_NUMBER"},INVALID_SIDE_NUMBER:Qa,INVALID_SCORE:co,INVALID_STAGE:wa,INVALID_START_TIME:ts,INVALID_STRUCTURE:ji,INVALID_STOP_TIME:es,INVALID_TIE_FORMAT:Ea,INVALID_TIME:ao,INVALID_TIME_ITEM:ns,INVALID_TOURNAMENT_DATES:oo,INVALID_TOURNAMENT_RECORD:ki,INVALID_VALUES:ys,INVALID_WINNING_SIDE:uo,MATCHUP_NOT_FOUND:La,METHOD_NOT_FOUND:Os,MISSING_ASSIGNMENTS:Pa,MISSING_ASYNC_STATE_PROVIDER:is,MISSING_AVOIDANCE_POLICY:$a,MISSING_COLLECTION_DEFINITION:Fa,MISSING_COURT_ID:Ja,MISSING_COURTS_INFO:Ho,MISSING_DATE_AVAILABILITY:no,MISSING_DATE:Xa,MISSING_DRAW_DEFINITION:Li,MISSING_DRAW_ID:ra,MISSING_DRAW_POSITION:Ji,MISSING_DRAW_POSITIONS:Yi,MISSING_DRAW_SIZE:ta,MISSING_ENTRIES:va,MISSING_EVENT:Ua,MISSING_MATCHUP_FORMAT:Oa,MISSING_MATCHUP_ID:_a,MISSING_MATCHUP_IDS:xa,MISSING_MATCHUP:Ba,MISSING_MATCHUPS:Va,MISSING_PARTICIPANT_COUNT:Mo,MISSING_PARTICIPANT_ID:Do,MISSING_PARTICIPANT_IDS:No,MISSING_PARTICIPANT_ROLE:vo,MISSING_PARTICIPANT:To,MISSING_PARTICIPANTS:Po,MISSING_PENALTY_ID:$o,MISSING_PENALTY_TYPE:qo,MISSING_PERSON_DETAILS:Eo,MISSING_POLICY_ATTRIBUTES:Wa,MISSING_POLICY_DEFINITION:qa,MISSING_POLICY_TYPE:Ga,MISSING_POSITION_ASSIGNMENTS:Ra,MISSING_ROUND_NUMBER:{message:"Missing roundNumber",code:"ERR_MISSING_ROUND_NUMBER"},MISSING_SCHEDULE:cs,MISSING_SCORING_POLICY:{message:"Missing scoring policy / matchUpFormats",code:"ERR_MISSING_POLICY_SCORING_MATCHUP_FORMATS"},MISSING_SEED_ASSIGNMENTS:ca,MISSING_SEEDCOUNT_THRESHOLDS:aa,MISSING_SEEDING_POLICY:{message:"Missing seeding policy",code:"ERR_MISSING_POLICY_SEEDING"},MISSING_SET_NUMBER:{message:"Missing setNumber",code:"ERR_MISSING_SET_NUMBER"},MISSING_SET_OBJECT:Ka,MISSING_SIDE_NUMBER:{message:"Missing sideNumber",code:"ERR_MISSING_SIDE_NUMBER"},MISSING_STAGE:Da,MISSING_STRUCTURE_ID:la,MISSING_STRUCTURE:ha,MISSING_STRUCTURES:fa,MISSING_TARGET_LINK:da,MISSING_TIE_FORMAT:ka,MISSING_TIME_ITEM:as,MISSING_TIME_ITEMS:os,MISSING_TOURNAMENT_ID:_i,MISSING_TOURNAMENT_RECORD:Fi,MISSING_TOURNAMENT_RECORDS:Oi,MISSING_VALUE:Za,MISSING_VENUE_ID:Jo,MODIFICATIONS_FAILED:ds,NO_CANDIDATES:ms,NO_DRAW_POSITIONS_AVAILABLE_FOR_QUALIFIERS:{message:"Insufficient drawPositions to accommodate qualifiers",code:"ERR_UNCHANGED_NO_DRAW_POSITIONS_FOR_QUALIFIERS"},NO_MODIFICATIONS_APPLIED:ps,NO_STAGE_SPACE_AVAILABLE_FOR_ENTRY_STATUS:jo,NO_PARTICIPANT_REMOVED:Ro,NO_VALID_ACTIONS:Ts,NO_VALID_ATTRIBUTES:Ps,NO_VALID_DATES:eo,NOT_FOUND:ws,NOT_IMPLEMENTED:bs,PARTICIPANT_COUNT_EXCEEDS_DRAW_SIZE:Fo,PARTICIPANT_ID_EXISTS:bo,PARTICIPANT_NOT_CHECKED_IN:Ao,PARTICIPANT_NOT_FOUND:wo,PARTICIPANT_PAIR_EXISTS:{message:"participant pair exists",code:"ERR_EXISTING_PARTICIPANT_PAIR"},PENALTY_NOT_FOUND:Wo,POLICY_NOT_ATTACHED:{message:"Policy not attached",code:"ERR_FAILURE_POLICY_NOT_ATTACHED"},POLICY_NOT_FOUND:Ya,SCHEDULE_NOT_CLEARED:Wi,SCHEDULED_MATCHUPS:Fs,SCORES_PRESENT:ks,SEEDSCOUNT_GREATER_THAN_DRAW_SIZE:{message:"seedsCount greater than drawSize",code:"ERR_INVALID_SEED_COUNT"},STAGE_SEQUENCE_LIMIT:ba,STRUCTURE_NOT_FOUND:ma,TEAM_NOT_FOUND:vs,UNABLE_TO_ASSIGN_COURT:ls,UNLINKED_STRUCTURES:ga,UNRECOGNIZED_DRAW_TYPE:zi,UNRECOGNIZED_MATCHUP_FORMAT:Na,UNRECOGNIZED_MATCHUP_STATUS:{message:"Unrecognized matchUpStatus",code:"ERR_UNRECOGNIZED_MATCHUP_STATUS"},VALUE_UNCHANGED:Ds,VENUE_EXISTS:Qo};function xs({tournamentRecords:e}){if("object"!=typeof e||!Object.keys(e).length)return{error:Oi};const t=n({tournamentRecords:e}),{tournamentIds:r}=t;if(r?.length>1){return o({tournamentRecords:e,discover:!0,extension:{name:fi,value:{tournamentIds:r}}})}return{...Ni}}function Ls({tournamentRecords:e}){if("object"!=typeof e||!Object.keys(e).length)return{error:Oi};const t=i({name:fi,tournamentRecords:e,discover:!0});return a({result:t,stack:"unlinkTournaments"})}function Vs({tournamentRecords:r,tournamentId:i}){if("object"!=typeof r)return{error:ys};if(!i)return{error:_i};const a=n({tournamentRecords:r}),{tournamentIds:o}=a;if(!o.includes(i))return{error:_i};let c;return o.every((n=>{const a=r[n],{extension:o}=s({element:a,name:fi});if(!o)return!0;const u=o?.value?.tournamentIds||[];if(!u?.length||1===u.length&&u.includes(i)||n===i){const t=e({name:fi,tournamentRecord:a});return t.error&&(c=t.error),t.success}const d=u.filter((e=>e!==i));o.value={tournamentIds:d};const p=t({tournamentRecord:a,extension:o});return p.error&&(c=p.error),p.success})),c?{error:c}:{...Ni}}var Bs=Object.freeze({__proto__:null,linkTournaments:xs,unlinkTournament:Vs,unlinkTournaments:Ls});function js({tournamentRecords:e}){if("object"!=typeof e||!Object.keys(e).length)return{error:Oi};return{linkedTournamentIds:Object.assign({},...Object.keys(e).map((t=>{const r=e[t],n=r?.tournamentId,{extension:i}=s({element:r,name:fi});return{[t]:(i?.value?.tournamentIds||[]).filter((e=>e!==n))}})))}}const Gs={disableNotifications:!1,tournamentId:void 0,tournamentRecords:{},subscriptions:{},modified:!1,methods:{},notices:[]};var qs={addNotice:function({topic:e,payload:t,key:r}){if("string"!=typeof e||"object"!=typeof t)return;Gs.disableNotifications||(Gs.modified=!0);if(Gs.disableNotifications||!Gs.subscriptions[e])return;r&&(Gs.notices=Gs.notices.filter((t=>!(t.topic===e&&t.key===r))));return Gs.notices.push({topic:e,payload:t,key:r}),{...Ni}},callListener:function({topic:e,notices:t}){const r=Gs.subscriptions[e];r&&"function"==typeof r&&r(t)},cycleMutationStatus:function(){const e=Gs.modified;return Gs.modified=!1,e},deleteNotice:function({topic:e,key:t}){Gs.notices=Gs.notices.filter((r=>(!e||r.topic===e)&&r.key!==t))},deleteNotices:function(){Gs.notices=[]},disableNotifications:function(){Gs.disableNotifications=!0},enableNotifications:function(){Gs.disableNotifications=!1},getMethods:Ws,getNotices:function({topic:e}){const t=Gs.notices.filter((t=>t.topic===e)).map((e=>e.payload));return t.length&&t},getTopics:function(){return{topics:Object.keys(Gs.subscriptions)}},getTournamentId:$s,getTournamentRecord:function(e){return Gs.tournamentRecords[e]},getTournamentRecords:function(){return Gs.tournamentRecords},removeTournamentRecord:function(e){if("string"!=typeof e)return{error:ys};if(!Gs.tournamentRecords[e])return{error:ws};delete Gs.tournamentRecords[e];const t=Object.keys(Gs.tournamentRecords);1===t.length?Gs.tournamentId=t[0]:t.length||(Gs.tournamentId=void 0);return{success:!0}},setMethods:function(e){return Object.keys(e).forEach((t=>{"function"==typeof e[t]&&(Gs.methods[t]=e[t])})),{...Ni}},setSubscriptions:function(e){return"object"!=typeof e.subscriptions?{error:ys}:(Object.keys(e.subscriptions).forEach((t=>{Gs.subscriptions[t]=e.subscriptions[t]})),{...Ni})},setTournamentId:function(e){if(!e)return Gs.tournamentId=void 0,{success:!0};return Gs.tournamentRecords[e]?(Gs.tournamentId=e,{success:!0}):{error:Fi}},setTournamentRecord:function(e){const t=e?.tournamentId;return t?(Gs.tournamentRecords[t]=e,{success:!0}):{error:ki}},setTournamentRecords:function(e){Gs.tournamentRecords=e;const t=Object.keys(e);1===t.length?Gs.tournamentId=t[0]:t.length||(Gs.tournamentId=void 0)},handleCaughtError:function({engineName:e,methodName:t,params:r,err:n}){let i;"string"==typeof n?i=n.toUpperCase():n instanceof Error&&(i=n.message);return console.log("ERROR",{tournamentId:$s(),params:JSON.stringify(r),engine:e,methodName:t,error:i}),{error:i}}};function $s(){return Gs.tournamentId}function Ws(){return Gs.methods??{}}const Hs={tournamentFactoryVersion:"0.0.0",timers:{default:{elapsedTime:0}},deepCopyAttributes:{stringify:[],ignore:[],toJSON:[]},deepCopy:!0};let zs=qs;const Ys=["addNotice","callListener","cycleMutationStatus","deleteNotice","deleteNotices","disableNotifications","enableNotifications","getMethods","getNotices","getTopics","getTournamentId","getTournamentRecord","getTournamentRecords","removeTournamentRecord","setSubscriptions","setTournamentId","setTournamentRecord","setTournamentRecords"];function Qs(){if(zs.createInstanceState){try{zs.createInstanceState()}catch(e){return{error:e}}return{success:!0}}return{error:is}}function Ks(e){return e&&"object"==typeof e?"object"==typeof Hs.devContext&&(Object.keys(e).every((t=>Hs.devContext?.[t]===e[t]))&&Hs.devContext):Hs.devContext??!1}function Js(e){"function"==typeof e?Hs.globalLog=e:delete Hs.globalLog}function Zs(e){Hs.devContext=e}function Xs(e,t){"boolean"==typeof e&&(Hs.deepCopy=e),"object"==typeof t&&(Array.isArray(t.ignore)&&(Hs.deepCopyAttributes.ignore=t.ignore),Array.isArray(t.toJSON)&&(Hs.deepCopyAttributes.toJSON=t.toJSON),Array.isArray(t.stringify)&&(Hs.deepCopyAttributes.stringify=t.stringify),t.threshold&&(Hs.deepCopyAttributes.threshold=t.threshold))}function ec(){return{enabled:Hs.deepCopy,...Hs.deepCopyAttributes}}function tc(){return zs.cycleMutationStatus()}function rc(e){return zs.addNotice(e)}function nc(){return zs.getMethods()}function ic(e){return zs.getNotices(e)}function ac({key:e,topic:t}){return zs.deleteNotice({key:e,topic:t})}function oc(){return zs.deleteNotices()}function sc(){return zs.getTopics()}async function cc(e){return zs.callListener(e)}function uc(){return zs.getTournamentId()}function dc(e){return zs.getTournamentRecord(e)}function pc(){return zs.getTournamentRecords()}function lc(e){return zs.setTournamentRecords(e)}function mc(e){return zs.setTournamentId(e)}function fc(e){return zs.removeTournamentRecord(e)}function hc(){return zs}function gc({engineName:e,methodName:t,params:r,err:n}){return("function"==typeof zs.handleCaughtError&&zs.handleCaughtError||qs.handleCaughtError)({engineName:e,methodName:t,params:r,err:n})}function Ic(e,t){if(Hs.globalLog)try{Hs.globalLog({log:e,engine:t})}catch(r){console.log("globalLog error",r),console.log(t,e),Js()}else console.log(t,e)}var Uc=Object.freeze({__proto__:null,addNotice:rc,callListener:cc,createInstanceState:Qs,cycleMutationStatus:tc,deepCopyEnabled:ec,deleteNotice:ac,deleteNotices:oc,disableNotifications:function(){zs.disableNotifications()},enableNotifications:function(){zs.enableNotifications()},getDevContext:Ks,getMethods:nc,getNotices:ic,getProvider:hc,getTopics:sc,getTournamentId:uc,getTournamentRecord:dc,getTournamentRecords:pc,globalLog:Ic,handleCaughtError:gc,removeTournamentRecord:fc,setDeepCopy:Xs,setDevContext:Zs,setGlobalLog:Js,setMethods:function(e){return e?"object"!=typeof e?{error:ys}:zs.setMethods(e):{error:Za,info:"missing method declarations"}},setStateProvider:function(e){if("object"!=typeof e)throw new Error("Global state provider can not be undefined or null");if(c(Object.keys(e),Ys).length!==Ys.length)throw new Error("Global state provider is missing required methods");return zs=e,{success:!0}},setSubscriptions:function(e){return e?.subscriptions?zs.setSubscriptions({subscriptions:e.subscriptions}):{error:Za,info:"missing subscriptions"}},setTournamentId:mc,setTournamentRecord:function(e){return zs.setTournamentRecord(e)},setTournamentRecords:lc,timeKeeper:function(e="reset",t="default"){const r=Date.now();if("report"===e){if("allTimers"===t){return Object.keys(Hs.timers).filter((e=>"default"!==e||Hs.timers[e].startTime)).map((e=>{const t=Hs.timers[e],n="stopped"===t.state?0:(r-(t?.startTime??0))/1e3,i=t.elapsedTime+n;return{state:Hs.timers[e].state,elapsedTime:i.toFixed(2),timer:e}}))}{const e="stopped"===Hs.timers[t].state?0:(r-(Hs.timers[t]?.startTime??0))/1e3,n=Hs.timers[t].elapsedTime+e;return{state:Hs.timers[t].state,elapsedTime:n.toFixed(2),timer:t}}}if(!Hs.timers[t]||"reset"===e){if("allTimers"===t)return Hs.timers={default:{elapsedTime:0}},!0;Hs.timers[t]={startTime:r,state:"active",elapsedTime:0}}return Hs.timers[t].elapsedTime||(Hs.timers[t].elapsedTime=0),"stop"===e&&"stopped"!==Hs.timers[t].state&&(Hs.timers[t].state="stopped")&&(Hs.timers[t].elapsedTime+=(r-(Hs.timers[t]?.startTime??0))/1e3),"start"===e&&(Hs.timers[t].startTime=r)&&(Hs.timers[t].state="active"),Hs.timers[t]}});const yc=/^[\d]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][\d]|3[0-1])$/,Sc=/^((0[\d]|1[\d]|2[0-3]):[0-5][\d](:[0-5][\d])?)([.,][0-9]{3})?$/,vc=/^([\d]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][\d]|3[0-1]))([ T](0[\d]|1[\d]|2[0-3]):[0-5][\d](:[0-5][\d])?)?([.,][\d]{3})?Z?$/,Tc=/^([\d]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][\d]|3[0-1]))?([ T]?(0[\d]|1[\d]|2[0-3]):[0-5][\d](:[0-5][\d])?)?([.,][\d]{3})?Z?$/;function Pc(e){let{scheduledDate:t}=e;if(!t&&e.scheduledTime&&(t=Lc(e.scheduledTime)),!t)return;const r=xc(e.scheduledTime);let n=Lc(t);return n&&r&&(n+=`T${r}`),n}function Dc(e){if("object"!=typeof e||Array.isArray(e))return!1;return"[object Date]"===Object.prototype.toString.call(e)}function wc(e){const t="string"==typeof e?e?.split(" "):[];return!(e&&t?.length>1&&!["AM","PM"].includes(t[1].toUpperCase()))&&!(e&&!Tc.test(jc(e,!0,!0)))}function bc(e){return Oc(e)||yc.test(e)}const Rc=e=>{const t=Ac(e)||Oc(e)?new Date(e):new Date,r=t.getUTCMonth()+1,n=r<10?`0${r}`:`${r}`;return`${t.getUTCFullYear()}-${Yc(n)}-${Yc(t.getUTCDate())}`};function Nc(e,t="-",r="YMD"){if(!e)return"";"string"==typeof e&&e.indexOf("T")<0&&(e+="T00:00");const n=new Date(e);let i=""+(n.getMonth()+1),a=""+n.getDate();const o=n.getFullYear();return i.length<2&&(i="0"+i),a.length<2&&(a="0"+a),"DMY"===r?[a,i,o].join(t):"MDY"===r?[i,a,o].join(t):"YDM"===r?[o,a,i].join(t):"DYM"===r?[a,o,i].join(t):"MYD"===r?[i,o,a].join(t):[o,i,a].join(t)}function Mc(e){const t=e?new Date(e):new Date,r=t.getTimezoneOffset();return new Date(t.getTime()-60*r*1e3)}function Ac(e){if("boolean"==typeof e)return!1;const t=e instanceof Date&&e||!isNaN(e)&&new Date(e)||!1;return t&&!isNaN(t.valueOf())}function Ec(e,t){if(!bc(e)||!bc(t))return[];const r=Lc(e)+"T00:00",n=Lc(t)+"T00:00",i=new Date(r),a=new Date(n);const o=[];let s=0;if(Ac(a)&&Ac(i)&&i<=a){const e=i;let t=e.getTime();for(;t<=a.getTime()&&s<300;)s+=1,o.push(new Date(e)),t=e.setDate(e.getDate()+1)}return o.map((e=>Nc(e)))}const Cc=/^([+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-2])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([.,]\d+(?!:))?)?(\17[0-5]\d([.,]\d+)?)?([zZ]|([+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/;function Oc(e){return"string"==typeof e&&Cc.test(e)}function Fc(e){if("string"!=typeof e)return!1;const t=e.split("Z")[0].split(":"),r=t.every((e=>!isNaN(parseInt(e))));return!(t.length<2||!r||parseInt(t[0])>23||parseInt(t[1])>60)}function kc(e){const t=xc(e);if(!t)return 0;const[r,n]=t.split(":").map((e=>parseInt(e)));return 60*r+n}function _c(e){return Fc(e)?e.split(":").slice(0,2).map(Yc).join(":"):void 0}function xc(e){return Oc(e)&&e.indexOf("T")>0?_c(e.split("T").reverse()[0]):_c(e)}function Lc(e){return Oc(e)||vc.test(e)?e.split("T")[0]:void 0}function Vc(e,t){const r=new Date(e);return r.setDate(r.getDate()+t),Lc(r.toISOString())}function Bc(e){e="string"!=typeof e?"00:00":e;const t={},r={};return({0:t.time,1:t.ampm}=e.split(" ")||[]),({0:r.hours,1:r.minutes}=t.time.split(":")||[]),r.ampm=t.ampm,isNaN(r.hours)||isNaN(r.minutes)||r.ampm&&!["AM","PM"].includes(r.ampm.toUpperCase())?{}:r}function jc(e,t,r){const n=Lc(e),i=xc(e),a=n?i:e;return e?t&&(n&&r&&e||function(e){const t=Bc(e);return t.ampm&&t.hours&&("pm"===t.ampm.toLowerCase()&&parseInt(t.hours)<12&&(t.hours=(t.hours&&parseInt(t.hours)||0)+12),"am"===t.ampm.toLowerCase()&&"12"===t.hours&&(t.hours="00")),`${t.hours||"12"}:${t.minutes||"00"}`.split(":").map(Yc).join(":")}(a))||function(e){const t=Bc(e);if("object"!=typeof t||Object.keys(t).length)return t.ampm?e:(t.hours>12?(t.hours-=12,t.ampm="PM"):"12"===t.hours?t.ampm="PM":"00"===t.hours?(t.hours="12",t.ampm="AM"):t.ampm="AM","0"===t.hours?.[0]&&(t.hours=t.hours.slice(1)),`${t.hours||"12"}:${t.minutes||"00"} ${t.ampm}`)}(a):void 0}function Gc(e,t){const r=Bc(e),n=Bc(t);if(parseInt(r.hours)<parseInt(n.hours))return-1;if(parseInt(r.hours)>parseInt(n.hours))return 1;if(r.hours===n.hours){if(parseInt(r.minutes)<parseInt(n.minutes))return-1;if(parseInt(r.minutes)>parseInt(n.minutes))return 1}return 0}function qc(e,t=7){const r=Lc(e)+"T00:00",n=new Date(r);return Nc(new Date(n.setDate(n.getDate()+t)))}function $c(e,t=void 0){const[r,n]=(e||"00:00").split(":").map(Yc),i=Mc(t).setHours(r,n,0,0);return Mc(i)}function Wc(e,t,r=!0){const n=new Date(e),i=(new Date(t).getTime()-n.getTime())/1e3/60;return r?Math.abs(Math.round(i)):Math.round(i)}function Hc(e,t){const r=xc(e);if(!r)return"00:00";const n=isNaN(t)?0:t;return xc(zc($c(r),n).toISOString())}function zc(e,t){const r=new Date(e);return new Date(r.getTime()+6e4*t)}function Yc(e){return e.toString()[1]?e:"0"+e}function Qc(e,t){const r=new Date(e),n=new Date(t);return r.getFullYear()===n.getFullYear()&&r.getMonth()===n.getMonth()&&r.getDate()===n.getDate()}const Kc={addDays:qc,addWeek:function(e){return qc(e)},addMinutesToTimeString:Hc,convertTime:jc,getIsoDateString:Pc,getUTCdateString:Rc,DateHHMM:function(e){const t=new Date(e);return function(e,t){const r=parseInt(e,10),n=Math.floor(r/3600),i=Math.floor((r-3600*n)/60),a=r-3600*n-60*i;return(!t||t?.displaySeconds?n+":"+i+":"+a:n+":"+i).split(":").map(Yc).join(":")}(t.getSeconds()+60*t.getMinutes()+3600*t.getHours(),{displaySeconds:!1})},extractDate:Lc,extractTime:xc,formatDate:Nc,getDateByWeek:function(e,t,r,n=!1){const i=new Date(t,0,1+7*(e-1)),a=n?0:1;return i.setDate(i.getDate()+(a-i.getDay())),Nc(i,r)},isISODateString:Oc,isDate:Ac,isTimeString:Fc,offsetDate:Mc,offsetTime:function(e){return Mc(e).getTime()},sameDay:Qc,timeStringMinutes:kc,timeToDate:$c,timeUTC:function(e){const t=Ac(e)||Oc(e)?new Date(e):new Date;return Date.UTC(t.getFullYear(),t.getMonth(),t.getDate())},validTimeValue:wc,validDateString:yc,timeValidation:Tc,dateValidation:vc};function Jc(e,t,r,n,i=0){if(hc().makeDeepCopy)return hc().makeDeepCopy(e,t,r,n);const a=ec(),{stringify:o,toJSON:s,ignore:c,modulate:u}=a||{};if(!a?.enabled&&!r||"object"!=typeof e||"function"==typeof e||null===e||"number"==typeof a?.threshold&&i>=a.threshold)return e;const d=Array.isArray(e)?[]:{},p=Object.keys(e).filter((e=>!r||!c||Array.isArray(c)&&!c.includes(e)||"function"==typeof c&&!c(e))),l=(e,t)=>{d[e]="function"==typeof t?.toString?t.toString():JSON.stringify(t)};for(const a of p){const c=e[a],p="function"==typeof u?u(c):void 0;if(void 0!==p)d[a]=p;else if(t&&"extensions"===a&&Array.isArray(c)){const e=Zc(c);Object.assign(d,...e)}else n&&"extensions"===a?d[a]=[]:Array.isArray(o)&&o.includes(a)?l(a,c):Array.isArray(s)&&s.includes(a)&&"function"==typeof c?.toJSON?d[a]=c.toJSON():null===c?d[a]=void 0:Dc(c)?d[a]=new Date(c).toISOString():d[a]=Jc(c,t,r,n,i+1)}return d}function Zc(e){return e?.map((e=>{const{name:t,value:r}=e;return t&&r&&{[`_${t}`]:r}})).filter(Boolean)}function Xc({element:e,accessor:t}){if("string"!=typeof t)return{values:[]};const r=Jc(e),n=t.split("."),i=[];let a;!function e({targetElement:t,attributes:r=[],significantCharacters:n}){for(const[n,s]of r.entries())if(t?.[s]){const c=r.slice(n+1);if(c.length)if(Array.isArray(t[s])){t[s].forEach((t=>e({targetElement:t,attributes:c})))}else o({targetElement:t=t[s],index:n});else a||(a=t[s]),i.includes(t[s])||i.push(t[s])}function o({targetElement:e,index:t}){if(e&&t===r.length-1&&["string","number"].includes(typeof e)){const t=n?e.slice(0,n):e;a?i.includes(t)||i.push(t):(a=t,i.push(t))}}}({targetElement:r,attributes:n});const o={value:a};return i.length&&(o.values=i),o}function eu(e){return"function"==typeof e}function tu(e){return"string"==typeof e}function ru(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function nu(e,t){return Array.isArray(e)?Object.assign({},...(e??[]).filter(ru).map((e=>e[t]&&{[e[t]]:e})).filter(Boolean)):{}}const iu=e=>t=>e&&"object"==typeof t?Array.isArray(e)&&e.map((e=>({[e]:Xc({element:t,accessor:e})?.value})))||"object"==typeof e&&Object.keys(e).map((e=>({[e]:Xc({element:t,accessor:e})?.value})))||("string"==typeof e&&Xc({element:t,accessor:e}))?.value:void 0,au=iu;function ou(e){return Array.isArray(e)?e.length+e.map(ou).reduce(((e,t)=>e+t),0):"object"==typeof e&&null!==e?Object.keys(e).length+Object.keys(e).map((t=>ou(e[t]))).reduce(((e,t)=>e+t),0):0}function su({tournamentRecords:e}){return{tournamentIds:ru(e)?Object.keys(e):[],...Ni}}var cu=Object.freeze({__proto__:null,getLinkedTournamentIds:js,getTournamentIds:su}),uu=Object.freeze({__proto__:null,getLinkedTournamentIds:js,getTournamentIds:su,linkTournaments:xs,mutate:Bs,query:cu,unlinkTournament:Vs,unlinkTournaments:Ls});const du="DYNAMIC",pu="RANKING",lu="RATING",mu="SCALE",fu="SEEDING",hu={RANKING:pu,RATING:lu,SCALE:mu,SEEDING:fu},gu="tournamentRecords",Iu="policyDefinitions",Uu="tournamentRecord",yu="drawDefinition",Su="matchUpFormat",vu="participantId",Tu="scheduleDates",Pu="structureId",Du="participant",wu="matchUpIds",bu="structures",Ru="matchUpId",Nu="inContext",Mu="structure",Au="courtIds",Eu="venueIds",Cu="matchUps",Ou="courtId",Fu="eventId",ku="matchUp",_u="drawId",xu="error",Lu="event",Vu="param",Bu="object",ju="array",Gu="validate",qu="invalid",$u="_ofType",Wu="_oneOf";function Hu(e){const t=y(e,[{[Du]:!0}]);if(t.error)return t;const r=e.participant.timeItems?.filter((({itemType:e})=>e?.startsWith(mu)&&[pu,lu,fu].includes(e.split(".")[1]))),n={ratings:{},rankings:{},seedings:{}};if(r?.length){const e=e=>r.filter((t=>t?.itemType===e)).sort(((e,t)=>new Date(e.createdAt||void 0).getTime()-new Date(t.createdAt||void 0).getTime())).pop(),t=u(r.map((({itemType:e})=>e)));for(const r of t){const t=e(r);if(t){const[,e,r,i,a]=t.itemType.split("."),o=a?`${i}.${a}`:i,s=(e===fu?"seedings":e===pu&&"rankings")||"ratings";n[s][r]||(n[s][r]=[]),n[s][r].push({scaleValue:t.itemValue,scaleDate:t.itemDate,scaleName:o})}}}return{...Ni,...n}}function zu(e){if(null===e)return{};const{source:t,template:r}=e||{};if(!r)return t;const n={};return function e(t,r,n){if(!t||!r)return;const i=Object.keys(t),a=Object.keys(r),o=Object.assign({},...a.filter((e=>e.indexOf("||"))).map((e=>e.split("||").map((t=>({[t]:e}))))).flat()),s=a.concat(...Object.keys(o)),c=s.includes("*");for(const a of i)if(s.indexOf(a)>=0||c){const i=r[o[a]||a]||c,s=t[a];if("object"!=typeof i||"function"==typeof s||Array.isArray(i)){const e=t[a];if(Array.isArray(i)&&!i.includes(e))return!1;(r[a]||c&&!1!==r[a])&&(n[a]=e)}else if(Array.isArray(s)){const t=s.map((t=>{const r={};return!1!==e(t,i,r)?r:void 0})).filter(Boolean);n[a]=t}else s&&(n[a]={},e(s,i,n[a]))}return}(t,r,n),n}const Yu="voluntaryConsolation",Qu="competitiveBands",Ku="roundRobinTally",Ju="positionActions",Zu="matchUpActions",Xu="rankingPoints",ed="roundNaming",td="participant",rd="progression",nd="scheduling",id="avoidance",ad="scoring",od="seeding",sd="feedIn",cd="draws",ud={POLICY_TYPE_VOLUNTARY_CONSOLATION:Yu,POLICY_TYPE_COMPETITIVE_BANDS:Qu,POLICY_TYPE_ROUND_ROBIN_TALLY:Ku,POLICY_TYPE_POSITION_ACTIONS:Ju,POLICY_TYPE_MATCHUP_ACTIONS:Zu,POLICY_TYPE_RANKING_POINTS:Xu,POLICY_TYPE_ROUND_NAMING:ed,POLICY_TYPE_PARTICIPANT:td,POLICY_TYPE_PROGRESSION:rd,POLICY_TYPE_SCHEDULING:nd,POLICY_TYPE_AVOIDANCE:id,POLICY_TYPE_DISPLAY:"display",POLICY_TYPE_FEED_IN:sd,POLICY_TYPE_SCORING:ad,POLICY_TYPE_SEEDING:od,POLICY_TYPE_AUDIT:"audit",POLICY_TYPE_DRAWS:cd};function dd({tournamentParticipants:e=[],policyDefinitions:t={},contextProfile:r,participantId:n,internalUse:i,personId:a}){const o=Jc(e.find((e=>n&&e.participantId===n||a&&e.person&&e.person.personId===a)),!1,i);if(o){const e=t?.[td];if(r?.withScaleValues){const{ratings:e,rankings:t}=Hu({participant:o});o.rankings=t,o.ratings=e}if(e?.participant)return zu({template:e.participant,source:o})}return o}function pd({context:e,result:t,stack:r,info:n}){return t&&!Array.isArray(t?.stack)&&(t.stack=[]),t&&Array.isArray(t?.stack)&&"string"==typeof r&&t.stack.push(r),t&&n&&(t.info=n),t&&"object"==typeof e&&Object.keys(e).length&&Object.assign(t,S(e)),!t||t?.error||t?.success||Object.assign(t,{...Ni}),t??{success:!0}}const ld="element required",md="missing name";function fd(e){if(!e||"object"!=typeof e)return{error:Za};if(e.element&&"object"!=typeof e?.element)return{error:ys};if(!e?.name)return{error:Za,info:md};if(!e?.element){if(e.discover&&e.tournamentRecords){for(const t of Object.keys(e.tournamentRecords)){const r=fd({element:e.tournamentRecords[t],name:e.name});if(r.error)return pd({result:r,stack:"removeExtension"})}return{...Ni}}return{error:Za,info:ld}}return e?.element.extensions?(e.element.extensions=e.element.extensions.filter((t=>t?.name!==e.name)),{...Ni}):{...Ni,info:ws}}function hd({requiredAttributes:e=["name","value"],extension:t}){if(!t||"object"!=typeof t)return!1;if("string"!=typeof t.name)return!1;const r=Object.keys(t);return e.filter((e=>r.includes(e))).length===e.length}function gd(e){if("object"!=typeof e)return{error:Za};const t="addExtension";if(e?.element&&"object"!=typeof e.element)return pd({result:{error:ys},stack:t});if(!hd({extension:e.extension}))return pd({result:{error:ys,info:"invalid extension"},stack:t});if(!e.element){if(e.discover&&!e.tournamentId&&e.tournamentRecords){for(const r of Object.values(e.tournamentRecords)){const n=gd({extension:e.extension,element:r});if(n.error)return pd({result:n,stack:t})}return{...Ni}}return pd({result:{error:Za},stack:t})}e.element.extensions||(e.element.extensions=[]);if(e?.creationTime??!0){const t=(new Date).toISOString();Object.assign(e.extension,{createdAt:t})}const r=e.element.extensions.find((({name:t})=>t===e.extension.name));return r?r.value=e.extension.value:e.extension.value&&e.element.extensions.push(e.extension),{...Ni}}function Id(e){return e&&"object"==typeof e?e.tournamentRecord?gd({creationTime:e.creationTime,element:e.tournamentRecord,extension:e.extension}):{error:Fi}:{error:Za}}function Ud(e){return e&&"object"==typeof e?e.drawDefinition?gd({creationTime:e.creationTime,element:e.drawDefinition,extension:e.extension}):{error:Bi}:{error:Za}}function yd(e){return e&&"object"==typeof e?e.event?gd({creationTime:e.creationTime,extension:e.extension,element:e.event}):{error:ya}:{error:Za}}function Sd(e){if(!e||"object"!=typeof e)return{error:Za};if(!e.participantId)return{error:Do};const t=e.tournamentRecord?.participants||[],r=dd({participantId:e.participantId,tournamentParticipants:t});return r?gd({creationTime:e.creationTime,extension:e.extension,element:r}):{error:wo}}function vd(e){return e&&"object"==typeof e?e.tournamentRecord?fd({element:e.tournamentRecord,name:e.name}):{error:Fi}:{error:Za}}function Td(e){return e&&"object"==typeof e?e.drawDefinition?fd({element:e.drawDefinition,name:e.name}):{error:Bi}:{error:Za}}function Pd(e){return e&&"object"==typeof e?e?.event?fd({element:e.event,name:e.name}):{error:ya}:{error:Za}}function Dd(e){if(!e||"object"!=typeof e)return{error:Za};if(!e.participantId)return{error:Do};const t=e.tournamentRecord?.participants||[],r=dd({participantId:e.participantId,tournamentParticipants:t});return r?fd({element:r,name:e.name}):{error:wo}}const wd=e=>t=>e[t],bd=(e=[])=>e.map(Nd).filter(Boolean),Rd=(e={})=>wd(e)("participantId"),Nd=(e={})=>wd(e)("matchUpId"),Md=(e={})=>wd(e)("drawId");function Ad(e,t){return(e??0)-(t??0)}function Ed(e){return"number"==typeof e?parseInt(e.toString()):"string"==typeof e?parseInt(e):0}function Cd(e){return!isNaN(e)&&(e&&0==(e&e-1))}function Od(e){return isNaN(e)?0:e%2&&e+1||e}function Fd(e){return Math.pow(2,Math.round(Math.log(e)/Math.log(2)))}function kd(e){return!isNaN(parseFloat(e))}function _d(e){const t=Ed(e);if(!isNaN(t))return 0!==t&&1==(t&-t)}function xd(e){if(isNaN(e))return!1;for(;!Cd(e);)e++;return e}function Ld(e,t){return e=Math.ceil(e),t=Math.floor(t),Math.floor(Math.random()*(t-e+1))+e}function Vd(e){return Number.isSafeInteger("string"==typeof e?+e:e)}function Bd(e,t,r,n,i=2){const a=1-Math.random(),o=1-Math.random();let s=Math.sqrt(-2*Math.log(a))*Math.cos(2*Math.PI*o);return s=s/10+.5,s>1||s<0?s=Bd(e,t,r):(s=Math.pow(s,r),s*=t-e,s+=e),n&&(s=function(e,t){t||(t=1);const r=1/t;return Math.round(e*r)/r}(s,n)),parseFloat(s.toFixed(i))}function jd(e){return Array.isArray(e)?e?.filter(((e,t,r)=>r.lastIndexOf(e)===t)):[]}function Gd(e){return Array.isArray(e)?e.map((e=>[Math.random(),e])).sort(((e,t)=>e[0]-t[0])).map((e=>e[1])):[]}function qd(e){return Vd(e)?e:1/0}function $d(e){return Array.isArray(e)?e.reduce(((e,t)=>(e[t]||(e[t]=0),e[t]++,e)),{}):{}}function Wd(e){return Object.keys(e).reduce(((t,r)=>{const n=e[r];return t[n]?t[n].push(r):t[n]=[r],t}),{})}function Hd(e,t,r){return r.indexOf(e)===t}function zd(e){return Array.isArray(e)&&e.length?e.splice(Math.floor(Math.random()*e.length),1)[0]:void 0}function Yd(e){return e[Math.floor(Math.random()*e.length)]}function Qd(e,t){return Array.from({length:t-e},((t,r)=>r+e))}function Kd(e,t){return t.reduce(((t,r,n)=>(r===e&&t.push(n),t)),[])}function Jd(e,t){return Array.isArray(e)&&Array.isArray(t)?e.filter((e=>-1!==t.indexOf(e))).filter(((e,t,r)=>r.indexOf(e)===t)):[]}function Zd(e,t){return Array.isArray(e)&&Array.isArray(t)?e.filter((e=>!t.includes(e))):[]}function Xd(e,t){return!(!Array.isArray(e)||!Array.isArray(t))&&e.some((e=>t.includes(e)))}function ep(e,t){return Array.isArray(e)?e.reduce(((e,r,n)=>{const i=Math.floor(n/t);return e[i]=[].concat(e[i]||[],r),e}),[]):[]}function tp(e){return!!Array.isArray(e)&&e.reduce(((e,t)=>!isNaN(parseInt(t))&&e),!0)}function rp(e){return!!Array.isArray(e)&&e.reduce(((e,t)=>isNaN(parseInt(t))&&e),!0)}function np(e,t,r){return Array.isArray(e)?e.reduce(((e,n,i)=>{const a=!!r&&!!(Math.floor(i/t)%2),o=i%t,s=a?t-1-o:o;return e[s]||(e[s]=[]),e[s].push(n),e}),[]):[]}function ip({representativeParticipantIds:e,drawDefinition:t}){if(!t)return{error:Bi};if(!Array.isArray(e))return{error:ys};const r=((e=[])=>e.map(Rd).filter(Boolean))(t?.entries||[]);if(e.length&&Jd(e,r).length<e.length)return{error:ys};return Ud({drawDefinition:t,extension:{name:gi,value:e}})}function ap({drawDefinition:e}){if(!e)return{error:Li};const t={};return{allPositionedParticipantIds:(e.structures||[]).map((e=>{const r=e.stage;t[r]||(t[r]=[]);const{positionAssignments:n}=op({structure:e}),i=n?.map(v).filter(Boolean)??[];return t[r].push(...i),i})).flat(),stagePositionedParticipantIds:t}}function op({drawDefinition:e,structureId:t,structure:r}){let n,i=[];if(!r){if(!e)return{positionAssignments:i,error:Li};if(({structure:r,error:n}=w({drawDefinition:e,structureId:t})),n)return{positionAssignments:i,error:n}}return r.structures?i=[].concat(...r.structures.map((e=>op({structure:e}).positionAssignments))):r.positionAssignments?i=r.positionAssignments:n=Ra,{positionAssignments:i,error:n}}function sp({drawDefinition:e,structureId:t,structure:r}){const n=op({drawDefinition:e,structureId:t,structure:r})?.positionAssignments||[],i=n?.filter((e=>e.participantId??e.bye??e.qualifier)),a=n&&n?.length===i?.length,o=n?.filter((e=>!e.participantId&&!e.bye&&!e.qualifier)),s=n?.filter((e=>!e.participantId&&e.bye)),c=n?.filter((e=>!e.participantId&&e.qualifier));return{allPositionsAssigned:a,positionAssignments:n,unassignedPositions:o,assignedPositions:i,qualifierPositions:c,byePositions:s}}const cp="addDrawDefinition",up="addMatchUps",dp="addParticipants",pp="addScaleItems",lp="addVenue",mp="audit",fp="deleteParticipants",hp="deleteVenue",gp="deletedDrawIds",Ip="deletedMatchUpIds",Up="modifyDrawDefinition",yp="modifyDrawEntries",Sp="modifyEventEntries",vp="modifyMatchUp",Tp="modifyParticipants",Pp="modifyPositionAssignments",Dp="modifySeedAssignments",wp="modifyTournamentDetail",bp="modifyVenue",Rp="mutations",Np="publishEvent",Mp="publishEventSeeding",Ap="publishOrderOfPlay",Ep="unPublishEvent",Cp="unPublishEventSeeding",Op="unPublishOrderOfPlay",Fp="updateInContextMatchUp",kp={ADD_DRAW_DEFINITION:cp,ADD_MATCHUPS:up,ADD_PARTICIPANTS:dp,ADD_SCALE_ITEMS:pp,ADD_VENUE:lp,AUDIT:mp,DELETE_PARTICIPANTS:fp,DELETE_VENUE:hp,DELETED_DRAW_IDS:gp,DELETED_MATCHUP_IDS:Ip,MODIFY_DRAW_DEFINITION:Up,MODIFY_DRAW_ENTRIES:yp,MODIFY_EVENT_ENTRIES:Sp,MODIFY_MATCHUP:vp,MODIFY_PARTICIPANTS:Tp,MODIFY_POSITION_ASSIGNMENTS:Pp,MODIFY_SEED_ASSIGNMENTS:Dp,MODIFY_TOURNAMENT_DETAIL:wp,MODIFY_VENUE:bp,MUTATIONS:Rp,PUBLISH_EVENT_SEEDING:Mp,PUBLISH_EVENT:Np,PUBLISH_ORDER_OF_PLAY:Ap,UNPUBLISH_EVENT_SEEDING:Cp,UNPUBLISH_EVENT:Ep,UNPUBLISH_ORDER_OF_PLAY:Op,UPDATE_INCONTEXT_MATCHUP:Fp};function _p(e,t){if(!e)return{error:Li};let r=Date.now();e.updatedAt&&r===new Date(e.updatedAt).getTime()&&(r+=1);const n=new Date(r).toISOString(),i=t?.filter(Boolean);return e.updatedAt=n,e.structures?.filter(Boolean).forEach((e=>{i?.length&&!i?.includes(e.structureId)||(e.updatedAt=n)})),{...Ni}}function xp({drawDefinition:e,tournamentId:t,matchUps:r,eventId:n}){return e&&_p(e),rc({payload:{matchUps:r,tournamentId:t,eventId:n},topic:up}),{...Ni}}function Lp({drawDefinition:e,tournamentId:t,matchUpIds:r,eventId:n,action:i}){e&&_p(e),rc({topic:Ip,payload:{tournamentId:t,matchUpIds:r,eventId:n,action:i}});for(const e of r)ac({key:e});return{...Ni}}function Vp({drawDefinition:e,tournamentId:t,structureId:r,context:n,eventId:i,matchUp:a}){if(!a)return console.log(Ba),{error:Ba};if(e){jp({drawDefinition:e,structureIds:r?[r]:void 0,tournamentId:t,eventId:i})}return rc({topic:vp,payload:{matchUp:a,tournamentId:t,context:n},key:a.matchUpId}),{...Ni}}function Bp({tournamentId:e,eventId:t,drawDefinition:r}){return r?(_p(r),rc({payload:{drawDefinition:r,tournamentId:e,eventId:t},topic:cp,key:r.drawId}),{...Ni}):(console.log(Li),{error:Li})}function jp({drawDefinition:e,tournamentId:t,structureIds:r,eventId:n}){return e?(_p(e,r),rc({payload:{tournamentId:t,eventId:n,drawDefinition:e},topic:Up,key:e.drawId}),{...Ni}):{error:Li}}function Gp({drawDefinition:e,tournamentId:t,structure:r,event:n}){if(!e)return{error:Li};if(!r)return{error:ha};const i=op({structure:r}),a=r.structureId,o=e.drawId,s=n?.eventId;return rc({topic:Pp,payload:{positionAssignments:i,tournamentId:t,structureId:a,eventId:s,drawId:o},key:a}),jp({structureIds:[a],drawDefinition:e,tournamentId:t,eventId:s}),{...Ni}}const qp="MAIN",$p="QUALIFYING",Wp="CONSOLATION",Hp="VOLUNTARY_CONSOLATION",zp="PLAY_OFF",Yp=[qp,$p,Wp,zp,Hp],Qp={[$p]:1,[qp]:2,[zp]:3,[Wp]:3,[Hp]:4},Kp="finishingPositions",Jp="aggregateEventStructures",Zp={[qp]:1,[zp]:2,[Wp]:3,[$p]:4,[Hp]:5},Xp={[zp]:1,[qp]:2,[Wp]:3,[$p]:4,[Hp]:5},el="CLUSTER",tl="WATERFALL",rl="ITEM",nl="CONTAINER",il="DRAW",al="RANDOM",ol="TOP_DOWN",sl="BOTTOM_UP",cl="POSITION",ul="WINNER",dl="LOSER",pl="FIRST_MATCHUP",ll="AD_HOC",ml="FEED_IN",fl="COMPASS",hl="OLYMPIC",gl="SINGLE_ELIMINATION",Il="DOUBLE_ELIMINATION",Ul="FIRST_MATCH_LOSER_CONSOLATION",yl="FIRST_ROUND_LOSER_CONSOLATION",Sl="LUCKY_DRAW",vl="CURTIS_CONSOLATION",Tl="CURTIS_CONSOLATION",Pl="FEED_IN_CHAMPIONSHIP_TO_SF",Dl="FEED_IN_CHAMPIONSHIP_TO_SF",wl="FEED_IN_CHAMPIONSHIP_TO_QF",bl="FEED_IN_CHAMPIONSHIP_TO_QF",Rl="FEED_IN_CHAMPIONSHIP_TO_R16",Nl="FEED_IN_CHAMPIONSHIP_TO_R16",Ml="MODIFIED_FEED_IN_CHAMPIONSHIP",Al="MODIFIED_FEED_IN_CHAMPIONSHIP",El="FEED_IN_CHAMPIONSHIP",Cl="ROUND_ROBIN",Ol="ROUND_ROBIN_WITH_PLAYOFF",Fl="DECIDER",kl="BACKDRAW",_l={0:{name:"East",abbreviation:"E"},"0-1":{name:"West",abbreviation:"W"},"0-2":{name:"North",abbreviation:"N"},"0-3":{name:"Northeast",abbreviation:"NE"},"0-1-1":{name:"South",abbreviation:"S"},"0-1-2":{name:"Southwest",abbreviation:"SW"},"0-2-1":{name:"Northwest",abbreviation:"NW"},"0-1-1-1":{name:"Southeast",abbreviation:"SE"}},xl={0:{name:"East",abbreviation:"E"},"0-1":{name:"West",abbreviation:"W"},"0-2":{name:"North",abbreviation:"N"},"0-1-1":{name:"South",abbreviation:"S"}},Ll="WIN_RATIO",Vl="ROUND_OUTCOME",Bl=[fl,vl,bl,Nl,Dl,El,wl,Rl,Pl,Ul,yl,Sl,Al,hl,zp,Ol],jl={MAIN:qp,QUALIFYING:$p,CONSOLATION:Wp,ITEM:rl,CONTAINER:nl,FIRST_MATCHUP:pl,WINNER:ul,LOSER:dl,AD_HOC:ll,FEED_IN:ml,FLEX_ROUNDS:"AD_HOC",COMPASS:fl,PLAY_OFF:zp,OLYMPIC:hl,KNOCKOUT:"SINGLE_ELIMINATION",SINGLE_ELIMINATION:gl,DOUBLE_ELIMINATION:Il,CURTIS:vl,FICSF:Pl,FICQF:wl,FICR16:Rl,MFIC:Ml,VOLUNTARY_CONSOLATION:Hp,FIRST_MATCH_LOSER_CONSOLATION:Ul,FIRST_ROUND_LOSER_CONSOLATION:yl,MODIFIED_FEED_IN_CHAMPIONSHIP:Al,FEED_IN_CHAMPIONSHIP_TO_R16:Nl,FEED_IN_CHAMPIONSHIP_TO_QF:bl,FEED_IN_CHAMPIONSHIP_TO_SF:Dl,FEED_IN_CHAMPIONSHIP:El,LUCKY_DRAW:Sl,ROUND_ROBIN_WITH_PLAYOFF:Ol,ROUND_ROBIN:Cl,DECIDER:Fl,BACKDRAW:kl,COMPASS_ATTRIBUTES:_l,OLYMPIC_ATTRIBUTES:xl,DRAW:il,RANDOM:al,TOP_DOWN:ol,BOTTOM_UP:sl,WATERFALL:tl,WIN_RATIO:Ll,ROUND_OUTCOME:Vl,MULTI_STRUCTURE_DRAWS:Bl,generatedDrawTypes:[ll,fl,vl,Il,bl,Nl,Dl,El,ml,Ul,yl,Sl,Al,hl,zp,Cl,Ol,gl],stageOrder:Qp,finishOrder:Zp,AGGREGATE_EVENT_STRUCTURES:Jp,FINISHING_POSITIONS:Kp};function Gl({tournamentRecord:e,drawDefinition:t,resetEntries:r,event:n}){if(!t)return{error:Li};const i=t.structures?.find((e=>e.stage===Hp));if(!i)return{error:ma};const a=i.matchUps?.map((({matchUpId:e})=>e))||[];return i.positionAssignments=[],i.seedAssignments=[],i.matchUps=[],Lp({tournamentId:e?.tournamentId,action:"resetVoluntaryConsolationStructure",matchUpIds:a,drawDefinition:t}),r&&(t.entries=t.entries.filter((e=>e.entryStage!==Hp))),jp({tournamentId:e?.tournamentId,eventId:n?.eventId,drawDefinition:t,structureIds:[i.structureId]}),{...Ni}}function ql({drawPositions:e,structure:t}){if([$p,qp].includes(t.stage)&&1===t.stageSequence)return;const{positionAssignments:r}=op({structure:t}),n=r?.filter((({drawPosition:t})=>e?.includes(t)));n?.forEach((e=>{gd({element:e,extension:{name:si,value:!0}})}))}const $l="extensionQueries";function Wl({discover:e,element:t,name:r,...n}){if(!t||!r){if(e&&n){const t=Object.keys(n).filter((t=>"boolean"==typeof e||Array.isArray(e)&&e.includes(t))).find((e=>!!Array.isArray(n[e]?.extensions)&&n[e].extensions.find((e=>e?.name===r))));let i=t&&n[t];!i&&n.tournamentRecords&&(i=Object.values(n.tournamentRecords).find((e=>e.extensions?.length)));const a=i?.extensions?.find((e=>e?.name===r));return{extension:a,info:a?void 0:ws}}return a({result:{error:Za},stack:$l})}if(!Array.isArray(t.extensions))return{info:"no extensions"};const i=t.extensions.find((e=>e?.name===r));return{extension:i,info:i?void 0:ws}}function Hl({drawDefinition:e,positionAction:t}){const{extension:r}=Wl({name:ni,element:e}),n=Array.isArray(r?.value)?r?.value??[]:[];if(!n?.length){const t=e.structures.find((e=>e.stage===qp));if(t){const e=op({structure:t}).positionAssignments?.map((({drawPosition:e,participantId:t,bye:r,qualifier:n})=>({drawPosition:e,participantId:t,qualifier:n,bye:r})));n.push({name:"initialMainAssignments",initialAssignments:e})}}gd({element:e,extension:{name:ni,value:n.concat(t)}})}const zl="ALTERNATE",Yl="CONFIRMED",Ql="DIRECT_ACCEPTANCE",Kl="FEED_IN",Jl="JUNIOR_EXEMPT",Zl="LUCKY_LOSER",Xl="ORGANISER_ACCEPTANCE",em="QUALIFIER",tm="SPECIAL_EXEMPT",rm="UNGROUPED",nm="UNPAIRED",im="WILDCARD",am="WITHDRAWN",om=[Yl,Ql,Jl,Xl,tm],sm=[Kl,Zl,em],cm=[Yl,Ql,Kl,Jl,Xl,tm,im],um=[Yl,Ql,Jl,Zl,em,Xl,tm,im],dm=[zl,Yl,Ql,Kl,Jl,Zl,Xl,em,"REGISTERED",tm,rm,nm,im,am],pm={ALTERNATE:zl,CONFIRMED:Yl,DIRECT_ACCEPTANCE:Ql,DIRECT_ENTRY_STATUSES:cm,DRAW_SPECIFIC_STATUSES:sm,EQUIVALENT_ACCEPTANCE_STATUSES:om,FEED_IN:Kl,JUNIOR_EXEMPT:Jl,LUCKY_LOSER:Zl,ORGANISER_ACCEPTANCE:Xl,QUALIFIER:em,SPECIAL_EXEMPT:tm,STRUCTURE_SELECTED_STATUSES:um,UNGROUPED:rm,UNPAIRED:nm,VALID_ENTRY_STATUSES:dm,WILDCARD:im,WITHDRAWN:am},lm="SIGN_IN_STATUS",mm="SIGNED_OUT",fm="SIGNED_IN",hm="TEAM",gm="INDIVIDUAL",Im="GROUP",Um="PAIR",ym="TEAM",Sm={TEAM_PARTICIPANT:hm,INDIVIDUAL:gm,GROUP:Im,TEAM:ym,PAIR:Um},vm={INDIVIDUAL:gm,GROUP:Im,PAIR:Um,TEAM:ym,SIGN_IN_STATUS:lm,SIGNED_OUT:mm,SIGNED_IN:fm};function Tm(e){const{tournamentRecord:t,replaceWithBye:r,drawDefinition:n,destroyPair:i,entryStatus:o,matchUpsMap:s,drawId:c}=e,u="removeDrawPositionAssignment",d=N(e);if(d.error)return a({result:d,stack:u});const{participantId:p}=d,{drawPosition:l,event:m,structureId:f}=e;if([zl,am].includes(o)&&p){const{tournamentRecord:t}=e,{participant:r}=M({tournamentRecord:t,participantId:p}),{participantType:s,individualParticipantIds:d}=r??{};if(i&&s===Um){const e=E({tournamentRecord:t,drawDefinition:n,participantId:p,event:m});if(e.error)return a({result:e,stack:u});d&&A({participantIds:d,tournamentRecord:t,drawDefinition:n,entryStatus:o,drawId:c,event:m})}else A({participantIds:[p],tournamentRecord:t,drawDefinition:n,entryStatus:o,drawId:c,event:m})}if(r){const e=R({tournamentRecord:t,drawDefinition:n,drawPosition:l,structureId:f,matchUpsMap:s,event:m});if(e.error)return a({result:e,stack:u})}const{structure:h}=w({drawDefinition:n,structureId:f});ql({structure:h,drawPositions:[l]});return Hl({drawDefinition:n,positionAction:{name:"removeDrawPositionAssignment",replaceWithBye:r,drawPosition:l,entryStatus:o,structureId:f}}),d}function Pm(e){return Object.assign(e,{entryStatus:am}),Tm(e)}function Dm(e){return tu(e)?e.split(" ").map((e=>e.split("").map(((e,t)=>t?e.toLowerCase():e.toUpperCase())).join(""))).join(" "):e}function wm(e){return tu(e)?Dm(e.replace(/_/g," ")):""}function bm(){const e=[];for(let t=0;t<256;t++)e[t]=(t<16?"0":"")+t.toString(16);const t=4294967295*Math.random()|0,r=4294967295*Math.random()|0,n=4294967295*Math.random()|0,i=4294967295*Math.random()|0;return e[255&t]+e[t>>8&255]+e[t>>16&255]+e[t>>24&255]+"-"+e[255&r]+e[r>>8&255]+"-"+e[r>>16&15|64]+e[r>>24&255]+"-"+e[63&n|128]+e[n>>8&255]+"-"+e[n>>16&255]+e[n>>24&255]+e[255&i]+e[i>>8&255]+e[i>>16&255]+e[i>>24&255]}const Rm=({finishingPosition:e=Vl,qualifyingRoundNumber:t,structureAbbreviation:r,seedAssignments:n=[],stageSequence:i=1,structureOrder:a,seedingProfile:o,matchUpFormat:s,structureType:c,structureName:u,matchUpType:d,matchUps:p=[],structureId:l,roundOffset:m,roundLimit:f,stageOrder:h,structures:g,stage:I})=>{const U={structureId:l??bm(),structureAbbreviation:r,finishingPosition:e,seedAssignments:n,matchUpFormat:s,stageSequence:i,structureName:u};a&&(U.structureOrder=a),c&&(U.structureType=c),o&&("string"==typeof o?U.seedingProfile=o:"object"==typeof o&&"string"==typeof o.positioning&&(U.seedingProfile=o.positioning)),d&&(U.matchUpType=d),m&&(U.roundOffset=m),h&&(U.stageOrder=h),f&&(U.roundLimit=f),I&&(U.stage=I),t&&(U.qualifyingRoundNumber=t);const y=p.flatMap((({drawPositions:e})=>e)).filter(Boolean);return g?U.structures=g:(U.matchUps=p,U.positionAssignments=jd(y).sort(((e,t)=>e-t)).map((e=>({drawPosition:e})))),U};function Nm({structureName:e=wm(Hp),structureAbbreviation:t,drawDefinition:r,matchUpType:n,structureId:i}){if(!r)return{error:Li};const a=Rm({stage:Hp,structureAbbreviation:t,structureName:e,matchUps:[],structureId:i,matchUpType:n});return r.structures||(r.structures=[]),r.structures.push(a),jp({drawDefinition:r,structureIds:[a.structureId]}),{...Ni}}function Mm({drawDefinition:e,structure:t}){const r={},n=[];return(e?.structures??[t]).filter((e=>e&&"object"==typeof e)).forEach((e=>{if(!e)return;const{structureId:t,matchUps:i,structures:a}=e,o=Array.isArray(a);if(o)o&&a.forEach((e=>{const{structureName:i}=e,a=e.matchUps;r[e.structureId]={matchUps:a,itemStructureIds:[],structureName:i},a&&(n.push(...a),a.forEach((e=>{e.tieMatchUps&&n.push(...e.tieMatchUps)}))),r[t]||(r[t]={itemStructureIds:[],matchUps:[]}),r[t].itemStructureIds||(r[t].itemStructureIds=[]),r[t].itemStructureIds.push(e.structureId)}));else{const e=i;r[t]={matchUps:e,itemStructureIds:[]},e?.forEach((e=>{n.push(e),e.tieMatchUps&&n.push(...e.tieMatchUps)}))}})),{mappedMatchUps:r,drawMatchUps:n}}function Am({mappedMatchUps:e,matchUpsMap:t,structureId:r,inContext:n}){const i=(e=t?.mappedMatchUps??e)[r],a=(i?.itemStructureIds||[]).map((t=>{const{matchUps:i,structureName:a}=e[t];return n?i.map((e=>Object.assign(L(e,!0,!0),{containerStructureId:r,structureId:t,structureName:a}))):i})).flat();return(i?.matchUps||[]).concat(...a)}function Em(e){Object.assign(e,{requireParticipants:!1});const t=Cm(e);if(t.error)return a({result:t,stack:"getAllDrawMatchUps"});const{abandonedMatchUps:r,completedMatchUps:n,upcomingMatchUps:i,pendingMatchUps:o,byeMatchUps:s,matchUpsMap:c}=t;return{matchUps:(r??[]).concat(...n??[],...i??[],...o??[],...s??[]),matchUpsMap:c}}function Cm(e){if(!e?.drawDefinition)return{error:Li};let{tournamentParticipants:t,contextContent:r,matchUpsMap:n}=e;const{scheduleVisibilityFilters:i,tournamentAppliedPolicies:a,requireParticipants:o,participantsProfile:s,afterRecoveryTimes:c,policyDefinitions:u,tournamentRecord:d,usePublishState:p,contextFilters:l,matchUpFilters:m,scheduleTiming:f,participantMap:h,publishStatus:g,contextProfile:I,drawDefinition:U,nextMatchUps:y,inContext:S,context:v,event:T}=e;let P,D=[],w=[],R=[],N=[],M=[];I&&!r&&(r=k({policyDefinitions:u,tournamentRecord:d,contextProfile:I,event:T})),!t?.length&&d&&(t=d?.participants,(S||s?.withGroupings)&&t?.length&&({participantsWithGroupings:t,groupInfo:P}=C({participants:t,participantsProfile:s})));const{structures:A}=b({drawDefinition:U});if(!A)return{error:ma};n||(n=Mm({drawDefinition:U}));const E=U&&_({drawDefinition:U}).exitProfiles;A.forEach((e=>{const{byeMatchUps:s=[],pendingMatchUps:P=[],upcomingMatchUps:b=[],completedMatchUps:A=[],abandonedMatchUps:C=[]}=F({matchUpFilters:y?void 0:m,contextFilters:y?void 0:l,inContext:S||y||l,tournamentAppliedPolicies:a,scheduleVisibilityFilters:i,tournamentParticipants:t,requireParticipants:o,afterRecoveryTimes:c,policyDefinitions:u,tournamentRecord:d,usePublishState:p,contextContent:r,participantMap:h,scheduleTiming:f,publishStatus:g,contextProfile:I,drawDefinition:U,exitProfiles:E,matchUpsMap:n,structure:e,context:v,event:T});D=D.concat(...C),w=w.concat(...A),R=R.concat(...b),N=N.concat(...P),M=M.concat(...s)}));const L=e=>m||y||l?(m&&(e=x({matchUps:e,...m})),l&&(e=x({matchUps:e,...l,processContext:!0})),e):e,V={abandonedMatchUps:L(D),completedMatchUps:L(w),upcomingMatchUps:L(R),pendingMatchUps:L(N),byeMatchUps:L(M),matchUpsMap:n,...Ni,groupInfo:P};if(y){const e="object"==typeof y||{abandoned:!0,completed:!0,upcoming:!0,pending:!0,bye:!0},{abandoned:t,completed:r,upcoming:n,pending:i,bye:a}=e,o=[].concat(...t&&D||[],...r&&w||[],...n&&R||[],...i&&N||[],...a&&M||[]);O({inContextDrawMatchUps:o,drawDefinition:U})}return V}function Om({drawDefinition:e,structureId:t}){if(!e)return{error:Li};if(!t)return{error:la};const{structures:r}=Fm({drawDefinition:e}),n=r?.map((e=>e.structures?[...e.structures].concat(e):e)).flat(),i=n?.find((e=>e.structureId===t));if(!i)return{error:ma};return{structure:i,containingStructure:i.structureType===rl?n?.find((e=>e.structures?.some((e=>e.structureId===t)))):void 0}}function Fm({withStageGrouping:e,drawDefinition:t,stageSequences:r,stageSequence:n,roundTarget:i,sortConfig:a,stages:o,stage:c}){const u=!t&&Li||!t?.structures&&fa||void 0;if(u)return{error:u,structures:[],stageStructures:{}};const d=t?.structures?.filter((function(e){return!c&&!Array.isArray(o)||c&&e.stage===c||Array.isArray(o)&&o.includes(e.stage)})).filter((function(e){return!n&&!Array.isArray(r)||n&&e.stageSequence===n||Array.isArray(r)&&r.includes(e.stageSequence)})).filter((e=>{const t=s({element:e,name:yi})?.extension?.value;return!i||i===t})).sort(((e,t)=>V(e,t,a)))??[],p=e?Object.assign({},...Yp.map((e=>{const t=d?.filter((t=>t.stage===e));return t?.length&&{[e]:t}})).filter(Boolean)):{};return{structures:d,stageStructures:p}}const km="ABANDONED",_m="AWAITING_RESULT",xm="BYE",Lm="CANCELLED",Vm="COMPLETED",Bm="DEAD_RUBBER",jm="DEFAULTED",Gm="DOUBLE_DEFAULT",qm="DOUBLE_WALKOVER",$m="IN_PROGRESS",Wm="INCOMPLETE",Hm="NOT_PLAYED",zm="RETIRED",Ym="SUSPENDED",Qm="TO_BE_PLAYED",Km="WALKOVER",Jm=[_m,Vm,jm,$m,Wm,zm,Ym],Zm=[_m,Vm,jm,qm,Gm,$m,Wm,zm,Ym,Km],Xm=[km,_m,xm,Lm,Vm,Bm,jm,qm,Gm,$m,Wm,Hm,zm,Ym,Qm,Km],ef=[xm,qm,Gm,Vm,jm,zm,Km],tf=[km,_m,Lm,Bm,$m,Wm,Hm,Ym,Qm,void 0],rf=[Lm,km,Vm,Bm,jm,qm,Gm,zm,Km],nf=[km,Vm,jm,qm,Gm,$m,zm,Km],af=[$m,Wm,Ym,Qm],of={ABANDONED:km,AWAITING_RESULT:_m,BYE:xm,CANCELLED:Lm,COMPLETED:Vm,DEAD_RUBBER:Bm,DEFAULTED:jm,DOUBLE_WALKOVER:qm,DOUBLE_DEFAULT:Gm,IN_PROGRESS:$m,INCOMPLETE:Wm,NOT_PLAYED:Hm,RETIRED:zm,SUSPENDED:Ym,TO_BE_PLAYED:Qm,WALKOVER:Km};function sf({provisionalPositioning:e,isPositionAction:t,tournamentRecord:r,drawDefinition:n,drawPosition:i,matchUpsMap:o,structureId:s,structure:c,event:u}){if(!n)return{error:Li};if(c||({structure:c}=w({drawDefinition:n,structureId:s})),!c)return{error:ma};s||({structureId:s}=c);const d="assignDrawPositionBye";me({method:d,color:"cyan",drawPosition:i}),o||(o=se({drawDefinition:n}));const{positionAssignments:p}=Q({structure:c}),{activeDrawPositions:l}=j({drawDefinition:n,structureId:s}),m=p?.find((e=>e.drawPosition===i));if(m?.bye)return{...Ni};const f=l?.includes(i);if(f)return{error:Qi};const h=p?.find((e=>e.drawPosition===i));if(!h)return{error:Ki};const{filled:g,containsBye:I,assignedParticipantId:U}=function(e){const t=e.bye,r=e.qualifier,n=e.participantId,i=t||r||n;return{containsBye:t,containsQualifier:r,assignedParticipantId:n,filled:i}}(h);if(I)return{...Ni};if(g&&!I)return a({result:{error:$i},stack:d});const y=ue({inContext:!0,drawDefinition:n,matchUpsMap:o}).matchUps??[],{matchUps:S}=J({provisionalPositioning:e,drawDefinition:n,matchUpFilters:{isCollectionMatchUp:!1},matchUpsMap:o,structure:c});if(p?.forEach((e=>{e.drawPosition===i&&(e.bye=!0)})),c.structureType===nl)return function({tournamentRecord:e,drawDefinition:t,drawPosition:r,matchUps:n,event:i}){n.forEach((n=>{n.drawPositions?.includes(r)&&uf({eventId:i?.eventId,tournamentRecord:e,drawDefinition:t,matchUp:n})}))}({tournamentRecord:r,drawDefinition:n,drawPosition:i,matchUps:S}),G({tournamentId:r?.tournamentId,drawDefinition:n,structure:c,event:u}),cf({assignedParticipantId:U,isPositionAction:t,drawDefinition:n,drawPosition:i,structureId:s,stack:d});const{roundProfile:v,roundMatchUps:T}=le({matchUps:S}),P=v&&Object.keys(v).map((e=>parseInt(e))).reverse(),D=P?.find((e=>v?.[e].drawPositions?.includes(i))),b=D?T?.[D].find((({drawPositions:e})=>e?.includes(i))):void 0;b&&uf({tournamentRecord:r,drawDefinition:n,matchUp:b,event:u});const R=b?.drawPositions?.find((e=>e!==i));if(b&&R){const e=df({sourceDrawPositions:b.drawPositions,matchUpId:b.matchUpId,inContextDrawMatchUps:y,drawPositionToAdvance:R,tournamentRecord:r,drawDefinition:n,matchUpsMap:o});if(e.error)return e}return G({tournamentId:r?.tournamentId,drawDefinition:n,structure:c,event:u}),cf({assignedParticipantId:U,isPositionAction:t,drawDefinition:n,drawPosition:i,structureId:s,stack:d})}function cf({assignedParticipantId:e,isPositionAction:t,drawDefinition:r,drawPosition:n,structureId:i,stack:o}){if(t){pe({drawDefinition:r,positionAction:{removedParticipantId:e,drawPosition:n,structureId:i,name:o}})}return a({result:{...Ni},stack:o})}function uf({tournamentRecord:e,drawDefinition:t,eventId:r,matchUp:n,event:i}){Object.assign(n,{matchUpStatus:xm,score:void 0,winningSide:void 0}),q({tournamentId:e?.tournamentId,eventId:r??i?.eventId,context:"setMatchUpStatusBye",drawDefinition:t,matchUp:n})}function df({drawPositionToAdvance:e,inContextDrawMatchUps:t,sourceDrawPositions:r,tournamentRecord:n,drawDefinition:i,matchUpsMap:o,matchUpId:s,event:c}){me({method:"advanceDrawPosition",color:"cyan",drawPositionToAdvance:e});const u=o.drawMatchUps.find((e=>e.matchUpId===s)),d=t.find((e=>e.matchUpId===s)),p=d?.structureId,{structure:l}=w({drawDefinition:i,structureId:p}),{positionAssignments:m}=Q({structure:l}),f=m?.filter((e=>e.bye)).map((e=>e.drawPosition)),h=u?.drawPositions?.find((t=>t!==e)),g=h&&f?.includes(h),{targetLinks:{loserTargetLink:I},targetMatchUps:{loserMatchUp:U,winnerMatchUp:y,loserTargetDrawPosition:S}}=de({inContextDrawMatchUps:t,drawDefinition:i,matchUpId:s});if(y&&y.structureId===l?.structureId&&function({drawPositionToAdvance:e,inContextDrawMatchUps:t,sourceDrawPositions:r,tournamentRecord:n,drawDefinition:i,winnerMatchUp:o,matchUpsMap:s,event:c}){const u="advanceWinner",d=s.drawMatchUps.find((e=>e.matchUpId===o.matchUpId)),p=t.find((e=>e.matchUpId===o.matchUpId)),l=p?.structureId,{structure:m}=w({drawDefinition:i,structureId:l}),{positionAssignments:f}=Q({structure:m}),h=f?.find((({drawPosition:t})=>t===e)),g=h?.bye,I=d.drawPositions?.filter(Boolean),U=f?.filter((e=>I?.includes(e.drawPosition))),y=f?.find((({drawPosition:t})=>t===e)),S=r?.find((t=>t!==e)),v=S&&U?.find((({drawPosition:e})=>e===S)),T=v?.bye,P=g&&T;P&&console.log({isByeAdvancedBye:P});if(I?.length>1&&g&&!T)return a({result:{error:$i},stack:u});const D=I?.find((t=>t!==e));let b=P;const R=[...(d.drawPositions||[]).filter(Boolean),void 0,void 0].slice(0,2),N=R.map((t=>!t&&!b||t===e?(b=!0,e):t)).sort(fe);if(!b)return console.log("@@@@@@@",{advancingAssignmentIsBye:y,drawPositionToAdvance:e,existingAssignments:U}),a({result:{error:$i},stack:u});const M=f?.find((({drawPosition:e})=>e===D))?.bye,A=f?.find((({drawPosition:t})=>t===e))?.bye,E=A||M?xm:Qm;Object.assign(d,{matchUpStatus:E,score:void 0,winningSide:void 0,drawPositions:N});const C=d.drawPositions.find((e=>!R.includes(e)));me({method:u,color:"brightyellow",changedDrawPosition:C,pairedDrawPositionIsBye:M,drawPositionIsBye:A}),q({tournamentId:n?.tournamentId,matchUp:d,eventId:c?.eventId,context:u,drawDefinition:i});const{targetLinks:{loserTargetLink:O},targetMatchUps:{loserMatchUp:F,loserTargetDrawPosition:k}}=de({matchUpId:o.matchUpId,inContextDrawMatchUps:t,drawDefinition:i});if(M||A){const r=M?e:D;if(r)df({drawPositionToAdvance:r,matchUpId:o.matchUpId,inContextDrawMatchUps:t,tournamentRecord:n,drawDefinition:i,matchUpsMap:s});else if(A&&O&&F)if(F.feedRound)pf({loserTargetDrawPosition:k,tournamentRecord:n,loserTargetLink:O,drawDefinition:i,loserMatchUp:F,matchUpsMap:s});else{const e=1-o.roundPosition%2,t=F.drawPositions[e],r=sf({structureId:O.target.structureId,drawPosition:t,tournamentRecord:n,drawDefinition:i,event:c});if(r.error);}}}({drawPositionToAdvance:e,inContextDrawMatchUps:t,sourceDrawPositions:r,tournamentRecord:n,drawDefinition:i,winnerMatchUp:y,matchUpsMap:o,event:c}),U&&g&&U.structureId!==l?.structureId){const{roundNumber:e}=U;if(1===e){const e=sf({structureId:I.target.structureId,drawPosition:S,tournamentRecord:n,drawDefinition:i,event:c});if(e.error)return e}else pf({loserTargetDrawPosition:S,tournamentRecord:n,loserTargetLink:I,drawDefinition:i,loserMatchUp:U,matchUpsMap:o,event:c})}return{...Ni}}function pf({loserTargetDrawPosition:e,tournamentRecord:t,loserTargetLink:r,drawDefinition:n,loserMatchUp:i,matchUpsMap:a,event:o}){const{roundNumber:s}=i;me({method:"assignFedDrawPositionBye",color:"cyan",loserTargetDrawPosition:e});const c=(a?.mappedMatchUps||{})[i.structureId].matchUps,{initialRoundNumber:u}=X({drawPosition:e,matchUps:c});if(u===s){const i=sf({structureId:r.target.structureId,drawPosition:e,tournamentRecord:t,drawDefinition:n,event:o});if(i.error)return i}}const lf="SINGLES",mf="SINGLES",ff="DOUBLES",hf="DOUBLES",gf="TEAM",If="TEAM",Uf={SINGLES_MATCHUP:lf,SINGLES:mf,DOUBLES_MATCHUP:ff,DOUBLES:hf,TEAM_MATCHUP:gf,TEAM:If};function yf({inContextDrawMatchUps:e,sourceMatchUpStatus:t,tournamentRecord:r,sourceMatchUpId:n,drawDefinition:i,matchUpStatus:o,drawPosition:s,matchUpsMap:c,matchUpId:u,event:p}){const l="assignMatchUpDrawPosition";c||(c=se({drawDefinition:i})),e||(e=ue({inContext:!0,drawDefinition:i,matchUpsMap:c}).matchUps??[]);const m=e.find((e=>e.matchUpId===u)),f=m?.structureId,h=i?.structures?.find((e=>e.structureId===f));if(!h)return{error:ma};const g=c?.drawMatchUps?.find((e=>e.matchUpId===u)),I=g?.drawPositions??[],{positionAdded:U,positionAssigned:y,updatedDrawPositions:S}=ie({drawPosition:s,drawPositions:I}),{positionAssignments:v}=Q({drawDefinition:i,structure:h}),T=v?.filter((e=>S.includes(e.drawPosition))),P=T?.find((({bye:e})=>e)),D=g?.matchUpStatus&&[Km,jm].includes(g.matchUpStatus)&&S.filter(Boolean).length<2;if(o=P&&xm||o||D&&g.matchUpStatus||g?.matchUpStatus&&[qm,Gm].includes(g.matchUpStatus)&&g.matchUpStatus||Qm,g&&U){e=ue({inContext:!0,drawDefinition:i,matchUpsMap:c}).matchUps??[];const a=D&&oe({inContextDrawMatchUps:e,drawPosition:s,matchUpId:u})||void 0;g?.matchUpStatusCodes&&ae({inContextDrawMatchUps:e,sourceMatchUpStatus:t,sourceMatchUpId:n,matchUpsMap:c,matchUp:g}),Object.assign(g,{drawPositions:S,winningSide:a,matchUpStatus:o}),q({tournamentId:r?.tournamentId,eventId:m?.eventId,context:l,drawDefinition:i,matchUp:g})}const w=de({inContextDrawMatchUps:e,inContextMatchUp:m,drawDefinition:i,matchUpId:u}),{targetMatchUps:{winnerMatchUp:b,loserMatchUp:R,loserTargetDrawPosition:N},targetLinks:{loserTargetLink:M}}=w,A=ce({structureId:h.structureId,matchUpsMap:c});if(y&&P){if(b)if([xm,qm,Gm].includes(o)){const t=yf({matchUpId:b.matchUpId,inContextDrawMatchUps:e,tournamentRecord:r,drawDefinition:i,drawPosition:s,matchUpsMap:c});if(t.error)return t}else{const{structureId:e}=b;e!==h.structureId&&console.log("winnerMatchUp in different structure... participant is in different targetDrawPosition")}}else if(b&&m&&!m.feedRound){const{pairedPreviousMatchUpIsDoubleExit:t}=ne({targetMatchUp:g,drawPosition:s,matchUpsMap:c,structure:h});if(t){const t=yf({matchUpId:b.matchUpId,inContextDrawMatchUps:e,tournamentRecord:r,drawDefinition:i,drawPosition:s,matchUpsMap:c});if(t.error)return t}}if(g?.matchUpType===If){const t=e?.find((({matchUpId:e})=>e===g.matchUpId)),n=(t?.sides??[]).reduce(((e,t,r)=>t.drawPosition===s?r:e),void 0),a=v?.find((e=>e.drawPosition===s))?.participantId;a&&void 0!==n&&ee({inContextTargetMatchUp:t,drawPositionSideIndex:n,teamParticipantId:a,tournamentRecord:r,drawDefinition:i,matchUp:g})}if(M?.linkCondition===pl&&2===S.filter(Boolean).length&&!P){if(A.filter((({drawPositions:e,roundNumber:t})=>1===t&&d(e,S))).every((({matchUpStatus:e})=>[Vm,zm].includes(e)))&&R){const{structureId:e}=R,t=sf({drawPosition:N,tournamentRecord:r,drawDefinition:i,structureId:e,matchUpsMap:c,event:p});if(t.error)return t}}return y?{...Ni}:a({result:{error:$i},context:{drawPosition:s},stack:l})}function Sf(e){let{inContextDrawMatchUps:t,participantId:r,drawPosition:n}=e;const{tournamentRecord:i,drawDefinition:a,structureId:o,matchUpsMap:s,event:c}=e,{structure:u}=w({drawDefinition:a,structureId:o}),d=(K({drawDefinition:a,structure:u}).positionAssignments||[]).find((e=>r&&e.participantId===r||n&&e.drawPosition===n));if(d&&r&&!n&&(n=d?.drawPosition),!n)return{error:Ji};r||(r=d?.participantId);const{activeDrawPositions:p}=j({drawDefinition:a,structureId:o});if(p.includes(n))return{error:Qi};t||({matchUps:t}=ue({inContext:!0,drawDefinition:a,matchUpsMap:s}));return vf({inContextDrawMatchUps:t,tournamentRecord:i,drawDefinition:a,structureId:o,drawPosition:n,matchUpsMap:s,event:c}).drawPositionCleared?(G({tournamentId:i?.tournamentId,drawDefinition:a,structure:u,event:c}),{...Ni,participantId:r}):{error:Hi}}function vf({inContextDrawMatchUps:e,tournamentRecord:t,drawDefinition:r,drawPosition:n,matchUpsMap:i,structureId:a,event:o}){const{structure:s}=w({drawDefinition:r,structureId:a});if(!s)return{error:ma};const c=K({drawDefinition:r,structure:s}).positionAssignments||[],u=c.some((e=>{if(e.drawPosition===n)return delete e.participantId,delete e.qualifier,delete e.bye,!0}));if(s.structureType===nl)return B({positionAssignments:c,tournamentRecord:t,drawDefinition:r,matchUpsMap:i,structure:s}),{drawPositionCleared:u,...Ni};const{matchUps:p}=J({drawDefinition:r,matchUpFilters:{isCollectionMatchUp:!1},matchUpsMap:i,structure:s,event:o}),{roundProfile:l,roundMatchUps:m}=le({matchUps:p}),f=l&&Object.keys(l),h=f?.map((e=>ve(e)));let g=n;const I=h?.map((e=>{const t=l?.[e],r=t?.pairedDrawPositions?.find((e=>e.includes(g))),n=r?.find((e=>e!==g)),i=c.find((e=>e.drawPosition===n)),a=l?.[e+1],o=i?.bye,s=a?.pairedDrawPositions?.find((e=>e.includes(n))),u=o&&s&&a&&a.drawPositions?.includes(n),d=r&&{pairedDrawPositionByeAdvancedPair:!u&&s,pairedDrawPosition:n,targetDrawPosition:g,relevantPair:r,roundNumber:e};return u&&(g=n),d})).filter((e=>e?.targetDrawPosition)),U=I?.reduce(((e,t)=>{const{roundNumber:r,relevantPair:n,targetDrawPosition:i,pairedDrawPosition:a,pairedDrawPositionByeAdvancedPair:o}=t,s=[{roundNumber:r,targetDrawPosition:i,relevantPair:n},o&&{roundNumber:r+1,targetDrawPosition:a,relevantPair:o,subsequentRoundRemoval:!0}].filter(Boolean);return e.concat(...s)}),[]);return U?.forEach((({roundNumber:u,targetDrawPosition:p,relevantPair:l})=>{const f=m?.[u].find((e=>d(e.drawPositions?.filter(Boolean),l.filter(Boolean))));f&&(!function({inContextDrawMatchUps:e,targetDrawPosition:t,tournamentRecord:r,drawDefinition:n,matchUpsMap:i,roundNumber:a,structureId:o}){const{structure:s}=w({drawDefinition:n,structureId:o});if(!s)return{error:ma};if(s.structureType===nl)return;i=i||se({drawDefinition:n});const c=i?.mappedMatchUps||{},u=c[o].matchUps,{initialRoundNumber:d}=X({drawPosition:t,matchUps:u}),p=u?.filter((e=>e.roundNumber>=a&&e.roundNumber!==d&&e.drawPositions?.includes(t))),l=Q({drawDefinition:n,structureId:o}).positionAssignments??[];p?.forEach((a=>Tf({drawPosition:t,targetMatchUp:a,inContextDrawMatchUps:e,positionAssignments:l,tournamentRecord:r,drawDefinition:n,matchUpsMap:i,structure:s})))}({inContextDrawMatchUps:e,targetDrawPosition:p,tournamentRecord:t,drawDefinition:r,structureId:a,roundNumber:u,matchUpsMap:i}),Tf({inContextDrawMatchUps:e,positionAssignments:c,tournamentRecord:t,drawDefinition:r,targetMatchUp:f,drawPosition:n,matchUpsMap:i,structure:s,event:o}))})),{tasks:U,drawPositionCleared:u,positionAssignments:c}}function Tf({inContextDrawMatchUps:e,positionAssignments:t,tournamentRecord:r,drawDefinition:n,targetMatchUp:i,drawPosition:o,matchUpsMap:s,structure:c,event:u}){const d="removeDrawPosition",p=i.drawPositions?.slice(),l=i.matchUpStatus,m=i.winningSide,f=(s=s??se({drawDefinition:n})).mappedMatchUps[c.structureId].matchUps,{initialRoundNumber:h}=X({drawPosition:o,matchUps:f});if(i.roundNumber&&h&&i.roundNumber>h){const e=(i.drawPositions??[]).map((e=>e===o?void 0:e));i.drawPositions=e}if(i.matchUpType===If){const t=e?.find((e=>e.matchUpId===i.matchUpId)),a=(t?.sides??[]).reduce(((e,t,r)=>t.drawPosition===o?r:e),void 0);void 0!==a&&i.sides?.[a]?.lineUp&&(delete i.sides?.[a].lineUp,q({tournamentId:r?.tournamentId,context:`${d}-TEAM`,eventId:u?.eventId,matchUp:i,drawDefinition:n}))}const g=de({matchUpId:i.matchUpId,inContextDrawMatchUps:e,drawDefinition:n}),{targetLinks:{winnerTargetLink:I},targetMatchUps:{loserMatchUp:U,winnerMatchUp:y,loserMatchUpDrawPositionIndex:S}}=g,v=t.filter((({drawPosition:e})=>i.drawPositions?.includes(e))).filter((e=>e.bye)).length,T=v&&xm||i.matchUpStatus&&[jm,Km].includes(i.matchUpStatus)&&i.matcHUpStatus||2===i.drawPositions?.length&&Qm||void 0;i.matchUpStatus=T,i.matchUpStatus&&[Km,jm].includes(i.matchUpStatus)&&(i.winningSide=void 0);const P=p?.find((e=>!i.drawPositions?.includes(e)));if(p?.includes(o)&&l===i.matchUpStatus&&m===i.winningSide||(P&&me({method:d,color:"brightyellow",removedDrawPosition:P}),q({tournamentId:r?.tournamentId,eventId:u?.eventId,matchUp:i,context:`${d}-${o}`,drawDefinition:n})),U&&U.structureId!==g.matchUp.structureId&&!v){const{drawPositions:t,roundNumber:i}=U;if(1===i){const i=t[S];vf({structureId:U.structureId,drawPosition:i,inContextDrawMatchUps:e,tournamentRecord:r,drawDefinition:n,matchUpsMap:s})}else{const i=Math.min(...t.filter(Boolean)),o=function({loserMatchUpDrawPosition:e,inContextDrawMatchUps:t,tournamentRecord:r,drawDefinition:n,loserMatchUp:i,matchUpsMap:a,event:o}){const{structure:s}=w({structureId:i.structureId,drawDefinition:n}),{positionAssignments:c}=Q({structure:s}),u=c?.find((t=>t.drawPosition===e));if(u?.bye){const s=Sf({drawPosition:e,structureId:i.structureId,inContextDrawMatchUps:t,tournamentRecord:r,drawDefinition:n,matchUpsMap:a,event:o});if(s.error)return s}return{...Ni}}({loserMatchUpDrawPosition:i,inContextDrawMatchUps:e,tournamentRecord:r,drawDefinition:n,loserMatchUp:U,matchUpsMap:s,event:u});if(o.error)return a({result:o,stack:d});const c=(s?.mappedMatchUps||{})[U.structureId].matchUps,{initialRoundNumber:p}=X({drawPosition:i,matchUps:c});1===p&&(me({method:d,color:"brightyellow",loserMatchUpDrawPosition:i}),vf({structureId:U.structureId,drawPosition:i,inContextDrawMatchUps:e,tournamentRecord:r,drawDefinition:n,matchUpsMap:s}))}}return y&&y.structureId!==g.matchUp.structureId&&I.target.feedProfile,{...Ni}}function Pf({provisionalPositioning:e,inContextDrawMatchUps:t,isQualifierPosition:r,sourceMatchUpStatus:n,tournamentRecord:i,drawDefinition:o,seedingProfile:s,participantId:c,seedBlockInfo:u,drawPosition:d,matchUpsMap:p,structureId:l,event:m}){const f="assignDrawPosition";if(!c&&!r)return a({result:{error:Do},stack:f});p=p??se({drawDefinition:o}),t||({matchUps:t}=ue({inContext:!0,drawDefinition:o,matchUpsMap:p}));const h=w({drawDefinition:o,structureId:l});if(h.error)return a({result:h,stack:f});const{structure:g}=h;if(!g)return{error:ma};if(Se({drawDefinition:o,structure:g}))return a({result:{error:ja},stack:f});const{seedAssignments:I}=Y({provisionalPositioning:e,drawDefinition:o,structure:g}),U=I?.find((e=>e.participantId===c)),y=U?.seedNumber,{appliedPolicies:S}=te({tournamentRecord:i,drawDefinition:o,structure:g,event:m});if(y){if(!ge({seedNumber:y,appliedPolicies:S,drawDefinition:o,seedBlockInfo:u,drawPosition:d,structureId:l}))return a({result:{error:qi},context:{drawPosition:d},stack:f})}const T=K({structure:g}).positionAssignments||[],P=T?.find((e=>e.drawPosition===d));if(!P)return a({result:{error:Ki},context:{drawPosition:d},stack:f});const D=T?.map(v).includes(c);if(D)return a({result:{error:Co},context:{drawPosition:d},stack:f});const{containsParticipant:b,containsBye:R}=function(e){const t=e.bye,r=e.qualifier,n=e.participantId;return{containsBye:t,containsQualifier:r,containsParticipant:n,filled:t||r||n}}(P);if(R){const e=Sf({inContextDrawMatchUps:t,tournamentRecord:i,drawDefinition:o,drawPosition:d,structureId:l,matchUpsMap:p,event:m});if(e.error)return a({result:e,stack:f})}if(b&&P.participantId!==c){const{activeDrawPositions:e}=j({drawDefinition:o,structureId:l});if(e.includes(d))return a({result:{error:Qi},stack:f});ye({assignments:[P],inContextDrawMatchUps:t,tournamentRecord:i,drawDefinition:o,matchUpsMap:p,structure:g})}if(P.participantId=c,r&&(P.qualifier=!0),(g?.stageSequence||0)>1||g.stage&&[Wp,zp].includes(g.stage)){const t=g.stage===$p?$p:qp,r=o.structures?.find((e=>e?.stage===t&&1===e?.stageSequence)),n=(r?.seedAssignments??[]).find((e=>e.participantId===c));if(n?.participantId){const{participantId:t,seedNumber:r,seedValue:a}=n;Z({eventId:m?.eventId,provisionalPositioning:e,tournamentRecord:i,drawDefinition:o,seedingProfile:s,participantId:t,seedNumber:r,seedValue:a,structureId:l,event:m})}}if(g.structureType!==nl)!function({provisionalPositioning:e,inContextDrawMatchUps:t,sourceMatchUpStatus:r,tournamentRecord:n,drawDefinition:i,drawPosition:o,matchUpsMap:s,structure:c,event:u}){const d={isCollectionMatchUp:!1},{matchUps:p}=J({provisionalPositioning:e,matchUpFilters:d,drawDefinition:i,matchUpsMap:s,structure:c,event:u}),{roundMatchUps:l}=le({matchUps:p}),{initialRoundNumber:m}=X({drawPosition:o,matchUps:p}),f=m&&l?.[m].find((e=>e.drawPositions?.includes(o)));if(f){const e=yf({matchUpId:f.matchUpId,inContextDrawMatchUps:t,sourceMatchUpStatus:r,tournamentRecord:n,drawDefinition:i,drawPosition:o,matchUpsMap:s});if(e.error)return a({stack:"assignDrawPositionToMatchUps",context:{drawPosition:o},result:e})}}({provisionalPositioning:e,inContextDrawMatchUps:t,sourceMatchUpStatus:n,tournamentRecord:i,drawDefinition:o,drawPosition:d,matchUpsMap:p,structure:g,event:m});else{B({positionAssignments:T,tournamentRecord:i,drawDefinition:o,matchUpsMap:p,structure:g});const{drawPositions:e,matchUps:r,targetMatchUps:n}=he({assignments:[P],inContextDrawMatchUps:t,drawDefinition:o,matchUpsMap:p,structure:g});if(e&&1===r?.length&&r[0].matchUpType===If){const t=(n?.[0].sides??[]).reduce(((t,r,n)=>e?.includes(r.drawPosition)?n:t),void 0);ee({inContextTargetMatchUp:n[0],teamParticipantId:c,matchUp:r[0],drawPositionSideIndex:t,tournamentRecord:i,drawDefinition:o})}}return G({tournamentId:i?.tournamentId,drawDefinition:o,structure:g,event:m}),{positionAssignments:T,...Ni}}function Df(e){const{participantIdAttributeName:t="participantId",isQualifierPosition:r,positionActionName:n,tournamentRecord:i,drawDefinition:a,participantId:o,drawPosition:s,structureId:c,event:u}=e,d="positionParticipantAction";if(!a)return{error:Li};let{inContextDrawMatchUps:p,matchUpsMap:l}=e;l||(l=Mm({drawDefinition:a}),Object.assign(e,{matchUpsMap:l})),p||(({matchUps:p}=Em({inContext:!0,drawDefinition:a,matchUpsMap:l})),Object.assign(e,{inContextDrawMatchUps:p}));const{positionAssignments:m}=op({drawDefinition:a,structureId:c}),f=m?.find((e=>e.drawPosition===s));if(f?.participantId){const e=f.participantId,t=Pf({inContextDrawMatchUps:p,tournamentRecord:i,drawDefinition:a,participantId:o,drawPosition:s,structureId:c,matchUpsMap:l,event:u});return t.success?U({removedParticipantId:e}):pd({result:t,stack:d})}const h=Sf({inContextDrawMatchUps:p,tournamentRecord:i,drawDefinition:a,drawPosition:s,structureId:c,matchUpsMap:l,event:u});if(h.error)return pd({result:h,stack:d});const g=h.participantId,I=Pf({inContextDrawMatchUps:p,isQualifierPosition:r,tournamentRecord:i,drawDefinition:a,participantId:o,drawPosition:s,structureId:c,matchUpsMap:l,event:u});return I.success?U({removedParticipantId:g}):pd({result:I,stack:d});function U({removedParticipantId:e}){const{structure:r}=Om({drawDefinition:a,structureId:c});ql({drawPositions:[s],structure:r});return Hl({drawDefinition:a,positionAction:{[t]:o,name:n,drawPosition:s,structureId:c}}),pd({context:{removedParticipantId:e},result:{...Ni},stack:d})}}function wf(e){return function({luckyLoserParticipantId:e,tournamentRecord:t,drawDefinition:r,drawPosition:n,structureId:i}){return Df({positionActionName:"luckyLoserDrawPositionAssignment",participantId:e,tournamentRecord:t,drawDefinition:r,drawPosition:n,structureId:i})}(e)}function bf(e){return function({alternateParticipantId:e,tournamentRecord:t,drawDefinition:r,drawPosition:n,structureId:i}){return Df({positionActionName:"alternateDrawPositionAssignment",participantIdAttributeName:"alternateParticipantid",participantId:e,tournamentRecord:t,drawDefinition:r,drawPosition:n,structureId:i})}(e)}function Rf({structurePositionAssignments:e,provisionalPositioning:t,tournamentRecord:r,drawDefinition:n,event:i}){if(!n)return{error:Li};if(!Array.isArray(e))return{error:ys};for(const a of e){const{structureId:e,positionAssignments:o}=a;if(!o)continue;const s=Om({drawDefinition:n,structureId:e});if(s.error)return s;const c=s.structure;if(!c)return{error:ma};const u=op({structure:c}).positionAssignments?.map((({drawPosition:e})=>e)),d=o?.map((({drawPosition:e})=>e));if(Jd(u,d).length!==u?.length)return pd({result:{error:ys},info:"drawPositions do not match",stack:"setPositionAssignments"});const p=Mm({drawDefinition:n}),{matchUps:l}=Em({inContext:!0,drawDefinition:n,matchUpsMap:p});for(const a of o||[]){const{drawPosition:s,participantId:u,bye:d,qualifier:m}=a;if(d){const t=sf({tournamentRecord:r,drawDefinition:n,drawPosition:s,matchUpsMap:p,structureId:e,structure:c,event:i});if(t?.error)return t}else if(m)o.forEach((e=>{e.drawPosition===s&&(e.qualifier=!0,delete e.participantId,delete e.bye)}));else if(u){const a=Pf({provisionalPositioning:t,inContextDrawMatchUps:l,tournamentRecord:r,drawDefinition:n,participantId:u,drawPosition:s,matchUpsMap:p,structureId:e,event:i});if(a?.error)return a}}Gp({tournamentId:r?.tournamentId,drawDefinition:n,structure:c,event:i})}const a=e.map((({structureId:e})=>e));return jp({tournamentId:r?.tournamentId,eventId:i?.eventId,drawDefinition:n,structureIds:a}),{...Ni}}function Nf(e){return function({qualifyingParticipantId:e,tournamentRecord:t,drawDefinition:r,drawPosition:n,structureId:i}){return Df({positionActionName:"qualifierDrawPositionAssignment",participantId:e,isQualifierPosition:!0,tournamentRecord:t,drawDefinition:r,drawPosition:n,structureId:i})}(e)}function Mf(e,t,r,n){if("object"!=typeof e||null===e)return e;const i=ec();i?.enabled||(n=!0);const a=["",void 0,null];t&&a.push(!1);const o=function(e,t,r){return Object.keys(e).filter((n=>!t.includes(e[n])&&(!r||!Array.isArray(e[n])||e[n].length)))}(e,a,r);return Object.assign({},...o.map((t=>Array.isArray(e[t])?{[t]:n?e[t]:e[t].map((e=>Mf(e)))}:{[t]:n?e[t]:Mf(e[t])})))}function Af(e){if(!ru(e))return!1;const{matchUpId:t,drawPositions:r}=e,n="string"==typeof t,i=!r||Array.isArray(r)&&r.length<=2&&r.every((e=>Vd(e)||null==e));return n&&i}function Ef(e){return!!Array.isArray(e)&&e.every(Af)}function Cf({matchUps:e=[],interpolate:t}){if(!Ef(e))return{roundMatchUps:[],error:ys};const r=e.reduce(((e,t)=>{const r="string"==typeof t.roundNumber?Ed(t.roundNumber):t.roundNumber;return!t.roundNumber||e.includes(r)?e:e.concat(r)}),[]).sort(Ad).map((t=>{const r=e.filter((e=>e.roundNumber===t)),n=r.find((({matchUpType:e})=>e===If))?r.filter((({matchUpType:e})=>e===If)):r;return{[t]:(i=n,i.sort(((e,t)=>Ad(e.roundPosition,t.roundPosition))))};var i})),n=e.reduce(((e,t)=>{const r="string"==typeof t.roundNumber?Ed(t.roundNumber):t.roundNumber;return e[r]||(e[r]=Mf({abbreviatedRoundName:t.abbreviatedRoundName,finishingRound:t.finishingRound,roundName:t.roundName})),e}),{}),i=Object.assign({},...r);if(t){const e=Math.max(...Object.keys(i).map((e=>Ed(e))).filter((e=>!isNaN(e)))),t=i[e]?.length;if(t>1&&Cd(t)){const r=e+1;Qd(r,r+t/2).forEach(((e,r)=>{i[e]=Qd(0,t/(2+2*r)).map((()=>({})))}))}}let a=0;const o=Object.assign({},...Object.keys(i).map((e=>{const t=i[e]?.length,r=i[e]?.filter((e=>!rf.includes(e.matchUpStatus)&&!e.score?.scoreStringSide1))?.length,n=t&&t===r;return a=Math.max(a,t),{[e]:{matchUpsCount:t,inactiveCount:r,inactiveRound:n}}})));let s=0,c=0;const u=Object.keys(i).map((e=>Ed(e))).filter((e=>!isNaN(e)));u.forEach((e=>{const t=i[e].sort(((e,t)=>e.roundPosition-t.roundPosition)),r=t.map((e=>e?.drawPositions||[])).flat();if(o[e].roundNumber=e,o[e].roundFactor=o[e].matchUpsCount?a/o[e].matchUpsCount:1,o[e].finishingRound=n[e]?.finishingRound,o[e].roundName=n[e]?.roundName,o[e].abbreviatedRoundName=n[e]?.abbreviatedRoundName,o[e].finishingPositionRange=i[e]?.[0]?.finishingPositionRange,1!==e&&o[e-1]){const r=o[e-1],n=r.drawPositions,i=r.matchUpsCount/o[e].matchUpsCount,a=ep(n,i),s=t.map((t=>{const{roundPosition:r}=t,i=[...t.drawPositions||[],void 0,void 0].slice(0,2);if(!r)return i;const o=i?.filter(Boolean)||[];if(!o?.length)return[void 0,void 0];if(e<3&&2===o?.length)return i?.slice().sort(Ad);const s=Jd(n,o).length!==o?.length;if(o?.length&&s)return 1===o?.length?[o[0],void 0]:i?.slice().sort(Ad);const c=2*(r-1);return a.slice(c,c+2).map((e=>o?.find((t=>e.includes(t)))))}));o[e].drawPositions=s?.flat(),o[e].pairedDrawPositions=s}else{const t=r.sort(Ad),n=ep(t,2);o[e].drawPositions=t,o[e].pairedDrawPositions=n}o[e+1]&&o[e+1].matchUpsCount===o[e].matchUpsCount&&(o[e+1].feedRound=!0,o[e+1].feedRoundIndex=c,o[e].preFeedRound=!0,c+=1),o[e]&&!o[e].feedRound&&(o[e].roundIndex=s,s+=1)}));const d=!!Object.values(o).find((({matchUpsCount:e})=>!Cd(e)));return{hasNoRoundPositions:e.some((e=>!e.roundPosition)),roundsNotPowerOf2:d,maxMatchUpsCount:a,roundMatchUps:i,roundNumbers:u,roundProfile:o,...Ni}}function Of(e){if(!Array.isArray(e))return"";const t=e.filter(kd);if(!t.length)return"";return jd([Math.min(...t),Math.max(...t)]).join("-")}function Ff({drawDefinition:e,structureId:t,matchUpsMap:r}){if(!e)return{error:Li};if(!t)return{error:la};const{structure:n}=Om({drawDefinition:e,structureId:t});if(n?.stage!==Wp)return{error:wa,info:"Structure is not CONSOLATION stage"};const{links:i}=e,a=i?.filter((e=>e.target.structureId===t))||[],o=a?.reduce(((e,t)=>{const{structureId:r}=t.source;return e.includes(r)?e:e.concat(r)}),[])||[],s=Object.assign({},...o.map((e=>({[e]:Cf({matchUps:Am({structureId:e,matchUpsMap:r})}).roundProfile})))),c=Am({matchUpsMap:r,structureId:t}),{roundProfile:u}=Cf({matchUps:c}),d={};return a?.forEach((e=>{const{structureId:t,roundNumber:r}=e.source,{feedProfile:n,groupedOrder:i,positionInterleave:a,roundNumber:o}=e.target,c=s[t],p=c[1]?.drawPositions,l=c[r],m=l?.matchUpsCount;if(!m)return;const f=m?p.length/m:0,h=p.length/f;let g=p.slice();const I=function({groupedOrder:e,roundPositionsCount:t}){if(!e||e?.length<=t)return e;const r=ep(e,e.length/t).map((e=>e.reduce(((e,t)=>e+t)))),n=r.slice().sort(Ad);return r.map((e=>n.indexOf(e)+1))}({roundPositionsCount:g.length,groupedOrder:i}),U=I?.length||1;if(U<=h){const e=ep(g,p.length/U);n===sl&&e.forEach((e=>e.reverse())),g=I?.length&&I?.map((t=>e[t-1])).flat()||g}let y=ep(g,f);if(I?.length||n!==sl||y.reverse(),a){const e=Qd(0,a.interleave).map((()=>{})),t=Qd(0,a.offset).map((()=>{}));y=y.map((t=>[t,...e])),y.unshift(t),y=y.flat(1);const r=y.length-a.offset;y=y.slice(0,r)}d[o]||(d[o]={});const S=u?.[o],v=S?.feedRound?2:1;y.forEach(((e,t)=>{const r=1+t*v;d[o][r]||(d[o][r]=Of(e))}))})),{sourceDrawPositionRanges:d}}const kf={[ed]:{policyName:"Round Naming Default",namingConventions:{round:"Round",pre:"Pre"},qualifyingFinishMap:{1:"Final"},abbreviatedRoundNamingMap:{1:"F",2:"SF",4:"QF"},roundNamingMap:{1:"Final",2:"Semifinal",4:"Quarterfinal"},affixes:{roundNumber:"R",preFeedRound:"Q",preQualifying:"P"},stageConstants:{[qp]:"",[zp]:"P",[$p]:"Q",[Wp]:"C"}}};function _f({drawPositionCollectionAssignment:e,sideNumberCollectionAssignment:t,positionAssignments:r,displaySideNumber:n,seedAssignments:i,drawPosition:a,isFeedRound:o,sideNumber:s}){const c=r.find((e=>e.drawPosition&&e.drawPosition===a)),u=a&&e,d=s&&t,p=u?u[a]?.participantId:c?.participantId,l=c?function({displaySideNumber:e,seedAssignments:t,participantId:r,assignment:n,sideNumber:i}){const a={drawPosition:n.drawPosition,displaySideNumber:e,sideNumber:i};if(r){const e=function({seedAssignments:e,participantId:t}){return e?.find((e=>!e.seedProxy&&e.participantId===t))}({seedAssignments:t,participantId:r});Object.assign(a,e,{participantId:r})}else n.bye&&Object.assign(a,{bye:!0});n.qualifier&&Object.assign(a,{qualifier:!0});return a}({displaySideNumber:n,seedAssignments:i,participantId:p,assignment:c,sideNumber:s}):{...d?.[s]};if(o&&(1===s?Object.assign(l,{participantFed:!0}):Object.assign(l,{participantAdvanced:!0})),a&&u){const e=u[a]?.teamParticipant,t=u[a]?.participant,r=u[a]?.substitutions;t&&(l.participant=t),r&&(l.substitutions=r),e&&(l.teamParticipant=e)}return l}const xf="ANY",Lf="MALE",Vf="MIXED",Bf="OTHER",jf="FEMALE",Gf={ANY:xf,MALE:Lf,FEMALE:jf,MIXED:Vf,OTHER:Bf},qf="SINGLES",$f="SINGLES",Wf="DOUBLES",Hf="DOUBLES",zf="TEAM",Yf="TEAM",Qf={AGE:"AGE",BOTH:"BOTH",DOUBLES:Wf,DOUBLES_EVENT:Hf,RATING:"RATING",SINGLES:qf,SINGLES_EVENT:$f,TEAM_EVENT:Yf,TEAM:zf};function Kf({scheduleVisibilityFilters:e,tournamentAppliedPolicies:t,provisionalPositioning:r,tournamentParticipants:n,afterRecoveryTimes:i,policyDefinitions:a,tournamentRecord:o,seedAssignments:s,usePublishState:c,contextFilters:d,contextContent:f,matchUpFilters:h,participantMap:g,scheduleTiming:I,contextProfile:U,drawDefinition:y,publishStatus:v,context:T={},exitProfiles:P,matchUpsMap:D,structure:w,inContext:b,event:R}){let N={},M={};if(n=n??o?.participants,!w)return{collectionPositionMatchUps:N,error:ha,roundMatchUps:M,matchUps:[]};const A=Array.isArray(h?.eventIds)?h?.eventIds.filter(Boolean):[],E=Array.isArray(h?.structureIds)?h?.structureIds.filter(Boolean):[],C=Array.isArray(h?.drawIds)?h?.drawIds.filter(Boolean):[],O=!T?.eventId||!A?.length&&!d?.eventIds?.filter(Boolean).length||A?.includes(T.eventId)||d?.eventIds?.includes(T.eventId),F=!E?.length||E.includes(w.structureId),V=!y||!C?.length||C.includes(y.drawId);if(!O||!F||!V)return{collectionPositionMatchUps:N,roundMatchUps:M,matchUps:[]};U&&!f&&(f=k({tournamentRecord:o,contextProfile:U,drawDefinition:y}));const{appliedPolicies:B}=te({drawDefinition:y}),j={...t,...B,...a},G=j?.scoring?.structures,q=w.stage&&G?.stage&&G?.stage[w.stage],$=w.stageSequence&&q?.stageSequence&&q.stageSequence[w.stageSequence],W=j?.scoring?.requireAllPositionsAssigned||q?.requireAllPositionsAssigned||$?.requireAllPositionsAssigned;D||(D=Mm({drawDefinition:y,structure:w}));const{positionAssignments:H,allPositionsAssigned:z}=K({structure:w}),Q=!W||z,{seedAssignments:J}=Y({provisionalPositioning:r,drawDefinition:y,structure:w});s=s??J;const{roundOffset:Z,structureId:X,structureName:ee,stage:re,stageSequence:ne}=w,{drawId:ie,drawName:ae,drawType:oe}=y??{};P=P||y&&_({drawDefinition:y}).exitProfiles;const se=P?.[X],ce=se?.length&&(se[0].split("-").map((e=>parseInt(e))).reduce(((e,t)=>e+t))||0),ue=!!w.structures;let de=Am({matchUpsMap:D,structureId:X,inContext:b});const pe=j?.[ed],le=function({roundNamingPolicy:e,drawDefinition:t,structure:r,matchUps:n}){const{roundProfile:i,roundMatchUps:a}=Cf({matchUps:n}),{structureAbbreviation:o,stage:s}=r,c=Se({structure:r}),u=Ae({structure:r}),d=r.structures,p={},l=kf[ed],m=r.stage===$p,f=m?Math.max(...(t?.structures??[]).filter((e=>e.stage===$p)).map((({stageSequence:e})=>e??1)),0):0,h=(r.stageSequence??1)<f?r.stageSequence??1:"",g=h&&(e?.affixes?.preQualifying||l.affixes.preQualifying)||"",I=e?.roundNamingMap||l.roundNamingMap||{},U=e?.abbreviatedRoundNamingMap||l.abbreviatedRoundNamingMap||{},y=e?.affixes?.preFeedRound||l.affixes.preFeedRound,S=e?.affixes?.roundNumber||l.affixes.roundNumber,v=(e?.namingConventions||l.namingConventions).round,T=s&&s!==qp?s[0]:"",P=e?.stageConstants||l.stageConstants,D=`${g}${s&&P?.[s]||T}${h}`,w=i?Object.keys(i):[],b=m&&P?.[$p]?`${P?.[$p]}-`:"";if(d||c||u)Object.assign(p,...w.map((e=>({[e]:{roundName:`${b}${v} ${e}`,abbreviatedRoundName:`${S}${e}`}}))));else{const t=m&&(e?.qualifyingFinishMap||l?.qualifyingFinishMap||{});Object.assign(p,...w.map((e=>{if(!i?.[e])return;const{matchUpsCount:r,preFeedRound:n}=i[e],a=2*r,s=t?.[i?.[e].finishingRound]||t&&`${S}${a}`||I[r]||`${S}${a}`,c=n?`-${y}`:"",u=[D,o,`${s}${c}`].filter(Boolean).join("-"),d=U[r]||`${S}${a}`;return{[e]:{abbreviatedRoundName:[D,o,`${d}${c}`].filter(Boolean).join("-"),roundName:u}}})))}return{roundNamingProfile:p,roundProfile:i,roundMatchUps:a}}({roundNamingPolicy:pe,drawDefinition:y,structure:w,matchUps:de}),{roundNamingProfile:me,roundProfile:he}=le;if(M=le?.roundMatchUps??[],h&&(de=x({matchUps:de,...h,filterMatchUpTypes:!1,filterMatchUpIds:!1})),b){const{sourceDrawPositionRanges:t}=Ff({drawDefinition:y,matchUpsMap:D,structureId:X}),r=y?function({drawDefinition:e,roundProfile:t,structureId:r,matchUpsMap:n}){if(!e)return{error:Li};if(!r)return{error:la};if(!t){const e=Am({matchUpsMap:n,structureId:r});if(({roundProfile:t}=Cf({matchUps:e})),!t)return{error:Za}}const i=(Math.min(...t?.[1]?.drawPositions??[])||1)-1,a=Object.keys(t),o=Object.assign({},...(a||[]).map((e=>{const r=t?.[e]?.matchUpsCount,n=t?.[1]?.drawPositions??[],o=p(n,n.length/r),s=o.map(Of),c=o.map((e=>e.map((e=>e-i)))).map(Of),d=a.map((n=>{if(n>e)return;const i=t?.[n]?.drawPositions??[];return p(i,i.length/r)})).filter(Boolean),f=l(0,r).map((e=>d.map((t=>t[e])).flat().filter(Boolean).sort(fe))).map((e=>u(e))),h=f.map((e=>m(e).map(Of).join(", "))),g=Object.assign({},...l(0,r).map((e=>({[e+1]:{firstRoundDrawPositionsRange:s[e],firstRoundOffsetDrawPositionsRange:c[e],possibleDrawPositions:f[e],drawPositionsRange:h[e]}}))));return{[e]:g}})));return{drawPositionsRanges:o}}({drawDefinition:y,roundProfile:he,matchUpsMap:D,structureId:X}).drawPositionsRanges:void 0;de=de.map((n=>ge({scheduleVisibilityFilters:e,sourceDrawPositionRanges:t,drawPositionsRanges:r,roundNamingProfile:me,initialRoundOfPlay:ce,appliedPolicies:j,usePublishState:c,publishStatus:v,isRoundRobin:ue,roundProfile:he,matchUp:n,event:R})));const n=de?.filter((e=>Array.isArray(e.tieMatchUps)));n.forEach((e=>{const t=e.tieMatchUps;de=de.concat(...t)})),d&&(de=x({processContext:!0,...d,matchUps:de}))}else{const e=de?.filter((e=>Array.isArray(e.tieMatchUps)));e.forEach((e=>{const t=e.tieMatchUps;de=de.concat(...t)}))}return h&&(de=x({matchUps:de,...h,filterMatchUpTypes:!1,filterMatchUpIds:!1})),(h?.matchUpTypes||h?.matchUpIds)&&(de=x({matchUpTypes:h.matchUpTypes,matchUpIds:h.matchUpIds,matchUps:de})),(h?.matchUpTypes||h?.matchUpIds||b)&&(M=Cf({matchUps:de}).roundMatchUps??[]),we({drawDefinition:y,structure:w,event:R})?.tieFormat&&({collectionPositionMatchUps:N}=function({matchUps:e}){const t=e.reduce(((e,t)=>!t.collectionPosition||e.includes(t.collectionPosition)?e:e.concat(t.collectionPosition)),[]).map((t=>({[t]:e.filter((e=>e.collectionPosition===t))})));return{collectionPositionMatchUps:Object.assign({},...t)}}({matchUps:de})),{collectionPositionMatchUps:N,roundMatchUps:M,roundProfile:he,matchUpsMap:D,matchUps:de};function ge({scheduleVisibilityFilters:e,sourceDrawPositionRanges:t,drawPositionsRanges:r,initialRoundOfPlay:a,additionalContext:c,roundNamingProfile:d,tieDrawPositions:p,appliedPolicies:l,isCollectionBye:m,usePublishState:h,publishStatus:v,matchUpTieId:P,isRoundRobin:D,roundProfile:b,sideLineUps:R,matchUp:N,event:M}){c=c??{};const A=we({drawDefinition:y,structure:w,matchUp:N,event:M})?.tieFormat,E=A?.collectionDefinitions,C=N.collectionId&&E?.find((e=>e.collectionId===N.collectionId)),O=N.collectionId?C?.matchUpFormat:N.matchUpFormat??w?.matchUpFormat??y?.matchUpFormat??M?.matchUpFormat,F=N.matchUpType||C?.matchUpType||w?.matchUpType||y?.matchUpType||M?.eventType!==zf&&M?.eventType,k=m?xm:N.matchUpStatus,{schedule:_,endDate:x}=De({scheduleVisibilityFilters:e,afterRecoveryTimes:i,tournamentRecord:o,usePublishState:h,scheduleTiming:I,matchUpFormat:O,publishStatus:v,matchUpType:F,matchUp:N,event:M}),V=p??N.drawPositions??[],{collectionPosition:B,collectionId:j,roundPosition:G}=N,q=N.roundNumber??c.roundNumber,$=j?function({tournamentParticipants:e,positionAssignments:t,collectionPosition:r,drawPositions:n=[],participantMap:i,drawDefinition:a,collectionId:o,sideLineUps:s,matchUpType:c}){if(!o||!r)return{};const u=({attribute:t,lineUp:n,teamParticipant:a})=>{const{assignedParticipantIds:s,substitutions:u}=Re({collectionPosition:r,collectionId:o,lineUp:n});if(c!==hf){const e=s?.[0];return e&&{[t]:{participantId:e,teamParticipant:a,substitutions:u}}}if(s?.length<=2){const r=i?.[s[0]]?.pairIdMap?.[s[1]],n=r&&i[r]?.participant||Ne({participantIds:s,tournamentParticipants:e}).participant,o=n?.participantId;return{[t]:{participantId:o,teamParticipant:a,substitutions:u}}}if(s?.length>2)return{[t]:{teamParticipant:a,substitutions:u}}};if(!n?.length){const e=s?.map((e=>{const{teamParticipant:t,sideNumber:r}=e,n=e.lineUp||Me({participantId:t.teamParticipantId,drawDefinition:a})?.lineUp;return u({attribute:r,lineUp:n,teamParticipant:t})})).filter(Boolean)||{};return{sideNumberCollectionAssignment:Object.assign({},...e)}}const d=n?.map((r=>{const n=t.find((e=>e.drawPosition===r))?.participantId,o=s?.find((e=>e?.drawPosition===r)),c=o?.teamParticipant||n&&i?.[n]?.participant||e?.find((({participantId:e})=>e===n)),d=o?.lineUp||Me({participantId:n,drawDefinition:a})?.lineUp;return u({attribute:r,lineUp:d,teamParticipant:c})})).filter(Boolean)||{};return{drawPositionCollectionAssignment:Object.assign({},...d)}}({tournamentParticipants:n,positionAssignments:H,collectionPosition:B,drawDefinition:y,participantMap:g,drawPositions:V,collectionId:j,sideLineUps:R,matchUpType:F}):void 0,W=d?.[q]?.roundName||c.roundName,z=d?.[q]?.abbreviatedRoundName||c.abbreviatedRoundName,Y=b?.[q]?.feedRound,K=b?.[q]?.preFeedRound,J=b?.[q]?.roundFactor,te=r?.[q],se=G?te?.[G]:void 0,ce=t?.[q],ue=C?.category?{...T?.category||{},...C.category}:T?.category??M?.category,de=N.processCodes?.length&&N.processCodes||C?.processCodes?.length&&C?.processCodes||w?.processCodes?.length&&w?.processCodes||y?.processCodes?.length&&y?.processCodes||M?.processCodes?.length&&M?.processCodes||o?.processCodes,pe=U?.withCompetitiveness&&Te({...f,matchUp:N}),le=N.finishingPositionRange??c.finishingPositionRange,me=e=>S(e,void 0,!0),fe={...me(T),...me({matchUpFormat:N.matchUpType===zf?void 0:O,tieFormat:N.matchUpType!==zf?void 0:A,gender:C?.gender??M?.gender,roundOfPlay:re!==$p&&Fe(a)&&a+(q||0),endDate:N.endDate??x,discipline:M?.discipline,category:ue,finishingPositionRange:le,abbreviatedRoundName:z,drawPositionsRange:se,competitiveProfile:pe,structureName:ee,stageSequence:ne,drawPositions:V,matchUpStatus:k,processCodes:de,isRoundRobin:D,matchUpTieId:P,preFeedRound:K,matchUpType:F,roundFactor:J,roundOffset:Z,structureId:X,roundNumber:q,feedRound:Y,roundName:W,drawName:ae,drawType:oe,schedule:_,drawId:ie,stage:re}),...L(me(N),!0,!0)};if(O&&N.score?.scoreStringSide1){const e=be(O),{bestOf:t,finalSetFormat:r,setFormat:n}=e??{};(r?.tiebreakSet||n?.tiebreakSet||n?.timed)&&(fe.score.sets=fe.score.sets.sort(((e,t)=>e.setNumber-t.setNumber)).map(((e,i)=>(i+1===t?(r?.tiebreakSet||r?.timed)&&(e.tiebreakSet=!0):(n?.tiebreakSet||n?.timed)&&(e.tiebreakSet=!0),e))))}if(Array.isArray(V)){const{orderedDrawPositions:e,displayOrder:t}=function({drawPositions:e,roundProfile:t,roundNumber:r}){const n=[void 0,void 0];if(rp(e))return{orderedDrawPositions:n,displayOrder:n};const i=t?.[r],a=i?.pairedDrawPositions,o=a?.find((t=>Xd(t||[],e.filter(Boolean))))??n,s=i?.feedRound;if(tp(e)){const t=[...e].sort(Ad);return{orderedDrawPositions:2===t.length?t:o,displayOrder:s?t:o}}if(s){const t=[e.find((e=>!isNaN(Ed(e)))),void 0];return{orderedDrawPositions:t,displayOrder:t}}return{orderedDrawPositions:o,displayOrder:o}}({drawPositions:V,roundProfile:b,roundNumber:q}),r=b?.[q]?.feedRound,n=t[0]!==e[0],i=e.concat(void 0,void 0).slice(0,2).map(((e,t)=>{const i=t+1,a=_f({...$,positionAssignments:H,displaySideNumber:n?3-i:i,seedAssignments:s,drawPosition:e,isFeedRound:r,sideNumber:i}),o=N.sides?.find((e=>e.sideNumber===i)),c=G?2*(G-1)+t+1:void 0;return me({sourceDrawPositionRange:c?ce?.[c]:void 0,...o,...a})}));Object.assign(fe,L({sides:i},!0,!0))}if(n&&fe.sides){const e=l?.[td],t=t=>{const r=g?.[t]?.participant;return r&&Ce({template:e?.participant,source:r})};if(fe.sides.filter(Boolean).forEach((e=>{if(e.participantId){const r=L(t(e.participantId)||n&&Oe({policyDefinitions:l,participantId:e.participantId,tournamentParticipants:n,internalUse:!0,contextProfile:U}),void 0,!0);if(r){if(y?.entries){const t=y.entries.find((t=>t.participantId===e.participantId));t?.entryStatus&&(r.entryStatus=t.entryStatus),t?.entryStage&&(r.entryStage=t.entryStage)}Object.assign(e,{participant:r})}}if(e?.participant?.individualParticipantIds?.length&&!e.participant.individualParticipants?.length){const r=e.participant.individualParticipantIds.map((e=>t(e)||n&&Oe({policyDefinitions:l,tournamentParticipants:n,internalUse:!0,contextProfile:U,participantId:e})));Object.assign(e.participant,{individualParticipants:r})}})),!fe.matchUpType){const{matchUpType:e}=Ee({matchUp:fe});e&&Object.assign(fe,{matchUpType:e})}if(U?.inferGender&&(!fe.gender||fe.gender===Vf)&&2===fe.sides?.length&&fe.matchUpType!==zf){const e=fe.sides.map((e=>{if(fe.matchUpType===mf)return e.participant?.person?.sex;if(2===e.participant?.individualParticipants?.length){const t=u(e.participant.individualParticipants.map((e=>e.person?.sex))).filter(Boolean);if(1===t.length)return t[0]}}));if(2===e.filter(Boolean).length&&1===u(e).length){const t=e[0];fe.inferredGender=t}}}if(fe.tieMatchUps){const n=fe.matchUpStatus===xm,i=fe.sides?.map((({participant:e,drawPosition:t,sideNumber:r,lineUp:n})=>{const i=e?.participantType===zf&&e;return{teamParticipant:i&&S({participantRoleResponsibilities:i.participantRoleResponsibilities,participantOtherName:i.participanOthertName,participantName:i.participantName,participantId:i.participantId,teamId:i.teamId}),drawPosition:t,sideNumber:r,lineUp:n}}));fe.tieMatchUps=fe.tieMatchUps.map((o=>{const s=fe.matchUpId,c=fe.finishingPositionRange;return ge({tieDrawPositions:V,scheduleVisibilityFilters:e,sourceDrawPositionRanges:t,sideLineUps:i,drawPositionsRanges:r,initialRoundOfPlay:a,roundNamingProfile:d,additionalContext:{finishingPositionRange:c,abbreviatedRoundName:z,roundNumber:q,roundName:W},appliedPolicies:l,isCollectionBye:n,usePublishState:h,publishStatus:v,matchUpTieId:s,isRoundRobin:D,roundProfile:b,matchUp:o,event:M})}))}const he=fe.sides&&2===fe.sides.filter((e=>e?.participantId)).length,Ie=!fe.winningSide,Ue=Q&&he&&Ie;if(Object.assign(fe,{readyToScore:Ue,hasContext:!0}),he){const{allParticipantsCheckedIn:e,checkedInParticipantIds:t}=Pe({matchUp:fe});Object.assign(fe,{allParticipantsCheckedIn:e,checkedInParticipantIds:t})}return Array.isArray(U?.exclude)&&U?.exclude.forEach((e=>delete fe[e])),fe}}function Jf({inContextDrawMatchUps:e,inheritance:t=!0,tournamentRecord:r,drawDefinition:n,matchUpsMap:i,assignments:a,structure:o,event:s}){if(!n)return{error:Li};const{drawPositions:c,matchUps:u,targetMatchUps:d}=he({inContextDrawMatchUps:e,matchUpsMap:i,assignments:a,structure:o});for(const e of d)e.matchUpType===gf&&(e.sides??[]).forEach(((i,a)=>{if(i?.drawPosition&&c?.includes(i.drawPosition)){const o=u.find((({matchUpId:t})=>t===e.matchUpId));if(o?.sides?.[a]){if(delete o.sides[a].lineUp,!1===t){const t=e.tieFormat,r=i.participantId;t&&r&&Ge({drawDefinition:n,participantId:r,lineUp:[],tieFormat:t})}q({tournamentId:r?.tournamentId,context:"resetLineUps",eventId:s?.eventId,drawDefinition:n,matchUp:o})}}}));return{...Ni}}function Zf({tournamentRecord:e,drawDefinition:t,drawPositions:r,structureId:n,event:i}){if(!t)return{error:Li};if(!n)return{error:la};if(2!==r?.length)return{error:ys,drawPositions:r};const a=Mm({drawDefinition:t}),{matchUps:o}=Em({inContext:!0,drawDefinition:t,matchUpsMap:a}),{structure:s}=Om({drawDefinition:t,structureId:n});if(!s)return{error:ma};let c;if(c=s.structureType===nl?function({inContextDrawMatchUps:e,tournamentRecord:t,drawDefinition:r,drawPositions:n,matchUpsMap:i,structure:a,event:o}){const s=a.structures?.reduce(((e,t)=>{const r=t?.positionAssignments.filter((e=>n?.includes(e.drawPosition)));return r&&e.push(...r),e}),[]);if(2===s.filter((({bye:e})=>e)).length)return{...Ni};if(2===s.filter((({qualifier:e})=>e)).length)return{...Ni};Jf({inContextDrawMatchUps:e,tournamentRecord:t,drawDefinition:r,matchUpsMap:i,assignments:s,structure:a,event:o});const c=s.some((({qualifier:e})=>e));if(s.some((({bye:e})=>e))&&!c)Xf({inContextDrawMatchUps:e,tournamentRecord:t,drawDefinition:r,assignments:s,matchUpsMap:i,structure:a,event:o});else{const e=Jc(s,!1,!0);s.forEach(((t,r)=>{const n=e[1-r].participantId;t.qualifier=e[1-r].qualifier,t.participantId=n}))}return{...Ni}}({inContextDrawMatchUps:o,tournamentRecord:e,drawDefinition:t,drawPositions:r,matchUpsMap:a,structure:s,event:i}):function({inContextDrawMatchUps:e,tournamentRecord:t,drawDefinition:r,drawPositions:n,matchUpsMap:i,structure:a,event:o}){const s=a?.positionAssignments.filter((e=>n?.includes(e.drawPosition)));if(!s)return{error:ys,structure:a,info:"Missing positionAssignments"};if(2===s.filter((({bye:e})=>e)).length)return{...Ni};if(2===s.filter((({qualifier:e})=>e)).length)return{...Ni};const c=s.some((({qualifier:e})=>e));return s.some((({bye:e})=>e))&&!c?Xf({inContextDrawMatchUps:e,tournamentRecord:t,drawDefinition:r,assignments:s,matchUpsMap:i,structure:a,event:o}):function({inContextDrawMatchUps:e,tournamentRecord:t,drawDefinition:r,assignments:n,matchUpsMap:i,structure:a,event:o}){const s=Object.assign({},...n.map(((e,t)=>{const{drawPosition:r}=e;return{[r]:{...n[1-t],drawPosition:r}}})));return a.positionAssignments=a.positionAssignments.map((e=>s[e.drawPosition]||e)),Jf({inContextDrawMatchUps:e,tournamentRecord:t,drawDefinition:r,matchUpsMap:i,assignments:n,structure:a,event:o}),{...Ni}}({inContextDrawMatchUps:e,tournamentRecord:t,drawDefinition:r,assignments:s,matchUpsMap:i,structure:a,event:o})}({inContextDrawMatchUps:o,tournamentRecord:e,drawDefinition:t,drawPositions:r,matchUpsMap:a,structure:s,event:i}),c.error)return c;ql({structure:s,drawPositions:r});if(Hl({drawDefinition:t,positionAction:{name:"swapDrawPositionAssignments",drawPositions:r,structureId:n}}),Gp({tournamentId:e?.tournamentId,drawDefinition:t,structure:s,event:i}),i.eventType===Yf){const n=Kf({matchUpFilters:{matchUpTypes:[gf]},inContext:!0,structure:s}).matchUps.filter((e=>e.drawPositions?.some((e=>r.includes(e))))),a=Kf({structure:s,matchUpFilters:{matchUpTypes:[gf]}}).matchUps;n.forEach((n=>{(n.sides||[]).forEach((o=>{const s=o?.drawPosition;if(r.includes(s)){const r=o.participantId,c=a.find((({matchUpId:e})=>e===n.matchUpId)),u=n?.sides?.reduce(((e,t,r)=>t.drawPosition===s?r:e),void 0);!function({inContextTargetMatchUp:e,drawPositionSideIndex:t,teamParticipantId:r,tournamentRecord:n,drawDefinition:i,matchUp:a,event:o}){const s=e?.sides?.[t]?.sideNumber,c=s&&a.sides?.find((e=>e.sideNumber===s)),{extension:u}=Wl({element:i,name:mi}),d=Jc((u?.value||{})[r],!1,!0);if(c)a?.sides?.forEach((e=>{e.sideNumber===s&&(e.lineUp=d)}));else{a.sides=[1,2].map((e=>({...a.sides?.find((t=>t.sideNumber===e))??{},sideNumber:e})));const e=a.sides.find((e=>e.sideNumber===s));e&&(e.lineUp=d)}Vp({tournamentId:n?.tournamentId,context:"updateSidLineUp",eventId:o?.eventId,drawDefinition:i,matchUp:a})}({inContextTargetMatchUp:n,drawPositionSideIndex:u,teamParticipantId:r,tournamentRecord:e,drawDefinition:t,matchUp:c,event:i})}}))}))}return jp({drawDefinition:t,structureIds:[n]}),{...Ni}}function Xf({inContextDrawMatchUps:e,tournamentRecord:t,drawDefinition:r,assignments:n,matchUpsMap:i,structure:a,event:o}){const s=n.find((({bye:e})=>e)),c=n.find((({participantId:e})=>e)),u=s.drawPosition,{participantId:d,drawPosition:p}=c,{structureId:l}=a;let m=Tm({drawPosition:u,inContextDrawMatchUps:e,tournamentRecord:t,drawDefinition:r,structureId:l,matchUpsMap:i});return m.error?m:(m=Tm({drawPosition:p,inContextDrawMatchUps:e,tournamentRecord:t,drawDefinition:r,structureId:l,matchUpsMap:i}),m.error?m:(sf({drawPosition:p,tournamentRecord:t,drawDefinition:r,structureId:l,matchUpsMap:i,event:o}),m=Pf({drawPosition:u,inContextDrawMatchUps:e,tournamentRecord:t,drawDefinition:r,structureId:l,participantId:d,matchUpsMap:i,event:o}),m.error?m:{...Ni}))}function eh(e){return Zf(e)}function th({drawDefinition:e,attributes:t}){let{extension:r}=Wl({element:e,name:di});const n=r?.value||{};return t.forEach((e=>{Object.keys(e).forEach((t=>{n[t]?Object.assign(n[t],e[t]):n[t]=e[t]}))})),r={name:di,value:n},Ud({drawDefinition:e,extension:r}),{entryProfile:n}}function rh({drawDefinition:e}){const{extension:t}=Wl({element:e,name:di});return{entryProfile:t?.value||{}}}function nh({stage:e,drawDefinition:t}){const{entryProfile:r}=rh({drawDefinition:t}),n=Object.keys(r).includes(e);if(!n&&Yp.includes(e)){return th({drawDefinition:t,attributes:[{[e]:{drawSize:void 0,alternates:!0}}]}),!0}return n}function ih({stage:e,drawDefinition:t,entryStatus:r}){return t.entries.reduce(((t,n)=>n.entryStage===e&&n.entryStatus===r?t+1:t),0)}function ah({provisionalPositioning:e,placementGroup:t,drawDefinition:r,stageSequence:n,entryStatuses:i,structureId:a,roundTarget:o,stages:s,stage:c}){const u=r.entries?.reduce(((e,t)=>{const r=Wl({name:yi,element:t})?.extension?.value,a=c&&t.entryStage===c||s?.length&&t.entryStage&&s.includes(t.entryStage),u=!i||t.entryStatus&&i.includes(t.entryStatus),d=t.entryStageSequence??1;return a&&(!n||d===n)&&u&&(!o||!r||o===r)?e.concat(t):e}),[])??[];if(a&&c===zp){const{playoffEntries:n,error:i}=function({provisionalPositioning:e,drawDefinition:t,structureId:r}){const n=[],i=(t.links??[]).find((e=>e.linkType===cl&&e.target.structureId===r));if(i){const{finishingPositions:r,structureId:a}=i.source,{structure:o}=Om({drawDefinition:t,structureId:a});if(o?.structureType===nl){(o.structures??[]).forEach((t=>{const i=t.positionAssignments??[],{structureId:a}=t,o=a,s=Object.assign({},...i.map((e=>{const{participantId:t}=e,r=Wl({element:e,name:Di}).extension?.value;return r&&t?{[t]:r}:void 0})).filter(Boolean)),c=Object.keys(s).reduce(((t,r)=>{const n=s[r],i=n.groupOrder||e&&n.provisionalOrder;return t.includes(i)||t.push(i),t}),[]),u=c.length===Object.keys(s).length,d=Object.keys(s).filter((t=>{const n=s[t],i=n.groupOrder||e&&n.provisionalOrder;return r?.includes(i)}));e&&!u||d.forEach((t=>{const i=s[t],{groupOrder:a,provisionalOrder:c,GEMscore:u}=i,d=a||e&&c,p=[...r??[]].sort(Ad).indexOf(d)+1;n.push({entryStage:zp,entryStatus:Kl,placementGroup:p,groupingValue:o,participantId:t,GEMscore:u})}))}))}}return{playoffEntries:n}}({provisionalPositioning:e,drawDefinition:r,structureId:a});return i&&console.log("playoff entries error"),(n?.length?n:u).filter((e=>!t||e.placementGroup===t))}return u}function oh({provisionalPositioning:e,returnAllProxies:t,drawDefinition:r,structureId:n,structure:i}){let a,o=[];i||({structure:i,error:a}=Om({drawDefinition:r,structureId:n}));const s=op({structure:i}).positionAssignments;if(a||!i)return{seedAssignments:[],error:ma};n||(n=i.structureId);const{stage:c,stageSequence:u}=i,d=c===zp&&r&&ah({provisionalPositioning:e,drawDefinition:r,stageSequence:u,structureId:n,stage:c}),p=d?d.filter((e=>1===e.placementGroup)).sort(((e,t)=>(e.GEMscore<t.GEMscore?1:e.GEMscore>t.GEMscore&&-1)||0)).map(((e,t)=>{const r=t+1;return{participantId:e.participantId,seedValue:r,seedProxy:!0,seedNumber:r}})):[],l=p?.slice(0,t?p.length:s.length/2);l.length?o=l:i.seedAssignments?o=i.seedAssignments:a=ca;return{seedAssignments:o,stageSequence:u,seedLimit:i.seedLimit??i?.positionAssignments?.length,stage:c,error:a}}function sh({validation:e=!0,tournamentRecord:t,drawDefinition:r,participantId:n,structureId:i,seedValue:a,event:o}){if(!r)return{error:Li};if(!i)return{error:la};const s=(t?.participants??[]).find((e=>e.participantId===n));if(t&&!s)return{error:Io};const{structure:c}=Om({drawDefinition:r,structureId:i});if(!c)return{error:ma};if(!(!e||kd(a)||void 0===a||""===a||"string"==typeof a&&a.split("-").every((e=>kd(e)&&Ed(e)>0))))return{error:ys};const{seedAssignments:u}=oh({drawDefinition:r,structure:c}),d=u?.map((e=>e.seedNumber)),p=u?.find((e=>e.participantId===n));if(p){const e="string"==typeof a?a.includes("-")&&a.split("-").map((e=>parseInt(e))).join("-")||parseInt(a)>0&&parseInt(a)||"":a&&a>0&&a||"";p.seedValue=e}else{const e={seedNumber:Math.max(0,...d||[])+1,participantId:n};a&&(e.seedValue=a),c.seedAssignments||(c.seedAssignments=[]),c.seedAssignments.push(e)}return function({drawDefinition:e,tournamentId:t,structure:r,eventId:n}){if(!e)return{error:Li};if(!r)return{error:ha};const i=r.seedAssignments,a=r.structureId;rc({payload:{tournamentId:t,eventId:n,drawId:e.drawId,structureId:a,seedAssignments:i},topic:Dp,key:e.drawId}),jp({structureIds:[a],drawDefinition:e,tournamentId:t,eventId:n})}({tournamentId:t?.tournamentId,eventId:o?.eventId,drawDefinition:r,structure:c}),{...Ni}}function ch({drawDefinition:e,structureId:t}){if(!e)return{error:Li};const{structure:r}=Om({drawDefinition:e,structureId:t}),n=(e?.links||[]).filter((e=>e.source?.structureId===t)).map((e=>e.target?.structureId));return{playoffStructures:(e?.structures||[]).filter((e=>n.includes(e.structureId))),structure:r}}function uh({withStageGrouping:e,stageSequences:t,stageSequence:r,roundTarget:n,stages:i,event:a,stage:o}){if(!a)return{error:Ua};const s={},c=[];for(const u of a.drawDefinitions||[]){const{structures:a,stageStructures:d}=Fm({withStageGrouping:e,stageSequences:t,drawDefinition:u,stageSequence:r,roundTarget:n,stages:i,stage:o});if(c.push(...a),d)for(const e of Object.keys(d))s[e]||(s[e]=[]),s[e].push(...d[e])}return{structures:c,stageStructures:s}}function dh({withStageGrouping:e,tournamentRecord:t,stageSequences:r,stageSequence:n,roundTarget:i,stages:a,stage:o}){if(!t)return{error:Fi};const s={},c=[];for(const u of t.events||[]){const{structures:t,stageStructures:d}=uh({withStageGrouping:e,stageSequences:r,stageSequence:n,roundTarget:i,stages:a,event:u,stage:o});if(t&&c.push(...t),d)for(const e of Object.keys(d))s[e]||(s[e]=[]),s[e].push(...d[e])}return{structures:c,stageStructures:s}}function ph({requireParticipants:e=!0,scheduleVisibilityFilters:t,tournamentAppliedPolicies:r,tournamentParticipants:n,afterRecoveryTimes:i,policyDefinitions:a,tournamentRecord:o,usePublishState:s,matchUpFilters:c,contextFilters:u,contextContent:d,participantMap:p,scheduleTiming:l,publishStatus:m,contextProfile:f,drawDefinition:h,exitProfiles:g,matchUpsMap:I,structureId:U,inContext:y,structure:S,context:v,event:T}){!S&&U&&({structure:S}=w({drawDefinition:h,structureId:U}));const P=J({tournamentAppliedPolicies:r,scheduleVisibilityFilters:t,tournamentParticipants:n,afterRecoveryTimes:i,policyDefinitions:a,tournamentRecord:o,usePublishState:s,matchUpFilters:c,contextFilters:u,contextContent:d,participantMap:p,scheduleTiming:l,publishStatus:m,contextProfile:f,drawDefinition:h,exitProfiles:g,matchUpsMap:I,structure:S,inContext:y,context:v,event:T}),D=[],b=[],R=[],N=[],M=[];if(P.error)return P;const{matchUps:A}=P,{assignedPositions:E}=K({structure:S}),C=E?.filter((e=>e.participantId)).map((e=>e.drawPosition));let O;return A.filter((e=>{const t=1===c?.matchUpTypes?.length&&c.matchUpTypes[0]===If;return!(e.matchUpType!==If&&t)})).forEach((t=>{if(t.matchUpStatus===km)return void D.push(t);t.matchUpType===If&&(O=!0);const r=t.collectionId,n=r&&t.sides?.every((e=>e.participantId)),i=!r&&2===t.drawPositions?.filter(Boolean).length,a=!r&&t.drawPositions?.every((e=>C?.includes(e))),o=E?.filter((e=>e.bye)).map((e=>e.drawPosition)),s=!r&&t.drawPositions?.find((e=>o?.includes(e))),c=af.includes(t.matchUpStatus)&&(n||i&&(!e||a));return s?M.push(t):qe({matchUp:t})?b.push(t):c?R.push(t):N.push(t)})),{includesTeamMatchUps:O,abandonedMatchUps:D,completedMatchUps:b,upcomingMatchUps:R,pendingMatchUps:N,byeMatchUps:M,structure:S}}function lh(e){if(!e?.drawDefinition)return!1;const t=ph(e),r=t?.includesTeamMatchUps;let{completedMatchUps:n,pendingMatchUps:i,upcomingMatchUps:a}=t||{};r&&(n=n?.filter((({matchUpType:e})=>e===If)),i=i?.filter((({matchUpType:e})=>e===If)),a=a?.filter((({matchUpType:e})=>e===If)));return!!(n?.length&&!i?.length&&!a?.length)}function mh(e){const{drawDefinition:t,structureId:r}=e;if(!t)return{error:Li};const{playoffStructures:n}=ch({drawDefinition:t,structureId:r});if(!n?.length)return!1;const i=t?.entries?.filter((e=>e?.entryStatus&&um.includes(e.entryStatus)))?.length??0;let a=0;return(n||[]).reduce(((e,t)=>{const r=op({structure:t}).positionAssignments??[],n=r?.filter((e=>(e.participantId&&a++,e?.bye??e?.participantId))).length;return!(!n||!e)}),!!n.length)||a===i}function fh(e,t,r){const n=e=>Wl({element:e,name:yi})?.extension?.value,i=r?.deprioritizeCompleted,a=r?.mode===Jp&&Xp,o=r?.mode===Kp&&Zp,s=o||a||Qp,c=e=>(e=>e?.stage===qp&&1===e?.stageSequence)(e)?-1:s[e?.stage],u=e=>e?.matchUps.every((({matchUpStatus:e})=>rf.includes(e)?1:-1));return i&&u(e)-u(t)||a&&c(e)-c(t)||(e?.stage&&s[e.stage]||0)-(t?.stage&&s[t.stage]||0)||(n(e)||0)-(n(t)||0)||!o&&!a&&(t?.positionAssignments?.length??1/0)-(e?.positionAssignments?.length??1/0)||(e?.stageSequence??0)-(t?.stageSequence??0)||(hh(e)||0)-(hh(t)||0)}function hh(e){return(e?.matchUps||[]).reduce(((e,t)=>{const r=(t.finishingPositionRange?.winner||[]).reduce(((e,t)=>e+t),0);return!e||r<e?r:e}),void 0)}function gh({candidatePositionAssignments:e,participantsWithGroupings:t,policyAttributes:r,idCollections:n}){const i=Object.assign({},...t.map((e=>({[e.participantId]:e}))));return e.map((e=>{const a=i[e.participantId],{values:o}=function({policyAttributes:e,idCollections:t,participants:r,participant:n}){if(!Array.isArray(e))return{error:Wa};if(!n)return{error:To};const i=[];return e.forEach((e=>{const{directive:a,groupings:o,key:s,significantCharacters:c}=e||{};if(s){const e=s.split(".");i.push(...He({significantCharacters:c,value:n,accessors:e}))}else if(a){const o=e?.includeIds,s=(t?.[a]||[]).filter((e=>!o||o.includes(e)));s?.length&&r?.length&&s.forEach((e=>{const t=r.find((t=>t.participantId===e));if(t?.individualParticipantIds?.includes(n.participantId)){const e=t?.participantId;i.push(e)}}))}else o&&Object.keys(o).forEach((e=>{o[e].includes(n.participantId)&&i.push(e)}))})),{values:u(i)}}({participants:t,policyAttributes:r,idCollections:n,participant:a});return{...e,values:o}}))}function Ih({participantIdGroups:e,positionAssignments:t,groupsToAvoid:r}){return Object.assign({},...t.filter((e=>e?.participantId)).map((t=>{const{drawPosition:n,participantId:i}=t,a=e&&e[i]||[],o=!!r.some((e=>a.includes(e)));return{[n]:{participantGroups:a,includesGroupsToAvoid:o}}})))}function Uh(e){const{unfilledPositions:t,chunkedDrawPositions:r}=e,n=Ih(e);return r.map((e=>{const r=t.filter((t=>e.includes(t))),i=function(e){return e.filter((e=>!t(e)));function t(t){const r=yh(t);return!e.includes(r)}}(r),a=r.filter((e=>!i.includes(e))).filter((e=>{const t=yh(e);return!n[t]?.includesGroupsToAvoid}));return{unassigned:r,unpaired:i,pairedNoConflict:a}}))}function yh(e){return Number(e%2?e+1:e-1)}function Sh({selectedParticipantGroups:e,participantIdGroups:t,positionAssignments:r,drawPositionChunks:n,unfilledPositions:i,isRoundRobin:a}){const o=n.map((n=>a?function(e){const{unfilledPositions:t,chunkedDrawPositions:r}=e,n=Ih(e);return r.map((e=>{const r=t.filter((t=>e.includes(t))),i=r.length===e.length?r:[],a=e.filter((e=>n[e]?.includesGroupsToAvoid)).length;return{unassigned:r,unpaired:i,pairedNoConflict:a?[]:r,conflictsCount:a}}))}({groupsToAvoid:e,chunkedDrawPositions:n,participantIdGroups:t,positionAssignments:r,unfilledPositions:i}):Uh({groupsToAvoid:e,chunkedDrawPositions:n,participantIdGroups:t,positionAssignments:r,unfilledPositions:i})));if(a){return{unassigned:o.map((e=>e.map((e=>e.unassigned)).filter((e=>e?.length)))).filter((e=>e?.length)).sort(((e,t)=>(t.length||0)-(e.length||0))),unpaired:o.map((e=>e.map((e=>e.unpaired)).filter((e=>e?.length)))).filter((e=>e?.length)),pairedNoConflict:o.map((e=>e.map((e=>e.pairedNoConflict)).filter((e=>e?.length)))).filter((e=>e?.length)).sort(((e,t)=>(t.length||0)-(e.length||0)))}}return{unassigned:o.map((e=>e.map((e=>e.unassigned)).filter((e=>e?.length)))).filter((e=>e?.length)),unpaired:o.map((e=>e.map((e=>e.unpaired)).filter((e=>e?.length)))).filter((e=>e?.length)),pairedNoConflict:o.map((e=>e.map((e=>e.pairedNoConflict)).filter((e=>e?.length)))).filter((e=>e?.length))}}function vh({positionAssignments:e,participantIds:t}){const r=e.map((e=>e.participantId));return t.filter((e=>!r.includes(e)))}function Th({candidatePositionAssignments:e,unseededParticipantIds:t,participantIdGroups:r,drawPositionChunks:n,drawPositionGroups:i,pairedPriority:a,allGroups:o,groupKey:s}){const c=i.reduce(((e,t)=>t.length>e?t.length:e),0)<=2,u=vh({positionAssignments:e,participantIds:t}),d=function({drawPositionGroups:e,positionAssignments:t}){const r=Object.assign({},...t.map((e=>({[e.drawPosition]:e}))));return e.map((e=>e.filter(Boolean).map((e=>r[e])).filter(Boolean).filter((e=>!e.participantId&&!e.bye)).map((e=>e.drawPosition)))).flat().filter(Boolean)}({positionAssignments:e,drawPositionGroups:i}),{participantId:p,groupKey:l}=function({useSpecifiedGroupKey:e=!1,targetParticipantIds:t,largestFirst:r=!0,allGroups:n,groupKey:i}){const a=Object.assign({},...Object.keys(n).map((e=>[e,n[e].filter((e=>t.includes(e)))])).filter((e=>e[1].length)).map((([e,t])=>({[e]:t})))),o=Object.keys(a).reduce(((e,t)=>a[t].length>e?a[t].length:e),0),s=Object.keys(a).filter((e=>a[e].length===o)),c=Yd(r?s:Object.keys(a));return{participantId:(i=e&&a[i]?.length?i:c)&&a[i]?Yd(a[i]):Yd(t),groupKey:i}}({targetParticipantIds:u,useSpecifiedGroupKey:c,allGroups:o,groupKey:s}),m=function({allGroups:e,participantId:t}){return Object.keys(e).filter((r=>e[r].includes(t)))}({participantId:p,allGroups:o}),f=Sh({positionAssignments:e,isRoundRobin:c,selectedParticipantGroups:m,participantIdGroups:r,drawPositionChunks:n,unfilledPositions:d}),{unassigned:h,unpaired:g,pairedNoConflict:I}=f,U=I?.length&&I[0],y=g?.length&&g[0],S=a&&U?U:y,v=a?y:U,T=S?.length&&S||v?.length&&v;let P;if(T?.length){const e=zd(T);P=zd(e)}else{const e=zd(h[0]);P=zd(e)}return{newGroupKey:l,selectedParticipantId:p,targetDrawPosition:P}}function Ph({drawPositions:e}){if(!e?.length)return{error:Yi};const t=[].concat(...(e??[]).map((t=>e.filter((e=>e!==t)).map((e=>[t,e]))))),r=jd(t.map(Dh)).map((e=>e.split("|").map((e=>+e))));return{groupMatchUps:t,uniqueMatchUpGroupings:r}}function Dh(e=[]){return Array.isArray(e)&&e.length?[...e].sort(Ad).join("|"):""}function wh({groupSize:e,drawPositionOffset:t}){if(!e)return[];const r=e=>[...Array(e)].map(((e,t)=>t)),n=r(2*Math.round(e/2)+1).slice(1),i=r(n.length-1).map((()=>[]));let a=n.slice(0,n.length/2),o=n.slice(n.length/2);n.slice(1).forEach(((e,t)=>{a.forEach(((e,r)=>{i[t].push([a[r],o[r]])}));const r=a.shift(),n=a.pop(),s=o.shift();a=[r,s,...a].filter(Boolean),o=[...o,n].filter(Boolean)}));const s=a.shift(),c=a.pop(),u=o.shift();a=[s,u,...a].filter(Boolean),o=[...o,c].filter(Boolean);const d=e=>e[0].reduce(((e,t)=>e+t));return[...i].reverse().sort(((e,t)=>d(e)-d(t))).map((r=>r.filter((t=>t.every((t=>t<=e)))).map((e=>Dh(e.map((e=>e+t)))))))}const bh={getRoundRobinGroupMatchUps:Ph,determineRoundNumber:function({rounds:e,hash:t}){return e?.length?e?.reduce(((e,r,n)=>r.includes(t)?n+1:e),void 0):{error:Za}},drawPositionsHash:Dh,groupRounds:wh};function Rh({isRoundRobin:e,groupedParticipants:t}){const r=[];return e?t.forEach((e=>{const t=Ph({drawPositions:e.map((e=>e.drawPosition))}).uniqueMatchUpGroupings??[],n=Object.assign({},...e.map((e=>({[e.drawPosition]:e}))));t.forEach((t=>{Xd(n[t[0]].values||[],n[t[1]].values||[])&&(r.push(t),e.conflict=!0)}))})):t.forEach((e=>{Xd(e[0]?.values||[],e[1]?.values||[])&&(r.push(e),e.conflict=!0)})),r}function Nh({positionedParticipants:e,potentialDrawPositions:t,drawPositionGroups:r,avoidanceConflicts:n,isRoundRobin:i}){return n.map((n=>{const a=n.map((e=>e.drawPosition));return n.filter((e=>t.includes(e.drawPosition))).map((n=>{const o=t.filter((e=>!a?.includes(e))).filter((t=>{const a=r.find((e=>e.includes(t))).find((e=>e!==t)),o=e.find((e=>e.drawPosition===a)),s=Rh({isRoundRobin:i,groupedParticipants:[[n,o]]}),c=e.find((e=>e.drawPosition===t)),u=Rh({isRoundRobin:i,groupedParticipants:[[c,o]]});return!s.length&&!u.length}));if(o.length)return{drawPosition:n.drawPosition,possibleDrawPositions:o}})).filter(Boolean)})).flat(1)}function Mh(e){const{initialPositionAssignments:t,participantsWithGroupings:r,opponentsToPlaceCount:n,unseededByePositions:i,drawPositionGroups:a,policyAttributes:o,idCollections:s,allGroups:c}=e,u=[];let d;const p=Math.min(...(a||[]).map((e=>e?.length)).filter(Boolean)),l=p>2,m=Jc(t,!1,!0).filter((e=>!e.qualifier)),f=t.filter((e=>!e.participantId&&(!e.bye||i?.includes(e.drawPosition)))).map((e=>e.drawPosition));Qd(0,n).forEach((()=>{const{newGroupKey:t,selectedParticipantId:r,targetDrawPosition:n}=Th({...e,candidatePositionAssignments:m,allGroups:c,groupKey:d});d=t,m.forEach((e=>{e.drawPosition===n&&(e.participantId=r)}))}));let h=gh({candidatePositionAssignments:m,participantsWithGroupings:r,policyAttributes:o,idCollections:s}),g=ep(h,p),I=Rh({groupedParticipants:g,isRoundRobin:l}),U=0;for(;U<20&&I.length;){const e=Nh({positionedParticipants:h,potentialDrawPositions:f,avoidanceConflicts:I,drawPositionGroups:a,isRoundRobin:l});if(e.length){const t=Ah({candidatePositionAssignments:m,swapOptions:e});t.error&&console.log({result:t}),h=gh({candidatePositionAssignments:m,participantsWithGroupings:r,policyAttributes:o,idCollections:s}),g=ep(h,p),I=Rh({groupedParticipants:g,isRoundRobin:l}),U++}else U=20}return m.forEach((e=>{if(e.bye&&e.participantId){const e=sa;u.push(e)}if(e.qualifier&&e.participantId){const e=sa;u.push(e)}})),{positionAssignments:m,conflicts:I.length,groupedParticipants:g,errors:u}}function Ah({candidatePositionAssignments:e,swapOptions:t}){const r=zd(t);if(!r)return{error:{message:"No swap options"}};const n=r.drawPosition,i=zd(r.possibleDrawPositions),a=e.find((e=>e.drawPosition===n)),o=e.find((e=>e.drawPosition===i))??{},s={participantId:o?.participantId,qualifier:o?.qualifier,bye:o?.bye},c={participantId:a.participantId,qualifier:a.qualifier,bye:a.bye};return Object.assign(a,s),Object.assign(o,c),{...Ni}}function Eh({participantsProfile:e,participants:t=[],deepCopy:r}){const n=new Map,i=!1!==r?Jc(t,e?.convertExtensions,!0):t,a=i.filter((e=>e.participantType===ym)),o=i.filter((e=>e.participantType===Im)),s=i.filter((e=>e.participantType===Um));return i.forEach((e=>{if(e.participantType===gm){const{participantId:t}=e;e.groupParticipantIds=[],e.teamParticipantIds=[],e.pairParticipantIds=[],e.groups=[],e.teams=[],a.forEach((r=>{(r?.individualParticipantIds||[]).forEach((i=>{i!==t||e.teamParticipantIds?.includes(r.participantId)||(e.teamParticipantIds.push(r.participantId),n.get(r.participantId)||n.set(r.participantId,{participantName:r.participantName,participantId:r.participantId}),e.teams.push({participantRoleResponsibilities:r.participantRoleResponsibilities,participantOtherName:r.participantOtherName,participantName:r.participantName,participantId:r.participantId,teamId:r.teamId}))}))})),s.forEach((r=>{(r?.individualParticipantIds||[]).forEach((n=>{n!==t||e.pairParticipantIds.includes(r.participantId)||e.pairParticipantIds.push(r.participantId)}))})),o.forEach((r=>{(r?.individualParticipantIds||[]).forEach((n=>{n!==t||e.groupParticipantIds.includes(r.participantId)||(e.groupParticipantIds.push(r.participantId),e.groups.push({participantRoleResponsibilities:r.participantRoleResponsibilities,participantOtherName:r.participantOtherName,participantName:r.participantName,participantId:r.participantId}))}))}))}})),{participantsWithGroupings:i,groupInfo:Object.fromEntries(n)}}function Ch({provisionalPositioning:e,unseededParticipantIds:t,inContextDrawMatchUps:r,unseededByePositions:n,tournamentRecord:i,drawDefinition:o,seedBlockInfo:s,participants:c,matchUpsMap:u,structureId:d,avoidance:m,drawSize:f,event:h}){if(!m)return{error:$a};const{candidatesCount:g=1,policyAttributes:I,targetDivisions:U}=m;let{roundsToSeparate:y}=m;const S="randomUnseededSeparation",{structure:v}=w({drawDefinition:o,structureId:d}),{matchUps:T}=J({provisionalPositioning:e,matchUpsMap:u,structure:v,event:h});if(U&&ke(U)&&!y){const e=_e(U)||0,t=T.reduce(((e,t)=>t.roundNumber>e?t.roundNumber:e),0);y=t<e?1:t-e+1}const{positionAssignments:P}=K({structure:v}),D=Eh({participantsProfile:{convertExtensions:!0},deepCopy:!1,participants:c}).participantsWithGroupings,b=P?.filter((e=>!e.participantId)),N=P?.map((e=>e.drawPosition)),M=v?.structureType===nl,A=M?{structure:v,matchUps:T,allDrawPositions:N,roundsToSeparate:y}:{matchUps:T,allDrawPositions:N,roundsToSeparate:y},{drawPositionGroups:E,drawPositionChunks:C}=M?function(e){const{structure:{structures:t}}=e,r=t.map((e=>e.positionAssignments.map((e=>e.drawPosition))));return{drawPositionGroups:r,drawPositionChunks:[r]}}(A):function({allDrawPositions:e,roundsToSeparate:t,matchUps:r}){const n=r.filter((e=>1===e.roundNumber)).map((e=>e.drawPositions)),i=n.flat().sort(fe),a=Math.max(...i),o=e.filter((e=>e>a)),s=i.length,c=l(2===s?1:2,s).filter((e=>e===xe(e))),u=c.slice(0,t||c.length).reverse(),d=u.map((e=>p(i,e)));o.length&&console.log({fedDrawPositions:o});return{drawPositionGroups:n,drawPositionChunks:d}}(A),O={groupParticipants:c.filter((e=>e.participantType===Im)).map((e=>e.participantId)),teamParticipants:c.filter((e=>e.participantType===ym)).map((e=>e.participantId)),pairParticipants:c.filter((e=>e.participantType===Um)).map((e=>e.participantId))},F=We({targetParticipantIds:t,policyAttributes:I,idCollections:O,participants:c});if(F.error)return a({result:F,stack:S});const k=Object.assign({},...t.map((e=>{const t=Object.keys(F).filter((t=>(F[t]??[]).includes(e)));return{[e]:t}}))),_=vh({participantIds:t,positionAssignments:P});if(_.length>(b?.length||0))return{error:Go};let x;const L=_.length,V=l(0,g).map((()=>Mh({initialPositionAssignments:P,participantsWithGroupings:D,unseededParticipantIds:t,opponentsToPlaceCount:L,pairedPriority:!1,unseededByePositions:n,participantIdGroups:k,drawPositionChunks:C,drawPositionGroups:E,policyAttributes:I,idCollections:O,allGroups:F,drawSize:f})));if(x=V.reduce(((e,t)=>!e||(t.conflicts||0)<(e.conflicts||0)?t:e),void 0),!x||x.conflicts){const e=l(0,g).map((()=>Mh({initialPositionAssignments:P,participantsWithGroupings:D,unseededParticipantIds:t,opponentsToPlaceCount:L,pairedPriority:!0,unseededByePositions:n,participantIdGroups:k,drawPositionChunks:C,drawPositionGroups:E,policyAttributes:I,idCollections:O,allGroups:F,drawSize:f})));x=V.concat(...e).filter((e=>!e.errors?.length)).reduce(((e,t)=>!e||(t.conflicts||0)<(e.conflicts||0)?t:e),void 0)}if(!x)return{error:ms};const B=(Q({structure:v})?.positionAssignments??[]).filter((e=>e.participantId)).map((e=>e.participantId)),j=x.positionAssignments.filter((e=>!B.includes(e.participantId)));for(const e of j)if(e.bye){const t=R({tournamentRecord:i,drawDefinition:o,seedBlockInfo:s,structureId:d,matchUpsMap:u,event:h,...e});if(t.error)return a({result:t,stack:S})}else if(e.participantId){const t=$e({automaticPlacement:!0,inContextDrawMatchUps:r,tournamentRecord:i,drawDefinition:o,seedBlockInfo:s,structureId:d,matchUpsMap:u,event:h,...e});if(t.error)return a({result:t,stack:S,context:{assignment:e}})}return{...Ni}}function Oh({onlySpecifiedPolicyTypes:e=!1,policyTypes:t=[],tournamentRecord:r,drawDefinition:n,structure:i,event:a}){if(!Array.isArray(t))return{error:Ga};const o={};return r&&s(r),a&&s(a),n&&s(n),i&&s(i),{appliedPolicies:o,...Ni};function s(r){const n=r?.extensions,i=n?.find((e=>e.name===ri))?.value;if(i)for(const r of Object.keys(i))(e?t.includes(r):!t.length||t.includes(r))&&(o[r]=Jc(i[r],!1,!0))}}function Fh({policyTypes:e=[],tournamentRecord:t,drawDefinition:r,structure:n,event:i}){if(!Array.isArray(e))return{error:Ga};const{appliedPolicies:a}=Oh({tournamentRecord:t,drawDefinition:r,structure:n,event:i}),o={};for(const t of e){const e=a?.[t];e&&(o[t]=e)}return Object.keys(o).length?{policyDefinitions:o}:{info:Ya.message}}function kh({provisionalPositioning:e,inContextDrawMatchUps:t,unseededByePositions:r,multipleStructures:n,tournamentRecord:i,drawDefinition:a,seedBlockInfo:o,participants:s,matchUpsMap:c,structureId:u,structure:d,drawSize:p,event:l}){d||({structure:d}=Om({drawDefinition:a,structureId:u})),u||({structureId:u}=d);const{positionAssignments:m}=sp({structure:d}),{seedAssignments:f}=oh({provisionalPositioning:e,drawDefinition:a,structure:d}),h=f?.map((e=>e.participantId)).filter(Boolean),{stage:g,stageSequence:I}=d,U=g===$p?Wl({element:d,name:yi})?.extension?.value:void 0,y=ah({provisionalPositioning:e,drawDefinition:a,stageSequence:I,entryStatuses:cm,structureId:u,roundTarget:U,stage:g}),S=y.filter((e=>!h?.includes(e.participantId))).map((e=>e.participantId)),v=m?.filter((e=>!e.participantId&&!e.bye&&!e.qualifier)).map((e=>e.drawPosition));if(!n&&S.length>(v?.length||0))return pd({result:{error:Go},context:{unseededParticipantsCount:S.length,unfilledDrawPositionsCount:v?.length},stack:"positionUnseededParticipants"});const{appliedPolicies:T}=Oh({tournamentRecord:i,drawDefinition:a,event:l});let P=T?.[id];if(d.stage===zp){const e=y.reduce(((e,t)=>(e[t.groupingValue]||(e[t.groupingValue]=[]),e[t.groupingValue].push(t.participantId),e)),{});Object.keys(e).length&&(P||(P={policyName:"Playoff Avoidance"}),P.policyAttributes||(P.policyAttributes=[]),P.policyAttributes.push({groupings:e}))}return P&&s?Ch({provisionalPositioning:e,unseededParticipantIds:S,inContextDrawMatchUps:t,unseededByePositions:r,tournamentRecord:i,drawDefinition:a,seedBlockInfo:o,participants:s,matchUpsMap:c,structureId:u,avoidance:P,drawSize:p,entries:y}):function({provisionalPositioning:e,unseededParticipantIds:t,inContextDrawMatchUps:r,unfilledDrawPositions:n,multipleStructures:i,tournamentRecord:a,drawDefinition:o,seedBlockInfo:s,matchUpsMap:c,structureId:u,drawSize:d,event:p}){const l=d>2?Gd(n):n.reverse();for(const n of t){const t=l.pop();if(!i||t){const i=Pf({provisionalPositioning:e,inContextDrawMatchUps:r,tournamentRecord:a,drawDefinition:o,seedBlockInfo:s,participantId:n,drawPosition:t,matchUpsMap:c,structureId:u,event:p});if(i?.error&&console.log("!!!!!",{result:i}),i?.error)return pd({result:i,stack:"randomUnseededDistribution"})}}return{...Ni}}({provisionalPositioning:e,unseededParticipantIds:S,inContextDrawMatchUps:t,unfilledDrawPositions:v,multipleStructures:n,tournamentRecord:i,drawDefinition:a,seedBlockInfo:o,structureId:u,matchUpsMap:c,drawSize:p,event:l})}function _h(e){if(!e)return 1/0;if(Vd(e))return Ed(e);const t=e.split("-")[0];return Vd(t)?Ed(t):1/0}function xh({orderedSortedFirstRoundSeededDrawPositions:e,validSeedBlocks:t,byesToPlace:r}){const n=[];t.forEach((t=>{if(r-n.length>t.drawPositions.length)n.push(...t.drawPositions);else{const r=Vh(ep(t.drawPositions,2));let i,a=e[n.length];for(;i=Lh(r,a);)n.push(i),a=e[n.length]}}));const i=n.map((e=>Array.isArray(e)?Gd(e):e)).flat(1/0);if(_d(r)){if(t.map((e=>e.seedNumbers[0])).includes(r))return e}return i}function Lh(e,t){if(Array.isArray(e)&&2!==e.length)return e.pop();if(!Array.isArray(e[0]))return e.includes(t)?e.indexOf(t)?e.pop():e.shift():Math.round(Math.random())?e.pop():e.shift();const r=e[0].flat(1/0).length,n=e[1].flat(1/0).length;if(r===n){const r=e[0].flat(1/0).includes(t)?e[0]:e[1];return Lh(t?r:e[Math.round(Math.random())],t)}return Lh(r<n?e[1]:e[0],t)}function Vh(e){const t=Math.floor(e.length/2);return e.length>2?[Vh(e.slice(0,t)),Vh(e.slice(t))]:e}function Bh(e){const{roundRobinGroupsCount:t,participantsCount:r,cluster:n}=e;if(!Fe(r))return{seedBlocks:void 0,...a({result:{error:ys},context:{participantsCount:r},stack:"getSeedBlocks"})};const i=Le(r);if(t){const e=Math.min(t,i),r=[];let n=1;for(l(0,e).forEach((()=>{r.push([n]),n++}));n<i;){const t=l(n,n+e);n+=e,r.push(t)}return{...Ni,seedBlocks:r}}const o=l(1,i+1),s=[];let c=i/2;for(;c>1;){const e=p(o,c),t=e.length;e.forEach(((e,r)=>{let i;const a=r<t/2,o=r%2==0,c=e[0],u=e[e.length-1];i=n&&t>4?8===t?a?u:c:o?c:u:a?c:u,d(e,s)||s.push(i)})),c/=2}const u=o.filter((e=>!s.includes(e)));for(;u.length;)u.length%2==0?s.push(u.pop()):s.push(u.shift());const m=l(0,20).map((e=>Math.pow(2,e)));m.unshift(1);const f=m.indexOf(i);let h=0;const g=[];return l(0,f).forEach((e=>{g.push(s.slice(h,h+m[e])),h+=m[e]})),{...Ni,seedBlocks:g}}function jh({roundRobinGroupsCount:e,drawSize:t}){const r="getSeedGroups";if(!Fe(t))return{seedGroups:void 0,...a({result:{error:ys},context:{drawSize:t},stack:r})};if(e){if(!Fe(e))return{seedGroups:void 0,...a({context:{roundRobinGroupsCount:e},result:{error:ys},stack:r})};let n=1;const i=Math.floor(t/e);return{seedGroups:l(0,i).map((()=>{const t=l(n,n+e);return n+=e,t}))}}{const{seedBlocks:r}=Bh({participantsCount:t,roundRobinGroupsCount:e});let n=0;return{seedGroups:(r||[]).map((e=>(e||[]).map((()=>(n+=1,n)))))}}}function Gh({roundRobinGroupsCount:e,participantsCount:t}){if(e){const{validGroupSizes:r}=ct({drawSize:t}),n=r?.map((e=>Math.ceil(t/e)));if(!n?.includes(e))return a({context:{roundRobinGroupsCount:e},result:{error:ys}})}const{seedGroups:r}=jh({drawSize:t,roundRobinGroupsCount:e}),n=r?.map((e=>Math.min(...e)))||[];return{...Ni,seedingThresholds:n}}function qh({positioning:e,size:t}){const r=function({size:e}){const t=[e];let r=e;for(;r/2===Math.floor(r/2);)r/=2,t.push(r);return t.includes(1)||t.push(1),t.sort(Ad),t.reverse(),t}({size:t}),n=[],i=[],a=e=>e[0],o=(t,r)=>(e&&[el,tl].includes(e)&&r%2?(e=>e[e.length-1])(t):a(t))||a(t),s=(e,t)=>{if(e.every((e=>!i.includes(e)))){const r=o(e,t);return i.push(r),r}},c=e=>{const t=e.filter((e=>!i.includes(e)));if(t.length)return i.push(...t),t},u=(e,t)=>{const r=o(e,t);if(!i.includes(r))return i.push(r),r},d=Qd(1,t+1);for(const e of r)if(1===e){const e=ep(d,2),t=e.map(s).filter(Boolean);t.length&&n.push(t);const r=e.flatMap(c).filter(Boolean);r.length&&n.push(r)}else{const t=ep(d,e).map(u).filter(Boolean);t.length&&n.push(t)}return{divisions:r,divisionGroupings:n}}function $h({provisionalPositioning:e,returnAllProxies:t,appliedPolicies:r,seedingProfile:n,drawDefinition:i,allPositions:a,structure:o}){let s=[];if(!o)return{error:ha};const{matchUps:c,roundMatchUps:u}=Kf({matchUpFilters:{roundNumbers:[1]},provisionalPositioning:e,structure:o}),{seedAssignments:d}=oh({provisionalPositioning:e,returnAllProxies:t,drawDefinition:i,structure:o}),{positionAssignments:p}=sp({structure:o}),l=p?.length,m=d?.length??0;let f=[];const h=Object.keys(u).map((e=>parseInt(e))).sort(((e,t)=>e-t)).map((e=>{const t=u[e].map((e=>e.drawPositions)).flat(1/0).filter(Boolean),r=t.filter((e=>!f.includes(e)));return f=f.concat(...t),r})).filter((e=>e.length)).reverse(),g=h.pop(),I=g&&Math.min(...g)-1||0;n=n??r?.seeding?.seedingProfile;const U=g?.length||0,y=h.filter((e=>e.filter((e=>e<=m)).length)),{stage:S,structureType:v,roundLimit:T}=o,P=v===nl,D=!P&&h?.length,w=!P&&S===$p&&T,b=y.flat(1/0),R=D?b?.length:0,N=a?l:m,M=function({roundsNotPowerOf2:e,drawDefinition:t,structure:r,matchUps:n}){if(!r)return!1;n=n??r.matchUps??[],e=e??Cf({matchUps:n}).roundsNotPowerOf2;const i=!!r.positionAssignments?.find((({drawPosition:e})=>e))||!!n?.find((({drawPositions:e})=>e?.length));return(!t?.drawType||t.drawType!==Sl)&&!r?.structures&&e&&i}({drawDefinition:i,structure:o,matchUps:c}),A=M?0:!D&&N||N&&b.length<N&&N-b.length||0;if(w){const e=o?.matchUps?o.matchUps.filter((({roundNumber:e})=>e===o.roundLimit)).length:0,t=g.length/e;if(D);else{const e=zh(n),r=ep(g,t);let i=1;const a=Qd(0,r[0].length).map((()=>{const e=Qd(i,i+r.length);return i+=r.length,e}));({validSeedBlocks:s}=Wh({drawPositionBlocks:r,nonRandom:n?.nonRandom,positioning:e,seedGroups:a}))}}else if(P){const e=function({seedingProfile:e,structure:t,nonRandom:r}){const n=t.structures||[],i=n.length,a=op({structure:t})?.positionAssignments,o=zh(e),s=a?.length??0,{seedGroups:c}=jh({roundRobinGroupsCount:i,drawSize:s});return Wh({drawPositionBlocks:n.map((e=>op({structure:e}).positionAssignments?.map((e=>e.drawPosition)))),positioning:o,seedGroups:c,nonRandom:r})}({nonRandom:n?.nonRandom,seedingProfile:n,structure:o});({validSeedBlocks:s}=e)}else if(D)s=y.map((e=>({seedNumbers:e,drawPositions:e})));else if(M){ep(g,2).map(((e,t)=>({drawPositions:[e[0]],seedNumbers:[t+1]}))).forEach((e=>s.push(e)))}if(!P&&!M&&!w){const{blocks:e}=function(e){const{drawPositionOffset:t=0,roundRobinGroupsCount:r,seedNumberOffset:n=0,seedingProfile:i,seedCountGoal:a,baseDrawSize:o}=e;let s=1;const c=[],{seedBlocks:u}=Bh({cluster:zh(i)===el,participantsCount:o,roundRobinGroupsCount:r});s=0;for(const e of u){if(s+1>a)break;const r=e.map((e=>e+t)),i=d(s+1,e.length).map((e=>+e+n));s+=e.length,c.push({drawPositions:r,seedNumbers:i})}return{blocks:c};function d(e,t){return Array.from(new Array(t),((t,r)=>r+e))}}({drawPositionOffset:I,seedNumberOffset:R,seedCountGoal:A,seedingProfile:n,baseDrawSize:U});e.forEach((e=>s.push(e)))}const E=s.flatMap((e=>e.drawPositions)).reduce(((e,t)=>g?.includes(t)&&e),!0);return M||D||P||E?{isLuckyStructure:M,validSeedBlocks:s,isContainer:P,isFeedIn:D}:{error:ua,validSeedBlocks:[],isContainer:P,isFeedIn:D}}function Wh({drawPositionBlocks:e,positioning:t,seedGroups:r,nonRandom:n}){const i=[],{divisionGroupings:a}=qh({size:r.length,positioning:t}),o=[];return r.forEach(((r,s)=>{const c=function({blockPattern:e,index:t}){let r=0;for(const n of e){if(r===t)return n;let e=0;for(;e<n.length;){if(r===t)return n;r+=1,e++}}}({blockPattern:a,index:s});r.forEach(((r,a)=>{const u=s%2?e.length-a-1:a;let d=e[u].slice().filter(((e,t)=>c.includes(t+1)&&e));t!==tl?d=n?d:Gd(d):s%2&&d.reverse();const p=d.find((e=>!o.includes(e)));p&&(o.push(p),i.push({drawPositions:[p],seedNumbers:[r]}))}))})),{validSeedBlocks:i}}function Hh(e){const{provisionalPositioning:t,drawDefinition:r,seedingProfile:n,seedBlockInfo:i,structureId:a,randomize:o}=e,{structure:s}=Om({drawDefinition:r,structureId:a}),{seedAssignments:c}=oh({returnAllProxies:e.returnAllProxies,provisionalPositioning:t,drawDefinition:r,structure:s}),{positionAssignments:u}=sp({structure:s}),d=u?.filter((e=>e.participantId??e.bye??e.qualifier)),p=d?.map((e=>e.drawPosition)).filter(Boolean),{appliedPolicies:l}=Oh({drawDefinition:r}),m=(i?.validSeedBlocks||s&&$h({returnAllProxies:e.returnAllProxies,provisionalPositioning:t,appliedPolicies:l,drawDefinition:r,seedingProfile:n,structure:s})?.validSeedBlocks||[]).filter((e=>e.drawPositions.filter((e=>!p?.includes(e))).length))[0],f=c?.map((e=>e.participantId)).filter(Boolean),h=u?.map((e=>e.participantId)).filter(Boolean),g=f?.filter((e=>h?.includes(e))),I=f?.filter((e=>!h?.includes(e))),U=c?.filter((e=>I?.includes(e.participantId))),y=c?.filter((e=>!e.participantId)),S=(U?.length&&U.length>0?U.length:y?.length??0)&&m?.drawPositions.filter((e=>!p?.includes(e)))||[],v=o?Gd(S):S,T=[],P=v.map((()=>{const e=function(e,t){const r=e.filter((e=>!t.includes(e.participantId))),n=Math.min(...r.map((e=>_h(e.seedValue)))),i=r.filter((e=>_h(e.seedValue)===n));return Gd(i).pop()}(U,T),t=e?.participantId;return t&&T.push(t),t})).filter(Boolean),D=c?.filter((e=>g?.includes(e.participantId))).map((e=>e.seedNumber)),w=(m?.seedNumbers||[]).filter((e=>!D?.includes(e))),b=c?.filter((e=>w.includes(e.seedNumber))).map((e=>e.participantId)),R=l?.seeding?.duplicateSeedNumbers;return{nextSeedBlock:m,unplacedSeedParticipantIds:void 0===R||R?P:b,unplacedSeedNumbers:w,unfilledPositions:v,unplacedSeedAssignments:U}}function zh(e){return"string"==typeof e?e:"object"==typeof e?e.positioning:void 0}function Yh({provisionalPositioning:e,relevantMatchUps:t,appliedPolicies:r,drawDefinition:n,seedingProfile:i,seedBlockInfo:a,byesToPlace:o,structure:s}){a||(a=$h({provisionalPositioning:e,appliedPolicies:r,drawDefinition:n,seedingProfile:i,structure:s}));const{isFeedIn:c,isLuckyStructure:u,isContainer:d}=a;let{validSeedBlocks:p}=a;r?.seeding?.containerByesIgnoreSeeding&&(p=[]);const l=function({provisionalPositioning:e,drawDefinition:t,structure:r}){const{positionAssignments:n}=sp({structure:r}),{seedAssignments:i}=oh({provisionalPositioning:e,drawDefinition:t,structure:r}),a=Object.assign({},...(i||[]).filter((e=>e.participantId)).map((e=>({[e.participantId]:e}))));return n?.map((e=>a[e.participantId]?{...e,seedNumber:a[e.participantId].seedNumber,seedValue:a[e.participantId].seedValue}:"")).filter(Boolean)}({provisionalPositioning:e,drawDefinition:n,structure:s})??[],m=jd([].concat(...t.map((e=>e.drawPositions)))),f=l.filter((e=>m.includes(e.drawPosition))),h=(e,t)=>_h(e.seedValue)-_h(t.seedValue),g=p.reduce(((e,t)=>{const r=f.filter((e=>t.drawPositions?.includes(e.drawPosition))).sort(h);return e.concat(...r)}),[]).map((e=>e.drawPosition)),I=xh({orderedSortedFirstRoundSeededDrawPositions:g,validSeedBlocks:p,byesToPlace:o});return{strictSeedOrderByePositions:Qh({orderedSeedDrawPositions:g,relevantMatchUps:t}).slice(0,o),blockSeedOrderByePositions:Qh({orderedSeedDrawPositions:I,relevantMatchUps:t}).slice(0,o),isLuckyStructure:u,positionedSeeds:l,isContainer:d,isFeedIn:c}}function Qh({orderedSeedDrawPositions:e,relevantMatchUps:t}){const r=t.map((e=>e.drawPositions)).map((e=>e?.sort(((e,t)=>e-t)))).filter((e=>e?.[0]+1===e?.[1]));return e.map((e=>r.find((t=>t?.includes(e))))).filter(Boolean).map((t=>t?.reduce(((t,r)=>e.includes(r)?t:r),void 0))).filter(Boolean)}function Kh({provisionalPositioning:e,tournamentRecord:t,appliedPolicies:r,drawDefinition:n,seedBlockInfo:i,seedingProfile:a,matchUpsMap:o,structureId:s,structure:c,seedLimit:u,seedsOnly:d,event:p}){c||({structure:c}=w({drawDefinition:n,structureId:s})),s||(s=c?.structureId);const l=!(c?.structures??c?.stage===$p),{byesCount:m,placedByes:h,relevantMatchUps:g}=ut({provisionalPositioning:e,drawDefinition:n,matchUpsMap:o,structure:c,event:p}),I=m-(h||0);if(I<=0)return{...Ni};const{strictSeedOrderByePositions:U,blockSeedOrderByePositions:y,isLuckyStructure:S,isFeedIn:v}=Yh({provisionalPositioning:e,relevantMatchUps:g,appliedPolicies:r,drawDefinition:n,seedingProfile:a,seedBlockInfo:i,byesToPlace:I,structure:c}),T=c?.structureType&&[nl,rl].includes(c.structureType)&&r?.seeding?.containerByesIgnoreSeeding,P=l&&y?.length?y:U;let{unseededByePositions:D}=function({provisionalPositioning:e,seedOrderByePositions:t,isLuckyStructure:r,appliedPolicies:n,drawDefinition:i,seedLimit:a,structure:o,isFeedIn:s}){const c=n?.seeding?.seedingProfile,u=o.stage===$p,{positionAssignments:d}=sp({structure:o}),p=d?.filter((e=>e.participantId)).map((e=>e.drawPosition)),{matchUps:l,roundMatchUps:m}=Kf({provisionalPositioning:e,matchUpFilters:{isCollectionMatchUp:!1},structure:o}),f=m?.[1]||[],h=o.structureType===nl?l:f,g=jd([].concat(...h.map((e=>e.drawPositions)))),I=Math.min(...g)-1,U=p?.filter((e=>g.includes(e))),y=e=>{const t=Math.ceil(e.length/2),r=[e.slice(0,t),e.slice(t)],n=r.map((e=>[].concat(...e.flat(1/0)).length)),i=Math.min(...n.flat(1/0)),a=Math.max(...n.flat(1/0)),o=n.indexOf(a),s=i!==a,c=Gd(r),[u,d]=!i||s?[r[o],r[1-o]]:[c[0],c[1]];return{greaterHalf:u,lesserHalf:d}},S=e=>{const{greaterHalf:t,lesserHalf:r}=y(e),{greaterHalf:n,lesserHalf:i}=y(t),a=Gd(n.flat(1/0)).pop();return{newlyFilteredChunks:[...r,...i,n.flat().filter((e=>e!==a))],drawPosition:a}},v=e=>!U?.includes(e),T=e=>{let t=ep(e.sort(Ad),Math.ceil(e.length/4)).map((e=>e.filter(v)));const r=[].concat(...t.flat(1/0)).length,n=[];for(let e=0;e<r;e++){const{newlyFilteredChunks:e,drawPosition:r}=S(t);n.push(r),t=e}return n},{validSeedBlocks:P}=$h({provisionalPositioning:e,allPositions:!0,appliedPolicies:n,drawDefinition:i,structure:o}),D=P?.map((e=>e.drawPositions?.map((e=>e+I))));let w;if(s){const e=g.length,{seedBlocks:t}=Bh({cluster:zh(c)===el,participantsCount:e});w=t.map((e=>e.map((e=>e+I)))).map(T).filter((e=>e.length))}else w=u?D?.map((e=>e.filter(v))):D?.map(T).filter((e=>e.length));const b=h.map((e=>e.drawPositions)).map((e=>e?.sort(((e,t)=>e-t)))).filter((e=>e?.[0]+1===e?.[1])),R=e=>b.reduce(((t,r)=>r.includes(e)?r.reduce(((t,r)=>r!==e?r:t),void 0):t),void 0);let N=w.map((e=>e.map(R))).flat(1/0).filter(v).filter((e=>!t.includes(e))).filter(Boolean);if(u&&!o.structures){const e=a%4,t=N.slice(0,e),r=m[o.roundLimit]?.length,n=ep(N.slice(e),r).map(Gd).flat();N=t.concat(n)}return{unseededByePositions:N}}({provisionalPositioning:e,seedOrderByePositions:P,isLuckyStructure:S,appliedPolicies:r,drawDefinition:n,seedLimit:u,structure:c,isFeedIn:v});let b=[].concat(...P);if(!d)for(;D.length;){const e=D.find((e=>{return t=e,(b||[]).every((e=>e%2?t!==e+1:t!==e-1));var t}));e?(b.push(e),D=D.filter((t=>t!==e))):(b.push(...D),D=[])}T&&(b=f(b),Ye({ignoreSeededByes:T})&&console.log({byePositions:b}));const N=b.slice(0,I);for(const r of N){const i=R({provisionalPositioning:e,tournamentRecord:t,drawDefinition:n,drawPosition:r,matchUpsMap:o,structureId:s,structure:c,event:p});if(i?.error)return i}return{...Ni,unseededByePositions:D,byeDrawPositions:N}}function Jh({applyPositioning:e=!0,provisionalPositioning:t,inContextDrawMatchUps:r,multipleStructures:n,placeByes:i=!0,tournamentRecord:o,appliedPolicies:s,placementGroup:c,drawDefinition:u,seedingProfile:d,structureId:p,matchUpsMap:l,seedLimit:m,seedsOnly:f,drawType:h,drawSize:g,event:I}){const U=[];e||(Qe(),u=L(u,!1,!0));const y=t=>(e||Ke(),a({result:t,stack:"automatedPositioning"})),S=w({drawDefinition:u,structureId:p});if(S.error)return y(S);const v=S.structure;if(!v)return{error:ma};s||(s=te({drawDefinition:u,structure:v,event:I})?.appliedPolicies);const{qualifiersCount:T}=dt({stageSequence:v.stageSequence,provisionalPositioning:t,stage:v.stage,drawDefinition:u,structureId:p}),P=cm,D=lt({stageSequence:v.stageSequence,provisionalPositioning:t,stage:v.stage,placementGroup:c,drawDefinition:u,entryStatuses:P,structureId:p});if(!D?.length&&!T)return b={...Ni},e||Ke(),b;var b;l=l??se({drawDefinition:u}),r||({matchUps:r}=ue({inContext:!0,drawDefinition:u,matchUpsMap:l}));let R=[];const N=Ie({provisionalPositioning:t,appliedPolicies:s,drawDefinition:u,seedingProfile:d,structure:v});if(N.error)return N;const{validSeedBlocks:M}=N;U.push({validSeedBlocks:M});const A=o?pt({withIndividualParticipants:!0,tournamentRecord:o})?.participants:[];if(Ue(v.seedingProfile||d)===tl){let e=i?Kh({provisionalPositioning:t,tournamentRecord:o,appliedPolicies:s,drawDefinition:u,seedBlockInfo:N,matchUpsMap:l,structure:v,seedLimit:m,seedsOnly:f,event:I}):void 0;if(e?.error)return y(e);R=e.unseededByePositions,U.push({action:"positionByes",unseededByePositions:R});const n=v.seedingProfile?{positioning:v.seedingProfile}:d;if(e=st({seedingProfile:n,provisionalPositioning:t,inContextDrawMatchUps:r,tournamentRecord:o,appliedPolicies:s,validSeedBlocks:M,drawDefinition:u,seedBlockInfo:N,participants:A,matchUpsMap:l,structure:v,event:I}),e.error)return y(e);U.push({seedPositions:e.seedPositions,action:"positionSeedBlocks"})}else{if(h!==Sl){const e=v.seedingProfile?{positioning:v.seedingProfile}:d,n=st({seedingProfile:e,provisionalPositioning:t,inContextDrawMatchUps:r,tournamentRecord:o,appliedPolicies:s,validSeedBlocks:M,drawDefinition:u,seedBlockInfo:N,participants:A,matchUpsMap:l,structure:v,event:I});if(n.error)return y(n);U.push({action:"positionSeedBlocks",seedPositions:n.seedPositions})}const e=i?Kh({provisionalPositioning:t,tournamentRecord:o,appliedPolicies:s,drawDefinition:u,seedBlockInfo:N,matchUpsMap:l,structure:v,seedLimit:m,seedsOnly:f,event:I}):void 0;if(e?.error)return y(e);R=e?.unseededByePositions,U.push({action:"positionByes",byeDrawPositions:e?.byeDrawPositions,unseededByePositions:R})}const E={};if(!f){let e=ze({inContextDrawMatchUps:r,tournamentRecord:o,appliedPolicies:s,validSeedBlocks:M,drawDefinition:u,seedBlockInfo:N,participants:A,matchUpsMap:l,structure:v});if(e.error)return y(e);if(e.conflicts&&(E.qualifierConflicts=e.conflicts),U.push({action:"positionQualifiers",qualifierDrawPositions:e.qualifierDrawPositions}),e=kh({provisionalPositioning:t,inContextDrawMatchUps:r,unseededByePositions:R,multipleStructures:n,tournamentRecord:o,drawDefinition:u,seedBlockInfo:N,participants:A,matchUpsMap:l,structureId:p,structure:v,drawSize:g,event:I}),e.error)return y(e);e.conflicts&&(E.unseededConflicts=e.conflicts),U.push({action:"positionUnseededParticipants"})}const{positionAssignments:C}=Q({drawDefinition:u,structure:v});return $({drawDefinition:u,structureIds:[p]}),e||Ke(),{positionAssignments:C,conflicts:E,...Ni,positioningReport:U}}function Zh(e){const{applyPositioning:t=!0,provisionalPositioning:r,tournamentRecord:n,drawDefinition:i,seedingProfile:a,structureId:o,placeByes:s,seedsOnly:c,event:u}=e;if(!u)return{error:ya};if(!i)return{error:Bi};if(!lh({drawDefinition:i,structureId:o})&&!r)return{error:Gi};const d=ch({drawDefinition:i,structureId:o}).playoffStructures?.sort(((e,t)=>hh(e)-hh(t))),p=[],l=[];if(d)for(const e of d){const{structureId:o}=e,u=Jh({structureId:o,provisionalPositioning:r,applyPositioning:t,tournamentRecord:n,drawDefinition:i,seedingProfile:a,placeByes:s,seedsOnly:c});if(u.error)return u;u.positionAssignments&&p.push({positionAssignments:u.positionAssignments,structureId:o}),u.positioningReport&&l.push(u.positioningReport)}return{...Ni,structurePositionAssignments:p,positioningReports:l}}function Xh({drawDefinition:e,orderMap:t}){return e?("object"==typeof t&&Object.values(t).every((e=>Fe(e)))||a({result:{error:ys},context:{orderMap:t}}),e.structures||(e.structures=[]),e.structures.forEach((e=>{const r=t[e.structureId];r&&(e.structureOrder=r)})),e.structures.sort(((e,t)=>h(e.structureOrder)-h(t.structureOrder))),{...Ni}):{error:Li}}function eg({drawDefinition:e}){const t=e.structures??[],r=e.links??[],n=new Map,i=e=>{const r=n.get(e)||n.set(e,{drawSources:[],drawTargets:[],progeny:[],sources:[],targets:[]})&&n.get(e);if(r&&!r?.stage){const n=t.find((t=>t.structureId===e));r.stage=n?.stage}return r},a={},o={};let s=r.map((e=>{const t=e.source.structureId,r=e.target.structureId,n=i(t),s=i(r);return[sl,ol,al,tl].includes(e.target.feedProfile)?(n?.targets.push(r),s?.sources.push(t)):e.target.feedProfile===il&&(s?.drawSources.push(t),n?.drawTargets.push(r)),o[r]=o[r]||e.target.feedProfile===il,a[r]=jd([...a[r]||[],t]).filter(Boolean),[e.source.structureId,e.target.structureId]}));for(const e of n.keys()){const t=n.get(e);if(t){const e=t.targets??[];for(;e.length;){const r=e.pop(),i=r&&n[r];i?.targets?.length?e.push(...i.targets):i&&(t.rootStage=i.stage)}if(t.rootStage||(t.rootStage=t.stage),!t.targets?.length){const e=t.sources??[];for(;e.length;){const r=e.pop(),i=r&&n[r];if(i?.sources?.length){for(const e of i.sources)t.progeny?.includes(e)||t.progeny?.push(e);e.push(...i.sources)}}}}}let c=0;for(const e of n.keys()){const t=n.get(e);if(t&&t.rootStage===$p){const e=[t.drawTargets?.[0]];let r=0;for(;e.length;){r+=1;const t=e.pop(),i=t?n.get(t):void 0;i?.drawTargets?.length&&e.push(i.drawTargets[0])}t.distanceFromMain=r,r>c&&(c=r)}}const u=s.length;Qd(0,Math.ceil(u/2)).forEach((()=>{s=Qd(0,u).map((e=>{const t=s[e],r=s.reduce(((e,r)=>Xd(t,r)?e.concat(...r):e),[])||[];return jd(t.concat(...r))}))}));const d=s[0],p=s.slice(1).reduce(((e,t)=>{return e&&Jd(r=t,d).length===r.length;var r}),!0),l=[d].filter(Boolean),m=[d].filter(Boolean);t.forEach((e=>{const{structureId:t,stage:r}=e;l.find((e=>e.includes(t)))||(l.push([t]),r!==Hp&&m.push([t]))}));const f=p&&1===m.length;return r?.length||1!==t.length||i(t[0].structureId),{structureProfiles:Object.fromEntries(n),allStructuresLinked:f,maxQualifyingDepth:c,sourceStructureIds:a,hasDrawFeedProfile:o,structureGroups:l}}function tg({drawDefinition:e}){const{maxQualifyingDepth:t,structureProfiles:r}=eg({drawDefinition:e});for(const n of e.structures){const e=r[n.structureId];e.distanceFromMain&&(n.stageSequence=t+1-e.distanceFromMain)}return{...Ni}}function rg(e){const{tournamentRecord:t,participantId:r}=e,n=e.tournamentRecords||t&&{[t.tournamentId]:t}||{};for(const e of Object.values(n)){const t=e.participants?.find((e=>e.participantId===r));if(t)return{participant:t,tournamentId:e.tournamentId}}return{error:wo}}function ng({returnPreviousValues:e,itemSubTypes:t,itemType:r,element:n}){if(!n)return{error:Za,info:ld};if(t&&!Array.isArray(t))return{error:ys,context:{itemSubTypes:t}};if(!Array.isArray(n.timeItems))return{error:os};const i=n.timeItems.filter((e=>e?.itemType===r)).filter((e=>!t?.length||t.some((t=>e?.itemSubTypes?.includes(t))))).sort(((e,t)=>new Date(e.createdAt||void 0).getTime()-new Date(t.createdAt||void 0).getTime())),a=i.pop();if(a){const t={timeItem:a,...Ni};return e&&Object.assign(t,{previousItems:i}),t}return{info:ws}}function ig({returnPreviousValues:e,drawDefinition:t,itemSubTypes:r,itemType:n}){if(!t)return{error:ra};if(!t.timeItems)return{info:ws};const{timeItem:i,previousItems:a,info:o}=ng({element:t,returnPreviousValues:e,itemSubTypes:r,itemType:n});return i&&{timeItem:i,previousItems:a}||{info:o}}function ag({returnPreviousValues:e,itemSubTypes:t,itemType:r,event:n}){if(!n)return{error:Ua};if(!n.timeItems)return{info:ws};const{timeItem:i,previousItems:a,info:o}=ng({returnPreviousValues:e,element:n,itemSubTypes:t,itemType:r});return i&&{timeItem:i,previousItems:a}||{info:o}}function og({returnPreviousValues:e,tournamentRecord:t,itemSubTypes:r,itemType:n}){if(!t)return{error:Fi};if(!t.timeItems)return{info:ws};const{timeItem:i,previousItems:a,info:o}=ng({element:t,returnPreviousValues:e,itemSubTypes:r,itemType:n});return i&&{timeItem:i,previousItems:a}||{info:o}}function sg({returnPreviousValues:e,tournamentRecord:t,participantId:r,itemSubTypes:n,itemType:i}){if(!t)return{error:Fi};if(!r)return{error:Do};const a=M({tournamentRecord:t,participantId:r});if(a.error)return a;const{participant:o}=a;if(!o?.timeItems)return{info:ws};const{timeItem:s,previousItems:c,info:u}=ng({element:a.participant,returnPreviousValues:e,itemSubTypes:n,itemType:i});return s&&{timeItem:s,previousItems:c}||{info:u}}function cg(e){const{duplicateValues:t=!0,creationTime:r=!0,removePriorValues:n,timeItem:i,element:a}=e;if(!i)return{error:as};if(!a)return{error:Za,info:ld};const o=i&&Object.keys(i),s=["itemType","itemValue"];if(!(s.filter((e=>o.includes(e))).length===s.length))return{error:ns};if(a.timeItems){const{itemType:e,itemSubTypes:r,itemValue:n}=i,o=e&&ng({itemSubTypes:r,itemType:e,element:a})?.timeItem;if(o&&JSON.stringify(o?.itemValue)===JSON.stringify(n)&&!t)return{...Ni}}else a.timeItems=[];if(i.itemSubTypes&&!i.itemSubTypes.length&&delete i.itemSubTypes,r){const e=(new Date).toISOString();Object.assign(i,{createdAt:e})}n&&(a.timeItems=a.timeItems.filter((({itemType:e})=>i.itemType!==e)));return n&&!i.itemValue||a.timeItems.push(i),{...Ni}}function ug({creationTime:e=!0,removePriorValues:t,tournamentRecord:r,duplicateValues:n,participantId:i,timeItem:a}){if(!r)return{error:Fi};if(!i)return{error:Do};const o=rg({tournamentRecord:r,participantId:i});return o.error?o:cg({element:o.participant,removePriorValues:t,duplicateValues:n,creationTime:e,timeItem:a})}function dg(e){const{removePriorValues:t,tournamentRecord:r,duplicateValues:n,creationTime:i,timeItem:a}=e;return r?cg({element:r,removePriorValues:t,duplicateValues:n,creationTime:i,timeItem:a}):{error:Fi}}function pg(e){const{removePriorValues:t,duplicateValues:r,creationTime:n,timeItem:i,event:a}=e;return a?cg({removePriorValues:t,duplicateValues:r,element:a,creationTime:n,timeItem:i}):{error:ya}}function lg({tournamentRecord:e,drawDefinition:t,structure:r,link:n}){if(!e)return{error:Fi};if(!t)return{error:Li};const i=function({drawDefinition:e,tournamentId:t,structure:r,eventId:n,link:i}){if(!e)return{error:Li};if(!r)return{error:ha};if(!i)return{error:da};const a=i.target.structureId,o=Om({drawDefinition:e,structureId:a});if(o.error)return pd({stack:"attachQualifyingStructure",context:{targetStructureId:a},result:o});e.structures||(e.structures=[]);e.links||(e.links=[]);e.structures.push(r),e.links.push(i),tg({drawDefinition:e});const s=Kf({structure:r})?.matchUps||[];return xp({drawDefinition:e,tournamentId:t,matchUps:s,eventId:n}),jp({drawDefinition:e,structureIds:[r.structureId]}),{...Ni}}({tournamentId:e.tournamentId,drawDefinition:t,structure:r,link:n});if(i.error)return i;return dg({tournamentRecord:e,timeItem:{itemType:"attachQualifyingStructures",itemValue:{structureId:r.structureId,drawId:t.drawId}}}),i}function mg({drawDefinition:e,structureDetails:t}){if(!Array.isArray(t))return{error:ys};if(!e)return{error:Li};const r=Object.assign({},...t.map((e=>{if(!mt(e))return;const{structureId:t,structureName:r}=e||{};return t&&r?{[t]:r}:void 0})).filter(Boolean));if(!Object.values(r).length)return{error:Za};for(const t of e.structures||[]){const e=r[t.structureId];e&&(t.structureName=e)}return{...Ni}}function fg({drawDefinition:e,timeItem:t}){if(!e)return{error:Bi};if(!t)return{error:as};const r=t&&Object.keys(t),n=["itemType","itemValue"];if(!(n.filter((e=>r.includes(e))).length===n.length))return{error:ns};e.timeItems||(e.timeItems=[]);const i=(new Date).toISOString();return Object.assign(t,{createdAt:i}),e.timeItems.push(t),Bp({drawDefinition:e}),{...Ni}}function hg(e){const t=e?.matchUp,r=e?.score||t?.score,n=r?.sets?.[0],{side1Score:i,side2Score:a,side1TiebreakScore:o,side2TiebreakScore:s,side1PointScore:c,side2PointScore:u}=n||{},d=i||a||o||s||c||u;return!!(r?.sets?.length>1||d)}function gg({tournamentRecord:e,drawDefinition:t,structureId:r,event:n,force:i}){if("string"!=typeof r)return{error:ys};if(!t)return{error:Li};if(!r)return{error:la};const a=t.structures??[],o=[],s=a.find((e=>e.structureId===r));if(!s)return{error:ma};if(Kf({structure:s}).matchUps.some((({score:e})=>hg({score:e})))){const r=Oh({tournamentRecord:e,drawDefinition:t,structure:s,event:n})?.appliedPolicies;if(!(i??r?.[ad]?.allowDeletionWithScoresPresent?.structures))return{error:ks}}const c=a.find((({stage:e,stageSequence:t})=>e===qp&&1===t)),u=r===c?.structureId,d=a.filter((({stage:e})=>e===$p)).map(au("structureId"));if(u&&!d.length)return{error:Ei};const p=a.map(au("structureId")),l=[],m=d.includes(r),f=new Map;p.forEach((e=>{return f.set(e,m?(r=e,t.links?.map((e=>d.includes(e.source.structureId)&&e.target.structureId===r&&e.source.structureId)).filter(Boolean)??[]):(e=>t.links?.map((t=>t.source.structureId===e&&t.target.structureId!==c?.structureId&&t.target.structureId)).filter(Boolean)??[])(e));var r}));const h=u?f.get(r):[r];for(;h?.length;){const e=h.pop(),{structure:n}=Om({structureId:e,drawDefinition:t}),{matchUps:i}=Kf({structure:n}),a=bd(i);l.push(...a),t.links=t.links?.filter((t=>t.source.structureId!==e&&t.target.structureId!==e))??[],(!u||u&&d.length||e!==r)&&(t.structures=(t.structures??[]).filter((t=>(e&&e===t.structureId&&o.push(e),t.structureId!==e))));const s=e&&f.get(e)?.filter((e=>e!==c?.structureId||r===c.structureId));s?.length&&h.push(...s)}const{matchUps:g}=Em({drawDefinition:t});if(g?.forEach((e=>{e.winnerMatchUpId&&l.includes(e.winnerMatchUpId)&&delete e.winnerMatchUpId,e.loserMatchUpId&&l.includes(e.loserMatchUpId)&&delete e.loserMatchUpId})),u){const e=(c.matchUps??[])?.map(au("matchUpId"));l.push(...e),c.positionAssignments=[],c.seedAssignments=[],c.matchUps=[],c.extensions&&(c.extensions=[])}return m&&tg({drawDefinition:t}),Lp({tournamentId:e?.tournamentId,matchUpIds:l,action:"removeStructure",eventId:n?.eventId,drawDefinition:t}),jp({drawDefinition:t,eventId:n?.eventId}),{...Ni,removedMatchUpIds:l,removedStructureIds:o}}function Ig(e){const{provisionalPositioning:t,drawDefinition:r,stageSequence:n,structureId:i,stage:a}=e;if(!r)return{error:Li};const{entryProfile:o}=rh({drawDefinition:r}),s=a&&n&&o?.[a]?.stageSequence?.[n]?.qualifiersCount||a&&o?.[a]?.qualifiersCount||0,c={};if(!i)return{qualifiersCount:s,roundQualifiersCounts:c};const{structure:u}=Om({drawDefinition:r,structureId:i}),d=r.links?.filter((e=>e?.target?.structureId===u?.structureId));let p=0;if(d?.length)for(const e of d){const n=Om({structureId:e.source.structureId,drawDefinition:r})?.structure;if(n?.stage===$p){const r=e.source.roundNumber,i=e.target.roundNumber;let a=0;if(n.structureType===nl){a=(n.structures?.length??0)*(e.source.finishingPositions?.length??0)}else{const e=Kf({matchUpFilters:{roundNumbers:[r]},structure:n,afterRecoveryTimes:!1,provisionalPositioning:t,inContext:!1}).matchUps;a=e?.length||0}c[i]||(c[i]=0),c[i]+=a,p+=a}}const l=Object.keys(c);if(l.length<=1){const e=l[0]||1;c[e]=Math.max(c[e]||0,s)}return p=Math.max(p,s),{qualifiersCount:p,roundQualifiersCounts:c}}function Ug({stage:e,drawDefinition:t}){const{entryProfile:r}=rh({drawDefinition:t});return r?.[e]?.drawSize||0}function yg({stageSequence:e=1,drawDefinition:t,drawSize:r,stage:n}){if(!t)return{error:Li};if(!nh({drawDefinition:t,stage:n}))return{error:wa};const i=function({stage:e,drawDefinition:t}){return cm.reduce(((r,n)=>(ih({drawDefinition:t,entryStatus:n,stage:e})||0)+r),0)}({drawDefinition:t,stage:n}),{qualifiersCount:a}=Ig({drawDefinition:t,stageSequence:e,stage:n});if(r<i+a)return{error:ea};const{entryProfile:o}=th({attributes:[{[n]:{drawSize:r}}],drawDefinition:t});return jp({drawDefinition:t}),{...Ni,entryProfile:o}}function Sg(e){return function({drawDefinition:e,drawSize:t}){if(!e)return{error:Li};const r=yg({stage:Hp,stageSequence:1,drawDefinition:e,drawSize:t});return r.error?r:(jp({drawDefinition:e}),{...Ni})}(e)}function vg({tournamentRecord:e,drawDefinition:t,participantId:r,structureId:n}){const i="removeSeededParticipant";if(!e)return{error:Fi};if(!t)return{error:Li};const o=(t.structures??[]).find((e=>e.structureId===n));if(!o)return a({result:{error:ma},stack:i});if(!o.stage||![qp,$p].includes(o.stage)||o.stage===qp&&1!==o.stageSequence)return a({result:{error:ji},stack:i});const s=o.seedAssignments?.find((e=>e.participantId===r));return s?{...Ni}:a({info:"participant not seeded",result:{error:ws},context:{participantId:r}})}function Tg({targetEntryRound:e=1,finishingPositions:t,sourceRoundNumber:r,sourceStructureId:n,targetStructureId:i,linkType:a=ul}){if(!n||!i)return{error:la};return{link:Mf({linkType:a,source:{roundNumber:r,structureId:n,finishingPositions:t},target:{feedProfile:il,roundNumber:e,structureId:i}})}}function Pg(e){const{groupNameBase:t="Group",playoffAttributes:r,stageSequence:n=1,structureOptions:i,appliedPolicies:a,seedingProfile:s,stage:c=qp,matchUpType:u,roundTarget:d,structureId:p,groupNames:m,drawSize:f,idPrefix:h,isMock:g,uuids:I}=e,U=e.structureName??r?.[0]?.name??St(qp),{groupCount:y,groupSize:S}=function({appliedPolicies:e,structureOptions:t,drawSize:r}){let n=t?.groupSize;const i=t?.groupSizeLimit||8,{validGroupSizes:a}=Dg({groupSizeLimit:i,drawSize:r}),o=a&&Math.max(...a),s=n&&a?.includes(n);s||(n=n&&n>4||!a?.includes(4)?o:4);const c=Math.ceil(r/n);return{groupSize:n,groupCount:c}}({structureOptions:i,appliedPolicies:a,drawSize:f}),v=Ll;let T;const P=l(1,y+1).map((e=>{const r=function({structureOrder:e,matchUpType:t,groupSize:r,drawSize:n,idPrefix:i,isMock:a,uuids:o}){const s=(e-1)*r,c=l(1+s,r+1+s),u=Ph({drawPositions:c}).uniqueMatchUpGroupings??[],d=wh({groupSize:r,drawPositionOffset:s}),p=u.map(f).sort(((e,t)=>(e.roundNumber??1/0)-(t.roundNumber??1/0)));return p;function m(e){return d.reduce(((t,r,n)=>r.includes(e)?n+1:t),void 0)}function f(r){const s=m(Dh(r)),c=[1,n],u=function({structureOrder:e,drawPositions:t,roundNumber:r,idPrefix:n,uuids:i}){return n?`${n}-${e}-${r}-DP-${t.join("-")}`:i?.pop()||vt()}({structureOrder:e,drawPositions:r,roundNumber:s,idPrefix:i,uuids:o}),d={matchUpStatus:s?Qm:xm,matchUpType:t,finishingPositionRange:{winner:c,loser:c},drawPositions:r,roundNumber:s,matchUpId:u};return a&&(d.isMock=!0),d}}({groupSize:S,structureOrder:e,matchUpType:u,drawSize:f,idPrefix:h,isMock:g});T=Array.isArray(r)?Math.max(...r.map((({roundNumber:e})=>e??0))):0;const n=m?.[e-1]??`${t} ${e}`;return yt({structureId:I?.pop(),structureType:rl,finishingPosition:v,structureOrder:e,structureName:n,matchUps:r})})),D=yt({structureId:p??I?.pop(),structureType:nl,finishingPosition:v,seedingProfile:s,structureName:U,stageSequence:n,structures:P,stage:c});return d&&o({extension:{name:yi,value:d},element:D}),{structures:[D],maxRoundNumber:T,groupCount:y,links:[],groupSize:S,...Ni}}function Dg({drawSize:e,groupSizeLimit:t=10}){const r=l(3,t+1).filter((t=>{const r=Math.ceil(e/t),n=r*t-e,i=Math.ceil(e/r),a=Math.ceil(n/r);return(!n||n<t)&&i===t&&i>=3&&a<2}));return{...Ni,validGroupSizes:r}}function wg({finishingPositionOffset:e=0,finishingPositionLimit:t,positionsFed:r,roundsCount:n,roundLimit:i,matchUps:a,lucky:o,fmlc:s}){if(!Ef(a))return[];const{roundProfile:c,roundNumbers:u=[]}=Cf({interpolate:!0,matchUps:a});n=n??Math.max(...u,0);const d=i?n-i:0,p=d&&c?.[n-d]?.matchUpsCount,l=c&&Object.values(c).map(au("matchUpsCount")),m=(e,r)=>{let n=Math.min(...e);p&&r&&1===n&&(n=p);let i=Math.max(...e);return t&&i>t&&(i=t),[n,i]},f=c&&Object.assign({},...u.map((t=>{const i=(n??0)+1-t-d,a=c[t].matchUpsCount,u={finishingPositionRange:{},finishingRound:i},p=l?.slice(t-1).reduce(((e,t)=>e+(t||0)),0),f=1+e+(s&&1!==t?r??0:0),h=Qd(f,o?f+2*a:p+f+1),g=p+1-a,I=m(h.slice(g)),U=m(h.slice(0,g),!0);return u.finishingPositionRange={loser:I,winner:U},{[t]:u}}))),h=Ks({finishingRound:!0});return a.filter(Boolean).forEach((e=>{const t=e.roundNumber&&f[e.roundNumber];h&&!t&&console.log({roundFinishingData:f,matchUp:e}),e.finishingRound=t?.finishingRound,e.finishingPositionRange=t?.finishingPositionRange})),a}function bg({roundPosition:e,roundNumber:t,idPrefix:r,uuids:n}){return r?`${r}-${t}-${e}`:n?.pop()||bm()}function Rg({includeMatchUpType:e,matchUpType:t,roundNumber:r,matchUps:n,idPrefix:i,isMock:a,uuids:o,nodes:s}){let c=0;const u=[];let d=1;const p=r-1,l=s?.length;for(;c<(l||0);){const l=s?.[c],m=s?.[c+1];p&&(l.roundNumber=p),m&&p&&(m.roundNumber=p);const f={roundPosition:d,children:[l,m],matchUpId:bg({roundPosition:d,roundNumber:r,idPrefix:i,uuids:o})};u.push(f);const h={drawPositions:f.children.map((e=>e?.drawPosition)).filter(Boolean),matchUpStatus:Qm,matchUpId:f.matchUpId,roundPosition:d,roundNumber:r};e&&t&&(h.matchUpType=t),a&&(h.isMock=!0),n.push(h),d++,c+=2}return{roundNodes:u,matchUps:n}}function Ng({finishingPositionOffset:e,finishingPositionLimit:t,qualifyingRoundNumber:r,qualifyingPositions:n,matchUpType:i,roundLimit:a,idPrefix:o,drawSize:s,isMock:c,uuids:u}){if(isNaN(s)||s<2||n&&s<=n)return{matchUps:[],roundsCount:0};if(n&&(!Cd(s)||s%n)){let e=n;for(;e<s;)e*=2;s=e}const d=n&&!(s%2)&&(!isNaN(n)||r&&!isNaN(r))&&(s/n===Math.round(s/n)||r&&s/r===Math.round(s/r));if(!Cd(s)&&!d)return{matchUps:[],roundsCount:0};const p=Qd(1,s+1).map((e=>({drawPosition:e})));let l,m=[],f=1;for(({roundNodes:l,matchUps:m}=Rg({matchUpType:i,roundNumber:f,idPrefix:o,matchUps:m,isMock:c,nodes:p,uuids:u})),f++,a=a??r;l.length>1;)n&&l.length===n&&(a=f-1),({roundNodes:l,matchUps:m}=Rg({nodes:l,matchUpType:i,roundNumber:f,idPrefix:o,matchUps:m,isMock:c,uuids:u})),f++;const h=f-1;return m=wg({finishingPositionOffset:e,finishingPositionLimit:t,roundsCount:h,roundLimit:a,matchUps:m}),a?m=m.filter((e=>a&&(e.roundNumber??0)<=a)):a=f-1,{drawSize:s,matchUps:m,roundsCount:h,roundLimit:a}}function Mg(e){const t="generateQualifyingStructure";if(!e.drawDefinition)return pd({result:{error:Li},stack:t});if(e.drawSize&&!Vd(e.drawSize)||e.participantsCount&&!Vd(e.participantsCount)||e.qualifyingPositions&&!Vd(e.qualifyingPositions))return pd({result:{error:ys},stack:t});let r=e.drawSize??Od(e.participantsCount);const{qualifyingRoundNumber:n,qualifyingPositions:i,targetStructureId:a,structureOptions:o,appliedPolicies:s,drawDefinition:c,matchUpFormat:u,structureName:d,structureId:p,roundTarget:l,drawType:m,idPrefix:f,isMock:h,uuids:g}=e;if(!e.drawSize)return pd({result:{error:ta},context:{drawSize:r},stack:t});if(i&&i>=e.drawSize)return pd({result:{error:ys},context:{drawSize:r,qualifyingPositions:i},stack:t});let I,U,y,S,v,T=0;const{structureProfiles:P}=eg({drawDefinition:c}),D=P[a];if(!D)return pd({result:{error:ma},context:{targetStructureId:a},stack:t});const w=c.matchUpType,b=l?`${l}-`:"",R=D.stage===$p,N=s?.[ed]?.namingConventions?.pre??kf[ed]?.namingConventions?.pre,M=R&&N?`${N}-`:"",A=d??(b?`${M}${wm($p)} ${b}`:`${M}${wm($p)}`);if(m===Cl){const{maxRoundNumber:e,structures:t,groupCount:n}=Pg({structureName:d??A,structureId:p??g?.pop(),stage:$p,structureOptions:o,appliedPolicies:s,stageSequence:1,matchUpType:w,roundTarget:l,idPrefix:f,drawSize:r,isMock:h,uuids:g});T=n,I=e,y=t[0],v=[1]}else({drawSize:r,matchUps:S,roundLimit:I,roundsCount:U}=Ng({qualifyingRoundNumber:n,qualifyingPositions:i,matchUpType:w,idPrefix:f,drawSize:r,isMock:h,uuids:g})),I||(I=U),y=Rm({structureName:d??A,structureId:p??g?.pop(),qualifyingRoundNumber:I,stage:$p,matchUpFormat:u,stageSequence:1,matchUpType:w,roundLimit:I,matchUps:S}),l&&gd({extension:{name:yi,value:l},element:y}),T=S?.filter((e=>e.roundNumber===I))?.length;const E=m===Cl?cl:ul,C=y&&I&&Tg({sourceStructureId:y.structureId,sourceRoundNumber:I,targetStructureId:a,finishingPositions:v,linkType:E})?.link;return{qualifyingDrawPositionsCount:r,qualifiersCount:T,...Ni,structure:y,link:C}}function Ag(e){const t=e.tournamentRecord;if(!t)return{error:Fi};const r=function(e){if(!e.drawDefinition)return{error:Li};if(!e.targetStructureId)return{error:la};const t=Mg(e);if(t.error)return t;const{structure:r,link:n}=t;return r&&n?lg({tournamentRecord:e.tournamentRecord,drawDefinition:e.drawDefinition,structure:r,link:n}):{error:ys}}(e);if(r.error)return r;const{qualifyingRoundNumber:n,qualifyingPositions:i,targetStructureId:a,drawDefinition:o,structureName:s,matchUpType:c,drawSize:u,drawType:d}=e;return dg({tournamentRecord:t,timeItem:{itemType:"addQualifyingStructures",itemValue:Mf({drawId:o.drawId,qualifyingRoundNumber:n,qualifyingPositions:i,targetStructureId:a,structureName:s,matchUpType:c,drawSize:u,drawType:d})}}),r}function Eg(e){if(!e)return;const{tieFormatId:t,tieFormats:r}=e;return e.tieFormat?e.tieFormat:t&&Array.isArray(r)?r.find((e=>e.tieFormatId===t)):void 0}function Cg({item:e,drawDefinition:t,structure:r,event:n}){if(e){if(e.tieFormat)return e.tieFormat;if(e.tieFormatId){if(t.tieFormat)return t.tieFormat;const r=t.tieFormats?.find((t=>e.tieFormatId===t.tieFormatId));return r||(n.tieFormat?n.tieFormat:n.tieFormats?.find((t=>e.tieFormatId===t.tieFormatId)))}if(r.tieFormat)return r.tieFormat;if(r.tieFormatId){const e=t.tieFormats?.find((e=>r.tieFormatId===e.tieFormatId));if(e)return e}}}function Og({drawDefinition:e,structure:t,matchUp:r,event:n}){return{tieFormat:Cg({item:r,drawDefinition:e,structure:t,event:n})||Cg({item:t,drawDefinition:e,structure:t,event:n})||Eg(e)||Eg(n)}}function Fg({includeMatchUpType:e,drawPosition:t,roundNumber:r,matchUpType:n,idPrefix:i,matchUps:a,isMock:o,uuids:s,nodes:c,fed:u}){const d=c.length,p=t?t-d:void 0,l=Qd(0,d).map((e=>p?p+e:void 0)),m=[];for(let t=0;t<d;t++){const d=l.shift(),p={drawPosition:d,fed:u+1,feed:!0},f=c[t];f.roundNumber=r-1;const h=bg({roundPosition:f.roundPosition,roundNumber:r,idPrefix:i,uuids:s}),g={roundPosition:f.roundPosition,drawPositions:[d],matchUpStatus:Qm,roundNumber:r,matchUpId:h};e&&(g.matchUpType=n),o&&(g.isMock=!0),a.push(g);const I={children:[f,p]};m.push(I)}return{roundNodes:m,matchUps:a,drawPosition:t?t-d:void 0}}function kg(e){const t=e.drawSize;let{feedRoundsProfile:r,feedRounds:n=0,skipRounds:i=0,baseDrawSize:a}=e;const{linkFedFinishingRoundNumbers:o,finishingPositionOffset:s,linkFedRoundNumbers:c,feedsFromFinal:u,isConsolation:d,matchUpType:p,idPrefix:l,isMock:m,uuids:f,fmlc:h}=e;a=a??function(e){const t=Fd(e);return t>e?t/2:t}(t);const g=function({drawSize:e}){const t=Math.ceil(Math.log(e)/Math.log(2));return Qd(0,t).reverse().map((e=>Math.pow(2,e)))}({drawSize:a}),I=g.length;let U=0;if(r?.length)U=r.reduce(((e,t)=>e+t),0);else if(t){let e=t-a;r=g.filter((t=>t<=e&&(e-=t,!0))),U=r.reduce(((e,t)=>e+t),0),n=r.length}else i>=I?n=0:u&&(n=I-u,i=0),r=g.filter(((e,t)=>u&&!n||n&&t>=i+n||t<i?0:e)),U=r.reduce(((e,t)=>e+t),0),n=r.length;const y=[...g,...r].sort(((e,t)=>t-e)),S=y.length,v=[...(c??[]).map((e=>e-1)),...(o??[]).map((e=>S-e))].map((e=>y[e])).reduce(((e,t)=>e+t),0);U-=v;let T,P=0,D=[],w=1;let b=Qd(0,a).map(((e,t)=>({drawPosition:t+1+U}))),R=U+1;for(const e of g){if(({roundNodes:T,matchUps:D}=Rg({matchUpType:p,roundNumber:w,idPrefix:l,matchUps:D,isMock:m,nodes:b,uuids:f})),w++,r.includes(e)){const t=Qd(0,$d(r)[e]),n=S+1-w,i=o?.includes(n)??c?.includes(w);t.forEach((()=>{const e=!i&&R||void 0;({roundNodes:T,matchUps:D,drawPosition:R}=Fg({drawPosition:e,nodes:T,matchUpType:p,roundNumber:w,idPrefix:l,matchUps:D,isMock:m,uuids:f,fed:P})),w++,P+=1}))}b=T}S!==w-1&&console.log("ERROR");D=wg({finishingPositionOffset:d?a-U:s,positionsFed:U,roundsCount:S,matchUps:D,fmlc:h});const N=T?.length?T[0]:T;return N&&(N.roundNumber=w-1,N.matchUps=D),{draw:N,matchUps:D,roundsCount:S}}function _g(e){const{finishingPositionOffset:t=0,playoffAttributes:r,stageSequence:n=1,staggeredEntry:i,structureName:a,stage:o=qp,matchUpType:s,structureId:c,idPrefix:u,drawSize:d,isMock:p,uuids:l}=e,m={finishingPositionOffset:t,matchUpType:s,drawSize:d,idPrefix:u,isMock:p,uuids:l},{matchUps:f}=i?kg(m):Ng(m),h=Rm({structureName:a||r?.[0]?.name||wm(qp),structureId:c||l?.pop(),stageSequence:n,matchUpType:s,matchUps:f,stage:o}),g=[h],I=[];if(d>2){const n=d/2,{matchUps:i}=Ng({finishingPositionOffset:t+n,idPrefix:u&&`${u}-c`,drawSize:n,matchUpType:s,isMock:p}),o=wm(Wp),c=r?.["0-1"]?.name??e.consolationStructureName??(a?`${a} ${o}`:o),m=Rm({structureName:c,matchUps:i,structureId:l?.pop(),stage:Wp,stageSequence:1,matchUpType:s});g.push(m);const f={linkType:dl,source:{roundNumber:1,structureId:h.structureId},target:{roundNumber:1,feedProfile:ol,structureId:m.structureId}};I.push(f)}return{...Ni,structures:g,links:I}}function xg({consolationStructure:e,roundOffset:t=0,mainStructure:r,roundsCount:n,feedPolicy:i,fmlc:a}){const o=e.matchUps.reduce(((e,t)=>(t.drawPositions||[]).filter(Boolean).length&&!e.includes(t.roundNumber)?e.concat(t.roundNumber):e),[]),s=i?.roundGroupedOrder||[],c=i?.roundFeedProfiles;return Qd(1+t,n+1+t).map((n=>{const i=c&&c[n-1]?c[n-1]:n%2?ol:sl,u=n-t<=2?n-t:2*(n-t-2)+2,d={linkType:dl,source:{roundNumber:n,structureId:r.structureId},target:{feedProfile:i,roundNumber:u,structureId:e.structureId}},p=s[n-1];return p&&(d.target.groupedOrder=p),Ks()&&(d.source.structureName=r.structureName,d.target.structureName=e.structureName),2===n&&a&&(d.linkCondition=pl,d.target.feedProfile=ol),o.includes(u)?d:void 0})).filter(Boolean)}function Lg(e){const{playoffStructureNameBase:t,finishingPositionOffset:r,stageSequence:n=1,playoffAttributes:i,structureNameMap:a,staggeredEntry:o,stage:s=qp,matchUpType:c,structureId:u,drawSize:d,idPrefix:p,isMock:l,uuids:m}=e,f={finishingPositionOffset:r,matchUpType:c,drawSize:d,idPrefix:p,isMock:l,uuids:m},{matchUps:h,roundsCount:g}=o?kg(f):Ng(f),I=e.structureName??i?.[0]?.name??wm(qp),U=Rm({structureId:u||m?.pop(),structureName:I,stageSequence:n,matchUpType:c,matchUps:h,stage:s}),y=[U],S=[];if(d>2){const e=[0,2].slice(0,d/16).map(((e,r)=>{const n=r+1,{consolationStructure:o}=function({playoffStructureNameBase:e,stageSequence:t=1,playoffAttributes:r,structureNameMap:n,roundOffset:i=0,matchUpType:a,structureId:o,idPrefix:s,drawSize:c,isMock:u,index:d,uuids:p}){const l=c/(2*Math.pow(2,i)),{matchUps:m,roundsCount:f}=kg({finishingPositionOffset:l,baseDrawSize:l,isConsolation:!0,feedRounds:1,matchUpType:a,idPrefix:s,isMock:u,uuids:p}),h=0===d&&r?.["0-1"]?.name||1===d&&r?.["0-3"]?.name,g=h||`${wm(Wp)} ${d+1}`,I=n?.[g]||g,U=e?`${e} ${I}`:I,y=Rm({matchUps:m,stage:Wp,structureName:U,stageSequence:t,matchUpType:a,structureId:o});return{consolationStructure:y,consolationRoundsCount:f}}({idPrefix:p&&`${p}-c${r}`,structureId:m?.pop(),playoffStructureNameBase:t,playoffAttributes:i,structureNameMap:a,stageSequence:n,roundOffset:e,matchUpType:c,drawSize:d,isMock:l,index:r,uuids:m});y.push(o);return{consolationStructure:o,links:xg({consolationStructure:o,roundsCount:2,mainStructure:U,roundOffset:e})}})),r=e.map((e=>e.links)).flat();if(S.push(...r),d>=4&&d<=16||d>32){const{matchUps:e}=Ng({idPrefix:p&&`${p}-p3t4`,finishingPositionOffset:2,drawSize:2,matchUpType:c,isMock:l}),r=i?.["3-4"]?.name??wm(zp),n=a?.[r]||r,o=t?`${t} ${n}`:n,s=Rm({structureId:m?.pop(),matchUps:e,stageSequence:2,stage:zp,structureName:o,matchUpType:c}),u={linkType:dl,source:{roundNumber:g-1,structureId:U.structureId},target:{structureId:s.structureId,feedProfile:ol,roundNumber:1}};y.push(s),S.push(u)}}return{structures:y,links:S,...Ni}}function Vg(e){const{finishingPositionOffset:t,stageSequence:r=1,playoffAttributes:n,policyDefinitions:i,feedsFromFinal:a,staggeredEntry:o,structureName:s,stage:c=qp,structureId:u,matchUpType:d,skipRounds:p,feedRounds:l,idPrefix:m,drawSize:f,isMock:h,uuids:g,fmlc:I}=e,U=e.feedPolicy||i?.[sd],y={finishingPositionOffset:t,matchUpType:d,skipRounds:p,drawSize:f,idPrefix:m,isMock:h,uuids:g},{matchUps:S}=o?kg(y):Ng(y),v=Rm({structureName:s||n?.[0]?.name||wm(qp),structureId:u||g?.pop(),stageSequence:r,matchUpType:d,matchUps:S,stage:c}),T=[v],P=[],D=f/2,{matchUps:w,roundsCount:b}=kg({finishingPositionOffset:D,idPrefix:m&&`${m}-c`,isConsolation:!0,feedsFromFinal:a,baseDrawSize:D,matchUpType:d,feedRounds:l,skipRounds:p,isMock:h,uuids:g,fmlc:I});if(f>2){const t=n?.["0-1"]?.name??wm(Wp),r=e.playoffStructureNameBase?`${e.playoffStructureNameBase} ${t}`:t,i=Rm({matchUps:w,structureId:g?.pop(),stage:Wp,stageSequence:1,structureName:r,matchUpType:d});T.push(i);const a=xg({consolationStructure:i,mainStructure:v,roundsCount:b,feedPolicy:U,fmlc:I});P.push(...a)}return{...Ni,structures:T,links:P}}const Bg="WALKOVER",jg="RETIRED",Gg="COMPETITIVE",qg="ROUTINE",$g="DECISIVE",Wg="winRatio";function Hg({requireSequential:e=!0,playoffMatchUpFormat:t,playoffAttributes:r,sourceStructureId:n,policyDefinitions:i,stageSequence:o,drawDefinition:s,playoffGroups:c,matchUpType:u,feedPolicy:d,groupCount:p,idPrefix:l,isMock:m,uuids:f}){d=d||i?.[sd];const h="processPlayoffGroups";let g=0;const I=[],U=[],y=[],{error:S,positionRangeMap:v}=Pt({structureId:n,drawDefinition:s,playoffGroups:c});if(S)return a({result:{error:S},stack:h});if(!(!v||c?.every((t=>{const{finishingPositions:r=[]}=t;if(!r.length)return!1;const n=[...r].sort(fe).map(((e,t)=>(r[t+1]||e)-e)).every((e=>e<2));return(!e||n)&&r.every((e=>v[e]))}))))return a({context:{validFinishingPositions:Object.values(v)},result:{error:ys},stack:h});for(const e of c){const a=e.finishingPositions,s=v&&a.map((e=>v[e]?.finishingPositions)).flat(),c=p*a.length,h=Le(c),S=2===h&&gl||e.drawType||gl;s&&(g=Math.min(...s)-1);const T=s&&`${Math.min(...s)}-${Math.max(...s)}`,P=e.structureName||T&&e.playoffAttributes?.[T]?.name||e.playoffAttributes?.[0]?.name,D={...{addNameBaseToAttributeName:e.addNameBaseToAttributeName,playoffStructureNameBase:e.playoffStructureNameBase,finishingPositionNaming:e.finishingPositionNaming,finishingPositionLimit:e.finishingPositionLimit,structureId:e.structureId??f?.pop(),playoffAttributes:e.playoffAttributes,structureNameMap:e.structureNameMap,sequenceLimit:e.sequenceLimit,structureName:P},idPrefix:l&&`${l}-po`,appliedPolicies:i,finishingPositionOffset:g,stage:zp,stageSequence:o,matchUpType:u,drawSize:h,isMock:m,uuids:f},w=({playoffStructures:e,playoffLinks:t})=>{const[r]=e,i=zg({playoffStructureId:r.structureId,finishingPositions:a,sourceStructureId:n});y.push(i),y.push(...t),U.push(...e),I.push({structureId:r.structureId,finishingPositions:a}),g+=c};if(S===gl){const{matchUps:r}=Ng({finishingPositionLimit:g+c,idPrefix:l&&`${l}-po`,finishingPositionOffset:g,matchUpType:u,drawSize:h,isMock:m,uuids:f}),i=Ut({structureId:e.structureId??f?.pop(),matchUpFormat:t,stage:zp,structureName:P,stageSequence:o,matchUps:r});U.push(i);const s=zg({playoffStructureId:i.structureId,finishingPositions:a,sourceStructureId:n});y.push(s),g+=c,I.push({structureId:i.structureId,finishingPositions:a})}else if([fl,hl,zp].includes(S)){const t={playoffAttributes:e.playoffAttributes??r,playoffStructureNameBase:e.playoffStructureNameBase,structureId:e.structureId??f?.pop(),structureName:e.structureName,idPrefix:l&&`${l}-po`,addNameBaseToAttributeName:!0,finishingPositionOffset:g,stage:zp,roundOffset:0,stageSequence:o,drawSize:h,isMock:m,uuids:f};S===fl?Object.assign(t,{playoffAttributes:e?.playoffAttributes??r??_l,roundOffsetLimit:3}):S===hl&&Object.assign(t,{playoffAttributes:e?.playoffAttributes??r??xl,roundOffsetLimit:2});const i=Tt(t);if(i.error)return i;if(i.links?.length&&y.push(...i.links),i.structures?.length&&U.push(...i.structures),U.sort(V),i.structureId){const e=zg({playoffStructureId:i.structureId,finishingPositions:a,sourceStructureId:n});y.push(e),I.push({structureId:i.structureId,finishingPositions:a})}g+=c}else if([Ul,El,Nl,bl,Dl,Al].includes(S)){const t=[f?.pop(),f?.pop()],r={playoffStructureNameBase:e.playoffStructureNameBase,structureId:e.structureId??f?.pop(),playoffAttributes:e.playoffAttributes,idPrefix:l&&`${l}-po`,finishingPositionOffset:g,uuids:t,stage:zp,structureName:P,matchUpType:u,feedPolicy:d,drawSize:h,isMock:m},i={[Ul]:{fmlc:!0,feedRounds:1},[Al]:{feedRounds:1},[Nl]:{feedsFromFinal:3},[bl]:{feedsFromFinal:2},[Dl]:{feedsFromFinal:1}};Object.assign(r,i[S]||{});const{structures:o,links:s}=Vg(r),[p]=o,v=zg({playoffStructureId:p.structureId,finishingPositions:a,sourceStructureId:n});y.push(v),y.push(...s),U.push(...o),I.push({structureId:p.structureId,finishingPositions:a}),g+=c}else if([Cl].includes(S)){const{structures:t,links:r}=Pg({...D,structureOptions:e.structureOptions||{groupSize:4}});w({playoffStructures:t,playoffLinks:r})}else if([yl].includes(S)){const{structures:e,links:t}=_g(D);w({playoffStructures:e,playoffLinks:t})}else if([Tl].includes(S)){const{structures:e,links:t}=Lg(D);w({playoffStructures:e,playoffLinks:t})}else if([ll].includes(S)){w({playoffStructures:[Ut({structureId:e.structureId??f?.pop(),structureName:e.structureName,finishingPosition:Wg,stage:zp,stageSequence:o,matchUps:[]})],playoffLinks:[]})}}return{finishingPositionTargets:I,positionRangeMap:v,structures:U,links:y}}function zg({playoffStructureId:e,finishingPositions:t,sourceStructureId:r}){return{linkType:cl,source:{structureId:r,finishingPositions:t},target:{structureId:e,feedProfile:il,roundNumber:1}}}function Yg({matchUp:e,tieFormat:t,isMock:r,uuids:n}){const{collectionDefinitions:i}=t??{},a=(i??[]).map((t=>function({collectionPositionOffset:e=0,collectionDefinition:t,matchUpsLimit:r,matchUp:n,isMock:i,uuids:a}){const{matchUpCount:o,matchUpType:s,collectionId:c,processCodes:u}=t||{},d=e=>{if(!i&&!n?.isMock)return a?.pop()??bm();const r=t?.collectionId;return a?.pop()??`${n?.matchUpId}-${r}-TMU-${e+1}`};return Qd(0,r??o??0).map((t=>{const r=e+t+1;return{sides:[{sideNumber:1},{sideNumber:2}],matchUpId:d(t),matchUpStatus:Qm,collectionPosition:r,collectionId:c,processCodes:u,matchUpType:s,isMock:i}}))}({matchUp:e,collectionDefinition:t,uuids:n,isMock:r}))).filter(Boolean).flat();return{tieMatchUps:a}}function Qg(e){const{finishingPositionOffset:t=0,addNameBaseToAttributeName:r,playoffStructureNameBase:n,finishingPositionNaming:i,finishingPositionLimit:a,playoffAttributes:o,stageSequence:s=1,exitProfile:c="0",exitProfileLimit:u,roundOffsetLimit:d,roundOffset:p=0,drawDefinition:l,staggeredEntry:m,sequenceLimit:f,stage:h=qp,drawSize:g,idPrefix:I,isMock:U,uuids:y}=e;if(!(!o||!u||o?.[c])||g<2||f&&s>f)return{};const S=[],v=[],T=[],P=e.matchUpType??l?.matchUpType,D=t+1,w=`${D}-${t+g}`,b=o?.[c],R=n&&`${n} `||"",N=o?.[w]??i?.[w],M=e.structureName||N?.name||b?.name&&(r?`${R}${b?.name}`:b.name)||`${R}${w}`,A=N?.abbreviation??b?.abbreviation,E=e.structureId??b?.structureId??y?.pop(),C={idPrefix:I&&`${I}-${M}-RP`,finishingPositionOffset:t,matchUpType:P,drawSize:g,isMock:U,uuids:y},{matchUps:O}=m?kg(C):Ng(C),F=Rm({structureAbbreviation:A,stageSequence:s,structureName:M,matchUpType:P,roundOffset:p,structureId:E,matchUps:O,stage:h});S.push(...O),v.push(F);const k=Math.ceil(Math.log(g)/Math.log(2)),_=d?Math.min(d-p,k):!a||D<a?k:0;return g>2&&Qd(1,_+1).forEach((e=>function(e){const m=g/Math.pow(2,e);if(m<2)return;const U=g/Math.pow(2,e)+t;if(a&&U+1>a)return;const{structures:D,structureId:w,matchUps:b,links:R}=Qg({finishingPositionOffset:U,exitProfile:`${c}-${e}`,roundOffset:p+e,stageSequence:s+1,drawSize:m,addNameBaseToAttributeName:r,playoffStructureNameBase:n,finishingPositionNaming:i,finishingPositionLimit:a,playoffAttributes:o,exitProfileLimit:u,roundOffsetLimit:d,drawDefinition:l,sequenceLimit:f,matchUpType:P,idPrefix:I,uuids:y,stage:h});if(F.structureId&&w){const t={linkType:dl,source:{roundNumber:e,structureId:F.structureId},target:{roundNumber:1,feedProfile:ol,structureId:w}};R&&F&&R.push(t),R?.length&&T.push(...R)}D?.length&&v.push(...D);b?.length&&S.push(...b);return{structureId:w,childLinks:R,structures:v}}(e))),{structureId:F.structureId,matchUps:S,structureName:M,structures:v,links:T,...Ni}}function Kg(e){const t="genPlayoffStructure";if(!e.drawDefinition)return a({result:{error:Li},stack:t});const r=Dt(e);if(r.error)return a({result:r,stack:t});const{structureId:n,addNameBaseToAttributeName:i,playoffStructureNameBase:o,finishingPositionNaming:s,finishingPositionLimit:c,playoffAttributes:u,playoffPositions:d,roundOffsetLimit:p,tournamentRecord:l,exitProfileLimit:m,roundProfiles:f,roundNumbers:h,idPrefix:g,isMock:I,event:U,uuids:y}=e,S=L(e.drawDefinition,!1,!0),{structure:v}=w({structureId:n,drawDefinition:S});if(!v)return a({result:{error:ma},stack:t});if(v.structureType===nl||v.structures)return function(e){const t="generateAndPopulateRRplayoffStructures";if(!e.playoffGroups)return pd({result:{error:Za},info:"playoffGroups required",stack:t});const{sourceStructureId:r,requireSequential:n,tournamentRecord:i,drawDefinition:a,playoffGroups:o,groupCount:s,groupSize:c,event:u}=e,{structures:d=[],links:p=[],finishingPositionTargets:l,positionRangeMap:m,error:f}=Hg({requireSequential:n,sourceStructureId:r,playoffGroups:o,groupCount:s,groupSize:c,...e});if(f)return{error:f};const h=l?.map((({finishingPositions:e})=>e)).flat().map((e=>m[e].finishingPositions)).flat();a.structures.push(...d),a.links.push(...p);const{matchUps:g,matchUpsMap:I}=Em({inContext:!0,drawDefinition:a}),U=d.map((({structureId:e})=>e)),y=g?.filter((({structureId:e})=>U.includes(e))).map(Nd),S=I?.drawMatchUps?.filter((({matchUpId:e})=>y?.includes(e)));if(S?.length){const t=Og({drawDefinition:a,event:u})?.tieFormat;t&&S.forEach((r=>{const{tieMatchUps:n}=Yg({isMock:e.isMock,tieFormat:t,matchUp:r});Object.assign(r,{tieMatchUps:n,matchUpType:gf})}))}const{positionAssignments:v}=op({structureId:r,drawDefinition:a}),T={};v?.forEach((e=>{const t=Wl({element:e,name:Di}),r=t?.extension?.value,n=r?.groupOrder;n&&(T[n]||(T[n]=[]),T[n].push(e.participantId))}));const P=Zh({provisionalPositioning:e.provisionalPositioning,structureId:r,applyPositioning:!0,event:e.event,tournamentRecord:i,drawDefinition:a});return P.error&&P.error?.code!==Gi.code?pd({result:P,stack:t}):{structures:d,links:p,positionsPlayedOff:h,drawDefinition:a,...Ni}}({sourceStructureId:v.structureId,...e,...r,drawDefinition:S});const{playoffRoundsRanges:P,playoffRounds:D}=r,{playoffPositionsReturned:b,error:N,playoffSourceRounds:M,playoffRoundsRanges:A}=Rt(e);if(N)return a({result:{error:N},stack:t});const E=f?.length&&Object.assign({},...f),C=h||"object"==typeof f&&f.map((e=>Object.keys(e))).flat(),O=Array.isArray(C)&&C.map((e=>!isNaN(e)&&ve(e))).filter(Boolean);if(O){if(!Array.isArray(O))return a({result:{error:ys},context:{validRoundNumbers:O},stack:t});O.forEach((e=>{if(!D?.includes(e))return a({result:{error:ys},context:{roundNumber:e},stack:t})}))}d&&d.forEach((e=>{if(!b?.includes(e))return a({result:{error:ys},context:{playoffPosition:e},stack:t})}));const F=O||M,k=O?P:A,_=[],x=[];for(const e of F??[]){const r=k?.find((t=>t.roundNumber===e));if(!r)return a({result:{error:ys},context:{roundNumber:e},stack:t});const d=r.finishingPositions.length,l=Math.min(...r.finishingPositions)-1,f=2,h=e&&E?.[e]&&f+E[e]-1,U=Qg({exitProfile:`0-${e}`,addNameBaseToAttributeName:i,playoffStructureNameBase:o,finishingPositionOffset:l,playoffAttributes:u,exitProfileLimit:m,stage:zp,roundOffset:0,drawDefinition:S,sequenceLimit:h,stageSequence:f,drawSize:d,idPrefix:g,isMock:I,uuids:y,finishingPositionNaming:s,finishingPositionLimit:c,roundOffsetLimit:p});if(U.error)return a({result:U,stack:t});const{structures:v,links:T}=U;if(v?.length&&_.push(...v),T?.length&&x.push(...T),U.structureId&&e){const t={linkType:dl,source:{structureId:n,roundNumber:e},target:{structureId:U.structureId,feedProfile:ol,roundNumber:1}};x.push(t)}}if(!_.length)return a({result:{error:ys},info:"No structures generated",stack:t});S.structures.push(..._),S.links.push(...x);const{matchUps:V,matchUpsMap:B}=ue({inContext:!0,drawDefinition:S}),j=_.map((({structureId:e})=>e)),G=V?.filter((({structureId:e})=>j.includes(e))).map(T),q=B?.drawMatchUps?.filter((({matchUpId:e})=>G?.includes(e)));if(q?.length){const e=we({drawDefinition:S,event:U})?.tieFormat;e&&q.forEach((t=>{const{tieMatchUps:r}=Yg({matchUp:t,tieFormat:e,isMock:I});Object.assign(t,{tieMatchUps:r,matchUpType:If})}))}const $=V?.filter((e=>qe({matchUp:e})&&e.structureId===n));$?.forEach((e=>{const{matchUpId:t,score:r,winningSide:n}=e,i=de({inContextDrawMatchUps:V,drawDefinition:S,matchUpId:t}),a=wt({inContextDrawMatchUps:V,tournamentRecord:l,drawDefinition:S,matchUpsMap:B,winningSide:n,targetData:i,matchUpId:t,structure:v,matchUp:e,score:r,event:U});a.error&&console.log(a.error)}));const W=V?.filter((e=>e.matchUpStatus===xm&&e.structureId===n));W?.forEach((e=>{const{matchUpId:t}=e,r=de({inContextDrawMatchUps:V,drawDefinition:S,matchUpId:t}),{targetLinks:{loserTargetLink:n},targetMatchUps:{loserMatchUpDrawPositionIndex:i,loserMatchUp:a}}=r;if(n&&a){const e=n.target.structureId,t=a.drawPositions[i],r=R({drawPosition:t,structureId:e,tournamentRecord:l,drawDefinition:S,event:U});r.error&&console.log(r.error)}}));const H=[],z=bt({inContextDrawMatchUps:V,drawDefinition:S,matchUpsMap:B}).goesToMap,{structure:Y}=w({drawDefinition:e.drawDefinition,structureId:n}),{matchUps:Q}=J({structure:Y});return Q.forEach((r=>{const n=z?.loserMatchUpIds[r.matchUpId];if(n&&r.loserMatchUpId!==n){r.loserMatchUpId=n;const i={tournamentId:l?.tournamentId,eventId:e.event?.eventId,context:t,matchUp:r};H.push(i)}const i=z?.winnerMatchUpIds[r.matchUpId];if(i&&r.winnerMatchUpId!==i){r.winnerMatchUpId=i;const n={tournamentId:l?.tournamentId,eventId:e.event?.eventId,context:t,matchUp:r};H.push(n)}})),{structures:_,matchUpModifications:H,links:x,drawDefinition:S,...Ni}}function Jg({inContextDrawMatchUps:e,drawDefinition:t,matchUpsMap:r}){if(!t)return{error:Li};const n={loserMatchUpIds:{},winnerMatchUpIds:{}};e||({matchUps:e,matchUpsMap:r}=ue({inContext:!0,drawDefinition:t,matchUpsMap:r}));const i=r?.drawMatchUps.some((e=>e.finishingPositionRange));if(!i&&1===t?.structures?.length&&!t?.structures[0].structures){Et({matchUps:r?.drawMatchUps??[]})}return(e??[]).filter((({collectionId:e})=>!e)).forEach((i=>{const{matchUpId:a,structureId:o}=i,s=de({inContextDrawMatchUps:e,drawDefinition:t,matchUpId:a}),{winnerMatchUp:c,loserMatchUp:u}=s.targetMatchUps,d=c?.matchUpId,p=u?.matchUpId,l=ce({matchUpsMap:r,structureId:o}).find((e=>e.matchUpId===a));if(l&&(d&&(n.winnerMatchUpIds[l.matchUpId]=d,Object.assign(l,{winnerMatchUpId:d}),Object.assign(i,{winnerMatchUpId:d})),p&&(n.loserMatchUpIds[l.matchUpId]=p,i.loserMatchUpId=p,l.loserMatchUpId=p,i.finishingPositionRange))){const e=u.finishingPositionRange&&[...i.finishingPositionRange.loser,...u.finishingPositionRange.loser],t=e&&[Math.min(...e),Math.max(...e)];i.finishingPositionRange.loser=t,l.finishingPositionRange.loser=t}})),{inContextDrawMatchUps:e,goesToMap:n}}function Zg(e){return eI({...e,itemType:"attachConsolationStructures"})}function Xg(e){return eI({...e,itemType:"attachPlayoffStructures"})}function eI({itemType:e="attachStructures",matchUpModifications:t,tournamentRecord:r,drawDefinition:n,structures:i,links:o=[],event:s}){const c="attachStructures";if(!n)return{error:Li};if(!Array.isArray(i)||!Array.isArray(o))return a({result:{error:ys},stack:c});const u=e=>[e.source.structureId,e.source.roundNumber||e.source.finishingPositions?.join("|"),e.target.roundNumber].join("|"),d=n.links?.map(u);if(o.some((e=>{const t=u(e);return d?.includes(t)})))return a({result:{error:Cs},info:"playoff structure exists",stack:c});o.length&&n.links?.push(...o);const p=i.map((({structureId:e})=>e)),l=n.structures?.map((({structureId:e})=>e));n.structures=(n.structures??[]).map((e=>p.includes(e.structureId)?i.find((({structureId:t})=>t===e.structureId)):e));const m=i?.filter((({structureId:e})=>!l?.includes(e)));m.length&&n.structures.push(...m),Jg({drawDefinition:n});const f=i.map((e=>J({structure:e})?.matchUps||[])).flat();W({tournamentId:r?.tournamentId,eventId:s?.eventId,drawDefinition:n,matchUps:f});const h=i.map((({structureId:e})=>e));if($({drawDefinition:n,structureIds:h}),t?.length){const e={};t.forEach((t=>{const r=t.matchUp?.matchUpId;r&&(e[r]=t)}));const r=t=>{t.matchUps.forEach((t=>{if(e[t.matchUpId]){const{tieMatchUps:r,...n}=e[t.matchUpId].matchUp;if(Object.assign(t,n),r?.length){const n={};r.forEach((t=>e[t.matchUpId]=t)),t.tieMatchUps.forEach((e=>Object.assign(e,n[e.matchUpId])))}e[t.matchUpId].matchUp=t,q(e[t.matchUpId])}}))};n.structures.forEach((e=>{if(l?.includes(e.structureId))if(e.structures)for(const t of e.structures)r(t);else r(e)}))}const g=m.map(ft("structureId"));if(r){const t={structureIds:h,drawId:n.drawId};Nt({element:r,timeItem:{itemValue:t,itemType:e}})}return{...Ni,addedStructureIds:g}}function tI(e){const{structures:t,links:r,matchUpModifications:n,error:i}=Kg(e);if(i)return{error:i};const a=e.drawDefinition;return Xg({tournamentId:e.tournamentRecord?.tournamentId,eventId:e.event?.eventId||e.eventId,matchUpModifications:n,drawDefinition:a,structures:t,links:r})}function rI({tournamentRecord:e,drawDefinition:t,flightProfile:n,drawName:i,drawId:o,event:s}){if(!i||"string"!=typeof i)return a({result:{error:ys},context:{drawName:i}});n||(n=Ot({event:s}).flightProfile);const c=n?.flights?.find((e=>e.drawId===o));if(c){c.drawName=i;const e={name:pi,value:{...n,flights:n.flights}};r({event:s,extension:e})}return t&&(t.drawName=i,$({tournamentId:e?.tournamentId,drawDefinition:t})),c||t?{...Ni,flight:c}:{error:Li}}function nI({tournamentRecord:e,drawDefinition:t,drawUpdates:n,drawId:i,event:a}){if(!mt(n))return{error:ys};const o=Ot({event:a}).flightProfile,s=n.drawName&&rI({drawName:n.drawName,tournamentRecord:e,drawDefinition:t,flightProfile:o,drawId:i,event:a});if(s?.error)return s?.error;const c=s?.flight||o?.flights?.find((e=>e.drawId===i));if(!c&&!t)return{error:Li};if(c){const e={name:pi,value:{...o,flights:o.flights}};r({event:a,extension:e})}return t&&(n.policyDefinitions&&Ct({policyDefinitions:n.policyDefinitions,drawDefinition:t}),$({tournamentId:e?.tournamentId,drawDefinition:t})),{...Ni}}const iI={matchUpStatus:Qm,matchUpStatusCodes:[],score:{scoreStringSide1:"",scoreStringSide2:"",sets:void 0},matchUpFormat:void 0,winningSide:void 0},aI="CHECK_IN",oI="CHECK_OUT",sI="SCHEDULE.ASSIGNMENT.VENUE",cI="SCHEDULE.ALLOCATION.COURTS",uI="SCHEDULE.ASSIGNMENT.COURT",dI="SCHEDULE.COURT.ORDER",pI="SCHEDULE.DATE",lI="SCHEDULE.ASSIGN.OFFICIAL",mI="SCHEDULE.TIME.SCHEDULED",fI="SCHEDULE.TIME.START",hI="SCHEDULE.TIME.STOP",gI="SCHEDULE.TIME.RESUME",II="SCHEDULE.TIME.END",UI="SCHEDULE.TIME.MODIFIERS",yI="TO_BE_ANNOUNCED",SI="NEXT_AVAILABLE",vI="FOLLOWED_BY",TI="AFTER_REST",PI="RAIN_DELAY",DI=[yI,SI,vI,TI,PI],wI="SCALE",bI="RATING",RI="RANKING",NI="SEEDING",MI="PUBLISH",AI="PUBLIC",EI="STATUS",CI={MUTUALLY_EXCLUSIVE_TIME_MODIFIERS:DI,AFTER_REST:TI,ALLOCATE_COURTS:cI,ASSIGN_COURT:uI,ASSIGN_OFFICIAL:lI,ASSIGN_VENUE:sI,CHECK_IN:aI,CHECK_OUT:oI,COMPLETED_DATE:"COMPLETED.DATE",COURT_ORDER:dI,ELIGIBILITY:"ELIGIBILITY",END_TIME:II,FOLLOWED_BY:vI,MEDICAL:"MEDICAL",MODIFICATION:"MODIFICATION",NEXT_AVAILABLE:SI,NOT_BEFORE:"NOT_BEFORE",OTHER:"other",PENALTY:"PENALTY",PUBLIC:AI,PUBLISH:MI,RANKING:RI,RATING:bI,RAIN_DELAY:PI,REGISTRATION:"REGISTRATION",RESUME_TIME:gI,RETRIEVAL:"RETRIEVAL",SCALE:wI,SCHEDULE:"SCHEDULE",SCHEDULED_DATE:pI,SCHEDULED_TIME:mI,SEEDING:NI,START_TIME:fI,STATUS:EI,STOP_TIME:hI,SUSPENSION:"SUSPENSION",TIME_MODIFIERS:UI,TO_BE_ANNOUNCED:yI};function OI({tournamentRecord:e,removeScheduling:t,drawDefinition:r}){if(!r)return{error:Li};const n=Mm({drawDefinition:r}),i=e=>n?.drawMatchUps?.find((t=>t.matchUpId===e));for(const a of r.structures||[]){const{positionAssignments:o,stage:s,stageSequence:c}=a;!o||1===c&&[$p,qp].includes(s)||(a.positionAssignments=o.map((e=>(delete e.participantId,e))),a.seedAssignments=[]);const{matchUps:u}=Kf({afterRecoveryTimes:!1,inContext:!0,matchUpsMap:n,structure:a});for(const n of u){const{matchUpId:a,roundNumber:o,sides:s}=n,c=i(a);if(c){if(delete c.extensions,delete c.notes,c.matchUpStatus!==xm&&Object.assign(c,iI),o&&o>1&&c.drawPositions){const e=s?.map((({drawPosition:e,participantFed:t})=>!t&&e)).filter(Boolean),t=c.drawPositions.map((t=>e.includes(t)?void 0:t));c.drawPositions=t}t?delete c.timeItems:c.timeItems?.length&&(c.timeItems=c.timeItems.filter((e=>e.itemType&&![cI,uI,sI,lI,pI,mI].includes(e.itemType)))),Vp({tournamentId:e?.tournamentId,context:"resetDrawDefiniton",drawDefinition:r,matchUp:c})}}}return jp({drawDefinition:r,structureIds:(r.structures||[]).map((({structureId:e})=>e))}),{...Ni}}function FI({drawDefinition:e,structureId:t,roundNumber:r}){if(!e)return{error:Li};if(!t)return{error:la};return{links:(e.links||[]).filter(Boolean).reduce(((e,n)=>(n.source?.structureId!==t||r&&n.source.roundNumber!==r||(e.source=e.source.concat(n)),n.target?.structureId!==t||r&&n.target.roundNumber!==r||(e.target=e.target.concat(n)),e)),{source:[],target:[]})}}function kI({tournamentRecord:e}){if(!e)return{error:Fi};const t={positionsNoOutcomes:[],canBePruned:[],matchPlay:[],inactive:[],drawAnalysis:{}},r={},n=e.events?.map((e=>{const t=e.eventId;return r[t]=e,(e?.drawDefinitions||[]).map((e=>({drawDefinition:e,eventId:t})))})).flat().filter(Boolean);return n.forEach((({drawDefinition:e,eventId:n})=>{let i=0,a=0,o=0;const{allStructuresLinked:s}=eg({drawDefinition:e}),c=r[n],d=(e?.structures||[]).map((t=>{const{stage:r,stageSequence:n,structureId:s}=t,d=Qp[r],{inContextStructureMatchUps:p}=function(e){const{drawDefinition:t,findContainer:r,structureId:n,event:i}=e;let a=e.structure;const{containedStructures:o}=Ft({drawDefinition:t}),s=n&&o[n]||[];if(!a){const e=w({drawDefinition:t,structureId:n});if(e.error)return e;a=r?e.containingStructure??e.structure:e.structure}if(Se({drawDefinition:t,structure:a}))return{structure:a,isAdHoc:!0,error:Ki};const{matchUps:c}=ue({inContext:!0,matchUpFilters:{isCollectionMatchUp:!1},drawDefinition:t,event:i}),d=c?.filter((e=>e.structureId===n||s.includes(e.structureId))),{matchUpDependencies:p}=kt({drawIds:[t.drawId],matchUps:c,drawDefinition:t}),l=[],m=[],f={},h=[];for(const e of c??[]){if(e.structureId===n||s.includes(e.structureId)){m.push(...e.drawPositions??[]);const t=e.roundNumber;for(const r of(e.drawPositions??[]).filter(Boolean))(!f[r]||t&&f[r]>t)&&(f[r]=t)}_t(e)&&(h.push(e),l.push(e.matchUpId,...p?.[e?.matchUpId]?.matchUpIds||[]))}const g=u(m.filter(Boolean)).sort(fe),I=u(l),U=u(d?.map((({matchUpId:e,drawPositions:t})=>I.includes(e)?t:[])).flat().filter(Boolean)).sort(fe),{positionAssignments:y}=Q({drawDefinition:t,structure:a}),S=y?.filter((e=>e.bye)).map((e=>e.drawPosition)),v=y?.filter((e=>e.qualifier)).map((e=>e.drawPosition)),T=g?.filter((e=>!U.includes(e)))||[];return{allDrawPositions:g,inContextStructureMatchUps:d,drawPositionInitialRounds:f,activeDependentMatchUpIds:I,qualifyingDrawPositions:v,inactiveDrawPositions:T,positionAssignments:y,activeDrawPositions:U,byeDrawPositions:S,activeMatchUps:h,structure:a}}({drawDefinition:e,structure:t,event:c}),l=p?.filter((({winningSide:e})=>e)),m=l.filter(Boolean).length||0;a+=m,o+=p.length-a;const f=Math.max(l.filter((({roundNumber:e})=>1===e)).map((({roundPosition:e})=>e))),{positionAssignments:h}=op({structure:t}),g=h?.filter((({participantId:e})=>e));i+=g?.length??0;const I=(h?.length??0)-(g?.length??0),{roundMatchUps:U,roundProfile:y,roundNumbers:S,maxMatchUpsCount:v}=Cf({matchUps:p}),T=y&&Object.keys(y).filter((e=>!y[e].inactiveRound)).map((e=>parseInt(e))),P=y&&Object.keys(y).filter((e=>y[e].inactiveRound)).map((e=>parseInt(e))),D=y&&Object.values(y).every((e=>e.inactiveRound));return{positionsAssignedCount:g?.length??0,maxWinningSideFirstRoundPosition:f,unassignedPositionsCount:I,inactiveStructure:D,maxMatchUpsCount:v,inactiveRounds:P,roundMatchUps:U,activeRounds:T,roundNumbers:S,roundProfile:y,structureId:s,stageSequence:n,orderNumber:d,stage:r}})),p=d.find((e=>2===e.orderNumber&&1===e.stageSequence)),l=d.filter((({inactiveStructure:e})=>!e)).length,{links:m}=FI({structureId:p.structureId,drawDefinition:e}),f=1===Ed(p.activeRounds[0])&&1===p.activeRounds.length&&1===l,h=d?.every((({inactiveStructure:e})=>e)),g=!m.length&&p.activeRounds.length&&(p.roundProfile[1].inactiveCount||p.inactiveRounds.length),I=e.drawId;i&&!a&&t.positionsNoOutcomes.push(I),h&&t.inactive.push(I),f&&t.matchPlay.push(I),g&&t.canBePruned.push(I);const U={matchUpsWithWinningSideCount:a,matchUpsNoOutcomeCount:o,positionsAssignedCount:i,allStructuresLinked:s,structuresData:d,inactiveDraw:h,isMatchPlay:f,drawId:I};t.drawAnalysis[I]=U})),{...Ni,drawsAnalysis:t}}function _I({matchPlayDrawPositions:e=!0,tournamentRecord:t,drawDefinition:r,drawId:n}){if(!t)return{error:Fi};if(!r)return{error:Li};let i=[];const{drawsAnalysis:a}=kI({tournamentRecord:t});if(a.canBePruned.includes(n)){const o=a.matchPlay.includes(n),s=a.drawAnalysis[n],{structures:[c]}=Fm({stageSequence:1,drawDefinition:r,stage:qp}),u=s.structuresData.find((({structureId:e})=>c.structureId===e)),d=(c.matchUps??[]).sort(((e,t)=>e.roundPosition-t.roundPosition));i=d.filter((({roundNumber:e})=>!u.inactiveRounds.includes(e)));const p=i.map(Nd),l=d.map(Nd).filter((e=>!p.includes(e)));if(o){const t=i.filter((({roundNumber:e})=>!u.inactiveRounds.includes(e))).filter((({winningSide:e})=>e)),r=t.map(Nd),n=p.filter((e=>!r.includes(e)));l.push(...n);const a=t.flatMap((e=>e.drawPositions??[])).filter(Boolean).flat(),o=Object.assign({},...a.map(((e,t)=>({[e]:t+1}))));if(t.forEach((t=>{e?t.drawPositions=t.drawPositions.map((e=>o[e])):delete t.drawPositions})),e){const e=c?.positionAssignments?.filter((e=>a.includes(e.drawPosition))).map((e=>(e.drawPosition=o[e.drawPosition],e)));c.positionAssignments=e}else c.positionAssignments=[];c.matchUps=t,i=t}Lp({tournamentId:t?.tournamentId,matchUpIds:l,drawDefinition:r}),jp({drawDefinition:r})}return{...Ni,matchUps:i}}function xI({tournamentRecord:e,drawDefinition:t,participantId:r,drawPosition:n,structureId:i,qualifier:a,event:o,bye:s}){if(!t)return{error:Li};if(!n)return{error:Ji};if(!i)return{error:la};if(s){const r=sf({tournamentRecord:e,drawDefinition:t,drawPosition:n,structureId:i,event:o});if(r.error)return r}else{if(a)return{error:bs};{const a=Pf({tournamentRecord:e,drawDefinition:t,participantId:r,drawPosition:n,structureId:i,event:o});if(a.error)return a}}return{...Ni}}const LI="SET3-S:6/TB7",VI="SET3-S:6/TB7-F:TB10",BI={FORMAT_STANDARD:LI,FORMAT_STANDARD_NOAD:"SET3-S:6NOAD",FORMAT_ATP_DOUBLES:VI,FORMAT_SHORT_SETS:"SET3-S:4/TB7",FORMAT_FAST4:"SET3-S:4/TB5@3",FORMAT_PRO_SET:"SET1-S:8/TB7",FORMAT_COLLEGE_PRO_SET:"SET1-S:8/TB7@7",TIMED20:"SET1-S:T20"};function jI({winningSide:e,matchUpFormat:t=LI,matchUpStatus:r,tallyPolicy:n,score:i}){const a=[0,0],o=i?.sets,s="number"==typeof e&&e-1,c=be(t),u=GI(c?.bestOf??1);if("number"==typeof s&&(r===jm&&n?.setsCreditForDefaults||r===Km&&n?.setsCreditForWalkovers))a[s]=u;else for(const e of o||[]){const{winningSide:t}=e;t&&(a[t-1]+=1)}return"number"==typeof s&&r===zm&&(+a[1-s]===u&&(a[1-s]-=1),n?.setsCreditForRetirements&&(a[s]=u)),a}function GI(e){return e&&Math.ceil(e/2)||1}function qI(e){return"P"===e}function $I(e){return!qI(e)}const WI="timed",HI="NOAD",zI="SET",YI={S:"normal",F:"final"};function QI(e){if("string"==typeof e){const t=e.startsWith("T")&&WI||e.startsWith(zI)&&zI||"";if(t===WI){const t=XI(e);if(t)return{simplified:!0,setFormat:t,bestOf:1}}if(t===zI)return function(e){const t=e.split("-"),r=tU(t[0].slice(3)),n=1===r||r%2!=0?r:void 0,i=1!==r&&r%2==0?r:void 0,a=t&&KI(t[1]),o=t&&KI(t[2]),s=a&&a.timed||o&&o.timed,c=n&&n<6||s&&i,u=!t[2]||o,d=a,p=Mf({setFormat:a,exactly:i,bestOf:n});o&&(p.finalSetFormat=o);if(c&&d&&u)return p}(e)}}function KI(e){if(":"===e?.[1]){const t=e.split(":"),r=YI[t[0]],n=t[1];if(r&&n){if(n.startsWith("TB")){const e=ZI(n);return!1!==e&&("object"==typeof e?{tiebreakSet:e}:void 0)}if(n.startsWith("T"))return XI(n);const t=e.match(/^[FS]:(\d+)([A-Za-z]*)/),r=t&&eU(t[2])||!1,i=!t?.[2]||r,a=t?tU(t[1]):void 0,o=JI(n),s=!1!==o,c=s&&o||a,u=ZI(n.split("/")[1]),d=!1!==u,p={setTo:a};return r&&(p.NoAD=!0),u?(p.tiebreakFormat=u,p.tiebreakAt=c):p.noTiebreak=!0,a&&i&&d&&s&&p||!1}}}function JI(e,t=!0){const r=e?.indexOf("@")>0&&e.split("@");if(r){return(t?tU(r[1]):r[1])||!1}}function ZI(e){if(e){if(e.startsWith("TB")){const t=JI(e,!1),r=e.match(/^TB(\d+)([A-Za-z]*)/),n=r?.[1],i=r&&eU(r[2]),a=!r?.[2]||i,o=tU(n);if(o&&a){const e={tiebreakTo:o};return t&&"string"==typeof t&&!Vd(t)&&(e.modifier=t),i&&(e.NoAD=!0),e}return!1}return!1}}function XI(e){const t=e.slice(1),r=t.match(/^(\d+)(@?[A-Za-z]*)/),n=tU(r?.[1]);if(!n)return;const i={timed:!0,minutes:n},a=r?.[2],o=[void 0,"P","G"].includes(a);if(a&&!o){const e=t.match(/^(\d+)(@)([A-Za-z]+)$/)?.[3];return e?(i.modifier=e,i):void 0}return a&&(i.based=r[2]),i}function eU(e){return e&&e.indexOf(HI)>=0}function tU(e){return isNaN(Number(e))?0:Number(e)}function rU({participantIds:e,matchUpFormat:t,tallyPolicy:r,perPlayer:n,matchUps:i}){const a={},o=r?.excludeMatchUpStatuses||[],s=i.filter((t=>(t.tieMatchUps||!o.includes(t.matchUpStatus))&&(!e?.length||2===Jd(e,[aU(t,0),aU(t,1)]).length))),c=s.flatMap((({score:e,tieMatchUps:t})=>t?t.filter((({matchUpStatus:e})=>!o.includes(e))).flatMap((({score:e})=>e?.sets?.length??0)):e?.sets?.length??0)).reduce(((e,t)=>e+t),0);for(const e of s){const{matchUpStatus:i,tieMatchUps:o,tieFormat:s,score:c,winningSide:u,sides:d}=e,p=s&&e._disableAutoCalc&&s.collectionDefinitions.every((({scoreValue:e})=>e)),l=u&&nU(e),m=u&&iU(e);if(l||m)if(oU(a,l),oU(a,m),o?.length){n=0;for(const e of o){const{matchUpType:t}=e,n=t===hf,i=t===mf;e.winningSide&&(e.winningSide===u?(l&&(a[l].tieMatchUpsWon+=1,i&&(a[l].tieSinglesWon+=1),n&&(a[l].tieDoublesWon+=1)),m&&(a[m].tieMatchUpsLost+=1,i&&(a[m].tieSinglesLost+=1),n&&(a[m].tieDoublesLost+=1))):e.winningSide!==u&&(m&&(a[m].tieMatchUpsWon+=1,i&&(a[m].tieSinglesWon+=1),n&&(a[m].tieDoublesWon+=1)),l&&(a[l].tieMatchUpsLost+=1,i&&(a[l].tieSinglesLost+=1),n&&(a[l].tieDoublesLost+=1)))),cU({matchUpFormat:e.matchUpFormat,matchUpStatus:e.matchUpStatus,score:e.score,winningParticipantId:l,losingParticipantId:m,participantResults:a,isTieMatchUp:!0,manualGamesOverride:p,tallyPolicy:r,winningSide:u})}uU({winningParticipantId:l,losingParticipantId:m,participantResults:a,matchUpStatus:i})}else cU({matchUpFormat:e.matchUpFormat??t,isTieMatchUp:void 0,winningParticipantId:l,manualGamesOverride:p,losingParticipantId:m,participantResults:a,matchUpStatus:i,tallyPolicy:r,winningSide:u,score:c});else if(i&&rf.includes(i)){const t=aU(e,0),r=aU(e,1);t&&(oU(a,t),a[t].matchUpsCancelled+=1),r&&(oU(a,r),a[r].matchUpsCancelled+=1)}else if(o?.length){n=0;for(const e of o){if(e.winningSide){const t=d?.find((({sideNumber:t})=>t===e.winningSide))?.participantId,r=d?.find((({sideNumber:t})=>t===e.winningSide))?.participantId;t&&r&&(oU(a,t),oU(a,r),a[t].tieMatchUpsWon+=1,a[r].tieMatchUpsLost+=1,e.matchUpType===mf?(a[t].tieSinglesWon+=1,a[r].tieSinglesLost+=1):e.matchUpType===hf&&(a[t].tieDoublesWon+=1,a[r].tieDoublesLost+=1))}sU({score:e.score,manualGamesOverride:p,participantResults:a,sides:d})}}else sU({manualGamesOverride:p,participantResults:a,score:c,sides:d});if(p){const e=d?.find((({sideNumber:e})=>1===e))?.participantId,t=d?.find((({sideNumber:e})=>2===e))?.participantId;oU(a,e),oU(a,t);const r=c?.sets?.reduce(((e,t)=>e+(t?.side1Score??0)),0),n=c?.sets?.reduce(((e,t)=>e+(t.side2Score??0)),0);e&&(a[e].gamesWon+=r,a[e].gamesLost+=n),t&&(a[t].gamesWon+=n,a[t].gamesLost+=r)}}return function({participantResults:e,matchUpFormat:t,tallyPolicy:r,perPlayer:n,totalSets:i}){const a=t&&QI(t)||{},o=a.bestOf,s=o&&Math.ceil(o/2)||1,c=a.setFormat?.setTo;Object.keys(e).forEach((t=>{const a=e[t].setsWon,o=e[t].setsLost,u=r?.groupTotalSetsPlayed?i:n*(s||0)||a+o;let d=Math.round(a/u*1e3)/1e3;(d===1/0||isNaN(d))&&(d=u);const p=e[t].tieMatchUpsWon,l=p+e[t].tieMatchUpsLost;let m=Math.round(p/l*1e3)/1e3;(m===1/0||isNaN(m))&&(m=p);const f=e[t].matchUpsWon,h=f+e[t].matchUpsLost;let g=Math.round(f/h*1e3)/1e3;(g===1/0||isNaN(g))&&(g=f);const I=e[t].gamesWon||0,U=e[t].gamesLost||0,y=(n||0)*(s||0)*(c||0),S=Math.max(y,I+U);let v=Math.round(I/S*1e3)/1e3;(v===1/0||isNaN(v))&&(v=0);let T=Math.round(e[t].pointsWon/e[t].pointsLost*1e3)/1e3;(T===1/0||isNaN(T))&&(T=0),e[t].setsWon=a,e[t].setsLost=o,e[t].setsPct=d,e[t].tieMatchUpsWon=p,e[t].tieMatchUpsPct=m,e[t].matchUpsPct=g,e[t].gamesWon=I,e[t].gamesLost=U,e[t].gamesPct=v,e[t].pointsPct=T,e[t].result=`${e[t].matchUpsWon}/${e[t].matchUpsLost}`}))}({participantResults:a,matchUpFormat:t,tallyPolicy:r,perPlayer:n,totalSets:c}),{participantResults:a}}function nU(e){return aU(e,e.winningSide-1)}function iU(e){return aU(e,1-(e.winningSide-1))}function aU(e,t){if(!e?.sides)return console.log("no sides:",{matchUp:e}),"foo";const r=e.sides[t];return r?r.participantId:(console.log("No Side",{matchUp:e,index:t}),"foo")}function oU(e,t){t&&!e[t]&&(e[t]={allDefaults:0,defaults:0,defeats:[],gamesLost:0,gamesWon:0,matchUpsCancelled:0,matchUpsLost:0,matchUpsWon:0,pointsLost:0,pointsWon:0,retirements:0,setsLost:0,setsWon:0,tieSinglesWon:0,tieSinglesLost:0,tieDoublesWon:0,tieDoublesLost:0,tieMatchUpsLost:0,tieMatchUpsWon:0,victories:[],walkovers:0})}function sU({manualGamesOverride:e,participantResults:t,score:r,sides:n}){const{sets:i}=r||{},a=[[],[]],o=[0,0];for(const e of i||[]){const{winningSide:t,side1Score:r,side2Score:n}=e;t&&(o[t-1]+=1),a[0].push(Ed(r||0)),a[1].push(Ed(n||0))}const s=[a[0].reduce(((e,t)=>e+t),0),a[1].reduce(((e,t)=>e+t),0)];n.forEach(((r,n)=>{const{participantId:i}=r;i&&(oU(t,i),t[i].setsWon+=o[n],t[i].setsLost+=o[1-n],e||(t[i].gamesWon+=s[n],t[i].gamesLost+=s[1-n]))}))}function cU({winningParticipantId:e,losingParticipantId:t,participantResults:r,manualGamesOverride:n,matchUpFormat:i,matchUpStatus:a,isTieMatchUp:o,tallyPolicy:s,winningSide:c,score:u}){const d=c&&c-1,p=1-d;o||uU({winningParticipantId:e,losingParticipantId:t,participantResults:r,matchUpStatus:a});const l=jI({matchUpStatus:a,matchUpFormat:i,tallyPolicy:s,winningSide:c,score:u}),m=function({matchUpFormat:e=LI,winningSide:t,matchUpStatus:r,tallyPolicy:n,score:i}){const{sets:a}=i||{};if(!a)return[0,0];const o="number"==typeof t&&t-1,s=be(e),c=GI(s?.bestOf??1),u=s?.setFormat?.tiebreakAt||0,d=[[],[]];if("number"==typeof o&&(r===jm&&n?.gamesCreditForDefaults||r===Km&&n?.gamesCreditForWalkovers)){const e=c*(s?.setFormat?.setTo||0);d[o].push(e)}else a.forEach(((e,t)=>{const r=(e.setNumber||t+1)>c&&s?.finalSetFormat?"finalSetFormat":"setFormat",i=s?.[r]?.based,a=s?.[r].tiebreakSet,{side1Score:o,side2Score:u}=e;$I(i)&&(d[0].push(ve(o||0)),d[1].push(ve(u||0))),a&&e.winningSide&&!1!==n?.gamesCreditForTiebreakSets&&d[e.winningSide-1].push(1)}));if(r===zm&&"number"==typeof o){const i=a.length>c&&s?.finalSetFormat?"finalSetFormat":"setFormat",p=s?.[i];if($I(p.based)){const i=p?.setTo||0,l=e=>{if(s&&""!==e)return+e==u-1||+e===u?ve(u||0)+1:+e<u?i:u},m=jI({winningSide:t,score:{sets:a},matchUpStatus:r,matchUpFormat:e,tallyPolicy:n});if(d.map((e=>e[o]<=e[1-o])).reduce(((e,t)=>e+(t?1:0)),0)>m[1-o]){const e=d[o].length,t=l(d[1-o][e-1]);t&&(d[o][e-1]=t)}c>d[o].length&&n?.gamesCreditForRetirements&&d[o].push(i)}}return[d[0].reduce(((e,t)=>e+t),0),d[1].reduce(((e,t)=>e+t),0)]}({matchUpStatus:a,matchUpFormat:i,tallyPolicy:s,winningSide:c,score:u}),{pointsTally:f}=function({matchUpFormat:e,score:t}){const r=e?be(e):void 0,n=GI(r?.bestOf??1),i=[0,0],a=[0,0];return t?.sets?.forEach(((e,t)=>{const o=(e.setNumber||t+1)>n&&r?.finalSetFormat?"finalSetFormat":"setFormat",s=r?.[o]?.based;if(qI(s)){const{side1Score:t,side2Score:r}=e;t&&(a[0]+=ve(t||0)),r&&(a[1]+=ve(r||0))}else e.side1TiebreakScore&&(a[0]+=ve(e.side1TiebreakScore||0)),e.side2TiebreakScore&&(a[1]+=ve(e.side2TiebreakScore||0)),(e.side1TiebreakScore||e.side2TiebreakScore)&&e.winningSide&&(i[e.winningSide-1]+=1)})),{pointsTally:a,tiebreaksTally:i}}({score:u,matchUpFormat:i});e&&(r[e].setsWon+=l[d],r[e].setsLost+=l[p],n||(r[e].gamesWon+=m[d],r[e].gamesLost+=m[p]),r[e].pointsWon+=f[d],r[e].pointsLost+=f[p]),t&&(r[t].setsWon+=l[p],r[t].setsLost+=l[d],n||(r[t].gamesWon+=m[p],r[t].gamesLost+=m[d]),r[t].pointsWon+=f[p],r[t].pointsLost+=f[d])}function uU({winningParticipantId:e,losingParticipantId:t,participantResults:r,matchUpStatus:n}){t&&(n===Km&&(r[t].walkovers+=1),n===jm&&(r[t].defaults+=1),n===zm&&(r[t].retirements+=1),[jm,zm,Km].includes(n)&&(r[t].allDefaults+=1),r[t].matchUpsLost+=1),e&&(r[e].matchUpsWon+=1),t&&e&&(r[t].defeats.push(e),r[e].victories.push(t))}function dU({participantResults:e,participantIds:t,attribute:r}){return pU({participantResults:e,participantIds:t}).reduce(((e,t)=>{const{participantId:n,results:i}=t,a=i?.[r];return!isNaN(a)&&n&&(e[a]?e[a].push(n):e[a]=[n]),e}),{})}function pU(e){return(e.participantIds||Object.keys(e.participantResults)).reduce(((t,r,n)=>(t.push({participantId:r,i:n,results:e.participantResults[r]}),t)),[])}const lU=[{attribute:"matchUpsPct",idsFilter:!1},{attribute:"allDefaults",reversed:!0,idsFilter:!1},{attribute:"defaults",reversed:!0,idsFilter:!1},{attribute:"walkovers",reversed:!0,idsFilter:!1},{attribute:"retirements",reversed:!0,idsFilter:!1},{attribute:"setsPct",idsFilter:!1},{attribute:"gamesPct",idsFilter:!1},{attribute:"pointsPct",idsFilter:!1},{attribute:"matchUpsPct",idsFilter:!0},{attribute:"setsPct",idsFilter:!0},{attribute:"gamesPct",idsFilter:!0},{attribute:"pointsPct",idsFilter:!0}],mU={matchUpsPct:20,tieMatchUpsPct:16,setsPct:12,gamesPct:8,pointsPct:4};function fU(e){const{requireCompletion:t=!0,participantResults:r,subOrderMap:n,tallyPolicy:i}=e,a=[];if(t&&!function({participantResults:e,participantsCount:t}){const r=pU({participantResults:e}),n=r.filter((e=>t-1===e.results.matchUpsWon+e.results.matchUpsLost+e.results.matchUpsCancelled));return t===n.length}(e))return{};const o=["tieMatchUpsWon","tieSinglesWon","tieDoublesWon","matchUpsWon","pointsWon","gamesWon","setsWon","gamesPct","setsPct","pointsPct","matchUpsPct"].includes(i?.groupOrderKey)?i.groupOrderKey:"matchUpsWon",s=dU({participantResults:r,attribute:o});a.push({attribute:o,groups:s});const c=Object.keys(s).map((e=>parseFloat(e))).sort(((e,t)=>t-e)).map((e=>s[e])).map((t=>{const r=hU({participantIds:t,...e});return a.push(...r.report??[]),r.order})).flat(1/0);let u,d=1;c.forEach(((e,t)=>{t&&(e.resolved||u&&!e.resolved)&&(d+=1),u=e.resolved,e.resolved?(e.position=t+1,d=e.position):e.position=d}));const p=$d(c.map((({position:e})=>e)));return c.forEach((e=>{const{participantId:t,position:a}=e||{},o=r[t];e.GEMscore=function(e){const t=Array.isArray(i?.GEMscore)?Object.keys(mU).filter((e=>i.GEMscore.includes(e))):Object.keys(mU);return t.map((t=>(e[t]||0)*Math.pow(10,mU[t].toFixed(3)))).reduce(((e,t)=>e+t),0)}(o);const s=p[a];void 0!==e?.position&&(s>1&&(e.ties=s,n&&(e.subOrder=n[t])),e.rankOrder=a,e.groupOrder=a+(e.subOrder||1)-1)})),{groupOrder:c,report:a.flat(1/0).filter(Boolean)}}function hU({participantResults:e,disableHeadToHead:t,participantIds:r,matchUpFormat:n,tallyPolicy:i,matchUps:a}){const o=[],s=[];let c;if(1===r?.length){return{order:[{resolved:!0,participantId:r[0]}]}}if(2===r?.length&&(!i?.headToHead||!i.headToHead.disabled&&!t)){const t=function({participantIds:e,participantResults:t}){if(!e)return;if(t[e[0]].victories.includes(e[1]))return e.map((e=>({resolved:!0,participantId:e})));if(t[e[1]].victories.includes(e[0]))return e.reverse().map((e=>({resolved:!0,participantId:e})))}({participantIds:r,participantResults:e});if(t){const e=t[0].participantId;return s.push({attribute:"head2Head",participantIds:r,headToHeadWinner:e}),{order:[t],headToHeadWinner:e,report:s}}}const u=(i?.tallyDirectives||lU).filter((e=>{const t=!(kd(e.maxParticipants)&&r?.length>e.maxParticipants);return t||o.push(e),t}));return o.length&&s.push({excludedDirectives:o,participantIds:r}),u.every((({attribute:e,reversed:t,idsFilter:o,disableHeadToHead:u})=>(c=function({disableHeadToHead:e,participantIds:t,matchUpFormat:r,tallyPolicy:n,attribute:i,idsFilter:a,matchUps:o,reversed:s}){const{participantResults:c}=rU({participantIds:a&&t,matchUpFormat:r,tallyPolicy:n,matchUps:o}),u=dU({participantResults:c,participantIds:t,attribute:i}),d=[{attribute:i,reversed:s,groups:u,idsFilter:a}];let p;return Object.keys(u).length>1&&t.length&&(p=Object.keys(u).map((e=>parseFloat(e))).sort(((e,t)=>s?e-t:t-e)).map((e=>u[e])).map((t=>{const i=hU({participantResults:c,disableHeadToHead:e,participantIds:t,matchUpFormat:r,tallyPolicy:n,matchUps:o});return d.push(...i.report??[]),i.order})).flat(1/0)),{order:p,report:d}}({disableHeadToHead:u,participantIds:r,matchUpFormat:n,tallyPolicy:i,attribute:e,idsFilter:o,matchUps:a,reversed:t}),s.push(c.report),!c.order))),c.order?{order:c.order,report:s}:{order:r?.map((e=>({participantId:e}))),report:s}}function gU({policyDefinitions:e,generateReport:t,matchUpFormat:r,matchUps:n=[],subOrderMap:i,perPlayer:a}){if(!xt(n))return{error:Va};if(1!==n.reduce(((e,{structureId:t})=>e.includes(t)?e:e.concat(t)),[]).length)return{error:ys,info:"Maximum one structureId"};const o=n.filter((e=>e&&e.matchUpStatus!==xm)),s=o.length&&u(o.map((({drawPositions:e})=>e)).flat()).length,c=o.filter((e=>qe({matchUp:e}))).length===o.length;c||(a=0);const d=n.every((({matchUpType:e,tieMatchUps:t})=>e===If&&t?.every((e=>qe({matchUp:e}))))),p=e?.[Ku],l=n.filter((e=>qe({matchUp:e})||e.matchUpType===If)),{participantResults:m}=rU({matchUps:l,matchUpFormat:r,tallyPolicy:p,perPlayer:a});let f,h;const{groupOrder:g,report:I}=fU({matchUps:l,participantResults:m,participantsCount:s,matchUpFormat:r,tallyPolicy:p,subOrderMap:i});if(c&&g)f=I,h=g,g.forEach((e=>{const{participantId:t,groupOrder:r,rankOrder:n,subOrder:i,ties:a,GEMscore:o}=e,s=m[t];Object.assign(s,{groupOrder:r,rankOrder:n,GEMscore:o,subOrder:i,ties:a})}));else{const{groupOrder:e,report:t}=fU({requireCompletion:!1,participantResults:m,participantsCount:s,matchUpFormat:r,tallyPolicy:p,subOrderMap:i,matchUps:n});f=t,h=e,e&&e.forEach((e=>{const{participantId:t,groupOrder:r,GEMscore:n}=e,i=m[t];Object.assign(i,{provisionalOrder:r,GEMscore:n})}))}const U={completedTieMatchUps:d,readableReport:"",participantResults:m,bracketComplete:c,order:[],report:f};if((c||d)&&(U.order=h),t||Ye({tally:!0})){const e=function({matchUps:e,order:t,report:r}){const n={};e.forEach((({sides:e})=>{e.forEach((e=>{e.participantId&&e.participant&&(n[e.participantId]=e.participant.participantName)}))}));const i=[];return Array.isArray(r)&&r.forEach(((e,t)=>{if(e.excludedDirectives?.length){const t=e.excludedDirectives.map((({attribute:e})=>e)).join(", "),r=`${t.length} directives were excluded due to participants limit}`;i.push(r);const n=`Excluded: ${t}`;i.push(n)}else{const r=(t,r)=>parseFloat(e.reversed?t:r)-parseFloat(e.reversed?r:t),a=e.groups?Object.values(e.groups).flat(1/0).length:e.participantIds?.length??0,o=e=>{e.groups&&Object.keys(e.groups).sort(r).forEach((t=>{const r=e.groups[t].map((e=>n[e])).join(", "),a=`${t} ${e.attribute}: ${r}`;i.push(a)}))},s=e.reversed?" in reverse order":"",c=`Step ${t+1}: ${a} particiants were ${e.groups?"grouped":"separated"}${s} by ${e.attribute}`;if(i.push(c),e.idsFilter){const t=`${e.attribute} was calculated considering ONLY TIED PARTICIPANTS`;i.push(t)}o(e)}i.push("----------------------")})),i.push("Final Order:"),t.forEach((e=>{const{participantId:t,resolved:r}=e,a=e.groupOrder||e.provisionalOrder;i.push(`${a}: ${n[t]} => resolved: ${!!r}`)})),i.join("\r\n")}({matchUps:n,report:f,order:h});Ye({tally:!0})&&console.log(e),U.readableReport=e}return U}function IU({positionAssignments:e,tournamentRecord:t,drawDefinition:r,matchUpFormat:n,matchUps:i,event:a}){if(!Ef(i))return{error:ys};if(!e)return{error:ys};const{policyDefinitions:o}=Fh({policyTypes:[Ku],tournamentRecord:t,drawDefinition:r,event:a}),{subOrderMap:s}=function({positionAssignments:e}){const t=(e||[]).filter(au(vu)).map((e=>{const{extension:t}=Wl({element:e,name:Pi}),r=Ed(t?.value),n=!isNaN(r)&&r;return n&&{participantId:e.participantId,subOrder:n}})).filter(Boolean),r=$d(t.map((({subOrder:e})=>e)));return{subOrderMap:Object.assign({},...t.filter((({subOrder:e})=>1===r[e])).map((({participantId:e,subOrder:t})=>({[e]:t}))))}}({positionAssignments:e}),c=gU({policyDefinitions:o,matchUpFormat:n,subOrderMap:s,matchUps:i});if(c.error)return c;const{participantResults:u,bracketComplete:d,report:p}=c,l=Object.keys(u);return e.forEach((e=>{const{participantId:t}=e;if(l.includes(t)){gd({element:e,extension:{value:u[t],name:Di}}),u[t].ties||fd({element:e,name:Pi})}else fd({element:e,name:Di}),fd({element:e,name:Pi})})),jp({drawDefinition:r}),{...Ni,participantResults:u,bracketComplete:d,report:p}}function UU(e){const{tournamentRecord:t,matchUpIds:r=[],drawDefinition:n,event:i}=e;if("object"!=typeof n)return{error:Li};if(!Array.isArray(r))return{error:ys};const a=e.structureId??n?.structures?.find((e=>e.matchUps?.some((({matchUpId:e})=>r.includes(e)))))?.structureId;if(!a)return{error:ma};const o=n.structures?.find((e=>e.structureId===a));if(!o)return{error:ma};const s=o?.matchUps,c=s?.find((e=>!!e.roundPosition));if(o.structures||c||o.finishingPosition===Vl)return{error:ji};const u=[],d=s?.filter((({matchUpId:e,score:t})=>(hg({score:t})&&u.push(e),r.includes(e))))??[],p=d.map(Nd),l=d.map((({tieMatchUps:e})=>e?.map(Nd))).filter(Boolean).flat();if(p.length){o.matchUps=(o.matchUps??[]).filter((({matchUpId:e})=>!p.includes(e))),Lp({tournamentId:t?.tournamentId,matchUpIds:[...l,...p],action:"deleteAdHocMatchUps",eventId:i?.eventId,drawDefinition:n});const e=function(e,t=1){return Array.isArray(e)&&e.every(Vd)?Qd(Math.min(...e,t),Math.max(...e)+1).filter((t=>!e.includes(t))):[]}(jd(o.matchUps.map(au("roundNumber"))));if(e.length){e.reverse();for(const r of e)o.matchUps.forEach((e=>{e.roundNumber&&e.roundNumber>r&&(e.roundNumber-=1,Vp({tournamentId:t?.tournamentId,context:["adHoc round deletion"],eventId:i?.eventId,drawDefinition:n,matchUp:e}))}))}if(u.length){o.positionAssignments=jd(o.matchUps.flatMap((e=>(e.sides??[]).map((e=>e.participantId)))).filter(Boolean)).map((e=>({participantId:e})));const e=o?.matchUpFormat??n?.matchUpFormat??i?.matchUpFormat,r=IU({positionAssignments:o.positionAssignments,matchUps:o.matchUps,tournamentRecord:t,drawDefinition:n,matchUpFormat:e,event:i});r.error&&console.log(r)}jp({structureIds:[a],eventId:i?.eventId,drawDefinition:n})}return{...Ni}}function yU({removeCompletedMatchUps:e,tournamentRecord:t,drawDefinition:r,structureId:n,roundNumber:i,event:o}){if(!t)return{error:Fi};if(!r)return{error:Li};if(!i)return a({result:{error:Za},info:"roundNumber required"});const s=w({drawDefinition:r,structureId:n});if(s.error)return s;const c=s.structure;if(c?.structures)return{error:ji};return Se({drawDefinition:r,structure:c})?function({removeCompletedMatchUps:e,drawDefinition:t,tournamentId:r,roundNumber:n,structure:i,eventId:a}){const o=i?.matchUps??[],s=[],c=[];let u=!1;if(o.reduce(((e,t)=>{const r=t?.roundNumber;return r?e.includes(r)?e:e.concat(r):e}),[]).sort(fe).includes(n)){const d=o.filter((t=>{const r=t.roundNumber===n&&(!rf.includes(t.matchUpStatus)||e);return r&&(c.push(t.matchUpId),t.tieMatchUps&&s.push(...t.tieMatchUps.map(T))),!r}));if(c.length){H({matchUpIds:[...s,...c],drawDefinition:t,tournamentId:r,eventId:a});d.some((e=>e.roundNumber===n))||(d.forEach((e=>{e.roundNumber>n&&(e.roundNumber-=1,q({drawDefinition:t,tournamentId:r,eventId:a,matchUp:e}))})),u=!0),i.matchUps=d}}return{deletedMatchUpsCount:c.length,roundRemoved:u,...Ni}}({tournamentId:t.tournamentId,removeCompletedMatchUps:e,eventId:o.eventId,drawDefinition:r,roundNumber:i,structure:c}):(console.log("not implemented"),{...Ni})}function SU(e){return`${e} must be an array`}function vU({lineUp:e,tieFormat:t}){const r=[];if(!Array.isArray(e))return r.push(SU("lineUp")),{valid:!1,errors:r,error:ys};const n=e.every((e=>{if("object"!=typeof e)return r.push("lineUp entries must be objects"),!1;const{participantId:t,collectionAssignments:n}=e;return t?"string"!=typeof t?(r.push("participantIds must be strings"),!1):Array.isArray(n)?n.every((e=>{if("object"!=typeof e)return r.push("collectionAssignments must be objects"),!1;const{collectionPosition:t}=e;return"number"==typeof t||(r.push("collectionPosition must be a number"),!1)})):(r.push(SU("collectionAssignments")),!1):(r.push("Missing participantId"),!1)})),i=jd(e.map(Rd)).length===e.length;i||r.push("Duplicated participantId(s)");return{valid:n&&i,errors:r,error:r.length?ys:void 0}}function TU({drawDefinition:e,participantId:t,tieFormat:r,lineUp:n}){if("object"!=typeof e)return{error:Li};if("string"!=typeof t)return{error:Do};const i=vU({lineUp:n,tieFormat:r});if(!i.valid)return i;const{extension:a}=Wl({element:e,name:mi}),o=a?.value||{};o[t]=function({lineUp:e}){if(!Array.isArray(e))return;const t={};return u(e.flatMap((({collectionAssignments:e})=>e?.map((({collectionId:e,collectionPosition:t})=>[e,t].join("|"))))).filter(Boolean)).forEach((r=>{const[n,i]=r.split("|"),a=parseInt(i),{assignedParticipantIds:o}=Re({collectionPosition:a,collectionId:n,lineUp:e});o.forEach((e=>{t[e]||(t[e]=[]),t[e].push({collectionId:n,collectionPosition:a})}))})),Object.keys(t).map((e=>({participantId:e,collectionAssignments:t[e]})))}({lineUp:n});return gd({element:e,extension:{name:mi,value:o}}),Bp({drawDefinition:e}),{...Ni}}function PU(e){const{suppressNotifications:t,tournamentRecord:r,drawDefinition:n,matchUps:i,event:a}=e;if("object"!=typeof n)return{error:Li};let o=e?.structureId;if(o||1!==n.structures?.length||(o=n.structures?.[0]?.structureId),"string"!=typeof o)return{error:la};if(!xt(i))return{error:ys,info:Vt("matchUps")};const s=n.structures?.find((e=>e.structureId===o));if(!s)return{error:ma};const c=s?.matchUps,u=c.find((e=>!!e.roundPosition));if(s.structures||u||s.finishingPosition===Vl)return{error:ji};const p=Lt({tournamentRecord:r,inContext:!1})?.matchUps?.map(T)??[],l=i.map(T);if(d(p,l))return{error:As,info:"One or more matchUpIds already present in tournamentRecord"};s.matchUps.push(...i);const m=i.map((({tieMatchUps:e})=>e)).filter(Boolean).flat();return t||(W({tournamentId:r?.tournamentId,matchUps:[...m,...i],eventId:a?.eventId,drawDefinition:n}),$({drawDefinition:n,structureIds:[o]})),{...Ni}}function DU({tournamentRecord:e,drawDefinition:t,drawPosition:r,structureId:n,subOrder:i,event:a}){if(!t)return{error:Li};if(!n)return{error:la};if(!r)return{error:Ji};const{structure:s}=w({drawDefinition:t,structureId:n});if(!s)return{error:ma};let c=s;s.structures&&s.structureType===nl&&(c=s.structures?.find((e=>e.positionAssignments?.find((e=>e.drawPosition===r)))));const u=c?.positionAssignments,d=u?.find((e=>e.drawPosition===r));d&&o({element:d,extension:{name:Pi,value:i}});const p=(a?.eventType===If||t.matchUpType===If||(a?.tieFormat??t?.tieFormat??s?.tieFormat))&&{matchUpTypes:[If]},{matchUps:l}=J({structure:c,afterRecoveryTimes:!1,inContext:!0,matchUpFilters:p,event:a}),m=s?.matchUpFormat??t.matchUpFormat;return Bt({positionAssignments:u,tournamentRecord:e,drawDefinition:t,matchUpFormat:m,matchUps:l,event:a}),$({drawDefinition:t,structureIds:[n]}),{...Ni}}function wU({scaleAttributes:e,scaledEntries:t,stageEntries:r,seedsCount:n,scaleName:i}){if(!e)return{error:Za,info:"missing scaleAttributes"};const a=Object.assign({},...(t||[]).slice(0,n).map((({participantId:e},t)=>({[e]:t+1}))));i=i||e.scaleName;const o=(new Date).toISOString();return{scaleItemsWithParticipantIds:r.map((({participantId:t})=>({scaleItems:[{scaleValue:a[t],eventType:e.eventType,scaleType:fu,scaleName:i,scaleDate:o}],participantId:t})))}}function bU({event:e,eventId:t}){if(!e)return{error:Ua};const r=Wl({name:pi,element:e}),n=r?.extension,i=t?Jc(n?.value,!1,!0):n?.value;return t&&e.drawDefinitions?.forEach((e=>{i?.flights?.forEach((t=>{t.drawId===e.drawId&&Object.assign(t,{drawDefinition:e})}))})),{flightProfile:i}}function RU({selected:e=!0,drawDefinition:t,entryStatuses:r,drawId:n,event:i,stage:a}){let o=i.entries??[];if(n){const{flightProfile:e}=bU({event:i}),r=e?.flights?.find((e=>e.drawId===n));r?o=r.drawEntries:t.entries&&(o=t?.entries)}const s=o.filter((t=>(!r?.length||!t.entryStatus||r.includes(t.entryStatus))&&(!a||!t.entryStage||t.entryStage===a)&&(!e||t.entryStatus&&um.includes(t.entryStatus))));return{entries:o,stageEntries:s}}function NU(e){let{drawSizeProgression:t=!1,policyDefinitions:r,drawSize:n}=e||{};const{requireParticipantCount:i=!0,tournamentRecord:o,drawDefinition:s,event:c}=e||{},u="getSeedsCount",d=e?.participantsCount??e?.participantCount;if(!r){const e=re({tournamentRecord:o,drawDefinition:s,event:c});if(e.error)return a({result:e,stack:u});r=e.policyDefinitions}const p=Fe(d);if(d&&!p)return a({result:{error:ys},context:{participantsCount:d},stack:u});if(i&&!p)return a({result:{error:Mo},stack:u});if(isNaN(n)){if(!d)return a({result:{error:ta},stack:u});({drawSize:n}=jt({participantsCount:d}))}const l=i&&d||n;if(l&&l>n)return{error:Fo};const m=r?.[od];if(!m)return{error:Ha};const f=m.seedsCountThresholds;if(!f)return{error:aa};void 0!==m.drawSizeProgression&&(t=m.drawSizeProgression);return{seedsCount:f.filter((e=>t?e.drawSize<=n:n===e.drawSize)).reduce(((e,t)=>d&&d>=t.minimumParticipantCount?t.seedsCount:e),0)}}function MU({policyDefinitions:e,drawDefinition:t,drawSize:r,drawId:n,event:i,stage:o}){if(!i)return{error:Ua};const{entries:s,stageEntries:c}=RU({drawDefinition:t,drawId:n,stage:o,event:i}),u=c.length,{drawSize:d}=function({participantsCount:e,participantCount:t}){if(!(e=e??t))return{error:ys};const r=Le(e);return r?{drawSize:r}:a({result:{error:ys},stack:"getEliminationDrawSize",context:{participantsCount:e}})}({participantsCount:u}),p=NU({drawSize:r??d,participantsCount:u,policyDefinitions:e});if(p.error)return pd({result:p,stack:"getEntriesAndSeedsCount"});const{seedsCount:l}=p;return{entries:s,seedsCount:l,stageEntries:c}}function AU({requireTimeStamp:e,scaleAttributes:t,participant:r}){if(!r)return{error:To};if(!ru(t))return{error:ys};if(r.timeItems||(r.timeItems=[]),Array.isArray(r.timeItems)){const{accessor:n,scaleType:i,eventType:a,scaleName:o}=t,s=[mu,i,a,o].join("."),c=r.timeItems.filter((e=>e?.itemType===s)).filter((t=>!e||t?.itemDate)).sort(((e,t)=>(e.createdAt?new Date(e.createdAt).getTime():0)-(t.createdAt?new Date(t.createdAt).getTime():0))).pop();if(c){const[e,t,r,i]=c.itemType?.split(".")??[];if(e!==mu)return{error:us};const a=n&&Gt({element:c.itemValue,accessor:n}),o=a?.value||c.itemValue,s={eventType:r,scaleDate:c.itemDate,scaleValue:o,scaleName:i,scaleType:t};return{...Ni,scaleItem:s}}}return{...Ni,scaleItem:void 0}}function EU(e){const{tournamentRecord:t,scaleAttributes:r,participantId:n}=e,i=e.tournamentRecords||t&&{[t.tournamentId]:t}||{};if(!n)return{error:Do};const{participant:a,tournamentId:o}=rg({tournamentRecords:i,tournamentRecord:t,participantId:n});return a?{...AU({participant:a,scaleAttributes:r}),tournamentId:o}:{error:wo}}function CU({sortDescending:e=!1,tournamentRecord:t,scaleAttributes:r,scaleSortMethod:n,stageSequence:i,entries:a,event:o,stage:s}){if(!t)return{error:Fi};return{scaledEntries:(a=a??o?.entries??[]).filter((e=>(!s||!e.entryStage||e.entryStage===s)&&(!i||!e.entryStageSequence||e.entryStageSequence===i)&&um.includes(e.entryStatus))).map((e=>{const{participantId:n}=e,{scaleItem:i}=EU({tournamentRecord:t,scaleAttributes:r,participantId:n});return{...e,...i}})).filter((e=>{const t=e.scaleValue;return!!(n||!isNaN(t)&&parseFloat(t))&&t})).sort(n||function(t,r){return e?c(r)-c(t):c(t)-c(r)})};function c(t){return parseFloat(t.scaleValue||(e?-1:1e5))}}function OU({tournamentRecord:e,drawDefinition:t,policyDefinitions:r,scaleAttributes:n,scaleName:i,drawSize:a,drawId:o,event:s,stage:c,sortDescending:u,scaleSortMethod:d}){const p=MU({policyDefinitions:r,drawDefinition:t,drawSize:a,drawId:o,event:s,stage:c});if(p.error)return p;const{entries:l,seedsCount:m,stageEntries:f}=p;if(!f||!m)return{error:ys};const h=CU({tournamentRecord:e,scaleAttributes:n,scaleSortMethod:d,sortDescending:u,entries:l,stage:c}).scaledEntries??[],{scaleItemsWithParticipantIds:g}=wU({scaleAttributes:n,scaledEntries:h,stageEntries:f,seedsCount:m,scaleName:i});return{scaleItemsWithParticipantIds:g}}var FU=Object.freeze({__proto__:null,addAdHocMatchUps:PU,addDrawDefinitionTimeItem:fg,addFinishingRounds:wg,addGoesTo:Jg,addPlayoffStructures:tI,addQualifyingStructure:Ag,addVoluntaryConsolationStage:Sg,addVoluntaryConsolationStructure:Nm,alternateDrawPositionAssignment:bf,assignDrawPosition:xI,assignDrawPositionBye:sf,attachConsolationStructures:Zg,attachPlayoffStructures:Xg,attachQualifyingStructure:lg,attachStructures:eI,autoSeeding:OU,automatedPlayoffPositioning:Zh,automatedPositioning:Jh,deleteAdHocMatchUps:UU,luckyLoserDrawPositionAssignment:wf,modifyDrawDefinition:nI,modifyDrawName:rI,modifySeedAssignment:sh,pruneDrawDefinition:_I,qualifierDrawPositionAssignment:Nf,removeDrawPositionAssignment:Tm,removeRoundMatchUps:yU,removeSeededParticipant:vg,removeStructure:gg,renameStructures:mg,resetDrawDefinition:OI,resetVoluntaryConsolationStructure:Gl,setDrawParticipantRepresentativeIds:ip,setPositionAssignments:Rf,setStructureOrder:Xh,setSubOrder:DU,swapDrawPositionAssignments:eh,updateTeamLineUp:TU,withdrawParticipantAtDrawPosition:Pm});function kU(e){return e&&void 0!==String.fromCodePoint?e.toUpperCase().replace(/./g,(e=>String.fromCodePoint(e.charCodeAt(0)+127397))):e}const _U=[{ioc:"",iso2:"",iso:"",label:"NONE",phone:""},{ioc:"AND",iso2:"AD",iso:"AND",label:"Andorra",phone:"376"},{ioc:"UAE",iso2:"AE",iso:"ARE",label:"United Arab Emirates",phone:"971"},{ioc:"AFG",iso2:"AF",iso:"AFG",label:"Afghanistan",phone:"93"},{ioc:"ANT",iso2:"AG",iso:"ATG",label:"Antigua and Barbuda",phone:"1-268"},{ioc:"AIA",iso2:"AI",iso:"AIA",label:"Anguilla",phone:"1-264"},{ioc:"ALB",iso2:"AL",iso:"ALB",label:"Albania",phone:"355"},{ioc:"ARM",iso2:"AM",iso:"ARM",label:"Armenia",phone:"374"},{ioc:"ANG",iso2:"AO",iso:"AGO",label:"Angola",phone:"244"},{ioc:"",iso2:"AQ",iso:"ATA",label:"Antarctica",phone:"672"},{ioc:"ARG",iso2:"AR",iso:"ARG",label:"Argentina",phone:"54"},{ioc:"ASA",iso2:"AS",iso:"ASM",label:"American Samoa",phone:"1-684"},{ioc:"AUT",iso2:"AT",iso:"AUT",label:"Austria",phone:"43"},{ioc:"AUS",iso2:"AU",iso:"AUS",label:"Australia",phone:"61",suggested:!0},{ioc:"ARU",iso2:"AW",iso:"ABW",label:"Aruba",phone:"297"},{ioc:"AZE",iso2:"AZ",iso:"AZE",label:"Azerbaijan",phone:"994"},{ioc:"BIH",iso2:"BA",iso:"BIH",label:"Bosnia and Herzegovina",phone:"387"},{ioc:"BAR",iso2:"BB",iso:"BRB",label:"Barbados",phone:"1-246"},{ioc:"BAN",iso2:"BD",iso:"BGD",label:"Bangladesh",phone:"880"},{ioc:"BEL",iso2:"BE",iso:"BEL",label:"Belgium",phone:"32"},{ioc:"BUR",iso2:"BF",iso:"BFA",label:"Burkina Faso",phone:"226"},{ioc:"BUL",iso2:"BG",iso:"BGR",label:"Bulgaria",phone:"359"},{ioc:"BRN",iso2:"BH",iso:"BHR",label:"Bahrain",phone:"973"},{ioc:"BDI",iso2:"BI",iso:"BDI",label:"Burundi",phone:"257"},{ioc:"BEN",iso2:"BJ",iso:"BEN",label:"Benin",phone:"229"},{ioc:"",iso2:"BL",iso:"BLM",label:"Saint Barthelemy",phone:"590"},{ioc:"BER",iso2:"BM",iso:"BMU",label:"Bermuda",phone:"1-441"},{ioc:"BRU",iso2:"BN",iso:"BRN",label:"Brunei Darussalam",phone:"673"},{ioc:"BOL",iso2:"BO",iso:"BOL",label:"Bolivia",phone:"591"},{ioc:"BRA",iso2:"BR",iso:"BRA",label:"Brazil",phone:"55"},{ioc:"BAH",iso2:"BS",iso:"BHS",label:"Bahamas",phone:"1-242"},{ioc:"BHU",iso2:"BT",iso:"BTN",label:"Bhutan",phone:"975"},{ioc:"",iso2:"BV",iso:"BVT",label:"Bouvet Island",phone:"47"},{ioc:"BOT",iso2:"BW",iso:"BWA",label:"Botswana",phone:"267"},{ioc:"BLR",iso2:"BY",iso:"BLR",label:"Belarus",phone:"375"},{ioc:"BIZ",iso2:"BZ",iso:"BLZ",label:"Belize",phone:"501"},{ioc:"CAN",iso2:"CA",iso:"CAN",label:"Canada",phone:"1",suggested:!0},{ioc:"",iso2:"CC",iso:"CCK",label:"Cocos (Keeling) Islands",phone:"61"},{ioc:"CGO",iso2:"CD",iso:"COG",label:"Congo, Republic of the",phone:"242"},{ioc:"CAF",iso2:"CF",iso:"CAF",label:"Central African Republic",phone:"236"},{ioc:"COD",iso2:"CG",iso:"CGD",label:"Congo, Democratic Republic of the",phone:"243"},{ioc:"SUI",iso2:"CH",iso:"CHE",label:"Switzerland",phone:"41"},{ioc:"CIV",iso2:"CI",iso:"CIV",label:"Cote d'Ivoire",phone:"225"},{ioc:"COK",iso2:"CK",iso:"COK",label:"Cook Islands",phone:"682"},{ioc:"CHI",iso2:"CL",iso:"CHL",label:"Chile",phone:"56"},{ioc:"CMR",iso2:"CM",iso:"CMR",label:"Cameroon",phone:"237"},{ioc:"CHN",iso2:"CN",iso:"CHN",label:"China",phone:"86"},{ioc:"COL",iso2:"CO",iso:"COL",label:"Colombia",phone:"57"},{ioc:"CRC",iso2:"CR",iso:"CRI",label:"Costa Rica",phone:"506"},{ioc:"CUB",iso2:"CU",iso:"CUB",label:"Cuba",phone:"53"},{ioc:"CPV",iso2:"CV",iso:"CPV",label:"Cape Verde",phone:"238"},{ioc:"CUW",iso2:"CW",iso:"CUW",label:"Curacao",phone:"599"},{ioc:"CXR",iso2:"CX",iso:"CXR",label:"Christmas Island",phone:"61"},{ioc:"CYP",iso2:"CY",iso:"CYP",label:"Cyprus",phone:"357"},{ioc:"CZE",iso2:"CZ",iso:"CZE",label:"Czech Republic",phone:"420"},{ioc:"GER",iso2:"DE",iso:"DEU",label:"Germany",phone:"49",suggested:!0},{ioc:"DJI",iso2:"DJ",iso:"DJI",label:"Djibouti",phone:"253"},{ioc:"DEN",iso2:"DK",iso:"DNK",label:"Denmark",phone:"45"},{ioc:"DMA",iso2:"DM",iso:"DMA",label:"Dominica",phone:"1-767"},{ioc:"DOM",iso2:"DO",iso:"DOM",label:"Dominican Republic",phone:"1-809"},{ioc:"ALG",iso2:"DZ",iso:"DZA",label:"Algeria",phone:"213"},{ioc:"ECU",iso2:"EC",iso:"ECU",label:"Ecuador",phone:"593"},{ioc:"EST",iso2:"EE",iso:"ESE",label:"Estonia",phone:"372"},{ioc:"EGY",iso2:"EG",iso:"EGY",label:"Egypt",phone:"20"},{ioc:"",iso2:"EH",iso:"ESH",label:"Western Sahara",phone:"212"},{ioc:"ERI",iso2:"ER",iso:"ERI",label:"Eritrea",phone:"291"},{ioc:"ESP",iso2:"ES",iso:"ESP",label:"Spain",phone:"34"},{ioc:"ETH",iso2:"ET",iso:"ETH",label:"Ethiopia",phone:"251"},{ioc:"FIN",iso2:"FI",iso:"FIN",label:"Finland",phone:"358"},{ioc:"FIJ",iso2:"FJ",iso:"FJI",label:"Fiji",phone:"679"},{ioc:"FLK",iso2:"FK",iso:"FLK",label:"Falkland Islands (Malvinas)",phone:"500"},{ioc:"FSM",iso2:"FM",iso:"FSM",label:"Micronesia, Federated States of",phone:"691"},{ioc:"FAR",iso2:"FO",iso:"FRO",label:"Faroe Islands",phone:"298"},{ioc:"FRA",iso2:"FR",iso:"FRA",label:"France",phone:"33",suggested:!0},{ioc:"GAB",iso2:"GA",iso:"GAB",label:"Gabon",phone:"241"},{ioc:"GBR",iso2:"GB",iso:"GBR",label:"United Kingdom",phone:"44"},{ioc:"GRN",iso2:"GD",iso:"GRD",label:"Grenada",phone:"1-473"},{ioc:"GEO",iso2:"GE",iso:"GEO",label:"Georgia",phone:"995"},{ioc:"FGU",iso2:"GF",iso:"GUF",label:"French Guiana",phone:"594"},{ioc:"",iso2:"GG",iso:"GGY",label:"Guernsey",phone:"44"},{ioc:"",iso2:"GH",iso:"GHA",label:"Ghana",phone:"233"},{ioc:"GIB",iso2:"GI",iso:"GIB",label:"Gibraltar",phone:"350"},{ioc:"GRL",iso2:"GL",iso:"GRL",label:"Greenland",phone:"299"},{ioc:"GAM",iso2:"GM",iso:"GMB",label:"Gambia",phone:"220"},{ioc:"GUI",iso2:"GN",iso:"GIN",label:"Guinea",phone:"224"},{ioc:"GUD",iso2:"GP",iso:"GLP",label:"Guadeloupe",phone:"590"},{ioc:"GEQ",iso2:"GQ",iso:"GNQ",label:"Equatorial Guinea",phone:"240"},{ioc:"GRE",iso2:"GR",iso:"GRC",label:"Greece",phone:"30"},{ioc:"",iso2:"GS",iso:"SGS",label:"South Georgia and the South Sandwich Islands",phone:"500"},{ioc:"GUA",iso2:"GT",iso:"GTM",label:"Guatemala",phone:"502"},{ioc:"GUM",iso2:"GU",iso:"GUM",label:"Guam",phone:"1-671"},{ioc:"GBS",iso2:"GW",iso:"GNB",label:"Guinea-Bissau",phone:"245"},{ioc:"GUY",iso2:"GY",iso:"GUY",label:"Guyana",phone:"592"},{ioc:"HKG",iso2:"HK",iso:"HKG",label:"Hong Kong",phone:"852"},{ioc:"",iso2:"HM",iso:"HMD",label:"Heard Island and McDonald Islands",phone:"672"},{ioc:"HON",iso2:"HN",iso:"HND",label:"Honduras",phone:"504"},{ioc:"CRO",iso2:"HR",iso:"HRV",label:"Croatia",phone:"385"},{ioc:"HAI",iso2:"HT",iso:"HTI",label:"Haiti",phone:"509"},{ioc:"HUN",iso2:"HU",iso:"HUN",label:"Hungary",phone:"36"},{ioc:"INA",iso2:"ID",iso:"IDN",label:"Indonesia",phone:"62"},{ioc:"IRL",iso2:"IE",iso:"IRL",label:"Ireland",phone:"353"},{ioc:"ISR",iso2:"IL",iso:"ISR",label:"Israel",phone:"972"},{ioc:"",iso2:"IM",iso:"IMN",label:"Isle of Man",phone:"44"},{ioc:"IND",iso2:"IN",iso:"IND",label:"India",phone:"91"},{ioc:"",iso2:"IO",iso:"IOT",label:"British Indian Ocean Territory",phone:"246"},{ioc:"IRQ",iso2:"IQ",iso:"IRQ",label:"Iraq",phone:"964"},{ioc:"IRI",iso2:"IR",iso:"IRN",label:"Iran, Islamic Republic of",phone:"98"},{ioc:"ISL",iso2:"IS",iso:"ISL",label:"Iceland",phone:"354"},{ioc:"ITA",iso2:"IT",iso:"ITA",label:"Italy",phone:"39"},{ioc:"",iso2:"JE",iso:"JEY",label:"Jersey",phone:"44"},{ioc:"JAM",iso2:"JM",iso:"JAM",label:"Jamaica",phone:"1-876"},{ioc:"JOR",iso2:"JO",iso:"JOR",label:"Jordan",phone:"962"},{ioc:"JPN",iso2:"JP",iso:"JPN",label:"Japan",phone:"81",suggested:!0},{ioc:"KEN",iso2:"KE",iso:"KEN",label:"Kenya",phone:"254"},{ioc:"KGZ",iso2:"KG",iso:"KGZ",label:"Kyrgyzstan",phone:"996"},{ioc:"CAM",iso2:"KH",iso:"KHM",label:"Cambodia",phone:"855"},{ioc:"KIR",iso2:"KI",iso:"KIR",label:"Kiribati",phone:"686"},{ioc:"COM",iso2:"KM",iso:"COM",label:"Comoros",phone:"269"},{ioc:"SKN",iso2:"KN",iso:"KNA",label:"Saint Kitts and Nevis",phone:"1-869"},{ioc:"KOR",iso2:"KP",iso:"KOR",label:"Korea, Democratic People's Republic of",phone:"850"},{ioc:"PRK",iso2:"KR",iso:"PRK",label:"Korea, Republic of",phone:"82"},{ioc:"KUW",iso2:"KW",iso:"KWT",label:"Kuwait",phone:"965"},{ioc:"CAY",iso2:"KY",iso:"CYM",label:"Cayman Islands",phone:"1-345"},{ioc:"KAZ",iso2:"KZ",iso:"KAZ",label:"Kazakhstan",phone:"7"},{ioc:"LAO",iso2:"LA",iso:"LAO",label:"Lao People's Democratic Republic",phone:"856"},{ioc:"LIB",iso2:"LB",iso:"LBN",label:"Lebanon",phone:"961"},{ioc:"LCA",iso2:"LC",iso:"LCA",label:"Saint Lucia",phone:"1-758"},{ioc:"LIE",iso2:"LI",iso:"LIE",label:"Liechtenstein",phone:"423"},{ioc:"SRI",iso2:"LK",iso:"LKA",label:"Sri Lanka",phone:"94"},{ioc:"LBR",iso2:"LR",iso:"LBR",label:"Liberia",phone:"231"},{ioc:"LES",iso2:"LS",iso:"LSO",label:"Lesotho",phone:"266"},{ioc:"LTU",iso2:"LT",iso:"LTU",label:"Lithuania",phone:"370"},{ioc:"LUX",iso2:"LU",iso:"LUX",label:"Luxembourg",phone:"352"},{ioc:"LAT",iso2:"LV",iso:"LVA",label:"Latvia",phone:"371"},{ioc:"LBA",iso2:"LY",iso:"LBY",label:"Libya",phone:"218"},{ioc:"MAR",iso2:"MA",iso:"MAR",label:"Morocco",phone:"212"},{ioc:"MON",iso2:"MC",iso:"MCO",label:"Monaco",phone:"377"},{ioc:"MDA",iso2:"MD",iso:"MDA",label:"Moldova, Republic of",phone:"373"},{ioc:"MNE",iso2:"ME",iso:"MNE",label:"Montenegro",phone:"382"},{ioc:"",iso2:"MF",iso:"MAF",label:"Saint Martin (French part)",phone:"590"},{ioc:"MAD",iso2:"MG",iso:"MDG",label:"Madagascar",phone:"261"},{ioc:"MSH",iso2:"MH",iso:"MHL",label:"Marshall Islands",phone:"692"},{ioc:"MKD",iso2:"MK",iso:"MKD",label:"Macedonia, the Former Yugoslav Republic of",phone:"389"},{ioc:"MLI",iso2:"ML",iso:"MLI",label:"Mali",phone:"223"},{ioc:"MYA",iso2:"MM",iso:"MMR",label:"Myanmar",phone:"95"},{ioc:"MGL",iso2:"MN",iso:"MNG",label:"Mongolia",phone:"976"},{ioc:"MAC",iso2:"MO",iso:"MAC",label:"Macao",phone:"853"},{ioc:"NMA",iso2:"MP",iso:"NMP",label:"Northern Mariana Islands",phone:"1-670"},{ioc:"MRT",iso2:"MQ",iso:"MTQ",label:"Martinique",phone:"596"},{ioc:"MTN",iso2:"MR",iso:"MRT",label:"Mauritania",phone:"222"},{ioc:"MNT",iso2:"MS",iso:"MSR",label:"Montserrat",phone:"1-664"},{ioc:"MLT",iso2:"MT",iso:"MLT",label:"Malta",phone:"356"},{ioc:"MRI",iso2:"MU",iso:"MUS",label:"Mauritius",phone:"230"},{ioc:"MDV",iso2:"MV",iso:"MDV",label:"Maldives",phone:"960"},{ioc:"MAW",iso2:"MW",iso:"MWI",label:"Malawi",phone:"265"},{ioc:"MEX",iso2:"MX",iso:"MEX",label:"Mexico",phone:"52"},{ioc:"MAS",iso2:"MY",iso:"MYS",label:"Malaysia",phone:"60"},{ioc:"MOZ",iso2:"MZ",iso:"MOZ",label:"Mozambique",phone:"258"},{ioc:"NAM",iso2:"NA",iso:"NAM",label:"Namibia",phone:"264"},{ioc:"NCL",iso2:"NC",iso:"NCL",label:"New Caledonia",phone:"687"},{ioc:"NIG",iso2:"NE",iso:"NER",label:"Niger",phone:"227"},{ioc:"NFI",iso2:"NF",iso:"NFK",label:"Norfolk Island",phone:"672"},{ioc:"NGR",iso2:"NG",iso:"NGA",label:"Nigeria",phone:"234"},{ioc:"NCA",iso2:"NI",iso:"NIC",label:"Nicaragua",phone:"505"},{ioc:"NED",iso2:"NL",iso:"NLD",label:"Netherlands",phone:"31"},{ioc:"NOR",iso2:"NO",iso:"NOR",label:"Norway",phone:"47"},{ioc:"NEP",iso2:"NP",iso:"NPL",label:"Nepal",phone:"977"},{ioc:"NRU",iso2:"NR",iso:"NRU",label:"Nauru",phone:"674"},{ioc:"NIU",iso2:"NU",iso:"NIU",label:"Niue",phone:"683"},{ioc:"NZL",iso2:"NZ",iso:"NZL",label:"New Zealand",phone:"64"},{ioc:"OMA",iso2:"OM",iso:"OMN",label:"Oman",phone:"968"},{ioc:"PAN",iso2:"PA",iso:"PAN",label:"Panama",phone:"507"},{ioc:"PER",iso2:"PE",iso:"PER",label:"Peru",phone:"51"},{ioc:"FPO",iso2:"PF",iso:"PYF",label:"French Polynesia",phone:"689"},{ioc:"PNG",iso2:"PG",iso:"PNG",label:"Papua New Guinea",phone:"675"},{ioc:"PHI",iso2:"PH",iso:"PHL",label:"Philippines",phone:"63"},{ioc:"PAK",iso2:"PK",iso:"PAK",label:"Pakistan",phone:"92"},{ioc:"POL",iso2:"PL",iso:"POL",label:"Poland",phone:"48"},{ioc:"SPM",iso2:"PM",iso:"SPM",label:"Saint Pierre and Miquelon",phone:"508"},{ioc:"",iso2:"PN",iso:"PCN",label:"Pitcairn",phone:"870"},{ioc:"PUR",iso2:"PR",iso:"PRI",label:"Puerto Rico",phone:"1"},{ioc:"PLE",iso2:"PS",iso:"PSE",label:"Palestine, State of",phone:"970"},{ioc:"POR",iso2:"PT",iso:"PRT",label:"Portugal",phone:"351"},{ioc:"PLW",iso2:"PW",iso:"PLW",label:"Palau",phone:"680"},{ioc:"PAR",iso2:"PY",iso:"PRY",label:"Paraguay",phone:"595"},{ioc:"QAT",iso2:"QA",iso:"QAT",label:"Qatar",phone:"974"},{ioc:"REU",iso2:"RE",iso:"REU",label:"Reunion",phone:"262"},{ioc:"ROU",iso2:"RO",iso:"ROU",label:"Romania",phone:"40"},{ioc:"SRB",iso2:"RS",iso:"SRB",label:"Serbia",phone:"381"},{ioc:"RUS",iso2:"RU",iso:"RUS",label:"Russia",phone:"7"},{ioc:"RWA",iso2:"RW",iso:"RWA",label:"Rwanda",phone:"250"},{ioc:"KSA",iso2:"SA",iso:"SAU",label:"Saudi Arabia",phone:"966"},{ioc:"SOL",iso2:"SB",iso:"SLB",label:"Solomon Islands",phone:"677"},{ioc:"SEY",iso2:"SC",iso:"SYC",label:"Seychelles",phone:"248"},{ioc:"SUD",iso2:"SD",iso:"SDN",label:"Sudan",phone:"249"},{ioc:"SWE",iso2:"SE",iso:"SWE",label:"Sweden",phone:"46"},{ioc:"SIN",iso2:"SG",iso:"SGP",label:"Singapore",phone:"65"},{ioc:"HEL",iso2:"SH",iso:"SHN",label:"Saint Helena",phone:"290"},{ioc:"SLO",iso2:"SI",iso:"SVN",label:"Slovenia",phone:"386"},{ioc:"",iso2:"SJ",iso:"SJM",label:"Svalbard and Jan Mayen",phone:"47"},{ioc:"SVK",iso2:"SK",iso:"SVK",label:"Slovakia",phone:"421"},{ioc:"SLE",iso2:"SL",iso:"SLE",label:"Sierra Leone",phone:"232"},{ioc:"SMR",iso2:"SM",iso:"SMR",label:"San Marino",phone:"378"},{ioc:"SEN",iso2:"SN",iso:"SEN",label:"Senegal",phone:"221"},{ioc:"SOM",iso2:"SO",iso:"SOM",label:"Somalia",phone:"252"},{ioc:"SUR",iso2:"SR",iso:"SUR",label:"Suriname",phone:"597"},{ioc:"",iso2:"SS",iso:"SSD",label:"South Sudan",phone:"211"},{ioc:"STP",iso2:"ST",iso:"STP",label:"Sao Tome and Principe",phone:"239"},{ioc:"ESA",iso2:"SV",iso:"SLV",label:"El Salvador",phone:"503"},{ioc:"",iso2:"SX",iso:"SMX",label:"Sint Maarten",phone:"1-721"},{ioc:"SYR",iso2:"SY",iso:"SYR",label:"Syria",phone:"963"},{ioc:"",iso2:"SZ",iso:"SWZ",label:"Swaziland",phone:"268"},{ioc:"TKS",iso2:"TC",iso:"TCA",label:"Turks and Caicos Islands",phone:"1-649"},{ioc:"CHA",iso2:"TD",iso:"TCD",label:"Chad",phone:"235"},{ioc:"",iso2:"TF",iso:"ATF",label:"French Southern Territories",phone:"262"},{ioc:"TOG",iso2:"TG",iso:"TGO",label:"Togo",phone:"228"},{ioc:"THA",iso2:"TH",iso:"THA",label:"Thailand",phone:"66"},{ioc:"TJK",iso2:"TJ",iso:"TJK",label:"Tajikistan",phone:"992"},{ioc:"",iso2:"TK",iso:"TKL",label:"Tokelau",phone:"690"},{ioc:"TLS",iso2:"TL",iso:"TLS",label:"Timor-Leste",phone:"670"},{ioc:"TKM",iso2:"TM",iso:"TKM",label:"Turkmenistan",phone:"993"},{ioc:"TUN",iso2:"TN",iso:"TUN",label:"Tunisia",phone:"216"},{ioc:"TGA",iso2:"TO",iso:"TON",label:"Tonga",phone:"676"},{ioc:"TUR",iso2:"TR",iso:"TUR",label:"Turkey",phone:"90"},{ioc:"TTO",iso2:"TT",iso:"TTO",label:"Trinidad and Tobago",phone:"1-868"},{ioc:"TUV",iso2:"TV",iso:"TUV",label:"Tuvalu",phone:"688"},{ioc:"TPE",iso2:"TW",iso:"TWN",label:"Taiwan",phone:"886"},{ioc:"TAN",iso2:"TZ",iso:"TZA",label:"United Republic of Tanzania",phone:"255"},{ioc:"UKR",iso2:"UA",iso:"UKR",label:"Ukraine",phone:"380"},{ioc:"UGA",iso2:"UG",iso:"UGA",label:"Uganda",phone:"256"},{ioc:"USA",iso2:"US",label:"United States",phone:"1",suggested:!0,iso:"USA"},{ioc:"URU",iso2:"UY",iso:"URY",label:"Uruguay",phone:"598"},{ioc:"UZB",iso2:"UZ",iso:"UZB",label:"Uzbekistan",phone:"998"},{ioc:"",iso2:"VA",iso:"VAT",label:"Holy See (Vatican City State)",phone:"379"},{ioc:"VIN",iso2:"VC",iso:"VCT",label:"Saint Vincent and the Grenadines",phone:"1-784"},{ioc:"VEN",iso2:"VE",iso:"VEN",label:"Venezuela",phone:"58"},{ioc:"IVB",iso2:"VG",iso:"VGB",label:"British Virgin Islands",phone:"1-284"},{ioc:"ISV",iso2:"VI",iso:"VIR",label:"US Virgin Islands",phone:"1-340"},{ioc:"VIE",iso2:"VN",iso:"VNM",label:"Vietnam",phone:"84"},{ioc:"VAN",iso2:"VU",iso:"VUT",label:"Vanuatu",phone:"678"},{ioc:"WAF",iso2:"WF",iso:"WLF",label:"Wallis and Futuna",phone:"681"},{ioc:"SAM",iso2:"WS",iso:"WSM",label:"Samoa",phone:"685"},{ioc:"KOS",iso2:"XK",iso:"KOS",label:"Kosovo",phone:"383"},{ioc:"YEM",iso2:"YE",iso:"YEM",label:"Yemen",phone:"967"},{ioc:"MAY",iso2:"YT",iso:"MYT",label:"Mayotte",phone:"262"},{ioc:"RSA",iso2:"ZA",iso:"ZAF",label:"South Africa",phone:"27"},{ioc:"ZAM",iso2:"ZM",iso:"ZMB",label:"Zambia",phone:"260"},{ioc:"ZIM",iso2:"ZW",iso:"ZWE",label:"Zimbabwe",phone:"263"}];function xU({participant:e,withISO2:t,withIOC:r}){const{person:n,individualParticipants:i}=e;[n,i?.map((({person:e})=>e))].flat().filter(Boolean).forEach((function(e){const{nationalityCode:n}=e||{};if(n){const i=_U.find((({iso:e})=>e===n));r&&i?.ioc&&!e.iocNationalityCode&&(e.iocNationalityCode=i.ioc),t&&i?.iso2&&!e.iso2NationalityCode&&(e.iso2NationalityCode=i.iso2),i?.label&&!e.countryName&&(e.countryName=i.label)}}))}const LU={[Im]:"groupParticipantIds",[Um]:"pairParticipantIds",[ym]:"teamParticipantIds"},VU={[Im]:"groups",[ym]:"teams"};function BU({withIndividualParticipants:e,convertExtensions:t,tournamentRecord:r,withSignInStatus:n,withScaleValues:i,internalUse:a,withISO2:o,withIOC:s}){const c={};for(const e of r.participants??[]){const t=e?.participantId;t&&qU({participantMap:c,participantId:t})}for(const e of r.participants??[]){const r=Jc(e,t,a),{participantId:u,individualParticipantIds:d,participantType:p}=r;if(Object.assign(c[u].participant,r),d&&GU({individualParticipantIds:d,participantCopy:r,participantMap:c,participantType:p,participantId:u}),n&&(c[u].participant.signedIn=jU(r)),i){const{ratings:e,rankings:t,seedings:n}=Hu({participant:r});c[u].participant.seedings=n,c[u].participant.rankings=t,c[u].participant.ratings=e}(s||o)&&xU({participant:c[u].participant,withISO2:o,withIOC:s})}if(e){!function({participantMap:e,template:t}){const r=Object.values(e);for(const n of r){const r=n.participant;if(r.individualParticipantIds?.length){r.individualParticipants=[];for(const n of r.individualParticipantIds){const i=e[n].participant;r.individualParticipants.push(t?zu({template:t,source:i}):i)}}}}({participantMap:c,template:ru(e)?e:void 0})}return{participantMap:c}}function jU(e){const{timeItem:t}=ng({itemType:lm,element:e});return t?.itemValue===fm}function GU({individualParticipantIds:e,participantCopy:t,participantMap:r,participantType:n,participantId:i}){for(const a of e){const o=r[a].participant;if(o[LU[n]].push(i),[ym,Im].includes(n)){const{participantRoleResponsibilities:e,participantOtherName:r,participantName:i,participantId:a,teamId:s}=t;o[VU[n]].push({participantRoleResponsibilities:e,participantOtherName:r,participantName:i,participantId:a,teamId:s})}if(n===Um){const t=e.find((e=>e!==a));r[a].pairIdMap[i]=t,r[a].pairIdMap[t]=i}}}function qU({participantMap:e,participantId:t}){if(e[t])return;const r={walkoverWins:0,defaultWins:0,walkovers:0,defaults:0,losses:0,wins:0};e[t]={structureParticipation:{},potentialMatchUps:{},scheduleConflicts:{},scheduleItems:[],participant:{groupParticipantIds:[],pairParticipantIds:[],teamParticipantIds:[],seedings:{},rankings:{},ratings:{},groups:[],teams:[]},statistics:{},opponents:{},pairIdMap:{},matchUps:{},events:{},draws:{},counters:{[mf]:{...r},[hf]:{...r},[ym]:{...r},...r}}}function $U({participantsProfile:e,useParticipantMap:t,tournamentRecord:r,contextProfile:n,inContext:i}){if(t){const t=BU({...e,...n,tournamentRecord:r})?.participantMap;return{participantMap:t}}let a,o=Jc(r.participants,!1,!0)||[];if((e?.withIOC||e?.withISO2)&&o.forEach((t=>xU({participant:t,...e}))),(i||e?.withGroupings)&&o?.length&&({participantsWithGroupings:o,groupInfo:a}=Eh({participantsProfile:e,deepCopy:!1,participants:o})),e?.withScaleValues&&o?.length)for(const e of o){const{ratings:t,rankings:r}=Hu({participant:e});e.rankings=r,e.ratings=t}return{participants:o,groupInfo:a}}const WU={[Qu]:{policyName:"Competitive Bands Default",profileBands:{[$g]:20,[qg]:50}}};function HU({policyDefinitions:e,tournamentRecord:t,contextProfile:r,drawDefinition:n,event:i}){const a={policies:{}};if(!r)return a;const o=Fh({tournamentRecord:t,drawDefinition:n,event:i}).policyDefinitions;if(r.withCompetitiveness){const t=e?.[Qu]??o?.[Qu]??WU[Qu];a.policies[Qu]=t}return a}function zU(e){let{participants:t,participantMap:r,contextContent:n}=e;const{scheduleVisibilityFilters:i,tournamentAppliedPolicies:a,participantsProfile:o,afterRecoveryTimes:s,policyDefinitions:c,useParticipantMap:u,tournamentRecord:d,matchUpFilters:p,contextFilters:l,contextProfile:m,drawDefinition:f,nextMatchUps:h,inContext:g,context:I,event:U}=e,{eventId:y,eventName:S,eventType:v,category:T,gender:P,matchUpFormat:D}=U??{},w={...I,eventId:y,eventType:v,eventName:S,category:T,gender:P,matchUpFormat:D,indoorOutDoor:U?.indoorOutdoor??d?.indoorOutdoor,surfaceCategory:U?.surfaceCategory??d?.surfaceCategory,endDate:U?.endDate};let b;t?.length||r||!d||({participants:t=[],participantMap:r,groupInfo:b}=$U({participantsProfile:o,useParticipantMap:u,policyDefinitions:c,tournamentRecord:d,contextProfile:m,inContext:g})),m&&!n&&(n=HU({policyDefinitions:c,tournamentRecord:d,contextProfile:m,drawDefinition:f,event:U}));return{...Em({context:w,tournamentAppliedPolicies:a,scheduleVisibilityFilters:i,tournamentParticipants:t,participantsProfile:o,afterRecoveryTimes:s,policyDefinitions:c,tournamentRecord:d,drawDefinition:f,contextContent:n,contextFilters:l,contextProfile:m,matchUpFilters:p,participantMap:r,nextMatchUps:h,inContext:g,event:U}),groupInfo:b}}function YU({tournamentRecord:e,drawDefinition:t,policyType:r,structure:n,event:i}){if(!e)return{error:Fi};const{appliedPolicies:a}=Oh({tournamentRecord:e,drawDefinition:t,structure:n,event:i});return a?.[r]?{policy:a[r]}:{info:Ya?.message}}function QU({tournamentRecord:e,categoryName:t,categoryType:r,event:n}){t=t??n?.category?.categoryName??n?.category?.ageCategoryCode,r=r??n?.category?.categoryType??n?.category?.subType;const{policy:i}=YU({policyType:nd,tournamentRecord:e,event:n}),a=e?Wl({element:e,name:vi}).extension:void 0,o=a?.value,s=n&&Wl({name:vi,element:n}).extension,c=s?.value;return{scheduleTiming:{tournamentScheduling:o,eventScheduling:c,categoryName:t,categoryType:r,policy:i}}}function KU(e){let{participants:t=[],contextContent:r,participantMap:n}=e;const{scheduleVisibilityFilters:i,tournamentAppliedPolicies:a,participantsProfile:o,afterRecoveryTimes:s,policyDefinitions:c,useParticipantMap:u,tournamentRecord:d,contextFilters:p,contextProfile:l,matchUpFilters:m,nextMatchUps:f,inContext:h,context:g,event:I}=e;if(!I)return{error:Ua};const{eventId:U,eventName:y,endDate:S,category:v,gender:T,matchUpFormat:P}=I,D={...g,...Mf({indoorOutDoor:I.indoorOutdoor??d?.indoorOutdoor,surfaceCategory:I.surfaceCategory??d?.surfaceCategory,endDate:I.endDate??d?.endDate,tournamentId:d?.tournamentId,matchUpFormat:P,eventName:y,category:v,gender:T,eventId:U})};let w;if(S&&(D.endDate=S),l&&!r&&(r=HU({policyDefinitions:c,tournamentRecord:d,contextProfile:l,event:I})),!t?.length&&!n&&d){const e=$U({participantsProfile:o,useParticipantMap:u,policyDefinitions:c,tournamentRecord:d,contextProfile:l,inContext:h});n=e.participantMap,t=e.participants??[],w=e.groupInfo}const b=I.drawDefinitions??[],R=QU({tournamentRecord:d,event:I}).scheduleTiming;return{matchUps:b.flatMap((e=>{const{matchUps:u}=Em({tournamentParticipants:t,tournamentAppliedPolicies:a,scheduleVisibilityFilters:i,context:D,participantsProfile:o,afterRecoveryTimes:s,policyDefinitions:c,tournamentRecord:d,contextFilters:p,contextProfile:l,drawDefinition:e,contextContent:r,matchUpFilters:m,participantMap:n,scheduleTiming:R,nextMatchUps:f,inContext:h,event:I});return u??[]})),groupInfo:w}}function JU({excludedMatchUpStatuses:e=[],includeEventParticipants:t,includeQualifyingStage:r,finishingRoundLimit:n,policyDefinitions:i,roundNumberLimit:a,tournamentRecord:o,drawDefinition:s,matchUpsLimit:c,requirePlay:u,requireLoss:d,allEntries:p,winsLimit:l,event:m}){if(!s)return{error:Li};const f=[qp,zp];r&&f.push($p);const h=m?.eventType?{matchUpTypes:[m.eventType]}:void 0,g=s?.matchUpType?{matchUpTypes:[s.matchUpType]}:void 0,I=t&&m?KU({contextFilters:{stages:f},matchUpFilters:h,tournamentRecord:o,inContext:!0,event:m})?.matchUps??[]:zU({contextFilters:{stages:f},matchUpFilters:g,tournamentRecord:o,inContext:!0,drawDefinition:s})?.matchUps??[],U=ah({stage:Hp,drawDefinition:s}).map((({participantId:e})=>e)),y={},S={},v={},T={};i||(i=Fh({policyTypes:[Yu],tournamentRecord:o,drawDefinition:s,event:m}).policyDefinitions);const P=i?.[Yu];e=e.length&&e||P?.excludedMatchUpStatuses||[],t=t??P?.includeEventParticipants,p=p??P?.allEntries,n=n??P?.finishingRoundLimit,a=a??P?.roundNumberLimit,c=c??P?.matchUpsLimit,void 0===u&&(u=void 0===P?.requirePlay||P.requirePlay),void 0===d&&(d=void 0===P?.requireLoss||P.requireLoss),l=l??P?.winsLimit;for(const t of I){if(u&&t.winningSide&&![1,2].includes(t.winningSide)&&t.matchUpStatus!==qm)continue;if(t.finishingRound&&n&&t.finishingRound>=n)continue;if(t.finishingRound&&a&&t.finishingRound<=a)continue;const r=t.sides?.find((({sideNumber:e})=>t.winningSide&&e===3-t.winningSide)),i=t.sides?.find((({sideNumber:e})=>t.winningSide&&e===t.winningSide));if(t.sides?.forEach((r=>{const n=r?.participant?.participantId;n&&(v[n]=r.participant,t.matchUpStatus!==qm||u||(S[n]=r.participant,y[n]||(y[n]=0),t.matchUpStatus&&e.includes(t.matchUpStatus)||(y[n]+=1)))})),r?.participant){const n=r.participant.participantId;S[n]=r.participant,y[n]||(y[n]=0),t.matchUpStatus&&!e.includes(t.matchUpStatus)&&(y[n]+=1)}if(i?.participant){const r=i.participant.participantId;T[r]||(T[r]=0),T[r]+=1,y[r]||(y[r]=0),t.matchUpStatus&&!e.includes(t.matchUpStatus)&&(y[r]+=1)}}const D=o?.participants&&!u&&!d&&p,w=D?((t&&m?m.entries:s.entries)??[]).filter((e=>![am,rm].includes(e.entryStatus))).map((({participantId:e})=>e)):[],b=Object.keys(S),R=D?(o?.participants??[]).filter((({participantId:e})=>w.includes(e))):d&&Object.values(S)||Object.values(v);return{eligibleParticipants:R.filter((e=>{return t=e.participantId,(!d||b.includes(t))&&(e=>!u||(y[e]||0)>=0)(e.participantId)&&(e=>!l||(T[e]||0)<=l)(e.participantId)&&(e=>!c||y[e]<=c)(e.participantId)&&(e=>!U.includes(e))(e.participantId);var t})).map((e=>({...e,individualParticipants:e.individualParticipantIds?.map((e=>o?.participants?.find((t=>t.participantId===e))))}))),losingParticipantIds:b,...Ni}}function ZU({drawDefinition:e}){const t=Wl({name:"participantRepresentatives",element:e});if(t.error)return t;return{representativeParticipantIds:t.extension?.value||[]}}function XU({drawDefinition:e,structureIds:t,matchUpsMap:r}){if(t&&!Array.isArray(t))return{error:ys,context:{structureIds:t}};if(!e)return{error:Li};const n=(t=t??(e.structures??[]).filter((e=>e.stage!==$p)).map((({structureId:e})=>e))).map((t=>{const{roundProfile:n}=$t({drawDefinition:e,matchUpsMap:r,structureId:t}),i=n&&Object.values(n);return i?.map(qt).flat()})).flat(),i=n.filter((e=>1===e?.length)).sort(fe).flat();return{positionsNotPlayedOff:u(n.flat()).filter((e=>!i.includes(e))),positionsPlayedOff:i}}function ey({drawDefinition:e,matchUpsMap:t,structureId:r}){const n=w({drawDefinition:e,structureId:r});if(n.error)return a({result:n});const{matchUps:i}=J({structure:n.structure,matchUpsMap:t});return{...Cf({matchUps:i}),matchUps:i,matchUpsMap:t}}function ty({finishingPositions:e,drawDefinition:t,structureId:r}){const{roundProfile:n}=ey({drawDefinition:t,structureId:r}),i=n&&Object.keys(n);return i?.reduce(((t,r)=>{var i;return(i=n?.[r],[jd(i?.finishingPositionRange?.loser||[]),jd(i?.finishingPositionRange?.winner||[])]).forEach((n=>{e.forEach((e=>{(function({position:e,rangeDefinition:t}){if(!Array.isArray(t))return!1;if(t.reduce(((e,t)=>e||isNaN(t)),!1))return!1;const[r,n]=t;return Qd(r,(n||r)+1).includes(e)})({position:e,rangeDefinition:n})&&(t[e]={roundNumber:r})}))})),t}),{})}function ry({excludeRoundNumbers:e=[],playoffPositions:t=[],drawDefinition:r,structureId:n}){if(!r)return{error:Li};if(!n)return{error:la};if(!t)return{error:Za,info:"missing playoffPositions"};const i=XU({drawDefinition:r});if(i.error)return i;const a=i.positionsPlayedOff,o=ty({finishingPositions:t.filter((e=>!a.includes(e))),drawDefinition:r,structureId:n}),s=Object.values(o).reduce(((e,t)=>e.includes(t.roundNumber)?e:e.concat(t.roundNumber)),[]).map((e=>Ed(e))).filter((t=>!e.includes(t))),c=ty({finishingPositions:a,drawDefinition:r,structureId:n}),u=c?Object.values(c):[],d=c?u.reduce(((e,t)=>e.includes(t.roundNumber)?e:e.concat(t.roundNumber)),[]).map((e=>Ed(e))):[],p=s.filter((e=>!d.includes(e))).sort(Ad),{roundProfile:l}=ey({drawDefinition:r,structureId:n}),m=p.map((e=>{const t=l?.[e].finishingPositionRange.loser,[r,n]=t??[0,0];return Qd(r,(n||r)+1)})).flat().sort(Ad),{playoffRoundsRanges:f}=function({playoffSourceRounds:e,roundProfile:t}){const r=e.map((e=>{const r=t[e].finishingPositionRange.loser,[n,i]=r,a=Qd(n,(i||n)+1);return{finishingPositionRange:r.join("-"),finishingPositions:a,roundNumber:e}}));return{playoffRoundsRanges:r}}({playoffSourceRounds:p,roundProfile:l}),h=[...p,...d];return{playoffPositionsReturned:m,playedOffSourceRounds:d,playoffRoundsRanges:f,playoffSourceRounds:p,sourceRounds:h,roundProfile:l}}function ny({drawDefinition:e,structureId:t}){if(!e)return{error:Li};const{matchUps:r,matchUpsMap:n}=zU({inContext:!0,drawDefinition:e}),{positionsNotPlayedOff:i,positionsPlayedOff:a}=XU({drawDefinition:e,matchUpsMap:n}),{structures:o}=Fm({drawDefinition:e}),s=o.filter((e=>!t&&e.stage!==Hp||e.structureId===t)),c={};for(const t of s){const n=t?.structureId,a=iy({playoffPositions:i,drawDefinition:e,structure:t,matchUps:r}),{error:o,...s}=a;if(o)return a;c[n]={structureId:n,...s}}return t?{positionsPlayedOff:a,...c[t]}:{availablePlayoffProfiles:Object.values(c),availablePlayoffRounds:Object.values(c),positionsPlayedOff:a}}function iy({playoffPositions:e,drawDefinition:t,structure:r,matchUps:n}){const i=r?.structureId,{links:a}=FI({drawDefinition:t,structureId:i});if(r.structureType===nl||r.structures){const e=op({structure:r})?.positionAssignments?.length,o=r.structures.length,s=(e??0)/o,c=a.source?.flatMap((({source:e})=>e?.finishingPositions||[]))||[],u=Qd(1,s+1).filter((e=>!c.includes(e))),d=n.find((e=>e.containerStructureId===i&&e.finishingPositionRange))?.finishingPositionRange?.winner||[0,1],p=a?.source.map((({target:e})=>e.structureId)),{positionsPlayedOff:l=[],positionsNotPlayedOff:m=[]}=XU({structureIds:p,drawDefinition:t}),f=[...l,...m],h=Qd(d[0],d[1]+1).filter((e=>!f.includes(e))),g=ep(h,h.length/u.length);return{positionsNotPlayedOff:h,playoffFinishingPositionRanges:u.map(((e,t)=>{const r=g[t];return{finishingPosition:e,finishingPositions:r,finishingPositionRange:[Math.min(...r||[]),Math.max(...r||[])].join("-")}})),finishingPositionsAvailable:u,finishingPositionsPlayedOff:c,positionsPlayedOff:l,groupCount:o,groupSize:s}}const o=a?.source?.filter((e=>e.linkCondition!==pl)).map((e=>e.source?.roundNumber))||[],s=a?.source?.filter((e=>e.linkCondition===pl)).map((e=>e.source?.roundNumber))||[],c=ry({excludeRoundNumbers:o,playoffPositions:e,drawDefinition:t,structureId:i}),u=c?.playoffSourceRounds?[...c?.playoffSourceRounds||[]]:void 0,d=[...c?.playoffRoundsRanges||[]],{roundProfile:p,error:l}=c;for(const e of s){const t=a?.source.find((t=>t.source.roundNumber===e)),r=t?.target.roundNumber,i=t?.target.structureId,o=n.filter((({roundNumber:e,structureId:t})=>t===i&&e===r)),s=o.filter((({sides:e})=>e.find((e=>e.participantFed&&!e.participantId)))).length;if(u&&s===o.length){u.push(e);const t=p?.[e]?.finishingPositionRange?.loser;if(t){const r=Math.min(...t),n=r+s,i=Qd(r,n),a={finishingPositionRange:[r,n-1].join("-"),finishingPositions:i,roundNumber:e};d.push(a)}}}return u&&u.sort(Ad),d.sort(((e,t)=>e.roundNumber-t.roundNumber)),{playoffRounds:u,playoffRoundsRanges:d,error:l}}function ay({byeAdvancements:e=!1,tournamentRecord:t,drawDefinition:r}){if(!r)return{error:Li};const{participantIds:n,participantIdMatchUps:i}=function({tournamentParticipants:e,drawDefinition:t,event:r}){if(!t)return{error:Li};const n=Jc(Em({tournamentParticipants:e,inContext:!0,drawDefinition:t,event:r}).matchUps,!1,!0),i=jd(n.reduce(((e,t)=>e.concat(...t.sides.map((e=>e.participantId)).filter(Boolean))),[])),a=Object.assign({},...i.map((e=>{const t=n.filter((t=>t.sides.map((e=>e.participantId)).filter(Boolean).includes(e)));return{[e]:t}})));return{participantIds:i,participantIdMatchUps:a}}({tournamentParticipants:t?.participants,drawDefinition:r}),a=n?.map((t=>{const r=i[t].filter((e=>[Vm,xm].includes(e.matchUpStatus)||e.winningSide)),n=r.map((r=>{const n=r.sides.find((e=>e.bye)),i=r.sides.find((e=>e.participantId===t)).sideNumber;return(r.winningSide||e&&n&&i)===i?r.finishingPositionRange.winner:r.finishingPositionRange.loser})),a=e=>Math.abs(e[0]-e[1]),o=n.reduce(((e,t)=>e&&a(e)<a(t)?e:t),void 0);return{[t]:{relevantMatchUps:r,finishingPositionRanges:n,finishingPositionRange:o}}}))||[];return Object.assign({},...a)}function oy({drawDefinition:e,stages:t}){if(!e)return{error:Li};const r=(e?.structures??[]).filter((e=>!t?.length||e.stage&&t.includes(e.stage))),n=u(r.map((e=>{const{positionAssignments:t}=op({structure:e});return t?t.map(v):[]})).flat().filter(Boolean));return{...Ni,assignedParticipantIds:n}}const sy={[gu]:Oi,[Uu]:Fi,[Iu]:qa,[yu]:Li,[vu]:Do,tournamentId:_i,[Pu]:la,[wu]:xa,[Du]:To,[bu]:fa,[Ru]:_a,[Mu]:ha,[Ou]:Ja,[Cu]:Va,[ku]:Ba,[Au]:Za,[Eu]:Za,[_u]:ra,[Fu]:Ua,[Lu]:ya},cy={[gu]:Bu,[Iu]:Bu,[Uu]:Bu,[yu]:Bu,[Tu]:ju,[Du]:Bu,[wu]:ju,[bu]:ju,[Mu]:Bu,[Au]:ju,[Eu]:ju,[Cu]:ju,[ku]:Bu,[Lu]:Bu,uuids:ju};function uy(e,t,r){if(!e&&!mt(e))return{error:ys};if(!t?.length||e?._bypassParamCheck)return{valid:!0};if(!Array.isArray(t))return{error:ys};const{paramError:n,errorParam:i}=function(e,t){let r;const n=t.find((({_ofType:t,_oneOf:n,_anyOf:i,validate:a,...o})=>{const s=n&&function(e,t){if(!t)return;const r=dy(e,t);return 1!==r.length?{error:ys}:r.reduce(((e,t)=>({...e,[t]:!0})),{})}(e,n);if(s?.error)return s.error;s&&Object.assign(o,s);const c=i&&function(e,t){if(!t)return;const r=dy(e,t).filter((t=>e[t]));return r.length<1?{error:ys}:r.reduce(((e,t)=>({...e,[t]:!0})),{})}(e,i);if(c?.error)return c.error;c&&Object.assign(o,c);const u=Object.keys(o).filter((e=>"boolean"==typeof o[e])),d=u.find((n=>{const i=a&&!ht(a),s=e[n]&&!a&&function(e,t,r){if(r=r||cy[t]||"string","array"===r)return!Array.isArray(e[t]);return typeof e[t]!==r}(e,n,t),c=o[n]&&!e[n],u=i||s||c||a&&e[n]&&!function(e,t){return!ht(t)||t(e)}(e[n],a);return u&&(r=n),u}));return!u.length||d}));return{paramError:n,errorParam:r}}(e,t);if(!n)return{valid:!0};const o=void 0===e[i]?sy[i]||ys:n.validate&&n.invalid||ys;return a({info:{param:i},result:{error:o},stack:r})}function dy(e,t){const r=Object.keys(e),n=Object.keys(t);return c(r,n)}function py(e){const t=uy(e,[{[gu]:!0}]);if(t.error)return t;return Object.keys(e.tournamentRecords).reduce(((t,r)=>{t.tournamentIdMap[r]=[];const n=e.tournamentRecords[r].events??[],i=n.map((({eventId:e})=>e)),a=n.map((e=>(e.drawDefinitions??[]).map((({drawId:e})=>e)))).flat();return t.tournamentIdMap[r].push(...i,...a),t.eventIds.push(...i),t.drawIds.push(...a),t}),{eventIds:[],drawIds:[],tournamentIdMap:{}})}function ly(e){const{tournamentRecord:t,eventId:r,drawId:n}=e,i="findEvent",o={},s=e.tournamentRecords??(t&&{[t.tournamentId]:t})??{},c=Object.values(s).map((({events:e,tournamentId:t})=>(e&&e.forEach((e=>{o[e.eventId]={tournamentId:t}})),e??[]))).flat();let u;if(n){let e;const t=c.find((t=>{const r=(t?.drawDefinitions??[]).find((e=>e.drawId===n));if(r)e=r,u=o[t.eventId].tournamentId;else{const e=t&&Ot({event:t})?.flightProfile,r=e?.flights?.find((e=>e.drawId===n));if(r)return u=o[t.eventId].tournamentId,{entries:r.drawEntries,drawName:r.drawName,tournamentId:u,drawId:n}}return r}));if(t)return{event:t,drawDefinition:e,tournamentId:u}}if(r){const e=c.find((e=>e?.eventId===r));return e?(u=o[e.eventId].tournamentId,{event:e,drawDefinition:void 0,tournamentId:u}):{event:void 0,drawDefinition:void 0,...a({result:{error:ya},stack:i})}}return{event:void 0,drawDefinition:void 0,...a({result:{error:Bi},context:{drawId:n,eventId:r},stack:i})}}function my({tournamentRecords:e,tournamentRecord:t,tournamentId:r,drawId:n}){if(!t&&!e)return{error:Fi};if(!n)return{error:ra};if(!t&&e){if("string"!=typeof r&&(r=function({tournamentRecords:e,eventId:t,drawId:r}){const{tournamentIdMap:n}=py({tournamentRecords:e});return(n?Object.keys(n):[]).find((e=>t&&n?.[e].includes(t)||r&&n?.[e].includes(r)))}({tournamentRecords:e,drawId:n}),!r))return{error:_i};if(!(t=e[r]))return{error:Fi}}const i=t&&ly({tournamentRecord:t,drawId:n});return i?.drawDefinition?{drawDefinition:i.drawDefinition,event:i.event,tournamentRecord:t,...Ni}:pd({result:{error:Bi},stack:"findDrawDefinition"})}function fy(e){const{drawDefinition:t,error:r}=my(e);return r?{error:r}:{drawDefinition:L(t)}}const hy="qualifierDrawPositionAssignment",gy="alternateDrawPositionAssignment",Iy="luckyLoserDrawPositionAssignment",Uy="removeDrawPositionAssignment",yy="swapDrawPositionAssignments",Sy="modifyPairAssignment",vy="assignDrawPosition",Ty="assignDrawPositionBye",Py="addPenalty",Dy="MODIFY_PAIR",wy="QUALIFIER",by="ALTERNATE",Ry="WITHDRAW",Ny="ASSIGN",My="REMOVE",Ay="LUCKY",Ey="REMOVE_SEED",Cy="SWAP",Oy="NICKNAME",Fy="SEED_VALUE",ky="PENALTY",_y="BYE",xy={MODIFY_PAIR_ASSIGNMENT:Dy,QUALIFYING_PARTICIPANT:wy,ALTERNATE_PARTICIPANT:by,WITHDRAW_PARTICIPANT:Ry,ASSIGN_PARTICIPANT:Ny,LUCKY_PARTICIPANT:Ay,REMOVE_ASSIGNMENT:My,SWAP_PARTICIPANTS:Cy,ADD_NICKNAME:Oy,REMOVE_SEED:Ey,ADD_PENALTY:ky,ASSIGN_BYE:_y,SEED_VALUE:Fy};function Ly({drawPosition:e,matchUps:t=[]}){return{initialRoundNumber:t.filter((({drawPositions:t})=>e&&t?.includes(e))).map((({roundNumber:e})=>e)).sort(Ad)[0]}}function Vy({restrictQualifyingAlternates:e,structure:t,entry:r}){const{stage:n}=t;if(!r.entryStage||r.entryStage===n||n===$p&&!e||r.entryStage===qp&&n===Wp)return!0}function By(e,t){return e.bye||_h(e.seedValue)<_h(t.seedValue)||e.seedValue&&!t.seedValue?-1:(e.seedNumber||0)-(t.seedNumber||0)}function jy({targetRoundNumber:e,finishingPosition:t,drawDefinition:r,structureId:n,linkType:i}){const{links:a}=FI({drawDefinition:r,structureId:n})||{},o=(a?.target||[]).filter((({linkType:e})=>e===i)).filter((({target:t})=>!e||e===t.roundNumber)).map((e=>{const n=e.source.structureId,{structure:i}=Om({structureId:n,drawDefinition:r});if(!t||i?.finishingPosition===t)return e})).filter(Boolean);return{sourceStructureIds:o.map((({source:e})=>e.structureId)),relevantLinks:o}}const Gy={[Ju]:{policyName:"positionActionsDefault",enabledStructures:[{stages:[$p,qp],stageSequences:[1],enabledActions:[],disabledActions:[]},{stages:[],stageSequences:[],enabledActions:[Oy,ky,wy,Fy],disabledActions:[]}],disbledStructures:[],otherFlightEntries:!1,activePositionOverrides:[]}},qy={[Zu]:{policyName:"matchUpActionsDefault",enabledStructures:[{stages:[],stageSequences:[],enabledActions:[],disabledActions:[]}],participants:{enforceCategory:!0,enforceGender:!0},processCodes:{substitution:["RANKING.IGNORE","RATING.IGNORE"]},substituteAfterCompleted:!1,substituteWithoutScore:!1}},$y="positionAction",Wy="matchUpAction";function Hy({actionType:e=$y,appliedPolicies:t,drawDefinition:r,structure:n}){const i=e===$y&&Ju||e===Wy&&Zu,a=e===$y&&Gy||e===Wy&&qy,o=i&&(t?.[i]||a?.[i]),s=r.links?.filter((e=>e?.target?.structureId===n?.structureId)),c=s?.map((({target:e})=>e.feedProfile))??[],{enabledStructures:u,disabledStructures:d}=o||{},p=d?.find((e=>{const{stages:t,stageSequences:r,structureTypes:i,feedProfiles:a}=e;return(!a?.length||Array.isArray(a)&&a.some((e=>c.includes(e))))&&(!t?.length||Array.isArray(t)&&t?.includes(n?.stage))&&(!i?.length||Array.isArray(i)&&i?.includes(n?.structureType))&&(!r?.length||Array.isArray(r)&&r.includes(n?.stageSequence))}));return{enabledStructures:u,actionsDisabled:p,actionsPolicy:o}}function zy({activePositionOverrides:e,activeDrawPositions:t,action:r}){return!(!r||!e.includes(r))||!t.length}function Yy({enabledStructures:e,drawDefinition:t,structure:r}){if(!1===e)return{};if(!e?.length)return{policyActions:{enabledActions:[],disabledActions:[]}};const{stage:n,stageSequence:i,structureType:a}=r||{},o=t.links?.filter((e=>e?.target?.structureId===r?.structureId)),s=o?.map((({target:e})=>e.feedProfile))||[];return{policyActions:e.find((e=>{const{stages:t,stageSequences:r,structureTypes:o,feedProfiles:c}=e||{},u=!t?.length||Array.isArray(t)&&t.includes(n),d=!r?.length||Array.isArray(r)&&r.includes(i),p=!o?.length||Array.isArray(o)&&o.includes(a),l=!c?.length||Array.isArray(c)&&c.some((e=>s.includes(e)));return d&&p&&l&&e&&u}))}}function Qy({action:e,policyActions:t}){const r=!t?.enabledActions||t?.disabledActions?.length&&t.disabledActions.includes(e);if(r)return!1;return(0===t?.enabledActions.length||t?.enabledActions.includes(e))&&!r}const Ky="replaceTieMatchUpParticipantId",Jy="assignTieMatchUpParticipantId",Zy="removeTieMatchUpParticipantId",Xy="assignMatchUpSideParticipant",eS="removeMatchUpSideParticipant",tS="substituteParticipant",rS="REMOVE_SUBSTITUTION",nS="REPLACE_PARTICIPANT",iS="REMOVE_PARTICIPANT",aS="setMatchUpStatus",oS="SUBSTITUTION",sS="SCHEDULE",cS="REFEREE",uS="STATUS",dS="START",pS="SCORE",lS="END",mS={REPLACE_TEAM_POSITION_METHOD:Ky,ASSIGN_TEAM_POSITION_METHOD:Jy,REMOVE_TEAM_POSITION_METHOD:Zy,REPLACE_PARTICIPANT:nS,SUBSTITUTION_METHOD:tS,REMOVE_SUBSTITUTION:rS,REMOVE_PARTICIPANT:iS,SCHEDULE_METHOD:aS,SUBSTITUTION:oS,SCHEDULE:sS,PENALTY:"PENALTY",REFEREE:cS,STATUS:uS,SCORE:pS,START:dS,END:lS};function fS({restrictAdHocRoundParticipants:e,tournamentParticipants:t,matchUpParticipantIds:r,otherFlightEntries:n,drawDefinition:i,structureId:a,sideNumber:o,matchUpId:s,structure:c,matchUp:u,drawId:d,event:p}){const l=[],m=(c?.matchUps??[]).filter((({roundNumber:e})=>e===u.roundNumber)),f=i?.entries?.filter((({entryStatus:e})=>e&&cm.includes(e))).map(Rd)??[],h=m.map((e=>(e.sides??[]).flatMap(Rd))).flat().filter(Boolean),g=f.filter((t=>!(r.includes(t)||e&&h.includes(t)))),I=t?.filter((e=>g?.includes(e.participantId))).map((e=>Jc(e,void 0,!0)));I?.forEach((e=>{const t=(i.entries??[]).find((t=>t.participantId===e.participantId));e.entryPosition=t?.entryPosition})),g.length&&l.push({payload:{drawId:d,matchUpId:s,structureId:a,sideNumber:o},method:Xy,type:Ny,availableParticipantIds:g,participantsAvailable:I});const U=function({eventEntries:e,structure:t}){return e.filter((e=>e.entryStatus===zl&&Vy({structure:t,entry:e}))).sort(((e,t)=>(e.entryPosition||1/0)-(t.entryPosition||1/0))).map(Rd)}({eventEntries:p?.entries??[],structure:c});let y=jd(f.concat(U));if(n){const e=p?bU({event:p}):void 0,t=e?.flights?.filter((e=>e.drawId!==d)).flatMap((e=>e.drawEntries.filter((e=>e.participantId&&![am,rm,nm].includes(e.entryStatus))).map((({participantId:e})=>e)))).filter(Boolean);t?.length&&y.push(...t)}y=y.filter((t=>!(r.includes(t)||g.includes(t)||e&&h.includes(t))));const S=t?.filter((e=>y.includes(e.participantId))).map((e=>Jc(e,void 0,!0)));if(S?.forEach((e=>{const t=(i.entries??[]).find((t=>t.participantId===e.participantId));e.entryPosition=t?.entryPosition})),S?.sort(((e,t)=>(e.entryPosition||1/0)-(t.entryPosition||1/0))),y.length&&l.push({payload:{drawId:d,matchUpId:s,structureId:a,sideNumber:o},availableParticipantIds:y,participantsAvailable:S,method:Xy,type:zl}),!hg(u)&&o){const e=u.sides?.find((e=>e.sideNumber===o));e?.participantId&&l.push({payload:{drawId:d,matchUpId:s,structureId:a,sideNumber:o},method:eS,type:iS})}return l}function hS(e){if(!e)return{error:ys};let t,r;const{restrictAdHocRoundParticipants:n=!0,policyDefinitions:i,enforceGender:o,participantId:s,sideNumber:c,matchUpId:u}=e,d=e.tournamentRecord??(e.tournamentId&&gt(e.tournamentId)&&e.tournamentRecords?.[e.tournamentId]);if(!d)return{error:Fi};if(!u||!gt(u))return{error:_a};if(c&&![1,2].includes(c))return a({result:{error:ys},context:{sideNumber:c}});if(!t){const e=(Lt({tournamentRecord:d}).matchUps??[]).find((e=>e.matchUpId===u));r=(d?.events??[]).find((t=>t.eventId===e?.eventId)),t=(r?.drawDefinitions??[]).find((t=>t.drawId===e?.drawId))}if(!t)return{error:Li};const p=pt({tournamentRecord:d,withIndividualParticipants:!0}).participants,{drawId:l}=t,{matchUp:m,structure:f}=Jt({drawDefinition:t,matchUpId:u,event:r});if(!m)return{error:La};const h=te({tournamentRecord:d,drawDefinition:t,structure:f,event:r}).appliedPolicies??{};Object.assign(h,i??{});const g=h?.[Ju]?.otherFlightEntries,I=h?.[Zu]??qy[Zu],{enabledStructures:U}=Hy({actionType:Wy,appliedPolicies:h,drawDefinition:t,structure:f}),{policyActions:y}=Yy({enabledStructures:U,drawDefinition:t,structure:f}),S=e.matchUpsMap??se({drawDefinition:t}),v=e.inContextDrawMatchUps??ue({tournamentParticipants:p,inContext:!0,drawDefinition:t,matchUpsMap:S,event:r}).matchUps,T=v?.find((e=>e.matchUpId===u)),P=c&&T?.sides?.find((e=>e.sideNumber===c)),D=T?.sides?.map((e=>e.participantId||e.participant?.participantid)).filter(Boolean)??[],{assignedPositions:w,allPositionsAssigned:b}=K({structure:f}),{structureId:R}=f??{},N=[];if(!R)return{validActions:N};const M=Se({drawDefinition:t,structure:f}),A=m.collectionId;if(M&&!A){const e=fS({restrictAdHocRoundParticipants:n,tournamentParticipants:p,matchUpParticipantIds:D,otherFlightEntries:g,drawDefinition:t,structureId:R,sideNumber:c,matchUpId:u,structure:f,matchUp:m,drawId:l,event:r});N.push(...e)}const E=zt({drawDefinition:t,structure:f}),C=w?.filter((e=>e.participantId)).map((e=>e.drawPosition)),O=w?.filter((e=>e.bye)).map((e=>e.drawPosition)),F=m.matchUpStatus===xm||!A&&m.drawPositions?.reduce(((e,t)=>O?.includes(t)||e),!1);if(F)return{validActions:N,isByeMatchUp:F};Qy({policyActions:y,action:cS})&&N.push({type:cS,payload:{matchUpId:u}});const k=!Qt({matchUpStatus:m.matchUpStatus}),_=h?.scoring?.structures,x=f?.stage&&_?.stage&&_?.stage[f.stage],L=f?.stageSequence&&x?.stageSequence&&x.stageSequence[f.stageSequence],V=!(h?.scoring?.requireAllPositionsAssigned||x?.requireAllPositionsAssigned||L?.requireAllPositionsAssigned)||b,B=m.sides&&2===m.sides.filter((e=>e?.participantId)).length,j=m.matchUpStatus&&[qm,Gm].includes(m.matchUpStatus),G=de({inContextDrawMatchUps:v,drawDefinition:t,matchUpId:u}),q=Yt({inContextDrawMatchUps:v,drawDefinition:t,targetData:G}),$=(2===T?.drawPositions?.length&&T.drawPositions.every((e=>C?.includes(e)))&&2===T?.sides?.length&&T.sides.every((({participantId:e})=>e))||B)&&!(j&&q),W={method:Py,type:ky,payload:{drawId:l,matchUpId:u,penaltyCode:void 0,penaltyType:void 0,participantIds:[],notes:void 0}};if(k&&N.push({payload:{drawId:l,matchUpId:u,schedule:{}},method:aS,type:sS}),Qy({policyActions:y,action:ky})&&(P?.participant||!c&&D?.length)&&N.push(W),k&&$&&N.push({type:uS}),V&&$){const{matchUpId:e,matchUpFormat:t}=m,r={drawId:l,matchUpId:e,matchUpFormat:t,outcome:{scoreStringSide1:void 0,scoreStringSide2:void 0,sets:[]},winningSide:void 0};N.push({info:"set outcome and winningSide",method:aS,type:pS,payload:r}),Qy({policyActions:y,action:dS})&&N.push({type:dS}),Qy({policyActions:y,action:lS})&&N.push({type:lS})}if(A&&T){const e=function({specifiedPolicyDefinitions:e,inContextDrawMatchUps:t,matchUpParticipantIds:r,matchUpActionsPolicy:n,inContextMatchUp:i,policyActions:a,enforceGender:o,participantId:s,sideNumber:c,matchUpId:u,matchUp:d,drawId:p,side:l}){const m=[],f=i.sides?.find((e=>e.participant)),h=i.gender===Vf&&i.sideNumber&&1===i.sides?.filter((e=>e.particiapntId)).length&&f?.participant?.person?.sex,g=i.matchUpType,I=!1!==(o??n?.participants?.enforceGender)?i.gender:void 0,U=i.sides?.flatMap((e=>e.participant?.individualParticipants||e.participant)).filter(Boolean),y=U?.map(Rd),S=i.sides?.filter((e=>!c||e.sideNumber===c)).flatMap((e=>e.participant?.individualParticipants||e.participant)).filter(Boolean),v=S?.map(Rd),T=t?.find((e=>e.matchUpId===i.matchUpTieId)),P=T?.sides?.map((e=>e.participant?.individualParticipants.filter((({participantId:e,person:t})=>!v?.includes(e)&&(!I||I===xf||t.sex===I||I===Vf&&!h||h&&t.sex!==h))))),D=c?P?.[c-1]:P?.map(((e,t)=>({participants:e,sideNumber:t+1}))),w=c?P?.[c-1]?.map(Rd):P?.map(((e,t)=>({participants:e?.map(Rd),sideNumber:t+1}))),b=c&&(g===lf&&!v?.length||g===ff&&(v?.length??0)<2)||!c&&(g===lf&&(v?.length??0)<2||g===ff&&(v?.length??0)<4),R=w?.filter((e=>!y?.includes(e))),N=D?.filter((({participantId:e})=>R.includes(e)));if(b&&R?.length&&m.push({availableParticipantIds:R,method:Jy,availableParticipants:N,type:Ny,payload:{participantId:void 0,tieMatchUpId:u,sideNumber:c,drawId:p}}),!v?.length||hg(d)&&!l?.substitutions?.length||m.push({method:Zy,type:iS,existingParticipantIds:v,payload:{participantId:void 0,tieMatchUpId:u,drawId:p}}),N?.length&&(!c&&v?.length||c&&l?.participant)&&m.push({availableParticipantIds:R,method:Ky,availableParticipants:N,type:nS,existingParticipantIds:v,payload:{existingParticipantId:void 0,participantId:void 0,tieMatchUpId:u,drawId:p}}),Qy({policyActions:a,action:rS})&&l?.substitutions?.length){const e=l.participant?.participantType===gm&&[l.participantId]||l.participant?.participantType===Um&&l.participant.individualParticipantIds||[],t=l.substitutions.map((e=>e.participantId)).filter((t=>e.includes(t)));s&&!t.includes(s)||m.push({method:Zy,type:rS,substitutedParticipantIds:t,payload:{participantId:void 0,tieMatchUpId:u,drawId:p}})}const M=e?.[Zu],A=M?.substituteWithoutScore,E=M?.substituteAfterCompleted;if(Qy({policyActions:a,action:oS})&&2===r.length&&(!c&&v?.length||c&&l?.participant)&&(A||hg(d))&&(E||d.matchUpStatus&&!rf.includes(d.matchUpStatus))&&S?.length&&D.length){const e=S.map(Rd);m.push({info:"list of team players available for substitution",method:tS,availableParticipantIds:w,existingParticipantIds:e,availableParticipants:D,existingParticipants:S,type:oS,payload:{substituteParticipantId:void 0,existingParticipantId:void 0,sideNumber:c,matchUpId:u,drawId:p}})}return m}({specifiedPolicyDefinitions:i,inContextDrawMatchUps:v,matchUpParticipantIds:D,matchUpActionsPolicy:I,inContextMatchUp:T,policyActions:y,enforceGender:o,participantId:s,sideNumber:c,matchUpId:u,matchUp:m,drawId:l,side:P});N.push(...e)}return{structureIsComplete:E,validActions:N,isDoubleExit:j}}function gS({onlyAssignedPositions:e=!0,possiblyDisablingAction:t,tournamentParticipants:r,inactiveDrawPositions:n,activeDrawPositions:i,positionAssignments:a,returnParticipants:o,byeDrawPositions:s,drawDefinition:c,isByePosition:u,drawPosition:d,structureId:p,structure:l,drawId:m,event:f}){if(i.includes(d))return{};const h=n?.filter((e=>e!==d&&!(u&&s.includes(e)))),g=a?.filter((t=>(t=>!e||t.participantId||t.qualifier||t.bye)(t)&&h?.includes(t.drawPosition)))??[],I=g.map((({drawPosition:e})=>e)),{matchUps:U}=Kf({afterRecoveryTimes:!1,inContext:!0,drawDefinition:c,structure:l,event:f}),y=U.filter((({drawPositions:e})=>Xd(e,I))),S=Object.assign({},...y.map((e=>e.sides?.filter((({sourceDrawPositionRange:e})=>e)).map((({drawPosition:e,sourceDrawPositionRange:t})=>({[e]:t}))))).flat()),v=g.map((e=>e.participantId)).filter(Boolean),T=(r??[]).filter((e=>v.includes(e.participantId))),P=Object.assign({},...T.map((e=>({[e.participantId]:e})))),D=g.map((e=>{const t=P?.[e.participantId],r=S[e.drawPosition];return Mf({...e,participant:o?Jc(t,!1,!0):void 0,sourceDrawPositionRange:r})}));if(D.length){return{validSwapAction:{payload:{drawId:m,structureId:p,drawPositions:[d]},willDisableLinks:t,method:yy,type:Cy,availableAssignments:D}}}return{}}function IS(e){const{sides:t,matchUpType:r}=e||{},n=e.potentialParticipants?.length?e.potentialParticipants.flat().map((e=>r===hf?e?.individualParticipantIds||[]:e.participantId)).flat():[],i=(t||[]).map((e=>r===hf&&(e?.participant?.individualParticipantIds||[])||e?.participantId&&[e.participantId]||[])).flat();return{individualParticipantIds:i.concat(n).flat(),enteredIndividualParticipantIds:i,potentialIndividualParticipantIds:n}}function US(e){return e?.tournamentRecords??(e?.tournamentRecord&&{[e.tournamentRecord.tournamentId]:e.tournamentRecord})??{}}function yS(e){if(!e?.tournamentRecord)return{error:Fi};let{participantMap:t,participants:r}=e;const{scheduleVisibilityFilters:n,participantsProfile:i,afterRecoveryTimes:a,useParticipantMap:o,policyDefinitions:s,tournamentRecord:c,inContext:u=!0,contextProfile:d,matchUpFilters:p,contextFilters:l,nextMatchUps:m,context:f}=e,h=e.tournamentId??c.tournamentId,g=c?.events??[];r||({participants:r,participantMap:t}=Zt({participantsProfile:i,useParticipantMap:o,policyDefinitions:s,tournamentRecord:c,contextProfile:d,inContext:u}));const{appliedPolicies:I}=te({tournamentRecord:c}),U={...f,tournamentId:h,indoorOutDoor:c.indoorOutdoor,surfaceCategory:c.surfaceCategory,endDate:c.endDate},y=k({policyDefinitions:s,tournamentRecord:c,contextProfile:d});return{matchUps:g.flatMap((e=>(U.eventDrawsCount=e.drawDefinitions?.length??0,KU({context:U,scheduleVisibilityFilters:n,tournamentAppliedPolicies:I,participantsProfile:i,afterRecoveryTimes:a,policyDefinitions:s,tournamentRecord:c,contextContent:y,contextFilters:l,contextProfile:d,matchUpFilters:p,participantMap:t,nextMatchUps:m,participants:r,inContext:u,event:e}).matchUps??[]))).concat(...c.matchUps??[])}}function SS({scheduleVisibilityFilters:e,afterRecoveryTimes:t,participantsProfile:r,tournamentRecords:n,policyDefinitions:i,matchUpFilters:a,contextFilters:o,nextMatchUps:s,inContext:c}){if("object"!=typeof n||!Object.keys(n).length)return{error:Oi};return{matchUps:Object.keys(n).map((u=>{const d=n[u];return yS({scheduleVisibilityFilters:e,afterRecoveryTimes:t,participantsProfile:r,policyDefinitions:i,tournamentRecord:d,matchUpFilters:a,contextFilters:o,nextMatchUps:s,inContext:c}).matchUps??[]})).flat()}}function vS(e,t){return function(e,t){return(Qp[e?.stage]||0)-(Qp[t?.stage]||0)}(e,t)||(e?.stageSequence||0)-(t?.stageSequence||0)||e?.roundNumber&&t.roundNumber&&e?.roundNumber-t?.roundNumber||(e?.roundPosition??0)-(t?.roundPosition??0)}function TS(e){let t=US(e);const r=e.matchUps??[];let n=e.drawIds??[];const{includeParticipantDependencies:i,tournamentRecord:a,drawDefinition:o}=e;if(!Array.isArray(r))return{error:Va};if(!Array.isArray(n))return{error:ra};const s=e.matchUpIds?.length?e.matchUpIds:r.map((e=>e.matchUpId));if(!Array.isArray(s))return{error:xa};const c={},u={},d={},p={};a&&!Object.keys(t).length&&(t={[a.tournamentId]:a});const l=Object.values(t),m=l.reduce(((e,t)=>e.concat(t.events??[]).map((e=>(e.drawDefinitions||[]).map((e=>e.links||[])))).flat(1/0)),[]).filter((({linkType:e})=>e===cl));let f=r;if(m.length){f=SS({nextMatchUps:!0,tournamentRecords:t}).matchUps;const e=m.reduce(((e,t)=>{const r=t.source?.structureId,n=t.target?.structureId;return r&&n&&(d[n]=r),r&&!e.includes(r)&&e.push(r),e}),[]);for(const t of e)c[t]=[];for(const t of f??[]){const r=t.containerStructureId||t.structureId;e.includes(r)&&c[r].push(t.matchUpId)}}const h=e=>{u[e]||(u[e]={dependentMatchUpIds:[],participantIds:[],matchUpIds:[],sources:[]},p[e]=[])},g=(e,t)=>{u[e].matchUpIds.forEach((e=>{u[t].matchUpIds.push(e)})),u[t].matchUpIds.push(e),u[e].dependentMatchUpIds.push(t),i&&u[e].participantIds.forEach((e=>u[t].participantIds.push(e)))},I=e=>{const t=Object.keys(c).length;for(const r of e||[]){const{matchUpId:e,winnerMatchUpId:n,loserMatchUpId:a}=r;if(!s.length||s.includes(e)){if(h(e),i){const{individualParticipantIds:t}=IS(r);u[e].participantIds=t}n&&(h(n),g(e,n),p[n].push(e)),a&&(h(a),g(e,a),p[a].push(e)),u[e].sources.push(p[e]);const o=p[e].map((e=>u[e].sources[0])).flat(),s=p[e].map((e=>u[e].sources[1])).flat();if(u[e].sources.push(o,s),t){const t=r.containerStructureId||r.structureId,n=d[t];if(c[n])for(const t of c[n])h(t),g(t,e),p[t].push(e)}}}};if(o)Jg({drawDefinition:o}),f?.length||(f=zU({drawDefinition:o}).matchUps),I(f);else{if(f?.length||(f=SS({nextMatchUps:!0,tournamentRecords:t}).matchUps),!n.length){const e=l?.length?l.map((({events:e=[]})=>e.map((({drawDefinitions:e=[]})=>e.map((({drawId:e})=>e)))))).flat(1/0):[];e&&(n=e)}for(const e of n){const r=f?.filter((t=>t.drawId===e)).sort(vS),n=r?.find((({roundPosition:e})=>!e));if(!n){const n=r?.find((({tournamentId:e})=>e)),{drawDefinition:i}=ly({tournamentRecord:t[n?.tournamentId],drawId:e});i&&Jg({drawDefinition:i})}I(r)}}return{positionDependencies:c,matchUpDependencies:u,sourceMatchUpIds:p,matchUps:f,...Ni}}function PS(e){const{participantMap:t,participantId:r,matchUpStatus:n,roundPosition:i,structureId:a,matchUpType:o,roundNumber:s,matchUpId:c,potential:u,schedule:d,drawId:p,score:l}=e;if(!d||!Object.keys(d).length)return;n===xm||t[r].scheduleItems.push({...d,scheduledDate:Lc(d?.scheduledDate),scheduledTime:xc(d?.scheduledTime),checkScoreHasValue:hg({score:l}),matchUpStatus:n,roundPosition:i,structureId:a,matchUpType:o,roundNumber:s,matchUpId:c,potential:u,drawId:p})}function DS({publishedSeeding:e,usePublishState:t,withSeeding:r,participant:n,event:i}){const a={},o=e=>[mu,fu,i.eventType,e].join("."),s=Object.assign({},...(n.timeItems||[]).filter((({itemType:e})=>e.split(".")[1]===fu)).map((({itemType:e,itemValue:t})=>({[e]:t})))),c=(e?.stageSeedingScaleNames&&Object.values(e?.stageSeedingScaleNames)||Array.isArray(e?.seedingScaleNames)&&e.seedingScaleNames||[]).map(o),u=Jd(Object.keys(s),c);if(!(t&&(Object.keys(s).length||e?.drawIds?.length)&&!u.length)&&u.length){if(e?.stageSeedingScaleNames){const t=Object.keys(e.stageSeedingScaleNames).map((t=>{const r=o(e.stageSeedingScaleNames[t]);return[t,s[r]]})).filter((e=>e[1])).map((e=>({[e[0]]:{seedValue:e[1]}}))),r=Object.assign({},...t);a.seedAssignments=r}else if(u){const e=u.map((e=>s[e]));a.seedValue=e.pop()}}else if(t||"object"!=typeof r){const{categoryName:r,ageCategoryCode:o}=i.category||{},s=[o,i.eventId,r].filter(Boolean);let c;for(const e of s){const t=AU({scaleAttributes:{eventType:i.eventType,scaleType:fu,scaleName:e},participant:n});if(t.scaleItem){c=t.scaleItem;break}}if(c){if(!t||e?.published&&!e?.published?.drawIds?.length){const e=c.scaleValue;a.seedValue=e}}}else{const e=Object.keys(r).map((e=>{const t=o(r[e]);return[e,s[t]]})).filter((e=>e[1])).map((e=>({[e[0]]:{seedValue:e[1]}}))),t=Object.assign({},...e);a.seedAssignments=t}return a}function wS({convertExtensions:e,seedAssignments:t,participant:r,withSeeding:n,seedValue:i,eventId:a,ranking:o,entry:s}){const{entryStatus:c,entryStage:u,entryPosition:d,extensions:p}=s,l=p?.length&&e?Object.assign({},...Zc(p)):{},m=Object.assign(l,{entryPosition:d,entryStatus:c,entryStage:u,ranking:o,eventId:a});r.events[a]=Mf(m,!1,!1,!0),n&&(t&&(r.events[a].seedAssignments=t),i&&(r.events[a].seedValue=i))}function bS(e,t){return(e||"").localeCompare(t||"")}function RS({tournamentRecord:e,drawDefinition:t,eventIds:r,eventId:n,drawIds:i,drawId:a,event:o}){if(n&&!o)return{error:ya};if(Array.isArray(r)&&r?.length){const t={};for(const n of r){if(!tu(n))return{error:ys};const r=ly({tournamentRecord:e,eventId:n});if(!r)return{error:ya};const i=NS({event:r});if(i.error)return i;t[n]=i}return{...Ni,publishState:t}}if(!o){if(e){const t={},r=Xt({tournamentRecord:e});t.tournament=r;for(const r of e.events??[]){const e=NS({event:r});if(t[r.eventId]=e,e.error)return e;for(const{drawId:n}of r.drawDefinitions??[]){if(!tu(n))return{error:ys};const r=e.publishState?.publishedDrawIds?.includes(n);r&&(t[n]={status:{published:r}})}}return{...Ni,publishState:t}}return{error:Fi}}{const e=NS({event:o});if(e.error)return e;if(a)return t?{publishState:{status:{published:!!e.status.publishedDrawIds?.includes(a),drawDetail:e.status.drawDetails?.[a]},...Ni}}:{error:Bi};if(!Array.isArray(i)||!i?.length)return{publishState:e};{const t={};for(const r of i)return tu(r)?(t[r]={status:{published:!!e.status.publishedDrawIds.includes(r),drawDetail:e.status.drawDetails?.[r]}},{...Ni,publishState:t}):{error:ys}}}return{error:ys}}function NS({event:e}){const t=er({event:e});if(!t)return{status:{published:!1}};const r={published:void 0,seedingScaleNames:[],drawIds:[]};t.seeding&&Object.assign(r,t.seeding);const n=t.drawDetails??{};for(const t of e.drawDefinitions?.map(P)||[])n[t]||(n[t]={publishingDetail:{published:!1}});const i=n&&Object.keys(n).filter((e=>tr({drawDetails:n,drawId:e})))||t.drawIds||[];return{status:{published:i.length>0,publishedDrawIds:i,publishedSeeding:r,drawDetails:n}}}function MS({finishingPositionRange:e={},participantMap:t,finishingRound:r,participantWon:n,matchUpStatus:i,participantId:a,stageSequence:o,roundNumber:s,structureId:c,matchUpId:u,drawId:d,stage:p}){const l=t[a],m=e=>Math.abs(e[0]-e[1]);l.structureParticipation[c]||(l.structureParticipation[c]={rankingStage:p,walkoverWinCount:0,defaultWinCount:0,stageSequence:o,winCount:0,structureId:c,drawId:d});const f=l.structureParticipation[c],{winner:h,loser:g}=e,I=n?h:g;n&&(f.winCount+=1,i===Km&&(f.walkoverWinCount+=1),i===jm&&(f.defaultWinCount+=1)),I&&(!f.finishingPositionRange||m(I)<m(f.finishingPositionRange))&&(f.finishingPositionRange=I),r&&((!f.finishingRound||r<f.finishingRound)&&(f.finishingMatchUpId=u,f.finishingRound=r,f.roundNumber=s),1===r&&(f.participantWon=n))}function AS(e){const{withScheduleItems:t,scheduleAnalysis:r,withTeamMatchUps:n,participantMap:i,withOpponents:a,withMatchUps:o,withEvents:s,withDraws:c,finishingPositionRange:u,finishingRound:d,matchUpStatus:p,stageSequence:l,roundNumber:m,structureId:f,score:h,stage:g,withRankingProfile:I,tieWinningSide:U,roundPosition:y,matchUpTieId:S,matchUpSides:v,collectionId:T,matchUpType:P,winningSide:D,matchUpId:w,schedule:b,eventId:R,drawId:N,sides:M}=e,A=a&&2===M?.length&&Object.assign({},...M.map((({sideNumber:e},t)=>{const r=M[1-t].participantId;return e&&{[e]:r}})).filter(Boolean));for(const e of M){const{participantId:M,sideNumber:E,bye:C}=e;if(C)continue;const O=D===E,F=e=>{const t=i[e]?.participant,r=t?.participantType,n=[{participantId:e,participantType:r}];if(r!==hm)for(const e of t?.individualParticipantIds||[]){const t=i[e]?.participant;n.push({participantType:t?.participantType,participantId:e})}return n},k=(e,n)=>{if(o){if(i[e].matchUps[w]={participantWon:O,matchUpType:P,structureId:f,sideNumber:E,matchUpId:w,eventId:R,drawId:N,stage:g},a){const t=F(n);i[e].matchUps[w].opponentParticipantInfo=t}T&&(i[e].matchUps[w].collectionId=T)}a&&n&&(i[e].opponents[n]={participantId:n,matchUpId:w,eventId:R,drawId:N}),I&&MS({finishingPositionRange:u,participantMap:i,participantWon:O,finishingRound:d,matchUpStatus:p,participantId:e,stageSequence:l,roundNumber:m,structureId:f,matchUpId:w,drawId:N,stage:g}),(r||t)&&PS({participantMap:i,participantId:e,matchUpStatus:p,roundPosition:y,matchUpType:P,roundNumber:m,structureId:f,matchUpId:w,schedule:b,drawId:N,score:h})},_=({participant:e,partnerParticipantId:t})=>{const r=(e,t)=>{e&&(e.partnerParticipantIds||(e.partnerParticipantIds=[]),e.partnerParticipantIds.includes(t)||e.partnerParticipantIds.push(t))};c&&r(e?.draws?.[N],t),s&&r(e?.events?.[R],t),o&&r(e?.matchUps?.[w],t)};if(M&&i[M]){const e=A?.[E];k(M,e);const t=i[M]?.participant.participantType===Um,r=i[M]?.participant.individualParticipantIds||[];if(S){if(n){const e=e=>i[e].matchUps[S]={participantWon:U===E,matchUpId:S,matchUpType:If,sideNumber:E};e(M),r.forEach(e)}if(c&&!i[M].draws[N]){const e=v.find((e=>e.sideNumber===E))?.participant?.participantId,t=i[e]?.draws?.[N]?.entryStatus,n=e=>i[e].draws[N]={entryStatus:t,eventId:R,drawId:N};n(M),r.forEach(n)}}if(t&&(r.forEach((t=>i[t]&&k(t,e))),r.forEach(((e,t)=>{const n=r[1-t],a=i[e];a&&_({participant:a,partnerParticipantId:n})})),s&&v)){const e=v.find((e=>e.sideNumber===E))?.participant?.participantId;if(e){const t=i[e]?.events[R];t?(i[M].events[R]={...t},r.forEach((e=>i[e].events[R]={...t}))):console.log("Missing teamEntry",{eventId:R,teamParticipantId:e})}}if(D){const e=e=>{O?(i[e].counters[P].wins+=1,i[e].counters.wins+=1,p===Km&&(i[e].counters[P].walkoverWins+=1,i[e].counters.walkoverWins+=1),p===jm&&(i[e].counters[P].defaultWins+=1,i[e].counters.defaultWins+=1)):(i[e].counters[P].losses+=1,i[e].counters.losses+=1,p===Km&&(i[e].counters[P].walkovers+=1,i[e].counters.walkovers+=1),p===jm&&(i[e].counters[P].defaults+=1,i[e].counters.defaults+=1))};e(M),r.forEach(e)}}}}function ES({participantFilters:e={},tournamentRecord:t,participants:r=[]}){if(!Object.keys(e).length)return r;const{accessorValues:n,drawEntryStatuses:i,positionedParticipants:a,eventEntryStatuses:o,participantRoles:s,participantRoleResponsibilities:c,participantTypes:u,participantIds:d,signInStatus:p,enableOrFiltering:l,eventIds:m,genders:f}=e,h=CS(m)&&t?.events?.filter((e=>m?.includes(e.eventId)))||t?.events||[],g=i&&function({drawEntryStatuses:e,tournamentEvents:t}){const r=({entryStatus:t})=>!Array.isArray(e)||e.includes(t);return jd(t.reduce(((e,t)=>{const{flightProfile:n}=bU({event:t}),i=n?.flights?.map((({drawEntries:e})=>Array.isArray(e)?e.filter(r).map(Rd):[])).flat()||[],a=t.drawDefinitions?.map((({entries:e})=>e?e.filter(r).map(Rd):[]))||[];return e.concat(...i,...a)}),[]))}({drawEntryStatuses:i,tournamentEvents:h}),I=o&&function({eventEntryStatuses:e,tournamentEvents:t}){return jd(t.reduce(((t,r)=>{const n=(r.entries||[]).filter((({entryStatus:t})=>!Array.isArray(e)||e.includes(t))).map(Rd);return t.concat(...n)}),[]))}({eventEntryStatuses:o,tournamentEvents:h}),U=void 0!==a&&[!0,!1].includes(a)&&h.reduce(((e,t)=>e.concat(...(t.drawDefinitions||[]).map((e=>ap({drawDefinition:e}).allPositionedParticipantIds)).filter(Boolean))),[]),y=e=>n?.reduce(((t,r)=>{const{accessor:n,value:i}=r,{values:a}=Xc({element:e,accessor:n});return t&&a?.includes(i)}),!0);if(r=r?.filter((e=>{const t=ng({element:e,itemType:lm})?.timeItem?.itemValue,{participantRoleResponsibilities:r,participantType:i,participantRole:o,participantId:m,person:h}=e,S=Array.isArray(f)&&f?.length&&h?.sex&&f.includes(h.sex);return l?f&&S||a&&U.includes(m)||!1===a&&!U.includes(m)||g?.includes(m)||I?.includes(m)||d?.includes(m)||p&&t===p||u&&i&&CS(u)&&u.includes(i)||s&&o&&CS(s)&&s.includes(o)||c&&CS(r)&&CS(c)&&c.find((e=>r?.includes(e)))||n?.length&&CS(n)&&y(e):(!f||S)&&(void 0===a||a&&U.includes(m)||!1===a&&!U.includes(m))&&(!g||g.includes(m))&&(!I||I.includes(m))&&(!d||d.includes(m))&&(!p||t===p)&&(!u||i&&CS(u)&&u.includes(i))&&(!s||o&&CS(s)&&s.includes(o))&&(!c||CS(r)&&CS(c)&&c.find((e=>r?.includes(e))))&&(!n?.length||CS(n)&&y(e))})),h.length&&m){const e=h.filter((e=>m.includes(e.eventId))).map((e=>{const r=(e.entries||[]).map((e=>e.participantId));if(e.eventType===qf)return r;const n=(t?.participants??[]).filter((e=>r.includes(e.participantId))).map((e=>e.individualParticipantIds)).flat(1);return r.concat(...n)})).flat(1);r=r?.filter((t=>e.includes(t.participantId)))}return r}function CS(e){return e&&Array.isArray(e)&&e.length}function OS(e){const{withIndividualParticipants:t,participantFilters:r={},withPotentialMatchUps:n,withRankingProfile:i,convertExtensions:a,policyDefinitions:o,withScheduleItems:s,tournamentRecord:c,scheduleAnalysis:u,withSignInStatus:d,withTeamMatchUps:p,withScaleValues:l,usePublishState:m,contextProfile:f,withStatistics:h,withOpponents:g,withMatchUps:I,internalUse:U,withSeeding:y,withEvents:S,withDraws:v,withISO2:T,withIOC:P}=e;if(!c)return{error:Fi};(I||i)&&TS({tournamentRecord:c});let{participantMap:D}=BU({convertExtensions:a,tournamentRecord:c,withSignInStatus:d,withScaleValues:l,internalUse:U,withISO2:T,withIOC:P});const w=function(e){const{participantFilters:t,convertExtensions:r,policyDefinitions:n,tournamentRecord:i,usePublishState:a,contextProfile:o,participantMap:s,withPotentialMatchUps:c,withRankingProfile:u,withScheduleItems:d,scheduleAnalysis:p,withTeamMatchUps:l,withStatistics:m,withOpponents:f,withMatchUps:h,withSeeding:g,withEvents:I,withDraws:U}=e,y=t?.participantIds,S=e=>{const t=[e];return s[e]?.participant.individualParticipantIds?.forEach((e=>t.push(e))),t.some((e=>!y?.length||y.includes(e)))?t:[]},v={withMatchUps:h||u,withEvents:I||u,withDraws:U||u,withPotentialMatchUps:c,withRankingProfile:u,withScheduleItems:d,scheduleAnalysis:p,withTeamMatchUps:l,withStatistics:m,participantMap:s,withOpponents:f,withSeeding:g},T=[],P={},D=[],w={},b={},R={},N=({eventType:e,scaleNames:t,participantId:r})=>s[r].participant?.rankings?.[e]?.find((e=>t.includes(e.scaleName)))?.scaleValue;for(const e of i?.events||[]){if(t?.eventIds&&!t.eventIds.includes(e.eventId))continue;const{drawDefinitions:y=[],extensions:T=[],eventType:M,eventName:A,category:E,entries:C,eventId:O,gender:F}=e,{flightProfile:k}=bU({event:e}),_=k?.flights??[],x=RS({event:e}).publishState;x&&(w[O]=x);const L=x?.status?.publishedSeeding;if(I||g||u){const t=r?Object.assign({},...Zc(T)):{};b[O]={...t,eventName:A,eventType:M,category:E,eventId:O,gender:F};const n=[E?.categoryName,E?.ageCategoryCode].filter(Boolean);for(const t of C){const{participantId:i}=t;if(!i||!s[i])continue;const o=N({eventType:M,scaleNames:n,participantId:i});let c,u;if(g){const t=s[i].participant;({seedAssignments:c,seedValue:u}=DS({publishedSeeding:L,usePublishState:a,withSeeding:g,participant:t,event:e}))}const d=e=>{if(s[e]?.events?.[O])return;const n=s[e];wS({convertExtensions:r,seedAssignments:c,participant:n,withSeeding:g,seedValue:u,eventId:O,ranking:o,entry:t})};d(i),(s[i].participant.individualParticipantIds||[]).forEach(d)}}const V=w?.[O]?.publishedSeeding;if(U||u||g){const e=e=>e?Object.assign({},...e.map((({participantId:e,seedValue:t,seedNumber:r})=>({[e]:{seedValue:t,seedNumber:r}})))):void 0,t=jd([...y.map(Md),..._.map(Md)]);for(const r of t){const t=y.find((e=>e.drawId===r)),n=_?.find((e=>e.drawId===r)),i=t?.entries||n?.drawEntries,{structures:o=[],drawOrder:c,drawName:d,drawType:p}=t??{},l=n?.flightNumber,m=[E?.categoryName,E?.ageCategoryCode].filter(Boolean),f=(t?.structures||[]).sort(((e,t)=>fh(e,t))).map((({structureId:e,structures:t})=>[e,...(t||[]).map((({structureId:e})=>e))])).flat(1/0);let h,I,S,v,T=0;const P=o.filter((({stage:e,stageSequence:t})=>e===qp&&1===t||e===$p)).flatMap((e=>{const{seedAssignments:t,stageSequence:r,stage:n}=e,{positionAssignments:i}=op({structure:e});return n===qp?(T=i?.length??0,S=i,v=t):1===r&&(h=i,I=t),i})).map((({participantId:e})=>e)).filter(Boolean),D=e(v),w=e(I),b=t?i.filter((({participantId:e})=>P.includes(e))):i,A=!a||V?.published&&(0===V?.drawIds?.length||V?.drawIds?.includes(r));for(const e of b){const{entryStatus:t,entryStage:n,entryPosition:i,participantId:a}=e,o=N({participantId:a,scaleNames:m,eventType:M}),c=e=>{if(s[e].draws?.[r])return;const c=g&&A,d=c?{}:void 0,p=c?D?.[a]?.seedValue||D?.[a]?.seedNumber:void 0,l=p?D?.[a]:void 0,m=c?w?.[a]?.seedValue||w?.[a]?.seedNumber:void 0,f=m?w?.[a]:void 0;d&&p&&(d[qp]=l),d&&m&&(d[$p]=f);const h=p||m;h&&(s[e].participant.seedings[M]||(s[e].participant.seedings[M]=[]),l&&s[e].participant.seedings[M].push({...l,scaleName:r}),f&&s[e].participant.seedings[M].push({...f,scaleName:r}),d&&(s[e].events[O].seedAssignments||(s[e].events[O].seedAssignments={}),Object.keys(d).forEach((t=>s[e].events[O].seedAssignments[t]=d[t])))),(U||u)&&(s[e].draws[r]=Mf({seedAssignments:d,entryPosition:i,entryStatus:t,entryStage:n,seedValue:h,eventId:O,ranking:o,drawId:r},!1,!1,!0))};if(![rm,nm].includes(t)){c(a);const e=s[a].participant.individualParticipantIds||[];e?.forEach(c)}}const C=(t?.structures??[]).reduce(((e,t)=>(e.includes(t.stage)||e.push(t.stage),e)),[]),F=(t?.links??[]).length;R[r]={qualifyingPositionAssignments:h,qualifyingSeedAssignments:I,mainPositionAssignments:S,qualifyingSeedingMap:w,mainSeedAssignments:v,orderedStructureIds:f,mainSeedingMap:D,flightNumber:l,linksCount:F,drawOrder:c,drawName:d,drawType:p,drawSize:T,drawId:r,stages:C}}}if(u||p||l||m||f||h||U){const t=!!p||c,r=KU({afterRecoveryTimes:!!p,policyDefinitions:n,tournamentRecord:i,inContext:!0,contextProfile:o,participantMap:s,nextMatchUps:t,event:e})?.matchUps??[];for(const e of r){const{finishingPositionRange:r,potentialParticipants:n,tieMatchUps:a=[],sides:o=[],winningSide:c,matchUpType:u,matchUpId:l,eventId:m,drawId:f,collectionId:h,stageSequence:g,finishingRound:I,matchUpStatus:U,roundPosition:y,roundNumber:T,structureId:D,schedule:w,score:b,stage:R}=e;P[l]=e;const N={finishingPositionRange:r,finishingRound:I,stageSequence:g,roundPosition:y,collectionId:h,roundNumber:T,structureId:D,schedule:w,eventId:m,drawId:f,score:b,stage:R};AS({...N,...v,matchUpStatus:U,winningSide:c,matchUpType:u,matchUpId:l,sides:o});for(const e of a){const{winningSide:t,sides:r=[],matchUpId:n,matchUpStatus:i,matchUpType:a}=e;AS({...N,...v,winningSide:t,tieWinningSide:c,matchUpTieId:l,matchUpId:n,sides:r,matchUpSides:o,matchUpStatus:i,matchUpType:a})}if(Array.isArray(n)&&(t||p||d)){const e=n.flat().map(Rd).filter(Boolean);e?.forEach((e=>{const t=S(e);t?.forEach((e=>{s[e]&&(s[e].potentialMatchUps[l]=Mf({tournamentId:i?.tournamentId,matchUpId:l,eventId:m,drawId:f}))})),(p||d)&&PS({potential:!0,participantMap:s,participantId:e,matchUpStatus:U,roundPosition:y,structureId:D,matchUpType:u,roundNumber:T,matchUpId:l,schedule:w,drawId:f,score:b})}))}}D.push(...r)}}if(m||u||p){const e=Object.values(s);for(const t of e){const{wins:e,losses:r,[mf]:{wins:n,losses:i},[hf]:{wins:a,losses:o}}=t.counters,c=(e,r,n)=>{const i=r+n,a=r,o=i&&a/i;t.statistics[e]={denominator:i,numerator:a,statValue:o,statCode:e}};if(m&&(c(Wg,e,r),c(`${Wg}.${mf}`,n,i),c(`${Wg}.${hf}`,a,o)),u){const e=(e=[])=>Math.abs(e[0]-e[1]);for(const r of Object.keys(t.draws)){const{orderedStructureIds:n=[],flightNumber:i}=R[r]||{};if(t.structureParticipation&&n.length){let a,o=0;const s=n.map((r=>{const n=t.structureParticipation[r];if(!n)return;a||(a=n?.finishingPositionRange),e(a)>e(n?.finishingPositionRange)&&(a=n?.finishingPositionRange);const s=n.stage!==$p;s&&(o+=1);const c=s?o:void 0;return Mf({...n,participationOrder:c,flightNumber:i})})).filter(Boolean);t.draws[r]&&(t.draws[r].finishingPositionRange=a,t.draws[r].structureParticipation=s)}}}if(p){const e=ru(p)?p.scheduledMinutesDifference:0,r=t.scheduleItems||[],n=t.potentialMatchUps||{},i=r.reduce(((e,t)=>{const{scheduledDate:r,scheduledTime:n}=t;return e[r]||(e[r]=[]),n&&e[r].push(t),e}),{});Object.values(i).forEach((e=>e.sort(Gc)));for(const a of r){const{typeChangeTimeAfterRecovery:r,timeAfterRecovery:o,scheduledDate:s,scheduledTime:c}=a,u=i[s],d=kc(c);for(const i of u){if(i.matchUpId===a.matchUpId||[Km,jm].includes(i.matchUpStatus)&&!i.checkScoreHasValue)continue;const s=a.matchUpType!==i.matchUpType&&r||o,c=a.drawId===i.drawId,u=n[a.matchUpId]&&n[i.matchUpId],p=kc(i.scheduledTime),l=Math.abs(p-d),m=p>=d;if((e&&!isNaN(e)?l<=e:m&&kc(i.scheduledTime)<kc(s))&&(!u||!c)&&m){const e=[a.matchUpId,i.matchUpId].sort(bS).join("|");t.scheduleConflicts[e]={priorScheduledMatchUpId:a.matchUpId,matchUpIdWithConflict:i.matchUpId}}}}const a=t.participant.participantId;Object.keys(t.scheduleConflicts).length&&T.push(a),s[a].scheduleConflicts=t.scheduleConflicts}}}return{participantIdsWithConflicts:T,eventsPublishStatuses:w,derivedEventInfo:b,derivedDrawInfo:R,mappedMatchUps:P,participantMap:s,matchUps:D}}({withMatchUps:I??i,withEvents:S??i,withDraws:v??i,withPotentialMatchUps:n,participantFilters:r,withRankingProfile:i,convertExtensions:a,withScheduleItems:s,policyDefinitions:o,tournamentRecord:c,scheduleAnalysis:u,withTeamMatchUps:p,usePublishState:m,withStatistics:h,participantMap:D,withOpponents:g,contextProfile:f,withSeeding:y}),{participantIdsWithConflicts:b,eventsPublishStatuses:R,derivedEventInfo:N,derivedDrawInfo:M,mappedMatchUps:A}=w,E=w.matchUps;D=w.participantMap;const C=u??n,O=({potentialMatchUps:e,scheduleConflicts:t,scheduleItems:r,participant:n,statistics:a,opponents:o,matchUps:c,events:d,draws:p})=>{const l=Object.values(p),m=Object.values(o);return g&&l?.forEach((e=>{e.opponents=m.filter((t=>t.drawId===e.drawId))})),Mf({...n,scheduleConflicts:u?Object.values(t):void 0,draws:v||i?l:void 0,events:S||i?Object.values(d):void 0,matchUps:I||i?Object.values(c):void 0,opponents:g?m:void 0,potentialMatchUps:C?Object.values(e):void 0,statistics:h?Object.values(a):void 0,scheduleItems:s?r:void 0},!1,!1,!0)},F=new Map;for(const e of Object.keys(D))F.set(e,O(D[e]));const k=[...F.values()],_=o?.[td],x=_?.participant,L=ES({participants:k,participantFilters:r,tournamentRecord:c});if(t){const e=ru(t)?t:void 0;for(const t of L)for(const r of t.individualParticipantIds??[]){t.individualParticipants||(t.individualParticipants=[]);const n=F.get(r);t.individualParticipants.push(e?zu({template:e,source:n}):n)}}return{participantIdsWithConflicts:b,eventsPublishStatuses:R,derivedEventInfo:N,derivedDrawInfo:M,mappedMatchUps:A,participantMap:D,participants:x?L.map((e=>zu({source:e,template:x}))):L,...Ni,matchUps:E}}function FS(e){const{policyDefinitions:t,returnParticipants:r=!0,provisionalPositioning:n,tournamentRecord:i,drawDefinition:a,drawPosition:o,event:s}=e;if(!s)return{error:Ua};if(!a)return{error:Li};if(!e.structureId)return{error:la};const c=e.tournamentParticipants??(i&&OS({withIndividualParticipants:!0,tournamentRecord:i}).participants)??[];let u=w({structureId:e.structureId,drawDefinition:a});if(u.error)return u;const d=u.containingStructure||u.structure;if(!d)return{error:ma};const p=d.structureId;if(u=j({drawDefinition:a,structureId:p}),void 0===o&&!u.isAdHoc)return{error:Ji};if(u.isAdHoc)return hS(e);if(u.error)return u;const{drawPositionInitialRounds:l,inactiveDrawPositions:m,activeDrawPositions:f,byeDrawPositions:h}=u,g=te({tournamentRecord:i,drawDefinition:a,structure:d,event:s}).appliedPolicies??{};Object.assign(g,t??{});const{actionsPolicy:I,enabledStructures:U,actionsDisabled:y}=Hy({actionType:$y,appliedPolicies:g,drawDefinition:a,structure:d}),S=I?.activePositionOverrides||[],{sourceStructureIds:v}=Wt({finishingPosition:Ll,targetRoundNumber:1,linkType:cl,drawDefinition:a,structureId:p})||{};let T;v?.length&&(T=v.reduce(((e,t)=>zt({structureId:t,drawDefinition:a})&&e),!0));const P=v.length,D=v.length&&!T,{policyActions:b}=Yy({enabledStructures:U,drawDefinition:a,structure:d}),R=![$p,qp].includes(d.stage)||1!==d.stageSequence,{drawId:N}=a,M=[],{assignedPositions:A,positionAssignments:E}=K({structure:d}),C=A?.find((e=>e.drawPosition===o)),O=E?.map((e=>e.drawPosition));if(!O?.includes(o))return{error:Ki};const{stage:F,stageSequence:k}=d,_=[F];F===Wp&&_.push(qp),F===qp&&_.push(Wp);const x=lt({entryStatuses:cm,provisionalPositioning:n,drawDefinition:a,stageSequence:k,structureId:p,stages:_}),L=Ht({drawDefinition:a,stages:_}).assignedParticipantIds??[],V=x.filter((e=>!L.includes(e.participantId))).map((e=>e.participantId)),B=h.includes(o),G=f.includes(o);if(y)return{hasPositionAssigned:!!C,info:"Actions Disabled for structure",isActiveDrawPosition:G,isDrawPosition:!0,validActions:[],isByePosition:B};if(Qy({policyActions:b,action:Ny})&&!G&&E&&!D&&(!C||B)){const{validAssignmentActions:e}=function({positionSourceStructureIds:e,unassignedParticipantIds:t,possiblyDisablingAction:r,provisionalPositioning:n,tournamentParticipants:i,isWinRatioFedStructure:a,positionAssignments:o,returnParticipants:s,appliedPolicies:c,drawDefinition:u,seedingProfile:d,isByePosition:p,drawPosition:l,structureId:m,event:f}){const{drawId:h}=u,g=[];let I,U,y=[];const S=c?.[od]?.validSeedPositions?.ignore;if(!S){const e=Hh({provisionalPositioning:n,returnAllProxies:!0,randomize:!0,drawDefinition:u,seedingProfile:d,structureId:m,event:f});({unplacedSeedParticipantIds:I,unplacedSeedAssignments:U,unfilledPositions:y}=e)}if(y?.length||(y=o.filter((e=>!e.participantId&&!e.bye&&!e.qualifier)).map((e=>e.drawPosition))),p||g.push({payload:{drawId:h,structureId:m,drawPosition:l,isPositionAction:!0},willDisableLinks:r,method:Ty,type:_y}),a&&S){const t=o.map((e=>e.participantId)).filter(Boolean),n={structureIds:e},{completedMatchUps:a}=Cm({inContext:!0,matchUpFilters:n,drawDefinition:u}),c=jd((a??[]).filter((({matchUpType:e})=>f?.eventType!==zf||e===zf))?.map((({sides:e})=>e?.map(Rd))).flat().filter((e=>e&&!t.includes(e)))),d=s?i?.filter((e=>c?.includes(e.participantId))).map((e=>Jc(e,void 0,!0))):void 0;return d?.forEach((e=>{const t=(u.entries??[]).find((t=>t.participantId===e.participantId));e.entryPosition=t?.entryPosition})),d?.length&&g.push(Mf({payload:{drawId:h,structureId:m,drawPosition:l},willDisableLinks:r,method:vy,type:Ny,availableParticipantIds:c,participantsAvailable:d})),{validAssignmentActions:g}}if(y.includes(l)||p){let e;if(U?.length){const t=U.filter((e=>I?.includes(e.participantId)));t.sort(By),e=t.map((e=>e.participantId))}else e=t;const n=s?i?.filter((t=>e.includes(t.participantId))).map((e=>Jc(e,void 0,!0))):void 0;n?.length&&g.push(Mf({payload:{drawId:h,structureId:m,drawPosition:l},willDisableLinks:r,method:vy,type:Ny,availableParticipantIds:e,participantsAvailable:n}))}return{validAssignmentActions:g}}({positionSourceStructureIds:v,unassignedParticipantIds:V,possiblyDisablingAction:R,isWinRatioFedStructure:P,tournamentParticipants:c,positionAssignments:E,returnParticipants:r,appliedPolicies:g,drawDefinition:a,isByePosition:B,drawPosition:o,structureId:p,event:s});e?.forEach((e=>M.push(e)))}if(Qy({policyActions:b,action:wy})){const{validAssignmentActions:e}=function({drawPositionInitialRounds:e,tournamentParticipants:t,positionAssignments:r,returnParticipants:n,appliedPolicies:i,drawDefinition:a,drawPosition:o,structureId:s,drawId:c}){const u=[],d=[],p=[],l=[],m=r.map((e=>e.participantId)).filter(Boolean),f=i?.[Ju],h=!f?.disableRoundRestrictions&&e[o],g=f?.requireCompletedStructures,{sourceStructureIds:I,relevantLinks:U}=jy({targetRoundNumber:h,linkType:ul,drawDefinition:a,structureId:s})||{};I?.length&&l.push(...I);const{sourceStructureIds:y,relevantLinks:S}=jy({targetRoundNumber:h,linkType:cl,drawDefinition:a,structureId:s})||{};y?.length&&l.push(...y);for(const e of U){const r=a.structures?.find((t=>t.structureId===e.source.structureId));if(r?.stage!==$p)continue;const i=lh({structureId:e.source.structureId,drawDefinition:a});if(!g||i){const e=r.qualifyingRoundNumber,{matchUps:i}=Kf({matchUpFilters:{roundNumbers:[e],hasWinningSide:!0},afterRecoveryTimes:!1,tournamentParticipants:t,inContext:!0,structure:r});for(const e of i){const t=e.sides.find((t=>t?.sideNumber===e.winningSide)),r=e.matchUpStatus===xm&&e.sides?.find((({participantId:e})=>e));if(t||r){const{participantId:e,participant:i}=t||r||{};e&&!m.includes(e)&&(i&&n&&u.push(i),d.push(e))}}}}for(const e of S){const r=a.structures?.find((t=>t.structureId===e.source.structureId));if(r?.stage!==$p)continue;const i=lh({structureId:e.source.structureId,drawDefinition:a});if(!g||i){const{positionAssignments:e}=op({structure:r}),i=e?.map((e=>{const t=e.participantId,r=Wl({element:e,name:Di}).extension?.value;return r?{participantId:t,groupOrder:r?.groupOrder}:{}})).filter((({groupOrder:e,participantId:t})=>1===e&&!m.includes(t))).map((({participantId:e})=>e))??[];if(i&&d.push(...i),n){const e=t.filter((({participantId:e})=>i.includes(e)));u.push(...e)}}}return d.length&&p.push(Mf({payload:{qualifyingParticipantId:void 0,drawPosition:o,structureId:s,drawId:c},method:hy,type:wy,qualifyingParticipantIds:d,qualifyingParticipants:n?u:void 0})),{validAssignmentActions:p,sourceStructureIds:l}}({drawPositionInitialRounds:l,tournamentParticipants:c,positionAssignments:E,returnParticipants:r,appliedPolicies:g,drawDefinition:a,drawPosition:o,structureId:p,drawId:N});e?.forEach((e=>M.push(e)))}const{participantId:q}=C||{},$=q&&c.find((e=>e.participantId===q));if(C){Qy({policyActions:b,action:My})&&!G&&(M.push({type:My,method:Uy,payload:{drawId:N,structureId:p,drawPosition:o},willDisableLinks:R}),B||M.push({type:Ry,method:"withdrawParticipantAtDrawPosition",payload:{drawId:N,structureId:p,drawPosition:o},willDisableLinks:R}),Qy({policyActions:b,action:_y})&&!B&&M.push({type:_y,method:Uy,payload:{drawId:N,structureId:p,drawPosition:o,replaceWithBye:!0},willDisableLinks:R}));const e=d.stage===$p||d.stage===qp&&1===d.stageSequence;if(!B&&zy({activePositionOverrides:S,activeDrawPositions:f,action:Fy})&&Qy({policyActions:b,action:Fy})&&ge({drawDefinition:a,structureId:p,drawPosition:o})&&e){const{seedAssignments:e}=Y({returnAllProxies:!0,drawDefinition:a,structure:d}),{seedNumber:t,seedValue:r}=e?.find((e=>e.participantId===q))??{};M.push({type:Fy,method:"modifySeedAssignment",participant:$,seedNumber:t,payload:{drawId:N,structureId:p,participantId:q,seedValue:r}})}if(!B&&zy({activePositionOverrides:S,activeDrawPositions:f,action:Ey})&&Qy({policyActions:b,action:Ey})&&ge({drawDefinition:a,structureId:p,drawPosition:o})&&e){const{seedAssignments:e}=Y({returnAllProxies:!0,drawDefinition:a,structure:d}),{seedNumber:t}=e?.find((e=>e.participantId===q))??{};M.push({method:"removeSeededParticipant",type:Ey,participant:$,seedNumber:t,payload:{participantId:q,structureId:p,drawId:N}})}if(!B&&q){if(Qy({policyActions:b,action:ky})){const e={type:ky,method:Py,participant:$,payload:{penaltyCode:void 0,penaltyType:void 0,participantIds:[],notes:void 0,drawId:N}};M.push(e)}if(Qy({policyActions:b,action:Oy})){const e={type:Oy,method:"modifyParticipantOtherName",participant:$,payload:{participantId:q,otherName:void 0}};M.push(e)}}if(Qy({policyActions:b,action:Cy})){const{validSwapAction:e}=gS({possiblyDisablingAction:R,tournamentParticipants:c,inactiveDrawPositions:m,activeDrawPositions:f,positionAssignments:E,returnParticipants:r,byeDrawPositions:h,drawDefinition:a,isByePosition:B,drawPosition:o,structureId:p,structure:d,drawId:N});e&&M.push(e)}}if(Qy({policyActions:b,action:by})&&!D){const{validAlternatesAction:e}=function({tournamentParticipants:e=[],possiblyDisablingAction:t,activeDrawPositions:r,positionAssignments:n,returnParticipants:i,appliedPolicies:a,drawDefinition:o,drawPosition:s,validActions:c,structureId:u,structure:d,drawId:p,event:l}){if(r.includes(s))return{};const m=c.find((e=>e.type===Ny))?.availableParticipantIds,f=a?.[Ju]?.otherFlightEntries,h=a?.[Ju]?.restrictQualifyingAlternates,g=(o.entries??[]).filter((({entryStage:e})=>!h||(d.stage===$p?e===$p:e!==$p))).sort(((e,t)=>(e.entryPosition??1/0)-(t.entryPosition??1/0))).map((({participantId:e})=>e)).filter(Boolean),{allPositionedParticipantIds:I}=ap({drawDefinition:o}),U=n.map((e=>e.participantId)).filter(Boolean),y=g.filter((e=>d.stage&&[$p,qp,zp].includes(d.stage)?!I?.includes(e):!U.includes(e))),S=(l?.entries??[]).filter((e=>e.entryStatus===zl&&Vy({restrictQualifyingAlternates:h,structure:d,entry:e})&&(d.stage&&[$p,qp,zp].includes(d.stage)?!I?.includes(e.participantId):!U.includes(e.participantId)))).sort(((e,t)=>(e.entryPosition??1/0)-(t.entryPosition??1/0))).map((e=>e.participantId));let v=jd(y.concat(S));if(f){const e=l?bU({event:l}).flightProfile:void 0,t=e?.flights?.filter((e=>e.drawId!==p)).map((e=>e.drawEntries.filter((e=>e.participantId&&![am,rm,nm].includes(e.entryStatus)&&!g.includes(e.participantId))).map((({participantId:e})=>e)))).flat().filter(Boolean);t?.length&&v.push(...t)}m?.length&&(v=v.filter((e=>!m.includes(e))));const T=i?e?.filter((e=>v.includes(e.participantId))):void 0;if(T?.forEach((e=>{const t=(o.entries??[]).find((t=>t.participantId===e.participantId));e.entryPosition=t?.entryPosition})),T?.sort(((e,t)=>(e.entryPosition||1/0)-(t.entryPosition||1/0))),v.length)return{validAlternatesAction:Mf({payload:{drawId:p,structureId:u,drawPosition:s},willDisableLinks:t,method:gy,availableAlternatesParticipantIds:v,type:by,availableAlternates:T})};return{}}({possiblyDisablingAction:R,tournamentParticipants:c,positionAssignments:E,activeDrawPositions:f,returnParticipants:r,appliedPolicies:g,drawDefinition:a,drawPosition:o,validActions:M,structureId:p,structure:d,drawId:N,event:s});e&&M.push(e)}if(Qy({policyActions:b,action:Ay})&&!D&&E){const{validLuckyLosersAction:e}=function({tournamentParticipants:e=[],sourceStructuresComplete:t,possiblyDisablingAction:r,isWinRatioFedStructure:n,activeDrawPositions:i,positionAssignments:a,drawDefinition:o,drawPosition:s,structureId:c,structure:u,drawId:d,event:p}){if(i.includes(s)||n&&!t)return{};const{sourceStructureIds:l,targetStructureIds:m}=o.links?.reduce(((e,t)=>{const r=t.source?.structureId,n=t.target?.structureId;return e.sourceStructureIds.includes(r)||e.sourceStructureIds.push(r),e.targetStructureIds.includes(n)||e.targetStructureIds.push(n),e}),{sourceStructureIds:[],targetStructureIds:[]})||{},f=[],h=o.links?.filter((e=>e.target?.structureId===u.structureId))??[];for(const e of h){const t=e?.source?.structureId,{structure:r}=Om({structureId:t,drawDefinition:o}),n={};if(r?.finishingPosition===Vl&&(1!==l?.length||1!==m?.length)){const{matchUps:e}=Kf({drawDefinition:o,structure:u,event:p}),{initialRoundNumber:t}=Ly({drawPosition:s,matchUps:e}),r=o.links?.find((e=>e.target?.structureId===u?.structureId&&e.target.roundNumber===t)),i=r?.source?.roundNumber;n.roundNumbers=[i]}const{completedMatchUps:i}=ph({structureId:t,inContext:!0,matchUpFilters:n,drawDefinition:o}),c=a.map((e=>e.participantId)).filter(Boolean),d=i?.filter((({matchUpType:e,winningSide:t})=>t&&(p?.eventType!==zf||e===zf))).map((({winningSide:e,sides:t})=>e&&t?.[1-(e-1)])).map(Rd).filter((e=>e&&!c.includes(e)));d?.forEach((e=>{f.includes(e)||f.push(e)}))}const g=e?.filter((e=>f?.includes(e.participantId)));if(g?.forEach((e=>{const t=(o.entries??[]).find((t=>t.participantId===e.participantId));e.entryPosition=t?.entryPosition})),f?.length)return{validLuckyLosersAction:{type:Ay,method:Iy,availableLuckyLosers:g,availableLuckyLoserParticipantIds:f,willDisableLinks:r,payload:{drawId:d,structureId:c,drawPosition:s}}};return{}}({sourceStructuresComplete:T,possiblyDisablingAction:R,isWinRatioFedStructure:P,tournamentParticipants:c,activeDrawPositions:f,positionAssignments:E,drawDefinition:a,drawPosition:o,structureId:p,structure:d,drawId:N});e&&M.push(e)}if($?.participantType===Um&&Qy({policyActions:b,action:Dy})){const{validModifyAssignedPairAction:e}=function({tournamentParticipants:e,returnParticipants:t,drawPosition:r,participant:n,drawId:i,event:a}){const o=a?.entries?.filter((({entryStatus:e})=>[rm,nm].includes(e))).map((({participantId:e})=>e))||[];if(o.length){const a=n.individualParticipantIds,s=t?e.filter((({participantId:e})=>o.includes(e))):void 0,c=t?e.filter((({participantId:e})=>a.includes(e))):void 0;return{validModifyAssignedPairAction:Mf({payload:{participantId:n.participantId,replacementIndividualParticipantId:void 0,existingIndividualParticipantId:void 0,drawPosition:r,drawId:i},method:Sy,availableIndividualParticipantIds:o,availableIndividualParticipants:s,existingIndividualParticipantIds:a,existingIndividualParticipants:c,type:Dy},!1,!1,!0)}}return{}}({tournamentParticipants:c,returnParticipants:r,drawPosition:o,participant:$,drawId:N,event:s});e&&M.push(e)}return{hasPositionAssigned:!!C,isActiveDrawPosition:G,isDrawPosition:!0,isByePosition:B,validActions:M}}function kS({policyDefinitions:e,appliedPolicies:t,drawType:r}){const n=e?.[cd]?.drawTypeCoercion,i=t?.[cd]?.drawTypeCoercion;return("boolean"==typeof n?n:void 0)??(r&&n?.[r])??("boolean"==typeof i?i:void 0)??(r&&i?.[r])??!0}function _S({tournamentRecord:e,drawDefinition:t,stage:r=qp,structureId:n,structure:i}){if(!e)return{error:Fi};if(!i&&!t)return{error:Li};if(i||n||1!==t?.structures?.filter((e=>e.stage===r)).length||(i=t.structures.find((e=>e.stage===r))),!i&&!n)return{error:la};const{error:a,positionAssignments:o}=op({drawDefinition:t,structureId:n,structure:i});return{positionAssignments:o??[],structureId:i?.structureId,error:a}}function xS({structureId:e,drawDefinition:t}){if(!t)return{error:Li};if(!tu(e))return{error:ys};const r=FI({drawDefinition:t,structureId:e});if(r.error)return r;const n=r.links.target.flatMap((e=>e.target.feedProfile)).filter(Boolean),i=!Jd([sl,ol,al,tl],n).length;return{...Ni,valid:i}}function LS({drawDefinition:e,participantId:t}){if("object"!=typeof e)return{error:Li};if("string"!=typeof t)return{error:Do};const{extension:r}=Wl({element:e,name:mi});return{lineUp:(r?.value||{})[t]}}function VS(e){return[nm,rm].includes(e)}function BS({consideredEntries:e,policyDefinitions:t,tournamentRecord:r,appliedPolicies:n,participantMap:i,enforceGender:a,participants:o,event:s}){if(o&&i||!r||({participants:o,participantMap:i}=OS({tournamentRecord:r})),!o)return{error:Po};if(!Array.isArray(o))return{error:ys};if(!s)return{error:Ua};const c=t?.[Zu]??n?.[Zu]??qy[Zu],u=!1!==(a??c?.participants?.enforceGender),{eventType:d,gender:p}=s,l=d===Hf,m=d===Yf&&ym||l&&Um||gm,f=Object.assign({},...(e??s.entries??[]).map((e=>({[e.participantId]:e.entryStatus})))),h=Object.keys(f),g=o.filter((e=>h.includes(e.participantId))).filter((e=>{const t=function({participant:e,participantType:t,eventType:r,entryStatusMap:n}){const i=n[e.participantId],a=r&&[Hf,Yf].includes(r)&&e.participantType===gm&&(VS(i)||i===am);return e.participantType!==t&&!a}({participant:e,participantType:m,eventType:d,entryStatusMap:f}),r=function(e){const{participant:t,participantMap:r,eventGender:n,mismatch:i,isDoubles:a,genderEnforced:o}=e,s=!i&&a&&jd(t?.individualParticipantIds?.map((e=>r?.[e]?.participant?.person?.sex)).filter(Boolean)??[])||[],c=!n||!s?.length||xf===n||[Lf,jf].includes(n)&&s[0]===n||Vf===n&&(1==s.length&&1===t.individualParticipantIds?.length||2===s.length),u=t?.person?.sex,d=!t?.person||!n||[xf,Vf].includes(n)||[Lf,jf].includes(n)&&u===n;return!o||c&&d}({genderEnforced:u,participantMap:i,eventGender:p,participant:e,isDoubles:l,mismatch:t});return t||!r}));if(g.length){const e=g.map((e=>e.participantId));return{error:Ta,invalidParticipantIds:e}}return{...Ni,valid:!0}}function jS({drawDefinition:e,structure:t}){if(!t)return!1;const r=t.matchUps||t.roundMatchUps&&Object.values(t.roundMatchUps).flat(),n=r?.find((e=>e?.roundPosition)),i=r?.find((e=>e?.drawPositions?.length));return!(t?.structures||t?.stage===Hp||e?.drawType&&e.drawType!==ll||n||i)}var GS=Object.freeze({__proto__:null,allPlayoffPositionsFilled:mh,checkValidEntries:BS,findDrawDefinition:fy,getAssignedParticipantIds:oy,getAvailablePlayoffProfiles:ny,getDrawDefinitionTimeItem:ig,getDrawParticipantRepresentativeIds:ZU,getDrawTypeCoercion:kS,getEligibleVoluntaryConsolationParticipants:JU,getParticipantIdFinishingPositions:ay,getPositionAssignments:_S,getPositionsPlayedOff:XU,getSeedingThresholds:Gh,getSeedsCount:NU,getStructureSeedAssignments:oh,getTeamLineUp:LS,getValidGroupSizes:Dg,isAdHoc:jS,isCompletedStructure:lh,isValidForQualifying:xS,positionActions:FS});function qS({drawSize:e,qualifyingRoundNumber:t}){let r=e,n=0;for(;n<t;)r=Math.floor(r/2),n+=1;return r}function $S({structureName:e,matchUpType:t,idPrefix:r,drawSize:n,isMock:i,uuids:a}){const o=[],{matchUps:s}=kg({linkFedFinishingRoundNumbers:[1],drawSize:n+1,matchUpType:t,idPrefix:r,isMock:i}),c=Rm({structureName:e||wm(qp),structureId:a?.pop(),stageSequence:1,stage:qp,matchUpType:t,matchUps:s});o.push(c);const u=n/2,{matchUps:d}=kg({finishingPositionOffset:u,idPrefix:r&&`${r}-c`,drawSize:n-1,isConsolation:!0,matchUpType:t,isMock:i,uuids:a}),p=Rm({structureName:wm(kl),matchUps:d,structureId:a?.pop(),stage:Wp,stageSequence:2,matchUpType:t});o.push(p);const{matchUps:l}=Ng({idPrefix:r&&`${r}-p1t2`,drawSize:2,matchUpType:t,isMock:i}),m=Rm({structureName:wm(Fl),matchUps:l,structureId:a?.pop(),stageSequence:3,stage:zp,matchUpType:t});o.push(m);const f=function({mainStructure:e,consolationStructure:t,deciderStructure:r}){const n=t.matchUps.reduce(((e,t)=>(t.drawPositions||[]).filter(Boolean).length&&!e.includes(t.roundNumber)?e.concat(t.roundNumber):e),[]),i=e.matchUps.reduce(((e,t)=>!e||t.roundNumber>e?t.roundNumber:e),void 0),a=t.matchUps.reduce(((e,t)=>!e||t.roundNumber>e?t.roundNumber:e),void 0);return[...n.map(((r,i)=>{const a=n.indexOf(r)%2?ol:sl;return{linkType:dl,source:{roundNumber:1+i,structureId:e.structureId},target:{feedProfile:a,roundNumber:r,structureId:t.structureId}}})),{linkType:ul,source:{roundNumber:a,structureId:t.structureId},target:{feedProfile:ol,roundNumber:i,structureId:e.structureId}},{linkType:ul,source:{roundNumber:i,structureId:e.structureId},target:{feedProfile:ol,roundNumber:1,structureId:r.structureId}},{linkType:dl,source:{roundNumber:i,structureId:e.structureId},target:{feedProfile:ol,roundNumber:1,structureId:r.structureId}}]}({mainStructure:c,consolationStructure:p,deciderStructure:m});return{structures:o,links:f,...Ni}}function WS(e){const{qualifyingRoundNumber:t,finishingPositionOffset:r,qualifyingPositions:n,matchUpType:i,idPrefix:a,drawSize:o,isMock:s,uuids:c}=e;if(!Vd(o)||o<2)return{matchUps:[],roundsCount:0};if(Cd(o))return Ng(e);const u=function(e){const t=Ed(e);let r=t%2?t+1:t;const n=!!(Math.ceil(r/2)%2),i=[{participantsCount:r,preFeedRound:n}];for(;r>2;){const e=Math.ceil(r/2),t=1===e,n=!(t||!(e%2));r=!t&&n?e+1:e;const a=!!(2!==r&&Math.ceil(r/2)%2);i.push({participantsCount:r,preFeedRound:a,feedRound:n})}return i}(o),d=u.shift(),p=Qd(1,(d?.participantsCount||0)+1).map((e=>({drawPosition:e})));let l=[],m=1;({matchUps:l}=Rg({roundNumber:m,matchUpType:i,idPrefix:a,matchUps:l,isMock:s,nodes:p,uuids:c})),m++;let f=e.roundLimit||t;for(const e of u){const t=e.participantsCount/2,r=Qd(1,t+1);n&&t===n&&(f=m-1);const i=r.map((e=>{const t=bg({roundPosition:e,roundNumber:m,idPrefix:a,uuids:c});return{roundPosition:e,roundNumber:m,matchUpId:t}}));l.push(...i),m++}const h=m-1;return l=wg({finishingPositionOffset:r,lucky:!0,roundsCount:h,roundLimit:f,matchUps:l}),f&&(l=l.filter((e=>e.roundNumber<=f))),{matchUps:l,roundsCount:h,roundLimit:f}}function HS(e){const{playoffAttributes:t,stageSequence:r=1,stage:n=qp,matchUpType:i,drawSize:a,uuids:o}=e,s=e.structureId||(()=>{if(!e.isMock&&!e.idPrefix)return;return`${e.drawDefinition.drawId}-s-0`})()||o?.pop(),{appliedPolicies:c}=Oh(e),u=e.policyDefinitions?.[sd]||c?.[sd];e.skipRounds=e.skipRounds||a<=4&&(u?.feedMainFinal?0:1)||0;const d=e.structureName??t?.[0]?.name??wm(qp),p={[ll]:()=>({structures:[Rm({finishingPosition:Ll,stageSequence:r,structureName:d,matchUps:[],matchUpType:i,structureId:s,stage:n})],links:[],...Ni}),[Sl]:()=>{const{matchUps:t}=WS(e);return{structures:[Rm({stageSequence:r,structureName:d,matchUpType:i,structureId:s,matchUps:t,stage:n})],links:[],...Ni}},[gl]:()=>(()=>{const{matchUps:t}=Ng(e);return{structures:[Rm({stageSequence:r,structureName:d,matchUpType:i,structureId:s,matchUps:t,stage:n})],links:[],...Ni}})(),[Il]:()=>$S(e),[fl]:()=>Qg({...e,roundOffsetLimit:3,playoffAttributes:t??_l}),[hl]:()=>Qg({...e,roundOffsetLimit:2,playoffAttributes:t??xl}),[zp]:()=>Qg(e),[ml]:()=>{const{matchUps:e}=kg({drawSize:a,uuids:o,matchUpType:i});return{structures:[Rm({stageSequence:r,structureName:d,matchUpType:i,structureId:s,stage:qp,matchUps:e})],links:[],...Ni}},[yl]:()=>_g(e),[Ul]:()=>Vg({...e,feedRounds:1,fmlc:!0}),[Ml]:()=>Vg({...e,feedRounds:1}),[Pl]:()=>Vg({...e,feedsFromFinal:1}),[wl]:()=>Vg({...e,feedsFromFinal:2}),[Rl]:()=>Vg({...e,feedsFromFinal:3}),[El]:()=>Vg(e),[vl]:()=>Lg(e),[Cl]:()=>Pg(e),[Ol]:()=>function(e){const{drawDefinition:t,structureOptions:r,requireSequential:n}=e,i={structureName:wm(qp),...e,stage:qp},{structures:a,groupCount:o,groupSize:s}=Pg(i);if(o<1)return{error:fs};const c=r?.playoffGroups||[{finishingPositions:[1],structureName:wm(zp)}],[u]=a,{structures:d,links:p}=Hg({sourceStructureId:u.structureId,requireSequential:n,drawDefinition:t,playoffGroups:c,groupCount:o,groupSize:s,...e});return d&&a.push(...d),{...Ni,structures:a,links:p}}(e)};return{generators:p}}function zS(e){const{enforceMinimumDrawSize:t=!0,overwriteExisting:r,appliedPolicies:n,staggeredEntry:i,drawDefinition:s,tieFormat:c,isMock:u,uuids:d}=e||{},p=Ed(e.drawSize),l=e.drawTypeCoercion??kS({appliedPolicies:n,drawType:e.drawType}),m=function(e){const{drawTypeCoercion:t,enforceMinimumDrawSize:r}=e,n=ve(e.drawSize);let i=t&&("boolean"==typeof t||t<=2)&&2===n&&gl||e.drawType||gl;const o=Bl.includes(i);if(n&&o)if(t&&("boolean"==typeof t&&n<4||n<=t))i=gl;else if(n<4&&r)return{...a({context:{enforceMinimumDrawSize:r,drawSize:n,drawType:i},result:{error:Xi},stack:"getCoercedDrawType"}),drawType:i};return{drawType:i}}({drawType:e.drawType,enforceMinimumDrawSize:t,drawTypeCoercion:l,drawSize:p});if(m.error)return m;const f=m.drawType,h=[],g=[],I=e?.matchUpType??mf,U=s?.structures?.filter((({stage:e})=>e===$p));U&&h.push(...U);const y=U?.map((({structureId:e})=>e)),S=s?.structures?.find((({stage:e,stageSequence:t})=>e===qp&&1===t)),v=s?.links?.filter((e=>e.target.structureId===S?.structureId&&y?.includes(e.source.structureId))),T=(e,t)=>{if(e.linkType===cl&&t?.structures){const r=e.source.finishingPositions||[];return t.structures.length*r.length}if(e.linkType===ul&&t?.matchUps?.length){const r=e.source.roundNumber;return t.matchUps.filter((({roundNumber:e})=>e===r)).length}},P=U?.map((e=>{const t=v?.find((t=>t.target.structureId===e.structureId)),r=op({structure:e})?.positionAssignments?.length??0;if(!t)return r;const n=t?.source.structureId,i=s.structures?.find((e=>e.structureId===n));return r-(T(t,i)||0)})).filter(Boolean).reduce(((e,t)=>e+t),0),D=v?.map((e=>{const t=e.source.structureId,r=U?.find((e=>e.structureId===t));return T(e,r)})).filter(Boolean).reduce(((e,t)=>e+t),0),w=!(!S||S?.matchUps?.length);if(U?.length&&!w)return{error:Es};const b=!U?.length&&e.qualifyingProfiles,R=b?.length&&function({qualifyingProfiles:e,appliedPolicies:t,idPrefix:r,isMock:n,uuids:i}){const s=[],c=[],u=[],d=(e,t)=>e.stageSequence-t.stageSequence,p=(e,t)=>e.roundTarget-t.roundTarget;let l,m=0,f=0,h=1;for(const g of e.sort(p)){const p=g.structureProfiles||[];h=g.roundTarget||h;let I,U,y,S=1,v=0;for(const s of(p||[]).sort(d)){let d=Ve(s.drawSize||s.participantsCount);const{qualifyingRoundNumber:f,structureOptions:g,matchUpFormat:T,structureName:P,structureId:D,drawType:w}=s,b=s.matchUpType,R=s.qualifyingPositions||qS({drawSize:d,qualifyingRoundNumber:f});let N,M,A;if(!Fe(d))return a({result:{error:ta},stack:"generateQualifyingSTructures"});const E=e.length>1?`${h}-`:"",C=p.length>1||E?S:"",O=P||(E||C?`${St($p)} ${E}${C}`:St($p));if(w===Cl){const{structures:e,groupCount:a,maxRoundNumber:o}=Pg({structureName:s.structureName||O,structureId:D||i?.pop(),stage:$p,structureOptions:g,appliedPolicies:t,stageSequence:S,matchUpType:b,roundTarget:h,drawSize:d,idPrefix:r,isMock:n,uuids:i});v=a,N=o,M=e[0],l=[1]}else({drawSize:d,matchUps:A,roundLimit:N}=Ng({qualifyingRoundNumber:f,qualifyingPositions:R,matchUpType:b,drawSize:d,idPrefix:r,isMock:n,uuids:i})),M=Ut({structureName:s.structureName||O,structureId:D||i?.pop(),qualifyingRoundNumber:N,stage:$p,matchUpFormat:T,stageSequence:S,matchUpType:b,roundLimit:N,matchUps:A}),h&&o({extension:{name:yi,value:h},element:M}),v=A?.filter((e=>e.roundNumber===N))?.length||0;if(S>1){const{link:e}=nr({sourceStructureId:U,sourceRoundNumber:I,targetStructureId:M.structureId,finishingPositions:y===cl?[1]:void 0,linkType:y});u.push(e),m+=(d||0)-v}else m+=d||0;y=w===Cl?cl:ul,U=M.structureId,I=N,c.push(M),S+=1}f+=v,s.push({qualifiersCount:v,finalQualifyingRoundNumber:I,finalQualifyingStructureId:U,finishingPositions:l,roundTarget:h,linkType:y}),h+=1}return{qualifiersCount:f,qualifyingDrawPositionsCount:m,qualifyingDetails:s,structures:c,...Ni,links:u}}({idPrefix:e.idPrefix,qualifyingProfiles:b,appliedPolicies:n,isMock:u,uuids:d});if(R?.error)return R;const{qualifyingDrawPositionsCount:N,qualifyingDetails:M,qualifiersCount:A}=R||{qualifyingDrawPositionsCount:P,qualifiersCount:D};N&&(R?.structures&&h.push(...R.structures),R?.links&&g.push(...R.links)),Object.assign(e,Mf({drawSize:p,matchUpType:I,tieFormat:c}));const E=f!==ll&&(!p||p<2||!i&&![ml,Sl].includes(f)&&([Ol,Cl].includes(f)&&p<3||![Cl,Ol].includes(f)&&!Cd(p)));if(E&&!N)return pd({context:{drawSize:p,invalidDrawSize:E},result:{error:Xi},stack:"generateDrawStructuresAndLinks"});const{generators:C,error:O}=HS(e);if(O)return{error:O};const F=C[f];if(!F)return{error:zi};const k=F?.();if(k.error)return k;const{structures:_,links:x}=k;if(_?.length){const e=_.find((({stage:e,stageSequence:t})=>e===qp&&1===t));if(S&&e)if(w){const t=e.structureId;if(e.structureId=S.structureId,x?.length)for(const e of x)e.source.structureId===t&&(e.source.structureId=S.structureId),e.target.structureId===t&&(e.target.structureId=S.structureId)}else if(!r)return{error:Es};h.push(..._)}h.sort(fh),x?.length&&g.push(...x);const L=k.structures.find((({stage:e,stageSequence:t})=>e===qp&&1===t));for(const e of M||[]){const{finalQualifyingRoundNumber:t,finalQualifyingStructureId:r,roundTarget:n,finishingPositions:i,linkType:a}=e,o=L&&Tg({targetStructureId:L.structureId,sourceStructureId:r,sourceRoundNumber:t,finishingPositions:i,targetEntryRound:n,linkType:a})?.link;if(o?.error)return o;o&&g.push(o)}return v&&g.push(...v),{...Ni,qualifyingResult:{qualifyingDrawPositionsCount:N,qualifiersCount:A},structures:h,links:g}}function YS(e){const{modifyOriginal:t=!0,stageSequence:r=1,isMock:n}=e||{},i="generateDrawTypeAndModifyDrawDefinition";if(!e.drawDefinition)return a({result:{error:Li},stack:i});const o=t?e.drawDefinition:L(e.drawDefinition,!1,!0);let{tieFormat:s,matchUpType:c}=e;if(s){const e=ar({tieFormat:s});if(e.error)return e}s=ir(s??we({drawDefinition:o})?.tieFormat),c=c??(o.matchUpType||mf),e.tieFormat=s,e.matchUpType=c;const u=rr({drawDefinition:o,stage:qp});e.drawSize=e.drawSize??u,!u&&e.drawSize&&yg({drawSize:e.drawSize,drawDefinition:o,stageSequence:r,stage:qp});const d=se({drawDefinition:o}).drawMatchUps.map(T),p=zS(e);if(p.error)return a({result:p,stack:i});const{structures:l,links:m,qualifyingResult:f}=p;o.structures=l,o.links=m;const h=Math.max(e.qualifiersCount??0,f?.qualifiersCount||0);if(f?.qualifyingDrawPositionsCount){if(!rr({stage:$p,drawDefinition:o})){const e=yg({drawSize:f.qualifyingDrawPositionsCount,stage:$p,drawDefinition:o});if(e.error)return e}}if(h){const e=function({qualifiersCount:e=0,drawDefinition:t,stage:r}){return t?nh({drawDefinition:t,stage:r})?r!==qp?{error:ea,info:"qualifiersCount can only be set for main stage"}:(th({attributes:[{[r]:{qualifiersCount:e}}],drawDefinition:t}),jp({drawDefinition:t}),{...Ni}):{error:wa}:{error:Li}}({qualifiersCount:h,drawDefinition:o,stage:qp});if(e.error)return e}const g=e.drawSize??u;Object.assign(e,S({drawSize:g,matchUpType:c,tieFormat:s}));const{matchUps:I,matchUpsMap:U}=ue({drawDefinition:o});s&&I?.forEach((e=>{if(!d.includes(e.matchUpId)){const{tieMatchUps:t}=Yg({tieFormat:s,matchUp:e,isMock:n});Object.assign(e,{tieMatchUps:t,matchUpType:c})}}));const{inContextDrawMatchUps:y}=bt({drawDefinition:o,matchUpsMap:U});return $({tournamentId:e.tournamentRecord?.tournamentId,drawDefinition:o}),{inContextDrawMatchUps:y,drawDefinition:o,matchUpsMap:U,...Ni,structures:l,matchUps:I,links:m}}function QS(e){if(e)return Jc(e,!1,!0)}const KS="MIXED events can not contain mixed singles or { gender: ANY } collections",JS="events with { gender: ANY } can not contain MIXED singles collections";function ZS(e){const t="tieFormatGenderValidityCheck",{referenceGender:r,matchUpType:n,gender:i}=e;return r&&i&&[Lf,jf].includes(r)&&r!==i?a({result:{valid:!1,error:Is},context:{gender:i},stack:t}):r===Vf&&(i===xf||i===Vf&&n!==hf)?a({result:{error:Is,valid:!1},info:KS,stack:t}):r===xf&&i===Vf&&n!==hf?a({result:{error:Is,valid:!1},info:JS,stack:t}):{valid:!0}}const XS=(e,t)=>e.filter(Boolean).every((e=>typeof e===t)),ev=e=>e.filter(Boolean).every(kd);function tv(e){const t=e.category;if("object"!=typeof t)return{error:Us};let{ageCategoryCode:r,ageMaxDate:n,ageMinDate:i,ageMax:a,ageMin:o}=t;const s=t.categoryName;let c;if(!XS([r,n,i,s],"string")||!ev([a,o]))return{error:Us};const u=e.consideredDate??Lc((new Date).toLocaleDateString("sv"));if(!bc(u))return{error:io};const[d]=u.split("-").slice(0,3).map((e=>parseInt(e))),p=Vc(u,-1),[l,m]=p.split("-").slice(1,3).map((e=>parseInt(e))),f=`${Yc(l)}-${Yc(m)}`,h=Vc(u,1),[g,I]=h.split("-").slice(1,3).map((e=>parseInt(e))),U=`${Yc(g)}-${Yc(I)}`;let y=o&&Vc(u,-365*o),S=a&&Vc(u,-365*a);const v=[],T=e=>!v.includes(e)&&v.push(e);r=r??s;const P=/^([UO]?)(\d{1,2})([UO]?)$/,D=/^C(\d{1,2})-(\d{1,2})$/,w=r?.includes("-"),b=w&&r?.match(D),R=r?.match(P),N=(e,t)=>`${e}-${t}`,M=e=>{const n=N(d-e-1,U);t.ageMin&&t.ageMin>e&&T(`Invalid submitted ageMin: ${o}`),t.ageMax&&t.ageMax>e&&T(`Invalid submitted ageMax: ${a}`),t.ageMinDate&&t.ageMinDate!==n&&T(`Invalid submitted ageMinDate: ${i}`),i=n,r&&(t.ageMax&&t.ageMax!==e&&(T(`Invalid submitted ageMax: ${a}`),y=void 0),a=e)},A=e=>{const i=N(d-e,f);t.ageMaxDate&&t.ageMaxDate!==i&&T(`Invalid submitted ageMaxDate: ${n}`),n=i,r&&(t.ageMin&&t.ageMin!==e+1&&(T(`Invalid submitted ageMin: ${o}`),y=void 0),o=e+1)},E=e=>{const[s,c,u]=(e.match(P)||[]).slice(1),p=parseInt(c);"U"===s?(t.ageMaxDate&&t.ageMaxDate!==n&&T(`Invalid submitted ageMaxDate: ${t.ageMaxDate}`),(e=>{const n=N(d-e,U);t.ageMinDate&&t.ageMinDate!==n&&T(`Invalid submitted ageMinDate: ${i}`),i=n,r&&(t.ageMax&&t.ageMax!==e-1&&(T(`Invalid submitted ageMax: ${a}`),S=void 0),a=e-1)})(p)):"O"===s&&A(p),"U"===u?(t.ageMaxDate&&t.ageMaxDate!==n&&T(`Invalid submitted ageMaxDate: ${t.ageMaxDate}`),M(p)):"O"===u&&(e=>{const i=N(d-e-1,f);t.ageMaxDate&&t.ageMaxDate!==i&&T(`Invalid submitted ageMaxDate: ${n}`),n=i,r&&(t.ageMin&&t.ageMin!==e&&(T(`Invalid submitted ageMin: ${o}`),y=void 0),o=e)})(p),n=n??y,i=i??S};if(b){if(n=void 0,i=void 0,a=void 0,o=void 0,t.ageMin){const e=d-t.ageMin;n=N(e,f)}if(t.ageMax){const e=d-t.ageMax-1;i=N(e,U)}const[e,s]=(r?.match(D)??[]).slice(1).map((e=>parseInt(e)));e<=s?(o=e,a=s,c=!0):T(`Invalid combined age range ${r}`)}else w?r?.split("-").forEach(E):R?E(r):(o&&A(o),a&&M(a));a&&t.ageMin&&t.ageMin>a&&(T(`Invalid submitted ageMin: ${t.ageMin}`),o=void 0);const C=Mf({consideredDate:u,combinedAge:c,ageMaxDate:n,ageMinDate:i,ageMax:a,ageMin:o});return v.length&&(C.errors=v),C}function rv({category:e}){if(!ru(e))return{error:ys};const t=tv({category:e});if(t.error)return{error:t};const{ratingMax:r,ratingMin:n}=e;return r&&!kd(r)?pd({result:{error:ys},context:{ratingMax:r}}):n&&!kd(n)?pd({result:{error:ys},context:{ratingMin:n}}):{...t}}function nv({childCategory:e,withDetails:t,category:r}){const n=rv({category:r}),i=rv({category:e}),a=i.ageMin&&(n.ageMin&&i.ageMin<n.ageMin||n.ageMax&&i.ageMin>n.ageMax),o=i.ageMax&&(n.ageMax&&i.ageMax>n.ageMax||n.ageMin&&i.ageMax<n.ageMin),s=i.ageMinDate&&n.ageMaxDate&&new Date(i.ageMinDate)>new Date(n.ageMaxDate),c=i.ageMaxDate&&n.ageMinDate&&new Date(i.ageMaxDate)<new Date(n.ageMinDate),u=r?.ratingType&&e?.ratingType&&r.ratingType===e.ratingType&&(r.ratingMin&&e.ratingMin&&e.ratingMin<r.ratingMin||r.ratingMax&&e.ratingMax&&e.ratingMax>r.ratingMax||r.ratingMin&&e.ratingMax&&e.ratingMax<r.ratingMin||r.ratingMax&&e.ratingMin&&e.ratingMin>r.ratingMax),d=r?.ballType&&e?.ballType&&r.ballType!==e.ballType,p=Mf({invalidRatingRange:u,invalidAgeMinDate:s,invalidAgeMaxDate:c,invalidBallType:d,invalidAgeMax:o,invalidAgeMin:a,valid:!(u||s||c||d||o||a)},!0);return t&&Object.assign(p,{categoryDetails:n,childCategoryDetails:i}),p}function iv(e,t){if((e?.bestOf||e?.exactly)&&e?.setFormat)return function(e,t){const r=av(e.bestOf)||void 0,n=av(e.exactly)||void 0,i=r||n;if(e.setFormat?.timed&&e.simplified&&1===i)return ov(e.setFormat);const a=i&&`${zI}${i}`||"",o=sv(e.setFormat,t),s=o&&`S:${o}`||"",c=sv(e.finalSetFormat,t),u=i&&i>1&&c&&o!==c&&`F:${c}`||"";if(a&&o)return[a,s,u].filter((e=>e)).join("-");return}(e,t)}function av(e){return!isNaN(Number(e))&&Number(e)}function ov(e){let t=`T${e.minutes}`;return e.based&&(t+=e.based),e.modifier&&(t+=`@${e.modifier}`),t}function sv(e,t){if("object"==typeof e&&Object.keys(e).length){if(e.timed)return ov(e);if(e.tiebreakSet)return cv(e.tiebreakSet);const r=av(e.setTo);if(r){const n=e.NoAD&&HI||"",i=cv(e.tiebreakFormat),a=i&&`/${i}`||"",o=av(e.tiebreakAt);if(!1!==i)return`${r}${n}${a}${o&&(o!==r||t)&&`@${o}`||""}`}}}function cv(e){if(e){if("object"!=typeof e||e.tiebreakTo){if("object"==typeof e&&av(e.tiebreakTo)){let t=`TB${e.tiebreakTo}${e.NoAD?HI:""}`;return e.modifier&&(t+=`@${e.modifier}`),t}return!1}return""}}function uv({matchUpFormat:e}){if("string"!=typeof e)return!1;const t=QI(e),r=e.match(/-S:([1-9])+\/TB([0-9]{1,2})@?([1-9]?)*/),n=r?.[1],i=r?.[2],a=r?.[3],o=e.match(/-F:([1-9])+\/TB([0-9]{1,2})@?([1-9]?)*/),s=o?.[1],c=o?.[2],u=o?.[3];return iv(t,!!(r&&i&&n===a||o&&c&&s===u))===e}function dv({checkCategory:e=!0,collectionDefinition:t,checkCollectionIds:r,checkGender:n=!0,referenceCategory:i,referenceGender:a,event:o}){a=a??o?.gender;const s="validateCollectionDefinition",c=[];if("object"!=typeof t)return c.push(`collectionDefinition must be an object: ${t}`),pd({result:{errors:c,error:gs},stack:s});const{collectionValueProfiles:u,collectionGroupNumber:d,collectionValue:p,collectionId:l,matchUpCount:m,matchUpFormat:f,matchUpValue:h,matchUpType:g,scoreValue:I,setValue:U,category:y,gender:S}=t;r&&"string"!=typeof l&&c.push(`collectionId is not type string: ${l}`),"number"!=typeof m&&c.push(`matchUpCount is not type number: ${m}`),g&&![mf,hf].includes(g)&&c.push(`matchUpType must be SINGLES or DOUBLES: ${g}`);if(1!==[!!u?.length].concat([h,p,I,U].map(Vd)).filter(Boolean).length&&c.push("Missing value definition for matchUps: matchUpValue, collectionValue, or collectionValueProfiles"),h&&"number"!=typeof h&&c.push(`matchUpValue is not type number: ${h}`),p&&"number"!=typeof p&&c.push(`collectionValue is not type number: ${p}`),u&&m){const e=function({collectionValueProfiles:e,matchUpCount:t}){const r=[];if(!Array.isArray(e))return r.push(`collectionValueProfiles is not an array: ${e}`),{errors:r};if(e.length&&e.length!==t)return r.push("collectionValueProfiles do not align with matchUpsCount"),{errors:r};for(const n of e){if("object"!=typeof n)return r.push(`valueProfile is not type object: ${n}`),{errors:r};const{matchUpValue:e,collectionPosition:i}=n;if("number"!=typeof e||"number"!=typeof i||i>t||i<1)return r.push("Invalid value profile: value and collectionPosition must be numeric. collectionPosition cannot be greater than matchUpCount"),{errors:r}}const n=e.map((e=>e.collectionPosition));return n.length!==jd(n).length?(r.push("collectionPositions are not unique"),{errors:r}):{...Ni}}({collectionValueProfiles:u,matchUpCount:m});e.errors&&c.push(...e.errors)}if(d&&"number"!=typeof d&&c.push(`collectionGroupNumber is not type number: ${p}`),f&&!uv({matchUpFormat:f})&&c.push(`Invalid matchUpFormat: ${f}`),n){const e=ZS({referenceGender:a,matchUpType:g,gender:S});if(e.error)return pd({context:{referenceGender:a,gender:S},result:e,stack:s})}if(e&&i&&y){const e=nv({category:i,childCategory:y});if(!e.valid)return pd({result:{error:Us},context:e,stack:s})}return c.length?pd({result:{errors:c,error:hs},stack:s}):{valid:!0}}function pv(e){const t=!(!1===e?.enforceCategory||!e?.category),r=!(!1===e?.enforceGender||!e?.gender),n=e?.checkCollectionIds,i=e?.tieFormat,o=e?.event,s="validateTieFormat",c=[];if(!e||!i||"object"!=typeof i)return c.push("tieFormat must be an object"),a({result:{error:Ea},context:{tieFormat:i,errors:c},stack:s});if("object"!=typeof i.winCriteria)return c.push("tieFormat.winCriteria must be an object"),a({result:{error:Ea},context:{tieFormat:i,errors:c},stack:s});if(!Array.isArray(i.collectionDefinitions))return c.push(Vt("tieFormat.collectionDefinitions")),a({result:{error:Ea},context:{tieFormat:i,errors:c},stack:s});let d;const p=i.collectionDefinitions.every((i=>{const{setValue:a,scoreValue:s,collectionValue:u}=i;!a&&!s||u||(d=!0);const{valid:p,errors:l}=dv({referenceCategory:e.category,referenceGender:e.gender,collectionDefinition:i,checkCollectionIds:n,checkCategory:t,checkGender:r,event:o});return!!p||(Array.isArray(l)&&c.push(...l),!1)})),l="number"==typeof i.winCriteria?.valueGoal&&i.winCriteria?.valueGoal>0&&!d||i.winCriteria?.aggregateValue;if(!l&&!i.winCriteria?.aggregateValue)return d?c.push("aggregateValue is required"):c.push("Either non-zero valueGoal, or { aggregateValue: true } must be specified in winCriteria"),a({context:{tieFormat:i,errors:c,aggregateValueImperative:d},result:{error:Ea},stack:s});const m=i.collectionDefinitions.map((({collectionId:e})=>e)),f=!n||m.length===u(m).length,h=p&&l&&f;return h?{valid:h,errors:c}:a({result:{error:Ea},context:{tieFormat:i,errors:c},stack:s})}function lv(e){const{drawType:t=gl,attachConsolation:r=!0,applyPositioning:n=!0,tournamentRecord:i,staggeredEntry:a,automated:o,placeByes:s,isMock:c,event:u}=e;let d=e?.drawDefinition;if(!d)return{error:Li};const p=Hp,l=ah({stageSequence:1,drawDefinition:d,stage:p}),m=[Cl,Il,Ol].includes(t)?l.length:xd(l.length);if(!a&&t===ml&&l.length<2||t===Cl&&l.length<3)return{error:Xi};let{tieFormat:f,matchUpType:h}=e;if(f){const e=pv({tieFormat:f});if(e.error)return e}f=QS(f??Og({drawDefinition:d})?.tieFormat),h=h??d.matchUpType??mf;const{structures:g}=Fm({stageSequence:1,drawDefinition:d,stage:p});if(g.length>1)return{error:ba};if(g?.[0]?.matchUps?.length)return{error:Cs};const I=g?.[0]?.structureId;Object.assign(e,Mf({structureName:e.structureName??wm(Hp),structureId:I,matchUpType:h,tieFormat:f,drawSize:m,stage:p}));const U=HS(e);if(U.error)return U;const y=U.generators[t];if(!y)return{error:zi};const S=y?.();if(S.error)return S;const{structures:v,links:T}=S,P=v.map((e=>Kf({structure:e}).matchUps)).flat();f&&P.forEach((e=>{const{tieMatchUps:t}=Yg({matchUp:e,tieFormat:f,isMock:c});Object.assign(e,{tieMatchUps:t,matchUpType:h})})),n&&r||(d=Jc(d,!1,!0)),d.links||(d.links=[]),T.length&&d.links.push(...T);const D=v.map((({structureId:e})=>e));d.structures||(d.structures=[]);const w=d.structures.map((({structureId:e})=>e));d.structures=d.structures.map((e=>D.includes(e.structureId)?v.find((({structureId:t})=>t===e.structureId)):e));const b=v.filter((({structureId:e})=>!w.includes(e)));return b.length&&d.structures.push(...b),o&&Jh({seedingProfile:e.seedingProfile,applyPositioning:n,tournamentRecord:i,drawDefinition:d,structureId:I,placeByes:s,drawSize:m,event:u}),r&&jp({drawDefinition:d}),{links:T,structures:v,...Ni}}function mv(e){const{matchUpIds:t=[],drawDefinition:r,roundNumber:n,newRound:i,isMock:o,event:s}=e;if("object"!=typeof r)return{error:Li};let{participantIdPairings:c,matchUpsCount:u}=e;const d=e.structureId??(1===r.structures?.length&&r.structures?.[0]?.structureId);if("string"!=typeof d)return{error:la};const p=r.structures?.find((e=>e.structureId===d));if(!p)return{error:ma};let m;const f=p.matchUps??[],h=f?.reduce(((e,t)=>(t.roundPosition&&(m=!0),(t?.roundNumber||0)>e?t.roundNumber:e)),0),g=r?.entries?.filter((e=>{const t=e.entryStatus;return um.includes(t)}))??[],I=Math.floor(g?.length/2)||1;if(u){if(u>I&&!1!==e.restrictMatchUpsCount)return a({result:{error:ys,info:"matchUpsCount error",context:{roundMatchUpsCount:I}}})}else if(i)u=I;else{const e=n??h??1,t=I-(p.matchUps?.filter((t=>t.roundNumber===e))?.length??0);t>0&&(u=t)}if(c&&!Array.isArray(c)||u&&!Fe(u)||t&&!Array.isArray(t)||!c&&!u)return{error:ys,info:"matchUpsCount or pairings error"};if(u&&u>25)return{error:ys,info:"matchUpsCount must be less than 25"};if(p.structures||m||p.finishingPosition===Vl)return{error:ji};if(n&&!e.ignoreLastRoundNumber&&n-1>(h||0))return{error:ys,info:"roundNumber error"};const U=n??(i&&(h??0)+1||h||1);c=c??l(0,u).map((()=>({participantIds:[void 0,void 0]})));const y=c?.map(((n,i)=>{const a=n?.participantIds??[void 0,void 0];a.push(void 0,void 0);const s=a.slice(0,2).map(((e,t)=>S({sideNumber:t+1,participantId:e}))),c=t[i]??(t=>{if(!e.idPrefix&&!o)return;return`${r.drawId}-${e.idPrefix??"ah"}-${U}-${t}`})(i)??vt();return{roundNumber:U,matchUpStatus:Qm,matchUpId:c,sides:s}}));if(y?.length){const e=we({drawDefinition:r,event:s})?.tieFormat;e&&y.forEach((t=>{const{tieMatchUps:r}=or({tieFormat:e,matchUp:t,isMock:o});Object.assign(t,{tieMatchUps:r,matchUpType:If})}))}return{roundNumber:U,matchUpsCount:y?.length??0,matchUps:y,...Ni}}function fv(e){return e.participantIdPairings.map((({participantIds:e})=>e.sort().join("|"))).sort().join("/")}function hv({valueSortedPairings:e,stipulated:t=[],pairingValueMap:r,deltaObjects:n,valueObjects:i,actorsCount:a}){const o=[].concat(...t),s=[];let c=0;t.filter(Boolean).forEach((e=>{const[t,n]=e,i=gv(t,n),a=r[i];s.push({participantIds:e,value:a}),c+=r[i]}));p(e,a).map((e=>f(e).map((e=>({...e,value:e.value+Math.random()*Math.round(Math.random())}))))).flat().forEach((e=>{const t=e.pairing.split("|");if(!t.reduce(((e,t)=>o.includes(t)||e),!1)){o.push(...t);const r=e.value;c+=r,s.push({participantIds:t,value:r})}})),s.sort(((e,t)=>e.value-t.value));const u=s.reduce(((e,t)=>{const[r,i]=t.participantIds,a=gv(r,i),o=n[a];return o>e?o:e}),0),d=s.reduce(((e,t)=>{const[r,n]=t.participantIds,a=gv(r,n),o=i[a];return o>e?o:e}),0);return{value:c,participantIdPairings:s,maxDelta:u,maxDiff:d}}function gv(e,t){return[e,t].sort(sr).join("|")}function Iv({participantIds:e}){const t={},r=[];e.forEach((n=>{t[n]=e.filter((e=>e!==n)),t[n].forEach((e=>{const t=gv(e,n);r.includes(t)||r.push(t)}))}));const n=Object.assign({},...r.map((e=>({[e]:0}))));return{uniquePairings:r,possiblePairings:t,deltaObjects:n}}const Uv="ELO",yv="NTRP",Sv="WTN",vv={ELO:Uv,NTRP:yv,TRN:"TRN",UTR:"UTR",WTN:Sv},Tv={[Uv]:{defaultInitialization:1500,decimalsCount:0,range:[0,3e3],ascending:!0},[yv]:{accessors:["ntrpRating","dntrpRatingHundredths"],attributes:{ustaRatingType:""},accessor:"dntrpRatingHundredths",defaultInitialization:3,decimalsCount:1,ascending:!0,range:[1,7]},UTR:{defaultInitialization:6,accessors:["utrRating"],accessor:"utrRating",decimalsCount:2,ascending:!0,range:[1,16]},[Sv]:{attributes:{confidence:{generator:!0,range:[60,100]}},accessors:["wtnRating","confidence"],defaultInitialization:23,accessor:"wtnRating",ascending:!1,decimalsCount:2,range:[40,1]}},Pv=0;function Dv({tournamentParticipants:e,adHocRatings:t={},possiblePairings:r,uniquePairings:n,maxIterations:i,deltaObjects:a,valueObjects:o,eventType:s,scaleName:c,salted:u}){n.forEach((r=>{const n=function({tournamentParticipants:e,adHocRatings:t,eventType:r,scaleName:n,pairing:i}){const a=Tv[n]?.defaultInitialization??Pv;return i.split("|").map((n=>{if(r===Wf){const r=e?.find((e=>e.participantId===n))?.individualParticipantIds;return r?r?.map((e=>t[e]||a)):2*a}return t[n]||a}))}({tournamentParticipants:e,adHocRatings:t,scaleName:c,eventType:s,pairing:r}),i="number"==typeof u&&u||.5,d=u&&(Math.round(Math.random())?i:-1*i)||0,p=Math.abs(n[0]-n[1])+d,l=Math.abs(n[0]-n[1]);a[r]=l,o[r]||(o[r]=0),o[r]+=p?Math.pow(p,2):0}));const d=n.map((e=>({pairing:e,value:o[e]}))).sort(((e,t)=>e.value-t.value)),{pairingValues:p}=function({possiblePairings:e,valueObjects:t}){const r={};for(const t of Object.keys(e)){const i=e[t].map((e=>n(t,e)));r[t]=i.sort(((e,t)=>e.value-t.value))}function n(e,r){const n=gv(e,r);return{opponent:r,value:t[n]}}return{pairingValues:r}}({possiblePairings:r,valueObjects:o}),{candidate:l,candidatesCount:m,deltaCandidate:f,iterations:h}=function({maxIterations:e=4e3,valueSortedPairings:t,pairingValues:r,valueObjects:n,deltaObjects:i}){const a=Object.assign({},...t.map((e=>({[e.pairing]:e.value})))),o=Object.keys(r);let s=[];const c=hv({actorsCount:o.length,valueSortedPairings:t,pairingValueMap:a,deltaObjects:i,valueObjects:n}),u=[fv(c)];s.push(c);let d,p=c.value,l=c,m=0,f=0,h=o.length;do{h-=1,d=o.length*r[o[0]].length}while(d>e&&h>5);const I=[];o.forEach((e=>{r[e].slice(0,h).forEach((r=>{f+=1;const c=gv(e,r.opponent);if(!I.includes(c)){const d=hv({stipulated:[[e,r.opponent]],actorsCount:o.length,valueSortedPairings:t,pairingValueMap:a,deltaObjects:i,valueObjects:n});if(!u.includes(fv(d))){u.push(fv(d)),s.push(d);const{maxDelta:e,value:t}=d;e<l.maxDelta&&(l=d),(t<p||t===p&&Math.round(Math.random()))&&(p=t),I.push(c),m+=1}}})),s=s.filter((e=>Math.abs(e.value-p)<5))})),s.sort(((e,t)=>e.maxDiff-t.maxDiff));const U=g(s);return{candidatesCount:m,deltaCandidate:l,maxIterations:e,iterations:f,candidate:U}}({valueSortedPairings:d,maxIterations:i,pairingValues:p,deltaObjects:a,valueObjects:o}),{participantIdPairings:I}=l;return{participantIdPairings:I,candidatesCount:m,deltaCandidate:f,iterations:h,candidate:l}}const wv=100,bv=100,Rv=4e3;function Nv({encounterValue:e=wv,sameTeamValue:t=bv,maxIterations:r=Rv,generateMatchUps:n=!0,ignoreLastRoundNumber:i,iterationMatchUps:a,tournamentRecord:o,participantIds:s,drawDefinition:c,adHocRatings:u,salted:d=.5,roundNumber:p,structureId:l,matchUpIds:m,eventType:f,structure:h,scaleName:g,idPrefix:I,isMock:U,event:y}){if(!c)return{error:Li};if(!h&&!l)return{error:ma};if(h||(h=w({drawDefinition:c,structureId:l}).structure),!mt(h))return{error:ha};if(!s?.length)return{error:No};const S=[...a??[],...h?.matchUps??[]],{encounters:T}=function({matchUps:e}){const t=[];for(const r of e){const e=r.sides.map(v);if(2===e.length){const[r,n]=e,i=gv(r,n);t.includes(i)||t.push(i)}}return{encounters:t}}({matchUps:S}),P=o?.participants??[],{valueObjects:D}=function({encounters:e,tournamentParticipants:t,encounterValue:r,sameTeamValue:n}){const i={};for(const t of e)i[t]||(i[t]=0),i[t]+=r;const a=t?.filter((({participantType:e})=>e===ym));if(a)for(const e of a){const t=e.individualParticipantIds??[],{uniquePairings:r}=Iv({participantIds:t});for(const e of r)i[e]||(i[e]=0),i[e]+=n}return{valueObjects:i}}({tournamentParticipants:P,encounterValue:e,sameTeamValue:t,encounters:T}),{uniquePairings:b,possiblePairings:R,deltaObjects:N}=Iv({participantIds:s}),M={tournamentParticipants:P,possiblePairings:R,drawDefinition:c,participantIds:s,uniquePairings:b,maxIterations:r,adHocRatings:u,deltaObjects:N,valueObjects:D,eventType:f,scaleName:g,structure:h,salted:d},{candidatesCount:A,participantIdPairings:E,iterations:C,candidate:O}=Dv(M);if(!A)return{error:ms};let F,k;if(n){const e=mv({structureId:h?.structureId,ignoreLastRoundNumber:i,participantIdPairings:E,newRound:!0,drawDefinition:c,roundNumber:p,matchUpIds:m,idPrefix:I,isMock:U,event:y});if(e.error)return e;F=e.roundNumber,k=e.matchUps}const{maxDelta:_,maxDiff:x}=O;return{roundNumber:F,participantIdPairings:E,candidatesCount:A,...Ni,iterations:C,matchUps:k,maxDelta:_,maxDiff:x}}function Mv(e){const t=e.drawDefinition,{existingQualifyingPlaceholderStructureId:r,drawEntries:n,appliedPolicies:i,structureId:a,idPrefix:o,isMock:s}=e,c=e.qualifyingProfiles,u=c?.length?mr({uuids:e.uuids,qualifyingProfiles:c,appliedPolicies:i,idPrefix:o,isMock:s}):void 0;if(u?.error)return u;t.structures=t.structures?.filter((({structureId:e})=>e!==r)),t.links=t.links?.filter((({source:e})=>e.structureId!==r));const{qualifiersCount:d,qualifyingDrawPositionsCount:p,qualifyingDetails:l}=u??{};p&&(u?.structures&&t.structures?.push(...u.structures),u?.links&&t.links?.push(...u.links));const m=t.structures?.find((({stage:e,stageSequence:t})=>e===qp&&1===t)),{qualifiersCount:f}=dt({stageSequence:1,drawDefinition:t,structureId:a,stage:qp}),h=Math.max(d??0,f??0);let g=pr({qualifiersCount:h,drawDefinition:t,stage:qp});if(g.error)return g;if(g=lr({drawSize:p,stage:$p,drawDefinition:t}),g.error)return g;!function({drawDefinition:e,drawEntries:t}){for(const r of(t??[]).filter((({entryStage:e})=>e===$p))){const t={...r,entryStage:r.entryStage??qp,drawDefinition:e};fr(t)}}({drawDefinition:t,drawEntries:n});const I=function({mainStructure:e,qualifyingDetails:t,drawDefinition:r}){for(const n of t||[]){const{finalQualifyingRoundNumber:t,finalQualifyingStructureId:i,roundTarget:a,finishingPositions:o,linkType:s}=n,c=e&&nr({targetStructureId:e.structureId,sourceStructureId:i,sourceRoundNumber:t,finishingPositions:o,targetEntryRound:a,linkType:s})?.link;if(c?.error)return c;c&&(r.links||(r.links=[]),r.links.push(c))}return{error:void 0}}({mainStructure:m,qualifyingDetails:l,drawDefinition:t});return I.error?I:{drawDefinition:t,structureId:a}}function Av(e){let{participantIds:t}=e;const r=e.drawDefinition?.entries?.filter((t=>{const r=t.entryStatus;return!e.restrictEntryStatus||um.includes(r)})).map(v)??[];if(t){const e=t.filter((e=>!r?.includes(e)));if(e?.length)return a({result:{error:Io},info:{invalidParticipantIds:e}})}else t=r;return e.roundsCount&&!1!==e.restrictRoundsCount&&e.roundsCount>t.length-1&&(!e.enableDoubleRobin||e.roundsCount>2*(t.length-1))?{error:ys,info:"Not enough participants for roundsCount"}:e.roundsCount&&e.roundsCount>25?{error:ys,info:"roundsCount must be less than 25"}:{participantIds:t}}function Ev(e){const t=[],{roundsCount:r=1,drawDefinition:n,matchUpsCount:i,structureId:o,idPrefix:s,isMock:c,event:u}=e;let d;const p=Av(e);if(p.error)return p;for(const p of l(1,r+1)){const r=mv({restrictMatchUpsCount:e.restrictMatchUpsCount,ignoreLastRoundNumber:!!d,newRound:!d,drawDefinition:n,matchUpsCount:i,structureId:o,roundNumber:d,idPrefix:s,isMock:c,event:u});if(r.error)return a({result:r,info:{iteration:p}});r.matchUps?.length&&t.push(...r.matchUps),d=(r?.roundNumber??1)+1}return{matchUps:t}}function Cv(e){const t=function(e){if(e.roundsCount&&"number"!=typeof e.roundsCount)return{error:ys,info:"roundsCount must be a number"};if("object"!=typeof e.drawDefinition||e.drawDefinition.drawType&&e.drawDefinition.drawType!==ll)return{error:xi};if(!Array.isArray(e.drawDefinition?.entries)&&e.participantIds&&!Array.isArray(e.participantIds))return{error:ys,info:"Missing Entries"};return{error:void 0}}(e);if(t?.error)return t;const r=Av(e);if(r.error)return r;const n=function(e){if(e.structureId)return e.structureId;const t=e.drawDefinition,r=t?.structures?.filter((e=>1===e.stageSequence))?.reduce(((e,r)=>{const n=r.stage&&Qp[r.stage];return Se({drawDefinition:t,structure:r})&&n>(Qp[e?.stage]||1)?r:e}),void 0),n=t?.structures?.find((e=>e.structureId===r?.structureId));if(!n)return{error:ma};return Se({drawDefinition:t,structure:n})?{structure:n}:{error:xi}}(e);if(n.error)return n;const i=function(e){const{tournamentRecord:t,participantIds:r,scaleAccessor:n,scaleName:i,eventType:a,adHocRatings:o={}}=e,s=t.participants??[];for(const e of r??[]){const t=s?.find((t=>t.participantId===e));let r=Ov({scaleName:`${i}.${du}`,scaleAccessor:n,participant:t,eventType:a});!r&&i&&(r=Ov({scaleAccessor:n,participant:t,scaleName:i,eventType:a})),r&&!o[e]&&(o[e]=r)}return o}(e),a=e.tournamentRecord?.isMock??e.isMock,o=e.eventType??e.event?.eventType,s=[],c=[];let u;for(const t of l(1,(e.roundsCount??1)+1)){const d=Nv({...e,participantIds:r.participantIds,structure:n.structure,ignoreLastRoundNumber:!0,iterationMatchUps:s,adHocRatings:i,roundNumber:u,eventType:o,isMock:a});if(d.error)return d;const{matchUps:p,...l}=d;c.push({...l,iteration:t,matchUpsCount:p?.length}),u=(l?.roundNumber??1)+1,p?.length&&s.push(...p)}return{...Ni,matchUps:s,roundResults:c}}function Ov({scaleType:e=lu,scaleAccessor:t,participant:r,scaleName:n,eventType:i}){const a=r&&Ir({scaleAttributes:{eventType:i??$f,scaleType:e,scaleName:n},participant:r}),o=a?.scaleItem?.scaleValue;return t&&mt(o)?o[t]:o}function Fv(e){const{tournamentRecord:t,drawDefinition:r,structureId:n,idPrefix:i,isMock:a,event:o}=e,s=o?.entries?.filter((({entryStage:e,entryStatus:t})=>(!e||e===qp)&&t&&um.includes(t))),c=s?.map(v),u=s?Math.floor(s.length/2):0;if(e.automated)return function(e){const{restrictEntryStatus:t,generateMatchUps:r,structureId:n,matchUpIds:i,scaleName:a}=e.drawMatic??{},o=Cv({...e,eventType:e.drawMatic?.eventType??e.matchUpType,generateMatchUps:r??!0,participantIds:e.participantIds,roundsCount:e.roundsCount,restrictEntryStatus:t,structureId:n,matchUpIds:i,scaleName:a});return o.error?o:(o?.matchUps?.length&&gr({tournamentRecord:e.tournamentRecord,drawDefinition:e.drawDefinition,suppressNotifications:!0,matchUps:o.matchUps,event:e.event,structureId:n}),{...Ni})}({...e,participantIds:c});{const s=Ev({roundsCount:e.roundsCount,drawDefinition:r,matchUpsCount:u,idPrefix:i,isMock:a,event:o});if(s.error)return s;s.matchUps?.length&&gr({matchUps:s.matchUps,suppressNotifications:!0,tournamentRecord:t,drawDefinition:r,structureId:n,event:o})}return{...Ni}}function kv(e){const t="prepareStage",{drawDefinition:r}=e,{structures:n}=b({stageSequence:e.stageSequence||1,roundTarget:e.roundTarget,stage:e.stage,drawDefinition:r}),i=e.preparedStructureIds||[],o=n?.find((({structureId:e})=>!i.includes(e)));if(!o)return a({result:{error:ma},stack:t});const c=o?.structureId,{seedsCount:u,stageEntries:d,seedLimit:p}=function(e){let{seedsCount:t}=e;e.seededParticipants&&(t=e.seededParticipants.length);t>e.drawSize&&(t=e.drawSize);const r=function({entries:e,stage:t,stageSequence:r,roundTarget:n}){return e.filter((e=>{const i=s({name:yi,element:e})?.extension?.value;return(!e.entryStage||e.entryStage===t)&&(!r||!e.entryStageSequence||e.entryStageSequence===r)&&(!n||!i||i===n)&&cm.includes(e.entryStatus)}))}(e);t>r.length&&(t=r.length);const{seedLimit:n}=Ur({enforcePolicyLimits:e.enforcePolicyLimits??!0,appliedPolicies:e.appliedPolicies,participantsCount:r.length,seedingProfile:e.seedingProfile,drawDefinition:e.drawDefinition,structureId:e.structureId,seedsCount:t});n&&n<t&&(t=n);return{seedsCount:t,stageEntries:r,seedLimit:n}}({...e,structureId:c});(e.seededParticipants||e.event||e.seedingScaleName)&&function(e){const{seededParticipants:t,seedingScaleName:r,entries:n,event:i}=e,a=n.map(v);t?function(e){const{provisionalPositioning:t,enteredParticipantIds:r,seededParticipants:n,tournamentRecord:i,appliedPolicies:a,drawDefinition:o,seedingProfile:s,structureId:c,structure:u,event:d}=e,p=u?Ie({provisionalPositioning:t,appliedPolicies:a,drawDefinition:o,seedingProfile:s,structure:u}):void 0;n.filter((({participantId:e})=>r.includes(e))).filter((e=>!e.seedNumber||e.seedNumber<=n.length)).sort(((e,t)=>e.seedNumber<t.seedNumber?-1:e.seedNumber<t.seedNumber?1:0)).forEach((e=>{const{participantId:r,seedNumber:n,seedValue:a}=e;Z({provisionalPositioning:t,tournamentRecord:i,drawDefinition:o,seedingProfile:s,participantId:r,seedBlockInfo:p,structureId:c,seedNumber:n,seedValue:a,event:d})}))}({...e,enteredParticipantIds:a}):(i||r)&&function(e){let t=e.seedsCount;const{provisionalPositioning:r,enteredParticipantIds:n,seedAssignmentProfile:i,assignSeedsCount:a,tournamentRecord:o,drawDefinition:s,seedByRanking:c,seedingProfile:u,structureId:d,event:p}=e,{categoryName:l,ageCategoryCode:m}=p?.category||{},f=p?.eventType,h=function(e){const{tournamentRecord:t,seedingScaleName:r,stageSequence:n,entries:i,stage:a,event:o}=e,{categoryName:s,ageCategoryCode:c}=o?.category||{},u=o?.eventType,d={scaleName:r||s||c||o.eventId,scaleType:fu,eventType:u};return Sr({scaleAttributes:d,tournamentRecord:t,stageSequence:n,entries:i,stage:a}).scaledEntries}({...e,ageCategoryCode:m,categoryName:l,eventType:f})||c&&function(e){const{tournamentRecord:t,stageSequence:r,event:n,entries:i,stage:a}=e,{categoryName:o,ageCategoryCode:s}=n?.category||{},c=n?.eventType,u={scaleName:o||s,scaleType:pu,eventType:c};return Sr({scaleAttributes:u,tournamentRecord:t,stageSequence:r,entries:i,stage:a}).scaledEntries}({...e,ageCategoryCode:m,categoryName:l,eventType:f}),g=h?.length??0;g<t&&(t=g);h?.filter((({participantId:e})=>n.includes(e))).slice(0,a||t).forEach(((e,t)=>{const n=t+1,{participantId:a,scaleValue:c}=e;Z({provisionalPositioning:r,tournamentRecord:o,drawDefinition:s,seedingProfile:u,participantId:a,structureId:d,seedNumber:n,seedValue:i?.[n]||c||n,event:p})}))}({...e,enteredParticipantIds:a})}({...e,seedsCount:u,structure:o,structureId:c});const l=!1!==e.automated&&e.drawType!==ll&&!(e.qualifyingOnly&&e.stage!==$p),m=(n?.length||0)>1,f=l?function(e){const t="object"==typeof e.automated&&e.automated.seedsOnly,r=yr({...e,seedsOnly:t});if(r.error)return r;const n=r?.positionAssignments,i=r?.positioningReport;return{conflicts:r.conflicts,positionAssignments:n,positioningReport:i}}({...e,multipleStructures:m,seedLimit:p,structureId:c}):{};return f?.error?a({result:f,stack:t}):{...f,stageEntries:d,structureId:c,seedsCount:u}}function _v(e){const t=hr({...e,modifyOriginal:!1});if(t.error)return t;const r=t.drawDefinition,{ignoreStageSpace:n,appliedPolicies:i,qualifyingOnly:a,seedingProfile:o,participants:s,drawEntries:c,placeByes:u,drawSize:d,drawType:p,entries:l}=e,m=[];let f=[];const h=function(e){const{ignoreStageSpace:t,drawDefinition:r,drawEntries:n,drawType:i,entries:a}=e;for(const e of a){if(n&&e.entryStage&&e.entryStage!==qp)continue;const a={...e,ignoreStageSpace:t??i===ll,entryStage:e.entryStage??qp,drawDefinition:r,drawType:i},o=fr(a);if(n&&o.error)return o}return{error:void 0}}({ignoreStageSpace:n,drawDefinition:r,drawEntries:c,drawType:p,entries:l});if(h.error)return h;const g=p===Sl?0:ve(e.seedsCount??0),I=kv({...e,qualifyingOnly:!d||a,appliedPolicies:i,drawDefinition:r,seedingProfile:o,participants:s,stage:qp,seedsCount:g,placeByes:u,drawSize:d,entries:l});if(I.error&&!I.conflicts)return I;I.positioningReport?.length&&m.push({[qp]:I.positioningReport});const U=I.structureId;return I.conflicts&&(f=I.conflicts),p===ll&&e.roundsCount&&Fv({...e,drawDefinition:r,structureId:U}),{drawDefinition:r,positioningReports:m,conflicts:f,structureId:U}}function xv({tournamentParticipants:e,afterRecoveryTimes:t,contextContent:r,contextProfile:n,drawDefinition:i,matchUpsMap:a,matchUpId:o,inContext:s,context:c,event:u}){if(!i)return{error:Li};if(!o)return{error:_a};if("string"!=typeof o)return{error:ys};const{structures:d=[]}=Fm({drawDefinition:i});n&&!r&&(r=k({contextProfile:n,drawDefinition:i}));for(const p of d){const{matchUps:d}=J({tournamentParticipants:e,afterRecoveryTimes:t,contextContent:r,drawDefinition:i,contextProfile:n,matchUpsMap:a,inContext:s,structure:p,context:c,event:u}),{matchUp:l}=Tr({matchUps:d,matchUpId:o});if(l)return{matchUp:l,structure:p}}return{error:La}}function Lv(e){let t=e.structureIds;const{tournamentRecord:r,drawDefinition:n,matchUpFormat:i,structureId:a,matchUpId:o,event:s}=e;if(!n)return{error:Li};if(!i)return{error:Oa};if(!uv({matchUpFormat:i}))return{error:Na};if(o){const e=xv({drawDefinition:n,matchUpId:o,event:s});if(e.error)return e;if(!e.matchUp)return{error:La};const t=e.matchUp;if(t?.matchUpType===zf)return{error:ja,info:"Cannot set matchUpFormat when { matchUpType: TEAM }"};t.matchUpFormat=i,Vp({tournamentId:r?.tournamentId,eventId:s?.eventId,context:"setMatchUpFormat",drawDefinition:n,matchUp:t})}else if(Array.isArray(t)){if(s?.eventType===zf)return{error:Ia};for(const e of t){const t=Om({drawDefinition:n,structureId:e});if(t.error)return t;if(!t.structure)return{error:ma};t.structure.matchUpFormat=i}}else if(a){if(s?.eventType===zf)return{error:Ia};const e=Om({drawDefinition:n,structureId:a});if(e.error)return e;if(!e.structure)return{error:ma};e.structure.matchUpFormat=i}else n&&(n.matchUpFormat=i);return t=t??(a?[a]:void 0),jp({drawDefinition:n,structureIds:t}),{...Ni}}function Vv({tournamentRecord:e,drawDefinition:t,matchUpFormat:r,matchUpType:n,tieFormat:i,event:a}){if(r||i){if(!(r&&a?.matchUpFormat===r||a?.tieFormat&&i&&JSON.stringify(a.tieFormat)===JSON.stringify(i))){if(i){const e=function({tieFormat:e}){const t=ar({checkCollectionIds:!1,tieFormat:e});if(t.error)return t;for(const t of e.collectionDefinitions)t.collectionId||(t.collectionId=vt());return{tieFormat:e}}({tieFormat:i});if(e.error)return e;t.tieFormat=e.tieFormat??i}else if(r){const n=Lv({tournamentRecord:e,drawDefinition:t,matchUpFormat:r,event:a});if(n.error)return{info:"matchUpFormat or tieFormat error",error:n.error}}n&&(t.matchUpType=n)}}return{error:void 0}}function Bv(e){const t=y(e,[{_anyOf:{[gu]:!1,[Uu]:!1,[yu]:!1,[Lu]:!1},[Iu]:!0}]);if(t.error)return t;const r=[],n=e.drawDefinition??e.event??((e.tournamentId||!e.tournamentRecords)&&e.tournamentRecord);if(n){const t=jv(e,n);if(t.error)return t;r.push(...t?.applied??[]),e.drawDefinition&&$({drawDefinition:e.drawDefinition,tournamentId:e.tournamentId})}else{if(!e.tournamentRecords)return{error:Fi};{const t=Object.keys(e.tournamentRecords);if(!t.length)return{error:Fi};for(const n of t){const t=jv(e,e.tournamentRecords[n]);if(t.error)return t;r.push(...t?.applied??[])}}}return r.length?{...Ni,applied:r}:{error:za}}function jv(e,t){const r=te(e).appliedPolicies??{};t.extensions||(t.extensions=[]);const n=[],i=Object.keys(e.policyDefinitions);if(!i.length)return{error:qa};for(const t of i)if(!r[t]||e.allowReplacement){const i=e.policyDefinitions[t];if(!i)continue;if(!ru(i))return{error:ys};const{policyName:a,...o}=i;if(!o||!Object.keys(o).length||a&&!tu(a))return{error:ys};r[t]=e.policyDefinitions[t],n.push(t)}if(n?.length){return{...o({element:t,extension:{name:ri,value:r}}),applied:n}}return{applied:n,error:za}}function Gv(e){const t=uy(e,[{policyType:!0,_anyOf:{[gu]:!1,[Uu]:!1,[yu]:!1,[Lu]:!1}}]);if(t.error)return t;let r;const n=e.drawDefinition??e.event??((e.tournamentId||!e.tournamentRecords)&&e.tournamentRecord);if(n)return qv(e,n);if(!e.tournamentRecords)return{error:Fi};{const t=Object.keys(e.tournamentRecords);if(!t.length)return{error:Fi};for(const n of t){const t=qv(e,e.tournamentRecords[n]);if(t.error)return t;r=!0}}return r?{...Ni}:{error:Ya}}function qv(e,t){const r=Oh(e).appliedPolicies??{};if(r[e.policyType]){if(delete r[e.policyType],Object.keys(r).length){gd({element:t,extension:{name:ri,value:r}})}else fd({element:t,name:ri});return{...Ni}}return{error:Ya}}var $v=Object.freeze({__proto__:null,attachPolicies:Bv,removePolicy:Gv}),Wv=Object.freeze({__proto__:null,findPolicy:YU,getAppliedPolicies:Oh,getPolicyDefinitions:Fh}),Hv=Object.freeze({__proto__:null,attachPolicies:Bv,findPolicy:YU,getAppliedPolicies:Oh,getPolicyDefinitions:Fh,mutate:$v,query:Wv,removePolicy:Gv});const zv={[od]:{validSeedPositions:{ignore:!0},duplicateSeedNumbers:!0,drawSizeProgression:!0,seedingProfile:{drawTypes:{[Ol]:{positioning:tl},[Cl]:{positioning:tl}},positioning:"SEPARATE"},policyName:"USTA SEEDING",seedsCountThresholds:[{drawSize:4,minimumParticipantCount:3,seedsCount:2},{drawSize:16,minimumParticipantCount:12,seedsCount:4},{drawSize:32,minimumParticipantCount:24,seedsCount:8},{drawSize:64,minimumParticipantCount:48,seedsCount:16},{drawSize:128,minimumParticipantCount:96,seedsCount:32},{drawSize:256,minimumParticipantCount:192,seedsCount:64}]}};function Yv({appliedPolicies:e,policyDefinitions:t,drawDefinition:r,stack:n}){if(t&&"object"!=typeof t)return pd({info:"policyDefinitions must be an object",result:{error:ys},stack:n});const i={[id]:e?.[id]};return t?function({policyDefinitions:e,appliedPolicies:t,policiesToAttach:r,drawDefinition:n}){for(const n of Object.keys(e))JSON.stringify(t?.[n])!==JSON.stringify(e[n])&&(r[n]=e[n]);Object.keys(r).length&&(Bv({policyDefinitions:r,drawDefinition:n}),t&&Object.assign(t,r))}({policyDefinitions:t,appliedPolicies:e,policiesToAttach:i,drawDefinition:r}):i.avoidance&&Bv({drawDefinition:r,policyDefinitions:i}),e?.[od]||t?.[od]||(Bv({policyDefinitions:zv,drawDefinition:r}),e&&Object.assign(e,zv)),{error:void 0}}function Qv(e){const t="generateOrGetExisting",r=[],n=[],i=function(e){const{tournamentRecord:t,matchUpFormat:r,appliedPolicies:n,policyDefinitions:i,matchUpType:o,tieFormat:s,drawType:c,stack:u,event:d}=e,p=e.drawId?d?.drawDefinitions?.find((t=>t.drawId===e.drawId)):void 0;p&&c!==p.drawType&&(p.drawType=c);const l=p??vr({processCodes:e.processCodes,drawId:e.drawId,drawType:c}),m=Vv({tournamentRecord:t,drawDefinition:l,matchUpFormat:r,matchUpType:o,tieFormat:s,event:d});if(m.error)return a({result:m,stack:u});const f=Yv({appliedPolicies:n,policyDefinitions:i,drawDefinition:l,stack:u});if(f.error)return f;const h=p?.structures?.find((e=>e.stage===qp&&1===e.stageSequence))?.structureId,g=p?p.structures?.filter((e=>e.stage===$p)):[];return{drawDefinition:l,structureId:h,existingDrawDefinition:p,existingQualifyingPlaceholderStructureId:1===g?.length&&!g[0].matchUps?.length&&g[0].structureId}}(e);if(i.error)return a({result:i,stack:t});const o=i.existingDrawDefinition;let s=i.drawDefinition??{},c=i.structureId;const u=e.drawEntries??e.eventEntries??[],d=i.existingQualifyingPlaceholderStructureId&&Mv({...e,...i})||_v({...e,...i,entries:u});return d.error?a({result:d,stack:t}):(d.positioningReports?.length&&r.push(...d.positioningReports??[]),d.conflicts?.length&&n.push(...d.conflicts??[]),s=d.drawDefinition,c=d.structureId,{existingDrawDefinition:o,positioningReports:r,drawDefinition:s,structureId:c,conflicts:n,entries:u})}function Kv(e){const{voluntaryConsolation:t,tournamentRecord:r,event:n}=e,i="generateDrawDefinition",{participants:o,participantMap:s}=pt({withIndividualParticipants:!0,convertExtensions:!0,internalUse:!0,tournamentRecord:r}),c=n?.entries?.filter((e=>e.entryStatus&&[...um,em].includes(e.entryStatus)))??[],u=ur({...e,participantMap:s,participants:o,eventEntries:c});if(u.error)return a({result:u,stack:i});const{appliedPolicies:d,policyDefinitions:p,drawSize:l,drawType:m,enforceGender:f,seedingProfile:h}=u,g=n?.eventType,I=e.matchUpType??g,U=dr({...e,enforceGender:f,eventType:g,matchUpType:I});if(U.error)return a({result:U,stack:i});const{matchUpFormat:y,tieFormat:S}=U;if(e.drawId&&"string"!=typeof e.drawId)return a({result:{error:ys},stack:i});const v=Qv({...e,isMock:e.isMock??!0,policyDefinitions:p,tournamentRecord:r,appliedPolicies:d,matchUpFormat:y,seedingProfile:h,participants:o,eventEntries:c,matchUpType:I,tieFormat:S,drawSize:l,drawType:m,event:n});if(v.error)return a({result:v,stack:i});const{existingDrawDefinition:T,positioningReports:P,drawDefinition:D,structureId:w,conflicts:b,entries:R}=v;if(!D)return a({result:{error:ys},stack:i});const N=function(e){const{qualifyingPlaceholder:t,qualifyingProfiles:r,existingDrawDefinition:n,positioningReports:i,appliedPolicies:o,qualifyingOnly:s,drawDefinition:c,seedingProfile:u,participants:d,structureId:p,entries:l,stack:m}=e,f=t&&!r?.length&&!n,h=[];if(r){const t=(e,t)=>e.stageSequence-t.stageSequence,n=(e,t)=>e.roundTarget-t.roundTarget,p=[];let f=1;r.sort(n);for(const n of r){if(!Array.isArray(n.structureProfiles))return a({info:Vt("structureProfiles"),result:{error:Za},stack:m});f=n.roundTarget||f;const r=n.structureProfiles?.sort(t)||[];let g=1;for(const t of r){const{qualifyingRoundNumber:r,qualifyingPositions:n,seededParticipants:a,seedingScaleName:m,seedsCount:I=0,seedByRanking:U,placeByes:y,drawSize:S}=t,v=kv({...e,seedingProfile:t.seedingProfile??u,stageSequence:g,qualifyingRoundNumber:r,preparedStructureIds:p,qualifyingPositions:n,seededParticipants:a,stage:$p,seedingScaleName:m,appliedPolicies:o,drawDefinition:c,qualifyingOnly:s,seedByRanking:U,participants:d,roundTarget:f,seedsCount:I,placeByes:y,drawSize:S,entries:l});if(v.error)return v;v.structureId&&p.push(v.structureId),g+=1,v.conflicts?.length&&h.push(...v.conflicts),v.positioningReport?.length&&i.push({[$p]:v.positioningReport})}f+=1}}else if(p&&f){const e=Ut({structureName:St($p),stage:$p}),{link:t}=nr({sourceStructureId:e.structureId,targetStructureId:p,sourceRoundNumber:0,linkType:cl});c.structures||(c.structures=[]),c.structures.push(e),c.links||(c.links=[]),c.links.push(t)}return{qualifyingConflicts:h,error:void 0}}({...e,existingDrawDefinition:T,positioningReports:P,appliedPolicies:d,drawDefinition:D,seedingProfile:h,participants:o,structureId:w,entries:R,params:e,stack:i});if(N.error)return N;const{qualifyingConflicts:M}=N;return D.drawName=e.drawName??(m&&St(m)),l&&"object"==typeof t&&l>=4&&cr({...t,drawDefinition:D,matchUpType:I}),{existingDrawDefinition:!!T,qualifyingConflicts:M,positioningReports:P,drawDefinition:D,structureId:w,...Ni,conflicts:b}}var Jv=Object.freeze({__proto__:null,addAdHocMatchUps:PU,addDrawDefinitionTimeItem:fg,addFinishingRounds:wg,addGoesTo:Jg,addPlayoffStructures:tI,addQualifyingStructure:Ag,addVoluntaryConsolationStage:Sg,addVoluntaryConsolationStructure:Nm,allPlayoffPositionsFilled:mh,alternateDrawPositionAssignment:bf,assignDrawPosition:xI,assignDrawPositionBye:sf,attachConsolationStructures:Zg,attachPlayoffStructures:Xg,attachQualifyingStructure:lg,attachStructures:eI,autoSeeding:OU,automatedPlayoffPositioning:Zh,automatedPositioning:Jh,checkValidEntries:BS,deleteAdHocMatchUps:UU,drawMatic:Cv,findDrawDefinition:fy,generateAdHocMatchUps:mv,generateAdHocRounds:Ev,generateAndPopulatePlayoffStructures:Kg,generateDrawDefinition:Kv,generateDrawMaticRound:Nv,generateDrawStructuresAndLinks:zS,generateDrawTypeAndModifyDrawDefinition:YS,generateQualifyingStructure:Mg,generateVoluntaryConsolation:lv,getAssignedParticipantIds:oy,getAvailablePlayoffProfiles:ny,getDrawDefinitionTimeItem:ig,getDrawParticipantRepresentativeIds:ZU,getDrawTypeCoercion:kS,getEligibleVoluntaryConsolationParticipants:JU,getParticipantIdFinishingPositions:ay,getPositionAssignments:_S,getPositionsPlayedOff:XU,getSeedingThresholds:Gh,getSeedsCount:NU,getStructureSeedAssignments:oh,getTeamLineUp:LS,getValidGroupSizes:Dg,isAdHoc:jS,isCompletedStructure:lh,isValidForQualifying:xS,luckyLoserDrawPositionAssignment:wf,modifyDrawDefinition:nI,modifyDrawName:rI,modifySeedAssignment:sh,mutate:FU,positionActions:FS,pruneDrawDefinition:_I,qualifierDrawPositionAssignment:Nf,query:GS,removeDrawPositionAssignment:Tm,removeRoundMatchUps:yU,removeSeededParticipant:vg,removeStructure:gg,renameStructures:mg,resetDrawDefinition:OI,resetVoluntaryConsolationStructure:Gl,setDrawParticipantRepresentativeIds:ip,setPositionAssignments:Rf,setStructureOrder:Xh,setSubOrder:DU,swapDrawPositionAssignments:eh,updateTeamLineUp:TU,withdrawParticipantAtDrawPosition:Pm});const Zv="COMPETITOR",Xv="OFFICIAL",eT="OTHER",tT={ADMINISTRATION:"ADMINISTRATION",CAPTAIN:"CAPTAIN",COACH:"COACH",COMPETITOR:Zv,MEDIA:"MEDIA",MEDICAL:"MEDICAL",OFFICIAL:Xv,OTHER:eT,SECURITY:"SECURITY"};function rT({addIndividualParticipantsToEvents:e,individualParticipantIds:t,groupingParticipantId:r,tournamentRecord:n,suppressErrors:i}){const o="removeIndividualParticipantIds";if(!n)return a({result:{error:Fi},stack:o});if(!r||!t)return a({result:{error:Za},stack:o});const s=(n.participants??[]).find((e=>e.participantId===r));if(!s)return a({result:{error:wo},stack:o});if(![ym,Im].includes(s.participantType))return a({result:{participantType:s.participantType,error:So},stack:o});const c=nT({individualParticipantIds:t,groupingParticipant:s,tournamentRecord:n,suppressErrors:i}),{removed:u,error:d}=c;if(d)return a({result:c,stack:o});if(e)for(const e of n.events??[]){const t=(e.entries??[]).map((({participantId:e})=>e)).filter(Boolean);if(t.includes(r)){const r=u?.filter((e=>!t.includes(e)));wr({participantIds:r,entryStatus:rm,tournamentRecord:n,event:e})}}return u&&Je({topic:Tp,payload:{tournamentId:n.tournamentId,participants:[s]}}),{...Ni,...c}}function nT({individualParticipantIds:e=[],groupingParticipant:t,tournamentRecord:r,suppressErrors:n,mappedMatchUps:i,participants:a}){const c=[];if(!t)return{removed:c};const u=[],d=[];a||({participants:a,mappedMatchUps:i}=pt({withMatchUps:!0,tournamentRecord:r,withEvents:!0}));const p=a?.find((({participantId:e})=>e===t.participantId)),l=p?.events?.map((({eventId:e})=>e)),m=(t.individualParticipantIds??[]).filter((n=>{const p=e?.includes(n),m=p&&a?.find((e=>e.participantId===n))?.matchUps.filter((({eventId:e})=>l.includes(e))).map((({matchUpId:e})=>i?.[e])).filter((({winningSide:e,score:t})=>e||Pr({score:t}))),f=p&&!m?.length;if(p&&!f&&d.push(n),f){c.push(n);for(const e of r.events??[])for(const i of e.drawDefinitions??[]){const{extension:e}=s({element:i,name:mi}),a=e?.value[t.participantId];e&&a&&(e.value[t.participantId]=a.filter((e=>e.participantId!==n)),o({element:i,extension:e}),z({drawDefinition:i}));const c=Dr({drawDefinition:i,inContext:!1}).matchUps??[];for(const e of c){const t=e.sides??[];for(const a of t){const t=a.lineUp??[];t.find((e=>e.participantId===n))&&(a.lineUp=t.filter((e=>e.participantId!==n)),q({tournamentId:r?.tournamentId,drawDefinition:i,matchUp:e}))}}}}else u.push(n);return!f}));t.individualParticipantIds=m;const f={groupingParticipantId:t.participantId,cannotRemove:d,notRemoved:u,removed:c};return d.length&&!n&&{...f,cannotRemove:d,error:fo}||f}function iT({participantRole:e=Zv,individualParticipantIds:t=[],groupingTypes:r=[hm,Im],tournamentRecord:n}){if(!n)return{error:Fi};const i=n.participants??[],{participants:a,mappedMatchUps:o}=pt({withMatchUps:!0,tournamentRecord:n,withEvents:!0});let s=0;return i.filter((t=>(t.participantRole===e||!t.participantRole)&&t.participantType&&r.includes(t.participantType))).forEach((e=>{const{removed:r}=nT({groupingParticipant:e,individualParticipantIds:t,tournamentRecord:n,mappedMatchUps:o,participants:a});r&&s++})),s?Ni:{error:Ro}}function aT(e){const t=(e?.entries??[]).filter(Boolean).reduce(((e,t)=>{const{entryStage:r,entryStatus:n}=t,i=`_${r||qp}${n||""}`;return e[i]||(e[i]=[]),e[i].push(t),e}),{}),r=e=>isNaN(e)?1/0:e;return Object.keys(t).map((e=>t[e].sort(((e,t)=>r(e.entryPosition)-r(t.entryPosition))).map(((e,t)=>({...e,entryPosition:t+1}))))).flat()}function oT({autoEntryPositions:e=!0,participantIds:t=[],entryStatuses:r,stage:n,event:i}){const a="removeEventEntries";if(!i?.eventId)return{error:Ua};if(!Array.isArray(t)||t.some((e=>!tu(e))))return pd({result:{error:Io},stack:a});const o=(i.drawDefinitions??[]).flatMap((e=>oy({drawDefinition:e}).assignedParticipantIds??[])),s=(r?.length&&i.entries?.filter((e=>e.entryStatus&&r.includes(e.entryStatus)))||[]).map(Rd).filter((e=>!o.includes(e))),c=(n&&i.entries?.filter((e=>e.entryStage&&e.entryStage===n))||[]).map(Rd).filter((e=>!o.includes(e)));if(t.length?t=t.filter((e=>(!r?.length||s.includes(e))&&(!n||c.includes(e)))):s.length&&c.length?t=Jd(s,c):s.length?t=s:c.length&&(t=c),t?.length&&o.some((e=>t.includes(e))))return pd({result:{error:Co},stack:a});if(!t?.length)return{...Ni,participantIdsRemoved:[]};const u=[];i.entries=(i.entries??[]).filter((e=>{const r=!t.includes(e?.participantId);return r||u.push(e.participantId),r})),e&&(i.entries=aT({entries:i.entries}));const{flightProfile:d}=bU({event:i});return d?.flights?.forEach((e=>{e.drawEntries=(e.drawEntries||[]).filter((e=>!t.includes(e.participantId)))})),i.drawDefinitions?.forEach((e=>{e.entries=(e.entries??[]).filter((e=>!t.includes(e.participantId)))})),{...Ni,participantIdsRemoved:u}}function sT(e){const{entryStatus:t=Ql,autoEntryPositions:r=!0,enforceGender:n=!0,participantIds:i=[],entryStageSequence:s,policyDefinitions:c,entryStage:u=qp,tournamentRecord:d,ignoreStageSpace:p,drawDefinition:l,roundTarget:m,extensions:f,extension:h,drawId:g,event:I}=e,U="addEventEntries";if(!I)return{error:Ua};if(!i?.length)return a({result:{error:No},stack:U});if(!I?.eventId)return{error:ya};const y=te({tournamentRecord:d,event:I}).appliedPolicies??{},v=c?.[Zu]??y?.[Zu]??qy[Zu],T=!1!==(n??v?.participants?.enforceGender),P=[],D=[];if(f&&(!Array.isArray(f)||!f.every((e=>Rr({extension:e}))))||h&&!Rr({extension:h}))return a({context:S({extension:h,extensions:f}),result:{error:ys},info:"Invalid extension(s)",stack:U});const w=!!d,b=[];let R;const N=d?.participants?.filter((e=>{if(!i.includes(e.participantId))return!1;const r=I.eventType===mf&&e.participantType===gm&&!Nr(t),n=I.eventType===hf&&e.participantType===Um;return!(!r||I.gender&&T&&![Vf,xf].includes(I.gender)&&I.gender!==e.person?.sex)||(!(!n||Nr(t))||(!(I.eventType!==hf||e.participantType!==gm||!Nr(t))||(r&&I.gender&&T&&![Vf,xf].includes(I.gender)&&I.gender!==e.person?.sex?(b.push({participantId:e.participantId,sex:e.person?.sex}),!1):I.eventType===ym&&(e.participantType===ym||Nr(t)&&e.participantType===gm))))})).map((e=>e.participantId))??[],M=i.filter((e=>!w||N.includes(e)));I.entries||(I.entries=[]);const A=I.entries.map((e=>e.participantId||e.participant?.participantId));if(M.forEach((e=>{if(!A.includes(e)){const r=S({participantId:e,entryStatus:t,entryStage:u,extensions:f});h&&o({element:r,extension:h}),m&&o({extension:{name:yi,value:m},element:r}),s&&(r.entryStageSequence=s),P.push(r.participantId),I.entries?.push(r)}})),g&&!Nr(u)){const e=br({participantIds:M,autoEntryPositions:r,entryStageSequence:s,ignoreStageSpace:p,drawDefinition:l,entryStatus:t,roundTarget:m,entryStage:u,extension:h,drawId:g,event:I});e.error&&(R=e.error)}if(I.eventType&&[Hf,Yf].includes(I.eventType)){const e=(I.entries||[]).map((e=>e.participantId)),t=(I.entries||[]).filter((e=>Nr(e.entryStatus))).map((e=>e.participantId)),r=(d?.participants??[]).filter((t=>e.includes(t.participantId)&&t.participantType&&[Um,ym].includes(t.participantType))).map((e=>e.individualParticipantIds)).flat(1/0),n=t.filter((e=>r.includes(e)));n.length&&(D.push(...n),oT({participantIds:n,autoEntryPositions:!1,event:I}))}if(M.length!==i.length)return a({context:{mismatchedGender:b,gender:I.gender},result:{error:Uo},stack:U});r&&(I.entries=aT({entries:I.entries||[]}));const E=P.length-D.length;return a({result:{...Ni,addedEntriesCount:E},stack:U,info:R})}function cT(e){if(!e?.tournamentRecord)return{error:Fi};if(!e?.participantIds?.length)return{error:No};const{addIndividualParticipantsToEvents:t,tournamentRecord:r,participantIds:n}=e,i=r.participants?.length||0;if(!i)return{...Ni};const a=(r.events||[])?.filter((({eventType:e})=>e===zf)).map((e=>e?.drawDefinitions?.map((({drawId:e})=>e)))).flat(1/0),o=OS({participantFilters:{participantIds:n},tournamentRecord:r,withDraws:!0}).participants??[],s=a?.length&&Jd((yS({matchUpFilters:{drawIds:a,matchUpTypes:[hf]},tournamentRecord:r}).matchUps??[]).map((({sides:e})=>e?.map((({participantId:e})=>e)))).flat().filter(Boolean),n),c=o.filter((e=>e.draws?.filter((e=>(!a?.length||!a?.includes(e.drawId))&&e.positionAssignments)).length));if(s?.length||c.length)return{error:Co};const u={},d={};for(const e of r.events||[]){const t=oT({participantIds:n,event:e});if(t.error)return t;u[e.eventId]=t.participantIdsRemoved}r.participants=r.participants.filter((e=>{const r=n.includes(e.participantId)||e.participantType===Um&&e.individualParticipantIds.some((e=>n.includes(e)));if(!r&&e.participantType===zf&&e.individualParticipantIds.some((e=>n.includes(e)))&&(e.individualParticipantIds=e.individualParticipantIds.filter((e=>!n.includes(e)))),r&&t&&[Um,ym].includes(e.participantType))for(const t of e.individualParticipantIds||[])n.includes(t)||(d[e.participantId]||(d[e.participantId]=[]),d[e.participantId].push(t));return!r}));const p=i-r.participants.length;if(iT({individualParticipantIds:n,tournamentRecord:r}),t)for(const e of r.events||[]){sT({participantIds:u[e.eventId].map((e=>d[e]||[])).flat(),entryStatus:rm,tournamentRecord:r,event:e})}return p&&rc({payload:{participantIds:n,tournamentId:r.tournamentId},topic:fp}),p?{...Ni,participantsRemovedCount:p}:{error:fo}}function uT({removeGroupParticipant:e,tournamentRecord:t,drawDefinition:r,participantId:n,drawId:i,stage:a,event:o}){const s="destroyGroupEntry";if(!t)return{error:Fi};if(!n)return pd({result:{error:Do},stack:s});if(!o)return{error:Ua};if(!o.eventType||![Hf,Yf].includes(o.eventType))return pd({result:{error:Ia},stack:s});const c=t.participants??[],u=c.find((e=>e.participantId===n));if(!u)return pd({result:{error:wo},stack:s});if(!u.participantType||![Um,hm].includes(u.participantType)||u.participantType===hm&&o.eventType!==Yf||u.participantType===Um&&o.eventType!==Hf)return{error:So};const d=(o.entries??[]).find((e=>e.participantId===n));if(!d)return{error:_o};const{stageEntries:p}=RU({selected:!1,drawDefinition:r,drawId:i,event:o,stage:a}),l=p.map(Rd),m=c.filter((({participantId:e})=>l.includes(e))).map((({individualParticipantIds:e})=>e)).flat().filter(Boolean),f=u.individualParticipantIds?.filter((e=>1===Kd(e,m).length));let h,g=oT({participantIds:[n],event:o});if(g.error)return g;if(f?.length&&(g=sT({participantIds:f,entryStatus:rm,entryStage:d.entryStage,tournamentRecord:t,drawDefinition:r,drawId:i,event:o}),g.error))return g;if(e){cT({participantIds:[n],tournamentRecord:t}).success&&(h=!0)}return{...Ni,participantRemoved:h}}function dT({removeGroupParticipant:e,tournamentRecord:t,drawDefinition:r,participantId:n,drawId:i,event:a}){return uT({removeGroupParticipant:e,tournamentRecord:t,drawDefinition:r,participantId:n,drawId:i,event:a})}function pT(e){if(!e.tournamentRecord)return{error:Fi};const{participantIds:t,...r}=e;let n=0;const i=[];for(const e of t){const t=uT({participantId:e,...r});t.success&&(n+=1),t.error&&i.push(t.error)}return n?{destroyedCount:n,...Ni}:{error:i}}function lT({tournamentRecord:e,drawDefinition:t,participantId:r,entryPosition:n,skipRefresh:i,event:a}){if(!e)return{error:Fi};if(!r)return pd({result:{error:Do},stack:"setEntryPositions"});if(void 0!==n&&!Number.isSafeInteger(n))return{error:ys,entryPosition:n};(a?.entries||[]).forEach((e=>{e.participantId===r&&(e.entryPosition=n)})),(t?.entries||[]).forEach((e=>{e.participantId===r&&(e.entryPosition=n)}));const o=e=>{e.entries.forEach((e=>{e.entryPosition===n&&e.participantId!==r&&(e.entryPosition+=.1)}))};return i||(a?.entries&&(o(a),a.entries=aT({entries:a.entries})),t?.entries&&(o(t),t.entries=aT({entries:t.entries}))),{...Ni}}function mT({tournamentRecord:e,entryPositions:t,drawDefinition:r,event:n}){if(!e)return{error:Fi};if(!Array.isArray(t))return{error:ys};for(const i of t){const{participantId:t,entryPosition:a}=i,o=lT({skipRefresh:!0,tournamentRecord:e,drawDefinition:r,participantId:t,entryPosition:a,event:n});if(o.error)return o}return n?.entries&&(n.entries=aT({entries:n.entries})),r?.entries&&(r.entries=aT({entries:r.entries})),{...Ni}}function fT(e){const{participantId:t}=e;return t&&"string"!=typeof t?{error:ys,participantId:t}:hT({...e,participantIds:[t].filter(Boolean)})}function hT({tournamentRecord:e,drawDefinition:t,participantIds:r,stageSequence:n,stage:i=qp,eventId:a,event:o}){if(!e)return{error:Fi};if(!Array.isArray(r))return{error:ys,participantIds:r};if(!o)return{error:Ua};if(o){const e=gT({element:o,participantIds:r,stageSequence:n,stage:i});if(e.error)return e}if(t){const e=gT({element:t,participantIds:r,stageSequence:n,stage:i});if(e.error)return a?pd({context:{drawPromotionError:e.error,drawId:t.drawId},result:{...Ni},stack:"promoteAlternates"}):e}return{...Ni}}function gT({participantIds:e,stageSequence:t,element:r,stage:n}){const i=(r.entries||[]).filter((e=>e.entryStatus===zl)),a=(r.entries||[]).filter((t=>e.includes(t.participantId))),o=i.reduce(((e,t)=>{const{entryPosition:r}=t;return isNaN(r)&&e||(!e||r<e.entryPosition)&&t||e}),void 0),s=a.length?a:[o].filter(Boolean);if(!s?.length)return{error:_o};const c=s.filter((({entryStatus:e})=>e!==zl));if(c.length)return{error:ko,invalidEntryStatus:c};const u=s.filter((({entryStage:e})=>e&&e!==n));if(u.length)return{error:xo,invalidStage:u};const d=t&&s.filter((e=>e.stageSequence!==t));if(d?.length)return{error:Lo,invalidStageSequence:d};for(const e of s){e.entryStatus=Ql;const t=e?.entryPosition;isNaN(t)||r.entries.forEach((e=>{e.entryStatus===zl&&e.entryPosition>t&&(e.entryPosition=e.entryPosition-1)}));const n=Math.max(...r.entries.filter((e=>e.entryStatus===Ql&&!isNaN(e.entryPosition))).map((({entryPosition:e})=>Ed(e||0))),0);e.entryPosition=n||0}return{...Ni}}function IT({autoEntryPositions:e=!0,participantIds:t,drawDefinition:r,drawId:n,stages:i,event:a}){if(!a)return{error:Ua};if(!n)return{error:ra};if(!t?.length)return{error:No};if(Xd(oy({drawDefinition:r,stages:i}).assignedParticipantIds??[],t))return{error:Co};const o=e=>{const r=e.participantId;return!t.includes(r)},{flightProfile:s}=bU({event:a}),c=s?.flights?.find((e=>e.drawId===n));return c?.drawEntries&&(c.drawEntries=c.drawEntries.filter(o),e&&(c.drawEntries=aT({entries:c.drawEntries}))),r?.entries&&(r.entries=r.entries.filter(o),e&&(r.entries=aT({entries:r.entries}))),{...Ni}}function UT({autoEntryPositions:e=!0,ignoreAssignment:t,tournamentRecord:r,drawDefinition:n,participantIds:i,entryStatus:a,entryStage:o,extension:s,eventSync:c,drawId:u,stage:d,event:p}){if(!i||!Array.isArray(i))return{error:Io,method:"modifyEntriesStatus",participantIds:i};if(!n&&!p)return{error:Ua};if(a&&!dm.includes(a))return{error:ko};if(o&&!Yp.includes(o))return{error:wa};const l="modifyEntriesStatus",m=[];if(!a&&!s)return pd({result:{error:Za},info:"Missing entryStatus",stack:l});if(s&&!hd({extension:s,requiredAttributes:["name"]}))return pd({result:{error:ys},info:"Invalid extension",context:{extension:s},stack:l});const f=[];p?.drawDefinitions?.forEach((e=>{const t=oy({stages:d&&[d],drawDefinition:e}).assignedParticipantIds??[];f.push(...t)}));const h=r?.participants??[];if(!i.every((e=>{const t=dd({tournamentParticipants:h,participantId:e})?.participantType;return!(t&&[Um,hm].includes(t)&&VS(a)||a&&p?.eventType&&t===gm&&[Wf,Yf].includes(p.eventType)&&[zl,...om].includes(a))})))return{error:ko};const g=p&&bU({event:p}).flightProfile,I=g?.flights?.find((e=>e.drawId===u)),U=e=>{const r=(e||[]).filter((e=>!d||!e.entryStage||d===e.entryStage)).filter((({participantId:e})=>i.includes(e)));return r.every((e=>!((e=>a&&f.includes(e.participantId)&&!(om.includes(e.entryStatus)&&om.includes(a)))(e)&&!t)&&(a&&(e.entryStatus=a,delete e.entryPosition),o&&(e.entryStage=o,delete e.entryPosition),s&&(s.value?gd({element:e,extension:s}):fd({element:e,name:s.name})),!0)))?{...Ni}:{error:Co}},y=({flight:e,drawDefinition:t})=>{p&&(p.entries=aT({entries:p.entries??[]})),e&&(e.drawEntries=aT({entries:e.drawEntries})),t&&(t.entries=aT({entries:t.entries}))},S=e=>{const{flight:t,drawDefinition:r}=e,n="updateDrawEntries";if(t){const e=U(t.drawEntries);if(e.error)return pd({result:e,stack:n})}if(r){const e=U(r.entries);if(e.error)return pd({result:e,stack:n});m.includes(r.drawId)||m.push(r.drawId)}return{...Ni}},v=p?.entries?.find((({entryPosition:e})=>e))??(I?.drawEntries?.find((({entryPosition:e})=>e))||n?.entries?.find((({entryPosition:e})=>e)));if(e&&!v&&y({flight:I,drawDefinition:n}),I||n){const e=S({flight:I,drawDefinition:n});if(e.error)return pd({result:e,stack:l})}const T=p?.drawDefinitions?.map((({drawId:e})=>e))??[],P=g?.flights?.filter((e=>!T.includes(e.drawId)))||[];for(const e of P){const t=e&&S({flight:e});if(t?.error)return pd({result:t,stack:l})}const D=1===g?.flights?.length&&(p?.drawDefinitions?.length??0)<=g?.flights?.length;if(!I&&!n&&a&&sm.includes(a))return{error:Bo};if(!I&&!n||a===am||c&&D){const e=U(p?.entries);if(e?.error)return pd({result:e,stack:l});let t;if(a===am&&(g?.flights?.every((e=>{const r=U(e.drawEntries);return r.error?(t=r.error,!1):(e.drawEntries=e.drawEntries.filter((({participantId:e})=>!i.includes(e))),!0)})),p?.drawDefinitions?.every((e=>{const r=U(e.entries);return r.error?(t=r.error,!1):(e.entries=e.entries?.filter((({participantId:e})=>!i.includes(e))),!0)}))),t)return pd({result:{error:t},stack:l})}e&&y({flight:I,drawDefinition:n});for(const e of p?.drawDefinitions??[])m.length&&!m.includes(e.drawId)||jp({tournamentId:r.tournamentId,eventId:p?.eventId,drawDefinition:e});return{...Ni}}function yT({tournamentParticipants:e,tournamentRecord:t,participantIds:r}){const n="getPairedParticipant";if(!e&&!t)return{error:Fi};if(!Array.isArray(r)||r.length>2)return{error:Uo};if(!r.length)return pd({result:{error:No},stack:n});const i=(e=e??t?.participants??[]).filter((e=>e.participantType===Um&&Jd(r,e.individualParticipantIds).length===r.length&&e.individualParticipantIds.length===r.length)),a=i[0];if(!a)return pd({result:{error:wo},stack:n});const o=Jc(i.slice(1),!1,!0);return{participant:Jc(a),duplicatedPairParticipants:o,...Ni}}function ST(e){const t="addParticipant",{allowDuplicateParticipantIdPairs:r,returnParticipant:n,disableNotice:i,pairOverride:a,participant:o}=e,s=e.tournamentId?e.tournamentRecords?.[e.tournamentId]:e.tournamentRecord??(e.activeTournamentId&&e.tournamentRecords?.[e.activeTournamentId]);if(!s)return{error:Fi};if(!o)return pd({result:{error:To},stack:t});o.participantId||(o.participantId=bm()),s.participants||(s.participants=[]);const{participantId:c,individualParticipantIds:u}=o;if(s.participants.reduce(((e,t)=>t.participantId===c||e),!1))return{error:bo};const{participantType:d,participantRole:p}=o;if(!d||!Object.keys(Sm).includes(d))return{error:So,participantType:d};if(!p)return{error:vo};const l=s.participants||[],m=l.filter((e=>e.participantType===gm)).map((e=>e.participantId));if(d!==gm&&o.person)return{error:ys,person:o.person};if(u&&!Array.isArray(u))return{error:ys,individualParticipantIds:u};if(d===Um){if(o.person)return{error:ys,person:o.person};if(!o.individualParticipantIds)return pd({result:{error:No},stack:t});if(2!==o.individualParticipantIds.length&&!a)return pd({info:"PAIR must be 2 individualParticipantIds",result:{error:Uo},stack:t});{const e=l.filter((e=>e.participantType===gm)).map((e=>e.participantId));if(!Array.isArray(o.individualParticipantIds))return pd({result:{error:Uo},stack:t});if(!o.individualParticipantIds.reduce(((t,r)=>e.includes(r)&&t),!0))return pd({result:{error:Uo},stack:t})}const e=l.filter((e=>e.participantType===Um)).map((e=>({individualParticipantIds:e.individualParticipantIds,participant:e}))),i=o.participantType===Um&&e.find((e=>2===Jd(e.individualParticipantIds,o.individualParticipantIds).length));if(i&&!r)return{...Ni,existingParticipant:!0,participant:n&&Jc(i.participant)};if(!o.participantName){const e=l.filter((e=>o.individualParticipantIds?.includes(e.participantId)));let t=e.map((e=>e.person?.standardFamilyName)).filter(Boolean).join("/");1===e.length&&(t+="/Unknown"),o.participantName=t}}else if(d===gm){if(!o.person?.standardFamilyName||!o.person?.standardGivenName)return{error:Eo};if(!o.participantName){const e=`${o.person.standardFamilyName.toUpperCase()}, ${o.person.standardGivenName}`;o.participantName=e}}else{if(!d||![ym,Im].includes(d))return{error:So};if(u||(o.individualParticipantIds=[]),o.individualParticipantIds?.length)for(const e of o.individualParticipantIds){if("string"!=typeof e)return pd({result:{participantId:e,error:ys},stack:t});if(!m.includes(e))return pd({result:{participantId:e,error:wo},stack:t})}}s.participants.push(o),i||rc({payload:{tournamentId:s.tournamentId,participants:[o]},topic:dp});return Mf({participant:n&&Jc(o),...Ni})}function vT({allowDuplicateParticipantIdPairs:e,returnParticipants:t,tournamentRecord:r,participants:n=[]}){if(!r)return{error:Fi};r.participants||(r.participants=[]);const i=r.participants.map((e=>e.participantId))||[];n.forEach((e=>{e.participantId||(e.participantId=bm())}));const a=n.filter((e=>!i.includes(e.participantId))),o=n.filter((e=>i.includes(e.participantId))),s=a.filter((e=>e.participantType===gm)),c=a.filter((e=>e.participantType!==gm)),u=s.concat(...c),d=[];if(u.length){for(const t of u){const n=ST({allowDuplicateParticipantIdPairs:e,returnParticipant:!0,disableNotice:!0,tournamentRecord:r,participant:t});if(n.error)return n;n.success&&!n.existingParticipant&&d.push(n.participant)}d.length&&rc({topic:dp,payload:{tournamentId:r.tournamentId,participants:d}});const n={participants:t&&Jc(d),addedCount:d.length,...Ni};return o.length&&Object.assign(n,{notAdded:o,info:Oo}),Mf(n)}return{info:"No new participants to add",addedCount:0,...Ni}}function TT({allowDuplicateParticipantIdPairs:e,entryStage:t=qp,entryStatus:r=zl,participantIdPairs:n=[],tournamentRecord:i,drawDefinition:a,event:o,uuids:s}){if(!i)return{error:Fi};if(!o)return{error:Ua};if(o.eventType!==hf)return{error:Ia};const c=[],u=new Map;for(const e of i.participants??[]){const{participantType:t,participantId:r,person:n,individualParticipantIds:i}=e;t===gm&&n?.sex?u.set(r,n.sex):t===Um&&i&&c.push(i)}const d=n.filter((e=>{if(2!==e.length)return!0;if(!u.has(e[0])||!u.has(e[1]))return!0;if(!o.gender||o.gender===xf)return!1;const t=e.map((e=>u.get(e)));let r=o.gender===Lf&&(t[0]!==Lf||t[1]!==Lf)||o.gender===jf&&(t[0]!==jf||t[1]!==jf);return o.gender===Vf&&(t.sort(bS),t[0]===jf&&t[1]===Lf||(r=!0)),r}));if(d.length)return{error:Uo,invalidParticipantIdPairs:d};const p=n.map((e=>({participantId:s?.pop()??bm(),participantRole:Zv,individualParticipantIds:e,participantType:Um}))),l=e?p:p.filter((e=>!c.find((t=>2===Jd(t,e.individualParticipantIds).length))));let m,f=[];if(l){const t=vT({allowDuplicateParticipantIdPairs:e,participants:l,returnParticipants:!0,tournamentRecord:i});if(t.error)return t;f=t.participants||[],m=t.info}const h=sT({participantIds:n.map((e=>{const t=f.find((t=>2===Jd(t.individualParticipantIds,e).length));if(t)return t;const{participant:r}=yT({tournamentRecord:i,participantIds:e});return r})).map((e=>e.participantId)),tournamentRecord:i,drawDefinition:a,entryStatus:r,entryStage:t,event:o});l.length&&rc({payload:{participants:l},topic:dp});return{...h,info:m,newParticipantIds:l.map(Rd)}}function PT({entryStatus:e=Ql,unpairedParticipantIds:t=[],participantIdPairs:r=[],entryStage:n=qp,tournamentRecord:i,event:a}){if(!i)return{error:Fi};if(!a)return{error:Ua};const o=i.participants??[],s=o.filter((e=>e.participantType===gm)).map((e=>e.participantId)),c=t.concat(...r).flat(1/0).filter((e=>!s.includes(e)));if(c.length)return{error:Uo,invalidParticipantIds:c};const u=r.filter((e=>2!==e.length));if(u.length)return{error:Uo,invalidParticipantIdPairs:u};const d=o.filter((e=>e.participantType===Um)).map((e=>e.individualParticipantIds)),p=vT({participants:r.filter((e=>!d.find((t=>2===Jd(t,e).length)))).map((e=>({participantType:Um,participantRole:Zv,individualParticipantIds:e}))),tournamentRecord:i});if(p.error)return p;const l=r.map((e=>{const{participant:t}=yT({tournamentRecord:i,participantIds:e});return t})).map((t=>({participantId:t,entryStatus:e,entryStage:n}))),m=t.map((e=>({entryStatus:rm,participantId:e,entryStage:n})));return a.entries=(a.entries??[]).filter((e=>e.entryStage===n)),a.entries=a.entries.concat(...l,...m),{...Ni}}function DT({participantId:e,drawDefinition:t,entryStatus:r,entryStage:n}){if(!t)return{error:Li};const i=t.entries?.find((t=>!(t.participantId!==e||r&&r!==t.entryStatus||n&&n!==t.entryStage)));return e&&i}function wT({entryStatus:e=Ql,drawDefinition:t,stageSequence:r,stage:n}){if(e===zl)return function({stage:e,drawDefinition:t}){const{entryProfile:r}=rh({drawDefinition:t});return r[e]?.alternates||0}({stage:n,drawDefinition:t})?{positionsAvailable:1/0,...Ni}:{error:Vo};const i=function(e){const{provisionalPositioning:t,drawDefinition:r,stageSequence:n,stage:i}=e,a=Ug({stage:i,drawDefinition:r}),{qualifiersCount:o}=Ig({provisionalPositioning:t,drawDefinition:r,stageSequence:n,stage:i});return a&&a-o}({drawDefinition:t,stageSequence:r,stage:n}),a=function({stage:e,drawDefinition:t}){const{entryProfile:r}=rh({drawDefinition:t});return r[e]?.wildcardsCount||0}({drawDefinition:t,stage:n}),o=ih({entryStatus:im,drawDefinition:t,stage:n}),s=o+ih({entryStatus:Ql,drawDefinition:t,stage:n}),c=i-s;return n!==Hp&&s>=i?{error:jo}:e===im?o<a?{...Ni}:{error:jo}:{positionsAvailable:c,...Ni}}function bT(e){const{entryStatus:t=Ql,stage:r=qp,autoEntryPositions:n=!0,ignoreStageSpace:i,drawDefinition:a,participantIds:o,stageSequence:s,roundTarget:c,extension:u}=e;if(!r)return{error:Da};if(!a)return{error:Li};if(!Array.isArray(o))return{error:Uo};if(!function({stage:e,drawDefinition:t}){return Boolean(e===Hp||nh({stage:e,drawDefinition:t})&&Ug({stage:e,drawDefinition:t}))}({stage:r,drawDefinition:a}))return{error:wa};if(u&&!hd({extension:u}))return pd({result:{error:ys},info:"Invalid extension",context:{extension:u},stack:"addDrawEntries"});const d=wT({drawDefinition:a,stageSequence:s,entryStatus:t,stage:r});if(!i&&!d.success)return{error:d.error};const p=d.positionsAvailable??0;if(!i&&r!==Hp&&p<o.length)return{error:Fo};const l=o.reduce(((e,n)=>{const i=t===Zl&&DT({participantId:n,drawDefinition:a,entryStatus:t}),o=r===Hp&&DT({entryStage:r,drawDefinition:a,participantId:n});return t!==Zl&&r!==Hp&&DT({drawDefinition:a,participantId:n})||i||o?e.concat(n):e}),[]);return o.filter((e=>e&&!l.includes(e))).forEach((e=>{const n={entryStageSequence:s,entryStage:r,participantId:e,entryStatus:t};u&&gd({element:n,extension:u}),c&&gd({extension:{name:yi,value:c},element:n}),a.entries||(a.entries=[]),a.entries.push(n)})),n&&(a.entries=aT({entries:a.entries})),jp({drawDefinition:a}),l?.length?{info:"some participantIds could not be added",participantIdsNotAdded:l,...Ni}:{...Ni}}function RT({autoEntryPositions:e=!0,entryStageSequence:t,ignoreStageSpace:r,drawDefinition:n,participantIds:i,entryStatus:a,roundTarget:o,entryStage:s,extension:c,drawId:u,event:d}){if(!i?.length)return{error:No};if(!d)return{error:ya};if(!u)return{error:ra};const p=(d.entries||[]).map(Rd);if(i.filter((e=>!p.includes(e))).length)return{error:va};if(n){const u=bT({stageSequence:t,autoEntryPositions:e,stage:s,ignoreStageSpace:r,drawDefinition:n,participantIds:i,entryStatus:a,roundTarget:o,extension:c});if(u.error)return u}const{flightProfile:l}=bU({event:d}),m=l?.flights.find((e=>e.drawId===u));return m?.drawEntries&&(i.forEach((e=>{const t=a===Zl&&NT({participantId:e,entryStatus:a,flight:m}),r=s===Hp&&NT({participantId:e,entryStage:s,flight:m});a!==Zl&&s!==Hp&&NT({flight:m,participantId:e})||t||r||m.drawEntries.push({participantId:e,entryStatus:a,entryStage:s})})),e&&(m.drawEntries=aT({entries:m.drawEntries}))),{...Ni}}function NT({participantId:e,entryStatus:t,entryStage:r,flight:n}){const i=n.drawEntries?.find((n=>!(n.participantId!==e||t&&t!==n.entryStatus||r&&r!==n.entryStage)));return e&&i}var MT=Object.freeze({__proto__:null,addDrawEntries:RT,addEventEntries:sT,addEventEntryPairs:TT,destroyPairEntries:pT,destroyPairEntry:dT,modifyEntriesStatus:UT,modifyEventEntries:PT,promoteAlternate:fT,promoteAlternates:hT,removeDrawEntries:IT,removeEventEntries:oT,setEntryPosition:lT,setEntryPositions:mT});function AT(e){const{entries:t=[],entryStatus:r,stage:n}=e;return Math.max(...t.filter((e=>!(n&&n!==e.entryStage||r&&e.entryStatus!==r||isNaN(e.entryPosition)))).map((({entryPosition:e})=>Ed(e||0))),0)}var ET=Object.freeze({__proto__:null,getEntriesAndSeedsCount:MU,getMaxEntryPosition:AT}),CT=Object.freeze({__proto__:null,addDrawEntries:RT,addEventEntries:sT,addEventEntryPairs:TT,destroyPairEntries:pT,destroyPairEntry:dT,getEntriesAndSeedsCount:MU,getMaxEntryPosition:AT,modifyEntriesStatus:UT,modifyEventEntries:PT,mutate:MT,promoteAlternate:fT,promoteAlternates:hT,query:ET,removeDrawEntries:IT,removeEventEntries:oT,setEntryPosition:lT,setEntryPositions:mT});function OT({schedulingProfile:e,venueIds:t,eventIds:r,drawIds:n}){const i=[],a=e?.map((e=>{const a=Lc(e?.scheduleDate);if(!a)return void i.push(`Invalid date: ${e?.scheduledDate}`);const o=(e?.venues||[]).map((e=>{const{rounds:a,venueId:o}=e,s=t?.includes(o);if(!s)return void i.push(`Missing venueId: ${o}`);const c=a.filter((e=>{const t=r.includes(e.eventId)&&n.includes(e.drawId);return t||i.push(`Invalid eventId: ${e.eventId} or drawId: ${e.drawId}`),t}));return c.length?{venueId:o,rounds:c}:void 0})).filter(Boolean);return o.length&&a&&{...e,venues:o}})).filter(Boolean);return{updatedSchedulingProfile:a,modifications:i.length,issues:i}}function FT({tournamentRecords:e,schedulingProfile:t}){if(!t)return{valid:!0};if(!Array.isArray(t))return{valid:!1,error:ys};const{venueIds:r,tournamentsMap:n}=function(e){const t=e?.tournamentRecords&&Object.values(e?.tournamentRecords)||[],r={},{venueIds:n,eventIds:i,drawIds:a,structureIds:o,tournamentIds:s}=t.reduce(((e,t)=>{const{tournamentIds:n,tournamentMap:i,structureIds:a,venueIds:o,eventIds:s,drawIds:c}=function(e){const{tournamentRecord:t={},tournamentMap:r={},requireCourts:n}=e,i=[],a=[],o=[],s=[],c=(t?.venues||[]).map((({venueId:e,courts:t})=>(!n||t?.length)&&e)),u=t?.tournamentId;if(u){i.push(u),r[u]={};(t?.events||[]).forEach((e=>{const t=e.eventId;o.push(t),r[u][t]={},(e.drawDefinitions||[]).forEach((e=>{const n=e.drawId;s.push(n),r[u][t][n]={};const{structures:i}=Fm({drawDefinition:e});(i||[]).forEach((e=>{const i=e.structureId,{matchUps:o}=Kf({structure:e}),{roundMatchUps:s}=Cf({matchUps:o}),c=s&&Object.keys(s).map((e=>parseInt(e)));r[u][t][n][i]=c,a.push(i),e.structures?.length&&e.structures.forEach((e=>{a.push(e.structureId),r[u][t][n][e.structureId]=c}))}))}))}))}return{tournamentMap:r,tournamentIds:i,structureIds:a,venueIds:c,eventIds:o,drawIds:s}}({tournamentRecord:t});return o.forEach((t=>{e.venueIds.includes(t)||e.venueIds.push(t)})),e.tournamentIds.push(...n),e.structureIds.push(...a),e.eventIds.push(...s),e.drawIds.push(...c),Object.assign(r,i),e}),{tournamentIds:[],structureIds:[],venueIds:[],eventIds:[],drawIds:[]});return{tournamentsMap:r,tournamentIds:s,structureIds:o,venueIds:n,eventIds:i,drawIds:a}}({tournamentRecords:e});let i,a;const o=t.every((e=>{const{scheduleDate:t,venues:o}=e;return!!bc(t)&&o.every((e=>{const{venueId:t,rounds:o}=e;if("string"!=typeof t)return a="venueId should be a string",!1;if(!Array.isArray(o))return a="rounds should be an array",!1;if(!r.includes(t))return i=Ko,!1;return!!o.every((e=>{if(!e)return a="empty round",!1;const{roundSegment:t,tournamentId:r,structureId:i,roundNumber:o,eventId:s,drawId:c}=e,u=n?.[r]?.[s]?.[c]?.[i],d=u?.includes(o);d||(a="Invalid rounds");const{segmentNumber:p,segmentsCount:l}=t||{},m=!t||Vd(p)&&Cd(l)&&p<=l;return m||(a="Invalid segment"),d&&m}))}))}));return o||i||(i=ys),{valid:!!o,error:i,info:a}}function kT({convertExtensions:e,ignoreDisabled:t,venue:r,court:n}){const i={...Jc(n,e,!0),venueId:r.venueId},{extension:a}=Wl({name:oi,element:n});if(t&&a){const e=ru(a.value)?a.value?.dates:void 0,t=!0===a?.value?[]:i.dateAvailability.map((t=>{const r=t.date;if(r&&!e.includes(r))return t})).filter(Boolean);i.dateAvailability=t}return{inContextCourt:i}}function _T(e){const{convertExtensions:t,ignoreDisabled:r,venueIds:n=[],dates:i}=e,a=e.tournamentRecords||e.tournamentRecord&&{[e.tournamentRecord.tournamentId]:e.tournamentRecord}||{},o=[],c=[],u=[],d=[];return Object.keys(a).filter((t=>!e.tournamentId||t===e.tournamentId)).forEach((e=>{const p=a[e];for(const e of p.venues??[])if(!n.length||n.includes(e.venueId)){if(r){const{extension:t}=s({name:oi,element:e});if(t?.value)continue}o.includes(e.venueId)||(d.push(L(e,t,!0)),o.push(e.venueId));for(const n of e.courts??[])if(!c.includes(n.courtId)){if(r){const{extension:e}=s({name:oi,element:n});if(Mr({extension:e,dates:i}))continue}const{inContextCourt:a}=kT({convertExtensions:t,ignoreDisabled:r,venue:e,court:n});u.push(a),c.push(n.courtId)}}})),{courts:u,venues:d,...Ni}}function xT({tournamentRecords:e,requireCourts:t,dates:r}){if("object"!=typeof e||!Object.keys(e).length)return{error:Oi};return Object.keys(e).reduce(((n,i)=>{const a=e[i],{venues:o}=function({convertExtensions:e,tournamentRecord:t,ignoreDisabled:r,dates:n}){if(!t)return{error:Oi};const i=L(t.venues??[],e).filter((e=>{if(!r)return e;const{extension:t}=s({name:oi,element:e});return!t?.value&&e})).filter(Boolean),a=i.reduce(((t,i)=>{const a=(i?.courts||[]).filter((e=>{if(!r&&!n?.length)return e;const{extension:t}=s({name:oi,element:e});return Mr({extension:t,dates:n})})).filter(Boolean).map((t=>{const{inContextCourt:n}=kT({convertExtensions:e,ignoreDisabled:r,venue:i,court:t});return n}));return a.length?t.concat(a):t}),[]);return{venues:i,courts:a}}({tournamentRecord:a,dates:r});return o?.forEach((e=>{const{venueId:r,courts:i}=e;(!t||i?.length)&&!n.venueIds.includes(r)&&(n.venues.push(e),n.venueIds.push(r))})),n}),{venues:[],venueIds:[]})}function LT({tournamentRecords:e,tournamentRecord:t}){if("object"!=typeof e||!Object.keys(e).length)return{error:Oi};const{extension:r}=Wl({element:t,name:Ti,tournamentRecords:e,discover:!0});let n=r?.value||[];if(n.length){const{venueIds:r}=xT({requireCourts:!0,tournamentRecords:e}),{eventIds:i,drawIds:a}=py({tournamentRecords:e}),{updatedSchedulingProfile:o,modifications:s,issues:c}=OT({schedulingProfile:n,venueIds:r,eventIds:i,drawIds:a});if(s){n=o;const r=VT({tournamentRecords:e,tournamentRecord:t,schedulingProfile:n});return r.error?r:{schedulingProfile:n,modifications:s,issues:c}}}return{schedulingProfile:n,modifications:0}}function VT({tournamentRecords:e,tournamentRecord:t,schedulingProfile:r}){const n=FT({tournamentRecords:e,schedulingProfile:r});if(n.error)return n;if(!r)return fd({element:t,name:Ti,tournamentRecords:e,discover:!0});return gd({tournamentRecords:e,discover:!0,extension:{name:Ti,value:r}})}function BT(e){const{tournamentRecord:t}=e,r=e.tournamentRecords||t&&{[t.tournamentId]:t}||{};if(!e.schedulingProfile){const{modifications:e,issues:n}=LT({tournamentRecords:r,tournamentRecord:t});return{success:!e,modifications:e,issues:n}}const{venueIds:n}=xT({tournamentRecords:r}),{eventIds:i,drawIds:a}=py({tournamentRecords:r}),{updatedSchedulingProfile:o,modifications:s,issues:c}=OT({schedulingProfile:e.schedulingProfile,venueIds:n,eventIds:i,drawIds:a});return s?{...VT({schedulingProfile:o,tournamentRecords:r}),modifications:s,issues:c}:{...Ni,modifications:s,issues:c}}function jT({event:e,status:t=AI}){const r=`${MI}.${EI}`;return ag({itemType:r,event:e})?.timeItem?.itemValue?.[t]}function GT({removePriorValues:e=!0,status:t=AI,statusObject:r,event:n}){if(!ru(r))return{error:ys};const i=jT({event:n,status:t}),a=`${MI}.${EI}`;return pg({timeItem:{itemValue:{[t]:{...i,...r}},itemType:a},removePriorValues:e,event:n})}function qT(e){const{includePositionAssignments:t,tournamentRecord:r,participantsProfile:n,policyDefinitions:i,usePublishState:a,status:o=AI,sortConfig:s,event:c}=e,u=L(r,!1,!0),d=L(c,!1,!0);if(!u)return{error:Fi};if(!d)return{error:Ua};const{eventId:p}=d,{tournamentId:m,endDate:f}=u,h=er({event:d,status:o}),{publishState:g}=Er({event:d}),{participants:I}=pt({withGroupings:!0,withEvents:!1,withDraws:!1,...n,tournamentRecord:u}),U=(d.drawDefinitions||[]).filter((({drawId:e})=>!a||(h.drawDetails?h.drawDetails[e]?.publishingDetail?.published:!h.drawIds||h.drawIds.includes(e)))).map((r=>(({drawInfo:e,structures:t})=>({...e,structures:t}))(Cr({allParticipantResults:e.allParticipantResults,context:{eventId:p,tournamentId:m,endDate:f},includePositionAssignments:t,tournamentParticipants:I,noDeepCopy:!0,policyDefinitions:i,tournamentRecord:u,usePublishState:a,drawDefinition:r,publishStatus:h,sortConfig:s,event:d})))).map((({structures:e,...t})=>{const r=e?.filter((({stage:e,structureId:r})=>(({structureId:e,drawId:t})=>{if(!a)return!0;const r=h?.drawDetails?.[t]?.structureDetails;return!r||!Object.keys(r).length||r[e]?.published})({structureId:r,drawId:t.drawId})&&(({stage:e,drawId:t})=>{if(!a)return!0;const r=h?.drawDetails?.[t]?.stageDetails;return!r||!Object.keys(r).length||r[e]?.published})({stage:e,drawId:t.drawId}))).map((e=>(({drawId:e,structure:t})=>{if(!a)return t;const r=h?.drawDetails?.[e]?.structureDetails?.[t.structureId]?.roundLimit;if(Fe(r)){const e=l(1,r+1),n={},i={};for(const r of e)t.roundMatchUps[r]&&(n[r]=t.roundMatchUps[r],i[r]=t.roundProfile[r]);t.roundMatchUps=n,t.roundProfile=i}return t})({drawId:t.drawId,structure:e})));return{...t,structures:r}})).filter((e=>e.structures?.length)),{tournamentInfo:y}=Ar({tournamentRecord:u}),S={tournamentInfo:y,venuesData:(u.venues||[]).map((e=>(({venueData:e})=>({...e}))(Or({tournamentRecord:u,venueId:e.venueId})))),eventInfo:(({eventId:e,eventName:t,eventType:r,eventLevel:n,surfaceCategory:i,matchUpFormat:a,category:o,gender:s,startDate:c,endDate:u,ballType:d,discipline:p})=>({eventId:e,eventName:t,eventType:r,eventLevel:n,surfaceCategory:i,matchUpFormat:a,category:o,gender:s,startDate:c,endDate:u,ballType:d,discipline:p}))(d),drawsData:U};return S.eventInfo.publishState=g,S.eventInfo.publish=h,{...Ni,eventData:S}}function $T(e){const{includePositionAssignments:t,removePriorValues:r,tournamentRecord:n,status:i=AI,event:a,drawIdsToRemove:o,drawIdsToAdd:s}=e;if(!n)return{error:Fi};if(!a)return{error:Ua};const{appliedPolicies:c}=Oh({tournamentRecord:n,event:a}),u={...c,...e.policyDefinitions},d=a.drawDefinitions?.map((({drawId:e})=>e))??[],p=e.drawDetails?Object.keys(e.drawDetails):[],l=p.length?[]:e.drawIds,m=(s??[]).concat(...o??[],...l??[],...p),f=m.filter((e=>!d.includes(e)));if(f.length)return pd({result:{error:Bi},context:{invalidDrawIds:f}});const h=jT({event:a,status:i}),g=Object.keys(h?.drawDetails||{}).filter((e=>d.includes(e))).reduce(((e,t)=>(e[t]=h.drawDetails[t],e)),{});for(const t of d)if(m.length&&!m.includes(t)||(o?.includes(t)||l?.length&&!l.includes(t)?g[t]={...g[t],publishingDetail:{published:!1}}:(s?.includes(t)||l?.includes(t)||!l?.length)&&(g[t]={...g[t],publishingDetail:{published:!0}})),e.drawDetails?.[t]){const r=e.drawDetails[t];let n=r.structureDetails??g[t].structureDetails;const i=r.stageDetails??g[t].stageDetails??{},{structureIdsToRemove:o=[],structureIdsToAdd:s=[],publishingDetail:c={},stagesToRemove:u=[],stagesToAdd:d=[]}=r;if((s||d)&&(c.published=!0),g[t]={publishingDetail:c,structureDetails:n,stageDetails:i},s.length||o.length){const e=(a.drawDefinitions?.find((e=>e.drawId===t))?.structures??[]).map((({structureId:e})=>e)),r=(s??[]).concat(o??[]).filter((t=>!e.includes(t)));if(r.length)return pd({result:{error:ma},context:{invalidStructureIds:r}});n=n??{};for(const t of e)o.includes(t)?n[t]={published:!1}:n[t]={published:!0};g[t].structureDetails=n}const p=(a.drawDefinitions?.find((e=>e.drawId===t))?.structures??[]).map((({stage:e})=>e));if(d.length){for(const e of d)i[e]={published:!0};for(const e of p)i[e]||(i[e]={published:!1})}if(d.length||u.length){for(const e of u)i[e]={published:!1};for(const e of p)i[e]||(i[e]={published:!0})}(d.length||u.length)&&(g[t].stageDetails=i)}GT({statusObject:{drawDetails:g},removePriorValues:r,status:i,event:a});const{eventData:I}=qT({includePositionAssignments:t,usePublishState:!0,tournamentRecord:n,policyDefinitions:u,event:a});return rc({payload:{eventData:I,tournamentId:n.tournamentId},topic:Np}),{...Ni,eventData:I}}const WT="deleteDrawDefinitions",HT="autoSchedulingAudit",zT="deleteEvents",YT={AUTO_SCHEDULING_AUDIT:HT,DELETE_EVENTS:zT,DELETE_DRAW_DEFINITIONS:WT};function QT(e){if(!e.tournamentRecord)return{error:Fi};const t="deleteDrawDefinitions";let r=e.drawIds??[],n=e.event;const{autoPublish:i=!0,tournamentRecord:a,auditData:o,eventId:s,force:c}=e,{appliedPolicies:u}=Oh({tournamentRecord:a,event:n}),d={...u,...e.policyDefinitions},p=Array.isArray(r)?r[0]:void 0;if(!n){const e=ly({tournamentRecord:a,eventId:s,drawId:p});if(e.error)return e;n=e.event}const l=[],m=[],f=[];if(!n?.drawDefinitions)return pd({info:"event has no drawDefinition",result:{...Ni},stack:t});const h=n.drawDefinitions.map((({drawId:e})=>e));if(r.length||(r=h),r=r.filter((e=>h.includes(e))),!r.length)return pd({info:"nothing to do; no matching drawIds in event.",result:{...Ni},stack:t});const g=Jc(bU({event:n}).flightProfile,!1,!0),I=({participantId:e,drawPosition:t,qualifier:r,bye:n})=>({bye:n,qualifier:r,drawPosition:t,participantId:e}),U=c??u?.[ad]?.allowDeletionWithScoresPresent?.drawDefinitions,y=jT({event:n})??{};let S,v=y.drawIds??(y.drawDetails&&Object.keys(y.drawDetails))??[];const T=[],P=n.drawDefinitions.filter((e=>{if(r.includes(e.drawId)){const t=zU({event:n,drawDefinition:e})?.matchUps??[];if(t.some((({score:e})=>hg({score:e})))&&!U)return T.push(e.drawId),!0;const{drawId:r,drawType:i,drawName:c}=e,u=g?.flights?.find((t=>t.drawId===e.drawId));u&&(u.drawEntries=u.drawEntries?.filter((e=>um.includes(e.entryStatus)))),v.includes(r)&&(v=v.filter((e=>e!==r)),S=!0);const d=Fm({stageSequence:1,drawDefinition:e,stage:qp})?.structures?.[0],p=d?_S({structureId:d.structureId,tournamentRecord:a,drawDefinition:e}):void 0,h=p?.positionAssignments?.map(I),y=Fm({stage:$p,drawDefinition:e})?.structures,P=y?.length?y.map((t=>{const r=t.stageSequence,n=_S({structureId:t.structureId,tournamentRecord:a,drawDefinition:e}),i=n?.positionAssignments.map(I);return{positionAssignments:i,stageSequence:r}})):void 0,D={action:WT,payload:{drawDefinitions:[e],eventId:s??n?.eventId,auditData:o}};f.push(D),l.push(Mf({tournamentId:a.tournamentId,eventId:s??n?.eventId,qualifyingPositionAssignments:P,positionAssignments:h,auditData:o,drawType:i,drawName:c,drawId:r})),t?.forEach((({matchUpId:e})=>m.push(e)))}return!r.includes(e.drawId)}));if(T.length&&!c)return pd({context:{drawIdsWithScoresPresent:T},result:{error:ks},stack:t});if(n.drawDefinitions=P,g){yd({event:n,extension:{name:pi,value:g}})}if(BT({tournamentRecord:a}),S){const e={};for(const t of v)e[t]=y.drawDetails?.[t]??{published:!0};const t=GT({statusObject:{drawDetails:e},event:n});if(t.error)return{error:t.error}}if(f.length&&rc({topic:mp,payload:f}),m.length&&Lp({tournamentId:a?.tournamentId,matchUpIds:m}),r.forEach((e=>{!function({tournamentId:e,eventId:t,drawId:r}){rc({payload:{drawId:r,tournamentId:e,eventId:t},topic:gp,key:r}),ac({key:r})}({drawId:e})})),function({event:e,deletedDrawsDetail:t,auditData:r}){const{extension:n}=Wl({name:ui,element:e}),i={...r,deletedDrawsDetail:t},a={name:ui,value:Array.isArray(n?.value)?n?.value.concat(i):[i]};gd({element:e,extension:a})}({event:n,deletedDrawsDetail:l,auditData:o}),i&&S){const e=$T({drawIdsToRemove:r,policyDefinitions:d,tournamentRecord:a,event:n});if(e.error)return{...Ni,info:e.error}}return{...Ni}}function KT({autoPublish:e=!0,tournamentRecord:t,auditData:r,event:n,force:i}){if(!t)return{error:Fi};if(!n)return{error:Ua};const{flightProfile:a}=bU({event:n});if(a){const o=a.flights?.map((({drawId:e})=>e)).filter(Boolean),s=QT({eventId:n.eventId,tournamentRecord:t,autoPublish:e,auditData:r,drawIds:o,event:n,force:i});return s.error?s:Pd({event:n,name:pi})}return{...Ni}}function JT(e){const t=y(e,[{[Uu]:!0},{[Gu]:e=>_r({matchUpFormat:e}),[qu]:Na,[Su]:!0}]);if(t.error)return t;const{tournamentRecord:r,matchUpFormat:n,event:i}=e,{extension:a}=s({name:vi,element:i}),o=a?.value,{extension:c}=s({element:r,name:vi}),u=c?.value,d=[o?.matchUpAverageTimes&&Fr({...o,matchUpFormat:n}),u?.matchUpAverageTimes&&Fr({...u,matchUpFormat:n})].find((e=>e));return{matchUpFormat:n,recoveryTimes:[o?.matchUpRecoveryTimes&&kr({...o,matchUpFormat:n}),u?.matchUpRecoveryTimes&&kr({...u,matchUpFormat:n})].find((e=>e)),averageTimes:d}}function ZT(e){const{matchUpFormat:t,recoveryTimes:r,averageTimes:n,tournamentId:i,eventId:a}=e,o=e?.tournamentRecords??(e?.tournamentRecord&&{[e.tournamentRecord.tournamentId]:e.tournamentRecord})??{};if(!Object.keys(o).length)return{error:Oi};const s=Object.keys(o).filter((e=>!i||i===e));if(i&&!s.includes(i))return{error:ys};let c;for(const e of s){const i=o[e],{event:s}=ly({tournamentRecord:i,eventId:a});a&&s&&(c=!0);const u=XT({tournamentRecord:i,event:s,matchUpFormat:t,averageTimes:n,recoveryTimes:r});if(u.error)return u}return!a||c?{...Ni}:{error:ya}}function XT({tournamentRecord:e,recoveryTimes:t,matchUpFormat:r,averageTimes:n,event:i}){if(!e)return{error:Fi};if(n&&!Array.isArray(n))return{error:ys};if(t&&!Array.isArray(t))return{error:ys};const a=vi;if(i){const{extension:e}=Wl({element:i,name:a});gd({element:i,extension:{name:a,value:eP({...e?.value||{},matchUpFormat:r,averageTimes:n,recoveryTimes:t})}})}else{const{extension:i}=Wl({element:e,name:a});gd({extension:{name:a,value:eP({...i?.value||{},matchUpFormat:r,averageTimes:n,recoveryTimes:t})},element:e})}return{...Ni}}function eP(e){const{matchUpRecoveryTimes:t=[],matchUpAverageTimes:r=[],matchUpFormat:n}=e;let{averageTimes:i,recoveryTimes:a}=e;i=(i||[]).filter((e=>e?.categoryNames?.length||e?.categoryTypes?.length));const o=i?.length&&r.map((e=>e?.matchUpFormatCodes.includes(n)?{...e,matchUpFormatCodes:e.matchUpFormatCodes?.filter((e=>e!==n))}:e)).filter((({matchUpFormatCodes:e})=>e?.length)).concat({matchUpFormatCodes:[n],averageTimes:i});a=(a||[]).filter((e=>e?.categoryNames?.length||e?.categoryTypes?.length));const s=a?.length&&t.map((e=>e?.matchUpFormatCodes.includes(n)?{...e,matchUpFormatCodes:e.matchUpFormatCodes?.filter((e=>e!==n))}:e)).filter((({matchUpFormatCodes:e,averageTimes:t})=>e?.length||t)).concat({matchUpFormatCodes:[n],recoveryTimes:a});return{matchUpAverageTimes:o?.length&&o||r,matchUpRecoveryTimes:s?.length&&s||t}}function tP(e){const{tournamentRecord:t,recoveryMinutes:r,averageMinutes:n,matchUpFormat:i,categoryType:a,eventId:o,event:s}=e;if(!t)return{error:Fi};if(!uv({matchUpFormat:i}))return{error:ys};if(!s)return{error:Ua};const{averageTimes:c=[],recoveryTimes:u=[]}=JT({tournamentRecord:t,matchUpFormat:i,event:s}),d=s.category,p=d?.categoryName||d?.ageCategoryCode||s?.eventId;let l={categoryNames:[p],minutes:{}};const m={categoryNames:[p],minutes:{}},f=e=>{if(e.categoryTypes?.includes(a)&&console.log("encountered:",{categoryType:a}),!e.categoryNames?.includes(p)||(e.categoryNames=e.categoryNames.filter((e=>e!==p)),l={minutes:e.minutes,categoryNames:[p]},e.categoryNames.length))return e},h=n&&!isNaN(Ed(n)),g=r&&!isNaN(Ed(r)),I=c.map(f).filter((e=>e?.categoryNames?.length)),U=u.map(f).filter((e=>e?.categoryNames?.length));return h&&(Object.assign(l.minutes,{[s?.eventType||mf]:n}),I.push(l)),g&&(Object.assign(m.minutes,{[s?.eventType||mf]:r}),U.push(m)),h||g?ZT({averageTimes:h&&I,recoveryTimes:g&&U,tournamentRecord:t,matchUpFormat:i,eventId:o,event:s}):{error:ys}}function rP(e){if(e.event)return nP({event:e.event});{e.tournamentRecord&&!e.tournamentRecords&&(e.tournamentRecords={[e.tournamentRecord.tournamentId]:e.tournamentRecord});const t=uy(e,[{[gu]:!0,[Fu]:!0}]);if(t.error)return t;const{tournamentRecords:r,eventId:n}=e;for(const e of Object.values(r??{})){const{event:t}=ly({tournamentRecord:e,eventId:n});if(t)return nP({event:t})}}return{error:ya}}function nP({event:e}){return Pd({event:e,name:vi})}function iP({tournamentRecord:e,event:t,startDate:r}){if(!e)return{error:Fi};if(!t)return{error:Ua};if(!xr.test(r))return{error:io};const n=sP(e);if(n.error)return n;const{tournamentStartDate:i,tournamentEndDate:a}=n,o=new Date(Vr(r)).getTime();if(!i||!a||o<i||o>a)return{error:io};const s=t.endDate&&new Date(Vr(t.endDate)).getTime();return s&&o>s&&(t.endDate=r),t.startDate=r,{...Ni}}function aP({tournamentRecord:e,event:t,endDate:r}){if(!e)return{error:Fi};if(!t)return{error:Ua};if(!xr.test(r))return{error:io};const n=sP(e);if(n.error)return n;const{tournamentStartDate:i,tournamentEndDate:a}=n,o=new Date(Vr(r)).getTime();if(!i||!a||o<i||o>a)return{error:io};const s=t.startDate&&new Date(Vr(t.startDate)).getTime();return s&&o<s&&(t.startDate=r),t.endDate=r,{...Ni}}function oP({tournamentRecord:e,event:t,startDate:r,endDate:n}){if(!e)return{error:Fi};if(!t)return{error:Ua};if(!r&&!n)return{error:Za,info:"missing date"};if(r&&!xr.test(r))return{error:io};if(n&&!xr.test(n))return{error:io};if(r&&n){if(new Date(Vr(r)).getTime()>new Date(Vr(n)).getTime())return{error:ys}}if(r){const n=iP({tournamentRecord:e,event:t,startDate:r});if(n.error)return n}if(n){const r=aP({tournamentRecord:e,event:t,endDate:n});if(r.error)return r}return{...Ni}}function sP(e){const{startDate:t,endDate:r}=e;return xr.test(t)&&xr.test(r)?{tournamentStartDate:new Date(Vr(t)).getTime(),tournamentEndDate:new Date(Vr(r)).getTime()}:a({result:{error:oo},context:{startDate:t,endDate:r}})}function cP({event:e,orderedDrawIdsMap:t}){if("object"!=typeof e)return{error:Ua};if(!t)return{error:Za,info:"Missing drawIdsOrderMap"};if("object"!=typeof t)return{error:ys,info:"orderedDrawIdsMap must be an object"};const r=Object.values(t);if(!r.every((e=>!isNaN(e))))return{error:ys,info:"drawOrder must be numeric"};if(jd(r).length!==r.length)return{error:ys,info:"drawOrder values must be unique"};if(e.drawDefinitions?.length){const r=(e.drawDefinitions||[]).map((({drawId:e})=>e)),n=Object.keys(t);if(n?.length&&Jd(r,n).length!==r.length)return{error:ys,info:"Missing drawIds"};e.drawDefinitions.forEach((e=>{e.drawOrder=t[e.drawId]}))}const{flightProfile:n}=bU({event:e});return n?.flights?.forEach((e=>{e.flightNumber=t[e.drawId]})),{...Ni}}function uP({tournamentRecord:e,event:t}){if(!e)return{error:Fi};if(!t)return{error:Ua};const{flightProfile:r}=bU({event:t}),n=r?.flights&&Object.assign({},...r.flights.sort(((e,t)=>e.flightNumber-t.flightNumber)).map(((e,t)=>({[e.drawId]:t+1}))))||t.drawDefinitions?.length&&Object.assign({},...t.drawDefinitions.sort(((e,t)=>e.drawOrder-t.drawOrder)).map(((e,t)=>({[e.drawId]:t+1}))))||void 0;return n?cP({event:t,orderedDrawIdsMap:n}):{...Ni}}function dP({autoPublish:e=!0,tournamentRecord:t,auditData:r,drawId:n,event:i,force:a}){if(!t)return{error:Fi};if(!n)return{error:ra};if(!i)return{error:Ua};const{flightProfile:o}=bU({event:i});if(o){const e=o.flights?.find((e=>e.drawId===n));if(e){const e=o.flights.filter((e=>e.drawId!==n));yd({event:i,extension:{name:pi,value:{...o,flights:e}}})}}const s=i.drawDefinitions?.find((e=>e.drawId===n));if(s){const o=QT({drawIds:[n],eventId:i.eventId,tournamentRecord:t,autoPublish:e,auditData:r,event:i,force:a});if(o.error)return o}return uP({tournamentRecord:t,event:i})}function pP({replacementIndividualParticipantId:e,existingIndividualParticipantId:t,tournamentRecord:r,drawDefinition:n,participantId:i,event:a,uuids:o}){if(!a)return{error:Ua};if(a?.eventType!==Wf)return{error:Ia};if(o&&!Array.isArray(o))return{error:ys};if(!r)return{error:Fi};if(![e,t,i].every((e=>"string"==typeof e)))return{error:Do};if(!(a?.entries?.filter((({entryStatus:e})=>[rm,nm].includes(e))).map((({participantId:e})=>e))||[]).includes(e))return{error:Io};const s=(r.participants||[]).find((e=>e.participantId===i));if(s?.participantType!==Um)return{error:go,participant:s};const c=s.individualParticipantIds,u=[e,...c.filter((e=>e!==t))],{participant:d}=yT({participantIds:u,tournamentRecord:r});let p;if(d)p=d.participantId;else{const e=ST({participant:{participantId:o?.pop(),participantRole:Zv,individualParticipantIds:u,participantType:Um},returnParticipant:!0,tournamentRecord:r});if(e.error)return e;p=e.participant.participantId}const{flightProfile:l}=bU({event:a});if(n){const e=l?.flights?.find((({drawId:e})=>e===n.drawId));e&&(e.drawEntries=e.drawEntries.map((e=>e.participantId===i?{...e,participantId:p}:e))),n.entries=n.entries.map((e=>e.participantId===i?{...e,participantId:p}:e));for(const e of n.structures||[])if(e.positionAssignments)e.positionAssignments=e.positionAssignments.map((e=>e.participantId===i?{...e,participantId:p}:e));else if(e.structures)for(const t of e.structures)t.positionAssignments=t.positionAssignments.map((e=>e.participantId===i?{...e,participantId:p}:e))}a.entries=a.entries.map((r=>r.participantId===i&&{...r,participantId:p}||r.participantId===e&&{...r,participantId:t}||r));const m=r.events.some((({entries:e,eventId:t,drawDefinitions:r})=>a.eventId===t?r.some((({drawId:e,entries:t})=>e!==n?.drawId&&t?.find((e=>e.participantId===i)))):e?.find((e=>e.participantId===i))));if(!m){const e=cT({addIndividualParticipantsToEvents:!1,participantIds:[i],tournamentRecord:r});if(e.error)return e}return{...Ni,participantOtherEntries:m,newPairParticipantId:p}}function lP(e){const{flight:t,suppressNotifications:n,modifyEventEntries:i,existingDrawCount:o,allowReplacement:s,checkEntryStatus:c,tournamentRecord:u,drawDefinition:d,event:p}=e;if(!d)return{error:Li};if(!p)return{error:Ua};p.drawDefinitions||(p.drawDefinitions=[]);const{drawId:l,drawName:m,entries:f}=d,{entries:h}=p;let g=0;if(void 0!==o&&o!==p.drawDefinitions.length)return{error:ys,info:"drawDefintions count mismatch"};const{flightProfile:I}=Ot({event:p}),U=t&&I?.flights?.find((e=>e.flightNumber===t.flightNumber)),y=I?.links?.find((e=>e?.target?.drawId===l))?.source?.drawId;if(y&&!p.drawDefinitions.find((e=>e.drawId===y)))return a({result:{error:Li},info:{sourceDrawId:y}});if(U&&U.drawId!==d.drawId)return a({result:{error:xi},info:{relevantFlight:U}});const S=f?.every((({participantId:e,entryStatus:t})=>{const r=U?.drawEntries.find((t=>t.participantId===e));return!t||r?.entryStatus===t})),v=!c||h&&f?.every((({participantId:e,entryStatus:t,entryStage:r})=>{const n=h.find((t=>t.participantId===e&&(!t.entryStage||t.entryStage===r)));return n?.entryStatus===t}));if(U&&!S)return a({result:{error:xi},context:{drawEntriesPresentInFlight:S,matchingEventEntries:v,relevantFlight:U},info:"Draw entries are not present in flight or do not match entryStatuses"});if(i&&f?.filter(Boolean).forEach((e=>{if(e?.entryStatus&&um.includes(e?.entryStatus)){const t=h?.filter(Boolean).find((t=>t.participantId===e.participantId));t&&e.entryStatus&&t?.entryStatus!==e.entryStatus&&(t.entryStatus=e.entryStatus,g+=1)}})),h&&!v)return a({result:{info:"Draw entries do not match event entryStatuses",context:{matchingEventEntries:v,eventEntries:h},error:xi}});const P=I?.flights?.map((({flightNumber:e})=>!isNaN(e)&&ve(e)))?.filter(Boolean)||[],D=p.drawDefinitions.map((({drawOrder:e})=>e&&ve(e)))?.filter(Boolean)||[];let w=Math.max(0,...D,...P)+1;const b=I?.flights?.find((e=>e.drawId===l));let R;if(b){b.drawName=d.drawName,R={name:pi,value:{...I,flights:I.flights}};const e=b.flightNumber;e&&!D.includes(e)?w=e:b.flightNumber=w}else{const e=I?.flights||[];e.push({manuallyAdded:!0,flightNumber:w,drawEntries:f,drawName:m,drawId:l}),R={name:pi,value:{...I||{},flights:e}}}r({event:p,extension:R}),Object.assign(d,{drawOrder:w});const N=p.drawDefinitions.find((e=>e.drawId===l)),M=u?.tournamentId,A=p.eventId;if(N){if(!s)return{error:na};const e=Dr({drawDefinition:N})?.matchUps,t=e?.map(T)??[],r=Dr({drawDefinition:d})?.matchUps;if(!n){t?.length&&H({matchUpIds:t,action:"modifyDrawDefinition",tournamentId:M,eventId:A}),r?.length&&W({matchUps:r,tournamentId:M,eventId:A}),p.drawDefinitions=p.drawDefinitions.map((e=>e.drawId===l?d:e));const e=d.structures?.map((({structureId:e})=>e));$({drawDefinition:d,tournamentId:M,structureIds:e,eventId:A})}}else if(p.drawDefinitions.push(d),!n){const{matchUps:e}=Dr({drawDefinition:d,event:p});e&&W({tournamentId:u?.tournamentId,matchUps:e}),z({drawDefinition:d,tournamentId:M,eventId:A})}return{...Ni,modifiedEventEntryStatusCount:g}}function mP(e){const{provisionalPositioning:t,useExistingSeedLimit:r,tournamentRecord:n,drawDefinition:i,seedingProfile:a,structureId:o,assignments:s,drawId:c,event:u}=e;let d=0;if(!s?.length)return{error:Pa};if(!n)return{error:Fi};if(!c)return{error:ra};const p=Y({provisionalPositioning:t,drawDefinition:i,structureId:o});if(p.error)return p;const{seedAssignments:l,seedLimit:m}=p,f=Object.assign({},...(l??[]).filter((e=>e.seedNumber)).map((e=>({[e.seedNumber]:e}))));s.forEach((e=>{const{seedNumber:t}=e;m&&t<=m&&(!r||f[t])&&(f[t]=e)}));const h=Object.values(f),g=h.map((e=>e?.participantId)).filter(Boolean);if(g.length!==I(g).length)return{error:ia};for(const e of h){const r=Z({...e,provisionalPositioning:t,tournamentRecord:n,drawDefinition:i,seedingProfile:a,structureId:o,event:u});if(r?.error)return r;r?.success&&d++}return d?{...Ni,modifications:d}:{error:ps}}function fP({deleteExisting:e,event:t,flightProfile:r}){const n="attachFlightProfile";if(!r)return pd({result:{error:Za},stack:n});if(!t)return pd({result:{error:Ua},stack:n});const{flightProfile:i}=bU({event:t});if(i&&!e)return pd({result:{error:Ns},stack:n});if(t.drawDefinitions?.length)return pd({result:{error:Vi},stack:n});return yd({event:t,extension:{name:pi,value:r}}),{flightProfile:Jc(r,!1,!0),...Ni}}function hP({tournamentRecord:e,scaleAttributes:t,drawDefinition:r,entryStatuses:n,drawId:i,event:a,stage:o}){if(!a)return{error:Ua};if(n&&!Array.isArray(n))return pd({result:{error:ys},info:SU("entryStatus"),stack:"removeScaleValues"});let s=a.entries;if(i){const{flightProfile:e}=bU({event:a}),t=e?.flights?.find((e=>e.drawId===i));s=t?t.drawEntries:r?.entries}return function({tournamentRecord:e,scaleAttributes:t,participantIds:r}){if(!e)return{error:Fi};if(!r)return{error:No};if(!t)return{error:Za,info:"scaleAttributes required"};const{scaleType:n,eventType:i,scaleName:a}=t,o=[wI,n,i,a].join(".");return e.participants?.forEach((e=>{r.includes(e.participantId)&&e.timeItems&&(e.timeItems=e.timeItems.filter((e=>e&&e?.itemType!==o)))})),{...Ni}}({tournamentRecord:e,scaleAttributes:t,participantIds:(s||[]).filter((e=>(!o||!e.entryStage||e.entryStage===o)&&(!n||n.includes(e.entryStatus)))).map(Rd)})}function gP({removePriorValues:e,tournamentRecord:t,displaySettings:r,status:n=AI,event:i}){if(!t)return a({result:{error:Fi}});if(!i)return a({result:{error:Ua}});if(!mt(r))return a({result:{error:Za}});if(mt(r.draws))for(const e of Object.keys(r.draws)){const t=r.draws[e].scheduleDetails??[];if(t.length){const n=[];for(const e of t){const t=n.find((t=>It(t.attributes,e.attributes)));t?.dates&&e.dates?t.dates.push(...e.dates):n.push(e)}r.draws[e].scheduleDetails=n}}const o=GT({statusObject:{displaySettings:r},removePriorValues:e,status:n,event:i});return o.error?o:{...Ni}}function IP({tournamentRecord:e,drawDefinition:t,entryStatuses:r,scaleName:n,drawId:i,event:a,stage:o}){if(!e)return{error:Fi};if(!a)return{error:Ua};n=n||a.category?.categoryName||a.category?.ageCategoryCode;return hP({tournamentRecord:e,scaleAttributes:{eventType:a.eventType,scaleType:fu,scaleName:n},drawDefinition:t,entryStatuses:r,drawId:i,event:a,stage:o})}function UP({removePairParticipants:e,tournamentRecord:t,eventIds:r}){if(!t)return{error:Fi};if(!t.events)return{error:ya};if(!Array.isArray(r))return{error:Za,info:SU("drawIds")};const n=[],i=[],a=[],o=[];if(t.events=(t.events||[]).filter((e=>{if(r.includes(e.eventId)){const r={action:zT,payload:{events:[e]}};n.push(r),i.push({tournamentId:t.tournamentId,eventName:e.eventName,eventType:e.eventType,category:e.category,eventId:e.eventId,gender:e.gender})}const s=e.eventType===Wf?(e.entries||[]).map((({entryStatus:e,participantId:t})=>e!==rm&&t)).filter(Boolean):[],c=r.includes(e.eventId);return c?o.push(...s):a.push(...s),!c})),e){const e=o.filter((e=>!a.includes(e)));t.participants=t.participants.filter((({participantId:t})=>!e.includes(t)))}if(BT({tournamentRecord:t}),n.length){rc({topic:mp,payload:n});dg({tournamentRecord:t,timeItem:{itemType:zT,itemValue:i}})}return{...Ni}}function yP({tournamentRecord:e,eventUpdates:t,eventId:r,event:n}){const i="modifyEvent";if(!e)return a({result:{error:Fi},stack:i});if(!gt(r))return a({result:{error:Ua},context:{eventId:r},stack:i});if(!mt(t))return a({result:{error:ys},context:{eventUpdates:t},stack:i});const o=n?.entries?.filter((({entryStatus:e})=>{const t=e;return[...um,zl].includes(t)})).map((({participantId:e})=>e))??[],s=o?pt({participantFilters:{participantIds:o},withIndividualParticipants:!0,tournamentRecord:e}).participants??[]:[],c=[],d=s.reduce(((e,t)=>{const r=t.person?.sex?[t.person.sex]:t.individualParticpants?.map((e=>e.person?.sex))||[];return c.push(...r),e.includes(t.participantType)?e:e.concat(t.participantType)}),[]),p=u(c),l=!p.length||[Vf,xf].includes(t.gender??"")||1===p.length&&p[0]===t.gender;if(t.gender&&!l)return a({context:{gender:t.gender,validGender:l},result:{error:ys},stack:i});const m=(d.includes(zf)&&[zf]||d.includes(gm)&&[qf]||d.includes(Um)&&[Wf]||[Wf,qf,zf]).includes(t.eventType??"");return t.eventType&&!m?a({context:{participantType:t.eventType,validEventType:m},result:{error:ys},stack:i}):(t.eventType&&(n.eventType=t.eventType),t.eventName&&(n.eventName=t.eventName),t.gender&&(n.gender=t.gender),{...Ni})}function SP({qualifyingPositions:e,drawEntries:t=[],drawName:r,drawId:n,event:i,stage:a}){const o="addFlight";if(!i)return pd({result:{error:Ua},stack:o});if(!r)return pd({result:{error:Za},stack:o});if(t?.length){const e=(i.entries??[]).map(Rd),r=t.map(Rd);if(Jd(r,e).length!==r.length)return pd({result:{error:ys},stack:o})}const s=bU({event:i})?.flightProfile,c=s?.flights?.map((({flightNumber:e})=>!isNaN(e)&&Ed(e)))?.filter(Boolean)||[],u=Math.max(0,...c)+1,d={drawId:n||bm(),flightNumber:u,drawEntries:t,drawName:r};a&&(d.stage=a),e&&(d.qualifyingPositions=e);if((s?.flights||[]).find((({drawId:e})=>e===d.drawId)))return pd({result:{error:Rs},stack:o});const p=(s?.flights||[]).concat(d);return yd({event:i,extension:{name:pi,value:{...s||{},flights:p}}})}var vP={collectionDefinitions:[{collectionName:"Male Singles",matchUpFormat:"SET3-S:6/TB7",matchUpType:"SINGLES",matchUpCount:4,matchUpValue:1,gender:"MALE"},{collectionName:"Female Singles",matchUpFormat:"SET3-S:6/TB7",matchUpType:"SINGLES",gender:"FEMALE",matchUpCount:4,matchUpValue:1},{collectionName:"Male Doubles",matchUpFormat:"SET1-S:8/TB7@7",matchUpType:"DOUBLES",matchUpCount:2,matchUpValue:1,gender:"MALE"},{collectionName:"Female Doubles",matchUpFormat:"SET1-S:8/TB7@7",matchUpType:"DOUBLES",gender:"FEMALE",matchUpCount:2,matchUpValue:1},{collectionName:"Mixed Doubles",matchUpFormat:"SET1-S:8/TB7@7",matchUpType:"DOUBLES",matchUpCount:4,matchUpValue:1,gender:"MIXED"}],tieFormatName:"USTA_GOLD_TEAM_CHALLENGE",winCriteria:{valueGoal:9}},TP={collectionDefinitions:[{collectionName:"Round 1",matchUpCount:3,matchUpFormat:"SET1-S:T20",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Round 2",matchUpCount:3,matchUpFormat:"SET1-S:T20",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Round 3",matchUpCount:3,matchUpFormat:"SET1-S:T20",matchUpType:"DOUBLES",scoreValue:1}],tieFormatName:"Doubles Shuffle",unrestrictedSelections:!0,winCriteria:{aggregateValue:!0}},PP={collectionDefinitions:[{collectionName:"Male Singles",gender:"MALE",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{collectionName:"Female Singles",gender:"FEMALE",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{collectionName:"Mixed Doubles",gender:"MIXED",matchUpCount:3,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1}],tieFormatName:"USTA_SOUTHERN_LEVEL_5",winCriteria:{valueGoal:8}},DP={collectionDefinitions:[{category:{ageCategoryCode:"16U"},collectionName:"16U Singles",matchUpCount:4,matchUpFormat:"SET3-S:6/TB7",matchUpType:"SINGLES",matchUpValue:1},{category:{ageCategoryCode:"18U"},collectionName:"18U Singles",matchUpCount:4,matchUpFormat:"SET3-S:6/TB7",matchUpType:"SINGLES",matchUpValue:1},{category:{ageCategoryCode:"16U"},collectionName:"16U Doubles",matchUpCount:2,matchUpFormat:"SET1-S:6/TB7",matchUpType:"DOUBLES",matchUpValue:1},{category:{ageCategoryCode:"18U"},collectionName:"18U Doubles",matchUpCount:2,matchUpFormat:"SET1-S:6/TB7",matchUpType:"DOUBLES",matchUpValue:1},{collectionName:"Tiebreak Doubles",matchUpCount:1,matchUpFormat:"SET1-S:TB10",matchUpType:"DOUBLES",matchUpValue:1,processCodes:["RANKING.IGNORE"]}],tieFormatName:"USTA_SECTION_BATTLE",winCriteria:{valueGoal:9}},wP={collectionDefinitions:[{collectionName:"Male Singles",gender:"MALE",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{collectionName:"Female Singles",gender:"FEMALE",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{collectionName:"Male Doubles",gender:"MALE",matchUpCount:1,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1},{collectionName:"Female Doubles",gender:"FEMALE",matchUpCount:1,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1},{collectionName:"Mixed Doubles",gender:"MIXED",matchUpCount:1,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1}],tieFormatName:"USTA_INTERSECTIONAL",winCriteria:{valueGoal:8}},bP={collectionDefinitions:[{scoreValue:1,matchUpType:"SINGLES",collectionName:"Men's Singles",matchUpFormat:"SET1-S:T60",gender:"MALE",matchUpCount:1},{scoreValue:1,matchUpType:"SINGLES",collectionName:"Women's Singles",matchUpFormat:"SET1-S:T60",gender:"FEMALE",matchUpCount:1},{matchUpValue:1,matchUpType:"DOUBLES",collectionName:"Mixed Doubles",matchUpFormat:"SET1-S:T60",gender:"MIXED",matchUpCount:1}],tieFormatName:"Time Tennis Pro Circuit",winCriteria:{aggregateValue:!0}},RP={collectionDefinitions:[{collectionName:"Mixed Doubles",gender:"MIXED",matchUpCount:1,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1},{collectionName:"Male Singles",matchUpCount:1,gender:"MALE",matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{collectionName:"Female Singles",gender:"FEMALE",matchUpCount:1,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1}],tieFormatName:"DOMINANT_DUO_MIXED",winCriteria:{valueGoal:2}},NP={collectionDefinitions:[{scoreValue:1,matchUpType:"SINGLES",collectionName:"Men's Singles",matchUpFormat:"SET1-S:T60",gender:"MALE",matchUpCount:3},{scoreValue:1,matchUpType:"SINGLES",collectionName:"Women's Singles",matchUpFormat:"SET1-S:T60",gender:"FEMALE",matchUpCount:3},{scoreValue:1,matchUpType:"DOUBLES",collectionName:"Men's Doubles",matchUpFormat:"SET1-S:T60",gender:"MALE",matchUpCount:1},{matchUpValue:1,matchUpType:"DOUBLES",collectionName:"Women's Doubles",matchUpFormat:"SET1-S:T60",gender:"FEMALE",matchUpCount:1},{matchUpValue:1,matchUpType:"DOUBLES",collectionName:"Mixed Doubles",matchUpFormat:"SET1-S:T60",gender:"MIXED",matchUpCount:1}],tieFormatName:"Time Tennis Dual",winCriteria:{aggregateValue:!0}},MP={collectionDefinitions:[{category:{ageCategoryCode:"14U"},collectionName:"14U Singles",matchUpCount:2,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{category:{ageCategoryCode:"16U"},collectionName:"16U Singles",matchUpCount:2,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{category:{ageCategoryCode:"18U"},collectionName:"18U Singles",matchUpCount:2,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{category:{ageCategoryCode:"14U"},collectionName:"14U Doubles",collectionGroupNumber:1,matchUpCount:1,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1},{category:{ageCategoryCode:"16U"},collectionName:"16U Doubles",collectionGroupNumber:1,matchUpCount:1,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1},{category:{ageCategoryCode:"18U"},collectionName:"18U Doubles",collectionGroupNumber:1,matchUpCount:1,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1}],collectionGroups:[{groupNumber:1,groupName:"Doubles",groupValue:1,winCriteria:{valueGoal:2}}],tieFormatName:"USTA_BREWER_CUP",winCriteria:{valueGoal:4}},AP={winCriteria:{valueGoal:23},tieFormatName:"USTA_OZAKI_CUP",collectionDefinitions:[{category:{ageCategoryCode:"18U"},matchUpFormat:"SET3-S:6/TB7-F:TB10",collectionName:"18U Boys Singles",matchUpType:"SINGLES",matchUpCount:3,matchUpValue:1,gender:"MALE"},{category:{ageCategoryCode:"18U"},matchUpFormat:"SET3-S:6/TB7-F:TB10",collectionName:"18U Girls Singles",matchUpType:"SINGLES",gender:"FEMALE",matchUpCount:3,matchUpValue:1},{category:{ageCategoryCode:"18U"},collectionName:"18U Boys Doubles",matchUpFormat:"SET1-S:8/TB8",matchUpType:"DOUBLES",matchUpCount:1,matchUpValue:1,gender:"MALE"},{category:{ageCategoryCode:"18U"},collectionName:"18U Girls Doubles",matchUpFormat:"SET1-S:8/TB8",matchUpType:"DOUBLES",gender:"FEMALE",matchUpCount:1,matchUpValue:1},{category:{ageCategoryCode:"18U"},collectionName:"18U Mixed Doubles",matchUpFormat:"SET1-S:8/TB8",matchUpType:"DOUBLES",gender:"MIXED",matchUpCount:1,matchUpValue:1},{category:{ageCategoryCode:"16U"},matchUpFormat:"SET3-S:6/TB7-F:TB10",collectionName:"16U Boys Singles",matchUpType:"SINGLES",matchUpCount:3,matchUpValue:1,gender:"MALE"},{category:{ageCategoryCode:"16U"},matchUpFormat:"SET3-S:6/TB7-F:TB10",collectionName:"16U Girls Singles",matchUpType:"SINGLES",gender:"FEMALE",matchUpCount:3,matchUpValue:1},{category:{ageCategoryCode:"16U"},collectionName:"16U Boys Doubles",matchUpFormat:"SET1-S:8/TB8",matchUpType:"DOUBLES",matchUpCount:1,matchUpValue:1,gender:"MALE"},{category:{ageCategoryCode:"16U"},collectionName:"16U Girls Doubles",matchUpFormat:"SET1-S:8/TB8",matchUpType:"DOUBLES",gender:"FEMALE",matchUpCount:1,matchUpValue:1},{category:{ageCategoryCode:"16U"},collectionName:"16U Mixed Doubles",matchUpFormat:"SET1-S:8/TB8",matchUpType:"DOUBLES",gender:"MIXED",matchUpCount:1,matchUpValue:1},{category:{ageCategoryCode:"14U"},matchUpFormat:"SET3-S:6/TB7-F:TB10",collectionName:"14U Boys Singles",matchUpType:"SINGLES",matchUpCount:3,matchUpValue:1,gender:"MALE"},{category:{ageCategoryCode:"14U"},matchUpFormat:"SET3-S:6/TB7-F:TB10",collectionName:"14U Girls Singles",matchUpType:"SINGLES",gender:"FEMALE",matchUpCount:3,matchUpValue:1},{category:{ageCategoryCode:"14U"},collectionName:"14U Boys Doubles",matchUpFormat:"SET1-S:8/TB8",matchUpType:"DOUBLES",matchUpCount:1,matchUpValue:1,gender:"MALE"},{category:{ageCategoryCode:"14U"},collectionName:"14U Girls Doubles",matchUpFormat:"SET1-S:8/TB8",matchUpType:"DOUBLES",gender:"FEMALE",matchUpCount:1,matchUpValue:1},{category:{ageCategoryCode:"14U"},collectionName:"14U Mixed Doubles",matchUpFormat:"SET1-S:8/TB8",matchUpType:"DOUBLES",gender:"MIXED",matchUpCount:1,matchUpValue:1},{category:{ageCategoryCode:"12U"},matchUpFormat:"SET3-S:6/TB7-F:TB10",collectionName:"12U Boys Singles",matchUpType:"SINGLES",matchUpCount:3,matchUpValue:1,gender:"MALE"},{category:{ageCategoryCode:"12U"},matchUpFormat:"SET3-S:6/TB7-F:TB10",collectionName:"12U Girls Singles",matchUpType:"SINGLES",gender:"FEMALE",matchUpCount:3,matchUpValue:1},{category:{ageCategoryCode:"12U"},collectionName:"12U Boys Doubles",matchUpFormat:"SET1-S:8/TB8",matchUpType:"DOUBLES",matchUpCount:1,matchUpValue:1,gender:"MALE"},{category:{ageCategoryCode:"12U"},collectionName:"12U Girls Doubles",matchUpFormat:"SET1-S:8/TB8",matchUpType:"DOUBLES",gender:"FEMALE",matchUpCount:1,matchUpValue:1},{category:{ageCategoryCode:"12U"},collectionName:"12U Mixed Doubles",matchUpFormat:"SET1-S:8/TB8",matchUpType:"DOUBLES",gender:"MIXED",matchUpCount:1,matchUpValue:1}]},EP={collectionDefinitions:[{collectionName:"Doubles",matchUpCount:1,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1},{collectionName:"Singles",matchUpCount:2,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1}],tieFormatName:"DOMINANT_DUO",winCriteria:{valueGoal:2}},CP={collectionDefinitions:[{collectionName:"Doubles",matchUpCount:3,matchUpFormat:"SET1-S:8/TB7@7",matchUpType:"DOUBLES",collectionValue:1},{collectionName:"Singles",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1}],tieFormatName:"USTA_COLLEGE",winCriteria:{valueGoal:4}},OP={collectionDefinitions:[{collectionName:"Male Singles",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7",matchUpType:"SINGLES",matchUpValue:1},{collectionName:"Female Singles",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7",matchUpType:"SINGLES",matchUpValue:1},{collectionName:"Male Doubles",matchUpCount:3,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1},{collectionName:"Female Doubles",matchUpCount:3,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1}],tieFormatName:"USTA_LEVEL_1",winCriteria:{valueGoal:10}},FP={collectionDefinitions:[{collectionName:"Female Doubles",gender:"FEMALE",matchUpCount:1,matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Male Doubles",gender:"MALE",matchUpCount:1,matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Female Singles",gender:"FEMALE",matchUpCount:1,matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"SINGLES",scoreValue:1},{collectionName:"Male Singles",matchUpCount:1,gender:"MALE",matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"SINGLES",scoreValue:1},{collectionName:"Mixed Doubles",matchUpCount:1,gender:"MIXED",matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Mixed Doubles",matchUpCount:1,gender:"MIXED",matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Overtime",matchUpCount:1,gender:"MIXED",matchUpFormat:"SET1-S:T20",matchUpType:"DOUBLES",scoreValue:1}],tieFormatName:"USTA_WTT_ITT",winCriteria:{aggregateValue:!0}},kP={collectionDefinitions:[{collectionName:"Male Singles",gender:"MALE",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{collectionName:"Female Singles",gender:"FEMALE",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{collectionName:"Male Doubles",gender:"MALE",matchUpCount:3,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1},{collectionName:"Female Doubles",gender:"FEMALE",matchUpCount:3,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1},{collectionName:"Mixed Doubles",gender:"MIXED",matchUpCount:1,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1}],tieFormatName:"USTA_ZONAL",winCriteria:{valueGoal:10}},_P={collectionDefinitions:[{collectionGroupNumber:1,matchUpType:"DOUBLES",matchUpCount:1,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpValue:1},{collectionGroupNumber:1,matchUpType:"SINGLES",matchUpCount:3,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpValue:1},{collectionGroupNumber:2,matchUpType:"DOUBLES",matchUpCount:1,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpValue:2},{collectionGroupNumber:2,matchUpType:"SINGLES",matchUpCount:3,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpValue:2},{collectionGroupNumber:3,matchUpType:"DOUBLES",matchUpCount:1,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpValue:3},{collectionGroupNumber:3,matchUpType:"SINGLES",matchUpCount:3,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpValue:3}],collectionGroups:[{groupNumber:1,groupName:"Day 1"},{groupNumber:2,groupName:"Day 2"},{groupNumber:3,groupName:"Day 3"}],tieFormatName:"LAVER_CUP",winCriteria:{valueGoal:13}},xP={collectionDefinitions:[{collectionName:"Female Doubles",gender:"FEMALE",matchUpCount:1,matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Male Doubles",gender:"MALE",matchUpCount:1,matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Female Singles",gender:"FEMALE",matchUpCount:1,matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"SINGLES",scoreValue:1},{collectionName:"Male Singles",matchUpCount:1,gender:"MALE",matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"SINGLES",scoreValue:1},{collectionName:"Mixed Doubles",matchUpCount:1,gender:"MIXED",matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Overtime",matchUpCount:1,gender:"MIXED",matchUpFormat:"SET1-S:T20",matchUpType:"DOUBLES",scoreValue:1}],tieFormatName:"USTA_TOC",winCriteria:{aggregateValue:!0}};const LP="COLLEGE_DEFAULT",VP="COLLEGE_JUCO",BP="COLLEGE_D3",jP="DOMINANT_DUO",GP="DOMINANT_DUO_MIXED",qP="LAVER_CUP",$P="TEAM_DOUBLES_3_AGGREGATION",WP="TIME_TENNIS_DUAL",HP="TIME_TENNIS_PRO_CIRCUIT",zP="USTA_BREWER_CUP",YP="USTA_OZAKI_CUP",QP="USTA_COLLEGE",KP="USTA_GOLD_TEAM_CHALLENGE",JP="USTA_LEVEL_1",ZP="USTA_INTERSECTIONAL",XP="USTA_SECTION_BATTLE",eD="USTA_SOUTHERN_LEVEL_5",tD="USTA_TOC",rD="USTA_WTT_ITT",nD="USTA_ZONAL",iD={COLLEGE_D3:BP,COLLEGE_DEFAULT:LP,COLLEGE_JUCO:VP,DOMINANT_DUO:jP,DOMINANT_DUO_MIXED:GP,LAVER_CUP:qP,TEAM_DOUBLES_3_AGGREGATION:$P,TIME_TENNIS_DUAL:WP,TIME_TENNIS_PRO_CIRCUIT:HP,USTA_BREWER_CUP:zP,USTA_OZAKI_CUP:YP,USTA_COLLEGE:QP,USTA_GOLD_TEAM_CHALLENGE:KP,USTA_INTERSECTIONAL:ZP,USTA_LEVEL_1:JP,USTA_SECTION_BATTLE:XP,USTA_SOUTHERN_LEVEL_5:eD,USTA_TOC:tD,USTA_WTT_ITT:rD,USTA_ZONAL:nD},aD="STANDARD",oD={[aD]:{hydrate:!0,doubles:{matchUpCount:3,matchUpValue:1},singles:{matchUpCount:6,matchUpValue:1},valueGoal:5},[BP]:{hydrate:!0,doubles:{matchUpCount:3,matchUpValue:1,matchUpFormat:"SET1-S:8/TB7@7"},singles:{matchUpFormat:LI,matchUpCount:6,matchUpValue:1},tieFormatName:BP,valueGoal:5},[LP]:{hydrate:!0,doubles:{matchUpCount:3,collectionValue:1,matchUpFormat:LI},singles:{matchUpCount:6,matchUpValue:1,matchUpFormat:LI},tieFormatName:LP,valueGoal:4},[VP]:{hydrate:!0,doubles:{matchUpCount:3,matchUpValue:1,matchUpFormat:"SET1-S:8/TB7"},singles:{matchUpCount:6,matchUpValue:1,matchUpFormat:LI},tieFormatName:VP,valueGoal:5},[qP]:_P,[jP]:EP,[GP]:RP,[$P]:TP,[WP]:NP,[HP]:bP,[zP]:MP,[YP]:AP,[QP]:CP,[KP]:vP,[ZP]:wP,[JP]:OP,[XP]:DP,[eD]:PP,[rD]:FP,[tD]:xP,[nD]:kP},sD=e=>{const t=e?.namedFormat&&Object.keys(oD).includes(e.namedFormat)?e.namedFormat:aD,r=Array.isArray(e?.uuids)?e?.uuids:[];let n;const{category:i,gender:a}=e?.event??{},o=Jc(oD[t],!1,!0),s=t=>{if(!e?.isMock&&!e?.event?.isMock||!e.event)return r?.pop()??bm();const n=e?.event?.eventId;return r.pop()??`${n}-COL-${t+1}`};return o.hydrate?(n={winCriteria:{valueGoal:o.valueGoal},collectionDefinitions:[{collectionId:s(0),matchUpFormat:VI,collectionName:"Doubles",matchUpType:hf,...o.doubles},{collectionId:s(1),matchUpFormat:LI,collectionName:"Singles",matchUpType:mf,...o.singles}]},o.tieFormatName&&(n.tieFormatName=o.tieFormatName)):(o.collectionDefinitions.forEach(((e,t)=>e.collectionId=s(t))),n=o),e?.hydrateCollections&&n.collectionDefinitions.forEach((e=>{i&&!e.category&&(e.category=i),a&&!e.gender&&(e.gender=a)})),n};const cD={COLLEGE_D3:{collectionDefinitions:[{collectionName:"Doubles",matchUpCount:3,matchUpFormat:"SET1-S:8/TB7@7",matchUpType:"DOUBLES",matchUpValue:1},{collectionName:"Singles",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7",matchUpType:"SINGLES",matchUpValue:1}],tieFormatName:"COLLEGE_D3",winCriteria:{valueGoal:5}},COLLEGE_DEFAULT:{collectionDefinitions:[{collectionName:"Doubles",collectionValue:1,matchUpCount:3,matchUpFormat:"SET1-S:6/TB7",matchUpType:"DOUBLES"},{collectionName:"Singles",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7",matchUpType:"SINGLES",matchUpValue:1}],tieFormatName:"COLLEGE_DEFAULT",winCriteria:{valueGoal:5}},COLLEGE_JUCO:{collectionDefinitions:[{collectionName:"Doubles",matchUpCount:3,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1},{collectionName:"Singles",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7",matchUpType:"SINGLES",matchUpValue:1}],tieFormatName:"COLLEGE_JUCO",winCriteria:{valueGoal:5}},DOMINANT_DUO:EP,DOMINANT_DUO_MIXED:RP,LAVER_CUP:_P,TEAM_DOUBLES_3_AGGREGATION:TP,TIME_TENNIS_DUAL:NP,TIME_TENNIS_PRO_CIRCUIT:bP,USTA_BREWER_CUP:MP,USTA_OZAKI_CUP:AP,USTA_COLLEGE:CP,USTA_GOLD_TEAM_CHALLENGE:vP,USTA_INTERSECTIONAL:wP,USTA_LEVEL_1:OP,USTA_SECTION_BATTLE:DP,USTA_SOUTHERN_LEVEL_5:PP,USTA_TOC:xP,USTA_WTT_ITT:FP,USTA_ZONAL:kP};function uD({suppressNotifications:e,tournamentRecord:t,internalUse:r,event:n}){if(!t)return{error:Fi};if(t.events||(t.events=[]),!n)return{error:Ua};const{startDate:i,endDate:a}=t;if(!r&&(n.entries?.length||n.drawDefinitions?.length)){const e=Mf({drawDefinitions:!!n.drawDefinitions?.length,entries:!!n.entries?.length});return{info:"entries/drawDefinitions cannot exist",error:ys,context:e}}const o={eventType:$f,drawDefinitions:[],entries:[],startDate:i,endDate:a,...n};if(n.eventType===Yf)if(n.tieFormat){const e=pv({tieFormat:n.tieFormat});if(e.error)return e}else if(n.tieFormatName){if(!cD[n.tieFormatName])return{context:{tieFormatName:n.tieFormatName},error:ys};const e=sD({isMock:t?.isMock,namedFormat:n.tieFormatName,event:n});o.tieFormat=e}o.eventId||(o.eventId=bm());if(t.events.reduce(((e,t)=>e||t.eventId===o.eventId),void 0))return{error:Sa};{const r=o;if(t.events.push(r),!e){const{topics:e}=sc();if(e.includes(up)){const e=KU({event:n}).matchUps??[];xp({tournamentId:t?.tournamentId,eventId:n.eventId,matchUps:e})}for(const e of n.drawDefinitions||[])Bp({drawDefinition:e})}return{...Ni,event:o}}}var dD=Object.freeze({__proto__:null,addDrawDefinition:lP,addEvent:uD,addFlight:SP,assignSeedPositions:mP,attachFlightProfile:fP,deleteDrawDefinitions:QT,deleteEvents:UP,deleteFlightAndFlightDraw:dP,deleteFlightProfileAndFlightDraws:KT,modifyEvent:yP,modifyEventMatchUpFormatTiming:tP,modifyPairAssignment:pP,refreshEventDrawOrder:uP,removeEventMatchUpFormatTiming:rP,removeScaleValues:hP,removeSeeding:IP,setEventDates:oP,setEventDisplay:gP,setEventEndDate:aP,setEventStartDate:iP,updateDrawIdsOrder:cP,validateCategory:rv});function pD({drawDetails:e,drawId:t}){const r=e?.[t]?.publishingDetail;return r?.published}function lD({tournamentRecord:e,outcomes:t}){if(!e)return{error:Fi};if(!t?.length)return{error:Za,info:"Missing outcomes"};const r=t.reduce(((e,t)=>{const{drawId:r,eventId:n}=t;return n&&r&&(e[n]?e[n].includes(r)||e[n].push(r):e[n]=[r]),e}),{}),n=Object.keys(r),i=e.events?.filter((e=>n.includes(e.eventId)));return{publishedEventIds:i.filter((e=>{const t=jT({event:e}),{drawDetails:n,drawIds:i}=t??{},{eventId:a}=e;return r[a].filter((e=>{const r=n?Object.keys(t.drawDetails).filter((e=>pD({drawId:e,drawDetails:n}))):[];return i?.includes(e)||r.includes(e)})).length})).map((e=>e.eventId)),eventIdPublishedDrawIdsMap:r}}function mD({tournamentRecord:e,event:t}){if(!e)return{error:Fi};if(!t)return{error:Ua};const r=t.entries||[],n=e.participants||[],i=t.category?.categoryName||t.category?.ageCategoryCode,{eventType:a}=t,o=r.map((e=>e.participantId));let s,c,u;return{entryScaleAttributes:n.filter((e=>o.includes(e.participantId))).map((e=>{const{participantId:t,participantName:r,name:n}=e;let o={scaleType:NI,eventType:a,scaleName:i};const d=AU({participant:e,scaleAttributes:o})?.scaleItem?.scaleValue;o={scaleType:RI,eventType:a,scaleName:i};const p=AU({participant:e,scaleAttributes:o})?.scaleItem?.scaleValue;o={scaleType:bI,eventType:a,scaleName:i};const l=AU({participant:e,scaleAttributes:o})?.scaleItem?.scaleValue;return s=!(!s&&!d),c=!(!c&&!p),u=!(!u&&!l),{participantId:t,participantName:r||n,seed:d,ranking:p,rating:l}})),hasSeededParticipants:s,hasRankedParticipants:c,hasRatedParticipants:u}}function fD({tournamentRecord:e,withScaleValues:t,scaleEventType:r,inContext:n,eventIds:i,drawIds:a,context:o}){if(!e)return{error:Fi};const{tournamentId:s}=e,u=(e.events??[]).filter((({eventId:e})=>!i||Array.isArray(i)&&i.includes(e))).map((e=>{const t=e.drawDefinitions?.map(P);if(a?.length&&!c(a,t).length)return;const r=L(e);return n&&Object.assign(r,{tournamentId:s}),o&&Object.assign(r,o),r})).filter(Boolean),d={};if(t){const t=pt({withScaleValues:!0,tournamentRecord:e}).participantMap,n=e=>e.reduce(((e,t)=>e+parseFloat(t)),0);for(const e of u){const i=r??e.eventType,o=e.eventId;d[o]||(d[o]={ratingsStats:{},ratings:{},ranking:{},draws:{}});const s=(e.entries??[]).filter((({entryStatus:e})=>um.includes(e))).map(v),c=e=>{if(e?.ratings?.[i])for(const t of e?.ratings?.[i]??[]){const e=t.scaleName;d[o].ratings[e]||(d[o].ratings[e]=[]);const r=Tv[e]?.accessor;if(r){const n=parseFloat(t.scaleValue?.[r]);n&&d[o].ratings[e].push(n)}}if(e?.rankings?.[i])for(const t of e?.rankings?.[i]??[]){const e=t.scaleName;d[o].ranking[e]||(d[o].ranking[e]=[]),t.scaleValue&&d[o].ranking[e].push(t.scaleValue)}};for(const e of s){const r=t?.[e]?.participant;if(r?.participantType!==gm)for(const e of r?.individualParticipantIds??[]){const r=t?.[e]?.participant;c(r)}else c(r)}const u=d[o].ratings;for(const e of Object.keys(u)){const t=u[e];if(!t.length)continue;const r=Be(t)?.toFixed(2);d[o].ratingsStats[e]={avg:parseFloat((n(t)/t.length).toFixed(2)),median:r?parseFloat(r):void 0,max:Math.max(...t),min:Math.min(...t)}}const p=(e,r)=>{const n=t=>{if(d[o].draws?.[e]&&t?.ratings?.[i])for(const r of t?.ratings?.[i]??[]){const t=r.scaleName;d[o].draws[e]?.ratings[t]||(d[o].draws[e].ratings[t]=[]);const n=Tv[t]?.accessor;if(n){const i=parseFloat(r.scaleValue?.[n]);i&&d[o].draws[e].ratings[t].push(i)}}if(d[o].draws?.[e]&&t?.rankings?.[i])for(const r of t?.rankings?.[i]??[]){const t=r.scaleName;d[o].draws[e]?.ranking[t]||(d[o].draws[e].ranking[t]=[]);const n=r.scaleValue;n&&d[o].draws[e].ranking[t].push(n)}};for(const e of r.filter(Boolean)){const r=t?.[e]?.participant;if(r?.participantType!==gm)for(const e of r?.individualParticipantIds??[]){const r=t?.[e]?.participant;n(r)}else n(r)}},l=[],m=e=>a?.length&&a.includes(e)||l.includes(e);for(const t of e.drawDefinitions??[]){const e=t.drawId;if(m(e))continue;const r=Ht({drawDefinition:t}).assignedParticipantIds??[];d[o].draws[e]||(d[o].draws[e]={ratingsStats:{},ratings:{},ranking:{}}),l.push(e),p(e,r)}const f=Ot({event:e}).flightProfile;for(const e of f?.flights??[]){const t=e.drawId;if(m(t))continue;p(t,e.drawEntries.map(v))}for(const e of l){const t=d[o].draws[e].ratings;for(const r of Object.keys(t)){const i=t[r];if(!i.length)continue;const a=Be(i)?.toFixed(2);d[o].draws[e].ratingsStats[r]={avg:parseFloat((n(i)/i.length).toFixed(2)),median:a?parseFloat(a):void 0,max:Math.max(...i),min:Math.min(...i)}}}}}return S({eventScaleValues:d,events:u,...Ni})}function hD({tournamentRecord:e,drawDefinition:t,context:r,event:n}){if(!e)return{error:Fi};if(!n)return{error:Ua};const i=Jc(n);r&&Object.assign(i,r);return Mf({drawDefinition:t&&i.drawDefinitions?.find((({drawId:e})=>t.drawId===e)),event:i})}var gD=Object.freeze({__proto__:null,bulkUpdatePublishedEventIds:lD,categoryCanContain:nv,getCategoryAgeDetails:tv,getEvent:hD,getEventProperties:mD,getEventStructures:uh,getEventTimeItem:ag,getEvents:fD,getFlightProfile:bU,getScaledEntries:CU}),ID=Object.freeze({__proto__:null,addDrawDefinition:lP,addEvent:uD,addFlight:SP,assignSeedPositions:mP,attachFlightProfile:fP,bulkUpdatePublishedEventIds:lD,categoryCanContain:nv,deleteDrawDefinitions:QT,deleteEvents:UP,deleteFlightAndFlightDraw:dP,deleteFlightProfileAndFlightDraws:KT,getCategoryAgeDetails:tv,getEvent:hD,getEventProperties:mD,getEventStructures:uh,getEventTimeItem:ag,getEvents:fD,getFlightProfile:bU,getScaledEntries:CU,modifyEvent:yP,modifyEventMatchUpFormatTiming:tP,modifyPairAssignment:pP,mutate:dD,query:gD,refreshEventDrawOrder:uP,removeEventMatchUpFormatTiming:rP,removeScaleValues:hP,removeSeeding:IP,setEventDates:oP,setEventDisplay:gP,setEventEndDate:aP,setEventStartDate:iP,updateDrawIdsOrder:cP,validateCategory:rv});const UD="splitWaterfall",yD="splitShuttle",SD={SPLIT_LEVEL_BASED:"splitLevelBased",SPLIT_WATERFALL:UD,SPLIT_SHUTTLE:yD};const vD="ASC",TD="DESC",PD={ASC:"ASC",ASCENDING:vD,DESC:"DESC",DESCENDING:TD};function DD(e){let{tieFormat:t}=e;const{useDefaultEventRanking:r,tournamentRecord:n,drawDefinition:i,scaleAccessor:a,singlesOnly:s,attach:c,event:u}=e;if(u?.eventType!==Yf)return{error:Ia};if(!n)return{error:Fi};if(!t&&!i)return{error:Bi};if(t=t??we({drawDefinition:i,event:u})?.tieFormat,ar({tieFormat:t}).error)return{error:Ea};if("object"!=typeof a&&!r)return{error:ys,context:{scaleAccessor:a}};const d={},p=(i?.entries??u?.entries??[]).filter((e=>e?.entryStatus===Ql)).map(v),{participants:m=[]}=pt({withIndividualParticipants:!0,withScaleValues:!0,tournamentRecord:n}),f=m.filter((({participantId:e})=>p.includes(e))),h=u?.category?.categoryName??u?.category?.ageCategoryCode,{scaleName:g=h,scaleType:I=pu,sortOrder:U,accessor:y}=a||{},S=I===pu?"rankings":"ratings";const T=(e,t)=>{let n=e[S]?.[t];if(!n&&r&&(n=e[S]?.[lf]),Array.isArray(n)){const e=n.find((e=>e.scaleName===g))?.scaleValue;if(je(e))return e;if(y&&"object"==typeof e)return e[y]}return 0},P=(e,t,r)=>{const n=U===TD?e:t;return T(U===TD?t:e,r)-T(n,r)},D=(e,t)=>P(e,t,lf),w=(e,t)=>P(e,t,ff),b=[],R=t?.collectionDefinitions??[];for(const e of f){const t=e.individualParticipants?.sort(D)??[],r=s?t:e.individualParticipants?.sort(w)??[],n={};for(const e of R){const i=[],{collectionId:a,matchUpCount:o,matchUpType:s,gender:c}=e,u=s===lf;l(0,o).forEach((e=>{const o=u?t:r??[],s=e+1,d=[];l(0,u?1:2).forEach((e=>{const t=o?.find((t=>{const r=c&&([Lf,jf].includes(c)&&c||c===Vf&&[Lf,jf][e]);return!(r&&r!==t.person?.sex||i.includes(t.participantId))}))?.participantId;t&&(d.push(t),i.push(t),n[t]||(n[t]=[]),n[t].push({collectionPosition:s,collectionId:a}))})),u||b.push(d)}))}const i=Object.keys(n).map((e=>({collectionAssignments:n[e],participantId:e})));d[e.participantId]=i}const N=[];for(const e of b){const{participant:t}=Ne({tournamentParticipants:m,participantIds:e});if(!t){const t={individualParticipantIds:e,participantRole:Zv,participantType:Um};N.push(t)}}if(c){for(;N.length;)Jr({participant:N.pop(),tournamentRecord:n});o({element:i,extension:{name:mi,value:d}})}return{...Ni,lineUps:d,participantsToAdd:N}}function wD(e){if(!e)return{error:Za};const t=y(e,[{dates:!1,[Gu]:e=>Array.isArray(e)&&e.every(Br)},{uuids:!1,[Gu]:e=>Array.isArray(e)&&e.every(gt)},{startTime:!1,endTime:!1,[Gu]:jr},{idPrefix:!1,namePrefix:!1,[Gu]:gt},{count:!0,[Gu]:je}]);if(t.error)return t;const{startDate:r,endDate:n}=e.tournamentRecord??{},i=e.dates||r&&n&&Gr(r,n)||[],a=l(1,e.count+1).map((t=>S({courtId:e.uuids?.pop()??(e.idPrefix&&`${e.idPrefix}-${t}`)??vt(),courtName:e.courtNames?.pop()??(e.namePrefix&&`${e.namePrefix} ${t}`),dateAvailability:i.map((t=>({startTime:e.startTime??"08:00",endTime:e.endTime??"20:00",date:t})))})));return{...Ni,courts:a}}function bD({court:e,date:t}){const r=t&&e.dateAvailability.find((e=>Qc(e.date,t))),n=e.dateAvailability.find((e=>!e.date));return r||n}function RD(e){const t=uy(e,[{courtDate:!0,_ofType:Bu}]);if(t.error)return t;const{includeBookingTypes:r=[],courtDate:n}=e,i=[];let a=qr(n.startTime);(n.bookings||[]).filter((e=>!e.bookingType||!r.includes(e.bookingType))).sort(((e,t)=>$r(e.startTime).localeCompare($r(t.startTime)))).forEach((e=>{const t={startTime:Wr(a.toISOString()),endTime:e.startTime};qr(e.startTime)>a&&i.push(t),qr(e.endTime)>a&&(a=qr(e.endTime))}));const o={startTime:Wr(a.toISOString()),endTime:n.endTime};return qr(n.endTime)>a&&i.push(o),{timeSlots:i}}function ND(e){const t=y(e,[{periodStart:!0,date:!0},{courts:!0,_ofType:ju}]);if(t.error)return t;const{averageMatchUpMinutes:r,includeBookingTypes:n,periodStart:i,date:a}=e,o=e.courts,s=qr(i),c=Hr(s,r),{enoughTime:u}=function({averageMatchUpMinutes:e,includeBookingTypes:t,periodStartTime:r,periodEndTime:n}){function i(t){const i=$c(t.startTime),a=$c(t.endTime);return!(i>r)&&(!(a<n)&&Wc(r,a)>=e)}return{enoughTime:e=>{const{timeSlots:r}=RD({includeBookingTypes:t,courtDate:e}),n=r?.filter(i);return!!n?.length}}}({averageMatchUpMinutes:r,includeBookingTypes:n,periodStartTime:s,periodEndTime:c});return{availableToScheduleCount:(o?.filter((e=>{if(!Array.isArray(e.dateAvailability))return!1;const t=bD({date:a,court:e});return!(!t||!u(t))}))||[]).length,...Ni}}function MD({scheduleDate:e,startTime:t,endTime:r,courts:n}){const i=(t?"startTime":r&&"endTime")||void 0;return n.reduce(((n,a)=>{const o=bD({date:e,court:a}),s=i&&(o?.[i]||a[i]);return s&&(!n||t&&kc(s)<kc(n)||r&&kc(s)>kc(n))?s:n}),void 0)}function AD(e){const t=y(e,[{courts:!0,_ofType:ju}]);if(t.error)return t;let{date:r=zr(),startTime:n="08:00",endTime:i="19:00",periodLength:a,courts:o}=e;const{calculateStartTimeFromCourts:s=!0,remainingScheduleTimes:c,averageMatchUpMinutes:u,clearScheduleDates:d,courtsCount:p,bookings:m}=e;a=a||Xr({averageMatchUpMinutes:u}),r=Vr(r),n=Wr(n),i=Wr(i);let f=0,h=0,g=0,I=0,U=0;!o&&p&&(o=en({startTime:n,endTime:i,count:p,date:r}));const{virtualCourts:S}=Zr({remainingScheduleTimes:c,clearScheduleDates:d,scheduleDate:r,periodLength:a,bookings:m,courts:o}),{firstTimeSlotStartTime:v}=function({averageMinutes:e,startTime:t,endTime:r,courts:n,date:i}){let a;if(t=t||MD({courts:n,scheduleDate:i,startTime:!0}),r=r||MD({courts:n,scheduleDate:i,endTime:!0}),t&&r){const o=$c(t),s=$c(r);for(const t of n||[]){if(!Array.isArray(t.dateAvailability))continue;const r=bD({court:t,date:i}),{timeSlots:n}=RD({courtDate:r});n?.forEach((t=>{const r=$c(t.startTime),n=$c(t.endTime);if(r>s||r<o)return!1;if(n<o)return!1;if(Wc(r,n)>=e){const e=xc(r.toISOString());(!a||e<a)&&(a=e)}}))}}return{firstTimeSlotStartTime:a}}({averageMinutes:u,courts:S,startTime:n,endTime:i,date:r});s&&v&&(n=v||n);const T=Yr(n),P=Yr(i)-T,D=Math.floor(P/a),w=l(0,D+1).map((e=>{const t=Qr(T+e*a),n=ND({courts:S??[],averageMatchUpMinutes:u,periodStart:t,date:r});if(n.error)return{error:n.error};const{availableToScheduleCount:i=0}=n,o=i>h?i-h:0;U+=e?i:0;const s=e?U/e:i,c=e?a*s/u*(e-1)+s:s,d=i?h&&c-f||o:0;f=c,h=i,g+=d;const p=ve(g)-I;return I+=p,{periodStart:t,add:p,availableToScheduleCount:i,newCourts:o,totalMatchUps:I}}));return{scheduleTimes:w.reduce(((e,t)=>{const r=l(0,t.add).map((()=>({scheduleTime:t.periodStart})));return e.concat(...r)}),[]).flat(),timingProfile:w,totalMatchUps:I}}const ED={getCourtsAvailableAtPeriodStart:ND,generateTimeSlots:RD,getScheduleTimes:AD,courtGenerator:function(e){const{startTime:t="8:00",endTime:r="20:30",count:n=10,date:i}=e??{};return Qd(0,n).map((()=>({dateAvailability:[{date:i,startTime:t,endTime:r}]})))}};var CD=Object.freeze({__proto__:null,default:ED,garman:ED}),OD=Object.freeze({__proto__:null,drawMatic:Cv,garman:CD,generateAdHocMatchUps:mv,generateAdHocRounds:Ev,generateAndPopulatePlayoffStructures:Kg,generateCourts:wD,generateDrawDefinition:Kv,generateDrawMaticRound:Nv,generateDrawStructuresAndLinks:zS,generateDrawTypeAndModifyDrawDefinition:YS,generateFlightProfile:function(e){const{drawNameRoot:t="Flight",attachFlightProfile:r,tournamentRecord:n,scaleAttributes:i,scaleSortMethod:a,deleteExisting:o,sortDescending:s,drawNames:c=[],flightsCount:u,splitMethod:d,uuids:p=[],event:l,stage:m}=e;if(!l)return{error:Ua};const f=l.entries??[],{flightProfile:h}=bU({event:l});if(h&&r&&!o)return{error:Ns};const g=e.scaledEntries??CU({tournamentRecord:n,scaleAttributes:i,scaleSortMethod:a,sortDescending:s,event:l,stage:m}).scaledEntries,I=g.map(Rd),U=Gd(f.filter((({participantId:e})=>!I.includes(e))).filter((e=>(!m||!e.entryStage||e.entryStage===m)&&(!e.entryStatus||cm.includes(e.entryStatus))))),y=g.concat(...U),S=y.length;let v=ep(y,Math.ceil(S/u));d===UD?v=np(y,u):d===yD&&(v=np(y,u,!0));const T=Qd(0,u).map((e=>{const r=e+1;return{flightNumber:r,drawId:p?.pop()??bm(),drawEntries:(n=v[e],(n||[]).map((({participantId:e,scaleValue:t})=>{const r=f.find((t=>t.participantId===e));return r?.scaleValue&&t&&(r.scaleValue=t),r})).sort(((e,t)=>e.scaleValue-t.scaleValue)).map(((e,t)=>(e.scaleValue&&(e.seedNumber=t+1),e)))),drawName:c?.length&&c[e]||`${t} ${r}`};var n})),P={scaleAttributes:i,splitMethod:d,flights:T};if(r){const e=fP({flightProfile:P,deleteExisting:o,event:l});return{splitEntries:Ks()&&v||void 0,...e}}return{flightProfile:P,...Ni}},generateLineUps:DD,generateQualifyingStructure:Mg,generateSeedingScaleItems:wU,generateVoluntaryConsolation:lv,roundRobinGroups:bh}),FD=Object.freeze({__proto__:null,isValid:uv,isValidMatchUpFormat:uv,parse:QI,stringify:iv});function kD({tournamentRecord:e,drawDefinition:t,participantId:r,sideNumber:n,matchUpId:i,event:o}){if(r&&"string"!=typeof r)return{error:Io};if(!t)return{error:Li};if(!i)return{error:_a};const s=void 0===n;if(s&&(n=1),![1,2].includes(n))return a({result:{error:ys,context:{sideNumber:n}}});const{matchUp:c,structure:u}=Jt({drawDefinition:t,matchUpId:i,event:o});if(!c)return{error:La};if(!!(u?.structures||t.drawType&&t.drawType!==ll||u?.matchUps?.find((({roundPosition:e})=>!!e))))return{error:Zi};if(!r&&(c?.score?.scoreStringSide1||rf.includes(c?.matchUpstatus)||c?.matchUpStatus&&[qm,Gm].includes(c.matchUpStatus)))return{error:fo,info:"matchUp has completed status or score"};if(c){if(c.sides=[1,2].map((e=>{const t=c.sides?.find((t=>t.sideNumber===e))??{sideNumber:e};return n===e?{...t,participantId:r}:t})),s)for(const e of c.sides)e.sideNumber&&(e.sideNumber=3-e.sideNumber);q({tournamentId:e?.tournamentId,context:"assignSideParticipant",drawDefinition:t,matchUp:c})}return{...Ni,sidesSwapped:s}}function _D({matchUp:e}){if(!e)return{error:Ba};if(e&&!e.sides)return{error:ja};if(e&&!e.hasContext)return{error:ss};const t=(e.sides??[])?.map((e=>e?.participantId)).filter(Boolean),r=e.sides?.filter((e=>e.participant?.participantType===gm)).map((e=>e.participantId)).filter(Boolean)??[],n=((e.sides??[])?.map((e=>e.participant?.individualParticipants)).filter(Boolean)??[]).map((e=>(e??[]).map((e=>e?.participantId)).filter(Boolean))),i=[...r,...n.flat()].filter(Boolean)??[];return{nestedIndividualParticipantIds:n,allRelevantParticipantIds:u(i.concat(t)).filter(Boolean)??[],individualParticipantIds:i,sideParticipantIds:t,...Ni}}function xD({matchUp:e}){if(!e)return{error:Ba};if(!e.hasContext)return{error:ss};if(!e.sides||2!==e.sides.filter(Boolean).length)return{error:ja};const{nestedIndividualParticipantIds:t,allRelevantParticipantIds:r,sideParticipantIds:n}=_D({matchUp:e}),i=(e.timeItems??[]).filter((e=>e?.itemType&&[aI,oI].includes(e.itemType))).sort(((e,t)=>(e.createdAt?new Date(e.createdAt).getTime():0)-(t.createdAt?new Date(t.createdAt).getTime():0))),a=i.map((e=>e.itemValue)).filter((e=>i.filter((t=>t?.itemValue===e)).reverse()[0].itemType===aI));t?.forEach(((e,t)=>{const r=n?.[t],i=e?.length&&e.every((e=>a.includes(e)));r&&i&&!a.includes(r)&&a.push(r)})),n?.forEach(((e,r)=>{a.includes(e)&&(t?.[r]??[]).forEach((e=>{e&&!a.includes(e)&&a.push(e)}))}));const o=n?.reduce(((e,t)=>a.includes(t)&&e),!0);return{allRelevantParticipantIds:r,allParticipantsCheckedIn:o,checkedInParticipantIds:a,...Ni}}function LD(e){Object.assign(e,{inContext:!0});const{matchUp:t,error:r}=VD(e);return{matchUp:Jc(t,!0,!0),error:r}}function VD({participantsProfile:e,afterRecoveryTimes:t,tournamentRecord:r,contextContent:n,contextProfile:i,drawDefinition:a,nextMatchUps:o,matchUpId:s,inContext:c,eventId:u,drawId:d,event:p}){if(!r)return{error:Fi};if("string"!=typeof s)return{error:_a};if(!a||!p){const e=(yS({tournamentRecord:r,nextMatchUps:o}).matchUps??[]).find((e=>e.matchUpId===s));if(!e)return{error:La};({eventId:u,drawId:d}=e),({event:p,drawDefinition:a}=ly({tournamentRecord:r,eventId:u,drawId:d}))}if(!a)return{error:Bi};i&&!n&&(n=HU({tournamentRecord:r,contextProfile:i}));const l={surfaceCategory:p?.surfaceCategory??r.surfaceCategory,indoorOutDoor:p?.indoorOutdoor??r.indoorOutdoor,endDate:p?.endDate??r.endDate,tournamentId:r.tournamentId,eventId:u??p?.eventId,drawId:d},{participants:m=[]}=$U({participantsProfile:e,tournamentRecord:r,contextProfile:i,inContext:c});if(o){const e=(zU({context:c?l:void 0,participants:m,afterRecoveryTimes:t,contextContent:n,contextProfile:i,drawDefinition:a,nextMatchUps:o,inContext:c,event:p}).matchUps??[]).find((e=>e.matchUpId===s));if(!e)return{error:La};const r=a?.structures?.find((t=>t.structureId===e.structureId));return{drawDefinition:a,structure:r,matchUp:e}}{const{matchUp:e,structure:r}=xv({context:c?l:void 0,tournamentParticipants:m,afterRecoveryTimes:t,contextContent:n,drawDefinition:a,contextProfile:i,matchUpId:s,inContext:c,event:p});return{matchUp:e,structure:r,drawDefinition:a}}}function BD(e,t){if(!ru(e))return{error:ys};if(!Array.isArray(t))return{error:ys};const r={};for(const{param:n,error:i,attr:a}of t){const t=jD({params:e,param:n,attr:a,error:i});if(t?.error)return t;r[n]=t}return r}function jD({params:e,param:t,attr:r,error:n}){if(t===Mu&&ru(e.drawDefinition)&&tu(e.structureId)){const t=(e.drawDefinition.structures??[]).find((({structureId:t})=>t===e.structureId));return!t.length&&n?{error:n}:{structure:t}}if(t===ku){const t=VD({...e,...r});return t.error&&n?{...t,error:n}:t}return{error:ws,info:{param:t}}}function GD({removePriorValues:e,tournamentRecord:t,duplicateValues:r,drawDefinition:n,disableNotice:i,matchUpId:a,timeItem:o,event:s}){const{matchUp:c}=xv({drawDefinition:n,event:s,matchUpId:a});if(!c)return{error:La};const u=cg({removePriorValues:e,element:c,duplicateValues:r,timeItem:o});return i||Vp({tournamentId:t?.tournamentId,eventId:s?.eventId,context:"addTimeItem",drawDefinition:n,matchUp:c}),u}function qD(e){const t=uy(e,[{[Uu]:!0},{[yu]:!0},{[vu]:!0},{[Ru]:!0}]);if(t.error)return t;const r=BD(e,[{[Vu]:ku,attr:{[Nu]:!0}}]);if(r.error)return r;const{tournamentRecord:n,drawDefinition:i,participantId:a,matchUpId:o}=e,s=r?.matchUp?.matchUp,{matchUpStatus:c,score:u}=s??{};if(c&&nf.includes(c)||c&&rf.includes(c)||hg({score:u}))return{error:oa};const d=xD({matchUp:s});if(d?.error)return d;const{checkedInParticipantIds:p,allRelevantParticipantIds:l}=d??{};if(!l?.includes(a))return{error:Io};if(!p?.includes(a))return{error:Ao};const m=_D({matchUp:s});if(m?.error)return m;const{sideParticipantIds:f,nestedIndividualParticipantIds:h}=m??{},g=f?.indexOf(a);void 0!==g&&[0,1].includes(g)&&(h?.[g]??[]).forEach((e=>{GD({drawDefinition:i,matchUpId:o,timeItem:{itemType:oI,itemValue:e}})}));return GD({tournamentRecord:n,drawDefinition:i,matchUpId:o,timeItem:{itemValue:a,itemType:oI}})}function $D(e){const t=uy(e,[{[Uu]:!0},{[yu]:!0},{[vu]:!0},{[Ru]:!0}]);if(t[xu])return t;const r=BD(e,[{[Vu]:ku,attr:{[Nu]:!0}}]);if(r[xu])return r;const{tournamentRecord:n,drawDefinition:i,participantId:a,matchUpId:o}=e,s=xD({matchUp:r?.matchUp?.matchUp});if(s?.error)return s;const{checkedInParticipantIds:c,allRelevantParticipantIds:u}=s??{};if(c?.includes(a))return{...Ni};if(!u?.includes(a))return{[xu]:Io};return GD({tournamentRecord:n,drawDefinition:i,matchUpId:o,timeItem:{itemValue:a,itemType:aI}})}function WD(e){const t=uy(e,[{[vu]:!0,[yu]:!0,[Ru]:!0}]);if(t.error)return t;const r=e.tournamentId??e.activeTournamentId,n=e.tournamentRecord??(r&&e.tournamentRecords?.[r]),{participantId:i,matchUpId:a,drawDefinition:o}=e;if(!n)return{error:Fi};const s=BD(e,[{[Vu]:ku,[xu]:La}]),c=s.matchUp?.matchUp;if(!c)return{error:La};const{checkedInParticipantIds:u=[]}=xD({matchUp:c});return i&&u.includes(i)?qD({tournamentRecord:n,drawDefinition:o,participantId:i,matchUpId:a,matchUp:c}):$D({tournamentRecord:n,drawDefinition:o,participantId:i,matchUpId:a,matchUp:c})}function HD({inContextDualMatchUp:e,drawDefinition:t,tournamentId:r,dualMatchUp:n,eventId:i}){if(n){e||(e=xv({matchUpId:n.matchUpId,inContext:!0,drawDefinition:t})?.matchUp);const{extension:a}=Wl({element:t,name:mi}),o=Jc(a?.value||{},!1,!0),s=({displaySideNumber:e,drawPosition:t,sideNumber:r})=>({drawPosition:t,sideNumber:r,displaySideNumber:e});n.sides=e?.sides?.map((e=>{const t=e.participantId,r=t&&o[t]||void 0,{lineUp:i,...a}=n.sides?.find((({sideNumber:t})=>t===e.sideNumber))??{},c=i?.length?i:r;return{...s(e),...a,lineUp:c}})),Vp({context:"ensureSidLineUps",matchUp:n,drawDefinition:t,tournamentId:r,eventId:i})}}function zD(e){const t=tn(e);if(t.error)return t;const r="replaceTieMatchUpParticipantid",{existingParticipantId:n,tournamentRecord:i,newParticipantId:o,drawDefinition:s,substitution:c,event:d}=e;if(!n||!o)return a({result:{error:Do},stack:r});if(n===o)return{...Ni};const{inContextDualMatchUp:p,inContextTieMatchUp:l,collectionPosition:m,collectionId:f,dualMatchUp:h,tieMatchUp:g,tieFormat:I}=t,U=l?.matchUpType,y=l?.sides?.find((e=>e.participant?.participantId===n||e.participant?.individualParticipantIds?.includes(n)));if(!y)return{error:wo};const S=pt({tournamentRecord:i,participantFilters:{participantIds:[n,o]}})?.participants??[];if(2!==S.length)return a({result:{error:Do},stack:r});if(S[0].participantType!==S[1].participantType)return a({result:{error:So},stack:r});const{appliedPolicies:v}=te({tournamentRecord:i,drawDefinition:s,event:d}),T=e.policyDefinitions?.[Zu]??v?.[Zu]??qy[Zu],P=S.find((({participantId:e})=>e===o));if(!1!==(e.enforceGender??T?.participants?.enforceGender)&&[Lf,jf].includes(l?.gender)&&l?.gender!==P?.person?.sex)return{error:go,info:"Gender mismatch"};const D=T?.processCodes?.substitution;HD({tournamentId:i.tournamentId,eventId:d.eventId,inContextDualMatchUp:p,drawDefinition:s,dualMatchUp:h});const w=h?.sides?.find((({sideNumber:e})=>e===y.sideNumber));if(!w)return a({result:{sideNumber:y.sideNumber,existingParticipantId:n,error:ws},stack:r});const b=l?.sides?.flatMap((e=>e.participant?.individualParticipantIds||e.participant?.participantId||[]));if(b?.includes(o))return a({result:{error:Oo},stack:r});const R=p?.sides?.find((({sideNumber:e})=>e===y.sideNumber))?.participantId,N=w.lineUp,M=N?.find((({participantId:e})=>o===e)),A=N?.reduce(((e,t)=>t.substitutionOrder>e?t.substitutionOrder:e),0),E=N?.map((e=>{const t=L(e,!1,!0);if(![n,o].includes(t.participantId))return t;if(!c&&[n,o].includes(t.participantId)&&(t.collectionAssignments=t.collectionAssignments?.filter((e=>!(e.collectionPosition===m&&e.collectionId===f)))),c&&n===t.participantId&&(t.collectionAssignments=t.collectionAssignments.map((e=>e.collectionPosition===m&&e.collectionId===f&&void 0===e.substitutionOrder?{...e,substitutionOrder:A}:e))),t.participantId===o){t.collectionAssignments||(t.collectionAssignments=[]);const e={collectionId:f,collectionPosition:m};c&&(e.previousParticipantId=n,e.substitutionOrder=(A??0)+1),t.collectionAssignments.push(e)}return t}))??[];if(!M){const e={collectionId:f,collectionPosition:m};c&&(e.substitutionOrder=(A??0)+1,e.previousParticipantId=n);const t={collectionAssignments:[e],participantId:o};E.push(t)}const C=U===hf,{assignedParticipantIds:O}=Re({lineUp:N,collectionPosition:m,collectionId:f}),{assignedParticipantIds:F}=Re({lineUp:E,collectionPosition:m,collectionId:f});if(w.lineUp=E,R&&I){const e=Ge({participantId:R,lineUp:E,drawDefinition:s,tieFormat:I});if(e.error)return a({result:e,stack:r})}else console.log("team participantId not found");let k,_;if(C){const{tournamentRecord:t}=e;let n=Ne({participantIds:F,tournamentRecord:t});if(!n.participant){const e=Jr({returnParticipant:!0,pairOverride:!0,tournamentRecord:t,participant:{participantRole:Zv,individualParticipantIds:F,participantType:Um}});if(e.error)return a({result:e,stack:r});k=e.participant?.participantId}n=Ne({participantIds:O,tournamentRecord:t});const i=n.participant?.participantId;if(i){rn({participantIds:[i],tournamentRecord:t}).success&&(_=i)}}if(c||1===y.substitutions?.length){if(c)D&&g&&(g.processCodes=u([...g?.processCodes??[],...D]));else for(const e of D||[]){const t=g?.processCodes?.lastIndexOf(e);void 0!==t&&g?.processCodes?.splice(t,1)}g&&q({tournamentId:i?.tournamentId,matchUp:g,context:r,drawDefinition:s})}return h&&q({tournamentId:i?.tournamentId,matchUp:h,context:r,drawDefinition:s}),{...Ni,modifiedLineUp:E,participantRemoved:_,participantAdded:k}}function YD(e){const t=tn(e);if(t.error)return t;const r="assignTieMatchUpParticipantId";let n=e.teamParticipantId;const{tournamentRecord:i,drawDefinition:o,participantId:s,event:c}=e;if(!s)return a({result:{error:Do},stack:r});if(e.sideNumber&&![1,2].includes(e.sideNumber))return a({result:{error:Qa},stack:r});const{inContextDualMatchUp:u,inContextTieMatchUp:p,relevantAssignments:l,collectionPosition:m,teamParticipants:f,collectionId:h,matchUpType:g,dualMatchUp:I,tieFormat:U}=t,y=p?.sides?.flatMap((e=>e.participant?.individualParticipantIds||e.participant?.participantId||[]));if(y?.includes(s))return a({result:{...Ni},stack:r});n=n??(e.sideNumber?u?.sides?.find((t=>t.sideNumber===e.sideNumber))?.participantId:void 0);const S=pt({participantFilters:{participantIds:[s]},tournamentRecord:i})?.participants?.[0];if(!S)return a({result:{error:wo},stack:r});const{appliedPolicies:v}=te({tournamentRecord:i,drawDefinition:o,event:c}),T=e.policyDefinitions?.[Zu]??v?.[Zu]??qy[Zu];if(!1!==(e.enforceGender??T?.participants?.enforceGender)&&[Lf,jf].includes(p?.gender)&&p?.gender!==S.person?.sex)return{error:go,info:"Gender mismatch"};const{individualParticipantIds:P,participantType:D}=S;if(g===mf&&D!==gm)return{error:So};const w=D===gm?[s]:P,b=n&&f?.find((({participantId:e})=>e===n))||f?.find((({individualParticipantIds:e})=>d(w,e)));if(!b)return{error:vs};if(n||(n=b.participantId),!n)return{error:wo};const R=l?.find((e=>e.participantId===b?.participantId)),N=R?.drawPosition,M=I?.sides?.find((e=>e.participantId===n))?.sideNumber,A=p?.sides?.find((e=>N&&e.drawPosition===N))?.sideNumber,E=M??A??e.sideNumber;if(!U)return{error:ka};const C=U.collectionDefinitions?.find((e=>e.collectionId===h));if(!C)return{error:Fa};HD({tournamentId:i.tournamentId,eventId:c.eventId,inContextDualMatchUp:u,drawDefinition:o,dualMatchUp:I});const O=I?.sides?.find((e=>e.sideNumber===E)),F=p?.sides?.find((e=>e.sideNumber===E)),k=O?.lineUp??Me({participantId:n,drawDefinition:o})?.lineUp,_=k?.filter((e=>e.collectionAssignments?.find((e=>e.collectionPosition===m&&e.collectionId===h&&!e.previousParticipantId)))),x=_?.map((e=>e?.participantId)),L=x?.length>1&&x||(D===Um?S.individualParticipantIds:[s]),V=nn({collectionPosition:m,teamParticipantId:n,dualMatchUpSide:O,drawDefinition:o,participantIds:L,collectionId:h});if(V.error)return a({result:V,stack:r});const{modifiedLineUp:B}=V;let j;if(g===hf){if(D!==Um){let e=QD({collectionPosition:m,teamParticipantId:n,drawDefinition:o,modifiedLineUp:B,participantId:s,collectionId:h,tieFormat:U});if(e?.error)return a({result:e,stack:r});if(e=function({side:e}){let t;if(e.participant){const r=e.participant.individualParticipantIds||[];if(1===r.filter(Boolean).length){const{participant:e}=Ne({participantIds:r,tournamentRecord:i});r.push(s);const{participant:n}=Ne({participantIds:r,tournamentRecord:i});if(!n&&e){e.individualParticipantIds=r;const t=an({pairOverride:!0,tournamentRecord:i,participant:e});if(t.error)return t}else t=e?.participantId}}else{const e=Jr({participant:{individualParticipantIds:[s],participantRole:Zv,participantType:Um},pairOverride:!0,tournamentRecord:i});if(e.error)return e}return{...Ni,deletedParticipantId:t}}({side:F}),e.error)return e;j=e.deletedParticipantId,O&&(O.lineUp=B),I&&q({tournamentId:i?.tournamentId,matchUp:I,context:r,drawDefinition:o})}else if(D===Um)for(const e of L)QD({collectionPosition:m,teamParticipantId:n,drawDefinition:o,modifiedLineUp:B,participantId:e,collectionId:h,tieFormat:U})}else{const e=QD({collectionPosition:m,teamParticipantId:n,drawDefinition:o,modifiedLineUp:B,participantId:s,collectionId:h,tieFormat:U});if(e?.error)return e}if(O&&(O.lineUp=B),I&&q({tournamentId:i?.tournamentId,matchUp:I,context:r,drawDefinition:o}),j){const{error:e}=rn({participantIds:[j],tournamentRecord:i});e&&console.log("cleanup")}return{...Ni,modifiedLineUp:B}}function QD({collectionPosition:e,teamParticipantId:t,drawDefinition:r,modifiedLineUp:n,participantId:i,collectionId:a,tieFormat:o}){const s=Me({participantId:t,drawDefinition:r})?.lineUp,c=(n||s)?.find((e=>e?.participantId===i)),u={collectionId:a,collectionPosition:e};if(c)c.collectionAssignments.push(u);else{const e={collectionAssignments:[u],participantId:i};n.push(e)}return Ge({participantId:t,lineUp:n,drawDefinition:r,tieFormat:o})}function KD(e){const{tournamentRecord:t,drawDefinition:r,participantId:n,event:i}=e,o="removeTieMatchUpParticiapantId";if(!n)return a({result:{error:Do},stack:o});const s=tn(e);if(s.error)return s;const{appliedPolicies:c}=te({tournamentRecord:t,drawDefinition:r,event:i}),u=e.policyDefinitions?.[Zu]??c?.[Zu]??qy[Zu],d=u?.processCodes?.substitution,{inContextDualMatchUp:p,inContextTieMatchUp:l,relevantAssignments:m,collectionPosition:f,teamParticipants:h,collectionId:g,matchUpType:I,dualMatchUp:U,tieMatchUp:y,tieFormat:S}=s;if(!U)return a({result:{error:Ba},stack:o});const v=l?.sides?.find((e=>e.participant?.participantId===n||e.participant?.individualParticipantIds?.includes(n)));if(!v)return a({result:{error:wo},stack:o});if(!v.substitutions?.length&&(Pr({score:l?.score})||l?.winningSide))return a({result:{error:Ms},stack:o});const T=p?.sides?.find((({sideNumber:e})=>e===v.sideNumber))?.participantId;if(!T)return a({result:{error:wo},stack:o});const P=pt({participantFilters:{participantIds:[n]},tournamentRecord:t})?.participants?.[0];if(!P)return a({result:{error:wo},stack:o});if(I===mf&&P.participantType===Um)return a({result:{error:go},stack:o});const D=P.participantType===gm?[n]:P.individualParticipantIds;HD({tournamentId:t.tournamentId,eventId:i.eventId,inContextDualMatchUp:p,drawDefinition:r,dualMatchUp:U});let w=U.sides?.find((({sideNumber:e})=>e===v.sideNumber));if(!w&&(U.sides?.filter((({lineUp:e})=>!e)).length||0)<2){const e=h?.map((({participantId:e})=>({drawPosition:m?.find((t=>t.participantId===e))?.drawPosition,teamParticipantId:e})));w=U.sides?.find((t=>e?.find((({drawPosition:e})=>e===t.drawPosition))?.teamParticipantId===T))}if(!w)return a({result:{error:wo,context:{participantId:n}}});const{modifiedLineUp:b,previousParticipantIds:R}=nn({collectionPosition:f,teamParticipantId:T,dualMatchUpSide:w,participantIds:D,drawDefinition:r,collectionId:g});if(w.lineUp=b,T&&S&&Ge({participantId:T,lineUp:b,drawDefinition:r,tieFormat:S}),I===hf&&P.participantType===gm){const e=l?.sides?.find((e=>e.sideNumber===w?.sideNumber)),{participantId:r}=e??{},i=r&&pt({participantFilters:{participantIds:[r]},tournamentRecord:t,withDraws:!0})?.participants?.[0];if(!i)return a({result:{error:wo},stack:o});{const e=i?.individualParticipantIds?.filter((e=>e!==n))??[];if(R&&e.push(...R),e.length>2)return a({result:{error:Uo},stack:o});if(i.draws?.length){if(1===e.length){const{participant:r}=Ne({participantIds:e,tournamentRecord:t});if(!r){const r=Jr({participant:{participantRole:Zv,individualParticipantIds:e,participantType:Um},pairOverride:!0,tournamentRecord:t});if(r.error)return a({result:r,stack:o})}}}else if(e.length){i.individualParticipantIds=e;const r=an({participant:i,pairOverride:!0,tournamentRecord:t});if(r.error)return a({result:r,stack:o})}else{const e=rn({participantIds:[r],tournamentRecord:t});e.error&&console.log("cleanup",{result:e})}}}if(1===v.substitutions?.length){const e=l?.sides?.find((e=>e.sideNumber!==v.sideNumber));if(!e?.substitutions?.length&&y?.processCodes?.length){for(const e of d||[]){const t=y.processCodes.lastIndexOf(e);y.processCodes.splice(t,1)}q({tournamentId:t?.tournamentId,matchUp:y,context:o,drawDefinition:r})}}return q({tournamentId:t?.tournamentId,matchUp:U,context:o,drawDefinition:r}),{...Ni,modifiedLineUp:b}}function JD({tournamentRecord:e,drawDefinition:t,sideNumber:r,matchUpId:n,event:i}){if(!e)return{error:Fi};if(!t)return{error:Li};if(!n)return{error:_a};if(!r)return{error:Za};if(![1,2].includes(r))return{error:ys,sideNumber:r};const{matchUp:a,structure:o}=xv({drawDefinition:t,matchUpId:n,event:i});if(!a)return{error:La};return o?.structures||t.drawType&&t.drawType!==ll||o?.matchUps?.find((({roundPosition:e})=>!!e))?{error:Zi}:(a.sides?.forEach((e=>{e.sideNumber===r&&delete e.participantId})),Vp({tournamentId:e?.tournamentId,context:"assignSideParticipant",drawDefinition:t,matchUp:a}),{...Ni})}function ZD({existingMatchUpStatus:e,matchUpFormat:t,matchUpStatus:r,winningSide:n,score:i}){if("object"!=typeof i)return{error:ys};const{sets:a,scoreStringSide1:o,scoreStringSide2:s}=i,c="scoreString must be a string!";if(void 0!==o&&"string"!=typeof o)return{error:ys,info:c};if(void 0!==s&&"string"!=typeof s)return{error:ys,info:c};if(void 0!==a&&!Array.isArray(a))return{error:ys,info:Vt("sets")};if(a?.length){const o=a.map((e=>e?.setNumber)).filter(Boolean);if(o.length!==u(o).length)return{error:ys,info:"setNumbers not unique"};for(const e of a){const{side1Score:t,side2Score:r,side1TiebreakScore:n,side2TiebreakScore:i,side1PointScore:a,side2PointScore:o,winningSide:s,setNumber:c}=e;if(![[t,r],[n,i],[a,o]].filter((e=>e.some((e=>void 0!==e)))).every((e=>e.every((e=>Fe(e))))))return{error:ys,info:"non-numeric values"};if(![c,s].filter((e=>void 0!==e)).every((e=>Fe(e))))return{error:ys,info:"non-numeric values"};if(s&&![1,2].includes(s))return{error:ys,info:"winningSide must be 1 or 2"}}const{valid:s}=fn({existingMatchUpStatus:e,matchUpStatus:r,matchUpFormat:t,winningSide:n,score:i});if(!s)return{error:co,info:"score is invalid for matchUpFormat or winningSide does not match calculated winningSide"}}return{valid:!0}}function XD(e){const t="setMatchUpStatus";e.matchUpStatus&&[Km,qm].includes(e.matchUpStatus)&&(e.score=void 0);const{allowChangePropagation:r,disableScoreValidation:n,tournamentRecords:s,tournamentRecord:c,disableAutoCalc:u,enableAutoCalc:d,drawDefinition:p,matchUpStatus:l,winningSide:m,matchUpId:f,event:h,score:g}=e;if(!p)return{error:Li};if(l&&[Lm,Wm,km,Qm].includes(l)&&m)return{error:ys,winningSide:m,matchUpStatus:l};if(![void 0,...Xm].includes(l))return a({result:{error:Aa},info:"matchUpStatus does not exist",stack:"setMatchUpStatus"});const I=se({drawDefinition:p}),{matchUps:U}=ue({nextMatchUps:!0,inContext:!0,drawDefinition:p,matchUpsMap:I,event:h}),y=I.drawMatchUps.find((e=>e.matchUpId===f)),S=U?.find((e=>e.matchUpId===f));if(!y||!U)return{error:La};if((y.winningSide||m)&&l===xm)return{context:"Cannot have Bye with winningSide",error:Ma,matchUpStatus:l};const v=S?.structureId,{structure:T}=w({drawDefinition:p,structureId:v}),P=S?.drawPositions?.filter(Boolean);let D;if(y.matchUpType===If){if(u)o({extension:{name:ci,value:!0},element:y});else if(d){const t=y.winningSide;i({name:ci,element:y});const{winningSide:r,scoreStringSide1:n,scoreStringSide2:a,set:o}=cn({drawDefinition:p,matchUpsMap:I,structure:T,matchUp:y,event:h}),s={scoreStringSide1:n,scoreStringSide2:a,sets:o?[o]:[]};D=r!==t,Object.assign(e,{winningSide:r,dualWinningSideChange:D,projectedWinningSide:r,score:s})}mn({tournamentId:c?.tournamentId,inContextDualMatchUp:S,eventId:h?.eventId,dualMatchUp:y,drawDefinition:p})}if(y.matchUpType===If&&l&&[_m].includes(l))return{error:ys,info:"Not supported for matchUpType: TEAM"};const b=S?.matchUpTieId,R=de({matchUpId:b||f,inContextDrawMatchUps:U,drawDefinition:p});if(g&&y.matchUpType!==If&&!n){const e=y.matchUpFormat??T?.matchUpFormat??p?.matchUpFormat??h?.matchUpFormat,t=ZD({existingMatchUpStatus:y.matchUpStatus,matchUpFormat:e,matchUpStatus:l,winningSide:m,score:g});if(t.error)return t}const N=y?.sides?[]:Q({drawDefinition:p,structureId:v}).positionAssignments,M=2===S?.sides?.map((e=>e.participantId)).filter(Boolean).length||2===P?.length&&N?.filter((e=>P.includes(e.drawPosition))).every((e=>e.participantId));if(l&&Zm.includes(l)&&!M)return a({info:"present in participantRequiredMatchUpStatuses",context:{matchUpStatus:l,bothSideParticipants:M},result:{error:Aa}});const A=te({policyTypes:[rd,ad],tournamentRecord:c,drawDefinition:p,event:h})?.appliedPolicies??{};"object"==typeof e.policyDefinitions&&Object.assign(A,e.policyDefinitions);const E=S?.stage===$p&&1===S.finishingRound,C=E&&m,O=E&&y.winningSide&&!m&&(!e.matchUpStatus||e.matchUpStatus&&Kt({matchUpStatus:e.matchUpStatus}))&&(!e.outcome||!Pr({outcome:e.outcome})),F=C&&m!==y.winningSide&&y.winningSide;if(Object.assign(e,{inContextDrawMatchUps:U,qualifierAdvancing:C,qualifierChanging:F,removingQualifier:O,inContextMatchUp:S,appliedPolicies:A,matchUpTieId:b,matchUpsMap:I,targetData:R,structure:T,matchUp:y}),b){const{matchUp:t}=Jt({matchUpId:b,inContext:!0,drawDefinition:p,matchUpsMap:I,event:h});if(t){const r=we({matchUp:t,drawDefinition:p,structure:T,event:h})?.tieFormat,{projectedWinningSide:n}=on({drawDefinition:p,matchUpStatus:l,dualMatchUp:t,matchUpsMap:I,winningSide:m,tieFormat:r,structure:T,matchUp:y,event:h,score:g});D=n!==t.winningSide,Object.assign(e,{isCollectionMatchUp:!0,dualWinningSideChange:D,projectedWinningSide:n,matchUpTieId:b,dualMatchUp:t,tieFormat:r})}}const k=Yt(e),_=Qt({matchUpStatus:l});if(!b){if(k&&!m&&(l&&Kt({matchUpStatus:l})||l&&[qm,Gm].includes(l)))return{error:Ma,activeDownstream:k,winningSide:m};if(m&&m===y.winningSide&&l&&!_)return{context:"winningSide must include directing matchUpStatus",error:Ma,directingMatchUpStatus:_,matchUpStatus:l}}const{schedule:x}=e;if(x){const e=un({disableNotice:!0,tournamentRecords:s,tournamentRecord:c,drawDefinition:p,matchUpId:f,schedule:x});if(e.error)return e}const L=y.matchUpType!==If&&!D&&m&&y.winningSide&&y.winningSide!==m;if(r&&L&&y.roundPosition)return dn(e);const V=m&&!b||e.projectedWinningSide;me({activeDownstream:k,matchUpWinner:V,method:t,winningSide:m});const B=!k&&sn(e)||V&&function(e){const{matchUp:t,winningSide:r,matchUpTieId:n,dualWinningSideChange:i}=e;return r===t.winningSide||n&&!i?ew(e):a({stack:"winningSideWithDownstreamDependencies",result:{error:ho},context:{winningSide:r,matchUp:t}})}(e)||_&&ew(e)||{error:Ts};return a({result:B,stack:t})}function ew(e){const{tournamentRecord:t,matchUp:r,event:n}=e,i=e.isCollectionMatchUp&&r.winningSide&&!e.winningSide&&!Pr({score:e.score}),a=e.isCollectionMatchUp?e.matchUpStatus||i&&Qm||Vm:e.matchUpStatus||Vm,o=e.removeScore||[Lm,Km].includes(a)&&![Wm,km].includes(a),s=ln({...e,matchUpStatus:a,removeWinningSide:i,context:"sms",removeScore:o});if(s.error)return s;if(e.isCollectionMatchUp){const{matchUpTieId:r,drawDefinition:i,matchUpsMap:a}=e,o=pn({appliedPolicies:e.appliedPolicies,matchUpId:r,tournamentRecord:t,drawDefinition:i,matchUpsMap:a,event:n});if(o.error)return o;Object.assign(s,{tieMatchUpResult:o})}return s}function tw({tournamentRecord:e,drawDefinition:t,matchUpId:r,event:n}){if(!t)return{error:Li};const{matchUp:i}=xv({drawDefinition:t,matchUpId:r,event:n});return i?.matchUpType!==gf?{error:ja}:XD({enableAutoCalc:!0,tournamentRecord:e,drawDefinition:t,matchUpId:r,event:n})}function rw({drawDefinition:e,event:t,matchUpId:r}){if(!e)return{error:Li};if(!r)return{error:_a};const{matchUp:n}=xv({drawDefinition:e,event:t,matchUpId:r});return n?fd({name:ai,element:n}):{error:La}}function nw(e){return function({substituteParticipantId:e,existingParticipantId:t,tournamentRecord:r,drawDefinition:n,sideNumber:i,matchUpId:a,event:o}){const s="substituteParticipant";if(!n)return{error:Li};if(!a)return{error:_a};if(!t||!e)return pd({result:{error:Do},stack:s});const{matchUp:c}=xv({drawDefinition:n,matchUpId:a,event:o});if(!c)return{error:La};if(!c.collectionId)return pd({result:{error:ja},stack:s});const u=Mm({drawDefinition:n}),{matchUps:d}=Em({tournamentParticipants:r?.participants,inContext:!0,drawDefinition:n,matchUpsMap:u}),p=d?.find((e=>e.matchUpId===a)),l=d?.find((e=>e.matchUpId===p?.matchUpTieId)),m=l?.sides?.find((e=>e.participant.individualParticipants.some((({participantId:e})=>e===t))));if(!m||i&&m.sideNumber!==i)return{error:Io};const f=m.participant?.individualParticipants?.map(Rd).filter((e=>e!==t));return f?.includes(e)?zD({newParticipantId:e,tieMatchUpId:a,existingParticipantId:t,substitution:!0,tournamentRecord:r,drawDefinition:n,event:o}):pd({result:{error:Io},stack:s})}(e)}function iw({drawDefinition:e,matchUpId:t,event:r}){if(!e)return{error:Li};const{matchUp:n}=xv({drawDefinition:e,matchUpId:t,event:r});return gd({extension:{name:ci,value:!0},element:n})}function aw(e){const t="setMatchUpFormat",{tournamentRecord:r,drawDefinition:n,scheduledDates:i,stageSequences:a,matchUpFormat:o,structureId:s,eventType:c,matchUpId:u,eventId:d,stages:p,drawId:l,event:m,force:f}=e;if(!r)return{error:Fi};if(!o)return{error:Oa};if(o&&!uv({matchUpFormat:o}))return pd({result:{error:Na,matchUpFormat:o},stack:t});if(i&&!Array.isArray(i))return pd({result:{error:ys,scheduledDates:i},stack:t});if(c&&![qf,Wf].includes(c))return pd({result:{error:Ia},stack:t});let h=0;const g=e.structureIds||s&&[s].filter(Boolean)||[],I=e.eventIds||d&&[d].filter(Boolean)||[],U=e.drawIds||l&&[l].filter(Boolean)||[];if((s||g?.length)&&!n)return pd({result:{error:Li},stack:t});if(l&&u&&n){const e=Lv({tournamentRecord:r,drawDefinition:n,matchUpFormat:o,structureIds:g,structureId:s,matchUpId:u});if(e.error)return e;h+=1}const y=e=>{const n=[];for(const s of e.structures||[]){if(Array.isArray(p)&&!p.includes(s.stage)||Array.isArray(a)&&!a.includes(s.stageSequence)||g?.length&&!g.includes(s.structureId))continue;g?.length&&s.matchUpFormat!==o&&(s.matchUpFormat=o,n.push(s.structureId),h+=1);const c=(f||i)&&Kf({matchUpFilters:{matchUpStatuses:[Qm]},structure:s}).matchUps,u=i&&Kf({matchUpFilters:{matchUpStatuses:[Qm]},contextFilters:{scheduledDates:i},afterRecoveryTimes:!1,inContext:!0,structure:s}).matchUps;if(c?.length){const n=u?u.map(Nd):c.map(Nd);for(const a of c)n.includes(a.matchUpId)&&(a.matchUpFormat=i?.length?o:void 0,Vp({tournamentId:r?.tournamentId,eventId:m?.eventId,context:t,drawDefinition:e,matchUp:a}))}}return n.length||e.matchUpFormat===o||(e.matchUpFormat=o,h+=1),n};for(const e of r.events||[])if(!(I?.length&&!I.includes(e.eventId)||c&&c!==e.eventType||c===zf))if(Array.isArray(a)||Array.isArray(p)||g?.length||U?.length)for(const t of e.drawDefinitions||[]){if(Array.isArray(U)&&!U.includes(t.drawId))continue;jp({structureIds:y(t),drawDefinition:t})}else e.matchUpFormat!==o&&(e.matchUpFormat=o,h+=1);return h?{...Ni,modificationsCount:h}:{...Ni,info:ps}}function ow({inheritance:e=!0,tournamentRecord:t,drawDefinition:r,matchUpId:n,event:i}){if(!r)return{error:Li};const a=xv({drawDefinition:r,matchUpId:n})?.matchUp;if(!a?.tieMatchUps)return{error:ja};const o=xv({inContext:!0,drawDefinition:r,matchUpId:n,event:i})?.matchUp;let s=0;return(a?.sides||[]).forEach((e=>{e.lineUp&&delete e.lineUp})),(o?.sides||[]).forEach((n=>{if(s+=1,!1===e){const e=o?.tieFormat,t=n.participantId;e&&t&&TU({drawDefinition:r,participantId:t,lineUp:[],tieFormat:e})}Vp({tournamentId:t?.tournamentId,context:"resetMatchUpLineUps",eventId:i?.eventId,drawDefinition:r,matchUp:a})})),{...Ni,modificationsCount:s}}function sw(e){const{winnerFirst:t=!0,addOutcomeString:r,reversed:n=!1,matchUpStatus:i,matchUpFormat:a,autoComplete:o,winningSide:s,sets:c}=e;if(!c)return{error:Za,info:"missing sets"};const u=a&&QI(a),{bestOf:d,finalSetFormat:p,setFormat:l}=u??{},m=n||!(!t||!s||1===s),f=r?function({matchUpStatus:e}){const t={[zm]:"RET",[Km]:"WO",[Gm]:"DF/DF",[qm]:"WO/WO",[Ym]:"SUS",[km]:"ABN",[jm]:"DEF",[Bm]:"DR"};return e&&t[e]||""}({matchUpStatus:i}):"",h=c?.sort(cw).map((function(e){const t=d&&e.setNumber===d&&p?p:l,r=t?.tiebreakSet||(f=e,!(kd(f?.side1Score)||kd(f?.side2Score))&&(e=>kd(e?.side1TiebreakScore)||kd(e?.side2TiebreakScore))(e)),{side1Score:n,side2Score:i,side1TiebreakScore:a,side2TiebreakScore:s}=e,c=a||(kd(a)||o?0:""),u=s||(kd(s)||o?0:"");var f;if(r){return`[${(m?[u,c]:[c,u]).join("-")}]`}const h=Math.min(c,u),g=h?`(${h})`:"",I=n||(kd(n)||o?0:""),U=i||(kd(i)||o?0:"");let y=m?`${[U,I].join("-")}${g}`:`${[I,U].join("-")}${g}`;["-"," "].includes(y)&&(y="");return y})).filter(Boolean).join(" ")||"";return f?2===s?`${f} ${h}`:`${h} ${f}`:h}function cw(e,t){return e.setNumber-t.setNumber}function uw(e){const{matchUpFormat:t,matchUpStatus:r,winningSide:n,score:i}=e;if(!i)return{sets:[]};const a=i.sets||[];let o=sw({winnerFirst:!1,matchUpFormat:t,matchUpStatus:r,sets:a}),s=sw({winnerFirst:!1,reversed:!0,matchUpFormat:t,matchUpStatus:r,sets:a});const c=sw({matchUpFormat:t,matchUpStatus:r,winningSide:n,sets:a}),u=o===c?s:o;return n&&(o=1===n?c:u,s=2===n?c:u),{score:{sets:a,scoreStringSide1:o,scoreStringSide2:s}}}function dw(e){const t=US(e);if(!e.drawDefinition){const r=e.tournamentRecord??(e.tournamentId&&t[e.tournamentId]);e.tournamentRecord||(e.tournamentRecord=r);const n=ly({eventId:e.eventId,drawId:e.drawId,tournamentRecord:r});if(n.error)return n;n.drawDefinition&&(e.drawDefinition=n.drawDefinition),e.event=n.event}const{disableScoreValidation:r,policyDefinitions:n,tournamentRecord:i,disableAutoCalc:a,enableAutoCalc:o,drawDefinition:s,matchUpFormat:c,matchUpId:u,schedule:d,event:p,notes:l}=e;if(!s)return{error:ra};if(!u)return{error:_a};const{policy:m}=YU({policyType:ad,tournamentRecord:i,event:p}),f=void 0!==e.allowChangePropagation&&e.allowChangePropagation||void 0!==m?.allowChangePropagation&&m.allowChangePropagation||void 0,{outcome:h}=e;if(c){const e=Lv({tournamentRecord:i,drawDefinition:s,matchUpFormat:c,matchUpId:u,event:p});if(e.error)return e}if(h?.score?.sets&&!h.score.scoreStringSide1){const{score:e}=uw(h);h.score=e,h.score.sets=h.score.sets.filter((e=>e.side1Score||e.side2Score||e.side1TiebreakScore||e.side2TiebreakScore))}return XD({matchUpStatusCodes:h?.matchUpStatusCodes,matchUpStatus:h?.matchUpStatus,winningSide:h?.winningSide,allowChangePropagation:f,disableScoreValidation:r,score:h?.score,tournamentRecords:t,policyDefinitions:n,tournamentRecord:i,disableAutoCalc:a,enableAutoCalc:o,drawDefinition:s,matchUpFormat:c,matchUpId:u,schedule:d,event:p,notes:l})}function pw(e){if(!e?.outcomes)return{error:Za};if(!Array.isArray(e.outcomes))return{error:Za,info:{outcomes:e.outcomes}};const t=e.tournamentRecords||e.tournamentRecord&&{[e.tournamentRecord.tournamentId]:e.tournamentRecord}||{},r=e.outcomes??[],n=r.reduce(((e,t)=>e.includes(t.tournamentId)?e:e.concat(t.tournamentId)),[]);for(const e of n){const n=t[e];if(!n)return{error:Fi};const i=r.filter((t=>t.tournamentId===e));if(i.length){const e=lw({outcomes:i,tournamentRecord:n});if(e.error)return e}}return{...Ni}}function lw(e){const{tournamentRecords:t,tournamentRecord:r,outcomes:n,policyDefinitions:i}=e,a={};n.forEach((e=>{const{eventId:t}=e;a[t]||(a[t]=[]),a[t].push(e)}));for(const e of Object.keys(a)){const{event:n}=ly({tournamentRecord:r,eventId:e});for(const o of a[e]){const{drawId:e}=o,a=n?.drawDefinitions?.find((t=>t.drawId===e));if(a&&e){const{matchUpFormat:s,matchUpId:c}=o,u=dw({schedule:o?.schedule,tournamentRecords:t,policyDefinitions:i,tournamentRecord:r,drawDefinition:a,matchUpFormat:s,matchUpId:c,outcome:o,drawId:e,event:n});if(u.error)return u}}}return{...Ni}}function mw(e){return function({drawDefinition:e,matchUpId:t,outcome:r,matchUp:n}){if(!n&&!e)return{error:Li};if(!r)return{error:Za,info:"missing outcome"};if(!n&&!t)return{error:Ba};if(!n){const r=xv({drawDefinition:e,matchUpId:t});if(r.error)return r;n=r.matchUp}return"object"==typeof r&&r.score?.scoreStringSide1&&r.score?.scoreStringSide2?gd({element:n,extension:{name:ai,value:r}}):{error:ys}}(e)}function fw(e){const{exitWhenNoValues:t,drawDefinition:r,matchUpStatus:n,removeScore:a,matchUpsMap:o,matchUpId:c,event:u}=e,d=e.tournamentRecords||e.tournamentRecord&&{[e.tournamentRecord?.tournamentId]:e.tournamentRecord}||{},p=e.tournamentId||e.tournamentRecord?.tournamentId;d&&hn({tournamentRecords:d,...e});const l=p&&d[p];if(!l)return{error:Fi};const m=Jt({drawDefinition:r,event:u,matchUpId:c});if(m.error)return m;if(!m.matchUp)return{error:La};const{matchUp:f,structure:h}=m;if(!f.tieMatchUps)return{error:ja};mn({tournamentId:l?.tournamentId,eventId:u?.eventId,dualMatchUp:f,drawDefinition:r});const{extension:g}=s({name:ci,element:f});if(g?.value){if(!a)return{...Ni,score:f.score};i({element:f,name:ci})}const I=we({drawDefinition:r,structure:h,matchUp:f,event:u})?.tieFormat;f.tieFormat=ir(I);const U=cn({drawDefinition:r,matchUpsMap:o,structure:h,matchUp:f,event:u}),{winningSide:y,set:S,scoreStringSide1:v,scoreStringSide2:T}=U,P=S?.side1Score||S?.side2Score;if(t&&!f.score&&!P)return{...Ni};const D={scoreStringSide1:v,scoreStringSide2:T,sets:S?[S]:[]},w=y&&[1,2].includes(y),b=w&&Vm||_t({matchUpStatus:n??f.matchUpStatus,tieMatchUps:f.tieMatchUps,winningSide:f.winningSide,score:D})&&$m||Qm,R=!(!f.winningSide||w),N=f.tieMatchUps.find((({score:e,winningSide:t,matchUpStatus:r})=>e?.sets?.length&&(e.sets[0].side1Score||e.sets[0].side2Score)||r&&rf.includes(r)||t));let M;if(f.tieFormat&&!w&&!N){const e=we({drawDefinition:r,structure:h,event:u})?.tieFormat;e&&JSON.stringify(I)===JSON.stringify(e)&&(f.tieFormatId=void 0,f.tieFormat=void 0,M=!0)}return ln({appliedPolicies:e.appliedPolicies,matchUpStatus:b,score:D,removeWinningSide:R,tournamentRecord:l,drawDefinition:r,removeScore:a,winningSide:y,matchUpId:c,matchUp:f,event:u}),{...Ni,score:D,removeWinningSide:R,tieFormatRemoved:M,winningSide:y}}function hw({drawDefinition:e,finishingOrder:t}){if(!e)return{error:Li};const r="setOrderOfFinish";if(!Array.isArray(t))return pd({info:SU("finishingOrder"),result:{error:ys},stack:r});const{completedMatchUps:n,matchUpsMap:i}=Cm({inContext:!0,drawDefinition:e}),a=n?.map(Nd)??[],o=t.map(Nd),{matchUpTypes:s,roundNumbers:c,structureIds:u,matchUpTieIds:d}=(n??[]).filter((({matchUpId:e})=>o.includes(e))).reduce(((e,t)=>{const{matchUpTieId:r,matchUpType:n,roundNumber:i,structureId:a}=t;return e.matchUpTypes.includes(n)||e.matchUpTypes.push(n),e.roundNumbers.includes(i)||e.roundNumbers.push(i),e.structureIds.includes(a)||e.structureIds.push(a),e.matchUpTieIds.includes(r)||e.matchUpTieIds.push(r),e}),{matchUpTypes:[],roundNumbers:[],structureIds:[],matchUpTieIds:[]});if(s.length>1||d.length>1||c.length>1||u.length>1)return pd({info:"matchUpType, structureId and roundNumber must be equivalent",result:{error:ys},stack:r});let p,l;const m={},f=[],h=[],g=t.every((({orderOfFinish:e,matchUpId:t})=>(f.push(t),e&&h.push(e),m[t]=e,p=a.includes(t),l=void 0===e||Vd(e)&&Math.floor(e)>0,p&&l)));if(!g)return pd({result:{error:p?ys:Aa},info:(p?!l&&"orderOfFinish must be integer > 0 or undefined":"matchUps must be completed")||void 0,stack:r});const I=n?.filter((e=>e.structureId===u[0]&&e.roundNumber===c[0]&&e.matchUpType===s[0]&&e.matchUpTieId===d[0]&&!f.includes(e.matchUpId)));for(const e of I??[]){const{orderOfFinish:t}=e||{};if(t){if(!Vd(t))return pd({context:{orderOfFinish:t,matchUp:e},result:{error:ys},stack:r});h.push(t)}}if((U=h,U.filter(Hd)).length!==h.length||Math.max(...h)>h.length)return pd({info:"Values not unique or greater than expected number of values",result:{error:ys},stack:r});var U;if(u.length){const t=ph({matchUpFilters:{matchUpIds:o},structureId:u[0],drawDefinition:e,matchUpsMap:i});if(t.error)return pd({result:t,stack:r});t.completedMatchUps?.forEach((e=>e.orderOfFinish=m[e.matchUpId]))}return{...Ni}}function gw(e){return hw(e)}function Iw({tournamentRecord:e,drawDefinition:t,matchUpId:r,lineUps:n,event:i}){if(!e)return{error:Fi};if(!t)return{error:Bi};if("string"!=typeof r)return{error:ja};if(!Array.isArray(n))return{error:ys,lineUps:n};const a=e.participants||[];let o=xv({tournamentParticipants:a,inContext:!0,drawDefinition:t,matchUpId:r});if(o.error)return o;if(!o.matchUp)return{error:La};const{matchUp:s,structure:c}=o,{drawPositions:u,matchUpType:d}=s;if(d!==If)return{error:ja};if(!u?.length)return{error:Yi};const p=Og({matchUp:s,drawDefinition:t,structure:c,event:i})?.tieFormat,l={};for(const t of n){if(!Array.isArray(t))return{error:ys,lineUp:t};const r={},n=[];for(const e of t){if("object"!=typeof e)return{error:ys,lineUpAssignment:e};const{participantId:t,collectionAssignments:i=[]}=e;if(!Array.isArray(i))return{error:ys,collectionAssignments:i};const o=a.find((e=>e.participantId===t));if(!o)return{error:wo};if(o.participantType!==gm)return{error:So};const c=s.sides?.find((e=>e.participant?.individualParticipantIds?.includes(t)))?.sideNumber;c&&n.push(c);for(const e of i){if("object"!=typeof e)return{error:ys,collectionAssignment:e};const{collectionId:n,collectionPosition:i}=e,a=p?.collectionDefinitions?.find((e=>e.collectionId===n));if(!a)return{error:ys,collectionId:n};const o=`${n}-${i}`;r[o]||(r[o]=[]);const s=r[o].length;if(a.matchUpType===mf&&s||a.matchUpType===hf&&s>1)return{info:"Excessive collectionPosition assignments",error:ys};r[o].push(t)}}const i=Object.values(r);for(const t of i)if(2===t.length){const{participant:r}=yT({tournamentParticipants:a,participantIds:t});if(!r){const r=ST({participant:{participantType:Um,participantRole:Zv,individualParticipantIds:t},pairOverride:!0,tournamentRecord:e});if(r.error)return r}}const o=$d(n),c=((o[1]||0)>(o[2]||0)?1:(o[2]||0)>(o[1]||0)&&2)||void 0,u=Object.keys(l).map((e=>parseInt(e)));c&&!u.includes(c)&&(l[c]=t)}if(!Object.keys(l).length)return{error:Ds};if(o=xv({drawDefinition:t,matchUpId:r}),o.error)return o;if(!o.matchUp)return{error:La};const{matchUp:m}=o;m.sides||(m.sides=[]);for(const e of[1,2]){const t=m.sides.find((t=>t.sideNumber===e)),r=l[e];r&&(t?t.lineUp=r:m.sides.push({lineUp:r,sideNumber:e}))}return Vp({tournamentId:e?.tournamentId,context:"applyLineUps",drawDefinition:t,matchUp:m}),{...Ni}}function Uw(e){const t="resetTieFormat",{drawDefinition:r,event:n,uuids:i}=e,o=y(e,[{[Uu]:!0,[Ru]:!0}],t);if(o.error)return o;const s=In(e,[{[Vu]:ku}]);if(s[xu])return s;const c=e.tournamentRecord?.tournamentId,{matchUp:u,structure:d}=s?.matchUp??{};if(!u?.tieMatchUps)return a({result:{error:ja},info:"Must be a TEAM matchUp",stack:t});if(!u.tieFormat)return{...Ni};const p=we({structure:d,drawDefinition:r,event:n})?.tieFormat;if(!p)return a({result:{error:ws},info:"No inherited tieFormat",stack:t});const l=[],m=[],f=[],h=[];for(const e of p.collectionDefinitions){const{matchUpCount:t,collectionId:r}=e;m.push(r);const n=(u.tieMatchUps||[]).filter((e=>e.collectionId===r));if(n.length>t)n.sort(((e,t)=>(e.matchUpStatus===Qm?1:0)-(t.matchUpStatus===Qm?1:0))),f.push(...n.slice(0,t)),l.push(...n.slice(3).map(T));else if(f.push(...n),n.length<t){const r=t-n.length,a=gn({collectionDefinition:e,matchUpsLimit:r,matchUp:u,uuids:i});h.push(...a)}}for(const e of u?.tieMatchUps||[])e.collectionId&&!m.includes(e.collectionId)&&l.push(e.matchUpId);return h.length&&(f.push(...h),W({eventId:n?.eventId,matchUps:h,drawDefinition:r,tournamentId:c})),l.length&&H({matchUpIds:l,eventId:n?.eventId,drawDefinition:r,tournamentId:c}),u&&(u.tieMatchUps=f,u.tieFormatId=void 0,u.tieFormat=void 0,q({structureId:d?.structureId,eventId:n?.eventId,context:t,drawDefinition:r,tournamentId:c,matchUp:u})),{...Ni,newMatchUps:h,deletedMatchUpIds:l}}function yw({inContextDrawMatchUps:e=[],useTargetMatchUpIds:t,inContextMatchUp:r,drawDefinition:n,matchUpId:i}){let a=r;e.length&&!a&&(a=e.find((e=>e.matchUpId===i)));const{structure:o}=w({structureId:a?.structureId,drawDefinition:n}),s=o?.finishingPosition;return s===Vl?function({inContextDrawMatchUps:e,useTargetMatchUpIds:t,drawDefinition:r,structure:n,matchUp:i}){const{winnerMatchUpId:a,loserMatchUpId:o}=i,{links:s}=yn({roundNumber:i.roundNumber,structureId:n.structureId,drawDefinition:r}),c=s?.source,u=Sn({source:c,linkType:ul}),d=Sn({linkCondition:pl,linkType:dl,source:c});let p=Sn({source:c,linkType:dl});const l=d&&p;p||(p=d);const m=u?.target?.feedProfile,f=p?.target?.feedProfile,h=d?.target?.feedProfile;let g,I,U,y,v,T,P,D,w,b;if(t&&(a||o)&&(P=a&&m!==il&&e.find((({matchUpId:e})=>e===a)),y=o&&f!==il&&e.find((({matchUpId:e})=>e===o)),P||y))return{matchUp:i,targetLinks:{loserTargetLink:p,winnerTargetLink:u},targetMatchUps:{loserMatchUp:y,winnerMatchUp:P}};const{roundPosition:R}=i;b=b||e.filter((e=>e.structureId===n.structureId));const N=b.reduce(((e,t)=>t.roundNumber!==i.roundNumber||t.matchUpTieId?e:e+1),0);p&&!y&&f!==il&&({matchUpDrawPositionIndex:T,targetDrawPosition:v,matchUp:y}=Tn({targetLink:p,sourceRoundMatchUpCount:N,inContextDrawMatchUps:e,sourceRoundPosition:R,drawDefinition:r}));l&&h!==il&&({matchUpDrawPositionIndex:U,targetDrawPosition:I,matchUp:g}=Tn({targetLink:d,sourceRoundMatchUpCount:N,inContextDrawMatchUps:e,sourceRoundPosition:R,drawDefinition:r}));u&&!P&&m!==il&&({matchUpDrawPositionIndex:w,targetDrawPosition:D,matchUp:P}=Tn({targetLink:u,sourceRoundMatchUpCount:N,inContextDrawMatchUps:e,sourceRoundPosition:R,drawDefinition:r}));P||(b=b||e.filter((e=>e.structureId===n.structureId)),({matchUp:P}=vn({structureMatchUps:b,matchUp:i})));return S({matchUp:i,targetLinks:{loserTargetLink:p,winnerTargetLink:u,byeTargetLink:d},targetMatchUps:{winnerMatchUpDrawPositionIndex:w,loserMatchUpDrawPositionIndex:T,byeMatchUpDrawPositionIndex:U,winnerTargetDrawPosition:D,loserTargetDrawPosition:v,byeTargetDrawPosition:I,winnerMatchUp:P,loserMatchUp:y,byeMatchUp:g},targetMatchUpIds:!(!a&&!o)})}({inContextDrawMatchUps:e,useTargetMatchUpIds:t,drawDefinition:n,structure:o,matchUp:a}):function({matchUp:e}){return{targetLinks:{loserTargetLink:void 0,winnerTargetLink:void 0},targetMatchUps:{loserMatchUp:void 0,winnerMatchUp:void 0},matchUp:e}}({matchUp:a})}function Sw(e){const{tournamentRecord:t,drawDefinition:r,matchUpId:n,event:i}=e,o="resetScorecard";if(!r)return a({result:{error:Li},stack:o});if(!n)return a({result:{error:_a},stack:o});if(!gt(n))return a({result:{error:ys,matchUpId:n},stack:o});const s=se({drawDefinition:r}),{matchUps:c}=ue({nextMatchUps:!0,inContext:!0,drawDefinition:r,matchUpsMap:s}),u=s.drawMatchUps.find((e=>e.matchUpId===n)),d=c?.find((e=>e.matchUpId===n));if(!u||!c)return{error:La};if(u.matchUpType!==Yf)return{error:ja};const p=yw({inContextDrawMatchUps:c,drawDefinition:r,matchUpId:n}),l=d?.structureId,{structure:m}=w({drawDefinition:r,structureId:l});Object.assign(e,{inContextDrawMatchUps:c,inContextMatchUp:d,matchUpsMap:s,targetData:p,structure:m,matchUp:u});if(Yt(e))return{error:ho};if(u.tieMatchUps?.length)for(const e of u.tieMatchUps){const s=XD({matchUpId:e.matchUpId,matchUpTieId:n,winningSide:void 0,removeScore:!0,tournamentRecord:t,drawDefinition:r,event:i});if(s.error)return a({result:s,stack:o})}const f=te({tournamentRecord:t,drawDefinition:r,event:i})?.appliedPolicies,h=pn({event:e.event,removeScore:!0,tournamentRecord:t,appliedPolicies:f,drawDefinition:r,matchUpsMap:s,matchUpId:n});if(h.error)return a({result:h,stack:o});if(e.tiebreakReset&&!h.tieFormatRemoved){const e=we({drawDefinition:r,structure:m,event:i})?.tieFormat;if(u.tieFormat&&e){const{matchUpCountDifference:a,descendantDifferences:o,ancestorDifferences:s,valueDifference:c}=Un({descendant:u.tieFormat,ancestor:e});if(1===o.collectionIds.length&&!s.collectionIds.length&&!s.groupsCount&&1===a&&1===c){const e=Pn({tournamentRecord:t,drawDefinition:r,matchUpId:n,event:i});if(e.error)return e}}}return{...Ni}}var vw=Object.freeze({__proto__:null,applyLineUps:Iw,assignMatchUpSideParticipant:kD,assignTieMatchUpParticipantId:YD,bulkMatchUpStatusUpdate:pw,checkInParticipant:$D,checkOutParticipant:qD,disableTieAutoCalc:iw,enableTieAutoCalc:tw,findMatchUp:LD,removeDelegatedOutcome:rw,removeMatchUpSideParticipant:JD,removeTieMatchUpParticipantId:KD,replaceTieMatchUpParticipantId:zD,resetMatchUpLineUps:ow,resetScorecard:Sw,resetTieFormat:Uw,setDelegatedOutcome:mw,setMatchUpFormat:aw,setMatchUpStatus:dw,setOrderOfFinish:gw,substituteParticipant:nw,toggleParticipantCheckInState:WD,updateTieMatchUpScore:fw});function Tw({tournamentRecords:e,extensionName:t}){if("object"!=typeof e||!Object.keys(e).length)return{error:Oi};const r=[];let n;for(const i of Object.values(e)){const{extension:e}=Wl({element:i,name:t});e&&!n&&(r.push({params:{extension:e,discover:!0},method:"addExtension"}),n=!0);const a=i.events??[];for(const e of a){const{eventId:n}=e,{extension:i}=Wl({name:t,element:e});i&&r.push({params:{eventId:n,extension:i},method:"addEventExtension"})}}return{methods:r}}function Pw({tournamentRecords:e}){return Tw({extensionName:vi,tournamentRecords:e})}function Dw(e){const{matchUpAverageTimes:t,matchUpFormat:r}=e||{},n=t?.map((({matchUpFormatCodes:e})=>e?.filter((e=>e===r)))).flat().filter(Boolean).sort(((e,t)=>(e?.length||0)-(t?.length||0)))||[],i=n.includes(r)?r:n[0],a=t?.find((({matchUpFormatCodes:e,averageTimes:t})=>e?.find((e=>i===e))&&t));return a?.averageTimes}function ww(e){const{matchUpRecoveryTimes:t,averageMinutes:r,matchUpFormat:n}=e||{};return t?.find((({matchUpFormatCodes:e,averageTimes:t,recoveryTimes:i})=>{if(t&&r){const{greaterThan:e=0,lessThan:n=360}=t;if(r>e&&r<n)return!0}return e?.find((e=>e===n))&&i}))?.recoveryTimes}function bw({timesBlockArray:e,categoryName:t,categoryType:r}){return e.filter((e=>Array.isArray(e))).map((e=>e.sort(((e,t)=>(t.categoryNames?.length||0)-(e.categoryNames?.length||0))).find((({categoryTypes:e,categoryNames:n})=>!n?.length&&!e?.length||n?.includes(t)||e?.includes(r))))).find(Boolean)}const Rw="DOUBLES_SINGLES",Nw="SINGLES_DOUBLES",Mw="total",Aw="participantConflict",Ew="matchUpConflict",Cw="ISSUE_IDS",Ow="CONFLICT",Fw="WARNING",kw="ERROR",_w="ISSUE",xw="STATE",Lw={SINGLES_DOUBLES:Nw,DOUBLES_SINGLES:Rw,TOTAL:Mw,CONFLICT_MATCHUP_ORDER:Ew,CONFLICT_PARTICIPANTS:Aw,SCHEDULE_ISSUE_IDS:Cw,SCHEDULE_CONFLICT:Ow,SCHEDULE_WARNING:Fw,SCHEDULE_ERROR:kw,SCHEDULE_ISSUE:_w,SCHEDULE_STATE:xw};function Vw({defaultAverageMinutes:e=90,defaultRecoveryMinutes:t=0,tournamentRecord:r,matchUpFormat:n,categoryName:i,categoryType:a,eventType:o,event:s}){if(!r)return{error:Fi};o=o??s?.eventType??$f;const c={averageTimes:[{minutes:{default:e}}],recoveryTimes:[{minutes:{default:t}}]},{scheduleTiming:u}=QU({tournamentRecord:r,categoryName:i,categoryType:a,event:s});return Bw({eventType:o,timingDetails:{...u,matchUpFormat:n,categoryType:a,defaultTiming:c}})}function Bw({timingDetails:e,eventType:t}){const r=function({matchUpFormat:e,categoryName:t,categoryType:r,defaultTiming:n,tournamentScheduling:i,eventScheduling:a,policy:o}){return bw({categoryName:t,categoryType:r,timesBlockArray:[a?.matchUpAverageTimes&&Dw({...a,matchUpFormat:e}),i?.matchUpAverageTimes&&Dw({...i,matchUpFormat:e}),o?.matchUpAverageTimes&&Dw({...o,matchUpFormat:e}),o?.defaultTimes?.averageTimes,n?.averageTimes]})}(e),n=Object.keys(r?.minutes||{}),i=r?.minutes&&(n?.includes(t)&&r.minutes[t]||r.minutes.default),a=function({tournamentScheduling:e,eventScheduling:t,averageMinutes:r,defaultTiming:n,matchUpFormat:i,categoryName:a,categoryType:o,policy:s}){return bw({categoryName:a,categoryType:o,timesBlockArray:[t?.matchUpRecoveryTimes&&ww({...t,averageMinutes:r,matchUpFormat:i}),e?.matchUpRecoveryTimes&&ww({...e,averageMinutes:r,matchUpFormat:i}),s?.matchUpRecoveryTimes&&ww({...s,averageMinutes:r,matchUpFormat:i}),s?.defaultTimes?.recoveryTimes,n?.recoveryTimes]})}({...e,averageMinutes:i}),o=Object.keys(a?.minutes||{}),s=a?.minutes&&(o?.includes(t)&&a.minutes[t]||a.minutes.default),c=t===$f?Nw:Rw;return{averageMinutes:i,recoveryMinutes:s,typeChangeRecoveryMinutes:a?.minutes&&(o?.includes(c)&&a.minutes[c]||s)}}const jw="ADULT",Gw="JUNIOR",qw="WHEELCHAIR",$w={[nd]:{allowModificationWhenMatchUpsScheduled:{courts:!1,venues:!1},defaultTimes:{averageTimes:[{categoryNames:[],minutes:{default:90}}],recoveryTimes:[{minutes:{[hf]:30,default:60}}]},defaultDailyLimits:{[mf]:2,[hf]:2,total:3},matchUpAverageTimes:[{matchUpFormatCodes:[LI],averageTimes:[{categoryNames:[],minutes:{default:90}},{categoryTypes:[qw],minutes:{default:120}}]},{matchUpFormatCodes:["SET3-S:6/TB7-F:TB10"],averageTimes:[{categoryNames:[],minutes:{default:85}}]},{matchUpFormatCodes:["SET3-S:6/TB7-F:TB7"],averageTimes:[{categoryNames:[],minutes:{default:70}}]},{matchUpFormatCodes:["SET3-S:4NOAD-F:TB7"],averageTimes:[{categoryNames:[],minutes:{default:55}}]},{matchUpFormatCodes:["SET3-S:4/TB7"],averageTimes:[{categoryNames:[],minutes:{default:60}}]},{matchUpFormatCodes:["SET3-S:4/TB7-F:TB7"],averageTimes:[{categoryNames:[],minutes:{default:50}}]},{matchUpFormatCodes:["SET3-S:4/TB7-F:TB10"],averageTimes:[{categoryNames:[],minutes:{default:55}}]},{matchUpFormatCodes:["SET3-S:4/TB5@3"],averageTimes:[{categoryNames:[],minutes:{default:45}}]},{matchUpFormatCodes:["SET1-S:8/TB7","SET1-S:8/TB7@7"],averageTimes:[{categoryNames:[],minutes:{default:40}}]},{matchUpFormatCodes:["SET1-S:5/TB9@4"],averageTimes:[{categoryNames:[],minutes:{default:30}}]},{matchUpFormatCodes:["SET1-S:6/TB7"],averageTimes:[{categoryNames:[],minutes:{default:30}}]},{matchUpFormatCodes:["SET1-S:6NOAD"],averageTimes:[{categoryNames:[],minutes:{default:30}}]},{matchUpFormatCodes:["SET1-S:4/TB7","SET1-S:4/TB5@3","SET3-S:TB10","SET1-S:T20"],averageTimes:[{categoryNames:[],minutes:{default:20}}]},{matchUpFormatCodes:["SET1-S:4NOAD"],averageTimes:[{categoryNames:[],minutes:{default:20}}]},{matchUpFormatCodes:["SET1-S:TB10"],averageTimes:[{categoryNames:[],minutes:{default:10}}]}],matchUpRecoveryTimes:[{matchUpFormatCodes:["SET3-S:6/TB7","SET3-S:6/TB7-F:TB10","SET3-S:6/TB7-F:TB7"],recoveryTimes:[{categoryTypes:[jw,qw],minutes:{default:60,[hf]:30}},{categoryTypes:[Gw],minutes:{default:60,[hf]:60}}]},{matchUpFormatCodes:["SET3-S:4/TB7-F:TB7","SET3-S:4/TB7-F:TB10","SET3-S:4NOAD-F:TB7","SET3-S:4/TB7","SET3-S:4/TB5@3"],recoveryTimes:[{categoryTypes:[jw,qw],minutes:{default:30}},{categoryTypes:[Gw],minutes:{default:60}}]},{matchUpFormatCodes:["SET1-S:8/TB7","SET1-S:8/TB7@7","SET1-S:5/TB9@4","SET1-S:6/TB7","SET1-S:6NOAD","SET1-S:4/TB7","SET1-S:4NOAD","SET3-S:TB10","SET1-S:T20"],recoveryTimes:[{categoryNames:[],minutes:{default:30}}]},{matchUpFormatCodes:["SET1-S:4/TB5@3"],recoveryTimes:[{categoryTypes:[jw,Gw],minutes:{default:30}},{categoryTypes:[qw],minutes:{default:15}}]},{matchUpFormatCodes:["SET1-S:TB10"],recoveryTimes:[{categoryNames:[],minutes:{default:15}}]}],matchUpDailyLimits:[]}};function Ww({tournamentRecord:e,matchUpFormats:t,categoryType:r,event:n}){if(!n)return{error:Ua};let i,a=[];if(t?.length){const e=[];a=t.map((t=>{const r="string"==typeof t?{matchUpFormat:t}:t;if(!e.includes(r?.matchUpFormat)&&uv({matchUpFormat:r?.matchUpFormat}))return e.push(r.matchUpFormat),r})).filter(Boolean)}else{const{policy:t}=YU({policyType:ad,tournamentRecord:e,event:n});if(t?.matchUpFormats)a=t?.matchUpFormats;else{const{extension:e}=Wl({name:vi,element:n});let t,r;({matchUpAverageTimes:t,matchUpRecoveryTimes:r}=e?.value?e.value:$w[nd]),a=jd([...(t||[]).map((e=>e.matchUpFormatCodes)),...(r||[]).map((e=>e.matchUpFormatCodes))].flat()).map((e=>({matchUpFormat:e}))),i="default scheduling policy in use"}}const{eventType:o,eventId:s,category:c}=n,u=c?.categoryName??c?.ageCategoryCode??s;if(!s)return{error:Ua};return Mf({eventMatchUpFormatTiming:a.map((({matchUpFormat:t,description:i})=>({matchUpFormat:t,description:i,...Vw({tournamentRecord:e,matchUpFormat:t,categoryName:u,categoryType:r,eventType:o,event:n})}))),info:i})}function Hw({tournamentRecords:e}){return Tw({extensionName:Si,tournamentRecords:e})}const zw=({scheduleAttributes:e=["scheduledDate","scheduledTime"],schedule:t={}})=>!!Object.keys(t).filter((t=>e.includes(t))).filter((e=>t[e])).length;function Yw({scheduleAttributes:e=["scheduledDate","scheduledTime"],matchUps:t=[]}){if(!Ef(t))return{error:Va};if(!Array.isArray(e))return{error:ys};const r=t.filter(Boolean).filter((({schedule:t})=>zw({schedule:t,scheduleAttributes:e}))).reduce(((e,t)=>{const{schedule:r}=t,n=Lc(r?.scheduledDate),i=xc(r?.scheduledTime);return n&&i&&(e[n]?e[n].push(t):e[n]=[t]),e}),{});return Object.keys(r).forEach((e=>{r[e].sort(((e,t)=>Gc(xc(e.schedule?.scheduledTime),xc(t.schedule?.scheduledTime))))})),{...Ni,scheduledMatchUps:r}}function Qw({schedulingProfile:e,matchUps:t=[]}){const r={},n=({eventId:e,drawId:t,structureId:r,roundNumber:n})=>`${e}|${t}|${r}${n}`;if(e?.length){e.map((({venues:e})=>e.map((({rounds:e})=>e)))).flat().forEach((e=>{e.sort(((e,t)=>(e.sortOrder||0)-(t.sortOrder||0))).forEach((({eventId:e,drawId:t,structureId:i,roundNumber:a},o)=>{const s=n({eventId:e,drawId:t,structureId:i,roundNumber:a});r[s]=o}))}))}const i=[],a={noScheduledDate:[]};for(const e of t){const t=e.schedule||{},r=t.scheduledDate&&Lc(t.scheduledDate)||t.scheduledTime&&Lc(t.scheduledTime)||"noScheduledDate";a[r]||(a[r]=[]),a[r].push(e)}const o=Object.keys(a).sort();for(const e of o){const t=a[e],o={noScheduledTime:[]};for(const e of t){const t=e.schedule||{},r=t.scheduledTime&&xc(t.scheduledTime)||"noScheduledTime";o[r]||(o[r]=[]),o[r].push(e)}const s=Object.keys(o).sort();for(const e of s){const t=o[e];t.sort(((e,t)=>(r[n(e)]||0)-(r[n(t)]||0))),i.push(...t)}}return i}function Kw({courtPrefix:e="C|",minRowsCount:t,courtsData:r}){if(!Array.isArray(r))return{error:ys};const n=r?.reduce(((e,t)=>{const r=t.matchUps||[],n=Math.max(0,...r.map((e=>e.schedule.courtOrder||0)));return n>e?n:e}),1),i=Qd(0,t?Math.max(t,n):n).map((e=>({matchUps:Qd(0,r.length).map((t=>{const n=r[t],{courtId:i,venueId:a}=n;return{schedule:{courtOrder:e+1,venueId:a,courtId:i}}}))})));return r.forEach(((e,t)=>{for(const r of e.matchUps){const e=r.schedule?.courtOrder;e&&(i[e-1].matchUps[t]=r)}})),{courtPrefix:e,rows:i.map(((t,r)=>Object.assign({rowId:`rowId-${r+1}`},...t.matchUps.map(((t,r)=>({[`${e}${r}`]:t}))))))}}function Jw(e){let{participants:t,contextContent:r,participantMap:n}=e;const{tournamentAppliedPolicies:i,scheduleVisibilityFilters:a,participantsProfile:o,afterRecoveryTimes:s,policyDefinitions:c,useParticipantMap:u,tournamentRecord:d,usePublishState:p,contextFilters:l,matchUpFilters:m,contextProfile:f,nextMatchUps:h,tournamentId:g,inContext:I,context:U,event:y}=e;if(!y)return{error:Ua};const{eventId:S,eventName:v,endDate:T}=y,P={...U,...Mf({eventId:S,eventName:v,endDate:T??d?.endDate,tournamentId:g??d?.tournamentId,indoorOutDoor:y.indoorOutdoor??d?.indoorOutdoor,surfaceCategory:y.surfaceCategory??d?.surfaceCategory})};let D;!t&&d&&({participants:t,participantMap:n,groupInfo:D}=$U({participantsProfile:o,policyDefinitions:c,useParticipantMap:u,tournamentRecord:d,contextProfile:f,inContext:I})),f&&!r&&(r=HU({policyDefinitions:c,tournamentRecord:d,contextProfile:f,event:y}));const w=jT({event:y});return{...(y.drawDefinitions??[]).reduce(((e,u)=>{const g=Cm({context:P,tournamentAppliedPolicies:i,scheduleVisibilityFilters:a,tournamentParticipants:t,participantsProfile:o,afterRecoveryTimes:s,policyDefinitions:c,tournamentRecord:d,usePublishState:p,contextContent:r,contextFilters:l,matchUpFilters:m,participantMap:n,publishStatus:w,contextProfile:f,drawDefinition:u,nextMatchUps:h,inContext:I,event:y}),U=Object.keys(g);return U?.forEach((t=>{Array.isArray(g[t])&&(e[t]||(e[t]=[]),e[t]=e[t].concat(g[t]))})),e}),{}),...Ni,groupInfo:D}}function Zw(e){if(!e?.tournamentRecord)return{error:Fi};let t=e.contextContent;const{scheduleVisibilityFilters:r,participantsProfile:n,afterRecoveryTimes:i,policyDefinitions:a,useParticipantMap:o,tournamentRecord:s,inContext:c=!0,usePublishState:u,contextFilters:d,matchUpFilters:p,contextProfile:l,nextMatchUps:m,context:f}=e,h=e.tournamentId??s.tournamentId,g=s?.events??[],{participants:I,participantMap:U,groupInfo:y}=$U({participantsProfile:n,policyDefinitions:a,useParticipantMap:o,tournamentRecord:s,contextProfile:l,inContext:c});l&&!t&&(t=HU({policyDefinitions:a,tournamentRecord:s,contextProfile:l}));const{appliedPolicies:S}=Oh({tournamentRecord:s}),v=d?.eventIds??[];return{...g.filter((e=>!v.includes(e.eventId))).map((e=>{const o=bU({event:e}).flightProfile;return Jw({context:{eventDrawsCount:o?.flights?.length||e.drawDefinitions?.length||0,...f},tournamentAppliedPolicies:S,scheduleVisibilityFilters:r,participantsProfile:n,afterRecoveryTimes:i,policyDefinitions:a,tournamentRecord:s,usePublishState:u,contextFilters:d,contextProfile:l,contextContent:t,matchUpFilters:p,participantMap:U,participants:I,tournamentId:h,nextMatchUps:m,inContext:c,event:e})})).reduce(((e,t)=>{const r=t&&Object.keys(t).filter((e=>!["success","matchUpsMap"].includes(e)));return r?.forEach((r=>{Array.isArray(t[r])&&(e[r]||(e[r]=[]),e[r]=e[r].concat(t[r]),e.matchUpsCount+=t[r].length)})),e}),{matchUpsCount:0}),groupInfo:y}}function Xw({scheduleVisibilityFilters:e,participantsProfile:t,tournamentRecords:r,policyDefinitions:n,usePublishState:i,matchUpFilters:a,contextFilters:o,nextMatchUps:s,inContext:c}){if("object"!=typeof r||!Object.keys(r).length)return{error:Oi};const u=Object.keys(r).map((u=>{const d=r[u];return Zw({scheduleVisibilityFilters:e,participantsProfile:t,policyDefinitions:n,tournamentRecord:d,usePublishState:i,matchUpFilters:a,contextFilters:o,nextMatchUps:s,inContext:c})})),d={};return{...u.reduce(((e,t)=>(Object.keys(t).forEach((r=>{Array.isArray(t[r])&&(e[r]||(e[r]=[]),e[r]=e[r].concat(t[r])),"groupInfo"===r&&Object.assign(d,t[r])})),e)),{}),groupInfo:d}}function eb(e){if("object"!=typeof e?.tournamentRecords||!Object.keys(e?.tournamentRecords).length)return{error:Oi};const{courts:t,venues:r}=_T(e),n=LT(e).schedulingProfile,{sortDateMatchUps:i=!0,courtCompletedMatchUps:a,alwaysReturnCompleted:o,activeTournamentId:s,tournamentRecords:c,withCourtGridRows:u,minCourtGridRows:d,usePublishState:p,status:l=AI,sortCourtsData:m}=e,f=p?og({tournamentRecord:c[s??uc()],itemType:`${MI}.${EI}`}).timeItem?.itemValue?.[l]:void 0,h=o?Xw({...e,matchUpFilters:{...e.matchUpFilters,matchUpStatuses:[Vm]},contextFilters:e.contextFilters}).completedMatchUps:[];if(p&&(!f||!Object.keys(f).length))return{completedMatchUps:h,dateMatchUps:[],courtsData:[],venues:r};let g,I;p&&({drawIds:g,detailsMap:I}=function({tournamentRecords:e}){const t=[],r={};for(const n of Object.values(e))for(const e of n.events??[]){const n=jT({event:e}),i=n?.drawDetails;ru(i)?(Object.assign(r,i),t.push(...Object.keys(i).filter((e=>pD({drawId:e,drawDetails:i}))))):n?.drawIds?.length&&t.push(...n.drawIds)}return{drawIds:t,detailsMap:r}}({tournamentRecords:c})),g?.length&&(e.contextFilters||(e.contextFilters={}),e.contextFilters?.drawIds?e.contextFilters.drawIds=e.contextFilters.drawIds.filter((e=>g.includes(e))):e.contextFilters.drawIds=g),f?.eventIds?.length&&(e.matchUpFilters||(e.matchUpFilters={}),e.matchUpFilters?.eventIds&&e.matchUpFilters.eventIds.length?e.matchUpFilters.eventIds=e.matchUpFilters.eventIds.filter((e=>f.eventIds.includes(e))):e.matchUpFilters.eventIds=f.eventIds),f?.scheduledDates?.length&&(e.matchUpFilters||(e.matchUpFilters={}),e.matchUpFilters.scheduledDates&&e.matchUpFilters.scheduledDates.length?e.matchUpFilters.scheduledDates=e.matchUpFilters.scheduledDates.filter((e=>f.scheduledDates.includes(e))):e.matchUpFilters.scheduledDates=f.scheduledDates),o&&(e.matchUpFilters||(e.matchUpFilters={}),e.matchUpFilters?.excludeMatchUpStatuses?.length?e.matchUpFilters.excludeMatchUpStatuses.includes(Vm)||e.matchUpFilters.excludeMatchUpStatuses.push(Vm):e.matchUpFilters.excludeMatchUpStatuses=[Vm]);const{completedMatchUps:U,upcomingMatchUps:y,pendingMatchUps:S,groupInfo:v}=Xw({...e,matchUpFilters:e.matchUpFilters,contextFilters:e.contextFilters});let T=[...y??[],...S??[]];I&&Object.keys(I).length&&(T=T.filter((e=>{const{drawId:t,structureId:r,stage:n}=e;if(!I[t])return!1;if(I[t].stageDetails){const e=Object.keys(I[t].stageDetails),r=e.filter((e=>!I[t].stageDetails[e].published)),i=e.filter((e=>I[t].stageDetails[e].published));return(!r.length||!r.includes(n))&&(!(!i.length||!i.includes(n))||r.length&&!r.includes(n)&&!i.length)}if(I[t].structureDetails){const e=Object.keys(I[t].structureDetails),n=e.filter((e=>!I[t].structureDetails[e].published)),i=e.filter((e=>I[t].structureDetails[e].published));return(!n.length||!n.includes(r))&&(!(!i.length||!i.includes(r))||n.length&&!n.includes(r)&&!i.length)}return!0})));const P=i?Qw({matchUps:T,schedulingProfile:n}):T,D=t?.map((e=>{const t=function({courtId:e}){const t=(a?P.concat(U??[]):P).filter((t=>t.schedule?.courtId===e||t.schedule?.allocatedCourts?.map((({courtId:e})=>e)).includes(e)));return m?Qw({matchUps:t,schedulingProfile:n}):t}(e);return{surfaceCategory:e?.surfaceCategory??"",matchUps:t,...e}})),w={completedMatchUps:o?h:U,dateMatchUps:P,courtsData:D,groupInfo:v,venues:r};if(u){const{rows:e,courtPrefix:t}=Kw({minRowsCount:d,courtsData:D});w.courtPrefix=t,w.rows=e}return{...w,...Ni}}const tb=(e,t)=>(e||0)+(t||0);function rb(e,t){const r=Array.isArray(e)?e[0]:e;return isNaN(r)&&Bg||r<=t[$g]&&$g||r<=t[qg]&&qg||Gg}function nb({score:e}){const t=e?.sets||[],r=t.reduce(((e,t)=>(e[0]+=t.side1Score||0,e[1]+=t.side2Score||0,e)),[0,0]),n=t.reduce(((e,t)=>(e[0]+=t.side1TiebreakScore||0,e[1]+=t.side2TiebreakScore||0,e)),[0,0]);return n.reduce(tb)&&(r[n[0]>n[1]?0:1]+=1),{sets:t,games:r,score:e}}function ib(e){const t=Math.min(...e.games),r=Math.max(...e.games);return Math.round(t/r*100)}function ab(e){return e.map(ib).sort().map((e=>parseFloat(e.toFixed(2))))}function ob({tournamentRecord:e,profileBands:t,matchUp:r}){if(!r)return{error:Ba};const{score:n,winningSide:i}=r;if(!i)return{error:ys};const a=!t&&e&&YU({policyType:Qu,tournamentRecord:e}).policy,o=t||a?.profileBands||WU[Qu].profileBands,s=ab([nb({score:n})]),c=rb(s,o),u=Array.isArray(s)?s[0]:s;return{...Ni,competitiveness:c,pctSpread:u}}function sb(e){return e.createdAt?new Date(e.createdAt).getTime():0}function cb({visibilityThreshold:e,timeItems:t,itemType:r}){const n=t.filter((t=>t&&t.itemType===r&&(!e||sb(t)<new Date(e).getTime()))).sort(((e,t)=>sb(e)-sb(t))).pop(),i=n&&sb(n);return{itemValue:n?.itemValue,timeStamp:i}}function ub({visibilityThreshold:e,timeStamp:t,schedule:r,matchUp:n}){const{itemValue:i,timeStamp:a}=cb({timeItems:n?.timeItems||[],itemType:mI,visibilityThreshold:e});return!r||a&&t&&new Date(a).getTime()>new Date(t).getTime()?{scheduledTime:i}:r}function db({visibilityThreshold:e,timeStamp:t,schedule:r,matchUp:n}){const{itemValue:i,timeStamp:a}=cb({timeItems:n?.timeItems||[],itemType:pI,visibilityThreshold:e});return!r||a&&t&&new Date(a).getTime()>new Date(t).getTime()?{scheduledDate:i}:r}function pb({visibilityThreshold:e,timeStamp:t,schedule:r,matchUp:n}){const{itemValue:i,timeStamp:a}=cb({timeItems:n?.timeItems||[],itemType:cI,visibilityThreshold:e});return!r||a&&t&&new Date(a).getTime()>new Date(t).getTime()?{allocatedCourts:Jc(i,!1,!0)}:r}function lb({visibilityThreshold:e,timeStamp:t,schedule:r,matchUp:n}){const{itemValue:i,timeStamp:a}=cb({timeItems:n?.timeItems||[],itemType:uI,visibilityThreshold:e});return!r||a&&t&&new Date(a).getTime()>new Date(t).getTime()?{courtId:i}:r}function mb({visibilityThreshold:e,timeStamp:t,schedule:r,matchUp:n}){const{itemValue:i,timeStamp:a}=cb({timeItems:n?.timeItems||[],itemType:sI,visibilityThreshold:e});return!r||a&&t&&new Date(a).getTime()>new Date(t).getTime()?{venueId:i}:r}function fb(e){const{disableNotice:t,venue:r,context:n}=e;if("object"!=typeof r)return{error:ys};const i=US(e);let a;r.venueId||(r.venueId=bm());for(const e of Object.values(i)){const t=hb({disableNotice:!0,tournamentRecord:e,context:n,venue:r});if(t?.error)return t;a=t.venue}return t||rc({topic:lp,payload:{venue:r}}),Mf({...Ni,venue:a})}function hb({tournamentRecord:e,disableNotice:t,context:r,venue:n}){if(!e)return{error:Fi};if(!n)return{error:Za,info:"missing venue"};e.venues||(e.venues=[]),n.venueId||(n.venueId=bm());if(e.venues.reduce(((e,t)=>e||t.venueId===n.venueId),void 0))return{error:Qo};if(r){gd({element:n,extension:{value:r,name:ii}})}return e.venues.push(n),t||rc({payload:{venue:n,tournamentId:e.tournamentId},topic:lp}),{...Ni,venue:Jc(n)}}function gb({tournamentRecords:e,tournamentRecord:t,venueId:r}){if(!t)return{error:Fi};if(!r)return{error:Jo};const n=(t.venues??[]).reduce(((e,t)=>t.venueId===r?t:e),void 0);if(!n&&e){const i=(js({tournamentRecords:e}).linkedTournamentIds??[])[t.tournamentId];for(const a of i){const i=gb({tournamentRecord:e[a],venueId:r});if(i.success&&i.venue)return fb({tournamentRecord:t,venue:i.venue}),{...Ni,venue:n}}}return n?{...Ni,venue:n}:{error:Ko}}function Ib({convertExtensions:e,...t}){const{tournamentRecords:r,tournamentRecord:n,venueId:i}=t;return Jc(gb({tournamentRecords:r,tournamentRecord:n,venueId:i}),e,!0)}function Ub({tournamentRecords:e,tournamentRecord:t,courtId:r}){if(!t)return{error:Fi};if(!r)return{error:Ja};let n,i;if((t.venues??[]).forEach((e=>{(e.courts??[]).forEach((t=>{t.courtId===r&&(n=t,i=e)}))})),n)return{...Ni,court:n,venue:i};if(e){const a=(js({tournamentRecords:e}).linkedTournamentIds??[])[t.tournamentId];for(const o of a){const a=Ub({tournamentRecord:e[o],courtId:r});if(a.success)return a.venue&&fb({tournamentRecord:t,venue:a.venue}),{...Ni,court:n,venue:i}}}return pd({result:{error:zo},stack:"findCourt"})}function yb(e){return Jc(Ub(e),!1,!0)}function Sb({tournamentRecord:e,internalUse:t,courtId:r}){if(!e)return{error:Fi};if(!r)return{error:Ja};const n=Ub({tournamentRecord:e,courtId:r});if(n.error)return n;const i=n.court&&(({altitude:e,courtId:t,courtName:r,courtDimensions:n,latitude:i,longitude:a,surfaceCategory:o,surfaceType:s,surfacedDate:c,pace:u,notes:d})=>({altitude:e,courtId:t,courtName:r,courtDimensions:n,latitude:i,longitude:a,surfaceCategory:o,surfaceType:s,surfacedDate:c,pace:u,notes:d}))(n.court);return{...Ni,courtInfo:Jc(i,!1,t)}}function vb({tournamentRecord:e,venueId:t}){if(!e)return{error:Fi};if(!t)return{error:Jo};const r=gb({tournamentRecord:e,venueId:t});if(r.error)return r;const n=(r.venue?.courts??[]).map((t=>(({courtInfo:e})=>({...e}))(Sb({courtId:t.courtId,internalUse:!0,tournamentRecord:e})))),i=r.venue&&(({venueId:e,venueName:t,venueAbbreviation:r})=>({venueAbbreviation:r,venueName:t,venueId:e}))(r.venue),a=i&&{...i,courtsInfo:n};return{...Ni,venueData:Jc(a,!1,!0)}}function Tb({visibilityThreshold:e,timeStamp:t,schedule:r,matchUp:n}){const{itemValue:i,timeStamp:a}=cb({timeItems:n?.timeItems||[],itemType:UI,visibilityThreshold:e});return!r||a&&t&&new Date(a).getTime()>new Date(t).getTime()?{timeModifiers:i}:r}function Pb(e){if(Sc.test(e)){const t=Rc();return new Date(`${t}T${e}`)}return new Date(e)}function Db(e){const t=(e,t=2)=>("00"+e).slice(-t);return t(e/36e5|0)+":"+t(e%36e5/6e4|0)+":"+t(e%6e4/1e3|0)}function wb(e){let t=e.event,r=e.matchUpType;const{scheduleVisibilityFilters:n,afterRecoveryTimes:i,tournamentRecord:a,usePublishState:o,scheduleTiming:s,matchUpFormat:c,publishStatus:u,matchUp:d}=e;if(!d)return{error:Ba};if(i&&!d.matchUpType&&!e.matchUpType&&(t||a)&&d.drawId){let n=t?.drawDefinitions?.find((e=>e.drawId===d.drawId));!n&&a&&({drawDefinition:n,event:t}=ly({tournamentRecord:a,drawId:d.drawId}));const i=d.structureId&&n?.structures?.find((({structureId:e})=>e===d.structureId));r=e.matchUpType||i?.matchUpType||n?.matchUpType||t?.eventType!==zf&&t?.eventType}const{milliseconds:p,time:l}=function({matchUp:e}){if(!e)return{error:Ba};if(!e.timeItems)return{error:os};const t=e.timeItems.filter((e=>[fI,hI,gI,II].includes(e?.itemType))).sort(((e,t)=>Pb(e.itemValue).getTime()-Pb(t.itemValue).getTime())),r=t.reduce(((e,t)=>{let r;const n=t?.itemType?.split("."),i=`SCHEDULE.TIME.${t?.itemType?.startsWith("SCHEDULE.TIME")&&n[2]}`;switch(i){case fI:r=0;break;case II:if(e.lastValue&&[fI,gI].includes(e.lastType)){const n=Pb(t.itemValue).getTime()-Pb(e.lastValue).getTime();r=e.milliseconds+n}else r=e.milliseconds;break;case hI:if([fI,"SCHECULE.TIME.RESUME"].includes(e.lastType)){const n=Pb(t.itemValue).getTime()-Pb(e.lastValue).getTime();r=e.milliseconds+n}else r=e.milliseconds;break;default:r=e.milliseconds}return{milliseconds:r,lastType:i,lastValue:t.itemValue}}),{milliseconds:0,lastType:void 0,lastValue:void 0});if([fI,gI].includes(r.lastType)){const e=(new Date).getTime()-Pb(r.lastValue).getTime();r.milliseconds+=e}return{milliseconds:r.milliseconds,time:Db(r.milliseconds),relevantTimeItems:t}}({matchUp:d}),{startTime:m}=function({matchUp:e}){const t=e=>e.createdAt?new Date(e.createdAt).getTime():0,r=(e?.timeItems||[]).reduce(((e,r)=>{const n=r.itemType===fI&&r;return n&&(!e||t(n)<t(e))?n:e}),void 0),n=r?.itemValue;return{startTime:n}}({matchUp:d}),{endTime:f}=function({matchUp:e}){const t=e=>e.createdAt?new Date(e.createdAt).getTime():0,r=(e?.timeItems||[]).reduce(((e,r)=>{const n=r.itemType===II&&r;return n&&(!e||t(n)>t(e))?n:e}),void 0),n=r?.itemValue;return{endTime:n}}({matchUp:d});let h;const{visibilityThreshold:g,eventIds:I,drawIds:U}=n??{};if(I&&!I.includes(d.eventId)||U&&!U.includes(d.drawId))h=Mf({milliseconds:p,startTime:m,endTime:f,time:l});else{const e={matchUp:d,visibilityThreshold:g},{allocatedCourts:t}=pb(e),{scheduledTime:n}=ub(e);let{scheduledDate:o}=db(e);const{venueId:u}=mb(e),{courtId:I}=lb(e),{courtOrder:U}=function({visibilityThreshold:e,timeStamp:t,schedule:r,matchUp:n}){const{itemValue:i,timeStamp:a}=cb({timeItems:n?.timeItems||[],itemType:dI,visibilityThreshold:e});return!r||a&&t&&new Date(a).getTime()>new Date(t).getTime()?{courtOrder:i}:r}(e),{timeModifiers:y}=Tb(e);let S,v,T,P,D;const w=d.matchUpType??r;if(s&&n&&i&&w){const e={matchUpFormat:d.matchUpFormat??c,...s};({averageMinutes:v=0,recoveryMinutes:T=0,typeChangeRecoveryMinutes:P=0}=Bw({timingDetails:e,eventType:w})),(v||T)&&(S=f?Hc(xc(f),T):Hc(n,v+T)),P&&(D=f?Hc(xc(f),P):Hc(n,v+P))}!o&&n&&(o=Lc(n));const b=Pc({scheduledDate:o,scheduledTime:n}),R={},N=(a&&u&&vb({tournamentRecord:a,venueId:u}))?.venueData||{};u&&(R[u]=N);const{venueName:M,venueAbbreviation:A,courtsInfo:E}=N,C=I&&E?.find((e=>e.courtId===I)),O=C?.courtName;for(const e of t||[]){if(!a)break;e.venueId&&!R[e.venueid]&&(R[e.venueId]=vb({venueId:e.venueId,tournamentRecord:a})?.venueData);const t=R[e.venueId];e.venueName=t?.venueName;const r=t?.courtsInfo?.find((t=>t.courtId===e.courtId));e.courtName=r?.courtName}h=Mf({typeChangeTimeAfterRecovery:D,timeAfterRecovery:S,scheduledDate:o,scheduledTime:n,isoDateString:b,allocatedCourts:t,timeModifiers:y,venueAbbreviation:A,venueName:M,venueId:u,courtOrder:U,courtName:O,courtId:I,typeChangeRecoveryMinutes:P,recoveryMinutes:T,averageMinutes:v,milliseconds:p,startTime:m,endTime:f,time:l})}const{scheduledDate:y}=db({matchUp:d}),{scheduledTime:S}=ub({matchUp:d});if(o&&u?.displaySettings?.draws){const e=u.displaySettings.draws,t=(e?.[d.drawId]??e?.default)?.scheduleDetails;if(t){const e=(t.find((e=>y&&e.dates?.includes(y)))??t.find((e=>!e.dates?.length)))?.attributes;if(e){h=zu({source:h,template:Object.assign({},...Object.keys(h).map((e=>({[e]:!0}))),e)})}}}return{schedule:h,endDate:d.matchUpStatus&&rf.includes(d.matchUpStatus)&&(Lc(f)||Lc(y)||Lc(S))||void 0}}function bb({tournamentRecords:e,tournamentId:t}){if("object"!=typeof e||!Object.keys(e).length)return{error:Oi};let r;return Object.keys(e).filter((e=>!t||e===t)).forEach((t=>{const n=e[t],{matchUpDailyLimits:i}=function(e){const t=y(e,[{[Uu]:!0}]);if(t.error)return t;const{tournamentRecord:r}=e,{policy:n}=YU({policyType:nd,tournamentRecord:r}),{extension:i}=s({element:r,name:Si}),a=i?.value?.dailyLimits,o=n?.defaultDailyLimits;return{matchUpDailyLimits:a||o}}({tournamentRecord:n});r=i})),{matchUpDailyLimits:r}}function Rb({matchUp:e}){return!!e&&(rf.includes(e?.matchUpStatus)||e?.winningSide)}function Nb(e){let{matchUps:t}=e;const{singlesForDoubles:r,tournamentRecord:n,drawDefinition:i,excludeMargin:a,exclusionRule:o,zoneDoubling:s,matchUpType:c,scaleName:u,eventId:d,zonePct:p,drawId:l,event:m}=e;if(!n&&!t)return{error:Fi};if(c&&![mf,hf].includes(c))return{error:ys,info:{matchUpType:c}};if(t&&!Ef(t))return{error:ys,context:{matchUps:t}};const f=Tv[u],h=f?.ascending??e.ascending??!1,g=f?.accessor??e.valueAccessor,I=Array.isArray(f?.range)?Math.abs(f.range[0]-f.range[1]):0,U=Vd(p)&&I?(p??0)*I:e.zoneMargin??I,y={withScaleValues:!0,withCompetitiveness:!0},S={matchUpTypes:c?[c]:[mf,hf]},v=n?.participants;t?.[0]?.hasContext?l?t=t.filter((e=>e.drawId===l)):d&&(t=t.filter((e=>e.eventId===d))):void 0===t&&(t=l&&!i&&[]||!l&&d&&!m&&[]||l&&zU({inContext:!0,drawDefinition:i,contextFilters:S,contextProfile:y,participants:v})?.matchUps||!l&&d&&KU({inContext:!0,contextFilters:S,contextProfile:y,participants:v,event:m})?.matchUps||yS({tournamentRecord:n,contextFilters:S,contextProfile:y})?.matchUps||[]),c&&(t=t.filter((e=>e.matchUpType===c)));const T=t.filter((({winningSide:e,score:t,sides:r,matchUpStatus:n})=>![zm,jm,Km,Bm,km].includes(n??"")&&hg({score:t})&&2===r?.length&&e)),P=function({excludeMargin:e,exclusionRule:t,valueAccessor:r,ascending:n,scaleName:i,matchUps:a}){const o={affirmative:[],negative:[],excluded:[]};for(const s of a){const{matchUpType:a,sides:c,score:u,winningSide:d}=s;if(!d)continue;if(t&&(!t.valueAccessor||!t.range))return{info:"exclusionRule requires valueAccessor and range",error:Za};const p=d-1,l=Mb({exclusionRule:t,valueAccessor:r,matchUpType:a,scaleName:i,sides:c});if(t){const e=l.map((({exclusionValues:e})=>e)).flat();if(e.length){o.excluded.push({scoreString:u?.scoreStringSide1,exclusionValues:e,winningSide:d,sideValues:l});continue}}if(l.filter((e=>![void 0,"",null].includes(e.value))).length<2){o.excluded.push({scoreString:u?.scoreStringSide1,missingValues:!0,winningSide:d,sideValues:l});continue}const m=l[p].value-l[1-p].value,f=parseFloat(e||0),h=f&&Math.abs(m)<f;if(h){o.excluded.push({scoreString:u?.scoreStringSide1,excludeMargin:e,winningSide:d,excludeGap:h,sideValues:l,valuesGap:m});continue}const g=n?m:-1*m,I=1===d?u?.scoreStringSide1:u?.scoreStringSide2;g>0?o.affirmative.push({winningScoreString:I,winningSide:d,sideValues:l,valuesGap:m,score:u}):o.negative.push({winningScoreString:I,winningSide:d,sideValues:l,valuesGap:m,score:u})}const s=o.affirmative.length+o.negative.length,c=s&&o.affirmative.length/s*100;return o.percent=c?Math.round(100*c)/100:0,o}({matchUps:T,excludeMargin:a,exclusionRule:o,valueAccessor:g,ascending:h,scaleName:u}),D=s&&c!==mf?2*(U||0):U,w=U?T.map((({competitiveProfile:e,matchUpType:t,score:n,sides:i})=>{const a=Mb({singlesForDoubles:r,valueAccessor:g,matchUpType:t,scaleName:u,sides:i}),o=Math.abs(a[0].value-a[1].value);return{competitiveness:e?.competitiveness,valuesGap:o,score:n}})).filter((({valuesGap:e})=>e<=D)):[],b=function({zoneData:e}){const t={[Gg]:[],[qg]:[],[$g]:[]};for(const r of e){const{competitiveness:e,score:n,valuesGap:i}=r;t[e]&&t[e].push({score:n,valuesGap:i})}return t}({zoneData:w}),R=b&&[].concat(Object.values(b)).flat().length,N=R&&Object.assign({},...Object.keys(b).map((e=>({[e]:Math.round(1e4*b[e].length/R)/100})))),M=T.length-(w?.length||0);return{...Ni,relevantMatchUps:T,zoneDistribution:N,zoneData:w,accuracy:P,nonZone:M}}function Mb({singlesForDoubles:e,exclusionRule:t,valueAccessor:r,matchUpType:n,scaleName:i,sides:a}){const o=t?.range.sort(),s=e=>{const r=e?.[t?.valueAccessor];return{exclude:t&&r>=o[0]&&r<=o[1],exclusionValue:r}};return a.sort(((e,t)=>e.sideNumber-t.sideNumber)).map((({participant:t})=>{const a=[],o=t?.individualParticipants;if(o?.length){const c=[];let u=0;for(const t of o){const{scaleValue:o,value:d}=Ab({singlesForDoubles:e,valueAccessor:r,participant:t,matchUpType:n,scaleName:i}),{exclude:p,exclusionValue:l}=s(o);p&&a.push(l),c.push(o),d&&!isNaN(u)?u+=d:u=void 0}return{participantName:t.participantName,exclusionValues:a,scaleValues:c,value:u}}if(t){const{scaleValue:o,value:c}=Ab({singlesForDoubles:e,valueAccessor:r,matchUpType:n,participant:t,scaleName:i}),{exclude:u,exclusionValue:d}=s(o);return u&&a.push(d),{participantName:t.participantName,exclusionValues:a,scaleValue:o,value:c}}return{}}))}function Ab({singlesForDoubles:e,valueAccessor:t,matchUpType:r,participant:n,scaleName:i}){const a=e?mf:r,o=n?.rankings?.[a]?.find((e=>e.scaleName===i)),s=n?.ratings?.[a]?.find((e=>e.scaleName===i)),c=(s||o)?.scaleValue;return{scaleValue:c,value:t?c?.[t]:c}}function Eb({collectionDefinitions:e=[],collectionGroups:t=[]}){let r=0;const{groupValueNumbers:n}=Dn({collectionGroups:t});let i;for(const t of e||[]){const{collectionValueProfiles:e,collectionGroupNumber:a,collectionValue:o,matchUpCount:s,matchUpValue:c,scoreValue:u,setValue:d}=t,p=a&&n.includes(a);if(Fe(d||u))i=!0;else{if(p)continue;if("number"==typeof o&&Fe(o))r+=o;else if(e?.length)for(const t of e)r+=t.matchUpValue;else"number"==typeof c&&Fe(c)&&(r+=(s??0)*c)}}for(const e of t)r+=e.groupValue??0;if(i||!r)return{aggregateValue:!0,...Ni};return{valueGoal:Math.floor(r/2)+1,...Ni}}function Cb({matchUps:e,matchUpId:t}){if(!Ef(e))return{error:ys};const r=e.find((e=>e.matchUpId===t)),{drawId:n,eventId:i,structureId:a,tournamentId:o}=r||{};return{matchUpId:t,drawId:n,eventId:i,structureId:a,tournamentId:o}}function Ob(e){const{structureId:t,matchUpId:r,event:n}=e;let i=e.drawDefinition;const a=uy(e,[{[Uu]:!0},{_anyOf:{[Pu]:!1,[Ru]:!1,[_u]:!1,[Lu]:!1}}]);if(a[xu])return a;const o=BD(e,[{[Vu]:ku,[xu]:Za}]),s=o?.matchUp;if(r&&s?.error)return s;!i&&s?.drawDefinition&&(i=s?.drawDefinition);let c=s?.structure;if(!c&&t&&!r){if(!i)return{error:ra};const e=Om({drawDefinition:i,structureId:t});if(e.error)return e;c=e.structure}const u=c?.matchUpFormat,d=i?.matchUpFormat,p=n?.matchUpFormat;return{structureDefaultMatchUpFormat:u,eventDefaultMatchUpFormat:p,drawDefaultMatchUpFormat:d,matchUpFormat:s?.matchUp?.matchUpFormat||u||d||p}}function Fb({profileBands:e,tournamentRecord:t,matchUps:r}){if(!Ef(r))return{error:Va};const n=!e&&YU({policyType:Qu,tournamentRecord:t}).policy,i=e||n?.profileBands||WU[Qu].profileBands,a=r.filter((({winningSide:e})=>e)),o=a.map(nb),s=ab(o).reduce(((e,t)=>((e,t)=>(e[rb(t,i)]+=1,e))(e,t)),{[Gg]:0,[qg]:0,[$g]:0,[Bg]:0}),c=Object.keys(s).reduce(((e,t)=>(s[t]||0)+e),0),u=Object.keys(s).map((e=>({[e]:100*parseFloat((s[e]/c).toFixed(4))}))),d=a.filter((({matchUpStatus:e})=>e===jg)).length;return u.push({[jg]:100*parseFloat((d/c).toFixed(4))}),{competitiveBands:Object.assign({},...u),...Ni}}function kb({defaultRecoveryMinutes:e=0,defaultAverageMinutes:t,tournamentRecords:r,matchUpFormat:n,categoryName:i,categoryType:a,tournamentId:o,eventType:s,eventId:c}){if(!uv({matchUpFormat:n}))return{error:Na};let u;return Object.keys(r).filter((e=>!o||e===o)).forEach((e=>{if(u)return;const t=r[e],o=c?ly({tournamentRecord:t,eventId:c})?.event:void 0;return u=Vw({tournamentRecord:t,matchUpFormat:n,categoryName:i,categoryType:a,eventType:s,event:o}),u?.averageMinutes||u?.recoveryMinutes})),{recoveryMinutes:u?.recoveryMinutes||e,averageMinutes:u?.averageMinutes||t,typeChangeRecoveryMinutes:u?.typeChangeRecoveryMinutes||u?.recoveryMinutes||e}}function _b(e){const{containerStructureId:t,roundSegment:r,isRoundRobin:n,tournamentId:i,roundNumber:a,structureId:o,eventId:s,drawId:c}=e,u=n?t:o,d=[i,s,c,u,a].join("|");return Mf({structureId:u,roundSegment:r,tournamentId:i,roundNumber:a,eventId:s,drawId:c,id:d})}function xb({round:e,matchUps:t,events:r,tournamentRecords:n}){const i=r.find((t=>t.eventId===e.eventId)),{eventType:a,category:o,categoryType:s}=i||{},{categoryName:c,ageCategoryCode:u}=o||{},d=$d(t.map((({matchUpFormat:e})=>e)));let p=0;return Object.keys(d).forEach((t=>{const r=d[t],i=kb({categoryName:c||u,tournamentId:e.tournamentId,eventId:e.eventId,tournamentRecords:n,matchUpFormat:t,categoryType:s,eventType:a});if(i.error)return i;const o=i.averageMinutes*r;isNaN(p)||(p+=o)})),{roundMinutes:p}}function Lb(e){const t=e.length,r=e.filter((({sides:e})=>e?.some((({bye:e})=>e)))).length||0,n=e.filter((({winningSide:e,matchUpStatus:t})=>e||rf.includes(t))).length||0,i=e.filter((({schedule:e,matchUpStatus:t})=>e?.scheduledDate&&e?.scheduledTime&&t!==xm)).length||0,a=t-r;return{unscheduledCount:a-i,incompleteCount:a-i,scheduledCount:i,completedCount:n,matchUpsCount:t,isScheduled:a===i,isComplete:a===n,byeCount:r}}function Vb({tournamentRecords:e,schedulingProfile:t,tournamentRecord:r,withRoundId:n}){if(r&&!e){if("object"!=typeof r)return{error:ki};e={[r.tournamentId]:r}}if(t){const r=FT({tournamentRecords:e,schedulingProfile:t});if(r.error)return r}if(!t&&e){const r=LT({tournamentRecords:e});if(r.error)return r;t=r.schedulingProfile}if(!t)return{error:ws};const i={};return{profileRounds:t.map((({venues:e,scheduleDate:t})=>e.map((({rounds:e})=>e.map((e=>{const r=_b(e);return r.roundSegment?.segmentsCount&&(i[r.id]=r.roundSegment.segmentsCount),Mf({id:n?r.id:void 0,scheduleDate:t,...r})})))))).flat(1/0),segmentedRounds:i}}const{stageOrder:Bb}=jl;function jb(e,t){return e.eventName.localeCompare(t.eventName)||e.eventId.localeCompare(t.eventId)||(Bb[e?.stage]||0)-(Bb[t?.stage]||0)||t.matchUpsCount-e.matchUpsCount||`${e.stageSequence}-${e.roundNumber}-${e.minFinishingSum}`.localeCompare(`${t.stageSequence}-${t.roundNumber}-${t.minFinishingSum}`)}function Gb({excludeScheduleDateProfileRounds:e,excludeScheduledRounds:t,excludeCompletedRounds:r,inContextMatchUps:n,tournamentRecords:i,schedulingProfile:a,tournamentRecord:o,withSplitRounds:s,matchUpFilters:c,scheduleDate:u,withRoundId:d,venueId:p,context:l}){if(n&&!Array.isArray(n||"object"!=typeof n[0]))return{error:ys,inContextMatchUps:n};if(o&&!i){if("object"!=typeof o)return{error:ki};i={[o.tournamentId]:o}}const m="object"!=typeof i||!Object.keys(i).length;if((p||u||!n||!a&&(e||r||a||s))&&m)return{error:Oi};const f=Object.assign({},...Object.values(i??{}).map((({venues:e=[],tournamentId:t})=>({[t]:e?.map((({venueId:e})=>e))})))),h=Object.values(i??{}).map((({events:e=[],tournamentId:t,startDate:r,endDate:n})=>e.map((e=>({...e,validVenueIds:f[t],startDate:e.startDate??r,endDate:e.endDate??n}))))).flat(),{segmentedRounds:g,profileRounds:I}=i&&(e||r||a||s)&&Vb({tournamentRecords:i,schedulingProfile:a})||{},U=e&&Object.assign({},...I.map((e=>({[e.id]:e})))),y=n||i&&SS({tournamentRecords:i,matchUpFilters:c})?.matchUps||[],S=[],v=y&&Object.values(y.reduce(((e,t)=>{const r=_b(t).id,n=g?.[r],i=[...e[r]?.matchUps??[],t],{containerStructureId:a,stageSequence:o,structureName:s,tournamentId:c,isRoundRobin:u,matchUpType:p,roundNumber:l,roundOffset:m,structureId:f,eventName:h,roundName:I,drawName:U,eventId:y,drawId:S}=t,v=u?a:f;return{...e,[r]:{id:d?r:void 0,structureId:v,stageSequence:o,segmentsCount:n,structureName:s,tournamentId:c,matchUpType:p,roundNumber:l,roundOffset:m,eventName:h,roundName:I,drawName:U,matchUps:i,eventId:y,drawId:S}}}),{})).map((e=>{const{minFinishingSum:t,winnerFinishingPositionRange:r}=(e.matchUps||[]).reduce(((e,t)=>{const r=(t.finishingPositionRange?.winner||[]).reduce(((e,t)=>e+t),0),n=(t.finishingPositionRange?.winner||[]).join("-")||"";return!e.minFinishingSum||r<e.minFinishingSum?{minFinishingSum:r,winnerFinishingPositionRange:n}:e}),{minFinishingSum:0,winnerFinishingPositionRange:""});const n=e.segmentsCount;if(n){const a=e.matchUps.length/n;return ep(e.matchUps.sort(((e,t)=>e.roundPosition-t.roundPosition)),a).map(((a,o)=>{const{unscheduledCount:s,incompleteCount:c,matchUpsCount:u,isScheduled:d,isComplete:p,byeCount:m}=Lb(a),f=xb({matchUps:e.matchUps,tournamentRecords:i,events:h,round:e});return Mf({...e,...l,roundSegment:{segmentsCount:n,segmentNumber:o+1},winnerFinishingPositionRange:r,unscheduledCount:s,incompleteCount:c,minFinishingSum:t,matchUpsCount:u,isScheduled:d,roundTiming:f,isComplete:p,byeCount:m,matchUps:a})}))}const{unscheduledCount:a,incompleteCount:o,matchUpsCount:s,isScheduled:c,isComplete:u,byeCount:d}=Lb(e.matchUps),p=xb({matchUps:e.matchUps,tournamentRecords:i,events:h,round:e});return Mf({...e,...l,winnerFinishingPositionRange:r,unscheduledCount:a,incompleteCount:o,minFinishingSum:t,matchUpsCount:s,isScheduled:c,roundTiming:p,isComplete:u,byeCount:d})})).flat().filter((n=>{if(e){const t=Lc(e),r=d?n.id:_b(n).id;if(t&&U[r]&&Lc(U[r].scheduleDate)===t)return!1}const{isComplete:i,isScheduled:a}=n,s=!r||!i,c=!t||!a,l=p||u?h?.find((({eventId:e})=>e===n.eventId)):void 0,m=l?.startDate??o?.startDate,f=l?.endDate??o?.endDate,g=!u||!m||new Date(u)>=new Date(m),I=!u||!f||new Date(u)<=new Date(f),y=g&&I,v=!p||l?.validVenueIds.includes(p),T=s&&c&&v&&y;return T||S.push(n),T})).sort(jb)||[];return{...Ni,rounds:v,excludedRounds:S}}function qb(e){const t=y(e,[{[ku]:!0}]);if(t.error)return t;const r=e?.matchUp;let n=r?.matchUpType;if(!n&&r?.sides?.length){const e=r.sides.find((({participant:e})=>e)),t=e?.participant,i=t?.participantType;n=i===gm&&mf||i===Um&&hf||i===ym&&ym||void 0}return{matchUpType:n}}function $b({ignoreTiebreak:e=!1,matchUpScoringFormat:t,matchUpFormat:r,isTiebreakSet:n,isDecidingSet:i,set:a}){if(!a)return{error:Za,info:"missing set"};t=t||r&&QI(r);const o=i&&t.finalSetFormat||t?.setFormat||{},{side1Score:s,side2Score:c}=a,{setTo:u,tiebreakAt:d}=o,p=Wb({set:a}),l=Math.abs(s-c),m=s>=u||c>=u,f=n||s>=u&&c>=u||d&&d<u&&(s===d||c===d),h=e||f&&(1===p&&a.side1TiebreakScore>a.side2TiebreakScore||2===p&&a.side2TiebreakScore>a.side1TiebreakScore),g=!f&&o.NoAD||f||n&&o.tiebreakFormat?.NoAD?1:2;return!(!(m&&(l>=g||f))&&!n||f&&!h)}function Wb({set:e}){if(e.side1Score||e.side2Score){if(e.side1Score>e.side2Score)return 1;if(e.side2Score>e.side1Score)return 2}else if(e.side1TiebreakScore||e.side2TiebreakScore){if(e.side1TiebreakScore>e.side2TiebreakScore)return 1;if(e.side2TiebreakScore>e.side1TiebreakScore)return 2}}function Hb(e){const{setObject:t,matchUpScoringFormat:r}=e;if(!t)return{error:Ka};const{setNumber:n}=t||{},{bestOf:i}=r||{},a=!(!n||!i||n!==i),o=a&&r?.finalSetFormat||r?.setFormat,s=!!o?.tiebreakSet,c=!!o?.timed,u=!s&&!c,d=!!(n&&i&&n<=i),p=[t?.side1Score,t?.side2Score],l=[t?.side1PointScore,t?.side2PointScore],m=[t?.side1TiebreakScore,t?.side2TiebreakScore],f=p.filter((e=>void 0!==e)).length,h=l.filter((e=>void 0!==e)).length,g=m.filter((e=>void 0!==e)).length,I=p?.filter((e=>!isNaN(e))).length,U=m?.filter((e=>!isNaN(e))).length,{tiebreakAt:y}=o||{},S=y&&2===p.filter((e=>e>=y)).length,v=S&&((p[0]>p[1]?1:p[1]>p[0]&&2)||void 0),T=!(!U||I),P=!!t?.winningSide,{error:D,result:w}=function({setObject:e,setFormat:t,sideGameScores:r,sideTiebreakScores:n}){if(!e)return{result:!1,error:Ka};const i=!!t?.tiebreakSet,a=!!t?.timed;if(!t||i||a)return{result:!1,error:ys};const o=2===r?.filter((e=>!isNaN(e))).length;if(!o)return{result:!1,error:so};const{setTo:s,tiebreakAt:c,tiebreakFormat:u,NoAD:d}=t||{},p=!(!s||!r?.find((e=>e>=s)));if(!p)return{result:!1,error:so};const l=[1,2].includes(e?.winningSide);if(!e||!l)return{result:!1,error:uo};const m=e?.winningSide-1,f=1-m,h=r[m],g=r[f],I=h-g;if(!(h>g))return{result:!1,error:{message:"winningSide game scoreString is not high"}};const U=c&&u,y=2===n?.filter((e=>!isNaN(e))).length,S=n?.[m],v=n?.[f],T=c&&2===r.filter((e=>e>=c)).length;if(U){const{NoAD:e,tiebreakTo:t}=u;if(T){if(I>1)return{result:!1,error:{message:"invalid winning game scoreString (5)"}};if(!y)return{result:!1,error:{message:"invalid tiebreak scores (1)"}};if(isNaN(t))return{result:!1,error:{message:"tiebreakTo error"}};if(!!(!t||!n?.find((e=>e>=t))))return{result:!1,error:{message:"invalid tiebreak scores (2)"}};if(h>(c<s?s:s+1))return{result:!1,error:{message:"invalid winning game scoreString (1)"}};if(!S||!v||S<v)return{result:!1,error:{message:"winningSide tiebreak value is not high"}};const r=S-v;if(r&&v>=t-1&&r<(e?1:2))return{result:!1,error:{message:"invalid tiebreak scores (3)"}}}if(h>s&&!T)return{result:!1,error:{message:"invalid winning game scoreString (2)"}}}const P=d?1:2,D=g>=s-1,w=I&&D&&!T&&I<P;if(w)return{result:!1,error:{message:"invalid winning game scoreString (3)"}};if(I>P&&h>s)return{result:!1,error:{message:"invalid winning game scoreString (4)"}};return{result:!0}}({setObject:t,setFormat:o,sideGameScores:p,sideTiebreakScores:m}),{error:b,result:R}=function({setObject:e,setFormat:t,sideTiebreakScores:r}){if(!e)return{result:!1,error:Ka};const n=!!t?.tiebreakSet,i=!!t?.timed;if(!t||!n||i)return{result:!1,error:{message:"not tiebreak set"}};const a=[1,2].includes(e?.winningSide);if(!e||!a)return{result:!1,error:uo};const{tiebreakSet:o}=t||{},{NoAD:s,tiebreakTo:c}=o||{},u=2===r?.filter((e=>!isNaN(e))).length;if(!u)return{result:!1,error:{message:"invalid tiebreak scores (1)"}};if(isNaN(c))return{result:!1,error:{message:"tiebreakTo error"}};const d=!!r?.find((e=>e>=c));if(!d)return{result:!1,error:{message:"invalid tiebreak scores (2)"}};const p=e?.winningSide-1,l=1-p,m=r[p],f=r[l];if(!m||!f||m<f)return{result:!1,error:{message:"winningSide tiebreak value is not high"}};const h=s?1:2,g=m-f,I=f>=c-1;if(g&&I&&g<h)return{result:!1,error:{message:"invalid tiebreak scores (3)"}};return{result:!0}}({setObject:t,setFormat:o,sideTiebreakScores:m}),N=u&&!T&&w||s&&T&&R,M=d&&!(s&&!T)&&!(u&&T)&&(!P||N),A=function({matchUpScoringFormat:e,isDecidingSet:t,isTiebreakSet:r,setObject:n}){if(!n)return;const i=Wb({set:n});return $b({matchUpScoringFormat:e,set:n,isDecidingSet:t,isTiebreakSet:r})&&i||void 0}({isDecidingSet:a,isTiebreakSet:T,matchUpScoringFormat:r,setObject:t}),E={expectTiebreakSet:s,expectTimedSet:c,hasTiebreakCondition:S,isCompletedSet:P,isDecidingSet:a,isTiebreakSet:T,isValidSet:M,isValidSetNumber:d,isValidSetOutcome:N,leadingSide:v,setFormat:o,sideGameScores:p,sideGameScoresCount:f,sidePointScores:l,sidePointScoresCount:h,sideTiebreakScores:m,sideTiebreakScoresCount:g,winningSide:A};return void 0!==t?.winningSide&&(T?(E.isValidTiebreakSetOutcome=R,R||(E.tiebreakSetError=b)):(E.isValidStandardSetOutcome=w,w||(E.standardSetError=D))),E}function zb(e){const{matchUp:t,sideNumber:r,setNumber:n,isTiebreakValue:i,isPointValue:a}=e||{};let{matchUpFormat:o}=e||{};if(!t)return{error:Ba};o=o||t?.matchUpFormat;const s=be(o),c=!!t?.winningSide,u=t.score?.sets,d=u?.length,p=n&&n-1,l=!!u?.find(((e,t)=>e.setNumber===n&&t===p)),m=u?.filter((e=>e?.winningSide))||[],f=m?.length||0,h=n&&u?.slice(n)||[],g=!!(d&&n&&h?.reduce(((e,t)=>(!t||!t.side1Score&&!t.side2Score&&!t.side1TiebreakScore&&!t.side2TiebreakScore&&!t.side1PointScore&&!t.side2PointScore)&&e),!0)),I=n<=d&&u.find((e=>e.setNumber===n)),y=I&&Hb({setObject:I,matchUpScoringFormat:s}),{isCompletedSet:S,sideGameScores:v,sideTiebreakScores:T}=y||{},P=!!(I&&!S&&g||n&&n===d+1&&!c),D=[1,2].includes(r),w=D?r-1:0,b=I&&D&&(!i&&!a&&void 0!==v[w]&&v[w]||i&&void 0!==T[w]&&T[w]),R=!!b,N=m?.map((e=>Hb({setObject:e,matchUpScoringFormat:s}).isValidSetOutcome)).reduce(((e,t)=>e&&t),!0),M=m.reduce(((e,t)=>{const{winningSide:r}=t;return e[r-1]++,e}),[0,0]),A=t?.winningSide,E=A&&A-1,C=1-E,O=M[E],F=M[C],k=Math.max(...M),_=U(M)[k],{bestOf:x}=s??{},L=k===(x&&Math.ceil(x/2)||1)&&1===_&&M.indexOf(k)+1||void 0,V=O>F&&A===L;return{completedSetsHaveValidOutcomes:N,validMatchUpWinningSide:V,calculatedWinningSide:L,matchUpScoringFormat:s,validMatchUpOutcome:L&&N&&V,isLastSetWithValues:g,completedSetsCount:f,isCompletedMatchUp:c,isValidSideNumber:D,hasExistingValue:R,existingValue:b,isExistingSet:l,isActiveSet:P,...y}}function Yb({participants:e,tournamentAppliedPolicies:t,scheduleVisibilityFilters:r,participantsProfile:n,afterRecoveryTimes:i,policyDefinitions:a,useParticipantMap:o,tournamentRecord:s,usePublishState:c,contextFilters:u,contextContent:d,matchUpFilters:p,participantMap:l,publishStatus:m,contextProfile:f,drawDefinition:h,nextMatchUps:g,tournamentId:I,inContext:U,context:y,event:S}){const{eventId:v,eventName:T,endDate:P}=S??{},D={...y,...Mf({eventId:v,eventName:T,endDate:P??S?.endDate??s?.endDate,tournamentId:I??s?.tournamentId,indoorOutDoor:S?.indoorOutdoor??s?.indoorOutdoor,surfaceCategory:S?.surfaceCategory??s?.surfaceCategory})};let w;!e?.length&&s&&({participants:e,participantMap:l,groupInfo:w}=$U({participantsProfile:n,policyDefinitions:a,useParticipantMap:o,tournamentRecord:s,contextProfile:f,inContext:U})),S&&f&&!d&&(d=HU({policyDefinitions:a,tournamentRecord:s,contextProfile:f,drawDefinition:h,event:S}));return{...Cm({context:D,tournamentAppliedPolicies:t,scheduleVisibilityFilters:r,tournamentParticipants:e,participantsProfile:n,afterRecoveryTimes:i,policyDefinitions:a,tournamentRecord:s,usePublishState:c,participantMap:l,contextContent:d,contextFilters:u,matchUpFilters:p,publishStatus:m,contextProfile:f,drawDefinition:h,nextMatchUps:g,inContext:U,event:S}),groupInfo:w}}var Qb=Object.freeze({__proto__:null,allCompetitionMatchUps:SS,allDrawMatchUps:zU,allEventMatchUps:KU,allTournamentMatchUps:yS,analyzeMatchUp:zb,calculateWinCriteria:Eb,checkMatchUpIsComplete:Rb,competitionScheduleMatchUps:eb,drawMatchUps:Yb,eventMatchUps:Jw,getAllDrawMatchUps:Em,getCheckedInParticipantIds:xD,getCompetitionMatchUps:Xw,getEventMatchUpFormatTiming:Ww,getMatchUpCompetitiveProfile:ob,getMatchUpContextIds:Cb,getMatchUpDailyLimits:bb,getMatchUpDailyLimitsUpdate:Hw,getMatchUpDependencies:TS,getMatchUpFormat:Ob,getMatchUpFormatTiming:Vw,getMatchUpFormatTimingUpdate:Pw,getMatchUpScheduleDetails:wb,getMatchUpType:qb,getMatchUpsStats:Fb,getModifiedMatchUpFormatTiming:JT,getPredictiveAccuracy:Nb,getRoundMatchUps:Cf,getRounds:Gb,isValidMatchUpFormat:uv,matchUpActions:hS,participantScheduledMatchUps:Yw,tallyParticipantResults:gU,tournamentMatchUps:Zw,validMatchUp:Af,validMatchUps:Ef}),Kb=Object.freeze({__proto__:null,allCompetitionMatchUps:SS,allDrawMatchUps:zU,allEventMatchUps:KU,allTournamentMatchUps:yS,analyzeMatchUp:zb,applyLineUps:Iw,assignMatchUpSideParticipant:kD,assignTieMatchUpParticipantId:YD,bulkMatchUpStatusUpdate:pw,calculateWinCriteria:Eb,checkInParticipant:$D,checkMatchUpIsComplete:Rb,checkOutParticipant:qD,competitionScheduleMatchUps:eb,disableTieAutoCalc:iw,drawMatchUps:Yb,enableTieAutoCalc:tw,eventMatchUps:Jw,findMatchUp:LD,getAllDrawMatchUps:Em,getCheckedInParticipantIds:xD,getCompetitionMatchUps:Xw,getEventMatchUpFormatTiming:Ww,getMatchUpCompetitiveProfile:ob,getMatchUpContextIds:Cb,getMatchUpDailyLimits:bb,getMatchUpDailyLimitsUpdate:Hw,getMatchUpDependencies:TS,getMatchUpFormat:Ob,getMatchUpFormatTiming:Vw,getMatchUpFormatTimingUpdate:Pw,getMatchUpScheduleDetails:wb,getMatchUpType:qb,getMatchUpsStats:Fb,getModifiedMatchUpFormatTiming:JT,getPredictiveAccuracy:Nb,getRoundMatchUps:Cf,getRounds:Gb,isValidMatchUpFormat:uv,matchUpActions:hS,mutate:vw,participantScheduledMatchUps:Yw,query:Qb,removeDelegatedOutcome:rw,removeMatchUpSideParticipant:JD,removeTieMatchUpParticipantId:KD,replaceTieMatchUpParticipantId:zD,resetMatchUpLineUps:ow,resetScorecard:Sw,resetTieFormat:Uw,setDelegatedOutcome:mw,setMatchUpFormat:aw,setMatchUpStatus:dw,setOrderOfFinish:gw,substituteParticipant:nw,tallyParticipantResults:gU,toggleParticipantCheckInState:WD,tournamentMatchUps:Zw,updateTieMatchUpScore:fw,validMatchUp:Af,validMatchUps:Ef});const Jb=e=>{const{isSide1:t,lowValue:r,setTo:n,tiebreakAt:i,NoAD:a}=e;if(void 0===r)return!1;let o,s=Ed(r);s?.toString().length>2&&(s=parseInt(s.toString().slice(0,2))),i&&i<n&&s>i&&(s=i),a&&!i?(s>n&&(o=n),o=s<n?n:n-1):o=s+1<n&&n||i&&i<n&&s===i&&n||!i&&s+2||n+1;return[t?s:o,t?o:s]},Zb=e=>{const{isSide1:t,lowValue:r,tiebreakTo:n,tiebreakNoAd:i}=e;if(void 0===r)return!1;let a="string"==typeof r?parseInt(r):r;a?.toString().length>2&&(a=parseInt(a.toString().slice(0,2))),i&&a>n-1&&(a=n-1);const o=function(e){const{lowValue:t,NoAD:r,tiebreakTo:n}=e,i=r?1:2;if(t+1>=n)return t+i;return n}({lowValue:a,NoAD:i,tiebreakTo:n});return[t?a:o,t?o:a]};function Xb({tiebreakTo:e=7,scoreString:t=""}){return t?.split(" ").filter(Boolean).map(((t,r)=>function({set:t,setNumber:r}){const n=t?.startsWith("[")&&t.split("[")[1].split("]")[0].split("-").map((e=>parseInt(e))),i=t.includes("(")&&t.split("(")[0]||t.includes("[")&&t.split("[")[0]||t,a=!n&&i.split("-").map((e=>parseInt(e))),o=n?(n[0]>n[1]?1:n[0]<n[1]&&2)||void 0:(a[0]>a[1]?1:a[0]<a[1]&&2)||void 0,s=t.includes("(")?t.split("(")[1].split(")")[0]:void 0,c=(s&&Zb({lowValue:s,isSide1:2===o,tiebreakTo:e}))??[],[u,d]=a||[],[p,l]=n||c||[];return{side1Score:u,side2Score:d,side1TiebreakScore:p,side2TiebreakScore:l,winningSide:o,setNumber:r}}({set:t,setNumber:r+1})))}function eR(e){const{matchUpFormat:t,matchUpStatus:r,winningSide:n,scoreString:i}=e;if(!i)return{outcome:{...iI,winningSide:n,matchUpStatus:r}};if(n&&![1,2,void 0].includes(n))return{error:ys,winningSide:n};const a=i&&Xb({scoreString:i}),o={},s=sw({sets:a,matchUpFormat:t}),c=sw({sets:a,reversed:!0,matchUpFormat:t});return 2===n?(o.scoreStringSide1=c,o.scoreStringSide2=s):(o.scoreStringSide1=s,o.scoreStringSide2=c),o.sets=Xb({scoreString:o.scoreStringSide1}),Mf({outcome:{matchUpStatus:r,winningSide:n,score:o}})}function tR({tournamentRecord:e,drawDefinition:t,event:r}){const n=e?.events||r&&[r],i=n?.map((e=>e?.drawDefinitions)).flat().filter(Boolean)||t&&[t]||[],a={},o={},s=i.map((e=>e?.structures?.filter((e=>e?.structures)))).flat().filter(Boolean);for(const e of s){const{structures:t,structureId:r}=e??{};t&&r&&(a[r]=t?.map((e=>e.structureId)))&&t.forEach((t=>o[t.structureId]=e?.structureId))}return{containedStructures:a,containerStructures:o}}function rR(e){const t="addMatchUpScheduledTime";let r=e.matchUp;const{removePriorValues:n,tournamentRecord:i,drawDefinition:a,disableNotice:o,scheduledTime:s,matchUpId:c}=e;if(!c)return pd({result:{error:_a},stack:t});if(!wc(s))return pd({result:{error:ao},stack:t});if(!r){const e=xv({drawDefinition:a,matchUpId:c});if(e.error)return pd({result:e,stack:t});r=e.matchUp}const u=Lc(s),d=db({matchUp:r}).scheduledDate,p=u&&!d,l=Tb({matchUp:r}).timeModifiers||[];if(l?.length){const e=nR({disableNotice:!0,removePriorValues:n,tournamentRecord:i,timeModifiers:[],drawDefinition:a,matchUpId:c,matchUp:r});if(e?.error)return pd({result:e,stack:t})}const m=jc(s,!0,p);return GD({duplicateValues:!1,removePriorValues:n,tournamentRecord:i,drawDefinition:a,disableNotice:o,matchUpId:c,timeItem:{itemType:mI,itemValue:m}})}function nR({removePriorValues:e,tournamentRecord:t,drawDefinition:r,disableNotice:n,timeModifiers:i,matchUpId:a,matchUp:o}){const s="addMatchUpTimeModifiers";if(!a)return pd({result:{error:_a},stack:s});if(void 0!==i&&!Array.isArray(i))return pd({info:SU("timeModifiers"),result:{error:ys},stack:s});if(!o){const e=xv({drawDefinition:r,matchUpId:a});if(e.error)return pd({result:e,stack:s});o=e.matchUp}let c=Tb({matchUp:o}).timeModifiers||[];const u=i.filter((e=>!c.includes(e)));if(i.length&&!u.length)return{...Ni};if(u.some((e=>DI.includes(e)))){c=c.filter((e=>!DI.includes(e)));const n=rR({disableNotice:!0,removePriorValues:e,scheduledTime:"",tournamentRecord:t,drawDefinition:r,matchUpId:a});if(n.error)return pd({result:n,stack:s})}const d=i?.length?[...u,...c]:void 0;return GD({duplicateValues:!1,removePriorValues:e,tournamentRecord:t,drawDefinition:r,disableNotice:n,matchUpId:a,timeItem:{itemType:UI,itemValue:d}})}function iR({removePriorValues:e,tournamentRecords:t,tournamentRecord:r,drawDefinition:n,disableNotice:i,matchUpId:a,venueId:o}){if(!r)return{error:Fi};if(!a)return{error:_a};if(o){const e=gb({tournamentRecords:t,tournamentRecord:r,venueId:o});if(e.error)return e}return GD({duplicateValues:!1,removePriorValues:e,tournamentRecord:r,drawDefinition:n,disableNotice:i,matchUpId:a,timeItem:{itemType:sI,itemValue:o}})}function aR({matchUpScheduleTimes:e,matchUpDependencies:t,allDateMatchUpIds:r,matchUp:n}){const i=(t?.[n.matchUpId]?.matchUpIds||[]).filter((e=>r.includes(e))),a=i.filter((t=>!e[t]));return{dependenciesScheduled:!a?.length,remainingDependencies:a}}function oR({matchUpPotentialParticipantIds:e,matchUpNotBeforeTimes:t,timeAfterRecovery:r,matchUp:n}){const{individualParticipantIds:i}=IS(n);r=r??n.schedule?.timeAfterRecovery;const a=t=>{e[t]||(e[t]=[]),e[t]=jd(e[t].concat(...i))},o=e=>{r&&(!t[e]||r>t[e])&&(t[e]=r)},s=n.winnerTo?.matchUpId||n.winnerMatchUpId;s&&(r&&o(s),a(s));const c=n.loserTo?.matchUpId||n.loserMatchUpId;c&&(r&&o(c),a(c)),n.sidesTo?.length&&n.sidesTo.forEach((({matchUpId:e})=>{e&&(r&&o(e),a(e))}))}function sR({individualParticipantProfiles:e,participantId:t}){e[t]||(e[t]={typeChangeTimeAfterRecovery:void 0,timeAfterRecovery:void 0,priorMatchUpType:void 0,potentialRecovery:{},potentialCounted:{},potentialBookings:{},bookings:[],counters:{}})}function cR({matchUpPotentialParticipantIds:e,individualParticipantProfiles:t,typeChangeRecoveryMinutes:r,averageMatchUpMinutes:n=0,matchUpNotBeforeTimes:i,matchUpDependencies:a,recoveryMinutes:o=0,scheduleTime:s,matchUp:c}){const u=xc(c?.schedule?.endTime),d=u?Hc(u,Ed(o)):Hc(s,Ed(n)+Ed(o)),p=r&&(u?Hc(xc(u),r):Hc(s,Ed(n)+Ed(r))),l=a?.[c.matchUpId]?.participantIds||[],m=(c.roundPosition&&e[c.matchUpId]||[]).flat();l.forEach((e=>{sR({individualParticipantProfiles:t,participantId:e});const r=t[e].priorMatchUpType!==c.matchUpType&&p||d;m.includes(e)?function({individualParticipantProfiles:e,recoveryValue:t,participantId:r,scheduleTime:n,drawId:i}){e[r].potentialRecovery[i]||(e[r].potentialRecovery[i]=[]),e[r].potentialRecovery[i].push(t),e[r].potentialBookings[i]||(e[r].potentialBookings[i]=[]),e[r].potentialBookings[i].push({timeAfterRecovery:t,scheduleTime:n})}({individualParticipantProfiles:t,drawId:c.drawId,recoveryValue:r,participantId:e,scheduleTime:s}):(t[e].timeAfterRecovery=r,t[e].bookings.push({scheduleTime:s,timeAfterRecovery:r}))})),oR({matchUpPotentialParticipantIds:e,matchUpNotBeforeTimes:i,timeAfterRecovery:d,matchUp:c})}function uR({matchUpScheduleTimes:e,matchUpDependencies:t,scheduleTime:r,matchUpId:n,details:i}){let a;const o=i.minutesMap?.[n]?.recoveryMinutes,s=i.minutesMap?.[n]?.averageMinutes,c=Hc(r,(s||0)+(o||0)),u=t?.[n]?.dependentMatchUpIds||[];if(u.length){const t=u.reduce(((t,r)=>{const n=e[r];if(!n)return t;const i={scheduleTime:n,matchUpId:r};return n&&!t.matchUpId||kc(n)<kc(t.scheduleTime)?i:t}),{});t.scheduleTime&&kc(c)>kc(t.scheduleTime)&&(a=t)}return{scheduledDependent:a}}const dR="DO_NOT_SCHEDULE",pR={DO_NOT_SCHEDULE:dR};function lR({averageMatchUpMinutes:e=90,requestConflicts:t={},potentials:r=!0,personRequests:n,scheduleTime:i,scheduleDate:a,matchUp:o}){const s=function(e){const{sides:t,matchUpType:r}=e||{};return(t||[]).map((e=>r===hf&&(e?.participant?.individualParticipants||[])||e?.participant&&[e.participant]||[])).flat()}(o).map((({person:e})=>e?.personId));if(r){const e=(o?.potentialParticipants||[]).flat().map((({person:e})=>e?.personId));s.push(...e)}const c=s.map((e=>n[e]?.map((t=>({...t,personId:e}))))).filter(Boolean).flat().filter((e=>e.requestType===dR&&Qc(a,e.date))),u=[],d=o?.matchUpId,p=$c(xc(i),Lc(a)),l=xc(zc(p,e).toISOString());for(const e of c){const{requestId:r,startTime:n,endTime:a}=e;(i>n&&i<a||l>n&&l<a)&&(u.push({matchUpId:d,request:e,scheduleTime:i}),t[r]?(t[r].scheduleTimes.includes(i)||t[r].scheduleTimes.push(i),t[r].matchUpIds.includes(d)||t[r].matchUpIds.push(d)):t[r]={request:e,scheduleTimes:[i],matchUpIds:[d]})}return{conflicts:u}}function mR({scheduleCompletedMatchUps:e,containedStructureIds:t,tournamentRecords:r,periodLength:n=30,matchUps:i,rounds:a}){if("object"!=typeof r)return{error:Oi};if(!Array.isArray(a))return{error:Za,info:SU("rounds")};const o={},s=[];a.sort(((e,t)=>(e.sortOrder??0)-(t.sortOrder??0))),t=t??Object.assign({},...Object.values(r).map((e=>tR({tournamentRecord:e}).containedStructures))),i||({matchUps:i}=SS({nextMatchUps:!0,tournamentRecords:r}));let c=0;const u={},d={},p={},l=a.flatMap((a=>{const l=a.periodLength||n,m=[];t?.[a.structureId]?m.push(...t[a.structureId]):m.push(a.structureId);let f=i?function(e){const{matchUps:t,isCollectionMatchUp:r,excludeMatchUpStatuses:n,matchUpStatuses:i,hasWinningSide:a,matchUpFormats:o,roundPositions:s,matchUpFormat:c,collectionIds:u,isMatchUpTie:d,roundNumbers:p,matchUpIds:l,roundNames:m,stageSequences:f,scheduledDates:h,scheduledDate:g,participantIds:I,processContext:U,tournamentIds:y,matchUpTypes:S,structureIds:v,readyToScore:T,courtIds:P,eventIds:D,venueIds:w,drawIds:b,stages:R,filterMatchUpIds:N=!0,filterMatchUpTypes:M=!0}=e,A=Array.isArray(I)?I.filter(Boolean):[],E=Array.isArray(i)?i.filter(Boolean):[],C=Array.isArray(n)?n.filter(Boolean):[],O=Array.isArray(R)?R.filter(Boolean):[],F=Array.isArray(f)?f.filter(Boolean):[],k=Array.isArray(u)?u.filter(Boolean):[],_=Array.isArray(m)?m.filter(Boolean):[],x=Array.isArray(p)?p.filter(Boolean):[],L=Array.isArray(s)?s.filter(Boolean):[],V=Array.isArray(l)&&N?l.filter(Boolean):[],B=Array.isArray(S)&&M?S.filter(Boolean):[],j=Array.isArray(P)?P.filter(Boolean):[],G=Array.isArray(w)?w.filter(Boolean):[],q=Array.isArray(o)&&o.filter(Boolean)||"string"==typeof c&&[c]||[],$=Array.isArray(h)&&h.filter(Boolean)||"string"==typeof g&&g.length&&[g]||[],W=Array.isArray(y)?y.filter(Boolean):[],H=Array.isArray(D)?D.filter(Boolean):[],z=Array.isArray(b)?b.filter(Boolean):[],Y=Array.isArray(v)?v.filter(Boolean):[];return t.filter((e=>{if(T&&e.matchUpType!==gf&&!e.readyToScore)return!1;if(e.winningSide&&a&&![1,2].includes(e.winningSide))return!1;if(void 0!==d){if(d&&!e.tieMatchUps)return!1;if(!d&&e.tieMatchUps)return!1}if(void 0!==r){if(r&&!e.collectionId)return!1;if(!r&&e.collectionId)return!1}if(O.length&&!O.includes(e.stage))return!1;if(F.length&&!F.includes(e.stageSequence))return!1;if(k.length&&(!e.collectionId||!k.includes(e.collectionId)))return!1;if(_.length&&(!e.roundName||!_.includes(e.roundName)))return!1;if(x.length&&(!e.roundNumber||!x.includes(e.roundNumber)))return!1;if(L.length&&(!e.roundPosition||!L.includes(e.roundPosition)))return!1;if(E.length&&(!e.matchUpStatus||!E.includes(e.matchUpStatus)))return!1;if(C.length&&e.matchUpStatus&&C.includes(e.matchUpStatus))return!1;if(V.length&&!V.includes(e.matchUpId))return!1;if(B.length&&(!e.matchUpType||!B.includes(e.matchUpType)))return!1;if(q.length&&(!e.matchUpFormat||!q.includes(e.matchUpFormat)))return!1;if($?.length){const{scheduledTime:t}=ub({matchUp:e}),{scheduledDate:r}=db({matchUp:e}),n=Lc(t)||r;if(!$.find((e=>Qc(e,n))))return!1}if(j.length){const{courtId:t}=lb({matchUp:e}),{allocatedCourts:r}=pb({matchUp:e}),n=r?.map((({courtId:e})=>e));if(!j.filter(Boolean).includes(t)||n?.includes(t))return!1}if(G.length){const{venueId:t}=mb({matchUp:e});if(!G.filter(Boolean).includes(t))return!1}if(U){if(W.length&&!W.includes(e.tournamentId))return!1;if(H.length&&!H.includes(e.eventId))return!1;if(z.length&&!z.includes(e.drawId))return!1;if(Y.length&&!Y.includes(e.structureId))return!1;if(A.length){const t=e.sides?.map((({participantId:e})=>e)).filter(Boolean)??[];if(!A.some((e=>t.includes(e))))return!1}}return!0}))}({tournamentIds:[a.tournamentId],roundNumbers:[a.roundNumber],matchUpIds:a.matchUpIds,eventIds:[a.eventId],drawIds:[a.drawId],processContext:!0,structureIds:m,matchUps:i}).sort(vS):[];const{segmentNumber:h,segmentsCount:g}=a.roundSegment||{};if(Vd(h)&&Cd(f?.length)&&Cd(g)&&h>0&&h<=g&&g<f?.length&&!a.matchUpIds?.length){const e=f.length/g,t=e*(h-1);f=f.slice(t,t+e)}const I=r[a.tournamentId],U=ly({drawId:a.drawId,tournamentRecord:I}).event,y=[];for(const e of f){const t=e.matchUpFormat;t&&(o[t]||(o[t]=[],o[t].push(e)),y.push(t))}for(const t of y){const{eventType:n,category:i}=U??{},{categoryName:o,ageCategoryCode:m}=i??{},{typeChangeRecoveryMinutes:h,recoveryMinutes:g,averageMinutes:I,error:y}=kb({categoryName:o??m,categoryType:i?.categoryType,tournamentId:a.tournamentId,eventId:a.eventId,tournamentRecords:r,matchUpFormat:t,eventType:n});if(y)return{error:y,round:a};const S=f.filter((t=>(e||!rf.includes(t.matchUpStatus))&&t.matchUpStatus!==xm)).map(Nd);S.forEach((e=>{p[e]={typeChangeRecoveryMinutes:h,recoveryMinutes:g,averageMinutes:I},u[e]=g,d[e]=I})),s.push(...S),c=Math.max(I||0,c);return{roundPeriodLength:l,recoveryMinutes:g,averageMinutes:I,matchUpIds:S,hash:`${I}|${l}`}}}));return{scheduledRoundsDetails:l,greatestAverageMinutes:c,matchUpFormatCohorts:o,recoveryMinutesMap:u,averageMinutesMap:d,orderedMatchUpIds:s,minutesMap:p,...Ni}}function fR({scheduledRoundsDetails:e,greatestAverageMinutes:t,garmanSinglePass:r}){const n=[];let i,a,o,s,c=[];for(const u of e.filter(Boolean))s||(s=u.hash),(u.hash===s||r)&&(c=c.concat(u.matchUpIds)),u.hash===s||r||(s=u.hash,n.push({averageMinutes:o,recoveryMinutes:a,roundPeriodLength:i,matchUpIds:c}),c=u.matchUpIds),o=r?t:u.averageMinutes,a=u.recoveryMinutes,i=u.roundPeriodLength;return c.length&&n.push({matchUpIds:c,roundPeriodLength:i,recoveryMinutes:a,averageMinutes:o}),{groupedRounds:n}}function hR({matchUpPotentialParticipantIds:e,individualParticipantProfiles:t,matchUp:r,value:n}){const{matchUpType:i}=r,{individualParticipantIds:a}=IS(r),o=(e[r.matchUpId]||[]).filter((e=>!Xd(e,a))).flat();[...a,...o].forEach((e=>{if(sR({individualParticipantProfiles:t,participantId:e}),!t[e].potentialCounted[r.drawId]){const a=t[e].counters;a[i]?a[i]+=n:n>0&&(a[i]=n),a[Mw]?a[Mw]+=n:n>0&&(a[Mw]=n),o.includes(e)&&(t[e].potentialCounted[r.drawId]=!0)}}))}function gR({matchUpPotentialParticipantIds:e,individualParticipantProfiles:t,dateScheduledMatchUpIds:r,greatestAverageMinutes:n,dateScheduledMatchUps:i,matchUpNotBeforeTimes:a,matchUpScheduleTimes:o,matchUpDependencies:s,clearScheduleDates:c,scheduleDate:u,minutesMap:d,matchUps:p}){const l=[];r||(i=p?.filter((e=>{const t=e.schedule||{},r=e.matchUpStatus===xm;return r&&l.push({tournamentId:e.tournamentId,matchUpId:e.matchUpId}),!r&&zw({schedule:t})&&(!u||e.schedule.scheduledDate===u)})),r=i.map(Nd));const m=Array.isArray(c)?c.includes(u):c,f=m?[]:p.filter((({matchUpId:e})=>r.includes(e)));for(const r of f){hR({matchUpPotentialParticipantIds:e,individualParticipantProfiles:t,value:1,matchUp:r});const i=r.schedule?.scheduledTime;if(i){o[r.matchUpId]=i;const c=d?.[r.matchUpId]?.recoveryMinutes;cR({individualParticipantProfiles:t,matchUpPotentialParticipantIds:e,matchUpNotBeforeTimes:a,matchUpDependencies:s,averageMatchUpMinutes:n,recoveryMinutes:c,scheduleTime:i,matchUp:r})}}return{dateScheduledMatchUpIds:r,byeScheduledMatchUpDetails:l,dateScheduledMatchUps:i,clearDate:m}}function IR({matchUpPotentialParticipantIds:e,scheduleCompletedMatchUps:t,dateScheduledMatchUpIds:r,matchUpNotBeforeTimes:n,matchUpScheduleTimes:i,orderedMatchUpIds:a,clearDate:o,matchUps:s}){const c=Object.keys(i),u=a.map((e=>s.find((t=>t.matchUpId===e)))).filter(Boolean).filter((e=>{const n=!o&&(r.includes(e.matchUpId)||c.includes(e.matchUpId)),i=[xm,jm,Vm,km,zm,Km,qm,Gm].includes(e?.matchUpStatus);return t||!n&&!e.winningSide&&!i})),{matchUpMap:d}=u.reduce(((t,r)=>{const{drawId:i,tournamentId:a}=r;return t.matchUpMap[a]||(t.matchUpMap[a]={}),t.matchUpMap[a][i]?t.matchUpMap[a][i].push(r):t.matchUpMap[a][i]=[r],oR({matchUpPotentialParticipantIds:e,matchUpNotBeforeTimes:n,matchUp:r}),t}),{matchUpMap:{}});return{matchUpsToSchedule:u,matchUpMap:d}}function UR({averageMatchUpMinutes:e,periodLength:t=30,recoveryMinutes:r}){const n=(e||90)+(r||0);return t>n?n:t||30}function yR({defaultRecoveryMinutes:e=0,averageMatchUpMinutes:t=90,dateScheduledMatchUps:r,tournamentRecords:n,venueIds:i=[],periodLength:a,scheduleDate:o,matchUps:s}){if("object"!=typeof n)return{error:Oi};if(!Ef(s)&&!Array.isArray(r))return{error:Va};a=a??UR({recoveryMinutes:e,averageMatchUpMinutes:t});const c=Object.assign({},...Object.values(n).map((e=>(e.events??[]).map((t=>{const{scheduleTiming:r}=QU({tournamentRecord:e,event:t});return{[t.eventId]:{event:t,scheduleTiming:r}}})))).flat()),u={averageTimes:[{minutes:{default:t}}],recoveryTimes:[{minutes:{default:e}}]};r||(r=s?.filter((e=>{const t=e.schedule;return zw({schedule:t})&&(!o||e.schedule.scheduledDate===o)})));const d=r?.filter((e=>(!i.length||i.includes(e.schedule.venueId))&&e.matchUpStatus!==xm)),p=d?.map((({eventId:e,schedule:t,matchUpFormat:r})=>{const{event:n,scheduleTiming:i}=c[e],o=n?.eventType,s={...i,defaultTiming:u,matchUpFormat:r},{averageMinutes:d,recoveryMinutes:p}=Bw({timingDetails:s,eventType:o}),{courtId:l,venueId:m}=t,f=xc(t.scheduledTime),h=Hc(f,d);return{recoveryMinutes:p,averageMinutes:d,periodLength:a,startTime:f,courtId:l,endTime:h,venueId:m}})).filter(Boolean);return{bookings:p,relevantMatchUps:d,dateScheduledMatchUps:r}}function SR({calculateStartTimeFromCourts:e=!0,remainingScheduleTimes:t,defaultRecoveryMinutes:r,averageMatchUpMinutes:n,clearScheduleDates:i,tournamentRecords:a,tournamentRecord:o,periodLength:s,scheduleDate:c,startTime:u,venueIds:d,matchUps:p,endTime:l}){if(o&&!a&&(a={[o.tournamentId]:o}),"object"!=typeof a||!Object.keys(a).length)return{error:Oi};s=s??UR({recoveryMinutes:r,averageMatchUpMinutes:n});const{courts:m,venues:f}=_T({dates:[c],ignoreDisabled:!0,tournamentRecords:a}),h=m?.filter((e=>!d||d.includes(e.venueId)))??[];u=u??MD({courts:h,scheduleDate:c,startTime:!0}),l=l??MD({courts:h,scheduleDate:c,endTime:!0});const{bookings:g,dateScheduledMatchUps:I}=yR({defaultRecoveryMinutes:r,averageMatchUpMinutes:n,tournamentRecords:a,scheduleDate:c,periodLength:s,venueIds:d,matchUps:p}),U={calculateStartTimeFromCourts:e,remainingScheduleTimes:t,averageMatchUpMinutes:n,clearScheduleDates:i,date:c,periodLength:s,startTime:u,bookings:g,endTime:l,courts:h},{scheduleTimes:y}=AD(U),S=1===d?.length&&d[0]||1===f?.length&&f[0].venueId||void 0,v=I?.map(au("matchUpId"));return{dateScheduledMatchUpIds:v,dateScheduledMatchUps:I,scheduleTimes:y,venueId:S}}function vR({matchUpPotentialParticipantIds:e,individualParticipantProfiles:t,scheduleCompletedMatchUps:r,containedStructureIds:n,matchUpNotBeforeTimes:i,matchUpScheduleTimes:a,matchUpDependencies:o,clearScheduleDates:s,tournamentRecords:c,periodLength:u,scheduleDate:d,useGarman:p,matchUps:l,courts:m,venues:f}){const h={},g=[],I=[],U=[];for(const y of f){const{rounds:f=[],venueId:S}=y,{scheduledRoundsDetails:v,greatestAverageMinutes:T,orderedMatchUpIds:P,minutesMap:D}=mR({scheduleCompletedMatchUps:r,containedStructureIds:n,tournamentRecords:c,periodLength:u,matchUps:l,rounds:f});U.push(...P??[]);const{groupedRounds:w}=fR({scheduledRoundsDetails:v,greatestAverageMinutes:T,garmanSinglePass:!0});let b,R,N=[];p&&({scheduleTimes:N,dateScheduledMatchUpIds:b,dateScheduledMatchUps:R}=SR({averageMatchUpMinutes:w[0]?.averageMinutes,scheduleDate:Lc(d),venueIds:[y.venueId],clearScheduleDates:s,tournamentRecords:c,periodLength:u,matchUps:l}));const M=gR({matchUpPotentialParticipantIds:e,individualParticipantProfiles:t,dateScheduledMatchUpIds:b,greatestAverageMinutes:T,matchUpNotBeforeTimes:i,matchUpScheduleTimes:a,matchUpDependencies:o,clearScheduleDates:s,scheduleDate:d,minutesMap:D,matchUps:l});({dateScheduledMatchUpIds:b,dateScheduledMatchUps:R}=M);const{byeScheduledMatchUpDetails:A,clearDate:E}=M;A?.length&&I.push(...A);const{matchUpsToSchedule:C,matchUpMap:O}=IR({matchUpPotentialParticipantIds:e,scheduleCompletedMatchUps:r,dateScheduledMatchUpIds:b,matchUpNotBeforeTimes:i,matchUpScheduleTimes:a,orderedMatchUpIds:P,clearDate:E,matchUps:l}),F=m.filter((e=>e.venueId===S));h[S]={previousRemainingScheduleTimes:[],courtsCount:F.length,greatestAverageMinutes:T,scheduledRoundsDetails:v,dateScheduledMatchUps:R,matchUpsToSchedule:C,scheduleTimes:N,groupedRounds:w,venueCourts:F,minutesMap:D,matchUpMap:O},s||g.push(...b)}return{allDateScheduledByeMatchUpDetails:I,allDateScheduledMatchUpIds:g,venueScheduledRoundDetails:h,allDateMatchUpIds:U}}function TR({individualParticipantProfiles:e,matchUpNotBeforeTimes:t,matchUpDependencies:r,scheduleTime:n,matchUp:i,details:a}){const o=(r?.[i.matchUpId]?.participantIds||[]).flat(),s=a?.minutesMap?.[i.matchUpId]?.averageMinutes||0,c=a?.minutesMap?.[i.matchUpId]?.recoveryMinutes||0,u=o.every((t=>{sR({individualParticipantProfiles:e,participantId:t});const r=e[t];if(!r.timeAfterRecovery)return!0;const a=xc(i?.schedule?.endTime),o=a?Hc(a,Ed(c)):Hc(n,Ed(s)+Ed(c));return!!![...Object.keys(r.potentialBookings).filter((e=>e!==i.drawId)).map((e=>r.potentialBookings[e])).flat(),...r.bookings].find((e=>function(e,t){const r=kc(e.scheduleTime),n=kc(e.timeAfterRecovery),i=kc(t.scheduleTime),a=kc(t.timeAfterRecovery),o=r>i&&r<a,s=i>r&&i<n,c=n>i&&n<a,u=a>r&&a<n;return Mf({hasOverlap:r===i||n===a||o||c||s||u,startAisContained:o,endAisContained:c,startBisContained:s,endBisContained:u},!0)}({scheduleTime:n,timeAfterRecovery:o},e).hasOverlap))})),d=t[i.matchUpId],p=d?Wc($c(d),$c(n),!1):0;return{enoughTime:u&&p>=0}}function PR({individualParticipantProfiles:e,matchUpPotentialParticipantIds:t,matchUpDailyLimits:r={},matchUp:n}){const{matchUpId:i,matchUpType:a}=n,{enteredIndividualParticipantIds:o}=IS(n),s=(n.roundPosition&&t[i]||[]).flat(),c=jd(o.concat(...s));c.forEach((t=>{sR({individualParticipantProfiles:e,participantId:t})}));return{participantIdsAtLimit:c.filter((t=>{const n=e[t];if(n)return[a,Mw].find((e=>{const t=n.counters?.[e]||0,i=r[e]||0;return t&&i&&t>=i}))})),relevantParticipantIds:c}}function DR({removePriorValues:e,tournamentRecords:t,tournamentRecord:r,drawDefinition:n,disableNotice:i,courtDayDate:a,matchUpId:o,courtIds:s}){if(!r&&!t)return{error:Fi};if(!o)return{error:_a};const c=xv({drawDefinition:n,matchUpId:o});if(c.error)return c;if(c?.matchUp?.matchUpType!==gf)return{error:ja};if(!(void 0===s||Array.isArray(s)&&s.length&&s.every((e=>"string"==typeof e))))return{error:ys,context:{courtIds:s}};let u;if(s){const e=_T({tournamentRecords:t||r&&{[r.tournamentId]:r}});if(e.error)return e;const n=e.courts?.filter((e=>s.includes(e.courtId)));if(n?.length!==s.length)return{error:ys,context:{courtIds:s}};u=n?.map((e=>({venueId:e.venueId,courtId:e.courtId})))}return GD({duplicateValues:!1,removePriorValues:e,tournamentRecord:r,drawDefinition:n,disableNotice:i,matchUpId:o,timeItem:{itemType:cI,itemDate:a,itemValue:u}})}function wR({removePriorValues:e,tournamentRecords:t,tournamentRecord:r,drawDefinition:n,disableNotice:i,courtDayDate:a,matchUpId:o,courtId:s}){if(!r&&!t)return{error:Fi};if(!o)return{error:_a};if(s){const e=Ub({tournamentRecords:t,tournamentRecord:r,courtId:s});if(e.error)return e;const a=e.venue?.venueId;iR({tournamentRecords:t,tournamentRecord:r,drawDefinition:n,disableNotice:i,matchUpId:o,venueId:a})}return GD({duplicateValues:!1,removePriorValues:e,tournamentRecord:r,drawDefinition:n,disableNotice:i,matchUpId:o,timeItem:{itemType:uI,itemDate:a,itemValue:s}})}function bR(e,t){const r=Lr.test(e)?e:xc(e),n=Lc(e)||Lc(t)||Nc(new Date);return new Date(`${n}T${r}`).getTime()}function RR({errorOnAnachronism:e=!1,checkChronology:t=!0,matchUpDependencies:r,inContextMatchUps:n,removePriorValues:i,tournamentRecords:o,tournamentRecord:s,drawDefinition:c,disableNotice:u,drawMatchUps:d,matchUpId:p,schedule:l,event:m}){if(!l)return{error:Za,info:"Missing schedule"};if(!c)return{error:Li};if(!p)return{error:_a};const f="addMatchUpScheduleItems";let h,g;if(d)h=d.find((e=>e.matchUpId===p));else{const e=Jt({drawDefinition:c,event:m,matchUpId:p});if(e.error)return e;h=e.matchUp}const{endTime:I,courtId:U,courtIds:y,courtOrder:S,resumeTime:v,scheduledDate:T,scheduledTime:P,startTime:D,stopTime:w,timeModifiers:b,venueId:R}=l;!t||r&&n||({matchUpDependencies:r,matchUps:n}=kt({drawDefinition:c}));const N=r?.[p]?.matchUpIds;if(l.scheduledDate&&t&&N){const t=n?.filter((e=>(e.schedule?.scheduledDate||Lc(e.schedule?.scheduledTime))&&N.includes(e.matchUpId))).map((({schedule:e})=>{const t=Pc(e);return new Date(t).getTime()}));if(t?.length){const r=Pc(l),n=new Date(r).getTime();if(Math.max(...t)>=n){if(e)return a({result:{error:Ai},stack:f});g=Ai}}}if(void 0!==T){const e=NR({disableNotice:!0,removePriorValues:i,tournamentRecord:s,drawDefinition:c,scheduledDate:T,matchUpId:p});if(e?.error)return a({result:e,stack:f,context:{scheduledDate:T}})}if(void 0!==P){const e=rR({disableNotice:!0,removePriorValues:i,tournamentRecord:s,drawDefinition:c,scheduledTime:P,matchUpId:p,matchUp:h});if(e?.error)return a({result:e,stack:f,context:{scheduledTime:P}})}if(void 0!==D){const e=ER({disableNotice:!0,removePriorValues:i,tournamentRecord:s,drawDefinition:c,matchUpId:p,startTime:D,event:m});if(e?.error)return a({result:e,stack:f,context:{startTime:D}})}if(void 0!==w){const e=OR({disableNotice:!0,removePriorValues:i,tournamentRecord:s,drawDefinition:c,matchUpId:p,stopTime:w,event:m});if(e?.error)return a({result:e,stack:f,context:{stopTime:w}})}if(void 0!==v){const e=FR({disableNotice:!0,removePriorValues:i,tournamentRecord:s,drawDefinition:c,resumeTime:v,matchUpId:p,event:m});if(e?.error)return a({result:e,stack:f,context:{resumeTime:v}})}if(void 0!==I){const e=CR({disableNotice:!0,removePriorValues:i,tournamentRecord:s,drawDefinition:c,matchUpId:p,endTime:I,event:m});if(e?.error)return a({result:e,stack:f,context:{endTime:I}})}if(void 0!==y){const e=DR({disableNotice:!0,removePriorValues:i,tournamentRecord:s,drawDefinition:c,matchUpId:p,courtIds:y});if(e?.error)return a({result:e,stack:f,context:{courtIds:y}})}if(void 0!==U&&void 0!==T){const e=wR({courtDayDate:T,disableNotice:!0,removePriorValues:i,tournamentRecords:o,tournamentRecord:s,drawDefinition:c,matchUpId:p,courtId:U});if(e?.error)return a({result:e,stack:f,context:{courtId:U}})}if(void 0!==R){const e=iR({disableNotice:!0,removePriorValues:i,tournamentRecords:o,tournamentRecord:s,drawDefinition:c,matchUpId:p,venueId:R});if(e?.error)return a({result:e,stack:f,context:{venueId:R}})}if(void 0!==S&&Fe(S)){const e=MR({disableNotice:!0,removePriorValues:i,tournamentRecord:s,drawDefinition:c,courtOrder:S,matchUpId:p});if(e?.error)return a({result:e,stack:f,context:{courtOrder:S}})}if(void 0!==b){const e=nR({disableNotice:!0,removePriorValues:i,tournamentRecord:s,drawDefinition:c,timeModifiers:b,matchUpId:p,matchUp:h});if(e?.error)return a({result:e,stack:f,context:{timeModifiers:b}})}return u||q({tournamentId:s?.tournamentId,eventId:m?.eventId,context:f,drawDefinition:c,matchUp:h}),g?{...Ni,warnings:[g]}:{...Ni}}function NR({scheduledDate:e,removePriorValues:t,tournamentRecord:r,drawDefinition:n,disableNotice:i,matchUpId:a}){if(!a)return{error:_a};const o=e&&xr.test(e);if(e&&!o)return{error:io};return GD({duplicateValues:!1,removePriorValues:t,tournamentRecord:r,drawDefinition:n,disableNotice:i,matchUpId:a,timeItem:{itemValue:Lc(e),itemType:pI}})}function MR({removePriorValues:e,tournamentRecord:t,drawDefinition:r,disableNotice:n,courtOrder:i,matchUpId:a}){if(!a)return{error:_a};if(i&&!Fe(i))return{error:ys,info:"courtOrder must be numeric"};const o=i&&ve(i);return GD({duplicateValues:!1,removePriorValues:e,tournamentRecord:t,drawDefinition:r,disableNotice:n,matchUpId:a,timeItem:{itemType:dI,itemValue:o}})}function AR({removePriorValues:e,tournamentRecord:t,drawDefinition:r,disableNotice:n,participantId:i,officialType:a,matchUpId:o}){if(!o)return{error:_a};if(!i)return{error:Do};if(t){const e=pt({tournamentRecord:t,participantFilters:{participantTypes:[gm],participantRoles:[Xv]}}).participants??[];if(!Oe({tournamentParticipants:e,participantId:i}))return{error:wo}}const s={itemType:"SCHEDULE.ASSIGNMENT.OFFICIAL",itemValue:i};return a&&(s.itemSubTypes=[a]),GD({duplicateValues:!1,removePriorValues:e,tournamentRecord:t,drawDefinition:r,disableNotice:n,matchUpId:o,timeItem:s})}function ER({removePriorValues:e,tournamentRecord:t,drawDefinition:r,disableNotice:n,matchUpId:i,startTime:a,event:o}){if(!i)return{error:_a};if(!wc(a))return{error:ao};const{matchUp:s}=Jt({drawDefinition:r,event:o,matchUpId:i}),{scheduledDate:c}=wn({matchUp:s}),u=(s?.timeItems??[]).filter((e=>[hI,gI,II].includes(e?.itemType))).map((e=>bR(e.itemValue,c))).reduce(((e,t)=>!e||t<e?t:e),void 0);if(!u||bR(a,c)<u){s?.timeItems&&(s.timeItems=s.timeItems.filter((e=>e.itemType!==fI)));const o=jc(a,!0,!0);return GD({duplicateValues:!1,removePriorValues:e,tournamentRecord:t,drawDefinition:r,disableNotice:n,matchUpId:i,timeItem:{itemType:fI,itemValue:o}})}return{error:ts}}function CR({validateTimeSeries:e=!0,removePriorValues:t,tournamentRecord:r,drawDefinition:n,disableNotice:i,matchUpId:a,endTime:o,event:s}){if(!a)return{error:_a};if(!wc(o))return{error:ao};const{matchUp:c}=Jt({drawDefinition:n,event:s,matchUpId:a}),{scheduledDate:u}=wn({matchUp:c}),d=(c?.timeItems??[]).filter((e=>[fI,gI,hI].includes(e?.itemType))).map((e=>bR(e.itemValue,u))).reduce(((e,t)=>!e||t>e?t:e),void 0);if(!e||!d||bR(o,u)>d){c?.timeItems&&(c.timeItems=c.timeItems.filter((e=>e.itemType!==II)));const e=jc(o,!0,!0);return GD({duplicateValues:!1,removePriorValues:t,tournamentRecord:r,drawDefinition:n,disableNotice:i,matchUpId:a,timeItem:{itemType:II,itemValue:e}})}return{error:Zo}}function OR({removePriorValues:e,tournamentRecord:t,drawDefinition:r,disableNotice:n,matchUpId:i,stopTime:a,event:o}){if(!i)return{error:_a};if(!wc(a))return{error:ao};const{matchUp:s}=Jt({drawDefinition:r,event:o,matchUpId:i}),{scheduledDate:c}=wn({matchUp:s}),u=s?.timeItems??[];if(u.reduce(((e,t)=>t.itemType===II||e),void 0))return{error:Xo};const d=u.filter((e=>[fI,gI,hI].includes(e?.itemType))).sort(((e,t)=>bR(e.itemValue,c)-bR(t.itemValue,c))),p=d[d.length-1],l=p&&p.itemType===hI,m=d.filter((e=>!l||e.createdAt!==p.createdAt)).map((e=>bR(e.itemValue,c))).reduce(((e,t)=>!e||t>e?t:e),void 0);if(bR(a,c)>m){if(s?.timeItems&&l){const e=p.createdAt;s.timeItems=s.timeItems.filter((t=>t.createdAt!==e))}return GD({duplicateValues:!0,removePriorValues:e,tournamentRecord:t,drawDefinition:r,disableNotice:n,matchUpId:i,timeItem:{itemValue:jc(a,!0,!0),itemType:hI}})}return{error:es}}function FR({removePriorValues:e,tournamentRecord:t,drawDefinition:r,disableNotice:n,resumeTime:i,matchUpId:a,event:o}){if(!a)return{error:_a};if(!wc(i))return{error:ao};const{matchUp:s}=Jt({drawDefinition:r,event:o,matchUpId:a}),{scheduledDate:c}=wn({matchUp:s}),u=s?.timeItems??[];if(u.reduce(((e,t)=>t.itemType===II||e),void 0))return{error:Xo};const d=u.filter((e=>[fI,gI,hI].includes(e?.itemType))).sort(((e,t)=>bR(e.itemValue,c)-bR(t.itemValue,c))),p=d[d.length-1],l=p&&p.itemType===gI,m=d.filter((e=>!l||e.createdAt!==p.createdAt)).map((e=>bR(e.itemValue,c))).reduce(((e,t)=>!e||t>e?t:e),void 0);if(bR(i,c)>m){if(s?.timeItems&&l){const e=p.createdAt;s.timeItems=s.timeItems.filter((t=>t.createdAt!==e))}return GD({duplicateValues:!0,removePriorValues:e,tournamentRecord:t,drawDefinition:r,disableNotice:n,matchUpId:a,timeItem:{itemValue:jc(i,!0,!0),itemType:gI}})}return{error:rs}}function kR({scheduleCompletedMatchUps:e=!1,scheduleByeMatchUps:t=!1,errorOnAnachronism:r=!1,checkChronology:n=!0,matchUpDependencies:i,removePriorValues:a,tournamentRecords:o,tournamentRecord:s,matchUpDetails:c,matchUpIds:u,schedule:d}){if(!s)return{error:Fi};if(!(c||u&&Array.isArray(u)))return{error:xa};if(!(c||d&&"object"==typeof d))return{error:cs};let p;const l=[];let m=0;if(n&&!i){const e=TS({tournamentRecords:o,tournamentRecord:s});i=e.matchUpDependencies,p=e.matchUps}p||(p=yS({tournamentRecord:s})?.matchUps??[]);const f=p.reduce(((r,n)=>{const{matchUpId:i,drawId:a,matchUpStatus:o}=n;return!t&&o===xm||!e&&rf.includes(o)||(r[a]?r[a].push(i):r[a]=[i]),r}),{}),h=c?.map((e=>e.matchUpId));for(const e of Object.keys(f)){const{drawDefinition:t}=my({tournamentRecord:s,drawId:e});if(!t)continue;const g=f[e].filter((e=>u?.includes(e)??h?.includes(e))),I=zU({inContext:!1,drawDefinition:t}).matchUps;for(const e of g){const u=RR({schedule:c?.find((t=>t.matchUpId===e))?.schedule||d,matchUpDependencies:i,errorOnAnachronism:r,removePriorValues:a,inContextMatchUps:p,tournamentRecords:o,tournamentRecord:s,checkChronology:n,drawDefinition:t,drawMatchUps:I,matchUpId:e});if(u?.warnings?.length&&l.push(...u.warnings),u?.success&&(m+=1),u.error)return u}}return l.length?{...Ni,scheduled:m,warnings:l}:{...Ni,scheduled:m}}function _R(e){const{scheduleCompletedMatchUps:t=!1,scheduleByeMatchUps:r=!1,errorOnAnachronism:n,matchUpContextIds:i,removePriorValues:a,tournamentRecords:o,checkChronology:s,matchUpDetails:c,schedule:u}=e;if(e.matchUpIds&&!i)return kR(e);const d=uy(e,[{[gu]:!0},{[Wu]:{matchUpContextIds:!1,matchUpDetails:!1},[qu]:ys,[$u]:ju}]);if(d.error)return d;if((!c||i)&&!u)return{error:Za,info:"schedule is required"};const p=[];let l=0;const{matchUpDependencies:m}=TS({tournamentRecords:o});for(const e of Object.values(o)){const{tournamentId:d}=e,f=i?.filter((e=>e.tournamentId===d)).map(Nd),h=c?.filter((e=>e?.tournamentId===d));if(f?.length||h?.length){const i=kR({matchUpDetails:h,scheduleCompletedMatchUps:t,scheduleByeMatchUps:r,matchUpDependencies:m,errorOnAnachronism:n,removePriorValues:a,tournamentRecords:o,tournamentRecord:e,checkChronology:s,matchUpIds:f,schedule:u});if(i.warnings?.length&&p.push(...i.warnings),i.scheduled&&(l+=i.scheduled),i.error)return i}}return p.length?{...Ni,scheduled:l,warnings:p}:{...Ni,scheduled:l}}function xR({autoSchedulingAudit:e,tournamentRecords:t}){rc({topic:mp,payload:e});const r=e=>{if(!e)return 0;return Object.values(e).reduce(((e,t)=>e+t.length||0),0)},n=(e?.schedulingProfile||[]).reduce(((e,t)=>e+t.venues.reduce(((e,t)=>e+t.rounds.length),0)),0),i={scheduledDatesCount:e.scheduledDates?.length,noTimeMatchUpIdsCount:r(e?.noTimeMatchUpIds),scheduledMatchUpIdsCount:r(e?.scheduledMatchUpIds),overLimitMatchUpIdsCount:r(e?.overLimitMatchUpIds),requestConflictsCount:r(e?.requestConflicts),profileRoundsCount:n},a={itemType:HT,itemValue:i};for(const e of Object.values(t))dg({tournamentRecord:e,timeItem:a})}function LR(e){const{tournamentRecords:t,requestType:r}=e,n=uy(e,[{[gu]:!0}]);if(n.error)return n;const i={};for(const e of Object.values(t)){const{extension:t}=Wl({element:e,name:Ii}),n=t?.value||[];for(const e of n){const{personId:t,requests:n}=e||{};i[t]||(i[t]=[]);for(const e of n)r&&e.requestType!==r||i[t].push(e)}}return{personRequests:i,...Ni}}function VR(e){const{remainingScheduleTimes:t=[],clearScheduleDates:r,periodLength:n=30,scheduleDate:i,courts:a=[]}=e;let{bookings:o=[]}=e;if(!Array.isArray(a)||!a.length)return{error:ys,courts:a};if(!Array.isArray(o))return{error:to};if(!bc(i))return{error:io};r&&(Array.isArray(r)?r.includes(i)&&(o=[]):o=[]);const{courtBookings:s,unassignedBookings:c}=o.reduce(((e,t)=>{const{courtId:r}=t;return r?e.courtBookings[r]?e.courtBookings[r].push(t):e.courtBookings[r]=[t]:e.unassignedBookings.push(t),e}),{courtBookings:{},unassignedBookings:[]}),u=a.map(((e,r)=>{const{courtId:n,courtName:a}=e,o=s[n]||[],c=bD({date:i,court:e})||{},{bookings:u=[],startTime:d,endTime:p,date:l}=c;return{courtId:n,courtName:a,dateAvailability:{bookings:[t[r]&&{startTime:d,endTime:t[r]},...Jc(u,!1,!0),...o].filter(Boolean),startTime:d,endTime:p,date:l}}}));c.sort(((e,t)=>kc(e.startTime)-kc(t.startTime)));const d=[];for(const e of c){const{startTime:t,endTime:r,averageMinutes:i,recoveryMinutes:a,matchUpId:o}=e,s=kc(t),c=kc(r),p=u.map((e=>{const t=e.dateAvailability,{timeSlots:r=[]}=RD({courtDate:t});return{courtName:e.courtName,courtId:e.courtId,timeSlots:r}})).flat().reduce(((e,{courtId:t,courtName:r,timeSlots:i})=>{let a;return i.find((({startTime:t,endTime:r})=>{a=kc(t)-s;const i=s>=kc(t);return c<=kc(r)&&0!==e.startDifference&&((0===a||a+n>=0)&&(void 0===e.startDifference||a<e.startDifference)||i)}))?{courtName:r,courtId:t,startDifference:a}:e}),{});if(p.courtId){const e={averageMinutes:i,recoveryMinutes:a,matchUpId:o,startTime:t,endTime:r};d.push(e);const n=u.find((({courtId:e})=>e===p.courtId));n?.dateAvailability.bookings.push(e)}else console.log({unassignedBooking:e})}return{virtualCourts:u.map((({courtId:e,courtName:t,dateAvailability:r})=>({dateAvailability:[r],courtName:t,courtId:e}))),assignedBookings:d}}function BR({averageMinutes:e,startTime:t,endTime:r,court:n,date:i}){if(!Array.isArray(n.dateAvailability))return{error:Za,stack:"getEarliestCourtTime"};const a=MD({scheduleDate:i,courts:[n],startTime:!0}),o=MD({scheduleDate:i,courts:[n],endTime:!0});t=t||a,r=r||o;const s=bD({court:n,date:i}),{timeSlots:c}=RD({courtDate:s}),u=$c(t),d=$c(r),p=c?.reduce(((t,r)=>{const n=$c(r.startTime),i=$c(r.endTime);if(n>d||i<u)return t;const a=u>n?u:n;if(Wc(a,i)>=e){const e=xc(a.toISOString());(!t||e<t)&&(t=e)}return t}),void 0);return{earliestCourtTime:p,courtStartTime:a,courtEndTime:o}}function jR(e){const{scheduleAttributes:t=["scheduledDate","scheduledTime"],ignoreMatchUpStatuses:r=rf,scheduledDates:n,venueIds:i}=e,a=bn(e),o=mt(a)?Object.values(a).map((({tournamentId:e})=>e)).filter(Boolean):[];if(!o?.length)return{error:Oi};let s=0;for(const e of o){const o=GR({ignoreMatchUpStatuses:r,scheduleAttributes:t,tournamentRecord:a[e],scheduledDates:n,venueIds:i});if(o.error)return o;s+=o.clearedScheduleCount??0}return{...Ni,clearedScheduleCount:s}}function GR({scheduleAttributes:e=["scheduledDate","scheduledTime"],ignoreMatchUpStatuses:t=rf,tournamentRecord:r,scheduledDates:n,venueIds:i=[]}){if("object"!=typeof r)return{error:Fi};if(!Array.isArray(t)||!Array.isArray(i))return{error:ys};i.length&&e.push("venueId");const a=(Lt({matchUpFilters:{scheduledDates:n},tournamentRecord:r}).matchUps??[]).filter((r=>r.matchUpStatus&&!t.includes(r.matchUpStatus)&&zw({schedule:r.schedule,scheduleAttributes:e})&&(!i?.length||i.includes(r.schedule.venueId)))).map(T),o=Lt({tournamentRecord:r,inContext:!1}).matchUps??[];let s=0;for(const e of o)a.includes(e.matchUpId)&&(e.timeItems=(e.timeItems??[]).filter((e=>e?.itemType&&![cI,uI,sI,pI,mI].includes(e?.itemType))),s+=1);return{...Ni,clearedScheduleCount:s}}function qR(e){const{checkPotentialRequestConflicts:t=!0,scheduleCompletedMatchUps:r,clearScheduleDates:n,scheduleDates:i=[],tournamentRecords:a,periodLength:o,useGarman:s,dryRun:c,pro:u}=e,d=uy(e,[{[gu]:!0},{[Gu]:e=>!e||Array.isArray(e)&&e.every(bc),[Tu]:!1,[$u]:ju}]);if(d.error)return d;const p=LT({tournamentRecords:a});if(p.error)return p;if(!p.schedulingProfile.length)return{...Ni};const{modifications:l,issues:m=[],schedulingProfile:f=[]}=p,h=Object.assign({},...Object.values(a).map((e=>tR({tournamentRecord:e}).containedStructures))),g=i.map((e=>{if(bc(e))return Lc(e)})).filter(Boolean),I=f.map((e=>e.scheduleDate)).map((e=>bc(e)&&Lc(e))).filter((e=>e&&(!i.length||g.includes(e))));if(!I.length)return{error:eo};if(n&&!c){jR({tournamentRecords:a,scheduledDates:Array.isArray(n)?n:[]})}const U=_T({ignoreDisabled:!1,tournamentRecords:a}).courts,{matchUps:y}=SS({matchUpFilters:{matchUpTypes:[mf,hf]},afterRecoveryTimes:!0,nextMatchUps:!0,tournamentRecords:a}),{matchUpDependencies:S}=TS({includeParticipantDependencies:!0,tournamentRecords:a,matchUps:y}),{matchUpDailyLimits:v}=bb({tournamentRecords:a}),{personRequests:T}=LR({requestType:dR,tournamentRecords:a}),P={schedulingProfileModifications:l,checkPotentialRequestConflicts:t,scheduleCompletedMatchUps:r,schedulingProfileIssues:m,dateSchedulingProfiles:f.filter((e=>{const t=Lc(e?.scheduleDate);return I.includes(t)})).sort(((e,t)=>new Date(e.scheduleDate).getTime()-new Date(t.scheduleDate).getTime())),containedStructureIds:h,matchUpDependencies:S,matchUpDailyLimits:v,clearScheduleDates:n,tournamentRecords:a,schedulingProfile:f,personRequests:T,periodLength:o,useGarman:s,matchUps:y,dryRun:c,courts:U};return u?function({schedulingProfileModifications:e,checkPotentialRequestConflicts:t,scheduleCompletedMatchUps:r,schedulingProfileIssues:n,dateSchedulingProfiles:i,containedStructureIds:a,matchUpDependencies:o,matchUpDailyLimits:s,clearScheduleDates:c,tournamentRecords:u,periodLength:d=30,schedulingProfile:p,personRequests:l,matchUps:m=[],courts:f,dryRun:h}){const g={},I={},U={},y={},S={},v={},T={},P={},D={};for(const e of i??[]){const n=Lc(e?.scheduleDate),i=e?.venues||[],p={},w={},b=(e,t)=>{e.forEach((e=>{const r=w[e].counters;r[t]?r[t]+=1:r[t]=1,r[Mw]?r[Mw]+=1:r[Mw]=1}))};g[n]={},I[n]={},v[n]=[],T[n]=[],P[n]=[],D[n]=[];const R={};m?.forEach((e=>{e.schedule?.scheduledDate&&Qc(n,Lc(e.schedule.scheduledDate))&&oR({matchUpPotentialParticipantIds:p,matchUpNotBeforeTimes:R,matchUp:e})}));const{allDateScheduledByeMatchUpDetails:N,allDateScheduledMatchUpIds:M,venueScheduledRoundDetails:A,allDateMatchUpIds:E}=vR({matchUpPotentialParticipantIds:p,individualParticipantProfiles:w,scheduleCompletedMatchUps:r,containedStructureIds:a,matchUpNotBeforeTimes:R,matchUpScheduleTimes:S,matchUpDependencies:o,clearScheduleDates:c,tournamentRecords:u,periodLength:d,scheduleDate:n,matchUps:m,courts:f,venues:i}),C=m?.filter((({matchUpId:e})=>M.includes(e))),{bookings:O}=yR({dateScheduledMatchUps:C,tournamentRecords:u,scheduleDate:n,periodLength:d}),{virtualCourts:F}=VR({scheduleDate:n,periodLength:d,bookings:O,courts:f}),k=F?.reduce(((e,t)=>{const{earliestCourtTime:r,courtEndTime:i}=BR({date:n,averageMinutes:0,court:t});return(!e.startTime||$c(r)<$c(e.startTime))&&(e.startTime=r),(!e.endTime||$c(i)>$c(e.endTime))&&(e.endTime=i),e}),{});let _=k.startTime;const x=({courtId:e,booking:t})=>F?.find((t=>t.courtId===e))?.dateAvailability[0].bookings.push(t),L=10;let V,B=0;for(;!V;){for(const{venueId:e}of i){const r=A[e],i=r.matchUpsToSchedule.length,a=[],c=[];let u,m=0;for(;!u;){for(const i of r.matchUpsToSchedule){if(c.length===r.courtsCount||a.length===r.courtsCount){u=!0;break}const{matchUpId:m,matchUpType:f}=i,{participantIdsAtLimit:h,relevantParticipantIds:v}=PR({matchUpPotentialParticipantIds:p,individualParticipantProfiles:w,matchUpDailyLimits:s,matchUp:i});if(h.length){T[n].includes(m)||T[n].push(m);continue}const{dependenciesScheduled:P,remainingDependencies:N}=aR({matchUpScheduleTimes:S,matchUpDependencies:o,allDateMatchUpIds:E,matchUp:i});if(!P){I[n][m]||(I[n][m]=[]),I[n][m].push({remainingDependencies:N});continue}const M=[],A=F?.reduce(((e,a)=>{if(c.includes(a.courtId))return e;const{earliestCourtTime:s}=BR({averageMinutes:r.greatestAverageMinutes,startTime:_,date:n,court:a});if(e.scheduleTime&&kc(s)>=kc(e.scheduleTime))return e;const{scheduledDependent:u}=uR({matchUpScheduleTimes:S,matchUpDependencies:o,scheduleTime:s,matchUpId:m,details:r});if(u)return e;const{enoughTime:d}=TR({individualParticipantProfiles:w,matchUpNotBeforeTimes:R,matchUpDependencies:o,scheduleTime:s,details:r,matchUp:i});if(!d)return g[n][m]||(g[n][m]=[]),g[n][m].includes(s)||g[n][m].push(s),e;const h=r.minutesMap?.[m]?.averageMinutes||r.greatestAverageMinutes,{conflicts:I}=lR({potentials:t,averageMatchUpMinutes:h,requestConflicts:D,personRequests:l,scheduleTime:s,scheduleDate:n,matchUp:i});if(I?.length)return M.push(...I),!1;b(v,f);const U=r.minutesMap?.[m]?.recoveryMinutes;return cR({matchUpPotentialParticipantIds:p,individualParticipantProfiles:w,matchUpNotBeforeTimes:R,averageMatchUpMinutes:h,matchUpDependencies:o,recoveryMinutes:U,scheduleTime:s,matchUp:i}),(!e.scheduleTime||kc(s)<kc(e.scheduleTime))&&(e.averageMatchUpMinutes=h,e.recoveryMinutes=U,e.scheduleTime=s,e.courtName=a.courtName,e.courtId=a.courtId),e}),{});if(A.scheduleTime){const{averageMatchUpMinutes:t,recoveryMinutes:n,scheduleTime:i,courtId:o}=A;S[m]=i,y[m]=o,a.push(m),c.push(o);const s=i,u=Hc(s,t);x({courtId:o,booking:{averageMatchUpMinutes:t,recoveryMinutes:n,periodLength:d,matchUpId:m,startTime:s,courtId:o,endTime:u,venueId:e}}),r.matchUpsToSchedule=r.matchUpsToSchedule.filter((e=>e.matchUpId!==m))}else M?.length&&(U[n]||(U[n]=[]),U[n].push(...M))}c.length!==r.courtsCount&&a.length!==r.courtsCount&&r.matchUpsToSchedule.length||(u=!0),r.matchUpsToSchedule.length&&a<r.courtsCount&&($c(_)<$c(k.endTime)?_=Hc(_,d):(u=!0,r.complete=!0)),m+=1,!u&&m>=i&&(u=!0)}r.matchUpsToSchedule?.length||(r.complete=!0)}B+=1,V=i.every((({venueId:e})=>A[e].complete))||B===L}for(const{venueId:e}of i){const t=A[e].matchUpMap;Object.keys(t).forEach((e=>{const r=u[e];r&&Object.keys(t[e]).forEach((i=>{const{drawDefinition:a}=my({tournamentRecord:r,drawId:i});a&&t[e][i].forEach((({matchUpId:e})=>{const t=S[e],i=y[e];if(t){const o=t.split(":").map(Yc).join(":"),s=`${Lc(n)}T${o}`;h||(rR({drawDefinition:a,scheduledTime:s,matchUpId:e}),wR({courtDayDate:n,tournamentRecords:u,tournamentRecord:r,drawDefinition:a,matchUpId:e,courtId:i})),v[n].push(e)}}))}))})),P[n]=A[e].matchUpsToSchedule.map(Nd)}!h&&N?.length&&_R({matchUpDetails:N,scheduleByeMatchUps:!0,removePriorValues:!0,tournamentRecords:u,schedule:{scheduledDate:"",scheduledTime:"",courtOrder:"",courtId:"",venueId:""}});for(const t of e.venues)for(const e of t.rounds){const t=(e.matchUps??[]).map((({matchUpId:e})=>e)),r=t?.filter((e=>v[n].includes(e)));e.canScheduledMatchUpIds=r;let i=Math.round((r?.length||0)/e.matchUpsCount*1e4)/100;(i===1/0||isNaN(i))&&(i=void 0),e.possibleToSchedulePct=i,e.matchUpsCount===r?.length&&(e.possibleToSchedule=!0)}}const w=(i??[]).map((({scheduleDate:e})=>e)),b={timeStamp:Date.now(),overLimitMatchUpIds:T,scheduledMatchUpIds:v,schedulingProfile:p,noTimeMatchUpIds:P,requestConflicts:D,scheduledDates:w};return xR({tournamentRecords:u,autoSchedulingAudit:b}),{...Ni,schedulingProfileModifications:e,schedulingProfileIssues:n,dateSchedulingProfiles:i,recoveryTimeDeferredMatchUpIds:g,dependencyDeferredMatchUpIds:I,matchUpScheduleTimes:S,overLimitMatchUpIds:T,scheduledMatchUpIds:v,noTimeMatchUpIds:P,requestConflicts:D,scheduledDates:w}}(P):function({schedulingProfileModifications:e,checkPotentialRequestConflicts:t,scheduleCompletedMatchUps:r,schedulingProfileIssues:n,dateSchedulingProfiles:i,containedStructureIds:a,matchUpDependencies:o,matchUpDailyLimits:s,clearScheduleDates:c,tournamentRecords:u,schedulingProfile:d,personRequests:p,periodLength:l,matchUps:m,courts:f,dryRun:h}){const g={},I={},U={},y={},S={},v={},T={},P={},D={},w={};for(const e of i){const n=Lc(e?.scheduleDate),i=e?.venues||[],d={},b={},R=(e,t)=>{e.forEach((e=>{const r=b[e].counters;r[t]?r[t]+=1:r[t]=1,r[Mw]?r[Mw]+=1:r[Mw]=1}))};U[n]={},y[n]={},g[n]={},I[n]={},T[n]=[],P[n]=[],D[n]=[],w[n]=[];const N={};m.forEach((e=>{e.schedule?.scheduledDate&&Qc(n,Lc(e.schedule.scheduledDate))&&oR({matchUpPotentialParticipantIds:d,matchUpNotBeforeTimes:N,matchUp:e})}));const{allDateScheduledByeMatchUpDetails:M,venueScheduledRoundDetails:A,allDateMatchUpIds:E}=vR({matchUpPotentialParticipantIds:d,individualParticipantProfiles:b,scheduleCompletedMatchUps:r,containedStructureIds:a,matchUpNotBeforeTimes:N,matchUpScheduleTimes:v,matchUpDependencies:o,clearScheduleDates:c,tournamentRecords:u,useGarman:!0,periodLength:l,scheduleDate:n,matchUps:m,courts:f,venues:i}),C=10;let O,F=0;const k=10;for(;!O;){for(const{venueId:e}of i){let r=0;const i=A[e];for(;i.courtsCount&&i.scheduleTimes?.length&&i.matchUpsToSchedule?.length&&r<=i.courtsCount;){const{scheduleTime:a,attempts:c=0}=i.scheduleTimes.shift(),u=i.matchUpsToSchedule.find((e=>{const{matchUpId:r,matchUpType:c}=e,{participantIdsAtLimit:u,relevantParticipantIds:l}=PR({matchUpPotentialParticipantIds:d,individualParticipantProfiles:b,matchUpDailyLimits:s,matchUp:e});if(u.length)return P[n].includes(r)||P[n].push(r),!1;const{scheduledDependent:m}=uR({matchUpScheduleTimes:v,matchUpDependencies:o,scheduleTime:a,matchUpId:r,details:i});if(m)return!1;const{dependenciesScheduled:f,remainingDependencies:h}=aR({matchUpScheduleTimes:v,matchUpDependencies:o,allDateMatchUpIds:E,matchUp:e});if(!f)return y[n][r]||(y[n][r]=[]),y[n][r].push({scheduleTime:a,remainingDependencies:h}),!1;const{enoughTime:g}=TR({individualParticipantProfiles:b,matchUpNotBeforeTimes:N,matchUpDependencies:o,scheduleTime:a,details:i,matchUp:e});if(!g)return U[n][r]||(U[n][r]=[]),U[n][r].push({scheduleTime:a}),!1;const I=i.greatestAverageMinutes,{conflicts:T}=lR({potentials:t,averageMatchUpMinutes:I,requestConflicts:w,personRequests:p,scheduleTime:a,scheduleDate:n,matchUp:e});if(T?.length)return S[n]||(S[n]=[]),S[n].push(...T),!1;R(l,c);const D=i.minutesMap?.[r]?.recoveryMinutes;return cR({matchUpPotentialParticipantIds:d,individualParticipantProfiles:b,matchUpNotBeforeTimes:N,averageMatchUpMinutes:I,matchUpDependencies:o,recoveryMinutes:D,scheduleTime:a,matchUp:e}),v[r]=a,!0}));i.matchUpsToSchedule=i.matchUpsToSchedule.filter((({matchUpId:e})=>e!==u?.matchUpId)),u?r+=1:(I[n][e]||(I[n][e]=[]),I[n][e].push({scheduleTime:a,attempts:c+1}))}i.matchUpsToSchedule?.length&&(I[n][e]=I[n][e]?.filter((e=>{const t=e.attempts<C;return t&&i.scheduleTimes.push(e),!t}))),i.scheduleTimes?.length&&i.matchUpsToSchedule?.length||(i.complete=!0)}F+=1,O=i.every((({venueId:e})=>A[e].complete))||F===k}for(const{venueId:e}of i){const t=A[e].matchUpMap;Object.keys(t).forEach((r=>{const i=u[r];i&&Object.keys(t[r]).forEach((a=>{const{drawDefinition:o}=my({tournamentRecord:i,drawId:a});o&&t[r][a].forEach((({matchUpId:t})=>{const r=v[t];if(r){const a=r.split(":").map(Yc).join(":"),s=`${Lc(n)}T${a}`;h?T[n].push(t):(rR({drawDefinition:o,scheduledTime:s,matchUpId:t}).success&&T[n].push(t),e&&iR({tournamentRecord:i,drawDefinition:o,matchUpId:t,venueId:e}))}}))}))})),D[n]=A[e].matchUpsToSchedule.map(Nd),g[n][e]=A[e].scheduleTimes.sort(((e,t)=>kc(e.scheduleTime)-kc(t.scheduleTime)))}!h&&M?.length&&_R({matchUpDetails:M,scheduleByeMatchUps:!0,removePriorValues:!0,tournamentRecords:u,schedule:{scheduledDate:"",scheduledTime:"",courtOrder:"",courtId:"",venueId:""}});for(const t of e.venues)for(const e of t.rounds){const t=e.matchUps?.map((({matchUpId:e})=>e))||[],r=t.filter((e=>T[n].includes(e)));e.canScheduledMatchUpIds=r;let i=Math.round(r.length/e.matchUpsCount*1e4)/100;(i===1/0||isNaN(i))&&(i=0),e.possibleToSchedulePct=i,e.matchUpsCount===r.length&&(e.possibleToSchedule=!0)}}const b=i.map((({scheduleDate:e})=>e)),R={timeStamp:Date.now(),overLimitMatchUpIds:P,scheduledMatchUpIds:T,schedulingProfile:d,noTimeMatchUpIds:D,requestConflicts:w,scheduledDates:b};return xR({tournamentRecords:u,autoSchedulingAudit:R}),{...Ni,schedulingProfileModifications:e,schedulingProfileIssues:n,scheduleTimesRemaining:g,dateSchedulingProfiles:i,skippedScheduleTimes:I,recoveryTimeDeferredMatchUpIds:U,dependencyDeferredMatchUpIds:y,matchUpScheduleTimes:v,overLimitMatchUpIds:P,scheduledMatchUpIds:T,noTimeMatchUpIds:D,requestConflicts:w,scheduledDates:b}}(P)}function $R(e){const t=e||{};return t.tournamentId||(t.tournamentId=bm()),(!t.startDate||Oc(t.startDate)||yc.test(t.startDate))&&(!t.endDate||Oc(t.endDate)||yc.test(t.endDate))?(t.extensions&&(t.extensions=t.extensions.filter(hd)),{...t}):{error:io}}function WR({addParticipants:e=!0,participantAttribute:t,tournamentRecord:r,personAttribute:n,teamNames:i,accessor:a,uuids:o}){if(!r)return{error:Fi};const s={},c=(r.participants??[]).filter((({participantType:e,participantRole:t})=>e===gm&&t===Zv));let u=0;for(const e of c){const r=a&&Xc({element:e,accessor:a})?.value||n&&e.person?.[n]||t&&e[t];if(r){if(!Object.keys(s).includes(r)){s[r]={participantName:i?.[u]??r,participantId:o?.pop()??bm(),individualParticipantIds:[],participantRole:Zv,participantType:ym};const e={value:n??t,name:li};gd({element:s[r],extension:e}),u+=1}s[r].individualParticipantIds.push(e.participantId)}}const d=Object.keys(s),p=(r.participants??[]).map((e=>{if(e.participantType!==ym)return;if(e.participantRole!==Zv)return;const{extension:t}=Wl({name:li,element:e}),r=t?.value;return d.includes(r)?e.participantId:void 0})).filter(Boolean);let l=0;const m=[];return Object.keys(s).forEach((t=>{const n=s[t],{participantId:i}=n;p.includes(i)||(r.participants||(r.participants=[]),e&&r.participants.push(n),m.push(n),l++)})),e&&l?(rc({payload:{tournamentId:r.tournamentId,participants:m},topic:dp}),{...Ni,participantsAdded:l}):m.length?{...Ni,newParticipants:m}:{error:po}}var HR=[{AA:"Annexia"},{BA:"Bacteria"},{BO:"Borduria"},{BM:"Bensalem"},{BS:"Basenji"},{BI:"Balnibarbi"},{BV:"Bartovia"},{BZ:"Berzerkistan"},{CA:"Caldonia"},{CC:"Concordia"},{CH:"Chula"},{DA:"Deltora"},{DW:"Discworld"},{EA:"Eastasia"},{EP:"Ecotopia"},{ER:"Erewhon"},{FA:"Freedonia"},{FN:"Florin"},{FG:"Fogg"},{FK:"Fourecks"},{GA:"Genovia"},{GL:"Gilead"},{GD:"Gilead"},{GL:"Gondal"},{GO:"Gondor"},{GR:"Gruzinia"},{GT:"Goritania"},{GU:"Guilder"},{HA:"Heldscalla"},{HO:"Hidalgo"},{IL:"Illyria"},{KA:"Kinakuta"},{KG:"Kangan"},{KN:"Kreplachistan"},{KS:"Kallipolis"},{LH:"Lugash"},{LI:"Listenbourg"},{LT:"Lilliput"},{LU:"Luggnagg"},{LV:"Lichtenslava"},{MR:"Moher"},{NA:"Narnia"},{NV:"Novaria"},{OA:"Oceania"},{OS:"Orsinia"},{OV:"Octavia"},{PA:"Palombia"},{PG:"Penguina"},{QA:"Qasha"},{PM:"Panem"},{SA:"Solymbria"},{SD:"Syldavia"},{SG:"San Glucose"},{SL:"San Lorenzo"},{SR:"Sontar"},{SY:"Sylvania"},{TF:"Tralfamadore"},{TH:"Themyscira"},{UA:"Utopia"},{VA:"Vespugia"},{WA:"Wakanda"},{WX:"Wessex"},{ZA:"Zamunda"},{ZK:"Zubrowka"}],zR=["Amber","Ansul","Atlantis","Braavos","Busytown","Castle Rock","Centralia","Coober Pedy","Chefchaouen","Chronopolis","Damanhur","Diaspar","Dictionopolis","Diomira","El Dorado","Elista","Ephesus","Gotham","Hadleyburg","Hallstatt","Hierusalem","Ilium","Inverness","Kowloon","Laputa","Longyearbyen","Lys","Matmata","Maycomb","Metropolis","Miyake-jima","Monowi","Nagoro","Navarre","New New York","Nimbin","Pemberley","Pseudopolis","Rivendell","Roswell","Shangri-La","Springfield","Supilinn","Thneedville","Trantor","Wobegon","Yonwood","Xanadu","Xylar","Zion"];function YR({count:e=1,participantsCount:t=32}={}){const r=Gd(zR),n=r.slice(0,e);return{cities:Qd(0,t).map((t=>t<Math.min(e,r.length)?n[t]:Yd(n)))}}function QR({count:e=1,participantsCount:t=32}={}){const r=Gd(HR),n=r.slice(0,e).map((e=>Object.keys(e))).flat();return{states:Qd(0,t).map((t=>t<Math.min(e,r.length)?n[t]:Yd(n)))}}function KR({count:e=1,participantsCount:t=32}={}){const r=Qd(0,e).map((()=>Qd(0,5).map((()=>Ld(0,9))).join("")));return{postalCodes:Qd(0,t).map((t=>t<e?r[t]:Yd(r)))}}function JR(e){const{cities:t,states:r,postalCodes:n,nationalityCode:i,participantIndex:a}=e;return{postalCode:n?.[a],state:r?.[a],city:t?.[a],countryCode:i}}var ZR={lastNames:["Abbey","Ahern","Ampleforth","Ananiadis","Andelic","Assange","Atreides","Austen","Bach","Banks","Barrington","Batty","Bauers","Beals","Beer","Bennett","Berry","Bonaparte","Brockovich","Bukowski","Cassidy","Catton","Calvino","Carson","Chip","Constant","Crane","Crowne","Cummings","Curie","Dallas","Diamond","Deckard","Drazic","Dunbar","Earhart","Eisenstein","Eldritch","Elliot","Escher","Eyre","Faulkner","Fulcher","Fukuoka","Godel","Goldstein","Greer","Hedges","Herbert","Holmgren","Humperdinck","Huxley","Illich","Jeffers","Jensen","Jevons","Johnson","Johnstone","Jovovich","Kingsnorth","Langer","Fernwright","Fuller","Le Guin","Lem","Lovelace","Mander","Midgely","Mond","Montoya","Moore","Murry","Nagle","Nearing","Ogden","Ophuls","Parks","Paz","Peet","Perfect","Pendejo","Pevensie","Postman","Ripley","Rodda","Rumfoord","Runciter","Rugen","Sale","Schumacher","Shaftoe","Shelley","Shepard","Smith","Stratton","Stewart","Swift","Tillich","Turing","Tyrell","Twain","Yeats","Veblen","Yates","Vonnegut","Waterhouse","Watson","Wolin","Wirt","Waschuk","Wormwood"],firstFemale:["Ada","Amelia","Amelie","America","Anne","Antonia","Aravis","Astrid","Beatrice","Brienne","Buttercup","Caitlin","Cimorene","Cordelia","Desdemona","Ellen","Elizabeth","Emily","Emmie","Erin","Eva","Evelyn","Heather","Helen","Hermia","Hypatia","Imogen","Jane","Jasmine","Juliana","Juliet","Katniss","Leeloo","Lenina","Lilith","Linda","Lizzie","Louise","Lucy","Marie","Mary","Martha","Matilda","Milla","Miranda","Meg","Melba","Nicole","Ola","Portia","Pris","Rachael","Rachel","Rebecca","River","Rosa","Rosalind","Scout","Sharn","Susanne","Titania","Uhura","Ursula","Valentina","Viola","Virginia","Xena","Zoe"],firstMale:["Alan","Aldous","August","Axel","Barda","Barry","Bill","Bruce","Charles","Chris","Constantine","Darwin","David","Derrick","Edward","Emmanuel","Ernst","Estlin","Fezzik","Filby","Frank","Frito","George","Glen","Helmholtz","Inigo","Italo","Ivan","James","Jared","Jerry","Joe","Johann","Julian","John Michael","Jonathan","Korben","Kirkpatrick","Kurt","Lief","Malachi","Mark","Masanobu","Maurits","Michael","Mustapha","Neil","Nikola","Octavio","Palmer","Paul","Pierre","Robinson","Rick","Rincewind","Roy","Shannon","Sheldon","Stafford","Stanislaw","Stanley","Syme","Thorstein","Thomas","Tyrone","Vizzini","Walton","Walker","Warren","Wendell","Westley","William","Winston","Zoran"]};function XR(e){const{count:t=100,sex:r}=e||{};if(!t||r&&![Lf,jf].includes(r))return{personData:[],error:ys};const n=Math.ceil(1.3*t),{lastNames:i,firstFemale:a,firstMale:o}=ZR,s=_U.map((({iso:e})=>e)).filter(Boolean),c=Math.ceil(n/i.length),u=Math.ceil(n/a.length),d=Math.ceil(n/o.length),p=Qd(0,c).flatMap((()=>{const e=Jc(i,!1,!0);return Qd(0,i.length).map((()=>zd(e)))})),l=Qd(0,u).flatMap((()=>{const e=Jc(a,!1,!0);return Qd(0,a.length).map((()=>zd(e)))})),m=Qd(0,d).flatMap((()=>{const e=Jc(o,!1,!0);return Qd(0,o.length).map((()=>zd(e)))})),f={};for(let e=0;e<n;e++){const e=p.pop(),t=r||Yd([Lf,jf]),n=t===Lf?m.pop():l.pop(),i=Yd(s);f[`${n}${e}`]={nationalityCode:i,sex:t,firstName:n,lastName:e}}return{personData:Object.values(f).slice(0,t)}}function eN(e){let t=e?.count||1;const{personExtensions:r,consideredDate:n,isMock:i=!0,gendersCount:a,personData:o,category:s,sex:c}=e||{};if(isNaN(t))return{error:ys};const u=a?.[Lf]||c===Lf&&t||0,d=a?.[jf]||c===jf&&t||0;t=Math.max(t,u+d);const p=t-(u+d),l=[...u&&XR({count:u,sex:Lf}).personData||[],...d&&XR({count:d,sex:jf}).personData||[],...p&&XR({count:p}).personData||[]];let m=l.filter((e=>!c||u&&d||e.sex===c));const f=[];if(Array.isArray(o)){const e=o.filter((e=>"string"==typeof e.firstName&&("string"==typeof e.lastName&&(!(e.sex&&![Lf,jf].includes(e.sex))&&(!(e.nationalityCode&&("string"!=typeof e.nationalityCode||e.nationalityCode.length>3||!_U.find((({iso:t,ioc:r})=>[t,r].includes(e.nationalityCode)))))&&(e.nationalityCode&&f.push(e.nationalityCode),!0))))));if(!e.length)return{error:ys};m=e}const h=o?m:Gd(m);if(h.length<t){const{maleFirstNames:e,maleLastNames:r,femaleFirstNames:n,femaleLastNames:i,nationalityCodes:a}=l.reduce(((e,t)=>{const{firstName:r,lastName:n,nationalityCode:i}=t;return t.sex===Lf?(e.maleFirstNames.includes(r)||e.maleFirstNames.push(r),e.maleLastNames.includes(n)||e.maleLastNames.push(n)):(e.femaleFirstNames.includes(r)||e.femaleFirstNames.push(r),e.femaleLastNames.includes(n)||e.femaleLastNames.push(n)),e.nationalityCodes.includes(i)||e.nationalityCodes.push(i),e}),{maleFirstNames:[],maleLastNames:[],femaleFirstNames:[],femaleLastNames:[],nationalityCodes:[]});Qd(0,t-h.length).forEach((()=>{const t=c||Yd([Lf,jf]),o=Yd(a),s={firstName:Yd(t===Lf?e:n),lastName:Yd(t===Lf?r:i),sex:t,nationalityCode:o};h.push(s)}))}const{ageMinDate:g,ageMaxDate:I}=tv({consideredDate:n,category:s}),U=Ed(g?.slice(0,4)||0)||Ed(I?.slice(0,4)||0)-3,y=Ed(I?.slice(0,4)||0)||Ed(g?.slice(0,4)||0)+3,S=(g||I)&&[U,y],v=h.slice(0,t).map(((e,t)=>{const[n,a]=S||[],o=S&&zd(Qd(n,a)),s=zd(Qd(0,365)),c=o&&function(e,t,r){const n=new Date(e,0);return Nc(new Date(n.setDate(t)),r)}(o,s);return Object.assign(Mf({extensions:r||[{name:"regionCode",value:t+1}],birthDate:c,isMock:i}),e)}));return{persons:v.length&&v||h[0],nationalityCodes:f}}var tN=["Ace Academy","Avengers","Ball Bouncers","Baseliners","Captivators","Civil Disobedients","Continentals","Court Royal","Court Sharks","Diamond Dogs","Danger Zone","Doubles Dominators","Double Faults","Tricksters","Eliminators","Court Crusaders","Fuzz Busters","Game Changers","Goal Gurus","Good Volley","Green Machine","Hawk Eyes","Inside Outers","Killer Instinct","Line Toers","Masters of Mayhem","Matter Catchers","Cheap Shot","Mean Machines","Mindspace Invaders","Net Centric","Net Positive","Smash Mullet","Over Your Head","Spin Meisters","Aggressors","Racket Machine","Slice Happy","Refs Nightmare","Sandeaters","Sun Seekers","Slicer Dicers","Sparkle Soul Tribe","Stacked Deck","Cross Stringers","The Emergence","Total Demolition","Touch and Go","Upside Downers","Vertically Challenged","Visual Spectacle"];function rN({nameRoot:e="TEAM",count:t=1}={}){const r=Gd(tN).slice(0,t);return r.length<t&&Qd(0,t-r.length).forEach((t=>r.push(`${e} ${t+1}`))),{names:r}}function nN({idPrefix:e,participantType:t,index:r,uuids:n}){return e?`${e}-${t===gm?"I":"P"}-${r}`:n?.pop()||bm()}function iN(e){let{rankingRange:t,scaledParticipantsCount:r}=e;const{ratingsParameters:n=Tv,valuesInstanceLimit:i,consideredDate:a,category:o,nationalityCodesCount:s,nationalityCodeType:c,nationalityCodes:u,participantsCount:d=32,participantType:p,personIds:l,idPrefix:m,uuids:f,personExtensions:h,addressProps:g,gendersCount:I,matchUpType:U,personData:y,sex:S,inContext:v,withISO2:T,withIOC:P,scaleAllParticipants:D}=e,w=p===Um||U===ff,b=p===ym||U===ym;!t||Array.isArray(t)&&t.every((e=>kd(e)))&&2===t.length||(t=void 0),r=D?d:r;t=t||[1,r&&r>1e3?r:1e3],t[1]+=1;const R=d*(w?2:b?8:1),N=eN({count:R,personExtensions:h,consideredDate:a,gendersCount:I,personData:y,category:o,sex:S});if(N.error)return N;const{nationalityCodes:M,persons:A}=N;let E=[],C=[],O=[],F=[];if("object"==typeof o){const{categoryName:e,ageCategoryCode:i,ratingType:a}=o;if((e||i)&&!a){const[e,n]=t||[];if(C=Gd(Qd(e,n)).slice(0,r||Ld(20,30)),[Um,ym].includes(p)){const[e,n]=t||[];E=Gd(Qd(e,n)).slice(0,r||Ld(20,30))}}if(a&&n[a]){const{ratingMax:e,ratingMin:t,ratingAttributes:i}=o,s={...n[a],...i||{}},{attributes:c={},decimalsCount:u,accessors:d,range:l,step:m}=s,f=e=>{const t={},r=Object.keys(e||{});for(const n of r){const r=e[n];if("object"==typeof r&&r.generator){const{range:e}=r,[i,a]=e.slice().sort();t[n]=Ld(i,a)}else t[n]=r}return t},h=l[0]>l[1]?2:.5,[g,I]=l.slice().sort(),U=()=>Qd(0,2e3).map((()=>Bd(g,I,h,m,u))).filter((r=>(!e||r<=e)&&(!t||r>=t))).slice(0,r||Ld(20,30)).map((e=>d?Object.assign({},...d.map((t=>({[t]:e}))),f(c)):e));O=U(),[Um,ym].includes(p)&&(F=U())}}const k=_U.filter((e=>"IOC"===c&&e.ioc||e.iso));const{postalCodesProfile:_,postalCodesCount:x,statesProfile:L,citiesProfile:V,citiesCount:B,statesCount:j}=g||{},G=e=>Object.keys(e).map((e=>Qd(0,L[e]).map((()=>e)))).flat(),q={cities:V&&G(V)||g?.cities||YR({count:B||R,participantsCount:R}).cities,states:L&&G(L)||g?.states||QR({count:j||R,participantsCount:R}).states,postalCodes:_&&G(_)||g?.postalCodes||KR({count:x||R,participantsCount:R}).postalCodes},$=function(e){const t=Math.ceil(R/e);return i&&t>i?Math.ceil(R/i):e}(s),W=$?Gd(k).slice(0,s):u?k.filter((e=>u.includes(e.iso))):k,H=Gd(Qd(0,Math.ceil(R/($||1))).map((()=>W)).flat(1/0)),z=rN({count:d}).names;return{participants:Qd(0,d).map((e=>{const t=w?2:b?8:1,r=Qd(0,t).map((r=>function(e){const t=A[e],{nationalityCode:r,participantExtensions:n,participantTimeItems:i,extensions:a,firstName:s,birthDate:u,lastName:d,personId:p,sex:h}=t||{},g=s||"GivenName",I=d||"FamilyName",U=`${g} ${I}`,y=H[e],S=M?.length&&r||y&&("IOC"===c?y.ioc||y.iso:y.iso||y.ioc)||r;!H?.length||S||r||console.log("%c Invalid Nationality Code",{participantIndex:e,country:y});const v=JR({...q,participantIndex:e,nationalityCode:S}),D=Mf({participantId:nN({participantType:gm,index:e,idPrefix:m,uuids:f}),extensions:n,timeItems:i,participantRole:Zv,participantType:gm,participantName:U,person:{addresses:[v],personId:p||l?.length&&l[e]||bm(),standardFamilyName:I,standardGivenName:g,nationalityCode:S,extensions:a,birthDate:bc(u)?u:void 0,sex:h}});if(P&&S){const e=_U.find((({iso:e})=>e===S));e?.ioc&&(D.person.iocNationalityCode=e.ioc),e?.label&&(D.person.countryName=e.label)}if(T&&S){const e=_U.find((({iso:e})=>e===S));e?.iso2&&(D.person.iso2NationalityCode=e.iso2),e?.label&&(D.person.countryName=e.label)}if(o){const t=C[e],r=E[e];aN({scaleValue:t,eventType:$f,scaleType:pu,participant:D,category:o}),aN({scaleValue:r,eventType:Hf,scaleType:pu,participant:D,category:o});const n=O[e],i=F[e];aN({scaleValue:n,eventType:$f,scaleType:lu,participant:D,category:o}),aN({scaleValue:i,eventType:Hf,scaleType:lu,participant:D,category:o})}return D}(e*t+r))),n=r.map((e=>e.participantId)),i=r.map((e=>e.person.standardFamilyName)).join("/"),a=w?Um:ym,s={participantId:nN({participantType:a,idPrefix:m,index:e,uuids:f}),participantRole:Zv,participantName:w?i:z[e],individualParticipantIds:n,participantType:a};return v&&(s.individualParticipants=r),w||b?[s,...r]:r})).flat(),...Ni}}function aN({scaleValue:e,participant:t,eventType:r,scaleType:n,category:i}){const a=i.categoryName||i.ratingType||i.ageCategoryCode,o={itemValue:e,itemType:[mu,n,r,a].join(".")};a&&e&&(t.timeItems||(t.timeItems=[]),t.timeItems.push(o))}function oN({alternatesCount:e=0,tieFormatName:t,tieFormat:r,drawSize:n}){let i=0,a=0,o=0,s=0;const c={},u={[Lf]:0,[jf]:0,[Vf]:0,[Bf]:0,[xf]:0};r="object"==typeof r?r:sD({namedFormat:t}),r?.collectionDefinitions?.filter(Boolean).forEach((e=>{const{category:t,collectionId:r,matchUpType:n,matchUpCount:d,gender:p}=e;if([Lf,jf].includes(p)){const e=d*(n===hf?2:1);u[p]<e&&(u[p]=e)}else p===Vf&&(u[Lf]<d&&(u[Lf]=d),u[jf]<d&&(u[jf]=d));if(t){const e=JSON.stringify(t);c[e]=t}if(r||(e.collectionId=bm()),n===hf){const e=d;s+=d,i=Math.max(i,e)}if(n===mf){const e=d;o+=d,a=Math.max(a,e)}}));const d=Object.keys(c).length?Math.max(o,2*s):Math.max(a,2*i);return{maxDoublesDraw:i*(n+e),maxSinglesDraw:a*(n+e),teamSize:d,genders:u}}function sN({participantsProfile:e,tournamentRecord:t,eventProfiles:r,drawProfiles:n,startDate:i,uuids:a}){const{participantsCount:o,participantType:s,largestTeamDraw:c,largestTeamSize:u,gendersCount:d}=function({participantsProfile:e,eventProfiles:t,drawProfiles:r}){let{participantsCount:n,participantType:i=gm}=e||{};const a=n||0,o={[jf]:0,[Vf]:0,[Bf]:0,[Lf]:0,[xf]:0};let s=0,c=0,u=0,d=0,p=0;const l=({alternatesCount:e=0,uniqueParticipants:t,tieFormatName:r,drawSize:n=0,eventType:i,tieFormat:a,category:l,gender:m,stage:f})=>{const h=i===Wf,g=i===zf,I=Boolean(t||f===$p||l||m);if(g){d=Math.max(d,n+e),a="object"==typeof a?a:sD({namedFormat:r});const{teamSize:t,maxDoublesDraw:i,maxSinglesDraw:p,genders:l}=oN({alternatesCount:e,tieFormatName:r,tieFormat:a,drawSize:n});u=Math.max(u,t),c=Math.max(c,p),I||(s=Math.max(s,i)),Object.keys(l).forEach((e=>o[e]+=l[e]))}else if(h)if(I){const t=2*(n+e);p+=t,m&&(o[m]+=t)}else n+e&&n+e>s&&(s=n+e);else if(I){const t=n+e;m&&(o[m]+=t),p+=t}else n&&n>c&&(c=n+e)};if(t?.forEach((e=>{const{tieFormatName:t,tieFormat:r,drawProfiles:n,eventType:i,category:a,gender:o}=e;if(n)for(const e of n){const{tieFormatName:n,tieFormat:s}=e;l({...e,tieFormatName:n||t,tieFormat:s||r,eventType:i,category:a,gender:o})}})),Array.isArray(r))for(const e of r)l(e);const m=Math.max(d*u,2*s,c);return s&&(i=Um),(n||a)<m&&(n=m),n&&s&&[Um,zf].includes(i)&&(c&&Math.floor(c/2)>s?n=Math.floor(c/2):(!c||2*s>=c)&&(n=Math.ceil(n/2))),void 0===n&&(n=t?.length||r?.length?0:32),n<a&&(n=a),{uniqueParticipantsCount:p,participantsCount:n,largestTeamDraw:d,largestTeamSize:u,participantType:i,gendersCount:o}}({participantsProfile:e,eventProfiles:r,drawProfiles:n}),p=e?.teamKey,l=iN({uuids:a,...e,consideredDate:i,participantsCount:o,participantType:s,gendersCount:d}).participants;let m=0,f=vT({tournamentRecord:t,participants:l});if(f.error)return f;if(m+=f.addedCount,p){const e=WR({tournamentRecord:t,...p});if(e.error)return e}const h=l.filter((({participantType:e})=>e===gm)).map(Rd),g=e?.idPrefix?`${ym}-${e.idPrefix}`:void 0;return f=vT({participants:Qd(0,c).map((e=>{const t=h.slice(e*u,(e+1)*u),r=nN({index:e,participantType:s,idPrefix:g,uuids:a});return{participantName:`Team ${e+1}`,participantRole:Zv,individualParticipantIds:t,participantType:ym,participantId:r}})),tournamentRecord:t}),f.error?f:(m+=f.addedCount,{addedCount:m,...Ni})}function cN({tournamentRecord:e,disableNotice:t,venueId:r,courtId:n,court:i}){const{venue:a}=gb({tournamentRecord:e,venueId:r});if(!a)return{error:Ko};a.courts||(a.courts=[]);const o={...Nn(),venueId:r,courtId:n};o.courtId||(o.courtId=vt());if(a.courts.some((e=>e.courtId===o.courtId)))return{error:Yo};{const n=(i?.dateAvailability||[]).map((e=>({...e,date:Vr(e.date),startTime:Wr(e.startTime),endTime:Wr(e.endTime),bookings:e.bookings?.map((({startTime:e,endTime:t,bookingType:r})=>({startTime:Wr(e),endTime:Wr(t),bookingType:r})))}))),s=Object.keys(o);for(const e of s)if(i?.[e])if("dateAvailability"===e){const e=Mn({dateAvailability:n});if(!e.valid&&e.error)return e;o.dateAvailability=n}else o[e]=i[e];const c=o;return a.courts.push(c),t||Je({payload:{venue:a,tournamentId:e.tournamentId},topic:bp,key:a.venueId}),{...Ni,court:L(o),venueId:r}}}function uN(e){const{tournamentRecord:t,venueId:r}=e;if("string"!=typeof r||!r)return{error:Jo};const n=e.tournamentRecords??(t&&{[t.tournamentId]:t})??{},i=[];let a;for(const t of Object.values(n)){const{venue:n}=gb({tournamentRecord:t,venueId:r});if(n){const r=dN({...e,tournamentRecord:t});for(const e of r?.courts??[])i.push(e?.courtId);if(r.error)return r;a=!0}}return a?{...Ni,courtIds:i}:{error:Ko}}function dN({courtNameRoot:e="Court",dateAvailability:t=[],venueAbbreviationRoot:r,tournamentRecord:n,courtNames:i=[],courtTimings:o,courtsCount:s,startTime:c,courtIds:u,endTime:d,idPrefix:p,venueId:m,dates:f}){if(!m)return{error:Jo};const h=gb({tournamentRecord:n,venueId:m});if(h.error)return h;const{venue:g}=h;if(!je(s)||!i)return{error:Ho};s=s??i.length;const I=l(0,s).map((n=>{const a=o?.[n],s=a?f.map((e=>({date:Kr(e),startTime:c,endTime:d,...a}))):t;return a&&c&&d&&s.push({startTime:c,endTime:d}),{courtName:i[n]||r&&g?.venueAbbreviation&&`${g?.venueAbbreviation} ${n+1}`||`${e} ${n+1}`,dateAvailability:s}})).map(((e,t)=>{const r=u?.pop()||p&&`${p}-${t+1}`;return cN({disableNotice:!0,tournamentRecord:n,courtId:r,venueId:m,court:e})})).map((e=>e.court)).filter(Boolean);return I.length!==s?a({info:"not all courts could be generated",result:{error:ys}}):(g&&Je({payload:{venue:g,tournamentId:n.tournamentId},topic:bp,key:g.venueId}),{...Ni,courts:L(I)})}function pN({tournamentRecord:e,venueProfiles:t,uuids:r}){const{startDate:n,endDate:i}=e,a=[];for(const[o,s]of t.entries()){const{venueAbbreviation:t,venueId:c=r?.pop()??bm(),dateAvailability:u,startTime:d="07:00",endTime:p="19:00",courtTimings:l,courtsCount:m,courtNames:f,venueName:h,idPrefix:g,courtIds:I}=s,U=fb({tournamentRecord:e,venue:{venueName:h||`Venue ${o+1}`,venueAbbreviation:t,venueId:c}});if(U.error)return U;a.push(c);const y=Ec(n,i),S=!Array.isArray(u)&&[{startTime:d,endTime:p}].concat(y.map((e=>({date:Nc(e),startTime:d,endTime:p})))),v=uN({dateAvailability:u||S,tournamentRecord:e,courtTimings:l,courtsCount:m,courtNames:f,startTime:d,idPrefix:g,courtIds:I,endTime:p,venueId:c,dates:y});if(v.error)return v}return a}function lN({drawProfiles:e,category:t,gender:r}){const n={},i=e?.reduce(((e,i)=>{const{qualifyingPositions:a=0,participantsCount:o=0,uniqueParticipants:s,stage:c=qp,drawSize:u=0}=i||{};Object.keys(e).includes(c)||(e[c]=0);const d=(o||u)-a;return s||r||t||c===$p?(Object.keys(n).includes(c)||(n[c]=0),n[c]+=d):e[c]=Math.max(e[c],d),e}),{}),a=Object.keys(n);return a.forEach((e=>i[e]+=n[e])),{stageParticipantsCount:i,uniqueParticipantsCount:n,uniqueParticipantStages:a}}function mN({allUniqueParticipantIds:e,stageParticipantsCount:t,eventParticipantType:r,targetParticipants:n}){const i=t[qp]||0,a=t[$p]||0;return{stageParticipants:{QUALIFYING:n.filter((({participantType:e})=>e===r)).filter((({participantId:t})=>!e.includes(t))).slice(0,a),MAIN:n.filter((({participantType:e})=>e===r)).filter((({participantId:t})=>!e.includes(t))).slice(a,a+i)}}}function fN(e){const{removePriorValues:t,tournamentRecord:r,participantId:n,scaleItem:i}=e;let a,o;if(!gN({scaleItem:i}))return{error:us};if(n&&Array.isArray(r.participants)&&(o=r.participants.find((e=>e.participantId===n)),o)){const e=IN({removePriorValues:t,participant:o,scaleItem:i});if(e.error)return e;a=!e.valueChanged;const{topics:n}=Ze();n.includes(Tp)&&Je({topic:Tp,payload:{tournamentId:r.tournamentId,participants:[o]}})}return a&&{...Ni,info:Ds,existingValue:i?.scaleValue}||o&&{...Ni,newValue:i?.scaleValue}||{error:wo}}function hN(e){const{scaleItemsWithParticipantIds:t=[],removePriorValues:r,tournamentRecord:n,auditData:i,context:a}=e;if(!n)return{error:Fi};if(!n.participants)return{error:Po};let o=0;const s={},c=[];for(const e of t){const t=e?.participantId;if(Array.isArray(e?.scaleItems))for(const r of e.scaleItems){if(!gN({scaleItem:r}))return{error:us};Array.isArray(s[t])||(s[t]=[]),s[t].push(r)}}n.participants.forEach((e=>{const{participantId:t}=e||{};Array.isArray(s[t])&&s[t].forEach((t=>{IN({participant:e,scaleItem:t,removePriorValues:r}),c.push(e),o++}))}));const u=o?void 0:ps,{topics:d}=Ze();if(d.includes(Tp)&&o&&Je({topic:Tp,payload:{tournamentId:n.tournamentId,participants:c}}),a){const{eventId:e,drawId:t,...r}=a,i=r.scaleAttributes?.scaleType&&[r.scaleAttributes.scaleType];if(Object.keys(r).length){const a={itemType:pp,itemValue:r};if(i&&(a.itemSubTypes=i),t||e){const{drawDefinition:r,event:i}=En({tournamentRecord:n,eventId:e,drawId:t});t&&An({drawDefinition:r,timeItem:a}),e&&Mt({event:i,timeItem:a})}else At({tournamentRecord:n,timeItem:a})}}return i&&d.includes(mp)&&Je({topic:mp,payload:i}),S({...Ni,modificationsApplied:o,info:u})}function gN({scaleItem:e}){const t=e&&Object.keys(e),r=["scaleType","eventType","scaleName"];return!!(r.filter((e=>t?.includes(e))).length===r.length)}function IN({removePriorValues:e,participant:t,scaleItem:r}){if(!t)return{error:To};const n=r&&Object.keys(r),i=["scaleType","eventType","scaleName"];if(!(i.filter((e=>n.includes(e)&&r[e])).length===i.length))return{error:us};const a=(new Date).toISOString();t.timeItems||(t.timeItems=[]);const{scaleItem:o}=Ir({scaleAttributes:r,participant:t}),s=e=>[void 0,null,""].includes(e),c=!(s(o?.scaleValue)&&s(r.scaleValue))&&JSON.stringify(o?.scaleValue)!==JSON.stringify(r.scaleValue);if(c){const{scaleType:n,eventType:i,scaleName:o}=r,s=[mu,n,i,o].join("."),c=S({itemValue:r.scaleValue,itemDate:r.scaleDate,createdAt:a,itemType:s});r.scaleId&&(c.itemSubTypes=[r.scaleId]),e&&(t.timeItems=t.timeItems.filter((e=>e.itemType!==s))),t.timeItems.push(c)}return{...Ni,valueChanged:c,newValue:r.scaleValue}}const UN={[Km]:2,[qm]:1,[Gm]:1,[zm]:1,[jm]:4};function yN(e){let{defaultWithScorePercent:t=2,winningSide:r}=e;const{matchUpStatusProfile:n=UN,matchUpFormat:i=LI,pointsPerMinute:a=1,sideWeight:o=4}=e;if(!uv({matchUpFormat:i}))return{error:Ca};if("object"!=typeof n)return{error:ys};if(t>100&&(t=100),isNaN(t)||isNaN(a)||isNaN(o))return{error:ys};const s=Object.keys(n).filter((e=>Object.keys(of).includes(e)&&e!==Vm));if(Object.keys(s).reduce(((e,t)=>e+n[t]),0)>100)return{error:ys,matchUpStatusProfile:n};const c=s.reduce(((e,t)=>(e.pointer=e.pointer+n[t],e.valueMap.push([e.pointer,t]),e)),{pointer:0,valueMap:[]}),u=Ld(1,100),d=(c.valueMap.find((e=>u<=e[0]))??[100,Vm])[1],p={sets:[],scoreStringSide1:"",side2ScoreString:""};if([Km,jm].includes(d)){r=r||Ld(1,2);const e={score:p,winningSide:r,matchUpStatus:d};if(!(d===jm&&Ld(1,100)>100-t))return{outcome:e}}else if([qm,Gm].includes(d))return{outcome:{score:p,matchUpStatus:d}};const l=QI(i),{bestOf:m,setFormat:f,finalSetFormat:h}=l??{},g=[],I=Ld(0,1),U=r?[r-1]:[...Qd(0,o).map((()=>I)),1-I],y=[zm,jm,Wm,Ym].includes(d)&&(zd(Qd(1,m))||1);let S;for(const e of Qd(1,(m??0)+1)){const t=e===m,{set:r,incomplete:n,winningSideNumber:o}=SN({incomplete:y===e,matchUpStatus:d,pointsPerMinute:a,setFormat:t&&h||f,setNumber:e,weightedRange:U});if(g.push(r),n){S=o;break}if(zb({matchUp:{score:{sets:g},matchUpFormat:i}}).calculatedWinningSide)break}const v=zb({matchUp:{score:{sets:g},matchUpFormat:i}}),T=S?r||S:v.calculatedWinningSide,{score:P}=uw({score:{sets:g},winningSide:T,matchUpStatus:d});return{outcome:{score:P,winningSide:T,matchUpStatus:d}}}function SN({weightedRange:e=[0,1],pointsPerMinute:t,matchUpStatus:r,incomplete:n,setFormat:i,setNumber:a}){const o={setNumber:a},{setTo:s,tiebreakFormat:c,tiebreakAt:u,tiebreakSet:d,timed:p,minutes:l}=i,m=Ld(0,e.length-1),f=e[m];let h;if(p){const i=l*t,a=Math.round(.2*i),s=i+zd([1,-1])*a,c=function(e=1,t=3,r=!0){let n=0;for(let r=0;r<t;r++)n+=Math.random()*(e/t);return r&&e>1?Math.round(n):n}(s,2),u=[c,s-c];f&&u.reverse(),h=e[m]+1;let d=(u[0]>u[1]?1:u[1]>u[0]&&2)||0;if(n){const[e,t]=u;return Object.assign(o,{side1Score:e,side2Score:t}),rf.includes(r)?{set:o,incomplete:n,winningSideNumber:h}:{set:o,incomplete:n}}d||(u[Ld(0,1)]+=1),d=u[0]>u[1]?1:2,d!==h&&u.reverse();const[p,g]=u;return Object.assign(o,{side1Score:p,side2Score:g,winningSide:h}),{set:o}}if(n)return o.side1Score=Ld(0,u),o.side2Score=Ld(0,u),rf.includes(r)&&(h=e[m]+1),{set:o,incomplete:n,winningSideNumber:h};{const t=Qd(1,s+1).map((e=>Qd(0,s+2-e).map((()=>e)))).flat(),r=t[Ld(0,t.length-1)],n=s&&Jb({isSide1:!0,tiebreakAt:u,lowValue:r,setTo:s}),a=!n,p=1===e.length&&e[m]+1;if(!a){if(p){(n[0]>n[1]?1:2)!==p&&n.reverse()}else f&&n.reverse();const[e,t]=n;Object.assign(o,{side1Score:e,side2Score:t})}const l=Hb({matchUpScoringFormat:{setFormat:i},setObject:o});let h;if(l.hasTiebreakCondition||a){const{NoAD:e,tiebreakTo:t}=c||d||{},r=Qd(1,t+1).map((e=>Qd(0,t+2-e).map((()=>e)))).flat(),n=r[Ld(0,r.length-1)],i=Zb({isSide1:!0,tiebreakNoAd:e,tiebreakTo:t,lowValue:n});if(i)if(a){const e=i[0]>i[1]?1:2;p?e!==p&&i.reverse():f&&i.reverse(),[o.side1TiebreakScore,o.side2TiebreakScore]=i,h=(i[0]>i[1]?1:i[1]>i[0]&&2)||void 0}else 2===l.leadingSide?[o.side1TiebreakScore,o.side2TiebreakScore]=i:[o.side2TiebreakScore,o.side1TiebreakScore]=i}o.winningSide=l.winningSide||l.leadingSide||p||h}return{set:o}}function vN(e){const{matchUpStatusProfile:t,completeAllMatchUps:r,randomWinningSide:n,tournamentRecord:i,completionGoal:a,drawDefinition:o,event:s}=e;if(!o)return{error:Li};const c=e.matchUpFormat||o.matchUpFormat||s?.matchUpFormat,u=o.structures.slice().sort(fh);let d=0;const{matchUps:p,matchUpsMap:l}=Em({contextFilters:{stages:[qp,$p]},matchUpFilters:{matchUpTypes:[If],roundNumbers:[1]},inContext:!0,drawDefinition:o});if(p?.length){const e=s?.category?.ageCategoryCode||s?.category?.categoryName;if(e){const t=DD({singlesOnly:!0,tournamentRecord:i,drawDefinition:o,scaleAccessor:{scaleName:e,sortOrder:vD,scaleType:pu},event:s});if(t.error)return t;const{lineUps:r,participantsToAdd:n}=t;vT({tournamentRecord:i,participants:n});gd({element:o,extension:{name:mi,value:r}})}else{const e=p[0]?.structureId,{positionAssignments:t}=op({drawDefinition:o,structureId:e});if(t?.length){const{participants:e}=OS({participantFilters:{participantTypes:[If]},tournamentRecord:i}),r=r=>{const n=r.tieMatchUps.filter((({matchUpType:e})=>e===mf)),a=r.tieMatchUps.filter((({matchUpType:e})=>e===hf));n.forEach(((r,n)=>{const a=r.matchUpId;r.sides.forEach((r=>{const{drawPosition:c}=r,u=e?.find((e=>{const{participantId:r}=e,n=t.find((e=>e.participantId===r));return n?.drawPosition===c}));if(u){const e=u.individualParticipantIds?.[n];e&&YD({teamParticipantId:u.participantId,participantId:e,tournamentRecord:i,drawDefinition:o,tieMatchUpId:a,event:s})}}))})),a.forEach(((r,n)=>{const a=r.matchUpId;r.sides.forEach((r=>{const{drawPosition:c}=r,u=e?.find((e=>{const{participantId:r}=e,n=t.find((e=>e.participantId===r));return n?.drawPosition===c}));if(u){const e=u.individualParticipantIds?.slice(2*n,2*n+2);e?.forEach((e=>{YD({teamParticipantId:u.participantId,participantId:e,tournamentRecord:i,drawDefinition:o,tieMatchUpId:a,event:s})}))}}))}))};p.forEach(r)}}}const m="string"==typeof r&&r,f=m&&Vm;for(const e of u){if(d>=a)break;const{matchUps:r}=Kf({matchUpFilters:{matchUpTypes:[hf,mf]},afterRecoveryTimes:!1,tournamentRecord:i,inContext:!0,drawDefinition:o,matchUpsMap:l,structure:e,event:s}),u=r.filter((({winningSide:e})=>!e)).sort(vS).map(Nd);for(const r of u){if(!isNaN(a)&&d>=a)break;const{matchUps:u}=Kf({matchUpFilters:{matchUpTypes:[hf,mf]},afterRecoveryTimes:!1,tournamentRecord:i,inContext:!0,drawDefinition:o,matchUpsMap:l,structure:e,event:s}),p=u.find((e=>e.matchUpId===r)),h=[qm,Gm].includes(p.matchUpStatus);if(p?.readyToScore&&!h){const e=PN({winningSide:!n&&1,matchUpStatusProfile:t,tournamentRecord:i,drawDefinition:o,targetMatchUp:p,matchUpFormat:c,matchUpStatus:f,scoreString:m,event:s});if(e?.error)return e;d+=1}}}return{...Ni,completedCount:d}}function TN(e){const{matchUpStatusCodes:t,policyDefinitions:r,tournamentRecord:n,drawDefinition:i,targetMatchUp:a,matchUpStatus:o,matchUpFormat:s,scoreString:c,winningSide:u,event:d}=e;if(!a||a.matchUpStatus===xm)return;const{matchUpId:p}=a||{},{outcome:l}=eR({matchUpFormat:s,matchUpStatus:o,scoreString:c,winningSide:u});return t&&(l.matchUpStatusCodes=t),dw({tournamentRecord:n,policyDefinitions:r,drawDefinition:i,matchUpFormat:s,matchUpId:p,outcome:l,event:d})}function PN(e){const{matchUpStatusProfile:t={},tournamentRecord:r,policyDefinitions:n,drawDefinition:i,matchUpStatus:a,matchUpFormat:o,targetMatchUp:s,scoreString:c,winningSide:u,event:d}=e;if(c||a)return TN(e);const{matchUpId:p}=s||{},{outcome:l}=yN({matchUpStatusProfile:t,matchUpFormat:o,winningSide:u});return dw({policyDefinitions:n,tournamentRecord:r,drawDefinition:i,matchUpFormat:o,matchUpId:p,outcome:l,event:d})}function DN({matchUpStatusProfile:e,completeAllMatchUps:t,randomWinningSide:r,tournamentRecord:n,drawProfiles:i,event:a}){const o=bU({event:a}).flightProfile,{eventName:s,eventType:c,category:u}=a,{startDate:d}=n,p=[],l=u?.categoryName||u?.ageCategoryCode||u?.ratingType,m=a.drawDefinitions?.map((({drawId:e})=>e));if(Array.isArray(o?.flights))for(const[u,f]of o.flights.entries()){const{drawId:o,stage:h,drawName:g,drawEntries:I}=f;p.push(f.drawId);const U=i[u],{seedsCount:y,generate:S=!0}=U||{};if(S){const p=I.filter(au(vu)).map(au(vu)),f=l||s;if(n&&y&&y<=p.length){Qd(1,y+1).forEach(((e,t)=>{const r={scaleValue:e,scaleName:f,scaleType:fu,eventType:c,scaleDate:d},i=p[t];fN({tournamentRecord:n,participantId:i,scaleItem:r})}))}if(m?.includes(o))break;let S=Kv({...U,matchUpType:c,seedingScaleName:f,tournamentRecord:n,isMock:!0,drawEntries:I,drawName:g,drawId:o,event:a,stage:h});if(S.error)return{error:S.error,drawIds:[]};const{drawDefinition:v}=S;if(!v)return{error:Bi};const T=i[u]?.drawExtensions;if(Array.isArray(T)&&T.filter(hd).forEach((e=>gd({element:v,extension:e}))),S=lP({suppressNotifications:!0,tournamentRecord:n,drawDefinition:v,event:a}),S.error)return{error:S.error,drawIds:[]};if(U?.withPlayoffs){const e=v.structures?.[0].structureId,t=tI({idPrefix:U.idPrefix,...U.withPlayoffs,tournamentRecord:n,drawDefinition:v,isMock:!0,structureId:e,event:a});if(t?.error)return t}const P=U?.completionGoal;if(!(!1===U?.automated)&&(t||P)){const i=U?.matchUpFormat,o=vN({completeAllMatchUps:!P&&t,matchUpStatusProfile:e,randomWinningSide:r,tournamentRecord:n,completionGoal:P,drawDefinition:v,matchUpFormat:i,event:a});if(o.error)return{error:o.error,drawIds:[]};const s=o.completedCount;if(U?.drawType===Ol){const o=v.structures?.find((e=>e.stage===qp));if(!o)return{error:ma};let c=Zh({structureId:o.structureId,tournamentRecord:n,drawDefinition:v,event:a});if(c.error)return{error:c.error,drawIds:[]};if(c=vN({completeAllMatchUps:!P&&t,completionGoal:P?P?P-(s??0):void 0:void 0,matchUpStatusProfile:e,randomWinningSide:r,tournamentRecord:n,drawDefinition:v,matchUpFormat:i,event:a}),c.error)return{error:c.error,drawIds:[]}}}}}return{...Ni,drawIds:p}}function wN(e){const{participantsProfile:t={},uniqueParticipantsCount:r,ratingsParameters:n,tournamentRecord:i,eventProfile:a,eventIndex:o,event:s,uuids:c}=e,{category:u,gender:d,eventType:p}=s,l=p===qf&&gm||p===Wf&&Um||p,m=r[qp]||0,f=r[$p]||0,h=a.drawProfiles?.length?m+f:a.participantsProfile?.participantsCount??0,g=[Lf,jf].includes(d)?d:void 0,I=t?.idPrefix?`E-${o}-${t?.idPrefix}`:void 0,{participants:U}=iN({uuids:a.uuids||c,...t,scaledParticipantsCount:a.scaledParticipantsCount,consideredDate:i?.startDate,rankingRange:a.rankingRange,participantType:l,participantsCount:h,ratingsParameters:n,category:u,idPrefix:I,sex:g}),y=vT({tournamentRecord:i,participants:U});if(y.error)return y;const S=U?.filter((({participantType:e})=>e===l)),v=U?.map(Rd);return{uniqueDrawParticipants:S,uniqueParticipantIds:v}}function bN({autoEntryPositions:e,tournamentRecord:t,drawParticipants:r,drawProfile:n,event:i}){const{drawType:a=gl,qualifyingPositions:o=0,stage:s=qp,drawSize:c=0,drawName:u,drawId:d}=n,p=c-o,l=r.slice(0,p).map(Rd);if(l.length){const r=sT({participantIds:l,autoEntryPositions:e,entryStage:s,tournamentRecord:t,event:i});if(r.error)return r}const m=SP({drawName:u||a,qualifyingPositions:o,drawEntries:l.map((e=>({entryStatus:Ql,entryStage:s,participantId:e}))),drawId:d,event:i,stage:s});return m.error?m:{...Ni}}function RN({uniqueDrawParticipants:e,autoEntryPositions:t,stageParticipants:r,tournamentRecord:n,drawProfiles:i,category:a,gender:o,event:s}){let c=0;for(const u of i){const{qualifyingPositions:i=0,uniqueParticipants:d,stage:p=qp,drawSize:l=0}=u,m=l-i,f=d||o||a||p===$p,h=f?e.slice(c,c+m):r[p||qp]||[];f&&(c+=m);const g=bN({autoEntryPositions:t,drawParticipants:h,tournamentRecord:n,drawProfile:u,event:s});if(g.error)return g}return{...Ni}}function NN(e){const{allUniqueParticipantIds:t,matchUpStatusProfile:r,participantsProfile:n,completeAllMatchUps:i,autoEntryPositions:a,hydrateCollections:o,randomWinningSide:s,ratingsParameters:c,tournamentRecord:u,eventProfile:d,eventIndex:p,publish:l,isMock:m,uuids:f}=e;let h=d.gender,g=d.eventName;const{eventType:I=qf,policyDefinitions:U,drawProfiles:y=[],eventExtensions:S,surfaceCategory:v,tieFormatName:T,processCodes:P,discipline:D,eventLevel:w,timeItems:b,ballType:R,category:N}=d,M=d.eventId||bm(),A=d.tieFormat||(I===zf?sD({namedFormat:T,event:{eventId:M,category:N,gender:h},hydrateCollections:o,isMock:m}):void 0),E=u.participants;for(const e of y)!h&&e.gender&&(h=e?.gender);const{stageParticipantsCount:C,uniqueParticipantsCount:O,uniqueParticipantStages:F}=lN({drawProfiles:y,category:N,gender:h}),k=I===qf&&gm||I===Wf&&Um||I,{uniqueDrawParticipants:_=[],uniqueParticipantIds:x=[]}=F?wN({event:{eventType:I,category:N,gender:h},uniqueParticipantsCount:O,participantsProfile:n,ratingsParameters:c,tournamentRecord:u,eventProfile:d,eventIndex:p,uuids:f}):{};let{eventAttributes:L}=d;"object"!=typeof L&&(L={});const V=N?.categoryName||N?.ageCategoryCode||N?.ratingType;g=g||V||"Generated Event";const B={...L,surfaceCategory:v,processCodes:P,discipline:D,eventLevel:w,eventName:g,eventType:I,tieFormat:A,ballType:R,category:N,eventId:M,gender:h};if(S?.length&&Array.isArray(S)){const e=S.filter(hd);e?.length&&Object.assign(B,{extensions:e})}if(Array.isArray(b)&&b.forEach((e=>pg({event:q,timeItem:e}))),"object"==typeof U)for(const e of Object.keys(U))Bv({policyDefinitions:{[e]:U[e]},event:B});let j;B.category&&(B.category.categoryName=V);const G=uD({suppressNotifications:!1,internalUse:!0,tournamentRecord:u,event:B});if(G.error)return G;const q=G?.event,{stageParticipants:$}=mN({allUniqueParticipantIds:t,stageParticipantsCount:C,eventParticipantType:k,targetParticipants:E});if(y?.length){const e=RN({uniqueDrawParticipants:_,autoEntryPositions:a,stageParticipants:$,tournamentRecord:u,drawProfiles:y,category:N,gender:h,event:q});if(e.error)return e;const t=DN({matchUpStatusProfile:r,completeAllMatchUps:i,randomWinningSide:s,tournamentRecord:u,drawProfiles:y,event:q});if(t.error)return t;j=t.drawIds}else if(d?.participantsProfile?.participantsCount){const e=_.map(Rd);if(e.length){const t=sT({participantIds:e,autoEntryPositions:a,tournamentRecord:u,entryStage:qp,event:q});if(t.error)return t}}return l&&$T({tournamentRecord:u,event:q}),{drawIds:j,eventId:M,uniqueParticipantIds:x}}function MN({tournamentRecord:e}){if(!e)return{error:Fi};const t=(({tournamentId:e,tournamentRank:t,tournamentStatus:r,formalName:n,tournamentName:i,promotionalName:a,onlineResources:o,localTimeZone:s,startDate:c,endDate:u,hostCountryCode:d,tournamentContacts:p,tournamentAddresses:l})=>({tournamentId:e,tournamentRank:t,tournamentStatus:r,formalName:n,tournamentName:i,promotionalName:a,onlineResources:o,localTimeZone:s,startDate:c,endDate:u,hostCountryCode:d,tournamentContacts:p,tournamentAddresses:l}))(e);return{...Ni,tournamentInfo:Jc(t,!1,!0)}}function AN({tournamentRecords:e}){if(!ru(e))return{error:Oi};const t=Object.keys(e??{}).reduce(((t,r)=>{const n=e[r],{tournamentInfo:{startDate:i,endDate:a}}=MN({tournamentRecord:n}),o=i&&new Date(Lc(i));(!t.startDate||o&&o<t.startDate)&&(t.startDate=o);const s=a&&new Date(Lc(a));return(!t.endDate||s&&s>t.endDate)&&(t.endDate=s),t}),{startDate:void 0,endDate:void 0}),r=t.startDate&&Lc(t.startDate.toISOString()),n=t.endDate&&Lc(t.endDate.toISOString());return r&&n?{startDate:r,endDate:n}:{error:Xa}}function EN({tournamentRecords:e,scheduleDate:t,venueId:r,round:n}){if(!bc(t))return{error:io};const{extension:i}=Wl({name:Ti,tournamentRecords:e,discover:!0}),a=i?.value||[];let o=a.find((e=>Qc(t,e.scheduleDate)));if(!o){const{startDate:r,endDate:n}=AN({tournamentRecords:e}),i=new Date(t);if(r&&i<new Date(r)||n&&i>new Date(n))return{error:io};o={scheduleDate:t,venues:[]},a.push(o)}let s=o.venues.find((e=>e.venueId===r));s||(s={venueId:r,rounds:[]},o.venues.push(s));const c=["notBeforeTime"],u=e=>Object.keys(e).filter((e=>!c.includes(e))).sort().map((t=>ru(e[t])?u(e[t]):e[t])).flat().join("|");if(s.rounds.find((e=>u(e)===u(n))))return pd({result:{error:pa},stack:"addSchedulingProfileRound"});s.rounds.push(n);const d=VT({tournamentRecords:e,schedulingProfile:a});return d.error?d:{...Ni}}function CN(e){const t=uy(e,[{drawProfile:!0,_ofType:Bu}]);if(t.error)return t;const{allUniqueParticipantIds:r=[],participantsProfile:n={},matchUpStatusProfile:i,completeAllMatchUps:a,autoEntryPositions:o,hydrateCollections:s,randomWinningSide:c,ratingsParameters:u,tournamentRecord:d,isMock:p=!0,drawProfile:l,startDate:m,drawIndex:f,uuids:h}=e,g=Jc(l,!1,!0),{excessParticipantAlternates:I=!0,matchUpFormat:U=LI,drawType:y=gl,tournamentAlternates:S=0,alternatesCount:v=0,qualifyingPositions:T,qualifyingProfiles:P,generate:D=!0,eventExtensions:w,drawExtensions:b,completionGoal:R,tieFormatName:N,seedsCount:M,timeItems:A,drawName:E,category:C,idPrefix:O,publish:F,gender:k,stage:_}=g,x=g.drawSize||(g.ignoreDefaults?void 0:32),L=g.eventId||bm(),V=l.eventType||l.matchUpType||qf,B=V===Wf?Um:gm,j="object"==typeof l.tieFormat&&l.tieFormat||V===ym&&sD({event:{eventId:L,category:C,gender:k},namedFormat:N,hydrateCollections:s,isMock:p})||void 0,G=C?.categoryName||C?.ageCategoryCode||C?.ratingType,q=l.eventName||G||`Generated ${V}`;let $=d?.participants||[];const W=(P?.map((e=>e.structureProfiles||[])).flat().reduce(((e,t)=>e+(!t.participantsCount||t.participantsCount>t.drawSize?t.drawSize:t.participantsCount||0)),0)||0)*(B===Um?2:1),H=(!l.participantsCount||l.participantsCount>x?x:l.participantsCount)||0,z={eventName:q,eventType:V,tieFormat:j,category:C,eventId:L,gender:k};Array.isArray(A)&&A.forEach((e=>pg({event:z,timeItem:e})));let{eventAttributes:Y}=l;if("object"!=typeof Y&&(Y={}),Object.assign(z,Y),w?.length&&Array.isArray(w)){const e=w.filter(hd);e?.length&&Object.assign(z,{extensions:e})}const Q=[];if(W||l.uniqueParticipants||!d||k||C){const e=(H||0)+v+W;let t=e;const r={[Lf]:0,[jf]:0};let i,a;V===ym&&(({teamSize:i,genders:a}=oN({alternatesCount:v,tieFormatName:N,tieFormat:j,drawSize:x})),Object.keys(a).forEach((e=>{[Lf,jf].includes(e)&&a[e]&&(r[e]=x*a[e])})),t=i*((x||0)+W));const o=n?.idPrefix?`D-${f}-${n?.idPrefix}`:void 0,s=iN({...n,scaledParticipantsCount:l.scaledParticipantsCount||n.scaledParticipantsCount,participantsCount:t,consideredDate:d?.startDate,sex:k||n?.sex,rankingRange:l.rankingRange,uuids:l.uuids||h,ratingsParameters:u,participantType:B,gendersCount:r,idPrefix:o,category:C}).participants;if(z.category&&(z.category.categoryName=G),d){const e=vT({participants:s,tournamentRecord:d});if(e.error)return e}if(s.forEach((({participantId:e})=>Q.push(e))),$=s,V===ym){const t=a[Lf]?s.filter((({participantType:e,person:t})=>e===gm&&t?.sex===Lf)).map(Rd):[],r=a[jf]?s.filter((({participantType:e,person:t})=>e===gm&&t?.sex===jf)).map(Rd):[],n=s.filter((({participantType:e})=>e===gm)).map(Rd).filter((e=>!t.includes(e)&&!r.includes(e))),o=i-(a[Lf]+a[jf]);let c=0,u=0,p=0;const l=Qd(0,e).map((e=>{const i=r.slice(c,c+a[jf]),s=t.slice(u,u+a[Lf]),d=n.slice(p,p+o);return c+=a[jf],u+=a[Lf],p+=o,{individualParticipantIds:[...i,...s,...d],participantOtherName:`TM${e+1}`,participantName:`Team ${e+1}`,participantRole:Zv,participantType:ym,participantId:bm()}})),m=vT({participants:l,tournamentRecord:d});if(!m.success)return m;$=l}}const K=e=>{const{participantType:t}=e;return V===qf&&t===gm||(V===Wf&&t===Um||V===ym&&t===ym)},J=e=>!l.gender||(e.person?.sex===l.gender||e.individualParticipantIds?.some((e=>{const t=$.find((t=>t.participantId===e));return t&&J(t)}))),Z=$.filter(K).filter(J).filter((({participantId:e})=>!r.includes(e))),X=Z.slice(0,H).map((e=>e.participantId));if(p&&X?.length){const e=sT({autoEntryPositions:o,entryStage:_,tournamentRecord:d,participantIds:X,event:z});if(e.error)return e}const ee=W?Z.slice(H,H+W).map((e=>e.participantId)):0;if(p&&ee?.length){let e=0,t=1;const r=(e,t)=>e.stageSequence-t.stageSequence,n=(e,t)=>e.roundTarget-t.roundTarget;for(const i of P.sort(n)){t=i.roundTarget||t;let n,a=1;for(const s of i.structureProfiles.sort(r)){const r=(s.drawSize||Od(s.participantsCount))-(n||0),i=ee.slice(e,e+r),c=sT({entryStage:$p,entryStageSequence:a,autoEntryPositions:o,tournamentRecord:d,participantIds:i,roundTarget:t,event:z});if(c.error)return c;n=s.qualifyingPositions,e+=r,a+=1}t+=1}}const te=I&&d?.participants?.filter((({participantId:e})=>!X.includes(e))).filter(K).filter(J).slice(0,v||x-H||S).map((e=>e.participantId));if(p&&te?.length){const e=sT({participantIds:te,autoEntryPositions:!1,entryStatus:zl,tournamentRecord:d,event:z});if(e.error)return e.error}const re=G||q;if(d&&M&&M<=X.length){Qd(1,M+1).forEach(((e,t)=>{const r={scaleName:re,scaleDate:m,scaleType:NI,scaleValue:e,eventType:V},n=X[t];fN({tournamentRecord:d,participantId:n,scaleItem:r})}))}const ne=Kv({...Jc(l,!1,!0),tournamentRecord:d,seedingScaleName:re,matchUpFormat:U,eventId:L,isMock:p,event:z});if(ne.error)return ne;if(!ne.drawDefinition)return{error:Bi};const{drawDefinition:ie}=ne,ae=ie.drawId;if(Array.isArray(b)&&b.filter(hd).forEach((e=>gd({element:ie,extension:e}))),D){if(lP({drawDefinition:ie,event:z,suppressNotifications:!0}),l.withPlayoffs){const e=ie.structures?.[0].structureId,t=tI({...l.withPlayoffs,tournamentRecord:d,drawDefinition:ie,structureId:e,idPrefix:O,isMock:p,event:z});if(t?.error)return t}const e=!1===l.automated;if(p&&!e){const e=e=>{const t=vN({completeAllMatchUps:e.completeAllMatchUps,completionGoal:e.completionGoal,matchUpStatusProfile:i,randomWinningSide:c,tournamentRecord:d,drawDefinition:ie,matchUpFormat:U,event:z});if(t.error)return t;const r=t.completedCount;if(y===Ol){const e=ie.structures?.find((e=>e.stage===qp));if(!e)return{error:ma};Zh({structureId:e.structureId,tournamentRecord:d,drawDefinition:ie,event:z});const t=vN({completionGoal:R?R?R-(r??0):void 0:void 0,matchUpStatusProfile:i,completeAllMatchUps:a,randomWinningSide:c,tournamentRecord:d,drawDefinition:ie,matchUpFormat:U,event:z});if(t.error)return t}};if(R&&e({completionGoal:R}),l.outcomes){const{matchUps:e}=zU({inContext:!0,drawDefinition:ie,event:z});for(const t of l.outcomes){const{matchUpStatus:r=Vm,matchUpStatusCodes:n,stageSequence:i=1,matchUpIndex:a=0,structureOrder:o,matchUpFormat:s,drawPositions:c,roundPosition:u,stage:p=qp,roundNumber:l,winningSide:m,scoreString:f}=t,h=e?.reduce(((e,t)=>{const{structureId:r,matchUpId:n}=t;return e[r]?e[r].push(n):e[r]=[n],e}),{})??[],g=Object.assign({},...Object.keys(h).map(((e,t)=>({[e]:t+1})))),I=e?.filter((e=>!(p&&e.stage!==p||i&&e.stageSequence!==i||l&&e.roundNumber!==l||u&&e.roundPosition!==u||o&&g[e.structureId]!==o||c&&2!==Jd(c,e.drawPositions).length))),U=I?.[a],y=TN({matchUpStatusCodes:n,tournamentRecord:d,drawDefinition:ie,targetMatchUp:U,matchUpFormat:s,matchUpStatus:r,scoreString:f,winningSide:m});if(y?.error)return y}}a&&e({completeAllMatchUps:a})}F&&$T({tournamentRecord:d,event:z})}else{const e=SP({drawEntries:ie.entries,drawName:E||y,qualifyingPositions:T,drawId:ae,event:z,stage:_});if(e.error)return e}return{...Ni,event:Mf(z),uniqueParticipantIds:Q,targetParticipants:$,drawDefinition:ie,eventId:L,drawId:ae}}const ON=["Mock Tournament","CourtHive Challenge","Racket Rally","Generated Tournament","Factory Follies","Open Competition"];function FN(e){let{tournamentAttributes:t,startDate:r,endDate:n}=e??{};const{tournamentName:i=zd(ON),ratingsParameters:a=Tv,scheduleCompletedMatchUps:o,tournamentExtensions:s,matchUpStatusProfile:c,completeAllMatchUps:u,participantsProfile:d,autoEntryPositions:p,hydrateCollections:l,randomWinningSide:m,policyDefinitions:f,schedulingProfile:h,periodLength:g,autoSchedule:I,eventProfiles:U,venueProfiles:y,drawProfiles:S,uuids:v}=e??{};if(r&&!bc(r)||n&&!bc(n))return{error:io};if(U&&!Array.isArray(U))return{error:ys};if(!r){const e=new Date;r=Nc(n??e),n=Nc(e.setDate(e.getDate()+7))}if(!n){const e=new Date(r);n=Nc(e.setDate(e.getDate()+7))}"object"!=typeof t&&(t={});const T=$R({...t,tournamentName:i,isMock:!0,startDate:r,endDate:n});if(s?.length&&Array.isArray(s)){const e=s.filter((e=>hd({extension:e})));e?.length&&Object.assign(T,{extensions:e,isMock:!0})}if("object"==typeof f)for(const e of Object.keys(f))Bv({policyDefinitions:{[e]:f[e]},tournamentRecord:T});const P=sN({participantsProfile:d,tournamentRecord:T,eventProfiles:U,drawProfiles:S,startDate:r,uuids:v});if(!P.success)return P;const D=[],w=[],b=[];if(Array.isArray(S)){let e=0;for(const t of S){let n=CN({allUniqueParticipantIds:D,matchUpStatusProfile:c,completeAllMatchUps:u,autoEntryPositions:p,hydrateCollections:l,participantsProfile:d,randomWinningSide:m,ratingsParameters:a,tournamentRecord:T,isMock:!0,drawProfile:t,startDate:r,drawIndex:e,uuids:v});if(n.error)return n;const{drawId:i,eventId:o,event:s,uniqueParticipantIds:f}=n;if(n=uD({suppressNotifications:!1,internalUse:!0,tournamentRecord:T,event:s}),n.error)return n;i&&b.push(i),w.push(o),f?.length&&D.push(...f),e+=1}}if(U){let e=0;for(const t of U){const n=NN({allUniqueParticipantIds:D,matchUpStatusProfile:c,participantsProfile:d,completeAllMatchUps:u,autoEntryPositions:p,hydrateCollections:l,randomWinningSide:m,ratingsParameters:a,tournamentRecord:T,eventProfile:t,eventIndex:e,startDate:r,uuids:v});if(n.error)return n;const{eventId:i,drawIds:o,uniqueParticipantIds:s}=n;o&&b.push(...o),w.push(i),s?.length&&D.push(...s),e+=1}}const R=y?.length?pN({tournamentRecord:T,venueProfiles:y,uuids:v}):[];let N,M={};if(h){const e=function({schedulingProfile:e,tournamentRecord:t}){if("object"!=typeof e)return{error:ys};const r=tR({tournamentRecord:t}).containedStructures,n=yS({tournamentRecord:t}).matchUps??[],{tournamentId:i}=t,a=[];for(const o of e){const{scheduleDate:e,venues:s=[]}=o;for(const o of s){const{rounds:s,venueId:c}=o;for(const o of s){const{drawId:s,winnerFinishingPositionRange:u,roundSegment:d}=o,p=n.filter((e=>{const t=u?.indexOf("-")>0&&u.split("-").map((e=>+e)),r=e.finishingPositionRange?.winner;return!(e.drawId!==s||o.roundNumber&&e.roundNumber!==o.roundNumber||r&&t&&2!==Jd(r,t).length&&(jd(r).length!==jd(t).length||Jd(r,t).length!==jd(r).length))}))[0];if(p){const{eventId:n,roundNumber:o,drawName:l,structureName:m,roundName:f}=p;let h=p.structureId;o&&!u&&(h=Object.keys(r).find((e=>r[e].includes(h)))??h);const g={tournamentId:i,structureId:h,roundNumber:o,roundSegment:d,eventId:n,drawId:s},I=EN({tournamentRecords:{[i]:t},round:g,scheduleDate:e,venueId:c});if(I.error)return I;a.push({structureName:m,roundName:f,drawName:l,...g})}}}}return{scheduledRounds:a}}({schedulingProfile:h,tournamentRecord:T});if(e.error)return e;if(N=e.scheduledRounds,I){const{tournamentId:e}=T;M=qR({scheduleCompletedMatchUps:o,tournamentRecords:{[e]:T},periodLength:g})}}return tc(),Mf({...Ni,tournamentRecord:T,scheduledRounds:N,schedulerResult:M,eventIds:w,venueIds:R,drawIds:b})}var kN=Object.freeze({__proto__:null,generateEventWithDraw:CN,generateOutcome:yN,generateOutcomeFromScoreString:eR,generateParticipants:iN,generateTournamentRecord:FN});function _N({keepExtensions:e=[],anonymizeParticipantNames:t=!0,tournamentRecord:r,tournamentName:n,personIds:i=[],tournamentId:a}){if(!r)return{error:Fi};const o=Array.isArray(e)?Ri.concat(...e):Ri,s=t=>Array.isArray(e)?t?.extensions?.filter((e=>o.includes(e.name))):t?.extensions,c={};r.extensions=s(r);const u=a||bm();c[r.tournamentId]=u,r.tournamentId=u,r.createdAt=(new Date).toISOString(),r.tournamentName=n||`Anonymized: ${Nc(new Date)}`,r.isMock=!0,delete r.parentOrganisation;for(const e of r.participants||[]){const t=bm();c[e.participantId]=t,e.participantId=t}for(const e of r.participants||[])Array.isArray(e.individualParticipantIds)&&(e.individualParticipantIds=e.individualParticipantIds.map((e=>c[e])));let d=0;for(const e of r.venues||[]){e.extensions=s(e),e.venueName=`Venue #${d}`,e.venueAbbreviation=`V${d}`;const t=bm();c[e.venueId]=t,e.isMock=!0,d+=1}let p=1;for(const e of r.events||[]){e.extensions=s(e),e.isMock=!0;const t=bm();c[e.eventId]=t,e.eventId=t;const r=e.category?.categoryName||e.category?.ageCategoryCode||e.category?.ratingType||e.gender;if(e.eventName=`Event ${p} ${r}`,Array.isArray(e.entries))for(const t of e.entries)t.participantId=c[t.participantId];for(const t of e.drawDefinitions||[]){t.extensions=s(t);const e=bm();if(c[t.drawId]=e,t.drawId=e,t.isMock=!0,Array.isArray(t.entries))for(const e of t.entries)e.participantId=c[e.participantId];const r=e=>{e.extensions=s(e);const t=bm();c[e.structureId]=t,e.structureId=t;for(const t of e.positionAssignments||[])t.participantId&&(t.participantId=c[t.participantId]);for(const t of e.seedAssignments||[])t.participantId&&(t.participantId=c[t.participantId]);for(const t of e.matchUps||[]){t.isMock=!0;for(const e of t.sides||[])e.lineUp&&(e.lineUp=e.lineUp.map((({participantId:e,collectionAssignments:t})=>({participantId:c[e],collectionAssignments:t}))))}};for(const e of t.structures||[])if(r(e),Array.isArray(e.structures))for(const t of e.structures)r(t);for(const e of t.links||[])e.source.structureId=c[e.source.structureId],e.target.structureId=c[e.target.structureId]}const{extension:n}=Wl({name:pi,element:e});Array.isArray(n?.value?.flights)&&n?.value.flights?.forEach((e=>{if(e.drawId=c[e.drawId],Array.isArray(e.drawEntries))for(const t of e.drawEntries)t.participantId=c[t.participantId]})),p+=1}const l=r.startDate||Nc(new Date),m=(r.participants||[]).filter((({participantType:e})=>e===gm)),f=m.reduce(((e,t)=>{const r=t.person?.sex;return[Lf,jf].includes(r)?e[r]+=1:e[Bf]+=1,e}),{[Lf]:0,[jf]:0,[Bf]:0}),h=Object.assign({},...Object.keys(f).map((e=>({[e]:eN({category:{ageCategoryCode:"O18"},count:f[e],addressProps:{citiesCount:10},personExtensions:[],consideredDate:l,sex:e})?.persons||[]})))),g={[Lf]:0,[jf]:0,[Bf]:0},I=m.length,U=m.reduce(((e,t)=>{const r=t.person?.addresses?.[0]||{},{city:n,state:i,postalCode:a}=r;return e.cities.includes(n)||e.cities.push(n),e.states.includes(i)||e.states.push(i),e.postalCodes.includes(a)||e.postalCodes.push(a),e}),{cities:[],postalCodes:[],states:[]}),y=U.postalCodes.length,S=U.cities.length,v=U.states.length,{cities:T}=YR({count:S||I,participantsCount:I}),{states:P}=QR({count:v||I,participantsCount:I}),{postalCodes:D}=KR({count:y||I,participantsCount:I}),w={cities:T,states:P,postalCodes:D};m.forEach(((e,r)=>{const n=e?.person,a=n?.sex||Bf,o=Lc(n?.birthDate)?.split("-")[0],u=g[a],d=h[a][u];if(g[a]+=1,o){const[,e,t]=d?.birthDate?.split("-")||[],r=[o,e,t].join("-");d.birthDate=r}if(n?.addresses){const e=JR({...w,participantIndex:r,nationalityCode:d.nationalityCode});d.addresses=[e]}d.personId=i?.[r]||bm(),t?(d.standardFamilyName=d.lastName,d.standardGivenName=d.firstName,e.participantName=`${d.standardGivenName} ${d.standardFamilyName}`):(d.standardFamilyName=n?.standardFamilyName,d.standardGivenName=n?.standardGivenName),delete d.firstName,delete d.lastName,d.extensions=s(n),e.person=d,c[n?.personId]=d.personId}));(r.participants||[]).filter((({participantType:e})=>e===Um)).forEach((e=>{const{individualParticipantIds:t}=e;e.participantName=function({individualParticipantIds:e,individualParticipants:t}){let r=t.filter((({participantId:t})=>e.includes(t))).map((({person:e})=>e?.standardFamilyName)).filter(Boolean).sort().join("/");1===e.length&&(r+="/Unknown");return r}({individualParticipantIds:t,individualParticipants:m})}));const b=(r.participants||[]).filter((({participantType:e})=>e===ym)),R=rN({count:b.length}).names;b.forEach(((e,t)=>{e.participantName=R[t]}));const N=(r.participants||[]).filter((({participantType:e})=>e===Im)),M=rN({count:N.length,nameRoot:"Group"}).names;N.forEach(((e,t)=>{e.participantName=M[t]}));const{extension:A}=Wl({element:r,name:Ti});Array.isArray(A?.value)&&A?.value.forEach((e=>{e.tournamentId=c[e.tournamentId],e.structureId=c[e.structureId],e.eventId=c[e.eventId],e.drawId=c[e.drawId]}));const{extension:E}=Wl({element:r,name:Ii});return Array.isArray(E?.value)&&E?.value.forEach((e=>{e.personId=c[e.personId]})),{...Ni}}function xN(e){const{ratingsParameters:t=Tv,participantsProfile:r={},matchUpStatusProfile:n,completeAllMatchUps:i,autoEntryPositions:a,hydrateCollections:o,randomWinningSide:s,schedulingProfile:c,tournamentRecord:u,eventProfiles:d,periodLength:p,venueProfiles:l,autoSchedule:m,drawProfiles:f,uuids:h}=e;if(!u)return{error:Fi};const g=[],I=[],U=[];d?.forEach((e=>{const t=u.events?.find(((t,r)=>void 0!==e.eventIndex&&r===e.eventIndex||e.eventName&&t.eventName===e.eventName||e.eventId&&t.eventId===e.eventId));t?.gender&&(e.gender=t.gender)}));const y=u.participants?.length||void 0;y&&r?.idPrefix&&(r.idPrefix=`${r.idPrefix}-${y}`);const S=sN({startDate:u.startDate,participantsProfile:r,tournamentRecord:u,eventProfiles:d,drawProfiles:f,uuids:h});if(!S.success)return S;if(d){let e=u.events?.length||0;for(const t of d){const{ratingsParameters:o}=t,c=u.events?.find(((e,r)=>void 0!==t.eventIndex&&r===t.eventIndex||t.eventName&&e.eventName===t.eventName||t.eventId&&e.eventId===t.eventId));if(c){const{gender:e,category:d,eventType:p}=c,{drawProfiles:l,publish:m}=t,f=p===qf&&gm||p===Wf&&Um||p;if(l){const{stageParticipantsCount:m,uniqueParticipantsCount:I,uniqueParticipantStages:y}=lN({drawProfiles:l,category:d,gender:e}),{uniqueDrawParticipants:S=[],uniqueParticipantIds:v=[]}=y?wN({event:{eventType:p,category:d,gender:e},uniqueParticipantsCount:I,participantsProfile:r,ratingsParameters:o,tournamentRecord:u,eventProfile:t,uuids:h}):{};g.push(...v);const{stageParticipants:T}=mN({targetParticipants:u.participants||[],allUniqueParticipantIds:g,stageParticipantsCount:m,eventParticipantType:f});let P=RN({uniqueDrawParticipants:S,autoEntryPositions:a,stageParticipants:T,tournamentRecord:u,drawProfiles:l,category:d,gender:e,event:c});if(P.error)return P;if(P=DN({matchUpStatusProfile:n,completeAllMatchUps:i,randomWinningSide:s,tournamentRecord:u,drawProfiles:l,event:c}),P.error)return P;U.push(...P.drawIds)}m&&$T({tournamentRecord:u,event:c})}else{const c=NN({startDate:u.startDate,allUniqueParticipantIds:g,matchUpStatusProfile:n,participantsProfile:r,completeAllMatchUps:i,autoEntryPositions:a,randomWinningSide:s,ratingsParameters:o,tournamentRecord:u,eventProfile:t,eventIndex:e,uuids:h});if(c.error)return c;const{eventId:d,drawIds:p,uniqueParticipantIds:l}=c;p&&U.push(...p),I.push(d),l?.length&&g.push(...l),e+=1}}}if(f){let e=(u.events||[]).map((e=>e.drawDefinitions?.map((()=>1))||[])).flat().reduce(((e,t)=>e+t),0);for(const c of f){let d=CN({startDate:u.startDate,allUniqueParticipantIds:g,matchUpStatusProfile:n,participantsProfile:r,completeAllMatchUps:i,autoEntryPositions:a,hydrateCollections:o,randomWinningSide:s,ratingsParameters:t,tournamentRecord:u,drawProfile:c,drawIndex:e,uuids:h});if(d.error)return d;const{drawId:p,eventId:l,event:m,uniqueParticipantIds:f}=d;if(d=uD({tournamentRecord:u,event:m,internalUse:!0}),d.error)return d;p&&U.push(p),I.push(l),f?.length&&g.push(...f),e+=1}}const v=l?.length?pN({tournamentRecord:u,venueProfiles:l}):[];let T={};if(c?.length){const e=VT({tournamentRecords:{[u.tournamentId]:u},schedulingProfile:c});if(e.error)return e;if(m){const{tournamentId:e}=u;T=qR({tournamentRecords:{[e]:u},periodLength:p})}}return{totalParticipantsCount:u.participants.length,scheduledRounds:undefined,schedulerResult:T,...Ni,eventIds:I,venueIds:v,drawIds:U}}var LN=Object.freeze({__proto__:null,anonymizeTournamentRecord:_N,modifyTournamentRecord:xN}),VN=Object.freeze({__proto__:null,anonymizeTournamentRecord:_N,generate:kN,generateEventWithDraw:CN,generateOutcome:yN,generateOutcomeFromScoreString:eR,generateParticipants:iN,generateTournamentRecord:FN,modifyTournamentRecord:xN,mutate:LN});function BN(e=0){("number"!=typeof e||isNaN(e))&&(e=0);const t=new Date;return t.setHours(t.getHours()+e),t.getTime().toString(36).slice(-6).toUpperCase()}function jN({personRequests:e,personId:t,requests:r}){e[t]||(e[t]=[]);const n=r.filter((({requestType:e})=>e)).map((e=>{let{date:t,startTime:r,endTime:n}=e;return e.requestType===dR&&(t=Lc(t),r=xc(r),n=xc(n),t&&r&&n)?{date:t,startTime:r,endTime:n,requestType:e.requestType}:e})).filter(Boolean);for(const r of n)r.requestId=BN(),e[t].push(r);return{mergeCount:n.length}}function GN(e){const{tournamentRecords:t,personRequests:r}=e,n=uy(e,[{[gu]:!0}]);if(n.error)return n;if(!r)return{...Ni};const i=Object.values(t);for(const e of i){const t=e.participants??[],n=[];for(const e of Object.keys(r))if(dd({tournamentParticipants:t,personId:e})){const t=r[e];t.length&&n.push({personId:e,requests:t})}if(Object.keys(n).length){gd({element:e,extension:{value:n,name:Ii}})}}return{...Ni}}function qN(e){const{tournamentRecords:t,requests:r,personId:n}=e,i=uy(e,[{[gu]:!0},{requests:!0,[$u]:ju,[qu]:ys}]);if(i.error)return i;const a=r.map((({requestId:e})=>e)).filter(Boolean),{personRequests:o}=LR({tournamentRecords:t}),s=e=>{o&&(o[e]=o[e].map((e=>{if(!a.includes(e.requestId))return e;const t=r.find((t=>t.requestId===e.requestId));return t.requestType?Object.assign(e,t):void 0})).filter(Boolean))};if(n&&o?.[n])s(n);else if(o)for(const e of Object.keys(o))s(e);const c=r.filter((e=>!e.requestId));return c.length&&jN({personRequests:o,personId:n,requests:c}),GN({tournamentRecords:t,personRequests:o})}function $N(e){const{tournamentRecords:t,requestType:r,requestId:n,personId:i,date:a}=e,o=uy(e,[{[gu]:!0}]);if(o.error)return o;const{personRequests:s}=LR({tournamentRecords:t}),c=e=>{s&&(s[e]=s[e].filter((e=>!(r&&e.requestType===r||n&&e.requestId===n||a&&e.date===a))),s?.[e]?.length||delete s[e])},u=!(r||n||i||a);if(!u)if(i&&s?.[i])c(i);else if(s)for(const e of Object.keys(s))c(e);return!u&&s&&Object.keys(s).length?GN({tournamentRecords:t,personRequests:s}):fd({name:Ii,tournamentRecords:t,discover:!0})}function WN(e){const{tournamentRecords:t,personId:r,requests:n}=e,i=uy(e,[{[gu]:!0,personId:!0},{requests:!0,[$u]:ju,[qu]:ys}]);if(i.error)return i;const{personRequests:a}=LR({tournamentRecords:t}),{mergeCount:o}=jN({personRequests:a,personId:r,requests:n});return o&&a?GN({tournamentRecords:t,personRequests:a}):{error:ys}}function HN({individualParticipantIds:e,groupingParticipantId:t,removeFromOtherTeams:r,tournamentRecord:n}){const i="addIndividualParticipantIds";if(!n)return a({result:{error:Fi},stack:i});if(!t||!e)return a({result:{error:Za},stack:i});const o=n.participants??[],s=o.find((e=>e.participantId===t));if(!s)return a({result:{error:wo},stack:i});if(s?.participantType&&![ym,Im].includes(s.participantType))return a({context:{participantType:s.participantType},result:{error:So},stack:i});const c=e.filter((e=>{const t=o.find((t=>t.participantId===e));return t?.participantType!==gm}));if(c.length)return a({result:{error:Uo,invalidParticipantIds:c},stack:i});s.individualParticipantIds||(s.individualParticipantIds=[]);const u=s.individualParticipantIds,d=e.filter((e=>!u.includes(e)));d.length&&(r&&iT({individualParticipantIds:d,tournamentRecord:n}),s.individualParticipantIds=s.individualParticipantIds.concat(...d));const{topics:p}=Ze();if(p.includes(Tp)){const e=o.find((({participantId:e})=>e===t));Je({topic:Tp,payload:{participants:[e]}})}return function({individualParticipantIds:e,groupingParticipantId:t,tournamentRecord:r}){const n=(r.events||[]).filter((e=>e?.eventType===zf&&e?.entries?.some((e=>e.participantId===t)))),i=t=>!e.includes(t.participantId);for(const e of n){e.entries=(e.entries||[]).filter(i);const{flightProfile:t}=bU({event:e});t?.flights?.forEach((e=>{e.drawEntries=(e.drawEntries||[]).filter(i)})),e?.drawDefinitions?.forEach((e=>{e.entries=(e.entries||[]).filter(i)}))}}({individualParticipantIds:e,groupingParticipantId:t,tournamentRecord:n}),{groupingParticipant:L(s,!1,!0),added:d.length,...Ni}}function zN({individualParticipantIds:e,groupingParticipantId:t,tournamentRecord:r}){const n="modifyIndividualParticipantIds";if(!r)return pd({result:{error:Fi},stack:n});if(!t||!e)return pd({result:{error:Za},stack:n});const i=r.participants||[],a=i.find((e=>e.participantId===t));if(!a)return pd({result:{error:wo},stack:n});if(![ym,Im].includes(a.participantType))return pd({result:{error:So},context:{participantType:a.participantType},stack:n});const o=e.filter((e=>{const t=i.find((t=>t.participantId===e));return t?.participantType!==gm}));if(o.length)return pd({result:{error:Uo,invalidParticipantIds:o},stack:n});const s=a.individualParticipantIds||[],c=e.filter((e=>!s.includes(e))),u=s.filter((t=>!e.includes(t))),d=HN({individualParticipantIds:c,groupingParticipantId:t,tournamentRecord:r});if(d.error)return pd({result:d,stack:n});const p=rT({individualParticipantIds:u,groupingParticipantId:t,tournamentRecord:r});if(p.error)return pd({result:p,stack:n});const{topics:l}=sc();if(l.includes(Tp)){const e=i.find((({participantId:e})=>e===t));rc({topic:Tp,payload:{tournamentId:r.tournamentId,participants:[e]}})}return{...d,...p}}function YN({tournamentRecord:e,participantIds:t,signInState:r}){if(!e)return{error:Fi};if(!Array.isArray(t))return{error:Za};if(![fm,mm].includes(r))return{error:ys,signInState:r};const n=e.participants||[];if(!n.length)return{error:Po};const i=n.map(Rd),a=t.filter((e=>!i.includes(e)));if(a.length)return{error:ys,context:{invalidParticipantIds:a}};const o=[],s=(new Date).toISOString();for(const i of n){const{participantId:n}=i;if(t.includes(n)){const t=ug({duplicateValues:!1,tournamentRecord:e,participantId:n,timeItem:{itemType:lm,itemValue:r,createdAt:s}});if(t.error)return t;o.push(i)}}const{topics:c}=sc();return o.length&&c.includes(Tp)&&rc({topic:Tp,payload:{tournamentId:e.tournamentId,participants:o}}),{...Ni}}function QN({tournamentRecord:e,participantId:t,participantOtherName:r}){if(!e)return{error:Fi};if(!t)return{error:Do};const{participant:n}=rg({tournamentRecord:e,participantId:t});if(!n)return{error:wo};n.participantOtherName=r;const{topics:i}=sc();return i.includes(Tp)&&rc({topic:Tp,payload:{tournamentId:e.tournamentId,participants:[n]}}),{...Ni}}function KN({personFormat:e,person:t}){const r=e=>e.replace(/\W/g,""),n=e=>e.toLowerCase().indexOf("l")<e.toLowerCase().indexOf("f"),i=e=>e.indexOf(",")>=0;if(!t)return;const a=e.indexOf(" ")>0?" ":"";let o=Dm(t?.standardGivenName??""),s=Dm(t?.standardFamilyName??"");if(!e)return`${o}${a}${s}`;!(e=>e.toLowerCase().indexOf("f.")>=0)(e)||i(e)||n(e)||(o=`${o[0]}.`),(e=>/^[a-z]*$/.test(r(e)))(e)?(o=o.toLowerCase(),s=s.toLowerCase()):(e=>/^[A-Z]*$/.test(r(e)))(e)?(o=o.toUpperCase(),s=s.toUpperCase()):(e=>/^[LAST]{4}/.test(r(e)))(e)&&(s=s.toUpperCase());let c=`${o}${a}${s}`;return(e=>e.toLowerCase().indexOf("f")<0)(e)?c=s:n(e)&&(c=i(e)?`${s},${a}${o}`:`${s}${a}${o}`),c}function JN({participantMap:e,participant:t,formats:r}){const{participantType:n,individualParticipantIds:i,person:a}=t,o=n&&r[n];if(n!==hm&&o){const{personFormat:r,doublesJoiner:s}=o;n===gm&&(t.participantName=KN({person:a,personFormat:r})),n===Um&&(t.participantName=i?.map((t=>{const n=e[t]?.person;return KN({person:n,personFormat:r})})).filter(Boolean).join(s??"/"))}}function ZN({tournamentRecord:e,formats:t}){if(!e)return{error:Fi};if(!ru(t))return{error:Za};const r=e.participants??[],n=nu(r,"participantId");for(const e of r)JN({participant:e,participantMap:n,formats:t});return{...Ni}}function XN(e){const{tournamentRecord:t,policyDefinitions:r,contextProfile:n,participantId:i,personId:a}=e,o=e.tournamentRecords||t&&{[t.tournamentId]:t}||{};if("string"!=typeof i&&"string"!=typeof a)return{error:Za,stack:"publicFindParticipant"};let s,c;for(const e of Object.values(o)){c=e.tournamentId;if(s=dd({tournamentParticipants:e.participants||[],internalUse:!0,policyDefinitions:r,contextProfile:n,participantId:i,personId:a}),s)break}return{participant:s,tournamentId:c,...Ni}}function eM({individualParticipantIds:e=[],participantRoleResponsibilities:t,participantRole:r=eT,tournamentRecord:n,participantId:i,groupName:a}){if(!n)return{error:Fi};if(!a)return{error:Za,info:"Missing groupName"};if(!Array.isArray(e))return{info:"Invalid individualParticipantIds",error:ys};const o=(OS({participantFilters:{participantTypes:[gm]},tournamentRecord:n}).participants??[]).map((e=>e.participantId));for(const t of e)if(!o.includes(t))return{error:So,participantId:t};const s=Mf({participantId:i||bm(),participantRoleResponsibilities:t,participantName:a,individualParticipantIds:e,participantType:Im,participantRole:r}),c=ST({participant:s,tournamentRecord:n});if(c.error)return c;const{topics:u}=sc();return u.includes(dp)&&rc({topic:dp,payload:{tournamentId:n.tournamentId,participants:[s]}}),{...Ni,participant:Jc(s)}}function tM({tournamentRecord:e,participantName:t,participantId:r}){if(!e)return{error:Fi};if(!r)return{error:Do};if(!t)return{error:Za,info:"Missing participantName"};const{participant:n}=rg({tournamentRecord:e,participantId:r});if(!n)return{error:wo};n.participantName=t;const{topics:i}=sc();return i.includes(Tp)&&rc({topic:Tp,payload:{tournamentId:e.tournamentId,participants:[n]}}),{...Ni}}function rM({clearExistingAssignments:e=!0,individualParticipantIds:t,reverseAssignmentOrder:r,initialTeamIndex:n=0,scaledParticipants:i=[],teamParticipantIds:a,tournamentRecord:o,scaleAttributes:s,teamNameBase:c,teamsCount:u,eventId:d,event:p}){if(!o)return{error:Fi};if(!Array.isArray(a)&&!Vd(u)&&!d||!Vd(n)||i&&!Array.isArray(i)||s&&("object"!=typeof s||!Object.keys(s).length))return{error:ys};if(!s&&!i.length||!i&&(!t||!s))return{error:Za,info:"Missing scaling details"};if(d&&!a){if(p?.eventType!==Yf)return{error:Ia};a=p?.entries?.filter((({entryStatus:e})=>e===Ql)).map(Rd)}if(!a?.length&&!u)return{info:"Missing teamParticipantIds or teamsCount",error:Za};let l=t??i.map((({participantId:e})=>e));r&&(a?.reverse(),n+=1),n>(a?.length||0)-1&&(n=0);const m=a?.slice(n).concat(...a.slice(0,n))??[],f=[];for(const e of o.participants??[]){const{participantId:t,participantType:r}=e;if(m.includes(t)){if(r!==hm)return{error:So,participant:e};f.push(e)}}if(u&&f.length<u){const e=c??"Team",t=Qd(0,u-(f?.length||0)).map((t=>({participantName:`${e} ${t+1}`,participantType:hm,participantRole:Zv}))),{participants:r=[]}=vT({participants:t,returnParticipants:!0,tournamentRecord:o}),n=r.map(Rd),i=o.participants?.filter((({participantId:e})=>n.includes(e)))??[];f.push(...i)}if(!f.length)return{error:vs};if(e)for(const e of f)e.individualParticipantIds=[];else{const e=f.map((e=>e)).flat();t?.length?l=l.filter((t=>!e.includes(t))):i=i?.filter((({participantId:t})=>!e.includes(t)))}if(!t?.length&&!i?.length)return{error:ms,info:"Nothing to be done"};if(!i.length){for(const e of o.participants??[]){const{participantId:t,participantType:r}=e;if(!l.includes(t))continue;if(r!==gm)return{error:So,participant:e};const n=AU({scaleAttributes:s,participant:e})?.scaleItem,a={participantId:t,scaleValue:s?.accessor?n?.scaleValue?.[s?.accessor]:n?.scaleValue};i.push(a)}if(!i.length)return{error:wo}}i.sort(((e,t)=>s?.sortOrder?(t?.scaleValue||0)-(e?.scaleValue||0):(e?.scaleValue||1/0)-(t?.scaleValue||1/0)));for(const e of i)if(!e.participantId)return{error:ys,scaledParticipant:e};let h=0;for(;h<i.length;){for(const e of f){if(h+1>i.length)break;const t=i[h];e.individualParticipantIds.push(t.participantId),h++}f.reverse()}const g=f.map(Rd);for(const e of o.events??[]){if(e.eventType!==Yf)continue;const t=(e.entries??[]).filter((e=>g.includes(e.participantId)));for(const r of t){const t=r.participantId,n=f.find((e=>e.participantId===t)),i=n?.individualParticipantIds;e.entries=(e.entries??[]).filter((e=>!i.includes(e.participantId))),(e.drawDefinitions??[]).forEach((e=>{e.entries=(e.entries??[]).filter((e=>!i.includes(e.participantId)))}));const{flightProfile:a}=bU({event:e});(a?.flights||[]).forEach((e=>{e.drawEntries=(e.drawEntries||[]).filter((e=>!i.includes(e.participantId)))}))}}return{...Ni,scaledParticipants:i}}function nM(e){const{tournamentRecords:t}=e;if("object"!=typeof t||!Object.keys(t).length)return{error:Oi};for(const r of Object.values(t)){const t=iM({...e,tournamentRecord:r});if(t.error&&t.error!==Wo)return t}return{...Ni}}function iM({tournamentRecord:e,penaltyId:t}){if(!e)return{error:Fi};if(!t)return{error:$o};const r=[];let n,i=!1;return(e?.participants??[]).forEach((e=>{let a=!1;e.penalties=(e.penalties??[]).filter((o=>(o.penaltyId===t&&(a=!0,i||(n=o,i=!0)),a&&r.push(e),o.penaltyId!==t)))})),n&&rc({topic:Tp,payload:{tournamentId:e.tournamentId,participants:r}}),n?{...Ni,penalty:n}:{error:Wo}}const aM=({penaltyId:e=bm()}={})=>({refereeParticipantId:void 0,penaltyCode:void 0,penaltyType:void 0,extensions:void 0,matchUpId:void 0,createdAt:void 0,issuedAt:void 0,notes:void 0,penaltyId:e});function oM(e){const{tournamentRecords:t}=e;if("object"!=typeof t||!Object.keys(t).length)return{error:Oi};for(const r of Object.values(t)){const t=sM({...e,tournamentRecord:r});if(t.error&&t.error!==Wo)return t;if(t.success)return t}return{error:Wo}}function sM({tournamentRecord:e,modifications:t,penaltyId:r}){if(!e)return{error:Fi};if(!t)return{error:ys,modifications:t};if(!r)return{error:$o};const n=e?.participants??[],i=Object.keys(aM()).filter((e=>"penaltyId"!==e)),a=Object.keys(t).filter((e=>i.includes(e)));if(!a.length)return{error:Ps};let o;const s=[];return n.forEach((e=>{let n=!1;e.penalties=(e.penalties??[]).map((e=>(e.penaltyId===r&&(n=!0,a.forEach((r=>Object.assign(e,{[r]:t[r]}))),o||(o=e)),e))),n&&s.push(e)})),o&&rc({topic:Tp,payload:{tournamentId:e.tournamentId,participants:s}}),o?{...Ni,penalty:o}:{error:Wo}}function cM(e,t,r){if(!e&&t)return t;if(e&&!t)return e;if("object"!=typeof e||"object"!=typeof t)return e;return jd(Object.keys(e).concat(Object.keys(t))).reduce(((n,i)=>{if(t[i])if(e[i])if(typeof e[i]!=typeof t[i])n[i]=t[i];else if(Array.isArray(e[i]))if(!0===r||Array.isArray(r)&&r.includes(i)){const r=jd(e[i].map((e=>JSON.stringify(e))).concat(t[i].map((e=>JSON.stringify(e))))).map((e=>JSON.parse(e)));n[i]=r}else n[i]=t[i];else"object"==typeof e[i]?n[i]=cM(e[i],t[i],r):n[i]=t[i];else n[i]=t[i];else n[i]=e[i];return n}),{})}function uM({participants:e=[],tournamentRecord:t,arraysToMerge:r}){if(!t)return{error:Fi};t.participants||(t.participants=[]);const n=e.filter(au(vu)).map((e=>({[e.participantId]:e}))),i=Object.assign({},...n),a=[];t.participants=t.participants.map((e=>{if(i[e.participantId]){const t=cM(e,i[e.participantId],r);return a.push(t),t}return e}));const o=t.participants.map(au(vu))||[],s=e.filter((({participantId:e})=>!o.includes(e))),{topics:c}=sc();return s.length&&(t.participants=t.participants.concat(...s),c.includes(dp)&&rc({topic:dp,payload:{participants:s}})),a.length&&c.includes(Tp)&&rc({topic:Tp,payload:{tournamentId:t.tournamentId,participants:a}}),{modifiedParticipantsCount:a.length,newParticipantsCount:s.length,...Ni}}function dM(e){const{updateParticipantName:t=!0,groupingParticipantId:r,removeFromOtherTeams:n,tournamentRecord:i,pairOverride:a,participant:o}=e;if(!i)return{error:Fi};if(!o)return{error:To};if(!o.participantId)return ST({tournamentRecord:i,participant:o});const{participant:s}=rg({participantId:o.participantId,tournamentRecord:i});if(!s)return ST({tournamentRecord:i,participant:o});const{participantRoleResponsibilties:c,individualParticipantIds:u,participantOtherName:d,participantName:p,participantRole:l,participantType:m,onlineResources:f,contacts:h,person:g}=o;if(m&&s.participantType!==m)return{error:mo};const I={};if(h&&(I.contacts=h),f&&(I.onlineResources=f),p&&"string"==typeof p&&(I.participantName=p),d&&"string"==typeof d&&(I.participantOtherName=d),Array.isArray(u)){const{participants:e}=OS({participantFilters:{participantTypes:[gm]},tournamentRecord:i}),r=e?.map(Rd);if(r){const n=u.filter((e=>"string"==typeof e&&r.includes(e)));([Im,If].includes(m||s.participantType)||m===Um&&(2===n.length||a))&&(I.individualParticipantIds=n),s.participantType===Sm.PAIR&&t&&(I.participantName=function({individualParticipants:e,newValues:t}){const r=t.individualParticipantIds;let n=e.filter((({participantId:e})=>r.includes(e))).map((({person:e})=>e?.standardFamilyName)).filter(Boolean).sort().join("/");1===r.length&&(n+="/Unknown");return n}({individualParticipants:e,newValues:I}))}}return Object.keys(tT).includes(l)&&(I.participantRole=l),Object.keys(Sm).includes(m)&&(I.participantType=m),Array.isArray(c)&&(I.participantRoleResponsibilties=c),s.participantType===Sm.INDIVIDUAL&&g&&function({updateParticipantName:e,existingParticipant:t,newValues:r,person:n}){const i={},{standardFamilyName:a,standardGivenName:o,nationalityCode:s,personId:c,sex:u}=n;u&&Object.keys(Gf).includes(u)&&(i.sex=u);let d;c&&"string"==typeof c&&(i.personId=c);s&&"string"==typeof s&&(p=s,_U.flatMap((({iso:e,ioc:t})=>[e,t])).filter(Boolean).includes(p)||""===s)&&(i.nationalityCode=s);var p;a&&"string"==typeof a&&a.length>1&&(i.standardFamilyName=a,d=!0);o&&"string"==typeof o&&o.length>1&&(i.standardGivenName=o,d=!0);if(d&&e){const e=`${i.standardGivenName} ${i.standardFamilyName}`;r.participantName=e}Object.assign(t.person,i)}({updateParticipantName:t,existingParticipant:s,newValues:I,person:g}),Object.assign(s,Mf(I)),r&&HN({individualParticipantIds:[s.participantId],groupingParticipantId:r,removeFromOtherTeams:n,tournamentRecord:i}),rc({topic:Tp,payload:{tournamentId:i.tournamentId,participants:[s]}}),{participant:Jc(s),...Ni}}function pM(e){const{tournamentRecord:t,participantIds:r}=e,n=e.tournamentRecords??(t&&{[t.tournamentId]:t})??{};let i;for(const t of Object.values(n)){const n=pt({tournamentRecord:t}).participants??[],a=n?.map(v).filter((e=>r.includes(e)));if(a.length){i=lM({...e,penaltyId:e.penaltyId??i,tournamentRecord:t,participantIds:a}).penaltyId}}return i?{...Ni,penaltyId:i}:{error:wo}}function lM({refereeParticipantId:e,tournamentRecord:t,participantIds:r,penaltyCode:n,penaltyType:i,extensions:a,penaltyId:s,matchUpId:c,issuedAt:u,notes:d}){if(!t)return{error:Fi};if(!r)return{error:Do};if(!i)return{error:qo};const p=(t?.participants??[]).filter((e=>r.includes(e.participantId)));if(!p.length)return{error:wo};const l=(new Date).toISOString(),m=Object.assign(aM({penaltyId:s}),{refereeParticipantId:e,penaltyCode:n,penaltyType:i,matchUpId:c,notes:d,issuedAt:u,createdAt:l});return Array.isArray(a)&&a.forEach((e=>o({element:m,extension:e}))),p.forEach((e=>{e.penalties||(e.penalties=[]),e.penalties.push(m)})),Je({topic:Tp,payload:{tournamentId:t.tournamentId,participants:p}}),{...Ni,penaltyId:m.penaltyId}}function mM({participantRole:e=Zv,tournamentRecord:t,persons:r}){if(!t)return{error:Fi};if(!Array.isArray(r))return{error:ys};if(!Object.keys(tT).includes(e))return{error:yo};const n=(t.participants||[]).map((({person:e})=>e?.personId)).filter(Boolean),i=[],a=r.filter((e=>e&&(!e.personId||!n.includes(e.personId)))).map((e=>(e.personId||(e.personId=bm()),i.push(e.personId),e)));let o=0,s=0,c=vT({participants:a.map((t=>{return Mf({extensions:t.participantExtensions,timeItems:t.participantTimeItems,participantType:gm,participantRole:e,person:(r=t,n=["participantExtensions","participantTimeItems","pairedPersons"],Object.assign({},...Object.keys(r).filter((e=>!n.includes(e))).map((e=>({[e]:r[e]})))))});var r,n})),tournamentRecord:t});if(c.error)return c;s=c.addedCount||0;const u=[],d=OS({participantFilters:{participantTypes:[gm]},tournamentRecord:t})?.participants??[];if(e===Zv&&r.filter((({pairedPersons:e})=>e)).forEach((({personId:e,pairedPersons:t})=>{Array.isArray(t)&&t.forEach((t=>{const r=[e,t.personId].map((e=>dd({tournamentParticipants:d,personId:e}))).filter(Boolean);if(2===r.length){const e=r.map(Rd);u.push(Mf({extensions:t.participantExtensions,timeItems:t.timeItems,participantRole:Zv,individualParticipantIds:e,participantType:Um}))}}))})),u.length){if(c=vT({participants:u,tournamentRecord:t}),c.error)return c;o=c.addedCount||0}const p=s+o;return{...Ni,addedCount:p,newPersonIds:i}}var fM=Object.freeze({__proto__:null,addIndividualParticipantIds:HN,addParticipant:ST,addParticipants:vT,addPenalty:pM,addPersonRequests:WN,addPersons:mM,createGroupParticipant:eM,createTeamsFromParticipantAttributes:WR,deleteParticipants:cT,findParticipant:XN,mergeParticipants:uM,modifyIndividualParticipantIds:zN,modifyParticipant:dM,modifyParticipantName:tM,modifyParticipantOtherName:QN,modifyParticipantsSignInStatus:YN,modifyPenalty:oM,modifyPersonRequests:qN,regenerateParticipantNames:ZN,removeIndividualParticipantIds:rT,removeParticipantIdsFromAllTeams:iT,removePenalty:nM,removePersonRequests:$N,scaledTeamAssignment:rM,setParticipantScaleItem:fN,setParticipantScaleItems:hN});function hM(e){const{tournamentRecords:t}=e||{};if("object"!=typeof t||!Object.keys(t).length)return{error:Oi};const r=[],n={},i={},a={},o=[],s={},c=[];for(const u of Object.values(t)){const{participantIdsWithConflicts:t,mappedMatchUps:d,participantMap:p,participants:l,matchUps:m,derivedEventInfo:f,derivedDrawInfo:h}=OS({...e,tournamentRecord:u});Object.assign(s,d),Object.assign(n,p),Object.assign(i,f),Object.assign(a,h),r.push(...l??[]),o.push(...m??[]),t?.forEach((e=>{c.includes(e)||c.push(e)}))}return{participantIdsWithConflicts:c,derivedEventInfo:i,derivedDrawInfo:a,participantMap:n,mappedMatchUps:s,participants:r,...Ni,matchUps:o}}function gM({tournamentRecord:e,participantId:t}){if(!e)return{error:Fi};if(!t)return{error:Do};const r=[t].concat((e.participants??[]).filter((e=>e?.participantType&&[ym,Um].includes(e.participantType)&&e.individualParticipantIds?.includes(t))).map((e=>e.participantId)));return{eventDetails:(e.events??[]).filter((e=>{const t=(e?.entries??[]).map((e=>e.participantId));return d(t,r)})).map((e=>({eventName:e.eventName,eventId:e.eventId})))}}function IM({tournamentRecord:e,participantId:t}){if(!e)return{error:Fi};if(!t)return{error:Do};const{participants:r}=OS({participantFilters:{participantTypes:[ym,Um,Im]},tournamentRecord:e});return(r??[]).filter((e=>e.individualParticipantIds?.includes(t))).reduce(((e,t)=>{const r=t.participantType;return r&&(e[r]||(e[r]=[]),e[r].push(t)),e}),{})}function UM({participantFilters:e={},tournamentRecord:t}){if(!t)return{error:Fi};if("object"!=typeof e)return{error:gs,context:{participantFilters:e}};const r=yS({tournamentRecord:t,contextFilters:{eventIds:e.eventIds}}).matchUps??[],n=Object.assign({},...r.map((e=>({[e.matchUpId]:e})))),i=r.filter((({schedule:e})=>e&&Object.keys(e).length)),a=TS({tournamentRecord:t,matchUps:r}).sourceMatchUpIds??[],o={};for(const e of i){const{sides:t}=e;let r;const i=t?.map((t=>{if(t.participant)return[t.participant].concat(...t.participant.individualParticipants||[]);a[e.matchUpId]&&!r&&(r=(a[e.matchUpId]||[]).map((e=>n[e])).filter((({winningSide:e,bye:t})=>!e&&!t)))})).filter(Boolean).flat()??[];for(const t of i){const{participantId:r}=t;o[r]||(o[r]={potentialMatchUps:[],participant:t,matchUps:[]}),o[r].matchUps.push(e)}const s=r?.map((({sides:e})=>e)).flat().map((({participant:e})=>e&&[e].concat(...e.individualParticipants||[]))).filter(Boolean).flat()||[];for(const t of s){const{participantId:r}=t;o[r]||(o[r]={potentialMatchUps:[],participant:t,matchUps:[]}),o[r].potentialMatchUps.push(e)}}return{participantSchedules:Object.values(o).filter((({participant:t})=>!(e.participantIds&&!e.participantIds.includes(t.participantId)||e.participantTypes&&!e.participantTypes.includes(t.participantType)))),...Ni}}function yM({tournamentRecord:e,participantId:t}){if(!e)return{error:Fi};if(!t)return{error:Do};const{participant:r}=rg({tournamentRecord:e,participantId:t});if(!r)return{error:wo};const{timeItem:n}=ng({itemType:lm,element:r});return n&&n.itemValue===fm&&fm}var SM=Object.freeze({__proto__:null,filterParticipants:ES,getCompetitionParticipants:hM,getPairedParticipant:yT,getParticipantEventDetails:gM,getParticipantMembership:IM,getParticipantScaleItem:EU,getParticipantSchedules:UM,getParticipantSignInStatus:yM,getParticipantTimeItem:sg,getParticipants:OS,getScaleValues:Hu,participantScaleItem:AU,validateLineUp:vU}),vM=Object.freeze({__proto__:null,addIndividualParticipantIds:HN,addParticipant:ST,addParticipants:vT,addPenalty:pM,addPersonRequests:WN,addPersons:mM,createGroupParticipant:eM,createTeamsFromParticipantAttributes:WR,deleteParticipants:cT,filterParticipants:ES,findParticipant:XN,getCompetitionParticipants:hM,getPairedParticipant:yT,getParticipantEventDetails:gM,getParticipantMembership:IM,getParticipantScaleItem:EU,getParticipantSchedules:UM,getParticipantSignInStatus:yM,getParticipantTimeItem:sg,getParticipants:OS,getScaleValues:Hu,mergeParticipants:uM,modifyIndividualParticipantIds:zN,modifyParticipant:dM,modifyParticipantName:tM,modifyParticipantOtherName:QN,modifyParticipantsSignInStatus:YN,modifyPenalty:oM,modifyPersonRequests:qN,mutate:fM,participantScaleItem:AU,query:SM,regenerateParticipantNames:ZN,removeIndividualParticipantIds:rT,removeParticipantIdsFromAllTeams:iT,removePenalty:nM,removePersonRequests:$N,scaledTeamAssignment:rM,setParticipantScaleItem:fN,setParticipantScaleItems:hN,validateLineUp:vU});function TM({removePriorValues:e=!0,stageSeedingScaleNames:t,seedingScaleNames:r,tournamentRecord:n,status:i=AI,drawIds:a=[],event:o}){if(!n)return{error:Fi};if(!o)return{error:Ua};const s=jT({event:o,status:i}),c=(s?.seeding?.seedingScaleNames||r)&&{...s?.seeding?.seedingScaleNames,...r};return GT({statusObject:{seeding:Mf({stageSeedingScaleNames:(s?.seeding?.stageSeedingScaleNames||t)&&{...s?.seeding?.stageSeedingScaleNames,...t},seedingScaleNames:c,published:!0,drawIds:a})},removePriorValues:e,status:i,event:o}),rc({topic:Mp,payload:{tournamentId:n.tournamentId,eventId:o.eventId,drawIds:a}}),{...Ni}}function PM({removePriorValues:e=!0,seedingScaleNames:t,tournamentRecord:r,status:n=AI,drawIds:i,stages:a,event:o}){if(!r)return{error:Fi};if(!o)return{error:Ua};const s=jT({event:o});if(s){const r=s.seeding;if(Array.isArray(a)&&r.stageSeedingScaleNames)for(const e of a)r.stageSeedingScaleNames[e]&&delete r.stageSeedingScaleNames[e];Array.isArray(t)&&r?.seedingScaleNames&&(r.seedingScaleNames=r.seedingScaleNames.filter((e=>!t.includes(e)))),Array.isArray(i)&&r?.drawIds&&(r.drawIds=r.drawIds.filter((e=>!i.includes(e)))),(Object.values(r.stageSeedingScaleNames??{}).length||r.seedingScaleNames?.length||r.drawIds?.length)&&(a||t||i?.length)||(delete r.stageSeedingScaleNames,delete r.seedingScaleNames,delete r.drawIds,r.published=!1),GT({statusObject:{seeding:r},removePriorValues:e,status:n,event:o})}return rc({topic:Cp,payload:{tournamentId:r.tournamentId,eventId:o.eventId}}),{...Ni}}function DM(e){const t=e?.tournamentRecords??(e?.tournamentRecord&&{[e.tournamentRecord.tournamentId]:e.tournamentRecord})??{};if(!Object.keys(t).length)return{error:Oi};for(const r of Object.values(t)){const t=wM({tournamentRecord:r,...e});if(t.error)return t}return{...Ni}}function wM({removePriorValues:e=!0,tournamentRecord:t,status:r=AI}){if(!t)return{error:Fi};const n=`${MI}.${EI}`,{timeItem:i}=ng({element:t,itemType:n}),a=i?.itemValue||{[r]:{}};a[r]&&delete a[r].orderOfPlay;return cg({timeItem:{itemValue:a,itemType:n},element:t,removePriorValues:e}),rc({topic:Op,payload:{tournamentId:t.tournamentId}}),{...Ni}}function bM(e){const t=US(e);if(!Object.keys(t).length)return{error:Oi};for(const r of Object.values(t)){const t=RM({tournamentRecord:r,...e});if(t.error)return t}return{...Ni}}function RM({scheduledDates:e=[],removePriorValues:t,tournamentRecord:r,status:n=AI,eventIds:i=[]}){if(!r)return{error:Fi};const a=`${MI}.${EI}`,{timeItem:o}=ng({element:r,itemType:a}),s=o?.itemValue||{[n]:{}};s[n].orderOfPlay={published:!0,scheduledDates:e,eventIds:i};return cg({timeItem:{itemValue:s,itemType:a},element:r,removePriorValues:t}),rc({topic:Ap,payload:{tournamentId:r.tournamentId,scheduledDates:e,eventIds:i}}),{...Ni}}function NM({removePriorValues:e=!0,tournamentRecord:t,status:r=AI,event:n}){if(!t)return{error:Fi};if(!n)return{error:Ua};const i=`${MI}.${EI}`,{timeItem:a}=ag({itemType:i,event:n}),o=a?.itemValue||{[r]:{}};delete o[r].structureIds,delete o[r].drawDetails,delete o[r].drawIds;return pg({event:n,timeItem:{itemValue:o,itemType:i},removePriorValues:e}),GT({statusObject:{structureIds:void 0,drawIds:void 0,seeding:void 0},removePriorValues:e,status:r,event:n}),rc({topic:Ep,payload:{tournamentId:t.tournamentId,eventId:n.eventId}}),{eventId:n.eventId,...Ni}}var MM=Object.freeze({__proto__:null,publishEvent:$T,publishEventSeeding:TM,publishOrderOfPlay:bM,setEventDisplay:gP,unPublishEvent:NM,unPublishEventSeeding:PM,unPublishOrderOfPlay:DM});function AM({tournamentRecord:e,status:t=AI}){const r=`${MI}.${EI}`;return og({tournamentRecord:e,itemType:r})?.timeItem?.itemValue?.[t]}function EM({tournamentRecord:e,policyDefinitions:t}){if(!e)return{error:Fi};const r=e.events||[],n=e?.participants||[],{tournamentInfo:i}=MN({tournamentRecord:e}),{venues:a}=_T({tournamentRecord:e});return{allEventData:{tournamentInfo:i,venuesData:a,eventsData:r.map((r=>{const{eventId:i}=r,a=(({eventId:e,eventName:t,eventType:r,eventLevel:n,surfaceCategory:i,matchUpFormat:a,category:o,gender:s,startDate:c,endDate:u,ballType:d,discipline:p})=>({eventId:e,eventName:t,eventType:r,eventLevel:n,surfaceCategory:i,matchUpFormat:a,category:o,gender:s,startDate:c,endDate:u,ballType:d,discipline:p}))(r),o=QU({tournamentRecord:e,event:r}).scheduleTiming,s=(r.drawDefinitions||[]).map((a=>{const s=(({drawId:e,drawName:t,matchUpFormat:r,updatedAt:n})=>({matchUpFormat:r,updatedAt:n,drawName:t,drawId:e}))(a),{abandonedMatchUps:c,completedMatchUps:u,upcomingMatchUps:d,pendingMatchUps:p}=Cm({requireParticipants:!0,tournamentParticipants:n,context:{eventId:i},policyDefinitions:t,tournamentRecord:e,inContext:!0,scheduleTiming:o,drawDefinition:a,event:r});return{drawInfo:s,matchUps:{abandonedMatchUps:c,completedMatchUps:u,upcomingMatchUps:d,pendingMatchUps:p}}})),c=jT({event:r});return Object.assign(a,{drawsData:s,publish:c}),a}))}}}function CM(e){const{tournamentParticipants:t=[],includePositionAssignments:r,policyDefinitions:n,tournamentRecord:i,inContext:a=!0,usePublishState:o,drawDefinition:c,publishStatus:u,noDeepCopy:d,sortConfig:p,context:l,event:m}=e;if(!c)return{error:Li};const f=(({matchUpFormat:e,updatedAt:t,drawType:r,drawName:n,drawId:i})=>({matchUpFormat:e,updatedAt:t,drawName:n,drawType:r,drawId:i}))(c);let h,g;const{allStructuresLinked:I,sourceStructureIds:U,hasDrawFeedProfile:y,structureGroups:S}=Fn({drawDefinition:c});if(!I)return{error:ga};let v=!1,T=!1;const P=S.map((d=>{const I={},S=d.map((e=>{const{structure:t}=w({drawDefinition:c,structureId:e}),{seedAssignments:r}=Y({drawDefinition:c,structure:t});return t?.stage===qp&&1===t.stageSequence&&(h=r),t?.stage===$p&&1===t.stageSequence&&(g=r),t})).sort(((e,t)=>V(e,t,p))).map((r=>{if(!r)return;const d=r?.structureId;let p=[];r.stage&&[qp,Wp,zp].includes(r.stage)&&(p=h),r?.stage===$p&&(p=g);const{matchUps:S,roundMatchUps:P,roundProfile:D}=J({seedAssignments:r?.seedAssignments?.length?void 0:p,context:{drawId:f.drawId,...l},tournamentParticipants:t,policyDefinitions:n,tournamentRecord:i,usePublishState:o,publishStatus:u,drawDefinition:c,inContext:a,structure:r,event:m}),{positionAssignments:w}=Q({structure:r});let b=w?.filter(ft(vu)).map((e=>{T=!0;const{drawPosition:t,participantId:r}=e,{extension:n}=s({element:e,name:Di});return n&&{drawPosition:t,participantId:r,participantResult:n.value}})).filter((e=>e?.participantResult));if(!b?.length&&S.length&&e.allParticipantResults){const{subOrderMap:e}=Cn({positionAssignments:w}),t=On({matchUpFormat:r.matchUpFormat,policyDefinitions:n,subOrderMap:e,matchUps:S});b=w?.map((e=>{const{drawPosition:r,participantId:n}=e;return n&&t.participantResults?.[n]&&{participantResult:t.participantResults[n],participantId:n,drawPosition:r}})).filter((e=>e?.participantResult))}const R=r?(({stageSequence:e,structureName:t,structureType:r,matchUpFormat:n,stage:i})=>({stageSequence:e,structureName:t,structureType:r,matchUpFormat:n,stage:i}))(r):{};R.sourceStructureIds=U[d],R.hasDrawFeedProfile=y[d],R.positionAssignments=w,R.structureActive=S.reduce(((e,t)=>{const r=[Vm,Lm,jm,zm,Km,$m,Gm,qm].includes(t.matchUpStatus);return e||r||!!t.winningSide||!!t.score?.scoreStringSide1}),!1);const N=S.reduce(((e,t)=>e&&[xm,Vm,zm,Km,jm,km].includes(t.matchUpStatus)),!!S.length);return R.structureCompleted=N,I[d]=N,R.structureActive&&(v=!0),{...R,participantResults:b,seedAssignments:p,roundMatchUps:P,roundProfile:D,structureId:d}}));return S.forEach((e=>{r||delete e.positionAssignments,e.sourceStructuresComplete=e.sourceStructureIds?.every((e=>I[e]))})),S})).flat();return f.drawActive=v,f.participantPlacements=T,f.drawGenerated=P?.reduce(((e,t)=>e||!!t?.roundMatchUps),!1),f.drawCompleted=P?.reduce(((e,t)=>e&&t.structureCompleted),!0),{structures:d?P:L(P,!1,!0),drawInfo:d?f:L(f,!1,!0),...Ni}}var OM=Object.freeze({__proto__:null,bulkUpdatePublishedEventIds:lD,getAllEventData:EM,getCourtInfo:Sb,getDrawData:CM,getEventData:qT,getEventPublishStatus:jT,getPublishState:RS,getTournamentPublishStatus:AM,getVenueData:vb}),FM=Object.freeze({__proto__:null,bulkUpdatePublishedEventIds:lD,getAllEventData:EM,getCourtInfo:Sb,getDrawData:CM,getEventData:qT,getEventPublishStatus:jT,getPublishState:RS,getTournamentPublishStatus:AM,getVenueData:vb,mutate:MM,publishEvent:$T,publishEventSeeding:TM,publishOrderOfPlay:bM,query:OM,setEventDisplay:gP,unPublishEvent:NM,unPublishEventSeeding:PM,unPublishOrderOfPlay:DM});function kM({tournamentRecord:e,categoryName:t,categoryType:r}){if(!e)return{error:Fi};const{appliedPolicies:n}=Oh({tournamentRecord:e}),i=n?.[ad];return(i?.matchUpFormats||[]).filter((({categoryNames:e,categoryTypes:n})=>!t&&!n||t&&e?.includes(t)||r&&n?.includes(r)))}function _M({tournamentRecord:e,categoryName:t,categoryType:r}){if(!e)return{error:Fi};const{appliedPolicies:n}=Oh({tournamentRecord:e}),i=n?.[cd];return(i?.allowedDrawTypes||[]).filter((({categoryNames:e,categoryTypes:n})=>!t&&!n||t&&e?.includes(t)||r&&n?.includes(r)))}function xM({tournamentRecord:e}){if(!e)return{error:Fi};const t=(e?.participants??[]).reduce(((e,t)=>{const{participantId:r}=t;return(t.penalties??[]).forEach((t=>{const{penaltyId:n}=t||{};e[n]?e[n].participants.push(r):e[n]={...t,participantIds:[r]}})),e}),{});return{penalties:Object.values(t)}}function LM({tournamentRecords:e}){if("object"!=typeof e||!Object.keys(e).length)return{error:Oi};const t=[];for(const r of Object.values(e)){const{penalties:e}=xM({tournamentRecord:r});t.push(...e??[])}return{penalties:t}}function VM({tournamentRecord:e,participantFilters:t}){if(!e)return{error:Fi};let r=e.participants||[];t&&(r=ES({participants:r,participantFilters:t,tournamentRecord:e}));const n={};return r.forEach((e=>{e.person&&(e=>{if(e.person){const{personId:t}=e.person;n[t]?n[t].participantIds.push(e.participantId):n[t]={...e.person,participantIds:[e.participantId]}}})(e)})),{tournamentPersons:Object.values(n)}}function BM(e){const t=e.participants?.filter((({participantType:e})=>e===ym)),r=2===t?.length,n=1===e.events?.length&&e.events[0],i=1===n?.drawDefinitions?.length&&n.drawDefinitions[0],a=1===i?.structures?.length&&i.structures[0],o=2===a?.positionAssignments?.length;return!!(n.tieFormat&&r&&o)}function jM({tournamentRecord:e}){if(!e)return{error:Fi};const{drawsAnalysis:t}=kI({tournamentRecord:e}),r={isDual:BM(e),drawsAnalysis:t};return{...Ni,analysis:r}}var GM=Object.freeze({__proto__:null,analyzeDraws:kI,analyzeTournament:jM,getAllowedDrawTypes:_M,getAllowedMatchUpFormats:kM,getAppliedPolicies:Oh,getCompetitionDateRange:AN,getCompetitionPenalties:LM,getPolicyDefinitions:Fh,getTournamentInfo:MN,getTournamentPenalties:xM,getTournamentPersons:VM,getTournamentStructures:dh,getTournamentTimeItem:og});function qM(e){if(!e)return{};const t=[],r=e.tieFormatName,n=e.collectionDefinitions?.map((e=>{const{matchUpType:r,matchUpFormat:n,matchUpCount:i,category:a,gender:o}=e;t.includes(n)||t.push(n);const s=a?.ageCategoryCode;return[i,r===ff?"D":"S",s,n,o].join(";")})).join("|");return{tieFormatName:e&&r||"UNNAMED",matchUpFormats:t,tieFormatDesc:n}}function $M({considerations:e={},descendant:t,ancestor:r}){const n={},i={},{matchUpFormats:a,tieFormatDesc:o}=qM(t),{matchUpFormats:s,tieFormatDesc:c}=qM(r),u=jd((a??[]).filter((e=>!(s??[]).includes(e))).concat((s??[]).filter((e=>!(a??[]).includes(e))))),d=!(!e?.collectionName||t.collectionDefinitions.map((({collectionName:e})=>e)).join("|")===r.collectionDefinitions.map((({collectionName:e})=>e)).join("|")),p=!(!e?.collectionOrder||t.collectionDefinitions.map((({collectionOrder:e})=>e)).join("|")===r.collectionDefinitions.map((({collectionOrder:e})=>e)).join("|")),l=Object.assign({},...(t?.collectionDefinitions||[]).map((e=>({[e.collectionId]:e})))),m=Object.assign({},...(r?.collectionDefinitions||[]).map((e=>({[e.collectionId]:e}))));n.collectionIds=Zd(Object.keys(l),Object.keys(m)),i.collectionIds=Zd(Object.keys(m),Object.keys(l)),n.collectionsValue=WM(l),i.collectionsValue=WM(m),n.groupsCount=r?.collectionGroups?.length??(0-(t?.collectionGroups?.length??0)||0),i.groupsCount=n.groupsCount?-1*n.groupsCount:0;const f=n.collectionsValue.totalValue-i.collectionsValue.totalValue,h=n.collectionsValue.totalMatchUps-i.collectionsValue.totalMatchUps,g=i.collectionsValue.assignmentValues.length!==n.collectionsValue.assignmentValues.length,I=i.collectionsValue.assignmentValues.some(((e,t)=>{const r=n.collectionsValue.assignmentValues[t];return!r||(e.valueKey!==r.valueKey||(e.value!==r.value||!!Array.isArray(e.value)&&e.value.every(((e,t)=>r.value[t]===e))))})),U=d||p||c!==o||g||I||0!==f,y=[...i.collectionsValue.invalidValues,...n.collectionsValue.invalidValues],S=y.length&&y;return{matchUpFormatDifferences:u,matchUpCountDifference:h,descendantDifferences:n,ancestorDifferences:i,orderDifference:p,valueDifference:f,nameDifference:d,descendantDesc:o,ancestorDesc:c,...Ni,different:U,invalid:S}}function WM(e){const t=[],r=[];let n=0;return{totalValue:Object.keys(e).sort(bS).reduce(((i,a)=>{const o=e[a],{collectionValueProfiles:s,collectionValue:c,matchUpCount:u,matchUpValue:d,scoreValue:p,setValue:l}=o,m={collectionValueProfiles:s,collectionValue:c,matchUpValue:d,scoreValue:p,setValue:l},f=Object.keys(m).filter((e=>![void 0,null].includes(m[e])));1!==f.length&&t.push({collectionId:a});const h=f[0];if(h){const e="collectionValueProfiles"===h?Object.values(s):m[h];r.push({valueKey:h,value:e})}return n+=u,s?i+s.reduce(((e,t)=>e+t.value),0):u?Vd(d)?i+d*u:Vd(p)?i+p*u:Vd(l)?i+l*u:i+c:i}),0),totalMatchUps:n,invalidValues:t,assignmentValues:r}}function HM({tournamentRecord:e,drawDefinition:t,structureId:r,matchUpId:n,structure:i,eventId:a,drawId:o,event:s}){if(!e)return{error:Fi};if(!(o||s||r||n))return pd({result:{error:Za},stack:"getTieFormat"});a&&!s&&(s=e.events?.find((e=>e.eventId===a)));const c=LD({tournamentRecord:e,drawDefinition:t,matchUpId:n,drawId:o,event:s});if(n&&c?.error)return c;if(!t&&c?.drawDefinition&&(t=c?.drawDefinition),!(i=i??c?.structure)&&r&&!n){if(!t)return{error:ra};const e=Om({drawDefinition:t,structureId:r});if(e.error)return e;i=e.structure}const u=(i?.tieFormat||i?.tieFormatId)&&Og({structure:i,drawDefinition:t,event:s})?.tieFormat,d=(t?.tieFormat||t?.tieFormatId)&&Og({drawDefinition:t,event:s})?.tieFormat,p=Og({event:s})?.tieFormat,l=Og({matchUp:c?.matchUp,drawDefinition:t,structure:i,event:s})?.tieFormat;return{...Ni,matchUp:c?.matchUp,structureDefaultTieFormat:QS(u),eventDefaultTieFormat:QS(p),drawDefaultTieFormat:QS(d),tieFormat:QS(l),structure:i}}var zM=Object.freeze({__proto__:null,compareTieFormats:$M,getTieFormat:HM,tieFormatGenderValidityCheck:ZS,validateCollectionDefinition:dv});function YM(e){const{scheduleDates:t=[],tournamentRecords:r,periodLength:n=30}=e??{};if("object"!=typeof r)return{error:ki};if(!Array.isArray(t))return{error:ys};if(!t.every(bc))return{error:io};const i=[];let a=0;const o={},{schedulingProfile:s}=LT({tournamentRecords:r});if(!s)return{issues:i,...Ni};const{matchUps:c}=SS({nextMatchUps:!0,tournamentRecords:r});for(const e of s){const{scheduleDate:s,venues:u=[]}=e;if(!t?.length||t.includes(s))for(const e of u||[])if(e){const{rounds:t}=e,u=[],{orderedMatchUpIds:d,scheduledRoundsDetails:p}=mR({tournamentRecords:r,periodLength:n,matchUps:c,rounds:t}),{matchUpDependencies:l}=TS({tournamentRecords:r,matchUps:c}),m=e=>{let t;return p?.find(((r,n)=>{const i=r.matchUpIds.includes(e);return i&&(t=n),i})),t};if(d?.forEach(((e,t)=>{const r=Jd(d.slice(t+1),l?.[e]?.matchUpIds||[]);r.length&&u.push({matchUpId:e,shouldBeAfter:r})})),u.length){a+=u.length;const e=u.map((({matchUpId:e,shouldBeAfter:t})=>{const r=m(e),n=jd(t.map(m));return o[s]||(o[s]={}),o[s][r]||(o[s][r]=[]),n.forEach((e=>{o[s][r].includes(e)||o[s][r].push(e)})),{matchUpId:e,matchUpRoundIndex:r,earlierRoundIndices:n,shouldBeAfter:t}}));i.push(...e)}}}const u={matchUpIdShouldBeAfter:Object.assign({},...i.map((e=>{const{matchUpId:t,shouldBeAfter:r,earlierRoundIndices:n}=e;return{[t]:{earlierRoundIndices:n,shouldBeAfter:r}}})))};return{issuesCount:a,profileIssues:u,roundIndexShouldBeAfter:o,...Ni}}var QM=Object.freeze({__proto__:null,getPersonRequests:LR,getScheduledRoundsDetails:mR,getSchedulingProfile:LT,getSchedulingProfileIssues:YM});function KM({tournamentRecord:e,venueId:t,venueIds:r}){if(!e)return{error:Fi};return{courts:(e.venues||[]).filter((e=>t?e.venueId===t:!r||r.includes(e.venueId))).map((e=>{const{venueId:t}=e,r=Jc(e.courts||[]);return r.forEach((e=>Object.assign(e,{venueId:t}))),r})).flat()}}var JM=Object.freeze({__proto__:null,getCompetitionVenues:xT,getCourts:KM,getVenuesAndCourts:_T,publicFindVenue:Ib}),ZM=Object.freeze({__proto__:null,allCompetitionMatchUps:SS,allDrawMatchUps:zU,allEventMatchUps:KU,allPlayoffPositionsFilled:mh,allTournamentMatchUps:yS,analyzeDraws:kI,analyzeMatchUp:zb,analyzeTournament:jM,bulkUpdatePublishedEventIds:lD,calculateWinCriteria:Eb,categoryCanContain:nv,checkMatchUpIsComplete:Rb,checkValidEntries:BS,compareTieFormats:$M,competitionScheduleMatchUps:eb,credits:function(){return"\n This project would not have been possible without the generous input and patience\n of tournament organizers and directors who worked with early versions of CourtHive/TMX.\n\n Thanks to Pavel, Ivan, Mladen, Zdenko, Antonia, Jakov, Kreso, Barry, Jeff, Bobby... to name just a few. \n\n The project would not have even begun without the support of Miro, or the introduction by Sretchko.\n The project would not have succeeded without the enthusiasm of Randy and Bruce.\n Thanks to serendipity and Luca and the ensuing TODS conversations with ITF.\n Thanks to Scott and Jake for sanity checks, suggestions, and camaraderie.\n Thanks to Zoran for inspiring the async support and getting into the weeds with subscriptions.\n Thanks to Dave for backing the conversion of TMX 1.x source into the factory repository.\n Thanks to Vuk and Pavle and Rich and Chris and Deepa for the direct engagement with the APIs.\n Thanks to Joe for repeatedly challenging me and the many pointers to useful tooling.\n Thanks to Shannon for the validation of the approach from his deep domain experience.\n Thanks to Nikola for the ongoing camaraderie and explorations of what we can do with TODS.\n\n And a special thanks to my family for putting up with the long days and weeks and months of coding\n and conversations at all hours.\n "},drawMatchUps:Yb,eventMatchUps:Jw,filterParticipants:ES,findDrawDefinition:fy,findExtension:Wl,getAllDrawMatchUps:Em,getAllowedDrawTypes:_M,getAllowedMatchUpFormats:kM,getAppliedPolicies:Oh,getAssignedParticipantIds:oy,getAvailablePlayoffProfiles:ny,getCategoryAgeDetails:tv,getCheckedInParticipantIds:xD,getCompetitionDateRange:AN,getCompetitionMatchUps:Xw,getCompetitionParticipants:hM,getCompetitionPenalties:LM,getCompetitionVenues:xT,getCourts:KM,getDrawDefinitionTimeItem:ig,getDrawParticipantRepresentativeIds:ZU,getDrawTypeCoercion:kS,getEligibleVoluntaryConsolationParticipants:JU,getEntriesAndSeedsCount:MU,getEvent:hD,getEventMatchUpFormatTiming:Ww,getEventProperties:mD,getEventStructures:uh,getEventTimeItem:ag,getEvents:fD,getFlightProfile:bU,getLinkedTournamentIds:js,getMatchUpCompetitiveProfile:ob,getMatchUpContextIds:Cb,getMatchUpDailyLimits:bb,getMatchUpDailyLimitsUpdate:Hw,getMatchUpDependencies:TS,getMatchUpFormat:Ob,getMatchUpFormatTiming:Vw,getMatchUpFormatTimingUpdate:Pw,getMatchUpScheduleDetails:wb,getMatchUpType:qb,getMatchUpsStats:Fb,getMaxEntryPosition:AT,getModifiedMatchUpFormatTiming:JT,getPairedParticipant:yT,getParticipantEventDetails:gM,getParticipantIdFinishingPositions:ay,getParticipantMembership:IM,getParticipantScaleItem:EU,getParticipantSchedules:UM,getParticipantSignInStatus:yM,getParticipantTimeItem:sg,getParticipants:OS,getPersonRequests:LR,getPolicyDefinitions:Fh,getPositionAssignments:_S,getPositionsPlayedOff:XU,getPredictiveAccuracy:Nb,getRoundMatchUps:Cf,getRounds:Gb,getScaleValues:Hu,getScaledEntries:CU,getScheduledRoundsDetails:mR,getSchedulingProfile:LT,getSchedulingProfileIssues:YM,getSeedingThresholds:Gh,getSeedsCount:NU,getStructureSeedAssignments:oh,getTeamLineUp:LS,getTieFormat:HM,getTimeItem:ng,getTournamentIds:su,getTournamentInfo:MN,getTournamentPenalties:xM,getTournamentPersons:VM,getTournamentStructures:dh,getTournamentTimeItem:og,getValidGroupSizes:Dg,getVenuesAndCourts:_T,isAdHoc:jS,isCompletedStructure:lh,isValidForQualifying:xS,isValidMatchUpFormat:uv,matchUpActions:hS,participantScaleItem:AU,participantScheduledMatchUps:Yw,positionActions:FS,publicFindVenue:Ib,tallyParticipantResults:gU,tieFormatGenderValidityCheck:ZS,tournamentMatchUps:Zw,validMatchUp:Af,validMatchUps:Ef,validateCollectionDefinition:dv,validateLineUp:vU});function XM({participant:e,eventType:t}){const r=e?.person?.personId,n=e?.person?.personOtherIds?.[0],i=e?.person?.tennisId,a=e?.ratings?.[t]?.find((({scaleName:e})=>e===Sv)),o=a?.scaleValue,{wtnRating:s,confidence:c}=o||{};return{timeStamp:a?.scaleDate,personOtherId:n,confidence:c,wtnRating:s,personId:r,tennisId:i}}function eA({eventType:e,matchUps:t,eventId:r,drawId:n}){const i={},a=t.filter((e=>r?e.eventId===r:e.drawId===n)).reduce(((e,t)=>((e=>{const t=e?.matchUpFormat;t&&(i[t]||(i[t]=0),i[t]+=1)})(t),(t.sides??[]).flatMap((e=>(e?.participant?.individualParticipants||[e?.participant]).filter(Boolean))).forEach((t=>e[t.participantId]=t)),e)),{}),o=Object.values(a),s=o.map((t=>XM({participant:t,eventType:e}))).filter((({wtnRating:e})=>e)),c=(o.length-s.length)/o.length*100,u=s.reduce(((e,t)=>{const{wtnRating:r,confidence:n}=t;return e.totalWTN+=r,e.totalConfidence+=n,e}),{totalWTN:0,totalConfidence:0}),d=s?.length?u.totalWTN/s.length:0,p=s?.length?u.totalConfidence/s.length:0,l=Object.values(i).reduce(((e,t)=>e+(t||0)),0);return{matchUpFormatCounts:i,matchUpsCount:l,avgConfidence:p,pctNoRating:c,avgWTN:d}}var tA=Object.freeze({__proto__:null,getEntryStatusReports:function({tournamentRecord:e}){if(!e)return{error:Fi};const t=e.tournamentId,{participantMap:r}=OS({withScaleValues:!0,withEvents:!0,withSeeding:!0,tournamentRecord:e,withDraws:!0}),n=(yS({matchUpFilters:{matchUpTypes:[lf,ff]},tournamentRecord:e}).matchUps??[]).flatMap((({sides:e,matchUpType:t})=>e?.flatMap((e=>t===ff?e?.participant?.individualParticipantIds:e?.participant?.participantId||e.participantId)).filter(Boolean))).filter(Boolean),i=[],a={},o={},s={};let c=0;const u=({id:e,entry:n,eventId:o,eventType:s})=>{const{qualifyingSeeding:c,mainSeeding:u,entryStatus:d,entryStage:p,drawId:l}=n;a[e]||(a[e]=[]);const{participant:m,events:f}=r?.[e]??{},h=XM({participant:m,eventType:s}),g=f?.[o]?.ranking;d===Ry&&i.push(e),a[e].push({participantType:m?.participantType,participantId:e,tournamentId:t,eventType:s,eventId:o,drawId:l,entryStatus:d,entryStage:p,...h,ranking:g,mainSeeding:u,qualifyingSeeding:c})};for(const i of e.events??[]){const e={},a=t=>{e[t]||(e[t]={count:0}),e[t].count+=1},{drawDefinitions:d=[],eventType:p,eventId:l}=i,m=d.flatMap((e=>{const{drawId:t,entries:n}=e;c+=1;const i=(e.structures??[]).filter((({stage:e,stageSequence:t})=>e===qp&&1===t||e===$p)).flatMap((({positionAssignments:e})=>e)).filter(Boolean).map((({participantId:e})=>e));return n?.filter((({participantId:e})=>i.includes(e))).map((e=>{const{participantId:n,entryStatus:i,entryStage:o}=e;a(i);const s=r?.[n]?.draws?.[t]?.seedAssignments?.[qp],c=r?.[n]?.draws?.[t]?.seedAssignments?.[$p];return{qualifyingSeeding:c,participantId:n,mainSeeding:s,entryStatus:i,entryStage:o,drawId:t}}))})),f=e=>{const t=e.participantId,i=r?.[t].participant.individualParticipantIds?.filter((e=>n.includes(e)));return t&&{[t]:{individualParticipantIds:i}}};p===Hf?(()=>{const e=Object.assign({},...m.map(f).filter(Boolean));m.forEach((t=>{e[t.participantId].individualParticipantIds.forEach((e=>{u({id:e,eventType:p,eventId:l,entry:t})}))}))})():m.forEach((e=>{u({id:e?.participantId,eventType:p,eventId:l,entry:e})}));const h=Object.values(e).reduce(((e,t)=>e+t.count),0);Object.keys(e).forEach((t=>{e[t].pct=e[t].count/h*100})),s[l]={tournamentId:t,eventId:l,entries:m,entryStatuses:e};const g=Object.assign({},...um.flatMap((t=>[{[t+"_count"]:e[t]?.count},{[t+"_pct"]:e[t]?.pct}])));o[l]={tournamentId:t,eventId:l,...g}}const d=Object.values(r??{}).filter((({participant:{participantType:e,participantRole:t}})=>e===gm&&t===Zv)),p=d.filter((({participant:e})=>!n.includes(e.participantId))).map((({participant:e})=>e.participantId)),l={nonParticipatingEntriesCount:p.length,individualParticipantsCount:d.length,eventsCount:Object.values(s).length,nonParticipatingParticipantIds:p,drawDefinitionsCount:c,tournamentId:t};return{entryStatusReports:Object.values(o).flat(),participantEntryReports:Object.values(a).flat(),eventReports:Object.values(s).flat(),withDrawnParticipantIds:i,tournamentEntryReport:l}},getParticipantStats:function({withCompetitiveProfiles:e,opponentParticipantId:t,withIndividualStats:r,teamParticipantId:n,tournamentRecord:i,withScaleValues:o,tallyPolicy:s,matchUps:u}){if(!i)return{error:Fi};if(u&&!Array.isArray(u))return{error:ja};if(u=u??Lt({tournamentRecord:i,participantsProfile:o?{withScaleValues:o}:void 0}).matchUps,!u?.length)return{error:Va};const d=[];t&&d.push(t),n&&d.push(n);const p=d.length?{participantIds:d}:{participantTypes:[hm]},l=pt({participantFilters:p,tournamentRecord:i}).participants??[];if(!l.every((({participantType:e})=>e===hm)))return{error:Uo};d.length||d.push(...l.map(v));const m=new Map,f=new Map,h=new Map,g=new Map,I=(e,t="")=>f.get(e)||f.set(e,{participantName:t,participantId:e,competitorIds:[],competitiveness:{},matchUpStatuses:{},tiebreaks:[0,0],matchUps:[0,0],points:[0,0],games:[0,0],sets:[0,0]})&&f.get(e);for(const e of l){const{participantId:t,individualParticipantIds:r}=e;g.set(t,r??[]),I(t,e.participantName)}if(n&&!g.get(n))return a({result:{error:wo},context:{teamParticipantId:n}});if(t&&!g.get(t))return a({result:{error:wo},context:{opponentParticipantId:t}});const U=[],y=e=>{const i=[[],[]];for(const t of e){const e=t.participant;if(e?.participantName){m.set(e.participantId,{participantName:e.participantName,ratings:e.ratings});const t=f.get(e.participantId);t&&(t.participantName=e.participantName)}}const a=({side:e,individualParticipantIds:t})=>e.participantId&&(!t?.length||t.includes(e.participantId))&&[e.participantId]||e.participant?.individualParticipantIds?.length&&(!t?.length||c(t,e.participant?.individualParticipantIds).length===e.participant?.individualParticipantIds?.length)&&e.participant.individualParticipantIds;if(g.size){const o=(t,n)=>{for(const o of e){if(!o.participant)continue;const e=a({individualParticipantIds:n,side:o});if(e?.length){const n=o.sideNumber;if(!n)continue;const a=[t];r&&a.push(...e),i[n-1]=a;const s=f.get(t);for(const t of e.filter(Boolean))s&&!s.competitorIds.includes(t)&&s.competitorIds.push(t)}}};if(n){(!t||e.every((e=>e.participant&&(a({individualParticipantIds:g.get(n),side:e})||a({individualParticipantIds:g.get(t),side:e})))))&&o(n,g.get(n))}else for(const[e,t]of g)o(e,t)}else if(r)for(const t of e){if(!t.participant)continue;const e=a({individualParticipantIds:[],side:t}),r=t.sideNumber;r&&(i[r-1]=e)}return i};for(const t of u){if(!mt(t))return{error:ja};const{matchUpStatus:r,matchUpFormat:n,matchUpType:i,winningSide:a,score:o,sides:c}=t;if(!c||!o||i===gf||r===xm)continue;const u=y(c);if(!u.filter(Boolean).length)continue;const d=e&&a&&Te({matchUp:t})?.competitiveness;U.push(t);const p=kn({matchUpStatus:r,matchUpFormat:n,tallyPolicy:s,winningSide:a,score:o}),l=_n({matchUpStatus:r,matchUpFormat:n,tallyPolicy:s,winningSide:a,score:o}),{pointsTally:f,tiebreaksTally:h}=xn({matchUpFormat:n,score:o});u.forEach(((e,t)=>{for(const n of e){const e=m.get(n)?.participantName,i=I(n,e);if(i){const e=(e,t)=>t.forEach(((t,r)=>i[e][r]+=t)),n=t?[...h].reverse():h,o=t?[...f].reverse():f,s=t?[...l].reverse():l,c=t?[...p].reverse():p;if(e("tiebreaks",n),e("points",o),e("games",s),e("sets",c),a){const e=a-1===t?0:1;i.matchUps[e]+=1}if(d){const e=d.toLowerCase();i.competitiveness[e]||(i.competitiveness[e]=[0,0]),i.competitiveness[e][t]+=1}if(r){const e=r.toLowerCase();i.matchUpStatuses[e]||(i.matchUpStatuses[e]=0),i.matchUpStatuses[e]+=1}}}}))}const S=["tiebreaks","matchUps","points","games","sets"],T=["competitive","routine","decisive"],P=new Map,D=(e,t)=>(e??0)+(t??0);for(const[e,t]of f.entries()){for(const r of S){const n=t[r].reduce(D);if(n){const i=t[r][0]/n,a=`${r}Ratio`,o=parseFloat(i.toFixed(2));t[a]=o,h.set(e,!0),P.has(a)||P.set(a,[]),P.get(a)?.push(o)}}for(const e of T){const r=t.competitiveness?.[e]?.reduce(D);if(r){const n=t.competitiveness[e][0]/r,i=`${e}Ratio`,a=parseFloat(n.toFixed(2));t[i]=a}}}if(!n){const e=(e,t)=>t-e;for(const t of f.values())for(const r of S){const n=`${r}Ratio`;if("number"==typeof t[n]){const i=P.get(n)?.sort(e).indexOf(t[n]);if("number"==typeof i&&i>=0){t[`${r}Rank`]=i+1}}}}const w={relevantMatchUps:U,...Ni};return n?(w.teamStats=f.get(n),t&&(w.opponentStats=f.get(t))):w.participatingTeamsCount=h.size,w.allParticipantStats=[...f.values()],w},getStructureReports:function({firstFlightOnly:e=!0,extensionProfiles:t,tournamentRecord:r}){if(!r)return{error:_i};const n={},i=Object.assign({},...(t??[]).map((({name:e,label:t,accessor:n})=>{const i=Wl({element:r,name:e})?.extension?.value;return{[t||e]:n?Xc({element:i,accessor:n})?.value:i}}))),a=r?.tournamentId,o=yS({participantsProfile:{withScaleValues:!0},tournamentRecord:r}).matchUps??[],s=e=>{const t=ng({itemType:pp,itemSubTypes:[fu],element:{timeItems:e}})?.timeItem;return t?.itemValue?.scaleBasis},c=r?.events?.flatMap((({timeItems:t,drawDefinitions:r=[],extensions:c,eventType:u,eventId:d,category:p})=>{const l=c?.find((e=>e.name===pi)),m=l?.value?.flights?.map((e=>({[e.drawId]:e.flightNumber}))),f=m&&Object.assign({},...m),h=c?.find((e=>e.name===ui))?.value?.length||0,g=Object.values(f),I=f&&Math.min(...g),U=s(t);return n[d]={totalPositionManipulations:0,maxPositionManipulations:0,generatedDrawsCount:0,drawDeletionsCount:h,seedingBasis:U?JSON.stringify(U):void 0,tournamentId:a,eventId:d},r.filter((t=>!e||!m||f[t.drawId]===I)).flatMap((e=>{const{matchUpFormat:t,tieFormat:r,timeItems:c,extensions:l,structures:m,drawType:h,drawId:g}=e,{matchUpFormatCounts:I,matchUpsCount:y,avgConfidence:S,pctNoRating:v,avgWTN:T}=eA({eventType:u,matchUps:o,drawId:g}),P=s(c)||U,D=function({extensions:e}){return e?.find((({name:e})=>e===ni))?.value?.slice(1)}({extensions:l}),w=D?.length||0;return n[d].totalPositionManipulations+=w,n[d].generatedDrawsCount+=1,w>n[d].maxPositionManipulations&&(n[d].maxPositionManipulations=w),m?.filter((e=>1===e.stageSequence&&[$p,qp,Wp,zp].includes(e.stage))).map((e=>{const n=[qp,zp].includes(e.stage)?o.find((t=>t.structureId===e.structureId&&1===t.finishingRound&&t.winningSide)):void 0,s=n?.sides?.find((e=>e.sideNumber===n.winningSide)),c=s?.participant,l=c?.participantType===hm&&c.participantId,m=c?.participantType===Um?c.individualParticipants:[],U=XM({participant:m?.[0]||c,eventType:u}),{personId:w,personOtherId:b,tennisId:R,confidence:N,wtnRating:M}=U||{},A=XM({participant:m?.[1],eventType:u}),{personId:E,personOtherId:C,tennisId:O,confidence:F,wtnRating:k}=A||{},{ageCategoryCode:_,categoryName:x,subType:L}=p??{},V=e.matchUpFormat||t,B=(I[V]||0)/y*100,{tieFormatName:j,tieFormatDesc:G}=qM(r),{tieFormatName:q,tieFormatDesc:$}=qM(e.tieFormat),W=G===$,H=!W&&q,z=e.tieFormat&&!W&&$,Y=D?.filter((t=>t.structureId===e.structureId))?.length||0;return{...i,tournamentId:a,eventId:d,structureId:e.structureId,drawId:g,eventType:u,category:L,categoryName:x,ageCategoryCode:_,flightNumber:f[g],drawType:h,stage:e.stage,seedingBasis:P?JSON.stringify(P):void 0,winningPersonId:w,winningPersonOtherId:b,winningPersonTennisId:R,winningPersonWTNrating:M,winningPersonWTNconfidence:N,winningPerson2Id:E,winningPerson2OtherId:C,winningPerson2TennisId:O,winningPerson2WTNrating:k,winningPerson2WTNconfidence:F,winningTeamId:l,positionManipulations:Y,pctNoRating:v,matchUpFormat:V,pctInitialMatchUpFormat:B,matchUpsCount:y,drawTieFormatName:j,drawTieFormatDesc:G,tieFormatName:H,tieFormatDesc:z,avgConfidence:S,avgWTN:T}}))}))}));return{eventStructureReports:Object.values(n),structureReports:c}},getVenuesReport:function({ignoreDisabled:e=!0,tournamentRecords:t,tournamentId:r,venueIds:n=[],dates:i=[]}){if(!Array.isArray(i))return{error:ys,dates:i};if(!Array.isArray(n))return{error:ys,venueIds:n};if(!(t&&Object.keys(t).filter((e=>!r||e===r))||[]).length)return{error:Oi};if(!i.every(bc))return{error:io};const a=_T({tournamentRecords:t,ignoreDisabled:e,dates:i});if(a.error)return a;const o=a?.venues?.filter((({venueId:e})=>!n?.length||n.includes(e))),s=a.courts?.reduce(((e,t)=>(t.dateAvailability?.forEach((t=>{const r=t.date;e.includes(r)||e.push(r)})),e)),[]).filter((e=>!i.length||i.includes(e))),c={venueIds:o?.map((({venueId:e})=>e))},{matchUps:u}=SS({afterRecoveryTimes:!0,tournamentRecords:t,matchUpFilters:c}),d=o?.map((e=>function(e,t,r){const{venueId:n,courts:i,venueName:a}=t,o={};return e.forEach((e=>{let t=0,a=0,s=0;for(const r of i){const n=r.dateAvailability.find((t=>t.date===e)),i=n&&RD({courtDate:n}).timeSlots,a=i?.reduce(((e,t)=>{const{startTime:r,endTime:n}=t;return e+(kc(n)-kc(r))}),0);a&&(s+=1),t+=a}const c=r.filter((({schedule:t})=>t.venueId===n&&Qc(e,t.scheduledDate)));c.forEach((({schedule:e})=>{const t=xc(e.scheduledTime),r=kc(Hc(t,e.averageMinutes))-kc(t);a+=r}));const u=t?(a/t*100).toFixed(2):"100";o[e]={scheduledMatchUpsCount:c.length,availableCourts:s,availableMinutes:t,scheduledMinutes:a,percentUtilization:u}})),{venueId:n,venueName:a,venueReport:o}}(s,e,u)));return{venuesReport:d}}});function rA({calculateStartTimeFromCourts:e=!0,defaultRecoveryMinutes:t=0,averageMatchUpMinutes:r=90,remainingScheduleTimes:n,clearScheduleDates:i,tournamentRecords:a,periodLength:o,scheduleDate:s,startTime:c,venueIds:u,endTime:d}){if("object"!=typeof a||!Object.keys(a).length)return{error:Oi};o=o??UR({recoveryMinutes:t,averageMatchUpMinutes:r});const{courts:p,venues:l}=_T({dates:[s],ignoreDisabled:!0,tournamentRecords:a}),m=p?.filter((e=>!u||u.includes(e.venueId)));c||(c=m?.reduce(((e,t)=>{const r=t.dateAvailability?.find((e=>!e.date||Qc(s,e.date))),n=r?.startTime??t.startTime;return n&&(!e||kc(n)<kc(e))?n:e}),void 0)),d||(d=m?.reduce(((e,t)=>{const r=t.dateAvailability?.find((e=>!e.date||Qc(s,e.date))),n=r?.endTime??t.endTime;return n&&(!e||kc(n)>kc(e))?n:e}),void 0));const f=Object.values(a),h=Object.assign({},...f.map((e=>(e.events??[]).map((t=>{const{scheduleTiming:r}=QU({tournamentRecord:e,event:t});return{[t.eventId]:{event:t,scheduleTiming:r}}})))).flat()),g=eb({sortDateMatchUps:!1,tournamentRecords:a,matchUpFilters:{scheduledDate:s,venueIds:u}}),I=g?.dateMatchUps??[],U=g?.completedMatchUps??[],y=[];y.push(...I),y.push(...U);const S={averageTimes:[{minutes:{default:r}}],recoveryTimes:[{minutes:{default:t}}]},v=y?.map((({eventId:e,schedule:t,matchUpFormat:r})=>{const{event:n,scheduleTiming:i}=h[e],a=n?.eventType,s={...i,defaultTiming:S,matchUpFormat:r},{averageMinutes:c,recoveryMinutes:u}=Bw({eventType:a,timingDetails:s}),{courtId:d,venueId:p}=t,l=xc(t.scheduledTime),m=Hc(l,c);return{recoveryMinutes:u,averageMinutes:c,periodLength:o,startTime:l,endTime:m,courtId:d,venueId:p}})),T={calculateStartTimeFromCourts:e,remainingScheduleTimes:n,averageMatchUpMinutes:r,date:s,clearScheduleDates:i,periodLength:o,startTime:c,endTime:d,bookings:v,courts:m},{scheduleTimes:P}=AD(T);return{venueId:1===u?.length&&u[0]||1===l?.length&&l[0].venueId||void 0,scheduleTimes:P,dateScheduledMatchUpIds:y.map(Nd)}}function nA(e){const t=uy(e,[{[gu]:!0}]);if(t.error)return t;const{removePriorValues:r,tournamentRecords:n,tournamentId:i,courtDayDate:a,matchUpId:o,courtId:s,drawId:c}=e,u=n[i];if(!u)return{error:Fi};const{drawDefinition:d,event:p}=my({tournamentRecord:u,drawId:c});if(!d)return{error:Li};const l=xv({drawDefinition:d,event:p,matchUpId:o});if(l.error)return l;if(l?.matchUp?.matchUpType===gf){const{itemValue:e}=cb({timeItems:l.matchUp.timeItems??[],itemType:cI}),t=s&&e.filter((e=>e.courtId!==s));return GD({duplicateValues:!1,removePriorValues:r,tournamentRecord:u,drawDefinition:d,matchUpId:o,timeItem:{itemType:cI,itemValue:t}})}return wR({tournamentRecord:u,drawDefinition:d,courtDayDate:a,courtId:"",matchUpId:o})}function iA({scheduleCompletedMatchUps:e,tournamentRecords:t,scheduledDate:r,matchUps:n}){if(!Ef(n))return{error:ys};if(n.some((({hasContext:e})=>!e)))return{info:"matchUps must have { inContext: true, nextMatchUps: true }",error:ss};let i=eb({courtCompletedMatchUps:!0,withCourtGridRows:!0,minCourtGridRows:10,tournamentRecords:t,matchUpFilters:{localPerspective:!0,scheduledDate:r}});if(i.error)return i;const{rows:a}=i,o=[],s=e=>[(e.sides||[]).map((e=>[e.participantId,e.participant?.individualParticipantIds])),(e.potentialParticipants||[]).flat().map((e=>[e.participantId,e.individualParticipantIds]))].flat(1/0).filter(Boolean),c=a?.reduce(((e,t)=>{const r=[],n=[];Object.values(t).forEach((e=>{if(ru(e)&&(e.matchUpId&&(r.push(e.matchUpId),o.push(e)),e.sides)){const t=s(e);n.push(...t)}}));const i=Object.values(t).filter((e=>ru(e)&&!e.matchUpId));return e.concat({matchUpIds:r,availableCourts:i,rowId:t.rowId,participantIds:n})}),[]);n.filter((({matchUpStatus:t})=>t&&t!==xm&&(e||!rf.includes(t)))).sort(vS);const u=TS({matchUps:n.concat(o),includeParticipantDependencies:!0,tournamentRecords:t}).matchUpDependencies,d=[],p=[];for(;n.length&&c.length;){const e=c.shift(),t=[];for(;n.length&&e.availableCourts.length;){const r=n.concat(t).map((e=>e.matchUpId)),i=n.shift(),a=i?.matchUpId,o=a&&u[a].matchUpIds.concat(u[a].dependentMatchUpIds),c=a&&r.some((e=>u[a].matchUpIds.includes(e))),l=a&&p.some((e=>u[a].dependentMatchUpIds.includes(e))),m=e.matchUpIds.some((e=>o.includes(e))),f=s(i),h=e.participantIds.some((e=>f.includes(e)));if(!i||m||c||h||l)i&&t.push(i);else{const t=e.availableCourts.shift();Object.assign(i.schedule,t.schedule),Object.assign(t,i),d.push(i),e.participantIds.push(...f),e.matchUpIds.push(a)}}n.push(...t),p.push(...e.matchUpIds)}const l=d.map((({matchUpId:e,tournamentId:t,schedule:n,drawId:i})=>({tournamentId:t,matchUpId:e,drawId:i,schedule:{...n,scheduledDate:r}})));i=_R({tournamentRecords:t,matchUpDetails:l});const m=n;return{...i,scheduled:d,notScheduled:m}}function aA(e){const{courtDayDate:t}=e,r=uy(e,[{courtAssignments:!0,[$u]:ju,[qu]:Za},{[gu]:!0}]);if(r.error)return r;const n=e.courtAssignments.reduce(((e,t)=>{const{tournamentId:r}=t;return e[r]||(e[r]=[]),e[r].push(t),e}),{});let i;return Object.keys(n).every((r=>{const a=e[gu][r];if(!a)return i={error:Fi},!1;const o=n[r].reduce(((e,t)=>{const{drawId:r}=t;return e[r]||(e[r]=[]),e[r].push(t),e}),{});Object.keys(o).every((e=>{const{drawDefinition:r}=ly({tournamentRecord:a,drawId:e});return r?(o[e].every((e=>{const{matchUpId:n,courtId:o}=e,s=wR({tournamentRecord:a,drawDefinition:r,courtDayDate:t,matchUpId:n,courtId:o});if(s.success)return s?.success;i={error:ls}})),!0):(i={error:Li},!1)}))})),i||Ni}function oA(e){const{tournamentRecords:t,allDateMatchUpIds:r=[],averageMatchUpMinutes:n=90,recoveryMinutes:i=0,recoveryMinutesMap:a,matchUpPotentialParticipantIds:o={},individualParticipantProfiles:s={},matchUpNotBeforeTimes:c={},matchUpDailyLimits:u={},checkPotentialRequestConflicts:d=!0,remainingScheduleTimes:p,clearScheduleDates:l,periodLength:m=30,scheduleDate:f,matchUpIds:h,venueIds:g,startTime:I,endTime:U,dryRun:y}=e,S=uy(e,[{[gu]:!0,[wu]:!0},{[Gu]:bc,[qu]:io,scheduleDate:!0},{[Gu]:e=>!e||!isNaN(e),averageMatchUpMinutes:!1,[qu]:ys,recoveryMinutes:!1,periodLength:!1}]);if(S.error)return S;const v=e.competitionMatchUps??SS({nextMatchUps:!0,tournamentRecords:t}).matchUps??[],T=e.matchUpDependencies??TS({includeParticipantDependencies:!0,matchUps:v,tournamentRecords:t}).matchUpDependencies;v.forEach((e=>{e.schedule?.scheduledDate&&Qc(f,Lc(e.schedule.scheduledDate))&&oR({matchUpPotentialParticipantIds:o,matchUpNotBeforeTimes:c,matchUp:e})}));const P=h.map((e=>v.find((t=>t.matchUpId===e)))).filter(Boolean),{venueId:D,scheduleTimes:w,dateScheduledMatchUpIds:b}=rA({tournamentRecords:t,remainingScheduleTimes:p,startTime:xc(I),endTime:xc(U),scheduleDate:Lc(f),averageMatchUpMinutes:n,clearScheduleDates:l,periodLength:m,venueIds:g}),R={},N=[],M={},A={},E={},C=v.filter((({matchUpId:e})=>b?.includes(e)));C.forEach((e=>{hR({matchUpPotentialParticipantIds:o,individualParticipantProfiles:s,matchUp:e,value:1});const t=e.schedule?.scheduledTime;if(t){M[e.matchUpId]=t;const r=a?.[e.matchUpId];cR({recoveryMinutes:r||i,matchUpPotentialParticipantIds:o,individualParticipantProfiles:s,matchUpNotBeforeTimes:c,averageMatchUpMinutes:n,matchUpDependencies:T,scheduleTime:t,matchUp:e})}}));let O=P.filter((e=>{const t=b?.includes(e.matchUpId),r=[xm,jm,Vm,km,zm,Km].includes(e?.matchUpStatus);return!t&&!e.winningSide&&!r}));const{matchUpMap:F,overLimitMatchUpIds:k,participantIdsAtLimit:_}=O.reduce(((e,t)=>{const{drawId:r,tournamentId:n,matchUpType:i}=t,{participantIdsAtLimit:a,relevantParticipantIds:d}=PR({individualParticipantProfiles:s,matchUpPotentialParticipantIds:o,matchUpDailyLimits:u,matchUp:t});return a?.length?(e.overLimitMatchUpIds.push(t.matchUpId),e.participantIdsAtLimit.push(...a),e):(d.forEach((e=>{sR({individualParticipantProfiles:s,participantId:e});const t=s[e].counters;t[i]?t[i]+=1:t[i]=1,t[Mw]?t[Mw]+=1:t[Mw]=1})),e.matchUpMap[n]||(e.matchUpMap[n]={}),e.matchUpMap[n][r]?e.matchUpMap[n][r].push(t):e.matchUpMap[n][r]=[t],oR({matchUpPotentialParticipantIds:o,matchUpNotBeforeTimes:c,matchUp:t}),e)}),{matchUpMap:{},overLimitMatchUpIds:[],participantIdsAtLimit:[]});O=O.filter((({matchUpId:e})=>!k.includes(e)));let x=0;const L=w?.length??0,{personRequests:V}=LR({tournamentRecords:t,requestType:dR});for(;w?.length&&O.length&&x<=L;){x++;const{scheduleTime:e}=w.shift(),t=O.find((t=>{const{matchUpId:u}=t,{dependenciesScheduled:p,remainingDependencies:l}=aR({matchUpScheduleTimes:M,matchUpDependencies:T,allDateMatchUpIds:r,matchUp:t});if(!p)return E[u]||(E[u]=[]),E[u].push({scheduleTime:e,remainingDependencies:l}),!1;const{enoughTime:m}=TR({individualParticipantProfiles:s,matchUpNotBeforeTimes:c,matchUpDependencies:T,scheduleTime:e,matchUp:t});if(!m)return A[u]||(A[u]=[]),A[u].push({scheduleTime:e}),!1;const{conflicts:h}=lR({potentials:d,averageMatchUpMinutes:n,requestConflicts:R,personRequests:V,scheduleTime:e,scheduleDate:f,matchUp:t});if(h?.length)return!1;const g=a?.[t.matchUpId];return cR({recoveryMinutes:g||i,matchUpPotentialParticipantIds:o,individualParticipantProfiles:s,matchUpNotBeforeTimes:c,averageMatchUpMinutes:n,matchUpDependencies:T,scheduleTime:e,matchUp:t}),M[t.matchUpId]=e,!0}));O=O.filter((({matchUpId:e})=>e!==t?.matchUpId)),t||N.push(e)}O.forEach((e=>{hR({individualParticipantProfiles:s,matchUpPotentialParticipantIds:o,value:-1,matchUp:e})}));const B=[];Object.keys(F).forEach((e=>{const r=t[e];r&&Object.keys(F[e]).forEach((n=>{const{drawDefinition:i}=my({tournamentRecord:r,drawId:n});if(i){F[e][n].forEach((({matchUpId:e})=>{const n=M[e];if(n){const a=n.split(":").map(Yc).join(":"),o=`${Lc(f)}T${a}`;if(y)B.push(e);else{rR({drawDefinition:i,matchUpId:e,scheduledTime:o}).success&&B.push(e),D&&iR({tournamentRecords:t,tournamentRecord:r,drawDefinition:i,matchUpId:e,venueId:D})}}}))}}))}));const j=bd(O);return{...Ni,requestConflicts:Object.values(R),remainingScheduleTimes:w?.map((({scheduleTime:e})=>e)),individualParticipantProfiles:s,matchUpNotBeforeTimes:c,participantIdsAtLimit:_,skippedScheduleTimes:N,overLimitMatchUpIds:k,scheduledMatchUpIds:B,noTimeMatchUpIds:j,recoveryTimeDeferred:A,dependencyDeferred:E}}function sA({tournamentRecords:e,matchUps:t}){if(!Ef(t))return{error:Va};if(t.some((({matchUpId:e,hasContext:t})=>e&&!t)))return{info:"matchUps must have { inContext: true, nextMatchUps: true }",error:ss};const r=Qd(1,Math.max(...t.map((({schedule:e})=>e?.courtOrder||1)).map((e=>Ed(e))))+1).map((e=>t.filter((t=>Ed(t.schedule?.courtOrder)===e)))),n={},i={},a={};r.flat().filter(Boolean).sort(vS).forEach((({schedule:e})=>delete e[xw]));const o=TS({includeParticipantDependencies:!0,tournamentRecords:e,drawIds:jd(t.map((({drawId:e})=>e)))}).matchUpDependencies,s=r.map(((e,t)=>e.reduce(((e,r)=>{if(!r.matchUpId)return e;const{matchUpId:s,winnerMatchUpId:c,loserMatchUpId:u,schedule:d,sides:p,potentialParticipants:l}=r,m=d?.courtId;n[s]=t,i[m]=[],e.matchUpIds.push(s),a[s]=r;const f=o[s].matchUpIds;f.length&&e.sourceMatchUpIds.push(...f);const h=p?.map((e=>[e.participant?.individualParticipantIds,e.participantId])).flat().filter(Boolean)??[],g=l?.flat().map((({individualParticipantIds:e,participantId:t})=>[e,t])).flat().filter(Boolean)||[];return e.participantIds.push(...g,...h),c&&e.targetMatchUpIds.push(c),u&&e.targetMatchUpIds.push(u),e}),{sourceMatchUpIds:[],targetMatchUpIds:[],participantIds:[],matchUpIds:[]}))),c=s.map((()=>[])),u=(e,t,r,o)=>{if(!a[e].schedule[xw]){a[e].schedule[xw]=t,a[e].schedule[Cw]=o,c[n[e]].push({matchUpId:e,issueType:r,issueIds:o,issue:t});const s=a[e].schedule.courtId;i[s]||(i[s]=[]),i[s].push({matchUpId:e,issue:t,issueType:r,issueIds:o})}};return s.forEach(((e,t)=>{const r=t?s[t-1]:void 0,n=s.slice(t+1),i={},c=$d(e.participantIds),d=Object.keys(c).filter((e=>c[e]>1)),p=e.matchUpIds.filter((e=>o[e].participantIds.some((e=>d.includes(e)))));p.forEach((e=>{i[e]||(i[e]={}),i[e][Ow]||(i[e][Ow]=p.filter((t=>t!==e)))}));const l=r&&e.participantIds.filter((e=>r.participantIds.includes(e)));l&&l.forEach((t=>{const n=e.matchUpIds.concat(r.matchUpIds).filter((e=>o[e].participantIds.includes(t)));n.forEach((e=>{i[e]||(i[e]={}),i[e][Fw]||(i[e][Fw]=n.filter((t=>t!==e)))}))})),e.matchUpIds.forEach((t=>{const s=o[t].matchUpIds;for(const e of n){const r=e.matchUpIds.filter((e=>s.includes(e)));r?.length&&(r.forEach((e=>u(e,kw,Ew,[t]))),u(t,kw,Ew,r))}if(i[t]?.[Ow]&&u(t,Ow,Aw,i[t][Ow]),e.sourceMatchUpIds.includes(t)){const r=e.matchUpIds.filter((e=>o[e].matchUpIds.includes(t)));u(t,Ow,Ew,r),e.matchUpIds.filter((e=>o[e].matchUpIds.includes(t))).forEach((e=>u(e,Ow,Ew,[t])))}const c=r?.matchUpIds?.filter((e=>{return r=e,o[t].sources.reduce(((e,t,n)=>t.includes(r)&&n+1||e),0)>1;var r}));if(c?.length&&(u(t,_w,Ew,c),c.forEach((e=>u(e,_w,Ew,[t])))),i[t]?.[Fw]&&u(t,Fw,Aw,i[t][Fw]),r?.targetMatchUpIds?.includes(t)){const e=a[t].schedule.courtId,n=s.filter((e=>r.matchUpIds.includes(e)));n.some((t=>a[t].schedule.courtId===e))||(n.forEach((e=>u(e,Fw,Ew,[t]))),u(t,Fw,Ew,n))}}))})),{courtIssues:i,rowIssues:c}}function cA(e){const t="reorderUpcomingMatchUps",{tournamentRecords:r}=e;if("object"!=typeof r||!Object.keys(r).length)return pd({result:{error:Oi},stack:t});const{matchUpsContextIds:n,firstToLast:i}=e;if(!n)return pd({result:{error:Za},stack:t});const a=n?.length;if(!a)return{...Ni};let o=0;return n.forEach(((e,t)=>{const{tournamentId:s,drawId:c,matchUpId:u}=e;let d=t+(i?-1:1);d<0&&(d=a-1),d===a&&(d=0);const p=function({tournamentId:e,scheduledTime:t,matchUpId:n,drawId:i}){const a=r[e],{drawDefinition:o}=my({tournamentRecord:a,drawId:i});return o?rR({drawDefinition:o,scheduledTime:t,matchUpId:n}):{error:Bi}}({tournamentId:s,scheduledTime:n[d].schedule.scheduledTime,matchUpId:u,drawId:c});if(!p.success)return p;o++})),o===a?Ni:pd({result:{error:ds},stack:t})}function uA(e){const{scheduleChange:t,matchUpIds:r,dryRun:n}=e;if(!r||!Array.isArray(r))return{error:xa};if("object"!=typeof t)return{error:ys};const i=bn(e),a=[];let o=[];for(const e of Object.values(i)){const i=dA({tournamentRecord:e,scheduleChange:t,matchUpIds:r,dryRun:n});if(i.error)return i;Array.isArray(i.notRescheduled)&&o.push(...i.notRescheduled);const s=D(i.notRescheduled),c=[];i.rescheduled?.forEach((e=>{const{matchUpId:t}=e;s.includes(t)&&c.push(t),a.push(e)})),c.length&&(o=i?.notRescheduled?.filter((({matchUpId:e})=>!c.includes(e)))||[])}const s=!(!a.length||o.length);return{...Ni,rescheduled:a,notRescheduled:o,allRescheduled:s}}function dA({tournamentRecord:e,scheduleChange:t,matchUpIds:r,dryRun:n}){if(!e)return{error:Fi};if(!r||!Array.isArray(r))return{error:xa};if("object"!=typeof t)return{error:ys};const i=[],a=[],{minutesChange:o,daysChange:s}=t;if(!o&&!s)return{...Ni};if(o&&isNaN(o))return{error:ys};if(s&&isNaN(s))return{error:ys};const{matchUps:c}=Lt({matchUpFilters:{matchUpIds:r},tournamentRecord:e}),u=c?.filter((e=>zw({schedule:e.schedule}))).filter((e=>(({matchUpStatus:e})=>!rf.includes(e))({matchUpStatus:e.matchUpStatus})));if(!u?.length)return{...Ni};const{tournamentInfo:d}=Ar({tournamentRecord:e}),{startDate:p,endDate:l}=d,m=u?.reduce(((e,t)=>{const{matchUpId:r,drawId:n}=t;return e[n]?e[n].push(r):e[n]=[r],e}),{});for(const t of Object.keys(m)){const c=Ln({tournamentRecord:e,drawId:t});if(c.error)return c;const d=c.drawDefinition,f=m[t].filter((e=>r.includes(e)));for(const e of f)if(e&&d){const t=u.find((t=>t.matchUpId===e)),r=t?.schedule,{scheduledTime:c,scheduledDate:m}=r;let f,h,g;if(!f&&s&&m){g=Vc(Lc(m),s),f=new Date(g)<new Date(p)||new Date(g)>new Date(l)}if(o&&c){const e=Lc(c),t=kc(xc(c))+o;if(f=t<0||t>1440,!f){const t=Hc(c,o),r=e&&g||m===e&&e;h=r?`${r}T${t}`:t}}if(f)a.push(e);else{if(!n){if(h){const t=rR({scheduledTime:h,drawDefinition:d,matchUpId:e});if(t.error)return t}if(g){const t=NR({scheduledDate:g,drawDefinition:d,matchUpId:e});if(t.error)return t}}(h||g)&&i.push(e)}}}const f=Lt({matchUpFilters:{matchUpIds:r},tournamentRecord:e}).matchUps??[],h=f.filter((({matchUpId:e})=>i.includes(e))),g=f.filter((({matchUpId:e})=>a.includes(e))),I=h.length&&!g.length;return{...Ni,rescheduled:h,notRescheduled:g,allRescheduled:I}}function pA(e){const t="matchUpScheduleChange",{tournamentRecords:r}=e;if("object"!=typeof r||!Object.keys(r).length)return{error:Oi};const{sourceMatchUpContextIds:n,targetMatchUpContextIds:i,sourceCourtId:a,targetCourtId:o,courtDayDate:s}=e||{},{drawId:c,matchUpId:u,tournamentId:d}=n||{},{drawId:p,matchUpId:l,tournamentId:m}=i||{};if(!u&&!l)return pd({result:{error:Za},stack:t});const{matchUps:f}=SS({matchUpFilters:{matchUpIds:[u,l].filter(Boolean),drawIds:[c,p].filter(Boolean)},tournamentRecords:e.tournamentRecords}),h=f?.find((({matchUpId:e})=>e===u)),g=f?.find((({matchUpId:e})=>e===l));let I=0;if(o&&u&&!l){const e=U({tournamentId:d,matchUpId:u,courtId:o,matchUp:h,drawId:c,tournamentRecords:r,sourceCourtId:a,courtDayDate:s});if(e?.success&&I++,e.error)return pd({result:e,stack:t})}else{if(!(a&&o&&u&&l))return{error:Za};{const e=U({tournamentId:d,matchUpId:u,courtId:o,matchUp:h,drawId:c,tournamentRecords:r,sourceCourtId:a,courtDayDate:s});if(e.success&&I++,e.error)return pd({result:e,stack:t,info:"source"});const n=U({tournamentId:m,sourceCourtId:o,matchUpId:l,matchUp:g,courtId:a,drawId:p,tournamentRecords:r,courtDayDate:s});if(n.success&&I++,n.error)return pd({result:n,stack:t,info:"target"})}}return I?Ni:pd({result:{error:ps},stack:t});function U(e){const{tournamentRecords:t,tournamentId:r,matchUp:n,drawId:i}=e,a=t[r],{drawDefinition:o}=my({tournamentRecord:a,drawId:i});return n.matchUpType===If?function({removePriorValues:e,tournamentRecords:t,tournamentRecord:r,drawDefinition:n,sourceCourtId:i,courtDayDate:a,matchUpId:o,matchUp:s,courtId:c}){const u=[c].concat(s.schedule.allocatedCourts.map((({courtId:e})=>e)).filter((e=>e!==i)));return DR({removePriorValues:e,tournamentRecords:t,tournamentRecord:r,drawDefinition:n,courtDayDate:a,matchUpId:o,courtIds:u})}({...e,tournamentRecord:a,drawDefinition:o}):wR({...e,tournamentRecord:a,drawDefinition:o})}}function lA({scheduleAttributes:e=[cI,uI,sI,pI,mI,fI,II,gI,hI],tournamentRecord:t,drawDefinition:r,matchUpId:n}){const i=r?zU({matchUpFilters:{matchUpIds:[n]},inContext:!1,drawDefinition:r}).matchUps?.[0]:yS({matchUpFilters:{matchUpIds:[n]},tournamentRecord:t,inContext:!1}).matchUps?.[0];if(!i)return{error:La};const a=(i.timeItems??[]).filter((t=>t?.itemType&&!e.includes(t?.itemType)));return i.timeItems=a,Vp({tournamentId:t.tournamentId,context:"clearMatchUpSchedule",drawDefinition:r,matchUp:i}),{...Ni}}function mA(e){const{tournamentRecord:t,tournamentId:r,dailyLimits:n}=e,i=e.tournamentRecords||t&&{[t.tournamentId]:t}||{};if("object"!=typeof i||!Object.keys(i).length)return{error:Oi};if("object"!=typeof n)return{error:gs};const a=Object.keys(i).filter((e=>!r||r===e));if(r&&!a.includes(r))return{error:ys};for(const e of a){const t=i[e],r=o({element:t,extension:{name:Si,value:{dailyLimits:n}}});if(r.error)return r}return{...Ni}}var fA=Object.freeze({__proto__:null,addMatchUpCourtOrder:MR,addMatchUpEndTime:CR,addMatchUpOfficial:AR,addMatchUpResumeTime:FR,addMatchUpScheduleItems:RR,addMatchUpScheduledDate:NR,addMatchUpScheduledTime:rR,addMatchUpStartTime:ER,addMatchUpStopTime:OR,addSchedulingProfileRound:EN,allocateTeamMatchUpCourts:DR,assignMatchUpCourt:wR,assignMatchUpVenue:iR,bulkRescheduleMatchUps:uA,bulkScheduleMatchUps:_R,bulkScheduleTournamentMatchUps:kR,bulkUpdateCourtAssignments:aA,calculateScheduleTimes:rA,clearMatchUpSchedule:lA,clearScheduledMatchUps:jR,courtGridRows:Kw,findMatchUpFormatTiming:kb,findVenue:gb,generateBookings:yR,generateVirtualCourts:VR,getProfileRounds:Vb,matchUpScheduleChange:pA,modifyMatchUpFormatTiming:ZT,proAutoSchedule:iA,proConflicts:sA,publicFindCourt:yb,removeEventMatchUpFormatTiming:rP,removeMatchUpCourtAssignment:nA,reorderUpcomingMatchUps:cA,scheduleMatchUps:oA,scheduleProfileRounds:qR,setMatchUpDailyLimits:mA,setSchedulingProfile:VT,toggleParticipantCheckInState:WD,validateSchedulingProfile:FT}),hA=Object.freeze({__proto__:null,addMatchUpCourtOrder:MR,addMatchUpEndTime:CR,addMatchUpOfficial:AR,addMatchUpResumeTime:FR,addMatchUpScheduleItems:RR,addMatchUpScheduledDate:NR,addMatchUpScheduledTime:rR,addMatchUpStartTime:ER,addMatchUpStopTime:OR,addSchedulingProfileRound:EN,allocateTeamMatchUpCourts:DR,assignMatchUpCourt:wR,assignMatchUpVenue:iR,bulkRescheduleMatchUps:uA,bulkScheduleMatchUps:_R,bulkScheduleTournamentMatchUps:kR,bulkUpdateCourtAssignments:aA,calculateScheduleTimes:rA,clearMatchUpSchedule:lA,clearScheduledMatchUps:jR,courtGridRows:Kw,findMatchUpFormatTiming:kb,findVenue:gb,generateBookings:yR,generateVirtualCourts:VR,getPersonRequests:LR,getProfileRounds:Vb,getScheduledRoundsDetails:mR,getSchedulingProfile:LT,getSchedulingProfileIssues:YM,matchUpScheduleChange:pA,modifyMatchUpFormatTiming:ZT,mutate:fA,proAutoSchedule:iA,proConflicts:sA,publicFindCourt:yb,query:QM,removeEventMatchUpFormatTiming:rP,removeMatchUpCourtAssignment:nA,reorderUpcomingMatchUps:cA,scheduleMatchUps:oA,scheduleProfileRounds:qR,setMatchUpDailyLimits:mA,setSchedulingProfile:VT,toggleParticipantCheckInState:WD,validateSchedulingProfile:FT});function gA({collectionDefinition:e,groupValueNumbers:t,groupValueGroups:r,sideTieValues:n,tieMatchUps:i}){const a=i.filter((t=>t.collectionId===e.collectionId)),o=[0,0];let s=[0,0];const c=a.every((e=>rf.includes(e.matchUpStatus))),{collectionValueProfiles:u,collectionGroupNumber:d,collectionValue:p,matchUpValue:l,winCriteria:m,scoreValue:f,setValue:h}=e,g=d&&t.includes(d),I=[0,0];if(a.forEach((e=>{e.winningSide&&(I[e.winningSide-1]+=1)})),Vd(l)?a.forEach((e=>{e.winningSide&&(o[e.winningSide-1]+=l)})):Vd(h)?a.forEach((e=>{e.score?.sets?.forEach((e=>{e.winningSide&&(o[e.winningSide-1]+=h)}))})):Vd(f)?a.forEach((e=>{e.score?.sets?.forEach((t=>{const{side1TiebreakScore:r=0,side2TiebreakScore:n=0,side1Score:i=0,side2Score:a=0}=t;(e.matchUpStatus===Vm||e.winningSide||t.winningSide)&&(i||a?(o[0]+=i,o[1]+=a):(r||n)&&t.winningSide&&(o[t.winningSide-1]+=1))}))})):Array.isArray(u)&&a.forEach((t=>{if(t.winningSide){const r=t.collectionPosition,n=function({collectionDefinition:e,collectionPosition:t}){const r=e.collectionValueProfiles||[],n=r?.find((e=>e.collectionPosition===t));return n?.matchUpValue}({collectionDefinition:e,collectionPosition:r});Vd(n)&&(o[t.winningSide-1]+=n)}})),Vd(p)){let t;if(m?.aggregateValue)c&&(Vd(l||h||f)&&o[0]!==o[1]?t=o[0]>o[1]?1:2:I[0]!==I[1]&&(t=I[0]>I[1]?1:2));else if(m?.valueGoal)t=o.reduce(((e,t,r)=>t>=m.valueGoal?r+1:e),0);else{const r=Math.floor(e.matchUpCount/2)+1;t=I.reduce(((e,t,n)=>t>=r?n+1:e),0)}t&&(g?r[d].values[t-1]+=p:s[t-1]+=p)}else g?(r[d].values[0]+=o[0]||0,r[d].values[1]+=o[1]||0):s=o;g?(r[d].sideWins[0]+=I[0]||0,r[d].sideWins[1]+=I[1]||0,r[d].allGroupMatchUpsCompleted=r[d].allGroupMatchUpsCompleted&&c,r[d].matchUpsCount+=a.length):s.forEach(((e,t)=>n[t]+=e||0))}const IA="\\d+-\\d+",UA="\\d+-\\d+\\(\\d+\\)",yA="\\[\\d+-\\d+\\]",SA=new RegExp(`(${IA}),`,"g"),vA=new RegExp(`(${UA}),`,"g"),TA=[IA,UA,yA,"\\d+-\\d+\\(\\d+-\\d+\\)"],PA=["0","1","2","00","01","10","11","002","012","102","112","000","001","010","100","011","101","110","111","002","012","102","112","0002","0012","0102","1002","0112","1012","1102","1112","3","03","13","013","103"].map((e=>{const t=e.split("").map((e=>TA[e])).join(" ");return new RegExp(`^${t}$`)}));function DA(e){return!e||PA.some((t=>t.test(e)))}function wA(e){return/^\(\d+\)$/.test(e)||/^\(\d+$/.test(e)}function bA(e){const t=(r=e,r?.split("-").join("").split("/").join(""));var r;if(/^\d+$/.test(t)&&2===t.length){const e=t.split("");return 1===Math.abs(e.reduce(((e,t)=>+e-+t)))}return!1}function RA(e,t){const r=[e.slice(t,t+2),t?e.slice(0,1):e.slice(2)].map((e=>parseInt(e.join(""))));t&&r.reverse();const n=r;if(Math.abs(n.reduce(((e,t)=>+e-+t)))>=2)return n.join("-")}function NA(e){return 2===e.length?e.split("").join("-"):([", ",",","/"," "].forEach((t=>e=e.split(t).join("-"))),e=e.replace(/-{2,}/,"-"))}function MA(e){return e.startsWith("(")&&e.endsWith(")")}function AA(e){if(!/^[\d-]+(\(\d\))*$/.test(e))return e;const t=Kd("-",e.split(""));if(!t.length)return e;const r=e.split("-"),n=!(r.length%2),i=!!(t.length%2);if(n&&i&&t.length>r.length/2){t.filter(((e,t)=>t%2)).forEach((t=>{e=e.substring(0,t)+" "+e.substring(t+1)}))}return e}function EA({score:e}){const t=e.split(""),r=[];let n;const i=()=>n=[void 0,void 0,void 0],a=()=>{let e=`${n[0]}-${n[1]}`;return n[2]&&(e+=` (${n[2]})`),i(),n.push(n),e};i();const o=()=>void 0!==n[0]&&void 0!==n[1]&&Math.abs(parseInt(n[0])-parseInt(n[1]));for(;t.length;){const e=t.shift(),i=kd(e)&&parseInt(e),s=void 0!==n[0]&&void 0!==n[1];if(kd(i)){if(void 0===n[0]){n[0]=i;continue}if(void 0===n[1]&&(n[1]=i,o())){r.push(a()),n=[void 0,void 0];continue}if(s&&1===t.length&&kd(t[0])){const e=t.pop();n[0]=n[0].toString()+n[1].toString(),n[1]=e,r.push(a()),n=[void 0,void 0]}s&&o()}}return{sets:r}}function CA(e){const t=e.indexOf("1"),r=e.split(""),n=r.every((e=>!isNaN(e)));if(n&&3===e.length&&0===t){const e=RA(r,t);if(e)return e}if(n&&7===e.length&&t>3){const e=RA(r.slice(4),t-4);if(e)return`${r[0]}-${r[1]} ${r[2]}-${r[3]} ${e}`}}function OA(e){let{score:t}=e;const{applied:r,matchUpStatus:n}=e,i=t?.toString().split(""),a=i?.every((e=>kd(e))),o=e=>Math.abs(e[0]-e[1]);if("number"==typeof t||a){t=t.toString().toLowerCase(),a&&(t=i.join(""));const e=a?i.map((e=>parseInt(e))):t.split("").map((e=>parseInt(e)));if(EA({score:t}),e.length,3===t.length&&1===o(e.slice(0,2))){const[n,i,a]=e;t=`${n}-${i}(${a})`,r.push("numericTiebreakPattern1")}else if(3===t.length&&1===e[0]){const[n,i,a]=e;t=`[${n}${i}-${a}]`,r.push("numericTiebreakPattern2")}else if(4===t.length&&1===o(e.slice(0,2))&&"987654".split("").includes(e[0].toString())){const[n,i,a,o]=e;t=`${n}-${i}(${Math.min(a,o)})`,r.push("numericTiebreakPattern3")}else if(4===t.length&&1===e[0]&&1===e[2]){const[n,i,a,o]=e;t=`[${n}${i}-${a}${o}]`,r.push("bigSuper")}else if(4===t.length){const[n,i,a,o]=e;t=`${n}${i} ${a}${o}`,r.push("split4")}else if(5===t.length&&1===o(e.slice(0,2))){const[n,i,a,o,s]=e;t=`${n}-${i}(${a}) ${o}-${s}`,r.push("numericTiebreakPattern4")}else if(5===t.length&&1===o(e.slice(3))){const[n,i,a,o,s]=e;t=`${n}-${i} ${a}-${o}(${s})`,r.push("numericTiebreakPattern5")}else if(7===e.length)if(o(e.slice(0,2))>1&&o(e.slice(2,4))>1&&1===e[4]){const[n,i,a,o,s,c,u]=e;t=`${n}-${i} ${a}-${o} [${s}${c}-${u}]`,r.push("numericTiebreakPattern6")}else if(1===o(e.slice(0,2))&&o(e.slice(3,5))>1&&o(e.slice(5,7))>1){const[n,i,a,o,s,c,u]=e;t=`${n}-${i}(${a}) ${o}-${s} ${c}-${u}`,r.push("numericTiebreakPattern7")}else if(o(e.slice(0,2))>1&&1===o(e.slice(2,4))&&o(e.slice(5,7))>1){const[n,i,a,o,s,c,u]=e;t=`${n}-${i} ${a}-${o}(${s}) ${c}-${u}`,r.push("numericTiebreakPattern8")}else if(o(e.slice(0,2))>1&&o(e.slice(2,4))>1&&1===o(e.slice(4,6))){const[n,i,a,o,s,c,u]=e;t=`${n}-${i} ${a}-${o} ${s}-${c}(${u})`,r.push("numericTiebreakPattern9")}else t=t.slice(0,2)+" "+t.slice(2,4)+" "+t.slice(4),r.push("numericMatchTiebreakPattern");else if(t.length%2){const e=CA(t);e&&t!==e&&r.push("parsedSuperPattern"),t=e??t}else{const n=ep(t.split(""),2).map((e=>e.join(""))),i=n.map((e=>{const[t,r]=e.split("").map((e=>parseInt(e))),n=t>r?1:2;return Math.abs(t-r)>1&&n||-1*n})),a=i.reduce(((e,t)=>e>0&&t>0),1),o=$d(i),s=$d(i.map((e=>Math.abs(e)))),c=i[0]<0,u=!c&&i[1]<0;if(i[0]>0&&i[1]>0&&i[0]!==i[1])t=[n.slice(0,2).join(" "),n.slice(2).join("-")].join(" "),r.push("numeric3rdSetTiebreakPattern");else if(a)t=n.join(" "),r.push("chunkSplit");else if(6==e.length){if(2==o[1]||2===o[2])if(Object.values(s).includes(3)){const[n,a,o,s,c,u]=e,d=i.reduce(((e,t,r)=>t<0?r:e),void 0);if(0===d){t=`${n}-${a}(${Math.min(o,s)}) ${c}-${u}`,r.push("chunkSplitTiebreak1")}else if(1===d){t=`${n}-${a} ${o}-${s}(${Math.min(c,u)})`,r.push("chunkSplitTiebreak2")}else t=`${n}-${a} ${o}-${s}`,r.push("chunkSplitTrimExtraneous")}else t=n.join(" "),r.push("chunkSplit")}else if(8===e.length){const[r,n,a,o,s,d,p,l]=e;c||u?1===e[5]&&(t=c?`${r}-${n}(${a}) ${o}-${s} [${d}${p}-${l}]`:`${r}-${n} ${a}-${o}(${s}) [${d}${p}-${l}]`):(i[0],i[1])}}}return{score:t,applied:r,matchUpStatus:n}}function FA(e){const t=[0,0],r=[],n=e.split(" "),i=/(\d+)-(\d+)/;n.forEach((e=>{if(i.test(e)){const n=e.match(i).slice(1).map((e=>parseInt(e))),a=n[0]>n[1]?1:n[1]>n[0]&&2;a&&(t[a-1]+=1,r.push(a))}}));const a=t[0]>t[1]?1:t[1]>t[0]&&2,o=t[0]>0&&t[0]===t[1],s=t.reduce(((e,t)=>e+t),0);return{setsWon:t,setsTied:o,setWinners:r,totalSets:s,winningSide:a}}const kA={handleTiebreakSlashSeparation:function({score:e}){const t=new RegExp(/\(\d+\/\d+\)/g),r=e.match(t);for(const t of r||[]){const r=t.replace("/","-");e=e.replace(t,r)}return{score:e}},handleSetSlashSeparation:function({score:e}){return new RegExp(/-\d+\/\d+-/).test(e)&&(e=e.split("/").join(" ")),{score:e}},punctuationAdjustments:function({score:e,applied:t}){e=function(e){const t="[];",r="()",n=t+r,i=[t[0],r[0]],a=Object.assign({},...n.split("").map((e=>({[e]:0}))));let o="";const s=e.split("").map((e=>{const s=n.includes(e)&&e,c=i.includes(s);if(c&&s)return a[s]+=1,o=s,e;if(!c&&s&&o&&s!==o){a[o]-=1;const e=t.includes(o)&&t||r.includes(o)&&r||"",n=e.split("").find((e=>e!==o));if(!e.includes(s))return a[s]||(o=""),n;a[o]||(o="")}return e})).join("");return e!==s?s:e}(e);const r=/\)(\d+)/g;if(r.test(e))for(const t of e.match(r)){const r=t.replace(")",") ");e=e.replace(t,r)}const n=/\(([\d- ]+)\)/,i=(e=(e=e.replace(/\)\//g,") / ")).replace(/\/\)/g,")")).match(/\(([\d- ]+)\)/g);for(const t of i||[]){const[r]=t.match(n).slice(1),i=r.replace(/ /g,"");e=e.replace(t,`(${i})`)}let a=/\(\(\d-\d\)\)/g;if(a.test(e)){const t=e.match(a);t.length&&t.forEach((t=>{const r=t.match(/\((\(\d-\d\))\)/).slice(1)[0];e=e.replace(t,r)}))}if(a=/\(\((\d)\)\)/g,a.test(e)){const t=e.match(a);t.length&&t.forEach((t=>{const r=t.match(/\((\(\d\))\)/).slice(1)[0];e=e.replace(t,r)}))}/(^|\s)6-,/.test(e)&&(e=e.replace(/(^|\s)6-,/g,"6-0,"));const o=new RegExp(/[-,]{2,}/g);e=e.replace(o,"-"),["- "," -"].forEach((t=>{const r=new RegExp(`(\\d+)${t}(\\d+)`,"g"),n=e.match(r);n&&n.forEach((r=>e=e.replace(r,r.split(t).join("-"))))})),/^[(-/,]+$/.test(e)&&(e=""),/\)[-/,]+$/.test(e)&&(e=e.slice(0,e.length-1)),/\d \/\d/.test(e)&&(e=e.replace(/ \//g,"/")),e.includes(" /")&&(e=e.replace(/ \//g," "));const s=/\(\d+, \)/g;if(s.test(e)){e.match(s).forEach((t=>{const[r]=t.match(/\((\d+), \)/).slice(1);2===r.length?e=e.replace(t,`(${r})`):1===r.length&&"6"===r&&(e=e.replace(t,"(6-0)"))}))}const c=/\((\d+)\/\)/g;if(c.test(e)){e.match(c).forEach((t=>{const[r]=t.match(/\((\d+)\/\)/).slice(1);e=2===r.length?e.replace(t,`(${r})`):1===r.length&&"6"===r?e.replace(t,"(6-0)"):e.replace(t,`(${r})`)}))}const u=/\d\/\d\/,/g;if(u.test(e)){e.match(u).forEach((r=>{const[n]=r.match(/(\d\/\d)\/,/).slice(1);e=e.replace(r,`${n},`),t.push("slashComma")}))}const d=/\(\/(\d+)\)/g;if(d.test(e)){e.match(d).forEach((t=>{const[r]=t.match(/\(\/(\d+)\)/).slice(1);e=2===r.length?e.replace(t,`(${r})`):1===r.length&&parseInt(r)<6?e.replace(t,`(6-${r})`):e.replace(t,`(${r})`)}))}let p,l,m,f,h;const g=()=>{h=$d(e.split("")),l=h["("]===(h[")"]||0)+1,p=(h["("]||0)+1===h[")"],m=h["["]===h["]"]+1,f=l&&!m};g();const I=/(\d+-\d+\(\d+)0,/;if(I.test(e)){const[t]=e.match(I).slice(1);e=e.replace(I,t+")")}if(h["("]===h[")"]&&h["("]>1){const t=e.split(")(").join(") (").split(" ");e=t.every(MA)?t.map((e=>{const t=e.slice(1,e.length-1);return t.length>2?t:e})).join(" "):t.join(" ")}g();const U=/[A-Za-z]+/.test(e),y=/\d+/.test(e);if(!U&&!y)return{score:""};if(/^\[.+\]$/.test(e)&&"()/,- ".split("").some((e=>h[e]))&&(e=e.slice(1,e.length-1)),/^\(.+\)$/.test(e)&&1===h["("]&&1===h[")"]&&"[]/,".split("").some((e=>h[e]>1))&&(e=e.slice(1,e.length-1)),e.startsWith("(")&&e.endsWith("))")&&(e=e.slice(1,e.length-1)),h["("]>(h[")"]||0)&&"("===e[e.length-1]&&(e=e.slice(0,e.length-1)+")",g()),1!==h["("]||h[")"]||"("!==e[0]||(e+=")",g()),h["("]>(h[")"]||0)&&"(("===e.slice(0,2)&&(e=e.slice(1)),p){if(/^9\d/.test(e))e="("+e.slice(1);else if("("!==e[0])e="("+e;else{const t=[];let r=0;for(const n of e.split("").reverse())")"===n&&(r?t.push("("):r+=1),"("===n&&(r-=1),t.push(n);t.reverse(),e=t.join("")}g()}if(h[")"]>(h["("]||0)&&")"===e[0]&&(e="("+e.slice(1),g()),f&&(e.endsWith(9)||/\d+0$/.test(e))&&(e=e.slice(0,e.length-1)+")",g()),!f||e.endsWith(")")&&!e.startsWith("((")||(e+=")",g()),f){let t="",r=0;for(const n of e.split(""))"("===n&&(r?t+=")":r+=1),")"===n&&(r-=1),t+=n;e=t}if(g(),m&&!l&&(e+="]"),e.includes("([")&&e.includes("])")&&(e=e.split("([").join("[").split("])").join("]"),g()),/\(\d+0$/.test(e)&&(e=e.slice(0,e.length-1)+")"),g(),1===h[")"]&&!h["("]&&e.endsWith(")")&&(e=e.slice(0,e.length-1)),e.startsWith("(")&&e.endsWith(")")&&1===h["("]&&1===h[")"]&&(e=e.slice(1,e.length-1),g()),/^\([\d ]+.*[\d ]+\)$/.test(e)&&h["("]===h[")"]){const t=e.slice(1,e.length-1);(e=>{const t=e.indexOf("("),r=e.indexOf(")");return t>=0&&r>=0&&t<r})(t)&&(e=t,g())}return{score:e,applied:t}},handleGameSeparation:function({score:e}){const t=new RegExp(/^\d+\/\d+/),r=e.split(" ");r.some((e=>t.test(e)))&&(e=r.map((e=>t.test(e)?e.replace("/","-"):e)).join(" "));const n=/^(\d+), *(\d+)$/;if(n.test(e)){const[t,r]=e.match(n).slice(1);e=[t,r].join("-")}return{score:e}},joinFloatingTiebreak:function({score:e}){if("string"!=typeof e)return{score:e};const t=e=>e?.split("-").join("").split("/").join(""),r=e=>e.split("[").join("(").split("]").join(")");let n=(e=e.split(", ").join(" ")).split(" ");e=n.map((e=>{const t=/^-(\d+)$/;if(t.test(e)){const[r]=e.match(t).slice(1);if(2===r.length)return r.split("").join("-")}return e})).join(" "),n=e.split(" ");const i=n.filter(wA);let a=0,o="";for(const e of i){const r=Kd(e,n).filter((e=>!a||e>a))[0],i=n.slice(a,r-1),s=n[r-1],c=t(s);if(/^\d+$/.test(c)&&2===c.length){const t=c.split(""),n=Math.abs(t.reduce(((e,t)=>+e-+t)));if(1===n){o+=[i.join(" "),[s,e].join("")].join(" "),a=r+1}else if(0===n){const n=Math.max(...t);if([4,5,6,7,8,9].includes(n)){const t=[n,[6,4].includes(n)?n+1:n-1].sort().reverse().join("-");o+=[i.join(" "),[t,e].join("")].join(" "),a=r+1}}}}if(i.length&&o.length){return o=[o,n.slice(a).join(" ")].join(" "),{score:o.trim()}}if(2===n.length&&["(","["].some((e=>n[1].includes(e)))){const e=t(n[0]).split("");if(1===Math.abs(e.reduce(((e,t)=>+e-+t),0)))return n[1]=r(n[1]),{score:n.join("")}}const s=n.map((e=>function(e){return/^\(\d+-\d+\)$/.test(e)||/^\[\d+-\d+\]$/.test(e)}(e)?"bracket":bA(e)&&"set"));if(s.includes("set")&&s.includes("bracket")){let e,t="";return n.forEach(((n,i)=>{"bracket"===s[i]&&"set"===e?(n=r(n),t+=n):t+=` ${n}`,e=s[i]})),{score:t.trim()}}let c;n=e.split(" ");let u=n.map((e=>{const t=new RegExp(/^(\d+)-(\d+)$/);if(t.test(e)){const[r,n]=e.match(t).slice(1),i=Math.abs([r,n].reduce(((e,t)=>+e-+t))),a=Math.max(r,n);if(1===i)return c="tiebreakSet",c;if(i>=2&&a>=7&&"tiebreakSet"===c)return c="tiebreak",c}}));const d=Kd("tiebreak",u);if(d.length){let t="";n.forEach(((e,r)=>{d.includes(r)?t+=`(${e}) `:d.includes(r+1)?t+=`${e}`:t+=`${e} `})),e=t.trim()}const p=/(\d+-\d+)\((\d+)-(\d+)\)$/;if(p.test(e)){const[t,r,n]=e.match(p).slice(1),i=Math.max(r,n)>=10;!bA(t)&&i&&(e=e.replace(p,`${t} [${r}-${n}]`))}return u=[],e=e.split(" ").map((e=>{const t=/^\((.*)\)$/,r=t.test(e),n=(new RegExp(yA).test(e)?"super":new RegExp(UA).test(e)&&"tiebreak")||new RegExp(IA).test(e)&&"standard"||"unknown";return u.push(n),"standard"===n&&r?e.match(t)[1]:e})).join(" "),{score:e}},handleBracketSpacing:function({score:e,applied:t}){return e.includes("( ")&&(t.push("removeParenSpacingAfterOpen"),e=e.split("( ").map((e=>e.trim())).join("(")),e.includes(" )")&&(t.push("removeParenSpacingBeforeClose"),e=e.split(" )").map((e=>e.trim())).join(")")),[SA,vA].forEach((r=>{const n=e.match(r);n?.length&&(n.forEach((t=>{e=e.replace(t,t.slice(0,t.length-1)+" ")})),t.push("setsEndComma"))})),{score:e=e.split(" ").filter(Boolean).map(AA).join(" "),applied:t}},handleSpaceSeparator:function({score:e}){if(e.includes(",")){const t=e.split(",").map((e=>e.trim())),r=e=>/\d \d/.test(e);t.every(r)&&(e=t.map((e=>{const t=/\d+ \d+/g;for(const r of e.match(t)){const[t,n]=r.match(/(\d+) (\d+)/).slice(1);e=e.replace(r,`${t}-${n}`)}return e})).join(" "))}if(e.includes(" ")){const t=e.replace(/[ ,]/g,"");t.split("").every((e=>kd(e)))&&4===t.length&&(e=t)}return{score:e}},separateScoreBlocks:function({score:e,applied:t}){return"string"!=typeof e?{score:e}:{score:e=e.toLowerCase().split(" ").map((e=>{if(/^\d+$/.test(e)&&e.length>2){const r=e.indexOf("1");if(e.length%2){if(3===e.length&&0===r){const n=RA(e.split(""),r);return t.push("getSuper"),n}}else{const{score:r,applied:n}=OA({score:e,applied:[]});r!==e&&(e=r,t.push(...n))}}return e})).join(" "),applied:t}},matchKnownPatterns:function({score:e,applied:t}){for(const r of[".",","," ","/"]){const n=new RegExp(`^(\\d+)\\${r}(\\d+)$`);if(n.test(e)){const i=e.match(n).slice(1).map((e=>parseInt(e))),a=Math.abs(i[0]-i[1]);a<=10&&a>=2&&(e=e.split(r).join("-"),t.push("variedJoinerPattern"))}}e.includes(";")&&(e=e.split(";").join(" "),t.push("semicolon set separation"));const r=/(^|\s)(\d)\/(\d)(\d)\/(\d)(\(|$)/;if(r.test(e)){const[n,i,a,o,s,c]=e.match(r).slice(1);e=e.replace(r,`${n}${i}-${a} ${o}-${s}${c}`),t.push("smashSlashPattern")}/.*\s6[/-]+$/.test(e)&&(e+="0",t.push("incompleteFinalSetPattern"));const n=/\(6,\)/g;n.test(e)&&(e=e.replace(n,"(6, 0)"),t.push("missingZeroPattern1"));const i=/^\d{3,}\(/,a=/\(\d+\)\d+/;[i,a].forEach((()=>{const r=e.split(" ");e=r.map((e=>(i.test(e)&&(e=e.replace("("," (")),a.test(e)&&(e=e.replace(")",") ")),e))).join(" "),t.push("spaceConsiderationPatterns")}));const o=AA(e);o!==e&&(e=o,t.push("deDashMash"));const s=/^(\d)[-/,]+(\d{2})[-/,]+(\d)$/;if(s.test(e)){const[r,n,i]=e.match(s).slice(1),[a,o]=n.split("");e=`${r}-${a} ${o}-${i}`,t.push("smashSetPattern")}const c=/^(\d+)[ -](\d+)$/,u=/^([\d -]+)\/([\d -]+)$/;if(u.test(e)){const[r,n]=e.match(u).slice(1),i=r.trim(),a=n.trim();if(c.test(i)&&c.test(a)){const r=i.match(c).slice(1,3).join("-"),n=a.match(c).slice(1,3).join("-");e=`${r} ${n}`,t.push("slashSeparationPattern")}}const d=/^([\d -]+),([\d -]+)$/;if(d.test(e)){const[r,n]=e.match(d).slice(1),i=r.trim(),a=n.trim();if(c.test(i)&&c.test(a)){const r=i.match(c).slice(1,3).join("-"),n=a.match(c).slice(1,3).join("-");e=`${r} ${n}`,t.push("commaSeparationPattern")}}const p=/^\d \d,/;if(p.test(e)){const r=e.match(p)[0],n=r.slice(0,r.length-1).split(" ").join("-");e=e.replace(r,n),t.push("singleSetCommaSeparationPattern")}let l=0;const m=/(\d+)-(\d{2})-(\d+)/;for(;m.test(e)&&l<3;){const[r,n,i]=e.match(m).slice(1),a=n.split(""),o=`${r}-${a[0]} ${a[1]}-${i}`;e=e.replace(m,o),t.push("noSetSeparationPattern"),l+=1}const f=e.match(/(^|\s)7-6\s(\d+)\s/g);if(f?.length){const r=/(^|\s)7-6\s(\d+)\s/;f.forEach((n=>{const i=n.match(r).slice(2)[0];e=e.replace(n,`7-6(${i}) `),t.push("floatingTiebreakPattern1")}))}let h=e.match(/\d \d /);h?.forEach((r=>{const n=r.slice(0,r.length-1).split(" ").join("-");e=e.replace(r,n),t.push("spaceSeparatedSetPattern1")})),h=e.match(/ \d \d$/),h?.forEach((r=>{const n=" "+r.slice(1).split(" ").join("-");e=e.replace(r,n),t.push("spaceSeparatedSetPattern2")}));const g=/^\d, *\d\/\d, *\d/;if(g.test(e)){const r=e.match(g)[0],n=r.split("/").map((e=>`(${e})`)).join(" ")+" ";e=e.replace(r,n),t.push("slashCommaSetPattern")}const I=/\(6-\)/g;I.test(e)&&(e=e.replace(I,"(6-0)"),t.push("missingZeroPattern2"));const U=/(?<!-)(\d+)\/(\d+)(?!-)/g;if(U.test(e)){const r=e.match(U),n=/(?<!-)(\d+)\/(\d+)(?!-)/;let i=e;r.forEach((e=>{const[t,r]=e.match(n).slice(1),a=`${t}-${r}`;i=i.replace(e,a)})),e=i,t.push("slashSetPattern")}const y=/(.*)\s(1\d)\s(\d+)$/;if(y.test(e)){const[r,n,i]=e.match(y).slice(1);r.replace(/\D/g,"").length>=4&&(e=r+` ${n}${i}`,t.push("spaceSeparatedSuperPattern"))}const S=/(^|\s)(\d+-\d+)\s(\d+)(\s|$)/g;for(const r of e.match(S)||[]){const[n,i,a,o]=r.match(/(^|\s)(\d+-\d+)\s(\d+)(\s|$)/).slice(1),[s,c]=i.split("-").map((e=>parseInt(e)));1===Math.abs(s-c)&&(e=e.replace(r,`${n}${i}(${a})${o}`),t.push("spaceSeparatedSetPattern"))}const v=/\d-\d \(\d{1,2}\)(\s|$|,)/g;for(const r of e.match(v)||[]){const n=/(\d-\d) \((\d{1,2})\)(\s|$|,)/,[i,a,o]=r.match(n).slice(1),[s,c]=i.split("-").map((e=>parseInt(e)));1===Math.abs(s-c)&&(e=e.replace(r,`${i}(${a})${o}`),t.push("floatingTiebreakPattern2"))}const T=/(^|\s)(\d \d)\(/g;for(const r of e.match(T)||[]){const n=/(^|\s)(\d \d)\(/,[i,a]=r.match(n).slice(1);e=e.replace(r,`${i}${a.split(" ").join("-")}(`),t.push("spacedTiebreakPattern")}return{score:e,applied:t}},removeDanglingBits:function({score:e,attributes:t}){(e.endsWith(" am")||e.endsWith(" pm"))&&(e=""),e=e.replace(/[A-Za-z]+/g,"").trim(),[".",","].some((t=>e.endsWith(t)))&&(e=e.slice(0,e.length-1));const r="()/-".split("").some((t=>e.includes(t)));if(/ \d$/.test(e)&&r){t={removed:e.slice(e.length-2).trim()},e=e.slice(0,e.length-2)}const n=/(.*)[A-Za-z]+$/;if(n.test(e)){const t=e.match(n).slice(1)[0];e=t.trim()}return{score:e,attributes:t}},removeErroneous:function({score:e,applied:t}){if("string"!=typeof e)return{score:e};if([3,4].includes(e.length)&&CA(e)){return{score:CA(e)}}return{score:e=e.toLowerCase().split(" ").map((e=>{if(!/^\d+$/.test(e)||1!==e.length)return e;t.push("removeErroneous1")})).filter(Boolean).join(" "),applied:t}},handleWalkover:function({score:e,applied:t}){return["walkover","wo","w/o","w-o"].includes(e?.toString().toLowerCase())?(t.push("handleWalkover"),{matchUpStatus:"walkover",score:"",applied:t}):{score:e}},properTiebreak:function({score:e,matchUpStatus:t}){let r=e?.split(" ");e=r.map((e=>{if(e.endsWith("]")){const t=e.split("[");if(bA(t[0]))return t[0]+`(${t[1].slice(0,t[1].length-1)})`}return e})).join(" ");const n=new RegExp(/(\([\d ]+\))/g);if(n.test(e))for(const t of e.match(n)){const r=t.replace(" ","-");let n=r.match(/\((.*)\)/)?.[1];if(kd(n)&&n?.[0]>2)if([2,4].includes(n.length))n=n.split("").join("-");else if(3===n.length){const e=n.indexOf("1");n=RA(n.split(""),e)}e=e.replace(t,`(${n})`)}r=e?.split(" ");let i=new RegExp(/^(\d[-/]+\d)\((\d+)[-/]+(\d+)\)$/);const a=r.length-1;e=r.map(((e,r)=>{const n=[void 0,"","COMPLETED"].includes(t)||r!==a;if(i.test(e)&&n){const[t,r,n]=Array.from(e.match(i)).slice(1);return`${t}(${Math.min(r,n)})`}return e})).join(" "),r=e?.split(" "),i=new RegExp(/^(\d{2})\((\d+)\)$/),e=r.map((e=>{if(i.test(e)){const[t,r]=Array.from(e.match(i)).slice(1),n=t.split("");return`${n[0]}-${n[1]}(${r})`}return e})).join(" "),r=e?.split(" "),i=new RegExp(/^\((\d[-/]+\d)\)(\d+)$/),e=r.map((e=>{if(i.test(e)){const[t,r]=Array.from(e.match(i)).slice(1);return bA(t)?`${t}(${r})`:t}return e})).join(" "),r=e?.split(" "),i=new RegExp(/^1-0\((\d+)\)$/),e=r.map((e=>{if(i.test(e)){const[t]=e.match(i).slice(1);return`[${t<9?10:parseInt(t)+2}-${t}]`}return e})).join(" ");const o=/\((\d)+0 /;if(o.test(e)){const t=e.match(o)[1];e=e.replace(o,`(${t}) `)}return{score:e}},handleNumeric:OA,handleRetired:function({score:e,profile:t,applied:r}){e=e?.toString().toLowerCase();const n=/^(.*\d+.*)(ret|con)+[A-Za-z ]*$/;if(n.test(e)){const[t]=e.match(n).slice(1);return r.push("handleRetired"),{score:t.trim(),matchUpStatus:"retired",applied:r}}const i=t?.matchUpStatuses?.retired,a=["rtd",...Array.isArray(i)?i:[i].filter(Boolean)].find((t=>e?.endsWith(t)));return a?(r.push("handleRetired"),{matchUpStatus:"retired",score:e?.replace(a,"").trim(),applied:r}):{score:e}},containedSets:function({score:e,attributes:t,identifier:r}){if("string"!=typeof e)return{score:e,identifier:r};const n=new RegExp(/\([\d,/ ]+\)/g),i=e.match(n);for(const t of i||[]){const r=t.match(/^\((.*)\)$/),n=r?.slice(1)?.[0],i=e.split(t)[0].split(")").reverse()[0].replace(/\D/g,"");if(2===n?.length&&i?.length>=2){const e=i.slice(i.length-2).split("").map((e=>parseInt(e)));if(1===Math.abs(e[0]-e[1]))continue}const a=AA(NA(n));e=e.replace(t,`(${a})`).trim()}const a=new RegExp(/\[[\d,/ ]+\]/g),o=e.match(a);o?.forEach((t=>{const r=NA(t.match(/^\[(.*)\]$/)[1]);e=e.replace(t,`(${r}) `).trim()}));const s=[")(","), (",") (",")[",") [","](","] ("];if(e.startsWith("(")&&[")","]"].some((t=>e.endsWith(t)))&&s.some((t=>e.includes(t)))){let t="";const r=e.split(/[)\]]/).filter(Boolean).map((e=>(e.startsWith(",")&&(e=e.slice(1)),e.trim()))),n=r.every((e=>e.includes(",")||wA(e))),i=r.every((e=>e.includes("/")||wA(e))),a=r.every((e=>e.includes("-")||wA(e))),o=(n?",":a&&"-")||i&&"/";if(o){let n;r.forEach((e=>{if(e.startsWith("("))if("set"===n&&(t+=" "),e.includes(o))t+=e.slice(1).split(o).map((e=>e.trim())).join("-"),n="set";else{const r=e.slice(1);t+=`(${r}) `,n="tiebreak"}else if(e.startsWith("[")){const r=e.slice(1).split(o).map((e=>parseInt(e.trim()))),i=Math.min(...r);t+="set"===n?`(${i}) `:`[${r.join("-")}] `,n="tiebreak"}})),e=t.trim()}}const c=$d(e.split(""));1===c["("]&&1===c[")"]&&e.startsWith("(")&&e.endsWith(")")&&(e=e.slice(1,e.length-1),1===c["-"]&&bA(e)&&kd(t?.removed)&&(e+=`(${t.removed})`,t.removed=void 0));const u=/\(\)/g;return u.test(e)&&(e=e.replace(u,"").trim()),{score:e}},sensibleSets:function({score:e,matchUpStatus:t,attributes:r}){const n=[];let i;const a=e.split(" "),o=a.length;e=a.map(((e,r)=>{if(new RegExp(UA).test(e)){const r=e.slice(3),n=e.slice(0,3),i=n.split("-");if(!bA(n)&&!t){const e=Math.max(...i),t=[e,e-1];n.indexOf(e)&&t.reverse();return t.join("-")+r}}else if(2===e.length&&kd(e))return e.split("").join("-");e=AA(e);const a=(new RegExp(`^${yA}$`).test(e)?"super":new RegExp(`^${UA}$`).test(e)&&"tiebreak")||new RegExp(`^${IA}$`).test(e)&&"standard"||"unknown";if(n.push(a),o>1&&"standard"===a&&r<2){const[t,n]=e.split("-"),a=Math.abs(parseInt(t)-parseInt(n)),o=Math.max(t,n),s=Math.min(t,n),c=[parseInt(t),parseInt(n)].indexOf(s);if(o>9&&a>2){const t=o.toString().split(""),n=t.find((e=>parseInt(e)>s||r&&parseInt(e)<=i))??t[0];n&&(e=c?[n,s].join("-"):[s,n].join("-"))}o>(i||0)&&(i=o)}if("standard"===a){const[r,n]=e.split("-");if(!Math.abs(parseInt(r)-parseInt(n))&&"RETIRED"!==t)return""}return e})).filter(Boolean).join(" ");const{setsWon:s,setWinners:c,totalSets:u}=FA(e);if(1===u&&"6"===r?.removed&&(e+=" 6-0"),e.split(" ").length>2&&Math.max(...s)>=2&&c[0]===c[1]&&(e=e.split(" ").slice(0,2).join(" ")),Math.max(...s)>2){const t=[0,0];e=e.split(" ").map(((e,r)=>(t[c[r]]+=1,Math.max(...t)>2?void 0:e))).filter(Boolean).join(" ")}return{score:e,profile:n}},stringScore:function({score:e}){return{score:e=e?.toString().toLowerCase()||""}},superSquare:function({score:e}){const{setsTied:t,winningSide:r}=FA(e),n=/\s\((\d+)\)$/;if(!r&&t&&n.test(e)){const t=e.match(n).slice(1)[0],r=t<=8?10:t+2;e=e.replace(n,` [${r}-${t}]`)}const i=e.split(" "),a=i[i.length-1];if(!a.includes("-")||a.indexOf("(")>0)return{score:e};let o=a.split("(").join("").split(")").join("").split("-");if(!o.every((e=>kd(e))))return{score:e};if("76"===o[0]){const t=2===o[1].length?Math.min(...o[1].split("").map((e=>parseInt(e)))):o[1];e=[...i.slice(0,i.length-1),`7-6(${t})`].join(" ")}else{o=o.map((e=>parseInt(e)));const t=Math.max(...o);let r=Math.abs(o[0]-o[1]);if(t>=10){if(r>2&&o.every((e=>+e>=10))){const e=o.map((e=>e===t?e-10:10)).sort();r=Math.abs(e[0]-e[1]),r>2&&(o=e)}e=[...i.slice(0,i.length-1),`[${o.join("-")}]`].join(" ")}else 3===i.length&&t>=7&&r>2&&(e=[...i.slice(0,i.length-1),`[${o.join("-")}]`].join(" "))}return{score:e}},setBuilder:EA,excisions:function({score:e}){const t=new RegExp(/^\[\d+\](.*)$/);t.test(e)&&(e=e.match(t).slice(1)[0].trim());const r=/\(,/g;return r.test(e)&&(e=e.replace(r,"(")),{score:e}},replaceOh:function({score:e,applied:t}){return"string"!=typeof e?{score:e}:(e.toLowerCase().includes("o")&&(e=e.toLowerCase().split(" ").map((e=>e.split("o").join("0"))).join(" "),t.push("replaceOh")),{score:e,applied:t})}};let _A={};const xA=["handleNumeric","handleWalkover","handleRetired","replaceOh","stringScore","punctuationAdjustments","excisions","handleSpaceSeparator","matchKnownPatterns","removeDanglingBits","handleBracketSpacing","matchKnownPatterns","containedSets","separateScoreBlocks","handleGameSeparation","removeErroneous","joinFloatingTiebreak","handleSetSlashSeparation","handleTiebreakSlashSeparation","properTiebreak","sensibleSets","superSquare"],LA=["handleNumeric","separateScoreBlocks","sensibleSets","superSquare"];const VA=" ",BA="DEF",jA="WO",GA="ABN",qA="SUS",$A="RET",WA="INT",HA=[$A,BA,jA,"WO/WO",GA,qA,WA],zA="DEFAULTED",YA="WALKOVER",QA="ABANDONED",KA="SUSPENDED",JA="RETIRED",ZA="INTERRUPTED",XA=[JA,zA,YA],eE="()",tE="[]",rE=["up","left","shift+tab"],nE=["enter","down","tab","right"],iE="backspace",aE="r",oE="s",sE="a",cE="d",uE="w",dE="i",pE=[aE,cE,uE,sE,oE,dE],lE="space",mE=["[","("],fE=[...rE,...nE,lE,"]"],hE="-",gE="-",IE=["/"],UE=["0","1","2","3","4","5","6","7","8","9"].concat(pE),yE=UE.map((e=>`shift+${e}`)),SE=[hE,iE].concat(fE,IE),vE=[UE,yE,SE].join(","),TE=[vE,rE,nE,["=","+","num_1","num_2","shift+=","shift+-"]].join(",");[].concat(...UE,...UE,...SE,...UE,...UE,...UE,...UE,...UE,...UE);const PE={OUTCOMEKEYS:pE,SIDE1KEYS:UE,SIDE2KEYS:yE,MODIFIERS:SE,PROMPT:"Enter Score",MOVEUP:rE,MOVEDOWN:nE,HOTKEYS:TE};function DE({scoreString:e,lowSide:t,outcome:r}){if(({scoreString:e}=wE({scoreString:e})),2===t){return e+((e&&e[e.length-1])!==VA?VA:"")+r}return r+VA+e}function wE({scoreString:e}){if(!e)return{scoreString:""};let t=!1;for(const r of HA){const n=e?.indexOf(r);0===n?e=e.slice(r.length+1).trim()+VA:n>0&&(e=e.slice(0,n)),n>=0&&(t=!0)}return e?.trim()||(e=""),{scoreString:e,removed:t}}function bE({analysis:e,scoreString:t,sets:r,lowSide:n}){let i,a;if(!t)return{scoreString:t,sets:r};const{scoreString:o,removed:s}=wE({scoreString:t});if(t=o,s)return{scoreString:t,sets:r,outcomeRemoved:!0};let c=r[r.length-1]||{};const u=Object.values(c).filter((e=>void 0!==e)).length;c.setNumber&&1===u&&(c=(r=r.slice(0,r.length-1))[r.length-1]||{});const{tiebreakSet:d}=e.setFormat,{tiebreakTo:p,NoAD:l}=d||{},{isTiebreakEntry:m}=RE({brackets:tE,scoreString:t}),f=function(e){const t=e.split("");return t.reduce(((e,t,r)=>(t.match(/\d+/g)&&e.push(r),e)),[]).pop()}(t);if(f>=0){i=t.slice(0,f);const{isTiebreakEntry:o}=RE({brackets:eE,scoreString:i}),{lastOpenBracketIndex:s,isTiebreakEntry:u}=RE({brackets:tE,scoreString:i}),d=i&&i[i.length-1].trim(),h=i&&!isNaN(d);let g=e.isIncompleteSetScore;if(m&&u){const e=i.slice(s+1).split(gE),r=e?.length>0&&void 0!==e[0]&&!isNaN(parseInt(e[0]))&&parseInt(e[0])||void 0,a=e?.length>1&&void 0!==e[1]&&parseInt(e[1])||void 0,o=[r,a];if(a){const e=1===n?1:0;o[e]=(o?.[1-e]||0)+(l?1:2),(o[e]||0)<p&&(o[e]=p),i=t.slice(0,s+1),i+=o.join(gE)}else void 0!==r?(i=t.slice(0,s+1),i+=r):(i=t.slice(0,s),g=!0);c.side1TiebreakScore=o[0]||0,c.side2TiebreakScore=o[1]||0}if(i.length||(i=void 0),g){const t=c.side1Score?.toString();if(t){const e=t?.slice(0,t.length-1);c.side1Score=!isNaN(e)&&parseInt(e)||void 0,void 0===c.side1Score&&(c.side2Score=void 0)}e.isTimedSet?(a=c.side1Score?r:r?.slice(0,r.length-1)||[],a[r.length-1]=c):a=r?.slice(0,r.length-1)||[]}else if(h){const t=c.side2Score?.toString(),n=c.side1Score?.toString();if(!e.isTiebreakEntry&&!e.isMatchTiebreak)if(c.side2Score){const e=t?.slice(0,t.length-1);c.side2Score=!isNaN(e)&&parseInt(e)||void 0}else{const e=n?.slice(0,n.length-1);c.side1Score=!isNaN(e)&&parseInt(e)||void 0}e.isTimedSet?c.side1Score?(a=r||[],a[r.length-1]=c):a=r?.slice(0,r.length-1)||[]:(a=r||[],a[r.length-1]=c),a[a.length-1]&&Object.assign(a[a.length-1],{winningSide:void 0})}else o?(a=r||[],Object.assign(a[a.length-1]||{},{winningSide:void 0,side1TiebreakScore:void 0,side2TiebreakScore:void 0})):(m&&!u?a=r?.slice(0,r.length-1)||[]:(a=r,a[r.length-1]=c),m||(a[a.length-1].side2Score=0,a[a.length-1].winningSide=void 0));return{scoreString:i,sets:a}}return{scoreString:t,sets:r}}function RE({brackets:e=eE,scoreString:t}){if(!t)return{};const[r,n]=e.split(""),i=t.split(""),a=Math.max(...Kd(r,i));return{isTiebreakEntry:a>Math.max(...Kd(n,i)),lastOpenBracketIndex:a}}function NE(e){const{lowValue:t=0,NoAD:r=!1,tiebreakTo:n}=e||{};return t+1>=n?t+(r?1:2):parseInt(n)}function ME({matchUpFormat:e,matchUpStatus:t,winningSide:r,sets:n}){const i=QI(e),{bestOf:a}=i,o=Math.ceil(a/2),s=n?.reduce(((e,t)=>{const{winningSide:r}=t;return r&&e[r-1]++,e}),[0,0]);let c=s?.indexOf(o)+1||void 0;return XA.includes(t)&&r&&(c=r),{matchUpWinningSide:c}}function AE({analysis:e,set:t}){const r=Wb({set:t}),{isDecidingSet:n,isTiebreakSet:i,matchUpScoringFormat:a}=e;return $b({matchUpScoringFormat:a,isDecidingSet:n,isTiebreakSet:i,set:t})&&r}function EE({lowSide:e,value:t,sets:r,scoreString:n,winningSide:i,matchUpStatus:a}){let o;return t===aE?n?(o=!0,n=DE({scoreString:n,lowSide:e,outcome:$A}),i=2===e?1:2,a=JA):(o=!0,n=DE({scoreString:n,lowSide:e,outcome:BA}),i=2===e?1:2,a=zA):t===cE?(o=!0,n=DE({scoreString:n,lowSide:e,outcome:BA}),i=2===e?1:2,a=zA):t===uE?(o=!0,r=[],n=jA,i=2===e?1:2,a=YA):t===oE&&n?(o=!0,n=DE({scoreString:n,lowSide:e,outcome:qA}),a=KA,i=void 0):t===sE?(o=!0,n=DE({scoreString:n,lowSide:e,outcome:GA}),a=QA,i=void 0):t===dE&&n&&(o=!0,n=DE({scoreString:n,lowSide:e,outcome:WA}),a=ZA,i=void 0),{updated:o,sets:r,scoreString:n,matchUpStatus:a,winningSide:i}}function CE({matchUpFormat:e,scoreString:t,winningSide:r,value:n,sets:i}){const a=(i?.filter((e=>e?.winningSide))?.length||0)+(r?0:1),o=QI(e),s=a===o?.bestOf,c=s&&o?.finalSetFormat||o?.setFormat||{},u=c?.timed,d=s&&i[o?.bestOf-1],p=d?.winningSide,{isTiebreakEntry:l}=RE({brackets:eE,scoreString:t}),{isTiebreakEntry:m}=RE({brackets:tE,scoreString:t}),f=l||m,h=!!c.tiebreakSet,g=t?.[t.length-1]?.trim(),I=t&&!isNaN(g),U=!f&&g===hE,y=l&&mE.includes(g),S=m&&mE.includes(g),v=m&&g===gE,T=t?.split(""),[P]=tE.split(""),D=T&&Math.max(...Kd(P,T)),w=T&&Math.max(...Kd(gE,T)),b=T&&w>D,R=i[i.length-1]?.winningSide,N=i?.length&&!R,M=HA.find((e=>t?.indexOf(e)>=0)),A=!isNaN(n),E=n===lE,C=fE.includes(n),O=t?.split("").find((e=>mE.includes(e))),F=C&&m&&!S&&(v||!function({scoreString:e}){if(!e)return!1;const t=e&&e[e.length-1].trim(),r=e&&!isNaN(t),[n,i]=tE.split(""),a=e.split(""),o=Math.max(...Kd(n,a)),s=Math.max(...Kd(i,a)),c=Math.max(...Kd(gE,a));return r&&o>s&&c>o}({scoreString:t}));return{isTiebreakSetValue:h&&A,matchUpScoringFormat:o,setNumber:a,setFormat:c,matchTiebreakHasJoiner:b,isGameScoreEntry:N,isSpace:E,isCloser:C,isTiebreakCloser:C&&O&&f&&I,isDecidingSet:s,isTiebreakSet:h,isTimedSet:u,isNumericEnding:I,isNumericValue:A,hasOpener:O,hasOutcome:M,finalSet:d,finalSetIsComplete:p,lastSetIsComplete:R,isInvalidSetTiebreakValue:E&&f&&y,isInvalidMatchTiebreakValue:F,isTiebreakEntry:f,isSetTiebreakEntry:l,isMatchTiebreakEntry:m,isIncompleteSetScore:U,isIncompleteSetTiebreak:y,isIncompleteMatchTiebreak:S,isPartialMatchTiebreakValue:v}}function OE({matchUp:e}){const{extension:t}=Wl({name:hi,element:e});if(!t)return{error:ws};const{history:r=[],undoHistory:n=[]}=t.value;return{history:r,undoHistory:n,...Ni}}function FE({undoHistory:e,history:t,matchUp:r}){return gd({element:r,extension:{value:{history:t,undoHistory:e},name:hi}})}var kE=Object.freeze({__proto__:null,addGame:function({matchUp:e,game:t}){if("object"!=typeof t)return{error:ys,context:{game:t}};const{history:r=[]}=OE({matchUp:e});return r.push(t),FE({matchUp:e,history:r})},addPoint:function({matchUp:e,point:t}){if(!t||!e)return{error:Za};if("object"!=typeof t)return{error:ys,context:{point:t}};const{history:r=[]}=OE({matchUp:e});return r.push(t),FE({matchUp:e,history:r})},addSet:function({matchUp:e,set:t}){if("object"!=typeof t)return{error:Za};const{history:r=[]}=OE({matchUp:e});return r.push(t),FE({matchUp:e,history:r})},addShot:function({matchUp:e,shot:t}){if("object"!=typeof t)return{error:Za};const{history:r=[]}=OE({matchUp:e});return r.push(t),FE({matchUp:e,history:r})},analyzeSet:Hb,calculateHistoryScore:function(e){if(!e)return{error:Za};const{matchUp:t,updateScore:r}=e;if(!t)return{error:Ba};const n=OE({matchUp:t})?.history||[];if(!Array.isArray(n))return{error:ys,info:"history is not an array"};const{matchUpFormat:i}=t;if(!i)return{error:Oa};if(!uv({matchUpFormat:i}))return{error:Ca};const a=QI(i),{bestOf:o,finalSetFormat:s,setFormat:c}=a,u=["0","15","30","40","A","G"],d={sets:[]};let p,l,m=[],f=[0,0],h=1,g=0,I=0;const U=e=>[1,2].includes(e),y=()=>(g+=1,{winningSide:void 0,side1Score:0,side2Score:0,setNumber:g,games:[]});let S={winningSide:void 0,side1Score:"",side2Score:"",shots:[]},v={winningSide:void 0,points:[]},T=y(),P=0;for(const e of n){P+=1,l=d.sets.length+1===o;const t=l&&s?s:c,{tiebreakAt:r,setTo:n,NoAD:i,tiebbreakFormat:a}=t,g=T.side1Score===r&&T.side1Score===T.side2Score,D=!!t.tiebreakSet,w=D?t.tiebreakSet:a,{tiebreakTo:b,NoAD:R}=w||{},N=()=>{p=void 0,f=[0,0],h=3-h,T.side1TiebreakScore=0,T.side2TiebreakScore=0,T.side1PointScore="",T.side2PointScore="",I=0},M=e=>{T.winningSide=e;const{s:t,...r}=T;d.sets.push(r),S={winningSide:void 0,side1Score:"",side2Score:"",shots:[]},v={winningSide:void 0,points:[]},T=y(),N()},A=e=>{v.winningSide=e;const{g:t,...r}=v;T.games.push(r),S={winningSide:void 0,side1Score:"",side2Score:"",shots:[]},v={winningSide:void 0,points:[]},N();T[`side${e}Score`]+=1},E=e=>{S.winningSide=e;const{p:t,...r}=S;v.points.push(r),S={winningSide:void 0,side1Score:"",side2Score:"",shots:[]},I=0;const n=e-1;if(g||D){f[n]+=1,p=f.reduce(((e,t)=>e+t))%4/4>.5?h:3-h,T[`side${e}TiebreakScore`]=f[n],T[`side${3-e}TiebreakScore`]=f[1-n];const t=R?1:2;if(f[n]>=b&&f[n]>=f[1-n]+t)return A(e),{gameCompleted:!0}}else if(4===f[1-n]&&3===f[n]?f[1-n]-=1:f[n]+=1,T.side1PointScore=u[f[0]],T.side2PointScore=u[f[1]],5===f[n]||4===f[n]&&f[1-n]<3||i&&4===f[n])return A(e),{gameCompleted:!0}};if(U(e.srv)&&(h=e.srv),["p","s","g","o"].includes(e.u)&&m.push(e.u),e.shotOutcome){S.shots.push(e);if("SERVE"===e.shotType&&["OUT","NET"].includes(e.shotOutcome)&&(I+=1),2===I){E(3-h)}}if(U(e.p)||Vd(e.pointNumber)){const t=E(e.winningSide||e.p);if(t?.gameCompleted)continue}if(U(e.g)||Vd(e.gameNumber)){const t=e.winningSide||e.g;v.winningSide=t;const r=`side${t}Score`,a=`side${3-t}Score`;m.length&&(m.includes("p"),m=[]),A(t);if(T[r]===n&&T[r]-T[a]>=(i?1:2)&&(M(t),l))break}if(U(e.s)||Vd(e.setNumber)){if(M(e.winningSide||e.s),m.length&&(m.includes("p"),m.includes("g"),m=[]),l)break}}return P!==n.length&&console.log({error:"Match completed with excess history"}),(T.side1Score||T.side2Score||T.games.length||T.side1TiebreakScore||T.side2TiebreakScore)&&d.sets.push(T),d.scoreStringSide1=sw({...d,matchUpFormat:i}),d.scoreStringSide2=sw({...d,matchUpFormat:i,reversed:!0}),h=p||h,r&&(t.score=d),{...Ni,servingSide:h,score:d}},checkScoreHasValue:hg,checkSetIsComplete:$b,clearHistory:function({matchUp:e}){return FE({matchUp:e})},generateScoreString:sw,generateTieMatchUpScore:function(e){const{sideAdjustments:t=[0,0],separator:r="-",drawDefinition:n,matchUpsMap:i,structure:a,matchUp:o,event:s}=e;if(!Array.isArray(t)||2!==t.length||isNaN(t.reduce(((e,t)=>e+t))))return{error:ys};if(!o)return{error:Ba};const c=we({matchUp:o,drawDefinition:n,structure:a,event:s})?.tieFormat||e?.tieFormat;if(!c)return{error:ka};const u=ar({tieFormat:c});if(u.error)return u;const d=c?.collectionDefinitions||[],p=o?.tieMatchUps??[],l=[0,0],{groupValueGroups:m,groupValueNumbers:f}=Dn(c);for(const e of d)gA({collectionDefinition:e,groupValueNumbers:f,groupValueGroups:m,sideTieValues:l,tieMatchUps:p});for(const e of f){const t=m[e],{allGroupMatchUpsCompleted:r,matchUpCount:n,winCriteria:i,groupValue:a,sideWins:o,values:s}=t;let c;if(i?.aggregateValue)r&&s[0]!==s[1]&&(c=s[0]>s[1]?1:2);else if(i?.valueGoal)c=s.reduce(((e,t,r)=>t>=i.valueGoal?r+1:e),void 0);else{const e=Math.floor(n/2)+1;c=o.reduce(((t,r,n)=>r>=e?n+1:t),void 0)}c&&(l[c-1]+=a||0)}const h=l.map(((e,r)=>(e||0)+t[r])),g={side1Score:h[0],side2Score:h[1],winningSide:void 0},I=h.join(r),U=h.slice().reverse().join(r);let y;if(c?.winCriteria){const{valueGoal:e,aggregateValue:t,tallyDirectives:r}=c.winCriteria;if(e){const t=h.map(((e,t)=>({sideNumber:t+1,points:e}))).find((({points:t})=>t>=e));y=t?.sideNumber}else if(t){p.every((e=>e.matchUpStatus&&rf.includes(e.matchUpStatus)||e.winningSide))&&h[0]!==h[1]&&(y=h[0]>h[1]?1:2)}if(!y&&r){const e=o.matchUpId,t=o.hasContext?o:i?.drawMatchUps?.[e]||n&&Jt({inContext:!0,drawDefinition:n,matchUpId:e})?.matchUp;if(t){const{completedTieMatchUps:e,order:r}=Vn({matchUps:[t]});if(e&&r?.length){const e=r[0].participantId;y=t.sides.find((({participantId:t})=>t===e))?.sideNumber}}}}return y&&(g.winningSide=y),{scoreStringSide1:I,scoreStringSide2:U,winningSide:y,set:g}},getSetComplement:Jb,getTiebreakComplement:Zb,isValidMatchUpFormat:uv,keyValueScore:function(e){let{lowSide:t=1,value:r}=e,{scoreString:n,sets:i,winningSide:a,matchUpStatus:o}=e;const{matchUpFormat:s,shiftFirst:c,auto:u=!0}=e;let d,p;const l=c&&2===t||!c&&1===t;if(!vE.includes(r))return{updated:!1,info:"invalid key"};c&&(t=3-t);const{matchUpWinningSide:m}=ME({sets:i,winningSide:a,matchUpStatus:o,matchUpFormat:s});a=m;const f=CE({value:r,winningSide:a,scoreString:n,sets:i,matchUpFormat:s});if(IE.includes(r)&&(r=hE),f.hasOpener&&f.isTiebreakEntry&&!f.isTiebreakSet&&l&&0===Ed(r)&&(f.isTiebreakCloser=!0),fE.includes(r)&&f.hasOpener&&(r=""),fE.includes(r)&&(r=lE),f.lastSetIsComplete){const e=n?.length&&n[n.length-1];n&&" "!==e&&(n+=" ")}if(f.isTimedSet)({info:p,sets:i,scoreString:n,updated:d,matchUpStatus:o,winningSide:a}=function(e){let{sets:t,info:r,scoreString:n,winningSide:i,matchUpStatus:a}=e;const{analysis:o,lowSide:s,value:c}=e;let u,d;t?.length||c===iE||(t=[{setNumber:1}]);const p=t.length-1;if(pE.includes(c)){const e=t[t.length-1]||{},{side1Score:d,side2Score:p}=e;d&&!p?r="missing side2Score":o.finalSetIsComplete||i?r="final set is already complete":o.isIncompleteSetScore?r="incomplete set scoreString":o.isIncompleteSetScore||({sets:t,scoreString:n,winningSide:i,matchUpStatus:a,updated:u}=EE({lowSide:s,value:c,sets:t,scoreString:n,matchUpStatus:a,winningSide:i}))}else if(c===iE){if(({scoreString:n,sets:t,outcomeRemoved:d}=bE({analysis:o,scoreString:n,sets:t})),""===n?.trim()&&(n=n.trim()),n||(t=[]),d){const e=t[t.length-1]||{},{side1Score:r,side2Score:n}=e;if(r&&n){const i=(r>n?1:n>r&&2)||void 0;i&&(e.winningSide=i,t.push({setNumber:t.length+1}))}}a=void 0,i=void 0,u=!0}else if(o.hasOutcome)r="has outcome";else{if(i)return{sets:t,scoreString:n,winningSide:i,matchUpStatus:a,updated:!1,info:"matchUp is complete"};if(c===lE){const e=t[t.length-1]||{},{side1Score:r,side2Score:a}=e,s=(r>a?1:a>r&&2)||void 0;!s||i||o.isIncompleteSetScore||(t[t.length-1].winningSide=s,t.push({setNumber:t.length+1}),n+=" ",u=!0)}else if(c===hE&&void 0!==t[p].side1Score&&void 0===t[p].side2Score&&n&&o.isNumericEnding)n+="-",t[p].side2Score=0,a=void 0,i=void 0,u=!0;else if(!isNaN(c)){let e;if(void 0===t[p].side2Score){const r=Ed((t[p].side1Score||0).toString()+c).toString().slice(0,2);t[p].side1Score=Ed(r),e=t[p].side1Score.toString(),u=!0}else{const r=Ed((t[p].side2Score||0).toString()+c).toString().slice(0,2);t[p].side2Score=Ed(r),e=[t[p].side1Score,t[p].side2Score].join("-"),u=!0}if(u){const r=(t.slice(0,p)||[]).filter((e=>e)).map((e=>{const{side1Score:t,side2Score:r}=e;return[t,r].join("-")})).join(" ");n=r?r+" "+e:e}}}return{sets:t,scoreString:n,winningSide:i,matchUpStatus:a,info:r,updated:u}}({analysis:f,lowSide:t,scoreString:n,sets:i,matchUpStatus:o,winningSide:a,value:r}));else if(pE.includes(r))f.finalSetIsComplete||a?p="final set is already complete":f.isTiebreakEntry||f.isIncompleteSetScore?f.isTiebreakEntry||f.isIncompleteSetScore?p="incomplete set scoreString or tiebreak entry":console.log("handle case",{value:r}):({sets:i,scoreString:n,matchUpStatus:o,winningSide:a,updated:d}=EE({lowSide:t,sets:i,scoreString:n,matchUpStatus:o,winningSide:a,value:r}));else if(r===iE)d=!0,({scoreString:n,sets:i}=bE({analysis:f,scoreString:n,sets:i,lowSide:t})),n||(i=[]),o=void 0,a=void 0;else if(f.hasOutcome)p="has outcome";else if(r!==hE||f.isMatchTiebreakEntry)if(r===gE&&f.isMatchTiebreakEntry&&!f.isSetTiebreakEntry)f.matchTiebreakHasJoiner?p="existing joiner":f.isNumericEnding&&(d=!0,n+=gE);else if([hE,gE].includes(r))p="invalid location for joiner";else{if(a)return{updated:!1,info:"matchUp is complete"};if(f.isIncompleteSetScore)f.isNumericValue&&({sets:i,scoreString:n,updated:d}=function({analysis:e,scoreString:t,sets:r,value:n}){let i;if(!r?.length)return{sets:[]};const a=r[r.length-1];n=Ed(n);const{validSide2Score:o,requiresTiebreak:s}=function({analysis:e,set:t={},value:r}){const n=e.isDecidingSet&&e.matchUpScoringFormat.finalSetFormat||e.matchUpScoringFormat.setFormat,{tiebreakAt:i,setTo:a,NoAD:o}=n,{side1Score:s}=t;let c,u;return c=i&&i<a?s===i?r<=a:r<=i:s===a?o?r<a:r<=a+1:s===a-1?o?r<=a:r<=a+1:s===a+1?r===a||r===a-1:r<=a,c&&(u=i&&i<a?s===a&&r===i||s===i&&r===a:s>=a&&r>=a&&s!==r),{validSide2Score:c,requiresTiebreak:u}}({analysis:e,set:a,value:n});if(o){i=!0,t=(t||"")+n,a.side2Score=n;const o=AE({analysis:e,set:r[r.length-1]});a.winningSide=o||void 0,s?t+=eE.split("")[0]:e.isDecidingSet||(t+=VA)}return{sets:r,scoreString:t,updated:i}}({analysis:f,scoreString:n,sets:i,value:r}));else if(f.isInvalidMatchTiebreakValue)p="invalid matchUp tiebreak character";else if(f.isInvalidSetTiebreakValue)p="invalid set tiebreak character";else if(f.isTiebreakCloser){const e=f.isSetTiebreakEntry?eE:tE,t=e.split("").reverse()[0],r=e.split("")[0],a=i[i.length-1],{tiebreakFormat:o}=f.setFormat,{tiebreakTo:s,NoAD:c}=o||{},u=Wb({set:a});if(!f.isTiebreakSet){const e=parseInt(n.split(r).reverse()[0]),t=NE({lowValue:e,tiebreakTo:s,NoAD:c});1===u?(a.side1TiebreakScore=t,a.side2TiebreakScore=e):(a.side1TiebreakScore=e,a.side2TiebreakScore=t)}n=(n||"")+t,f.isDecidingSet||(n+=VA);const p=AE({analysis:f,set:a});a.winningSide=p||void 0,d=!0}else if(f.isTiebreakSetValue)({info:p,scoreString:n,sets:i,updated:d}=function({analysis:e,auto:t,lowSide:r,scoreString:n="",sets:i,value:a}){let o,s;const{tiebreakSet:{tiebreakTo:c,NoAD:u}}=e.setFormat,[d]=tE.split("");if(e.isMatchTiebreakEntry||(n+=d),i[e.setNumber-1]){const{lastOpenBracketIndex:e}=RE({brackets:tE,scoreString:n}),d=(n.slice((e??0)+1)+(t?"":a)).split(gE);if((d[r-1]?.length||0)>=2)s="tiebreak digit limit";else if(t){1===r&&(d[0]=(d[0]||"")+a),2===r&&(d[1]=(d[1]||"")+a);const t=[d[0]||0,d[1]||0].map((e=>Ed(e))),s=1===r?1:0;t[s]=t[1-s]+(u?1:2),t[s]<c&&(t[s]=c);const p=i[i.length-1];p.side1TiebreakScore=t[0],p.side2TiebreakScore=t[1],n=n.slice(0,(e??0)+1),n+=t.join(gE),o=!0}else{const e=[d[0]||0,d[1]||0].map((e=>Ed(e))),t=i[i.length-1];t.side1TiebreakScore=e[0],t.side2TiebreakScore=e[1],n+=a,o=!0}}else{const e=NE({lowValue:Ed(a||0),tiebreakTo:c,NoAD:u}),t=[Ed(a),e];2===r&&t.reverse();const s={side1TiebreakScore:t[0],side2TiebreakScore:t[1],setNumber:i?.length+1||1};i.push(s),n+=t.join(gE),o=!0}return{info:s,scoreString:n,sets:i,updated:o}}({analysis:f,auto:u,lowSide:t,scoreString:n,sets:i,value:r}));else if(f.isSetTiebreakEntry){const[e]=eE.split(""),t=Math.max(...Kd(e,n.split(""))),i=n.slice(t+1),a=i&&0===Ed(i),o=Ed(i?i+r:r),{tiebreakFormat:s}=f.setFormat,{tiebreakTo:c,NoAD:u}=s||{};!a&&i.length<2?u&&o>c-1?p="invalid low value for NoAD tiebreak":(d=!0,n=(n||"")+r):p=a?"tiebreak begins with zero":"tiebreak digit limit"}else if(f.isCloser)p=`invalid key: ${r}`;else if(f.isGameScoreEntry)p="game scoreString entry";else if(f.lastSetIsComplete||!i.length){d=!0;const{scoreString:e,set:a}=function({analysis:e,lowSide:t,scoreString:r,value:n}){const{setTo:i,tiebreakAt:a,NoAD:o}=e?.setFormat||{},s=n===parseInt(a||i);if(a&&a<i&&n>a)return{scoreString:r};if(o&&n===i||n>i)return{scoreString:r};const c=s?n+1:n+1===i?n+(o?1:2):i,u=[n,c];2===t&&u.reverse();const d=eE.split("")[0];r=(r||"")+(u.join(hE)+(s?d:VA));const p={side1Score:u[0],side2Score:u[1]},l=AE({analysis:e,set:p});return p.winningSide=l||void 0,{scoreString:r,set:p}}({analysis:f,lowSide:t,scoreString:n,value:Ed(r)});a&&(a.setNumber=i?.length+1||1),i=i?.concat(a).filter(Boolean)||[a],n=e||void 0}else console.log("error: unknown outcome")}else(!f.isSetTiebreakEntry||f.isSetTiebreakEntry&&!f.isNumericEnding)&&(d=!0,({scoreString:n,sets:i}=bE({analysis:f,scoreString:n,sets:i,lowSide:t})),o=void 0);if(d){i=i?.filter(Boolean);const{matchUpWinningSide:e}=ME({sets:i,winningSide:a,matchUpStatus:o,matchUpFormat:s});return a=e,!e||o&&![Qm,Wm].includes(o)?!n||a||[KA,QA,ZA].includes(o)||(o=void 0):(o="COMPLETED",i=i.filter((e=>{const{side1Score:t,side2Score:r,side1TiebreakScore:n,side2TiebreakScore:i}=e;return t||r||n||i}))),{updated:d,scoreString:n,sets:i,winningSide:a,matchUpStatus:o,info:p}}return{updated:d,scoreString:n,sets:i,winningSide:a,matchUpStatus:o,info:p}},parseMatchUpFormat:QI,parseScoreString:Xb,redo:function({matchUp:e}){const{history:t=[],undoHistory:r=[]}=OE({matchUp:e});return r.length&&t.push(r.pop()),FE({matchUp:e,history:t,undoHistory:r})},reverseScore:function(e){if(!e?.score)return{error:Za};const{sets:t}=e.score,r=t.map((e=>{const{side1TiebreakScore:t,side2TiebreakScore:r,winningSide:n,side1Score:i,side2Score:a,setNumber:o}=e;return Mf({winningSide:n?3-n:void 0,side1TiebreakScore:r,side2TiebreakScore:t,side1Score:a,side2Score:i,setNumber:o})}));return{reversedScore:{sets:r,scoreStringSide1:sw({sets:r}),scoreStringSide2:sw({sets:r,reversed:!0})},...Ni}},setServingSide:function({matchUp:e,sideNumber:t}){if(![1,2].includes(t))return{error:Qa};const{history:r=[]}=OE({matchUp:e});return r.push({srv:t}),FE({matchUp:e,history:r})},stringifyMatchUpFormat:iv,tidyScore:function(e){if(!e.score)return{error:ys};const{score:t,sheetName:r,identifier:n,fileName:i,stepLog:a,fullLog:o,profile:s}=e,c=[];let u,d,p,l=[],m=t;const f=e=>{e.forEach((e=>{p=kA[e]({profile:s,identifier:n,matchUpStatus:u,attributes:d,applied:l,score:m});const t=p.score!==m;t&&c.push({method:e,score:p.score}),a&&(o||t||p.matchUpStatus!==u)&&(u?console.log({score:p.score,matchUpStatus:u},e):console.log({score:p.score},e)),p.matchUpStatus&&(u=p.matchUpStatus),p.attributes&&(d=p.attributes),p.applied&&(l=p.applied),m=p.score}))};f(xA);let h=DA(m);return h||(m=t.toString().replace(/\D/g,""),d?.removed&&(d.removed=void 0),f(LA),h=DA(m),h||(m="")),l.forEach((e=>{_A[e]||(_A[e]=0),_A[e]+=1})),{matchUpStatus:u?.toUpperCase(),modifications:c,attributes:d,isValid:h,score:m}},umo:{},undo:function({matchUp:e}){const{history:t=[],undoHistory:r=[]}=OE({matchUp:e});return r.push(t.pop()),FE({matchUp:e,history:t,undoHistory:r})},updateTieMatchUpScore:fw,validateScore:ZD,validateTieFormat:pv});function _E({drawDefinition:e,auditData:t}){const{extension:r}=Wl({name:wi,element:e});gd({element:e,extension:{name:wi,value:Array.isArray(r?.value)?r?.value.concat(t):[t]}})}function xE({updateInProgressMatchUps:e=!1,tournamentRecord:t,collectionOrder:r,collectionName:n,tieFormatName:i,drawDefinition:o,matchUpFormat:s,matchUpCount:u,collectionId:d,matchUpType:p,structureId:l,matchUpId:m,category:f,eventId:h,gender:g,event:I,collectionValueProfiles:U,collectionValue:y,matchUpValue:v,scoreValue:T,setValue:P}){const D="modifyCollectionDefinition";if(s&&!_r({matchUpFormat:s}))return a({result:{error:ys},context:{matchUpFormat:s},stack:D});if(n&&"string"!=typeof n)return a({result:{error:ys},context:{collectionName:n},stack:D});if(g&&!Object.values(Gf).includes(g))return a({result:{error:ys},context:{gender:g},stack:D});if(f&&"object"!=typeof f)return a({result:{error:ys},context:{category:f},stack:D});const w={collectionValueProfiles:U,collectionValue:y,matchUpValue:v,scoreValue:T,setValue:P};if(!(Object.values(w).filter(Boolean).length||r||n||s||u||p))return a({result:{error:Za},stack:D});if(Object.values(w).filter(Boolean).length>1)return a({info:"Only one value assignment allowed per collectionDefinition",result:{error:ys},stack:D});let b=Gn({drawDefinition:o,structureId:l,matchUpId:m,eventId:h,event:I});if(b.error)return a({result:b,stack:D});const{matchUp:R,structure:N,tieFormat:M}=b,A=ir(M),E=M?.collectionDefinitions.find((e=>e.collectionId===d)),C=A?.collectionDefinitions.find((e=>e.collectionId===d));if(!E)return a({info:"source collectionDefinition",result:{error:ws},context:{collectionId:d},stack:D});const O=y??v??T??P;if(U){const e=Bn({matchUpCount:u??E?.matchUpCount??0,collectionValueProfiles:U});if(e.errors)return a({result:{error:ys},info:e.errors,stack:D})}else if(O&&!Fe(O))return a({result:{error:ys},info:"value is not an integer",context:{value:O},stack:D});const F=U&&(!E.collectionValueProfiles||(k=E.collectionValueProfiles,_=U,!(c(Object.keys(k),Object.keys(_)).length===Object.keys(k).length&&c(Object.values(k),Object.values(_)).length===Object.values(k).length)));var k,_;const x=[];if((Fe(y)&&E.collectionValue!==y||Fe(v)&&E.matchUpValue!==v||Fe(T)&&E.scoreValue!==T||Fe(P)&&E.setValue!==P||F)&&(C.collectionValueProfiles=void 0,C.collectionValue=void 0,C.matchUpValue=void 0,C.scoreValue=void 0,C.setValue=void 0,Object.assign(C,w),x.push({collectionId:d,...S(w)})),(Fe(T)||Fe(P))&&C.collectionGroupNumber){const e=C.collectionGroupNumber;A.collectionDefinitions=A.collectionDefinitions.map((t=>{const{collectionGroupNumber:r,...n}=t;return r===e?n:t})),A.collectionGroups=A.collectionGroups.filter((({groupNumber:t})=>t!==e)),x.push({collectionId:d,change:"collectionGroupNumber removed"})}const{aggregateValue:L,valueGoal:V}=jn(A),B=S({aggregateValue:L,valueGoal:V});if(B.aggregateValue===M?.winCriteria.aggregateValue&&B.valueGoal===M?.winCriteria.valueGoal||(A.winCriteria=B,x.push({collectionId:d,winCriteria:B})),Fe(r)&&E.collectionOrder!==r&&(C.collectionOrder=r,x.push({collectionId:d,collectionOrder:r})),n&&E.collectionName!==n&&(C.collectionName=n,x.push({collectionId:d,collectionName:n})),s&&E.matchUpFormat!==s&&(C.matchUpFormat=s,x.push({collectionId:d,matchUpFormat:s})),Fe(u)&&E.matchUpCount!==u&&(C.matchUpCount=u,x.push({collectionId:d,matchUpCount:u})),p&&E.matchUpType!==p)return a({result:{error:bs},context:{matchUpType:p},stack:D});f&&E.category!==f&&(C.category=f,x.push({collectionId:d,category:f})),g&&E.gender!==g&&(C.gender=g,x.push({collectionId:d,gender:g}));const j=S(A);if(b=ar({tieFormat:j}),b.error)return a({result:b,stack:D});if(!x.length)return a({result:{...Ni,modifications:x}});if(M?.tieFormatName!==i?(j.tieFormatName=i,x.push({tieFormatName:i})):x.length&&(delete j.tieFormatName,x.push("tieFormatName removed: modifications without new tieFormatName")),b=qn({tieFormat:j,updateInProgressMatchUps:e,tournamentRecord:t,drawDefinition:o,structure:N,eventId:h,matchUp:R,event:I}),!b.error){const{appliedPolicies:e}=te({tournamentRecord:t});if(e?.audit?.[wi]){_E({drawDefinition:o,auditData:S({collectionDefinition:C,drawId:o?.drawId,action:D,structureId:l,matchUpId:m,eventId:h})})}}return a({result:{...b,modifications:x},stack:D})}function LE({updateInProgressMatchUps:e,originalValueGoal:t,tournamentRecord:r,wasAggregateValue:n,tieFormatName:i,drawDefinition:a,structureId:o,structure:s,tieFormat:c,matchUpId:u,matchUp:d,eventId:p,event:l}){const{aggregateValue:m,valueGoal:f}=Eb(c);c.winCriteria=Mf({aggregateValue:m,valueGoal:f}),(t&&t!==f||m&&!n)&&(i?c.tieFormatName=i:delete c.tieFormatName);const{targetMatchUps:h}=function({updateInProgressMatchUps:e,drawDefinition:t,structureId:r,structure:n,matchUpId:i,matchUp:a}){let o=[];return i&&a?o=[a]:r&&n?o=Kf({matchUpFilters:{matchUpTypes:[If]},structure:n})?.matchUps??[]:t&&(o=zU({matchUpFilters:{matchUpTypes:[If]},drawDefinition:t})?.matchUps??[]),{targetMatchUps:o.filter((t=>!t.winningSide&&t.matchUpStatus!==Vm&&(e||t.matchUpStatus!==$m&&!hg(t))))}}({updateInProgressMatchUps:e,drawDefinition:a,structureId:o,structure:s,matchUpId:u,matchUp:d});!function({updateInProgressMatchUps:e,tournamentRecord:t,drawDefinition:r,targetMatchUps:n,tieFormat:i,event:a}){for(const o of n){const n=!!o.tieFormat;let s;if(n&&(o.tieFormat=ir(i)),e){const e=te({tournamentRecord:t,drawDefinition:r,event:a}).appliedPolicies,n=pn({matchUpId:o.matchUpId,exitWhenNoValues:!0,tournamentRecord:t,appliedPolicies:e,drawDefinition:r,event:a});if(n.error)return n;s=n.score}n&&!s&&q({tournamentId:t?.tournamentId,context:"updateTargetTeamMatchUps",eventId:a?.eventId,matchUp:o,drawDefinition:r})}}({updateInProgressMatchUps:e,tournamentRecord:r,targetMatchUps:h,drawDefinition:a,tieFormat:c,event:l});const g=Mf(c),I=pv({tieFormat:g});if(I.error)return I;if(p&&l)l.tieFormat=g;else if(u&&d)d.tieFormat=c;else if(s)s.tieFormat=g;else if(a)a.tieFormat=g;else if(!d||!a)return{error:Li};return jp({drawDefinition:a,eventId:l?.eventId}),{...Ni}}function VE({drawDefinition:e,structureId:t,matchUpId:r,structure:n,matchUp:i,eventId:o,event:s}){const c="getTieFormat";let u;if(t=n?.structureId??t,((r=i?.matchUpId??r)||t)&&!e)return{error:Li};if(o&&s)u=Eg(s);else if(r){if(e&&(!i||!n)){const t=Jt({drawDefinition:e,matchUpId:r});if(t.error)return t;if(t.matchUp?.matchUpType!==gf)return a({result:{error:ja},stack:c});n||(n=t.structure),i||(i=t.matchUp)}u=Cg({item:i,drawDefinition:e,structure:n,event:s})||Cg({item:n,drawDefinition:e,structure:n,event:s})||Eg(e)||Eg(s)}else if(e&&t){if(!n){const r=w({drawDefinition:e,structureId:t});if(r.error)return r;n=r?.structure}u=Cg({item:n,drawDefinition:e,structure:n,event:s})||Eg(e)||Eg(s)}else u=Eg(e)||Eg(s);return u?{...Ni,structure:n,tieFormat:u,matchUp:i}:a({result:{error:ka},stack:c})}function BE({updateInProgressMatchUps:e=!0,collectionGroupNumber:t,tournamentRecord:r,drawDefinition:n,tieFormatName:i,structureId:a,matchUpId:o,matchUp:s,eventId:c,event:u}){if(!t)return{error:Za};if(isNaN(t))return{error:ys};const d="removeCollectionGroup";let p=s?void 0:VE({drawDefinition:n,structureId:a,matchUpId:o,eventId:c,event:u});if(p?.error)return pd({result:p,stack:d});const l=p?.structure;s=s??p?.matchUp;const m=p?.tieFormat,f=m?.winCriteria.valueGoal,h=m?.winCriteria.aggregateValue,g=QS(m);if(p=pv({tieFormat:g}),p.error)return pd({result:p,stack:d});const I=[];if(g.collectionDefinitions=g.collectionDefinitions.map((e=>{const{collectionGroupNumber:r,...n}=e;return r!==t?e:(I.push(e.collectionId),n)})),g.collectionGroups=g.collectionGroups.filter((({groupNumber:e})=>e!==t)),p=LE({updateInProgressMatchUps:e,originalValueGoal:f,wasAggregateValue:h,tournamentRecord:r,drawDefinition:n,tieFormatName:i,structureId:a,structure:l,tieFormat:g,matchUpId:o,matchUp:s,eventId:c,event:u}),!p.error){const{appliedPolicies:e}=Oh({tournamentRecord:r});if(e?.audit?.[wi]){_E({drawDefinition:n,auditData:Mf({drawId:n?.drawId,collectionGroupNumber:t,action:d,structureId:a,matchUpId:o,eventId:c})})}}return pd({result:{...p,modifiedCollectionIds:I},stack:d})}function jE({tieFormat:e,orderMap:t}){const r=QS(e);return r.collectionDefinitions.forEach((e=>{const r=t[e.collectionId];r&&(e.collectionOrder=r)})),r.collectionDefinitions.sort(((e,t)=>qd(e.collectionOrder)-qd(t.collectionOrder))),r}function GE({tournamentRecord:e,drawDefinition:t,structureId:r,matchUpId:n,orderMap:i,eventId:a,matchUp:o,event:s}){if("object"!=typeof i||!Object.values(i).every((e=>Vd(e))))return pd({result:{error:ys},context:{orderMap:i}});if(a&&s?.tieFormat)qE({tournamentRecord:e,event:s,orderMap:i});else if(n){const r=t&&xv({drawDefinition:t,matchUpId:n});if(r?.error)return r;if(!(o=r.matchUp))return{error:Ba};o?.tieFormat&&(o.tieFormat=jE({tieFormat:o.tieFormat,orderMap:i}),Vp({tournamentId:e?.tournamentId,eventId:s?.eventId,drawDefinition:t,matchUp:o}))}else if(r){const n=Om({drawDefinition:t,structureId:r});if(n.error)return n;const a=n.structure;if(a?.tieFormat)a.tieFormat=jE({tieFormat:a.tieFormat,orderMap:i}),WE({eventId:s?.eventId,tournamentRecord:e,drawDefinition:t,structure:a,orderMap:i}),jp({drawDefinition:t,structureIds:[a.structureId]});else if(t.tieFormat)$E({structureIds:[r],tournamentRecord:e,drawDefinition:t,orderMap:i,event:s});else{if(!s?.tieFormat)return{error:ws};qE({structureIds:[r],tournamentRecord:e,orderMap:i,event:s})}}else{if(!t?.tieFormat)return{error:ws};$E({tournamentRecord:e,drawDefinition:t,orderMap:i,event:s})}return{...Ni}}function qE({tournamentRecord:e,structureIds:t,orderMap:r,event:n}){const i=jE({tieFormat:n.tieFormat,orderMap:r});t?.length||(n.tieFormat=i);for(const i of n.drawDefinitions??[])$E({tournamentRecord:e,drawDefinition:i,structureIds:t,orderMap:r,event:n})}function $E({tournamentRecord:e,drawDefinition:t,structureIds:r,orderMap:n,event:i}){const a=jE({tieFormat:t.tieFormat??i?.tieFormat,orderMap:n});r?.length||(t.tieFormat=a);const o=[];for(const a of t.structures??[])r?.length&&!r.includes(a.structureId)||((a.tieFormat||r?.includes(a.structureId))&&(a.tieFormat=jE({tieFormat:a.tieFormat??t.tieFormat??i?.tieFormat,orderMap:n})),WE({eventId:i?.eventId,tournamentRecord:e,drawDefinition:t,structure:a,orderMap:n}),o.push(a.structureId));jp({drawDefinition:t,structureIds:o})}function WE({tournamentRecord:e,drawDefinition:t,structure:r,orderMap:n,eventId:i}){const a=Kf({matchUpFilters:{matchUpTypes:[If]},structure:r})?.matchUps;for(const r of a)r.tieFormat&&(r.tieFormat=jE({tieFormat:r.tieFormat,orderMap:n}),Vp({tournamentId:e?.tournamentId,drawDefinition:t,eventId:i,matchUp:r}))}function HE({updateInProgressMatchUps:e=!0,tieFormatComparison:t,tournamentRecord:r,drawDefinition:n,tieFormatName:i,collectionId:a,structureId:o,matchUpId:s,eventId:c,matchUp:u,event:d}){const p="removeCollectionDefinition";let l=u?void 0:Gn({drawDefinition:n,structureId:o,matchUpId:s,eventId:c,event:d});if(l?.error)return pd({result:l,stack:p});const m=l?.structure;u=u??l?.matchUp;const f=l?.tieFormat,h=ir(f);if(l=pv({tieFormat:h}),l.error)return pd({result:l,stack:p});const g=h?.collectionDefinitions?.find((e=>e.collectionId===a));if(!g)return pd({result:{error:ws,collectionId:a}});h.collectionDefinitions=h.collectionDefinitions.filter((e=>e.collectionId!==a)),g.collectionGroupNumber&&(h.collectionDefinitions=h.collectionDefinitions.map((e=>{const{collectionGroupNumber:t,...r}=e;return r})),h.collectionGroups=h.collectionGroups.filter((({groupNumber:e})=>e!==g.collectionGroupNumber)));const{aggregateValue:I,valueGoal:U}=jn(h);h.winCriteria=S({aggregateValue:I,valueGoal:U});const y=f?.winCriteria.valueGoal,v=f?.winCriteria.aggregateValue;(y&&y!==U||I&&!v)&&(i?h.tieFormatName=i:delete h.tieFormatName);let T=[];s&&u?T=[u]:o&&m?T=J({matchUpFilters:{matchUpTypes:[If]},structure:m})?.matchUps??[]:n?T=Dr({matchUpFilters:{matchUpTypes:[If]},drawDefinition:n})?.matchUps??[]:d&&(T=Hn({matchUpFilters:{matchUpTypes:[If]},drawDefinition:n})?.matchUps??[]);const P=(T||[]).filter((r=>{const n=r.tieMatchUps?.filter((e=>e.collectionId===a)),i=n?.some(Pr),o=!(!t||!r.tieFormat)&&Un({descendant:r.tieFormat,ancestor:h})?.different;return e&&!i||!r.winningSide&&r.matchUpStatus!==Vm&&(e||r.matchUpStatus!==$m&&!Pr(r)&&!o)}));if(!P.length)return{error:ps};const{appliedPolicies:D}=te({tournamentRecord:r});if(s&&u&&e){const e=u.tieMatchUps?.filter((e=>e.collectionId===a));for(const t of e??[]){let e=Wn({matchUpId:t.matchUpId,tieMatchUpId:u?.matchUpId,winningSide:void 0,removeScore:!0,tournamentRecord:r,appliedPolicies:D,drawDefinition:n,event:d});if(e.error)return e;if(e=Jt({drawDefinition:n,matchUpId:s}),e.error)return e;u=e?.matchUp}}const w=[];for(const t of P){for(const e of t?.sides??[])e.lineUp=(e.lineUp??[]).map((e=>({participantId:e.participantId,collectionAssignments:(e?.collectionAssignments??[]).filter((e=>e.collectionId!==a))})));if(t.tieMatchUps=(t.tieMatchUps??[]).filter((e=>{const t=e.collectionId===a;return t&&w.push(e.matchUpId),!t})),t.tieFormat&&(t.tieFormat=ir(h)),e){const e=pn({matchUpId:t.matchUpId,exitWhenNoValues:!0,tournamentRecord:r,appliedPolicies:D,drawDefinition:n,event:d});if(e.error)return e}q({tournamentId:r?.tournamentId,eventId:d?.eventId,drawDefinition:n,context:p,matchUp:t})}w.length&&H({tournamentId:r?.tournamentId,matchUpIds:w,eventId:d?.eventId,drawDefinition:n});const b=S(h);if(l=pv({tieFormat:b}),l.error)return pd({result:l,stack:p});if(c&&d)d.tieFormat=b;else if(s&&u)u.tieFormat=b;else if(m)m.tieFormat=b;else if(n)n.tieFormat=b;else if(!u||!n)return{error:Li};if($({drawDefinition:n,eventId:d?.eventId}),D?.audit?.[wi]){const e=S({drawId:n?.drawId,action:p,collectionId:a,structureId:o,matchUpId:s,eventId:c});$n({drawDefinition:n,auditData:e})}return{tieFormat:b,deletedMatchUpIds:w,targetMatchUps:P,...Ni}}function zE({updateInProgressMatchUps:e=!0,tournamentRecord:t,groupDefinition:r,drawDefinition:n,collectionIds:i,tieFormatName:a,structureId:o,matchUpId:s,matchUp:c,eventId:u,event:d}){const p="addCollectionGroup";if(!Array.isArray(i))return pd({result:{error:Za},stack:p});let l=c?void 0:VE({drawDefinition:n,structureId:o,matchUpId:s,eventId:u,event:d});if(l?.error)return pd({result:l,stack:p});const m=l?.structure;c=c||l?.matchUp;const f=l?.tieFormat,h=f?.winCriteria.valueGoal,g=QS(f);if(l=pv({tieFormat:g}),l.error)return pd({result:l,stack:p});for(const e of g.collectionDefinitions){const{collectionId:t,collectionGroupNumber:r}=e;if(r&&i.includes(t))return pd({info:"collectionIds cannot be part of other collectionGroups",result:{error:ys},stack:p})}const I=(g.collectionGroups||[]).reduce(((e,t)=>t.groupNumber>e?t.groupNumber:e),0)+1;return r.groupNumber=I,g.collectionDefinitions=g.collectionDefinitions.map((e=>i.includes(e.collectionId)?{...e,collectionGroupNumber:I}:e)),g.collectionGroups=[...g.collecitonGroups||[],r],LE({updateInProgressMatchUps:e,originalValueGoal:h,tournamentRecord:t,drawDefinition:n,tieFormatName:a,structureId:o,structure:m,tieFormat:g,matchUpId:s,matchUp:c,eventId:u,event:d})}function YE({updateInProgressMatchUps:e=!0,collectionDefinition:t,referenceCategory:r,tournamentRecord:n,policyDefinitions:i,enforceCategory:o,referenceGender:s,drawDefinition:c,tieFormatName:u,enforceGender:d,structureId:p,matchUpId:l,matchUp:m,eventId:f,uuids:h,event:g}){const I="addCollectionDefinition",U=te({tournamentRecord:n,drawDefinition:c,event:g}).appliedPolicies??{},y=i?.[Zu]??U?.[Zu];o=o??y?.participants?.enforceCategory;const v=!1!==(d??y?.participants?.enforceGender),T=!(!(r??g?.category)||!1===o),P=!(!(s??g?.gender)||!v),D=zn({referenceCategory:r??g?.category,collectionDefinition:t,referenceGender:s,checkCategory:T,checkGender:P,event:g});if(D.error)return a({result:D,stack:I});let w=m?.tieFormat?void 0:Gn({drawDefinition:c,structureId:p,matchUpId:l,eventId:f,event:g});if(w?.error)return a({result:{error:w.error},stack:I});const b=w?.structure;m=m??w?.matchUp;const R=m?.tieFormat??w?.tieFormat,N=ir(R);if(w=ar({tieFormat:N}),w?.error)return a({result:{error:w.error},stack:I});if(t.collectionId){if(N.collectionDefinitions.map((({collectionId:e})=>e)).includes(t.collectionId))return a({context:{collectionId:t.collectionId},result:{error:Ss}})}else t.collectionId=vt();N.collectionDefinitions.push(t),N.collectionDefinitions.sort(((e,t)=>(e.collectionOrder||0)-(t.collectionOrder||0))).forEach(((e,t)=>e.collectionOrder=t+1));const{aggregateValue:M,valueGoal:A}=jn(N);N.winCriteria=S({aggregateValue:M,valueGoal:A});const E=R?.winCriteria.valueGoal,C=R?.winCriteria.aggregateValue;(E&&E!==A||M&&!C)&&(u?N.tieFormatName=u:delete N.tieFormatName);const O=[],F=[];let k=[];const _=S(N);if(w=ar({tieFormat:_}),w?.error)return a({result:{error:w.error},stack:I});if(f&&g){g.tieFormat=_;for(const r of g.drawDefinitions??[])if(!r.tieFormat)for(const n of r.structures??[]){if(n.tieFormat)continue;const r=QE({updateInProgressMatchUps:e,collectionDefinition:t,structure:n,uuids:h});F.push(...r.newMatchUps),k.push(...r.targetMatchUps),O.push(n.structureId)}KE({modifiedMatchUps:k,eventId:g?.eventId,modifiedStructureIds:O,tournamentRecord:n,drawDefinition:c,addedMatchUps:F,stack:I})}else if(p&&b){b.tieFormat=_;const r=QE({updateInProgressMatchUps:e,collectionDefinition:t,structure:b,uuids:h});F.push(...r.newMatchUps),k=r.targetMatchUps,KE({modifiedMatchUps:k,eventId:g?.eventId,modifiedStructureIds:O,tournamentRecord:n,drawDefinition:c,addedMatchUps:F,stack:I})}else if(l&&m){if(!Yn({matchUp:m,updateInProgressMatchUps:e}))return a({result:{error:lo},stack:I});m.tieFormat=_;const r=gn({collectionDefinition:t,matchUp:m,uuids:h});Array.isArray(m.tieMatchUps)||(m.tieMatchUps=[]),m.tieMatchUps.push(...r),F.push(...r),KE({modifiedMatchUps:[m],eventId:g?.eventId,modifiedStructureIds:O,tournamentRecord:n,drawDefinition:c,addedMatchUps:F,stack:I})}else{if(!c)return{error:Li};c.tieFormat=_;for(const r of c.structures??[]){const n=QE({updateInProgressMatchUps:e,collectionDefinition:t,structure:r,uuids:h});O.push(r.structureId),F.push(...n.newMatchUps),k.push(...n.targetMatchUps)}KE({modifiedMatchUps:k,eventId:g?.eventId,tournamentRecord:n,drawDefinition:c,addedMatchUps:F,stack:I})}if(U?.audit?.[wi]){const e=S({drawId:c?.drawId,collectionDefinition:t,action:I,structureId:p,matchUpId:l,eventId:f});$n({drawDefinition:c,auditData:e})}return{tieFormat:_,targetMatchUps:k,addedMatchUps:F,...Ni}}function QE({updateInProgressMatchUps:e,collectionDefinition:t,structure:r,uuids:n}){const i=[],a=J({matchUpFilters:{matchUpTypes:[If]},structure:r})?.matchUps,o=a.filter((t=>Yn({matchUp:t,updateInProgressMatchUps:e})&&!t.tieFormat));for(const e of o){const r=gn({collectionDefinition:t,matchUp:e,uuids:n});Array.isArray(e.tieMatchUps)||(e.tieMatchUps=[]),e.tieMatchUps.push(...r),i.push(...r)}return{newMatchUps:i,targetMatchUps:o}}function KE({modifiedStructureIds:e,tournamentRecord:t,modifiedMatchUps:r,drawDefinition:n,addedMatchUps:i,eventId:a,stack:o}){W({tournamentId:t?.tournamentId,matchUps:i,drawDefinition:n,eventId:a}),r?.forEach((e=>{q({tournamentId:t?.tournamentId,drawDefinition:n,context:o,matchUp:e,eventId:a})})),$({structureIds:e,drawDefinition:n,eventId:a})}function JE({updateInProgressMatchUps:e=!1,tieFormatComparison:t,modifiedTieFormat:r,tournamentRecord:n,drawDefinition:i,structureId:o,matchUpId:s,eventId:c,uuids:u,event:d}){const p="modifyTieFormat";if(!ar({tieFormat:r}).valid)return a({result:{error:Ea},info:"falied validation",stack:p});const l=Gn({drawDefinition:i,structureId:o,matchUpId:s,eventId:c,event:d});if(l.error)return a({result:l,stack:p});const{matchUp:m,tieFormat:f}=l,g=ir(f),I=Un({descendant:r,ancestor:g});if(I.invalid)return a({context:{invalid:I.invalid},result:{error:Ea},stack:p});if(!I?.different)return a({result:{...Ni},info:"Nothing to do",stack:p});const U=g.collectionDefinitions.map((({collectionId:e})=>e)),y=r.collectionDefinitions.map((({collectionId:e})=>e)),S=U.filter((e=>!y.includes(e))),v=r.collectionDefinitions.filter((({collectionId:e})=>!U.includes(e))),T=v.map(ft("collectionId")),P=[];let D;const w=r.tieFormatName;for(const t of r.collectionDefinitions){if(T.includes(t.collectionId))continue;const r=Qn({updateInProgressMatchUps:e,...t,tournamentRecord:n,tieFormatName:w,drawDefinition:i,structureId:o,matchUpId:s,eventId:c,event:d});if(r.modifications&&P.push(...r.modifications),r.error)return a({result:r,stack:p});r.tieFormat&&(D=r.tieFormat)}for(const t of v){const r=Jn({updateInProgressMatchUps:e,collectionDefinition:t,tournamentRecord:n,drawDefinition:i,tieFormatName:w,structureId:o,matchUpId:s,matchUp:m,eventId:c,uuids:u,event:d});if(r.error)return a({result:r,stack:p});r.tieFormat&&(D=r.tieFormat)}for(const r of S){const u=Kn({updateInProgressMatchUps:e,tieFormatComparison:t,tournamentRecord:n,drawDefinition:i,tieFormatName:w,collectionId:r,structureId:o,matchUpId:s,eventId:c,matchUp:m,event:d});if(u.error)return a({result:u,stack:p});u.tieFormat&&(D=u.tieFormat)}return f?.tieFormatName!==w?(D.tieFormatName=w,P.push({tieFormatName:w})):(P.length||T.length||S.length)&&(delete D.tieFormatName,P.push("tieFormatName removed: modifications without new tieFormatName")),D.collectionDefinitions=D.collectionDefinitions.sort(((e,t)=>h(e.collectionOrder)-h(t.collectionOrder))).map(((e,t)=>({...e,collectionOrder:t+1}))),{processedTieFormat:ir(D),modifications:P,...Ni}}function ZE({tournamentRecord:e}){if(!e)return{error:Fi};let t=0;for(const r of e.events??[]){const n=r.tieFormats??[],i=e=>{if(!e.tieFormat)return;let r;for(const t of n){Un({descendant:e.tieFormat,ancestor:t}).different||(r=t.tieFormatId)}if(r)e.tieFormatId=r,delete e.tieFormat;else{const r=L(e.tieFormat,void 0,!0);r.tieFormatId||(r.tieFormatId=vt()),e.tieFormatId=r.tieFormatId,delete e.tieFormat,n.push(r),t+=1}},a=r.eventType;i({tieFormat:r.tieFormat,eventType:a});for(const e of r.drawDefinitions??[]){i({tieFormat:e.tieFormat,eventType:a});for(const t of e.structures??[])i({tieFormat:t.tieFormat,eventType:a})}const o=(t,n)=>{const i=c.matchUps?.find((e=>e.matchUpId===t));i&&(i.tieFormatId=n,delete i.tieFormat,q({tournamentId:e?.tournamentId,eventId:r.eventId,matchUp:i}))},s=e=>{const r=L(e.tieFormat,void 0,!0);r.tieFormatId||(r.tieFormatId=vt()),n.push(r),t+=1,o(e.matchUpId,r.tieFormatId)},c=Hn({matchUpFilters:{matchUpTypes:[gf]},event:r}),u=c.matchUps??[];for(const e of u){let t;for(const r of n){e.tieFormat&&Un({descendant:e.tieFormat,ancestor:r}).different||(t=r.tieFormatId)}t?o(e.matchUpId,t):s(e)}n.length&&(r.tieFormats=n)}return{...Ni,addedCount:t}}var XE=Object.freeze({__proto__:null,addCollectionDefinition:YE,addCollectionGroup:zE,aggregateTieFormats:ZE,modifyCollectionDefinition:xE,modifyTieFormat:JE,orderCollectionDefinitions:GE,removeCollectionDefinition:HE,removeCollectionGroup:BE}),eC=Object.freeze({__proto__:null,addCollectionDefinition:YE,addCollectionGroup:zE,aggregateTieFormats:ZE,compareTieFormats:$M,getTieFormat:HM,modifyCollectionDefinition:xE,modifyTieFormat:JE,mutate:XE,orderCollectionDefinitions:GE,query:zM,removeCollectionDefinition:HE,removeCollectionGroup:BE,tieFormatGenderValidityCheck:ZS,validateCollectionDefinition:dv});const tC={ABANDONED:"ABANDONED",ACTIVE:"ACTIVE",CANCELLED:"CANCELLED",COMPLETED:"COMPLETED",IN_PROGRESS:"IN_PROGRESS"};function rC({tournamentRecord:e,status:t}){return e?t&&!Object.keys(tC).includes(t)?{error:ys,info:"Unknown status"}:(e.tournamentStatus=t,{...Ni}):{error:Fi}}function nC(e){return"object"!=typeof e?{error:Za}:"object"!=typeof e.element?{error:ys}:e.notes?"string"==typeof e.notes||e.notes?.testing?(Object.assign(e.element,{notes:e.notes}),{...Ni}):{error:ys}:{error:Za}}function iC(e){return"object"!=typeof e?{error:Za}:"object"!=typeof e.element?{error:ys}:(e.element.notes&&delete e.element.notes,{...Ni})}function aC({tournamentRecord:e,onlineResource:t,organisationId:r,participantId:n,personId:i,courtId:o,venueId:s}){if(!e)return{error:Fi};if(!mt(t))return{error:Za};if(3!==c(Object.keys(t),["resourceSubType","resourceType","identifier"]).length)return a({result:{error:gs},context:{onlineResource:t}});if(r){if(e.parentOrganisation?.parentOrganisationId!==r)return a({result:{error:ws}});e.parentOrganisation.onlineResources||(e.parentOrganisation.onlineResources=[]),e.parentOrganisation.onlineResources.push(t)}else if(n||i){const r=(e.participants??[]).find((e=>i&&e.person?.personId===i||e.participantId===n));if(!r)return a(i?{result:{error:ws}}:{result:{error:wo}});if(i){if(r.person?.personId!==i)return a({result:{error:go}});r.person.onlineResources||(r.person.onlineResources=[]),r.person.onlineResources.push(t)}else r.onlineResources||(r.onlineResources=[]),r.onlineResources.push(t)}else if(o){const r=(e.venues??[]).filter((e=>!s||e.venueId===s)).flatMap((e=>(e.courts??[]).filter((e=>e.courtId===o))))?.[0];if(!r)return a({result:{error:zo}});r.onlineResources||(r.onlineResources=[]),r.onlineResources.push(t)}else if(s){const r=(e.venues??[]).find((e=>e.venueId===s));if(!r)return a({result:{error:Ko}});r.onlineResources||(r.onlineResources=[]),r.onlineResources.push(t)}else e.onlineResources||(e.onlineResources=[]),e.onlineResources.push(t);return{...Ni}}function oC({tournamentRecord:e,promotionalName:t,tournamentName:r,formalName:n}){return e?(r&&(e.tournamentName=r),t&&(e.promotionalName=t),n&&(e.formalName=n),e.promotionalName===e.tournamentName&&delete e.promotionalName,e.formalName===e.tournamentName&&delete e.formalName,{...Ni}):{error:Fi}}function sC({tournamentRecord:e,notes:t}){return e?nC({element:e,notes:t}):{error:Fi}}function cC({tournamentRecord:e,categories:t}){return e?(t=(t||[]).filter((e=>e.categoryName&&e.type)),e.tournamentCategories=t,{...Ni}):{error:Fi}}function uC({tournamentRecord:e,startDate:t,endDate:r}){if(!e)return{error:Fi};if(t&&!vc.test(t)||r&&!vc.test(r))return{error:io};if(!t&&!r)return{error:Xa};if(r&&t&&new Date(r)<new Date(t))return{error:ys};let n;(t&&e.startDate&&new Date(t)>new Date(e.startDate)||r&&e.endDate&&new Date(r)<new Date(e.endDate))&&(n=!0),t&&(e.startDate=t),r&&(e.endDate=r),t&&e.endDate&&new Date(t)>new Date(e.endDate)&&(e.endDate=t),r&&e.startDate&&new Date(r)<new Date(e.startDate)&&(e.startDate=r);const i=n&&function({tournamentRecord:e}){const t=yS({tournamentRecord:e}).matchUps??[],r=e.startDate&&new Date(e.startDate),n=e.endDate&&new Date(e.endDate),i=[],a=[];for(const e of t){const{schedule:t,matchUpId:o}=e;if(t&&t.scheduledDate){const e=new Date(t.scheduledDate);(r&&e<r||n&&e>n)&&(a.push(o),i.includes(t.scheduledDate)||i.push(t.scheduledDate))}}if(i.length){if(!jR({scheduledDates:i,tournamentRecord:e}).clearedScheduleCount)return{error:Wi}}return{unscheduledMatchUpIds:a}}({tournamentRecord:e})?.unscheduledMatchUpIds;return function({tournamentRecord:e}){if(!e)return{error:Fi};const{startDate:t,endDate:r}=e,n=Ec(t,r),i=[];for(const t of e.venues||[])t?.courts?.length&&i.push(...t.courts);for(const e of i){const{startTime:t,endTime:r}=(e.dateAvailability??[]).reduce(((e,t)=>{const r=kc(e.startTime),n=kc(e.endTime);return t.startTime&&kc(t.startTime)<r&&(e.startTime=t.startTime),t.endTime&&kc(t.endTime)>n&&(e.endTime=t.endTime),e}),{startTime:"08:00",endTime:"18:00"}),i=n.map((n=>{const i=e.dateAvailability?.find((e=>e.date===n));return i??{date:n,startTime:t,endTime:r}})),a=e.dateAvailability?.find((e=>!e.date));a&&i.unshift(a),e.dateAvailability=i}}({tournamentRecord:e}),rc({topic:wp,payload:{startDate:t,endDate:r}}),{...Ni,unscheduledMatchUpIds:i}}function dC({tournamentRecord:e,startDate:t}){return uC({tournamentRecord:e,startDate:t})}function pC({tournamentRecord:e,endDate:t}){return uC({tournamentRecord:e,endDate:t})}var lC=Object.freeze({__proto__:null,addDrawDefinitionExtension:Ud,addEventExtension:yd,addEventTimeItem:pg,addExtension:gd,addNotes:nC,addOnlineResource:aC,addParticipantExtension:Sd,addParticipantTimeItem:ug,addTimeItem:cg,addTournamentExtension:Id,addTournamentTimeItem:dg,removeDrawDefinitionExtension:Td,removeEventExtension:Pd,removeExtension:fd,removeNotes:iC,removeParticipantExtension:Dd,removeTournamentExtension:vd,setTournamentCategories:cC,setTournamentDates:uC,setTournamentEndDate:pC,setTournamentName:oC,setTournamentNotes:sC,setTournamentStartDate:dC,setTournamentStatus:rC}),mC=Object.freeze({__proto__:null,addDrawDefinitionExtension:Ud,addEventExtension:yd,addEventTimeItem:pg,addExtension:gd,addNotes:nC,addOnlineResource:aC,addParticipantExtension:Sd,addParticipantTimeItem:ug,addTimeItem:cg,addTournamentExtension:Id,addTournamentTimeItem:dg,analyzeDraws:kI,analyzeTournament:jM,getAllowedDrawTypes:_M,getAllowedMatchUpFormats:kM,getAppliedPolicies:Oh,getCompetitionDateRange:AN,getCompetitionPenalties:LM,getPolicyDefinitions:Fh,getTournamentInfo:MN,getTournamentPenalties:xM,getTournamentPersons:VM,getTournamentStructures:dh,getTournamentTimeItem:og,mutate:lC,query:GM,removeDrawDefinitionExtension:Td,removeEventExtension:Pd,removeExtension:fd,removeNotes:iC,removeParticipantExtension:Dd,removeTournamentExtension:vd,setTournamentCategories:cC,setTournamentDates:uC,setTournamentEndDate:pC,setTournamentName:oC,setTournamentNotes:sC,setTournamentStartDate:dC,setTournamentStatus:rC}),fC=Object.freeze({__proto__:null,generateCourts:wD});function hC(e){if(!e?.tournamentRecord&&!Array.isArray(e?.venueMatchUps))return{error:Fi};if(!e?.courtId)return{error:Ja};const{scheduleVisibilityFilters:t,tournamentRecord:r,matchUpFilters:n,venueMatchUps:i,courtId:a}=e,{schedulingProfile:o}=Xn({tournamentRecord:r});if(Array.isArray(i))return{matchUps:c({matchUps:i,courtId:a})};const{matchUps:s}=Lt({scheduleVisibilityFilters:t,tournamentRecord:r,matchUpFilters:n});return{matchUps:c({matchUps:s,courtId:a})};function c({matchUps:e,courtId:t}){const r=e.filter((e=>{const r=e.schedule?.allocatedCourts?.map((({courtId:e})=>e));return e.schedule?.courtId===t||r?.includes(t)}));return Zn({matchUps:r,schedulingProfile:o})}}function gC(e){return parseInt(e)}function IC({startTime:e="",endTime:t=""}={}){if(!(e&&t&&Tc.test(e)&&Tc.test(t)))return!1;const[r,n]=e.split(":").map(gC),[i,a]=t.split(":").map(gC);return!(i<r)&&!(r===i&&a<n)}function UC(e,t){const[r,n]=e.startTime.split(":").map(gC),[i,a]=t.startTime.split(":").map(gC);return r<i?-1:r>i?1:n<a?-1:n>a?1:0}function yC({tournamentRecord:e,dateAvailability:t,disableNotice:r,venueMatchUps:n,courtId:i,force:a}){if(!e)return{error:Fi};if(!i)return{error:Ja};const o=function({dateAvailability:e}){if(!e)return{error:no};if(!Array.isArray(e))return{error:ro};const t="Times must be 24 hour => 00:00";for(const r of e){if("object"!=typeof r)return{error:ro};const{date:e,startTime:n,endTime:i,bookings:a=[]}=r;if(!n||!i)return{error:ro};if(e&&!vc.test(e))return{error:io,dateAvailability:{date:e},info:"Dates must be formated => YYYY-MM-DD"};if(!Tc.test(n))return{error:ao,dateAvailability:{startTime:n},info:t};if(!Tc.test(i))return{error:ao,dateAvailability:{endTime:i},info:t};if(n===i)return{error:ao,dateAvailability:{startTime:n,endTime:i},info:"startTime and endTime are equivalent"};if(!IC({startTime:n,endTime:i}))return{error:ao,dateAvailability:{startTime:n,endTime:i},info:"endTime must be after startTime"};if(a){if(!Array.isArray(a))return{error:to};for(const e of a){if("object"!=typeof e)return{error:to};const{startTime:r,endTime:n}=e;if(!Tc.test(r))return{error:ao,booking:{startTime:r},info:t};if(!Tc.test(n))return{error:ao,booking:{endTime:n},info:t};if(r===n)return{error:ao,dateAvailability:{startTime:r,endTime:n},info:"startTime and endTime are equivalent"};if(!IC({startTime:r,endTime:n}))return{error:ao,dateAvailability:{startTime:r,endTime:n},info:"endTime must be after startTime"}}}}return{valid:!0}}({dateAvailability:t});if(o.error)return o;const{updatedDateAvailability:s,totalMergeCount:c}=function(e){let t=0;const r=e.reduce(((e,t)=>{const{date:r,startTime:n,endTime:i,bookings:a}=t;return e[r]||(e[r]=[]),e[r].push({startTime:n,endTime:i,bookings:a}),e}),{}),n=[];return Object.keys(r).forEach((e=>{r[e].sort(UC);const{mergedAvailability:i,mergeCount:a}=function(e){let t,r,n,i=e.length,a=0;const o=[];for(;e.length&&i;){const s=e.shift(),{startTime:c,endTime:u,bookings:d}=s;if(i-=1,t){if(Wc($c(r),$c(c),!1)>0){const e={startTime:t,endTime:r};n?.length&&(e.bookings=n),o.push(e),t=c,n=d,r=u}else d&&(n?n.push(d):n=d),r=u,a+=1}else t=c,n=d,r=u}const s={startTime:t,endTime:r};n?.length&&(s.bookings=n);return o.push(s),{mergedAvailability:o,mergeCount:a}}(r[e]);n.push(...i.map((t=>({date:e,...t})))),t+=a})),{updatedDateAvailability:n,totalMergeCount:t}}(t);t=s;const u=Ub({tournamentRecord:e,courtId:i});if(u.error)return u;const{court:d,venue:p}=u,{matchUps:l}=hC({tournamentRecord:e,venueMatchUps:n,courtId:i});if(l?.length){const t=Oh({tournamentRecord:e})?.appliedPolicies,r=a??t?.[nd]?.allowDeletionWithScoresPresent?.courts,n=[];n.length&&(r||console.log("throw error: scheduled court matchUps",n.length))}return d&&(d.dateAvailability=t,!r&&p&&rc({payload:{venue:p,tournamentId:e.tournamentId},topic:bp,key:p.venueId})),{...Ni,totalMergeCount:c}}function SC({matchUpsCount:e=0}){return{error:Fs,info:`Schedule would be deleted from ${e} ${1===e?"matchUp":"matchUps"}; use { force: true }`}}function vC({tournamentRecord:e,drawDefinition:t,matchUpId:r,drawId:n}){if(!r)return{error:_a};if(!t&&!n)return{error:ra};let i;if(!t){if(!e)return{error:Fi};({drawDefinition:t}=ly({tournamentRecord:e,drawId:n}))}if(t)({matchUp:i}=xv({drawDefinition:t,matchUpId:r}));else{if(!e)return{error:Fi};const t=yS({tournamentRecord:e,inContext:!1}).matchUps??[];({matchUp:i}=function({matchUps:e,matchUpId:t}){return{matchUp:(e||[]).find((e=>e.matchUpId===t))}}({matchUps:t,matchUpId:r}))}if(!i)return{error:La};if(i.timeItems){i.timeItems.find((e=>[uI,cI].includes(e.itemType)))&&(i.timeItems=i.timeItems.filter((({itemType:e})=>![uI,cI].includes(e))),Vp({tournamentId:e?.tournamentId,context:"removeCourtAssignment",drawDefinition:t,matchUp:i}))}return{...Ni}}function TC(e){if("string"!=typeof e?.venueId)return{error:Jo};const{tournamentRecord:t,venueId:r,force:n}=e,i=e.tournamentRecords||t&&{[t.tournamentId]:t}||{};if(!Object.keys(i).length)return{error:Fi};const a=SS({tournamentRecords:i,contextFilters:{venueIds:[r]}}).matchUps??[],o=Oh({tournamentRecord:t})?.appliedPolicies,s=n??o?.[nd]?.allowDeletionWithScoresPresent?.venues;if(a.length&&!s)return SC({matchUpsCount:a.length});for(const e of Object.values(i)){for(const t of a){const r=vC({matchUpId:t.matchUpId,drawId:t.drawId,tournamentRecord:e});if(r.error)return r}let t;e.venues=(e.venues??[]).filter((e=>e?.venueId!==r||(t=!0,!1))),t&&rc({payload:{venueId:r,tournamentId:e.tournamentId},topic:hp,key:r})}return BT({tournamentRecords:i}),{...Ni}}function PC({tournamentRecord:e,venueIds:t,force:r}){if(!e)return{error:Fi};if(!Array.isArray(t))return{error:ys};for(const n of e.venues||[]){const{venueId:i}=n;if(t.includes(i)){const{venueId:t}=n,i=TC({tournamentRecord:e,venueId:t,force:r});if(i.error)return i}}return{...Ni}}function DC(e){const{courtIds:t,dates:r}=e,n=US(e),i=uy(e,[{[gu]:!0,[Au]:!0}]);if(i.error)return i;for(const e of Object.values(n))wC({tournamentRecord:e,courtIds:t,dates:r});return{...Ni}}function wC({tournamentRecord:e,courtIds:t,dates:r}){const n=!Array.isArray(r)||!r.length||{dates:r},i=e=>gd({extension:{value:n,name:oi},creationTime:!1,element:e});for(const r of e.venues||[])for(const e of r.courts||[])if(t?.includes(e.courtId)){const t=i(e);if(t.error)return t}return{...Ni}}function bC(e){const{tournamentRecords:t,tournamentId:r,venueIds:n}=e,i=uy(e,[{[gu]:!0,[Eu]:!0}]);if(i.error)return i;const a=Object.keys(t).filter((e=>!r||e===r));for(const e of a){RC({tournamentRecord:t[e],venueIds:n})}return{...Ni}}function RC({tournamentRecord:e,venueIds:t}){for(const r of e.venues||[])if(t?.includes(r.venueId)){const e=gd({creationTime:!1,element:r,extension:{name:oi,value:!0}});if(e.error)return e}return{...Ni}}function NC(e){const t=US(e),r=[{[gu]:!0}];!e.enableAll&&r.push({[Au]:!0});const n=uy(e,r);if(n.error)return n;const{enableAll:i,courtIds:a,dates:o}=e;for(const e of Object.values(t))MC({tournamentRecord:e,courtIds:a,enableAll:i,dates:o});return{...Ni}}function MC({tournamentRecord:e,courtIds:t,enableAll:r,dates:n}){for(const i of e.venues||[])for(const e of i.courts||[])if(r||t?.includes(e.courtId))if(Array.isArray(n)){const{extension:t}=Wl({element:e,name:oi});if(t){const r=t.value;Array.isArray(r.dates)&&(r.dates=r.dates.filter((e=>!n.includes(e)))),gd({extension:{name:oi,value:r},creationTime:!1,element:e})}}else fd({element:e,name:oi});return{...Ni}}function AC(e){const t=US(e),r=[{[gu]:!0}];!e.enableAll&&r.push({[Eu]:!0});const n=uy(e,r);if(n.error)return n;const{venueIds:i,enableAll:a}=e;for(const e of Object.values(t))for(const t of e.venues||[])(a||i?.includes(t.venueId))&&fd({element:t,name:oi});return{...Ni}}function EC(e){const{courtId:t,disableNotice:r,force:n}=e,i=US(e),a=uy(e,[{[gu]:!0,[Ou]:!0}]);if(a.error)return a;let o,s;for(const e of Object.values(i)){if(s=CC({tournamentRecord:e,disableNotice:r,courtId:t,force:n}),s.error&&s.error!==zo)return s;s.success&&(o=!0)}return o?{...Ni}:s}function CC({tournamentRecord:e,disableNotice:t,courtId:r,force:n}){const i=Ub({tournamentRecord:e,courtId:r});if(i.error)return i;const a=i.venue,{matchUps:o}=hC({tournamentRecord:e,courtId:r}),s=Oh({tournamentRecord:e})?.appliedPolicies,c=n??s?.[nd]?.allowDeletionWithScoresPresent?.courts;if(o?.length&&!c)return SC({matchUpsCount:o.length});for(const t of o??[]){const r=vC({matchUpId:t.matchUpId,drawId:t.drawId,tournamentRecord:e});if(r.error)return r}return a&&(a.courts=(a.courts??[]).filter((e=>e.courtId!==r)),t||rc({payload:{venue:a,tournamentId:e.tournamentId},topic:bp,key:a.venueId})),{...Ni}}function OC(e){const{disableNotice:t,modifications:r,courtId:n,force:i,venueMatchUps:a}=e,o=bn(e);if(!Object.keys(o).length)return{error:Oi};let s;for(const e of Object.values(o)){const o=FC({tournamentRecord:e,disableNotice:t,venueMatchUps:a,modifications:r,courtId:n,force:i});if(o?.error)return o;s=!0}return s?{...Ni}:undefined}function FC({tournamentRecord:e,disableNotice:t,venueMatchUps:r,modifications:n,courtId:i,force:a}){if(!e)return{error:Fi};if(!i)return{error:Ja};if(!n||"object"!=typeof n)return{error:gs};const o=Ub({tournamentRecord:e,courtId:i});if(o.error)return o;const{venue:s,court:c}=o,u=Object.keys(Rn()).filter((e=>"courtId"!==e));if(!Object.keys(n).filter((e=>u.includes(e))).length)return{error:Ps};const d=u.filter((e=>!["dateAvailability"].includes(e))),p=Object.keys(n).filter((e=>d.includes(e)));if(c&&p.forEach((e=>Object.assign(c,{[e]:n[e]}))),n.dateAvailability){const o=yC({dateAvailability:n.dateAvailability,tournamentRecord:e,venueMatchUps:r,disableNotice:t,courtId:i,force:a});if(o.error)return o}return t||Je({payload:{venue:s,tournamentId:e.tournamentId},topic:bp,key:s?.venueId}),{...Ni,court:L(c)}}const kC=()=>({venueId:void 0,venueName:"",venueAbbreviation:"",onlineResources:[],venueType:void 0,addresses:[],contacts:[],courts:[],roles:[]});function _C(e){const{modifications:t,venueId:r,force:n}=e,i=US(e);if(!Object.keys(i).length)return{error:Oi};if("string"!=typeof r)return{error:Jo};let a,o;for(const e of Object.values(i)){const i=xC({tournamentRecord:e,modifications:t,venueId:r,force:n});if(i.success&&(o=!0),i.error&&(a=i.error),i.error&&i.error!==Ko)return i}return BT({tournamentRecords:i}),o?{...Ni}:{error:a}}function xC({tournamentRecord:e,modifications:t,venueId:r,force:n}){if(!e)return{error:Fi};if(!t||"object"!=typeof t)return{error:gs};if(!r)return{error:Jo};const i=Oh({tournamentRecord:e})?.appliedPolicies,a=n??i?.[nd]?.allowDeletionWithScoresPresent?.venues,{matchUps:o}=function({scheduleVisibilityFilters:e,tournamentRecord:t,matchUpFilters:r,venueId:n}){if(!t)return{error:Fi};if(!n)return{error:Jo};const{schedulingProfile:i}=Xn({tournamentRecord:t}),{matchUps:a}=Lt({scheduleVisibilityFilters:e,tournamentRecord:t,matchUpFilters:r});return{matchUps:function({matchUps:e,venueId:t}){const r=e.filter((e=>{const r=e.schedule?.allocatedCourts?.map((({venueId:e})=>e));return e.schedule?.venueId===t||r?.includes(t)}));return Zn({matchUps:r,schedulingProfile:i})}({matchUps:a,venueId:n})}}({tournamentRecord:e,venueId:r}),s=gb({tournamentRecord:e,venueId:r});if(s.error)return s;const c=s.venue,u=Object.keys(kC()).filter((e=>"venueId"!==e));if(!Object.keys(t).filter((e=>u.includes(e))).length)return{error:Ps};const d=u.filter((e=>!["courts","onlineResources"].includes(e))),p=Object.keys(t).filter((e=>d.includes(e)));c&&p.forEach((e=>Object.assign(c,{[e]:t[e]})));const l=c?.courts?.map((e=>e.courtId))??[],m=t.courts?.map((e=>e.courtId))||[],f=m.length&&l.filter((e=>!m.includes(e))),h=[];if(f.length){const t=c?.courts?.filter((e=>f.includes(e.courtId))),r=t?.map((t=>{const r=hC({courtId:t.courtId,tournamentRecord:e,venueMatchUps:o});for(const e of r.matchUps??[])h.push({matchUpId:e.matchUpId,drawId:e.drawId});return r.matchUps?.length??0})).reduce(((e,t)=>e+t));if(!c||r&&!a)return SC({matchUpsCount:r});c.courts=c.courts?.filter((e=>m.includes(e.courtId))),kR({schedule:{courtId:"",scheduledDate:""},matchUpDetails:h,removePriorValues:!0,tournamentRecord:e})}if(t.courts)for(const i of t.courts){const{courtId:t}=i||{};let a=OC({modifications:i,disableNotice:!0,tournamentRecord:e,venueMatchUps:o,courtId:t,force:n});if(a.error===zo&&(a=cN({disableNotice:!0,tournamentRecord:e,venueId:r,court:i})),a.error)return a}return BT({tournamentRecord:e}),c&&rc({payload:{venue:c,tournamentId:e.tournamentId},topic:bp,key:c?.venueId}),{...Ni,venue:Jc(c)}}var LC=Object.freeze({__proto__:null,addCourt:cN,addCourts:uN,addVenue:fb,deleteCourt:EC,deleteVenue:TC,deleteVenues:PC,disableCourts:DC,disableVenues:bC,enableCourts:NC,enableVenues:AC,modifyCourt:OC,modifyCourtAvailability:yC,modifyVenue:_C}),VC=Object.freeze({__proto__:null,addCourt:cN,addCourts:uN,addVenue:fb,deleteCourt:EC,deleteVenue:TC,deleteVenues:PC,disableCourts:DC,disableVenues:bC,enableCourts:NC,enableVenues:AC,generate:fC,generateCourts:wD,getCompetitionVenues:xT,getCourts:KM,getVenuesAndCourts:_T,modifyCourt:OC,modifyCourtAvailability:yC,modifyVenue:_C,mutate:LC,publicFindVenue:Ib,query:JM}),BC=Object.freeze({__proto__:null,competitionGovernor:uu,drawsGovernor:Jv,entriesGovernor:CT,eventGovernor:ID,generationGovernor:OD,matchUpFormatGovernor:FD,matchUpGovernor:Kb,mocksGovernor:VN,participantGovernor:vM,policyGovernor:Hv,publishingGovernor:FM,queryGovernor:ZM,reportGovernor:tA,scheduleGovernor:hA,scoreGovernor:kE,tieFormatGovernor:eC,tournamentGovernor:mC,venueGovernor:VC});const jC={reset:"",bright:"",dim:"",red:"",brightred:"",green:"",brightgreen:"",yellow:"",brightyellow:"",blue:"",brightblue:"",lightblue:"",magenta:"",brightmagenta:"",cyan:"",brightcyan:"",white:"",brightwhite:""},GC=[];function qC(e,t){"string"==typeof e&&(e={method:e}),(t||Ks())&&GC.push(e)}function $C(e){const t=function(e){const t=GC.slice();return e&&(GC.length=0),t}(e),r=t.map((e=>{const{color:t,keyColors:r,method:n,newline:i}=e,a=Object.keys(jC).includes(t)?jC[t]:jC.cyan,o=Object.keys(e).filter((e=>!["color","keyColors","method","newline"].includes(e))).map((t=>{const n=r&&Object.keys(r).includes(t)&&jC[r[t]]?jC[r[t]]:jC.brightwhite;return`${jC.white}${t}: ${n}${e[t]}`})).join(", ");return[i?"\n":"",a,n,n?.length<15?"\t\t":"\t",jC.white,o,jC.reset,"\n"].join("")}));r?.length&&console.log(...r)}const WC=["collectionId","collectionPosition","drawPositions","extensions","finishingPositionRange","finishingRound","isMock","matchUpId","matchUpStatus","matchUpStatusCodes","orderOfFinish","processCodes","roundNumber","tieFormat","tieMatchUps","roundPosition","score","sides","winnerMatchUpId","loserMatchUpId","matchUpDuration","winningSide"];function HC(e,t=".",r=[]){return"object"==typeof e&&Object.keys(e).reduce(((n,i)=>"object"!=typeof e[i]?(n[r.concat(i).join(t)]=e[i],n):Object.assign(n,HC(e[i],t,r.concat(i)))),{})}var zC=Object.freeze({__proto__:null,JSON2CSV:function(e,t){if(t&&"object"!=typeof t)return{error:ys};let{columnTransform:r={}}=t||{};const{includeTransformAccessors:n,includeHeaderRow:i=!0,returnTransformedJSON:a,removeEmptyColumns:o,onlyHeaderRow:s,columnAccessors:c=[],functionMap:u={},columnMap:d={},valuesMap:p={},context:l={},delimiter:m='"',columnJoiner:f=",",rowJoiner:h="\r\n",keyJoiner:g="."}=t||{};if(!Array.isArray(e)||!Array.isArray(c)||"object"!=typeof l||"object"!=typeof d||"object"!=typeof r||"object"!=typeof u||"object"!=typeof p||"string"!=typeof f||"string"!=typeof h||"string"!=typeof g||"string"!=typeof m)return{error:ys};r=Object.assign({},...Object.keys(r).reverse().map((e=>({[e]:Array.isArray(r[e])?r[e]:["string"==typeof r[e]&&r[e]].filter(Boolean)}))));const I=e.filter(Boolean).map((e=>HC(e,g))),U=Object.values(r).flat();n&&c.push(...U);const y=I.reduce(((e,t)=>Object.keys(t).every((t=>!e.includes(t)&&e.push(t)||!0))&&e),[]).filter((e=>!c?.length||c.includes(e))),S=Object.assign({},...Object.keys(r).reverse().map((e=>r[e].map((t=>({[t]:e}))).flat())).flat()),v=y.reduce(((e,t)=>{const r=S[t];return r?e.includes(r)||e.push(r):e.push(t),e}),[]).sort(((e,r)=>t?.sortOrder?t.sortOrder.includes(e)&&t.sortOrder.includes(r)&&t.sortOrder.indexOf(e)-t.sortOrder.indexOf(r)||!t.sortOrder.includes(r)&&-1:0));Object.keys(d).forEach((e=>!v.includes(e)&&v.unshift(e))),Object.keys(r).forEach((e=>!v.includes(e)&&v.unshift(e))),"object"==typeof l&&Object.keys(l).forEach((e=>!v.includes(e)&&v.unshift(e)));let T=v.map((e=>d[e]||e));if(s)return[T];const P=e=>`${m}${e}${m}`,D=[];let w=I.map((e=>Object.values(v.reduce(((t,n,i)=>{const a=r[n],o=(a?.length?e[a.find((t=>e[t]))]:e[n])||l?.[n]||"",s=p[n]?.[o]||o,c="function"==typeof u[n]?u[n](s):s;return t[n]=P(c),c&&(D[i]=(D[i]||0)+1),t}),{}))));const b=o&&[...D].map(((e,t)=>!e&&t)).filter(kd).reverse();if(b){const e=e=>e.filter(((e,t)=>!b.includes(t)));w=w.map(e),T=e(T)}const R=w.map((e=>e.join(f)));return a?R.map((e=>{const t=e.split(f);return Object.assign({},...t.map(((e,t)=>({[T[t]]:e}))))})):i?[T.map(P).join(f),...R].join(h):R.join(h)},UUID:bm,UUIDS:function(e=1){return Qd(0,e).map(bm)},allNumeric:tp,attributeFilter:zu,chunkArray:ep,chunkByNth:np,chunkSizeProfile:function e(t,[r,...n]){return t.length?[t.slice(0,r),...e(t.slice(r),[...n,r])]:[]},constantToString:wm,countValues:function(e){return Wd($d(e))},createMap:nu,dateTime:Kc,definedAttributes:Mf,dehydrateMatchUps:function({tournamentRecord:e}){if(!e)return{error:Fi};if("object"!=typeof e||!e.tournamentId)return{error:ys};const{matchUps:t}=yS({tournamentRecord:e,inContext:!1});if(t?.length){const r=function({tournamentRecord:e}){const t={};for(const r of e.events||[]){r.matchUpFormat&&(t[r.eventId]=r.matchUpFormat);for(const e of r.drawDefinitions||[]){e.matchUpFormat&&(t[e.drawId]=e.matchUpFormat);for(const r of e.structures||[]){r.matchUpFormat&&(t[r.structureId]=r.matchUpFormat);for(const e of r.structures||[])e.matchUpFormat&&(t[e.structureId]=e.matchUpFormat)}}}return t}({tournamentRecord:e});!function(e,t={}){for(const r of e){const{structureId:e,drawId:n,eventId:i}=r,a=t[e]||t[n]||t[i],o=r.matchUpFormat===a?void 0:r.matchUpFormat;for(const e of Object.keys(r))WC.includes(e)||delete r[e];r.sides&&r.drawPositions&&!r.tieMatchUps&&delete r.sides,o&&(r.matchUpFormat=o)}}(t,r)}return{...Ni}},extractAttributes:iu,flattenJSON:HC,generateDateRange:Ec,generateHashCode:function(e){if(null===e||"object"!=typeof e)return;const t=JSON.stringify(e),r=ou(e),n=t.split("").reduce(((e,t)=>e+t.charCodeAt(0)),0);return[t.length,r,n].map((e=>e.toString(36))).join("")},generateRange:Qd,generateTimeCode:BN,groupValues:Wd,hasAttributeValues:e=>t=>Object.keys(e).every((r=>t[r]===e[r])),instanceCount:$d,intersection:Jd,isConvertableInteger:Vd,isNumeric:kd,isOdd:_d,isPowerOf2:Cd,makeDeepCopy:Jc,matchUpSort:vS,nearestPowerOf2:Fd,nextPowerOf2:xd,noNulls:function(e){return Array.isArray(e)?e?.map((e=>null===e?void 0:e)):e},noNumeric:rp,numericSort:Ad,occurrences:function(e,t){return Array.isArray(t)&&t.reduce(((e,t)=>(e[t]=1+e[t]||1,e)),{})[e]||0},overlap:Xd,randomMember:Yd,randomPop:zd,shuffleArray:Gd,structureSort:fh,subSort:function(e,t,r,n){return Array.isArray(e)?[].concat(...e.slice(0,t),...e.slice(t,t+r).sort(n),...e.slice(t+r,e.length)):[]},undefinedToNull:function e(t,r){if(void 0===t)return null;if("object"!=typeof t||null===t)return t;const n=Object.keys(t);return Object.assign({},...n.map((n=>{return Array.isArray(t[n])?{[n]:r?t[n]:t[n].map((t=>e(t)))}:{[n]:r?(i=t[n],void 0===i?null:i):e(t[n])};var i})))},unique:jd,visualizeScheduledMatchUps:function({scheduledMatchUps:e,showGlobalLog:t}){GC.length=0;const r=e?.reduce(((e,{structureId:t})=>e.includes(t)?e:e.concat(t)),[]),n=Array.isArray(r)&&{...r.map((t=>{const{structureName:r,matchUpType:n}=e.find((e=>e.structureId===t));return{[t]:`${r} ${n}`}}))};r?.forEach((t=>{qC({color:"blue",method:"draw",structure:n[t],keyColors:{structure:"magenta"}},!0);const r=e.filter((e=>e.structureId===t)),i=Cf({matchUps:r})?.roundMatchUps||[];Object.keys(i).forEach((e=>{qC({roundNumber:e,keyColors:{roundNumber:"brightcyan"}},!0),i[e].forEach((({matchUpId:e,schedule:t})=>{qC({matchUpId:e,time:xc(t.scheduledTime),date:t.scheduledDate,venue:t.venueId,keyColors:{time:"brightcyan",date:"brightcyan",matchUpId:"yellow",venue:"magenta"}},!0)}))}))})),t&&$C()}});const YC={};function QC(e){const{mutationStatus:t,tournamentId:r,directives:n,timeStamp:i}=e||{},{topics:a}=sc();for(const e of[...a].sort(ZC)){const t=ic({topic:e});t&&cc({topic:e,notices:t})}t&&i&&a.includes(Rp)&&cc({notices:[{tournamentId:r,directives:n,timeStamp:i}],topic:Rp})}async function KC(e){const{mutationStatus:t,tournamentId:r,directives:n,timeStamp:i}=e||{},{topics:a}=sc();for(const e of[...a].sort(ZC)){const t=ic({topic:e});t&&await cc({topic:e,notices:t})}t&&i&&a.includes(Rp)&&cc({notices:[{tournamentId:r,directives:n,timeStamp:i}],topic:Rp})}const JC={[Cp]:5,[Ep]:5,[Op]:5,[Dp]:5,[Pp]:5,[Up]:5,[yp]:5,[Sp]:5,[vp]:1,[Fp]:1,[Tp]:5,[bp]:5,[Ip]:4,[fp]:4,[hp]:4,[gp]:4,[up]:3,[cp]:2};function ZC(e,t){return(JC[t]||0)-(JC[e]||0)}const{FACTORY:XC}=bi;function eO({timeStamp:e}){const t=pc(),r=tc();return r&&Object.values(t).forEach((t=>{!function({tournamentRecord:e,value:t}){const{extension:r}=Wl({element:e,name:XC});gd({element:e,extension:{name:XC,value:{...r?.value,...t}}})}({tournamentRecord:t,value:{version:"2.0.10",timeStamp:e}})})),r}function tO({methodName:e,params:t,start:r}){const n={error:Os,methodName:e},i=r?Date.now()-r:0;return ei({result:n,methodName:e,elapsed:i,params:t,engineType:"sync"}),n}function rO(e,t,r,n,i){delete e.success,delete e.error;const a=Date.now(),o=uc();r&&(r.activeTournamentId=o);const s=r?.tournamentRecord||dc(o),c="object"==typeof r?.tournamentRecord&&{[r?.tournamentRecord.tournamentId]:r.tournamentRecord}||pc(),u=r?Jc(r,void 0,!0):void 0,d=r?function(e,t){if(!1===t._middleware)return t;if(t.tournamentId&&!e[t.tournamentId])return{error:Fi};const r=t.drawId||t.matchUp?.drawId;if(r){const{event:n,drawDefinition:i,tournamentId:a}=ly({tournamentRecords:e,drawId:r});i&&(t.drawDefinition=i),a&&(t.tournamentId=a),n&&(t.event=n)}if(t.eventId&&!t.event){const{event:r,tournamentId:n}=ly({eventId:t.eventId,tournamentRecords:e});if(!r)return{error:ya};t.tournamentId=n,t.event=r}const n=t.tournamentId??uc();if(!n&&t)return t;const i=e[n];return n&&!i?{error:Fi}:i?(t.tournamentRecord=i,t):t}(c,r):void 0;if(d?.error)return d;const p=function({tournamentRecords:e,tournamentRecord:t,params:r,methodName:n,method:i}){if(Ks())return i({tournamentRecords:e,tournamentRecord:t,...r});try{return i({tournamentRecords:e,tournamentRecord:t,...r})}catch(e){return gc({engineName:"engine",methodName:n,params:r,err:e})}}({params:d,tournamentRecords:c,tournamentRecord:s,methodName:n,method:t});return function({engineType:e,methodName:t,elapsed:r,params:n,result:i}){const a=Ks();if("object"!=typeof a)return;const o={method:t},s=i?.error&&(!0===a.errors||Array.isArray(a.errors)&&a.errors.includes(t)),c=Array.isArray(a.params)&&a.params?.includes(t),u=a.params&&!Array.isArray(a.params)||c,d=Array.isArray(a.exclude)&&a.exclude.includes(t);!d&&![void 0,!1].includes(a.perf)&&!isNaN(a.perf)&&r>=a.perf&&(o.elapsed=r),d||!s&&!u||(o.params=n),!d&&(s||a.result&&!Array.isArray(a.result)&&(!Array.isArray(a.params)||c)||Array.isArray(a.result)&&a.result?.includes(t))&&(o.result=i),Object.keys(o).length>1&&Ic(o,e)}({result:p,methodName:n,elapsed:Date.now()-a,params:u,engineType:i}),p}function nO(e,t=!0){return"object"!=typeof e||Array.isArray(e)?{error:gs}:e?.tournamentId?it(t?L(e):e):{error:ys}}function iO(e,t=!0){if("object"!=typeof e)return{error:gs};if(Xe(),Array.isArray(e)){if(!(e.filter((e=>e?.tournamentId)).length===e.length))return{error:Ci};e=Object.assign({},...e.map((e=>({[e.tournamentId]:e}))))}else if(e?.tournamentId)e={[e.tournamentId]:e},Xe(e.tournamentId);else{if(!Object.keys(e).every((t=>e[t].tournamentId===t)))return{error:Ci}}return et(t?L(e):e)}async function aO(e,t){if(!ru(t))return{error:ys,message:"args must be an object"};const r=Object.values(t).filter(eu).length;if(r>1)return{message:"there must be only one arg with typeof function",error:ys};const n=r?Object.keys(t).find((e=>eu(t[e]))):tu(t.method)&&t.method;if(!n)return{error:Os};const{[n]:i,...a}=t,o=t?.params?{...t.params}:{...a},s=o.rollbackOnError&&Jc(pc(),!1,!0),c=i||e[n]||Ws()[n];if(!c)return tO({methodName:n,params:o});const u=await rO(e,c,o,n,"async")??{};u?.error&&s&&iO(s);const d=Date.now(),p=eO({timeStamp:d}),l=u?.success&&!0!==o?.delayNotify&&!0!==o?.doNotNotify;return l&&await KC({directives:[{method:c,params:o}],mutationStatus:p,timeStamp:d}),(l||!u?.success||o?.doNotNotify)&&oc(),u}function oO(e,t){return t?.error?(e.error=t.error,e.success=!1):(e.error=void 0,e.success=!0),e}function sO(e,t){e.importMethods=(r,n,i)=>function(e,t,r,n,i){if(!mt(r))return{error:ys};const a=Array.isArray(n)?n:[],o={},s=(e,t=0)=>{Object.keys(e).forEach((r=>{ht(e[r])?o[r]=e[r]:mt(e[r])&&(!0===n||a?.includes(r))&&(void 0===i||t<i)&&s(e[r],t+1)}))};return s(r),at(o),Object.keys(o).filter((e=>ht(o[e]))).forEach((r=>{e[r]=n=>{const i=()=>t(e,{[r]:o[r],...n});if(Ye())return i();try{return i()}catch(e){ot({engineName:"engine",methodName:r,params:n,err:e})}}})),{...Ni,...e}}(e,t,r,n,i),e.getTournament=e=>function(e){const{convertExtensions:t=!1,removeExtensions:r=!1}=e??{},n=e?.tournamentId??rt();if("string"!=typeof n)return{};const i=nt(n);return{tournamentRecord:L(i,t,!1,r)}}(e),e.getState=e=>function({convertExtensions:e,removeExtensions:t}){const r=tt();return{tournamentId:rt(),tournamentRecords:L(r,e,!1,t)}}({convertExtensions:e?.convertExtensions,removeExtensions:e?.removeExtensions}),e.version=()=>"2.0.10",e.reset=()=>(lc({}),oO(e)),e.devContext=t=>(Zs(t),oO(e)),e.getDevContext=e=>Ks(e),e.newTournamentRecord=(e={})=>{const t=$R(e),r=t.tournamentId;return t.error?t:(nO(t),mc(r),{...Ni,tournamentId:r})},e.setState=(t,r,n)=>{Xs(r,n);const i=iO(t,r);return oO(e,i)},e.setTournamentId=e=>mc(e),e.getTournamentId=()=>uc(),e.setTournamentRecord=(t,r,n)=>{Xs(r,n);const i=nO(t,r);return oO(e,i)},e.removeTournamentRecord=t=>{const r=fc(t);return oO(e,r)},e.removeUnlinkedTournamentRecords=()=>{const t=function(){const e=tt(),{extension:t}=s({name:fi,tournamentRecords:e,discover:!0}),r=t?.value?.tournamentIds||[];return Object.keys(e).forEach((t=>{r.includes(t)||delete e[t]})),et(e)}();return oO(e,t)}}function cO(e){const t=Qs();if(t.error&&!e)return t;const r={executionQueue:(e,t)=>async function(e,t,r){if(!Array.isArray(t))return{error:ys,message:"directives must be an array"};const n=nc(),i=Date.now(),a=r&&Jc(pc(),!1,!0),o=[];for(const r of t){if("object"!=typeof r)return{error:ys,message:"directive must be an object"};const{method:t,pipe:s}=r,c=r.params?{...r.params}:{};if(!n[t])return tO({methodName:t,start:i,params:c});if(s){const e=o[o.length-1],t=Object.keys(s);for(const r of t)e[r]&&(c[r]=e[r])}const u=rO(e,n[t],c,t,"async");if(u?.error)return a&&iO(a),{...u,rolledBack:!!a};o.push({...u,methodName:t})}const s=Date.now();return KC({directives:t,mutationStatus:eO({timeStamp:s}),timeStamp:s}),oc(),{success:o.every((e=>e.success)),results:o}}(r,e,t),execute:e=>aO(r,e)};return sO(r,aO),r}function uO(e,t){if(!ru(t))return{error:ys,message:"args must be an object"};const r=Object.values(t).filter(eu).length;if(r>1)return{message:"there must be only one arg with typeof function",error:ys};const n=r?Object.keys(t).find((e=>eu(t[e]))):tu(t.method)&&t.method;if(!n)return{error:Os};const{[n]:i,...a}=t,o=t?.params?{...t.params}:{...a},s=o.rollbackOnError&&Jc(pc(),!1,!0),c=i||e[n]||Ws()[n];if(!c)return tO({methodName:n,params:o});const u=rO(e,c,o,n,"sync")??{};u?.error&&s&&iO(s);const d=Date.now(),p=eO({timeStamp:d}),l=u?.success&&!0!==o?.delayNotify&&!0!==o?.doNotNotify;return l&&QC({directives:[{method:c,params:o}],mutationStatus:p,timeStamp:d}),(l||!u?.success||o?.doNotNotify)&&oc(),u}const dO=(()=>{const e={executionQueue:(t,r)=>function(e,t,r){if(!Array.isArray(t))return{error:ys,message:"directives must be an array"};const n=nc(),i=Date.now(),a=r&&Jc(pc(),!1,!0),o=[];for(const r of t){if("object"!=typeof r)return{error:ys,message:"directive must be an object"};if(r.params&&"object"!=typeof r.params)return{error:ys,message:"params must be an object"};const{method:t,pipe:s}=r,c=r.params?{...r.params}:{};if(!n[t])return tO({methodName:t,start:i,params:c});if(s){const e=o[o.length-1],t=Object.keys(s);for(const r of t)e[r]&&(c[r]=e[r])}const u=rO(e,n[t],c,t,"sync");if(u?.error)return a&&iO(a),{...u,rolledBack:!!a};o.push({...u,methodName:t})}const s=Date.now();return QC({directives:t,mutationStatus:eO({timeStamp:s}),timeStamp:s}),oc(),{success:o.every((e=>e.success)),results:o}}(e,t,r),execute:t=>uO(e,t)};return sO(e,uO),e})();function pO(e,t){if(!ru(t))return{error:ys,message:"args must be an object"};const r=Object.values(t).filter(eu).length;if(r>1)return{message:"there must be only one arg with typeof function",error:ys};const n=r?Object.keys(t).find((e=>eu(t[e]))):tu(t.method)&&t.method;if(!n)return{error:Os};const{[n]:i,...a}=t,o=t?.params?{...t.params}:{...a},s=i||e[n]||Ws()[n];return s?rO(e,s,o,n,"ask"):tO({methodName:n,params:o})}const lO=(()=>{const e={execute:t=>pO(e,t)};return sO(e,pO),e})();let mO,fO={};function hO(e,t=!0){if(!e)return{error:Za};if("object"!=typeof e)return{error:gs};if(e.matchUpId)mO=e.matchUpId,fO[mO]=t?Jc(e):e;else if(Array.isArray(e))for(const r of e.reverse())r.matchUpId&&(fO[r.matchUpId]=t?Jc(r):r,mO||(mO=r.matchUpId));else for(const r of Object.values(e))r.matchUpId&&(fO[r.matchUpId]=t?Jc(r):r,mO||(mO=r.matchUpId));return t?Jc(e):e}const gO=(()=>{const e={getState:e=>function(e){return Jc(fO[mO],e?.convertExtensions,!1,e?.removeExtensions)}(e),version:()=>"2.0.10",reset:()=>(mO=void 0,fO={},{...Ni}),drawId:void 0,error:void 0,success:!1,devContext:t=>(Zs(t),e),setState:(t,r,n)=>{Xs(r,n);return function(t){t?.error?(e.error=t.error,e.success=!1):(e.error=void 0,e.success=!0,e.drawId=t.drawId);return e}(hO(t))}};return function(r){r.forEach((r=>{Object.keys(r).forEach((n=>{e[n]=e=>{if(Ks())return t({params:e,governor:r,methodName:n});try{return t({params:e,governor:r,methodName:n})}catch(t){gc({engineName:"matchUpEngine",methodName:n,params:e,err:t})}}}))}))}([kE]),e;function t({params:t,governor:r,methodName:n}){e.error=void 0,e.success=!1;const i=t?.matchUp||fO[mO],a=t?.matchUps||Object.values(fO),o=t?.rollbackOnError&&Jc(i,!1,!0);t={...t,matchUpId:i?.matchUpId,matchUps:a,matchUp:i};const s=r[n](t);if(s?.error)return o&&hO(o),{...s,rolledBack:!!o};const c=s?.success&&!0!==t?.delayNotify&&!0!==t?.doNotNotify;return c&&QC(),(c||!s?.success||t?.doNotNotify)&&oc(),s}})();let IO=!1;const UO=(()=>{const e={version:()=>"2.0.10",setDeepCopy:(t,r)=>(Xs(t,r),e),devContext:t=>(Zs(t),IO=!0,e)};return function(t){t.forEach((t=>{Object.keys(t).forEach((r=>{e[r]=e=>{try{const n=function(e,t){const r=e({...t});r?.error||QC();oc(),IO&&(Zs(!1),IO=!1);return r}(t[r],e);return!n?.error&&e?.setState&&n?.tournamentRecord&&iO(n.tournamentRecord),n}catch(t){let n;"string"==typeof t?n=t.toUpperCase():t instanceof Error&&(n=t.message),console.log("ERROR",{params:JSON.stringify(e),method:r,error:n})}}}))}))}([VN]),e})();dO.importMethods(BC,!0,1);const yO=dO,SO=dO;function vO(e,t){return e&&t&&Array.isArray(t)&&t[e-1]||"object"==typeof t&&t[e]}function TO(e){const{participation:t={},awardProfiles:r,startDate:n,eventType:i,drawSize:a,drawType:o,category:s,endDate:c,level:u}=e,{participationOrder:d,flightNumber:p,rankingStage:l}=t;return{awardProfile:r.find((e=>(e=>!n&&!c||!e.dateRanges||e.dateRanges.some((e=>{const t=!n||!e.startDate||new Date(n)>new Date(e.startDate),r=!c||!e.endDate||new Date(c)<=new Date(e.endDate);return t&&r})))(e)&&(!e.maxFlightNumber||p<=e.maxFlightNumber)&&(!e.drawTypes?.length||e.drawTypes?.includes(o))&&(!e.drawSizes?.length||e.drawSizes.includes(a))&&(!e.stages?.length||e.stages.includes(l))&&(!e.levels?.length||e.levels.includes(u))&&(!e.maxDrawSize||a<=e.maxDrawSize)&&(!e.drawSize||e.drawSize===a)&&(!e.maxLevel||u<=e.maxLevel)&&(!p||!e.flights?.flightNumbers?.length||e.flights.flightNumbers.includes(p))&&(!e.participationOrder||e.participationOrder===d)&&(!e.category?.ageCategoryCodes||e.category.ageCategoryCodes.includes(s?.ageCategoryCode))&&(!e.eventTypes?.length||e.eventTypes?.includes(i))))}}function PO({participantWon:e,flightNumber:t,valueObj:r,drawSize:n,flights:i,level:a}){const o=(e,t)=>{const r=e?.value||e?.v||(Vd(e)?e:0),n=vO(a,e?.level),i=((e,t)=>{if(e){if(Array.isArray(t)){const r=t.find((t=>t.flight===e||t.f===e));return r.value||r.v}if("object"==typeof t){const r=t.flights||t.f;if(Array.isArray(r))return r[e-1]}}})(t,n);return{value:i||Vd(n)&&n||r}};let s,c,u,d,p=0;const l=(e?"won":!1===e&&"lost")||void 0;if(Array.isArray(r)){let e=r.find((e=>e.drawSize===n||e.drawSizes?.includes(n))),i=r.find((e=>e.drawSize&&e.threshold&&n>e.drawSize)),a=r.find((e=>!e.drawSize&&!e.drawSizes?.length));void 0!==l&&(e=e?.[l],i=i?.[l],a=a?.[l]),c=o(e,t).value,u=o(i,t).value,d=o(a,t).value,p=c||u||d,s=c&&e.requireWin||u&&i.requireWin||a?.requireWin}else if("object"==typeof r){let e=r?.drawSizes?.[n],i=r;void 0!==l&&(e=e?.[l],i=i?.[l]),c=o(e,t).value,d=o(i,t).value,p=c||d,s=c?e.requireWin:i?.requireWin}else Vd(r)&&void 0===l&&(p=r);return t&&i?.pct?.[t]&&(p=Math.round(p*i.pct[t])),{awardPoints:p,requireWin:s}}const DO={getTournamentPoints:function({participantFilters:e,policyDefinitions:t,tournamentRecord:r,saveRankings:n,level:i}){if(!r)return{error:Fi};const{policyDefinitions:a}=Fh({policyTypes:[Xu],tournamentRecord:r}),o=t?.[Xu]??a?.[Xu];if(!o)return{error:qa};const s=o.awardProfiles;let c=o.requireWinFirstRound;const u=o.requireWinForPoints,{participants:d,derivedEventInfo:p,derivedDrawInfo:l,mappedMatchUps:m}=OS({withRankingProfile:!0,participantFilters:e,tournamentRecord:r}),f=d?.filter((e=>e.draws?.length)),h={},g={},I={};for(const e of f??[]){const{participantType:t,participantId:n,person:a,draws:o}=e;for(const d of o){const{drawId:o,structureParticipation:f,eventId:U}=d,y=p[U],S=l[o],v=S?.drawType,{category:T,eventType:P}=y||{},D=d.startDate||y.startDate||r.startDate,w=d.endDate||y.endDate||r.endDate;if(P===Yf&&n!==hm)continue;let b;if(s){let r,d=u,p=0,l=0,U=0;for(const a of f){const{finishingPositionRange:o,participationOrder:u,participantWon:f,flightNumber:h,rankingStage:g,winCount:I}=a;p+=I||0;const y=S?.drawSize,{awardProfile:R}=TO({awardProfiles:s,participation:a,eventType:P,startDate:D,category:T,drawSize:y,drawType:v,endDate:w,level:i});if(R){if(!y)continue;const e=Array.isArray(o)&&Math.max(...o),t=jd(o||[]).join("-"),n=e&&g!==$p&&o?.includes(y);void 0!==R.requireWinForPoints&&(d=R.requireWinForPoints),void 0!==R.requireWinFirstRound&&(c=R.requireWinFirstRound);const{finishingPositionPoints:a={},finishingPositionRanges:s,finishingRound:p,pointsPerWin:m,flights:S}=R,v=Array.isArray(R.perWinPoints)?R.perWinPoints?.find((e=>e.participationOrders?.includes(u))):R.perWinPoints,T=a.participationOrders;let P,D=0;if((!T||T.includes(u))&&s&&e){const t=s[e];t&&({awardPoints:D,requireWin:P}=PO({flightNumber:h,valueObj:t,drawSize:y,flights:S,level:i}))}if(!D&&p&&1===u&&e){const t=p[e];t&&({awardPoints:D,requireWin:P}=PO({participantWon:f,flightNumber:h,valueObj:t,drawSize:y,flights:S,level:i}))}if(n&&void 0!==c&&(d=c),void 0!==P&&(d=P),D>l&&(!d||I)&&(l=D,r=e),!D&&m&&I&&(U+=I*m,r=t),!D&&I&&v){const e=vO(i,v?.level);e?U+=I*e:v.value&&(U+=I*v.value)}}if(b=l+U,t===hm){const t=(e.matchUps||[]).filter((({structureId:e})=>e===a.structureId));for(const{matchUpId:e}of t){const t=m[e],r=t.sides.find((e=>e.participantId===n)).sideNumber;if(t.winningSice===r)for(const e of t.tieMatchUps)e.winningSide}}}if(U||l){const e={winCount:p,positionPoints:l,rangeAccessor:r,perWinPoints:U,eventType:P,drawId:o,points:b},i=a?.personId;i?(h[i]||(h[i]=[]),h[i].push(e)):t===Um?(I[n]||(I[n]=[]),I[n].push(e)):t===hm&&(g[n]||(g[n]=[]),g[n].push(e))}}}}if(n){gd({element:r,extension:{name:Ui,value:{personPoints:h,teamPoints:g,pairPoints:I}}})}return{participantsWithOutcomes:f,personPoints:h,pairPoints:I,teamPoints:g,...Ni}}};const wO={nSpread:400,diffThreshold:.125,kCalc:e=>250/Math.pow(e+5,.4),kMultiplier:function(e=3,t=2){const r=e/t;return isNaN(r)?wO.kDefault():r},kDefault:()=>1};function bO(e){let{winnerRating:t,loserRating:r,ratingRange:n}=e;const{ratings:i=Tv,winnerCountables:a=1,loserCountables:o=0,ratingType:s=Uv,maxCountables:c,countables:u}=e||{},d=i?.[s];if(!d)return{error:Za};n=d.range||n,t=t||d.defaultInitialization,r=r||d.defaultInitialization;const p=n[0]>n[1],l=d.decimalsCount||0,m=p?n.slice().reverse():n,f=(e,t)=>parseFloat(t)>=Math.min(...e)&&parseFloat(t)<=Math.max(...e);f(n,t)&&f(n,r)||(f(n,t)||(t=d.defaultInitialization),f(n,r)||(r=d.defaultInitialization));const h=({value:e,sourceRange:t,targetRange:r})=>(e-t[0])*(r[1]-r[0])/(t[1]-t[0])+r[0],g=h({targetRange:Tv[Uv].range,sourceRange:m,value:p?n[0]-t:t}),I=h({targetRange:Tv[Uv].range,sourceRange:m,value:p?n[0]-r:r}),U=(e,t)=>1/(1+Math.pow(10,(t-e)/wO.nSpread)),y=U(g,I),S=U(I,g),v=wO.kCalc(a),T=wO.kCalc(o),P=wO.kMultiplier(c,u),D=g+P*v*(1-y),w=I+P*T*(0-S),b=h({sourceRange:Tv[Uv].range,value:D,targetRange:m}),R=h({sourceRange:Tv[Uv].range,value:w,targetRange:m}),N=p?n[0]-b:b;let M=parseFloat(parseFloat(N).toFixed(l));const A=p?n[0]-R:R;let E=parseFloat(parseFloat(A).toFixed(l));const C=Math.max(...n)?Math.abs(t-r)/Math.max(...n):0;return(b>R&&C>wO.diffThreshold||M<0||E<0)&&(M=t,E=r),{newWinnerRating:M,newLoserRating:E}}const RO={calculateNewRatings:bO,generateDynamicRatings:function({removePriorValues:e=!0,tournamentRecord:t,ratingType:r=Uv,considerGames:n,matchUpIds:i,asDynamic:a}){if(!t)return{error:Fi};if(!Array.isArray(i))return{error:Va};if("string"!=typeof r)return{error:ys,ratingType:r};if(!Tv[r])return{error:ys};const o=Tv[r],{accessor:s}=o,c={},u=yS({matchUpFilters:{matchUpIds:i,matchUpStatuses:rf},tournamentRecord:t,inContext:!0}).matchUps??[];u.sort(vS);for(const i of u){const{endDate:o,matchUpFormat:u,score:p,sides:l,winningSide:m}=i,f=i.matchUpType,h={eventType:f,scaleName:r,scaleType:lu},g=`${r}.${du}`,I={scaleName:g,eventType:f,scaleType:lu},U=Object.assign({},...(l??[]).map((e=>{const{sideNumber:t,participant:r}=e;return t&&{[t]:[r?.participantId,...r?.individualParticipantIds??[]].filter(Boolean).flat()}}))),y=a?g:r,S=Object.assign({},...Object.values(U).flat().map((e=>{const{scaleItem:r}=EU({scaleAttributes:I,tournamentRecord:t,participantId:e}),{scaleItem:n}=EU({tournamentRecord:t,scaleAttributes:h,participantId:e});return e&&{[e]:r??n??{scaleName:y,eventType:f,scaleDate:o,scaleType:lu,scaleValue:s?{[s]:void 0}:void 0}}}))),v=u?QI(u):{},T=v?.bestOf||1,P=n?T&(v?.setsTo||1):T,D=p?.sets&&(d=p.sets,d?.reduce(((e,t)=>(t.winningSide&&(e[t.winningSide-1]+=1),e)),[0,0])||[0,0])||1===m&&[1,0]||[0,1],w=m?U[m]:[],b=m?U[3-m]:[];for(const n of w){const i=S[n]?.scaleValue,a="object"==typeof i?i[s]:i;for(const o of b){const c=S[o]?.scaleValue,u="object"==typeof c?c[s]:c,d=m?D[m]:[0,0],p=m?D[3-m]:[0,0],{newWinnerRating:l,newLoserRating:f}=bO({winnerCountables:d,loserCountables:p,maxCountables:P,winnerRating:a,loserRating:u,ratingType:r}),h=s?{...i,[s]:l}:l,g=s?{...c,[s]:f}:f;S[n].scaleValue=h,S[o].scaleValue=g;let I=fN({participantId:n,removePriorValues:e,tournamentRecord:t,scaleItem:{...S[n],scaleName:y}});if(I.error)return I;if(I=fN({participantId:o,removePriorValues:e,tournamentRecord:t,scaleItem:{...S[o],scaleName:y}}),I.error)return I}}Object.assign(c,S)}var d;const p=u.map((({matchUpId:e})=>e));return{...Ni,modifiedScaleValues:c,processedMatchUpIds:p}}},NO={...DO,...RO};dO.importMethods(NO);const MO=dO,AO={ratingsParameters:Tv,matchUpFormats:BI,countryToFlag:kU,tieFormats:cD,countries:_U,policies:{POLICY_AVOIDANCE_COUNTRY:{[id]:{roundsToSeparate:void 0,policyName:"Nationality Code",policyAttributes:[{key:"person.nationalityCode"},{key:"individualParticipants.person.nationalityCode"}]}},POLICY_POSITION_ACTIONS_DEFAULT:Gy,POLICY_POSITION_ACTIONS_DISABLED:{[Ju]:{policyName:"positionActionsDisabled",enabledStructures:!1}},POLICY_POSITION_ACTIONS_NO_MOVEMENT:{[Ju]:{policyName:"positionActionsNoMovement",enabledStructures:[{stages:[],stageSequences:[],enabledActions:[Fy,Oy,ky],disabledActions:[]}]}},POLICY_POSITION_ACTIONS_UNRESTRICTED:{[Ju]:{policyName:"positionActionsUnrestricted",enabledStructures:[],otherFlightEntries:!0,disableRoundRestrictions:!0,activePositionOverrides:[Fy,Ey]}},POLICY_PRIVACY_DEFAULT:{[td]:{policyName:"Participant Privacy Policy",participant:{contacts:!1,individualParticipants:{onlineResources:!1,participantName:!0,participantOtherName:!0,participantId:!0,participantRole:!0,participantStatus:!0,penalties:!1,representing:!0,participantRoleResponsibilities:!1,participantType:!0,person:{addresses:!1,biographicalInformation:!1,birthDate:!1,contacts:!1,nationalityCode:!0,nativeFamilyName:!1,nativeGivenName:!1,onlineResources:!1,otherNames:!0,parentOrganisationId:!1,passportFamilyName:!1,passportGivenName:!1,personId:!1,personOtherIds:!1,previousNames:!1,sex:!1,standardFamilyName:!0,standardGivenName:!0,status:!1,tennisId:!1,wheelchair:!0}},individualParticipantIds:!0,onlineResources:!1,participantName:!0,participantOtherName:!0,participantId:!0,participantRole:!0,participantStatus:!0,penalties:!1,representing:!0,participantRoleResponsibilities:!1,participantType:!0,person:{addresses:!1,biographicalInformation:!1,birthDate:!1,contacts:!1,nationalityCode:!0,nativeFamilyName:!1,nativeGivenName:!1,onlineResources:!1,otherNames:!0,parentOrganisationId:!1,passportFamilyName:!1,passportGivenName:!1,personId:!1,personOtherIds:!1,previousNames:!1,sex:!1,standardFamilyName:!0,standardGivenName:!0,status:!1,tennisId:!1,wheelchair:!0}}}},POLICY_ROUND_NAMING_DEFAULT:kf,POLICY_SCHEDULING_DEFAULT:$w,POLICY_SCORING_DEFAULT:{[ad]:{defaultMatchUpFormat:LI,allowDeletionWithScoresPresent:{drawDefinitions:!1,structures:!1},requireAllPositionsAssigned:!1,processCodes:{incompleteAssignmentsOnDefault:["RANKING.IGNORE"]},stage:{[qp]:{stageSequence:{1:{requireAllPositionsAssigned:!0}}}}}},POLICY_SCORING_USTA:{[ad]:{requireAllPositionsAssigned:!1,stage:{[qp]:{stageSequence:{1:{requireAllPositionsAssigned:!0}}}},defaultMatchUpFormat:LI,matchUpFormats:[{description:"Best of 3 tiebreak sets",matchUpFormat:LI,categoryNames:[],categoryTypes:[]},{description:"Two tiebreak sets, 7-point match tiebreak at one set all",matchUpFormat:"SET3-S:6/TB7-F:TB7"},{description:"Two tiebreak sets, 10-point match tiebreak at one set all",matchUpFormat:"SET3-S:6/TB7-F:TB10"},{description:"One standard tiebreak set to 6, 7-point tiebreak at 6 games all",matchUpFormat:"SET1-S:6/TB7"},{description:"Best of 3 sets to 4",matchUpFormat:"SET3-S:4/TB7"},{description:"Two out of three short sets to 4 with 5-point tiebreak at 3 games all",matchUpFormat:"SET3-S:4/TB5@3"},{description:"One short set to 4, 7-point tiebreak at 4 games all",matchUpFormat:"SET1-S:4/TB7"},{description:"One short set to 4, 5-point tiebreak at 3 games all",matchUpFormat:"SET1-S:4/TB5@3"},{description:"Two short sets to 4, 10-point match tiebreak at one set all",matchUpFormat:"SET3-S:4/TB7-F:TB10"},{description:"Two short sets to 4, 7-point match tiebreak at one set all",matchUpFormat:"SET3-S:4/TB7-F:TB7"},{description:"One no advantage set to 5, tiebreak to 9 at 4-4",matchUpFormat:"SET1-S:5/TB9@4"},{description:"One set to 6 with deciding game at 5 games all",matchUpFormat:"SET1-S:6NOAD"},{description:"One short set to 4, deciding game is played at 3 games all",matchUpFormat:"SET1-S:4NOAD"},{description:"Two short sets to 4 with deciding game at 3-3, 7-point match tiebreak at one set all",matchUpFormat:"SET3-S:4NOAD-F:TB7"},{description:"8 game pro-set with 7 point tiebreak at 8 games all",matchUpFormat:"SET1-S:8/TB7"},{description:"8 game pro-set with 7 point tiebreak at 7 games all",matchUpFormat:"SET1-S:8/TB7@7"},{description:"Best of 3 10-point tiebreak games",matchUpFormat:"SET3-S:TB10"},{description:"One 10-point tiebreak game",matchUpFormat:"SET1-S:TB10"},{description:"Timed 20 minute game - game based",matchUpFormat:"SET1-S:T20"}]}},POLICY_SEEDING_ITF:{[od]:{seedingProfile:{positioning:el},validSeedPositions:{ignore:!0},duplicateSeedNumbers:!0,drawSizeProgression:!0,policyName:"ITF SEEDING",seedsCountThresholds:[{drawSize:4,minimumParticipantCount:3,seedsCount:2},{drawSize:16,minimumParticipantCount:12,seedsCount:4},{drawSize:32,minimumParticipantCount:24,seedsCount:8},{drawSize:64,minimumParticipantCount:48,seedsCount:16},{drawSize:128,minimumParticipantCount:97,seedsCount:32},{drawSize:256,minimumParticipantCount:192,seedsCount:64}]}},POLICY_SEEDING_DEFAULT:zv},flagIOC:function(e){return kU(Object.assign({},..._U.filter((e=>e.ioc)).map((e=>({[e.ioc]:e.iso}))))[e])}},EO={COACHING:"Coaching",BALL_ABUSE:"Ball Abuse",RACKET_ABUSE:"Racket Abuse",VERBAL_ABUSE:"Verbal Abuse",PHYSICAL_ABUSE:"Physical Abuse",INELIGIBILITY:"INELIGIBILITY",UNSPORTSMANLIKE_CONDUCT:"Unsportmanlike Conduct",PROHIBITED_SUBSTANCE:"PROHIBITED_SUBSTANCE",DRESS_CODE_VIOLATION:"Dress Code Violation",EQUIMENT_VIOLATION:"Equipment Violation",LEAVING_THE_COURT:"Leaving the court",REFUSAL_TO_PLAY:"REFUSAL_TO_PLAY",FAILURE_TO_COMPLETE:"Failure to complete",NO_SHOW:"No Show",OTHER:"Other",PUNCTUALITY:"Puncuality",FAILUIRE_TO_SIGN_IN:"Failure to sign in"},CO={CLAY:"CLAY",HARD:"HARD",GRASS:"GRASS",CARPET:"CARPET",ARTIFICIAL:"ARTIFICIAL"},OO={INDOOR:"INDOOR",OUTDOOR:"OUTDOOR"};var FO=Object.freeze({__proto__:null,activeMatchUpStatuses:nf,auditConstants:YT,completedMatchUpStatuses:rf,directingMatchUpStatuses:ef,drawDefinitionConstants:jl,entryStatusConstants:pm,errorConditionConstants:_s,eventConstants:Qf,extensionConstants:bi,flightConstants:SD,genderConstants:Gf,keyValueConstants:PE,matchUpActionConstants:mS,matchUpStatusConstants:of,matchUpTypes:Uf,nonDirectingMatchUpStatuses:tf,particicipantsRequiredMatchUpStatuses:Zm,participantConstants:vm,participantRoles:tT,participantTypes:Sm,penaltyConstants:EO,policyConstants:ud,positionActionConstants:xy,ratingConstants:vv,recoveryTimeRequiredMatchUpStatuses:Jm,requestConstants:pR,resultConstants:Mi,scaleConstants:hu,scheduleConstants:Lw,sortingConstants:PD,surfaceConstants:CO,tieFormatConstants:iD,timeItemConstants:CI,topicConstants:kp,tournamentConstants:tC,upcomingMatchUpStatuses:af,validMatchUpStatuses:Xm,venueConstants:OO});export{nf as activeMatchUpStatuses,lO as askEngine,cO as asyncEngine,YT as auditConstants,yO as competitionEngine,uu as competitionGovernor,rf as completedMatchUpStatuses,ef as directingMatchUpStatuses,jl as drawDefinitionConstants,Jv as drawsGovernor,CT as entriesGovernor,pm as entryStatusConstants,_s as errorConditionConstants,Qf as eventConstants,ID as eventGovernor,bi as extensionConstants,FO as factoryConstants,AO as fixtures,SD as flightConstants,YC as forge,Gf as genderConstants,OD as generationGovernor,Uc as globalState,BC as governors,PE as keyValueConstants,mS as matchUpActionConstants,gO as matchUpEngine,FD as matchUpFormatCode,FD as matchUpFormatGovernor,Kb as matchUpGovernor,of as matchUpStatusConstants,Uf as matchUpTypes,UO as mocksEngine,VN as mocksGovernor,tf as nonDirectingMatchUpStatuses,Zm as particicipantsRequiredMatchUpStatuses,vm as participantConstants,vM as participantGovernor,tT as participantRoles,Sm as participantTypes,EO as penaltyConstants,ud as policyConstants,Hv as policyGovernor,xy as positionActionConstants,FM as publishingGovernor,ZM as queryGovernor,vv as ratingConstants,Jm as recoveryTimeRequiredMatchUpStatuses,tA as reportGovernor,pR as requestConstants,Mi as resultConstants,hu as scaleConstants,MO as scaleEngine,Lw as scheduleConstants,hA as scheduleGovernor,kE as scoreGovernor,PD as sortingConstants,CO as surfaceConstants,dO as syncEngine,iD as tieFormatConstants,eC as tieFormatGovernor,CI as timeItemConstants,zC as tools,kp as topicConstants,tC as tournamentConstants,SO as tournamentEngine,mC as tournamentGovernor,af as upcomingMatchUpStatuses,zC as utilities,Xm as validMatchUpStatuses,OO as venueConstants,VC as venueGovernor,ti as version};
2
- //# sourceMappingURL=index.mjs.map
1
+ var ow=Object.defineProperty;var ne=(t,e)=>{for(var r in e)ow(t,r,{get:e[r],enumerable:!0})};function xa(){return"2.0.11"}var CA={};ne(CA,{competitionGovernor:()=>mE,drawsGovernor:()=>dN,entriesGovernor:()=>TN,eventGovernor:()=>_N,generationGovernor:()=>FN,matchUpFormatGovernor:()=>VT,matchUpGovernor:()=>iD,mocksGovernor:()=>xg,participantGovernor:()=>wD,policyGovernor:()=>mN,publishingGovernor:()=>jD,queryGovernor:()=>AP,reportGovernor:()=>YD,scheduleGovernor:()=>nM,scoreGovernor:()=>lg,tieFormatGovernor:()=>lM,tournamentGovernor:()=>EM,venueGovernor:()=>_M});var mE={};ne(mE,{getLinkedTournamentIds:()=>kc,getTournamentIds:()=>zu,linkTournaments:()=>sE,mutate:()=>uE,query:()=>pE,unlinkTournament:()=>cE,unlinkTournaments:()=>aE});var uE={};ne(uE,{linkTournaments:()=>sE,unlinkTournament:()=>cE,unlinkTournaments:()=>aE});var uC={};ne(uC,{addNotice:()=>Tt,callListener:()=>em,createInstanceState:()=>jy,cycleMutationStatus:()=>Ml,deepCopyEnabled:()=>Dl,deleteNotice:()=>dI,deleteNotices:()=>yi,disableNotifications:()=>Yy,enableNotifications:()=>Nl,getDevContext:()=>Tr,getMethods:()=>Cl,getNotices:()=>mI,getProvider:()=>lI,getTopics:()=>Fr,getTournamentId:()=>Hi,getTournamentRecord:()=>Rl,getTournamentRecords:()=>Eo,globalLog:()=>zy,handleCaughtError:()=>Wu,removeTournamentRecord:()=>Ky,setDeepCopy:()=>Oc,setDevContext:()=>bc,setGlobalLog:()=>cC,setMethods:()=>qy,setStateProvider:()=>ww,setSubscriptions:()=>Fw,setTournamentId:()=>Hu,setTournamentRecord:()=>$y,setTournamentRecords:()=>rm,timeKeeper:()=>Lw});var R={success:!0},iw="error",qM={SUCCESS:R,ERROR:iw};var qg={message:"Chronological error; time violation.",code:"ANACHRONISM"},wA={message:"Cannot remove main structure",code:"ERR_CANNOT_REMOVE_MAIN_STRUCTURE"},$g={message:"records must be an object with tournamentId keys",code:"ERR_INVALID_TOURNAMENTS"},wt={message:"Missing tournamentRecords",code:"ERR_MISSING_TOURNAMENTS"},j={message:"Missing tournamentRecord",code:"ERR_MISSING_TOURNAMENT"},wa={message:"Invalid tournamentRecord",code:"ERR_INVALID_TOURNAMENT"},Xs={message:"Missing tournamentId",code:"ERR_MISSING_TOURNAMENT_ID"},Js={message:"Invalid drawDefinition",code:"ERR_INVALID_DRAWDEF"},z={message:"Missing drawDefinition",code:"ERR_MISSING_DRAWDEF"},LA={message:"Existing drawDefinition(s)",code:"ERR_EXISTING_DRAWDEFS"},fr={message:"drawDefinition not found",code:"ERR_NOT_FOUND_DRAWDEF"},hs={message:"Invalid structure",code:"ERR_INVALID_STRUCTURE"},Xd={message:"Incomplete source structure",code:"ERR_INCOMPLETE_STRUCTURE"},Jd={message:"Invalid drawPosition for seedAssignment",code:"ERR_INVALID_SEEDING_POSITION"},La={message:"drawPosition already assigned",code:"ERR_EXISTING_POSITION_ASSIGNMENT"},FA={message:"Schedule not cleared",code:"ERR_UNCHANGED_SCHEDULE_NOT_CLEARED"},GA={message:"drawPosition not cleared",code:"ERR_FAILURE_POSITION_NOT_CLEARED"},sw={message:"drawPosition not found",code:"ERR_NOT_FOUND_DRAW_POSITION"},Zd={message:"Unrecognized drawType",code:"ERR_UNRECOGNIZED_DRAW_TYPE"},Fa={message:"Missing drawPositions",code:"ERR_MISSING_DRAW_POSITIONS"},Ou={message:"drawPosition is active",code:"ERR_ACTIVE_DRAW_POSITION"},Ss={message:"Invlid drawPosition",code:"ERR_INVALID_DRAW_POSITION"},Ts={message:"Missing drawPosition",code:"ERR_MISSING_DRAW_POSITION"},Qp={message:"Invalid drawType",code:"ERR_INVALID_DRAW_TYPE"},_u={message:"Invalid drawSize",code:"ERR_INVALID_DRAW_SIZE"},Kg={message:"Cannot set drawSize to be less than existing entries",code:"ERR_INVALID_DRAW_SIZE_MISMATCH"},Ga={message:"Missing drawSize",code:"ERR_MISSING_DRAW_SIZE"},Ur={message:"Missing drawId",code:"ERR_MISSING_DRAW_ID"},kA={message:"drawId exists",code:"ERR_EXISTING_DRAW_ID"},VA={message:"participantId cannot be assigned to multiple seedNumbers",code:"INVALID_PARTICIPANT_SEEDING"},BA={message:"seedsCount greater than drawSize",code:"ERR_INVALID_SEED_COUNT"},HA={message:"Missing seedCountThresholds",code:"ERR_MISSING_SEED_COUNT_THRESHOLD"},WA={message:"Invalid action",code:"ERR_INVALID_ACTION"},zg={message:"Invalid assignment",code:"ERR_INVALID_ASSIGNMENT"},jA={message:"Missing seedAssignments",code:"ERR_MISSING_SEED_ASSIGNMENTS"},YA={message:"Invalid seedNumber",code:"ERR_INVALID_SEED_NUMBER"},qA={message:"Invalid seedPosition",code:"ERR_INVALID_SEED_POSITION"},tl={message:"Missing targetLink",code:"ERR_MISSING_LINK_TARGET"},$A={message:"Existing round",code:"ERR_EXISTING_ROUND"},aw={message:"Missing roundNumber",code:"ERR_MISSING_ROUND_NUMBER"},We={message:"Missing structureId",code:"ERR_MISSING_STRUCTURE_ID"},_t={message:"structure not found",code:"ERR_NOT_FOUND_STRUCTURE"},el={message:"Missing structures",code:"ERR_MISSING_STRUCTURES"},Ao={message:"Missing structure",code:"ERR_MISSING_STRUCTURE"},KA={message:"drawDefinition contains unlinked structures",code:"ERR_MISSING_STRUCTURE_LINKS"},yo={message:"Invalid eventType",code:"ERR_INVALID_EVENT_TYPE"};var St={message:"Missing event / eventId",code:"ERR_MISSING_EVENT_ID"},Ir={message:"Event not found",code:"ERR_NOT_FOUND_EVENT"},zA={message:"Event exists",code:"ERR_EXISTING_EVENT"},QA={message:"Missing entries",code:"ERR_MISSING_ENTRIES"},XA={message:"Invalid entries",code:"ERR_INVALID_ENTRIES"},rl={message:"Missing assignments",code:"ERR_MISSING_ASSIGNMENTS"},Qg={message:"Missing stage",code:"ERR_MISSING_STAGE"},Si={message:"Invalid stage",code:"ERR_INVALID_STAGE"},JA={message:"stageSequence limit",code:"ERR_LIMIT_STAGE_SEQUENCE"},ZA={message:"Missing positionAssignments",code:"ERR_MISSING_POSITION_ASSIGNMENTS"},ty={message:"Cannot Assign BYE status if no assignment: { bye: true }",code:"ERR_UNCHANGED_CANNOT_ASSIGN_BYE"},Xg={message:"Unrecognized matchUpStatus",code:"ERR_UNRECOGNIZED_MATCHUP_STATUS"},ka={message:"Unrecognized matchUpFormat",code:"ERR_UNRECOGNIZED_MATCHUP_FORMAT"},nl={message:"Incompatible matchUpStatus",code:"ERR_INCOMPATIBLE_MATCHUP_STATUS"},Zs={message:"Invalid matchUpStatus",code:"ERR_INVALID_MATCHUP_STATUS"},Jo={message:"Invalid tieFormat",code:"ERR_INVALID_TIE_FORMAT"},ol={message:"Invalid matchUpFormat",code:"ERR_INVALID_MATCHUP_FORMAT"},vu={message:"Missing matchUpFormat",code:"ERR_MISSING_MATCHUP_FORMAT"},ey={message:"Missing collectionDefinition",code:"ERR_MISSING_COLLECTION_DEFINITION"},Va={message:"Missing tieFormat",code:"ERR_MISSING_TIE_FORMAT"},Ne={message:"Missing matchUpId",code:"ERR_MISSING_MATCHUP_ID"},ta={message:"Missing matchUpIds",code:"ERR_MISSING_MATCHUP_IDS"},De={message:"matchUp not found",code:"ERR_NOT_FOUND_MATCHUP"},wn={message:"Missing matchUps",code:"ERR_MISSING_MATCHUPS"},or={message:"Missing matchUp",code:"ERR_MISSING_MATCHUP"},ze={message:"Invalid matchUp",code:"ERR_INVALID_MATCHUP"},Jg={message:"Missing policyType",code:"ERR_MISSING_POLICY_TYPE"},xu={message:"Missing policyDefinitions",code:"ERR_MISSING_POLICY_DEFINITIONS"},cw={message:"Missing seeding policy",code:"ERR_MISSING_POLICY_SEEDING"},ry={message:"Missing avoidance policy",code:"ERR_MISSING_POLICY_AVOIDANCE"},Zg={message:"Missing policy attributes",code:"ERR_MISSING_POLICY_ATTRIBUTES"},ny={message:"Invalid policyDefinitions",code:"ERR_INVALID_POLICY_DEFINITIONS"},tI={message:"existing policyType",code:"ERR_EXISTING_POLICY_TYPE"},uw={message:"Policy not attached",code:"ERR_FAILURE_POLICY_NOT_ATTACHED"},Mc={message:"Policy not found",code:"ERR_NOT_FOUND_POLICY"},pw={message:"Missing scoring policy / matchUpFormats",code:"ERR_MISSING_POLICY_SCORING_MATCHUP_FORMATS"},il={message:"Invalid sideNumber",code:"ERR_INVALID_SIDE_NUMBER"},mw={message:"Invalid setNumber",code:"ERR_INVALID_SET_NUMBER"},sl={message:"Missing setObject",code:"ERR_MISSING_SET_ATTRIBUTE"},dw={message:"Missing setNumber",code:"ERR_MISSING_SET_NUMBER"},lw={message:"Missing sideNumber",code:"ERR_MISSING_SIDE_NUMBER"},Ti={message:"Missing courtId",code:"ERR_MISSING_COURT_ID"},et={message:"Missing value",code:"ERR_MISSING_VALUE"},al={message:"Missing date",code:"ERR_MISSING_DATE"},oy={message:"No valid dates",code:"ERR_NO_VALID_DATES"},Xp={message:"Invalid bookings",code:"ERR_INVALID_BOOKINGS"},cl={message:"Invalid dateAvailability",code:"ERR_INVALID_DATE_AVAILABILITY"},iy={message:"Missing dateAvailability",code:"ERR_MISSING_DATE_AVAILABILITY"},ir={message:"Invalid Date",code:"ERR_INVALID_DATE"},io={message:"Invalid time",code:"ERR_INVALID_TIME"},sy={message:"Invalid tournament dates",code:"ERR_INVALID_DATES_TOURNAMENT"};var eI={message:"Invalid game scores",code:"ERR_INVALID_SCORES_GAME"},ay={message:"Invalid score",code:"ERR_INVALID_SCORE"},rI={message:"Invalid winningSide",code:"ERR_INVALID_WINNING_SIDE"};var $M={message:"No participants generated",code:"ERR_NO_PARTICIPANTS_GENERATED"},ul={message:"Cannot modify tieFormat",code:"ERR_UNCHANGED_CANNOT_MODIFY_TIEFORMAT"},cy={message:"Cannot modify participantType",code:"ERR_UNCHANGED_CANNOT_MODIFY_PARTICIPANT_TYPE"},wu={message:"Cannot remove participants",code:"ERR_UNCHANGED_CANNOT_REMOVE_PARTICIPANTS"},pl={message:"Cannot change winningSide",code:"ERR_UNCHANGED_CANNOT_CHANGE_WINNING_SIDE"},As={message:"Invalid participant",code:"ERR_INVALID_PARTICIPANT"},sn={message:"Invalid participantId",code:"ERR_INVALID_PARTICIPANT_ID"},Hr={message:"Invalid participantIds",code:"ERR_INVALID_PARTICIPANT_IDS"},uy={message:"Invalid participantRole",code:"ERR_INVALID_PARTICIPANT_ROLE"},tn={message:"Invalid participantType",code:"ERR_INVALID_PARTICIPANT_TYPE"},py={message:"Missing participantRole",code:"ERR_MISSING_PARTICIPANT_ROLE"},Ai={message:"Missing participant",code:"ERR_MISSING_PARTICIPANT"},Ba={message:"Missing participants",code:"ERR_MISSING_PARTICIPANTS"},te={message:"Missing participantId",code:"ERR_MISSING_PARTICIPANT_ID"},Jt={message:"Participant Not Found",code:"ERR_NOT_FOUND_PARTICIPANT"},my={message:"participantId exists",code:"ERR_EXISTING_PARTICIPANT_ID"},fw={message:"participant pair exists",code:"ERR_EXISTING_PARTICIPANT_PAIR"},dy={message:"No participant removed",code:"ERR_UNCHANGED_NO_PARTICIPANT_REMOVED"},so={message:"Missing participantIds",code:"ERR_MISSING_PARTICIPANT_IDS"},ly={message:"Missing participantsCount",code:"ERR_MISSING_PARTICIPANT_COUNT"},fy={message:"Participant not checked in",code:"ERR_UNCHANGED_PARTICIPANT_NOT_CHECKED_IN"},gy={message:"Missing person details",code:"ERR_MISSING_PERSON_DETAILS"},ys={message:"Existing participant drawPosition assignment",code:"ERR_EXISTING_PARTICIPANT_DRAW_POSITION_ASSIGNMENT"},Lu={message:"Existing participant",code:"ERR_EXISTING_PARTICIPANT"},ml={message:"participantsCount exceeds drawSize",code:"ERR_INVALID_PARTICIPANT_COUNT"},dl={message:"Invalid entry status",code:"ERR_INVALID_ENTRY_STATUS"},nI={message:"Participant Entry Not Found",code:"ERR_NOT_FOUND_PARTICIPANT_ENTRY"},KM={message:"Participant not entered in stage",code:"ERR_UNCHANGED_PARTICIPANT_NOT_ENTERED"},zM={message:"Participant not found in stageSequence",code:"ERR_NOT_FOUND_PARTICIPANT_IN_STAGE"},Iy={message:"entryStatus not allowed in stage",code:"ERR_INVALID_ENTRY_STATUS_IN_STAGE"},hy={message:"entryStatus not allowed for event",code:"ERR_INVALID_ENTRY_STATUS_IN_EVENT"},oI={message:"No stage space available for entryStatus",code:"ERR_UNCHANGED_NO_AVAILABLE_STAGE_SPACE"},Sy={message:"Insufficient drawPositions to accommodate qualifiers",code:"ERR_UNCHANGED_NO_DRAW_POSITIONS_FOR_QUALIFIERS"},ll={message:"Insufficient drawPositions to accommodate entries",code:"ERR_INSUFFICIENT_DRAW_POSITIONS"},Ty={message:"Missing penaltyType",code:"ERR_MISSING_PENALTY_TYPE"},fl={message:"Missing penaltyId",code:"ERR_MISSING_PENALTY_ID"},Cc={message:"Penalty not found",code:"ERR_NOT_FOUND_PENALTY"},Ay={message:"Missing courtsCount/courtNames",code:"ERR_MISSING_COURTS_INFO"},Ha={message:"Court not found",code:"ERR_NOT_FOUND_COURT"},yy={message:"Court exists",code:"ERR_EXISTING_COURT"},Ey={message:"Venue exists",code:"ERR_EXISTING_VENUE"},Es={message:"Venue not found",code:"ERR_NOT_FOUND_VENUE"},vo={message:"Missing venueId",code:"ERR_MISSING_VENUE_ID"},Uy={message:"Invalid endTime",code:"ERR_INVALID_END_TIME"},iI={message:"Existing endTime",code:"ERR_EXISTING_END_TIME"},Py={message:"Invalid stopTime",code:"ERR_INVALID_STOP_TIME"},Ny={message:"Invalid startTime",code:"ERR_INVALID_START_TIME"},QM={message:"Invalid resumeTime",code:"ERR_INVALID_RESUME_TIME"},gl={message:"Invalid timeItem",code:"ERR_INVALID_TIME_ITEMS"},Dy={message:"Missing async state provider",code:"ERR_MISSING_ASYNC_STATE_PROVIDER"},Il={message:"Missing timeItem",code:"ERR_MISSING_TIME_ITEM"},hl={message:"Missing timeItems",code:"ERR_MISSING_TIME_ITEMS"},Rc={message:"Missing context",code:"ERR_MISSING_CONTEXT"},My={message:"Missing schedule",code:"ERR_MISSING_SCHEDULE"},Fu={message:"Invalid scaleItem",code:"ERR_INVALID_SCALE_ITEM"},Cy={message:"Modifications failed",code:"ERR_FAILURE_MODIFICATIONS"},Us={message:"No modifications applied",code:"ERR_UNCHANGED_NO_MODIFICATIONS_APPLIED"},Ry={message:"Unable to assign court",code:"ERR_UNCHANGED_COURT_NOT_ASSIGNED"},Gu={message:"No Candidates",code:"ERR_UNCHANGED_NO_CANDIDATES"},by={message:"Invalid configuration",code:"ERR_INVALID_CONFIG"},Oy={message:"Invalid collectionDefinition",code:"ERR_INVALID_COLLECTION_DEFINITION"},Yn={message:"Invalid object",code:"ERR_INVALID_OBJECT"},Sl={message:"Invalid gender",code:"ERR_INVALID_GENDER"},Jp={message:"Invalid category",code:"ERR_INVALID_CATEGORY"},G={message:"Invalid values",code:"ERR_INVALID_VALUES"},_y={message:"Duplicate value",code:"ERR_DUPLICATE_VALUE"},Tl={message:"Team not found",code:"ERR_NOT_FOUND_TEAM"},vy={message:"No valid actions",code:"ERR_NO_VALID_ACTIONS"},ku={message:"No valid attributes",code:"ERR_NO_VALID_ATTRIBUTES"},Al={message:"Value unchanged",code:"ABORT_UNCHANGED"},je={message:"Not found",code:"ERR_NOT_FOUND"},Vu={message:"Not implemented",code:"ERR_NOT_IMPLEMENTED"},xy={message:"Existing flight",code:"ERR_EXISTING_FLIGHT"},yl={message:"Existing flight profile",code:"ERR_EXISTING_FLIGHT_PROFILE"},wy={message:"Existing outcome",code:"ERR_EXISTING_OUTCOME"},Ly={message:"Existing matchUpId",code:"ERR_EXISTING_MATCHUP_ID"},sI={message:"Existing stage",code:"ERR_EXISTING_STAGE"},El={message:"Existing structure",code:"ERR_EXISTING_STRUCTURE"},Wa={message:"Method not found",code:"ERR_NOT_FOUND_METHOD"},Fy={message:"Scheduled matchUps",code:"ERR_SCHEDULED_MATCHUPS"},Ul={message:"Scores present",code:"ERR_SCORES_PRESENT"},XM={ANACHRONISM:qg,CANNOT_CHANGE_WINNING_SIDE:pl,CANNOT_MODIFY_TIEFORMAT:ul,CANNOT_MODIFY_PARTICIPANT_TYPE:cy,CANNOT_REMOVE_MAIN_STRUCTURE:wA,CANNOT_REMOVE_PARTICIPANTS:wu,COURT_EXISTS:yy,COURT_NOT_FOUND:Ha,DRAW_DEFINITION_NOT_FOUND:fr,DRAW_ID_EXISTS:kA,DRAW_POSITION_ACTIVE:Ou,DRAW_POSITION_ASSIGNED:La,DRAW_POSITION_NOT_CLEARED:GA,DRAW_POSITION_NOT_FOUND:sw,DRAW_SIZE_MISMATCH:Kg,DUPLICATE_VALUE:_y,ENTRY_STATUS_NOT_ALLOWED_FOR_EVENT:hy,ENTRY_STATUS_NOT_ALLOWED_IN_STAGE:Iy,EVENT_EXISTS:zA,EVENT_NOT_FOUND:Ir,EXISTING_DRAW_DEFINITIONS:LA,EXISTING_END_TIME:iI,EXISTING_FLIGHT:xy,EXISTING_MATCHUP_ID:Ly,EXISTING_OUTCOME:wy,EXISTING_PARTICIPANT_DRAW_POSITION_ASSIGNMENT:ys,EXISTING_PARTICIPANT:Lu,EXISTING_POLICY_TYPE:tI,EXISTING_PROFILE:yl,EXISTING_ROUND:$A,EXISTING_STAGE:sI,EXISTING_STRUCTURE:El,INCOMPATIBLE_MATCHUP_STATUS:nl,INCOMPLETE_SOURCE_STRUCTURE:Xd,INSUFFICIENT_DRAW_POSITIONS:ll,INVALID_ACTION:WA,INVALID_ASSIGNMENT:zg,INVALID_BOOKINGS:Xp,INVALID_CATEGORY:Jp,INVALID_COLLECTION_DEFINITION:Oy,INVALID_CONFIGURATION:by,INVALID_DATE_AVAILABILITY:cl,INVALID_DATE:ir,INVALID_DRAW_DEFINITION:Js,INVALID_DRAW_POSITION_FOR_SEEDING:Jd,INVALID_DRAW_POSITION:Ss,INVALID_DRAW_SIZE:_u,INVALID_END_TIME:Uy,INVALID_ENTRIES:XA,INVALID_EVENT_TYPE:yo,INVALID_GAME_SCORES:eI,INVALID_GENDER:Sl,INVALID_MATCHUP_FORMAT:ol,INVALID_MATCHUP_STATUS:Zs,INVALID_MATCHUP_STATUS_BYE:ty,INVALID_MATCHUP:ze,INVALID_OBJECT:Yn,INVALID_PARTICIPANT_ID:sn,INVALID_PARTICIPANT_IDS:Hr,INVALID_PARTICIPANT_ROLE:uy,INVALID_PARTICIPANT_SEEDING:VA,INVALID_PARTICIPANT_TYPE:tn,INVALID_PARTICIPANT:As,INVALID_POLICY_DEFINITION:ny,INVALID_RECORDS:$g,INVALID_SCALE_ITEM:Fu,INVALID_SEED_NUMBER:YA,INVALID_SEED_POSITION:qA,INVALID_SET_NUMBER:mw,INVALID_SIDE_NUMBER:il,INVALID_SCORE:ay,INVALID_STAGE:Si,INVALID_START_TIME:Ny,INVALID_STRUCTURE:hs,INVALID_STOP_TIME:Py,INVALID_TIE_FORMAT:Jo,INVALID_TIME:io,INVALID_TIME_ITEM:gl,INVALID_TOURNAMENT_DATES:sy,INVALID_TOURNAMENT_RECORD:wa,INVALID_VALUES:G,INVALID_WINNING_SIDE:rI,MATCHUP_NOT_FOUND:De,METHOD_NOT_FOUND:Wa,MISSING_ASSIGNMENTS:rl,MISSING_ASYNC_STATE_PROVIDER:Dy,MISSING_AVOIDANCE_POLICY:ry,MISSING_COLLECTION_DEFINITION:ey,MISSING_COURT_ID:Ti,MISSING_COURTS_INFO:Ay,MISSING_DATE_AVAILABILITY:iy,MISSING_DATE:al,MISSING_DRAW_DEFINITION:z,MISSING_DRAW_ID:Ur,MISSING_DRAW_POSITION:Ts,MISSING_DRAW_POSITIONS:Fa,MISSING_DRAW_SIZE:Ga,MISSING_ENTRIES:QA,MISSING_EVENT:St,MISSING_MATCHUP_FORMAT:vu,MISSING_MATCHUP_ID:Ne,MISSING_MATCHUP_IDS:ta,MISSING_MATCHUP:or,MISSING_MATCHUPS:wn,MISSING_PARTICIPANT_COUNT:ly,MISSING_PARTICIPANT_ID:te,MISSING_PARTICIPANT_IDS:so,MISSING_PARTICIPANT_ROLE:py,MISSING_PARTICIPANT:Ai,MISSING_PARTICIPANTS:Ba,MISSING_PENALTY_ID:fl,MISSING_PENALTY_TYPE:Ty,MISSING_PERSON_DETAILS:gy,MISSING_POLICY_ATTRIBUTES:Zg,MISSING_POLICY_DEFINITION:xu,MISSING_POLICY_TYPE:Jg,MISSING_POSITION_ASSIGNMENTS:ZA,MISSING_ROUND_NUMBER:aw,MISSING_SCHEDULE:My,MISSING_SCORING_POLICY:pw,MISSING_SEED_ASSIGNMENTS:jA,MISSING_SEEDCOUNT_THRESHOLDS:HA,MISSING_SEEDING_POLICY:cw,MISSING_SET_NUMBER:dw,MISSING_SET_OBJECT:sl,MISSING_SIDE_NUMBER:lw,MISSING_STAGE:Qg,MISSING_STRUCTURE_ID:We,MISSING_STRUCTURE:Ao,MISSING_STRUCTURES:el,MISSING_TARGET_LINK:tl,MISSING_TIE_FORMAT:Va,MISSING_TIME_ITEM:Il,MISSING_TIME_ITEMS:hl,MISSING_TOURNAMENT_ID:Xs,MISSING_TOURNAMENT_RECORD:j,MISSING_TOURNAMENT_RECORDS:wt,MISSING_VALUE:et,MISSING_VENUE_ID:vo,MODIFICATIONS_FAILED:Cy,NO_CANDIDATES:Gu,NO_DRAW_POSITIONS_AVAILABLE_FOR_QUALIFIERS:Sy,NO_MODIFICATIONS_APPLIED:Us,NO_STAGE_SPACE_AVAILABLE_FOR_ENTRY_STATUS:oI,NO_PARTICIPANT_REMOVED:dy,NO_VALID_ACTIONS:vy,NO_VALID_ATTRIBUTES:ku,NO_VALID_DATES:oy,NOT_FOUND:je,NOT_IMPLEMENTED:Vu,PARTICIPANT_COUNT_EXCEEDS_DRAW_SIZE:ml,PARTICIPANT_ID_EXISTS:my,PARTICIPANT_NOT_CHECKED_IN:fy,PARTICIPANT_NOT_FOUND:Jt,PARTICIPANT_PAIR_EXISTS:fw,PENALTY_NOT_FOUND:Cc,POLICY_NOT_ATTACHED:uw,POLICY_NOT_FOUND:Mc,SCHEDULE_NOT_CLEARED:FA,SCHEDULED_MATCHUPS:Fy,SCORES_PRESENT:Ul,SEEDSCOUNT_GREATER_THAN_DRAW_SIZE:BA,STAGE_SEQUENCE_LIMIT:JA,STRUCTURE_NOT_FOUND:_t,TEAM_NOT_FOUND:Tl,UNABLE_TO_ASSIGN_COURT:Ry,UNLINKED_STRUCTURES:KA,UNRECOGNIZED_DRAW_TYPE:Zd,UNRECOGNIZED_MATCHUP_FORMAT:ka,UNRECOGNIZED_MATCHUP_STATUS:Xg,VALUE_UNCHANGED:Al,VENUE_EXISTS:Ey};var Qe={disableNotifications:!1,tournamentId:void 0,tournamentRecords:{},subscriptions:{},modified:!1,methods:{},notices:[]},Gy={addNotice:Dw,callListener:Ow,cycleMutationStatus:Nw,deleteNotice:Rw,deleteNotices:Cw,disableNotifications:gw,enableNotifications:Iw,getMethods:Bu,getNotices:Mw,getTopics:bw,getTournamentId:JM,getTournamentRecord:hw,getTournamentRecords:Sw,removeTournamentRecord:Ew,setMethods:Pw,setSubscriptions:Uw,setTournamentId:Aw,setTournamentRecord:Tw,setTournamentRecords:yw,handleCaughtError:_w};function gw(){Qe.disableNotifications=!0}function Iw(){Qe.disableNotifications=!1}function JM(){return Qe.tournamentId}function hw(t){return Qe.tournamentRecords[t]}function Sw(){return Qe.tournamentRecords}function Tw(t){let e=t?.tournamentId;return e?(Qe.tournamentRecords[e]=t,{success:!0}):{error:wa}}function Aw(t){return t?Qe.tournamentRecords[t]?(Qe.tournamentId=t,{success:!0}):{error:j}:(Qe.tournamentId=void 0,{success:!0})}function yw(t){Qe.tournamentRecords=t;let e=Object.keys(t);e.length===1?Qe.tournamentId=e[0]:e.length||(Qe.tournamentId=void 0)}function Ew(t){if(typeof t!="string")return{error:G};if(!Qe.tournamentRecords[t])return{error:je};delete Qe.tournamentRecords[t];let e=Object.keys(Qe.tournamentRecords);return e.length===1?Qe.tournamentId=e[0]:e.length||(Qe.tournamentId=void 0),{success:!0}}function Uw(t){return typeof t.subscriptions!="object"?{error:G}:(Object.keys(t.subscriptions).forEach(e=>{Qe.subscriptions[e]=t.subscriptions[e]}),{...R})}function Pw(t){return Object.keys(t).forEach(e=>{typeof t[e]=="function"&&(Qe.methods[e]=t[e])}),{...R}}function Nw(){let t=Qe.modified;return Qe.modified=!1,t}function Dw({topic:t,payload:e,key:r}){if(!(typeof t!="string"||typeof e!="object")&&(Qe.disableNotifications||(Qe.modified=!0),!(Qe.disableNotifications||!Qe.subscriptions[t])))return r&&(Qe.notices=Qe.notices.filter(n=>!(n.topic===t&&n.key===r))),Qe.notices.push({topic:t,payload:e,key:r}),{...R}}function Bu(){return Qe.methods??{}}function Mw({topic:t}){let e=Qe.notices.filter(r=>r.topic===t).map(r=>r.payload);return e.length&&e}function Cw(){Qe.notices=[]}function Rw({topic:t,key:e}){Qe.notices=Qe.notices.filter(r=>(!t||r.topic===t)&&r.key!==e)}function bw(){return{topics:Object.keys(Qe.subscriptions)}}function Ow({topic:t,notices:e}){let r=Qe.subscriptions[t];r&&typeof r=="function"&&r(e)}function _w({engineName:t,methodName:e,params:r,err:n}){let o;return typeof n=="string"?o=n.toUpperCase():n instanceof Error&&(o=n.message),console.log("ERROR",{tournamentId:JM(),params:JSON.stringify(r),engine:t,methodName:e,error:o}),{error:o}}function oe(t,e){return(t??0)-(e??0)}function ct(t){return typeof t=="number"?parseInt(t.toString()):typeof t=="string"?parseInt(t):0}function gn(t){return isNaN(t)?!1:t&&(t&t-1)===0}function ky(t){if(!t.length)return;let e=[...t].sort(oe),r=Math.floor(e.length/2);return e.length%2?e[r]:(e[r-1]+e[r])/2}function ZM(t){if(!gn(t))return!1;let e=t,r=1;for(;e!==2;)r+=1,e=e/2;return r}function Zp(t){return isNaN(t)?0:t%2&&t+1||t}function tm(t){return Math.pow(2,Math.round(Math.log(t)/Math.log(2)))}function se(t){return!isNaN(parseFloat(t))}function aI(t){let e=ct(t);if(!isNaN(e))return e===0?!1:(e&-e)===1}function Bi(t){if(isNaN(t))return!1;for(;!gn(t);)t++;return t}function qn(t,e){return t=Math.ceil(t),e=Math.floor(e),Math.floor(Math.random()*(e-t+1))+t}function lt(t){return Number.isSafeInteger(typeof t=="string"?+t:t)}function tC(t=1,e=3,r=!0){let n=0;for(let o=0;o<e;o++)n+=Math.random()*(t/e);return r&&t>1?Math.round(n):n}function vw(t,e){e||(e=1);let r=1/e;return Math.round(t*r)/r}function Vy(t,e,r,n,o=2){let i=1-Math.random(),s=1-Math.random(),a=Math.sqrt(-2*Math.log(i))*Math.cos(2*Math.PI*s);return a=a/10+.5,a>1||a<0?a=Vy(t,e,r):(a=Math.pow(a,r),a*=e-t,a+=t),n&&(a=vw(a,n)),parseFloat(a.toFixed(o))}function mt(t){return Array.isArray(t)?t?.filter((e,r,n)=>n.lastIndexOf(e)===r):[]}function eC(t){return Array.isArray(t)?t?.map(e=>e===null?void 0:e):t}function sr(t){return Array.isArray(t)?t.map(e=>[Math.random(),e]).sort((e,r)=>e[0]-r[0]).map(e=>e[1]):[]}function ja(t){return lt(t)?t:1/0}function pr(t){return Array.isArray(t)?t.reduce((e,r)=>(e[r]||(e[r]=0),e[r]++,e),{}):{}}function rC(t){return By(pr(t))}function By(t){return Object.keys(t).reduce((e,r)=>{let n=t[r];return e[n]?e[n].push(r):e[n]=[r],e},{})}function xw(t,e,r){return r.indexOf(t)===e}function cI(t){return t.filter(xw)}function Rr(t){return Array.isArray(t)&&t.length?t.splice(Math.floor(Math.random()*t.length),1)[0]:void 0}function en(t){let e=Math.floor(Math.random()*t.length);return t[e]}function Z(t,e){return Array.from({length:e-t},(r,n)=>n+t)}function $n(t,e){return e.reduce((r,n,o)=>(n===t&&r.push(o),r),[])}function Wt(t,e){return!Array.isArray(t)||!Array.isArray(e)?[]:t.filter(r=>e.indexOf(r)!==-1).filter((r,n,o)=>o.indexOf(r)===n)}function Hy(t,e){return!Array.isArray(t)||!Array.isArray(e)?[]:t.filter(r=>!e.includes(r))}function ve(t,e){return!Array.isArray(t)||!Array.isArray(e)?!1:t.some(r=>e.includes(r))}function nC(t,e){return Array.isArray(e)&&e.reduce((r,n)=>(r[n]=1+r[n]||1,r),{})[t]||0}function oC(t,e,r,n){return Array.isArray(t)?[].concat(...t.slice(0,e),...t.slice(e,e+r).sort(n),...t.slice(e+r,t.length)):[]}function Ae(t,e){return Array.isArray(t)?t.reduce((r,n,o)=>{let i=Math.floor(o/e);return r[i]=[].concat(r[i]||[],n),r},[]):[]}function Wy(t,[e,...r]){return t.length?[t.slice(0,e),...Wy(t.slice(e),[...r,e])]:[]}function iC(t){return t.reduce((e,r)=>{let n=e[e.length-1];return(!n||n[n.length-1]!==r-1)&&e.push([]),e[e.length-1].push(r),e},[])}function uI(t){return Array.isArray(t)?t.reduce((e,r)=>!isNaN(parseInt(r))&&e,!0):!1}function pI(t){return Array.isArray(t)?t.reduce((e,r)=>isNaN(parseInt(r))&&e,!0):!1}function Pl(t,e,r){return Array.isArray(t)?t.reduce((n,o,i)=>{let s=r?!!(Math.floor(i/e)%2):!1,a=i%e,c=s?e-1-a:a;return n[c]||(n[c]=[]),n[c].push(o),n},[]):[]}function sC(t,e=1){if(!Array.isArray(t)||!t.every(lt))return[];let r=Math.min(...t,e),n=Math.max(...t);return Z(r,n+1).filter(o=>!t.includes(o))}var Ye={tournamentFactoryVersion:"0.0.0",timers:{default:{elapsedTime:0}},deepCopyAttributes:{stringify:[],ignore:[],toJSON:[]},deepCopy:!0},Lr=Gy,aC=["addNotice","callListener","cycleMutationStatus","deleteNotice","deleteNotices","disableNotifications","enableNotifications","getMethods","getNotices","getTopics","getTournamentId","getTournamentRecord","getTournamentRecords","removeTournamentRecord","setSubscriptions","setTournamentId","setTournamentRecord","setTournamentRecords"];function ww(t){if(typeof t!="object")throw new Error("Global state provider can not be undefined or null");if(Wt(Object.keys(t),aC).length!==aC.length)throw new Error("Global state provider is missing required methods");return Lr=t,{success:!0}}function jy(){if(Lr.createInstanceState){try{Lr.createInstanceState()}catch(t){return{error:t}}return{success:!0}}else return{error:Dy}}function Tr(t){return!t||typeof t!="object"?Ye.devContext??!1:typeof Ye.devContext!="object"?!1:Object.keys(t).every(e=>Ye.devContext?.[e]===t[e])&&Ye.devContext}function Lw(t="reset",e="default"){let r=Date.now();if(t==="report"){if(e==="allTimers")return Object.keys(Ye.timers).filter(o=>o!=="default"||Ye.timers[o].startTime).map(o=>{let i=Ye.timers[o],s=i.state==="stopped"?0:(r-(i?.startTime??0))/1e3,a=i.elapsedTime+s;return{state:Ye.timers[o].state,elapsedTime:a.toFixed(2),timer:o}});{let n=Ye.timers[e].state==="stopped"?0:(r-(Ye.timers[e]?.startTime??0))/1e3,o=Ye.timers[e].elapsedTime+n;return{state:Ye.timers[e].state,elapsedTime:o.toFixed(2),timer:e}}}if(!Ye.timers[e]||t==="reset"){if(e==="allTimers")return Ye.timers={default:{elapsedTime:0}},!0;Ye.timers[e]={startTime:r,state:"active",elapsedTime:0}}return Ye.timers[e].elapsedTime||(Ye.timers[e].elapsedTime=0),t==="stop"&&Ye.timers[e].state!=="stopped"&&(Ye.timers[e].state="stopped")&&(Ye.timers[e].elapsedTime+=(r-(Ye.timers[e]?.startTime??0))/1e3),t==="start"&&(Ye.timers[e].startTime=r)&&(Ye.timers[e].state="active"),Ye.timers[e]}function cC(t){typeof t=="function"?Ye.globalLog=t:delete Ye.globalLog}function bc(t){Ye.devContext=t}function Yy(){Lr.disableNotifications()}function Nl(){Lr.enableNotifications()}function Oc(t,e){typeof t=="boolean"&&(Ye.deepCopy=t),typeof e=="object"&&(Array.isArray(e.ignore)&&(Ye.deepCopyAttributes.ignore=e.ignore),Array.isArray(e.toJSON)&&(Ye.deepCopyAttributes.toJSON=e.toJSON),Array.isArray(e.stringify)&&(Ye.deepCopyAttributes.stringify=e.stringify),e.threshold&&(Ye.deepCopyAttributes.threshold=e.threshold))}function Dl(){return{enabled:Ye.deepCopy,...Ye.deepCopyAttributes}}function Fw(t){return t?.subscriptions?Lr.setSubscriptions({subscriptions:t.subscriptions}):{error:et,info:"missing subscriptions"}}function qy(t){return t?typeof t!="object"?{error:G}:Lr.setMethods(t):{error:et,info:"missing method declarations"}}function Ml(){return Lr.cycleMutationStatus()}function Tt(t){return Lr.addNotice(t)}function Cl(){return Lr.getMethods()}function mI(t){return Lr.getNotices(t)}function dI({key:t,topic:e}){return Lr.deleteNotice({key:t,topic:e})}function yi(){return Lr.deleteNotices()}function Fr(){return Lr.getTopics()}async function em(t){return Lr.callListener(t)}function Hi(){return Lr.getTournamentId()}function Rl(t){return Lr.getTournamentRecord(t)}function Eo(){return Lr.getTournamentRecords()}function $y(t){return Lr.setTournamentRecord(t)}function rm(t){return Lr.setTournamentRecords(t)}function Hu(t){return Lr.setTournamentId(t)}function Ky(t){return Lr.removeTournamentRecord(t)}function lI(){return Lr}function Wu({engineName:t,methodName:e,params:r,err:n}){return(typeof Lr.handleCaughtError=="function"&&Lr.handleCaughtError||Gy.handleCaughtError)({engineName:t,methodName:e,params:r,err:n})}function zy(t,e){if(Ye.globalLog)try{Ye.globalLog({log:t,engine:e})}catch(r){console.log("globalLog error",r),console.log(e,t),cC()}else console.log(e,t)}function Gw(t,e,r){return Object.keys(t).filter(n=>!e.includes(t[n])&&(!r||(Array.isArray(t[n])?t[n].length:!0)))}function rt(t,e,r,n){if(typeof t!="object"||t===null)return t;Dl()?.enabled||(n=!0);let i=["",void 0,null];e&&i.push(!1);let s=Gw(t,i,r);return Object.assign({},...s.map(a=>Array.isArray(t[a])?{[a]:n?t[a]:t[a].map(c=>rt(c))}:{[a]:n?t[a]:rt(t[a])}))}function v({context:t,result:e,stack:r,info:n}){return e&&!Array.isArray(e?.stack)&&(e.stack=[]),e&&Array.isArray(e?.stack)&&typeof r=="string"&&e.stack.push(r),e&&n&&(e.info=n),e&&typeof t=="object"&&Object.keys(t).length&&Object.assign(e,rt(t)),e&&!e?.error&&!e?.success&&Object.assign(e,{...R}),e??{success:!0}}var nm=/^[\d]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][\d]|3[0-1])$/,fI=/^((0[\d]|1[\d]|2[0-3]):[0-5][\d](:[0-5][\d])?)([.,][0-9]{3})?$/,ao=/^([\d]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][\d]|3[0-1]))([ T](0[\d]|1[\d]|2[0-3]):[0-5][\d](:[0-5][\d])?)?([.,][\d]{3})?Z?$/,Ps=/^([\d]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][\d]|3[0-1]))?([ T]?(0[\d]|1[\d]|2[0-3]):[0-5][\d](:[0-5][\d])?)?([.,][\d]{3})?Z?$/;function om(t){let{scheduledDate:e}=t;if(!e&&t.scheduledTime&&(e=At(t.scheduledTime)),!e)return;let r=qt(t.scheduledTime),n=At(e);return n&&r&&(n+=`T${r}`),n}function pC(t){return typeof t!="object"||Array.isArray(t)?!1:Object.prototype.toString.call(t)==="[object Date]"}function _c(t){let e=typeof t=="string"?t?.split(" "):[];return t&&e?.length>1&&!["AM","PM"].includes(e[1].toUpperCase())?!1:!!(!t||Ps.test(qa(t,!0,!0)))}function Pr(t){return Ya(t)||nm.test(t)}function kw(t){let e=new Date(t),r=e.getSeconds()+60*e.getMinutes()+60*60*e.getHours();return Vw(r,{displaySeconds:!1})}function Vw(t,e){let r=parseInt(t,10),n=Math.floor(r/3600),o=Math.floor((r-n*3600)/60),i=r-n*3600-o*60;return(!e||e?.displaySeconds?n+":"+o+":"+i:n+":"+o).split(":").map(Ln).join(":")}var _l=t=>{let e=bl(t)||Ya(t)?new Date(t):new Date,r=e.getUTCMonth()+1,n=r<10?`0${r}`:`${r}`;return`${e.getUTCFullYear()}-${Ln(n)}-${Ln(e.getUTCDate())}`};function Bw(t){let e=bl(t)||Ya(t)?new Date(t):new Date;return Date.UTC(e.getFullYear(),e.getMonth(),e.getDate())}function Kn(t,e="-",r="YMD"){if(!t)return"";typeof t=="string"&&t.indexOf("T")<0&&(t=t+"T00:00");let n=new Date(t),o=""+(n.getMonth()+1),i=""+n.getDate(),s=n.getFullYear();return o.length<2&&(o="0"+o),i.length<2&&(i="0"+i),r==="DMY"?[i,o,s].join(e):r==="MDY"?[o,i,s].join(e):r==="YDM"?[s,i,o].join(e):r==="DYM"?[i,s,o].join(e):r==="MYD"?[o,s,i].join(e):[s,o,i].join(e)}function gI(t){let e=t?new Date(t):new Date,r=e.getTimezoneOffset();return new Date(e.getTime()-r*60*1e3)}function Hw(t){return gI(t).getTime()}function bl(t){if(typeof t=="boolean")return!1;let e=t instanceof Date&&t||!isNaN(t)&&new Date(t)||!1;return e&&!isNaN(e.valueOf())}function vc(t,e){if(!Pr(t)||!Pr(e))return[];let r=At(t)+"T00:00",n=At(e)+"T00:00",o=new Date(r),i=new Date(n),s=bl(i)&&bl(o)&&u(o,i),a=[],c=0;if(s){let p=o,m=p.getTime();for(;m<=i.getTime()&&c<300;)c+=1,a.push(new Date(p)),m=p.setDate(p.getDate()+1)}return a.map(p=>Kn(p));function u(p,m){return p<=m}}var Ww=/^([+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-2])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([.,]\d+(?!:))?)?(\17[0-5]\d([.,]\d+)?)?([zZ]|([+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/;function Ya(t){return typeof t!="string"?!1:Ww.test(t)}function hI(t){if(typeof t!="string")return!1;let r=t.split("Z")[0].split(":"),n=r.every(i=>!isNaN(parseInt(i)));return!(r.length<2||!n||parseInt(r[0])>23||parseInt(r[1])>60)}function Gt(t){let e=qt(t);if(!e)return 0;let[r,n]=e.split(":").map(o=>parseInt(o));return r*60+n}function mC(t){let e=Math.floor(t/60),r=t-e*60;return e>23&&(e=e%24),[Ln(e),Ln(r)].join(":")}function Ol(t){return hI(t)?t.split(":").slice(0,2).map(Ln).join(":"):void 0}function qt(t){return Ya(t)&&t.indexOf("T")>0?Ol(t.split("T").reverse()[0]):Ol(t)}function At(t){return Ya(t)||ao.test(t)?t.split("T")[0]:void 0}function ju(t,e){let r=new Date(t);return r.setDate(r.getDate()+e),At(r.toISOString())}function II(t){t=typeof t!="string"?"00:00":t;let e={},r={};return{0:e.time,1:e.ampm}=t.split(" ")||[],{0:r.hours,1:r.minutes}=e.time.split(":")||[],r.ampm=e.ampm,isNaN(r.hours)||isNaN(r.minutes)||r.ampm&&!["AM","PM"].includes(r.ampm.toUpperCase())?{}:r}function jw(t){let e=II(t);return e.ampm&&e.hours&&(e.ampm.toLowerCase()==="pm"&&parseInt(e.hours)<12&&(e.hours=(e.hours&&parseInt(e.hours)||0)+12),e.ampm.toLowerCase()==="am"&&e.hours==="12"&&(e.hours="00")),`${e.hours||"12"}:${e.minutes||"00"}`.split(":").map(Ln).join(":")}function Yw(t){let e=II(t);if(!(typeof e=="object"&&!Object.keys(e).length))return e.ampm?t:(e.hours>12?(e.hours-=12,e.ampm="PM"):e.hours==="12"?e.ampm="PM":(e.hours==="00"&&(e.hours="12"),e.ampm="AM"),e.hours?.[0]==="0"&&(e.hours=e.hours.slice(1)),`${e.hours||"12"}:${e.minutes||"00"} ${e.ampm}`)}function qa(t,e,r){let n=At(t),o=qt(t),i=n?o:t;return t?e&&(n&&r&&t||jw(i))||Yw(i):void 0}function SI(t,e){let r=II(t),n=II(e);if(parseInt(r.hours)<parseInt(n.hours))return-1;if(parseInt(r.hours)>parseInt(n.hours))return 1;if(r.hours===n.hours){if(parseInt(r.minutes)<parseInt(n.minutes))return-1;if(parseInt(r.minutes)>parseInt(n.minutes))return 1}return 0}function dC(t,e=7){let r=At(t)+"T00:00",n=new Date(r),o=new Date(n.setDate(n.getDate()+e));return Kn(o)}function qw(t){return dC(t)}function $w(t,e,r,n=!1){let o=new Date(e,0,1+(t-1)*7),i=n?0:1;return o.setDate(o.getDate()+(i-o.getDay())),Kn(o,r)}function lC(t,e,r){let n=new Date(t,0);return Kn(new Date(n.setDate(e)),r)}function xe(t,e=void 0){let[r,n]=(t||"00:00").split(":").map(Ln),o=gI(e).setHours(r,n,0,0);return gI(o)}function ea(t,e,r=!0){let n=new Date(t),i=(new Date(e).getTime()-n.getTime())/1e3/60;return r?Math.abs(Math.round(i)):Math.round(i)}function Nr(t,e){let r=qt(t);if(!r)return"00:00";let n=isNaN(e)?0:e;return qt(vl(xe(r),n).toISOString())}function vl(t,e){let r=new Date(t);return new Date(r.getTime()+e*6e4)}function Ln(t){return t.toString()[1]?t:"0"+t}function Dn(t,e){let r=new Date(t),n=new Date(e);return r.getFullYear()===n.getFullYear()&&r.getMonth()===n.getMonth()&&r.getDate()===n.getDate()}var fC={addDays:dC,addWeek:qw,addMinutesToTimeString:Nr,convertTime:qa,getIsoDateString:om,getUTCdateString:_l,DateHHMM:kw,extractDate:At,extractTime:qt,formatDate:Kn,getDateByWeek:$w,isISODateString:Ya,isDate:bl,isTimeString:hI,offsetDate:gI,offsetTime:Hw,sameDay:Dn,timeStringMinutes:Gt,timeToDate:xe,timeUTC:Bw,validTimeValue:_c,validDateString:nm,timeValidation:Ps,dateValidation:ao};function J(t,e,r,n,o=0){if(lI().makeDeepCopy)return lI().makeDeepCopy(t,e,r,n);let i=Dl(),{stringify:s,toJSON:a,ignore:c,modulate:u}=i||{};if(!i?.enabled&&!r||typeof t!="object"||typeof t=="function"||t===null||typeof i?.threshold=="number"&&o>=i.threshold)return t;let p=Array.isArray(t)?[]:{},m=Object.keys(t).filter(l=>!r||!c||Array.isArray(c)&&!c.includes(l)||typeof c=="function"&&!c(l)),d=(l,f)=>{p[l]=typeof f?.toString=="function"?f.toString():JSON.stringify(f)};for(let l of m){let f=t[l],g=typeof u=="function"?u(f):void 0;if(g!==void 0)p[l]=g;else if(e&&l==="extensions"&&Array.isArray(f)){let I=xl(f);Object.assign(p,...I)}else n&&l==="extensions"?p[l]=[]:Array.isArray(s)&&s.includes(l)?d(l,f):Array.isArray(a)&&a.includes(l)&&typeof f?.toJSON=="function"?p[l]=f.toJSON():f===null?p[l]=void 0:pC(f)?p[l]=new Date(f).toISOString():p[l]=J(f,e,r,n,o+1)}return p}function xl(t){return t?.map(e=>{let{name:r,value:n}=e;return r&&n&&{[`_${r}`]:n}}).filter(Boolean)}function Wi({element:t,accessor:e}){if(typeof e!="string")return{values:[]};let r=J(t),n=e.split("."),o=[],i;a({targetElement:r,attributes:n});let s={value:i};return o.length&&(s.values=o),s;function a({targetElement:c,attributes:u=[],significantCharacters:p}){for(let[d,l]of u.entries())if(c?.[l]){let f=u.slice(d+1);f.length?Array.isArray(c[l])?c[l].forEach(I=>a({targetElement:I,attributes:f})):(c=c[l],m({targetElement:c,index:d})):(i||(i=c[l]),o.includes(c[l])||o.push(c[l]))}function m({targetElement:d,index:l}){if(d&&l===u.length-1&&["string","number"].includes(typeof d)){let f=p?d.slice(0,p):d;i?o.includes(f)||o.push(f):(i=f,o.push(f))}}}}function xo(t){return typeof t=="function"}function er(t){return typeof t=="string"}function Ct(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function gC(t,e){if(!Ct(t)||!Ct(e))return!1;let r=Object.keys(t),n=Object.keys(e);if(r.length!==n.length)return!1;for(let o of r)if(t[o]!==e[o])return!1;return!0}function AI(t,e){return Array.isArray(t)?Object.assign({},...(t??[]).filter(Ct).map(r=>r[e]&&{[r[e]]:r}).filter(Boolean)):{}}var IC=t=>e=>Object.keys(t).every(r=>e[r]===t[r]);var Xy=t=>e=>!t||typeof e!="object"?void 0:Array.isArray(t)&&t.map(r=>({[r]:Wi({element:e,accessor:r})?.value}))||typeof t=="object"&&Object.keys(t).map(r=>({[r]:Wi({element:e,accessor:r})?.value}))||(typeof t=="string"&&Wi({element:e,accessor:t}))?.value,Dr=Xy;function TI(t,e){if(t===void 0)return null;if(typeof t!="object"||t===null)return t;let r=Object.keys(t),n=o=>o===void 0?null:o;return Object.assign({},...r.map(o=>Array.isArray(t[o])?{[o]:e?t[o]:t[o].map(i=>TI(i))}:{[o]:e?n(t[o]):TI(t[o])}))}function Qy(t){return Array.isArray(t)?t.length+t.map(Qy).reduce((e,r)=>e+r,0):typeof t=="object"&&t!==null?Object.keys(t).length+Object.keys(t).map(e=>Qy(t[e])).reduce((e,r)=>e+r,0):0}function hC(t){if(t===null||typeof t!="object")return;let e=JSON.stringify(t),r=Qy(t),n=e.split("").reduce((o,i)=>o+i.charCodeAt(0),0);return[e.length,r,n].map(o=>o.toString(36)).join("")}var ye="tournamentRecords",wl="policyDefinitions",Fn="tournamentRecord",Ei="drawDefinition",SC="matchUpFormat",zn="participantId",yI="scheduleDates",TC="tournamentId",AC="scheduleDate",EI="structureId",Ll="participant",Fl="matchUpIds",yC="policyType",Jy="structures",ji="matchUpId",UI="inContext",Gl="structure",Yu="courtIds",EC="personId",qu="venueIds",Zy="matchUps",PI="courtId",NI="eventId",co="matchUp",DI="drawId",Ns="error",$a="event",ra="param",UC="uuids",PC="averageMatchUpMinutes",NC="recoveryMinutes",DC="periodLength";var Ui="object",an="array";var Pi="validate",Ni="invalid",na="_ofType",MC="_anyOf",CC="_oneOf";var Kw={[ye]:wt,[Fn]:j,[wl]:xu,[Ei]:z,[zn]:te,[TC]:Xs,[EI]:We,[Fl]:ta,[Ll]:Ai,[Jy]:el,[ji]:Ne,[Gl]:Ao,[PI]:Ti,[Zy]:wn,[co]:or,[Yu]:et,[qu]:et,[DI]:Ur,[NI]:St,[$a]:Ir},zw={[ye]:Ui,[wl]:Ui,[Fn]:Ui,[Ei]:Ui,[yI]:an,[Ll]:Ui,[Fl]:an,[Jy]:an,[Gl]:Ui,[Yu]:an,[qu]:an,[Zy]:an,[co]:Ui,[$a]:Ui,[UC]:an};function vt(t,e,r){if(!t&&!Ct(t))return{error:G};if(!e?.length||t?._bypassParamCheck)return{valid:!0};if(!Array.isArray(e))return{error:G};let{paramError:n,errorParam:o}=Jw(t,e);if(!n)return{valid:!0};let i=t[o]===void 0?Kw[o]||G:n.validate&&n.invalid||G;return v({info:{param:o},result:{error:i},stack:r})}function RC(t,e){let r=Object.keys(t),n=Object.keys(e);return Wt(r,n)}function Qw(t,e){if(!e)return;let r=RC(t,e);return r.length!==1?{error:G}:r.reduce((n,o)=>({...n,[o]:!0}),{})}function Xw(t,e){if(!e)return;let r=RC(t,e).filter(n=>t[n]);return r.length<1?{error:G}:r.reduce((n,o)=>({...n,[o]:!0}),{})}function Jw(t,e){let r;return{paramError:e.find(({_ofType:o,_oneOf:i,_anyOf:s,validate:a,...c})=>{let u=i&&Qw(t,i);if(u?.error)return u.error;u&&Object.assign(c,u);let p=s&&Xw(t,s);if(p?.error)return p.error;p&&Object.assign(c,p);let m=Object.keys(c).filter(l=>typeof c[l]=="boolean"),d=m.find(l=>{let f=a&&!xo(a),g=t[l]&&!a&&Zw(t,l,o),I=c[l]&&!t[l],S=f||g||I||a&&t[l]&&!tL(t[l],a);return S&&(r=l),S});return!m.length||d}),errorParam:r}}function Zw(t,e,r){return r=r||zw[e]||"string",r==="array"?!Array.isArray(t[e]):typeof t[e]!==r}function tL(t,e){return xo(e)?e(t):!0}var MI="DYNAMIC",Zo="RANKING",Yi="RATING",qi="SCALE",Qn="SEEDING",bC={RANKING:Zo,RATING:Yi,SCALE:qi,SEEDING:Qn};function oa(t){let e=vt(t,[{[Ll]:!0}]);if(e.error)return e;let r=t.participant.timeItems?.filter(({itemType:o})=>o?.startsWith(qi)&&[Zo,Yi,Qn].includes(o.split(".")[1])),n={ratings:{},rankings:{},seedings:{}};if(r?.length){let o=s=>r.filter(a=>a?.itemType===s).sort((a,c)=>new Date(a.createdAt||void 0).getTime()-new Date(c.createdAt||void 0).getTime()).pop(),i=mt(r.map(({itemType:s})=>s));for(let s of i){let a=o(s);if(a){let[,c,u,p,m]=a.itemType.split("."),d=m?`${p}.${m}`:p,l=c===Qn&&"seedings"||c===Zo&&"rankings"||"ratings";n[l][u]||(n[l][u]=[]),n[l][u].push({scaleValue:a.itemValue,scaleDate:a.itemDate,scaleName:d})}}}return{...R,...n}}function Di(t){if(t===null)return{};let{source:e,template:r}=t||{};if(!r)return e;let n={};return o(e,r,n),n;function o(i,s,a){if(!i||!s)return;let c=Object.keys(i),u=Object.keys(s),p=Object.assign({},...u.filter(l=>l.indexOf("||")).map(l=>l.split("||").map(f=>({[f]:l}))).flat()),m=u.concat(...Object.keys(p)),d=m.includes("*");for(let l of c)if(m.indexOf(l)>=0||d){let f=p[l]||l,g=s[f]||d,I=i[l];if(typeof g=="object"&&typeof I!="function"&&!Array.isArray(g))if(Array.isArray(I)){let h=I.map(S=>{let T={};return o(S,g,T)!==!1?T:void 0}).filter(Boolean);a[l]=h}else I&&(a[l]={},o(I,g,a[l]));else{let h=i[l];if(Array.isArray(g)&&!g.includes(h))return!1;(s[l]||d&&s[l]!==!1)&&(a[l]=h)}}}}var CI="voluntaryConsolation",ti="competitiveBands",kl="roundRobinTally",Xn="positionActions",qe="matchUpActions",Vl="rankingPoints",ia="roundNaming",Ka="participant",xc="progression",uo="scheduling",wc="avoidance",eL="display",Mn="scoring",In="seeding",Lc="feedIn",rL="audit",im="draws",OC={POLICY_TYPE_VOLUNTARY_CONSOLATION:CI,POLICY_TYPE_COMPETITIVE_BANDS:ti,POLICY_TYPE_ROUND_ROBIN_TALLY:kl,POLICY_TYPE_POSITION_ACTIONS:Xn,POLICY_TYPE_MATCHUP_ACTIONS:qe,POLICY_TYPE_RANKING_POINTS:Vl,POLICY_TYPE_ROUND_NAMING:ia,POLICY_TYPE_PARTICIPANT:Ka,POLICY_TYPE_PROGRESSION:xc,POLICY_TYPE_SCHEDULING:uo,POLICY_TYPE_AVOIDANCE:wc,POLICY_TYPE_DISPLAY:eL,POLICY_TYPE_FEED_IN:Lc,POLICY_TYPE_SCORING:Mn,POLICY_TYPE_SEEDING:In,POLICY_TYPE_AUDIT:rL,POLICY_TYPE_DRAWS:im};function Uo({tournamentParticipants:t=[],policyDefinitions:e={},contextProfile:r,participantId:n,internalUse:o,personId:i}){let s=t.find(c=>n&&c.participantId===n||i&&c.person&&c.person.personId===i),a=J(s,!1,o);if(a){let c=e?.[Ka];if(r?.withScaleValues){let{ratings:u,rankings:p}=oa({participant:a});a.rankings=p,a.ratings=u}if(c?.participant)return Di({template:c.participant,source:a})}return a}var sm="element required",_C="missing name";function rr(t){if(!t||typeof t!="object")return{error:et};if(t.element&&typeof t?.element!="object")return{error:G};if(!t?.name)return{error:et,info:_C};if(!t?.element){if(t.discover&&t.tournamentRecords){for(let e of Object.keys(t.tournamentRecords)){let r=t.tournamentRecords[e],n=rr({element:r,name:t.name});if(n.error)return v({result:n,stack:"removeExtension"})}return{...R}}return{error:et,info:sm}}return t?.element.extensions?(t.element.extensions=t.element.extensions.filter(e=>e?.name!==t.name),{...R}):{...R,info:je}}function hn({requiredAttributes:t=["name","value"],extension:e}){if(!e||typeof e!="object"||typeof e.name!="string")return!1;let r=Object.keys(e);return t.filter(n=>r.includes(n)).length===t.length}function gt(t){if(typeof t!="object")return{error:et};let e="addExtension";if(t?.element&&typeof t.element!="object")return v({result:{error:G},stack:e});if(!hn({extension:t.extension}))return v({result:{error:G,info:"invalid extension"},stack:e});if(!t.element)if(t.discover&&!t.tournamentId&&t.tournamentRecords){for(let o of Object.values(t.tournamentRecords)){let i=gt({extension:t.extension,element:o});if(i.error)return v({result:i,stack:e})}return{...R}}else return v({result:{error:et},stack:e});if(t.element.extensions||(t.element.extensions=[]),t?.creationTime??!0){let o=new Date().toISOString();Object.assign(t.extension,{createdAt:o})}let n=t.element.extensions.find(({name:o})=>o===t.extension.name);return n?n.value=t.extension.value:t.extension.value&&t.element.extensions.push(t.extension),{...R}}function Bl(t){return!t||typeof t!="object"?{error:et}:t.tournamentRecord?gt({creationTime:t.creationTime,element:t.tournamentRecord,extension:t.extension}):{error:j}}function $u(t){return!t||typeof t!="object"?{error:et}:t.drawDefinition?gt({creationTime:t.creationTime,element:t.drawDefinition,extension:t.extension}):{error:fr}}function po(t){return!t||typeof t!="object"?{error:et}:t.event?gt({creationTime:t.creationTime,extension:t.extension,element:t.event}):{error:Ir}}function tE(t){if(!t||typeof t!="object")return{error:et};if(!t.participantId)return{error:te};let e=t.tournamentRecord?.participants||[],r=Uo({participantId:t.participantId,tournamentParticipants:e});return r?gt({creationTime:t.creationTime,extension:t.extension,element:r}):{error:Jt}}function Hl(t){return!t||typeof t!="object"?{error:et}:t.tournamentRecord?rr({element:t.tournamentRecord,name:t.name}):{error:j}}function eE(t){return!t||typeof t!="object"?{error:et}:t.drawDefinition?rr({element:t.drawDefinition,name:t.name}):{error:fr}}function Ku(t){return!t||typeof t!="object"?{error:et}:t?.event?rr({element:t.event,name:t.name}):{error:Ir}}function rE(t){if(!t||typeof t!="object")return{error:et};if(!t.participantId)return{error:te};let e=t.tournamentRecord?.participants||[],r=Uo({participantId:t.participantId,tournamentParticipants:e});return r?rr({element:r,name:t.name}):{error:Jt}}function zu({tournamentRecords:t}){return{tournamentIds:Ct(t)?Object.keys(t):[],...R}}var nL="extensionQueries";function ut({discover:t,element:e,name:r,...n}){if(!e||!r){if(t&&n){let s=Object.keys(n).filter(p=>typeof t=="boolean"||Array.isArray(t)&&t.includes(p)).find(p=>Array.isArray(n[p]?.extensions)?n[p].extensions.find(m=>m?.name===r):!1),a=s&&n[s];!a&&n.tournamentRecords&&(a=Object.values(n.tournamentRecords).find(p=>p.extensions?.length));let c=a?.extensions?.find(p=>p?.name===r);return{extension:c,info:c?void 0:je}}return v({result:{error:et},stack:nL})}if(!Array.isArray(e.extensions))return{info:"no extensions"};let o=e.extensions.find(s=>s?.name===r);return{extension:o,info:o?void 0:je}}var oL="activeSuspension",Fc="appliedPolicies",am="positionActions",nE="context",cm="delegatedOutcome",Gn="disabled",um="disableLinks",za="disableAutoCalc",pm="drawDeletions",iL="drawProfile",mm="entryProfile",sL="eventProfile",aL="eventWithdrawalRequests",cL="factory",Gr="flightProfile",RI="groupingAttribute",mo="lineUps",sa="linkedTournamentsIds",dm="matchUpHistory",bI="participantRepresentatives",aa="personRequests",oE="rankingPoints";var cn="roundTarget",Gc="scheduleLimits",Po="scheduleTiming",ca="schedulingProfile",uL="statusDetail",Qa="subOrder",wo="tally",$i="tieFormatModification",OI={ACTIVE_SUSPENSION:oL,APPLIED_POLICIES:Fc,AUDIT_POSITION_ACTIONS:am,CONTEXT:nE,DELEGATED_OUTCOME:cm,DISABLED:Gn,DISABLE_LINKS:um,DISABLE_AUTO_CALC:za,DRAW_DELETIONS:pm,DRAW_PROFILE:iL,ENTRY_PROFILE:mm,EVENT_PROFILE:sL,EVENT_WITHDRAWAL_REQUESTS:aL,FLIGHT_PROFILE:Gr,GROUPING_ATTRIBUTE:RI,LINEUPS:mo,LINKED_TOURNAMENTS:sa,MATCHUP_HISTORY:dm,PARTICIPANT_REPRESENTATIVES:bI,PERSON_REQUESTS:aa,RANKING_POINTS:oE,ROUND_TARGET:cn,SCHEDULE_LIMITS:Gc,SCHEDULE_TIMING:Po,SCHEDULING_PROFILE:ca,STATUS_DETAIL:uL,SUB_ORDER:Qa,TALLY:wo,TIE_FORMAT_MODIFICATIONS:$i,FACTORY:cL},iE=[cm,Gn,um,Gr,mo,dm,bI,aa,cn,Gc,Po,ca,Qa,wo];function sE({tournamentRecords:t}){if(typeof t!="object"||!Object.keys(t).length)return{error:wt};let e=zu({tournamentRecords:t}),{tournamentIds:r}=e;return r?.length>1?gt({tournamentRecords:t,discover:!0,extension:{name:sa,value:{tournamentIds:r}}}):{...R}}function aE({tournamentRecords:t}){if(typeof t!="object"||!Object.keys(t).length)return{error:wt};let e=rr({name:sa,tournamentRecords:t,discover:!0});return v({result:e,stack:"unlinkTournaments"})}function cE({tournamentRecords:t,tournamentId:e}){if(typeof t!="object")return{error:G};if(!e)return{error:Xs};let r=zu({tournamentRecords:t}),{tournamentIds:n}=r;if(!n.includes(e))return{error:Xs};let o;return n.every(i=>{let s=t[i],{extension:a}=ut({element:s,name:sa});if(!a)return!0;let c=a?.value?.tournamentIds||[];if(!c?.length||c.length===1&&c.includes(e)||i===e){let m=Hl({name:sa,tournamentRecord:s});return m.error&&(o=m.error),m.success}let u=c.filter(m=>m!==e);a.value={tournamentIds:u};let p=Bl({tournamentRecord:s,extension:a});return p.error&&(o=p.error),p.success}),o?{error:o}:{...R}}var pE={};ne(pE,{getLinkedTournamentIds:()=>kc,getTournamentIds:()=>zu});function kc({tournamentRecords:t}){return typeof t!="object"||!Object.keys(t).length?{error:wt}:{linkedTournamentIds:Object.assign({},...Object.keys(t).map(r=>{let n=t[r],o=n?.tournamentId,{extension:i}=ut({element:n,name:sa}),s=(i?.value?.tournamentIds||[]).filter(a=>a!==o);return{[r]:s}}))}}var dN={};ne(dN,{addAdHocMatchUps:()=>rd,addDrawDefinitionTimeItem:()=>Hf,addFinishingRounds:()=>Cs,addGoesTo:()=>rs,addPlayoffStructures:()=>Sp,addQualifyingStructure:()=>yU,addVoluntaryConsolationStage:()=>TU,addVoluntaryConsolationStructure:()=>_f,allPlayoffPositionsFilled:()=>bh,alternateDrawPositionAssignment:()=>iU,assignDrawPosition:()=>xU,assignDrawPositionBye:()=>yr,attachConsolationStructures:()=>bU,attachPlayoffStructures:()=>qf,attachQualifyingStructure:()=>Bf,attachStructures:()=>$f,autoSeeding:()=>GU,automatedPlayoffPositioning:()=>pc,automatedPositioning:()=>uc,checkValidEntries:()=>sd,deleteAdHocMatchUps:()=>wU,drawMatic:()=>Cd,findDrawDefinition:()=>eS,generateAdHocMatchUps:()=>Su,generateAdHocRounds:()=>Md,generateAndPopulatePlayoffStructures:()=>ed,generateDrawDefinition:()=>Uu,generateDrawMaticRound:()=>ud,generateDrawStructuresAndLinks:()=>ad,generateDrawTypeAndModifyDrawDefinition:()=>cd,generateQualifyingStructure:()=>qm,generateVoluntaryConsolation:()=>AS,getAssignedParticipantIds:()=>di,getAvailablePlayoffProfiles:()=>cu,getDrawDefinitionTimeItem:()=>dh,getDrawParticipantRepresentativeIds:()=>Zh,getDrawTypeCoercion:()=>hu,getEligibleVoluntaryConsolationParticipants:()=>Jh,getParticipantIdFinishingPositions:()=>tS,getPositionAssignments:()=>yp,getPositionsPlayedOff:()=>dc,getSeedingThresholds:()=>Eh,getSeedsCount:()=>gu,getStructureSeedAssignments:()=>vr,getTeamLineUp:()=>ts,getValidGroupSizes:()=>dp,isAdHoc:()=>Br,isCompletedStructure:()=>qo,isValidForQualifying:()=>IS,luckyLoserDrawPositionAssignment:()=>oU,modifyDrawDefinition:()=>OU,modifyDrawName:()=>Kf,modifySeedAssignment:()=>uU,mutate:()=>kU,positionActions:()=>gS,pruneDrawDefinition:()=>vU,qualifierDrawPositionAssignment:()=>aU,query:()=>JU,removeDrawPositionAssignment:()=>su,removeRoundMatchUps:()=>LU,removeSeededParticipant:()=>AU,removeStructure:()=>SU,renameStructures:()=>hU,resetDrawDefinition:()=>_U,resetVoluntaryConsolationStructure:()=>RE,setDrawParticipantRepresentativeIds:()=>lE,setPositionAssignments:()=>sU,setStructureOrder:()=>IU,setSubOrder:()=>FU,swapDrawPositionAssignments:()=>cU,updateTeamLineUp:()=>_i,withdrawParticipantAtDrawPosition:()=>rU});var kU={};ne(kU,{addAdHocMatchUps:()=>rd,addDrawDefinitionTimeItem:()=>Hf,addFinishingRounds:()=>Cs,addGoesTo:()=>rs,addPlayoffStructures:()=>Sp,addQualifyingStructure:()=>yU,addVoluntaryConsolationStage:()=>TU,addVoluntaryConsolationStructure:()=>_f,alternateDrawPositionAssignment:()=>iU,assignDrawPosition:()=>xU,assignDrawPositionBye:()=>yr,attachConsolationStructures:()=>bU,attachPlayoffStructures:()=>qf,attachQualifyingStructure:()=>Bf,attachStructures:()=>$f,autoSeeding:()=>GU,automatedPlayoffPositioning:()=>pc,automatedPositioning:()=>uc,deleteAdHocMatchUps:()=>wU,luckyLoserDrawPositionAssignment:()=>oU,modifyDrawDefinition:()=>OU,modifyDrawName:()=>Kf,modifySeedAssignment:()=>uU,pruneDrawDefinition:()=>vU,qualifierDrawPositionAssignment:()=>aU,removeDrawPositionAssignment:()=>su,removeRoundMatchUps:()=>LU,removeSeededParticipant:()=>AU,removeStructure:()=>SU,renameStructures:()=>hU,resetDrawDefinition:()=>_U,resetVoluntaryConsolationStructure:()=>RE,setDrawParticipantRepresentativeIds:()=>lE,setPositionAssignments:()=>sU,setStructureOrder:()=>IU,setSubOrder:()=>FU,swapDrawPositionAssignments:()=>cU,updateTeamLineUp:()=>_i,withdrawParticipantAtDrawPosition:()=>rU});var dE=t=>e=>t[e],lm=(t=[])=>t.map(le).filter(Boolean),Wl=(t=[])=>t.map(ft).filter(Boolean),ft=(t={})=>dE(t)("participantId");var le=(t={})=>dE(t)("matchUpId"),Qu=(t={})=>dE(t)("drawId");function lE({representativeParticipantIds:t,drawDefinition:e}){if(!e)return{error:fr};if(!Array.isArray(t))return{error:G};let r=Wl(e?.entries||[]);return t.length&&Wt(t,r).length<t.length?{error:G}:$u({drawDefinition:e,extension:{name:bI,value:t}})}var kr="ABANDONED",Xa="AWAITING_RESULT",Ut="BYE",Lo="CANCELLED",me="COMPLETED",Vc="DEAD_RUBBER",bt="DEFAULTED",Me="DOUBLE_DEFAULT",fe="DOUBLE_WALKOVER",Sn="IN_PROGRESS",No="INCOMPLETE",fE="NOT_PLAYED",mr="RETIRED",Ki="SUSPENDED",Kt="TO_BE_PLAYED",Ot="WALKOVER",vC=[Xa,me,bt,Sn,No,mr,Ki],_I=[Xa,me,bt,fe,Me,Sn,No,mr,Ki,Ot],vI=[kr,Xa,Ut,Lo,me,Vc,bt,fe,Me,Sn,No,fE,mr,Ki,Kt,Ot],xI=[Ut,fe,Me,me,bt,mr,Ot],wI=[kr,Xa,Lo,Vc,Sn,No,fE,Ki,Kt,void 0],ie=[Lo,kr,me,Vc,bt,fe,Me,mr,Ot],fm=[kr,me,bt,fe,Me,Sn,mr,Ot],LI=[Sn,No,Ki,Kt],FI={ABANDONED:kr,AWAITING_RESULT:Xa,BYE:Ut,CANCELLED:Lo,COMPLETED:me,DEAD_RUBBER:Vc,DEFAULTED:bt,DOUBLE_WALKOVER:fe,DOUBLE_DEFAULT:Me,IN_PROGRESS:Sn,INCOMPLETE:No,NOT_PLAYED:fE,RETIRED:mr,SUSPENDED:Ki,TO_BE_PLAYED:Kt,WALKOVER:Ot};var tt="MAIN",at="QUALIFYING",Ge="CONSOLATION",ke="VOLUNTARY_CONSOLATION",ae="PLAY_OFF",gm=[tt,at,Ge,ae,ke],Ds={[at]:1,[tt]:2,[ae]:3,[Ge]:3,[ke]:4},gE="finishingPositions",IE="aggregateEventStructures",hE={[tt]:1,[ae]:2,[Ge]:3,[at]:4,[ke]:5},xC={[ae]:1,[tt]:2,[Ge]:3,[at]:4,[ke]:5},Bc="CLUSTER",wC="SEPARATE",ei="WATERFALL",Xu="ITEM",we="CONTAINER",Wr="DRAW",Ju="RANDOM",rn="TOP_DOWN",Fo="BOTTOM_UP",kn="POSITION",Jn="WINNER",Vn="LOSER",Bn="FIRST_MATCHUP",br="AD_HOC",pL="AD_HOC",ua="FEED_IN",Hc="COMPASS",Wc="OLYMPIC",mL="SINGLE_ELIMINATION";var Zn="SINGLE_ELIMINATION",jc="DOUBLE_ELIMINATION",Yc="FIRST_MATCH_LOSER_CONSOLATION",Zu="FIRST_ROUND_LOSER_CONSOLATION",Mi="LUCKY_DRAW",jl="CURTIS_CONSOLATION",LC="CURTIS_CONSOLATION",GI="FEED_IN_CHAMPIONSHIP_TO_SF",Im="FEED_IN_CHAMPIONSHIP_TO_SF",kI="FEED_IN_CHAMPIONSHIP_TO_QF",hm="FEED_IN_CHAMPIONSHIP_TO_QF",VI="FEED_IN_CHAMPIONSHIP_TO_R16",Sm="FEED_IN_CHAMPIONSHIP_TO_R16",SE="MODIFIED_FEED_IN_CHAMPIONSHIP",Tm="MODIFIED_FEED_IN_CHAMPIONSHIP",tp="FEED_IN_CHAMPIONSHIP",un="ROUND_ROBIN",to="ROUND_ROBIN_WITH_PLAYOFF",TE="DECIDER",AE="BACKDRAW",Yl={0:{name:"East",abbreviation:"E"},"0-1":{name:"West",abbreviation:"W"},"0-2":{name:"North",abbreviation:"N"},"0-3":{name:"Northeast",abbreviation:"NE"},"0-1-1":{name:"South",abbreviation:"S"},"0-1-2":{name:"Southwest",abbreviation:"SW"},"0-2-1":{name:"Northwest",abbreviation:"NW"},"0-1-1-1":{name:"Southeast",abbreviation:"SE"}},ql={0:{name:"East",abbreviation:"E"},"0-1":{name:"West",abbreviation:"W"},"0-2":{name:"North",abbreviation:"N"},"0-1-1":{name:"South",abbreviation:"S"}},Ms="WIN_RATIO",Ci="ROUND_OUTCOME",yE=[Hc,jl,hm,Sm,Im,tp,kI,VI,GI,Yc,Zu,Mi,Tm,Wc,ae,to],dL=[br,Hc,jl,jc,hm,Sm,Im,tp,ua,Yc,Zu,Mi,Tm,Wc,ae,un,to,Zn],EE={MAIN:tt,QUALIFYING:at,CONSOLATION:Ge,ITEM:Xu,CONTAINER:we,FIRST_MATCHUP:Bn,WINNER:Jn,LOSER:Vn,AD_HOC:br,FEED_IN:ua,FLEX_ROUNDS:pL,COMPASS:Hc,PLAY_OFF:ae,OLYMPIC:Wc,KNOCKOUT:mL,SINGLE_ELIMINATION:Zn,DOUBLE_ELIMINATION:jc,CURTIS:jl,FICSF:GI,FICQF:kI,FICR16:VI,MFIC:SE,VOLUNTARY_CONSOLATION:ke,FIRST_MATCH_LOSER_CONSOLATION:Yc,FIRST_ROUND_LOSER_CONSOLATION:Zu,MODIFIED_FEED_IN_CHAMPIONSHIP:Tm,FEED_IN_CHAMPIONSHIP_TO_R16:Sm,FEED_IN_CHAMPIONSHIP_TO_QF:hm,FEED_IN_CHAMPIONSHIP_TO_SF:Im,FEED_IN_CHAMPIONSHIP:tp,LUCKY_DRAW:Mi,ROUND_ROBIN_WITH_PLAYOFF:to,ROUND_ROBIN:un,DECIDER:TE,BACKDRAW:AE,COMPASS_ATTRIBUTES:Yl,OLYMPIC_ATTRIBUTES:ql,DRAW:Wr,RANDOM:Ju,TOP_DOWN:rn,BOTTOM_UP:Fo,WATERFALL:ei,WIN_RATIO:Ms,ROUND_OUTCOME:Ci,MULTI_STRUCTURE_DRAWS:yE,generatedDrawTypes:dL,stageOrder:Ds,finishOrder:hE,AGGREGATE_EVENT_STRUCTURES:IE,FINISHING_POSITIONS:gE},FC=EE;function ri(t,e,r){let n=m=>ut({element:m,name:cn})?.extension?.value,o=r?.deprioritizeCompleted,i=r?.mode===IE&&xC,s=r?.mode===gE&&hE,a=s||i||Ds,c=m=>m?.stage===tt&&m?.stageSequence===1,u=m=>c(m)?-1:a[m?.stage],p=m=>m?.matchUps.every(({matchUpStatus:d})=>ie.includes(d)?1:-1);return o&&p(t)-p(e)||i&&u(t)-u(e)||(t?.stage&&a[t.stage]||0)-(e?.stage&&a[e.stage]||0)||(n(t)||0)-(n(e)||0)||!s&&!i&&(e?.positionAssignments?.length??1/0)-(t?.positionAssignments?.length??1/0)||(t?.stageSequence??0)-(e?.stageSequence??0)||($l(t)||0)-($l(e)||0)}function $l(t){return(t?.matchUps||[]).reduce((e,r)=>{let n=(r.finishingPositionRange?.winner||[]).reduce((o,i)=>o+i,0);return!e||n<e?n:e},void 0)}function st({drawDefinition:t,structureId:e}){if(!t)return{error:z};if(!e)return{error:We};let{structures:r}=Cn({drawDefinition:t}),n=r?.map(s=>s.structures?[...s.structures].concat(s):s).flat(),o=n?.find(s=>s.structureId===e);if(!o)return{error:_t};let i=o.structureType===Xu?n?.find(s=>s.structures?.some(a=>a.structureId===e)):void 0;return{structure:o,containingStructure:i}}function Cn({withStageGrouping:t,drawDefinition:e,stageSequences:r,stageSequence:n,roundTarget:o,sortConfig:i,stages:s,stage:a}){let c=!e&&z||!e?.structures&&el||void 0;if(c)return{error:c,structures:[],stageStructures:{}};let u=f=>{let g=ut({element:f,name:cn})?.extension?.value;return!o||o===g},p=e?.structures?.filter(d).filter(l).filter(u).sort((f,g)=>ri(f,g,i))??[],m=t?Object.assign({},...gm.map(f=>{let g=p?.filter(I=>I.stage===f);return g?.length&&{[f]:g}}).filter(Boolean)):{};return{structures:p,stageStructures:m};function d(f){return!a&&!Array.isArray(s)||a&&f.stage===a||Array.isArray(s)&&s.includes(f.stage)}function l(f){return!n&&!Array.isArray(r)||n&&f.stageSequence===n||Array.isArray(r)&&r.includes(f.stageSequence)}}function BI({drawDefinition:t}){if(!t)return{error:z};let e={};return{allPositionedParticipantIds:(t.structures||[]).map(n=>{let o=n.stage;e[o]||(e[o]=[]);let{positionAssignments:i}=Dt({structure:n}),s=i?.map(ft).filter(Boolean)??[];return e[o].push(...s),s}).flat(),stagePositionedParticipantIds:e}}function Dt({drawDefinition:t,structureId:e,structure:r}){let n,o=[];if(!r){if(!t)return{positionAssignments:o,error:z};if({structure:r,error:n}=st({drawDefinition:t,structureId:e}),n)return{positionAssignments:o,error:n}}return r.structures?o=[].concat(...r.structures.map(i=>Dt({structure:i}).positionAssignments)):r.positionAssignments?o=r.positionAssignments:n=ZA,{positionAssignments:o,error:n}}function de({drawDefinition:t,structureId:e,structure:r}){let n=Dt({drawDefinition:t,structureId:e,structure:r})?.positionAssignments||[],o=n?.filter(u=>u.participantId??u.bye??u.qualifier),i=n&&n?.length===o?.length,s=n?.filter(u=>!u.participantId&&!u.bye&&!u.qualifier),a=n?.filter(u=>!u.participantId&&u.bye),c=n?.filter(u=>!u.participantId&&u.qualifier);return{allPositionsAssigned:i,positionAssignments:n,unassignedPositions:s,assignedPositions:o,qualifierPositions:c,byePositions:a}}var Kl="addDrawDefinition",ep="addMatchUps",Go="addParticipants",zl="addScaleItems",HI="addVenue",pa="audit",Ql="deleteParticipants",Xl="deleteVenue",Jl="deletedDrawIds",Zl="deletedMatchUpIds",tf="modifyDrawDefinition",UE="modifyDrawEntries",PE="modifyEventEntries",ef="modifyMatchUp",$e="modifyParticipants",rf="modifyPositionAssignments",nf="modifySeedAssignments",NE="modifyTournamentDetail",ni="modifyVenue",Am="mutations",DE="publishEvent",ME="publishEventSeeding",CE="publishOrderOfPlay",of="unPublishEvent",sf="unPublishEventSeeding",af="unPublishOrderOfPlay",rp="updateInContextMatchUp",GC={ADD_DRAW_DEFINITION:Kl,ADD_MATCHUPS:ep,ADD_PARTICIPANTS:Go,ADD_SCALE_ITEMS:zl,ADD_VENUE:HI,AUDIT:pa,DELETE_PARTICIPANTS:Ql,DELETE_VENUE:Xl,DELETED_DRAW_IDS:Jl,DELETED_MATCHUP_IDS:Zl,MODIFY_DRAW_DEFINITION:tf,MODIFY_DRAW_ENTRIES:UE,MODIFY_EVENT_ENTRIES:PE,MODIFY_MATCHUP:ef,MODIFY_PARTICIPANTS:$e,MODIFY_POSITION_ASSIGNMENTS:rf,MODIFY_SEED_ASSIGNMENTS:nf,MODIFY_TOURNAMENT_DETAIL:NE,MODIFY_VENUE:ni,MUTATIONS:Am,PUBLISH_EVENT_SEEDING:ME,PUBLISH_EVENT:DE,PUBLISH_ORDER_OF_PLAY:CE,UNPUBLISH_EVENT_SEEDING:sf,UNPUBLISH_EVENT:of,UNPUBLISH_ORDER_OF_PLAY:af,UPDATE_INCONTEXT_MATCHUP:rp};function WI(t,e){if(!t)return{error:z};let r=Date.now();t.updatedAt&&r===new Date(t.updatedAt).getTime()&&(r+=1);let n=new Date(r).toISOString(),o=e?.filter(Boolean);return t.updatedAt=n,t.structures?.filter(Boolean).forEach(i=>{(!o?.length||o?.includes(i.structureId))&&(i.updatedAt=n)}),{...R}}function lo({drawDefinition:t,tournamentId:e,matchUps:r,eventId:n}){return t&&WI(t),Tt({payload:{matchUps:r,tournamentId:e,eventId:n},topic:ep}),{...R}}function Rn({drawDefinition:t,tournamentId:e,matchUpIds:r,eventId:n,action:o}){t&&WI(t),Tt({topic:Zl,payload:{tournamentId:e,matchUpIds:r,eventId:n,action:o}});for(let i of r)dI({key:i});return{...R}}function ht({drawDefinition:t,tournamentId:e,structureId:r,context:n,eventId:o,matchUp:i}){return i?(t&&Rt({drawDefinition:t,structureIds:r?[r]:void 0,tournamentId:e,eventId:o}),Tt({topic:ef,payload:{matchUp:i,tournamentId:e,context:n},key:i.matchUpId}),{...R}):(console.log(or),{error:or})}function kC({tournamentId:t,inContextMatchUp:e}){return e?(Tt({payload:{inContextMatchUp:e,tournamentId:t},topic:rp,key:e.matchUpId}),{...R}):{error:or}}function ma({tournamentId:t,eventId:e,drawDefinition:r}){return r?(WI(r),Tt({payload:{drawDefinition:r,tournamentId:t,eventId:e},topic:Kl,key:r.drawId}),{...R}):(console.log(z),{error:z})}function VC({tournamentId:t,eventId:e,drawId:r}){return Tt({payload:{drawId:r,tournamentId:t,eventId:e},topic:Jl,key:r}),dI({key:r}),{...R}}function Rt({drawDefinition:t,tournamentId:e,structureIds:r,eventId:n}){return t?(WI(t,r),Tt({payload:{tournamentId:e,eventId:n,drawDefinition:t},topic:tf,key:t.drawId}),{...R}):{error:z}}function jI({drawDefinition:t,tournamentId:e,structure:r,eventId:n}){if(!t)return{error:z};if(!r)return{error:Ao};let o=r.seedAssignments,i=r.structureId,s=t.drawId;return Tt({payload:{tournamentId:e,eventId:n,drawId:s,structureId:i,seedAssignments:o},topic:nf,key:t.drawId}),Rt({structureIds:[i],drawDefinition:t,tournamentId:e,eventId:n}),{...R}}function fo({drawDefinition:t,tournamentId:e,structure:r,event:n}){if(!t)return{error:z};if(!r)return{error:Ao};let o=Dt({structure:r}),i=r.structureId,s=t.drawId,a=n?.eventId;return Tt({topic:rf,payload:{positionAssignments:o,tournamentId:e,structureId:i,eventId:a,drawId:s},key:i}),Rt({structureIds:[i],drawDefinition:t,tournamentId:e,eventId:a}),{...R}}function RE({tournamentRecord:t,drawDefinition:e,resetEntries:r,event:n}){if(!e)return{error:z};let o=e.structures?.find(s=>s.stage===ke);if(!o)return{error:_t};let i=o.matchUps?.map(({matchUpId:s})=>s)||[];return o.positionAssignments=[],o.seedAssignments=[],o.matchUps=[],Rn({tournamentId:t?.tournamentId,action:"resetVoluntaryConsolationStructure",matchUpIds:i,drawDefinition:e}),r&&(e.entries=e.entries.filter(s=>s.entryStage!==ke)),Rt({tournamentId:t?.tournamentId,eventId:n?.eventId,drawDefinition:e,structureIds:[o.structureId]}),{...R}}function ym({drawPositions:t,structure:e}){if([at,tt].includes(e.stage)&&e.stageSequence===1)return;let{positionAssignments:r}=Dt({structure:e});r?.filter(({drawPosition:o})=>t?.includes(o))?.forEach(o=>{gt({element:o,extension:{name:um,value:!0}})})}function qc({drawDefinition:t,positionAction:e}){let{extension:r}=ut({name:am,element:t}),n=Array.isArray(r?.value)?r?.value??[]:[];if(!n?.length){let i=t.structures.find(s=>s.stage===tt);if(i){let s=Dt({structure:i}).positionAssignments?.map(({drawPosition:a,participantId:c,bye:u,qualifier:p})=>({drawPosition:a,participantId:c,qualifier:p,bye:u}));n.push({name:"initialMainAssignments",initialAssignments:s})}}let o={name:am,value:n.concat(e)};gt({element:t,extension:o})}function zi({tournamentRecord:t,drawDefinition:e,event:r}){let o=(t?.events||r&&[r])?.map(c=>c?.drawDefinitions).flat().filter(Boolean)||e&&[e]||[],i={},s={},a=o.map(c=>c?.structures?.filter(u=>u?.structures)).flat().filter(Boolean);for(let c of a){let{structures:u,structureId:p}=c??{};u&&p&&(i[p]=u?.map(m=>m.structureId))&&u.forEach(m=>s[m.structureId]=c?.structureId)}return{containedStructures:i,containerStructures:s}}var da="SINGLES",ee="SINGLES",Ri="DOUBLES",jt="DOUBLES",pn="TEAM",Bt="TEAM",BC={SINGLES_MATCHUP:da,SINGLES:ee,DOUBLES_MATCHUP:Ri,DOUBLES:jt,TEAM_MATCHUP:pn,TEAM:Bt};function $c(t){let{sides:e,matchUpType:r}=t||{},n=t.potentialParticipants?.length?t.potentialParticipants.flat().map(s=>r===jt?s?.individualParticipantIds||[]:s.participantId).flat():[],o=(e||[]).map(s=>r===jt&&(s?.participant?.individualParticipantIds||[])||s?.participantId&&[s.participantId]||[]).flat();return{individualParticipantIds:o.concat(n).flat(),enteredIndividualParticipantIds:o,potentialIndividualParticipantIds:n}}function jr(t){return t?.tournamentRecords??(t?.tournamentRecord&&{[t.tournamentRecord.tournamentId]:t.tournamentRecord})??{}}function cf(t){if(!Ct(t))return!1;let{matchUpId:e,drawPositions:r}=t,n=typeof e=="string",o=!r||Array.isArray(r)&&r.length<=2&&r.every(i=>lt(i)||i===void 0||i===null);return n&&o}function Ar(t){return Array.isArray(t)?t.every(cf):!1}function Xe({matchUps:t=[],interpolate:e}){if(!Ar(t))return{roundMatchUps:[],error:G};let r=t.reduce((d,l)=>{let f=typeof l.roundNumber=="string"?ct(l.roundNumber):l.roundNumber;return!l.roundNumber||d.includes(f)?d:d.concat(f)},[]).sort(oe).map(d=>{let l=t.filter(h=>h.roundNumber===d),g=l.find(({matchUpType:h})=>h===Bt)?l.filter(({matchUpType:h})=>h===Bt):l,I=h=>h.sort((S,T)=>oe(S.roundPosition,T.roundPosition));return{[d]:I(g)}}),n=t.reduce((d,l)=>{let f=typeof l.roundNumber=="string"?ct(l.roundNumber):l.roundNumber;return d[f]||(d[f]=rt({abbreviatedRoundName:l.abbreviatedRoundName,finishingRound:l.finishingRound,roundName:l.roundName})),d},{}),o=Object.assign({},...r);if(e){let d=Math.max(...Object.keys(o).map(f=>ct(f)).filter(f=>!isNaN(f))),l=o[d]?.length;if(l>1&&gn(l)){let f=d+1,g=f+l/2;Z(f,g).forEach((h,S)=>{o[h]=Z(0,l/(2+S*2)).map(()=>({}))})}}let i=0,s=Object.assign({},...Object.keys(o).map(d=>{let l=o[d]?.length,f=o[d]?.filter(I=>!ie.includes(I.matchUpStatus)&&!I.score?.scoreStringSide1)?.length,g=l&&l===f;return i=Math.max(i,l),{[d]:{matchUpsCount:l,inactiveCount:f,inactiveRound:g}}})),a=0,c=0,u=Object.keys(o).map(d=>ct(d)).filter(d=>!isNaN(d));u.forEach(d=>{let l=o[d].sort((g,I)=>g.roundPosition-I.roundPosition),f=l.map(g=>g?.drawPositions||[]).flat();if(s[d].roundNumber=d,s[d].roundFactor=s[d].matchUpsCount?i/s[d].matchUpsCount:1,s[d].finishingRound=n[d]?.finishingRound,s[d].roundName=n[d]?.roundName,s[d].abbreviatedRoundName=n[d]?.abbreviatedRoundName,s[d].finishingPositionRange=o[d]?.[0]?.finishingPositionRange,d===1||!s[d-1]){let g=f.sort(oe),I=Ae(g,2);s[d].drawPositions=g,s[d].pairedDrawPositions=I}else{let g=s[d-1],I=g.drawPositions,h=g.matchUpsCount/s[d].matchUpsCount,S=Ae(I,h),T=l.map(A=>{let{roundPosition:P}=A,y=[...A.drawPositions||[],void 0,void 0].slice(0,2);if(!P)return y;let E=y?.filter(Boolean)||[];if(!E?.length)return[void 0,void 0];if(d<3&&E?.length===2)return y?.slice().sort(oe);let U=Wt(I,E).length!==E?.length;if(E?.length&&U)return E?.length===1?[E[0],void 0]:y?.slice().sort(oe);let M=(P-1)*2;return S.slice(M,M+2).map(C=>E?.find(D=>C.includes(D)))});s[d].drawPositions=T?.flat(),s[d].pairedDrawPositions=T}s[d+1]&&s[d+1].matchUpsCount===s[d].matchUpsCount&&(s[d+1].feedRound=!0,s[d+1].feedRoundIndex=c,s[d].preFeedRound=!0,c+=1),s[d]&&!s[d].feedRound&&(s[d].roundIndex=a,a+=1)});let p=!!Object.values(s).find(({matchUpsCount:d})=>!gn(d));return{hasNoRoundPositions:t.some(d=>!d.roundPosition),roundsNotPowerOf2:p,maxMatchUpsCount:i,roundMatchUps:o,roundNumbers:u,roundProfile:s,...R}}function Cs({finishingPositionOffset:t=0,finishingPositionLimit:e,positionsFed:r,roundsCount:n,roundLimit:o,matchUps:i,lucky:s,fmlc:a}){if(!Ar(i))return[];let{roundProfile:c,roundNumbers:u=[]}=Xe({interpolate:!0,matchUps:i});n=n??Math.max(...u,0);let p=o?n-o:0,m=p&&c?.[n-p]?.matchUpsCount,d=c&&Object.values(c).map(Dr("matchUpsCount")),l=(I,h)=>{let S=Math.min(...I);m&&h&&S===1&&(S=m);let T=Math.max(...I);return e&&T>e&&(T=e),[S,T]},f=c&&Object.assign({},...u.map(I=>{let h=(n??0)+1-I-p,S=c[I].matchUpsCount,T={finishingPositionRange:{},finishingRound:h},A=d?.slice(I-1).reduce((D,O)=>D+(O||0),0),P=a&&I!==1,y=1+t+(P?r??0:0),E=1,U=Z(y,s?y+S*2:A+y+E),M=A+E-S,N=l(U.slice(M)),C=l(U.slice(0,M),!0);return T.finishingPositionRange={loser:N,winner:C},{[I]:T}})),g=Tr({finishingRound:!0});return i.filter(Boolean).forEach(I=>{let h=I.roundNumber&&f[I.roundNumber];g&&!h&&console.log({roundFinishingData:f,matchUp:I}),I.finishingRound=h?.finishingRound,I.finishingPositionRange=h?.finishingPositionRange}),i}function be({drawDefinition:t,structure:e}){let r={},n=[];return(t?.structures??[e]).filter(o=>o&&typeof o=="object").forEach(o=>{if(!o)return;let{structureId:i,matchUps:s,structures:a}=o,c=Array.isArray(a);if(c)c&&a.forEach(u=>{let{structureName:p}=u,m=u.matchUps;r[u.structureId]={matchUps:m,itemStructureIds:[],structureName:p},m&&(n.push(...m),m.forEach(d=>{d.tieMatchUps&&n.push(...d.tieMatchUps)})),r[i]||(r[i]={itemStructureIds:[],matchUps:[]}),r[i].itemStructureIds||(r[i].itemStructureIds=[]),r[i].itemStructureIds.push(u.structureId)});else{let u=s;r[i]={matchUps:u,itemStructureIds:[]},u?.forEach(p=>{n.push(p),p.tieMatchUps&&n.push(...p.tieMatchUps)})}}),{mappedMatchUps:r,drawMatchUps:n}}function ko({mappedMatchUps:t,matchUpsMap:e,structureId:r,inContext:n}){t=e?.mappedMatchUps??t;let o=t[r],i=(o?.itemStructureIds||[]).map(s=>{let{matchUps:a,structureName:c}=t[s];return n?a.map(u=>Object.assign(J(u,!0,!0),{containerStructureId:r,structureId:s,structureName:c})):a}).flat();return(o?.matchUps||[]).concat(...i)}var Ja="SIGN_IN_STATUS",bE="SIGNED_OUT",Kc="SIGNED_IN",Yr="TEAM",It="INDIVIDUAL",hr="GROUP",pt="PAIR",Lt="TEAM",zc={TEAM_PARTICIPANT:Yr,INDIVIDUAL:It,GROUP:hr,TEAM:Lt,PAIR:pt},HC={INDIVIDUAL:It,GROUP:hr,PAIR:pt,TEAM:Lt,SIGN_IN_STATUS:Ja,SIGNED_OUT:bE,SIGNED_IN:Kc};function Em({participantsProfile:t,participants:e=[],deepCopy:r}){let n=new Map,o=r!==!1?J(e,t?.convertExtensions,!0):e,i=o.filter(c=>c.participantType===Lt),s=o.filter(c=>c.participantType===hr),a=o.filter(c=>c.participantType===pt);return o.forEach(c=>{if(c.participantType===It){let{participantId:u}=c;c.groupParticipantIds=[],c.teamParticipantIds=[],c.pairParticipantIds=[],c.groups=[],c.teams=[],i.forEach(p=>{(p?.individualParticipantIds||[]).forEach(m=>{m===u&&!c.teamParticipantIds?.includes(p.participantId)&&(c.teamParticipantIds.push(p.participantId),n.get(p.participantId)||n.set(p.participantId,{participantName:p.participantName,participantId:p.participantId}),c.teams.push({participantRoleResponsibilities:p.participantRoleResponsibilities,participantOtherName:p.participantOtherName,participantName:p.participantName,participantId:p.participantId,teamId:p.teamId}))})}),a.forEach(p=>{(p?.individualParticipantIds||[]).forEach(m=>{m===u&&!c.pairParticipantIds.includes(p.participantId)&&c.pairParticipantIds.push(p.participantId)})}),s.forEach(p=>{(p?.individualParticipantIds||[]).forEach(m=>{m===u&&!c.groupParticipantIds.includes(p.participantId)&&(c.groupParticipantIds.push(p.participantId),c.groups.push({participantRoleResponsibilities:p.participantRoleResponsibilities,participantOtherName:p.participantOtherName,participantName:p.participantName,participantId:p.participantId}))})})}}),{participantsWithGroupings:o,groupInfo:Object.fromEntries(n)}}function WC({drawDefinition:t,roundNumber:e,structureId:r}){if(!t)return{error:z};if(!r)return{error:We};let{links:n}=Rs({drawDefinition:t,structureId:r}),o=n.source.reduce((s,a)=>!a.source.roundNumber||a.source.roundNumber===e?s.concat(a):s,[]),i=n.target.reduce((s,a)=>!a.target.roundNumber||a.target.roundNumber===e?s.concat(a):s,[]);return{links:{source:o,target:i}}}function YI({finishingPositions:t,linkCondition:e,linkType:r,source:n}){let o=n.find(i=>{let s=!i.source?.finishingPositions||!t||ve(t,i.source?.finishingPositions);return e===i.linkCondition&&s&&i.linkType===r});return[Jn,Vn].includes(o?.linkType)&&!o?.source?.roundNumber?v({result:{error:G},stack:"getTargetLink",context:o}):o}function Rs({drawDefinition:t,structureId:e,roundNumber:r}){return t?e?{links:(t.links||[]).filter(Boolean).reduce((i,s)=>(s.source?.structureId===e&&(!r||s.source.roundNumber===r)&&(i.source=i.source.concat(s)),s.target?.structureId===e&&(!r||s.target.roundNumber===r)&&(i.target=i.target.concat(s)),i),{source:[],target:[]})}:{error:We}:{error:z}}function jC({structureMatchUps:t,matchUp:e}){let{roundNumber:r,roundPosition:n}=e,o=t.filter(s=>s.roundNumber===r&&!s.matchUpTieId),i=t.filter(s=>s.roundNumber===r+1&&!s.matchUpTieId);if(i.length){let s;return i.length===o.length?s=i.find(a=>a.roundPosition===n):i.length===o.length/2&&(s=i.find(a=>a.roundPosition===Math.ceil(n/2))),{matchUp:s}}return{message:"no progression found"}}function qI({groupedOrder:t,roundPositionsCount:e}){if(!t||t?.length<=e)return t;let n=Ae(t,t.length/e).map(i=>i.reduce((s,a)=>s+a)),o=n.slice().sort(oe);return n.map(i=>o.indexOf(i)+1)}function $I({sourceRoundMatchUpCount:t,inContextDrawMatchUps:e,sourceRoundPosition:r,drawDefinition:n,targetLink:o}){if(!o)return{error:tl};let{target:{structureId:i,feedProfile:s,groupedOrder:a,roundNumber:c,positionInterleave:u}}=o,{structure:p}=st({drawDefinition:n,structureId:i}),{positionAssignments:m}=Dt({structure:p}),l=(e?.filter(N=>N.structureId===p?.structureId)).filter(N=>N.roundNumber===c&&!N.matchUpTieId),f=l.length,g=Z(1,f+1),I=f/t,h=Math.ceil(I*r),S=1-r%2;if(u?.interleave&&I!==.5){let N=u.offset+(r-1)*u.interleave,C=r+N;h=Math.ceil(C/2),S=1-C%2}let T=g,A=g[h-1],P=qI({groupedOrder:a,roundPositionsCount:g.length}),y=P?.length||1;if(y<=g.length){let N=f/y,C=Ae(g,N);s===Fo&&C.forEach(D=>D.reverse()),T=P?.length&&P?.map(D=>C[D-1]).flat()||T}s===rn?A=T[h-1]:s===Fo?((!P?.length||y>g.length)&&(h=l.length+1-h),A=T[h-1]):s===Ju&&Tr()&&console.log(Vu,{feedProfile:s});let E=A&&l.reduce((N,C)=>C.roundPosition===A?C:N,void 0),U;E?.feedRound?(S=0,U=Math.min(...(E.drawPositions||[]).filter(Boolean))):U=E?.drawPositions?.length===2&&E?.drawPositions[S];let M=m?.find(({drawPosition:N})=>N===U);if(M){let{extension:N}=ut({element:M,name:um});if(N?.value)return{disabledDrawPosition:U}}return{matchUp:E,targetDrawPosition:U,matchUpDrawPositionIndex:S}}function Je({inContextDrawMatchUps:t=[],useTargetMatchUpIds:e,inContextMatchUp:r,drawDefinition:n,matchUpId:o}){let i=r;t.length&&!i&&(i=t.find(c=>c.matchUpId===o));let{structure:s}=st({structureId:i?.structureId,drawDefinition:n});return s?.finishingPosition===Ci?lL({inContextDrawMatchUps:t,useTargetMatchUpIds:e,drawDefinition:n,structure:s,matchUp:i}):fL({matchUp:i})}function lL({inContextDrawMatchUps:t,useTargetMatchUpIds:e,drawDefinition:r,structure:n,matchUp:o}){let{winnerMatchUpId:i,loserMatchUpId:s}=o,{links:a}=WC({roundNumber:o.roundNumber,structureId:n.structureId,drawDefinition:r}),c=a?.source,u=YI({source:c,linkType:Jn}),p=YI({linkCondition:Bn,linkType:Vn,source:c}),m=YI({source:c,linkType:Vn}),d=p&&m;m||(m=p);let l=u?.target?.feedProfile,f=m?.target?.feedProfile,g=p?.target?.feedProfile,I,h,S,T,A,P,y,E,U,M;if(e&&(i||s)&&(y=i&&l!==Wr&&t.find(({matchUpId:D})=>D===i),T=s&&f!==Wr&&t.find(({matchUpId:D})=>D===s),y||T))return{matchUp:o,targetLinks:{loserTargetLink:m,winnerTargetLink:u},targetMatchUps:{loserMatchUp:T,winnerMatchUp:y}};let{roundPosition:N}=o;M=M||t.filter(D=>D.structureId===n.structureId);let C=M.reduce((D,O)=>O.roundNumber===o.roundNumber&&!O.matchUpTieId?D+1:D,0);return m&&!T&&f!==Wr&&({matchUpDrawPositionIndex:P,targetDrawPosition:A,matchUp:T}=$I({targetLink:m,sourceRoundMatchUpCount:C,inContextDrawMatchUps:t,sourceRoundPosition:N,drawDefinition:r})),d&&g!==Wr&&({matchUpDrawPositionIndex:S,targetDrawPosition:h,matchUp:I}=$I({targetLink:p,sourceRoundMatchUpCount:C,inContextDrawMatchUps:t,sourceRoundPosition:N,drawDefinition:r})),u&&!y&&l!==Wr&&({matchUpDrawPositionIndex:U,targetDrawPosition:E,matchUp:y}=$I({targetLink:u,sourceRoundMatchUpCount:C,inContextDrawMatchUps:t,sourceRoundPosition:N,drawDefinition:r})),y||(M=M||t.filter(D=>D.structureId===n.structureId),{matchUp:y}=jC({structureMatchUps:M,matchUp:o})),rt({matchUp:o,targetLinks:{loserTargetLink:m,winnerTargetLink:u,byeTargetLink:p},targetMatchUps:{winnerMatchUpDrawPositionIndex:U,loserMatchUpDrawPositionIndex:P,byeMatchUpDrawPositionIndex:S,winnerTargetDrawPosition:E,loserTargetDrawPosition:A,byeTargetDrawPosition:h,winnerMatchUp:y,loserMatchUp:T,byeMatchUp:I},targetMatchUpIds:!!(i||s)})}function fL({matchUp:t}){return{targetLinks:{loserTargetLink:void 0,winnerTargetLink:void 0},targetMatchUps:{loserMatchUp:void 0,winnerMatchUp:void 0},matchUp:t}}function YC({drawDefinition:t,inContextDrawMatchUps:e}){let r={};return e.forEach(n=>{let{matchUpId:o,structureId:i,drawPositions:s=[]}=n,{structure:a}=st({drawDefinition:t,structureId:i});if(a?.finishingPosition===Ms){let{roundNumber:c}=n,u=c&&ct(c)+1,p=a.matchUps??[],{roundMatchUps:m}=Xe({matchUps:p});if(u&&m?.[u]){let d=[...s].sort(oe).map((l,f)=>{let g=m[u].find(I=>I.drawPositions?.includes(l));return{matchUpId:g?.matchUpId,roundNumber:u,schedule:g?.schedule,sideNumber:f+1,structureName:a.structureName}});Object.assign(n,{sidesTo:d})}}else{let c=Je({useTargetMatchUpIds:!0,inContextDrawMatchUps:e,inContextMatchUp:n,drawDefinition:t,matchUpId:o}),{winnerMatchUp:u}=c.targetMatchUps,{loserMatchUp:p}=c.targetMatchUps;!n.winnerMatchUpId&&u&&(n.winnerMatchUpId=u.matchUpId),!n.loserMatchUpId&&p&&(n.loserMatchUpId=p.matchUpId);let m=OE({upcomingMatchUp:u}),d=OE({upcomingMatchUp:p});if(n.matchUpStatus!==Ut&&p?.matchUpStatus===Ut){let{matchUp:f}=qC({matchUp:p,drawDefinition:t,inContextDrawMatchUps:e})||{};d=f&&OE({upcomingMatchUp:f})||d}let l=n.schedule?.timeAfterRecovery;if(l&&(m?.schedule?.scheduledTime&&Gt(m.schedule.scheduledTime)<Gt(l)&&(r[m.matchUpId]=n.matchUpId,m.schedule.scheduleConflict=n.matchUpId),d?.schedule?.scheduledTime&&Gt(d.schedule.scheduledTime)<Gt(l)&&(r[d.matchUpId]=n.matchUpId,d.schedule.scheduleConflict=n.matchUpId)),Object.assign(n,{winnerTo:m,loserTo:d}),n.drawPositions?.filter(Boolean).length){let g=c.targetLinks?.loserTargetLink?.linkCondition===Bn,I=gL(n);if(I.length){let h=Wl(u?.sides),S=Wl(p?.sides),A=I.find(({participantId:E})=>h.includes(E))?[]:I,y=I.find(({participantId:E})=>S.includes(E))?[]:I;p&&g&&y.length<2&&y.push({bye:!0,tbd:!0}),A?.length&&u&&(!c.targetMatchUpIds&&u&&(u=e.find(({matchUpId:E})=>E===u.matchUpId)),u.potentialParticipants||(u.potentialParticipants=[]),u.potentialParticipants.push(A)),y?.length&&p&&(c.targetMatchUpIds||(u=e.find(({matchUpId:E})=>E===p.matchUpId)),p.potentialParticipants||(p.potentialParticipants=[]),p.potentialParticipants.push(y))}}}}),Object.keys(r).length&&e.forEach(n=>{Object.keys(r).includes(n.matchUpId)&&(n.schedule.scheduleConflict=r[n.matchUpId])}),{scheduleConflictMatchUpIds:r}}function gL(t){return t?.sides?.map(({participant:e,participantId:r,qualifier:n})=>e||r&&{participantId:r}||n&&{qualifier:n}).filter(Boolean)||[]}function qC({matchUp:t,drawDefinition:e,inContextDrawMatchUps:r}){let{matchUpId:n,matchUpStatus:o,structureId:i}=t||{};if(!t||!i||t?.matchUpStatus===Kt)return{matchUp:t};if(o===Ut){let s;return t.winnerMatchUpId?s=r.find(({matchUpId:a})=>a===t.winnerMatchUpId):{winnerMatchUp:s}=Je({inContextDrawMatchUps:r,drawDefinition:e,matchUpId:n})?.targetMatchUps||{},qC({matchUp:s,drawDefinition:e,inContextDrawMatchUps:r})}return{matchUp:void 0}}function OE(t){if(t?.upcomingMatchUp)return(({matchUpId:e,structureId:r,schedule:n,roundNumber:o,roundPosition:i,structureName:s})=>({matchUpId:e,structureId:r,schedule:n,roundNumber:o,roundPosition:i,structureName:s}))(t.upcomingMatchUp)}function uf({drawDefinition:t,attributes:e}){let{extension:r}=ut({element:t,name:mm}),n=r?.value||{};return e.forEach(o=>{Object.keys(o).forEach(i=>{n[i]?Object.assign(n[i],o[i]):n[i]=o[i]})}),r={name:mm,value:n},$u({drawDefinition:t,extension:r}),{entryProfile:n}}function Qc({drawDefinition:t}){let{extension:e}=ut({element:t,name:mm});return{entryProfile:e?.value||{}}}var Or="ALTERNATE",pf="CONFIRMED",qr="DIRECT_ACCEPTANCE",Um="FEED_IN",mf="JUNIOR_EXEMPT",Qi="LUCKY_LOSER",df="ORGANISER_ACCEPTANCE",Pm="QUALIFIER",IL="REGISTERED",lf="SPECIAL_EXEMPT",_r="UNGROUPED",oi="UNPAIRED",Xc="WILDCARD",go="WITHDRAWN",ff=[pf,qr,mf,df,lf],_E=[Um,Qi,Pm],Vo=[pf,qr,Um,mf,df,lf,Xc],Mr=[pf,qr,mf,Qi,Pm,df,lf,Xc],vE=[Or,pf,qr,Um,mf,Qi,df,Pm,IL,lf,_r,oi,Xc,go],$C={ALTERNATE:Or,CONFIRMED:pf,DIRECT_ACCEPTANCE:qr,DIRECT_ENTRY_STATUSES:Vo,DRAW_SPECIFIC_STATUSES:_E,EQUIVALENT_ACCEPTANCE_STATUSES:ff,FEED_IN:Um,JUNIOR_EXEMPT:mf,LUCKY_LOSER:Qi,ORGANISER_ACCEPTANCE:df,QUALIFIER:Pm,SPECIAL_EXEMPT:lf,STRUCTURE_SELECTED_STATUSES:Mr,UNGROUPED:_r,UNPAIRED:oi,VALID_ENTRY_STATUSES:vE,WILDCARD:Xc,WITHDRAWN:go};function gf({stage:t,drawDefinition:e}){let{entryProfile:r}=Qc({drawDefinition:e}),n=Object.keys(r).includes(t);if(!n&&gm.includes(t)){let o=[{[t]:{drawSize:void 0,alternates:!0}}];return uf({drawDefinition:e,attributes:o}),!0}return n}function KC({stage:t,drawDefinition:e}){let{entryProfile:r}=Qc({drawDefinition:e});return r[t]?.alternates||0}function zC({stage:t,drawDefinition:e}){let{entryProfile:r}=Qc({drawDefinition:e});return r[t]?.wildcardsCount||0}function KI({stage:t,drawDefinition:e,entryStatus:r}){return e.entries.reduce((n,o)=>o.entryStage===t&&o.entryStatus===r?n+1:n,0)}function ii({provisionalPositioning:t,placementGroup:e,drawDefinition:r,stageSequence:n,entryStatuses:o,structureId:i,roundTarget:s,stages:a,stage:c}){let u=r.entries?.reduce((p,m)=>{let d=ut({name:cn,element:m})?.extension?.value,l=c&&m.entryStage===c||a?.length&&m.entryStage&&a.includes(m.entryStage),f=!o||m.entryStatus&&o.includes(m.entryStatus),g=m.entryStageSequence??1;return l&&(!n||g===n)&&f&&(!s||!d||s===d)?p.concat(m):p},[])??[];if(i&&c===ae){let{playoffEntries:p,error:m}=hL({provisionalPositioning:t,drawDefinition:r,structureId:i});return m&&console.log("playoff entries error"),(p?.length?p:u).filter(d=>!e||d.placementGroup===e)}return u}function hL({provisionalPositioning:t,drawDefinition:e,structureId:r}){let n=[],o=(e.links??[]).find(i=>i.linkType===kn&&i.target.structureId===r);if(o){let{finishingPositions:i,structureId:s}=o.source,{structure:a}=st({drawDefinition:e,structureId:s});a?.structureType===we&&(a.structures??[]).forEach(u=>{let p=u.positionAssignments??[],{structureId:m}=u,d=m,l=Object.assign({},...p.map(h=>{let{participantId:S}=h,T=ut({element:h,name:wo}).extension?.value;return T&&S?{[S]:T}:void 0}).filter(Boolean)),g=Object.keys(l).reduce((h,S)=>{let T=l[S],A=T.groupOrder||t&&T.provisionalOrder;return h.includes(A)||h.push(A),h},[]).length===Object.keys(l).length,I=Object.keys(l).filter(h=>{let S=l[h],T=S.groupOrder||t&&S.provisionalOrder;return i?.includes(T)});(!t||g)&&I.forEach(h=>{let S=l[h],{groupOrder:T,provisionalOrder:A,GEMscore:P}=S,y=T||t&&A,E=[...i??[]].sort(oe).indexOf(y)+1;n.push({entryStage:ae,entryStatus:Um,placementGroup:E,groupingValue:d,participantId:h,GEMscore:P})})})}return{playoffEntries:n}}function QC({stage:t,drawDefinition:e}){return Vo.reduce((r,n)=>(KI({drawDefinition:e,entryStatus:n,stage:t})||0)+r,0)}function vr({provisionalPositioning:t,returnAllProxies:e,drawDefinition:r,structureId:n,structure:o}){let i,s=[];o||({structure:o,error:i}=st({drawDefinition:r,structureId:n}));let a=Dt({structure:o}).positionAssignments;if(i||!o)return{seedAssignments:[],error:_t};n||(n=o.structureId);let{stage:c,stageSequence:u}=o,m=c===ae&&r&&ii({provisionalPositioning:t,drawDefinition:r,stageSequence:u,structureId:n,stage:c}),d=m?m.filter(g=>g.placementGroup===1).sort((g,I)=>g.GEMscore<I.GEMscore&&1||g.GEMscore>I.GEMscore&&-1||0).map((g,I)=>{let h=I+1;return{participantId:g.participantId,seedValue:h,seedProxy:!0,seedNumber:h}}):[],l=d?.slice(0,e?d.length:a.length/2);l.length?s=l:o.seedAssignments?s=o.seedAssignments:i=jA;let f=o.seedLimit??o?.positionAssignments?.length;return{seedAssignments:s,stageSequence:u,seedLimit:f,stage:c,error:i}}var zI="WALKOVER",xE="RETIRED",Nm="COMPETITIVE",Za="ROUTINE",tc="DECISIVE",Dm="winRatio";var SL=(t,e)=>(t||0)+(e||0);function QI(t,e){let r=Array.isArray(t)?t[0]:t;return isNaN(r)&&zI||r<=e[tc]&&tc||r<=e[Za]&&Za||Nm}function XI({score:t}){let e=t?.sets||[],r=e.reduce((o,i)=>(o[0]+=i.side1Score||0,o[1]+=i.side2Score||0,o),[0,0]),n=e.reduce((o,i)=>(o[0]+=i.side1TiebreakScore||0,o[1]+=i.side2TiebreakScore||0,o),[0,0]);return n.reduce(SL)&&(r[n[0]>n[1]?0:1]+=1),{sets:e,games:r,score:t}}function TL(t){let e=Math.min(...t.games),r=Math.max(...t.games);return Math.round(e/r*100)}function JI(t){return t.map(TL).sort().map(e=>parseFloat(e.toFixed(2)))}function yt({onlySpecifiedPolicyTypes:t=!1,policyTypes:e=[],tournamentRecord:r,drawDefinition:n,structure:o,event:i}){if(!Array.isArray(e))return{error:Jg};let s={};return r&&a(r),i&&a(i),n&&a(n),o&&a(o),{appliedPolicies:s,...R};function a(c){let p=c?.extensions?.find(m=>m.name===Fc)?.value;if(p)for(let m of Object.keys(p))(t?e.includes(m):!e.length||e.includes(m))&&(s[m]=J(p[m],!1,!0))}}function Io({policyTypes:t=[],tournamentRecord:e,drawDefinition:r,structure:n,event:o}){if(!Array.isArray(t))return{error:Jg};let{appliedPolicies:i}=yt({tournamentRecord:e,drawDefinition:r,structure:n,event:o}),s={};for(let a of t){let c=i?.[a];c&&(s[a]=c)}return Object.keys(s).length?{policyDefinitions:s}:{info:Mc.message}}function Bo({tournamentRecord:t,drawDefinition:e,policyType:r,structure:n,event:o}){if(!t)return{error:j};let{appliedPolicies:i}=yt({tournamentRecord:t,drawDefinition:e,structure:n,event:o});return i?.[r]?{policy:i[r]}:{info:Mc?.message}}var AL={[ti]:{policyName:"Competitive Bands Default",profileBands:{[tc]:20,[Za]:50}}},Mm=AL;function Jc({tournamentRecord:t,profileBands:e,matchUp:r}){if(!r)return{error:or};let{score:n,winningSide:o}=r;if(!o)return{error:G};let i=!e&&t&&Bo({policyType:ti,tournamentRecord:t}).policy,s=e||i?.profileBands||Mm[ti].profileBands,a=XI({score:n}),c=JI([a]),u=QI(c,s),p=Array.isArray(c)?c[0]:c;return{...R,competitiveness:u,pctSpread:p}}function ZI({matchUp:t}){if(!t)return{error:or};if(t&&!t.sides)return{error:ze};if(t&&!t.hasContext)return{error:Rc};let e=(t.sides??[])?.map(a=>a?.participantId).filter(Boolean),r=t.sides?.filter(a=>a.participant?.participantType===It).map(a=>a.participantId).filter(Boolean)??[],o=((t.sides??[])?.map(a=>a.participant?.individualParticipants).filter(Boolean)??[]).map(a=>(a??[]).map(c=>c?.participantId).filter(Boolean)),i=[...r,...o.flat()].filter(Boolean)??[],s=mt(i.concat(e)).filter(Boolean)??[];return{nestedIndividualParticipantIds:o,allRelevantParticipantIds:s,individualParticipantIds:i,sideParticipantIds:e,...R}}var Cm="CHECK_IN",Rm="CHECK_OUT",XC="SCHEDULE",bs="SCHEDULE.ASSIGNMENT.VENUE",ho="SCHEDULE.ALLOCATION.COURTS",si="SCHEDULE.ASSIGNMENT.COURT",If="SCHEDULE.COURT.ORDER",Os="SCHEDULE.DATE",yL="COMPLETED.DATE",wE="SCHEDULE.ASSIGN.OFFICIAL",_s="SCHEDULE.TIME.SCHEDULED",So="SCHEDULE.TIME.START",bi="SCHEDULE.TIME.STOP",ai="SCHEDULE.TIME.RESUME",ci="SCHEDULE.TIME.END",hf="SCHEDULE.TIME.MODIFIERS",JC="TO_BE_ANNOUNCED",ZC="NEXT_AVAILABLE",tR="FOLLOWED_BY",eR="AFTER_REST",rR="RAIN_DELAY",EL="NOT_BEFORE",th=[JC,ZC,tR,eR,rR],UL="ELIGIBILITY",PL="REGISTRATION",NL="SUSPENSION",DL="MEDICAL",ML="PENALTY",LE="SCALE",FE="RATING",GE="RANKING",Sf="SEEDING",Ho="PUBLISH",$r="PUBLIC",Wo="STATUS",CL="MODIFICATION",RL="RETRIEVAL",bL="other",nR={MUTUALLY_EXCLUSIVE_TIME_MODIFIERS:th,AFTER_REST:eR,ALLOCATE_COURTS:ho,ASSIGN_COURT:si,ASSIGN_OFFICIAL:wE,ASSIGN_VENUE:bs,CHECK_IN:Cm,CHECK_OUT:Rm,COMPLETED_DATE:yL,COURT_ORDER:If,ELIGIBILITY:UL,END_TIME:ci,FOLLOWED_BY:tR,MEDICAL:DL,MODIFICATION:CL,NEXT_AVAILABLE:ZC,NOT_BEFORE:EL,OTHER:bL,PENALTY:ML,PUBLIC:$r,PUBLISH:Ho,RANKING:GE,RATING:FE,RAIN_DELAY:rR,REGISTRATION:PL,RESUME_TIME:ai,RETRIEVAL:RL,SCALE:LE,SCHEDULE:XC,SCHEDULED_DATE:Os,SCHEDULED_TIME:_s,SEEDING:Sf,START_TIME:So,STATUS:Wo,STOP_TIME:bi,SUSPENSION:NL,TIME_MODIFIERS:hf,TO_BE_ANNOUNCED:JC};function Xi({matchUp:t}){if(!t)return{error:or};if(!t.hasContext)return{error:Rc};if(!t.sides||t.sides.filter(Boolean).length!==2)return{error:ze};let{nestedIndividualParticipantIds:e,allRelevantParticipantIds:r,sideParticipantIds:n}=ZI({matchUp:t}),i=(t.timeItems??[]).filter(u=>u?.itemType&&[Cm,Rm].includes(u.itemType)).sort((u,p)=>(u.createdAt?new Date(u.createdAt).getTime():0)-(p.createdAt?new Date(p.createdAt).getTime():0)),a=i.map(u=>u.itemValue).filter(u=>i.filter(p=>p?.itemValue===u).reverse()[0].itemType===Cm);e?.forEach((u,p)=>{let m=n?.[p],d=u?.length&&u.every(l=>a.includes(l));m&&d&&!a.includes(m)&&a.push(m)}),n?.forEach((u,p)=>{a.includes(u)&&(e?.[p]??[]).forEach(m=>{m&&!a.includes(m)&&a.push(m)})});let c=n?.reduce((u,p)=>a.includes(p)&&u,!0);return{allRelevantParticipantIds:r,allParticipantsCheckedIn:c,checkedInParticipantIds:a,...R}}function np(t){let{matchUpAverageTimes:e,matchUpFormat:r}=t||{},n=e?.map(({matchUpFormatCodes:a})=>a?.filter(c=>c===r)).flat().filter(Boolean).sort((a,c)=>(a?.length||0)-(c?.length||0))||[],i=n.includes(r)?r:n[0];return e?.find(({matchUpFormatCodes:a,averageTimes:c})=>a?.find(u=>i===u)&&c)?.averageTimes}function op(t){let{matchUpRecoveryTimes:e,averageMinutes:r,matchUpFormat:n}=t||{};return e?.find(({matchUpFormatCodes:o,averageTimes:i,recoveryTimes:s})=>{if(i&&r){let{greaterThan:a=0,lessThan:c=360}=i;if(r>a&&r<c)return!0}return o?.find(a=>a===n)&&s})?.recoveryTimes}function eh({timesBlockArray:t,categoryName:e,categoryType:r}){return t.filter(n=>Array.isArray(n)).map(n=>n.sort((o,i)=>(i.categoryNames?.length||0)-(o.categoryNames?.length||0)).find(({categoryTypes:o,categoryNames:i})=>!i?.length&&!o?.length||i?.includes(e)||o?.includes(r))).find(Boolean)}function oR({tournamentScheduling:t,eventScheduling:e,averageMinutes:r,defaultTiming:n,matchUpFormat:o,categoryName:i,categoryType:s,policy:a}){let c=e?.matchUpRecoveryTimes&&op({...e,averageMinutes:r,matchUpFormat:o}),u=t?.matchUpRecoveryTimes&&op({...t,averageMinutes:r,matchUpFormat:o}),p=a?.matchUpRecoveryTimes&&op({...a,averageMinutes:r,matchUpFormat:o}),m=[c,u,p,a?.defaultTimes?.recoveryTimes,n?.recoveryTimes];return eh({categoryName:i,categoryType:s,timesBlockArray:m})}function iR({matchUpFormat:t,categoryName:e,categoryType:r,defaultTiming:n,tournamentScheduling:o,eventScheduling:i,policy:s}){let a=i?.matchUpAverageTimes&&np({...i,matchUpFormat:t}),c=o?.matchUpAverageTimes&&np({...o,matchUpFormat:t}),u=s?.matchUpAverageTimes&&np({...s,matchUpFormat:t}),p=[a,c,u,s?.defaultTimes?.averageTimes,n?.averageTimes];return eh({categoryName:e,categoryType:r,timesBlockArray:p})}function la({tournamentRecord:t,categoryName:e,categoryType:r,event:n}){e=e??n?.category?.categoryName??n?.category?.ageCategoryCode,r=r??n?.category?.categoryType??n?.category?.subType;let{policy:o}=Bo({policyType:uo,tournamentRecord:t,event:n}),s=(t?ut({element:t,name:Po}).extension:void 0)?.value,c=(n&&ut({name:Po,element:n}).extension)?.value;return{scheduleTiming:{tournamentScheduling:s,eventScheduling:c,categoryName:e,categoryType:r,policy:o}}}var kE="DOUBLES_SINGLES",VE="SINGLES_DOUBLES",Hn="total",rh="participantConflict",fa="matchUpConflict",BE="ISSUE_IDS",ec="CONFLICT",rc="WARNING",nh="ERROR",oh="ISSUE",Tf="STATE",sR={SINGLES_DOUBLES:VE,DOUBLES_SINGLES:kE,TOTAL:Hn,CONFLICT_MATCHUP_ORDER:fa,CONFLICT_PARTICIPANTS:rh,SCHEDULE_ISSUE_IDS:BE,SCHEDULE_CONFLICT:ec,SCHEDULE_WARNING:rc,SCHEDULE_ERROR:nh,SCHEDULE_ISSUE:oh,SCHEDULE_STATE:Tf};var eo="SINGLES",vs="SINGLES",Vr="DOUBLES",ui="DOUBLES",Le="TEAM",Kr="TEAM",OL="AGE",_L="RATING",vL="BOTH",aR={AGE:OL,BOTH:vL,DOUBLES:Vr,DOUBLES_EVENT:ui,RATING:_L,SINGLES:eo,SINGLES_EVENT:vs,TEAM_EVENT:Kr,TEAM:Le};function Zc({defaultAverageMinutes:t=90,defaultRecoveryMinutes:e=0,tournamentRecord:r,matchUpFormat:n,categoryName:o,categoryType:i,eventType:s,event:a}){if(!r)return{error:j};s=s??a?.eventType??vs;let c={averageTimes:[{minutes:{default:t}}],recoveryTimes:[{minutes:{default:e}}]},{scheduleTiming:u}=la({tournamentRecord:r,categoryName:o,categoryType:i,event:a}),p={...u,matchUpFormat:n,categoryType:i,defaultTiming:c};return ip({eventType:s,timingDetails:p})}function ip({timingDetails:t,eventType:e}){let r=iR(t),n=Object.keys(r?.minutes||{}),o=r?.minutes&&(n?.includes(e)&&r.minutes[e]||r.minutes.default),i=oR({...t,averageMinutes:o}),s=Object.keys(i?.minutes||{}),a=i?.minutes&&(s?.includes(e)&&i.minutes[e]||i.minutes.default),c=e===vs?VE:kE,u=i?.minutes&&(s?.includes(c)&&i.minutes[c]||a);return{averageMinutes:o,recoveryMinutes:a,typeChangeRecoveryMinutes:u}}function ih(t){return t.createdAt?new Date(t.createdAt).getTime():0}function Do({visibilityThreshold:t,timeItems:e,itemType:r}){let n=e.filter(i=>i&&i.itemType===r&&(!t||ih(i)<new Date(t).getTime())).sort((i,s)=>ih(i)-ih(s)).pop(),o=n&&ih(n);return{itemValue:n?.itemValue,timeStamp:o}}function Af({visibilityThreshold:t,timeStamp:e,schedule:r,matchUp:n}){let{itemValue:o,timeStamp:i}=Do({timeItems:n?.timeItems||[],itemType:_s,visibilityThreshold:t});return!r||i&&e&&new Date(i).getTime()>new Date(e).getTime()?{scheduledTime:o}:r}function Ji({visibilityThreshold:t,timeStamp:e,schedule:r,matchUp:n}){let{itemValue:o,timeStamp:i}=Do({timeItems:n?.timeItems||[],itemType:Os,visibilityThreshold:t});return!r||i&&e&&new Date(i).getTime()>new Date(e).getTime()?{scheduledDate:o}:r}function sh({visibilityThreshold:t,timeStamp:e,schedule:r,matchUp:n}){let{itemValue:o,timeStamp:i}=Do({timeItems:n?.timeItems||[],itemType:ho,visibilityThreshold:t});return!r||i&&e&&new Date(i).getTime()>new Date(e).getTime()?{allocatedCourts:J(o,!1,!0)}:r}function ah({visibilityThreshold:t,timeStamp:e,schedule:r,matchUp:n}){let{itemValue:o,timeStamp:i}=Do({timeItems:n?.timeItems||[],itemType:si,visibilityThreshold:t});return!r||i&&e&&new Date(i).getTime()>new Date(e).getTime()?{courtId:o}:r}function ch({visibilityThreshold:t,timeStamp:e,schedule:r,matchUp:n}){let{itemValue:o,timeStamp:i}=Do({timeItems:n?.timeItems||[],itemType:bs,visibilityThreshold:t});return!r||i&&e&&new Date(i).getTime()>new Date(e).getTime()?{venueId:o}:r}function cR(t=1){return Z(0,t).map(Mt)}function Mt(){let t=[];for(let i=0;i<256;i++)t[i]=(i<16?"0":"")+i.toString(16);let e=Math.random()*4294967295|0,r=Math.random()*4294967295|0,n=Math.random()*4294967295|0,o=Math.random()*4294967295|0;return t[e&255]+t[e>>8&255]+t[e>>16&255]+t[e>>24&255]+"-"+t[r&255]+t[r>>8&255]+"-"+t[r>>16&15|64]+t[r>>24&255]+"-"+t[n&63|128]+t[n>>8&255]+"-"+t[n>>16&255]+t[n>>24&255]+t[o&255]+t[o>>8&255]+t[o>>16&255]+t[o>>24&255]}function nc(t){let{disableNotice:e,venue:r,context:n}=t;if(typeof r!="object")return{error:G};let o=jr(t);r.venueId||(r.venueId=Mt());let i;for(let s of Object.values(o)){let a=xL({disableNotice:!0,tournamentRecord:s,context:n,venue:r});if(a?.error)return a;i=a.venue}return e||Tt({topic:HI,payload:{venue:r}}),rt({...R,venue:i})}function xL({tournamentRecord:t,disableNotice:e,context:r,venue:n}){return t?n?(t.venues||(t.venues=[]),n.venueId||(n.venueId=Mt()),t.venues.reduce((i,s)=>i||s.venueId===n.venueId,void 0)?{error:Ey}:(r&&gt({element:n,extension:{value:r,name:nE}}),t.venues.push(n),e||Tt({payload:{venue:n,tournamentId:t.tournamentId},topic:HI}),{...R,venue:J(n)})):{error:et,info:"missing venue"}:{error:j}}function jo({tournamentRecords:t,tournamentRecord:e,venueId:r}){if(!e)return{error:j};if(!r)return{error:vo};let o=(e.venues??[]).reduce((i,s)=>s.venueId===r?s:i,void 0);if(!o&&t){let s=(kc({tournamentRecords:t}).linkedTournamentIds??[])[e.tournamentId];for(let a of s){let c=t[a],u=jo({tournamentRecord:c,venueId:r});if(u.success&&u.venue)return nc({tournamentRecord:e,venue:u.venue}),{...R,venue:o}}}return o?{...R,venue:o}:{error:Es}}function uh({convertExtensions:t,...e}){let{tournamentRecords:r,tournamentRecord:n,venueId:o}=e,i=jo({tournamentRecords:r,tournamentRecord:n,venueId:o});return J(i,t,!0)}function Zi({tournamentRecords:t,tournamentRecord:e,courtId:r}){if(!e)return{error:j};if(!r)return{error:Ti};let n="findCourt",o,i;if((e.venues??[]).forEach(s=>{(s.courts??[]).forEach(a=>{a.courtId===r&&(o=a,i=s)})}),o)return{...R,court:o,venue:i};if(t){let a=(kc({tournamentRecords:t}).linkedTournamentIds??[])[e.tournamentId];for(let c of a){let u=t[c],p=Zi({tournamentRecord:u,courtId:r});if(p.success)return p.venue&&nc({tournamentRecord:e,venue:p.venue}),{...R,court:o,venue:i}}}return v({result:{error:Ha},stack:n})}function HE(t){return J(Zi(t),!1,!0)}function yf({tournamentRecord:t,internalUse:e,courtId:r}){if(!t)return{error:j};if(!r)return{error:Ti};let n=Zi({tournamentRecord:t,courtId:r});if(n.error)return n;let o=n.court&&(({altitude:i,courtId:s,courtName:a,courtDimensions:c,latitude:u,longitude:p,surfaceCategory:m,surfaceType:d,surfacedDate:l,pace:f,notes:g})=>({altitude:i,courtId:s,courtName:a,courtDimensions:c,latitude:u,longitude:p,surfaceCategory:m,surfaceType:d,surfacedDate:l,pace:f,notes:g}))(n.court);return{...R,courtInfo:J(o,!1,e)}}function tu({tournamentRecord:t,venueId:e}){if(!t)return{error:j};if(!e)return{error:vo};let r=jo({tournamentRecord:t,venueId:e});if(r.error)return r;let o=(r.venue?.courts??[]).map(a=>(({courtInfo:c})=>({...c}))(yf({courtId:a.courtId,internalUse:!0,tournamentRecord:t}))),i=r.venue&&(({venueId:a,venueName:c,venueAbbreviation:u})=>({venueAbbreviation:u,venueName:c,venueId:a}))(r.venue),s=i&&{...i,courtsInfo:o};return{...R,venueData:J(s,!1,!0)}}function Ef({visibilityThreshold:t,timeStamp:e,schedule:r,matchUp:n}){let{itemValue:o,timeStamp:i}=Do({timeItems:n?.timeItems||[],itemType:hf,visibilityThreshold:t});return!r||i&&e&&new Date(i).getTime()>new Date(e).getTime()?{timeModifiers:o}:r}function sp(t){if(fI.test(t)){let e=_l();return new Date(`${e}T${t}`)}else return new Date(t)}function uR({matchUp:t}){if(!t)return{error:or};if(!t.timeItems)return{error:hl};let e=t.timeItems.filter(n=>[So,bi,ai,ci].includes(n?.itemType)).sort((n,o)=>sp(n.itemValue).getTime()-sp(o.itemValue).getTime()),r=e.reduce((n,o)=>{let i,s=o?.itemType?.split("."),c=`SCHEDULE.TIME.${o?.itemType?.startsWith("SCHEDULE.TIME")&&s[2]}`;switch(c){case So:i=0;break;case ci:if(n.lastValue&&[So,ai].includes(n.lastType)){let u=sp(o.itemValue).getTime()-sp(n.lastValue).getTime();i=n.milliseconds+u}else i=n.milliseconds;break;case bi:if([So,"SCHECULE.TIME.RESUME"].includes(n.lastType)){let u=sp(o.itemValue).getTime()-sp(n.lastValue).getTime();i=n.milliseconds+u}else i=n.milliseconds;break;default:i=n.milliseconds;break}return{milliseconds:i,lastType:c,lastValue:o.itemValue}},{milliseconds:0,lastType:void 0,lastValue:void 0});if([So,ai].includes(r.lastType)){let n=new Date().getTime()-sp(r.lastValue).getTime();r.milliseconds+=n}return{milliseconds:r.milliseconds,time:wL(r.milliseconds),relevantTimeItems:e}}function wL(t){let e=(r,n=2)=>("00"+r).slice(-n);return e(t/36e5|0)+":"+e(t%36e5/6e4|0)+":"+e(t%6e4/1e3|0)}function kt({event:t,eventId:e}){if(!t)return{error:St};let n=ut({name:Gr,element:t})?.extension,o=e?J(n?.value,!1,!0):n?.value;return e&&t.drawDefinitions?.forEach(i=>{o?.flights?.forEach(s=>{s.drawId===i.drawId&&Object.assign(s,{drawDefinition:i})})}),{flightProfile:o}}function nr(t){let{tournamentRecord:e,eventId:r,drawId:n}=t,o="findEvent",i={},s=t.tournamentRecords??(e&&{[e.tournamentId]:e})??{},a=Object.values(s).map(({events:u,tournamentId:p})=>(u&&u.forEach(m=>{i[m.eventId]={tournamentId:p}}),u??[])).flat(),c;if(n){let u,p=a.find(m=>{let l=(m?.drawDefinitions??[]).find(f=>f.drawId===n);if(l)u=l,c=i[m.eventId].tournamentId;else{let g=(m&&kt({event:m})?.flightProfile)?.flights?.find(I=>I.drawId===n);if(g)return c=i[m.eventId].tournamentId,{entries:g.drawEntries,drawName:g.drawName,tournamentId:c,drawId:n}}return l});if(p)return{event:p,drawDefinition:u,tournamentId:c}}if(r){let u=a.find(p=>p?.eventId===r);if(u)c=i[u.eventId].tournamentId;else return{event:void 0,drawDefinition:void 0,...v({result:{error:Ir},stack:o})};return{event:u,drawDefinition:void 0,tournamentId:c}}return{event:void 0,drawDefinition:void 0,...v({result:{error:fr},context:{drawId:n,eventId:r},stack:o})}}function pR({visibilityThreshold:t,timeStamp:e,schedule:r,matchUp:n}){let{itemValue:o,timeStamp:i}=Do({timeItems:n?.timeItems||[],itemType:If,visibilityThreshold:t});return!r||i&&e&&new Date(i).getTime()>new Date(e).getTime()?{courtOrder:o}:r}function mR({matchUp:t}){let e=t?.timeItems||[],r=i=>i.createdAt?new Date(i.createdAt).getTime():0;return{startTime:e.reduce((i,s)=>{let a=s.itemType===So&&s;return a&&(!i||r(a)<r(i))?a:i},void 0)?.itemValue}}function dR({matchUp:t}){let e=t?.timeItems||[],r=i=>i.createdAt?new Date(i.createdAt).getTime():0;return{endTime:e.reduce((i,s)=>{let a=s.itemType===ci&&s;return a&&(!i||r(a)>r(i))?a:i},void 0)?.itemValue}}function bm(t){let e=t.event,r=t.matchUpType,{scheduleVisibilityFilters:n,afterRecoveryTimes:o,tournamentRecord:i,usePublishState:s,scheduleTiming:a,matchUpFormat:c,publishStatus:u,matchUp:p}=t;if(!p)return{error:or};if(o&&!p.matchUpType&&!t.matchUpType&&(e||i)&&p.drawId){let E=e?.drawDefinitions?.find(M=>M.drawId===p.drawId);!E&&i&&({drawDefinition:E,event:e}=nr({tournamentRecord:i,drawId:p.drawId}));let U=p.structureId&&E?.structures?.find(({structureId:M})=>M===p.structureId);r=t.matchUpType||U?.matchUpType||E?.matchUpType||e?.eventType!==Le&&e?.eventType}let{milliseconds:m,time:d}=uR({matchUp:p}),{startTime:l}=mR({matchUp:p}),{endTime:f}=dR({matchUp:p}),g,{visibilityThreshold:I,eventIds:h,drawIds:S}=n??{};if((!h||h.includes(p.eventId))&&(!S||S.includes(p.drawId))){let E={matchUp:p,visibilityThreshold:I},{allocatedCourts:U}=sh(E),{scheduledTime:M}=Af(E),{scheduledDate:N}=Ji(E),{venueId:C}=ch(E),{courtId:D}=ah(E),{courtOrder:O}=pR(E),{timeModifiers:b}=Ef(E),_,L,F,w,x,H=p.matchUpType??r;if(a&&M&&o&&H){let $={matchUpFormat:p.matchUpFormat??c,...a};({averageMinutes:L=0,recoveryMinutes:F=0,typeChangeRecoveryMinutes:w=0}=ip({timingDetails:$,eventType:H})),(L||F)&&(_=f?Nr(qt(f),F):Nr(M,L+F)),w&&(x=f?Nr(qt(f),w):Nr(M,L+w))}!N&&M&&(N=At(M));let V=om({scheduledDate:N,scheduledTime:M}),W={},B=(i&&C&&tu({tournamentRecord:i,venueId:C}))?.venueData||{};C&&(W[C]=B);let{venueName:q,venueAbbreviation:Y,courtsInfo:k}=B,X=(D&&k?.find($=>$.courtId===D))?.courtName;for(let $ of U||[]){if(!i)break;$.venueId&&!W[$.venueid]&&(W[$.venueId]=tu({venueId:$.venueId,tournamentRecord:i})?.venueData);let nt=W[$.venueId];$.venueName=nt?.venueName;let Q=nt?.courtsInfo?.find(it=>it.courtId===$.courtId);$.courtName=Q?.courtName}g=rt({typeChangeTimeAfterRecovery:x,timeAfterRecovery:_,scheduledDate:N,scheduledTime:M,isoDateString:V,allocatedCourts:U,timeModifiers:b,venueAbbreviation:Y,venueName:q,venueId:C,courtOrder:O,courtName:X,courtId:D,typeChangeRecoveryMinutes:w,recoveryMinutes:F,averageMinutes:L,milliseconds:m,startTime:l,endTime:f,time:d})}else g=rt({milliseconds:m,startTime:l,endTime:f,time:d});let{scheduledDate:T}=Ji({matchUp:p}),{scheduledTime:A}=Af({matchUp:p});if(s&&u?.displaySettings?.draws){let E=u.displaySettings.draws,U=(E?.[p.drawId]??E?.default)?.scheduleDetails;if(U){let M=(U.find(N=>T&&N.dates?.includes(T))??U.find(N=>!N.dates?.length))?.attributes;if(M){let N=Object.assign({},...Object.keys(g).map(C=>({[C]:!0})),M);g=Di({source:g,template:N})}}}let y=p.matchUpStatus&&ie.includes(p.matchUpStatus)&&(At(f)||At(T)||At(A))||void 0;return{schedule:g,endDate:y}}function xs(t){if(!t)return;let{tieFormatId:e,tieFormats:r}=t;if(t.tieFormat)return t.tieFormat;if(e&&Array.isArray(r))return r.find(n=>n.tieFormatId===e)}function ap({item:t,drawDefinition:e,structure:r,event:n}){if(t){if(t.tieFormat)return t.tieFormat;if(t.tieFormatId){if(e.tieFormat)return e.tieFormat;let o=e.tieFormats?.find(i=>t.tieFormatId===i.tieFormatId);return o||(n.tieFormat?n.tieFormat:n.tieFormats?.find(i=>t.tieFormatId===i.tieFormatId))}if(r.tieFormat)return r.tieFormat;if(r.tieFormatId){let o=e.tieFormats?.find(i=>r.tieFormatId===i.tieFormatId);if(o)return o}}}function Ve({drawDefinition:t,structure:e,matchUp:r,event:n}){return{tieFormat:ap({item:r,drawDefinition:t,structure:e,event:n})||ap({item:e,drawDefinition:t,structure:e,event:n})||xs(t)||xs(n)}}function lR({matchUps:t}){let e=t.reduce((n,o)=>!o.collectionPosition||n.includes(o.collectionPosition)?n:n.concat(o.collectionPosition),[]).map(n=>({[n]:t.filter(o=>o.collectionPosition===n)}));return{collectionPositionMatchUps:Object.assign({},...e)}}function Om(t){if(!Array.isArray(t))return"";let e=t.filter(se);return e.length?mt([Math.min(...e),Math.max(...e)]).join("-"):""}function fR({drawDefinition:t,structureId:e,matchUpsMap:r}){if(!t)return{error:z};if(!e)return{error:We};let{structure:n}=st({drawDefinition:t,structureId:e});if(n?.stage!==Ge)return{error:Si,info:"Structure is not CONSOLATION stage"};let{links:o}=t,i=o?.filter(m=>m.target.structureId===e)||[],s=i?.reduce((m,d)=>{let{structureId:l}=d.source;return m.includes(l)?m:m.concat(l)},[])||[],a=Object.assign({},...s.map(m=>{let d=ko({structureId:m,matchUpsMap:r}),f=Xe({matchUps:d}).roundProfile;return{[m]:f}})),c=ko({matchUpsMap:r,structureId:e}),{roundProfile:u}=Xe({matchUps:c}),p={};return i?.forEach(m=>{let{structureId:d,roundNumber:l}=m.source,{feedProfile:f,groupedOrder:g,positionInterleave:I,roundNumber:h}=m.target,S=a[d],T=S[1]?.drawPositions,P=S[l]?.matchUpsCount;if(!P)return;let y=P?T.length/P:0,E=T.length/y,U=T.slice(),M=qI({roundPositionsCount:U.length,groupedOrder:g}),N=M?.length||1;if(N<=E){let b=T.length/N,_=Ae(U,b);f===Fo&&_.forEach(L=>L.reverse()),U=M?.length&&M?.map(L=>_[L-1]).flat()||U}let C=Ae(U,y);if(!M?.length&&f===Fo&&C.reverse(),I){let b=Z(0,I.interleave).map(()=>{}),_=Z(0,I.offset).map(()=>{});C=C.map(F=>[F,...b]),C.unshift(_),C=C.flat(1);let L=C.length-I.offset;C=C.slice(0,L)}p[h]||(p[h]={});let O=u?.[h]?.feedRound?2:1;C.forEach((b,_)=>{let L=1+_*O;p[h][L]||(p[h][L]=Om(b))})}),{sourceDrawPositionRanges:p}}function bn({policyDefinitions:t,tournamentRecord:e,contextProfile:r,drawDefinition:n,event:o}){let i={policies:{}};if(!r)return i;let s=Io({tournamentRecord:e,drawDefinition:n,event:o}).policyDefinitions;if(r.withCompetitiveness){let a=t?.[ti]??s?.[ti]??Mm[ti];i.policies[ti]=a}return i}var LL="normal",WE="timed",FL="final",Uf="NOAD",_m="SET",gR={S:LL,F:FL};function Ze(t){if(typeof t=="string"){let e=t.startsWith("T")&&WE||t.startsWith(_m)&&_m||"";if(e===WE){let r=TR(t),n={simplified:!0,setFormat:r,bestOf:1};if(r)return n}if(e===_m)return GL(t)}}function GL(t){let e=t.split("-"),r=Pf(e[0].slice(3)),n=r===1||r%2!==0?r:void 0,o=r!==1&&r%2===0?r:void 0,i=e&&IR(e[1]),s=e&&IR(e[2]),a=i&&i.timed||s&&s.timed,c=n&&n<6||a&&o,u=!e[2]||s,p=i,m=rt({setFormat:i,exactly:o,bestOf:n});if(s&&(m.finalSetFormat=s),c&&p&&u)return m}function IR(t){if(t?.[1]===":"){let e=t.split(":"),r=gR[e[0]],n=e[1];if(r&&n){if(n.startsWith("TB")){let I=hR(n);return I===!1?!1:typeof I=="object"?{tiebreakSet:I}:void 0}if(n.startsWith("T"))return TR(n);let s=t.match(/^[FS]:(\d+)([A-Za-z]*)/),a=s&&AR(s[2])||!1,c=!s?.[2]||a,u=s?Pf(s[1]):void 0,p=SR(n),m=p!==!1,d=m&&p||u,l=hR(n.split("/")[1]),f=l!==!1,g={setTo:u};return a&&(g.NoAD=!0),l?(g.tiebreakFormat=l,g.tiebreakAt=d):g.noTiebreak=!0,u&&c&&f&&m&&g||!1}}}function SR(t,e=!0){let r=t?.indexOf("@")>0&&t.split("@");if(r)return(e?Pf(r[1]):r[1])||!1}function hR(t){if(t)if(t.startsWith("TB")){let e=SR(t,!1),r=t.match(/^TB(\d+)([A-Za-z]*)/),n=r?.[1],o=r&&AR(r[2]),i=!r?.[2]||o,s=Pf(n);if(s&&i){let a={tiebreakTo:s};return e&&typeof e=="string"&&!lt(e)&&(a.modifier=e),o&&(a.NoAD=!0),a}else return!1}else return!1}function TR(t){let e=t.slice(1),r=e.match(/^(\d+)(@?[A-Za-z]*)/),n=Pf(r?.[1]);if(!n)return;let o={timed:!0,minutes:n},i=r?.[2],s=[void 0,"P","G"].includes(i);if(i&&!s){let a=e.match(/^(\d+)(@)([A-Za-z]+)$/)?.[3];return a?(o.modifier=a,o):void 0}return i&&(o.based=r[2]),o}function AR(t){return t&&t.indexOf(Uf)>=0}function Pf(t){return isNaN(Number(t))?0:Number(t)}function yR({drawPositions:t,roundProfile:e,roundNumber:r}){let n=[void 0,void 0];if(pI(t))return{orderedDrawPositions:n,displayOrder:n};let o=e?.[r],s=o?.pairedDrawPositions?.find(c=>ve(c||[],t.filter(Boolean)))??n,a=o?.feedRound;if(uI(t)){let c=[...t].sort(oe);return{orderedDrawPositions:c.length===2?c:s,displayOrder:a?c:s}}if(a){let u=[t.find(p=>!isNaN(ct(p))),void 0];return{orderedDrawPositions:u,displayOrder:u}}return{orderedDrawPositions:s,displayOrder:s}}function cp({collectionPosition:t,collectionId:e,lineUp:r}){let n=[],o=[];if(r){let i=a=>a===void 0?-1:a,s=r.map(a=>{let{collectionAssignments:c,participantId:u}=a,p=c?.find(m=>m.collectionPosition===t&&m.collectionId===e);return p&&{participantId:u,...p}}).filter(Boolean).sort((a,c)=>i(a.substitutionOrder)-i(c.substitutionOrder));for(let a of s){let{participantId:c,previousParticipantId:u,substitutionOrder:p}=a;n.includes(c)||(u&&o.push({previousParticipantId:u,substitutionOrder:p,participantId:c}),n=n.filter(m=>m!==u),n.push(c))}}return{assignedParticipantIds:n,substitutions:o}}function zr({tournamentParticipants:t,tournamentRecord:e,participantIds:r}){let n="getPairedParticipant";if(!t&&!e)return{error:j};if(!Array.isArray(r)||r.length>2)return{error:Hr};if(!r.length)return v({result:{error:so},stack:n});t=t??e?.participants??[];let o=t.filter(a=>a.participantType===pt&&Wt(r,a.individualParticipantIds).length===r.length&&a.individualParticipantIds.length===r.length),i=o[0];if(!i)return v({result:{error:Jt},stack:n});let s=J(o.slice(1),!1,!0);return{participant:J(i),duplicatedPairParticipants:s,...R}}function ts({drawDefinition:t,participantId:e}){if(typeof t!="object")return{error:z};if(typeof e!="string")return{error:te};let{extension:r}=ut({element:t,name:mo});return{lineUp:(r?.value||{})[e]}}function ER({tournamentParticipants:t,positionAssignments:e,collectionPosition:r,drawPositions:n=[],participantMap:o,drawDefinition:i,collectionId:s,sideLineUps:a,matchUpType:c}){if(!s||!r)return{};let u=({attribute:m,lineUp:d,teamParticipant:l})=>{let{assignedParticipantIds:f,substitutions:g}=cp({collectionPosition:r,collectionId:s,lineUp:d});if(c===jt){if(f?.length<=2){let I=o?.[f[0]]?.pairIdMap?.[f[1]],T=(I&&o[I]?.participant||zr({participantIds:f,tournamentParticipants:t}).participant)?.participantId;return{[m]:{participantId:T,teamParticipant:l,substitutions:g}}}else if(f?.length>2)return{[m]:{teamParticipant:l,substitutions:g}}}else{let I=f?.[0];return I&&{[m]:{participantId:I,teamParticipant:l,substitutions:g}}}};if(!n?.length){let m=a?.map(d=>{let{teamParticipant:l,sideNumber:f}=d,g=d.lineUp||ts({participantId:l.teamParticipantId,drawDefinition:i})?.lineUp;return u({attribute:f,lineUp:g,teamParticipant:l})}).filter(Boolean)||{};return{sideNumberCollectionAssignment:Object.assign({},...m)}}let p=n?.map(m=>{let d=e.find(I=>I.drawPosition===m)?.participantId,l=a?.find(I=>I?.drawPosition===m),f=l?.teamParticipant||d&&o?.[d]?.participant||t?.find(({participantId:I})=>I===d),g=l?.lineUp||ts({participantId:d,drawDefinition:i})?.lineUp;return u({attribute:m,lineUp:g,teamParticipant:f})}).filter(Boolean)||{};return{drawPositionCollectionAssignment:Object.assign({},...p)}}function ph({drawDefinition:t}){if(typeof t!="object")return{error:Js};let e={},{structures:r=[],links:n=[]}=t||{},o=r.reduce((s,a)=>{let{stage:c}=a;return s[c]?s[c].push(a):s[c]=[a],s},{});for(let s of Object.keys(o)){let a=o[s].find(({stageSequence:p})=>p===1);if(!a)continue;let{structureId:c}=a;i({aggregator:{},targetRound:0,exitProfiles:e,exitProfile:"0",structureId:c,stage:s})}return{exitProfiles:e};function i({exitProfiles:s,exitProfile:a,structureId:c,targetRound:u,aggregator:p,stage:m}){s[c]||(s[c]=[]),a==="0"&&[Ge,ae].includes(m)||s[c].push(a);let d=n.filter(l=>l.source.structureId===c&&l.source.roundNumber>=u);for(let l of d){let f=l.source.roundNumber,g=l.target.roundNumber,I=l.target.structureId,h=r.find(T=>T.structureId===I).stage,S=[h,I,g,f].join("|");if(p[S])return;p[S]=!0,i({exitProfile:`${a}-${f}`,structureId:I,exitProfiles:s,targetRound:g,aggregator:p,stage:h})}}}function UR({drawDefinition:t,roundProfile:e,structureId:r,matchUpsMap:n}){if(!t)return{error:z};if(!r)return{error:We};if(!e){let c=ko({matchUpsMap:n,structureId:r});if({roundProfile:e}=Xe({matchUps:c}),!e)return{error:et}}let i=(Math.min(...e?.[1]?.drawPositions??[])||1)-1,s=Object.keys(e);return{drawPositionsRanges:Object.assign({},...(s||[]).map(c=>{let u=e?.[c]?.matchUpsCount,p=e?.[1]?.drawPositions??[],m=Ae(p,p.length/u),d=m.map(Om),l=m.map(S=>S.map(T=>T-i)).map(Om),f=s.map(S=>{if(S>c)return;let T=e?.[S]?.drawPositions??[];return Ae(T,T.length/u)}).filter(Boolean),g=Z(0,u).map(S=>f.map(T=>T[S]).flat().filter(Boolean).sort(oe)).map(S=>mt(S)),I=g.map(S=>iC(S).map(Om).join(", ")),h=Object.assign({},...Z(0,u).map(S=>({[S+1]:{firstRoundDrawPositionsRange:d[S],firstRoundOffsetDrawPositionsRange:l[S],possibleDrawPositions:g[S],drawPositionsRange:I[S]}})));return{[c]:h}}))}}function vm({roundsNotPowerOf2:t,drawDefinition:e,structure:r,matchUps:n}){if(!r)return!1;n=n??r.matchUps??[],t=t??Xe({matchUps:n}).roundsNotPowerOf2;let o=!!r.positionAssignments?.find(({drawPosition:i})=>i)||!!n?.find(({drawPositions:i})=>i?.length);return(!e?.drawType||e.drawType!==Mi)&&!r?.structures&&t&&o}function Br({drawDefinition:t,structure:e}){if(!e)return!1;let r=e.matchUps||e.roundMatchUps&&Object.values(e.roundMatchUps).flat(),n=r?.find(i=>i?.roundPosition),o=r?.find(i=>i?.drawPositions?.length);return!e?.structures&&e?.stage!==ke&&!(t?.drawType&&t.drawType!==br)&&!n&&!o}var Nf={[ia]:{policyName:"Round Naming Default",namingConventions:{round:"Round",pre:"Pre"},qualifyingFinishMap:{1:"Final"},abbreviatedRoundNamingMap:{1:"F",2:"SF",4:"QF"},roundNamingMap:{1:"Final",2:"Semifinal",4:"Quarterfinal"},affixes:{roundNumber:"R",preFeedRound:"Q",preQualifying:"P"},stageConstants:{[tt]:"",[ae]:"P",[at]:"Q",[Ge]:"C"}}},PR=Nf;function NR({roundNamingPolicy:t,drawDefinition:e,structure:r,matchUps:n}){let{roundProfile:o,roundMatchUps:i}=Xe({matchUps:n}),{structureAbbreviation:s,stage:a}=r,c=Br({structure:r}),u=vm({structure:r}),p=r.structures,m={},d=Nf[ia],l=r.stage===at,f=l?Math.max(...(e?.structures??[]).filter(O=>O.stage===at).map(({stageSequence:O})=>O??1),0):0,g=(r.stageSequence??1)<f?r.stageSequence??1:"",I=g&&(t?.affixes?.preQualifying||d.affixes.preQualifying)||"",h=t?.roundNamingMap||d.roundNamingMap||{},S=t?.abbreviatedRoundNamingMap||d.abbreviatedRoundNamingMap||{},T=t?.affixes?.preFeedRound||d.affixes.preFeedRound,A=t?.affixes?.roundNumber||d.affixes.roundNumber,y=(t?.namingConventions||d.namingConventions).round,E=a&&a!==tt?a[0]:"",U=t?.stageConstants||d.stageConstants,M=a&&U?.[a]||E,N=`${I}${M}${g}`,C=o?Object.keys(o):[],D=l&&U?.[at]?`${U?.[at]}-`:"";if(p||c||u)Object.assign(m,...C.map(O=>{let b=`${D}${y} ${O}`,_=`${A}${O}`;return{[O]:{roundName:b,abbreviatedRoundName:_}}}));else{let O=l&&(t?.qualifyingFinishMap||d?.qualifyingFinishMap||{});Object.assign(m,...C.map(b=>{if(!o?.[b])return;let{matchUpsCount:_,preFeedRound:L}=o[b],F=_*2,w=O?.[o?.[b].finishingRound]||O&&`${A}${F}`||h[_]||`${A}${F}`,x=L?`-${T}`:"",H=`${w}${x}`,V=[N,s,H].filter(Boolean).join("-"),B=`${S[_]||`${A}${F}`}${x}`,q=[N,s,B].filter(Boolean).join("-");return{[b]:{abbreviatedRoundName:q,roundName:V}}}))}return{roundNamingProfile:m,roundProfile:o,roundMatchUps:i}}function xm(t){let e=vt(t,[{[co]:!0}]);if(e.error)return e;let r=t?.matchUp,n=r?.matchUpType;if(!n&&r?.sides?.length){let s=r.sides.find(({participant:a})=>a)?.participant?.participantType;n=s===It&&ee||s===pt&&jt||s===Lt&&Lt||void 0}return{matchUpType:n}}function ga(t){let{matchUps:e,isCollectionMatchUp:r,excludeMatchUpStatuses:n,matchUpStatuses:o,hasWinningSide:i,matchUpFormats:s,roundPositions:a,matchUpFormat:c,collectionIds:u,isMatchUpTie:p,roundNumbers:m,matchUpIds:d,roundNames:l,stageSequences:f,scheduledDates:g,scheduledDate:I,participantIds:h,processContext:S,tournamentIds:T,matchUpTypes:A,structureIds:P,readyToScore:y,courtIds:E,eventIds:U,venueIds:M,drawIds:N,stages:C,filterMatchUpIds:D=!0,filterMatchUpTypes:O=!0}=t,b=Array.isArray(h)?h.filter(Boolean):[],_=Array.isArray(o)?o.filter(Boolean):[],L=Array.isArray(n)?n.filter(Boolean):[],F=Array.isArray(C)?C.filter(Boolean):[],w=Array.isArray(f)?f.filter(Boolean):[],x=Array.isArray(u)?u.filter(Boolean):[],H=Array.isArray(l)?l.filter(Boolean):[],V=Array.isArray(m)?m.filter(Boolean):[],W=Array.isArray(a)?a.filter(Boolean):[],B=Array.isArray(d)&&D?d.filter(Boolean):[],q=Array.isArray(A)&&O?A.filter(Boolean):[],Y=Array.isArray(E)?E.filter(Boolean):[],k=Array.isArray(M)?M.filter(Boolean):[],K=Array.isArray(s)&&s.filter(Boolean)||typeof c=="string"&&[c]||[],X=Array.isArray(g)&&g.filter(Boolean)||typeof I=="string"&&I.length&&[I]||[],$=Array.isArray(T)?T.filter(Boolean):[],nt=Array.isArray(U)?U.filter(Boolean):[],Q=Array.isArray(N)?N.filter(Boolean):[],it=Array.isArray(P)?P.filter(Boolean):[];return e.filter(ot=>{if(y&&ot.matchUpType!==pn&&!ot.readyToScore||ot.winningSide&&i&&![1,2].includes(ot.winningSide)||p!==void 0&&(p&&!ot.tieMatchUps||!p&&ot.tieMatchUps)||r!==void 0&&(r&&!ot.collectionId||!r&&ot.collectionId)||F.length&&!F.includes(ot.stage)||w.length&&!w.includes(ot.stageSequence)||x.length&&(!ot.collectionId||!x.includes(ot.collectionId))||H.length&&(!ot.roundName||!H.includes(ot.roundName))||V.length&&(!ot.roundNumber||!V.includes(ot.roundNumber))||W.length&&(!ot.roundPosition||!W.includes(ot.roundPosition))||_.length&&(!ot.matchUpStatus||!_.includes(ot.matchUpStatus))||L.length&&ot.matchUpStatus&&L.includes(ot.matchUpStatus)||B.length&&!B.includes(ot.matchUpId)||q.length&&(!ot.matchUpType||!q.includes(ot.matchUpType))||K.length&&(!ot.matchUpFormat||!K.includes(ot.matchUpFormat)))return!1;if(X?.length){let{scheduledTime:dt}=Af({matchUp:ot}),{scheduledDate:zt}=Ji({matchUp:ot}),ge=At(dt)||zt;if(!X.find(Ee=>Dn(Ee,ge)))return!1}if(Y.length){let{courtId:dt}=ah({matchUp:ot}),{allocatedCourts:zt}=sh({matchUp:ot}),Et=zt?.map(({courtId:ge})=>ge);if(!Y.filter(Boolean).includes(dt)||Et?.includes(dt))return!1}if(k.length){let{venueId:dt}=ch({matchUp:ot});if(!k.filter(Boolean).includes(dt))return!1}if(S){if($.length&&!$.includes(ot.tournamentId)||nt.length&&!nt.includes(ot.eventId)||Q.length&&!Q.includes(ot.drawId)||it.length&&!it.includes(ot.structureId))return!1;if(b.length){let dt=ot.sides?.map(({participantId:Et})=>Et).filter(Boolean)??[];if(!b.some(Et=>dt.includes(Et)))return!1}}return!0})}function DR({drawPositionCollectionAssignment:t,sideNumberCollectionAssignment:e,positionAssignments:r,displaySideNumber:n,seedAssignments:o,drawPosition:i,isFeedRound:s,sideNumber:a}){let c=r.find(l=>l.drawPosition&&l.drawPosition===i),u=i&&t,p=a&&e,m=u?u[i]?.participantId:c?.participantId,d=c?kL({displaySideNumber:n,seedAssignments:o,participantId:m,assignment:c,sideNumber:a}):{...p?.[a]};if(s&&(a===1?Object.assign(d,{participantFed:!0}):Object.assign(d,{participantAdvanced:!0})),i&&u){let l=u[i]?.teamParticipant,f=u[i]?.participant,g=u[i]?.substitutions;f&&(d.participant=f),g&&(d.substitutions=g),l&&(d.teamParticipant=l)}return d}function kL({displaySideNumber:t,seedAssignments:e,participantId:r,assignment:n,sideNumber:o}){let i={drawPosition:n.drawPosition,displaySideNumber:t,sideNumber:o};if(r){let s=VL({seedAssignments:e,participantId:r});Object.assign(i,s,{participantId:r})}else n.bye&&Object.assign(i,{bye:!0});return n.qualifier&&Object.assign(i,{qualifier:!0}),i}function VL({seedAssignments:t,participantId:e}){return t?.find(r=>!r.seedProxy&&r.participantId===e)}var On="ANY",Zt="MALE",Cr="MIXED",Ia="OTHER",ce="FEMALE",wm={ANY:On,MALE:Zt,FEMALE:ce,MIXED:Cr,OTHER:Ia};function Pt({scheduleVisibilityFilters:t,tournamentAppliedPolicies:e,provisionalPositioning:r,tournamentParticipants:n,afterRecoveryTimes:o,policyDefinitions:i,tournamentRecord:s,seedAssignments:a,usePublishState:c,contextFilters:u,contextContent:p,matchUpFilters:m,participantMap:d,scheduleTiming:l,contextProfile:f,drawDefinition:g,publishStatus:I,context:h={},exitProfiles:S,matchUpsMap:T,structure:A,inContext:P,event:y}){let E={},U={};if(n=n??s?.participants,!A)return{collectionPositionMatchUps:E,error:Ao,roundMatchUps:U,matchUps:[]};let M=Array.isArray(m?.eventIds)?m?.eventIds.filter(Boolean):[],N=Array.isArray(m?.structureIds)?m?.structureIds.filter(Boolean):[],C=Array.isArray(m?.drawIds)?m?.drawIds.filter(Boolean):[],D=!h?.eventId||!M?.length&&!u?.eventIds?.filter(Boolean).length||M?.includes(h.eventId)||u?.eventIds?.includes(h.eventId),O=!N?.length||N.includes(A.structureId),b=!g||!C?.length||C.includes(g.drawId);if(!D||!O||!b)return{collectionPositionMatchUps:E,roundMatchUps:U,matchUps:[]};f&&!p&&(p=bn({tournamentRecord:s,contextProfile:f,drawDefinition:g}));let{appliedPolicies:_}=yt({drawDefinition:g}),L={...e,..._,...i},F=L?.scoring?.structures,w=A.stage&&F?.stage&&F?.stage[A.stage],x=A.stageSequence&&w?.stageSequence&&w.stageSequence[A.stageSequence],H=L?.scoring?.requireAllPositionsAssigned||w?.requireAllPositionsAssigned||x?.requireAllPositionsAssigned;T||(T=be({drawDefinition:g,structure:A}));let{positionAssignments:V,allPositionsAssigned:W}=de({structure:A}),B=!H||W,{seedAssignments:q}=vr({provisionalPositioning:r,drawDefinition:g,structure:A});a=a??q;let{roundOffset:Y,structureId:k,structureName:K,stage:X,stageSequence:$}=A,{drawId:nt,drawName:Q,drawType:it}=g??{};S=S||g&&ph({drawDefinition:g}).exitProfiles;let ot=S?.[k],dt=ot?.length&&(ot[0].split("-").map(Ht=>parseInt(Ht)).reduce((Ht,Ie)=>Ht+Ie)||0),zt=!!A.structures,Et=ko({matchUpsMap:T,structureId:k,inContext:P}),ge=L?.[ia],Ee=NR({roundNamingPolicy:ge,drawDefinition:g,structure:A,matchUps:Et}),{roundNamingProfile:Ce,roundProfile:Xt}=Ee;if(U=Ee?.roundMatchUps??[],m&&(Et=ga({matchUps:Et,...m,filterMatchUpTypes:!1,filterMatchUpIds:!1})),P){let{sourceDrawPositionRanges:Ht}=fR({drawDefinition:g,matchUpsMap:T,structureId:k}),Ie=g?UR({drawDefinition:g,roundProfile:Xt,matchUpsMap:T,structureId:k}).drawPositionsRanges:void 0;Et=Et.map(Qt=>Ue({scheduleVisibilityFilters:t,sourceDrawPositionRanges:Ht,drawPositionsRanges:Ie,roundNamingProfile:Ce,initialRoundOfPlay:dt,appliedPolicies:L,usePublishState:c,publishStatus:I,isRoundRobin:zt,roundProfile:Xt,matchUp:Qt,event:y})),(Et?.filter(Qt=>Array.isArray(Qt.tieMatchUps))).forEach(Qt=>{let Ft=Qt.tieMatchUps;Et=Et.concat(...Ft)}),u&&(Et=ga({processContext:!0,...u,matchUps:Et}))}else(Et?.filter(Ie=>Array.isArray(Ie.tieMatchUps))).forEach(Ie=>{let Nt=Ie.tieMatchUps;Et=Et.concat(...Nt)});return m&&(Et=ga({matchUps:Et,...m,filterMatchUpTypes:!1,filterMatchUpIds:!1})),(m?.matchUpTypes||m?.matchUpIds)&&(Et=ga({matchUpTypes:m.matchUpTypes,matchUpIds:m.matchUpIds,matchUps:Et})),(m?.matchUpTypes||m?.matchUpIds||P)&&(U=Xe({matchUps:Et}).roundMatchUps??[]),Ve({drawDefinition:g,structure:A,event:y})?.tieFormat&&({collectionPositionMatchUps:E}=lR({matchUps:Et})),{collectionPositionMatchUps:E,roundMatchUps:U,roundProfile:Xt,matchUpsMap:T,matchUps:Et};function Ue({scheduleVisibilityFilters:Ht,sourceDrawPositionRanges:Ie,drawPositionsRanges:Nt,initialRoundOfPlay:Qt,additionalContext:Ft,roundNamingProfile:Yt,tieDrawPositions:ue,appliedPolicies:Se,isCollectionBye:ur,usePublishState:Oe,publishStatus:Vt,matchUpTieId:_e,isRoundRobin:tr,roundProfile:Re,sideLineUps:Er,matchUp:Te,event:Pe}){Ft=Ft??{};let dr=Ve({drawDefinition:g,structure:A,matchUp:Te,event:Pe})?.tieFormat,Xo=dr?.collectionDefinitions,He=Te.collectionId&&Xo?.find(jn=>jn.collectionId===Te.collectionId),Pn=Te.collectionId?He?.matchUpFormat:Te.matchUpFormat??A?.matchUpFormat??g?.matchUpFormat??Pe?.matchUpFormat,Ii=Te.matchUpType||He?.matchUpType||A?.matchUpType||g?.matchUpType||Pe?.eventType!==Le&&Pe?.eventType,Gi=ur?Ut:Te.matchUpStatus,{schedule:fn,endDate:Dc}=bm({scheduleVisibilityFilters:Ht,afterRecoveryTimes:o,tournamentRecord:s,usePublishState:Oe,scheduleTiming:l,matchUpFormat:Pn,publishStatus:Vt,matchUpType:Ii,matchUp:Te,event:Pe}),ki=ue??Te.drawPositions??[],{collectionPosition:Hg,collectionId:BM,roundPosition:Wg}=Te,Vi=Te.roundNumber??Ft.roundNumber,Bx=BM?ER({tournamentParticipants:n,positionAssignments:V,collectionPosition:Hg,drawDefinition:g,participantMap:d,drawPositions:ki,collectionId:BM,sideLineUps:Er,matchUpType:Ii}):void 0,HM=Yt?.[Vi]?.roundName||Ft.roundName,WM=Yt?.[Vi]?.abbreviatedRoundName||Ft.abbreviatedRoundName,Hx=Re?.[Vi]?.feedRound,Wx=Re?.[Vi]?.preFeedRound,jx=Re?.[Vi]?.roundFactor,Yx=Nt?.[Vi],qx=Wg?Yx?.[Wg]:void 0,$x=Ie?.[Vi],Kx=He?.category?{...h?.category||{},...He.category}:h?.category??Pe?.category,zx=Te.processCodes?.length&&Te.processCodes||He?.processCodes?.length&&He?.processCodes||A?.processCodes?.length&&A?.processCodes||g?.processCodes?.length&&g?.processCodes||Pe?.processCodes?.length&&Pe?.processCodes||s?.processCodes,Qx=f?.withCompetitiveness&&Jc({...p,matchUp:Te}),Xx=Te.finishingPositionRange??Ft.finishingPositionRange,jg=jn=>rt(jn,void 0,!0),lr={...jg(h),...jg({matchUpFormat:Te.matchUpType===Le?void 0:Pn,tieFormat:Te.matchUpType!==Le?void 0:dr,gender:He?.gender??Pe?.gender,roundOfPlay:X!==at&&lt(Qt)&&Qt+(Vi||0),endDate:Te.endDate??Dc,discipline:Pe?.discipline,category:Kx,finishingPositionRange:Xx,abbreviatedRoundName:WM,drawPositionsRange:qx,competitiveProfile:Qx,structureName:K,stageSequence:$,drawPositions:ki,matchUpStatus:Gi,processCodes:zx,isRoundRobin:tr,matchUpTieId:_e,preFeedRound:Wx,matchUpType:Ii,roundFactor:jx,roundOffset:Y,structureId:k,roundNumber:Vi,feedRound:Hx,roundName:HM,drawName:Q,drawType:it,schedule:fn,drawId:nt,stage:X}),...J(jg(Te),!0,!0)};if(Pn&&Te.score?.scoreStringSide1){let jn=Ze(Pn),{bestOf:Qs,finalSetFormat:Is,setFormat:gr}=jn??{};(Is?.tiebreakSet||gr?.tiebreakSet||gr?.timed)&&(lr.score.sets=lr.score.sets.sort((wr,Nn)=>wr.setNumber-Nn.setNumber).map((wr,Nn)=>(Nn+1===Qs?(Is?.tiebreakSet||Is?.timed)&&(wr.tiebreakSet=!0):(gr?.tiebreakSet||gr?.timed)&&(wr.tiebreakSet=!0),wr)))}if(Array.isArray(ki)){let{orderedDrawPositions:jn,displayOrder:Qs}=yR({drawPositions:ki,roundProfile:Re,roundNumber:Vi}),Is=Re?.[Vi]?.feedRound,gr=Qs[0]!==jn[0],Nn=jn.concat(void 0,void 0).slice(0,2).map((hi,xA)=>{let Yg=xA+1,Zx=gr?3-Yg:Yg,tw=DR({...Bx,positionAssignments:V,displaySideNumber:Zx,seedAssignments:a,drawPosition:hi,isFeedRound:Is,sideNumber:Yg}),ew=Te.sides?.find(nw=>nw.sideNumber===Yg),YM=Wg?(Wg-1)*2+xA+1:void 0,rw=YM?$x?.[YM]:void 0;return jg({sourceDrawPositionRange:rw,...ew,...tw})});Object.assign(lr,J({sides:Nn},!0,!0))}if(n&&lr.sides){let jn=Se?.[Ka],Qs=gr=>{let wr=d?.[gr]?.participant;return wr&&Di({template:jn?.participant,source:wr})};if(lr.sides.filter(Boolean).forEach(gr=>{if(gr.participantId){let wr=J(Qs(gr.participantId)||n&&Uo({policyDefinitions:Se,participantId:gr.participantId,tournamentParticipants:n,internalUse:!0,contextProfile:f}),void 0,!0);if(wr){if(g?.entries){let Nn=g.entries.find(hi=>hi.participantId===gr.participantId);Nn?.entryStatus&&(wr.entryStatus=Nn.entryStatus),Nn?.entryStage&&(wr.entryStage=Nn.entryStage)}Object.assign(gr,{participant:wr})}}if(gr?.participant?.individualParticipantIds?.length&&!gr.participant.individualParticipants?.length){let wr=gr.participant.individualParticipantIds.map(Nn=>Qs(Nn)||n&&Uo({policyDefinitions:Se,tournamentParticipants:n,internalUse:!0,contextProfile:f,participantId:Nn}));Object.assign(gr.participant,{individualParticipants:wr})}}),!lr.matchUpType){let{matchUpType:gr}=xm({matchUp:lr});gr&&Object.assign(lr,{matchUpType:gr})}if(f?.inferGender&&(!lr.gender||lr.gender===Cr)&&lr.sides?.length===2&&lr.matchUpType!==Le){let gr=lr.sides.map(wr=>{if(lr.matchUpType===ee)return wr.participant?.person?.sex;if(wr.participant?.individualParticipants?.length===2){let Nn=mt(wr.participant.individualParticipants.map(hi=>hi.person?.sex)).filter(Boolean);if(Nn.length===1)return Nn[0]}});if(gr.filter(Boolean).length===2&&mt(gr).length===1){let wr=gr[0];lr.inferredGender=wr}}}if(lr.tieMatchUps){let jn=lr.matchUpStatus===Ut,Qs=lr.sides?.map(({participant:Is,drawPosition:gr,sideNumber:wr,lineUp:Nn})=>{let hi=Is?.participantType===Le&&Is;return{teamParticipant:hi&&rt({participantRoleResponsibilities:hi.participantRoleResponsibilities,participantOtherName:hi.participanOthertName,participantName:hi.participantName,participantId:hi.participantId,teamId:hi.teamId}),drawPosition:gr,sideNumber:wr,lineUp:Nn}});lr.tieMatchUps=lr.tieMatchUps.map(Is=>{let gr=lr.matchUpId,Nn={finishingPositionRange:lr.finishingPositionRange,abbreviatedRoundName:WM,roundNumber:Vi,roundName:HM};return Ue({tieDrawPositions:ki,scheduleVisibilityFilters:Ht,sourceDrawPositionRanges:Ie,sideLineUps:Qs,drawPositionsRanges:Nt,initialRoundOfPlay:Qt,roundNamingProfile:Yt,additionalContext:Nn,appliedPolicies:Se,isCollectionBye:jn,usePublishState:Oe,publishStatus:Vt,matchUpTieId:gr,isRoundRobin:tr,roundProfile:Re,matchUp:Is,event:Pe})})}let jM=lr.sides&&lr.sides.filter(jn=>jn?.participantId).length===2,Jx=!lr.winningSide;if(Object.assign(lr,{readyToScore:B&&jM&&Jx,hasContext:!0}),jM){let{allParticipantsCheckedIn:jn,checkedInParticipantIds:Qs}=Xi({matchUp:lr});Object.assign(lr,{allParticipantsCheckedIn:jn,checkedInParticipantIds:Qs})}return Array.isArray(f?.exclude)&&f?.exclude.forEach(jn=>delete lr[jn]),lr}}function es({matchUp:t}){return t?ie.includes(t?.matchUpStatus)||t?.winningSide:!1}function eu({requireParticipants:t=!0,scheduleVisibilityFilters:e,tournamentAppliedPolicies:r,tournamentParticipants:n,afterRecoveryTimes:o,policyDefinitions:i,tournamentRecord:s,usePublishState:a,matchUpFilters:c,contextFilters:u,contextContent:p,participantMap:m,scheduleTiming:d,publishStatus:l,contextProfile:f,drawDefinition:g,exitProfiles:I,matchUpsMap:h,structureId:S,inContext:T,structure:A,context:P,event:y}){!A&&S&&({structure:A}=st({drawDefinition:g,structureId:S}));let E=Pt({tournamentAppliedPolicies:r,scheduleVisibilityFilters:e,tournamentParticipants:n,afterRecoveryTimes:o,policyDefinitions:i,tournamentRecord:s,usePublishState:a,matchUpFilters:c,contextFilters:u,contextContent:p,participantMap:m,scheduleTiming:d,publishStatus:l,contextProfile:f,drawDefinition:g,exitProfiles:I,matchUpsMap:h,structure:A,inContext:T,context:P,event:y}),U=[],M=[],N=[],C=[],D=[];if(E.error)return E;let{matchUps:O}=E,{assignedPositions:b}=de({structure:A}),_=b?.filter(F=>F.participantId).map(F=>F.drawPosition),L;return O.filter(F=>{let w=c?.matchUpTypes?.length===1&&c.matchUpTypes[0]===Bt;return!(F.matchUpType!==Bt&&w)}).forEach(F=>{if(F.matchUpStatus===kr){U.push(F);return}F.matchUpType===Bt&&(L=!0);let w=F.collectionId,x=w&&F.sides?.every(k=>k.participantId),H=!w&&F.drawPositions?.filter(Boolean).length===2,V=!w&&F.drawPositions?.every(k=>_?.includes(k)),W=b?.filter(k=>k.bye).map(k=>k.drawPosition),B=!w&&F.drawPositions?.find(k=>W?.includes(k)),Y=LI.includes(F.matchUpStatus)&&(x||H&&(!t||V));return B?D.push(F):es({matchUp:F})?M.push(F):Y?N.push(F):C.push(F)}),{includesTeamMatchUps:L,abandonedMatchUps:U,completedMatchUps:M,upcomingMatchUps:N,pendingMatchUps:C,byeMatchUps:D,structure:A}}function re(t){let e="getAllDrawMatchUps";Object.assign(t,{requireParticipants:!1});let r=ws(t);if(r.error)return v({result:r,stack:e});let{abandonedMatchUps:n,completedMatchUps:o,upcomingMatchUps:i,pendingMatchUps:s,byeMatchUps:a,matchUpsMap:c}=r;return{matchUps:(n??[]).concat(...o??[],...i??[],...s??[],...a??[]),matchUpsMap:c}}function ws(t){if(!t?.drawDefinition)return{error:z};let{tournamentParticipants:e,contextContent:r,matchUpsMap:n}=t,{scheduleVisibilityFilters:o,tournamentAppliedPolicies:i,requireParticipants:s,participantsProfile:a,afterRecoveryTimes:c,policyDefinitions:u,tournamentRecord:p,usePublishState:m,contextFilters:d,matchUpFilters:l,scheduleTiming:f,participantMap:g,publishStatus:I,contextProfile:h,drawDefinition:S,nextMatchUps:T,inContext:A,context:P,event:y}=t,E=[],U=[],M=[],N=[],C=[];h&&!r&&(r=bn({policyDefinitions:u,tournamentRecord:p,contextProfile:h,event:y}));let D;!e?.length&&p&&(e=p?.participants,(A||a?.withGroupings)&&e?.length&&({participantsWithGroupings:e,groupInfo:D}=Em({participants:e,participantsProfile:a})));let{structures:O}=Cn({drawDefinition:S});if(!O)return{error:_t};n||(n=be({drawDefinition:S}));let b=S&&ph({drawDefinition:S}).exitProfiles;O.forEach(F=>{let{byeMatchUps:w=[],pendingMatchUps:x=[],upcomingMatchUps:H=[],completedMatchUps:V=[],abandonedMatchUps:W=[]}=eu({matchUpFilters:T?void 0:l,contextFilters:T?void 0:d,inContext:A||T||d,tournamentAppliedPolicies:i,scheduleVisibilityFilters:o,tournamentParticipants:e,requireParticipants:s,afterRecoveryTimes:c,policyDefinitions:u,tournamentRecord:p,usePublishState:m,contextContent:r,participantMap:g,scheduleTiming:f,publishStatus:I,contextProfile:h,drawDefinition:S,exitProfiles:b,matchUpsMap:n,structure:F,context:P,event:y});E=E.concat(...W),U=U.concat(...V),M=M.concat(...H),N=N.concat(...x),C=C.concat(...w)});let _=F=>(!l&&!T&&!d||(l&&(F=ga({matchUps:F,...l})),d&&(F=ga({matchUps:F,...d,processContext:!0}))),F),L={abandonedMatchUps:_(E),completedMatchUps:_(U),upcomingMatchUps:_(M),pendingMatchUps:_(N),byeMatchUps:_(C),matchUpsMap:n,...R,groupInfo:D};if(T){let F=typeof T=="object"||{abandoned:!0,completed:!0,upcoming:!0,pending:!0,bye:!0},{abandoned:w,completed:x,upcoming:H,pending:V,bye:W}=F,B=[].concat(...w&&E||[],...x&&U||[],...H&&M||[],...V&&N||[],...W&&C||[]);YC({inContextDrawMatchUps:B,drawDefinition:S})}return L}function rs({inContextDrawMatchUps:t,drawDefinition:e,matchUpsMap:r}){if(!e)return{error:z};let n={loserMatchUpIds:{},winnerMatchUpIds:{}};if(t||({matchUps:t,matchUpsMap:r}=re({inContext:!0,drawDefinition:e,matchUpsMap:r})),!r?.drawMatchUps.some(i=>i.finishingPositionRange)&&e?.structures?.length===1&&!e?.structures[0].structures){let i=r?.drawMatchUps??[];Cs({matchUps:i})}return(t??[]).filter(({collectionId:i})=>!i).forEach(i=>{let{matchUpId:s,structureId:a}=i,c=Je({inContextDrawMatchUps:t,drawDefinition:e,matchUpId:s}),{winnerMatchUp:u,loserMatchUp:p}=c.targetMatchUps,m=u?.matchUpId,d=p?.matchUpId,f=ko({matchUpsMap:r,structureId:a}).find(g=>g.matchUpId===s);if(f&&(m&&(n.winnerMatchUpIds[f.matchUpId]=m,Object.assign(f,{winnerMatchUpId:m}),Object.assign(i,{winnerMatchUpId:m})),d&&(n.loserMatchUpIds[f.matchUpId]=d,i.loserMatchUpId=d,f.loserMatchUpId=d,i.finishingPositionRange))){let g=p.finishingPositionRange&&[...i.finishingPositionRange.loser,...p.finishingPositionRange.loser],I=g&&[Math.min(...g),Math.max(...g)];i.finishingPositionRange.loser=I,f.finishingPositionRange.loser=I}}),{inContextDrawMatchUps:t,goesToMap:n}}function jE(t){return t&&typeof String.fromCodePoint<"u"?t.toUpperCase().replace(/./g,e=>String.fromCodePoint(e.charCodeAt(0)+127397)):t}function MR(t){let e=Object.assign({},...Yo.filter(r=>r.ioc).map(r=>({[r.ioc]:r.iso})));return jE(e[t])}var Yo=[{ioc:"",iso2:"",iso:"",label:"NONE",phone:""},{ioc:"AND",iso2:"AD",iso:"AND",label:"Andorra",phone:"376"},{ioc:"UAE",iso2:"AE",iso:"ARE",label:"United Arab Emirates",phone:"971"},{ioc:"AFG",iso2:"AF",iso:"AFG",label:"Afghanistan",phone:"93"},{ioc:"ANT",iso2:"AG",iso:"ATG",label:"Antigua and Barbuda",phone:"1-268"},{ioc:"AIA",iso2:"AI",iso:"AIA",label:"Anguilla",phone:"1-264"},{ioc:"ALB",iso2:"AL",iso:"ALB",label:"Albania",phone:"355"},{ioc:"ARM",iso2:"AM",iso:"ARM",label:"Armenia",phone:"374"},{ioc:"ANG",iso2:"AO",iso:"AGO",label:"Angola",phone:"244"},{ioc:"",iso2:"AQ",iso:"ATA",label:"Antarctica",phone:"672"},{ioc:"ARG",iso2:"AR",iso:"ARG",label:"Argentina",phone:"54"},{ioc:"ASA",iso2:"AS",iso:"ASM",label:"American Samoa",phone:"1-684"},{ioc:"AUT",iso2:"AT",iso:"AUT",label:"Austria",phone:"43"},{ioc:"AUS",iso2:"AU",iso:"AUS",label:"Australia",phone:"61",suggested:!0},{ioc:"ARU",iso2:"AW",iso:"ABW",label:"Aruba",phone:"297"},{ioc:"AZE",iso2:"AZ",iso:"AZE",label:"Azerbaijan",phone:"994"},{ioc:"BIH",iso2:"BA",iso:"BIH",label:"Bosnia and Herzegovina",phone:"387"},{ioc:"BAR",iso2:"BB",iso:"BRB",label:"Barbados",phone:"1-246"},{ioc:"BAN",iso2:"BD",iso:"BGD",label:"Bangladesh",phone:"880"},{ioc:"BEL",iso2:"BE",iso:"BEL",label:"Belgium",phone:"32"},{ioc:"BUR",iso2:"BF",iso:"BFA",label:"Burkina Faso",phone:"226"},{ioc:"BUL",iso2:"BG",iso:"BGR",label:"Bulgaria",phone:"359"},{ioc:"BRN",iso2:"BH",iso:"BHR",label:"Bahrain",phone:"973"},{ioc:"BDI",iso2:"BI",iso:"BDI",label:"Burundi",phone:"257"},{ioc:"BEN",iso2:"BJ",iso:"BEN",label:"Benin",phone:"229"},{ioc:"",iso2:"BL",iso:"BLM",label:"Saint Barthelemy",phone:"590"},{ioc:"BER",iso2:"BM",iso:"BMU",label:"Bermuda",phone:"1-441"},{ioc:"BRU",iso2:"BN",iso:"BRN",label:"Brunei Darussalam",phone:"673"},{ioc:"BOL",iso2:"BO",iso:"BOL",label:"Bolivia",phone:"591"},{ioc:"BRA",iso2:"BR",iso:"BRA",label:"Brazil",phone:"55"},{ioc:"BAH",iso2:"BS",iso:"BHS",label:"Bahamas",phone:"1-242"},{ioc:"BHU",iso2:"BT",iso:"BTN",label:"Bhutan",phone:"975"},{ioc:"",iso2:"BV",iso:"BVT",label:"Bouvet Island",phone:"47"},{ioc:"BOT",iso2:"BW",iso:"BWA",label:"Botswana",phone:"267"},{ioc:"BLR",iso2:"BY",iso:"BLR",label:"Belarus",phone:"375"},{ioc:"BIZ",iso2:"BZ",iso:"BLZ",label:"Belize",phone:"501"},{ioc:"CAN",iso2:"CA",iso:"CAN",label:"Canada",phone:"1",suggested:!0},{ioc:"",iso2:"CC",iso:"CCK",label:"Cocos (Keeling) Islands",phone:"61"},{ioc:"CGO",iso2:"CD",iso:"COG",label:"Congo, Republic of the",phone:"242"},{ioc:"CAF",iso2:"CF",iso:"CAF",label:"Central African Republic",phone:"236"},{ioc:"COD",iso2:"CG",iso:"CGD",label:"Congo, Democratic Republic of the",phone:"243"},{ioc:"SUI",iso2:"CH",iso:"CHE",label:"Switzerland",phone:"41"},{ioc:"CIV",iso2:"CI",iso:"CIV",label:"Cote d'Ivoire",phone:"225"},{ioc:"COK",iso2:"CK",iso:"COK",label:"Cook Islands",phone:"682"},{ioc:"CHI",iso2:"CL",iso:"CHL",label:"Chile",phone:"56"},{ioc:"CMR",iso2:"CM",iso:"CMR",label:"Cameroon",phone:"237"},{ioc:"CHN",iso2:"CN",iso:"CHN",label:"China",phone:"86"},{ioc:"COL",iso2:"CO",iso:"COL",label:"Colombia",phone:"57"},{ioc:"CRC",iso2:"CR",iso:"CRI",label:"Costa Rica",phone:"506"},{ioc:"CUB",iso2:"CU",iso:"CUB",label:"Cuba",phone:"53"},{ioc:"CPV",iso2:"CV",iso:"CPV",label:"Cape Verde",phone:"238"},{ioc:"CUW",iso2:"CW",iso:"CUW",label:"Curacao",phone:"599"},{ioc:"CXR",iso2:"CX",iso:"CXR",label:"Christmas Island",phone:"61"},{ioc:"CYP",iso2:"CY",iso:"CYP",label:"Cyprus",phone:"357"},{ioc:"CZE",iso2:"CZ",iso:"CZE",label:"Czech Republic",phone:"420"},{ioc:"GER",iso2:"DE",iso:"DEU",label:"Germany",phone:"49",suggested:!0},{ioc:"DJI",iso2:"DJ",iso:"DJI",label:"Djibouti",phone:"253"},{ioc:"DEN",iso2:"DK",iso:"DNK",label:"Denmark",phone:"45"},{ioc:"DMA",iso2:"DM",iso:"DMA",label:"Dominica",phone:"1-767"},{ioc:"DOM",iso2:"DO",iso:"DOM",label:"Dominican Republic",phone:"1-809"},{ioc:"ALG",iso2:"DZ",iso:"DZA",label:"Algeria",phone:"213"},{ioc:"ECU",iso2:"EC",iso:"ECU",label:"Ecuador",phone:"593"},{ioc:"EST",iso2:"EE",iso:"ESE",label:"Estonia",phone:"372"},{ioc:"EGY",iso2:"EG",iso:"EGY",label:"Egypt",phone:"20"},{ioc:"",iso2:"EH",iso:"ESH",label:"Western Sahara",phone:"212"},{ioc:"ERI",iso2:"ER",iso:"ERI",label:"Eritrea",phone:"291"},{ioc:"ESP",iso2:"ES",iso:"ESP",label:"Spain",phone:"34"},{ioc:"ETH",iso2:"ET",iso:"ETH",label:"Ethiopia",phone:"251"},{ioc:"FIN",iso2:"FI",iso:"FIN",label:"Finland",phone:"358"},{ioc:"FIJ",iso2:"FJ",iso:"FJI",label:"Fiji",phone:"679"},{ioc:"FLK",iso2:"FK",iso:"FLK",label:"Falkland Islands (Malvinas)",phone:"500"},{ioc:"FSM",iso2:"FM",iso:"FSM",label:"Micronesia, Federated States of",phone:"691"},{ioc:"FAR",iso2:"FO",iso:"FRO",label:"Faroe Islands",phone:"298"},{ioc:"FRA",iso2:"FR",iso:"FRA",label:"France",phone:"33",suggested:!0},{ioc:"GAB",iso2:"GA",iso:"GAB",label:"Gabon",phone:"241"},{ioc:"GBR",iso2:"GB",iso:"GBR",label:"United Kingdom",phone:"44"},{ioc:"GRN",iso2:"GD",iso:"GRD",label:"Grenada",phone:"1-473"},{ioc:"GEO",iso2:"GE",iso:"GEO",label:"Georgia",phone:"995"},{ioc:"FGU",iso2:"GF",iso:"GUF",label:"French Guiana",phone:"594"},{ioc:"",iso2:"GG",iso:"GGY",label:"Guernsey",phone:"44"},{ioc:"",iso2:"GH",iso:"GHA",label:"Ghana",phone:"233"},{ioc:"GIB",iso2:"GI",iso:"GIB",label:"Gibraltar",phone:"350"},{ioc:"GRL",iso2:"GL",iso:"GRL",label:"Greenland",phone:"299"},{ioc:"GAM",iso2:"GM",iso:"GMB",label:"Gambia",phone:"220"},{ioc:"GUI",iso2:"GN",iso:"GIN",label:"Guinea",phone:"224"},{ioc:"GUD",iso2:"GP",iso:"GLP",label:"Guadeloupe",phone:"590"},{ioc:"GEQ",iso2:"GQ",iso:"GNQ",label:"Equatorial Guinea",phone:"240"},{ioc:"GRE",iso2:"GR",iso:"GRC",label:"Greece",phone:"30"},{ioc:"",iso2:"GS",iso:"SGS",label:"South Georgia and the South Sandwich Islands",phone:"500"},{ioc:"GUA",iso2:"GT",iso:"GTM",label:"Guatemala",phone:"502"},{ioc:"GUM",iso2:"GU",iso:"GUM",label:"Guam",phone:"1-671"},{ioc:"GBS",iso2:"GW",iso:"GNB",label:"Guinea-Bissau",phone:"245"},{ioc:"GUY",iso2:"GY",iso:"GUY",label:"Guyana",phone:"592"},{ioc:"HKG",iso2:"HK",iso:"HKG",label:"Hong Kong",phone:"852"},{ioc:"",iso2:"HM",iso:"HMD",label:"Heard Island and McDonald Islands",phone:"672"},{ioc:"HON",iso2:"HN",iso:"HND",label:"Honduras",phone:"504"},{ioc:"CRO",iso2:"HR",iso:"HRV",label:"Croatia",phone:"385"},{ioc:"HAI",iso2:"HT",iso:"HTI",label:"Haiti",phone:"509"},{ioc:"HUN",iso2:"HU",iso:"HUN",label:"Hungary",phone:"36"},{ioc:"INA",iso2:"ID",iso:"IDN",label:"Indonesia",phone:"62"},{ioc:"IRL",iso2:"IE",iso:"IRL",label:"Ireland",phone:"353"},{ioc:"ISR",iso2:"IL",iso:"ISR",label:"Israel",phone:"972"},{ioc:"",iso2:"IM",iso:"IMN",label:"Isle of Man",phone:"44"},{ioc:"IND",iso2:"IN",iso:"IND",label:"India",phone:"91"},{ioc:"",iso2:"IO",iso:"IOT",label:"British Indian Ocean Territory",phone:"246"},{ioc:"IRQ",iso2:"IQ",iso:"IRQ",label:"Iraq",phone:"964"},{ioc:"IRI",iso2:"IR",iso:"IRN",label:"Iran, Islamic Republic of",phone:"98"},{ioc:"ISL",iso2:"IS",iso:"ISL",label:"Iceland",phone:"354"},{ioc:"ITA",iso2:"IT",iso:"ITA",label:"Italy",phone:"39"},{ioc:"",iso2:"JE",iso:"JEY",label:"Jersey",phone:"44"},{ioc:"JAM",iso2:"JM",iso:"JAM",label:"Jamaica",phone:"1-876"},{ioc:"JOR",iso2:"JO",iso:"JOR",label:"Jordan",phone:"962"},{ioc:"JPN",iso2:"JP",iso:"JPN",label:"Japan",phone:"81",suggested:!0},{ioc:"KEN",iso2:"KE",iso:"KEN",label:"Kenya",phone:"254"},{ioc:"KGZ",iso2:"KG",iso:"KGZ",label:"Kyrgyzstan",phone:"996"},{ioc:"CAM",iso2:"KH",iso:"KHM",label:"Cambodia",phone:"855"},{ioc:"KIR",iso2:"KI",iso:"KIR",label:"Kiribati",phone:"686"},{ioc:"COM",iso2:"KM",iso:"COM",label:"Comoros",phone:"269"},{ioc:"SKN",iso2:"KN",iso:"KNA",label:"Saint Kitts and Nevis",phone:"1-869"},{ioc:"KOR",iso2:"KP",iso:"KOR",label:"Korea, Democratic People's Republic of",phone:"850"},{ioc:"PRK",iso2:"KR",iso:"PRK",label:"Korea, Republic of",phone:"82"},{ioc:"KUW",iso2:"KW",iso:"KWT",label:"Kuwait",phone:"965"},{ioc:"CAY",iso2:"KY",iso:"CYM",label:"Cayman Islands",phone:"1-345"},{ioc:"KAZ",iso2:"KZ",iso:"KAZ",label:"Kazakhstan",phone:"7"},{ioc:"LAO",iso2:"LA",iso:"LAO",label:"Lao People's Democratic Republic",phone:"856"},{ioc:"LIB",iso2:"LB",iso:"LBN",label:"Lebanon",phone:"961"},{ioc:"LCA",iso2:"LC",iso:"LCA",label:"Saint Lucia",phone:"1-758"},{ioc:"LIE",iso2:"LI",iso:"LIE",label:"Liechtenstein",phone:"423"},{ioc:"SRI",iso2:"LK",iso:"LKA",label:"Sri Lanka",phone:"94"},{ioc:"LBR",iso2:"LR",iso:"LBR",label:"Liberia",phone:"231"},{ioc:"LES",iso2:"LS",iso:"LSO",label:"Lesotho",phone:"266"},{ioc:"LTU",iso2:"LT",iso:"LTU",label:"Lithuania",phone:"370"},{ioc:"LUX",iso2:"LU",iso:"LUX",label:"Luxembourg",phone:"352"},{ioc:"LAT",iso2:"LV",iso:"LVA",label:"Latvia",phone:"371"},{ioc:"LBA",iso2:"LY",iso:"LBY",label:"Libya",phone:"218"},{ioc:"MAR",iso2:"MA",iso:"MAR",label:"Morocco",phone:"212"},{ioc:"MON",iso2:"MC",iso:"MCO",label:"Monaco",phone:"377"},{ioc:"MDA",iso2:"MD",iso:"MDA",label:"Moldova, Republic of",phone:"373"},{ioc:"MNE",iso2:"ME",iso:"MNE",label:"Montenegro",phone:"382"},{ioc:"",iso2:"MF",iso:"MAF",label:"Saint Martin (French part)",phone:"590"},{ioc:"MAD",iso2:"MG",iso:"MDG",label:"Madagascar",phone:"261"},{ioc:"MSH",iso2:"MH",iso:"MHL",label:"Marshall Islands",phone:"692"},{ioc:"MKD",iso2:"MK",iso:"MKD",label:"Macedonia, the Former Yugoslav Republic of",phone:"389"},{ioc:"MLI",iso2:"ML",iso:"MLI",label:"Mali",phone:"223"},{ioc:"MYA",iso2:"MM",iso:"MMR",label:"Myanmar",phone:"95"},{ioc:"MGL",iso2:"MN",iso:"MNG",label:"Mongolia",phone:"976"},{ioc:"MAC",iso2:"MO",iso:"MAC",label:"Macao",phone:"853"},{ioc:"NMA",iso2:"MP",iso:"NMP",label:"Northern Mariana Islands",phone:"1-670"},{ioc:"MRT",iso2:"MQ",iso:"MTQ",label:"Martinique",phone:"596"},{ioc:"MTN",iso2:"MR",iso:"MRT",label:"Mauritania",phone:"222"},{ioc:"MNT",iso2:"MS",iso:"MSR",label:"Montserrat",phone:"1-664"},{ioc:"MLT",iso2:"MT",iso:"MLT",label:"Malta",phone:"356"},{ioc:"MRI",iso2:"MU",iso:"MUS",label:"Mauritius",phone:"230"},{ioc:"MDV",iso2:"MV",iso:"MDV",label:"Maldives",phone:"960"},{ioc:"MAW",iso2:"MW",iso:"MWI",label:"Malawi",phone:"265"},{ioc:"MEX",iso2:"MX",iso:"MEX",label:"Mexico",phone:"52"},{ioc:"MAS",iso2:"MY",iso:"MYS",label:"Malaysia",phone:"60"},{ioc:"MOZ",iso2:"MZ",iso:"MOZ",label:"Mozambique",phone:"258"},{ioc:"NAM",iso2:"NA",iso:"NAM",label:"Namibia",phone:"264"},{ioc:"NCL",iso2:"NC",iso:"NCL",label:"New Caledonia",phone:"687"},{ioc:"NIG",iso2:"NE",iso:"NER",label:"Niger",phone:"227"},{ioc:"NFI",iso2:"NF",iso:"NFK",label:"Norfolk Island",phone:"672"},{ioc:"NGR",iso2:"NG",iso:"NGA",label:"Nigeria",phone:"234"},{ioc:"NCA",iso2:"NI",iso:"NIC",label:"Nicaragua",phone:"505"},{ioc:"NED",iso2:"NL",iso:"NLD",label:"Netherlands",phone:"31"},{ioc:"NOR",iso2:"NO",iso:"NOR",label:"Norway",phone:"47"},{ioc:"NEP",iso2:"NP",iso:"NPL",label:"Nepal",phone:"977"},{ioc:"NRU",iso2:"NR",iso:"NRU",label:"Nauru",phone:"674"},{ioc:"NIU",iso2:"NU",iso:"NIU",label:"Niue",phone:"683"},{ioc:"NZL",iso2:"NZ",iso:"NZL",label:"New Zealand",phone:"64"},{ioc:"OMA",iso2:"OM",iso:"OMN",label:"Oman",phone:"968"},{ioc:"PAN",iso2:"PA",iso:"PAN",label:"Panama",phone:"507"},{ioc:"PER",iso2:"PE",iso:"PER",label:"Peru",phone:"51"},{ioc:"FPO",iso2:"PF",iso:"PYF",label:"French Polynesia",phone:"689"},{ioc:"PNG",iso2:"PG",iso:"PNG",label:"Papua New Guinea",phone:"675"},{ioc:"PHI",iso2:"PH",iso:"PHL",label:"Philippines",phone:"63"},{ioc:"PAK",iso2:"PK",iso:"PAK",label:"Pakistan",phone:"92"},{ioc:"POL",iso2:"PL",iso:"POL",label:"Poland",phone:"48"},{ioc:"SPM",iso2:"PM",iso:"SPM",label:"Saint Pierre and Miquelon",phone:"508"},{ioc:"",iso2:"PN",iso:"PCN",label:"Pitcairn",phone:"870"},{ioc:"PUR",iso2:"PR",iso:"PRI",label:"Puerto Rico",phone:"1"},{ioc:"PLE",iso2:"PS",iso:"PSE",label:"Palestine, State of",phone:"970"},{ioc:"POR",iso2:"PT",iso:"PRT",label:"Portugal",phone:"351"},{ioc:"PLW",iso2:"PW",iso:"PLW",label:"Palau",phone:"680"},{ioc:"PAR",iso2:"PY",iso:"PRY",label:"Paraguay",phone:"595"},{ioc:"QAT",iso2:"QA",iso:"QAT",label:"Qatar",phone:"974"},{ioc:"REU",iso2:"RE",iso:"REU",label:"Reunion",phone:"262"},{ioc:"ROU",iso2:"RO",iso:"ROU",label:"Romania",phone:"40"},{ioc:"SRB",iso2:"RS",iso:"SRB",label:"Serbia",phone:"381"},{ioc:"RUS",iso2:"RU",iso:"RUS",label:"Russia",phone:"7"},{ioc:"RWA",iso2:"RW",iso:"RWA",label:"Rwanda",phone:"250"},{ioc:"KSA",iso2:"SA",iso:"SAU",label:"Saudi Arabia",phone:"966"},{ioc:"SOL",iso2:"SB",iso:"SLB",label:"Solomon Islands",phone:"677"},{ioc:"SEY",iso2:"SC",iso:"SYC",label:"Seychelles",phone:"248"},{ioc:"SUD",iso2:"SD",iso:"SDN",label:"Sudan",phone:"249"},{ioc:"SWE",iso2:"SE",iso:"SWE",label:"Sweden",phone:"46"},{ioc:"SIN",iso2:"SG",iso:"SGP",label:"Singapore",phone:"65"},{ioc:"HEL",iso2:"SH",iso:"SHN",label:"Saint Helena",phone:"290"},{ioc:"SLO",iso2:"SI",iso:"SVN",label:"Slovenia",phone:"386"},{ioc:"",iso2:"SJ",iso:"SJM",label:"Svalbard and Jan Mayen",phone:"47"},{ioc:"SVK",iso2:"SK",iso:"SVK",label:"Slovakia",phone:"421"},{ioc:"SLE",iso2:"SL",iso:"SLE",label:"Sierra Leone",phone:"232"},{ioc:"SMR",iso2:"SM",iso:"SMR",label:"San Marino",phone:"378"},{ioc:"SEN",iso2:"SN",iso:"SEN",label:"Senegal",phone:"221"},{ioc:"SOM",iso2:"SO",iso:"SOM",label:"Somalia",phone:"252"},{ioc:"SUR",iso2:"SR",iso:"SUR",label:"Suriname",phone:"597"},{ioc:"",iso2:"SS",iso:"SSD",label:"South Sudan",phone:"211"},{ioc:"STP",iso2:"ST",iso:"STP",label:"Sao Tome and Principe",phone:"239"},{ioc:"ESA",iso2:"SV",iso:"SLV",label:"El Salvador",phone:"503"},{ioc:"",iso2:"SX",iso:"SMX",label:"Sint Maarten",phone:"1-721"},{ioc:"SYR",iso2:"SY",iso:"SYR",label:"Syria",phone:"963"},{ioc:"",iso2:"SZ",iso:"SWZ",label:"Swaziland",phone:"268"},{ioc:"TKS",iso2:"TC",iso:"TCA",label:"Turks and Caicos Islands",phone:"1-649"},{ioc:"CHA",iso2:"TD",iso:"TCD",label:"Chad",phone:"235"},{ioc:"",iso2:"TF",iso:"ATF",label:"French Southern Territories",phone:"262"},{ioc:"TOG",iso2:"TG",iso:"TGO",label:"Togo",phone:"228"},{ioc:"THA",iso2:"TH",iso:"THA",label:"Thailand",phone:"66"},{ioc:"TJK",iso2:"TJ",iso:"TJK",label:"Tajikistan",phone:"992"},{ioc:"",iso2:"TK",iso:"TKL",label:"Tokelau",phone:"690"},{ioc:"TLS",iso2:"TL",iso:"TLS",label:"Timor-Leste",phone:"670"},{ioc:"TKM",iso2:"TM",iso:"TKM",label:"Turkmenistan",phone:"993"},{ioc:"TUN",iso2:"TN",iso:"TUN",label:"Tunisia",phone:"216"},{ioc:"TGA",iso2:"TO",iso:"TON",label:"Tonga",phone:"676"},{ioc:"TUR",iso2:"TR",iso:"TUR",label:"Turkey",phone:"90"},{ioc:"TTO",iso2:"TT",iso:"TTO",label:"Trinidad and Tobago",phone:"1-868"},{ioc:"TUV",iso2:"TV",iso:"TUV",label:"Tuvalu",phone:"688"},{ioc:"TPE",iso2:"TW",iso:"TWN",label:"Taiwan",phone:"886"},{ioc:"TAN",iso2:"TZ",iso:"TZA",label:"United Republic of Tanzania",phone:"255"},{ioc:"UKR",iso2:"UA",iso:"UKR",label:"Ukraine",phone:"380"},{ioc:"UGA",iso2:"UG",iso:"UGA",label:"Uganda",phone:"256"},{ioc:"USA",iso2:"US",label:"United States",phone:"1",suggested:!0,iso:"USA"},{ioc:"URU",iso2:"UY",iso:"URY",label:"Uruguay",phone:"598"},{ioc:"UZB",iso2:"UZ",iso:"UZB",label:"Uzbekistan",phone:"998"},{ioc:"",iso2:"VA",iso:"VAT",label:"Holy See (Vatican City State)",phone:"379"},{ioc:"VIN",iso2:"VC",iso:"VCT",label:"Saint Vincent and the Grenadines",phone:"1-784"},{ioc:"VEN",iso2:"VE",iso:"VEN",label:"Venezuela",phone:"58"},{ioc:"IVB",iso2:"VG",iso:"VGB",label:"British Virgin Islands",phone:"1-284"},{ioc:"ISV",iso2:"VI",iso:"VIR",label:"US Virgin Islands",phone:"1-340"},{ioc:"VIE",iso2:"VN",iso:"VNM",label:"Vietnam",phone:"84"},{ioc:"VAN",iso2:"VU",iso:"VUT",label:"Vanuatu",phone:"678"},{ioc:"WAF",iso2:"WF",iso:"WLF",label:"Wallis and Futuna",phone:"681"},{ioc:"SAM",iso2:"WS",iso:"WSM",label:"Samoa",phone:"685"},{ioc:"KOS",iso2:"XK",iso:"KOS",label:"Kosovo",phone:"383"},{ioc:"YEM",iso2:"YE",iso:"YEM",label:"Yemen",phone:"967"},{ioc:"MAY",iso2:"YT",iso:"MYT",label:"Mayotte",phone:"262"},{ioc:"RSA",iso2:"ZA",iso:"ZAF",label:"South Africa",phone:"27"},{ioc:"ZAM",iso2:"ZM",iso:"ZMB",label:"Zambia",phone:"260"},{ioc:"ZIM",iso2:"ZW",iso:"ZWE",label:"Zimbabwe",phone:"263"}];function mh({participant:t,withISO2:e,withIOC:r}){let{person:n,individualParticipants:o}=t,i=[n,o?.map(({person:a})=>a)].flat().filter(Boolean);function s(a){let{nationalityCode:c}=a||{};if(c){let u=Yo.find(({iso:p})=>p===c);r&&u?.ioc&&!a.iocNationalityCode&&(a.iocNationalityCode=u.ioc),e&&u?.iso2&&!a.iso2NationalityCode&&(a.iso2NationalityCode=u.iso2),u?.label&&!a.countryName&&(a.countryName=u.label)}}i.forEach(s)}function CR({participantMap:t,template:e}){let r=Object.values(t);for(let n of r){let o=n.participant;if(o.individualParticipantIds?.length){o.individualParticipants=[];for(let i of o.individualParticipantIds){let s=t[i].participant;o.individualParticipants.push(e?Di({template:e,source:s}):s)}}}}function Mo(t){let{tournamentRecord:e,participantId:r}=t,n=t.tournamentRecords||e&&{[e.tournamentId]:e}||{};for(let o of Object.values(n)){let i=o.participants?.find(s=>s.participantId===r);if(i)return{participant:i,tournamentId:o.tournamentId}}return{error:Jt}}function _n({returnPreviousValues:t,itemSubTypes:e,itemType:r,element:n}){if(!n)return{error:et,info:sm};if(e&&!Array.isArray(e))return{error:G,context:{itemSubTypes:e}};if(!Array.isArray(n.timeItems))return{error:hl};let o=n.timeItems.filter(s=>s?.itemType===r).filter(s=>!e?.length||e.some(a=>s?.itemSubTypes?.includes(a))).sort((s,a)=>{let c=new Date(s.createdAt||void 0).getTime(),u=new Date(a.createdAt||void 0).getTime();return c-u}),i=o.pop();if(i){let s={timeItem:i,...R};return t&&Object.assign(s,{previousItems:o}),s}else return{info:je}}function dh({returnPreviousValues:t,drawDefinition:e,itemSubTypes:r,itemType:n}){if(!e)return{error:Ur};if(!e.timeItems)return{info:je};let{timeItem:o,previousItems:i,info:s}=_n({element:e,returnPreviousValues:t,itemSubTypes:r,itemType:n});return o&&{timeItem:o,previousItems:i}||{info:s}}function ru({returnPreviousValues:t,itemSubTypes:e,itemType:r,event:n}){if(!n)return{error:St};if(!n.timeItems)return{info:je};let{timeItem:o,previousItems:i,info:s}=_n({returnPreviousValues:t,element:n,itemSubTypes:e,itemType:r});return o&&{timeItem:o,previousItems:i}||{info:s}}function nu({returnPreviousValues:t,tournamentRecord:e,itemSubTypes:r,itemType:n}){if(!e)return{error:j};if(!e.timeItems)return{info:je};let{timeItem:o,previousItems:i,info:s}=_n({element:e,returnPreviousValues:t,itemSubTypes:r,itemType:n});return o&&{timeItem:o,previousItems:i}||{info:s}}function lh({returnPreviousValues:t,tournamentRecord:e,participantId:r,itemSubTypes:n,itemType:o}){if(!e)return{error:j};if(!r)return{error:te};let i=Mo({tournamentRecord:e,participantId:r});if(i.error)return i;let{participant:s}=i;if(!s?.timeItems)return{info:je};let{timeItem:a,previousItems:c,info:u}=_n({element:i.participant,returnPreviousValues:t,itemSubTypes:n,itemType:o});return a&&{timeItem:a,previousItems:c}||{info:u}}var BL={[hr]:"groupParticipantIds",[pt]:"pairParticipantIds",[Lt]:"teamParticipantIds"},HL={[hr]:"groups",[Lt]:"teams"};function fh({withIndividualParticipants:t,convertExtensions:e,tournamentRecord:r,withSignInStatus:n,withScaleValues:o,internalUse:i,withISO2:s,withIOC:a}){let c={};for(let u of r.participants??[]){let p=u?.participantId;p&&YL({participantMap:c,participantId:p})}for(let u of r.participants??[]){let p=J(u,e,i),{participantId:m,individualParticipantIds:d,participantType:l}=p;if(Object.assign(c[m].participant,p),d&&jL({individualParticipantIds:d,participantCopy:p,participantMap:c,participantType:l,participantId:m}),n&&(c[m].participant.signedIn=WL(p)),o){let{ratings:f,rankings:g,seedings:I}=oa({participant:p});c[m].participant.seedings=I,c[m].participant.rankings=g,c[m].participant.ratings=f}(a||s)&&mh({participant:c[m].participant,withISO2:s,withIOC:a})}if(t){let u=Ct(t)?t:void 0;CR({participantMap:c,template:u})}return{participantMap:c}}function WL(t){let{timeItem:e}=_n({itemType:Ja,element:t});return e?.itemValue===Kc}function jL({individualParticipantIds:t,participantCopy:e,participantMap:r,participantType:n,participantId:o}){for(let i of t){let s=r[i].participant;if(s[BL[n]].push(o),[Lt,hr].includes(n)){let{participantRoleResponsibilities:a,participantOtherName:c,participantName:u,participantId:p,teamId:m}=e,d=HL[n];s[d].push({participantRoleResponsibilities:a,participantOtherName:c,participantName:u,participantId:p,teamId:m})}if(n===pt){let a=t.find(c=>c!==i);r[i].pairIdMap[o]=a,r[i].pairIdMap[a]=o}}}function YL({participantMap:t,participantId:e}){if(t[e])return;let r={walkoverWins:0,defaultWins:0,walkovers:0,defaults:0,losses:0,wins:0};t[e]={structureParticipation:{},potentialMatchUps:{},scheduleConflicts:{},scheduleItems:[],participant:{groupParticipantIds:[],pairParticipantIds:[],teamParticipantIds:[],seedings:{},rankings:{},ratings:{},groups:[],teams:[]},statistics:{},opponents:{},pairIdMap:{},matchUps:{},events:{},draws:{},counters:{[ee]:{...r},[jt]:{...r},[Lt]:{...r},...r}}}function pi({participantsProfile:t,useParticipantMap:e,tournamentRecord:r,contextProfile:n,inContext:o}){if(e)return{participantMap:fh({...t,...n,tournamentRecord:r})?.participantMap};let i=J(r.participants,!1,!0)||[];(t?.withIOC||t?.withISO2)&&i.forEach(a=>mh({participant:a,...t}));let s;if((o||t?.withGroupings)&&i?.length&&({participantsWithGroupings:i,groupInfo:s}=Em({participantsProfile:t,deepCopy:!1,participants:i})),t?.withScaleValues&&i?.length)for(let a of i){let{ratings:c,rankings:u}=oa({participant:a});a.rankings=u,a.ratings=c}return{participants:i,groupInfo:s}}function ro(t){let{participants:e=[],contextContent:r,participantMap:n}=t,{scheduleVisibilityFilters:o,tournamentAppliedPolicies:i,participantsProfile:s,afterRecoveryTimes:a,policyDefinitions:c,useParticipantMap:u,tournamentRecord:p,contextFilters:m,contextProfile:d,matchUpFilters:l,nextMatchUps:f,inContext:g,context:I,event:h}=t;if(!h)return{error:St};let{eventId:S,eventName:T,endDate:A,category:P,gender:y,matchUpFormat:E}=h,U={...I,...rt({indoorOutDoor:h.indoorOutdoor??p?.indoorOutdoor,surfaceCategory:h.surfaceCategory??p?.surfaceCategory,endDate:h.endDate??p?.endDate,tournamentId:p?.tournamentId,matchUpFormat:E,eventName:T,category:P,gender:y,eventId:S})};A&&(U.endDate=A),d&&!r&&(r=bn({policyDefinitions:c,tournamentRecord:p,contextProfile:d,event:h}));let M;if(!e?.length&&!n&&p){let O=pi({participantsProfile:s,useParticipantMap:u,policyDefinitions:c,tournamentRecord:p,contextProfile:d,inContext:g});n=O.participantMap,e=O.participants??[],M=O.groupInfo}let N=h.drawDefinitions??[],C=la({tournamentRecord:p,event:h}).scheduleTiming;return{matchUps:N.flatMap(O=>{let{matchUps:b}=re({tournamentParticipants:e,tournamentAppliedPolicies:i,scheduleVisibilityFilters:o,context:U,participantsProfile:s,afterRecoveryTimes:a,policyDefinitions:c,tournamentRecord:p,contextFilters:m,contextProfile:d,drawDefinition:O,contextContent:r,matchUpFilters:l,participantMap:n,scheduleTiming:C,nextMatchUps:f,inContext:g,event:h});return b??[]}),groupInfo:M}}function pe(t){if(!t?.tournamentRecord)return{error:j};let{participantMap:e,participants:r}=t,{scheduleVisibilityFilters:n,participantsProfile:o,afterRecoveryTimes:i,useParticipantMap:s,policyDefinitions:a,tournamentRecord:c,inContext:u=!0,contextProfile:p,matchUpFilters:m,contextFilters:d,nextMatchUps:l,context:f}=t,g=t.tournamentId??c.tournamentId,I=c?.events??[];r||({participants:r,participantMap:e}=pi({participantsProfile:o,useParticipantMap:s,policyDefinitions:a,tournamentRecord:c,contextProfile:p,inContext:u}));let{appliedPolicies:h}=yt({tournamentRecord:c}),S={...f,tournamentId:g,indoorOutDoor:c.indoorOutdoor,surfaceCategory:c.surfaceCategory,endDate:c.endDate},T=bn({policyDefinitions:a,tournamentRecord:c,contextProfile:p});return{matchUps:I.flatMap(P=>(S.eventDrawsCount=P.drawDefinitions?.length??0,ro({context:S,scheduleVisibilityFilters:n,tournamentAppliedPolicies:h,participantsProfile:o,afterRecoveryTimes:i,policyDefinitions:a,tournamentRecord:c,contextContent:T,contextFilters:d,contextProfile:p,matchUpFilters:m,participantMap:e,nextMatchUps:l,participants:r,inContext:u,event:P}).matchUps??[])).concat(...c.matchUps??[])}}function nn({scheduleVisibilityFilters:t,afterRecoveryTimes:e,participantsProfile:r,tournamentRecords:n,policyDefinitions:o,matchUpFilters:i,contextFilters:s,nextMatchUps:a,inContext:c}){return typeof n!="object"||!Object.keys(n).length?{error:wt}:{matchUps:Object.keys(n).map(m=>{let d=n[m];return pe({scheduleVisibilityFilters:t,afterRecoveryTimes:e,participantsProfile:r,policyDefinitions:o,tournamentRecord:d,matchUpFilters:i,contextFilters:s,nextMatchUps:a,inContext:c}).matchUps??[]}).flat()}}function mi(t,e){return qL(t,e)||(t?.stageSequence||0)-(e?.stageSequence||0)||t?.roundNumber&&e.roundNumber&&t?.roundNumber-e?.roundNumber||(t?.roundPosition??0)-(e?.roundPosition??0)}function qL(t,e){return(Ds[t?.stage]||0)-(Ds[e?.stage]||0)}function ar(t){let{participants:e,participantMap:r,contextContent:n}=t,{scheduleVisibilityFilters:o,tournamentAppliedPolicies:i,participantsProfile:s,afterRecoveryTimes:a,policyDefinitions:c,useParticipantMap:u,tournamentRecord:p,matchUpFilters:m,contextFilters:d,contextProfile:l,drawDefinition:f,nextMatchUps:g,inContext:I,context:h,event:S}=t,{eventId:T,eventName:A,eventType:P,category:y,gender:E,matchUpFormat:U}=S??{},M={...h,eventId:T,eventType:P,eventName:A,category:y,gender:E,matchUpFormat:U,indoorOutDoor:S?.indoorOutdoor??p?.indoorOutdoor,surfaceCategory:S?.surfaceCategory??p?.surfaceCategory,endDate:S?.endDate},N;return!e?.length&&!r&&p&&({participants:e=[],participantMap:r,groupInfo:N}=pi({participantsProfile:s,useParticipantMap:u,policyDefinitions:c,tournamentRecord:p,contextProfile:l,inContext:I})),l&&!n&&(n=bn({policyDefinitions:c,tournamentRecord:p,contextProfile:l,drawDefinition:f,event:S})),{...re({context:M,tournamentAppliedPolicies:i,scheduleVisibilityFilters:o,tournamentParticipants:e,participantsProfile:s,afterRecoveryTimes:a,policyDefinitions:c,tournamentRecord:p,drawDefinition:f,contextContent:n,contextFilters:d,contextProfile:l,matchUpFilters:m,participantMap:r,nextMatchUps:g,inContext:I,event:S}),groupInfo:N}}function xr(t){let e=jr(t),r=t.matchUps??[],n=t.drawIds??[],{includeParticipantDependencies:o,tournamentRecord:i,drawDefinition:s}=t;if(!Array.isArray(r))return{error:wn};if(!Array.isArray(n))return{error:Ur};let a=t.matchUpIds?.length?t.matchUpIds:r.map(T=>T.matchUpId);if(!Array.isArray(a))return{error:ta};let c={},u={},p={},m={};i&&!Object.keys(e).length&&(e={[i.tournamentId]:i});let d=Object.values(e),f=d.reduce((T,A)=>T.concat(A.events??[]).map(P=>(P.drawDefinitions||[]).map(y=>y.links||[])).flat(1/0),[]).filter(({linkType:T})=>T===kn),g=r;if(f.length){g=nn({nextMatchUps:!0,tournamentRecords:e}).matchUps;let T=f.reduce((A,P)=>{let y=P.source?.structureId,E=P.target?.structureId;return y&&E&&(p[E]=y),y&&!A.includes(y)&&A.push(y),A},[]);for(let A of T)c[A]=[];for(let A of g??[]){let P=A.containerStructureId||A.structureId;T.includes(P)&&c[P].push(A.matchUpId)}}let I=T=>{u[T]||(u[T]={dependentMatchUpIds:[],participantIds:[],matchUpIds:[],sources:[]},m[T]=[])},h=(T,A)=>{u[T].matchUpIds.forEach(y=>{u[A].matchUpIds.push(y)}),u[A].matchUpIds.push(T),u[T].dependentMatchUpIds.push(A),o&&u[T].participantIds.forEach(y=>u[A].participantIds.push(y))},S=T=>{let A=Object.keys(c).length;for(let P of T||[]){let{matchUpId:y,winnerMatchUpId:E,loserMatchUpId:U}=P;if(!a.length||a.includes(y)){if(I(y),o){let{individualParticipantIds:C}=$c(P);u[y].participantIds=C}E&&(I(E),h(y,E),m[E].push(y)),U&&(I(U),h(y,U),m[U].push(y)),u[y].sources.push(m[y]);let M=m[y].map(C=>u[C].sources[0]).flat(),N=m[y].map(C=>u[C].sources[1]).flat();if(u[y].sources.push(M,N),A){let C=P.containerStructureId||P.structureId,D=p[C];if(c[D])for(let O of c[D])I(O),h(O,y),m[O].push(y)}}}};if(s)rs({drawDefinition:s}),g?.length||(g=ar({drawDefinition:s}).matchUps),S(g);else{if(g?.length||(g=nn({nextMatchUps:!0,tournamentRecords:e}).matchUps),!n.length){let T=d?.length?d.map(({events:A=[]})=>A.map(({drawDefinitions:P=[]})=>P.map(({drawId:y})=>y))).flat(1/0):[];T&&(n=T)}for(let T of n){let A=g?.filter(y=>y.drawId===T).sort(mi);if(!A?.find(({roundPosition:y})=>!y)){let y=A?.find(({tournamentId:U})=>U),{drawDefinition:E}=nr({tournamentRecord:e[y?.tournamentId],drawId:T});E&&rs({drawDefinition:E})}S(A)}}return{positionDependencies:c,matchUpDependencies:u,sourceMatchUpIds:m,matchUps:g,...R}}function he(t){let e=t?.matchUp,r=t?.score||e?.score,n=r?.sets?.[0],{side1Score:o,side2Score:i,side1TiebreakScore:s,side2TiebreakScore:a,side1PointScore:c,side2PointScore:u}=n||{},p=o||i||s||a||c||u;return!!(r?.sets?.length>1||p)}function ha({matchUpStatus:t}){return xI.includes(t)}function RR({matchUpStatus:t}){return fm.includes(t)}function Df({matchUpStatus:t}){return wI.includes(t)}function Mf({matchUpStatus:t,winningSide:e,tieMatchUps:r,sides:n,score:o}){let i=n?.find(({participantId:c})=>c),s=r?.filter(Mf)?.length;return he({score:o})||s||e&&i||t&&RR({matchUpStatus:t})&&![bt,Ot,Sn].includes(t)}function Sa(t){let{drawDefinition:e,findContainer:r,structureId:n,event:o}=t,i=t.structure,s={isCollectionMatchUp:!1},{containedStructures:a}=zi({drawDefinition:e}),c=n?a[n]||[]:[];if(!i){let E=st({drawDefinition:e,structureId:n});if(E.error)return E;i=r?E.containingStructure??E.structure:E.structure}if(Br({drawDefinition:e,structure:i}))return{structure:i,isAdHoc:!0,error:Ss};let{matchUps:u}=re({inContext:!0,matchUpFilters:s,drawDefinition:e,event:o}),p=u?.filter(E=>E.structureId===n||c.includes(E.structureId)),{matchUpDependencies:m}=xr({drawIds:[e.drawId],matchUps:u,drawDefinition:e}),d=[],l=[],f={},g=[];for(let E of u??[]){if(E.structureId===n||c.includes(E.structureId)){l.push(...E.drawPositions??[]);let U=E.roundNumber;for(let M of(E.drawPositions??[]).filter(Boolean))(!f[M]||U&&f[M]>U)&&(f[M]=U)}Mf(E)&&(g.push(E),d.push(E.matchUpId,...m?.[E?.matchUpId]?.matchUpIds||[]))}let I=mt(l.filter(Boolean)).sort(oe),h=mt(d),S=mt(p?.map(({matchUpId:E,drawPositions:U})=>h.includes(E)?U:[]).flat().filter(Boolean)).sort(oe),{positionAssignments:T}=Dt({drawDefinition:e,structure:i}),A=T?.filter(E=>E.bye).map(E=>E.drawPosition),P=T?.filter(E=>E.qualifier).map(E=>E.drawPosition),y=I?.filter(E=>!S.includes(E))||[];return{allDrawPositions:I,inContextStructureMatchUps:p,drawPositionInitialRounds:f,activeDependentMatchUpIds:h,qualifyingDrawPositions:P,inactiveDrawPositions:y,positionAssignments:T,activeDrawPositions:S,byeDrawPositions:A,activeMatchUps:g,structure:i}}function ns({drawPosition:t,matchUps:e=[]}){return{initialRoundNumber:e.filter(({drawPositions:n})=>t&&n?.includes(t)).map(({roundNumber:n})=>n).sort(oe)[0]}}var Ta={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",red:"\x1B[31m",brightred:"\x1B[91m",green:"\x1B[32m",brightgreen:"\x1B[92m",yellow:"\x1B[33m",brightyellow:"\x1B[93m",blue:"\x1B[34m",brightblue:"\x1B[94m",lightblue:"\x1B[105m",magenta:"\x1B[35m",brightmagenta:"\x1B[95m",cyan:"\x1B[36m",brightcyan:"\x1B[96m",white:"\x1B[37m",brightwhite:"\x1B[97m"};var gh=[];function vn(t,e){typeof t=="string"&&(t={method:t}),(e||Tr())&&gh.push(t)}function $L(t){let e=gh.slice();return t&&(gh.length=0),e}function bR(t){let r=$L(t).map(n=>{let{color:o,keyColors:i,method:s,newline:a}=n,c=Object.keys(Ta).includes(o)?Ta[o]:Ta.cyan,p=Object.keys(n).filter(d=>!["color","keyColors","method","newline"].includes(d)).map(d=>{let l=i&&Object.keys(i).includes(d)&&Ta[i[d]]?Ta[i[d]]:Ta.brightwhite;return`${Ta.white}${d}: ${l}${n[d]}`}).join(", "),m=s?.length<15?" ":" ";return[a?`
2
+ `:"",c,s,m,Ta.white,p,Ta.reset,`
3
+ `].join("")});r?.length&&console.log(...r)}function OR(){gh.length=0}function yr({provisionalPositioning:t,isPositionAction:e,tournamentRecord:r,drawDefinition:n,drawPosition:o,matchUpsMap:i,structureId:s,structure:a,event:c}){if(!n)return{error:z};if(a||({structure:a}=st({drawDefinition:n,structureId:s})),!a)return{error:_t};s||({structureId:s}=a);let u="assignDrawPositionBye";vn({method:u,color:"cyan",drawPosition:o}),i||(i=be({drawDefinition:n}));let{positionAssignments:p}=Dt({structure:a}),{activeDrawPositions:m}=Sa({drawDefinition:n,structureId:s});if(p?.find(C=>C.drawPosition===o)?.bye)return{...R};if(m?.includes(o))return{error:Ou};let f=p?.find(C=>C.drawPosition===o);if(!f)return{error:Ss};let{filled:g,containsBye:I,assignedParticipantId:h}=KL(f);if(I)return{...R};if(g&&!I)return v({result:{error:La},stack:u});let S=re({inContext:!0,drawDefinition:n,matchUpsMap:i}).matchUps??[],T={isCollectionMatchUp:!1},{matchUps:A}=Pt({provisionalPositioning:t,drawDefinition:n,matchUpFilters:T,matchUpsMap:i,structure:a});if(p?.forEach(C=>{C.drawPosition===o&&(C.bye=!0)}),a.structureType===we)return zL({tournamentRecord:r,drawDefinition:n,drawPosition:o,matchUps:A}),fo({tournamentId:r?.tournamentId,drawDefinition:n,structure:a,event:c}),_R({assignedParticipantId:h,isPositionAction:e,drawDefinition:n,drawPosition:o,structureId:s,stack:u});let{roundProfile:P,roundMatchUps:y}=Xe({matchUps:A}),U=(P&&Object.keys(P).map(C=>parseInt(C)).reverse())?.find(C=>P?.[C].drawPositions?.includes(o)),M=U?y?.[U].find(({drawPositions:C})=>C?.includes(o)):void 0;M&&vR({tournamentRecord:r,drawDefinition:n,matchUp:M,event:c});let N=M?.drawPositions?.find(C=>C!==o);if(M&&N){let C=Ih({sourceDrawPositions:M.drawPositions,matchUpId:M.matchUpId,inContextDrawMatchUps:S,drawPositionToAdvance:N,tournamentRecord:r,drawDefinition:n,matchUpsMap:i});if(C.error)return C}return fo({tournamentId:r?.tournamentId,drawDefinition:n,structure:a,event:c}),_R({assignedParticipantId:h,isPositionAction:e,drawDefinition:n,drawPosition:o,structureId:s,stack:u})}function _R({assignedParticipantId:t,isPositionAction:e,drawDefinition:r,drawPosition:n,structureId:o,stack:i}){return e&&qc({drawDefinition:r,positionAction:{removedParticipantId:t,drawPosition:n,structureId:o,name:i}}),v({result:{...R},stack:i})}function KL(t){let e=t.bye,r=t.qualifier,n=t.participantId;return{containsBye:e,containsQualifier:r,assignedParticipantId:n,filled:e||r||n}}function vR({tournamentRecord:t,drawDefinition:e,eventId:r,matchUp:n,event:o}){Object.assign(n,{matchUpStatus:Ut,score:void 0,winningSide:void 0}),ht({tournamentId:t?.tournamentId,eventId:r??o?.eventId,context:"setMatchUpStatusBye",drawDefinition:e,matchUp:n})}function zL({tournamentRecord:t,drawDefinition:e,drawPosition:r,matchUps:n,event:o}){n.forEach(i=>{i.drawPositions?.includes(r)&&vR({eventId:o?.eventId,tournamentRecord:t,drawDefinition:e,matchUp:i})})}function Ih({drawPositionToAdvance:t,inContextDrawMatchUps:e,sourceDrawPositions:r,tournamentRecord:n,drawDefinition:o,matchUpsMap:i,matchUpId:s,event:a}){vn({method:"advanceDrawPosition",color:"cyan",drawPositionToAdvance:t});let u=i.drawMatchUps.find(P=>P.matchUpId===s),m=e.find(P=>P.matchUpId===s)?.structureId,{structure:d}=st({drawDefinition:o,structureId:m}),{positionAssignments:l}=Dt({structure:d}),f=l?.filter(P=>P.bye).map(P=>P.drawPosition),g=u?.drawPositions?.find(P=>P!==t),I=g&&f?.includes(g),{targetLinks:{loserTargetLink:h},targetMatchUps:{loserMatchUp:S,winnerMatchUp:T,loserTargetDrawPosition:A}}=Je({inContextDrawMatchUps:e,drawDefinition:o,matchUpId:s});if(T&&T.structureId===d?.structureId&&QL({drawPositionToAdvance:t,inContextDrawMatchUps:e,sourceDrawPositions:r,tournamentRecord:n,drawDefinition:o,winnerMatchUp:T,matchUpsMap:i,event:a}),S&&I&&S.structureId!==d?.structureId){let{roundNumber:P}=S;if(P===1){let y=yr({structureId:h.target.structureId,drawPosition:A,tournamentRecord:n,drawDefinition:o,event:a});if(y.error)return y}else xR({loserTargetDrawPosition:A,tournamentRecord:n,loserTargetLink:h,drawDefinition:o,loserMatchUp:S,matchUpsMap:i,event:a})}return{...R}}function QL({drawPositionToAdvance:t,inContextDrawMatchUps:e,sourceDrawPositions:r,tournamentRecord:n,drawDefinition:o,winnerMatchUp:i,matchUpsMap:s,event:a}){let c="advanceWinner",u=s.drawMatchUps.find(w=>w.matchUpId===i.matchUpId),m=e.find(w=>w.matchUpId===i.matchUpId)?.structureId,{structure:d}=st({drawDefinition:o,structureId:m}),{positionAssignments:l}=Dt({structure:d}),g=l?.find(({drawPosition:w})=>w===t)?.bye,I=u.drawPositions?.filter(Boolean),h=l?.filter(w=>I?.includes(w.drawPosition)),S=l?.find(({drawPosition:w})=>w===t),T=r?.find(w=>w!==t),P=(T&&h?.find(({drawPosition:w})=>w===T))?.bye,y=g&&P;if(y&&console.log({isByeAdvancedBye:y}),I?.length>1&&g&&!P)return v({result:{error:La},stack:c});let E=I?.find(w=>w!==t),U=y,M=[...(u.drawPositions||[]).filter(Boolean),void 0,void 0].slice(0,2),N=M.map(w=>!w&&!U||w===t?(U=!0,t):w).sort(oe);if(!U)return console.log("@@@@@@@",{advancingAssignmentIsBye:S,drawPositionToAdvance:t,existingAssignments:h}),v({result:{error:La},stack:c});let C=l?.find(({drawPosition:w})=>w===E)?.bye,D=l?.find(({drawPosition:w})=>w===t)?.bye;Object.assign(u,{matchUpStatus:D||C?Ut:Kt,score:void 0,winningSide:void 0,drawPositions:N});let b=u.drawPositions.find(w=>!M.includes(w));vn({method:c,color:"brightyellow",changedDrawPosition:b,pairedDrawPositionIsBye:C,drawPositionIsBye:D}),ht({tournamentId:n?.tournamentId,matchUp:u,eventId:a?.eventId,context:c,drawDefinition:o});let{targetLinks:{loserTargetLink:_},targetMatchUps:{loserMatchUp:L,loserTargetDrawPosition:F}}=Je({matchUpId:i.matchUpId,inContextDrawMatchUps:e,drawDefinition:o});if(C||D){let w=C?t:E;if(w)Ih({drawPositionToAdvance:w,matchUpId:i.matchUpId,inContextDrawMatchUps:e,tournamentRecord:n,drawDefinition:o,matchUpsMap:s});else if(D&&_&&L)if(L.feedRound)xR({loserTargetDrawPosition:F,tournamentRecord:n,loserTargetLink:_,drawDefinition:o,loserMatchUp:L,matchUpsMap:s});else{let H=1-i.roundPosition%2,V=L.drawPositions[H],W=yr({structureId:_.target.structureId,drawPosition:V,tournamentRecord:n,drawDefinition:o,event:a});if(W.error)return W}}}function xR({loserTargetDrawPosition:t,tournamentRecord:e,loserTargetLink:r,drawDefinition:n,loserMatchUp:o,matchUpsMap:i,event:s}){let{roundNumber:a}=o;vn({method:"assignFedDrawPositionBye",color:"cyan",loserTargetDrawPosition:t});let p=(i?.mappedMatchUps||{})[o.structureId].matchUps,{initialRoundNumber:m}=ns({drawPosition:t,matchUps:p});if(m===a){let d=yr({structureId:r.target.structureId,drawPosition:t,tournamentRecord:e,drawDefinition:n,event:s});if(d.error)return d}}function hh({positionAssignments:t,tournamentRecord:e,drawDefinition:r,matchUpsMap:n,structure:o,event:i}){let{matchUps:s}=Pt({drawDefinition:r,matchUpsMap:n,structure:o,event:i});s.forEach(a=>{let u=t.filter(({drawPosition:p})=>a.drawPositions?.includes(p)).filter(p=>p.bye).length;a.winningSide||(Object.assign(a,{matchUpStatus:u?Ut:Kt}),ht({tournamentId:e?.tournamentId,context:"modifyRoundRobinMatchUpsStatus",eventId:i?.eventId,drawDefinition:r,matchUp:a}))})}function oc(t){let{inContextDrawMatchUps:e,participantId:r,drawPosition:n}=t,{tournamentRecord:o,drawDefinition:i,structureId:s,matchUpsMap:a,event:c}=t,{structure:u}=st({drawDefinition:i,structureId:s}),m=(de({drawDefinition:i,structure:u}).positionAssignments||[]).find(g=>r&&g.participantId===r||n&&g.drawPosition===n);if(m&&r&&!n&&(n=m?.drawPosition),!n)return{error:Ts};r||(r=m?.participantId);let{activeDrawPositions:d}=Sa({drawDefinition:i,structureId:s});return d.includes(n)?{error:Ou}:(e||({matchUps:e}=re({inContext:!0,drawDefinition:i,matchUpsMap:a})),YE({inContextDrawMatchUps:e,tournamentRecord:o,drawDefinition:i,structureId:s,drawPosition:n,matchUpsMap:a,event:c}).drawPositionCleared?(fo({tournamentId:o?.tournamentId,drawDefinition:i,structure:u,event:c}),{...R,participantId:r}):{error:GA})}function YE({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,matchUpsMap:o,structureId:i,event:s}){let{structure:a}=st({drawDefinition:r,structureId:i});if(!a)return{error:_t};let c=de({drawDefinition:r,structure:a}).positionAssignments||[],u=c.some(T=>{if(T.drawPosition===n)return delete T.participantId,delete T.qualifier,delete T.bye,!0});if(a.structureType===we)return hh({positionAssignments:c,tournamentRecord:e,drawDefinition:r,matchUpsMap:o,structure:a}),{drawPositionCleared:u,...R};let p={isCollectionMatchUp:!1},{matchUps:m}=Pt({drawDefinition:r,matchUpFilters:p,matchUpsMap:o,structure:a,event:s}),{roundProfile:d,roundMatchUps:l}=Xe({matchUps:m}),g=(d&&Object.keys(d))?.map(T=>ct(T)),I=n,S=g?.map(T=>{let P=d?.[T]?.pairedDrawPositions?.find(b=>b.includes(I)),y=P?.find(b=>b!==I),E=c.find(b=>b.drawPosition===y),U=d?.[T+1],M=E?.bye,N=U?.pairedDrawPositions?.find(b=>b.includes(y)),C=M&&N&&U&&U.drawPositions?.includes(y),O=P&&{pairedDrawPositionByeAdvancedPair:!C&&N,pairedDrawPosition:y,targetDrawPosition:I,relevantPair:P,roundNumber:T};return C&&(I=y),O}).filter(T=>T?.targetDrawPosition)?.reduce((T,A)=>{let{roundNumber:P,relevantPair:y,targetDrawPosition:E,pairedDrawPosition:U,pairedDrawPositionByeAdvancedPair:M}=A,N={roundNumber:P,targetDrawPosition:E,relevantPair:y},C=M&&{roundNumber:P+1,targetDrawPosition:U,relevantPair:M,subsequentRoundRemoval:!0},D=[N,C].filter(Boolean);return T.concat(...D)},[]);return S?.forEach(({roundNumber:T,targetDrawPosition:A,relevantPair:P})=>{let y=l?.[T].find(E=>ve(E.drawPositions?.filter(Boolean),P.filter(Boolean)));y&&(XL({inContextDrawMatchUps:t,targetDrawPosition:A,tournamentRecord:e,drawDefinition:r,structureId:i,roundNumber:T,matchUpsMap:o}),wR({inContextDrawMatchUps:t,positionAssignments:c,tournamentRecord:e,drawDefinition:r,targetMatchUp:y,drawPosition:n,matchUpsMap:o,structure:a,event:s}))}),{tasks:S,drawPositionCleared:u,positionAssignments:c}}function XL({inContextDrawMatchUps:t,targetDrawPosition:e,tournamentRecord:r,drawDefinition:n,matchUpsMap:o,roundNumber:i,structureId:s}){let{structure:a}=st({drawDefinition:n,structureId:s});if(!a)return{error:_t};if(a.structureType===we)return;o=o||be({drawDefinition:n});let u=(o?.mappedMatchUps||{})[s].matchUps,{initialRoundNumber:p}=ns({drawPosition:e,matchUps:u}),m=u?.filter(l=>l.roundNumber>=i&&l.roundNumber!==p&&l.drawPositions?.includes(e)),d=Dt({drawDefinition:n,structureId:s}).positionAssignments??[];return m?.forEach(l=>wR({drawPosition:e,targetMatchUp:l,inContextDrawMatchUps:t,positionAssignments:d,tournamentRecord:r,drawDefinition:n,matchUpsMap:o,structure:a})),{...R}}function wR({inContextDrawMatchUps:t,positionAssignments:e,tournamentRecord:r,drawDefinition:n,targetMatchUp:o,drawPosition:i,matchUpsMap:s,structure:a,event:c}){let u="removeDrawPosition",p=o.drawPositions?.slice(),m=o.matchUpStatus,d=o.winningSide;s=s??be({drawDefinition:n});let f=s.mappedMatchUps[a.structureId].matchUps,{initialRoundNumber:g}=ns({drawPosition:i,matchUps:f});if(o.roundNumber&&g&&o.roundNumber>g){let N=(o.drawPositions??[]).map(C=>C===i?void 0:C);o.drawPositions=N}if(o.matchUpType===Bt){let D=(t?.find(O=>O.matchUpId===o.matchUpId)?.sides??[]).reduce((O,b,_)=>b.drawPosition===i?_:O,void 0);D!==void 0&&o.sides?.[D]?.lineUp&&(delete o.sides?.[D].lineUp,ht({tournamentId:r?.tournamentId,context:`${u}-TEAM`,eventId:c?.eventId,matchUp:o,drawDefinition:n}))}let I=Je({matchUpId:o.matchUpId,inContextDrawMatchUps:t,drawDefinition:n}),{targetLinks:{winnerTargetLink:h},targetMatchUps:{loserMatchUp:S,winnerMatchUp:T,loserMatchUpDrawPositionIndex:A}}=I,y=e.filter(({drawPosition:N})=>o.drawPositions?.includes(N)).filter(N=>N.bye).length,E=y&&Ut||o.matchUpStatus&&[bt,Ot].includes(o.matchUpStatus)&&o.matcHUpStatus||o.drawPositions?.length===2&&Kt||void 0;o.matchUpStatus=E,o.matchUpStatus&&[Ot,bt].includes(o.matchUpStatus)&&(o.winningSide=void 0);let U=p?.find(N=>!o.drawPositions?.includes(N));if(p?.includes(i)&&m===o.matchUpStatus&&d===o.winningSide||(U&&vn({method:u,color:"brightyellow",removedDrawPosition:U}),ht({tournamentId:r?.tournamentId,eventId:c?.eventId,matchUp:o,context:`${u}-${i}`,drawDefinition:n})),S&&S.structureId!==I.matchUp.structureId&&!y){let{drawPositions:N,roundNumber:C}=S;if(C===1){let D=N[A];YE({structureId:S.structureId,drawPosition:D,inContextDrawMatchUps:t,tournamentRecord:r,drawDefinition:n,matchUpsMap:s})}else{let D=Math.min(...N.filter(Boolean)),O=JL({loserMatchUpDrawPosition:D,inContextDrawMatchUps:t,tournamentRecord:r,drawDefinition:n,loserMatchUp:S,matchUpsMap:s,event:c});if(O.error)return v({result:O,stack:u});let _=(s?.mappedMatchUps||{})[S.structureId].matchUps,{initialRoundNumber:L}=ns({drawPosition:D,matchUps:_});L===1&&(vn({method:u,color:"brightyellow",loserMatchUpDrawPosition:D}),YE({structureId:S.structureId,drawPosition:D,inContextDrawMatchUps:t,tournamentRecord:r,drawDefinition:n,matchUpsMap:s}))}}return T&&T.structureId!==I.matchUp.structureId&&(h.target.feedProfile,Wr),{...R}}function JL({loserMatchUpDrawPosition:t,inContextDrawMatchUps:e,tournamentRecord:r,drawDefinition:n,loserMatchUp:o,matchUpsMap:i,event:s}){let{structure:a}=st({structureId:o.structureId,drawDefinition:n}),{positionAssignments:c}=Dt({structure:a});if(c?.find(p=>p.drawPosition===t)?.bye){let p=oc({drawPosition:t,structureId:o.structureId,inContextDrawMatchUps:e,tournamentRecord:r,drawDefinition:n,matchUpsMap:i,event:s});if(p.error)return p}return{...R}}function di({drawDefinition:t,stages:e}){if(!t)return{error:z};let r=(t?.structures??[]).filter(o=>!e?.length||o.stage&&e.includes(o.stage)),n=mt(r.map(o=>{let{positionAssignments:i}=Dt({structure:o});return i?i.map(ft):[]}).flat().filter(Boolean));return{...R,assignedParticipantIds:n}}function xn(t){let e=(t?.entries??[]).filter(Boolean).reduce((n,o)=>{let{entryStage:i,entryStatus:s}=o,a=`_${i||tt}${s||""}`;return n[a]||(n[a]=[]),n[a].push(o),n},{}),r=n=>isNaN(n)?1/0:n;return Object.keys(e).map(n=>e[n].sort((o,i)=>r(o.entryPosition)-r(i.entryPosition)).map((o,i)=>{let s=i+1;return{...o,entryPosition:s}})).flat()}function Ls(t){return[oi,_r].includes(t)}function Lm({autoEntryPositions:t=!0,ignoreAssignment:e,tournamentRecord:r,drawDefinition:n,participantIds:o,entryStatus:i,entryStage:s,extension:a,eventSync:c,drawId:u,stage:p,event:m}){if(!o||!Array.isArray(o))return{error:sn,method:"modifyEntriesStatus",participantIds:o};if(!n&&!m)return{error:St};if(i&&!vE.includes(i))return{error:dl};if(s&&!gm.includes(s))return{error:Si};let d="modifyEntriesStatus",l=[];if(!i&&!a)return v({result:{error:et},info:"Missing entryStatus",stack:d});if(a&&!hn({extension:a,requiredAttributes:["name"]}))return v({result:{error:G},info:"Invalid extension",context:{extension:a},stack:d});let f=[];m?.drawDefinitions?.forEach(N=>{let C=di({stages:p&&[p],drawDefinition:N}).assignedParticipantIds??[];f.push(...C)});let g=r?.participants??[];if(!o.every(N=>{let C=Uo({tournamentParticipants:g,participantId:N})?.participantType;return!(C&&[pt,Yr].includes(C)&&Ls(i))&&!(i&&m?.eventType&&C===It&&[Vr,Kr].includes(m.eventType)&&[Or,...ff].includes(i))}))return{error:dl};let h=m&&kt({event:m}).flightProfile,S=h?.flights?.find(N=>N.drawId===u),T=N=>{let C=(N||[]).filter(b=>!p||!b.entryStage||p===b.entryStage).filter(({participantId:b})=>o.includes(b)),D=b=>i&&f.includes(b.participantId)&&!(ff.includes(b.entryStatus)&&ff.includes(i));return C.every(b=>D(b)&&!e?!1:(i&&(b.entryStatus=i,delete b.entryPosition),s&&(b.entryStage=s,delete b.entryPosition),a&&(a.value?gt({element:b,extension:a}):rr({element:b,name:a.name})),!0))?{...R}:{error:ys}},A=({flight:N,drawDefinition:C})=>{m&&(m.entries=xn({entries:m.entries??[]})),N&&(N.drawEntries=xn({entries:N.drawEntries})),C&&(C.entries=xn({entries:C.entries}))},P=N=>{let{flight:C,drawDefinition:D}=N,O="updateDrawEntries";if(C){let b=T(C.drawEntries);if(b.error)return v({result:b,stack:O})}if(D){let b=T(D.entries);if(b.error)return v({result:b,stack:O});l.includes(D.drawId)||l.push(D.drawId)}return{...R}},y=m?.entries?.find(({entryPosition:N})=>N)??(S?.drawEntries?.find(({entryPosition:N})=>N)||n?.entries?.find(({entryPosition:N})=>N));if(t&&!y&&A({flight:S,drawDefinition:n}),S||n){let N=P({flight:S,drawDefinition:n});if(N.error)return v({result:N,stack:d})}let E=m?.drawDefinitions?.map(({drawId:N})=>N)??[],U=h?.flights?.filter(N=>!E.includes(N.drawId))||[];for(let N of U){let C=N&&P({flight:N});if(C?.error)return v({result:C,stack:d})}let M=h?.flights?.length===1&&(m?.drawDefinitions?.length??0)<=h?.flights?.length;if(!S&&!n&&i&&_E.includes(i))return{error:hy};if(!S&&!n||i===go||c&&M){let N=T(m?.entries);if(N?.error)return v({result:N,stack:d});let C;if(i===go&&(h?.flights?.every(D=>{let O=T(D.drawEntries);return O.error?(C=O.error,!1):(D.drawEntries=D.drawEntries.filter(({participantId:b})=>!o.includes(b)),!0)}),m?.drawDefinitions?.every(D=>{let O=T(D.entries);return O.error?(C=O.error,!1):(D.entries=D.entries?.filter(({participantId:b})=>!o.includes(b)),!0)})),C)return v({result:{error:C},stack:d})}t&&A({flight:S,drawDefinition:n});for(let N of m?.drawDefinitions??[])l.length&&!l.includes(N.drawId)||Rt({tournamentId:r.tournamentId,eventId:m?.eventId,drawDefinition:N});return{...R}}function Sh(t){let{participantMap:e,participantId:r,matchUpStatus:n,roundPosition:o,structureId:i,matchUpType:s,roundNumber:a,matchUpId:c,potential:u,schedule:p,drawId:m,score:d}=t;if(!p||!Object.keys(p).length)return;n===Ut||e[r].scheduleItems.push({...p,scheduledDate:At(p?.scheduledDate),scheduledTime:qt(p?.scheduledTime),checkScoreHasValue:he({score:d}),matchUpStatus:n,roundPosition:o,structureId:i,matchUpType:s,roundNumber:a,matchUpId:c,potential:u,drawId:m})}function no({requireTimeStamp:t,scaleAttributes:e,participant:r}){if(!r)return{error:Ai};if(!Ct(e))return{error:G};if(r.timeItems||(r.timeItems=[]),Array.isArray(r.timeItems)){let{accessor:n,scaleType:o,eventType:i,scaleName:s}=e,a=[qi,o,i,s].join("."),u=r.timeItems.filter(p=>p?.itemType===a).filter(p=>!t||p?.itemDate).sort((p,m)=>(p.createdAt?new Date(p.createdAt).getTime():0)-(m.createdAt?new Date(m.createdAt).getTime():0)).pop();if(u){let[p,m,d,l]=u.itemType?.split(".")??[];if(p!==qi)return{error:Fu};let g=(n&&Wi({element:u.itemValue,accessor:n}))?.value||u.itemValue,I={eventType:d,scaleDate:u.itemDate,scaleValue:g,scaleName:l,scaleType:m};return{...R,scaleItem:I}}}return{...R,scaleItem:void 0}}function LR({publishedSeeding:t,usePublishState:e,withSeeding:r,participant:n,event:o}){let i={},s=m=>[qi,Qn,o.eventType,m].join("."),a=Object.assign({},...(n.timeItems||[]).filter(({itemType:m})=>m.split(".")[1]===Qn).map(({itemType:m,itemValue:d})=>({[m]:d}))),c=(t?.stageSeedingScaleNames&&Object.values(t?.stageSeedingScaleNames)||Array.isArray(t?.seedingScaleNames)&&t.seedingScaleNames||[]).map(s),u=Wt(Object.keys(a),c);if(!!(!e||!Object.keys(a).length&&!t?.drawIds?.length||u.length)&&u.length){if(t?.stageSeedingScaleNames){let m=Object.keys(t.stageSeedingScaleNames).map(l=>{let f=s(t.stageSeedingScaleNames[l]),g=a[f];return[l,g]}).filter(l=>l[1]).map(l=>({[l[0]]:{seedValue:l[1]}})),d=Object.assign({},...m);i.seedAssignments=d}else if(u){let m=u.map(d=>a[d]);i.seedValue=m.pop()}}else if(!e&&typeof r=="object"){let m=Object.keys(r).map(l=>{let f=s(r[l]),g=a[f];return[l,g]}).filter(l=>l[1]).map(l=>({[l[0]]:{seedValue:l[1]}})),d=Object.assign({},...m);i.seedAssignments=d}else{let{categoryName:m,ageCategoryCode:d}=o.category||{},l=[d,o.eventId,m].filter(Boolean),f;for(let g of l){let I={eventType:o.eventType,scaleType:Qn,scaleName:g},h=no({scaleAttributes:I,participant:n});if(h.scaleItem){f=h.scaleItem;break}}if(f&&(!e||t?.published&&!t?.published?.drawIds?.length)){let I=f.scaleValue;i.seedValue=I}}return i}function FR({convertExtensions:t,seedAssignments:e,participant:r,withSeeding:n,seedValue:o,eventId:i,ranking:s,entry:a}){let{entryStatus:c,entryStage:u,entryPosition:p,extensions:m}=a,d=m?.length&&t?Object.assign({},...xl(m)):{},l=Object.assign(d,{entryPosition:p,entryStatus:c,entryStage:u,ranking:s,eventId:i});r.events[i]=rt(l,!1,!1,!0),n&&(e&&(r.events[i].seedAssignments=e),o&&(r.events[i].seedValue=o))}function ou(t,e){return(t||"").localeCompare(e||"")}function Cf({tournamentRecord:t,status:e=$r}){let r=`${Ho}.${Wo}`;return nu({tournamentRecord:t,itemType:r})?.timeItem?.itemValue?.[e]}function Qr({event:t,status:e=$r}){let r=`${Ho}.${Wo}`;return ru({itemType:r,event:t})?.timeItem?.itemValue?.[e]}function Fm({drawDetails:t,drawId:e}){return t?.[e]?.publishingDetail?.published}function up({tournamentRecord:t,drawDefinition:e,eventIds:r,eventId:n,drawIds:o,drawId:i,event:s}){if(n&&!s)return{error:Ir};if(Array.isArray(r)&&r?.length){let a={};for(let c of r){if(!er(c))return{error:G};let u=nr({tournamentRecord:t,eventId:c});if(!u)return{error:Ir};let p=qE({event:u});if(p.error)return p;a[c]=p}return{...R,publishState:a}}else if(s){let a=qE({event:s});if(a.error)return a;if(i)return e?{publishState:{status:{published:!!a.status.publishedDrawIds?.includes(i),drawDetail:a.status.drawDetails?.[i]},...R}}:{error:fr};if(Array.isArray(o)&&o?.length){let c={};for(let u of o)return er(u)?(c[u]={status:{published:!!a.status.publishedDrawIds.includes(u),drawDetail:a.status.drawDetails?.[u]}},{...R,publishState:c}):{error:G}}else return{publishState:a}}else if(t){let a={},c=Cf({tournamentRecord:t});a.tournament=c;for(let u of t.events??[]){let p=qE({event:u});if(a[u.eventId]=p,p.error)return p;for(let{drawId:m}of u.drawDefinitions??[]){if(!er(m))return{error:G};let d=p.publishState?.publishedDrawIds?.includes(m);d&&(a[m]={status:{published:d}})}}return{...R,publishState:a}}else return{error:j};return{error:G}}function qE({event:t}){let e=Qr({event:t});if(!e)return{status:{published:!1}};let r={published:void 0,seedingScaleNames:[],drawIds:[]};e.seeding&&Object.assign(r,e.seeding);let n=e.drawDetails??{};for(let i of t.drawDefinitions?.map(Qu)||[])n[i]||(n[i]={publishingDetail:{published:!1}});let o=n&&Object.keys(n).filter(i=>Fm({drawDetails:n,drawId:i}))||e.drawIds||[];return{status:{published:o.length>0,publishedDrawIds:o,publishedSeeding:r,drawDetails:n}}}function GR({finishingPositionRange:t={},participantMap:e,finishingRound:r,participantWon:n,matchUpStatus:o,participantId:i,stageSequence:s,roundNumber:a,structureId:c,matchUpId:u,drawId:p,stage:m}){let d=e[i],l=S=>Math.abs(S[0]-S[1]);d.structureParticipation[c]||(d.structureParticipation[c]={rankingStage:m,walkoverWinCount:0,defaultWinCount:0,stageSequence:s,winCount:0,structureId:c,drawId:p});let f=d.structureParticipation[c],{winner:g,loser:I}=t,h=n?g:I;n&&(f.winCount+=1,o===Ot&&(f.walkoverWinCount+=1),o===bt&&(f.defaultWinCount+=1)),h&&(!f.finishingPositionRange||l(h)<l(f.finishingPositionRange))&&(f.finishingPositionRange=h),r&&((!f.finishingRound||r<f.finishingRound)&&(f.finishingMatchUpId=u,f.finishingRound=r,f.roundNumber=a),r===1&&(f.participantWon=n))}function $E(t){let{withScheduleItems:e,scheduleAnalysis:r,withTeamMatchUps:n,participantMap:o,withOpponents:i,withMatchUps:s,withEvents:a,withDraws:c,finishingPositionRange:u,finishingRound:p,matchUpStatus:m,stageSequence:d,roundNumber:l,structureId:f,score:g,stage:I,withRankingProfile:h,tieWinningSide:S,roundPosition:T,matchUpTieId:A,matchUpSides:P,collectionId:y,matchUpType:E,winningSide:U,matchUpId:M,schedule:N,eventId:C,drawId:D,sides:O}=t,b=i&&O?.length===2&&Object.assign({},...O.map(({sideNumber:_},L)=>{let F=O[1-L].participantId;return _&&{[_]:F}}).filter(Boolean));for(let _ of O){let{participantId:L,sideNumber:F,bye:w}=_;if(w)continue;let x=U===F,H=B=>{let q=o[B]?.participant,Y=q?.participantType,k=[{participantId:B,participantType:Y}];if(Y!==Yr)for(let K of q?.individualParticipantIds||[]){let X=o[K]?.participant;k.push({participantType:X?.participantType,participantId:K})}return k},V=(B,q)=>{if(s){if(o[B].matchUps[M]={participantWon:x,matchUpType:E,structureId:f,sideNumber:F,matchUpId:M,eventId:C,drawId:D,stage:I},i){let Y=H(q);o[B].matchUps[M].opponentParticipantInfo=Y}y&&(o[B].matchUps[M].collectionId=y)}i&&q&&(o[B].opponents[q]={participantId:q,matchUpId:M,eventId:C,drawId:D}),h&&GR({finishingPositionRange:u,participantMap:o,participantWon:x,finishingRound:p,matchUpStatus:m,participantId:B,stageSequence:d,roundNumber:l,structureId:f,matchUpId:M,drawId:D,stage:I}),(r||e)&&Sh({participantMap:o,participantId:B,matchUpStatus:m,roundPosition:T,matchUpType:E,roundNumber:l,structureId:f,matchUpId:M,schedule:N,drawId:D,score:g})},W=({participant:B,partnerParticipantId:q})=>{let Y=(k,K)=>{k&&(k.partnerParticipantIds||(k.partnerParticipantIds=[]),k.partnerParticipantIds.includes(K)||k.partnerParticipantIds.push(K))};c&&Y(B?.draws?.[D],q),a&&Y(B?.events?.[C],q),s&&Y(B?.matchUps?.[M],q)};if(L&&o[L]){let B=b?.[F];V(L,B);let q=o[L]?.participant.participantType===pt,Y=o[L]?.participant.individualParticipantIds||[];if(A){if(n){let k=K=>o[K].matchUps[A]={participantWon:S===F,matchUpId:A,matchUpType:Bt,sideNumber:F};k(L),Y.forEach(k)}if(c&&!o[L].draws[D]){let k=P.find($=>$.sideNumber===F)?.participant?.participantId,K=o[k]?.draws?.[D]?.entryStatus,X=$=>o[$].draws[D]={entryStatus:K,eventId:C,drawId:D};X(L),Y.forEach(X)}}if(q&&(Y.forEach(k=>o[k]&&V(k,B)),Y.forEach((k,K)=>{let X=Y[1-K],$=o[k];$&&W({participant:$,partnerParticipantId:X})}),a&&P)){let k=P.find(K=>K.sideNumber===F)?.participant?.participantId;if(k){let K=o[k]?.events[C];K?(o[L].events[C]={...K},Y.forEach(X=>o[X].events[C]={...K})):console.log("Missing teamEntry",{eventId:C,teamParticipantId:k})}}if(U){let k=K=>{x?(o[K].counters[E].wins+=1,o[K].counters.wins+=1,m===Ot&&(o[K].counters[E].walkoverWins+=1,o[K].counters.walkoverWins+=1),m===bt&&(o[K].counters[E].defaultWins+=1,o[K].counters.defaultWins+=1)):(o[K].counters[E].losses+=1,o[K].counters.losses+=1,m===Ot&&(o[K].counters[E].walkovers+=1,o[K].counters.walkovers+=1),m===bt&&(o[K].counters[E].defaults+=1,o[K].counters.defaults+=1))};k(L),Y.forEach(k)}}}}function kR(t){let{participantFilters:e,convertExtensions:r,policyDefinitions:n,tournamentRecord:o,usePublishState:i,contextProfile:s,participantMap:a,withPotentialMatchUps:c,withRankingProfile:u,withScheduleItems:p,scheduleAnalysis:m,withTeamMatchUps:d,withStatistics:l,withOpponents:f,withMatchUps:g,withSeeding:I,withEvents:h,withDraws:S}=t,T=e?.participantIds,A=O=>{let b=[O];return a[O]?.participant.individualParticipantIds?.forEach(_=>b.push(_)),b.some(_=>!T?.length||T.includes(_))?b:[]},P={withMatchUps:g||u,withEvents:h||u,withDraws:S||u,withPotentialMatchUps:c,withRankingProfile:u,withScheduleItems:p,scheduleAnalysis:m,withTeamMatchUps:d,withStatistics:l,participantMap:a,withOpponents:f,withSeeding:I},y=[],E={},U=[],M={},N={},C={},D=({eventType:O,scaleNames:b,participantId:_})=>a[_].participant?.rankings?.[O]?.find(L=>b.includes(L.scaleName))?.scaleValue;for(let O of o?.events||[]){if(e?.eventIds&&!e.eventIds.includes(O.eventId))continue;let{drawDefinitions:b=[],extensions:_=[],eventType:L,eventName:F,category:w,entries:x,eventId:H,gender:V}=O,{flightProfile:W}=kt({event:O}),B=W?.flights??[],q=up({event:O}).publishState;q&&(M[H]=q);let Y=q?.status?.publishedSeeding;if(h||I||u){let K=r?Object.assign({},...xl(_)):{};N[H]={...K,eventName:F,eventType:L,category:w,eventId:H,gender:V};let X=[w?.categoryName,w?.ageCategoryCode].filter(Boolean);for(let $ of x){let{participantId:nt}=$;if(!nt||!a[nt])continue;let Q=D({eventType:L,scaleNames:X,participantId:nt}),it,ot;if(I){let Et=a[nt].participant;({seedAssignments:it,seedValue:ot}=LR({publishedSeeding:Y,usePublishState:i,withSeeding:I,participant:Et,event:O}))}let dt=Et=>{if(a[Et]?.events?.[H])return;let ge=a[Et];FR({convertExtensions:r,seedAssignments:it,participant:ge,withSeeding:I,seedValue:ot,eventId:H,ranking:Q,entry:$})};dt(nt),(a[nt].participant.individualParticipantIds||[]).forEach(dt)}}let k=M?.[H]?.publishedSeeding;if(S||u||I){let K=$=>$?Object.assign({},...$.map(({participantId:nt,seedValue:Q,seedNumber:it})=>({[nt]:{seedValue:Q,seedNumber:it}}))):void 0,X=mt([...b.map(Qu),...B.map(Qu)]);for(let $ of X){let nt=b.find(Vt=>Vt.drawId===$),Q=B?.find(Vt=>Vt.drawId===$),it=nt?.entries||Q?.drawEntries,{structures:ot=[],drawOrder:dt,drawName:zt,drawType:Et}=nt??{},ge=Q?.flightNumber,Ee=[w?.categoryName,w?.ageCategoryCode].filter(Boolean),Ce=(nt?.structures||[]).sort((Vt,_e)=>ri(Vt,_e)).map(({structureId:Vt,structures:_e})=>[Vt,...(_e||[]).map(({structureId:tr})=>tr)]).flat(1/0),Xt,Ue,Ht,Ie,Nt=0,Qt=ot.filter(({stage:Vt,stageSequence:_e})=>Vt===tt&&_e===1||Vt===at).flatMap(Vt=>{let{seedAssignments:_e,stageSequence:tr,stage:Re}=Vt,{positionAssignments:Er}=Dt({structure:Vt});return Re===tt?(Nt=Er?.length??0,Ht=Er,Ie=_e):tr===1&&(Xt=Er,Ue=_e),Er}).map(({participantId:Vt})=>Vt).filter(Boolean),Ft=K(Ie),Yt=K(Ue),ue=nt?it.filter(({participantId:Vt})=>Qt.includes(Vt)):it,Se=!i||k?.published&&(k?.drawIds?.length===0||k?.drawIds?.includes($));for(let Vt of ue){let{entryStatus:_e,entryStage:tr,entryPosition:Re,participantId:Er}=Vt,Te=D({participantId:Er,scaleNames:Ee,eventType:L}),Pe=dr=>{if(a[dr].draws?.[$])return;let Xo=I&&Se,He=Xo?{}:void 0,Pn=Xo?Ft?.[Er]?.seedValue||Ft?.[Er]?.seedNumber:void 0,Ii=Pn?Ft?.[Er]:void 0,Gi=Xo?Yt?.[Er]?.seedValue||Yt?.[Er]?.seedNumber:void 0,fn=Gi?Yt?.[Er]:void 0;He&&Pn&&(He[tt]=Ii),He&&Gi&&(He[at]=fn);let Dc=Pn||Gi;Dc&&(a[dr].participant.seedings[L]||(a[dr].participant.seedings[L]=[]),Ii&&a[dr].participant.seedings[L].push({...Ii,scaleName:$}),fn&&a[dr].participant.seedings[L].push({...fn,scaleName:$}),He&&(a[dr].events[H].seedAssignments||(a[dr].events[H].seedAssignments={}),Object.keys(He).forEach(ki=>a[dr].events[H].seedAssignments[ki]=He[ki]))),(S||u)&&(a[dr].draws[$]=rt({seedAssignments:He,entryPosition:Re,entryStatus:_e,entryStage:tr,seedValue:Dc,eventId:H,ranking:Te,drawId:$},!1,!1,!0))};[_r,oi].includes(_e)||(Pe(Er),(a[Er].participant.individualParticipantIds||[])?.forEach(Pe))}let ur=(nt?.structures??[]).reduce((Vt,_e)=>(Vt.includes(_e.stage)||Vt.push(_e.stage),Vt),[]),Oe=(nt?.links??[]).length;C[$]={qualifyingPositionAssignments:Xt,qualifyingSeedAssignments:Ue,mainPositionAssignments:Ht,qualifyingSeedingMap:Yt,mainSeedAssignments:Ie,orderedStructureIds:Ce,mainSeedingMap:Ft,flightNumber:ge,linksCount:Oe,drawOrder:dt,drawName:zt,drawType:Et,drawSize:Nt,drawId:$,stages:ur}}}if(u||m||d||l||f||g||S){let K=!!m||c,X=ro({afterRecoveryTimes:!!m,policyDefinitions:n,tournamentRecord:o,inContext:!0,contextProfile:s,participantMap:a,nextMatchUps:K,event:O})?.matchUps??[];for(let $ of X){let{finishingPositionRange:nt,potentialParticipants:Q,tieMatchUps:it=[],sides:ot=[],winningSide:dt,matchUpType:zt,matchUpId:Et,eventId:ge,drawId:Ee,collectionId:Ce,stageSequence:Xt,finishingRound:Ue,matchUpStatus:Ht,roundPosition:Ie,roundNumber:Nt,structureId:Qt,schedule:Ft,score:Yt,stage:ue}=$;E[Et]=$;let Se={finishingPositionRange:nt,finishingRound:Ue,stageSequence:Xt,roundPosition:Ie,collectionId:Ce,roundNumber:Nt,structureId:Qt,schedule:Ft,eventId:ge,drawId:Ee,score:Yt,stage:ue};$E({...Se,...P,matchUpStatus:Ht,winningSide:dt,matchUpType:zt,matchUpId:Et,sides:ot});for(let ur of it){let{winningSide:Oe,sides:Vt=[],matchUpId:_e,matchUpStatus:tr,matchUpType:Re}=ur;$E({...Se,...P,winningSide:Oe,tieWinningSide:dt,matchUpTieId:Et,matchUpId:_e,sides:Vt,matchUpSides:ot,matchUpStatus:tr,matchUpType:Re})}Array.isArray(Q)&&(K||m||p)&&Q.flat().map(ft).filter(Boolean)?.forEach(Oe=>{A(Oe)?.forEach(_e=>{a[_e]&&(a[_e].potentialMatchUps[Et]=rt({tournamentId:o?.tournamentId,matchUpId:Et,eventId:ge,drawId:Ee}))}),(m||p)&&Sh({potential:!0,participantMap:a,participantId:Oe,matchUpStatus:Ht,roundPosition:Ie,structureId:Qt,matchUpType:zt,roundNumber:Nt,matchUpId:Et,schedule:Ft,drawId:Ee,score:Yt})})}U.push(...X)}}if(l||u||m){let O=Object.values(a);for(let b of O){let{wins:_,losses:L,[ee]:{wins:F,losses:w},[jt]:{wins:x,losses:H}}=b.counters,V=(W,B,q)=>{let Y=B+q,k=B,K=Y&&k/Y;b.statistics[W]={denominator:Y,numerator:k,statValue:K,statCode:W}};if(l&&(V(Dm,_,L),V(`${Dm}.${ee}`,F,w),V(`${Dm}.${jt}`,x,H)),u){let W=(B=[])=>Math.abs(B[0]-B[1]);for(let B of Object.keys(b.draws)){let{orderedStructureIds:q=[],flightNumber:Y}=C[B]||{};if(b.structureParticipation&&q.length){let k,K=0,X=q.map($=>{let nt=b.structureParticipation[$];if(!nt)return;k||(k=nt?.finishingPositionRange),W(k)>W(nt?.finishingPositionRange)&&(k=nt?.finishingPositionRange);let Q=nt.stage!==at;return Q&&(K+=1),rt({...nt,participationOrder:Q?K:void 0,flightNumber:Y})}).filter(Boolean);b.draws[B]&&(b.draws[B].finishingPositionRange=k,b.draws[B].structureParticipation=X)}}}if(m){let W=Ct(m)?m.scheduledMinutesDifference:0,B=b.scheduleItems||[],q=b.potentialMatchUps||{},Y=B.reduce((K,X)=>{let{scheduledDate:$,scheduledTime:nt}=X;return K[$]||(K[$]=[]),nt&&K[$].push(X),K},{});Object.values(Y).forEach(K=>K.sort(SI));for(let K of B){let{typeChangeTimeAfterRecovery:X,timeAfterRecovery:$,scheduledDate:nt,scheduledTime:Q}=K,it=Y[nt],ot=Gt(Q);for(let dt of it){if(dt.matchUpId===K.matchUpId||[Ot,bt].includes(dt.matchUpStatus)&&!dt.checkScoreHasValue)continue;let ge=K.matchUpType!==dt.matchUpType&&X||$,Ee=K.drawId===dt.drawId,Ce=q[K.matchUpId]&&q[dt.matchUpId],Xt=Gt(dt.scheduledTime),Ue=Math.abs(Xt-ot),Ht=Xt>=ot;if((W&&!isNaN(W)?Ue<=W:Ht&&Gt(dt.scheduledTime)<Gt(ge))&&!(Ce&&Ee)&&Ht){let Nt=[K.matchUpId,dt.matchUpId].sort(ou).join("|");b.scheduleConflicts[Nt]={priorScheduledMatchUpId:K.matchUpId,matchUpIdWithConflict:dt.matchUpId}}}}let k=b.participant.participantId;Object.keys(b.scheduleConflicts).length&&y.push(k),a[k].scheduleConflicts=b.scheduleConflicts}}}return{participantIdsWithConflicts:y,eventsPublishStatuses:M,derivedEventInfo:N,derivedDrawInfo:C,mappedMatchUps:E,participantMap:a,matchUps:U}}function iu({participantFilters:t={},tournamentRecord:e,participants:r=[]}){if(!Object.keys(t).length)return r;let{accessorValues:n,drawEntryStatuses:o,positionedParticipants:i,eventEntryStatuses:s,participantRoles:a,participantRoleResponsibilities:c,participantTypes:u,participantIds:p,signInStatus:m,enableOrFiltering:d,eventIds:l,genders:f}=t,g=Fs(l)&&e?.events?.filter(A=>l?.includes(A.eventId))||e?.events||[],I=o&&ZL({drawEntryStatuses:o,tournamentEvents:g}),h=s&&tF({eventEntryStatuses:s,tournamentEvents:g}),S=i!==void 0&&[!0,!1].includes(i)&&g.reduce((A,P)=>A.concat(...(P.drawDefinitions||[]).map(y=>BI({drawDefinition:y}).allPositionedParticipantIds).filter(Boolean)),[]),T=A=>n?.reduce((P,y)=>{let{accessor:E,value:U}=y,{values:M}=Wi({element:A,accessor:E});return P&&M?.includes(U)},!0);if(r=r?.filter(A=>{let P=_n({element:A,itemType:Ja})?.timeItem?.itemValue,{participantRoleResponsibilities:y,participantType:E,participantRole:U,participantId:M,person:N}=A,C=Array.isArray(f)&&f?.length&&N?.sex&&f.includes(N.sex);return d?f&&C||i&&S.includes(M)||i===!1&&!S.includes(M)||I?.includes(M)||h?.includes(M)||p?.includes(M)||m&&P===m||u&&E&&Fs(u)&&u.includes(E)||a&&U&&Fs(a)&&a.includes(U)||c&&Fs(y)&&Fs(c)&&c.find(D=>y?.includes(D))||n?.length&&Fs(n)&&T(A):(!f||C)&&(i===void 0||i&&S.includes(M)||i===!1&&!S.includes(M))&&(!I||I.includes(M))&&(!h||h.includes(M))&&(!p||p.includes(M))&&(!m||P===m)&&(!u||E&&Fs(u)&&u.includes(E))&&(!a||U&&Fs(a)&&a.includes(U))&&(!c||Fs(y)&&Fs(c)&&c.find(D=>y?.includes(D)))&&(!n?.length||Fs(n)&&T(A))}),g.length&&l){let A=g.filter(P=>l.includes(P.eventId)).map(P=>{let y=(P.entries||[]).map(U=>U.participantId);if(P.eventType===eo)return y;let E=(e?.participants??[]).filter(U=>y.includes(U.participantId)).map(U=>U.individualParticipantIds).flat(1);return y.concat(...E)}).flat(1);r=r?.filter(P=>A.includes(P.participantId))}return r}function Fs(t){return t&&Array.isArray(t)&&t.length}function ZL({drawEntryStatuses:t,tournamentEvents:e}){let r=({entryStatus:n})=>Array.isArray(t)?t.includes(n):!0;return mt(e.reduce((n,o)=>{let{flightProfile:i}=kt({event:o}),s=i?.flights?.map(({drawEntries:c})=>Array.isArray(c)?c.filter(r).map(ft):[]).flat()||[],a=o.drawDefinitions?.map(({entries:c})=>c?c.filter(r).map(ft):[])||[];return n.concat(...s,...a)},[]))}function tF({eventEntryStatuses:t,tournamentEvents:e}){return mt(e.reduce((r,n)=>{let o=(n.entries||[]).filter(({entryStatus:i})=>Array.isArray(t)?t.includes(i):!0).map(ft);return r.concat(...o)},[]))}function $t(t){let{withIndividualParticipants:e,participantFilters:r={},withPotentialMatchUps:n,withRankingProfile:o,convertExtensions:i,policyDefinitions:s,withScheduleItems:a,tournamentRecord:c,scheduleAnalysis:u,withSignInStatus:p,withTeamMatchUps:m,withScaleValues:d,usePublishState:l,contextProfile:f,withStatistics:g,withOpponents:I,withMatchUps:h,internalUse:S,withSeeding:T,withEvents:A,withDraws:P,withISO2:y,withIOC:E}=t;if(!c)return{error:j};(h||o)&&xr({tournamentRecord:c});let{participantMap:U}=fh({convertExtensions:i,tournamentRecord:c,withSignInStatus:p,withScaleValues:d,internalUse:S,withISO2:y,withIOC:E}),M=kR({withMatchUps:h??o,withEvents:A??o,withDraws:P??o,withPotentialMatchUps:n,participantFilters:r,withRankingProfile:o,convertExtensions:i,withScheduleItems:a,policyDefinitions:s,tournamentRecord:c,scheduleAnalysis:u,withTeamMatchUps:m,usePublishState:l,withStatistics:g,participantMap:U,withOpponents:I,contextProfile:f,withSeeding:T}),{participantIdsWithConflicts:N,eventsPublishStatuses:C,derivedEventInfo:D,derivedDrawInfo:O,mappedMatchUps:b}=M,_=M.matchUps;U=M.participantMap;let L=u??n,F=({potentialMatchUps:q,scheduleConflicts:Y,scheduleItems:k,participant:K,statistics:X,opponents:$,matchUps:nt,events:Q,draws:it})=>{let ot=Object.values(it),dt=Object.values($);return I&&ot?.forEach(zt=>{zt.opponents=dt.filter(Et=>Et.drawId===zt.drawId)}),rt({...K,scheduleConflicts:u?Object.values(Y):void 0,draws:P||o?ot:void 0,events:A||o?Object.values(Q):void 0,matchUps:h||o?Object.values(nt):void 0,opponents:I?dt:void 0,potentialMatchUps:L?Object.values(q):void 0,statistics:g?Object.values(X):void 0,scheduleItems:a?k:void 0},!1,!1,!0)},w=new Map;for(let q of Object.keys(U))w.set(q,F(U[q]));let x=[...w.values()],V=s?.[Ka]?.participant,W=iu({participants:x,participantFilters:r,tournamentRecord:c});if(e){let q=Ct(e)?e:void 0;for(let Y of W)for(let k of Y.individualParticipantIds??[]){Y.individualParticipants||(Y.individualParticipants=[]);let K=w.get(k);Y.individualParticipants.push(q?Di({template:q,source:K}):K)}}let B=V?W.map(q=>Di({source:q,template:V})):W;return{participantIdsWithConflicts:N,eventsPublishStatuses:C,derivedEventInfo:D,derivedDrawInfo:O,mappedMatchUps:b,participantMap:U,participants:B,...R,matchUps:_}}function ic({participantId:t,drawDefinition:e,entryStatus:r,entryStage:n}){if(!e)return{error:z};let o=e.entries?.find(i=>i.participantId===t&&(!r||r===i.entryStatus)&&(!n||n===i.entryStage));return t&&o}function os(t){let{provisionalPositioning:e,drawDefinition:r,stageSequence:n,structureId:o,stage:i}=t;if(!r)return{error:z};let{entryProfile:s}=Qc({drawDefinition:r}),a=i&&n&&s?.[i]?.stageSequence?.[n]?.qualifiersCount||i&&s?.[i]?.qualifiersCount||0,c={};if(!o)return{qualifiersCount:a,roundQualifiersCounts:c};let{structure:u}=st({drawDefinition:r,structureId:o}),p=r.links?.filter(l=>l?.target?.structureId===u?.structureId),m=0;if(p?.length)for(let l of p){let f=st({structureId:l.source.structureId,drawDefinition:r})?.structure;if(f?.stage===at){let g=l.source.roundNumber,I=l.target.roundNumber,h=0;if(f.structureType===we){let S=f.structures?.length??0,T=l.source.finishingPositions?.length??0;h=S*T}else h=Pt({matchUpFilters:{roundNumbers:[g]},structure:f,afterRecoveryTimes:!1,provisionalPositioning:e,inContext:!1}).matchUps?.length||0;c[I]||(c[I]=0),c[I]+=h,m+=h}}let d=Object.keys(c);if(d.length<=1){let l=d[0]||1;c[l]=Math.max(c[l]||0,a)}return m=Math.max(m,a),{qualifiersCount:m,roundQualifiersCounts:c}}function pp({stage:t,drawDefinition:e}){let{entryProfile:r}=Qc({drawDefinition:e});return r?.[t]?.drawSize||0}function VR(t){let{provisionalPositioning:e,drawDefinition:r,stageSequence:n,stage:o}=t,i=pp({stage:o,drawDefinition:r}),{qualifiersCount:s}=os({provisionalPositioning:e,drawDefinition:r,stageSequence:n,stage:o});return i&&i-s}function KE({stage:t,drawDefinition:e}){return!!(t===ke||gf({stage:t,drawDefinition:e})&&pp({stage:t,drawDefinition:e}))}function zE({entryStatus:t=qr,drawDefinition:e,stageSequence:r,stage:n}){if(t===Or)return KC({stage:n,drawDefinition:e})?{positionsAvailable:1/0,...R}:{error:Iy};let o=VR({drawDefinition:e,stageSequence:r,stage:n}),i=zC({drawDefinition:e,stage:n}),s=KI({entryStatus:Xc,drawDefinition:e,stage:n}),a=KI({entryStatus:qr,drawDefinition:e,stage:n}),c=s+a,u=c>=o,p=o-c;return n!==ke&&u?{error:oI}:t===Xc?s<i?{...R}:{error:oI}:{positionsAvailable:p,...R}}function Th(t){let{entryStatus:e=qr,entryStageSequence:r,entryStage:n=tt,ignoreStageSpace:o,drawDefinition:i,entryPosition:s,participant:a,roundTarget:c,extensions:u,extension:p,drawType:m}=t,d="addDrawEntry";if(!i)return{error:z};if(!n)return{error:Qg};if(m!==br&&!KE({stage:n,drawDefinition:i}))return v({result:{error:Si},stack:d});let l=zE({stageSequence:r,stage:n,drawDefinition:i,entryStatus:e});if(!o&&!l.success)return{error:l.error};if(p&&!hn({extension:p}))return v({result:{error:G},info:"Invalid extension",context:{extension:p},stack:d});let f=t.participantId||a?.participantId;if(!f)return v({result:{error:te},stack:d});let g=e===Qi&&ic({participantId:f,drawDefinition:i,entryStatus:e}),I=n===ke&&ic({participantId:f,drawDefinition:i,entryStage:n}),h=e!==Qi&&n!==ke&&ic({drawDefinition:i,participantId:f});if(h||g||I)return v({context:{invalidEntry:h,invalidLuckyLoser:g,invalidVoluntaryConsolation:I},result:{error:Lu},stack:d});let S=rt({entryStageSequence:r,participantId:f,entryPosition:s,entryStatus:e,entryStage:n,extensions:u});return p&&gt({element:S,extension:p}),c&&gt({extension:{name:"roundEntry",value:c},element:S}),i.entries||(i.entries=[]),i.entries.push(S),Rt({drawDefinition:i}),{...R}}function BR(t){let e="addDrawEntries",{entryStatus:r=qr,stage:n=tt,autoEntryPositions:o=!0,ignoreStageSpace:i,drawDefinition:s,participantIds:a,stageSequence:c,roundTarget:u,extension:p}=t;if(!n)return{error:Qg};if(!s)return{error:z};if(!Array.isArray(a))return{error:Hr};if(!KE({stage:n,drawDefinition:s}))return{error:Si};if(p&&!hn({extension:p}))return v({result:{error:G},info:"Invalid extension",context:{extension:p},stack:e});let m=zE({drawDefinition:s,stageSequence:c,entryStatus:r,stage:n});if(!i&&!m.success)return{error:m.error};let d=m.positionsAvailable??0;if(!i&&n!==ke&&d<a.length)return{error:ml};let l=a.reduce((f,g)=>{let I=r===Qi&&ic({participantId:g,drawDefinition:s,entryStatus:r}),h=n===ke&&ic({entryStage:n,drawDefinition:s,participantId:g});return r!==Qi&&n!==ke&&ic({drawDefinition:s,participantId:g})||I||h?f.concat(g):f},[]);return a.filter(f=>f&&!l.includes(f)).forEach(f=>{let g={entryStageSequence:c,entryStage:n,participantId:f,entryStatus:r};p&&gt({element:g,extension:p}),u&&gt({extension:{name:cn,value:u},element:g}),s.entries||(s.entries=[]),s.entries.push(g)}),o&&(s.entries=xn({entries:s.entries})),Rt({drawDefinition:s}),l?.length?{info:"some participantIds could not be added",participantIdsNotAdded:l,...R}:{...R}}function Rf({autoEntryPositions:t=!0,entryStageSequence:e,ignoreStageSpace:r,drawDefinition:n,participantIds:o,entryStatus:i,roundTarget:s,entryStage:a,extension:c,drawId:u,event:p}){if(!o?.length)return{error:so};if(!p)return{error:Ir};if(!u)return{error:Ur};let m=(p.entries||[]).map(ft);if(o.filter(g=>!m.includes(g)).length)return{error:QA};if(n){let g=BR({stageSequence:e,autoEntryPositions:t,stage:a,ignoreStageSpace:r,drawDefinition:n,participantIds:o,entryStatus:i,roundTarget:s,extension:c});if(g.error)return g}let{flightProfile:l}=kt({event:p}),f=l?.flights.find(g=>g.drawId===u);return f?.drawEntries&&(o.forEach(g=>{let I=i===Qi&&QE({participantId:g,entryStatus:i,flight:f}),h=a===ke&&QE({participantId:g,entryStage:a,flight:f});!(i!==Qi&&a!==ke&&QE({flight:f,participantId:g}))&&!I&&!h&&f.drawEntries.push({participantId:g,entryStatus:i,entryStage:a})}),t&&(f.drawEntries=xn({entries:f.drawEntries}))),{...R}}function QE({participantId:t,entryStatus:e,entryStage:r,flight:n}){let o=n.drawEntries?.find(i=>i.participantId===t&&(!e||e===i.entryStatus)&&(!r||r===i.entryStage));return t&&o}function sc({autoEntryPositions:t=!0,participantIds:e=[],entryStatuses:r,stage:n,event:o}){let i="removeEventEntries";if(!o?.eventId)return{error:St};if(!Array.isArray(e)||e.some(m=>!er(m)))return v({result:{error:sn},stack:i});let s=(o.drawDefinitions??[]).flatMap(m=>di({drawDefinition:m}).assignedParticipantIds??[]),a=(r?.length&&o.entries?.filter(m=>m.entryStatus&&r.includes(m.entryStatus))||[]).map(ft).filter(m=>!s.includes(m)),c=(n&&o.entries?.filter(m=>m.entryStage&&m.entryStage===n)||[]).map(ft).filter(m=>!s.includes(m));if(e.length?e=e.filter(m=>(!r?.length||a.includes(m))&&(!n||c.includes(m))):a.length&&c.length?e=Wt(a,c):a.length?e=a:c.length&&(e=c),e?.length&&s.some(m=>e.includes(m)))return v({result:{error:ys},stack:i});if(!e?.length)return{...R,participantIdsRemoved:[]};let u=[];o.entries=(o.entries??[]).filter(m=>{let d=!e.includes(m?.participantId);return d||u.push(m.participantId),d}),t&&(o.entries=xn({entries:o.entries}));let{flightProfile:p}=kt({event:o});return p?.flights?.forEach(m=>{m.drawEntries=(m.drawEntries||[]).filter(d=>!e.includes(d.participantId))}),o.drawDefinitions?.forEach(m=>{m.entries=(m.entries??[]).filter(d=>!e.includes(d.participantId))}),{...R,participantIdsRemoved:u}}var XE={[qe]:{policyName:"matchUpActionsDefault",enabledStructures:[{stages:[],stageSequences:[],enabledActions:[],disabledActions:[]}],participants:{enforceCategory:!0,enforceGender:!0},processCodes:{substitution:["RANKING.IGNORE","RATING.IGNORE"]},substituteAfterCompleted:!1,substituteWithoutScore:!1}},is=XE;function Wn(t){let{entryStatus:e=qr,autoEntryPositions:r=!0,enforceGender:n=!0,participantIds:o=[],entryStageSequence:i,policyDefinitions:s,entryStage:a=tt,tournamentRecord:c,ignoreStageSpace:u,drawDefinition:p,roundTarget:m,extensions:d,extension:l,drawId:f,event:g}=t,I="addEventEntries";if(!g)return{error:St};if(!o?.length)return v({result:{error:so},stack:I});if(!g?.eventId)return{error:Ir};let h=yt({tournamentRecord:c,event:g}).appliedPolicies??{},S=s?.[qe]??h?.[qe]??is[qe],T=(n??S?.participants?.enforceGender)!==!1,A=[],P=[];if(d&&(!Array.isArray(d)||!d.every(b=>hn({extension:b})))||l&&!hn({extension:l}))return v({context:rt({extension:l,extensions:d}),result:{error:G},info:"Invalid extension(s)",stack:I});let y=!!c,E=[],U,M=c?.participants?.filter(b=>{if(!o.includes(b.participantId))return!1;let _=g.eventType===ee&&b.participantType===It&&!Ls(e),L=g.eventType===jt&&b.participantType===pt;return _&&(!g.gender||!T||[Cr,On].includes(g.gender)||g.gender===b.person?.sex)||L&&!Ls(e)||g.eventType===jt&&b.participantType===It&&Ls(e)?!0:_&&g.gender&&T&&![Cr,On].includes(g.gender)&&g.gender!==b.person?.sex?(E.push({participantId:b.participantId,sex:b.person?.sex}),!1):g.eventType===Lt&&(b.participantType===Lt||Ls(e)&&b.participantType===It)}).map(b=>b.participantId)??[],N=o.filter(b=>!y||M.includes(b));g.entries||(g.entries=[]);let C=g.entries.map(b=>b.participantId||b.participant?.participantId);if(N.forEach(b=>{if(!C.includes(b)){let _=rt({participantId:b,entryStatus:e,entryStage:a,extensions:d});l&&gt({element:_,extension:l}),m&&gt({extension:{name:cn,value:m},element:_}),i&&(_.entryStageSequence=i),A.push(_.participantId),g.entries?.push(_)}}),f&&!Ls(a)){let b=Rf({participantIds:N,autoEntryPositions:r,entryStageSequence:i,ignoreStageSpace:u,drawDefinition:p,entryStatus:e,roundTarget:m,entryStage:a,extension:l,drawId:f,event:g});b.error&&(U=b.error)}if(g.eventType&&[ui,Kr].includes(g.eventType)){let b=(g.entries||[]).map(x=>x.participantId),_=(g.entries||[]).filter(x=>Ls(x.entryStatus)).map(x=>x.participantId),F=(c?.participants??[]).filter(x=>b.includes(x.participantId)&&x.participantType&&[pt,Lt].includes(x.participantType)).map(x=>x.individualParticipantIds).flat(1/0),w=_.filter(x=>F.includes(x));w.length&&(P.push(...w),sc({participantIds:w,autoEntryPositions:!1,event:g}))}if(N.length!==o.length)return v({context:{mismatchedGender:E,gender:g.gender},result:{error:Hr},stack:I});r&&(g.entries=xn({entries:g.entries||[]}));let O=A.length-P.length;return v({result:{...R,addedEntriesCount:O},stack:I,info:U})}var eF="ADMINISTRATION",rF="CAPTAIN",nF="COACH",Fe="COMPETITOR",oF="MEDIA",iF="MEDICAL",JE="OFFICIAL",ZE="OTHER",sF="SECURITY",Gm={ADMINISTRATION:eF,CAPTAIN:rF,COACH:nF,COMPETITOR:Fe,MEDIA:oF,MEDICAL:iF,OFFICIAL:JE,OTHER:ZE,SECURITY:sF};function bf({addIndividualParticipantsToEvents:t,individualParticipantIds:e,groupingParticipantId:r,tournamentRecord:n,suppressErrors:o}){let i="removeIndividualParticipantIds";if(!n)return v({result:{error:j},stack:i});if(!r||!e)return v({result:{error:et},stack:i});let a=(n.participants??[]).find(m=>m.participantId===r);if(!a)return v({result:{error:Jt},stack:i});if(![Lt,hr].includes(a.participantType))return v({result:{participantType:a.participantType,error:tn},stack:i});let c=HR({individualParticipantIds:e,groupingParticipant:a,tournamentRecord:n,suppressErrors:o}),{removed:u,error:p}=c;if(p)return v({result:c,stack:i});if(t)for(let m of n.events??[]){let d=(m.entries??[]).map(({participantId:l})=>l).filter(Boolean);if(d.includes(r)){let l=u?.filter(f=>!d.includes(f));Wn({participantIds:l,entryStatus:_r,tournamentRecord:n,event:m})}}return u&&Tt({topic:$e,payload:{tournamentId:n.tournamentId,participants:[a]}}),{...R,...c}}function HR({individualParticipantIds:t=[],groupingParticipant:e,tournamentRecord:r,suppressErrors:n,mappedMatchUps:o,participants:i}){let s=[];if(!e)return{removed:s};let a=[],c=[];i||({participants:i,mappedMatchUps:o}=$t({withMatchUps:!0,tournamentRecord:r,withEvents:!0}));let p=i?.find(({participantId:l})=>l===e.participantId)?.events?.map(({eventId:l})=>l),m=(e.individualParticipantIds??[]).filter(l=>{let f=t?.includes(l),g=f&&i?.find(h=>h.participantId===l)?.matchUps.filter(({eventId:h})=>p.includes(h)).map(({matchUpId:h})=>o?.[h]).filter(({winningSide:h,score:S})=>h||he({score:S})),I=f&&!g?.length;if(f&&!I&&c.push(l),I){s.push(l);for(let h of r.events??[])for(let S of h.drawDefinitions??[]){let{extension:T}=ut({element:S,name:mo}),A=T?.value[e.participantId];T&&A&&(T.value[e.participantId]=A.filter(y=>y.participantId!==l),gt({element:S,extension:T}),ma({drawDefinition:S}));let P=ar({drawDefinition:S,inContext:!1}).matchUps??[];for(let y of P){let E=y.sides??[];for(let U of E){let M=U.lineUp??[];M.find(C=>C.participantId===l)&&(U.lineUp=M.filter(C=>C.participantId!==l),ht({tournamentId:r?.tournamentId,drawDefinition:S,matchUp:y}))}}}}else a.push(l);return!I});e.individualParticipantIds=m;let d={groupingParticipantId:e.participantId,cannotRemove:c,notRemoved:a,removed:s};return c.length&&!n&&{...d,cannotRemove:c,error:wu}||d}function mp({participantRole:t=Fe,individualParticipantIds:e=[],groupingTypes:r=[Yr,hr],tournamentRecord:n}){if(!n)return{error:j};let o=n.participants??[],{participants:i,mappedMatchUps:s}=$t({withMatchUps:!0,tournamentRecord:n,withEvents:!0}),a=0;return o.filter(c=>(c.participantRole===t||!c.participantRole)&&c.participantType&&r.includes(c.participantType)).forEach(c=>{let{removed:u}=HR({groupingParticipant:c,individualParticipantIds:e,tournamentRecord:n,mappedMatchUps:s,participants:i});u&&a++}),a?R:{error:dy}}function Oi(t){if(!t?.tournamentRecord)return{error:j};if(!t?.participantIds?.length)return{error:so};let{addIndividualParticipantsToEvents:e,tournamentRecord:r,participantIds:n}=t,o=r.participants?.length||0;if(!o)return{...R};let i=(r.events||[])?.filter(({eventType:l})=>l===Le).map(l=>l?.drawDefinitions?.map(({drawId:f})=>f)).flat(1/0),s=$t({participantFilters:{participantIds:n},tournamentRecord:r,withDraws:!0}).participants??[],a=()=>{let f=(pe({matchUpFilters:{drawIds:i,matchUpTypes:[jt]},tournamentRecord:r}).matchUps??[]).map(({sides:g})=>g?.map(({participantId:I})=>I)).flat().filter(Boolean);return Wt(f,n)},c=i?.length&&a(),u=s.filter(l=>l.draws?.filter(f=>(!i?.length||!i?.includes(f.drawId))&&f.positionAssignments).length);if(c?.length||u.length)return{error:ys};let p={},m={};for(let l of r.events||[]){let f=sc({participantIds:n,event:l});if(f.error)return f;p[l.eventId]=f.participantIdsRemoved}r.participants=r.participants.filter(l=>{let f=n.includes(l.participantId)||l.participantType===pt&&l.individualParticipantIds.some(g=>n.includes(g));if(!f&&l.participantType===Le&&l.individualParticipantIds.some(g=>n.includes(g))&&(l.individualParticipantIds=l.individualParticipantIds.filter(g=>!n.includes(g))),f&&e&&[pt,Lt].includes(l.participantType))for(let g of l.individualParticipantIds||[])n.includes(g)||(m[l.participantId]||(m[l.participantId]=[]),m[l.participantId].push(g));return!f});let d=o-r.participants.length;if(mp({individualParticipantIds:n,tournamentRecord:r}),e)for(let l of r.events||[]){let g=p[l.eventId].map(I=>m[I]||[]).flat();Wn({participantIds:g,entryStatus:_r,tournamentRecord:r,event:l})}return d&&Tt({payload:{participantIds:n,tournamentId:r.tournamentId},topic:Ql}),d?{...R,participantsRemovedCount:d}:{error:wu}}function Ah({selected:t=!0,drawDefinition:e,entryStatuses:r,drawId:n,event:o,stage:i}){let s=o.entries??[];if(n){let{flightProfile:c}=kt({event:o}),u=c?.flights?.find(p=>p.drawId===n);u?s=u.drawEntries:e.entries&&(s=e?.entries)}let a=s.filter(c=>(!r?.length||!c.entryStatus||r.includes(c.entryStatus))&&(!i||!c.entryStage||c.entryStage===i)&&(!t||c.entryStatus&&Mr.includes(c.entryStatus)));return{entries:s,stageEntries:a}}function tU({removeGroupParticipant:t,tournamentRecord:e,drawDefinition:r,participantId:n,drawId:o,stage:i,event:s}){let a="destroyGroupEntry";if(!e)return{error:j};if(!n)return v({result:{error:te},stack:a});if(!s)return{error:St};if(!s.eventType||![ui,Kr].includes(s.eventType))return v({result:{error:yo},stack:a});let c=e.participants??[],u=c.find(S=>S.participantId===n);if(!u)return v({result:{error:Jt},stack:a});if(!u.participantType||![pt,Yr].includes(u.participantType)||u.participantType===Yr&&s.eventType!==Kr||u.participantType===pt&&s.eventType!==ui)return{error:tn};let m=(s.entries??[]).find(S=>S.participantId===n);if(!m)return{error:nI};let{stageEntries:d}=Ah({selected:!1,drawDefinition:r,drawId:o,event:s,stage:i}),l=d.map(ft),f=c.filter(({participantId:S})=>l.includes(S)).map(({individualParticipantIds:S})=>S).flat().filter(Boolean),g=u.individualParticipantIds?.filter(S=>$n(S,f).length===1),I=sc({participantIds:[n],event:s});if(I.error||g?.length&&(I=Wn({participantIds:g,entryStatus:_r,entryStage:m.entryStage,tournamentRecord:e,drawDefinition:r,drawId:o,event:s}),I.error))return I;let h;return t&&Oi({participantIds:[n],tournamentRecord:e}).success&&(h=!0),{...R,participantRemoved:h}}function Of({removeGroupParticipant:t,tournamentRecord:e,drawDefinition:r,participantId:n,drawId:o,event:i}){return tU({removeGroupParticipant:t,tournamentRecord:e,drawDefinition:r,participantId:n,drawId:o,event:i})}function eU(t){if(!t.tournamentRecord)return{error:j};let{participantIds:e,...r}=t,n=0,o=[];for(let i of e){let s=tU({participantId:i,...r});s.success&&(n+=1),s.error&&o.push(s.error)}return n?{destroyedCount:n,...R}:{error:o}}function su(t){let{tournamentRecord:e,replaceWithBye:r,drawDefinition:n,destroyPair:o,entryStatus:i,matchUpsMap:s,drawId:a}=t,c="removeDrawPositionAssignment",u=oc(t);if(u.error)return v({result:u,stack:c});let{participantId:p}=u,{drawPosition:m,event:d,structureId:l}=t;if([Or,go].includes(i)&&p){let{tournamentRecord:I}=t,{participant:h}=Mo({tournamentRecord:I,participantId:p}),{participantType:S,individualParticipantIds:T}=h??{};if(o&&S===pt){let A=Of({tournamentRecord:I,drawDefinition:n,participantId:p,event:d});if(A.error)return v({result:A,stack:c});T&&Lm({participantIds:T,tournamentRecord:I,drawDefinition:n,entryStatus:i,drawId:a,event:d})}else Lm({participantIds:[p],tournamentRecord:I,drawDefinition:n,entryStatus:i,drawId:a,event:d})}if(r){let I=yr({tournamentRecord:e,drawDefinition:n,drawPosition:m,structureId:l,matchUpsMap:s,event:d});if(I.error)return v({result:I,stack:c})}let{structure:f}=st({drawDefinition:n,structureId:l});return ym({structure:f,drawPositions:[m]}),qc({drawDefinition:n,positionAction:{name:"removeDrawPositionAssignment",replaceWithBye:r,drawPosition:m,entryStatus:i,structureId:l}}),u}function rU(t){return Object.assign(t,{entryStatus:go}),su(t)}function yh(t){return er(t)?t.split(" ").map(e=>e.split("").map((r,n)=>n?r.toLowerCase():r.toUpperCase()).join("")).join(" "):t}function Be(t){return er(t)?yh(t.replace(/_/g," ")):""}var ss=({finishingPosition:t=Ci,qualifyingRoundNumber:e,structureAbbreviation:r,seedAssignments:n=[],stageSequence:o=1,structureOrder:i,seedingProfile:s,matchUpFormat:a,structureType:c,structureName:u,matchUpType:p,matchUps:m=[],structureId:d,roundOffset:l,roundLimit:f,stageOrder:g,structures:I,stage:h})=>{let S={structureId:d??Mt(),structureAbbreviation:r,finishingPosition:t,seedAssignments:n,matchUpFormat:a,stageSequence:o,structureName:u};i&&(S.structureOrder=i),c&&(S.structureType=c),s&&(typeof s=="string"?S.seedingProfile=s:typeof s=="object"&&typeof s.positioning=="string"&&(S.seedingProfile=s.positioning)),p&&(S.matchUpType=p),l&&(S.roundOffset=l),g&&(S.stageOrder=g),f&&(S.roundLimit=f),h&&(S.stage=h),e&&(S.qualifyingRoundNumber=e);let T=m.flatMap(({drawPositions:A})=>A).filter(Boolean);return I?S.structures=I:(S.matchUps=m,S.positionAssignments=mt(T).sort((A,P)=>A-P).map(A=>({drawPosition:A}))),S},Xr=ss;function _f({structureName:t=Be(ke),structureAbbreviation:e,drawDefinition:r,matchUpType:n,structureId:o}){if(!r)return{error:z};let i=Xr({stage:ke,structureAbbreviation:e,structureName:t,matchUps:[],structureId:o,matchUpType:n});return r.structures||(r.structures=[]),r.structures.push(i),Rt({drawDefinition:r,structureIds:[i.structureId]}),{...R}}function vf({drawPositions:t}){if(!t?.length)return{error:Fa};let e=o=>t.filter(i=>i!==o).map(i=>[o,i]),r=[].concat(...(t??[]).map(e)),n=mt(r.map(xf)).map(o=>o.split("|").map(i=>+i));return{groupMatchUps:r,uniqueMatchUpGroupings:n}}function xf(t=[]){return!Array.isArray(t)||!t.length?"":[...t].sort(oe).join("|")}function nU({groupSize:t,drawPositionOffset:e}){if(!t)return[];let r=m=>[...Array(m)].map((d,l)=>l),n=r(2*Math.round(t/2)+1).slice(1),o=r(n.length-1).map(()=>[]),i=n.slice(0,n.length/2),s=n.slice(n.length/2);n.slice(1).forEach((m,d)=>{i.forEach((I,h)=>{o[d].push([i[h],s[h]])});let l=i.shift(),f=i.pop(),g=s.shift();i=[l,g,...i].filter(Boolean),s=[...s,f].filter(Boolean)});let a=i.shift(),c=i.pop(),u=s.shift();i=[a,u,...i].filter(Boolean),s=[...s,c].filter(Boolean);let p=m=>m[0].reduce((d,l)=>d+l);return[...o].reverse().sort((m,d)=>p(m)-p(d)).map(m=>m.filter(d=>d.every(l=>l<=t)).map(d=>{let l=d.map(f=>f+e);return xf(l)}))}function aF({rounds:t,hash:e}){return t?.length?t?.reduce((r,n,o)=>n.includes(e)?o+1:r,void 0):{error:et}}var WR={getRoundRobinGroupMatchUps:vf,determineRoundNumber:aF,drawPositionsHash:xf,groupRounds:nU};function Aa(t){let{groupNameBase:e="Group",playoffAttributes:r,stageSequence:n=1,structureOptions:o,appliedPolicies:i,seedingProfile:s,stage:a=tt,matchUpType:c,roundTarget:u,structureId:p,groupNames:m,drawSize:d,idPrefix:l,isMock:f,uuids:g}=t,I=t.structureName??r?.["0"]?.name??Be(tt),{groupCount:h,groupSize:S}=cF({structureOptions:o,appliedPolicies:i,drawSize:d}),T=Ms,A,P=Z(1,h+1).map(E=>{let U=uF({groupSize:S,structureOrder:E,matchUpType:c,drawSize:d,idPrefix:l,isMock:f});A=Array.isArray(U)?Math.max(...U.map(({roundNumber:N})=>N??0)):0;let M=m?.[E-1]??`${e} ${E}`;return ss({structureId:g?.pop(),structureType:Xu,finishingPosition:T,structureOrder:E,structureName:M,matchUps:U})}),y=ss({structureId:p??g?.pop(),structureType:we,finishingPosition:T,seedingProfile:s,structureName:I,stageSequence:n,structures:P,stage:a});return u&&gt({extension:{name:cn,value:u},element:y}),{structures:[y],maxRoundNumber:A,groupCount:h,links:[],groupSize:S,...R}}function cF({appliedPolicies:t,structureOptions:e,drawSize:r}){let n=e?.groupSize,o=e?.groupSizeLimit||8,{validGroupSizes:i}=dp({groupSizeLimit:o,drawSize:r}),s=i&&Math.max(...i);n&&i?.includes(n)||(n&&n>4||!i?.includes(4)?n=s:n=4);let c=Math.ceil(r/n);return{groupSize:n,groupCount:c}}function dp({drawSize:t,groupSizeLimit:e=10}){let r=Z(3,e+1).filter(n=>{let o=Math.ceil(t/n),i=o*n-t,s=Math.ceil(t/o),a=Math.ceil(i/o);return(!i||i<n)&&s===n&&s>=3&&a<2});return{...R,validGroupSizes:r}}function uF({structureOrder:t,matchUpType:e,groupSize:r,drawSize:n,idPrefix:o,isMock:i,uuids:s}){let a=(t-1)*r,c=Z(1+a,r+1+a),u=vf({drawPositions:c}).uniqueMatchUpGroupings??[],p=nU({groupSize:r,drawPositionOffset:a});return u.map(l).sort((f,g)=>(f.roundNumber??1/0)-(g.roundNumber??1/0));function d(f){return p.reduce((g,I,h)=>I.includes(f)?h+1:g,void 0)}function l(f){let g=xf(f),I=d(g),h=[1,n],S=pF({structureOrder:t,drawPositions:f,roundNumber:I,idPrefix:o,uuids:s}),T={matchUpStatus:I?Kt:Ut,matchUpType:e,finishingPositionRange:{winner:h,loser:h},drawPositions:f,roundNumber:I,matchUpId:S};return i&&(T.isMock=!0),T}}function pF({structureOrder:t,drawPositions:e,roundNumber:r,idPrefix:n,uuids:o}){return n?`${n}-${t}-${r}-DP-${e.join("-")}`:o?.pop()||Mt()}function wf(t){let{roundRobinGroupsCount:e,participantsCount:r,cluster:n}=t;if(!lt(r))return{seedBlocks:void 0,...v({result:{error:G},context:{participantsCount:r},stack:"getSeedBlocks"})};let o=Bi(r);if(e){let l=Math.min(e,o),f=[],g=1;for(Z(0,l).forEach(()=>{f.push([g]),g++});g<o;){let I=Z(g,g+l);g+=l,f.push(I)}return{...R,seedBlocks:f}}let i=Z(1,o+1),s=[],a=o/2;for(;a>1;){let l=Ae(i,a),f=l.length;l.forEach((g,I)=>{let h,S=I<f/2,T=I%2===0,A=g[0],P=g[g.length-1];n&&f>4?f===8?h=S?P:A:h=T?A:P:h=S?A:P,ve(g,s)||s.push(h)}),a=a/2}let c=i.filter(l=>!s.includes(l));for(;c.length;)c.length%2===0?s.push(c.pop()):s.push(c.shift());let u=Z(0,20).map(l=>Math.pow(2,l));u.unshift(1);let p=u.indexOf(o),m=0,d=[];return Z(0,p).forEach(l=>{d.push(s.slice(m,m+u[l])),m+=u[l]}),{...R,seedBlocks:d}}function Lf({roundRobinGroupsCount:t,drawSize:e}){let r="getSeedGroups";if(!lt(e))return{seedGroups:void 0,...v({result:{error:G},context:{drawSize:e},stack:r})};if(t){if(!lt(t))return{seedGroups:void 0,...v({context:{roundRobinGroupsCount:t},result:{error:G},stack:r})};let n=1,o=Math.floor(e/t);return{seedGroups:Z(0,o).map(()=>{let s=Z(n,n+t);return n+=t,s})}}else{let{seedBlocks:n}=wf({participantsCount:e,roundRobinGroupsCount:t}),o=0;return{seedGroups:(n||[]).map(s=>(s||[]).map(()=>(o+=1,o)))}}}function Eh({roundRobinGroupsCount:t,participantsCount:e}){if(t){let{validGroupSizes:o}=dp({drawSize:e});if(!o?.map(a=>Math.ceil(e/a))?.includes(t))return v({context:{roundRobinGroupsCount:t},result:{error:G}})}let{seedGroups:r}=Lf({drawSize:e,roundRobinGroupsCount:t}),n=r?.map(o=>Math.min(...o))||[];return{...R,seedingThresholds:n}}function ac(t){if(!t)return 1/0;if(lt(t))return ct(t);let e=t.split("-")[0];return lt(e)?ct(e):1/0}function mF({size:t}){let e=[t],r=t;for(;r/2===Math.floor(r/2);)r=r/2,e.push(r);return e.includes(1)||e.push(1),e.sort(oe),e.reverse(),e}function jR({blockPattern:t,index:e}){let r=0;for(let n of t){if(r===e)return n;let o=0;for(;o<n.length;){if(r===e)return n;r+=1,o++}}}function YR({positioning:t,size:e}){let r=mF({size:e}),n=[],o=[],i=d=>d[0],s=d=>d[d.length-1],a=(d,l)=>(t&&[Bc,ei].includes(t)&&l%2?s(d):i(d))||i(d),c=(d,l)=>{if(d.every(f=>!o.includes(f))){let f=a(d,l);return o.push(f),f}},u=d=>{let l=d.filter(f=>!o.includes(f));if(l.length)return o.push(...l),l},p=(d,l)=>{let f=a(d,l);if(!o.includes(f))return o.push(f),f},m=Z(1,e+1);for(let d of r)if(d===1){let l=Ae(m,2),f=l.map(c).filter(Boolean);f.length&&n.push(f);let g=l.flatMap(u).filter(Boolean);g.length&&n.push(g)}else{let f=Ae(m,d).map(p).filter(Boolean);f.length&&n.push(f)}return{divisions:r,divisionGroupings:n}}function as({provisionalPositioning:t,returnAllProxies:e,appliedPolicies:r,seedingProfile:n,drawDefinition:o,allPositions:i,structure:s}){let a=[];if(!s)return{error:Ao};let{matchUps:c,roundMatchUps:u}=Pt({matchUpFilters:{roundNumbers:[1]},provisionalPositioning:t,structure:s}),{seedAssignments:p}=vr({provisionalPositioning:t,returnAllProxies:e,drawDefinition:o,structure:s}),{positionAssignments:m}=de({structure:s}),d=m?.length,l=p?.length??0,f=[],I=Object.keys(u).map(w=>parseInt(w)).sort((w,x)=>w-x).map(w=>{let x=u[w].map(V=>V.drawPositions).flat(1/0).filter(Boolean),H=x.filter(V=>!f.includes(V));return f=f.concat(...x),H}).filter(w=>w.length).reverse(),h=I.pop(),S=h&&Math.min(...h)-1||0;n=n??r?.seeding?.seedingProfile;let T=h?.length||0,A=I.filter(w=>w.filter(x=>x<=l).length),{stage:P,structureType:y,roundLimit:E}=s,U=y===we,M=!U&&I?.length,N=!U&&P===at&&E,C=A.flat(1/0),D=M?C?.length:0,O=i?d:l,b=vm({drawDefinition:o,structure:s,matchUps:c}),_=b?0:!M&&O||O&&C.length<O&&O-C.length||0;if(N){let w=s?.matchUps?s.matchUps.filter(({roundNumber:H})=>H===s.roundLimit).length:0,x=h.length/w;if(!M){let H=fp(n),V=Ae(h,x),W=1,B=Z(0,V[0].length).map(()=>{let q=Z(W,W+V.length);return W+=V.length,q});({validSeedBlocks:a}=qR({drawPositionBlocks:V,nonRandom:n?.nonRandom,positioning:H,seedGroups:B}))}}else U?{validSeedBlocks:a}=dF({nonRandom:n?.nonRandom,seedingProfile:n,structure:s}):M?a=A.map(w=>({seedNumbers:w,drawPositions:w})):b&&Ae(h,2).map((x,H)=>({drawPositions:[x[0]],seedNumbers:[H+1]})).forEach(x=>a.push(x));if(!U&&!b&&!N){let{blocks:w}=lF({drawPositionOffset:S,seedNumberOffset:D,seedCountGoal:_,seedingProfile:n,baseDrawSize:T});w.forEach(x=>a.push(x))}let F=a.flatMap(w=>w.drawPositions).reduce((w,x)=>h?.includes(x)&&w,!0);return!b&&!M&&!U&&!F?{error:qA,validSeedBlocks:[],isContainer:U,isFeedIn:M}:{isLuckyStructure:b,validSeedBlocks:a,isContainer:U,isFeedIn:M}}function dF({seedingProfile:t,structure:e,nonRandom:r}){let n=e.structures||[],o=n.length,i=Dt({structure:e})?.positionAssignments,s=fp(t),a=i?.length??0,{seedGroups:c}=Lf({roundRobinGroupsCount:o,drawSize:a}),u=n.map(p=>Dt({structure:p}).positionAssignments?.map(m=>m.drawPosition));return qR({drawPositionBlocks:u,positioning:s,seedGroups:c,nonRandom:r})}function qR({drawPositionBlocks:t,positioning:e,seedGroups:r,nonRandom:n}){let o=[],{divisionGroupings:i}=YR({size:r.length,positioning:e}),s=[];return r.forEach((a,c)=>{let u=jR({blockPattern:i,index:c});a.forEach((p,m)=>{let d=c%2?t.length-m-1:m,f=t[d].slice().filter((I,h)=>u.includes(h+1)&&I);e!==ei?f=n?f:sr(f):c%2&&f.reverse();let g=f.find(I=>!s.includes(I));g&&(s.push(g),o.push({drawPositions:[g],seedNumbers:[p]}))})}),{validSeedBlocks:o}}function lF(t){let{drawPositionOffset:e=0,roundRobinGroupsCount:r,seedNumberOffset:n=0,seedingProfile:o,seedCountGoal:i,baseDrawSize:s}=t,a=1,c=[],{seedBlocks:u}=wf({cluster:fp(o)===Bc,participantsCount:s,roundRobinGroupsCount:r});a=0;for(let m of u){if(a+1>i)break;let d=m.map(f=>f+e),l=p(a+1,m.length).map(f=>+f+n);a+=m.length,c.push({drawPositions:d,seedNumbers:l})}return{blocks:c};function p(m,d){return Array.from(new Array(d),(l,f)=>f+m)}}function lp({appliedPolicies:t,drawDefinition:e,seedBlockInfo:r,drawPosition:n,structureId:o,seedNumber:i}){let{structure:s}=st({drawDefinition:e,structureId:o});t||(t=yt({drawDefinition:e}).appliedPolicies);let a=r?.validSeedBlocks;return!a&&s&&(a=as({appliedPolicies:t,drawDefinition:e,structure:s})?.validSeedBlocks),t?.seeding?.validSeedPositions?.ignore?!0:t?.seeding?.validSeedPositions?.strict?(a.find(m=>m.seedNumbers.includes(i))?.drawPositions||[]).includes(n):[].concat(...a.map(u=>u.drawPositions)).includes(n)}function Uh(t){let{provisionalPositioning:e,drawDefinition:r,seedingProfile:n,seedBlockInfo:o,structureId:i,randomize:s}=t,{structure:a}=st({drawDefinition:r,structureId:i}),{seedAssignments:c}=vr({returnAllProxies:t.returnAllProxies,provisionalPositioning:e,drawDefinition:r,structure:a}),{positionAssignments:u}=de({structure:a}),m=u?.filter(x=>x.participantId??x.bye??x.qualifier)?.map(x=>x.drawPosition).filter(Boolean),{appliedPolicies:d}=yt({drawDefinition:r}),g=(o?.validSeedBlocks||a&&as({returnAllProxies:t.returnAllProxies,provisionalPositioning:e,appliedPolicies:d,drawDefinition:r,seedingProfile:n,structure:a})?.validSeedBlocks||[]).filter(x=>x.drawPositions.filter(V=>!m?.includes(V)).length)[0],I=c?.map(x=>x.participantId).filter(Boolean),h=u?.map(x=>x.participantId).filter(Boolean),S=I?.filter(x=>h?.includes(x)),T=I?.filter(x=>!h?.includes(x)),A=c?.filter(x=>T?.includes(x.participantId)),P=c?.filter(x=>!x.participantId),E=(A?.length&&A.length>0?A.length:P?.length??0)&&g?.drawPositions.filter(x=>!m?.includes(x))||[],U=s?sr(E):E,M=[],N=U.map(()=>{let H=w(A,M)?.participantId;return H&&M.push(H),H}).filter(Boolean),C=c?.filter(x=>S?.includes(x.participantId)).map(x=>x.seedNumber),O=(g?.seedNumbers||[]).filter(x=>!C?.includes(x)),b=c?.filter(x=>O.includes(x.seedNumber)).map(x=>x.participantId),_=d?.seeding?.duplicateSeedNumbers;return{nextSeedBlock:g,unplacedSeedParticipantIds:(_!==void 0?_:!0)?N:b,unplacedSeedNumbers:O,unfilledPositions:U,unplacedSeedAssignments:A};function w(x,H){let V=x.filter(Y=>!H.includes(Y.participantId)),W=Math.min(...V.map(Y=>ac(Y.seedValue))),B=V.filter(Y=>ac(Y.seedValue)===W);return sr(B).pop()}}function fp(t){if(typeof t=="string")return t;if(typeof t=="object")return t.positioning}function Gs({provisionalPositioning:t,tournamentRecord:e,drawDefinition:r,seedingProfile:n,participantId:o,seedBlockInfo:i,structureId:s,seedNumber:a,seedValue:c,eventId:u,event:p}){let m="assignSeed",{structure:d}=st({drawDefinition:r,structureId:s}),{positionAssignments:l}=de({structure:d}),f=vr({provisionalPositioning:t,drawDefinition:r,structure:d}).seedAssignments,g=f.map(y=>y.seedNumber),I=ic({drawDefinition:r,participantId:o});if(o&&!I)return v({result:{error:sn},context:{participantId:o},stack:m});let h=p?kt({event:p}).flightProfile?.flights?.length:0,S=h&&h>1,A=l?.find(y=>y.participantId===o)?.drawPosition;if(A&&!lp({drawPosition:A,drawDefinition:r,seedBlockInfo:i,structureId:s,seedNumber:a}))return v({result:{error:Jd},context:{assignedDrawPosition:A},info:"invalid seed position",stack:m});g.includes(a)||f.push({seedNumber:a,seedValue:c});let P;return f.forEach(y=>{y.participantId===o&&y.seedNumber!==a&&(y.participantId=void 0),y.seedNumber===a&&(y.participantId=o,!n?.groupSeedingThreshold&&!S&&(y.seedValue=c??a),P=!0)}),P?(jI({tournamentId:e?.tournamentId,drawDefinition:r,structure:d,eventId:u}),{...R}):v({result:{error:YA},stack:m})}function km({inContextTargetMatchUp:t,drawPositionSideIndex:e,teamParticipantId:r,tournamentRecord:n,drawDefinition:o,matchUp:i,event:s}){let a=t?.sides?.[e]?.sideNumber,c=a&&i.sides?.find(d=>d.sideNumber===a),{extension:u}=ut({element:o,name:mo}),p=u?.value||{},m=J(p[r],!1,!0);if(c)i?.sides?.forEach(d=>{d.sideNumber===a&&(d.lineUp=m)});else{i.sides=[1,2].map(l=>({...i.sides?.find(g=>g.sideNumber===l)??{},sideNumber:l}));let d=i.sides.find(l=>l.sideNumber===a);d&&(d.lineUp=m)}ht({tournamentId:n?.tournamentId,context:"updateSidLineUp",eventId:s?.eventId,drawDefinition:o,matchUp:i})}function Ph(t){let{sourceMatchUp:e}=t,{targetMatchUp:r,structure:n,matchUpsMap:o,drawPosition:i}=t,s=r.roundNumber>1&&r.roundNumber-1,a=ko({structureId:n.structureId,matchUpsMap:o});!e&&i&&(e=a.find(({drawPositions:f,roundNumber:g})=>g===s&&f?.includes(i)));let c=e?.roundPosition,u=c%2?1:-1,p=c+u,m=s&&a.find(({roundNumber:f,roundPosition:g})=>f===s&&g===p),d=m?.matchUpStatus,l=[fe,Me].includes(d);return{pairedPreviousMatchUp:m,pairedPreviousMatchUpIsDoubleExit:l}}function $R({drawPosition:t,drawPositions:e}){let r=!1,n=!!e?.includes(t);return{updatedDrawPositions:n?e||[]:[...e,void 0,void 0].slice(0,2).map(s=>!s&&!n?(n=!0,r=!0,t):s).sort(oe).filter(Boolean),positionAdded:r,positionAssigned:n}}function Nh({structureId:t,matchUpsMap:e,matchUp:r}){let n=r?.roundPosition,o=n%2?1:-1,i=n+o;return{pairedPreviousMatchUp:ko({matchUpsMap:e,structureId:t}).find(({roundNumber:c,roundPosition:u})=>c===r?.roundNumber&&u===i)}}function Dh({inContextDrawMatchUps:t,sourceMatchUpStatus:e,sourceMatchUpId:r,matchUpsMap:n,matchUp:o}){let i=t.find(a=>a.matchUpId===r),{pairedPreviousMatchUp:s}=Nh({structureId:i?.structureId,matchUp:i,matchUpsMap:n});if(i&&s){let a=s?.matchUpId,c=t.find(p=>p.matchUpId===a),u=i?.structureId===c?.structureId?i?.roundPosition<c?.roundPosition&&1||2:i.structureId===c?.structureId&&2||1;o.matchUpStatusCodes=(o.matchUpStatusCodes??[]).map(p=>{let m=er(p)||!isNaN(p)?{code:p}:p;return m.sideNumber===u?{...m,previousMatchUpStatus:e}:m})}}function Vm({inContextDrawMatchUps:t,drawPosition:e,matchUpId:r}){let n=t.filter(({winnerMatchUpId:s,loserMatchUpId:a})=>a===r||s===r).sort((s,a)=>s.roundPosition-a.roundPosition);return t.find(s=>s.matchUpId===r).feedRound?1:n.reduce((s,a,c)=>a.drawPositions?.includes(e)?c+1:s,void 0)}function cc({inContextDrawMatchUps:t,sourceMatchUpStatus:e,tournamentRecord:r,sourceMatchUpId:n,drawDefinition:o,matchUpStatus:i,drawPosition:s,matchUpsMap:a,matchUpId:c,event:u}){let p="assignMatchUpDrawPosition";a||(a=be({drawDefinition:o})),t||(t=re({inContext:!0,drawDefinition:o,matchUpsMap:a}).matchUps??[]);let m=t.find(O=>O.matchUpId===c),d=m?.structureId,l=o?.structures?.find(O=>O.structureId===d);if(!l)return{error:_t};let f=a?.drawMatchUps?.find(O=>O.matchUpId===c),g=f?.drawPositions??[],{positionAdded:I,positionAssigned:h,updatedDrawPositions:S}=$R({drawPosition:s,drawPositions:g}),{positionAssignments:T}=Dt({drawDefinition:o,structure:l}),P=T?.filter(O=>S.includes(O.drawPosition))?.find(({bye:O})=>O),y=f?.matchUpStatus&&[Ot,bt].includes(f.matchUpStatus)&&S.filter(Boolean).length<2;if(i=P&&Ut||i||y&&f.matchUpStatus||f?.matchUpStatus&&[fe,Me].includes(f.matchUpStatus)&&f.matchUpStatus||Kt,f&&I){t=re({inContext:!0,drawDefinition:o,matchUpsMap:a}).matchUps??[];let O=y&&Vm({inContextDrawMatchUps:t,drawPosition:s,matchUpId:c})||void 0;f?.matchUpStatusCodes&&Dh({inContextDrawMatchUps:t,sourceMatchUpStatus:e,sourceMatchUpId:n,matchUpsMap:a,matchUp:f}),Object.assign(f,{drawPositions:S,winningSide:O,matchUpStatus:i}),ht({tournamentId:r?.tournamentId,eventId:m?.eventId,context:p,drawDefinition:o,matchUp:f})}let E=Je({inContextDrawMatchUps:t,inContextMatchUp:m,drawDefinition:o,matchUpId:c}),{targetMatchUps:{winnerMatchUp:U,loserMatchUp:M,loserTargetDrawPosition:N},targetLinks:{loserTargetLink:C}}=E,D=ko({structureId:l.structureId,matchUpsMap:a});if(h&&P){if(U)if([Ut,fe,Me].includes(i)){let O=cc({matchUpId:U.matchUpId,inContextDrawMatchUps:t,tournamentRecord:r,drawDefinition:o,drawPosition:s,matchUpsMap:a});if(O.error)return O}else{let{structureId:O}=U;O!==l.structureId&&console.log("winnerMatchUp in different structure... participant is in different targetDrawPosition")}}else if(U&&m&&!m.feedRound){let{pairedPreviousMatchUpIsDoubleExit:O}=Ph({targetMatchUp:f,drawPosition:s,matchUpsMap:a,structure:l});if(O){let b=cc({matchUpId:U.matchUpId,inContextDrawMatchUps:t,tournamentRecord:r,drawDefinition:o,drawPosition:s,matchUpsMap:a});if(b.error)return b}}if(f?.matchUpType===Bt){let O=t?.find(({matchUpId:F})=>F===f.matchUpId),_=(O?.sides??[]).reduce((F,w,x)=>w.drawPosition===s?x:F,void 0),L=T?.find(F=>F.drawPosition===s)?.participantId;L&&_!==void 0&&km({inContextTargetMatchUp:O,drawPositionSideIndex:_,teamParticipantId:L,tournamentRecord:r,drawDefinition:o,matchUp:f})}if(C?.linkCondition===Bn&&S.filter(Boolean).length===2&&!P&&D.filter(({drawPositions:_,roundNumber:L})=>L===1&&ve(_,S)).every(({matchUpStatus:_})=>[me,mr].includes(_))&&M){let{structureId:_}=M,L=yr({drawPosition:N,tournamentRecord:r,drawDefinition:o,structureId:_,matchUpsMap:a,event:u});if(L.error)return L}return h?{...R}:v({result:{error:La},context:{drawPosition:s},stack:p})}function Mh({inContextDrawMatchUps:t,drawDefinition:e,assignments:r,matchUpsMap:n,structure:o}){let s=zi({drawDefinition:e})?.containedStructures?.[o.structureId]?.map(({structureId:m})=>m)||[];s.push(o?.structureId);let a=r?.map(({drawPosition:m})=>m)||[],c=t?.filter(m=>s.includes(m.structureId)&&Wt(m.drawPositions??[],a).length)??[],u=c.map(({matchUpId:m})=>m),p=n?.drawMatchUps?.filter(m=>u.includes(m.matchUpId))??[];return{drawPositions:a,matchUps:p,targetMatchUps:c}}function Bm({lineUp:t}){if(!Array.isArray(t))return;let e={};return mt(t.flatMap(({collectionAssignments:n})=>n?.map(({collectionId:o,collectionPosition:i})=>[o,i].join("|"))).filter(Boolean)).forEach(n=>{let[o,i]=n.split("|"),s=parseInt(i),{assignedParticipantIds:a}=cp({collectionPosition:s,collectionId:o,lineUp:t});a.forEach(c=>{e[c]||(e[c]=[]),e[c].push({collectionId:o,collectionPosition:s})})}),Object.keys(e).map(n=>({participantId:n,collectionAssignments:e[n]}))}function Tn(t){return`${t} must be an array`}function Hm({lineUp:t,tieFormat:e}){let r=[];if(!Array.isArray(t))return r.push(Tn("lineUp")),{valid:!1,errors:r,error:G};let n=t.every(s=>{if(typeof s!="object")return r.push("lineUp entries must be objects"),!1;let{participantId:a,collectionAssignments:c}=s;return a?typeof a!="string"?(r.push("participantIds must be strings"),!1):Array.isArray(c)?c.every(u=>{if(typeof u!="object")return r.push("collectionAssignments must be objects"),!1;let{collectionPosition:p}=u;return typeof p!="number"?(r.push("collectionPosition must be a number"),!1):!0}):(r.push(Tn("collectionAssignments")),!1):(r.push("Missing participantId"),!1)}),o=mt(t.map(ft)).length===t.length;return o||r.push("Duplicated participantId(s)"),{valid:n&&o,errors:r,error:r.length?G:void 0}}function _i({drawDefinition:t,participantId:e,tieFormat:r,lineUp:n}){if(typeof t!="object")return{error:z};if(typeof e!="string")return{error:te};let o=Hm({lineUp:n,tieFormat:r});if(!o.valid)return o;let{extension:i}=ut({element:t,name:mo}),s=i?.value||{};return s[e]=Bm({lineUp:n}),gt({element:t,extension:{name:mo,value:s}}),ma({drawDefinition:t}),{...R}}function Ff({inContextDrawMatchUps:t,inheritance:e=!0,tournamentRecord:r,drawDefinition:n,matchUpsMap:o,assignments:i,structure:s,event:a}){if(!n)return{error:z};let{drawPositions:c,matchUps:u,targetMatchUps:p}=Mh({inContextDrawMatchUps:t,matchUpsMap:o,assignments:i,structure:s});for(let m of p)m.matchUpType===pn&&(m.sides??[]).forEach((d,l)=>{if(d?.drawPosition&&c?.includes(d.drawPosition)){let f=u.find(({matchUpId:g})=>g===m.matchUpId);if(f?.sides?.[l]){if(delete f.sides[l].lineUp,e===!1){let g=m.tieFormat,I=d.participantId;g&&I&&_i({drawDefinition:n,participantId:I,lineUp:[],tieFormat:g})}ht({tournamentId:r?.tournamentId,context:"resetLineUps",eventId:a?.eventId,drawDefinition:n,matchUp:f})}}});return{...R}}function An({provisionalPositioning:t,inContextDrawMatchUps:e,isQualifierPosition:r,sourceMatchUpStatus:n,tournamentRecord:o,drawDefinition:i,seedingProfile:s,participantId:a,seedBlockInfo:c,drawPosition:u,matchUpsMap:p,structureId:m,event:d}){let l="assignDrawPosition";if(!a&&!r)return v({result:{error:te},stack:l});p=p??be({drawDefinition:i}),e||({matchUps:e}=re({inContext:!0,drawDefinition:i,matchUpsMap:p}));let f=st({drawDefinition:i,structureId:m});if(f.error)return v({result:f,stack:l});let{structure:g}=f;if(!g)return{error:_t};if(Br({drawDefinition:i,structure:g}))return v({result:{error:ze},stack:l});let{seedAssignments:I}=vr({provisionalPositioning:t,drawDefinition:i,structure:g}),S=I?.find(C=>C.participantId===a)?.seedNumber,{appliedPolicies:T}=yt({tournamentRecord:o,drawDefinition:i,structure:g,event:d});if(S&&!lp({seedNumber:S,appliedPolicies:T,drawDefinition:i,seedBlockInfo:c,drawPosition:u,structureId:m}))return v({result:{error:Jd},context:{drawPosition:u},stack:l});let P=de({structure:g}).positionAssignments||[],y=P?.find(C=>C.drawPosition===u);if(!y)return v({result:{error:Ss},context:{drawPosition:u},stack:l});if(P?.map(ft).includes(a))return v({result:{error:ys},context:{drawPosition:u},stack:l});let{containsParticipant:U,containsBye:M}=N(y);if(M){let C=oc({inContextDrawMatchUps:e,tournamentRecord:o,drawDefinition:i,drawPosition:u,structureId:m,matchUpsMap:p,event:d});if(C.error)return v({result:C,stack:l})}if(U&&y.participantId!==a){let{activeDrawPositions:C}=Sa({drawDefinition:i,structureId:m});if(C.includes(u))return v({result:{error:Ou},stack:l});Ff({assignments:[y],inContextDrawMatchUps:e,tournamentRecord:o,drawDefinition:i,matchUpsMap:p,structure:g})}if(y.participantId=a,r&&(y.qualifier=!0),(g?.stageSequence||0)>1||g.stage&&[Ge,ae].includes(g.stage)){let C=g.stage===at?at:tt,b=(i.structures?.find(_=>_?.stage===C&&_?.stageSequence===1)?.seedAssignments??[]).find(_=>_.participantId===a);if(b?.participantId){let{participantId:_,seedNumber:L,seedValue:F}=b;Gs({eventId:d?.eventId,provisionalPositioning:t,tournamentRecord:o,drawDefinition:i,seedingProfile:s,participantId:_,seedNumber:L,seedValue:F,structureId:m,event:d})}}if(g.structureType!==we)fF({provisionalPositioning:t,inContextDrawMatchUps:e,sourceMatchUpStatus:n,tournamentRecord:o,drawDefinition:i,drawPosition:u,matchUpsMap:p,structure:g,event:d});else{hh({positionAssignments:P,tournamentRecord:o,drawDefinition:i,matchUpsMap:p,structure:g});let{drawPositions:C,matchUps:D,targetMatchUps:O}=Mh({assignments:[y],inContextDrawMatchUps:e,drawDefinition:i,matchUpsMap:p,structure:g});if(C&&D?.length===1&&D[0].matchUpType===Bt){let _=(O?.[0].sides??[]).reduce((L,F,w)=>C?.includes(F.drawPosition)?w:L,void 0);km({inContextTargetMatchUp:O[0],teamParticipantId:a,matchUp:D[0],drawPositionSideIndex:_,tournamentRecord:o,drawDefinition:i})}}return fo({tournamentId:o?.tournamentId,drawDefinition:i,structure:g,event:d}),{positionAssignments:P,...R};function N(C){let D=C.bye,O=C.qualifier,b=C.participantId;return{containsBye:D,containsQualifier:O,containsParticipant:b,filled:D||O||b}}}function fF({provisionalPositioning:t,inContextDrawMatchUps:e,sourceMatchUpStatus:r,tournamentRecord:n,drawDefinition:o,drawPosition:i,matchUpsMap:s,structure:a,event:c}){let u={isCollectionMatchUp:!1},{matchUps:p}=Pt({provisionalPositioning:t,matchUpFilters:u,drawDefinition:o,matchUpsMap:s,structure:a,event:c}),{roundMatchUps:m}=Xe({matchUps:p}),{initialRoundNumber:d}=ns({drawPosition:i,matchUps:p}),l=d&&m?.[d].find(f=>f.drawPositions?.includes(i));if(l){let f=cc({matchUpId:l.matchUpId,inContextDrawMatchUps:e,sourceMatchUpStatus:r,tournamentRecord:n,drawDefinition:o,drawPosition:i,matchUpsMap:s});if(f.error)return v({stack:"assignDrawPositionToMatchUps",context:{drawPosition:i},result:f})}return{...R}}function Wm(t){let{participantIdAttributeName:e="participantId",isQualifierPosition:r,positionActionName:n,tournamentRecord:o,drawDefinition:i,participantId:s,drawPosition:a,structureId:c,event:u}=t,p="positionParticipantAction";if(!i)return{error:z};let{inContextDrawMatchUps:m,matchUpsMap:d}=t;d||(d=be({drawDefinition:i}),Object.assign(t,{matchUpsMap:d})),m||({matchUps:m}=re({inContext:!0,drawDefinition:i,matchUpsMap:d}),Object.assign(t,{inContextDrawMatchUps:m}));let{positionAssignments:l}=Dt({drawDefinition:i,structureId:c}),f=l?.find(T=>T.drawPosition===a);if(f?.participantId){let T=f.participantId,A=An({inContextDrawMatchUps:m,tournamentRecord:o,drawDefinition:i,participantId:s,drawPosition:a,structureId:c,matchUpsMap:d,event:u});return A.success?S({removedParticipantId:T}):v({result:A,stack:p})}let g=oc({inContextDrawMatchUps:m,tournamentRecord:o,drawDefinition:i,drawPosition:a,structureId:c,matchUpsMap:d,event:u});if(g.error)return v({result:g,stack:p});let I=g.participantId,h=An({inContextDrawMatchUps:m,isQualifierPosition:r,tournamentRecord:o,drawDefinition:i,participantId:s,drawPosition:a,structureId:c,matchUpsMap:d,event:u});if(!h.success)return v({result:h,stack:p});return S({removedParticipantId:I});function S({removedParticipantId:T}){let{structure:A}=st({drawDefinition:i,structureId:c});ym({drawPositions:[a],structure:A});let P={[e]:s,name:n,drawPosition:a,structureId:c};return qc({drawDefinition:i,positionAction:P}),v({context:{removedParticipantId:T},result:{...R},stack:p})}}function KR({luckyLoserParticipantId:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,structureId:o}){return Wm({positionActionName:"luckyLoserDrawPositionAssignment",participantId:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,structureId:o})}function oU(t){return KR(t)}function zR({alternateParticipantId:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,structureId:o}){return Wm({positionActionName:"alternateDrawPositionAssignment",participantIdAttributeName:"alternateParticipantid",participantId:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,structureId:o})}function iU(t){return zR(t)}function sU({structurePositionAssignments:t,provisionalPositioning:e,tournamentRecord:r,drawDefinition:n,event:o}){if(!n)return{error:z};if(!Array.isArray(t))return{error:G};let i="setPositionAssignments";for(let a of t){let{structureId:c,positionAssignments:u}=a;if(!u)continue;let p=st({drawDefinition:n,structureId:c});if(p.error)return p;let m=p.structure;if(!m)return{error:_t};let d=Dt({structure:m}).positionAssignments?.map(({drawPosition:I})=>I),l=u?.map(({drawPosition:I})=>I);if(Wt(d,l).length!==d?.length)return v({result:{error:G},info:"drawPositions do not match",stack:i});let f=be({drawDefinition:n}),{matchUps:g}=re({inContext:!0,drawDefinition:n,matchUpsMap:f});for(let I of u||[]){let{drawPosition:h,participantId:S,bye:T,qualifier:A}=I;if(T){let P=yr({tournamentRecord:r,drawDefinition:n,drawPosition:h,matchUpsMap:f,structureId:c,structure:m,event:o});if(P?.error)return P}else if(A)u.forEach(P=>{P.drawPosition===h&&(P.qualifier=!0,delete P.participantId,delete P.bye)});else if(S){let P=An({provisionalPositioning:e,inContextDrawMatchUps:g,tournamentRecord:r,drawDefinition:n,participantId:S,drawPosition:h,matchUpsMap:f,structureId:c,event:o});if(P?.error)return P}}fo({tournamentId:r?.tournamentId,drawDefinition:n,structure:m,event:o})}let s=t.map(({structureId:a})=>a);return Rt({tournamentId:r?.tournamentId,eventId:o?.eventId,drawDefinition:n,structureIds:s}),{...R}}function QR({qualifyingParticipantId:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,structureId:o}){return Wm({positionActionName:"qualifierDrawPositionAssignment",participantId:t,isQualifierPosition:!0,tournamentRecord:e,drawDefinition:r,drawPosition:n,structureId:o})}function aU(t){return QR(t)}function XR({tournamentRecord:t,drawDefinition:e,drawPositions:r,structureId:n,event:o}){if(!e)return{error:z};if(!n)return{error:We};if(r?.length!==2)return{error:G,drawPositions:r};let i=be({drawDefinition:e}),{matchUps:s}=re({inContext:!0,drawDefinition:e,matchUpsMap:i}),{structure:a}=st({drawDefinition:e,structureId:n});if(!a)return{error:_t};let c;if(a.structureType===we?c=hF({inContextDrawMatchUps:s,tournamentRecord:t,drawDefinition:e,drawPositions:r,matchUpsMap:i,structure:a,event:o}):c=gF({inContextDrawMatchUps:s,tournamentRecord:t,drawDefinition:e,drawPositions:r,matchUpsMap:i,structure:a,event:o}),c.error)return c;if(ym({structure:a,drawPositions:r}),qc({drawDefinition:e,positionAction:{name:"swapDrawPositionAssignments",drawPositions:r,structureId:n}}),fo({tournamentId:t?.tournamentId,drawDefinition:e,structure:a,event:o}),o.eventType===Kr){let p=Pt({matchUpFilters:{matchUpTypes:[pn]},inContext:!0,structure:a}).matchUps.filter(d=>d.drawPositions?.some(l=>r.includes(l))),m=Pt({structure:a,matchUpFilters:{matchUpTypes:[pn]}}).matchUps;p.forEach(d=>{(d.sides||[]).forEach(l=>{let f=l?.drawPosition;if(r.includes(f)){let g=l.participantId,I=m.find(({matchUpId:S})=>S===d.matchUpId),h=d?.sides?.reduce((S,T,A)=>T.drawPosition===f?A:S,void 0);km({inContextTargetMatchUp:d,drawPositionSideIndex:h,teamParticipantId:g,tournamentRecord:t,drawDefinition:e,matchUp:I,event:o})}})})}return Rt({drawDefinition:e,structureIds:[n]}),{...R}}function gF({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,drawPositions:n,matchUpsMap:o,structure:i,event:s}){let a=i?.positionAssignments.filter(p=>n?.includes(p.drawPosition));if(!a)return{error:G,structure:i,info:"Missing positionAssignments"};if(a.filter(({bye:p})=>p).length===2)return{...R};if(a.filter(({qualifier:p})=>p).length===2)return{...R};let c=a.some(({qualifier:p})=>p);return a.some(({bye:p})=>p)&&!c?JR({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,assignments:a,matchUpsMap:o,structure:i,event:s}):IF({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,assignments:a,matchUpsMap:o,structure:i,event:s})}function JR({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,assignments:n,matchUpsMap:o,structure:i,event:s}){let a=n.find(({bye:f})=>f),c=n.find(({participantId:f})=>f),u=a.drawPosition,{participantId:p,drawPosition:m}=c,{structureId:d}=i,l=su({drawPosition:u,inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,structureId:d,matchUpsMap:o});return l.error||(l=su({drawPosition:m,inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,structureId:d,matchUpsMap:o}),l.error)||(yr({drawPosition:m,tournamentRecord:e,drawDefinition:r,structureId:d,matchUpsMap:o,event:s}),l=An({drawPosition:u,inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,structureId:d,participantId:p,matchUpsMap:o,event:s}),l.error)?l:{...R}}function IF({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,assignments:n,matchUpsMap:o,structure:i,event:s}){let a=Object.assign({},...n.map((c,u)=>{let{drawPosition:p}=c,m={...n[1-u],drawPosition:p};return{[p]:m}}));return i.positionAssignments=i.positionAssignments.map(c=>a[c.drawPosition]||c),Ff({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,matchUpsMap:o,assignments:n,structure:i,event:s}),{...R}}function hF({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,drawPositions:n,matchUpsMap:o,structure:i,event:s}){let a=i.structures?.reduce((p,m)=>{let d=m?.positionAssignments.filter(l=>n?.includes(l.drawPosition));return d&&p.push(...d),p},[]);if(a.filter(({bye:p})=>p).length===2)return{...R};if(a.filter(({qualifier:p})=>p).length===2)return{...R};Ff({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,matchUpsMap:o,assignments:a,structure:i,event:s});let c=a.some(({qualifier:p})=>p);if(a.some(({bye:p})=>p)&&!c)JR({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,assignments:a,matchUpsMap:o,structure:i,event:s});else{let p=J(a,!1,!0);a.forEach((m,d)=>{let l=p[1-d].participantId;m.qualifier=p[1-d].qualifier,m.participantId=l})}return{...R}}function cU(t){return XR(t)}function uU({validation:t=!0,tournamentRecord:e,drawDefinition:r,participantId:n,structureId:o,seedValue:i,event:s}){if(!r)return{error:z};if(!o)return{error:We};let a=(e?.participants??[]).find(l=>l.participantId===n);if(e&&!a)return{error:sn};let{structure:c}=st({drawDefinition:r,structureId:o});if(!c)return{error:_t};if(!(!t||se(i)||i===void 0||i===""||typeof i=="string"&&i.split("-").every(l=>se(l)&&ct(l)>0)))return{error:G};let{seedAssignments:p}=vr({drawDefinition:r,structure:c}),m=p?.map(l=>l.seedNumber),d=p?.find(l=>l.participantId===n);if(d){let l=typeof i=="string"?i.includes("-")&&i.split("-").map(f=>parseInt(f)).join("-")||parseInt(i)>0&&parseInt(i)||"":i&&i>0&&i||"";d.seedValue=l}else{let f={seedNumber:Math.max(0,...m||[])+1,participantId:n};i&&(f.seedValue=i),c.seedAssignments||(c.seedAssignments=[]),c.seedAssignments.push(f)}return jI({tournamentId:e?.tournamentId,eventId:s?.eventId,drawDefinition:r,structure:c}),{...R}}function Ch({drawDefinition:t,structureId:e}){if(!t)return{error:z};let{structure:r}=st({drawDefinition:t,structureId:e}),n=(t?.links||[]).filter(i=>i.source?.structureId===e).map(i=>i.target?.structureId);return{playoffStructures:(t?.structures||[]).filter(i=>n.includes(i.structureId)),structure:r}}function Gf({withStageGrouping:t,stageSequences:e,stageSequence:r,roundTarget:n,stages:o,event:i,stage:s}){if(!i)return{error:St};let a={},c=[];for(let u of i.drawDefinitions||[]){let{structures:p,stageStructures:m}=Cn({withStageGrouping:t,stageSequences:e,drawDefinition:u,stageSequence:r,roundTarget:n,stages:o,stage:s});if(c.push(...p),m)for(let d of Object.keys(m))a[d]||(a[d]=[]),a[d].push(...m[d])}return{structures:c,stageStructures:a}}function Rh({withStageGrouping:t,tournamentRecord:e,stageSequences:r,stageSequence:n,roundTarget:o,stages:i,stage:s}){if(!e)return{error:j};let a={},c=[];for(let u of e.events||[]){let{structures:p,stageStructures:m}=Gf({withStageGrouping:t,stageSequences:r,stageSequence:n,roundTarget:o,stages:i,event:u,stage:s});if(p&&c.push(...p),m)for(let d of Object.keys(m))a[d]||(a[d]=[]),a[d].push(...m[d])}return{structures:c,stageStructures:a}}function qo(t){if(!t?.drawDefinition)return!1;let e=eu(t),r=e?.includesTeamMatchUps,{completedMatchUps:n,pendingMatchUps:o,upcomingMatchUps:i}=e||{};return r&&(n=n?.filter(({matchUpType:a})=>a===Bt),o=o?.filter(({matchUpType:a})=>a===Bt),i=i?.filter(({matchUpType:a})=>a===Bt)),!!(n?.length&&!o?.length&&!i?.length)}function bh(t){let{drawDefinition:e,structureId:r}=t;if(!e)return{error:z};let{playoffStructures:n}=Ch({drawDefinition:e,structureId:r});if(!n?.length)return!1;let o=e?.entries?.filter(c=>c?.entryStatus&&Mr.includes(c.entryStatus))?.length??0,i=0;return(n||[]).reduce((c,u)=>!!((Dt({structure:u}).positionAssignments??[])?.filter(d=>(d.participantId&&i++,d?.bye??d?.participantId)).length&&c),!!n.length)||i===o}function Oh({significantCharacters:t,accessors:e=[],value:r}){let n=[],o=e[0];if(r?.[o]){let s=e.slice(1);if(Array.isArray(r[o]))r[o].forEach(c=>{let u=Oh({accessors:s,significantCharacters:t,value:c});n.push(...u)});else if(r=r[o],s.length){let a=Oh({accessors:s,significantCharacters:t,value:r});n.push(...a)}else i({value:r})}function i({value:s}){if(s&&["string","number"].includes(typeof s)){let a=t?s.slice(0,t):s;n.push(a)}}return n}function ZR({targetParticipantIds:t,policyAttributes:e,idCollections:r,participants:n}){if(!Array.isArray(e))return{error:Zg};if(!Array.isArray(n))return{error:Ba};let o={};return t.forEach(i=>{let s=n.find(c=>c.participantId===i),{values:a}=pU({policyAttributes:e,idCollections:r,participants:n,participant:s});a&&a.forEach(c=>{o[c]||(o[c]=[]),o[c].includes(i)||o[c].push(i)})}),o}function pU({policyAttributes:t,idCollections:e,participants:r,participant:n}){if(!Array.isArray(t))return{error:Zg};if(!n)return{error:Ai};let o=[];return t.forEach(s=>{let{directive:a,groupings:c,key:u,significantCharacters:p}=s||{};if(u){let m=u.split(".");o.push(...Oh({significantCharacters:p,value:n,accessors:m}))}else if(a){let m=s?.includeIds,d=(e?.[a]||[]).filter(l=>!m||m.includes(l));d?.length&&r?.length&&d.forEach(l=>{let f=r.find(g=>g.participantId===l);if(f?.individualParticipantIds?.includes(n.participantId)){let g=f?.participantId;o.push(g)}})}else c&&Object.keys(c).forEach(m=>{c[m].includes(n.participantId)&&o.push(m)})}),{values:mt(o)}}function mU({candidatePositionAssignments:t,participantsWithGroupings:e,policyAttributes:r,idCollections:n}){let o=Object.assign({},...e.map(i=>({[i.participantId]:i})));return t.map(i=>{let s=o[i.participantId],{values:a}=pU({participants:e,policyAttributes:r,idCollections:n,participant:s});return{...i,values:a}})}function eb({participantIdGroups:t,positionAssignments:e,groupsToAvoid:r}){return Object.assign({},...e.filter(n=>n?.participantId).map(n=>{let{drawPosition:o,participantId:i}=n,s=t?t[i]||[]:[],a=!!r.some(c=>s.includes(c));return{[o]:{participantGroups:s,includesGroupsToAvoid:a}}}))}function rb(t){let{unfilledPositions:e,chunkedDrawPositions:r}=t,n=eb(t);return r.map(s=>{let a=e.filter(m=>s.includes(m)),c=i(a),p=a.filter(m=>!c.includes(m)).filter(m=>{let d=tb(m);return!n[d]?.includesGroupsToAvoid});return{unassigned:a,unpaired:c,pairedNoConflict:p}});function i(s){return s.filter(c=>!a(c));function a(c){let u=tb(c);return!s.includes(u)}}}function nb(t){let{unfilledPositions:e,chunkedDrawPositions:r}=t,n=eb(t);return r.map(o=>{let i=e.filter(u=>o.includes(u)),s=i.length===o.length?i:[],a=o.filter(u=>n[u]?.includesGroupsToAvoid).length;return{unassigned:i,unpaired:s,pairedNoConflict:a?[]:i,conflictsCount:a}})}function tb(t){return Number(t%2?t+1:t-1)}function ob({allGroups:t,participantId:e}){return Object.keys(t).filter(r=>t[r].includes(e))}function ib({selectedParticipantGroups:t,participantIdGroups:e,positionAssignments:r,drawPositionChunks:n,unfilledPositions:o,isRoundRobin:i}){let s=n.map(a=>i?nb({groupsToAvoid:t,chunkedDrawPositions:a,participantIdGroups:e,positionAssignments:r,unfilledPositions:o}):rb({groupsToAvoid:t,chunkedDrawPositions:a,participantIdGroups:e,positionAssignments:r,unfilledPositions:o}));if(i){let a=s.map(p=>p.map(m=>m.unassigned).filter(m=>m?.length)).filter(p=>p?.length).sort((p,m)=>(m.length||0)-(p.length||0)),c=s.map(p=>p.map(m=>m.unpaired).filter(m=>m?.length)).filter(p=>p?.length),u=s.map(p=>p.map(m=>m.pairedNoConflict).filter(m=>m?.length)).filter(p=>p?.length).sort((p,m)=>(m.length||0)-(p.length||0));return{unassigned:a,unpaired:c,pairedNoConflict:u}}else{let a=s.map(p=>p.map(m=>m.unassigned).filter(m=>m?.length)).filter(p=>p?.length),c=s.map(p=>p.map(m=>m.unpaired).filter(m=>m?.length)).filter(p=>p?.length),u=s.map(p=>p.map(m=>m.pairedNoConflict).filter(m=>m?.length)).filter(p=>p?.length);return{unassigned:a,unpaired:c,pairedNoConflict:u}}}function _h({positionAssignments:t,participantIds:e}){let r=t.map(n=>n.participantId);return e.filter(n=>!r.includes(n))}function sb({useSpecifiedGroupKey:t=!1,targetParticipantIds:e,largestFirst:r=!0,allGroups:n,groupKey:o}){let i=Object.assign({},...Object.keys(n).map(p=>[p,n[p].filter(m=>e.includes(m))]).filter(p=>p[1].length).map(([p,m])=>({[p]:m}))),s=Object.keys(i).reduce((p,m)=>i[m].length>p?i[m].length:p,0),a=Object.keys(i).filter(p=>i[p].length===s),c=r?en(a):en(Object.keys(i));return o=t&&i[o]?.length?o:c,{participantId:o&&i[o]?en(i[o]):en(e),groupKey:o}}function ab({drawPositionGroups:t,positionAssignments:e}){let r=Object.assign({},...e.map(n=>({[n.drawPosition]:n})));return t.map(n=>n.filter(Boolean).map(o=>r[o]).filter(Boolean).filter(o=>!o.participantId&&!o.bye).map(o=>o.drawPosition)).flat().filter(Boolean)}function cb({candidatePositionAssignments:t,unseededParticipantIds:e,participantIdGroups:r,drawPositionChunks:n,drawPositionGroups:o,pairedPriority:i,allGroups:s,groupKey:a}){let u=o.reduce((M,N)=>N.length>M?N.length:M,0)<=2,p=_h({positionAssignments:t,participantIds:e}),m=ab({positionAssignments:t,drawPositionGroups:o}),{participantId:d,groupKey:l}=sb({targetParticipantIds:p,useSpecifiedGroupKey:u,allGroups:s,groupKey:a}),f=ob({participantId:d,allGroups:s}),g=ib({positionAssignments:t,isRoundRobin:u,selectedParticipantGroups:f,participantIdGroups:r,drawPositionChunks:n,unfilledPositions:m}),{unassigned:I,unpaired:h,pairedNoConflict:S}=g,T=S?.length&&S[0],A=h?.length&&h[0],P=i&&T?T:A,y=i?A:T,E=P?.length&&P||y?.length&&y,U;if(E?.length){let M=Rr(E);U=Rr(M)}else{let M=Rr(I[0]);U=Rr(M)}return{newGroupKey:l,selectedParticipantId:d,targetDrawPosition:U}}function jm({isRoundRobin:t,groupedParticipants:e}){let r=[];return t?e.forEach(n=>{let o=n.map(a=>a.drawPosition),i=vf({drawPositions:o}).uniqueMatchUpGroupings??[],s=Object.assign({},...n.map(a=>({[a.drawPosition]:a})));i.forEach(a=>{ve(s[a[0]].values||[],s[a[1]].values||[])&&(r.push(a),n.conflict=!0)})}):e.forEach(n=>{ve(n[0]?.values||[],n[1]?.values||[])&&(r.push(n),n.conflict=!0)}),r}function ub({positionedParticipants:t,potentialDrawPositions:e,drawPositionGroups:r,avoidanceConflicts:n,isRoundRobin:o}){return n.map(i=>{let s=i.map(c=>c.drawPosition);return i.filter(c=>e.includes(c.drawPosition)).map(c=>{let p=e.filter(m=>!s?.includes(m)).filter(m=>{let d=r.find(T=>T.includes(m)).find(T=>T!==m),l=t.find(T=>T.drawPosition===d),g=jm({isRoundRobin:o,groupedParticipants:[[c,l]]}),h=[t.find(T=>T.drawPosition===m),l],S=jm({isRoundRobin:o,groupedParticipants:[h]});return!g.length&&!S.length});if(p.length)return{drawPosition:c.drawPosition,possibleDrawPositions:p}}).filter(Boolean)}).flat(1)}function dU(t){let{initialPositionAssignments:e,participantsWithGroupings:r,opponentsToPlaceCount:n,unseededByePositions:o,drawPositionGroups:i,policyAttributes:s,idCollections:a,allGroups:c}=t,u=[],p,m=Math.min(...(i||[]).map(T=>T?.length).filter(Boolean)),d=m>2,l=J(e,!1,!0).filter(T=>!T.qualifier),f=e.filter(T=>!T.participantId&&(!T.bye||o?.includes(T.drawPosition))).map(T=>T.drawPosition);Z(0,n).forEach(()=>{let{newGroupKey:T,selectedParticipantId:A,targetDrawPosition:P}=cb({...t,candidatePositionAssignments:l,allGroups:c,groupKey:p});p=T,l.forEach(y=>{y.drawPosition===P&&(y.participantId=A)})});let g=mU({candidatePositionAssignments:l,participantsWithGroupings:r,policyAttributes:s,idCollections:a}),I=Ae(g,m),h=jm({groupedParticipants:I,isRoundRobin:d}),S=0;for(;S<20&&h.length;){let T=ub({positionedParticipants:g,potentialDrawPositions:f,avoidanceConflicts:h,drawPositionGroups:i,isRoundRobin:d});if(T.length){let A=SF({candidatePositionAssignments:l,swapOptions:T});A.error&&console.log({result:A}),g=mU({candidatePositionAssignments:l,participantsWithGroupings:r,policyAttributes:s,idCollections:a}),I=Ae(g,m),h=jm({groupedParticipants:I,isRoundRobin:d}),S++}else S=20}return l.forEach(T=>{if(T.bye&&T.participantId){let A=zg;u.push(A)}if(T.qualifier&&T.participantId){let A=zg;u.push(A)}}),{positionAssignments:l,conflicts:h.length,groupedParticipants:I,errors:u}}function SF({candidatePositionAssignments:t,swapOptions:e}){let r=Rr(e);if(!r)return{error:{message:"No swap options"}};let n=r.drawPosition,o=Rr(r.possibleDrawPositions),i=t.find(u=>u.drawPosition===n),s=t.find(u=>u.drawPosition===o)??{},a={participantId:s?.participantId,qualifier:s?.qualifier,bye:s?.bye},c={participantId:i.participantId,qualifier:i.qualifier,bye:i.bye};return Object.assign(i,a),Object.assign(s,c),{...R}}function pb({provisionalPositioning:t,unseededParticipantIds:e,inContextDrawMatchUps:r,unseededByePositions:n,tournamentRecord:o,drawDefinition:i,seedBlockInfo:s,participants:a,matchUpsMap:c,structureId:u,avoidance:p,drawSize:m,event:d}){if(!p)return{error:ry};let{candidatesCount:l=1,policyAttributes:f,targetDivisions:g}=p,{roundsToSeparate:I}=p,h="randomUnseededSeparation",{structure:S}=st({drawDefinition:i,structureId:u}),{matchUps:T}=Pt({provisionalPositioning:t,matchUpsMap:c,structure:S,event:d});if(g&&gn(g)&&!I){let V=ZM(g)||0,W=T.reduce((B,q)=>q.roundNumber>B?q.roundNumber:B,0);I=W<V?1:W-V+1}let{positionAssignments:A}=de({structure:S}),P=Em({participantsProfile:{convertExtensions:!0},deepCopy:!1,participants:a}).participantsWithGroupings,y=A?.filter(V=>!V.participantId),E=A?.map(V=>V.drawPosition),U=S?.structureType===we,M=U?{structure:S,matchUps:T,allDrawPositions:E,roundsToSeparate:I}:{matchUps:T,allDrawPositions:E,roundsToSeparate:I},{drawPositionGroups:N,drawPositionChunks:C}=U?TF(M):AF(M),D={groupParticipants:a.filter(V=>V.participantType===hr).map(V=>V.participantId),teamParticipants:a.filter(V=>V.participantType===Lt).map(V=>V.participantId),pairParticipants:a.filter(V=>V.participantType===pt).map(V=>V.participantId)},O=ZR({targetParticipantIds:e,policyAttributes:f,idCollections:D,participants:a});if(O.error)return v({result:O,stack:h});let b=Object.assign({},...e.map(V=>{let W=Object.keys(O).filter(B=>(O[B]??[]).includes(V));return{[V]:W}})),_=_h({participantIds:e,positionAssignments:A});if(_.length>(y?.length||0))return{error:ll};let L,F=_.length,w=Z(0,l).map(()=>dU({initialPositionAssignments:A,participantsWithGroupings:P,unseededParticipantIds:e,opponentsToPlaceCount:F,pairedPriority:!1,unseededByePositions:n,participantIdGroups:b,drawPositionChunks:C,drawPositionGroups:N,policyAttributes:f,idCollections:D,allGroups:O,drawSize:m}));if(L=w.reduce((V,W)=>!V||(W.conflicts||0)<(V.conflicts||0)?W:V,void 0),!L||L.conflicts){let V=Z(0,l).map(()=>dU({initialPositionAssignments:A,participantsWithGroupings:P,unseededParticipantIds:e,opponentsToPlaceCount:F,pairedPriority:!0,unseededByePositions:n,participantIdGroups:b,drawPositionChunks:C,drawPositionGroups:N,policyAttributes:f,idCollections:D,allGroups:O,drawSize:m}));L=w.concat(...V).filter(B=>!B.errors?.length).reduce((B,q)=>!B||(q.conflicts||0)<(B.conflicts||0)?q:B,void 0)}if(!L)return{error:Gu};let x=(Dt({structure:S})?.positionAssignments??[]).filter(V=>V.participantId).map(V=>V.participantId),H=L.positionAssignments.filter(V=>!x.includes(V.participantId));for(let V of H)if(V.bye){let W=yr({tournamentRecord:o,drawDefinition:i,seedBlockInfo:s,structureId:u,matchUpsMap:c,event:d,...V});if(W.error)return v({result:W,stack:h})}else if(V.participantId){let W=An({automaticPlacement:!0,inContextDrawMatchUps:r,tournamentRecord:o,drawDefinition:i,seedBlockInfo:s,structureId:u,matchUpsMap:c,event:d,...V});if(W.error)return v({result:W,stack:h,context:{assignment:V}})}return{...R}}function TF(t){let{structure:{structures:e}}=t,r=e.map(n=>n.positionAssignments.map(o=>o.drawPosition));return{drawPositionGroups:r,drawPositionChunks:[r]}}function AF({allDrawPositions:t,roundsToSeparate:e,matchUps:r}){let n=r.filter(d=>d.roundNumber===1).map(d=>d.drawPositions),o=n.flat().sort(oe),i=Math.max(...o),s=t.filter(d=>d>i),a=o.length,u=Z(a===2?1:2,a).filter(d=>d===tm(d)),m=u.slice(0,e||u.length).reverse().map(d=>Ae(o,d));return s.length&&console.log({fedDrawPositions:s}),{drawPositionGroups:n,drawPositionChunks:m}}function mb({provisionalPositioning:t,inContextDrawMatchUps:e,unseededByePositions:r,multipleStructures:n,tournamentRecord:o,drawDefinition:i,seedBlockInfo:s,participants:a,matchUpsMap:c,structureId:u,structure:p,drawSize:m,event:d}){let l="positionUnseededParticipants";p||({structure:p}=st({drawDefinition:i,structureId:u})),u||({structureId:u}=p);let{positionAssignments:f}=de({structure:p}),{seedAssignments:g}=vr({provisionalPositioning:t,drawDefinition:i,structure:p}),I=g?.map(C=>C.participantId).filter(Boolean),{stage:h,stageSequence:S}=p,T=h===at?ut({element:p,name:cn})?.extension?.value:void 0,P=ii({provisionalPositioning:t,drawDefinition:i,stageSequence:S,entryStatuses:Vo,structureId:u,roundTarget:T,stage:h}),E=P.filter(C=>!I?.includes(C.participantId)).map(C=>C.participantId),U=f?.filter(C=>!C.participantId&&!C.bye&&!C.qualifier).map(C=>C.drawPosition);if(!n&&E.length>(U?.length||0))return v({result:{error:ll},context:{unseededParticipantsCount:E.length,unfilledDrawPositionsCount:U?.length},stack:l});let{appliedPolicies:M}=yt({tournamentRecord:o,drawDefinition:i,event:d}),N=M?.[wc];if(p.stage===ae){let C=P.reduce((D,O)=>(D[O.groupingValue]||(D[O.groupingValue]=[]),D[O.groupingValue].push(O.participantId),D),{});Object.keys(C).length&&(N||(N={policyName:"Playoff Avoidance"}),N.policyAttributes||(N.policyAttributes=[]),N.policyAttributes.push({groupings:C}))}return N&&a?pb({provisionalPositioning:t,unseededParticipantIds:E,inContextDrawMatchUps:e,unseededByePositions:r,tournamentRecord:o,drawDefinition:i,seedBlockInfo:s,participants:a,matchUpsMap:c,structureId:u,avoidance:N,drawSize:m,entries:P}):yF({provisionalPositioning:t,unseededParticipantIds:E,inContextDrawMatchUps:e,unfilledDrawPositions:U,multipleStructures:n,tournamentRecord:o,drawDefinition:i,seedBlockInfo:s,structureId:u,matchUpsMap:c,drawSize:m,event:d})}function yF({provisionalPositioning:t,unseededParticipantIds:e,inContextDrawMatchUps:r,unfilledDrawPositions:n,multipleStructures:o,tournamentRecord:i,drawDefinition:s,seedBlockInfo:a,matchUpsMap:c,structureId:u,drawSize:p,event:m}){let d=p>2?sr(n):n.reverse();for(let l of e){let f=d.pop();if(!o||f){let g=An({provisionalPositioning:t,inContextDrawMatchUps:r,tournamentRecord:i,drawDefinition:s,seedBlockInfo:a,participantId:l,drawPosition:f,matchUpsMap:c,structureId:u,event:m});if(g?.error&&console.log("!!!!!",{result:g}),g?.error)return v({result:g,stack:"randomUnseededDistribution"})}}return{...R}}function db(t){let e=t.structure??st(t).structure,r="positionQualifiers",n=[];if(e.stage===Ge)return v({result:{error:Si},stack:r});let{unplacedRoundQualifierCounts:o,positionAssignments:i,roundDrawPositions:s}=EF(t);for(let a of Object.keys(o)){let c=i?.filter(u=>s[a].includes(u.drawPosition)&&!u.participantId&&!u.qualifier&&!u.bye).map(u=>u.drawPosition);if(o[a]>(c||0))return v({result:{error:Sy},context:{unfilledDrawPositions:c},stack:r});Z(0,o[a]).forEach(()=>{let u=Rr(c);n.push(u),i?.forEach(p=>{p.drawPosition===u&&(p.qualifier=!0,delete p.participantId,delete p.bye)})})}return{...R,qualifierDrawPositions:n}}function EF({drawDefinition:t,structure:e,structureId:r}){e||({structure:e}=st({drawDefinition:t,structureId:r})),r||({structureId:r}=e);let{positionAssignments:n}=de({structure:e}),{stage:o,stageSequence:i}=e,{qualifiersCount:s,roundQualifiersCounts:a}=os({drawDefinition:t,stageSequence:i,structureId:r,stage:o}),u=(a?Object.keys(a):[]).map(h=>ct(h)),{matchUps:p}=Pt({structure:e}),{roundProfile:m}=Xe({matchUps:p}),d=Object.assign({},...u.filter(h=>m?.[h]).map(h=>({[h]:m?.[h]?.drawPositions?.filter(Boolean)??[]}))),l=n?.filter(h=>h.qualifier).map(h=>h.drawPosition),f=s-(l?.length??0),g=l?.length;return{unplacedRoundQualifierCounts:Object.assign({},...u.map(h=>{let S=n?.filter(T=>T.qualifier&&d[h]?.drawPositions?.includes(T.drawPosition)).map(T=>T.drawPosition);return{[h]:(a?.[h]??0)-(S?.length??0)}})),unplacedQualifiersCount:f,placedQualifiersCount:g,roundQualifiersCounts:a,positionAssignments:n,roundDrawPositions:d,qualifiersCount:s}}function lU({provisionalPositioning:t,inContextDrawMatchUps:e,tournamentRecord:r,appliedPolicies:n,validSeedBlocks:o,drawDefinition:i,seedingProfile:s,seedBlockInfo:a,participants:c,groupsCount:u,structureId:p,matchUpsMap:m,structure:d,event:l}){let f=[],g=[],I=0;if(d||({structure:d}=st({drawDefinition:i,structureId:p})),p||(p=d?.structureId),n||(n=yt({drawDefinition:i}).appliedPolicies),!o){let h=d&&as({provisionalPositioning:t,appliedPolicies:n,drawDefinition:i,seedingProfile:s,structure:d});h?.error&&g.push(h.error),o=h?.validSeedBlocks}return u=u??o?.length??0,Z(0,u).forEach(()=>{if(I<(u||0)){let h=UF({provisionalPositioning:t,inContextDrawMatchUps:e,tournamentRecord:r,drawDefinition:i,seedingProfile:s,seedBlockInfo:a,participants:c,structureId:p,matchUpsMap:m,event:l});h?.success&&(I++,f.push(...h.seedPositions??[])),h.error&&g.push({seedPositionError:h.error})}}),g.length?{error:g}:{...R,seedPositions:f}}function UF({provisionalPositioning:t,inContextDrawMatchUps:e,tournamentRecord:r,drawDefinition:n,seedingProfile:o,seedBlockInfo:i,participants:s,structureId:a,matchUpsMap:c,event:u}){let{unplacedSeedParticipantIds:p,unfilledPositions:m}=Uh({provisionalPositioning:t,randomize:!0,drawDefinition:n,seedingProfile:o,seedBlockInfo:i,structureId:a,event:u}),{appliedPolicies:d}=yt({drawDefinition:n}),{avoidance:l}=d??{};l&&s&&p?.length>2;let f=[];for(let g of p){let I=m.pop();if(!I)return{error:Ts};f.push(I);let h=An({provisionalPositioning:t,inContextDrawMatchUps:e,tournamentRecord:r,drawDefinition:n,seedingProfile:o,participantId:g,seedBlockInfo:i,drawPosition:I,matchUpsMap:c,structureId:a,event:u});if(!h.success)return h}return{...R,seedPositions:f}}function lb({provisionalPositioning:t,drawDefinition:e,structure:r}){let{positionAssignments:n}=de({structure:r}),{seedAssignments:o}=vr({provisionalPositioning:t,drawDefinition:e,structure:r}),i=Object.assign({},...(o||[]).filter(s=>s.participantId).map(s=>({[s.participantId]:s})));return n?.map(s=>i[s.participantId]?{...s,seedNumber:i[s.participantId].seedNumber,seedValue:i[s.participantId].seedValue}:"").filter(Boolean)}function fb({orderedSortedFirstRoundSeededDrawPositions:t,validSeedBlocks:e,byesToPlace:r}){let n=[];e.forEach(i=>{if(r-n.length>i.drawPositions.length)n.push(...i.drawPositions);else{let a=fU(Ae(i.drawPositions,2)),c,u=t[n.length];for(;c=kf(a,u);)n.push(c),u=t[n.length]}});let o=n.map(i=>Array.isArray(i)?sr(i):i).flat(1/0);return aI(r)&&e.map(s=>s.seedNumbers[0]).includes(r)?t:o}function kf(t,e){if(Array.isArray(t)&&t.length!==2)return t.pop();if(!Array.isArray(t[0]))return t.includes(e)?t.indexOf(e)?t.pop():t.shift():Math.round(Math.random())?t.pop():t.shift();let r=t[0].flat(1/0).length,n=t[1].flat(1/0).length;if(r===n){let o=t[0].flat(1/0).includes(e)?t[0]:t[1];return kf(e?o:t[Math.round(Math.random())],e)}return r<n?kf(t[1],e):kf(t[0],e)}function fU(t){let e=Math.floor(t.length/2);return t.length>2?[fU(t.slice(0,e)),fU(t.slice(e))]:t}function Ib({provisionalPositioning:t,relevantMatchUps:e,appliedPolicies:r,drawDefinition:n,seedingProfile:o,seedBlockInfo:i,byesToPlace:s,structure:a}){i||(i=as({provisionalPositioning:t,appliedPolicies:r,drawDefinition:n,seedingProfile:o,structure:a}));let{isFeedIn:c,isLuckyStructure:u,isContainer:p}=i,{validSeedBlocks:m}=i;r?.seeding?.containerByesIgnoreSeeding&&(m=[]);let d=lb({provisionalPositioning:t,drawDefinition:n,structure:a})??[],l=mt([].concat(...e.map(P=>P.drawPositions))),f=d.filter(P=>l.includes(P.drawPosition)),g=(P,y)=>ac(P.seedValue)-ac(y.seedValue),h=m.reduce((P,y)=>{let E=f.filter(U=>y.drawPositions?.includes(U.drawPosition)).sort(g);return P.concat(...E)},[]).map(P=>P.drawPosition),S=fb({orderedSortedFirstRoundSeededDrawPositions:h,validSeedBlocks:m,byesToPlace:s}),T=gb({orderedSeedDrawPositions:h,relevantMatchUps:e}).slice(0,s),A=gb({orderedSeedDrawPositions:S,relevantMatchUps:e}).slice(0,s);return{strictSeedOrderByePositions:T,blockSeedOrderByePositions:A,isLuckyStructure:u,positionedSeeds:d,isContainer:p,isFeedIn:c}}function gb({orderedSeedDrawPositions:t,relevantMatchUps:e}){let n=e.map(i=>i.drawPositions).map(i=>i?.sort((s,a)=>s-a)).filter(i=>i?.[0]+1===i?.[1]);return t.map(i=>n.find(s=>s?.includes(i))).filter(Boolean).map(i=>i?.reduce((s,a)=>t.includes(a)?s:a,void 0)).filter(Boolean)}function hb({provisionalPositioning:t,seedOrderByePositions:e,isLuckyStructure:r,appliedPolicies:n,drawDefinition:o,seedLimit:i,structure:s,isFeedIn:a}){let c=n?.seeding?.seedingProfile,u=s.stage===at,{positionAssignments:p}=de({structure:s}),m=p?.filter(_=>_.participantId).map(_=>_.drawPosition),d={isCollectionMatchUp:!1},{matchUps:l,roundMatchUps:f}=Pt({provisionalPositioning:t,matchUpFilters:d,structure:s}),g=f?.[1]||[],I=s.structureType===we?l:g,h=mt([].concat(...I.map(_=>_.drawPositions))),S=Math.min(...h)-1,T=m?.filter(_=>h.includes(_)),A=_=>{let L=Math.ceil(_.length/2),F=[_.slice(0,L),_.slice(L)],w=F.map(k=>[].concat(...k.flat(1/0)).length),x=Math.min(...w.flat(1/0)),H=Math.max(...w.flat(1/0)),V=w.indexOf(H),W=x!==H,B=sr(F),[q,Y]=!x||W?[F[V],F[1-V]]:[B[0],B[1]];return{greaterHalf:q,lesserHalf:Y}},P=_=>{let{greaterHalf:L,lesserHalf:F}=A(_),{greaterHalf:w,lesserHalf:x}=A(L),V=sr(w.flat(1/0)).pop(),W=w.flat().filter(q=>q!==V);return{newlyFilteredChunks:[...F,...x,W],drawPosition:V}},y=_=>!e.includes(_),E=_=>!T?.includes(_),U=_=>{let F=Ae(_.sort(oe),Math.ceil(_.length/4)).map(H=>H.filter(E)),w=[].concat(...F.flat(1/0)).length,x=[];for(let H=0;H<w;H++){let{newlyFilteredChunks:V,drawPosition:W}=P(F);x.push(W),F=V}return x},{validSeedBlocks:M}=as({provisionalPositioning:t,allPositions:!0,appliedPolicies:n,drawDefinition:o,structure:s}),N=M?.map(_=>_.drawPositions?.map(L=>L+S)),C;if(a){let _=h.length,{seedBlocks:L}=wf({cluster:fp(c)===Bc,participantsCount:_});C=L.map(w=>w.map(x=>x+S)).map(U).filter(w=>w.length)}else u?C=N?.map(_=>_.filter(E)):C=N?.map(U).filter(_=>_.length);let D=I.map(_=>_.drawPositions).map(_=>_?.sort((L,F)=>L-F)).filter(_=>_?.[0]+1===_?.[1]),O=_=>D.reduce((L,F)=>F.includes(_)?F.reduce((w,x)=>x!==_?x:w,void 0):L,void 0),b=C.map(_=>_.map(O)).flat(1/0).filter(E).filter(y).filter(Boolean);if(u&&!s.structures){let _=i%4,L=b.slice(0,_),F=f[s.roundLimit]?.length,w=Ae(b.slice(_),F).map(sr).flat();b=L.concat(w)}return{unseededByePositions:b}}function Sb({provisionalPositioning:t,drawDefinition:e,matchUpsMap:r,structure:n,event:o}){let i={isCollectionMatchUp:!1},{matchUps:s,roundMatchUps:a}=Pt({afterRecoveryTimes:!1,provisionalPositioning:t,drawDefinition:e,matchUpFilters:i,matchUpsMap:r,structure:n,event:o}),c=a?.[1]||[],u=n?.structureType===we,p=u?s:c,m=u?n?.structures?.length||0:s.length,{structureId:d,stage:l,stageSequence:f}=n,g=ii({entryStatuses:Mr,provisionalPositioning:t,drawDefinition:e,stageSequence:f,structureId:d,stage:l}),{qualifiersCount:I}=os({provisionalPositioning:t,drawDefinition:e,stageSequence:f,structureId:d,stage:l}),h=g.length+I,{positionAssignments:S,unassignedPositions:T}=de({structure:n}),A=T?.map(N=>N.drawPosition),P=S?.filter(N=>N.bye).length,y=S?.filter(N=>N.bye).map(N=>N.drawPosition),E=p.map(N=>N.drawPositions).filter(N=>N?.reduce((C,D)=>!y?.includes(D)&&C,!0)).flat(1/0).filter(N=>A?.includes(N)),U=S?.length,M=U?U-h:0;return M>m&&n.stageSequence===1&&n.stage!==Ge&&(M=m),{placedByes:P,byesCount:M,relevantMatchUps:p,placedByePositions:y,roundMatchUps:a,positionsToAvoidDoubleBye:E}}function gU({provisionalPositioning:t,tournamentRecord:e,appliedPolicies:r,drawDefinition:n,seedBlockInfo:o,seedingProfile:i,matchUpsMap:s,structureId:a,structure:c,seedLimit:u,seedsOnly:p,event:m}){c||({structure:c}=st({drawDefinition:n,structureId:a})),a||(a=c?.structureId);let d=!(c?.structures??c?.stage===at),{byesCount:l,placedByes:f,relevantMatchUps:g}=Sb({provisionalPositioning:t,drawDefinition:n,matchUpsMap:s,structure:c,event:m}),I=l-(f||0);if(I<=0)return{...R};let{strictSeedOrderByePositions:h,blockSeedOrderByePositions:S,isLuckyStructure:T,isFeedIn:A}=Ib({provisionalPositioning:t,relevantMatchUps:g,appliedPolicies:r,drawDefinition:n,seedingProfile:i,seedBlockInfo:o,byesToPlace:I,structure:c}),P=c?.structureType&&[we,Xu].includes(c.structureType)&&r?.seeding?.containerByesIgnoreSeeding,y=d&&S?.length?S:h,{unseededByePositions:E}=hb({provisionalPositioning:t,seedOrderByePositions:y,isLuckyStructure:T,appliedPolicies:r,drawDefinition:n,seedLimit:u,structure:c,isFeedIn:A}),U=D=>D%2,M=(D,O)=>(D||[]).every(b=>U(b)?O!==b+1:O!==b-1),N=[].concat(...y);if(!p)for(;E.length;){let D=E.find(O=>M(N,O));D?(N.push(D),E=E.filter(O=>O!==D)):(N.push(...E),E=[])}P&&(N=sr(N),Tr({ignoreSeededByes:P})&&console.log({byePositions:N}));let C=N.slice(0,I);for(let D of C){let O=yr({provisionalPositioning:t,tournamentRecord:e,drawDefinition:n,drawPosition:D,matchUpsMap:s,structureId:a,structure:c,event:m});if(O?.error)return O}return{...R,unseededByePositions:E,byeDrawPositions:C}}function uc({applyPositioning:t=!0,provisionalPositioning:e,inContextDrawMatchUps:r,multipleStructures:n,placeByes:o=!0,tournamentRecord:i,appliedPolicies:s,placementGroup:a,drawDefinition:c,seedingProfile:u,structureId:p,matchUpsMap:m,seedLimit:d,seedsOnly:l,drawType:f,drawSize:g,event:I}){let h=[];t||(Yy(),c=J(c,!1,!0));let S=_=>(t||Nl(),v({result:_,stack:"automatedPositioning"})),T=_=>(t||Nl(),_),A=st({drawDefinition:c,structureId:p});if(A.error)return S(A);let P=A.structure;if(!P)return{error:_t};s||(s=yt({drawDefinition:c,structure:P,event:I})?.appliedPolicies);let{qualifiersCount:y}=os({stageSequence:P.stageSequence,provisionalPositioning:e,stage:P.stage,drawDefinition:c,structureId:p}),E=Vo;if(!ii({stageSequence:P.stageSequence,provisionalPositioning:e,stage:P.stage,placementGroup:a,drawDefinition:c,entryStatuses:E,structureId:p})?.length&&!y)return T({...R});m=m??be({drawDefinition:c}),r||({matchUps:r}=re({inContext:!0,drawDefinition:c,matchUpsMap:m}));let M=[],N=as({provisionalPositioning:e,appliedPolicies:s,drawDefinition:c,seedingProfile:u,structure:P});if(N.error)return N;let{validSeedBlocks:C}=N;h.push({validSeedBlocks:C});let D=i?$t({withIndividualParticipants:!0,tournamentRecord:i})?.participants:[];if(fp(P.seedingProfile||u)===ei){let _=o?gU({provisionalPositioning:e,tournamentRecord:i,appliedPolicies:s,drawDefinition:c,seedBlockInfo:N,matchUpsMap:m,structure:P,seedLimit:d,seedsOnly:l,event:I}):void 0;if(_?.error)return S(_);M=_.unseededByePositions,h.push({action:"positionByes",unseededByePositions:M});let L=P.seedingProfile?{positioning:P.seedingProfile}:u;if(_=lU({seedingProfile:L,provisionalPositioning:e,inContextDrawMatchUps:r,tournamentRecord:i,appliedPolicies:s,validSeedBlocks:C,drawDefinition:c,seedBlockInfo:N,participants:D,matchUpsMap:m,structure:P,event:I}),_.error)return S(_);h.push({seedPositions:_.seedPositions,action:"positionSeedBlocks"})}else{if(f!==Mi){let L=P.seedingProfile?{positioning:P.seedingProfile}:u,F=lU({seedingProfile:L,provisionalPositioning:e,inContextDrawMatchUps:r,tournamentRecord:i,appliedPolicies:s,validSeedBlocks:C,drawDefinition:c,seedBlockInfo:N,participants:D,matchUpsMap:m,structure:P,event:I});if(F.error)return S(F);h.push({action:"positionSeedBlocks",seedPositions:F.seedPositions})}let _=o?gU({provisionalPositioning:e,tournamentRecord:i,appliedPolicies:s,drawDefinition:c,seedBlockInfo:N,matchUpsMap:m,structure:P,seedLimit:d,seedsOnly:l,event:I}):void 0;if(_?.error)return S(_);M=_?.unseededByePositions,h.push({action:"positionByes",byeDrawPositions:_?.byeDrawPositions,unseededByePositions:M})}let O={};if(!l){let _=db({inContextDrawMatchUps:r,tournamentRecord:i,appliedPolicies:s,validSeedBlocks:C,drawDefinition:c,seedBlockInfo:N,participants:D,matchUpsMap:m,structure:P});if(_.error||(_.conflicts&&(O.qualifierConflicts=_.conflicts),h.push({action:"positionQualifiers",qualifierDrawPositions:_.qualifierDrawPositions}),_=mb({provisionalPositioning:e,inContextDrawMatchUps:r,unseededByePositions:M,multipleStructures:n,tournamentRecord:i,drawDefinition:c,seedBlockInfo:N,participants:D,matchUpsMap:m,structureId:p,structure:P,drawSize:g,event:I}),_.error))return S(_);_.conflicts&&(O.unseededConflicts=_.conflicts),h.push({action:"positionUnseededParticipants"})}let{positionAssignments:b}=Dt({drawDefinition:c,structure:P});return Rt({drawDefinition:c,structureIds:[p]}),t||Nl(),{positionAssignments:b,conflicts:O,...R,positioningReport:h}}function pc(t){let{applyPositioning:e=!0,provisionalPositioning:r,tournamentRecord:n,drawDefinition:o,seedingProfile:i,structureId:s,placeByes:a,seedsOnly:c,event:u}=t;if(!u)return{error:Ir};if(!o)return{error:fr};if(!qo({drawDefinition:o,structureId:s})&&!r)return{error:Xd};let m=Ch({drawDefinition:o,structureId:s}).playoffStructures?.sort((f,g)=>$l(f)-$l(g)),d=[],l=[];if(m)for(let f of m){let{structureId:g}=f,I=uc({structureId:g,provisionalPositioning:r,applyPositioning:e,tournamentRecord:n,drawDefinition:o,seedingProfile:i,placeByes:a,seedsOnly:c});if(I.error)return I;I.positionAssignments&&d.push({positionAssignments:I.positionAssignments,structureId:g}),I.positioningReport&&l.push(I.positioningReport)}return{...R,structurePositionAssignments:d,positioningReports:l}}function IU({drawDefinition:t,orderMap:e}){return t?((typeof e!="object"||!Object.values(e).every(r=>lt(r)))&&v({result:{error:G},context:{orderMap:e}}),t.structures||(t.structures=[]),t.structures.forEach(r=>{let n=e[r.structureId];n&&(r.structureOrder=n)}),t.structures.sort((r,n)=>ja(r.structureOrder)-ja(n.structureOrder)),{...R}):{error:z}}function au({drawDefinition:t}){let e=t.structures??[],r=t.links??[],n=new Map,o=I=>{let h=n.get(I)||n.set(I,{drawSources:[],drawTargets:[],progeny:[],sources:[],targets:[]})&&n.get(I);if(h&&!h?.stage){let S=e.find(T=>T.structureId===I);h.stage=S?.stage}return h},i={},s={},a=r.map(I=>{let h=I.source.structureId,S=I.target.structureId,T=o(h),A=o(S);return[Fo,rn,Ju,ei].includes(I.target.feedProfile)?(T?.targets.push(S),A?.sources.push(h)):I.target.feedProfile===Wr&&(A?.drawSources.push(h),T?.drawTargets.push(S)),s[S]=s[S]||I.target.feedProfile===Wr,i[S]=mt([...i[S]||[],h]).filter(Boolean),[I.source.structureId,I.target.structureId]});for(let I of n.keys()){let h=n.get(I);if(h){let S=h.targets??[];for(;S.length;){let T=S.pop(),A=T&&n[T];A?.targets?.length?S.push(...A.targets):A&&(h.rootStage=A.stage)}if(h.rootStage||(h.rootStage=h.stage),!h.targets?.length){let T=h.sources??[];for(;T.length;){let A=T.pop(),P=A&&n[A];if(P?.sources?.length){for(let y of P.sources)h.progeny?.includes(y)||h.progeny?.push(y);T.push(...P.sources)}}}}}let c=0;for(let I of n.keys()){let h=n.get(I);if(h&&h.rootStage===at){let S=[h.drawTargets?.[0]],T=0;for(;S.length;){T+=1;let A=S.pop(),P=A?n.get(A):void 0;P?.drawTargets?.length&&S.push(P.drawTargets[0])}h.distanceFromMain=T,T>c&&(c=T)}}let u=a.length;Z(0,Math.ceil(u/2)).forEach(()=>{a=Z(0,u).map(I=>{let h=a[I],S=a.reduce((T,A)=>ve(h,A)?T.concat(...A):T,[])||[];return mt(h.concat(...S))})});let p=a[0],m=(I,h)=>Wt(I,h).length===I.length,d=a.slice(1).reduce((I,h)=>I&&m(h,p),!0),l=[p].filter(Boolean),f=[p].filter(Boolean);e.forEach(I=>{let{structureId:h,stage:S}=I;l.find(A=>A.includes(h))||(l.push([h]),S!==ke&&f.push([h]))});let g=d&&f.length===1;return!r?.length&&e.length===1&&o(e[0].structureId),{structureProfiles:Object.fromEntries(n),allStructuresLinked:g,maxQualifyingDepth:c,sourceStructureIds:i,hasDrawFeedProfile:s,structureGroups:l}}function vh({drawDefinition:t}){let{maxQualifyingDepth:e,structureProfiles:r}=au({drawDefinition:t});for(let n of t.structures){let o=r[n.structureId];o.distanceFromMain&&(n.stageSequence=e+1-o.distanceFromMain)}return{...R}}function li(t){let{duplicateValues:e=!0,creationTime:r=!0,removePriorValues:n,timeItem:o,element:i}=t;if(!o)return{error:Il};if(!i)return{error:et,info:sm};let s=o&&Object.keys(o),a=["itemType","itemValue"];if(!(a.filter(p=>s.includes(p)).length===a.length))return{error:gl};if(!i.timeItems)i.timeItems=[];else{let{itemType:p,itemSubTypes:m,itemValue:d}=o,l=p&&_n({itemSubTypes:m,itemType:p,element:i})?.timeItem;if(l&&JSON.stringify(l?.itemValue)===JSON.stringify(d)&&!e)return{...R}}if(o.itemSubTypes&&!o.itemSubTypes.length&&delete o.itemSubTypes,r){let p=new Date().toISOString();Object.assign(o,{createdAt:p})}return n&&(i.timeItems=i.timeItems.filter(({itemType:p})=>o.itemType!==p)),n&&!o.itemValue||i.timeItems.push(o),{...R}}function Vf({creationTime:t=!0,removePriorValues:e,tournamentRecord:r,duplicateValues:n,participantId:o,timeItem:i}){if(!r)return{error:j};if(!o)return{error:te};let s=Mo({tournamentRecord:r,participantId:o});return s.error?s:li({element:s.participant,removePriorValues:e,duplicateValues:n,creationTime:t,timeItem:i})}function vi(t){let{removePriorValues:e,tournamentRecord:r,duplicateValues:n,creationTime:o,timeItem:i}=t;return r?li({element:r,removePriorValues:e,duplicateValues:n,creationTime:o,timeItem:i}):{error:j}}function xi(t){let{removePriorValues:e,duplicateValues:r,creationTime:n,timeItem:o,event:i}=t;return i?li({removePriorValues:e,duplicateValues:r,element:i,creationTime:n,timeItem:o}):{error:Ir}}function Bf({tournamentRecord:t,drawDefinition:e,structure:r,link:n}){if(!t)return{error:j};if(!e)return{error:z};let o=PF({tournamentId:t.tournamentId,drawDefinition:e,structure:r,link:n});if(o.error)return o;let s={itemType:"attachQualifyingStructures",itemValue:{structureId:r.structureId,drawId:e.drawId}};return vi({tournamentRecord:t,timeItem:s}),o}function PF({drawDefinition:t,tournamentId:e,structure:r,eventId:n,link:o}){if(!t)return{error:z};if(!r)return{error:Ao};if(!o)return{error:tl};let i=o.target.structureId,s=st({drawDefinition:t,structureId:i});if(s.error)return v({stack:"attachQualifyingStructure",context:{targetStructureId:i},result:s});t.structures||(t.structures=[]),t.links||(t.links=[]),t.structures.push(r),t.links.push(o),vh({drawDefinition:t});let a=Pt({structure:r})?.matchUps||[];return lo({drawDefinition:t,tournamentId:e,matchUps:a,eventId:n}),Rt({drawDefinition:t,structureIds:[r.structureId]}),{...R}}function hU({drawDefinition:t,structureDetails:e}){if(!Array.isArray(e))return{error:G};if(!t)return{error:z};let r=Object.assign({},...e.map(n=>{if(!Ct(n))return;let{structureId:o,structureName:i}=n||{};if(!(!o||!i))return{[o]:i}}).filter(Boolean));if(!Object.values(r).length)return{error:et};for(let n of t.structures||[]){let o=r[n.structureId];o&&(n.structureName=o)}return{...R}}function Hf({drawDefinition:t,timeItem:e}){if(!t)return{error:fr};if(!e)return{error:Il};let r=e&&Object.keys(e),n=["itemType","itemValue"];if(!(n.filter(s=>r.includes(s)).length===n.length))return{error:gl};t.timeItems||(t.timeItems=[]);let i=new Date().toISOString();return Object.assign(e,{createdAt:i}),t.timeItems.push(e),ma({drawDefinition:t}),{...R}}function SU({tournamentRecord:t,drawDefinition:e,structureId:r,event:n,force:o}){if(typeof r!="string")return{error:G};if(!e)return{error:z};if(!r)return{error:We};let i=e.structures??[],s=[],a=i.find(P=>P.structureId===r);if(!a)return{error:_t};if(Pt({structure:a}).matchUps.some(({score:P})=>he({score:P}))){let P=yt({tournamentRecord:t,drawDefinition:e,structure:a,event:n})?.appliedPolicies;if(!(o??P?.[Mn]?.allowDeletionWithScoresPresent?.structures))return{error:Ul}}let p=i.find(({stage:P,stageSequence:y})=>P===tt&&y===1),m=r===p?.structureId,d=i.filter(({stage:P})=>P===at).map(Dr("structureId"));if(m&&!d.length)return{error:wA};let l=i.map(Dr("structureId")),f=[],g=P=>e.links?.map(y=>y.source.structureId===P&&y.target.structureId!==p?.structureId&&y.target.structureId).filter(Boolean)??[],I=P=>e.links?.map(y=>d.includes(y.source.structureId)&&y.target.structureId===P&&y.source.structureId).filter(Boolean)??[],h=d.includes(r),S=new Map;l.forEach(P=>S.set(P,h?I(P):g(P)));let T=m?S.get(r):[r];for(;T?.length;){let P=T.pop(),{structure:y}=st({structureId:P,drawDefinition:e}),{matchUps:E}=Pt({structure:y}),U=lm(E);f.push(...U),e.links=e.links?.filter(N=>N.source.structureId!==P&&N.target.structureId!==P)??[],(!m||m&&d.length||P!==r)&&(e.structures=(e.structures??[]).filter(N=>(P&&P===N.structureId&&s.push(P),N.structureId!==P)));let M=P&&S.get(P)?.filter(N=>N!==p?.structureId||r===p.structureId);M?.length&&T.push(...M)}let{matchUps:A}=re({drawDefinition:e});if(A?.forEach(P=>{P.winnerMatchUpId&&f.includes(P.winnerMatchUpId)&&delete P.winnerMatchUpId,P.loserMatchUpId&&f.includes(P.loserMatchUpId)&&delete P.loserMatchUpId}),m){let P=(p.matchUps??[])?.map(Dr("matchUpId"));f.push(...P),p.positionAssignments=[],p.seedAssignments=[],p.matchUps=[],p.extensions&&(p.extensions=[])}return h&&vh({drawDefinition:e}),Rn({tournamentId:t?.tournamentId,matchUpIds:f,action:"removeStructure",eventId:n?.eventId,drawDefinition:e}),Rt({drawDefinition:e,eventId:n?.eventId}),{...R,removedMatchUpIds:f,removedStructureIds:s}}function gp({stageSequence:t=1,drawDefinition:e,drawSize:r,stage:n}){if(!e)return{error:z};if(!gf({drawDefinition:e,stage:n}))return{error:Si};let o=QC({drawDefinition:e,stage:n}),{qualifiersCount:i}=os({drawDefinition:e,stageSequence:t,stage:n}),s=o+i;if(r<s)return{error:Kg};let{entryProfile:a}=uf({attributes:[{[n]:{drawSize:r}}],drawDefinition:e});return Rt({drawDefinition:e}),{...R,entryProfile:a}}function xh({qualifiersCount:t=0,drawDefinition:e,stage:r}){return e?gf({drawDefinition:e,stage:r})?r!==tt?{error:Kg,info:"qualifiersCount can only be set for main stage"}:(uf({attributes:[{[r]:{qualifiersCount:t}}],drawDefinition:e}),Rt({drawDefinition:e}),{...R}):{error:Si}:{error:z}}function Tb({drawDefinition:t,drawSize:e}){if(!t)return{error:z};let r=gp({stage:ke,stageSequence:1,drawDefinition:t,drawSize:e});return r.error?r:(Rt({drawDefinition:t}),{...R})}function TU(t){return Tb(t)}function AU({tournamentRecord:t,drawDefinition:e,participantId:r,structureId:n}){let o="removeSeededParticipant";if(!t)return{error:j};if(!e)return{error:z};let i=(e.structures??[]).find(a=>a.structureId===n);return i?!i.stage||![tt,at].includes(i.stage)||i.stage===tt&&i.stageSequence!==1?v({result:{error:hs},stack:o}):i.seedAssignments?.find(a=>a.participantId===r)?{...R}:v({info:"participant not seeded",result:{error:je},context:{participantId:r}}):v({result:{error:_t},stack:o})}function ya({targetEntryRound:t=1,finishingPositions:e,sourceRoundNumber:r,sourceStructureId:n,targetStructureId:o,linkType:i=Jn}){return!n||!o?{error:We}:{link:rt({linkType:i,source:{roundNumber:r,structureId:n,finishingPositions:e},target:{feedProfile:Wr,roundNumber:t,structureId:o}})}}function Ym({roundPosition:t,roundNumber:e,idPrefix:r,uuids:n}){return r?`${r}-${e}-${t}`:n?.pop()||Mt()}function Ip({includeMatchUpType:t,matchUpType:e,roundNumber:r,matchUps:n,idPrefix:o,isMock:i,uuids:s,nodes:a}){let c=0,u=[],p=1,m=r-1,d=a?.length;for(;c<(d||0);){let l=a?.[c],f=a?.[c+1];m&&(l.roundNumber=m),f&&m&&(f.roundNumber=m);let g=Ym({roundPosition:p,roundNumber:r,idPrefix:o,uuids:s}),I={roundPosition:p,children:[l,f],matchUpId:g};u.push(I);let h={drawPositions:I.children.map(S=>S?.drawPosition).filter(Boolean),matchUpStatus:Kt,matchUpId:I.matchUpId,roundPosition:p,roundNumber:r};t&&e&&(h.matchUpType=e),i&&(h.isMock=!0),n.push(h),p++,c+=2}return{roundNodes:u,matchUps:n}}function mn({finishingPositionOffset:t,finishingPositionLimit:e,qualifyingRoundNumber:r,qualifyingPositions:n,matchUpType:o,roundLimit:i,idPrefix:s,drawSize:a,isMock:c,uuids:u}){if(isNaN(a)||a<2||n&&a<=n)return{matchUps:[],roundsCount:0};if(n&&(!gn(a)||a%n)){let I=n;for(;I<a;)I=2*I;a=I}let p=n&&!(a%2)&&(!isNaN(n)||r&&!isNaN(r))&&(a/n===Math.round(a/n)||r&&a/r===Math.round(a/r));if(!gn(a)&&!p)return{matchUps:[],roundsCount:0};let m=Z(1,a+1).map(I=>({drawPosition:I})),d,l=[],f=1;for({roundNodes:d,matchUps:l}=Ip({matchUpType:o,roundNumber:f,idPrefix:s,matchUps:l,isMock:c,nodes:m,uuids:u}),f++,i=i??r;d.length>1;)n&&d.length===n&&(i=f-1),{roundNodes:d,matchUps:l}=Ip({nodes:d,matchUpType:o,roundNumber:f,idPrefix:s,matchUps:l,isMock:c,uuids:u}),f++;let g=f-1;return l=Cs({finishingPositionOffset:t,finishingPositionLimit:e,roundsCount:g,roundLimit:i,matchUps:l}),i?l=l.filter(I=>i&&(I.roundNumber??0)<=i):i=f-1,{drawSize:a,matchUps:l,roundsCount:g,roundLimit:i}}function qm(t){let e="generateQualifyingStructure";if(!t.drawDefinition)return v({result:{error:z},stack:e});if(t.drawSize&&!lt(t.drawSize)||t.participantsCount&&!lt(t.participantsCount)||t.qualifyingPositions&&!lt(t.qualifyingPositions))return v({result:{error:G},stack:e});let r=t.drawSize??Zp(t.participantsCount),{qualifyingRoundNumber:n,qualifyingPositions:o,targetStructureId:i,structureOptions:s,appliedPolicies:a,drawDefinition:c,matchUpFormat:u,structureName:p,structureId:m,roundTarget:d,drawType:l,idPrefix:f,isMock:g,uuids:I}=t;if(!t.drawSize)return v({result:{error:Ga},context:{drawSize:r},stack:e});if(o&&o>=t.drawSize)return v({result:{error:G},context:{drawSize:r,qualifyingPositions:o},stack:e});let h,S,T,A,P=0,y,E=1,{structureProfiles:U}=au({drawDefinition:c}),M=U[i];if(!M)return v({result:{error:_t},context:{targetStructureId:i},stack:e});let N=c.matchUpType,C=d?`${d}-`:"",D=M.stage===at,O=a?.[ia]?.namingConventions?.pre??PR[ia]?.namingConventions?.pre,b=D&&O?`${O}-`:"",_=p??(C?`${b}${Be(at)} ${C}`:`${b}${Be(at)}`);if(l===un){let{maxRoundNumber:w,structures:x,groupCount:H}=Aa({structureName:p??_,structureId:m??I?.pop(),stage:at,structureOptions:s,appliedPolicies:a,stageSequence:E,matchUpType:N,roundTarget:d,idPrefix:f,drawSize:r,isMock:g,uuids:I});P=H,h=w,T=x[0],y=[1]}else({drawSize:r,matchUps:A,roundLimit:h,roundsCount:S}=mn({qualifyingRoundNumber:n,qualifyingPositions:o,matchUpType:N,idPrefix:f,drawSize:r,isMock:g,uuids:I})),h||(h=S),T=Xr({structureName:p??_,structureId:m??I?.pop(),qualifyingRoundNumber:h,stage:at,matchUpFormat:u,stageSequence:E,matchUpType:N,roundLimit:h,matchUps:A}),d&&gt({extension:{name:cn,value:d},element:T}),P=A?.filter(w=>w.roundNumber===h)?.length;let L=l===un?kn:Jn,F=T&&h&&ya({sourceStructureId:T.structureId,sourceRoundNumber:h,targetStructureId:i,finishingPositions:y,linkType:L})?.link;return{qualifyingDrawPositionsCount:r,qualifiersCount:P,...R,structure:T,link:F}}function yU(t){let e=t.tournamentRecord;if(!e)return{error:j};let r=NF(t);if(r.error)return r;let{qualifyingRoundNumber:n,qualifyingPositions:o,targetStructureId:i,drawDefinition:s,structureName:a,matchUpType:c,drawSize:u,drawType:p}=t,d={itemType:"addQualifyingStructures",itemValue:rt({drawId:s.drawId,qualifyingRoundNumber:n,qualifyingPositions:o,targetStructureId:i,structureName:a,matchUpType:c,drawSize:u,drawType:p})};return vi({tournamentRecord:e,timeItem:d}),r}function NF(t){if(!t.drawDefinition)return{error:z};if(!t.targetStructureId)return{error:We};let e=qm(t);if(e.error)return e;let{structure:r,link:n}=e;return!r||!n?{error:G}:Bf({tournamentRecord:t.tournamentRecord,drawDefinition:t.drawDefinition,structure:r,link:n})}function Ab({includeMatchUpType:t,drawPosition:e,roundNumber:r,matchUpType:n,idPrefix:o,matchUps:i,isMock:s,uuids:a,nodes:c,fed:u}){let p=c.length,m=e?e-p:void 0,d=Z(0,p).map(g=>m?m+g:void 0),l=[];for(let g=0;g<p;g++){let I=d.shift(),h={drawPosition:I,fed:u+1,feed:!0},S=c[g];S.roundNumber=r-1;let T=Ym({roundPosition:S.roundPosition,roundNumber:r,idPrefix:o,uuids:a}),A={roundPosition:S.roundPosition,drawPositions:[I],matchUpStatus:Kt,roundNumber:r,matchUpId:T};t&&(A.matchUpType=n),s&&(A.isMock=!0),i.push(A);let P={children:[S,h]};l.push(P)}let f=e?e-p:void 0;return{roundNodes:l,matchUps:i,drawPosition:f}}function $o(t){let e=t.drawSize,{feedRoundsProfile:r,feedRounds:n=0,skipRounds:o=0,baseDrawSize:i}=t,{linkFedFinishingRoundNumbers:s,finishingPositionOffset:a,linkFedRoundNumbers:c,feedsFromFinal:u,isConsolation:p,matchUpType:m,idPrefix:d,isMock:l,uuids:f,fmlc:g}=t;i=i??F(e);let I=DF({drawSize:i}),h=I.length,S=0;if(r?.length)S=r.reduce((w,x)=>w+x,0);else if(e){let w=e-i;r=I.filter(x=>x<=w?(w-=x,!0):!1),S=r.reduce((x,H)=>x+H,0),n=r.length}else o>=h?n=0:u&&(n=h-u,o=0),r=I.filter((w,x)=>u&&!n||n&&x>=o+n||x<o?0:w),S=r.reduce((w,x)=>w+x,0),n=r.length;let T=[...I,...r].sort((w,x)=>x-w),A=T.length,y=[...(c??[]).map(w=>w-1),...(s??[]).map(w=>A-w)].map(w=>T[w]).reduce((w,x)=>w+x,0);S=S-y;let E=0,U=[],M,N=1,D=Z(0,i).map((w,x)=>({drawPosition:x+1+S})),O=S+1;for(let w of I){if({roundNodes:M,matchUps:U}=Ip({matchUpType:m,roundNumber:N,idPrefix:d,matchUps:U,isMock:l,nodes:D,uuids:f}),N++,r.includes(w)){let x=pr(r)[w],H=Z(0,x),V=A+1-N,W=s?.includes(V)??c?.includes(N);H.forEach(()=>{({roundNodes:M,matchUps:U,drawPosition:O}=Ab({drawPosition:!W&&O||void 0,nodes:M,matchUpType:m,roundNumber:N,idPrefix:d,matchUps:U,isMock:l,uuids:f,fed:E})),N++,E+=1})}D=M}A!==N-1&&console.log("ERROR");let b=i-S;U=Cs({finishingPositionOffset:p?b:a,positionsFed:S,roundsCount:A,matchUps:U,fmlc:g});let L=M?.length?M[0]:M;return L&&(L.roundNumber=N-1,L.matchUps=U),{draw:L,matchUps:U,roundsCount:A};function F(w){let x=tm(w);return x>w?x/2:x}}function DF({drawSize:t}){let e=Math.ceil(Math.log(t)/Math.log(2));return Z(0,e).reverse().map(n=>Math.pow(2,n))}function mc(t){let{finishingPositionOffset:e=0,addNameBaseToAttributeName:r,playoffStructureNameBase:n,finishingPositionNaming:o,finishingPositionLimit:i,playoffAttributes:s,stageSequence:a=1,exitProfile:c="0",exitProfileLimit:u,roundOffsetLimit:p,roundOffset:m=0,drawDefinition:d,staggeredEntry:l,sequenceLimit:f,stage:g=tt,drawSize:I,idPrefix:h,isMock:S,uuids:T}=t;if(!(!s||!u||s?.[c])||I<2||f&&a>f)return{};let P=[],y=[],E=[],U=t.matchUpType??d?.matchUpType,M=e+1,N=e+I,C=`${M}-${N}`,D=s?.[c],O=n&&`${n} `||"",b=s?.[C]??o?.[C],_=t.structureName||b?.name||D?.name&&(r?`${O}${D?.name}`:D.name)||`${O}${C}`,L=b?.abbreviation??D?.abbreviation,F=t.structureId??D?.structureId??T?.pop(),w={idPrefix:h&&`${h}-${_}-RP`,finishingPositionOffset:e,matchUpType:U,drawSize:I,isMock:S,uuids:T},{matchUps:x}=l?$o(w):mn(w),H=Xr({structureAbbreviation:L,stageSequence:a,structureName:_,matchUpType:U,roundOffset:m,structureId:F,matchUps:x,stage:g});P.push(...x),y.push(H);let V=Math.ceil(Math.log(I)/Math.log(2)),W=p?Math.min(p-m,V):!i||M<i?V:0;return I>2&&Z(1,W+1).forEach(q=>B(q)),{structureId:H.structureId,matchUps:P,structureName:_,structures:y,links:E,...R};function B(q){let Y=I/Math.pow(2,q);if(Y<2)return;let k=I/Math.pow(2,q)+e;if(i&&k+1>i)return;let{structures:K,structureId:X,matchUps:$,links:nt}=mc({finishingPositionOffset:k,exitProfile:`${c}-${q}`,roundOffset:m+q,stageSequence:a+1,drawSize:Y,addNameBaseToAttributeName:r,playoffStructureNameBase:n,finishingPositionNaming:o,finishingPositionLimit:i,playoffAttributes:s,exitProfileLimit:u,roundOffsetLimit:p,drawDefinition:d,sequenceLimit:f,matchUpType:U,idPrefix:h,uuids:T,stage:g});if(H.structureId&&X){let Q={linkType:Vn,source:{roundNumber:q,structureId:H.structureId},target:{roundNumber:1,feedProfile:rn,structureId:X}};nt&&H&&nt.push(Q),nt?.length&&E.push(...nt)}return K?.length&&y.push(...K),$?.length&&P.push(...$),{structureId:X,childLinks:nt,structures:y}}}function $m({drawDefinition:t,matchUpsMap:e,structureId:r}){let n=st({drawDefinition:t,structureId:r});if(n.error)return v({result:n});let{matchUps:o}=Pt({structure:n.structure,matchUpsMap:e});return{...Xe({matchUps:o}),matchUps:o,matchUpsMap:e}}function EU({finishingPositions:t,drawDefinition:e,structureId:r}){let{roundProfile:n}=$m({drawDefinition:e,structureId:r});return(n&&Object.keys(n))?.reduce((i,s)=>(yb(n?.[s]).forEach(c=>{t.forEach(u=>{MF({position:u,rangeDefinition:c})&&(i[u]={roundNumber:s})})}),i),{})}function MF({position:t,rangeDefinition:e}){if(!Array.isArray(e)||e.reduce((i,s)=>i||isNaN(s),!1))return!1;let[r,n]=e;return Z(r,(n||r)+1).includes(t)}function yb(t){return[mt(t?.finishingPositionRange?.loser||[]),mt(t?.finishingPositionRange?.winner||[])]}function Eb(t){return yb(t).map(e=>Z(e[0],e[1]&&e[1]+1||e[0]+1))}function dc({drawDefinition:t,structureIds:e,matchUpsMap:r}){if(e&&!Array.isArray(e))return{error:G,context:{structureIds:e}};if(!t)return{error:z};e=e??(t.structures??[]).filter(a=>a.stage!==at).map(({structureId:a})=>a);let n=e.map(a=>{let{roundProfile:c}=$m({drawDefinition:t,matchUpsMap:r,structureId:a});return(c&&Object.values(c))?.map(Eb).flat()}).flat(),o=n.filter(a=>a?.length===1).sort(oe).flat();return{positionsNotPlayedOff:mt(n.flat()).filter(a=>!o.includes(a)),positionsPlayedOff:o}}function wh({excludeRoundNumbers:t=[],playoffPositions:e=[],drawDefinition:r,structureId:n}){if(!r)return{error:z};if(!n)return{error:We};if(!e)return{error:et,info:"missing playoffPositions"};let o=dc({drawDefinition:r});if(o.error)return o;let i=o.positionsPlayedOff,s=e.filter(S=>!i.includes(S)),a=EU({finishingPositions:s,drawDefinition:r,structureId:n}),u=Object.values(a).reduce((S,T)=>S.includes(T.roundNumber)?S:S.concat(T.roundNumber),[]).map(S=>ct(S)).filter(S=>!t.includes(S)),p=EU({finishingPositions:i,drawDefinition:r,structureId:n}),m=p?Object.values(p):[],d=p?m.reduce((S,T)=>S.includes(T.roundNumber)?S:S.concat(T.roundNumber),[]).map(S=>ct(S)):[],l=u.filter(S=>!d.includes(S)).sort(oe),{roundProfile:f}=$m({drawDefinition:r,structureId:n}),g=l.map(S=>{let T=f?.[S].finishingPositionRange.loser,[A,P]=T??[0,0];return Z(A,(P||A)+1)}).flat().sort(oe),{playoffRoundsRanges:I}=CF({playoffSourceRounds:l,roundProfile:f}),h=[...l,...d];return{playoffPositionsReturned:g,playedOffSourceRounds:d,playoffRoundsRanges:I,playoffSourceRounds:l,sourceRounds:h,roundProfile:f}}function CF({playoffSourceRounds:t,roundProfile:e}){return{playoffRoundsRanges:t.map(n=>{let o=e[n].finishingPositionRange.loser,[i,s]=o,a=Z(i,(s||i)+1);return{finishingPositionRange:o.join("-"),finishingPositions:a,roundNumber:n}})}}function cu({drawDefinition:t,structureId:e}){if(!t)return{error:z};let{matchUps:r,matchUpsMap:n}=ar({inContext:!0,drawDefinition:t}),{positionsNotPlayedOff:o,positionsPlayedOff:i}=dc({drawDefinition:t,matchUpsMap:n}),{structures:s}=Cn({drawDefinition:t}),a=s.filter(u=>!e&&u.stage!==ke||u.structureId===e),c={};for(let u of a){let p=u?.structureId,m=RF({playoffPositions:o,drawDefinition:t,structure:u,matchUps:r}),{error:d,...l}=m;if(d)return m;c[p]={structureId:p,...l}}return e?{positionsPlayedOff:i,...c[e]}:{availablePlayoffProfiles:Object.values(c),availablePlayoffRounds:Object.values(c),positionsPlayedOff:i}}function RF({playoffPositions:t,drawDefinition:e,structure:r,matchUps:n}){let o=r?.structureId,{links:i}=Rs({drawDefinition:e,structureId:o});if(r.structureType===we||r.structures){let l=Dt({structure:r})?.positionAssignments?.length,f=r.structures.length,g=(l??0)/f,I=i.source?.flatMap(({source:N})=>N?.finishingPositions||[])||[],h=Z(1,g+1).filter(N=>!I.includes(N)),S=n.find(N=>N.containerStructureId===o&&N.finishingPositionRange)?.finishingPositionRange?.winner||[0,1],T=i?.source.map(({target:N})=>N.structureId),{positionsPlayedOff:A=[],positionsNotPlayedOff:P=[]}=dc({structureIds:T,drawDefinition:e}),y=[...A,...P],E=Z(S[0],S[1]+1).filter(N=>!y.includes(N)),U=Ae(E,E.length/h.length),M=h.map((N,C)=>{let D=U[C],O=[Math.min(...D||[]),Math.max(...D||[])].join("-");return{finishingPosition:N,finishingPositions:D,finishingPositionRange:O}});return{positionsNotPlayedOff:E,playoffFinishingPositionRanges:M,finishingPositionsAvailable:h,finishingPositionsPlayedOff:I,positionsPlayedOff:A,groupCount:f,groupSize:g}}let s=i?.source?.filter(l=>l.linkCondition!==Bn).map(l=>l.source?.roundNumber)||[],a=i?.source?.filter(l=>l.linkCondition===Bn).map(l=>l.source?.roundNumber)||[],c=wh({excludeRoundNumbers:s,playoffPositions:t,drawDefinition:e,structureId:o}),u=c?.playoffSourceRounds?[...c?.playoffSourceRounds||[]]:void 0,p=[...c?.playoffRoundsRanges||[]],{roundProfile:m,error:d}=c;for(let l of a){let f=i?.source.find(T=>T.source.roundNumber===l),g=f?.target.roundNumber,I=f?.target.structureId,h=n.filter(({roundNumber:T,structureId:A})=>A===I&&T===g),S=h.filter(({sides:T})=>T.find(A=>A.participantFed&&!A.participantId)).length;if(u&&S===h.length){u.push(l);let T=m?.[l]?.finishingPositionRange?.loser;if(T){let A=Math.min(...T),P=A+S,y=Z(A,P),E={finishingPositionRange:[A,P-1].join("-"),finishingPositions:y,roundNumber:l};p.push(E)}}}return u&&u.sort(oe),p.sort((l,f)=>l.roundNumber-f.roundNumber),{playoffRounds:u,playoffRoundsRanges:p,error:d}}function Ub({playoffGroups:t,drawDefinition:e,structureId:r}){if(!e)return{error:z};if(typeof r!="string"||!Array.isArray(t))return{error:G};let n=t.map(({finishingPositions:a})=>a).flat();return{positionRangeMap:cu({drawDefinition:e,structureId:r}).playoffFinishingPositionRanges?.filter(a=>n.includes(a.finishingPosition))?.reduce((a,c)=>(a[c.finishingPosition]=c,a),{})}}function Lh(t){let{finishingPositionOffset:e=0,playoffAttributes:r,stageSequence:n=1,staggeredEntry:o,structureName:i,stage:s=tt,matchUpType:a,structureId:c,idPrefix:u,drawSize:p,isMock:m,uuids:d}=t,l={finishingPositionOffset:e,matchUpType:a,drawSize:p,idPrefix:u,isMock:m,uuids:d},{matchUps:f}=o?$o(l):mn(l),g=Xr({structureName:i||r?.["0"]?.name||Be(tt),structureId:c||d?.pop(),stageSequence:n,matchUpType:a,matchUps:f,stage:s}),I=[g],h=[];if(p>2){let S=p/2,{matchUps:T}=mn({finishingPositionOffset:e+S,idPrefix:u&&`${u}-c`,drawSize:S,matchUpType:a,isMock:m}),A=Be(Ge),P=r?.["0-1"]?.name??t.consolationStructureName??(i?`${i} ${A}`:A),y=Xr({structureName:P,matchUps:T,structureId:d?.pop(),stage:Ge,stageSequence:1,matchUpType:a});I.push(y);let E={linkType:Vn,source:{roundNumber:1,structureId:g.structureId},target:{roundNumber:1,feedProfile:rn,structureId:y.structureId}};h.push(E)}return{...R,structures:I,links:h}}function Fh({consolationStructure:t,roundOffset:e=0,mainStructure:r,roundsCount:n,feedPolicy:o,fmlc:i}){let a=t.matchUps.reduce((p,m)=>(m.drawPositions||[]).filter(Boolean).length&&!p.includes(m.roundNumber)?p.concat(m.roundNumber):p,[]),c=o?.roundGroupedOrder||[],u=o?.roundFeedProfiles;return Z(1+e,n+1+e).map(p=>{let m=u&&u[p-1]?u[p-1]:p%2?rn:Fo,d=p-e<=2?p-e:(p-e-2)*2+2,l={linkType:Vn,source:{roundNumber:p,structureId:r.structureId},target:{feedProfile:m,roundNumber:d,structureId:t.structureId}},f=c[p-1];return f&&(l.target.groupedOrder=f),Tr()&&(l.source.structureName=r.structureName,l.target.structureName=t.structureName),p===2&&i&&(l.linkCondition=Bn,l.target.feedProfile=rn),a.includes(d)?l:void 0}).filter(Boolean)}function Gh(t){let{playoffStructureNameBase:e,finishingPositionOffset:r,stageSequence:n=1,playoffAttributes:o,structureNameMap:i,staggeredEntry:s,stage:a=tt,matchUpType:c,structureId:u,drawSize:p,idPrefix:m,isMock:d,uuids:l}=t,f={finishingPositionOffset:r,matchUpType:c,drawSize:p,idPrefix:m,isMock:d,uuids:l},{matchUps:g,roundsCount:I}=s?$o(f):mn(f),h=t.structureName??o?.["0"]?.name??Be(tt),S=ss({structureId:u||l?.pop(),structureName:h,stageSequence:n,matchUpType:c,matchUps:g,stage:a}),T=[S],A=[];if(p>2){let E=[0,2].slice(0,p/16).map((U,M)=>{let N=M+1,{consolationStructure:C}=bF({idPrefix:m&&`${m}-c${M}`,structureId:l?.pop(),playoffStructureNameBase:e,playoffAttributes:o,structureNameMap:i,stageSequence:N,roundOffset:U,matchUpType:c,drawSize:p,isMock:d,index:M,uuids:l});T.push(C);let D=Fh({consolationStructure:C,roundsCount:2,mainStructure:S,roundOffset:U});return{consolationStructure:C,links:D}}).map(U=>U.links).flat();if(A.push(...E),p>=4&&p<=16||p>32){let{matchUps:U}=mn({idPrefix:m&&`${m}-p3t4`,finishingPositionOffset:2,drawSize:2,matchUpType:c,isMock:d}),M=o?.["3-4"]?.name??Be(ae),N=i?.[M]||M,C=e?`${e} ${N}`:N,D=ss({structureId:l?.pop(),matchUps:U,stageSequence:2,stage:ae,structureName:C,matchUpType:c}),O={linkType:Vn,source:{roundNumber:I-1,structureId:S.structureId},target:{structureId:D.structureId,feedProfile:rn,roundNumber:1}};T.push(D),A.push(O)}}return{structures:T,links:A,...R}}function bF({playoffStructureNameBase:t,stageSequence:e=1,playoffAttributes:r,structureNameMap:n,roundOffset:o=0,matchUpType:i,structureId:s,idPrefix:a,drawSize:c,isMock:u,index:p,uuids:m}){let d=c/(2*Math.pow(2,o)),{matchUps:l,roundsCount:f}=$o({finishingPositionOffset:d,baseDrawSize:d,isConsolation:!0,feedRounds:1,matchUpType:i,idPrefix:a,isMock:u,uuids:m}),I=p===0&&r?.["0-1"]?.name||p===1&&r?.["0-3"]?.name||`${Be(Ge)} ${p+1}`,h=n?.[I]||I,S=t?`${t} ${h}`:h;return{consolationStructure:ss({matchUps:l,stage:Ge,structureName:S,stageSequence:e,matchUpType:i,structureId:s}),consolationRoundsCount:f}}function lc(t){let{finishingPositionOffset:e,stageSequence:r=1,playoffAttributes:n,policyDefinitions:o,feedsFromFinal:i,staggeredEntry:s,structureName:a,stage:c=tt,structureId:u,matchUpType:p,skipRounds:m,feedRounds:d,idPrefix:l,drawSize:f,isMock:g,uuids:I,fmlc:h}=t,S=t.feedPolicy||o?.[Lc],T={finishingPositionOffset:e,matchUpType:p,skipRounds:m,drawSize:f,idPrefix:l,isMock:g,uuids:I},{matchUps:A}=s?$o(T):mn(T),P=Xr({structureName:a||n?.["0"]?.name||Be(tt),structureId:u||I?.pop(),stageSequence:r,matchUpType:p,matchUps:A,stage:c}),y=[P],E=[],U=f/2,{matchUps:M,roundsCount:N}=$o({finishingPositionOffset:U,idPrefix:l&&`${l}-c`,isConsolation:!0,feedsFromFinal:i,baseDrawSize:U,matchUpType:p,feedRounds:d,skipRounds:m,isMock:g,uuids:I,fmlc:h});if(f>2){let C=n?.["0-1"]?.name??Be(Ge),D=t.playoffStructureNameBase?`${t.playoffStructureNameBase} ${C}`:C,O=Xr({matchUps:M,structureId:I?.pop(),stage:Ge,stageSequence:1,structureName:D,matchUpType:p});y.push(O);let b=Fh({consolationStructure:O,mainStructure:P,roundsCount:N,feedPolicy:S,fmlc:h});E.push(...b)}return{...R,structures:y,links:E}}function Vh({requireSequential:t=!0,playoffMatchUpFormat:e,playoffAttributes:r,sourceStructureId:n,policyDefinitions:o,stageSequence:i,drawDefinition:s,playoffGroups:a,matchUpType:c,feedPolicy:u,groupCount:p,idPrefix:m,isMock:d,uuids:l}){u=u||o?.[Lc];let f="processPlayoffGroups",g=0,I=[],h=[],S=[],{error:T,positionRangeMap:A}=Ub({structureId:n,drawDefinition:s,playoffGroups:a});if(T)return v({result:{error:T},stack:f});if(!(!A||a?.every(y=>{let{finishingPositions:E=[]}=y;if(!E.length)return!1;let U=[...E].sort(oe).map((M,N)=>(E[N+1]||M)-M).every(M=>M<2);return(!t||U)&&E.every(M=>A[M])})))return v({context:{validFinishingPositions:Object.values(A)},result:{error:G},stack:f});for(let y of a){let E=y.finishingPositions,U=A&&E.map(F=>A[F]?.finishingPositions).flat(),M=p*E.length,N=Bi(M),C=N===2&&Zn||y.drawType||Zn;U&&(g=Math.min(...U)-1);let D=U&&`${Math.min(...U)}-${Math.max(...U)}`,O=y.structureName||D&&y.playoffAttributes?.[D]?.name||y.playoffAttributes?.["0"]?.name,_={...{addNameBaseToAttributeName:y.addNameBaseToAttributeName,playoffStructureNameBase:y.playoffStructureNameBase,finishingPositionNaming:y.finishingPositionNaming,finishingPositionLimit:y.finishingPositionLimit,structureId:y.structureId??l?.pop(),playoffAttributes:y.playoffAttributes,structureNameMap:y.structureNameMap,sequenceLimit:y.sequenceLimit,structureName:O},idPrefix:m&&`${m}-po`,appliedPolicies:o,finishingPositionOffset:g,stage:ae,stageSequence:i,matchUpType:c,drawSize:N,isMock:d,uuids:l},L=({playoffStructures:F,playoffLinks:w})=>{let[x]=F,H=kh({playoffStructureId:x.structureId,finishingPositions:E,sourceStructureId:n});S.push(H),S.push(...w),h.push(...F),I.push({structureId:x.structureId,finishingPositions:E}),g+=M};if(C===Zn){let{matchUps:F}=mn({finishingPositionLimit:g+M,idPrefix:m&&`${m}-po`,finishingPositionOffset:g,matchUpType:c,drawSize:N,isMock:d,uuids:l}),w=Xr({structureId:y.structureId??l?.pop(),matchUpFormat:e,stage:ae,structureName:O,stageSequence:i,matchUps:F});h.push(w);let x=kh({playoffStructureId:w.structureId,finishingPositions:E,sourceStructureId:n});S.push(x),g+=M,I.push({structureId:w.structureId,finishingPositions:E})}else if([Hc,Wc,ae].includes(C)){let F={playoffAttributes:y.playoffAttributes??r,playoffStructureNameBase:y.playoffStructureNameBase,structureId:y.structureId??l?.pop(),structureName:y.structureName,idPrefix:m&&`${m}-po`,addNameBaseToAttributeName:!0,finishingPositionOffset:g,stage:ae,roundOffset:0,stageSequence:i,drawSize:N,isMock:d,uuids:l};C===Hc?Object.assign(F,{playoffAttributes:y?.playoffAttributes??r??Yl,roundOffsetLimit:3}):C===Wc&&Object.assign(F,{playoffAttributes:y?.playoffAttributes??r??ql,roundOffsetLimit:2});let w=mc(F);if(w.error)return w;if(w.links?.length&&S.push(...w.links),w.structures?.length&&h.push(...w.structures),h.sort(ri),w.structureId){let x=kh({playoffStructureId:w.structureId,finishingPositions:E,sourceStructureId:n});S.push(x),I.push({structureId:w.structureId,finishingPositions:E})}g+=M}else if([Yc,tp,Sm,hm,Im,Tm].includes(C)){let F=[l?.pop(),l?.pop()],w={playoffStructureNameBase:y.playoffStructureNameBase,structureId:y.structureId??l?.pop(),playoffAttributes:y.playoffAttributes,idPrefix:m&&`${m}-po`,finishingPositionOffset:g,uuids:F,stage:ae,structureName:O,matchUpType:c,feedPolicy:u,drawSize:N,isMock:d},x={[Yc]:{fmlc:!0,feedRounds:1},[Tm]:{feedRounds:1},[Sm]:{feedsFromFinal:3},[hm]:{feedsFromFinal:2},[Im]:{feedsFromFinal:1}};Object.assign(w,x[C]||{});let{structures:H,links:V}=lc(w),[W]=H,B=kh({playoffStructureId:W.structureId,finishingPositions:E,sourceStructureId:n});S.push(B),S.push(...V),h.push(...H),I.push({structureId:W.structureId,finishingPositions:E}),g+=M}else if([un].includes(C)){let{structures:F,links:w}=Aa({..._,structureOptions:y.structureOptions||{groupSize:4}});L({playoffStructures:F,playoffLinks:w})}else if([Zu].includes(C)){let{structures:F,links:w}=Lh(_);L({playoffStructures:F,playoffLinks:w})}else if([LC].includes(C)){let{structures:F,links:w}=Gh(_);L({playoffStructures:F,playoffLinks:w})}else if([br].includes(C)){let F=Xr({structureId:y.structureId??l?.pop(),structureName:y.structureName,finishingPosition:Dm,stage:ae,stageSequence:i,matchUps:[]});L({playoffStructures:[F],playoffLinks:[]})}}return{finishingPositionTargets:I,positionRangeMap:A,structures:h,links:S}}function kh({playoffStructureId:t,finishingPositions:e,sourceStructureId:r}){return{linkType:kn,source:{structureId:r,finishingPositions:e},target:{structureId:t,feedProfile:Wr,roundNumber:1}}}function Ea({matchUp:t,tieFormat:e,isMock:r,uuids:n}){let{collectionDefinitions:o}=e??{};return{tieMatchUps:(o??[]).map(s=>uu({matchUp:t,collectionDefinition:s,uuids:n,isMock:r})).filter(Boolean).flat()}}function uu({collectionPositionOffset:t=0,collectionDefinition:e,matchUpsLimit:r,matchUp:n,isMock:o,uuids:i}){let{matchUpCount:s,matchUpType:a,collectionId:c,processCodes:u}=e||{},p=r??s??0,m=d=>{if(!o&&!n?.isMock)return i?.pop()??Mt();let l=e?.collectionId;return i?.pop()??`${n?.matchUpId}-${l}-TMU-${d+1}`};return Z(0,p).map(d=>{let l=t+d+1;return{sides:[{sideNumber:1},{sideNumber:2}],matchUpId:m(d),matchUpStatus:Kt,collectionPosition:l,collectionId:c,processCodes:u,matchUpType:a,isMock:o}})}function Pb(t){let e="generateAndPopulateRRplayoffStructures";if(!t.playoffGroups)return v({result:{error:et},info:"playoffGroups required",stack:e});let{sourceStructureId:r,requireSequential:n,tournamentRecord:o,drawDefinition:i,playoffGroups:s,groupCount:a,groupSize:c,event:u}=t,{structures:p=[],links:m=[],finishingPositionTargets:d,positionRangeMap:l,error:f}=Vh({requireSequential:n,sourceStructureId:r,playoffGroups:s,groupCount:a,groupSize:c,...t});if(f)return{error:f};let g=d?.map(({finishingPositions:U})=>U).flat().map(U=>l[U].finishingPositions).flat();i.structures.push(...p),i.links.push(...m);let{matchUps:I,matchUpsMap:h}=re({inContext:!0,drawDefinition:i}),S=p.map(({structureId:U})=>U),T=I?.filter(({structureId:U})=>S.includes(U)).map(le),A=h?.drawMatchUps?.filter(({matchUpId:U})=>T?.includes(U));if(A?.length){let U=Ve({drawDefinition:i,event:u})?.tieFormat;U&&A.forEach(M=>{let{tieMatchUps:N}=Ea({isMock:t.isMock,tieFormat:U,matchUp:M});Object.assign(M,{tieMatchUps:N,matchUpType:pn})})}let{positionAssignments:P}=Dt({structureId:r,drawDefinition:i}),y={};P?.forEach(U=>{let C=ut({element:U,name:wo})?.extension?.value?.groupOrder;C&&(y[C]||(y[C]=[]),y[C].push(U.participantId))});let E=pc({provisionalPositioning:t.provisionalPositioning,structureId:r,applyPositioning:!0,event:t.event,tournamentRecord:o,drawDefinition:i});return E.error&&E.error?.code!==Xd.code?v({result:E,stack:e}):{structures:p,links:m,positionsPlayedOff:g,drawDefinition:i,...R}}var on="SET3-S:6/TB7",OF="SET3-S:6NOAD",UU="SET3-S:6/TB7-F:TB10",_F="SET3-S:4/TB7",vF="SET3-S:4/TB5@3",xF="SET1-S:T20",wF="SET1-S:8/TB7",LF="SET1-S:8/TB7@7",Nb={FORMAT_STANDARD:on,FORMAT_STANDARD_NOAD:OF,FORMAT_ATP_DOUBLES:UU,FORMAT_SHORT_SETS:_F,FORMAT_FAST4:vF,FORMAT_PRO_SET:wF,FORMAT_COLLEGE_PRO_SET:LF,TIMED20:xF};function Wf({winningSide:t,matchUpFormat:e=on,matchUpStatus:r,tallyPolicy:n,score:o}){let i=[0,0],s=o?.sets,a=typeof t=="number"&&t-1,c=Ze(e),u=PU(c?.bestOf??1);if(typeof a=="number"&&(r===bt&&n?.setsCreditForDefaults||r===Ot&&n?.setsCreditForWalkovers))i[a]=u;else for(let p of s||[]){let{winningSide:m}=p;m&&(i[m-1]+=1)}return typeof a=="number"&&r===mr&&(+i[1-a]===u&&(i[1-a]-=1),n?.setsCreditForRetirements&&(i[a]=u)),i}function Bh({matchUpFormat:t=on,winningSide:e,matchUpStatus:r,tallyPolicy:n,score:o}){let{sets:i}=o||{};if(!i)return[0,0];let s=typeof e=="number"&&e-1,a=Ze(t),c=a?.bestOf??1,u=PU(c),p=a?.setFormat?.tiebreakAt||0,m=[[],[]];if(typeof s=="number"&&(r===bt&&n?.gamesCreditForDefaults||r===Ot&&n?.gamesCreditForWalkovers)){let d=a?.setFormat?.setTo||0,l=u*d;m[s].push(l)}else i.forEach((d,l)=>{let g=(d.setNumber||l+1)>u&&a?.finalSetFormat?"finalSetFormat":"setFormat",I=a?.[g]?.based,h=a?.[g].tiebreakSet,{side1Score:S,side2Score:T}=d;Db(I)&&(m[0].push(ct(S||0)),m[1].push(ct(T||0))),h&&d.winningSide&&n?.gamesCreditForTiebreakSets!==!1&&m[d.winningSide-1].push(1)});if(r===mr&&typeof s=="number"){let d=i.length>u&&a?.finalSetFormat?"finalSetFormat":"setFormat",l=a?.[d];if(Db(l.based)){let f=l?.setTo||0,g=S=>{if(!(!a||S===""))return+S===p-1||+S===p?ct(p||0)+1:+S<p?f:p},I=Wf({winningSide:e,score:{sets:i},matchUpStatus:r,matchUpFormat:t,tallyPolicy:n});if(m.map(S=>S[s]<=S[1-s]).reduce((S,T)=>S+(T?1:0),0)>I[1-s]){let S=m[s].length,T=g(m[1-s][S-1]);T&&(m[s][S-1]=T)}u>m[s].length&&n?.gamesCreditForRetirements&&m[s].push(f)}}return[m[0].reduce((d,l)=>d+l,0),m[1].reduce((d,l)=>d+l,0)]}function Hh({matchUpFormat:t,score:e}){let r=t?Ze(t):void 0,n=r?.bestOf??1,o=PU(n),i=[0,0],s=[0,0];return e?.sets?.forEach((a,c)=>{let p=(a.setNumber||c+1)>o&&r?.finalSetFormat?"finalSetFormat":"setFormat",m=r?.[p]?.based;if(Mb(m)){let{side1Score:d,side2Score:l}=a;d&&(s[0]+=ct(d||0)),l&&(s[1]+=ct(l||0))}else a.side1TiebreakScore&&(s[0]+=ct(a.side1TiebreakScore||0)),a.side2TiebreakScore&&(s[1]+=ct(a.side2TiebreakScore||0)),(a.side1TiebreakScore||a.side2TiebreakScore)&&a.winningSide&&(i[a.winningSide-1]+=1)}),{pointsTally:s,tiebreaksTally:i}}function PU(t){return t&&Math.ceil(t/2)||1}function Mb(t){return t==="P"}function Db(t){return!Mb(t)}function Cb({participantResults:t,matchUpFormat:e,tallyPolicy:r,perPlayer:n,totalSets:o}){let i=e&&Ze(e)||{},s=i.bestOf,a=s&&Math.ceil(s/2)||1,c=i.setFormat?.setTo;Object.keys(t).forEach(u=>{let p=t[u].setsWon,m=t[u].setsLost,d=r?.groupTotalSetsPlayed?o:n*(a||0)||p+m,l=Math.round(p/d*1e3)/1e3;(l===1/0||isNaN(l))&&(l=d);let f=t[u].tieMatchUpsWon,g=t[u].tieMatchUpsLost,I=f+g,h=Math.round(f/I*1e3)/1e3;(h===1/0||isNaN(h))&&(h=f);let S=t[u].matchUpsWon,T=t[u].matchUpsLost,A=S+T,P=Math.round(S/A*1e3)/1e3;(P===1/0||isNaN(P))&&(P=S);let y=t[u].gamesWon||0,E=t[u].gamesLost||0,U=(n||0)*(a||0)*(c||0),M=Math.max(U,y+E),N=Math.round(y/M*1e3)/1e3;(N===1/0||isNaN(N))&&(N=0);let C=Math.round(t[u].pointsWon/t[u].pointsLost*1e3)/1e3;(C===1/0||isNaN(C))&&(C=0),t[u].setsWon=p,t[u].setsLost=m,t[u].setsPct=l,t[u].tieMatchUpsWon=f,t[u].tieMatchUpsPct=h,t[u].matchUpsPct=P,t[u].gamesWon=y,t[u].gamesLost=E,t[u].gamesPct=N,t[u].pointsPct=C,t[u].result=`${t[u].matchUpsWon}/${t[u].matchUpsLost}`})}function Wh({participantIds:t,matchUpFormat:e,tallyPolicy:r,perPlayer:n,matchUps:o}){let i={},s=r?.excludeMatchUpStatuses||[],a=o.filter(p=>(p.tieMatchUps||!s.includes(p.matchUpStatus))&&(!t?.length||Wt(t,[Km(p,0),Km(p,1)]).length===2)),u=a.flatMap(({score:p,tieMatchUps:m})=>m?m.filter(({matchUpStatus:d})=>!s.includes(d)).flatMap(({score:d})=>d?.sets?.length??0):p?.sets?.length??0).reduce((p,m)=>p+m,0);for(let p of a){let{matchUpStatus:m,tieMatchUps:d,tieFormat:l,score:f,winningSide:g,sides:I}=p,h=l&&p._disableAutoCalc&&l.collectionDefinitions.every(({scoreValue:A})=>A),S=g&&FF(p),T=g&&GF(p);if(!S&&!T)if(m&&ie.includes(m)){let A=Km(p,0),P=Km(p,1);A&&(fc(i,A),i[A].matchUpsCancelled+=1),P&&(fc(i,P),i[P].matchUpsCancelled+=1)}else if(d?.length){n=0;for(let A of d){if(A.winningSide){let P=I?.find(({sideNumber:E})=>E===A.winningSide)?.participantId,y=I?.find(({sideNumber:E})=>E===A.winningSide)?.participantId;P&&y&&(fc(i,P),fc(i,y),i[P].tieMatchUpsWon+=1,i[y].tieMatchUpsLost+=1,A.matchUpType===ee?(i[P].tieSinglesWon+=1,i[y].tieSinglesLost+=1):A.matchUpType===jt&&(i[P].tieDoublesWon+=1,i[y].tieDoublesLost+=1))}Rb({score:A.score,manualGamesOverride:h,participantResults:i,sides:I})}}else Rb({manualGamesOverride:h,participantResults:i,score:f,sides:I});else if(fc(i,S),fc(i,T),d?.length){n=0;for(let A of d){let{matchUpType:P}=A,y=P===jt,E=P===ee;A.winningSide&&(A.winningSide===g?(S&&(i[S].tieMatchUpsWon+=1,E&&(i[S].tieSinglesWon+=1),y&&(i[S].tieDoublesWon+=1)),T&&(i[T].tieMatchUpsLost+=1,E&&(i[T].tieSinglesLost+=1),y&&(i[T].tieDoublesLost+=1))):A.winningSide!==g&&(T&&(i[T].tieMatchUpsWon+=1,E&&(i[T].tieSinglesWon+=1),y&&(i[T].tieDoublesWon+=1)),S&&(i[S].tieMatchUpsLost+=1,E&&(i[S].tieSinglesLost+=1),y&&(i[S].tieDoublesLost+=1)))),bb({matchUpFormat:A.matchUpFormat,matchUpStatus:A.matchUpStatus,score:A.score,winningParticipantId:S,losingParticipantId:T,participantResults:i,isTieMatchUp:!0,manualGamesOverride:h,tallyPolicy:r,winningSide:g})}Ob({winningParticipantId:S,losingParticipantId:T,participantResults:i,matchUpStatus:m})}else bb({matchUpFormat:p.matchUpFormat??e,isTieMatchUp:void 0,winningParticipantId:S,manualGamesOverride:h,losingParticipantId:T,participantResults:i,matchUpStatus:m,tallyPolicy:r,winningSide:g,score:f});if(h){let A=I?.find(({sideNumber:U})=>U===1)?.participantId,P=I?.find(({sideNumber:U})=>U===2)?.participantId;fc(i,A),fc(i,P);let y=f?.sets?.reduce((U,M)=>U+(M?.side1Score??0),0),E=f?.sets?.reduce((U,M)=>U+(M.side2Score??0),0);A&&(i[A].gamesWon+=y,i[A].gamesLost+=E),P&&(i[P].gamesWon+=E,i[P].gamesLost+=y)}}return Cb({participantResults:i,matchUpFormat:e,tallyPolicy:r,perPlayer:n,totalSets:u}),{participantResults:i}}function FF(t){let e=t.winningSide-1;return Km(t,e)}function GF(t){let e=1-(t.winningSide-1);return Km(t,e)}function Km(t,e){if(!t?.sides)return console.log("no sides:",{matchUp:t}),"foo";let r=t.sides[e];return r?r.participantId:(console.log("No Side",{matchUp:t,index:e}),"foo")}function fc(t,e){e&&!t[e]&&(t[e]={allDefaults:0,defaults:0,defeats:[],gamesLost:0,gamesWon:0,matchUpsCancelled:0,matchUpsLost:0,matchUpsWon:0,pointsLost:0,pointsWon:0,retirements:0,setsLost:0,setsWon:0,tieSinglesWon:0,tieSinglesLost:0,tieDoublesWon:0,tieDoublesLost:0,tieMatchUpsLost:0,tieMatchUpsWon:0,victories:[],walkovers:0})}function Rb({manualGamesOverride:t,participantResults:e,score:r,sides:n}){let{sets:o}=r||{},i=[[],[]],s=[0,0];for(let c of o||[]){let{winningSide:u,side1Score:p,side2Score:m}=c;u&&(s[u-1]+=1),i[0].push(ct(p||0)),i[1].push(ct(m||0))}let a=[i[0].reduce((c,u)=>c+u,0),i[1].reduce((c,u)=>c+u,0)];n.forEach((c,u)=>{let{participantId:p}=c;p&&(fc(e,p),e[p].setsWon+=s[u],e[p].setsLost+=s[1-u],t||(e[p].gamesWon+=a[u],e[p].gamesLost+=a[1-u]))})}function bb({winningParticipantId:t,losingParticipantId:e,participantResults:r,manualGamesOverride:n,matchUpFormat:o,matchUpStatus:i,isTieMatchUp:s,tallyPolicy:a,winningSide:c,score:u}){let p=c&&c-1,m=1-p;s||Ob({winningParticipantId:t,losingParticipantId:e,participantResults:r,matchUpStatus:i});let d=Wf({matchUpStatus:i,matchUpFormat:o,tallyPolicy:a,winningSide:c,score:u}),l=Bh({matchUpStatus:i,matchUpFormat:o,tallyPolicy:a,winningSide:c,score:u}),{pointsTally:f}=Hh({score:u,matchUpFormat:o});t&&(r[t].setsWon+=d[p],r[t].setsLost+=d[m],n||(r[t].gamesWon+=l[p],r[t].gamesLost+=l[m]),r[t].pointsWon+=f[p],r[t].pointsLost+=f[m]),e&&(r[e].setsWon+=d[m],r[e].setsLost+=d[p],n||(r[e].gamesWon+=l[m],r[e].gamesLost+=l[p]),r[e].pointsWon+=f[m],r[e].pointsLost+=f[p])}function Ob({winningParticipantId:t,losingParticipantId:e,participantResults:r,matchUpStatus:n}){e&&(n===Ot&&(r[e].walkovers+=1),n===bt&&(r[e].defaults+=1),n===mr&&(r[e].retirements+=1),[bt,mr,Ot].includes(n)&&(r[e].allDefaults+=1),r[e].matchUpsLost+=1),t&&(r[t].matchUpsWon+=1),e&&t&&(r[e].defeats.push(t),r[t].victories.push(e))}function _b({matchUps:t,order:e,report:r}){let n={};t.forEach(({sides:i})=>{i.forEach(s=>{s.participantId&&s.participant&&(n[s.participantId]=s.participant.participantName)})});let o=[];return Array.isArray(r)&&r.forEach((i,s)=>{if(i.excludedDirectives?.length){let a=i.excludedDirectives.map(({attribute:p})=>p).join(", "),c=`${a.length} directives were excluded due to participants limit}`;o.push(c);let u=`Excluded: ${a}`;o.push(u)}else{let a=(l,f)=>parseFloat(i.reversed?l:f)-parseFloat(i.reversed?f:l),c=i.groups?Object.values(i.groups).flat(1/0).length:i.participantIds?.length??0,u=l=>{l.groups&&Object.keys(l.groups).sort(a).forEach(f=>{let g=l.groups[f].map(h=>n[h]).join(", "),I=`${f} ${l.attribute}: ${g}`;o.push(I)})},p=i.reversed?" in reverse order":"",m=i.groups?"grouped":"separated",d=`Step ${s+1}: ${c} particiants were ${m}${p} by ${i.attribute}`;if(o.push(d),i.idsFilter){let l=`${i.attribute} was calculated considering ONLY TIED PARTICIPANTS`;o.push(l)}u(i)}o.push("----------------------")}),o.push("Final Order:"),e.forEach(i=>{let{participantId:s,resolved:a}=i,c=i.groupOrder||i.provisionalOrder;o.push(`${c}: ${n[s]} => resolved: ${!!a}`)}),o.join(`\r
4
+ `)}function NU({participantResults:t,participantIds:e,attribute:r}){return DU({participantResults:t,participantIds:e}).reduce((o,i)=>{let{participantId:s,results:a}=i,c=a?.[r];return!isNaN(c)&&s&&(o[c]?o[c].push(s):o[c]=[s]),o},{})}function DU(t){return(t.participantIds||Object.keys(t.participantResults)).reduce((r,n,o)=>(r.push({participantId:n,i:o,results:t.participantResults[n]}),r),[])}var kF=[{attribute:"matchUpsPct",idsFilter:!1},{attribute:"allDefaults",reversed:!0,idsFilter:!1},{attribute:"defaults",reversed:!0,idsFilter:!1},{attribute:"walkovers",reversed:!0,idsFilter:!1},{attribute:"retirements",reversed:!0,idsFilter:!1},{attribute:"setsPct",idsFilter:!1},{attribute:"gamesPct",idsFilter:!1},{attribute:"pointsPct",idsFilter:!1},{attribute:"matchUpsPct",idsFilter:!0},{attribute:"setsPct",idsFilter:!0},{attribute:"gamesPct",idsFilter:!0},{attribute:"pointsPct",idsFilter:!0}],MU={matchUpsPct:20,tieMatchUpsPct:16,setsPct:12,gamesPct:8,pointsPct:4};function CU(t){let{requireCompletion:e=!0,participantResults:r,subOrderMap:n,tallyPolicy:o}=t,i=[];if(e&&!VF(t))return{};let s=["tieMatchUpsWon","tieSinglesWon","tieDoublesWon","matchUpsWon","pointsWon","gamesWon","setsWon","gamesPct","setsPct","pointsPct","matchUpsPct"].includes(o?.groupOrderKey)?o.groupOrderKey:"matchUpsWon",a=NU({participantResults:r,attribute:s});i.push({attribute:s,groups:a});let c=Object.keys(a).map(f=>parseFloat(f)).sort((f,g)=>g-f).map(f=>a[f]).map(f=>{let g=vb({participantIds:f,...t});return i.push(...g.report??[]),g.order}).flat(1/0),u=1,p;c.forEach((f,g)=>{g&&(f.resolved||p&&!f.resolved)&&(u+=1),p=f.resolved,f.resolved?(f.position=g+1,u=f.position):f.position=u});let m=c.map(({position:f})=>f),d=pr(m);return c.forEach(f=>{let{participantId:g,position:I}=f||{},h=r[g];f.GEMscore=l(h);let S=d[I];f?.position!==void 0&&(S>1&&(f.ties=S,n&&(f.subOrder=n[g])),f.rankOrder=I,f.groupOrder=I+(f.subOrder||1)-1)}),{groupOrder:c,report:i.flat(1/0).filter(Boolean)};function l(f){return(Array.isArray(o?.GEMscore)?Object.keys(MU).filter(h=>o.GEMscore.includes(h)):Object.keys(MU)).map(h=>(f[h]||0)*Math.pow(10,MU[h].toFixed(3))).reduce((h,S)=>h+S,0)}}function VF({participantResults:t,participantsCount:e}){let n=DU({participantResults:t}).filter(o=>e-1===o.results.matchUpsWon+o.results.matchUpsLost+o.results.matchUpsCancelled);return e===n.length}function BF({disableHeadToHead:t,participantIds:e,matchUpFormat:r,tallyPolicy:n,attribute:o,idsFilter:i,matchUps:s,reversed:a}){let{participantResults:c}=Wh({participantIds:i&&e,matchUpFormat:r,tallyPolicy:n,matchUps:s}),u=NU({participantResults:c,participantIds:e,attribute:o}),p=[{attribute:o,reversed:a,groups:u,idsFilter:i}],m;return Object.keys(u).length>1&&e.length&&(m=Object.keys(u).map(d=>parseFloat(d)).sort((d,l)=>a?d-l:l-d).map(d=>u[d]).map(d=>{let l=vb({participantResults:c,disableHeadToHead:t,participantIds:d,matchUpFormat:r,tallyPolicy:n,matchUps:s});return p.push(...l.report??[]),l.order}).flat(1/0)),{order:m,report:p}}function vb({participantResults:t,disableHeadToHead:e,participantIds:r,matchUpFormat:n,tallyPolicy:o,matchUps:i}){let s=[],a=[],c;if(r?.length===1)return{order:[{resolved:!0,participantId:r[0]}]};if(r?.length===2&&(!o?.headToHead||!o.headToHead.disabled&&!e)){let m=HF({participantIds:r,participantResults:t});if(m){let d=m[0].participantId;return a.push({attribute:"head2Head",participantIds:r,headToHeadWinner:d}),{order:[m],headToHeadWinner:d,report:a}}}let p=(o?.tallyDirectives||kF).filter(m=>{let d=!(se(m.maxParticipants)&&r?.length>m.maxParticipants);return d||s.push(m),d});return s.length&&a.push({excludedDirectives:s,participantIds:r}),p.every(({attribute:m,reversed:d,idsFilter:l,disableHeadToHead:f})=>(c=BF({disableHeadToHead:f,participantIds:r,matchUpFormat:n,tallyPolicy:o,attribute:m,idsFilter:l,matchUps:i,reversed:d}),a.push(c.report),!c.order)),c.order?{order:c.order,report:a}:{order:r?.map(m=>({participantId:m})),report:a}}function HF({participantIds:t,participantResults:e}){if(t){if(e[t[0]].victories.includes(t[1]))return t.map(r=>({resolved:!0,participantId:r}));if(e[t[1]].victories.includes(t[0]))return t.reverse().map(r=>({resolved:!0,participantId:r}))}}function Ua({policyDefinitions:t,generateReport:e,matchUpFormat:r,matchUps:n=[],subOrderMap:o,perPlayer:i}){if(!Ar(n))return{error:wn};if(n.reduce((T,{structureId:A})=>T.includes(A)?T:T.concat(A),[]).length!==1)return{error:G,info:"Maximum one structureId"};let a=n.filter(T=>T&&T.matchUpStatus!==Ut),c=a.length&&mt(a.map(({drawPositions:T})=>T).flat()).length,u=a.filter(T=>es({matchUp:T})).length===a.length;u||(i=0);let p=n.every(({matchUpType:T,tieMatchUps:A})=>T===Bt&&A?.every(P=>es({matchUp:P}))),m=t?.[kl],d=n.filter(T=>es({matchUp:T})||T.matchUpType===Bt),{participantResults:l}=Wh({matchUps:d,matchUpFormat:r,tallyPolicy:m,perPlayer:i}),f,g,{groupOrder:I,report:h}=CU({matchUps:d,participantResults:l,participantsCount:c,matchUpFormat:r,tallyPolicy:m,subOrderMap:o});if(u&&I)f=h,g=I,I.forEach(T=>{let{participantId:A,groupOrder:P,rankOrder:y,subOrder:E,ties:U,GEMscore:M}=T,N=l[A];Object.assign(N,{groupOrder:P,rankOrder:y,GEMscore:M,subOrder:E,ties:U})});else{let{groupOrder:T,report:A}=CU({requireCompletion:!1,participantResults:l,participantsCount:c,matchUpFormat:r,tallyPolicy:m,subOrderMap:o,matchUps:n});f=A,g=T,T&&T.forEach(P=>{let{participantId:y,groupOrder:E,GEMscore:U}=P,M=l[y];Object.assign(M,{provisionalOrder:E,GEMscore:U})})}let S={completedTieMatchUps:p,readableReport:"",participantResults:l,bracketComplete:u,order:[],report:f};if((u||p)&&(S.order=g),e||Tr({tally:!0})){let T=_b({matchUps:n,report:f,order:g});Tr({tally:!0})&&console.log(T),S.readableReport=T}return S}function jh({positionAssignments:t}){let e=(t||[]).filter(Dr(zn)).map(i=>{let{extension:s}=ut({element:i,name:Qa}),a=ct(s?.value),c=!isNaN(a)&&a;return c&&{participantId:i.participantId,subOrder:c}}).filter(Boolean),r=e.map(({subOrder:i})=>i),n=pr(r);return{subOrderMap:Object.assign({},...e.filter(({subOrder:i})=>n[i]===1).map(({participantId:i,subOrder:s})=>({[i]:s})))}}function zm({positionAssignments:t,tournamentRecord:e,drawDefinition:r,matchUpFormat:n,matchUps:o,event:i}){if(!Ar(o))return{error:G};if(!t)return{error:G};let{policyDefinitions:s}=Io({policyTypes:[kl],tournamentRecord:e,drawDefinition:r,event:i}),{subOrderMap:a}=jh({positionAssignments:t}),c=Ua({policyDefinitions:s,matchUpFormat:n,subOrderMap:a,matchUps:o});if(c.error)return c;let{participantResults:u,bracketComplete:p,report:m}=c,d=Object.keys(u);return t.forEach(l=>{let{participantId:f}=l;if(d.includes(f)){let g={value:u[f],name:wo};gt({element:l,extension:g}),u[f].ties||rr({element:l,name:Qa})}else rr({element:l,name:wo}),rr({element:l,name:Qa})}),Rt({drawDefinition:r}),{...R,participantResults:u,bracketComplete:p,report:m}}function Yh({matchUps:t,matchUpId:e}){return{matchUp:(t||[]).find(n=>n.matchUpId===e)}}function xt({tournamentParticipants:t,afterRecoveryTimes:e,contextContent:r,contextProfile:n,drawDefinition:o,matchUpsMap:i,matchUpId:s,inContext:a,context:c,event:u}){if(!o)return{error:z};if(!s)return{error:Ne};if(typeof s!="string")return{error:G};let{structures:p=[]}=Cn({drawDefinition:o});n&&!r&&(r=bn({contextProfile:n,drawDefinition:o}));for(let m of p){let{matchUps:d}=Pt({tournamentParticipants:t,afterRecoveryTimes:e,contextContent:r,drawDefinition:o,contextProfile:n,matchUpsMap:i,inContext:a,structure:m,context:c,event:u}),{matchUp:l}=Yh({matchUps:d,matchUpId:s});if(l)return{matchUp:l,structure:m}}return{error:De}}function hp(t){return typeof t!="object"?{error:et}:typeof t.element!="object"?{error:G}:t.notes?typeof t.notes!="string"&&!t.notes?.testing?{error:G}:(Object.assign(t.element,{notes:t.notes}),{...R}):{error:et}}function RU(t){return typeof t!="object"?{error:et}:typeof t.element!="object"?{error:G}:(t.element.notes&&delete t.element.notes,{...R})}var pu={matchUpStatus:Kt,matchUpStatusCodes:[],score:{scoreStringSide1:"",scoreStringSide2:"",sets:void 0},matchUpFormat:void 0,winningSide:void 0};function yn(t){let e="modifyMatchUpScore",r=t.matchUpFormat,n=t.matchUp,o,{matchUpStatusCodes:i,removeWinningSide:s,tournamentRecord:a,drawDefinition:c,matchUpStatus:u,removeScore:p,winningSide:m,matchUpId:d,event:l,notes:f,score:g}=t,h=t.appliedPolicies&&Object.keys(t.appliedPolicies).length?t.appliedPolicies:yt({policyTypes:[Mn],tournamentRecord:a,drawDefinition:c,structure:o,event:l})?.appliedPolicies,S=n.matchUpType===Bt;if(S&&c){if(d&&n.matchUpId!==d){let M=xt({drawDefinition:c,matchUpId:d,event:l});if(!M.matchUp)return{error:De};({matchUp:n,structure:o}=M)}}else n.matchUpId!==d&&console.log("!!!!!");u&&[Ot,fe].includes(u)||p?Object.assign(n,{...pu}):g&&(n.score=g);let T=u&&n?.matchUpStatus===bt&&u!==bt;u&&(n.matchUpStatus=u),r&&(n.matchUpFormat=r),i&&(n.matchUpStatusCodes=i),m&&(n.winningSide=m),s&&(n.winningSide=void 0),!o&&c&&({structure:o}=xt({drawDefinition:c,matchUpId:d,event:l})),u&&!n.winningSide&&he(n)&&!ie.includes(u)&&![Xa,Ki].includes(u)&&(n.matchUpStatus=Sn);let A;if((T&&n?.processCodes?.length||u===bt)&&(A=h?.[Mn]?.processCodes?.incompleteAssignmentsOnDefault),!n.collectionId){let M=o?.structureType===we,N=Br({drawDefinition:c,structure:o});if(vm({drawDefinition:c,structure:o})||N||M){let C=b=>{r=S?"SET1-S:T100":r??n.matchUpFormat??b?.matchUpFormat??c?.matchUpFormat??l?.matchUpFormat;let _=S?{matchUpTypes:[Bt]}:void 0,{matchUps:L}=Pt({afterRecoveryTimes:!1,tournamentRecord:a,inContext:!0,matchUpFilters:_,drawDefinition:c,structure:b,event:l});return N&&(b.positionAssignments=mt(L.flatMap(F=>(F.sides??[]).map(w=>w.participantId)).filter(Boolean)).map(F=>({participantId:F}))),zm({positionAssignments:b.positionAssignments,tournamentRecord:a,drawDefinition:c,matchUpFormat:r,matchUps:L,event:l})},D=M&&o.structures.find(b=>b?.matchUps.find(_=>_.matchUpId===d)),O=C(D||o);if(O.error)return v({result:O,stack:e})}}if(f){let M=hp({element:n,notes:f});if(M.error)return v({result:M,stack:e})}let P=a?.tournamentId,y=Fr().topics.includes(rp),E=(y||A)&&be({drawDefinition:c}),U=E&&re({matchUpFilters:{matchUpIds:[d]},nextMatchUps:!0,tournamentRecord:a,inContext:!0,drawDefinition:c,matchUpsMap:E}).matchUps?.[0];if(y&&U&&kC({tournamentId:P,inContextMatchUp:U}),Array.isArray(A)&&U&&!U.sides?.every(({participantId:M})=>M))if(u===bt)n.processCodes=mt([...n.processCodes??[],...A]);else for(let M of A||[]){let N=M&&n?.processCodes?.lastIndexOf(M);n?.processCodes?.splice(N,1)}return ht({eventId:l?.eventId,context:e,drawDefinition:c,tournamentId:P,matchUp:n}),{...R}}function Qm(t){let{dualWinningSideChange:e,matchUpStatusCodes:r,drawDefinition:n,matchUpStatus:o,structure:i,matchUp:s}=t,a=ha({matchUpStatus:o})||[Lo,kr].includes(o)&&e,c="attemptToModifyScore",u=!!s.collectionId,p=Br({drawDefinition:n,structure:i});if(!(u||p||WF({structure:i,matchUp:s})))return{error:rl};let d=[Ot].includes(o),l=yn({...t,matchUpStatusCodes:a&&r||[],matchUpStatus:a&&o||me,context:c,removeScore:d});return v({result:l,stack:c})}function WF({structure:t,matchUp:e}){let{drawPositions:r}=e,{positionAssignments:n}=de({structure:t});return n?.filter(i=>r?.includes(i.drawPosition)&&i.participantId)?.length===2}function qh({collectionGroups:t=[]}){let e=Object.assign({},...t.filter(n=>lt(n?.groupValue)&&n?.groupNumber).map(n=>({[n.groupNumber]:{...n,allGroupMatchUpsCompleted:!0,matchUpsCount:0,sideWins:[0,0],values:[0,0]}}))),r=Object.keys(e).map(n=>ct(n));return{groupValueGroups:e,groupValueNumbers:r}}function xb({collectionDefinition:t,groupValueNumbers:e,groupValueGroups:r,sideTieValues:n,tieMatchUps:o}){let i=o.filter(S=>S.collectionId===t.collectionId),s=[0,0],a=[0,0],c=i.every(S=>ie.includes(S.matchUpStatus)),{collectionValueProfiles:u,collectionGroupNumber:p,collectionValue:m,matchUpValue:d,winCriteria:l,scoreValue:f,setValue:g}=t,I=p&&e.includes(p),h=[0,0];if(i.forEach(S=>{S.winningSide&&(h[S.winningSide-1]+=1)}),lt(d)?i.forEach(S=>{S.winningSide&&(s[S.winningSide-1]+=d)}):lt(g)?i.forEach(S=>{S.score?.sets?.forEach(T=>{T.winningSide&&(s[T.winningSide-1]+=g)})}):lt(f)?i.forEach(S=>{S.score?.sets?.forEach(T=>{let{side1TiebreakScore:A=0,side2TiebreakScore:P=0,side1Score:y=0,side2Score:E=0}=T;(S.matchUpStatus===me||S.winningSide||T.winningSide)&&(y||E?(s[0]+=y,s[1]+=E):(A||P)&&T.winningSide&&(s[T.winningSide-1]+=1))})}):Array.isArray(u)&&i.forEach(S=>{if(S.winningSide){let T=S.collectionPosition,A=jF({collectionDefinition:t,collectionPosition:T});lt(A)&&(s[S.winningSide-1]+=A)}}),lt(m)){let S;if(l?.aggregateValue)c&&(lt(d||g||f)&&s[0]!==s[1]?S=s[0]>s[1]?1:2:h[0]!==h[1]&&(S=h[0]>h[1]?1:2));else if(l?.valueGoal)S=s.reduce((T,A,P)=>A>=l.valueGoal?P+1:T,0);else{let T=Math.floor(t.matchUpCount/2)+1;S=h.reduce((A,P,y)=>P>=T?y+1:A,0)}S&&(I?r[p].values[S-1]+=m:a[S-1]+=m)}else I?(r[p].values[0]+=s[0]||0,r[p].values[1]+=s[1]||0):a=s;I?(r[p].sideWins[0]+=h[0]||0,r[p].sideWins[1]+=h[1]||0,r[p].allGroupMatchUpsCompleted=r[p].allGroupMatchUpsCompleted&&c,r[p].matchUpsCount+=i.length):a.forEach((S,T)=>n[T]+=S||0)}function jF({collectionDefinition:t,collectionPosition:e}){return(t.collectionValueProfiles||[])?.find(o=>o.collectionPosition===e)?.matchUpValue}function $h({collectionValueProfiles:t,matchUpCount:e}){let r=[];if(!Array.isArray(t))return r.push(`collectionValueProfiles is not an array: ${t}`),{errors:r};if(t.length&&t.length!==e)return r.push("collectionValueProfiles do not align with matchUpsCount"),{errors:r};for(let o of t){if(typeof o!="object")return r.push(`valueProfile is not type object: ${o}`),{errors:r};let{matchUpValue:i,collectionPosition:s}=o;if(typeof i!="number"||typeof s!="number"||s>e||s<1)return r.push("Invalid value profile: value and collectionPosition must be numeric. collectionPosition cannot be greater than matchUpCount"),{errors:r}}let n=t.map(o=>o.collectionPosition);return n.length!==mt(n).length?(r.push("collectionPositions are not unique"),{errors:r}):{...R}}var YF="MIXED events can not contain mixed singles or { gender: ANY } collections",qF="events with { gender: ANY } can not contain MIXED singles collections";function Xm(t){let e="tieFormatGenderValidityCheck",{referenceGender:r,matchUpType:n,gender:o}=t;return r&&o&&[Zt,ce].includes(r)&&r!==o?v({result:{valid:!1,error:Sl},context:{gender:o},stack:e}):r===Cr&&(o===On||o===Cr&&n!==jt)?v({result:{error:Sl,valid:!1},info:YF,stack:e}):r===On&&o===Cr&&n!==jt?v({result:{error:Sl,valid:!1},info:qF,stack:e}):{valid:!0}}var $F=(t,e)=>t.filter(Boolean).every(r=>typeof r===e),KF=t=>t.filter(Boolean).every(se);function mu(t){let e=t.category;if(typeof e!="object")return{error:Jp};let{ageCategoryCode:r,ageMaxDate:n,ageMinDate:o,ageMax:i,ageMin:s}=e,a=e.categoryName,c;if(!$F([r,n,o,a],"string")||!KF([i,s]))return{error:Jp};let u=t.consideredDate??At(new Date().toLocaleDateString("sv"));if(!Pr(u))return{error:ir};let[p]=u.split("-").slice(0,3).map(x=>parseInt(x)),m=ju(u,-1),[d,l]=m.split("-").slice(1,3).map(x=>parseInt(x)),f=`${Ln(d)}-${Ln(l)}`,g=ju(u,1),[I,h]=g.split("-").slice(1,3).map(x=>parseInt(x)),S=`${Ln(I)}-${Ln(h)}`,T=s&&ju(u,-1*365*s),A=i&&ju(u,-1*365*i),P=[],y=x=>!P.includes(x)&&P.push(x);r=r??a;let E=/^([UO]?)(\d{1,2})([UO]?)$/,U=/^C(\d{1,2})-(\d{1,2})$/,M=r?.includes("-"),N=M&&r?.match(U),C=r?.match(E),D=(x,H)=>`${x}-${H}`,O=x=>{let H=p-x,V=D(H,S);e.ageMinDate&&e.ageMinDate!==V&&y(`Invalid submitted ageMinDate: ${o}`),o=V,r&&(e.ageMax&&e.ageMax!==x-1&&(y(`Invalid submitted ageMax: ${i}`),A=void 0),i=x-1)},b=x=>{let H=p-x-1,V=D(H,S);e.ageMin&&e.ageMin>x&&y(`Invalid submitted ageMin: ${s}`),e.ageMax&&e.ageMax>x&&y(`Invalid submitted ageMax: ${i}`),e.ageMinDate&&e.ageMinDate!==V&&y(`Invalid submitted ageMinDate: ${o}`),o=V,r&&(e.ageMax&&e.ageMax!==x&&(y(`Invalid submitted ageMax: ${i}`),T=void 0),i=x)},_=x=>{let H=p-x,V=D(H,f);e.ageMaxDate&&e.ageMaxDate!==V&&y(`Invalid submitted ageMaxDate: ${n}`),n=V,r&&(e.ageMin&&e.ageMin!==x+1&&(y(`Invalid submitted ageMin: ${s}`),T=void 0),s=x+1)},L=x=>{let H=p-x-1,V=D(H,f);e.ageMaxDate&&e.ageMaxDate!==V&&y(`Invalid submitted ageMaxDate: ${n}`),n=V,r&&(e.ageMin&&e.ageMin!==x&&(y(`Invalid submitted ageMin: ${s}`),T=void 0),s=x)},F=x=>{let[H,V,W]=(x.match(E)||[]).slice(1),B=parseInt(V);H==="U"?(e.ageMaxDate&&e.ageMaxDate!==n&&y(`Invalid submitted ageMaxDate: ${e.ageMaxDate}`),O(B)):H==="O"&&_(B),W==="U"?(e.ageMaxDate&&e.ageMaxDate!==n&&y(`Invalid submitted ageMaxDate: ${e.ageMaxDate}`),b(B)):W==="O"&&L(B),n=n??T,o=o??A};if(N){if(n=void 0,o=void 0,i=void 0,s=void 0,e.ageMin){let V=p-e.ageMin;n=D(V,f)}if(e.ageMax){let V=p-e.ageMax-1;o=D(V,S)}let[x,H]=(r?.match(U)??[]).slice(1).map(V=>parseInt(V));x<=H?(s=x,i=H,c=!0):y(`Invalid combined age range ${r}`)}else M?r?.split("-").forEach(F):C?F(r):(s&&_(s),i&&b(i));i&&e.ageMin&&e.ageMin>i&&(y(`Invalid submitted ageMin: ${e.ageMin}`),s=void 0);let w=rt({consideredDate:u,combinedAge:c,ageMaxDate:n,ageMinDate:o,ageMax:i,ageMin:s});return P.length&&(w.errors=P),w}function Jm({category:t}){if(!Ct(t))return{error:G};let e=mu({category:t});if(e.error)return{error:e};let{ratingMax:r,ratingMin:n}=t;return r&&!se(r)?v({result:{error:G},context:{ratingMax:r}}):n&&!se(n)?v({result:{error:G},context:{ratingMin:n}}):{...e}}function Zm({childCategory:t,withDetails:e,category:r}){let n=Jm({category:r}),o=Jm({category:t}),i=o.ageMin&&(n.ageMin&&o.ageMin<n.ageMin||n.ageMax&&o.ageMin>n.ageMax),s=o.ageMax&&(n.ageMax&&o.ageMax>n.ageMax||n.ageMin&&o.ageMax<n.ageMin),a=o.ageMinDate&&n.ageMaxDate&&new Date(o.ageMinDate)>new Date(n.ageMaxDate),c=o.ageMaxDate&&n.ageMinDate&&new Date(o.ageMaxDate)<new Date(n.ageMinDate),p=r?.ratingType&&t?.ratingType&&r.ratingType===t.ratingType&&(r.ratingMin&&t.ratingMin&&t.ratingMin<r.ratingMin||r.ratingMax&&t.ratingMax&&t.ratingMax>r.ratingMax||r.ratingMin&&t.ratingMax&&t.ratingMax<r.ratingMin||r.ratingMax&&t.ratingMin&&t.ratingMin>r.ratingMax),m=r?.ballType&&t?.ballType&&r.ballType!==t.ballType,f=rt({invalidRatingRange:p,invalidAgeMinDate:a,invalidAgeMaxDate:c,invalidBallType:m,invalidAgeMax:s,invalidAgeMin:i,valid:!p&&!a&&!c&&!m&&!s&&!i},!0);return e&&Object.assign(f,{categoryDetails:n,childCategoryDetails:o}),f}function td(t,e){if(Ct(t),(t?.bestOf||t?.exactly)&&t?.setFormat)return zF(t,e)}function jf(t){return!isNaN(Number(t))&&Number(t)}function Fb(t){let e=`T${t.minutes}`;return t.based&&(e+=t.based),t.modifier&&(e+=`@${t.modifier}`),e}function zF(t,e){let r=jf(t.bestOf)||void 0,n=jf(t.exactly)||void 0,o=r||n;if(t.setFormat?.timed&&t.simplified&&o===1)return Fb(t.setFormat);let i=o&&`${_m}${o}`||"",s=wb(t.setFormat,e),a=s&&`S:${s}`||"",c=wb(t.finalSetFormat,e),u=o&&o>1&&c&&s!==c&&`F:${c}`||"";if(i&&s)return[i,a,u].filter(m=>m).join("-")}function wb(t,e){if(typeof t=="object"&&Object.keys(t).length){if(t.timed)return Fb(t);if(t.tiebreakSet)return Lb(t.tiebreakSet);let r=jf(t.setTo);if(r){let n=t.NoAD&&Uf||"",o=Lb(t.tiebreakFormat),i=o&&`/${o}`||"",s=jf(t.tiebreakAt),a=s&&(s!==r||e)&&`@${s}`||"";if(o!==!1)return`${r}${n}${i}${a}`}}}function Lb(t){if(t){if(typeof t=="object"&&!t.tiebreakTo)return"";if(typeof t=="object"&&jf(t.tiebreakTo)){let e=`TB${t.tiebreakTo}${t.NoAD?Uf:""}`;return t.modifier&&(e+=`@${t.modifier}`),e}else return!1}}function Sr({matchUpFormat:t}){if(typeof t!="string")return!1;let e=Ze(t),r=t.match(/-S:([1-9])+\/TB([0-9]{1,2})@?([1-9]?)*/),n=r?.[1],o=r?.[2],i=r?.[3],s=t.match(/-F:([1-9])+\/TB([0-9]{1,2})@?([1-9]?)*/),a=s?.[1],c=s?.[2],u=s?.[3];return td(e,!!(r&&o&&n===i||s&&c&&a===u))===t}function du({checkCategory:t=!0,collectionDefinition:e,checkCollectionIds:r,checkGender:n=!0,referenceCategory:o,referenceGender:i,event:s}){i=i??s?.gender;let a="validateCollectionDefinition",c=[];if(typeof e!="object")return c.push(`collectionDefinition must be an object: ${e}`),v({result:{errors:c,error:Yn},stack:a});let{collectionValueProfiles:u,collectionGroupNumber:p,collectionValue:m,collectionId:d,matchUpCount:l,matchUpFormat:f,matchUpValue:g,matchUpType:I,scoreValue:h,setValue:S,category:T,gender:A}=e;if(r&&typeof d!="string"&&c.push(`collectionId is not type string: ${d}`),typeof l!="number"&&c.push(`matchUpCount is not type number: ${l}`),I&&![ee,jt].includes(I)&&c.push(`matchUpType must be SINGLES or DOUBLES: ${I}`),[!!u?.length].concat([g,m,h,S].map(lt)).filter(Boolean).length!==1&&c.push("Missing value definition for matchUps: matchUpValue, collectionValue, or collectionValueProfiles"),g&&typeof g!="number"&&c.push(`matchUpValue is not type number: ${g}`),m&&typeof m!="number"&&c.push(`collectionValue is not type number: ${m}`),u&&l){let y=$h({collectionValueProfiles:u,matchUpCount:l});y.errors&&c.push(...y.errors)}if(p&&typeof p!="number"&&c.push(`collectionGroupNumber is not type number: ${m}`),f&&!Sr({matchUpFormat:f})&&c.push(`Invalid matchUpFormat: ${f}`),n){let y=Xm({referenceGender:i,matchUpType:I,gender:A});if(y.error)return v({context:{referenceGender:i,gender:A},result:y,stack:a})}if(t&&o&&T){let y=Zm({category:o,childCategory:T});if(!y.valid)return v({result:{error:Jp},context:y,stack:a})}return c.length?v({result:{errors:c,error:Oy},stack:a}):{valid:!0}}function cr(t){let e=!!(t?.enforceCategory!==!1&&t?.category),r=!!(t?.enforceGender!==!1&&t?.gender),n=t?.checkCollectionIds,o=t?.tieFormat,i=t?.event,s="validateTieFormat",a=[];if(!t||!o||typeof o!="object")return a.push("tieFormat must be an object"),v({result:{error:Jo},context:{tieFormat:o,errors:a},stack:s});if(typeof o.winCriteria!="object")return a.push("tieFormat.winCriteria must be an object"),v({result:{error:Jo},context:{tieFormat:o,errors:a},stack:s});if(!Array.isArray(o.collectionDefinitions))return a.push(Tn("tieFormat.collectionDefinitions")),v({result:{error:Jo},context:{tieFormat:o,errors:a},stack:s});let c,u=o.collectionDefinitions.every(g=>{let{setValue:I,scoreValue:h,collectionValue:S}=g;(I||h)&&!S&&(c=!0);let{valid:T,errors:A}=du({referenceCategory:t.category,referenceGender:t.gender,collectionDefinition:g,checkCollectionIds:n,checkCategory:e,checkGender:r,event:i});return T?!0:(Array.isArray(A)&&a.push(...A),!1)}),p=typeof o.winCriteria?.valueGoal=="number"&&o.winCriteria?.valueGoal>0&&!c||o.winCriteria?.aggregateValue;if(!(p||o.winCriteria?.aggregateValue))return c?a.push("aggregateValue is required"):a.push("Either non-zero valueGoal, or { aggregateValue: true } must be specified in winCriteria"),v({context:{tieFormat:o,errors:a,aggregateValueImperative:c},result:{error:Jo},stack:s});let m=o.collectionDefinitions.map(({collectionId:g})=>g),d=!n||m.length===mt(m).length,l=u&&p&&d,f={valid:l,errors:a};return l?f:v({result:{error:Jo},context:{tieFormat:o,errors:a},stack:s})}function lu(t){let{sideAdjustments:e=[0,0],separator:r="-",drawDefinition:n,matchUpsMap:o,structure:i,matchUp:s,event:a}=t;if(!Array.isArray(e)||e.length!==2||isNaN(e.reduce((A,P)=>A+P)))return{error:G};if(!s)return{error:or};let c=Ve({matchUp:s,drawDefinition:n,structure:i,event:a})?.tieFormat||t?.tieFormat;if(!c)return{error:Va};let u=cr({tieFormat:c});if(u.error)return u;let p=c?.collectionDefinitions||[],m=s?.tieMatchUps??[],d=[0,0],{groupValueGroups:l,groupValueNumbers:f}=qh(c);for(let A of p)xb({collectionDefinition:A,groupValueNumbers:f,groupValueGroups:l,sideTieValues:d,tieMatchUps:m});for(let A of f){let P=l[A],{allGroupMatchUpsCompleted:y,matchUpCount:E,winCriteria:U,groupValue:M,sideWins:N,values:C}=P,D;if(U?.aggregateValue)y&&C[0]!==C[1]&&(D=C[0]>C[1]?1:2);else if(U?.valueGoal)D=C.reduce((O,b,_)=>b>=U.valueGoal?_+1:O,void 0);else{let O=Math.floor(E/2)+1;D=N.reduce((b,_,L)=>_>=O?L+1:b,void 0)}D&&(d[D-1]+=M||0)}let g=d.map((A,P)=>(A||0)+e[P]),I={side1Score:g[0],side2Score:g[1],winningSide:void 0},h=g.join(r),S=g.slice().reverse().join(r),T;if(c?.winCriteria){let{valueGoal:A,aggregateValue:P,tallyDirectives:y}=c.winCriteria;if(A?T=g.map((U,M)=>({sideNumber:M+1,points:U})).find(({points:U})=>U>=A)?.sideNumber:P&&m.every(U=>U.matchUpStatus&&ie.includes(U.matchUpStatus)||U.winningSide)&&g[0]!==g[1]&&(T=g[0]>g[1]?1:2),!T&&y){let E=s.matchUpId,U=s.hasContext?s:o?.drawMatchUps?.[E]||n&&xt({inContext:!0,drawDefinition:n,matchUpId:E})?.matchUp;if(U){let{completedTieMatchUps:M,order:N}=Ua({matchUps:[U]});if(M&&N?.length){let C=N[0].participantId;T=U.sides.find(({participantId:D})=>D===C)?.sideNumber}}}}return T&&(I.winningSide=T),{scoreStringSide1:h,scoreStringSide2:S,winningSide:T,set:I}}function Pa({inContextDualMatchUp:t,drawDefinition:e,tournamentId:r,dualMatchUp:n,eventId:o}){if(n){t||(t=xt({matchUpId:n.matchUpId,inContext:!0,drawDefinition:e})?.matchUp);let{extension:i}=ut({element:e,name:mo}),s=J(i?.value||{},!1,!0),a=({displaySideNumber:c,drawPosition:u,sideNumber:p})=>({drawPosition:u,sideNumber:p,displaySideNumber:c});n.sides=t?.sides?.map(c=>{let u=c.participantId,p=u&&s[u]||void 0,{lineUp:m,...d}=n.sides?.find(({sideNumber:f})=>f===c.sideNumber)??{},l=m?.length?m:p;return{...a(c),...d,lineUp:l}}),ht({context:"ensureSidLineUps",matchUp:n,drawDefinition:e,tournamentId:r,eventId:o})}}function Ke(t){if(t)return J(t,!1,!0)}function Yf(t){let e=vt(t,[{[ye]:!0}]);return e.error?e:Object.keys(t.tournamentRecords).reduce((n,o)=>{n.tournamentIdMap[o]=[];let s=t.tournamentRecords[o].events??[],a=s.map(({eventId:u})=>u),c=s.map(u=>(u.drawDefinitions??[]).map(({drawId:p})=>p)).flat();return n.tournamentIdMap[o].push(...a,...c),n.eventIds.push(...a),n.drawIds.push(...c),n},{eventIds:[],drawIds:[],tournamentIdMap:{}})}function Kh({tournamentRecords:t,eventId:e,drawId:r}){let{tournamentIdMap:n}=Yf({tournamentRecords:t});return(n?Object.keys(n):[]).find(i=>e&&n?.[i].includes(e)||r&&n?.[i].includes(r))}function En(t){let{exitWhenNoValues:e,drawDefinition:r,matchUpStatus:n,removeScore:o,matchUpsMap:i,matchUpId:s,event:a}=t,c=t.tournamentRecords||t.tournamentRecord&&{[t.tournamentRecord?.tournamentId]:t.tournamentRecord}||{},u=t.tournamentId||t.tournamentRecord?.tournamentId;c&&Kh({tournamentRecords:c,...t});let p=u&&c[u];if(!p)return{error:j};let m=xt({drawDefinition:r,event:a,matchUpId:s});if(m.error)return m;if(!m.matchUp)return{error:De};let{matchUp:d,structure:l}=m;if(!d.tieMatchUps)return{error:ze};Pa({tournamentId:p?.tournamentId,eventId:a?.eventId,dualMatchUp:d,drawDefinition:r});let{extension:f}=ut({name:za,element:d});if(f?.value)if(o)rr({element:d,name:za});else return{...R,score:d.score};let g=Ve({drawDefinition:r,structure:l,matchUp:d,event:a})?.tieFormat;d.tieFormat=Ke(g);let I=lu({drawDefinition:r,matchUpsMap:i,structure:l,matchUp:d,event:a}),{winningSide:h,set:S,scoreStringSide1:T,scoreStringSide2:A}=I,P=S?.side1Score||S?.side2Score;if(e&&!d.score&&!P)return{...R};let y={scoreStringSide1:T,scoreStringSide2:A,sets:S?[S]:[]},E=h&&[1,2].includes(h),U=E&&me||Mf({matchUpStatus:n??d.matchUpStatus,tieMatchUps:d.tieMatchUps,winningSide:d.winningSide,score:y})&&Sn||Kt,M=!!(d.winningSide&&!E),N=d.tieMatchUps.find(({score:D,winningSide:O,matchUpStatus:b})=>D?.sets?.length&&(D.sets[0].side1Score||D.sets[0].side2Score)||b&&ie.includes(b)||O),C;if(d.tieFormat&&!E&&!N){let D=Ve({drawDefinition:r,structure:l,event:a})?.tieFormat;D&&JSON.stringify(g)===JSON.stringify(D)&&(d.tieFormatId=void 0,d.tieFormat=void 0,C=!0)}return yn({appliedPolicies:t.appliedPolicies,matchUpStatus:U,score:y,removeWinningSide:M,tournamentRecord:p,drawDefinition:r,removeScore:o,winningSide:h,matchUpId:s,matchUp:d,event:a}),{...R,score:y,removeWinningSide:M,tieFormatRemoved:C,winningSide:h}}function Gb({winnerMatchUpDrawPositionIndex:t,inContextDrawMatchUps:e,projectedWinningSide:r,sourceMatchUpStatus:n,winningDrawPosition:o,tournamentRecord:i,winnerTargetLink:s,sourceMatchUpId:a,drawDefinition:c,winnerMatchUp:u,dualMatchUp:p,matchUpsMap:m,event:d}){let l="directWinner";if(s){let f=u.drawPositions||[],g=f[t],I=s.source.structureId,h=st({structureId:I,drawDefinition:c});if(h.error)return h;let{structure:S}=h,{positionAssignments:T}=de({structureId:I,drawDefinition:c}),P=T?.find(D=>D.drawPosition===o)?.participantId,y=s.target.structureId,{positionAssignments:E}=de({structureId:y,drawDefinition:c}),M=E?.find(D=>D.participantId===P)?.drawPosition,N=E?.filter(D=>{let O=f.includes(D.drawPosition),b=!D.participantId&&!D.bye&&!D.qualifier;return O&&b}).map(D=>D.drawPosition),C=N?.includes(g);if(P&&s.target.roundNumber===1&&C)An({drawPosition:g,participantId:P,structureId:y,inContextDrawMatchUps:e,sourceMatchUpStatus:n,tournamentRecord:i,drawDefinition:c,matchUpsMap:m,event:d});else if(P&&N?.length){let D=N.pop();D&&An({participantId:P,structureId:y,inContextDrawMatchUps:e,sourceMatchUpStatus:n,tournamentRecord:i,drawDefinition:c,drawPosition:D,matchUpsMap:m,event:d})}else if(M){let D=cc({drawPosition:M,matchUpId:u.matchUpId,inContextDrawMatchUps:e,sourceMatchUpStatus:n,tournamentRecord:i,sourceMatchUpId:a,drawDefinition:c,matchUpsMap:m});if(D.error)return v({result:D,stack:l})}else if(S?.stage!==at){let D="winner target position unavaiallble";return console.log(D),{error:D}}if(S?.seedAssignments&&S.structureId!==y){let D=S.seedAssignments.find(({participantId:b})=>b===P),O=D?.participantId;D&&O&&Gs({eventId:u?.eventId,structureId:y,...D,tournamentRecord:i,drawDefinition:c,participantId:O})}}else{let f=cc({matchUpId:u.matchUpId,drawPosition:o,inContextDrawMatchUps:e,sourceMatchUpStatus:n,tournamentRecord:i,sourceMatchUpId:a,drawDefinition:c,matchUpsMap:m});if(f.error)return f}if(p&&r){let f=p.sides?.find(g=>g.sideNumber===r);if(f?.lineUp){let g=p.roundPosition,I=u.roundPosition,h=g===I&&g!==1||Math.floor(g/2)===I?2:1,S=m?.drawMatchUps?.find(({matchUpId:P})=>P===u.matchUpId),T=[1,2].map(P=>({...S.sides?.find(E=>E.sideNumber===P)||{},sideNumber:P}));S.sides=T;let A=S.sides.find(P=>P.sideNumber===h);if(A){let P=f.lineUp?.filter(y=>y?.participantId);A.lineUp=Bm({lineUp:P}),ht({tournamentId:i?.tournamentId,eventId:u?.eventId,matchUp:S,context:l,drawDefinition:c})}}}return{...R}}function kb(t){let{loserMatchUpDrawPositionIndex:e,inContextDrawMatchUps:r,projectedWinningSide:n,sourceMatchUpStatus:o,loserDrawPosition:i,tournamentRecord:s,loserTargetLink:a,drawDefinition:c,loserMatchUp:u,dualMatchUp:p,matchUpsMap:m,event:d}=t,l="directLoser",f=a.linkCondition,g=u.drawPositions||[],I=f===Bn&&u.roundNumber===2&&Math.min(...g.filter(Boolean)),h=I||g[e],S=I||g[1-e],T=a.source.structureId,{structure:A}=st({structureId:T,drawDefinition:c}),{matchUps:P}=Pt({afterRecoveryTimes:!1,inContext:!0,drawDefinition:c,structure:A,event:d}),E=P.filter(B=>B.drawPositions?.includes(i)).filter(B=>{let q=B.sides.find(k=>k.drawPosition===i),Y=B.matchUpStatus===Ot||B.matchUpStatus===bt&&!he(B);return q?.sideNumber===B.winningSide&&!Y}),U=f===Bn&&E.length===0,{positionAssignments:M}=de({structureId:T,drawDefinition:c}),C=M?.find(B=>B.drawPosition===i)?.participantId,D=a.target.structureId,{positionAssignments:O}=de({structureId:D,drawDefinition:c}),b=O?.filter(({drawPosition:B})=>g.includes(B));if(b?.some(B=>B.participantId===C))return{...R};let L=b?.filter(B=>{let q=g.includes(B.drawPosition),Y=!B.participantId&&!B.bye&&!B.qualifier;return q&&Y}).map(B=>B.drawPosition),F=L?.includes(h),w=a.target.roundNumber>1&&L?.length,x=a.target.roundNumber===1&&F;if(I){let B=H();if(B.error)return v({result:B,stack:l})}else if(x){let B=W();if(B.error)return v({result:B,stack:l})}else if(C&&w){L.sort(oe);let B=L[0],q=An({participantId:C,structureId:D,drawPosition:B,inContextDrawMatchUps:r,sourceMatchUpStatus:o,tournamentRecord:s,drawDefinition:c,matchUpsMap:m,event:d});if(q.error)return v({result:q,stack:l})}else return v({result:{error:Ss},context:{loserDrawPosition:i,loserTargetLink:a},stack:l});if(A?.seedAssignments&&A.structureId!==D){let B=A.seedAssignments.find(({participantId:Y})=>Y===C),q=B?.participantId;B&&q&&Gs({eventId:u?.eventId,structureId:D,...B,tournamentRecord:s,drawDefinition:c,participantId:q})}if(p&&n){let B=p.sides?.find(q=>q.sideNumber===3-n);if(B?.lineUp){let{roundNumber:q,eventId:Y}=u,{roundPosition:k}=p,K=q===1?2-k%2:1,X=m?.drawMatchUps?.find(({matchUpId:Q})=>Q===u.matchUpId),$=[1,2].map(Q=>({...X.sides?.find(ot=>ot.sideNumber===Q)||{},sideNumber:Q}));X.sides=$;let nt=X.sides.find(Q=>Q.sideNumber===K);nt&&(nt.lineUp=Bm({lineUp:B.lineUp}),ht({tournamentId:s?.tournamentId,matchUp:X,context:l,drawDefinition:c,eventId:Y}))}}return{...R};function H(){let B="loserLinkFedFMLC";return U?v({result:W(),stack:B}):v({result:V(),stack:B})}function V(){let B=yr({drawPosition:S,structureId:D,tournamentRecord:s,drawDefinition:c,event:d});return v({result:B,stack:"assignLoserPositionBye"})}function W(){let B=C?An({drawPosition:h,participantId:C,structureId:D,inContextDrawMatchUps:r,sourceMatchUpStatus:o,tournamentRecord:s,drawDefinition:c,matchUpsMap:m,event:d}):{error:te};return v({result:B,stack:"assignLoserDrawPosition"})}}function zh(t){let e=Qm(t);if(e.error)return e;let r=ha({matchUpStatus:t.matchUpStatus}),{dualWinningSideChange:n,projectedWinningSide:o,inContextDrawMatchUps:i,tournamentRecord:s,drawDefinition:a,matchUpStatus:c,dualMatchUp:u,matchUpsMap:p,winningSide:m,targetData:d,matchUpId:l,structure:f,matchUp:g,event:I}=t,h="directParticipants",S=!!g.collectionId,T=Br({drawDefinition:a,structure:f}),A=g.drawPositions,P;if(S){let{matchUpTieId:y,matchUpsMap:E}=t,U=En({appliedPolicies:t.appliedPolicies,matchUpId:y,tournamentRecord:s,drawDefinition:a,matchUpsMap:E,event:I});if(P=U&&{tieMatchUpResult:U},A=i.find(({matchUpId:N})=>N===y)?.drawPositions,!n)return v({result:{...R,...P},stack:h})}if(T)return v({result:{...R,...P},stack:h});if(A){let y=o?o-1:m-1,E=1-y,U=A[y],M=A[E],{targetLinks:{loserTargetLink:N,winnerTargetLink:C,byeTargetLink:D},targetMatchUps:{winnerMatchUpDrawPositionIndex:O,loserMatchUpDrawPositionIndex:b,winnerMatchUp:_,loserMatchUp:L,byeMatchUp:F}}=d;if(_){let w=Gb({sourceMatchUpStatus:r&&c||me,winnerMatchUpDrawPositionIndex:O,sourceMatchUpId:l,inContextDrawMatchUps:i,projectedWinningSide:o,winningDrawPosition:U,tournamentRecord:s,winnerTargetLink:C,drawDefinition:a,winnerMatchUp:_,dualMatchUp:u,matchUpsMap:p,event:I});if(w.error)return v({result:w,stack:h})}if(L){let w=kb({sourceMatchUpStatus:r&&c||me,loserMatchUpDrawPositionIndex:b,sourceMatchUpId:l,inContextDrawMatchUps:i,projectedWinningSide:o,loserDrawPosition:M,tournamentRecord:s,loserTargetLink:N,drawDefinition:a,loserMatchUp:L,winningSide:m,matchUpsMap:p,dualMatchUp:u,event:I});if(w.error)return v({result:w,stack:h})}if(F){let w=F.drawPositions||[],x=Math.min(...w.filter(Boolean)),H=D.target.structureId,V=yr({drawPosition:x,structureId:H,tournamentRecord:s,drawDefinition:a,event:I});if(V.error)return v({result:V,stack:h})}}else return v({result:{error:Fa},stack:h});return v({result:{...R,...P},stack:h})}function ed(t){let e="genPlayoffStructure";if(!t.drawDefinition)return v({result:{error:z},stack:e});let r=cu(t);if(r.error)return v({result:r,stack:e});let{structureId:n,addNameBaseToAttributeName:o,playoffStructureNameBase:i,finishingPositionNaming:s,finishingPositionLimit:a,playoffAttributes:c,playoffPositions:u,roundOffsetLimit:p,tournamentRecord:m,exitProfileLimit:d,roundProfiles:l,roundNumbers:f,idPrefix:g,isMock:I,event:h,uuids:S}=t,T=J(t.drawDefinition,!1,!0),{structure:A}=st({structureId:n,drawDefinition:T});if(!A)return v({result:{error:_t},stack:e});if(A.structureType===we||A.structures)return Pb({sourceStructureId:A.structureId,...t,...r,drawDefinition:T});let{playoffRoundsRanges:P,playoffRounds:y}=r,{playoffPositionsReturned:E,error:U,playoffSourceRounds:M,playoffRoundsRanges:N}=wh(t);if(U)return v({result:{error:U},stack:e});let C=l?.length&&Object.assign({},...l),D=f||typeof l=="object"&&l.map($=>Object.keys($)).flat(),O=Array.isArray(D)&&D.map($=>!isNaN($)&&ct($)).filter(Boolean);if(O){if(!Array.isArray(O))return v({result:{error:G},context:{validRoundNumbers:O},stack:e});O.forEach($=>{if(!y?.includes($))return v({result:{error:G},context:{roundNumber:$},stack:e})})}u&&u.forEach($=>{if(!E?.includes($))return v({result:{error:G},context:{playoffPosition:$},stack:e})});let b=O||M,_=O?P:N,L=[],F=[];for(let $ of b??[]){let nt=_?.find(Ee=>Ee.roundNumber===$);if(!nt)return v({result:{error:G},context:{roundNumber:$},stack:e});let Q=nt.finishingPositions.length,it=Math.min(...nt.finishingPositions)-1,ot=2,dt=$&&C?.[$]&&ot+C[$]-1,zt=mc({exitProfile:`0-${$}`,addNameBaseToAttributeName:o,playoffStructureNameBase:i,finishingPositionOffset:it,playoffAttributes:c,exitProfileLimit:d,stage:ae,roundOffset:0,drawDefinition:T,sequenceLimit:dt,stageSequence:ot,drawSize:Q,idPrefix:g,isMock:I,uuids:S,finishingPositionNaming:s,finishingPositionLimit:a,roundOffsetLimit:p});if(zt.error)return v({result:zt,stack:e});let{structures:Et,links:ge}=zt;if(Et?.length&&L.push(...Et),ge?.length&&F.push(...ge),zt.structureId&&$){let Ee={linkType:Vn,source:{structureId:n,roundNumber:$},target:{structureId:zt.structureId,feedProfile:rn,roundNumber:1}};F.push(Ee)}}if(!L.length)return v({result:{error:G},info:"No structures generated",stack:e});T.structures.push(...L),T.links.push(...F);let{matchUps:w,matchUpsMap:x}=re({inContext:!0,drawDefinition:T}),H=L.map(({structureId:$})=>$),V=w?.filter(({structureId:$})=>H.includes($)).map(le),W=x?.drawMatchUps?.filter(({matchUpId:$})=>V?.includes($));if(W?.length){let $=Ve({drawDefinition:T,event:h})?.tieFormat;$&&W.forEach(nt=>{let{tieMatchUps:Q}=Ea({matchUp:nt,tieFormat:$,isMock:I});Object.assign(nt,{tieMatchUps:Q,matchUpType:Bt})})}w?.filter($=>es({matchUp:$})&&$.structureId===n)?.forEach($=>{let{matchUpId:nt,score:Q,winningSide:it}=$,ot=Je({inContextDrawMatchUps:w,drawDefinition:T,matchUpId:nt}),dt=zh({inContextDrawMatchUps:w,tournamentRecord:m,drawDefinition:T,matchUpsMap:x,winningSide:it,targetData:ot,matchUpId:nt,structure:A,matchUp:$,score:Q,event:h});dt.error&&console.log(dt.error)}),w?.filter($=>$.matchUpStatus===Ut&&$.structureId===n)?.forEach($=>{let{matchUpId:nt}=$,Q=Je({inContextDrawMatchUps:w,drawDefinition:T,matchUpId:nt}),{targetLinks:{loserTargetLink:it},targetMatchUps:{loserMatchUpDrawPositionIndex:ot,loserMatchUp:dt}}=Q;if(it&&dt){let zt=it.target.structureId,Et=dt.drawPositions[ot],ge=yr({drawPosition:Et,structureId:zt,tournamentRecord:m,drawDefinition:T,event:h});ge.error&&console.log(ge.error)}});let Y=[],k=rs({inContextDrawMatchUps:w,drawDefinition:T,matchUpsMap:x}).goesToMap,{structure:K}=st({drawDefinition:t.drawDefinition,structureId:n}),{matchUps:X}=Pt({structure:K});return X.forEach($=>{let nt=k?.loserMatchUpIds[$.matchUpId];if(nt&&$.loserMatchUpId!==nt){$.loserMatchUpId=nt;let it={tournamentId:m?.tournamentId,eventId:t.event?.eventId,context:e,matchUp:$};Y.push(it)}let Q=k?.winnerMatchUpIds[$.matchUpId];if(Q&&$.winnerMatchUpId!==Q){$.winnerMatchUpId=Q;let it={tournamentId:m?.tournamentId,eventId:t.event?.eventId,context:e,matchUp:$};Y.push(it)}}),{structures:L,matchUpModifications:Y,links:F,drawDefinition:T,...R}}function bU(t){return $f({...t,itemType:"attachConsolationStructures"})}function qf(t){return $f({...t,itemType:"attachPlayoffStructures"})}function $f({itemType:t="attachStructures",matchUpModifications:e,tournamentRecord:r,drawDefinition:n,structures:o,links:i=[],event:s}){let a="attachStructures";if(!n)return{error:z};if(!Array.isArray(o)||!Array.isArray(i))return v({result:{error:G},stack:a});let c=h=>[h.source.structureId,h.source.roundNumber||h.source.finishingPositions?.join("|"),h.target.roundNumber].join("|"),u=n.links?.map(c);if(i.some(h=>{let S=c(h);return u?.includes(S)}))return v({result:{error:El},info:"playoff structure exists",stack:a});i.length&&n.links?.push(...i);let m=o.map(({structureId:h})=>h),d=n.structures?.map(({structureId:h})=>h);n.structures=(n.structures??[]).map(h=>m.includes(h.structureId)?o.find(({structureId:S})=>S===h.structureId):h);let l=o?.filter(({structureId:h})=>!d?.includes(h));l.length&&n.structures.push(...l),rs({drawDefinition:n});let f=o.map(h=>Pt({structure:h})?.matchUps||[]).flat();lo({tournamentId:r?.tournamentId,eventId:s?.eventId,drawDefinition:n,matchUps:f});let g=o.map(({structureId:h})=>h);if(Rt({drawDefinition:n,structureIds:g}),e?.length){let h={};e.forEach(T=>{let A=T.matchUp?.matchUpId;A&&(h[A]=T)});let S=T=>{T.matchUps.forEach(A=>{if(h[A.matchUpId]){let{tieMatchUps:P,...y}=h[A.matchUpId].matchUp;if(Object.assign(A,y),P?.length){let E={};P.forEach(U=>h[U.matchUpId]=U),A.tieMatchUps.forEach(U=>Object.assign(U,E[U.matchUpId]))}h[A.matchUpId].matchUp=A,ht(h[A.matchUpId])}})};n.structures.forEach(T=>{if(d?.includes(T.structureId))if(T.structures)for(let A of T.structures)S(A);else S(T)})}let I=l.map(Dr("structureId"));if(r){let S={itemValue:{structureIds:g,drawId:n.drawId},itemType:t};li({element:r,timeItem:S})}return{...R,addedStructureIds:I}}function Sp(t){let{structures:e,links:r,matchUpModifications:n,error:o}=ed(t);if(o)return{error:o};let i=t.drawDefinition;return qf({tournamentId:t.tournamentRecord?.tournamentId,eventId:t.event?.eventId||t.eventId,matchUpModifications:n,drawDefinition:i,structures:e,links:r})}function wi(t){let e=vt(t,[{_anyOf:{[ye]:!1,[Fn]:!1,[Ei]:!1,[$a]:!1},[wl]:!0}]);if(e.error)return e;let r=[],n=t.drawDefinition??t.event??((t.tournamentId||!t.tournamentRecords)&&t.tournamentRecord);if(n){let o=Vb(t,n);if(o.error)return o;r.push(...o?.applied??[]),t.drawDefinition&&Rt({drawDefinition:t.drawDefinition,tournamentId:t.tournamentId})}else if(t.tournamentRecords){let o=Object.keys(t.tournamentRecords);if(!o.length)return{error:j};for(let i of o){let s=t.tournamentRecords[i],a=Vb(t,s);if(a.error)return a;r.push(...a?.applied??[])}}else return{error:j};return r.length?{...R,applied:r}:{error:tI}}function Vb(t,e){let r=yt(t).appliedPolicies??{};e.extensions||(e.extensions=[]);let n=[],o=Object.keys(t.policyDefinitions);if(!o.length)return{error:xu};for(let i of o)if(!r[i]||t.allowReplacement){let s=t.policyDefinitions[i];if(!s)continue;if(!Ct(s))return{error:G};let{policyName:a,...c}=s;if(!c||!Object.keys(c).length||a&&!er(a))return{error:G};r[i]=t.policyDefinitions[i],n.push(i)}return n?.length?{...gt({element:e,extension:{name:Fc,value:r}}),applied:n}:{applied:n,error:tI}}function Kf({tournamentRecord:t,drawDefinition:e,flightProfile:r,drawName:n,drawId:o,event:i}){if(!n||typeof n!="string")return v({result:{error:G},context:{drawName:n}});r||(r=kt({event:i}).flightProfile);let s=r?.flights?.find(a=>a.drawId===o);if(s){s.drawName=n;let a={name:Gr,value:{...r,flights:r.flights}};po({event:i,extension:a})}return e&&(e.drawName=n,Rt({tournamentId:t?.tournamentId,drawDefinition:e})),!s&&!e?{error:z}:{...R,flight:s}}function OU({tournamentRecord:t,drawDefinition:e,drawUpdates:r,drawId:n,event:o}){if(!Ct(r))return{error:G};let i=kt({event:o}).flightProfile,s=r.drawName&&Kf({drawName:r.drawName,tournamentRecord:t,drawDefinition:e,flightProfile:i,drawId:n,event:o});if(s?.error)return s?.error;let a=s?.flight||i?.flights?.find(c=>c.drawId===n);if(!a&&!e)return{error:z};if(a){let c={name:Gr,value:{...i,flights:i.flights}};po({event:o,extension:c})}return e&&(r.policyDefinitions&&wi({policyDefinitions:r.policyDefinitions,drawDefinition:e}),Rt({tournamentId:t?.tournamentId,drawDefinition:e})),{...R}}function _U({tournamentRecord:t,removeScheduling:e,drawDefinition:r}){if(!r)return{error:z};let n=be({drawDefinition:r}),o=s=>n?.drawMatchUps?.find(a=>a.matchUpId===s);for(let s of r.structures||[]){let{positionAssignments:a,stage:c,stageSequence:u}=s;a&&(u!==1||![at,tt].includes(c))&&(s.positionAssignments=a.map(m=>(delete m.participantId,m)),s.seedAssignments=[]);let{matchUps:p}=Pt({afterRecoveryTimes:!1,inContext:!0,matchUpsMap:n,structure:s});for(let m of p){let{matchUpId:d,roundNumber:l,sides:f}=m,g=o(d);if(g){if(delete g.extensions,delete g.notes,g.matchUpStatus!==Ut&&Object.assign(g,pu),l&&l>1&&g.drawPositions){let I=f?.map(({drawPosition:S,participantFed:T})=>!T&&S).filter(Boolean),h=g.drawPositions.map(S=>I.includes(S)?void 0:S);g.drawPositions=h}e?delete g.timeItems:g.timeItems?.length&&(g.timeItems=g.timeItems.filter(I=>I.itemType&&![ho,si,bs,wE,Os,_s].includes(I.itemType))),ht({tournamentId:t?.tournamentId,context:"resetDrawDefiniton",drawDefinition:r,matchUp:g})}}}let i=(r.structures||[]).map(({structureId:s})=>s);return Rt({drawDefinition:r,structureIds:i}),{...R}}function fu({tournamentRecord:t}){if(!t)return{error:j};let e={positionsNoOutcomes:[],canBePruned:[],matchPlay:[],inactive:[],drawAnalysis:{}},r={};return(t.events?.map(o=>{let i=o.eventId;return r[i]=o,(o?.drawDefinitions||[]).map(s=>({drawDefinition:s,eventId:i}))}).flat().filter(Boolean)).forEach(({drawDefinition:o,eventId:i})=>{let s=0,a=0,c=0,{allStructuresLinked:u}=au({drawDefinition:o}),p=r[i],d=(o?.structures||[]).map(P=>{let{stage:y,stageSequence:E,structureId:U}=P,M=Ds[y],{inContextStructureMatchUps:N}=Sa({drawDefinition:o,structure:P,event:p}),C=N?.filter(({winningSide:q})=>q),D=C.filter(Boolean).length||0;a+=D,c+=N.length-a;let O=Math.max(C.filter(({roundNumber:q})=>q===1).map(({roundPosition:q})=>q)),{positionAssignments:b}=Dt({structure:P}),_=b?.filter(({participantId:q})=>q);s+=_?.length??0;let L=(b?.length??0)-(_?.length??0),{roundMatchUps:F,roundProfile:w,roundNumbers:x,maxMatchUpsCount:H}=Xe({matchUps:N}),V=w&&Object.keys(w).filter(q=>!w[q].inactiveRound).map(q=>parseInt(q)),W=w&&Object.keys(w).filter(q=>w[q].inactiveRound).map(q=>parseInt(q)),B=w&&Object.values(w).every(q=>q.inactiveRound);return{positionsAssignedCount:_?.length??0,maxWinningSideFirstRoundPosition:O,unassignedPositionsCount:L,inactiveStructure:B,maxMatchUpsCount:H,inactiveRounds:W,roundMatchUps:F,activeRounds:V,roundNumbers:x,roundProfile:w,structureId:U,stageSequence:E,orderNumber:M,stage:y}}),l=d.find(P=>P.orderNumber===2&&P.stageSequence===1),f=d.filter(({inactiveStructure:P})=>!P).length,{links:g}=Rs({structureId:l.structureId,drawDefinition:o}),I=ct(l.activeRounds[0])===1&&l.activeRounds.length===1&&f===1,h=d?.every(({inactiveStructure:P})=>P),S=!g.length&&l.activeRounds.length&&(l.roundProfile[1].inactiveCount||l.inactiveRounds.length),T=o.drawId;s&&!a&&e.positionsNoOutcomes.push(T),h&&e.inactive.push(T),I&&e.matchPlay.push(T),S&&e.canBePruned.push(T);let A={matchUpsWithWinningSideCount:a,matchUpsNoOutcomeCount:c,positionsAssignedCount:s,allStructuresLinked:u,structuresData:d,inactiveDraw:h,isMatchPlay:I,drawId:T};e.drawAnalysis[T]=A}),{...R,drawsAnalysis:e}}function vU({matchPlayDrawPositions:t=!0,tournamentRecord:e,drawDefinition:r,drawId:n}){if(!e)return{error:j};if(!r)return{error:z};let o=[],{drawsAnalysis:i}=fu({tournamentRecord:e});if(i.canBePruned.includes(n)){let s=i.matchPlay.includes(n),a=i.drawAnalysis[n],{structures:[c]}=Cn({stageSequence:1,drawDefinition:r,stage:tt}),u=a.structuresData.find(({structureId:l})=>c.structureId===l),p=(c.matchUps??[]).sort((l,f)=>l.roundPosition-f.roundPosition);o=p.filter(({roundNumber:l})=>!u.inactiveRounds.includes(l));let m=o.map(le),d=p.map(le).filter(l=>!m.includes(l));if(s){let l=o.filter(({roundNumber:T})=>!u.inactiveRounds.includes(T)).filter(({winningSide:T})=>T),f=l.map(le),g=m.filter(T=>!f.includes(T));d.push(...g);let h=l.flatMap(T=>T.drawPositions??[]).filter(Boolean).flat(),S=Object.assign({},...h.map((T,A)=>({[T]:A+1})));if(l.forEach(T=>{t?T.drawPositions=T.drawPositions.map(A=>S[A]):delete T.drawPositions}),t){let T=c?.positionAssignments?.filter(A=>h.includes(A.drawPosition)).map(A=>(A.drawPosition=S[A.drawPosition],A));c.positionAssignments=T}else c.positionAssignments=[];c.matchUps=l,o=l}Rn({tournamentId:e?.tournamentId,matchUpIds:d,drawDefinition:r}),Rt({drawDefinition:r})}return{...R,matchUps:o}}function xU({tournamentRecord:t,drawDefinition:e,participantId:r,drawPosition:n,structureId:o,qualifier:i,event:s,bye:a}){if(!e)return{error:z};if(!n)return{error:Ts};if(!o)return{error:We};if(a){let c=yr({tournamentRecord:t,drawDefinition:e,drawPosition:n,structureId:o,event:s});if(c.error)return c}else{if(i)return{error:Vu};{let c=An({tournamentRecord:t,drawDefinition:e,participantId:r,drawPosition:n,structureId:o,event:s});if(c.error)return c}}return{...R}}function wU(t){let{tournamentRecord:e,matchUpIds:r=[],drawDefinition:n,event:o}=t;if(typeof n!="object")return{error:z};if(!Array.isArray(r))return{error:G};let i=t.structureId??n?.structures?.find(l=>l.matchUps?.some(({matchUpId:f})=>r.includes(f)))?.structureId;if(!i)return{error:_t};let s=n.structures?.find(l=>l.structureId===i);if(!s)return{error:_t};let a=s?.matchUps,c=a?.find(l=>!!l.roundPosition);if(s.structures||c||s.finishingPosition===Ci)return{error:hs};let u=[],p=a?.filter(({matchUpId:l,score:f})=>(he({score:f})&&u.push(l),r.includes(l)))??[],m=p.map(le),d=p.map(({tieMatchUps:l})=>l?.map(le)).filter(Boolean).flat();if(m.length){s.matchUps=(s.matchUps??[]).filter(({matchUpId:g})=>!m.includes(g)),Rn({tournamentId:e?.tournamentId,matchUpIds:[...d,...m],action:"deleteAdHocMatchUps",eventId:o?.eventId,drawDefinition:n});let l=mt(s.matchUps.map(Dr("roundNumber"))),f=sC(l);if(f.length){f.reverse();for(let g of f)s.matchUps.forEach(I=>{I.roundNumber&&I.roundNumber>g&&(I.roundNumber-=1,ht({tournamentId:e?.tournamentId,context:["adHoc round deletion"],eventId:o?.eventId,drawDefinition:n,matchUp:I}))})}if(u.length){s.positionAssignments=mt(s.matchUps.flatMap(h=>(h.sides??[]).map(S=>S.participantId)).filter(Boolean)).map(h=>({participantId:h}));let g=s?.matchUpFormat??n?.matchUpFormat??o?.matchUpFormat,I=zm({positionAssignments:s.positionAssignments,matchUps:s.matchUps,tournamentRecord:e,drawDefinition:n,matchUpFormat:g,event:o});I.error&&console.log(I)}Rt({structureIds:[i],eventId:o?.eventId,drawDefinition:n})}return{...R}}function LU({removeCompletedMatchUps:t,tournamentRecord:e,drawDefinition:r,structureId:n,roundNumber:o,event:i}){if(!e)return{error:j};if(!r)return{error:z};if(!o)return v({result:{error:et},info:"roundNumber required"});let s=st({drawDefinition:r,structureId:n});if(s.error)return s;let a=s.structure;return a?.structures?{error:hs}:Br({drawDefinition:r,structure:a})?QF({tournamentId:e.tournamentId,removeCompletedMatchUps:t,eventId:i.eventId,drawDefinition:r,roundNumber:o,structure:a}):(console.log("not implemented"),{...R})}function QF({removeCompletedMatchUps:t,drawDefinition:e,tournamentId:r,roundNumber:n,structure:o,eventId:i}){let s=o?.matchUps??[],a=[],c=[],u=!1;if(s.reduce((m,d)=>{let l=d?.roundNumber;return l?m.includes(l)?m:m.concat(l):m},[]).sort(oe).includes(n)){let m=s.filter(d=>{let l=d.roundNumber===n&&(!ie.includes(d.matchUpStatus)||t);return l&&(c.push(d.matchUpId),d.tieMatchUps&&a.push(...d.tieMatchUps.map(le))),!l});c.length&&(Rn({matchUpIds:[...a,...c],drawDefinition:e,tournamentId:r,eventId:i}),m.some(l=>l.roundNumber===n)||(m.forEach(l=>{l.roundNumber>n&&(l.roundNumber-=1,ht({drawDefinition:e,tournamentId:r,eventId:i,matchUp:l}))}),u=!0),o.matchUps=m)}return{deletedMatchUpsCount:c.length,roundRemoved:u,...R}}function rd(t){let{suppressNotifications:e,tournamentRecord:r,drawDefinition:n,matchUps:o,event:i}=t;if(typeof n!="object")return{error:z};let s=t?.structureId;if(!s&&n.structures?.length===1&&(s=n.structures?.[0]?.structureId),typeof s!="string")return{error:We};if(!Ar(o))return{error:G,info:Tn("matchUps")};let a=n.structures?.find(l=>l.structureId===s);if(!a)return{error:_t};let u=(a?.matchUps).find(l=>!!l.roundPosition);if(a.structures||u||a.finishingPosition===Ci)return{error:hs};let p=pe({tournamentRecord:r,inContext:!1})?.matchUps?.map(le)??[],m=o.map(le);if(ve(p,m))return{error:Ly,info:"One or more matchUpIds already present in tournamentRecord"};a.matchUps.push(...o);let d=o.map(({tieMatchUps:l})=>l).filter(Boolean).flat();return e||(lo({tournamentId:r?.tournamentId,matchUps:[...d,...o],eventId:i?.eventId,drawDefinition:n}),Rt({drawDefinition:n,structureIds:[s]})),{...R}}function FU({tournamentRecord:t,drawDefinition:e,drawPosition:r,structureId:n,subOrder:o,event:i}){if(!e)return{error:z};if(!n)return{error:We};if(!r)return{error:Ts};let{structure:s}=st({drawDefinition:e,structureId:n});if(!s)return{error:_t};let a=s;s.structures&&s.structureType===we&&(a=s.structures?.find(g=>g.positionAssignments?.find(I=>I.drawPosition===r)));let c=a?.positionAssignments,u=c?.find(g=>g.drawPosition===r);u&&gt({element:u,extension:{name:Qa,value:o}});let d=(i?.eventType===Bt||e.matchUpType===Bt||(i?.tieFormat??e?.tieFormat??s?.tieFormat))&&{matchUpTypes:[Bt]},{matchUps:l}=Pt({structure:a,afterRecoveryTimes:!1,inContext:!0,matchUpFilters:d,event:i}),f=s?.matchUpFormat??e.matchUpFormat;return zm({positionAssignments:c,tournamentRecord:t,drawDefinition:e,matchUpFormat:f,matchUps:l,event:i}),Rt({drawDefinition:e,structureIds:[n]}),{...R}}function Qh({scaleAttributes:t,scaledEntries:e,stageEntries:r,seedsCount:n,scaleName:o}){if(!t)return{error:et,info:"missing scaleAttributes"};let i=Object.assign({},...(e||[]).slice(0,n).map(({participantId:c},u)=>({[c]:u+1})));o=o||t.scaleName;let s=new Date().toISOString();return{scaleItemsWithParticipantIds:r.map(({participantId:c})=>({scaleItems:[{scaleValue:i[c],eventType:t.eventType,scaleType:Qn,scaleName:o,scaleDate:s}],participantId:c}))}}function Xh({participantsCount:t,participantCount:e}){if(t=t??e,!t)return{error:G};let r=Bi(t);return r?{drawSize:r}:v({result:{error:G},stack:"getEliminationDrawSize",context:{participantsCount:t}})}function gu(t){let{drawSizeProgression:e=!1,policyDefinitions:r,drawSize:n}=t||{},{requireParticipantCount:o=!0,tournamentRecord:i,drawDefinition:s,event:a}=t||{},c="getSeedsCount",u=t?.participantsCount??t?.participantCount;if(!r){let I=Io({tournamentRecord:i,drawDefinition:s,event:a});if(I.error)return v({result:I,stack:c});r=I.policyDefinitions}let p=lt(u);if(u&&!p)return v({result:{error:G},context:{participantsCount:u},stack:c});if(o&&!p)return v({result:{error:ly},stack:c});if(isNaN(n))if(u)({drawSize:n}=Xh({participantsCount:u}));else return v({result:{error:Ga},stack:c});let m=o&&u||n;if(m&&m>n)return{error:ml};let d=r?.[In];if(!d)return{error:ny};let l=d.seedsCountThresholds;return l?(d.drawSizeProgression!==void 0&&(e=d.drawSizeProgression),{seedsCount:l.filter(I=>e?I.drawSize<=n:n===I.drawSize).reduce((I,h)=>u&&u>=h.minimumParticipantCount?h.seedsCount:I,0)}):{error:HA}}function nd({policyDefinitions:t,drawDefinition:e,drawSize:r,drawId:n,event:o,stage:i}){if(!o)return{error:St};let{entries:s,stageEntries:a}=Ah({drawDefinition:e,drawId:n,stage:i,event:o}),c=a.length,{drawSize:u}=Xh({participantsCount:c}),p=gu({drawSize:r??u,participantsCount:c,policyDefinitions:t});if(p.error)return v({result:p,stack:"getEntriesAndSeedsCount"});let{seedsCount:m}=p;return{entries:s,seedsCount:m,stageEntries:a}}function gc(t){let{tournamentRecord:e,scaleAttributes:r,participantId:n}=t,o=t.tournamentRecords||e&&{[e.tournamentId]:e}||{};if(!n)return{error:te};let{participant:i,tournamentId:s}=Mo({tournamentRecords:o,tournamentRecord:e,participantId:n});return i?{...no({participant:i,scaleAttributes:r}),tournamentId:s}:{error:Jt}}function ks({sortDescending:t=!1,tournamentRecord:e,scaleAttributes:r,scaleSortMethod:n,stageSequence:o,entries:i,event:s,stage:a}){if(!e)return{error:j};return i=i??s?.entries??[],{scaledEntries:i.filter(d=>(!a||!d.entryStage||d.entryStage===a)&&(!o||!d.entryStageSequence||d.entryStageSequence===o)&&Mr.includes(d.entryStatus)).map(d=>{let{participantId:l}=d,{scaleItem:f}=gc({tournamentRecord:e,scaleAttributes:r,participantId:l});return{...d,...f}}).filter(d=>{let l=d.scaleValue;return!n&&(isNaN(l)||!parseFloat(l))?!1:l}).sort(n||p)};function p(d,l){return t?m(l)-m(d):m(d)-m(l)}function m(d){return parseFloat(d.scaleValue||(t?-1:1e5))}}function GU({tournamentRecord:t,drawDefinition:e,policyDefinitions:r,scaleAttributes:n,scaleName:o,drawSize:i,drawId:s,event:a,stage:c,sortDescending:u,scaleSortMethod:p}){let m=nd({policyDefinitions:r,drawDefinition:e,drawSize:i,drawId:s,event:a,stage:c});if(m.error)return m;let{entries:d,seedsCount:l,stageEntries:f}=m;if(!f||!l)return{error:G};let g=ks({tournamentRecord:t,scaleAttributes:n,scaleSortMethod:p,sortDescending:u,entries:d,stage:c}).scaledEntries??[],{scaleItemsWithParticipantIds:I}=Qh({scaleAttributes:n,scaledEntries:g,stageEntries:f,seedsCount:l,scaleName:o});return{scaleItemsWithParticipantIds:I}}var JU={};ne(JU,{allPlayoffPositionsFilled:()=>bh,checkValidEntries:()=>sd,findDrawDefinition:()=>eS,getAssignedParticipantIds:()=>di,getAvailablePlayoffProfiles:()=>cu,getDrawDefinitionTimeItem:()=>dh,getDrawParticipantRepresentativeIds:()=>Zh,getDrawTypeCoercion:()=>hu,getEligibleVoluntaryConsolationParticipants:()=>Jh,getParticipantIdFinishingPositions:()=>tS,getPositionAssignments:()=>yp,getPositionsPlayedOff:()=>dc,getSeedingThresholds:()=>Eh,getSeedsCount:()=>gu,getStructureSeedAssignments:()=>vr,getTeamLineUp:()=>ts,getValidGroupSizes:()=>dp,isAdHoc:()=>Br,isCompletedStructure:()=>qo,isValidForQualifying:()=>IS,positionActions:()=>gS});function Jh({excludedMatchUpStatuses:t=[],includeEventParticipants:e,includeQualifyingStage:r,finishingRoundLimit:n,policyDefinitions:o,roundNumberLimit:i,tournamentRecord:s,drawDefinition:a,matchUpsLimit:c,requirePlay:u,requireLoss:p,allEntries:m,winsLimit:d,event:l}){if(!a)return{error:z};let f=[tt,ae];r&&f.push(at);let g=l?.eventType?{matchUpTypes:[l.eventType]}:void 0,I=a?.matchUpType?{matchUpTypes:[a.matchUpType]}:void 0,h=e&&l?ro({contextFilters:{stages:f},matchUpFilters:g,tournamentRecord:s,inContext:!0,event:l})?.matchUps??[]:ar({contextFilters:{stages:f},matchUpFilters:I,tournamentRecord:s,inContext:!0,drawDefinition:a})?.matchUps??[],T=ii({stage:ke,drawDefinition:a}).map(({participantId:x})=>x),A={},P={},y={},E={};o||(o=Io({policyTypes:[CI],tournamentRecord:s,drawDefinition:a,event:l}).policyDefinitions);let U=o?.[CI];t=t.length&&t||U?.excludedMatchUpStatuses||[],e=e??U?.includeEventParticipants,m=m??U?.allEntries,n=n??U?.finishingRoundLimit,i=i??U?.roundNumberLimit,c=c??U?.matchUpsLimit,u===void 0&&(u=U?.requirePlay!==void 0?U.requirePlay:!0),p===void 0&&(p=U?.requireLoss!==void 0?U.requireLoss:!0),d=d??U?.winsLimit;for(let x of h){if(u&&x.winningSide&&![1,2].includes(x.winningSide)&&x.matchUpStatus!==fe||x.finishingRound&&n&&x.finishingRound>=n||x.finishingRound&&i&&x.finishingRound<=i)continue;let H=x.sides?.find(({sideNumber:W})=>x.winningSide&&W===3-x.winningSide),V=x.sides?.find(({sideNumber:W})=>x.winningSide&&W===x.winningSide);if(x.sides?.forEach(W=>{let B=W?.participant?.participantId;B&&(y[B]=W.participant,x.matchUpStatus===fe&&!u&&(P[B]=W.participant,A[B]||(A[B]=0),(!x.matchUpStatus||!t.includes(x.matchUpStatus))&&(A[B]+=1)))}),H?.participant){let W=H.participant.participantId;P[W]=H.participant,A[W]||(A[W]=0),x.matchUpStatus&&!t.includes(x.matchUpStatus)&&(A[W]+=1)}if(V?.participant){let W=V.participant.participantId;E[W]||(E[W]=0),E[W]+=1,A[W]||(A[W]=0),x.matchUpStatus&&!t.includes(x.matchUpStatus)&&(A[W]+=1)}}let M=s?.participants&&!u&&!p&&m,N=M?((e&&l?l.entries:a.entries)??[]).filter(x=>![go,_r].includes(x.entryStatus)).map(({participantId:x})=>x):[],C=Object.keys(P),D=M?(s?.participants??[]).filter(({participantId:x})=>N.includes(x)):p&&Object.values(P)||Object.values(y),O=x=>!p||C.includes(x),b=x=>!u||(A[x]||0)>=0,_=x=>!d||(E[x]||0)<=d,L=x=>!c||A[x]<=c,F=x=>!T.includes(x);return{eligibleParticipants:D.filter(x=>O(x.participantId)&&b(x.participantId)&&_(x.participantId)&&L(x.participantId)&&F(x.participantId)).map(x=>({...x,individualParticipants:x.individualParticipantIds?.map(H=>s?.participants?.find(V=>V.participantId===H))})),losingParticipantIds:C,...R}}function Zh({drawDefinition:t}){let e=ut({name:"participantRepresentatives",element:t});return e.error?e:{representativeParticipantIds:e.extension?.value||[]}}function Bb({tournamentParticipants:t,drawDefinition:e,event:r}){if(!e)return{error:z};let n=re({tournamentParticipants:t,inContext:!0,drawDefinition:e,event:r}),o=J(n.matchUps,!1,!0),i=mt(o.reduce((a,c)=>a.concat(...c.sides.map(u=>u.participantId).filter(Boolean)),[])),s=Object.assign({},...i.map(a=>{let c=o.filter(u=>u.sides.map(m=>m.participantId).filter(Boolean).includes(a));return{[a]:c}}));return{participantIds:i,participantIdMatchUps:s}}function tS({byeAdvancements:t=!1,tournamentRecord:e,drawDefinition:r}){if(!r)return{error:z};let{participantIds:n,participantIdMatchUps:o}=Bb({tournamentParticipants:e?.participants,drawDefinition:r}),i=n?.map(s=>{let c=o[s].filter(d=>[me,Ut].includes(d.matchUpStatus)||d.winningSide),u=c.map(d=>{let l=d.sides.find(I=>I.bye),f=d.sides.find(I=>I.participantId===s).sideNumber;return(d.winningSide||t&&l&&f)===f?d.finishingPositionRange.winner:d.finishingPositionRange.loser}),p=d=>Math.abs(d[0]-d[1]),m=u.reduce((d,l)=>d&&p(d)<p(l)?d:l,void 0);return{[s]:{relevantMatchUps:c,finishingPositionRanges:u,finishingPositionRange:m}}})||[];return Object.assign({},...i)}function To({tournamentRecords:t,tournamentRecord:e,tournamentId:r,drawId:n}){if(!e&&!t)return{error:j};if(!n)return{error:Ur};if(!e&&t){if(typeof r!="string"&&(r=Kh({tournamentRecords:t,drawId:n}),!r))return{error:Xs};if(e=t[r],!e)return{error:j}}let o=e&&nr({tournamentRecord:e,drawId:n});return o?.drawDefinition?{drawDefinition:o.drawDefinition,event:o.event,tournamentRecord:e,...R}:v({result:{error:fr},stack:"findDrawDefinition"})}function eS(t){let{drawDefinition:e,error:r}=To(t);return r?{error:r}:{drawDefinition:J(e)}}function zf({targetRoundNumber:t,finishingPosition:e,drawDefinition:r,structureId:n,linkType:o}){let{links:i}=Rs({drawDefinition:r,structureId:n})||{},a=(i?.target||[]).filter(({linkType:u})=>u===o).filter(({target:u})=>!t||t===u.roundNumber).map(u=>{let p=u.source.structureId,{structure:m}=st({structureId:p,drawDefinition:r});if(!(e&&m?.finishingPosition!==e))return u}).filter(Boolean);return{sourceStructureIds:a.map(({source:u})=>u.structureId),relevantLinks:a}}var Hb="qualifierDrawPositionAssignment",Wb="withdrawParticipantAtDrawPosition",jb="alternateDrawPositionAssignment",Yb="luckyLoserDrawPositionAssignment",VU="removeDrawPositionAssignment",qb="swapDrawPositionAssignments",$b="modifyPairAssignment",Kb="modifyParticipantOtherName",BU="assignDrawPosition",zb="removeSeededParticipant",Qb="assignDrawPositionBye",Xb="modifySeedAssignment",rS="addPenalty",Qf="MODIFY_PAIR",Tp="QUALIFIER",Xf="ALTERNATE",Jf="WITHDRAW",cs="ASSIGN",nS="REMOVE",Zf="LUCKY",Ap="REMOVE_SEED",tg="SWAP",Iu="NICKNAME",Vs="SEED_VALUE",Bs="PENALTY",od="BYE",Jb={MODIFY_PAIR_ASSIGNMENT:Qf,QUALIFYING_PARTICIPANT:Tp,ALTERNATE_PARTICIPANT:Xf,WITHDRAW_PARTICIPANT:Jf,ASSIGN_PARTICIPANT:cs,LUCKY_PARTICIPANT:Zf,REMOVE_ASSIGNMENT:nS,SWAP_PARTICIPANTS:tg,ADD_NICKNAME:Iu,REMOVE_SEED:Ap,ADD_PENALTY:Bs,ASSIGN_BYE:od,SEED_VALUE:Vs};function Zb({tournamentParticipants:t,returnParticipants:e,drawPosition:r,participant:n,drawId:o,event:i}){let s=i?.entries?.filter(({entryStatus:a})=>[_r,oi].includes(a)).map(({participantId:a})=>a)||[];if(s.length){let a=n.individualParticipantIds,c=e?t.filter(({participantId:m})=>s.includes(m)):void 0,u=e?t.filter(({participantId:m})=>a.includes(m)):void 0;return{validModifyAssignedPairAction:rt({payload:{participantId:n.participantId,replacementIndividualParticipantId:void 0,existingIndividualParticipantId:void 0,drawPosition:r,drawId:o},method:$b,availableIndividualParticipantIds:s,availableIndividualParticipants:c,existingIndividualParticipantIds:a,existingIndividualParticipants:u,type:Qf},!1,!1,!0)}}return{}}function tO({tournamentParticipants:t=[],sourceStructuresComplete:e,possiblyDisablingAction:r,isWinRatioFedStructure:n,activeDrawPositions:o,positionAssignments:i,drawDefinition:s,drawPosition:a,structureId:c,structure:u,drawId:p,event:m}){if(o.includes(a)||n&&!e)return{};let{sourceStructureIds:d,targetStructureIds:l}=s.links?.reduce((h,S)=>{let T=S.source?.structureId,A=S.target?.structureId;return h.sourceStructureIds.includes(T)||h.sourceStructureIds.push(T),h.targetStructureIds.includes(A)||h.targetStructureIds.push(A),h},{sourceStructureIds:[],targetStructureIds:[]})||{},f=[],g=s.links?.filter(h=>h.target?.structureId===u.structureId)??[];for(let h of g){let S=h?.source?.structureId,{structure:T}=st({structureId:S,drawDefinition:s}),A=T?.finishingPosition===Ci&&(d?.length!==1||l?.length!==1),P={};if(A){let{matchUps:M}=Pt({drawDefinition:s,structure:u,event:m}),{initialRoundNumber:N}=ns({drawPosition:a,matchUps:M}),D=s.links?.find(O=>O.target?.structureId===u?.structureId&&O.target.roundNumber===N)?.source?.roundNumber;P.roundNumbers=[D]}let{completedMatchUps:y}=eu({structureId:S,inContext:!0,matchUpFilters:P,drawDefinition:s}),E=i.map(M=>M.participantId).filter(Boolean);y?.filter(({matchUpType:M,winningSide:N})=>N&&(m?.eventType!==Le||M===Le)).map(({winningSide:M,sides:N})=>M&&N?.[1-(M-1)]).map(ft).filter(M=>M&&!E.includes(M))?.forEach(M=>{f.includes(M)||f.push(M)})}let I=t?.filter(h=>f?.includes(h.participantId));return I?.forEach(h=>{let S=(s.entries??[]).find(T=>T.participantId===h.participantId);h.entryPosition=S?.entryPosition}),f?.length?{validLuckyLosersAction:{type:Zf,method:Yb,availableLuckyLosers:I,availableLuckyLoserParticipantIds:f,willDisableLinks:r,payload:{drawId:p,structureId:c,drawPosition:a}}}:{}}function eO({tournamentParticipants:t=[],possiblyDisablingAction:e,activeDrawPositions:r,positionAssignments:n,returnParticipants:o,appliedPolicies:i,drawDefinition:s,drawPosition:a,validActions:c,structureId:u,structure:p,drawId:m,event:d}){if(r.includes(a))return{};let l=c.find(U=>U.type===cs)?.availableParticipantIds,f=i?.[Xn]?.otherFlightEntries,g=i?.[Xn]?.restrictQualifyingAlternates,I=(s.entries??[]).filter(({entryStage:U})=>!g||(p.stage===at?U===at:U!==at)).sort((U,M)=>(U.entryPosition??1/0)-(M.entryPosition??1/0)).map(({participantId:U})=>U).filter(Boolean),{allPositionedParticipantIds:h}=BI({drawDefinition:s}),S=n.map(U=>U.participantId).filter(Boolean),T=I.filter(U=>p.stage&&[at,tt,ae].includes(p.stage)?!h?.includes(U):!S.includes(U)),P=(d?.entries??[]).filter(U=>U.entryStatus===Or&&HU({restrictQualifyingAlternates:g,structure:p,entry:U})&&(p.stage&&[at,tt,ae].includes(p.stage)?!h?.includes(U.participantId):!S.includes(U.participantId))).sort((U,M)=>(U.entryPosition??1/0)-(M.entryPosition??1/0)).map(U=>U.participantId),y=mt(T.concat(P));if(f){let M=(d?kt({event:d}).flightProfile:void 0)?.flights?.filter(N=>N.drawId!==m).map(N=>N.drawEntries.filter(C=>C.participantId&&![go,_r,oi].includes(C.entryStatus)&&!I.includes(C.participantId)).map(({participantId:C})=>C)).flat().filter(Boolean);M?.length&&y.push(...M)}l?.length&&(y=y.filter(U=>!l.includes(U)));let E=o?t?.filter(U=>y.includes(U.participantId)):void 0;return E?.forEach(U=>{let M=(s.entries??[]).find(N=>N.participantId===U.participantId);U.entryPosition=M?.entryPosition}),E?.sort((U,M)=>(U.entryPosition||1/0)-(M.entryPosition||1/0)),y.length?{validAlternatesAction:rt({payload:{drawId:m,structureId:u,drawPosition:a},willDisableLinks:e,method:jb,availableAlternatesParticipantIds:y,type:Xf,availableAlternates:E})}:{}}function HU({restrictQualifyingAlternates:t,structure:e,entry:r}){let{stage:n}=e;if(!r.entryStage||r.entryStage===n||n===at&&!t||r.entryStage===tt&&n===Ge)return!0}function rO({positionSourceStructureIds:t,unassignedParticipantIds:e,possiblyDisablingAction:r,provisionalPositioning:n,tournamentParticipants:o,isWinRatioFedStructure:i,positionAssignments:s,returnParticipants:a,appliedPolicies:c,drawDefinition:u,seedingProfile:p,isByePosition:m,drawPosition:d,structureId:l,event:f}){let{drawId:g}=u,I=[],h,S,T=[],A=c?.[In]?.validSeedPositions?.ignore;if(A||({unplacedSeedParticipantIds:h,unplacedSeedAssignments:S,unfilledPositions:T}=Uh({provisionalPositioning:n,returnAllProxies:!0,randomize:!0,drawDefinition:u,seedingProfile:p,structureId:l,event:f})),T?.length||(T=s.filter(P=>!P.participantId&&!P.bye&&!P.qualifier).map(P=>P.drawPosition)),m||I.push({payload:{drawId:g,structureId:l,drawPosition:d,isPositionAction:!0},willDisableLinks:r,method:Qb,type:od}),i&&A){let P=s.map(N=>N.participantId).filter(Boolean),y={structureIds:t},{completedMatchUps:E}=ws({inContext:!0,matchUpFilters:y,drawDefinition:u}),U=mt((E??[]).filter(({matchUpType:N})=>f?.eventType!==Le||N===Le)?.map(({sides:N})=>N?.map(ft)).flat().filter(N=>N&&!P.includes(N))),M=a?o?.filter(N=>U?.includes(N.participantId)).map(N=>J(N,void 0,!0)):void 0;return M?.forEach(N=>{let C=(u.entries??[]).find(D=>D.participantId===N.participantId);N.entryPosition=C?.entryPosition}),M?.length&&I.push(rt({payload:{drawId:g,structureId:l,drawPosition:d},willDisableLinks:r,method:BU,type:cs,availableParticipantIds:U,participantsAvailable:M})),{validAssignmentActions:I}}if(T.includes(d)||m){let P;if(S?.length){let E=S.filter(U=>h?.includes(U.participantId));E.sort(XF),P=E.map(U=>U.participantId)}else P=e;let y=a?o?.filter(E=>P.includes(E.participantId)).map(E=>J(E,void 0,!0)):void 0;y?.length&&I.push(rt({payload:{drawId:g,structureId:l,drawPosition:d},willDisableLinks:r,method:BU,type:cs,availableParticipantIds:P,participantsAvailable:y}))}return{validAssignmentActions:I}}function XF(t,e){return t.bye||ac(t.seedValue)<ac(e.seedValue)||t.seedValue&&!e.seedValue?-1:(t.seedNumber||0)-(e.seedNumber||0)}function nO({drawPositionInitialRounds:t,tournamentParticipants:e,positionAssignments:r,returnParticipants:n,appliedPolicies:o,drawDefinition:i,drawPosition:s,structureId:a,drawId:c}){let u=[],p=[],m=[],d=[],l=r.map(P=>P.participantId).filter(Boolean),f=o?.[Xn],g=!f?.disableRoundRestrictions&&t[s],I=f?.requireCompletedStructures,{sourceStructureIds:h,relevantLinks:S}=zf({targetRoundNumber:g,linkType:Jn,drawDefinition:i,structureId:a})||{};h?.length&&d.push(...h);let{sourceStructureIds:T,relevantLinks:A}=zf({targetRoundNumber:g,linkType:kn,drawDefinition:i,structureId:a})||{};T?.length&&d.push(...T);for(let P of S){let y=i.structures?.find(U=>U.structureId===P.source.structureId);if(y?.stage!==at)continue;let E=qo({structureId:P.source.structureId,drawDefinition:i});if(!I||E){let U=y.qualifyingRoundNumber,{matchUps:M}=Pt({matchUpFilters:{roundNumbers:[U],hasWinningSide:!0},afterRecoveryTimes:!1,tournamentParticipants:e,inContext:!0,structure:y});for(let N of M){let C=N.sides.find(O=>O?.sideNumber===N.winningSide),D=N.matchUpStatus===Ut&&N.sides?.find(({participantId:O})=>O);if(C||D){let{participantId:O,participant:b}=C||D||{};O&&!l.includes(O)&&(b&&n&&u.push(b),p.push(O))}}}}for(let P of A){let y=i.structures?.find(U=>U.structureId===P.source.structureId);if(y?.stage!==at)continue;let E=qo({structureId:P.source.structureId,drawDefinition:i});if(!I||E){let{positionAssignments:U}=Dt({structure:y}),M=U?.map(N=>{let C=N.participantId,D=ut({element:N,name:wo}).extension?.value;return D?{participantId:C,groupOrder:D?.groupOrder}:{}}).filter(({groupOrder:N,participantId:C})=>N===1&&!l.includes(C)).map(({participantId:N})=>N)??[];if(M&&p.push(...M),n){let N=e.filter(({participantId:C})=>M.includes(C));u.push(...N)}}}return p.length&&m.push(rt({payload:{qualifyingParticipantId:void 0,drawPosition:s,structureId:a,drawId:c},method:Hb,type:Tp,qualifyingParticipantIds:p,qualifyingParticipants:n?u:void 0})),{validAssignmentActions:m,sourceStructureIds:d}}function fi(t){let{inContextDrawMatchUps:e,targetData:r,drawDefinition:n,relevantLink:o}=t;if(o?.linkCondition===Bn&&r?.matchUp?.matchUpStatus===Ut)return!1;let{targetMatchUps:{loserMatchUp:s,winnerMatchUp:a},targetLinks:c}=r,u=[bt,Ot].includes(s?.matchUpStatus),p=a?.drawPositions?.filter(Boolean).length||0;if(s?.winningSide&&!u||a?.winningSide&&p===2&&(!a.feedRound||![Ot,bt].includes(a?.matchUpStatus)))return!0;let m=s&&Je({matchUpId:s.matchUpId,inContextDrawMatchUps:e,drawDefinition:n}),d=a&&Je({matchUpId:a.matchUpId,inContextDrawMatchUps:e,drawDefinition:n}),l=m&&fi({relevantLink:c?.loserTargetLink,targetData:m,inContextDrawMatchUps:e,drawDefinition:n});return!!(d&&fi({targetData:d,inContextDrawMatchUps:e,drawDefinition:n})||l)}var oS={[Xn]:{policyName:"positionActionsDefault",enabledStructures:[{stages:[at,tt],stageSequences:[1],enabledActions:[],disabledActions:[]},{stages:[],stageSequences:[],enabledActions:[Iu,Bs,Tp,Vs],disabledActions:[]}],disbledStructures:[],otherFlightEntries:!1,activePositionOverrides:[]}};var eg="positionAction",iS="matchUpAction";function sS({actionType:t=eg,appliedPolicies:e,drawDefinition:r,structure:n}){let o=t===eg&&Xn||t===iS&&qe,i=t===eg&&oS||t===iS&&XE,s=o&&(e?.[o]||i?.[o]),c=r.links?.filter(d=>d?.target?.structureId===n?.structureId)?.map(({target:d})=>d.feedProfile)??[],{enabledStructures:u,disabledStructures:p}=s||{},m=p?.find(d=>{let{stages:l,stageSequences:f,structureTypes:g,feedProfiles:I}=d;return(!I?.length||Array.isArray(I)&&I.some(h=>c.includes(h)))&&(!l?.length||Array.isArray(l)&&l?.includes(n?.stage))&&(!g?.length||Array.isArray(g)&&g?.includes(n?.structureType))&&(!f?.length||Array.isArray(f)&&f.includes(n?.stageSequence))});return{enabledStructures:u,actionsDisabled:m,actionsPolicy:s}}function WU({activePositionOverrides:t,activeDrawPositions:e,action:r}){return r&&t.includes(r)?!0:!e.length}function aS({enabledStructures:t,drawDefinition:e,structure:r}){if(t===!1)return{};if(!t?.length)return{policyActions:{enabledActions:[],disabledActions:[]}};let{stage:n,stageSequence:o,structureType:i}=r||{},a=e.links?.filter(u=>u?.target?.structureId===r?.structureId)?.map(({target:u})=>u.feedProfile)||[];return{policyActions:t.find(u=>{let{stages:p,stageSequences:m,structureTypes:d,feedProfiles:l}=u||{},f=!p?.length||Array.isArray(p)&&p.includes(n),g=!m?.length||Array.isArray(m)&&m.includes(o),I=!d?.length||Array.isArray(d)&&d.includes(i),h=!l?.length||Array.isArray(l)&&l.some(S=>a.includes(S));return g&&I&&h&&u&&f})}}function Un({action:t,policyActions:e}){let r=!e?.enabledActions||e?.disabledActions?.length&&e.disabledActions.includes(t);return r?!1:(e?.enabledActions.length===0||e?.enabledActions.includes(t))&&!r}var jU="replaceTieMatchUpParticipantId",YU="assignTieMatchUpParticipantId",cS="removeTieMatchUpParticipantId",qU="assignMatchUpSideParticipant",oO="removeMatchUpSideParticipant",$U="substituteParticipant",uS="REMOVE_SUBSTITUTION",KU="REPLACE_PARTICIPANT",rg="REMOVE_PARTICIPANT",pS="setMatchUpStatus",mS="SUBSTITUTION",zU="SCHEDULE",JF="PENALTY",dS="REFEREE",QU="STATUS",lS="START",XU="SCORE",fS="END",iO={REPLACE_TEAM_POSITION_METHOD:jU,ASSIGN_TEAM_POSITION_METHOD:YU,REMOVE_TEAM_POSITION_METHOD:cS,REPLACE_PARTICIPANT:KU,SUBSTITUTION_METHOD:$U,REMOVE_SUBSTITUTION:uS,REMOVE_PARTICIPANT:rg,SCHEDULE_METHOD:pS,SUBSTITUTION:mS,SCHEDULE:zU,PENALTY:JF,REFEREE:dS,STATUS:QU,SCORE:XU,START:lS,END:fS};function sO({specifiedPolicyDefinitions:t,inContextDrawMatchUps:e,matchUpParticipantIds:r,matchUpActionsPolicy:n,inContextMatchUp:o,policyActions:i,enforceGender:s,participantId:a,sideNumber:c,matchUpId:u,matchUp:p,drawId:m,side:d}){let l=[],f=o.sides?.find(F=>F.participant),g=o.gender===Cr&&o.sideNumber&&o.sides?.filter(F=>F.particiapntId).length===1&&f?.participant?.person?.sex,I=o.matchUpType,S=(s??n?.participants?.enforceGender)!==!1?o.gender:void 0,A=o.sides?.flatMap(F=>F.participant?.individualParticipants||F.participant).filter(Boolean)?.map(ft),P=o.sides?.filter(F=>!c||F.sideNumber===c).flatMap(F=>F.participant?.individualParticipants||F.participant).filter(Boolean),y=P?.map(ft),U=e?.find(F=>F.matchUpId===o.matchUpTieId)?.sides?.map(F=>F.participant?.individualParticipants.filter(({participantId:w,person:x})=>!y?.includes(w)&&(!S||S===On||x.sex===S||S===Cr&&!g||g&&x.sex!==g))),M=c?U?.[c-1]:U?.map((F,w)=>({participants:F,sideNumber:w+1})),N=c?U?.[c-1]?.map(ft):U?.map((F,w)=>({participants:F?.map(ft),sideNumber:w+1})),C=c&&(I===da&&!y?.length||I===Ri&&(y?.length??0)<2)||!c&&(I===da&&(y?.length??0)<2||I===Ri&&(y?.length??0)<4),D=N?.filter(F=>!A?.includes(F)),O=M?.filter(({participantId:F})=>D.includes(F));if(C&&D?.length&&l.push({availableParticipantIds:D,method:YU,availableParticipants:O,type:cs,payload:{participantId:void 0,tieMatchUpId:u,sideNumber:c,drawId:m}}),y?.length&&(!he(p)||d?.substitutions?.length)&&l.push({method:cS,type:rg,existingParticipantIds:y,payload:{participantId:void 0,tieMatchUpId:u,drawId:m}}),O?.length&&(!c&&y?.length||c&&d?.participant)&&l.push({availableParticipantIds:D,method:jU,availableParticipants:O,type:KU,existingParticipantIds:y,payload:{existingParticipantId:void 0,participantId:void 0,tieMatchUpId:u,drawId:m}}),Un({policyActions:i,action:uS})&&d?.substitutions?.length){let F=d.participant?.participantType===It&&[d.participantId]||d.participant?.participantType===pt&&d.participant.individualParticipantIds||[],w=d.substitutions.map(x=>x.participantId).filter(x=>F.includes(x));(!a||w.includes(a))&&l.push({method:cS,type:uS,substitutedParticipantIds:w,payload:{participantId:void 0,tieMatchUpId:u,drawId:m}})}let b=t?.[qe],_=b?.substituteWithoutScore,L=b?.substituteAfterCompleted;if(Un({policyActions:i,action:mS})&&r.length===2&&(!c&&y?.length||c&&d?.participant)&&(_||he(p))&&(L||p.matchUpStatus&&!ie.includes(p.matchUpStatus))&&P?.length&&M.length){let F=P.map(ft);l.push({info:"list of team players available for substitution",method:$U,availableParticipantIds:N,existingParticipantIds:F,availableParticipants:M,existingParticipants:P,type:mS,payload:{substituteParticipantId:void 0,existingParticipantId:void 0,sideNumber:c,matchUpId:u,drawId:m}})}return l}function aO({eventEntries:t,structure:e}){let r=o=>o.entryStatus===Or&&HU({structure:e,entry:o}),n=(o,i)=>(o.entryPosition||1/0)-(i.entryPosition||1/0);return t.filter(r).sort(n).map(ft)}function cO({restrictAdHocRoundParticipants:t,tournamentParticipants:e,matchUpParticipantIds:r,otherFlightEntries:n,drawDefinition:o,structureId:i,sideNumber:s,matchUpId:a,structure:c,matchUp:u,drawId:p,event:m}){let d=[],l=(c?.matchUps??[]).filter(({roundNumber:y})=>y===u.roundNumber),f=o?.entries?.filter(({entryStatus:y})=>y&&Vo.includes(y)).map(ft)??[],g=l.map(y=>(y.sides??[]).flatMap(ft)).flat().filter(Boolean),I=f.filter(y=>!r.includes(y)&&(!t||!g.includes(y))),h=e?.filter(y=>I?.includes(y.participantId)).map(y=>J(y,void 0,!0));h?.forEach(y=>{let E=(o.entries??[]).find(U=>U.participantId===y.participantId);y.entryPosition=E?.entryPosition}),I.length&&d.push({payload:{drawId:p,matchUpId:a,structureId:i,sideNumber:s},method:qU,type:cs,availableParticipantIds:I,participantsAvailable:h});let S=m?.entries??[],T=aO({eventEntries:S,structure:c}),A=mt(f.concat(T));if(n){let E=(m?kt({event:m}):void 0)?.flights?.filter(U=>U.drawId!==p).flatMap(U=>U.drawEntries.filter(M=>M.participantId&&![go,_r,oi].includes(M.entryStatus)).map(({participantId:M})=>M)).filter(Boolean);E?.length&&A.push(...E)}A=A.filter(y=>!r.includes(y)&&!I.includes(y)&&(!t||!g.includes(y)));let P=e?.filter(y=>A.includes(y.participantId)).map(y=>J(y,void 0,!0));return P?.forEach(y=>{let E=(o.entries??[]).find(U=>U.participantId===y.participantId);y.entryPosition=E?.entryPosition}),P?.sort((y,E)=>(y.entryPosition||1/0)-(E.entryPosition||1/0)),A.length&&d.push({payload:{drawId:p,matchUpId:a,structureId:i,sideNumber:s},availableParticipantIds:A,participantsAvailable:P,method:qU,type:Or}),!he(u)&&s&&u.sides?.find(E=>E.sideNumber===s)?.participantId&&d.push({payload:{drawId:p,matchUpId:a,structureId:i,sideNumber:s},method:oO,type:rg}),d}function id(t){if(!t)return{error:G};let e,r,{restrictAdHocRoundParticipants:n=!0,policyDefinitions:o,enforceGender:i,participantId:s,sideNumber:a,matchUpId:c}=t,u=t.tournamentRecord??(t.tournamentId&&er(t.tournamentId)&&t.tournamentRecords?.[t.tournamentId]);if(!u)return{error:j};if(!c||!er(c))return{error:Ne};if(a&&![1,2].includes(a))return v({result:{error:G},context:{sideNumber:a}});if(!e){let it=(pe({tournamentRecord:u}).matchUps??[]).find(ot=>ot.matchUpId===c);r=(u?.events??[]).find(ot=>ot.eventId===it?.eventId),e=(r?.drawDefinitions??[]).find(ot=>ot.drawId===it?.drawId)}if(!e)return{error:z};let p=$t({tournamentRecord:u,withIndividualParticipants:!0}).participants,{drawId:m}=e,{matchUp:d,structure:l}=xt({drawDefinition:e,matchUpId:c,event:r});if(!d)return{error:De};let f=yt({tournamentRecord:u,drawDefinition:e,structure:l,event:r}).appliedPolicies??{};Object.assign(f,o??{});let g=f?.[Xn]?.otherFlightEntries,I=f?.[qe]??is[qe],{enabledStructures:h}=sS({actionType:iS,appliedPolicies:f,drawDefinition:e,structure:l}),{policyActions:S}=aS({enabledStructures:h,drawDefinition:e,structure:l}),T=t.matchUpsMap??be({drawDefinition:e}),A=t.inContextDrawMatchUps??re({tournamentParticipants:p,inContext:!0,drawDefinition:e,matchUpsMap:T,event:r}).matchUps,P=A?.find(Q=>Q.matchUpId===c),y=a&&P?.sides?.find(Q=>Q.sideNumber===a),E=P?.sides?.map(Q=>Q.participantId||Q.participant?.participantid).filter(Boolean)??[],{assignedPositions:U,allPositionsAssigned:M}=de({structure:l}),{structureId:N}=l??{},C=[];if(!N)return{validActions:C};let D=Br({drawDefinition:e,structure:l}),O=d.collectionId;if(D&&!O){let Q=cO({restrictAdHocRoundParticipants:n,tournamentParticipants:p,matchUpParticipantIds:E,otherFlightEntries:g,drawDefinition:e,structureId:N,sideNumber:a,matchUpId:c,structure:l,matchUp:d,drawId:m,event:r});C.push(...Q)}let b=qo({drawDefinition:e,structure:l}),_=U?.filter(Q=>Q.participantId).map(Q=>Q.drawPosition),L=U?.filter(Q=>Q.bye).map(Q=>Q.drawPosition),F=d.matchUpStatus===Ut||!O&&d.drawPositions?.reduce((Q,it)=>L?.includes(it)||Q,!1);if(F)return{validActions:C,isByeMatchUp:F};Un({policyActions:S,action:dS})&&C.push({type:dS,payload:{matchUpId:c}});let w=!ha({matchUpStatus:d.matchUpStatus}),x=f?.scoring?.structures,H=l?.stage&&x?.stage&&x?.stage[l.stage],V=l?.stageSequence&&H?.stageSequence&&H.stageSequence[l.stageSequence],B=!(f?.scoring?.requireAllPositionsAssigned||H?.requireAllPositionsAssigned||V?.requireAllPositionsAssigned)||M,q=d.sides&&d.sides.filter(Q=>Q?.participantId).length===2,Y=d.matchUpStatus&&[fe,Me].includes(d.matchUpStatus),k=Je({inContextDrawMatchUps:A,drawDefinition:e,matchUpId:c}),K=fi({inContextDrawMatchUps:A,drawDefinition:e,targetData:k}),$=(P?.drawPositions?.length===2&&P.drawPositions.every(Q=>_?.includes(Q))&&P?.sides?.length===2&&P.sides.every(({participantId:Q})=>Q)||q)&&!(Y&&K),nt={method:rS,type:Bs,payload:{drawId:m,matchUpId:c,penaltyCode:void 0,penaltyType:void 0,participantIds:[],notes:void 0}};if(w&&C.push({payload:{drawId:m,matchUpId:c,schedule:{}},method:pS,type:zU}),Un({policyActions:S,action:Bs})&&(y?.participant||!a&&E?.length)&&C.push(nt),w&&$&&C.push({type:QU}),B&&$){let{matchUpId:Q,matchUpFormat:it}=d,ot={drawId:m,matchUpId:Q,matchUpFormat:it,outcome:{scoreStringSide1:void 0,scoreStringSide2:void 0,sets:[]},winningSide:void 0};C.push({info:"set outcome and winningSide",method:pS,type:XU,payload:ot}),Un({policyActions:S,action:lS})&&C.push({type:lS}),Un({policyActions:S,action:fS})&&C.push({type:fS})}if(O&&P){let Q=sO({specifiedPolicyDefinitions:o,inContextDrawMatchUps:A,matchUpParticipantIds:E,matchUpActionsPolicy:I,inContextMatchUp:P,policyActions:S,enforceGender:i,participantId:s,sideNumber:a,matchUpId:c,matchUp:d,drawId:m,side:y});C.push(...Q)}return{structureIsComplete:b,validActions:C,isDoubleExit:Y}}function uO({onlyAssignedPositions:t=!0,possiblyDisablingAction:e,tournamentParticipants:r,inactiveDrawPositions:n,activeDrawPositions:o,positionAssignments:i,returnParticipants:s,byeDrawPositions:a,drawDefinition:c,isByePosition:u,drawPosition:p,structureId:m,structure:d,drawId:l,event:f}){if(o.includes(p))return{};let g=N=>!t||N.participantId||N.qualifier||N.bye,I=n?.filter(N=>N!==p&&!(u&&a.includes(N))),h=i?.filter(N=>g(N)&&I?.includes(N.drawPosition))??[],S=h.map(({drawPosition:N})=>N),{matchUps:T}=Pt({afterRecoveryTimes:!1,inContext:!0,drawDefinition:c,structure:d,event:f}),A=T.filter(({drawPositions:N})=>ve(N,S)),P=Object.assign({},...A.map(N=>N.sides?.filter(({sourceDrawPositionRange:C})=>C).map(({drawPosition:C,sourceDrawPositionRange:D})=>({[C]:D}))).flat()),y=h.map(N=>N.participantId).filter(Boolean),E=(r??[]).filter(N=>y.includes(N.participantId)),U=Object.assign({},...E.map(N=>({[N.participantId]:N}))),M=h.map(N=>{let C=U?.[N.participantId],D=P[N.drawPosition];return rt({...N,participant:s?J(C,!1,!0):void 0,sourceDrawPositionRange:D})});return M.length?{validSwapAction:{payload:{drawId:l,structureId:m,drawPositions:[p]},willDisableLinks:e,method:qb,type:tg,availableAssignments:M}}:{}}function gS(t){let{policyDefinitions:e,returnParticipants:r=!0,provisionalPositioning:n,tournamentRecord:o,drawDefinition:i,drawPosition:s,event:a}=t;if(!a)return{error:St};if(!i)return{error:z};if(!t.structureId)return{error:We};let c=t.tournamentParticipants??(o&&$t({withIndividualParticipants:!0,tournamentRecord:o}).participants)??[],u=st({structureId:t.structureId,drawDefinition:i});if(u.error)return u;let p=u.containingStructure||u.structure;if(!p)return{error:_t};let m=p.structureId;if(u=Sa({drawDefinition:i,structureId:m}),s===void 0&&!u.isAdHoc)return{error:Ts};if(u.isAdHoc)return id(t);if(u.error)return u;let{drawPositionInitialRounds:d,inactiveDrawPositions:l,activeDrawPositions:f,byeDrawPositions:g}=u,I=yt({tournamentRecord:o,drawDefinition:i,structure:p,event:a}).appliedPolicies??{};Object.assign(I,e??{});let{actionsPolicy:h,enabledStructures:S,actionsDisabled:T}=sS({actionType:eg,appliedPolicies:I,drawDefinition:i,structure:p}),A=h?.activePositionOverrides||[],{sourceStructureIds:P}=zf({finishingPosition:Ms,targetRoundNumber:1,linkType:kn,drawDefinition:i,structureId:m})||{},y;P?.length&&(y=P.reduce((K,X)=>qo({structureId:X,drawDefinition:i})&&K,!0));let E=P.length,U=P.length&&!y,{policyActions:M}=aS({enabledStructures:S,drawDefinition:i,structure:p}),N=![at,tt].includes(p.stage)||p.stageSequence!==1,{drawId:C}=i,D=[],{assignedPositions:O,positionAssignments:b}=de({structure:p}),_=O?.find(K=>K.drawPosition===s);if(!b?.map(K=>K.drawPosition)?.includes(s))return{error:Ss};let{stage:F,stageSequence:w}=p,x=[F];F===Ge&&x.push(tt),F===tt&&x.push(Ge);let H=ii({entryStatuses:Vo,provisionalPositioning:n,drawDefinition:i,stageSequence:w,structureId:m,stages:x}),V=di({drawDefinition:i,stages:x}).assignedParticipantIds??[],W=H.filter(K=>!V.includes(K.participantId)).map(K=>K.participantId),B=g.includes(s),q=f.includes(s);if(T)return{hasPositionAssigned:!!_,info:"Actions Disabled for structure",isActiveDrawPosition:q,isDrawPosition:!0,validActions:[],isByePosition:B};if(Un({policyActions:M,action:cs})&&!q&&b&&!U&&(!_||B)){let{validAssignmentActions:K}=rO({positionSourceStructureIds:P,unassignedParticipantIds:W,possiblyDisablingAction:N,isWinRatioFedStructure:E,tournamentParticipants:c,positionAssignments:b,returnParticipants:r,appliedPolicies:I,drawDefinition:i,isByePosition:B,drawPosition:s,structureId:m,event:a});K?.forEach(X=>D.push(X))}if(Un({policyActions:M,action:Tp})){let{validAssignmentActions:K}=nO({drawPositionInitialRounds:d,tournamentParticipants:c,positionAssignments:b,returnParticipants:r,appliedPolicies:I,drawDefinition:i,drawPosition:s,structureId:m,drawId:C});K?.forEach(X=>D.push(X))}let{participantId:Y}=_||{},k=Y&&c.find(K=>K.participantId===Y);if(_){Un({policyActions:M,action:nS})&&!q&&(D.push({type:nS,method:VU,payload:{drawId:C,structureId:m,drawPosition:s},willDisableLinks:N}),B||D.push({type:Jf,method:Wb,payload:{drawId:C,structureId:m,drawPosition:s},willDisableLinks:N}),Un({policyActions:M,action:od})&&!B&&D.push({type:od,method:VU,payload:{drawId:C,structureId:m,drawPosition:s,replaceWithBye:!0},willDisableLinks:N}));let K=p.stage===at||p.stage===tt&&p.stageSequence===1;if(!B&&WU({activePositionOverrides:A,activeDrawPositions:f,action:Vs})&&Un({policyActions:M,action:Vs})&&lp({drawDefinition:i,structureId:m,drawPosition:s})&&K){let{seedAssignments:X}=vr({returnAllProxies:!0,drawDefinition:i,structure:p}),{seedNumber:$,seedValue:nt}=X?.find(Q=>Q.participantId===Y)??{};D.push({type:Vs,method:Xb,participant:k,seedNumber:$,payload:{drawId:C,structureId:m,participantId:Y,seedValue:nt}})}if(!B&&WU({activePositionOverrides:A,activeDrawPositions:f,action:Ap})&&Un({policyActions:M,action:Ap})&&lp({drawDefinition:i,structureId:m,drawPosition:s})&&K){let{seedAssignments:X}=vr({returnAllProxies:!0,drawDefinition:i,structure:p}),{seedNumber:$}=X?.find(nt=>nt.participantId===Y)??{};D.push({method:zb,type:Ap,participant:k,seedNumber:$,payload:{participantId:Y,structureId:m,drawId:C}})}if(!B&&Y){if(Un({policyActions:M,action:Bs})){let X={type:Bs,method:rS,participant:k,payload:{penaltyCode:void 0,penaltyType:void 0,participantIds:[],notes:void 0,drawId:C}};D.push(X)}if(Un({policyActions:M,action:Iu})){let X={type:Iu,method:Kb,participant:k,payload:{participantId:Y,otherName:void 0}};D.push(X)}}if(Un({policyActions:M,action:tg})){let{validSwapAction:X}=uO({possiblyDisablingAction:N,tournamentParticipants:c,inactiveDrawPositions:l,activeDrawPositions:f,positionAssignments:b,returnParticipants:r,byeDrawPositions:g,drawDefinition:i,isByePosition:B,drawPosition:s,structureId:m,structure:p,drawId:C});X&&D.push(X)}}if(Un({policyActions:M,action:Xf})&&!U){let{validAlternatesAction:K}=eO({possiblyDisablingAction:N,tournamentParticipants:c,positionAssignments:b,activeDrawPositions:f,returnParticipants:r,appliedPolicies:I,drawDefinition:i,drawPosition:s,validActions:D,structureId:m,structure:p,drawId:C,event:a});K&&D.push(K)}if(Un({policyActions:M,action:Zf})&&!U&&b){let{validLuckyLosersAction:K}=tO({sourceStructuresComplete:y,possiblyDisablingAction:N,isWinRatioFedStructure:E,tournamentParticipants:c,activeDrawPositions:f,positionAssignments:b,drawDefinition:i,drawPosition:s,structureId:m,structure:p,drawId:C});K&&D.push(K)}if(k?.participantType===pt&&Un({policyActions:M,action:Qf})){let{validModifyAssignedPairAction:K}=Zb({tournamentParticipants:c,returnParticipants:r,drawPosition:s,participant:k,drawId:C,event:a});K&&D.push(K)}return{hasPositionAssigned:!!_,isActiveDrawPosition:q,isDrawPosition:!0,isByePosition:B,validActions:D}}function hu({policyDefinitions:t,appliedPolicies:e,drawType:r}){let n=t?.[im]?.drawTypeCoercion,o=e?.[im]?.drawTypeCoercion;return(typeof n=="boolean"?n:void 0)??(r&&n?.[r])??(typeof o=="boolean"?o:void 0)??(r&&o?.[r])??!0}function yp({tournamentRecord:t,drawDefinition:e,stage:r=tt,structureId:n,structure:o}){if(!t)return{error:j};if(!o&&!e)return{error:z};if(!o&&!n&&e?.structures?.filter(a=>a.stage===r).length===1&&(o=e.structures.find(a=>a.stage===r)),!o&&!n)return{error:We};let{error:i,positionAssignments:s}=Dt({drawDefinition:e,structureId:n,structure:o});return{positionAssignments:s??[],structureId:o?.structureId,error:i}}function IS({structureId:t,drawDefinition:e}){if(!e)return{error:z};if(!er(t))return{error:G};let r=Rs({drawDefinition:e,structureId:t});if(r.error)return r;let n=r.links.target.flatMap(i=>i.target.feedProfile).filter(Boolean),o=!Wt([Fo,rn,Ju,ei],n).length;return{...R,valid:o}}function sd({consideredEntries:t,policyDefinitions:e,tournamentRecord:r,appliedPolicies:n,participantMap:o,enforceGender:i,participants:s,event:a}){if((!s||!o)&&r&&({participants:s,participantMap:o}=$t({tournamentRecord:r})),!s)return{error:Ba};if(!Array.isArray(s))return{error:G};if(!a)return{error:St};let c=e?.[qe]??n?.[qe]??is[qe],u=(i??c?.participants?.enforceGender)!==!1,{eventType:p,gender:m}=a,d=p===ui,l=p===Kr&&Lt||d&&pt||It,f=Object.assign({},...(t??a.entries??[]).map(S=>({[S.participantId]:S.entryStatus}))),g=Object.keys(f),h=s.filter(S=>g.includes(S.participantId)).filter(S=>{let T=ZF({participant:S,participantType:l,eventType:p,entryStatusMap:f}),A=tG({genderEnforced:u,participantMap:o,eventGender:m,participant:S,isDoubles:d,mismatch:T});return T||!A});if(h.length){let S=h.map(T=>T.participantId);return{error:XA,invalidParticipantIds:S}}return{...R,valid:!0}}function ZF({participant:t,participantType:e,eventType:r,entryStatusMap:n}){let o=n[t.participantId],i=r&&[ui,Kr].includes(r)&&t.participantType===It&&(Ls(o)||o===go);return t.participantType!==e&&!i}function tG(t){let{participant:e,participantMap:r,eventGender:n,mismatch:o,isDoubles:i,genderEnforced:s}=t,a=!o&&i&&mt(e?.individualParticipantIds?.map(m=>r?.[m]?.participant?.person?.sex).filter(Boolean)??[])||[],c=!n||!a?.length||On===n||[Zt,ce].includes(n)&&a[0]===n||Cr===n&&(a.length==1&&e.individualParticipantIds?.length===1||a.length===2),u=e?.person?.sex,p=!e?.person||!n||[On,Cr].includes(n)||[Zt,ce].includes(n)&&u===n;return!s||c&&p}function hS({qualifyingProfiles:t,appliedPolicies:e,idPrefix:r,isMock:n,uuids:o}){let i="generateQualifyingSTructures",s=[],a=[],c=[],u=(g,I)=>g.stageSequence-I.stageSequence,p=(g,I)=>g.roundTarget-I.roundTarget,m=0,d=0,l,f=1;for(let g of t.sort(p)){let I=g.structureProfiles||[];f=g.roundTarget||f;let h=1,S=0,T,A,P;for(let y of(I||[]).sort(u)){let E=Zp(y.drawSize||y.participantsCount),{qualifyingRoundNumber:U,structureOptions:M,matchUpFormat:N,structureName:C,structureId:D,drawType:O}=y,b=y.matchUpType,_=y.qualifyingPositions||eG({drawSize:E,qualifyingRoundNumber:U}),L,F,w;if(!lt(E))return v({result:{error:Ga},stack:i});let x=t.length>1?`${f}-`:"",H=I.length>1||x?h:"",V=C||(x||H?`${Be(at)} ${x}${H}`:Be(at));if(O===un){let{structures:W,groupCount:B,maxRoundNumber:q}=Aa({structureName:y.structureName||V,structureId:D||o?.pop(),stage:at,structureOptions:M,appliedPolicies:e,stageSequence:h,matchUpType:b,roundTarget:f,drawSize:E,idPrefix:r,isMock:n,uuids:o});S=B,L=q,F=W[0],l=[1]}else({drawSize:E,matchUps:w,roundLimit:L}=mn({qualifyingRoundNumber:U,qualifyingPositions:_,matchUpType:b,drawSize:E,idPrefix:r,isMock:n,uuids:o})),F=Xr({structureName:y.structureName||V,structureId:D||o?.pop(),qualifyingRoundNumber:L,stage:at,matchUpFormat:N,stageSequence:h,matchUpType:b,roundLimit:L,matchUps:w}),f&&gt({extension:{name:cn,value:f},element:F}),S=w?.filter(W=>W.roundNumber===L)?.length||0;if(h>1){let{link:W}=ya({sourceStructureId:A,sourceRoundNumber:T,targetStructureId:F.structureId,finishingPositions:P===kn?[1]:void 0,linkType:P});c.push(W),m+=(E||0)-S}else m+=E||0;P=O===un?kn:Jn,A=F.structureId,T=L,a.push(F),h+=1}d+=S,s.push({qualifiersCount:S,finalQualifyingRoundNumber:T,finalQualifyingStructureId:A,finishingPositions:l,roundTarget:f,linkType:P}),f+=1}return{qualifiersCount:d,qualifyingDrawPositionsCount:m,qualifyingDetails:s,structures:a,...R,links:c}}function eG({drawSize:t,qualifyingRoundNumber:e}){let r=t,n=0;for(;n<e;)r=Math.floor(r/2),n+=1;return r}function SS(t){let{drawTypeCoercion:e,enforceMinimumDrawSize:r}=t,n=ct(t.drawSize),o=e&&(typeof e=="boolean"||e<=2)&&n===2&&Zn||t.drawType||Zn,i=yE.includes(o);if(n&&i){if(e&&(typeof e=="boolean"&&n<4||n<=e))o=Zn;else if(n<4&&r)return{...v({context:{enforceMinimumDrawSize:r,drawSize:n,drawType:o},result:{error:_u},stack:"getCoercedDrawType"}),drawType:o}}return{drawType:o}}function pO(t){let{drawDefinition:e,structureOptions:r,requireSequential:n}=t,o={structureName:Be(tt),...t,stage:tt},{structures:i,groupCount:s,groupSize:a}=Aa(o);if(s<1)return{error:by};let c=r?.playoffGroups||[{finishingPositions:[1],structureName:Be(ae)}],[u]=i,{structures:p,links:m}=Vh({sourceStructureId:u.structureId,requireSequential:n,drawDefinition:e,playoffGroups:c,groupCount:s,groupSize:a,...t});return p&&i.push(...p),{...R,structures:i,links:m}}function mO({mainStructure:t,consolationStructure:e,deciderStructure:r}){let o=e.matchUps.reduce((p,m)=>(m.drawPositions||[]).filter(Boolean).length&&!p.includes(m.roundNumber)?p.concat(m.roundNumber):p,[]),i=t.matchUps.reduce((p,m)=>!p||m.roundNumber>p?m.roundNumber:p,void 0),s=e.matchUps.reduce((p,m)=>!p||m.roundNumber>p?m.roundNumber:p,void 0),a=o.map((p,m)=>{let l=o.indexOf(p)%2?rn:Fo,f=1+m;return{linkType:Vn,source:{roundNumber:f,structureId:t.structureId},target:{feedProfile:l,roundNumber:p,structureId:e.structureId}}}),c={linkType:Jn,source:{roundNumber:s,structureId:e.structureId},target:{feedProfile:rn,roundNumber:i,structureId:t.structureId}},u=[{linkType:Jn,source:{roundNumber:i,structureId:t.structureId},target:{feedProfile:rn,roundNumber:1,structureId:r.structureId}},{linkType:Vn,source:{roundNumber:i,structureId:t.structureId},target:{feedProfile:rn,roundNumber:1,structureId:r.structureId}}];return[...a,c,...u]}function dO({structureName:t,matchUpType:e,idPrefix:r,drawSize:n,isMock:o,uuids:i}){let s=[],{matchUps:a}=$o({linkFedFinishingRoundNumbers:[1],drawSize:n+1,matchUpType:e,idPrefix:r,isMock:o}),c=ss({structureName:t||Be(tt),structureId:i?.pop(),stageSequence:1,stage:tt,matchUpType:e,matchUps:a});s.push(c);let u=n/2,{matchUps:p}=$o({finishingPositionOffset:u,idPrefix:r&&`${r}-c`,drawSize:n-1,isConsolation:!0,matchUpType:e,isMock:o,uuids:i}),m=ss({structureName:Be(AE),matchUps:p,structureId:i?.pop(),stage:Ge,stageSequence:2,matchUpType:e});s.push(m);let{matchUps:d}=mn({idPrefix:r&&`${r}-p1t2`,drawSize:2,matchUpType:e,isMock:o}),l=ss({structureName:Be(TE),matchUps:d,structureId:i?.pop(),stageSequence:3,stage:ae,matchUpType:e});s.push(l);let f=mO({mainStructure:c,consolationStructure:m,deciderStructure:l});return{structures:s,links:f,...R}}function lO(t){let{qualifyingRoundNumber:e,finishingPositionOffset:r,qualifyingPositions:n,matchUpType:o,idPrefix:i,drawSize:s,isMock:a,uuids:c}=t;if(!lt(s)||s<2)return{matchUps:[],roundsCount:0};if(gn(s))return mn(t);let u=rG(s),p=u.shift(),m=Z(1,(p?.participantsCount||0)+1).map(I=>({drawPosition:I})),d=[],l=1;({matchUps:d}=Ip({roundNumber:l,matchUpType:o,idPrefix:i,matchUps:d,isMock:a,nodes:m,uuids:c})),l++;let f=t.roundLimit||e;for(let I of u){let h=I.participantsCount/2,S=Z(1,h+1);n&&h===n&&(f=l-1);let T=S.map(A=>{let P=Ym({roundPosition:A,roundNumber:l,idPrefix:i,uuids:c});return{roundPosition:A,roundNumber:l,matchUpId:P}});d.push(...T),l++}let g=l-1;return d=Cs({finishingPositionOffset:r,lucky:!0,roundsCount:g,roundLimit:f,matchUps:d}),f&&(d=d.filter(I=>I.roundNumber<=f)),{matchUps:d,roundsCount:g,roundLimit:f}}function rG(t){let e=ct(t),r=e%2?e+1:e,n=!!(Math.ceil(r/2)%2),o=[{participantsCount:r,preFeedRound:n}];for(;r>2;){let i=Math.ceil(r/2),s=i===1,a=!!(!s&&i%2);r=!s&&a?i+1:i;let c=!!(r!==2&&Math.ceil(r/2)%2);o.push({participantsCount:r,preFeedRound:c,feedRound:a})}return o}function TS(t){let{playoffAttributes:e,stageSequence:r=1,stage:n=tt,matchUpType:o,drawSize:i,uuids:s}=t,a=()=>!t.isMock&&!t.idPrefix?void 0:`${t.drawDefinition.drawId}-s-0`,c=t.structureId||a()||s?.pop(),{appliedPolicies:u}=yt(t),p=t.policyDefinitions?.[Lc]||u?.[Lc];t.skipRounds=t.skipRounds||i<=4&&(p?.feedMainFinal?0:1)||0;let m=t.structureName??e?.["0"]?.name??Be(tt),d=()=>{let{matchUps:f}=mn(t);return{structures:[Xr({stageSequence:r,structureName:m,matchUpType:o,structureId:c,matchUps:f,stage:n})],links:[],...R}};return{generators:{[br]:()=>({structures:[Xr({finishingPosition:Ms,stageSequence:r,structureName:m,matchUps:[],matchUpType:o,structureId:c,stage:n})],links:[],...R}),[Mi]:()=>{let{matchUps:f}=lO(t);return{structures:[Xr({stageSequence:r,structureName:m,matchUpType:o,structureId:c,matchUps:f,stage:n})],links:[],...R}},[Zn]:()=>d(),[jc]:()=>dO(t),[Hc]:()=>mc({...t,roundOffsetLimit:3,playoffAttributes:e??Yl}),[Wc]:()=>mc({...t,roundOffsetLimit:2,playoffAttributes:e??ql}),[ae]:()=>mc(t),[ua]:()=>{let{matchUps:f}=$o({drawSize:i,uuids:s,matchUpType:o});return{structures:[Xr({stageSequence:r,structureName:m,matchUpType:o,structureId:c,stage:tt,matchUps:f})],links:[],...R}},[Zu]:()=>Lh(t),[Yc]:()=>lc({...t,feedRounds:1,fmlc:!0}),[SE]:()=>lc({...t,feedRounds:1}),[GI]:()=>lc({...t,feedsFromFinal:1}),[kI]:()=>lc({...t,feedsFromFinal:2}),[VI]:()=>lc({...t,feedsFromFinal:3}),[tp]:()=>lc(t),[jl]:()=>Gh(t),[un]:()=>Aa(t),[to]:()=>pO(t)}}}function ad(t){let{enforceMinimumDrawSize:e=!0,overwriteExisting:r,appliedPolicies:n,staggeredEntry:o,drawDefinition:i,tieFormat:s,isMock:a,uuids:c}=t||{},u=ct(t.drawSize),p=t.drawTypeCoercion??hu({appliedPolicies:n,drawType:t.drawType}),m="generateDrawStructuresAndLinks",d=SS({drawType:t.drawType,enforceMinimumDrawSize:e,drawTypeCoercion:p,drawSize:u});if(d.error)return d;let l=d.drawType,f=[],g=[],I=t?.matchUpType??ee,h=i?.structures?.filter(({stage:W})=>W===at);h&&f.push(...h);let S=h?.map(({structureId:W})=>W),T=i?.structures?.find(({stage:W,stageSequence:B})=>W===tt&&B===1),A=i?.links?.filter(W=>W.target.structureId===T?.structureId&&S?.includes(W.source.structureId)),P=(W,B)=>{if(W.linkType===kn&&B?.structures){let q=W.source.finishingPositions||[];return B.structures.length*q.length}else if(W.linkType===Jn&&B?.matchUps?.length){let q=W.source.roundNumber;return B.matchUps.filter(({roundNumber:k})=>k===q).length}},y=h?.map(W=>{let B=A?.find(X=>X.target.structureId===W.structureId),q=Dt({structure:W})?.positionAssignments?.length??0;if(!B)return q;let Y=B?.source.structureId,k=i.structures?.find(X=>X.structureId===Y),K=P(B,k)||0;return q-K}).filter(Boolean).reduce((W,B)=>W+B,0),E=A?.map(W=>{let B=W.source.structureId,q=h?.find(Y=>Y.structureId===B);return P(W,q)}).filter(Boolean).reduce((W,B)=>W+B,0),U=!!(T&&!T?.matchUps?.length);if(h?.length&&!U)return{error:sI};let M=!h?.length&&t.qualifyingProfiles,N=M?.length&&hS({idPrefix:t.idPrefix,qualifyingProfiles:M,appliedPolicies:n,isMock:a,uuids:c});if(N?.error)return N;let{qualifyingDrawPositionsCount:C,qualifyingDetails:D,qualifiersCount:O}=N||{qualifyingDrawPositionsCount:y,qualifiersCount:E};C&&(N?.structures&&f.push(...N.structures),N?.links&&g.push(...N.links)),Object.assign(t,rt({drawSize:u,matchUpType:I,tieFormat:s}));let b=l!==br&&(!u||u<2||!o&&![ua,Mi].includes(l)&&([to,un].includes(l)&&u<3||![un,to].includes(l)&&!gn(u)));if(b&&!C)return v({context:{drawSize:u,invalidDrawSize:b},result:{error:_u},stack:m});let{generators:_,error:L}=TS(t);if(L)return{error:L};let F=_[l];if(!F)return{error:Zd};let w=F?.();if(w.error)return w;let{structures:x,links:H}=w;if(x?.length){let W=x.find(({stage:B,stageSequence:q})=>B===tt&&q===1);if(T&&W){if(U){let B=W.structureId;if(W.structureId=T.structureId,H?.length)for(let q of H)q.source.structureId===B&&(q.source.structureId=T.structureId),q.target.structureId===B&&(q.target.structureId=T.structureId)}else if(!r)return{error:sI}}f.push(...x)}f.sort(ri),H?.length&&g.push(...H);let V=w.structures.find(({stage:W,stageSequence:B})=>W===tt&&B===1);for(let W of D||[]){let{finalQualifyingRoundNumber:B,finalQualifyingStructureId:q,roundTarget:Y,finishingPositions:k,linkType:K}=W,X=V&&ya({targetStructureId:V.structureId,sourceStructureId:q,sourceRoundNumber:B,finishingPositions:k,targetEntryRound:Y,linkType:K})?.link;if(X?.error)return X;X&&g.push(X)}return A&&g.push(...A),{...R,qualifyingResult:{qualifyingDrawPositionsCount:C,qualifiersCount:O},structures:f,links:g}}function cd(t){let{modifyOriginal:e=!0,stageSequence:r=1,isMock:n}=t||{},o="generateDrawTypeAndModifyDrawDefinition";if(!t.drawDefinition)return v({result:{error:z},stack:o});let i=e?t.drawDefinition:J(t.drawDefinition,!1,!0),{tieFormat:s,matchUpType:a}=t;if(s){let T=cr({tieFormat:s});if(T.error)return T}s=Ke(s??Ve({drawDefinition:i})?.tieFormat),a=a??(i.matchUpType||ee),t.tieFormat=s,t.matchUpType=a;let c=pp({drawDefinition:i,stage:tt});t.drawSize=t.drawSize??c,!c&&t.drawSize&&gp({drawSize:t.drawSize,drawDefinition:i,stageSequence:r,stage:tt});let u=be({drawDefinition:i}).drawMatchUps.map(le),p=ad(t);if(p.error)return v({result:p,stack:o});let{structures:m,links:d,qualifyingResult:l}=p;i.structures=m,i.links=d;let f=Math.max(t.qualifiersCount??0,l?.qualifiersCount||0);if(l?.qualifyingDrawPositionsCount&&!pp({stage:at,drawDefinition:i})){let A=gp({drawSize:l.qualifyingDrawPositionsCount,stage:at,drawDefinition:i});if(A.error)return A}if(f){let T=xh({qualifiersCount:f,drawDefinition:i,stage:tt});if(T.error)return T}let g=t.drawSize??c;Object.assign(t,rt({drawSize:g,matchUpType:a,tieFormat:s}));let{matchUps:I,matchUpsMap:h}=re({drawDefinition:i});s&&I?.forEach(T=>{if(!u.includes(T.matchUpId)){let{tieMatchUps:A}=Ea({tieFormat:s,matchUp:T,isMock:n});Object.assign(T,{tieMatchUps:A,matchUpType:a})}});let{inContextDrawMatchUps:S}=rs({drawDefinition:i,matchUpsMap:h});return Rt({tournamentId:t.tournamentRecord?.tournamentId,drawDefinition:i}),{inContextDrawMatchUps:S,drawDefinition:i,matchUpsMap:h,...R,structures:m,matchUps:I,links:d}}function AS(t){let{drawType:e=Zn,attachConsolation:r=!0,applyPositioning:n=!0,tournamentRecord:o,staggeredEntry:i,automated:s,placeByes:a,isMock:c,event:u}=t,p=t?.drawDefinition;if(!p)return{error:z};let m=ke,d=ii({stageSequence:1,drawDefinition:p,stage:m}),l=[un,jc,to].includes(e)?d.length:Bi(d.length);if(!i&&e===ua&&d.length<2||e===un&&d.length<3)return{error:_u};let{tieFormat:f,matchUpType:g}=t;if(f){let D=cr({tieFormat:f});if(D.error)return D}f=Ke(f??Ve({drawDefinition:p})?.tieFormat),g=g??p.matchUpType??ee;let{structures:I}=Cn({stageSequence:1,drawDefinition:p,stage:m});if(I.length>1)return{error:JA};if(I?.[0]?.matchUps?.length)return{error:El};let S=I?.[0]?.structureId;Object.assign(t,rt({structureName:t.structureName??Be(ke),structureId:S,matchUpType:g,tieFormat:f,drawSize:l,stage:m}));let T=TS(t);if(T.error)return T;let A=T.generators[e];if(!A)return{error:Zd};let P=A?.();if(P.error)return P;let{structures:y,links:E}=P,U=y.map(D=>Pt({structure:D}).matchUps).flat();f&&U.forEach(D=>{let{tieMatchUps:O}=Ea({matchUp:D,tieFormat:f,isMock:c});Object.assign(D,{tieMatchUps:O,matchUpType:g})}),(!n||!r)&&(p=J(p,!1,!0)),p.links||(p.links=[]),E.length&&p.links.push(...E);let M=y.map(({structureId:D})=>D);p.structures||(p.structures=[]);let N=p.structures.map(({structureId:D})=>D);p.structures=p.structures.map(D=>M.includes(D.structureId)?y.find(({structureId:O})=>O===D.structureId):D);let C=y.filter(({structureId:D})=>!N.includes(D));return C.length&&p.structures.push(...C),s&&uc({seedingProfile:t.seedingProfile,applyPositioning:n,tournamentRecord:o,drawDefinition:p,structureId:S,placeByes:a,drawSize:l,event:u}),r&&Rt({drawDefinition:p}),{links:E,structures:y,...R}}function Su(t){let{matchUpIds:e=[],drawDefinition:r,roundNumber:n,newRound:o,isMock:i,event:s}=t;if(typeof r!="object")return{error:z};let{participantIdPairings:a,matchUpsCount:c}=t,u=t.structureId??(r.structures?.length===1&&r.structures?.[0]?.structureId);if(typeof u!="string")return{error:We};let p=r.structures?.find(T=>T.structureId===u);if(!p)return{error:_t};let m,l=(p.matchUps??[])?.reduce((T,A)=>(A.roundPosition&&(m=!0),(A?.roundNumber||0)>T?A.roundNumber:T),0),f=r?.entries?.filter(T=>{let A=T.entryStatus;return Mr.includes(A)})??[],g=Math.floor(f?.length/2)||1;if(c){if(c>g&&t.restrictMatchUpsCount!==!1)return v({result:{error:G,info:"matchUpsCount error",context:{roundMatchUpsCount:g}}})}else if(o)c=g;else{let T=n??l??1,A=p.matchUps?.filter(y=>y.roundNumber===T)?.length??0,P=g-A;P>0&&(c=P)}if(a&&!Array.isArray(a)||c&&!lt(c)||e&&!Array.isArray(e)||!a&&!c)return{error:G,info:"matchUpsCount or pairings error"};if(c&&c>25)return{error:G,info:"matchUpsCount must be less than 25"};if(p.structures||m||p.finishingPosition===Ci)return{error:hs};if(n&&!t.ignoreLastRoundNumber&&n-1>(l||0))return{error:G,info:"roundNumber error"};let I=n??(o&&(l??0)+1||l||1);a=a??Z(0,c).map(()=>({participantIds:[void 0,void 0]}));let h=T=>{if(!t.idPrefix&&!i)return;let A=r.drawId,P=t.idPrefix??"ah";return`${A}-${P}-${I}-${T}`},S=a?.map((T,A)=>{let P=T?.participantIds??[void 0,void 0];P.push(void 0,void 0);let E=P.slice(0,2).map((M,N)=>rt({sideNumber:N+1,participantId:M})),U=e[A]??h(A)??Mt();return{roundNumber:I,matchUpStatus:Kt,matchUpId:U,sides:E}});if(S?.length){let T=Ve({drawDefinition:r,event:s})?.tieFormat;T&&S.forEach(A=>{let{tieMatchUps:P}=Ea({tieFormat:T,matchUp:A,isMock:i});Object.assign(A,{tieMatchUps:P,matchUpType:Bt})})}return{roundNumber:I,matchUpsCount:S?.length??0,matchUps:S,...R}}function gO({maxIterations:t=4e3,valueSortedPairings:e,pairingValues:r,valueObjects:n,deltaObjects:o}){let i=Object.assign({},...e.map(S=>({[S.pairing]:S.value}))),s=Object.keys(r),a=[],c=fO({actorsCount:s.length,valueSortedPairings:e,pairingValueMap:i,deltaObjects:o,valueObjects:n}),u=[ZU(c)];a.push(c);let p=c.value,m=c,d=0,l=0,f=s.length,g;do f-=1,g=s.length*r[s[0]].length;while(g>t&&f>5);let I=[];s.forEach(S=>{r[S].slice(0,f).forEach(A=>{l+=1;let P=Na(S,A.opponent);if(!I.includes(P)){let y=fO({stipulated:[[S,A.opponent]],actorsCount:s.length,valueSortedPairings:e,pairingValueMap:i,deltaObjects:o,valueObjects:n});if(!u.includes(ZU(y))){u.push(ZU(y)),a.push(y);let{maxDelta:E,value:U}=y;E<m.maxDelta&&(m=y),(U<p||U===p&&Math.round(Math.random()))&&(p=U),I.push(P),d+=1}}}),a=a.filter(A=>Math.abs(A.value-p)<5)}),a.sort((S,T)=>S.maxDiff-T.maxDiff);let h=Rr(a);return{candidatesCount:d,deltaCandidate:m,maxIterations:t,iterations:l,candidate:h}}function ZU(t){return t.participantIdPairings.map(({participantIds:e})=>e.sort().join("|")).sort().join("/")}function fO({valueSortedPairings:t,stipulated:e=[],pairingValueMap:r,deltaObjects:n,valueObjects:o,actorsCount:i}){let s=[].concat(...e),a=[],c=0;e.filter(Boolean).forEach(d=>{let[l,f]=d,g=Na(l,f),I=r[g];a.push({participantIds:d,value:I}),c+=r[g]}),Ae(t,i).map(d=>sr(d).map(l=>({...l,value:l.value+Math.random()*Math.round(Math.random())}))).flat().forEach(d=>{let l=d.pairing.split("|");if(!l.reduce((g,I)=>s.includes(I)||g,!1)){s.push(...l);let g=d.value;c+=g,a.push({participantIds:l,value:g})}}),a.sort((d,l)=>d.value-l.value);let p=a.reduce((d,l)=>{let[f,g]=l.participantIds,I=Na(f,g),h=n[I];return h>d?h:d},0),m=a.reduce((d,l)=>{let[f,g]=l.participantIds,I=Na(f,g),h=o[I];return h>d?h:d},0);return{value:c,participantIdPairings:a,maxDelta:p,maxDiff:m}}function Na(t,e){return[t,e].sort(ou).join("|")}function tP({participantIds:t}){let e={},r=[];t.forEach(o=>{e[o]=t.filter(i=>i!==o),e[o].forEach(i=>{let s=Na(i,o);r.includes(s)||r.push(s)})});let n=Object.assign({},...r.map(o=>({[o]:0})));return{uniquePairings:r,possiblePairings:e,deltaObjects:n}}function IO({matchUps:t}){let e=[];for(let r of t){let n=r.sides.map(ft);if(n.length===2){let[o,i]=n,s=Na(o,i);e.includes(s)||e.push(s)}}return{encounters:e}}function hO({possiblePairings:t,valueObjects:e}){let r={};for(let o of Object.keys(t)){let i=t[o].map(s=>n(o,s));r[o]=i.sort((s,a)=>s.value-a.value)}function n(o,i){let s=Na(o,i);return{opponent:i,value:e[s]}}return{pairingValues:r}}var Hs="ELO",eP="NTRP",nG="TRN",rP="UTR",ng="WTN",SO={ELO:Hs,NTRP:eP,TRN:nG,UTR:rP,WTN:ng};var oG={[Hs]:{defaultInitialization:1500,decimalsCount:0,range:[0,3e3],ascending:!0},[eP]:{accessors:["ntrpRating","dntrpRatingHundredths"],attributes:{ustaRatingType:""},accessor:"dntrpRatingHundredths",defaultInitialization:3,decimalsCount:1,ascending:!0,range:[1,7]},[rP]:{defaultInitialization:6,accessors:["utrRating"],accessor:"utrRating",decimalsCount:2,ascending:!0,range:[1,16]},[ng]:{attributes:{confidence:{generator:!0,range:[60,100]}},accessors:["wtnRating","confidence"],defaultInitialization:23,accessor:"wtnRating",ascending:!1,decimalsCount:2,range:[40,1]}},Jr=oG;var iG=0;function TO({tournamentParticipants:t,adHocRatings:e,eventType:r,scaleName:n,pairing:o}){let i=Jr[n]?.defaultInitialization??iG;return o.split("|").map(s=>{if(r===Vr){let a=t?.find(c=>c.participantId===s)?.individualParticipantIds;return a?a?.map(c=>e[c]||i):i*2}else return e[s]||i})}function AO({tournamentParticipants:t,adHocRatings:e={},possiblePairings:r,uniquePairings:n,maxIterations:o,deltaObjects:i,valueObjects:s,eventType:a,scaleName:c,salted:u}){n.forEach(h=>{let S=TO({tournamentParticipants:t,adHocRatings:e,scaleName:c,eventType:a,pairing:h}),T=typeof u=="number"&&u||.5,A=u&&(Math.round(Math.random())?T:T*-1)||0,P=Math.abs(S[0]-S[1])+A,y=Math.abs(S[0]-S[1]);i[h]=y,s[h]||(s[h]=0),s[h]+=P?Math.pow(P,2):0});let p=n.map(h=>({pairing:h,value:s[h]})).sort((h,S)=>h.value-S.value),{pairingValues:m}=hO({possiblePairings:r,valueObjects:s}),{candidate:d,candidatesCount:l,deltaCandidate:f,iterations:g}=gO({valueSortedPairings:p,maxIterations:o,pairingValues:m,deltaObjects:i,valueObjects:s}),{participantIdPairings:I}=d;return{participantIdPairings:I,candidatesCount:l,deltaCandidate:f,iterations:g,candidate:d}}var sG=100,aG=100,cG=4e3;function ud({encounterValue:t=sG,sameTeamValue:e=aG,maxIterations:r=cG,generateMatchUps:n=!0,ignoreLastRoundNumber:o,iterationMatchUps:i,tournamentRecord:s,participantIds:a,drawDefinition:c,adHocRatings:u,salted:p=.5,roundNumber:m,structureId:d,matchUpIds:l,eventType:f,structure:g,scaleName:I,idPrefix:h,isMock:S,event:T}){if(!c)return{error:z};if(!g&&!d)return{error:_t};if(g||(g=st({drawDefinition:c,structureId:d}).structure),!Ct(g))return{error:Ao};if(!a?.length)return{error:so};let A=[...i??[],...g?.matchUps??[]],{encounters:P}=IO({matchUps:A}),y=s?.participants??[],{valueObjects:E}=uG({tournamentParticipants:y,encounterValue:t,sameTeamValue:e,encounters:P}),{uniquePairings:U,possiblePairings:M,deltaObjects:N}=tP({participantIds:a}),C={tournamentParticipants:y,possiblePairings:M,drawDefinition:c,participantIds:a,uniquePairings:U,maxIterations:r,adHocRatings:u,deltaObjects:N,valueObjects:E,eventType:f,scaleName:I,structure:g,salted:p},{candidatesCount:D,participantIdPairings:O,iterations:b,candidate:_}=AO(C);if(!D)return{error:Gu};let L,F;if(n){let H=Su({structureId:g?.structureId,ignoreLastRoundNumber:o,participantIdPairings:O,newRound:!0,drawDefinition:c,roundNumber:m,matchUpIds:l,idPrefix:h,isMock:S,event:T});if(H.error)return H;L=H.roundNumber,F=H.matchUps}let{maxDelta:w,maxDiff:x}=_;return{roundNumber:L,participantIdPairings:O,candidatesCount:D,...R,iterations:b,matchUps:F,maxDelta:w,maxDiff:x}}function uG({encounters:t,tournamentParticipants:e,encounterValue:r,sameTeamValue:n}){let o={};for(let s of t)o[s]||(o[s]=0),o[s]+=r;let i=e?.filter(({participantType:s})=>s===Lt);if(i)for(let s of i){let a=s.individualParticipantIds??[],{uniquePairings:c}=tP({participantIds:a});for(let u of c)o[u]||(o[u]=0),o[u]+=n}return{valueObjects:o}}var AP={};ne(AP,{allCompetitionMatchUps:()=>nn,allDrawMatchUps:()=>ar,allEventMatchUps:()=>ro,allPlayoffPositionsFilled:()=>bh,allTournamentMatchUps:()=>pe,analyzeDraws:()=>fu,analyzeMatchUp:()=>Cp,analyzeTournament:()=>RS,bulkUpdatePublishedEventIds:()=>Rp,calculateWinCriteria:()=>ps,categoryCanContain:()=>Zm,checkMatchUpIsComplete:()=>es,checkValidEntries:()=>sd,compareTieFormats:()=>Co,competitionScheduleMatchUps:()=>Au,credits:()=>yO,drawMatchUps:()=>jS,eventMatchUps:()=>Id,filterParticipants:()=>iu,findDrawDefinition:()=>eS,findExtension:()=>ut,getAllDrawMatchUps:()=>re,getAllowedDrawTypes:()=>pd,getAllowedMatchUpFormats:()=>DS,getAppliedPolicies:()=>yt,getAssignedParticipantIds:()=>di,getAvailablePlayoffProfiles:()=>cu,getCategoryAgeDetails:()=>mu,getCheckedInParticipantIds:()=>Xi,getCompetitionDateRange:()=>dd,getCompetitionMatchUps:()=>Np,getCompetitionParticipants:()=>yS,getCompetitionPenalties:()=>MS,getCompetitionVenues:()=>Pp,getCourts:()=>YS,getDrawDefinitionTimeItem:()=>dh,getDrawParticipantRepresentativeIds:()=>Zh,getDrawTypeCoercion:()=>hu,getEligibleVoluntaryConsolationParticipants:()=>Jh,getEntriesAndSeedsCount:()=>nd,getEvent:()=>KS,getEventMatchUpFormatTiming:()=>LS,getEventProperties:()=>qS,getEventStructures:()=>Gf,getEventTimeItem:()=>ru,getEvents:()=>$S,getFlightProfile:()=>kt,getLinkedTournamentIds:()=>kc,getMatchUpCompetitiveProfile:()=>Jc,getMatchUpContextIds:()=>VS,getMatchUpDailyLimits:()=>Sd,getMatchUpDailyLimitsUpdate:()=>FS,getMatchUpDependencies:()=>xr,getMatchUpFormat:()=>BS,getMatchUpFormatTiming:()=>Zc,getMatchUpFormatTimingUpdate:()=>xS,getMatchUpScheduleDetails:()=>bm,getMatchUpType:()=>xm,getMatchUpsStats:()=>HS,getMaxEntryPosition:()=>_S,getModifiedMatchUpFormatTiming:()=>fd,getPairedParticipant:()=>zr,getParticipantEventDetails:()=>ES,getParticipantIdFinishingPositions:()=>tS,getParticipantMembership:()=>US,getParticipantScaleItem:()=>gc,getParticipantSchedules:()=>PS,getParticipantSignInStatus:()=>NS,getParticipantTimeItem:()=>lh,getParticipants:()=>$t,getPersonRequests:()=>gi,getPolicyDefinitions:()=>Io,getPositionAssignments:()=>yp,getPositionsPlayedOff:()=>dc,getPredictiveAccuracy:()=>kS,getRoundMatchUps:()=>Xe,getRounds:()=>WS,getScaleValues:()=>oa,getScaledEntries:()=>ks,getScheduledRoundsDetails:()=>Tu,getSchedulingProfile:()=>Ro,getSchedulingProfileIssues:()=>OS,getSeedingThresholds:()=>Eh,getSeedsCount:()=>gu,getStructureSeedAssignments:()=>vr,getTeamLineUp:()=>ts,getTieFormat:()=>bS,getTimeItem:()=>_n,getTournamentIds:()=>zu,getTournamentInfo:()=>us,getTournamentPenalties:()=>md,getTournamentPersons:()=>CS,getTournamentStructures:()=>Rh,getTournamentTimeItem:()=>nu,getValidGroupSizes:()=>dp,getVenuesAndCourts:()=>oo,isAdHoc:()=>Br,isCompletedStructure:()=>qo,isValidForQualifying:()=>IS,isValidMatchUpFormat:()=>Sr,matchUpActions:()=>id,participantScaleItem:()=>no,participantScheduledMatchUps:()=>GS,positionActions:()=>gS,publicFindVenue:()=>uh,tallyParticipantResults:()=>Ua,tieFormatGenderValidityCheck:()=>Xm,tournamentMatchUps:()=>hd,validMatchUp:()=>cf,validMatchUps:()=>Ar,validateCollectionDefinition:()=>du,validateLineUp:()=>Hm});function yO(){return`
5
+ This project would not have been possible without the generous input and patience
6
+ of tournament organizers and directors who worked with early versions of CourtHive/TMX.
7
+
8
+ Thanks to Pavel, Ivan, Mladen, Zdenko, Antonia, Jakov, Kreso, Barry, Jeff, Bobby... to name just a few.
9
+
10
+ The project would not have even begun without the support of Miro, or the introduction by Sretchko.
11
+ The project would not have succeeded without the enthusiasm of Randy and Bruce.
12
+ Thanks to serendipity and Luca and the ensuing TODS conversations with ITF.
13
+ Thanks to Scott and Jake for sanity checks, suggestions, and camaraderie.
14
+ Thanks to Zoran for inspiring the async support and getting into the weeds with subscriptions.
15
+ Thanks to Dave for backing the conversion of TMX 1.x source into the factory repository.
16
+ Thanks to Vuk and Pavle and Rich and Chris and Deepa for the direct engagement with the APIs.
17
+ Thanks to Joe for repeatedly challenging me and the many pointers to useful tooling.
18
+ Thanks to Shannon for the validation of the approach from his deep domain experience.
19
+ Thanks to Nikola for the ongoing camaraderie and explorations of what we can do with TODS.
20
+
21
+ And a special thanks to my family for putting up with the long days and weeks and months of coding
22
+ and conversations at all hours.
23
+ `}var nP={};ne(nP,{filterParticipants:()=>iu,getCompetitionParticipants:()=>yS,getPairedParticipant:()=>zr,getParticipantEventDetails:()=>ES,getParticipantMembership:()=>US,getParticipantScaleItem:()=>gc,getParticipantSchedules:()=>PS,getParticipantSignInStatus:()=>NS,getParticipantTimeItem:()=>lh,getParticipants:()=>$t,getScaleValues:()=>oa,participantScaleItem:()=>no,validateLineUp:()=>Hm});function yS(t){let{tournamentRecords:e}=t||{};if(typeof e!="object"||!Object.keys(e).length)return{error:wt};let r=[],n={},o={},i={},s=[],a={},c=[];for(let u of Object.values(e)){let{participantIdsWithConflicts:p,mappedMatchUps:m,participantMap:d,participants:l,matchUps:f,derivedEventInfo:g,derivedDrawInfo:I}=$t({...t,tournamentRecord:u});Object.assign(a,m),Object.assign(n,d),Object.assign(o,g),Object.assign(i,I),r.push(...l??[]),s.push(...f??[]),p?.forEach(h=>{c.includes(h)||c.push(h)})}return{participantIdsWithConflicts:c,derivedEventInfo:o,derivedDrawInfo:i,participantMap:n,mappedMatchUps:a,participants:r,...R,matchUps:s}}function ES({tournamentRecord:t,participantId:e}){if(!t)return{error:j};if(!e)return{error:te};let r=[e].concat((t.participants??[]).filter(o=>o?.participantType&&[Lt,pt].includes(o.participantType)&&o.individualParticipantIds?.includes(e)).map(o=>o.participantId));return{eventDetails:(t.events??[]).filter(o=>{let i=(o?.entries??[]).map(s=>s.participantId);return ve(i,r)}).map(o=>({eventName:o.eventName,eventId:o.eventId}))}}function US({tournamentRecord:t,participantId:e}){if(!t)return{error:j};if(!e)return{error:te};let{participants:r}=$t({participantFilters:{participantTypes:[Lt,pt,hr]},tournamentRecord:t});return(r??[]).filter(o=>o.individualParticipantIds?.includes(e)).reduce((o,i)=>{let s=i.participantType;return s&&(o[s]||(o[s]=[]),o[s].push(i)),o},{})}function PS({participantFilters:t={},tournamentRecord:e}){if(!e)return{error:j};if(typeof t!="object")return{error:Yn,context:{participantFilters:t}};let r={eventIds:t.eventIds},n=pe({tournamentRecord:e,contextFilters:r}).matchUps??[],o=Object.assign({},...n.map(p=>({[p.matchUpId]:p}))),i=n.filter(({schedule:p})=>p&&Object.keys(p).length),s=xr({tournamentRecord:e,matchUps:n}).sourceMatchUpIds??[],a={};for(let p of i){let{sides:m}=p,d,l=m?.map(g=>{if(g.participant)return[g.participant].concat(...g.participant.individualParticipants||[]);s[p.matchUpId]&&!d&&(d=(s[p.matchUpId]||[]).map(I=>o[I]).filter(({winningSide:I,bye:h})=>!I&&!h))}).filter(Boolean).flat()??[];for(let g of l){let{participantId:I}=g;a[I]||(a[I]={potentialMatchUps:[],participant:g,matchUps:[]}),a[I].matchUps.push(p)}let f=d?.map(({sides:g})=>g).flat().map(({participant:g})=>g&&[g].concat(...g.individualParticipants||[])).filter(Boolean).flat()||[];for(let g of f){let{participantId:I}=g;a[I]||(a[I]={potentialMatchUps:[],participant:g,matchUps:[]}),a[I].potentialMatchUps.push(p)}}return{participantSchedules:Object.values(a).filter(({participant:p})=>!(t.participantIds&&!t.participantIds.includes(p.participantId)||t.participantTypes&&!t.participantTypes.includes(p.participantType))),...R}}function NS({tournamentRecord:t,participantId:e}){if(!t)return{error:j};if(!e)return{error:te};let{participant:r}=Mo({tournamentRecord:t,participantId:e});if(!r)return{error:Jt};let{timeItem:n}=_n({itemType:Ja,element:r});return n&&n.itemValue===Kc&&Kc}var oP={};ne(oP,{analyzeDraws:()=>fu,analyzeTournament:()=>RS,getAllowedDrawTypes:()=>pd,getAllowedMatchUpFormats:()=>DS,getAppliedPolicies:()=>yt,getCompetitionDateRange:()=>dd,getCompetitionPenalties:()=>MS,getPolicyDefinitions:()=>Io,getTournamentInfo:()=>us,getTournamentPenalties:()=>md,getTournamentPersons:()=>CS,getTournamentStructures:()=>Rh,getTournamentTimeItem:()=>nu});function DS({tournamentRecord:t,categoryName:e,categoryType:r}){if(!t)return{error:j};let{appliedPolicies:n}=yt({tournamentRecord:t});return(n?.[Mn]?.matchUpFormats||[]).filter(({categoryNames:s,categoryTypes:a})=>!e&&!a||e&&s?.includes(e)||r&&a?.includes(r))}function pd({tournamentRecord:t,categoryName:e,categoryType:r}){if(!t)return{error:j};let{appliedPolicies:n}=yt({tournamentRecord:t});return(n?.[im]?.allowedDrawTypes||[]).filter(({categoryNames:s,categoryTypes:a})=>!e&&!a||e&&s?.includes(e)||r&&a?.includes(r))}function md({tournamentRecord:t}){if(!t)return{error:j};let r=(t?.participants??[]).reduce((n,o)=>{let{participantId:i}=o;return(o.penalties??[]).forEach(s=>{let{penaltyId:a}=s||{};n[a]?n[a].participants.push(i):n[a]={...s,participantIds:[i]}}),n},{});return{penalties:Object.values(r)}}function MS({tournamentRecords:t}){if(typeof t!="object"||!Object.keys(t).length)return{error:wt};let e=[];for(let r of Object.values(t)){let{penalties:n}=md({tournamentRecord:r});e.push(...n??[])}return{penalties:e}}function us({tournamentRecord:t}){if(!t)return{error:j};let e=(({tournamentId:r,tournamentRank:n,tournamentStatus:o,formalName:i,tournamentName:s,promotionalName:a,onlineResources:c,localTimeZone:u,startDate:p,endDate:m,hostCountryCode:d,tournamentContacts:l,tournamentAddresses:f})=>({tournamentId:r,tournamentRank:n,tournamentStatus:o,formalName:i,tournamentName:s,promotionalName:a,onlineResources:c,localTimeZone:u,startDate:p,endDate:m,hostCountryCode:d,tournamentContacts:l,tournamentAddresses:f}))(t);return{...R,tournamentInfo:J(e,!1,!0)}}function dd({tournamentRecords:t}){if(!Ct(t))return{error:wt};let r=Object.keys(t??{}).reduce((i,s)=>{let a=t[s],{tournamentInfo:{startDate:c,endDate:u}}=us({tournamentRecord:a}),p=c&&new Date(At(c));(!i.startDate||p&&p<i.startDate)&&(i.startDate=p);let m=u&&new Date(At(u));return(!i.endDate||m&&m>i.endDate)&&(i.endDate=m),i},{startDate:void 0,endDate:void 0}),n=r.startDate&&At(r.startDate.toISOString()),o=r.endDate&&At(r.endDate.toISOString());return!n||!o?{error:al}:{startDate:n,endDate:o}}function CS({tournamentRecord:t,participantFilters:e}){if(!t)return{error:j};let r=t.participants||[];e&&(r=iu({participants:r,participantFilters:e,tournamentRecord:t}));let n={},o=i=>{if(i.person){let{personId:s}=i.person;n[s]?n[s].participantIds.push(i.participantId):n[s]={...i.person,participantIds:[i.participantId]}}};return r.forEach(i=>{i.person&&o(i)}),{tournamentPersons:Object.values(n)}}function EO(t){let r=t.participants?.filter(({participantType:a})=>a===Lt)?.length===2,n=t.events?.length===1&&t.events[0],o=n?.drawDefinitions?.length===1&&n.drawDefinitions[0],s=(o?.structures?.length===1&&o.structures[0])?.positionAssignments?.length===2;return!!(n.tieFormat&&r&&s)}function RS({tournamentRecord:t}){if(!t)return{error:j};let{drawsAnalysis:e}=fu({tournamentRecord:t}),r={isDual:EO(t),drawsAnalysis:e};return{...R,analysis:r}}var sP={};ne(sP,{compareTieFormats:()=>Co,getTieFormat:()=>bS,tieFormatGenderValidityCheck:()=>Xm,validateCollectionDefinition:()=>du});function ld(t){if(!t)return{};let e=[],r=t.tieFormatName,n=t.collectionDefinitions?.map(o=>{let{matchUpType:i,matchUpFormat:s,matchUpCount:a,category:c,gender:u}=o;e.includes(s)||e.push(s);let p=c?.ageCategoryCode;return[a,i===Ri?"D":"S",p,s,u].join(";")}).join("|");return{tieFormatName:t&&r||"UNNAMED",matchUpFormats:e,tieFormatDesc:n}}function Co({considerations:t={},descendant:e,ancestor:r}){let n={},o={},{matchUpFormats:i,tieFormatDesc:s}=ld(e),{matchUpFormats:a,tieFormatDesc:c}=ld(r),u=mt((i??[]).filter(P=>!(a??[]).includes(P)).concat((a??[]).filter(P=>!(i??[]).includes(P)))),p=!!(t?.collectionName&&e.collectionDefinitions.map(({collectionName:P})=>P).join("|")!==r.collectionDefinitions.map(({collectionName:P})=>P).join("|")),m=!!(t?.collectionOrder&&e.collectionDefinitions.map(({collectionOrder:P})=>P).join("|")!==r.collectionDefinitions.map(({collectionOrder:P})=>P).join("|")),d=Object.assign({},...(e?.collectionDefinitions||[]).map(P=>({[P.collectionId]:P}))),l=Object.assign({},...(r?.collectionDefinitions||[]).map(P=>({[P.collectionId]:P})));n.collectionIds=Hy(Object.keys(d),Object.keys(l)),o.collectionIds=Hy(Object.keys(l),Object.keys(d)),n.collectionsValue=UO(d),o.collectionsValue=UO(l),n.groupsCount=r?.collectionGroups?.length??(0-(e?.collectionGroups?.length??0)||0),o.groupsCount=n.groupsCount?-1*n.groupsCount:0;let f=n.collectionsValue.totalValue-o.collectionsValue.totalValue,g=n.collectionsValue.totalMatchUps-o.collectionsValue.totalMatchUps,I=o.collectionsValue.assignmentValues.length!==n.collectionsValue.assignmentValues.length,h=o.collectionsValue.assignmentValues.some((P,y)=>{let E=n.collectionsValue.assignmentValues[y];return!E||P.valueKey!==E.valueKey||P.value!==E.value?!0:Array.isArray(P.value)?P.value.every((U,M)=>E.value[M]===U):!1}),S=p||m||c!==s||I||h||f!==0,T=[...o.collectionsValue.invalidValues,...n.collectionsValue.invalidValues],A=T.length&&T;return{matchUpFormatDifferences:u,matchUpCountDifference:g,descendantDifferences:n,ancestorDifferences:o,orderDifference:m,valueDifference:f,nameDifference:p,descendantDesc:s,ancestorDesc:c,...R,different:S,invalid:A}}function UO(t){let e=[],r=[],n=0;return{totalValue:Object.keys(t).sort(ou).reduce((s,a)=>{let c=t[a],{collectionValueProfiles:u,collectionValue:p,matchUpCount:m,matchUpValue:d,scoreValue:l,setValue:f}=c,g={collectionValueProfiles:u,collectionValue:p,matchUpValue:d,scoreValue:l,setValue:f},I=Object.keys(g).filter(S=>![void 0,null].includes(g[S]));I.length!==1&&e.push({collectionId:a});let h=I[0];if(h){let S=h==="collectionValueProfiles"?Object.values(u):g[h];r.push({valueKey:h,value:S})}return n+=m,u?s+u.reduce((S,T)=>S+T.value,0):m?lt(d)?s+d*m:lt(l)?s+l*m:lt(f)?s+f*m:s+p:s},0),totalMatchUps:n,invalidValues:e,assignmentValues:r}}function og(t){Object.assign(t,{inContext:!0});let{matchUp:e,error:r}=iP(t);return{matchUp:J(e,!0,!0),error:r}}function iP({participantsProfile:t,afterRecoveryTimes:e,tournamentRecord:r,contextContent:n,contextProfile:o,drawDefinition:i,nextMatchUps:s,matchUpId:a,inContext:c,eventId:u,drawId:p,event:m}){if(!r)return{error:j};if(typeof a!="string")return{error:Ne};if(!i||!m){let g=(pe({tournamentRecord:r,nextMatchUps:s}).matchUps??[]).find(I=>I.matchUpId===a);if(!g)return{error:De};({eventId:u,drawId:p}=g),{event:m,drawDefinition:i}=nr({tournamentRecord:r,eventId:u,drawId:p})}if(!i)return{error:fr};o&&!n&&(n=bn({tournamentRecord:r,contextProfile:o}));let d={surfaceCategory:m?.surfaceCategory??r.surfaceCategory,indoorOutDoor:m?.indoorOutdoor??r.indoorOutdoor,endDate:m?.endDate??r.endDate,tournamentId:r.tournamentId,eventId:u??m?.eventId,drawId:p},{participants:l=[]}=pi({participantsProfile:t,tournamentRecord:r,contextProfile:o,inContext:c});if(s){let g=(ar({context:c?d:void 0,participants:l,afterRecoveryTimes:e,contextContent:n,contextProfile:o,drawDefinition:i,nextMatchUps:s,inContext:c,event:m}).matchUps??[]).find(h=>h.matchUpId===a);if(!g)return{error:De};let I=i?.structures?.find(h=>h.structureId===g.structureId);return{drawDefinition:i,structure:I,matchUp:g}}else{let{matchUp:f,structure:g}=xt({context:c?d:void 0,tournamentParticipants:l,afterRecoveryTimes:e,contextContent:n,drawDefinition:i,contextProfile:o,matchUpId:a,inContext:c,event:m});return{matchUp:f,structure:g,drawDefinition:i}}}function bS({tournamentRecord:t,drawDefinition:e,structureId:r,matchUpId:n,structure:o,eventId:i,drawId:s,event:a}){if(!t)return{error:j};if(!s&&!a&&!r&&!n)return v({result:{error:et},stack:"getTieFormat"});i&&!a&&(a=t.events?.find(l=>l.eventId===i));let c=og({tournamentRecord:t,drawDefinition:e,matchUpId:n,drawId:s,event:a});if(n&&c?.error)return c;if(!e&&c?.drawDefinition&&(e=c?.drawDefinition),o=o??c?.structure,!o&&r&&!n){if(!e)return{error:Ur};let l=st({drawDefinition:e,structureId:r});if(l.error)return l;o=l.structure}let u=(o?.tieFormat||o?.tieFormatId)&&Ve({structure:o,drawDefinition:e,event:a})?.tieFormat,p=(e?.tieFormat||e?.tieFormatId)&&Ve({drawDefinition:e,event:a})?.tieFormat,m=Ve({event:a})?.tieFormat,d=Ve({matchUp:c?.matchUp,drawDefinition:e,structure:o,event:a})?.tieFormat;return{...R,matchUp:c?.matchUp,structureDefaultTieFormat:Ke(u),eventDefaultTieFormat:Ke(m),drawDefaultTieFormat:Ke(p),tieFormat:Ke(d),structure:o}}var pP={};ne(pP,{getPersonRequests:()=>gi,getScheduledRoundsDetails:()=>Tu,getSchedulingProfile:()=>Ro,getSchedulingProfileIssues:()=>OS});function Ep({defaultRecoveryMinutes:t=0,defaultAverageMinutes:e,tournamentRecords:r,matchUpFormat:n,categoryName:o,categoryType:i,tournamentId:s,eventType:a,eventId:c}){if(!Sr({matchUpFormat:n}))return{error:ka};let u=Object.keys(r).filter(m=>!s||m===s),p;return u.forEach(m=>{if(p)return;let d=r[m],l=c?nr({tournamentRecord:d,eventId:c})?.event:void 0;return p=Zc({tournamentRecord:d,matchUpFormat:n,categoryName:o,categoryType:i,eventType:a,event:l}),p?.averageMinutes||p?.recoveryMinutes}),{recoveryMinutes:p?.recoveryMinutes||t,averageMinutes:p?.averageMinutes||e,typeChangeRecoveryMinutes:p?.typeChangeRecoveryMinutes||p?.recoveryMinutes||t}}function Tu({scheduleCompletedMatchUps:t,containedStructureIds:e,tournamentRecords:r,periodLength:n=30,matchUps:o,rounds:i}){if(typeof r!="object")return{error:wt};if(!Array.isArray(i))return{error:et,info:Tn("rounds")};let s={},a=[],c=[];i.sort((f,g)=>(f.sortOrder??0)-(g.sortOrder??0)),e=e??Object.assign({},...Object.values(r).map(f=>zi({tournamentRecord:f}).containedStructures)),o||({matchUps:o}=nn({nextMatchUps:!0,tournamentRecords:r}));let u=0,p={},m={},d={};return{scheduledRoundsDetails:i.flatMap(f=>{let g=f.periodLength||n,I=[];e?.[f.structureId]?I.push(...e[f.structureId]):I.push(f.structureId);let h=o?ga({tournamentIds:[f.tournamentId],roundNumbers:[f.roundNumber],matchUpIds:f.matchUpIds,eventIds:[f.eventId],drawIds:[f.drawId],processContext:!0,structureIds:I,matchUps:o}).sort(mi):[],{segmentNumber:S,segmentsCount:T}=f.roundSegment||{};if(lt(S)&&gn(h?.length)&&gn(T)&&S>0&&S<=T&&T<h?.length&&!f.matchUpIds?.length){let E=h.length/T,U=E*(S-1);h=h.slice(U,U+E)}let A=r[f.tournamentId],P=nr({drawId:f.drawId,tournamentRecord:A}).event,y=[];for(let E of h){let U=E.matchUpFormat;U&&(s[U]||(s[U]=[],s[U].push(E)),y.push(U))}for(let E of y){let{eventType:U,category:M}=P??{},{categoryName:N,ageCategoryCode:C}=M??{},{typeChangeRecoveryMinutes:D,recoveryMinutes:O,averageMinutes:b,error:_}=Ep({categoryName:N??C,categoryType:M?.categoryType,tournamentId:f.tournamentId,eventId:f.eventId,tournamentRecords:r,matchUpFormat:E,eventType:U});if(_)return{error:_,round:f};let L=h.filter(w=>(t||!ie.includes(w.matchUpStatus))&&w.matchUpStatus!==Ut).map(le);L.forEach(w=>{d[w]={typeChangeRecoveryMinutes:D,recoveryMinutes:O,averageMinutes:b},p[w]=O,m[w]=b}),c.push(...L),u=Math.max(b||0,u);let F=`${b}|${g}`;return a.includes(F)||a.push(F),{roundPeriodLength:g,recoveryMinutes:O,averageMinutes:b,matchUpIds:L,hash:F}}}),greatestAverageMinutes:u,matchUpFormatCohorts:s,recoveryMinutesMap:p,averageMinutesMap:m,orderedMatchUpIds:c,minutesMap:d,...R}}function aP({schedulingProfile:t,venueIds:e,eventIds:r,drawIds:n}){let o=[],i=t?.map(a=>{let c=At(a?.scheduleDate);if(!c){o.push(`Invalid date: ${a?.scheduledDate}`);return}let u=(a?.venues||[]).map(p=>{let{rounds:m,venueId:d}=p;if(!e?.includes(d)){o.push(`Missing venueId: ${d}`);return}let f=m.filter(g=>{let I=r.includes(g.eventId)&&n.includes(g.drawId);return I||o.push(`Invalid eventId: ${g.eventId} or drawId: ${g.drawId}`),I});if(f.length)return{venueId:d,rounds:f}}).filter(Boolean);return u.length&&c&&{...a,venues:u}}).filter(Boolean),s=o.length;return{updatedSchedulingProfile:i,modifications:s,issues:o}}function Up({tournamentRecords:t,schedulingProfile:e}){if(!e)return{valid:!0};if(!Array.isArray(e))return{valid:!1,error:G};let{venueIds:r,tournamentsMap:n}=mG({tournamentRecords:t}),o,i,s=e.every(a=>{let{scheduleDate:c,venues:u}=a;return Pr(c)?u.every(p=>{let{venueId:m,rounds:d}=p;return typeof m!="string"?(i="venueId should be a string",!1):Array.isArray(d)?r.includes(m)?!!d.every(f=>{if(!f)return i="empty round",!1;let{roundSegment:g,tournamentId:I,structureId:h,roundNumber:S,eventId:T,drawId:A}=f,y=n?.[I]?.[T]?.[A]?.[h]?.includes(S);y||(i="Invalid rounds");let{segmentNumber:E,segmentsCount:U}=g||{},M=!g||lt(E)&&gn(U)&&E<=U;return M||(i="Invalid segment"),y&&M}):(o=Es,!1):(i="rounds should be an array",!1)}):!1});return!s&&!o&&(o=G),{valid:!!s,error:o,info:i}}function pG(t){let{tournamentRecord:e={},tournamentMap:r={},requireCourts:n}=t,o=[],i=[],s=[],a=[],c=(e?.venues||[]).map(({venueId:p,courts:m})=>(!n||m?.length)&&p),u=e?.tournamentId;return u&&(o.push(u),r[u]={},(e?.events||[]).forEach(m=>{let d=m.eventId;s.push(d),r[u][d]={},(m.drawDefinitions||[]).forEach(l=>{let f=l.drawId;a.push(f),r[u][d][f]={};let{structures:g}=Cn({drawDefinition:l});(g||[]).forEach(I=>{let h=I.structureId,{matchUps:S}=Pt({structure:I}),{roundMatchUps:T}=Xe({matchUps:S}),A=T&&Object.keys(T).map(P=>parseInt(P));r[u][d][f][h]=A,i.push(h),I.structures?.length&&I.structures.forEach(P=>{i.push(P.structureId),r[u][d][f][P.structureId]=A})})})})),{tournamentMap:r,tournamentIds:o,structureIds:i,venueIds:c,eventIds:s,drawIds:a}}function mG(t){let e=t?.tournamentRecords&&Object.values(t?.tournamentRecords)||[],r={},{venueIds:n,eventIds:o,drawIds:i,structureIds:s,tournamentIds:a}=e.reduce((c,u)=>{let{tournamentIds:p,tournamentMap:m,structureIds:d,venueIds:l,eventIds:f,drawIds:g}=pG({tournamentRecord:u});return l.forEach(I=>{c.venueIds.includes(I)||c.venueIds.push(I)}),c.tournamentIds.push(...p),c.structureIds.push(...d),c.eventIds.push(...f),c.drawIds.push(...g),Object.assign(r,m),c},{tournamentIds:[],structureIds:[],venueIds:[],eventIds:[],drawIds:[]});return{tournamentsMap:r,tournamentIds:a,structureIds:s,venueIds:n,eventIds:o,drawIds:i}}function cP({dates:t=[],extension:e}){if(!e)return!1;if(typeof e.value=="boolean"&&e.value)return!0;if(!t.length)return!1;let r=Ct(e.value)?e.value?.dates:void 0;if(Array.isArray(r))return r?.length?!!r.filter(o=>!t.length||t.includes(o)).length:!1}function uP({convertExtensions:t,ignoreDisabled:e,venue:r,court:n}){let o={...J(n,t,!0),venueId:r.venueId},{extension:i}=ut({name:Gn,element:n});if(e&&i){let s=Ct(i.value)?i.value?.dates:void 0,a=i?.value===!0?[]:o.dateAvailability.map(c=>{let u=c.date;if(!(!u||s.includes(u)))return c}).filter(Boolean);o.dateAvailability=a}return{inContextCourt:o}}function oo(t){let{convertExtensions:e,ignoreDisabled:r,venueIds:n=[],dates:o}=t,i=t.tournamentRecords||t.tournamentRecord&&{[t.tournamentRecord.tournamentId]:t.tournamentRecord}||{},s=[],a=[],c=[],u=[];return Object.keys(i).filter(m=>!t.tournamentId||m===t.tournamentId).forEach(m=>{let d=i[m];for(let l of d.venues??[])if(!(n.length&&!n.includes(l.venueId))){if(r){let{extension:f}=ut({name:Gn,element:l});if(f?.value)continue}s.includes(l.venueId)||(u.push(J(l,e,!0)),s.push(l.venueId));for(let f of l.courts??[])if(!a.includes(f.courtId)){if(r){let{extension:I}=ut({name:Gn,element:f});if(cP({extension:I,dates:o}))continue}let{inContextCourt:g}=uP({convertExtensions:e,ignoreDisabled:r,venue:l,court:f});c.push(g),a.push(f.courtId)}}}),{courts:c,venues:u,...R}}function dG({convertExtensions:t,tournamentRecord:e,ignoreDisabled:r,dates:n}){if(!e)return{error:wt};let o=J(e.venues??[],t).filter(s=>{if(!r)return s;let{extension:a}=ut({name:Gn,element:s});return!a?.value&&s}).filter(Boolean),i=o.reduce((s,a)=>{let c=(a?.courts||[]).filter(u=>{if(!r&&!n?.length)return u;let{extension:p}=ut({name:Gn,element:u});return cP({extension:p,dates:n})}).filter(Boolean).map(u=>{let{inContextCourt:p}=uP({convertExtensions:t,ignoreDisabled:r,venue:a,court:u});return p});return c.length?s.concat(c):s},[]);return{venues:o,courts:i}}function Pp({tournamentRecords:t,requireCourts:e,dates:r}){return typeof t!="object"||!Object.keys(t).length?{error:wt}:Object.keys(t).reduce((o,i)=>{let s=t[i],{venues:a}=dG({tournamentRecord:s,dates:r});return a?.forEach(c=>{let{venueId:u,courts:p}=c;(!e||p?.length)&&!o.venueIds.includes(u)&&(o.venues.push(c),o.venueIds.push(u))}),o},{venues:[],venueIds:[]})}function Ro({tournamentRecords:t,tournamentRecord:e}){if(typeof t!="object"||!Object.keys(t).length)return{error:wt};let{extension:r}=ut({element:e,name:ca,tournamentRecords:t,discover:!0}),n=r?.value||[];if(n.length){let{venueIds:o}=Pp({requireCourts:!0,tournamentRecords:t}),{eventIds:i,drawIds:s}=Yf({tournamentRecords:t}),{updatedSchedulingProfile:a,modifications:c,issues:u}=aP({schedulingProfile:n,venueIds:o,eventIds:i,drawIds:s});if(c){n=a;let p=Ic({tournamentRecords:t,tournamentRecord:e,schedulingProfile:n});return p.error?p:{schedulingProfile:n,modifications:c,issues:u}}}return{schedulingProfile:n,modifications:0}}function Ic({tournamentRecords:t,tournamentRecord:e,schedulingProfile:r}){let n=Up({tournamentRecords:t,schedulingProfile:r});return n.error?n:r?gt({tournamentRecords:t,discover:!0,extension:{name:ca,value:r}}):rr({element:e,name:ca,tournamentRecords:t,discover:!0})}function hc(t){let{tournamentRecord:e}=t,r=t.tournamentRecords||e&&{[e.tournamentId]:e}||{};if(!t.schedulingProfile){let{modifications:u,issues:p}=Ro({tournamentRecords:r,tournamentRecord:e});return{success:!u,modifications:u,issues:p}}let{venueIds:n}=Pp({tournamentRecords:r}),{eventIds:o,drawIds:i}=Yf({tournamentRecords:r}),{updatedSchedulingProfile:s,modifications:a,issues:c}=aP({schedulingProfile:t.schedulingProfile,venueIds:n,eventIds:o,drawIds:i});return a?{...Ic({schedulingProfile:s,tournamentRecords:r}),modifications:a,issues:c}:{...R,modifications:a,issues:c}}function OS(t){let{scheduleDates:e=[],tournamentRecords:r,periodLength:n=30}=t??{};if(typeof r!="object")return{error:wa};if(!Array.isArray(e))return{error:G};if(!e.every(Pr))return{error:ir};let i=[],s=0,a={},{schedulingProfile:c}=Ro({tournamentRecords:r});if(!c)return{issues:i,...R};let{matchUps:u}=nn({nextMatchUps:!0,tournamentRecords:r});for(let m of c){let{scheduleDate:d,venues:l=[]}=m;if(!e?.length||e.includes(d)){for(let f of l||[])if(f){let{rounds:g}=f,I=[],{orderedMatchUpIds:h,scheduledRoundsDetails:S}=Tu({tournamentRecords:r,periodLength:n,matchUps:u,rounds:g}),{matchUpDependencies:T}=xr({tournamentRecords:r,matchUps:u}),A=P=>{let y;return S?.find((E,U)=>{let M=E.matchUpIds.includes(P);return M&&(y=U),M}),y};if(h?.forEach((P,y)=>{let E=h.slice(y+1),U=Wt(E,T?.[P]?.matchUpIds||[]);U.length&&I.push({matchUpId:P,shouldBeAfter:U})}),I.length){s+=I.length;let P=I.map(({matchUpId:y,shouldBeAfter:E})=>{let U=A(y),M=mt(E.map(A));return a[d]||(a[d]={}),a[d][U]||(a[d][U]=[]),M.forEach(N=>{a[d][U].includes(N)||a[d][U].push(N)}),{matchUpId:y,matchUpRoundIndex:U,earlierRoundIndices:M,shouldBeAfter:E}});i.push(...P)}}}}let p={matchUpIdShouldBeAfter:Object.assign({},...i.map(m=>{let{matchUpId:d,shouldBeAfter:l,earlierRoundIndices:f}=m;return{[d]:{earlierRoundIndices:f,shouldBeAfter:l}}}))};return{issuesCount:s,profileIssues:p,roundIndexShouldBeAfter:a,...R}}function gi(t){let{tournamentRecords:e,requestType:r}=t,n=vt(t,[{[ye]:!0}]);if(n.error)return n;let o={};for(let i of Object.values(e)){let{extension:s}=ut({element:i,name:aa}),a=s?.value||[];for(let c of a){let{personId:u,requests:p}=c||{};o[u]||(o[u]=[]);for(let m of p)r&&m.requestType!==r||o[u].push(m)}}return{personRequests:o,...R}}var mP={};ne(mP,{getEntriesAndSeedsCount:()=>nd,getMaxEntryPosition:()=>_S});function _S(t){let{entries:e=[],entryStatus:r,stage:n}=t;return Math.max(...e.filter(o=>(!n||n===o.entryStage)&&(!r||o.entryStatus===r)&&!isNaN(o.entryPosition)).map(({entryPosition:o})=>ct(o||0)),0)}var hP={};ne(hP,{allCompetitionMatchUps:()=>nn,allDrawMatchUps:()=>ar,allEventMatchUps:()=>ro,allTournamentMatchUps:()=>pe,analyzeMatchUp:()=>Cp,calculateWinCriteria:()=>ps,checkMatchUpIsComplete:()=>es,competitionScheduleMatchUps:()=>Au,drawMatchUps:()=>jS,eventMatchUps:()=>Id,getAllDrawMatchUps:()=>re,getCheckedInParticipantIds:()=>Xi,getCompetitionMatchUps:()=>Np,getEventMatchUpFormatTiming:()=>LS,getMatchUpCompetitiveProfile:()=>Jc,getMatchUpContextIds:()=>VS,getMatchUpDailyLimits:()=>Sd,getMatchUpDailyLimitsUpdate:()=>FS,getMatchUpDependencies:()=>xr,getMatchUpFormat:()=>BS,getMatchUpFormatTiming:()=>Zc,getMatchUpFormatTimingUpdate:()=>xS,getMatchUpScheduleDetails:()=>bm,getMatchUpType:()=>xm,getMatchUpsStats:()=>HS,getModifiedMatchUpFormatTiming:()=>fd,getPredictiveAccuracy:()=>kS,getRoundMatchUps:()=>Xe,getRounds:()=>WS,isValidMatchUpFormat:()=>Sr,matchUpActions:()=>id,participantScheduledMatchUps:()=>GS,tallyParticipantResults:()=>Ua,tournamentMatchUps:()=>hd,validMatchUp:()=>cf,validMatchUps:()=>Ar});function vS({tournamentRecords:t,extensionName:e}){if(typeof t!="object"||!Object.keys(t).length)return{error:wt};let r=[],n;for(let o of Object.values(t)){let{extension:i}=ut({element:o,name:e});i&&!n&&(r.push({params:{extension:i,discover:!0},method:"addExtension"}),n=!0);let s=o.events??[];for(let a of s){let{eventId:c}=a,{extension:u}=ut({name:e,element:a});u&&r.push({params:{eventId:c,extension:u},method:"addEventExtension"})}}return{methods:r}}function xS({tournamentRecords:t}){return vS({extensionName:Po,tournamentRecords:t})}var dP="ADULT",lP="JUNIOR",wS="WHEELCHAIR",fP={[uo]:{allowModificationWhenMatchUpsScheduled:{courts:!1,venues:!1},defaultTimes:{averageTimes:[{categoryNames:[],minutes:{default:90}}],recoveryTimes:[{minutes:{[jt]:30,default:60}}]},defaultDailyLimits:{[ee]:2,[jt]:2,total:3},matchUpAverageTimes:[{matchUpFormatCodes:[on],averageTimes:[{categoryNames:[],minutes:{default:90}},{categoryTypes:[wS],minutes:{default:120}}]},{matchUpFormatCodes:["SET3-S:6/TB7-F:TB10"],averageTimes:[{categoryNames:[],minutes:{default:85}}]},{matchUpFormatCodes:["SET3-S:6/TB7-F:TB7"],averageTimes:[{categoryNames:[],minutes:{default:70}}]},{matchUpFormatCodes:["SET3-S:4NOAD-F:TB7"],averageTimes:[{categoryNames:[],minutes:{default:55}}]},{matchUpFormatCodes:["SET3-S:4/TB7"],averageTimes:[{categoryNames:[],minutes:{default:60}}]},{matchUpFormatCodes:["SET3-S:4/TB7-F:TB7"],averageTimes:[{categoryNames:[],minutes:{default:50}}]},{matchUpFormatCodes:["SET3-S:4/TB7-F:TB10"],averageTimes:[{categoryNames:[],minutes:{default:55}}]},{matchUpFormatCodes:["SET3-S:4/TB5@3"],averageTimes:[{categoryNames:[],minutes:{default:45}}]},{matchUpFormatCodes:["SET1-S:8/TB7","SET1-S:8/TB7@7"],averageTimes:[{categoryNames:[],minutes:{default:40}}]},{matchUpFormatCodes:["SET1-S:5/TB9@4"],averageTimes:[{categoryNames:[],minutes:{default:30}}]},{matchUpFormatCodes:["SET1-S:6/TB7"],averageTimes:[{categoryNames:[],minutes:{default:30}}]},{matchUpFormatCodes:["SET1-S:6NOAD"],averageTimes:[{categoryNames:[],minutes:{default:30}}]},{matchUpFormatCodes:["SET1-S:4/TB7","SET1-S:4/TB5@3","SET3-S:TB10","SET1-S:T20"],averageTimes:[{categoryNames:[],minutes:{default:20}}]},{matchUpFormatCodes:["SET1-S:4NOAD"],averageTimes:[{categoryNames:[],minutes:{default:20}}]},{matchUpFormatCodes:["SET1-S:TB10"],averageTimes:[{categoryNames:[],minutes:{default:10}}]}],matchUpRecoveryTimes:[{matchUpFormatCodes:["SET3-S:6/TB7","SET3-S:6/TB7-F:TB10","SET3-S:6/TB7-F:TB7"],recoveryTimes:[{categoryTypes:[dP,wS],minutes:{default:60,[jt]:30}},{categoryTypes:[lP],minutes:{default:60,[jt]:60}}]},{matchUpFormatCodes:["SET3-S:4/TB7-F:TB7","SET3-S:4/TB7-F:TB10","SET3-S:4NOAD-F:TB7","SET3-S:4/TB7","SET3-S:4/TB5@3"],recoveryTimes:[{categoryTypes:[dP,wS],minutes:{default:30}},{categoryTypes:[lP],minutes:{default:60}}]},{matchUpFormatCodes:["SET1-S:8/TB7","SET1-S:8/TB7@7","SET1-S:5/TB9@4","SET1-S:6/TB7","SET1-S:6NOAD","SET1-S:4/TB7","SET1-S:4NOAD","SET3-S:TB10","SET1-S:T20"],recoveryTimes:[{categoryNames:[],minutes:{default:30}}]},{matchUpFormatCodes:["SET1-S:4/TB5@3"],recoveryTimes:[{categoryTypes:[dP,lP],minutes:{default:30}},{categoryTypes:[wS],minutes:{default:15}}]},{matchUpFormatCodes:["SET1-S:TB10"],recoveryTimes:[{categoryNames:[],minutes:{default:15}}]}],matchUpDailyLimits:[]}},PO=fP;function LS({tournamentRecord:t,matchUpFormats:e,categoryType:r,event:n}){if(!n)return{error:St};let o=[],i;if(e?.length){let m=[];o=e.map(d=>{let l=typeof d=="string"?{matchUpFormat:d}:d;if(!m.includes(l?.matchUpFormat)&&Sr({matchUpFormat:l?.matchUpFormat}))return m.push(l.matchUpFormat),l}).filter(Boolean)}else{let{policy:m}=Bo({policyType:Mn,tournamentRecord:t,event:n});if(m?.matchUpFormats)o=m?.matchUpFormats;else{let{extension:d}=ut({name:Po,element:n}),l,f;d?.value?{matchUpAverageTimes:l,matchUpRecoveryTimes:f}=d.value:{matchUpAverageTimes:l,matchUpRecoveryTimes:f}=PO[uo],o=mt([...(l||[]).map(g=>g.matchUpFormatCodes),...(f||[]).map(g=>g.matchUpFormatCodes)].flat()).map(g=>({matchUpFormat:g})),i="default scheduling policy in use"}}let{eventType:s,eventId:a,category:c}=n,u=c?.categoryName??c?.ageCategoryCode??a;if(!a)return{error:St};let p=o.map(({matchUpFormat:m,description:d})=>{let l=Zc({tournamentRecord:t,matchUpFormat:m,categoryName:u,categoryType:r,eventType:s,event:n});return{matchUpFormat:m,description:d,...l}});return rt({eventMatchUpFormatTiming:p,info:i})}function fd(t){let e=vt(t,[{[Fn]:!0},{[Pi]:g=>Sr({matchUpFormat:g}),[Ni]:ka,[SC]:!0}]);if(e.error)return e;let{tournamentRecord:r,matchUpFormat:n,event:o}=t,{extension:i}=ut({name:Po,element:o}),s=i?.value,{extension:a}=ut({element:r,name:Po}),c=a?.value,u=s?.matchUpAverageTimes&&np({...s,matchUpFormat:n}),p=c?.matchUpAverageTimes&&np({...c,matchUpFormat:n}),m=[u,p].find(g=>g),d=s?.matchUpRecoveryTimes&&op({...s,matchUpFormat:n}),l=c?.matchUpRecoveryTimes&&op({...c,matchUpFormat:n}),f=[d,l].find(g=>g);return{matchUpFormat:n,recoveryTimes:f,averageTimes:m}}function FS({tournamentRecords:t}){return vS({extensionName:Gc,tournamentRecords:t})}var Da=({scheduleAttributes:t=["scheduledDate","scheduledTime"],schedule:e={}})=>!!Object.keys(e).filter(n=>t.includes(n)).filter(n=>e[n]).length;function GS({scheduleAttributes:t=["scheduledDate","scheduledTime"],matchUps:e=[]}){if(!Ar(e))return{error:wn};if(!Array.isArray(t))return{error:G};let r=e.filter(Boolean).filter(({schedule:o})=>Da({schedule:o,scheduleAttributes:t})).reduce((o,i)=>{let{schedule:s}=i,a=At(s?.scheduledDate),c=qt(s?.scheduledTime);return a&&c&&(o[a]?o[a].push(i):o[a]=[i]),o},{});return Object.keys(r).forEach(o=>{r[o].sort((i,s)=>SI(qt(i.schedule?.scheduledTime),qt(s.schedule?.scheduledTime)))}),{...R,scheduledMatchUps:r}}function NO({tournamentRecords:t}){let e=[],r={};for(let n of Object.values(t))for(let o of n.events??[]){let i=Qr({event:o}),s=i?.drawDetails;Ct(s)?(Object.assign(r,s),e.push(...Object.keys(s).filter(a=>Fm({drawId:a,drawDetails:s})))):i?.drawIds?.length&&e.push(...i.drawIds)}return{drawIds:e,detailsMap:r}}function gd({schedulingProfile:t,matchUps:e=[]}){let r={},n=({eventId:a,drawId:c,structureId:u,roundNumber:p})=>`${a}|${c}|${u}${p}`;t?.length&&t.map(({venues:c})=>c.map(({rounds:u})=>u)).flat().forEach(c=>{c.sort((p,m)=>(p.sortOrder||0)-(m.sortOrder||0)).forEach(({eventId:p,drawId:m,structureId:d,roundNumber:l},f)=>{let g=n({eventId:p,drawId:m,structureId:d,roundNumber:l});r[g]=f})});let o=[],i={noScheduledDate:[]};for(let a of e){let c=a.schedule||{},u=c.scheduledDate&&At(c.scheduledDate)||c.scheduledTime&&At(c.scheduledTime)||"noScheduledDate";i[u]||(i[u]=[]),i[u].push(a)}let s=Object.keys(i).sort();for(let a of s){let c=i[a],u={noScheduledTime:[]};for(let m of c){let d=m.schedule||{},l=d.scheduledTime&&qt(d.scheduledTime)||"noScheduledTime";u[l]||(u[l]=[]),u[l].push(m)}let p=Object.keys(u).sort();for(let m of p){let d=u[m];d.sort((l,f)=>{let g=r[n(l)]||0,I=r[n(f)]||0;return g-I}),o.push(...d)}}return o}function ig({courtPrefix:t="C|",minRowsCount:e,courtsData:r}){if(!Array.isArray(r))return{error:G};let n=r?.reduce((s,a)=>{let c=a.matchUps||[],u=Math.max(0,...c.map(p=>p.schedule.courtOrder||0));return u>s?u:s},1),o=e?Math.max(e,n):n,i=Z(0,o).map(s=>({matchUps:Z(0,r.length).map(a=>{let c=r[a],{courtId:u,venueId:p}=c;return{schedule:{courtOrder:s+1,venueId:p,courtId:u}}})}));return r.forEach((s,a)=>{for(let c of s.matchUps){let u=c.schedule?.courtOrder;u&&(i[u-1].matchUps[a]=c)}}),{courtPrefix:t,rows:i.map((s,a)=>Object.assign({rowId:`rowId-${a+1}`},...s.matchUps.map((c,u)=>({[`${t}${u}`]:c}))))}}function Id(t){let{participants:e,contextContent:r,participantMap:n}=t,{tournamentAppliedPolicies:o,scheduleVisibilityFilters:i,participantsProfile:s,afterRecoveryTimes:a,policyDefinitions:c,useParticipantMap:u,tournamentRecord:p,usePublishState:m,contextFilters:d,matchUpFilters:l,contextProfile:f,nextMatchUps:g,tournamentId:I,inContext:h,context:S,event:T}=t;if(!T)return{error:St};let{eventId:A,eventName:P,endDate:y}=T,E={...S,...rt({eventId:A,eventName:P,endDate:y??p?.endDate,tournamentId:I??p?.tournamentId,indoorOutDoor:T.indoorOutdoor??p?.indoorOutdoor,surfaceCategory:T.surfaceCategory??p?.surfaceCategory})},U;!e&&p&&({participants:e,participantMap:n,groupInfo:U}=pi({participantsProfile:s,policyDefinitions:c,useParticipantMap:u,tournamentRecord:p,contextProfile:f,inContext:h})),f&&!r&&(r=bn({policyDefinitions:c,tournamentRecord:p,contextProfile:f,event:T}));let M=Qr({event:T});return{...(T.drawDefinitions??[]).reduce((D,O)=>{let b=ws({context:E,tournamentAppliedPolicies:o,scheduleVisibilityFilters:i,tournamentParticipants:e,participantsProfile:s,afterRecoveryTimes:a,policyDefinitions:c,tournamentRecord:p,usePublishState:m,contextContent:r,contextFilters:d,matchUpFilters:l,participantMap:n,publishStatus:M,contextProfile:f,drawDefinition:O,nextMatchUps:g,inContext:h,event:T});return Object.keys(b)?.forEach(L=>{Array.isArray(b[L])&&(D[L]||(D[L]=[]),D[L]=D[L].concat(b[L]))}),D},{}),...R,groupInfo:U}}function hd(t){if(!t?.tournamentRecord)return{error:j};let e=t.contextContent,{scheduleVisibilityFilters:r,participantsProfile:n,afterRecoveryTimes:o,policyDefinitions:i,useParticipantMap:s,tournamentRecord:a,inContext:c=!0,usePublishState:u,contextFilters:p,matchUpFilters:m,contextProfile:d,nextMatchUps:l,context:f}=t,g=t.tournamentId??a.tournamentId,I=a?.events??[],{participants:h,participantMap:S,groupInfo:T}=pi({participantsProfile:n,policyDefinitions:i,useParticipantMap:s,tournamentRecord:a,contextProfile:d,inContext:c});d&&!e&&(e=bn({policyDefinitions:i,tournamentRecord:a,contextProfile:d}));let{appliedPolicies:A}=yt({tournamentRecord:a}),P=p?.eventIds??[];return{...I.filter(U=>!P.includes(U.eventId)).map(U=>{let N={eventDrawsCount:kt({event:U}).flightProfile?.flights?.length||U.drawDefinitions?.length||0,...f};return Id({context:N,tournamentAppliedPolicies:A,scheduleVisibilityFilters:r,participantsProfile:n,afterRecoveryTimes:o,policyDefinitions:i,tournamentRecord:a,usePublishState:u,contextFilters:p,contextProfile:d,contextContent:e,matchUpFilters:m,participantMap:S,participants:h,tournamentId:g,nextMatchUps:l,inContext:c,event:U})}).reduce((U,M)=>((M&&Object.keys(M).filter(C=>!["success","matchUpsMap"].includes(C)))?.forEach(C=>{Array.isArray(M[C])&&(U[C]||(U[C]=[]),U[C]=U[C].concat(M[C]),U.matchUpsCount+=M[C].length)}),U),{matchUpsCount:0}),groupInfo:T}}function Np({scheduleVisibilityFilters:t,participantsProfile:e,tournamentRecords:r,policyDefinitions:n,usePublishState:o,matchUpFilters:i,contextFilters:s,nextMatchUps:a,inContext:c}){if(typeof r!="object"||!Object.keys(r).length)return{error:wt};let p=Object.keys(r).map(l=>{let f=r[l];return hd({scheduleVisibilityFilters:t,participantsProfile:e,policyDefinitions:n,tournamentRecord:f,usePublishState:o,matchUpFilters:i,contextFilters:s,nextMatchUps:a,inContext:c})}),m={};return{...p.reduce((l,f)=>(Object.keys(f).forEach(I=>{Array.isArray(f[I])&&(l[I]||(l[I]=[]),l[I]=l[I].concat(f[I])),I==="groupInfo"&&Object.assign(m,f[I])}),l),{}),groupInfo:m}}function Au(t){if(typeof t?.tournamentRecords!="object"||!Object.keys(t?.tournamentRecords).length)return{error:wt};let{courts:e,venues:r}=oo(t),o=Ro(t).schedulingProfile,{sortDateMatchUps:i=!0,courtCompletedMatchUps:s,alwaysReturnCompleted:a,activeTournamentId:c,tournamentRecords:u,withCourtGridRows:p,minCourtGridRows:m,usePublishState:d,status:l=$r,sortCourtsData:f}=t,g=d?nu({tournamentRecord:u[c??Hi()],itemType:`${Ho}.${Wo}`}).timeItem?.itemValue?.[l]:void 0,I=a?Np({...t,matchUpFilters:{...t.matchUpFilters,matchUpStatuses:[me]},contextFilters:t.contextFilters}).completedMatchUps:[];if(d&&(!g||!Object.keys(g).length))return{completedMatchUps:I,dateMatchUps:[],courtsData:[],venues:r};let h,S;d&&({drawIds:h,detailsMap:S}=NO({tournamentRecords:u})),h?.length&&(t.contextFilters||(t.contextFilters={}),t.contextFilters?.drawIds?t.contextFilters.drawIds=t.contextFilters.drawIds.filter(D=>h.includes(D)):t.contextFilters.drawIds=h),g?.eventIds?.length&&(t.matchUpFilters||(t.matchUpFilters={}),t.matchUpFilters?.eventIds&&t.matchUpFilters.eventIds.length?t.matchUpFilters.eventIds=t.matchUpFilters.eventIds.filter(D=>g.eventIds.includes(D)):t.matchUpFilters.eventIds=g.eventIds),g?.scheduledDates?.length&&(t.matchUpFilters||(t.matchUpFilters={}),t.matchUpFilters.scheduledDates&&t.matchUpFilters.scheduledDates.length?t.matchUpFilters.scheduledDates=t.matchUpFilters.scheduledDates.filter(D=>g.scheduledDates.includes(D)):t.matchUpFilters.scheduledDates=g.scheduledDates),a&&(t.matchUpFilters||(t.matchUpFilters={}),t.matchUpFilters?.excludeMatchUpStatuses?.length?t.matchUpFilters.excludeMatchUpStatuses.includes(me)||t.matchUpFilters.excludeMatchUpStatuses.push(me):t.matchUpFilters.excludeMatchUpStatuses=[me]);let{completedMatchUps:T,upcomingMatchUps:A,pendingMatchUps:P,groupInfo:y}=Np({...t,matchUpFilters:t.matchUpFilters,contextFilters:t.contextFilters}),E=[...A??[],...P??[]];S&&Object.keys(S).length&&(E=E.filter(D=>{let{drawId:O,structureId:b,stage:_}=D;if(!S[O])return!1;if(S[O].stageDetails){let L=Object.keys(S[O].stageDetails),F=L.filter(x=>!S[O].stageDetails[x].published),w=L.filter(x=>S[O].stageDetails[x].published);return F.length&&F.includes(_)?!1:w.length&&w.includes(_)?!0:F.length&&!F.includes(_)&&!w.length}if(S[O].structureDetails){let L=Object.keys(S[O].structureDetails),F=L.filter(x=>!S[O].structureDetails[x].published),w=L.filter(x=>S[O].structureDetails[x].published);return F.length&&F.includes(b)?!1:w.length&&w.includes(b)?!0:F.length&&!F.includes(b)&&!w.length}return!0}));let U=i?gd({matchUps:E,schedulingProfile:o}):E,M=e?.map(D=>{let O=C(D);return{surfaceCategory:D?.surfaceCategory??"",matchUps:O,...D}}),N={completedMatchUps:a?I:T,dateMatchUps:U,courtsData:M,groupInfo:y,venues:r};if(p){let{rows:D,courtPrefix:O}=ig({minRowsCount:m,courtsData:M});N.courtPrefix=O,N.rows=D}return{...N,...R};function C({courtId:D}){let b=(s?U.concat(T??[]):U).filter(_=>_.schedule?.courtId===D||_.schedule?.allocatedCourts?.map(({courtId:L})=>L).includes(D));return f?gd({matchUps:b,schedulingProfile:o}):b}}function Sd({tournamentRecords:t,tournamentId:e}){if(typeof t!="object"||!Object.keys(t).length)return{error:wt};let r=Object.keys(t).filter(o=>!e||o===e),n;return r.forEach(o=>{let i=t[o],{matchUpDailyLimits:s}=lG({tournamentRecord:i});n=s}),{matchUpDailyLimits:n}}function lG(t){let e=vt(t,[{[Fn]:!0}]);if(e.error)return e;let{tournamentRecord:r}=t,{policy:n}=Bo({policyType:uo,tournamentRecord:r}),{extension:o}=ut({element:r,name:Gc}),i=o?.value?.dailyLimits,s=n?.defaultDailyLimits;return{matchUpDailyLimits:i||s}}function kS(t){let{matchUps:e}=t,{singlesForDoubles:r,tournamentRecord:n,drawDefinition:o,excludeMargin:i,exclusionRule:s,zoneDoubling:a,matchUpType:c,scaleName:u,eventId:p,zonePct:m,drawId:d,event:l}=t;if(!n&&!e)return{error:j};if(c&&![ee,jt].includes(c))return{error:G,info:{matchUpType:c}};if(e&&!Ar(e))return{error:G,context:{matchUps:e}};let f=Jr[u],g=f?.ascending??t.ascending??!1,I=f?.accessor??t.valueAccessor,h=Array.isArray(f?.range)?Math.abs(f.range[0]-f.range[1]):0,S=lt(m)&&h?(m??0/100)*h:t.zoneMargin??h,T={withScaleValues:!0,withCompetitiveness:!0},A={matchUpTypes:c?[c]:[ee,jt]},P=n?.participants;e?.[0]?.hasContext?d?e=e.filter(b=>b.drawId===d):p&&(e=e.filter(b=>b.eventId===p)):e===void 0&&(e=d&&!o&&[]||!d&&p&&!l&&[]||d&&ar({inContext:!0,drawDefinition:o,contextFilters:A,contextProfile:T,participants:P})?.matchUps||!d&&p&&ro({inContext:!0,contextFilters:A,contextProfile:T,participants:P,event:l})?.matchUps||pe({tournamentRecord:n,contextFilters:A,contextProfile:T})?.matchUps||[]),c&&(e=e.filter(b=>b.matchUpType===c));let y=e.filter(({winningSide:b,score:_,sides:L,matchUpStatus:F})=>![mr,bt,Ot,Vc,kr].includes(F??"")&&he({score:_})&&L?.length===2&&b),E=gG({matchUps:y,excludeMargin:i,exclusionRule:s,valueAccessor:I,ascending:g,scaleName:u}),U=!a||c===ee?S:(S||0)*2,M=S?y.map(({competitiveProfile:b,matchUpType:_,score:L,sides:F})=>{let w=MO({singlesForDoubles:r,valueAccessor:I,matchUpType:_,scaleName:u,sides:F}),x=Math.abs(w[0].value-w[1].value);return{competitiveness:b?.competitiveness,valuesGap:x,score:L}}).filter(({valuesGap:b})=>b<=U):[],N=fG({zoneData:M}),C=N&&[].concat(Object.values(N)).flat().length,D=C&&Object.assign({},...Object.keys(N).map(b=>({[b]:Math.round(1e4*N[b].length/C)/100}))),O=y.length-(M?.length||0);return{...R,relevantMatchUps:y,zoneDistribution:D,zoneData:M,accuracy:E,nonZone:O}}function fG({zoneData:t}){let e={[Nm]:[],[Za]:[],[tc]:[]};for(let r of t){let{competitiveness:n,score:o,valuesGap:i}=r;e[n]&&e[n].push({score:o,valuesGap:i})}return e}function MO({singlesForDoubles:t,exclusionRule:e,valueAccessor:r,matchUpType:n,scaleName:o,sides:i}){let s=e?.range.sort(),a=c=>{let u=c?.[e?.valueAccessor];return{exclude:e&&u>=s[0]&&u<=s[1],exclusionValue:u}};return i.sort((c,u)=>c.sideNumber-u.sideNumber).map(({participant:c})=>{let u=[],p=c?.individualParticipants;if(p?.length){let m=[],d=0;for(let l of p){let{scaleValue:f,value:g}=DO({singlesForDoubles:t,valueAccessor:r,participant:l,matchUpType:n,scaleName:o}),{exclude:I,exclusionValue:h}=a(f);I&&u.push(h),m.push(f),g&&!isNaN(d)?d+=g:d=void 0}return{participantName:c.participantName,exclusionValues:u,scaleValues:m,value:d}}else if(c){let{scaleValue:m,value:d}=DO({singlesForDoubles:t,valueAccessor:r,matchUpType:n,participant:c,scaleName:o}),{exclude:l,exclusionValue:f}=a(m);return l&&u.push(f),{participantName:c.participantName,exclusionValues:u,scaleValue:m,value:d}}else return{}})}function DO({singlesForDoubles:t,valueAccessor:e,matchUpType:r,participant:n,scaleName:o}){let i=t?ee:r,s=n?.rankings?.[i]?.find(p=>p.scaleName===o),c=(n?.ratings?.[i]?.find(p=>p.scaleName===o)||s)?.scaleValue,u=e?c?.[e]:c;return{scaleValue:c,value:u}}function gG({excludeMargin:t,exclusionRule:e,valueAccessor:r,ascending:n,scaleName:o,matchUps:i}){let s={affirmative:[],negative:[],excluded:[]};for(let u of i){let{matchUpType:p,sides:m,score:d,winningSide:l}=u;if(!l)continue;if(e&&(!e.valueAccessor||!e.range))return{info:"exclusionRule requires valueAccessor and range",error:et};let f=l-1,g=MO({exclusionRule:e,valueAccessor:r,matchUpType:p,scaleName:o,sides:m});if(e){let P=g.map(({exclusionValues:y})=>y).flat();if(P.length){s.excluded.push({scoreString:d?.scoreStringSide1,exclusionValues:P,winningSide:l,sideValues:g});continue}}if(g.filter(P=>![void 0,"",null].includes(P.value)).length<2){s.excluded.push({scoreString:d?.scoreStringSide1,missingValues:!0,winningSide:l,sideValues:g});continue}let I=g[f].value-g[1-f].value,h=parseFloat(t||0),S=h&&Math.abs(I)<h;if(S){s.excluded.push({scoreString:d?.scoreStringSide1,excludeMargin:t,winningSide:l,excludeGap:S,sideValues:g,valuesGap:I});continue}let T=n?I:I*-1,A=l===1?d?.scoreStringSide1:d?.scoreStringSide2;T>0?s.affirmative.push({winningScoreString:A,winningSide:l,sideValues:g,valuesGap:I,score:d}):s.negative.push({winningScoreString:A,winningSide:l,sideValues:g,valuesGap:I,score:d})}let a=s.affirmative.length+s.negative.length,c=a&&s.affirmative.length/a*100;return s.percent=c?Math.round(100*c)/100:0,s}function ps({collectionDefinitions:t=[],collectionGroups:e=[]}){let r=0,{groupValueNumbers:n}=qh({collectionGroups:e}),o;for(let s of t||[]){let{collectionValueProfiles:a,collectionGroupNumber:c,collectionValue:u,matchUpCount:p,matchUpValue:m,scoreValue:d,setValue:l}=s,f=c&&n.includes(c);if(lt(l||d))o=!0;else{if(f)continue;if(typeof u=="number"&&lt(u))r+=u;else if(a?.length)for(let g of a)r+=g.matchUpValue;else typeof m=="number"&&lt(m)&&(r+=(p??0)*m)}}for(let s of e)r+=s.groupValue??0;return o||!r?{aggregateValue:!0,...R}:{valueGoal:Math.floor(r/2)+1,...R}}function VS({matchUps:t,matchUpId:e}){if(!Ar(t))return{error:G};let r=t.find(a=>a.matchUpId===e),{drawId:n,eventId:o,structureId:i,tournamentId:s}=r||{};return{matchUpId:e,drawId:n,eventId:o,structureId:i,tournamentId:s}}function Ma(t,e){if(!Ct(t))return{error:G};if(!Array.isArray(e))return{error:G};let r={};for(let{param:n,error:o,attr:i}of e){let s=IG({params:t,param:n,attr:i,error:o});if(s?.error)return s;r[n]=s}return r}function IG({params:t,param:e,attr:r,error:n}){if(e===Gl&&Ct(t.drawDefinition)&&er(t.structureId)){let o=(t.drawDefinition.structures??[]).find(({structureId:i})=>i===t.structureId);return!o.length&&n?{error:n}:{structure:o}}if(e===co){let o=iP({...t,...r});return o.error&&n?{...o,error:n}:o}return{error:je,info:{param:e}}}function BS(t){let{structureId:e,matchUpId:r,event:n}=t,o=t.drawDefinition,i=vt(t,[{[Fn]:!0},{[MC]:{[EI]:!1,[ji]:!1,[DI]:!1,[$a]:!1}}]);if(i[Ns])return i;let a=Ma(t,[{[ra]:co,[Ns]:et}])?.matchUp;if(r&&a?.error)return a;!o&&a?.drawDefinition&&(o=a?.drawDefinition);let c=a?.structure;if(!c&&e&&!r){if(!o)return{error:Ur};let l=st({drawDefinition:o,structureId:e});if(l.error)return l;c=l.structure}let u=c?.matchUpFormat,p=o?.matchUpFormat,m=n?.matchUpFormat,d=a?.matchUp?.matchUpFormat||u||p||m;return{structureDefaultMatchUpFormat:u,eventDefaultMatchUpFormat:m,drawDefaultMatchUpFormat:p,matchUpFormat:d}}function HS({profileBands:t,tournamentRecord:e,matchUps:r}){if(!Ar(r))return{error:wn};let n=!t&&Bo({policyType:ti,tournamentRecord:e}).policy,o=t||n?.profileBands||Mm[ti].profileBands,i=r.filter(({winningSide:d})=>d),s=i.map(XI),a=(d,l)=>{let f=QI(l,o);return d[f]+=1,d},c=JI(s).reduce((d,l)=>a(d,l),{[Nm]:0,[Za]:0,[tc]:0,[zI]:0}),u=Object.keys(c).reduce((d,l)=>(c[l]||0)+d,0),p=Object.keys(c).map(d=>{let l=parseFloat((c[d]/u).toFixed(4));return{[d]:l*100}}),m=i.filter(({matchUpStatus:d})=>d===xE).length;return p.push({[xE]:parseFloat((m/u).toFixed(4))*100}),{competitiveBands:Object.assign({},...p),...R}}function sg(t){let{containerStructureId:e,roundSegment:r,isRoundRobin:n,tournamentId:o,roundNumber:i,structureId:s,eventId:a,drawId:c}=t,u=n?e:s,p=[o,a,c,u,i].join("|");return rt({structureId:u,roundSegment:r,tournamentId:o,roundNumber:i,eventId:a,drawId:c,id:p})}function gP({round:t,matchUps:e,events:r,tournamentRecords:n}){let o=r.find(d=>d.eventId===t.eventId),{eventType:i,category:s,categoryType:a}=o||{},{categoryName:c,ageCategoryCode:u}=s||{},p=pr(e.map(({matchUpFormat:d})=>d)),m=0;return Object.keys(p).forEach(d=>{let l=p[d],f=Ep({categoryName:c||u,tournamentId:t.tournamentId,eventId:t.eventId,tournamentRecords:n,matchUpFormat:d,categoryType:a,eventType:i});if(f.error)return f;let g=f.averageMinutes*l;isNaN(m)||(m+=g)}),{roundMinutes:m}}function CO(t){return(t||[]).reduce((e,r)=>{let n=(r.finishingPositionRange?.winner||[]).reduce((i,s)=>i+s,0),o=(r.finishingPositionRange?.winner||[]).join("-")||"";return!e.minFinishingSum||n<e.minFinishingSum?{minFinishingSum:n,winnerFinishingPositionRange:o}:e},{minFinishingSum:0,winnerFinishingPositionRange:""})}function IP(t){let e=t.length,r=t.filter(({sides:p})=>p?.some(({bye:m})=>m)).length||0,n=t.filter(({winningSide:p,matchUpStatus:m})=>p||ie.includes(m)).length||0,o=t.filter(({schedule:p,matchUpStatus:m})=>p?.scheduledDate&&p?.scheduledTime&&m!==Ut).length||0,i=e-r,s=i===n,a=i-o,c=i-o;return{unscheduledCount:a,incompleteCount:c,scheduledCount:o,completedCount:n,matchUpsCount:e,isScheduled:i===o,isComplete:s,byeCount:r}}function ag({tournamentRecords:t,schedulingProfile:e,tournamentRecord:r,withRoundId:n}){if(r&&!t){if(typeof r!="object")return{error:wa};t={[r.tournamentId]:r}}if(e){let s=Up({tournamentRecords:t,schedulingProfile:e});if(s.error)return s}if(!e&&t){let s=Ro({tournamentRecords:t});if(s.error)return s;e=s.schedulingProfile}if(!e)return{error:je};let o={};return{profileRounds:e.map(({venues:s,scheduleDate:a})=>s.map(({rounds:c})=>c.map(u=>{let p=sg(u);return p.roundSegment?.segmentsCount&&(o[p.id]=p.roundSegment.segmentsCount),rt({id:n?p.id:void 0,scheduleDate:a,...p})}))).flat(1/0),segmentedRounds:o}}var{stageOrder:RO}=FC;function bO(t,e){return t.eventName.localeCompare(e.eventName)||t.eventId.localeCompare(e.eventId)||(RO[t?.stage]||0)-(RO[e?.stage]||0)||e.matchUpsCount-t.matchUpsCount||`${t.stageSequence}-${t.roundNumber}-${t.minFinishingSum}`.localeCompare(`${e.stageSequence}-${e.roundNumber}-${e.minFinishingSum}`)}function WS({excludeScheduleDateProfileRounds:t,excludeScheduledRounds:e,excludeCompletedRounds:r,inContextMatchUps:n,tournamentRecords:o,schedulingProfile:i,tournamentRecord:s,withSplitRounds:a,matchUpFilters:c,scheduleDate:u,withRoundId:p,venueId:m,context:d}){if(n&&!Array.isArray(n||typeof n[0]!="object"))return{error:G,inContextMatchUps:n};if(s&&!o){if(typeof s!="object")return{error:wa};o={[s.tournamentId]:s}}let l=typeof o!="object"||!Object.keys(o).length;if((m||u||!n||!i&&(t||r||i||a))&&l)return{error:wt};let g=Object.assign({},...Object.values(o??{}).map(({venues:E=[],tournamentId:U})=>({[U]:E?.map(({venueId:M})=>M)}))),I=Object.values(o??{}).map(({events:E=[],tournamentId:U,startDate:M,endDate:N})=>E.map(C=>({...C,validVenueIds:g[U],startDate:C.startDate??M,endDate:C.endDate??N}))).flat(),{segmentedRounds:h,profileRounds:S}=o&&(t||r||i||a)&&ag({tournamentRecords:o,schedulingProfile:i})||{},T=t&&Object.assign({},...S.map(E=>({[E.id]:E}))),A=n||o&&nn({tournamentRecords:o,matchUpFilters:c})?.matchUps||[],P=[],y=A&&Object.values(A.reduce((E,U)=>{let M=sg(U).id,N=h?.[M],C=[...E[M]?.matchUps??[],U],{containerStructureId:D,stageSequence:O,structureName:b,tournamentId:_,isRoundRobin:L,matchUpType:F,roundNumber:w,roundOffset:x,structureId:H,eventName:V,roundName:W,drawName:B,eventId:q,drawId:Y}=U,k=L?D:H;return{...E,[M]:{id:p?M:void 0,structureId:k,stageSequence:O,segmentsCount:N,structureName:b,tournamentId:_,matchUpType:F,roundNumber:w,roundOffset:x,eventName:V,roundName:W,drawName:B,matchUps:C,eventId:q,drawId:Y}}},{})).map(E=>{let{minFinishingSum:U,winnerFinishingPositionRange:M}=CO(E.matchUps),N=E.segmentsCount;if(N){let w=E.matchUps.length/N;return Ae(E.matchUps.sort((H,V)=>H.roundPosition-V.roundPosition),w).map((H,V)=>{let{unscheduledCount:W,incompleteCount:B,matchUpsCount:q,isScheduled:Y,isComplete:k,byeCount:K}=IP(H),X=gP({matchUps:E.matchUps,tournamentRecords:o,events:I,round:E});return rt({...E,...d,roundSegment:{segmentsCount:N,segmentNumber:V+1},winnerFinishingPositionRange:M,unscheduledCount:W,incompleteCount:B,minFinishingSum:U,matchUpsCount:q,isScheduled:Y,roundTiming:X,isComplete:k,byeCount:K,matchUps:H})})}let{unscheduledCount:C,incompleteCount:D,matchUpsCount:O,isScheduled:b,isComplete:_,byeCount:L}=IP(E.matchUps),F=gP({matchUps:E.matchUps,tournamentRecords:o,events:I,round:E});return rt({...E,...d,winnerFinishingPositionRange:M,unscheduledCount:C,incompleteCount:D,minFinishingSum:U,matchUpsCount:O,isScheduled:b,roundTiming:F,isComplete:_,byeCount:L})}).flat().filter(E=>{if(t){let H=At(t),V=p?E.id:sg(E).id;if(H&&T[V]&&At(T[V].scheduleDate)===H)return!1}let{isComplete:U,isScheduled:M}=E,N=!r||!U,C=!e||!M,D=m||u?I?.find(({eventId:H})=>H===E.eventId):void 0,O=D?.startDate??s?.startDate,b=D?.endDate??s?.endDate,_=!u||!O||new Date(u)>=new Date(O),L=!u||!b||new Date(u)<=new Date(b),F=_&&L,w=!m||D?.validVenueIds.includes(m),x=N&&C&&w&&F;return x||P.push(E),x}).sort(bO)||[];return{...R,rounds:y,excludedRounds:P}}function Td({ignoreTiebreak:t=!1,matchUpScoringFormat:e,matchUpFormat:r,isTiebreakSet:n,isDecidingSet:o,set:i}){if(!i)return{error:et,info:"missing set"};e=e||r&&Ze(r);let s=o&&e.finalSetFormat||e?.setFormat||{},{side1Score:a,side2Score:c}=i,{setTo:u,tiebreakAt:p}=s,m=Dp({set:i}),d=Math.abs(a-c),l=a>=u||c>=u,f=n||a>=u&&c>=u||p&&p<u&&(a===p||c===p),g=t||f&&(m===1&&i.side1TiebreakScore>i.side2TiebreakScore||m===2&&i.side2TiebreakScore>i.side1TiebreakScore),I=!f&&s.NoAD||f||n&&s.tiebreakFormat?.NoAD?1:2,h=d>=I;return!!((l&&(h||f)||n)&&(!f||g))}function Dp({set:t}){if(t.side1Score||t.side2Score){if(t.side1Score>t.side2Score)return 1;if(t.side2Score>t.side1Score)return 2}else if(t.side1TiebreakScore||t.side2TiebreakScore){if(t.side1TiebreakScore>t.side2TiebreakScore)return 1;if(t.side2TiebreakScore>t.side1TiebreakScore)return 2}}function OO({matchUpScoringFormat:t,isDecidingSet:e,isTiebreakSet:r,setObject:n}){if(!n)return;let o=Dp({set:n});return Td({matchUpScoringFormat:t,set:n,isDecidingSet:e,isTiebreakSet:r})&&o||void 0}function Mp(t){let{setObject:e,matchUpScoringFormat:r}=t;if(!e)return{error:sl};let{setNumber:n}=e||{},{bestOf:o}=r||{},i=!!(n&&o&&n===o),s=i&&r?.finalSetFormat||r?.setFormat,a=!!s?.tiebreakSet,c=!!s?.timed,u=!a&&!c,p=!!(n&&o&&n<=o),m=[e?.side1Score,e?.side2Score],d=[e?.side1PointScore,e?.side2PointScore],l=[e?.side1TiebreakScore,e?.side2TiebreakScore],f=m.filter(L=>L!==void 0).length,g=d.filter(L=>L!==void 0).length,I=l.filter(L=>L!==void 0).length,h=m?.filter(L=>!isNaN(L)).length,S=l?.filter(L=>!isNaN(L)).length,{tiebreakAt:T}=s||{},A=T&&m.filter(L=>L>=T).length===2,P=A&&(m[0]>m[1]&&1||m[1]>m[0]&&2||void 0),y=!!(S&&!h),E=!!e?.winningSide,{error:U,result:M}=hG({setObject:e,setFormat:s,sideGameScores:m,sideTiebreakScores:l}),{error:N,result:C}=SG({setObject:e,setFormat:s,sideTiebreakScores:l}),D=u&&!y&&M||a&&y&&C,O=p&&!(a&&!y)&&!(u&&y)&&(!E||D),b=OO({isDecidingSet:i,isTiebreakSet:y,matchUpScoringFormat:r,setObject:e}),_={expectTiebreakSet:a,expectTimedSet:c,hasTiebreakCondition:A,isCompletedSet:E,isDecidingSet:i,isTiebreakSet:y,isValidSet:O,isValidSetNumber:p,isValidSetOutcome:D,leadingSide:P,setFormat:s,sideGameScores:m,sideGameScoresCount:f,sidePointScores:d,sidePointScoresCount:g,sideTiebreakScores:l,sideTiebreakScoresCount:I,winningSide:b};return e?.winningSide!==void 0&&(y?(_.isValidTiebreakSetOutcome=C,C||(_.tiebreakSetError=N)):(_.isValidStandardSetOutcome=M,M||(_.standardSetError=U))),_}function hG({setObject:t,setFormat:e,sideGameScores:r,sideTiebreakScores:n}){if(!t)return{result:!1,error:sl};let o=!!e?.tiebreakSet,i=!!e?.timed;if(!e||o||i)return{result:!1,error:G};if(!(r?.filter(C=>!isNaN(C)).length===2))return{result:!1,error:eI};let{setTo:a,tiebreakAt:c,tiebreakFormat:u,NoAD:p}=e||{};if(!!!(a&&r?.find(C=>C>=a)))return{result:!1,error:eI};let d=[1,2].includes(t?.winningSide);if(!t||!d)return{result:!1,error:rI};let l=t?.winningSide-1,f=1-l,g=r[l],I=r[f],h=g-I;if(!(g>I))return{result:!1,error:{message:"winningSide game scoreString is not high"}};let T=c&&u,A=n?.filter(C=>!isNaN(C)).length===2,P=n?.[l],y=n?.[f],E=c&&r.filter(C=>C>=c).length===2;if(T){let{NoAD:C,tiebreakTo:D}=u;if(E){if(h>1)return{result:!1,error:{message:"invalid winning game scoreString (5)"}};if(!A)return{result:!1,error:{message:"invalid tiebreak scores (1)"}};if(isNaN(D))return{result:!1,error:{message:"tiebreakTo error"}};if(!!!(D&&n?.find(H=>H>=D)))return{result:!1,error:{message:"invalid tiebreak scores (2)"}};let _=c<a?a:a+1;if(g>_)return{result:!1,error:{message:"invalid winning game scoreString (1)"}};if(!P||!y||P<y)return{result:!1,error:{message:"winningSide tiebreak value is not high"}};let L=C?1:2,F=P-y,w=y>=D-1;if(F&&w&&F<L)return{result:!1,error:{message:"invalid tiebreak scores (3)"}}}if(g>a&&!E)return{result:!1,error:{message:"invalid winning game scoreString (2)"}}}let U=p?1:2,M=I>=a-1;return h&&M&&!E&&h<U?{result:!1,error:{message:"invalid winning game scoreString (3)"}}:h>U&&g>a?{result:!1,error:{message:"invalid winning game scoreString (4)"}}:{result:!0}}function SG({setObject:t,setFormat:e,sideTiebreakScores:r}){if(!t)return{result:!1,error:sl};let n=!!e?.tiebreakSet,o=!!e?.timed;if(!e||!n||o)return{result:!1,error:{message:"not tiebreak set"}};let i=[1,2].includes(t?.winningSide);if(!t||!i)return{result:!1,error:rI};let{tiebreakSet:s}=e||{},{NoAD:a,tiebreakTo:c}=s||{};if(!(r?.filter(T=>!isNaN(T)).length===2))return{result:!1,error:{message:"invalid tiebreak scores (1)"}};if(isNaN(c))return{result:!1,error:{message:"tiebreakTo error"}};if(!!!r?.find(T=>T>=c))return{result:!1,error:{message:"invalid tiebreak scores (2)"}};let m=t?.winningSide-1,d=1-m,l=r[m],f=r[d];if(!l||!f||l<f)return{result:!1,error:{message:"winningSide tiebreak value is not high"}};let g=a?1:2,I=l-f,h=f>=c-1;return I&&h&&I<g?{result:!1,error:{message:"invalid tiebreak scores (3)"}}:{result:!0}}function Cp(t){let{matchUp:e,sideNumber:r,setNumber:n,isTiebreakValue:o,isPointValue:i}=t||{},{matchUpFormat:s}=t||{};if(!e)return{error:or};s=s||e?.matchUpFormat;let a=Ze(s),c=!!e?.winningSide,u=e.score?.sets,p=u?.length,m=n&&n-1,d=!!u?.find((Y,k)=>Y.setNumber===n&&k===m),l=u?.filter(Y=>Y?.winningSide)||[],f=l?.length||0,g=n&&u?.slice(n)||[],I=!!(p&&n&&g?.reduce((Y,k)=>(!k||!k.side1Score&&!k.side2Score&&!k.side1TiebreakScore&&!k.side2TiebreakScore&&!k.side1PointScore&&!k.side2PointScore)&&Y,!0)),h=n<=p&&u.find(Y=>Y.setNumber===n),S=h&&Mp({setObject:h,matchUpScoringFormat:a}),{isCompletedSet:T,sideGameScores:A,sideTiebreakScores:P}=S||{},y=!!(h&&!T&&I||n&&n===p+1&&!c),E=[1,2].includes(r),U=E?r-1:0,M=h&&E&&(!o&&!i&&A[U]!==void 0&&A[U]||o&&P[U]!==void 0&&P[U]),N=!!M,C=l?.map(Y=>Mp({setObject:Y,matchUpScoringFormat:a}).isValidSetOutcome).reduce((Y,k)=>Y&&k,!0),D=l.reduce((Y,k)=>{let{winningSide:K}=k,X=K-1;return Y[X]++,Y},[0,0]),O=e?.winningSide,b=O&&O-1,_=1-b,L=D[b],F=D[_],w=Math.max(...D),x=pr(D)[w],{bestOf:H}=a??{},V=H&&Math.ceil(H/2)||1,W=w===V&&x===1&&D.indexOf(w)+1||void 0,B=L>F&&O===W;return{completedSetsHaveValidOutcomes:C,validMatchUpWinningSide:B,calculatedWinningSide:W,matchUpScoringFormat:a,validMatchUpOutcome:W&&C&&B,isLastSetWithValues:I,completedSetsCount:f,isCompletedMatchUp:c,isValidSideNumber:E,hasExistingValue:N,existingValue:M,isExistingSet:d,isActiveSet:y,...S}}function jS({participants:t,tournamentAppliedPolicies:e,scheduleVisibilityFilters:r,participantsProfile:n,afterRecoveryTimes:o,policyDefinitions:i,useParticipantMap:s,tournamentRecord:a,usePublishState:c,contextFilters:u,contextContent:p,matchUpFilters:m,participantMap:d,publishStatus:l,contextProfile:f,drawDefinition:g,nextMatchUps:I,tournamentId:h,inContext:S,context:T,event:A}){let{eventId:P,eventName:y,endDate:E}=A??{},U={...T,...rt({eventId:P,eventName:y,endDate:E??A?.endDate??a?.endDate,tournamentId:h??a?.tournamentId,indoorOutDoor:A?.indoorOutdoor??a?.indoorOutdoor,surfaceCategory:A?.surfaceCategory??a?.surfaceCategory})},M;return!t?.length&&a&&({participants:t,participantMap:d,groupInfo:M}=pi({participantsProfile:n,policyDefinitions:i,useParticipantMap:s,tournamentRecord:a,contextProfile:f,inContext:S})),A&&f&&!p&&(p=bn({policyDefinitions:i,tournamentRecord:a,contextProfile:f,drawDefinition:g,event:A})),{...ws({context:U,tournamentAppliedPolicies:e,scheduleVisibilityFilters:r,tournamentParticipants:t,participantsProfile:n,afterRecoveryTimes:o,policyDefinitions:i,tournamentRecord:a,usePublishState:c,participantMap:d,contextContent:p,contextFilters:u,matchUpFilters:m,publishStatus:l,contextProfile:f,drawDefinition:g,nextMatchUps:I,inContext:S,event:A}),groupInfo:M}}var SP={};ne(SP,{getCompetitionVenues:()=>Pp,getCourts:()=>YS,getVenuesAndCourts:()=>oo,publicFindVenue:()=>uh});function YS({tournamentRecord:t,venueId:e,venueIds:r}){return t?{courts:(t.venues||[]).filter(o=>e?o.venueId===e:r?r.includes(o.venueId):!0).map(o=>{let{venueId:i}=o,s=J(o.courts||[]);return s.forEach(a=>Object.assign(a,{venueId:i})),s}).flat()}:{error:j}}var TP={};ne(TP,{bulkUpdatePublishedEventIds:()=>Rp,categoryCanContain:()=>Zm,getCategoryAgeDetails:()=>mu,getEvent:()=>KS,getEventProperties:()=>qS,getEventStructures:()=>Gf,getEventTimeItem:()=>ru,getEvents:()=>$S,getFlightProfile:()=>kt,getScaledEntries:()=>ks});function Rp({tournamentRecord:t,outcomes:e}){if(!t)return{error:j};if(!e?.length)return{error:et,info:"Missing outcomes"};let r=e.reduce((s,a)=>{let{drawId:c,eventId:u}=a;return u&&c&&(s[u]?s[u].includes(c)||s[u].push(c):s[u]=[c]),s},{}),n=Object.keys(r);return{publishedEventIds:(t.events?.filter(s=>n.includes(s.eventId))).filter(s=>{let a=Qr({event:s}),{drawDetails:c,drawIds:u}=a??{},{eventId:p}=s;return r[p].filter(d=>{let l=c?Object.keys(a.drawDetails).filter(f=>Fm({drawId:f,drawDetails:c})):[];return u?.includes(d)||l.includes(d)}).length}).map(s=>s.eventId),eventIdPublishedDrawIdsMap:r}}function qS({tournamentRecord:t,event:e}){if(!t)return{error:j};if(!e)return{error:St};let r=e.entries||[],n=t.participants||[],o=e.category?.categoryName||e.category?.ageCategoryCode,{eventType:i}=e,s=r.map(d=>d.participantId),a=n.filter(d=>s.includes(d.participantId)),c,u,p;return{entryScaleAttributes:a.map(d=>{let{participantId:l,participantName:f,name:g}=d,I={scaleType:Sf,eventType:i,scaleName:o},h=no({participant:d,scaleAttributes:I})?.scaleItem?.scaleValue;I={scaleType:GE,eventType:i,scaleName:o};let S=no({participant:d,scaleAttributes:I})?.scaleItem?.scaleValue;I={scaleType:FE,eventType:i,scaleName:o};let T=no({participant:d,scaleAttributes:I})?.scaleItem?.scaleValue;return c=!!(c||h),u=!!(u||S),p=!!(p||T),{participantId:l,participantName:f||g,seed:h,ranking:S,rating:T}}),hasSeededParticipants:c,hasRankedParticipants:u,hasRatedParticipants:p}}function $S({tournamentRecord:t,withScaleValues:e,scaleEventType:r,inContext:n,eventIds:o,drawIds:i,context:s}){if(!t)return{error:j};let{tournamentId:a}=t,c=(t.events??[]).filter(({eventId:p})=>!o||Array.isArray(o)&&o.includes(p)).map(p=>{let m=p.drawDefinitions?.map(Qu);if(i?.length&&!Wt(i,m).length)return;let d=J(p);return n&&Object.assign(d,{tournamentId:a}),s&&Object.assign(d,s),d}).filter(Boolean),u={};if(e){let p=$t({withScaleValues:!0,tournamentRecord:t}).participantMap,m=d=>d.reduce((l,f)=>l+parseFloat(f),0);for(let d of c){let l=r??d.eventType,f=d.eventId;u[f]||(u[f]={ratingsStats:{},ratings:{},ranking:{},draws:{}});let I=(d.entries??[]).filter(({entryStatus:E})=>Mr.includes(E)).map(ft),h=E=>{if(E?.ratings?.[l])for(let U of E?.ratings?.[l]??[]){let M=U.scaleName;u[f].ratings[M]||(u[f].ratings[M]=[]);let N=Jr[M]?.accessor;if(N){let C=parseFloat(U.scaleValue?.[N]);C&&u[f].ratings[M].push(C)}}if(E?.rankings?.[l])for(let U of E?.rankings?.[l]??[]){let M=U.scaleName;u[f].ranking[M]||(u[f].ranking[M]=[]),U.scaleValue&&u[f].ranking[M].push(U.scaleValue)}};for(let E of I){let U=p?.[E]?.participant;if(U?.participantType!==It)for(let M of U?.individualParticipantIds??[]){let N=p?.[M]?.participant;h(N)}else h(U)}let S=u[f].ratings;for(let E of Object.keys(S)){let U=S[E];if(!U.length)continue;let M=ky(U)?.toFixed(2);u[f].ratingsStats[E]={avg:parseFloat((m(U)/U.length).toFixed(2)),median:M?parseFloat(M):void 0,max:Math.max(...U),min:Math.min(...U)}}let T=(E,U)=>{let M=N=>{if(u[f].draws?.[E]&&N?.ratings?.[l])for(let C of N?.ratings?.[l]??[]){let D=C.scaleName;u[f].draws[E]?.ratings[D]||(u[f].draws[E].ratings[D]=[]);let O=Jr[D]?.accessor;if(O){let b=parseFloat(C.scaleValue?.[O]);b&&u[f].draws[E].ratings[D].push(b)}}if(u[f].draws?.[E]&&N?.rankings?.[l])for(let C of N?.rankings?.[l]??[]){let D=C.scaleName;u[f].draws[E]?.ranking[D]||(u[f].draws[E].ranking[D]=[]);let O=C.scaleValue;O&&u[f].draws[E].ranking[D].push(O)}};for(let N of U.filter(Boolean)){let C=p?.[N]?.participant;if(C?.participantType!==It)for(let D of C?.individualParticipantIds??[]){let O=p?.[D]?.participant;M(O)}else M(C)}},A=[],P=E=>i?.length&&i.includes(E)||A.includes(E);for(let E of d.drawDefinitions??[]){let U=E.drawId;if(P(U))continue;let M=di({drawDefinition:E}).assignedParticipantIds??[];u[f].draws[U]||(u[f].draws[U]={ratingsStats:{},ratings:{},ranking:{}}),A.push(U),T(U,M)}let y=kt({event:d}).flightProfile;for(let E of y?.flights??[]){let U=E.drawId;if(P(U))continue;let M=E.drawEntries.map(ft);T(U,M)}for(let E of A){let U=u[f].draws[E].ratings;for(let M of Object.keys(U)){let N=U[M];if(!N.length)continue;let C=ky(N)?.toFixed(2);u[f].draws[E].ratingsStats[M]={avg:parseFloat((m(N)/N.length).toFixed(2)),median:C?parseFloat(C):void 0,max:Math.max(...N),min:Math.min(...N)}}}}}return rt({eventScaleValues:u,events:c,...R})}function KS({tournamentRecord:t,drawDefinition:e,context:r,event:n}){if(!t)return{error:j};if(!n)return{error:St};let o=J(n);r&&Object.assign(o,r);let i=e&&o.drawDefinitions?.find(({drawId:s})=>e.drawId===s);return rt({drawDefinition:i,event:o})}var yP={[In]:{validSeedPositions:{ignore:!0},duplicateSeedNumbers:!0,drawSizeProgression:!0,seedingProfile:{drawTypes:{[to]:{positioning:ei},[un]:{positioning:ei}},positioning:wC},policyName:"USTA SEEDING",seedsCountThresholds:[{drawSize:4,minimumParticipantCount:3,seedsCount:2},{drawSize:16,minimumParticipantCount:12,seedsCount:4},{drawSize:32,minimumParticipantCount:24,seedsCount:8},{drawSize:64,minimumParticipantCount:48,seedsCount:16},{drawSize:128,minimumParticipantCount:96,seedsCount:32},{drawSize:256,minimumParticipantCount:192,seedsCount:64}]}},cg=yP;function _O(t){let e="validateAndDeriveDrawValues",{appliedPolicies:r,policyDefinitions:n}=yG(t),o=EG({...t,policyDefinitions:n,appliedPolicies:r}),i=AG(t),s=UG({...t,appliedPolicies:r});if(s?.error)return v({result:s,stack:e});let a=PG({...t,consideredEntries:i}),c=TG({...t,appliedPolicies:r,policyDefinitions:n,drawSize:a});if(c.error)return v({result:c,stack:e});let u=c.drawType;if(isNaN(a)&&u!==br)return v({result:{error:Ga},stack:e});let p=n?.[In]??r?.[In],m=t.seedingProfile??p?.seedingProfile?.drawTypes?.[u??""]??p?.seedingProfile;t.seedingProfile&&(n[In]||(n[In]={...cg[In]}),n[In].seedingProfile=m);let d=NG({...t,drawType:u});return d?.error?v({result:d,stack:e}):{drawSize:a,drawType:u,enforceGender:o,seedingProfile:m,appliedPolicies:r,policyDefinitions:n}}function TG(t){let{policyDefinitions:e,appliedPolicies:r,enforceMinimumDrawSize:n=!0,drawSize:o}=t,i=t.drawTypeCoercion??hu({drawType:t.drawType,policyDefinitions:e,appliedPolicies:r}),s=SS({drawType:t.drawType,enforceMinimumDrawSize:n,drawTypeCoercion:i,drawSize:o});return s.error?s:{drawType:s.drawType}}function AG({considerEventEntries:t=!0,drawEntries:e,eventEntries:r,qualifyingOnly:n}){return(n&&[]||e||(t?r:[])).filter(({entryStage:o})=>!o||o===tt)}function yG(t){let{tournamentRecord:e,event:r}=t,n=yt({tournamentRecord:e,event:r}).appliedPolicies??{},o=J(t.policyDefinitions??{},!1,!0);return{appliedPolicies:n,policyDefinitions:o}}function EG({enforceGender:t,policyDefinitions:e,appliedPolicies:r}){return t??e?.[qe]?.participants?.enforceGender??r?.[qe]?.participants?.enforceGender}function UG(t){let{consideredEntries:e,appliedPolicies:r,policyDefinitions:n,enforceGender:o,participantMap:i,participants:s,event:a}=t;return a&&s&&sd({consideredEntries:e,policyDefinitions:n,appliedPolicies:r,participantMap:i,enforceGender:o,participants:s,event:a})}function PG(t){return!t.drawSize&&t.consideredEntries.length&&![br,jc,ua,un,to].includes(t.drawType??"")&&Bi(t.consideredEntries.length)||t.drawSize&&ct(t.drawSize)||!1}function NG(t){let{tournamentRecord:e,event:r,ignoreAllowedDrawTypes:n,drawType:o}=t,i=!n&&e&&pd({tournamentRecord:e,categoryType:r?.category?.categoryType,categoryName:r?.category?.categoryName});return i?.length&&!i.includes(o)?{error:Qp}:{...R}}var lg={};ne(lg,{addGame:()=>f_,addPoint:()=>l_,addSet:()=>I_,addShot:()=>g_,analyzeSet:()=>Mp,calculateHistoryScore:()=>p_,checkScoreHasValue:()=>he,checkSetIsComplete:()=>Td,clearHistory:()=>d_,generateScoreString:()=>Ko,generateTieMatchUpScore:()=>lu,getSetComplement:()=>JS,getTiebreakComplement:()=>Ed,isValidMatchUpFormat:()=>Sr,keyValueScore:()=>u_,parseMatchUpFormat:()=>Ze,parseScoreString:()=>dg,redo:()=>h_,reverseScore:()=>KO,setServingSide:()=>m_,stringifyMatchUpFormat:()=>td,tidyScore:()=>$O,umo:()=>T_,undo:()=>S_,updateTieMatchUpScore:()=>En,validateScore:()=>XS,validateTieFormat:()=>cr});function Ko(t){let{winnerFirst:e=!0,addOutcomeString:r,reversed:n=!1,matchUpStatus:o,matchUpFormat:i,autoComplete:s,winningSide:a,sets:c}=t;if(!c)return{error:et,info:"missing sets"};let u=i&&Ze(i),{bestOf:p,finalSetFormat:m,setFormat:d}=u??{},f=n||!(!e||!a||a===1),g=r?DG({matchUpStatus:o}):"",I=c?.sort(MG).map(h).filter(Boolean).join(" ")||"";if(!g)return I;if(a===2)return`${g} ${I}`;return`${I} ${g}`;function h(S){let A=p&&S.setNumber===p&&m?m:d,P=x=>se(x?.side1Score)||se(x?.side2Score),y=x=>se(x?.side1TiebreakScore)||se(x?.side2TiebreakScore),E=A?.tiebreakSet||!P(S)&&y(S),{side1Score:U,side2Score:M,side1TiebreakScore:N,side2TiebreakScore:C}=S,D=N||(se(N)||s?0:""),O=C||(se(C)||s?0:"");if(E)return`[${(f?[O,D]:[D,O]).join("-")}]`;let b=Math.min(D,O),_=b?`(${b})`:"",L=U||(se(U)||s?0:""),F=M||(se(M)||s?0:""),w=f?`${[F,L].join("-")}${_}`:`${[L,F].join("-")}${_}`;return["-"," "].includes(w)&&(w=""),w}}function DG({matchUpStatus:t}){let e={[mr]:"RET",[Ot]:"WO",[Me]:"DF/DF",[fe]:"WO/WO",[Ki]:"SUS",[kr]:"ABN",[bt]:"DEF",[Vc]:"DR"};return t&&e[t]||""}function MG(t,e){return t.setNumber-e.setNumber}var Ad="\\d+-\\d+",bp="\\d+-\\d+\\(\\d+\\)",ug="\\[\\d+-\\d+\\]",CG="\\d+-\\d+\\(\\d+-\\d+\\)",vO=new RegExp(`(${Ad}),`,"g"),xO=new RegExp(`(${bp}),`,"g"),RG=[Ad,bp,ug,CG],bG=["0","1","2","00","01","10","11","002","012","102","112","000","001","010","100","011","101","110","111","002","012","102","112","0002","0012","0102","1002","0112","1012","1102","1112","3","03","13","013","103"],OG=bG.map(t=>{let r=t.split("").map(n=>RG[n]).join(" ");return new RegExp(`^${r}$`)});function EP(t){return!t||OG.some(e=>e.test(t))}function wO(t){let e="[];",r="()",n=e+r,o=[e[0],r[0]],i=Object.assign({},...n.split("").map(c=>({[c]:0}))),s="",a=t.split("").map(c=>{let u=n.includes(c)&&c,p=o.includes(u);if(p&&u)return i[u]+=1,s=u,c;if(!p&&u&&s&&u!==s){i[s]-=1;let m=e.includes(s)&&e||r.includes(s)&&r||"",d=m.split("").find(l=>l!==s);if(m.includes(u))i[s]||(s="");else return i[u]||(s=""),d}return c}).join("");return t!==a?a:t}function yd(t){return/^\(\d+\)$/.test(t)||/^\(\d+$/.test(t)}function LO(t){return/^\(\d+-\d+\)$/.test(t)||/^\[\d+-\d+\]$/.test(t)}function Ca(t){let r=(n=>n?.split("-").join("").split("/").join(""))(t);if(/^\d+$/.test(r)&&r.length===2){let n=r.split("");return Math.abs(n.reduce((i,s)=>+i-+s))===1}return!1}function Op(t,e){let r=[t.slice(e,e+2),e?t.slice(0,1):t.slice(2)].map(i=>parseInt(i.join("")));e&&r.reverse();let n=r;if(Math.abs(n.reduce((i,s)=>+i-+s))>=2)return n.join("-")}function UP(t){return t.length===2?t.split("").join("-"):([", ",",","/"," "].forEach(e=>t=t.split(e).join("-")),t=t.replace(/-{2,}/,"-"),t)}function FO(t){return t.startsWith("(")&&t.endsWith(")")}function GO({score:t,applied:e}){t=wO(t);let r=/\)(\d+)/g;if(r.test(t))for(let y of t.match(r)){let E=y.replace(")",") ");t=t.replace(y,E)}t=t.replace(/\)\//g,") / "),t=t.replace(/\/\)/g,")");let n=/\(([\d- ]+)\)/g,o=/\(([\d- ]+)\)/,i=t.match(n);for(let y of i||[]){let[E]=y.match(o).slice(1),U=E.replace(/ /g,"");t=t.replace(y,`(${U})`)}let s=/\(\(\d-\d\)\)/g;if(s.test(t)){let y=t.match(s);y.length&&y.forEach(E=>{let U=E.match(/\((\(\d-\d\))\)/).slice(1)[0];t=t.replace(E,U)})}if(s=/\(\((\d)\)\)/g,s.test(t)){let y=t.match(s);y.length&&y.forEach(E=>{let U=E.match(/\((\(\d\))\)/).slice(1)[0];t=t.replace(E,U)})}/(^|\s)6-,/.test(t)&&(t=t.replace(/(^|\s)6-,/g,"6-0,"));let a=new RegExp(/[-,]{2,}/g);t=t.replace(a,"-"),["- "," -"].forEach(y=>{let E=new RegExp(`(\\d+)${y}(\\d+)`,"g"),U=t.match(E);U&&U.forEach(M=>t=t.replace(M,M.split(y).join("-")))}),/^[(-/,]+$/.test(t)&&(t=""),/\)[-/,]+$/.test(t)&&(t=t.slice(0,t.length-1)),/\d \/\d/.test(t)&&(t=t.replace(/ \//g,"/")),t.includes(" /")&&(t=t.replace(/ \//g," "));let c=/\(\d+, \)/g;c.test(t)&&t.match(c).forEach(E=>{let[U]=E.match(/\((\d+), \)/).slice(1);U.length===2?t=t.replace(E,`(${U})`):U.length===1&&U==="6"&&(t=t.replace(E,"(6-0)"))});let u=/\((\d+)\/\)/g;u.test(t)&&t.match(u).forEach(E=>{let[U]=E.match(/\((\d+)\/\)/).slice(1);U.length===2?t=t.replace(E,`(${U})`):U.length===1&&U==="6"?t=t.replace(E,"(6-0)"):t=t.replace(E,`(${U})`)});let p=/\d\/\d\/,/g;p.test(t)&&t.match(p).forEach(E=>{let[U]=E.match(/(\d\/\d)\/,/).slice(1);t=t.replace(E,`${U},`),e.push("slashComma")});let m=/\(\/(\d+)\)/g;m.test(t)&&t.match(m).forEach(E=>{let[U]=E.match(/\(\/(\d+)\)/).slice(1);U.length===2?t=t.replace(E,`(${U})`):U.length===1&&parseInt(U)<6?t=t.replace(E,`(6-${U})`):t=t.replace(E,`(${U})`)});let d,l,f,g,I,h=()=>{I=pr(t.split("")),l=I["("]===(I[")"]||0)+1,d=(I["("]||0)+1===I[")"],f=I["["]===I["]"]+1,g=l&&!f};h();let S=/(\d+-\d+\(\d+)0,/;if(S.test(t)){let[y]=t.match(S).slice(1);t=t.replace(S,y+")")}if(I["("]===I[")"]&&I["("]>1){let y=t.split(")(").join(") (").split(" ");y.every(FO)?t=y.map(E=>{let U=E.slice(1,E.length-1);return U.length>2?U:E}).join(" "):t=y.join(" ")}h();let T=/[A-Za-z]+/.test(t),A=/\d+/.test(t);if(!T&&!A)return{score:""};if(/^\[.+\]$/.test(t)&&"()/,- ".split("").some(y=>I[y])&&(t=t.slice(1,t.length-1)),/^\(.+\)$/.test(t)&&I["("]===1&&I[")"]===1&&"[]/,".split("").some(y=>I[y]>1)&&(t=t.slice(1,t.length-1)),t.startsWith("(")&&t.endsWith("))")&&(t=t.slice(1,t.length-1)),I["("]>(I[")"]||0)&&t[t.length-1]==="("&&(t=t.slice(0,t.length-1)+")",h()),I["("]===1&&!I[")"]&&t[0]==="("&&(t=t+")",h()),I["("]>(I[")"]||0)&&t.slice(0,2)==="(("&&(t=t.slice(1)),d){if(/^9\d/.test(t))t="("+t.slice(1);else if(t[0]!=="(")t="("+t;else{let y=[],E=0;for(let U of t.split("").reverse())U===")"&&(E?y.push("("):E+=1),U==="("&&(E-=1),y.push(U);y.reverse(),t=y.join("")}h()}if(I[")"]>(I["("]||0)&&t[0]===")"&&(t="("+t.slice(1),h()),g&&(t.endsWith(9)||/\d+0$/.test(t))&&(t=t.slice(0,t.length-1)+")",h()),g&&(!t.endsWith(")")||t.startsWith("(("))&&(t=t+")",h()),g){let y="",E=0;for(let U of t.split(""))U==="("&&(E?y+=")":E+=1),U===")"&&(E-=1),y+=U;t=y}h(),f&&!l&&(t=t+"]"),t.includes("([")&&t.includes("])")&&(t=t.split("([").join("[").split("])").join("]"),h()),/\(\d+0$/.test(t)&&(t=t.slice(0,t.length-1)+")"),h(),I[")"]===1&&!I["("]&&t.endsWith(")")&&(t=t.slice(0,t.length-1)),t.startsWith("(")&&t.endsWith(")")&&I["("]===1&&I[")"]===1&&(t=t.slice(1,t.length-1),h());let P=y=>{let E=y.indexOf("("),U=y.indexOf(")");return E>=0&&U>=0&&E<U};if(/^\([\d ]+.*[\d ]+\)$/.test(t)&&I["("]===I[")"]){let y=t.slice(1,t.length-1);P(y)&&(t=y,h())}return{score:t,applied:e}}function yu(t){if(!/^[\d-]+(\(\d\))*$/.test(t))return t;let e=$n("-",t.split(""));if(!e.length)return t;let r=t.split("-"),n=!(r.length%2),o=!!(e.length%2);return n&&o&&e.length>r.length/2&&e.filter((s,a)=>a%2).forEach(s=>{t=t.substring(0,s)+" "+t.substring(s+1)}),t}function kO({score:t,applied:e}){return t.includes("( ")&&(e.push("removeParenSpacingAfterOpen"),t=t.split("( ").map(r=>r.trim()).join("(")),t.includes(" )")&&(e.push("removeParenSpacingBeforeClose"),t=t.split(" )").map(r=>r.trim()).join(")")),[vO,xO].forEach(r=>{let n=t.match(r);n?.length&&(n.forEach(o=>{t=t.replace(o,o.slice(0,o.length-1)+" ")}),e.push("setsEndComma"))}),t=t.split(" ").filter(Boolean).map(yu).join(" "),{score:t,applied:e}}function VO({score:t}){if(typeof t!="string")return{score:t};let e=d=>d?.split("-").join("").split("/").join(""),r=d=>d.split("[").join("(").split("]").join(")");t=t.split(", ").join(" ");let n=t.split(" ");t=n.map(d=>{let l=/^-(\d+)$/;if(l.test(d)){let[f]=d.match(l).slice(1);if(f.length===2)return f.split("").join("-")}return d}).join(" "),n=t.split(" ");let o=n.filter(yd),i=0,s="";for(let d of o){let l=$n(d,n).filter(h=>!i||h>i)[0],f=n.slice(i,l-1),g=n[l-1],I=e(g);if(/^\d+$/.test(I)&&I.length===2){let h=I.split(""),S=Math.abs(h.reduce((T,A)=>+T-+A));if(S===1){let T=[f.join(" "),[g,d].join("")].join(" ");s+=T,i=l+1}else if(S===0){let T=Math.max(...h);if([4,5,6,7,8,9].includes(T)){let A=[6,4].includes(T)?T+1:T-1,P=[T,A].sort().reverse().join("-"),y=[f.join(" "),[P,d].join("")].join(" ");s+=y,i=l+1}}}}if(o.length&&s.length){let d=n.slice(i).join(" ");return s=[s,d].join(" "),{score:s.trim()}}if(n.length===2&&["(","["].some(d=>n[1].includes(d))){let l=e(n[0]).split("");if(Math.abs(l.reduce((g,I)=>+g-+I,0))===1)return n[1]=r(n[1]),{score:n.join("")}}let a=n.map(d=>LO(d)&&"bracket"||Ca(d)&&"set");if(a.includes("set")&&a.includes("bracket")){let d,l="";return n.forEach((f,g)=>{a[g]==="bracket"&&d==="set"?(f=r(f),l+=f):l+=` ${f}`,d=a[g]}),{score:l.trim()}}n=t.split(" ");let c,u=n.map(d=>{let l=new RegExp(/^(\d+)-(\d+)$/);if(l.test(d)){let[f,g]=d.match(l).slice(1),I=Math.abs([f,g].reduce((S,T)=>+S-+T)),h=Math.max(f,g);if(I===1)return c="tiebreakSet",c;if(I>=2&&h>=7&&c==="tiebreakSet")return c="tiebreak",c}}),p=$n("tiebreak",u);if(p.length){let d="";n.forEach((l,f)=>{p.includes(f)?d+=`(${l}) `:p.includes(f+1)?d+=`${l}`:d+=`${l} `}),t=d.trim()}let m=/(\d+-\d+)\((\d+)-(\d+)\)$/;if(m.test(t)){let[d,l,f]=t.match(m).slice(1),I=Math.max(l,f)>=10;!Ca(d)&&I&&(t=t.replace(m,`${d} [${l}-${f}]`))}return u=[],t=t.split(" ").map(d=>{let l=/^\((.*)\)$/,f=l.test(d),g=new RegExp(ug).test(d)&&"super"||new RegExp(bp).test(d)&&"tiebreak"||new RegExp(Ad).test(d)&&"standard"||"unknown";return u.push(g),g==="standard"&&f?d.match(l)[1]:d}).join(" "),{score:t}}function BO({score:t,applied:e}){for(let N of[".",","," ","/"]){let C=new RegExp(`^(\\d+)\\${N}(\\d+)$`);if(C.test(t)){let D=t.match(C).slice(1).map(b=>parseInt(b)),O=Math.abs(D[0]-D[1]);O<=10&&O>=2&&(t=t.split(N).join("-"),e.push("variedJoinerPattern"))}}t.includes(";")&&(t=t.split(";").join(" "),e.push("semicolon set separation"));let r=/(^|\s)(\d)\/(\d)(\d)\/(\d)(\(|$)/;if(r.test(t)){let[N,C,D,O,b,_]=t.match(r).slice(1);t=t.replace(r,`${N}${C}-${D} ${O}-${b}${_}`),e.push("smashSlashPattern")}/.*\s6[/-]+$/.test(t)&&(t+="0",e.push("incompleteFinalSetPattern"));let o=/\(6,\)/g;o.test(t)&&(t=t.replace(o,"(6, 0)"),e.push("missingZeroPattern1"));let i=/^\d{3,}\(/,s=/\(\d+\)\d+/;[i,s].forEach(()=>{t=t.split(" ").map(C=>(i.test(C)&&(C=C.replace("("," (")),s.test(C)&&(C=C.replace(")",") ")),C)).join(" "),e.push("spaceConsiderationPatterns")});let c=yu(t);c!==t&&(t=c,e.push("deDashMash"));let u=/^(\d)[-/,]+(\d{2})[-/,]+(\d)$/;if(u.test(t)){let[N,C,D]=t.match(u).slice(1),[O,b]=C.split("");t=`${N}-${O} ${b}-${D}`,e.push("smashSetPattern")}let p=/^(\d+)[ -](\d+)$/,m=/^([\d -]+)\/([\d -]+)$/;if(m.test(t)){let[N,C]=t.match(m).slice(1),D=N.trim(),O=C.trim();if(p.test(D)&&p.test(O)){let b=D.match(p).slice(1,3).join("-"),_=O.match(p).slice(1,3).join("-");t=`${b} ${_}`,e.push("slashSeparationPattern")}}let d=/^([\d -]+),([\d -]+)$/;if(d.test(t)){let[N,C]=t.match(d).slice(1),D=N.trim(),O=C.trim();if(p.test(D)&&p.test(O)){let b=D.match(p).slice(1,3).join("-"),_=O.match(p).slice(1,3).join("-");t=`${b} ${_}`,e.push("commaSeparationPattern")}}let l=/^\d \d,/;if(l.test(t)){let N=t.match(l)[0],C=N.slice(0,N.length-1).split(" ").join("-");t=t.replace(N,C),e.push("singleSetCommaSeparationPattern")}let f=0,g=/(\d+)-(\d{2})-(\d+)/;for(;g.test(t)&&f<3;){let[N,C,D]=t.match(g).slice(1),O=C.split(""),b=`${N}-${O[0]} ${O[1]}-${D}`;t=t.replace(g,b),e.push("noSetSeparationPattern"),f+=1}let I=/(^|\s)7-6\s(\d+)\s/g,h=t.match(I);if(h?.length){let N=/(^|\s)7-6\s(\d+)\s/;h.forEach(C=>{let D=C.match(N).slice(2)[0];t=t.replace(C,`7-6(${D}) `),e.push("floatingTiebreakPattern1")})}let S=t.match(/\d \d /);S?.forEach(N=>{let C=N.slice(0,N.length-1).split(" ").join("-");t=t.replace(N,C),e.push("spaceSeparatedSetPattern1")}),S=t.match(/ \d \d$/),S?.forEach(N=>{let C=" "+N.slice(1).split(" ").join("-");t=t.replace(N,C),e.push("spaceSeparatedSetPattern2")});let T=/^\d, *\d\/\d, *\d/;if(T.test(t)){let N=t.match(T)[0],C=N.split("/").map(D=>`(${D})`).join(" ")+" ";t=t.replace(N,C),e.push("slashCommaSetPattern")}let A=/\(6-\)/g;A.test(t)&&(t=t.replace(A,"(6-0)"),e.push("missingZeroPattern2"));let P=/(?<!-)(\d+)\/(\d+)(?!-)/g;if(P.test(t)){let N=t.match(P),C=/(?<!-)(\d+)\/(\d+)(?!-)/,D=t;N.forEach(O=>{let[b,_]=O.match(C).slice(1),L=`${b}-${_}`;D=D.replace(O,L)}),t=D,e.push("slashSetPattern")}let y=/(.*)\s(1\d)\s(\d+)$/;if(y.test(t)){let[N,C,D]=t.match(y).slice(1);N.replace(/\D/g,"").length>=4&&(t=N+` ${C}${D}`,e.push("spaceSeparatedSuperPattern"))}let E=/(^|\s)(\d+-\d+)\s(\d+)(\s|$)/g;for(let N of t.match(E)||[]){let[C,D,O,b]=N.match(/(^|\s)(\d+-\d+)\s(\d+)(\s|$)/).slice(1),[_,L]=D.split("-").map(w=>parseInt(w));Math.abs(_-L)===1&&(t=t.replace(N,`${C}${D}(${O})${b}`),e.push("spaceSeparatedSetPattern"))}let U=/\d-\d \(\d{1,2}\)(\s|$|,)/g;for(let N of t.match(U)||[]){let C=/(\d-\d) \((\d{1,2})\)(\s|$|,)/,[D,O,b]=N.match(C).slice(1),[_,L]=D.split("-").map(w=>parseInt(w));Math.abs(_-L)===1&&(t=t.replace(N,`${D}(${O})${b}`),e.push("floatingTiebreakPattern2"))}let M=/(^|\s)(\d \d)\(/g;for(let N of t.match(M)||[]){let C=/(^|\s)(\d \d)\(/,[D,O]=N.match(C).slice(1);t=t.replace(N,`${D}${O.split(" ").join("-")}(`),e.push("spacedTiebreakPattern")}return{score:t,applied:e}}function HO({score:t,matchUpStatus:e}){let r=t?.split(" ");t=r.map(a=>{if(a.endsWith("]")){let c=a.split("[");if(Ca(c[0]))return c[0]+`(${c[1].slice(0,c[1].length-1)})`}return a}).join(" ");let n=new RegExp(/(\([\d ]+\))/g);if(n.test(t))for(let a of t.match(n)){let u=a.replace(" ","-").match(/\((.*)\)/)?.[1];if(se(u)&&u?.[0]>2){if([2,4].includes(u.length))u=u.split("").join("-");else if(u.length===3){let p=u.indexOf("1");u=Op(u.split(""),p)}}t=t.replace(a,`(${u})`)}r=t?.split(" ");let o=new RegExp(/^(\d[-/]+\d)\((\d+)[-/]+(\d+)\)$/),i=r.length-1;t=r.map((a,c)=>{let u=[void 0,"","COMPLETED"].includes(e)||c!==i;if(o.test(a)&&u){let[p,m,d]=Array.from(a.match(o)).slice(1),l=Math.min(m,d);return`${p}(${l})`}return a}).join(" "),r=t?.split(" "),o=new RegExp(/^(\d{2})\((\d+)\)$/),t=r.map(a=>{if(o.test(a)){let[c,u]=Array.from(a.match(o)).slice(1),p=c.split("");return`${p[0]}-${p[1]}(${u})`}return a}).join(" "),r=t?.split(" "),o=new RegExp(/^\((\d[-/]+\d)\)(\d+)$/),t=r.map(a=>{if(o.test(a)){let[c,u]=Array.from(a.match(o)).slice(1);return Ca(c)?`${c}(${u})`:c}return a}).join(" "),r=t?.split(" "),o=new RegExp(/^1-0\((\d+)\)$/),t=r.map(a=>{if(o.test(a)){let[c]=a.match(o).slice(1);return`[${c<9?10:parseInt(c)+2}-${c}]`}return a}).join(" ");let s=/\((\d)+0 /;if(s.test(t)){let a=t.match(s)[1];t=t.replace(s,`(${a}) `)}return{score:t}}function WO({score:t,attributes:e,identifier:r}){if(typeof t!="string")return{score:t,identifier:r};let n=new RegExp(/\([\d,/ ]+\)/g),o=t.match(n);for(let m of o||[]){let l=m.match(/^\((.*)\)$/)?.slice(1)?.[0],g=t.split(m)[0].split(")").reverse()[0].replace(/\D/g,"");if(l?.length===2&&g?.length>=2){let S=g.slice(g.length-2).split("").map(A=>parseInt(A));if(Math.abs(S[0]-S[1])===1)continue}let I=UP(l),h=yu(I);t=t.replace(m,`(${h})`).trim()}let i=new RegExp(/\[[\d,/ ]+\]/g);t.match(i)?.forEach(m=>{let d=UP(m.match(/^\[(.*)\]$/)[1]);t=t.replace(m,`(${d}) `).trim()});let a=[")","]"],c=[")(","), (",") (",")[",") [","](","] ("];if(t.startsWith("(")&&a.some(m=>t.endsWith(m))&&c.some(m=>t.includes(m))){let m="",d=t.split(/[)\]]/).filter(Boolean).map(h=>(h.startsWith(",")&&(h=h.slice(1)),h.trim())),l=d.every(h=>h.includes(",")||yd(h)),f=d.every(h=>h.includes("/")||yd(h)),g=d.every(h=>h.includes("-")||yd(h)),I=l&&","||g&&"-"||f&&"/";if(I){let h;d.forEach(S=>{if(S.startsWith("("))if(h==="set"&&(m+=" "),S.includes(I))m+=S.slice(1).split(I).map(T=>T.trim()).join("-"),h="set";else{let T=S.slice(1);m+=`(${T}) `,h="tiebreak"}else if(S.startsWith("[")){let T=S.slice(1).split(I).map(P=>parseInt(P.trim())),A=Math.min(...T);h==="set"?m+=`(${A}) `:m+=`[${T.join("-")}] `,h="tiebreak"}}),t=m.trim()}}let u=pr(t.split(""));u["("]===1&&u[")"]===1&&t.startsWith("(")&&t.endsWith(")")&&(t=t.slice(1,t.length-1),u["-"]===1&&Ca(t)&&se(e?.removed)&&(t=t+`(${e.removed})`,e.removed=void 0));let p=/\(\)/g;return p.test(t)&&(t=t.replace(p,"").trim()),{score:t}}function zS({score:t}){let e=t.split(""),r=[],n,o=()=>n=[void 0,void 0,void 0],i=()=>{let a=`${n[0]}-${n[1]}`;return n[2]&&(a+=` (${n[2]})`),o(),n.push(n),a};o();let s=()=>n[0]!==void 0&&n[1]!==void 0&&Math.abs(parseInt(n[0])-parseInt(n[1]));for(;e.length;){let a=e.shift(),c=se(a)&&parseInt(a),u=n[0]!==void 0&&n[1]!==void 0;if(se(c)){if(n[0]===void 0){n[0]=c;continue}if(n[1]===void 0&&(n[1]=c,s()||0>1)){r.push(i()),n=[void 0,void 0];continue}if(u&&e.length===1&&se(e[0])){let p=e.pop();n[0]=n[0].toString()+n[1].toString(),n[1]=p,r.push(i()),n=[void 0,void 0]}u&&s()}}return{sets:r}}function pg(t){let e=t.indexOf("1"),r=t.split(""),n=r.every(o=>!isNaN(o));if(n&&t.length===3&&e===0){let o=Op(r,e);if(o)return o}if(n&&t.length===7&&e>3){let o=r.slice(4),i=Op(o,e-4);if(i)return`${r[0]}-${r[1]} ${r[2]}-${r[3]} ${i}`}}function PP(t){let{score:e}=t,{applied:r,matchUpStatus:n}=t,o=e?.toString().split(""),i=o?.every(a=>se(a)),s=a=>Math.abs(a[0]-a[1]);if(typeof e=="number"||i){e=e.toString().toLowerCase(),i&&(e=o.join(""));let a=i?o.map(u=>parseInt(u)):e.split("").map(u=>parseInt(u)),{sets:c}=zS({score:e});if(a.length,e.length===3&&s(a.slice(0,2))===1){let[u,p,m]=a;e=`${u}-${p}(${m})`,r.push("numericTiebreakPattern1")}else if(e.length===3&&a[0]===1){let[u,p,m]=a;e=`[${u}${p}-${m}]`,r.push("numericTiebreakPattern2")}else if(e.length===4&&s(a.slice(0,2))===1&&"987654".split("").includes(a[0].toString())){let[u,p,m,d]=a,l=Math.min(m,d);e=`${u}-${p}(${l})`,r.push("numericTiebreakPattern3")}else if(e.length===4&&a[0]===1&&a[2]===1){let[u,p,m,d]=a;e=`[${u}${p}-${m}${d}]`,r.push("bigSuper")}else if(e.length===4){let[u,p,m,d]=a;e=`${u}${p} ${m}${d}`,r.push("split4")}else if(e.length===5&&s(a.slice(0,2))===1){let[u,p,m,d,l]=a;e=`${u}-${p}(${m}) ${d}-${l}`,r.push("numericTiebreakPattern4")}else if(e.length===5&&s(a.slice(3))===1){let[u,p,m,d,l]=a;e=`${u}-${p} ${m}-${d}(${l})`,r.push("numericTiebreakPattern5")}else if(a.length===7)if(s(a.slice(0,2))>1&&s(a.slice(2,4))>1&&a[4]===1){let[u,p,m,d,l,f,g]=a;e=`${u}-${p} ${m}-${d} [${l}${f}-${g}]`,r.push("numericTiebreakPattern6")}else if(s(a.slice(0,2))===1&&s(a.slice(3,5))>1&&s(a.slice(5,7))>1){let[u,p,m,d,l,f,g]=a;e=`${u}-${p}(${m}) ${d}-${l} ${f}-${g}`,r.push("numericTiebreakPattern7")}else if(s(a.slice(0,2))>1&&s(a.slice(2,4))===1&&s(a.slice(5,7))>1){let[u,p,m,d,l,f,g]=a;e=`${u}-${p} ${m}-${d}(${l}) ${f}-${g}`,r.push("numericTiebreakPattern8")}else if(s(a.slice(0,2))>1&&s(a.slice(2,4))>1&&s(a.slice(4,6))===1){let[u,p,m,d,l,f,g]=a;e=`${u}-${p} ${m}-${d} ${l}-${f}(${g})`,r.push("numericTiebreakPattern9")}else e=e.slice(0,2)+" "+e.slice(2,4)+" "+e.slice(4),r.push("numericMatchTiebreakPattern");else if(e.length%2){let u=pg(e);u&&e!==u&&r.push("parsedSuperPattern"),e=u??e}else{let u=Ae(e.split(""),2).map(h=>h.join("")),p=u.map(h=>{let[S,T]=h.split("").map(y=>parseInt(y)),A=Math.abs(S-T),P=S>T?1:2;return A>1&&P||P*-1}),m=p.reduce((h,S)=>h>0&&S>0,1),d=pr(p),l=p.map(h=>Math.abs(h)),f=pr(l),g=p[0]<0,I=!g&&p[1]<0;if(p[0]>0&&p[1]>0&&p[0]!==p[1])e=[u.slice(0,2).join(" "),u.slice(2).join("-")].join(" "),r.push("numeric3rdSetTiebreakPattern");else if(m)e=u.join(" "),r.push("chunkSplit");else if(a.length==6){if(d[1]==2||d[2]===2)if(!Object.values(f).includes(3))e=u.join(" "),r.push("chunkSplit");else{let[h,S,T,A,P,y]=a,E=p.reduce((U,M,N)=>M<0?N:U,void 0);if(E===0){let U=Math.min(T,A);e=`${h}-${S}(${U}) ${P}-${y}`,r.push("chunkSplitTiebreak1")}else if(E===1){let U=Math.min(P,y);e=`${h}-${S} ${T}-${A}(${U})`,r.push("chunkSplitTiebreak2")}else e=`${h}-${S} ${T}-${A}`,r.push("chunkSplitTrimExtraneous")}}else if(a.length===8){let[h,S,T,A,P,y,E,U]=a;g||I?a[5]===1&&(g?e=`${h}-${S}(${T}) ${A}-${P} [${y}${E}-${U}]`:e=`${h}-${S} ${T}-${A}(${P}) [${y}${E}-${U}]`):(p[0],p[1])}}}return{score:e,applied:r,matchUpStatus:n}}function QS(t){let e=[0,0],r=[],n=t.split(" "),o=/(\d+)-(\d+)/;n.forEach(c=>{if(o.test(c)){let u=c.match(o).slice(1).map(m=>parseInt(m)),p=u[0]>u[1]&&1||u[1]>u[0]&&2;p&&(e[p-1]+=1,r.push(p))}});let i=e[0]>e[1]&&1||e[1]>e[0]&&2,s=e[0]>0&&e[0]===e[1],a=e.reduce((c,u)=>c+u,0);return{setsWon:e,setsTied:s,setWinners:r,totalSets:a,winningSide:i}}function jO({score:t,matchUpStatus:e,attributes:r}){let n=[],o,i=t.split(" "),s=i.length;t=i.map((p,m)=>{if(new RegExp(bp).test(p)){let l=p.slice(3),f=p.slice(0,3),g=f.split("-");if(!Ca(f)&&!e){let I=Math.max(...g),h=f.indexOf(I),S=[I,I-1];return h&&S.reverse(),S.join("-")+l}}else if(p.length===2&&se(p))return p.split("").join("-");p=yu(p);let d=new RegExp(`^${ug}$`).test(p)&&"super"||new RegExp(`^${bp}$`).test(p)&&"tiebreak"||new RegExp(`^${Ad}$`).test(p)&&"standard"||"unknown";if(n.push(d),s>1&&d==="standard"&&m<2){let[l,f]=p.split("-"),g=Math.abs(parseInt(l)-parseInt(f)),I=Math.max(l,f),h=Math.min(l,f),S=[parseInt(l),parseInt(f)].indexOf(h);if(I>9&&g>2){let T=I.toString().split(""),A=T.find(P=>parseInt(P)>h||m&&parseInt(P)<=o)??T[0];A&&(p=S?[A,h].join("-"):[h,A].join("-"))}I>(o||0)&&(o=I)}if(d==="standard"){let[l,f]=p.split("-");if(!Math.abs(parseInt(l)-parseInt(f))&&e!=="RETIRED")return""}return p}).filter(Boolean).join(" ");let{setsWon:a,setWinners:c,totalSets:u}=QS(t);if(u===1&&r?.removed==="6"&&(t+=" 6-0"),t.split(" ").length>2&&Math.max(...a)>=2&&c[0]===c[1]&&(t=t.split(" ").slice(0,2).join(" ")),Math.max(...a)>2){let p=[0,0];t=t.split(" ").map((m,d)=>(p[c[d]]+=1,Math.max(...p)>2?void 0:m)).filter(Boolean).join(" ")}return{score:t,profile:n}}function YO({score:t}){let{setsTied:e,winningSide:r}=QS(t),n=/\s\((\d+)\)$/;if(!r&&e&&n.test(t)){let a=t.match(n).slice(1)[0],c=a<=8?10:a+2;t=t.replace(n,` [${c}-${a}]`)}let o=t.split(" "),i=o[o.length-1];if(!i.includes("-")||i.indexOf("(")>0)return{score:t};let s=i.split("(").join("").split(")").join("").split("-");if(!s.every(a=>se(a)))return{score:t};if(s[0]==="76"){let a=s[1].length===2?Math.min(...s[1].split("").map(c=>parseInt(c))):s[1];t=[...o.slice(0,o.length-1),`7-6(${a})`].join(" ")}else{s=s.map(u=>parseInt(u));let a=Math.max(...s),c=Math.abs(s[0]-s[1]);if(a>=10){if(c>2&&s.every(u=>+u>=10)){let u=s.map(p=>p===a?p-10:10).sort();c=Math.abs(u[0]-u[1]),c>2&&(s=u)}t=[...o.slice(0,o.length-1),`[${s.join("-")}]`].join(" ")}else o.length===3&&a>=7&&c>2&&(t=[...o.slice(0,o.length-1),`[${s.join("-")}]`].join(" "))}return{score:t}}function _G({score:t}){return t=t?.toString().toLowerCase()||"",{score:t}}function vG({score:t,applied:e}){return typeof t!="string"?{score:t}:(t.toLowerCase().includes("o")&&(t=t.toLowerCase().split(" ").map(r=>r.split("o").join("0")).join(" "),e.push("replaceOh")),{score:t,applied:e})}function xG({score:t,applied:e}){return typeof t!="string"?{score:t}:(t=t.toLowerCase().split(" ").map(r=>{if(/^\d+$/.test(r)&&r.length>2){let n=r.indexOf("1");if(r.length%2){if(r.length===3&&n===0){let o=Op(r.split(""),n);return e.push("getSuper"),o}}else{let{score:o,applied:i}=PP({score:r,applied:[]});o!==r&&(r=o,e.push(...i))}}return r}).join(" "),{score:t,applied:e})}function wG({score:t,applied:e}){return typeof t!="string"?{score:t}:[3,4].includes(t.length)&&pg(t)?{score:pg(t)}:(t=t.toLowerCase().split(" ").map(r=>{if(/^\d+$/.test(r)&&r.length===1){e.push("removeErroneous1");return}return r}).filter(Boolean).join(" "),{score:t,applied:e})}function LG({score:t,applied:e}){return["walkover","wo","w/o","w-o"].includes(t?.toString().toLowerCase())?(e.push("handleWalkover"),{matchUpStatus:"walkover",score:"",applied:e}):{score:t}}function FG({score:t,profile:e,applied:r}){t=t?.toString().toLowerCase();let n=/^(.*\d+.*)(ret|con)+[A-Za-z ]*$/;if(n.test(t)){let[a]=t.match(n).slice(1);return r.push("handleRetired"),{score:a.trim(),matchUpStatus:"retired",applied:r}}let o=e?.matchUpStatuses?.retired,s=["rtd",...Array.isArray(o)?o:[o].filter(Boolean)].find(a=>t?.endsWith(a));return s?(r.push("handleRetired"),{matchUpStatus:"retired",score:t?.replace(s,"").trim(),applied:r}):{score:t}}function GG({score:t,attributes:e}){(t.endsWith(" am")||t.endsWith(" pm"))&&(t=""),t=t.replace(/[A-Za-z]+/g,"").trim(),[".",","].some(o=>t.endsWith(o))&&(t=t.slice(0,t.length-1));let r="()/-".split("").some(o=>t.includes(o));/ \d$/.test(t)&&r&&(e={removed:t.slice(t.length-2).trim()},t=t.slice(0,t.length-2));let n=/(.*)[A-Za-z]+$/;return n.test(t)&&(t=t.match(n).slice(1)[0].trim()),{score:t,attributes:e}}function kG({score:t}){return new RegExp(/-\d+\/\d+-/).test(t)&&(t=t.split("/").join(" ")),{score:t}}function VG({score:t}){let e=new RegExp(/^\d+\/\d+/),r=t.split(" ");r.some(o=>e.test(o))&&(t=r.map(o=>e.test(o)?o.replace("/","-"):o).join(" "));let n=/^(\d+), *(\d+)$/;if(n.test(t)){let[o,i]=t.match(n).slice(1);t=[o,i].join("-")}return{score:t}}function BG({score:t}){let e=new RegExp(/\(\d+\/\d+\)/g),r=t.match(e);for(let n of r||[]){let o=n.replace("/","-");t=t.replace(n,o)}return{score:t}}function HG({score:t}){if(t.includes(",")){let e=t.split(",").map(o=>o.trim()),r=o=>/\d \d/.test(o);e.every(r)&&(t=e.map(o=>{let i=/\d+ \d+/g;for(let s of o.match(i)){let[a,c]=s.match(/(\d+) (\d+)/).slice(1);o=o.replace(s,`${a}-${c}`)}return o}).join(" "))}if(t.includes(" ")){let e=t.replace(/[ ,]/g,"");e.split("").every(n=>se(n))&&e.length===4&&(t=e)}return{score:t}}function WG({score:t}){let e=new RegExp(/^\[\d+\](.*)$/);e.test(t)&&(t=t.match(e).slice(1)[0].trim());let r=/\(,/g;return r.test(t)&&(t=t.replace(r,"(")),{score:t}}var qO={handleTiebreakSlashSeparation:BG,handleSetSlashSeparation:kG,punctuationAdjustments:GO,handleGameSeparation:VG,joinFloatingTiebreak:VO,handleBracketSpacing:kO,handleSpaceSeparator:HG,separateScoreBlocks:xG,matchKnownPatterns:BO,removeDanglingBits:GG,removeErroneous:wG,handleWalkover:LG,properTiebreak:HO,handleNumeric:PP,handleRetired:FG,containedSets:WO,sensibleSets:jO,stringScore:_G,superSquare:YO,setBuilder:zS,excisions:WG,replaceOh:vG};var NP={},jG=[],YG=["handleNumeric","handleWalkover","handleRetired","replaceOh","stringScore","punctuationAdjustments","excisions","handleSpaceSeparator","matchKnownPatterns","removeDanglingBits","handleBracketSpacing","matchKnownPatterns","containedSets","separateScoreBlocks","handleGameSeparation","removeErroneous","joinFloatingTiebreak","handleSetSlashSeparation","handleTiebreakSlashSeparation","properTiebreak","sensibleSets","superSquare"],qG=["handleNumeric","separateScoreBlocks","sensibleSets","superSquare"];function $O(t){if(!t.score)return{error:G};let{score:e,sheetName:r,identifier:n,fileName:o,stepLog:i,fullLog:s,profile:a}=t,c=[],u,p=[],m,d,l=e,f=I=>{I.forEach(h=>{d=qO[h]({profile:a,identifier:n,matchUpStatus:u,attributes:m,applied:p,score:l});let S=d.score!==l;S&&c.push({method:h,score:d.score}),i&&(s||S||d.matchUpStatus!==u)&&console.log(u?{score:d.score,matchUpStatus:u}:{score:d.score},h),d.matchUpStatus&&(u=d.matchUpStatus),d.attributes&&(m=d.attributes),d.applied&&(p=d.applied),l=d.score})};f(YG);let g=EP(l);return g||(l=e.toString().replace(/\D/g,""),m?.removed&&(m.removed=void 0),f(qG),g=EP(l),g||(jG.push({score:l,fileName:o,sheetName:r}),l="")),p.forEach(I=>{NP[I]||(NP[I]=0),NP[I]+=1}),{matchUpStatus:u?.toUpperCase(),modifications:c,attributes:m,isValid:g,score:l}}function KO(t){if(!t?.score)return{error:et};let{sets:e}=t.score,r=e.map(i=>{let{side1TiebreakScore:s,side2TiebreakScore:a,winningSide:c,side1Score:u,side2Score:p,setNumber:m}=i;return rt({winningSide:c?3-c:void 0,side1TiebreakScore:a,side2TiebreakScore:s,side1Score:p,side2Score:u,setNumber:m})}),n=Ko({sets:r}),o=Ko({sets:r,reversed:!0});return{reversedScore:{sets:r,scoreStringSide1:n,scoreStringSide2:o},...R}}function zO({existingMatchUpStatus:t,matchUpFormat:e,matchUpStatus:r,winningSide:n,score:o}){let i=o?.sets??[],a=(i?.filter(y=>y?.winningSide)||[]).reduce((y,E)=>{let{winningSide:U}=E;if(!U)return y;let M=U-1;return y[M]++,y},[0,0]),c=n?n-1:void 0,u=c!==void 0?1-c:void 0,p=c!==void 0&&a[c],m=u!==void 0&&a[u],d=e?Ze(e):void 0,l=Math.max(...a),f=pr(a)[l],g=d?.bestOf,I=g&&Math.ceil(g/2)||1,h=r??t,S=h&&[bt,mr,Ot].includes(h),T=!d||!i.length||i.every((y,E)=>{let U=E+1,M=U===g,N=U===i.length,{side1Score:C,side2Score:D,side1TiebreakScore:O,side2TiebreakScore:b,winningSide:_}=y,L=Math.max(C??0,D??0),F=O??b,{finalSetFormat:w,setFormat:x}=d,H=M&&w||x;if(F){let{tiebreakTo:W,NoAD:B}=H?.tiebreakFormat||{},q=Math.max(O??0,b??0);if(B&&q>W||q<W&&_&&(N&&!S||!N))return!1}return H.setTo?!(!H.noTiebreak&&L>H.setTo+1):!0}),A=(!e||l===I)&&f===1&&a.indexOf(l)+1||void 0;return{valid:T&&(n&&p>m&&n===A||!n&&!A||S)}}function XS({existingMatchUpStatus:t,matchUpFormat:e,matchUpStatus:r,winningSide:n,score:o}){if(typeof o!="object")return{error:G};let{sets:i,scoreStringSide1:s,scoreStringSide2:a}=o,c="scoreString must be a string!";if(s!==void 0&&typeof s!="string")return{error:G,info:c};if(a!==void 0&&typeof a!="string")return{error:G,info:c};if(i!==void 0&&!Array.isArray(i))return{error:G,info:Tn("sets")};if(i?.length){let u=i.map(m=>m?.setNumber).filter(Boolean);if(u.length!==mt(u).length)return{error:G,info:"setNumbers not unique"};for(let m of i){let{side1Score:d,side2Score:l,side1TiebreakScore:f,side2TiebreakScore:g,side1PointScore:I,side2PointScore:h,winningSide:S,setNumber:T}=m;if(![[d,l],[f,g],[I,h]].filter(y=>y.some(E=>E!==void 0)).every(y=>y.every(E=>lt(E))))return{error:G,info:"non-numeric values"};if(![T,S].filter(y=>y!==void 0).every(y=>lt(y)))return{error:G,info:"non-numeric values"};if(S&&![1,2].includes(S))return{error:G,info:"winningSide must be 1 or 2"}}let{valid:p}=zO({existingMatchUpStatus:t,matchUpStatus:r,matchUpFormat:e,winningSide:n,score:o});if(!p)return{error:ay,info:"score is invalid for matchUpFormat or winningSide does not match calculated winningSide"}}return{valid:!0}}var JS=t=>{let{isSide1:e,lowValue:r,setTo:n,tiebreakAt:o,NoAD:i}=t;if(r===void 0)return!1;let s=ct(r);s?.toString().length>2&&(s=parseInt(s.toString().slice(0,2))),o&&o<n&&s>o&&(s=o);let a;return i&&!o?(s>n&&(a=n),a=s<n?n:n-1):a=s+1<n&&n||o&&o<n&&s===o&&n||!o&&s+2||n+1,[e?s:a,e?a:s]},Ed=t=>{let{isSide1:e,lowValue:r,tiebreakTo:n,tiebreakNoAd:o}=t;if(r===void 0)return!1;let i=typeof r=="string"?parseInt(r):r;i?.toString().length>2&&(i=parseInt(i.toString().slice(0,2))),o&&i>n-1&&(i=n-1);let s=$G({lowValue:i,NoAD:o,tiebreakTo:n});return[e?i:s,e?s:i]};function $G(t){let{lowValue:e,NoAD:r,tiebreakTo:n}=t,o=r?1:2;return e+1>=n?e+o:n}var js=" ",ZS="DEF",QO="COMPLETED",DP="WO",KG="WO/WO",MP="ABN",CP="SUS",RP="RET",bP="INT",tT=[RP,ZS,DP,KG,MP,CP,bP];var eT="DEFAULTED";var OP="WALKOVER";var rT="ABANDONED",nT="SUSPENDED",_P="RETIRED",oT="INTERRUPTED";var XO=[_P,eT,OP],zG="Enter Score",ms="()",ds="[]",vP=["up","left","shift+tab"],xP=["enter","down","tab","right"],Ud="backspace",wP="r",LP="s",FP="a",GP="d",kP="w",VP="i",Pd=[wP,GP,kP,FP,LP,VP],_p="space",iT=["[","("],Nd=[...vP,...xP,_p,"]"],JO="-",QG="/",Ys=JO,zo=JO,BP=[QG],ZO=0,XG=["=","+","num_1","num_2","shift+=","shift+-"],Ws=["0","1","2","3","4","5","6","7","8","9"].concat(Pd),t_=Ws.map(t=>`shift+${t}`),HP=[Ys,Ud].concat(Nd,BP),WP=[Ws,t_,HP].join(","),JG=[WP,vP,xP,XG].join(","),JOt=[].concat(...Ws,...Ws,...HP,...Ws,...Ws,...Ws,...Ws,...Ws,...Ws),e_={OUTCOMEKEYS:Pd,SIDE1KEYS:Ws,SIDE2KEYS:t_,MODIFIERS:HP,PROMPT:zG,MOVEUP:vP,MOVEDOWN:xP,HOTKEYS:JG};function vp({scoreString:t,lowSide:e,outcome:r}){if({scoreString:t}=r_({scoreString:t}),e===2){let o=(t&&t[t.length-1])!==js?js:"";return t+o+r}else return r+js+t}function r_({scoreString:t}){if(!t)return{scoreString:""};let e=!1;for(let r of tT){let n=t?.indexOf(r);n===0?t=t.slice(r.length+1).trim()+js:n>0&&(t=t.slice(0,n)),n>=0&&(e=!0)}return t?.trim()||(t=""),{scoreString:t,removed:e}}function mg({analysis:t,scoreString:e,sets:r,lowSide:n}){let o,i;if(!e)return{scoreString:e,sets:r};let{scoreString:s,removed:a}=r_({scoreString:e});if(e=s,a)return{scoreString:e,sets:r,outcomeRemoved:!0};let c=r[r.length-1]||{},u=Object.values(c).filter(g=>g!==void 0).length;c.setNumber&&u===1&&(r=r.slice(0,r.length-1),c=r[r.length-1]||{});let{tiebreakSet:p}=t.setFormat,{tiebreakTo:m,NoAD:d}=p||{},{isTiebreakEntry:l}=Eu({brackets:ds,scoreString:e}),f=ZG(e);if(f>=0){o=e.slice(0,f);let{isTiebreakEntry:g}=Eu({brackets:ms,scoreString:o}),{lastOpenBracketIndex:I,isTiebreakEntry:h}=Eu({brackets:ds,scoreString:o}),S=o&&o[o.length-1].trim(),T=o&&!isNaN(S),A=t.isIncompleteSetScore;if(l&&h){let y=o.slice(I+1).split(zo),E=y?.length>0&&y[0]!==void 0&&!isNaN(parseInt(y[0]))&&parseInt(y[0])||void 0,U=y?.length>1&&y[1]!==void 0&&parseInt(y[1])||void 0,M=[E,U];if(U){let N=n===1?1:0;M[N]=(M?.[1-N]||0)+(d?1:2),(M[N]||0)<m&&(M[N]=m),o=e.slice(0,I+1),o+=M.join(zo)}else E!==void 0?(o=e.slice(0,I+1),o+=E):(o=e.slice(0,I),A=!0);c.side1TiebreakScore=M[0]||0,c.side2TiebreakScore=M[1]||0}if(o.length||(o=void 0),A){let P=c.side1Score?.toString();if(P){let y=P?.slice(0,P.length-1);c.side1Score=!isNaN(y)&&parseInt(y)||void 0,c.side1Score===void 0&&(c.side2Score=void 0)}t.isTimedSet?(i=c.side1Score?r:r?.slice(0,r.length-1)||[],i[r.length-1]=c):i=r?.slice(0,r.length-1)||[]}else if(T){let P=c.side2Score?.toString(),y=c.side1Score?.toString();if(!t.isTiebreakEntry&&!t.isMatchTiebreak)if(c.side2Score){let E=P?.slice(0,P.length-1);c.side2Score=!isNaN(E)&&parseInt(E)||void 0}else{let E=y?.slice(0,y.length-1);c.side1Score=!isNaN(E)&&parseInt(E)||void 0}t.isTimedSet?c.side1Score?(i=r||[],i[r.length-1]=c):i=r?.slice(0,r.length-1)||[]:(i=r||[],i[r.length-1]=c),i[i.length-1]&&Object.assign(i[i.length-1],{winningSide:void 0})}else g?(i=r||[],Object.assign(i[i.length-1]||{},{winningSide:void 0,side1TiebreakScore:void 0,side2TiebreakScore:void 0})):(l&&!h?i=r?.slice(0,r.length-1)||[]:(i=r,i[r.length-1]=c),l||(i[i.length-1].side2Score=0,i[i.length-1].winningSide=void 0));return{scoreString:o,sets:i}}return{scoreString:e,sets:r}}function Eu({brackets:t=ms,scoreString:e}){if(!e)return{};let[r,n]=t.split(""),o=e.split(""),i=Math.max(...$n(r,o)),s=Math.max(...$n(n,o));return{isTiebreakEntry:i>s,lastOpenBracketIndex:i}}function n_({scoreString:t}){if(!t)return!1;let e=t&&t[t.length-1].trim(),r=t&&!isNaN(e),[n,o]=ds.split(""),i=t.split(""),s=Math.max(...$n(n,i)),a=Math.max(...$n(o,i)),c=Math.max(...$n(zo,i));return r&&s>a&&c>s}function ZG(t){return t.split("").reduce((n,o,i)=>(o.match(/\d+/g)&&n.push(i),n),[]).pop()}function sT(t){let{lowValue:e=0,NoAD:r=!1,tiebreakTo:n}=t||{},o=r?1:2;return e+1>=n?e+o:parseInt(n)}function jP({matchUpFormat:t,matchUpStatus:e,winningSide:r,sets:n}){let o=Ze(t),{bestOf:i}=o,s=Math.ceil(i/2),c=n?.reduce((u,p)=>{let{winningSide:m}=p;return m&&u[m-1]++,u},[0,0])?.indexOf(s)+1||void 0;return XO.includes(e)&&r&&(c=r),{matchUpWinningSide:c}}function Dd({analysis:t,set:e}){let r=Dp({set:e}),{isDecidingSet:n,isTiebreakSet:o,matchUpScoringFormat:i}=t;return Td({matchUpScoringFormat:i,isDecidingSet:n,isTiebreakSet:o,set:e})&&r}function o_({analysis:t,scoreString:e,sets:r,value:n}){let o;if(!r?.length)return{sets:[]};let i=r[r.length-1];n=ct(n);let{validSide2Score:s,requiresTiebreak:a}=tk({analysis:t,set:i,value:n});if(s){o=!0,e=(e||"")+n,i.side2Score=n;let c=Dd({analysis:t,set:r[r.length-1]});if(i.winningSide=c||void 0,a){let u=ms.split("")[0];e+=u}else t.isDecidingSet||(e+=js)}return{sets:r,scoreString:e,updated:o}}function tk({analysis:t,set:e={},value:r}){let n=t.isDecidingSet&&t.matchUpScoringFormat.finalSetFormat||t.matchUpScoringFormat.setFormat,{tiebreakAt:o,setTo:i,NoAD:s}=n,{side1Score:a}=e,c,u;return o&&o<i?a===o?c=r<=i:c=r<=o:a===i?s?c=r<i:c=r<=i+1:a===i-1?s?c=r<=i:c=r<=i+1:a===i+1?c=r===i||r===i-1:c=r<=i,c&&(o&&o<i?u=a===i&&r===o||a===o&&r===i:u=a>=i&&r>=i&&a!==r),{validSide2Score:c,requiresTiebreak:u}}function aT({lowSide:t,value:e,sets:r,scoreString:n,winningSide:o,matchUpStatus:i}){let s;return e===wP?n?(s=!0,n=vp({scoreString:n,lowSide:t,outcome:RP}),o=t===2?1:2,i=_P):(s=!0,n=vp({scoreString:n,lowSide:t,outcome:ZS}),o=t===2?1:2,i=eT):e===GP?(s=!0,n=vp({scoreString:n,lowSide:t,outcome:ZS}),o=t===2?1:2,i=eT):e===kP?(s=!0,r=[],n=DP,o=t===2?1:2,i=OP):e===LP&&n?(s=!0,n=vp({scoreString:n,lowSide:t,outcome:CP}),i=nT,o=void 0):e===FP?(s=!0,n=vp({scoreString:n,lowSide:t,outcome:MP}),i=rT,o=void 0):e===VP&&n&&(s=!0,n=vp({scoreString:n,lowSide:t,outcome:bP}),i=oT,o=void 0),{updated:s,sets:r,scoreString:n,matchUpStatus:i,winningSide:o}}function i_(t){let{sets:e,info:r,scoreString:n,winningSide:o,matchUpStatus:i}=t,{analysis:s,lowSide:a,value:c}=t,u,p;!e?.length&&c!==Ud&&(e=[{setNumber:1}]);let m=e.length-1;if(Pd.includes(c)){let d=e[e.length-1]||{},{side1Score:l,side2Score:f}=d;l&&!f?r="missing side2Score":s.finalSetIsComplete||o?r="final set is already complete":s.isIncompleteSetScore?r="incomplete set scoreString":s.isIncompleteSetScore||({sets:e,scoreString:n,winningSide:o,matchUpStatus:i,updated:u}=aT({lowSide:a,value:c,sets:e,scoreString:n,matchUpStatus:i,winningSide:o}))}else if(c===Ud){if({scoreString:n,sets:e,outcomeRemoved:p}=mg({analysis:s,scoreString:n,sets:e}),n?.trim()===""&&(n=n.trim()),n||(e=[]),p){let d=e[e.length-1]||{},{side1Score:l,side2Score:f}=d;if(l&&f){let g=l>f&&1||f>l&&2||void 0;g&&(d.winningSide=g,e.push({setNumber:e.length+1}))}}i=void 0,o=void 0,u=!0}else if(s.hasOutcome)r="has outcome";else{if(o)return{sets:e,scoreString:n,winningSide:o,matchUpStatus:i,updated:!1,info:"matchUp is complete"};if(c===_p){let d=e[e.length-1]||{},{side1Score:l,side2Score:f}=d,g=l>f&&1||f>l&&2||void 0;g&&!o&&!s.isIncompleteSetScore&&(e[e.length-1].winningSide=g,e.push({setNumber:e.length+1}),n+=" ",u=!0)}else if(c===Ys&&e[m].side1Score!==void 0&&e[m].side2Score===void 0&&n&&s.isNumericEnding)n+="-",e[m].side2Score=0,i=void 0,o=void 0,u=!0;else if(!isNaN(c)){let d;if(e[m].side2Score===void 0){let l=ct((e[m].side1Score||0).toString()+c).toString().slice(0,2);e[m].side1Score=ct(l),d=e[m].side1Score.toString(),u=!0}else{let l=ct((e[m].side2Score||0).toString()+c).toString().slice(0,2);e[m].side2Score=ct(l),d=[e[m].side1Score,e[m].side2Score].join("-"),u=!0}if(u){let l=(e.slice(0,m)||[]).filter(f=>f).map(f=>{let{side1Score:g,side2Score:I}=f;return[g,I].join("-")}).join(" ");l?n=l+" "+d:n=d}}}return{sets:e,scoreString:n,winningSide:o,matchUpStatus:i,info:r,updated:u}}function s_({analysis:t,auto:e,lowSide:r,scoreString:n="",sets:o,value:i}){let s,a,{tiebreakSet:{tiebreakTo:c,NoAD:u}}=t.setFormat,[p]=ds.split("");if(t.isMatchTiebreakEntry||(n+=p),o[t.setNumber-1]){let{lastOpenBracketIndex:d}=Eu({brackets:ds,scoreString:n}),f=(n.slice((d??0)+1)+(e?"":i)).split(zo);if((f[r-1]?.length||0)>=2)a="tiebreak digit limit";else if(e){r===1&&(f[0]=(f[0]||"")+i),r===2&&(f[1]=(f[1]||"")+i);let I=[f[0]||0,f[1]||0].map(T=>ct(T)),h=r===1?1:0;I[h]=I[1-h]+(u?1:2),I[h]<c&&(I[h]=c);let S=o[o.length-1];S.side1TiebreakScore=I[0],S.side2TiebreakScore=I[1],n=n.slice(0,(d??0)+1),n+=I.join(zo),s=!0}else{let I=[f[0]||0,f[1]||0].map(S=>ct(S)),h=o[o.length-1];h.side1TiebreakScore=I[0],h.side2TiebreakScore=I[1],n+=i,s=!0}}else{let d=sT({lowValue:ct(i||0),tiebreakTo:c,NoAD:u}),l=[ct(i),d];r===2&&l.reverse();let f={side1TiebreakScore:l[0],side2TiebreakScore:l[1],setNumber:o?.length+1||1};o.push(f),n+=l.join(zo),s=!0}return{info:a,scoreString:n,sets:o,updated:s}}function a_({analysis:t,lowSide:e,scoreString:r,value:n}){let{setTo:o,tiebreakAt:i,NoAD:s}=t?.setFormat||{},a=n===parseInt(i||o);if(i&&i<o&&n>i)return{scoreString:r};if(s&&n===o||n>o)return{scoreString:r};let c=g(),u=[n,c];e===2&&u.reverse();let m=ms.split("")[0],d=u.join(Ys)+(a?m:js);r=(r||"")+d;let l={side1Score:u[0],side2Score:u[1]},f=Dd({analysis:t,set:l});return l.winningSide=f||void 0,{scoreString:r,set:l};function g(){return a?n+1:n+1===o?n+(s?1:2):o}}function c_({matchUpFormat:t,scoreString:e,winningSide:r,value:n,sets:o}){let s=(o?.filter(B=>B?.winningSide)?.length||0)+(r?0:1),a=Ze(t),c=s===a?.bestOf,u=c&&a?.finalSetFormat||a?.setFormat||{},p=u?.timed,m=c&&o[a?.bestOf-1],d=m?.winningSide,{isTiebreakEntry:l}=Eu({brackets:ms,scoreString:e}),{isTiebreakEntry:f}=Eu({brackets:ds,scoreString:e}),g=l||f,I=!!u.tiebreakSet,h=e?.[e.length-1]?.trim(),S=e&&!isNaN(h),T=!g&&h===Ys,A=l&&iT.includes(h),P=f&&iT.includes(h),y=f&&h===zo,E=e?.split(""),[U]=ds.split(""),M=E&&Math.max(...$n(U,E)),N=E&&Math.max(...$n(zo,E)),C=E&&N>M,D=o[o.length-1]?.winningSide,O=o?.length&&!D,b=tT.find(B=>e?.indexOf(B)>=0),_=!isNaN(n),L=n===_p,F=Nd.includes(n),w=e?.split("").find(B=>iT.includes(B)),x=F&&f&&!P&&(y||!n_({scoreString:e}));return{isTiebreakSetValue:I&&_,matchUpScoringFormat:a,setNumber:s,setFormat:u,matchTiebreakHasJoiner:C,isGameScoreEntry:O,isSpace:L,isCloser:F,isTiebreakCloser:F&&w&&g&&S,isDecidingSet:c,isTiebreakSet:I,isTimedSet:p,isNumericEnding:S,isNumericValue:_,hasOpener:w,hasOutcome:b,finalSet:m,finalSetIsComplete:d,lastSetIsComplete:D,isInvalidSetTiebreakValue:L&&g&&A,isInvalidMatchTiebreakValue:x,isTiebreakEntry:g,isSetTiebreakEntry:l,isMatchTiebreakEntry:f,isIncompleteSetScore:T,isIncompleteSetTiebreak:A,isIncompleteMatchTiebreak:P,isPartialMatchTiebreakValue:y}}function u_(t){let{lowSide:e=1,value:r}=t,{scoreString:n,sets:o,winningSide:i,matchUpStatus:s}=t,{matchUpFormat:a,shiftFirst:c,auto:u=!0}=t,p,m,d=c&&e===2||!c&&e===1;if(!WP.includes(r))return{updated:!1,info:"invalid key"};c&&(e=3-e);let{matchUpWinningSide:l}=jP({sets:o,winningSide:i,matchUpStatus:s,matchUpFormat:a});i=l;let f=c_({value:r,winningSide:i,scoreString:n,sets:o,matchUpFormat:a});if(BP.includes(r)&&(r=Ys),f.hasOpener&&f.isTiebreakEntry&&!f.isTiebreakSet&&d&&ct(r)===0&&(f.isTiebreakCloser=!0),Nd.includes(r)&&f.hasOpener&&(r=""),Nd.includes(r)&&(r=_p),f.lastSetIsComplete){let g=n?.length&&n[n.length-1];n&&g!==" "&&(n+=" ")}if(f.isTimedSet)({info:m,sets:o,scoreString:n,updated:p,matchUpStatus:s,winningSide:i}=i_({analysis:f,lowSide:e,scoreString:n,sets:o,matchUpStatus:s,winningSide:i,value:r}));else if(Pd.includes(r))f.finalSetIsComplete||i?m="final set is already complete":!f.isTiebreakEntry&&!f.isIncompleteSetScore?{sets:o,scoreString:n,matchUpStatus:s,winningSide:i,updated:p}=aT({lowSide:e,sets:o,scoreString:n,matchUpStatus:s,winningSide:i,value:r}):f.isTiebreakEntry||f.isIncompleteSetScore?m="incomplete set scoreString or tiebreak entry":console.log("handle case",{value:r});else if(r===Ud)p=!0,{scoreString:n,sets:o}=mg({analysis:f,scoreString:n,sets:o,lowSide:e}),n||(o=[]),s=void 0,i=void 0;else if(f.hasOutcome)m="has outcome";else if(r===Ys&&!f.isMatchTiebreakEntry)(!f.isSetTiebreakEntry||f.isSetTiebreakEntry&&!f.isNumericEnding)&&(p=!0,{scoreString:n,sets:o}=mg({analysis:f,scoreString:n,sets:o,lowSide:e}),s=void 0);else if(r===zo&&f.isMatchTiebreakEntry&&!f.isSetTiebreakEntry)f.matchTiebreakHasJoiner?m="existing joiner":f.isNumericEnding&&(p=!0,n+=zo);else if([Ys,zo].includes(r))m="invalid location for joiner";else{if(i)return{updated:!1,info:"matchUp is complete"};if(f.isIncompleteSetScore)f.isNumericValue&&({sets:o,scoreString:n,updated:p}=o_({analysis:f,scoreString:n,sets:o,value:r}));else if(f.isInvalidMatchTiebreakValue)m="invalid matchUp tiebreak character";else if(f.isInvalidSetTiebreakValue)m="invalid set tiebreak character";else if(f.isTiebreakCloser){let g=f.isSetTiebreakEntry?ms:ds,I=g.split("").reverse()[0],h=g.split("")[0],S=o[o.length-1],{tiebreakFormat:T}=f.setFormat,{tiebreakTo:A,NoAD:P}=T||{},y=Dp({set:S});if(!f.isTiebreakSet){let U=parseInt(n.split(h).reverse()[0]),M=sT({lowValue:U,tiebreakTo:A,NoAD:P});y===1?(S.side1TiebreakScore=M,S.side2TiebreakScore=U):(S.side1TiebreakScore=U,S.side2TiebreakScore=M)}n=(n||"")+I,f.isDecidingSet||(n+=js);let E=Dd({analysis:f,set:S});S.winningSide=E||void 0,p=!0}else if(f.isTiebreakSetValue)({info:m,scoreString:n,sets:o,updated:p}=s_({analysis:f,auto:u,lowSide:e,scoreString:n,sets:o,value:r}));else if(f.isSetTiebreakEntry){let[g]=ms.split(""),I=Math.max(...$n(g,n.split(""))),h=n.slice(I+1),S=h&&ct(h)===ZO,T=ct(h?h+r:r),{tiebreakFormat:A}=f.setFormat,{tiebreakTo:P,NoAD:y}=A||{};!S&&h.length<2?y&&T>P-1?m="invalid low value for NoAD tiebreak":(p=!0,n=(n||"")+r):m=S?"tiebreak begins with zero":"tiebreak digit limit"}else if(f.isCloser)m=`invalid key: ${r}`;else if(f.isGameScoreEntry)m="game scoreString entry";else if(f.lastSetIsComplete||!o.length){p=!0;let{scoreString:g,set:I}=a_({analysis:f,lowSide:e,scoreString:n,value:ct(r)});I&&(I.setNumber=o?.length+1||1),o=o?.concat(I).filter(Boolean)||[I],n=g||void 0}else console.log("error: unknown outcome")}if(p){o=o?.filter(Boolean);let{matchUpWinningSide:g}=jP({sets:o,winningSide:i,matchUpStatus:s,matchUpFormat:a});return i=g,g&&(!s||[Kt,No].includes(s))?(s=QO,o=o.filter(I=>{let{side1Score:h,side2Score:S,side1TiebreakScore:T,side2TiebreakScore:A}=I;return h||S||T||A})):n&&!i&&![nT,rT,oT].includes(s)&&(s=void 0),{updated:p,scoreString:n,sets:o,winningSide:i,matchUpStatus:s,info:m}}return{updated:p,scoreString:n,sets:o,winningSide:i,matchUpStatus:s,info:m}}function dg({tiebreakTo:t=7,scoreString:e=""}){return e?.split(" ").filter(Boolean).map((n,o)=>r({set:n,setNumber:o+1}));function r({set:n,setNumber:o}){let i=n?.startsWith("[")&&n.split("[")[1].split("]")[0].split("-").map(I=>parseInt(I)),s=n.includes("(")&&n.split("(")[0]||n.includes("[")&&n.split("[")[0]||n,a=!i&&s.split("-").map(I=>parseInt(I)),c=i?i[0]>i[1]&&1||i[0]<i[1]&&2||void 0:a[0]>a[1]&&1||a[0]<a[1]&&2||void 0,u=n.includes("(")?n.split("(")[1].split(")")[0]:void 0,m=(u&&Ed({lowValue:u,isSide1:c===2,tiebreakTo:t}))??[],[d,l]=a||[],[f,g]=i||m||[];return{side1Score:d,side2Score:l,side1TiebreakScore:f,side2TiebreakScore:g,winningSide:c,setNumber:o}}}function bo({matchUp:t}){let{extension:e}=ut({name:dm,element:t});if(!e)return{error:je};let{history:r=[],undoHistory:n=[]}=e.value;return{history:r,undoHistory:n,...R}}function p_(t){if(!t)return{error:et};let{matchUp:e,updateScore:r}=t;if(!e)return{error:or};let n=bo({matchUp:e})?.history||[];if(!Array.isArray(n))return{error:G,info:"history is not an array"};let{matchUpFormat:o}=e;if(!o)return{error:vu};if(!Sr({matchUpFormat:o}))return{error:ol};let i=Ze(o),{bestOf:s,finalSetFormat:a,setFormat:c}=i,u=["0","15","30","40","A","G"],p={sets:[]},m=[],d,l=[0,0],f=1,g=0,I,h=0,S=N=>[1,2].includes(N),T=()=>(g+=1,{winningSide:void 0,side1Score:0,side2Score:0,setNumber:g,games:[]}),A=()=>({winningSide:void 0,points:[]}),P=()=>({winningSide:void 0,side1Score:"",side2Score:"",shots:[]}),y=P(),E=A(),U=T(),M=0;for(let N of n){M+=1,I=p.sets.length+1===s;let C=I&&a?a:c,{tiebreakAt:D,setTo:O,NoAD:b,tiebbreakFormat:_}=C,L=U.side1Score===D&&U.side1Score===U.side2Score,F=!!C.tiebreakSet,w=F?C.tiebreakSet:_,{tiebreakTo:x,NoAD:H}=w||{},V=()=>{d=void 0,l=[0,0],f=3-f,U.side1TiebreakScore=0,U.side2TiebreakScore=0,U.side1PointScore="",U.side2PointScore="",h=0},W=Y=>{U.winningSide=Y;let{s:k,...K}=U;p.sets.push(K),y=P(),E=A(),U=T(),V()},B=Y=>{E.winningSide=Y;let{g:k,...K}=E;U.games.push(K),y=P(),E=A(),V();let X=`side${Y}Score`;U[X]+=1},q=Y=>{y.winningSide=Y;let{p:k,...K}=y;E.points.push(K),y=P(),h=0;let X=()=>l.reduce((it,ot)=>it+ot)%4/4>.5?f:3-f,$=Y-1;if(L||F){l[$]+=1,d=X(),U[`side${Y}TiebreakScore`]=l[$],U[`side${3-Y}TiebreakScore`]=l[1-$];let nt=H?1:2;if(l[$]>=x&&l[$]>=l[1-$]+nt)return B(Y),{gameCompleted:!0}}else if(l[1-$]===4&&l[$]===3?l[1-$]-=1:l[$]+=1,U.side1PointScore=u[l[0]],U.side2PointScore=u[l[1]],l[$]===5||l[$]===4&&l[1-$]<3||b&&l[$]===4)return B(Y),{gameCompleted:!0}};if(S(N.srv)&&(f=N.srv),["p","s","g","o"].includes(N.u)&&m.push(N.u),N.shotOutcome&&(y.shots.push(N),N.shotType==="SERVE"&&["OUT","NET"].includes(N.shotOutcome)&&(h+=1),h===2)){let k=3-f;q(k)}if(S(N.p)||lt(N.pointNumber)){let Y=N.winningSide||N.p;if(q(Y)?.gameCompleted)continue}if(S(N.g)||lt(N.gameNumber)){let Y=N.winningSide||N.g;E.winningSide=Y;let k=`side${Y}Score`,K=`side${3-Y}Score`;if(m.length&&(m.includes("p"),m=[]),B(Y),U[k]===O&&U[k]-U[K]>=(b?1:2)&&(W(Y),I))break}if(S(N.s)||lt(N.setNumber)){let Y=N.winningSide||N.s;if(W(Y),m.length&&(m.includes("p"),m.includes("g"),m=[]),I)break}}return M!==n.length&&console.log({error:"Match completed with excess history"}),(U.side1Score||U.side2Score||U.games.length||U.side1TiebreakScore||U.side2TiebreakScore)&&p.sets.push(U),p.scoreStringSide1=Ko({...p,matchUpFormat:o}),p.scoreStringSide2=Ko({...p,matchUpFormat:o,reversed:!0}),f=d||f,r&&(e.score=p),{...R,servingSide:f,score:p}}function Oo({undoHistory:t,history:e,matchUp:r}){return gt({element:r,extension:{value:{history:e,undoHistory:t},name:dm}})}function m_({matchUp:t,sideNumber:e}){if(![1,2].includes(e))return{error:il};let{history:r=[]}=bo({matchUp:t});return r.push({srv:e}),Oo({matchUp:t,history:r})}function d_({matchUp:t}){return Oo({matchUp:t})}function l_({matchUp:t,point:e}){if(!e||!t)return{error:et};if(typeof e!="object")return{error:G,context:{point:e}};let{history:r=[]}=bo({matchUp:t});return r.push(e),Oo({matchUp:t,history:r})}function f_({matchUp:t,game:e}){if(typeof e!="object")return{error:G,context:{game:e}};let{history:r=[]}=bo({matchUp:t});return r.push(e),Oo({matchUp:t,history:r})}function g_({matchUp:t,shot:e}){if(typeof e!="object")return{error:et};let{history:r=[]}=bo({matchUp:t});return r.push(e),Oo({matchUp:t,history:r})}function I_({matchUp:t,set:e}){if(typeof e!="object")return{error:et};let{history:r=[]}=bo({matchUp:t});return r.push(e),Oo({matchUp:t,history:r})}function h_({matchUp:t}){let{history:e=[],undoHistory:r=[]}=bo({matchUp:t});return r.length&&e.push(r.pop()),Oo({matchUp:t,history:e,undoHistory:r})}function S_({matchUp:t}){let{history:e=[],undoHistory:r=[]}=bo({matchUp:t});return r.push(e.pop()),Oo({matchUp:t,history:e,undoHistory:r})}var T_={};var cT={collectionDefinitions:[{collectionName:"Male Singles",matchUpFormat:"SET3-S:6/TB7",matchUpType:"SINGLES",matchUpCount:4,matchUpValue:1,gender:"MALE"},{collectionName:"Female Singles",matchUpFormat:"SET3-S:6/TB7",matchUpType:"SINGLES",gender:"FEMALE",matchUpCount:4,matchUpValue:1},{collectionName:"Male Doubles",matchUpFormat:"SET1-S:8/TB7@7",matchUpType:"DOUBLES",matchUpCount:2,matchUpValue:1,gender:"MALE"},{collectionName:"Female Doubles",matchUpFormat:"SET1-S:8/TB7@7",matchUpType:"DOUBLES",gender:"FEMALE",matchUpCount:2,matchUpValue:1},{collectionName:"Mixed Doubles",matchUpFormat:"SET1-S:8/TB7@7",matchUpType:"DOUBLES",matchUpCount:4,matchUpValue:1,gender:"MIXED"}],tieFormatName:"USTA_GOLD_TEAM_CHALLENGE",winCriteria:{valueGoal:9}};var uT={collectionDefinitions:[{collectionName:"Round 1",matchUpCount:3,matchUpFormat:"SET1-S:T20",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Round 2",matchUpCount:3,matchUpFormat:"SET1-S:T20",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Round 3",matchUpCount:3,matchUpFormat:"SET1-S:T20",matchUpType:"DOUBLES",scoreValue:1}],tieFormatName:"Doubles Shuffle",unrestrictedSelections:!0,winCriteria:{aggregateValue:!0}};var pT={collectionDefinitions:[{collectionName:"Male Singles",gender:"MALE",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{collectionName:"Female Singles",gender:"FEMALE",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{collectionName:"Mixed Doubles",gender:"MIXED",matchUpCount:3,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1}],tieFormatName:"USTA_SOUTHERN_LEVEL_5",winCriteria:{valueGoal:8}};var mT={collectionDefinitions:[{category:{ageCategoryCode:"16U"},collectionName:"16U Singles",matchUpCount:4,matchUpFormat:"SET3-S:6/TB7",matchUpType:"SINGLES",matchUpValue:1},{category:{ageCategoryCode:"18U"},collectionName:"18U Singles",matchUpCount:4,matchUpFormat:"SET3-S:6/TB7",matchUpType:"SINGLES",matchUpValue:1},{category:{ageCategoryCode:"16U"},collectionName:"16U Doubles",matchUpCount:2,matchUpFormat:"SET1-S:6/TB7",matchUpType:"DOUBLES",matchUpValue:1},{category:{ageCategoryCode:"18U"},collectionName:"18U Doubles",matchUpCount:2,matchUpFormat:"SET1-S:6/TB7",matchUpType:"DOUBLES",matchUpValue:1},{collectionName:"Tiebreak Doubles",matchUpCount:1,matchUpFormat:"SET1-S:TB10",matchUpType:"DOUBLES",matchUpValue:1,processCodes:["RANKING.IGNORE"]}],tieFormatName:"USTA_SECTION_BATTLE",winCriteria:{valueGoal:9}};var dT={collectionDefinitions:[{collectionName:"Male Singles",gender:"MALE",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{collectionName:"Female Singles",gender:"FEMALE",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{collectionName:"Male Doubles",gender:"MALE",matchUpCount:1,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1},{collectionName:"Female Doubles",gender:"FEMALE",matchUpCount:1,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1},{collectionName:"Mixed Doubles",gender:"MIXED",matchUpCount:1,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1}],tieFormatName:"USTA_INTERSECTIONAL",winCriteria:{valueGoal:8}};var lT={collectionDefinitions:[{scoreValue:1,matchUpType:"SINGLES",collectionName:"Men's Singles",matchUpFormat:"SET1-S:T60",gender:"MALE",matchUpCount:1},{scoreValue:1,matchUpType:"SINGLES",collectionName:"Women's Singles",matchUpFormat:"SET1-S:T60",gender:"FEMALE",matchUpCount:1},{matchUpValue:1,matchUpType:"DOUBLES",collectionName:"Mixed Doubles",matchUpFormat:"SET1-S:T60",gender:"MIXED",matchUpCount:1}],tieFormatName:"Time Tennis Pro Circuit",winCriteria:{aggregateValue:!0}};var fT={collectionDefinitions:[{collectionName:"Mixed Doubles",gender:"MIXED",matchUpCount:1,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1},{collectionName:"Male Singles",matchUpCount:1,gender:"MALE",matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{collectionName:"Female Singles",gender:"FEMALE",matchUpCount:1,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1}],tieFormatName:"DOMINANT_DUO_MIXED",winCriteria:{valueGoal:2}};var gT={collectionDefinitions:[{scoreValue:1,matchUpType:"SINGLES",collectionName:"Men's Singles",matchUpFormat:"SET1-S:T60",gender:"MALE",matchUpCount:3},{scoreValue:1,matchUpType:"SINGLES",collectionName:"Women's Singles",matchUpFormat:"SET1-S:T60",gender:"FEMALE",matchUpCount:3},{scoreValue:1,matchUpType:"DOUBLES",collectionName:"Men's Doubles",matchUpFormat:"SET1-S:T60",gender:"MALE",matchUpCount:1},{matchUpValue:1,matchUpType:"DOUBLES",collectionName:"Women's Doubles",matchUpFormat:"SET1-S:T60",gender:"FEMALE",matchUpCount:1},{matchUpValue:1,matchUpType:"DOUBLES",collectionName:"Mixed Doubles",matchUpFormat:"SET1-S:T60",gender:"MIXED",matchUpCount:1}],tieFormatName:"Time Tennis Dual",winCriteria:{aggregateValue:!0}};var IT={collectionDefinitions:[{category:{ageCategoryCode:"14U"},collectionName:"14U Singles",matchUpCount:2,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{category:{ageCategoryCode:"16U"},collectionName:"16U Singles",matchUpCount:2,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{category:{ageCategoryCode:"18U"},collectionName:"18U Singles",matchUpCount:2,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{category:{ageCategoryCode:"14U"},collectionName:"14U Doubles",collectionGroupNumber:1,matchUpCount:1,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1},{category:{ageCategoryCode:"16U"},collectionName:"16U Doubles",collectionGroupNumber:1,matchUpCount:1,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1},{category:{ageCategoryCode:"18U"},collectionName:"18U Doubles",collectionGroupNumber:1,matchUpCount:1,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1}],collectionGroups:[{groupNumber:1,groupName:"Doubles",groupValue:1,winCriteria:{valueGoal:2}}],tieFormatName:"USTA_BREWER_CUP",winCriteria:{valueGoal:4}};var hT={winCriteria:{valueGoal:23},tieFormatName:"USTA_OZAKI_CUP",collectionDefinitions:[{category:{ageCategoryCode:"18U"},matchUpFormat:"SET3-S:6/TB7-F:TB10",collectionName:"18U Boys Singles",matchUpType:"SINGLES",matchUpCount:3,matchUpValue:1,gender:"MALE"},{category:{ageCategoryCode:"18U"},matchUpFormat:"SET3-S:6/TB7-F:TB10",collectionName:"18U Girls Singles",matchUpType:"SINGLES",gender:"FEMALE",matchUpCount:3,matchUpValue:1},{category:{ageCategoryCode:"18U"},collectionName:"18U Boys Doubles",matchUpFormat:"SET1-S:8/TB8",matchUpType:"DOUBLES",matchUpCount:1,matchUpValue:1,gender:"MALE"},{category:{ageCategoryCode:"18U"},collectionName:"18U Girls Doubles",matchUpFormat:"SET1-S:8/TB8",matchUpType:"DOUBLES",gender:"FEMALE",matchUpCount:1,matchUpValue:1},{category:{ageCategoryCode:"18U"},collectionName:"18U Mixed Doubles",matchUpFormat:"SET1-S:8/TB8",matchUpType:"DOUBLES",gender:"MIXED",matchUpCount:1,matchUpValue:1},{category:{ageCategoryCode:"16U"},matchUpFormat:"SET3-S:6/TB7-F:TB10",collectionName:"16U Boys Singles",matchUpType:"SINGLES",matchUpCount:3,matchUpValue:1,gender:"MALE"},{category:{ageCategoryCode:"16U"},matchUpFormat:"SET3-S:6/TB7-F:TB10",collectionName:"16U Girls Singles",matchUpType:"SINGLES",gender:"FEMALE",matchUpCount:3,matchUpValue:1},{category:{ageCategoryCode:"16U"},collectionName:"16U Boys Doubles",matchUpFormat:"SET1-S:8/TB8",matchUpType:"DOUBLES",matchUpCount:1,matchUpValue:1,gender:"MALE"},{category:{ageCategoryCode:"16U"},collectionName:"16U Girls Doubles",matchUpFormat:"SET1-S:8/TB8",matchUpType:"DOUBLES",gender:"FEMALE",matchUpCount:1,matchUpValue:1},{category:{ageCategoryCode:"16U"},collectionName:"16U Mixed Doubles",matchUpFormat:"SET1-S:8/TB8",matchUpType:"DOUBLES",gender:"MIXED",matchUpCount:1,matchUpValue:1},{category:{ageCategoryCode:"14U"},matchUpFormat:"SET3-S:6/TB7-F:TB10",collectionName:"14U Boys Singles",matchUpType:"SINGLES",matchUpCount:3,matchUpValue:1,gender:"MALE"},{category:{ageCategoryCode:"14U"},matchUpFormat:"SET3-S:6/TB7-F:TB10",collectionName:"14U Girls Singles",matchUpType:"SINGLES",gender:"FEMALE",matchUpCount:3,matchUpValue:1},{category:{ageCategoryCode:"14U"},collectionName:"14U Boys Doubles",matchUpFormat:"SET1-S:8/TB8",matchUpType:"DOUBLES",matchUpCount:1,matchUpValue:1,gender:"MALE"},{category:{ageCategoryCode:"14U"},collectionName:"14U Girls Doubles",matchUpFormat:"SET1-S:8/TB8",matchUpType:"DOUBLES",gender:"FEMALE",matchUpCount:1,matchUpValue:1},{category:{ageCategoryCode:"14U"},collectionName:"14U Mixed Doubles",matchUpFormat:"SET1-S:8/TB8",matchUpType:"DOUBLES",gender:"MIXED",matchUpCount:1,matchUpValue:1},{category:{ageCategoryCode:"12U"},matchUpFormat:"SET3-S:6/TB7-F:TB10",collectionName:"12U Boys Singles",matchUpType:"SINGLES",matchUpCount:3,matchUpValue:1,gender:"MALE"},{category:{ageCategoryCode:"12U"},matchUpFormat:"SET3-S:6/TB7-F:TB10",collectionName:"12U Girls Singles",matchUpType:"SINGLES",gender:"FEMALE",matchUpCount:3,matchUpValue:1},{category:{ageCategoryCode:"12U"},collectionName:"12U Boys Doubles",matchUpFormat:"SET1-S:8/TB8",matchUpType:"DOUBLES",matchUpCount:1,matchUpValue:1,gender:"MALE"},{category:{ageCategoryCode:"12U"},collectionName:"12U Girls Doubles",matchUpFormat:"SET1-S:8/TB8",matchUpType:"DOUBLES",gender:"FEMALE",matchUpCount:1,matchUpValue:1},{category:{ageCategoryCode:"12U"},collectionName:"12U Mixed Doubles",matchUpFormat:"SET1-S:8/TB8",matchUpType:"DOUBLES",gender:"MIXED",matchUpCount:1,matchUpValue:1}]};var ST={collectionDefinitions:[{collectionName:"Doubles",matchUpCount:1,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1},{collectionName:"Singles",matchUpCount:2,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1}],tieFormatName:"DOMINANT_DUO",winCriteria:{valueGoal:2}};var TT={collectionDefinitions:[{collectionName:"Doubles",matchUpCount:3,matchUpFormat:"SET1-S:8/TB7@7",matchUpType:"DOUBLES",collectionValue:1},{collectionName:"Singles",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1}],tieFormatName:"USTA_COLLEGE",winCriteria:{valueGoal:4}};var AT={collectionDefinitions:[{collectionName:"Male Singles",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7",matchUpType:"SINGLES",matchUpValue:1},{collectionName:"Female Singles",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7",matchUpType:"SINGLES",matchUpValue:1},{collectionName:"Male Doubles",matchUpCount:3,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1},{collectionName:"Female Doubles",matchUpCount:3,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1}],tieFormatName:"USTA_LEVEL_1",winCriteria:{valueGoal:10}};var yT={collectionDefinitions:[{collectionName:"Female Doubles",gender:"FEMALE",matchUpCount:1,matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Male Doubles",gender:"MALE",matchUpCount:1,matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Female Singles",gender:"FEMALE",matchUpCount:1,matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"SINGLES",scoreValue:1},{collectionName:"Male Singles",matchUpCount:1,gender:"MALE",matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"SINGLES",scoreValue:1},{collectionName:"Mixed Doubles",matchUpCount:1,gender:"MIXED",matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Mixed Doubles",matchUpCount:1,gender:"MIXED",matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Overtime",matchUpCount:1,gender:"MIXED",matchUpFormat:"SET1-S:T20",matchUpType:"DOUBLES",scoreValue:1}],tieFormatName:"USTA_WTT_ITT",winCriteria:{aggregateValue:!0}};var ET={collectionDefinitions:[{collectionName:"Male Singles",gender:"MALE",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{collectionName:"Female Singles",gender:"FEMALE",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{collectionName:"Male Doubles",gender:"MALE",matchUpCount:3,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1},{collectionName:"Female Doubles",gender:"FEMALE",matchUpCount:3,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1},{collectionName:"Mixed Doubles",gender:"MIXED",matchUpCount:1,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1}],tieFormatName:"USTA_ZONAL",winCriteria:{valueGoal:10}};var UT={collectionDefinitions:[{collectionGroupNumber:1,matchUpType:"DOUBLES",matchUpCount:1,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpValue:1},{collectionGroupNumber:1,matchUpType:"SINGLES",matchUpCount:3,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpValue:1},{collectionGroupNumber:2,matchUpType:"DOUBLES",matchUpCount:1,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpValue:2},{collectionGroupNumber:2,matchUpType:"SINGLES",matchUpCount:3,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpValue:2},{collectionGroupNumber:3,matchUpType:"DOUBLES",matchUpCount:1,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpValue:3},{collectionGroupNumber:3,matchUpType:"SINGLES",matchUpCount:3,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpValue:3}],collectionGroups:[{groupNumber:1,groupName:"Day 1"},{groupNumber:2,groupName:"Day 2"},{groupNumber:3,groupName:"Day 3"}],tieFormatName:"LAVER_CUP",winCriteria:{valueGoal:13}};var PT={collectionDefinitions:[{collectionName:"Female Doubles",gender:"FEMALE",matchUpCount:1,matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Male Doubles",gender:"MALE",matchUpCount:1,matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Female Singles",gender:"FEMALE",matchUpCount:1,matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"SINGLES",scoreValue:1},{collectionName:"Male Singles",matchUpCount:1,gender:"MALE",matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"SINGLES",scoreValue:1},{collectionName:"Mixed Doubles",matchUpCount:1,gender:"MIXED",matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Overtime",matchUpCount:1,gender:"MIXED",matchUpFormat:"SET1-S:T20",matchUpType:"DOUBLES",scoreValue:1}],tieFormatName:"USTA_TOC",winCriteria:{aggregateValue:!0}};var NT="COLLEGE_DEFAULT",DT="COLLEGE_JUCO",MT="COLLEGE_D3",YP="DOMINANT_DUO",qP="DOMINANT_DUO_MIXED",$P="LAVER_CUP",KP="TEAM_DOUBLES_3_AGGREGATION",zP="TIME_TENNIS_DUAL",QP="TIME_TENNIS_PRO_CIRCUIT",XP="USTA_BREWER_CUP",JP="USTA_OZAKI_CUP",ZP="USTA_COLLEGE",tN="USTA_GOLD_TEAM_CHALLENGE",eN="USTA_LEVEL_1",rN="USTA_INTERSECTIONAL",nN="USTA_SECTION_BATTLE",oN="USTA_SOUTHERN_LEVEL_5",iN="USTA_TOC",sN="USTA_WTT_ITT",aN="USTA_ZONAL",A_={COLLEGE_D3:MT,COLLEGE_DEFAULT:NT,COLLEGE_JUCO:DT,DOMINANT_DUO:YP,DOMINANT_DUO_MIXED:qP,LAVER_CUP:$P,TEAM_DOUBLES_3_AGGREGATION:KP,TIME_TENNIS_DUAL:zP,TIME_TENNIS_PRO_CIRCUIT:QP,USTA_BREWER_CUP:XP,USTA_OZAKI_CUP:JP,USTA_COLLEGE:ZP,USTA_GOLD_TEAM_CHALLENGE:tN,USTA_INTERSECTIONAL:rN,USTA_LEVEL_1:eN,USTA_SECTION_BATTLE:nN,USTA_SOUTHERN_LEVEL_5:oN,USTA_TOC:iN,USTA_WTT_ITT:sN,USTA_ZONAL:aN};var E_="STANDARD",y_={[E_]:{hydrate:!0,doubles:{matchUpCount:3,matchUpValue:1},singles:{matchUpCount:6,matchUpValue:1},valueGoal:5},[MT]:{hydrate:!0,doubles:{matchUpCount:3,matchUpValue:1,matchUpFormat:"SET1-S:8/TB7@7"},singles:{matchUpFormat:on,matchUpCount:6,matchUpValue:1},tieFormatName:MT,valueGoal:5},[NT]:{hydrate:!0,doubles:{matchUpCount:3,collectionValue:1,matchUpFormat:on},singles:{matchUpCount:6,matchUpValue:1,matchUpFormat:on},tieFormatName:NT,valueGoal:4},[DT]:{hydrate:!0,doubles:{matchUpCount:3,matchUpValue:1,matchUpFormat:"SET1-S:8/TB7"},singles:{matchUpCount:6,matchUpValue:1,matchUpFormat:on},tieFormatName:DT,valueGoal:5},[$P]:UT,[YP]:ST,[qP]:fT,[KP]:uT,[zP]:gT,[QP]:lT,[XP]:IT,[JP]:hT,[ZP]:TT,[tN]:cT,[rN]:dT,[eN]:AT,[nN]:mT,[oN]:pT,[sN]:yT,[iN]:PT,[aN]:ET},Sk=t=>{let e=t?.namedFormat&&Object.keys(y_).includes(t.namedFormat)?t.namedFormat:E_,r=Array.isArray(t?.uuids)?t?.uuids:[],n,{category:o,gender:i}=t?.event??{},s=J(y_[e],!1,!0),a=c=>{if(!t?.isMock&&!t?.event?.isMock||!t.event)return r?.pop()??Mt();let u=t?.event?.eventId;return r.pop()??`${u}-COL-${c+1}`};return s.hydrate?(n={winCriteria:{valueGoal:s.valueGoal},collectionDefinitions:[{collectionId:a(0),matchUpFormat:UU,collectionName:"Doubles",matchUpType:jt,...s.doubles},{collectionId:a(1),matchUpFormat:on,collectionName:"Singles",matchUpType:ee,...s.singles}]},s.tieFormatName&&(n.tieFormatName=s.tieFormatName)):(s.collectionDefinitions.forEach((c,u)=>c.collectionId=a(u)),n=s),t?.hydrateCollections&&n.collectionDefinitions.forEach(c=>{o&&!c.category&&(c.category=o),i&&!c.gender&&(c.gender=i)}),n},Li=Sk;function U_(t){let{existingDrawDefinition:e,hydrateCollections:r,enforceGender:n,tieFormatName:o,matchUpType:i,eventType:s,isMock:a,event:c}=t,{tieFormat:u,matchUpFormat:p}=t;if(i===Le&&s===Le){let m=e?.structures?.find(({stage:d})=>d===tt)?.tieFormat;u=u||m||o&&c?.tieFormat?.tieFormatName===o&&c.tieFormat||o&&Li({namedFormat:o,hydrateCollections:r,isMock:a,event:c})||c?.tieFormat||Li({event:c,isMock:a,hydrateCollections:r}),p=void 0}else p||(u=void 0,c?.matchUpFormat||(p=on));if(u){let m=cr({gender:c?.gender,enforceGender:n,tieFormat:u});if(m.error)return m}return{tieFormat:u,matchUpFormat:p}}function P_(t){let e=t.drawDefinition,{existingQualifyingPlaceholderStructureId:r,drawEntries:n,appliedPolicies:o,structureId:i,idPrefix:s,isMock:a}=t,c=t.qualifyingProfiles,u=c?.length?hS({uuids:t.uuids,qualifyingProfiles:c,appliedPolicies:o,idPrefix:s,isMock:a}):void 0;if(u?.error)return u;e.structures=e.structures?.filter(({structureId:S})=>S!==r),e.links=e.links?.filter(({source:S})=>S.structureId!==r);let{qualifiersCount:p,qualifyingDrawPositionsCount:m,qualifyingDetails:d}=u??{};m&&(u?.structures&&e.structures?.push(...u.structures),u?.links&&e.links?.push(...u.links));let l=e.structures?.find(({stage:S,stageSequence:T})=>S===tt&&T===1),{qualifiersCount:f}=os({stageSequence:1,drawDefinition:e,structureId:i,stage:tt}),g=Math.max(p??0,f??0),I=xh({qualifiersCount:g,drawDefinition:e,stage:tt});if(I.error||(I=gp({drawSize:m,stage:at,drawDefinition:e}),I.error))return I;Tk({drawDefinition:e,drawEntries:n});let h=Ak({mainStructure:l,qualifyingDetails:d,drawDefinition:e});return h.error?h:{drawDefinition:e,structureId:i}}function Tk({drawDefinition:t,drawEntries:e}){for(let r of(e??[]).filter(({entryStage:n})=>n===at)){let n={...r,entryStage:r.entryStage??tt,drawDefinition:t};Th(n)}}function Ak({mainStructure:t,qualifyingDetails:e,drawDefinition:r}){for(let n of e||[]){let{finalQualifyingRoundNumber:o,finalQualifyingStructureId:i,roundTarget:s,finishingPositions:a,linkType:c}=n,u=t&&ya({targetStructureId:t.structureId,sourceStructureId:i,sourceRoundNumber:o,finishingPositions:a,targetEntryRound:s,linkType:c})?.link;if(u?.error)return u;u&&(r.links||(r.links=[]),r.links.push(u))}return{error:void 0}}function CT(t){let{participantIds:e}=t,r=t.drawDefinition?.entries?.filter(n=>{let o=n.entryStatus;return!t.restrictEntryStatus||Mr.includes(o)}).map(ft)??[];if(e){let n=e.filter(o=>!r?.includes(o));if(n?.length)return v({result:{error:sn},info:{invalidParticipantIds:n}})}else e=r;return t.roundsCount&&t.restrictRoundsCount!==!1&&t.roundsCount>e.length-1&&(!t.enableDoubleRobin||t.roundsCount>(e.length-1)*2)?{error:G,info:"Not enough participants for roundsCount"}:t.roundsCount&&t.roundsCount>25?{error:G,info:"roundsCount must be less than 25"}:{participantIds:e}}function Md(t){let e=[],{roundsCount:r=1,drawDefinition:n,matchUpsCount:o,structureId:i,idPrefix:s,isMock:a,event:c}=t,u,p=CT(t);if(p.error)return p;for(let m of Z(1,r+1)){let d=Su({restrictMatchUpsCount:t.restrictMatchUpsCount,ignoreLastRoundNumber:!!u,newRound:!u,drawDefinition:n,matchUpsCount:o,structureId:i,roundNumber:u,idPrefix:s,isMock:a,event:c});if(d.error)return v({result:d,info:{iteration:m}});d.matchUps?.length&&e.push(...d.matchUps),u=(d?.roundNumber??1)+1}return{matchUps:e}}function Cd(t){let e=Uk(t);if(e?.error)return e;let r=CT(t);if(r.error)return r;let n=Ek(t);if(n.error)return n;let o=yk(t),i=t.tournamentRecord?.isMock??t.isMock,s=t.eventType??t.event?.eventType,a=[],c=[],u;for(let p of Z(1,(t.roundsCount??1)+1)){let m=ud({...t,participantIds:r.participantIds,structure:n.structure,ignoreLastRoundNumber:!0,iterationMatchUps:a,adHocRatings:o,roundNumber:u,eventType:s,isMock:i});if(m.error)return m;let{matchUps:d,...l}=m;c.push({...l,iteration:p,matchUpsCount:d?.length}),u=(l?.roundNumber??1)+1,d?.length&&a.push(...d)}return{...R,matchUps:a,roundResults:c}}function N_({scaleType:t=Yi,scaleAccessor:e,participant:r,scaleName:n,eventType:o}){let a=(r&&no({scaleAttributes:{eventType:o??vs,scaleType:t,scaleName:n},participant:r}))?.scaleItem?.scaleValue;return e&&Ct(a)?a[e]:a}function yk(t){let{tournamentRecord:e,participantIds:r,scaleAccessor:n,scaleName:o,eventType:i,adHocRatings:s={}}=t,a=e.participants??[];for(let c of r??[]){let u=a?.find(m=>m.participantId===c),p=N_({scaleName:`${o}.${MI}`,scaleAccessor:n,participant:u,eventType:i});!p&&o&&(p=N_({scaleAccessor:n,participant:u,scaleName:o,eventType:i})),p&&!s[c]&&(s[c]=p)}return s}function Ek(t){if(t.structureId)return t.structureId;let e=t.drawDefinition,r=e?.structures?.filter(i=>i.stageSequence===1)?.reduce((i,s)=>{let a=s.stage&&Ds[s.stage];return Br({drawDefinition:e,structure:s})&&a>(Ds[i?.stage]||1)?s:i},void 0),n=e?.structures?.find(i=>i.structureId===r?.structureId);return n?Br({drawDefinition:e,structure:n})?{structure:n}:{error:Js}:{error:_t}}function Uk(t){return t.roundsCount&&typeof t.roundsCount!="number"?{error:G,info:"roundsCount must be a number"}:typeof t.drawDefinition!="object"||t.drawDefinition.drawType&&t.drawDefinition.drawType!==br?{error:Js}:!Array.isArray(t.drawDefinition?.entries)&&t.participantIds&&!Array.isArray(t.participantIds)?{error:G,info:"Missing Entries"}:{error:void 0}}function D_(t){let{tournamentRecord:e,drawDefinition:r,structureId:n,idPrefix:o,isMock:i,event:s}=t,a=s?.entries?.filter(({entryStage:p,entryStatus:m})=>(!p||p===tt)&&m&&Mr.includes(m)),c=a?.map(ft),u=a?Math.floor(a.length/2):0;if(t.automated)return Pk({...t,participantIds:c});{let p=Md({roundsCount:t.roundsCount,drawDefinition:r,matchUpsCount:u,idPrefix:o,isMock:i,event:s});if(p.error)return p;p.matchUps?.length&&rd({matchUps:p.matchUps,suppressNotifications:!0,tournamentRecord:e,drawDefinition:r,structureId:n,event:s})}return{...R}}function Pk(t){let{restrictEntryStatus:e,generateMatchUps:r,structureId:n,matchUpIds:o,scaleName:i}=t.drawMatic??{},s=Cd({...t,eventType:t.drawMatic?.eventType??t.matchUpType,generateMatchUps:r??!0,participantIds:t.participantIds,roundsCount:t.roundsCount,restrictEntryStatus:e,structureId:n,matchUpIds:o,scaleName:i});return s.error?s:(s?.matchUps?.length&&rd({tournamentRecord:t.tournamentRecord,drawDefinition:t.drawDefinition,suppressNotifications:!0,matchUps:s.matchUps,event:t.event,structureId:n}),{...R})}function M_({requireParticipantCount:t=!0,enforcePolicyLimits:e=!0,drawSizeProgression:r,participantsCount:n,participantCount:o,appliedPolicies:i,drawDefinition:s,seedingProfile:a,structureId:c,seedsCount:u}){n=n??o;let p=st({drawDefinition:s,structureId:c});if(p.error)return p;let m=p.structure;if(!m)return{error:_t};let{positionAssignments:d}=de({structure:m}),l=d?.length||0;if(u>l)return{error:BA};let f=m.structures?.length,g=lt(a?.groupSeedingThreshold)&&a?.groupSeedingThreshold,I=Lf({roundRobinGroupsCount:f,drawSize:l})?.seedGroups,{seedsCount:h}=gu({policyDefinitions:i,requireParticipantCount:t,drawSizeProgression:r,participantsCount:n,drawSize:l});return h&&i?.[In]&&u>h&&e&&(u=h),m.seedLimit=u,m.seedAssignments=Z(1,u+1).map(S=>{let T=I?.find(y=>y.includes(S)),A=T&&Math.min(...T),P=g&&S>=g?A:S;return{participantId:void 0,seedNumber:S,seedValue:P}}),Rt({drawDefinition:s,structureIds:[c]}),{...R,seedLimit:u}}function RT(t){let e="prepareStage",{drawDefinition:r}=t,{structures:n}=Cn({stageSequence:t.stageSequence||1,roundTarget:t.roundTarget,stage:t.stage,drawDefinition:r}),o=t.preparedStructureIds||[],i=n?.find(({structureId:l})=>!o.includes(l));if(!i)return v({result:{error:_t},stack:e});let s=i?.structureId,{seedsCount:a,stageEntries:c,seedLimit:u}=_k({...t,structureId:s});(t.seededParticipants||t.event||t.seedingScaleName)&&Mk({...t,seedsCount:a,structure:i,structureId:s});let p=t.automated!==!1&&t.drawType!==br&&!(t.qualifyingOnly&&t.stage!==at),m=(n?.length||0)>1,d=p?Dk({...t,multipleStructures:m,seedLimit:u,structureId:s}):{};return d?.error?v({result:d,stack:e}):{...d,stageEntries:c,structureId:s,seedsCount:a}}function Nk({entries:t,stage:e,stageSequence:r,roundTarget:n}){return t.filter(o=>{let i=ut({name:cn,element:o})?.extension?.value;return(!o.entryStage||o.entryStage===e)&&(!r||!o.entryStageSequence||o.entryStageSequence===r)&&(!n||!i||i===n)&&Vo.includes(o.entryStatus)})}function Dk(t){let e=typeof t.automated=="object"&&t.automated.seedsOnly,r=uc({...t,seedsOnly:e});if(r.error)return r;let n=r?.positionAssignments,o=r?.positioningReport;return{conflicts:r.conflicts,positionAssignments:n,positioningReport:o}}function Mk(t){let{seededParticipants:e,seedingScaleName:r,entries:n,event:o}=t,i=n.map(ft);e?Ck({...t,enteredParticipantIds:i}):(o||r)&&Rk({...t,enteredParticipantIds:i})}function Ck(t){let{provisionalPositioning:e,enteredParticipantIds:r,seededParticipants:n,tournamentRecord:o,appliedPolicies:i,drawDefinition:s,seedingProfile:a,structureId:c,structure:u,event:p}=t,m=u?as({provisionalPositioning:e,appliedPolicies:i,drawDefinition:s,seedingProfile:a,structure:u}):void 0;n.filter(({participantId:d})=>r.includes(d)).filter(d=>!d.seedNumber||d.seedNumber<=n.length).sort((d,l)=>d.seedNumber<l.seedNumber?-1:d.seedNumber<l.seedNumber?1:0).forEach(d=>{let{participantId:l,seedNumber:f,seedValue:g}=d;Gs({provisionalPositioning:e,tournamentRecord:o,drawDefinition:s,seedingProfile:a,participantId:l,seedBlockInfo:m,structureId:c,seedNumber:f,seedValue:g,event:p})})}function Rk(t){let e=t.seedsCount,{provisionalPositioning:r,enteredParticipantIds:n,seedAssignmentProfile:o,assignSeedsCount:i,tournamentRecord:s,drawDefinition:a,seedByRanking:c,seedingProfile:u,structureId:p,event:m}=t,{categoryName:d,ageCategoryCode:l}=m?.category||{},f=m?.eventType,g=bk({...t,ageCategoryCode:l,categoryName:d,eventType:f})||c&&Ok({...t,ageCategoryCode:l,categoryName:d,eventType:f}),I=g?.length??0;I<e&&(e=I),g?.filter(({participantId:h})=>n.includes(h)).slice(0,i||e).forEach((h,S)=>{let T=S+1,{participantId:A,scaleValue:P}=h,y=o?.[T]||P||T;Gs({provisionalPositioning:r,tournamentRecord:s,drawDefinition:a,seedingProfile:u,participantId:A,structureId:p,seedNumber:T,seedValue:y,event:m})})}function bk(t){let{tournamentRecord:e,seedingScaleName:r,stageSequence:n,entries:o,stage:i,event:s}=t,{categoryName:a,ageCategoryCode:c}=s?.category||{},u=s?.eventType,p={scaleName:r||a||c||s.eventId,scaleType:Qn,eventType:u};return ks({scaleAttributes:p,tournamentRecord:e,stageSequence:n,entries:o,stage:i}).scaledEntries}function Ok(t){let{tournamentRecord:e,stageSequence:r,event:n,entries:o,stage:i}=t,{categoryName:s,ageCategoryCode:a}=n?.category||{},c=n?.eventType;return ks({scaleAttributes:{scaleName:s||a,scaleType:Zo,eventType:c},tournamentRecord:e,stageSequence:r,entries:o,stage:i}).scaledEntries}function _k(t){let{seedsCount:e}=t;t.seededParticipants&&(e=t.seededParticipants.length),e>t.drawSize&&(e=t.drawSize);let r=Nk(t);e>r.length&&(e=r.length);let{seedLimit:n}=M_({enforcePolicyLimits:t.enforcePolicyLimits??!0,appliedPolicies:t.appliedPolicies,participantsCount:r.length,seedingProfile:t.seedingProfile,drawDefinition:t.drawDefinition,structureId:t.structureId,seedsCount:e});return n&&n<e&&(e=n),{seedsCount:e,stageEntries:r,seedLimit:n}}function C_(t){let e=cd({...t,modifyOriginal:!1});if(e.error)return e;let r=e.drawDefinition,{ignoreStageSpace:n,appliedPolicies:o,qualifyingOnly:i,seedingProfile:s,participants:a,drawEntries:c,placeByes:u,drawSize:p,drawType:m,entries:d}=t,l=[],f=[],g=vk({ignoreStageSpace:n,drawDefinition:r,drawEntries:c,drawType:m,entries:d});if(g.error)return g;let I=m===Mi?0:ct(t.seedsCount??0),h=RT({...t,qualifyingOnly:!p||i,appliedPolicies:o,drawDefinition:r,seedingProfile:s,participants:a,stage:tt,seedsCount:I,placeByes:u,drawSize:p,entries:d});if(h.error&&!h.conflicts)return h;h.positioningReport?.length&&l.push({[tt]:h.positioningReport});let S=h.structureId;return h.conflicts&&(f=h.conflicts),m===br&&t.roundsCount&&D_({...t,drawDefinition:r,structureId:S}),{drawDefinition:r,positioningReports:l,conflicts:f,structureId:S}}function vk(t){let{ignoreStageSpace:e,drawDefinition:r,drawEntries:n,drawType:o,entries:i}=t;for(let s of i){if(n&&s.entryStage&&s.entryStage!==tt)continue;let a={...s,ignoreStageSpace:e??o===br,entryStage:s.entryStage??tt,drawDefinition:r,drawType:o},c=Th(a);if(n&&c.error)return c}return{error:void 0}}var xk=()=>({matchUpType:void 0,drawName:void 0,drawId:void 0,structures:[],entries:[],links:[]});var R_=xk;function b_(t){let{drawId:e=Mt(),processCodes:r,matchUpType:n,drawType:o}=t??{},i=R_();return Object.assign(i,{processCodes:r,matchUpType:n,drawType:o,drawId:e})}function Rd(t){let e=t.structureIds,{tournamentRecord:r,drawDefinition:n,matchUpFormat:o,structureId:i,matchUpId:s,event:a}=t;if(!n)return{error:z};if(!o)return{error:vu};if(!Sr({matchUpFormat:o}))return{error:ka};let c="setMatchUpFormat";if(s){let u=xt({drawDefinition:n,matchUpId:s,event:a});if(u.error)return u;if(!u.matchUp)return{error:De};let p=u.matchUp;if(p?.matchUpType===Le)return{error:ze,info:"Cannot set matchUpFormat when { matchUpType: TEAM }"};p.matchUpFormat=o,ht({tournamentId:r?.tournamentId,eventId:a?.eventId,context:c,drawDefinition:n,matchUp:p})}else if(Array.isArray(e)){if(a?.eventType===Le)return{error:yo};for(let u of e){let p=st({drawDefinition:n,structureId:u});if(p.error)return p;if(p.structure)p.structure.matchUpFormat=o;else return{error:_t}}}else if(i){if(a?.eventType===Le)return{error:yo};let u=st({drawDefinition:n,structureId:i});if(u.error)return u;if(u.structure)u.structure.matchUpFormat=o;else return{error:_t}}else n&&(n.matchUpFormat=o);return e=e??(i?[i]:void 0),Rt({drawDefinition:n,structureIds:e}),{...R}}function O_({tieFormat:t}){let e=cr({checkCollectionIds:!1,tieFormat:t});if(e.error)return e;for(let r of t.collectionDefinitions)r.collectionId||(r.collectionId=Mt());return{tieFormat:t}}function __({tournamentRecord:t,drawDefinition:e,matchUpFormat:r,matchUpType:n,tieFormat:o,event:i}){if((r||o)&&!(r&&i?.matchUpFormat===r||i?.tieFormat&&o&&JSON.stringify(i.tieFormat)===JSON.stringify(o))){if(o){let a=O_({tieFormat:o});if(a.error)return a;e.tieFormat=a.tieFormat??o}else if(r){let a=Rd({tournamentRecord:t,drawDefinition:e,matchUpFormat:r,event:i});if(a.error)return{info:"matchUpFormat or tieFormat error",error:a.error}}n&&(e.matchUpType=n)}return{error:void 0}}var mN={};ne(mN,{attachPolicies:()=>wi,findPolicy:()=>Bo,getAppliedPolicies:()=>yt,getPolicyDefinitions:()=>Io,mutate:()=>uN,query:()=>pN,removePolicy:()=>cN});var uN={};ne(uN,{attachPolicies:()=>wi,removePolicy:()=>cN});function cN(t){let e=vt(t,[{[yC]:!0,_anyOf:{[ye]:!1,[Fn]:!1,[Ei]:!1,[$a]:!1}}]);if(e.error)return e;let r,n=t.drawDefinition??t.event??((t.tournamentId||!t.tournamentRecords)&&t.tournamentRecord);if(n)return v_(t,n);if(t.tournamentRecords){let o=Object.keys(t.tournamentRecords);if(!o.length)return{error:j};for(let i of o){let s=t.tournamentRecords[i],a=v_(t,s);if(a.error)return a;r=!0}}else return{error:j};return r?{...R}:{error:Mc}}function v_(t,e){let r=yt(t).appliedPolicies??{};return r[t.policyType]?(delete r[t.policyType],Object.keys(r).length?gt({element:e,extension:{name:Fc,value:r}}):rr({element:e,name:Fc}),{...R}):{error:Mc}}var pN={};ne(pN,{findPolicy:()=>Bo,getAppliedPolicies:()=>yt,getPolicyDefinitions:()=>Io});function x_({appliedPolicies:t,policyDefinitions:e,drawDefinition:r,stack:n}){if(e&&typeof e!="object")return v({info:"policyDefinitions must be an object",result:{error:G},stack:n});let o={[wc]:t?.[wc]};return e?wk({policyDefinitions:e,appliedPolicies:t,policiesToAttach:o,drawDefinition:r}):o.avoidance&&wi({drawDefinition:r,policyDefinitions:o}),!t?.[In]&&!e?.[In]&&(wi({policyDefinitions:cg,drawDefinition:r}),t&&Object.assign(t,cg)),{error:void 0}}function wk({policyDefinitions:t,appliedPolicies:e,policiesToAttach:r,drawDefinition:n}){for(let o of Object.keys(t))JSON.stringify(e?.[o])!==JSON.stringify(t[o])&&(r[o]=t[o]);Object.keys(r).length&&(wi({policyDefinitions:r,drawDefinition:n}),e&&Object.assign(e,r))}function w_(t){let{tournamentRecord:e,matchUpFormat:r,appliedPolicies:n,policyDefinitions:o,matchUpType:i,tieFormat:s,drawType:a,stack:c,event:u}=t,p=t.drawId?u?.drawDefinitions?.find(h=>h.drawId===t.drawId):void 0;p&&a!==p.drawType&&(p.drawType=a);let m=p??b_({processCodes:t.processCodes,drawId:t.drawId,drawType:a}),d=__({tournamentRecord:e,drawDefinition:m,matchUpFormat:r,matchUpType:i,tieFormat:s,event:u});if(d.error)return v({result:d,stack:c});let l=x_({appliedPolicies:n,policyDefinitions:o,drawDefinition:m,stack:c});if(l.error)return l;let f=p?.structures?.find(h=>h.stage===tt&&h.stageSequence===1)?.structureId,g=p?p.structures?.filter(h=>h.stage===at):[],I=g?.length===1&&!g[0].matchUps?.length&&g[0].structureId;return{drawDefinition:m,structureId:f,existingDrawDefinition:p,existingQualifyingPlaceholderStructureId:I}}function L_(t){let e="generateOrGetExisting",r=[],n=[],o=w_(t);if(o.error)return v({result:o,stack:e});let i=o.existingDrawDefinition,s=o.drawDefinition??{},a=o.structureId,c=t.drawEntries??t.eventEntries??[],u=o.existingQualifyingPlaceholderStructureId&&P_({...t,...o})||C_({...t,...o,entries:c});return u.error?v({result:u,stack:e}):(u.positioningReports?.length&&r.push(...u.positioningReports??[]),u.conflicts?.length&&n.push(...u.conflicts??[]),s=u.drawDefinition,a=u.structureId,{existingDrawDefinition:i,positioningReports:r,drawDefinition:s,structureId:a,conflicts:n,entries:c})}function F_(t){let{qualifyingPlaceholder:e,qualifyingProfiles:r,existingDrawDefinition:n,positioningReports:o,appliedPolicies:i,qualifyingOnly:s,drawDefinition:a,seedingProfile:c,participants:u,structureId:p,entries:m,stack:d}=t,l=e&&!r?.length&&!n,f=[];if(r){let g=(T,A)=>T.stageSequence-A.stageSequence,I=(T,A)=>T.roundTarget-A.roundTarget,h=[],S=1;r.sort(I);for(let T of r){if(!Array.isArray(T.structureProfiles))return v({info:Tn("structureProfiles"),result:{error:et},stack:d});S=T.roundTarget||S;let A=T.structureProfiles?.sort(g)||[],P=1;for(let y of A){let{qualifyingRoundNumber:E,qualifyingPositions:U,seededParticipants:M,seedingScaleName:N,seedsCount:C=0,seedByRanking:D,placeByes:O,drawSize:b}=y,_=RT({...t,seedingProfile:y.seedingProfile??c,stageSequence:P,qualifyingRoundNumber:E,preparedStructureIds:h,qualifyingPositions:U,seededParticipants:M,stage:at,seedingScaleName:N,appliedPolicies:i,drawDefinition:a,qualifyingOnly:s,seedByRanking:D,participants:u,roundTarget:S,seedsCount:C,placeByes:O,drawSize:b,entries:m});if(_.error)return _;_.structureId&&h.push(_.structureId),P+=1,_.conflicts?.length&&f.push(..._.conflicts),_.positioningReport?.length&&o.push({[at]:_.positioningReport})}S+=1}}else if(p&&l){let g=Xr({structureName:Be(at),stage:at}),{link:I}=ya({sourceStructureId:g.structureId,targetStructureId:p,sourceRoundNumber:0,linkType:kn});a.structures||(a.structures=[]),a.structures.push(g),a.links||(a.links=[]),a.links.push(I)}return{qualifyingConflicts:f,error:void 0}}function Uu(t){let{voluntaryConsolation:e,tournamentRecord:r,event:n}=t,o="generateDrawDefinition",{participants:i,participantMap:s}=$t({withIndividualParticipants:!0,convertExtensions:!0,internalUse:!0,tournamentRecord:r}),a=n?.entries?.filter(b=>b.entryStatus&&[...Mr,Pm].includes(b.entryStatus))??[],c=_O({...t,participantMap:s,participants:i,eventEntries:a});if(c.error)return v({result:c,stack:o});let{appliedPolicies:u,policyDefinitions:p,drawSize:m,drawType:d,enforceGender:l,seedingProfile:f}=c,g=n?.eventType,I=t.matchUpType??g,h=U_({...t,enforceGender:l,eventType:g,matchUpType:I});if(h.error)return v({result:h,stack:o});let{matchUpFormat:S,tieFormat:T}=h;if(t.drawId&&typeof t.drawId!="string")return v({result:{error:G},stack:o});let P=L_({...t,isMock:t.isMock??!0,policyDefinitions:p,tournamentRecord:r,appliedPolicies:u,matchUpFormat:S,seedingProfile:f,participants:i,eventEntries:a,matchUpType:I,tieFormat:T,drawSize:m,drawType:d,event:n});if(P.error)return v({result:P,stack:o});let{existingDrawDefinition:y,positioningReports:E,drawDefinition:U,structureId:M,conflicts:N,entries:C}=P;if(!U)return v({result:{error:G},stack:o});let D=F_({...t,existingDrawDefinition:y,positioningReports:E,appliedPolicies:u,drawDefinition:U,seedingProfile:f,participants:i,structureId:M,entries:C,params:t,stack:o});if(D.error)return D;let{qualifyingConflicts:O}=D;return U.drawName=t.drawName??(d&&Be(d)),m&&typeof e=="object"&&m>=4&&_f({...e,drawDefinition:U,matchUpType:I}),{existingDrawDefinition:!!y,qualifyingConflicts:O,positioningReports:E,drawDefinition:U,structureId:M,...R,conflicts:N}}var TN={};ne(TN,{addDrawEntries:()=>Rf,addEventEntries:()=>Wn,addEventEntryPairs:()=>IN,destroyPairEntries:()=>eU,destroyPairEntry:()=>Of,getEntriesAndSeedsCount:()=>nd,getMaxEntryPosition:()=>_S,modifyEntriesStatus:()=>Lm,modifyEventEntries:()=>hN,mutate:()=>SN,promoteAlternate:()=>fN,promoteAlternates:()=>OT,query:()=>mP,removeDrawEntries:()=>gN,removeEventEntries:()=>sc,setEntryPosition:()=>bT,setEntryPositions:()=>lN});var SN={};ne(SN,{addDrawEntries:()=>Rf,addEventEntries:()=>Wn,addEventEntryPairs:()=>IN,destroyPairEntries:()=>eU,destroyPairEntry:()=>Of,modifyEntriesStatus:()=>Lm,modifyEventEntries:()=>hN,promoteAlternate:()=>fN,promoteAlternates:()=>OT,removeDrawEntries:()=>gN,removeEventEntries:()=>sc,setEntryPosition:()=>bT,setEntryPositions:()=>lN});function bT({tournamentRecord:t,drawDefinition:e,participantId:r,entryPosition:n,skipRefresh:o,event:i}){let s="setEntryPositions";if(!t)return{error:j};if(!r)return v({result:{error:te},stack:s});if(n!==void 0&&!Number.isSafeInteger(n))return{error:G,entryPosition:n};(i?.entries||[]).forEach(c=>{c.participantId===r&&(c.entryPosition=n)}),(e?.entries||[]).forEach(c=>{c.participantId===r&&(c.entryPosition=n)});let a=c=>{c.entries.forEach(u=>{u.entryPosition===n&&u.participantId!==r&&(u.entryPosition+=.1)})};return o||(i?.entries&&(a(i),i.entries=xn({entries:i.entries})),e?.entries&&(a(e),e.entries=xn({entries:e.entries}))),{...R}}function lN({tournamentRecord:t,entryPositions:e,drawDefinition:r,event:n}){if(!t)return{error:j};if(!Array.isArray(e))return{error:G};for(let o of e){let{participantId:i,entryPosition:s}=o,a=bT({skipRefresh:!0,tournamentRecord:t,drawDefinition:r,participantId:i,entryPosition:s,event:n});if(a.error)return a}return n?.entries&&(n.entries=xn({entries:n.entries})),r?.entries&&(r.entries=xn({entries:r.entries})),{...R}}function fN(t){let{participantId:e}=t;return e&&typeof e!="string"?{error:G,participantId:e}:OT({...t,participantIds:[e].filter(Boolean)})}function OT({tournamentRecord:t,drawDefinition:e,participantIds:r,stageSequence:n,stage:o=tt,eventId:i,event:s}){if(!t)return{error:j};if(!Array.isArray(r))return{error:G,participantIds:r};if(!s)return{error:St};let a="promoteAlternates";if(s){let c=G_({element:s,participantIds:r,stageSequence:n,stage:o});if(c.error)return c}if(e){let c=G_({element:e,participantIds:r,stageSequence:n,stage:o});if(c.error)return i?v({context:{drawPromotionError:c.error,drawId:e.drawId},result:{...R},stack:a}):c}return{...R}}function G_({participantIds:t,stageSequence:e,element:r,stage:n}){let o=(r.entries||[]).filter(m=>m.entryStatus===Or),i=(r.entries||[]).filter(m=>t.includes(m.participantId)),s=o.reduce((m,d)=>{let{entryPosition:l}=d;return isNaN(l)&&m||(!m||l<m.entryPosition)&&d||m},void 0),a=i.length?i:[s].filter(Boolean);if(!a?.length)return{error:nI};let c=a.filter(({entryStatus:m})=>m!==Or);if(c.length)return{error:dl,invalidEntryStatus:c};let u=a.filter(({entryStage:m})=>m&&m!==n);if(u.length)return{error:KM,invalidStage:u};let p=e&&a.filter(m=>m.stageSequence!==e);if(p?.length)return{error:zM,invalidStageSequence:p};for(let m of a){m.entryStatus=qr;let d=m?.entryPosition;isNaN(d)||r.entries.forEach(f=>{f.entryStatus===Or&&f.entryPosition>d&&(f.entryPosition=f.entryPosition-1)});let l=Math.max(...r.entries.filter(f=>f.entryStatus===qr&&!isNaN(f.entryPosition)).map(({entryPosition:f})=>ct(f||0)),0);m.entryPosition=l||0}return{...R}}function gN({autoEntryPositions:t=!0,participantIds:e,drawDefinition:r,drawId:n,stages:o,event:i}){if(!i)return{error:St};if(!n)return{error:Ur};if(!e?.length)return{error:so};let s=di({drawDefinition:r,stages:o}).assignedParticipantIds??[];if(ve(s,e))return{error:ys};let c=m=>{let d=m.participantId;return!e.includes(d)},{flightProfile:u}=kt({event:i}),p=u?.flights?.find(m=>m.drawId===n);return p?.drawEntries&&(p.drawEntries=p.drawEntries.filter(c),t&&(p.drawEntries=xn({entries:p.drawEntries}))),r?.entries&&(r.entries=r.entries.filter(c),t&&(r.entries=xn({entries:r.entries}))),{...R}}function dn(t){let e="addParticipant",{allowDuplicateParticipantIdPairs:r,returnParticipant:n,disableNotice:o,pairOverride:i,participant:s}=t,a=t.tournamentId?t.tournamentRecords?.[t.tournamentId]:t.tournamentRecord??(t.activeTournamentId&&t.tournamentRecords?.[t.activeTournamentId]);if(!a)return{error:j};if(!s)return v({result:{error:Ai},stack:e});s.participantId||(s.participantId=Mt()),a.participants||(a.participants=[]);let{participantId:c,individualParticipantIds:u}=s;if(a.participants.reduce((I,h)=>h.participantId===c||I,!1))return{error:my};let{participantType:m,participantRole:d}=s;if(!m||!Object.keys(zc).includes(m))return{error:tn,participantType:m};if(!d)return{error:py};let l=a.participants||[],f=l.filter(I=>I.participantType===It).map(I=>I.participantId);if(m!==It&&s.person)return{error:G,person:s.person};if(u&&!Array.isArray(u))return{error:G,individualParticipantIds:u};if(m===pt){if(s.person)return{error:G,person:s.person};if(s.individualParticipantIds){if(s.individualParticipantIds.length!==2&&!i)return v({info:"PAIR must be 2 individualParticipantIds",result:{error:Hr},stack:e});{let S=l.filter(A=>A.participantType===It).map(A=>A.participantId);if(!Array.isArray(s.individualParticipantIds))return v({result:{error:Hr},stack:e});if(!s.individualParticipantIds.reduce((A,P)=>S.includes(P)&&A,!0))return v({result:{error:Hr},stack:e})}}else return v({result:{error:so},stack:e});let I=l.filter(S=>S.participantType===pt).map(S=>({individualParticipantIds:S.individualParticipantIds,participant:S})),h=s.participantType===pt&&I.find(S=>Wt(S.individualParticipantIds,s.individualParticipantIds).length===2);if(h&&!r)return{...R,existingParticipant:!0,participant:n&&J(h.participant)};if(!s.participantName){let S=l.filter(A=>s.individualParticipantIds?.includes(A.participantId)),T=S.map(A=>A.person?.standardFamilyName).filter(Boolean).join("/");S.length===1&&(T+="/Unknown"),s.participantName=T}}else if(m===It){if(!s.person?.standardFamilyName||!s.person?.standardGivenName)return{error:gy};if(!s.participantName){let I=`${s.person.standardFamilyName.toUpperCase()}, ${s.person.standardGivenName}`;s.participantName=I}}else if(m&&[Lt,hr].includes(m)){if(u||(s.individualParticipantIds=[]),s.individualParticipantIds?.length)for(let I of s.individualParticipantIds){if(typeof I!="string")return v({result:{participantId:I,error:G},stack:e});if(!f.includes(I))return v({result:{participantId:I,error:Jt},stack:e})}}else return{error:tn};a.participants.push(s),o||Tt({payload:{tournamentId:a.tournamentId,participants:[s]},topic:Go});let g={participant:n&&J(s),...R};return rt(g)}function ln({allowDuplicateParticipantIdPairs:t,returnParticipants:e,tournamentRecord:r,participants:n=[]}){if(!r)return{error:j};r.participants||(r.participants=[]);let i=r.participants.map(d=>d.participantId)||[];n.forEach(d=>{d.participantId||(d.participantId=Mt())});let s=n.filter(d=>!i.includes(d.participantId)),a=n.filter(d=>i.includes(d.participantId)),c=s.filter(d=>d.participantType===It),u=s.filter(d=>d.participantType!==It),p=c.concat(...u),m=[];if(p.length){for(let l of p){let f=dn({allowDuplicateParticipantIdPairs:t,returnParticipant:!0,disableNotice:!0,tournamentRecord:r,participant:l});if(f.error)return f;f.success&&!f.existingParticipant&&m.push(f.participant)}m.length&&Tt({topic:Go,payload:{tournamentId:r.tournamentId,participants:m}});let d={participants:e&&J(m),addedCount:m.length,...R};return a.length&&Object.assign(d,{notAdded:a,info:Lu}),rt(d)}else return{info:"No new participants to add",addedCount:0,...R}}function IN({allowDuplicateParticipantIdPairs:t,entryStage:e=tt,entryStatus:r=Or,participantIdPairs:n=[],tournamentRecord:o,drawDefinition:i,event:s,uuids:a}){if(!o)return{error:j};if(!s)return{error:St};if(s.eventType!==jt)return{error:yo};let c=[],u=new Map;for(let S of o.participants??[]){let{participantType:T,participantId:A,person:P,individualParticipantIds:y}=S;T===It&&P?.sex?u.set(A,P.sex):T===pt&&y&&c.push(y)}let p=n.filter(S=>{if(S.length!==2||!u.has(S[0])||!u.has(S[1]))return!0;if(!s.gender||s.gender===On)return!1;let T=S.map(P=>u.get(P)),A=s.gender===Zt&&(T[0]!==Zt||T[1]!==Zt)||s.gender===ce&&(T[0]!==ce||T[1]!==ce);return s.gender===Cr&&(T.sort(ou),(T[0]!==ce||T[1]!==Zt)&&(A=!0)),A});if(p.length)return{error:Hr,invalidParticipantIdPairs:p};let m=n.map(S=>({participantId:a?.pop()??Mt(),participantRole:Fe,individualParticipantIds:S,participantType:pt})),d=t?m:m.filter(S=>!c.find(T=>Wt(T,S.individualParticipantIds).length===2)),l,f=[];if(d){let S=ln({allowDuplicateParticipantIdPairs:t,participants:d,returnParticipants:!0,tournamentRecord:o});if(S.error)return S;f=S.participants||[],l=S.info}let g=n.map(S=>{let T=f.find(P=>Wt(P.individualParticipantIds,S).length===2);if(T)return T;let{participant:A}=zr({tournamentRecord:o,participantIds:S});return A}).map(S=>S.participantId),I=Wn({participantIds:g,tournamentRecord:o,drawDefinition:i,entryStatus:r,entryStage:e,event:s});d.length&&Tt({payload:{participants:d},topic:Go});let h=d.map(ft);return{...I,info:l,newParticipantIds:h}}function hN({entryStatus:t=qr,unpairedParticipantIds:e=[],participantIdPairs:r=[],entryStage:n=tt,tournamentRecord:o,event:i}){if(!o)return{error:j};if(!i)return{error:St};let s=o.participants??[],a=s.filter(h=>h.participantType===It).map(h=>h.participantId),u=e.concat(...r).flat(1/0).filter(h=>!a.includes(h));if(u.length)return{error:Hr,invalidParticipantIds:u};let p=r.filter(h=>h.length!==2);if(p.length)return{error:Hr,invalidParticipantIdPairs:p};let m=s.filter(h=>h.participantType===pt).map(h=>h.individualParticipantIds),l=r.filter(h=>!m.find(S=>Wt(S,h).length===2)).map(h=>({participantType:pt,participantRole:Fe,individualParticipantIds:h})),f=ln({participants:l,tournamentRecord:o});if(f.error)return f;let g=r.map(h=>{let{participant:S}=zr({tournamentRecord:o,participantIds:h});return S}).map(h=>({participantId:h,entryStatus:t,entryStage:n})),I=e.map(h=>({entryStatus:_r,participantId:h,entryStage:n}));return i.entries=(i.entries??[]).filter(h=>h.entryStage===n),i.entries=i.entries.concat(...g,...I),{...R}}var _N={};ne(_N,{addDrawDefinition:()=>wp,addEvent:()=>Sc,addFlight:()=>Lp,assignSeedPositions:()=>MN,attachFlightProfile:()=>Tg,bulkUpdatePublishedEventIds:()=>Rp,categoryCanContain:()=>Zm,deleteDrawDefinitions:()=>xp,deleteEvents:()=>RN,deleteFlightAndFlightDraw:()=>NN,deleteFlightProfileAndFlightDraws:()=>EN,getCategoryAgeDetails:()=>mu,getEvent:()=>KS,getEventProperties:()=>qS,getEventStructures:()=>Gf,getEventTimeItem:()=>ru,getEvents:()=>$S,getFlightProfile:()=>kt,getScaledEntries:()=>ks,modifyEvent:()=>bN,modifyEventMatchUpFormatTiming:()=>UN,modifyPairAssignment:()=>DN,mutate:()=>ON,query:()=>TP,refreshEventDrawOrder:()=>Sg,removeEventMatchUpFormatTiming:()=>bd,removeScaleValues:()=>Ag,removeSeeding:()=>CN,setEventDates:()=>PN,setEventDisplay:()=>Od,setEventEndDate:()=>xT,setEventStartDate:()=>vT,updateDrawIdsOrder:()=>hg,validateCategory:()=>Jm});var ON={};ne(ON,{addDrawDefinition:()=>wp,addEvent:()=>Sc,addFlight:()=>Lp,assignSeedPositions:()=>MN,attachFlightProfile:()=>Tg,deleteDrawDefinitions:()=>xp,deleteEvents:()=>RN,deleteFlightAndFlightDraw:()=>NN,deleteFlightProfileAndFlightDraws:()=>EN,modifyEvent:()=>bN,modifyEventMatchUpFormatTiming:()=>UN,modifyPairAssignment:()=>DN,refreshEventDrawOrder:()=>Sg,removeEventMatchUpFormatTiming:()=>bd,removeScaleValues:()=>Ag,removeSeeding:()=>CN,setEventDates:()=>PN,setEventDisplay:()=>Od,setEventEndDate:()=>xT,setEventStartDate:()=>vT,updateDrawIdsOrder:()=>hg,validateCategory:()=>Jm});function qs({removePriorValues:t=!0,status:e=$r,statusObject:r,event:n}){if(!Ct(r))return{error:G};let o=Qr({event:n,status:e}),i=`${Ho}.${Wo}`,s={itemValue:{[e]:{...o,...r}},itemType:i};return xi({timeItem:s,removePriorValues:t,event:n})}function fg(t){let{tournamentParticipants:e=[],includePositionAssignments:r,policyDefinitions:n,tournamentRecord:o,inContext:i=!0,usePublishState:s,drawDefinition:a,publishStatus:c,noDeepCopy:u,sortConfig:p,context:m,event:d}=t;if(!a)return{error:z};let l=(({matchUpFormat:U,updatedAt:M,drawType:N,drawName:C,drawId:D})=>({matchUpFormat:U,updatedAt:M,drawName:C,drawType:N,drawId:D}))(a),f,g,{allStructuresLinked:I,sourceStructureIds:h,hasDrawFeedProfile:S,structureGroups:T}=au({drawDefinition:a});if(!I)return{error:KA};let A=!1,P=!1,E=T.map(U=>{let M={},N=U.map(C=>{let{structure:D}=st({drawDefinition:a,structureId:C}),{seedAssignments:O}=vr({drawDefinition:a,structure:D});return D?.stage===tt&&D.stageSequence===1&&(f=O),D?.stage===at&&D.stageSequence===1&&(g=O),D}).sort((C,D)=>ri(C,D,p)).map(C=>{if(!C)return;let D=C?.structureId,O=[];C.stage&&[tt,Ge,ae].includes(C.stage)&&(O=f),C?.stage===at&&(O=g);let{matchUps:b,roundMatchUps:_,roundProfile:L}=Pt({seedAssignments:C?.seedAssignments?.length?void 0:O,context:{drawId:l.drawId,...m},tournamentParticipants:e,policyDefinitions:n,tournamentRecord:o,usePublishState:s,publishStatus:c,drawDefinition:a,inContext:i,structure:C,event:d}),{positionAssignments:F}=Dt({structure:C}),w=F?.filter(Dr(zn)).map(V=>{P=!0;let{drawPosition:W,participantId:B}=V,{extension:q}=ut({element:V,name:wo});return q&&{drawPosition:W,participantId:B,participantResult:q.value}}).filter(V=>V?.participantResult);if(!w?.length&&b.length&&t.allParticipantResults){let{subOrderMap:V}=jh({positionAssignments:F}),W=Ua({matchUpFormat:C.matchUpFormat,policyDefinitions:n,subOrderMap:V,matchUps:b});w=F?.map(B=>{let{drawPosition:q,participantId:Y}=B;return Y&&W.participantResults?.[Y]&&{participantResult:W.participantResults[Y],participantId:Y,drawPosition:q}}).filter(B=>B?.participantResult)}let x=C?(({stageSequence:V,structureName:W,structureType:B,matchUpFormat:q,stage:Y})=>({stageSequence:V,structureName:W,structureType:B,matchUpFormat:q,stage:Y}))(C):{};x.sourceStructureIds=h[D],x.hasDrawFeedProfile=S[D],x.positionAssignments=F,x.structureActive=b.reduce((V,W)=>{let B=[me,Lo,bt,mr,Ot,Sn,Me,fe].includes(W.matchUpStatus);return V||B||!!W.winningSide||!!W.score?.scoreStringSide1},!1);let H=b.reduce((V,W)=>V&&[Ut,me,mr,Ot,bt,kr].includes(W.matchUpStatus),!!b.length);return x.structureCompleted=H,M[D]=H,x.structureActive&&(A=!0),{...x,participantResults:w,seedAssignments:O,roundMatchUps:_,roundProfile:L,structureId:D}});return N.forEach(C=>{r||delete C.positionAssignments,C.sourceStructuresComplete=C.sourceStructureIds?.every(D=>M[D])}),N}).flat();return l.drawActive=A,l.participantPlacements=P,l.drawGenerated=E?.reduce((U,M)=>U||!!M?.roundMatchUps,!1),l.drawCompleted=E?.reduce((U,M)=>U&&M.structureCompleted,!0),{structures:u?E:J(E,!1,!0),drawInfo:u?l:J(l,!1,!0),...R}}function gg(t){let{includePositionAssignments:e,tournamentRecord:r,participantsProfile:n,policyDefinitions:o,usePublishState:i,status:s=$r,sortConfig:a,event:c}=t,u=J(r,!1,!0),p=J(c,!1,!0);if(!u)return{error:j};if(!p)return{error:St};let{eventId:m}=p,{tournamentId:d,endDate:l}=u,f=Qr({event:p,status:s}),{publishState:g}=up({event:p}),{participants:I}=$t({withGroupings:!0,withEvents:!1,withDraws:!1,...n,tournamentRecord:u}),h=({stage:D,drawId:O})=>{if(!i)return!0;let b=f?.drawDetails?.[O]?.stageDetails;return!b||!Object.keys(b).length?!0:b[D]?.published},S=({structureId:D,drawId:O})=>{if(!i)return!0;let b=f?.drawDetails?.[O]?.structureDetails;return!b||!Object.keys(b).length?!0:b[D]?.published},T=({drawId:D})=>i?f.drawDetails?f.drawDetails[D]?.publishingDetail?.published:f.drawIds?f.drawIds.includes(D):!0:!0,A=({drawId:D,structure:O})=>{if(!i)return O;let b=f?.drawDetails?.[D]?.structureDetails?.[O.structureId]?.roundLimit;if(lt(b)){let _=Z(1,b+1),L={},F={};for(let w of _)O.roundMatchUps[w]&&(L[w]=O.roundMatchUps[w],F[w]=O.roundProfile[w]);O.roundMatchUps=L,O.roundProfile=F}return O},y=(p.drawDefinitions||[]).filter(T).map(D=>(({drawInfo:O,structures:b})=>({...O,structures:b}))(fg({allParticipantResults:t.allParticipantResults,context:{eventId:m,tournamentId:d,endDate:l},includePositionAssignments:e,tournamentParticipants:I,noDeepCopy:!0,policyDefinitions:o,tournamentRecord:u,usePublishState:i,drawDefinition:D,publishStatus:f,sortConfig:a,event:p}))).map(({structures:D,...O})=>{let b=D?.filter(({stage:_,structureId:L})=>S({structureId:L,drawId:O.drawId})&&h({stage:_,drawId:O.drawId})).map(_=>A({drawId:O.drawId,structure:_}));return{...O,structures:b}}).filter(D=>D.structures?.length),{tournamentInfo:E}=us({tournamentRecord:u}),M=(u.venues||[]).map(D=>(({venueData:O})=>({...O}))(tu({tournamentRecord:u,venueId:D.venueId}))),N=(({eventId:D,eventName:O,eventType:b,eventLevel:_,surfaceCategory:L,matchUpFormat:F,category:w,gender:x,startDate:H,endDate:V,ballType:W,discipline:B})=>({eventId:D,eventName:O,eventType:b,eventLevel:_,surfaceCategory:L,matchUpFormat:F,category:w,gender:x,startDate:H,endDate:V,ballType:W,discipline:B}))(p),C={tournamentInfo:E,venuesData:M,eventInfo:N,drawsData:y};return C.eventInfo.publishState=g,C.eventInfo.publish=f,{...R,eventData:C}}function $s(t){let{includePositionAssignments:e,removePriorValues:r,tournamentRecord:n,status:o=$r,event:i,drawIdsToRemove:s,drawIdsToAdd:a}=t;if(!n)return{error:j};if(!i)return{error:St};let{appliedPolicies:c}=yt({tournamentRecord:n,event:i}),u={...c,...t.policyDefinitions},p=i.drawDefinitions?.map(({drawId:S})=>S)??[],m=t.drawDetails?Object.keys(t.drawDetails):[],d=m.length?[]:t.drawIds,l=(a??[]).concat(...s??[],...d??[],...m),f=l.filter(S=>!p.includes(S));if(f.length)return v({result:{error:fr},context:{invalidDrawIds:f}});let g=Qr({event:i,status:o}),I=Object.keys(g?.drawDetails||{}).filter(S=>p.includes(S)).reduce((S,T)=>(S[T]=g.drawDetails[T],S),{});for(let S of p)if((!l.length||l.includes(S))&&(s?.includes(S)||d?.length&&!d.includes(S)?I[S]={...I[S],publishingDetail:{published:!1}}:(a?.includes(S)||d?.includes(S)||!d?.length)&&(I[S]={...I[S],publishingDetail:{published:!0}})),t.drawDetails?.[S]){let T=t.drawDetails[S],A=T.structureDetails??I[S].structureDetails,P=T.stageDetails??I[S].stageDetails??{},{structureIdsToRemove:y=[],structureIdsToAdd:E=[],publishingDetail:U={},stagesToRemove:M=[],stagesToAdd:N=[]}=T;if((E||N)&&(U.published=!0),I[S]={publishingDetail:U,structureDetails:A,stageDetails:P},E.length||y.length){let D=(i.drawDefinitions?.find(_=>_.drawId===S)?.structures??[]).map(({structureId:_})=>_),b=(E??[]).concat(y??[]).filter(_=>!D.includes(_));if(b.length)return v({result:{error:_t},context:{invalidStructureIds:b}});A=A??{};for(let _ of D)y.includes(_)?A[_]={published:!1}:A[_]={published:!0};I[S].structureDetails=A}let C=(i.drawDefinitions?.find(D=>D.drawId===S)?.structures??[]).map(({stage:D})=>D);if(N.length){for(let D of N)P[D]={published:!0};for(let D of C)P[D]||(P[D]={published:!1})}if(N.length||M.length){for(let D of M)P[D]={published:!1};for(let D of C)P[D]||(P[D]={published:!0})}(N.length||M.length)&&(I[S].stageDetails=P)}qs({statusObject:{drawDetails:I},removePriorValues:r,status:o,event:i});let{eventData:h}=gg({includePositionAssignments:e,usePublishState:!0,tournamentRecord:n,policyDefinitions:u,event:i});return Tt({payload:{eventData:h,tournamentId:n.tournamentId},topic:DE}),{...R,eventData:h}}var AN="deleteDrawDefinitions",yN="autoSchedulingAudit",_T="deleteEvents",k_={AUTO_SCHEDULING_AUDIT:yN,DELETE_EVENTS:_T,DELETE_DRAW_DEFINITIONS:AN};function xp(t){if(!t.tournamentRecord)return{error:j};let e="deleteDrawDefinitions",r=t.drawIds??[],n=t.event,{autoPublish:o=!0,tournamentRecord:i,auditData:s,eventId:a,force:c}=t,{appliedPolicies:u}=yt({tournamentRecord:i,event:n}),p={...u,...t.policyDefinitions},m=Array.isArray(r)?r[0]:void 0;if(!n){let U=nr({tournamentRecord:i,eventId:a,drawId:m});if(U.error)return U;n=U.event}let d=[],l=[],f=[];if(!n?.drawDefinitions)return v({info:"event has no drawDefinition",result:{...R},stack:e});let g=n.drawDefinitions.map(({drawId:U})=>U);if(r.length||(r=g),r=r.filter(U=>g.includes(U)),!r.length)return v({info:"nothing to do; no matching drawIds in event.",result:{...R},stack:e});let I=J(kt({event:n}).flightProfile,!1,!0),h=({participantId:U,drawPosition:M,qualifier:N,bye:C})=>({bye:C,qualifier:N,drawPosition:M,participantId:U}),S=c??u?.[Mn]?.allowDeletionWithScoresPresent?.drawDefinitions,T=Qr({event:n})??{},A=T.drawIds??(T.drawDetails&&Object.keys(T.drawDetails))??[],P,y=[],E=n.drawDefinitions.filter(U=>{if(r.includes(U.drawId)){let M=ar({event:n,drawDefinition:U})?.matchUps??[];if(M.some(({score:V})=>he({score:V}))&&!S)return y.push(U.drawId),!0;let{drawId:C,drawType:D,drawName:O}=U,b=I?.flights?.find(V=>V.drawId===U.drawId);b&&(b.drawEntries=b.drawEntries?.filter(V=>Mr.includes(V.entryStatus))),A.includes(C)&&(A=A.filter(V=>V!==C),P=!0);let _=Cn({stageSequence:1,drawDefinition:U,stage:tt})?.structures?.[0],F=(_?yp({structureId:_.structureId,tournamentRecord:i,drawDefinition:U}):void 0)?.positionAssignments?.map(h),w=Cn({stage:at,drawDefinition:U})?.structures,x=w?.length?w.map(V=>{let W=V.stageSequence;return{positionAssignments:yp({structureId:V.structureId,tournamentRecord:i,drawDefinition:U})?.positionAssignments.map(h),stageSequence:W}}):void 0,H={action:AN,payload:{drawDefinitions:[U],eventId:a??n?.eventId,auditData:s}};f.push(H),d.push(rt({tournamentId:i.tournamentId,eventId:a??n?.eventId,qualifyingPositionAssignments:x,positionAssignments:F,auditData:s,drawType:D,drawName:O,drawId:C})),M?.forEach(({matchUpId:V})=>l.push(V))}return!r.includes(U.drawId)});if(y.length&&!c)return v({context:{drawIdsWithScoresPresent:y},result:{error:Ul},stack:e});if(n.drawDefinitions=E,I&&po({event:n,extension:{name:Gr,value:I}}),hc({tournamentRecord:i}),P){let U={};for(let N of A)U[N]=T.drawDetails?.[N]??{published:!0};let M=qs({statusObject:{drawDetails:U},event:n});if(M.error)return{error:M.error}}if(f.length&&Tt({topic:pa,payload:f}),l.length&&Rn({tournamentId:i?.tournamentId,matchUpIds:l}),r.forEach(U=>{VC({drawId:U})}),Lk({event:n,deletedDrawsDetail:d,auditData:s}),o&&P){let U=$s({drawIdsToRemove:r,policyDefinitions:p,tournamentRecord:i,event:n});if(U.error)return{...R,info:U.error}}return{...R}}function Lk({event:t,deletedDrawsDetail:e,auditData:r}){let{extension:n}=ut({name:pm,element:t}),o={...r,deletedDrawsDetail:e},i={name:pm,value:Array.isArray(n?.value)?n?.value.concat(o):[o]};gt({element:t,extension:i})}function EN({autoPublish:t=!0,tournamentRecord:e,auditData:r,event:n,force:o}){if(!e)return{error:j};if(!n)return{error:St};let{flightProfile:i}=kt({event:n});if(i){let s=i.flights?.map(({drawId:c})=>c).filter(Boolean),a=xp({eventId:n.eventId,tournamentRecord:e,autoPublish:t,auditData:r,drawIds:s,event:n,force:o});return a.error?a:Ku({event:n,name:Gr})}return{...R}}function Ig(t){let{matchUpFormat:e,recoveryTimes:r,averageTimes:n,tournamentId:o,eventId:i}=t,s=t?.tournamentRecords??(t?.tournamentRecord&&{[t.tournamentRecord.tournamentId]:t.tournamentRecord})??{};if(!Object.keys(s).length)return{error:wt};let a=Object.keys(s).filter(u=>!o||o===u);if(o&&!a.includes(o))return{error:G};let c;for(let u of a){let p=s[u],{event:m}=nr({tournamentRecord:p,eventId:i});i&&m&&(c=!0);let d=Fk({tournamentRecord:p,event:m,matchUpFormat:e,averageTimes:n,recoveryTimes:r});if(d.error)return d}return!i||c?{...R}:{error:Ir}}function Fk({tournamentRecord:t,recoveryTimes:e,matchUpFormat:r,averageTimes:n,event:o}){if(!t)return{error:j};if(n&&!Array.isArray(n))return{error:G};if(e&&!Array.isArray(e))return{error:G};let i=Po;if(o){let{extension:s}=ut({element:o,name:i}),a=s?.value||{},c=V_({...a,matchUpFormat:r,averageTimes:n,recoveryTimes:e});gt({element:o,extension:{name:i,value:c}})}else{let{extension:s}=ut({element:t,name:i}),a=s?.value||{},c=V_({...a,matchUpFormat:r,averageTimes:n,recoveryTimes:e});gt({extension:{name:i,value:c},element:t})}return{...R}}function V_(t){let{matchUpRecoveryTimes:e=[],matchUpAverageTimes:r=[],matchUpFormat:n}=t,{averageTimes:o,recoveryTimes:i}=t;o=(o||[]).filter(c=>c?.categoryNames?.length||c?.categoryTypes?.length);let s=o?.length&&r.map(c=>c?.matchUpFormatCodes.includes(n)?{...c,matchUpFormatCodes:c.matchUpFormatCodes?.filter(u=>u!==n)}:c).filter(({matchUpFormatCodes:c})=>c?.length).concat({matchUpFormatCodes:[n],averageTimes:o});i=(i||[]).filter(c=>c?.categoryNames?.length||c?.categoryTypes?.length);let a=i?.length&&e.map(c=>c?.matchUpFormatCodes.includes(n)?{...c,matchUpFormatCodes:c.matchUpFormatCodes?.filter(u=>u!==n)}:c).filter(({matchUpFormatCodes:c,averageTimes:u})=>c?.length||u).concat({matchUpFormatCodes:[n],recoveryTimes:i});return{matchUpAverageTimes:s?.length&&s||r,matchUpRecoveryTimes:a?.length&&a||e}}function UN(t){let{tournamentRecord:e,recoveryMinutes:r,averageMinutes:n,matchUpFormat:o,categoryType:i,eventId:s,event:a}=t;if(!e)return{error:j};if(!Sr({matchUpFormat:o}))return{error:G};if(!a)return{error:St};let{averageTimes:c=[],recoveryTimes:u=[]}=fd({tournamentRecord:e,matchUpFormat:o,event:a}),p=a.category,m=p?.categoryName||p?.ageCategoryCode||a?.eventId,d={categoryNames:[m],minutes:{}},l={categoryNames:[m],minutes:{}},f=T=>{if(T.categoryTypes?.includes(i)&&console.log("encountered:",{categoryType:i}),!(T.categoryNames?.includes(m)&&(T.categoryNames=T.categoryNames.filter(A=>A!==m),d={minutes:T.minutes,categoryNames:[m]},!T.categoryNames.length)))return T},g=n&&!isNaN(ct(n)),I=r&&!isNaN(ct(r)),h=c.map(f).filter(T=>T?.categoryNames?.length),S=u.map(f).filter(T=>T?.categoryNames?.length);return g&&(Object.assign(d.minutes,{[a?.eventType||ee]:n}),h.push(d)),I&&(Object.assign(l.minutes,{[a?.eventType||ee]:r}),S.push(l)),!g&&!I?{error:G}:Ig({averageTimes:g&&h,recoveryTimes:I&&S,tournamentRecord:e,matchUpFormat:o,eventId:s,event:a})}function bd(t){if(t.event)return B_({event:t.event});{t.tournamentRecord&&!t.tournamentRecords&&(t.tournamentRecords={[t.tournamentRecord.tournamentId]:t.tournamentRecord});let e=vt(t,[{[ye]:!0,[NI]:!0}]);if(e.error)return e;let{tournamentRecords:r,eventId:n}=t;for(let o of Object.values(r??{})){let{event:i}=nr({tournamentRecord:o,eventId:n});if(i)return B_({event:i})}}return{error:Ir}}function B_({event:t}){return Ku({event:t,name:Po})}function vT({tournamentRecord:t,event:e,startDate:r}){if(!t)return{error:j};if(!e)return{error:St};if(!ao.test(r))return{error:ir};let n=H_(t);if(n.error)return n;let{tournamentStartDate:o,tournamentEndDate:i}=n,s=new Date(At(r)).getTime();if(!o||!i||s<o||s>i)return{error:ir};let a=e.endDate&&new Date(At(e.endDate)).getTime();return a&&s>a&&(e.endDate=r),e.startDate=r,{...R}}function xT({tournamentRecord:t,event:e,endDate:r}){if(!t)return{error:j};if(!e)return{error:St};if(!ao.test(r))return{error:ir};let n=H_(t);if(n.error)return n;let{tournamentStartDate:o,tournamentEndDate:i}=n,s=new Date(At(r)).getTime();if(!o||!i||s<o||s>i)return{error:ir};let a=e.startDate&&new Date(At(e.startDate)).getTime();return a&&s<a&&(e.startDate=r),e.endDate=r,{...R}}function PN({tournamentRecord:t,event:e,startDate:r,endDate:n}){if(!t)return{error:j};if(!e)return{error:St};if(!r&&!n)return{error:et,info:"missing date"};if(r&&!ao.test(r))return{error:ir};if(n&&!ao.test(n))return{error:ir};if(r&&n){let o=new Date(At(r)).getTime(),i=new Date(At(n)).getTime();if(o>i)return{error:G}}if(r){let o=vT({tournamentRecord:t,event:e,startDate:r});if(o.error)return o}if(n){let o=xT({tournamentRecord:t,event:e,endDate:n});if(o.error)return o}return{...R}}function H_(t){let{startDate:e,endDate:r}=t;return!ao.test(e)||!ao.test(r)?v({result:{error:sy},context:{startDate:e,endDate:r}}):{tournamentStartDate:new Date(At(e)).getTime(),tournamentEndDate:new Date(At(r)).getTime()}}function hg({event:t,orderedDrawIdsMap:e}){if(typeof t!="object")return{error:St};if(!e)return{error:et,info:"Missing drawIdsOrderMap"};if(typeof e!="object")return{error:G,info:"orderedDrawIdsMap must be an object"};let r=Object.values(e);if(!r.every(i=>!isNaN(i)))return{error:G,info:"drawOrder must be numeric"};if(mt(r).length!==r.length)return{error:G,info:"drawOrder values must be unique"};if(t.drawDefinitions?.length){let i=(t.drawDefinitions||[]).map(({drawId:a})=>a),s=Object.keys(e);if(s?.length&&Wt(i,s).length!==i.length)return{error:G,info:"Missing drawIds"};t.drawDefinitions.forEach(a=>{a.drawOrder=e[a.drawId]})}let{flightProfile:o}=kt({event:t});return o?.flights?.forEach(i=>{i.flightNumber=e[i.drawId]}),{...R}}function Sg({tournamentRecord:t,event:e}){if(!t)return{error:j};if(!e)return{error:St};let{flightProfile:r}=kt({event:e}),n=r?.flights&&Object.assign({},...r.flights.sort((o,i)=>o.flightNumber-i.flightNumber).map((o,i)=>({[o.drawId]:i+1})))||e.drawDefinitions?.length&&Object.assign({},...e.drawDefinitions.sort((o,i)=>o.drawOrder-i.drawOrder).map((o,i)=>({[o.drawId]:i+1})))||void 0;return n?hg({event:e,orderedDrawIdsMap:n}):{...R}}function NN({autoPublish:t=!0,tournamentRecord:e,auditData:r,drawId:n,event:o,force:i}){if(!e)return{error:j};if(!n)return{error:Ur};if(!o)return{error:St};let{flightProfile:s}=kt({event:o});if(s&&s.flights?.find(u=>u.drawId===n)){let u=s.flights.filter(m=>m.drawId!==n),p={name:Gr,value:{...s,flights:u}};po({event:o,extension:p})}if(o.drawDefinitions?.find(c=>c.drawId===n)){let c=xp({drawIds:[n],eventId:o.eventId,tournamentRecord:e,autoPublish:t,auditData:r,event:o,force:i});if(c.error)return c}return Sg({tournamentRecord:e,event:o})}function DN({replacementIndividualParticipantId:t,existingIndividualParticipantId:e,tournamentRecord:r,drawDefinition:n,participantId:o,event:i,uuids:s}){if(!i)return{error:St};if(i?.eventType!==Vr)return{error:yo};if(s&&!Array.isArray(s))return{error:G};if(!r)return{error:j};if(![t,e,o].every(g=>typeof g=="string"))return{error:te};if(!(i?.entries?.filter(({entryStatus:g})=>[_r,oi].includes(g)).map(({participantId:g})=>g)||[]).includes(t))return{error:sn};let c=(r.participants||[]).find(g=>g.participantId===o);if(c?.participantType!==pt)return{error:As,participant:c};let u=c.individualParticipantIds,p=[t,...u.filter(g=>g!==e)],{participant:m}=zr({participantIds:p,tournamentRecord:r}),d;if(m)d=m.participantId;else{let g={participantId:s?.pop(),participantRole:Fe,individualParticipantIds:p,participantType:pt},I=dn({participant:g,returnParticipant:!0,tournamentRecord:r});if(I.error)return I;d=I.participant.participantId}let{flightProfile:l}=kt({event:i});if(n){let g=l?.flights?.find(({drawId:I})=>I===n.drawId);g&&(g.drawEntries=g.drawEntries.map(I=>I.participantId===o?{...I,participantId:d}:I)),n.entries=n.entries.map(I=>I.participantId===o?{...I,participantId:d}:I);for(let I of n.structures||[])if(I.positionAssignments)I.positionAssignments=I.positionAssignments.map(h=>h.participantId===o?{...h,participantId:d}:h);else if(I.structures)for(let h of I.structures)h.positionAssignments=h.positionAssignments.map(S=>S.participantId===o?{...S,participantId:d}:S)}i.entries=i.entries.map(g=>g.participantId===o&&{...g,participantId:d}||g.participantId===t&&{...g,participantId:e}||g);let f=r.events.some(({entries:g,eventId:I,drawDefinitions:h})=>i.eventId===I?h.some(({drawId:S,entries:T})=>S===n?.drawId?!1:T?.find(A=>A.participantId===o)):g?.find(S=>S.participantId===o));if(!f){let g=Oi({addIndividualParticipantsToEvents:!1,participantIds:[o],tournamentRecord:r});if(g.error)return g}return{...R,participantOtherEntries:f,newPairParticipantId:d}}function wp(t){let{flight:e,suppressNotifications:r,modifyEventEntries:n,existingDrawCount:o,allowReplacement:i,checkEntryStatus:s,tournamentRecord:a,drawDefinition:c,event:u}=t;if(!c)return{error:z};if(!u)return{error:St};u.drawDefinitions||(u.drawDefinitions=[]);let{drawId:p,drawName:m,entries:d}=c,{entries:l}=u,f=0;if(o!==void 0&&o!==u.drawDefinitions.length)return{error:G,info:"drawDefintions count mismatch"};let{flightProfile:g}=kt({event:u}),I=e&&g?.flights?.find(b=>b.flightNumber===e.flightNumber),h=g?.links?.find(b=>b?.target?.drawId===p)?.source?.drawId;if(h&&!u.drawDefinitions.find(b=>b.drawId===h))return v({result:{error:z},info:{sourceDrawId:h}});if(I&&I.drawId!==c.drawId)return v({result:{error:Js},info:{relevantFlight:I}});let A=d?.every(({participantId:b,entryStatus:_})=>{let L=I?.drawEntries.find(F=>F.participantId===b);return!_||L?.entryStatus===_}),P=!s||l&&d?.every(({participantId:b,entryStatus:_,entryStage:L})=>l.find(w=>w.participantId===b&&(!w.entryStage||w.entryStage===L))?.entryStatus===_);if(I&&!A)return v({result:{error:Js},context:{drawEntriesPresentInFlight:A,matchingEventEntries:P,relevantFlight:I},info:"Draw entries are not present in flight or do not match entryStatuses"});if(n&&d?.filter(Boolean).forEach(b=>{if(b?.entryStatus&&Mr.includes(b?.entryStatus)){let _=l?.filter(Boolean).find(L=>L.participantId===b.participantId);_&&b.entryStatus&&_?.entryStatus!==b.entryStatus&&(_.entryStatus=b.entryStatus,f+=1)}}),l&&!P)return v({result:{info:"Draw entries do not match event entryStatuses",context:{matchingEventEntries:P,eventEntries:l},error:Js}});let y=g?.flights?.map(({flightNumber:b})=>!isNaN(b)&&ct(b))?.filter(Boolean)||[],E=u.drawDefinitions.map(({drawOrder:b})=>b&&ct(b))?.filter(Boolean)||[],U=Math.max(0,...E,...y)+1,M=g?.flights?.find(b=>b.drawId===p),N;if(M){M.drawName=c.drawName,N={name:Gr,value:{...g,flights:g.flights}};let b=M.flightNumber;b&&!E.includes(b)?U=b:M.flightNumber=U}else{let b=g?.flights||[];b.push({manuallyAdded:!0,flightNumber:U,drawEntries:d,drawName:m,drawId:p}),N={name:Gr,value:{...g||{},flights:b}}}po({event:u,extension:N}),Object.assign(c,{drawOrder:U});let C=u.drawDefinitions.find(b=>b.drawId===p),D=a?.tournamentId,O=u.eventId;if(C){if(!i)return{error:kA};let _=ar({drawDefinition:C})?.matchUps?.map(le)??[],L=ar({drawDefinition:c})?.matchUps;if(!r){_?.length&&Rn({matchUpIds:_,action:"modifyDrawDefinition",tournamentId:D,eventId:O}),L?.length&&lo({matchUps:L,tournamentId:D,eventId:O}),u.drawDefinitions=u.drawDefinitions.map(w=>w.drawId===p?c:w);let F=c.structures?.map(({structureId:w})=>w);Rt({drawDefinition:c,tournamentId:D,structureIds:F,eventId:O})}}else if(u.drawDefinitions.push(c),!r){let{matchUps:b}=ar({drawDefinition:c,event:u});b&&lo({tournamentId:a?.tournamentId,matchUps:b}),ma({drawDefinition:c,tournamentId:D,eventId:O})}return{...R,modifiedEventEntryStatusCount:f}}function MN(t){let{provisionalPositioning:e,useExistingSeedLimit:r,tournamentRecord:n,drawDefinition:o,seedingProfile:i,structureId:s,assignments:a,drawId:c,event:u}=t,p=0;if(!a?.length)return{error:rl};if(!n)return{error:j};if(!c)return{error:Ur};let m=vr({provisionalPositioning:e,drawDefinition:o,structureId:s});if(m.error)return m;let{seedAssignments:d,seedLimit:l}=m,f=Object.assign({},...(d??[]).filter(h=>h.seedNumber).map(h=>({[h.seedNumber]:h})));a.forEach(h=>{let{seedNumber:S}=h;l&&S<=l&&(!r||f[S])&&(f[S]=h)});let g=Object.values(f),I=g.map(h=>h?.participantId).filter(Boolean);if(I.length!==cI(I).length)return{error:VA};for(let h of g){let S=Gs({...h,provisionalPositioning:e,tournamentRecord:n,drawDefinition:o,seedingProfile:i,structureId:s,event:u});if(S?.error)return S;S?.success&&p++}return p?{...R,modifications:p}:{error:Us}}function Tg({deleteExisting:t,event:e,flightProfile:r}){let n="attachFlightProfile";if(!r)return v({result:{error:et},stack:n});if(!e)return v({result:{error:St},stack:n});let{flightProfile:o}=kt({event:e});return o&&!t?v({result:{error:yl},stack:n}):e.drawDefinitions?.length?v({result:{error:LA},stack:n}):(po({event:e,extension:{name:Gr,value:r}}),{flightProfile:J(r,!1,!0),...R})}function W_({tournamentRecord:t,scaleAttributes:e,participantIds:r}){if(!t)return{error:j};if(!r)return{error:so};if(!e)return{error:et,info:"scaleAttributes required"};let{scaleType:n,eventType:o,scaleName:i}=e,s=[LE,n,o,i].join(".");return t.participants?.forEach(a=>{r.includes(a.participantId)&&a.timeItems&&(a.timeItems=a.timeItems.filter(c=>c&&c?.itemType!==s))}),{...R}}function Ag({tournamentRecord:t,scaleAttributes:e,drawDefinition:r,entryStatuses:n,drawId:o,event:i,stage:s}){if(!i)return{error:St};if(n&&!Array.isArray(n))return v({result:{error:G},info:Tn("entryStatus"),stack:"removeScaleValues"});let a=i.entries;if(o){let{flightProfile:p}=kt({event:i}),m=p?.flights?.find(d=>d.drawId===o);m?a=m.drawEntries:a=r?.entries}let u=(a||[]).filter(p=>(!s||!p.entryStage||p.entryStage===s)&&(!n||n.includes(p.entryStatus))).map(ft);return W_({tournamentRecord:t,scaleAttributes:e,participantIds:u})}function Od({removePriorValues:t,tournamentRecord:e,displaySettings:r,status:n=$r,event:o}){if(!e)return v({result:{error:j}});if(!o)return v({result:{error:St}});if(!Ct(r))return v({result:{error:et}});if(Ct(r.draws))for(let s of Object.keys(r.draws)){let a=r.draws[s].scheduleDetails??[];if(a.length){let c=[];for(let u of a){let p=c.find(m=>gC(m.attributes,u.attributes));p?.dates&&u.dates?p.dates.push(...u.dates):c.push(u)}r.draws[s].scheduleDetails=c}}let i=qs({statusObject:{displaySettings:r},removePriorValues:t,status:n,event:o});return i.error?i:{...R}}function CN({tournamentRecord:t,drawDefinition:e,entryStatuses:r,scaleName:n,drawId:o,event:i,stage:s}){if(!t)return{error:j};if(!i)return{error:St};n=n||i.category?.categoryName||i.category?.ageCategoryCode;let a={eventType:i.eventType,scaleType:Qn,scaleName:n};return Ag({tournamentRecord:t,scaleAttributes:a,drawDefinition:e,entryStatuses:r,drawId:o,event:i,stage:s})}function RN({removePairParticipants:t,tournamentRecord:e,eventIds:r}){if(!e)return{error:j};if(!e.events)return{error:Ir};if(!Array.isArray(r))return{error:et,info:Tn("drawIds")};let n=[],o=[],i=[],s=[];if(e.events=(e.events||[]).filter(a=>{if(r.includes(a.eventId)){let p={action:_T,payload:{events:[a]}};n.push(p),o.push({tournamentId:e.tournamentId,eventName:a.eventName,eventType:a.eventType,category:a.category,eventId:a.eventId,gender:a.gender})}let c=a.eventType===Vr?(a.entries||[]).map(({entryStatus:p,participantId:m})=>p!==_r&&m).filter(Boolean):[],u=r.includes(a.eventId);return u?s.push(...c):i.push(...c),!u}),t){let a=s.filter(c=>!i.includes(c));e.participants=e.participants.filter(({participantId:c})=>!a.includes(c))}return hc({tournamentRecord:e}),n.length&&(Tt({topic:pa,payload:n}),vi({tournamentRecord:e,timeItem:{itemType:_T,itemValue:o}})),{...R}}function bN({tournamentRecord:t,eventUpdates:e,eventId:r,event:n}){let o="modifyEvent";if(!t)return v({result:{error:j},stack:o});if(!er(r))return v({result:{error:St},context:{eventId:r},stack:o});if(!Ct(e))return v({result:{error:G},context:{eventUpdates:e},stack:o});let i=n?.entries?.filter(({entryStatus:l})=>{let f=l;return[...Mr,Or].includes(f)}).map(({participantId:l})=>l)??[],s=i?$t({participantFilters:{participantIds:i},withIndividualParticipants:!0,tournamentRecord:t}).participants??[]:[],a=[],c=s.reduce((l,f)=>{let g=f.person?.sex?[f.person.sex]:f.individualParticpants?.map(I=>I.person?.sex)||[];return a.push(...g),l.includes(f.participantType)?l:l.concat(f.participantType)},[]),u=mt(a),p=!u.length||[Cr,On].includes(e.gender??"")||u.length===1&&u[0]===e.gender;if(e.gender&&!p)return v({context:{gender:e.gender,validGender:p},result:{error:G},stack:o});let d=(c.includes(Le)&&[Le]||c.includes(It)&&[eo]||c.includes(pt)&&[Vr]||[Vr,eo,Le]).includes(e.eventType??"");return e.eventType&&!d?v({context:{participantType:e.eventType,validEventType:d},result:{error:G},stack:o}):(e.eventType&&(n.eventType=e.eventType),e.eventName&&(n.eventName=e.eventName),e.gender&&(n.gender=e.gender),{...R})}function Lp({qualifyingPositions:t,drawEntries:e=[],drawName:r,drawId:n,event:o,stage:i}){let s="addFlight";if(!o)return v({result:{error:St},stack:s});if(!r)return v({result:{error:et},stack:s});if(e?.length){let g=(o.entries??[]).map(ft),I=e.map(ft);if(Wt(I,g).length!==I.length)return v({result:{error:G},stack:s})}let a=kt({event:o})?.flightProfile,c=a?.flights?.map(({flightNumber:g})=>!isNaN(g)&&ct(g))?.filter(Boolean)||[],u=Math.max(0,...c)+1,m={drawId:n||Mt(),flightNumber:u,drawEntries:e,drawName:r};if(i&&(m.stage=i),t&&(m.qualifyingPositions=t),(a?.flights||[]).find(({drawId:g})=>g===m.drawId))return v({result:{error:xy},stack:s});let l=(a?.flights||[]).concat(m),f={name:Gr,value:{...a||{},flights:l}};return po({event:o,extension:f})}var j_={collectionDefinitions:[{collectionName:"Doubles",matchUpCount:3,matchUpFormat:"SET1-S:8/TB7@7",matchUpType:"DOUBLES",matchUpValue:1},{collectionName:"Singles",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7",matchUpType:"SINGLES",matchUpValue:1}],tieFormatName:"COLLEGE_D3",winCriteria:{valueGoal:5}};var Y_={collectionDefinitions:[{collectionName:"Doubles",collectionValue:1,matchUpCount:3,matchUpFormat:"SET1-S:6/TB7",matchUpType:"DOUBLES"},{collectionName:"Singles",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7",matchUpType:"SINGLES",matchUpValue:1}],tieFormatName:"COLLEGE_DEFAULT",winCriteria:{valueGoal:5}};var q_={collectionDefinitions:[{collectionName:"Doubles",matchUpCount:3,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1},{collectionName:"Singles",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7",matchUpType:"SINGLES",matchUpValue:1}],tieFormatName:"COLLEGE_JUCO",winCriteria:{valueGoal:5}};var wT={COLLEGE_D3:j_,COLLEGE_DEFAULT:Y_,COLLEGE_JUCO:q_,DOMINANT_DUO:ST,DOMINANT_DUO_MIXED:fT,LAVER_CUP:UT,TEAM_DOUBLES_3_AGGREGATION:uT,TIME_TENNIS_DUAL:gT,TIME_TENNIS_PRO_CIRCUIT:lT,USTA_BREWER_CUP:IT,USTA_OZAKI_CUP:hT,USTA_COLLEGE:TT,USTA_GOLD_TEAM_CHALLENGE:cT,USTA_INTERSECTIONAL:dT,USTA_LEVEL_1:AT,USTA_SECTION_BATTLE:mT,USTA_SOUTHERN_LEVEL_5:pT,USTA_TOC:PT,USTA_WTT_ITT:yT,USTA_ZONAL:ET};function Sc({suppressNotifications:t,tournamentRecord:e,internalUse:r,event:n}){if(!e)return{error:j};if(e.events||(e.events=[]),!n)return{error:St};let{startDate:o,endDate:i}=e;if(!r&&(n.entries?.length||n.drawDefinitions?.length)){let c=rt({drawDefinitions:!!n.drawDefinitions?.length,entries:!!n.entries?.length});return{info:"entries/drawDefinitions cannot exist",error:G,context:c}}let s={eventType:vs,drawDefinitions:[],entries:[],startDate:o,endDate:i,...n};if(n.eventType===Kr){if(n.tieFormat){let c=cr({tieFormat:n.tieFormat});if(c.error)return c}else if(n.tieFormatName){if(!wT[n.tieFormatName])return{context:{tieFormatName:n.tieFormatName},error:G};let c=Li({isMock:e?.isMock,namedFormat:n.tieFormatName,event:n});s.tieFormat=c}}if(s.eventId||(s.eventId=Mt()),e.events.reduce((c,u)=>c||u.eventId===s.eventId,void 0))return{error:zA};{let c=s;if(e.events.push(c),!t){let{topics:u}=Fr();if(u.includes(ep)){let p=ro({event:n}).matchUps??[];lo({tournamentId:e?.tournamentId,eventId:n.eventId,matchUps:p})}for(let p of n.drawDefinitions||[])ma({drawDefinition:p})}return{...R,event:s}}}var FN={};ne(FN,{drawMatic:()=>Cd,garman:()=>LN,generateAdHocMatchUps:()=>Su,generateAdHocRounds:()=>Md,generateAndPopulatePlayoffStructures:()=>ed,generateCourts:()=>yg,generateDrawDefinition:()=>Uu,generateDrawMaticRound:()=>ud,generateDrawStructuresAndLinks:()=>ad,generateDrawTypeAndModifyDrawDefinition:()=>cd,generateFlightProfile:()=>K_,generateLineUps:()=>FT,generateQualifyingStructure:()=>qm,generateSeedingScaleItems:()=>Qh,generateVoluntaryConsolation:()=>AS,roundRobinGroups:()=>WR});var Bk="splitLevelBased",vN="splitWaterfall",xN="splitShuttle",$_={SPLIT_LEVEL_BASED:Bk,SPLIT_WATERFALL:vN,SPLIT_SHUTTLE:xN};function K_(t){let{drawNameRoot:e="Flight",attachFlightProfile:r,tournamentRecord:n,scaleAttributes:o,scaleSortMethod:i,deleteExisting:s,sortDescending:a,drawNames:c=[],flightsCount:u,splitMethod:p,uuids:m=[],event:d,stage:l}=t;if(!d)return{error:St};let f=d.entries??[],{flightProfile:g}=kt({event:d});if(g&&r&&!s)return{error:yl};let I=t.scaledEntries??ks({tournamentRecord:n,scaleAttributes:o,scaleSortMethod:i,sortDescending:a,event:d,stage:l}).scaledEntries,h=I.map(ft),S=sr(f.filter(({participantId:N})=>!h.includes(N)).filter(N=>(!l||!N.entryStage||N.entryStage===l)&&(!N.entryStatus||Vo.includes(N.entryStatus)))),T=I.concat(...S),A=T.length,P=Math.ceil(A/u),y=Ae(T,P);p===vN?y=Pl(T,u):p===xN&&(y=Pl(T,u,!0));function E(N){return(N||[]).map(({participantId:C,scaleValue:D})=>{let O=f.find(b=>b.participantId===C);return O?.scaleValue&&D&&(O.scaleValue=D),O}).sort((C,D)=>C.scaleValue-D.scaleValue).map((C,D)=>(C.scaleValue&&(C.seedNumber=D+1),C))}let U=Z(0,u).map(N=>{let C=N+1;return{flightNumber:C,drawId:m?.pop()??Mt(),drawEntries:E(y[N]),drawName:c?.length&&c[N]||`${e} ${C}`}}),M={scaleAttributes:o,splitMethod:p,flights:U};if(r){let N=Tg({flightProfile:M,deleteExisting:s,event:d});return{splitEntries:Tr()&&y||void 0,...N}}else return{flightProfile:M,...R}}var Hk="ASC",wN="ASC",Wk="DESC",LT="DESC",z_={ASC:Hk,ASCENDING:wN,DESC:Wk,DESCENDING:LT};function FT(t){let{tieFormat:e}=t,{useDefaultEventRanking:r,tournamentRecord:n,drawDefinition:o,scaleAccessor:i,singlesOnly:s,attach:a,event:c}=t;if(c?.eventType!==Kr)return{error:yo};if(!n)return{error:j};if(!e&&!o)return{error:fr};if(e=e??Ve({drawDefinition:o,event:c})?.tieFormat,cr({tieFormat:e}).error)return{error:Jo};if(typeof i!="object"&&!r)return{error:G,context:{scaleAccessor:i}};let u={},m=(o?.entries??c?.entries??[]).filter(D=>D?.entryStatus===qr).map(ft),{participants:d=[]}=$t({withIndividualParticipants:!0,withScaleValues:!0,tournamentRecord:n}),l=d.filter(({participantId:D})=>m.includes(D)),f=D=>D===Zo?"rankings":"ratings",g=c?.category?.categoryName??c?.category?.ageCategoryCode,{scaleName:I=g,scaleType:h=Zo,sortOrder:S,accessor:T}=i||{},A=f(h),P=(D,O)=>{let b=D[A]?.[O];if(!b&&r&&(b=D[A]?.[da]),Array.isArray(b)){let _=b.find(L=>L.scaleName===I)?.scaleValue;if(se(_))return _;if(T&&typeof _=="object")return _[T]}return 0},y=(D,O,b)=>{let _=S===LT?O:D,L=S===LT?D:O;return P(_,b)-P(L,b)},E=(D,O)=>y(D,O,da),U=(D,O)=>y(D,O,Ri),M=[],N=e?.collectionDefinitions??[];for(let D of l){let O=D.individualParticipants?.sort(E)??[],b=s?O:D.individualParticipants?.sort(U)??[],_={};for(let F of N){let w=[],{collectionId:x,matchUpCount:H,matchUpType:V,gender:W}=F,B=V===da;Z(0,H).forEach(q=>{let Y=B?O:b??[],k=q+1,K=[];Z(0,B?1:2).forEach(X=>{let $=Y?.find(nt=>{let Q=W&&([Zt,ce].includes(W)&&W||W===Cr&&[Zt,ce][X]);return(!Q||Q===nt.person?.sex)&&!w.includes(nt.participantId)})?.participantId;$&&(K.push($),w.push($),_[$]||(_[$]=[]),_[$].push({collectionPosition:k,collectionId:x}))}),B||M.push(K)})}let L=Object.keys(_).map(F=>({collectionAssignments:_[F],participantId:F}));u[D.participantId]=L}let C=[];for(let D of M){let{participant:O}=zr({tournamentParticipants:d,participantIds:D});if(!O){let b={individualParticipantIds:D,participantRole:Fe,participantType:pt};C.push(b)}}if(a){for(;C.length;)dn({participant:C.pop(),tournamentRecord:n});gt({element:o,extension:{name:mo,value:u}})}return{...R,lineUps:u,participantsToAdd:C}}function yg(t){if(!t)return{error:et};let e=vt(t,[{dates:!1,[Pi]:s=>Array.isArray(s)&&s.every(Pr)},{uuids:!1,[Pi]:s=>Array.isArray(s)&&s.every(er)},{startTime:!1,endTime:!1,[Pi]:hI},{idPrefix:!1,namePrefix:!1,[Pi]:er},{count:!0,[Pi]:se}]);if(e.error)return e;let{startDate:r,endDate:n}=t.tournamentRecord??{},o=t.dates||r&&n&&vc(r,n)||[],i=Z(1,t.count+1).map(s=>rt({courtId:t.uuids?.pop()??(t.idPrefix&&`${t.idPrefix}-${s}`)??Mt(),courtName:t.courtNames?.pop()??(t.namePrefix&&`${t.namePrefix} ${s}`),dateAvailability:o.map(a=>({startTime:t.startTime??"08:00",endTime:t.endTime??"20:00",date:a}))}));return{...R,courts:i}}var LN={};ne(LN,{default:()=>jk,garman:()=>J_});function Ra({court:t,date:e}){let r=e&&t.dateAvailability.find(o=>Dn(o.date,e)),n=t.dateAvailability.find(o=>!o.date);return r||n}function ls(t){let e=vt(t,[{courtDate:!0,_ofType:Ui}]);if(e.error)return e;let{includeBookingTypes:r=[],courtDate:n}=t,o=[],i=xe(n.startTime);(n.bookings||[]).filter(a=>!a.bookingType||!r.includes(a.bookingType)).sort((a,c)=>Ol(a.startTime).localeCompare(Ol(c.startTime))).forEach(a=>{let c={startTime:qt(i.toISOString()),endTime:a.startTime};xe(a.startTime)>i&&o.push(c),xe(a.endTime)>i&&(i=xe(a.endTime))});let s={startTime:qt(i.toISOString()),endTime:n.endTime};return xe(n.endTime)>i&&o.push(s),{timeSlots:o}}function Q_({averageMatchUpMinutes:t,includeBookingTypes:e,periodStartTime:r,periodEndTime:n}){let o=s=>{let{timeSlots:a}=ls({includeBookingTypes:e,courtDate:s});return!!a?.filter(i)?.length};function i(s){let a=xe(s.startTime),c=xe(s.endTime);return a>r||c<n?!1:ea(r,c)>=t}return{enoughTime:o}}function GT(t){let e=vt(t,[{periodStart:!0,date:!0},{courts:!0,_ofType:an}]);if(e.error)return e;let{averageMatchUpMinutes:r,includeBookingTypes:n,periodStart:o,date:i}=t,s=t.courts,a=xe(o),c=vl(a,r),{enoughTime:u}=Q_({averageMatchUpMinutes:r,includeBookingTypes:n,periodStartTime:a,periodEndTime:c});return{availableToScheduleCount:(s?.filter(m=>{if(!Array.isArray(m.dateAvailability))return!1;let d=Ra({date:i,court:m});return!!(d&&u(d))})||[]).length,...R}}function Fp(t){let{remainingScheduleTimes:e=[],clearScheduleDates:r,periodLength:n=30,scheduleDate:o,courts:i=[]}=t,{bookings:s=[]}=t;if(!Array.isArray(i)||!i.length)return{error:G,courts:i};if(!Array.isArray(s))return{error:Xp};if(!Pr(o))return{error:ir};r&&(Array.isArray(r)?r.includes(o)&&(s=[]):s=[]);let{courtBookings:a,unassignedBookings:c}=s.reduce((l,f)=>{let{courtId:g}=f;return g?l.courtBookings[g]?l.courtBookings[g].push(f):l.courtBookings[g]=[f]:l.unassignedBookings.push(f),l},{courtBookings:{},unassignedBookings:[]}),u=i.map((l,f)=>{let{courtId:g,courtName:I}=l,h=a[g]||[],S=Ra({date:o,court:l})||{},{bookings:T=[],startTime:A,endTime:P,date:y}=S,U=[e[f]&&{startTime:A,endTime:e[f]},...J(T,!1,!0),...h].filter(Boolean);return{courtId:g,courtName:I,dateAvailability:{bookings:U,startTime:A,endTime:P,date:y}}});c.sort((l,f)=>Gt(l.startTime)-Gt(f.startTime));let p=()=>u.map(l=>{let f=l.dateAvailability,{timeSlots:g=[]}=ls({courtDate:f});return{courtName:l.courtName,courtId:l.courtId,timeSlots:g}}).flat(),m=[];for(let l of c){let{startTime:f,endTime:g,averageMinutes:I,recoveryMinutes:h,matchUpId:S}=l,T=Gt(f),A=Gt(g),y=p().reduce((E,{courtId:U,courtName:M,timeSlots:N})=>{let C;return N.find(({startTime:O,endTime:b})=>{C=Gt(O)-T;let _=T>=Gt(O);return A<=Gt(b)&&E.startDifference!==0&&((C===0||C+n>=0)&&(E.startDifference===void 0||C<E.startDifference)||_)})?{courtName:M,courtId:U,startDifference:C}:E},{});if(y.courtId){let E={averageMinutes:I,recoveryMinutes:h,matchUpId:S,startTime:f,endTime:g};m.push(E),u.find(({courtId:M})=>M===y.courtId)?.dateAvailability.bookings.push(E)}else console.log({unassignedBooking:l})}return{virtualCourts:u.map(({courtId:l,courtName:f,dateAvailability:g})=>({dateAvailability:[g],courtName:f,courtId:l})),assignedBookings:m}}function Pu({averageMatchUpMinutes:t,periodLength:e=30,recoveryMinutes:r}){let n=(t||90)+(r||0);return e>n?n:e||30}function kT(t){let{startTime:e="8:00",endTime:r="20:30",count:n=10,date:o}=t??{};return Z(0,n).map(()=>({dateAvailability:[{date:o,startTime:e,endTime:r}]}))}function Tc({scheduleDate:t,startTime:e,endTime:r,courts:n}){let o=e&&"startTime"||r&&"endTime"||void 0;return n.reduce((i,s)=>{let a=Ra({date:t,court:s}),c=o&&(a?.[o]||s[o]);return c&&(!i||e&&Gt(c)<Gt(i)||r&&Gt(c)>Gt(i))?c:i},void 0)}function X_({averageMinutes:t,startTime:e,endTime:r,courts:n,date:o}){e=e||Tc({courts:n,scheduleDate:o,startTime:!0}),r=r||Tc({courts:n,scheduleDate:o,endTime:!0});let i;if(e&&r){let s=xe(e),a=xe(r);for(let c of n||[]){if(!Array.isArray(c.dateAvailability))continue;let u=Ra({court:c,date:o}),{timeSlots:p}=ls({courtDate:u});p?.forEach(m=>{let d=xe(m.startTime),l=xe(m.endTime);if(d>a||d<s||l<s)return!1;if(ea(d,l)>=t){let I=qt(d.toISOString());(!i||I<i)&&(i=I)}})}}return{firstTimeSlotStartTime:i}}function _d(t){let e=vt(t,[{courts:!0,_ofType:an}]);if(e.error)return e;let{date:r=_l(),startTime:n="08:00",endTime:o="19:00",periodLength:i,courts:s}=t,{calculateStartTimeFromCourts:a=!0,remainingScheduleTimes:c,averageMatchUpMinutes:u,clearScheduleDates:p,courtsCount:m,bookings:d}=t;i=i||Pu({averageMatchUpMinutes:u}),r=At(r),n=qt(n),o=qt(o);let l=0,f=0,g=0,I=0,h=0;!s&&m&&(s=kT({startTime:n,endTime:o,count:m,date:r}));let{virtualCourts:S}=Fp({remainingScheduleTimes:c,clearScheduleDates:p,scheduleDate:r,periodLength:i,bookings:d,courts:s}),{firstTimeSlotStartTime:T}=X_({averageMinutes:u,courts:S,startTime:n,endTime:o,date:r});a&&T&&(n=T||n);let A=Gt(n),y=Gt(o)-A,E=Math.floor(y/i),M=Z(0,E+1).map(C=>{let D=A+C*i,O=mC(D),b=GT({courts:S??[],averageMatchUpMinutes:u,periodStart:O,date:r});if(b.error)return{error:b.error};let{availableToScheduleCount:_=0}=b,L=_>f?_-f:0;h+=C?_:0;let F=C?h/C:_,x=i*F/u,H=C?x*(C-1)+F:F,V=_?f&&H-l||L:0;l=H,f=_,g+=V;let W=ct(g)-I;return I+=W,{periodStart:O,add:W,availableToScheduleCount:_,newCourts:L,totalMatchUps:I}});return{scheduleTimes:M.reduce((C,D)=>{let b=Z(0,D.add).map(()=>({scheduleTime:D.periodStart}));return C.concat(...b)},[]).flat(),timingProfile:M,totalMatchUps:I}}var J_={getCourtsAvailableAtPeriodStart:GT,generateTimeSlots:ls,getScheduleTimes:_d,courtGenerator:kT},jk=J_;var VT={};ne(VT,{isValid:()=>Sr,isValidMatchUpFormat:()=>Sr,parse:()=>Ze,stringify:()=>td});var iD={};ne(iD,{allCompetitionMatchUps:()=>nn,allDrawMatchUps:()=>ar,allEventMatchUps:()=>ro,allTournamentMatchUps:()=>pe,analyzeMatchUp:()=>Cp,applyLineUps:()=>rD,assignMatchUpSideParticipant:()=>GN,assignTieMatchUpParticipantId:()=>wd,bulkMatchUpStatusUpdate:()=>ZN,calculateWinCriteria:()=>ps,checkInParticipant:()=>Ug,checkMatchUpIsComplete:()=>es,checkOutParticipant:()=>Eg,competitionScheduleMatchUps:()=>Au,disableTieAutoCalc:()=>QN,drawMatchUps:()=>jS,enableTieAutoCalc:()=>$N,eventMatchUps:()=>Id,findMatchUp:()=>og,getAllDrawMatchUps:()=>re,getCheckedInParticipantIds:()=>Xi,getCompetitionMatchUps:()=>Np,getEventMatchUpFormatTiming:()=>LS,getMatchUpCompetitiveProfile:()=>Jc,getMatchUpContextIds:()=>VS,getMatchUpDailyLimits:()=>Sd,getMatchUpDailyLimitsUpdate:()=>FS,getMatchUpDependencies:()=>xr,getMatchUpFormat:()=>BS,getMatchUpFormatTiming:()=>Zc,getMatchUpFormatTimingUpdate:()=>xS,getMatchUpScheduleDetails:()=>bm,getMatchUpType:()=>xm,getMatchUpsStats:()=>HS,getModifiedMatchUpFormatTiming:()=>fd,getPredictiveAccuracy:()=>kS,getRoundMatchUps:()=>Xe,getRounds:()=>WS,isValidMatchUpFormat:()=>Sr,matchUpActions:()=>id,mutate:()=>oD,participantScheduledMatchUps:()=>GS,query:()=>hP,removeDelegatedOutcome:()=>KN,removeMatchUpSideParticipant:()=>BN,removeTieMatchUpParticipantId:()=>VN,replaceTieMatchUpParticipantId:()=>Pg,resetMatchUpLineUps:()=>JN,resetScorecard:()=>nD,resetTieFormat:()=>Ng,setDelegatedOutcome:()=>tD,setMatchUpFormat:()=>XN,setMatchUpStatus:()=>Du,setOrderOfFinish:()=>eD,substituteParticipant:()=>zN,tallyParticipantResults:()=>Ua,toggleParticipantCheckInState:()=>vd,tournamentMatchUps:()=>hd,updateTieMatchUpScore:()=>En,validMatchUp:()=>cf,validMatchUps:()=>Ar});var oD={};ne(oD,{applyLineUps:()=>rD,assignMatchUpSideParticipant:()=>GN,assignTieMatchUpParticipantId:()=>wd,bulkMatchUpStatusUpdate:()=>ZN,checkInParticipant:()=>Ug,checkOutParticipant:()=>Eg,disableTieAutoCalc:()=>QN,enableTieAutoCalc:()=>$N,findMatchUp:()=>og,removeDelegatedOutcome:()=>KN,removeMatchUpSideParticipant:()=>BN,removeTieMatchUpParticipantId:()=>VN,replaceTieMatchUpParticipantId:()=>Pg,resetMatchUpLineUps:()=>JN,resetScorecard:()=>nD,resetTieFormat:()=>Ng,setDelegatedOutcome:()=>tD,setMatchUpFormat:()=>XN,setMatchUpStatus:()=>Du,setOrderOfFinish:()=>eD,substituteParticipant:()=>zN,toggleParticipantCheckInState:()=>vd,updateTieMatchUpScore:()=>En});function GN({tournamentRecord:t,drawDefinition:e,participantId:r,sideNumber:n,matchUpId:o,event:i}){if(r&&typeof r!="string")return{error:sn};if(!e)return{error:z};if(!o)return{error:Ne};let s=n===void 0;if(s&&(n=1),![1,2].includes(n))return v({result:{error:G,context:{sideNumber:n}}});let{matchUp:a,structure:c}=xt({drawDefinition:e,matchUpId:o,event:i});if(!a)return{error:De};if(!(!c?.structures&&!(e.drawType&&e.drawType!==br)&&!c?.matchUps?.find(({roundPosition:p})=>!!p)))return{error:Qp};if(!r&&(a?.score?.scoreStringSide1||ie.includes(a?.matchUpstatus)||a?.matchUpStatus&&[fe,Me].includes(a.matchUpStatus)))return{error:wu,info:"matchUp has completed status or score"};if(a){if(a.sides=[1,2].map(p=>{let m=a.sides?.find(d=>d.sideNumber===p)??{sideNumber:p};return n===p?{...m,participantId:r}:m}),s)for(let p of a.sides)p.sideNumber&&(p.sideNumber=3-p.sideNumber);ht({tournamentId:t?.tournamentId,context:"assignSideParticipant",drawDefinition:e,matchUp:a})}return{...R,sidesSwapped:s}}function Zr({removePriorValues:t,tournamentRecord:e,duplicateValues:r,drawDefinition:n,disableNotice:o,matchUpId:i,timeItem:s,event:a}){let{matchUp:c}=xt({drawDefinition:n,event:a,matchUpId:i});if(!c)return{error:De};let u=li({removePriorValues:t,element:c,duplicateValues:r,timeItem:s});return o||ht({tournamentId:e?.tournamentId,eventId:a?.eventId,context:"addTimeItem",drawDefinition:n,matchUp:c}),u}function Eg(t){let e=[{[Fn]:!0},{[Ei]:!0},{[zn]:!0},{[ji]:!0}],r=vt(t,e);if(r.error)return r;let n=Ma(t,[{[ra]:co,attr:{[UI]:!0}}]);if(n.error)return n;let{tournamentRecord:o,drawDefinition:i,participantId:s,matchUpId:a}=t,c=n?.matchUp?.matchUp,{matchUpStatus:u,score:p}=c??{};if(u&&fm.includes(u)||u&&ie.includes(u)||he({score:p}))return{error:WA};let m=Xi({matchUp:c});if(m?.error)return m;let{checkedInParticipantIds:d,allRelevantParticipantIds:l}=m??{};if(!l?.includes(s))return{error:sn};if(!d?.includes(s))return{error:fy};let f=ZI({matchUp:c});if(f?.error)return f;let{sideParticipantIds:g,nestedIndividualParticipantIds:I}=f??{},h=g?.indexOf(s);return h!==void 0&&[0,1].includes(h)&&(I?.[h]??[]).forEach(T=>{Zr({drawDefinition:i,matchUpId:a,timeItem:{itemType:Rm,itemValue:T}})}),Zr({tournamentRecord:o,drawDefinition:i,matchUpId:a,timeItem:{itemValue:s,itemType:Rm}})}function Ug(t){let e=[{[Fn]:!0},{[Ei]:!0},{[zn]:!0},{[ji]:!0}],r=vt(t,e);if(r[Ns])return r;let n=Ma(t,[{[ra]:co,attr:{[UI]:!0}}]);if(n[Ns])return n;let{tournamentRecord:o,drawDefinition:i,participantId:s,matchUpId:a}=t,c=Xi({matchUp:n?.matchUp?.matchUp});if(c?.error)return c;let{checkedInParticipantIds:u,allRelevantParticipantIds:p}=c??{};return u?.includes(s)?{...R}:p?.includes(s)?Zr({tournamentRecord:o,drawDefinition:i,matchUpId:a,timeItem:{itemValue:s,itemType:Cm}}):{[Ns]:sn}}function vd(t){let e=vt(t,[{[zn]:!0,[Ei]:!0,[ji]:!0}]);if(e.error)return e;let r=t.tournamentId??t.activeTournamentId,n=t.tournamentRecord??(r&&t.tournamentRecords?.[r]),{participantId:o,matchUpId:i,drawDefinition:s}=t;if(!n)return{error:j};let c=Ma(t,[{[ra]:co,[Ns]:De}]).matchUp?.matchUp;if(!c)return{error:De};let{checkedInParticipantIds:u=[]}=Xi({matchUp:c});return o&&u.includes(o)?Eg({tournamentRecord:n,drawDefinition:s,participantId:o,matchUpId:i,matchUp:c}):Ug({tournamentRecord:n,drawDefinition:s,participantId:o,matchUpId:i,matchUp:c})}function xd({tournamentRecord:t,drawDefinition:e,tieMatchUpId:r,event:n}){if(!t)return{error:j};if(!e)return{error:Ur};if(!n)return{error:Ir};let o=be({drawDefinition:e}),{matchUp:i}=xt({matchUpId:r,drawDefinition:e,matchUpsMap:o});if(!i)return{error:De};let{matchUp:s,structure:a}=xt({tournamentParticipants:t.participants,matchUpId:r,inContext:!0,drawDefinition:e,matchUpsMap:o,event:n});if(!s)return{error:De};let{collectionPosition:c,drawPositions:u,collectionId:p,matchUpTieId:m,matchUpType:d}=s;if(d&&![ee,jt].includes(d))return{error:ze};let{positionAssignments:l}=Dt({structure:a}),f=l?.filter(y=>u?.includes(y.drawPosition)),{matchUp:g}=xt({matchUpId:m,drawDefinition:e,matchUpsMap:o}),I=g?.sides?.map(ft)??[],h=f?.map(ft)??[],S=[...I,...h],{participants:T}=$t({tournamentRecord:t,participantFilters:{participantTypes:[Lt],participantIds:S}}),{matchUp:A}=xt({matchUpId:m,inContext:!0,drawDefinition:e,matchUpsMap:o}),P=Ve({matchUp:g,drawDefinition:e,structure:a,event:n})?.tieFormat;return{inContextDualMatchUp:A,inContextTieMatchUp:s,relevantAssignments:f,collectionPosition:c,teamParticipants:T,collectionId:p,matchUpType:d,dualMatchUp:g,tieMatchUp:i,tieFormat:P,structure:a,...R}}function Pg(t){let e=xd(t);if(e.error)return e;let r="replaceTieMatchUpParticipantid",{existingParticipantId:n,tournamentRecord:o,newParticipantId:i,drawDefinition:s,substitution:a,event:c}=t;if(!n||!i)return v({result:{error:te},stack:r});if(n===i)return{...R};let{inContextDualMatchUp:u,inContextTieMatchUp:p,collectionPosition:m,collectionId:d,dualMatchUp:l,tieMatchUp:f,tieFormat:g}=e,I=p?.matchUpType,h=p?.sides?.find(H=>H.participant?.participantId===n||H.participant?.individualParticipantIds?.includes(n));if(!h)return{error:Jt};let S=$t({tournamentRecord:o,participantFilters:{participantIds:[n,i]}})?.participants??[];if(S.length!==2)return v({result:{error:te},stack:r});if(S[0].participantType!==S[1].participantType)return v({result:{error:tn},stack:r});let{appliedPolicies:T}=yt({tournamentRecord:o,drawDefinition:s,event:c}),A=t.policyDefinitions?.[qe]??T?.[qe]??is[qe],P=S.find(({participantId:H})=>H===i);if((t.enforceGender??A?.participants?.enforceGender)!==!1&&[Zt,ce].includes(p?.gender)&&p?.gender!==P?.person?.sex)return{error:As,info:"Gender mismatch"};let E=A?.processCodes?.substitution;Pa({tournamentId:o.tournamentId,eventId:c.eventId,inContextDualMatchUp:u,drawDefinition:s,dualMatchUp:l});let U=l?.sides?.find(({sideNumber:H})=>H===h.sideNumber);if(!U)return v({result:{sideNumber:h.sideNumber,existingParticipantId:n,error:je},stack:r});if(p?.sides?.flatMap(H=>H.participant?.individualParticipantIds||H.participant?.participantId||[])?.includes(i))return v({result:{error:Lu},stack:r});let N=u?.sides?.find(({sideNumber:H})=>H===h.sideNumber)?.participantId,C=U.lineUp,D=C?.find(({participantId:H})=>i===H),O=C?.reduce((H,V)=>V.substitutionOrder>H?V.substitutionOrder:H,0),b=C?.map(H=>{let V=J(H,!1,!0);if(![n,i].includes(V.participantId))return V;if(!a&&[n,i].includes(V.participantId)&&(V.collectionAssignments=V.collectionAssignments?.filter(W=>!(W.collectionPosition===m&&W.collectionId===d))),a&&n===V.participantId&&(V.collectionAssignments=V.collectionAssignments.map(W=>W.collectionPosition===m&&W.collectionId===d&&W.substitutionOrder===void 0?{...W,substitutionOrder:O}:W)),V.participantId===i){V.collectionAssignments||(V.collectionAssignments=[]);let W={collectionId:d,collectionPosition:m};a&&(W.previousParticipantId=n,W.substitutionOrder=(O??0)+1),V.collectionAssignments.push(W)}return V})??[];if(!D){let H={collectionId:d,collectionPosition:m};a&&(H.substitutionOrder=(O??0)+1,H.previousParticipantId=n);let V={collectionAssignments:[H],participantId:i};b.push(V)}let _=I===jt,{assignedParticipantIds:L}=cp({lineUp:C,collectionPosition:m,collectionId:d}),{assignedParticipantIds:F}=cp({lineUp:b,collectionPosition:m,collectionId:d});if(U.lineUp=b,N&&g){let H=_i({participantId:N,lineUp:b,drawDefinition:s,tieFormat:g});if(H.error)return v({result:H,stack:r})}else console.log("team participantId not found");let w,x;if(_){let{tournamentRecord:H}=t,V=zr({participantIds:F,tournamentRecord:H});if(!V.participant){let q=dn({returnParticipant:!0,pairOverride:!0,tournamentRecord:H,participant:{participantRole:Fe,individualParticipantIds:F,participantType:pt}});if(q.error)return v({result:q,stack:r});w=q.participant?.participantId}V=zr({participantIds:L,tournamentRecord:H});let W=V.participant?.participantId;W&&Oi({participantIds:[W],tournamentRecord:H}).success&&(x=W)}if(a||h.substitutions?.length===1){if(a)E&&f&&(f.processCodes=mt([...f?.processCodes??[],...E]));else for(let H of E||[]){let V=f?.processCodes?.lastIndexOf(H);V!==void 0&&f?.processCodes?.splice(V,1)}f&&ht({tournamentId:o?.tournamentId,matchUp:f,context:r,drawDefinition:s})}return l&&ht({tournamentId:o?.tournamentId,matchUp:l,context:r,drawDefinition:s}),{...R,modifiedLineUp:b,participantRemoved:x,participantAdded:w}}function BT({collectionPosition:t,teamParticipantId:e,dualMatchUpSide:r,drawDefinition:n,participantIds:o,collectionId:i}){if(!i||!t||!Array.isArray(o))return{modifiedLineUp:r?.lineUp||[],error:G};let s=r?.lineUp||ts({participantId:e,drawDefinition:n})?.lineUp,a=[],c=[];return{modifiedLineUp:s?.map(p=>{if(!o.includes(p.participantId))return p;let m=p.collectionAssignments?.filter(d=>{let l=d.collectionId===i&&d.collectionPosition===t;return l&&(d.previousParticipantId&&a.push(d.previousParticipantId),c.push({participantId:p.participantId,...d})),!l});return{participantId:p.participantId,collectionAssignments:m}}).filter(Boolean)||[],assignmentsRemoved:c,previousParticipantIds:a}}function Z_({individualParticipantIds:t,groupingParticipantId:e,tournamentRecord:r}){let n=(r.events||[]).filter(i=>i?.eventType===Le&&i?.entries?.some(s=>s.participantId===e)),o=i=>!t.includes(i.participantId);for(let i of n){i.entries=(i.entries||[]).filter(o);let{flightProfile:s}=kt({event:i});s?.flights?.forEach(a=>{a.drawEntries=(a.drawEntries||[]).filter(o)}),i?.drawDefinitions?.forEach(a=>{a.entries=(a.entries||[]).filter(o)})}return{...R}}function Gp({individualParticipantIds:t,groupingParticipantId:e,removeFromOtherTeams:r,tournamentRecord:n}){let o="addIndividualParticipantIds";if(!n)return v({result:{error:j},stack:o});if(!e||!t)return v({result:{error:et},stack:o});let i=n.participants??[],s=i.find(m=>m.participantId===e);if(!s)return v({result:{error:Jt},stack:o});if(s?.participantType&&![Lt,hr].includes(s.participantType))return v({context:{participantType:s.participantType},result:{error:tn},stack:o});let a=t.filter(m=>i.find(l=>l.participantId===m)?.participantType!==It);if(a.length)return v({result:{error:Hr,invalidParticipantIds:a},stack:o});s.individualParticipantIds||(s.individualParticipantIds=[]);let c=s.individualParticipantIds,u=t.filter(m=>!c.includes(m));u.length&&(r&&mp({individualParticipantIds:u,tournamentRecord:n}),s.individualParticipantIds=s.individualParticipantIds.concat(...u));let{topics:p}=Fr();if(p.includes($e)){let m=i.find(({participantId:d})=>d===e);Tt({topic:$e,payload:{participants:[m]}})}return Z_({individualParticipantIds:t,groupingParticipantId:e,tournamentRecord:n}),{groupingParticipant:J(s,!1,!0),added:u.length,...R}}function kp(t){let{updateParticipantName:e=!0,groupingParticipantId:r,removeFromOtherTeams:n,tournamentRecord:o,pairOverride:i,participant:s}=t;if(!o)return{error:j};if(!s)return{error:Ai};if(!s.participantId)return dn({tournamentRecord:o,participant:s});let{participant:a}=Mo({participantId:s.participantId,tournamentRecord:o});if(!a)return dn({tournamentRecord:o,participant:s});let{participantRoleResponsibilties:c,individualParticipantIds:u,participantOtherName:p,participantName:m,participantRole:d,participantType:l,onlineResources:f,contacts:g,person:I}=s;if(l&&a.participantType!==l)return{error:cy};let h={};if(g&&(h.contacts=g),f&&(h.onlineResources=f),m&&typeof m=="string"&&(h.participantName=m),p&&typeof p=="string"&&(h.participantOtherName=p),Array.isArray(u)){let{participants:S}=$t({participantFilters:{participantTypes:[It]},tournamentRecord:o}),T=S?.map(ft);if(T){let A=u.filter(P=>typeof P=="string"&&T.includes(P));([hr,Bt].includes(l||a.participantType)||l===pt&&(A.length===2||i))&&(h.individualParticipantIds=A),a.participantType===zc.PAIR&&e&&(h.participantName=Yk({individualParticipants:S,newValues:h}))}}return Object.keys(Gm).includes(d)&&(h.participantRole=d),Object.keys(zc).includes(l)&&(h.participantType=l),Array.isArray(c)&&(h.participantRoleResponsibilties=c),a.participantType===zc.INDIVIDUAL&&I&&qk({updateParticipantName:e,existingParticipant:a,newValues:h,person:I}),Object.assign(a,rt(h)),r&&Gp({individualParticipantIds:[a.participantId],groupingParticipantId:r,removeFromOtherTeams:n,tournamentRecord:o}),Tt({topic:$e,payload:{tournamentId:o.tournamentId,participants:[a]}}),{participant:J(a),...R}}function Yk({individualParticipants:t,newValues:e}){let r=e.individualParticipantIds,n=t.filter(({participantId:o})=>r.includes(o)).map(({person:o})=>o?.standardFamilyName).filter(Boolean).sort().join("/");return r.length===1&&(n+="/Unknown"),n}function qk({updateParticipantName:t,existingParticipant:e,newValues:r,person:n}){let o={},{standardFamilyName:i,standardGivenName:s,nationalityCode:a,personId:c,sex:u}=n;u&&Object.keys(wm).includes(u)&&(o.sex=u);let p;if(c&&typeof c=="string"&&(o.personId=c),a&&typeof a=="string"&&($k(a)||a==="")&&(o.nationalityCode=a),i&&typeof i=="string"&&i.length>1&&(o.standardFamilyName=i,p=!0),s&&typeof s=="string"&&s.length>1&&(o.standardGivenName=s,p=!0),p&&t){let m=`${o.standardGivenName} ${o.standardFamilyName}`;r.participantName=m}Object.assign(e.person,o)}function $k(t){return Yo.flatMap(({iso:e,ioc:r})=>[e,r]).filter(Boolean).includes(t)}function wd(t){let e=xd(t);if(e.error)return e;let r="assignTieMatchUpParticipantId",n=t.teamParticipantId,{tournamentRecord:o,drawDefinition:i,participantId:s,event:a}=t;if(!s)return v({result:{error:te},stack:r});if(t.sideNumber&&![1,2].includes(t.sideNumber))return v({result:{error:il},stack:r});let{inContextDualMatchUp:c,inContextTieMatchUp:u,relevantAssignments:p,collectionPosition:m,teamParticipants:d,collectionId:l,matchUpType:f,dualMatchUp:g,tieFormat:I}=e;if(u?.sides?.flatMap(k=>k.participant?.individualParticipantIds||k.participant?.participantId||[])?.includes(s))return v({result:{...R},stack:r});n=n??(t.sideNumber?c?.sides?.find(k=>k.sideNumber===t.sideNumber)?.participantId:void 0);let S=$t({participantFilters:{participantIds:[s]},tournamentRecord:o})?.participants?.[0];if(!S)return v({result:{error:Jt},stack:r});let{appliedPolicies:T}=yt({tournamentRecord:o,drawDefinition:i,event:a}),A=t.policyDefinitions?.[qe]??T?.[qe]??is[qe];if((t.enforceGender??A?.participants?.enforceGender)!==!1&&[Zt,ce].includes(u?.gender)&&u?.gender!==S.person?.sex)return{error:As,info:"Gender mismatch"};let{individualParticipantIds:y,participantType:E}=S;if(f===ee&&E!==It)return{error:tn};let U=E===It?[s]:y,M=n&&d?.find(({participantId:k})=>k===n)||d?.find(({individualParticipantIds:k})=>ve(U,k));if(!M)return{error:Tl};if(n||(n=M.participantId),!n)return{error:Jt};let C=p?.find(k=>k.participantId===M?.participantId)?.drawPosition,D=g?.sides?.find(k=>k.participantId===n)?.sideNumber,O=u?.sides?.find(k=>C&&k.drawPosition===C)?.sideNumber,b=D??O??t.sideNumber;if(!I)return{error:Va};if(!I.collectionDefinitions?.find(k=>k.collectionId===l))return{error:ey};Pa({tournamentId:o.tournamentId,eventId:a.eventId,inContextDualMatchUp:c,drawDefinition:i,dualMatchUp:g});let L=g?.sides?.find(k=>k.sideNumber===b),F=u?.sides?.find(k=>k.sideNumber===b),H=(L?.lineUp??ts({participantId:n,drawDefinition:i})?.lineUp)?.filter(k=>k.collectionAssignments?.find(K=>K.collectionPosition===m&&K.collectionId===l&&!K.previousParticipantId))?.map(k=>k?.participantId),V=H?.length>1&&H||(E===pt?S.individualParticipantIds:[s]),W=BT({collectionPosition:m,teamParticipantId:n,dualMatchUpSide:L,drawDefinition:i,participantIds:V,collectionId:l});if(W.error)return v({result:W,stack:r});let{modifiedLineUp:B}=W,q;if(f===jt){if(E!==pt){let k=kN({collectionPosition:m,teamParticipantId:n,drawDefinition:i,modifiedLineUp:B,participantId:s,collectionId:l,tieFormat:I});if(k?.error)return v({result:k,stack:r});if(k=Y({side:F}),k.error)return k;q=k.deletedParticipantId,L&&(L.lineUp=B),g&&ht({tournamentId:o?.tournamentId,matchUp:g,context:r,drawDefinition:i})}else if(E===pt)for(let k of V)kN({collectionPosition:m,teamParticipantId:n,drawDefinition:i,modifiedLineUp:B,participantId:k,collectionId:l,tieFormat:I})}else{let k=kN({collectionPosition:m,teamParticipantId:n,drawDefinition:i,modifiedLineUp:B,participantId:s,collectionId:l,tieFormat:I});if(k?.error)return k}if(L&&(L.lineUp=B),g&&ht({tournamentId:o?.tournamentId,matchUp:g,context:r,drawDefinition:i}),q){let{error:k}=Oi({participantIds:[q],tournamentRecord:o});k&&console.log("cleanup")}return{...R,modifiedLineUp:B};function Y({side:k}){let K;if(k.participant){let X=k.participant.individualParticipantIds||[];if(X.filter(Boolean).length===1){let{participant:nt}=zr({participantIds:X,tournamentRecord:o});X.push(s);let{participant:Q}=zr({participantIds:X,tournamentRecord:o});if(!Q&&nt){nt.individualParticipantIds=X;let it=kp({pairOverride:!0,tournamentRecord:o,participant:nt});if(it.error)return it}else K=nt?.participantId}}else{let $=dn({participant:{individualParticipantIds:[s],participantRole:Fe,participantType:pt},pairOverride:!0,tournamentRecord:o});if($.error)return $}return{...R,deletedParticipantId:K}}}function kN({collectionPosition:t,teamParticipantId:e,drawDefinition:r,modifiedLineUp:n,participantId:o,collectionId:i,tieFormat:s}){let a=ts({participantId:e,drawDefinition:r})?.lineUp,c=(n||a)?.find(p=>p?.participantId===o),u={collectionId:i,collectionPosition:t};if(c)c.collectionAssignments.push(u);else{let p={collectionAssignments:[u],participantId:o};n.push(p)}return _i({participantId:e,lineUp:n,drawDefinition:r,tieFormat:s})}function VN(t){let{tournamentRecord:e,drawDefinition:r,participantId:n,event:o}=t,i="removeTieMatchUpParticiapantId";if(!n)return v({result:{error:te},stack:i});let s=xd(t);if(s.error)return s;let{appliedPolicies:a}=yt({tournamentRecord:e,drawDefinition:r,event:o}),u=(t.policyDefinitions?.[qe]??a?.[qe]??is[qe])?.processCodes?.substitution,{inContextDualMatchUp:p,inContextTieMatchUp:m,relevantAssignments:d,collectionPosition:l,teamParticipants:f,collectionId:g,matchUpType:I,dualMatchUp:h,tieMatchUp:S,tieFormat:T}=s;if(!h)return v({result:{error:or},stack:i});let A=m?.sides?.find(C=>C.participant?.participantId===n||C.participant?.individualParticipantIds?.includes(n));if(!A)return v({result:{error:Jt},stack:i});if(!A.substitutions?.length&&(he({score:m?.score})||m?.winningSide))return v({result:{error:wy},stack:i});let P=p?.sides?.find(({sideNumber:C})=>C===A.sideNumber)?.participantId;if(!P)return v({result:{error:Jt},stack:i});let y=$t({participantFilters:{participantIds:[n]},tournamentRecord:e})?.participants?.[0];if(!y)return v({result:{error:Jt},stack:i});if(I===ee&&y.participantType===pt)return v({result:{error:As},stack:i});let E=y.participantType===It?[n]:y.individualParticipantIds;Pa({tournamentId:e.tournamentId,eventId:o.eventId,inContextDualMatchUp:p,drawDefinition:r,dualMatchUp:h});let U=h.sides?.find(({sideNumber:C})=>C===A.sideNumber);if(!U&&(h.sides?.filter(({lineUp:C})=>!C).length||0)<2){let C=f?.map(({participantId:D})=>({drawPosition:d?.find(O=>O.participantId===D)?.drawPosition,teamParticipantId:D}));U=h.sides?.find(D=>C?.find(({drawPosition:O})=>O===D.drawPosition)?.teamParticipantId===P)}if(!U)return v({result:{error:Jt,context:{participantId:n}}});let{modifiedLineUp:M,previousParticipantIds:N}=BT({collectionPosition:l,teamParticipantId:P,dualMatchUpSide:U,participantIds:E,drawDefinition:r,collectionId:g});if(U.lineUp=M,P&&T&&_i({participantId:P,lineUp:M,drawDefinition:r,tieFormat:T}),I===jt&&y.participantType===It){let C=m?.sides?.find(b=>b.sideNumber===U?.sideNumber),{participantId:D}=C??{},O=D&&$t({participantFilters:{participantIds:[D]},tournamentRecord:e,withDraws:!0})?.participants?.[0];if(O){let b=O?.individualParticipantIds?.filter(_=>_!==n)??[];if(N&&b.push(...N),b.length>2)return v({result:{error:Hr},stack:i});if(O.draws?.length){if(b.length===1){let{participant:_}=zr({participantIds:b,tournamentRecord:e});if(!_){let F=dn({participant:{participantRole:Fe,individualParticipantIds:b,participantType:pt},pairOverride:!0,tournamentRecord:e});if(F.error)return v({result:F,stack:i})}}}else if(b.length){O.individualParticipantIds=b;let _=kp({participant:O,pairOverride:!0,tournamentRecord:e});if(_.error)return v({result:_,stack:i})}else{let _=Oi({participantIds:[D],tournamentRecord:e});_.error&&console.log("cleanup",{result:_})}}else return v({result:{error:Jt},stack:i})}if(A.substitutions?.length===1&&!m?.sides?.find(D=>D.sideNumber!==A.sideNumber)?.substitutions?.length&&S?.processCodes?.length){for(let D of u||[]){let O=S.processCodes.lastIndexOf(D);S.processCodes.splice(O,1)}ht({tournamentId:e?.tournamentId,matchUp:S,context:i,drawDefinition:r})}return ht({tournamentId:e?.tournamentId,matchUp:h,context:i,drawDefinition:r}),{...R,modifiedLineUp:M}}function BN({tournamentRecord:t,drawDefinition:e,sideNumber:r,matchUpId:n,event:o}){if(!t)return{error:j};if(!e)return{error:z};if(!n)return{error:Ne};if(!r)return{error:et};if(![1,2].includes(r))return{error:G,sideNumber:r};let{matchUp:i,structure:s}=xt({drawDefinition:e,matchUpId:n,event:o});return i?!s?.structures&&!(e.drawType&&e.drawType!==br)&&!s?.matchUps?.find(({roundPosition:c})=>!!c)?(i.sides?.forEach(c=>{c.sideNumber===r&&delete c.participantId}),ht({tournamentId:t?.tournamentId,context:"assignSideParticipant",drawDefinition:e,matchUp:i}),{...R}):{error:Qp}:{error:De}}function tv({drawDefinition:t,matchUpStatus:e,matchUpsMap:r,winningSide:n,dualMatchUp:o,tieFormat:i,structure:s,matchUp:a,event:c,score:u}){let p=J(o,void 0,!0);for(let d of p?.tieMatchUps||[])d.matchUpId===a.matchUpId&&(d.winningSide=n,d.score=u,!he({score:u})&&!e?Object.assign(d,{...pu}):e&&(d.matchUpStatus=e));i=i??Ve({matchUp:a,structure:s,drawDefinition:t,event:c})?.tieFormat;let{winningSide:m}=lu({matchUp:p,drawDefinition:t,matchUpsMap:r,structure:s,tieFormat:i,event:c});return{projectedWinningSide:m}}function ev({matchUpStatuses:t=[Ut,Ot,bt],drawPositionMatchUps:e,loserDrawPosition:r,sourceMatchUps:n}){let o=e?.reduce((p,m)=>!p||m.roundNumber>p.roundNumber?m:p,void 0),i=o?.drawPositions?.find(p=>p!==r),s=n.filter(p=>p?.drawPositions?.includes(i)).map(p=>p.matchUpStatus),a=n.filter(p=>p?.drawPositions?.includes(r)).map(p=>p.matchUpStatus),c=ve(s||[],t),u=ve(a||[],t);return{sourceMatchUp:o,winnerHadMatchUpStatus:c,winnerMatchUpStatuses:s,loserHadMatchUpStatus:u,loserMatchUpStatuses:a}}function rv({inContextDrawMatchUps:t,sourceMatchUpStatus:e,targetDrawPosition:r,tournamentRecord:n,sourceMatchUpId:o,drawDefinition:i,structureId:s,dualMatchUp:a,roundNumber:c,matchUpsMap:u,event:p}){let{structure:m}=st({drawDefinition:i,structureId:s});if(m?.structureType===we)return{...R};u=u??be({drawDefinition:i});let l=(u?.mappedMatchUps||{})[s].matchUps,{initialRoundNumber:f}=ns({drawPosition:r,matchUps:l}),g=l?.filter(h=>h.roundNumber>=c&&h.roundNumber!==f&&h.drawPositions?.includes(r)),{positionAssignments:I}=Dt({drawDefinition:i,structureId:s});for(let h of g??[])Kk({inContextDrawMatchUps:t,sourceMatchUpStatus:e,positionAssignments:I,targetDrawPosition:r,tournamentRecord:n,sourceMatchUpId:o,drawDefinition:i,dualMatchUp:a,matchUpsMap:u,matchUp:h,event:p});return{...R}}function Kk({inContextDrawMatchUps:t,positionAssignments:e,sourceMatchUpStatus:r,targetDrawPosition:n,tournamentRecord:o,sourceMatchUpId:i,drawDefinition:s,dualMatchUp:a,matchUpsMap:c,matchUp:u,event:p}){let m="removeSubsequentDrawPosition";if(a){let g=t.find(({matchUpId:h})=>u.matchUpId===h).sides?.find(h=>h.drawPosition===n)?.sideNumber,I=u.sides?.find(h=>h.sideNumber===g);I&&delete I.lineUp}u.drawPositions=(u.drawPositions||[]).map(f=>f===n?void 0:f).filter(Boolean);let l=e.filter(({drawPosition:f})=>u.drawPositions?.includes(f)).filter(f=>f.bye).length;return u.matchUpStatus=l&&Ut||[bt,Ot].includes(u.matchUpStatus)&&u.matchUpStatus||Kt,[Ot,bt].includes(u.matchUpStatus)&&(u.winningSide=void 0),u.matchUpStatusCodes&&Dh({inContextDrawMatchUps:t,sourceMatchUpStatus:r,sourceMatchUpId:i,matchUpsMap:c,matchUp:u}),ht({tournamentId:o?.tournamentId,eventId:p?.eventId,context:`${m}-${n}`,drawDefinition:s,matchUp:u}),{...R}}function Ac(t){let{dualWinningSideChange:e,inContextDrawMatchUps:r,tournamentRecord:n,drawDefinition:o,matchUpStatus:i,matchUpsMap:s,dualMatchUp:a,targetData:c,matchUpId:u,structure:p,event:m}=t,d=!!t.matchUp.collectionId,l=Br({drawDefinition:o,structure:p}),{drawPositions:f,winningSide:g}=c.matchUp||{};if(!l&&!f)return{error:Fa};let{targetLinks:{loserTargetLink:I,winnerTargetLink:h,byeTargetLink:S},targetMatchUps:{loserMatchUp:T,winnerMatchUp:A,byeMatchUp:P}}=c,y=yn({...t,matchUpStatus:i||Kt,removeWinningSide:!0});if(y.error)return y;let E;if(d){let{matchUpTieId:w,matchUpsMap:x}=t;if(E=En({appliedPolicies:t.appliedPolicies,matchUpId:w,tournamentRecord:n,drawDefinition:o,matchUpsMap:x,event:m}),!e&&!E.removeWinningSide)return{...R}}if(l)return{...R};let{matchUps:U}=Pt({afterRecoveryTimes:!1,inContext:!0,drawDefinition:o,matchUpsMap:s,structure:p}),{positionAssignments:M}=de({structure:p}),N=g-1,C=1-N,D=f[N],O=f[C],{winnerParticipantId:b,loserParticipantId:_}=M?.reduce((w,x)=>(x.drawPosition===O&&(w.loserParticipantId=x.participantId),x.drawPosition===D&&(w.winnerParticipantId=x.participantId),w),{winnerParticipantId:void 0,loserParticipantId:void 0})||{},L=U.filter(w=>w.drawPositions?.includes(O));if(A&&HN({sourceMatchUpStatus:i,sourceMatchUpId:u,inContextDrawMatchUps:r,winningDrawPosition:D,winnerParticipantId:b,tournamentRecord:n,winnerTargetLink:h,drawDefinition:o,winnerMatchUp:A,dualMatchUp:a,matchUpsMap:s}),T){let{winnerHadMatchUpStatus:w}=ev({drawPositionMatchUps:L,loserDrawPosition:O,sourceMatchUps:U}),H=I.linkCondition===Bn;if(w&&H){let W=Math.min(...T.drawPositions);HT({targetLink:I,inContextDrawMatchUps:r,drawDefinition:o,drawPosition:W,matchUpsMap:s,event:m})}let V=zk({sourceMatchUpStatus:i,sourceMatchUpId:u,loserParticipantId:_,tournamentRecord:n,loserTargetLink:I,drawDefinition:o,loserMatchUp:T,dualMatchUp:a,matchUpsMap:s,event:m});if(V.error)return V}if(P){let w=Math.min(...P.drawPositions);HT({sourceMatchUpId:u,targetLink:S,inContextDrawMatchUps:r,drawDefinition:o,drawPosition:w,matchUpsMap:s,event:m})}return{...R,...E&&{tieMatchUpResult:E}}}function HN({inContextDrawMatchUps:t,winningDrawPosition:e,sourceMatchUpStatus:r,winnerParticipantId:n,tournamentRecord:o,winnerTargetLink:i,sourceMatchUpId:s,drawDefinition:a,winnerMatchUp:c,matchUpsMap:u,dualMatchUp:p,event:m}){let{structureId:d,roundNumber:l}=c,f="removeDirectedWinner";if(i){let g=i.target.structureId,{structure:I}=st({drawDefinition:a,structureId:g});if(!I)return{error:_t};let{positionAssignments:h}=de({structure:I});I.seedAssignments=(I.seedAssignments??[]).filter(M=>M.participantId!==n);let T=h?.find(M=>M.participantId===n)?.drawPosition,{matchUps:A}=Pt({drawDefinition:a,structure:I,event:m}),P=A.map(M=>M.drawPositions).flat(1/0).filter(Boolean),y=pr(P);if((T?y[T]:void 0)===1)h?.forEach(M=>{M.participantId===n&&delete M.participantId});else{let M=A.filter(({drawPositions:N})=>N.includes(T));console.log("not removing from position assignments since instances > 1",{drawPositionMatchUps:M,winnerTargetLink:i})}let U=u?.drawMatchUps?.find(({matchUpId:M})=>M===c.matchUpId);U&&ht({tournamentId:o?.tournamentId,eventId:m?.eventId,matchUp:U,context:f,drawDefinition:a})}return l&&rv({targetDrawPosition:e,inContextDrawMatchUps:t,sourceMatchUpStatus:r,tournamentRecord:o,sourceMatchUpId:s,drawDefinition:a,dualMatchUp:p,matchUpsMap:u,roundNumber:l,structureId:d}),{...R}}function zk({sourceMatchUpStatus:t,loserParticipantId:e,tournamentRecord:r,loserTargetLink:n,sourceMatchUpId:o,drawDefinition:i,loserMatchUp:s,matchUpsMap:a,dualMatchUp:c,event:u}){let p="removeDirectedLoser",m=n.target.structureId,{structure:d}=st({drawDefinition:i,structureId:m});if(!d)return{error:_t};let{positionAssignments:l}=de({structure:d}),f=l?.find(g=>g.participantId===e)?.drawPosition;if(l?.forEach(g=>{g.participantId===e&&delete g.participantId}),d.seedAssignments=(d.seedAssignments??[]).filter(g=>g.participantId!==e),c){let g=s?.sides.reduce((S,T,A)=>T.drawPosition===f?A:S,void 0),I=a?.drawMatchUps?.find(({matchUpId:S})=>S===s.matchUpId),h=I?.sides?.[g];h&&(delete h.lineUp,ht({tournamentId:r?.tournamentId,eventId:u?.eventId,matchUp:I,context:p,drawDefinition:i}))}return{...R}}function HT({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,matchUpsMap:o,targetLink:i,event:s}){let a=i.target.structureId;return oc({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,matchUpsMap:o,drawPosition:n,structureId:a,event:s}),{...R}}function nv(t){let{matchUpFormat:e,score:r}=t,n=r?.sets?.length,o=e&&Ze(e),{setFormat:i,finalSetFormat:s,bestOf:a}=o??{};return(a&&n===a&&s||i)?.timed||!1}function ov({tournamentRecord:t,drawDefinition:e,structure:r,matchUp:n}){let o="attemptToSetMatchUpStatusBYE";if(n?.winningSide)return v({result:{error:Zs},context:{matchUpStatus:Ut},stack:o});let{positionAssignments:i}=de({structure:r}),s=i?.filter(c=>c.bye).map(c=>c.drawPosition);return n.drawPositions?.some(c=>s?.includes(c))?(n.matchUpStatus=Ut,n.matchUpStatusCodes=[],ht({tournamentId:t?.tournamentId,context:o,drawDefinition:e,matchUp:n}),{...R}):v({result:{error:ty},info:"matchUp does not include BYE",stack:o})}function Ld(t){let{tournamentRecord:e,appliedPolicies:r,drawDefinition:n,matchUpsMap:o,targetData:i,structure:s,event:a}=t,c="doubleExitAdvancement";if(s.structureType===we)return v({result:{...R},stack:c});let{matchUp:u,targetMatchUps:p,targetLinks:m}=i,{loserMatchUp:d,winnerMatchUp:l,loserTargetDrawPosition:f}=p;if(d&&d.matchUpStatus!==Ut){let{loserTargetLink:g}=m;if(r?.progression?.doubleExitPropagateBye){let I=sv({loserTargetDrawPosition:f,tournamentRecord:e,loserTargetLink:g,drawDefinition:n,loserMatchUp:d,matchUpsMap:o,event:a});if(I.error)return v({result:I,stack:c})}else{let{feedRound:I,drawPositions:h,matchUpId:S}=d,T=I?2:2-h.indexOf(f),A=iv({...t,targetMatchUp:d,walkoverWinningSide:T,tournamentRecord:e,sourceMatchUp:u,matchUpId:S});if(A.error)return v({result:A,stack:c})}}if(l){let g=iv({...t,matchUpId:l.matchUpId,targetMatchUp:l,tournamentRecord:e,sourceMatchUp:u});if(g.error)return v({result:g,stack:c})}return v({result:{...R},stack:c})}function iv(t){let{inContextDrawMatchUps:e,tournamentRecord:r,drawDefinition:n,sourceMatchUp:o,targetMatchUp:i,matchUpsMap:s}=t,a=n.structures.find(({structureId:Y})=>Y===i.structureId),c=t.matchUpStatus===Me?Me:fe,u=t.matchUpStatus===Me?bt:Ot,p="conditionallyAdvanceDrawPosition",m=s.drawMatchUps.find(Y=>Y.matchUpId===i.matchUpId);if(!m)return{error:or};let d=o?.drawPositions||[],l=m.drawPositions?.filter(Boolean),f=o?.structureId===i.structureId;if(f&&ve(d,l)&&(l=l.filter(Y=>!d.includes(Y))),f&&l.length>1)return v({result:{error:La},stack:p});let{pairedPreviousMatchUpIsDoubleExit:g,pairedPreviousMatchUp:I}=Ph(t),h=Je({matchUpId:i.matchUpId,inContextDrawMatchUps:e,drawDefinition:n}),{targetMatchUps:S,targetLinks:T}=h,{loserTargetDrawPosition:A,winnerMatchUp:P,loserMatchUp:y}=S;if(y){let{loserTargetLink:Y}=T,k=sv({loserTargetDrawPosition:A,loserMatchUp:y,tournamentRecord:r,loserTargetLink:Y,drawDefinition:n,matchUpsMap:s});if(k.error)return v({result:k,stack:p})}let E=m.drawPositions?.filter(Boolean)||[],U=E.length===1,M=t.walkoverWinningSide||U&&Vm({drawPosition:E[0],matchUpId:i.matchUpId,inContextDrawMatchUps:e})||void 0,N=[Ot,bt].includes(m.matchUpStatus)&&!E.length,C=m.finishingRound===1,D=N&&!C?c:u,O=e.find(Y=>Y.matchUpId===I.matchUpId),b=[],_;o&&(o?.structureId===O?.structureId?o.roundPosition<I?.roundPosition?_=1:_=2:i.feedRound?o.structureId===i.structureId?_=2:_=1:M&&(_=3-M));let L=t.matchUpStatus,F=I?.matchUpStatus;_===1?b=[{matchUpStatus:WT(L),previousMatchUpStatus:L,sideNumber:1},{matchUpStatus:WT(F),previousMatchUpStatus:F,sideNumber:2}]:_===2&&(b=[{matchUpStatus:WT(F),previousMatchUpStatus:F,sideNumber:1},{matchUpStatus:WT(L),previousMatchUpStatus:L,sideNumber:2}]),b.length&&(b=b.map(Y=>rt(Y)));let w=yn({...t,winningSide:M,matchUp:m,matchUpStatusCodes:b,context:p,matchUpStatus:D});if(w.error)return v({result:w,stack:p});if(N)return Ld({...t,matchUpStatus:D,targetData:h});if(!P)return v({result:{...R},stack:p});let x=l.length===2?l[M-1]:l[0],{positionAssignments:H}=Dt({structure:a}),V=H?.find(Y=>Y.drawPosition===x),W=s.drawMatchUps.find(Y=>Y.matchUpId===P.matchUpId),B=W?.drawPositions?.filter(Boolean),q=B.length===1;if(x){if(V?.bye){let Y=Je({matchUpId:W.matchUpId,inContextDrawMatchUps:e,drawDefinition:n});if(q){let k=B.filter(Boolean)[0],K=Vm({drawPosition:k,matchUpId:W.matchUpId,inContextDrawMatchUps:e}),X=yn({appliedPolicies:t.appliedPolicies,matchUpId:W.matchUpId,matchUp:W,matchUpStatus:u,matchUpStatusCodes:[],removeScore:!0,context:p,drawDefinition:n,winningSide:K});return X.error?v({result:X,stack:p}):Ih({drawPositionToAdvance:k,matchUpId:W.matchUpId,inContextDrawMatchUps:e,drawDefinition:n,matchUpsMap:s})}else if([Ot,bt].includes(P.matchUpStatus)){let k=Ld({...t,matchUpId:W.matchUpId,matchUpStatus:D,targetData:Y});if(k.error)return v({result:k,stack:p})}return v({result:{...R},stack:p})}return cc({matchUpId:P.matchUpId,drawPosition:x,inContextDrawMatchUps:e,drawDefinition:n})}else if(g){if(!W)return{error:or};if(q){let K=B[0],X=Vm({matchUpId:i.matchUpId,inContextDrawMatchUps:e,drawPosition:K});console.log("existing drawPosition is winningSide",{walkoverWinningSide:X})}let Y=[Ot,bt].includes(W.matchUpStatus)?u:c,k=yn({matchUpId:W.matchUpId,appliedPolicies:t.appliedPolicies,matchUp:W,matchUpStatusCodes:[],removeScore:!0,context:p,drawDefinition:n,matchUpStatus:Y});if(k.error)return v({result:k,stack:p});if(Y===c){let K=Ld({...t,matchUpId:i.matchUpId,matchUpStatus:Y,targetData:h});if(K.error)return K}}return v({result:{...R},stack:p})}function sv(t){let{loserTargetDrawPosition:e,tournamentRecord:r,loserTargetLink:n,drawDefinition:o,matchUpsMap:i,event:s}=t,a=n?.target?.structureId,{structure:c}=st({drawDefinition:o,structureId:a});return c?yr({drawPosition:e,tournamentRecord:r,drawDefinition:o,structureId:a,matchUpsMap:i,event:s}):{error:Ao}}function WT(t){return t===fe?Ot:t===Me?bt:t}function av(t){let{tournamentRecord:e,drawDefinition:r,matchUpStatus:n,structure:o,matchUp:i}=t,s=!!(i.tieMatchUps&&!i.rondPosition&&t.inContextDrawMatchUps.find(h=>h.matchUpId===i.matchUpId).containerStructureId),a="attemptToSetMatchUpStatus",c=n===Ut,u=i.winningSide,p=[fe,Me].includes(n),m=ha({matchUpStatus:n}),d=Df({matchUpStatus:n}),l=!m&&!d,f=t.matchUpTieId||u&&m&&!p,g=u&&p,I=()=>yn({...t,removeScore:[Lo,Ot].includes(n),matchUpStatus:n||Kt});return l&&{error:Xg}||f&&WN(t)||g&&Qk(t)||u&&Ac(t)||d&&I()||c&&ov({tournamentRecord:e,drawDefinition:r,structure:o,matchUp:i})||!m&&{error:Xg}||p&&Xk(t)||s&&WN(t)||v({result:{error:Zs},stack:a})}function Qk(t){let e=Ac(t);return e.error?e:Ld(t)}function Xk(t){let e=WN({...t,removeScore:!0});return e.error?e:Ld(t)}function WN(t){let e="scoreModification";if(t.isCollectionMatchUp&&t.dualMatchUp?.winningSide&&!t.projectedWinningSide){let i=Ac(t);if(i.error)return v({result:i,stack:e})}let n=!!t.matchUp.collectionId,o=yn({...t,context:e});if(n){let{matchUpTieId:i,drawDefinition:s,matchUpsMap:a}=t,c=En({tournamentRecord:t.tournamentRecord,appliedPolicies:t.appliedPolicies,matchUpId:i,event:t.event,drawDefinition:s,matchUpsMap:a});if(c.error)return v({result:c,stack:e});Object.assign(o,{tieMatchUpResult:c})}return v({result:o,stack:e})}function cv({drawDefinition:t,structure:e,matchUp:r}){let{drawPositions:n}=r,{positionAssignments:o}=Dt({drawDefinition:t,structure:e}),s=o?.filter(({drawPosition:m})=>n?.includes(m))?.map(m=>{let{extension:d}=ut({element:m,name:wo});return d?.value?.groupOrder}),{containerStructures:a}=zi({drawDefinition:t}),c=a[e.structureId];return{structureIds:Rs({drawDefinition:t,structureId:c})?.links?.source?.filter(m=>ve(s,m.source?.finishingPositions||[])).map(m=>m.source.structureId)}}function jT({drawDefinition:t,structure:e,matchUp:r}){let n=[];if(e.finishingPosition===Ms&&qo({drawDefinition:t,structure:e})){let{structureIds:i}=cv({drawDefinition:t,structure:e,matchUp:r});i?.length&&n.push(...i)}return{connectedStructureIds:n}}function uv(t){let e,{inContextDrawMatchUps:r,inContextMatchUp:n,drawDefinition:o,winningSide:i}=t,s=t.targetData.targetLinks?.winnerTargetLink;if(s.target.feedProfile===Wr){let a=n.sides.find(({sideNumber:u})=>u!==i).participantId,c=r.find(u=>u.structureId===s.target.structureId&&u.roundNumber===s.target.roundNumber&&u.sides.some(({participantId:p})=>p===a));if(c?.matchUpStatus===Kt){let u=Je({matchUpId:c.matchUpId,inContextDrawMatchUps:r,drawDefinition:o});if(!fi({inContextDrawMatchUps:r,drawDefinition:o,targetData:u})){let{structure:m}=st({structureId:c.structureId,drawDefinition:o}),d=Dt({structure:m}).positionAssignments;for(let l of d||[])if(l.participantId===a){let f=n.sides.find(({sideNumber:g})=>g===i).participantId;if(l.participantId=f,m?.positionAssignments)m.positionAssignments=d;else if(m?.structures){let g=Object.assign({},...(d||[]).map(I=>({[I.drawPosition]:I.participantId})));for(let I of m.structures)I.positionAssignments?.forEach(h=>h.participantId=g[h.drawPosition])}fo({tournamentId:t.tournamentRecord?.tournamentId,event:t.event,drawDefinition:o,structure:m}),e=!0}}}}return{...R,qualifierReplaced:e}}function pv(t){let e,{inContextDrawMatchUps:r,inContextMatchUp:n,drawDefinition:o,winningSide:i}=t,s=t.targetData.targetLinks?.winnerTargetLink;if(s.target.feedProfile===Wr){let a=n.sides.find(({sideNumber:p})=>p===i)?.participantId,c=r.filter(p=>p.structureId===s.target.structureId&&p.roundNumber===s.target.roundNumber&&p.sides.some(({participantId:m,qualifier:d})=>d&&!m)),u=en(c);if(u?.matchUpStatus===Kt){let p=Je({matchUpId:u.matchUpId,inContextDrawMatchUps:r,drawDefinition:o});if(!fi({inContextDrawMatchUps:r,drawDefinition:o,targetData:p})){let d=u.sides.find(g=>g.qualifier&&!g.participantId)?.drawPosition,{structure:l}=st({structureId:u.structureId,drawDefinition:o});if(!l)return{error:_t};let f=Dt({structure:l}).positionAssignments;for(let g of f||[])if(g.drawPosition===d&&!g.participantId){if(g.participantId=a,l.positionAssignments)l.positionAssignments=f;else if(l.structures){let I=Object.assign({},...(f||[]).map(h=>({[h.drawPosition]:h.participantId})));for(let h of l.structures)h.positionAssignments?.forEach(S=>S.participantId=I[S.drawPosition])}fo({tournamentId:t.tournamentRecord?.tournamentId,event:t.event,drawDefinition:o,structure:l}),e=!0}}}}return{...R,qualifierPlaced:e}}function mv(t){let e="attemptToSetWinningSide",r,{appliedPolicies:n,disableAutoCalc:o,drawDefinition:i,dualMatchUp:s,winningSide:a,structure:c,matchUp:u}=t;if(s?._disableAutoCalc&&o!==!1)return Qm(t);if(u.winningSide&&u.winningSide!==a){let{connectedStructureIds:l}=jT({drawDefinition:i,structure:c,matchUp:u});l.length&&(console.log({connectedStructureIds:l}),r=!0);let f=Ac(t);if(f.error)return f}let p=zh(t);if(p.error)return v({result:p,stack:e});let m,d;return t.qualifierChanging&&n?.[xc]?.autoReplaceQualifiers&&(m=uv(t).qualifierReplaced),t.qualifierAdvancing&&n?.[xc]?.autoPlaceQualifiers&&(d=pv(t).qualifierPlaced),v({result:rt({...R,...p,connectedStructures:r,qualifierReplaced:m,qualifierPlaced:d}),stack:e})}var YT={drawPositionToRemove:"green",iteration:"brightred",winner:"green",loser:"brightred"};function jN(t){let{inContextDrawMatchUps:e,appliedPolicies:r,drawDefinition:n,matchUpsMap:o,targetData:i,matchUp:s}=t,{iteration:a=0}=t;a+=1;let c="removeDoubleExit";vn({method:c,color:"brightyellow",iteration:a,keyColors:YT});let{targetLinks:{loserTargetLink:u},targetMatchUps:{loserMatchUp:p,winnerMatchUp:m,loserTargetDrawPosition:d}}=i;if(m&&m.matchUpStatus!==Ut){let{stage:l,roundNumber:f,roundPosition:g}=m;vn({winner:"winner",stage:l,roundNumber:f,roundPosition:g,keyColors:YT}),dv({...t,targetMatchUp:m,sourceMatchUp:s,iteration:a})}if(p&&p.matchUpStatus!==Ut){let l=e.find(({matchUpId:T})=>T===p.matchUpId),{structure:f}=st({drawDefinition:n,structureId:l.structureId}),{stage:g,roundNumber:I,roundPosition:h,feedRound:S}=p;if(vn({loser:"loser",stage:g,roundNumber:I,roundPosition:h,keyColors:YT,feedRound:S}),r?.progression?.doubleExitPropagateBye)HT({drawPosition:d,targetLink:u,inContextDrawMatchUps:e,drawDefinition:n,matchUpsMap:o});else{let T=dv({...t,structure:f,targetMatchUp:p,iteration:a});if(T.error)return v({result:T,stack:c})}}return v({result:{...R},stack:c})}function dv(t){let{inContextDrawMatchUps:e,appliedPolicies:r,drawDefinition:n,sourceMatchUp:o,targetMatchUp:i,matchUpsMap:s,structure:a,iteration:c}=t,u="conditionallyRemoveDrawPosition";vn({method:u});let p=Je({matchUpId:i.matchUpId,inContextDrawMatchUps:e,drawDefinition:n}),{targetMatchUps:{winnerMatchUp:m}}=p,d=s?.drawMatchUps.find(A=>A.matchUpId===i.matchUpId),l=[],f,g,I;if(i.feedRound)I=m?.drawPositions?.filter(Boolean)?.find(P=>i.drawPositions.includes(P));else if(!o)I=Wt(i?.drawPositions||[],m?.drawPositions||[])?.[0];else if(g=Nh({structureId:a.structureId,matchUp:o,matchUpsMap:s})?.pairedPreviousMatchUp,f=[fe,Me].includes(g?.matchUpStatus),l=g?.drawPositions?.filter(Boolean)||[],[...ie,Ut].includes(g?.matchUpStatus)||g?.winningSide){let P=o.drawPositions||[],y=i.drawPositions?.filter(Boolean);ve(P,y)&&(y=y?.filter(U=>!P.includes(U))),I=P.concat(l).find(U=>y?.includes(U))}if(m&&I){let{stage:A,roundNumber:P,roundPosition:y}=m;vn({method:"removeDirectedWinner",drawPositionToRemove:I,keyColors:YT,color:"brightgreen",stage:A,roundNumber:P,roundPosition:y}),HN({winningDrawPosition:I,winnerMatchUp:m,inContextDrawMatchUps:e,drawDefinition:n,matchUpsMap:s})}let h=jN({targetData:p,matchUp:i,inContextDrawMatchUps:e,appliedPolicies:r,drawDefinition:n,matchUpsMap:s,structure:a,iteration:c});if(h.error)return v({result:h,stack:u});let S=Jk({pairedPreviousDoubleExit:f,noContextTargetMatchUp:d}),T=!f;return h=yn({...t,matchUpId:i.matchUpId,matchUp:d,removeWinningSide:!0,matchUpStatusCodes:[],context:u,matchUpStatus:S,removeScore:T,score:{scoreStringSide1:"",scoreStringSide2:"",sets:void 0}}),h.error?v({result:h,stack:u}):{...R}}function Jk({pairedPreviousDoubleExit:t,noContextTargetMatchUp:e}){return e.matchUpStatus===Ut?Ut:t?[Me,bt].includes(e?.matchUpStatus)?bt:Ot:Kt}function lv(t){let e,{inContextDrawMatchUps:r,inContextMatchUp:n,drawDefinition:o}=t,i=t.targetData.targetLinks?.winnerTargetLink;if(i.target.feedProfile===Wr){let s=n.sides?.find(({sideNumber:c})=>c===n.winningSide)?.participantId,a=r.find(c=>c.structureId===i.target.structureId&&c.roundNumber===i.target.roundNumber&&c.sides?.some(({participantId:u})=>u===s));if(a&&a.matchUpStatus===Kt){let c=Je({matchUpId:a.matchUpId,inContextDrawMatchUps:r,drawDefinition:o});if(!fi({inContextDrawMatchUps:r,drawDefinition:o,targetData:c})){let{structure:p}=st({structureId:a.structureId,drawDefinition:o}),m=Dt({structure:p}).positionAssignments;for(let d of m||[])if(d.participantId===s){if(d.participantId=void 0,p?.positionAssignments)p.positionAssignments=m;else if(p?.structures){let l=Object.assign({},...(m||[]).map(f=>({[f.drawPosition]:f.participantId})));for(let f of p?.structures||[])f.positionAssignments?.forEach(g=>g.participantId=l[g.drawPosition])}fo({tournamentId:t.tournamentRecord?.tournamentId,event:t.event,drawDefinition:o,structure:p}),e=!0}}}}return{qualifierRemoved:e}}function gv(t){let{matchUp:e,matchUpStatus:r,score:n,winningSide:o}=t,i="noDownStreamDependencies";if([fe,Me].includes(e?.matchUpStatus)&&![fe,Me].includes(r)){let I=jN(t);if(I.error)return v({result:I,stack:i})}let a=r===fe,c=he({score:n})&&!a&&(t.isCollectionMatchUp&&!t.projectedWinningSide||!o),u=t?.inContextMatchUp?.collectionId&&nv(t.inContextMatchUp),p=t.removeScore||!u&&![No,kr].includes(r||No),m=t.isCollectionMatchUp&&t.dualMatchUp.winningSide&&!t.projectedWinningSide||e.winningSide&&!o&&!he({score:n}),d=r&&r!==Kt,l=I=>{let h,{structure:S,drawDefinition:T,dualMatchUp:A,disableAutoCalc:P}=t;if(A?._disableAutoCalc&&P!==!1)return Qm(t);let{connectedStructureIds:y}=jT({drawDefinition:T,structure:S,matchUp:e});y.length&&(console.log({connectedStructureIds:y}),h=!0),Object.assign(t,{removeScore:I});let E=Ac(t);if(E.error)return E;if(t.removingQualifier&&t.appliedPolicies?.[xc]?.autoRemoveQualifiers){let U=lv(t);return{...R,connectedStructures:h,...U}}return{...R,connectedStructures:h}};if(m&&o&&t.isCollectionMatchUp)return fv(t);let f=[Lo,kr].includes(r)&&t.dualWinningSideChange,g=(o||f)&&mv(t)||c&&l(p)||d&&av(t)||m&&l(p)||e&&fv({...t,removeScore:!0})||{...R};return v({result:g,stack:i})}function fv(t){let e="scoreModification";if(t.isCollectionMatchUp&&t.dualMatchUp?.winningSide&&!t.projectedWinningSide){let o=Ac(t);if(o.error)return o}let n=yn({...t,context:e});if(t.isCollectionMatchUp){let{matchUpTieId:o,drawDefinition:i,event:s,matchUpsMap:a}=t,{removeWinningSide:c}=En({tournamentRecord:t.tournamentRecord,appliedPolicies:t.appliedPolicies,matchUpId:o,drawDefinition:i,matchUpsMap:a,event:s});c&&console.log("REMOVE WINNING SIDE")}return v({result:n,stack:e})}function _o(t){let e="addMatchUpScheduledTime",r=t.matchUp,{removePriorValues:n,tournamentRecord:o,drawDefinition:i,disableNotice:s,scheduledTime:a,matchUpId:c}=t;if(!c)return v({result:{error:Ne},stack:e});if(!_c(a))return v({result:{error:io},stack:e});if(!r){let I=xt({drawDefinition:i,matchUpId:c});if(I.error)return v({result:I,stack:e});r=I.matchUp}let u=At(a),p=Ji({matchUp:r}).scheduledDate,m=u&&!p;if((Ef({matchUp:r}).timeModifiers||[])?.length){let I=YN({disableNotice:!0,removePriorValues:n,tournamentRecord:o,timeModifiers:[],drawDefinition:i,matchUpId:c,matchUp:r});if(I?.error)return v({result:I,stack:e})}let f=qa(a,!0,m);return Zr({duplicateValues:!1,removePriorValues:n,tournamentRecord:o,drawDefinition:i,disableNotice:s,matchUpId:c,timeItem:{itemType:_s,itemValue:f}})}function YN({removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,timeModifiers:o,matchUpId:i,matchUp:s}){let a="addMatchUpTimeModifiers";if(!i)return v({result:{error:Ne},stack:a});if(o!==void 0&&!Array.isArray(o))return v({info:Tn("timeModifiers"),result:{error:G},stack:a});if(!s){let l=xt({drawDefinition:r,matchUpId:i});if(l.error)return v({result:l,stack:a});s=l.matchUp}let c=Ef({matchUp:s}).timeModifiers||[],u=o.filter(l=>!c.includes(l));if(o.length&&!u.length)return{...R};if(u.some(l=>th.includes(l))){c=c.filter(f=>!th.includes(f));let l=_o({disableNotice:!0,removePriorValues:t,scheduledTime:"",tournamentRecord:e,drawDefinition:r,matchUpId:i});if(l.error)return v({result:l,stack:a})}let m=o?.length?[...u,...c]:void 0;return Zr({duplicateValues:!1,removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,matchUpId:i,timeItem:{itemType:hf,itemValue:m}})}function Vp({removePriorValues:t,tournamentRecords:e,tournamentRecord:r,drawDefinition:n,disableNotice:o,courtDayDate:i,matchUpId:s,courtIds:a}){if(!r&&!e)return{error:j};if(!s)return{error:Ne};let c=xt({drawDefinition:n,matchUpId:s});if(c.error)return c;if(c?.matchUp?.matchUpType!==pn)return{error:ze};if(!(a===void 0||Array.isArray(a)&&a.length&&a.every(d=>typeof d=="string")))return{error:G,context:{courtIds:a}};let p;if(a){let d=e||r&&{[r.tournamentId]:r},l=oo({tournamentRecords:d});if(l.error)return l;let f=l.courts?.filter(g=>a.includes(g.courtId));if(f?.length!==a.length)return{error:G,context:{courtIds:a}};p=f?.map(g=>({venueId:g.venueId,courtId:g.courtId}))}return Zr({duplicateValues:!1,removePriorValues:t,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:s,timeItem:{itemType:ho,itemDate:i,itemValue:p}})}function Ks({removePriorValues:t,tournamentRecords:e,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:i,venueId:s}){if(!r)return{error:j};if(!i)return{error:Ne};if(s){let c=jo({tournamentRecords:e,tournamentRecord:r,venueId:s});if(c.error)return c}return Zr({duplicateValues:!1,removePriorValues:t,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:i,timeItem:{itemType:bs,itemValue:s}})}function Fi({removePriorValues:t,tournamentRecords:e,tournamentRecord:r,drawDefinition:n,disableNotice:o,courtDayDate:i,matchUpId:s,courtId:a}){if(!r&&!e)return{error:j};if(!s)return{error:Ne};if(a){let u=Zi({tournamentRecords:e,tournamentRecord:r,courtId:a});if(u.error)return u;let p=u.venue?.venueId;Ks({tournamentRecords:e,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:s,venueId:p})}return Zr({duplicateValues:!1,removePriorValues:t,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:s,timeItem:{itemType:si,itemDate:i,itemValue:a}})}function fs(t,e){let r=fI.test(t)?t:qt(t),n=At(t)||At(e)||Kn(new Date);return new Date(`${n}T${r}`).getTime()}function Bp({errorOnAnachronism:t=!1,checkChronology:e=!0,matchUpDependencies:r,inContextMatchUps:n,removePriorValues:o,tournamentRecords:i,tournamentRecord:s,drawDefinition:a,disableNotice:c,drawMatchUps:u,matchUpId:p,schedule:m,event:d}){if(!m)return{error:et,info:"Missing schedule"};if(!a)return{error:z};if(!p)return{error:Ne};let l="addMatchUpScheduleItems",f,g;if(u)f=u.find(D=>D.matchUpId===p);else{let D=xt({drawDefinition:a,event:d,matchUpId:p});if(D.error)return D;f=D.matchUp}let{endTime:I,courtId:h,courtIds:S,courtOrder:T,resumeTime:A,scheduledDate:P,scheduledTime:y,startTime:E,stopTime:U,timeModifiers:M,venueId:N}=m;e&&(!r||!n)&&({matchUpDependencies:r,matchUps:n}=xr({drawDefinition:a}));let C=r?.[p]?.matchUpIds;if(m.scheduledDate&&e&&C){let D=n?.filter(O=>(O.schedule?.scheduledDate||At(O.schedule?.scheduledTime))&&C.includes(O.matchUpId)).map(({schedule:O})=>{let b=om(O);return new Date(b).getTime()});if(D?.length){let O=om(m),b=new Date(O).getTime();if(Math.max(...D)>=b){if(t)return v({result:{error:qg},stack:l});g=qg}}}if(P!==void 0){let D=Fd({disableNotice:!0,removePriorValues:o,tournamentRecord:s,drawDefinition:a,scheduledDate:P,matchUpId:p});if(D?.error)return v({result:D,stack:l,context:{scheduledDate:P}})}if(y!==void 0){let D=_o({disableNotice:!0,removePriorValues:o,tournamentRecord:s,drawDefinition:a,scheduledTime:y,matchUpId:p,matchUp:f});if(D?.error)return v({result:D,stack:l,context:{scheduledTime:y}})}if(E!==void 0){let D=$T({disableNotice:!0,removePriorValues:o,tournamentRecord:s,drawDefinition:a,matchUpId:p,startTime:E,event:d});if(D?.error)return v({result:D,stack:l,context:{startTime:E}})}if(U!==void 0){let D=zT({disableNotice:!0,removePriorValues:o,tournamentRecord:s,drawDefinition:a,matchUpId:p,stopTime:U,event:d});if(D?.error)return v({result:D,stack:l,context:{stopTime:U}})}if(A!==void 0){let D=QT({disableNotice:!0,removePriorValues:o,tournamentRecord:s,drawDefinition:a,resumeTime:A,matchUpId:p,event:d});if(D?.error)return v({result:D,stack:l,context:{resumeTime:A}})}if(I!==void 0){let D=KT({disableNotice:!0,removePriorValues:o,tournamentRecord:s,drawDefinition:a,matchUpId:p,endTime:I,event:d});if(D?.error)return v({result:D,stack:l,context:{endTime:I}})}if(S!==void 0){let D=Vp({disableNotice:!0,removePriorValues:o,tournamentRecord:s,drawDefinition:a,matchUpId:p,courtIds:S});if(D?.error)return v({result:D,stack:l,context:{courtIds:S}})}if(h!==void 0&&P!==void 0){let D=Fi({courtDayDate:P,disableNotice:!0,removePriorValues:o,tournamentRecords:i,tournamentRecord:s,drawDefinition:a,matchUpId:p,courtId:h});if(D?.error)return v({result:D,stack:l,context:{courtId:h}})}if(N!==void 0){let D=Ks({disableNotice:!0,removePriorValues:o,tournamentRecords:i,tournamentRecord:s,drawDefinition:a,matchUpId:p,venueId:N});if(D?.error)return v({result:D,stack:l,context:{venueId:N}})}if(T!==void 0&&lt(T)){let D=qT({disableNotice:!0,removePriorValues:o,tournamentRecord:s,drawDefinition:a,courtOrder:T,matchUpId:p});if(D?.error)return v({result:D,stack:l,context:{courtOrder:T}})}if(M!==void 0){let D=YN({disableNotice:!0,removePriorValues:o,tournamentRecord:s,drawDefinition:a,timeModifiers:M,matchUpId:p,matchUp:f});if(D?.error)return v({result:D,stack:l,context:{timeModifiers:M}})}return c||ht({tournamentId:s?.tournamentId,eventId:d?.eventId,context:l,drawDefinition:a,matchUp:f}),g?{...R,warnings:[g]}:{...R}}function Fd({scheduledDate:t,removePriorValues:e,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:i}){if(!i)return{error:Ne};let s=t&&ao.test(t);if(t&&!s)return{error:ir};let c={itemValue:At(t),itemType:Os};return Zr({duplicateValues:!1,removePriorValues:e,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:i,timeItem:c})}function qT({removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,courtOrder:o,matchUpId:i}){if(!i)return{error:Ne};if(o&&!lt(o))return{error:G,info:"courtOrder must be numeric"};let s=o&&ct(o);return Zr({duplicateValues:!1,removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,matchUpId:i,timeItem:{itemType:If,itemValue:s}})}function qN({removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,participantId:o,officialType:i,matchUpId:s}){if(!s)return{error:Ne};if(!o)return{error:te};if(e){let c=$t({tournamentRecord:e,participantFilters:{participantTypes:[It],participantRoles:[JE]}}).participants??[];if(!Uo({tournamentParticipants:c,participantId:o}))return{error:Jt}}let a={itemType:"SCHEDULE.ASSIGNMENT.OFFICIAL",itemValue:o};return i&&(a.itemSubTypes=[i]),Zr({duplicateValues:!1,removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,matchUpId:s,timeItem:a})}function $T({removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,matchUpId:o,startTime:i,event:s}){if(!o)return{error:Ne};if(!_c(i))return{error:io};let{matchUp:a}=xt({drawDefinition:r,event:s,matchUpId:o}),{scheduledDate:c}=Ji({matchUp:a}),p=(a?.timeItems??[]).filter(m=>[bi,ai,ci].includes(m?.itemType)).map(m=>fs(m.itemValue,c)).reduce((m,d)=>!m||d<m?d:m,void 0);if(!p||fs(i,c)<p){a?.timeItems&&(a.timeItems=a.timeItems.filter(l=>l.itemType!==So));let m=qa(i,!0,!0);return Zr({duplicateValues:!1,removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,matchUpId:o,timeItem:{itemType:So,itemValue:m}})}else return{error:Ny}}function KT({validateTimeSeries:t=!0,removePriorValues:e,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:i,endTime:s,event:a}){if(!i)return{error:Ne};if(!_c(s))return{error:io};let{matchUp:c}=xt({drawDefinition:n,event:a,matchUpId:i}),{scheduledDate:u}=Ji({matchUp:c}),m=(c?.timeItems??[]).filter(d=>[So,ai,bi].includes(d?.itemType)).map(d=>fs(d.itemValue,u)).reduce((d,l)=>!d||l>d?l:d,void 0);if(!t||!m||fs(s,u)>m){c?.timeItems&&(c.timeItems=c.timeItems.filter(f=>f.itemType!==ci));let d=qa(s,!0,!0);return Zr({duplicateValues:!1,removePriorValues:e,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:i,timeItem:{itemType:ci,itemValue:d}})}else return{error:Uy}}function zT({removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,matchUpId:o,stopTime:i,event:s}){if(!o)return{error:Ne};if(!_c(i))return{error:io};let{matchUp:a}=xt({drawDefinition:r,event:s,matchUpId:o}),{scheduledDate:c}=Ji({matchUp:a}),u=a?.timeItems??[];if(u.reduce((g,I)=>I.itemType===ci||g,void 0))return{error:iI};let m=u.filter(g=>[So,ai,bi].includes(g?.itemType)).sort((g,I)=>fs(g.itemValue,c)-fs(I.itemValue,c)),d=m[m.length-1],l=d&&d.itemType===bi,f=m.filter(g=>!l||g.createdAt!==d.createdAt).map(g=>fs(g.itemValue,c)).reduce((g,I)=>!g||I>g?I:g,void 0);if(fs(i,c)>f){if(a?.timeItems&&l){let h=d.createdAt;a.timeItems=a.timeItems.filter(S=>S.createdAt!==h)}let I={itemValue:qa(i,!0,!0),itemType:bi};return Zr({duplicateValues:!0,removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,matchUpId:o,timeItem:I})}else return{error:Py}}function QT({removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,resumeTime:o,matchUpId:i,event:s}){if(!i)return{error:Ne};if(!_c(o))return{error:io};let{matchUp:a}=xt({drawDefinition:r,event:s,matchUpId:i}),{scheduledDate:c}=Ji({matchUp:a}),u=a?.timeItems??[];if(u.reduce((g,I)=>I.itemType===ci||g,void 0))return{error:iI};let m=u.filter(g=>[So,ai,bi].includes(g?.itemType)).sort((g,I)=>fs(g.itemValue,c)-fs(I.itemValue,c)),d=m[m.length-1],l=d&&d.itemType===ai,f=m.filter(g=>!l||g.createdAt!==d.createdAt).map(g=>fs(g.itemValue,c)).reduce((g,I)=>!g||I>g?I:g,void 0);if(fs(o,c)>f){if(a?.timeItems&&l){let h=d.createdAt;a.timeItems=a.timeItems.filter(S=>S.createdAt!==h)}let I={itemValue:qa(o,!0,!0),itemType:ai};return Zr({duplicateValues:!0,removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,matchUpId:i,timeItem:I})}else return{error:QM}}function Iv(t){let{tournamentRecord:e,inContextMatchUp:r,structure:n,drawDefinition:o}=t,i=r.roundNumber,s=r.sides.find(y=>y.sideNumber===r.winningSide),a=r.sides.find(y=>y.sideNumber!==r.winningSide),{drawPosition:c,participantId:u}=s,{drawPosition:p,participantId:m}=a,d="swapWinnerLoser",{matchUps:l}=Pt(t),f=l.filter(({drawPositions:y,roundNumber:E})=>y?.includes(c)&&E>i);Tr({changeWinner:!0})&&console.log({existingWinnerSubsequentMatchUps:f}),f.forEach(y=>{y.drawPositions=y.drawPositions?.map(E=>E===c?p:E)||[],ht({tournamentId:e?.tournamentId,eventId:t.event?.eventId,context:d,drawDefinition:o,matchUp:y})});let{stage:g,stageSequence:I}=n,h=o.structures.filter(({stage:y,stageSequence:E})=>y===g&&E>I).map(({structureId:y})=>y),{targetLinks:{loserTargetLink:S,winnerTargetLink:T}}=t.targetData,A=[S?.target.structureId,T?.target?.structureId].filter(Boolean);return o.structures.filter(({stage:y,structureId:E})=>y!==g&&A.includes(E)).forEach(({stage:y,stageSequence:E,structureId:U})=>{h.includes(U)||h.push(U),o.structures.filter(({stage:M,stageSequence:N})=>M===y&&N>E).forEach(({structureId:M})=>{h.includes(M)||h.push(M)})}),o.structures.filter(({structureId:y})=>h.includes(y)).forEach(y=>{let{positionAssignments:E}=Dt({structure:y}),U=E?.find(({participantId:N})=>N===u),M=E?.find(({participantId:N})=>N===m);U&&(U.participantId=m),M&&(M.participantId=u)}),yn({...t,context:d})}function Nu(t){let e="setMatchUpStatus";t.matchUpStatus&&[Ot,fe].includes(t.matchUpStatus)&&(t.score=void 0);let{allowChangePropagation:r,disableScoreValidation:n,tournamentRecords:o,tournamentRecord:i,disableAutoCalc:s,enableAutoCalc:a,drawDefinition:c,matchUpStatus:u,winningSide:p,matchUpId:m,event:d,score:l}=t;if(!c)return{error:z};if(u&&[Lo,No,kr,Kt].includes(u)&&p)return{error:G,winningSide:p,matchUpStatus:u};if(![void 0,...vI].includes(u))return v({result:{error:Zs},info:"matchUpStatus does not exist",stack:"setMatchUpStatus"});let f=be({drawDefinition:c}),{matchUps:g}=re({nextMatchUps:!0,inContext:!0,drawDefinition:c,matchUpsMap:f,event:d}),I=f.drawMatchUps.find(V=>V.matchUpId===m),h=g?.find(V=>V.matchUpId===m);if(!I||!g)return{error:De};if((I.winningSide||p)&&u===Ut)return{context:"Cannot have Bye with winningSide",error:nl,matchUpStatus:u};let S=h?.structureId,{structure:T}=st({drawDefinition:c,structureId:S}),A=h?.drawPositions?.filter(Boolean),P;if(I.matchUpType===Bt){if(s)gt({extension:{name:za,value:!0},element:I});else if(a){let V=I.winningSide;rr({name:za,element:I});let{winningSide:W,scoreStringSide1:B,scoreStringSide2:q,set:Y}=lu({drawDefinition:c,matchUpsMap:f,structure:T,matchUp:I,event:d}),k={scoreStringSide1:B,scoreStringSide2:q,sets:Y?[Y]:[]};P=W!==V,Object.assign(t,{winningSide:W,dualWinningSideChange:P,projectedWinningSide:W,score:k})}Pa({tournamentId:i?.tournamentId,inContextDualMatchUp:h,eventId:d?.eventId,dualMatchUp:I,drawDefinition:c})}if(I.matchUpType===Bt&&u&&[Xa].includes(u))return{error:G,info:"Not supported for matchUpType: TEAM"};let y=h?.matchUpTieId,E=Je({matchUpId:y||m,inContextDrawMatchUps:g,drawDefinition:c});if(l&&I.matchUpType!==Bt&&!n){let V=I.matchUpFormat??T?.matchUpFormat??c?.matchUpFormat??d?.matchUpFormat,W=XS({existingMatchUpStatus:I.matchUpStatus,matchUpFormat:V,matchUpStatus:u,winningSide:p,score:l});if(W.error)return W}let U=I?.sides?[]:Dt({drawDefinition:c,structureId:S}).positionAssignments,M=h?.sides?.map(V=>V.participantId).filter(Boolean).length===2||A?.length===2&&U?.filter(V=>A.includes(V.drawPosition)).every(V=>V.participantId);if(u&&_I.includes(u)&&!M)return v({info:"present in participantRequiredMatchUpStatuses",context:{matchUpStatus:u,bothSideParticipants:M},result:{error:Zs}});let N=yt({policyTypes:[xc,Mn],tournamentRecord:i,drawDefinition:c,event:d})?.appliedPolicies??{};typeof t.policyDefinitions=="object"&&Object.assign(N,t.policyDefinitions);let C=h?.stage===at&&h.finishingRound===1,D=C&&p,O=C&&I.winningSide&&!p&&(!t.matchUpStatus||t.matchUpStatus&&Df({matchUpStatus:t.matchUpStatus}))&&(!t.outcome||!he({outcome:t.outcome})),b=D&&p!==I.winningSide&&I.winningSide;if(Object.assign(t,{inContextDrawMatchUps:g,qualifierAdvancing:D,qualifierChanging:b,removingQualifier:O,inContextMatchUp:h,appliedPolicies:N,matchUpTieId:y,matchUpsMap:f,targetData:E,structure:T,matchUp:I}),y){let{matchUp:V}=xt({matchUpId:y,inContext:!0,drawDefinition:c,matchUpsMap:f,event:d});if(V){let W=Ve({matchUp:V,drawDefinition:c,structure:T,event:d})?.tieFormat,{projectedWinningSide:B}=tv({drawDefinition:c,matchUpStatus:u,dualMatchUp:V,matchUpsMap:f,winningSide:p,tieFormat:W,structure:T,matchUp:I,event:d,score:l}),q=V.winningSide;P=B!==q,Object.assign(t,{isCollectionMatchUp:!0,dualWinningSideChange:P,projectedWinningSide:B,matchUpTieId:y,dualMatchUp:V,tieFormat:W})}}let _=fi(t),L=ha({matchUpStatus:u});if(!y){if(_&&!p&&(u&&Df({matchUpStatus:u})||u&&[fe,Me].includes(u)))return{error:nl,activeDownstream:_,winningSide:p};if(p&&p===I.winningSide&&u&&!L)return{context:"winningSide must include directing matchUpStatus",error:nl,directingMatchUpStatus:L,matchUpStatus:u}}let{schedule:F}=t;if(F){let V=Bp({disableNotice:!0,tournamentRecords:o,tournamentRecord:i,drawDefinition:c,matchUpId:m,schedule:F});if(V.error)return V}let w=I.matchUpType!==Bt&&!P&&p&&I.winningSide&&I.winningSide!==p;if(r&&w&&I.roundPosition)return Iv(t);let x=p&&!y||t.projectedWinningSide;vn({activeDownstream:_,matchUpWinner:x,method:e,winningSide:p});let H=!_&&gv(t)||x&&Zk(t)||L&&hv(t)||{error:vy};return v({result:H,stack:e})}function Zk(t){let{matchUp:e,winningSide:r,matchUpTieId:n,dualWinningSideChange:o}=t;return r===e.winningSide||n&&!o?hv(t):v({stack:"winningSideWithDownstreamDependencies",result:{error:pl},context:{winningSide:r,matchUp:e}})}function hv(t){let{tournamentRecord:e,matchUp:r,event:n}=t,o=t.isCollectionMatchUp&&r.winningSide&&!t.winningSide&&!he({score:t.score}),i=t.isCollectionMatchUp?t.matchUpStatus||o&&Kt||me:t.matchUpStatus||me,s=t.removeScore||[Lo,Ot].includes(i)&&![No,kr].includes(i),a=yn({...t,matchUpStatus:i,removeWinningSide:o,context:"sms",removeScore:s});if(a.error)return a;if(t.isCollectionMatchUp){let{matchUpTieId:c,drawDefinition:u,matchUpsMap:p}=t,m=En({appliedPolicies:t.appliedPolicies,matchUpId:c,tournamentRecord:e,drawDefinition:u,matchUpsMap:p,event:n});if(m.error)return m;Object.assign(a,{tieMatchUpResult:m})}return a}function $N({tournamentRecord:t,drawDefinition:e,matchUpId:r,event:n}){if(!e)return{error:z};let{matchUp:o}=xt({drawDefinition:e,matchUpId:r,event:n});return o?.matchUpType!==pn?{error:ze}:Nu({enableAutoCalc:!0,tournamentRecord:t,drawDefinition:e,matchUpId:r,event:n})}function KN({drawDefinition:t,event:e,matchUpId:r}){if(!t)return{error:z};if(!r)return{error:Ne};let{matchUp:n}=xt({drawDefinition:t,event:e,matchUpId:r});return n?rr({name:cm,element:n}):{error:De}}function Sv({substituteParticipantId:t,existingParticipantId:e,tournamentRecord:r,drawDefinition:n,sideNumber:o,matchUpId:i,event:s}){let a="substituteParticipant";if(!n)return{error:z};if(!i)return{error:Ne};if(!e||!t)return v({result:{error:te},stack:a});let{matchUp:c}=xt({drawDefinition:n,matchUpId:i,event:s});if(!c)return{error:De};if(!c.collectionId)return v({result:{error:ze},stack:a});let u=be({drawDefinition:n}),{matchUps:p}=re({tournamentParticipants:r?.participants,inContext:!0,drawDefinition:n,matchUpsMap:u}),m=p?.find(g=>g.matchUpId===i),l=p?.find(g=>g.matchUpId===m?.matchUpTieId)?.sides?.find(g=>g.participant.individualParticipants.some(({participantId:I})=>I===e));return!l||o&&l.sideNumber!==o?{error:sn}:l.participant?.individualParticipants?.map(ft).filter(g=>g!==e)?.includes(t)?Pg({newParticipantId:t,tieMatchUpId:i,existingParticipantId:e,substitution:!0,tournamentRecord:r,drawDefinition:n,event:s}):v({result:{error:sn},stack:a})}function zN(t){return Sv(t)}function QN({drawDefinition:t,matchUpId:e,event:r}){if(!t)return{error:z};let{matchUp:n}=xt({drawDefinition:t,matchUpId:e,event:r});return gt({extension:{name:za,value:!0},element:n})}function XN(t){let e="setMatchUpFormat",{tournamentRecord:r,drawDefinition:n,scheduledDates:o,stageSequences:i,matchUpFormat:s,structureId:a,eventType:c,matchUpId:u,eventId:p,stages:m,drawId:d,event:l,force:f}=t;if(!r)return{error:j};if(!s)return{error:vu};if(s&&!Sr({matchUpFormat:s}))return v({result:{error:ka,matchUpFormat:s},stack:e});if(o&&!Array.isArray(o))return v({result:{error:G,scheduledDates:o},stack:e});if(c&&![eo,Vr].includes(c))return v({result:{error:yo},stack:e});let g=0,I=t.structureIds||a&&[a].filter(Boolean)||[],h=t.eventIds||p&&[p].filter(Boolean)||[],S=t.drawIds||d&&[d].filter(Boolean)||[];if((a||I?.length)&&!n)return v({result:{error:z},stack:e});if(d&&u&&n){let A=Rd({tournamentRecord:r,drawDefinition:n,matchUpFormat:s,structureIds:I,structureId:a,matchUpId:u});if(A.error)return A;g+=1}let T=A=>{let P=[];for(let y of A.structures||[]){if(Array.isArray(m)&&!m.includes(y.stage)||Array.isArray(i)&&!i.includes(y.stageSequence)||I?.length&&!I.includes(y.structureId))continue;I?.length&&y.matchUpFormat!==s&&(y.matchUpFormat=s,P.push(y.structureId),g+=1);let E=(f||o)&&Pt({matchUpFilters:{matchUpStatuses:[Kt]},structure:y}).matchUps,U=o&&Pt({matchUpFilters:{matchUpStatuses:[Kt]},contextFilters:{scheduledDates:o},afterRecoveryTimes:!1,inContext:!0,structure:y}).matchUps;if(E?.length){let M=U?U.map(le):E.map(le);for(let N of E)M.includes(N.matchUpId)&&(N.matchUpFormat=o?.length?s:void 0,ht({tournamentId:r?.tournamentId,eventId:l?.eventId,context:e,drawDefinition:A,matchUp:N}))}}return!P.length&&A.matchUpFormat!==s&&(A.matchUpFormat=s,g+=1),P};for(let A of r.events||[])if(!(h?.length&&!h.includes(A.eventId)||c&&c!==A.eventType||c===Le))if(Array.isArray(i)||Array.isArray(m)||I?.length||S?.length)for(let P of A.drawDefinitions||[]){if(Array.isArray(S)&&!S.includes(P.drawId))continue;let y=T(P);Rt({structureIds:y,drawDefinition:P})}else A.matchUpFormat!==s&&(A.matchUpFormat=s,g+=1);return g?{...R,modificationsCount:g}:{...R,info:Us}}function JN({inheritance:t=!0,tournamentRecord:e,drawDefinition:r,matchUpId:n,event:o}){if(!r)return{error:z};let i=xt({drawDefinition:r,matchUpId:n})?.matchUp;if(!i?.tieMatchUps)return{error:ze};let s=xt({inContext:!0,drawDefinition:r,matchUpId:n,event:o})?.matchUp,a=0;return(i?.sides||[]).forEach(c=>{c.lineUp&&delete c.lineUp}),(s?.sides||[]).forEach(c=>{if(a+=1,t===!1){let u=s?.tieFormat,p=c.participantId;u&&p&&_i({drawDefinition:r,participantId:p,lineUp:[],tieFormat:u})}ht({tournamentId:e?.tournamentId,context:"resetMatchUpLineUps",eventId:o?.eventId,drawDefinition:r,matchUp:i})}),{...R,modificationsCount:a}}function XT(t){let{matchUpFormat:e,matchUpStatus:r,winningSide:n,score:o}=t;if(!o)return{sets:[]};let i=o.sets||[],s=Ko({winnerFirst:!1,matchUpFormat:e,matchUpStatus:r,sets:i}),a=Ko({winnerFirst:!1,reversed:!0,matchUpFormat:e,matchUpStatus:r,sets:i}),c=Ko({matchUpFormat:e,matchUpStatus:r,winningSide:n,sets:i}),u=s===c?a:s;return n&&(s=n===1?c:u,a=n===2?c:u),{score:{sets:i,scoreStringSide1:s,scoreStringSide2:a}}}function Du(t){let e=jr(t);if(!t.drawDefinition){let I=t.tournamentRecord??(t.tournamentId&&e[t.tournamentId]);t.tournamentRecord||(t.tournamentRecord=I);let h=nr({eventId:t.eventId,drawId:t.drawId,tournamentRecord:I});if(h.error)return h;h.drawDefinition&&(t.drawDefinition=h.drawDefinition),t.event=h.event}let{disableScoreValidation:r,policyDefinitions:n,tournamentRecord:o,disableAutoCalc:i,enableAutoCalc:s,drawDefinition:a,matchUpFormat:c,matchUpId:u,schedule:p,event:m,notes:d}=t;if(!a)return{error:Ur};if(!u)return{error:Ne};let{policy:l}=Bo({policyType:Mn,tournamentRecord:o,event:m}),f=t.allowChangePropagation!==void 0&&t.allowChangePropagation||l?.allowChangePropagation!==void 0&&l.allowChangePropagation||void 0,{outcome:g}=t;if(c){let I=Rd({tournamentRecord:o,drawDefinition:a,matchUpFormat:c,matchUpId:u,event:m});if(I.error)return I}if(g?.score?.sets&&!g.score.scoreStringSide1){let{score:I}=XT(g);g.score=I,g.score.sets=g.score.sets.filter(h=>h.side1Score||h.side2Score||h.side1TiebreakScore||h.side2TiebreakScore)}return Nu({matchUpStatusCodes:g?.matchUpStatusCodes,matchUpStatus:g?.matchUpStatus,winningSide:g?.winningSide,allowChangePropagation:f,disableScoreValidation:r,score:g?.score,tournamentRecords:e,policyDefinitions:n,tournamentRecord:o,disableAutoCalc:i,enableAutoCalc:s,drawDefinition:a,matchUpFormat:c,matchUpId:u,schedule:p,event:m,notes:d})}function ZN(t){if(!t?.outcomes)return{error:et};if(!Array.isArray(t.outcomes))return{error:et,info:{outcomes:t.outcomes}};let e=t.tournamentRecords||t.tournamentRecord&&{[t.tournamentRecord.tournamentId]:t.tournamentRecord}||{},r=t.outcomes??[],n=r.reduce((o,i)=>o.includes(i.tournamentId)?o:o.concat(i.tournamentId),[]);for(let o of n){let i=e[o];if(!i)return{error:j};let s=r.filter(a=>a.tournamentId===o);if(s.length){let a=tV({outcomes:s,tournamentRecord:i});if(a.error)return a}}return{...R}}function tV(t){let{tournamentRecords:e,tournamentRecord:r,outcomes:n,policyDefinitions:o}=t,i={};n.forEach(s=>{let{eventId:a}=s;i[a]||(i[a]=[]),i[a].push(s)});for(let s of Object.keys(i)){let{event:a}=nr({tournamentRecord:r,eventId:s});for(let c of i[s]){let{drawId:u}=c,p=a?.drawDefinitions?.find(m=>m.drawId===u);if(p&&u){let{matchUpFormat:m,matchUpId:d}=c,l=Du({schedule:c?.schedule,tournamentRecords:e,policyDefinitions:o,tournamentRecord:r,drawDefinition:p,matchUpFormat:m,matchUpId:d,outcome:c,drawId:u,event:a});if(l.error)return l}}}return{...R}}function Tv({drawDefinition:t,matchUpId:e,outcome:r,matchUp:n}){if(!n&&!t)return{error:z};if(!r)return{error:et,info:"missing outcome"};if(!n&&!e)return{error:or};if(!n){let i=xt({drawDefinition:t,matchUpId:e});if(i.error)return i;n=i.matchUp}return typeof r!="object"||!r.score?.scoreStringSide1||!r.score?.scoreStringSide2?{error:G}:gt({element:n,extension:{name:cm,value:r}})}function tD(t){return Tv(t)}function Av({drawDefinition:t,finishingOrder:e}){if(!t)return{error:z};let r="setOrderOfFinish";if(!Array.isArray(e))return v({info:Tn("finishingOrder"),result:{error:G},stack:r});let{completedMatchUps:n,matchUpsMap:o}=ws({inContext:!0,drawDefinition:t}),i=n?.map(le)??[],s=e.map(le),{matchUpTypes:a,roundNumbers:c,structureIds:u,matchUpTieIds:p}=(n??[]).filter(({matchUpId:S})=>s.includes(S)).reduce((S,T)=>{let{matchUpTieId:A,matchUpType:P,roundNumber:y,structureId:E}=T;return S.matchUpTypes.includes(P)||S.matchUpTypes.push(P),S.roundNumbers.includes(y)||S.roundNumbers.push(y),S.structureIds.includes(E)||S.structureIds.push(E),S.matchUpTieIds.includes(A)||S.matchUpTieIds.push(A),S},{matchUpTypes:[],roundNumbers:[],structureIds:[],matchUpTieIds:[]});if(a.length>1||p.length>1||c.length>1||u.length>1)return v({info:"matchUpType, structureId and roundNumber must be equivalent",result:{error:G},stack:r});let m,d,l={},f=[],g=[];if(!e.every(({orderOfFinish:S,matchUpId:T})=>(f.push(T),S&&g.push(S),l[T]=S,m=i.includes(T),d=S===void 0||lt(S)&&Math.floor(S)>0,m&&d)))return v({result:{error:m?G:Zs},info:!m&&"matchUps must be completed"||!d&&"orderOfFinish must be integer > 0 or undefined"||void 0,stack:r});let h=n?.filter(S=>S.structureId===u[0]&&S.roundNumber===c[0]&&S.matchUpType===a[0]&&S.matchUpTieId===p[0]&&!f.includes(S.matchUpId));for(let S of h??[]){let{orderOfFinish:T}=S||{};if(T){if(!lt(T))return v({context:{orderOfFinish:T,matchUp:S},result:{error:G},stack:r});g.push(T)}}if(cI(g).length!==g.length||Math.max(...g)>g.length)return v({info:"Values not unique or greater than expected number of values",result:{error:G},stack:r});if(u.length){let S=eu({matchUpFilters:{matchUpIds:s},structureId:u[0],drawDefinition:t,matchUpsMap:o});if(S.error)return v({result:S,stack:r});S.completedMatchUps?.forEach(T=>T.orderOfFinish=l[T.matchUpId])}return{...R}}function eD(t){return Av(t)}function rD({tournamentRecord:t,drawDefinition:e,matchUpId:r,lineUps:n,event:o}){if(!t)return{error:j};if(!e)return{error:fr};if(typeof r!="string")return{error:ze};if(!Array.isArray(n))return{error:G,lineUps:n};let i="applyLineUps",s=t.participants||[],a=xt({tournamentParticipants:s,inContext:!0,drawDefinition:e,matchUpId:r});if(a.error)return a;if(!a.matchUp)return{error:De};let{matchUp:c,structure:u}=a,{drawPositions:p,matchUpType:m}=c;if(m!==Bt)return{error:ze};if(!p?.length)return{error:Fa};let d=Ve({matchUp:c,drawDefinition:e,structure:u,event:o})?.tieFormat,l={};for(let g of n){if(!Array.isArray(g))return{error:G,lineUp:g};let I={},h=[];for(let y of g){if(typeof y!="object")return{error:G,lineUpAssignment:y};let{participantId:E,collectionAssignments:U=[]}=y;if(!Array.isArray(U))return{error:G,collectionAssignments:U};let M=s.find(C=>C.participantId===E);if(!M)return{error:Jt};if(M.participantType!==It)return{error:tn};let N=c.sides?.find(C=>C.participant?.individualParticipantIds?.includes(E))?.sideNumber;N&&h.push(N);for(let C of U){if(typeof C!="object")return{error:G,collectionAssignment:C};let{collectionId:D,collectionPosition:O}=C,b=d?.collectionDefinitions?.find(F=>F.collectionId===D);if(!b)return{error:G,collectionId:D};let _=`${D}-${O}`;I[_]||(I[_]=[]);let L=I[_].length;if(b.matchUpType===ee&&L||b.matchUpType===jt&&L>1)return{info:"Excessive collectionPosition assignments",error:G};I[_].push(E)}}let S=Object.values(I);for(let y of S)if(y.length===2){let{participant:E}=zr({tournamentParticipants:s,participantIds:y});if(!E){let M=dn({participant:{participantType:pt,participantRole:Fe,individualParticipantIds:y},pairOverride:!0,tournamentRecord:t});if(M.error)return M}}let T=pr(h),A=(T[1]||0)>(T[2]||0)&&1||(T[2]||0)>(T[1]||0)&&2||void 0,P=Object.keys(l).map(y=>parseInt(y));A&&!P.includes(A)&&(l[A]=g)}if(!Object.keys(l).length)return{error:Al};if(a=xt({drawDefinition:e,matchUpId:r}),a.error)return a;if(!a.matchUp)return{error:De};let{matchUp:f}=a;f.sides||(f.sides=[]);for(let g of[1,2]){let I=f.sides.find(S=>S.sideNumber===g),h=l[g];if(h)I?I.lineUp=h:f.sides.push({lineUp:h,sideNumber:g});else continue}return ht({tournamentId:t?.tournamentId,context:i,drawDefinition:e,matchUp:f}),{...R}}function Ng(t){let e="resetTieFormat",{drawDefinition:r,event:n,uuids:o}=t,i=vt(t,[{[Fn]:!0,[ji]:!0}],e);if(i.error)return i;let s=Ma(t,[{[ra]:co}]);if(s[Ns])return s;let a=t.tournamentRecord?.tournamentId,{matchUp:c,structure:u}=s?.matchUp??{};if(!c?.tieMatchUps)return v({result:{error:ze},info:"Must be a TEAM matchUp",stack:e});if(!c.tieFormat)return{...R};let p=Ve({structure:u,drawDefinition:r,event:n})?.tieFormat;if(!p)return v({result:{error:je},info:"No inherited tieFormat",stack:e});let m=[],d=[],l=[],f=[];for(let g of p.collectionDefinitions){let{matchUpCount:I,collectionId:h}=g;d.push(h);let S=(c.tieMatchUps||[]).filter(T=>T.collectionId===h);if(S.length>I)S.sort((T,A)=>(T.matchUpStatus===Kt?1:0)-(A.matchUpStatus===Kt?1:0)),l.push(...S.slice(0,I)),m.push(...S.slice(3).map(le));else if(l.push(...S),S.length<I){let T=I-S.length,A=uu({collectionDefinition:g,matchUpsLimit:T,matchUp:c,uuids:o});f.push(...A)}}for(let g of c?.tieMatchUps||[])g.collectionId&&!d.includes(g.collectionId)&&m.push(g.matchUpId);return f.length&&(l.push(...f),lo({eventId:n?.eventId,matchUps:f,drawDefinition:r,tournamentId:a})),m.length&&Rn({matchUpIds:m,eventId:n?.eventId,drawDefinition:r,tournamentId:a}),c&&(c.tieMatchUps=l,c.tieFormatId=void 0,c.tieFormat=void 0,ht({structureId:u?.structureId,eventId:n?.eventId,context:e,drawDefinition:r,tournamentId:a,matchUp:c})),{...R,newMatchUps:f,deletedMatchUpIds:m}}function nD(t){let{tournamentRecord:e,drawDefinition:r,matchUpId:n,event:o}=t,i="resetScorecard";if(!r)return v({result:{error:z},stack:i});if(!n)return v({result:{error:Ne},stack:i});if(!er(n))return v({result:{error:G,matchUpId:n},stack:i});let s=be({drawDefinition:r}),{matchUps:a}=re({nextMatchUps:!0,inContext:!0,drawDefinition:r,matchUpsMap:s}),c=s.drawMatchUps.find(I=>I.matchUpId===n),u=a?.find(I=>I.matchUpId===n);if(!c||!a)return{error:De};if(c.matchUpType!==Kr)return{error:ze};let p=Je({inContextDrawMatchUps:a,drawDefinition:r,matchUpId:n}),m=u?.structureId,{structure:d}=st({drawDefinition:r,structureId:m});if(Object.assign(t,{inContextDrawMatchUps:a,inContextMatchUp:u,matchUpsMap:s,targetData:p,structure:d,matchUp:c}),fi(t))return{error:pl};if(c.tieMatchUps?.length)for(let I of c.tieMatchUps){let h=Nu({matchUpId:I.matchUpId,matchUpTieId:n,winningSide:void 0,removeScore:!0,tournamentRecord:e,drawDefinition:r,event:o});if(h.error)return v({result:h,stack:i})}let f=yt({tournamentRecord:e,drawDefinition:r,event:o})?.appliedPolicies,g=En({event:t.event,removeScore:!0,tournamentRecord:e,appliedPolicies:f,drawDefinition:r,matchUpsMap:s,matchUpId:n});if(g.error)return v({result:g,stack:i});if(t.tiebreakReset&&!g.tieFormatRemoved){let I=Ve({drawDefinition:r,structure:d,event:o})?.tieFormat;if(c.tieFormat&&I){let{matchUpCountDifference:h,descendantDifferences:S,ancestorDifferences:T,valueDifference:A}=Co({descendant:c.tieFormat,ancestor:I});if(S.collectionIds.length===1&&!T.collectionIds.length&&!T.groupsCount&&h===1&&A===1){let P=Ng({tournamentRecord:e,drawDefinition:r,matchUpId:n,event:o});if(P.error)return P}}}return{...R}}var xg={};ne(xg,{anonymizeTournamentRecord:()=>lD,generate:()=>dD,generateEventWithDraw:()=>Yp,generateOutcome:()=>_g,generateOutcomeFromScoreString:()=>Dg,generateParticipants:()=>Pc,generateTournamentRecord:()=>mD,modifyTournamentRecord:()=>fD,mutate:()=>gD});var dD={};ne(dD,{generateEventWithDraw:()=>Yp,generateOutcome:()=>_g,generateOutcomeFromScoreString:()=>Dg,generateParticipants:()=>Pc,generateTournamentRecord:()=>mD});function Dg(t){let{matchUpFormat:e,matchUpStatus:r,winningSide:n,scoreString:o}=t;if(!o)return{outcome:{...pu,winningSide:n,matchUpStatus:r}};if(n&&![1,2,void 0].includes(n))return{error:G,winningSide:n};let i=o&&dg({scoreString:o}),s={},a=Ko({sets:i,matchUpFormat:e}),c=Ko({sets:i,reversed:!0,matchUpFormat:e});return n===2?(s.scoreStringSide1=c,s.scoreStringSide2=a):(s.scoreStringSide1=a,s.scoreStringSide2=c),s.sets=dg({scoreString:s.scoreStringSide1}),rt({outcome:{matchUpStatus:r,winningSide:n,score:s}})}function Gd({matchUpScheduleTimes:t,matchUpDependencies:e,allDateMatchUpIds:r,matchUp:n}){let i=(e?.[n.matchUpId]?.matchUpIds||[]).filter(a=>r.includes(a)).filter(a=>!t[a]);return{dependenciesScheduled:!i?.length,remainingDependencies:i}}function zs({matchUpPotentialParticipantIds:t,matchUpNotBeforeTimes:e,timeAfterRecovery:r,matchUp:n}){let{individualParticipantIds:o}=$c(n);r=r??n.schedule?.timeAfterRecovery;let i=u=>{t[u]||(t[u]=[]),t[u]=mt(t[u].concat(...o))},s=u=>{r&&(!e[u]||r>e[u])&&(e[u]=r)},a=n.winnerTo?.matchUpId||n.winnerMatchUpId;a&&(r&&s(a),i(a));let c=n.loserTo?.matchUpId||n.loserMatchUpId;c&&(r&&s(c),i(c)),n.sidesTo?.length&&n.sidesTo.forEach(({matchUpId:u})=>{u&&(r&&s(u),i(u))})}function ba({individualParticipantProfiles:t,participantId:e}){t[e]||(t[e]={typeChangeTimeAfterRecovery:void 0,timeAfterRecovery:void 0,priorMatchUpType:void 0,potentialRecovery:{},potentialCounted:{},potentialBookings:{},bookings:[],counters:{}})}function yv({individualParticipantProfiles:t,recoveryValue:e,participantId:r,scheduleTime:n,drawId:o}){t[r].potentialRecovery[o]||(t[r].potentialRecovery[o]=[]),t[r].potentialRecovery[o].push(e),t[r].potentialBookings[o]||(t[r].potentialBookings[o]=[]),t[r].potentialBookings[o].push({timeAfterRecovery:e,scheduleTime:n})}function yc({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,typeChangeRecoveryMinutes:r,averageMatchUpMinutes:n=0,matchUpNotBeforeTimes:o,matchUpDependencies:i,recoveryMinutes:s=0,scheduleTime:a,matchUp:c}){let u=qt(c?.schedule?.endTime),p=u?Nr(u,ct(s)):Nr(a,ct(n)+ct(s)),m=r&&(u?Nr(qt(u),r):Nr(a,ct(n)+ct(r))),d=i?.[c.matchUpId]?.participantIds||[],l=(c.roundPosition&&t[c.matchUpId]||[]).flat();d.forEach(f=>{ba({individualParticipantProfiles:e,participantId:f});let I=e[f].priorMatchUpType!==c.matchUpType&&m||p;l.includes(f)?yv({individualParticipantProfiles:e,drawId:c.drawId,recoveryValue:I,participantId:f,scheduleTime:a}):(e[f].timeAfterRecovery=I,e[f].bookings.push({scheduleTime:a,timeAfterRecovery:I}))}),zs({matchUpPotentialParticipantIds:t,matchUpNotBeforeTimes:o,timeAfterRecovery:p,matchUp:c})}function JT({matchUpScheduleTimes:t,matchUpDependencies:e,scheduleTime:r,matchUpId:n,details:o}){let i,s=o.minutesMap?.[n]?.recoveryMinutes,c=(o.minutesMap?.[n]?.averageMinutes||0)+(s||0),u=Nr(r,c),p=e?.[n]?.dependentMatchUpIds||[];if(p.length){let m=p.reduce((d,l)=>{let f=t[l];if(!f)return d;let g={scheduleTime:f,matchUpId:l};return f&&!d.matchUpId||Gt(f)<Gt(d.scheduleTime)?g:d},{});m.scheduleTime&&Gt(u)>Gt(m.scheduleTime)&&(i=m)}return{scheduledDependent:i}}function Ev(t){let{sides:e,matchUpType:r}=t||{};return(e||[]).map(n=>r===jt&&(n?.participant?.individualParticipants||[])||n?.participant&&[n.participant]||[]).flat()}var Ec="DO_NOT_SCHEDULE",Uv={DO_NOT_SCHEDULE:Ec};function kd({averageMatchUpMinutes:t=90,requestConflicts:e={},potentials:r=!0,personRequests:n,scheduleTime:o,scheduleDate:i,matchUp:s}){let a=Ev(s).map(({person:l})=>l?.personId);if(r){let l=(s?.potentialParticipants||[]).flat().map(({person:f})=>f?.personId);a.push(...l)}let c=a.map(l=>n[l]?.map(f=>({...f,personId:l}))).filter(Boolean).flat().filter(l=>l.requestType===Ec&&Dn(i,l.date)),u=[],p=s?.matchUpId,m=xe(qt(o),At(i)),d=qt(vl(m,t).toISOString());for(let l of c){let{requestId:f,startTime:g,endTime:I}=l;(o>g&&o<I||d>g&&d<I)&&(u.push({matchUpId:p,request:l,scheduleTime:o}),e[f]?(e[f].scheduleTimes.includes(o)||e[f].scheduleTimes.push(o),e[f].matchUpIds.includes(p)||e[f].matchUpIds.push(p)):e[f]={request:l,scheduleTimes:[o],matchUpIds:[p]})}return{conflicts:u}}function Pv({scheduledRoundsDetails:t,greatestAverageMinutes:e,garmanSinglePass:r}){let n=[],o=[],i,s,a,c;for(let u of t.filter(Boolean))c||(c=u.hash),(u.hash===c||r)&&(o=o.concat(u.matchUpIds)),u.hash!==c&&!r&&(c=u.hash,n.push({averageMinutes:a,recoveryMinutes:s,roundPeriodLength:i,matchUpIds:o}),o=u.matchUpIds),a=r?e:u.averageMinutes,s=u.recoveryMinutes,i=u.roundPeriodLength;return o.length&&n.push({matchUpIds:o,roundPeriodLength:i,recoveryMinutes:s,averageMinutes:a}),{groupedRounds:n}}function Mg({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,matchUp:r,value:n}){let{matchUpType:o}=r,{individualParticipantIds:i}=$c(r),a=(t[r.matchUpId]||[]).filter(u=>!ve(u,i)).flat();[...i,...a].forEach(u=>{if(ba({individualParticipantProfiles:e,participantId:u}),!e[u].potentialCounted[r.drawId]){let p=e[u].counters;p[o]?p[o]+=n:n>0&&(p[o]=n),p[Hn]?p[Hn]+=n:n>0&&(p[Hn]=n),a.includes(u)&&(e[u].potentialCounted[r.drawId]=!0)}})}function Nv({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,dateScheduledMatchUpIds:r,greatestAverageMinutes:n,dateScheduledMatchUps:o,matchUpNotBeforeTimes:i,matchUpScheduleTimes:s,matchUpDependencies:a,clearScheduleDates:c,scheduleDate:u,minutesMap:p,matchUps:m}){let d=[];r||(o=m?.filter(g=>{let I=g.schedule||{},h=g.matchUpStatus===Ut;return h&&d.push({tournamentId:g.tournamentId,matchUpId:g.matchUpId}),!h&&Da({schedule:I})&&(!u||g.schedule.scheduledDate===u)}),r=o.map(le));let l=Array.isArray(c)?c.includes(u):c,f=l?[]:m.filter(({matchUpId:g})=>r.includes(g));for(let g of f){Mg({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,value:1,matchUp:g});let I=g.schedule?.scheduledTime;if(I){s[g.matchUpId]=I;let h=p?.[g.matchUpId]?.recoveryMinutes;yc({individualParticipantProfiles:e,matchUpPotentialParticipantIds:t,matchUpNotBeforeTimes:i,matchUpDependencies:a,averageMatchUpMinutes:n,recoveryMinutes:h,scheduleTime:I,matchUp:g})}}return{dateScheduledMatchUpIds:r,byeScheduledMatchUpDetails:d,dateScheduledMatchUps:o,clearDate:l}}function Dv({matchUpPotentialParticipantIds:t,scheduleCompletedMatchUps:e,dateScheduledMatchUpIds:r,matchUpNotBeforeTimes:n,matchUpScheduleTimes:o,orderedMatchUpIds:i,clearDate:s,matchUps:a}){let c=Object.keys(o),u=i.map(m=>a.find(d=>d.matchUpId===m)).filter(Boolean).filter(m=>{let d=!s&&(r.includes(m.matchUpId)||c.includes(m.matchUpId)),l=[Ut,bt,me,kr,mr,Ot,fe,Me].includes(m?.matchUpStatus);return e||!d&&!m.winningSide&&!l}),{matchUpMap:p}=u.reduce((m,d)=>{let{drawId:l,tournamentId:f}=d;return m.matchUpMap[f]||(m.matchUpMap[f]={}),m.matchUpMap[f][l]?m.matchUpMap[f][l].push(d):m.matchUpMap[f][l]=[d],zs({matchUpPotentialParticipantIds:t,matchUpNotBeforeTimes:n,matchUp:d}),m},{matchUpMap:{}});return{matchUpsToSchedule:u,matchUpMap:p}}function Hp({defaultRecoveryMinutes:t=0,averageMatchUpMinutes:e=90,dateScheduledMatchUps:r,tournamentRecords:n,venueIds:o=[],periodLength:i,scheduleDate:s,matchUps:a}){if(typeof n!="object")return{error:wt};if(!Ar(a)&&!Array.isArray(r))return{error:wn};i=i??Pu({recoveryMinutes:t,averageMatchUpMinutes:e});let c=Object.assign({},...Object.values(n).map(d=>(d.events??[]).map(l=>{let{scheduleTiming:f}=la({tournamentRecord:d,event:l});return{[l.eventId]:{event:l,scheduleTiming:f}}})).flat()),u={averageTimes:[{minutes:{default:e}}],recoveryTimes:[{minutes:{default:t}}]};r||(r=a?.filter(d=>{let l=d.schedule;return Da({schedule:l})&&(!s||d.schedule.scheduledDate===s)}));let p=r?.filter(d=>(!o.length||o.includes(d.schedule.venueId))&&d.matchUpStatus!==Ut);return{bookings:p?.map(({eventId:d,schedule:l,matchUpFormat:f})=>{let{event:g,scheduleTiming:I}=c[d],h=g?.eventType,S={...I,defaultTiming:u,matchUpFormat:f},{averageMinutes:T,recoveryMinutes:A}=ip({timingDetails:S,eventType:h}),{courtId:P,venueId:y}=l,E=qt(l.scheduledTime),U=Nr(E,T);return{recoveryMinutes:A,averageMinutes:T,periodLength:i,startTime:E,courtId:P,endTime:U,venueId:y}}).filter(Boolean),relevantMatchUps:p,dateScheduledMatchUps:r}}function Mv({calculateStartTimeFromCourts:t=!0,remainingScheduleTimes:e,defaultRecoveryMinutes:r,averageMatchUpMinutes:n,clearScheduleDates:o,tournamentRecords:i,tournamentRecord:s,periodLength:a,scheduleDate:c,startTime:u,venueIds:p,matchUps:m,endTime:d}){if(s&&!i&&(i={[s.tournamentId]:s}),typeof i!="object"||!Object.keys(i).length)return{error:wt};a=a??Pu({recoveryMinutes:r,averageMatchUpMinutes:n});let{courts:l,venues:f}=oo({dates:[c],ignoreDisabled:!0,tournamentRecords:i}),g=l?.filter(y=>!p||p.includes(y.venueId))??[];u=u??Tc({courts:g,scheduleDate:c,startTime:!0}),d=d??Tc({courts:g,scheduleDate:c,endTime:!0});let{bookings:I,dateScheduledMatchUps:h}=Hp({defaultRecoveryMinutes:r,averageMatchUpMinutes:n,tournamentRecords:i,scheduleDate:c,periodLength:a,venueIds:p,matchUps:m}),S={calculateStartTimeFromCourts:t,remainingScheduleTimes:e,averageMatchUpMinutes:n,clearScheduleDates:o,date:c,periodLength:a,startTime:u,bookings:I,endTime:d,courts:g},{scheduleTimes:T}=_d(S),A=p?.length===1&&p[0]||f?.length===1&&f[0].venueId||void 0;return{dateScheduledMatchUpIds:h?.map(Dr("matchUpId")),dateScheduledMatchUps:h,scheduleTimes:T,venueId:A}}function ZT({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,scheduleCompletedMatchUps:r,containedStructureIds:n,matchUpNotBeforeTimes:o,matchUpScheduleTimes:i,matchUpDependencies:s,clearScheduleDates:a,tournamentRecords:c,periodLength:u,scheduleDate:p,useGarman:m,matchUps:d,courts:l,venues:f}){let g={},I=[],h=[],S=[];for(let T of f){let{rounds:A=[],venueId:P}=T,{scheduledRoundsDetails:y,greatestAverageMinutes:E,orderedMatchUpIds:U,minutesMap:M}=Tu({scheduleCompletedMatchUps:r,containedStructureIds:n,tournamentRecords:c,periodLength:u,matchUps:d,rounds:A});S.push(...U??[]);let{groupedRounds:N}=Pv({scheduledRoundsDetails:y,greatestAverageMinutes:E,garmanSinglePass:!0}),C,D,O=[];m&&({scheduleTimes:O,dateScheduledMatchUpIds:C,dateScheduledMatchUps:D}=Mv({averageMatchUpMinutes:N[0]?.averageMinutes,scheduleDate:At(p),venueIds:[T.venueId],clearScheduleDates:a,tournamentRecords:c,periodLength:u,matchUps:d}));let b=Nv({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,dateScheduledMatchUpIds:C,greatestAverageMinutes:E,matchUpNotBeforeTimes:o,matchUpScheduleTimes:i,matchUpDependencies:s,clearScheduleDates:a,scheduleDate:p,minutesMap:M,matchUps:d});({dateScheduledMatchUpIds:C,dateScheduledMatchUps:D}=b);let{byeScheduledMatchUpDetails:_,clearDate:L}=b;_?.length&&h.push(..._);let{matchUpsToSchedule:F,matchUpMap:w}=Dv({matchUpPotentialParticipantIds:t,scheduleCompletedMatchUps:r,dateScheduledMatchUpIds:C,matchUpNotBeforeTimes:o,matchUpScheduleTimes:i,orderedMatchUpIds:U,clearDate:L,matchUps:d}),x=l.filter(H=>H.venueId===P);g[P]={previousRemainingScheduleTimes:[],courtsCount:x.length,greatestAverageMinutes:E,scheduledRoundsDetails:y,dateScheduledMatchUps:D,matchUpsToSchedule:F,scheduleTimes:O,groupedRounds:N,venueCourts:x,minutesMap:M,matchUpMap:w},a||I.push(...C)}return{allDateScheduledByeMatchUpDetails:h,allDateScheduledMatchUpIds:I,venueScheduledRoundDetails:g,allDateMatchUpIds:S}}function Cv(t,e){let r=Gt(t.scheduleTime),n=Gt(t.timeAfterRecovery),o=Gt(e.scheduleTime),i=Gt(e.timeAfterRecovery),s=r===o||n===i,a=r>o&&r<i,c=o>r&&o<n,u=n>o&&n<i,p=i>r&&i<n;return rt({hasOverlap:s||a||u||c||p,startAisContained:a,endAisContained:u,startBisContained:c,endBisContained:p},!0)}function Vd({individualParticipantProfiles:t,matchUpNotBeforeTimes:e,matchUpDependencies:r,scheduleTime:n,matchUp:o,details:i}){let s=(r?.[o.matchUpId]?.participantIds||[]).flat(),a=i?.minutesMap?.[o.matchUpId]?.averageMinutes||0,c=i?.minutesMap?.[o.matchUpId]?.recoveryMinutes||0,u=s.every(f=>{ba({individualParticipantProfiles:t,participantId:f});let g=t[f];if(!g.timeAfterRecovery)return!0;let I=qt(o?.schedule?.endTime),h=I?Nr(I,ct(c)):Nr(n,ct(a)+ct(c));return!!![...Object.keys(g.potentialBookings).filter(P=>P!==o.drawId).map(P=>g.potentialBookings[P]).flat(),...g.bookings].find(P=>Cv({scheduleTime:n,timeAfterRecovery:h},P).hasOverlap)}),p=e[o.matchUpId],d=(p?ea(xe(p),xe(n),!1):0)>=0;return{enoughTime:u&&d}}function Bd({individualParticipantProfiles:t,matchUpPotentialParticipantIds:e,matchUpDailyLimits:r={},matchUp:n}){let{matchUpId:o,matchUpType:i}=n,{enteredIndividualParticipantIds:s}=$c(n),a=(n.roundPosition&&e[o]||[]).flat(),c=mt(s.concat(...a));return c.forEach(p=>{ba({individualParticipantProfiles:t,participantId:p})}),{participantIdsAtLimit:c.filter(p=>{let m=t[p];if(m)return[i,Hn].find(d=>{let l=m.counters?.[d]||0,f=r[d]||0;return l&&f&&l>=f})}),relevantParticipantIds:c}}function Mu({scheduleCompletedMatchUps:t=!1,scheduleByeMatchUps:e=!1,errorOnAnachronism:r=!1,checkChronology:n=!0,matchUpDependencies:o,removePriorValues:i,tournamentRecords:s,tournamentRecord:a,matchUpDetails:c,matchUpIds:u,schedule:p}){if(!a)return{error:j};if(!c&&(!u||!Array.isArray(u)))return{error:ta};if(!c&&(!p||typeof p!="object"))return{error:My};let m,d=[],l=0;if(n&&!o){let I=xr({tournamentRecords:s,tournamentRecord:a});o=I.matchUpDependencies,m=I.matchUps}m||(m=pe({tournamentRecord:a})?.matchUps??[]);let f=m.reduce((I,h)=>{let{matchUpId:S,drawId:T,matchUpStatus:A}=h;return(e||A!==Ut)&&(t||!ie.includes(A))&&(I[T]?I[T].push(S):I[T]=[S]),I},{}),g=c?.map(I=>I.matchUpId);for(let I of Object.keys(f)){let{drawDefinition:h}=To({tournamentRecord:a,drawId:I});if(!h)continue;let S=f[I].filter(A=>u?.includes(A)??g?.includes(A)),T=ar({inContext:!1,drawDefinition:h}).matchUps;for(let A of S){let P=c?.find(E=>E.matchUpId===A)?.schedule||p,y=Bp({schedule:P,matchUpDependencies:o,errorOnAnachronism:r,removePriorValues:i,inContextMatchUps:m,tournamentRecords:s,tournamentRecord:a,checkChronology:n,drawDefinition:h,drawMatchUps:T,matchUpId:A});if(y?.warnings?.length&&d.push(...y.warnings),y?.success&&(l+=1),y.error)return y}}return d.length?{...R,scheduled:l,warnings:d}:{...R,scheduled:l}}function Uc(t){let{scheduleCompletedMatchUps:e=!1,scheduleByeMatchUps:r=!1,errorOnAnachronism:n,matchUpContextIds:o,removePriorValues:i,tournamentRecords:s,checkChronology:a,matchUpDetails:c,schedule:u}=t;if(t.matchUpIds&&!o)return Mu(t);let p=vt(t,[{[ye]:!0},{[CC]:{matchUpContextIds:!1,matchUpDetails:!1},[Ni]:G,[na]:an}]);if(p.error)return p;if((!c||o)&&!u)return{error:et,info:"schedule is required"};let m=[],d=0,{matchUpDependencies:l}=xr({tournamentRecords:s});for(let f of Object.values(s)){let{tournamentId:g}=f,I=o?.filter(S=>S.tournamentId===g).map(le),h=c?.filter(S=>S?.tournamentId===g);if(I?.length||h?.length){let S=Mu({matchUpDetails:h,scheduleCompletedMatchUps:e,scheduleByeMatchUps:r,matchUpDependencies:l,errorOnAnachronism:n,removePriorValues:i,tournamentRecords:s,tournamentRecord:f,checkChronology:a,matchUpIds:I,schedule:u});if(S.warnings?.length&&m.push(...S.warnings),S.scheduled&&(d+=S.scheduled),S.error)return S}}return m.length?{...R,scheduled:d,warnings:m}:{...R,scheduled:d}}function tA({autoSchedulingAudit:t,tournamentRecords:e}){Tt({topic:pa,payload:t});let r=s=>s?Object.values(s).reduce((c,u)=>c+u.length||0,0):0,n=(t?.schedulingProfile||[]).reduce((s,a)=>s+a.venues.reduce((c,u)=>c+u.rounds.length,0),0),o={scheduledDatesCount:t.scheduledDates?.length,noTimeMatchUpIdsCount:r(t?.noTimeMatchUpIds),scheduledMatchUpIdsCount:r(t?.scheduledMatchUpIds),overLimitMatchUpIdsCount:r(t?.overLimitMatchUpIds),requestConflictsCount:r(t?.requestConflicts),profileRoundsCount:n},i={itemType:yN,itemValue:o};for(let s of Object.values(e))vi({tournamentRecord:s,timeItem:i})}function Rv({schedulingProfileModifications:t,checkPotentialRequestConflicts:e,scheduleCompletedMatchUps:r,schedulingProfileIssues:n,dateSchedulingProfiles:o,containedStructureIds:i,matchUpDependencies:s,matchUpDailyLimits:a,clearScheduleDates:c,tournamentRecords:u,schedulingProfile:p,personRequests:m,periodLength:d,matchUps:l,courts:f,dryRun:g}){let I={},h={},S={},T={},A={},P={},y={},E={},U={},M={};for(let D of o){let O=At(D?.scheduleDate),b=D?.venues||[],_={},L={},F=(k,K)=>{k.forEach(X=>{let $=L[X].counters;$[K]?$[K]+=1:$[K]=1,$[Hn]?$[Hn]+=1:$[Hn]=1})};S[O]={},T[O]={},I[O]={},h[O]={},y[O]=[],E[O]=[],U[O]=[],M[O]=[];let w={};l.forEach(k=>{k.schedule?.scheduledDate&&Dn(O,At(k.schedule.scheduledDate))&&zs({matchUpPotentialParticipantIds:_,matchUpNotBeforeTimes:w,matchUp:k})});let{allDateScheduledByeMatchUpDetails:x,venueScheduledRoundDetails:H,allDateMatchUpIds:V}=ZT({matchUpPotentialParticipantIds:_,individualParticipantProfiles:L,scheduleCompletedMatchUps:r,containedStructureIds:i,matchUpNotBeforeTimes:w,matchUpScheduleTimes:P,matchUpDependencies:s,clearScheduleDates:c,tournamentRecords:u,useGarman:!0,periodLength:d,scheduleDate:O,matchUps:l,courts:f,venues:b}),W=10,B=0,q,Y=10;for(;!q;){for(let{venueId:k}of b){let K=0,X=H[k];for(;X.courtsCount&&X.scheduleTimes?.length&&X.matchUpsToSchedule?.length&&K<=X.courtsCount;){let{scheduleTime:$,attempts:nt=0}=X.scheduleTimes.shift(),Q=X.matchUpsToSchedule.find(it=>{let{matchUpId:ot,matchUpType:dt}=it,{participantIdsAtLimit:zt,relevantParticipantIds:Et}=Bd({matchUpPotentialParticipantIds:_,individualParticipantProfiles:L,matchUpDailyLimits:a,matchUp:it});if(zt.length)return E[O].includes(ot)||E[O].push(ot),!1;let{scheduledDependent:ge}=JT({matchUpScheduleTimes:P,matchUpDependencies:s,scheduleTime:$,matchUpId:ot,details:X});if(ge)return!1;let{dependenciesScheduled:Ee,remainingDependencies:Ce}=Gd({matchUpScheduleTimes:P,matchUpDependencies:s,allDateMatchUpIds:V,matchUp:it});if(!Ee)return T[O][ot]||(T[O][ot]=[]),T[O][ot].push({scheduleTime:$,remainingDependencies:Ce}),!1;let{enoughTime:Xt}=Vd({individualParticipantProfiles:L,matchUpNotBeforeTimes:w,matchUpDependencies:s,scheduleTime:$,details:X,matchUp:it});if(!Xt)return S[O][ot]||(S[O][ot]=[]),S[O][ot].push({scheduleTime:$}),!1;let Ue=X.greatestAverageMinutes,{conflicts:Ht}=kd({potentials:e,averageMatchUpMinutes:Ue,requestConflicts:M,personRequests:m,scheduleTime:$,scheduleDate:O,matchUp:it});if(Ht?.length)return A[O]||(A[O]=[]),A[O].push(...Ht),!1;F(Et,dt);let Ie=X.minutesMap?.[ot]?.recoveryMinutes;return yc({matchUpPotentialParticipantIds:_,individualParticipantProfiles:L,matchUpNotBeforeTimes:w,averageMatchUpMinutes:Ue,matchUpDependencies:s,recoveryMinutes:Ie,scheduleTime:$,matchUp:it}),P[ot]=$,!0});X.matchUpsToSchedule=X.matchUpsToSchedule.filter(({matchUpId:it})=>it!==Q?.matchUpId),Q?K+=1:(h[O][k]||(h[O][k]=[]),h[O][k].push({scheduleTime:$,attempts:nt+1}))}X.matchUpsToSchedule?.length&&(h[O][k]=h[O][k]?.filter($=>{let nt=$.attempts<W;return nt&&X.scheduleTimes.push($),!nt})),(!X.scheduleTimes?.length||!X.matchUpsToSchedule?.length)&&(X.complete=!0)}B+=1,q=b.every(({venueId:k})=>H[k].complete)||B===Y}for(let{venueId:k}of b){let K=H[k].matchUpMap;Object.keys(K).forEach(X=>{let $=u[X];$&&Object.keys(K[X]).forEach(nt=>{let{drawDefinition:Q}=To({tournamentRecord:$,drawId:nt});Q&&K[X][nt].forEach(({matchUpId:ot})=>{let dt=P[ot];if(dt){let zt=dt.split(":").map(Ln).join(":"),Et=`${At(O)}T${zt}`;g?y[O].push(ot):(_o({drawDefinition:Q,scheduledTime:Et,matchUpId:ot}).success&&y[O].push(ot),k&&Ks({tournamentRecord:$,drawDefinition:Q,matchUpId:ot,venueId:k}))}})})}),U[O]=H[k].matchUpsToSchedule.map(le),I[O][k]=H[k].scheduleTimes.sort((X,$)=>Gt(X.scheduleTime)-Gt($.scheduleTime))}!g&&x?.length&&Uc({matchUpDetails:x,scheduleByeMatchUps:!0,removePriorValues:!0,tournamentRecords:u,schedule:{scheduledDate:"",scheduledTime:"",courtOrder:"",courtId:"",venueId:""}});for(let k of D.venues)for(let K of k.rounds){let $=(K.matchUps?.map(({matchUpId:Q})=>Q)||[]).filter(Q=>y[O].includes(Q));K.canScheduledMatchUpIds=$;let nt=Math.round($.length/K.matchUpsCount*1e4)/100;(nt===1/0||isNaN(nt))&&(nt=0),K.possibleToSchedulePct=nt,K.matchUpsCount===$.length&&(K.possibleToSchedule=!0)}}let N=o.map(({scheduleDate:D})=>D),C={timeStamp:Date.now(),overLimitMatchUpIds:E,scheduledMatchUpIds:y,schedulingProfile:p,noTimeMatchUpIds:U,requestConflicts:M,scheduledDates:N};return tA({tournamentRecords:u,autoSchedulingAudit:C}),{...R,schedulingProfileModifications:t,schedulingProfileIssues:n,scheduleTimesRemaining:I,dateSchedulingProfiles:o,skippedScheduleTimes:h,recoveryTimeDeferredMatchUpIds:S,dependencyDeferredMatchUpIds:T,matchUpScheduleTimes:P,overLimitMatchUpIds:E,scheduledMatchUpIds:y,noTimeMatchUpIds:U,requestConflicts:M,scheduledDates:N}}function sD({averageMinutes:t,startTime:e,endTime:r,court:n,date:o}){if(!Array.isArray(n.dateAvailability))return{error:et,stack:"getEarliestCourtTime"};let i=Tc({scheduleDate:o,courts:[n],startTime:!0}),s=Tc({scheduleDate:o,courts:[n],endTime:!0});e=e||i,r=r||s;let a=Ra({court:n,date:o}),{timeSlots:c}=ls({courtDate:a}),u=xe(e),p=xe(r);return{earliestCourtTime:c?.reduce((d,l)=>{let f=xe(l.startTime),g=xe(l.endTime);if(f>p||g<u)return d;let I=u>f?u:f;if(ea(I,g)>=t){let T=qt(I.toISOString());(!d||T<d)&&(d=T)}return d},void 0),courtStartTime:i,courtEndTime:s}}function bv({schedulingProfileModifications:t,checkPotentialRequestConflicts:e,scheduleCompletedMatchUps:r,schedulingProfileIssues:n,dateSchedulingProfiles:o,containedStructureIds:i,matchUpDependencies:s,matchUpDailyLimits:a,clearScheduleDates:c,tournamentRecords:u,periodLength:p=30,schedulingProfile:m,personRequests:d,matchUps:l=[],courts:f,dryRun:g}){let I={},h={},S={},T={},A={},P={},y={},E={},U={};for(let C of o??[]){let D=At(C?.scheduleDate),O=C?.venues||[],b={},_={},L=(Q,it)=>{Q.forEach(ot=>{let dt=_[ot].counters;dt[it]?dt[it]+=1:dt[it]=1,dt[Hn]?dt[Hn]+=1:dt[Hn]=1})};I[D]={},h[D]={},P[D]=[],y[D]=[],E[D]=[],U[D]=[];let F={};l?.forEach(Q=>{Q.schedule?.scheduledDate&&Dn(D,At(Q.schedule.scheduledDate))&&zs({matchUpPotentialParticipantIds:b,matchUpNotBeforeTimes:F,matchUp:Q})});let{allDateScheduledByeMatchUpDetails:w,allDateScheduledMatchUpIds:x,venueScheduledRoundDetails:H,allDateMatchUpIds:V}=ZT({matchUpPotentialParticipantIds:b,individualParticipantProfiles:_,scheduleCompletedMatchUps:r,containedStructureIds:i,matchUpNotBeforeTimes:F,matchUpScheduleTimes:A,matchUpDependencies:s,clearScheduleDates:c,tournamentRecords:u,periodLength:p,scheduleDate:D,matchUps:l,courts:f,venues:O}),W=l?.filter(({matchUpId:Q})=>x.includes(Q)),{bookings:B}=Hp({dateScheduledMatchUps:W,tournamentRecords:u,scheduleDate:D,periodLength:p}),{virtualCourts:q}=Fp({scheduleDate:D,periodLength:p,bookings:B,courts:f}),Y=q?.reduce((Q,it)=>{let{earliestCourtTime:ot,courtEndTime:dt}=sD({date:D,averageMinutes:0,court:it});return(!Q.startTime||xe(ot)<xe(Q.startTime))&&(Q.startTime=ot),(!Q.endTime||xe(dt)>xe(Q.endTime))&&(Q.endTime=dt),Q},{}),k=Y.startTime,K=({courtId:Q,booking:it})=>q?.find(ot=>ot.courtId===Q)?.dateAvailability[0].bookings.push(it),X=10,$=0,nt;for(;!nt;){for(let{venueId:Q}of O){let it=H[Q],ot=it.matchUpsToSchedule.length,dt=[],zt=[],Et,ge=0;for(;!Et;){for(let Ee of it.matchUpsToSchedule){if(zt.length===it.courtsCount||dt.length===it.courtsCount){Et=!0;break}let{matchUpId:Ce,matchUpType:Xt}=Ee,{participantIdsAtLimit:Ue,relevantParticipantIds:Ht}=Bd({matchUpPotentialParticipantIds:b,individualParticipantProfiles:_,matchUpDailyLimits:a,matchUp:Ee});if(Ue.length){y[D].includes(Ce)||y[D].push(Ce);continue}let{dependenciesScheduled:Ie,remainingDependencies:Nt}=Gd({matchUpScheduleTimes:A,matchUpDependencies:s,allDateMatchUpIds:V,matchUp:Ee});if(!Ie){h[D][Ce]||(h[D][Ce]=[]),h[D][Ce].push({remainingDependencies:Nt});continue}let Qt=[],Ft=q?.reduce((Yt,ue)=>{if(zt.includes(ue.courtId))return Yt;let{earliestCourtTime:Se}=sD({averageMinutes:it.greatestAverageMinutes,startTime:k,date:D,court:ue});if(Yt.scheduleTime&&Gt(Se)>=Gt(Yt.scheduleTime))return Yt;let{scheduledDependent:ur}=JT({matchUpScheduleTimes:A,matchUpDependencies:s,scheduleTime:Se,matchUpId:Ce,details:it});if(ur)return Yt;let{enoughTime:Oe}=Vd({individualParticipantProfiles:_,matchUpNotBeforeTimes:F,matchUpDependencies:s,scheduleTime:Se,details:it,matchUp:Ee});if(!Oe)return I[D][Ce]||(I[D][Ce]=[]),I[D][Ce].includes(Se)||I[D][Ce].push(Se),Yt;let Vt=it.minutesMap?.[Ce]?.averageMinutes||it.greatestAverageMinutes,{conflicts:_e}=kd({potentials:e,averageMatchUpMinutes:Vt,requestConflicts:U,personRequests:d,scheduleTime:Se,scheduleDate:D,matchUp:Ee});if(_e?.length)return Qt.push(..._e),!1;L(Ht,Xt);let tr=it.minutesMap?.[Ce]?.recoveryMinutes;return yc({matchUpPotentialParticipantIds:b,individualParticipantProfiles:_,matchUpNotBeforeTimes:F,averageMatchUpMinutes:Vt,matchUpDependencies:s,recoveryMinutes:tr,scheduleTime:Se,matchUp:Ee}),(!Yt.scheduleTime||Gt(Se)<Gt(Yt.scheduleTime))&&(Yt.averageMatchUpMinutes=Vt,Yt.recoveryMinutes=tr,Yt.scheduleTime=Se,Yt.courtName=ue.courtName,Yt.courtId=ue.courtId),Yt},{});if(Ft.scheduleTime){let{averageMatchUpMinutes:Yt,recoveryMinutes:ue,scheduleTime:Se,courtId:ur}=Ft;A[Ce]=Se,T[Ce]=ur,dt.push(Ce),zt.push(ur);let Oe=Se,Vt=Nr(Oe,Yt);K({courtId:ur,booking:{averageMatchUpMinutes:Yt,recoveryMinutes:ue,periodLength:p,matchUpId:Ce,startTime:Oe,courtId:ur,endTime:Vt,venueId:Q}}),it.matchUpsToSchedule=it.matchUpsToSchedule.filter(tr=>tr.matchUpId!==Ce)}else Qt?.length&&(S[D]||(S[D]=[]),S[D].push(...Qt))}(zt.length===it.courtsCount||dt.length===it.courtsCount||!it.matchUpsToSchedule.length)&&(Et=!0),it.matchUpsToSchedule.length&&dt<it.courtsCount&&(xe(k)<xe(Y.endTime)?k=Nr(k,p):(Et=!0,it.complete=!0)),ge+=1,!Et&&ge>=ot&&(Et=!0)}it.matchUpsToSchedule?.length||(it.complete=!0)}$+=1,nt=O.every(({venueId:Q})=>H[Q].complete)||$===X}for(let{venueId:Q}of O){let it=H[Q].matchUpMap;Object.keys(it).forEach(ot=>{let dt=u[ot];dt&&Object.keys(it[ot]).forEach(zt=>{let{drawDefinition:Et}=To({tournamentRecord:dt,drawId:zt});Et&&it[ot][zt].forEach(({matchUpId:Ee})=>{let Ce=A[Ee],Xt=T[Ee];if(Ce){let Ue=Ce.split(":").map(Ln).join(":"),Ht=`${At(D)}T${Ue}`;g||(_o({drawDefinition:Et,scheduledTime:Ht,matchUpId:Ee}),Fi({courtDayDate:D,tournamentRecords:u,tournamentRecord:dt,drawDefinition:Et,matchUpId:Ee,courtId:Xt})),P[D].push(Ee)}})})}),E[D]=H[Q].matchUpsToSchedule.map(le)}!g&&w?.length&&Uc({matchUpDetails:w,scheduleByeMatchUps:!0,removePriorValues:!0,tournamentRecords:u,schedule:{scheduledDate:"",scheduledTime:"",courtOrder:"",courtId:"",venueId:""}});for(let Q of C.venues)for(let it of Q.rounds){let dt=(it.matchUps??[]).map(({matchUpId:Et})=>Et)?.filter(Et=>P[D].includes(Et));it.canScheduledMatchUpIds=dt;let zt=Math.round((dt?.length||0)/it.matchUpsCount*1e4)/100;(zt===1/0||isNaN(zt))&&(zt=void 0),it.possibleToSchedulePct=zt,it.matchUpsCount===dt?.length&&(it.possibleToSchedule=!0)}}let M=(o??[]).map(({scheduleDate:C})=>C),N={timeStamp:Date.now(),overLimitMatchUpIds:y,scheduledMatchUpIds:P,schedulingProfile:m,noTimeMatchUpIds:E,requestConflicts:U,scheduledDates:M};return tA({tournamentRecords:u,autoSchedulingAudit:N}),{...R,schedulingProfileModifications:t,schedulingProfileIssues:n,dateSchedulingProfiles:o,recoveryTimeDeferredMatchUpIds:I,dependencyDeferredMatchUpIds:h,matchUpScheduleTimes:A,overLimitMatchUpIds:y,scheduledMatchUpIds:P,noTimeMatchUpIds:E,requestConflicts:U,scheduledDates:M}}function Wp(t){let{scheduleAttributes:e=["scheduledDate","scheduledTime"],ignoreMatchUpStatuses:r=ie,scheduledDates:n,venueIds:o}=t,i=jr(t),s=Ct(i)?Object.values(i).map(({tournamentId:c})=>c).filter(Boolean):[];if(!s?.length)return{error:wt};let a=0;for(let c of s){let u=i[c],p=eV({ignoreMatchUpStatuses:r,scheduleAttributes:e,tournamentRecord:u,scheduledDates:n,venueIds:o});if(p.error)return p;a+=p.clearedScheduleCount??0}return{...R,clearedScheduleCount:a}}function eV({scheduleAttributes:t=["scheduledDate","scheduledTime"],ignoreMatchUpStatuses:e=ie,tournamentRecord:r,scheduledDates:n,venueIds:o=[]}){if(typeof r!="object")return{error:j};if(!Array.isArray(e)||!Array.isArray(o))return{error:G};o.length&&t.push("venueId");let s=(pe({matchUpFilters:{scheduledDates:n},tournamentRecord:r}).matchUps??[]).filter(u=>u.matchUpStatus&&!e.includes(u.matchUpStatus)&&Da({schedule:u.schedule,scheduleAttributes:t})&&(!o?.length||o.includes(u.schedule.venueId))).map(le),a=pe({tournamentRecord:r,inContext:!1}).matchUps??[],c=0;for(let u of a)s.includes(u.matchUpId)&&(u.timeItems=(u.timeItems??[]).filter(p=>p?.itemType&&![ho,si,bs,Os,_s].includes(p?.itemType)),c+=1);return{...R,clearedScheduleCount:c}}function jp(t){let{checkPotentialRequestConflicts:e=!0,scheduleCompletedMatchUps:r,clearScheduleDates:n,scheduleDates:o=[],tournamentRecords:i,periodLength:s,useGarman:a,dryRun:c,pro:u}=t,p=vt(t,[{[ye]:!0},{[Pi]:M=>!M||Array.isArray(M)&&M.every(Pr),[yI]:!1,[na]:an}]);if(p.error)return p;let m=Ro({tournamentRecords:i});if(m.error)return m;if(!m.schedulingProfile.length)return{...R};let{modifications:d,issues:l=[],schedulingProfile:f=[]}=m,g=Object.assign({},...Object.values(i).map(M=>zi({tournamentRecord:M}).containedStructures)),I=o.map(M=>{if(Pr(M))return At(M)}).filter(Boolean),h=f.map(M=>M.scheduleDate).map(M=>Pr(M)&&At(M)).filter(M=>M&&(!o.length||I.includes(M)));if(!h.length)return{error:oy};if(n&&!c){let M=Array.isArray(n)?n:[];Wp({tournamentRecords:i,scheduledDates:M})}let S=oo({ignoreDisabled:!1,tournamentRecords:i}).courts,{matchUps:T}=nn({matchUpFilters:{matchUpTypes:[ee,jt]},afterRecoveryTimes:!0,nextMatchUps:!0,tournamentRecords:i}),{matchUpDependencies:A}=xr({includeParticipantDependencies:!0,tournamentRecords:i,matchUps:T}),{matchUpDailyLimits:P}=Sd({tournamentRecords:i}),{personRequests:y}=gi({requestType:Ec,tournamentRecords:i}),E=f.filter(M=>{let N=At(M?.scheduleDate);return h.includes(N)}).sort((M,N)=>new Date(M.scheduleDate).getTime()-new Date(N.scheduleDate).getTime()),U={schedulingProfileModifications:d,checkPotentialRequestConflicts:e,scheduleCompletedMatchUps:r,schedulingProfileIssues:l,dateSchedulingProfiles:E,containedStructureIds:g,matchUpDependencies:A,matchUpDailyLimits:P,clearScheduleDates:n,tournamentRecords:i,schedulingProfile:f,personRequests:y,periodLength:s,useGarman:a,matchUps:T,dryRun:c,courts:S};return u?bv(U):Rv(U)}function eA(t){let e=t||{};return e.tournamentId||(e.tournamentId=Mt()),e.startDate&&!Ya(e.startDate)&&!nm.test(e.startDate)?{error:ir}:e.endDate&&!Ya(e.endDate)&&!nm.test(e.endDate)?{error:ir}:(e.extensions&&(e.extensions=e.extensions.filter(hn)),{...e})}function Cg({addParticipants:t=!0,participantAttribute:e,tournamentRecord:r,personAttribute:n,teamNames:o,accessor:i,uuids:s}){if(!r)return{error:j};let a={},c=(r.participants??[]).filter(({participantType:f,participantRole:g})=>f===It&&g===Fe),u=0;for(let f of c){let I=i&&Wi({element:f,accessor:i})?.value||n&&f.person?.[n]||e&&f[e];if(I){if(!Object.keys(a).includes(I)){a[I]={participantName:o?.[u]??I,participantId:s?.pop()??Mt(),individualParticipantIds:[],participantRole:Fe,participantType:Lt};let h={value:n??e,name:RI};gt({element:a[I],extension:h}),u+=1}a[I].individualParticipantIds.push(f.participantId)}}let p=Object.keys(a),m=(r.participants??[]).map(f=>{if(f.participantType!==Lt||f.participantRole!==Fe)return;let{extension:g}=ut({name:RI,element:f}),I=g?.value;if(p.includes(I))return f.participantId}).filter(Boolean),d=0,l=[];return Object.keys(a).forEach(f=>{let g=a[f],{participantId:I}=g;m.includes(I)||(r.participants||(r.participants=[]),t&&r.participants.push(g),l.push(g),d++)}),t&&d?(Tt({payload:{tournamentId:r.tournamentId,participants:l},topic:Go}),{...R,participantsAdded:d}):l.length?{...R,newParticipants:l}:{error:$M}}var Ov=[{AA:"Annexia"},{BA:"Bacteria"},{BO:"Borduria"},{BM:"Bensalem"},{BS:"Basenji"},{BI:"Balnibarbi"},{BV:"Bartovia"},{BZ:"Berzerkistan"},{CA:"Caldonia"},{CC:"Concordia"},{CH:"Chula"},{DA:"Deltora"},{DW:"Discworld"},{EA:"Eastasia"},{EP:"Ecotopia"},{ER:"Erewhon"},{FA:"Freedonia"},{FN:"Florin"},{FG:"Fogg"},{FK:"Fourecks"},{GA:"Genovia"},{GL:"Gilead"},{GD:"Gilead"},{GL:"Gondal"},{GO:"Gondor"},{GR:"Gruzinia"},{GT:"Goritania"},{GU:"Guilder"},{HA:"Heldscalla"},{HO:"Hidalgo"},{IL:"Illyria"},{KA:"Kinakuta"},{KG:"Kangan"},{KN:"Kreplachistan"},{KS:"Kallipolis"},{LH:"Lugash"},{LI:"Listenbourg"},{LT:"Lilliput"},{LU:"Luggnagg"},{LV:"Lichtenslava"},{MR:"Moher"},{NA:"Narnia"},{NV:"Novaria"},{OA:"Oceania"},{OS:"Orsinia"},{OV:"Octavia"},{PA:"Palombia"},{PG:"Penguina"},{QA:"Qasha"},{PM:"Panem"},{SA:"Solymbria"},{SD:"Syldavia"},{SG:"San Glucose"},{SL:"San Lorenzo"},{SR:"Sontar"},{SY:"Sylvania"},{TF:"Tralfamadore"},{TH:"Themyscira"},{UA:"Utopia"},{VA:"Vespugia"},{WA:"Wakanda"},{WX:"Wessex"},{ZA:"Zamunda"},{ZK:"Zubrowka"}];var _v=["Amber","Ansul","Atlantis","Braavos","Busytown","Castle Rock","Centralia","Coober Pedy","Chefchaouen","Chronopolis","Damanhur","Diaspar","Dictionopolis","Diomira","El Dorado","Elista","Ephesus","Gotham","Hadleyburg","Hallstatt","Hierusalem","Ilium","Inverness","Kowloon","Laputa","Longyearbyen","Lys","Matmata","Maycomb","Metropolis","Miyake-jima","Monowi","Nagoro","Navarre","New New York","Nimbin","Pemberley","Pseudopolis","Rivendell","Roswell","Shangri-La","Springfield","Supilinn","Thneedville","Trantor","Wobegon","Yonwood","Xanadu","Xylar","Zion"];function rA({count:t=1,participantsCount:e=32}={}){let r=sr(_v),n=r.slice(0,t);return{cities:Z(0,e).map(i=>i<Math.min(t,r.length)?n[i]:en(n))}}function nA({count:t=1,participantsCount:e=32}={}){let r=sr(Ov),n=r.slice(0,t).map(i=>Object.keys(i)).flat();return{states:Z(0,e).map(i=>i<Math.min(t,r.length)?n[i]:en(n))}}function oA({count:t=1,participantsCount:e=32}={}){let r=Z(0,t).map(()=>Z(0,5).map(()=>qn(0,9)).join(""));return{postalCodes:Z(0,e).map(o=>o<t?r[o]:en(r))}}function iA(t){let{cities:e,states:r,postalCodes:n,nationalityCode:o,participantIndex:i}=t;return{postalCode:n?.[i],state:r?.[i],city:e?.[i],countryCode:o}}var vv={lastNames:["Abbey","Ahern","Ampleforth","Ananiadis","Andelic","Assange","Atreides","Austen","Bach","Banks","Barrington","Batty","Bauers","Beals","Beer","Bennett","Berry","Bonaparte","Brockovich","Bukowski","Cassidy","Catton","Calvino","Carson","Chip","Constant","Crane","Crowne","Cummings","Curie","Dallas","Diamond","Deckard","Drazic","Dunbar","Earhart","Eisenstein","Eldritch","Elliot","Escher","Eyre","Faulkner","Fulcher","Fukuoka","Godel","Goldstein","Greer","Hedges","Herbert","Holmgren","Humperdinck","Huxley","Illich","Jeffers","Jensen","Jevons","Johnson","Johnstone","Jovovich","Kingsnorth","Langer","Fernwright","Fuller","Le Guin","Lem","Lovelace","Mander","Midgely","Mond","Montoya","Moore","Murry","Nagle","Nearing","Ogden","Ophuls","Parks","Paz","Peet","Perfect","Pendejo","Pevensie","Postman","Ripley","Rodda","Rumfoord","Runciter","Rugen","Sale","Schumacher","Shaftoe","Shelley","Shepard","Smith","Stratton","Stewart","Swift","Tillich","Turing","Tyrell","Twain","Yeats","Veblen","Yates","Vonnegut","Waterhouse","Watson","Wolin","Wirt","Waschuk","Wormwood"],firstFemale:["Ada","Amelia","Amelie","America","Anne","Antonia","Aravis","Astrid","Beatrice","Brienne","Buttercup","Caitlin","Cimorene","Cordelia","Desdemona","Ellen","Elizabeth","Emily","Emmie","Erin","Eva","Evelyn","Heather","Helen","Hermia","Hypatia","Imogen","Jane","Jasmine","Juliana","Juliet","Katniss","Leeloo","Lenina","Lilith","Linda","Lizzie","Louise","Lucy","Marie","Mary","Martha","Matilda","Milla","Miranda","Meg","Melba","Nicole","Ola","Portia","Pris","Rachael","Rachel","Rebecca","River","Rosa","Rosalind","Scout","Sharn","Susanne","Titania","Uhura","Ursula","Valentina","Viola","Virginia","Xena","Zoe"],firstMale:["Alan","Aldous","August","Axel","Barda","Barry","Bill","Bruce","Charles","Chris","Constantine","Darwin","David","Derrick","Edward","Emmanuel","Ernst","Estlin","Fezzik","Filby","Frank","Frito","George","Glen","Helmholtz","Inigo","Italo","Ivan","James","Jared","Jerry","Joe","Johann","Julian","John Michael","Jonathan","Korben","Kirkpatrick","Kurt","Lief","Malachi","Mark","Masanobu","Maurits","Michael","Mustapha","Neil","Nikola","Octavio","Palmer","Paul","Pierre","Robinson","Rick","Rincewind","Roy","Shannon","Sheldon","Stafford","Stanislaw","Stanley","Syme","Thorstein","Thomas","Tyrone","Vizzini","Walton","Walker","Warren","Wendell","Westley","William","Winston","Zoran"]};function sA(t){let{count:e=100,sex:r}=t||{};if(!e||r&&![Zt,ce].includes(r))return{personData:[],error:G};let n=Math.ceil(e*1.3),{lastNames:o,firstFemale:i,firstMale:s}=vv,a=Yo.map(({iso:I})=>I).filter(Boolean),c=Math.ceil(n/o.length),u=Math.ceil(n/i.length),p=Math.ceil(n/s.length),m=Z(0,c).flatMap(()=>{let I=J(o,!1,!0);return Z(0,o.length).map(()=>Rr(I))}),d=Z(0,u).flatMap(()=>{let I=J(i,!1,!0);return Z(0,i.length).map(()=>Rr(I))}),l=Z(0,p).flatMap(()=>{let I=J(s,!1,!0);return Z(0,s.length).map(()=>Rr(I))}),f={};for(let I=0;I<n;I++){let h=m.pop(),S=r||en([Zt,ce]),T=S===Zt?l.pop():d.pop(),A=en(a);f[`${T}${h}`]={nationalityCode:A,sex:S,firstName:T,lastName:h}}return{personData:Object.values(f).slice(0,e)}}function aA(t){let e=t?.count||1,{personExtensions:r,consideredDate:n,isMock:o=!0,gendersCount:i,personData:s,category:a,sex:c}=t||{};if(isNaN(e))return{error:G};let u=i?.[Zt]||c===Zt&&e||0,p=i?.[ce]||c===ce&&e||0;e=Math.max(e,u+p);let m=e-(u+p),d=u&&sA({count:u,sex:Zt}).personData||[],l=p&&sA({count:p,sex:ce}).personData||[],f=[...d,...l,...m&&sA({count:m}).personData||[]],g=f.filter(U=>!c||u&&p||U.sex===c),I=[];if(Array.isArray(s)){let U=s.filter(M=>typeof M.firstName!="string"||typeof M.lastName!="string"||M.sex&&![Zt,ce].includes(M.sex)||M.nationalityCode&&(typeof M.nationalityCode!="string"||M.nationalityCode.length>3||!Yo.find(({iso:N,ioc:C})=>[N,C].includes(M.nationalityCode)))?!1:(M.nationalityCode&&I.push(M.nationalityCode),!0));if(U.length)g=U;else return{error:G}}let h=s?g:sr(g);if(h.length<e){let{maleFirstNames:U,maleLastNames:M,femaleFirstNames:N,femaleLastNames:C,nationalityCodes:D}=f.reduce((O,b)=>{let{firstName:_,lastName:L,nationalityCode:F}=b;return b.sex===Zt?(O.maleFirstNames.includes(_)||O.maleFirstNames.push(_),O.maleLastNames.includes(L)||O.maleLastNames.push(L)):(O.femaleFirstNames.includes(_)||O.femaleFirstNames.push(_),O.femaleLastNames.includes(L)||O.femaleLastNames.push(L)),O.nationalityCodes.includes(F)||O.nationalityCodes.push(F),O},{maleFirstNames:[],maleLastNames:[],femaleFirstNames:[],femaleLastNames:[],nationalityCodes:[]});Z(0,e-h.length).forEach(()=>{let O=c||en([Zt,ce]),b=en(D),_=O===Zt?en(U):en(N),L=O===Zt?en(M):en(C),F={firstName:_,lastName:L,sex:O,nationalityCode:b};h.push(F)})}let{ageMinDate:S,ageMaxDate:T}=mu({consideredDate:n,category:a}),A=ct(S?.slice(0,4)||0)||ct(T?.slice(0,4)||0)-3,P=ct(T?.slice(0,4)||0)||ct(S?.slice(0,4)||0)+3,y=(S||T)&&[A,P],E=h.slice(0,e).map((U,M)=>{let[N,C]=y||[],D=y&&Rr(Z(N,C)),O=Rr(Z(0,365)),b=D&&lC(D,O);return Object.assign(rt({extensions:r||[{name:"regionCode",value:M+1}],birthDate:b,isMock:o}),U)});return{persons:E.length&&E||h[0],nationalityCodes:I}}var xv=["Ace Academy","Avengers","Ball Bouncers","Baseliners","Captivators","Civil Disobedients","Continentals","Court Royal","Court Sharks","Diamond Dogs","Danger Zone","Doubles Dominators","Double Faults","Tricksters","Eliminators","Court Crusaders","Fuzz Busters","Game Changers","Goal Gurus","Good Volley","Green Machine","Hawk Eyes","Inside Outers","Killer Instinct","Line Toers","Masters of Mayhem","Matter Catchers","Cheap Shot","Mean Machines","Mindspace Invaders","Net Centric","Net Positive","Smash Mullet","Over Your Head","Spin Meisters","Aggressors","Racket Machine","Slice Happy","Refs Nightmare","Sandeaters","Sun Seekers","Slicer Dicers","Sparkle Soul Tribe","Stacked Deck","Cross Stringers","The Emergence","Total Demolition","Touch and Go","Upside Downers","Vertically Challenged","Visual Spectacle"];function Rg({nameRoot:t="TEAM",count:e=1}={}){let n=sr(xv).slice(0,e);return n.length<e&&Z(0,e-n.length).forEach(o=>n.push(`${t} ${o+1}`)),{names:n}}function bg({idPrefix:t,participantType:e,index:r,uuids:n}){return t?`${t}-${e===It?"I":pt?"P":Lt?"T":hr?"G":"X"}-${r}`:n?.pop()||Mt()}function Pc(t){let{rankingRange:e,scaledParticipantsCount:r}=t,{ratingsParameters:n=Jr,valuesInstanceLimit:o,consideredDate:i,category:s,nationalityCodesCount:a,nationalityCodeType:c,nationalityCodes:u,participantsCount:p=32,participantType:m,personIds:d,idPrefix:l,uuids:f,personExtensions:g,addressProps:I,gendersCount:h,matchUpType:S,personData:T,sex:A,inContext:P,withISO2:y,withIOC:E,scaleAllParticipants:U}=t,M=m===pt||S===Ri,N=m===Lt||S===Lt;e&&(!Array.isArray(e)||!e.every(Xt=>se(Xt))||e.length!==2)&&(e=void 0),r=U?p:r;let C=1e3,D=r&&r>C?r:C;e=e||[1,D],e[1]+=1;let O=p*(M?2:N?8:1),b=aA({count:O,personExtensions:g,consideredDate:i,gendersCount:h,personData:T,category:s,sex:A});if(b.error)return b;let{nationalityCodes:_,persons:L}=b,F=[],w=[],x=[],H=[];if(typeof s=="object"){let{categoryName:Xt,ageCategoryCode:Ue,ratingType:Ht}=s;if((Xt||Ue)&&!Ht){let[Ie,Nt]=e||[];if(w=sr(Z(Ie,Nt)).slice(0,r||qn(20,30)),[pt,Lt].includes(m)){let[Qt,Ft]=e||[];F=sr(Z(Qt,Ft)).slice(0,r||qn(20,30))}}if(Ht&&n[Ht]){let{ratingMax:Ie,ratingMin:Nt,ratingAttributes:Qt}=s,Ft={...n[Ht],...Qt||{}},{attributes:Yt={},decimalsCount:ue,accessors:Se,range:ur,step:Oe}=Ft,Vt=Pe=>{let dr={},Xo=Object.keys(Pe||{});for(let He of Xo){let Pn=Pe[He];if(typeof Pn=="object"&&Pn.generator){let{range:Ii}=Pn,[Gi,fn]=Ii.slice().sort();dr[He]=qn(Gi,fn)}else dr[He]=Pn}return dr},tr=ur[0]>ur[1]?2:.5,[Re,Er]=ur.slice().sort(),Te=()=>Z(0,2e3).map(()=>Vy(Re,Er,tr,Oe,ue)).filter(Pe=>(!Ie||Pe<=Ie)&&(!Nt||Pe>=Nt)).slice(0,r||qn(20,30)).map(Pe=>Se?Object.assign({},...Se.map(dr=>({[dr]:Pe})),Vt(Yt)):Pe);x=Te(),[pt,Lt].includes(m)&&(H=Te())}}let V=Yo.filter(Xt=>c==="IOC"&&Xt.ioc||Xt.iso);function W(Xt){let Ue=Math.ceil(O/Xt);return o&&Ue>o?Math.ceil(O/o):Xt}let{postalCodesProfile:B,postalCodesCount:q,statesProfile:Y,citiesProfile:k,citiesCount:K,statesCount:X}=I||{},$=Xt=>Object.keys(Xt).map(Ue=>Z(0,Y[Ue]).map(()=>Ue)).flat(),nt=k&&$(k)||I?.cities||rA({count:K||O,participantsCount:O}).cities,Q=Y&&$(Y)||I?.states||nA({count:X||O,participantsCount:O}).states,it=B&&$(B)||I?.postalCodes||oA({count:q||O,participantsCount:O}).postalCodes,ot={cities:nt,states:Q,postalCodes:it},dt=W(a),zt=dt?sr(V).slice(0,a):u?V.filter(Xt=>u.includes(Xt.iso)):V,Et=sr(Z(0,Math.ceil(O/(dt||1))).map(()=>zt).flat(1/0)),ge=Rg({count:p}).names;return{participants:Z(0,p).map(Xt=>{let Ue=M?2:N?8:1,Ht=Z(0,Ue).map(Yt=>{let ue=Xt*Ue+Yt;return Ce(ue)}),Ie=Ht.map(Yt=>Yt.participantId),Nt=Ht.map(Yt=>Yt.person.standardFamilyName).join("/"),Qt=M?pt:Lt,Ft={participantId:bg({participantType:Qt,idPrefix:l,index:Xt,uuids:f}),participantRole:Fe,participantName:M?Nt:ge[Xt],individualParticipantIds:Ie,participantType:Qt};return P&&(Ft.individualParticipants=Ht),M||N?[Ft,...Ht]:Ht}).flat(),...R};function Ce(Xt){let Ue=L[Xt],{nationalityCode:Ht,participantExtensions:Ie,participantTimeItems:Nt,extensions:Qt,firstName:Ft,birthDate:Yt,lastName:ue,personId:Se,sex:ur}=Ue||{},Oe=Ft||"GivenName",Vt=ue||"FamilyName",_e=`${Oe} ${Vt}`,tr=Et[Xt],Re=_?.length&&Ht||tr&&(c==="IOC"?tr.ioc||tr.iso:tr.iso||tr.ioc)||Ht;Et?.length&&!Re&&!Ht&&console.log("%c Invalid Nationality Code",{participantIndex:Xt,country:tr});let Er=iA({...ot,participantIndex:Xt,nationalityCode:Re}),Te=rt({participantId:bg({participantType:It,index:Xt,idPrefix:l,uuids:f}),extensions:Ie,timeItems:Nt,participantRole:Fe,participantType:It,participantName:_e,person:{addresses:[Er],personId:Se||d?.length&&d[Xt]||Mt(),standardFamilyName:Vt,standardGivenName:Oe,nationalityCode:Re,extensions:Qt,birthDate:Pr(Yt)?Yt:void 0,sex:ur}});if(E&&Re){let Pe=Yo.find(({iso:dr})=>dr===Re);Pe?.ioc&&(Te.person.iocNationalityCode=Pe.ioc),Pe?.label&&(Te.person.countryName=Pe.label)}if(y&&Re){let Pe=Yo.find(({iso:dr})=>dr===Re);Pe?.iso2&&(Te.person.iso2NationalityCode=Pe.iso2),Pe?.label&&(Te.person.countryName=Pe.label)}if(s){let Pe=w[Xt],dr=F[Xt];cA({scaleValue:Pe,eventType:vs,scaleType:Zo,participant:Te,category:s}),cA({scaleValue:dr,eventType:ui,scaleType:Zo,participant:Te,category:s});let Xo=x[Xt],He=H[Xt];cA({scaleValue:Xo,eventType:vs,scaleType:Yi,participant:Te,category:s}),cA({scaleValue:He,eventType:ui,scaleType:Yi,participant:Te,category:s})}return Te}}function cA({scaleValue:t,participant:e,eventType:r,scaleType:n,category:o}){let i=o.categoryName||o.ratingType||o.ageCategoryCode,s=[qi,n,r,i].join("."),a={itemValue:t,itemType:s};i&&t&&(e.timeItems||(e.timeItems=[]),e.timeItems.push(a))}function uA({alternatesCount:t=0,tieFormatName:e,tieFormat:r,drawSize:n}){let o=0,i=0,s=0,a=0,c={},u={[Zt]:0,[ce]:0,[Cr]:0,[Ia]:0,[On]:0};r=typeof r=="object"?r:Li({namedFormat:e}),r?.collectionDefinitions?.filter(Boolean).forEach(l=>{let{category:f,collectionId:g,matchUpType:I,matchUpCount:h,gender:S}=l;if([Zt,ce].includes(S)){let T=h*(I===jt?2:1);u[S]<T&&(u[S]=T)}else S===Cr&&(u[Zt]<h&&(u[Zt]=h),u[ce]<h&&(u[ce]=h));if(f){let T=JSON.stringify(f);c[T]=f}if(g||(l.collectionId=Mt()),I===jt){let T=h;a+=h,o=Math.max(o,T)}if(I===ee){let T=h;s+=h,i=Math.max(i,T)}});let p=Object.keys(c).length?Math.max(s,a*2):Math.max(i,o*2),m=o*(n+t),d=i*(n+t);return{maxDoublesDraw:m,maxSinglesDraw:d,teamSize:p,genders:u}}function wv({participantsProfile:t,eventProfiles:e,drawProfiles:r}){let{participantsCount:n,participantType:o=It}=t||{},i=n||0,s={[ce]:0,[Cr]:0,[Ia]:0,[Zt]:0,[On]:0},a=0,c=0,u=0,p=0,m=0,d=({alternatesCount:f=0,uniqueParticipants:g,tieFormatName:I,drawSize:h=0,eventType:S,tieFormat:T,category:A,gender:P,stage:y})=>{let E=S===Vr,U=S===Le,M=!!(g||y===at||A||P);if(U){p=Math.max(p,h+f),T=typeof T=="object"?T:Li({namedFormat:I});let{teamSize:N,maxDoublesDraw:C,maxSinglesDraw:D,genders:O}=uA({alternatesCount:f,tieFormatName:I,tieFormat:T,drawSize:h});u=Math.max(u,N),c=Math.max(c,D),M||(a=Math.max(a,C)),Object.keys(O).forEach(b=>s[b]+=O[b])}else if(E)if(M){let N=(h+f)*2;m+=N,P&&(s[P]+=N)}else h+f&&h+f>a&&(a=h+f);else if(M){let N=h+f;P&&(s[P]+=N),m+=N}else h&&h>c&&(c=h+f)};if(e?.forEach(f=>{let{tieFormatName:g,tieFormat:I,drawProfiles:h,eventType:S,category:T,gender:A}=f;if(h)for(let P of h){let{tieFormatName:y,tieFormat:E}=P;d({...P,tieFormatName:y||g,tieFormat:E||I,eventType:S,category:T,gender:A})}}),Array.isArray(r))for(let f of r)d(f);let l=Math.max(p*u,a*2,c);return a&&(o=pt),(n||i)<l&&(n=l),n&&a&&[pt,Le].includes(o)&&(c&&Math.floor(c/2)>a?n=Math.floor(c/2):(!c||a*2>=c)&&(n=Math.ceil(n/2))),n===void 0&&(n=!e?.length&&!r?.length?32:0),n<i&&(n=i),{uniqueParticipantsCount:m,participantsCount:n,largestTeamDraw:p,largestTeamSize:u,participantType:o,gendersCount:s}}function pA({participantsProfile:t,tournamentRecord:e,eventProfiles:r,drawProfiles:n,startDate:o,uuids:i}){let{participantsCount:s,participantType:a,largestTeamDraw:c,largestTeamSize:u,gendersCount:p}=wv({participantsProfile:t,eventProfiles:r,drawProfiles:n}),m=t?.teamKey,d=Pc({uuids:i,...t,consideredDate:o,participantsCount:s,participantType:a,gendersCount:p}).participants,l=0,f=ln({tournamentRecord:e,participants:d});if(f.error)return f;if(l+=f.addedCount,m){let S=Cg({tournamentRecord:e,...m});if(S.error)return S}let g=d.filter(({participantType:S})=>S===It).map(ft),I=t?.idPrefix?`${Lt}-${t.idPrefix}`:void 0,h=Z(0,c).map(S=>{let T=g.slice(S*u,(S+1)*u),A=bg({index:S,participantType:a,idPrefix:I,uuids:i});return{participantName:`Team ${S+1}`,participantRole:Fe,individualParticipantIds:T,participantType:Lt,participantId:A}});return f=ln({participants:h,tournamentRecord:e}),f.error?f:(l+=f.addedCount,{addedCount:l,...R})}var aD=()=>({altitude:void 0,courtId:void 0,courtName:"",courtDimensions:void 0,latitude:void 0,longitude:void 0,surfaceCategory:void 0,surfaceType:void 0,surfacedDate:void 0,dateAvailability:[],onlineResources:[],pace:void 0,notes:void 0}),Lv=aD;function mA(t){return parseInt(t)}function cD({startTime:t="",endTime:e=""}={}){if(!t||!e||!Ps.test(t)||!Ps.test(e))return!1;let[r,n]=t.split(":").map(mA),[o,i]=e.split(":").map(mA);return o<r?!1:!(r===o&&i<n)}function Fv(t,e){let[r,n]=t.startTime.split(":").map(mA),[o,i]=e.startTime.split(":").map(mA);return r<o?-1:r>o?1:n<i?-1:n>i?1:0}function dA({dateAvailability:t}){if(!t)return{error:iy};if(!Array.isArray(t))return{error:cl};let e="Dates must be formated => YYYY-MM-DD",r="Times must be 24 hour => 00:00";for(let n of t){if(typeof n!="object")return{error:cl};let{date:o,startTime:i,endTime:s,bookings:a=[]}=n;if(!i||!s)return{error:cl};if(o&&!ao.test(o))return{error:ir,dateAvailability:{date:o},info:e};if(!Ps.test(i))return{error:io,dateAvailability:{startTime:i},info:r};if(!Ps.test(s))return{error:io,dateAvailability:{endTime:s},info:r};if(i===s)return{error:io,dateAvailability:{startTime:i,endTime:s},info:"startTime and endTime are equivalent"};if(!cD({startTime:i,endTime:s}))return{error:io,dateAvailability:{startTime:i,endTime:s},info:"endTime must be after startTime"};if(a){if(!Array.isArray(a))return{error:Xp};for(let c of a){if(typeof c!="object")return{error:Xp};let{startTime:u,endTime:p}=c;if(!Ps.test(u))return{error:io,booking:{startTime:u},info:r};if(!Ps.test(p))return{error:io,booking:{endTime:p},info:r};if(u===p)return{error:io,dateAvailability:{startTime:u,endTime:p},info:"startTime and endTime are equivalent"};if(!cD({startTime:u,endTime:p}))return{error:io,dateAvailability:{startTime:u,endTime:p},info:"endTime must be after startTime"}}}}return{valid:!0}}function Hd({tournamentRecord:t,disableNotice:e,venueId:r,courtId:n,court:o}){let{venue:i}=jo({tournamentRecord:t,venueId:r});if(!i)return{error:Es};i.courts||(i.courts=[]);let s={...aD(),venueId:r,courtId:n};if(s.courtId||(s.courtId=Mt()),i.courts.some(c=>c.courtId===s.courtId))return{error:yy};{let c=(o?.dateAvailability||[]).map(m=>({...m,date:At(m.date),startTime:qt(m.startTime),endTime:qt(m.endTime),bookings:m.bookings?.map(({startTime:d,endTime:l,bookingType:f})=>({startTime:qt(d),endTime:qt(l),bookingType:f}))})),u=Object.keys(s);for(let m of u)if(o?.[m])if(m==="dateAvailability"){let d=dA({dateAvailability:c});if(!d.valid&&d.error)return d;s.dateAvailability=c}else s[m]=o[m];let p=s;return i.courts.push(p),e||Tt({payload:{venue:i,tournamentId:t.tournamentId},topic:ni,key:i.venueId}),{...R,court:J(s),venueId:r}}}function Og(t){let{tournamentRecord:e,venueId:r}=t;if(typeof r!="string"||!r)return{error:vo};let n=t.tournamentRecords??(e&&{[e.tournamentId]:e})??{},o=[],i;for(let s of Object.values(n)){let{venue:a}=jo({tournamentRecord:s,venueId:r});if(a){let c=sV({...t,tournamentRecord:s});for(let u of c?.courts??[])o.push(u?.courtId);if(c.error)return c;i=!0}}return i?{...R,courtIds:o}:{error:Es}}function sV({courtNameRoot:t="Court",dateAvailability:e=[],venueAbbreviationRoot:r,tournamentRecord:n,courtNames:o=[],courtTimings:i,courtsCount:s,startTime:a,courtIds:c,endTime:u,idPrefix:p,venueId:m,dates:d}){if(!m)return{error:vo};let l=jo({tournamentRecord:n,venueId:m});if(l.error)return l;let{venue:f}=l;if(!se(s)||!o)return{error:Ay};s=s??o.length;let h=Z(0,s).map(S=>{let T=i?.[S],A=T?d.map(P=>({date:Kn(P),startTime:a,endTime:u,...T})):e;return T&&a&&u&&A.push({startTime:a,endTime:u}),{courtName:o[S]||r&&f?.venueAbbreviation&&`${f?.venueAbbreviation} ${S+1}`||`${t} ${S+1}`,dateAvailability:A}}).map((S,T)=>{let A=c?.pop()||p&&`${p}-${T+1}`;return Hd({disableNotice:!0,tournamentRecord:n,courtId:A,venueId:m,court:S})}).map(S=>S.court).filter(Boolean);return h.length!==s?v({info:"not all courts could be generated",result:{error:G}}):(f&&Tt({payload:{venue:f,tournamentId:n.tournamentId},topic:ni,key:f.venueId}),{...R,courts:J(h)})}function lA({tournamentRecord:t,venueProfiles:e,uuids:r}){let{startDate:n,endDate:o}=t,i=[];for(let[s,a]of e.entries()){let{venueAbbreviation:c,venueId:u=r?.pop()??Mt(),dateAvailability:p,startTime:m="07:00",endTime:d="19:00",courtTimings:l,courtsCount:f,courtNames:g,venueName:I,idPrefix:h,courtIds:S}=a,T={venueName:I||`Venue ${s+1}`,venueAbbreviation:c,venueId:u},A=nc({tournamentRecord:t,venue:T});if(A.error)return A;i.push(u);let P=vc(n,o),y=!Array.isArray(p)&&[{startTime:m,endTime:d}].concat(P.map(U=>({date:Kn(U),startTime:m,endTime:d}))),E=Og({dateAvailability:p||y,tournamentRecord:t,courtTimings:l,courtsCount:f,courtNames:g,startTime:m,idPrefix:h,courtIds:S,endTime:d,venueId:u,dates:P});if(E.error)return E}return i}function fA({drawProfiles:t,category:e,gender:r}){let n={},o=t?.reduce((s,a)=>{let{qualifyingPositions:c=0,participantsCount:u=0,uniqueParticipants:p,stage:m=tt,drawSize:d=0}=a||{};Object.keys(s).includes(m)||(s[m]=0);let l=(u||d)-c;return p||r||e||m===at?(Object.keys(n).includes(m)||(n[m]=0),n[m]+=l):s[m]=Math.max(s[m],l),s},{}),i=Object.keys(n);return i.forEach(s=>o[s]+=n[s]),{stageParticipantsCount:o,uniqueParticipantsCount:n,uniqueParticipantStages:i}}function gA({allUniqueParticipantIds:t,stageParticipantsCount:e,eventParticipantType:r,targetParticipants:n}){let o=e[tt]||0,i=e[at]||0;return{stageParticipants:{QUALIFYING:n.filter(({participantType:a})=>a===r).filter(({participantId:a})=>!t.includes(a)).slice(0,i),MAIN:n.filter(({participantType:a})=>a===r).filter(({participantId:a})=>!t.includes(a)).slice(i,i+o)}}}function Oa(t){let{removePriorValues:e,tournamentRecord:r,participantId:n,scaleItem:o}=t,i,s;if(!Gv({scaleItem:o}))return{error:Fu};if(n&&Array.isArray(r.participants)&&(s=r.participants.find(a=>a.participantId===n),s)){let a=kv({removePriorValues:e,participant:s,scaleItem:o});if(a.error)return a;i=!a.valueChanged;let{topics:c}=Fr();c.includes($e)&&Tt({topic:$e,payload:{tournamentId:r.tournamentId,participants:[s]}})}return i&&{...R,info:Al,existingValue:o?.scaleValue}||s&&{...R,newValue:o?.scaleValue}||{error:Jt}}function uD(t){let{scaleItemsWithParticipantIds:e=[],removePriorValues:r,tournamentRecord:n,auditData:o,context:i}=t;if(!n)return{error:j};if(!n.participants)return{error:Ba};let s=0,a={},c=[];for(let m of e){let d=m?.participantId;if(Array.isArray(m?.scaleItems))for(let l of m.scaleItems)if(Gv({scaleItem:l}))Array.isArray(a[d])||(a[d]=[]),a[d].push(l);else return{error:Fu}}n.participants.forEach(m=>{let{participantId:d}=m||{};Array.isArray(a[d])&&a[d].forEach(l=>{kv({participant:m,scaleItem:l,removePriorValues:r}),c.push(m),s++})});let u=s?void 0:Us,{topics:p}=Fr();if(p.includes($e)&&s&&Tt({topic:$e,payload:{tournamentId:n.tournamentId,participants:c}}),i){let{eventId:m,drawId:d,...l}=i,f=l.scaleAttributes?.scaleType&&[l.scaleAttributes.scaleType];if(Object.keys(l).length){let g={itemType:zl,itemValue:l};if(f&&(g.itemSubTypes=f),d||m){let{drawDefinition:I,event:h}=nr({tournamentRecord:n,eventId:m,drawId:d});d&&Hf({drawDefinition:I,timeItem:g}),m&&xi({event:h,timeItem:g})}else vi({tournamentRecord:n,timeItem:g})}}return o&&p.includes(pa)&&Tt({topic:pa,payload:o}),rt({...R,modificationsApplied:s,info:u})}function Gv({scaleItem:t}){let e=t&&Object.keys(t),r=["scaleType","eventType","scaleName"];return!!(r.filter(o=>e?.includes(o)).length===r.length)}function kv({removePriorValues:t,participant:e,scaleItem:r}){if(!e)return{error:Ai};let n=r&&Object.keys(r),o=["scaleType","eventType","scaleName"];if(!(o.filter(p=>n.includes(p)&&r[p]).length===o.length))return{error:Fu};let s=new Date().toISOString();e.timeItems||(e.timeItems=[]);let{scaleItem:a}=no({scaleAttributes:r,participant:e}),c=p=>[void 0,null,""].includes(p),u=!(c(a?.scaleValue)&&c(r.scaleValue))&&JSON.stringify(a?.scaleValue)!==JSON.stringify(r.scaleValue);if(u){let{scaleType:p,eventType:m,scaleName:d}=r,l=[qi,p,m,d].join("."),f=rt({itemValue:r.scaleValue,itemDate:r.scaleDate,createdAt:s,itemType:l});r.scaleId&&(f.itemSubTypes=[r.scaleId]),t&&(e.timeItems=e.timeItems.filter(g=>g.itemType!==l)),e.timeItems.push(f)}return{...R,valueChanged:u,newValue:r.scaleValue}}var aV={[Ot]:2,[fe]:1,[Me]:1,[mr]:1,[bt]:4};function _g(t){let{defaultWithScorePercent:e=2,winningSide:r}=t,{matchUpStatusProfile:n=aV,matchUpFormat:o=on,pointsPerMinute:i=1,sideWeight:s=4}=t;if(!Sr({matchUpFormat:o}))return{error:ol};if(typeof n!="object")return{error:G};if(e>100&&(e=100),isNaN(e)||isNaN(i)||isNaN(s))return{error:G};let a=Object.keys(n).filter(C=>Object.keys(FI).includes(C)&&C!==me);if(Object.keys(a).reduce((C,D)=>C+n[D],0)>100)return{error:G,matchUpStatusProfile:n};let u=a.reduce((C,D)=>(C.pointer=C.pointer+n[D],C.valueMap.push([C.pointer,D]),C),{pointer:0,valueMap:[]}),p=qn(1,100),m=(u.valueMap.find(C=>p<=C[0])??[100,me])[1],d={sets:[],scoreStringSide1:"",side2ScoreString:""};if([Ot,bt].includes(m)){r=r||qn(1,2);let C={score:d,winningSide:r,matchUpStatus:m};if(!(m===bt&&qn(1,100)>100-e))return{outcome:C}}else if([fe,Me].includes(m))return{outcome:{score:d,matchUpStatus:m}};let l=Ze(o),{bestOf:f,setFormat:g,finalSetFormat:I}=l??{},h=[],S=qn(0,1),T=r?[r-1]:[...Z(0,s).map(()=>S),1-S],P=[mr,bt,No,Ki].includes(m)&&(Rr(Z(1,f))||1),y;for(let C of Z(1,(f??0)+1)){let D=C===f,{set:O,incomplete:b,winningSideNumber:_}=cV({incomplete:P===C,matchUpStatus:m,pointsPerMinute:i,setFormat:D&&I||g,setNumber:C,weightedRange:T});if(h.push(O),b){y=_;break}if(Cp({matchUp:{score:{sets:h},matchUpFormat:o}}).calculatedWinningSide)break}let E=Cp({matchUp:{score:{sets:h},matchUpFormat:o}}),U=y?r||y:E.calculatedWinningSide,{score:M}=XT({score:{sets:h},winningSide:U,matchUpStatus:m});return{outcome:{score:M,winningSide:U,matchUpStatus:m}}}function cV({weightedRange:t=[0,1],pointsPerMinute:e,matchUpStatus:r,incomplete:n,setFormat:o,setNumber:i}){let s={setNumber:i},{setTo:a,tiebreakFormat:c,tiebreakAt:u,tiebreakSet:p,timed:m,minutes:d}=o,l=qn(0,t.length-1),f=t[l],g;if(m){let I=d*e,h=Math.round(I*.2),S=I+Rr([1,-1])*h,T=tC(S,2),A=[T,S-T];f&&A.reverse(),g=t[l]+1;let P=A[0]>A[1]&&1||A[1]>A[0]&&2||0;if(n){let[U,M]=A;return Object.assign(s,{side1Score:U,side2Score:M}),ie.includes(r)?{set:s,incomplete:n,winningSideNumber:g}:{set:s,incomplete:n}}P||(A[qn(0,1)]+=1),P=A[0]>A[1]?1:2,P!==g&&A.reverse();let[y,E]=A;return Object.assign(s,{side1Score:y,side2Score:E,winningSide:g}),{set:s}}else{if(n)return s.side1Score=qn(0,u),s.side2Score=qn(0,u),ie.includes(r)&&(g=t[l]+1),{set:s,incomplete:n,winningSideNumber:g};{let I=Z(1,a+1).map(E=>Z(0,a+2-E).map(()=>E)).flat(),h=I[qn(0,I.length-1)],S=a&&JS({isSide1:!0,tiebreakAt:u,lowValue:h,setTo:a}),T=!S,A=t.length===1&&t[l]+1;if(!T){A?(S[0]>S[1]?1:2)!==A&&S.reverse():f&&S.reverse();let[E,U]=S;Object.assign(s,{side1Score:E,side2Score:U})}let P=Mp({matchUpScoringFormat:{setFormat:o},setObject:s}),y;if(P.hasTiebreakCondition||T){let{NoAD:E,tiebreakTo:U}=c||p||{},M=Z(1,U+1).map(D=>Z(0,U+2-D).map(()=>D)).flat(),N=M[qn(0,M.length-1)],C=Ed({isSide1:!0,tiebreakNoAd:E,tiebreakTo:U,lowValue:N});if(C)if(T){let D=C[0]>C[1]?1:2;A?D!==A&&C.reverse():f&&C.reverse(),[s.side1TiebreakScore,s.side2TiebreakScore]=C,y=C[0]>C[1]&&1||C[1]>C[0]&&2||void 0}else P.leadingSide===2?[s.side1TiebreakScore,s.side2TiebreakScore]=C:[s.side2TiebreakScore,s.side1TiebreakScore]=C}s.winningSide=P.winningSide||P.leadingSide||A||y}}return{set:s}}function Wd(t){let{matchUpStatusProfile:e,completeAllMatchUps:r,randomWinningSide:n,tournamentRecord:o,completionGoal:i,drawDefinition:s,event:a}=t;if(!s)return{error:z};let c=t.matchUpFormat||s.matchUpFormat||a?.matchUpFormat,u=s.structures.slice().sort(ri),p=0,{matchUps:m,matchUpsMap:d}=re({contextFilters:{stages:[tt,at]},matchUpFilters:{matchUpTypes:[Bt],roundNumbers:[1]},inContext:!0,drawDefinition:s});if(m?.length){let g=a?.category?.ageCategoryCode||a?.category?.categoryName;if(g){let h=FT({singlesOnly:!0,tournamentRecord:o,drawDefinition:s,scaleAccessor:{scaleName:g,sortOrder:wN,scaleType:Zo},event:a});if(h.error)return h;let{lineUps:S,participantsToAdd:T}=h;ln({tournamentRecord:o,participants:T}),gt({element:s,extension:{name:mo,value:S}})}else{let I=m[0]?.structureId,{positionAssignments:h}=Dt({drawDefinition:s,structureId:I});if(h?.length){let{participants:S}=$t({participantFilters:{participantTypes:[Bt]},tournamentRecord:o}),T=A=>{let P=A.tieMatchUps.filter(({matchUpType:E})=>E===ee),y=A.tieMatchUps.filter(({matchUpType:E})=>E===jt);P.forEach((E,U)=>{let M=E.matchUpId;E.sides.forEach(N=>{let{drawPosition:C}=N,D=S?.find(O=>{let{participantId:b}=O;return h.find(L=>L.participantId===b)?.drawPosition===C});if(D){let O=D.individualParticipantIds?.[U];O&&wd({teamParticipantId:D.participantId,participantId:O,tournamentRecord:o,drawDefinition:s,tieMatchUpId:M,event:a})}})}),y.forEach((E,U)=>{let M=E.matchUpId;E.sides.forEach(N=>{let{drawPosition:C}=N,D=S?.find(O=>{let{participantId:b}=O;return h.find(L=>L.participantId===b)?.drawPosition===C});D&&D.individualParticipantIds?.slice(U*2,U*2+2)?.forEach(b=>{wd({teamParticipantId:D.participantId,participantId:b,tournamentRecord:o,drawDefinition:s,tieMatchUpId:M,event:a})})})})};m.forEach(T)}}}let l=typeof r=="string"&&r,f=l&&me;for(let g of u){if(p>=i)break;let{matchUps:I}=Pt({matchUpFilters:{matchUpTypes:[jt,ee]},afterRecoveryTimes:!1,tournamentRecord:o,inContext:!0,drawDefinition:s,matchUpsMap:d,structure:g,event:a}),h=I.filter(({winningSide:S})=>!S).sort(mi).map(le);for(let S of h){if(!isNaN(i)&&p>=i)break;let{matchUps:T}=Pt({matchUpFilters:{matchUpTypes:[jt,ee]},afterRecoveryTimes:!1,tournamentRecord:o,inContext:!0,drawDefinition:s,matchUpsMap:d,structure:g,event:a}),A=T.find(y=>y.matchUpId===S),P=[fe,Me].includes(A.matchUpStatus);if(A?.readyToScore&&!P){let y=uV({winningSide:!n&&1,matchUpStatusProfile:e,tournamentRecord:o,drawDefinition:s,targetMatchUp:A,matchUpFormat:c,matchUpStatus:f,scoreString:l,event:a});if(y?.error)return y;p+=1}}}return{...R,completedCount:p}}function pD(t){let{matchUpStatusCodes:e,policyDefinitions:r,tournamentRecord:n,drawDefinition:o,targetMatchUp:i,matchUpStatus:s,matchUpFormat:a,scoreString:c,winningSide:u,event:p}=t;if(!i||i.matchUpStatus===Ut)return;let{matchUpId:m}=i||{},{outcome:d}=Dg({matchUpFormat:a,matchUpStatus:s,scoreString:c,winningSide:u});return e&&(d.matchUpStatusCodes=e),Du({tournamentRecord:n,policyDefinitions:r,drawDefinition:o,matchUpFormat:a,matchUpId:m,outcome:d,event:p})}function uV(t){let{matchUpStatusProfile:e={},tournamentRecord:r,policyDefinitions:n,drawDefinition:o,matchUpStatus:i,matchUpFormat:s,targetMatchUp:a,scoreString:c,winningSide:u,event:p}=t;if(c||i)return pD(t);let{matchUpId:m}=a||{},{outcome:d}=_g({matchUpStatusProfile:e,matchUpFormat:s,winningSide:u});return Du({policyDefinitions:n,tournamentRecord:r,drawDefinition:o,matchUpFormat:s,matchUpId:m,outcome:d,event:p})}function IA({matchUpStatusProfile:t,completeAllMatchUps:e,randomWinningSide:r,tournamentRecord:n,drawProfiles:o,event:i}){let s=kt({event:i}).flightProfile,{eventName:a,eventType:c,category:u}=i,{startDate:p}=n,m=[],d=u?.categoryName||u?.ageCategoryCode||u?.ratingType,l=i.drawDefinitions?.map(({drawId:f})=>f);if(Array.isArray(s?.flights))for(let[f,g]of s.flights.entries()){let{drawId:I,stage:h,drawName:S,drawEntries:T}=g;m.push(g.drawId);let A=o[f],{seedsCount:P,generate:y=!0}=A||{};if(y){let E=T.filter(Dr(zn)).map(Dr(zn)),U=d||a;if(n&&P&&P<=E.length&&Z(1,P+1).forEach((_,L)=>{let F={scaleValue:_,scaleName:U,scaleType:Qn,eventType:c,scaleDate:p},w=E[L];Oa({tournamentRecord:n,participantId:w,scaleItem:F})}),l?.includes(I))break;let M=Uu({...A,matchUpType:c,seedingScaleName:U,tournamentRecord:n,isMock:!0,drawEntries:T,drawName:S,drawId:I,event:i,stage:h});if(M.error)return{error:M.error,drawIds:[]};let{drawDefinition:N}=M;if(!N)return{error:fr};let C=o[f]?.drawExtensions;if(Array.isArray(C)&&C.filter(hn).forEach(b=>gt({element:N,extension:b})),M=wp({suppressNotifications:!0,tournamentRecord:n,drawDefinition:N,event:i}),M.error)return{error:M.error,drawIds:[]};if(A?.withPlayoffs){let b=N.structures?.[0].structureId,_=Sp({idPrefix:A.idPrefix,...A.withPlayoffs,tournamentRecord:n,drawDefinition:N,isMock:!0,structureId:b,event:i});if(_?.error)return _}let D=A?.completionGoal;if(!(A?.automated===!1)&&(e||D)){let b=A?.matchUpFormat,_=Wd({completeAllMatchUps:!D&&e,matchUpStatusProfile:t,randomWinningSide:r,tournamentRecord:n,completionGoal:D,drawDefinition:N,matchUpFormat:b,event:i});if(_.error)return{error:_.error,drawIds:[]};let L=_.completedCount;if(A?.drawType===to){let F=N.structures?.find(H=>H.stage===tt);if(!F)return{error:_t};let w=pc({structureId:F.structureId,tournamentRecord:n,drawDefinition:N,event:i});if(w.error)return{error:w.error,drawIds:[]};let x=D?D-(L??0):void 0;if(w=Wd({completeAllMatchUps:!D&&e,completionGoal:D?x:void 0,matchUpStatusProfile:t,randomWinningSide:r,tournamentRecord:n,drawDefinition:N,matchUpFormat:b,event:i}),w.error)return{error:w.error,drawIds:[]}}}}}return{...R,drawIds:m}}function hA(t){let{participantsProfile:e={},uniqueParticipantsCount:r,ratingsParameters:n,tournamentRecord:o,eventProfile:i,eventIndex:s,event:a,uuids:c}=t,{category:u,gender:p,eventType:m}=a,d=m===eo&&It||m===Vr&&pt||m,l=r[tt]||0,f=r[at]||0,g=i.drawProfiles?.length?l+f:i.participantsProfile?.participantsCount??0,I=[Zt,ce].includes(p)?p:void 0,h=e?.idPrefix?`E-${s}-${e?.idPrefix}`:void 0,{participants:S}=Pc({uuids:i.uuids||c,...e,scaledParticipantsCount:i.scaledParticipantsCount,consideredDate:o?.startDate,rankingRange:i.rankingRange,participantType:d,participantsCount:g,ratingsParameters:n,category:u,idPrefix:h,sex:I}),A=ln({tournamentRecord:o,participants:S});if(A.error)return A;let P=S?.filter(({participantType:E})=>E===d),y=S?.map(ft);return{uniqueDrawParticipants:P,uniqueParticipantIds:y}}function Vv({autoEntryPositions:t,tournamentRecord:e,drawParticipants:r,drawProfile:n,event:o}){let{drawType:i=Zn,qualifyingPositions:s=0,stage:a=tt,drawSize:c=0,drawName:u,drawId:p}=n,m=c-s,d=r.slice(0,m).map(ft);if(d.length){let g=Wn({participantIds:d,autoEntryPositions:t,entryStage:a,tournamentRecord:e,event:o});if(g.error)return g}let l=d.map(g=>({entryStatus:qr,entryStage:a,participantId:g})),f=Lp({drawName:u||i,qualifyingPositions:s,drawEntries:l,drawId:p,event:o,stage:a});return f.error?f:{...R}}function SA({uniqueDrawParticipants:t,autoEntryPositions:e,stageParticipants:r,tournamentRecord:n,drawProfiles:o,category:i,gender:s,event:a}){let c=0;for(let u of o){let{qualifyingPositions:p=0,uniqueParticipants:m,stage:d=tt,drawSize:l=0}=u,f=l-p,g=m||s||i||d===at,I=g?t.slice(c,c+f):r[d||tt]||[];g&&(c+=f);let h=Vv({autoEntryPositions:e,drawParticipants:I,tournamentRecord:n,drawProfile:u,event:a});if(h.error)return h}return{...R}}function TA(t){let{allUniqueParticipantIds:e,matchUpStatusProfile:r,participantsProfile:n,completeAllMatchUps:o,autoEntryPositions:i,hydrateCollections:s,randomWinningSide:a,ratingsParameters:c,tournamentRecord:u,eventProfile:p,eventIndex:m,publish:d,isMock:l,uuids:f}=t,g=p.gender,I=p.eventName,{eventType:h=eo,policyDefinitions:S,drawProfiles:T=[],eventExtensions:A,surfaceCategory:P,tieFormatName:y,processCodes:E,discipline:U,eventLevel:M,timeItems:N,ballType:C,category:D}=p,O=p.eventId||Mt(),b=p.tieFormat||(h===Le?Li({namedFormat:y,event:{eventId:O,category:D,gender:g},hydrateCollections:s,isMock:l}):void 0),_=u.participants;for(let $ of T)!g&&$.gender&&(g=$?.gender);let{stageParticipantsCount:L,uniqueParticipantsCount:F,uniqueParticipantStages:w}=fA({drawProfiles:T,category:D,gender:g}),x=h===eo&&It||h===Vr&&pt||h,{uniqueDrawParticipants:H=[],uniqueParticipantIds:V=[]}=w?hA({event:{eventType:h,category:D,gender:g},uniqueParticipantsCount:F,participantsProfile:n,ratingsParameters:c,tournamentRecord:u,eventProfile:p,eventIndex:m,uuids:f}):{},{eventAttributes:W}=p;typeof W!="object"&&(W={});let B=D?.categoryName||D?.ageCategoryCode||D?.ratingType;I=I||B||"Generated Event";let q={...W,surfaceCategory:P,processCodes:E,discipline:U,eventLevel:M,eventName:I,eventType:h,tieFormat:b,ballType:C,category:D,eventId:O,gender:g};if(A?.length&&Array.isArray(A)){let $=A.filter(hn);$?.length&&Object.assign(q,{extensions:$})}if(Array.isArray(N)&&N.forEach($=>xi({event:K,timeItem:$})),typeof S=="object")for(let $ of Object.keys(S))wi({policyDefinitions:{[$]:S[$]},event:q});q.category&&(q.category.categoryName=B);let Y,k=Sc({suppressNotifications:!1,internalUse:!0,tournamentRecord:u,event:q});if(k.error)return k;let K=k?.event,{stageParticipants:X}=gA({allUniqueParticipantIds:e,stageParticipantsCount:L,eventParticipantType:x,targetParticipants:_});if(T?.length){let $=SA({uniqueDrawParticipants:H,autoEntryPositions:i,stageParticipants:X,tournamentRecord:u,drawProfiles:T,category:D,gender:g,event:K});if($.error)return $;let nt=IA({matchUpStatusProfile:r,completeAllMatchUps:o,randomWinningSide:a,tournamentRecord:u,drawProfiles:T,event:K});if(nt.error)return nt;Y=nt.drawIds}else if(p?.participantsProfile?.participantsCount){let $=H.map(ft);if($.length){let nt=Wn({participantIds:$,autoEntryPositions:i,tournamentRecord:u,entryStage:tt,event:K});if(nt.error)return nt}}return d&&$s({tournamentRecord:u,event:K}),{drawIds:Y,eventId:O,uniqueParticipantIds:V}}function vg({tournamentRecords:t,scheduleDate:e,venueId:r,round:n}){if(!Pr(e))return{error:ir};let o="addSchedulingProfileRound",{extension:i}=ut({name:ca,tournamentRecords:t,discover:!0}),s=i?.value||[],a=s.find(l=>Dn(e,l.scheduleDate));if(!a){let{startDate:l,endDate:f}=dd({tournamentRecords:t}),g=new Date(e);if(l&&g<new Date(l)||f&&g>new Date(f))return{error:ir};a={scheduleDate:e,venues:[]},s.push(a)}let c=a.venues.find(l=>l.venueId===r);c||(c={venueId:r,rounds:[]},a.venues.push(c));let u=["notBeforeTime"],p=l=>Object.keys(l).filter(f=>!u.includes(f)).sort().map(f=>Ct(l[f])?p(l[f]):l[f]).flat().join("|");if(c.rounds.find(l=>p(l)===p(n)))return v({result:{error:$A},stack:o});c.rounds.push(n);let d=Ic({tournamentRecords:t,schedulingProfile:s});return d.error?d:{...R}}function Bv({schedulingProfile:t,tournamentRecord:e}){if(typeof t!="object")return{error:G};let r=zi({tournamentRecord:e}).containedStructures,n=pe({tournamentRecord:e}).matchUps??[],{tournamentId:o}=e,i=[];for(let s of t){let{scheduleDate:a,venues:c=[]}=s;for(let u of c){let{rounds:p,venueId:m}=u;for(let d of p){let{drawId:l,winnerFinishingPositionRange:f,roundSegment:g}=d,h=n.filter(S=>{let T=f?.indexOf("-")>0&&f.split("-").map(P=>+P),A=S.finishingPositionRange?.winner;return S.drawId===l&&(!d.roundNumber||S.roundNumber===d.roundNumber)&&(!A||!T||Wt(A,T).length===2||mt(A).length===mt(T).length&&Wt(A,T).length===mt(A).length)})[0];if(h){let{eventId:S,roundNumber:T,drawName:A,structureName:P,roundName:y}=h,E=h.structureId;T&&!f&&(E=Object.keys(r).find(N=>r[N].includes(E))??E);let U={tournamentId:o,structureId:E,roundNumber:T,roundSegment:g,eventId:S,drawId:l},M=vg({tournamentRecords:{[o]:e},round:U,scheduleDate:a,venueId:m});if(M.error)return M;i.push({structureName:P,roundName:y,drawName:A,...U})}}}}return{scheduledRounds:i}}function Yp(t){let e=vt(t,[{drawProfile:!0,_ofType:Ui}]);if(e.error)return e;let{allUniqueParticipantIds:r=[],participantsProfile:n={},matchUpStatusProfile:o,completeAllMatchUps:i,autoEntryPositions:s,hydrateCollections:a,randomWinningSide:c,ratingsParameters:u,tournamentRecord:p,isMock:m=!0,drawProfile:d,startDate:l,drawIndex:f,uuids:g}=t,I=J(d,!1,!0),{excessParticipantAlternates:h=!0,matchUpFormat:S=on,drawType:T=Zn,tournamentAlternates:A=0,alternatesCount:P=0,qualifyingPositions:y,qualifyingProfiles:E,generate:U=!0,eventExtensions:M,drawExtensions:N,completionGoal:C,tieFormatName:D,seedsCount:O,timeItems:b,drawName:_,category:L,idPrefix:F,publish:w,gender:x,stage:H}=I,V=I.drawSize||(I.ignoreDefaults?void 0:32),W=I.eventId||Mt(),B=d.eventType||d.matchUpType||eo,q=B===Vr?pt:It,Y=typeof d.tieFormat=="object"&&d.tieFormat||B===Lt&&Li({event:{eventId:W,category:L,gender:x},namedFormat:D,hydrateCollections:a,isMock:m})||void 0,k=L?.categoryName||L?.ageCategoryCode||L?.ratingType,K=d.eventName||k||`Generated ${B}`,X=p?.participants||[],$=(E?.map(Nt=>Nt.structureProfiles||[]).flat().reduce((Nt,Qt)=>{let Ft=!Qt.participantsCount||Qt.participantsCount>Qt.drawSize?Qt.drawSize:Qt.participantsCount||0;return Nt+Ft},0)||0)*(q===pt?2:1),nt=(!d.participantsCount||d.participantsCount>V?V:d.participantsCount)||0,Q={eventName:K,eventType:B,tieFormat:Y,category:L,eventId:W,gender:x};Array.isArray(b)&&b.forEach(Nt=>xi({event:Q,timeItem:Nt}));let{eventAttributes:it}=d;if(typeof it!="object"&&(it={}),Object.assign(Q,it),M?.length&&Array.isArray(M)){let Nt=M.filter(hn);Nt?.length&&Object.assign(Q,{extensions:Nt})}let ot=[];if($||d.uniqueParticipants||!p||x||L){let Nt=(nt||0)+P+$,Qt=Nt,Ft={[Zt]:0,[ce]:0},Yt,ue;B===Lt&&({teamSize:Yt,genders:ue}=uA({alternatesCount:P,tieFormatName:D,tieFormat:Y,drawSize:V}),Object.keys(ue).forEach(Vt=>{[Zt,ce].includes(Vt)&&ue[Vt]&&(Ft[Vt]=V*ue[Vt])}),Qt=Yt*((V||0)+$));let Se=n?.idPrefix?`D-${f}-${n?.idPrefix}`:void 0,Oe=Pc({...n,scaledParticipantsCount:d.scaledParticipantsCount||n.scaledParticipantsCount,participantsCount:Qt,consideredDate:p?.startDate,sex:x||n?.sex,rankingRange:d.rankingRange,uuids:d.uuids||g,ratingsParameters:u,participantType:q,gendersCount:Ft,idPrefix:Se,category:L}).participants;if(Q.category&&(Q.category.categoryName=k),p){let Vt=ln({participants:Oe,tournamentRecord:p});if(Vt.error)return Vt}if(Oe.forEach(({participantId:Vt})=>ot.push(Vt)),X=Oe,B===Lt){let Vt=ue[Zt]?Oe.filter(({participantType:He,person:Pn})=>He===It&&Pn?.sex===Zt).map(ft):[],_e=ue[ce]?Oe.filter(({participantType:He,person:Pn})=>He===It&&Pn?.sex===ce).map(ft):[],tr=Oe.filter(({participantType:He})=>He===It).map(ft).filter(He=>!Vt.includes(He)&&!_e.includes(He)),Re=Yt-(ue[Zt]+ue[ce]),Er=0,Te=0,Pe=0,dr=Z(0,Nt).map(He=>{let Pn=_e.slice(Er,Er+ue[ce]),Ii=Vt.slice(Te,Te+ue[Zt]),Gi=tr.slice(Pe,Pe+Re);return Er+=ue[ce],Te+=ue[Zt],Pe+=Re,{individualParticipantIds:[...Pn,...Ii,...Gi],participantOtherName:`TM${He+1}`,participantName:`Team ${He+1}`,participantRole:Fe,participantType:Lt,participantId:Mt()}}),Xo=ln({participants:dr,tournamentRecord:p});if(!Xo.success)return Xo;X=dr}}let dt=Nt=>{let{participantType:Qt}=Nt;return B===eo&&Qt===It||B===Vr&&Qt===pt?!0:B===Lt&&Qt===Lt},zt=Nt=>!d.gender||Nt.person?.sex===d.gender?!0:Nt.individualParticipantIds?.some(Qt=>{let Ft=X.find(Yt=>Yt.participantId===Qt);return Ft&&zt(Ft)}),Et=X.filter(dt).filter(zt).filter(({participantId:Nt})=>!r.includes(Nt)),ge=Et.slice(0,nt).map(Nt=>Nt.participantId);if(m&&ge?.length){let Nt=Wn({autoEntryPositions:s,entryStage:H,tournamentRecord:p,participantIds:ge,event:Q});if(Nt.error)return Nt}let Ee=$?Et.slice(nt,nt+$).map(Nt=>Nt.participantId):0;if(m&&Ee?.length){let Nt=0,Qt=1,Ft=(ue,Se)=>ue.stageSequence-Se.stageSequence,Yt=(ue,Se)=>ue.roundTarget-Se.roundTarget;for(let ue of E.sort(Yt)){Qt=ue.roundTarget||Qt;let Se=1,ur;for(let Oe of ue.structureProfiles.sort(Ft)){let _e=(Oe.drawSize||Zp(Oe.participantsCount))-(ur||0),tr=Ee.slice(Nt,Nt+_e),Re=Wn({entryStage:at,entryStageSequence:Se,autoEntryPositions:s,tournamentRecord:p,participantIds:tr,roundTarget:Qt,event:Q});if(Re.error)return Re;ur=Oe.qualifyingPositions,Nt+=_e,Se+=1}Qt+=1}}let Ce=h&&p?.participants?.filter(({participantId:Nt})=>!ge.includes(Nt)).filter(dt).filter(zt).slice(0,P||V-nt||A).map(Nt=>Nt.participantId);if(m&&Ce?.length){let Nt=Wn({participantIds:Ce,autoEntryPositions:!1,entryStatus:Or,tournamentRecord:p,event:Q});if(Nt.error)return Nt.error}let Xt=k||K;p&&O&&O<=ge.length&&Z(1,O+1).forEach((Qt,Ft)=>{let Yt={scaleName:Xt,scaleDate:l,scaleType:Sf,scaleValue:Qt,eventType:B},ue=ge[Ft];Oa({tournamentRecord:p,participantId:ue,scaleItem:Yt})});let Ue=Uu({...J(d,!1,!0),tournamentRecord:p,seedingScaleName:Xt,matchUpFormat:S,eventId:W,isMock:m,event:Q});if(Ue.error)return Ue;if(!Ue.drawDefinition)return{error:fr};let{drawDefinition:Ht}=Ue,Ie=Ht.drawId;if(Array.isArray(N)&&N.filter(hn).forEach(Nt=>gt({element:Ht,extension:Nt})),U){if(wp({drawDefinition:Ht,event:Q,suppressNotifications:!0}),d.withPlayoffs){let Qt=Ht.structures?.[0].structureId,Ft=Sp({...d.withPlayoffs,tournamentRecord:p,drawDefinition:Ht,structureId:Qt,idPrefix:F,isMock:m,event:Q});if(Ft?.error)return Ft}let Nt=d.automated===!1;if(m&&!Nt){let Qt=Ft=>{let Yt=Wd({completeAllMatchUps:Ft.completeAllMatchUps,completionGoal:Ft.completionGoal,matchUpStatusProfile:o,randomWinningSide:c,tournamentRecord:p,drawDefinition:Ht,matchUpFormat:S,event:Q});if(Yt.error)return Yt;let ue=Yt.completedCount;if(T===to){let Se=Ht.structures?.find(Vt=>Vt.stage===tt);if(!Se)return{error:_t};pc({structureId:Se.structureId,tournamentRecord:p,drawDefinition:Ht,event:Q});let ur=C?C-(ue??0):void 0,Oe=Wd({completionGoal:C?ur:void 0,matchUpStatusProfile:o,completeAllMatchUps:i,randomWinningSide:c,tournamentRecord:p,drawDefinition:Ht,matchUpFormat:S,event:Q});if(Oe.error)return Oe}};if(C&&Qt({completionGoal:C}),d.outcomes){let{matchUps:Ft}=ar({inContext:!0,drawDefinition:Ht,event:Q});for(let Yt of d.outcomes){let{matchUpStatus:ue=me,matchUpStatusCodes:Se,stageSequence:ur=1,matchUpIndex:Oe=0,structureOrder:Vt,matchUpFormat:_e,drawPositions:tr,roundPosition:Re,stage:Er=tt,roundNumber:Te,winningSide:Pe,scoreString:dr}=Yt,Xo=Ft?.reduce((fn,Dc)=>{let{structureId:ki,matchUpId:Hg}=Dc;return fn[ki]?fn[ki].push(Hg):fn[ki]=[Hg],fn},{})??[],He=Object.assign({},...Object.keys(Xo).map((fn,Dc)=>({[fn]:Dc+1}))),Ii=Ft?.filter(fn=>(!Er||fn.stage===Er)&&(!ur||fn.stageSequence===ur)&&(!Te||fn.roundNumber===Te)&&(!Re||fn.roundPosition===Re)&&(!Vt||He[fn.structureId]===Vt)&&(!tr||Wt(tr,fn.drawPositions).length===2))?.[Oe],Gi=pD({matchUpStatusCodes:Se,tournamentRecord:p,drawDefinition:Ht,targetMatchUp:Ii,matchUpFormat:_e,matchUpStatus:ue,scoreString:dr,winningSide:Pe});if(Gi?.error)return Gi}}i&&Qt({completeAllMatchUps:i})}w&&$s({tournamentRecord:p,event:Q})}else{let Nt=Lp({drawEntries:Ht.entries,drawName:_||T,qualifyingPositions:y,drawId:Ie,event:Q,stage:H});if(Nt.error)return Nt}return{...R,event:rt(Q),uniqueParticipantIds:ot,targetParticipants:X,drawDefinition:Ht,eventId:W,drawId:Ie}}var pV=["Mock Tournament","CourtHive Challenge","Racket Rally","Generated Tournament","Factory Follies","Open Competition"];function mD(t){let{tournamentAttributes:e,startDate:r,endDate:n}=t??{},{tournamentName:o=Rr(pV),ratingsParameters:i=Jr,scheduleCompletedMatchUps:s,tournamentExtensions:a,matchUpStatusProfile:c,completeAllMatchUps:u,participantsProfile:p,autoEntryPositions:m,hydrateCollections:d,randomWinningSide:l,policyDefinitions:f,schedulingProfile:g,periodLength:I,autoSchedule:h,eventProfiles:S,venueProfiles:T,drawProfiles:A,uuids:P}=t??{};if(r&&!Pr(r)||n&&!Pr(n))return{error:ir};if(S&&!Array.isArray(S))return{error:G};if(!r){let b=new Date;r=Kn(n??b),n=Kn(b.setDate(b.getDate()+7))}if(!n){let b=new Date(r);n=Kn(b.setDate(b.getDate()+7))}typeof e!="object"&&(e={});let y=eA({...e,tournamentName:o,isMock:!0,startDate:r,endDate:n});if(a?.length&&Array.isArray(a)){let b=a.filter(_=>hn({extension:_}));b?.length&&Object.assign(y,{extensions:b,isMock:!0})}if(typeof f=="object")for(let b of Object.keys(f))wi({policyDefinitions:{[b]:f[b]},tournamentRecord:y});let E=pA({participantsProfile:p,tournamentRecord:y,eventProfiles:S,drawProfiles:A,startDate:r,uuids:P});if(!E.success)return E;let U=[],M=[],N=[];if(Array.isArray(A)){let b=0;for(let _ of A){let L=Yp({allUniqueParticipantIds:U,matchUpStatusProfile:c,completeAllMatchUps:u,autoEntryPositions:m,hydrateCollections:d,participantsProfile:p,randomWinningSide:l,ratingsParameters:i,tournamentRecord:y,isMock:!0,drawProfile:_,startDate:r,drawIndex:b,uuids:P});if(L.error)return L;let{drawId:F,eventId:w,event:x,uniqueParticipantIds:H}=L;if(L=Sc({suppressNotifications:!1,internalUse:!0,tournamentRecord:y,event:x}),L.error)return L;F&&N.push(F),M.push(w),H?.length&&U.push(...H),b+=1}}if(S){let b=0;for(let _ of S){let L=TA({allUniqueParticipantIds:U,matchUpStatusProfile:c,participantsProfile:p,completeAllMatchUps:u,autoEntryPositions:m,hydrateCollections:d,randomWinningSide:l,ratingsParameters:i,tournamentRecord:y,eventProfile:_,eventIndex:b,startDate:r,uuids:P});if(L.error)return L;let{eventId:F,drawIds:w,uniqueParticipantIds:x}=L;w&&N.push(...w),M.push(F),x?.length&&U.push(...x),b+=1}}let C=T?.length?lA({tournamentRecord:y,venueProfiles:T,uuids:P}):[],D,O={};if(g){let b=Bv({schedulingProfile:g,tournamentRecord:y});if(b.error)return b;if(D=b.scheduledRounds,h){let{tournamentId:_}=y,L={[_]:y};O=jp({scheduleCompletedMatchUps:s,tournamentRecords:L,periodLength:I})}}return Ml(),rt({...R,tournamentRecord:y,scheduledRounds:D,schedulerResult:O,eventIds:M,venueIds:C,drawIds:N})}var gD={};ne(gD,{anonymizeTournamentRecord:()=>lD,modifyTournamentRecord:()=>fD});function lD({keepExtensions:t=[],anonymizeParticipantNames:e=!0,tournamentRecord:r,tournamentName:n,personIds:o=[],tournamentId:i}){if(!r)return{error:j};let s=Array.isArray(t)?iE.concat(...t):iE,a=x=>Array.isArray(t)?x?.extensions?.filter(H=>s.includes(H.name)):x?.extensions,c={};r.extensions=a(r);let u=i||Mt();c[r.tournamentId]=u,r.tournamentId=u,r.createdAt=new Date().toISOString(),r.tournamentName=n||`Anonymized: ${Kn(new Date)}`,r.isMock=!0,delete r.parentOrganisation;for(let x of r.participants||[]){let H=Mt();c[x.participantId]=H,x.participantId=H}for(let x of r.participants||[])Array.isArray(x.individualParticipantIds)&&(x.individualParticipantIds=x.individualParticipantIds.map(H=>c[H]));let p=0;for(let x of r.venues||[]){x.extensions=a(x),x.venueName=`Venue #${p}`,x.venueAbbreviation=`V${p}`;let H=Mt();c[x.venueId]=H,x.isMock=!0,p+=1}let m=1;for(let x of r.events||[]){x.extensions=a(x),x.isMock=!0;let H=Mt();c[x.eventId]=H,x.eventId=H;let V=x.category?.categoryName||x.category?.ageCategoryCode||x.category?.ratingType||x.gender;if(x.eventName=`Event ${m} ${V}`,Array.isArray(x.entries))for(let B of x.entries)B.participantId=c[B.participantId];for(let B of x.drawDefinitions||[]){B.extensions=a(B);let q=Mt();if(c[B.drawId]=q,B.drawId=q,B.isMock=!0,Array.isArray(B.entries))for(let k of B.entries)k.participantId=c[k.participantId];let Y=k=>{k.extensions=a(k);let K=Mt();c[k.structureId]=K,k.structureId=K;for(let X of k.positionAssignments||[])X.participantId&&(X.participantId=c[X.participantId]);for(let X of k.seedAssignments||[])X.participantId&&(X.participantId=c[X.participantId]);for(let X of k.matchUps||[]){X.isMock=!0;for(let $ of X.sides||[])$.lineUp&&($.lineUp=$.lineUp.map(({participantId:nt,collectionAssignments:Q})=>({participantId:c[nt],collectionAssignments:Q})))}};for(let k of B.structures||[])if(Y(k),Array.isArray(k.structures))for(let K of k.structures)Y(K);for(let k of B.links||[])k.source.structureId=c[k.source.structureId],k.target.structureId=c[k.target.structureId]}let{extension:W}=ut({name:Gr,element:x});Array.isArray(W?.value?.flights)&&W?.value.flights?.forEach(B=>{if(B.drawId=c[B.drawId],Array.isArray(B.drawEntries))for(let q of B.drawEntries)q.participantId=c[q.participantId]}),m+=1}let d=r.startDate||Kn(new Date),l=(r.participants||[]).filter(({participantType:x})=>x===It),f=l.reduce((x,H)=>{let V=H.person?.sex;return[Zt,ce].includes(V)?x[V]+=1:x[Ia]+=1,x},{[Zt]:0,[ce]:0,[Ia]:0}),g=Object.assign({},...Object.keys(f).map(x=>({[x]:aA({category:{ageCategoryCode:"O18"},count:f[x],addressProps:{citiesCount:10},personExtensions:[],consideredDate:d,sex:x})?.persons||[]}))),I={[Zt]:0,[ce]:0,[Ia]:0},h=l.length,S=l.reduce((x,H)=>{let V=H.person?.addresses?.[0]||{},{city:W,state:B,postalCode:q}=V;return x.cities.includes(W)||x.cities.push(W),x.states.includes(B)||x.states.push(B),x.postalCodes.includes(q)||x.postalCodes.push(q),x},{cities:[],postalCodes:[],states:[]}),T=S.postalCodes.length,A=S.cities.length,P=S.states.length,{cities:y}=rA({count:A||h,participantsCount:h}),{states:E}=nA({count:P||h,participantsCount:h}),{postalCodes:U}=oA({count:T||h,participantsCount:h}),M={cities:y,states:E,postalCodes:U};l.forEach((x,H)=>{let V=x?.person,W=V?.sex||Ia,B=At(V?.birthDate)?.split("-")[0],q=I[W],Y=g[W][q];if(I[W]+=1,B){let[,k,K]=Y?.birthDate?.split("-")||[],X=[B,k,K].join("-");Y.birthDate=X}if(V?.addresses){let k=iA({...M,participantIndex:H,nationalityCode:Y.nationalityCode});Y.addresses=[k]}Y.personId=o?.[H]||Mt(),e?(Y.standardFamilyName=Y.lastName,Y.standardGivenName=Y.firstName,x.participantName=`${Y.standardGivenName} ${Y.standardFamilyName}`):(Y.standardFamilyName=V?.standardFamilyName,Y.standardGivenName=V?.standardGivenName),delete Y.firstName,delete Y.lastName,Y.extensions=a(V),x.person=Y,c[V?.personId]=Y.personId}),(r.participants||[]).filter(({participantType:x})=>x===pt).forEach(x=>{let{individualParticipantIds:H}=x;x.participantName=mV({individualParticipantIds:H,individualParticipants:l})});let C=(r.participants||[]).filter(({participantType:x})=>x===Lt),D=C.length,O=Rg({count:D}).names;C.forEach((x,H)=>{x.participantName=O[H]});let b=(r.participants||[]).filter(({participantType:x})=>x===hr),_=b.length,L=Rg({count:_,nameRoot:"Group"}).names;b.forEach((x,H)=>{x.participantName=L[H]});let{extension:F}=ut({element:r,name:ca});Array.isArray(F?.value)&&F?.value.forEach(x=>{x.tournamentId=c[x.tournamentId],x.structureId=c[x.structureId],x.eventId=c[x.eventId],x.drawId=c[x.drawId]});let{extension:w}=ut({element:r,name:aa});return Array.isArray(w?.value)&&w?.value.forEach(x=>{x.personId=c[x.personId]}),{...R}}function mV({individualParticipantIds:t,individualParticipants:e}){let r=e.filter(({participantId:n})=>t.includes(n)).map(({person:n})=>n?.standardFamilyName).filter(Boolean).sort().join("/");return t.length===1&&(r+="/Unknown"),r}function fD(t){let{ratingsParameters:e=Jr,participantsProfile:r={},matchUpStatusProfile:n,completeAllMatchUps:o,autoEntryPositions:i,hydrateCollections:s,randomWinningSide:a,schedulingProfile:c,tournamentRecord:u,eventProfiles:p,periodLength:m,venueProfiles:d,autoSchedule:l,drawProfiles:f,uuids:g}=t;if(!u)return{error:j};let I=[],h=[],S=[];p?.forEach(M=>{let N=u.events?.find((C,D)=>M.eventIndex!==void 0&&D===M.eventIndex||M.eventName&&C.eventName===M.eventName||M.eventId&&C.eventId===M.eventId);N?.gender&&(M.gender=N.gender)});let T=u.participants?.length||void 0;T&&r?.idPrefix&&(r.idPrefix=`${r.idPrefix}-${T}`);let A=pA({startDate:u.startDate,participantsProfile:r,tournamentRecord:u,eventProfiles:p,drawProfiles:f,uuids:g});if(!A.success)return A;if(p){let M=u.events?.length||0;for(let N of p){let{ratingsParameters:C}=N,D=u.events?.find((O,b)=>N.eventIndex!==void 0&&b===N.eventIndex||N.eventName&&O.eventName===N.eventName||N.eventId&&O.eventId===N.eventId);if(D){let{gender:O,category:b,eventType:_}=D,{drawProfiles:L,publish:F}=N,w=_===eo&&It||_===Vr&&pt||_;if(L){let{stageParticipantsCount:x,uniqueParticipantsCount:H,uniqueParticipantStages:V}=fA({drawProfiles:L,category:b,gender:O}),{uniqueDrawParticipants:W=[],uniqueParticipantIds:B=[]}=V?hA({event:{eventType:_,category:b,gender:O},uniqueParticipantsCount:H,participantsProfile:r,ratingsParameters:C,tournamentRecord:u,eventProfile:N,uuids:g}):{};I.push(...B);let{stageParticipants:q}=gA({targetParticipants:u.participants||[],allUniqueParticipantIds:I,stageParticipantsCount:x,eventParticipantType:w}),Y=SA({uniqueDrawParticipants:W,autoEntryPositions:i,stageParticipants:q,tournamentRecord:u,drawProfiles:L,category:b,gender:O,event:D});if(Y.error||(Y=IA({matchUpStatusProfile:n,completeAllMatchUps:o,randomWinningSide:a,tournamentRecord:u,drawProfiles:L,event:D}),Y.error))return Y;S.push(...Y.drawIds)}F&&$s({tournamentRecord:u,event:D})}else{let O=TA({startDate:u.startDate,allUniqueParticipantIds:I,matchUpStatusProfile:n,participantsProfile:r,completeAllMatchUps:o,autoEntryPositions:i,randomWinningSide:a,ratingsParameters:C,tournamentRecord:u,eventProfile:N,eventIndex:M,uuids:g});if(O.error)return O;let{eventId:b,drawIds:_,uniqueParticipantIds:L}=O;_&&S.push(..._),h.push(b),L?.length&&I.push(...L),M+=1}}}if(f){let M=(u.events||[]).map(N=>N.drawDefinitions?.map(()=>1)||[]).flat().reduce((N,C)=>N+C,0);for(let N of f){let C=Yp({startDate:u.startDate,allUniqueParticipantIds:I,matchUpStatusProfile:n,participantsProfile:r,completeAllMatchUps:o,autoEntryPositions:i,hydrateCollections:s,randomWinningSide:a,ratingsParameters:e,tournamentRecord:u,drawProfile:N,drawIndex:M,uuids:g});if(C.error)return C;let{drawId:D,eventId:O,event:b,uniqueParticipantIds:_}=C;if(C=Sc({tournamentRecord:u,event:b,internalUse:!0}),C.error)return C;D&&S.push(D),h.push(O),_?.length&&I.push(..._),M+=1}}let P=d?.length?lA({tournamentRecord:u,venueProfiles:d}):[],y,E={};if(c?.length){let M={[u.tournamentId]:u},N=Ic({tournamentRecords:M,schedulingProfile:c});if(N.error)return N;if(l){let{tournamentId:C}=u,D={[C]:u};E=jp({tournamentRecords:D,periodLength:m})}}return{totalParticipantsCount:u.participants.length,scheduledRounds:y,schedulerResult:E,...R,eventIds:h,venueIds:P,drawIds:S}}var wD={};ne(wD,{addIndividualParticipantIds:()=>Gp,addParticipant:()=>dn,addParticipants:()=>ln,addPenalty:()=>_D,addPersonRequests:()=>SD,addPersons:()=>vD,createGroupParticipant:()=>ND,createTeamsFromParticipantAttributes:()=>Cg,deleteParticipants:()=>Oi,filterParticipants:()=>iu,findParticipant:()=>PD,getCompetitionParticipants:()=>yS,getPairedParticipant:()=>zr,getParticipantEventDetails:()=>ES,getParticipantMembership:()=>US,getParticipantScaleItem:()=>gc,getParticipantSchedules:()=>PS,getParticipantSignInStatus:()=>NS,getParticipantTimeItem:()=>lh,getParticipants:()=>$t,getScaleValues:()=>oa,mergeParticipants:()=>OD,modifyIndividualParticipantIds:()=>TD,modifyParticipant:()=>kp,modifyParticipantName:()=>DD,modifyParticipantOtherName:()=>yD,modifyParticipantsSignInStatus:()=>AD,modifyPenalty:()=>RD,modifyPersonRequests:()=>ID,mutate:()=>xD,participantScaleItem:()=>no,query:()=>nP,regenerateParticipantNames:()=>UD,removeIndividualParticipantIds:()=>bf,removeParticipantIdsFromAllTeams:()=>mp,removePenalty:()=>CD,removePersonRequests:()=>hD,scaledTeamAssignment:()=>MD,setParticipantScaleItem:()=>Oa,setParticipantScaleItems:()=>uD,validateLineUp:()=>Hm});var xD={};ne(xD,{addIndividualParticipantIds:()=>Gp,addParticipant:()=>dn,addParticipants:()=>ln,addPenalty:()=>_D,addPersonRequests:()=>SD,addPersons:()=>vD,createGroupParticipant:()=>ND,createTeamsFromParticipantAttributes:()=>Cg,deleteParticipants:()=>Oi,findParticipant:()=>PD,mergeParticipants:()=>OD,modifyIndividualParticipantIds:()=>TD,modifyParticipant:()=>kp,modifyParticipantName:()=>DD,modifyParticipantOtherName:()=>yD,modifyParticipantsSignInStatus:()=>AD,modifyPenalty:()=>RD,modifyPersonRequests:()=>ID,regenerateParticipantNames:()=>UD,removeIndividualParticipantIds:()=>bf,removeParticipantIdsFromAllTeams:()=>mp,removePenalty:()=>CD,removePersonRequests:()=>hD,scaledTeamAssignment:()=>MD,setParticipantScaleItem:()=>Oa,setParticipantScaleItems:()=>uD});function AA(t=0){(typeof t!="number"||isNaN(t))&&(t=0);let e=new Date;return e.setHours(e.getHours()+t),e.getTime().toString(36).slice(-6).toUpperCase()}function yA({personRequests:t,personId:e,requests:r}){t[e]||(t[e]=[]);let n=r.filter(({requestType:o})=>o).map(o=>{let{date:i,startTime:s,endTime:a}=o;return o.requestType===Ec&&(i=At(i),s=qt(s),a=qt(a),i&&s&&a)?{date:i,startTime:s,endTime:a,requestType:o.requestType}:o}).filter(Boolean);for(let o of n)o.requestId=AA(),t[e].push(o);return{mergeCount:n.length}}function jd(t){let{tournamentRecords:e,personRequests:r}=t,n=vt(t,[{[ye]:!0}]);if(n.error)return n;if(!r)return{...R};let o=Object.values(e);for(let i of o){let s=i.participants??[],a=[];for(let c of Object.keys(r))if(Uo({tournamentParticipants:s,personId:c})){let u=r[c];u.length&&a.push({personId:c,requests:u})}Object.keys(a).length&&gt({element:i,extension:{value:a,name:aa}})}return{...R}}function ID(t){let{tournamentRecords:e,requests:r,personId:n}=t,o=vt(t,[{[ye]:!0},{requests:!0,[na]:an,[Ni]:G}]);if(o.error)return o;let i=r.map(({requestId:u})=>u).filter(Boolean),{personRequests:s}=gi({tournamentRecords:e}),a=u=>{s&&(s[u]=s[u].map(p=>{if(!i.includes(p.requestId))return p;let m=r.find(d=>d.requestId===p.requestId);if(m.requestType)return Object.assign(p,m)}).filter(Boolean))};if(n&&s?.[n])a(n);else if(s)for(let u of Object.keys(s))a(u);let c=r.filter(u=>!u.requestId);return c.length&&yA({personRequests:s,personId:n,requests:c}),jd({tournamentRecords:e,personRequests:s})}function hD(t){let{tournamentRecords:e,requestType:r,requestId:n,personId:o,date:i}=t,s=vt(t,[{[ye]:!0}]);if(s.error)return s;let{personRequests:a}=gi({tournamentRecords:e}),c=p=>{a&&(a[p]=a[p].filter(m=>(!r||m.requestType!==r)&&(!n||m.requestId!==n)&&(!i||m.date!==i)),a?.[p]?.length||delete a[p])},u=!r&&!n&&!o&&!i;if(!u){if(o&&a?.[o])c(o);else if(a)for(let p of Object.keys(a))c(p)}return u||!a||!Object.keys(a).length?rr({name:aa,tournamentRecords:e,discover:!0}):jd({tournamentRecords:e,personRequests:a})}function SD(t){let{tournamentRecords:e,personId:r,requests:n}=t,o=vt(t,[{[ye]:!0,[EC]:!0},{requests:!0,[na]:an,[Ni]:G}]);if(o.error)return o;let{personRequests:i}=gi({tournamentRecords:e}),{mergeCount:s}=yA({personRequests:i,personId:r,requests:n});return s&&i?jd({tournamentRecords:e,personRequests:i}):{error:G}}function TD({individualParticipantIds:t,groupingParticipantId:e,tournamentRecord:r}){let n="modifyIndividualParticipantIds";if(!r)return v({result:{error:j},stack:n});if(!e||!t)return v({result:{error:et},stack:n});let o=r.participants||[],i=o.find(l=>l.participantId===e);if(!i)return v({result:{error:Jt},stack:n});if(![Lt,hr].includes(i.participantType))return v({result:{error:tn},context:{participantType:i.participantType},stack:n});let s=t.filter(l=>o.find(g=>g.participantId===l)?.participantType!==It);if(s.length)return v({result:{error:Hr,invalidParticipantIds:s},stack:n});let a=i.individualParticipantIds||[],c=t.filter(l=>!a.includes(l)),u=a.filter(l=>!t.includes(l)),p=Gp({individualParticipantIds:c,groupingParticipantId:e,tournamentRecord:r});if(p.error)return v({result:p,stack:n});let m=bf({individualParticipantIds:u,groupingParticipantId:e,tournamentRecord:r});if(m.error)return v({result:m,stack:n});let{topics:d}=Fr();if(d.includes($e)){let l=o.find(({participantId:f})=>f===e);Tt({topic:$e,payload:{tournamentId:r.tournamentId,participants:[l]}})}return{...p,...m}}function AD({tournamentRecord:t,participantIds:e,signInState:r}){if(!t)return{error:j};if(!Array.isArray(e))return{error:et};if(![Kc,bE].includes(r))return{error:G,signInState:r};let o=t.participants||[];if(!o.length)return{error:Ba};let i=o.map(ft),s=e.filter(p=>!i.includes(p));if(s.length)return{error:G,context:{invalidParticipantIds:s}};let a=[],c=new Date().toISOString();for(let p of o){let{participantId:m}=p;if(e.includes(m)){let l=Vf({duplicateValues:!1,tournamentRecord:t,participantId:m,timeItem:{itemType:Ja,itemValue:r,createdAt:c}});if(l.error)return l;a.push(p)}}let{topics:u}=Fr();return a.length&&u.includes($e)&&Tt({topic:$e,payload:{tournamentId:t.tournamentId,participants:a}}),{...R}}function yD({tournamentRecord:t,participantId:e,participantOtherName:r}){if(!t)return{error:j};if(!e)return{error:te};let{participant:n}=Mo({tournamentRecord:t,participantId:e});if(!n)return{error:Jt};n.participantOtherName=r;let{topics:o}=Fr();return o.includes($e)&&Tt({topic:$e,payload:{tournamentId:t.tournamentId,participants:[n]}}),{...R}}function ED({personFormat:t,person:e}){let r=g=>g.replace(/\W/g,""),n=g=>/^[a-z]*$/.test(r(g)),o=g=>/^[A-Z]*$/.test(r(g)),i=g=>/^[LAST]{4}/.test(r(g)),s=g=>g.toLowerCase().indexOf("l")<g.toLowerCase().indexOf("f"),a=g=>g.indexOf(",")>=0,c=g=>g.toLowerCase().indexOf("f.")>=0,u=g=>g.toLowerCase().indexOf("f")<0,p=g=>g.indexOf(" ")>0;if(!e)return;let m=p(t)?" ":"",d=yh(e?.standardGivenName??""),l=yh(e?.standardFamilyName??"");if(!t)return`${d}${m}${l}`;c(t)&&!a(t)&&!s(t)&&(d=`${d[0]}.`),n(t)?(d=d.toLowerCase(),l=l.toLowerCase()):o(t)?(d=d.toUpperCase(),l=l.toUpperCase()):i(t)&&(l=l.toUpperCase());let f=`${d}${m}${l}`;return u(t)?f=l:s(t)&&(a(t)?f=`${l},${m}${d}`:f=`${l}${m}${d}`),f}function Hv({participantMap:t,participant:e,formats:r}){let{participantType:n,individualParticipantIds:o,person:i}=e,s=n&&r[n];if(n!==Yr&&s){let{personFormat:a,doublesJoiner:c}=s;n===It&&(e.participantName=ED({person:i,personFormat:a})),n===pt&&(e.participantName=o?.map(u=>{let p=t[u]?.person;return ED({person:p,personFormat:a})}).filter(Boolean).join(c??"/"))}}function UD({tournamentRecord:t,formats:e}){if(!t)return{error:j};if(!Ct(e))return{error:et};let r=t.participants??[],n=AI(r,"participantId");for(let o of r)Hv({participant:o,participantMap:n,formats:e});return{...R}}function PD(t){let{tournamentRecord:e,policyDefinitions:r,contextProfile:n,participantId:o,personId:i}=t,s=t.tournamentRecords||e&&{[e.tournamentId]:e}||{};if(typeof o!="string"&&typeof i!="string")return{error:et,stack:"publicFindParticipant"};let a,c;for(let u of Object.values(s)){c=u.tournamentId;let p=u.participants||[];if(a=Uo({tournamentParticipants:p,internalUse:!0,policyDefinitions:r,contextProfile:n,participantId:o,personId:i}),a)break}return{participant:a,tournamentId:c,...R}}function ND({individualParticipantIds:t=[],participantRoleResponsibilities:e,participantRole:r=ZE,tournamentRecord:n,participantId:o,groupName:i}){if(!n)return{error:j};if(!i)return{error:et,info:"Missing groupName"};if(!Array.isArray(t))return{info:"Invalid individualParticipantIds",error:G};let a=($t({participantFilters:{participantTypes:[It]},tournamentRecord:n}).participants??[]).map(m=>m.participantId);for(let m of t)if(!a.includes(m))return{error:tn,participantId:m};let c=rt({participantId:o||Mt(),participantRoleResponsibilities:e,participantName:i,individualParticipantIds:t,participantType:hr,participantRole:r}),u=dn({participant:c,tournamentRecord:n});if(u.error)return u;let{topics:p}=Fr();return p.includes(Go)&&Tt({topic:Go,payload:{tournamentId:n.tournamentId,participants:[c]}}),{...R,participant:J(c)}}function DD({tournamentRecord:t,participantName:e,participantId:r}){if(!t)return{error:j};if(!r)return{error:te};if(!e)return{error:et,info:"Missing participantName"};let{participant:n}=Mo({tournamentRecord:t,participantId:r});if(!n)return{error:Jt};n.participantName=e;let{topics:o}=Fr();return o.includes($e)&&Tt({topic:$e,payload:{tournamentId:t.tournamentId,participants:[n]}}),{...R}}function MD({clearExistingAssignments:t=!0,individualParticipantIds:e,reverseAssignmentOrder:r,initialTeamIndex:n=0,scaledParticipants:o=[],teamParticipantIds:i,tournamentRecord:s,scaleAttributes:a,teamNameBase:c,teamsCount:u,eventId:p,event:m}){if(!s)return{error:j};if(!Array.isArray(i)&&!lt(u)&&!p||!lt(n)||o&&!Array.isArray(o)||a&&(typeof a!="object"||!Object.keys(a).length))return{error:G};if(!a&&!o.length||!o&&!(e&&a))return{error:et,info:"Missing scaling details"};if(p&&!i){if(m?.eventType!==Kr)return{error:yo};i=m?.entries?.filter(({entryStatus:h})=>h===qr).map(ft)}if(!i?.length&&!u)return{info:"Missing teamParticipantIds or teamsCount",error:et};let d=e??o.map(({participantId:h})=>h);r&&(i?.reverse(),n+=1),n>(i?.length||0)-1&&(n=0);let l=i?.slice(n).concat(...i.slice(0,n))??[],f=[];for(let h of s.participants??[]){let{participantId:S,participantType:T}=h;if(l.includes(S)){if(T!==Yr)return{error:tn,participant:h};f.push(h)}}if(u&&f.length<u){let h=u-(f?.length||0),S=c??"Team",T=Z(0,h).map(E=>({participantName:`${S} ${E+1}`,participantType:Yr,participantRole:Fe})),{participants:A=[]}=ln({participants:T,returnParticipants:!0,tournamentRecord:s}),P=A.map(ft),y=s.participants?.filter(({participantId:E})=>P.includes(E))??[];f.push(...y)}if(!f.length)return{error:Tl};if(t)for(let h of f)h.individualParticipantIds=[];else{let h=f.map(S=>S).flat();e?.length?d=d.filter(S=>!h.includes(S)):o=o?.filter(({participantId:S})=>!h.includes(S))}if(!e?.length&&!o?.length)return{error:Gu,info:"Nothing to be done"};if(!o.length){for(let h of s.participants??[]){let{participantId:S,participantType:T}=h;if(!d.includes(S))continue;if(T!==It)return{error:tn,participant:h};let A=no({scaleAttributes:a,participant:h})?.scaleItem,P=a?.accessor?A?.scaleValue?.[a?.accessor]:A?.scaleValue,y={participantId:S,scaleValue:P};o.push(y)}if(!o.length)return{error:Jt}}o.sort((h,S)=>a?.sortOrder?(S?.scaleValue||0)-(h?.scaleValue||0):(h?.scaleValue||1/0)-(S?.scaleValue||1/0));for(let h of o)if(!h.participantId)return{error:G,scaledParticipant:h};let g=0;for(;g<o.length;){for(let h of f){if(g+1>o.length)break;let S=o[g];h.individualParticipantIds.push(S.participantId),g++}f.reverse()}let I=f.map(ft);for(let h of s.events??[]){if(h.eventType!==Kr)continue;let S=(h.entries??[]).filter(T=>I.includes(T.participantId));for(let T of S){let A=T.participantId,y=f.find(U=>U.participantId===A)?.individualParticipantIds;h.entries=(h.entries??[]).filter(U=>!y.includes(U.participantId)),(h.drawDefinitions??[]).forEach(U=>{U.entries=(U.entries??[]).filter(M=>!y.includes(M.participantId))});let{flightProfile:E}=kt({event:h});(E?.flights||[]).forEach(U=>{U.drawEntries=(U.drawEntries||[]).filter(M=>!y.includes(M.participantId))})}}return{...R,scaledParticipants:o}}function CD(t){let{tournamentRecords:e}=t;if(typeof e!="object"||!Object.keys(e).length)return{error:wt};for(let r of Object.values(e)){let n=dV({...t,tournamentRecord:r});if(n.error&&n.error!==Cc)return n}return{...R}}function dV({tournamentRecord:t,penaltyId:e}){if(!t)return{error:j};if(!e)return{error:fl};let r=t?.participants??[],n=[],o=!1,i;return r.forEach(s=>{let a=!1;s.penalties=(s.penalties??[]).filter(c=>(c.penaltyId===e&&(a=!0,o||(i=c,o=!0)),a&&n.push(s),c.penaltyId!==e))}),i&&Tt({topic:$e,payload:{tournamentId:t.tournamentId,participants:n}}),i?{...R,penalty:i}:{error:Cc}}var lV=({penaltyId:t=Mt()}={})=>({refereeParticipantId:void 0,penaltyCode:void 0,penaltyType:void 0,extensions:void 0,matchUpId:void 0,createdAt:void 0,issuedAt:void 0,notes:void 0,penaltyId:t}),EA=lV;function RD(t){let{tournamentRecords:e}=t;if(typeof e!="object"||!Object.keys(e).length)return{error:wt};for(let r of Object.values(e)){let n=fV({...t,tournamentRecord:r});if(n.error&&n.error!==Cc||n.success)return n}return{error:Cc}}function fV({tournamentRecord:t,modifications:e,penaltyId:r}){if(!t)return{error:j};if(!e)return{error:G,modifications:e};if(!r)return{error:fl};let n=t?.participants??[],o=Object.keys(EA()).filter(c=>c!=="penaltyId"),i=Object.keys(e).filter(c=>o.includes(c));if(!i.length)return{error:ku};let s,a=[];return n.forEach(c=>{let u=!1;c.penalties=(c.penalties??[]).map(p=>(p.penaltyId===r&&(u=!0,i.forEach(m=>Object.assign(p,{[m]:e[m]})),s||(s=p)),p)),u&&a.push(c)}),s&&Tt({topic:$e,payload:{tournamentId:t.tournamentId,participants:a}}),s?{...R,penalty:s}:{error:Cc}}function bD(t,e,r){return!t&&e?e:t&&!e||typeof t!="object"||typeof e!="object"?t:mt(Object.keys(t).concat(Object.keys(e))).reduce((o,i)=>{if(!e[i])o[i]=t[i];else if(!t[i])o[i]=e[i];else if(typeof t[i]!=typeof e[i])o[i]=e[i];else if(Array.isArray(t[i]))if(r===!0||Array.isArray(r)&&r.includes(i)){let s=mt(t[i].map(a=>JSON.stringify(a)).concat(e[i].map(a=>JSON.stringify(a)))).map(a=>JSON.parse(a));o[i]=s}else o[i]=e[i];else typeof t[i]=="object"?o[i]=bD(t[i],e[i],r):o[i]=e[i];return o},{})}function OD({participants:t=[],tournamentRecord:e,arraysToMerge:r}){if(!e)return{error:j};e.participants||(e.participants=[]);let n=t.filter(Dr(zn)).map(u=>({[u.participantId]:u})),o=Object.assign({},...n),i=[];e.participants=e.participants.map(u=>{if(o[u.participantId]){let p=bD(u,o[u.participantId],r);return i.push(p),p}return u});let s=e.participants.map(Dr(zn))||[],a=t.filter(({participantId:u})=>!s.includes(u)),{topics:c}=Fr();return a.length&&(e.participants=e.participants.concat(...a),c.includes(Go)&&Tt({topic:Go,payload:{participants:a}})),i.length&&c.includes($e)&&Tt({topic:$e,payload:{tournamentId:e.tournamentId,participants:i}}),{modifiedParticipantsCount:i.length,newParticipantsCount:a.length,...R}}function _D(t){let{tournamentRecord:e,participantIds:r}=t,n=t.tournamentRecords??(e&&{[e.tournamentId]:e})??{},o;for(let i of Object.values(n)){let a=($t({tournamentRecord:i}).participants??[])?.map(ft).filter(c=>r.includes(c));a.length&&(o=gV({...t,penaltyId:t.penaltyId??o,tournamentRecord:i,participantIds:a}).penaltyId)}return o?{...R,penaltyId:o}:{error:Jt}}function gV({refereeParticipantId:t,tournamentRecord:e,participantIds:r,penaltyCode:n,penaltyType:o,extensions:i,penaltyId:s,matchUpId:a,issuedAt:c,notes:u}){if(!e)return{error:j};if(!r)return{error:te};if(!o)return{error:Ty};let m=(e?.participants??[]).filter(f=>r.includes(f.participantId));if(!m.length)return{error:Jt};let d=new Date().toISOString(),l=Object.assign(EA({penaltyId:s}),{refereeParticipantId:t,penaltyCode:n,penaltyType:o,matchUpId:a,notes:u,issuedAt:c,createdAt:d});return Array.isArray(i)&&i.forEach(f=>gt({element:l,extension:f})),m.forEach(f=>{f.penalties||(f.penalties=[]),f.penalties.push(l)}),Tt({topic:$e,payload:{tournamentId:e.tournamentId,participants:m}}),{...R,penaltyId:l.penaltyId}}function vD({participantRole:t=Fe,tournamentRecord:e,persons:r}){if(!e)return{error:j};if(!Array.isArray(r))return{error:G};if(!Object.keys(Gm).includes(t))return{error:uy};let n=(e.participants||[]).map(({person:f})=>f?.personId).filter(Boolean),o=[],i=r.filter(f=>f&&(!f.personId||!n.includes(f.personId))).map(f=>(f.personId||(f.personId=Mt()),o.push(f.personId),f)),s=(f,g)=>Object.assign({},...Object.keys(f).filter(I=>!g.includes(I)).map(I=>({[I]:f[I]}))),a=i.map(f=>rt({extensions:f.participantExtensions,timeItems:f.participantTimeItems,participantType:It,participantRole:t,person:s(f,["participantExtensions","participantTimeItems","pairedPersons"])})),c=0,u=0,p=ln({participants:a,tournamentRecord:e});if(p.error)return p;u=p.addedCount||0;let m=[],d=$t({participantFilters:{participantTypes:[It]},tournamentRecord:e})?.participants??[];if(t===Fe&&r.filter(({pairedPersons:f})=>f).forEach(({personId:f,pairedPersons:g})=>{Array.isArray(g)&&g.forEach(I=>{let h=[f,I.personId].map(S=>Uo({tournamentParticipants:d,personId:S})).filter(Boolean);if(h.length===2){let S=h.map(ft);m.push(rt({extensions:I.participantExtensions,timeItems:I.timeItems,participantRole:Fe,individualParticipantIds:S,participantType:pt}))}})}),m.length){if(p=ln({participants:m,tournamentRecord:e}),p.error)return p;c=p.addedCount||0}let l=u+c;return{...R,addedCount:l,newPersonIds:o}}var jD={};ne(jD,{bulkUpdatePublishedEventIds:()=>Rp,getAllEventData:()=>HD,getCourtInfo:()=>yf,getDrawData:()=>fg,getEventData:()=>gg,getEventPublishStatus:()=>Qr,getPublishState:()=>up,getTournamentPublishStatus:()=>Cf,getVenueData:()=>tu,mutate:()=>BD,publishEvent:()=>$s,publishEventSeeding:()=>LD,publishOrderOfPlay:()=>kD,query:()=>WD,setEventDisplay:()=>Od,unPublishEvent:()=>VD,unPublishEventSeeding:()=>FD,unPublishOrderOfPlay:()=>GD});var BD={};ne(BD,{publishEvent:()=>$s,publishEventSeeding:()=>LD,publishOrderOfPlay:()=>kD,setEventDisplay:()=>Od,unPublishEvent:()=>VD,unPublishEventSeeding:()=>FD,unPublishOrderOfPlay:()=>GD});function LD({removePriorValues:t=!0,stageSeedingScaleNames:e,seedingScaleNames:r,tournamentRecord:n,status:o=$r,drawIds:i=[],event:s}){if(!n)return{error:j};if(!s)return{error:St};let a=Qr({event:s,status:o}),c=(a?.seeding?.seedingScaleNames||r)&&{...a?.seeding?.seedingScaleNames,...r},u=(a?.seeding?.stageSeedingScaleNames||e)&&{...a?.seeding?.stageSeedingScaleNames,...e},p=rt({stageSeedingScaleNames:u,seedingScaleNames:c,published:!0,drawIds:i});return qs({statusObject:{seeding:p},removePriorValues:t,status:o,event:s}),Tt({topic:ME,payload:{tournamentId:n.tournamentId,eventId:s.eventId,drawIds:i}}),{...R}}function FD({removePriorValues:t=!0,seedingScaleNames:e,tournamentRecord:r,status:n=$r,drawIds:o,stages:i,event:s}){if(!r)return{error:j};if(!s)return{error:St};let a=Qr({event:s});if(a){let c=a.seeding;if(Array.isArray(i)&&c.stageSeedingScaleNames)for(let u of i)c.stageSeedingScaleNames[u]&&delete c.stageSeedingScaleNames[u];Array.isArray(e)&&c?.seedingScaleNames&&(c.seedingScaleNames=c.seedingScaleNames.filter(u=>!e.includes(u))),Array.isArray(o)&&c?.drawIds&&(c.drawIds=c.drawIds.filter(u=>!o.includes(u))),(!Object.values(c.stageSeedingScaleNames??{}).length&&!c.seedingScaleNames?.length&&!c.drawIds?.length||!i&&!e&&!o?.length)&&(delete c.stageSeedingScaleNames,delete c.seedingScaleNames,delete c.drawIds,c.published=!1),qs({statusObject:{seeding:c},removePriorValues:t,status:n,event:s})}return Tt({topic:sf,payload:{tournamentId:r.tournamentId,eventId:s.eventId}}),{...R}}function GD(t){let e=t?.tournamentRecords??(t?.tournamentRecord&&{[t.tournamentRecord.tournamentId]:t.tournamentRecord})??{};if(!Object.keys(e).length)return{error:wt};for(let r of Object.values(e)){let n=IV({tournamentRecord:r,...t});if(n.error)return n}return{...R}}function IV({removePriorValues:t=!0,tournamentRecord:e,status:r=$r}){if(!e)return{error:j};let n=`${Ho}.${Wo}`,{timeItem:o}=_n({element:e,itemType:n}),i=o?.itemValue||{[r]:{}};return i[r]&&delete i[r].orderOfPlay,li({timeItem:{itemValue:i,itemType:n},element:e,removePriorValues:t}),Tt({topic:af,payload:{tournamentId:e.tournamentId}}),{...R}}function kD(t){let e=jr(t);if(!Object.keys(e).length)return{error:wt};for(let r of Object.values(e)){let n=hV({tournamentRecord:r,...t});if(n.error)return n}return{...R}}function hV({scheduledDates:t=[],removePriorValues:e,tournamentRecord:r,status:n=$r,eventIds:o=[]}){if(!r)return{error:j};let i=`${Ho}.${Wo}`,{timeItem:s}=_n({element:r,itemType:i}),a=s?.itemValue||{[n]:{}};return a[n].orderOfPlay={published:!0,scheduledDates:t,eventIds:o},li({timeItem:{itemValue:a,itemType:i},element:r,removePriorValues:e}),Tt({topic:CE,payload:{tournamentId:r.tournamentId,scheduledDates:t,eventIds:o}}),{...R}}function VD({removePriorValues:t=!0,tournamentRecord:e,status:r=$r,event:n}){if(!e)return{error:j};if(!n)return{error:St};let o=`${Ho}.${Wo}`,{timeItem:i}=ru({itemType:o,event:n}),s=i?.itemValue||{[r]:{}};return delete s[r].structureIds,delete s[r].drawDetails,delete s[r].drawIds,xi({event:n,timeItem:{itemValue:s,itemType:o},removePriorValues:t}),qs({statusObject:{structureIds:void 0,drawIds:void 0,seeding:void 0},removePriorValues:t,status:r,event:n}),Tt({topic:of,payload:{tournamentId:e.tournamentId,eventId:n.eventId}}),{eventId:n.eventId,...R}}var WD={};ne(WD,{bulkUpdatePublishedEventIds:()=>Rp,getAllEventData:()=>HD,getCourtInfo:()=>yf,getDrawData:()=>fg,getEventData:()=>gg,getEventPublishStatus:()=>Qr,getPublishState:()=>up,getTournamentPublishStatus:()=>Cf,getVenueData:()=>tu});function HD({tournamentRecord:t,policyDefinitions:e}){if(!t)return{error:j};let r=t.events||[],n=t?.participants||[],{tournamentInfo:o}=us({tournamentRecord:t}),{venues:i}=oo({tournamentRecord:t}),s=r.map(c=>{let{eventId:u}=c,p=(({eventId:f,eventName:g,eventType:I,eventLevel:h,surfaceCategory:S,matchUpFormat:T,category:A,gender:P,startDate:y,endDate:E,ballType:U,discipline:M})=>({eventId:f,eventName:g,eventType:I,eventLevel:h,surfaceCategory:S,matchUpFormat:T,category:A,gender:P,startDate:y,endDate:E,ballType:U,discipline:M}))(c),m=la({tournamentRecord:t,event:c}).scheduleTiming,d=(c.drawDefinitions||[]).map(f=>{let g=(({drawId:A,drawName:P,matchUpFormat:y,updatedAt:E})=>({matchUpFormat:y,updatedAt:E,drawName:P,drawId:A}))(f),{abandonedMatchUps:I,completedMatchUps:h,upcomingMatchUps:S,pendingMatchUps:T}=ws({requireParticipants:!0,tournamentParticipants:n,context:{eventId:u},policyDefinitions:e,tournamentRecord:t,inContext:!0,scheduleTiming:m,drawDefinition:f,event:c});return{drawInfo:g,matchUps:{abandonedMatchUps:I,completedMatchUps:h,upcomingMatchUps:S,pendingMatchUps:T}}}),l=Qr({event:c});return Object.assign(p,{drawsData:d,publish:l}),p});return{allEventData:{tournamentInfo:o,venuesData:i,eventsData:s}}}var YD={};ne(YD,{getEntryStatusReports:()=>jv,getParticipantStats:()=>Wv,getStructureReports:()=>qv,getVenuesReport:()=>$v});function Wv({withCompetitiveProfiles:t,opponentParticipantId:e,withIndividualStats:r,teamParticipantId:n,tournamentRecord:o,withScaleValues:i,tallyPolicy:s,matchUps:a}){if(!o)return{error:j};if(a&&!Array.isArray(a))return{error:ze};if(a=a??pe({tournamentRecord:o,participantsProfile:i?{withScaleValues:i}:void 0}).matchUps,!a?.length)return{error:wn};let u=[];e&&u.push(e),n&&u.push(n);let p=u.length?{participantIds:u}:{participantTypes:[Yr]},m=$t({participantFilters:p,tournamentRecord:o}).participants??[];if(!m.every(({participantType:U})=>U===Yr))return{error:Hr};u.length||u.push(...m.map(ft));let d=new Map,l=new Map,f=new Map,g=new Map,I=(U,M="")=>l.get(U)||l.set(U,{participantName:M,participantId:U,competitorIds:[],competitiveness:{},matchUpStatuses:{},tiebreaks:[0,0],matchUps:[0,0],points:[0,0],games:[0,0],sets:[0,0]})&&l.get(U);for(let U of m){let{participantId:M,individualParticipantIds:N}=U;g.set(M,N??[]),I(M,U.participantName)}if(n&&!g.get(n))return v({result:{error:Jt},context:{teamParticipantId:n}});if(e&&!g.get(e))return v({result:{error:Jt},context:{opponentParticipantId:e}});let h=[],S=U=>{let M=[[],[]];for(let C of U){let D=C.participant;if(D?.participantName){d.set(D.participantId,{participantName:D.participantName,ratings:D.ratings});let O=l.get(D.participantId);O&&(O.participantName=D.participantName)}}let N=({side:C,individualParticipantIds:D})=>C.participantId&&(!D?.length||D.includes(C.participantId))&&[C.participantId]||C.participant?.individualParticipantIds?.length&&(!D?.length||Wt(D,C.participant?.individualParticipantIds).length===C.participant?.individualParticipantIds?.length)&&C.participant.individualParticipantIds;if(g.size){let C=(D,O)=>{for(let b of U){if(!b.participant)continue;let _=N({individualParticipantIds:O,side:b});if(_?.length){let L=b.sideNumber;if(!L)continue;let F=[D];r&&F.push(..._),M[L-1]=F;let w=l.get(D);for(let x of _.filter(Boolean))w&&!w.competitorIds.includes(x)&&w.competitorIds.push(x)}}};if(n)(!e||U.every(O=>O.participant&&(N({individualParticipantIds:g.get(n),side:O})||N({individualParticipantIds:g.get(e),side:O}))))&&C(n,g.get(n));else for(let[D,O]of g)C(D,O)}else if(r)for(let C of U){if(!C.participant)continue;let D=N({individualParticipantIds:[],side:C}),O=C.sideNumber;O&&(M[O-1]=D)}return M};for(let U of a){if(!Ct(U))return{error:ze};let{matchUpStatus:M,matchUpFormat:N,matchUpType:C,winningSide:D,score:O,sides:b}=U;if(!b||!O||C===pn||M===Ut)continue;let _=S(b);if(!_.filter(Boolean).length)continue;let L=t&&D&&Jc({matchUp:U})?.competitiveness;h.push(U);let F=Wf({matchUpStatus:M,matchUpFormat:N,tallyPolicy:s,winningSide:D,score:O}),w=Bh({matchUpStatus:M,matchUpFormat:N,tallyPolicy:s,winningSide:D,score:O}),{pointsTally:x,tiebreaksTally:H}=Hh({matchUpFormat:N,score:O});_.forEach((V,W)=>{for(let B of V){let q=d.get(B)?.participantName,Y=I(B,q);if(Y){let k=(Q,it)=>it.forEach((ot,dt)=>Y[Q][dt]+=ot),K=W?[...H].reverse():H,X=W?[...x].reverse():x,$=W?[...w].reverse():w,nt=W?[...F].reverse():F;if(k("tiebreaks",K),k("points",X),k("games",$),k("sets",nt),D){let Q=D-1===W?0:1;Y.matchUps[Q]+=1}if(L){let Q=L.toLowerCase();Y.competitiveness[Q]||(Y.competitiveness[Q]=[0,0]),Y.competitiveness[Q][W]+=1}if(M){let Q=M.toLowerCase();Y.matchUpStatuses[Q]||(Y.matchUpStatuses[Q]=0),Y.matchUpStatuses[Q]+=1}}}})}let T=["tiebreaks","matchUps","points","games","sets"],A=["competitive","routine","decisive"],P=new Map,y=(U,M)=>(U??0)+(M??0);for(let[U,M]of l.entries()){for(let N of T){let C=M[N].reduce(y);if(C){let D=M[N][0]/C,O=`${N}Ratio`,b=parseFloat(D.toFixed(2));M[O]=b,f.set(U,!0),P.has(O)||P.set(O,[]),P.get(O)?.push(b)}}for(let N of A){let C=M.competitiveness?.[N]?.reduce(y);if(C){let D=M.competitiveness[N][0]/C,O=`${N}Ratio`,b=parseFloat(D.toFixed(2));M[O]=b}}}if(!n){let U=(M,N)=>N-M;for(let M of l.values())for(let N of T){let C=`${N}Ratio`;if(typeof M[C]=="number"){let D=P.get(C)?.sort(U).indexOf(M[C]);if(typeof D=="number"&&D>=0){let O=`${N}Rank`;M[O]=D+1}}}}let E={relevantMatchUps:h,...R};return n?(E.teamStats=l.get(n),e&&(E.opponentStats=l.get(e))):E.participatingTeamsCount=f.size,E.allParticipantStats=[...l.values()],E}function qp({participant:t,eventType:e}){let r=t?.person?.personId,n=t?.person?.personOtherIds?.[0],o=t?.person?.tennisId,i=t?.ratings?.[e]?.find(({scaleName:u})=>u===ng),s=i?.scaleValue,{wtnRating:a,confidence:c}=s||{};return{timeStamp:i?.scaleDate,personOtherId:n,confidence:c,wtnRating:a,personId:r,tennisId:o}}function jv({tournamentRecord:t}){if(!t)return{error:j};let e=t.tournamentId,{participantMap:r}=$t({withScaleValues:!0,withEvents:!0,withSeeding:!0,tournamentRecord:t,withDraws:!0}),o=(pe({matchUpFilters:{matchUpTypes:[da,Ri]},tournamentRecord:t}).matchUps??[]).flatMap(({sides:f,matchUpType:g})=>f?.flatMap(I=>g===Ri?I?.participant?.individualParticipantIds:I?.participant?.participantId||I.participantId).filter(Boolean)).filter(Boolean),i=[],s={},a={},c={},u=0,p=({id:f,entry:g,eventId:I,eventType:h})=>{let{qualifyingSeeding:S,mainSeeding:T,entryStatus:A,entryStage:P,drawId:y}=g;s[f]||(s[f]=[]);let{participant:E,events:U}=r?.[f]??{},M=qp({participant:E,eventType:h}),N=U?.[I]?.ranking;A===Jf&&i.push(f),s[f].push({participantType:E?.participantType,participantId:f,tournamentId:e,eventType:h,eventId:I,drawId:y,entryStatus:A,entryStage:P,...M,ranking:N,mainSeeding:T,qualifyingSeeding:S})};for(let f of t.events??[]){let g={},I=M=>{g[M]||(g[M]={count:0}),g[M].count+=1},{drawDefinitions:h=[],eventType:S,eventId:T}=f,A=h.flatMap(M=>{let{drawId:N,entries:C}=M;u+=1;let D=({stage:F,stageSequence:w})=>F===tt&&w===1||F===at,b=(M.structures??[]).filter(D).flatMap(({positionAssignments:F})=>F).filter(Boolean).map(({participantId:F})=>F),_=({participantId:F})=>b.includes(F),L=F=>{let{participantId:w,entryStatus:x,entryStage:H}=F;I(x);let V=r?.[w]?.draws?.[N]?.seedAssignments?.[tt];return{qualifyingSeeding:r?.[w]?.draws?.[N]?.seedAssignments?.[at],participantId:w,mainSeeding:V,entryStatus:x,entryStage:H,drawId:N}};return C?.filter(_).map(L)}),P=M=>{let N=M.participantId,C=r?.[N].participant.individualParticipantIds?.filter(D=>o.includes(D));return N&&{[N]:{individualParticipantIds:C}}};S===ui?(()=>{let M=Object.assign({},...A.map(P).filter(Boolean)),N=C=>{M[C.participantId].individualParticipantIds.forEach(D=>{p({id:D,eventType:S,eventId:T,entry:C})})};A.forEach(N)})():A.forEach(M=>{p({id:M?.participantId,eventType:S,eventId:T,entry:M})});let E=Object.values(g).reduce((M,N)=>M+N.count,0);Object.keys(g).forEach(M=>{g[M].pct=g[M].count/E*100}),c[T]={tournamentId:e,eventId:T,entries:A,entryStatuses:g};let U=Object.assign({},...Mr.flatMap(M=>[{[M+"_count"]:g[M]?.count},{[M+"_pct"]:g[M]?.pct}]));a[T]={tournamentId:e,eventId:T,...U}}let m=Object.values(r??{}).filter(({participant:{participantType:f,participantRole:g}})=>f===It&&g===Fe),d=m.filter(({participant:f})=>!o.includes(f.participantId)).map(({participant:f})=>f.participantId),l={nonParticipatingEntriesCount:d.length,individualParticipantsCount:m.length,eventsCount:Object.values(c).length,nonParticipatingParticipantIds:d,drawDefinitionsCount:u,tournamentId:e};return{entryStatusReports:Object.values(a).flat(),participantEntryReports:Object.values(s).flat(),eventReports:Object.values(c).flat(),withDrawnParticipantIds:i,tournamentEntryReport:l}}function Yv({eventType:t,matchUps:e,eventId:r,drawId:n}){let o={},i=g=>{let I=g?.matchUpFormat;I&&(o[I]||(o[I]=0),o[I]+=1)},s=e.filter(g=>r?g.eventId===r:g.drawId===n).reduce((g,I)=>(i(I),(I.sides??[]).flatMap(h=>(h?.participant?.individualParticipants||[h?.participant]).filter(Boolean)).forEach(h=>g[h.participantId]=h),g),{}),a=Object.values(s),c=a.map(g=>qp({participant:g,eventType:t})).filter(({wtnRating:g})=>g),u=(a.length-c.length)/a.length*100,p=c.reduce((g,I)=>{let{wtnRating:h,confidence:S}=I;return g.totalWTN+=h,g.totalConfidence+=S,g},{totalWTN:0,totalConfidence:0}),m=c?.length?p.totalWTN/c.length:0,d=c?.length?p.totalConfidence/c.length:0,f=Object.values(o).reduce((g,I)=>g+(I||0),0);return{matchUpFormatCounts:o,matchUpsCount:f,avgConfidence:d,pctNoRating:u,avgWTN:m}}function qv({firstFlightOnly:t=!0,extensionProfiles:e,tournamentRecord:r}){if(!r)return{error:Xs};let n={},o=Object.assign({},...(e??[]).map(({name:p,label:m,accessor:d})=>{let l=ut({element:r,name:p})?.extension?.value,f=d?Wi({element:l,accessor:d})?.value:l;return{[m||p]:f}})),i=r?.tournamentId,a=pe({participantsProfile:{withScaleValues:!0},tournamentRecord:r}).matchUps??[],c=p=>_n({itemType:zl,itemSubTypes:[Qn],element:{timeItems:p}})?.timeItem?.itemValue?.scaleBasis,u=r?.events?.flatMap(({timeItems:p,drawDefinitions:m=[],extensions:d,eventType:l,eventId:f,category:g})=>{let h=d?.find(E=>E.name===Gr)?.value?.flights?.map(E=>({[E.drawId]:E.flightNumber})),S=h&&Object.assign({},...h),T=d?.find(E=>E.name===pm)?.value?.length||0,A=Object.values(S),P=S&&Math.min(...A),y=c(p);return n[f]={totalPositionManipulations:0,maxPositionManipulations:0,generatedDrawsCount:0,drawDeletionsCount:T,seedingBasis:y?JSON.stringify(y):void 0,tournamentId:i,eventId:f},m.filter(E=>!t||!h||S[E.drawId]===P).flatMap(E=>{let{matchUpFormat:U,tieFormat:M,timeItems:N,extensions:C,structures:D,drawType:O,drawId:b}=E,{matchUpFormatCounts:_,matchUpsCount:L,avgConfidence:F,pctNoRating:w,avgWTN:x}=Yv({eventType:l,matchUps:a,drawId:b}),H=c(N)||y,V=SV({extensions:C}),W=V?.length||0;return n[f].totalPositionManipulations+=W,n[f].generatedDrawsCount+=1,W>n[f].maxPositionManipulations&&(n[f].maxPositionManipulations=W),D?.filter(B=>B.stageSequence===1&&[at,tt,Ge,ae].includes(B.stage)).map(B=>{let q=[tt,ae].includes(B.stage)?a.find(Re=>Re.structureId===B.structureId&&Re.finishingRound===1&&Re.winningSide):void 0,k=q?.sides?.find(Re=>Re.sideNumber===q.winningSide)?.participant,K=k?.participantType===Yr&&k.participantId,X=k?.participantType===pt?k.individualParticipants:[],$=qp({participant:X?.[0]||k,eventType:l}),{personId:nt,personOtherId:Q,tennisId:it,confidence:ot,wtnRating:dt}=$||{},zt=qp({participant:X?.[1],eventType:l}),{personId:Et,personOtherId:ge,tennisId:Ee,confidence:Ce,wtnRating:Xt}=zt||{},{ageCategoryCode:Ue,categoryName:Ht,subType:Ie}=g??{},Nt=B.matchUpFormat||U,Ft=(_[Nt]||0)/L*100,{tieFormatName:Yt,tieFormatDesc:ue}=ld(M),{tieFormatName:Se,tieFormatDesc:ur}=ld(B.tieFormat),Oe=ue===ur,Vt=!Oe&&Se,_e=B.tieFormat&&!Oe&&ur,tr=V?.filter(Re=>Re.structureId===B.structureId)?.length||0;return{...o,tournamentId:i,eventId:f,structureId:B.structureId,drawId:b,eventType:l,category:Ie,categoryName:Ht,ageCategoryCode:Ue,flightNumber:S[b],drawType:O,stage:B.stage,seedingBasis:H?JSON.stringify(H):void 0,winningPersonId:nt,winningPersonOtherId:Q,winningPersonTennisId:it,winningPersonWTNrating:dt,winningPersonWTNconfidence:ot,winningPerson2Id:Et,winningPerson2OtherId:ge,winningPerson2TennisId:Ee,winningPerson2WTNrating:Xt,winningPerson2WTNconfidence:Ce,winningTeamId:K,positionManipulations:tr,pctNoRating:w,matchUpFormat:Nt,pctInitialMatchUpFormat:Ft,matchUpsCount:L,drawTieFormatName:Yt,drawTieFormatDesc:ue,tieFormatName:Vt,tieFormatDesc:_e,avgConfidence:F,avgWTN:x}})})});return{eventStructureReports:Object.values(n),structureReports:u}}function SV({extensions:t}){return t?.find(({name:e})=>e===am)?.value?.slice(1)}function $v({ignoreDisabled:t=!0,tournamentRecords:e,tournamentId:r,venueIds:n=[],dates:o=[]}){if(!Array.isArray(o))return{error:G,dates:o};if(!Array.isArray(n))return{error:G,venueIds:n};if(!(e&&Object.keys(e).filter(l=>!r||l===r)||[]).length)return{error:wt};if(!o.every(Pr))return{error:ir};let a=oo({tournamentRecords:e,ignoreDisabled:t,dates:o});if(a.error)return a;let c=a?.venues?.filter(({venueId:l})=>!n?.length||n.includes(l)),u=a.courts?.reduce((l,f)=>(f.dateAvailability?.forEach(g=>{let I=g.date;l.includes(I)||l.push(I)}),l),[]).filter(l=>!o.length||o.includes(l)),p={venueIds:c?.map(({venueId:l})=>l)},{matchUps:m}=nn({afterRecoveryTimes:!0,tournamentRecords:e,matchUpFilters:p});return{venuesReport:c?.map(l=>TV(u,l,m))}}function TV(t,e,r){let{venueId:n,courts:o,venueName:i}=e,s={};return t.forEach(a=>{let c=0,u=0,p=0;for(let l of o){let f=l.dateAvailability.find(h=>h.date===a),I=(f&&ls({courtDate:f}).timeSlots)?.reduce((h,S)=>{let{startTime:T,endTime:A}=S,P=Gt(A)-Gt(T);return h+P},0);I&&(p+=1),c+=I}let m=r.filter(({schedule:l})=>l.venueId===n&&Dn(a,l.scheduledDate));m.forEach(({schedule:l})=>{let f=qt(l.scheduledTime),g=Nr(f,l.averageMinutes),I=Gt(g)-Gt(f);u+=I});let d=c?(u/c*100).toFixed(2):"100";s[a]={scheduledMatchUpsCount:m.length,availableCourts:p,availableMinutes:c,scheduledMinutes:u,percentUtilization:d}}),{venueId:n,venueName:i,venueReport:s}}var nM={};ne(nM,{addMatchUpCourtOrder:()=>qT,addMatchUpEndTime:()=>KT,addMatchUpOfficial:()=>qN,addMatchUpResumeTime:()=>QT,addMatchUpScheduleItems:()=>Bp,addMatchUpScheduledDate:()=>Fd,addMatchUpScheduledTime:()=>_o,addMatchUpStartTime:()=>$T,addMatchUpStopTime:()=>zT,addSchedulingProfileRound:()=>vg,allocateTeamMatchUpCourts:()=>Vp,assignMatchUpCourt:()=>Fi,assignMatchUpVenue:()=>Ks,bulkRescheduleMatchUps:()=>JD,bulkScheduleMatchUps:()=>Uc,bulkScheduleTournamentMatchUps:()=>Mu,bulkUpdateCourtAssignments:()=>KD,calculateScheduleTimes:()=>wg,clearMatchUpSchedule:()=>tM,clearScheduledMatchUps:()=>Wp,courtGridRows:()=>ig,findMatchUpFormatTiming:()=>Ep,findVenue:()=>jo,generateBookings:()=>Hp,generateVirtualCourts:()=>Fp,getPersonRequests:()=>gi,getProfileRounds:()=>ag,getScheduledRoundsDetails:()=>Tu,getSchedulingProfile:()=>Ro,getSchedulingProfileIssues:()=>OS,matchUpScheduleChange:()=>ZD,modifyMatchUpFormatTiming:()=>Ig,mutate:()=>rM,proAutoSchedule:()=>$D,proConflicts:()=>QD,publicFindCourt:()=>HE,query:()=>pP,removeEventMatchUpFormatTiming:()=>bd,removeMatchUpCourtAssignment:()=>qD,reorderUpcomingMatchUps:()=>XD,scheduleMatchUps:()=>zD,scheduleProfileRounds:()=>jp,setMatchUpDailyLimits:()=>eM,setSchedulingProfile:()=>Ic,toggleParticipantCheckInState:()=>vd,validateSchedulingProfile:()=>Up});var rM={};ne(rM,{addMatchUpCourtOrder:()=>qT,addMatchUpEndTime:()=>KT,addMatchUpOfficial:()=>qN,addMatchUpResumeTime:()=>QT,addMatchUpScheduleItems:()=>Bp,addMatchUpScheduledDate:()=>Fd,addMatchUpScheduledTime:()=>_o,addMatchUpStartTime:()=>$T,addMatchUpStopTime:()=>zT,addSchedulingProfileRound:()=>vg,allocateTeamMatchUpCourts:()=>Vp,assignMatchUpCourt:()=>Fi,assignMatchUpVenue:()=>Ks,bulkRescheduleMatchUps:()=>JD,bulkScheduleMatchUps:()=>Uc,bulkScheduleTournamentMatchUps:()=>Mu,bulkUpdateCourtAssignments:()=>KD,calculateScheduleTimes:()=>wg,clearMatchUpSchedule:()=>tM,clearScheduledMatchUps:()=>Wp,courtGridRows:()=>ig,findMatchUpFormatTiming:()=>Ep,findVenue:()=>jo,generateBookings:()=>Hp,generateVirtualCourts:()=>Fp,getProfileRounds:()=>ag,matchUpScheduleChange:()=>ZD,modifyMatchUpFormatTiming:()=>Ig,proAutoSchedule:()=>$D,proConflicts:()=>QD,publicFindCourt:()=>HE,removeEventMatchUpFormatTiming:()=>bd,removeMatchUpCourtAssignment:()=>qD,reorderUpcomingMatchUps:()=>XD,scheduleMatchUps:()=>zD,scheduleProfileRounds:()=>jp,setMatchUpDailyLimits:()=>eM,setSchedulingProfile:()=>Ic,toggleParticipantCheckInState:()=>vd,validateSchedulingProfile:()=>Up});function wg({calculateStartTimeFromCourts:t=!0,defaultRecoveryMinutes:e=0,averageMatchUpMinutes:r=90,remainingScheduleTimes:n,clearScheduleDates:o,tournamentRecords:i,periodLength:s,scheduleDate:a,startTime:c,venueIds:u,endTime:p}){if(typeof i!="object"||!Object.keys(i).length)return{error:wt};s=s??Pu({recoveryMinutes:e,averageMatchUpMinutes:r});let{courts:m,venues:d}=oo({dates:[a],ignoreDisabled:!0,tournamentRecords:i}),l=m?.filter(C=>!u||u.includes(C.venueId));c||(c=l?.reduce((C,D)=>{let b=D.dateAvailability?.find(_=>!_.date||Dn(a,_.date))?.startTime??D.startTime;return b&&(!C||Gt(b)<Gt(C))?b:C},void 0)),p||(p=l?.reduce((C,D)=>{let b=D.dateAvailability?.find(_=>!_.date||Dn(a,_.date))?.endTime??D.endTime;return b&&(!C||Gt(b)>Gt(C))?b:C},void 0));let f=Object.values(i),g=Object.assign({},...f.map(C=>(C.events??[]).map(D=>{let{scheduleTiming:O}=la({tournamentRecord:C,event:D});return{[D.eventId]:{event:D,scheduleTiming:O}}})).flat()),h=Au({sortDateMatchUps:!1,tournamentRecords:i,matchUpFilters:{scheduledDate:a,venueIds:u}}),S=h?.dateMatchUps??[],T=h?.completedMatchUps??[],A=[];A.push(...S),A.push(...T);let P={averageTimes:[{minutes:{default:r}}],recoveryTimes:[{minutes:{default:e}}]},y=A?.map(({eventId:C,schedule:D,matchUpFormat:O})=>{let{event:b,scheduleTiming:_}=g[C],L=b?.eventType,F={..._,defaultTiming:P,matchUpFormat:O},{averageMinutes:w,recoveryMinutes:x}=ip({eventType:L,timingDetails:F}),{courtId:H,venueId:V}=D,W=qt(D.scheduledTime),B=Nr(W,w);return{recoveryMinutes:x,averageMinutes:w,periodLength:s,startTime:W,endTime:B,courtId:H,venueId:V}}),E={calculateStartTimeFromCourts:t,remainingScheduleTimes:n,averageMatchUpMinutes:r,date:a,clearScheduleDates:o,periodLength:s,startTime:c,endTime:p,bookings:y,courts:l},{scheduleTimes:U}=_d(E),M=u?.length===1&&u[0]||d?.length===1&&d[0].venueId||void 0,N=A.map(le);return{venueId:M,scheduleTimes:U,dateScheduledMatchUpIds:N}}function qD(t){let e=vt(t,[{[ye]:!0}]);if(e.error)return e;let{removePriorValues:r,tournamentRecords:n,tournamentId:o,courtDayDate:i,matchUpId:s,courtId:a,drawId:c}=t,u=n[o];if(!u)return{error:j};let{drawDefinition:p,event:m}=To({tournamentRecord:u,drawId:c});if(!p)return{error:z};let d=xt({drawDefinition:p,event:m,matchUpId:s});if(d.error)return d;if(d?.matchUp?.matchUpType===pn){let{itemValue:l}=Do({timeItems:d.matchUp.timeItems??[],itemType:ho}),f=a&&l.filter(I=>I.courtId!==a);return Zr({duplicateValues:!1,removePriorValues:r,tournamentRecord:u,drawDefinition:p,matchUpId:s,timeItem:{itemType:ho,itemValue:f}})}else return Fi({tournamentRecord:u,drawDefinition:p,courtDayDate:i,courtId:"",matchUpId:s})}function $D({scheduleCompletedMatchUps:t,tournamentRecords:e,scheduledDate:r,matchUps:n}){if(!Ar(n))return{error:G};if(n.some(({hasContext:g})=>!g))return{info:"matchUps must have { inContext: true, nextMatchUps: true }",error:Rc};let i=Au({courtCompletedMatchUps:!0,withCourtGridRows:!0,minCourtGridRows:10,tournamentRecords:e,matchUpFilters:{localPerspective:!0,scheduledDate:r}});if(i.error)return i;let{rows:s}=i,a=[],c=g=>[(g.sides||[]).map(I=>[I.participantId,I.participant?.individualParticipantIds]),(g.potentialParticipants||[]).flat().map(I=>[I.participantId,I.individualParticipantIds])].flat(1/0).filter(Boolean),u=s?.reduce((g,I)=>{let h=[],S=[];Object.values(I).forEach(A=>{if(Ct(A)&&(A.matchUpId&&(h.push(A.matchUpId),a.push(A)),A.sides)){let P=c(A);S.push(...P)}});let T=Object.values(I).filter(A=>Ct(A)&&!A.matchUpId);return g.concat({matchUpIds:h,availableCourts:T,rowId:I.rowId,participantIds:S})},[]);n.filter(({matchUpStatus:g})=>g&&g!==Ut&&(t||!ie.includes(g))).sort(mi);let p=xr({matchUps:n.concat(a),includeParticipantDependencies:!0,tournamentRecords:e}).matchUpDependencies,m=[],d=[];for(;n.length&&u.length;){let g=u.shift(),I=[];for(;n.length&&g.availableCourts.length;){let h=n.concat(I).map(N=>N.matchUpId),S=n.shift(),T=S?.matchUpId,A=T&&p[T].matchUpIds.concat(p[T].dependentMatchUpIds),P=T&&h.some(N=>p[T].matchUpIds.includes(N)),y=T&&d.some(N=>p[T].dependentMatchUpIds.includes(N)),E=g.matchUpIds.some(N=>A.includes(N)),U=c(S),M=g.participantIds.some(N=>U.includes(N));if(S&&!E&&!P&&!M&&!y){let N=g.availableCourts.shift();Object.assign(S.schedule,N.schedule),Object.assign(N,S),m.push(S),g.participantIds.push(...U),g.matchUpIds.push(T)}else S&&I.push(S)}n.push(...I),d.push(...g.matchUpIds)}let l=m.map(({matchUpId:g,tournamentId:I,schedule:h,drawId:S})=>({tournamentId:I,matchUpId:g,drawId:S,schedule:{...h,scheduledDate:r}}));return i=Uc({tournamentRecords:e,matchUpDetails:l}),{...i,scheduled:m,notScheduled:n}}function KD(t){let{courtDayDate:e}=t,r=vt(t,[{courtAssignments:!0,[na]:an,[Ni]:et},{[ye]:!0}]);if(r.error)return r;let n=t.courtAssignments.reduce((s,a)=>{let{tournamentId:c}=a;return s[c]||(s[c]=[]),s[c].push(a),s},{}),o;return Object.keys(n).every(s=>{let a=t[ye][s];if(!a)return o={error:j},!1;let c=n[s].reduce((p,m)=>{let{drawId:d}=m;return p[d]||(p[d]=[]),p[d].push(m),p},{});Object.keys(c).every(p=>{let{drawDefinition:m}=nr({tournamentRecord:a,drawId:p});return m?(c[p].every(d=>{let{matchUpId:l,courtId:f}=d,g=Fi({tournamentRecord:a,drawDefinition:m,courtDayDate:e,matchUpId:l,courtId:f});if(g.success)return g?.success;o={error:Ry}}),!0):(o={error:z},!1)})}),o||R}function zD(t){let{tournamentRecords:e,allDateMatchUpIds:r=[],averageMatchUpMinutes:n=90,recoveryMinutes:o=0,recoveryMinutesMap:i,matchUpPotentialParticipantIds:s={},individualParticipantProfiles:a={},matchUpNotBeforeTimes:c={},matchUpDailyLimits:u={},checkPotentialRequestConflicts:p=!0,remainingScheduleTimes:m,clearScheduleDates:d,periodLength:l=30,scheduleDate:f,matchUpIds:g,venueIds:I,startTime:h,endTime:S,dryRun:T}=t,A=vt(t,[{[ye]:!0,[Fl]:!0},{[Pi]:Pr,[Ni]:ir,[AC]:!0},{[Pi]:k=>!k||!isNaN(k),[PC]:!1,[Ni]:G,[NC]:!1,[DC]:!1}]);if(A.error)return A;let P=t.competitionMatchUps??nn({nextMatchUps:!0,tournamentRecords:e}).matchUps??[],y=t.matchUpDependencies??xr({includeParticipantDependencies:!0,matchUps:P,tournamentRecords:e}).matchUpDependencies;P.forEach(k=>{k.schedule?.scheduledDate&&Dn(f,At(k.schedule.scheduledDate))&&zs({matchUpPotentialParticipantIds:s,matchUpNotBeforeTimes:c,matchUp:k})});let E=g.map(k=>P.find(K=>K.matchUpId===k)).filter(Boolean),{venueId:U,scheduleTimes:M,dateScheduledMatchUpIds:N}=wg({tournamentRecords:e,remainingScheduleTimes:m,startTime:qt(h),endTime:qt(S),scheduleDate:At(f),averageMatchUpMinutes:n,clearScheduleDates:d,periodLength:l,venueIds:I}),C={},D=[],O={},b={},_={};P.filter(({matchUpId:k})=>N?.includes(k)).forEach(k=>{Mg({matchUpPotentialParticipantIds:s,individualParticipantProfiles:a,matchUp:k,value:1});let K=k.schedule?.scheduledTime;if(K){O[k.matchUpId]=K;let X=i?.[k.matchUpId];yc({recoveryMinutes:X||o,matchUpPotentialParticipantIds:s,individualParticipantProfiles:a,matchUpNotBeforeTimes:c,averageMatchUpMinutes:n,matchUpDependencies:y,scheduleTime:K,matchUp:k})}});let F=E.filter(k=>{let K=N?.includes(k.matchUpId),X=[Ut,bt,me,kr,mr,Ot].includes(k?.matchUpStatus);return!K&&!k.winningSide&&!X}),{matchUpMap:w,overLimitMatchUpIds:x,participantIdsAtLimit:H}=F.reduce((k,K)=>{let{drawId:X,tournamentId:$,matchUpType:nt}=K,{participantIdsAtLimit:Q,relevantParticipantIds:it}=Bd({individualParticipantProfiles:a,matchUpPotentialParticipantIds:s,matchUpDailyLimits:u,matchUp:K});return Q?.length?(k.overLimitMatchUpIds.push(K.matchUpId),k.participantIdsAtLimit.push(...Q),k):(it.forEach(ot=>{ba({individualParticipantProfiles:a,participantId:ot});let dt=a[ot].counters;dt[nt]?dt[nt]+=1:dt[nt]=1,dt[Hn]?dt[Hn]+=1:dt[Hn]=1}),k.matchUpMap[$]||(k.matchUpMap[$]={}),k.matchUpMap[$][X]?k.matchUpMap[$][X].push(K):k.matchUpMap[$][X]=[K],zs({matchUpPotentialParticipantIds:s,matchUpNotBeforeTimes:c,matchUp:K}),k)},{matchUpMap:{},overLimitMatchUpIds:[],participantIdsAtLimit:[]});F=F.filter(({matchUpId:k})=>!x.includes(k));let V=0,W=M?.length??0,{personRequests:B}=gi({tournamentRecords:e,requestType:Ec});for(;M?.length&&F.length&&V<=W;){V++;let{scheduleTime:k}=M.shift(),K=F.find(X=>{let{matchUpId:$}=X,{dependenciesScheduled:nt,remainingDependencies:Q}=Gd({matchUpScheduleTimes:O,matchUpDependencies:y,allDateMatchUpIds:r,matchUp:X});if(!nt)return _[$]||(_[$]=[]),_[$].push({scheduleTime:k,remainingDependencies:Q}),!1;let{enoughTime:it}=Vd({individualParticipantProfiles:a,matchUpNotBeforeTimes:c,matchUpDependencies:y,scheduleTime:k,matchUp:X});if(!it)return b[$]||(b[$]=[]),b[$].push({scheduleTime:k}),!1;let{conflicts:ot}=kd({potentials:p,averageMatchUpMinutes:n,requestConflicts:C,personRequests:B,scheduleTime:k,scheduleDate:f,matchUp:X});if(ot?.length)return!1;let dt=i?.[X.matchUpId];return yc({recoveryMinutes:dt||o,matchUpPotentialParticipantIds:s,individualParticipantProfiles:a,matchUpNotBeforeTimes:c,averageMatchUpMinutes:n,matchUpDependencies:y,scheduleTime:k,matchUp:X}),O[X.matchUpId]=k,!0});F=F.filter(({matchUpId:X})=>X!==K?.matchUpId),K||D.push(k)}F.forEach(k=>{Mg({individualParticipantProfiles:a,matchUpPotentialParticipantIds:s,value:-1,matchUp:k})});let q=[];Object.keys(w).forEach(k=>{let K=e[k];K&&Object.keys(w[k]).forEach(X=>{let{drawDefinition:$}=To({tournamentRecord:K,drawId:X});$&&w[k][X].forEach(({matchUpId:Q})=>{let it=O[Q];if(it){let ot=it.split(":").map(Ln).join(":"),dt=`${At(f)}T${ot}`;T?q.push(Q):(_o({drawDefinition:$,matchUpId:Q,scheduledTime:dt}).success&&q.push(Q),U&&Ks({tournamentRecords:e,tournamentRecord:K,drawDefinition:$,matchUpId:Q,venueId:U}))}})})});let Y=lm(F);return{...R,requestConflicts:Object.values(C),remainingScheduleTimes:M?.map(({scheduleTime:k})=>k),individualParticipantProfiles:a,matchUpNotBeforeTimes:c,participantIdsAtLimit:H,skippedScheduleTimes:D,overLimitMatchUpIds:x,scheduledMatchUpIds:q,noTimeMatchUpIds:Y,recoveryTimeDeferred:b,dependencyDeferred:_}}function QD({tournamentRecords:t,matchUps:e}){if(!Ar(e))return{error:wn};if(e.some(({matchUpId:f,hasContext:g})=>f&&!g))return{info:"matchUps must have { inContext: true, nextMatchUps: true }",error:Rc};let r=Math.max(...e.map(({schedule:f})=>f?.courtOrder||1).map(f=>ct(f))),n=Z(1,r+1).map(f=>e.filter(g=>ct(g.schedule?.courtOrder)===f)),o={},i={},s={};n.flat().filter(Boolean).sort(mi).forEach(({schedule:f})=>delete f[Tf]);let c=mt(e.map(({drawId:f})=>f)),u=xr({includeParticipantDependencies:!0,tournamentRecords:t,drawIds:c}).matchUpDependencies,p=n.map((f,g)=>f.reduce((I,h)=>{if(!h.matchUpId)return I;let{matchUpId:S,winnerMatchUpId:T,loserMatchUpId:A,schedule:P,sides:y,potentialParticipants:E}=h,U=P?.courtId;o[S]=g,i[U]=[],I.matchUpIds.push(S),s[S]=h;let M=u[S].matchUpIds;M.length&&I.sourceMatchUpIds.push(...M);let N=y?.map(D=>[D.participant?.individualParticipantIds,D.participantId]).flat().filter(Boolean)??[],C=E?.flat().map(({individualParticipantIds:D,participantId:O})=>[D,O]).flat().filter(Boolean)||[];return I.participantIds.push(...C,...N),T&&I.targetMatchUpIds.push(T),A&&I.targetMatchUpIds.push(A),I},{sourceMatchUpIds:[],targetMatchUpIds:[],participantIds:[],matchUpIds:[]})),m=(f,g)=>u[f].sources.reduce((I,h,S)=>h.includes(g)&&S+1||I,0),d=p.map(()=>[]),l=(f,g,I,h)=>{if(!s[f].schedule[Tf]){s[f].schedule[Tf]=g,s[f].schedule[BE]=h,d[o[f]].push({matchUpId:f,issueType:I,issueIds:h,issue:g});let S=s[f].schedule.courtId;i[S]||(i[S]=[]),i[S].push({matchUpId:f,issue:g,issueType:I,issueIds:h})}};return p.forEach((f,g)=>{let I=g?p[g-1]:void 0,h=p.slice(g+1),S={},T=pr(f.participantIds),A=Object.keys(T).filter(E=>T[E]>1),P=f.matchUpIds.filter(E=>u[E].participantIds.some(U=>A.includes(U)));P.forEach(E=>{S[E]||(S[E]={}),S[E][ec]||(S[E][ec]=P.filter(U=>U!==E))});let y=I&&f.participantIds.filter(E=>I.participantIds.includes(E));y&&y.forEach(E=>{let U=f.matchUpIds.concat(I.matchUpIds).filter(M=>u[M].participantIds.includes(E));U.forEach(M=>{S[M]||(S[M]={}),S[M][rc]||(S[M][rc]=U.filter(N=>N!==M))})}),f.matchUpIds.forEach(E=>{let U=u[E].matchUpIds;for(let N of h){let C=N.matchUpIds.filter(D=>U.includes(D));C?.length&&(C.forEach(D=>l(D,nh,fa,[E])),l(E,nh,fa,C))}if(S[E]?.[ec]&&l(E,ec,rh,S[E][ec]),f.sourceMatchUpIds.includes(E)){let N=f.matchUpIds.filter(C=>u[C].matchUpIds.includes(E));l(E,ec,fa,N),f.matchUpIds.filter(C=>u[C].matchUpIds.includes(E)).forEach(C=>l(C,ec,fa,[E]))}let M=I?.matchUpIds?.filter(N=>m(E,N)>1);if(M?.length&&(l(E,oh,fa,M),M.forEach(N=>l(N,oh,fa,[E]))),S[E]?.[rc]&&l(E,rc,rh,S[E][rc]),I?.targetMatchUpIds?.includes(E)){let N=s[E].schedule.courtId,C=U.filter(O=>I.matchUpIds.includes(O));C.some(O=>s[O].schedule.courtId===N)||(C.forEach(O=>l(O,rc,fa,[E])),l(E,rc,fa,C))}})}),{courtIssues:i,rowIssues:d}}function XD(t){let e="reorderUpcomingMatchUps",{tournamentRecords:r}=t;if(typeof r!="object"||!Object.keys(r).length)return v({result:{error:wt},stack:e});let{matchUpsContextIds:n,firstToLast:o}=t;if(!n)return v({result:{error:et},stack:e});let i=n?.length;if(!i)return{...R};let s=0;return n.forEach((c,u)=>{let{tournamentId:p,drawId:m,matchUpId:d}=c,l=u+(o?-1:1);l<0&&(l=i-1),l===i&&(l=0);let f=n[l].schedule.scheduledTime,g=a({tournamentId:p,scheduledTime:f,matchUpId:d,drawId:m});if(g.success)s++;else return g}),s===i?R:v({result:{error:Cy},stack:e});function a({tournamentId:c,scheduledTime:u,matchUpId:p,drawId:m}){let d=r[c],{drawDefinition:l}=To({tournamentRecord:d,drawId:m});return l?_o({drawDefinition:l,scheduledTime:u,matchUpId:p}):{error:fr}}}function JD(t){let{scheduleChange:e,matchUpIds:r,dryRun:n}=t;if(!r||!Array.isArray(r))return{error:ta};if(typeof e!="object")return{error:G};let o=jr(t),i=[],s=[];for(let c of Object.values(o)){let u=AV({tournamentRecord:c,scheduleChange:e,matchUpIds:r,dryRun:n});if(u.error)return u;Array.isArray(u.notRescheduled)&&s.push(...u.notRescheduled);let p=lm(u.notRescheduled),m=[];u.rescheduled?.forEach(d=>{let{matchUpId:l}=d;p.includes(l)&&m.push(l),i.push(d)}),m.length&&(s=u?.notRescheduled?.filter(({matchUpId:d})=>!m.includes(d))||[])}let a=!!(i.length&&!s.length);return{...R,rescheduled:i,notRescheduled:s,allRescheduled:a}}function AV({tournamentRecord:t,scheduleChange:e,matchUpIds:r,dryRun:n}){if(!t)return{error:j};if(!r||!Array.isArray(r))return{error:ta};if(typeof e!="object")return{error:G};let o=[],i=[],{minutesChange:s,daysChange:a}=e;if(!s&&!a)return{...R};if(s&&isNaN(s))return{error:G};if(a&&isNaN(a))return{error:G};let{matchUps:c}=pe({matchUpFilters:{matchUpIds:r},tournamentRecord:t}),u=({matchUpStatus:A})=>!ie.includes(A),p=c?.filter(A=>Da({schedule:A.schedule})).filter(A=>u({matchUpStatus:A.matchUpStatus}));if(!p?.length)return{...R};let{tournamentInfo:m}=us({tournamentRecord:t}),{startDate:d,endDate:l}=m,f=p?.reduce((A,P)=>{let{matchUpId:y,drawId:E}=P;return A[E]?A[E].push(y):A[E]=[y],A},{}),g=1440;for(let A of Object.keys(f)){let P=To({tournamentRecord:t,drawId:A});if(P.error)return P;let y=P.drawDefinition,E=f[A].filter(U=>r.includes(U));for(let U of E)if(U&&y){let N=p.find(L=>L.matchUpId===U)?.schedule,{scheduledTime:C,scheduledDate:D}=N,O,b,_;if(!O&&a&&D){let L=At(D);_=ju(L,a),O=new Date(_)<new Date(d)||new Date(_)>new Date(l)}if(s&&C){let L=At(C),w=Gt(qt(C))+s;if(O=w<0||w>g,!O){let x=Nr(C,s),H=L&&_||D===L&&L;b=H?`${H}T${x}`:x}}if(O)i.push(U);else{if(!n){if(b){let L=_o({scheduledTime:b,drawDefinition:y,matchUpId:U});if(L.error)return L}if(_){let L=Fd({scheduledDate:_,drawDefinition:y,matchUpId:U});if(L.error)return L}}(b||_)&&o.push(U)}}}let I=pe({matchUpFilters:{matchUpIds:r},tournamentRecord:t}).matchUps??[],h=I.filter(({matchUpId:A})=>o.includes(A)),S=I.filter(({matchUpId:A})=>i.includes(A)),T=h.length&&!S.length;return{...R,rescheduled:h,notRescheduled:S,allRescheduled:T}}function ZD(t){let e="matchUpScheduleChange",{tournamentRecords:r}=t;if(typeof r!="object"||!Object.keys(r).length)return{error:wt};let{sourceMatchUpContextIds:n,targetMatchUpContextIds:o,sourceCourtId:i,targetCourtId:s,courtDayDate:a}=t||{},{drawId:c,matchUpId:u,tournamentId:p}=n||{},{drawId:m,matchUpId:d,tournamentId:l}=o||{};if(!u&&!d)return v({result:{error:et},stack:e});let{matchUps:f}=nn({matchUpFilters:{matchUpIds:[u,d].filter(Boolean),drawIds:[c,m].filter(Boolean)},tournamentRecords:t.tournamentRecords}),g=f?.find(({matchUpId:A})=>A===u),I=f?.find(({matchUpId:A})=>A===d),h=0;if(s&&u&&!d){let A=S({tournamentId:p,matchUpId:u,courtId:s,matchUp:g,drawId:c,tournamentRecords:r,sourceCourtId:i,courtDayDate:a});if(A?.success&&h++,A.error)return v({result:A,stack:e})}else if(i&&s&&u&&d){let A=S({tournamentId:p,matchUpId:u,courtId:s,matchUp:g,drawId:c,tournamentRecords:r,sourceCourtId:i,courtDayDate:a});if(A.success&&h++,A.error)return v({result:A,stack:e,info:"source"});let P=S({tournamentId:l,sourceCourtId:s,matchUpId:d,matchUp:I,courtId:i,drawId:m,tournamentRecords:r,courtDayDate:a});if(P.success&&h++,P.error)return v({result:P,stack:e,info:"target"})}else return{error:et};return h?R:v({result:{error:Us},stack:e});function S(A){let{tournamentRecords:P,tournamentId:y,matchUp:E,drawId:U}=A,M=P[y],{drawDefinition:N}=To({tournamentRecord:M,drawId:U});return E.matchUpType===Bt?T({...A,tournamentRecord:M,drawDefinition:N}):Fi({...A,tournamentRecord:M,drawDefinition:N})}function T({removePriorValues:A,tournamentRecords:P,tournamentRecord:y,drawDefinition:E,sourceCourtId:U,courtDayDate:M,matchUpId:N,matchUp:C,courtId:D}){let O=[D].concat(C.schedule.allocatedCourts.map(({courtId:b})=>b).filter(b=>b!==U));return Vp({removePriorValues:A,tournamentRecords:P,tournamentRecord:y,drawDefinition:E,courtDayDate:M,matchUpId:N,courtIds:O})}}function tM({scheduleAttributes:t=[ho,si,bs,Os,_s,So,ci,ai,bi],tournamentRecord:e,drawDefinition:r,matchUpId:n}){let o="clearMatchUpSchedule",i=r?ar({matchUpFilters:{matchUpIds:[n]},inContext:!1,drawDefinition:r}).matchUps?.[0]:pe({matchUpFilters:{matchUpIds:[n]},tournamentRecord:e,inContext:!1}).matchUps?.[0];if(!i)return{error:De};let s=(i.timeItems??[]).filter(a=>a?.itemType&&!t.includes(a?.itemType));return i.timeItems=s,ht({tournamentId:e.tournamentId,context:o,drawDefinition:r,matchUp:i}),{...R}}function eM(t){let{tournamentRecord:e,tournamentId:r,dailyLimits:n}=t,o=t.tournamentRecords||e&&{[e.tournamentId]:e}||{};if(typeof o!="object"||!Object.keys(o).length)return{error:wt};if(typeof n!="object")return{error:Yn};let i=Object.keys(o).filter(s=>!r||r===s);if(r&&!i.includes(r))return{error:G};for(let s of i){let a=o[s],c=gt({element:a,extension:{name:Gc,value:{dailyLimits:n}}});if(c.error)return c}return{...R}}var lM={};ne(lM,{addCollectionDefinition:()=>Gg,addCollectionGroup:()=>cM,aggregateTieFormats:()=>mM,compareTieFormats:()=>Co,getTieFormat:()=>bS,modifyCollectionDefinition:()=>Lg,modifyTieFormat:()=>pM,mutate:()=>dM,orderCollectionDefinitions:()=>aM,query:()=>sP,removeCollectionDefinition:()=>Fg,removeCollectionGroup:()=>iM,tieFormatGenderValidityCheck:()=>Xm,validateCollectionDefinition:()=>du});var dM={};ne(dM,{addCollectionDefinition:()=>Gg,addCollectionGroup:()=>cM,aggregateTieFormats:()=>mM,modifyCollectionDefinition:()=>Lg,modifyTieFormat:()=>pM,orderCollectionDefinitions:()=>aM,removeCollectionDefinition:()=>Fg,removeCollectionGroup:()=>iM});function Qo({drawDefinition:t,structureId:e,matchUpId:r,structure:n,matchUp:o,eventId:i,event:s}){let a="getTieFormat",c;if(e=n?.structureId??e,r=o?.matchUpId??r,(r||e)&&!t)return{error:z};if(i&&s)c=xs(s);else if(r){if(t&&(!o||!n)){let u=xt({drawDefinition:t,matchUpId:r});if(u.error)return u;if(u.matchUp?.matchUpType!==pn)return v({result:{error:ze},stack:a});n||(n=u.structure),o||(o=u.matchUp)}c=ap({item:o,drawDefinition:t,structure:n,event:s})||ap({item:n,drawDefinition:t,structure:n,event:s})||xs(t)||xs(s)}else if(t&&e){if(!n){let u=st({drawDefinition:t,structureId:e});if(u.error)return u;n=u?.structure}c=ap({item:n,drawDefinition:t,structure:n,event:s})||xs(t)||xs(s)}else c=xs(t)||xs(s);return c?{...R,structure:n,tieFormat:c,matchUp:o}:v({result:{error:Va},stack:a})}function Yd({matchUp:t,updateInProgressMatchUps:e}){return!t.winningSide&&![ie].includes(t.matchUpStatus)&&(e||t.matchUpStatus!==Sn&&!he(t))}function oM({from:t,to:e}){let r=Object.keys(t),n=Wt(r,Object.keys(e)).length===r.length,i=r.filter(c=>t[c]!==e[c]).map(c=>({countChange:e[c]-t[c],collectionId:c})),s=r.every(c=>t[c]===e[c]);return{equivalent:n&&s,matchUpsCountChanges:i}}function zv({updateInProgressMatchUps:t,tournamentRecord:e,drawDefinition:r,structure:n,tieFormat:o,eventId:i,matchUp:s,event:a,uuids:c}){let u="updateTieFormat",p=e?.tournamentId,m=0,d=0,l=0,f=0,g=o?.collectionDefinitions.reduce((y,E)=>(y[E.collectionId]=(y[E.collectionId]||0)+E.matchUpCount,y),{}),I=({tieFormat:y})=>{let E=y?.collectionDefinitions.reduce((U,M)=>(U[M.collectionId]=(U[M.collectionId]||0)+M.matchUpCount,U),{});return oM({from:E,to:g}).equivalent},h=Qo({drawDefinition:r})?.tieFormat,S=Qo({event:a})?.tieFormat;if(a&&i){for(let y of a.drawDefinitions??[])T({drawDefinition:y});a.tieFormat=Ke(o),f+=1}else if(s){if(!s.tieMatchUps)return v({result:{error:ze},stack:u});let y=pr(s.tieMatchUps?.map(({collectionId:C})=>C)),E=oM({to:g,from:y}),{changes:U,changesArePossible:M,cannotChangeReaon:N}=Kv({matchUp:s,check:E});if(E.equivalent)if(Yd({matchUp:s,updateInProgressMatchUps:t}))s.tieFormat=Ke(o),f+=1;else return v({result:{error:ul},info:"matchUp is IN_PROGRESS or COMPLETE",stack:u});else if(M)P({tieFormat:o,matchUp:s,changes:U,uuids:c});else return v({context:{collectionMap:g,matchUpMap:y},result:{error:Jo},info:N||"specified changes not possible",stack:u});d+=1,ht({eventId:a?.eventId,context:u,drawDefinition:r,tournamentId:p,matchUp:s})}else if(n){let E=A({inheritedTieFormat:h??S,structure:n})?.modifiedMatchUpsCount;E&&(d+=E,m+=1,f+=1);let U=!n.tieFormat||Co({ancestor:n.tieFormat,descendant:o}).different;U&&(n.tieFormat=Ke(o),m+=1,f+=1),(E||U)&&r&&Rt({structureIds:[n.structureId],eventId:a?.eventId,drawDefinition:r})}else if(r)T({drawDefinition:r}),r.tieFormat=Ke(o),f+=1;else return{error:z};return{modifiedStructuresCount:m,modifiedMatchUpsCount:d,addedMatchUpsCount:l,modifiedCount:f,...R,tieFormat:o};function T({drawDefinition:y}){let E=y.structures||[],U=[];for(let M of E){if(M.tieFormat)continue;let C=A({inheritedTieFormat:S,structure:M})?.modifiedMatchUpsCount;if(C){m+=1,d+=C;let D=M.structureId;U.push(D)}}return Rt({structureIds:U,eventId:a?.eventId,drawDefinition:y}),U.length}function A({inheritedTieFormat:y,structure:E}){let U=0,M=Pt({matchUpFilters:{matchUpTypes:[Bt]},structure:E})?.matchUps||[];for(let N of M){let C=Yd({matchUp:N,updateInProgressMatchUps:t}),D=!1,O=pr(N.tieMatchUps?.map(({collectionId:_})=>_)),b=oM({from:O,to:g});if(b.equivalent)N.tieFormat&&I(N)&&C&&(N.tieFormat=Ke(o),D=!0);else{let{changes:_,changesArePossible:L}=Kv({matchUp:N,check:b});if(L&&!N.tieFormat)P({changes:_,matchUp:N,tieFormat:o,uuids:c});else if(y)(!N.tieFormat||Co({ancestor:y,descendant:N.tieFormat}).different)&&(N.tieFormat=y,D=!0);else return v({result:{error:Va},stack:u})}D&&(U+=1,ht({tournamentId:e?.tournamentId,drawDefinition:r,context:u,eventId:i,matchUp:N}))}return{modifiedMatchUpsCount:U}}function P({uuids:y,matchUp:E,tieFormat:U,changes:M}){E.tieFormat=Ke(U);let N=[],C=[];return M.forEach(D=>{if(D.countChange>0){let O=Math.max(0,...E.tieMatchUps.filter(L=>L.collectionId===D.collectionId).map(Dr("collectionPosition"))),b=U.collectionDefinitions.find(L=>L.collectionId===D.collectionId),_=uu({matchUpsLimit:D.countChange,collectionPositionOffset:O,collectionDefinition:b,matchUp:E,uuids:y});C.push(...J(_,!1,!0)),l+=C.length,E.tieMatchUps.push(..._)}else{let O=D.toBePlayedTieMatchUpIds.slice(0,Math.abs(D.countChange));console.log("remove",O.length),N.push(...O),E.tieMatchUps=E.tieMatchUps.filter(({matchUpId:b})=>!O.includes(b))}}),C.length&&lo({matchUps:C,drawDefinition:r,tournamentId:p,eventId:i}),N.length&&Rn({matchUpIds:N,action:"updateTieFormat",drawDefinition:r,tournamentId:p,eventId:i}),{matchUpIdsRemoved:N,matchUpsAdded:C}}}function Kv({check:t,matchUp:e}){let r="",n=[];return{changesArePossible:t.matchUpsCountChanges.every(({collectionId:i,countChange:s})=>{let a=e.tieMatchUps.filter(u=>u.collectionId===i&&u.matchUpStatus===Kt).map(Dr("matchUpId")),c=a.length+s>=0||s>0;return!c&&s<0&&(r="Insufficient TO_BE_PLAYED matchUps"),n.push({toBePlayedTieMatchUpIds:a,collectionId:i,countChange:s}),c}),changes:n,cannotChangeReaon:r}}function Cu({drawDefinition:t,auditData:e}){let{extension:r}=ut({name:$i,element:t}),n={name:$i,value:Array.isArray(r?.value)?r?.value.concat(e):[e]};gt({element:t,extension:n})}function Lg({updateInProgressMatchUps:t=!1,tournamentRecord:e,collectionOrder:r,collectionName:n,tieFormatName:o,drawDefinition:i,matchUpFormat:s,matchUpCount:a,collectionId:c,matchUpType:u,structureId:p,matchUpId:m,category:d,eventId:l,gender:f,event:g,collectionValueProfiles:I,collectionValue:h,matchUpValue:S,scoreValue:T,setValue:A}){let P="modifyCollectionDefinition";if(s&&!Sr({matchUpFormat:s}))return v({result:{error:G},context:{matchUpFormat:s},stack:P});if(n&&typeof n!="string")return v({result:{error:G},context:{collectionName:n},stack:P});if(f&&!Object.values(wm).includes(f))return v({result:{error:G},context:{gender:f},stack:P});if(d&&typeof d!="object")return v({result:{error:G},context:{category:d},stack:P});let y={collectionValueProfiles:I,collectionValue:h,matchUpValue:S,scoreValue:T,setValue:A};if(!Object.values(y).filter(Boolean).length&&!r&&!n&&!s&&!a&&!u)return v({result:{error:et},stack:P});if(Object.values(y).filter(Boolean).length>1)return v({info:"Only one value assignment allowed per collectionDefinition",result:{error:G},stack:P});let E=Qo({drawDefinition:i,structureId:p,matchUpId:m,eventId:l,event:g});if(E.error)return v({result:E,stack:P});let{matchUp:U,structure:M,tieFormat:N}=E,C=Ke(N),D=N?.collectionDefinitions.find(q=>q.collectionId===c),O=C?.collectionDefinitions.find(q=>q.collectionId===c);if(!D)return v({info:"source collectionDefinition",result:{error:je},context:{collectionId:c},stack:P});let b=h??S??T??A;if(I){let q=$h({matchUpCount:a??D?.matchUpCount??0,collectionValueProfiles:I});if(q.errors)return v({result:{error:G},info:q.errors,stack:P})}else if(b&&!lt(b))return v({result:{error:G},info:"value is not an integer",context:{value:b},stack:P});let _=(q,Y)=>Wt(Object.keys(q),Object.keys(Y)).length===Object.keys(q).length&&Wt(Object.values(q),Object.values(Y)).length===Object.values(q).length,L=I&&(!D.collectionValueProfiles||!_(D.collectionValueProfiles,I)),F=lt(h)&&D.collectionValue!==h||lt(S)&&D.matchUpValue!==S||lt(T)&&D.scoreValue!==T||lt(A)&&D.setValue!==A||L,w=[];if(F&&(O.collectionValueProfiles=void 0,O.collectionValue=void 0,O.matchUpValue=void 0,O.scoreValue=void 0,O.setValue=void 0,Object.assign(O,y),w.push({collectionId:c,...rt(y)})),(lt(T)||lt(A))&&O.collectionGroupNumber){let q=O.collectionGroupNumber;C.collectionDefinitions=C.collectionDefinitions.map(Y=>{let{collectionGroupNumber:k,...K}=Y;return k===q?K:Y}),C.collectionGroups=C.collectionGroups.filter(({groupNumber:Y})=>Y!==q),w.push({collectionId:c,change:"collectionGroupNumber removed"})}let{aggregateValue:x,valueGoal:H}=ps(C),V=rt({aggregateValue:x,valueGoal:H});if((V.aggregateValue!==N?.winCriteria.aggregateValue||V.valueGoal!==N?.winCriteria.valueGoal)&&(C.winCriteria=V,w.push({collectionId:c,winCriteria:V})),lt(r)&&D.collectionOrder!==r&&(O.collectionOrder=r,w.push({collectionId:c,collectionOrder:r})),n&&D.collectionName!==n&&(O.collectionName=n,w.push({collectionId:c,collectionName:n})),s&&D.matchUpFormat!==s&&(O.matchUpFormat=s,w.push({collectionId:c,matchUpFormat:s})),lt(a)&&D.matchUpCount!==a&&(O.matchUpCount=a,w.push({collectionId:c,matchUpCount:a})),u&&D.matchUpType!==u)return v({result:{error:Vu},context:{matchUpType:u},stack:P});d&&D.category!==d&&(O.category=d,w.push({collectionId:c,category:d})),f&&D.gender!==f&&(O.gender=f,w.push({collectionId:c,gender:f}));let W=rt(C);if(E=cr({tieFormat:W}),E.error)return v({result:E,stack:P});if(!w.length)return v({result:{...R,modifications:w}});if(N?.tieFormatName!==o?(W.tieFormatName=o,w.push({tieFormatName:o})):w.length&&(delete W.tieFormatName,w.push("tieFormatName removed: modifications without new tieFormatName")),E=zv({tieFormat:W,updateInProgressMatchUps:t,tournamentRecord:e,drawDefinition:i,structure:M,eventId:l,matchUp:U,event:g}),!E.error){let{appliedPolicies:q}=yt({tournamentRecord:e});if(q?.audit?.[$i]){let Y=rt({collectionDefinition:O,drawId:i?.drawId,action:P,structureId:p,matchUpId:m,eventId:l});Cu({drawDefinition:i,auditData:Y})}}return v({result:{...E,modifications:w},stack:P})}function Qv({updateInProgressMatchUps:t,tournamentRecord:e,drawDefinition:r,targetMatchUps:n,tieFormat:o,event:i}){for(let s of n){let a=!!s.tieFormat;a&&(s.tieFormat=Ke(o));let c;if(t){let u=yt({tournamentRecord:e,drawDefinition:r,event:i}).appliedPolicies,p=En({matchUpId:s.matchUpId,exitWhenNoValues:!0,tournamentRecord:e,appliedPolicies:u,drawDefinition:r,event:i});if(p.error)return p;c=p.score}a&&!c&&ht({tournamentId:e?.tournamentId,context:"updateTargetTeamMatchUps",eventId:i?.eventId,matchUp:s,drawDefinition:r})}return{...R}}function Xv({updateInProgressMatchUps:t,drawDefinition:e,structureId:r,structure:n,matchUpId:o,matchUp:i}){let s=[];return o&&i?s=[i]:r&&n?s=Pt({matchUpFilters:{matchUpTypes:[Bt]},structure:n})?.matchUps??[]:e&&(s=ar({matchUpFilters:{matchUpTypes:[Bt]},drawDefinition:e})?.matchUps??[]),{targetMatchUps:s.filter(c=>!c.winningSide&&c.matchUpStatus!==me&&(t||c.matchUpStatus!==Sn&&!he(c)))}}function UA({updateInProgressMatchUps:t,originalValueGoal:e,tournamentRecord:r,wasAggregateValue:n,tieFormatName:o,drawDefinition:i,structureId:s,structure:a,tieFormat:c,matchUpId:u,matchUp:p,eventId:m,event:d}){let{aggregateValue:l,valueGoal:f}=ps(c);c.winCriteria=rt({aggregateValue:l,valueGoal:f}),(e&&e!==f||l&&!n)&&(o?c.tieFormatName=o:delete c.tieFormatName);let{targetMatchUps:g}=Xv({updateInProgressMatchUps:t,drawDefinition:i,structureId:s,structure:a,matchUpId:u,matchUp:p});Qv({updateInProgressMatchUps:t,tournamentRecord:r,targetMatchUps:g,drawDefinition:i,tieFormat:c,event:d});let I=rt(c),h=cr({tieFormat:I});if(h.error)return h;if(m&&d)d.tieFormat=I;else if(u&&p)p.tieFormat=c;else if(a)a.tieFormat=I;else if(i)i.tieFormat=I;else if(!p||!i)return{error:z};return Rt({drawDefinition:i,eventId:d?.eventId}),{...R}}function iM({updateInProgressMatchUps:t=!0,collectionGroupNumber:e,tournamentRecord:r,drawDefinition:n,tieFormatName:o,structureId:i,matchUpId:s,matchUp:a,eventId:c,event:u}){if(!e)return{error:et};if(isNaN(e))return{error:G};let p="removeCollectionGroup",m=a?void 0:Qo({drawDefinition:n,structureId:i,matchUpId:s,eventId:c,event:u});if(m?.error)return v({result:m,stack:p});let d=m?.structure;a=a??m?.matchUp;let l=m?.tieFormat,f=l?.winCriteria.valueGoal,g=l?.winCriteria.aggregateValue,I=Ke(l);if(m=cr({tieFormat:I}),m.error)return v({result:m,stack:p});let h=[];if(I.collectionDefinitions=I.collectionDefinitions.map(S=>{let{collectionGroupNumber:T,...A}=S;return T!==e?S:(h.push(S.collectionId),A)}),I.collectionGroups=I.collectionGroups.filter(({groupNumber:S})=>S!==e),m=UA({updateInProgressMatchUps:t,originalValueGoal:f,wasAggregateValue:g,tournamentRecord:r,drawDefinition:n,tieFormatName:o,structureId:i,structure:d,tieFormat:I,matchUpId:s,matchUp:a,eventId:c,event:u}),!m.error){let{appliedPolicies:S}=yt({tournamentRecord:r});if(S?.audit?.[$i]){let T=rt({drawId:n?.drawId,collectionGroupNumber:e,action:p,structureId:i,matchUpId:s,eventId:c});Cu({drawDefinition:n,auditData:T})}}return v({result:{...m,modifiedCollectionIds:h},stack:p})}function qd({tieFormat:t,orderMap:e}){let r=Ke(t);return r.collectionDefinitions.forEach(n=>{let o=e[n.collectionId];o&&(n.collectionOrder=o)}),r.collectionDefinitions.sort((n,o)=>ja(n.collectionOrder)-ja(o.collectionOrder)),r}function aM({tournamentRecord:t,drawDefinition:e,structureId:r,matchUpId:n,orderMap:o,eventId:i,matchUp:s,event:a}){if(typeof o!="object"||!Object.values(o).every(c=>lt(c)))return v({result:{error:G},context:{orderMap:o}});if(i&&a?.tieFormat)Jv({tournamentRecord:t,event:a,orderMap:o});else if(n){let c=e&&xt({drawDefinition:e,matchUpId:n});if(c?.error)return c;if(s=c.matchUp,!s)return{error:or};s?.tieFormat&&(s.tieFormat=qd({tieFormat:s.tieFormat,orderMap:o}),ht({tournamentId:t?.tournamentId,eventId:a?.eventId,drawDefinition:e,matchUp:s}))}else if(r){let c=st({drawDefinition:e,structureId:r});if(c.error)return c;let u=c.structure;if(u?.tieFormat)u.tieFormat=qd({tieFormat:u.tieFormat,orderMap:o}),Zv({eventId:a?.eventId,tournamentRecord:t,drawDefinition:e,structure:u,orderMap:o}),Rt({drawDefinition:e,structureIds:[u.structureId]});else if(e.tieFormat)sM({structureIds:[r],tournamentRecord:t,drawDefinition:e,orderMap:o,event:a});else if(a?.tieFormat)Jv({structureIds:[r],tournamentRecord:t,orderMap:o,event:a});else return{error:je}}else if(e?.tieFormat)sM({tournamentRecord:t,drawDefinition:e,orderMap:o,event:a});else return{error:je};return{...R}}function Jv({tournamentRecord:t,structureIds:e,orderMap:r,event:n}){let o=qd({tieFormat:n.tieFormat,orderMap:r});e?.length||(n.tieFormat=o);for(let i of n.drawDefinitions??[])sM({tournamentRecord:t,drawDefinition:i,structureIds:e,orderMap:r,event:n})}function sM({tournamentRecord:t,drawDefinition:e,structureIds:r,orderMap:n,event:o}){let i=e.tieFormat??o?.tieFormat,s=qd({tieFormat:i,orderMap:n});r?.length||(e.tieFormat=s);let a=[];for(let c of e.structures??[])r?.length&&!r.includes(c.structureId)||((c.tieFormat||r?.includes(c.structureId))&&(c.tieFormat=qd({tieFormat:c.tieFormat??e.tieFormat??o?.tieFormat,orderMap:n})),Zv({eventId:o?.eventId,tournamentRecord:t,drawDefinition:e,structure:c,orderMap:n}),a.push(c.structureId));Rt({drawDefinition:e,structureIds:a})}function Zv({tournamentRecord:t,drawDefinition:e,structure:r,orderMap:n,eventId:o}){let i=Pt({matchUpFilters:{matchUpTypes:[Bt]},structure:r})?.matchUps;for(let s of i)s.tieFormat&&(s.tieFormat=qd({tieFormat:s.tieFormat,orderMap:n}),ht({tournamentId:t?.tournamentId,drawDefinition:e,eventId:o,matchUp:s}))}function Fg({updateInProgressMatchUps:t=!0,tieFormatComparison:e,tournamentRecord:r,drawDefinition:n,tieFormatName:o,collectionId:i,structureId:s,matchUpId:a,eventId:c,matchUp:u,event:p}){let m="removeCollectionDefinition",d=u?void 0:Qo({drawDefinition:n,structureId:s,matchUpId:a,eventId:c,event:p});if(d?.error)return v({result:d,stack:m});let l=d?.structure;u=u??d?.matchUp;let f=d?.tieFormat,g=Ke(f);if(d=cr({tieFormat:g}),d.error)return v({result:d,stack:m});let I=g?.collectionDefinitions?.find(N=>N.collectionId===i);if(!I)return v({result:{error:je,collectionId:i}});g.collectionDefinitions=g.collectionDefinitions.filter(N=>N.collectionId!==i),I.collectionGroupNumber&&(g.collectionDefinitions=g.collectionDefinitions.map(N=>{let{collectionGroupNumber:C,...D}=N;return D}),g.collectionGroups=g.collectionGroups.filter(({groupNumber:N})=>N!==I.collectionGroupNumber));let{aggregateValue:h,valueGoal:S}=ps(g);g.winCriteria=rt({aggregateValue:h,valueGoal:S});let T=f?.winCriteria.valueGoal,A=f?.winCriteria.aggregateValue;(T&&T!==S||h&&!A)&&(o?g.tieFormatName=o:delete g.tieFormatName);let P=[];a&&u?P=[u]:s&&l?P=Pt({matchUpFilters:{matchUpTypes:[Bt]},structure:l})?.matchUps??[]:n?P=ar({matchUpFilters:{matchUpTypes:[Bt]},drawDefinition:n})?.matchUps??[]:p&&(P=ro({matchUpFilters:{matchUpTypes:[Bt]},drawDefinition:n})?.matchUps??[]);let y=(P||[]).filter(N=>{let D=N.tieMatchUps?.filter(b=>b.collectionId===i)?.some(he),O=e&&N.tieFormat?Co({descendant:N.tieFormat,ancestor:g})?.different:!1;return t&&!D||!N.winningSide&&N.matchUpStatus!==me&&(t||N.matchUpStatus!==Sn&&!he(N)&&!O)});if(!y.length)return{error:Us};let{appliedPolicies:E}=yt({tournamentRecord:r});if(a&&u&&t){let N=u.tieMatchUps?.filter(C=>C.collectionId===i);for(let C of N??[]){let D=Nu({matchUpId:C.matchUpId,tieMatchUpId:u?.matchUpId,winningSide:void 0,removeScore:!0,tournamentRecord:r,appliedPolicies:E,drawDefinition:n,event:p});if(D.error||(D=xt({drawDefinition:n,matchUpId:a}),D.error))return D;u=D?.matchUp}}let U=[];for(let N of y){for(let C of N?.sides??[])C.lineUp=(C.lineUp??[]).map(D=>({participantId:D.participantId,collectionAssignments:(D?.collectionAssignments??[]).filter(O=>O.collectionId!==i)}));if(N.tieMatchUps=(N.tieMatchUps??[]).filter(C=>{let D=C.collectionId===i;return D&&U.push(C.matchUpId),!D}),N.tieFormat&&(N.tieFormat=Ke(g)),t){let C=En({matchUpId:N.matchUpId,exitWhenNoValues:!0,tournamentRecord:r,appliedPolicies:E,drawDefinition:n,event:p});if(C.error)return C}ht({tournamentId:r?.tournamentId,eventId:p?.eventId,drawDefinition:n,context:m,matchUp:N})}U.length&&Rn({tournamentId:r?.tournamentId,matchUpIds:U,eventId:p?.eventId,drawDefinition:n});let M=rt(g);if(d=cr({tieFormat:M}),d.error)return v({result:d,stack:m});if(c&&p)p.tieFormat=M;else if(a&&u)u.tieFormat=M;else if(l)l.tieFormat=M;else if(n)n.tieFormat=M;else if(!u||!n)return{error:z};if(Rt({drawDefinition:n,eventId:p?.eventId}),E?.audit?.[$i]){let N=rt({drawId:n?.drawId,action:m,collectionId:i,structureId:s,matchUpId:a,eventId:c});Cu({drawDefinition:n,auditData:N})}return{tieFormat:M,deletedMatchUpIds:U,targetMatchUps:y,...R}}function cM({updateInProgressMatchUps:t=!0,tournamentRecord:e,groupDefinition:r,drawDefinition:n,collectionIds:o,tieFormatName:i,structureId:s,matchUpId:a,matchUp:c,eventId:u,event:p}){let m="addCollectionGroup";if(!Array.isArray(o))return v({result:{error:et},stack:m});let d=c?void 0:Qo({drawDefinition:n,structureId:s,matchUpId:a,eventId:u,event:p});if(d?.error)return v({result:d,stack:m});let l=d?.structure;c=c||d?.matchUp;let f=d?.tieFormat,g=f?.winCriteria.valueGoal,I=Ke(f);if(d=cr({tieFormat:I}),d.error)return v({result:d,stack:m});for(let T of I.collectionDefinitions){let{collectionId:A,collectionGroupNumber:P}=T;if(P&&o.includes(A))return v({info:"collectionIds cannot be part of other collectionGroups",result:{error:G},stack:m})}let S=(I.collectionGroups||[]).reduce((T,A)=>A.groupNumber>T?A.groupNumber:T,0)+1;return r.groupNumber=S,I.collectionDefinitions=I.collectionDefinitions.map(T=>o.includes(T.collectionId)?{...T,collectionGroupNumber:S}:T),I.collectionGroups=[...I.collecitonGroups||[],r],UA({updateInProgressMatchUps:t,originalValueGoal:g,tournamentRecord:e,drawDefinition:n,tieFormatName:i,structureId:s,structure:l,tieFormat:I,matchUpId:a,matchUp:c,eventId:u,event:p})}function Gg({updateInProgressMatchUps:t=!0,collectionDefinition:e,referenceCategory:r,tournamentRecord:n,policyDefinitions:o,enforceCategory:i,referenceGender:s,drawDefinition:a,tieFormatName:c,enforceGender:u,structureId:p,matchUpId:m,matchUp:d,eventId:l,uuids:f,event:g}){let I="addCollectionDefinition",h=yt({tournamentRecord:n,drawDefinition:a,event:g}).appliedPolicies??{},S=o?.[qe]??h?.[qe];i=i??S?.participants?.enforceCategory;let T=(u??S?.participants?.enforceGender)!==!1,A=!!((r??g?.category)&&i!==!1),P=!!((s??g?.gender)&&T),y=du({referenceCategory:r??g?.category,collectionDefinition:e,referenceGender:s,checkCategory:A,checkGender:P,event:g});if(y.error)return v({result:y,stack:I});let E=d?.tieFormat?void 0:Qo({drawDefinition:a,structureId:p,matchUpId:m,eventId:l,event:g});if(E?.error)return v({result:{error:E.error},stack:I});let U=E?.structure;d=d??E?.matchUp;let M=d?.tieFormat??E?.tieFormat,N=Ke(M);if(E=cr({tieFormat:N}),E?.error)return v({result:{error:E.error},stack:I});if(!e.collectionId)e.collectionId=Mt();else if(N.collectionDefinitions.map(({collectionId:H})=>H).includes(e.collectionId))return v({context:{collectionId:e.collectionId},result:{error:_y}});N.collectionDefinitions.push(e),N.collectionDefinitions.sort((x,H)=>(x.collectionOrder||0)-(H.collectionOrder||0)).forEach((x,H)=>x.collectionOrder=H+1);let{aggregateValue:C,valueGoal:D}=ps(N);N.winCriteria=rt({aggregateValue:C,valueGoal:D});let O=M?.winCriteria.valueGoal,b=M?.winCriteria.aggregateValue;(O&&O!==D||C&&!b)&&(c?N.tieFormatName=c:delete N.tieFormatName);let _=[],L=[],F=[],w=rt(N);if(E=cr({tieFormat:w}),E?.error)return v({result:{error:E.error},stack:I});if(l&&g){g.tieFormat=w;for(let x of g.drawDefinitions??[])if(!x.tieFormat)for(let H of x.structures??[]){if(H.tieFormat)continue;let V=uM({updateInProgressMatchUps:t,collectionDefinition:e,structure:H,uuids:f});L.push(...V.newMatchUps),F.push(...V.targetMatchUps),_.push(H.structureId)}PA({modifiedMatchUps:F,eventId:g?.eventId,modifiedStructureIds:_,tournamentRecord:n,drawDefinition:a,addedMatchUps:L,stack:I})}else if(p&&U){U.tieFormat=w;let x=uM({updateInProgressMatchUps:t,collectionDefinition:e,structure:U,uuids:f});L.push(...x.newMatchUps),F=x.targetMatchUps,PA({modifiedMatchUps:F,eventId:g?.eventId,modifiedStructureIds:_,tournamentRecord:n,drawDefinition:a,addedMatchUps:L,stack:I})}else if(m&&d){if(!Yd({matchUp:d,updateInProgressMatchUps:t}))return v({result:{error:ul},stack:I});d.tieFormat=w;let x=uu({collectionDefinition:e,matchUp:d,uuids:f});Array.isArray(d.tieMatchUps)||(d.tieMatchUps=[]),d.tieMatchUps.push(...x),L.push(...x),PA({modifiedMatchUps:[d],eventId:g?.eventId,modifiedStructureIds:_,tournamentRecord:n,drawDefinition:a,addedMatchUps:L,stack:I})}else if(a){a.tieFormat=w;for(let x of a.structures??[]){let H=uM({updateInProgressMatchUps:t,collectionDefinition:e,structure:x,uuids:f});_.push(x.structureId),L.push(...H.newMatchUps),F.push(...H.targetMatchUps)}PA({modifiedMatchUps:F,eventId:g?.eventId,tournamentRecord:n,drawDefinition:a,addedMatchUps:L,stack:I})}else return{error:z};if(h?.audit?.[$i]){let x=rt({drawId:a?.drawId,collectionDefinition:e,action:I,structureId:p,matchUpId:m,eventId:l});Cu({drawDefinition:a,auditData:x})}return{tieFormat:w,targetMatchUps:F,addedMatchUps:L,...R}}function uM({updateInProgressMatchUps:t,collectionDefinition:e,structure:r,uuids:n}){let o=[],s=(Pt({matchUpFilters:{matchUpTypes:[Bt]},structure:r})?.matchUps).filter(a=>Yd({matchUp:a,updateInProgressMatchUps:t})&&!a.tieFormat);for(let a of s){let c=uu({collectionDefinition:e,matchUp:a,uuids:n});Array.isArray(a.tieMatchUps)||(a.tieMatchUps=[]),a.tieMatchUps.push(...c),o.push(...c)}return{newMatchUps:o,targetMatchUps:s}}function PA({modifiedStructureIds:t,tournamentRecord:e,modifiedMatchUps:r,drawDefinition:n,addedMatchUps:o,eventId:i,stack:s}){lo({tournamentId:e?.tournamentId,matchUps:o,drawDefinition:n,eventId:i}),r?.forEach(a=>{ht({tournamentId:e?.tournamentId,drawDefinition:n,context:s,matchUp:a,eventId:i})}),Rt({structureIds:t,drawDefinition:n,eventId:i})}function pM({updateInProgressMatchUps:t=!1,tieFormatComparison:e,modifiedTieFormat:r,tournamentRecord:n,drawDefinition:o,structureId:i,matchUpId:s,eventId:a,uuids:c,event:u}){let p="modifyTieFormat";if(!cr({tieFormat:r}).valid)return v({result:{error:Jo},info:"falied validation",stack:p});let m=Qo({drawDefinition:o,structureId:i,matchUpId:s,eventId:a,event:u});if(m.error)return v({result:m,stack:p});let{matchUp:d,tieFormat:l}=m,f=Ke(l),g=Co({descendant:r,ancestor:f});if(g.invalid)return v({context:{invalid:g.invalid},result:{error:Jo},stack:p});if(!g?.different)return v({result:{...R},info:"Nothing to do",stack:p});let I=f.collectionDefinitions.map(({collectionId:M})=>M),h=r.collectionDefinitions.map(({collectionId:M})=>M),S=I.filter(M=>!h.includes(M)),T=r.collectionDefinitions.filter(({collectionId:M})=>!I.includes(M)),A=T.map(Dr("collectionId")),P=[],y,E=r.tieFormatName;for(let M of r.collectionDefinitions){if(A.includes(M.collectionId))continue;let N=Lg({updateInProgressMatchUps:t,...M,tournamentRecord:n,tieFormatName:E,drawDefinition:o,structureId:i,matchUpId:s,eventId:a,event:u});if(N.modifications&&P.push(...N.modifications),N.error)return v({result:N,stack:p});N.tieFormat&&(y=N.tieFormat)}for(let M of T){let N=Gg({updateInProgressMatchUps:t,collectionDefinition:M,tournamentRecord:n,drawDefinition:o,tieFormatName:E,structureId:i,matchUpId:s,matchUp:d,eventId:a,uuids:c,event:u});if(N.error)return v({result:N,stack:p});N.tieFormat&&(y=N.tieFormat)}for(let M of S){let N=Fg({updateInProgressMatchUps:t,tieFormatComparison:e,tournamentRecord:n,drawDefinition:o,tieFormatName:E,collectionId:M,structureId:i,matchUpId:s,eventId:a,matchUp:d,event:u});if(N.error)return v({result:N,stack:p});N.tieFormat&&(y=N.tieFormat)}return l?.tieFormatName!==E?(y.tieFormatName=E,P.push({tieFormatName:E})):(P.length||A.length||S.length)&&(delete y.tieFormatName,P.push("tieFormatName removed: modifications without new tieFormatName")),y.collectionDefinitions=y.collectionDefinitions.sort((M,N)=>ja(M.collectionOrder)-ja(N.collectionOrder)).map((M,N)=>({...M,collectionOrder:N+1})),{processedTieFormat:Ke(y),modifications:P,...R}}function mM({tournamentRecord:t}){if(!t)return{error:j};let e=0;for(let r of t.events??[]){let n=r.tieFormats??[],o=p=>{if(!p.tieFormat)return;let m;for(let d of n)Co({descendant:p.tieFormat,ancestor:d}).different||(m=d.tieFormatId);if(m)p.tieFormatId=m,delete p.tieFormat;else{let d=J(p.tieFormat,void 0,!0);d.tieFormatId||(d.tieFormatId=Mt()),p.tieFormatId=d.tieFormatId,delete p.tieFormat,n.push(d),e+=1}},i=r.eventType;o({tieFormat:r.tieFormat,eventType:i});for(let p of r.drawDefinitions??[]){o({tieFormat:p.tieFormat,eventType:i});for(let m of p.structures??[])o({tieFormat:m.tieFormat,eventType:i})}let s=(p,m)=>{let d=c.matchUps?.find(l=>l.matchUpId===p);d&&(d.tieFormatId=m,delete d.tieFormat,ht({tournamentId:t?.tournamentId,eventId:r.eventId,matchUp:d}))},a=p=>{let m=J(p.tieFormat,void 0,!0);m.tieFormatId||(m.tieFormatId=Mt()),n.push(m),e+=1,s(p.matchUpId,m.tieFormatId)},c=ro({matchUpFilters:{matchUpTypes:[pn]},event:r}),u=c.matchUps??[];for(let p of u){let m;for(let d of n)p.tieFormat&&Co({descendant:p.tieFormat,ancestor:d}).different||(m=d.tieFormatId);m?s(p.matchUpId,m):a(p)}n.length&&(r.tieFormats=n)}return{...R,addedCount:e}}var EM={};ne(EM,{addDrawDefinitionExtension:()=>$u,addEventExtension:()=>po,addEventTimeItem:()=>xi,addExtension:()=>gt,addNotes:()=>hp,addOnlineResource:()=>gM,addParticipantExtension:()=>tE,addParticipantTimeItem:()=>Vf,addTimeItem:()=>li,addTournamentExtension:()=>Bl,addTournamentTimeItem:()=>vi,analyzeDraws:()=>fu,analyzeTournament:()=>RS,getAllowedDrawTypes:()=>pd,getAllowedMatchUpFormats:()=>DS,getAppliedPolicies:()=>yt,getCompetitionDateRange:()=>dd,getCompetitionPenalties:()=>MS,getPolicyDefinitions:()=>Io,getTournamentInfo:()=>us,getTournamentPenalties:()=>md,getTournamentPersons:()=>CS,getTournamentStructures:()=>Rh,getTournamentTimeItem:()=>nu,mutate:()=>yM,query:()=>oP,removeDrawDefinitionExtension:()=>eE,removeEventExtension:()=>Ku,removeExtension:()=>rr,removeNotes:()=>RU,removeParticipantExtension:()=>rE,removeTournamentExtension:()=>Hl,setTournamentCategories:()=>SM,setTournamentDates:()=>kg,setTournamentEndDate:()=>AM,setTournamentName:()=>IM,setTournamentNotes:()=>hM,setTournamentStartDate:()=>TM,setTournamentStatus:()=>fM});var yM={};ne(yM,{addDrawDefinitionExtension:()=>$u,addEventExtension:()=>po,addEventTimeItem:()=>xi,addExtension:()=>gt,addNotes:()=>hp,addOnlineResource:()=>gM,addParticipantExtension:()=>tE,addParticipantTimeItem:()=>Vf,addTimeItem:()=>li,addTournamentExtension:()=>Bl,addTournamentTimeItem:()=>vi,removeDrawDefinitionExtension:()=>eE,removeEventExtension:()=>Ku,removeExtension:()=>rr,removeNotes:()=>RU,removeParticipantExtension:()=>rE,removeTournamentExtension:()=>Hl,setTournamentCategories:()=>SM,setTournamentDates:()=>kg,setTournamentEndDate:()=>AM,setTournamentName:()=>IM,setTournamentNotes:()=>hM,setTournamentStartDate:()=>TM,setTournamentStatus:()=>fM});var yV="ABANDONED",EV="ACTIVE",UV="CANCELLED",PV="COMPLETED",NV="IN_PROGRESS",NA={ABANDONED:yV,ACTIVE:EV,CANCELLED:UV,COMPLETED:PV,IN_PROGRESS:NV};function fM({tournamentRecord:t,status:e}){return t?e&&!Object.keys(NA).includes(e)?{error:G,info:"Unknown status"}:(t.tournamentStatus=e,{...R}):{error:j}}function gM({tournamentRecord:t,onlineResource:e,organisationId:r,participantId:n,personId:o,courtId:i,venueId:s}){if(!t)return{error:j};if(!Ct(e))return{error:et};if(Wt(Object.keys(e),["resourceSubType","resourceType","identifier"]).length!==3)return v({result:{error:Yn},context:{onlineResource:e}});if(r){if(t.parentOrganisation?.parentOrganisationId!==r)return v({result:{error:je}});t.parentOrganisation.onlineResources||(t.parentOrganisation.onlineResources=[]),t.parentOrganisation.onlineResources.push(e)}else if(n||o){let a=(t.participants??[]).find(c=>o&&c.person?.personId===o||c.participantId===n);if(!a)return o?v({result:{error:je}}):v({result:{error:Jt}});if(o){if(a.person?.personId!==o)return v({result:{error:As}});a.person.onlineResources||(a.person.onlineResources=[]),a.person.onlineResources.push(e)}else a.onlineResources||(a.onlineResources=[]),a.onlineResources.push(e)}else if(i){let a=(t.venues??[]).filter(c=>!s||c.venueId===s).flatMap(c=>(c.courts??[]).filter(u=>u.courtId===i))?.[0];if(!a)return v({result:{error:Ha}});a.onlineResources||(a.onlineResources=[]),a.onlineResources.push(e)}else if(s){let a=(t.venues??[]).find(c=>c.venueId===s);if(!a)return v({result:{error:Es}});a.onlineResources||(a.onlineResources=[]),a.onlineResources.push(e)}else t.onlineResources||(t.onlineResources=[]),t.onlineResources.push(e);return{...R}}function IM({tournamentRecord:t,promotionalName:e,tournamentName:r,formalName:n}){return t?(r&&(t.tournamentName=r),e&&(t.promotionalName=e),n&&(t.formalName=n),t.promotionalName===t.tournamentName&&delete t.promotionalName,t.formalName===t.tournamentName&&delete t.formalName,{...R}):{error:j}}function hM({tournamentRecord:t,notes:e}){return t?hp({element:t,notes:e}):{error:j}}function SM({tournamentRecord:t,categories:e}){return t?(e=(e||[]).filter(r=>r.categoryName&&r.type),t.tournamentCategories=e,{...R}):{error:j}}function tx({tournamentRecord:t}){if(!t)return{error:j};let{startDate:e,endDate:r}=t,n=vc(e,r),o=[];for(let i of t.venues||[])i?.courts?.length&&o.push(...i.courts);for(let i of o){let{startTime:s,endTime:a}=(i.dateAvailability??[]).reduce((p,m)=>{let d=Gt(p.startTime),l=Gt(p.endTime);return m.startTime&&Gt(m.startTime)<d&&(p.startTime=m.startTime),m.endTime&&Gt(m.endTime)>l&&(p.endTime=m.endTime),p},{startTime:"08:00",endTime:"18:00"}),c=n.map(p=>i.dateAvailability?.find(d=>d.date===p)??{date:p,startTime:s,endTime:a}),u=i.dateAvailability?.find(p=>!p.date);u&&c.unshift(u),i.dateAvailability=c}return{...R}}function kg({tournamentRecord:t,startDate:e,endDate:r}){if(!t)return{error:j};if(e&&!ao.test(e)||r&&!ao.test(r))return{error:ir};if(!e&&!r)return{error:al};if(r&&e&&new Date(r)<new Date(e))return{error:G};let n;(e&&t.startDate&&new Date(e)>new Date(t.startDate)||r&&t.endDate&&new Date(r)<new Date(t.endDate))&&(n=!0),e&&(t.startDate=e),r&&(t.endDate=r),e&&t.endDate&&new Date(e)>new Date(t.endDate)&&(t.endDate=e),r&&t.startDate&&new Date(r)<new Date(t.startDate)&&(t.startDate=r);let o=n&&DV({tournamentRecord:t})?.unscheduledMatchUpIds;return tx({tournamentRecord:t}),Tt({topic:NE,payload:{startDate:e,endDate:r}}),{...R,unscheduledMatchUpIds:o}}function TM({tournamentRecord:t,startDate:e}){return kg({tournamentRecord:t,startDate:e})}function AM({tournamentRecord:t,endDate:e}){return kg({tournamentRecord:t,endDate:e})}function DV({tournamentRecord:t}){let e=pe({tournamentRecord:t}).matchUps??[],r=t.startDate&&new Date(t.startDate),n=t.endDate&&new Date(t.endDate),o=[],i=[];for(let s of e){let{schedule:a,matchUpId:c}=s;if(a&&a.scheduledDate){let u=new Date(a.scheduledDate);(r&&u<r||n&&u>n)&&(i.push(c),o.includes(a.scheduledDate)||o.push(a.scheduledDate))}}return o.length&&!Wp({scheduledDates:o,tournamentRecord:t}).clearedScheduleCount?{error:FA}:{unscheduledMatchUpIds:i}}var _M={};ne(_M,{addCourt:()=>Hd,addCourts:()=>Og,addVenue:()=>nc,deleteCourt:()=>RM,deleteVenue:()=>MA,deleteVenues:()=>PM,disableCourts:()=>NM,disableVenues:()=>DM,enableCourts:()=>MM,enableVenues:()=>CM,generate:()=>UM,generateCourts:()=>yg,getCompetitionVenues:()=>Pp,getCourts:()=>YS,getVenuesAndCourts:()=>oo,modifyCourt:()=>Bg,modifyCourtAvailability:()=>Vg,modifyVenue:()=>bM,mutate:()=>OM,publicFindVenue:()=>uh,query:()=>SP});var UM={};ne(UM,{generateCourts:()=>yg});var OM={};ne(OM,{addCourt:()=>Hd,addCourts:()=>Og,addVenue:()=>nc,deleteCourt:()=>RM,deleteVenue:()=>MA,deleteVenues:()=>PM,disableCourts:()=>NM,disableVenues:()=>DM,enableCourts:()=>MM,enableVenues:()=>CM,modifyCourt:()=>Bg,modifyCourtAvailability:()=>Vg,modifyVenue:()=>bM});function $d(t){if(!t?.tournamentRecord&&!Array.isArray(t?.venueMatchUps))return{error:j};if(!t?.courtId)return{error:Ti};let{scheduleVisibilityFilters:e,tournamentRecord:r,matchUpFilters:n,venueMatchUps:o,courtId:i}=t,{schedulingProfile:s}=Ro({tournamentRecord:r});if(Array.isArray(o))return{matchUps:u({matchUps:o,courtId:i})};let{matchUps:a}=pe({scheduleVisibilityFilters:e,tournamentRecord:r,matchUpFilters:n});return{matchUps:u({matchUps:a,courtId:i})};function u({matchUps:p,courtId:m}){let d=p.filter(l=>{let f=l.schedule?.allocatedCourts?.map(({courtId:g})=>g);return l.schedule?.courtId===m||f?.includes(m)});return gd({matchUps:d,schedulingProfile:s})}}function ex({scheduleVisibilityFilters:t,tournamentRecord:e,matchUpFilters:r,venueId:n}){if(!e)return{error:j};if(!n)return{error:vo};let{schedulingProfile:o}=Ro({tournamentRecord:e}),{matchUps:i}=pe({scheduleVisibilityFilters:t,tournamentRecord:e,matchUpFilters:r});return{matchUps:a({matchUps:i,venueId:n})};function a({matchUps:c,venueId:u}){let p=c.filter(m=>{let d=m.schedule?.allocatedCourts?.map(({venueId:l})=>l);return m.schedule?.venueId===u||d?.includes(u)});return gd({matchUps:p,schedulingProfile:o})}}function Vg({tournamentRecord:t,dateAvailability:e,disableNotice:r,venueMatchUps:n,courtId:o,force:i}){if(!t)return{error:j};if(!o)return{error:Ti};let s=dA({dateAvailability:e});if(s.error)return s;let{updatedDateAvailability:a,totalMergeCount:c}=MV(e);e=a;let u=Zi({tournamentRecord:t,courtId:o});if(u.error)return u;let{court:p,venue:m}=u,{matchUps:d}=$d({tournamentRecord:t,venueMatchUps:n,courtId:o});if(d?.length){let l=yt({tournamentRecord:t})?.appliedPolicies,f=i??l?.[uo]?.allowDeletionWithScoresPresent?.courts,g=[];g.length&&(f||console.log("throw error: scheduled court matchUps",g.length))}return p&&(p.dateAvailability=e,!r&&m&&Tt({payload:{venue:m,tournamentId:t.tournamentId},topic:ni,key:m.venueId})),{...R,totalMergeCount:c}}function MV(t){let e=0,r=t.reduce((o,i)=>{let{date:s,startTime:a,endTime:c,bookings:u}=i;return o[s]||(o[s]=[]),o[s].push({startTime:a,endTime:c,bookings:u}),o},{}),n=[];return Object.keys(r).forEach(o=>{r[o].sort(Fv);let{mergedAvailability:i,mergeCount:s}=CV(r[o]);n.push(...i.map(a=>({date:o,...a}))),e+=s}),{updatedDateAvailability:n,totalMergeCount:e}}function CV(t){let e,r,n,o=t.length,i=0,s=[];for(;t.length&&o;){let c=t.shift(),{startTime:u,endTime:p,bookings:m}=c;if(o-=1,!e)e=u,n=m,r=p;else if(ea(xe(r),xe(u),!1)>0){let l={startTime:e,endTime:r};n?.length&&(l.bookings=n),s.push(l),e=u,n=m,r=p}else m&&(n?n.push(m):n=m),r=p,i+=1}let a={startTime:e,endTime:r};return n?.length&&(a.bookings=n),s.push(a),{mergedAvailability:s,mergeCount:i}}function Kd({matchUpsCount:t=0}){let r=`Schedule would be deleted from ${t} ${t===1?"matchUp":"matchUps"}; use { force: true }`;return{error:Fy,info:r}}function DA({tournamentRecord:t,drawDefinition:e,matchUpId:r,drawId:n}){let o="removeCourtAssignment";if(!r)return{error:Ne};if(!e&&!n)return{error:Ur};let i;if(!e){if(!t)return{error:j};({drawDefinition:e}=nr({tournamentRecord:t,drawId:n}))}if(e)({matchUp:i}=xt({drawDefinition:e,matchUpId:r}));else{if(!t)return{error:j};let s=pe({tournamentRecord:t,inContext:!1}).matchUps??[];({matchUp:i}=Yh({matchUps:s,matchUpId:r}))}return i?(i.timeItems&&i.timeItems.find(a=>[si,ho].includes(a.itemType))&&(i.timeItems=i.timeItems.filter(({itemType:a})=>![si,ho].includes(a)),ht({tournamentId:t?.tournamentId,context:o,drawDefinition:e,matchUp:i})),{...R}):{error:De}}function MA(t){if(typeof t?.venueId!="string")return{error:vo};let{tournamentRecord:e,venueId:r,force:n}=t,o=t.tournamentRecords||e&&{[e.tournamentId]:e}||{};if(!Object.keys(o).length)return{error:j};let s=nn({tournamentRecords:o,contextFilters:{venueIds:[r]}}).matchUps??[],a=yt({tournamentRecord:e})?.appliedPolicies,c=n??a?.[uo]?.allowDeletionWithScoresPresent?.venues;if(!s.length||c)for(let u of Object.values(o)){for(let m of s){let d=DA({matchUpId:m.matchUpId,drawId:m.drawId,tournamentRecord:u});if(d.error)return d}let p;u.venues=(u.venues??[]).filter(m=>m?.venueId!==r?!0:(p=!0,!1)),p&&Tt({payload:{venueId:r,tournamentId:u.tournamentId},topic:Xl,key:r})}else return Kd({matchUpsCount:s.length});return hc({tournamentRecords:o}),{...R}}function PM({tournamentRecord:t,venueIds:e,force:r}){if(!t)return{error:j};if(!Array.isArray(e))return{error:G};for(let n of t.venues||[]){let{venueId:o}=n;if(e.includes(o)){let{venueId:i}=n,s=MA({tournamentRecord:t,venueId:i,force:r});if(s.error)return s}}return{...R}}function NM(t){let{courtIds:e,dates:r}=t,n=jr(t),o=[{[ye]:!0,[Yu]:!0}],i=vt(t,o);if(i.error)return i;for(let s of Object.values(n))RV({tournamentRecord:s,courtIds:e,dates:r});return{...R}}function RV({tournamentRecord:t,courtIds:e,dates:r}){let n=Array.isArray(r)&&r.length?{dates:r}:!0,o=i=>gt({extension:{value:n,name:Gn},creationTime:!1,element:i});for(let i of t.venues||[])for(let s of i.courts||[])if(e?.includes(s.courtId)){let a=o(s);if(a.error)return a}return{...R}}function DM(t){let{tournamentRecords:e,tournamentId:r,venueIds:n}=t,o=[{[ye]:!0,[qu]:!0}],i=vt(t,o);if(i.error)return i;let s=Object.keys(e).filter(a=>!r||a===r);for(let a of s){let c=e[a];bV({tournamentRecord:c,venueIds:n})}return{...R}}function bV({tournamentRecord:t,venueIds:e}){for(let r of t.venues||[])if(e?.includes(r.venueId)){let n=gt({creationTime:!1,element:r,extension:{name:Gn,value:!0}});if(n.error)return n}return{...R}}function MM(t){let e=jr(t),r=[{[ye]:!0}];!t.enableAll&&r.push({[Yu]:!0});let n=vt(t,r);if(n.error)return n;let{enableAll:o,courtIds:i,dates:s}=t;for(let a of Object.values(e))OV({tournamentRecord:a,courtIds:i,enableAll:o,dates:s});return{...R}}function OV({tournamentRecord:t,courtIds:e,enableAll:r,dates:n}){for(let o of t.venues||[])for(let i of o.courts||[])if(r||e?.includes(i.courtId))if(Array.isArray(n)){let{extension:s}=ut({element:i,name:Gn});if(s){let a=s.value;Array.isArray(a.dates)&&(a.dates=a.dates.filter(c=>!n.includes(c))),gt({extension:{name:Gn,value:a},creationTime:!1,element:i})}}else rr({element:i,name:Gn});return{...R}}function CM(t){let e=jr(t),r=[{[ye]:!0}];!t.enableAll&&r.push({[qu]:!0});let n=vt(t,r);if(n.error)return n;let{venueIds:o,enableAll:i}=t;for(let s of Object.values(e))for(let a of s.venues||[])(i||o?.includes(a.venueId))&&rr({element:a,name:Gn});return{...R}}function RM(t){let{courtId:e,disableNotice:r,force:n}=t,o=jr(t),i=vt(t,[{[ye]:!0,[PI]:!0}]);if(i.error)return i;let s,a;for(let c of Object.values(o)){if(a=_V({tournamentRecord:c,disableNotice:r,courtId:e,force:n}),a.error&&a.error!==Ha)return a;a.success&&(s=!0)}return s?{...R}:a}function _V({tournamentRecord:t,disableNotice:e,courtId:r,force:n}){let o=Zi({tournamentRecord:t,courtId:r});if(o.error)return o;let i=o.venue,{matchUps:s}=$d({tournamentRecord:t,courtId:r}),a=yt({tournamentRecord:t})?.appliedPolicies,c=n??a?.[uo]?.allowDeletionWithScoresPresent?.courts;if(!s?.length||c){for(let u of s??[]){let p=DA({matchUpId:u.matchUpId,drawId:u.drawId,tournamentRecord:t});if(p.error)return p}i&&(i.courts=(i.courts??[]).filter(u=>u.courtId!==r),e||Tt({payload:{venue:i,tournamentId:t.tournamentId},topic:ni,key:i.venueId}))}else return Kd({matchUpsCount:s.length});return{...R}}function Bg(t){let{disableNotice:e,modifications:r,courtId:n,force:o,venueMatchUps:i}=t,s=jr(t);if(!Object.keys(s).length)return{error:wt};let a,c;for(let u of Object.values(s)){let p=vV({tournamentRecord:u,disableNotice:e,venueMatchUps:i,modifications:r,courtId:n,force:o});if(p?.error)return p;a=!0}return a?{...R}:c}function vV({tournamentRecord:t,disableNotice:e,venueMatchUps:r,modifications:n,courtId:o,force:i}){if(!t)return{error:j};if(!o)return{error:Ti};if(!n||typeof n!="object")return{error:Yn};let s=Zi({tournamentRecord:t,courtId:o});if(s.error)return s;let{venue:a,court:c}=s,u=Object.keys(Lv()).filter(l=>l!=="courtId");if(!Object.keys(n).filter(l=>u.includes(l)).length)return{error:ku};let m=u.filter(l=>!["dateAvailability"].includes(l)),d=Object.keys(n).filter(l=>m.includes(l));if(c&&d.forEach(l=>Object.assign(c,{[l]:n[l]})),n.dateAvailability){let l=Vg({dateAvailability:n.dateAvailability,tournamentRecord:t,venueMatchUps:r,disableNotice:e,courtId:o,force:i});if(l.error)return l}return e||Tt({payload:{venue:a,tournamentId:t.tournamentId},topic:ni,key:a?.venueId}),{...R,court:J(c)}}var xV=()=>({venueId:void 0,venueName:"",venueAbbreviation:"",onlineResources:[],venueType:void 0,addresses:[],contacts:[],courts:[],roles:[]}),rx=xV;function bM(t){let{modifications:e,venueId:r,force:n}=t,o=jr(t);if(!Object.keys(o).length)return{error:wt};if(typeof r!="string")return{error:vo};let i,s;for(let a of Object.values(o)){let c=wV({tournamentRecord:a,modifications:e,venueId:r,force:n});if(c.success&&(s=!0),c.error&&(i=c.error),c.error&&c.error!==Es)return c}return hc({tournamentRecords:o}),s?{...R}:{error:i}}function wV({tournamentRecord:t,modifications:e,venueId:r,force:n}){if(!t)return{error:j};if(!e||typeof e!="object")return{error:Yn};if(!r)return{error:vo};let o=yt({tournamentRecord:t})?.appliedPolicies,i=n??o?.[uo]?.allowDeletionWithScoresPresent?.venues,{matchUps:s}=ex({tournamentRecord:t,venueId:r}),a=jo({tournamentRecord:t,venueId:r});if(a.error)return a;let c=a.venue,u=Object.keys(rx()).filter(h=>h!=="venueId");if(!Object.keys(e).filter(h=>u.includes(h)).length)return{error:ku};let m=u.filter(h=>!["courts","onlineResources"].includes(h)),d=Object.keys(e).filter(h=>m.includes(h));c&&d.forEach(h=>Object.assign(c,{[h]:e[h]}));let l=c?.courts?.map(h=>h.courtId)??[],f=e.courts?.map(h=>h.courtId)||[],g=f.length&&l.filter(h=>!f.includes(h)),I=[];if(g.length){let S=c?.courts?.filter(T=>g.includes(T.courtId))?.map(T=>{let A=$d({courtId:T.courtId,tournamentRecord:t,venueMatchUps:s});for(let P of A.matchUps??[])I.push({matchUpId:P.matchUpId,drawId:P.drawId});return A.matchUps?.length??0}).reduce((T,A)=>T+A);if(c&&(!S||i))c.courts=c.courts?.filter(T=>f.includes(T.courtId)),Mu({schedule:{courtId:"",scheduledDate:""},matchUpDetails:I,removePriorValues:!0,tournamentRecord:t});else return Kd({matchUpsCount:S})}if(e.courts)for(let h of e.courts){let{courtId:S}=h||{},T=Bg({modifications:h,disableNotice:!0,tournamentRecord:t,venueMatchUps:s,courtId:S,force:n});if(T.error===Ha&&(T=Hd({disableNotice:!0,tournamentRecord:t,venueId:r,court:h})),T.error)return T}return hc({tournamentRecord:t}),c&&Tt({payload:{venue:c,tournamentId:t.tournamentId},topic:ni,key:c?.venueId}),{...R,venue:J(c)}}var vM={};ne(vM,{JSON2CSV:()=>ix,UUID:()=>Mt,UUIDS:()=>cR,allNumeric:()=>uI,attributeFilter:()=>Di,chunkArray:()=>Ae,chunkByNth:()=>Pl,chunkSizeProfile:()=>Wy,constantToString:()=>Be,countValues:()=>rC,createMap:()=>AI,dateTime:()=>fC,definedAttributes:()=>rt,dehydrateMatchUps:()=>ox,extractAttributes:()=>Xy,flattenJSON:()=>RA,generateDateRange:()=>vc,generateHashCode:()=>hC,generateRange:()=>Z,generateTimeCode:()=>AA,groupValues:()=>By,hasAttributeValues:()=>IC,instanceCount:()=>pr,intersection:()=>Wt,isConvertableInteger:()=>lt,isNumeric:()=>se,isOdd:()=>aI,isPowerOf2:()=>gn,makeDeepCopy:()=>J,matchUpSort:()=>mi,nearestPowerOf2:()=>tm,nextPowerOf2:()=>Bi,noNulls:()=>eC,noNumeric:()=>pI,numericSort:()=>oe,occurrences:()=>nC,overlap:()=>ve,randomMember:()=>en,randomPop:()=>Rr,shuffleArray:()=>sr,structureSort:()=>ri,subSort:()=>oC,undefinedToNull:()=>TI,unique:()=>mt,visualizeScheduledMatchUps:()=>nx});function nx({scheduledMatchUps:t,showGlobalLog:e}){OR();let r=t?.reduce((o,{structureId:i})=>o.includes(i)?o:o.concat(i),[]),n=Array.isArray(r)&&{...r.map(o=>{let{structureName:i,matchUpType:s}=t.find(a=>a.structureId===o);return{[o]:`${i} ${s}`}})};r?.forEach(o=>{vn({color:"blue",method:"draw",structure:n[o],keyColors:{structure:"magenta"}},!0);let i=t.filter(a=>a.structureId===o),s=Xe({matchUps:i})?.roundMatchUps||[];Object.keys(s).forEach(a=>{vn({roundNumber:a,keyColors:{roundNumber:"brightcyan"}},!0),s[a].forEach(({matchUpId:c,schedule:u})=>{let p=qt(u.scheduledTime);vn({matchUpId:c,time:p,date:u.scheduledDate,venue:u.venueId,keyColors:{time:"brightcyan",date:"brightcyan",matchUpId:"yellow",venue:"magenta"}},!0)})})}),e&&bR()}function ox({tournamentRecord:t}){if(!t)return{error:j};if(typeof t!="object"||!t.tournamentId)return{error:G};let{matchUps:e}=pe({tournamentRecord:t,inContext:!1});if(e?.length){let r=LV({tournamentRecord:t});GV(e,r)}return{...R}}function LV({tournamentRecord:t}){let e={};for(let r of t.events||[]){r.matchUpFormat&&(e[r.eventId]=r.matchUpFormat);for(let n of r.drawDefinitions||[]){n.matchUpFormat&&(e[n.drawId]=n.matchUpFormat);for(let o of n.structures||[]){o.matchUpFormat&&(e[o.structureId]=o.matchUpFormat);for(let i of o.structures||[])i.matchUpFormat&&(e[i.structureId]=i.matchUpFormat)}}}return e}var FV=["collectionId","collectionPosition","drawPositions","extensions","finishingPositionRange","finishingRound","isMock","matchUpId","matchUpStatus","matchUpStatusCodes","orderOfFinish","processCodes","roundNumber","tieFormat","tieMatchUps","roundPosition","score","sides","winnerMatchUpId","loserMatchUpId","matchUpDuration","winningSide"];function GV(t,e={}){for(let r of t){let{structureId:n,drawId:o,eventId:i}=r,s=e[n]||e[o]||e[i],a=r.matchUpFormat===s?void 0:r.matchUpFormat;for(let c of Object.keys(r))FV.includes(c)||delete r[c];r.sides&&r.drawPositions&&!r.tieMatchUps&&delete r.sides,a&&(r.matchUpFormat=a)}}function ix(t,e){if(e&&typeof e!="object")return{error:G};let{columnTransform:r={}}=e||{},{includeTransformAccessors:n,includeHeaderRow:o=!0,returnTransformedJSON:i,removeEmptyColumns:s,onlyHeaderRow:a,columnAccessors:c=[],functionMap:u={},columnMap:p={},valuesMap:m={},context:d={},delimiter:l='"',columnJoiner:f=",",rowJoiner:g=`\r
24
+ `,keyJoiner:I="."}=e||{};if(!Array.isArray(t)||!Array.isArray(c)||typeof d!="object"||typeof p!="object"||typeof r!="object"||typeof u!="object"||typeof m!="object"||typeof f!="string"||typeof g!="string"||typeof I!="string"||typeof l!="string")return{error:G};r=Object.assign({},...Object.keys(r).reverse().map(b=>({[b]:Array.isArray(r[b])?r[b]:[typeof r[b]=="string"&&r[b]].filter(Boolean)})));let h=t.filter(Boolean).map(b=>RA(b,I)),S=Object.values(r).flat();n&&c.push(...S);let T=h.reduce((b,_)=>Object.keys(_).every(L=>!b.includes(L)&&b.push(L)||!0)&&b,[]).filter(b=>!c?.length||c.includes(b)),A=Object.assign({},...Object.keys(r).reverse().map(b=>r[b].map(_=>({[_]:b})).flat()).flat()),P=(b,_)=>e?.sortOrder?e.sortOrder.includes(b)&&e.sortOrder.includes(_)&&e.sortOrder.indexOf(b)-e.sortOrder.indexOf(_)||!e.sortOrder.includes(_)&&-1:0,y=T.reduce((b,_)=>{let L=A[_];return L?b.includes(L)||b.push(L):b.push(_),b},[]).sort(P);Object.keys(p).forEach(b=>!y.includes(b)&&y.unshift(b)),Object.keys(r).forEach(b=>!y.includes(b)&&y.unshift(b)),typeof d=="object"&&Object.keys(d).forEach(b=>!y.includes(b)&&y.unshift(b));let E=y.map(b=>p[b]||b);if(a)return[E];let U=b=>`${l}${b}${l}`,M=[],N=b=>Object.values(y.reduce((_,L,F)=>{let w=r[L],x=(w?.length?b[w.find(W=>b[W])]:b[L])||d?.[L]||"",H=m[L]?.[x]||x,V=typeof u[L]=="function"?u[L](H):H;return _[L]=U(V),V&&(M[F]=(M[F]||0)+1),_},{})),C=h.map(N),D=s&&[...M].map((b,_)=>!b&&_).filter(se).reverse();if(D){let b=_=>_.filter((L,F)=>!D.includes(F));C=C.map(b),E=b(E)}let O=C.map(b=>b.join(f));return i?O.map(b=>{let _=b.split(f);return Object.assign({},..._.map((L,F)=>({[E[F]]:L})))}):o?[E.map(U).join(f),...O].join(g):O.join(g)}function RA(t,e=".",r=[]){return typeof t=="object"&&Object.keys(t).reduce((n,o)=>typeof t[o]!="object"?(n[r.concat(o).join(e)]=t[o],n):Object.assign(n,RA(t[o],e,r.concat(o))),{})}var kV={};function Ru(t){let{mutationStatus:e,tournamentId:r,directives:n,timeStamp:o}=t||{},{topics:i}=Fr();for(let s of[...i].sort(ax)){let a=mI({topic:s});a&&em({topic:s,notices:a})}e&&o&&i.includes(Am)&&em({notices:[{tournamentId:r,directives:n,timeStamp:o}],topic:Am})}async function bA(t){let{mutationStatus:e,tournamentId:r,directives:n,timeStamp:o}=t||{},{topics:i}=Fr();for(let s of[...i].sort(ax)){let a=mI({topic:s});a&&await em({topic:s,notices:a})}e&&o&&i.includes(Am)&&em({notices:[{tournamentId:r,directives:n,timeStamp:o}],topic:Am})}var sx={[sf]:5,[of]:5,[af]:5,[nf]:5,[rf]:5,[tf]:5,[UE]:5,[PE]:5,[ef]:1,[rp]:1,[$e]:5,[ni]:5,[Zl]:4,[Ql]:4,[Xl]:4,[Jl]:4,[ep]:3,[Kl]:2};function ax(t,e){return(sx[e]||0)-(sx[t]||0)}var{FACTORY:cx}=OI;function ux({tournamentRecord:t,value:e}){let{extension:r}=ut({element:t,name:cx}),n={name:cx,value:{...r?.value,...e}};gt({element:t,extension:n})}function bu({timeStamp:t}){let e=Eo(),r=Ml();return r&&Object.values(e).forEach(n=>{ux({tournamentRecord:n,value:{version:xa(),timeStamp:t}})}),r}function OA({engineType:t,methodName:e,elapsed:r,params:n,result:o}){let i=Tr();if(typeof i!="object")return;let s={method:e},a=o?.error&&(i.errors===!0||Array.isArray(i.errors)&&i.errors.includes(e)),c=Array.isArray(i.params)&&i.params?.includes(e),u=i.params&&!Array.isArray(i.params)||c,p=Array.isArray(i.exclude)&&i.exclude.includes(e);!p&&![void 0,!1].includes(i.perf)&&!isNaN(i.perf)&&r>=i.perf&&(s.elapsed=r),!p&&(a||u)&&(s.params=n),!p&&(a||i.result&&!Array.isArray(i.result)&&(!Array.isArray(i.params)||c)||Array.isArray(i.result)&&i.result?.includes(e))&&(s.result=o),Object.keys(s).length>1&&zy(s,t)}function _a({methodName:t,params:e,start:r}){let n={error:Wa,methodName:t},o=r?Date.now()-r:0;return OA({result:n,methodName:t,elapsed:o,params:e,engineType:"sync"}),n}function px(t,e){if(e._middleware===!1)return e;if(e.tournamentId&&!t[e.tournamentId])return{error:j};let r=e.drawId||e.matchUp?.drawId;if(r){let{event:i,drawDefinition:s,tournamentId:a}=nr({tournamentRecords:t,drawId:r});s&&(e.drawDefinition=s),a&&(e.tournamentId=a),i&&(e.event=i)}if(e.eventId&&!e.event){let{event:i,tournamentId:s}=nr({eventId:e.eventId,tournamentRecords:t});if(!i)return{error:Ir};e.tournamentId=s,e.event=i}let n=e.tournamentId??Hi();if(!n&&e)return e;let o=t[n];return n&&!o?{error:j}:(o&&(e.tournamentRecord=o),e)}function va(t,e,r,n,o){delete t.success,delete t.error;let i=Date.now(),s=Hi();r&&(r.activeTournamentId=s);let a=r?.tournamentRecord||Rl(s),c=typeof r?.tournamentRecord=="object"&&{[r?.tournamentRecord.tournamentId]:r.tournamentRecord}||Eo(),u=r?J(r,void 0,!0):void 0,p=r?px(c,r):void 0;if(p?.error)return p;let m=VV({params:p,tournamentRecords:c,tournamentRecord:a,methodName:n,method:e}),d=Date.now()-i;return OA({result:m,methodName:n,elapsed:d,params:u,engineType:o}),m}function VV({tournamentRecords:t,tournamentRecord:e,params:r,methodName:n,method:o}){if(Tr())return o({tournamentRecords:t,tournamentRecord:e,...r});try{return o({tournamentRecords:t,tournamentRecord:e,...r})}catch(i){return Wu({engineName:"engine",methodName:n,params:r,err:i})}}function mx({convertExtensions:t,removeExtensions:e}){let r=Eo();return{tournamentId:Hi(),tournamentRecords:J(r,t,!1,e)}}function dx(t){let{convertExtensions:e=!1,removeExtensions:r=!1}=t??{},n=t?.tournamentId??Hi();if(typeof n!="string")return{};let o=Rl(n);return{tournamentRecord:J(o,e,!1,r)}}function lx(){let t=Eo(),{extension:e}=ut({name:sa,tournamentRecords:t,discover:!0}),r=e?.value?.tournamentIds||[];return Object.keys(t).forEach(n=>{r.includes(n)||delete t[n]}),rm(t)}function xM(t,e=!0){return typeof t!="object"||Array.isArray(t)?{error:Yn}:t?.tournamentId?$y(e?J(t):t):{error:G}}function gs(t,e=!0){if(typeof t!="object")return{error:Yn};if(Hu(),Array.isArray(t)){if(!(t.filter(n=>n?.tournamentId).length===t.length))return{error:$g};t=Object.assign({},...t.map(n=>({[n.tournamentId]:n})))}else if(t?.tournamentId)t={[t.tournamentId]:t},Hu(t.tournamentId);else if(!Object.keys(t).every(n=>t[n].tournamentId===n))return{error:$g};return rm(e?J(t):t)}async function fx(t,e,r){if(!Array.isArray(e))return{error:G,message:"directives must be an array"};let n=Cl(),o=Date.now(),i=r&&J(Eo(),!1,!0),s=[];for(let p of e){if(typeof p!="object")return{error:G,message:"directive must be an object"};let{method:m,pipe:d}=p,l=p.params?{...p.params}:{};if(!n[m])return _a({methodName:m,start:o,params:l});if(d){let g=s[s.length-1],I=Object.keys(d);for(let h of I)g[h]&&(l[h]=g[h])}let f=va(t,n[m],l,m,"async");if(f?.error)return i&&gs(i),{...f,rolledBack:!!i};s.push({...f,methodName:m})}let a=Date.now(),c=bu({timeStamp:a});return bA({directives:e,mutationStatus:c,timeStamp:a}),yi(),{success:s.every(p=>p.success),results:s}}async function wM(t,e){if(!Ct(e))return{error:G,message:"args must be an object"};let r=Object.values(e).filter(xo).length;if(r>1)return{message:"there must be only one arg with typeof function",error:G};let n=r?Object.keys(e).find(l=>xo(e[l])):er(e.method)&&e.method;if(!n)return{error:Wa};let{[n]:o,...i}=e,s=e?.params?{...e.params}:{...i},a=s.rollbackOnError&&J(Eo(),!1,!0),c=o||t[n]||Bu()[n];if(!c)return _a({methodName:n,params:s});let u=await va(t,c,s,n,"async")??{};u?.error&&a&&gs(a);let p=Date.now(),m=bu({timeStamp:p}),d=u?.success&&s?.delayNotify!==!0&&s?.doNotNotify!==!0;return d&&await bA({directives:[{method:c,params:s}],mutationStatus:m,timeStamp:p}),(d||!u?.success||s?.doNotNotify)&&yi(),u}function gx(t,e,r,n,o){if(!Ct(r))return{error:G};let i=Array.isArray(n)?n:[],s={},a=(u,p=0)=>{Object.keys(u).forEach(m=>{xo(u[m])?s[m]=u[m]:Ct(u[m])&&(n===!0||i?.includes(m))&&(o===void 0||p<o)&&a(u[m],p+1)})};return a(r),qy(s),Object.keys(s).filter(u=>xo(s[u])).forEach(u=>{t[u]=p=>{let m=()=>e(t,{[u]:s[u],...p});if(Tr())return m();try{return m()}catch(d){Wu({engineName:"engine",methodName:u,params:p,err:d})}}}),{...R,...t}}function $p(t,e){return e?.error?(t.error=e.error,t.success=!1):(t.error=void 0,t.success=!0),t}function zd(t,e){t.importMethods=(r,n,o)=>gx(t,e,r,n,o),t.getTournament=r=>dx(r),t.getState=r=>mx({convertExtensions:r?.convertExtensions,removeExtensions:r?.removeExtensions}),t.version=()=>xa(),t.reset=()=>(rm({}),$p(t)),t.devContext=r=>(bc(r),$p(t)),t.getDevContext=r=>Tr(r),t.newTournamentRecord=(r={})=>{let n=eA(r),o=n.tournamentId;return n.error?n:(xM(n),Hu(o),{...R,tournamentId:o})},t.setState=(r,n,o)=>{Oc(n,o);let i=gs(r,n);return $p(t,i)},t.setTournamentId=r=>Hu(r),t.getTournamentId=()=>Hi(),t.setTournamentRecord=(r,n,o)=>{Oc(n,o);let i=xM(r,n);return $p(t,i)},t.removeTournamentRecord=r=>{let n=Ky(r);return $p(t,n)},t.removeUnlinkedTournamentRecords=()=>{let r=lx();return $p(t,r)}}function BV(t){let e=jy();if(e.error&&!t)return e;let r={executionQueue:(n,o)=>fx(r,n,o),execute:n=>wM(r,n)};return zd(r,wM),r}function Ix(t,e,r){if(!Array.isArray(e))return{error:G,message:"directives must be an array"};let n=Cl(),o=Date.now(),i=r&&J(Eo(),!1,!0),s=[];for(let p of e){if(typeof p!="object")return{error:G,message:"directive must be an object"};if(p.params&&typeof p.params!="object")return{error:G,message:"params must be an object"};let{method:m,pipe:d}=p,l=p.params?{...p.params}:{};if(!n[m])return _a({methodName:m,start:o,params:l});if(d){let g=s[s.length-1],I=Object.keys(d);for(let h of I)g[h]&&(l[h]=g[h])}let f=va(t,n[m],l,m,"sync");if(f?.error)return i&&gs(i),{...f,rolledBack:!!i};s.push({...f,methodName:m})}let a=Date.now(),c=bu({timeStamp:a});return Ru({directives:e,mutationStatus:c,timeStamp:a}),yi(),{success:s.every(p=>p.success),results:s}}function LM(t,e){if(!Ct(e))return{error:G,message:"args must be an object"};let r=Object.values(e).filter(xo).length;if(r>1)return{message:"there must be only one arg with typeof function",error:G};let n=r?Object.keys(e).find(l=>xo(e[l])):er(e.method)&&e.method;if(!n)return{error:Wa};let{[n]:o,...i}=e,s=e?.params?{...e.params}:{...i},a=s.rollbackOnError&&J(Eo(),!1,!0),c=o||t[n]||Bu()[n];if(!c)return _a({methodName:n,params:s});let u=va(t,c,s,n,"sync")??{};u?.error&&a&&gs(a);let p=Date.now(),m=bu({timeStamp:p}),d=u?.success&&s?.delayNotify!==!0&&s?.doNotNotify!==!0;return d&&Ru({directives:[{method:c,params:s}],mutationStatus:m,timeStamp:p}),(d||!u?.success||s?.doNotNotify)&&yi(),u}var hx=(()=>{let t={executionQueue:(e,r)=>Ix(t,e,r),execute:e=>LM(t,e)};return zd(t,LM),t})(),Kp=hx;function FM(t,e){if(!Ct(e))return{error:G,message:"args must be an object"};let r=Object.values(e).filter(xo).length;if(r>1)return{message:"there must be only one arg with typeof function",error:G};let n=r?Object.keys(e).find(c=>xo(e[c])):er(e.method)&&e.method;if(!n)return{error:Wa};let{[n]:o,...i}=e,s=e?.params?{...e.params}:{...i},a=o||t[n]||Bu()[n];return a?va(t,a,s,n,"ask"):_a({methodName:n,params:s})}var HV=(()=>{let t={execute:e=>FM(t,e)};return zd(t,FM),t})();var zp={},Nc;function GM(t,e=!0){if(!t)return{error:et};if(typeof t!="object")return{error:Yn};if(t.matchUpId)Nc=t.matchUpId,zp[Nc]=e?J(t):t;else if(Array.isArray(t))for(let r of t.reverse())r.matchUpId&&(zp[r.matchUpId]=e?J(r):r,Nc||(Nc=r.matchUpId));else for(let r of Object.values(t))r.matchUpId&&(zp[r.matchUpId]=e?J(r):r,Nc||(Nc=r.matchUpId));return e?J(t):t}function Sx(){return zp[Nc]}function Tx(){return Object.values(zp)}function Ax(){Nc=void 0,zp={}}function yx(t){return J(zp[Nc],t?.convertExtensions,!1,t?.removeExtensions)}var WV=(()=>{let t={getState:o=>yx(o),version:()=>xa(),reset:()=>(Ax(),{...R}),drawId:void 0,error:void 0,success:!1,devContext:o=>(bc(o),t),setState:(o,i,s)=>{Oc(i,s);let a=GM(o);return e(a)}};function e(o){return o?.error?(t.error=o.error,t.success=!1):(t.error=void 0,t.success=!0,t.drawId=o.drawId),t}return r([lg]),t;function r(o){o.forEach(i=>{Object.keys(i).forEach(s=>{t[s]=a=>{if(Tr())return n({params:a,governor:i,methodName:s});try{return n({params:a,governor:i,methodName:s})}catch(c){Wu({engineName:"matchUpEngine",methodName:s,params:a,err:c})}}})})}function n({params:o,governor:i,methodName:s}){t.error=void 0,t.success=!1;let a=o?.matchUp||Sx(),c=o?.matchUps||Tx(),u=o?.rollbackOnError&&J(a,!1,!0);o={...o,matchUpId:a?.matchUpId,matchUps:c,matchUp:a};let p=i[s](o);if(p?.error)return u&&GM(u),{...p,rolledBack:!!u};let m=p?.success&&o?.delayNotify!==!0&&o?.doNotNotify!==!0;return m&&Ru(),(m||!p?.success||o?.doNotNotify)&&yi(),p}})();var kM=!1,jV=(()=>{let t={version:()=>xa(),setDeepCopy:(n,o)=>(Oc(n,o),t),devContext:n=>(bc(n),kM=!0,t)};return r([xg]),t;function e(n,o){let i=n({...o});return i?.error||Ru(),yi(),kM&&(bc(!1),kM=!1),i}function r(n){n.forEach(o=>{Object.keys(o).forEach(i=>{t[i]=s=>{try{let a=e(o[i],s);return!a?.error&&s?.setState&&a?.tournamentRecord&&gs(a.tournamentRecord),a}catch(a){let c;typeof a=="string"?c=a.toUpperCase():a instanceof Error&&(c=a.message),console.log("ERROR",{params:JSON.stringify(s),method:i,error:c})}}})})}})();Kp.importMethods(CA,!0,1);var YV=Kp,qV=Kp;function _A(t,e){return t&&e&&Array.isArray(e)&&e[t-1]||typeof e=="object"&&e[t]}function Ex(t){let{participation:e={},awardProfiles:r,startDate:n,eventType:o,drawSize:i,drawType:s,category:a,endDate:c,level:u}=t,{participationOrder:p,flightNumber:m,rankingStage:d}=e,l=g=>!n&&!c||!g.dateRanges?!0:g.dateRanges.some(I=>{let h=!n||!I.startDate||new Date(n)>new Date(I.startDate),S=!c||!I.endDate||new Date(c)<=new Date(I.endDate);return h&&S});return{awardProfile:r.find(g=>l(g)&&(!g.maxFlightNumber||m<=g.maxFlightNumber)&&(!g.drawTypes?.length||g.drawTypes?.includes(s))&&(!g.drawSizes?.length||g.drawSizes.includes(i))&&(!g.stages?.length||g.stages.includes(d))&&(!g.levels?.length||g.levels.includes(u))&&(!g.maxDrawSize||i<=g.maxDrawSize)&&(!g.drawSize||g.drawSize===i)&&(!g.maxLevel||u<=g.maxLevel)&&(!m||!g.flights?.flightNumbers?.length||g.flights.flightNumbers.includes(m))&&(!g.participationOrder||g.participationOrder===p)&&(!g.category?.ageCategoryCodes||g.category.ageCategoryCodes.includes(a?.ageCategoryCode))&&(!g.eventTypes?.length||g.eventTypes?.includes(o)))}}function VM({participantWon:t,flightNumber:e,valueObj:r,drawSize:n,flights:o,level:i}){let s=(f,g)=>{if(f){if(Array.isArray(g)){let I=g.find(h=>h.flight===f||h.f===f);return I.value||I.v}if(typeof g=="object"){let I=g.flights||g.f;if(Array.isArray(I))return I[f-1]}}},a=(f,g)=>{let I=f?.value||f?.v||(lt(f)?f:0),h=_A(i,f?.level);return{value:s(g,h)||lt(h)&&h||I}},c=0,u,p,m,d,l=t&&"won"||t===!1&&"lost"||void 0;if(Array.isArray(r)){let f=r.find(h=>h.drawSize===n||h.drawSizes?.includes(n)),g=r.find(h=>h.drawSize&&h.threshold&&n>h.drawSize),I=r.find(h=>!h.drawSize&&!h.drawSizes?.length);l!==void 0&&(f=f?.[l],g=g?.[l],I=I?.[l]),p=a(f,e).value,m=a(g,e).value,d=a(I,e).value,c=p||m||d,u=p&&f.requireWin||m&&g.requireWin||I?.requireWin}else if(typeof r=="object"){let f=r?.drawSizes?.[n],g=r;l!==void 0&&(f=f?.[l],g=g?.[l]),p=a(f,e).value,d=a(g,e).value,c=p||d,u=p?f.requireWin:g?.requireWin}else lt(r)&&l===void 0&&(c=r);return e&&o?.pct?.[e]&&(c=Math.round(c*o.pct[e])),{awardPoints:c,requireWin:u}}function Ux({participantFilters:t,policyDefinitions:e,tournamentRecord:r,saveRankings:n,level:o}){if(!r)return{error:j};let{policyDefinitions:i}=Io({policyTypes:[Vl],tournamentRecord:r}),s=e?.[Vl]??i?.[Vl];if(!s)return{error:xu};let a=s.awardProfiles,c=s.requireWinFirstRound,u=s.requireWinForPoints,{participants:p,derivedEventInfo:m,derivedDrawInfo:d,mappedMatchUps:l}=$t({withRankingProfile:!0,participantFilters:t,tournamentRecord:r}),f=p?.filter(S=>S.draws?.length),g={},I={},h={};for(let S of f??[]){let{participantType:T,participantId:A,person:P,draws:y}=S;for(let E of y){let{drawId:U,structureParticipation:M,eventId:N}=E,C=m[N],D=d[U],O=D?.drawType,{category:b,eventType:_}=C||{},L=E.startDate||C.startDate||r.startDate,F=E.endDate||C.endDate||r.endDate;if(_===Kr&&A!==Yr)continue;let w;if(a){let x=u,H=0,V=0,W=0,B;for(let q of M){let{finishingPositionRange:Y,participationOrder:k,participantWon:K,flightNumber:X,rankingStage:$,winCount:nt}=q;H+=nt||0;let Q=D?.drawSize,{awardProfile:it}=Ex({awardProfiles:a,participation:q,eventType:_,startDate:L,category:b,drawSize:Q,drawType:O,endDate:F,level:o});if(it){if(!Q)continue;let ot=Array.isArray(Y)&&Math.max(...Y),dt=mt(Y||[]).join("-"),zt=ot&&$!==at&&Y?.includes(Q);it.requireWinForPoints!==void 0&&(x=it.requireWinForPoints),it.requireWinFirstRound!==void 0&&(c=it.requireWinFirstRound);let{finishingPositionPoints:Et={},finishingPositionRanges:ge,finishingRound:Ee,pointsPerWin:Ce,flights:Xt}=it,Ue=Array.isArray(it.perWinPoints)?it.perWinPoints?.find(Ft=>Ft.participationOrders?.includes(k)):it.perWinPoints,Ht=Et.participationOrders,Ie=0,Nt;if((!Ht||Ht.includes(k))&&ge&&ot){let Ft=ge[ot];Ft&&({awardPoints:Ie,requireWin:Nt}=VM({flightNumber:X,valueObj:Ft,drawSize:Q,flights:Xt,level:o}))}if(!Ie&&Ee&&k===1&&ot){let Ft=Ee[ot];Ft&&({awardPoints:Ie,requireWin:Nt}=VM({participantWon:K,flightNumber:X,valueObj:Ft,drawSize:Q,flights:Xt,level:o}))}if(zt&&c!==void 0&&(x=c),Nt!==void 0&&(x=Nt),Ie>V&&(!x||nt)&&(V=Ie,B=ot),!Ie&&Ce&&nt&&(W+=nt*Ce,B=dt),!Ie&&nt&&Ue){let Ft=_A(o,Ue?.level);Ft?W+=nt*Ft:Ue.value&&(W+=nt*Ue.value)}}if(w=V+W,T===Yr){let ot=(S.matchUps||[]).filter(({structureId:dt})=>dt===q.structureId);for(let{matchUpId:dt}of ot){let zt=l[dt],Et=zt.sides.find(ge=>ge.participantId===A).sideNumber;if(zt.winningSice===Et)for(let ge of zt.tieMatchUps)ge.winningSide}}}if(W||V){let q={winCount:H,positionPoints:V,rangeAccessor:B,perWinPoints:W,eventType:_,drawId:U,points:w},Y=P?.personId;Y?(g[Y]||(g[Y]=[]),g[Y].push(q)):T===pt?(h[A]||(h[A]=[]),h[A].push(q)):T===Yr&&(I[A]||(I[A]=[]),I[A].push(q))}}}}return n&&gt({element:r,extension:{name:oE,value:{personPoints:g,teamPoints:I,pairPoints:h}}}),{participantsWithOutcomes:f,personPoints:g,pairPoints:h,teamPoints:I,...R}}var $V={getTournamentPoints:Ux},Px=$V;var KV=t=>250/Math.pow(t+5,.4),zV=()=>1;function QV(t=3,e=2){let r=t/e;return isNaN(r)?Qd.kDefault():r}var Qd={nSpread:400,diffThreshold:.125,kCalc:KV,kMultiplier:QV,kDefault:zV};function vA(t){let{winnerRating:e,loserRating:r,ratingRange:n}=t,{ratings:o=Jr,winnerCountables:i=1,loserCountables:s=0,ratingType:a=Hs,maxCountables:c,countables:u}=t||{},p=o?.[a];if(!p)return{error:et};n=p.range||n,e=e||p.defaultInitialization,r=r||p.defaultInitialization;let m=n[0]>n[1],d=p.decimalsCount||0,l=m?n.slice().reverse():n,f=(F,w)=>parseFloat(w)>=Math.min(...F)&&parseFloat(w)<=Math.max(...F);(!f(n,e)||!f(n,r))&&(f(n,e)||(e=p.defaultInitialization),f(n,r)||(r=p.defaultInitialization));let g=({value:F,sourceRange:w,targetRange:x})=>(F-w[0])*(x[1]-x[0])/(w[1]-w[0])+x[0],I=g({targetRange:Jr[Hs].range,sourceRange:l,value:m?n[0]-e:e}),h=g({targetRange:Jr[Hs].range,sourceRange:l,value:m?n[0]-r:r}),S=(F,w)=>1/(1+Math.pow(10,(w-F)/Qd.nSpread)),T=S(I,h),A=S(h,I),P=Qd.kCalc(i),y=Qd.kCalc(s),E=Qd.kMultiplier(c,u),U=I+E*P*(1-T),M=h+E*y*(0-A),N=g({sourceRange:Jr[Hs].range,value:U,targetRange:l}),C=g({sourceRange:Jr[Hs].range,value:M,targetRange:l}),D=m?n[0]-N:N,O=parseFloat(parseFloat(D).toFixed(d)),b=m?n[0]-C:C,_=parseFloat(parseFloat(b).toFixed(d)),L=Math.max(...n)?Math.abs(e-r)/Math.max(...n):0;return(N>C&&L>Qd.diffThreshold||O<0||_<0)&&(O=e,_=r),{newWinnerRating:O,newLoserRating:_}}var Nx=t=>t?.reduce((e,r)=>(r.winningSide&&(e[r.winningSide-1]+=1),e),[0,0])||[0,0];function Dx({removePriorValues:t=!0,tournamentRecord:e,ratingType:r=Hs,considerGames:n,matchUpIds:o,asDynamic:i}){if(!e)return{error:j};if(!Array.isArray(o))return{error:wn};if(typeof r!="string")return{error:G,ratingType:r};if(!Jr[r])return{error:G};let s=Jr[r],{accessor:a}=s,c={},u=pe({matchUpFilters:{matchUpIds:o,matchUpStatuses:ie},tournamentRecord:e,inContext:!0}).matchUps??[];u.sort(mi);for(let m of u){let{endDate:d,matchUpFormat:l,score:f,sides:g,winningSide:I}=m,h=m.matchUpType,S={eventType:h,scaleName:r,scaleType:Yi},T=`${r}.${MI}`,A={scaleName:T,eventType:h,scaleType:Yi},P=Object.assign({},...(g??[]).map(_=>{let{sideNumber:L,participant:F}=_;return L&&{[L]:[F?.participantId,...F?.individualParticipantIds??[]].filter(Boolean).flat()}})),y=i?T:r,E=Object.assign({},...Object.values(P).flat().map(_=>{let{scaleItem:L}=gc({scaleAttributes:A,tournamentRecord:e,participantId:_}),{scaleItem:F}=gc({tournamentRecord:e,scaleAttributes:S,participantId:_}),w=a?{[a]:void 0}:void 0;return _&&{[_]:L??F??{scaleName:y,eventType:h,scaleDate:d,scaleType:Yi,scaleValue:w}}})),U=l?Ze(l):{},M=U?.bestOf||1,N=U?.setsTo||1,C=n?M&N:M,D=f?.sets&&Nx(f.sets)||I===1&&[1,0]||[0,1],O=I?P[I]:[],b=I?P[3-I]:[];for(let _ of O){let L=E[_]?.scaleValue,F=typeof L=="object"?L[a]:L;for(let w of b){let x=E[w]?.scaleValue,H=typeof x=="object"?x[a]:x,V=I?D[I]:[0,0],W=I?D[3-I]:[0,0],{newWinnerRating:B,newLoserRating:q}=vA({winnerCountables:V,loserCountables:W,maxCountables:C,winnerRating:F,loserRating:H,ratingType:r}),Y=a?{...L,[a]:B}:B,k=a?{...x,[a]:q}:q;E[_].scaleValue=Y,E[w].scaleValue=k;let K=Oa({participantId:_,removePriorValues:t,tournamentRecord:e,scaleItem:{...E[_],scaleName:y}});if(K.error||(K=Oa({participantId:w,removePriorValues:t,tournamentRecord:e,scaleItem:{...E[w],scaleName:y}}),K.error))return K}}Object.assign(c,E)}let p=u.map(({matchUpId:m})=>m);return{...R,modifiedScaleValues:c,processedMatchUpIds:p}}var XV={calculateNewRatings:vA,generateDynamicRatings:Dx},Mx=XV;var JV={...Px,...Mx};Kp.importMethods(JV);var ZV=Kp;var Cx={[wc]:{roundsToSeparate:void 0,policyName:"Nationality Code",policyAttributes:[{key:"person.nationalityCode"},{key:"individualParticipants.person.nationalityCode"}]}};var Rx={[Xn]:{policyName:"positionActionsUnrestricted",enabledStructures:[],otherFlightEntries:!0,disableRoundRestrictions:!0,activePositionOverrides:[Vs,Ap]}};var bx={[Xn]:{policyName:"positionActionsNoMovement",enabledStructures:[{stages:[],stageSequences:[],enabledActions:[Vs,Iu,Bs],disabledActions:[]}]}};var Ox={[Xn]:{policyName:"positionActionsDisabled",enabledStructures:!1}};var _x={[Ka]:{policyName:"Participant Privacy Policy",participant:{contacts:!1,individualParticipants:{onlineResources:!1,participantName:!0,participantOtherName:!0,participantId:!0,participantRole:!0,participantStatus:!0,penalties:!1,representing:!0,participantRoleResponsibilities:!1,participantType:!0,person:{addresses:!1,biographicalInformation:!1,birthDate:!1,contacts:!1,nationalityCode:!0,nativeFamilyName:!1,nativeGivenName:!1,onlineResources:!1,otherNames:!0,parentOrganisationId:!1,passportFamilyName:!1,passportGivenName:!1,personId:!1,personOtherIds:!1,previousNames:!1,sex:!1,standardFamilyName:!0,standardGivenName:!0,status:!1,tennisId:!1,wheelchair:!0}},individualParticipantIds:!0,onlineResources:!1,participantName:!0,participantOtherName:!0,participantId:!0,participantRole:!0,participantStatus:!0,penalties:!1,representing:!0,participantRoleResponsibilities:!1,participantType:!0,person:{addresses:!1,biographicalInformation:!1,birthDate:!1,contacts:!1,nationalityCode:!0,nativeFamilyName:!1,nativeGivenName:!1,onlineResources:!1,otherNames:!0,parentOrganisationId:!1,passportFamilyName:!1,passportGivenName:!1,personId:!1,personOtherIds:!1,previousNames:!1,sex:!1,standardFamilyName:!0,standardGivenName:!0,status:!1,tennisId:!1,wheelchair:!0}}}};var vx={[Mn]:{defaultMatchUpFormat:on,allowDeletionWithScoresPresent:{drawDefinitions:!1,structures:!1},requireAllPositionsAssigned:!1,processCodes:{incompleteAssignmentsOnDefault:["RANKING.IGNORE"]},stage:{[tt]:{stageSequence:{1:{requireAllPositionsAssigned:!0}}}}}};var xx={[Mn]:{requireAllPositionsAssigned:!1,stage:{[tt]:{stageSequence:{1:{requireAllPositionsAssigned:!0}}}},defaultMatchUpFormat:on,matchUpFormats:[{description:"Best of 3 tiebreak sets",matchUpFormat:on,categoryNames:[],categoryTypes:[]},{description:"Two tiebreak sets, 7-point match tiebreak at one set all",matchUpFormat:"SET3-S:6/TB7-F:TB7"},{description:"Two tiebreak sets, 10-point match tiebreak at one set all",matchUpFormat:"SET3-S:6/TB7-F:TB10"},{description:"One standard tiebreak set to 6, 7-point tiebreak at 6 games all",matchUpFormat:"SET1-S:6/TB7"},{description:"Best of 3 sets to 4",matchUpFormat:"SET3-S:4/TB7"},{description:"Two out of three short sets to 4 with 5-point tiebreak at 3 games all",matchUpFormat:"SET3-S:4/TB5@3"},{description:"One short set to 4, 7-point tiebreak at 4 games all",matchUpFormat:"SET1-S:4/TB7"},{description:"One short set to 4, 5-point tiebreak at 3 games all",matchUpFormat:"SET1-S:4/TB5@3"},{description:"Two short sets to 4, 10-point match tiebreak at one set all",matchUpFormat:"SET3-S:4/TB7-F:TB10"},{description:"Two short sets to 4, 7-point match tiebreak at one set all",matchUpFormat:"SET3-S:4/TB7-F:TB7"},{description:"One no advantage set to 5, tiebreak to 9 at 4-4",matchUpFormat:"SET1-S:5/TB9@4"},{description:"One set to 6 with deciding game at 5 games all",matchUpFormat:"SET1-S:6NOAD"},{description:"One short set to 4, deciding game is played at 3 games all",matchUpFormat:"SET1-S:4NOAD"},{description:"Two short sets to 4 with deciding game at 3-3, 7-point match tiebreak at one set all",matchUpFormat:"SET3-S:4NOAD-F:TB7"},{description:"8 game pro-set with 7 point tiebreak at 8 games all",matchUpFormat:"SET1-S:8/TB7"},{description:"8 game pro-set with 7 point tiebreak at 7 games all",matchUpFormat:"SET1-S:8/TB7@7"},{description:"Best of 3 10-point tiebreak games",matchUpFormat:"SET3-S:TB10"},{description:"One 10-point tiebreak game",matchUpFormat:"SET1-S:TB10"},{description:"Timed 20 minute game - game based",matchUpFormat:"SET1-S:T20"}]}};var wx={[In]:{seedingProfile:{positioning:Bc},validSeedPositions:{ignore:!0},duplicateSeedNumbers:!0,drawSizeProgression:!0,policyName:"ITF SEEDING",seedsCountThresholds:[{drawSize:4,minimumParticipantCount:3,seedsCount:2},{drawSize:16,minimumParticipantCount:12,seedsCount:4},{drawSize:32,minimumParticipantCount:24,seedsCount:8},{drawSize:64,minimumParticipantCount:48,seedsCount:16},{drawSize:128,minimumParticipantCount:97,seedsCount:32},{drawSize:256,minimumParticipantCount:192,seedsCount:64}]}};var Lx={POLICY_AVOIDANCE_COUNTRY:Cx,POLICY_POSITION_ACTIONS_DEFAULT:oS,POLICY_POSITION_ACTIONS_DISABLED:Ox,POLICY_POSITION_ACTIONS_NO_MOVEMENT:bx,POLICY_POSITION_ACTIONS_UNRESTRICTED:Rx,POLICY_PRIVACY_DEFAULT:_x,POLICY_ROUND_NAMING_DEFAULT:Nf,POLICY_SCHEDULING_DEFAULT:fP,POLICY_SCORING_DEFAULT:vx,POLICY_SCORING_USTA:xx,POLICY_SEEDING_ITF:wx,POLICY_SEEDING_DEFAULT:yP};var t1={ratingsParameters:Jr,matchUpFormats:Nb,countryToFlag:jE,tieFormats:wT,countries:Yo,policies:Lx,flagIOC:MR};var Vx={};ne(Vx,{activeMatchUpStatuses:()=>fm,auditConstants:()=>k_,completedMatchUpStatuses:()=>ie,directingMatchUpStatuses:()=>xI,drawDefinitionConstants:()=>EE,entryStatusConstants:()=>$C,errorConditionConstants:()=>XM,eventConstants:()=>aR,extensionConstants:()=>OI,flightConstants:()=>$_,genderConstants:()=>wm,keyValueConstants:()=>e_,matchUpActionConstants:()=>iO,matchUpStatusConstants:()=>FI,matchUpTypes:()=>BC,nonDirectingMatchUpStatuses:()=>wI,particicipantsRequiredMatchUpStatuses:()=>_I,participantConstants:()=>HC,participantRoles:()=>Gm,participantTypes:()=>zc,penaltyConstants:()=>Fx,policyConstants:()=>OC,positionActionConstants:()=>Jb,ratingConstants:()=>SO,recoveryTimeRequiredMatchUpStatuses:()=>vC,requestConstants:()=>Uv,resultConstants:()=>qM,scaleConstants:()=>bC,scheduleConstants:()=>sR,sortingConstants:()=>z_,surfaceConstants:()=>Gx,tieFormatConstants:()=>A_,timeItemConstants:()=>nR,topicConstants:()=>GC,tournamentConstants:()=>NA,upcomingMatchUpStatuses:()=>LI,validMatchUpStatuses:()=>vI,venueConstants:()=>kx});var e1="Coaching",r1="Ball Abuse",n1="Racket Abuse",o1="Verbal Abuse",i1="INELIGIBILITY",s1="Physical Abuse",a1="Unsportmanlike Conduct",c1="Dress Code Violation",u1="Equipment Violation",p1="Leaving the court",m1="Failure to complete",d1="No Show",l1="Other",f1="REFUSAL_TO_PLAY",g1="PROHIBITED_SUBSTANCE",I1="Puncuality",h1="Failure to sign in",Fx={COACHING:e1,BALL_ABUSE:r1,RACKET_ABUSE:n1,VERBAL_ABUSE:o1,PHYSICAL_ABUSE:s1,INELIGIBILITY:i1,UNSPORTSMANLIKE_CONDUCT:a1,PROHIBITED_SUBSTANCE:g1,DRESS_CODE_VIOLATION:c1,EQUIMENT_VIOLATION:u1,LEAVING_THE_COURT:p1,REFUSAL_TO_PLAY:f1,FAILURE_TO_COMPLETE:m1,NO_SHOW:d1,OTHER:l1,PUNCTUALITY:I1,FAILUIRE_TO_SIGN_IN:h1};var S1="CLAY",T1="HARD",A1="GRASS",y1="CARPET",E1="ARTIFICIAL",Gx={CLAY:S1,HARD:T1,GRASS:A1,CARPET:y1,ARTIFICIAL:E1};var U1="INDOOR",P1="OUTDOOR",kx={INDOOR:U1,OUTDOOR:P1};export{fm as activeMatchUpStatuses,HV as askEngine,BV as asyncEngine,k_ as auditConstants,YV as competitionEngine,mE as competitionGovernor,ie as completedMatchUpStatuses,xI as directingMatchUpStatuses,EE as drawDefinitionConstants,dN as drawsGovernor,TN as entriesGovernor,$C as entryStatusConstants,XM as errorConditionConstants,aR as eventConstants,_N as eventGovernor,OI as extensionConstants,Vx as factoryConstants,t1 as fixtures,$_ as flightConstants,kV as forge,wm as genderConstants,FN as generationGovernor,uC as globalState,CA as governors,e_ as keyValueConstants,iO as matchUpActionConstants,WV as matchUpEngine,VT as matchUpFormatCode,VT as matchUpFormatGovernor,iD as matchUpGovernor,FI as matchUpStatusConstants,BC as matchUpTypes,jV as mocksEngine,xg as mocksGovernor,wI as nonDirectingMatchUpStatuses,_I as particicipantsRequiredMatchUpStatuses,HC as participantConstants,wD as participantGovernor,Gm as participantRoles,zc as participantTypes,Fx as penaltyConstants,OC as policyConstants,mN as policyGovernor,Jb as positionActionConstants,jD as publishingGovernor,AP as queryGovernor,SO as ratingConstants,vC as recoveryTimeRequiredMatchUpStatuses,YD as reportGovernor,Uv as requestConstants,qM as resultConstants,bC as scaleConstants,ZV as scaleEngine,sR as scheduleConstants,nM as scheduleGovernor,lg as scoreGovernor,z_ as sortingConstants,Gx as surfaceConstants,hx as syncEngine,A_ as tieFormatConstants,lM as tieFormatGovernor,nR as timeItemConstants,vM as tools,GC as topicConstants,NA as tournamentConstants,qV as tournamentEngine,EM as tournamentGovernor,LI as upcomingMatchUpStatuses,vM as utilities,vI as validMatchUpStatuses,kx as venueConstants,_M as venueGovernor,xa as version};