tods-competition-factory 2.0.37 → 2.0.39

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,6 +1,6 @@
1
- var jw=Object.defineProperty;var Zt=(t,e)=>{for(var r in e)jw(t,r,{get:e[r],enumerable:!0})};function Ha(){return"2.0.37"}var tA={};Zt(tA,{competitionGovernor:()=>wE,drawsGovernor:()=>aN,entriesGovernor:()=>fN,eventGovernor:()=>NN,generationGovernor:()=>vN,matchUpFormatGovernor:()=>fy,matchUpGovernor:()=>XN,mocksGovernor:()=>tI,participantGovernor:()=>NM,policyGovernor:()=>kD,publishingGovernor:()=>_M,queryGovernor:()=>iN,reportGovernor:()=>xM,scheduleGovernor:()=>qM,scoreGovernor:()=>Mg,tieFormatGovernor:()=>rC,tournamentGovernor:()=>mC,venueGovernor:()=>AC});var wE={};Zt(wE,{getLinkedTournamentIds:()=>Kc,getTournamentIds:()=>ip,linkTournaments:()=>bE,mutate:()=>_E,query:()=>xE,unlinkTournament:()=>OE,unlinkTournaments:()=>vE});var _E={};Zt(_E,{linkTournaments:()=>bE,unlinkTournament:()=>OE,unlinkTournaments:()=>vE});var oR={};Zt(oR,{addNotice:()=>St,callListener:()=>gm,createInstanceState:()=>hE,cycleMutationStatus:()=>ql,deepCopyEnabled:()=>Yl,deleteNotice:()=>_I,deleteNotices:()=>Oi,disableNotifications:()=>SE,enableNotifications:()=>jl,getDevContext:()=>Pr,getMethods:()=>$l,getNotices:()=>OI,getProvider:()=>xI,getTopics:()=>vr,getTournamentId:()=>zi,getTournamentRecord:()=>Kl,getTournamentRecords:()=>xo,globalLog:()=>AE,handleCaughtError:()=>Zu,removeTournamentRecord:()=>yE,setDeepCopy:()=>Bc,setDevContext:()=>Vc,setGlobalLog:()=>eR,setGlobalMethods:()=>rR,setGlobalSubscriptions:()=>UL,setMethods:()=>nR,setStateMethods:()=>EE,setStateProvider:()=>AL,setSubscriptions:()=>PL,setTournamentId:()=>Ju,setTournamentRecord:()=>TE,setTournamentRecords:()=>Im,timeKeeper:()=>EL});function br(t){return typeof t=="function"}function Re(t){return typeof t=="string"}function Pt(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function LC(t,e){if(!Pt(t)||!Pt(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 lI(t,e){return Array.isArray(t)?Object.assign({},...(t??[]).filter(Pt).map(r=>r[e]&&{[r[e]]:r}).filter(Boolean)):{}}var FC=t=>e=>Object.keys(t).every(r=>e[r]===t[r]);function dI(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=>dI(i))}:{[o]:e?n(t[o]):dI(t[o])}))}function sA(t){return Array.isArray(t)?t.length+t.map(sA).reduce((e,r)=>e+r,0):typeof t=="object"&&t!==null?Object.keys(t).length+Object.keys(t).map(e=>sA(t[e])).reduce((e,r)=>e+r,0):0}function GC(t){if(t===null||typeof t!="object")return;let e=JSON.stringify(t),r=sA(t),n=e.split("").reduce((o,i)=>o+i.charCodeAt(0),0);return[e.length,r,n].map(o=>o.toString(36)).join("")}var R={success:!0},Yw="error",kC={SUCCESS:R,ERROR:Yw};var fI={message:"Chronological error; time violation.",code:"ANACHRONISM"},cm={message:"Duplicate entry",code:"DUPLICATE_ENTRY"},aA={message:"Cannot remove main structure",code:"ERR_CANNOT_REMOVE_MAIN_STRUCTURE"},gI={message:"records must be an object with tournamentId keys",code:"ERR_INVALID_TOURNAMENTS"},kt={message:"Missing tournamentRecords",code:"ERR_MISSING_TOURNAMENTS"},j={message:"Missing tournamentRecord",code:"ERR_MISSING_TOURNAMENT"},Wa={message:"Invalid tournamentRecord",code:"ERR_INVALID_TOURNAMENT"},sa={message:"Missing tournamentId",code:"ERR_MISSING_TOURNAMENT_ID"},aa={message:"Invalid drawDefinition",code:"ERR_INVALID_DRAWDEF"},X={message:"Missing drawDefinition",code:"ERR_MISSING_DRAWDEF"},cA={message:"Existing drawDefinition(s)",code:"ERR_EXISTING_DRAWDEFS"},dr={message:"drawDefinition not found",code:"ERR_NOT_FOUND_DRAWDEF"},Ci={message:"Invalid structure",code:"ERR_INVALID_STRUCTURE"},hl={message:"Incomplete source structure",code:"ERR_INCOMPLETE_STRUCTURE"},Sl={message:"Invalid drawPosition for seedAssignment",code:"ERR_INVALID_SEEDING_POSITION"},ja={message:"drawPosition already assigned",code:"ERR_EXISTING_POSITION_ASSIGNMENT"},uA={message:"Schedule not cleared",code:"ERR_UNCHANGED_SCHEDULE_NOT_CLEARED"},pA={message:"drawPosition not cleared",code:"ERR_FAILURE_POSITION_NOT_CLEARED"},qw={message:"drawPosition not found",code:"ERR_NOT_FOUND_DRAW_POSITION"},Tl={message:"Unrecognized drawType",code:"ERR_UNRECOGNIZED_DRAW_TYPE"},Ya={message:"Missing drawPositions",code:"ERR_MISSING_DRAW_POSITIONS"},Bu={message:"drawPosition is active",code:"ERR_ACTIVE_DRAW_POSITION"},Ds={message:"Invlid drawPosition",code:"ERR_INVALID_DRAW_POSITION"},Ns={message:"Missing drawPosition",code:"ERR_MISSING_DRAW_POSITION"},um={message:"Invalid drawType",code:"ERR_INVALID_DRAW_TYPE"},Hu={message:"Invalid drawSize",code:"ERR_INVALID_DRAW_SIZE"},II={message:"Cannot set drawSize to be less than existing entries",code:"ERR_INVALID_DRAW_SIZE_MISMATCH"},qa={message:"Missing drawSize",code:"ERR_MISSING_DRAW_SIZE"},$r={message:"Missing drawId",code:"ERR_MISSING_DRAW_ID"},mA={message:"drawId exists",code:"ERR_EXISTING_DRAW_ID"},dA={message:"participantId cannot be assigned to multiple seedNumbers",code:"INVALID_PARTICIPANT_SEEDING"},lA={message:"seedsCount greater than drawSize",code:"ERR_INVALID_SEED_COUNT"},fA={message:"Missing seedCountThresholds",code:"ERR_MISSING_SEED_COUNT_THRESHOLD"},gA={message:"Invalid action",code:"ERR_INVALID_ACTION"},hI={message:"Invalid assignment",code:"ERR_INVALID_ASSIGNMENT"},IA={message:"Missing seedAssignments",code:"ERR_MISSING_SEED_ASSIGNMENTS"},hA={message:"Invalid seedNumber",code:"ERR_INVALID_SEED_NUMBER"},SA={message:"Invalid seedPosition",code:"ERR_INVALID_SEED_POSITION"},yl={message:"Missing targetLink",code:"ERR_MISSING_LINK_TARGET"},TA={message:"Existing round",code:"ERR_EXISTING_ROUND"},$w={message:"Missing roundNumber",code:"ERR_MISSING_ROUND_NUMBER"},Sr={message:"Missing structureId",code:"ERR_MISSING_STRUCTURE_ID"},Gt={message:"structure not found",code:"ERR_NOT_FOUND_STRUCTURE"},Al={message:"Missing structures",code:"ERR_MISSING_STRUCTURES"},Oo={message:"Missing structure",code:"ERR_MISSING_STRUCTURE"},yA={message:"drawDefinition contains unlinked structures",code:"ERR_MISSING_STRUCTURE_LINKS"},_o={message:"Invalid eventType",code:"ERR_INVALID_EVENT_TYPE"};var Dt={message:"Missing event / eventId",code:"ERR_MISSING_EVENT_ID"},lr={message:"Event not found",code:"ERR_NOT_FOUND_EVENT"},AA={message:"Event exists",code:"ERR_EXISTING_EVENT"},EA={message:"Missing entries",code:"ERR_MISSING_ENTRIES"},UA={message:"Invalid entries",code:"ERR_INVALID_ENTRIES"},El={message:"Missing assignments",code:"ERR_MISSING_ASSIGNMENTS"},SI={message:"Missing stage",code:"ERR_MISSING_STAGE"},Ri={message:"Invalid stage",code:"ERR_INVALID_STAGE"},PA={message:"stageSequence limit",code:"ERR_LIMIT_STAGE_SEQUENCE"},DA={message:"Missing positionAssignments",code:"ERR_MISSING_POSITION_ASSIGNMENTS"},NA={message:"Cannot Assign BYE status if no assignment: { bye: true }",code:"ERR_UNCHANGED_CANNOT_ASSIGN_BYE"},TI={message:"Unrecognized matchUpStatus",code:"ERR_UNRECOGNIZED_MATCHUP_STATUS"},$a={message:"Unrecognized matchUpFormat",code:"ERR_UNRECOGNIZED_MATCHUP_FORMAT"},Ul={message:"Incompatible matchUpStatus",code:"ERR_INCOMPATIBLE_MATCHUP_STATUS"},ca={message:"Invalid matchUpStatus",code:"ERR_INVALID_MATCHUP_STATUS"},ai={message:"Invalid tieFormat",code:"ERR_INVALID_TIE_FORMAT"},Pl={message:"Invalid matchUpFormat",code:"ERR_INVALID_MATCHUP_FORMAT"},Dl={message:"Missing matchUpFormat",code:"ERR_MISSING_MATCHUP_FORMAT"},MA={message:"Missing collectionDefinition",code:"ERR_MISSING_COLLECTION_DEFINITION"},Ms={message:"Missing tieFormat",code:"ERR_MISSING_TIE_FORMAT"},Be={message:"Missing matchUpId",code:"ERR_MISSING_MATCHUP_ID"},ua={message:"Missing matchUpIds",code:"ERR_MISSING_MATCHUP_IDS"},_e={message:"matchUp not found",code:"ERR_NOT_FOUND_MATCHUP"},An={message:"Missing matchUps",code:"ERR_MISSING_MATCHUPS"},cr={message:"Missing matchUp",code:"ERR_MISSING_MATCHUP"},Ze={message:"Invalid matchUp",code:"ERR_INVALID_MATCHUP"},yI={message:"Missing policyType",code:"ERR_MISSING_POLICY_TYPE"},Wu={message:"Missing policyDefinitions",code:"ERR_MISSING_POLICY_DEFINITIONS"},Kw={message:"Missing seeding policy",code:"ERR_MISSING_POLICY_SEEDING"},CA={message:"Missing avoidance policy",code:"ERR_MISSING_POLICY_AVOIDANCE"},AI={message:"Missing policy attributes",code:"ERR_MISSING_POLICY_ATTRIBUTES"},RA={message:"Invalid policyDefinitions",code:"ERR_INVALID_POLICY_DEFINITIONS"},EI={message:"existing policyType",code:"ERR_EXISTING_POLICY_TYPE"},zw={message:"Policy not attached",code:"ERR_FAILURE_POLICY_NOT_ATTACHED"},Fc={message:"Policy not found",code:"ERR_NOT_FOUND_POLICY"},Qw={message:"Missing scoring policy / matchUpFormats",code:"ERR_MISSING_POLICY_SCORING_MATCHUP_FORMATS"},Nl={message:"Invalid sideNumber",code:"ERR_INVALID_SIDE_NUMBER"},Xw={message:"Invalid setNumber",code:"ERR_INVALID_SET_NUMBER"},Ml={message:"Missing setObject",code:"ERR_MISSING_SET_ATTRIBUTE"},Jw={message:"Missing setNumber",code:"ERR_MISSING_SET_NUMBER"},Zw={message:"Missing sideNumber",code:"ERR_MISSING_SIDE_NUMBER"},bi={message:"Missing courtId",code:"ERR_MISSING_COURT_ID"},rt={message:"Missing value",code:"ERR_MISSING_VALUE"},bA={message:"Missing date",code:"ERR_MISSING_DATE"},vA={message:"No valid dates",code:"ERR_NO_VALID_DATES"},pm={message:"Invalid bookings",code:"ERR_INVALID_BOOKINGS"},Cl={message:"Invalid dateAvailability",code:"ERR_INVALID_DATE_AVAILABILITY"},OA={message:"Missing dateAvailability",code:"ERR_MISSING_DATE_AVAILABILITY"},ur={message:"Invalid Date",code:"ERR_INVALID_DATE"},Ao={message:"Invalid time",code:"ERR_INVALID_TIME"},_A={message:"Invalid tournament dates",code:"ERR_INVALID_DATES_TOURNAMENT"};var UI={message:"Invalid game scores",code:"ERR_INVALID_SCORES_GAME"},xA={message:"Invalid score",code:"ERR_INVALID_SCORE"},mm={message:"Invalid winningSide",code:"ERR_INVALID_WINNING_SIDE"};var VC={message:"No participants generated",code:"ERR_NO_PARTICIPANTS_GENERATED"},Rl={message:"Cannot modify tieFormat",code:"ERR_UNCHANGED_CANNOT_MODIFY_TIEFORMAT"},wA={message:"Cannot modify participantType",code:"ERR_UNCHANGED_CANNOT_MODIFY_PARTICIPANT_TYPE"},ju={message:"Cannot remove participants",code:"ERR_UNCHANGED_CANNOT_REMOVE_PARTICIPANTS"},bl={message:"Cannot change winningSide",code:"ERR_UNCHANGED_CANNOT_CHANGE_WINNING_SIDE"},Cs={message:"Invalid participant",code:"ERR_INVALID_PARTICIPANT"},Zr={message:"Invalid participantId",code:"ERR_INVALID_PARTICIPANT_ID"},Kr={message:"Invalid participantIds",code:"ERR_INVALID_PARTICIPANT_IDS"},LA={message:"Invalid participantRole",code:"ERR_INVALID_PARTICIPANT_ROLE"},an={message:"Invalid participantType",code:"ERR_INVALID_PARTICIPANT_TYPE"},FA={message:"Missing participantRole",code:"ERR_MISSING_PARTICIPANT_ROLE"},vi={message:"Missing participant",code:"ERR_MISSING_PARTICIPANT"},Ka={message:"Missing participants",code:"ERR_MISSING_PARTICIPANTS"},ee={message:"Missing participantId",code:"ERR_MISSING_PARTICIPANT_ID"},re={message:"Participant Not Found",code:"ERR_NOT_FOUND_PARTICIPANT"},GA={message:"participantId exists",code:"ERR_EXISTING_PARTICIPANT_ID"},tL={message:"participant pair exists",code:"ERR_EXISTING_PARTICIPANT_PAIR"},kA={message:"No participant removed",code:"ERR_UNCHANGED_NO_PARTICIPANT_REMOVED"},Eo={message:"Missing participantIds",code:"ERR_MISSING_PARTICIPANT_IDS"},VA={message:"Missing participantsCount",code:"ERR_MISSING_PARTICIPANT_COUNT"},BA={message:"Participant not checked in",code:"ERR_UNCHANGED_PARTICIPANT_NOT_CHECKED_IN"},HA={message:"Missing person details",code:"ERR_MISSING_PERSON_DETAILS"},Rs={message:"Existing participant drawPosition assignment",code:"ERR_EXISTING_PARTICIPANT_DRAW_POSITION_ASSIGNMENT"},Yu={message:"Existing participant",code:"ERR_EXISTING_PARTICIPANT"},vl={message:"participantsCount exceeds drawSize",code:"ERR_INVALID_PARTICIPANT_COUNT"},Ol={message:"Invalid entry status",code:"ERR_INVALID_ENTRY_STATUS"},PI={message:"Participant Entry Not Found",code:"ERR_NOT_FOUND_PARTICIPANT_ENTRY"},BC={message:"Participant not entered in stage",code:"ERR_UNCHANGED_PARTICIPANT_NOT_ENTERED"},HC={message:"Participant not found in stageSequence",code:"ERR_NOT_FOUND_PARTICIPANT_IN_STAGE"},WA={message:"entryStatus not allowed in stage",code:"ERR_INVALID_ENTRY_STATUS_IN_STAGE"},jA={message:"entryStatus not allowed for event",code:"ERR_INVALID_ENTRY_STATUS_IN_EVENT"},DI={message:"No stage space available for entryStatus",code:"ERR_UNCHANGED_NO_AVAILABLE_STAGE_SPACE"},YA={message:"Insufficient drawPositions to accommodate qualifiers",code:"ERR_UNCHANGED_NO_DRAW_POSITIONS_FOR_QUALIFIERS"},_l={message:"Insufficient drawPositions to accommodate entries",code:"ERR_INSUFFICIENT_DRAW_POSITIONS"},qA={message:"Missing penaltyType",code:"ERR_MISSING_PENALTY_TYPE"},xl={message:"Missing penaltyId",code:"ERR_MISSING_PENALTY_ID"},Gc={message:"Penalty not found",code:"ERR_NOT_FOUND_PENALTY"},$A={message:"Missing courtsCount/courtNames",code:"ERR_MISSING_COURTS_INFO"},za={message:"Court not found",code:"ERR_NOT_FOUND_COURT"},KA={message:"Court exists",code:"ERR_EXISTING_COURT"},zA={message:"Venue exists",code:"ERR_EXISTING_VENUE"},bs={message:"Venue not found",code:"ERR_NOT_FOUND_VENUE"},jo={message:"Missing venueId",code:"ERR_MISSING_VENUE_ID"},QA={message:"Invalid endTime",code:"ERR_INVALID_END_TIME"},NI={message:"Existing endTime",code:"ERR_EXISTING_END_TIME"},XA={message:"Invalid stopTime",code:"ERR_INVALID_STOP_TIME"},JA={message:"Invalid startTime",code:"ERR_INVALID_START_TIME"},WC={message:"Invalid resumeTime",code:"ERR_INVALID_RESUME_TIME"},wl={message:"Invalid timeItem",code:"ERR_INVALID_TIME_ITEMS"},ZA={message:"Missing async state provider",code:"ERR_MISSING_ASYNC_STATE_PROVIDER"},Ll={message:"Missing timeItem",code:"ERR_MISSING_TIME_ITEM"},Fl={message:"Missing timeItems",code:"ERR_MISSING_TIME_ITEMS"},kc={message:"Missing context",code:"ERR_MISSING_CONTEXT"},tE={message:"Missing schedule",code:"ERR_MISSING_SCHEDULE"},qu={message:"Invalid scaleItem",code:"ERR_INVALID_SCALE_ITEM"},eE={message:"Modifications failed",code:"ERR_FAILURE_MODIFICATIONS"},vs={message:"No modifications applied",code:"ERR_UNCHANGED_NO_MODIFICATIONS_APPLIED"},rE={message:"Unable to assign court",code:"ERR_UNCHANGED_COURT_NOT_ASSIGNED"},$u={message:"No Candidates",code:"ERR_UNCHANGED_NO_CANDIDATES"},nE={message:"Invalid configuration",code:"ERR_INVALID_CONFIG"},oE={message:"Invalid collectionDefinition",code:"ERR_INVALID_COLLECTION_DEFINITION"},no={message:"Invalid object",code:"ERR_INVALID_OBJECT"},Gl={message:"Invalid gender",code:"ERR_INVALID_GENDER"},dm={message:"Invalid category",code:"ERR_INVALID_CATEGORY"},G={message:"Invalid values",code:"ERR_INVALID_VALUES"},iE={message:"Duplicate value",code:"ERR_DUPLICATE_VALUE"},kl={message:"Team not found",code:"ERR_NOT_FOUND_TEAM"},sE={message:"No valid actions",code:"ERR_NO_VALID_ACTIONS"},Ku={message:"No valid attributes",code:"ERR_NO_VALID_ATTRIBUTES"},Vl={message:"Value unchanged",code:"ABORT_UNCHANGED"},Le={message:"Not found",code:"ERR_NOT_FOUND"},zu={message:"Not implemented",code:"ERR_NOT_IMPLEMENTED"},aE={message:"Existing flight",code:"ERR_EXISTING_FLIGHT"},Bl={message:"Existing flight profile",code:"ERR_EXISTING_FLIGHT_PROFILE"},cE={message:"Existing outcome",code:"ERR_EXISTING_OUTCOME"},uE={message:"Existing matchUpId",code:"ERR_EXISTING_MATCHUP_ID"},MI={message:"Existing stage",code:"ERR_EXISTING_STAGE"},Hl={message:"Existing structure",code:"ERR_EXISTING_STRUCTURE"},Qa={message:"Method not found",code:"ERR_NOT_FOUND_METHOD"},pE={message:"Scheduled matchUps",code:"ERR_SCHEDULED_MATCHUPS"},Qu={message:"Scores present",code:"ERR_SCORES_PRESENT"},jC={ANACHRONISM:fI,CANNOT_CHANGE_WINNING_SIDE:bl,CANNOT_MODIFY_TIEFORMAT:Rl,CANNOT_MODIFY_PARTICIPANT_TYPE:wA,CANNOT_REMOVE_MAIN_STRUCTURE:aA,CANNOT_REMOVE_PARTICIPANTS:ju,COURT_EXISTS:KA,COURT_NOT_FOUND:za,DRAW_DEFINITION_NOT_FOUND:dr,DRAW_ID_EXISTS:mA,DRAW_POSITION_ACTIVE:Bu,DRAW_POSITION_ASSIGNED:ja,DRAW_POSITION_NOT_CLEARED:pA,DRAW_POSITION_NOT_FOUND:qw,DRAW_SIZE_MISMATCH:II,DUPLICATE_ENTRY:cm,DUPLICATE_VALUE:iE,ENTRY_STATUS_NOT_ALLOWED_FOR_EVENT:jA,ENTRY_STATUS_NOT_ALLOWED_IN_STAGE:WA,EVENT_EXISTS:AA,EVENT_NOT_FOUND:lr,EXISTING_DRAW_DEFINITIONS:cA,EXISTING_END_TIME:NI,EXISTING_FLIGHT:aE,EXISTING_MATCHUP_ID:uE,EXISTING_OUTCOME:cE,EXISTING_PARTICIPANT_DRAW_POSITION_ASSIGNMENT:Rs,EXISTING_PARTICIPANT:Yu,EXISTING_POLICY_TYPE:EI,EXISTING_PROFILE:Bl,EXISTING_ROUND:TA,EXISTING_STAGE:MI,EXISTING_STRUCTURE:Hl,INCOMPATIBLE_MATCHUP_STATUS:Ul,INCOMPLETE_SOURCE_STRUCTURE:hl,INSUFFICIENT_DRAW_POSITIONS:_l,INVALID_ACTION:gA,INVALID_ASSIGNMENT:hI,INVALID_BOOKINGS:pm,INVALID_CATEGORY:dm,INVALID_COLLECTION_DEFINITION:oE,INVALID_CONFIGURATION:nE,INVALID_DATE_AVAILABILITY:Cl,INVALID_DATE:ur,INVALID_DRAW_DEFINITION:aa,INVALID_DRAW_POSITION_FOR_SEEDING:Sl,INVALID_DRAW_POSITION:Ds,INVALID_DRAW_SIZE:Hu,INVALID_END_TIME:QA,INVALID_ENTRIES:UA,INVALID_EVENT_TYPE:_o,INVALID_GAME_SCORES:UI,INVALID_GENDER:Gl,INVALID_MATCHUP_FORMAT:Pl,INVALID_MATCHUP_STATUS:ca,INVALID_MATCHUP_STATUS_BYE:NA,INVALID_MATCHUP:Ze,INVALID_OBJECT:no,INVALID_PARTICIPANT_ID:Zr,INVALID_PARTICIPANT_IDS:Kr,INVALID_PARTICIPANT_ROLE:LA,INVALID_PARTICIPANT_SEEDING:dA,INVALID_PARTICIPANT_TYPE:an,INVALID_PARTICIPANT:Cs,INVALID_POLICY_DEFINITION:RA,INVALID_RECORDS:gI,INVALID_SCALE_ITEM:qu,INVALID_SEED_NUMBER:hA,INVALID_SEED_POSITION:SA,INVALID_SET_NUMBER:Xw,INVALID_SIDE_NUMBER:Nl,INVALID_SCORE:xA,INVALID_STAGE:Ri,INVALID_START_TIME:JA,INVALID_STRUCTURE:Ci,INVALID_STOP_TIME:XA,INVALID_TIE_FORMAT:ai,INVALID_TIME:Ao,INVALID_TIME_ITEM:wl,INVALID_TOURNAMENT_DATES:_A,INVALID_TOURNAMENT_RECORD:Wa,INVALID_VALUES:G,INVALID_WINNING_SIDE:mm,MATCHUP_NOT_FOUND:_e,METHOD_NOT_FOUND:Qa,MISSING_ASSIGNMENTS:El,MISSING_ASYNC_STATE_PROVIDER:ZA,MISSING_AVOIDANCE_POLICY:CA,MISSING_COLLECTION_DEFINITION:MA,MISSING_COURT_ID:bi,MISSING_COURTS_INFO:$A,MISSING_DATE_AVAILABILITY:OA,MISSING_DATE:bA,MISSING_DRAW_DEFINITION:X,MISSING_DRAW_ID:$r,MISSING_DRAW_POSITION:Ns,MISSING_DRAW_POSITIONS:Ya,MISSING_DRAW_SIZE:qa,MISSING_ENTRIES:EA,MISSING_EVENT:Dt,MISSING_MATCHUP_FORMAT:Dl,MISSING_MATCHUP_ID:Be,MISSING_MATCHUP_IDS:ua,MISSING_MATCHUP:cr,MISSING_MATCHUPS:An,MISSING_PARTICIPANT_COUNT:VA,MISSING_PARTICIPANT_ID:ee,MISSING_PARTICIPANT_IDS:Eo,MISSING_PARTICIPANT_ROLE:FA,MISSING_PARTICIPANT:vi,MISSING_PARTICIPANTS:Ka,MISSING_PENALTY_ID:xl,MISSING_PENALTY_TYPE:qA,MISSING_PERSON_DETAILS:HA,MISSING_POLICY_ATTRIBUTES:AI,MISSING_POLICY_DEFINITION:Wu,MISSING_POLICY_TYPE:yI,MISSING_POSITION_ASSIGNMENTS:DA,MISSING_ROUND_NUMBER:$w,MISSING_SCHEDULE:tE,MISSING_SCORING_POLICY:Qw,MISSING_SEED_ASSIGNMENTS:IA,MISSING_SEEDCOUNT_THRESHOLDS:fA,MISSING_SEEDING_POLICY:Kw,MISSING_SET_NUMBER:Jw,MISSING_SET_OBJECT:Ml,MISSING_SIDE_NUMBER:Zw,MISSING_STAGE:SI,MISSING_STRUCTURE_ID:Sr,MISSING_STRUCTURE:Oo,MISSING_STRUCTURES:Al,MISSING_TARGET_LINK:yl,MISSING_TIE_FORMAT:Ms,MISSING_TIME_ITEM:Ll,MISSING_TIME_ITEMS:Fl,MISSING_TOURNAMENT_ID:sa,MISSING_TOURNAMENT_RECORD:j,MISSING_TOURNAMENT_RECORDS:kt,MISSING_VALUE:rt,MISSING_VENUE_ID:jo,MODIFICATIONS_FAILED:eE,NO_CANDIDATES:$u,NO_DRAW_POSITIONS_AVAILABLE_FOR_QUALIFIERS:YA,NO_MODIFICATIONS_APPLIED:vs,NO_STAGE_SPACE_AVAILABLE_FOR_ENTRY_STATUS:DI,NO_PARTICIPANT_REMOVED:kA,NO_VALID_ACTIONS:sE,NO_VALID_ATTRIBUTES:Ku,NO_VALID_DATES:vA,NOT_FOUND:Le,NOT_IMPLEMENTED:zu,PARTICIPANT_COUNT_EXCEEDS_DRAW_SIZE:vl,PARTICIPANT_ID_EXISTS:GA,PARTICIPANT_NOT_CHECKED_IN:BA,PARTICIPANT_NOT_FOUND:re,PARTICIPANT_PAIR_EXISTS:tL,PENALTY_NOT_FOUND:Gc,POLICY_NOT_ATTACHED:zw,POLICY_NOT_FOUND:Fc,SCHEDULE_NOT_CLEARED:uA,SCHEDULED_MATCHUPS:pE,SCORES_PRESENT:Qu,SEEDSCOUNT_GREATER_THAN_DRAW_SIZE:lA,STAGE_SEQUENCE_LIMIT:PA,STRUCTURE_NOT_FOUND:Gt,TEAM_NOT_FOUND:kl,UNABLE_TO_ASSIGN_COURT:rE,UNLINKED_STRUCTURES:yA,UNRECOGNIZED_DRAW_TYPE:Tl,UNRECOGNIZED_MATCHUP_FORMAT:$a,UNRECOGNIZED_MATCHUP_STATUS:TI,VALUE_UNCHANGED:Vl,VENUE_EXISTS:zA};var tr={disableNotifications:!1,tournamentId:void 0,tournamentRecords:{},subscriptions:{},modified:!1,methods:{},notices:[]},mE={addNotice:dL,callListener:hL,cycleMutationStatus:mL,deleteNotice:gL,deleteNotices:fL,disableNotifications:eL,enableNotifications:rL,getMethods:Xu,getNotices:lL,getTopics:IL,getTournamentId:YC,getTournamentRecord:nL,getTournamentRecords:oL,removeTournamentRecord:cL,setMethods:pL,setSubscriptions:uL,setTournamentId:sL,setTournamentRecord:iL,setTournamentRecords:aL,handleCaughtError:SL};function eL(){tr.disableNotifications=!0}function rL(){tr.disableNotifications=!1}function YC(){return tr.tournamentId}function nL(t){return tr.tournamentRecords[t]}function oL(){return tr.tournamentRecords}function iL(t){let e=t?.tournamentId;return e?(tr.tournamentRecords[e]=t,{success:!0}):{error:Wa}}function sL(t){return t?tr.tournamentRecords[t]?(tr.tournamentId=t,{success:!0}):{error:j}:(tr.tournamentId=void 0,{success:!0})}function aL(t){tr.tournamentRecords=t;let e=Object.keys(t);e.length===1?tr.tournamentId=e[0]:e.length||(tr.tournamentId=void 0)}function cL(t){if(typeof t!="string")return{error:G};if(!tr.tournamentRecords[t])return{error:Le};delete tr.tournamentRecords[t];let e=Object.keys(tr.tournamentRecords);return e.length===1?tr.tournamentId=e[0]:e.length||(tr.tournamentId=void 0),{success:!0}}function uL(t){return typeof t.subscriptions!="object"?{error:G}:(Object.keys(t.subscriptions).forEach(e=>{tr.subscriptions[e]=t.subscriptions[e]}),{...R})}function pL(t){return typeof t!="object"?{error:G}:(Object.keys(t).forEach(e=>{typeof t[e]=="function"&&(tr.methods[e]=t[e])}),{...R})}function mL(){let t=tr.modified;return tr.modified=!1,t}function dL({topic:t,payload:e,key:r},n){if(!(typeof t!="string"||typeof e!="object")&&(tr.disableNotifications||(tr.modified=!0),!(tr.disableNotifications||!tr.subscriptions[t]&&!n)))return r&&(tr.notices=tr.notices.filter(o=>!(o.topic===t&&o.key===r))),tr.notices.push({topic:t,payload:e,key:r}),{...R}}function Xu(){return tr.methods??{}}function lL({topic:t}){return tr.notices.filter(e=>e.topic===t).map(e=>e.payload)}function fL(){tr.notices=[]}function gL({topic:t,key:e}){tr.notices=tr.notices.filter(r=>(!t||r.topic===t)&&r.key!==e)}function IL(){return{topics:Object.keys(tr.subscriptions)}}function hL({topic:t,notices:e},r){let n=tr.subscriptions[t];n&&typeof n=="function"&&n(e);let o=r?.[t];o&&typeof o=="function"&&o(e)}function SL({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:YC(),params:JSON.stringify(r),engine:t,methodName:e,error:o}),{error:o}}function se(t,e){return(t??0)-(e??0)}function ct(t){return typeof t=="number"?parseInt(t.toString()):typeof t=="string"?parseInt(t):0}function En(t){return isNaN(t)?!1:t&&(t&t-1)===0}function dE(t){if(!t.length)return;let e=[...t].sort(se),r=Math.floor(e.length/2);return e.length%2?e[r]:(e[r-1]+e[r])/2}function qC(t){if(!En(t))return!1;let e=t,r=1;for(;e!==2;)r+=1,e=e/2;return r}function lm(t){return isNaN(t)?0:t%2&&t+1||t}function fm(t){return Math.pow(2,Math.round(Math.log(t)/Math.log(2)))}function Jt(t){return!isNaN(parseFloat(t))}function CI(t){let e=ct(t);if(!isNaN(e))return e===0?!1:(e&-e)===1}function Ki(t){if(isNaN(t))return!1;for(;!En(t);)t++;return t}function oo(t,e){return t=Math.ceil(t),e=Math.floor(e),Math.floor(Math.random()*(e-t+1))+t}function ft(t){return Number.isSafeInteger(typeof t=="string"?+t:t)}function $C(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 TL(t,e){e||(e=1);let r=1/e;return Math.round(t*r)/r}function lE(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=lE(t,e,r):(a=Math.pow(a,r),a*=e-t,a+=t),n&&(a=TL(a,n)),parseFloat(a.toFixed(o))}function pt(t){return Array.isArray(t)?t?.filter((e,r,n)=>n.lastIndexOf(e)===r):[]}function KC(t){return Array.isArray(t)?t?.map(e=>e===null?void 0:e):t}function pr(t){return Array.isArray(t)?t.map(e=>[Math.random(),e]).sort((e,r)=>e[0]-r[0]).map(e=>e[1]):[]}function Xa(t){return ft(t)?t:1/0}function fr(t){return Array.isArray(t)?t.reduce((e,r)=>(e[r]||(e[r]=0),e[r]++,e),{}):{}}function zC(t){return fE(fr(t))}function fE(t){return Object.keys(t).reduce((e,r)=>{let n=t[r];return e[n]?e[n].push(r):e[n]=[r],e},{})}function yL(t,e,r){return r.indexOf(t)===e}function RI(t){return t.filter(yL)}function Gr(t){return Array.isArray(t)&&t.length?t.splice(Math.floor(Math.random()*t.length),1)[0]:void 0}function cn(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 io(t,e){return e.reduce((r,n,o)=>(n===t&&r.push(o),r),[])}function jt(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 gE(t,e){return!Array.isArray(t)||!Array.isArray(e)?[]:t.filter(r=>!e.includes(r))}function Fe(t,e){return!Array.isArray(t)||!Array.isArray(e)?!1:t.some(r=>e.includes(r))}function QC(t,e){return Array.isArray(e)&&e.reduce((r,n)=>(r[n]=1+r[n]||1,r),{})[t]||0}function XC(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 Te(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 IE(t,[e,...r]){return t.length?[t.slice(0,e),...IE(t.slice(e),[...r,e])]:[]}function JC(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 bI(t){return Array.isArray(t)?t.reduce((e,r)=>!isNaN(parseInt(r))&&e,!0):!1}function vI(t){return Array.isArray(t)?t.reduce((e,r)=>isNaN(parseInt(r))&&e,!0):!1}function Wl(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 ZC(t,e=1){if(!Array.isArray(t)||!t.every(ft))return[];let r=Math.min(...t,e),n=Math.max(...t);return Z(r,n+1).filter(o=>!t.includes(o))}var De={timers:{default:{elapsedTime:0}},globalSubscriptions:{},deepCopyAttributes:{stringify:[],ignore:[],toJSON:[]},globalMethods:[],deepCopy:!0},zr=mE,tR=["addNotice","callListener","cycleMutationStatus","deleteNotice","deleteNotices","disableNotifications","enableNotifications","getMethods","getNotices","getTopics","getTournamentId","getTournamentRecord","getTournamentRecords","removeTournamentRecord","setSubscriptions","setTournamentId","setTournamentRecord","setTournamentRecords"];function AL(t){if(typeof t!="object")throw new Error("Global state provider can not be undefined or null");if(jt(Object.keys(t),tR).length!==tR.length)throw new Error("Global state provider is missing required methods");return zr=t,{success:!0}}function hE(){if(zr.createInstanceState){try{zr.createInstanceState()}catch(t){return{error:t}}return{success:!0}}else return{error:ZA}}function Pr(t){return!t||typeof t!="object"?De.devContext??!1:typeof De.devContext!="object"?!1:Object.keys(t).every(e=>De.devContext?.[e]===t[e])&&De.devContext}function EL(t="reset",e="default"){let r=Date.now();if(t==="report"){if(e==="allTimers")return Object.keys(De.timers).filter(o=>o!=="default"||De.timers[o].startTime).map(o=>{let i=De.timers[o],s=i.state==="stopped"?0:(r-(i?.startTime??0))/1e3,a=i.elapsedTime+s;return{state:De.timers[o].state,elapsedTime:a.toFixed(2),timer:o}});{let n=De.timers[e].state==="stopped"?0:(r-(De.timers[e]?.startTime??0))/1e3,o=De.timers[e].elapsedTime+n;return{state:De.timers[e].state,elapsedTime:o.toFixed(2),timer:e}}}if(!De.timers[e]||t==="reset"){if(e==="allTimers")return De.timers={default:{elapsedTime:0}},!0;De.timers[e]={startTime:r,state:"active",elapsedTime:0}}return De.timers[e].elapsedTime||(De.timers[e].elapsedTime=0),t==="stop"&&De.timers[e].state!=="stopped"&&(De.timers[e].state="stopped")&&(De.timers[e].elapsedTime+=(r-(De.timers[e]?.startTime??0))/1e3),t==="start"&&(De.timers[e].startTime=r)&&(De.timers[e].state="active"),De.timers[e]}function eR(t){br(t)?De.globalLog=t:delete De.globalLog}function Vc(t){De.devContext=t}function SE(){zr.disableNotifications()}function jl(){zr.enableNotifications()}function Bc(t,e){typeof t=="boolean"&&(De.deepCopy=t),typeof e=="object"&&(Array.isArray(e.ignore)&&(De.deepCopyAttributes.ignore=e.ignore),Array.isArray(e.toJSON)&&(De.deepCopyAttributes.toJSON=e.toJSON),Array.isArray(e.stringify)&&(De.deepCopyAttributes.stringify=e.stringify),e.threshold&&(De.deepCopyAttributes.threshold=e.threshold))}function Yl(){return{enabled:De.deepCopy,...De.deepCopyAttributes}}function UL(t){return t?.subscriptions?(Object.keys(t.subscriptions).forEach(e=>{De.globalSubscriptions[e]=t.subscriptions[e]}),{...R}):{error:rt,info:"missing subscriptions"}}function PL(t){return t?.subscriptions?zr.setSubscriptions({subscriptions:t.subscriptions}):{error:rt,info:"missing subscriptions"}}function rR(t){return t?typeof t!="object"?{error:G}:(Object.keys(t).forEach(e=>{br(t[e])&&(De.globalMethods[e]=t[e])}),{...R}):{error:rt,info:"missing method declarations"}}function nR(t){return t?typeof t!="object"?{error:G}:zr.setMethods(t):{error:rt,info:"missing method declarations"}}function ql(){return zr.cycleMutationStatus()}function St(t){if(typeof t?.topic!="string")return;let e=De.globalSubscriptions[t.topic];return zr.addNotice(t,e)}function $l(){return{...De.globalMethods,...zr.getMethods()}}function OI(t){return zr.getNotices(t)}function _I({key:t,topic:e}){return zr.deleteNotice({key:t,topic:e})}function Oi(){return zr.deleteNotices()}function vr(){return zr.getTopics()}async function gm(t){return zr.callListener(t,De.globalSubscriptions)}function zi(){return zr.getTournamentId()}function Kl(t){return zr.getTournamentRecord(t)}function xo(){return zr.getTournamentRecords()}function TE(t){return zr.setTournamentRecord(t)}function Im(t){return zr.setTournamentRecords(t)}function Ju(t){return zr.setTournamentId(t)}function yE(t){return zr.removeTournamentRecord(t)}function xI(){return zr}function Zu({engineName:t,methodName:e,params:r,err:n}){return(br(zr.handleCaughtError)&&zr.handleCaughtError||mE.handleCaughtError)({engineName:t,methodName:e,params:r,err:n})}function AE(t,e){if(De.globalLog)try{De.globalLog({log:t,engine:e})}catch(r){console.log("globalLog error",r),console.log(e,t),eR()}else console.log(e,t)}function EE(t,e,r,n){if(!Pt(t))return{error:G};Jt||(r=1);let o=Array.isArray(e)?e:[],i={},s=(a,c=0)=>{Object.keys(a).forEach(u=>{br(a[u])?i[u]=a[u]:Pt(a[u])&&(e===!0||o?.includes(u))&&(r===void 0||c<r)&&s(a[u],c+1)})};return s(t),n?rR(i):nR(i),{methods:i}}function DL(t,e,r){return Object.keys(t).filter(n=>!e.includes(t[n])&&(!r||(Array.isArray(t[n])?t[n].length:!0)))}function nt(t,e,r,n){if(typeof t!="object"||t===null)return t;Yl()?.enabled||(n=!0);let i=["",void 0,null];e&&i.push(!1);let s=DL(t,i,r);return Object.assign({},...s.map(a=>Array.isArray(t[a])?{[a]:n?t[a]:t[a].map(c=>nt(c))}:{[a]:n?t[a]:nt(t[a])}))}function _({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,nt(t)),e&&!e?.error&&!e?.success&&Object.assign(e,{...R}),e??{success:!0}}var Ae="tournamentRecords",zl="policyDefinitions",un="tournamentRecord",Or="drawDefinition",hm="matchUpFormat",jn="participantId",wI="scheduleDates",iR="tournamentId",sR="scheduleDate",Sm="structureId",Ql="participant",Ja="matchUpIds",aR="policyType",UE="structures",so="matchUpId",Hc="inContext",Xl="structure",tp="courtIds",cR="personId",ep="venueIds",PE="matchUps",LI="courtId",FI="eventId",Un="matchUp",GI="drawId",Yo="error",Os="event",Qi="param",uR="uuids",pR="averageMatchUpMinutes",mR="recoveryMinutes",dR="periodLength",lR="number";var Yn="object",Dr="array";var Pn="_validate",kI="_message",Dn="_invalid",dn="_ofType",Tm="_anyOf",Za="_oneOf";var NL={[Ae]:kt,[un]:j,[zl]:Wu,[Or]:X,[jn]:ee,[hm]:Dl,[iR]:sa,[Sm]:Sr,[Ja]:ua,[Ql]:vi,[UE]:Al,[so]:Be,[Xl]:Oo,[LI]:bi,[PE]:An,[FI]:lr,[Un]:cr,[tp]:rt,[ep]:rt,[GI]:$r,[Os]:Dt},ML={[Ae]:Yn,[zl]:Yn,[un]:Yn,[Or]:Yn,[wI]:Dr,[Ql]:Yn,[Ja]:Dr,[UE]:Dr,[Xl]:Yn,[tp]:Dr,[ep]:Dr,[PE]:Dr,[Un]:Yn,[Os]:Yn,[uR]:Dr};function ut(t,e,r){if(!t&&!Pt(t))return{error:G};if(!e?.length||t?._bypassParamCheck)return{valid:!0};if(!Array.isArray(e))return{error:G};let{paramError:n,errorParam:o}=bL(t,e);if(!n)return{valid:!0};let i=t?.[o]===void 0?NL[o]||n[Yo]||G:n[Pn]&&n[Dn]||G,s=o??(n[Za]&&Object.keys(n[Za]).join(", "));return _({info:{param:s,message:n[kI]},result:{error:i},stack:r})}function fR(t,e){let r=Object.keys(t),n=Object.keys(e);return jt(r,n)}function CL(t,e){if(!e)return;let r=fR(t,e);return r.length!==1?{error:G}:r.reduce((n,o)=>({...n,[o]:!0}),{})}function RL(t,e){if(!e)return;let r=fR(t,e).filter(n=>t[n]);return r.length<1?{error:G}:r.reduce((n,o)=>({...n,[o]:!0}),{})}function bL(t,e){let r,n;return{paramError:e.find(({_ofType:i,_oneOf:s,_anyOf:a,_validate:c,_info:u,...p})=>{let m=s&&CL(t,s);if(m?.error)return m.error;m&&Object.assign(p,m);let d=a&&RL(t,a);if(d?.error)return d.error;d&&Object.assign(p,d);let l=Object.keys(p).filter(g=>typeof p[g]=="boolean"),f=l.find(g=>{let I=c&&!br(c),h=t[g]!==void 0&&!c&&vL(t,g,i),S=p[g]&&[void 0,null].includes(t[g]),y=I||h||S||c&&t[g]!==void 0&&!OL(t[g],c);return y&&(r=g,n=u),y});return!l.length||f}),errorParam:r,paramInfo:n}}function vL(t,e,r){return r=r||ML[e]||"string",r==="array"?!Array.isArray(t[e]):typeof t[e]!==r}function OL(t,e){return br(e)?e(t):!0}var VI="DYNAMIC",ci="RANKING",Xi="RATING",Ji="SCALE",ao="SEEDING",gR={RANKING:ci,RATING:Xi,SCALE:Ji,SEEDING:ao};function pa(t){let e=ut(t,[{[Ql]:!0}]);if(e.error)return e;let r=t.participant.timeItems?.filter(({itemType:o})=>o?.startsWith(Ji)&&[ci,Xi,ao].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=pt(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===ao&&"seedings"||c===ci&&"rankings"||"ratings";n[l][u]||(n[l][u]=[]),n[l][u].push({scaleValue:a.itemValue,scaleDate:a.itemDate,scaleName:d})}}}return{...R,...n}}function _i(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 ym=/^[\d]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][\d]|3[0-1])$/,BI=/^((0[\d]|1[\d]|2[0-3]):[0-5][\d](:[0-5][\d])?)([.,][0-9]{3})?$/,wo=/^([\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?$/,_s=/^([\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 Am(t){let{scheduledDate:e}=t;if(!e&&t.scheduledTime&&(e=Ut(t.scheduledTime)),!e)return;let r=$t(t.scheduledTime),n=Ut(e);return n&&r&&(n+=`T${r}`),n}function IR(t){return typeof t!="object"||Array.isArray(t)?!1:Object.prototype.toString.call(t)==="[object Date]"}function Wc(t){let e=typeof t=="string"?t?.split(" "):[];return t&&e?.length>1&&!["AM","PM"].includes(e[1].toUpperCase())?!1:!!(!t||_s.test(ec(t,!0,!0)))}function _r(t){return tc(t)||ym.test(t)}function _L(t){let e=new Date(t),r=e.getSeconds()+60*e.getMinutes()+60*60*e.getHours();return xL(r,{displaySeconds:!1})}function xL(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(qn).join(":")}var tf=t=>{let e=Jl(t)||tc(t)?new Date(t):new Date,r=e.getUTCMonth()+1,n=r<10?`0${r}`:`${r}`;return`${e.getUTCFullYear()}-${qn(n)}-${qn(e.getUTCDate())}`};function wL(t){let e=Jl(t)||tc(t)?new Date(t):new Date;return Date.UTC(e.getFullYear(),e.getMonth(),e.getDate())}function co(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 HI(t){let e=t?new Date(t):new Date,r=e.getTimezoneOffset();return new Date(e.getTime()-r*60*1e3)}function LL(t){return HI(t).getTime()}function Jl(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 xs(t,e){if(!_r(t)||!_r(e))return[];let r=Ut(t)+"T00:00",n=Ut(e)+"T00:00",o=new Date(r),i=new Date(n),s=Jl(i)&&Jl(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=>co(p));function u(p,m){return p<=m}}var FL=/^([+-]?\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 tc(t){return typeof t!="string"?!1:FL.test(t)}function jI(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 Vt(t){let e=$t(t);if(!e)return 0;let[r,n]=e.split(":").map(o=>parseInt(o));return r*60+n}function hR(t){let e=Math.floor(t/60),r=t-e*60;return e>23&&(e=e%24),[qn(e),qn(r)].join(":")}function Zl(t){return jI(t)?t.split(":").slice(0,2).map(qn).join(":"):void 0}function $t(t){return tc(t)&&t.indexOf("T")>0?Zl(t.split("T").reverse()[0]):Zl(t)}function Ut(t){return tc(t)||wo.test(t)?t.split("T")[0]:void 0}function rp(t,e){let r=new Date(t);return r.setDate(r.getDate()+e),Ut(r.toISOString())}function WI(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 GL(t){let e=WI(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(qn).join(":")}function kL(t){let e=WI(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 ec(t,e,r){let n=Ut(t),o=$t(t),i=n?o:t;return t?e&&(n&&r&&t||GL(i))||kL(i):void 0}function YI(t,e){let r=WI(t),n=WI(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 SR(t,e=7){let r=Ut(t)+"T00:00",n=new Date(r),o=new Date(n.setDate(n.getDate()+e));return co(o)}function VL(t){return SR(t)}function BL(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())),co(o,r)}function TR(t,e,r){let n=new Date(t,0);return co(new Date(n.setDate(e)),r)}function Ge(t,e=void 0){let[r,n]=(t||"00:00").split(":").map(qn),o=HI(e).setHours(r,n,0,0);return HI(o)}function ma(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 xr(t,e){let r=$t(t);if(!r)return"00:00";let n=isNaN(e)?0:e;return $t(ef(Ge(r),n).toISOString())}function ef(t,e){let r=new Date(t);return new Date(r.getTime()+e*6e4)}function qn(t){return t.toString()[1]?t:"0"+t}function wn(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 yR={addDays:SR,addWeek:VL,addMinutesToTimeString:xr,convertTime:ec,getIsoDateString:Am,getUTCdateString:tf,DateHHMM:_L,extractDate:Ut,extractTime:$t,formatDate:co,getDateByWeek:BL,isISODateString:tc,isDate:Jl,isTimeString:jI,offsetDate:HI,offsetTime:LL,sameDay:wn,timeStringMinutes:Vt,timeToDate:Ge,timeUTC:wL,validTimeValue:Wc,validDateString:ym,timeValidation:_s,dateValidation:wo};function J(t,e,r,n,o=0){if(xI().makeDeepCopy)return xI().makeDeepCopy(t,e,r,n);let i=Yl(),{stringify:s,toJSON:a,ignore:c,modulate:u}=i||{};if(!i?.enabled&&!r||typeof t!="object"||br(t)||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)||br(c)&&!c(l)),d=(l,f)=>{p[l]=br(f?.toString)?f.toString():JSON.stringify(f)};for(let l of m){let f=t[l],g=br(u)?u(f):void 0;if(g!==void 0)p[l]=g;else if(e&&l==="extensions"&&Array.isArray(f)){let I=rf(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)&&br(f?.toJSON)?p[l]=f.toJSON():f===null?p[l]=void 0:IR(f)?p[l]=new Date(f).toISOString():p[l]=J(f,e,r,n,o+1)}return p}function rf(t){return t?.map(e=>{let{name:r,value:n}=e;return r&&n&&{[`_${r}`]:n}}).filter(Boolean)}var qI="voluntaryConsolation",ui="competitiveBands",nf="roundRobinTally",uo="positionActions",Qe="matchUpActions",of="rankingPoints",da="roundNaming",ws="participant",jc="progression",Uo="scheduling",Yc="avoidance",HL="display",Ln="scoring",Nn="seeding",rc="feedIn",WL="audit",Em="draws",AR={POLICY_TYPE_VOLUNTARY_CONSOLATION:qI,POLICY_TYPE_COMPETITIVE_BANDS:ui,POLICY_TYPE_ROUND_ROBIN_TALLY:nf,POLICY_TYPE_POSITION_ACTIONS:uo,POLICY_TYPE_MATCHUP_ACTIONS:Qe,POLICY_TYPE_RANKING_POINTS:of,POLICY_TYPE_ROUND_NAMING:da,POLICY_TYPE_PARTICIPANT:ws,POLICY_TYPE_PROGRESSION:jc,POLICY_TYPE_SCHEDULING:Uo,POLICY_TYPE_AVOIDANCE:Yc,POLICY_TYPE_DISPLAY:HL,POLICY_TYPE_FEED_IN:rc,POLICY_TYPE_SCORING:Ln,POLICY_TYPE_SEEDING:Nn,POLICY_TYPE_AUDIT:WL,POLICY_TYPE_DRAWS:Em};function Lo({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?.[ws];if(r?.withScaleValues){let{ratings:u,rankings:p}=pa({participant:a});a.rankings=p,a.ratings=u}if(c?.participant)return _i({template:c.participant,source:a})}return a}var ER="element required",UR="missing name";function sr(t){if(!t||typeof t!="object")return{error:rt};if(t.element&&typeof t?.element!="object")return{error:G};if(!t?.name)return{error:rt,info:UR};if(!t?.element){if(t.discover&&t.tournamentRecords){for(let e of Object.keys(t.tournamentRecords)){let r=t.tournamentRecords[e],n=sr({element:r,name:t.name});if(n.error)return _({result:n,stack:"removeExtension"})}return{...R}}return{error:rt,info:ER}}return t?.element.extensions?(t.element.extensions=t.element.extensions.filter(e=>e?.name!==t.name),{...R}):{...R,info:Le}}function Mn({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 yt(t){if(typeof t!="object")return{error:rt};let e="addExtension";if(t?.element&&typeof t.element!="object")return _({result:{error:G},stack:e});if(!Mn({extension:t.extension}))return _({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=yt({extension:t.extension,element:o});if(i.error)return _({result:i,stack:e})}return{...R}}else return _({result:{error:rt},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 sf(t){return!t||typeof t!="object"?{error:rt}:t.tournamentRecord?yt({creationTime:t.creationTime,element:t.tournamentRecord,extension:t.extension}):{error:j}}function np(t){return!t||typeof t!="object"?{error:rt}:t.drawDefinition?yt({creationTime:t.creationTime,element:t.drawDefinition,extension:t.extension}):{error:dr}}function Po(t){return!t||typeof t!="object"?{error:rt}:t.event?yt({creationTime:t.creationTime,extension:t.extension,element:t.event}):{error:lr}}function DE(t){if(!t||typeof t!="object")return{error:rt};if(!t.participantId)return{error:ee};let e=t.tournamentRecord?.participants||[],r=Lo({participantId:t.participantId,tournamentParticipants:e});return r?yt({creationTime:t.creationTime,extension:t.extension,element:r}):{error:re}}function af(t){return!t||typeof t!="object"?{error:rt}:t.tournamentRecord?sr({element:t.tournamentRecord,name:t.name}):{error:j}}function NE(t){return!t||typeof t!="object"?{error:rt}:t.drawDefinition?sr({element:t.drawDefinition,name:t.name}):{error:dr}}function op(t){return!t||typeof t!="object"?{error:rt}:t?.event?sr({element:t.event,name:t.name}):{error:lr}}function ME(t){if(!t||typeof t!="object")return{error:rt};if(!t.participantId)return{error:ee};let e=t.tournamentRecord?.participants||[],r=Lo({participantId:t.participantId,tournamentParticipants:e});return r?sr({element:r,name:t.name}):{error:re}}function ip({tournamentRecords:t}){return{tournamentIds:Pt(t)?Object.keys(t):[],...R}}var jL="extensionQueries";function dt({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:Le}}return _({result:{error:rt},stack:jL})}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:Le}}var YL="activeSuspension",qc="appliedPolicies",CE="context",Um="delegatedOutcome",$n="disabled",Pm="disableLinks",nc="disableAutoCalc",sp="drawDeletions",qL="drawProfile",Dm="entryProfile",$L="eventProfile",KL="eventWithdrawalRequests",zL="factory",Qr="flightProfile",$I="groupingAttribute",Do="lineUps",la="linkedTournamentsIds",Nm="matchUpHistory",KI="participantRepresentatives",fa="personRequests",ap="positionActions",QL="rankingPoints";var ln="roundTarget",$c="scheduleLimits",Fo="scheduleTiming",ga="schedulingProfile",XL="statusDetail",oc="subOrder",qo="tally",cf="tieFormatModification",zI={ACTIVE_SUSPENSION:YL,APPLIED_POLICIES:qc,CONTEXT:CE,DELEGATED_OUTCOME:Um,DISABLED:$n,DISABLE_LINKS:Pm,DISABLE_AUTO_CALC:nc,DRAW_DELETIONS:sp,DRAW_PROFILE:qL,ENTRY_PROFILE:Dm,EVENT_PROFILE:$L,EVENT_WITHDRAWAL_REQUESTS:KL,FLIGHT_PROFILE:Qr,GROUPING_ATTRIBUTE:$I,LINEUPS:Do,LINKED_TOURNAMENTS:la,MATCHUP_HISTORY:Nm,PARTICIPANT_REPRESENTATIVES:KI,PERSON_REQUESTS:fa,POSITION_ACTIONS:ap,RANKING_POINTS:QL,ROUND_TARGET:ln,SCHEDULE_LIMITS:$c,SCHEDULE_TIMING:Fo,SCHEDULING_PROFILE:ga,STATUS_DETAIL:XL,SUB_ORDER:oc,TALLY:qo,TIE_FORMAT_MODIFICATIONS:cf,FACTORY:zL},RE=[Um,$n,Pm,Qr,Do,Nm,KI,fa,ln,$c,Fo,ga,oc,qo];function bE({tournamentRecords:t}){if(typeof t!="object"||!Object.keys(t).length)return{error:kt};let e=ip({tournamentRecords:t}),{tournamentIds:r}=e;return r?.length>1?yt({tournamentRecords:t,discover:!0,extension:{name:la,value:{tournamentIds:r}}}):{...R}}function vE({tournamentRecords:t}){if(typeof t!="object"||!Object.keys(t).length)return{error:kt};let e=sr({name:la,tournamentRecords:t,discover:!0});return _({result:e,stack:"unlinkTournaments"})}function OE({tournamentRecords:t,tournamentId:e}){if(typeof t!="object")return{error:G};if(!e)return{error:sa};let r=ip({tournamentRecords:t}),{tournamentIds:n}=r;if(!n.includes(e))return{error:sa};let o;return n.every(i=>{let s=t[i],{extension:a}=dt({element:s,name:la});if(!a)return!0;let c=a?.value?.tournamentIds||[];if(!c?.length||c.length===1&&c.includes(e)||i===e){let m=af({name:la,tournamentRecord:s});return m.error&&(o=m.error),m.success}let u=c.filter(m=>m!==e);a.value={tournamentIds:u};let p=sf({tournamentRecord:s,extension:a});return p.error&&(o=p.error),p.success}),o?{error:o}:{...R}}var xE={};Zt(xE,{getLinkedTournamentIds:()=>Kc,getTournamentIds:()=>ip});function Kc({tournamentRecords:t}){return typeof t!="object"||!Object.keys(t).length?{error:kt}:{linkedTournamentIds:Object.assign({},...Object.keys(t).map(r=>{let n=t[r],o=n?.tournamentId,{extension:i}=dt({element:n,name:la}),s=(i?.value?.tournamentIds||[]).filter(a=>a!==o);return{[r]:s}}))}}var aN={};Zt(aN,{addAdHocMatchUps:()=>hd,addDrawDefinitionTimeItem:()=>sg,addFinishingRounds:()=>Ua,addGoesTo:()=>Gi,addPlayoffStructures:()=>Rp,addQualifyingStructure:()=>QU,addVoluntaryConsolationStage:()=>KU,addVoluntaryConsolationStructure:()=>Qf,allPlayoffPositionsFilled:()=>eS,alternateDrawPositionAssignment:()=>OU,assignDrawPosition:()=>dP,assignDrawPositionBye:()=>Cr,attachConsolationStructures:()=>cP,attachPlayoffStructures:()=>mg,attachQualifyingStructure:()=>ig,attachStructures:()=>dg,autoSeeding:()=>N_,automatedPlayoffPositioning:()=>Tc,automatedPositioning:()=>Sc,checkValidEntries:()=>Ad,deleteAdHocMatchUps:()=>lP,drawMatic:()=>wd,findDrawDefinition:()=>PS,generateAdHocMatchUps:()=>Ru,generateAdHocRounds:()=>xd,generateAndPopulatePlayoffStructures:()=>Id,generateDrawDefinition:()=>La,generateDrawMaticRound:()=>Dd,generateDrawStructuresAndLinks:()=>Ed,generateDrawTypeAndModifyDrawDefinition:()=>Ud,generateQualifyingStructure:()=>cd,generateVoluntaryConsolation:()=>qS,getAssignedParticipantIds:()=>Ei,getAvailableMatchUpsCount:()=>Sd,getAvailablePlayoffProfiles:()=>Su,getDrawDefinitionTimeItem:()=>lh,getDrawParticipantRepresentativeIds:()=>ES,getDrawTypeCoercion:()=>Mu,getEligibleVoluntaryConsolationParticipants:()=>AS,getMatchUpsMap:()=>ye,getParticipantIdFinishingPositions:()=>US,getPositionAssignments:()=>Op,getPositionsPlayedOff:()=>Ac,getSeedingThresholds:()=>Yh,getSeedsCount:()=>Cu,getStructureSeedAssignments:()=>Hr,getTeamLineUp:()=>is,getValidGroupSizes:()=>Ep,isAdHoc:()=>gr,isCompletedStructure:()=>ei,isValidForQualifying:()=>kS,luckyLoserDrawPositionAssignment:()=>vU,modifyDrawDefinition:()=>uP,modifyDrawName:()=>lg,modifySeedAssignment:()=>GU,mutate:()=>IP,positionActions:()=>GS,pruneDrawDefinition:()=>mP,qualifierDrawPositionAssignment:()=>LU,query:()=>RP,removeDrawPositionAssignment:()=>Iu,removeRoundMatchUps:()=>fP,removeSeededParticipant:()=>zU,removeStructure:()=>$U,renameStructures:()=>qU,resetDrawDefinition:()=>pP,resetVoluntaryConsolationStructure:()=>JE,setDrawParticipantRepresentativeIds:()=>FE,setPositionAssignments:()=>xU,setStructureOrder:()=>YU,setSubOrder:()=>gP,shiftAdHocRounds:()=>_U,swapAdHocRounds:()=>wU,swapDrawPositionAssignments:()=>FU,updateTeamLineUp:()=>Vi,withdrawParticipantAtDrawPosition:()=>RU});var IP={};Zt(IP,{addAdHocMatchUps:()=>hd,addDrawDefinitionTimeItem:()=>sg,addPlayoffStructures:()=>Rp,addQualifyingStructure:()=>QU,addVoluntaryConsolationStage:()=>KU,addVoluntaryConsolationStructure:()=>Qf,alternateDrawPositionAssignment:()=>OU,assignDrawPosition:()=>dP,assignDrawPositionBye:()=>Cr,attachConsolationStructures:()=>cP,attachPlayoffStructures:()=>mg,attachQualifyingStructure:()=>ig,attachStructures:()=>dg,automatedPlayoffPositioning:()=>Tc,automatedPositioning:()=>Sc,deleteAdHocMatchUps:()=>lP,luckyLoserDrawPositionAssignment:()=>vU,modifyDrawDefinition:()=>uP,modifyDrawName:()=>lg,modifySeedAssignment:()=>GU,pruneDrawDefinition:()=>mP,qualifierDrawPositionAssignment:()=>LU,removeDrawPositionAssignment:()=>Iu,removeRoundMatchUps:()=>fP,removeSeededParticipant:()=>zU,removeStructure:()=>$U,renameStructures:()=>qU,resetDrawDefinition:()=>pP,resetVoluntaryConsolationStructure:()=>JE,setDrawParticipantRepresentativeIds:()=>FE,setPositionAssignments:()=>xU,setStructureOrder:()=>YU,setSubOrder:()=>gP,shiftAdHocRounds:()=>_U,swapAdHocRounds:()=>wU,swapDrawPositionAssignments:()=>FU,updateTeamLineUp:()=>Vi,withdrawParticipantAtDrawPosition:()=>RU});var LE=t=>e=>t[e],Mm=(t=[])=>t.map(fe).filter(Boolean),uf=(t=[])=>t.map(gt).filter(Boolean),gt=(t={})=>LE(t)("participantId");var fe=(t={})=>LE(t)("matchUpId"),zc=(t={})=>LE(t)("drawId");function FE({representativeParticipantIds:t,drawDefinition:e}){if(!e)return{error:dr};if(!Array.isArray(t))return{error:G};let r=uf(e?.entries||[]);return t.length&&jt(t,r).length<t.length?{error:G}:np({drawDefinition:e,extension:{name:KI,value:t}})}var Ar="ABANDONED",ic="AWAITING_RESULT",Nt="BYE",Kn="CANCELLED",me="COMPLETED",Qc="DEAD_RUBBER",bt="DEFAULTED",Ne="DOUBLE_DEFAULT",ge="DOUBLE_WALKOVER",Cn="IN_PROGRESS",Fn="INCOMPLETE",GE="NOT_PLAYED",er="RETIRED",Zi="SUSPENDED",Qt="TO_BE_PLAYED",vt="WALKOVER",PR=[ic,me,bt,Cn,Fn,er,Zi],QI=[ic,me,bt,ge,Ne,Cn,Fn,er,Zi,vt],XI=[Ar,ic,Nt,Kn,me,Qc,bt,ge,Ne,Cn,Fn,GE,er,Zi,Qt,vt],JI=[Nt,ge,Ne,me,bt,er,vt],ZI=[Ar,ic,Kn,Qc,Cn,Fn,GE,Zi,Qt,void 0],ae=[Kn,Ar,me,Qc,bt,ge,Ne,er,vt],Cm=[Ar,me,bt,ge,Ne,Cn,er,vt],th=[Cn,Fn,Zi,Qt],eh={ABANDONED:Ar,AWAITING_RESULT:ic,BYE:Nt,CANCELLED:Kn,COMPLETED:me,DEAD_RUBBER:Qc,DEFAULTED:bt,DOUBLE_WALKOVER:ge,DOUBLE_DEFAULT:Ne,IN_PROGRESS:Cn,INCOMPLETE:Fn,NOT_PLAYED:GE,RETIRED:er,SUSPENDED:Zi,TO_BE_PLAYED:Qt,WALKOVER:vt};var tt="MAIN",at="QUALIFYING",He="CONSOLATION",We="VOLUNTARY_CONSOLATION",ue="PLAY_OFF",Rm=[tt,at,He,ue,We],Ls={[at]:1,[tt]:2,[ue]:3,[He]:3,[We]:4},kE="finishingPositions",VE="aggregateEventStructures",BE={[tt]:1,[ue]:2,[He]:3,[at]:4,[We]:5},DR={[ue]:1,[tt]:2,[He]:3,[at]:4,[We]:5},Xc="CLUSTER",NR="SEPARATE",pi="WATERFALL",cp="ITEM",ke="CONTAINER",tn="DRAW",up="RANDOM",pn="TOP_DOWN",mi="BOTTOM_UP",zn="POSITION",po="WINNER",Qn="LOSER",Xn="FIRST_MATCHUP",Xr="AD_HOC",JL="AD_HOC",Ia="FEED_IN",Jc="COMPASS",Zc="OLYMPIC",ZL="SINGLE_ELIMINATION";var mo="SINGLE_ELIMINATION",tu="DOUBLE_ELIMINATION",eu="FIRST_MATCH_LOSER_CONSOLATION",pp="FIRST_ROUND_LOSER_CONSOLATION",xi="LUCKY_DRAW",pf="CURTIS_CONSOLATION",MR="CURTIS_CONSOLATION",rh="FEED_IN_CHAMPIONSHIP_TO_SF",bm="FEED_IN_CHAMPIONSHIP_TO_SF",nh="FEED_IN_CHAMPIONSHIP_TO_QF",vm="FEED_IN_CHAMPIONSHIP_TO_QF",oh="FEED_IN_CHAMPIONSHIP_TO_R16",Om="FEED_IN_CHAMPIONSHIP_TO_R16",HE="MODIFIED_FEED_IN_CHAMPIONSHIP",_m="MODIFIED_FEED_IN_CHAMPIONSHIP",mp="FEED_IN_CHAMPIONSHIP",CR="DOUBLE_ROUND_ROBIN",fn="ROUND_ROBIN",lo="ROUND_ROBIN_WITH_PLAYOFF",WE="DECIDER",jE="BACKDRAW",mf={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"}},df={0:{name:"East",abbreviation:"E"},"0-1":{name:"West",abbreviation:"W"},"0-2":{name:"North",abbreviation:"N"},"0-1-1":{name:"South",abbreviation:"S"}},Fs="WIN_RATIO",wi="ROUND_OUTCOME",YE=[Jc,pf,vm,Om,bm,mp,nh,oh,rh,eu,pp,xi,_m,Zc,ue,lo],tF=[Xr,Jc,pf,tu,vm,Om,bm,mp,Ia,eu,pp,xi,_m,Zc,ue,fn,lo,mo],qE={MAIN:tt,QUALIFYING:at,CONSOLATION:He,ITEM:cp,CONTAINER:ke,FIRST_MATCHUP:Xn,WINNER:po,LOSER:Qn,AD_HOC:Xr,FEED_IN:Ia,FLEX_ROUNDS:JL,COMPASS:Jc,PLAY_OFF:ue,OLYMPIC:Zc,KNOCKOUT:ZL,SINGLE_ELIMINATION:mo,DOUBLE_ELIMINATION:tu,CURTIS:pf,FICSF:rh,FICQF:nh,FICR16:oh,MFIC:HE,VOLUNTARY_CONSOLATION:We,FIRST_MATCH_LOSER_CONSOLATION:eu,FIRST_ROUND_LOSER_CONSOLATION:pp,MODIFIED_FEED_IN_CHAMPIONSHIP:_m,FEED_IN_CHAMPIONSHIP_TO_R16:Om,FEED_IN_CHAMPIONSHIP_TO_QF:vm,FEED_IN_CHAMPIONSHIP_TO_SF:bm,FEED_IN_CHAMPIONSHIP:mp,LUCKY_DRAW:xi,ROUND_ROBIN_WITH_PLAYOFF:lo,ROUND_ROBIN:fn,DECIDER:WE,BACKDRAW:jE,COMPASS_ATTRIBUTES:mf,OLYMPIC_ATTRIBUTES:df,DRAW:tn,RANDOM:up,TOP_DOWN:pn,BOTTOM_UP:mi,WATERFALL:pi,WIN_RATIO:Fs,ROUND_OUTCOME:wi,MULTI_STRUCTURE_DRAWS:YE,generatedDrawTypes:tF,stageOrder:Ls,finishOrder:BE,AGGREGATE_EVENT_STRUCTURES:VE,FINISHING_POSITIONS:kE},RR=qE;function di(t,e,r){let n=m=>dt({element:m,name:ln})?.extension?.value,o=r?.deprioritizeCompleted,i=r?.mode===VE&&DR,s=r?.mode===kE&&BE,a=s||i||Ls,c=m=>m?.stage===tt&&m?.stageSequence===1,u=m=>c(m)?-1:a[m?.stage],p=m=>m?.matchUps.every(({matchUpStatus:d})=>ae.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)||(lf(t)||0)-(lf(e)||0)}function lf(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(t){let e=ut(t,[{[Or]:!0,[Sm]:!0}]);if(e.error)return e;let{drawDefinition:r,structureId:n}=t,{structures:o}=Gn({drawDefinition:r}),i=o?.map(c=>c.structures?[...c.structures].concat(c):c).flat(),s=i?.find(c=>c.structureId===n);if(!s)return{error:Gt};let a=s.structureType===cp?i?.find(c=>c.structures?.some(u=>u.structureId===n)):void 0;return{structure:s,containingStructure:a}}function Gn({withStageGrouping:t,drawDefinition:e,stageSequences:r,stageSequence:n,roundTarget:o,sortConfig:i,stages:s,stage:a}){let c=!e&&X||!e?.structures&&Al||void 0;if(c)return{error:c,structures:[],stageStructures:{}};let u=f=>{let g=dt({element:f,name:ln})?.extension?.value;return!o||o===g},p=e?.structures?.filter(d).filter(l).filter(u).sort((f,g)=>di(f,g,i))??[],m=t?Object.assign({},...Rm.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 ih({drawDefinition:t}){if(!t)return{error:X};let e={};return{allPositionedParticipantIds:(t.structures||[]).map(n=>{let o=n.stage;e[o]||(e[o]=[]);let{positionAssignments:i}=Ct({structure:n}),s=i?.map(gt).filter(Boolean)??[];return e[o].push(...s),s}).flat(),stagePositionedParticipantIds:e}}function Ct({drawDefinition:t,structureId:e,structure:r}){let n,o=[];if(!r){if(!t)return{positionAssignments:o,error:X};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=>Ct({structure:i}).positionAssignments)):r.positionAssignments?o=r.positionAssignments:n=DA,{positionAssignments:o,error:n}}function de({drawDefinition:t,structureId:e,structure:r}){let n=Ct({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 ff="addDrawDefinition",dp="addMatchUps",$o="addParticipants",gf="addScaleItems",sh="addVenue",ha="audit",ah="dataIssue",If="deleteParticipants",hf="deleteVenue",Sf="deletedDrawIds",Tf="deletedMatchUpIds",yf="modifyDrawDefinition",$E="modifyDrawEntries",KE="modifyEventEntries",Af="modifyMatchUp",Xe="modifyParticipants",Ef="modifyPositionAssignments",Uf="modifySeedAssignments",zE="modifyTournamentDetail",li="modifyVenue",xm="mutations",ch="publishEvent",QE="publishEventSeeding",XE="publishOrderOfPlay",Pf="unPublishEvent",Df="unPublishEventSeeding",Nf="unPublishOrderOfPlay",lp="updateInContextMatchUp",bR={ADD_DRAW_DEFINITION:ff,ADD_MATCHUPS:dp,ADD_PARTICIPANTS:$o,ADD_SCALE_ITEMS:gf,ADD_VENUE:sh,AUDIT:ha,DATA_ISSUE:ah,DELETE_PARTICIPANTS:If,DELETE_VENUE:hf,DELETED_DRAW_IDS:Sf,DELETED_MATCHUP_IDS:Tf,MODIFY_DRAW_DEFINITION:yf,MODIFY_DRAW_ENTRIES:$E,MODIFY_EVENT_ENTRIES:KE,MODIFY_MATCHUP:Af,MODIFY_PARTICIPANTS:Xe,MODIFY_POSITION_ASSIGNMENTS:Ef,MODIFY_SEED_ASSIGNMENTS:Uf,MODIFY_TOURNAMENT_DETAIL:zE,MODIFY_VENUE:li,MUTATIONS:xm,PUBLISH_EVENT_SEEDING:QE,PUBLISH_EVENT:ch,PUBLISH_ORDER_OF_PLAY:XE,UNPUBLISH_EVENT_SEEDING:Df,UNPUBLISH_EVENT:Pf,UNPUBLISH_ORDER_OF_PLAY:Nf,UPDATE_INCONTEXT_MATCHUP:lp};function uh(t,e){if(!t)return{error:X};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 No({drawDefinition:t,tournamentId:e,matchUps:r,eventId:n}){return t&&uh(t),St({payload:{matchUps:r,tournamentId:e,eventId:n},topic:dp}),{...R}}function kn({drawDefinition:t,tournamentId:e,matchUpIds:r,eventId:n,action:o}){t&&uh(t),St({topic:Tf,payload:{tournamentId:e,matchUpIds:r,eventId:n,action:o}});for(let i of r)_I({key:i});return{...R}}function It({drawDefinition:t,tournamentId:e,structureId:r,context:n,eventId:o,matchUp:i}){return i?(t&&Ot({drawDefinition:t,structureIds:r?[r]:void 0,tournamentId:e,eventId:o}),St({topic:Af,payload:{matchUp:i,tournamentId:e,context:n},key:i.matchUpId}),{...R}):(console.log(cr),{error:cr})}function vR({tournamentId:t,inContextMatchUp:e}){return e?(St({payload:{inContextMatchUp:e,tournamentId:t},topic:lp,key:e.matchUpId}),{...R}):{error:cr}}function Sa({tournamentId:t,eventId:e,drawDefinition:r}){return r?(uh(r),St({payload:{drawDefinition:r,tournamentId:t,eventId:e},topic:ff,key:r.drawId}),{...R}):(console.log(X),{error:X})}function OR({tournamentId:t,eventId:e,drawId:r}){return St({payload:{drawId:r,tournamentId:t,eventId:e},topic:Sf,key:r}),_I({key:r}),{...R}}function Ot({drawDefinition:t,tournamentId:e,structureIds:r,eventId:n}){return t?(uh(t,r),St({payload:{tournamentId:e,eventId:n,drawDefinition:t},topic:yf,key:t.drawId}),{...R}):{error:X}}function ph({drawDefinition:t,tournamentId:e,structure:r,eventId:n}){if(!t)return{error:X};if(!r)return{error:Oo};let o=r.seedAssignments,i=r.structureId,s=t.drawId;return St({payload:{tournamentId:e,eventId:n,drawId:s,structureId:i,seedAssignments:o},topic:Uf,key:t.drawId}),Ot({structureIds:[i],drawDefinition:t,tournamentId:e,eventId:n}),{...R}}function Mo({drawDefinition:t,tournamentId:e,structure:r,event:n}){if(!t)return{error:X};if(!r)return{error:Oo};let o=Ct({structure:r}),i=r.structureId,s=t.drawId,a=n?.eventId;return St({topic:Ef,payload:{positionAssignments:o,tournamentId:e,structureId:i,eventId:a,drawId:s},key:i}),Ot({structureIds:[i],drawDefinition:t,tournamentId:e,eventId:a}),{...R}}function JE({tournamentRecord:t,drawDefinition:e,resetEntries:r,event:n}){if(!e)return{error:X};let o=e.structures?.find(s=>s.stage===We);if(!o)return{error:Gt};let i=o.matchUps?.map(({matchUpId:s})=>s)||[];return o.positionAssignments=[],o.seedAssignments=[],o.matchUps=[],kn({tournamentId:t?.tournamentId,action:"resetVoluntaryConsolationStructure",matchUpIds:i,drawDefinition:e}),r&&(e.entries=e.entries.filter(s=>s.entryStage!==We)),Ot({tournamentId:t?.tournamentId,eventId:n?.eventId,drawDefinition:e,structureIds:[o.structureId]}),{...R}}function wm({drawPositions:t,structure:e}){if([at,tt].includes(e.stage)&&e.stageSequence===1)return;let{positionAssignments:r}=Ct({structure:e});r?.filter(({drawPosition:o})=>t?.includes(o))?.forEach(o=>{yt({element:o,extension:{name:Pm,value:!0}})})}function ru(t){let{appliedPolicies:e,positionAction:r,drawDefinition:n}=t;if(e?.audit?.[ap]===!1)return;let{extension:o}=dt({name:ap,element:n}),i=Array.isArray(o?.value)?o?.value??[]:[];if(!i?.length){let a=n.structures.find(c=>c.stage===tt);if(a){let c=Ct({structure:a}).positionAssignments?.map(({drawPosition:u,participantId:p,bye:m,qualifier:d})=>({drawPosition:u,participantId:p,qualifier:d,bye:m}));i.push({name:"initialMainAssignments",initialAssignments:c})}}let s={value:i.concat(r),name:ap};yt({element:n,extension:s})}function ts({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 Ta="SINGLES",Kt="SINGLES",Li="DOUBLES",wt="DOUBLES",gn="TEAM",Bt="TEAM",_R={SINGLES_MATCHUP:Ta,SINGLES:Kt,DOUBLES_MATCHUP:Li,DOUBLES:wt,TEAM_MATCHUP:gn,TEAM:Bt};function nu(t){let{sides:e,matchUpType:r}=t||{},n=t.potentialParticipants?.length?t.potentialParticipants.flat().map(s=>r===wt?s?.individualParticipantIds||[]:s.participantId).flat():[],o=(e||[]).map(s=>r===wt&&(s?.participant?.individualParticipantIds||[])||s?.participantId&&[s.participantId]||[]).flat();return{individualParticipantIds:o.concat(n).flat(),enteredIndividualParticipantIds:o,potentialIndividualParticipantIds:n}}function en(t){return t?.tournamentRecords??(t?.tournamentRecord&&{[t.tournamentRecord.tournamentId]:t.tournamentRecord})??{}}var sc="SIGN_IN_STATUS",ZE="SIGNED_OUT",ou="SIGNED_IN",rn="TEAM",Tt="INDIVIDUAL",Er="GROUP",lt="PAIR",xt="TEAM",iu={TEAM_PARTICIPANT:rn,INDIVIDUAL:Tt,GROUP:Er,TEAM:xt,PAIR:lt},xR={INDIVIDUAL:Tt,GROUP:Er,PAIR:lt,TEAM:xt,SIGN_IN_STATUS:sc,SIGNED_OUT:ZE,SIGNED_IN:ou};function Lm({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===xt),s=o.filter(c=>c.participantType===Er),a=o.filter(c=>c.participantType===lt);return o.forEach(c=>{if(c.participantType===Tt){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 tU(t){return t&&typeof String.fromCodePoint<"u"?t.toUpperCase().replace(/./g,e=>String.fromCodePoint(e.charCodeAt(0)+127397)):t}function wR(t){let e=Object.assign({},...Ko.filter(r=>r.ioc).map(r=>({[r.ioc]:r.iso})));return tU(e[t])}var Ko=[{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=Ko.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 LR({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?_i({template:e,source:s}):s)}}}}function fo(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:re}}function dh(t){let{tournamentRecord:e,participantId:r}=t;if(r){let o=fo({tournamentRecord:e,participantId:r});return o.participant??o}let n=t.element||t.drawDefinition||t.event||t.tournamentRecord;return n||{error:rt}}function Vn(t){let{returnPreviousValues:e,itemSubTypes:r,itemType:n}=t,o=dh(t);if(o.error)return o;if(r&&!Array.isArray(r))return{error:G,context:{itemSubTypes:r}};if(!Array.isArray(o.timeItems))return{error:Fl};let i=o.timeItems.filter(a=>a?.itemType===n).filter(a=>!r?.length||r.some(c=>a?.itemSubTypes?.includes(c))).sort((a,c)=>{let u=new Date(a.createdAt||void 0).getTime(),p=new Date(c.createdAt||void 0).getTime();return u-p}),s=i.pop();if(s){let a={timeItem:s,...R};return e&&Object.assign(a,{previousItems:i}),a}else return{info:Le}}function lh({returnPreviousValues:t,drawDefinition:e,itemSubTypes:r,itemType:n}){if(!e)return{error:$r};if(!e.timeItems)return{info:Le};let{timeItem:o,previousItems:i,info:s}=Vn({element:e,returnPreviousValues:t,itemSubTypes:r,itemType:n});return o&&{timeItem:o,previousItems:i}||{info:s}}function su({returnPreviousValues:t,itemSubTypes:e,itemType:r,event:n}){if(!n)return{error:Dt};if(!n.timeItems)return{info:Le};let{timeItem:o,previousItems:i,info:s}=Vn({returnPreviousValues:t,element:n,itemSubTypes:e,itemType:r});return o&&{timeItem:o,previousItems:i}||{info:s}}function au({returnPreviousValues:t,tournamentRecord:e,itemSubTypes:r,itemType:n}){if(!e)return{error:j};if(!e.timeItems)return{info:Le};let{timeItem:o,previousItems:i,info:s}=Vn({element:e,returnPreviousValues:t,itemSubTypes:r,itemType:n});return o&&{timeItem:o,previousItems:i}||{info:s}}function fh({returnPreviousValues:t,tournamentRecord:e,participantId:r,itemSubTypes:n,itemType:o}){if(!e)return{error:j};if(!r)return{error:ee};let i=fo({tournamentRecord:e,participantId:r});if(i.error)return i;let{participant:s}=i;if(!s?.timeItems)return{info:Le};let{timeItem:a,previousItems:c,info:u}=Vn({element:i.participant,returnPreviousValues:t,itemSubTypes:n,itemType:o});return a&&{timeItem:a,previousItems:c}||{info:u}}var eF={[Er]:"groupParticipantIds",[lt]:"pairParticipantIds",[xt]:"teamParticipantIds"},rF={[Er]:"groups",[xt]:"teams"};function gh({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&&iF({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&&oF({individualParticipantIds:d,participantCopy:p,participantMap:c,participantType:l,participantId:m}),n&&(c[m].participant.signedIn=nF(p)),o){let{ratings:f,rankings:g,seedings:I}=pa({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=Pt(t)?t:void 0;LR({participantMap:c,template:u})}return{participantMap:c}}function nF(t){let{timeItem:e}=Vn({itemType:sc,element:t});return e?.itemValue===ou}function oF({individualParticipantIds:t,participantCopy:e,participantMap:r,participantType:n,participantId:o}){for(let i of t){let s=r[i].participant;if(s[eF[n]].push(o),[xt,Er].includes(n)){let{participantRoleResponsibilities:a,participantOtherName:c,participantName:u,participantId:p,teamId:m}=e,d=rF[n];s[d].push({participantRoleResponsibilities:a,participantOtherName:c,participantName:u,participantId:p,teamId:m})}if(n===lt){let a=t.find(c=>c!==i);r[i].pairIdMap[o]=a,r[i].pairIdMap[a]=o}}}function iF({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:{[Kt]:{...r},[wt]:{...r},[xt]:{...r},...r}}}function fi({participantsProfile:t,useParticipantMap:e,tournamentRecord:r,contextProfile:n,inContext:o}){if(e)return{participantMap:gh({...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}=Lm({participantsProfile:t,deepCopy:!1,participants:i})),t?.withScaleValues&&i?.length)for(let a of i){let{ratings:c,rankings:u}=pa({participant:a});a.rankings=u,a.ratings=c}return{participants:i,groupInfo:s}}function ht({onlySpecifiedPolicyTypes:t=!1,policyTypes:e=[],tournamentRecord:r,drawDefinition:n,structure:o,event:i}){if(!Array.isArray(e))return{error:yI};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===qc)?.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 Co({policyTypes:t=[],tournamentRecord:e,drawDefinition:r,structure:n,event:o}){if(!Array.isArray(t))return{error:yI};let{appliedPolicies:i}=ht({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:Fc.message}}var Ih="WALKOVER",eU="RETIRED",Fm="COMPETITIVE",ac="ROUTINE",cc="DECISIVE",Gm="winRatio";var sF={[ui]:{policyName:"Competitive Bands Default",profileBands:{[cc]:20,[ac]:50}}},km=sF;function Bn({policyDefinitions:t,tournamentRecord:e,contextProfile:r,drawDefinition:n,event:o}){let i={policies:{}};if(!r)return i;let s=Co({tournamentRecord:e,drawDefinition:n,event:o}).policyDefinitions;if(r.withCompetitiveness){let a=t?.[ui]??s?.[ui]??km[ui];i.policies[ui]=a}return i}function zo({tournamentRecord:t,drawDefinition:e,policyType:r,structure:n,event:o}){if(!t)return{error:j};let{appliedPolicies:i}=ht({tournamentRecord:t,drawDefinition:e,structure:n,event:o});return i?.[r]?{policy:i[r]}:{info:Fc?.message}}function ya({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}=zo({policyType:Uo,tournamentRecord:t,event:n}),s=(t?dt({element:t,name:Fo}).extension:void 0)?.value,c=(n&&dt({name:Fo,element:n}).extension)?.value;return{scheduleTiming:{tournamentScheduling:s,eventScheduling:c,categoryName:e,categoryType:r,policy:o}}}function Mf({drawDefinition:t,attributes:e}){let{extension:r}=dt({element:t,name:Dm}),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:Dm,value:n},np({drawDefinition:t,extension:r}),{entryProfile:n}}function cu({drawDefinition:t}){let{extension:e}=dt({element:t,name:Dm});return{entryProfile:e?.value||{}}}var kr="ALTERNATE",Cf="CONFIRMED",Vr="DIRECT_ACCEPTANCE",Vm="FEED_IN",Rf="JUNIOR_EXEMPT",es="LUCKY_LOSER",bf="ORGANISER_ACCEPTANCE",Bm="QUALIFIER",aF="REGISTERED",vf="SPECIAL_EXEMPT",Br="UNGROUPED",gi="UNPAIRED",uu="WILDCARD",Jn="WITHDRAWN",Of=[Cf,Vr,Rf,bf,vf],rU=[Vm,es,Bm],Qo=[Cf,Vr,Vm,Rf,bf,vf,uu],wr=[Cf,Vr,Rf,es,Bm,bf,vf,uu],nU=[kr,Cf,Vr,Vm,Rf,es,bf,Bm,aF,vf,Br,gi,uu,Jn],FR={ALTERNATE:kr,CONFIRMED:Cf,DIRECT_ACCEPTANCE:Vr,DIRECT_ENTRY_STATUSES:Qo,DRAW_SPECIFIC_STATUSES:rU,EQUIVALENT_ACCEPTANCE_STATUSES:Of,FEED_IN:Vm,JUNIOR_EXEMPT:Rf,LUCKY_LOSER:es,ORGANISER_ACCEPTANCE:bf,QUALIFIER:Bm,SPECIAL_EXEMPT:vf,STRUCTURE_SELECTED_STATUSES:wr,UNGROUPED:Br,UNPAIRED:gi,VALID_ENTRY_STATUSES:nU,WILDCARD:uu,WITHDRAWN:Jn};function _f({stage:t,drawDefinition:e}){let{entryProfile:r}=cu({drawDefinition:e}),n=Object.keys(r).includes(t);if(!n&&Rm.includes(t)){let o=[{[t]:{drawSize:void 0,alternates:!0}}];return Mf({drawDefinition:e,attributes:o}),!0}return n}function GR({stage:t,drawDefinition:e}){let{entryProfile:r}=cu({drawDefinition:e});return r[t]?.alternates||0}function kR({stage:t,drawDefinition:e}){let{entryProfile:r}=cu({drawDefinition:e});return r[t]?.wildcardsCount||0}function hh({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=dt({name:ln,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===ue){let{playoffEntries:p,error:m}=cF({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 cF({provisionalPositioning:t,drawDefinition:e,structureId:r}){let n=[],o=(e.links??[]).find(i=>i.linkType===zn&&i.target.structureId===r);if(o){let{finishingPositions:i,structureId:s}=o.source,{structure:a}=st({drawDefinition:e,structureId:s});a?.structureType===ke&&(a.structures??[]).forEach(u=>{let p=u.positionAssignments??[],{structureId:m}=u,d=m,l=Object.assign({},...p.map(h=>{let{participantId:S}=h,T=dt({element:h,name:qo}).extension?.value;return T&&S?{[S]:T}:void 0}).filter(Boolean)),g=Object.keys(l).reduce((h,S)=>{let T=l[S],y=T.groupOrder||t&&T.provisionalOrder;return h.includes(y)||h.push(y),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:y,GEMscore:N}=S,E=T||t&&y,A=[...i??[]].sort(se).indexOf(E)+1;n.push({entryStage:ue,entryStatus:Vm,placementGroup:A,groupingValue:d,participantId:h,GEMscore:N})})})}return{playoffEntries:n}}function VR({stage:t,drawDefinition:e}){return Qo.reduce((r,n)=>(hh({drawDefinition:e,entryStatus:n,stage:t})||0)+r,0)}function Hr({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=Ct({structure:o}).positionAssignments;if(i||!o)return{seedAssignments:[],error:Gt};n||(n=o.structureId);let{stage:c,stageSequence:u}=o,m=c===ue&&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=IA;let f=o.seedLimit??o?.positionAssignments?.length;return{seedAssignments:s,stageSequence:u,seedLimit:f,stage:c,error:i}}var uF=(t,e)=>(t||0)+(e||0);function Sh(t,e){let r=Array.isArray(t)?t[0]:t;return isNaN(r)&&Ih||r<=e[cc]&&cc||r<=e[ac]&&ac||Fm}function Th({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(uF)&&(r[n[0]>n[1]?0:1]+=1),{sets:e,games:r,score:t}}function pF(t){let e=Math.min(...t.games),r=Math.max(...t.games);return Math.round(e/r*100)}function yh(t){return t.map(pF).sort().map(e=>parseFloat(e.toFixed(2)))}function pu({tournamentRecord:t,profileBands:e,matchUp:r}){if(!r)return{error:cr};let{score:n,winningSide:o}=r;if(!o)return{error:G};let i=!e&&t&&zo({policyType:ui,tournamentRecord:t}).policy,s=e||i?.profileBands||km[ui].profileBands,a=Th({score:n}),c=yh([a]),u=Sh(c,s),p=Array.isArray(c)?c[0]:c;return{...R,competitiveness:u,pctSpread:p}}function Ah({matchUp:t}){if(!t)return{error:cr};if(t&&!t.sides)return{error:Ze};if(t&&!t.hasContext)return{error:kc};let e=(t.sides??[])?.map(a=>a?.participantId).filter(Boolean),r=t.sides?.filter(a=>a.participant?.participantType===Tt).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=pt(i.concat(e)).filter(Boolean)??[];return{nestedIndividualParticipantIds:o,allRelevantParticipantIds:s,individualParticipantIds:i,sideParticipantIds:e,...R}}var Hm="CHECK_IN",Wm="CHECK_OUT",BR="SCHEDULE",Gs="SCHEDULE.ASSIGNMENT.VENUE",Ro="SCHEDULE.ALLOCATION.COURTS",hi="SCHEDULE.ASSIGNMENT.COURT",xf="SCHEDULE.COURT.ORDER",ks="SCHEDULE.DATE",mF="COMPLETED.DATE",Eh="HOME_PARTICIPANT_ID",oU="SCHEDULE.ASSIGN.OFFICIAL",Vs="SCHEDULE.TIME.SCHEDULED",bo="SCHEDULE.TIME.START",Fi="SCHEDULE.TIME.STOP",Si="SCHEDULE.TIME.RESUME",Ti="SCHEDULE.TIME.END",wf="SCHEDULE.TIME.MODIFIERS",HR="TO_BE_ANNOUNCED",WR="NEXT_AVAILABLE",jR="FOLLOWED_BY",YR="AFTER_REST",qR="RAIN_DELAY",dF="NOT_BEFORE",Uh=[HR,WR,jR,YR,qR],lF="ELIGIBILITY",fF="REGISTRATION",gF="SUSPENSION",IF="MEDICAL",hF="PENALTY",iU="SCALE",sU="RATING",aU="RANKING",Lf="SEEDING",Xo="PUBLISH",Wr="PUBLIC",Jo="STATUS",SF="MODIFICATION",TF="RETRIEVAL",yF="other",$R={MUTUALLY_EXCLUSIVE_TIME_MODIFIERS:Uh,AFTER_REST:YR,ALLOCATE_COURTS:Ro,ASSIGN_COURT:hi,ASSIGN_OFFICIAL:oU,ASSIGN_VENUE:Gs,CHECK_IN:Hm,CHECK_OUT:Wm,COMPLETED_DATE:mF,COURT_ORDER:xf,ELIGIBILITY:lF,END_TIME:Ti,FOLLOWED_BY:jR,MEDICAL:IF,MODIFICATION:SF,NEXT_AVAILABLE:WR,NOT_BEFORE:dF,OTHER:yF,PENALTY:hF,PUBLIC:Wr,PUBLISH:Xo,RANKING:aU,RATING:sU,RAIN_DELAY:qR,REGISTRATION:fF,RESUME_TIME:Si,RETRIEVAL:TF,SCALE:iU,SCHEDULE:BR,SCHEDULED_DATE:ks,SCHEDULED_TIME:Vs,SEEDING:Lf,START_TIME:bo,STATUS:Jo,STOP_TIME:Fi,SUSPENSION:gF,TIME_MODIFIERS:wf,TO_BE_ANNOUNCED:HR};function rs({matchUp:t}){if(!t)return{error:cr};if(!t.hasContext)return{error:kc};if(!t.sides||t.sides.filter(Boolean).length!==2)return{error:Ze};let{nestedIndividualParticipantIds:e,allRelevantParticipantIds:r,sideParticipantIds:n}=Ah({matchUp:t}),i=(t.timeItems??[]).filter(u=>u?.itemType&&[Hm,Wm].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===Hm);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}}var Ph={[Kt]:[Kt,"S"],[wt]:[wt,"D"],[Bt]:[Bt,"T"],S:[Kt,"S"],D:[wt,"D"],T:[Bt,"T"]};var ie=t=>e=>{let r=Pt(e)&&e?.matchUpType||Re(e)&&e;return r&&Ph[t].includes(r)};function fp(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 gp(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 Dh({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 KR({tournamentScheduling:t,eventScheduling:e,averageMinutes:r,defaultTiming:n,matchUpFormat:o,categoryName:i,categoryType:s,policy:a}){let c=e?.matchUpRecoveryTimes&&gp({...e,averageMinutes:r,matchUpFormat:o}),u=t?.matchUpRecoveryTimes&&gp({...t,averageMinutes:r,matchUpFormat:o}),p=a?.matchUpRecoveryTimes&&gp({...a,averageMinutes:r,matchUpFormat:o}),m=[c,u,p,a?.defaultTimes?.recoveryTimes,n?.recoveryTimes];return Dh({categoryName:i,categoryType:s,timesBlockArray:m})}function zR({matchUpFormat:t,categoryName:e,categoryType:r,defaultTiming:n,tournamentScheduling:o,eventScheduling:i,policy:s}){let a=i?.matchUpAverageTimes&&fp({...i,matchUpFormat:t}),c=o?.matchUpAverageTimes&&fp({...o,matchUpFormat:t}),u=s?.matchUpAverageTimes&&fp({...s,matchUpFormat:t}),p=[a,c,u,s?.defaultTimes?.averageTimes,n?.averageTimes];return Dh({categoryName:e,categoryType:r,timesBlockArray:p})}var cU="DOUBLES_SINGLES",uU="SINGLES_DOUBLES",Zn="total",Nh="participantConflict",Aa="matchUpConflict",pU="ISSUE_IDS",uc="CONFLICT",pc="WARNING",Mh="ERROR",Ch="ISSUE",Ff="STATE",QR={SINGLES_DOUBLES:uU,DOUBLES_SINGLES:cU,TOTAL:Zn,CONFLICT_MATCHUP_ORDER:Aa,CONFLICT_PARTICIPANTS:Nh,SCHEDULE_ISSUE_IDS:pU,SCHEDULE_CONFLICT:uc,SCHEDULE_WARNING:pc,SCHEDULE_ERROR:Mh,SCHEDULE_ISSUE:Ch,SCHEDULE_STATE:Ff};var go="SINGLES",Bs="SINGLES",Jr="DOUBLES",yi="DOUBLES",Ve="TEAM",jr="TEAM",AF="AGE",EF="RATING",UF="BOTH",XR={AGE:AF,BOTH:UF,DOUBLES:Jr,DOUBLES_EVENT:yi,RATING:EF,SINGLES:go,SINGLES_EVENT:Bs,TEAM_EVENT:jr,TEAM:Ve};function mu({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??Bs;let c={averageTimes:[{minutes:{default:t}}],recoveryTimes:[{minutes:{default:e}}]},{scheduleTiming:u}=ya({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=zR(t),n=Object.keys(r?.minutes||{}),o=r?.minutes&&(n?.includes(e)&&r.minutes[e]||r.minutes.default),i=KR({...t,averageMinutes:o}),s=Object.keys(i?.minutes||{}),a=i?.minutes&&(s?.includes(e)&&i.minutes[e]||i.minutes.default),c=ie(Bs)(e)?uU:cU,u=i?.minutes&&(s?.includes(c)&&i.minutes[c]||a);return{averageMinutes:o,recoveryMinutes:a,typeChangeRecoveryMinutes:u}}function Rh(t){return t.createdAt?new Date(t.createdAt).getTime():0}function Io({visibilityThreshold:t,timeItems:e,itemType:r}){let n=e.filter(i=>i&&i.itemType===r&&(!t||Rh(i)<new Date(t).getTime())).sort((i,s)=>Rh(i)-Rh(s)).pop(),o=n&&Rh(n);return{itemValue:n?.itemValue,timeStamp:o}}function Gf({visibilityThreshold:t,timeStamp:e,schedule:r,matchUp:n}){let{itemValue:o,timeStamp:i}=Io({timeItems:n?.timeItems||[],itemType:Vs,visibilityThreshold:t});return!r||i&&e&&new Date(i).getTime()>new Date(e).getTime()?{scheduledTime:o}:r}function ns({visibilityThreshold:t,timeStamp:e,schedule:r,matchUp:n}){let{itemValue:o,timeStamp:i}=Io({timeItems:n?.timeItems||[],itemType:ks,visibilityThreshold:t});return!r||i&&e&&new Date(i).getTime()>new Date(e).getTime()?{scheduledDate:o}:r}function bh({visibilityThreshold:t,timeStamp:e,schedule:r,matchUp:n}){let{itemValue:o,timeStamp:i}=Io({timeItems:n?.timeItems||[],itemType:Ro,visibilityThreshold:t});return!r||i&&e&&new Date(i).getTime()>new Date(e).getTime()?{allocatedCourts:J(o,!1,!0)}:r}function vh({visibilityThreshold:t,timeStamp:e,schedule:r,matchUp:n}){let{itemValue:o,timeStamp:i}=Io({timeItems:n?.timeItems||[],itemType:hi,visibilityThreshold:t});return!r||i&&e&&new Date(i).getTime()>new Date(e).getTime()?{courtId:o}:r}function Oh({visibilityThreshold:t,timeStamp:e,schedule:r,matchUp:n}){let{itemValue:o,timeStamp:i}=Io({timeItems:n?.timeItems||[],itemType:Gs,visibilityThreshold:t});return!r||i&&e&&new Date(i).getTime()>new Date(e).getTime()?{venueId:o}:r}function kf({visibilityThreshold:t,timeStamp:e,schedule:r,matchUp:n}){let{itemValue:o,timeStamp:i}=Io({timeItems:n?.timeItems||[],itemType:wf,visibilityThreshold:t});return!r||i&&e&&new Date(i).getTime()>new Date(e).getTime()?{timeModifiers:o}:r}function hp(t){if(BI.test(t)){let e=tf();return new Date(`${e}T${t}`)}else return new Date(t)}function JR({matchUp:t}){if(!t)return{error:cr};if(!t.timeItems)return{error:Fl};let e=t.timeItems.filter(n=>[bo,Fi,Si,Ti].includes(n?.itemType)).sort((n,o)=>hp(n.itemValue).getTime()-hp(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 bo:i=0;break;case Ti:if(n.lastValue&&[bo,Si].includes(n.lastType)){let u=hp(o.itemValue).getTime()-hp(n.lastValue).getTime();i=n.milliseconds+u}else i=n.milliseconds;break;case Fi:if([bo,"SCHECULE.TIME.RESUME"].includes(n.lastType)){let u=hp(o.itemValue).getTime()-hp(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([bo,Si].includes(r.lastType)){let n=new Date().getTime()-hp(r.lastValue).getTime();r.milliseconds+=n}return{milliseconds:r.milliseconds,time:PF(r.milliseconds),relevantTimeItems:e}}function PF(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 ZR({visibilityThreshold:t,timeStamp:e,schedule:r,matchUp:n}){let{itemValue:o,timeStamp:i}=Io({timeItems:n?.timeItems||[],itemType:xf,visibilityThreshold:t});return!r||i&&e&&new Date(i).getTime()>new Date(e).getTime()?{courtOrder:o}:r}function tb({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===bo&&s;return a&&(!i||r(a)<r(i))?a:i},void 0)?.itemValue}}function eb(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 mc(t){let{disableNotice:e,venue:r,context:n}=t;if(typeof r!="object")return{error:G};let o=en(t);r.venueId||(r.venueId=Mt());let i;for(let s of Object.values(o)){let a=DF({disableNotice:!0,tournamentRecord:s,context:n,venue:r});if(a?.error)return a;i=a.venue}return e||St({topic:sh,payload:{venue:r}}),nt({...R,venue:i})}function DF({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:zA}:(r&&yt({element:n,extension:{value:r,name:CE}}),t.venues.push(n),e||St({payload:{venue:n,tournamentId:t.tournamentId},topic:sh}),{...R,venue:J(n)})):{error:rt,info:"missing venue"}:{error:j}}function Zo({tournamentRecords:t,tournamentRecord:e,venueId:r}){if(!e)return{error:j};if(!r)return{error:jo};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=Zo({tournamentRecord:c,venueId:r});if(u.success&&u.venue)return mc({tournamentRecord:e,venue:u.venue}),{...R,venue:o}}}return o?{...R,venue:o}:{error:bs}}function _h({convertExtensions:t,...e}){let{tournamentRecords:r,tournamentRecord:n,venueId:o}=e,i=Zo({tournamentRecords:r,tournamentRecord:n,venueId:o});return J(i,t,!0)}function os({tournamentRecords:t,tournamentRecord:e,courtId:r}){if(!e)return{error:j};if(!r)return{error:bi};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=os({tournamentRecord:u,courtId:r});if(p.success)return p.venue&&mc({tournamentRecord:e,venue:p.venue}),{...R,court:o,venue:i}}}return _({result:{error:za},stack:n})}function mU(t){return J(os(t),!1,!0)}function jm({tournamentRecord:t,internalUse:e,courtId:r}){if(!t)return{error:j};if(!r)return{error:bi};let n=os({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 dc({tournamentRecord:t,venueId:e}){if(!t)return{error:j};if(!e)return{error:jo};let r=Zo({tournamentRecord:t,venueId:e});if(r.error)return r;let o=(r.venue?.courts??[]).map(a=>(({courtInfo:c})=>({...c}))(jm({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 rb({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===Ti&&s;return a&&(!i||r(a)>r(i))?a:i},void 0)?.itemValue}}function Ht({event:t,eventId:e}){if(!t)return{error:Dt};let n=dt({name:Qr,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 je(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&&Ht({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,..._({result:{error:lr},stack:o})};return{event:u,drawDefinition:void 0,tournamentId:c}}return{event:void 0,drawDefinition:void 0,..._({result:{error:dr},context:{drawId:n,eventId:r},stack:o})}}function Ym(t){let{visibilityThreshold:e,timeStamp:r,schedule:n,matchUp:o}=t,i=ut(t,[{[Un]:!0}]);if(i.error)return i;let{itemValue:s,timeStamp:a}=Io({timeItems:o?.timeItems||[],itemType:Eh,visibilityThreshold:e});return!n||a&&r&&new Date(a).getTime()>new Date(r).getTime()?{homeParticipantId:s}:n}function qm(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:cr};if(o&&!p.matchUpType&&!t.matchUpType&&(e||i)&&p.drawId){let A=e?.drawDefinitions?.find(C=>C.drawId===p.drawId);!A&&i&&({drawDefinition:A,event:e}=je({tournamentRecord:i,drawId:p.drawId}));let U=p.structureId&&A?.structures?.find(({structureId:C})=>C===p.structureId);r=t.matchUpType||U?.matchUpType||A?.matchUpType||e?.eventType!==Ve&&e?.eventType}let{milliseconds:m,time:d}=JR({matchUp:p}),{startTime:l}=tb({matchUp:p}),{endTime:f}=rb({matchUp:p}),g,{visibilityThreshold:I,eventIds:h,drawIds:S}=n??{};if((!h||h.includes(p.eventId))&&(!S||S.includes(p.drawId))){let A={matchUp:p,visibilityThreshold:I},{allocatedCourts:U}=bh(A),{homeParticipantId:C}=Ym(A),{scheduledTime:P}=Gf(A),{timeModifiers:D}=kf(A),{scheduledDate:M}=ns(A),{venueId:b}=Oh(A),{courtId:v}=vh(A),{courtOrder:O}=ZR(A),w,F,L,x,B,H=p.matchUpType??r;if(a&&P&&o&&H){let et={matchUpFormat:p.matchUpFormat??c,...a};({averageMinutes:F=0,recoveryMinutes:L=0,typeChangeRecoveryMinutes:x=0}=Ip({timingDetails:et,eventType:H})),(F||L)&&(w=f?xr($t(f),L):xr(P,F+L)),x&&(B=f?xr($t(f),x):xr(P,F+x))}!M&&P&&(M=Ut(P));let W=Am({scheduledDate:M,scheduledTime:P}),V={},Y=(i&&b&&dc({tournamentRecord:i,venueId:b}))?.venueData||{};b&&(V[b]=Y);let{venueName:$,venueAbbreviation:k,courtsInfo:K}=Y,q=(v&&K?.find(et=>et.courtId===v))?.courtName;for(let et of U||[]){if(!i)break;et.venueId&&!V[et.venueid]&&(V[et.venueId]=dc({venueId:et.venueId,tournamentRecord:i})?.venueData);let Q=V[et.venueId];et.venueName=Q?.venueName;let it=Q?.courtsInfo?.find(ot=>ot.courtId===et.courtId);et.courtName=it?.courtName}g=nt({typeChangeTimeAfterRecovery:B,timeAfterRecovery:w,scheduledDate:M,scheduledTime:P,isoDateString:W,allocatedCourts:U,homeParticipantId:C,timeModifiers:D,venueAbbreviation:k,venueName:$,venueId:b,courtOrder:O,courtName:q,courtId:v,typeChangeRecoveryMinutes:x,recoveryMinutes:L,averageMinutes:F,milliseconds:m,startTime:l,endTime:f,time:d})}else g=nt({milliseconds:m,startTime:l,endTime:f,time:d});let{scheduledDate:T}=ns({matchUp:p}),{scheduledTime:y}=Gf({matchUp:p});if(s&&u?.displaySettings?.draws){let A=u.displaySettings.draws,U=(A?.[p.drawId]??A?.default)?.scheduleDetails;if(U){let C=(U.find(P=>T&&P.dates?.includes(T))??U.find(P=>!P.dates?.length))?.attributes;if(C){let P=Object.assign({},...Object.keys(g).map(D=>({[D]:!0})),C);g=_i({source:g,template:P})}}}let E=p.matchUpStatus&&ae.includes(p.matchUpStatus)&&(Ut(f)||Ut(T)||Ut(y))||void 0;return{schedule:g,endDate:E}}function Hs(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 Sp({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 Ye({drawDefinition:t,structure:e,matchUp:r,event:n}){return{tieFormat:Sp({item:r,drawDefinition:t,structure:e,event:n})||Sp({item:e,drawDefinition:t,structure:e,event:n})||Hs(t)||Hs(n)}}function nb({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 ye({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 ti({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)}function xh({groupedOrder:t,roundPositionsCount:e}){if(!t||t?.length<=e)return t;let n=Te(t,t.length/e).map(i=>i.reduce((s,a)=>s+a)),o=n.slice().sort(se);return n.map(i=>o.indexOf(i)+1)}function Vf(t){if(!Pt(t))return!1;let{matchUpId:e,drawPositions:r}=t,n=typeof e=="string",o=!r||Array.isArray(r)&&r.length<=2&&r.every(i=>ft(i)||i===void 0||i===null);return n&&o}function Nr(t){return Array.isArray(t)?t.every(Vf):!1}function qe({matchUps:t=[],interpolate:e}){if(!Nr(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(se).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)=>se(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]=nt({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&&En(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=>!ae.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(se),I=Te(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=Te(I,h),T=l.map(y=>{let{roundPosition:N}=y,E=[...y.drawPositions||[],void 0,void 0].slice(0,2);if(!N)return E;let A=E?.filter(Boolean)||[];if(!A?.length)return[void 0,void 0];if(d<3&&A?.length===2)return E?.slice().sort(se);let U=jt(I,A).length!==A?.length;if(A?.length&&U)return A?.length===1?[A[0],void 0]:E?.slice().sort(se);let C=(N-1)*2;return S.slice(C,C+2).map(D=>A?.find(M=>D.includes(M)))});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})=>!En(d));return{hasNoRoundPositions:t.some(d=>!d.roundPosition),roundsNotPowerOf2:p,maxMatchUpsCount:i,roundMatchUps:o,roundNumbers:u,roundProfile:s,...R}}function $m(t){if(!Array.isArray(t))return"";let e=t.filter(Jt);return e.length?pt([Math.min(...e),Math.max(...e)]).join("-"):""}function ob({drawDefinition:t,structureId:e,matchUpsMap:r}){if(!t)return{error:X};if(!e)return{error:Sr};let{structure:n}=st({drawDefinition:t,structureId:e});if(n?.stage!==He)return{error:Ri,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=ti({structureId:m,matchUpsMap:r}),f=qe({matchUps:d}).roundProfile;return{[m]:f}})),c=ti({matchUpsMap:r,structureId:e}),{roundProfile:u}=qe({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,N=S[l]?.matchUpsCount;if(!N)return;let E=N?T.length/N:0,A=T.length/E,U=T.slice(),C=xh({roundPositionsCount:A,groupedOrder:g}),P=C?.length||1;if(P<=A){let v=T.length/P,O=Te(U,v);f===mi&&O.forEach(w=>w.reverse()),U=C?.length&&C?.map(w=>O[w-1]).flat()||U}let D=Te(U,E);if(I){let v=Z(0,I.interleave).map(()=>{}),O=Z(0,I.offset).map(()=>{});D=D.map(F=>[F,...v]),D.unshift(O),D=D.flat(1);let w=D.length-I.offset;D=D.slice(0,w)}p[h]||(p[h]={});let b=u?.[h]?.feedRound?2:1;D.forEach((v,O)=>{let w=1+O*b;p[h][w]||(p[h][w]=$m(v))})}),{sourceDrawPositionRanges:p}}function ib({drawPositions:t,roundProfile:e,roundNumber:r}){let n=[void 0,void 0];if(vI(t))return{orderedDrawPositions:n,displayOrder:n};let o=e?.[r],s=o?.pairedDrawPositions?.find(c=>Fe(c||[],t.filter(Boolean)))??n,a=o?.feedRound;if(bI(t)){let c=[...t].sort(se);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 Tp({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 nn({tournamentParticipants:t,tournamentRecord:e,participantIds:r}){let n="getPairedParticipant";if(!t&&!e)return{error:j};if(!Array.isArray(r)||r.length>2)return{error:Kr};if(!r.length)return _({result:{error:Eo},stack:n});t=t??e?.participants??[];let o=t.filter(a=>a.participantType===lt&&jt(r,a.individualParticipantIds).length===r.length&&a.individualParticipantIds.length===r.length),i=o[0];if(!i)return _({result:{error:re},stack:n});let s=J(o.slice(1),!1,!0);return{participant:J(i),duplicatedPairParticipants:s,...R}}function is({drawDefinition:t,participantId:e}){if(typeof t!="object")return{error:X};if(typeof e!="string")return{error:ee};let{extension:r}=dt({element:t,name:Do});return{lineUp:(r?.value||{})[e]}}function sb({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}=Tp({collectionPosition:r,collectionId:s,lineUp:d});if(c===wt){if(f?.length<=2){let I=o?.[f[0]]?.pairIdMap?.[f[1]],T=(I&&o[I]?.participant||nn({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||is({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||is({participantId:d,drawDefinition:i})?.lineUp;return u({attribute:m,lineUp:g,teamParticipant:f})}).filter(Boolean)||{};return{drawPositionCollectionAssignment:Object.assign({},...p)}}function wh({drawDefinition:t}){if(typeof t!="object")return{error:aa};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"&&[He,ue].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 ab({drawDefinition:t,roundProfile:e,structureId:r,matchUpsMap:n}){if(!t)return{error:X};if(!r)return{error:Sr};if(!e){let c=ti({matchUpsMap:n,structureId:r});if({roundProfile:e}=qe({matchUps:c}),!e)return{error:rt}}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=Te(p,p.length/u),d=m.map($m),l=m.map(S=>S.map(T=>T-i)).map($m),f=s.map(S=>{if(S>c)return;let T=e?.[S]?.drawPositions??[];return Te(T,T.length/u)}).filter(Boolean),g=Z(0,u).map(S=>f.map(T=>T[S]).flat().filter(Boolean).sort(se)).map(S=>pt(S)),I=g.map(S=>JC(S).map($m).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 Km({roundsNotPowerOf2:t,drawDefinition:e,structure:r,matchUps:n}){if(!r)return!1;n=n??r.matchUps??[],t=t??qe({matchUps:n}).roundsNotPowerOf2;let o=!!r.positionAssignments?.find(({drawPosition:i})=>i)||!!n?.find(({drawPositions:i})=>i?.length);return(!e?.drawType||e.drawType!==xi)&&!r?.structures&&t&&o}function gr({structure:t}){if(!t)return!1;let e=t.matchUps||t.roundMatchUps&&Object.values(t.roundMatchUps).flat(),r=!!e?.find(o=>o?.roundPosition),n=!!e?.find(o=>o?.drawPositions?.length);return!t?.structures&&t?.stage!==We&&(!e.length||!r&&!n)}var Bf={[da]:{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]:"",[ue]:"P",[at]:"Q",[He]:"C"}}},cb=Bf;function ub({roundNamingPolicy:t,drawDefinition:e,structure:r,matchUps:n}){let{roundProfile:o,roundMatchUps:i}=qe({matchUps:n}),{structureAbbreviation:s,stage:a}=r,c=gr({structure:r}),u=Km({structure:r}),p=r.structures,m={},d=Bf[da],l=r.stage===at,f=l?Math.max(...(e?.structures??[]).filter(b=>b.stage===at).map(({stageSequence:b})=>b??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,y=t?.affixes?.roundNumber||d.affixes.roundNumber,E=(t?.namingConventions||d.namingConventions).round,A=a&&a!==tt?a[0]:"",U=t?.stageConstants||d.stageConstants,C=a&&U?.[a]||A,P=`${I}${C}${g}`,D=o?Object.keys(o):[],M=l&&U?.[at]?`${U?.[at]}-`:"";if(p||c||u)Object.assign(m,...D.map(b=>{let v=`${M}${E} ${b}`,O=`${y}${b}`;return{[b]:{roundName:v,abbreviatedRoundName:O}}}));else{let b=l&&(t?.qualifyingFinishMap||d?.qualifyingFinishMap||{});Object.assign(m,...D.map(v=>{if(!o?.[v])return;let{matchUpsCount:O,preFeedRound:w}=o[v],F=O*2,L=b?.[o?.[v].finishingRound]||b&&`${y}${F}`||h[O]||`${y}${F}`,x=w?`-${T}`:"",B=`${L}${x}`,H=[P,s,B].filter(Boolean).join("-"),V=`${S[O]||`${y}${F}`}${x}`,Y=[P,s,V].filter(Boolean).join("-");return{[v]:{abbreviatedRoundName:Y,roundName:H}}}))}return{roundNamingProfile:m,roundProfile:o,roundMatchUps:i}}function zm(t){let e=ut(t,[{[Un]:!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===Tt&&Kt||s===lt&&wt||s===xt&&xt||void 0}return{matchUpType:n}}var NF="normal",dU="timed",MF="final",Hf="NOAD",Qm="SET",pb={S:NF,F:MF};function rr(t){if(typeof t=="string"){let e=t.startsWith("T")&&dU||t.startsWith(Qm)&&Qm||"";if(e===dU){let r=fb(t),n={simplified:!0,setFormat:r,bestOf:1};if(r)return n}if(e===Qm)return CF(t)}}function CF(t){let e=t.split("-"),r=Wf(e[0].slice(3)),n=r===1||r%2!==0?r:void 0,o=r!==1&&r%2===0?r:void 0,i=e&&mb(e[1]),s=e&&mb(e[2]),a=i&&i.timed||s&&s.timed,c=n&&n<6||a&&o,u=!e[2]||s,p=i,m=nt({setFormat:i,exactly:o,bestOf:n});if(s&&(m.finalSetFormat=s),c&&p&&u)return m}function mb(t){if(t?.[1]===":"){let e=t.split(":"),r=pb[e[0]],n=e[1];if(r&&n){if(n.startsWith("TB")){let I=db(n);return I===!1?!1:typeof I=="object"?{tiebreakSet:I}:void 0}if(n.startsWith("T"))return fb(n);let s=t.match(/^[FS]:(\d+)([A-Za-z]*)/),a=s&&gb(s[2])||!1,c=!s?.[2]||a,u=s?Wf(s[1]):void 0,p=lb(n),m=p!==!1,d=m&&p||u,l=db(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 lb(t,e=!0){let r=t?.indexOf("@")>0&&t.split("@");if(r)return(e?Wf(r[1]):r[1])||!1}function db(t){if(t)if(t.startsWith("TB")){let e=lb(t,!1),r=t.match(/^TB(\d+)([A-Za-z]*)/),n=r?.[1],o=r&&gb(r[2]),i=!r?.[2]||o,s=Wf(n);if(s&&i){let a={tiebreakTo:s};return e&&typeof e=="string"&&!ft(e)&&(a.modifier=e),o&&(a.NoAD=!0),a}else return!1}else return!1}function fb(t){let e=t.slice(1),r=e.match(/^(\d+)(@?[A-Za-z]*)/),n=Wf(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 gb(t){return t&&t.indexOf(Hf)>=0}function Wf(t){return isNaN(Number(t))?0:Number(t)}function du(t,e){return!Array.isArray(t)||!Re(e)?!1:jt(t,Ph[e]).length}function Ea(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:y,structureIds:N,readyToScore:E,courtIds:A,eventIds:U,venueIds:C,drawIds:P,stages:D,filterMatchUpIds:M=!0,filterMatchUpTypes:b=!0}=t,v=Array.isArray(h)?h.filter(Boolean):[],O=Array.isArray(o)?o.filter(Boolean):[],w=Array.isArray(n)?n.filter(Boolean):[],F=Array.isArray(D)?D.filter(Boolean):[],L=Array.isArray(f)?f.filter(Boolean):[],x=Array.isArray(u)?u.filter(Boolean):[],B=Array.isArray(l)?l.filter(Boolean):[],H=Array.isArray(m)?m.filter(Boolean):[],W=Array.isArray(a)?a.filter(Boolean):[],V=Array.isArray(d)&&M?d.filter(Boolean):[],Y=Array.isArray(y)&&b?y.filter(Boolean):[],$=Array.isArray(A)?A.filter(Boolean):[],k=Array.isArray(C)?C.filter(Boolean):[],K=Array.isArray(s)&&s.filter(Boolean)||typeof c=="string"&&[c]||[],z=Array.isArray(g)&&g.filter(Boolean)||typeof I=="string"&&I.length&&[I]||[],q=Array.isArray(T)?T.filter(Boolean):[],et=Array.isArray(U)?U.filter(Boolean):[],Q=Array.isArray(P)?P.filter(Boolean):[],it=Array.isArray(N)?N.filter(Boolean):[];return e.filter(ot=>{if(E&&!ie(gn)(ot)&&!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)||L.length&&!L.includes(ot.stageSequence)||x.length&&(!ot.collectionId||!x.includes(ot.collectionId))||B.length&&(!ot.roundName||!B.includes(ot.roundName))||H.length&&(!ot.roundNumber||!H.includes(ot.roundNumber))||W.length&&(!ot.roundPosition||!W.includes(ot.roundPosition))||O.length&&(!ot.matchUpStatus||!O.includes(ot.matchUpStatus))||w.length&&ot.matchUpStatus&&w.includes(ot.matchUpStatus)||V.length&&!V.includes(ot.matchUpId)||Y.length&&(!ot.matchUpType||!du(Y,ot.matchUpType))||K.length&&(!ot.matchUpFormat||!K.includes(ot.matchUpFormat)))return!1;if(z?.length){let{scheduledTime:mt}=Gf({matchUp:ot}),{scheduledDate:Xt}=ns({matchUp:ot}),Me=Ut(mt)||Xt;if(!z.find(Ee=>wn(Ee,Me)))return!1}if($.length){let{courtId:mt}=vh({matchUp:ot}),{allocatedCourts:Xt}=bh({matchUp:ot}),Et=Xt?.map(({courtId:Me})=>Me);if(!$.filter(Boolean).includes(mt)||Et?.includes(mt))return!1}if(k.length){let{venueId:mt}=Oh({matchUp:ot});if(!k.filter(Boolean).includes(mt))return!1}if(S){if(q.length&&!q.includes(ot.tournamentId)||et.length&&!et.includes(ot.eventId)||Q.length&&!Q.includes(ot.drawId)||it.length&&!it.includes(ot.structureId))return!1;if(v.length){let mt=ot.sides?.map(({participantId:Et})=>Et).filter(Boolean)??[];if(!v.some(Et=>mt.includes(Et)))return!1}}return!0})}function Ib({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?RF({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 RF({displaySideNumber:t,seedAssignments:e,participantId:r,assignment:n,sideNumber:o}){let i={drawPosition:n.drawPosition,displaySideNumber:t,sideNumber:o};if(r){let s=bF({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 bF({seedAssignments:t,participantId:e}){return t?.find(r=>!r.seedProxy&&r.participantId===e)}var In="ANY",te="MALE",Ur="MIXED",ss="OTHER",ce="FEMALE",Xm={ANY:In,MALE:te,FEMALE:ce,MIXED:Ur,OTHER:ss};function At({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:y,inContext:N,event:E}){let A={},U={};if(n=n??s?.participants,!y)return{collectionPositionMatchUps:A,error:Oo,roundMatchUps:U,matchUps:[]};let C=Array.isArray(m?.eventIds)?m?.eventIds.filter(Boolean):[],P=Array.isArray(m?.structureIds)?m?.structureIds.filter(Boolean):[],D=Array.isArray(m?.drawIds)?m?.drawIds.filter(Boolean):[],M=!h?.eventId||!C?.length&&!u?.eventIds?.filter(Boolean).length||C?.includes(h.eventId)||u?.eventIds?.includes(h.eventId),b=!P?.length||P.includes(y.structureId),v=!g||!D?.length||D.includes(g.drawId);if(!M||!b||!v)return{collectionPositionMatchUps:A,roundMatchUps:U,matchUps:[]};f&&!p&&(p=Bn({tournamentRecord:s,contextProfile:f,drawDefinition:g}));let{appliedPolicies:O}=ht({drawDefinition:g}),w={...e,...O,...i},F=w?.scoring?.structures,L=y.stage&&F?.stage&&F?.stage[y.stage],x=y.stageSequence&&L?.stageSequence&&L.stageSequence[y.stageSequence],B=w?.scoring?.requireAllPositionsAssigned||L?.requireAllPositionsAssigned||x?.requireAllPositionsAssigned;T||(T=ye({drawDefinition:g,structure:y}));let{positionAssignments:H,allPositionsAssigned:W}=de({structure:y}),V=!B||W,{seedAssignments:Y}=Hr({provisionalPositioning:r,drawDefinition:g,structure:y});a=a??Y;let{roundOffset:$,structureId:k,structureName:K,stage:z,stageSequence:q}=y,{drawId:et,drawName:Q,drawType:it}=g??{};S=S||g&&wh({drawDefinition:g}).exitProfiles;let ot=S?.[k],mt=ot?.length&&(ot[0].split("-").map(Ft=>parseInt(Ft)).reduce((Ft,Ue)=>Ft+Ue)||0),Xt=!!y.structures,Et=ti({matchUpsMap:T,structureId:k,inContext:N}),Me=w?.[da],Ee=ub({roundNamingPolicy:Me,drawDefinition:g,structure:y,matchUps:Et}),{roundNamingProfile:Ce,roundProfile:zt}=Ee;if(U=Ee?.roundMatchUps??[],m&&(Et=Ea({matchUps:Et,...m,filterMatchUpTypes:!1,filterMatchUpIds:!1})),N){let{sourceDrawPositionRanges:Ft}=ob({drawDefinition:g,matchUpsMap:T,structureId:k}),Ue=g?ab({drawDefinition:g,roundProfile:zt,matchUpsMap:T,structureId:k}).drawPositionsRanges:void 0;Et=Et.map(_t=>ve({scheduleVisibilityFilters:t,sourceDrawPositionRanges:Ft,drawPositionsRanges:Ue,roundNamingProfile:Ce,initialRoundOfPlay:mt,appliedPolicies:w,usePublishState:c,publishStatus:I,isRoundRobin:Xt,roundProfile:zt,matchUp:_t,event:E})),(Et?.filter(_t=>Array.isArray(_t.tieMatchUps))).forEach(_t=>{let oe=_t.tieMatchUps;Et=Et.concat(...oe)}),u&&(Et=Ea({processContext:!0,...u,matchUps:Et}))}else(Et?.filter(Ue=>Array.isArray(Ue.tieMatchUps))).forEach(Ue=>{let Rt=Ue.tieMatchUps;Et=Et.concat(...Rt)});return m&&(Et=Ea({matchUps:Et,...m,filterMatchUpTypes:!1,filterMatchUpIds:!1})),(m?.matchUpTypes||m?.matchUpIds)&&(Et=Ea({matchUpTypes:m.matchUpTypes,matchUpIds:m.matchUpIds,matchUps:Et})),(m?.matchUpTypes||m?.matchUpIds||N)&&(U=qe({matchUps:Et}).roundMatchUps??[]),Ye({drawDefinition:g,structure:y,event:E})?.tieFormat&&({collectionPositionMatchUps:A}=nb({matchUps:Et})),{collectionPositionMatchUps:A,roundMatchUps:U,isRoundRobin:Xt,roundProfile:zt,matchUpsMap:T,matchUps:Et};function ve({scheduleVisibilityFilters:Ft,sourceDrawPositionRanges:Ue,drawPositionsRanges:Rt,initialRoundOfPlay:_t,additionalContext:oe,roundNamingProfile:qt,tieDrawPositions:pe,appliedPolicies:he,isCollectionBye:mr,usePublishState:xe,publishStatus:Wt,matchUpTieId:we,isRoundRobin:ir,roundProfile:Oe,sideLineUps:Rr,matchUp:Se,event:Pe}){oe=oe??{};let Ir=Ye({drawDefinition:g,structure:y,matchUp:Se,event:Pe})?.tieFormat,si=Ir?.collectionDefinitions,ze=Se.collectionId&&si?.find(ro=>ro.collectionId===Se.collectionId),_n=Se.collectionId?ze?.matchUpFormat:Se.matchUpFormat??y?.matchUpFormat??g?.matchUpFormat??Pe?.matchUpFormat,Ni=Se.matchUpType||ze?.matchUpType||y?.matchUpType||g?.matchUpType||!ie(Ve)(Pe?.eventType)&&Pe?.eventType,Yi=mr?Nt:Se.matchUpStatus,{schedule:yn,endDate:Lc}=qm({scheduleVisibilityFilters:Ft,afterRecoveryTimes:o,tournamentRecord:s,usePublishState:xe,scheduleTiming:l,matchUpFormat:_n,publishStatus:Wt,matchUpType:Ni,matchUp:Se,event:Pe}),qi=pe??Se.drawPositions??[],{collectionPosition:cI,collectionId:vC,roundPosition:uI}=Se,$i=Se.roundNumber??oe.roundNumber,Mw=vC?sb({tournamentParticipants:n,positionAssignments:H,collectionPosition:cI,drawDefinition:g,participantMap:d,drawPositions:qi,collectionId:vC,sideLineUps:Rr,matchUpType:Ni}):void 0,OC=qt?.[$i]?.roundName||oe.roundName,_C=qt?.[$i]?.abbreviatedRoundName||oe.abbreviatedRoundName,Cw=Oe?.[$i]?.feedRound,Rw=Oe?.[$i]?.preFeedRound,bw=Oe?.[$i]?.roundFactor,vw=Rt?.[$i],Ow=uI?vw?.[uI]:void 0,_w=Ue?.[$i],xw=ze?.category?{...h?.category||{},...ze.category}:h?.category??Pe?.category,ww=Se.processCodes?.length&&Se.processCodes||ze?.processCodes?.length&&ze?.processCodes||y?.processCodes?.length&&y?.processCodes||g?.processCodes?.length&&g?.processCodes||Pe?.processCodes?.length&&Pe?.processCodes||s?.processCodes,Lw=f?.withCompetitiveness&&pu({...p,matchUp:Se}),Fw=Se.finishingPositionRange??oe.finishingPositionRange,pI=ro=>nt(ro,void 0,!0),hr={...pI(h),...pI({matchUpFormat:Se.matchUpType===Ve?void 0:_n,tieFormat:Se.matchUpType!==Ve?void 0:Ir,gender:ze?.gender??Pe?.gender,roundOfPlay:z!==at&&ft(_t)&&_t+($i||0),endDate:Se.endDate??Lc,discipline:Pe?.discipline,category:xw,finishingPositionRange:Fw,abbreviatedRoundName:_C,drawPositionsRange:Ow,competitiveProfile:Lw,structureName:K,stageSequence:q,drawPositions:qi,matchUpStatus:Yi,processCodes:ww,isRoundRobin:ir,matchUpTieId:we,preFeedRound:Rw,matchUpType:Ni,roundFactor:bw,roundOffset:$,structureId:k,roundNumber:$i,feedRound:Cw,roundName:OC,drawName:Q,drawType:it,schedule:yn,drawId:et,stage:z}),...J(pI(Se),!0,!0)};if(_n&&Se.score?.scoreStringSide1){let ro=rr(_n),{bestOf:ia,finalSetFormat:Ps,setFormat:yr}=ro??{};(Ps?.tiebreakSet||yr?.tiebreakSet||yr?.timed)&&(hr.score.sets=hr.score.sets.sort((qr,xn)=>qr.setNumber-xn.setNumber).map((qr,xn)=>(xn+1===ia?(Ps?.tiebreakSet||Ps?.timed)&&(qr.tiebreakSet=!0):(yr?.tiebreakSet||yr?.timed)&&(qr.tiebreakSet=!0),qr)))}if(Array.isArray(qi)){let{orderedDrawPositions:ro,displayOrder:ia}=ib({drawPositions:qi,roundProfile:Oe,roundNumber:$i}),Ps=Oe?.[$i]?.feedRound,yr=ia[0]!==ro[0],xn=ro.concat(void 0,void 0).slice(0,2).map((Mi,iA)=>{let mI=iA+1,kw=yr?3-mI:mI,Vw=Ib({...Mw,positionAssignments:H,displaySideNumber:kw,seedAssignments:a,drawPosition:Mi,isFeedRound:Ps,sideNumber:mI}),Bw=Se.sides?.find(Ww=>Ww.sideNumber===mI),wC=uI?(uI-1)*2+iA+1:void 0,Hw=wC?_w?.[wC]:void 0;return pI({sourceDrawPositionRange:Hw,...Bw,...Vw})});Object.assign(hr,J({sides:xn},!0,!0))}if(n&&hr.sides){let ro=he?.[ws],ia=yr=>{let qr=d?.[yr]?.participant;return qr&&_i({template:ro?.participant,source:qr})};if(hr.sides.filter(Boolean).forEach(yr=>{if(yr.participantId){let qr=J(ia(yr.participantId)||n&&Lo({policyDefinitions:he,participantId:yr.participantId,tournamentParticipants:n,internalUse:!0,contextProfile:f}),void 0,!0);if(qr){if(g?.entries){let xn=g.entries.find(Mi=>Mi.participantId===yr.participantId);xn?.entryStatus&&(qr.entryStatus=xn.entryStatus),xn?.entryStage&&(qr.entryStage=xn.entryStage)}Object.assign(yr,{participant:qr})}}if(yr?.participant?.individualParticipantIds?.length&&!yr.participant.individualParticipants?.length){let qr=yr.participant.individualParticipantIds.map(xn=>ia(xn)||n&&Lo({policyDefinitions:he,tournamentParticipants:n,internalUse:!0,contextProfile:f,participantId:xn}));Object.assign(yr.participant,{individualParticipants:qr})}}),!hr.matchUpType){let{matchUpType:yr}=zm({matchUp:hr});yr&&Object.assign(hr,{matchUpType:yr})}if(f?.inferGender&&(!hr.gender||hr.gender===Ur)&&hr.sides?.length===2&&hr.matchUpType!==Ve){let yr=hr.sides.map(qr=>{if(ie(Kt)(hr.matchUpType))return qr.participant?.person?.sex;if(qr.participant?.individualParticipants?.length===2){let xn=pt(qr.participant.individualParticipants.map(Mi=>Mi.person?.sex)).filter(Boolean);if(xn.length===1)return xn[0]}});if(yr.filter(Boolean).length===2&&pt(yr).length===1){let qr=yr[0];hr.inferredGender=qr}}}if(hr.tieMatchUps){let ro=hr.matchUpStatus===Nt,ia=hr.sides?.map(({participant:Ps,drawPosition:yr,sideNumber:qr,lineUp:xn})=>{let Mi=Ps?.participantType===Ve&&Ps;return{teamParticipant:Mi&&nt({participantRoleResponsibilities:Mi.participantRoleResponsibilities,participantOtherName:Mi.participanOthertName,participantName:Mi.participantName,participantId:Mi.participantId,teamId:Mi.teamId}),drawPosition:yr,sideNumber:qr,lineUp:xn}});hr.tieMatchUps=hr.tieMatchUps.map(Ps=>{let yr=hr.matchUpId,xn={finishingPositionRange:hr.finishingPositionRange,abbreviatedRoundName:_C,roundNumber:$i,roundName:OC};return ve({tieDrawPositions:qi,scheduleVisibilityFilters:Ft,sourceDrawPositionRanges:Ue,sideLineUps:ia,drawPositionsRanges:Rt,initialRoundOfPlay:_t,roundNamingProfile:qt,additionalContext:xn,appliedPolicies:he,isCollectionBye:ro,usePublishState:xe,publishStatus:Wt,matchUpTieId:yr,isRoundRobin:ir,roundProfile:Oe,matchUp:Ps,event:Pe})})}let xC=hr.sides&&hr.sides.filter(ro=>ro?.participantId).length===2,Gw=!hr.winningSide;if(Object.assign(hr,{readyToScore:V&&xC&&Gw,hasContext:!0}),xC){let{allParticipantsCheckedIn:ro,checkedInParticipantIds:ia}=rs({matchUp:hr});Object.assign(hr,{allParticipantsCheckedIn:ro,checkedInParticipantIds:ia})}return Array.isArray(f?.exclude)&&f?.exclude.forEach(ro=>delete hr[ro]),hr}}function as({matchUp:t}){return t?ae.includes(t?.matchUpStatus)||t?.winningSide:!1}function lu({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:y,context:N,event:E}){!y&&S&&({structure:y}=st({drawDefinition:g,structureId:S}));let A=At({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:y,inContext:T,context:N,event:E}),U=[],C=[],P=[],D=[],M=[];if(A.error)return A;let{matchUps:b}=A,{assignedPositions:v}=de({structure:y}),O=v?.filter(F=>F.participantId).map(F=>F.drawPosition),w;return b.filter(F=>{let L=c?.matchUpTypes?.length===1&&c.matchUpTypes[0]===Bt;return!(F.matchUpType!==Bt&&L)}).forEach(F=>{if(F.matchUpStatus===Ar){U.push(F);return}F.matchUpType===Bt&&(w=!0);let L=F.collectionId,x=L&&F.sides?.every(k=>k.participantId),B=!L&&F.drawPositions?.filter(Boolean).length===2,H=!L&&F.drawPositions?.every(k=>O?.includes(k)),W=v?.filter(k=>k.bye).map(k=>k.drawPosition),V=!L&&F.drawPositions?.find(k=>W?.includes(k)),$=th.includes(F.matchUpStatus)&&(x||B&&(!t||H));return V?M.push(F):as({matchUp:F})?C.push(F):$?P.push(F):D.push(F)}),{includesTeamMatchUps:w,abandonedMatchUps:U,completedMatchUps:C,upcomingMatchUps:P,pendingMatchUps:D,byeMatchUps:M,structure:y}}function hb({drawDefinition:t,roundNumber:e,structureId:r}){if(!t)return{error:X};if(!r)return{error:Sr};let{links:n}=Ws({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 Lh({finishingPositions:t,linkCondition:e,linkType:r,source:n}){let o=n.find(i=>{let s=!i.source?.finishingPositions||!t||Fe(t,i.source?.finishingPositions);return e===i.linkCondition&&s&&i.linkType===r});return[po,Qn].includes(o?.linkType)&&!o?.source?.roundNumber?_({result:{error:G},stack:"getTargetLink",context:o}):o}function Ws({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:Sr}:{error:X}}function Sb({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 Fh({sourceRoundMatchUpCount:t,inContextDrawMatchUps:e,sourceRoundPosition:r,drawDefinition:n,targetLink:o}){if(!o)return{error:yl};let{target:{structureId:i,feedProfile:s,groupedOrder:a,roundNumber:c,positionInterleave:u}}=o,{structure:p}=st({drawDefinition:n,structureId:i}),{positionAssignments:m}=Ct({structure:p}),l=(e?.filter(P=>P.structureId===p?.structureId)).filter(P=>P.roundNumber===c&&!P.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 P=u.offset+(r-1)*u.interleave,D=r+P;h=Math.ceil(D/2),S=1-D%2}let T=g,y=g[h-1],N=xh({roundPositionsCount:g.length,groupedOrder:a}),E=N?.length||1;if(E<=g.length){let P=f/E,D=Te(g,P);s===mi&&D.forEach(M=>M.reverse()),T=N?.length&&N?.map(M=>D[M-1]).flat()||T}s===pn?y=T[h-1]:s===mi?((!N?.length||E>g.length)&&(h=l.length+1-h),y=T[h-1]):s===up&&Pr()&&console.log(zu,{feedProfile:s});let A=y&&l.reduce((P,D)=>D.roundPosition===y?D:P,void 0),U;A?.feedRound?(S=0,U=Math.min(...(A.drawPositions||[]).filter(Boolean))):U=A?.drawPositions?.length===2&&A?.drawPositions[S];let C=m?.find(({drawPosition:P})=>P===U);if(C){let{extension:P}=dt({element:C,name:Pm});if(P?.value)return{disabledDrawPosition:U}}return{matchUp:A,targetDrawPosition:U,matchUpDrawPositionIndex:S}}function nr({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===wi?vF({inContextDrawMatchUps:t,useTargetMatchUpIds:e,drawDefinition:n,structure:s,matchUp:i}):OF({matchUp:i})}function vF({inContextDrawMatchUps:t,useTargetMatchUpIds:e,drawDefinition:r,structure:n,matchUp:o}){let{winnerMatchUpId:i,loserMatchUpId:s}=o,{links:a}=hb({roundNumber:o.roundNumber,structureId:n.structureId,drawDefinition:r}),c=a?.source,u=Lh({source:c,linkType:po}),p=Lh({linkCondition:Xn,linkType:Qn,source:c}),m=Lh({source:c,linkType:Qn}),d=p&&m;m||(m=p);let l=u?.target?.feedProfile,f=m?.target?.feedProfile,g=p?.target?.feedProfile,I,h,S,T,y,N,E,A,U,C;if(e&&(i||s)&&(E=i&&l!==tn&&t.find(({matchUpId:M})=>M===i),T=s&&f!==tn&&t.find(({matchUpId:M})=>M===s),E||T))return{matchUp:o,targetLinks:{loserTargetLink:m,winnerTargetLink:u},targetMatchUps:{loserMatchUp:T,winnerMatchUp:E}};let{roundPosition:P}=o;C=C||t.filter(M=>M.structureId===n.structureId);let D=C.reduce((M,b)=>b.roundNumber===o.roundNumber&&!b.matchUpTieId?M+1:M,0);return m&&!T&&f!==tn&&({matchUpDrawPositionIndex:N,targetDrawPosition:y,matchUp:T}=Fh({targetLink:m,sourceRoundMatchUpCount:D,inContextDrawMatchUps:t,sourceRoundPosition:P,drawDefinition:r})),d&&g!==tn&&({matchUpDrawPositionIndex:S,targetDrawPosition:h,matchUp:I}=Fh({targetLink:p,sourceRoundMatchUpCount:D,inContextDrawMatchUps:t,sourceRoundPosition:P,drawDefinition:r})),u&&!E&&l!==tn&&({matchUpDrawPositionIndex:U,targetDrawPosition:A,matchUp:E}=Fh({targetLink:u,sourceRoundMatchUpCount:D,inContextDrawMatchUps:t,sourceRoundPosition:P,drawDefinition:r})),E||(C=C||t.filter(M=>M.structureId===n.structureId),{matchUp:E}=Sb({structureMatchUps:C,matchUp:o})),nt({matchUp:o,targetLinks:{loserTargetLink:m,winnerTargetLink:u,byeTargetLink:p},targetMatchUps:{winnerMatchUpDrawPositionIndex:U,loserMatchUpDrawPositionIndex:N,byeMatchUpDrawPositionIndex:S,winnerTargetDrawPosition:A,loserTargetDrawPosition:y,byeTargetDrawPosition:h,winnerMatchUp:E,loserMatchUp:T,byeMatchUp:I},targetMatchUpIds:!!(i||s)})}function OF({matchUp:t}){return{targetLinks:{loserTargetLink:void 0,winnerTargetLink:void 0},targetMatchUps:{loserMatchUp:void 0,winnerMatchUp:void 0},matchUp:t}}function Tb({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===Fs){let{roundNumber:c}=n,u=c&&ct(c)+1,p=a.matchUps??[],{roundMatchUps:m}=qe({matchUps:p});if(u&&m?.[u]){let d=[...s].sort(se).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=nr({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=lU({upcomingMatchUp:u}),d=lU({upcomingMatchUp:p});if(n.matchUpStatus!==Nt&&p?.matchUpStatus===Nt){let{matchUp:f}=yb({matchUp:p,drawDefinition:t,inContextDrawMatchUps:e})||{};d=f&&lU({upcomingMatchUp:f})||d}let l=n.schedule?.timeAfterRecovery;if(l&&(m?.schedule?.scheduledTime&&Vt(m.schedule.scheduledTime)<Vt(l)&&(r[m.matchUpId]=n.matchUpId,m.schedule.scheduleConflict=n.matchUpId),d?.schedule?.scheduledTime&&Vt(d.schedule.scheduledTime)<Vt(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===Xn,I=_F(n);if(I.length){let h=uf(u?.sides),S=uf(p?.sides),y=I.find(({participantId:A})=>h.includes(A))?[]:I,E=I.find(({participantId:A})=>S.includes(A))?[]:I;p&&g&&E.length<2&&E.push({bye:!0,tbd:!0}),y?.length&&u&&(!c.targetMatchUpIds&&u&&(u=e.find(({matchUpId:A})=>A===u.matchUpId)),u.potentialParticipants||(u.potentialParticipants=[]),u.potentialParticipants.push(y)),E?.length&&p&&(c.targetMatchUpIds||(u=e.find(({matchUpId:A})=>A===p.matchUpId)),p.potentialParticipants||(p.potentialParticipants=[]),p.potentialParticipants.push(E))}}}}),Object.keys(r).length&&e.forEach(n=>{Object.keys(r).includes(n.matchUpId)&&(n.schedule.scheduleConflict=r[n.matchUpId])}),{scheduleConflictMatchUpIds:r}}function _F(t){return t?.sides?.map(({participant:e,participantId:r,qualifier:n})=>e||r&&{participantId:r}||n&&{qualifier:n}).filter(Boolean)||[]}function yb({matchUp:t,drawDefinition:e,inContextDrawMatchUps:r}){let{matchUpId:n,matchUpStatus:o,structureId:i}=t||{};if(!t||!i||t?.matchUpStatus===Qt)return{matchUp:t};if(o===Nt){let s;return t.winnerMatchUpId?s=r.find(({matchUpId:a})=>a===t.winnerMatchUpId):{winnerMatchUp:s}=nr({inContextDrawMatchUps:r,drawDefinition:e,matchUpId:n})?.targetMatchUps||{},yb({matchUp:s,drawDefinition:e,inContextDrawMatchUps:r})}return{matchUp:void 0}}function lU(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 ne(t){let e="getAllDrawMatchUps";Object.assign(t,{requireParticipants:!1});let r=js(t);if(r.error)return _({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 js(t){if(!t?.drawDefinition)return{error:X};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:y,context:N,event:E}=t,A=[],U=[],C=[],P=[],D=[];h&&!r&&(r=Bn({policyDefinitions:u,tournamentRecord:p,contextProfile:h,event:E}));let M;!e?.length&&p&&(e=p?.participants,(y||a?.withGroupings)&&e?.length&&({participantsWithGroupings:e,groupInfo:M}=Lm({participants:e,participantsProfile:a})));let{structures:b}=Gn({drawDefinition:S});if(!b)return{error:Gt};n||(n=ye({drawDefinition:S}));let v=S&&wh({drawDefinition:S}).exitProfiles;b.forEach(F=>{let{byeMatchUps:L=[],pendingMatchUps:x=[],upcomingMatchUps:B=[],completedMatchUps:H=[],abandonedMatchUps:W=[]}=lu({matchUpFilters:T?void 0:l,contextFilters:T?void 0:d,inContext:y||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:v,matchUpsMap:n,structure:F,context:N,event:E});A=A.concat(...W),U=U.concat(...H),C=C.concat(...B),P=P.concat(...x),D=D.concat(...L)});let O=F=>(!l&&!T&&!d||(l&&(F=Ea({matchUps:F,...l})),d&&(F=Ea({matchUps:F,...d,processContext:!0}))),F),w={abandonedMatchUps:O(A),completedMatchUps:O(U),upcomingMatchUps:O(C),pendingMatchUps:O(P),byeMatchUps:O(D),matchUpsMap:n,...R,groupInfo:M};if(T){let F=typeof T=="object"||{abandoned:!0,completed:!0,upcoming:!0,pending:!0,bye:!0},{abandoned:L,completed:x,upcoming:B,pending:H,bye:W}=F,V=[].concat(...L&&A||[],...x&&U||[],...B&&C||[],...H&&P||[],...W&&D||[]);Tb({inContextDrawMatchUps:V,drawDefinition:S})}return w}function ho(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:Dt};let{eventId:S,eventName:T,endDate:y,eventType:N,category:E,gender:A,matchUpFormat:U}=h??{},C={...I,...nt({indoorOutDoor:h.indoorOutdoor??p?.indoorOutdoor,surfaceCategory:h.surfaceCategory??p?.surfaceCategory,endDate:h.endDate??p?.endDate,tournamentId:p?.tournamentId,matchUpFormat:U,eventName:T,eventType:N,category:E,eventId:S,gender:A})};y&&(C.endDate=y),d&&!r&&(r=Bn({policyDefinitions:c,tournamentRecord:p,contextProfile:d,event:h}));let P;if(!e?.length&&!n&&p){let v=fi({participantsProfile:s,useParticipantMap:u,policyDefinitions:c,tournamentRecord:p,contextProfile:d,inContext:g});n=v.participantMap,e=v.participants??[],P=v.groupInfo}let D=h.drawDefinitions??[],M=ya({tournamentRecord:p,event:h}).scheduleTiming;return{matchUps:D.flatMap(v=>{let{matchUps:O}=ne({tournamentParticipants:e,tournamentAppliedPolicies:i,scheduleVisibilityFilters:o,context:C,participantsProfile:s,afterRecoveryTimes:a,policyDefinitions:c,tournamentRecord:p,contextFilters:m,contextProfile:d,drawDefinition:v,contextContent:r,matchUpFilters:l,participantMap:n,scheduleTiming:M,nextMatchUps:f,inContext:g,event:h});return O??[]}),groupInfo:P}}function le(t){let e=ut(t,[{tournamentRecord:!0}]);if(e.error)return e;if(!t?.tournamentRecord)return{error:j};let{participantMap:r,participants:n}=t,{scheduleVisibilityFilters:o,participantsProfile:i,afterRecoveryTimes:s,useParticipantMap:a,policyDefinitions:c,tournamentRecord:u,inContext:p=!0,contextProfile:m,matchUpFilters:d,contextFilters:l,nextMatchUps:f,context:g}=t,I=t.tournamentId??u.tournamentId,h=u?.events??[];n||({participants:n,participantMap:r}=fi({participantsProfile:i,useParticipantMap:a,policyDefinitions:c,tournamentRecord:u,contextProfile:m,inContext:p}));let{appliedPolicies:S}=ht({tournamentRecord:u}),T={...g,tournamentId:I,indoorOutDoor:u.indoorOutdoor,surfaceCategory:u.surfaceCategory,endDate:u.endDate},y=Bn({policyDefinitions:c,tournamentRecord:u,contextProfile:m});return{matchUps:h.flatMap(E=>(T.eventDrawsCount=E.drawDefinitions?.length??0,ho({context:T,scheduleVisibilityFilters:o,tournamentAppliedPolicies:S,participantsProfile:i,afterRecoveryTimes:s,policyDefinitions:c,tournamentRecord:u,contextContent:y,contextFilters:l,contextProfile:m,matchUpFilters:d,participantMap:r,nextMatchUps:f,participants:n,inContext:p,event:E}).matchUps??[])).concat(...u.matchUps??[])}}function mn({scheduleVisibilityFilters:t,afterRecoveryTimes:e,participantsProfile:r,tournamentRecords:n,policyDefinitions:o,matchUpFilters:i,contextFilters:s,nextMatchUps:a,inContext:c}){if(typeof n!="object"||!Object.keys(n).length)return{error:kt};let p=Object.keys(n).map(m=>{let d=n[m];return le({scheduleVisibilityFilters:t,afterRecoveryTimes:e,participantsProfile:r,policyDefinitions:o,tournamentRecord:d,matchUpFilters:i,contextFilters:s,nextMatchUps:a,inContext:c}).matchUps??[]}).flat();return{...R,matchUps:p}}function Ai(t,e){return xF(t,e)||(t?.stageSequence||0)-(e?.stageSequence||0)||t?.roundNumber&&e.roundNumber&&t?.roundNumber-e?.roundNumber||(t?.roundPosition??0)-(e?.roundPosition??0)}function xF(t,e){return(Ls[t?.stage]||0)-(Ls[e?.stage]||0)}function or(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:y,endDate:N,eventType:E,category:A,gender:U,matchUpFormat:C}=S??{},P={...h,surfaceCategory:S?.surfaceCategory??p?.surfaceCategory,indoorOutDoor:S?.indoorOutdoor??p?.indoorOutdoor,matchUpFormat:C,eventType:E,eventName:y,category:A,eventId:T,endDate:N,gender:U},D;return!e?.length&&!r&&p&&({participants:e=[],participantMap:r,groupInfo:D}=fi({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})),{...ne({context:P,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:D}}function cs({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))}}}}var fU=t=>e=>!t||typeof e!="object"?void 0:Array.isArray(t)&&t.map(r=>({[r]:cs({element:e,accessor:r})?.value}))||typeof t=="object"&&Object.keys(t).map(r=>({[r]:cs({element:e,accessor:r})?.value}))||(typeof t=="string"&&cs({element:e,accessor:t}))?.value,Mr=fU;function Ua({finishingPositionOffset:t=0,finishingPositionLimit:e,positionsFed:r,roundsCount:n,roundLimit:o,matchUps:i,lucky:s,fmlc:a}){if(!Nr(i))return[];let{roundProfile:c,roundNumbers:u=[]}=qe({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(Mr("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},y=d?.slice(I-1).reduce((M,b)=>M+(b||0),0),N=a&&I!==1,E=1+t+(N?r??0:0),A=1,U=Z(E,s?E+S*2:y+E+A),C=y+A-S,P=l(U.slice(C)),D=l(U.slice(0,C),!0);return T.finishingPositionRange={loser:P,winner:D},{[I]:T}})),g=Pr({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 Gi({inContextDrawMatchUps:t,drawDefinition:e,matchUpsMap:r}){if(!e)return{error:X};let n={loserMatchUpIds:{},winnerMatchUpIds:{}};if(t||({matchUps:t,matchUpsMap:r}=ne({inContext:!0,drawDefinition:e,matchUpsMap:r})),!r?.drawMatchUps.some(i=>i.finishingPositionRange)&&e?.structures?.length===1&&!e?.structures[0].structures){let i=r?.drawMatchUps??[];Ua({matchUps:i})}return(t??[]).filter(({collectionId:i})=>!i).forEach(i=>{let{matchUpId:s,structureId:a}=i,c=nr({inContextDrawMatchUps:t,drawDefinition:e,matchUpId:s}),{winnerMatchUp:u,loserMatchUp:p}=c.targetMatchUps,m=u?.matchUpId,d=p?.matchUpId,f=ti({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 Yr(t){let e=en(t),r=t.matchUps??[],n=t.drawIds??[],{includeParticipantDependencies:o,tournamentRecord:i,drawDefinition:s}=t;if(!Array.isArray(r))return{error:An};if(!Array.isArray(n))return{error:$r};let a=t.matchUpIds?.length?t.matchUpIds:r.map(T=>T.matchUpId);if(!Array.isArray(a))return{error:ua};let c={},u={},p={},m={};i&&!Object.keys(e).length&&(e={[i.tournamentId]:i});let d=Object.values(e),f=d.reduce((T,y)=>T.concat(y.events??[]).map(N=>(N.drawDefinitions||[]).map(E=>E.links||[])).flat(1/0),[]).filter(({linkType:T})=>T===zn),g=r;if(f.length){g=mn({nextMatchUps:!0,tournamentRecords:e}).matchUps;let T=f.reduce((y,N)=>{let E=N.source?.structureId,A=N.target?.structureId;return E&&A&&(p[A]=E),E&&!y.includes(E)&&y.push(E),y},[]);for(let y of T)c[y]=[];for(let y of g??[]){let N=y.containerStructureId||y.structureId;T.includes(N)&&c[N].push(y.matchUpId)}}let I=T=>{u[T]||(u[T]={dependentMatchUpIds:[],participantIds:[],matchUpIds:[],sources:[]},m[T]=[])},h=(T,y)=>{u[T].matchUpIds.forEach(E=>{u[y].matchUpIds.push(E)}),u[y].matchUpIds.push(T),u[T].dependentMatchUpIds.push(y),o&&u[T].participantIds.forEach(E=>u[y].participantIds.push(E))},S=T=>{let y=Object.keys(c).length;for(let N of T||[]){let{matchUpId:E,winnerMatchUpId:A,loserMatchUpId:U}=N;if(!a.length||a.includes(E)){if(I(E),o){let{individualParticipantIds:D}=nu(N);u[E].participantIds=D}A&&(I(A),h(E,A),m[A].push(E)),U&&(I(U),h(E,U),m[U].push(E)),u[E].sources.push(m[E]);let C=m[E].map(D=>u[D].sources[0]).flat(),P=m[E].map(D=>u[D].sources[1]).flat();if(u[E].sources.push(C,P),y){let D=N.containerStructureId||N.structureId,M=p[D];if(c[M])for(let b of c[M])I(b),h(b,E),m[b].push(E)}}}};if(s)Gi({drawDefinition:s}),g?.length||(g=or({drawDefinition:s}).matchUps),S(g);else{if(g?.length||(g=mn({nextMatchUps:!0,tournamentRecords:e}).matchUps),!n.length){let T=d?.length?d.map(({events:y=[]})=>y.map(({drawDefinitions:N=[]})=>N.map(({drawId:E})=>E))).flat(1/0):[];T&&(n=T)}for(let T of n){let y=g?.filter(E=>E.drawId===T).sort(Ai);if(!y?.find(({roundPosition:E})=>!E)){let E=y?.find(({tournamentId:U})=>U),{drawDefinition:A}=je({tournamentRecord:e[E?.tournamentId],drawId:T});A&&Gi({drawDefinition:A})}S(y)}}return{positionDependencies:c,matchUpDependencies:u,sourceMatchUpIds:m,matchUps:g,...R}}function Ie(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 Pa({matchUpStatus:t}){return JI.includes(t)}function Ab({matchUpStatus:t}){return Cm.includes(t)}function jf({matchUpStatus:t}){return ZI.includes(t)}function Yf({matchUpStatus:t,winningSide:e,tieMatchUps:r,sides:n,score:o}){let i=n?.find(({participantId:c})=>c),s=r?.filter(Yf)?.length;return Ie({score:o})||s||e&&i||t&&Ab({matchUpStatus:t})&&![bt,vt,Cn].includes(t)}function Da(t){let{drawDefinition:e,findContainer:r,structureId:n,event:o}=t,i=t.structure,s={isCollectionMatchUp:!1},{containedStructures:a}=ts({drawDefinition:e}),c=n?a[n]||[]:[];if(!i){let A=st({drawDefinition:e,structureId:n});if(A.error)return A;i=r?A.containingStructure??A.structure:A.structure}if(gr({structure:i}))return{structure:i,isAdHoc:!0,error:Ds};let{matchUps:u}=ne({inContext:!0,matchUpFilters:s,drawDefinition:e,event:o}),p=u?.filter(A=>A.structureId===n||c.includes(A.structureId)),{matchUpDependencies:m}=Yr({drawIds:[e.drawId],matchUps:u,drawDefinition:e}),d=[],l=[],f={},g=[];for(let A of u??[]){if(A.structureId===n||c.includes(A.structureId)){l.push(...A.drawPositions??[]);let U=A.roundNumber;for(let C of(A.drawPositions??[]).filter(Boolean))(!f[C]||U&&f[C]>U)&&(f[C]=U)}Yf(A)&&(g.push(A),d.push(A.matchUpId,...m?.[A?.matchUpId]?.matchUpIds||[]))}let I=pt(l.filter(Boolean)).sort(se),h=pt(d),S=pt(p?.map(({matchUpId:A,drawPositions:U})=>h.includes(A)?U:[]).flat().filter(Boolean)).sort(se),{positionAssignments:T}=Ct({drawDefinition:e,structure:i}),y=T?.filter(A=>A.bye).map(A=>A.drawPosition),N=T?.filter(A=>A.qualifier).map(A=>A.drawPosition),E=I?.filter(A=>!S.includes(A))||[];return{allDrawPositions:I,inContextStructureMatchUps:p,drawPositionInitialRounds:f,activeDependentMatchUpIds:h,qualifyingDrawPositions:N,inactiveDrawPositions:E,positionAssignments:T,activeDrawPositions:S,byeDrawPositions:y,activeMatchUps:g,structure:i}}function us({drawPosition:t,matchUps:e=[]}){return{initialRoundNumber:e.filter(({drawPositions:n})=>t&&n?.includes(t)).map(({roundNumber:n})=>n).sort(se)[0]}}var Na={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 Hn(t,e){typeof t=="string"&&(t={method:t}),(e||Pr())&&Gh.push(t)}function wF(t){let e=Gh.slice();return t&&(Gh.length=0),e}function Eb(t){let r=wF(t).map(n=>{let{color:o,keyColors:i,method:s,newline:a}=n,c=Object.keys(Na).includes(o)?Na[o]:Na.cyan,p=Object.keys(n).filter(d=>!["color","keyColors","method","newline"].includes(d)).map(d=>{let l=i&&Object.keys(i).includes(d)&&Na[i[d]]?Na[i[d]]:Na.brightwhite;return`${Na.white}${d}: ${l}${n[d]}`}).join(", "),m=s?.length<15?" ":" ";return[a?`
1
+ var jw=Object.defineProperty;var Zt=(t,e)=>{for(var r in e)jw(t,r,{get:e[r],enumerable:!0})};function Ha(){return"2.0.39"}var tA={};Zt(tA,{competitionGovernor:()=>wE,drawsGovernor:()=>aN,entriesGovernor:()=>fN,eventGovernor:()=>NN,generationGovernor:()=>vN,matchUpFormatGovernor:()=>fy,matchUpGovernor:()=>XN,mocksGovernor:()=>tI,participantGovernor:()=>NM,policyGovernor:()=>kD,publishingGovernor:()=>_M,queryGovernor:()=>iN,reportGovernor:()=>xM,scheduleGovernor:()=>qM,scoreGovernor:()=>Mg,tieFormatGovernor:()=>rC,tournamentGovernor:()=>mC,venueGovernor:()=>AC});var wE={};Zt(wE,{getLinkedTournamentIds:()=>Kc,getTournamentIds:()=>ip,linkTournaments:()=>bE,mutate:()=>_E,query:()=>xE,unlinkTournament:()=>OE,unlinkTournaments:()=>vE});var _E={};Zt(_E,{linkTournaments:()=>bE,unlinkTournament:()=>OE,unlinkTournaments:()=>vE});var oR={};Zt(oR,{addNotice:()=>St,callListener:()=>gm,createInstanceState:()=>hE,cycleMutationStatus:()=>ql,deepCopyEnabled:()=>Yl,deleteNotice:()=>_I,deleteNotices:()=>Oi,disableNotifications:()=>SE,enableNotifications:()=>jl,getDevContext:()=>Pr,getMethods:()=>$l,getNotices:()=>OI,getProvider:()=>xI,getTopics:()=>vr,getTournamentId:()=>zi,getTournamentRecord:()=>Kl,getTournamentRecords:()=>xo,globalLog:()=>AE,handleCaughtError:()=>Zu,removeTournamentRecord:()=>yE,setDeepCopy:()=>Bc,setDevContext:()=>Vc,setGlobalLog:()=>eR,setGlobalMethods:()=>rR,setGlobalSubscriptions:()=>UL,setMethods:()=>nR,setStateMethods:()=>EE,setStateProvider:()=>AL,setSubscriptions:()=>PL,setTournamentId:()=>Ju,setTournamentRecord:()=>TE,setTournamentRecords:()=>Im,timeKeeper:()=>EL});function br(t){return typeof t=="function"}function Re(t){return typeof t=="string"}function Pt(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function LC(t,e){if(!Pt(t)||!Pt(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 lI(t,e){return Array.isArray(t)?Object.assign({},...(t??[]).filter(Pt).map(r=>r[e]&&{[r[e]]:r}).filter(Boolean)):{}}var FC=t=>e=>Object.keys(t).every(r=>e[r]===t[r]);function dI(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=>dI(i))}:{[o]:e?n(t[o]):dI(t[o])}))}function sA(t){return Array.isArray(t)?t.length+t.map(sA).reduce((e,r)=>e+r,0):typeof t=="object"&&t!==null?Object.keys(t).length+Object.keys(t).map(e=>sA(t[e])).reduce((e,r)=>e+r,0):0}function GC(t){if(t===null||typeof t!="object")return;let e=JSON.stringify(t),r=sA(t),n=e.split("").reduce((o,i)=>o+i.charCodeAt(0),0);return[e.length,r,n].map(o=>o.toString(36)).join("")}var R={success:!0},Yw="error",kC={SUCCESS:R,ERROR:Yw};var fI={message:"Chronological error; time violation.",code:"ANACHRONISM"},cm={message:"Duplicate entry",code:"DUPLICATE_ENTRY"},aA={message:"Cannot remove main structure",code:"ERR_CANNOT_REMOVE_MAIN_STRUCTURE"},gI={message:"records must be an object with tournamentId keys",code:"ERR_INVALID_TOURNAMENTS"},kt={message:"Missing tournamentRecords",code:"ERR_MISSING_TOURNAMENTS"},j={message:"Missing tournamentRecord",code:"ERR_MISSING_TOURNAMENT"},Wa={message:"Invalid tournamentRecord",code:"ERR_INVALID_TOURNAMENT"},sa={message:"Missing tournamentId",code:"ERR_MISSING_TOURNAMENT_ID"},aa={message:"Invalid drawDefinition",code:"ERR_INVALID_DRAWDEF"},X={message:"Missing drawDefinition",code:"ERR_MISSING_DRAWDEF"},cA={message:"Existing drawDefinition(s)",code:"ERR_EXISTING_DRAWDEFS"},dr={message:"drawDefinition not found",code:"ERR_NOT_FOUND_DRAWDEF"},Ci={message:"Invalid structure",code:"ERR_INVALID_STRUCTURE"},hl={message:"Incomplete source structure",code:"ERR_INCOMPLETE_STRUCTURE"},Sl={message:"Invalid drawPosition for seedAssignment",code:"ERR_INVALID_SEEDING_POSITION"},ja={message:"drawPosition already assigned",code:"ERR_EXISTING_POSITION_ASSIGNMENT"},uA={message:"Schedule not cleared",code:"ERR_UNCHANGED_SCHEDULE_NOT_CLEARED"},pA={message:"drawPosition not cleared",code:"ERR_FAILURE_POSITION_NOT_CLEARED"},qw={message:"drawPosition not found",code:"ERR_NOT_FOUND_DRAW_POSITION"},Tl={message:"Unrecognized drawType",code:"ERR_UNRECOGNIZED_DRAW_TYPE"},Ya={message:"Missing drawPositions",code:"ERR_MISSING_DRAW_POSITIONS"},Bu={message:"drawPosition is active",code:"ERR_ACTIVE_DRAW_POSITION"},Ds={message:"Invlid drawPosition",code:"ERR_INVALID_DRAW_POSITION"},Ns={message:"Missing drawPosition",code:"ERR_MISSING_DRAW_POSITION"},um={message:"Invalid drawType",code:"ERR_INVALID_DRAW_TYPE"},Hu={message:"Invalid drawSize",code:"ERR_INVALID_DRAW_SIZE"},II={message:"Cannot set drawSize to be less than existing entries",code:"ERR_INVALID_DRAW_SIZE_MISMATCH"},qa={message:"Missing drawSize",code:"ERR_MISSING_DRAW_SIZE"},$r={message:"Missing drawId",code:"ERR_MISSING_DRAW_ID"},mA={message:"drawId exists",code:"ERR_EXISTING_DRAW_ID"},dA={message:"participantId cannot be assigned to multiple seedNumbers",code:"INVALID_PARTICIPANT_SEEDING"},lA={message:"seedsCount greater than drawSize",code:"ERR_INVALID_SEED_COUNT"},fA={message:"Missing seedCountThresholds",code:"ERR_MISSING_SEED_COUNT_THRESHOLD"},gA={message:"Invalid action",code:"ERR_INVALID_ACTION"},hI={message:"Invalid assignment",code:"ERR_INVALID_ASSIGNMENT"},IA={message:"Missing seedAssignments",code:"ERR_MISSING_SEED_ASSIGNMENTS"},hA={message:"Invalid seedNumber",code:"ERR_INVALID_SEED_NUMBER"},SA={message:"Invalid seedPosition",code:"ERR_INVALID_SEED_POSITION"},yl={message:"Missing targetLink",code:"ERR_MISSING_LINK_TARGET"},TA={message:"Existing round",code:"ERR_EXISTING_ROUND"},$w={message:"Missing roundNumber",code:"ERR_MISSING_ROUND_NUMBER"},Sr={message:"Missing structureId",code:"ERR_MISSING_STRUCTURE_ID"},Gt={message:"structure not found",code:"ERR_NOT_FOUND_STRUCTURE"},Al={message:"Missing structures",code:"ERR_MISSING_STRUCTURES"},Oo={message:"Missing structure",code:"ERR_MISSING_STRUCTURE"},yA={message:"drawDefinition contains unlinked structures",code:"ERR_MISSING_STRUCTURE_LINKS"},_o={message:"Invalid eventType",code:"ERR_INVALID_EVENT_TYPE"};var Dt={message:"Missing event / eventId",code:"ERR_MISSING_EVENT_ID"},lr={message:"Event not found",code:"ERR_NOT_FOUND_EVENT"},AA={message:"Event exists",code:"ERR_EXISTING_EVENT"},EA={message:"Missing entries",code:"ERR_MISSING_ENTRIES"},UA={message:"Invalid entries",code:"ERR_INVALID_ENTRIES"},El={message:"Missing assignments",code:"ERR_MISSING_ASSIGNMENTS"},SI={message:"Missing stage",code:"ERR_MISSING_STAGE"},Ri={message:"Invalid stage",code:"ERR_INVALID_STAGE"},PA={message:"stageSequence limit",code:"ERR_LIMIT_STAGE_SEQUENCE"},DA={message:"Missing positionAssignments",code:"ERR_MISSING_POSITION_ASSIGNMENTS"},NA={message:"Cannot Assign BYE status if no assignment: { bye: true }",code:"ERR_UNCHANGED_CANNOT_ASSIGN_BYE"},TI={message:"Unrecognized matchUpStatus",code:"ERR_UNRECOGNIZED_MATCHUP_STATUS"},$a={message:"Unrecognized matchUpFormat",code:"ERR_UNRECOGNIZED_MATCHUP_FORMAT"},Ul={message:"Incompatible matchUpStatus",code:"ERR_INCOMPATIBLE_MATCHUP_STATUS"},ca={message:"Invalid matchUpStatus",code:"ERR_INVALID_MATCHUP_STATUS"},ai={message:"Invalid tieFormat",code:"ERR_INVALID_TIE_FORMAT"},Pl={message:"Invalid matchUpFormat",code:"ERR_INVALID_MATCHUP_FORMAT"},Dl={message:"Missing matchUpFormat",code:"ERR_MISSING_MATCHUP_FORMAT"},MA={message:"Missing collectionDefinition",code:"ERR_MISSING_COLLECTION_DEFINITION"},Ms={message:"Missing tieFormat",code:"ERR_MISSING_TIE_FORMAT"},Be={message:"Missing matchUpId",code:"ERR_MISSING_MATCHUP_ID"},ua={message:"Missing matchUpIds",code:"ERR_MISSING_MATCHUP_IDS"},_e={message:"matchUp not found",code:"ERR_NOT_FOUND_MATCHUP"},An={message:"Missing matchUps",code:"ERR_MISSING_MATCHUPS"},cr={message:"Missing matchUp",code:"ERR_MISSING_MATCHUP"},Ze={message:"Invalid matchUp",code:"ERR_INVALID_MATCHUP"},yI={message:"Missing policyType",code:"ERR_MISSING_POLICY_TYPE"},Wu={message:"Missing policyDefinitions",code:"ERR_MISSING_POLICY_DEFINITIONS"},Kw={message:"Missing seeding policy",code:"ERR_MISSING_POLICY_SEEDING"},CA={message:"Missing avoidance policy",code:"ERR_MISSING_POLICY_AVOIDANCE"},AI={message:"Missing policy attributes",code:"ERR_MISSING_POLICY_ATTRIBUTES"},RA={message:"Invalid policyDefinitions",code:"ERR_INVALID_POLICY_DEFINITIONS"},EI={message:"existing policyType",code:"ERR_EXISTING_POLICY_TYPE"},zw={message:"Policy not attached",code:"ERR_FAILURE_POLICY_NOT_ATTACHED"},Fc={message:"Policy not found",code:"ERR_NOT_FOUND_POLICY"},Qw={message:"Missing scoring policy / matchUpFormats",code:"ERR_MISSING_POLICY_SCORING_MATCHUP_FORMATS"},Nl={message:"Invalid sideNumber",code:"ERR_INVALID_SIDE_NUMBER"},Xw={message:"Invalid setNumber",code:"ERR_INVALID_SET_NUMBER"},Ml={message:"Missing setObject",code:"ERR_MISSING_SET_ATTRIBUTE"},Jw={message:"Missing setNumber",code:"ERR_MISSING_SET_NUMBER"},Zw={message:"Missing sideNumber",code:"ERR_MISSING_SIDE_NUMBER"},bi={message:"Missing courtId",code:"ERR_MISSING_COURT_ID"},rt={message:"Missing value",code:"ERR_MISSING_VALUE"},bA={message:"Missing date",code:"ERR_MISSING_DATE"},vA={message:"No valid dates",code:"ERR_NO_VALID_DATES"},pm={message:"Invalid bookings",code:"ERR_INVALID_BOOKINGS"},Cl={message:"Invalid dateAvailability",code:"ERR_INVALID_DATE_AVAILABILITY"},OA={message:"Missing dateAvailability",code:"ERR_MISSING_DATE_AVAILABILITY"},ur={message:"Invalid Date",code:"ERR_INVALID_DATE"},Ao={message:"Invalid time",code:"ERR_INVALID_TIME"},_A={message:"Invalid tournament dates",code:"ERR_INVALID_DATES_TOURNAMENT"};var UI={message:"Invalid game scores",code:"ERR_INVALID_SCORES_GAME"},xA={message:"Invalid score",code:"ERR_INVALID_SCORE"},mm={message:"Invalid winningSide",code:"ERR_INVALID_WINNING_SIDE"};var VC={message:"No participants generated",code:"ERR_NO_PARTICIPANTS_GENERATED"},Rl={message:"Cannot modify tieFormat",code:"ERR_UNCHANGED_CANNOT_MODIFY_TIEFORMAT"},wA={message:"Cannot modify participantType",code:"ERR_UNCHANGED_CANNOT_MODIFY_PARTICIPANT_TYPE"},ju={message:"Cannot remove participants",code:"ERR_UNCHANGED_CANNOT_REMOVE_PARTICIPANTS"},bl={message:"Cannot change winningSide",code:"ERR_UNCHANGED_CANNOT_CHANGE_WINNING_SIDE"},Cs={message:"Invalid participant",code:"ERR_INVALID_PARTICIPANT"},Zr={message:"Invalid participantId",code:"ERR_INVALID_PARTICIPANT_ID"},Kr={message:"Invalid participantIds",code:"ERR_INVALID_PARTICIPANT_IDS"},LA={message:"Invalid participantRole",code:"ERR_INVALID_PARTICIPANT_ROLE"},an={message:"Invalid participantType",code:"ERR_INVALID_PARTICIPANT_TYPE"},FA={message:"Missing participantRole",code:"ERR_MISSING_PARTICIPANT_ROLE"},vi={message:"Missing participant",code:"ERR_MISSING_PARTICIPANT"},Ka={message:"Missing participants",code:"ERR_MISSING_PARTICIPANTS"},ee={message:"Missing participantId",code:"ERR_MISSING_PARTICIPANT_ID"},re={message:"Participant Not Found",code:"ERR_NOT_FOUND_PARTICIPANT"},GA={message:"participantId exists",code:"ERR_EXISTING_PARTICIPANT_ID"},tL={message:"participant pair exists",code:"ERR_EXISTING_PARTICIPANT_PAIR"},kA={message:"No participant removed",code:"ERR_UNCHANGED_NO_PARTICIPANT_REMOVED"},Eo={message:"Missing participantIds",code:"ERR_MISSING_PARTICIPANT_IDS"},VA={message:"Missing participantsCount",code:"ERR_MISSING_PARTICIPANT_COUNT"},BA={message:"Participant not checked in",code:"ERR_UNCHANGED_PARTICIPANT_NOT_CHECKED_IN"},HA={message:"Missing person details",code:"ERR_MISSING_PERSON_DETAILS"},Rs={message:"Existing participant drawPosition assignment",code:"ERR_EXISTING_PARTICIPANT_DRAW_POSITION_ASSIGNMENT"},Yu={message:"Existing participant",code:"ERR_EXISTING_PARTICIPANT"},vl={message:"participantsCount exceeds drawSize",code:"ERR_INVALID_PARTICIPANT_COUNT"},Ol={message:"Invalid entry status",code:"ERR_INVALID_ENTRY_STATUS"},PI={message:"Participant Entry Not Found",code:"ERR_NOT_FOUND_PARTICIPANT_ENTRY"},BC={message:"Participant not entered in stage",code:"ERR_UNCHANGED_PARTICIPANT_NOT_ENTERED"},HC={message:"Participant not found in stageSequence",code:"ERR_NOT_FOUND_PARTICIPANT_IN_STAGE"},WA={message:"entryStatus not allowed in stage",code:"ERR_INVALID_ENTRY_STATUS_IN_STAGE"},jA={message:"entryStatus not allowed for event",code:"ERR_INVALID_ENTRY_STATUS_IN_EVENT"},DI={message:"No stage space available for entryStatus",code:"ERR_UNCHANGED_NO_AVAILABLE_STAGE_SPACE"},YA={message:"Insufficient drawPositions to accommodate qualifiers",code:"ERR_UNCHANGED_NO_DRAW_POSITIONS_FOR_QUALIFIERS"},_l={message:"Insufficient drawPositions to accommodate entries",code:"ERR_INSUFFICIENT_DRAW_POSITIONS"},qA={message:"Missing penaltyType",code:"ERR_MISSING_PENALTY_TYPE"},xl={message:"Missing penaltyId",code:"ERR_MISSING_PENALTY_ID"},Gc={message:"Penalty not found",code:"ERR_NOT_FOUND_PENALTY"},$A={message:"Missing courtsCount/courtNames",code:"ERR_MISSING_COURTS_INFO"},za={message:"Court not found",code:"ERR_NOT_FOUND_COURT"},KA={message:"Court exists",code:"ERR_EXISTING_COURT"},zA={message:"Venue exists",code:"ERR_EXISTING_VENUE"},bs={message:"Venue not found",code:"ERR_NOT_FOUND_VENUE"},jo={message:"Missing venueId",code:"ERR_MISSING_VENUE_ID"},QA={message:"Invalid endTime",code:"ERR_INVALID_END_TIME"},NI={message:"Existing endTime",code:"ERR_EXISTING_END_TIME"},XA={message:"Invalid stopTime",code:"ERR_INVALID_STOP_TIME"},JA={message:"Invalid startTime",code:"ERR_INVALID_START_TIME"},WC={message:"Invalid resumeTime",code:"ERR_INVALID_RESUME_TIME"},wl={message:"Invalid timeItem",code:"ERR_INVALID_TIME_ITEMS"},ZA={message:"Missing async state provider",code:"ERR_MISSING_ASYNC_STATE_PROVIDER"},Ll={message:"Missing timeItem",code:"ERR_MISSING_TIME_ITEM"},Fl={message:"Missing timeItems",code:"ERR_MISSING_TIME_ITEMS"},kc={message:"Missing context",code:"ERR_MISSING_CONTEXT"},tE={message:"Missing schedule",code:"ERR_MISSING_SCHEDULE"},qu={message:"Invalid scaleItem",code:"ERR_INVALID_SCALE_ITEM"},eE={message:"Modifications failed",code:"ERR_FAILURE_MODIFICATIONS"},vs={message:"No modifications applied",code:"ERR_UNCHANGED_NO_MODIFICATIONS_APPLIED"},rE={message:"Unable to assign court",code:"ERR_UNCHANGED_COURT_NOT_ASSIGNED"},$u={message:"No Candidates",code:"ERR_UNCHANGED_NO_CANDIDATES"},nE={message:"Invalid configuration",code:"ERR_INVALID_CONFIG"},oE={message:"Invalid collectionDefinition",code:"ERR_INVALID_COLLECTION_DEFINITION"},no={message:"Invalid object",code:"ERR_INVALID_OBJECT"},Gl={message:"Invalid gender",code:"ERR_INVALID_GENDER"},dm={message:"Invalid category",code:"ERR_INVALID_CATEGORY"},G={message:"Invalid values",code:"ERR_INVALID_VALUES"},iE={message:"Duplicate value",code:"ERR_DUPLICATE_VALUE"},kl={message:"Team not found",code:"ERR_NOT_FOUND_TEAM"},sE={message:"No valid actions",code:"ERR_NO_VALID_ACTIONS"},Ku={message:"No valid attributes",code:"ERR_NO_VALID_ATTRIBUTES"},Vl={message:"Value unchanged",code:"ABORT_UNCHANGED"},Le={message:"Not found",code:"ERR_NOT_FOUND"},zu={message:"Not implemented",code:"ERR_NOT_IMPLEMENTED"},aE={message:"Existing flight",code:"ERR_EXISTING_FLIGHT"},Bl={message:"Existing flight profile",code:"ERR_EXISTING_FLIGHT_PROFILE"},cE={message:"Existing outcome",code:"ERR_EXISTING_OUTCOME"},uE={message:"Existing matchUpId",code:"ERR_EXISTING_MATCHUP_ID"},MI={message:"Existing stage",code:"ERR_EXISTING_STAGE"},Hl={message:"Existing structure",code:"ERR_EXISTING_STRUCTURE"},Qa={message:"Method not found",code:"ERR_NOT_FOUND_METHOD"},pE={message:"Scheduled matchUps",code:"ERR_SCHEDULED_MATCHUPS"},Qu={message:"Scores present",code:"ERR_SCORES_PRESENT"},jC={ANACHRONISM:fI,CANNOT_CHANGE_WINNING_SIDE:bl,CANNOT_MODIFY_TIEFORMAT:Rl,CANNOT_MODIFY_PARTICIPANT_TYPE:wA,CANNOT_REMOVE_MAIN_STRUCTURE:aA,CANNOT_REMOVE_PARTICIPANTS:ju,COURT_EXISTS:KA,COURT_NOT_FOUND:za,DRAW_DEFINITION_NOT_FOUND:dr,DRAW_ID_EXISTS:mA,DRAW_POSITION_ACTIVE:Bu,DRAW_POSITION_ASSIGNED:ja,DRAW_POSITION_NOT_CLEARED:pA,DRAW_POSITION_NOT_FOUND:qw,DRAW_SIZE_MISMATCH:II,DUPLICATE_ENTRY:cm,DUPLICATE_VALUE:iE,ENTRY_STATUS_NOT_ALLOWED_FOR_EVENT:jA,ENTRY_STATUS_NOT_ALLOWED_IN_STAGE:WA,EVENT_EXISTS:AA,EVENT_NOT_FOUND:lr,EXISTING_DRAW_DEFINITIONS:cA,EXISTING_END_TIME:NI,EXISTING_FLIGHT:aE,EXISTING_MATCHUP_ID:uE,EXISTING_OUTCOME:cE,EXISTING_PARTICIPANT_DRAW_POSITION_ASSIGNMENT:Rs,EXISTING_PARTICIPANT:Yu,EXISTING_POLICY_TYPE:EI,EXISTING_PROFILE:Bl,EXISTING_ROUND:TA,EXISTING_STAGE:MI,EXISTING_STRUCTURE:Hl,INCOMPATIBLE_MATCHUP_STATUS:Ul,INCOMPLETE_SOURCE_STRUCTURE:hl,INSUFFICIENT_DRAW_POSITIONS:_l,INVALID_ACTION:gA,INVALID_ASSIGNMENT:hI,INVALID_BOOKINGS:pm,INVALID_CATEGORY:dm,INVALID_COLLECTION_DEFINITION:oE,INVALID_CONFIGURATION:nE,INVALID_DATE_AVAILABILITY:Cl,INVALID_DATE:ur,INVALID_DRAW_DEFINITION:aa,INVALID_DRAW_POSITION_FOR_SEEDING:Sl,INVALID_DRAW_POSITION:Ds,INVALID_DRAW_SIZE:Hu,INVALID_END_TIME:QA,INVALID_ENTRIES:UA,INVALID_EVENT_TYPE:_o,INVALID_GAME_SCORES:UI,INVALID_GENDER:Gl,INVALID_MATCHUP_FORMAT:Pl,INVALID_MATCHUP_STATUS:ca,INVALID_MATCHUP_STATUS_BYE:NA,INVALID_MATCHUP:Ze,INVALID_OBJECT:no,INVALID_PARTICIPANT_ID:Zr,INVALID_PARTICIPANT_IDS:Kr,INVALID_PARTICIPANT_ROLE:LA,INVALID_PARTICIPANT_SEEDING:dA,INVALID_PARTICIPANT_TYPE:an,INVALID_PARTICIPANT:Cs,INVALID_POLICY_DEFINITION:RA,INVALID_RECORDS:gI,INVALID_SCALE_ITEM:qu,INVALID_SEED_NUMBER:hA,INVALID_SEED_POSITION:SA,INVALID_SET_NUMBER:Xw,INVALID_SIDE_NUMBER:Nl,INVALID_SCORE:xA,INVALID_STAGE:Ri,INVALID_START_TIME:JA,INVALID_STRUCTURE:Ci,INVALID_STOP_TIME:XA,INVALID_TIE_FORMAT:ai,INVALID_TIME:Ao,INVALID_TIME_ITEM:wl,INVALID_TOURNAMENT_DATES:_A,INVALID_TOURNAMENT_RECORD:Wa,INVALID_VALUES:G,INVALID_WINNING_SIDE:mm,MATCHUP_NOT_FOUND:_e,METHOD_NOT_FOUND:Qa,MISSING_ASSIGNMENTS:El,MISSING_ASYNC_STATE_PROVIDER:ZA,MISSING_AVOIDANCE_POLICY:CA,MISSING_COLLECTION_DEFINITION:MA,MISSING_COURT_ID:bi,MISSING_COURTS_INFO:$A,MISSING_DATE_AVAILABILITY:OA,MISSING_DATE:bA,MISSING_DRAW_DEFINITION:X,MISSING_DRAW_ID:$r,MISSING_DRAW_POSITION:Ns,MISSING_DRAW_POSITIONS:Ya,MISSING_DRAW_SIZE:qa,MISSING_ENTRIES:EA,MISSING_EVENT:Dt,MISSING_MATCHUP_FORMAT:Dl,MISSING_MATCHUP_ID:Be,MISSING_MATCHUP_IDS:ua,MISSING_MATCHUP:cr,MISSING_MATCHUPS:An,MISSING_PARTICIPANT_COUNT:VA,MISSING_PARTICIPANT_ID:ee,MISSING_PARTICIPANT_IDS:Eo,MISSING_PARTICIPANT_ROLE:FA,MISSING_PARTICIPANT:vi,MISSING_PARTICIPANTS:Ka,MISSING_PENALTY_ID:xl,MISSING_PENALTY_TYPE:qA,MISSING_PERSON_DETAILS:HA,MISSING_POLICY_ATTRIBUTES:AI,MISSING_POLICY_DEFINITION:Wu,MISSING_POLICY_TYPE:yI,MISSING_POSITION_ASSIGNMENTS:DA,MISSING_ROUND_NUMBER:$w,MISSING_SCHEDULE:tE,MISSING_SCORING_POLICY:Qw,MISSING_SEED_ASSIGNMENTS:IA,MISSING_SEEDCOUNT_THRESHOLDS:fA,MISSING_SEEDING_POLICY:Kw,MISSING_SET_NUMBER:Jw,MISSING_SET_OBJECT:Ml,MISSING_SIDE_NUMBER:Zw,MISSING_STAGE:SI,MISSING_STRUCTURE_ID:Sr,MISSING_STRUCTURE:Oo,MISSING_STRUCTURES:Al,MISSING_TARGET_LINK:yl,MISSING_TIE_FORMAT:Ms,MISSING_TIME_ITEM:Ll,MISSING_TIME_ITEMS:Fl,MISSING_TOURNAMENT_ID:sa,MISSING_TOURNAMENT_RECORD:j,MISSING_TOURNAMENT_RECORDS:kt,MISSING_VALUE:rt,MISSING_VENUE_ID:jo,MODIFICATIONS_FAILED:eE,NO_CANDIDATES:$u,NO_DRAW_POSITIONS_AVAILABLE_FOR_QUALIFIERS:YA,NO_MODIFICATIONS_APPLIED:vs,NO_STAGE_SPACE_AVAILABLE_FOR_ENTRY_STATUS:DI,NO_PARTICIPANT_REMOVED:kA,NO_VALID_ACTIONS:sE,NO_VALID_ATTRIBUTES:Ku,NO_VALID_DATES:vA,NOT_FOUND:Le,NOT_IMPLEMENTED:zu,PARTICIPANT_COUNT_EXCEEDS_DRAW_SIZE:vl,PARTICIPANT_ID_EXISTS:GA,PARTICIPANT_NOT_CHECKED_IN:BA,PARTICIPANT_NOT_FOUND:re,PARTICIPANT_PAIR_EXISTS:tL,PENALTY_NOT_FOUND:Gc,POLICY_NOT_ATTACHED:zw,POLICY_NOT_FOUND:Fc,SCHEDULE_NOT_CLEARED:uA,SCHEDULED_MATCHUPS:pE,SCORES_PRESENT:Qu,SEEDSCOUNT_GREATER_THAN_DRAW_SIZE:lA,STAGE_SEQUENCE_LIMIT:PA,STRUCTURE_NOT_FOUND:Gt,TEAM_NOT_FOUND:kl,UNABLE_TO_ASSIGN_COURT:rE,UNLINKED_STRUCTURES:yA,UNRECOGNIZED_DRAW_TYPE:Tl,UNRECOGNIZED_MATCHUP_FORMAT:$a,UNRECOGNIZED_MATCHUP_STATUS:TI,VALUE_UNCHANGED:Vl,VENUE_EXISTS:zA};var tr={disableNotifications:!1,tournamentId:void 0,tournamentRecords:{},subscriptions:{},modified:!1,methods:{},notices:[]},mE={addNotice:dL,callListener:hL,cycleMutationStatus:mL,deleteNotice:gL,deleteNotices:fL,disableNotifications:eL,enableNotifications:rL,getMethods:Xu,getNotices:lL,getTopics:IL,getTournamentId:YC,getTournamentRecord:nL,getTournamentRecords:oL,removeTournamentRecord:cL,setMethods:pL,setSubscriptions:uL,setTournamentId:sL,setTournamentRecord:iL,setTournamentRecords:aL,handleCaughtError:SL};function eL(){tr.disableNotifications=!0}function rL(){tr.disableNotifications=!1}function YC(){return tr.tournamentId}function nL(t){return tr.tournamentRecords[t]}function oL(){return tr.tournamentRecords}function iL(t){let e=t?.tournamentId;return e?(tr.tournamentRecords[e]=t,{success:!0}):{error:Wa}}function sL(t){return t?tr.tournamentRecords[t]?(tr.tournamentId=t,{success:!0}):{error:j}:(tr.tournamentId=void 0,{success:!0})}function aL(t){tr.tournamentRecords=t;let e=Object.keys(t);e.length===1?tr.tournamentId=e[0]:e.length||(tr.tournamentId=void 0)}function cL(t){if(typeof t!="string")return{error:G};if(!tr.tournamentRecords[t])return{error:Le};delete tr.tournamentRecords[t];let e=Object.keys(tr.tournamentRecords);return e.length===1?tr.tournamentId=e[0]:e.length||(tr.tournamentId=void 0),{success:!0}}function uL(t){return typeof t.subscriptions!="object"?{error:G}:(Object.keys(t.subscriptions).forEach(e=>{tr.subscriptions[e]=t.subscriptions[e]}),{...R})}function pL(t){return typeof t!="object"?{error:G}:(Object.keys(t).forEach(e=>{typeof t[e]=="function"&&(tr.methods[e]=t[e])}),{...R})}function mL(){let t=tr.modified;return tr.modified=!1,t}function dL({topic:t,payload:e,key:r},n){if(!(typeof t!="string"||typeof e!="object")&&(tr.disableNotifications||(tr.modified=!0),!(tr.disableNotifications||!tr.subscriptions[t]&&!n)))return r&&(tr.notices=tr.notices.filter(o=>!(o.topic===t&&o.key===r))),tr.notices.push({topic:t,payload:e,key:r}),{...R}}function Xu(){return tr.methods??{}}function lL({topic:t}){return tr.notices.filter(e=>e.topic===t).map(e=>e.payload)}function fL(){tr.notices=[]}function gL({topic:t,key:e}){tr.notices=tr.notices.filter(r=>(!t||r.topic===t)&&r.key!==e)}function IL(){return{topics:Object.keys(tr.subscriptions)}}function hL({topic:t,notices:e},r){let n=tr.subscriptions[t];n&&typeof n=="function"&&n(e);let o=r?.[t];o&&typeof o=="function"&&o(e)}function SL({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:YC(),params:JSON.stringify(r),engine:t,methodName:e,error:o}),{error:o}}function se(t,e){return(t??0)-(e??0)}function ct(t){return typeof t=="number"?parseInt(t.toString()):typeof t=="string"?parseInt(t):0}function En(t){return isNaN(t)?!1:t&&(t&t-1)===0}function dE(t){if(!t.length)return;let e=[...t].sort(se),r=Math.floor(e.length/2);return e.length%2?e[r]:(e[r-1]+e[r])/2}function qC(t){if(!En(t))return!1;let e=t,r=1;for(;e!==2;)r+=1,e=e/2;return r}function lm(t){return isNaN(t)?0:t%2&&t+1||t}function fm(t){return Math.pow(2,Math.round(Math.log(t)/Math.log(2)))}function Jt(t){return!isNaN(parseFloat(t))}function CI(t){let e=ct(t);if(!isNaN(e))return e===0?!1:(e&-e)===1}function Ki(t){if(isNaN(t))return!1;for(;!En(t);)t++;return t}function oo(t,e){return t=Math.ceil(t),e=Math.floor(e),Math.floor(Math.random()*(e-t+1))+t}function ft(t){return Number.isSafeInteger(typeof t=="string"?+t:t)}function $C(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 TL(t,e){e||(e=1);let r=1/e;return Math.round(t*r)/r}function lE(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=lE(t,e,r):(a=Math.pow(a,r),a*=e-t,a+=t),n&&(a=TL(a,n)),parseFloat(a.toFixed(o))}function pt(t){return Array.isArray(t)?t?.filter((e,r,n)=>n.lastIndexOf(e)===r):[]}function KC(t){return Array.isArray(t)?t?.map(e=>e===null?void 0:e):t}function pr(t){return Array.isArray(t)?t.map(e=>[Math.random(),e]).sort((e,r)=>e[0]-r[0]).map(e=>e[1]):[]}function Xa(t){return ft(t)?t:1/0}function fr(t){return Array.isArray(t)?t.reduce((e,r)=>(e[r]||(e[r]=0),e[r]++,e),{}):{}}function zC(t){return fE(fr(t))}function fE(t){return Object.keys(t).reduce((e,r)=>{let n=t[r];return e[n]?e[n].push(r):e[n]=[r],e},{})}function yL(t,e,r){return r.indexOf(t)===e}function RI(t){return t.filter(yL)}function Gr(t){return Array.isArray(t)&&t.length?t.splice(Math.floor(Math.random()*t.length),1)[0]:void 0}function cn(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 io(t,e){return e.reduce((r,n,o)=>(n===t&&r.push(o),r),[])}function jt(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 gE(t,e){return!Array.isArray(t)||!Array.isArray(e)?[]:t.filter(r=>!e.includes(r))}function Fe(t,e){return!Array.isArray(t)||!Array.isArray(e)?!1:t.some(r=>e.includes(r))}function QC(t,e){return Array.isArray(e)&&e.reduce((r,n)=>(r[n]=1+r[n]||1,r),{})[t]||0}function XC(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 Te(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 IE(t,[e,...r]){return t.length?[t.slice(0,e),...IE(t.slice(e),[...r,e])]:[]}function JC(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 bI(t){return Array.isArray(t)?t.reduce((e,r)=>!isNaN(parseInt(r))&&e,!0):!1}function vI(t){return Array.isArray(t)?t.reduce((e,r)=>isNaN(parseInt(r))&&e,!0):!1}function Wl(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 ZC(t,e=1){if(!Array.isArray(t)||!t.every(ft))return[];let r=Math.min(...t,e),n=Math.max(...t);return Z(r,n+1).filter(o=>!t.includes(o))}var De={timers:{default:{elapsedTime:0}},globalSubscriptions:{},deepCopyAttributes:{stringify:[],ignore:[],toJSON:[]},globalMethods:[],deepCopy:!0},zr=mE,tR=["addNotice","callListener","cycleMutationStatus","deleteNotice","deleteNotices","disableNotifications","enableNotifications","getMethods","getNotices","getTopics","getTournamentId","getTournamentRecord","getTournamentRecords","removeTournamentRecord","setSubscriptions","setTournamentId","setTournamentRecord","setTournamentRecords"];function AL(t){if(typeof t!="object")throw new Error("Global state provider can not be undefined or null");if(jt(Object.keys(t),tR).length!==tR.length)throw new Error("Global state provider is missing required methods");return zr=t,{success:!0}}function hE(){if(zr.createInstanceState){try{zr.createInstanceState()}catch(t){return{error:t}}return{success:!0}}else return{error:ZA}}function Pr(t){return!t||typeof t!="object"?De.devContext??!1:typeof De.devContext!="object"?!1:Object.keys(t).every(e=>De.devContext?.[e]===t[e])&&De.devContext}function EL(t="reset",e="default"){let r=Date.now();if(t==="report"){if(e==="allTimers")return Object.keys(De.timers).filter(o=>o!=="default"||De.timers[o].startTime).map(o=>{let i=De.timers[o],s=i.state==="stopped"?0:(r-(i?.startTime??0))/1e3,a=i.elapsedTime+s;return{state:De.timers[o].state,elapsedTime:a.toFixed(2),timer:o}});{let n=De.timers[e].state==="stopped"?0:(r-(De.timers[e]?.startTime??0))/1e3,o=De.timers[e].elapsedTime+n;return{state:De.timers[e].state,elapsedTime:o.toFixed(2),timer:e}}}if(!De.timers[e]||t==="reset"){if(e==="allTimers")return De.timers={default:{elapsedTime:0}},!0;De.timers[e]={startTime:r,state:"active",elapsedTime:0}}return De.timers[e].elapsedTime||(De.timers[e].elapsedTime=0),t==="stop"&&De.timers[e].state!=="stopped"&&(De.timers[e].state="stopped")&&(De.timers[e].elapsedTime+=(r-(De.timers[e]?.startTime??0))/1e3),t==="start"&&(De.timers[e].startTime=r)&&(De.timers[e].state="active"),De.timers[e]}function eR(t){br(t)?De.globalLog=t:delete De.globalLog}function Vc(t){De.devContext=t}function SE(){zr.disableNotifications()}function jl(){zr.enableNotifications()}function Bc(t,e){typeof t=="boolean"&&(De.deepCopy=t),typeof e=="object"&&(Array.isArray(e.ignore)&&(De.deepCopyAttributes.ignore=e.ignore),Array.isArray(e.toJSON)&&(De.deepCopyAttributes.toJSON=e.toJSON),Array.isArray(e.stringify)&&(De.deepCopyAttributes.stringify=e.stringify),e.threshold&&(De.deepCopyAttributes.threshold=e.threshold))}function Yl(){return{enabled:De.deepCopy,...De.deepCopyAttributes}}function UL(t){return t?.subscriptions?(Object.keys(t.subscriptions).forEach(e=>{De.globalSubscriptions[e]=t.subscriptions[e]}),{...R}):{error:rt,info:"missing subscriptions"}}function PL(t){return t?.subscriptions?zr.setSubscriptions({subscriptions:t.subscriptions}):{error:rt,info:"missing subscriptions"}}function rR(t){return t?typeof t!="object"?{error:G}:(Object.keys(t).forEach(e=>{br(t[e])&&(De.globalMethods[e]=t[e])}),{...R}):{error:rt,info:"missing method declarations"}}function nR(t){return t?typeof t!="object"?{error:G}:zr.setMethods(t):{error:rt,info:"missing method declarations"}}function ql(){return zr.cycleMutationStatus()}function St(t){if(typeof t?.topic!="string")return;let e=De.globalSubscriptions[t.topic];return zr.addNotice(t,e)}function $l(){return{...De.globalMethods,...zr.getMethods()}}function OI(t){return zr.getNotices(t)}function _I({key:t,topic:e}){return zr.deleteNotice({key:t,topic:e})}function Oi(){return zr.deleteNotices()}function vr(){return zr.getTopics()}async function gm(t){return zr.callListener(t,De.globalSubscriptions)}function zi(){return zr.getTournamentId()}function Kl(t){return zr.getTournamentRecord(t)}function xo(){return zr.getTournamentRecords()}function TE(t){return zr.setTournamentRecord(t)}function Im(t){return zr.setTournamentRecords(t)}function Ju(t){return zr.setTournamentId(t)}function yE(t){return zr.removeTournamentRecord(t)}function xI(){return zr}function Zu({engineName:t,methodName:e,params:r,err:n}){return(br(zr.handleCaughtError)&&zr.handleCaughtError||mE.handleCaughtError)({engineName:t,methodName:e,params:r,err:n})}function AE(t,e){if(De.globalLog)try{De.globalLog({log:t,engine:e})}catch(r){console.log("globalLog error",r),console.log(e,t),eR()}else console.log(e,t)}function EE(t,e,r,n){if(!Pt(t))return{error:G};Jt||(r=1);let o=Array.isArray(e)?e:[],i={},s=(a,c=0)=>{Object.keys(a).forEach(u=>{br(a[u])?i[u]=a[u]:Pt(a[u])&&(e===!0||o?.includes(u))&&(r===void 0||c<r)&&s(a[u],c+1)})};return s(t),n?rR(i):nR(i),{methods:i}}function DL(t,e,r){return Object.keys(t).filter(n=>!e.includes(t[n])&&(!r||(Array.isArray(t[n])?t[n].length:!0)))}function nt(t,e,r,n){if(typeof t!="object"||t===null)return t;Yl()?.enabled||(n=!0);let i=["",void 0,null];e&&i.push(!1);let s=DL(t,i,r);return Object.assign({},...s.map(a=>Array.isArray(t[a])?{[a]:n?t[a]:t[a].map(c=>nt(c))}:{[a]:n?t[a]:nt(t[a])}))}function _({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,nt(t)),e&&!e?.error&&!e?.success&&Object.assign(e,{...R}),e??{success:!0}}var Ae="tournamentRecords",zl="policyDefinitions",un="tournamentRecord",Or="drawDefinition",hm="matchUpFormat",jn="participantId",wI="scheduleDates",iR="tournamentId",sR="scheduleDate",Sm="structureId",Ql="participant",Ja="matchUpIds",aR="policyType",UE="structures",so="matchUpId",Hc="inContext",Xl="structure",tp="courtIds",cR="personId",ep="venueIds",PE="matchUps",LI="courtId",FI="eventId",Un="matchUp",GI="drawId",Yo="error",Os="event",Qi="param",uR="uuids",pR="averageMatchUpMinutes",mR="recoveryMinutes",dR="periodLength",lR="number";var Yn="object",Dr="array";var Pn="_validate",kI="_message",Dn="_invalid",dn="_ofType",Tm="_anyOf",Za="_oneOf";var NL={[Ae]:kt,[un]:j,[zl]:Wu,[Or]:X,[jn]:ee,[hm]:Dl,[iR]:sa,[Sm]:Sr,[Ja]:ua,[Ql]:vi,[UE]:Al,[so]:Be,[Xl]:Oo,[LI]:bi,[PE]:An,[FI]:lr,[Un]:cr,[tp]:rt,[ep]:rt,[GI]:$r,[Os]:Dt},ML={[Ae]:Yn,[zl]:Yn,[un]:Yn,[Or]:Yn,[wI]:Dr,[Ql]:Yn,[Ja]:Dr,[UE]:Dr,[Xl]:Yn,[tp]:Dr,[ep]:Dr,[PE]:Dr,[Un]:Yn,[Os]:Yn,[uR]:Dr};function ut(t,e,r){if(!t&&!Pt(t))return{error:G};if(!e?.length||t?._bypassParamCheck)return{valid:!0};if(!Array.isArray(e))return{error:G};let{paramError:n,errorParam:o}=bL(t,e);if(!n)return{valid:!0};let i=t?.[o]===void 0?NL[o]||n[Yo]||G:n[Pn]&&n[Dn]||G,s=o??(n[Za]&&Object.keys(n[Za]).join(", "));return _({info:{param:s,message:n[kI]},result:{error:i},stack:r})}function fR(t,e){let r=Object.keys(t),n=Object.keys(e);return jt(r,n)}function CL(t,e){if(!e)return;let r=fR(t,e);return r.length!==1?{error:G}:r.reduce((n,o)=>({...n,[o]:!0}),{})}function RL(t,e){if(!e)return;let r=fR(t,e).filter(n=>t[n]);return r.length<1?{error:G}:r.reduce((n,o)=>({...n,[o]:!0}),{})}function bL(t,e){let r,n;return{paramError:e.find(({_ofType:i,_oneOf:s,_anyOf:a,_validate:c,_info:u,...p})=>{let m=s&&CL(t,s);if(m?.error)return m.error;m&&Object.assign(p,m);let d=a&&RL(t,a);if(d?.error)return d.error;d&&Object.assign(p,d);let l=Object.keys(p).filter(g=>typeof p[g]=="boolean"),f=l.find(g=>{let I=c&&!br(c),h=t[g]!==void 0&&!c&&vL(t,g,i),S=p[g]&&[void 0,null].includes(t[g]),y=I||h||S||c&&t[g]!==void 0&&!OL(t[g],c);return y&&(r=g,n=u),y});return!l.length||f}),errorParam:r,paramInfo:n}}function vL(t,e,r){return r=r||ML[e]||"string",r==="array"?!Array.isArray(t[e]):typeof t[e]!==r}function OL(t,e){return br(e)?e(t):!0}var VI="DYNAMIC",ci="RANKING",Xi="RATING",Ji="SCALE",ao="SEEDING",gR={RANKING:ci,RATING:Xi,SCALE:Ji,SEEDING:ao};function pa(t){let e=ut(t,[{[Ql]:!0}]);if(e.error)return e;let r=t.participant.timeItems?.filter(({itemType:o})=>o?.startsWith(Ji)&&[ci,Xi,ao].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=pt(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===ao&&"seedings"||c===ci&&"rankings"||"ratings";n[l][u]||(n[l][u]=[]),n[l][u].push({scaleValue:a.itemValue,scaleDate:a.itemDate,scaleName:d})}}}return{...R,...n}}function _i(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 ym=/^[\d]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][\d]|3[0-1])$/,BI=/^((0[\d]|1[\d]|2[0-3]):[0-5][\d](:[0-5][\d])?)([.,][0-9]{3})?$/,wo=/^([\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?$/,_s=/^([\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 Am(t){let{scheduledDate:e}=t;if(!e&&t.scheduledTime&&(e=Ut(t.scheduledTime)),!e)return;let r=$t(t.scheduledTime),n=Ut(e);return n&&r&&(n+=`T${r}`),n}function IR(t){return typeof t!="object"||Array.isArray(t)?!1:Object.prototype.toString.call(t)==="[object Date]"}function Wc(t){let e=typeof t=="string"?t?.split(" "):[];return t&&e?.length>1&&!["AM","PM"].includes(e[1].toUpperCase())?!1:!!(!t||_s.test(ec(t,!0,!0)))}function _r(t){return tc(t)||ym.test(t)}function _L(t){let e=new Date(t),r=e.getSeconds()+60*e.getMinutes()+60*60*e.getHours();return xL(r,{displaySeconds:!1})}function xL(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(qn).join(":")}var tf=t=>{let e=Jl(t)||tc(t)?new Date(t):new Date,r=e.getUTCMonth()+1,n=r<10?`0${r}`:`${r}`;return`${e.getUTCFullYear()}-${qn(n)}-${qn(e.getUTCDate())}`};function wL(t){let e=Jl(t)||tc(t)?new Date(t):new Date;return Date.UTC(e.getFullYear(),e.getMonth(),e.getDate())}function co(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 HI(t){let e=t?new Date(t):new Date,r=e.getTimezoneOffset();return new Date(e.getTime()-r*60*1e3)}function LL(t){return HI(t).getTime()}function Jl(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 xs(t,e){if(!_r(t)||!_r(e))return[];let r=Ut(t)+"T00:00",n=Ut(e)+"T00:00",o=new Date(r),i=new Date(n),s=Jl(i)&&Jl(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=>co(p));function u(p,m){return p<=m}}var FL=/^([+-]?\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 tc(t){return typeof t!="string"?!1:FL.test(t)}function jI(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 Vt(t){let e=$t(t);if(!e)return 0;let[r,n]=e.split(":").map(o=>parseInt(o));return r*60+n}function hR(t){let e=Math.floor(t/60),r=t-e*60;return e>23&&(e=e%24),[qn(e),qn(r)].join(":")}function Zl(t){return jI(t)?t.split(":").slice(0,2).map(qn).join(":"):void 0}function $t(t){return tc(t)&&t.indexOf("T")>0?Zl(t.split("T").reverse()[0]):Zl(t)}function Ut(t){return tc(t)||wo.test(t)?t.split("T")[0]:void 0}function rp(t,e){let r=new Date(t);return r.setDate(r.getDate()+e),Ut(r.toISOString())}function WI(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 GL(t){let e=WI(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(qn).join(":")}function kL(t){let e=WI(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 ec(t,e,r){let n=Ut(t),o=$t(t),i=n?o:t;return t?e&&(n&&r&&t||GL(i))||kL(i):void 0}function YI(t,e){let r=WI(t),n=WI(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 SR(t,e=7){let r=Ut(t)+"T00:00",n=new Date(r),o=new Date(n.setDate(n.getDate()+e));return co(o)}function VL(t){return SR(t)}function BL(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())),co(o,r)}function TR(t,e,r){let n=new Date(t,0);return co(new Date(n.setDate(e)),r)}function Ge(t,e=void 0){let[r,n]=(t||"00:00").split(":").map(qn),o=HI(e).setHours(r,n,0,0);return HI(o)}function ma(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 xr(t,e){let r=$t(t);if(!r)return"00:00";let n=isNaN(e)?0:e;return $t(ef(Ge(r),n).toISOString())}function ef(t,e){let r=new Date(t);return new Date(r.getTime()+e*6e4)}function qn(t){return t.toString()[1]?t:"0"+t}function wn(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 yR={addDays:SR,addWeek:VL,addMinutesToTimeString:xr,convertTime:ec,getIsoDateString:Am,getUTCdateString:tf,DateHHMM:_L,extractDate:Ut,extractTime:$t,formatDate:co,getDateByWeek:BL,isISODateString:tc,isDate:Jl,isTimeString:jI,offsetDate:HI,offsetTime:LL,sameDay:wn,timeStringMinutes:Vt,timeToDate:Ge,timeUTC:wL,validTimeValue:Wc,validDateString:ym,timeValidation:_s,dateValidation:wo};function J(t,e,r,n,o=0){if(xI().makeDeepCopy)return xI().makeDeepCopy(t,e,r,n);let i=Yl(),{stringify:s,toJSON:a,ignore:c,modulate:u}=i||{};if(!i?.enabled&&!r||typeof t!="object"||br(t)||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)||br(c)&&!c(l)),d=(l,f)=>{p[l]=br(f?.toString)?f.toString():JSON.stringify(f)};for(let l of m){let f=t[l],g=br(u)?u(f):void 0;if(g!==void 0)p[l]=g;else if(e&&l==="extensions"&&Array.isArray(f)){let I=rf(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)&&br(f?.toJSON)?p[l]=f.toJSON():f===null?p[l]=void 0:IR(f)?p[l]=new Date(f).toISOString():p[l]=J(f,e,r,n,o+1)}return p}function rf(t){return t?.map(e=>{let{name:r,value:n}=e;return r&&n&&{[`_${r}`]:n}}).filter(Boolean)}var qI="voluntaryConsolation",ui="competitiveBands",nf="roundRobinTally",uo="positionActions",Qe="matchUpActions",of="rankingPoints",da="roundNaming",ws="participant",jc="progression",Uo="scheduling",Yc="avoidance",HL="display",Ln="scoring",Nn="seeding",rc="feedIn",WL="audit",Em="draws",AR={POLICY_TYPE_VOLUNTARY_CONSOLATION:qI,POLICY_TYPE_COMPETITIVE_BANDS:ui,POLICY_TYPE_ROUND_ROBIN_TALLY:nf,POLICY_TYPE_POSITION_ACTIONS:uo,POLICY_TYPE_MATCHUP_ACTIONS:Qe,POLICY_TYPE_RANKING_POINTS:of,POLICY_TYPE_ROUND_NAMING:da,POLICY_TYPE_PARTICIPANT:ws,POLICY_TYPE_PROGRESSION:jc,POLICY_TYPE_SCHEDULING:Uo,POLICY_TYPE_AVOIDANCE:Yc,POLICY_TYPE_DISPLAY:HL,POLICY_TYPE_FEED_IN:rc,POLICY_TYPE_SCORING:Ln,POLICY_TYPE_SEEDING:Nn,POLICY_TYPE_AUDIT:WL,POLICY_TYPE_DRAWS:Em};function Lo({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?.[ws];if(r?.withScaleValues){let{ratings:u,rankings:p}=pa({participant:a});a.rankings=p,a.ratings=u}if(c?.participant)return _i({template:c.participant,source:a})}return a}var ER="element required",UR="missing name";function sr(t){if(!t||typeof t!="object")return{error:rt};if(t.element&&typeof t?.element!="object")return{error:G};if(!t?.name)return{error:rt,info:UR};if(!t?.element){if(t.discover&&t.tournamentRecords){for(let e of Object.keys(t.tournamentRecords)){let r=t.tournamentRecords[e],n=sr({element:r,name:t.name});if(n.error)return _({result:n,stack:"removeExtension"})}return{...R}}return{error:rt,info:ER}}return t?.element.extensions?(t.element.extensions=t.element.extensions.filter(e=>e?.name!==t.name),{...R}):{...R,info:Le}}function Mn({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 yt(t){if(typeof t!="object")return{error:rt};let e="addExtension";if(t?.element&&typeof t.element!="object")return _({result:{error:G},stack:e});if(!Mn({extension:t.extension}))return _({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=yt({extension:t.extension,element:o});if(i.error)return _({result:i,stack:e})}return{...R}}else return _({result:{error:rt},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 sf(t){return!t||typeof t!="object"?{error:rt}:t.tournamentRecord?yt({creationTime:t.creationTime,element:t.tournamentRecord,extension:t.extension}):{error:j}}function np(t){return!t||typeof t!="object"?{error:rt}:t.drawDefinition?yt({creationTime:t.creationTime,element:t.drawDefinition,extension:t.extension}):{error:dr}}function Po(t){return!t||typeof t!="object"?{error:rt}:t.event?yt({creationTime:t.creationTime,extension:t.extension,element:t.event}):{error:lr}}function DE(t){if(!t||typeof t!="object")return{error:rt};if(!t.participantId)return{error:ee};let e=t.tournamentRecord?.participants||[],r=Lo({participantId:t.participantId,tournamentParticipants:e});return r?yt({creationTime:t.creationTime,extension:t.extension,element:r}):{error:re}}function af(t){return!t||typeof t!="object"?{error:rt}:t.tournamentRecord?sr({element:t.tournamentRecord,name:t.name}):{error:j}}function NE(t){return!t||typeof t!="object"?{error:rt}:t.drawDefinition?sr({element:t.drawDefinition,name:t.name}):{error:dr}}function op(t){return!t||typeof t!="object"?{error:rt}:t?.event?sr({element:t.event,name:t.name}):{error:lr}}function ME(t){if(!t||typeof t!="object")return{error:rt};if(!t.participantId)return{error:ee};let e=t.tournamentRecord?.participants||[],r=Lo({participantId:t.participantId,tournamentParticipants:e});return r?sr({element:r,name:t.name}):{error:re}}function ip({tournamentRecords:t}){return{tournamentIds:Pt(t)?Object.keys(t):[],...R}}var jL="extensionQueries";function dt({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:Le}}return _({result:{error:rt},stack:jL})}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:Le}}var YL="activeSuspension",qc="appliedPolicies",CE="context",Um="delegatedOutcome",$n="disabled",Pm="disableLinks",nc="disableAutoCalc",sp="drawDeletions",qL="drawProfile",Dm="entryProfile",$L="eventProfile",KL="eventWithdrawalRequests",zL="factory",Qr="flightProfile",$I="groupingAttribute",Do="lineUps",la="linkedTournamentsIds",Nm="matchUpHistory",KI="participantRepresentatives",fa="personRequests",ap="positionActions",QL="rankingPoints";var ln="roundTarget",$c="scheduleLimits",Fo="scheduleTiming",ga="schedulingProfile",XL="statusDetail",oc="subOrder",qo="tally",cf="tieFormatModification",zI={ACTIVE_SUSPENSION:YL,APPLIED_POLICIES:qc,CONTEXT:CE,DELEGATED_OUTCOME:Um,DISABLED:$n,DISABLE_LINKS:Pm,DISABLE_AUTO_CALC:nc,DRAW_DELETIONS:sp,DRAW_PROFILE:qL,ENTRY_PROFILE:Dm,EVENT_PROFILE:$L,EVENT_WITHDRAWAL_REQUESTS:KL,FLIGHT_PROFILE:Qr,GROUPING_ATTRIBUTE:$I,LINEUPS:Do,LINKED_TOURNAMENTS:la,MATCHUP_HISTORY:Nm,PARTICIPANT_REPRESENTATIVES:KI,PERSON_REQUESTS:fa,POSITION_ACTIONS:ap,RANKING_POINTS:QL,ROUND_TARGET:ln,SCHEDULE_LIMITS:$c,SCHEDULE_TIMING:Fo,SCHEDULING_PROFILE:ga,STATUS_DETAIL:XL,SUB_ORDER:oc,TALLY:qo,TIE_FORMAT_MODIFICATIONS:cf,FACTORY:zL},RE=[Um,$n,Pm,Qr,Do,Nm,KI,fa,ln,$c,Fo,ga,oc,qo];function bE({tournamentRecords:t}){if(typeof t!="object"||!Object.keys(t).length)return{error:kt};let e=ip({tournamentRecords:t}),{tournamentIds:r}=e;return r?.length>1?yt({tournamentRecords:t,discover:!0,extension:{name:la,value:{tournamentIds:r}}}):{...R}}function vE({tournamentRecords:t}){if(typeof t!="object"||!Object.keys(t).length)return{error:kt};let e=sr({name:la,tournamentRecords:t,discover:!0});return _({result:e,stack:"unlinkTournaments"})}function OE({tournamentRecords:t,tournamentId:e}){if(typeof t!="object")return{error:G};if(!e)return{error:sa};let r=ip({tournamentRecords:t}),{tournamentIds:n}=r;if(!n.includes(e))return{error:sa};let o;return n.every(i=>{let s=t[i],{extension:a}=dt({element:s,name:la});if(!a)return!0;let c=a?.value?.tournamentIds||[];if(!c?.length||c.length===1&&c.includes(e)||i===e){let m=af({name:la,tournamentRecord:s});return m.error&&(o=m.error),m.success}let u=c.filter(m=>m!==e);a.value={tournamentIds:u};let p=sf({tournamentRecord:s,extension:a});return p.error&&(o=p.error),p.success}),o?{error:o}:{...R}}var xE={};Zt(xE,{getLinkedTournamentIds:()=>Kc,getTournamentIds:()=>ip});function Kc({tournamentRecords:t}){return typeof t!="object"||!Object.keys(t).length?{error:kt}:{linkedTournamentIds:Object.assign({},...Object.keys(t).map(r=>{let n=t[r],o=n?.tournamentId,{extension:i}=dt({element:n,name:la}),s=(i?.value?.tournamentIds||[]).filter(a=>a!==o);return{[r]:s}}))}}var aN={};Zt(aN,{addAdHocMatchUps:()=>hd,addDrawDefinitionTimeItem:()=>sg,addFinishingRounds:()=>Ua,addGoesTo:()=>Gi,addPlayoffStructures:()=>Rp,addQualifyingStructure:()=>QU,addVoluntaryConsolationStage:()=>KU,addVoluntaryConsolationStructure:()=>Qf,allPlayoffPositionsFilled:()=>eS,alternateDrawPositionAssignment:()=>OU,assignDrawPosition:()=>dP,assignDrawPositionBye:()=>Cr,attachConsolationStructures:()=>cP,attachPlayoffStructures:()=>mg,attachQualifyingStructure:()=>ig,attachStructures:()=>dg,autoSeeding:()=>N_,automatedPlayoffPositioning:()=>Tc,automatedPositioning:()=>Sc,checkValidEntries:()=>Ad,deleteAdHocMatchUps:()=>lP,drawMatic:()=>wd,findDrawDefinition:()=>PS,generateAdHocMatchUps:()=>Ru,generateAdHocRounds:()=>xd,generateAndPopulatePlayoffStructures:()=>Id,generateDrawDefinition:()=>La,generateDrawMaticRound:()=>Dd,generateDrawStructuresAndLinks:()=>Ed,generateDrawTypeAndModifyDrawDefinition:()=>Ud,generateQualifyingStructure:()=>cd,generateVoluntaryConsolation:()=>qS,getAssignedParticipantIds:()=>Ei,getAvailableMatchUpsCount:()=>Sd,getAvailablePlayoffProfiles:()=>Su,getDrawDefinitionTimeItem:()=>lh,getDrawParticipantRepresentativeIds:()=>ES,getDrawTypeCoercion:()=>Mu,getEligibleVoluntaryConsolationParticipants:()=>AS,getMatchUpsMap:()=>ye,getParticipantIdFinishingPositions:()=>US,getPositionAssignments:()=>Op,getPositionsPlayedOff:()=>Ac,getSeedingThresholds:()=>Yh,getSeedsCount:()=>Cu,getStructureSeedAssignments:()=>Hr,getTeamLineUp:()=>is,getValidGroupSizes:()=>Ep,isAdHoc:()=>gr,isCompletedStructure:()=>ei,isValidForQualifying:()=>kS,luckyLoserDrawPositionAssignment:()=>vU,modifyDrawDefinition:()=>uP,modifyDrawName:()=>lg,modifySeedAssignment:()=>GU,mutate:()=>IP,positionActions:()=>GS,pruneDrawDefinition:()=>mP,qualifierDrawPositionAssignment:()=>LU,query:()=>RP,removeDrawPositionAssignment:()=>Iu,removeRoundMatchUps:()=>fP,removeSeededParticipant:()=>zU,removeStructure:()=>$U,renameStructures:()=>qU,resetDrawDefinition:()=>pP,resetVoluntaryConsolationStructure:()=>JE,setDrawParticipantRepresentativeIds:()=>FE,setPositionAssignments:()=>xU,setStructureOrder:()=>YU,setSubOrder:()=>gP,shiftAdHocRounds:()=>_U,swapAdHocRounds:()=>wU,swapDrawPositionAssignments:()=>FU,updateTeamLineUp:()=>Vi,withdrawParticipantAtDrawPosition:()=>RU});var IP={};Zt(IP,{addAdHocMatchUps:()=>hd,addDrawDefinitionTimeItem:()=>sg,addPlayoffStructures:()=>Rp,addQualifyingStructure:()=>QU,addVoluntaryConsolationStage:()=>KU,addVoluntaryConsolationStructure:()=>Qf,alternateDrawPositionAssignment:()=>OU,assignDrawPosition:()=>dP,assignDrawPositionBye:()=>Cr,attachConsolationStructures:()=>cP,attachPlayoffStructures:()=>mg,attachQualifyingStructure:()=>ig,attachStructures:()=>dg,automatedPlayoffPositioning:()=>Tc,automatedPositioning:()=>Sc,deleteAdHocMatchUps:()=>lP,luckyLoserDrawPositionAssignment:()=>vU,modifyDrawDefinition:()=>uP,modifyDrawName:()=>lg,modifySeedAssignment:()=>GU,pruneDrawDefinition:()=>mP,qualifierDrawPositionAssignment:()=>LU,removeDrawPositionAssignment:()=>Iu,removeRoundMatchUps:()=>fP,removeSeededParticipant:()=>zU,removeStructure:()=>$U,renameStructures:()=>qU,resetDrawDefinition:()=>pP,resetVoluntaryConsolationStructure:()=>JE,setDrawParticipantRepresentativeIds:()=>FE,setPositionAssignments:()=>xU,setStructureOrder:()=>YU,setSubOrder:()=>gP,shiftAdHocRounds:()=>_U,swapAdHocRounds:()=>wU,swapDrawPositionAssignments:()=>FU,updateTeamLineUp:()=>Vi,withdrawParticipantAtDrawPosition:()=>RU});var LE=t=>e=>t[e],Mm=(t=[])=>t.map(fe).filter(Boolean),uf=(t=[])=>t.map(gt).filter(Boolean),gt=(t={})=>LE(t)("participantId");var fe=(t={})=>LE(t)("matchUpId"),zc=(t={})=>LE(t)("drawId");function FE({representativeParticipantIds:t,drawDefinition:e}){if(!e)return{error:dr};if(!Array.isArray(t))return{error:G};let r=uf(e?.entries||[]);return t.length&&jt(t,r).length<t.length?{error:G}:np({drawDefinition:e,extension:{name:KI,value:t}})}var Ar="ABANDONED",ic="AWAITING_RESULT",Nt="BYE",Kn="CANCELLED",me="COMPLETED",Qc="DEAD_RUBBER",bt="DEFAULTED",Ne="DOUBLE_DEFAULT",ge="DOUBLE_WALKOVER",Cn="IN_PROGRESS",Fn="INCOMPLETE",GE="NOT_PLAYED",er="RETIRED",Zi="SUSPENDED",Qt="TO_BE_PLAYED",vt="WALKOVER",PR=[ic,me,bt,Cn,Fn,er,Zi],QI=[ic,me,bt,ge,Ne,Cn,Fn,er,Zi,vt],XI=[Ar,ic,Nt,Kn,me,Qc,bt,ge,Ne,Cn,Fn,GE,er,Zi,Qt,vt],JI=[Nt,ge,Ne,me,bt,er,vt],ZI=[Ar,ic,Kn,Qc,Cn,Fn,GE,Zi,Qt,void 0],ae=[Kn,Ar,me,Qc,bt,ge,Ne,er,vt],Cm=[Ar,me,bt,ge,Ne,Cn,er,vt],th=[Cn,Fn,Zi,Qt],eh={ABANDONED:Ar,AWAITING_RESULT:ic,BYE:Nt,CANCELLED:Kn,COMPLETED:me,DEAD_RUBBER:Qc,DEFAULTED:bt,DOUBLE_WALKOVER:ge,DOUBLE_DEFAULT:Ne,IN_PROGRESS:Cn,INCOMPLETE:Fn,NOT_PLAYED:GE,RETIRED:er,SUSPENDED:Zi,TO_BE_PLAYED:Qt,WALKOVER:vt};var tt="MAIN",at="QUALIFYING",He="CONSOLATION",We="VOLUNTARY_CONSOLATION",ue="PLAY_OFF",Rm=[tt,at,He,ue,We],Ls={[at]:1,[tt]:2,[ue]:3,[He]:3,[We]:4},kE="finishingPositions",VE="aggregateEventStructures",BE={[tt]:1,[ue]:2,[He]:3,[at]:4,[We]:5},DR={[ue]:1,[tt]:2,[He]:3,[at]:4,[We]:5},Xc="CLUSTER",NR="SEPARATE",pi="WATERFALL",cp="ITEM",ke="CONTAINER",tn="DRAW",up="RANDOM",pn="TOP_DOWN",mi="BOTTOM_UP",zn="POSITION",po="WINNER",Qn="LOSER",Xn="FIRST_MATCHUP",Xr="AD_HOC",JL="AD_HOC",Ia="FEED_IN",Jc="COMPASS",Zc="OLYMPIC",ZL="SINGLE_ELIMINATION";var mo="SINGLE_ELIMINATION",tu="DOUBLE_ELIMINATION",eu="FIRST_MATCH_LOSER_CONSOLATION",pp="FIRST_ROUND_LOSER_CONSOLATION",xi="LUCKY_DRAW",pf="CURTIS_CONSOLATION",MR="CURTIS_CONSOLATION",rh="FEED_IN_CHAMPIONSHIP_TO_SF",bm="FEED_IN_CHAMPIONSHIP_TO_SF",nh="FEED_IN_CHAMPIONSHIP_TO_QF",vm="FEED_IN_CHAMPIONSHIP_TO_QF",oh="FEED_IN_CHAMPIONSHIP_TO_R16",Om="FEED_IN_CHAMPIONSHIP_TO_R16",HE="MODIFIED_FEED_IN_CHAMPIONSHIP",_m="MODIFIED_FEED_IN_CHAMPIONSHIP",mp="FEED_IN_CHAMPIONSHIP",CR="DOUBLE_ROUND_ROBIN",fn="ROUND_ROBIN",lo="ROUND_ROBIN_WITH_PLAYOFF",WE="DECIDER",jE="BACKDRAW",mf={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"}},df={0:{name:"East",abbreviation:"E"},"0-1":{name:"West",abbreviation:"W"},"0-2":{name:"North",abbreviation:"N"},"0-1-1":{name:"South",abbreviation:"S"}},Fs="WIN_RATIO",wi="ROUND_OUTCOME",YE=[Jc,pf,vm,Om,bm,mp,nh,oh,rh,eu,pp,xi,_m,Zc,ue,lo],tF=[Xr,Jc,pf,tu,vm,Om,bm,mp,Ia,eu,pp,xi,_m,Zc,ue,fn,lo,mo],qE={MAIN:tt,QUALIFYING:at,CONSOLATION:He,ITEM:cp,CONTAINER:ke,FIRST_MATCHUP:Xn,WINNER:po,LOSER:Qn,AD_HOC:Xr,FEED_IN:Ia,FLEX_ROUNDS:JL,COMPASS:Jc,PLAY_OFF:ue,OLYMPIC:Zc,KNOCKOUT:ZL,SINGLE_ELIMINATION:mo,DOUBLE_ELIMINATION:tu,CURTIS:pf,FICSF:rh,FICQF:nh,FICR16:oh,MFIC:HE,VOLUNTARY_CONSOLATION:We,FIRST_MATCH_LOSER_CONSOLATION:eu,FIRST_ROUND_LOSER_CONSOLATION:pp,MODIFIED_FEED_IN_CHAMPIONSHIP:_m,FEED_IN_CHAMPIONSHIP_TO_R16:Om,FEED_IN_CHAMPIONSHIP_TO_QF:vm,FEED_IN_CHAMPIONSHIP_TO_SF:bm,FEED_IN_CHAMPIONSHIP:mp,LUCKY_DRAW:xi,ROUND_ROBIN_WITH_PLAYOFF:lo,ROUND_ROBIN:fn,DECIDER:WE,BACKDRAW:jE,COMPASS_ATTRIBUTES:mf,OLYMPIC_ATTRIBUTES:df,DRAW:tn,RANDOM:up,TOP_DOWN:pn,BOTTOM_UP:mi,WATERFALL:pi,WIN_RATIO:Fs,ROUND_OUTCOME:wi,MULTI_STRUCTURE_DRAWS:YE,generatedDrawTypes:tF,stageOrder:Ls,finishOrder:BE,AGGREGATE_EVENT_STRUCTURES:VE,FINISHING_POSITIONS:kE},RR=qE;function di(t,e,r){let n=m=>dt({element:m,name:ln})?.extension?.value,o=r?.deprioritizeCompleted,i=r?.mode===VE&&DR,s=r?.mode===kE&&BE,a=s||i||Ls,c=m=>m?.stage===tt&&m?.stageSequence===1,u=m=>c(m)?-1:a[m?.stage],p=m=>m?.matchUps.every(({matchUpStatus:d})=>ae.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)||(lf(t)||0)-(lf(e)||0)}function lf(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(t){let e=ut(t,[{[Or]:!0,[Sm]:!0}]);if(e.error)return e;let{drawDefinition:r,structureId:n}=t,{structures:o}=Gn({drawDefinition:r}),i=o?.map(c=>c.structures?[...c.structures].concat(c):c).flat(),s=i?.find(c=>c.structureId===n);if(!s)return{error:Gt};let a=s.structureType===cp?i?.find(c=>c.structures?.some(u=>u.structureId===n)):void 0;return{structure:s,containingStructure:a}}function Gn({withStageGrouping:t,drawDefinition:e,stageSequences:r,stageSequence:n,roundTarget:o,sortConfig:i,stages:s,stage:a}){let c=!e&&X||!e?.structures&&Al||void 0;if(c)return{error:c,structures:[],stageStructures:{}};let u=f=>{let g=dt({element:f,name:ln})?.extension?.value;return!o||o===g},p=e?.structures?.filter(d).filter(l).filter(u).sort((f,g)=>di(f,g,i))??[],m=t?Object.assign({},...Rm.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 ih({drawDefinition:t}){if(!t)return{error:X};let e={};return{allPositionedParticipantIds:(t.structures||[]).map(n=>{let o=n.stage;e[o]||(e[o]=[]);let{positionAssignments:i}=Ct({structure:n}),s=i?.map(gt).filter(Boolean)??[];return e[o].push(...s),s}).flat(),stagePositionedParticipantIds:e}}function Ct({drawDefinition:t,structureId:e,structure:r}){let n,o=[];if(!r){if(!t)return{positionAssignments:o,error:X};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=>Ct({structure:i}).positionAssignments)):r.positionAssignments?o=r.positionAssignments:n=DA,{positionAssignments:o,error:n}}function de({drawDefinition:t,structureId:e,structure:r}){let n=Ct({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 ff="addDrawDefinition",dp="addMatchUps",$o="addParticipants",gf="addScaleItems",sh="addVenue",ha="audit",ah="dataIssue",If="deleteParticipants",hf="deleteVenue",Sf="deletedDrawIds",Tf="deletedMatchUpIds",yf="modifyDrawDefinition",$E="modifyDrawEntries",KE="modifyEventEntries",Af="modifyMatchUp",Xe="modifyParticipants",Ef="modifyPositionAssignments",Uf="modifySeedAssignments",zE="modifyTournamentDetail",li="modifyVenue",xm="mutations",ch="publishEvent",QE="publishEventSeeding",XE="publishOrderOfPlay",Pf="unPublishEvent",Df="unPublishEventSeeding",Nf="unPublishOrderOfPlay",lp="updateInContextMatchUp",bR={ADD_DRAW_DEFINITION:ff,ADD_MATCHUPS:dp,ADD_PARTICIPANTS:$o,ADD_SCALE_ITEMS:gf,ADD_VENUE:sh,AUDIT:ha,DATA_ISSUE:ah,DELETE_PARTICIPANTS:If,DELETE_VENUE:hf,DELETED_DRAW_IDS:Sf,DELETED_MATCHUP_IDS:Tf,MODIFY_DRAW_DEFINITION:yf,MODIFY_DRAW_ENTRIES:$E,MODIFY_EVENT_ENTRIES:KE,MODIFY_MATCHUP:Af,MODIFY_PARTICIPANTS:Xe,MODIFY_POSITION_ASSIGNMENTS:Ef,MODIFY_SEED_ASSIGNMENTS:Uf,MODIFY_TOURNAMENT_DETAIL:zE,MODIFY_VENUE:li,MUTATIONS:xm,PUBLISH_EVENT_SEEDING:QE,PUBLISH_EVENT:ch,PUBLISH_ORDER_OF_PLAY:XE,UNPUBLISH_EVENT_SEEDING:Df,UNPUBLISH_EVENT:Pf,UNPUBLISH_ORDER_OF_PLAY:Nf,UPDATE_INCONTEXT_MATCHUP:lp};function uh(t,e){if(!t)return{error:X};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 No({drawDefinition:t,tournamentId:e,matchUps:r,eventId:n}){return t&&uh(t),St({payload:{matchUps:r,tournamentId:e,eventId:n},topic:dp}),{...R}}function kn({drawDefinition:t,tournamentId:e,matchUpIds:r,eventId:n,action:o}){t&&uh(t),St({topic:Tf,payload:{tournamentId:e,matchUpIds:r,eventId:n,action:o}});for(let i of r)_I({key:i});return{...R}}function It({drawDefinition:t,tournamentId:e,structureId:r,context:n,eventId:o,matchUp:i}){return i?(t&&Ot({drawDefinition:t,structureIds:r?[r]:void 0,tournamentId:e,eventId:o}),St({topic:Af,payload:{matchUp:i,tournamentId:e,context:n},key:i.matchUpId}),{...R}):(console.log(cr),{error:cr})}function vR({tournamentId:t,inContextMatchUp:e}){return e?(St({payload:{inContextMatchUp:e,tournamentId:t},topic:lp,key:e.matchUpId}),{...R}):{error:cr}}function Sa({tournamentId:t,eventId:e,drawDefinition:r}){return r?(uh(r),St({payload:{drawDefinition:r,tournamentId:t,eventId:e},topic:ff,key:r.drawId}),{...R}):(console.log(X),{error:X})}function OR({tournamentId:t,eventId:e,drawId:r}){return St({payload:{drawId:r,tournamentId:t,eventId:e},topic:Sf,key:r}),_I({key:r}),{...R}}function Ot({drawDefinition:t,tournamentId:e,structureIds:r,eventId:n}){return t?(uh(t,r),St({payload:{tournamentId:e,eventId:n,drawDefinition:t},topic:yf,key:t.drawId}),{...R}):{error:X}}function ph({drawDefinition:t,tournamentId:e,structure:r,eventId:n}){if(!t)return{error:X};if(!r)return{error:Oo};let o=r.seedAssignments,i=r.structureId,s=t.drawId;return St({payload:{tournamentId:e,eventId:n,drawId:s,structureId:i,seedAssignments:o},topic:Uf,key:t.drawId}),Ot({structureIds:[i],drawDefinition:t,tournamentId:e,eventId:n}),{...R}}function Mo({drawDefinition:t,tournamentId:e,structure:r,event:n}){if(!t)return{error:X};if(!r)return{error:Oo};let o=Ct({structure:r}),i=r.structureId,s=t.drawId,a=n?.eventId;return St({topic:Ef,payload:{positionAssignments:o,tournamentId:e,structureId:i,eventId:a,drawId:s},key:i}),Ot({structureIds:[i],drawDefinition:t,tournamentId:e,eventId:a}),{...R}}function JE({tournamentRecord:t,drawDefinition:e,resetEntries:r,event:n}){if(!e)return{error:X};let o=e.structures?.find(s=>s.stage===We);if(!o)return{error:Gt};let i=o.matchUps?.map(({matchUpId:s})=>s)||[];return o.positionAssignments=[],o.seedAssignments=[],o.matchUps=[],kn({tournamentId:t?.tournamentId,action:"resetVoluntaryConsolationStructure",matchUpIds:i,drawDefinition:e}),r&&(e.entries=e.entries.filter(s=>s.entryStage!==We)),Ot({tournamentId:t?.tournamentId,eventId:n?.eventId,drawDefinition:e,structureIds:[o.structureId]}),{...R}}function wm({drawPositions:t,structure:e}){if([at,tt].includes(e.stage)&&e.stageSequence===1)return;let{positionAssignments:r}=Ct({structure:e});r?.filter(({drawPosition:o})=>t?.includes(o))?.forEach(o=>{yt({element:o,extension:{name:Pm,value:!0}})})}function ru(t){let{appliedPolicies:e,positionAction:r,drawDefinition:n}=t;if(e?.audit?.[ap]===!1)return;let{extension:o}=dt({name:ap,element:n}),i=Array.isArray(o?.value)?o?.value??[]:[];if(!i?.length){let a=n.structures.find(c=>c.stage===tt);if(a){let c=Ct({structure:a}).positionAssignments?.map(({drawPosition:u,participantId:p,bye:m,qualifier:d})=>({drawPosition:u,participantId:p,qualifier:d,bye:m}));i.push({name:"initialMainAssignments",initialAssignments:c})}}let s={value:i.concat(r),name:ap};yt({element:n,extension:s})}function ts({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 Ta="SINGLES",Kt="SINGLES",Li="DOUBLES",wt="DOUBLES",gn="TEAM",Bt="TEAM",_R={SINGLES_MATCHUP:Ta,SINGLES:Kt,DOUBLES_MATCHUP:Li,DOUBLES:wt,TEAM_MATCHUP:gn,TEAM:Bt};function nu(t){let{sides:e,matchUpType:r}=t||{},n=t.potentialParticipants?.length?t.potentialParticipants.flat().map(s=>r===wt?s?.individualParticipantIds||[]:s.participantId).flat():[],o=(e||[]).map(s=>r===wt&&(s?.participant?.individualParticipantIds||[])||s?.participantId&&[s.participantId]||[]).flat();return{individualParticipantIds:o.concat(n).flat(),enteredIndividualParticipantIds:o,potentialIndividualParticipantIds:n}}function en(t){return t?.tournamentRecords??(t?.tournamentRecord&&{[t.tournamentRecord.tournamentId]:t.tournamentRecord})??{}}var sc="SIGN_IN_STATUS",ZE="SIGNED_OUT",ou="SIGNED_IN",rn="TEAM",Tt="INDIVIDUAL",Er="GROUP",lt="PAIR",xt="TEAM",iu={TEAM_PARTICIPANT:rn,INDIVIDUAL:Tt,GROUP:Er,TEAM:xt,PAIR:lt},xR={INDIVIDUAL:Tt,GROUP:Er,PAIR:lt,TEAM:xt,SIGN_IN_STATUS:sc,SIGNED_OUT:ZE,SIGNED_IN:ou};function Lm({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===xt),s=o.filter(c=>c.participantType===Er),a=o.filter(c=>c.participantType===lt);return o.forEach(c=>{if(c.participantType===Tt){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 tU(t){return t&&typeof String.fromCodePoint<"u"?t.toUpperCase().replace(/./g,e=>String.fromCodePoint(e.charCodeAt(0)+127397)):t}function wR(t){let e=Object.assign({},...Ko.filter(r=>r.ioc).map(r=>({[r.ioc]:r.iso})));return tU(e[t])}var Ko=[{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=Ko.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 LR({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?_i({template:e,source:s}):s)}}}}function fo(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:re}}function dh(t){let{tournamentRecord:e,participantId:r}=t;if(r){let o=fo({tournamentRecord:e,participantId:r});return o.participant??o}let n=t.element||t.drawDefinition||t.event||t.tournamentRecord;return n||{error:rt}}function Vn(t){let{returnPreviousValues:e,itemSubTypes:r,itemType:n}=t,o=dh(t);if(o.error)return o;if(r&&!Array.isArray(r))return{error:G,context:{itemSubTypes:r}};if(!Array.isArray(o.timeItems))return{error:Fl};let i=o.timeItems.filter(a=>a?.itemType===n).filter(a=>!r?.length||r.some(c=>a?.itemSubTypes?.includes(c))).sort((a,c)=>{let u=new Date(a.createdAt||void 0).getTime(),p=new Date(c.createdAt||void 0).getTime();return u-p}),s=i.pop();if(s){let a={timeItem:s,...R};return e&&Object.assign(a,{previousItems:i}),a}else return{info:Le}}function lh({returnPreviousValues:t,drawDefinition:e,itemSubTypes:r,itemType:n}){if(!e)return{error:$r};if(!e.timeItems)return{info:Le};let{timeItem:o,previousItems:i,info:s}=Vn({element:e,returnPreviousValues:t,itemSubTypes:r,itemType:n});return o&&{timeItem:o,previousItems:i}||{info:s}}function su({returnPreviousValues:t,itemSubTypes:e,itemType:r,event:n}){if(!n)return{error:Dt};if(!n.timeItems)return{info:Le};let{timeItem:o,previousItems:i,info:s}=Vn({returnPreviousValues:t,element:n,itemSubTypes:e,itemType:r});return o&&{timeItem:o,previousItems:i}||{info:s}}function au({returnPreviousValues:t,tournamentRecord:e,itemSubTypes:r,itemType:n}){if(!e)return{error:j};if(!e.timeItems)return{info:Le};let{timeItem:o,previousItems:i,info:s}=Vn({element:e,returnPreviousValues:t,itemSubTypes:r,itemType:n});return o&&{timeItem:o,previousItems:i}||{info:s}}function fh({returnPreviousValues:t,tournamentRecord:e,participantId:r,itemSubTypes:n,itemType:o}){if(!e)return{error:j};if(!r)return{error:ee};let i=fo({tournamentRecord:e,participantId:r});if(i.error)return i;let{participant:s}=i;if(!s?.timeItems)return{info:Le};let{timeItem:a,previousItems:c,info:u}=Vn({element:i.participant,returnPreviousValues:t,itemSubTypes:n,itemType:o});return a&&{timeItem:a,previousItems:c}||{info:u}}var eF={[Er]:"groupParticipantIds",[lt]:"pairParticipantIds",[xt]:"teamParticipantIds"},rF={[Er]:"groups",[xt]:"teams"};function gh({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&&iF({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&&oF({individualParticipantIds:d,participantCopy:p,participantMap:c,participantType:l,participantId:m}),n&&(c[m].participant.signedIn=nF(p)),o){let{ratings:f,rankings:g,seedings:I}=pa({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=Pt(t)?t:void 0;LR({participantMap:c,template:u})}return{participantMap:c}}function nF(t){let{timeItem:e}=Vn({itemType:sc,element:t});return e?.itemValue===ou}function oF({individualParticipantIds:t,participantCopy:e,participantMap:r,participantType:n,participantId:o}){for(let i of t){let s=r[i].participant;if(s[eF[n]].push(o),[xt,Er].includes(n)){let{participantRoleResponsibilities:a,participantOtherName:c,participantName:u,participantId:p,teamId:m}=e,d=rF[n];s[d].push({participantRoleResponsibilities:a,participantOtherName:c,participantName:u,participantId:p,teamId:m})}if(n===lt){let a=t.find(c=>c!==i);r[i].pairIdMap[o]=a,r[i].pairIdMap[a]=o}}}function iF({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:{[Kt]:{...r},[wt]:{...r},[xt]:{...r},...r}}}function fi({participantsProfile:t,useParticipantMap:e,tournamentRecord:r,contextProfile:n,inContext:o}){if(e)return{participantMap:gh({...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}=Lm({participantsProfile:t,deepCopy:!1,participants:i})),t?.withScaleValues&&i?.length)for(let a of i){let{ratings:c,rankings:u}=pa({participant:a});a.rankings=u,a.ratings=c}return{participants:i,groupInfo:s}}function ht({onlySpecifiedPolicyTypes:t=!1,policyTypes:e=[],tournamentRecord:r,drawDefinition:n,structure:o,event:i}){if(!Array.isArray(e))return{error:yI};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===qc)?.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 Co({policyTypes:t=[],tournamentRecord:e,drawDefinition:r,structure:n,event:o}){if(!Array.isArray(t))return{error:yI};let{appliedPolicies:i}=ht({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:Fc.message}}var Ih="WALKOVER",eU="RETIRED",Fm="COMPETITIVE",ac="ROUTINE",cc="DECISIVE",Gm="winRatio";var sF={[ui]:{policyName:"Competitive Bands Default",profileBands:{[cc]:20,[ac]:50}}},km=sF;function Bn({policyDefinitions:t,tournamentRecord:e,contextProfile:r,drawDefinition:n,event:o}){let i={policies:{}};if(!r)return i;let s=Co({tournamentRecord:e,drawDefinition:n,event:o}).policyDefinitions;if(r.withCompetitiveness){let a=t?.[ui]??s?.[ui]??km[ui];i.policies[ui]=a}return i}function zo({tournamentRecord:t,drawDefinition:e,policyType:r,structure:n,event:o}){if(!t)return{error:j};let{appliedPolicies:i}=ht({tournamentRecord:t,drawDefinition:e,structure:n,event:o});return i?.[r]?{policy:i[r]}:{info:Fc?.message}}function ya({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}=zo({policyType:Uo,tournamentRecord:t,event:n}),s=(t?dt({element:t,name:Fo}).extension:void 0)?.value,c=(n&&dt({name:Fo,element:n}).extension)?.value;return{scheduleTiming:{tournamentScheduling:s,eventScheduling:c,categoryName:e,categoryType:r,policy:o}}}function Mf({drawDefinition:t,attributes:e}){let{extension:r}=dt({element:t,name:Dm}),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:Dm,value:n},np({drawDefinition:t,extension:r}),{entryProfile:n}}function cu({drawDefinition:t}){let{extension:e}=dt({element:t,name:Dm});return{entryProfile:e?.value||{}}}var kr="ALTERNATE",Cf="CONFIRMED",Vr="DIRECT_ACCEPTANCE",Vm="FEED_IN",Rf="JUNIOR_EXEMPT",es="LUCKY_LOSER",bf="ORGANISER_ACCEPTANCE",Bm="QUALIFIER",aF="REGISTERED",vf="SPECIAL_EXEMPT",Br="UNGROUPED",gi="UNPAIRED",uu="WILDCARD",Jn="WITHDRAWN",Of=[Cf,Vr,Rf,bf,vf],rU=[Vm,es,Bm],Qo=[Cf,Vr,Vm,Rf,bf,vf,uu],wr=[Cf,Vr,Rf,es,Bm,bf,vf,uu],nU=[kr,Cf,Vr,Vm,Rf,es,bf,Bm,aF,vf,Br,gi,uu,Jn],FR={ALTERNATE:kr,CONFIRMED:Cf,DIRECT_ACCEPTANCE:Vr,DIRECT_ENTRY_STATUSES:Qo,DRAW_SPECIFIC_STATUSES:rU,EQUIVALENT_ACCEPTANCE_STATUSES:Of,FEED_IN:Vm,JUNIOR_EXEMPT:Rf,LUCKY_LOSER:es,ORGANISER_ACCEPTANCE:bf,QUALIFIER:Bm,SPECIAL_EXEMPT:vf,STRUCTURE_SELECTED_STATUSES:wr,UNGROUPED:Br,UNPAIRED:gi,VALID_ENTRY_STATUSES:nU,WILDCARD:uu,WITHDRAWN:Jn};function _f({stage:t,drawDefinition:e}){let{entryProfile:r}=cu({drawDefinition:e}),n=Object.keys(r).includes(t);if(!n&&Rm.includes(t)){let o=[{[t]:{drawSize:void 0,alternates:!0}}];return Mf({drawDefinition:e,attributes:o}),!0}return n}function GR({stage:t,drawDefinition:e}){let{entryProfile:r}=cu({drawDefinition:e});return r[t]?.alternates||0}function kR({stage:t,drawDefinition:e}){let{entryProfile:r}=cu({drawDefinition:e});return r[t]?.wildcardsCount||0}function hh({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=dt({name:ln,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===ue){let{playoffEntries:p,error:m}=cF({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 cF({provisionalPositioning:t,drawDefinition:e,structureId:r}){let n=[],o=(e.links??[]).find(i=>i.linkType===zn&&i.target.structureId===r);if(o){let{finishingPositions:i,structureId:s}=o.source,{structure:a}=st({drawDefinition:e,structureId:s});a?.structureType===ke&&(a.structures??[]).forEach(u=>{let p=u.positionAssignments??[],{structureId:m}=u,d=m,l=Object.assign({},...p.map(h=>{let{participantId:S}=h,T=dt({element:h,name:qo}).extension?.value;return T&&S?{[S]:T}:void 0}).filter(Boolean)),g=Object.keys(l).reduce((h,S)=>{let T=l[S],y=T.groupOrder||t&&T.provisionalOrder;return h.includes(y)||h.push(y),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:y,GEMscore:N}=S,E=T||t&&y,A=[...i??[]].sort(se).indexOf(E)+1;n.push({entryStage:ue,entryStatus:Vm,placementGroup:A,groupingValue:d,participantId:h,GEMscore:N})})})}return{playoffEntries:n}}function VR({stage:t,drawDefinition:e}){return Qo.reduce((r,n)=>(hh({drawDefinition:e,entryStatus:n,stage:t})||0)+r,0)}function Hr({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=Ct({structure:o}).positionAssignments;if(i||!o)return{seedAssignments:[],error:Gt};n||(n=o.structureId);let{stage:c,stageSequence:u}=o,m=c===ue&&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=IA;let f=o.seedLimit??o?.positionAssignments?.length;return{seedAssignments:s,stageSequence:u,seedLimit:f,stage:c,error:i}}var uF=(t,e)=>(t||0)+(e||0);function Sh(t,e){let r=Array.isArray(t)?t[0]:t;return isNaN(r)&&Ih||r<=e[cc]&&cc||r<=e[ac]&&ac||Fm}function Th({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(uF)&&(r[n[0]>n[1]?0:1]+=1),{sets:e,games:r,score:t}}function pF(t){let e=Math.min(...t.games),r=Math.max(...t.games);return Math.round(e/r*100)}function yh(t){return t.map(pF).sort().map(e=>parseFloat(e.toFixed(2)))}function pu({tournamentRecord:t,profileBands:e,matchUp:r}){if(!r)return{error:cr};let{score:n,winningSide:o}=r;if(!o)return{error:G};let i=!e&&t&&zo({policyType:ui,tournamentRecord:t}).policy,s=e||i?.profileBands||km[ui].profileBands,a=Th({score:n}),c=yh([a]),u=Sh(c,s),p=Array.isArray(c)?c[0]:c;return{...R,competitiveness:u,pctSpread:p}}function Ah({matchUp:t}){if(!t)return{error:cr};if(t&&!t.sides)return{error:Ze};if(t&&!t.hasContext)return{error:kc};let e=(t.sides??[])?.map(a=>a?.participantId).filter(Boolean),r=t.sides?.filter(a=>a.participant?.participantType===Tt).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=pt(i.concat(e)).filter(Boolean)??[];return{nestedIndividualParticipantIds:o,allRelevantParticipantIds:s,individualParticipantIds:i,sideParticipantIds:e,...R}}var Hm="CHECK_IN",Wm="CHECK_OUT",BR="SCHEDULE",Gs="SCHEDULE.ASSIGNMENT.VENUE",Ro="SCHEDULE.ALLOCATION.COURTS",hi="SCHEDULE.ASSIGNMENT.COURT",xf="SCHEDULE.COURT.ORDER",ks="SCHEDULE.DATE",mF="COMPLETED.DATE",Eh="HOME_PARTICIPANT_ID",oU="SCHEDULE.ASSIGN.OFFICIAL",Vs="SCHEDULE.TIME.SCHEDULED",bo="SCHEDULE.TIME.START",Fi="SCHEDULE.TIME.STOP",Si="SCHEDULE.TIME.RESUME",Ti="SCHEDULE.TIME.END",wf="SCHEDULE.TIME.MODIFIERS",HR="TO_BE_ANNOUNCED",WR="NEXT_AVAILABLE",jR="FOLLOWED_BY",YR="AFTER_REST",qR="RAIN_DELAY",dF="NOT_BEFORE",Uh=[HR,WR,jR,YR,qR],lF="ELIGIBILITY",fF="REGISTRATION",gF="SUSPENSION",IF="MEDICAL",hF="PENALTY",iU="SCALE",sU="RATING",aU="RANKING",Lf="SEEDING",Xo="PUBLISH",Wr="PUBLIC",Jo="STATUS",SF="MODIFICATION",TF="RETRIEVAL",yF="other",$R={MUTUALLY_EXCLUSIVE_TIME_MODIFIERS:Uh,AFTER_REST:YR,ALLOCATE_COURTS:Ro,ASSIGN_COURT:hi,ASSIGN_OFFICIAL:oU,ASSIGN_VENUE:Gs,CHECK_IN:Hm,CHECK_OUT:Wm,COMPLETED_DATE:mF,COURT_ORDER:xf,ELIGIBILITY:lF,END_TIME:Ti,FOLLOWED_BY:jR,MEDICAL:IF,MODIFICATION:SF,NEXT_AVAILABLE:WR,NOT_BEFORE:dF,OTHER:yF,PENALTY:hF,PUBLIC:Wr,PUBLISH:Xo,RANKING:aU,RATING:sU,RAIN_DELAY:qR,REGISTRATION:fF,RESUME_TIME:Si,RETRIEVAL:TF,SCALE:iU,SCHEDULE:BR,SCHEDULED_DATE:ks,SCHEDULED_TIME:Vs,SEEDING:Lf,START_TIME:bo,STATUS:Jo,STOP_TIME:Fi,SUSPENSION:gF,TIME_MODIFIERS:wf,TO_BE_ANNOUNCED:HR};function rs({matchUp:t}){if(!t)return{error:cr};if(!t.hasContext)return{error:kc};if(!t.sides||t.sides.filter(Boolean).length!==2)return{error:Ze};let{nestedIndividualParticipantIds:e,allRelevantParticipantIds:r,sideParticipantIds:n}=Ah({matchUp:t}),i=(t.timeItems??[]).filter(u=>u?.itemType&&[Hm,Wm].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===Hm);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}}var Ph={[Kt]:[Kt,"S"],[wt]:[wt,"D"],[Bt]:[Bt,"T"],S:[Kt,"S"],D:[wt,"D"],T:[Bt,"T"]};var ie=t=>e=>{let r=Pt(e)&&e?.matchUpType||Re(e)&&e;return r&&Ph[t].includes(r)};function fp(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 gp(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 Dh({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 KR({tournamentScheduling:t,eventScheduling:e,averageMinutes:r,defaultTiming:n,matchUpFormat:o,categoryName:i,categoryType:s,policy:a}){let c=e?.matchUpRecoveryTimes&&gp({...e,averageMinutes:r,matchUpFormat:o}),u=t?.matchUpRecoveryTimes&&gp({...t,averageMinutes:r,matchUpFormat:o}),p=a?.matchUpRecoveryTimes&&gp({...a,averageMinutes:r,matchUpFormat:o}),m=[c,u,p,a?.defaultTimes?.recoveryTimes,n?.recoveryTimes];return Dh({categoryName:i,categoryType:s,timesBlockArray:m})}function zR({matchUpFormat:t,categoryName:e,categoryType:r,defaultTiming:n,tournamentScheduling:o,eventScheduling:i,policy:s}){let a=i?.matchUpAverageTimes&&fp({...i,matchUpFormat:t}),c=o?.matchUpAverageTimes&&fp({...o,matchUpFormat:t}),u=s?.matchUpAverageTimes&&fp({...s,matchUpFormat:t}),p=[a,c,u,s?.defaultTimes?.averageTimes,n?.averageTimes];return Dh({categoryName:e,categoryType:r,timesBlockArray:p})}var cU="DOUBLES_SINGLES",uU="SINGLES_DOUBLES",Zn="total",Nh="participantConflict",Aa="matchUpConflict",pU="ISSUE_IDS",uc="CONFLICT",pc="WARNING",Mh="ERROR",Ch="ISSUE",Ff="STATE",QR={SINGLES_DOUBLES:uU,DOUBLES_SINGLES:cU,TOTAL:Zn,CONFLICT_MATCHUP_ORDER:Aa,CONFLICT_PARTICIPANTS:Nh,SCHEDULE_ISSUE_IDS:pU,SCHEDULE_CONFLICT:uc,SCHEDULE_WARNING:pc,SCHEDULE_ERROR:Mh,SCHEDULE_ISSUE:Ch,SCHEDULE_STATE:Ff};var go="SINGLES",Bs="SINGLES",Jr="DOUBLES",yi="DOUBLES",Ve="TEAM",jr="TEAM",AF="AGE",EF="RATING",UF="BOTH",XR={AGE:AF,BOTH:UF,DOUBLES:Jr,DOUBLES_EVENT:yi,RATING:EF,SINGLES:go,SINGLES_EVENT:Bs,TEAM_EVENT:jr,TEAM:Ve};function mu({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??Bs;let c={averageTimes:[{minutes:{default:t}}],recoveryTimes:[{minutes:{default:e}}]},{scheduleTiming:u}=ya({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=zR(t),n=Object.keys(r?.minutes||{}),o=r?.minutes&&(n?.includes(e)&&r.minutes[e]||r.minutes.default),i=KR({...t,averageMinutes:o}),s=Object.keys(i?.minutes||{}),a=i?.minutes&&(s?.includes(e)&&i.minutes[e]||i.minutes.default),c=ie(Bs)(e)?uU:cU,u=i?.minutes&&(s?.includes(c)&&i.minutes[c]||a);return{averageMinutes:o,recoveryMinutes:a,typeChangeRecoveryMinutes:u}}function Rh(t){return t.createdAt?new Date(t.createdAt).getTime():0}function Io({visibilityThreshold:t,timeItems:e,itemType:r}){let n=e.filter(i=>i&&i.itemType===r&&(!t||Rh(i)<new Date(t).getTime())).sort((i,s)=>Rh(i)-Rh(s)).pop(),o=n&&Rh(n);return{itemValue:n?.itemValue,timeStamp:o}}function Gf({visibilityThreshold:t,timeStamp:e,schedule:r,matchUp:n}){let{itemValue:o,timeStamp:i}=Io({timeItems:n?.timeItems||[],itemType:Vs,visibilityThreshold:t});return!r||i&&e&&new Date(i).getTime()>new Date(e).getTime()?{scheduledTime:o}:r}function ns({visibilityThreshold:t,timeStamp:e,schedule:r,matchUp:n}){let{itemValue:o,timeStamp:i}=Io({timeItems:n?.timeItems||[],itemType:ks,visibilityThreshold:t});return!r||i&&e&&new Date(i).getTime()>new Date(e).getTime()?{scheduledDate:o}:r}function bh({visibilityThreshold:t,timeStamp:e,schedule:r,matchUp:n}){let{itemValue:o,timeStamp:i}=Io({timeItems:n?.timeItems||[],itemType:Ro,visibilityThreshold:t});return!r||i&&e&&new Date(i).getTime()>new Date(e).getTime()?{allocatedCourts:J(o,!1,!0)}:r}function vh({visibilityThreshold:t,timeStamp:e,schedule:r,matchUp:n}){let{itemValue:o,timeStamp:i}=Io({timeItems:n?.timeItems||[],itemType:hi,visibilityThreshold:t});return!r||i&&e&&new Date(i).getTime()>new Date(e).getTime()?{courtId:o}:r}function Oh({visibilityThreshold:t,timeStamp:e,schedule:r,matchUp:n}){let{itemValue:o,timeStamp:i}=Io({timeItems:n?.timeItems||[],itemType:Gs,visibilityThreshold:t});return!r||i&&e&&new Date(i).getTime()>new Date(e).getTime()?{venueId:o}:r}function kf({visibilityThreshold:t,timeStamp:e,schedule:r,matchUp:n}){let{itemValue:o,timeStamp:i}=Io({timeItems:n?.timeItems||[],itemType:wf,visibilityThreshold:t});return!r||i&&e&&new Date(i).getTime()>new Date(e).getTime()?{timeModifiers:o}:r}function hp(t){if(BI.test(t)){let e=tf();return new Date(`${e}T${t}`)}else return new Date(t)}function JR({matchUp:t}){if(!t)return{error:cr};if(!t.timeItems)return{error:Fl};let e=t.timeItems.filter(n=>[bo,Fi,Si,Ti].includes(n?.itemType)).sort((n,o)=>hp(n.itemValue).getTime()-hp(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 bo:i=0;break;case Ti:if(n.lastValue&&[bo,Si].includes(n.lastType)){let u=hp(o.itemValue).getTime()-hp(n.lastValue).getTime();i=n.milliseconds+u}else i=n.milliseconds;break;case Fi:if([bo,"SCHECULE.TIME.RESUME"].includes(n.lastType)){let u=hp(o.itemValue).getTime()-hp(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([bo,Si].includes(r.lastType)){let n=new Date().getTime()-hp(r.lastValue).getTime();r.milliseconds+=n}return{milliseconds:r.milliseconds,time:PF(r.milliseconds),relevantTimeItems:e}}function PF(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 ZR({visibilityThreshold:t,timeStamp:e,schedule:r,matchUp:n}){let{itemValue:o,timeStamp:i}=Io({timeItems:n?.timeItems||[],itemType:xf,visibilityThreshold:t});return!r||i&&e&&new Date(i).getTime()>new Date(e).getTime()?{courtOrder:o}:r}function tb({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===bo&&s;return a&&(!i||r(a)<r(i))?a:i},void 0)?.itemValue}}function eb(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 mc(t){let{disableNotice:e,venue:r,context:n}=t;if(typeof r!="object")return{error:G};let o=en(t);r.venueId||(r.venueId=Mt());let i;for(let s of Object.values(o)){let a=DF({disableNotice:!0,tournamentRecord:s,context:n,venue:r});if(a?.error)return a;i=a.venue}return e||St({topic:sh,payload:{venue:r}}),nt({...R,venue:i})}function DF({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:zA}:(r&&yt({element:n,extension:{value:r,name:CE}}),t.venues.push(n),e||St({payload:{venue:n,tournamentId:t.tournamentId},topic:sh}),{...R,venue:J(n)})):{error:rt,info:"missing venue"}:{error:j}}function Zo({tournamentRecords:t,tournamentRecord:e,venueId:r}){if(!e)return{error:j};if(!r)return{error:jo};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=Zo({tournamentRecord:c,venueId:r});if(u.success&&u.venue)return mc({tournamentRecord:e,venue:u.venue}),{...R,venue:o}}}return o?{...R,venue:o}:{error:bs}}function _h({convertExtensions:t,...e}){let{tournamentRecords:r,tournamentRecord:n,venueId:o}=e,i=Zo({tournamentRecords:r,tournamentRecord:n,venueId:o});return J(i,t,!0)}function os({tournamentRecords:t,tournamentRecord:e,courtId:r}){if(!e)return{error:j};if(!r)return{error:bi};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=os({tournamentRecord:u,courtId:r});if(p.success)return p.venue&&mc({tournamentRecord:e,venue:p.venue}),{...R,court:o,venue:i}}}return _({result:{error:za},stack:n})}function mU(t){return J(os(t),!1,!0)}function jm({tournamentRecord:t,internalUse:e,courtId:r}){if(!t)return{error:j};if(!r)return{error:bi};let n=os({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 dc({tournamentRecord:t,venueId:e}){if(!t)return{error:j};if(!e)return{error:jo};let r=Zo({tournamentRecord:t,venueId:e});if(r.error)return r;let o=(r.venue?.courts??[]).map(a=>(({courtInfo:c})=>({...c}))(jm({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 rb({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===Ti&&s;return a&&(!i||r(a)>r(i))?a:i},void 0)?.itemValue}}function Ht({event:t,eventId:e}){if(!t)return{error:Dt};let n=dt({name:Qr,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 je(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&&Ht({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,..._({result:{error:lr},stack:o})};return{event:u,drawDefinition:void 0,tournamentId:c}}return{event:void 0,drawDefinition:void 0,..._({result:{error:dr},context:{drawId:n,eventId:r},stack:o})}}function Ym(t){let{visibilityThreshold:e,timeStamp:r,schedule:n,matchUp:o}=t,i=ut(t,[{[Un]:!0}]);if(i.error)return i;let{itemValue:s,timeStamp:a}=Io({timeItems:o?.timeItems||[],itemType:Eh,visibilityThreshold:e});return!n||a&&r&&new Date(a).getTime()>new Date(r).getTime()?{homeParticipantId:s}:n}function qm(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:cr};if(o&&!p.matchUpType&&!t.matchUpType&&(e||i)&&p.drawId){let A=e?.drawDefinitions?.find(C=>C.drawId===p.drawId);!A&&i&&({drawDefinition:A,event:e}=je({tournamentRecord:i,drawId:p.drawId}));let U=p.structureId&&A?.structures?.find(({structureId:C})=>C===p.structureId);r=t.matchUpType||U?.matchUpType||A?.matchUpType||e?.eventType!==Ve&&e?.eventType}let{milliseconds:m,time:d}=JR({matchUp:p}),{startTime:l}=tb({matchUp:p}),{endTime:f}=rb({matchUp:p}),g,{visibilityThreshold:I,eventIds:h,drawIds:S}=n??{};if((!h||h.includes(p.eventId))&&(!S||S.includes(p.drawId))){let A={matchUp:p,visibilityThreshold:I},{allocatedCourts:U}=bh(A),{homeParticipantId:C}=Ym(A),{scheduledTime:P}=Gf(A),{timeModifiers:D}=kf(A),{scheduledDate:M}=ns(A),{venueId:b}=Oh(A),{courtId:v}=vh(A),{courtOrder:O}=ZR(A),w,F,L,x,B,H=p.matchUpType??r;if(a&&P&&o&&H){let et={matchUpFormat:p.matchUpFormat??c,...a};({averageMinutes:F=0,recoveryMinutes:L=0,typeChangeRecoveryMinutes:x=0}=Ip({timingDetails:et,eventType:H})),(F||L)&&(w=f?xr($t(f),L):xr(P,F+L)),x&&(B=f?xr($t(f),x):xr(P,F+x))}!M&&P&&(M=Ut(P));let W=Am({scheduledDate:M,scheduledTime:P}),V={},Y=(i&&b&&dc({tournamentRecord:i,venueId:b}))?.venueData||{};b&&(V[b]=Y);let{venueName:$,venueAbbreviation:k,courtsInfo:K}=Y,q=(v&&K?.find(et=>et.courtId===v))?.courtName;for(let et of U||[]){if(!i)break;et.venueId&&!V[et.venueid]&&(V[et.venueId]=dc({venueId:et.venueId,tournamentRecord:i})?.venueData);let Q=V[et.venueId];et.venueName=Q?.venueName;let it=Q?.courtsInfo?.find(ot=>ot.courtId===et.courtId);et.courtName=it?.courtName}g=nt({typeChangeTimeAfterRecovery:B,timeAfterRecovery:w,scheduledDate:M,scheduledTime:P,isoDateString:W,allocatedCourts:U,homeParticipantId:C,timeModifiers:D,venueAbbreviation:k,venueName:$,venueId:b,courtOrder:O,courtName:q,courtId:v,typeChangeRecoveryMinutes:x,recoveryMinutes:L,averageMinutes:F,milliseconds:m,startTime:l,endTime:f,time:d})}else g=nt({milliseconds:m,startTime:l,endTime:f,time:d});let{scheduledDate:T}=ns({matchUp:p}),{scheduledTime:y}=Gf({matchUp:p});if(s&&u?.displaySettings?.draws){let A=u.displaySettings.draws,U=(A?.[p.drawId]??A?.default)?.scheduleDetails;if(U){let C=(U.find(P=>T&&P.dates?.includes(T))??U.find(P=>!P.dates?.length))?.attributes;if(C){let P=Object.assign({},...Object.keys(g).map(D=>({[D]:!0})),C);g=_i({source:g,template:P})}}}let E=p.matchUpStatus&&ae.includes(p.matchUpStatus)&&(Ut(f)||Ut(T)||Ut(y))||void 0;return{schedule:g,endDate:E}}function Hs(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 Sp({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 Ye({drawDefinition:t,structure:e,matchUp:r,event:n}){return{tieFormat:Sp({item:r,drawDefinition:t,structure:e,event:n})||Sp({item:e,drawDefinition:t,structure:e,event:n})||Hs(t)||Hs(n)}}function nb({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 ye({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 ti({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)}function xh({groupedOrder:t,roundPositionsCount:e}){if(!t||t?.length<=e)return t;let n=Te(t,t.length/e).map(i=>i.reduce((s,a)=>s+a)),o=n.slice().sort(se);return n.map(i=>o.indexOf(i)+1)}function Vf(t){if(!Pt(t))return!1;let{matchUpId:e,drawPositions:r}=t,n=typeof e=="string",o=!r||Array.isArray(r)&&r.length<=2&&r.every(i=>ft(i)||i===void 0||i===null);return n&&o}function Nr(t){return Array.isArray(t)?t.every(Vf):!1}function qe({matchUps:t=[],interpolate:e}){if(!Nr(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(se).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)=>se(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]=nt({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&&En(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=>!ae.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(se),I=Te(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=Te(I,h),T=l.map(y=>{let{roundPosition:N}=y,E=[...y.drawPositions||[],void 0,void 0].slice(0,2);if(!N)return E;let A=E?.filter(Boolean)||[];if(!A?.length)return[void 0,void 0];if(d<3&&A?.length===2)return E?.slice().sort(se);let U=jt(I,A).length!==A?.length;if(A?.length&&U)return A?.length===1?[A[0],void 0]:E?.slice().sort(se);let C=(N-1)*2;return S.slice(C,C+2).map(D=>A?.find(M=>D.includes(M)))});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})=>!En(d));return{hasNoRoundPositions:t.some(d=>!d.roundPosition),roundsNotPowerOf2:p,maxMatchUpsCount:i,roundMatchUps:o,roundNumbers:u,roundProfile:s,...R}}function $m(t){if(!Array.isArray(t))return"";let e=t.filter(Jt);return e.length?pt([Math.min(...e),Math.max(...e)]).join("-"):""}function ob({drawDefinition:t,structureId:e,matchUpsMap:r}){if(!t)return{error:X};if(!e)return{error:Sr};let{structure:n}=st({drawDefinition:t,structureId:e});if(n?.stage!==He)return{error:Ri,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=ti({structureId:m,matchUpsMap:r}),f=qe({matchUps:d}).roundProfile;return{[m]:f}})),c=ti({matchUpsMap:r,structureId:e}),{roundProfile:u}=qe({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,N=S[l]?.matchUpsCount;if(!N)return;let E=N?T.length/N:0,A=T.length/E,U=T.slice(),C=xh({roundPositionsCount:A,groupedOrder:g}),P=C?.length||1;if(P<=A){let v=T.length/P,O=Te(U,v);f===mi&&O.forEach(w=>w.reverse()),U=C?.length&&C?.map(w=>O[w-1]).flat()||U}let D=Te(U,E);if(I){let v=Z(0,I.interleave).map(()=>{}),O=Z(0,I.offset).map(()=>{});D=D.map(F=>[F,...v]),D.unshift(O),D=D.flat(1);let w=D.length-I.offset;D=D.slice(0,w)}p[h]||(p[h]={});let b=u?.[h]?.feedRound?2:1;D.forEach((v,O)=>{let w=1+O*b;p[h][w]||(p[h][w]=$m(v))})}),{sourceDrawPositionRanges:p}}function ib({drawPositions:t,roundProfile:e,roundNumber:r}){let n=[void 0,void 0];if(vI(t))return{orderedDrawPositions:n,displayOrder:n};let o=e?.[r],s=o?.pairedDrawPositions?.find(c=>Fe(c||[],t.filter(Boolean)))??n,a=o?.feedRound;if(bI(t)){let c=[...t].sort(se);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 Tp({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 nn({tournamentParticipants:t,tournamentRecord:e,participantIds:r}){let n="getPairedParticipant";if(!t&&!e)return{error:j};if(!Array.isArray(r)||r.length>2)return{error:Kr};if(!r.length)return _({result:{error:Eo},stack:n});t=t??e?.participants??[];let o=t.filter(a=>a.participantType===lt&&jt(r,a.individualParticipantIds).length===r.length&&a.individualParticipantIds.length===r.length),i=o[0];if(!i)return _({result:{error:re},stack:n});let s=J(o.slice(1),!1,!0);return{participant:J(i),duplicatedPairParticipants:s,...R}}function is({drawDefinition:t,participantId:e}){if(typeof t!="object")return{error:X};if(typeof e!="string")return{error:ee};let{extension:r}=dt({element:t,name:Do});return{lineUp:(r?.value||{})[e]}}function sb({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}=Tp({collectionPosition:r,collectionId:s,lineUp:d});if(c===wt){if(f?.length<=2){let I=o?.[f[0]]?.pairIdMap?.[f[1]],T=(I&&o[I]?.participant||nn({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||is({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||is({participantId:d,drawDefinition:i})?.lineUp;return u({attribute:m,lineUp:g,teamParticipant:f})}).filter(Boolean)||{};return{drawPositionCollectionAssignment:Object.assign({},...p)}}function wh({drawDefinition:t}){if(typeof t!="object")return{error:aa};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"&&[He,ue].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 ab({drawDefinition:t,roundProfile:e,structureId:r,matchUpsMap:n}){if(!t)return{error:X};if(!r)return{error:Sr};if(!e){let c=ti({matchUpsMap:n,structureId:r});if({roundProfile:e}=qe({matchUps:c}),!e)return{error:rt}}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=Te(p,p.length/u),d=m.map($m),l=m.map(S=>S.map(T=>T-i)).map($m),f=s.map(S=>{if(S>c)return;let T=e?.[S]?.drawPositions??[];return Te(T,T.length/u)}).filter(Boolean),g=Z(0,u).map(S=>f.map(T=>T[S]).flat().filter(Boolean).sort(se)).map(S=>pt(S)),I=g.map(S=>JC(S).map($m).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 Km({roundsNotPowerOf2:t,drawDefinition:e,structure:r,matchUps:n}){if(!r)return!1;n=n??r.matchUps??[],t=t??qe({matchUps:n}).roundsNotPowerOf2;let o=!!r.positionAssignments?.find(({drawPosition:i})=>i)||!!n?.find(({drawPositions:i})=>i?.length);return(!e?.drawType||e.drawType!==xi)&&!r?.structures&&t&&o}function gr({structure:t}){if(!t)return!1;let e=t.matchUps||t.roundMatchUps&&Object.values(t.roundMatchUps).flat(),r=!!e?.find(o=>o?.roundPosition),n=!!e?.find(o=>o?.drawPositions?.length);return!t?.structures&&t?.stage!==We&&(!e.length||!r&&!n)}var Bf={[da]:{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]:"",[ue]:"P",[at]:"Q",[He]:"C"}}},cb=Bf;function ub({roundNamingPolicy:t,drawDefinition:e,structure:r,matchUps:n}){let{roundProfile:o,roundMatchUps:i}=qe({matchUps:n}),{structureAbbreviation:s,stage:a}=r,c=gr({structure:r}),u=Km({structure:r}),p=r.structures,m={},d=Bf[da],l=r.stage===at,f=l?Math.max(...(e?.structures??[]).filter(b=>b.stage===at).map(({stageSequence:b})=>b??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,y=t?.affixes?.roundNumber||d.affixes.roundNumber,E=(t?.namingConventions||d.namingConventions).round,A=a&&a!==tt?a[0]:"",U=t?.stageConstants||d.stageConstants,C=a&&U?.[a]||A,P=`${I}${C}${g}`,D=o?Object.keys(o):[],M=l&&U?.[at]?`${U?.[at]}-`:"";if(p||c||u)Object.assign(m,...D.map(b=>{let v=`${M}${E} ${b}`,O=`${y}${b}`;return{[b]:{roundName:v,abbreviatedRoundName:O}}}));else{let b=l&&(t?.qualifyingFinishMap||d?.qualifyingFinishMap||{});Object.assign(m,...D.map(v=>{if(!o?.[v])return;let{matchUpsCount:O,preFeedRound:w}=o[v],F=O*2,L=b?.[o?.[v].finishingRound]||b&&`${y}${F}`||h[O]||`${y}${F}`,x=w?`-${T}`:"",B=`${L}${x}`,H=[P,s,B].filter(Boolean).join("-"),V=`${S[O]||`${y}${F}`}${x}`,Y=[P,s,V].filter(Boolean).join("-");return{[v]:{abbreviatedRoundName:Y,roundName:H}}}))}return{roundNamingProfile:m,roundProfile:o,roundMatchUps:i}}function zm(t){let e=ut(t,[{[Un]:!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===Tt&&Kt||s===lt&&wt||s===xt&&xt||void 0}return{matchUpType:n}}var NF="normal",dU="timed",MF="final",Hf="NOAD",Qm="SET",pb={S:NF,F:MF};function rr(t){if(typeof t=="string"){let e=t.startsWith("T")&&dU||t.startsWith(Qm)&&Qm||"";if(e===dU){let r=fb(t),n={simplified:!0,setFormat:r,bestOf:1};if(r)return n}if(e===Qm)return CF(t)}}function CF(t){let e=t.split("-"),r=Wf(e[0].slice(3)),n=r===1||r%2!==0?r:void 0,o=r!==1&&r%2===0?r:void 0,i=e&&mb(e[1]),s=e&&mb(e[2]),a=i&&i.timed||s&&s.timed,c=n&&n<6||a&&o,u=!e[2]||s,p=i,m=nt({setFormat:i,exactly:o,bestOf:n});if(s&&(m.finalSetFormat=s),c&&p&&u)return m}function mb(t){if(t?.[1]===":"){let e=t.split(":"),r=pb[e[0]],n=e[1];if(r&&n){if(n.startsWith("TB")){let I=db(n);return I===!1?!1:typeof I=="object"?{tiebreakSet:I}:void 0}if(n.startsWith("T"))return fb(n);let s=t.match(/^[FS]:(\d+)([A-Za-z]*)/),a=s&&gb(s[2])||!1,c=!s?.[2]||a,u=s?Wf(s[1]):void 0,p=lb(n),m=p!==!1,d=m&&p||u,l=db(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 lb(t,e=!0){let r=t?.indexOf("@")>0&&t.split("@");if(r)return(e?Wf(r[1]):r[1])||!1}function db(t){if(t)if(t.startsWith("TB")){let e=lb(t,!1),r=t.match(/^TB(\d+)([A-Za-z]*)/),n=r?.[1],o=r&&gb(r[2]),i=!r?.[2]||o,s=Wf(n);if(s&&i){let a={tiebreakTo:s};return e&&typeof e=="string"&&!ft(e)&&(a.modifier=e),o&&(a.NoAD=!0),a}else return!1}else return!1}function fb(t){let e=t.slice(1),r=e.match(/^(\d+)(@?[A-Za-z]*)/),n=Wf(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 gb(t){return t&&t.indexOf(Hf)>=0}function Wf(t){return isNaN(Number(t))?0:Number(t)}function du(t,e){return!Array.isArray(t)||!Re(e)?!1:jt(t,Ph[e]).length}function Ea(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:y,structureIds:N,readyToScore:E,courtIds:A,eventIds:U,venueIds:C,drawIds:P,stages:D,filterMatchUpIds:M=!0,filterMatchUpTypes:b=!0}=t,v=Array.isArray(h)?h.filter(Boolean):[],O=Array.isArray(o)?o.filter(Boolean):[],w=Array.isArray(n)?n.filter(Boolean):[],F=Array.isArray(D)?D.filter(Boolean):[],L=Array.isArray(f)?f.filter(Boolean):[],x=Array.isArray(u)?u.filter(Boolean):[],B=Array.isArray(l)?l.filter(Boolean):[],H=Array.isArray(m)?m.filter(Boolean):[],W=Array.isArray(a)?a.filter(Boolean):[],V=Array.isArray(d)&&M?d.filter(Boolean):[],Y=Array.isArray(y)&&b?y.filter(Boolean):[],$=Array.isArray(A)?A.filter(Boolean):[],k=Array.isArray(C)?C.filter(Boolean):[],K=Array.isArray(s)&&s.filter(Boolean)||typeof c=="string"&&[c]||[],z=Array.isArray(g)&&g.filter(Boolean)||typeof I=="string"&&I.length&&[I]||[],q=Array.isArray(T)?T.filter(Boolean):[],et=Array.isArray(U)?U.filter(Boolean):[],Q=Array.isArray(P)?P.filter(Boolean):[],it=Array.isArray(N)?N.filter(Boolean):[];return e.filter(ot=>{if(E&&!ie(gn)(ot)&&!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)||L.length&&!L.includes(ot.stageSequence)||x.length&&(!ot.collectionId||!x.includes(ot.collectionId))||B.length&&(!ot.roundName||!B.includes(ot.roundName))||H.length&&(!ot.roundNumber||!H.includes(ot.roundNumber))||W.length&&(!ot.roundPosition||!W.includes(ot.roundPosition))||O.length&&(!ot.matchUpStatus||!O.includes(ot.matchUpStatus))||w.length&&ot.matchUpStatus&&w.includes(ot.matchUpStatus)||V.length&&!V.includes(ot.matchUpId)||Y.length&&(!ot.matchUpType||!du(Y,ot.matchUpType))||K.length&&(!ot.matchUpFormat||!K.includes(ot.matchUpFormat)))return!1;if(z?.length){let{scheduledTime:mt}=Gf({matchUp:ot}),{scheduledDate:Xt}=ns({matchUp:ot}),Me=Ut(mt)||Xt;if(!z.find(Ee=>wn(Ee,Me)))return!1}if($.length){let{courtId:mt}=vh({matchUp:ot}),{allocatedCourts:Xt}=bh({matchUp:ot}),Et=Xt?.map(({courtId:Me})=>Me);if(!$.filter(Boolean).includes(mt)||Et?.includes(mt))return!1}if(k.length){let{venueId:mt}=Oh({matchUp:ot});if(!k.filter(Boolean).includes(mt))return!1}if(S){if(q.length&&!q.includes(ot.tournamentId)||et.length&&!et.includes(ot.eventId)||Q.length&&!Q.includes(ot.drawId)||it.length&&!it.includes(ot.structureId))return!1;if(v.length){let mt=ot.sides?.map(({participantId:Et})=>Et).filter(Boolean)??[];if(!v.some(Et=>mt.includes(Et)))return!1}}return!0})}function Ib({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?RF({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 RF({displaySideNumber:t,seedAssignments:e,participantId:r,assignment:n,sideNumber:o}){let i={drawPosition:n.drawPosition,displaySideNumber:t,sideNumber:o};if(r){let s=bF({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 bF({seedAssignments:t,participantId:e}){return t?.find(r=>!r.seedProxy&&r.participantId===e)}var In="ANY",te="MALE",Ur="MIXED",ss="OTHER",ce="FEMALE",Xm={ANY:In,MALE:te,FEMALE:ce,MIXED:Ur,OTHER:ss};function At({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:y,inContext:N,event:E}){let A={},U={};if(n=n??s?.participants,!y)return{collectionPositionMatchUps:A,error:Oo,roundMatchUps:U,matchUps:[]};let C=Array.isArray(m?.eventIds)?m?.eventIds.filter(Boolean):[],P=Array.isArray(m?.structureIds)?m?.structureIds.filter(Boolean):[],D=Array.isArray(m?.drawIds)?m?.drawIds.filter(Boolean):[],M=!h?.eventId||!C?.length&&!u?.eventIds?.filter(Boolean).length||C?.includes(h.eventId)||u?.eventIds?.includes(h.eventId),b=!P?.length||P.includes(y.structureId),v=!g||!D?.length||D.includes(g.drawId);if(!M||!b||!v)return{collectionPositionMatchUps:A,roundMatchUps:U,matchUps:[]};f&&!p&&(p=Bn({tournamentRecord:s,contextProfile:f,drawDefinition:g}));let{appliedPolicies:O}=ht({drawDefinition:g}),w={...e,...O,...i},F=w?.scoring?.structures,L=y.stage&&F?.stage&&F?.stage[y.stage],x=y.stageSequence&&L?.stageSequence&&L.stageSequence[y.stageSequence],B=w?.scoring?.requireAllPositionsAssigned||L?.requireAllPositionsAssigned||x?.requireAllPositionsAssigned;T||(T=ye({drawDefinition:g,structure:y}));let{positionAssignments:H,allPositionsAssigned:W}=de({structure:y}),V=!B||W,{seedAssignments:Y}=Hr({provisionalPositioning:r,drawDefinition:g,structure:y});a=a??Y;let{roundOffset:$,structureId:k,structureName:K,stage:z,stageSequence:q}=y,{drawId:et,drawName:Q,drawType:it}=g??{};S=S||g&&wh({drawDefinition:g}).exitProfiles;let ot=S?.[k],mt=ot?.length&&(ot[0].split("-").map(Ft=>parseInt(Ft)).reduce((Ft,Ue)=>Ft+Ue)||0),Xt=!!y.structures,Et=ti({matchUpsMap:T,structureId:k,inContext:N}),Me=w?.[da],Ee=ub({roundNamingPolicy:Me,drawDefinition:g,structure:y,matchUps:Et}),{roundNamingProfile:Ce,roundProfile:zt}=Ee;if(U=Ee?.roundMatchUps??[],m&&(Et=Ea({matchUps:Et,...m,filterMatchUpTypes:!1,filterMatchUpIds:!1})),N){let{sourceDrawPositionRanges:Ft}=ob({drawDefinition:g,matchUpsMap:T,structureId:k}),Ue=g?ab({drawDefinition:g,roundProfile:zt,matchUpsMap:T,structureId:k}).drawPositionsRanges:void 0;Et=Et.map(_t=>ve({scheduleVisibilityFilters:t,sourceDrawPositionRanges:Ft,drawPositionsRanges:Ue,roundNamingProfile:Ce,initialRoundOfPlay:mt,appliedPolicies:w,usePublishState:c,publishStatus:I,isRoundRobin:Xt,roundProfile:zt,matchUp:_t,event:E})),(Et?.filter(_t=>Array.isArray(_t.tieMatchUps))).forEach(_t=>{let oe=_t.tieMatchUps;Et=Et.concat(...oe)}),u&&(Et=Ea({processContext:!0,...u,matchUps:Et}))}else(Et?.filter(Ue=>Array.isArray(Ue.tieMatchUps))).forEach(Ue=>{let Rt=Ue.tieMatchUps;Et=Et.concat(...Rt)});return m&&(Et=Ea({matchUps:Et,...m,filterMatchUpTypes:!1,filterMatchUpIds:!1})),(m?.matchUpTypes||m?.matchUpIds)&&(Et=Ea({matchUpTypes:m.matchUpTypes,matchUpIds:m.matchUpIds,matchUps:Et})),(m?.matchUpTypes||m?.matchUpIds||N)&&(U=qe({matchUps:Et}).roundMatchUps??[]),Ye({drawDefinition:g,structure:y,event:E})?.tieFormat&&({collectionPositionMatchUps:A}=nb({matchUps:Et})),{collectionPositionMatchUps:A,roundMatchUps:U,isRoundRobin:Xt,roundProfile:zt,matchUpsMap:T,matchUps:Et};function ve({scheduleVisibilityFilters:Ft,sourceDrawPositionRanges:Ue,drawPositionsRanges:Rt,initialRoundOfPlay:_t,additionalContext:oe,roundNamingProfile:qt,tieDrawPositions:pe,appliedPolicies:he,isCollectionBye:mr,usePublishState:xe,publishStatus:Wt,matchUpTieId:we,isRoundRobin:ir,roundProfile:Oe,sideLineUps:Rr,matchUp:Se,event:Pe}){oe=oe??{};let Ir=Ye({drawDefinition:g,structure:y,matchUp:Se,event:Pe})?.tieFormat,si=Ir?.collectionDefinitions,ze=Se.collectionId&&si?.find(ro=>ro.collectionId===Se.collectionId),_n=Se.collectionId?ze?.matchUpFormat:Se.matchUpFormat??y?.matchUpFormat??g?.matchUpFormat??Pe?.matchUpFormat,Ni=Se.matchUpType||ze?.matchUpType||y?.matchUpType||g?.matchUpType||!ie(Ve)(Pe?.eventType)&&Pe?.eventType,Yi=mr?Nt:Se.matchUpStatus,{schedule:yn,endDate:Lc}=qm({scheduleVisibilityFilters:Ft,afterRecoveryTimes:o,tournamentRecord:s,usePublishState:xe,scheduleTiming:l,matchUpFormat:_n,publishStatus:Wt,matchUpType:Ni,matchUp:Se,event:Pe}),qi=pe??Se.drawPositions??[],{collectionPosition:cI,collectionId:vC,roundPosition:uI}=Se,$i=Se.roundNumber??oe.roundNumber,Mw=vC?sb({tournamentParticipants:n,positionAssignments:H,collectionPosition:cI,drawDefinition:g,participantMap:d,drawPositions:qi,collectionId:vC,sideLineUps:Rr,matchUpType:Ni}):void 0,OC=qt?.[$i]?.roundName||oe.roundName,_C=qt?.[$i]?.abbreviatedRoundName||oe.abbreviatedRoundName,Cw=Oe?.[$i]?.feedRound,Rw=Oe?.[$i]?.preFeedRound,bw=Oe?.[$i]?.roundFactor,vw=Rt?.[$i],Ow=uI?vw?.[uI]:void 0,_w=Ue?.[$i],xw=ze?.category?{...h?.category||{},...ze.category}:h?.category??Pe?.category,ww=Se.processCodes?.length&&Se.processCodes||ze?.processCodes?.length&&ze?.processCodes||y?.processCodes?.length&&y?.processCodes||g?.processCodes?.length&&g?.processCodes||Pe?.processCodes?.length&&Pe?.processCodes||s?.processCodes,Lw=f?.withCompetitiveness&&pu({...p,matchUp:Se}),Fw=Se.finishingPositionRange??oe.finishingPositionRange,pI=ro=>nt(ro,void 0,!0),hr={...pI(h),...pI({matchUpFormat:Se.matchUpType===Ve?void 0:_n,tieFormat:Se.matchUpType!==Ve?void 0:Ir,gender:ze?.gender??Pe?.gender,roundOfPlay:z!==at&&ft(_t)&&_t+($i||0),endDate:Se.endDate??Lc,discipline:Pe?.discipline,category:xw,finishingPositionRange:Fw,abbreviatedRoundName:_C,drawPositionsRange:Ow,competitiveProfile:Lw,structureName:K,stageSequence:q,drawPositions:qi,matchUpStatus:Yi,processCodes:ww,isRoundRobin:ir,matchUpTieId:we,preFeedRound:Rw,matchUpType:Ni,roundFactor:bw,roundOffset:$,structureId:k,roundNumber:$i,feedRound:Cw,roundName:OC,drawName:Q,drawType:it,schedule:yn,drawId:et,stage:z}),...J(pI(Se),!0,!0)};if(_n&&Se.score?.scoreStringSide1){let ro=rr(_n),{bestOf:ia,finalSetFormat:Ps,setFormat:yr}=ro??{};(Ps?.tiebreakSet||yr?.tiebreakSet||yr?.timed)&&(hr.score.sets=hr.score.sets.sort((qr,xn)=>qr.setNumber-xn.setNumber).map((qr,xn)=>(xn+1===ia?(Ps?.tiebreakSet||Ps?.timed)&&(qr.tiebreakSet=!0):(yr?.tiebreakSet||yr?.timed)&&(qr.tiebreakSet=!0),qr)))}if(Array.isArray(qi)){let{orderedDrawPositions:ro,displayOrder:ia}=ib({drawPositions:qi,roundProfile:Oe,roundNumber:$i}),Ps=Oe?.[$i]?.feedRound,yr=ia[0]!==ro[0],xn=ro.concat(void 0,void 0).slice(0,2).map((Mi,iA)=>{let mI=iA+1,kw=yr?3-mI:mI,Vw=Ib({...Mw,positionAssignments:H,displaySideNumber:kw,seedAssignments:a,drawPosition:Mi,isFeedRound:Ps,sideNumber:mI}),Bw=Se.sides?.find(Ww=>Ww.sideNumber===mI),wC=uI?(uI-1)*2+iA+1:void 0,Hw=wC?_w?.[wC]:void 0;return pI({sourceDrawPositionRange:Hw,...Bw,...Vw})});Object.assign(hr,J({sides:xn},!0,!0))}if(n&&hr.sides){let ro=he?.[ws],ia=yr=>{let qr=d?.[yr]?.participant;return qr&&_i({template:ro?.participant,source:qr})};if(hr.sides.filter(Boolean).forEach(yr=>{if(yr.participantId){let qr=J(ia(yr.participantId)||n&&Lo({policyDefinitions:he,participantId:yr.participantId,tournamentParticipants:n,internalUse:!0,contextProfile:f}),void 0,!0);if(qr){if(g?.entries){let xn=g.entries.find(Mi=>Mi.participantId===yr.participantId);xn?.entryStatus&&(qr.entryStatus=xn.entryStatus),xn?.entryStage&&(qr.entryStage=xn.entryStage)}Object.assign(yr,{participant:qr})}}if(yr?.participant?.individualParticipantIds?.length&&!yr.participant.individualParticipants?.length){let qr=yr.participant.individualParticipantIds.map(xn=>ia(xn)||n&&Lo({policyDefinitions:he,tournamentParticipants:n,internalUse:!0,contextProfile:f,participantId:xn}));Object.assign(yr.participant,{individualParticipants:qr})}}),!hr.matchUpType){let{matchUpType:yr}=zm({matchUp:hr});yr&&Object.assign(hr,{matchUpType:yr})}if(f?.inferGender&&(!hr.gender||hr.gender===Ur)&&hr.sides?.length===2&&hr.matchUpType!==Ve){let yr=hr.sides.map(qr=>{if(ie(Kt)(hr.matchUpType))return qr.participant?.person?.sex;if(qr.participant?.individualParticipants?.length===2){let xn=pt(qr.participant.individualParticipants.map(Mi=>Mi.person?.sex)).filter(Boolean);if(xn.length===1)return xn[0]}});if(yr.filter(Boolean).length===2&&pt(yr).length===1){let qr=yr[0];hr.inferredGender=qr}}}if(hr.tieMatchUps){let ro=hr.matchUpStatus===Nt,ia=hr.sides?.map(({participant:Ps,drawPosition:yr,sideNumber:qr,lineUp:xn})=>{let Mi=Ps?.participantType===Ve&&Ps;return{teamParticipant:Mi&&nt({participantRoleResponsibilities:Mi.participantRoleResponsibilities,participantOtherName:Mi.participanOthertName,participantName:Mi.participantName,participantId:Mi.participantId,teamId:Mi.teamId}),drawPosition:yr,sideNumber:qr,lineUp:xn}});hr.tieMatchUps=hr.tieMatchUps.map(Ps=>{let yr=hr.matchUpId,xn={finishingPositionRange:hr.finishingPositionRange,abbreviatedRoundName:_C,roundNumber:$i,roundName:OC};return ve({tieDrawPositions:qi,scheduleVisibilityFilters:Ft,sourceDrawPositionRanges:Ue,sideLineUps:ia,drawPositionsRanges:Rt,initialRoundOfPlay:_t,roundNamingProfile:qt,additionalContext:xn,appliedPolicies:he,isCollectionBye:ro,usePublishState:xe,publishStatus:Wt,matchUpTieId:yr,isRoundRobin:ir,roundProfile:Oe,matchUp:Ps,event:Pe})})}let xC=hr.sides&&hr.sides.filter(ro=>ro?.participantId).length===2,Gw=!hr.winningSide;if(Object.assign(hr,{readyToScore:V&&xC&&Gw,hasContext:!0}),xC){let{allParticipantsCheckedIn:ro,checkedInParticipantIds:ia}=rs({matchUp:hr});Object.assign(hr,{allParticipantsCheckedIn:ro,checkedInParticipantIds:ia})}return Array.isArray(f?.exclude)&&f?.exclude.forEach(ro=>delete hr[ro]),hr}}function as({matchUp:t}){return t?ae.includes(t?.matchUpStatus)||t?.winningSide:!1}function lu({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:y,context:N,event:E}){!y&&S&&({structure:y}=st({drawDefinition:g,structureId:S}));let A=At({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:y,inContext:T,context:N,event:E}),U=[],C=[],P=[],D=[],M=[];if(A.error)return A;let{matchUps:b}=A,{assignedPositions:v}=de({structure:y}),O=v?.filter(F=>F.participantId).map(F=>F.drawPosition),w;return b.filter(F=>{let L=c?.matchUpTypes?.length===1&&c.matchUpTypes[0]===Bt;return!(F.matchUpType!==Bt&&L)}).forEach(F=>{if(F.matchUpStatus===Ar){U.push(F);return}F.matchUpType===Bt&&(w=!0);let L=F.collectionId,x=L&&F.sides?.every(k=>k.participantId),B=!L&&F.drawPositions?.filter(Boolean).length===2,H=!L&&F.drawPositions?.every(k=>O?.includes(k)),W=v?.filter(k=>k.bye).map(k=>k.drawPosition),V=!L&&F.drawPositions?.find(k=>W?.includes(k)),$=th.includes(F.matchUpStatus)&&(x||B&&(!t||H));return V?M.push(F):as({matchUp:F})?C.push(F):$?P.push(F):D.push(F)}),{includesTeamMatchUps:w,abandonedMatchUps:U,completedMatchUps:C,upcomingMatchUps:P,pendingMatchUps:D,byeMatchUps:M,structure:y}}function hb({drawDefinition:t,roundNumber:e,structureId:r}){if(!t)return{error:X};if(!r)return{error:Sr};let{links:n}=Ws({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 Lh({finishingPositions:t,linkCondition:e,linkType:r,source:n}){let o=n.find(i=>{let s=!i.source?.finishingPositions||!t||Fe(t,i.source?.finishingPositions);return e===i.linkCondition&&s&&i.linkType===r});return[po,Qn].includes(o?.linkType)&&!o?.source?.roundNumber?_({result:{error:G},stack:"getTargetLink",context:o}):o}function Ws({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:Sr}:{error:X}}function Sb({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 Fh({sourceRoundMatchUpCount:t,inContextDrawMatchUps:e,sourceRoundPosition:r,drawDefinition:n,targetLink:o}){if(!o)return{error:yl};let{target:{structureId:i,feedProfile:s,groupedOrder:a,roundNumber:c,positionInterleave:u}}=o,{structure:p}=st({drawDefinition:n,structureId:i}),{positionAssignments:m}=Ct({structure:p}),l=(e?.filter(P=>P.structureId===p?.structureId)).filter(P=>P.roundNumber===c&&!P.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 P=u.offset+(r-1)*u.interleave,D=r+P;h=Math.ceil(D/2),S=1-D%2}let T=g,y=g[h-1],N=xh({roundPositionsCount:g.length,groupedOrder:a}),E=N?.length||1;if(E<=g.length){let P=f/E,D=Te(g,P);s===mi&&D.forEach(M=>M.reverse()),T=N?.length&&N?.map(M=>D[M-1]).flat()||T}s===pn?y=T[h-1]:s===mi?((!N?.length||E>g.length)&&(h=l.length+1-h),y=T[h-1]):s===up&&Pr()&&console.log(zu,{feedProfile:s});let A=y&&l.reduce((P,D)=>D.roundPosition===y?D:P,void 0),U;A?.feedRound?(S=0,U=Math.min(...(A.drawPositions||[]).filter(Boolean))):U=A?.drawPositions?.length===2&&A?.drawPositions[S];let C=m?.find(({drawPosition:P})=>P===U);if(C){let{extension:P}=dt({element:C,name:Pm});if(P?.value)return{disabledDrawPosition:U}}return{matchUp:A,targetDrawPosition:U,matchUpDrawPositionIndex:S}}function nr({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===wi?vF({inContextDrawMatchUps:t,useTargetMatchUpIds:e,drawDefinition:n,structure:s,matchUp:i}):OF({matchUp:i})}function vF({inContextDrawMatchUps:t,useTargetMatchUpIds:e,drawDefinition:r,structure:n,matchUp:o}){let{winnerMatchUpId:i,loserMatchUpId:s}=o,{links:a}=hb({roundNumber:o.roundNumber,structureId:n.structureId,drawDefinition:r}),c=a?.source,u=Lh({source:c,linkType:po}),p=Lh({linkCondition:Xn,linkType:Qn,source:c}),m=Lh({source:c,linkType:Qn}),d=p&&m;m||(m=p);let l=u?.target?.feedProfile,f=m?.target?.feedProfile,g=p?.target?.feedProfile,I,h,S,T,y,N,E,A,U,C;if(e&&(i||s)&&(E=i&&l!==tn&&t.find(({matchUpId:M})=>M===i),T=s&&f!==tn&&t.find(({matchUpId:M})=>M===s),E||T))return{matchUp:o,targetLinks:{loserTargetLink:m,winnerTargetLink:u},targetMatchUps:{loserMatchUp:T,winnerMatchUp:E}};let{roundPosition:P}=o;C=C||t.filter(M=>M.structureId===n.structureId);let D=C.reduce((M,b)=>b.roundNumber===o.roundNumber&&!b.matchUpTieId?M+1:M,0);return m&&!T&&f!==tn&&({matchUpDrawPositionIndex:N,targetDrawPosition:y,matchUp:T}=Fh({targetLink:m,sourceRoundMatchUpCount:D,inContextDrawMatchUps:t,sourceRoundPosition:P,drawDefinition:r})),d&&g!==tn&&({matchUpDrawPositionIndex:S,targetDrawPosition:h,matchUp:I}=Fh({targetLink:p,sourceRoundMatchUpCount:D,inContextDrawMatchUps:t,sourceRoundPosition:P,drawDefinition:r})),u&&!E&&l!==tn&&({matchUpDrawPositionIndex:U,targetDrawPosition:A,matchUp:E}=Fh({targetLink:u,sourceRoundMatchUpCount:D,inContextDrawMatchUps:t,sourceRoundPosition:P,drawDefinition:r})),E||(C=C||t.filter(M=>M.structureId===n.structureId),{matchUp:E}=Sb({structureMatchUps:C,matchUp:o})),nt({matchUp:o,targetLinks:{loserTargetLink:m,winnerTargetLink:u,byeTargetLink:p},targetMatchUps:{winnerMatchUpDrawPositionIndex:U,loserMatchUpDrawPositionIndex:N,byeMatchUpDrawPositionIndex:S,winnerTargetDrawPosition:A,loserTargetDrawPosition:y,byeTargetDrawPosition:h,winnerMatchUp:E,loserMatchUp:T,byeMatchUp:I},targetMatchUpIds:!!(i||s)})}function OF({matchUp:t}){return{targetLinks:{loserTargetLink:void 0,winnerTargetLink:void 0},targetMatchUps:{loserMatchUp:void 0,winnerMatchUp:void 0},matchUp:t}}function Tb({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===Fs){let{roundNumber:c}=n,u=c&&ct(c)+1,p=a.matchUps??[],{roundMatchUps:m}=qe({matchUps:p});if(u&&m?.[u]){let d=[...s].sort(se).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=nr({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=lU({upcomingMatchUp:u}),d=lU({upcomingMatchUp:p});if(n.matchUpStatus!==Nt&&p?.matchUpStatus===Nt){let{matchUp:f}=yb({matchUp:p,drawDefinition:t,inContextDrawMatchUps:e})||{};d=f&&lU({upcomingMatchUp:f})||d}let l=n.schedule?.timeAfterRecovery;if(l&&(m?.schedule?.scheduledTime&&Vt(m.schedule.scheduledTime)<Vt(l)&&(r[m.matchUpId]=n.matchUpId,m.schedule.scheduleConflict=n.matchUpId),d?.schedule?.scheduledTime&&Vt(d.schedule.scheduledTime)<Vt(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===Xn,I=_F(n);if(I.length){let h=uf(u?.sides),S=uf(p?.sides),y=I.find(({participantId:A})=>h.includes(A))?[]:I,E=I.find(({participantId:A})=>S.includes(A))?[]:I;p&&g&&E.length<2&&E.push({bye:!0,tbd:!0}),y?.length&&u&&(!c.targetMatchUpIds&&u&&(u=e.find(({matchUpId:A})=>A===u.matchUpId)),u.potentialParticipants||(u.potentialParticipants=[]),u.potentialParticipants.push(y)),E?.length&&p&&(c.targetMatchUpIds||(u=e.find(({matchUpId:A})=>A===p.matchUpId)),p.potentialParticipants||(p.potentialParticipants=[]),p.potentialParticipants.push(E))}}}}),Object.keys(r).length&&e.forEach(n=>{Object.keys(r).includes(n.matchUpId)&&(n.schedule.scheduleConflict=r[n.matchUpId])}),{scheduleConflictMatchUpIds:r}}function _F(t){return t?.sides?.map(({participant:e,participantId:r,qualifier:n})=>e||r&&{participantId:r}||n&&{qualifier:n}).filter(Boolean)||[]}function yb({matchUp:t,drawDefinition:e,inContextDrawMatchUps:r}){let{matchUpId:n,matchUpStatus:o,structureId:i}=t||{};if(!t||!i||t?.matchUpStatus===Qt)return{matchUp:t};if(o===Nt){let s;return t.winnerMatchUpId?s=r.find(({matchUpId:a})=>a===t.winnerMatchUpId):{winnerMatchUp:s}=nr({inContextDrawMatchUps:r,drawDefinition:e,matchUpId:n})?.targetMatchUps||{},yb({matchUp:s,drawDefinition:e,inContextDrawMatchUps:r})}return{matchUp:void 0}}function lU(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 ne(t){let e="getAllDrawMatchUps";Object.assign(t,{requireParticipants:!1});let r=js(t);if(r.error)return _({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 js(t){if(!t?.drawDefinition)return{error:X};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:y,context:N,event:E}=t,A=[],U=[],C=[],P=[],D=[];h&&!r&&(r=Bn({policyDefinitions:u,tournamentRecord:p,contextProfile:h,event:E}));let M;!e?.length&&p&&(e=p?.participants,(y||a?.withGroupings)&&e?.length&&({participantsWithGroupings:e,groupInfo:M}=Lm({participants:e,participantsProfile:a})));let{structures:b}=Gn({drawDefinition:S});if(!b)return{error:Gt};n||(n=ye({drawDefinition:S}));let v=S&&wh({drawDefinition:S}).exitProfiles;b.forEach(F=>{let{byeMatchUps:L=[],pendingMatchUps:x=[],upcomingMatchUps:B=[],completedMatchUps:H=[],abandonedMatchUps:W=[]}=lu({matchUpFilters:T?void 0:l,contextFilters:T?void 0:d,inContext:y||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:v,matchUpsMap:n,structure:F,context:N,event:E});A=A.concat(...W),U=U.concat(...H),C=C.concat(...B),P=P.concat(...x),D=D.concat(...L)});let O=F=>(!l&&!T&&!d||(l&&(F=Ea({matchUps:F,...l})),d&&(F=Ea({matchUps:F,...d,processContext:!0}))),F),w={abandonedMatchUps:O(A),completedMatchUps:O(U),upcomingMatchUps:O(C),pendingMatchUps:O(P),byeMatchUps:O(D),matchUpsMap:n,...R,groupInfo:M};if(T){let F=typeof T=="object"||{abandoned:!0,completed:!0,upcoming:!0,pending:!0,bye:!0},{abandoned:L,completed:x,upcoming:B,pending:H,bye:W}=F,V=[].concat(...L&&A||[],...x&&U||[],...B&&C||[],...H&&P||[],...W&&D||[]);Tb({inContextDrawMatchUps:V,drawDefinition:S})}return w}function ho(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:Dt};let{eventId:S,eventName:T,endDate:y,eventType:N,category:E,gender:A,matchUpFormat:U}=h??{},C={...I,...nt({indoorOutDoor:h.indoorOutdoor??p?.indoorOutdoor,surfaceCategory:h.surfaceCategory??p?.surfaceCategory,endDate:h.endDate??p?.endDate,tournamentId:p?.tournamentId,matchUpFormat:U,eventName:T,eventType:N,category:E,eventId:S,gender:A})};y&&(C.endDate=y),d&&!r&&(r=Bn({policyDefinitions:c,tournamentRecord:p,contextProfile:d,event:h}));let P;if(!e?.length&&!n&&p){let v=fi({participantsProfile:s,useParticipantMap:u,policyDefinitions:c,tournamentRecord:p,contextProfile:d,inContext:g});n=v.participantMap,e=v.participants??[],P=v.groupInfo}let D=h.drawDefinitions??[],M=ya({tournamentRecord:p,event:h}).scheduleTiming;return{matchUps:D.flatMap(v=>{let{matchUps:O}=ne({tournamentParticipants:e,tournamentAppliedPolicies:i,scheduleVisibilityFilters:o,context:C,participantsProfile:s,afterRecoveryTimes:a,policyDefinitions:c,tournamentRecord:p,contextFilters:m,contextProfile:d,drawDefinition:v,contextContent:r,matchUpFilters:l,participantMap:n,scheduleTiming:M,nextMatchUps:f,inContext:g,event:h});return O??[]}),groupInfo:P}}function le(t){let e=ut(t,[{tournamentRecord:!0}]);if(e.error)return e;if(!t?.tournamentRecord)return{error:j};let{participantMap:r,participants:n}=t,{scheduleVisibilityFilters:o,participantsProfile:i,afterRecoveryTimes:s,useParticipantMap:a,policyDefinitions:c,tournamentRecord:u,inContext:p=!0,contextProfile:m,matchUpFilters:d,contextFilters:l,nextMatchUps:f,context:g}=t,I=t.tournamentId??u.tournamentId,h=u?.events??[];n||({participants:n,participantMap:r}=fi({participantsProfile:i,useParticipantMap:a,policyDefinitions:c,tournamentRecord:u,contextProfile:m,inContext:p}));let{appliedPolicies:S}=ht({tournamentRecord:u}),T={...g,tournamentId:I,indoorOutDoor:u.indoorOutdoor,surfaceCategory:u.surfaceCategory,endDate:u.endDate},y=Bn({policyDefinitions:c,tournamentRecord:u,contextProfile:m});return{matchUps:h.flatMap(E=>(T.eventDrawsCount=E.drawDefinitions?.length??0,ho({context:T,scheduleVisibilityFilters:o,tournamentAppliedPolicies:S,participantsProfile:i,afterRecoveryTimes:s,policyDefinitions:c,tournamentRecord:u,contextContent:y,contextFilters:l,contextProfile:m,matchUpFilters:d,participantMap:r,nextMatchUps:f,participants:n,inContext:p,event:E}).matchUps??[])).concat(...u.matchUps??[])}}function mn({scheduleVisibilityFilters:t,afterRecoveryTimes:e,participantsProfile:r,tournamentRecords:n,policyDefinitions:o,matchUpFilters:i,contextFilters:s,nextMatchUps:a,inContext:c}){if(typeof n!="object"||!Object.keys(n).length)return{error:kt};let p=Object.keys(n).map(m=>{let d=n[m];return le({scheduleVisibilityFilters:t,afterRecoveryTimes:e,participantsProfile:r,policyDefinitions:o,tournamentRecord:d,matchUpFilters:i,contextFilters:s,nextMatchUps:a,inContext:c}).matchUps??[]}).flat();return{...R,matchUps:p}}function Ai(t,e){return xF(t,e)||(t?.stageSequence||0)-(e?.stageSequence||0)||t?.roundNumber&&e.roundNumber&&t?.roundNumber-e?.roundNumber||(t?.roundPosition??0)-(e?.roundPosition??0)}function xF(t,e){return(Ls[t?.stage]||0)-(Ls[e?.stage]||0)}function or(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:y,endDate:N,eventType:E,category:A,gender:U,matchUpFormat:C}=S??{},P={...h,surfaceCategory:S?.surfaceCategory??p?.surfaceCategory,indoorOutDoor:S?.indoorOutdoor??p?.indoorOutdoor,matchUpFormat:C,eventType:E,eventName:y,category:A,eventId:T,endDate:N,gender:U},D;return!e?.length&&!r&&p&&({participants:e=[],participantMap:r,groupInfo:D}=fi({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})),{...ne({context:P,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:D}}function cs({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))}}}}var fU=t=>e=>!t||typeof e!="object"?void 0:Array.isArray(t)&&t.map(r=>({[r]:cs({element:e,accessor:r})?.value}))||typeof t=="object"&&Object.keys(t).map(r=>({[r]:cs({element:e,accessor:r})?.value}))||(typeof t=="string"&&cs({element:e,accessor:t}))?.value,Mr=fU;function Ua({finishingPositionOffset:t=0,finishingPositionLimit:e,positionsFed:r,roundsCount:n,roundLimit:o,matchUps:i,lucky:s,fmlc:a}){if(!Nr(i))return[];let{roundProfile:c,roundNumbers:u=[]}=qe({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(Mr("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},y=d?.slice(I-1).reduce((M,b)=>M+(b||0),0),N=a&&I!==1,E=1+t+(N?r??0:0),A=1,U=Z(E,s?E+S*2:y+E+A),C=y+A-S,P=l(U.slice(C)),D=l(U.slice(0,C),!0);return T.finishingPositionRange={loser:P,winner:D},{[I]:T}})),g=Pr({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 Gi({inContextDrawMatchUps:t,drawDefinition:e,matchUpsMap:r}){if(!e)return{error:X};let n={loserMatchUpIds:{},winnerMatchUpIds:{}};if(t||({matchUps:t,matchUpsMap:r}=ne({inContext:!0,drawDefinition:e,matchUpsMap:r})),!r?.drawMatchUps.some(i=>i.finishingPositionRange)&&e?.structures?.length===1&&!e?.structures[0].structures){let i=r?.drawMatchUps??[];Ua({matchUps:i})}return(t??[]).filter(({collectionId:i})=>!i).forEach(i=>{let{matchUpId:s,structureId:a}=i,c=nr({inContextDrawMatchUps:t,drawDefinition:e,matchUpId:s}),{winnerMatchUp:u,loserMatchUp:p}=c.targetMatchUps,m=u?.matchUpId,d=p?.matchUpId,f=ti({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 Yr(t){let e=en(t),r=t.matchUps??[],n=t.drawIds??[],{includeParticipantDependencies:o,tournamentRecord:i,drawDefinition:s}=t;if(!Array.isArray(r))return{error:An};if(!Array.isArray(n))return{error:$r};let a=t.matchUpIds?.length?t.matchUpIds:r.map(T=>T.matchUpId);if(!Array.isArray(a))return{error:ua};let c={},u={},p={},m={};i&&!Object.keys(e).length&&(e={[i.tournamentId]:i});let d=Object.values(e),f=d.reduce((T,y)=>T.concat(y.events??[]).map(N=>(N.drawDefinitions||[]).map(E=>E.links||[])).flat(1/0),[]).filter(({linkType:T})=>T===zn),g=r;if(f.length){g=mn({nextMatchUps:!0,tournamentRecords:e}).matchUps;let T=f.reduce((y,N)=>{let E=N.source?.structureId,A=N.target?.structureId;return E&&A&&(p[A]=E),E&&!y.includes(E)&&y.push(E),y},[]);for(let y of T)c[y]=[];for(let y of g??[]){let N=y.containerStructureId||y.structureId;T.includes(N)&&c[N].push(y.matchUpId)}}let I=T=>{u[T]||(u[T]={dependentMatchUpIds:[],participantIds:[],matchUpIds:[],sources:[]},m[T]=[])},h=(T,y)=>{u[T].matchUpIds.forEach(E=>{u[y].matchUpIds.push(E)}),u[y].matchUpIds.push(T),u[T].dependentMatchUpIds.push(y),o&&u[T].participantIds.forEach(E=>u[y].participantIds.push(E))},S=T=>{let y=Object.keys(c).length;for(let N of T||[]){let{matchUpId:E,winnerMatchUpId:A,loserMatchUpId:U}=N;if(!a.length||a.includes(E)){if(I(E),o){let{individualParticipantIds:D}=nu(N);u[E].participantIds=D}A&&(I(A),h(E,A),m[A].push(E)),U&&(I(U),h(E,U),m[U].push(E)),u[E].sources.push(m[E]);let C=m[E].map(D=>u[D].sources[0]).flat(),P=m[E].map(D=>u[D].sources[1]).flat();if(u[E].sources.push(C,P),y){let D=N.containerStructureId||N.structureId,M=p[D];if(c[M])for(let b of c[M])I(b),h(b,E),m[b].push(E)}}}};if(s)Gi({drawDefinition:s}),g?.length||(g=or({drawDefinition:s}).matchUps),S(g);else{if(g?.length||(g=mn({nextMatchUps:!0,tournamentRecords:e}).matchUps),!n.length){let T=d?.length?d.map(({events:y=[]})=>y.map(({drawDefinitions:N=[]})=>N.map(({drawId:E})=>E))).flat(1/0):[];T&&(n=T)}for(let T of n){let y=g?.filter(E=>E.drawId===T).sort(Ai);if(!y?.find(({roundPosition:E})=>!E)){let E=y?.find(({tournamentId:U})=>U),{drawDefinition:A}=je({tournamentRecord:e[E?.tournamentId],drawId:T});A&&Gi({drawDefinition:A})}S(y)}}return{positionDependencies:c,matchUpDependencies:u,sourceMatchUpIds:m,matchUps:g,...R}}function Ie(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 Pa({matchUpStatus:t}){return JI.includes(t)}function Ab({matchUpStatus:t}){return Cm.includes(t)}function jf({matchUpStatus:t}){return ZI.includes(t)}function Yf({matchUpStatus:t,winningSide:e,tieMatchUps:r,sides:n,score:o}){let i=n?.find(({participantId:c})=>c),s=r?.filter(Yf)?.length;return Ie({score:o})||s||e&&i||t&&Ab({matchUpStatus:t})&&![bt,vt,Cn].includes(t)}function Da(t){let{drawDefinition:e,findContainer:r,structureId:n,event:o}=t,i=t.structure,s={isCollectionMatchUp:!1},{containedStructures:a}=ts({drawDefinition:e}),c=n?a[n]||[]:[];if(!i){let A=st({drawDefinition:e,structureId:n});if(A.error)return A;i=r?A.containingStructure??A.structure:A.structure}if(gr({structure:i}))return{structure:i,isAdHoc:!0,error:Ds};let{matchUps:u}=ne({inContext:!0,matchUpFilters:s,drawDefinition:e,event:o}),p=u?.filter(A=>A.structureId===n||c.includes(A.structureId)),{matchUpDependencies:m}=Yr({drawIds:[e.drawId],matchUps:u,drawDefinition:e}),d=[],l=[],f={},g=[];for(let A of u??[]){if(A.structureId===n||c.includes(A.structureId)){l.push(...A.drawPositions??[]);let U=A.roundNumber;for(let C of(A.drawPositions??[]).filter(Boolean))(!f[C]||U&&f[C]>U)&&(f[C]=U)}Yf(A)&&(g.push(A),d.push(A.matchUpId,...m?.[A?.matchUpId]?.matchUpIds||[]))}let I=pt(l.filter(Boolean)).sort(se),h=pt(d),S=pt(p?.map(({matchUpId:A,drawPositions:U})=>h.includes(A)?U:[]).flat().filter(Boolean)).sort(se),{positionAssignments:T}=Ct({drawDefinition:e,structure:i}),y=T?.filter(A=>A.bye).map(A=>A.drawPosition),N=T?.filter(A=>A.qualifier).map(A=>A.drawPosition),E=I?.filter(A=>!S.includes(A))||[];return{allDrawPositions:I,inContextStructureMatchUps:p,drawPositionInitialRounds:f,activeDependentMatchUpIds:h,qualifyingDrawPositions:N,inactiveDrawPositions:E,positionAssignments:T,activeDrawPositions:S,byeDrawPositions:y,activeMatchUps:g,structure:i}}function us({drawPosition:t,matchUps:e=[]}){return{initialRoundNumber:e.filter(({drawPositions:n})=>t&&n?.includes(t)).map(({roundNumber:n})=>n).sort(se)[0]}}var Na={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 Hn(t,e){typeof t=="string"&&(t={method:t}),(e||Pr())&&Gh.push(t)}function wF(t){let e=Gh.slice();return t&&(Gh.length=0),e}function Eb(t){let r=wF(t).map(n=>{let{color:o,keyColors:i,method:s,newline:a}=n,c=Object.keys(Na).includes(o)?Na[o]:Na.cyan,p=Object.keys(n).filter(d=>!["color","keyColors","method","newline"].includes(d)).map(d=>{let l=i&&Object.keys(i).includes(d)&&Na[i[d]]?Na[i[d]]:Na.brightwhite;return`${Na.white}${d}: ${l}${n[d]}`}).join(", "),m=s?.length<15?" ":" ";return[a?`
2
2
  `:"",c,s,m,Na.white,p,Na.reset,`
3
- `].join("")});r?.length&&console.log(...r)}function Ub(){Gh.length=0}function Cr({provisionalPositioning:t,isPositionAction:e,tournamentRecord:r,drawDefinition:n,drawPosition:o,matchUpsMap:i,structureId:s,structure:a,event:c}){if(!n)return{error:X};if(a||({structure:a}=st({drawDefinition:n,structureId:s})),!a)return{error:Gt};s||({structureId:s}=a);let u="assignDrawPositionBye";Hn({method:u,color:"cyan",drawPosition:o}),i||(i=ye({drawDefinition:n}));let{positionAssignments:p}=Ct({structure:a}),{activeDrawPositions:m}=Da({drawDefinition:n,structureId:s});if(p?.find(M=>M.drawPosition===o)?.bye)return{...R};if(m?.includes(o))return{error:Bu};let f=p?.find(M=>M.drawPosition===o);if(!f)return{error:Ds};let{filled:g,containsBye:I,assignedParticipantId:h}=LF(f);if(I)return{...R};if(g&&!I)return _({result:{error:ja},stack:u});let S=ht({tournamentRecord:r,drawDefinition:n,event:c}).appliedPolicies??{},T=ne({inContext:!0,drawDefinition:n,matchUpsMap:i}).matchUps??[],y={isCollectionMatchUp:!1},{matchUps:N}=At({provisionalPositioning:t,drawDefinition:n,matchUpFilters:y,matchUpsMap:i,structure:a});if(p?.forEach(M=>{M.drawPosition===o&&(M.bye=!0)}),a.structureType===ke)return FF({tournamentRecord:r,drawDefinition:n,drawPosition:o,matchUps:N}),Mo({tournamentId:r?.tournamentId,drawDefinition:n,structure:a,event:c}),Pb({assignedParticipantId:h,isPositionAction:e,appliedPolicies:S,drawDefinition:n,drawPosition:o,structureId:s,stack:u});let{roundProfile:E,roundMatchUps:A}=qe({matchUps:N}),C=(E&&Object.keys(E).map(M=>parseInt(M)).reverse())?.find(M=>E?.[M].drawPositions?.includes(o)),P=C?A?.[C].find(({drawPositions:M})=>M?.includes(o)):void 0;P&&Db({tournamentRecord:r,drawDefinition:n,matchUp:P,event:c});let D=P?.drawPositions?.find(M=>M!==o);if(P&&D){let M=kh({sourceDrawPositions:P.drawPositions,matchUpId:P.matchUpId,inContextDrawMatchUps:T,drawPositionToAdvance:D,tournamentRecord:r,drawDefinition:n,matchUpsMap:i});if(M.error)return M}return Mo({tournamentId:r?.tournamentId,drawDefinition:n,structure:a,event:c}),Pb({assignedParticipantId:h,isPositionAction:e,appliedPolicies:S,drawDefinition:n,drawPosition:o,structureId:s,stack:u})}function Pb({assignedParticipantId:t,isPositionAction:e,appliedPolicies:r,drawDefinition:n,drawPosition:o,structureId:i,stack:s}){return e&&ru({appliedPolicies:r,drawDefinition:n,positionAction:{removedParticipantId:t,drawPosition:o,structureId:i,name:s}}),_({result:{...R},stack:s})}function LF(t){let e=t.bye,r=t.qualifier,n=t.participantId;return{containsBye:e,containsQualifier:r,assignedParticipantId:n,filled:e||r||n}}function Db({tournamentRecord:t,drawDefinition:e,eventId:r,matchUp:n,event:o}){Object.assign(n,{matchUpStatus:Nt,score:void 0,winningSide:void 0}),It({tournamentId:t?.tournamentId,eventId:r??o?.eventId,context:"setMatchUpStatusBye",drawDefinition:e,matchUp:n})}function FF({tournamentRecord:t,drawDefinition:e,drawPosition:r,matchUps:n,event:o}){n.forEach(i=>{i.drawPositions?.includes(r)&&Db({eventId:o?.eventId,tournamentRecord:t,drawDefinition:e,matchUp:i})})}function kh({drawPositionToAdvance:t,inContextDrawMatchUps:e,sourceDrawPositions:r,tournamentRecord:n,drawDefinition:o,matchUpsMap:i,matchUpId:s,event:a}){Hn({method:"advanceDrawPosition",color:"cyan",drawPositionToAdvance:t});let u=i.drawMatchUps.find(N=>N.matchUpId===s),m=e.find(N=>N.matchUpId===s)?.structureId,{structure:d}=st({drawDefinition:o,structureId:m}),{positionAssignments:l}=Ct({structure:d}),f=l?.filter(N=>N.bye).map(N=>N.drawPosition),g=u?.drawPositions?.find(N=>N!==t),I=g&&f?.includes(g),{targetLinks:{loserTargetLink:h},targetMatchUps:{loserMatchUp:S,winnerMatchUp:T,loserTargetDrawPosition:y}}=nr({inContextDrawMatchUps:e,drawDefinition:o,matchUpId:s});if(T&&T.structureId===d?.structureId&&GF({drawPositionToAdvance:t,inContextDrawMatchUps:e,sourceDrawPositions:r,tournamentRecord:n,drawDefinition:o,winnerMatchUp:T,matchUpsMap:i,event:a}),S&&I&&S.structureId!==d?.structureId){let{roundNumber:N}=S;if(N===1){let E=Cr({structureId:h.target.structureId,drawPosition:y,tournamentRecord:n,drawDefinition:o,event:a});if(E.error)return E}else Nb({loserTargetDrawPosition:y,tournamentRecord:n,loserTargetLink:h,drawDefinition:o,loserMatchUp:S,matchUpsMap:i,event:a})}return{...R}}function GF({drawPositionToAdvance:t,inContextDrawMatchUps:e,sourceDrawPositions:r,tournamentRecord:n,drawDefinition:o,winnerMatchUp:i,matchUpsMap:s,event:a}){let c="advanceWinner",u=s.drawMatchUps.find(L=>L.matchUpId===i.matchUpId),m=e.find(L=>L.matchUpId===i.matchUpId)?.structureId,{structure:d}=st({drawDefinition:o,structureId:m}),{positionAssignments:l}=Ct({structure:d}),g=l?.find(({drawPosition:L})=>L===t)?.bye,I=u.drawPositions?.filter(Boolean),h=l?.filter(L=>I?.includes(L.drawPosition)),S=l?.find(({drawPosition:L})=>L===t),T=r?.find(L=>L!==t),N=(T&&h?.find(({drawPosition:L})=>L===T))?.bye,E=g&&N;if(E&&console.log({isByeAdvancedBye:E}),I?.length>1&&g&&!N)return _({result:{error:ja},stack:c});let A=I?.find(L=>L!==t),U=E,C=[...(u.drawPositions||[]).filter(Boolean),void 0,void 0].slice(0,2),P=C.map(L=>!L&&!U||L===t?(U=!0,t):L).sort(se);if(!U)return console.log("@@@@@@@",{advancingAssignmentIsBye:S,drawPositionToAdvance:t,existingAssignments:h}),_({result:{error:ja},stack:c});let D=l?.find(({drawPosition:L})=>L===A)?.bye,M=l?.find(({drawPosition:L})=>L===t)?.bye;Object.assign(u,{matchUpStatus:M||D?Nt:Qt,score:void 0,winningSide:void 0,drawPositions:P});let v=u.drawPositions.find(L=>!C.includes(L));Hn({method:c,color:"brightyellow",changedDrawPosition:v,pairedDrawPositionIsBye:D,drawPositionIsBye:M}),It({tournamentId:n?.tournamentId,matchUp:u,eventId:a?.eventId,context:c,drawDefinition:o});let{targetLinks:{loserTargetLink:O},targetMatchUps:{loserMatchUp:w,loserTargetDrawPosition:F}}=nr({matchUpId:i.matchUpId,inContextDrawMatchUps:e,drawDefinition:o});if(D||M){let L=D?t:A;if(L)kh({drawPositionToAdvance:L,matchUpId:i.matchUpId,inContextDrawMatchUps:e,tournamentRecord:n,drawDefinition:o,matchUpsMap:s});else if(M&&O&&w)if(w.feedRound)Nb({loserTargetDrawPosition:F,tournamentRecord:n,loserTargetLink:O,drawDefinition:o,loserMatchUp:w,matchUpsMap:s});else{let B=1-i.roundPosition%2,H=w.drawPositions[B],W=Cr({structureId:O.target.structureId,drawPosition:H,tournamentRecord:n,drawDefinition:o,event:a});if(W.error)return W}}}function Nb({loserTargetDrawPosition:t,tournamentRecord:e,loserTargetLink:r,drawDefinition:n,loserMatchUp:o,matchUpsMap:i,event:s}){let{roundNumber:a}=o;Hn({method:"assignFedDrawPositionBye",color:"cyan",loserTargetDrawPosition:t});let p=(i?.mappedMatchUps||{})[o.structureId].matchUps,{initialRoundNumber:m}=us({drawPosition:t,matchUps:p});if(m===a){let d=Cr({structureId:r.target.structureId,drawPosition:t,tournamentRecord:e,drawDefinition:n,event:s});if(d.error)return d}}function Vh({positionAssignments:t,tournamentRecord:e,drawDefinition:r,matchUpsMap:n,structure:o,event:i}){let{matchUps:s}=At({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?Nt:Qt}),It({tournamentId:e?.tournamentId,context:"modifyRoundRobinMatchUpsStatus",eventId:i?.eventId,drawDefinition:r,matchUp:a}))})}function lc(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:Ns};r||(r=m?.participantId);let{activeDrawPositions:d}=Da({drawDefinition:i,structureId:s});return d.includes(n)?{error:Bu}:(e||({matchUps:e}=ne({inContext:!0,drawDefinition:i,matchUpsMap:a})),gU({inContextDrawMatchUps:e,tournamentRecord:o,drawDefinition:i,structureId:s,drawPosition:n,matchUpsMap:a,event:c}).drawPositionCleared?(Mo({tournamentId:o?.tournamentId,drawDefinition:i,structure:u,event:c}),{...R,participantId:r}):{error:pA})}function gU({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:Gt};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===ke)return Vh({positionAssignments:c,tournamentRecord:e,drawDefinition:r,matchUpsMap:o,structure:a}),{drawPositionCleared:u,...R};let p={isCollectionMatchUp:!1},{matchUps:m}=At({drawDefinition:r,matchUpFilters:p,matchUpsMap:o,structure:a,event:s}),{roundProfile:d,roundMatchUps:l}=qe({matchUps:m}),g=(d&&Object.keys(d))?.map(T=>ct(T)),I=n,S=g?.map(T=>{let N=d?.[T]?.pairedDrawPositions?.find(v=>v.includes(I)),E=N?.find(v=>v!==I),A=c.find(v=>v.drawPosition===E),U=d?.[T+1],C=A?.bye,P=U?.pairedDrawPositions?.find(v=>v.includes(E)),D=C&&P&&U&&U.drawPositions?.includes(E),b=N&&{pairedDrawPositionByeAdvancedPair:!D&&P,pairedDrawPosition:E,targetDrawPosition:I,relevantPair:N,roundNumber:T};return D&&(I=E),b}).filter(T=>T?.targetDrawPosition)?.reduce((T,y)=>{let{roundNumber:N,relevantPair:E,targetDrawPosition:A,pairedDrawPosition:U,pairedDrawPositionByeAdvancedPair:C}=y,P={roundNumber:N,targetDrawPosition:A,relevantPair:E},D=C&&{roundNumber:N+1,targetDrawPosition:U,relevantPair:C,subsequentRoundRemoval:!0},M=[P,D].filter(Boolean);return T.concat(...M)},[]);return S?.forEach(({roundNumber:T,targetDrawPosition:y,relevantPair:N})=>{let E=l?.[T].find(A=>Fe(A.drawPositions?.filter(Boolean),N.filter(Boolean)));E&&(kF({inContextDrawMatchUps:t,targetDrawPosition:y,tournamentRecord:e,drawDefinition:r,structureId:i,roundNumber:T,matchUpsMap:o}),Mb({inContextDrawMatchUps:t,positionAssignments:c,tournamentRecord:e,drawDefinition:r,targetMatchUp:E,drawPosition:n,matchUpsMap:o,structure:a,event:s}))}),{tasks:S,drawPositionCleared:u,positionAssignments:c}}function kF({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:Gt};if(a.structureType===ke)return;o=o||ye({drawDefinition:n});let u=(o?.mappedMatchUps||{})[s].matchUps,{initialRoundNumber:p}=us({drawPosition:e,matchUps:u}),m=u?.filter(l=>l.roundNumber>=i&&l.roundNumber!==p&&l.drawPositions?.includes(e)),d=Ct({drawDefinition:n,structureId:s}).positionAssignments??[];return m?.forEach(l=>Mb({drawPosition:e,targetMatchUp:l,inContextDrawMatchUps:t,positionAssignments:d,tournamentRecord:r,drawDefinition:n,matchUpsMap:o,structure:a})),{...R}}function Mb({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??ye({drawDefinition:n});let f=s.mappedMatchUps[a.structureId].matchUps,{initialRoundNumber:g}=us({drawPosition:i,matchUps:f});if(o.roundNumber&&g&&o.roundNumber>g){let P=(o.drawPositions??[]).map(D=>D===i?void 0:D);o.drawPositions=P}if(o.matchUpType===Bt){let M=(t?.find(b=>b.matchUpId===o.matchUpId)?.sides??[]).reduce((b,v,O)=>v.drawPosition===i?O:b,void 0);M!==void 0&&o.sides?.[M]?.lineUp&&(delete o.sides?.[M].lineUp,It({tournamentId:r?.tournamentId,context:`${u}-TEAM`,eventId:c?.eventId,matchUp:o,drawDefinition:n}))}let I=nr({matchUpId:o.matchUpId,inContextDrawMatchUps:t,drawDefinition:n}),{targetLinks:{winnerTargetLink:h},targetMatchUps:{loserMatchUp:S,winnerMatchUp:T,loserMatchUpDrawPositionIndex:y}}=I,E=e.filter(({drawPosition:P})=>o.drawPositions?.includes(P)).filter(P=>P.bye).length,A=E&&Nt||o.matchUpStatus&&[bt,vt].includes(o.matchUpStatus)&&o.matcHUpStatus||o.drawPositions?.length===2&&Qt||void 0;o.matchUpStatus=A,o.matchUpStatus&&[vt,bt].includes(o.matchUpStatus)&&(o.winningSide=void 0);let U=p?.find(P=>!o.drawPositions?.includes(P));if(p?.includes(i)&&m===o.matchUpStatus&&d===o.winningSide||(U&&Hn({method:u,color:"brightyellow",removedDrawPosition:U}),It({tournamentId:r?.tournamentId,eventId:c?.eventId,matchUp:o,context:`${u}-${i}`,drawDefinition:n})),S&&S.structureId!==I.matchUp.structureId&&!E){let{drawPositions:P,roundNumber:D}=S;if(D===1){let M=P[y];gU({structureId:S.structureId,drawPosition:M,inContextDrawMatchUps:t,tournamentRecord:r,drawDefinition:n,matchUpsMap:s})}else{let M=Math.min(...P.filter(Boolean)),b=VF({loserMatchUpDrawPosition:M,inContextDrawMatchUps:t,tournamentRecord:r,drawDefinition:n,loserMatchUp:S,matchUpsMap:s,event:c});if(b.error)return _({result:b,stack:u});let O=(s?.mappedMatchUps||{})[S.structureId].matchUps,{initialRoundNumber:w}=us({drawPosition:M,matchUps:O});w===1&&(Hn({method:u,color:"brightyellow",loserMatchUpDrawPosition:M}),gU({structureId:S.structureId,drawPosition:M,inContextDrawMatchUps:t,tournamentRecord:r,drawDefinition:n,matchUpsMap:s}))}}return T&&T.structureId!==I.matchUp.structureId&&(h.target.feedProfile,tn),{...R}}function VF({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}=Ct({structure:a});if(c?.find(p=>p.drawPosition===t)?.bye){let p=lc({drawPosition:t,structureId:o.structureId,inContextDrawMatchUps:e,tournamentRecord:r,drawDefinition:n,matchUpsMap:i,event:s});if(p.error)return p}return{...R}}function Ei({drawDefinition:t,stages:e}){if(!t)return{error:X};let r=(t?.structures??[]).filter(o=>!e?.length||o.stage&&e.includes(o.stage)),n=pt(r.map(o=>{let{positionAssignments:i}=Ct({structure:o});return i?i.map(gt):[]}).flat().filter(Boolean));return{...R,assignedParticipantIds:n}}function Wn(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 Ys(t){return[gi,Br].includes(t)}function Jm({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:Zr,method:"modifyEntriesStatus",participantIds:o};if(!n&&!m)return{error:Dt};if(i&&!nU.includes(i))return{error:Ol};if(s&&!Rm.includes(s))return{error:Ri};let d="modifyEntriesStatus",l=[];if(!i&&!a)return _({result:{error:rt},info:"Missing entryStatus",stack:d});if(a&&!Mn({extension:a,requiredAttributes:["name"]}))return _({result:{error:G},info:"Invalid extension",context:{extension:a},stack:d});let f=[];m?.drawDefinitions?.forEach(P=>{let D=Ei({stages:p&&[p],drawDefinition:P}).assignedParticipantIds??[];f.push(...D)});let g=r?.participants??[];if(!o.every(P=>{let D=Lo({tournamentParticipants:g,participantId:P})?.participantType;return!(D&&[lt,rn].includes(D)&&Ys(i))&&!(i&&m?.eventType&&D===Tt&&[Jr,jr].includes(m.eventType)&&[kr,...Of].includes(i))}))return{error:Ol};let h=m&&Ht({event:m}).flightProfile,S=h?.flights?.find(P=>P.drawId===u),T=P=>{let D=(P||[]).filter(v=>!p||!v.entryStage||p===v.entryStage).filter(({participantId:v})=>o.includes(v)),M=v=>i&&f.includes(v.participantId)&&!(Of.includes(v.entryStatus)&&Of.includes(i));return D.every(v=>M(v)&&!e?!1:(i&&(v.entryStatus=i,delete v.entryPosition),s&&(v.entryStage=s,delete v.entryPosition),a&&(a.value?yt({element:v,extension:a}):sr({element:v,name:a.name})),!0))?{...R}:{error:Rs}},y=({flight:P,drawDefinition:D})=>{m&&(m.entries=Wn({entries:m.entries??[]})),P&&(P.drawEntries=Wn({entries:P.drawEntries})),D&&(D.entries=Wn({entries:D.entries}))},N=P=>{let{flight:D,drawDefinition:M}=P,b="updateDrawEntries";if(D){let v=T(D.drawEntries);if(v.error)return _({result:v,stack:b})}if(M){let v=T(M.entries);if(v.error)return _({result:v,stack:b});l.includes(M.drawId)||l.push(M.drawId)}return{...R}},E=m?.entries?.find(({entryPosition:P})=>P)??(S?.drawEntries?.find(({entryPosition:P})=>P)||n?.entries?.find(({entryPosition:P})=>P));if(t&&!E&&y({flight:S,drawDefinition:n}),S||n){let P=N({flight:S,drawDefinition:n});if(P.error)return _({result:P,stack:d})}let A=m?.drawDefinitions?.map(({drawId:P})=>P)??[],U=h?.flights?.filter(P=>!A.includes(P.drawId))||[];for(let P of U){let D=P&&N({flight:P});if(D?.error)return _({result:D,stack:d})}let C=h?.flights?.length===1&&(m?.drawDefinitions?.length??0)<=h?.flights?.length;if(!S&&!n&&i&&rU.includes(i))return{error:jA};if(!S&&!n||i===Jn||c&&C){let P=T(m?.entries);if(P?.error)return _({result:P,stack:d});let D;if(i===Jn&&(h?.flights?.every(M=>{let b=T(M.drawEntries);return b.error?(D=b.error,!1):(M.drawEntries=M.drawEntries.filter(({participantId:v})=>!o.includes(v)),!0)}),m?.drawDefinitions?.every(M=>{let b=T(M.entries);return b.error?(D=b.error,!1):(M.entries=M.entries?.filter(({participantId:v})=>!o.includes(v)),!0)})),D)return _({result:{error:D},stack:d})}t&&y({flight:S,drawDefinition:n});for(let P of m?.drawDefinitions??[])l.length&&!l.includes(P.drawId)||Ot({tournamentId:r.tournamentId,eventId:m?.eventId,drawDefinition:P});return{...R}}function So({requireTimeStamp:t,scaleAttributes:e,participant:r}){if(!r)return{error:vi};if(!Pt(e))return{error:G};if(r.timeItems||(r.timeItems=[]),Array.isArray(r.timeItems)){let{accessor:n,scaleType:o,eventType:i,scaleName:s}=e,a=[Ji,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!==Ji)return{error:qu};let g=(n&&cs({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 Cb({publishedSeeding:t,usePublishState:e,withSeeding:r,participant:n,event:o}){let i={},s=m=>[Ji,ao,o.eventType,m].join("."),a=Object.assign({},...(n.timeItems||[]).filter(({itemType:m})=>m.split(".")[1]===ao).map(({itemType:m,itemValue:d})=>({[m]:d}))),c=(t?.stageSeedingScaleNames&&Object.values(t?.stageSeedingScaleNames)||Array.isArray(t?.seedingScaleNames)&&t.seedingScaleNames||[]).map(s),u=jt(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:ao,scaleName:g},h=So({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 Rb({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({},...rf(m??[])):{},l=Object.assign(d,{entryPosition:p,entryStatus:c,entryStage:u,ranking:s,eventId:i});r.events[i]=nt(l,!1,!1,!0),n&&(e&&(r.events[i].seedAssignments=e),o&&(r.events[i].seedValue=o))}function Bh(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===Nt||e[r].scheduleItems.push({...p,scheduledDate:Ut(p?.scheduledDate),scheduledTime:$t(p?.scheduledTime),checkScoreHasValue:Ie({score:d}),matchUpStatus:n,roundPosition:o,structureId:i,matchUpType:s,roundNumber:a,matchUpId:c,potential:u,drawId:m})}function bb({tournamentRecord:t,status:e=Wr}){let r=`${Xo}.${Jo}`;return au({tournamentRecord:t,itemType:r})?.timeItem?.itemValue?.[e]}function vb(t){let{tournamentId:e}=t??{};return!!e}function Lr({event:t,status:e=Wr}){let r=`${Xo}.${Jo}`;return su({itemType:r,event:t})?.timeItem?.itemValue?.[e]}function Zm({drawDetails:t,drawId:e}){return t?.[e]?.publishingDetail?.published}function ps(t){let{tournamentRecord:e,drawDefinition:r,eventIds:n,eventId:o,drawIds:i,drawId:s,event:a}=t??{};if(e&&!vb(e))return{error:G};if(o&&!a)return{error:lr};if(Array.isArray(n)&&n?.length){let d={};for(let l of n){if(!Re(l))return{error:G};let f=je({tournamentRecord:e,eventId:l})?.event;if(!f)return{error:lr};let g=IU({event:f});d[l]=g}return{...R,publishState:d}}if(a){let d=IU({event:a}),l={};if(s)return r?{publishState:{status:{published:!!d.status.publishedDrawIds?.includes(s),drawDetail:d.status.drawDetails?.[s]},...R}}:{error:dr};if(Array.isArray(i)&&i?.length){let f=a.drawDefinitions?.map(zc)??[];for(let g of i){if(!Re(g))return{error:G};if(!f.includes(g))return{error:dr};l[g]={status:{published:!!d.status.publishedDrawIds.includes(g),drawDetail:d.status.drawDetails?.[g]}}}}else l=d;return{...R,publishState:l}}let c=[],u=!1,p={},m=bb({tournamentRecord:e});p.tournament=m??{};for(let d of e?.events??[]){let l=IU({event:d});p[d.eventId]=l,l.status.published&&(c.push(d.eventId),u=!0);for(let{drawId:f}of d.drawDefinitions??[]){let g=l.status?.publishedDrawIds?.includes(f);g&&(p[f]={status:{published:g}})}}return e&&(p.tournament.status={published:u,publishedEventIds:c}),{...R,publishState:p}}function IU({event:t}){let e=Lr({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(zc)||[])n[i]||(n[i]={publishingDetail:{published:!1}});let o=n&&Object.keys(n).length&&Object.keys(n).filter(i=>Zm({drawDetails:n,drawId:i}))||e.drawIds;return{status:{published:o&&o.length>0,publishedDrawIds:o,publishedSeeding:r,drawDetails:n}}}function fu(t,e){return(t||"").localeCompare(e||"")}function Ob({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===vt&&(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 hU(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:y,matchUpSides:N,collectionId:E,matchUpType:A,winningSide:U,matchUpId:C,schedule:P,eventId:D,drawId:M,sides:b}=t,v=i&&b?.length===2&&Object.assign({},...b.map(({sideNumber:O},w)=>{let F=b[1-w].participantId;return O&&{[O]:F}}).filter(Boolean));for(let O of b){let{participantId:w,sideNumber:F,bye:L}=O;if(L)continue;let x=U===F,B=V=>{let Y=o[V]?.participant,$=Y?.participantType,k=[{participantId:V,participantType:$}];if($!==rn)for(let K of Y?.individualParticipantIds||[]){let z=o[K]?.participant;k.push({participantType:z?.participantType,participantId:K})}return k},H=(V,Y)=>{if(s){if(o[V].matchUps[C]={participantWon:x,matchUpType:A,structureId:f,sideNumber:F,matchUpId:C,eventId:D,drawId:M,stage:I},i){let $=B(Y);o[V].matchUps[C].opponentParticipantInfo=$}E&&(o[V].matchUps[C].collectionId=E)}i&&Y&&(o[V].opponents[Y]={participantId:Y,matchUpId:C,eventId:D,drawId:M}),h&&Ob({finishingPositionRange:u,participantMap:o,participantWon:x,finishingRound:p,matchUpStatus:m,participantId:V,stageSequence:d,roundNumber:l,structureId:f,matchUpId:C,drawId:M,stage:I}),(r||e)&&Bh({participantMap:o,participantId:V,matchUpStatus:m,roundPosition:T,matchUpType:A,roundNumber:l,structureId:f,matchUpId:C,schedule:P,drawId:M,score:g})},W=({participant:V,partnerParticipantId:Y})=>{let $=(k,K)=>{k&&(k.partnerParticipantIds||(k.partnerParticipantIds=[]),k.partnerParticipantIds.includes(K)||k.partnerParticipantIds.push(K))};c&&$(V?.draws?.[M],Y),a&&$(V?.events?.[D],Y),s&&$(V?.matchUps?.[C],Y)};if(w&&o[w]){let V=v?.[F];H(w,V);let Y=o[w]?.participant.participantType===lt,$=o[w]?.participant.individualParticipantIds||[];if(y){if(n){let k=K=>o[K].matchUps[y]={participantWon:S===F,matchUpId:y,matchUpType:Bt,sideNumber:F};k(w),$.forEach(k)}if(c&&!o[w].draws[M]){let k=N.find(q=>q.sideNumber===F)?.participant?.participantId,K=o[k]?.draws?.[M]?.entryStatus,z=q=>o[q].draws[M]={entryStatus:K,eventId:D,drawId:M};z(w),$.forEach(z)}}if(Y&&($.forEach(k=>o[k]&&H(k,V)),$.forEach((k,K)=>{let z=$[1-K],q=o[k];q&&W({participant:q,partnerParticipantId:z})}),a&&N)){let k=N.find(K=>K.sideNumber===F)?.participant?.participantId;if(k){let K=o[k]?.events[D];K?(o[w].events[D]={...K},$.forEach(z=>o[z].events[D]={...K})):console.log("Missing teamEntry",{eventId:D,teamParticipantId:k})}}if(U){let k=K=>{x?(o[K].counters[A].wins+=1,o[K].counters.wins+=1,m===vt&&(o[K].counters[A].walkoverWins+=1,o[K].counters.walkoverWins+=1),m===bt&&(o[K].counters[A].defaultWins+=1,o[K].counters.defaultWins+=1)):(o[K].counters[A].losses+=1,o[K].counters.losses+=1,m===vt&&(o[K].counters[A].walkovers+=1,o[K].counters.walkovers+=1),m===bt&&(o[K].counters[A].defaults+=1,o[K].counters.defaults+=1))};k(w),$.forEach(k)}}}}function _b(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,y=b=>{let v=[b];return a[b]?.participant.individualParticipantIds?.forEach(O=>v.push(O)),v.some(O=>!T?.length||T.includes(O))?v:[]},N={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},E=[],A={},U=[],C={},P={},D={},M=({eventType:b,scaleNames:v,participantId:O})=>a[O].participant?.rankings?.[b]?.find(w=>v.includes(w.scaleName))?.scaleValue;for(let b of o?.events||[]){if(e?.eventIds&&!e.eventIds.includes(b.eventId))continue;let{drawDefinitions:v=[],extensions:O=[],eventType:w,eventName:F,category:L,entries:x,eventId:B,gender:H}=b,{flightProfile:W}=Ht({event:b}),V=W?.flights??[],Y=ps({event:b}).publishState;Y&&(C[B]=Y);let $=Y?.status?.publishedSeeding;if(h||I||u){let K=r?Object.assign({},...rf(O??[])):{};P[B]={...K,eventName:F,eventType:w,category:L,eventId:B,gender:H};let z=[L?.categoryName,L?.ageCategoryCode].filter(Boolean);for(let q of x){let{participantId:et}=q;if(!et||!a[et])continue;let Q=M({eventType:w,scaleNames:z,participantId:et}),it,ot;if(I){let Et=a[et].participant;({seedAssignments:it,seedValue:ot}=Cb({publishedSeeding:$,usePublishState:i,withSeeding:I,participant:Et,event:b}))}let mt=Et=>{if(a[Et]?.events?.[B])return;let Me=a[Et];Rb({convertExtensions:r,seedAssignments:it,participant:Me,withSeeding:I,seedValue:ot,eventId:B,ranking:Q,entry:q})};mt(et),(a[et].participant.individualParticipantIds||[]).forEach(mt)}}let k=C?.[B]?.publishedSeeding;if(S||u||I){let K=q=>q?Object.assign({},...q.map(({participantId:et,seedValue:Q,seedNumber:it})=>({[et]:{seedValue:Q,seedNumber:it}}))):void 0,z=pt([...v.map(zc),...V.map(zc)]);for(let q of z){let et=v.find(Wt=>Wt.drawId===q),Q=V?.find(Wt=>Wt.drawId===q),it=et?.entries||Q?.drawEntries,{structures:ot=[],drawOrder:mt,drawName:Xt,drawType:Et}=et??{},Me=Q?.flightNumber,Ee=[L?.categoryName,L?.ageCategoryCode].filter(Boolean),Ce=(et?.structures||[]).sort((Wt,we)=>di(Wt,we)).map(({structureId:Wt,structures:we})=>[Wt,...(we||[]).map(({structureId:ir})=>ir)]).flat(1/0),zt,ve,Ft,Ue,Rt=0,_t=ot.filter(({stage:Wt,stageSequence:we})=>Wt===tt&&we===1||Wt===at).flatMap(Wt=>{let{seedAssignments:we,stageSequence:ir,stage:Oe}=Wt,{positionAssignments:Rr}=Ct({structure:Wt});return Oe===tt?(Rt=Rr?.length??0,Ft=Rr,Ue=we):ir===1&&(zt=Rr,ve=we),Rr}).map(({participantId:Wt})=>Wt).filter(Boolean),oe=K(Ue),qt=K(ve),pe=et?it.filter(({participantId:Wt})=>_t.includes(Wt)):it,he=!i||k?.published&&(k?.drawIds?.length===0||k?.drawIds?.includes(q));for(let Wt of pe){let{entryStatus:we,entryStage:ir,entryPosition:Oe,participantId:Rr}=Wt,Se=M({participantId:Rr,scaleNames:Ee,eventType:w}),Pe=Ir=>{if(a[Ir].draws?.[q])return;let si=I&&he,ze=si?{}:void 0,_n=si?oe?.[Rr]?.seedValue||oe?.[Rr]?.seedNumber:void 0,Ni=_n?oe?.[Rr]:void 0,Yi=si?qt?.[Rr]?.seedValue||qt?.[Rr]?.seedNumber:void 0,yn=Yi?qt?.[Rr]:void 0;ze&&_n&&(ze[tt]=Ni),ze&&Yi&&(ze[at]=yn);let Lc=_n||Yi;Lc&&(a[Ir].participant.seedings[w]||(a[Ir].participant.seedings[w]=[]),Ni&&a[Ir].participant.seedings[w].push({...Ni,scaleName:q}),yn&&a[Ir].participant.seedings[w].push({...yn,scaleName:q}),ze&&(a[Ir].events[B].seedAssignments||(a[Ir].events[B].seedAssignments={}),Object.keys(ze).forEach(qi=>a[Ir].events[B].seedAssignments[qi]=ze[qi]))),(S||u)&&(a[Ir].draws[q]=nt({seedAssignments:ze,entryPosition:Oe,entryStatus:we,entryStage:ir,seedValue:Lc,eventId:B,ranking:Se,drawId:q},!1,!1,!0))};[Br,gi].includes(we)||(Pe(Rr),(a[Rr].participant.individualParticipantIds||[])?.forEach(Pe))}let mr=(et?.structures??[]).reduce((Wt,we)=>(Wt.includes(we.stage)||Wt.push(we.stage),Wt),[]),xe=(et?.links??[]).length;D[q]={qualifyingPositionAssignments:zt,qualifyingSeedAssignments:ve,mainPositionAssignments:Ft,qualifyingSeedingMap:qt,mainSeedAssignments:Ue,orderedStructureIds:Ce,mainSeedingMap:oe,flightNumber:Me,linksCount:xe,drawOrder:mt,drawName:Xt,drawType:Et,drawSize:Rt,drawId:q,stages:mr}}}if(u||m||d||l||f||g||S){let K=!!m||c,z=ho({afterRecoveryTimes:!!m,policyDefinitions:n,tournamentRecord:o,inContext:!0,contextProfile:s,participantMap:a,nextMatchUps:K,event:b})?.matchUps??[];for(let q of z){let{finishingPositionRange:et,potentialParticipants:Q,tieMatchUps:it=[],sides:ot=[],winningSide:mt,matchUpType:Xt,matchUpId:Et,eventId:Me,drawId:Ee,collectionId:Ce,stageSequence:zt,finishingRound:ve,matchUpStatus:Ft,roundPosition:Ue,roundNumber:Rt,structureId:_t,schedule:oe,score:qt,stage:pe}=q;A[Et]=q;let he={finishingPositionRange:et,finishingRound:ve,stageSequence:zt,roundPosition:Ue,collectionId:Ce,roundNumber:Rt,structureId:_t,schedule:oe,eventId:Me,drawId:Ee,score:qt,stage:pe};hU({...he,...N,matchUpStatus:Ft,winningSide:mt,matchUpType:Xt,matchUpId:Et,sides:ot});for(let mr of it){let{winningSide:xe,sides:Wt=[],matchUpId:we,matchUpStatus:ir,matchUpType:Oe}=mr;hU({...he,...N,winningSide:xe,tieWinningSide:mt,matchUpTieId:Et,matchUpId:we,sides:Wt,matchUpSides:ot,matchUpStatus:ir,matchUpType:Oe})}Array.isArray(Q)&&(K||m||p)&&Q.flat().map(gt).filter(Boolean)?.forEach(xe=>{y(xe)?.forEach(we=>{a[we]&&(a[we].potentialMatchUps[Et]=nt({tournamentId:o?.tournamentId,matchUpId:Et,eventId:Me,drawId:Ee}))}),(m||p)&&Bh({potential:!0,participantMap:a,participantId:xe,matchUpStatus:Ft,roundPosition:Ue,structureId:_t,matchUpType:Xt,roundNumber:Rt,matchUpId:Et,schedule:oe,drawId:Ee,score:qt})})}U.push(...z)}}if(l||u||m){let b=Object.values(a);for(let v of b){let{wins:O,losses:w,[Kt]:{wins:F,losses:L},[wt]:{wins:x,losses:B}}=v.counters,H=(W,V,Y)=>{let $=V+Y,k=V,K=$&&k/$;v.statistics[W]={denominator:$,numerator:k,statValue:K,statCode:W}};if(l&&(H(Gm,O,w),H(`${Gm}.${Kt}`,F,L),H(`${Gm}.${wt}`,x,B)),u){let W=(V=[])=>Math.abs(V[0]-V[1]);for(let V of Object.keys(v.draws)){let{orderedStructureIds:Y=[],flightNumber:$}=D[V]||{};if(v.structureParticipation&&Y.length){let k,K=0,z=Y.map(q=>{let et=v.structureParticipation[q];if(!et)return;k||(k=et?.finishingPositionRange),W(k)>W(et?.finishingPositionRange)&&(k=et?.finishingPositionRange);let Q=et.stage!==at;return Q&&(K+=1),nt({...et,participationOrder:Q?K:void 0,flightNumber:$})}).filter(Boolean);v.draws[V]&&(v.draws[V].finishingPositionRange=k,v.draws[V].structureParticipation=z)}}}if(m){let W=Pt(m)?m.scheduledMinutesDifference:0,V=v.scheduleItems||[],Y=v.potentialMatchUps||{},$=V.reduce((K,z)=>{let{scheduledDate:q,scheduledTime:et}=z;return K[q]||(K[q]=[]),et&&K[q].push(z),K},{});Object.values($).forEach(K=>K.sort(YI));for(let K of V){let{typeChangeTimeAfterRecovery:z,timeAfterRecovery:q,scheduledDate:et,scheduledTime:Q}=K,it=$[et],ot=Vt(Q);for(let mt of it){if(mt.matchUpId===K.matchUpId||[vt,bt].includes(mt.matchUpStatus)&&!mt.checkScoreHasValue)continue;let Me=K.matchUpType!==mt.matchUpType&&z||q,Ee=K.drawId===mt.drawId,Ce=Y[K.matchUpId]&&Y[mt.matchUpId],zt=Vt(mt.scheduledTime),ve=Math.abs(zt-ot),Ft=zt>=ot;if((W&&!isNaN(W)?ve<=W:Ft&&Vt(mt.scheduledTime)<Vt(Me))&&!(Ce&&Ee)&&Ft){let Rt=[K.matchUpId,mt.matchUpId].sort(fu).join("|");v.scheduleConflicts[Rt]={priorScheduledMatchUpId:K.matchUpId,matchUpIdWithConflict:mt.matchUpId}}}}let k=v.participant.participantId;Object.keys(v.scheduleConflicts).length&&E.push(k),a[k].scheduleConflicts=v.scheduleConflicts}}}return{participantIdsWithConflicts:E,eventsPublishStatuses:C,derivedEventInfo:P,derivedDrawInfo:D,mappedMatchUps:A,participantMap:a,matchUps:U}}function gu({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=qs(l)&&e?.events?.filter(y=>l?.includes(y.eventId))||e?.events||[],I=o&&BF({drawEntryStatuses:o,tournamentEvents:g}),h=s&&HF({eventEntryStatuses:s,tournamentEvents:g}),S=i!==void 0&&[!0,!1].includes(i)&&g.reduce((y,N)=>y.concat(...(N.drawDefinitions||[]).map(E=>ih({drawDefinition:E}).allPositionedParticipantIds).filter(Boolean)),[]),T=y=>n?.reduce((N,E)=>{let{accessor:A,value:U}=E,{values:C}=cs({element:y,accessor:A});return N&&C?.includes(U)},!0);if(r=r?.filter(y=>{let N=Vn({element:y,itemType:sc})?.timeItem?.itemValue,{participantRoleResponsibilities:E,participantType:A,participantRole:U,participantId:C,person:P}=y,D=Array.isArray(f)&&f?.length&&P?.sex&&f.includes(P.sex);return d?f&&D||i&&S.includes(C)||i===!1&&!S.includes(C)||I?.includes(C)||h?.includes(C)||p?.includes(C)||m&&N===m||u&&A&&qs(u)&&u.includes(A)||a&&U&&qs(a)&&a.includes(U)||c&&qs(E)&&qs(c)&&c.find(M=>E?.includes(M))||n?.length&&qs(n)&&T(y):(!f||D)&&(i===void 0||i&&S.includes(C)||i===!1&&!S.includes(C))&&(!I||I.includes(C))&&(!h||h.includes(C))&&(!p||p.includes(C))&&(!m||N===m)&&(!u||A&&qs(u)&&u.includes(A))&&(!a||U&&qs(a)&&a.includes(U))&&(!c||qs(E)&&qs(c)&&c.find(M=>E?.includes(M)))&&(!n?.length||qs(n)&&T(y))}),g.length&&l){let y=g.filter(N=>l.includes(N.eventId)).map(N=>{let E=(N.entries||[]).map(U=>U.participantId);if(ie(go)(N.eventType))return E;let A=(e?.participants??[]).filter(U=>E.includes(U.participantId)).map(U=>U.individualParticipantIds).flat(1);return E.concat(...A)}).flat(1);r=r?.filter(N=>y.includes(N.participantId))}return r}function qs(t){return t&&Array.isArray(t)&&t.length}function BF({drawEntryStatuses:t,tournamentEvents:e}){let r=({entryStatus:n})=>Array.isArray(t)?t.includes(n):!0;return pt(e.reduce((n,o)=>{let{flightProfile:i}=Ht({event:o}),s=i?.flights?.map(({drawEntries:c})=>Array.isArray(c)?c.filter(r).map(gt):[]).flat()||[],a=o.drawDefinitions?.map(({entries:c})=>c?c.filter(r).map(gt):[])||[];return n.concat(...s,...a)},[]))}function HF({eventEntryStatuses:t,tournamentEvents:e}){return pt(e.reduce((r,n)=>{let o=(n.entries||[]).filter(({entryStatus:i})=>Array.isArray(t)?t.includes(i):!0).map(gt);return r.concat(...o)},[]))}function Yt(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:y,withDraws:N,withISO2:E,withIOC:A}=t;if(!c)return{error:j};(h||o)&&Yr({tournamentRecord:c});let{participantMap:U}=gh({convertExtensions:i,tournamentRecord:c,withSignInStatus:p,withScaleValues:d,internalUse:S,withISO2:E,withIOC:A}),C=_b({withMatchUps:h??o,withEvents:y??o,withDraws:N??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:P,eventsPublishStatuses:D,derivedEventInfo:M,derivedDrawInfo:b,mappedMatchUps:v}=C,O=C.matchUps;U=C.participantMap;let w=u??n,F=({potentialMatchUps:Y,scheduleConflicts:$,scheduleItems:k,participant:K,statistics:z,opponents:q,matchUps:et,events:Q,draws:it})=>{let ot=Object.values(it),mt=Object.values(q);return I&&ot?.forEach(Xt=>{Xt.opponents=mt.filter(Et=>Et.drawId===Xt.drawId)}),nt({...K,scheduleConflicts:u?Object.values($):void 0,draws:N||o?ot:void 0,events:y||o?Object.values(Q):void 0,matchUps:h||o?Object.values(et):void 0,opponents:I?mt:void 0,potentialMatchUps:w?Object.values(Y):void 0,statistics:g?Object.values(z):void 0,scheduleItems:a?k:void 0},!1,!1,!0)},L=new Map;for(let Y of Object.keys(U))L.set(Y,F(U[Y]));let x=[...L.values()],H=s?.[ws]?.participant,W=gu({participants:x,participantFilters:r,tournamentRecord:c});if(e){let Y=Pt(e)?e:void 0;for(let $ of W)for(let k of $.individualParticipantIds??[]){$.individualParticipants||($.individualParticipants=[]);let K=L.get(k);$.individualParticipants.push(Y?_i({template:Y,source:K}):K)}}let V=H?W.map(Y=>_i({source:Y,template:H})):W;return{participantIdsWithConflicts:P,eventsPublishStatuses:D,derivedEventInfo:M,derivedDrawInfo:b,mappedMatchUps:v,participantMap:U,participants:V,...R,matchUps:O}}function fc({participantId:t,drawDefinition:e,entryStatus:r,entryStage:n}){if(!e)return{error:X};let o=e.entries?.find(i=>i.participantId===t&&(!r||r===i.entryStatus)&&(!n||n===i.entryStage));return t&&o}function ms(t){let{provisionalPositioning:e,drawDefinition:r,stageSequence:n,structureId:o,stage:i}=t;if(!r)return{error:X};let{entryProfile:s}=cu({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===ke){let S=f.structures?.length??0,T=l.source.finishingPositions?.length??0;h=S*T}else h=At({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 yp({stage:t,drawDefinition:e}){let{entryProfile:r}=cu({drawDefinition:e});return r?.[t]?.drawSize||0}function xb(t){let{provisionalPositioning:e,drawDefinition:r,stageSequence:n,stage:o}=t,i=yp({stage:o,drawDefinition:r}),{qualifiersCount:s}=ms({provisionalPositioning:e,drawDefinition:r,stageSequence:n,stage:o});return i&&i-s}function SU({stage:t,drawDefinition:e}){return!!(t===We||_f({stage:t,drawDefinition:e})&&yp({stage:t,drawDefinition:e}))}function TU({entryStatus:t=Vr,drawDefinition:e,stageSequence:r,stage:n}){if(t===kr)return GR({stage:n,drawDefinition:e})?{positionsAvailable:1/0,...R}:{error:WA};let o=xb({drawDefinition:e,stageSequence:r,stage:n}),i=kR({drawDefinition:e,stage:n}),s=hh({entryStatus:uu,drawDefinition:e,stage:n}),a=hh({entryStatus:Vr,drawDefinition:e,stage:n}),c=s+a,u=c>=o,p=o-c;return n!==We&&u?{error:DI}:t===uu?s<i?{...R}:{error:DI}:{positionsAvailable:p,...R}}function Hh(t){let{suppressDuplicateEntries:e=!0,entryStatus:r=Vr,entryStageSequence:n,entryStage:o=tt,ignoreStageSpace:i,drawDefinition:s,entryPosition:a,participant:c,roundTarget:u,extensions:p,extension:m,drawType:d,event:l}=t,f="addDrawEntry";if(!s)return{error:X};if(!o)return{error:SI};if(d!==Xr&&!SU({stage:o,drawDefinition:s}))return _({result:{error:Ri},stack:f});let g=TU({stageSequence:n,stage:o,drawDefinition:s,entryStatus:r});if(!i&&!g.success&&(!d||d!==Xr))return{error:g.error};if(m&&!Mn({extension:m}))return _({result:{error:G},info:"Invalid extension",context:{extension:m},stack:f});let I=t.participantId||c?.participantId;if(!I)return _({result:{error:ee},stack:f});let h=r===es&&fc({participantId:I,drawDefinition:s,entryStatus:r}),S=o===We&&fc({participantId:I,drawDefinition:s,entryStage:o}),T=fc({participantId:I,drawDefinition:s}),y=r!==es&&o!==We&&T;if(y)return e?(St({payload:{drawId:s.drawId,eventId:l?.eventId,error:cm,participantId:I},topic:ah}),{...R}):_({result:{error:cm},context:{participantId:I},stack:f});if(h||S)return _({context:{invalidEntry:y,invalidLuckyLoser:h,invalidVoluntaryConsolation:S},result:{error:Yu},stack:f});let N=nt({entryStageSequence:n,participantId:I,entryPosition:a,entryStatus:r,entryStage:o,extensions:p});return m&&yt({element:N,extension:m}),u&&yt({extension:{name:"roundEntry",value:u},element:N}),s.entries||(s.entries=[]),s.entries.push(N),Ot({drawDefinition:s}),{...R}}function wb(t){let e="addDrawEntries",{suppressDuplicateEntries:r=!0,entryStatus:n=Vr,stage:o=tt,autoEntryPositions:i=!0,ignoreStageSpace:s,participantIds:a,drawDefinition:c,stageSequence:u,roundTarget:p,extension:m,event:d}=t;if(!o)return{error:SI};if(!c)return{error:X};if(!Array.isArray(a))return{error:Kr};if(!SU({stage:o,drawDefinition:c}))return{error:Ri};if(m&&!Mn({extension:m}))return _({result:{error:G},info:"Invalid extension",context:{extension:m},stack:e});let l=TU({drawDefinition:c,stageSequence:u,entryStatus:n,stage:o});if(!s&&!l.success)return{error:l.error};let f=l.positionsAvailable??0;if(!s&&o!==We&&f<a.length)return{error:vl};let g=[],I=c.drawId,h=d?.eventId,S=a.reduce((T,y)=>{let N=n===es&&fc({participantId:y,drawDefinition:c,entryStatus:n}),E=o===We&&fc({entryStage:o,drawDefinition:c,participantId:y}),A=fc({participantId:y,drawDefinition:c});return n!==es&&o!==We&&A&&(g.push(y),r&&St({payload:{error:cm,participantId:y,eventId:h,drawId:I},topic:ah})),N||E?T.concat(y):T},[]);return g.length&&r?_({context:{eventId:h,drawId:I,duplicateEntries:g},result:{error:cm},stack:e}):(a.filter(T=>T&&!S.includes(T)).forEach(T=>{let y={entryStageSequence:u,entryStage:o,participantId:T,entryStatus:n};m&&yt({element:y,extension:m}),p&&yt({extension:{name:ln,value:p},element:y}),c.entries||(c.entries=[]),c.entries.push(y)}),i&&(c.entries=Wn({entries:c.entries})),Ot({drawDefinition:c}),S?.length||g?.length?{info:"some participantIds could not be added",participantIdsNotAdded:S,duplicateEntries:g,...R}:{...R})}function qf({suppressDuplicateEntries:t=!0,autoEntryPositions:e=!0,entryStageSequence:r,ignoreStageSpace:n,drawDefinition:o,participantIds:i,entryStatus:s,roundTarget:a,entryStage:c,extension:u,drawId:p,event:m}){if(!i?.length)return{error:Eo};if(!m)return{error:lr};if(!p)return{error:$r};let d=(m.entries||[]).map(gt);if(i.filter(I=>!d.includes(I)).length)return{error:EA};if(o){let I=wb({stageSequence:r,suppressDuplicateEntries:t,autoEntryPositions:e,stage:c,ignoreStageSpace:n,drawDefinition:o,participantIds:i,entryStatus:s,roundTarget:a,extension:u});if(I.error)return I}let{flightProfile:f}=Ht({event:m}),g=f?.flights.find(I=>I.drawId===p);return g?.drawEntries&&(i.forEach(I=>{let h=s===es&&yU({participantId:I,entryStatus:s,flight:g}),S=c===We&&yU({participantId:I,entryStage:c,flight:g});!(s!==es&&c!==We&&yU({flight:g,participantId:I}))&&!h&&!S&&g.drawEntries.push({participantId:I,entryStatus:s,entryStage:c})}),e&&(g.drawEntries=Wn({entries:g.drawEntries}))),{...R}}function yU({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 gc({autoEntryPositions:t=!0,participantIds:e=[],entryStatuses:r,stage:n,event:o}){let i="removeEventEntries";if(!o?.eventId)return{error:Dt};if(!Array.isArray(e)||e.some(m=>!Re(m)))return _({result:{error:Zr},stack:i});let s=(o.drawDefinitions??[]).flatMap(m=>Ei({drawDefinition:m}).assignedParticipantIds??[]),a=(r?.length&&o.entries?.filter(m=>m.entryStatus&&r.includes(m.entryStatus))||[]).map(gt).filter(m=>!s.includes(m)),c=(n&&o.entries?.filter(m=>m.entryStage&&m.entryStage===n)||[]).map(gt).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=jt(a,c):a.length?e=a:c.length&&(e=c),e?.length&&s.some(m=>e.includes(m)))return _({result:{error:Rs},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=Wn({entries:o.entries}));let{flightProfile:p}=Ht({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 AU={[Qe]:{policyName:"matchUpActionsDefault",enabledStructures:[{stages:[],stageSequences:[],enabledActions:[],disabledActions:[]}],participants:{enforceCategory:!0,enforceGender:!0},processCodes:{substitution:["RANKING.IGNORE","RATING.IGNORE"]},substituteAfterCompleted:!1,substituteWithoutScore:!1}},ds=AU;function to(t){let{suppressDuplicateEntries:e=!0,entryStatus:r=Vr,autoEntryPositions:n=!0,enforceGender:o=!0,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(!Array.isArray(t.participantIds))return _({result:{error:Kr},stack:I});let h=pt(t.participantIds??[]);if(!g)return{error:Dt};if(!h?.length)return _({result:{error:Eo},stack:I});if(!g?.eventId)return{error:lr};let S=ht({tournamentRecord:c,event:g}).appliedPolicies??{},T=s?.[Qe]??S?.[Qe]??ds[Qe],y=(o??T?.participants?.enforceGender)!==!1,N=[],E=[];if(d&&(!Array.isArray(d)||!d.every(O=>Mn({extension:O})))||l&&!Mn({extension:l}))return _({context:nt({extension:l,extensions:d}),result:{error:G},info:"Invalid extension(s)",stack:I});let A=!!c,U=[],C,P=c?.participants?.filter(O=>{if(!h.includes(O.participantId))return!1;let w=ie(Kt)(g.eventType)&&O.participantType===Tt&&!Ys(r),F=g.eventType===wt&&O.participantType===lt;return w&&(!g.gender||!y||[Ur,In].includes(g.gender)||g.gender===O.person?.sex)||F&&!Ys(r)||g.eventType===wt&&O.participantType===Tt&&Ys(r)?!0:w&&g.gender&&y&&![Ur,In].includes(g.gender)&&g.gender!==O.person?.sex?(U.push({participantId:O.participantId,sex:O.person?.sex}),!1):g.eventType===xt&&(O.participantType===xt||Ys(r)&&O.participantType===Tt)}).map(O=>O.participantId)??[],D=h.filter(O=>!A||P.includes(O));g.entries||(g.entries=[]);let M=g.entries.map(O=>O.participantId||O.participant?.participantId);if(D.forEach(O=>{if(!M.includes(O)){let w=nt({participantId:O,entryStatus:r,entryStage:a,extensions:d});l&&yt({element:w,extension:l}),m&&yt({extension:{name:ln,value:m},element:w}),i&&(w.entryStageSequence=i),N.push(w.participantId),g.entries?.push(w)}}),f&&!Ys(a)){let O=qf({participantIds:D,suppressDuplicateEntries:e,autoEntryPositions:n,entryStageSequence:i,ignoreStageSpace:u,drawDefinition:p,entryStatus:r,roundTarget:m,entryStage:a,extension:l,drawId:f,event:g});O.error&&(C=O.error)}if(g.eventType&&[yi,jr].includes(g.eventType)){let O=(g.entries||[]).map(B=>B.participantId),w=(g.entries||[]).filter(B=>Ys(B.entryStatus)).map(B=>B.participantId),L=(c?.participants??[]).filter(B=>O.includes(B.participantId)&&B.participantType&&[lt,xt].includes(B.participantType)).map(B=>B.individualParticipantIds).flat(1/0),x=w.filter(B=>L.includes(B));x.length&&(E.push(...x),gc({participantIds:x,autoEntryPositions:!1,event:g}))}if(D.length!==h.length)return _({context:{mismatchedGender:U,gender:g.gender},result:{error:Kr},stack:I});n&&(g.entries=Wn({entries:g.entries||[]}));let v=N.length-E.length;return _({result:{...R,addedEntriesCount:v},stack:I,info:C})}var EU="ADMINISTRATION",WF="CAPTAIN",jF="COACH",be="COMPETITOR",UU="MEDIA",PU="MEDICAL",$f="OFFICIAL",DU="OTHER",NU="SECURITY",td={ADMINISTRATION:EU,CAPTAIN:WF,COACH:jF,COMPETITOR:be,MEDIA:UU,MEDICAL:PU,OFFICIAL:$f,OTHER:DU,SECURITY:NU};function Kf({addIndividualParticipantsToEvents:t,individualParticipantIds:e,groupingParticipantId:r,tournamentRecord:n,suppressErrors:o}){let i="removeIndividualParticipantIds";if(!n)return _({result:{error:j},stack:i});if(!r||!e)return _({result:{error:rt},stack:i});let a=(n.participants??[]).find(m=>m.participantId===r);if(!a)return _({result:{error:re},stack:i});if(![xt,Er].includes(a.participantType))return _({result:{participantType:a.participantType,error:an},stack:i});let c=Lb({individualParticipantIds:e,groupingParticipant:a,tournamentRecord:n,suppressErrors:o}),{removed:u,error:p}=c;if(p)return _({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));to({participantIds:l,entryStatus:Br,tournamentRecord:n,event:m})}}return u&&St({topic:Xe,payload:{tournamentId:n.tournamentId,participants:[a]}}),{...R,...c}}function Lb({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}=Yt({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||Ie({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}=dt({element:S,name:Do}),y=T?.value[e.participantId];T&&y&&(T.value[e.participantId]=y.filter(E=>E.participantId!==l),yt({element:S,extension:T}),Sa({drawDefinition:S}));let N=or({drawDefinition:S,inContext:!1}).matchUps??[];for(let E of N){let A=E.sides??[];for(let U of A){let C=U.lineUp??[];C.find(D=>D.participantId===l)&&(U.lineUp=C.filter(D=>D.participantId!==l),It({tournamentId:r?.tournamentId,drawDefinition:S,matchUp:E}))}}}}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:ju}||d}function Ap({participantRole:t=be,individualParticipantIds:e=[],groupingTypes:r=[rn,Er],tournamentRecord:n}){if(!n)return{error:j};let o=n.participants??[],{participants:i,mappedMatchUps:s}=Yt({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}=Lb({groupingParticipant:c,individualParticipantIds:e,tournamentRecord:n,mappedMatchUps:s,participants:i});u&&a++}),a?R:{error:kA}}function ki(t){if(!t?.tournamentRecord)return{error:j};if(!t?.participantIds?.length)return{error:Eo};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===Ve).map(l=>l?.drawDefinitions?.map(({drawId:f})=>f)).flat(1/0),s=Yt({participantFilters:{participantIds:n},tournamentRecord:r,withDraws:!0}).participants??[],a=()=>{let f=(le({matchUpFilters:{drawIds:i,matchUpTypes:[wt]},tournamentRecord:r}).matchUps??[]).map(({sides:g})=>g?.map(({participantId:I})=>I)).flat().filter(Boolean);return jt(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:Rs};let p={},m={};for(let l of r.events||[]){let f=gc({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===lt&&l.individualParticipantIds.some(g=>n.includes(g));if(!f&&l.participantType===Ve&&l.individualParticipantIds.some(g=>n.includes(g))&&(l.individualParticipantIds=l.individualParticipantIds.filter(g=>!n.includes(g))),f&&e&&[lt,xt].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(Ap({individualParticipantIds:n,tournamentRecord:r}),e)for(let l of r.events||[]){let g=p[l.eventId].map(I=>m[I]||[]).flat();to({participantIds:g,entryStatus:Br,tournamentRecord:r,event:l})}return d&&St({payload:{participantIds:n,tournamentId:r.tournamentId},topic:If}),d?{...R,participantsRemovedCount:d}:{error:ju}}function Wh({selected:t=!0,drawDefinition:e,entryStatuses:r,drawId:n,event:o,stage:i}){let s=o.entries??[];if(n){let{flightProfile:c}=Ht({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&&wr.includes(c.entryStatus)));return{entries:s,stageEntries:a}}function MU({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 _({result:{error:ee},stack:a});if(!s)return{error:Dt};if(!s.eventType||![yi,jr].includes(s.eventType))return _({result:{error:_o},stack:a});let c=e.participants??[],u=c.find(S=>S.participantId===n);if(!u)return _({result:{error:re},stack:a});if(!u.participantType||![lt,rn].includes(u.participantType)||u.participantType===rn&&s.eventType!==jr||u.participantType===lt&&s.eventType!==yi)return{error:an};let m=(s.entries??[]).find(S=>S.participantId===n);if(!m)return{error:PI};let{stageEntries:d}=Wh({selected:!1,drawDefinition:r,drawId:o,event:s,stage:i}),l=d.map(gt),f=c.filter(({participantId:S})=>l.includes(S)).map(({individualParticipantIds:S})=>S).flat().filter(Boolean),g=u.individualParticipantIds?.filter(S=>io(S,f).length===1),I=gc({participantIds:[n],event:s});if(I.error||g?.length&&(I=to({participantIds:g,entryStatus:Br,entryStage:m.entryStage,tournamentRecord:e,drawDefinition:r,drawId:o,event:s}),I.error))return I;let h;return t&&ki({participantIds:[n],tournamentRecord:e}).success&&(h=!0),{...R,participantRemoved:h}}function zf({removeGroupParticipant:t,tournamentRecord:e,drawDefinition:r,participantId:n,drawId:o,event:i}){return MU({removeGroupParticipant:t,tournamentRecord:e,drawDefinition:r,participantId:n,drawId:o,event:i})}function CU(t){if(!t.tournamentRecord)return{error:j};let{participantIds:e,...r}=t,n=0,o=[];for(let i of e){let s=MU({participantId:i,...r});s.success&&(n+=1),s.error&&o.push(s.error)}return n?{destroyedCount:n,...R}:{error:o}}function Iu(t){let{tournamentRecord:e,replaceWithBye:r,drawDefinition:n,destroyPair:o,entryStatus:i,matchUpsMap:s,drawId:a}=t,c="removeDrawPositionAssignment",u=lc(t);if(u.error)return _({result:u,stack:c});let{participantId:p}=u,{drawPosition:m,event:d,structureId:l}=t,f=ht({tournamentRecord:e,drawDefinition:n,event:d}).appliedPolicies??{};if([kr,Jn].includes(i)&&p){let{tournamentRecord:h}=t,{participant:S}=fo({tournamentRecord:h,participantId:p}),{participantType:T,individualParticipantIds:y}=S??{};if(o&&T===lt){let N=zf({tournamentRecord:h,drawDefinition:n,participantId:p,event:d});if(N.error)return _({result:N,stack:c});y&&Jm({participantIds:y,tournamentRecord:h,drawDefinition:n,entryStatus:i,drawId:a,event:d})}else Jm({participantIds:[p],tournamentRecord:h,drawDefinition:n,entryStatus:i,drawId:a,event:d})}if(r){let h=Cr({tournamentRecord:e,drawDefinition:n,drawPosition:m,structureId:l,matchUpsMap:s,event:d});if(h.error)return _({result:h,stack:c})}let{structure:g}=st({drawDefinition:n,structureId:l});return wm({structure:g,drawPositions:[m]}),ru({appliedPolicies:f,drawDefinition:n,positionAction:{name:"removeDrawPositionAssignment",replaceWithBye:r,drawPosition:m,entryStatus:i,structureId:l}}),u}function RU(t){return Object.assign(t,{entryStatus:Jn}),Iu(t)}function jh(t){return Re(t)?t.split(" ").map(e=>e.split("").map((r,n)=>n?r.toLowerCase():r.toUpperCase()).join("")).join(" "):t}function $e(t){return Re(t)?jh(t.replace(/_/g," ")):""}var ls=({finishingPosition:t=wi,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:y})=>y).filter(Boolean);return I?S.structures=I:(S.matchUps=m,S.positionAssignments=pt(T).sort((y,N)=>y-N).map(y=>({drawPosition:y}))),S},on=ls;function Qf({structureName:t=$e(We),structureAbbreviation:e,drawDefinition:r,matchUpType:n,structureId:o}){if(!r)return{error:X};let i=on({stage:We,structureAbbreviation:e,structureName:t,matchUps:[],structureId:o,matchUpType:n});return r.structures||(r.structures=[]),r.structures.push(i),Ot({drawDefinition:r,structureIds:[i.structureId]}),{...R}}function Xf({drawPositions:t}){if(!t?.length)return{error:Ya};let e=o=>t.filter(i=>i!==o).map(i=>[o,i]),r=[].concat(...(t??[]).map(e)),n=pt(r.map(Jf)).map(o=>o.split("|").map(i=>+i));return{groupMatchUps:r,uniqueMatchUpGroupings:n}}function Jf(t=[]){return!Array.isArray(t)||!t.length?"":[...t].sort(se).join("|")}function bU({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 Jf(l)}))}function YF({rounds:t,hash:e}){return t?.length?t?.reduce((r,n,o)=>n.includes(e)?o+1:r,void 0):{error:rt}}var Fb={getRoundRobinGroupMatchUps:Xf,determineRoundNumber:YF,drawPositionsHash:Jf,groupRounds:bU};function Ma(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??$e(tt),{groupCount:h,groupSize:S}=qF({structureOptions:o,appliedPolicies:i,drawSize:d}),T=Fs,y,N=Z(1,h+1).map(A=>{let U=$F({groupSize:S,structureOrder:A,matchUpType:c,drawSize:d,idPrefix:l,isMock:f});y=Array.isArray(U)?Math.max(...U.map(({roundNumber:P})=>P??0)):0;let C=m?.[A-1]??`${e} ${A}`;return ls({structureId:g?.pop(),structureType:cp,finishingPosition:T,structureOrder:A,structureName:C,matchUps:U})}),E=ls({structureId:p??g?.pop(),structureType:ke,finishingPosition:T,seedingProfile:s,structureName:I,stageSequence:n,structures:N,stage:a});return u&&yt({extension:{name:ln,value:u},element:E}),{structures:[E],maxRoundNumber:y,groupCount:h,links:[],groupSize:S,...R}}function qF({appliedPolicies:t,structureOptions:e,drawSize:r}){let n=e?.groupSize,o=e?.groupSizeLimit||8,{validGroupSizes:i}=Ep({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 Ep({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 $F({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=Xf({drawPositions:c}).uniqueMatchUpGroupings??[],p=bU({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=Jf(f),I=d(g),h=[1,n],S=KF({structureOrder:t,drawPositions:f,roundNumber:I,idPrefix:o,uuids:s}),T={matchUpStatus:I?Qt:Nt,matchUpType:e,finishingPositionRange:{winner:h,loser:h},drawPositions:f,roundNumber:I,matchUpId:S};return i&&(T.isMock=!0),T}}function KF({structureOrder:t,drawPositions:e,roundNumber:r,idPrefix:n,uuids:o}){return n?`${n}-${t}-${r}-DP-${e.join("-")}`:o?.pop()||Mt()}function Zf(t){let{roundRobinGroupsCount:e,participantsCount:r,cluster:n}=t;if(!ft(r))return{seedBlocks:void 0,..._({result:{error:G},context:{participantsCount:r},stack:"getSeedBlocks"})};let o=Ki(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=Te(i,a),f=l.length;l.forEach((g,I)=>{let h,S=I<f/2,T=I%2===0,y=g[0],N=g[g.length-1];n&&f>4?f===8?h=S?N:y:h=T?y:N:h=S?y:N,Fe(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 tg({roundRobinGroupsCount:t,drawSize:e}){let r="getSeedGroups";if(!ft(e))return{seedGroups:void 0,..._({result:{error:G},context:{drawSize:e},stack:r})};if(t){if(!ft(t))return{seedGroups:void 0,..._({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}=Zf({participantsCount:e,roundRobinGroupsCount:t}),o=0;return{seedGroups:(n||[]).map(s=>(s||[]).map(()=>(o+=1,o)))}}}function Yh({roundRobinGroupsCount:t,participantsCount:e}){if(t){let{validGroupSizes:o}=Ep({drawSize:e});if(!o?.map(a=>Math.ceil(e/a))?.includes(t))return _({context:{roundRobinGroupsCount:t},result:{error:G}})}let{seedGroups:r}=tg({drawSize:e,roundRobinGroupsCount:t}),n=r?.map(o=>Math.min(...o))||[];return{...R,seedingThresholds:n}}function Ic(t){if(!t)return 1/0;if(ft(t))return ct(t);let e=t.split("-")[0];return ft(e)?ct(e):1/0}function zF({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(se),e.reverse(),e}function Gb({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 kb({positioning:t,size:e}){let r=zF({size:e}),n=[],o=[],i=d=>d[0],s=d=>d[d.length-1],a=(d,l)=>(t&&[Xc,pi].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=Te(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=Te(m,d).map(p).filter(Boolean);f.length&&n.push(f)}return{divisions:r,divisionGroupings:n}}function fs({provisionalPositioning:t,returnAllProxies:e,appliedPolicies:r,seedingProfile:n,drawDefinition:o,allPositions:i,structure:s}){let a=[];if(!s)return{error:Oo};let{matchUps:c,roundMatchUps:u}=At({matchUpFilters:{roundNumbers:[1]},provisionalPositioning:t,structure:s}),{seedAssignments:p}=Hr({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(L=>parseInt(L)).sort((L,x)=>L-x).map(L=>{let x=u[L].map(H=>H.drawPositions).flat(1/0).filter(Boolean),B=x.filter(H=>!f.includes(H));return f=f.concat(...x),B}).filter(L=>L.length).reverse(),h=I.pop()??[],S=h&&Math.min(...h)-1||0;n=n??r?.seeding?.seedingProfile;let T=h?.length||0,y=I.filter(L=>L.filter(x=>x<=l).length),{stage:N,structureType:E,roundLimit:A}=s,U=E===ke,C=!U&&I?.length,P=!U&&N===at&&A,D=y.flat(1/0),M=C?D?.length:0,b=i?d:l,v=Km({drawDefinition:o,structure:s,matchUps:c}),O=v?0:!C&&b||b&&D.length<b&&b-D.length||0;if(P){let L=s?.matchUps?s.matchUps.filter(({roundNumber:B})=>B===s.roundLimit).length:0,x=h.length/L;if(!C){let B=Pp(n),H=Te(h,x),W=1,V=Z(0,H[0].length).map(()=>{let Y=Z(W,W+H.length);return W+=H.length,Y});({validSeedBlocks:a}=Vb({drawPositionBlocks:H,nonRandom:n?.nonRandom,positioning:B,seedGroups:V}))}}else U?{validSeedBlocks:a}=QF({nonRandom:n?.nonRandom,seedingProfile:n,structure:s}):C?a=y.map(L=>({seedNumbers:L,drawPositions:L})):v&&Te(h,2).map((x,B)=>({drawPositions:[x[0]],seedNumbers:[B+1]})).forEach(x=>a.push(x));if(!U&&!v&&!P){let{blocks:L}=XF({drawPositionOffset:S,seedNumberOffset:M,seedCountGoal:O,seedingProfile:n,baseDrawSize:T});L.forEach(x=>a.push(x))}let F=a.flatMap(L=>L.drawPositions).reduce((L,x)=>h?.includes(x)&&L,!0);return!v&&!C&&!U&&!F?{error:SA,validSeedBlocks:[],isContainer:U,isFeedIn:C}:{isLuckyStructure:v,validSeedBlocks:a,isContainer:U,isFeedIn:C}}function QF({seedingProfile:t,structure:e,nonRandom:r}){let n=e.structures||[],o=n.length,i=Ct({structure:e})?.positionAssignments,s=Pp(t),a=i?.length??0,{seedGroups:c}=tg({roundRobinGroupsCount:o,drawSize:a}),u=n.map(p=>Ct({structure:p}).positionAssignments?.map(m=>m.drawPosition));return Vb({drawPositionBlocks:u,positioning:s,seedGroups:c,nonRandom:r})}function Vb({drawPositionBlocks:t,positioning:e,seedGroups:r,nonRandom:n}){let o=[],{divisionGroupings:i}=kb({size:r.length,positioning:e}),s=[];return r.forEach((a,c)=>{let u=Gb({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!==pi?f=n?f:pr(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 XF(t){let{drawPositionOffset:e=0,roundRobinGroupsCount:r,seedNumberOffset:n=0,seedingProfile:o,seedCountGoal:i,baseDrawSize:s}=t,a=1,c=[],{seedBlocks:u}=Zf({cluster:Pp(o)===Xc,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 Up({appliedPolicies:t,drawDefinition:e,seedBlockInfo:r,drawPosition:n,structureId:o,seedNumber:i}){let{structure:s}=st({drawDefinition:e,structureId:o});t||(t=ht({drawDefinition:e}).appliedPolicies);let a=r?.validSeedBlocks;return!a&&s&&(a=fs({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 qh(t){let{provisionalPositioning:e,drawDefinition:r,seedingProfile:n,seedBlockInfo:o,structureId:i,randomize:s}=t,{structure:a}=st({drawDefinition:r,structureId:i}),{seedAssignments:c}=Hr({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}=ht({drawDefinition:r}),g=(o?.validSeedBlocks||a&&fs({returnAllProxies:t.returnAllProxies,provisionalPositioning:e,appliedPolicies:d,drawDefinition:r,seedingProfile:n,structure:a})?.validSeedBlocks||[]).filter(x=>x.drawPositions.filter(H=>!m?.includes(H)).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)),y=c?.filter(x=>T?.includes(x.participantId)),N=c?.filter(x=>!x.participantId),A=(y?.length&&y.length>0?y.length:N?.length??0)&&g?.drawPositions.filter(x=>!m?.includes(x))||[],U=s?pr(A):A,C=[],P=U.map(()=>{let B=L(y,C)?.participantId;return B&&C.push(B),B}).filter(Boolean),D=c?.filter(x=>S?.includes(x.participantId)).map(x=>x.seedNumber),b=(g?.seedNumbers||[]).filter(x=>!D?.includes(x)),v=c?.filter(x=>b.includes(x.seedNumber)).map(x=>x.participantId),O=d?.seeding?.duplicateSeedNumbers;return{nextSeedBlock:g,unplacedSeedParticipantIds:(O!==void 0?O:!0)?P:v,unplacedSeedNumbers:b,unfilledPositions:U,unplacedSeedAssignments:y};function L(x,B){let H=x.filter($=>!B.includes($.participantId)),W=Math.min(...H.map($=>Ic($.seedValue))),V=H.filter($=>Ic($.seedValue)===W);return pr(V).pop()}}function Pp(t){if(typeof t=="string")return t;if(typeof t=="object")return t.positioning}function $s({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=Hr({provisionalPositioning:t,drawDefinition:r,structure:d}).seedAssignments,g=f.map(E=>E.seedNumber),I=fc({drawDefinition:r,participantId:o});if(o&&!I)return _({result:{error:Zr},context:{participantId:o},stack:m});let h=p?Ht({event:p}).flightProfile?.flights?.length:0,S=h&&h>1,y=l?.find(E=>E.participantId===o)?.drawPosition;if(y&&!Up({drawPosition:y,drawDefinition:r,seedBlockInfo:i,structureId:s,seedNumber:a}))return _({result:{error:Sl},context:{assignedDrawPosition:y},info:"invalid seed position",stack:m});g.includes(a)||f.push({seedNumber:a,seedValue:c});let N;return f.forEach(E=>{E.participantId===o&&E.seedNumber!==a&&(E.participantId=void 0),E.seedNumber===a&&(E.participantId=o,!n?.groupSeedingThreshold&&!S&&(E.seedValue=c??a),N=!0)}),N?(ph({tournamentId:e?.tournamentId,drawDefinition:r,structure:d,eventId:u}),{...R}):_({result:{error:hA},stack:m})}function ed({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}=dt({element:o,name:Do}),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)}It({tournamentId:n?.tournamentId,context:"updateSidLineUp",eventId:s?.eventId,drawDefinition:o,matchUp:i})}function $h(t){let{sourceMatchUp:e}=t,{targetMatchUp:r,structure:n,matchUpsMap:o,drawPosition:i}=t,s=r.roundNumber>1&&r.roundNumber-1,a=ti({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=[ge,Ne].includes(d);return{pairedPreviousMatchUp:m,pairedPreviousMatchUpIsDoubleExit:l}}function Bb({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(se).filter(Boolean),positionAdded:r,positionAssigned:n}}function Kh({structureId:t,matchUpsMap:e,matchUp:r}){let n=r?.roundPosition,o=n%2?1:-1,i=n+o;return{pairedPreviousMatchUp:ti({matchUpsMap:e,structureId:t}).find(({roundNumber:c,roundPosition:u})=>c===r?.roundNumber&&u===i)}}function zh({inContextDrawMatchUps:t,sourceMatchUpStatus:e,sourceMatchUpId:r,matchUpsMap:n,matchUp:o}){let i=t.find(a=>a.matchUpId===r),{pairedPreviousMatchUp:s}=Kh({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=Re(p)||!isNaN(p)?{code:p}:p;return m.sideNumber===u?{...m,previousMatchUpStatus:e}:m})}}function rd({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 hc({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=ye({drawDefinition:o})),t||(t=ne({inContext:!0,drawDefinition:o,matchUpsMap:a}).matchUps??[]);let m=t.find(b=>b.matchUpId===c),d=m?.structureId,l=o?.structures?.find(b=>b.structureId===d);if(!l)return{error:Gt};let f=a?.drawMatchUps?.find(b=>b.matchUpId===c),g=f?.drawPositions??[],{positionAdded:I,positionAssigned:h,updatedDrawPositions:S}=Bb({drawPosition:s,drawPositions:g}),{positionAssignments:T}=Ct({drawDefinition:o,structure:l}),N=T?.filter(b=>S.includes(b.drawPosition))?.find(({bye:b})=>b),E=f?.matchUpStatus&&[vt,bt].includes(f.matchUpStatus)&&S.filter(Boolean).length<2;if(i=N&&Nt||i||E&&f.matchUpStatus||f?.matchUpStatus&&[ge,Ne].includes(f.matchUpStatus)&&f.matchUpStatus||Qt,f&&I){t=ne({inContext:!0,drawDefinition:o,matchUpsMap:a}).matchUps??[];let b=E&&rd({inContextDrawMatchUps:t,drawPosition:s,matchUpId:c})||void 0;f?.matchUpStatusCodes&&zh({inContextDrawMatchUps:t,sourceMatchUpStatus:e,sourceMatchUpId:n,matchUpsMap:a,matchUp:f}),Object.assign(f,{drawPositions:S,winningSide:b,matchUpStatus:i}),It({tournamentId:r?.tournamentId,eventId:m?.eventId,context:p,drawDefinition:o,matchUp:f})}let A=nr({inContextDrawMatchUps:t,inContextMatchUp:m,drawDefinition:o,matchUpId:c}),{targetMatchUps:{winnerMatchUp:U,loserMatchUp:C,loserTargetDrawPosition:P},targetLinks:{loserTargetLink:D}}=A,M=ti({structureId:l.structureId,matchUpsMap:a});if(h&&N){if(U)if([Nt,ge,Ne].includes(i)){let b=hc({matchUpId:U.matchUpId,inContextDrawMatchUps:t,tournamentRecord:r,drawDefinition:o,drawPosition:s,matchUpsMap:a});if(b.error)return b}else{let{structureId:b}=U;b!==l.structureId&&console.log("winnerMatchUp in different structure... participant is in different targetDrawPosition")}}else if(U&&m&&!m.feedRound){let{pairedPreviousMatchUpIsDoubleExit:b}=$h({targetMatchUp:f,drawPosition:s,matchUpsMap:a,structure:l});if(b){let v=hc({matchUpId:U.matchUpId,inContextDrawMatchUps:t,tournamentRecord:r,drawDefinition:o,drawPosition:s,matchUpsMap:a});if(v.error)return v}}if(f?.matchUpType===Bt){let b=t?.find(({matchUpId:F})=>F===f.matchUpId),O=(b?.sides??[]).reduce((F,L,x)=>L.drawPosition===s?x:F,void 0),w=T?.find(F=>F.drawPosition===s)?.participantId;w&&O!==void 0&&ed({inContextTargetMatchUp:b,drawPositionSideIndex:O,teamParticipantId:w,tournamentRecord:r,drawDefinition:o,matchUp:f})}if(D?.linkCondition===Xn&&S.filter(Boolean).length===2&&!N&&M.filter(({drawPositions:O,roundNumber:w})=>w===1&&Fe(O,S)).every(({matchUpStatus:O})=>[me,er].includes(O))&&C){let{structureId:O}=C,w=Cr({drawPosition:P,tournamentRecord:r,drawDefinition:o,structureId:O,matchUpsMap:a,event:u});if(w.error)return w}return h?{...R}:_({result:{error:ja},context:{drawPosition:s},stack:p})}function Qh({inContextDrawMatchUps:t,drawDefinition:e,assignments:r,matchUpsMap:n,structure:o}){let s=ts({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)&&jt(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 nd({lineUp:t}){if(!Array.isArray(t))return;let e={};return pt(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}=Tp({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 Rn(t){return`${t} must be an array`}function od({lineUp:t,tieFormat:e}){let r=[];if(!Array.isArray(t))return r.push(Rn("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(Rn("collectionAssignments")),!1):(r.push("Missing participantId"),!1)}),o=pt(t.map(gt)).length===t.length;return o||r.push("Duplicated participantId(s)"),{valid:n&&o,errors:r,error:r.length?G:void 0}}function Vi({drawDefinition:t,participantId:e,tieFormat:r,lineUp:n}){if(typeof t!="object")return{error:X};if(typeof e!="string")return{error:ee};let o=od({lineUp:n,tieFormat:r});if(!o.valid)return o;let{extension:i}=dt({element:t,name:Do}),s=i?.value||{};return s[e]=nd({lineUp:n}),yt({element:t,extension:{name:Do,value:s}}),Sa({drawDefinition:t}),{...R}}function eg({inContextDrawMatchUps:t,inheritance:e=!0,tournamentRecord:r,drawDefinition:n,matchUpsMap:o,assignments:i,structure:s,event:a}){if(!n)return{error:X};let{drawPositions:c,matchUps:u,targetMatchUps:p}=Qh({inContextDrawMatchUps:t,matchUpsMap:o,assignments:i,structure:s});for(let m of p)m.matchUpType===gn&&(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&&Vi({drawDefinition:n,participantId:I,lineUp:[],tieFormat:g})}It({tournamentId:r?.tournamentId,context:"resetLineUps",eventId:a?.eventId,drawDefinition:n,matchUp:f})}}});return{...R}}function bn({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 _({result:{error:ee},stack:l});p=p??ye({drawDefinition:i}),e||({matchUps:e}=ne({inContext:!0,drawDefinition:i,matchUpsMap:p}));let f=st({drawDefinition:i,structureId:m});if(f.error)return _({result:f,stack:l});let{structure:g}=f;if(!g)return{error:Gt};if(gr({structure:g}))return _({result:{error:Ze},stack:l});let{seedAssignments:I}=Hr({provisionalPositioning:t,drawDefinition:i,structure:g}),S=I?.find(D=>D.participantId===a)?.seedNumber,{appliedPolicies:T}=ht({tournamentRecord:o,drawDefinition:i,structure:g,event:d});if(S&&!Up({seedNumber:S,appliedPolicies:T,drawDefinition:i,seedBlockInfo:c,drawPosition:u,structureId:m}))return _({result:{error:Sl},context:{drawPosition:u},stack:l});let N=de({structure:g}).positionAssignments||[],E=N?.find(D=>D.drawPosition===u);if(!E)return _({result:{error:Ds},context:{drawPosition:u},stack:l});if(N?.map(gt).includes(a))return _({result:{error:Rs},context:{drawPosition:u},stack:l});let{containsParticipant:U,containsBye:C}=P(E);if(C){let D=lc({inContextDrawMatchUps:e,tournamentRecord:o,drawDefinition:i,drawPosition:u,structureId:m,matchUpsMap:p,event:d});if(D.error)return _({result:D,stack:l})}if(U&&E.participantId!==a){let{activeDrawPositions:D}=Da({drawDefinition:i,structureId:m});if(D.includes(u))return _({result:{error:Bu},stack:l});eg({assignments:[E],inContextDrawMatchUps:e,tournamentRecord:o,drawDefinition:i,matchUpsMap:p,structure:g})}if(E.participantId=a,r&&(E.qualifier=!0),(g?.stageSequence||0)>1||g.stage&&[He,ue].includes(g.stage)){let D=g.stage===at?at:tt,v=(i.structures?.find(O=>O?.stage===D&&O?.stageSequence===1)?.seedAssignments??[]).find(O=>O.participantId===a);if(v?.participantId){let{participantId:O,seedNumber:w,seedValue:F}=v;$s({eventId:d?.eventId,provisionalPositioning:t,tournamentRecord:o,drawDefinition:i,seedingProfile:s,participantId:O,seedNumber:w,seedValue:F,structureId:m,event:d})}}if(g.structureType!==ke)JF({provisionalPositioning:t,inContextDrawMatchUps:e,sourceMatchUpStatus:n,tournamentRecord:o,drawDefinition:i,drawPosition:u,matchUpsMap:p,structure:g,event:d});else{Vh({positionAssignments:N,tournamentRecord:o,drawDefinition:i,matchUpsMap:p,structure:g});let{drawPositions:D,matchUps:M,targetMatchUps:b}=Qh({assignments:[E],inContextDrawMatchUps:e,drawDefinition:i,matchUpsMap:p,structure:g});if(D&&M?.length===1&&M[0].matchUpType===Bt){let O=(b?.[0].sides??[]).reduce((w,F,L)=>D?.includes(F.drawPosition)?L:w,void 0);ed({inContextTargetMatchUp:b[0],teamParticipantId:a,matchUp:M[0],drawPositionSideIndex:O,tournamentRecord:o,drawDefinition:i})}}return Mo({tournamentId:o?.tournamentId,drawDefinition:i,structure:g,event:d}),{positionAssignments:N,...R};function P(D){let M=D.bye,b=D.qualifier,v=D.participantId;return{containsBye:M,containsQualifier:b,containsParticipant:v,filled:M||b||v}}}function JF({provisionalPositioning:t,inContextDrawMatchUps:e,sourceMatchUpStatus:r,tournamentRecord:n,drawDefinition:o,drawPosition:i,matchUpsMap:s,structure:a,event:c}){let u={isCollectionMatchUp:!1},{matchUps:p}=At({provisionalPositioning:t,matchUpFilters:u,drawDefinition:o,matchUpsMap:s,structure:a,event:c}),{roundMatchUps:m}=qe({matchUps:p}),{initialRoundNumber:d}=us({drawPosition:i,matchUps:p}),l=d&&m?.[d].find(f=>f.drawPositions?.includes(i));if(l){let f=hc({matchUpId:l.matchUpId,inContextDrawMatchUps:e,sourceMatchUpStatus:r,tournamentRecord:n,drawDefinition:o,drawPosition:i,matchUpsMap:s});if(f.error)return _({stack:"assignDrawPositionToMatchUps",context:{drawPosition:i},result:f})}return{...R}}function id(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:X};let m=ht({tournamentRecord:o,drawDefinition:i,event:u}).appliedPolicies??{},{inContextDrawMatchUps:d,matchUpsMap:l}=t;l||(l=ye({drawDefinition:i}),Object.assign(t,{matchUpsMap:l})),d||({matchUps:d}=ne({inContext:!0,drawDefinition:i,matchUpsMap:l}),Object.assign(t,{inContextDrawMatchUps:d}));let{positionAssignments:f}=Ct({drawDefinition:i,structureId:c}),g=f?.find(y=>y.drawPosition===a);if(g?.participantId){let y=g.participantId,N=bn({inContextDrawMatchUps:d,tournamentRecord:o,drawDefinition:i,participantId:s,drawPosition:a,structureId:c,matchUpsMap:l,event:u});return N.success?T({appliedPolicies:m,removedParticipantId:y}):_({result:N,stack:p})}let I=lc({inContextDrawMatchUps:d,tournamentRecord:o,drawDefinition:i,drawPosition:a,structureId:c,matchUpsMap:l,event:u});if(I.error)return _({result:I,stack:p});let h=I.participantId,S=bn({inContextDrawMatchUps:d,isQualifierPosition:r,tournamentRecord:o,drawDefinition:i,participantId:s,drawPosition:a,structureId:c,matchUpsMap:l,event:u});if(!S.success)return _({result:S,stack:p});return T({appliedPolicies:m,removedParticipantId:h});function T({appliedPolicies:y,removedParticipantId:N}){let{structure:E}=st({drawDefinition:i,structureId:c});wm({drawPositions:[a],structure:E});let A={[e]:s,name:n,drawPosition:a,structureId:c};return ru({appliedPolicies:y,drawDefinition:i,positionAction:A}),_({context:{removedParticipantId:N},result:{...R},stack:p})}}function Hb({luckyLoserParticipantId:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,structureId:o}){return id({positionActionName:"luckyLoserDrawPositionAssignment",participantId:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,structureId:o})}function vU(t){return Hb(t)}function Wb({alternateParticipantId:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,structureId:o}){return id({positionActionName:"alternateDrawPositionAssignment",participantIdAttributeName:"alternateParticipantid",participantId:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,structureId:o})}function OU(t){return Wb(t)}function Xh({params:t,modMap:e,structure:r}){let{tournamentRecord:n,drawDefinition:o,event:i}=t;for(let s of r.matchUps)e[s.matchUpId]&&(s.roundNumber=e[s.matchUpId],It({tournamentId:n?.tournamentId,eventId:i?.eventId,drawDefinition:o,matchUp:s}))}function Jh(t,e){let r=[{drawDefinition:!0,structureId:!0}];Array.isArray(e)&&r.push(...e);let n=ut(t,r);if(n.error)return n;let o=st(t);if(o.error)return o;let i=o.structure;if(!gr({structure:i}))return _({result:{error:Ci,message:"structure must be adHoc"}});let{roundMatchUps:a=[],roundNumbers:c}=qe({matchUps:i?.matchUps});return c?.length?{valid:!0,structure:i,roundMatchUps:a,roundNumbers:c}:{error:An}}function _U(t){let e=Jh(t,[{targetRoundNumber:!0,roundNumber:!0,[dn]:lR}]);if(e.error)return e;let{structure:r,roundMatchUps:n,roundNumbers:o}=e,{targetRoundNumber:i,roundNumber:s}=t;if(!o?.includes(s)||!o?.includes(i))return _({result:{error:G},info:"roundNumbers must be valid rounds"});let a=i>s,c=a?Z(s+1,i+1):Z(i,s),u={};return c.forEach(p=>(n?.[p]??[]).forEach(({matchUpId:m})=>{u[m]=p-(a?1:-1)})),n?.[s]?.forEach(({matchUpId:p})=>u[p]=i),Xh({params:t,modMap:u,structure:r}),{...R}}function xU({structurePositionAssignments:t,provisionalPositioning:e,tournamentRecord:r,drawDefinition:n,event:o}){if(!n)return{error:X};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:Gt};let d=Ct({structure:m}).positionAssignments?.map(({drawPosition:I})=>I),l=u?.map(({drawPosition:I})=>I);if(jt(d,l).length!==d?.length)return _({result:{error:G},info:"drawPositions do not match",stack:i});let f=ye({drawDefinition:n}),{matchUps:g}=ne({inContext:!0,drawDefinition:n,matchUpsMap:f});for(let I of u||[]){let{drawPosition:h,participantId:S,bye:T,qualifier:y}=I;if(T){let N=Cr({tournamentRecord:r,drawDefinition:n,drawPosition:h,matchUpsMap:f,structureId:c,structure:m,event:o});if(N?.error)return N}else if(y)u.forEach(N=>{N.drawPosition===h&&(N.qualifier=!0,delete N.participantId,delete N.bye)});else if(S){let N=bn({provisionalPositioning:e,inContextDrawMatchUps:g,tournamentRecord:r,drawDefinition:n,participantId:S,drawPosition:h,matchUpsMap:f,structureId:c,event:o});if(N?.error)return N}}Mo({tournamentId:r?.tournamentId,drawDefinition:n,structure:m,event:o})}let s=t.map(({structureId:a})=>a);return Ot({tournamentId:r?.tournamentId,eventId:o?.eventId,drawDefinition:n,structureIds:s}),{...R}}function wU(t){let e=Jh(t,[{roundNumbers:!0,[dn]:Dr,[Pn]:s=>s.length===2&&s.every(Jt)}]);if(e.error)return e;let{structure:r,roundMatchUps:n,roundNumbers:o}=e;if(!t.roundNumbers.every(s=>o?.includes(s)))return _({result:{error:G,message:"roundNumbers must be valid rounds"}});let i={};return t.roundNumbers.forEach((s,a)=>(n?.[s]??[]).forEach(({matchUpId:c})=>{i[c]=t.roundNumbers[1-a]})),Xh({params:t,modMap:i,structure:r}),{...R}}function jb({qualifyingParticipantId:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,structureId:o}){return id({positionActionName:"qualifierDrawPositionAssignment",participantId:t,isQualifierPosition:!0,tournamentRecord:e,drawDefinition:r,drawPosition:n,structureId:o})}function LU(t){return jb(t)}function Yb({tournamentRecord:t,drawDefinition:e,drawPositions:r,structureId:n,event:o}){if(!e)return{error:X};if(!n)return{error:Sr};if(r?.length!==2)return{error:G,drawPositions:r};let i=ye({drawDefinition:e}),{matchUps:s}=ne({inContext:!0,drawDefinition:e,matchUpsMap:i}),{structure:a}=st({drawDefinition:e,structureId:n});if(!a)return{error:Gt};let c=ht({tournamentRecord:t,drawDefinition:e,event:o}).appliedPolicies??{},u;if(a.structureType===ke?u=eG({inContextDrawMatchUps:s,tournamentRecord:t,drawDefinition:e,drawPositions:r,matchUpsMap:i,structure:a,event:o}):u=ZF({inContextDrawMatchUps:s,tournamentRecord:t,drawDefinition:e,drawPositions:r,matchUpsMap:i,structure:a,event:o}),u.error)return u;if(wm({structure:a,drawPositions:r}),ru({appliedPolicies:c,drawDefinition:e,positionAction:{name:"swapDrawPositionAssignments",drawPositions:r,structureId:n}}),Mo({tournamentId:t?.tournamentId,drawDefinition:e,structure:a,event:o}),o.eventType===jr){let m=At({matchUpFilters:{matchUpTypes:[gn]},inContext:!0,structure:a}).matchUps.filter(l=>l.drawPositions?.some(f=>r.includes(f))),d=At({matchUpFilters:{matchUpTypes:[gn]},structure:a}).matchUps;m.forEach(l=>{(l.sides||[]).forEach(f=>{let g=f?.drawPosition;if(r.includes(g)){let I=f.participantId,h=d.find(({matchUpId:T})=>T===l.matchUpId),S=l?.sides?.reduce((T,y,N)=>y.drawPosition===g?N:T,void 0);ed({inContextTargetMatchUp:l,drawPositionSideIndex:S,teamParticipantId:I,tournamentRecord:t,drawDefinition:e,matchUp:h,event:o})}})})}return Ot({drawDefinition:e,structureIds:[n]}),{...R}}function ZF({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?qb({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,assignments:a,matchUpsMap:o,structure:i,event:s}):tG({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,assignments:a,matchUpsMap:o,structure:i,event:s})}function qb({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=Iu({drawPosition:u,inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,structureId:d,matchUpsMap:o});return l.error||(l=Iu({drawPosition:m,inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,structureId:d,matchUpsMap:o}),l.error)||(Cr({drawPosition:m,tournamentRecord:e,drawDefinition:r,structureId:d,matchUpsMap:o,event:s}),l=bn({drawPosition:u,inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,structureId:d,participantId:p,matchUpsMap:o,event:s}),l.error)?l:{...R}}function tG({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),eg({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,matchUpsMap:o,assignments:n,structure:i,event:s}),{...R}}function eG({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};eg({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)qb({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 FU(t){return Yb(t)}function GU({validation:t=!0,tournamentRecord:e,drawDefinition:r,participantId:n,structureId:o,seedValue:i,event:s}){if(!r)return{error:X};if(!o)return{error:Sr};let a=(e?.participants??[]).find(l=>l.participantId===n);if(e&&!a)return{error:Zr};let{structure:c}=st({drawDefinition:r,structureId:o});if(!c)return{error:Gt};if(!(!t||Jt(i)||i===void 0||i===""||typeof i=="string"&&i.split("-").every(l=>Jt(l)&&ct(l)>0)))return{error:G};let{seedAssignments:p}=Hr({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 ph({tournamentId:e?.tournamentId,eventId:s?.eventId,drawDefinition:r,structure:c}),{...R}}function Zh({drawDefinition:t,structureId:e}){if(!t)return{error:X};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 rg({withStageGrouping:t,stageSequences:e,stageSequence:r,roundTarget:n,stages:o,event:i,stage:s}){if(!i)return{error:Dt};let a={},c=[];for(let u of i.drawDefinitions||[]){let{structures:p,stageStructures:m}=Gn({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 tS({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}=rg({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 ei(t){if(!t?.drawDefinition)return!1;let e=lu(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 eS(t){let{drawDefinition:e,structureId:r}=t;if(!e)return{error:X};let{playoffStructures:n}=Zh({drawDefinition:e,structureId:r});if(!n?.length)return!1;let o=e?.entries?.filter(c=>c?.entryStatus&&wr.includes(c.entryStatus))?.length??0,i=0;return(n||[]).reduce((c,u)=>!!((Ct({structure:u}).positionAssignments??[])?.filter(d=>(d.participantId&&i++,d?.bye??d?.participantId)).length&&c),!!n.length)||i===o}function rS({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=rS({accessors:s,significantCharacters:t,value:c});n.push(...u)});else if(r=r[o],s.length){let a=rS({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 $b({targetParticipantIds:t,policyAttributes:e,idCollections:r,participants:n}){if(!Array.isArray(e))return{error:AI};if(!Array.isArray(n))return{error:Ka};let o={};return t.forEach(i=>{let s=n.find(c=>c.participantId===i),{values:a}=kU({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 kU({policyAttributes:t,idCollections:e,participants:r,participant:n}){if(!Array.isArray(t))return{error:AI};if(!n)return{error:vi};let o=[];return t.forEach(s=>{let{directive:a,groupings:c,key:u,significantCharacters:p}=s||{};if(u){let m=u.split(".");o.push(...rS({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:pt(o)}}function VU({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}=kU({participants:e,policyAttributes:r,idCollections:n,participant:s});return{...i,values:a}})}function zb({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 Qb(t){let{unfilledPositions:e,chunkedDrawPositions:r}=t,n=zb(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=Kb(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=Kb(c);return!s.includes(u)}}}function Xb(t){let{unfilledPositions:e,chunkedDrawPositions:r}=t,n=zb(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 Kb(t){return Number(t%2?t+1:t-1)}function Jb({allGroups:t,participantId:e}){return Object.keys(t).filter(r=>t[r].includes(e))}function Zb({selectedParticipantGroups:t,participantIdGroups:e,positionAssignments:r,drawPositionChunks:n,unfilledPositions:o,isRoundRobin:i}){let s=n.map(a=>i?Xb({groupsToAvoid:t,chunkedDrawPositions:a,participantIdGroups:e,positionAssignments:r,unfilledPositions:o}):Qb({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 nS({positionAssignments:t,participantIds:e}){let r=t.map(n=>n.participantId);return e.filter(n=>!r.includes(n))}function tv({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?cn(a):cn(Object.keys(i));return o=t&&i[o]?.length?o:c,{participantId:o&&i[o]?cn(i[o]):cn(e),groupKey:o}}function ev({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 rv({candidatePositionAssignments:t,unseededParticipantIds:e,participantIdGroups:r,drawPositionChunks:n,drawPositionGroups:o,pairedPriority:i,allGroups:s,groupKey:a}){let u=o.reduce((C,P)=>P.length>C?P.length:C,0)<=2,p=nS({positionAssignments:t,participantIds:e}),m=ev({positionAssignments:t,drawPositionGroups:o}),{participantId:d,groupKey:l}=tv({targetParticipantIds:p,useSpecifiedGroupKey:u,allGroups:s,groupKey:a}),f=Jb({participantId:d,allGroups:s}),g=Zb({positionAssignments:t,isRoundRobin:u,selectedParticipantGroups:f,participantIdGroups:r,drawPositionChunks:n,unfilledPositions:m}),{unassigned:I,unpaired:h,pairedNoConflict:S}=g,T=S?.length&&S[0],y=h?.length&&h[0],N=i&&T?T:y,E=i?y:T,A=N?.length&&N||E?.length&&E,U;if(A?.length){let C=Gr(A);U=Gr(C)}else{let C=Gr(I[0]);U=Gr(C)}return{newGroupKey:l,selectedParticipantId:d,targetDrawPosition:U}}function sd({isRoundRobin:t,groupedParticipants:e}){let r=[];return t?e.forEach(n=>{let o=n.map(a=>a.drawPosition),i=Xf({drawPositions:o}).uniqueMatchUpGroupings??[],s=Object.assign({},...n.map(a=>({[a.drawPosition]:a})));i.forEach(a=>{Fe(s[a[0]].values||[],s[a[1]].values||[])&&(r.push(a),n.conflict=!0)})}):e.forEach(n=>{Fe(n[0]?.values||[],n[1]?.values||[])&&(r.push(n),n.conflict=!0)}),r}function nv({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=sd({isRoundRobin:o,groupedParticipants:[[c,l]]}),h=[t.find(T=>T.drawPosition===m),l],S=sd({isRoundRobin:o,groupedParticipants:[h]});return!g.length&&!S.length});if(p.length)return{drawPosition:c.drawPosition,possibleDrawPositions:p}}).filter(Boolean)}).flat(1)}function BU(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:y,targetDrawPosition:N}=rv({...t,candidatePositionAssignments:l,allGroups:c,groupKey:p});p=T,l.forEach(E=>{E.drawPosition===N&&(E.participantId=y)})});let g=VU({candidatePositionAssignments:l,participantsWithGroupings:r,policyAttributes:s,idCollections:a}),I=Te(g,m),h=sd({groupedParticipants:I,isRoundRobin:d}),S=0;for(;S<20&&h.length;){let T=nv({positionedParticipants:g,potentialDrawPositions:f,avoidanceConflicts:h,drawPositionGroups:i,isRoundRobin:d});if(T.length){let y=rG({candidatePositionAssignments:l,swapOptions:T});y.error&&console.log({result:y}),g=VU({candidatePositionAssignments:l,participantsWithGroupings:r,policyAttributes:s,idCollections:a}),I=Te(g,m),h=sd({groupedParticipants:I,isRoundRobin:d}),S++}else S=20}return l.forEach(T=>{if(T.bye&&T.participantId){let y=hI;u.push(y)}if(T.qualifier&&T.participantId){let y=hI;u.push(y)}}),{positionAssignments:l,conflicts:h.length,groupedParticipants:I,errors:u}}function rG({candidatePositionAssignments:t,swapOptions:e}){let r=Gr(e);if(!r)return{error:{message:"No swap options"}};let n=r.drawPosition,o=Gr(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 ov({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:CA};let{candidatesCount:l=1,policyAttributes:f,targetDivisions:g}=p,{roundsToSeparate:I}=p,h="randomUnseededSeparation",{structure:S}=st({drawDefinition:i,structureId:u}),{matchUps:T}=At({provisionalPositioning:t,matchUpsMap:c,structure:S,event:d});if(g&&En(g)&&!I){let H=qC(g)||0,W=T.reduce((V,Y)=>Y.roundNumber>V?Y.roundNumber:V,0);I=W<H?1:W-H+1}let{positionAssignments:y}=de({structure:S}),N=Lm({participantsProfile:{convertExtensions:!0},deepCopy:!1,participants:a}).participantsWithGroupings,E=y?.filter(H=>!H.participantId),A=y?.map(H=>H.drawPosition),U=S?.structureType===ke,C=U?{structure:S,matchUps:T,allDrawPositions:A,roundsToSeparate:I}:{matchUps:T,allDrawPositions:A,roundsToSeparate:I},{drawPositionGroups:P,drawPositionChunks:D}=U?nG(C):oG(C),M={groupParticipants:a.filter(H=>H.participantType===Er).map(H=>H.participantId),teamParticipants:a.filter(H=>H.participantType===xt).map(H=>H.participantId),pairParticipants:a.filter(H=>H.participantType===lt).map(H=>H.participantId)},b=$b({targetParticipantIds:e,policyAttributes:f,idCollections:M,participants:a});if(b.error)return _({result:b,stack:h});let v=Object.assign({},...e.map(H=>{let W=Object.keys(b).filter(V=>(b[V]??[]).includes(H));return{[H]:W}})),O=nS({participantIds:e,positionAssignments:y});if(O.length>(E?.length||0))return{error:_l};let w,F=O.length,L=Z(0,l).map(()=>BU({initialPositionAssignments:y,participantsWithGroupings:N,unseededParticipantIds:e,opponentsToPlaceCount:F,pairedPriority:!1,unseededByePositions:n,participantIdGroups:v,drawPositionChunks:D,drawPositionGroups:P,policyAttributes:f,idCollections:M,allGroups:b,drawSize:m}));if(w=L.reduce((H,W)=>!H||(W.conflicts||0)<(H.conflicts||0)?W:H,void 0),!w||w.conflicts){let H=Z(0,l).map(()=>BU({initialPositionAssignments:y,participantsWithGroupings:N,unseededParticipantIds:e,opponentsToPlaceCount:F,pairedPriority:!0,unseededByePositions:n,participantIdGroups:v,drawPositionChunks:D,drawPositionGroups:P,policyAttributes:f,idCollections:M,allGroups:b,drawSize:m}));w=L.concat(...H).filter(V=>!V.errors?.length).reduce((V,Y)=>!V||(Y.conflicts||0)<(V.conflicts||0)?Y:V,void 0)}if(!w)return{error:$u};let x=(Ct({structure:S})?.positionAssignments??[]).filter(H=>H.participantId).map(H=>H.participantId),B=w.positionAssignments.filter(H=>!x.includes(H.participantId));for(let H of B)if(H.bye){let W=Cr({tournamentRecord:o,drawDefinition:i,seedBlockInfo:s,structureId:u,matchUpsMap:c,event:d,...H});if(W.error)return _({result:W,stack:h})}else if(H.participantId){let W=bn({automaticPlacement:!0,inContextDrawMatchUps:r,tournamentRecord:o,drawDefinition:i,seedBlockInfo:s,structureId:u,matchUpsMap:c,event:d,...H});if(W.error)return _({result:W,stack:h,context:{assignment:H}})}return{...R}}function nG(t){let{structure:{structures:e}}=t,r=e.map(n=>n.positionAssignments.map(o=>o.drawPosition));return{drawPositionGroups:r,drawPositionChunks:[r]}}function oG({allDrawPositions:t,roundsToSeparate:e,matchUps:r}){let n=r.filter(d=>d.roundNumber===1).map(d=>d.drawPositions),o=n.flat().sort(se),i=Math.max(...o),s=t.filter(d=>d>i),a=o.length,u=Z(a===2?1:2,a).filter(d=>d===fm(d)),m=u.slice(0,e||u.length).reverse().map(d=>Te(o,d));return s.length&&console.log({fedDrawPositions:s}),{drawPositionGroups:n,drawPositionChunks:m}}function iv({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}=Hr({provisionalPositioning:t,drawDefinition:i,structure:p}),I=g?.map(D=>D.participantId).filter(Boolean),{stage:h,stageSequence:S}=p,T=h===at?dt({element:p,name:ln})?.extension?.value:void 0,N=Ii({provisionalPositioning:t,drawDefinition:i,stageSequence:S,entryStatuses:Qo,structureId:u,roundTarget:T,stage:h}),A=N.filter(D=>!I?.includes(D.participantId)).map(D=>D.participantId),U=f?.filter(D=>!D.participantId&&!D.bye&&!D.qualifier).map(D=>D.drawPosition);if(!n&&A.length>(U?.length||0))return _({result:{error:_l},context:{unseededParticipantsCount:A.length,unfilledDrawPositionsCount:U?.length},stack:l});let{appliedPolicies:C}=ht({tournamentRecord:o,drawDefinition:i,event:d}),P=C?.[Yc];if(p.stage===ue){let D=N.reduce((M,b)=>(M[b.groupingValue]||(M[b.groupingValue]=[]),M[b.groupingValue].push(b.participantId),M),{});Object.keys(D).length&&(P||(P={policyName:"Playoff Avoidance"}),P.policyAttributes||(P.policyAttributes=[]),P.policyAttributes.push({groupings:D}))}return P&&a?ov({provisionalPositioning:t,unseededParticipantIds:A,inContextDrawMatchUps:e,unseededByePositions:r,tournamentRecord:o,drawDefinition:i,seedBlockInfo:s,participants:a,matchUpsMap:c,structureId:u,avoidance:P,drawSize:m,entries:N}):iG({provisionalPositioning:t,unseededParticipantIds:A,inContextDrawMatchUps:e,unfilledDrawPositions:U,multipleStructures:n,tournamentRecord:o,drawDefinition:i,seedBlockInfo:s,structureId:u,matchUpsMap:c,drawSize:m,event:d})}function iG({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?pr(n):n.reverse();for(let l of e){let f=d.pop();if(!o||f){let g=bn({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 _({result:g,stack:"randomUnseededDistribution"})}}return{...R}}function sv(t){let e=t.structure??st(t).structure,r="positionQualifiers",n=[];if(e.stage===He)return _({result:{error:Ri},stack:r});let{unplacedRoundQualifierCounts:o,positionAssignments:i,roundDrawPositions:s}=sG(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 _({result:{error:YA},context:{unfilledDrawPositions:c},stack:r});Z(0,o[a]).forEach(()=>{let u=Gr(c);n.push(u),i?.forEach(p=>{p.drawPosition===u&&(p.qualifier=!0,delete p.participantId,delete p.bye)})})}return{...R,qualifierDrawPositions:n}}function sG({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}=ms({drawDefinition:t,stageSequence:i,structureId:r,stage:o}),u=(a?Object.keys(a):[]).map(h=>ct(h)),{matchUps:p}=At({structure:e}),{roundProfile:m}=qe({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 HU({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=ht({drawDefinition:i}).appliedPolicies),!o){let h=d&&fs({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=aG({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 aG({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}=qh({provisionalPositioning:t,randomize:!0,drawDefinition:n,seedingProfile:o,seedBlockInfo:i,structureId:a,event:u}),{appliedPolicies:d}=ht({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:Ns};f.push(I);let h=bn({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 av({provisionalPositioning:t,drawDefinition:e,structure:r}){let{positionAssignments:n}=de({structure:r}),{seedAssignments:o}=Hr({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 cv({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=WU(Te(i.drawPositions,2)),c,u=t[n.length];for(;c=ng(a,u);)n.push(c),u=t[n.length]}});let o=n.map(i=>Array.isArray(i)?pr(i):i).flat(1/0);return CI(r)&&e.map(s=>s.seedNumbers[0]).includes(r)?t:o}function ng(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 ng(e?o:t[Math.round(Math.random())],e)}return r<n?ng(t[1],e):ng(t[0],e)}function WU(t){let e=Math.floor(t.length/2);return t.length>2?[WU(t.slice(0,e)),WU(t.slice(e))]:t}function pv({provisionalPositioning:t,relevantMatchUps:e,appliedPolicies:r,drawDefinition:n,seedingProfile:o,seedBlockInfo:i,byesToPlace:s,structure:a}){i||(i=fs({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=av({provisionalPositioning:t,drawDefinition:n,structure:a})??[],l=pt([].concat(...e.map(N=>N.drawPositions))),f=d.filter(N=>l.includes(N.drawPosition)),g=(N,E)=>Ic(N.seedValue)-Ic(E.seedValue),h=m.reduce((N,E)=>{let A=f.filter(U=>E.drawPositions?.includes(U.drawPosition)).sort(g);return N.concat(...A)},[]).map(N=>N.drawPosition),S=cv({orderedSortedFirstRoundSeededDrawPositions:h,validSeedBlocks:m,byesToPlace:s}),T=uv({orderedSeedDrawPositions:h,relevantMatchUps:e}).slice(0,s),y=uv({orderedSeedDrawPositions:S,relevantMatchUps:e}).slice(0,s);return{strictSeedOrderByePositions:T,blockSeedOrderByePositions:y,isLuckyStructure:u,positionedSeeds:d,isContainer:p,isFeedIn:c}}function uv({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 mv({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(O=>O.participantId).map(O=>O.drawPosition),d={isCollectionMatchUp:!1},{matchUps:l,roundMatchUps:f}=At({provisionalPositioning:t,matchUpFilters:d,structure:s}),g=f?.[1]||[],I=s.structureType===ke?l:g,h=pt([].concat(...I.map(O=>O.drawPositions))),S=Math.min(...h)-1,T=m?.filter(O=>h.includes(O)),y=O=>{let w=Math.ceil(O.length/2),F=[O.slice(0,w),O.slice(w)],L=F.map(k=>[].concat(...k.flat(1/0)).length),x=Math.min(...L.flat(1/0)),B=Math.max(...L.flat(1/0)),H=L.indexOf(B),W=x!==B,V=pr(F),[Y,$]=!x||W?[F[H],F[1-H]]:[V[0],V[1]];return{greaterHalf:Y,lesserHalf:$}},N=O=>{let{greaterHalf:w,lesserHalf:F}=y(O),{greaterHalf:L,lesserHalf:x}=y(w),H=pr(L.flat(1/0)).pop(),W=L.flat().filter(Y=>Y!==H);return{newlyFilteredChunks:[...F,...x,W],drawPosition:H}},E=O=>!e.includes(O),A=O=>!T?.includes(O),U=O=>{let F=Te(O.sort(se),Math.ceil(O.length/4)).map(B=>B.filter(A)),L=[].concat(...F.flat(1/0)).length,x=[];for(let B=0;B<L;B++){let{newlyFilteredChunks:H,drawPosition:W}=N(F);x.push(W),F=H}return x},{validSeedBlocks:C}=fs({provisionalPositioning:t,allPositions:!0,appliedPolicies:n,drawDefinition:o,structure:s}),P=C?.map(O=>O.drawPositions?.map(w=>w+S)),D;if(a){let O=h.length,{seedBlocks:w}=Zf({cluster:Pp(c)===Xc,participantsCount:O});D=w.map(L=>L.map(x=>x+S)).map(U).filter(L=>L.length)}else u?D=P?.map(O=>O.filter(A)):D=P?.map(U).filter(O=>O.length);let M=I.map(O=>O.drawPositions).map(O=>O?.sort((w,F)=>w-F)).filter(O=>O?.[0]+1===O?.[1]),b=O=>M.reduce((w,F)=>F.includes(O)?F.reduce((L,x)=>x!==O?x:L,void 0):w,void 0),v=D.map(O=>O.map(b)).flat(1/0).filter(A).filter(E).filter(Boolean);if(u&&!s.structures){let O=i%4,w=v.slice(0,O),F=f[s.roundLimit]?.length,L=Te(v.slice(O),F).map(pr).flat();v=w.concat(L)}return{unseededByePositions:v}}function dv({provisionalPositioning:t,drawDefinition:e,matchUpsMap:r,structure:n,event:o}){let i={isCollectionMatchUp:!1},{matchUps:s,roundMatchUps:a}=At({afterRecoveryTimes:!1,provisionalPositioning:t,drawDefinition:e,matchUpFilters:i,matchUpsMap:r,structure:n,event:o}),c=a?.[1]||[],u=n?.structureType===ke,p=u?s:c,m=u?n?.structures?.length||0:s.length,{structureId:d,stage:l,stageSequence:f}=n,g=Ii({entryStatuses:wr,provisionalPositioning:t,drawDefinition:e,stageSequence:f,structureId:d,stage:l}),{qualifiersCount:I}=ms({provisionalPositioning:t,drawDefinition:e,stageSequence:f,structureId:d,stage:l}),h=g.length+I,{positionAssignments:S,unassignedPositions:T}=de({structure:n}),y=T?.map(P=>P.drawPosition),N=S?.filter(P=>P.bye).length,E=S?.filter(P=>P.bye).map(P=>P.drawPosition),A=p.map(P=>P.drawPositions).filter(P=>P?.reduce((D,M)=>!E?.includes(M)&&D,!0)).flat(1/0).filter(P=>y?.includes(P)),U=S?.length,C=U?U-h:0;return C>m&&n.stageSequence===1&&n.stage!==He&&(C=m),{placedByes:N,byesCount:C,relevantMatchUps:p,placedByePositions:E,roundMatchUps:a,positionsToAvoidDoubleBye:A}}function jU({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}=dv({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:y}=pv({provisionalPositioning:t,relevantMatchUps:g,appliedPolicies:r,drawDefinition:n,seedingProfile:i,seedBlockInfo:o,byesToPlace:I,structure:c}),N=c?.structureType&&[ke,cp].includes(c.structureType)&&r?.seeding?.containerByesIgnoreSeeding,E=d&&S?.length?S:h,{unseededByePositions:A}=mv({provisionalPositioning:t,seedOrderByePositions:E,isLuckyStructure:T,appliedPolicies:r,drawDefinition:n,seedLimit:u,structure:c,isFeedIn:y}),U=M=>M%2,C=(M,b)=>(M||[]).every(v=>U(v)?b!==v+1:b!==v-1),P=[].concat(...E);if(!p)for(;A.length;){let M=A.find(b=>C(P,b));M?(P.push(M),A=A.filter(b=>b!==M)):(P.push(...A),A=[])}N&&(P=pr(P),Pr({ignoreSeededByes:N})&&console.log({byePositions:P}));let D=P.slice(0,I);for(let M of D){let b=Cr({provisionalPositioning:t,tournamentRecord:e,drawDefinition:n,drawPosition:M,matchUpsMap:s,structureId:a,structure:c,event:m});if(b?.error)return b}return{...R,unseededByePositions:A,byeDrawPositions:D}}function Sc(t){let{drawDefinition:e}=t,{applyPositioning:r=!0,provisionalPositioning:n,multipleStructures:o,placeByes:i=!0,tournamentRecord:s,placementGroup:a,seedingProfile:c,structureId:u,seedLimit:p,seedsOnly:m,drawType:d,drawSize:l,event:f}=t,g=[];r||(SE(),e=J(e,!1,!0));let I=w=>(r||jl(),_({result:w,stack:"automatedPositioning"})),h=w=>(r||jl(),w),S=st({drawDefinition:e,structureId:u});if(S.error)return I(S);let T=S.structure;if(!T)return{error:Gt};let y=t.appliedPolicies||ht({drawDefinition:e,structure:T,event:f})?.appliedPolicies,{qualifiersCount:N}=ms({stageSequence:T.stageSequence,provisionalPositioning:n,stage:T.stage,drawDefinition:e,structureId:u}),E=Qo;if(!Ii({stageSequence:T.stageSequence,provisionalPositioning:n,stage:T.stage,placementGroup:a,drawDefinition:e,entryStatuses:E,structureId:u})?.length&&!N)return h({...R});let U=t.matchUpsMap??ye({drawDefinition:e}),C=t.inContextDrawMatchUps??ne({inContext:!0,drawDefinition:e,matchUpsMap:U})?.matchUps,P=[],D=fs({provisionalPositioning:n,appliedPolicies:y,drawDefinition:e,seedingProfile:c,structure:T});if(D.error)return D;let{validSeedBlocks:M}=D;g.push({validSeedBlocks:M});let b=t.participants||(s?Yt({withIndividualParticipants:!0,convertExtensions:!0,tournamentRecord:s})?.participants:[]);if(Pp(T.seedingProfile||c)===pi){let w=i?jU({provisionalPositioning:n,tournamentRecord:s,appliedPolicies:y,drawDefinition:e,seedBlockInfo:D,matchUpsMap:U,structure:T,seedLimit:p,seedsOnly:m,event:f}):void 0;if(w?.error)return I(w);P=w.unseededByePositions,g.push({action:"positionByes",unseededByePositions:P});let F=T.seedingProfile?{positioning:T.seedingProfile}:c;if(w=HU({seedingProfile:F,provisionalPositioning:n,inContextDrawMatchUps:C,tournamentRecord:s,appliedPolicies:y,validSeedBlocks:M,drawDefinition:e,seedBlockInfo:D,participants:b,matchUpsMap:U,structure:T,event:f}),w.error)return I(w);g.push({seedPositions:w.seedPositions,action:"positionSeedBlocks"})}else{if(d!==xi){let F=T.seedingProfile?{positioning:T.seedingProfile}:c,L=HU({seedingProfile:F,provisionalPositioning:n,inContextDrawMatchUps:C,tournamentRecord:s,appliedPolicies:y,validSeedBlocks:M,drawDefinition:e,seedBlockInfo:D,participants:b,matchUpsMap:U,structure:T,event:f});if(L.error)return I(L);g.push({action:"positionSeedBlocks",seedPositions:L.seedPositions})}let w=i?jU({provisionalPositioning:n,tournamentRecord:s,appliedPolicies:y,drawDefinition:e,seedBlockInfo:D,matchUpsMap:U,structure:T,seedLimit:p,seedsOnly:m,event:f}):void 0;if(w?.error)return I(w);P=w?.unseededByePositions,g.push({action:"positionByes",byeDrawPositions:w?.byeDrawPositions,unseededByePositions:P})}let v={};if(!m){let w=sv({inContextDrawMatchUps:C,tournamentRecord:s,appliedPolicies:y,validSeedBlocks:M,drawDefinition:e,seedBlockInfo:D,participants:b,matchUpsMap:U,structure:T});if(w.error||(w.conflicts&&(v.qualifierConflicts=w.conflicts),g.push({action:"positionQualifiers",qualifierDrawPositions:w.qualifierDrawPositions}),w=iv({provisionalPositioning:n,inContextDrawMatchUps:C,unseededByePositions:P,multipleStructures:o,tournamentRecord:s,drawDefinition:e,seedBlockInfo:D,participants:b,matchUpsMap:U,structureId:u,structure:T,drawSize:l,event:f}),w.error))return I(w);w.conflicts&&(v.unseededConflicts=w.conflicts),g.push({action:"positionUnseededParticipants"})}let{positionAssignments:O}=Ct({drawDefinition:e,structure:T});return Ot({drawDefinition:e,structureIds:[u]}),r||jl(),{positionAssignments:O,conflicts:v,...R,positioningReport:g}}function Tc(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:lr};if(!o)return{error:dr};if(!ei({drawDefinition:o,structureId:s})&&!r)return{error:hl};let m=Zh({drawDefinition:o,structureId:s}).playoffStructures?.sort((f,g)=>lf(f)-lf(g)),d=[],l=[];if(m)for(let f of m){let{structureId:g}=f,I=Sc({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 YU({drawDefinition:t,orderMap:e}){return t?((typeof e!="object"||!Object.values(e).every(r=>ft(r)))&&_({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)=>Xa(r.structureOrder)-Xa(n.structureOrder)),{...R}):{error:X}}function hu({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),y=o(S);return[mi,pn,up,pi].includes(I.target.feedProfile)?(T?.targets.push(S),y?.sources.push(h)):I.target.feedProfile===tn&&(y?.drawSources.push(h),T?.drawTargets.push(S)),s[S]=s[S]||I.target.feedProfile===tn,i[S]=pt([...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(),y=T&&n[T];y?.targets?.length?S.push(...y.targets):y&&(h.rootStage=y.stage)}if(h.rootStage||(h.rootStage=h.stage),!h.targets?.length){let T=h.sources??[];for(;T.length;){let y=T.pop(),N=y&&n[y];if(N?.sources?.length){for(let E of N.sources)h.progeny?.includes(E)||h.progeny?.push(E);T.push(...N.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 y=S.pop(),N=y?n.get(y):void 0;N?.drawTargets?.length&&S.push(N.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,y)=>Fe(h,y)?T.concat(...y):T,[])||[];return pt(h.concat(...S))})});let p=a[0],m=(I,h)=>jt(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(y=>y.includes(h))||(l.push([h]),S!==We&&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 oS({drawDefinition:t}){let{maxQualifyingDepth:e,structureProfiles:r}=hu({drawDefinition:t});for(let n of t.structures){let o=r[n.structureId];o.distanceFromMain&&(n.stageSequence=e+1-o.distanceFromMain)}return{...R}}function Ui(t){let{duplicateValues:e=!0,creationTime:r=!0,removePriorValues:n,timeItem:o}=t;if(!o)return{error:Ll};let i=dh(t);if(i.error)return i;if(!(Pt(o)&&Re(o.itemType)&&Object.keys(o).includes("itemValue")))return{error:wl};if(!i.timeItems)i.timeItems=[];else if(cG({element:i,duplicateValues:e,timeItem:o}))return{...R};if(o.itemSubTypes&&!o.itemSubTypes.length&&delete o.itemSubTypes,r){let c=new Date().toISOString();Object.assign(o,{createdAt:c})}return n&&(i.timeItems=i.timeItems.filter(({itemType:c})=>o.itemType!==c)),n&&!o.itemValue||i.timeItems.push(o),{...R}}function cG({element:t,duplicateValues:e,timeItem:r}){let{itemType:n,itemSubTypes:o,itemValue:i}=r,s=n&&Vn({itemSubTypes:o,itemType:n,element:t})?.timeItem;return s&&JSON.stringify(s?.itemValue)===JSON.stringify(i)&&!e}function og({creationTime:t=!0,removePriorValues:e,tournamentRecord:r,duplicateValues:n,participantId:o,timeItem:i}){if(!r)return{error:j};if(!o)return{error:ee};let s=fo({tournamentRecord:r,participantId:o});return s.error?s:Ui({element:s.participant,removePriorValues:e,duplicateValues:n,creationTime:t,timeItem:i})}function Bi(t){let{removePriorValues:e,tournamentRecord:r,duplicateValues:n,creationTime:o,timeItem:i}=t;return r?Ui({element:r,removePriorValues:e,duplicateValues:n,creationTime:o,timeItem:i}):{error:j}}function Hi(t){let{removePriorValues:e,duplicateValues:r,creationTime:n,timeItem:o,event:i}=t;return i?Ui({removePriorValues:e,duplicateValues:r,element:i,creationTime:n,timeItem:o}):{error:lr}}function ig({tournamentRecord:t,drawDefinition:e,structure:r,link:n}){if(!t)return{error:j};if(!e)return{error:X};let o=uG({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 Bi({tournamentRecord:t,timeItem:s}),o}function uG({drawDefinition:t,tournamentId:e,structure:r,eventId:n,link:o}){if(!t)return{error:X};if(!r)return{error:Oo};if(!o)return{error:yl};let i=o.target.structureId,s=st({drawDefinition:t,structureId:i});if(s.error)return _({stack:"attachQualifyingStructure",context:{targetStructureId:i},result:s});t.structures||(t.structures=[]),t.links||(t.links=[]),t.structures.push(r),t.links.push(o),oS({drawDefinition:t});let a=At({structure:r})?.matchUps||[];return No({drawDefinition:t,tournamentId:e,matchUps:a,eventId:n}),Ot({drawDefinition:t,structureIds:[r.structureId]}),{...R}}function qU({drawDefinition:t,structureDetails:e}){if(!Array.isArray(e))return{error:G};if(!t)return{error:X};let r=Object.assign({},...e.map(n=>{if(!Pt(n))return;let{structureId:o,structureName:i}=n||{};if(!(!o||!i))return{[o]:i}}).filter(Boolean));if(!Object.values(r).length)return{error:rt};for(let n of t.structures||[]){let o=r[n.structureId];o&&(n.structureName=o)}return{...R}}function sg({drawDefinition:t,timeItem:e}){if(!t)return{error:dr};if(!e)return{error:Ll};let r=e&&Object.keys(e),n=["itemType","itemValue"];if(!(n.filter(s=>r.includes(s)).length===n.length))return{error:wl};t.timeItems||(t.timeItems=[]);let i=new Date().toISOString();return Object.assign(e,{createdAt:i}),t.timeItems.push(e),Sa({drawDefinition:t}),{...R}}function $U(t){let{tournamentRecord:e,drawDefinition:r,structureId:n,event:o}=t,i=ut(t,[{drawDefinition:!0,structureId:!0}]);if(i.error)return i;let s=r.structures??[],a=s.find(h=>h.structureId===n);if(!a)return{error:Gt};let c=s.find(({stage:h,stageSequence:S})=>h===tt&&S===1),u=n===c?.structureId,p=s.filter(({stage:h})=>h===at).map(Mr("structureId"));if(u&&!p.length)return{error:aA};let m=p.includes(n),d=pG({isQualifyingStructure:m,structure:a,...t});if(d?.error)return d;let{structureIdsToRemove:l,relatedStructureIdsMap:f}=dG({qualifyingStructureIds:p,isQualifyingStructure:m,isMainStageSequence1:u,mainStageSequence1:c,drawDefinition:r,structureId:n}),{removedMatchUpIds:g,removedStructureIds:I}=lG({relatedStructureIdsMap:f,qualifyingStructureIds:p,isMainStageSequence1:u,mainStageSequence1:c,drawDefinition:r,structureIdsToRemove:l,structureId:n});if(mG({removedMatchUpIds:g,drawDefinition:r}),u){let h=(c.matchUps??[])?.map(Mr("matchUpId"));g.push(...h),c.positionAssignments=[],c.seedAssignments=[],c.matchUps=[],c.extensions&&(c.extensions=[])}return m&&oS({drawDefinition:r}),kn({tournamentId:e?.tournamentId,matchUpIds:g,action:"removeStructure",eventId:o?.eventId,drawDefinition:r}),Ot({drawDefinition:r,eventId:o?.eventId}),{...R,removedMatchUpIds:g,removedStructureIds:I}}function pG({isQualifyingStructure:t,tournamentRecord:e,drawDefinition:r,structureId:n,structure:o,event:i,force:s}){let a=[n];if(t){let p=d=>r.links?.find(l=>l.target.structureId===d),m=p(n)?.source.structureId;for(;m;)a.push(m),m=p(m)?.source.structureId}if(ne({matchUpFilters:{structureIds:a},drawDefinition:r}).matchUps?.some(({score:p})=>Ie({score:p}))){let p=ht({tournamentRecord:e,drawDefinition:r,structure:o,event:i})?.appliedPolicies;if(!(s??p?.[Ln]?.allowDeletionWithScoresPresent?.structures))return{error:Qu}}return{...R}}function mG({removedMatchUpIds:t,drawDefinition:e}){let{matchUps:r}=ne({drawDefinition:e});r?.forEach(n=>{n.winnerMatchUpId&&t.includes(n.winnerMatchUpId)&&delete n.winnerMatchUpId,n.loserMatchUpId&&t.includes(n.loserMatchUpId)&&delete n.loserMatchUpId})}function dG({qualifyingStructureIds:t,isQualifyingStructure:e,isMainStageSequence1:r,mainStageSequence1:n,drawDefinition:o,structureId:i}){let a=(o.structures??[]).map(Mr("structureId")),c=d=>o.links?.map(l=>l.source.structureId===d&&l.target.structureId!==n?.structureId&&l.target.structureId).filter(Boolean)??[],u=d=>o.links?.map(l=>t.includes(l.source.structureId)&&l.target.structureId===d&&l.source.structureId).filter(Boolean)??[],p=new Map;return a.forEach(d=>p.set(d,e?u(d):c(d))),{structureIdsToRemove:r?p.get(i):[i],relatedStructureIdsMap:p}}function lG({relatedStructureIdsMap:t,qualifyingStructureIds:e,isMainStageSequence1:r,mainStageSequence1:n,drawDefinition:o,structureIdsToRemove:i,structureId:s}){let a=[],c=[];for(;i?.length;){let u=i.pop();c.push(...IG({idBeingRemoved:u,drawDefinition:o}));let p=gG({qualifyingStructureIds:e,isMainStageSequence1:r,idBeingRemoved:u,drawDefinition:o,structureId:s});a.push(...p.removedStructureIds);let m=fG({relatedStructureIdsMap:t,mainStageSequence1:n,idBeingRemoved:u,structureId:s});m?.length&&i.push(...m)}return{removedMatchUpIds:c,removedStructureIds:a}}function fG({idBeingRemoved:t,relatedStructureIdsMap:e,mainStageSequence1:r,structureId:n}){return t&&e.get(t)?.filter(o=>o!==r?.structureId||n===r.structureId)}function gG({qualifyingStructureIds:t,isMainStageSequence1:e,idBeingRemoved:r,drawDefinition:n,structureId:o}){let i=[];return n.links=n.links?.filter(s=>s.source.structureId!==r&&s.target.structureId!==r)??[],(!e||e&&t.length||r!==o)&&(n.structures=(n.structures??[]).filter(s=>(r&&r===s.structureId&&i.push(r),s.structureId!==r))),{removedStructureIds:i}}function IG({idBeingRemoved:t,drawDefinition:e}){let{structure:r}=st({structureId:t,drawDefinition:e}),n=At({structure:r}).matchUps;return Mm(n)}function Dp({stageSequence:t=1,drawDefinition:e,drawSize:r,stage:n}){if(!e)return{error:X};if(!_f({drawDefinition:e,stage:n}))return{error:Ri};let o=VR({drawDefinition:e,stage:n}),{qualifiersCount:i}=ms({drawDefinition:e,stageSequence:t,stage:n}),s=o+i;if(r<s)return{error:II};let{entryProfile:a}=Mf({attributes:[{[n]:{drawSize:r}}],drawDefinition:e});return Ot({drawDefinition:e}),{...R,entryProfile:a}}function iS({qualifiersCount:t=0,drawDefinition:e,stage:r}){return e?_f({drawDefinition:e,stage:r})?r!==tt?{error:II,info:"qualifiersCount can only be set for main stage"}:(Mf({attributes:[{[r]:{qualifiersCount:t}}],drawDefinition:e}),Ot({drawDefinition:e}),{...R}):{error:Ri}:{error:X}}function lv({drawDefinition:t,drawSize:e}){if(!t)return{error:X};let r=Dp({stage:We,stageSequence:1,drawDefinition:t,drawSize:e});return r.error?r:(Ot({drawDefinition:t}),{...R})}function KU(t){return lv(t)}function zU({tournamentRecord:t,drawDefinition:e,participantId:r,structureId:n}){let o="removeSeededParticipant";if(!t)return{error:j};if(!e)return{error:X};let i=(e.structures??[]).find(a=>a.structureId===n);return i?!i.stage||![tt,at].includes(i.stage)||i.stage===tt&&i.stageSequence!==1?_({result:{error:Ci},stack:o}):i.seedAssignments?.find(a=>a.participantId===r)?{...R}:_({info:"participant not seeded",result:{error:Le},context:{participantId:r}}):_({result:{error:Gt},stack:o})}function Ca({targetEntryRound:t=1,finishingPositions:e,sourceRoundNumber:r,sourceStructureId:n,targetStructureId:o,linkType:i=po}){return!n||!o?{error:Sr}:{link:nt({linkType:i,source:{roundNumber:r,structureId:n,finishingPositions:e},target:{feedProfile:tn,roundNumber:t,structureId:o}})}}function ad({roundPosition:t,roundNumber:e,idPrefix:r,uuids:n}){return r?`${r}-${e}-${t}`:n?.pop()||Mt()}function Np({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=ad({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:Qt,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 hn({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&&(!En(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(!En(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}=Np({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}=Np({nodes:d,matchUpType:o,roundNumber:f,idPrefix:s,matchUps:l,isMock:c,uuids:u}),f++;let g=f-1;return l=Ua({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 cd(t){let e="generateQualifyingStructure";if(!t.drawDefinition)return _({result:{error:X},stack:e});if(t.drawSize&&!ft(t.drawSize)||t.participantsCount&&!ft(t.participantsCount)||t.qualifyingPositions&&!ft(t.qualifyingPositions))return _({result:{error:G},stack:e});let r=t.drawSize??lm(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 _({result:{error:qa},context:{drawSize:r},stack:e});if(o&&o>=t.drawSize)return _({result:{error:G},context:{drawSize:r,qualifyingPositions:o},stack:e});let h,S,T,y,N=0,E,A=1,{structureProfiles:U}=hu({drawDefinition:c}),C=U[i];if(!C)return _({result:{error:Gt},context:{targetStructureId:i},stack:e});let P=c.matchUpType,D=d?`${d}-`:"",M=C.stage===at,b=a?.[da]?.namingConventions?.pre??cb[da]?.namingConventions?.pre,v=M&&b?`${b}-`:"",O=p??(D?`${v}${$e(at)} ${D}`:`${v}${$e(at)}`);if(l===fn){let{maxRoundNumber:L,structures:x,groupCount:B}=Ma({structureName:p??O,structureId:m??I?.pop(),stage:at,structureOptions:s,appliedPolicies:a,stageSequence:A,matchUpType:P,roundTarget:d,idPrefix:f,drawSize:r,isMock:g,uuids:I});N=B,h=L,T=x[0],E=[1]}else({drawSize:r,matchUps:y,roundLimit:h,roundsCount:S}=hn({qualifyingRoundNumber:n,qualifyingPositions:o,matchUpType:P,idPrefix:f,drawSize:r,isMock:g,uuids:I})),h||(h=S),T=on({structureName:p??O,structureId:m??I?.pop(),qualifyingRoundNumber:h,stage:at,matchUpFormat:u,stageSequence:A,matchUpType:P,roundLimit:h,matchUps:y}),d&&yt({extension:{name:ln,value:d},element:T}),N=y?.filter(L=>L.roundNumber===h)?.length;let w=l===fn?zn:po,F=T&&h&&Ca({sourceStructureId:T.structureId,sourceRoundNumber:h,targetStructureId:i,finishingPositions:E,linkType:w})?.link;return{qualifyingDrawPositionsCount:r,qualifiersCount:N,...R,structure:T,link:F}}function QU(t){let e=t.tournamentRecord;if(!e)return{error:j};let r=hG(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:nt({drawId:s.drawId,qualifyingRoundNumber:n,qualifyingPositions:o,targetStructureId:i,structureName:a,matchUpType:c,drawSize:u,drawType:p})};return Bi({tournamentRecord:e,timeItem:d}),r}function hG(t){if(!t.drawDefinition)return{error:X};if(!t.targetStructureId)return{error:Sr};let e=cd(t);if(e.error)return e;let{structure:r,link:n}=e;return!r||!n?{error:G}:ig({tournamentRecord:t.tournamentRecord,drawDefinition:t.drawDefinition,structure:r,link:n})}function fv({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=ad({roundPosition:S.roundPosition,roundNumber:r,idPrefix:o,uuids:a}),y={roundPosition:S.roundPosition,drawPositions:[I],matchUpStatus:Qt,roundNumber:r,matchUpId:T};t&&(y.matchUpType=n),s&&(y.isMock=!0),i.push(y);let N={children:[S,h]};l.push(N)}let f=e?e-p:void 0;return{roundNodes:l,matchUps:i,drawPosition:f}}function ri(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=SG({drawSize:i}),h=I.length,S=0;if(r?.length)S=r.reduce((L,x)=>L+x,0);else if(e){let L=e-i;r=I.filter(x=>x<=L?(L-=x,!0):!1),S=r.reduce((x,B)=>x+B,0),n=r.length}else o>=h?n=0:u&&(n=h-u,o=0),r=I.filter((L,x)=>u&&!n||n&&x>=o+n||x<o?0:L),S=r.reduce((L,x)=>L+x,0),n=r.length;let T=[...I,...r].sort((L,x)=>x-L),y=T.length,E=[...(c??[]).map(L=>L-1),...(s??[]).map(L=>y-L)].map(L=>T[L]).reduce((L,x)=>L+x,0);S=S-E;let A=0,U=[],C,P=1,M=Z(0,i).map((L,x)=>({drawPosition:x+1+S})),b=S+1;for(let L of I){if({roundNodes:C,matchUps:U}=Np({matchUpType:m,roundNumber:P,idPrefix:d,matchUps:U,isMock:l,nodes:M,uuids:f}),P++,r.includes(L)){let x=fr(r)[L],B=Z(0,x),H=y+1-P,W=s?.includes(H)??c?.includes(P);B.forEach(()=>{({roundNodes:C,matchUps:U,drawPosition:b}=fv({drawPosition:!W&&b||void 0,nodes:C,matchUpType:m,roundNumber:P,idPrefix:d,matchUps:U,isMock:l,uuids:f,fed:A})),P++,A+=1})}M=C}y!==P-1&&console.log("ERROR");let v=i-S;U=Ua({finishingPositionOffset:p?v:a,positionsFed:S,roundsCount:y,matchUps:U,fmlc:g});let w=C?.length?C[0]:C;return w&&(w.roundNumber=P-1,w.matchUps=U),{draw:w,matchUps:U,roundsCount:y};function F(L){let x=fm(L);return x>L?x/2:x}}function SG({drawSize:t}){let e=Math.ceil(Math.log(t)/Math.log(2));return Z(0,e).reverse().map(n=>Math.pow(2,n))}function yc(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 N=[],E=[],A=[],U=t.matchUpType??d?.matchUpType,C=e+1,P=e+I,D=`${C}-${P}`,M=s?.[c],b=n&&`${n} `||"",v=s?.[D]??o?.[D],O=t.structureName||v?.name||M?.name&&(r?`${b}${M?.name}`:M.name)||`${b}${D}`,w=v?.abbreviation??M?.abbreviation,F=t.structureId??M?.structureId??T?.pop(),L={idPrefix:h&&`${h}-${O}-RP`,finishingPositionOffset:e,matchUpType:U,drawSize:I,isMock:S,uuids:T},{matchUps:x}=l?ri(L):hn(L),B=on({structureAbbreviation:w,stageSequence:a,structureName:O,matchUpType:U,roundOffset:m,structureId:F,matchUps:x,stage:g});N.push(...x),E.push(B);let H=Math.ceil(Math.log(I)/Math.log(2)),W=p?Math.min(p-m,H):!i||C<i?H:0;return I>2&&Z(1,W+1).forEach(Y=>V(Y)),{structureId:B.structureId,matchUps:N,structureName:O,structures:E,links:A,...R};function V(Y){let $=I/Math.pow(2,Y);if($<2)return;let k=I/Math.pow(2,Y)+e;if(i&&k+1>i)return;let{structures:K,structureId:z,matchUps:q,links:et}=yc({finishingPositionOffset:k,exitProfile:`${c}-${Y}`,roundOffset:m+Y,stageSequence:a+1,drawSize:$,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(B.structureId&&z){let Q={linkType:Qn,source:{roundNumber:Y,structureId:B.structureId},target:{roundNumber:1,feedProfile:pn,structureId:z}};et&&B&&et.push(Q),et?.length&&A.push(...et)}return K?.length&&E.push(...K),q?.length&&N.push(...q),{structureId:z,childLinks:et,structures:E}}}function ud({drawDefinition:t,matchUpsMap:e,structureId:r}){let n=st({drawDefinition:t,structureId:r});if(n.error)return _({result:n});let{matchUps:o}=At({structure:n.structure,matchUpsMap:e});return{...qe({matchUps:o}),matchUps:o,matchUpsMap:e}}function XU({finishingPositions:t,drawDefinition:e,structureId:r}){let{roundProfile:n}=ud({drawDefinition:e,structureId:r});return(n&&Object.keys(n))?.reduce((i,s)=>(gv(n?.[s]).forEach(c=>{t.forEach(u=>{TG({position:u,rangeDefinition:c})&&(i[u]={roundNumber:s})})}),i),{})}function TG({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 gv(t){return[pt(t?.finishingPositionRange?.loser||[]),pt(t?.finishingPositionRange?.winner||[])]}function Iv(t){return gv(t).map(e=>Z(e[0],e[1]&&e[1]+1||e[0]+1))}function Ac({drawDefinition:t,structureIds:e,matchUpsMap:r}){if(e&&!Array.isArray(e))return{error:G,context:{structureIds:e}};if(!t)return{error:X};e=e??(t.structures??[]).filter(a=>a.stage!==at).map(({structureId:a})=>a);let n=e.map(a=>{let{roundProfile:c}=ud({drawDefinition:t,matchUpsMap:r,structureId:a});return(c&&Object.values(c))?.map(Iv).flat()}).flat(),o=n.filter(a=>a?.length===1).sort(se).flat();return{positionsNotPlayedOff:pt(n.flat()).filter(a=>!o.includes(a)),positionsPlayedOff:o}}function sS({excludeRoundNumbers:t=[],playoffPositions:e=[],drawDefinition:r,structureId:n}){if(!r)return{error:X};if(!n)return{error:Sr};if(!e)return{error:rt,info:"missing playoffPositions"};let o=Ac({drawDefinition:r});if(o.error)return o;let i=o.positionsPlayedOff,s=e.filter(S=>!i.includes(S)),a=XU({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=XU({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(se),{roundProfile:f}=ud({drawDefinition:r,structureId:n}),g=l.map(S=>{let T=f?.[S].finishingPositionRange.loser,[y,N]=T??[0,0];return Z(y,(N||y)+1)}).flat().sort(se),{playoffRoundsRanges:I}=yG({playoffSourceRounds:l,roundProfile:f}),h=[...l,...d];return{playoffPositionsReturned:g,playedOffSourceRounds:d,playoffRoundsRanges:I,playoffSourceRounds:l,sourceRounds:h,roundProfile:f}}function yG({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 Su({drawDefinition:t,structureId:e}){if(!t)return{error:X};let{matchUps:r,matchUpsMap:n}=or({inContext:!0,drawDefinition:t}),{positionsNotPlayedOff:o,positionsPlayedOff:i}=Ac({drawDefinition:t,matchUpsMap:n}),{structures:s}=Gn({drawDefinition:t}),a=s.filter(u=>!e&&u.stage!==We||u.structureId===e),c={};for(let u of a){let p=u?.structureId,m=AG({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 AG({playoffPositions:t,drawDefinition:e,structure:r,matchUps:n}){let o=r?.structureId,{links:i}=Ws({drawDefinition:e,structureId:o});if(r.structureType===ke||r.structures){let l=Ct({structure:r})?.positionAssignments?.length,f=r.structures.length,g=(l??0)/f,I=i.source?.flatMap(({source:P})=>P?.finishingPositions||[])||[],h=Z(1,g+1).filter(P=>!I.includes(P)),S=n.find(P=>P.containerStructureId===o&&P.finishingPositionRange)?.finishingPositionRange?.winner||[0,1],T=i?.source.map(({target:P})=>P.structureId),{positionsPlayedOff:y=[],positionsNotPlayedOff:N=[]}=Ac({structureIds:T,drawDefinition:e}),E=[...y,...N],A=Z(S[0],S[1]+1).filter(P=>!E.includes(P)),U=Te(A,A.length/h.length),C=h.map((P,D)=>{let M=U[D],b=[Math.min(...M||[]),Math.max(...M||[])].join("-");return{finishingPosition:P,finishingPositions:M,finishingPositionRange:b}});return{positionsNotPlayedOff:A,playoffFinishingPositionRanges:C,finishingPositionsAvailable:h,finishingPositionsPlayedOff:I,positionsPlayedOff:y,groupCount:f,groupSize:g}}let s=i?.source?.filter(l=>l.linkCondition!==Xn).map(l=>l.source?.roundNumber)||[],a=i?.source?.filter(l=>l.linkCondition===Xn).map(l=>l.source?.roundNumber)||[],c=sS({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:y})=>y===I&&T===g),S=h.filter(({sides:T})=>T.find(y=>y.participantFed&&!y.participantId)).length;if(u&&S===h.length){u.push(l);let T=m?.[l]?.finishingPositionRange?.loser;if(T){let y=Math.min(...T),N=y+S,E=Z(y,N),A={finishingPositionRange:[y,N-1].join("-"),finishingPositions:E,roundNumber:l};p.push(A)}}}return u&&u.sort(se),p.sort((l,f)=>l.roundNumber-f.roundNumber),{playoffRounds:u,playoffRoundsRanges:p,error:d}}function hv({playoffGroups:t,drawDefinition:e,structureId:r}){if(!e)return{error:X};if(typeof r!="string"||!Array.isArray(t))return{error:G};let n=t.map(({finishingPositions:a})=>a).flat();return{positionRangeMap:Su({drawDefinition:e,structureId:r}).playoffFinishingPositionRanges?.filter(a=>n.includes(a.finishingPosition))?.reduce((a,c)=>(a[c.finishingPosition]=c,a),{})}}function aS(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?ri(l):hn(l),g=on({structureName:i||r?.["0"]?.name||$e(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}=hn({finishingPositionOffset:e+S,idPrefix:u&&`${u}-c`,drawSize:S,matchUpType:a,isMock:m}),y=$e(He),N=r?.["0-1"]?.name??t.consolationStructureName??(i?`${i} ${y}`:y),E=on({structureName:N,matchUps:T,structureId:d?.pop(),stage:He,stageSequence:1,matchUpType:a});I.push(E);let A={linkType:Qn,source:{roundNumber:1,structureId:g.structureId},target:{roundNumber:1,feedProfile:pn,structureId:E.structureId}};h.push(A)}return{...R,structures:I,links:h}}function cS({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?pn:mi,d=p-e<=2?p-e:(p-e-2)*2+2,l={linkType:Qn,source:{roundNumber:p,structureId:r.structureId},target:{feedProfile:m,roundNumber:d,structureId:t.structureId}},f=c[p-1];return f&&(l.target.groupedOrder=f),Pr()&&(l.source.structureName=r.structureName,l.target.structureName=t.structureName),p===2&&i&&(l.linkCondition=Xn,l.target.feedProfile=pn),a.includes(d)?l:void 0}).filter(Boolean)}function uS(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?ri(f):hn(f),h=t.structureName??o?.["0"]?.name??$e(tt),S=ls({structureId:u||l?.pop(),structureName:h,stageSequence:n,matchUpType:c,matchUps:g,stage:a}),T=[S],y=[];if(p>2){let A=[0,2].slice(0,p/16).map((U,C)=>{let P=C+1,{consolationStructure:D}=EG({idPrefix:m&&`${m}-c${C}`,structureId:l?.pop(),playoffStructureNameBase:e,playoffAttributes:o,structureNameMap:i,stageSequence:P,roundOffset:U,matchUpType:c,drawSize:p,isMock:d,index:C,uuids:l});T.push(D);let M=cS({consolationStructure:D,roundsCount:2,mainStructure:S,roundOffset:U});return{consolationStructure:D,links:M}}).map(U=>U.links).flat();if(y.push(...A),p>=4&&p<=16||p>32){let{matchUps:U}=hn({idPrefix:m&&`${m}-p3t4`,finishingPositionOffset:2,drawSize:2,matchUpType:c,isMock:d}),C=o?.["3-4"]?.name??$e(ue),P=i?.[C]||C,D=e?`${e} ${P}`:P,M=ls({structureId:l?.pop(),matchUps:U,stageSequence:2,stage:ue,structureName:D,matchUpType:c}),b={linkType:Qn,source:{roundNumber:I-1,structureId:S.structureId},target:{structureId:M.structureId,feedProfile:pn,roundNumber:1}};T.push(M),y.push(b)}}return{structures:T,links:y,...R}}function EG({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}=ri({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||`${$e(He)} ${p+1}`,h=n?.[I]||I,S=t?`${t} ${h}`:h;return{consolationStructure:ls({matchUps:l,stage:He,structureName:S,stageSequence:e,matchUpType:i,structureId:s}),consolationRoundsCount:f}}function Ec(t){let{finishingPositionOffset:e,stageSequence:r=1,playoffAttributes:n,feedsFromFinal:o,staggeredEntry:i,structureName:s,stage:a=tt,structureId:c,matchUpType:u,skipRounds:p,feedRounds:m,idPrefix:d,drawSize:l,isMock:f,uuids:g,fmlc:I}=t,h=t.feedPolicy||t.policyDefinitions?.[rc]||t.appliedPolicies?.[rc],S={finishingPositionOffset:e,matchUpType:u,skipRounds:p,drawSize:l,idPrefix:d,isMock:f,uuids:g},{matchUps:T}=i?ri(S):hn(S),y=on({structureName:s||n?.["0"]?.name||$e(tt),structureId:c||g?.pop(),stageSequence:r,matchUpType:u,matchUps:T,stage:a}),N=[y],E=[],A=l/2,{matchUps:U,roundsCount:C}=ri({finishingPositionOffset:A,idPrefix:d&&`${d}-c`,isConsolation:!0,feedsFromFinal:o,baseDrawSize:A,matchUpType:u,feedRounds:m,skipRounds:p,isMock:f,uuids:g,fmlc:I});if(l>2){let P=n?.["0-1"]?.name??$e(He),D=t.playoffStructureNameBase?`${t.playoffStructureNameBase} ${P}`:P,M=on({matchUps:U,structureId:g?.pop(),stage:He,stageSequence:1,structureName:D,matchUpType:u});N.push(M);let b=cS({consolationStructure:M,mainStructure:y,roundsCount:C,feedPolicy:h,fmlc:I});E.push(...b)}return{...R,structures:N,links:E}}function mS({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?.[rc];let f="processPlayoffGroups",g=0,I=[],h=[],S=[],{error:T,positionRangeMap:y}=hv({structureId:n,drawDefinition:s,playoffGroups:a});if(T)return _({result:{error:T},stack:f});if(!(!y||a?.every(E=>{let{finishingPositions:A=[]}=E;if(!A.length)return!1;let U=[...A].sort(se).map((C,P)=>(A[P+1]||C)-C).every(C=>C<2);return(!t||U)&&A.every(C=>y[C])})))return _({context:{validFinishingPositions:Object.values(y)},result:{error:G},stack:f});for(let E of a){let A=E.finishingPositions,U=y&&A.map(F=>y[F]?.finishingPositions).flat(),C=p*A.length,P=Ki(C),D=P===2&&mo||E.drawType||mo;U&&(g=Math.min(...U)-1);let M=U&&`${Math.min(...U)}-${Math.max(...U)}`,b=E.structureName||M&&E.playoffAttributes?.[M]?.name||E.playoffAttributes?.["0"]?.name,O={...{addNameBaseToAttributeName:E.addNameBaseToAttributeName,playoffStructureNameBase:E.playoffStructureNameBase,finishingPositionNaming:E.finishingPositionNaming,finishingPositionLimit:E.finishingPositionLimit,structureId:E.structureId??l?.pop(),playoffAttributes:E.playoffAttributes,structureNameMap:E.structureNameMap,sequenceLimit:E.sequenceLimit,structureName:b},idPrefix:m&&`${m}-po`,appliedPolicies:o,finishingPositionOffset:g,stage:ue,stageSequence:i,matchUpType:c,drawSize:P,isMock:d,uuids:l},w=({playoffStructures:F,playoffLinks:L})=>{let[x]=F,B=pS({playoffStructureId:x.structureId,finishingPositions:A,sourceStructureId:n});S.push(B),S.push(...L),h.push(...F),I.push({structureId:x.structureId,finishingPositions:A}),g+=C};if(D===mo){let{matchUps:F}=hn({finishingPositionLimit:g+C,idPrefix:m&&`${m}-po`,finishingPositionOffset:g,matchUpType:c,drawSize:P,isMock:d,uuids:l}),L=on({structureId:E.structureId??l?.pop(),matchUpFormat:e,stage:ue,structureName:b,stageSequence:i,matchUps:F});h.push(L);let x=pS({playoffStructureId:L.structureId,finishingPositions:A,sourceStructureId:n});S.push(x),g+=C,I.push({structureId:L.structureId,finishingPositions:A})}else if([Jc,Zc,ue].includes(D)){let F={playoffAttributes:E.playoffAttributes??r,playoffStructureNameBase:E.playoffStructureNameBase,structureId:E.structureId??l?.pop(),structureName:E.structureName,idPrefix:m&&`${m}-po`,addNameBaseToAttributeName:!0,finishingPositionOffset:g,stage:ue,roundOffset:0,stageSequence:i,drawSize:P,isMock:d,uuids:l};D===Jc?Object.assign(F,{playoffAttributes:E?.playoffAttributes??r??mf,roundOffsetLimit:3}):D===Zc&&Object.assign(F,{playoffAttributes:E?.playoffAttributes??r??df,roundOffsetLimit:2});let L=yc(F);if(L.error)return L;if(L.links?.length&&S.push(...L.links),L.structures?.length&&h.push(...L.structures),h.sort(di),L.structureId){let x=pS({playoffStructureId:L.structureId,finishingPositions:A,sourceStructureId:n});S.push(x),I.push({structureId:L.structureId,finishingPositions:A})}g+=C}else if([eu,mp,Om,vm,bm,_m].includes(D)){let F=[l?.pop(),l?.pop()],L={playoffStructureNameBase:E.playoffStructureNameBase,structureId:E.structureId??l?.pop(),playoffAttributes:E.playoffAttributes,idPrefix:m&&`${m}-po`,finishingPositionOffset:g,uuids:F,stage:ue,structureName:b,matchUpType:c,feedPolicy:u,drawSize:P,isMock:d},x={[eu]:{fmlc:!0,feedRounds:1},[_m]:{feedRounds:1},[Om]:{feedsFromFinal:3},[vm]:{feedsFromFinal:2},[bm]:{feedsFromFinal:1}};Object.assign(L,x[D]||{});let{structures:B,links:H}=Ec(L),[W]=B,V=pS({playoffStructureId:W.structureId,finishingPositions:A,sourceStructureId:n});S.push(V),S.push(...H),h.push(...B),I.push({structureId:W.structureId,finishingPositions:A}),g+=C}else if([fn].includes(D)){let{structures:F,links:L}=Ma({...O,structureOptions:E.structureOptions||{groupSize:4}});w({playoffStructures:F,playoffLinks:L})}else if([pp].includes(D)){let{structures:F,links:L}=aS(O);w({playoffStructures:F,playoffLinks:L})}else if([MR].includes(D)){let{structures:F,links:L}=uS(O);w({playoffStructures:F,playoffLinks:L})}else if([Xr].includes(D)){let F=on({structureId:E.structureId??l?.pop(),structureName:E.structureName,finishingPosition:Gm,stage:ue,stageSequence:i,matchUps:[]});w({playoffStructures:[F],playoffLinks:[]})}}return{finishingPositionTargets:I,positionRangeMap:y,structures:h,links:S}}function pS({playoffStructureId:t,finishingPositions:e,sourceStructureId:r}){return{linkType:zn,source:{structureId:r,finishingPositions:e},target:{structureId:t,feedProfile:tn,roundNumber:1}}}function Ra({matchUp:t,tieFormat:e,isMock:r,uuids:n}){let{collectionDefinitions:o}=e??{};return{tieMatchUps:(o??[]).map(s=>Tu({matchUp:t,collectionDefinition:s,uuids:n,isMock:r})).filter(Boolean).flat()}}function Tu({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:Qt,collectionPosition:l,collectionId:c,processCodes:u,matchUpType:a,isMock:o}})}function Sv(t){let e="generateAndPopulateRRplayoffStructures";if(!t.playoffGroups)return _({result:{error:rt},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}=mS({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}=ne({inContext:!0,drawDefinition:i}),S=p.map(({structureId:U})=>U),T=I?.filter(({structureId:U})=>S.includes(U)).map(fe),y=h?.drawMatchUps?.filter(({matchUpId:U})=>T?.includes(U));if(y?.length){let U=Ye({drawDefinition:i,event:u})?.tieFormat;U&&y.forEach(C=>{let{tieMatchUps:P}=Ra({isMock:t.isMock,tieFormat:U,matchUp:C});Object.assign(C,{tieMatchUps:P,matchUpType:gn})})}let{positionAssignments:N}=Ct({structureId:r,drawDefinition:i}),E={};N?.forEach(U=>{let D=dt({element:U,name:qo})?.extension?.value?.groupOrder;D&&(E[D]||(E[D]=[]),E[D].push(U.participantId))});let A=Tc({provisionalPositioning:t.provisionalPositioning,structureId:r,applyPositioning:!0,event:t.event,tournamentRecord:o,drawDefinition:i});return A.error&&A.error?.code!==hl.code?_({result:A,stack:e}):{structures:p,links:m,positionsPlayedOff:g,drawDefinition:i,...R}}var Sn="SET3-S:6/TB7",UG="SET3-S:6NOAD",JU="SET3-S:6/TB7-F:TB10",PG="SET3-S:4/TB7",DG="SET3-S:4/TB5@3",NG="SET1-S:T20",MG="SET1-S:8/TB7",CG="SET1-S:8/TB7@7",Tv={FORMAT_STANDARD:Sn,FORMAT_STANDARD_NOAD:UG,FORMAT_ATP_DOUBLES:JU,FORMAT_SHORT_SETS:PG,FORMAT_FAST4:DG,FORMAT_PRO_SET:MG,FORMAT_COLLEGE_PRO_SET:CG,TIMED20:NG};function ag({winningSide:t,matchUpFormat:e=Sn,matchUpStatus:r,tallyPolicy:n,score:o}){let i=[0,0],s=o?.sets,a=typeof t=="number"&&t-1,c=rr(e),u=ZU(c?.bestOf??1);if(typeof a=="number"&&(r===bt&&n?.setsCreditForDefaults||r===vt&&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===er&&(+i[1-a]===u&&(i[1-a]-=1),n?.setsCreditForRetirements&&(i[a]=u)),i}function dS({matchUpFormat:t=Sn,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=rr(t),c=a?.bestOf??1,u=ZU(c),p=a?.setFormat?.tiebreakAt||0,m=[[],[]];if(typeof s=="number"&&(r===bt&&n?.gamesCreditForDefaults||r===vt&&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;yv(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===er&&typeof s=="number"){let d=i.length>u&&a?.finalSetFormat?"finalSetFormat":"setFormat",l=a?.[d];if(yv(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=ag({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 lS({matchUpFormat:t,score:e}){let r=t?rr(t):void 0,n=r?.bestOf??1,o=ZU(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(Av(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 ZU(t){return t&&Math.ceil(t/2)||1}function Av(t){return t==="P"}function yv(t){return!Av(t)}function Ev({participantResults:t,matchUpFormat:e,tallyPolicy:r,perPlayer:n,totalSets:o}){let i=e&&rr(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,y=S+T,N=Math.round(S/y*1e3)/1e3;(N===1/0||isNaN(N))&&(N=S);let E=t[u].gamesWon||0,A=t[u].gamesLost||0,U=(n||0)*(a||0)*(c||0),C=Math.max(U,E+A),P=Math.round(E/C*1e3)/1e3;(P===1/0||isNaN(P))&&(P=0);let D=Math.round(t[u].pointsWon/t[u].pointsLost*1e3)/1e3;(D===1/0||isNaN(D))&&(D=0),t[u].setsWon=p,t[u].setsLost=m,t[u].setsPct=l,t[u].tieMatchUpsWon=f,t[u].tieMatchUpsPct=h,t[u].matchUpsPct=N,t[u].gamesWon=E,t[u].gamesLost=A,t[u].gamesPct=P,t[u].pointsPct=D,t[u].result=`${t[u].matchUpsWon}/${t[u].matchUpsLost}`})}var To="ELO",tP="NTRP",RG="TRN",eP="UTR",cg="WTN",Uv={ELO:To,NTRP:tP,TRN:RG,UTR:eP,WTN:cg};var bG={[To]:{defaultInitialization:1500,decimalsCount:0,range:[0,3e3],ascending:!0},[tP]:{accessors:["ntrpRating","dntrpRatingHundredths"],attributes:{ustaRatingType:""},accessor:"dntrpRatingHundredths",defaultInitialization:3,decimalsCount:1,ascending:!0,range:[1,7]},[eP]:{defaultInitialization:6,accessors:["utrRating"],accessor:"utrRating",decimalsCount:2,ascending:!0,range:[1,16]},[cg]:{attributes:{confidence:{generator:!0,range:[60,100]}},accessors:["wtnRating","confidence"],defaultInitialization:23,accessor:"wtnRating",ascending:!1,decimalsCount:2,range:[40,1]}},Ke=bG;function yu({value:t,sourceRange:e,targetRange:r}){return(t-e[0])*(r[1]-r[0])/(e[1]-e[0])+r[0]}function Pv({sourceRatingType:t,sourceRating:e}){let r=Ke[t].range,n=r[0]>r[1],o=Ke[To].range;return yu({value:n?r[0]-e:e,sourceRange:r,targetRange:o})}function Dv({targetRatingType:t,sourceRating:e}){let r=Ke[t].decimalsCount||0,n=Ke[t].range,o=n[0]>n[1],i=Ke[To].range,s=yu({targetRange:n,sourceRange:i,value:e}),a=parseFloat(parseFloat(s).toFixed(r));return o?n[0]-a:a}function rP(t){let e=ut(t,[{ratings:!0,[dn]:Yn}]);if(e.error)return e;let r=t.matchUpType&&[Kt,wt].includes(t.matchUpType)?t.matchUpType:Kt,n=Object.keys(Ke),o=t.targetRatingType&&n.includes(t.targetRatingType)?t.targetRatingType:To,i=t.ratings[r]?t.ratings[r].reduce((m,d)=>m.includes(d.scaleName)?m:m.concat(d.scaleName),[]):[];if(!i)return{error:Le};let s=t.ratings[r]?.find(m=>m.scaleName===o)??t.ratings[r][0];if(i[0]===o)return s;let a=Ke[s.scaleName].accessor,c=a?s.scaleValue[a]:s.scaleValue,u=Pv({sourceRatingType:s.scaleName,sourceRating:c});return{convertedRating:Dv({targetRatingType:o,sourceRating:u})}}function Au({participantIds:t,pressureRating:e,matchUpFormat:r,tallyPolicy:n,perPlayer:o,matchUps:i}){let s={},a=n?.excludeMatchUpStatuses||[],c=i?.filter(m=>(m.tieMatchUps||!a.includes(m.matchUpStatus))&&(!t?.length||jt(t,[pd(m,0),pd(m,1)]).length===2)),p=c?.flatMap(({score:m,tieMatchUps:d})=>d?d.filter(({matchUpStatus:l})=>!a.includes(l)).flatMap(({score:l})=>l?.sets?.length??0):m?.sets?.length??0)?.reduce((m,d)=>m+d,0);for(let m of c??[]){let{matchUpStatus:d,tieMatchUps:l,tieFormat:f,score:g,winningSide:I,sides:h}=m,S=f&&m._disableAutoCalc&&f.collectionDefinitions.every(({scoreValue:A})=>A),T=I&&vG(m),y=I&&OG(m);if(!T&&!y)if(d&&ae.includes(d)){let A=pd(m,0),U=pd(m,1);A&&(Uc(s,A),s[A].matchUpsCancelled+=1),U&&(Uc(s,U),s[U].matchUpsCancelled+=1)}else if(l?.length){o=0;for(let A of l){if(A.winningSide){let U=h?.find(({sideNumber:P})=>P===A.winningSide)?.participantId,C=h?.find(({sideNumber:P})=>P===A.winningSide)?.participantId;U&&C&&(Uc(s,U),Uc(s,C),s[U].tieMatchUpsWon+=1,s[C].tieMatchUpsLost+=1,ie(Kt)(A.matchUpType)?(s[U].tieSinglesWon+=1,s[C].tieSinglesLost+=1):ie(wt)(A.matchUpType)&&(s[U].tieDoublesWon+=1,s[C].tieDoublesLost+=1))}Nv({score:A.score,manualGamesOverride:S,participantResults:s,sides:h})}}else Nv({manualGamesOverride:S,participantResults:s,score:g,sides:h});else if(Uc(s,T),Uc(s,y),l?.length){o=0;for(let A of l){let{matchUpType:U}=A,C=ie(wt)(U),P=ie(Kt)(U);A.winningSide&&(A.winningSide===I?(T&&(s[T].tieMatchUpsWon+=1,P&&(s[T].tieSinglesWon+=1),C&&(s[T].tieDoublesWon+=1)),y&&(s[y].tieMatchUpsLost+=1,P&&(s[y].tieSinglesLost+=1),C&&(s[y].tieDoublesLost+=1))):A.winningSide!==I&&(y&&(s[y].tieMatchUpsWon+=1,P&&(s[y].tieSinglesWon+=1),C&&(s[y].tieDoublesWon+=1)),T&&(s[T].tieMatchUpsLost+=1,P&&(s[T].tieSinglesLost+=1),C&&(s[T].tieDoublesLost+=1)))),Mv({matchUpFormat:A.matchUpFormat,matchUpStatus:A.matchUpStatus,score:A.score,sides:A.sides,winningParticipantId:T,losingParticipantId:y,manualGamesOverride:S,participantResults:s,isTieMatchUp:!0,pressureRating:e,tallyPolicy:n,winningSide:I})}Cv({winningParticipantId:T,losingParticipantId:y,participantResults:s,matchUpStatus:d})}else Mv({matchUpFormat:m.matchUpFormat??r,isTieMatchUp:void 0,winningParticipantId:T,manualGamesOverride:S,losingParticipantId:y,participantResults:s,pressureRating:e,matchUpStatus:d,tallyPolicy:n,winningSide:I,score:g,sides:h});let N=g?.sets?.reduce((A,U)=>A+(U?.side1Score??0),0),E=g?.sets?.reduce((A,U)=>A+(U.side2Score??0),0);if(S){let A=h?.find(({sideNumber:C})=>C===1)?.participantId,U=h?.find(({sideNumber:C})=>C===2)?.participantId;Uc(s,A),Uc(s,U),A&&(s[A].gamesWon+=N,s[A].gamesLost+=E),U&&(s[U].gamesWon+=E,s[U].gamesLost+=N)}}return Ev({participantResults:s,matchUpFormat:r,tallyPolicy:n,perPlayer:o,totalSets:p}),{participantResults:s}}function vG(t){let e=t.winningSide-1;return pd(t,e)}function OG(t){let e=1-(t.winningSide-1);return pd(t,e)}function pd(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 Uc(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,pressureScores:[],ratingVariation:[],retirements:0,setsLost:0,setsWon:0,tieSinglesWon:0,tieSinglesLost:0,tieDoublesWon:0,tieDoublesLost:0,tieMatchUpsLost:0,tieMatchUpsWon:0,victories:[],walkovers:0})}function Nv({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&&(Uc(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 Mv({winningParticipantId:t,manualGamesOverride:e,losingParticipantId:r,participantResults:n,pressureRating:o,matchUpFormat:i,matchUpStatus:s,isTieMatchUp:a,tallyPolicy:c,winningSide:u,score:p,sides:m}){let d=u&&u-1,l=1-d;if(o){let h=D=>parseFloat(Number(Math.round(D*1e3)/1e3).toFixed(2)),S=p?.sets?.reduce((D,M)=>D+(M?.side1Score??0),0),T=p?.sets?.reduce((D,M)=>D+(M.side2Score??0),0),y=m.find(({sideNumber:D})=>D===1),N=m.find(({sideNumber:D})=>D===2),E=rP({ratings:y?.participant?.ratings}).convertedRating,A=rP({ratings:N?.participant?.ratings}).convertedRating,U=S*A,C=T*E;n[y?.participantId].pressureScores.push(h(U/(U+C))),n[N?.participantId].pressureScores.push(h(C/(U+C)));let P=Math.max(...Ke[To].range);n[y?.participantId].ratingVariation.push(h((E-A)/P)),n[N?.participantId].ratingVariation.push(h((A-E)/P))}a||Cv({winningParticipantId:t,losingParticipantId:r,participantResults:n,matchUpStatus:s});let f=ag({matchUpStatus:s,matchUpFormat:i,tallyPolicy:c,winningSide:u,score:p}),g=dS({matchUpStatus:s,matchUpFormat:i,tallyPolicy:c,winningSide:u,score:p}),{pointsTally:I}=lS({score:p,matchUpFormat:i});t&&(n[t].setsWon+=f[d],n[t].setsLost+=f[l],e||(n[t].gamesWon+=g[d],n[t].gamesLost+=g[l]),n[t].pointsWon+=I[d],n[t].pointsLost+=I[l]),r&&(n[r].setsWon+=f[l],n[r].setsLost+=f[d],e||(n[r].gamesWon+=g[l],n[r].gamesLost+=g[d]),n[r].pointsWon+=I[l],n[r].pointsLost+=I[d])}function Cv({winningParticipantId:t,losingParticipantId:e,participantResults:r,matchUpStatus:n}){e&&(n===vt&&(r[e].walkovers+=1),n===bt&&(r[e].defaults+=1),n===er&&(r[e].retirements+=1),[bt,er,vt].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 Rv({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
3
+ `].join("")});r?.length&&console.log(...r)}function Ub(){Gh.length=0}function Cr({provisionalPositioning:t,isPositionAction:e,tournamentRecord:r,drawDefinition:n,drawPosition:o,matchUpsMap:i,structureId:s,structure:a,event:c}){if(!n)return{error:X};if(a||({structure:a}=st({drawDefinition:n,structureId:s})),!a)return{error:Gt};s||({structureId:s}=a);let u="assignDrawPositionBye";Hn({method:u,color:"cyan",drawPosition:o}),i||(i=ye({drawDefinition:n}));let{positionAssignments:p}=Ct({structure:a}),{activeDrawPositions:m}=Da({drawDefinition:n,structureId:s});if(p?.find(M=>M.drawPosition===o)?.bye)return{...R};if(m?.includes(o))return{error:Bu};let f=p?.find(M=>M.drawPosition===o);if(!f)return{error:Ds};let{filled:g,containsBye:I,assignedParticipantId:h}=LF(f);if(I)return{...R};if(g&&!I)return _({result:{error:ja},stack:u});let S=ht({tournamentRecord:r,drawDefinition:n,event:c}).appliedPolicies??{},T=ne({inContext:!0,drawDefinition:n,matchUpsMap:i}).matchUps??[],y={isCollectionMatchUp:!1},{matchUps:N}=At({provisionalPositioning:t,drawDefinition:n,matchUpFilters:y,matchUpsMap:i,structure:a});if(p?.forEach(M=>{M.drawPosition===o&&(M.bye=!0)}),a.structureType===ke)return FF({tournamentRecord:r,drawDefinition:n,drawPosition:o,matchUps:N}),Mo({tournamentId:r?.tournamentId,drawDefinition:n,structure:a,event:c}),Pb({assignedParticipantId:h,isPositionAction:e,appliedPolicies:S,drawDefinition:n,drawPosition:o,structureId:s,stack:u});let{roundProfile:E,roundMatchUps:A}=qe({matchUps:N}),C=(E&&Object.keys(E).map(M=>parseInt(M)).reverse())?.find(M=>E?.[M].drawPositions?.includes(o)),P=C?A?.[C].find(({drawPositions:M})=>M?.includes(o)):void 0;P&&Db({tournamentRecord:r,drawDefinition:n,matchUp:P,event:c});let D=P?.drawPositions?.find(M=>M!==o);if(P&&D){let M=kh({sourceDrawPositions:P.drawPositions,matchUpId:P.matchUpId,inContextDrawMatchUps:T,drawPositionToAdvance:D,tournamentRecord:r,drawDefinition:n,matchUpsMap:i});if(M.error)return M}return Mo({tournamentId:r?.tournamentId,drawDefinition:n,structure:a,event:c}),Pb({assignedParticipantId:h,isPositionAction:e,appliedPolicies:S,drawDefinition:n,drawPosition:o,structureId:s,stack:u})}function Pb({assignedParticipantId:t,isPositionAction:e,appliedPolicies:r,drawDefinition:n,drawPosition:o,structureId:i,stack:s}){return e&&ru({appliedPolicies:r,drawDefinition:n,positionAction:{removedParticipantId:t,drawPosition:o,structureId:i,name:s}}),_({result:{...R},stack:s})}function LF(t){let e=t.bye,r=t.qualifier,n=t.participantId;return{containsBye:e,containsQualifier:r,assignedParticipantId:n,filled:e||r||n}}function Db({tournamentRecord:t,drawDefinition:e,eventId:r,matchUp:n,event:o}){Object.assign(n,{matchUpStatus:Nt,score:void 0,winningSide:void 0}),It({tournamentId:t?.tournamentId,eventId:r??o?.eventId,context:"setMatchUpStatusBye",drawDefinition:e,matchUp:n})}function FF({tournamentRecord:t,drawDefinition:e,drawPosition:r,matchUps:n,event:o}){n.forEach(i=>{i.drawPositions?.includes(r)&&Db({eventId:o?.eventId,tournamentRecord:t,drawDefinition:e,matchUp:i})})}function kh({drawPositionToAdvance:t,inContextDrawMatchUps:e,sourceDrawPositions:r,tournamentRecord:n,drawDefinition:o,matchUpsMap:i,matchUpId:s,event:a}){Hn({method:"advanceDrawPosition",color:"cyan",drawPositionToAdvance:t});let u=i.drawMatchUps.find(N=>N.matchUpId===s),m=e.find(N=>N.matchUpId===s)?.structureId,{structure:d}=st({drawDefinition:o,structureId:m}),{positionAssignments:l}=Ct({structure:d}),f=l?.filter(N=>N.bye).map(N=>N.drawPosition),g=u?.drawPositions?.find(N=>N!==t),I=g&&f?.includes(g),{targetLinks:{loserTargetLink:h},targetMatchUps:{loserMatchUp:S,winnerMatchUp:T,loserTargetDrawPosition:y}}=nr({inContextDrawMatchUps:e,drawDefinition:o,matchUpId:s});if(T&&T.structureId===d?.structureId&&GF({drawPositionToAdvance:t,inContextDrawMatchUps:e,sourceDrawPositions:r,tournamentRecord:n,drawDefinition:o,winnerMatchUp:T,matchUpsMap:i,event:a}),S&&I&&S.structureId!==d?.structureId){let{roundNumber:N}=S;if(N===1){let E=Cr({structureId:h.target.structureId,drawPosition:y,tournamentRecord:n,drawDefinition:o,event:a});if(E.error)return E}else Nb({loserTargetDrawPosition:y,tournamentRecord:n,loserTargetLink:h,drawDefinition:o,loserMatchUp:S,matchUpsMap:i,event:a})}return{...R}}function GF({drawPositionToAdvance:t,inContextDrawMatchUps:e,sourceDrawPositions:r,tournamentRecord:n,drawDefinition:o,winnerMatchUp:i,matchUpsMap:s,event:a}){let c="advanceWinner",u=s.drawMatchUps.find(L=>L.matchUpId===i.matchUpId),m=e.find(L=>L.matchUpId===i.matchUpId)?.structureId,{structure:d}=st({drawDefinition:o,structureId:m}),{positionAssignments:l}=Ct({structure:d}),g=l?.find(({drawPosition:L})=>L===t)?.bye,I=u.drawPositions?.filter(Boolean),h=l?.filter(L=>I?.includes(L.drawPosition)),S=l?.find(({drawPosition:L})=>L===t),T=r?.find(L=>L!==t),N=(T&&h?.find(({drawPosition:L})=>L===T))?.bye,E=g&&N;if(E&&console.log({isByeAdvancedBye:E}),I?.length>1&&g&&!N)return _({result:{error:ja},stack:c});let A=I?.find(L=>L!==t),U=E,C=[...(u.drawPositions||[]).filter(Boolean),void 0,void 0].slice(0,2),P=C.map(L=>!L&&!U||L===t?(U=!0,t):L).sort(se);if(!U)return console.log("@@@@@@@",{advancingAssignmentIsBye:S,drawPositionToAdvance:t,existingAssignments:h}),_({result:{error:ja},stack:c});let D=l?.find(({drawPosition:L})=>L===A)?.bye,M=l?.find(({drawPosition:L})=>L===t)?.bye;Object.assign(u,{matchUpStatus:M||D?Nt:Qt,score:void 0,winningSide:void 0,drawPositions:P});let v=u.drawPositions.find(L=>!C.includes(L));Hn({method:c,color:"brightyellow",changedDrawPosition:v,pairedDrawPositionIsBye:D,drawPositionIsBye:M}),It({tournamentId:n?.tournamentId,matchUp:u,eventId:a?.eventId,context:c,drawDefinition:o});let{targetLinks:{loserTargetLink:O},targetMatchUps:{loserMatchUp:w,loserTargetDrawPosition:F}}=nr({matchUpId:i.matchUpId,inContextDrawMatchUps:e,drawDefinition:o});if(D||M){let L=D?t:A;if(L)kh({drawPositionToAdvance:L,matchUpId:i.matchUpId,inContextDrawMatchUps:e,tournamentRecord:n,drawDefinition:o,matchUpsMap:s});else if(M&&O&&w)if(w.feedRound)Nb({loserTargetDrawPosition:F,tournamentRecord:n,loserTargetLink:O,drawDefinition:o,loserMatchUp:w,matchUpsMap:s});else{let B=1-i.roundPosition%2,H=w.drawPositions[B],W=Cr({structureId:O.target.structureId,drawPosition:H,tournamentRecord:n,drawDefinition:o,event:a});if(W.error)return W}}}function Nb({loserTargetDrawPosition:t,tournamentRecord:e,loserTargetLink:r,drawDefinition:n,loserMatchUp:o,matchUpsMap:i,event:s}){let{roundNumber:a}=o;Hn({method:"assignFedDrawPositionBye",color:"cyan",loserTargetDrawPosition:t});let p=(i?.mappedMatchUps||{})[o.structureId].matchUps,{initialRoundNumber:m}=us({drawPosition:t,matchUps:p});if(m===a){let d=Cr({structureId:r.target.structureId,drawPosition:t,tournamentRecord:e,drawDefinition:n,event:s});if(d.error)return d}}function Vh({positionAssignments:t,tournamentRecord:e,drawDefinition:r,matchUpsMap:n,structure:o,event:i}){let{matchUps:s}=At({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?Nt:Qt}),It({tournamentId:e?.tournamentId,context:"modifyRoundRobinMatchUpsStatus",eventId:i?.eventId,drawDefinition:r,matchUp:a}))})}function lc(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:Ns};r||(r=m?.participantId);let{activeDrawPositions:d}=Da({drawDefinition:i,structureId:s});return d.includes(n)?{error:Bu}:(e||({matchUps:e}=ne({inContext:!0,drawDefinition:i,matchUpsMap:a})),gU({inContextDrawMatchUps:e,tournamentRecord:o,drawDefinition:i,structureId:s,drawPosition:n,matchUpsMap:a,event:c}).drawPositionCleared?(Mo({tournamentId:o?.tournamentId,drawDefinition:i,structure:u,event:c}),{...R,participantId:r}):{error:pA})}function gU({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:Gt};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===ke)return Vh({positionAssignments:c,tournamentRecord:e,drawDefinition:r,matchUpsMap:o,structure:a}),{drawPositionCleared:u,...R};let p={isCollectionMatchUp:!1},{matchUps:m}=At({drawDefinition:r,matchUpFilters:p,matchUpsMap:o,structure:a,event:s}),{roundProfile:d,roundMatchUps:l}=qe({matchUps:m}),g=(d&&Object.keys(d))?.map(T=>ct(T)),I=n,S=g?.map(T=>{let N=d?.[T]?.pairedDrawPositions?.find(v=>v.includes(I)),E=N?.find(v=>v!==I),A=c.find(v=>v.drawPosition===E),U=d?.[T+1],C=A?.bye,P=U?.pairedDrawPositions?.find(v=>v.includes(E)),D=C&&P&&U&&U.drawPositions?.includes(E),b=N&&{pairedDrawPositionByeAdvancedPair:!D&&P,pairedDrawPosition:E,targetDrawPosition:I,relevantPair:N,roundNumber:T};return D&&(I=E),b}).filter(T=>T?.targetDrawPosition)?.reduce((T,y)=>{let{roundNumber:N,relevantPair:E,targetDrawPosition:A,pairedDrawPosition:U,pairedDrawPositionByeAdvancedPair:C}=y,P={roundNumber:N,targetDrawPosition:A,relevantPair:E},D=C&&{roundNumber:N+1,targetDrawPosition:U,relevantPair:C,subsequentRoundRemoval:!0},M=[P,D].filter(Boolean);return T.concat(...M)},[]);return S?.forEach(({roundNumber:T,targetDrawPosition:y,relevantPair:N})=>{let E=l?.[T].find(A=>Fe(A.drawPositions?.filter(Boolean),N.filter(Boolean)));E&&(kF({inContextDrawMatchUps:t,targetDrawPosition:y,tournamentRecord:e,drawDefinition:r,structureId:i,roundNumber:T,matchUpsMap:o}),Mb({inContextDrawMatchUps:t,positionAssignments:c,tournamentRecord:e,drawDefinition:r,targetMatchUp:E,drawPosition:n,matchUpsMap:o,structure:a,event:s}))}),{tasks:S,drawPositionCleared:u,positionAssignments:c}}function kF({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:Gt};if(a.structureType===ke)return;o=o||ye({drawDefinition:n});let u=(o?.mappedMatchUps||{})[s].matchUps,{initialRoundNumber:p}=us({drawPosition:e,matchUps:u}),m=u?.filter(l=>l.roundNumber>=i&&l.roundNumber!==p&&l.drawPositions?.includes(e)),d=Ct({drawDefinition:n,structureId:s}).positionAssignments??[];return m?.forEach(l=>Mb({drawPosition:e,targetMatchUp:l,inContextDrawMatchUps:t,positionAssignments:d,tournamentRecord:r,drawDefinition:n,matchUpsMap:o,structure:a})),{...R}}function Mb({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??ye({drawDefinition:n});let f=s.mappedMatchUps[a.structureId].matchUps,{initialRoundNumber:g}=us({drawPosition:i,matchUps:f});if(o.roundNumber&&g&&o.roundNumber>g){let P=(o.drawPositions??[]).map(D=>D===i?void 0:D);o.drawPositions=P}if(o.matchUpType===Bt){let M=(t?.find(b=>b.matchUpId===o.matchUpId)?.sides??[]).reduce((b,v,O)=>v.drawPosition===i?O:b,void 0);M!==void 0&&o.sides?.[M]?.lineUp&&(delete o.sides?.[M].lineUp,It({tournamentId:r?.tournamentId,context:`${u}-TEAM`,eventId:c?.eventId,matchUp:o,drawDefinition:n}))}let I=nr({matchUpId:o.matchUpId,inContextDrawMatchUps:t,drawDefinition:n}),{targetLinks:{winnerTargetLink:h},targetMatchUps:{loserMatchUp:S,winnerMatchUp:T,loserMatchUpDrawPositionIndex:y}}=I,E=e.filter(({drawPosition:P})=>o.drawPositions?.includes(P)).filter(P=>P.bye).length,A=E&&Nt||o.matchUpStatus&&[bt,vt].includes(o.matchUpStatus)&&o.matcHUpStatus||o.drawPositions?.length===2&&Qt||void 0;o.matchUpStatus=A,o.matchUpStatus&&[vt,bt].includes(o.matchUpStatus)&&(o.winningSide=void 0);let U=p?.find(P=>!o.drawPositions?.includes(P));if(p?.includes(i)&&m===o.matchUpStatus&&d===o.winningSide||(U&&Hn({method:u,color:"brightyellow",removedDrawPosition:U}),It({tournamentId:r?.tournamentId,eventId:c?.eventId,matchUp:o,context:`${u}-${i}`,drawDefinition:n})),S&&S.structureId!==I.matchUp.structureId&&!E){let{drawPositions:P,roundNumber:D}=S;if(D===1){let M=P[y];gU({structureId:S.structureId,drawPosition:M,inContextDrawMatchUps:t,tournamentRecord:r,drawDefinition:n,matchUpsMap:s})}else{let M=Math.min(...P.filter(Boolean)),b=VF({loserMatchUpDrawPosition:M,inContextDrawMatchUps:t,tournamentRecord:r,drawDefinition:n,loserMatchUp:S,matchUpsMap:s,event:c});if(b.error)return _({result:b,stack:u});let O=(s?.mappedMatchUps||{})[S.structureId].matchUps,{initialRoundNumber:w}=us({drawPosition:M,matchUps:O});w===1&&(Hn({method:u,color:"brightyellow",loserMatchUpDrawPosition:M}),gU({structureId:S.structureId,drawPosition:M,inContextDrawMatchUps:t,tournamentRecord:r,drawDefinition:n,matchUpsMap:s}))}}return T&&T.structureId!==I.matchUp.structureId&&(h.target.feedProfile,tn),{...R}}function VF({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}=Ct({structure:a});if(c?.find(p=>p.drawPosition===t)?.bye){let p=lc({drawPosition:t,structureId:o.structureId,inContextDrawMatchUps:e,tournamentRecord:r,drawDefinition:n,matchUpsMap:i,event:s});if(p.error)return p}return{...R}}function Ei({drawDefinition:t,stages:e}){if(!t)return{error:X};let r=(t?.structures??[]).filter(o=>!e?.length||o.stage&&e.includes(o.stage)),n=pt(r.map(o=>{let{positionAssignments:i}=Ct({structure:o});return i?i.map(gt):[]}).flat().filter(Boolean));return{...R,assignedParticipantIds:n}}function Wn(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 Ys(t){return[gi,Br].includes(t)}function Jm({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:Zr,method:"modifyEntriesStatus",participantIds:o};if(!n&&!m)return{error:Dt};if(i&&!nU.includes(i))return{error:Ol};if(s&&!Rm.includes(s))return{error:Ri};let d="modifyEntriesStatus",l=[];if(!i&&!a)return _({result:{error:rt},info:"Missing entryStatus",stack:d});if(a&&!Mn({extension:a,requiredAttributes:["name"]}))return _({result:{error:G},info:"Invalid extension",context:{extension:a},stack:d});let f=[];m?.drawDefinitions?.forEach(P=>{let D=Ei({stages:p&&[p],drawDefinition:P}).assignedParticipantIds??[];f.push(...D)});let g=r?.participants??[];if(!o.every(P=>{let D=Lo({tournamentParticipants:g,participantId:P})?.participantType;return!(D&&[lt,rn].includes(D)&&Ys(i))&&!(i&&m?.eventType&&D===Tt&&[Jr,jr].includes(m.eventType)&&[kr,...Of].includes(i))}))return{error:Ol};let h=m&&Ht({event:m}).flightProfile,S=h?.flights?.find(P=>P.drawId===u),T=P=>{let D=(P||[]).filter(v=>!p||!v.entryStage||p===v.entryStage).filter(({participantId:v})=>o.includes(v)),M=v=>i&&f.includes(v.participantId)&&!(Of.includes(v.entryStatus)&&Of.includes(i));return D.every(v=>M(v)&&!e?!1:(i&&(v.entryStatus=i,delete v.entryPosition),s&&(v.entryStage=s,delete v.entryPosition),a&&(a.value?yt({element:v,extension:a}):sr({element:v,name:a.name})),!0))?{...R}:{error:Rs}},y=({flight:P,drawDefinition:D})=>{m&&(m.entries=Wn({entries:m.entries??[]})),P&&(P.drawEntries=Wn({entries:P.drawEntries})),D&&(D.entries=Wn({entries:D.entries}))},N=P=>{let{flight:D,drawDefinition:M}=P,b="updateDrawEntries";if(D){let v=T(D.drawEntries);if(v.error)return _({result:v,stack:b})}if(M){let v=T(M.entries);if(v.error)return _({result:v,stack:b});l.includes(M.drawId)||l.push(M.drawId)}return{...R}},E=m?.entries?.find(({entryPosition:P})=>P)??(S?.drawEntries?.find(({entryPosition:P})=>P)||n?.entries?.find(({entryPosition:P})=>P));if(t&&!E&&y({flight:S,drawDefinition:n}),S||n){let P=N({flight:S,drawDefinition:n});if(P.error)return _({result:P,stack:d})}let A=m?.drawDefinitions?.map(({drawId:P})=>P)??[],U=h?.flights?.filter(P=>!A.includes(P.drawId))||[];for(let P of U){let D=P&&N({flight:P});if(D?.error)return _({result:D,stack:d})}let C=h?.flights?.length===1&&(m?.drawDefinitions?.length??0)<=h?.flights?.length;if(!S&&!n&&i&&rU.includes(i))return{error:jA};if(!S&&!n||i===Jn||c&&C){let P=T(m?.entries);if(P?.error)return _({result:P,stack:d});let D;if(i===Jn&&(h?.flights?.every(M=>{let b=T(M.drawEntries);return b.error?(D=b.error,!1):(M.drawEntries=M.drawEntries.filter(({participantId:v})=>!o.includes(v)),!0)}),m?.drawDefinitions?.every(M=>{let b=T(M.entries);return b.error?(D=b.error,!1):(M.entries=M.entries?.filter(({participantId:v})=>!o.includes(v)),!0)})),D)return _({result:{error:D},stack:d})}t&&y({flight:S,drawDefinition:n});for(let P of m?.drawDefinitions??[])l.length&&!l.includes(P.drawId)||Ot({tournamentId:r.tournamentId,eventId:m?.eventId,drawDefinition:P});return{...R}}function So({requireTimeStamp:t,scaleAttributes:e,participant:r}){if(!r)return{error:vi};if(!Pt(e))return{error:G};if(r.timeItems||(r.timeItems=[]),Array.isArray(r.timeItems)){let{accessor:n,scaleType:o,eventType:i,scaleName:s}=e,a=[Ji,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!==Ji)return{error:qu};let g=(n&&cs({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 Cb({publishedSeeding:t,usePublishState:e,withSeeding:r,participant:n,event:o}){let i={},s=m=>[Ji,ao,o.eventType,m].join("."),a=Object.assign({},...(n.timeItems||[]).filter(({itemType:m})=>m.split(".")[1]===ao).map(({itemType:m,itemValue:d})=>({[m]:d}))),c=(t?.stageSeedingScaleNames&&Object.values(t?.stageSeedingScaleNames)||Array.isArray(t?.seedingScaleNames)&&t.seedingScaleNames||[]).map(s),u=jt(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:ao,scaleName:g},h=So({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 Rb({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({},...rf(m??[])):{},l=Object.assign(d,{entryPosition:p,entryStatus:c,entryStage:u,ranking:s,eventId:i});r.events[i]=nt(l,!1,!1,!0),n&&(e&&(r.events[i].seedAssignments=e),o&&(r.events[i].seedValue=o))}function Bh(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===Nt||e[r].scheduleItems.push({...p,scheduledDate:Ut(p?.scheduledDate),scheduledTime:$t(p?.scheduledTime),checkScoreHasValue:Ie({score:d}),matchUpStatus:n,roundPosition:o,structureId:i,matchUpType:s,roundNumber:a,matchUpId:c,potential:u,drawId:m})}function bb({tournamentRecord:t,status:e=Wr}){let r=`${Xo}.${Jo}`;return au({tournamentRecord:t,itemType:r})?.timeItem?.itemValue?.[e]}function vb(t){let{tournamentId:e}=t??{};return!!e}function Lr({event:t,status:e=Wr}){let r=`${Xo}.${Jo}`;return su({itemType:r,event:t})?.timeItem?.itemValue?.[e]}function Zm({drawDetails:t,drawId:e}){return t?.[e]?.publishingDetail?.published}function ps(t){let{tournamentRecord:e,drawDefinition:r,eventIds:n,eventId:o,drawIds:i,drawId:s,event:a}=t??{};if(e&&!vb(e))return{error:G};if(o&&!a)return{error:lr};if(Array.isArray(n)&&n?.length){let d={};for(let l of n){if(!Re(l))return{error:G};let f=je({tournamentRecord:e,eventId:l})?.event;if(!f)return{error:lr};let g=IU({event:f});d[l]=g}return{...R,publishState:d}}if(a){let d=IU({event:a}),l={};if(s)return r?{publishState:{status:{published:!!d.status.publishedDrawIds?.includes(s),drawDetail:d.status.drawDetails?.[s]},...R}}:{error:dr};if(Array.isArray(i)&&i?.length){let f=a.drawDefinitions?.map(zc)??[];for(let g of i){if(!Re(g))return{error:G};if(!f.includes(g))return{error:dr};l[g]={status:{published:!!d.status.publishedDrawIds.includes(g),drawDetail:d.status.drawDetails?.[g]}}}}else l=d;return{...R,publishState:l}}let c=[],u=!1,p={},m=bb({tournamentRecord:e});p.tournament=m??{};for(let d of e?.events??[]){let l=IU({event:d});p[d.eventId]=l,l.status.published&&(c.push(d.eventId),u=!0);for(let{drawId:f}of d.drawDefinitions??[]){let g=l.status?.publishedDrawIds?.includes(f);g&&(p[f]={status:{published:g}})}}return e&&(p.tournament.status={published:u,publishedEventIds:c}),{...R,publishState:p}}function IU({event:t}){let e=Lr({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(zc)||[])n[i]||(n[i]={publishingDetail:{published:!1}});let o=n&&Object.keys(n).length&&Object.keys(n).filter(i=>Zm({drawDetails:n,drawId:i}))||e.drawIds;return{status:{published:o&&o.length>0,publishedDrawIds:o,publishedSeeding:r,drawDetails:n}}}function fu(t,e){return(t||"").localeCompare(e||"")}function Ob({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===vt&&(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 hU(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:y,matchUpSides:N,collectionId:E,matchUpType:A,winningSide:U,matchUpId:C,schedule:P,eventId:D,drawId:M,sides:b}=t,v=i&&b?.length===2&&Object.assign({},...b.map(({sideNumber:O},w)=>{let F=b[1-w].participantId;return O&&{[O]:F}}).filter(Boolean));for(let O of b){let{participantId:w,sideNumber:F,bye:L}=O;if(L)continue;let x=U===F,B=V=>{let Y=o[V]?.participant,$=Y?.participantType,k=[{participantId:V,participantType:$}];if($!==rn)for(let K of Y?.individualParticipantIds||[]){let z=o[K]?.participant;k.push({participantType:z?.participantType,participantId:K})}return k},H=(V,Y)=>{if(s){if(o[V].matchUps[C]={participantWon:x,matchUpType:A,structureId:f,sideNumber:F,matchUpId:C,eventId:D,drawId:M,stage:I},i){let $=B(Y);o[V].matchUps[C].opponentParticipantInfo=$}E&&(o[V].matchUps[C].collectionId=E)}i&&Y&&(o[V].opponents[Y]={participantId:Y,matchUpId:C,eventId:D,drawId:M}),h&&Ob({finishingPositionRange:u,participantMap:o,participantWon:x,finishingRound:p,matchUpStatus:m,participantId:V,stageSequence:d,roundNumber:l,structureId:f,matchUpId:C,drawId:M,stage:I}),(r||e)&&Bh({participantMap:o,participantId:V,matchUpStatus:m,roundPosition:T,matchUpType:A,roundNumber:l,structureId:f,matchUpId:C,schedule:P,drawId:M,score:g})},W=({participant:V,partnerParticipantId:Y})=>{let $=(k,K)=>{k&&(k.partnerParticipantIds||(k.partnerParticipantIds=[]),k.partnerParticipantIds.includes(K)||k.partnerParticipantIds.push(K))};c&&$(V?.draws?.[M],Y),a&&$(V?.events?.[D],Y),s&&$(V?.matchUps?.[C],Y)};if(w&&o[w]){let V=v?.[F];H(w,V);let Y=o[w]?.participant.participantType===lt,$=o[w]?.participant.individualParticipantIds||[];if(y){if(n){let k=K=>o[K].matchUps[y]={participantWon:S===F,matchUpId:y,matchUpType:Bt,sideNumber:F};k(w),$.forEach(k)}if(c&&!o[w].draws[M]){let k=N.find(q=>q.sideNumber===F)?.participant?.participantId,K=o[k]?.draws?.[M]?.entryStatus,z=q=>o[q].draws[M]={entryStatus:K,eventId:D,drawId:M};z(w),$.forEach(z)}}if(Y&&($.forEach(k=>o[k]&&H(k,V)),$.forEach((k,K)=>{let z=$[1-K],q=o[k];q&&W({participant:q,partnerParticipantId:z})}),a&&N)){let k=N.find(K=>K.sideNumber===F)?.participant?.participantId;if(k){let K=o[k]?.events[D];K?(o[w].events[D]={...K},$.forEach(z=>o[z].events[D]={...K})):console.log("Missing teamEntry",{eventId:D,teamParticipantId:k})}}if(U){let k=K=>{x?(o[K].counters[A].wins+=1,o[K].counters.wins+=1,m===vt&&(o[K].counters[A].walkoverWins+=1,o[K].counters.walkoverWins+=1),m===bt&&(o[K].counters[A].defaultWins+=1,o[K].counters.defaultWins+=1)):(o[K].counters[A].losses+=1,o[K].counters.losses+=1,m===vt&&(o[K].counters[A].walkovers+=1,o[K].counters.walkovers+=1),m===bt&&(o[K].counters[A].defaults+=1,o[K].counters.defaults+=1))};k(w),$.forEach(k)}}}}function _b(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,y=b=>{let v=[b];return a[b]?.participant.individualParticipantIds?.forEach(O=>v.push(O)),v.some(O=>!T?.length||T.includes(O))?v:[]},N={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},E=[],A={},U=[],C={},P={},D={},M=({eventType:b,scaleNames:v,participantId:O})=>a[O].participant?.rankings?.[b]?.find(w=>v.includes(w.scaleName))?.scaleValue;for(let b of o?.events||[]){if(e?.eventIds&&!e.eventIds.includes(b.eventId))continue;let{drawDefinitions:v=[],extensions:O=[],eventType:w,eventName:F,category:L,entries:x,eventId:B,gender:H}=b,{flightProfile:W}=Ht({event:b}),V=W?.flights??[],Y=ps({event:b}).publishState;Y&&(C[B]=Y);let $=Y?.status?.publishedSeeding;if(h||I||u){let K=r?Object.assign({},...rf(O??[])):{};P[B]={...K,eventName:F,eventType:w,category:L,eventId:B,gender:H};let z=[L?.categoryName,L?.ageCategoryCode].filter(Boolean);for(let q of x){let{participantId:et}=q;if(!et||!a[et])continue;let Q=M({eventType:w,scaleNames:z,participantId:et}),it,ot;if(I){let Et=a[et].participant;({seedAssignments:it,seedValue:ot}=Cb({publishedSeeding:$,usePublishState:i,withSeeding:I,participant:Et,event:b}))}let mt=Et=>{if(a[Et]?.events?.[B])return;let Me=a[Et];Rb({convertExtensions:r,seedAssignments:it,participant:Me,withSeeding:I,seedValue:ot,eventId:B,ranking:Q,entry:q})};mt(et),(a[et].participant.individualParticipantIds||[]).forEach(mt)}}let k=C?.[B]?.publishedSeeding;if(S||u||I){let K=q=>q?Object.assign({},...q.map(({participantId:et,seedValue:Q,seedNumber:it})=>({[et]:{seedValue:Q,seedNumber:it}}))):void 0,z=pt([...v.map(zc),...V.map(zc)]);for(let q of z){let et=v.find(Wt=>Wt.drawId===q),Q=V?.find(Wt=>Wt.drawId===q),it=et?.entries||Q?.drawEntries,{structures:ot=[],drawOrder:mt,drawName:Xt,drawType:Et}=et??{},Me=Q?.flightNumber,Ee=[L?.categoryName,L?.ageCategoryCode].filter(Boolean),Ce=(et?.structures||[]).sort((Wt,we)=>di(Wt,we)).map(({structureId:Wt,structures:we})=>[Wt,...(we||[]).map(({structureId:ir})=>ir)]).flat(1/0),zt,ve,Ft,Ue,Rt=0,_t=ot.filter(({stage:Wt,stageSequence:we})=>Wt===tt&&we===1||Wt===at).flatMap(Wt=>{let{seedAssignments:we,stageSequence:ir,stage:Oe}=Wt,{positionAssignments:Rr}=Ct({structure:Wt});return Oe===tt?(Rt=Rr?.length??0,Ft=Rr,Ue=we):ir===1&&(zt=Rr,ve=we),Rr}).map(({participantId:Wt})=>Wt).filter(Boolean),oe=K(Ue),qt=K(ve),pe=et?it.filter(({participantId:Wt})=>_t.includes(Wt)):it,he=!i||k?.published&&(k?.drawIds?.length===0||k?.drawIds?.includes(q));for(let Wt of pe){let{entryStatus:we,entryStage:ir,entryPosition:Oe,participantId:Rr}=Wt,Se=M({participantId:Rr,scaleNames:Ee,eventType:w}),Pe=Ir=>{if(a[Ir].draws?.[q])return;let si=I&&he,ze=si?{}:void 0,_n=si?oe?.[Rr]?.seedValue||oe?.[Rr]?.seedNumber:void 0,Ni=_n?oe?.[Rr]:void 0,Yi=si?qt?.[Rr]?.seedValue||qt?.[Rr]?.seedNumber:void 0,yn=Yi?qt?.[Rr]:void 0;ze&&_n&&(ze[tt]=Ni),ze&&Yi&&(ze[at]=yn);let Lc=_n||Yi;Lc&&(a[Ir].participant.seedings[w]||(a[Ir].participant.seedings[w]=[]),Ni&&a[Ir].participant.seedings[w].push({...Ni,scaleName:q}),yn&&a[Ir].participant.seedings[w].push({...yn,scaleName:q}),ze&&(a[Ir].events[B].seedAssignments||(a[Ir].events[B].seedAssignments={}),Object.keys(ze).forEach(qi=>a[Ir].events[B].seedAssignments[qi]=ze[qi]))),(S||u)&&(a[Ir].draws[q]=nt({seedAssignments:ze,entryPosition:Oe,entryStatus:we,entryStage:ir,seedValue:Lc,eventId:B,ranking:Se,drawId:q},!1,!1,!0))};[Br,gi].includes(we)||(Pe(Rr),(a[Rr].participant.individualParticipantIds||[])?.forEach(Pe))}let mr=(et?.structures??[]).reduce((Wt,we)=>(Wt.includes(we.stage)||Wt.push(we.stage),Wt),[]),xe=(et?.links??[]).length;D[q]={qualifyingPositionAssignments:zt,qualifyingSeedAssignments:ve,mainPositionAssignments:Ft,qualifyingSeedingMap:qt,mainSeedAssignments:Ue,orderedStructureIds:Ce,mainSeedingMap:oe,flightNumber:Me,linksCount:xe,drawOrder:mt,drawName:Xt,drawType:Et,drawSize:Rt,drawId:q,stages:mr}}}if(u||m||d||l||f||g||S){let K=!!m||c,z=ho({afterRecoveryTimes:!!m,policyDefinitions:n,tournamentRecord:o,inContext:!0,contextProfile:s,participantMap:a,nextMatchUps:K,event:b})?.matchUps??[];for(let q of z){let{finishingPositionRange:et,potentialParticipants:Q,tieMatchUps:it=[],sides:ot=[],winningSide:mt,matchUpType:Xt,matchUpId:Et,eventId:Me,drawId:Ee,collectionId:Ce,stageSequence:zt,finishingRound:ve,matchUpStatus:Ft,roundPosition:Ue,roundNumber:Rt,structureId:_t,schedule:oe,score:qt,stage:pe}=q;A[Et]=q;let he={finishingPositionRange:et,finishingRound:ve,stageSequence:zt,roundPosition:Ue,collectionId:Ce,roundNumber:Rt,structureId:_t,schedule:oe,eventId:Me,drawId:Ee,score:qt,stage:pe};hU({...he,...N,matchUpStatus:Ft,winningSide:mt,matchUpType:Xt,matchUpId:Et,sides:ot});for(let mr of it){let{winningSide:xe,sides:Wt=[],matchUpId:we,matchUpStatus:ir,matchUpType:Oe}=mr;hU({...he,...N,winningSide:xe,tieWinningSide:mt,matchUpTieId:Et,matchUpId:we,sides:Wt,matchUpSides:ot,matchUpStatus:ir,matchUpType:Oe})}Array.isArray(Q)&&(K||m||p)&&Q.flat().map(gt).filter(Boolean)?.forEach(xe=>{y(xe)?.forEach(we=>{a[we]&&(a[we].potentialMatchUps[Et]=nt({tournamentId:o?.tournamentId,matchUpId:Et,eventId:Me,drawId:Ee}))}),(m||p)&&Bh({potential:!0,participantMap:a,participantId:xe,matchUpStatus:Ft,roundPosition:Ue,structureId:_t,matchUpType:Xt,roundNumber:Rt,matchUpId:Et,schedule:oe,drawId:Ee,score:qt})})}U.push(...z)}}if(l||u||m){let b=Object.values(a);for(let v of b){let{wins:O,losses:w,[Kt]:{wins:F,losses:L},[wt]:{wins:x,losses:B}}=v.counters,H=(W,V,Y)=>{let $=V+Y,k=V,K=$&&k/$;v.statistics[W]={denominator:$,numerator:k,statValue:K,statCode:W}};if(l&&(H(Gm,O,w),H(`${Gm}.${Kt}`,F,L),H(`${Gm}.${wt}`,x,B)),u){let W=(V=[])=>Math.abs(V[0]-V[1]);for(let V of Object.keys(v.draws)){let{orderedStructureIds:Y=[],flightNumber:$}=D[V]||{};if(v.structureParticipation&&Y.length){let k,K=0,z=Y.map(q=>{let et=v.structureParticipation[q];if(!et)return;k||(k=et?.finishingPositionRange),W(k)>W(et?.finishingPositionRange)&&(k=et?.finishingPositionRange);let Q=et.stage!==at;return Q&&(K+=1),nt({...et,participationOrder:Q?K:void 0,flightNumber:$})}).filter(Boolean);v.draws[V]&&(v.draws[V].finishingPositionRange=k,v.draws[V].structureParticipation=z)}}}if(m){let W=Pt(m)?m.scheduledMinutesDifference:0,V=v.scheduleItems||[],Y=v.potentialMatchUps||{},$=V.reduce((K,z)=>{let{scheduledDate:q,scheduledTime:et}=z;return K[q]||(K[q]=[]),et&&K[q].push(z),K},{});Object.values($).forEach(K=>K.sort(YI));for(let K of V){let{typeChangeTimeAfterRecovery:z,timeAfterRecovery:q,scheduledDate:et,scheduledTime:Q}=K,it=$[et],ot=Vt(Q);for(let mt of it){if(mt.matchUpId===K.matchUpId||[vt,bt].includes(mt.matchUpStatus)&&!mt.checkScoreHasValue)continue;let Me=K.matchUpType!==mt.matchUpType&&z||q,Ee=K.drawId===mt.drawId,Ce=Y[K.matchUpId]&&Y[mt.matchUpId],zt=Vt(mt.scheduledTime),ve=Math.abs(zt-ot),Ft=zt>=ot;if((W&&!isNaN(W)?ve<=W:Ft&&Vt(mt.scheduledTime)<Vt(Me))&&!(Ce&&Ee)&&Ft){let Rt=[K.matchUpId,mt.matchUpId].sort(fu).join("|");v.scheduleConflicts[Rt]={priorScheduledMatchUpId:K.matchUpId,matchUpIdWithConflict:mt.matchUpId}}}}let k=v.participant.participantId;Object.keys(v.scheduleConflicts).length&&E.push(k),a[k].scheduleConflicts=v.scheduleConflicts}}}return{participantIdsWithConflicts:E,eventsPublishStatuses:C,derivedEventInfo:P,derivedDrawInfo:D,mappedMatchUps:A,participantMap:a,matchUps:U}}function gu({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=qs(l)&&e?.events?.filter(y=>l?.includes(y.eventId))||e?.events||[],I=o&&BF({drawEntryStatuses:o,tournamentEvents:g}),h=s&&HF({eventEntryStatuses:s,tournamentEvents:g}),S=i!==void 0&&[!0,!1].includes(i)&&g.reduce((y,N)=>y.concat(...(N.drawDefinitions||[]).map(E=>ih({drawDefinition:E}).allPositionedParticipantIds).filter(Boolean)),[]),T=y=>n?.reduce((N,E)=>{let{accessor:A,value:U}=E,{values:C}=cs({element:y,accessor:A});return N&&C?.includes(U)},!0);if(r=r?.filter(y=>{let N=Vn({element:y,itemType:sc})?.timeItem?.itemValue,{participantRoleResponsibilities:E,participantType:A,participantRole:U,participantId:C,person:P}=y,D=Array.isArray(f)&&f?.length&&P?.sex&&f.includes(P.sex);return d?f&&D||i&&S.includes(C)||i===!1&&!S.includes(C)||I?.includes(C)||h?.includes(C)||p?.includes(C)||m&&N===m||u&&A&&qs(u)&&u.includes(A)||a&&U&&qs(a)&&a.includes(U)||c&&qs(E)&&qs(c)&&c.find(M=>E?.includes(M))||n?.length&&qs(n)&&T(y):(!f||D)&&(i===void 0||i&&S.includes(C)||i===!1&&!S.includes(C))&&(!I||I.includes(C))&&(!h||h.includes(C))&&(!p||p.includes(C))&&(!m||N===m)&&(!u||A&&qs(u)&&u.includes(A))&&(!a||U&&qs(a)&&a.includes(U))&&(!c||qs(E)&&qs(c)&&c.find(M=>E?.includes(M)))&&(!n?.length||qs(n)&&T(y))}),g.length&&l){let y=g.filter(N=>l.includes(N.eventId)).map(N=>{let E=(N.entries||[]).map(U=>U.participantId);if(ie(go)(N.eventType))return E;let A=(e?.participants??[]).filter(U=>E.includes(U.participantId)).map(U=>U.individualParticipantIds).flat(1);return E.concat(...A)}).flat(1);r=r?.filter(N=>y.includes(N.participantId))}return r}function qs(t){return t&&Array.isArray(t)&&t.length}function BF({drawEntryStatuses:t,tournamentEvents:e}){let r=({entryStatus:n})=>Array.isArray(t)?t.includes(n):!0;return pt(e.reduce((n,o)=>{let{flightProfile:i}=Ht({event:o}),s=i?.flights?.map(({drawEntries:c})=>Array.isArray(c)?c.filter(r).map(gt):[]).flat()||[],a=o.drawDefinitions?.map(({entries:c})=>c?c.filter(r).map(gt):[])||[];return n.concat(...s,...a)},[]))}function HF({eventEntryStatuses:t,tournamentEvents:e}){return pt(e.reduce((r,n)=>{let o=(n.entries||[]).filter(({entryStatus:i})=>Array.isArray(t)?t.includes(i):!0).map(gt);return r.concat(...o)},[]))}function Yt(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:y,withDraws:N,withISO2:E,withIOC:A}=t;if(!c)return{error:j};(h||o)&&Yr({tournamentRecord:c});let{participantMap:U}=gh({convertExtensions:i,tournamentRecord:c,withSignInStatus:p,withScaleValues:d,internalUse:S,withISO2:E,withIOC:A}),C=_b({withMatchUps:h??o,withEvents:y??o,withDraws:N??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:P,eventsPublishStatuses:D,derivedEventInfo:M,derivedDrawInfo:b,mappedMatchUps:v}=C,O=C.matchUps;U=C.participantMap;let w=u??n,F=({potentialMatchUps:Y,scheduleConflicts:$,scheduleItems:k,participant:K,statistics:z,opponents:q,matchUps:et,events:Q,draws:it})=>{let ot=Object.values(it),mt=Object.values(q);return I&&ot?.forEach(Xt=>{Xt.opponents=mt.filter(Et=>Et.drawId===Xt.drawId)}),nt({...K,scheduleConflicts:u?Object.values($):void 0,draws:N||o?ot:void 0,events:y||o?Object.values(Q):void 0,matchUps:h||o?Object.values(et):void 0,opponents:I?mt:void 0,potentialMatchUps:w?Object.values(Y):void 0,statistics:g?Object.values(z):void 0,scheduleItems:a?k:void 0},!1,!1,!0)},L=new Map;for(let Y of Object.keys(U))L.set(Y,F(U[Y]));let x=[...L.values()],H=s?.[ws]?.participant,W=gu({participants:x,participantFilters:r,tournamentRecord:c});if(e){let Y=Pt(e)?e:void 0;for(let $ of W)for(let k of $.individualParticipantIds??[]){$.individualParticipants||($.individualParticipants=[]);let K=L.get(k);$.individualParticipants.push(Y?_i({template:Y,source:K}):K)}}let V=H?W.map(Y=>_i({source:Y,template:H})):W;return{participantIdsWithConflicts:P,eventsPublishStatuses:D,derivedEventInfo:M,derivedDrawInfo:b,mappedMatchUps:v,participantMap:U,participants:V,...R,matchUps:O}}function fc({participantId:t,drawDefinition:e,entryStatus:r,entryStage:n}){if(!e)return{error:X};let o=e.entries?.find(i=>i.participantId===t&&(!r||r===i.entryStatus)&&(!n||n===i.entryStage));return t&&o}function ms(t){let{provisionalPositioning:e,drawDefinition:r,stageSequence:n,structureId:o,stage:i}=t;if(!r)return{error:X};let{entryProfile:s}=cu({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===ke){let S=f.structures?.length??0,T=l.source.finishingPositions?.length??0;h=S*T}else h=At({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 yp({stage:t,drawDefinition:e}){let{entryProfile:r}=cu({drawDefinition:e});return r?.[t]?.drawSize||0}function xb(t){let{provisionalPositioning:e,drawDefinition:r,stageSequence:n,stage:o}=t,i=yp({stage:o,drawDefinition:r}),{qualifiersCount:s}=ms({provisionalPositioning:e,drawDefinition:r,stageSequence:n,stage:o});return i&&i-s}function SU({stage:t,drawDefinition:e}){return!!(t===We||_f({stage:t,drawDefinition:e})&&yp({stage:t,drawDefinition:e}))}function TU({entryStatus:t=Vr,drawDefinition:e,stageSequence:r,stage:n}){if(t===kr)return GR({stage:n,drawDefinition:e})?{positionsAvailable:1/0,...R}:{error:WA};let o=xb({drawDefinition:e,stageSequence:r,stage:n}),i=kR({drawDefinition:e,stage:n}),s=hh({entryStatus:uu,drawDefinition:e,stage:n}),a=hh({entryStatus:Vr,drawDefinition:e,stage:n}),c=s+a,u=c>=o,p=o-c;return n!==We&&u?{error:DI}:t===uu?s<i?{...R}:{error:DI}:{positionsAvailable:p,...R}}function Hh(t){let{suppressDuplicateEntries:e=!0,entryStatus:r=Vr,entryStageSequence:n,entryStage:o=tt,ignoreStageSpace:i,drawDefinition:s,entryPosition:a,participant:c,roundTarget:u,extensions:p,extension:m,drawType:d,event:l}=t,f="addDrawEntry";if(!s)return{error:X};if(!o)return{error:SI};if(d!==Xr&&!SU({stage:o,drawDefinition:s}))return _({result:{error:Ri},stack:f});let g=TU({stageSequence:n,stage:o,drawDefinition:s,entryStatus:r});if(!i&&!g.success&&(!d||d!==Xr))return{error:g.error};if(m&&!Mn({extension:m}))return _({result:{error:G},info:"Invalid extension",context:{extension:m},stack:f});let I=t.participantId||c?.participantId;if(!I)return _({result:{error:ee},stack:f});let h=r===es&&fc({participantId:I,drawDefinition:s,entryStatus:r}),S=o===We&&fc({participantId:I,drawDefinition:s,entryStage:o}),T=fc({participantId:I,drawDefinition:s}),y=r!==es&&o!==We&&T;if(y)return e?(St({payload:{drawId:s.drawId,eventId:l?.eventId,error:cm,participantId:I},topic:ah}),{...R}):_({result:{error:cm},context:{participantId:I},stack:f});if(h||S)return _({context:{invalidEntry:y,invalidLuckyLoser:h,invalidVoluntaryConsolation:S},result:{error:Yu},stack:f});let N=nt({entryStageSequence:n,participantId:I,entryPosition:a,entryStatus:r,entryStage:o,extensions:p});return m&&yt({element:N,extension:m}),u&&yt({extension:{name:"roundEntry",value:u},element:N}),s.entries||(s.entries=[]),s.entries.push(N),Ot({drawDefinition:s}),{...R}}function wb(t){let e="addDrawEntries",{suppressDuplicateEntries:r=!0,entryStatus:n=Vr,stage:o=tt,autoEntryPositions:i=!0,ignoreStageSpace:s,participantIds:a,drawDefinition:c,stageSequence:u,roundTarget:p,extension:m,event:d}=t;if(!o)return{error:SI};if(!c)return{error:X};if(!Array.isArray(a))return{error:Kr};if(!SU({stage:o,drawDefinition:c}))return{error:Ri};if(m&&!Mn({extension:m}))return _({result:{error:G},info:"Invalid extension",context:{extension:m},stack:e});let l=TU({drawDefinition:c,stageSequence:u,entryStatus:n,stage:o});if(!s&&!l.success)return{error:l.error};let f=l.positionsAvailable??0;if(!s&&o!==We&&f<a.length)return{error:vl};let g=[],I=c.drawId,h=d?.eventId,S=a.reduce((T,y)=>{let N=n===es&&fc({participantId:y,drawDefinition:c,entryStatus:n}),E=o===We&&fc({entryStage:o,drawDefinition:c,participantId:y}),A=fc({participantId:y,drawDefinition:c});return n!==es&&o!==We&&A&&(g.push(y),r&&St({payload:{error:cm,participantId:y,eventId:h,drawId:I},topic:ah})),N||E?T.concat(y):T},[]);return g.length&&r?_({context:{eventId:h,drawId:I,duplicateEntries:g},result:{error:cm},stack:e}):(a.filter(T=>T&&!S.includes(T)).forEach(T=>{let y={entryStageSequence:u,entryStage:o,participantId:T,entryStatus:n};m&&yt({element:y,extension:m}),p&&yt({extension:{name:ln,value:p},element:y}),c.entries||(c.entries=[]),c.entries.push(y)}),i&&(c.entries=Wn({entries:c.entries})),Ot({drawDefinition:c}),S?.length||g?.length?{info:"some participantIds could not be added",participantIdsNotAdded:S,duplicateEntries:g,...R}:{...R})}function qf({suppressDuplicateEntries:t=!0,autoEntryPositions:e=!0,entryStageSequence:r,ignoreStageSpace:n,drawDefinition:o,participantIds:i,entryStatus:s,roundTarget:a,entryStage:c,extension:u,drawId:p,event:m}){if(!i?.length)return{error:Eo};if(!m)return{error:lr};if(!p)return{error:$r};let d=(m.entries||[]).map(gt);if(i.filter(I=>!d.includes(I)).length)return{error:EA};if(o){let I=wb({stageSequence:r,suppressDuplicateEntries:t,autoEntryPositions:e,stage:c,ignoreStageSpace:n,drawDefinition:o,participantIds:i,entryStatus:s,roundTarget:a,extension:u});if(I.error)return I}let{flightProfile:f}=Ht({event:m}),g=f?.flights.find(I=>I.drawId===p);return g?.drawEntries&&(i.forEach(I=>{let h=s===es&&yU({participantId:I,entryStatus:s,flight:g}),S=c===We&&yU({participantId:I,entryStage:c,flight:g});!(s!==es&&c!==We&&yU({flight:g,participantId:I}))&&!h&&!S&&g.drawEntries.push({participantId:I,entryStatus:s,entryStage:c})}),e&&(g.drawEntries=Wn({entries:g.drawEntries}))),{...R}}function yU({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 gc({autoEntryPositions:t=!0,participantIds:e=[],entryStatuses:r,stage:n,event:o}){let i="removeEventEntries";if(!o?.eventId)return{error:Dt};if(!Array.isArray(e)||e.some(m=>!Re(m)))return _({result:{error:Zr},stack:i});let s=(o.drawDefinitions??[]).flatMap(m=>Ei({drawDefinition:m}).assignedParticipantIds??[]),a=(r?.length&&o.entries?.filter(m=>m.entryStatus&&r.includes(m.entryStatus))||[]).map(gt).filter(m=>!s.includes(m)),c=(n&&o.entries?.filter(m=>m.entryStage&&m.entryStage===n)||[]).map(gt).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=jt(a,c):a.length?e=a:c.length&&(e=c),e?.length&&s.some(m=>e.includes(m)))return _({result:{error:Rs},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=Wn({entries:o.entries}));let{flightProfile:p}=Ht({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 AU={[Qe]:{policyName:"matchUpActionsDefault",enabledStructures:[{stages:[],stageSequences:[],enabledActions:[],disabledActions:[]}],participants:{enforceCategory:!0,enforceGender:!0},processCodes:{substitution:["RANKING.IGNORE","RATING.IGNORE"]},substituteAfterCompleted:!1,substituteWithoutScore:!1}},ds=AU;function to(t){let{suppressDuplicateEntries:e=!0,entryStatus:r=Vr,autoEntryPositions:n=!0,enforceGender:o=!0,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(!Array.isArray(t.participantIds))return _({result:{error:Kr},stack:I});let h=pt(t.participantIds??[]);if(!g)return{error:Dt};if(!h?.length)return _({result:{error:Eo},stack:I});if(!g?.eventId)return{error:lr};let S=ht({tournamentRecord:c,event:g}).appliedPolicies??{},T=s?.[Qe]??S?.[Qe]??ds[Qe],y=(o??T?.participants?.enforceGender)!==!1,N=[],E=[];if(d&&(!Array.isArray(d)||!d.every(O=>Mn({extension:O})))||l&&!Mn({extension:l}))return _({context:nt({extension:l,extensions:d}),result:{error:G},info:"Invalid extension(s)",stack:I});let A=!!c,U=[],C,P=c?.participants?.filter(O=>{if(!h.includes(O.participantId))return!1;let w=ie(Kt)(g.eventType)&&O.participantType===Tt&&!Ys(r),F=g.eventType===wt&&O.participantType===lt;return w&&(!g.gender||!y||[Ur,In].includes(g.gender)||g.gender===O.person?.sex)||F&&!Ys(r)||g.eventType===wt&&O.participantType===Tt&&Ys(r)?!0:w&&g.gender&&y&&![Ur,In].includes(g.gender)&&g.gender!==O.person?.sex?(U.push({participantId:O.participantId,sex:O.person?.sex}),!1):g.eventType===xt&&(O.participantType===xt||Ys(r)&&O.participantType===Tt)}).map(O=>O.participantId)??[],D=h.filter(O=>!A||P.includes(O));g.entries||(g.entries=[]);let M=g.entries.map(O=>O.participantId||O.participant?.participantId);if(D.forEach(O=>{if(!M.includes(O)){let w=nt({participantId:O,entryStatus:r,entryStage:a,extensions:d});l&&yt({element:w,extension:l}),m&&yt({extension:{name:ln,value:m},element:w}),i&&(w.entryStageSequence=i),N.push(w.participantId),g.entries?.push(w)}}),f&&!Ys(a)){let O=qf({participantIds:D,suppressDuplicateEntries:e,autoEntryPositions:n,entryStageSequence:i,ignoreStageSpace:u,drawDefinition:p,entryStatus:r,roundTarget:m,entryStage:a,extension:l,drawId:f,event:g});O.error&&(C=O.error)}if(g.eventType&&[yi,jr].includes(g.eventType)){let O=(g.entries||[]).map(B=>B.participantId),w=(g.entries||[]).filter(B=>Ys(B.entryStatus)).map(B=>B.participantId),L=(c?.participants??[]).filter(B=>O.includes(B.participantId)&&B.participantType&&[lt,xt].includes(B.participantType)).map(B=>B.individualParticipantIds).flat(1/0),x=w.filter(B=>L.includes(B));x.length&&(E.push(...x),gc({participantIds:x,autoEntryPositions:!1,event:g}))}if(D.length!==h.length)return _({context:{mismatchedGender:U,gender:g.gender},result:{error:Kr},stack:I});n&&(g.entries=Wn({entries:g.entries||[]}));let v=N.length-E.length;return _({result:{...R,addedEntriesCount:v},stack:I,info:C})}var EU="ADMINISTRATION",WF="CAPTAIN",jF="COACH",be="COMPETITOR",UU="MEDIA",PU="MEDICAL",$f="OFFICIAL",DU="OTHER",NU="SECURITY",td={ADMINISTRATION:EU,CAPTAIN:WF,COACH:jF,COMPETITOR:be,MEDIA:UU,MEDICAL:PU,OFFICIAL:$f,OTHER:DU,SECURITY:NU};function Kf({addIndividualParticipantsToEvents:t,individualParticipantIds:e,groupingParticipantId:r,tournamentRecord:n,suppressErrors:o}){let i="removeIndividualParticipantIds";if(!n)return _({result:{error:j},stack:i});if(!r||!e)return _({result:{error:rt},stack:i});let a=(n.participants??[]).find(m=>m.participantId===r);if(!a)return _({result:{error:re},stack:i});if(![xt,Er].includes(a.participantType))return _({result:{participantType:a.participantType,error:an},stack:i});let c=Lb({individualParticipantIds:e,groupingParticipant:a,tournamentRecord:n,suppressErrors:o}),{removed:u,error:p}=c;if(p)return _({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));to({participantIds:l,entryStatus:Br,tournamentRecord:n,event:m})}}return u&&St({topic:Xe,payload:{tournamentId:n.tournamentId,participants:[a]}}),{...R,...c}}function Lb({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}=Yt({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||Ie({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}=dt({element:S,name:Do}),y=T?.value[e.participantId];T&&y&&(T.value[e.participantId]=y.filter(E=>E.participantId!==l),yt({element:S,extension:T}),Sa({drawDefinition:S}));let N=or({drawDefinition:S,inContext:!1}).matchUps??[];for(let E of N){let A=E.sides??[];for(let U of A){let C=U.lineUp??[];C.find(D=>D.participantId===l)&&(U.lineUp=C.filter(D=>D.participantId!==l),It({tournamentId:r?.tournamentId,drawDefinition:S,matchUp:E}))}}}}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:ju}||d}function Ap({participantRole:t=be,individualParticipantIds:e=[],groupingTypes:r=[rn,Er],tournamentRecord:n}){if(!n)return{error:j};let o=n.participants??[],{participants:i,mappedMatchUps:s}=Yt({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}=Lb({groupingParticipant:c,individualParticipantIds:e,tournamentRecord:n,mappedMatchUps:s,participants:i});u&&a++}),a?R:{error:kA}}function ki(t){if(!t?.tournamentRecord)return{error:j};if(!t?.participantIds?.length)return{error:Eo};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===Ve).map(l=>l?.drawDefinitions?.map(({drawId:f})=>f)).flat(1/0),s=Yt({participantFilters:{participantIds:n},tournamentRecord:r,withDraws:!0}).participants??[],a=()=>{let f=(le({matchUpFilters:{drawIds:i,matchUpTypes:[wt]},tournamentRecord:r}).matchUps??[]).map(({sides:g})=>g?.map(({participantId:I})=>I)).flat().filter(Boolean);return jt(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:Rs};let p={},m={};for(let l of r.events||[]){let f=gc({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===lt&&l.individualParticipantIds.some(g=>n.includes(g));if(!f&&l.participantType===Ve&&l.individualParticipantIds.some(g=>n.includes(g))&&(l.individualParticipantIds=l.individualParticipantIds.filter(g=>!n.includes(g))),f&&e&&[lt,xt].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(Ap({individualParticipantIds:n,tournamentRecord:r}),e)for(let l of r.events||[]){let g=p[l.eventId].map(I=>m[I]||[]).flat();to({participantIds:g,entryStatus:Br,tournamentRecord:r,event:l})}return d&&St({payload:{participantIds:n,tournamentId:r.tournamentId},topic:If}),d?{...R,participantsRemovedCount:d}:{error:ju}}function Wh({selected:t=!0,drawDefinition:e,entryStatuses:r,drawId:n,event:o,stage:i}){let s=o.entries??[];if(n){let{flightProfile:c}=Ht({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&&wr.includes(c.entryStatus)));return{entries:s,stageEntries:a}}function MU({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 _({result:{error:ee},stack:a});if(!s)return{error:Dt};if(!s.eventType||![yi,jr].includes(s.eventType))return _({result:{error:_o},stack:a});let c=e.participants??[],u=c.find(S=>S.participantId===n);if(!u)return _({result:{error:re},stack:a});if(!u.participantType||![lt,rn].includes(u.participantType)||u.participantType===rn&&s.eventType!==jr||u.participantType===lt&&s.eventType!==yi)return{error:an};let m=(s.entries??[]).find(S=>S.participantId===n);if(!m)return{error:PI};let{stageEntries:d}=Wh({selected:!1,drawDefinition:r,drawId:o,event:s,stage:i}),l=d.map(gt),f=c.filter(({participantId:S})=>l.includes(S)).map(({individualParticipantIds:S})=>S).flat().filter(Boolean),g=u.individualParticipantIds?.filter(S=>io(S,f).length===1),I=gc({participantIds:[n],event:s});if(I.error||g?.length&&(I=to({participantIds:g,entryStatus:Br,entryStage:m.entryStage,tournamentRecord:e,drawDefinition:r,drawId:o,event:s}),I.error))return I;let h;return t&&ki({participantIds:[n],tournamentRecord:e}).success&&(h=!0),{...R,participantRemoved:h}}function zf({removeGroupParticipant:t,tournamentRecord:e,drawDefinition:r,participantId:n,drawId:o,event:i}){return MU({removeGroupParticipant:t,tournamentRecord:e,drawDefinition:r,participantId:n,drawId:o,event:i})}function CU(t){if(!t.tournamentRecord)return{error:j};let{participantIds:e,...r}=t,n=0,o=[];for(let i of e){let s=MU({participantId:i,...r});s.success&&(n+=1),s.error&&o.push(s.error)}return n?{destroyedCount:n,...R}:{error:o}}function Iu(t){let{tournamentRecord:e,replaceWithBye:r,drawDefinition:n,destroyPair:o,entryStatus:i,matchUpsMap:s,drawId:a}=t,c="removeDrawPositionAssignment",u=lc(t);if(u.error)return _({result:u,stack:c});let{participantId:p}=u,{drawPosition:m,event:d,structureId:l}=t,f=ht({tournamentRecord:e,drawDefinition:n,event:d}).appliedPolicies??{};if([kr,Jn].includes(i)&&p){let{tournamentRecord:h}=t,{participant:S}=fo({tournamentRecord:h,participantId:p}),{participantType:T,individualParticipantIds:y}=S??{};if(o&&T===lt){let N=zf({tournamentRecord:h,drawDefinition:n,participantId:p,event:d});if(N.error)return _({result:N,stack:c});y&&Jm({participantIds:y,tournamentRecord:h,drawDefinition:n,entryStatus:i,drawId:a,event:d})}else Jm({participantIds:[p],tournamentRecord:h,drawDefinition:n,entryStatus:i,drawId:a,event:d})}if(r){let h=Cr({tournamentRecord:e,drawDefinition:n,drawPosition:m,structureId:l,matchUpsMap:s,event:d});if(h.error)return _({result:h,stack:c})}let{structure:g}=st({drawDefinition:n,structureId:l});return wm({structure:g,drawPositions:[m]}),ru({appliedPolicies:f,drawDefinition:n,positionAction:{name:"removeDrawPositionAssignment",replaceWithBye:r,drawPosition:m,entryStatus:i,structureId:l}}),u}function RU(t){return Object.assign(t,{entryStatus:Jn}),Iu(t)}function jh(t){return Re(t)?t.split(" ").map(e=>e.split("").map((r,n)=>n?r.toLowerCase():r.toUpperCase()).join("")).join(" "):t}function $e(t){return Re(t)?jh(t.replace(/_/g," ")):""}var ls=({finishingPosition:t=wi,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:y})=>y).filter(Boolean);return I?S.structures=I:(S.matchUps=m,S.positionAssignments=pt(T).sort((y,N)=>y-N).map(y=>({drawPosition:y}))),S},on=ls;function Qf({structureName:t=$e(We),structureAbbreviation:e,drawDefinition:r,matchUpType:n,structureId:o}){if(!r)return{error:X};let i=on({stage:We,structureAbbreviation:e,structureName:t,matchUps:[],structureId:o,matchUpType:n});return r.structures||(r.structures=[]),r.structures.push(i),Ot({drawDefinition:r,structureIds:[i.structureId]}),{...R}}function Xf({drawPositions:t}){if(!t?.length)return{error:Ya};let e=o=>t.filter(i=>i!==o).map(i=>[o,i]),r=[].concat(...(t??[]).map(e)),n=pt(r.map(Jf)).map(o=>o.split("|").map(i=>+i));return{groupMatchUps:r,uniqueMatchUpGroupings:n}}function Jf(t=[]){return!Array.isArray(t)||!t.length?"":[...t].sort(se).join("|")}function bU({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 Jf(l)}))}function YF({rounds:t,hash:e}){return t?.length?t?.reduce((r,n,o)=>n.includes(e)?o+1:r,void 0):{error:rt}}var Fb={getRoundRobinGroupMatchUps:Xf,determineRoundNumber:YF,drawPositionsHash:Jf,groupRounds:bU};function Ma(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??$e(tt),{groupCount:h,groupSize:S}=qF({structureOptions:o,appliedPolicies:i,drawSize:d}),T=Fs,y,N=Z(1,h+1).map(A=>{let U=$F({groupSize:S,structureOrder:A,matchUpType:c,drawSize:d,idPrefix:l,isMock:f});y=Array.isArray(U)?Math.max(...U.map(({roundNumber:P})=>P??0)):0;let C=m?.[A-1]??`${e} ${A}`;return ls({structureId:g?.pop(),structureType:cp,finishingPosition:T,structureOrder:A,structureName:C,matchUps:U})}),E=ls({structureId:p??g?.pop(),structureType:ke,finishingPosition:T,seedingProfile:s,structureName:I,stageSequence:n,structures:N,stage:a});return u&&yt({extension:{name:ln,value:u},element:E}),{structures:[E],maxRoundNumber:y,groupCount:h,links:[],groupSize:S,...R}}function qF({appliedPolicies:t,structureOptions:e,drawSize:r}){let n=e?.groupSize,o=e?.groupSizeLimit||8,{validGroupSizes:i}=Ep({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 Ep({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 $F({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=Xf({drawPositions:c}).uniqueMatchUpGroupings??[],p=bU({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=Jf(f),I=d(g),h=[1,n],S=KF({structureOrder:t,drawPositions:f,roundNumber:I,idPrefix:o,uuids:s}),T={matchUpStatus:I?Qt:Nt,matchUpType:e,finishingPositionRange:{winner:h,loser:h},drawPositions:f,roundNumber:I,matchUpId:S};return i&&(T.isMock=!0),T}}function KF({structureOrder:t,drawPositions:e,roundNumber:r,idPrefix:n,uuids:o}){return n?`${n}-${t}-${r}-DP-${e.join("-")}`:o?.pop()||Mt()}function Zf(t){let{roundRobinGroupsCount:e,participantsCount:r,cluster:n}=t;if(!ft(r))return{seedBlocks:void 0,..._({result:{error:G},context:{participantsCount:r},stack:"getSeedBlocks"})};let o=Ki(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=Te(i,a),f=l.length;l.forEach((g,I)=>{let h,S=I<f/2,T=I%2===0,y=g[0],N=g[g.length-1];n&&f>4?f===8?h=S?N:y:h=T?y:N:h=S?y:N,Fe(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 tg({roundRobinGroupsCount:t,drawSize:e}){let r="getSeedGroups";if(!ft(e))return{seedGroups:void 0,..._({result:{error:G},context:{drawSize:e},stack:r})};if(t){if(!ft(t))return{seedGroups:void 0,..._({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}=Zf({participantsCount:e,roundRobinGroupsCount:t}),o=0;return{seedGroups:(n||[]).map(s=>(s||[]).map(()=>(o+=1,o)))}}}function Yh({roundRobinGroupsCount:t,participantsCount:e}){if(t){let{validGroupSizes:o}=Ep({drawSize:e});if(!o?.map(a=>Math.ceil(e/a))?.includes(t))return _({context:{roundRobinGroupsCount:t},result:{error:G}})}let{seedGroups:r}=tg({drawSize:e,roundRobinGroupsCount:t}),n=r?.map(o=>Math.min(...o))||[];return{...R,seedingThresholds:n}}function Ic(t){if(!t)return 1/0;if(ft(t))return ct(t);let e=t.split("-")[0];return ft(e)?ct(e):1/0}function zF({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(se),e.reverse(),e}function Gb({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 kb({positioning:t,size:e}){let r=zF({size:e}),n=[],o=[],i=d=>d[0],s=d=>d[d.length-1],a=(d,l)=>(t&&[Xc,pi].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=Te(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=Te(m,d).map(p).filter(Boolean);f.length&&n.push(f)}return{divisions:r,divisionGroupings:n}}function fs({provisionalPositioning:t,returnAllProxies:e,appliedPolicies:r,seedingProfile:n,drawDefinition:o,allPositions:i,structure:s}){let a=[];if(!s)return{error:Oo};let{matchUps:c,roundMatchUps:u}=At({matchUpFilters:{roundNumbers:[1]},provisionalPositioning:t,structure:s}),{seedAssignments:p}=Hr({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(L=>parseInt(L)).sort((L,x)=>L-x).map(L=>{let x=u[L].map(H=>H.drawPositions).flat(1/0).filter(Boolean),B=x.filter(H=>!f.includes(H));return f=f.concat(...x),B}).filter(L=>L.length).reverse(),h=I.pop()??[],S=h&&Math.min(...h)-1||0;n=n??r?.seeding?.seedingProfile;let T=h?.length||0,y=I.filter(L=>L.filter(x=>x<=l).length),{stage:N,structureType:E,roundLimit:A}=s,U=E===ke,C=!U&&I?.length,P=!U&&N===at&&A,D=y.flat(1/0),M=C?D?.length:0,b=i?d:l,v=Km({drawDefinition:o,structure:s,matchUps:c}),O=v?0:!C&&b||b&&D.length<b&&b-D.length||0;if(P){let L=s?.matchUps?s.matchUps.filter(({roundNumber:B})=>B===s.roundLimit).length:0,x=h.length/L;if(!C){let B=Pp(n),H=Te(h,x),W=1,V=Z(0,H[0].length).map(()=>{let Y=Z(W,W+H.length);return W+=H.length,Y});({validSeedBlocks:a}=Vb({drawPositionBlocks:H,nonRandom:n?.nonRandom,positioning:B,seedGroups:V}))}}else U?{validSeedBlocks:a}=QF({nonRandom:n?.nonRandom,seedingProfile:n,structure:s}):C?a=y.map(L=>({seedNumbers:L,drawPositions:L})):v&&Te(h,2).map((x,B)=>({drawPositions:[x[0]],seedNumbers:[B+1]})).forEach(x=>a.push(x));if(!U&&!v&&!P){let{blocks:L}=XF({drawPositionOffset:S,seedNumberOffset:M,seedCountGoal:O,seedingProfile:n,baseDrawSize:T});L.forEach(x=>a.push(x))}let F=a.flatMap(L=>L.drawPositions).reduce((L,x)=>h?.includes(x)&&L,!0);return!v&&!C&&!U&&!F?{error:SA,validSeedBlocks:[],isContainer:U,isFeedIn:C}:{isLuckyStructure:v,validSeedBlocks:a,isContainer:U,isFeedIn:C}}function QF({seedingProfile:t,structure:e,nonRandom:r}){let n=e.structures||[],o=n.length,i=Ct({structure:e})?.positionAssignments,s=Pp(t),a=i?.length??0,{seedGroups:c}=tg({roundRobinGroupsCount:o,drawSize:a}),u=n.map(p=>Ct({structure:p}).positionAssignments?.map(m=>m.drawPosition));return Vb({drawPositionBlocks:u,positioning:s,seedGroups:c,nonRandom:r})}function Vb({drawPositionBlocks:t,positioning:e,seedGroups:r,nonRandom:n}){let o=[],{divisionGroupings:i}=kb({size:r.length,positioning:e}),s=[];return r.forEach((a,c)=>{let u=Gb({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!==pi?f=n?f:pr(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 XF(t){let{drawPositionOffset:e=0,roundRobinGroupsCount:r,seedNumberOffset:n=0,seedingProfile:o,seedCountGoal:i,baseDrawSize:s}=t,a=1,c=[],{seedBlocks:u}=Zf({cluster:Pp(o)===Xc,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 Up({appliedPolicies:t,drawDefinition:e,seedBlockInfo:r,drawPosition:n,structureId:o,seedNumber:i}){let{structure:s}=st({drawDefinition:e,structureId:o});t||(t=ht({drawDefinition:e}).appliedPolicies);let a=r?.validSeedBlocks;return!a&&s&&(a=fs({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 qh(t){let{provisionalPositioning:e,drawDefinition:r,seedingProfile:n,seedBlockInfo:o,structureId:i,randomize:s}=t,{structure:a}=st({drawDefinition:r,structureId:i}),{seedAssignments:c}=Hr({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}=ht({drawDefinition:r}),g=(o?.validSeedBlocks||a&&fs({returnAllProxies:t.returnAllProxies,provisionalPositioning:e,appliedPolicies:d,drawDefinition:r,seedingProfile:n,structure:a})?.validSeedBlocks||[]).filter(x=>x.drawPositions.filter(H=>!m?.includes(H)).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)),y=c?.filter(x=>T?.includes(x.participantId)),N=c?.filter(x=>!x.participantId),A=(y?.length&&y.length>0?y.length:N?.length??0)&&g?.drawPositions.filter(x=>!m?.includes(x))||[],U=s?pr(A):A,C=[],P=U.map(()=>{let B=L(y,C)?.participantId;return B&&C.push(B),B}).filter(Boolean),D=c?.filter(x=>S?.includes(x.participantId)).map(x=>x.seedNumber),b=(g?.seedNumbers||[]).filter(x=>!D?.includes(x)),v=c?.filter(x=>b.includes(x.seedNumber)).map(x=>x.participantId),O=d?.seeding?.duplicateSeedNumbers;return{nextSeedBlock:g,unplacedSeedParticipantIds:(O!==void 0?O:!0)?P:v,unplacedSeedNumbers:b,unfilledPositions:U,unplacedSeedAssignments:y};function L(x,B){let H=x.filter($=>!B.includes($.participantId)),W=Math.min(...H.map($=>Ic($.seedValue))),V=H.filter($=>Ic($.seedValue)===W);return pr(V).pop()}}function Pp(t){if(typeof t=="string")return t;if(typeof t=="object")return t.positioning}function $s({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=Hr({provisionalPositioning:t,drawDefinition:r,structure:d}).seedAssignments,g=f.map(E=>E.seedNumber),I=fc({drawDefinition:r,participantId:o});if(o&&!I)return _({result:{error:Zr},context:{participantId:o},stack:m});let h=p?Ht({event:p}).flightProfile?.flights?.length:0,S=h&&h>1,y=l?.find(E=>E.participantId===o)?.drawPosition;if(y&&!Up({drawPosition:y,drawDefinition:r,seedBlockInfo:i,structureId:s,seedNumber:a}))return _({result:{error:Sl},context:{assignedDrawPosition:y},info:"invalid seed position",stack:m});g.includes(a)||f.push({seedNumber:a,seedValue:c});let N;return f.forEach(E=>{E.participantId===o&&E.seedNumber!==a&&(E.participantId=void 0),E.seedNumber===a&&(E.participantId=o,!n?.groupSeedingThreshold&&!S&&(E.seedValue=c??a),N=!0)}),N?(ph({tournamentId:e?.tournamentId,drawDefinition:r,structure:d,eventId:u}),{...R}):_({result:{error:hA},stack:m})}function ed({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}=dt({element:o,name:Do}),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)}It({tournamentId:n?.tournamentId,context:"updateSidLineUp",eventId:s?.eventId,drawDefinition:o,matchUp:i})}function $h(t){let{sourceMatchUp:e}=t,{targetMatchUp:r,structure:n,matchUpsMap:o,drawPosition:i}=t,s=r.roundNumber>1&&r.roundNumber-1,a=ti({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=[ge,Ne].includes(d);return{pairedPreviousMatchUp:m,pairedPreviousMatchUpIsDoubleExit:l}}function Bb({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(se).filter(Boolean),positionAdded:r,positionAssigned:n}}function Kh({structureId:t,matchUpsMap:e,matchUp:r}){let n=r?.roundPosition,o=n%2?1:-1,i=n+o;return{pairedPreviousMatchUp:ti({matchUpsMap:e,structureId:t}).find(({roundNumber:c,roundPosition:u})=>c===r?.roundNumber&&u===i)}}function zh({inContextDrawMatchUps:t,sourceMatchUpStatus:e,sourceMatchUpId:r,matchUpsMap:n,matchUp:o}){let i=t.find(a=>a.matchUpId===r),{pairedPreviousMatchUp:s}=Kh({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=Re(p)||!isNaN(p)?{code:p}:p;return m.sideNumber===u?{...m,previousMatchUpStatus:e}:m})}}function rd({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 hc({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=ye({drawDefinition:o})),t||(t=ne({inContext:!0,drawDefinition:o,matchUpsMap:a}).matchUps??[]);let m=t.find(b=>b.matchUpId===c),d=m?.structureId,l=o?.structures?.find(b=>b.structureId===d);if(!l)return{error:Gt};let f=a?.drawMatchUps?.find(b=>b.matchUpId===c),g=f?.drawPositions??[],{positionAdded:I,positionAssigned:h,updatedDrawPositions:S}=Bb({drawPosition:s,drawPositions:g}),{positionAssignments:T}=Ct({drawDefinition:o,structure:l}),N=T?.filter(b=>S.includes(b.drawPosition))?.find(({bye:b})=>b),E=f?.matchUpStatus&&[vt,bt].includes(f.matchUpStatus)&&S.filter(Boolean).length<2;if(i=N&&Nt||i||E&&f.matchUpStatus||f?.matchUpStatus&&[ge,Ne].includes(f.matchUpStatus)&&f.matchUpStatus||Qt,f&&I){t=ne({inContext:!0,drawDefinition:o,matchUpsMap:a}).matchUps??[];let b=E&&rd({inContextDrawMatchUps:t,drawPosition:s,matchUpId:c})||void 0;f?.matchUpStatusCodes&&zh({inContextDrawMatchUps:t,sourceMatchUpStatus:e,sourceMatchUpId:n,matchUpsMap:a,matchUp:f}),Object.assign(f,{drawPositions:S,winningSide:b,matchUpStatus:i}),It({tournamentId:r?.tournamentId,eventId:m?.eventId,context:p,drawDefinition:o,matchUp:f})}let A=nr({inContextDrawMatchUps:t,inContextMatchUp:m,drawDefinition:o,matchUpId:c}),{targetMatchUps:{winnerMatchUp:U,loserMatchUp:C,loserTargetDrawPosition:P},targetLinks:{loserTargetLink:D}}=A,M=ti({structureId:l.structureId,matchUpsMap:a});if(h&&N){if(U)if([Nt,ge,Ne].includes(i)){let b=hc({matchUpId:U.matchUpId,inContextDrawMatchUps:t,tournamentRecord:r,drawDefinition:o,drawPosition:s,matchUpsMap:a});if(b.error)return b}else{let{structureId:b}=U;b!==l.structureId&&console.log("winnerMatchUp in different structure... participant is in different targetDrawPosition")}}else if(U&&m&&!m.feedRound){let{pairedPreviousMatchUpIsDoubleExit:b}=$h({targetMatchUp:f,drawPosition:s,matchUpsMap:a,structure:l});if(b){let v=hc({matchUpId:U.matchUpId,inContextDrawMatchUps:t,tournamentRecord:r,drawDefinition:o,drawPosition:s,matchUpsMap:a});if(v.error)return v}}if(f?.matchUpType===Bt){let b=t?.find(({matchUpId:F})=>F===f.matchUpId),O=(b?.sides??[]).reduce((F,L,x)=>L.drawPosition===s?x:F,void 0),w=T?.find(F=>F.drawPosition===s)?.participantId;w&&O!==void 0&&ed({inContextTargetMatchUp:b,drawPositionSideIndex:O,teamParticipantId:w,tournamentRecord:r,drawDefinition:o,matchUp:f})}if(D?.linkCondition===Xn&&S.filter(Boolean).length===2&&!N&&M.filter(({drawPositions:O,roundNumber:w})=>w===1&&Fe(O,S)).every(({matchUpStatus:O})=>[me,er].includes(O))&&C){let{structureId:O}=C,w=Cr({drawPosition:P,tournamentRecord:r,drawDefinition:o,structureId:O,matchUpsMap:a,event:u});if(w.error)return w}return h?{...R}:_({result:{error:ja},context:{drawPosition:s},stack:p})}function Qh({inContextDrawMatchUps:t,drawDefinition:e,assignments:r,matchUpsMap:n,structure:o}){let s=ts({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)&&jt(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 nd({lineUp:t}){if(!Array.isArray(t))return;let e={};return pt(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}=Tp({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 Rn(t){return`${t} must be an array`}function od({lineUp:t,tieFormat:e}){let r=[];if(!Array.isArray(t))return r.push(Rn("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(Rn("collectionAssignments")),!1):(r.push("Missing participantId"),!1)}),o=pt(t.map(gt)).length===t.length;return o||r.push("Duplicated participantId(s)"),{valid:n&&o,errors:r,error:r.length?G:void 0}}function Vi({drawDefinition:t,participantId:e,tieFormat:r,lineUp:n}){if(typeof t!="object")return{error:X};if(typeof e!="string")return{error:ee};let o=od({lineUp:n,tieFormat:r});if(!o.valid)return o;let{extension:i}=dt({element:t,name:Do}),s=i?.value||{};return s[e]=nd({lineUp:n}),yt({element:t,extension:{name:Do,value:s}}),Sa({drawDefinition:t}),{...R}}function eg({inContextDrawMatchUps:t,inheritance:e=!0,tournamentRecord:r,drawDefinition:n,matchUpsMap:o,assignments:i,structure:s,event:a}){if(!n)return{error:X};let{drawPositions:c,matchUps:u,targetMatchUps:p}=Qh({inContextDrawMatchUps:t,matchUpsMap:o,assignments:i,structure:s});for(let m of p)m.matchUpType===gn&&(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&&Vi({drawDefinition:n,participantId:I,lineUp:[],tieFormat:g})}It({tournamentId:r?.tournamentId,context:"resetLineUps",eventId:a?.eventId,drawDefinition:n,matchUp:f})}}});return{...R}}function bn({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 _({result:{error:ee},stack:l});p=p??ye({drawDefinition:i}),e||({matchUps:e}=ne({inContext:!0,drawDefinition:i,matchUpsMap:p}));let f=st({drawDefinition:i,structureId:m});if(f.error)return _({result:f,stack:l});let{structure:g}=f;if(!g)return{error:Gt};if(gr({structure:g}))return _({result:{error:Ze},stack:l});let{seedAssignments:I}=Hr({provisionalPositioning:t,drawDefinition:i,structure:g}),S=I?.find(D=>D.participantId===a)?.seedNumber,{appliedPolicies:T}=ht({tournamentRecord:o,drawDefinition:i,structure:g,event:d});if(S&&!Up({seedNumber:S,appliedPolicies:T,drawDefinition:i,seedBlockInfo:c,drawPosition:u,structureId:m}))return _({result:{error:Sl},context:{drawPosition:u},stack:l});let N=de({structure:g}).positionAssignments||[],E=N?.find(D=>D.drawPosition===u);if(!E)return _({result:{error:Ds},context:{drawPosition:u},stack:l});if(N?.map(gt).includes(a))return _({result:{error:Rs},context:{drawPosition:u},stack:l});let{containsParticipant:U,containsBye:C}=P(E);if(C){let D=lc({inContextDrawMatchUps:e,tournamentRecord:o,drawDefinition:i,drawPosition:u,structureId:m,matchUpsMap:p,event:d});if(D.error)return _({result:D,stack:l})}if(U&&E.participantId!==a){let{activeDrawPositions:D}=Da({drawDefinition:i,structureId:m});if(D.includes(u))return _({result:{error:Bu},stack:l});eg({assignments:[E],inContextDrawMatchUps:e,tournamentRecord:o,drawDefinition:i,matchUpsMap:p,structure:g})}if(E.participantId=a,r&&(E.qualifier=!0),(g?.stageSequence||0)>1||g.stage&&[He,ue].includes(g.stage)){let D=g.stage===at?at:tt,v=(i.structures?.find(O=>O?.stage===D&&O?.stageSequence===1)?.seedAssignments??[]).find(O=>O.participantId===a);if(v?.participantId){let{participantId:O,seedNumber:w,seedValue:F}=v;$s({eventId:d?.eventId,provisionalPositioning:t,tournamentRecord:o,drawDefinition:i,seedingProfile:s,participantId:O,seedNumber:w,seedValue:F,structureId:m,event:d})}}if(g.structureType!==ke)JF({provisionalPositioning:t,inContextDrawMatchUps:e,sourceMatchUpStatus:n,tournamentRecord:o,drawDefinition:i,drawPosition:u,matchUpsMap:p,structure:g,event:d});else{Vh({positionAssignments:N,tournamentRecord:o,drawDefinition:i,matchUpsMap:p,structure:g});let{drawPositions:D,matchUps:M,targetMatchUps:b}=Qh({assignments:[E],inContextDrawMatchUps:e,drawDefinition:i,matchUpsMap:p,structure:g});if(D&&M?.length===1&&M[0].matchUpType===Bt){let O=(b?.[0].sides??[]).reduce((w,F,L)=>D?.includes(F.drawPosition)?L:w,void 0);ed({inContextTargetMatchUp:b[0],teamParticipantId:a,matchUp:M[0],drawPositionSideIndex:O,tournamentRecord:o,drawDefinition:i})}}return Mo({tournamentId:o?.tournamentId,drawDefinition:i,structure:g,event:d}),{positionAssignments:N,...R};function P(D){let M=D.bye,b=D.qualifier,v=D.participantId;return{containsBye:M,containsQualifier:b,containsParticipant:v,filled:M||b||v}}}function JF({provisionalPositioning:t,inContextDrawMatchUps:e,sourceMatchUpStatus:r,tournamentRecord:n,drawDefinition:o,drawPosition:i,matchUpsMap:s,structure:a,event:c}){let u={isCollectionMatchUp:!1},{matchUps:p}=At({provisionalPositioning:t,matchUpFilters:u,drawDefinition:o,matchUpsMap:s,structure:a,event:c}),{roundMatchUps:m}=qe({matchUps:p}),{initialRoundNumber:d}=us({drawPosition:i,matchUps:p}),l=d&&m?.[d].find(f=>f.drawPositions?.includes(i));if(l){let f=hc({matchUpId:l.matchUpId,inContextDrawMatchUps:e,sourceMatchUpStatus:r,tournamentRecord:n,drawDefinition:o,drawPosition:i,matchUpsMap:s});if(f.error)return _({stack:"assignDrawPositionToMatchUps",context:{drawPosition:i},result:f})}return{...R}}function id(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:X};let m=ht({tournamentRecord:o,drawDefinition:i,event:u}).appliedPolicies??{},{inContextDrawMatchUps:d,matchUpsMap:l}=t;l||(l=ye({drawDefinition:i}),Object.assign(t,{matchUpsMap:l})),d||({matchUps:d}=ne({inContext:!0,drawDefinition:i,matchUpsMap:l}),Object.assign(t,{inContextDrawMatchUps:d}));let{positionAssignments:f}=Ct({drawDefinition:i,structureId:c}),g=f?.find(y=>y.drawPosition===a);if(g?.participantId){let y=g.participantId,N=bn({inContextDrawMatchUps:d,tournamentRecord:o,drawDefinition:i,participantId:s,drawPosition:a,structureId:c,matchUpsMap:l,event:u});return N.success?T({appliedPolicies:m,removedParticipantId:y}):_({result:N,stack:p})}let I=lc({inContextDrawMatchUps:d,tournamentRecord:o,drawDefinition:i,drawPosition:a,structureId:c,matchUpsMap:l,event:u});if(I.error)return _({result:I,stack:p});let h=I.participantId,S=bn({inContextDrawMatchUps:d,isQualifierPosition:r,tournamentRecord:o,drawDefinition:i,participantId:s,drawPosition:a,structureId:c,matchUpsMap:l,event:u});if(!S.success)return _({result:S,stack:p});return T({appliedPolicies:m,removedParticipantId:h});function T({appliedPolicies:y,removedParticipantId:N}){let{structure:E}=st({drawDefinition:i,structureId:c});wm({drawPositions:[a],structure:E});let A={[e]:s,name:n,drawPosition:a,structureId:c};return ru({appliedPolicies:y,drawDefinition:i,positionAction:A}),_({context:{removedParticipantId:N},result:{...R},stack:p})}}function Hb({luckyLoserParticipantId:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,structureId:o}){return id({positionActionName:"luckyLoserDrawPositionAssignment",participantId:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,structureId:o})}function vU(t){return Hb(t)}function Wb({alternateParticipantId:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,structureId:o}){return id({positionActionName:"alternateDrawPositionAssignment",participantIdAttributeName:"alternateParticipantid",participantId:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,structureId:o})}function OU(t){return Wb(t)}function Xh({params:t,modMap:e,structure:r}){let{tournamentRecord:n,drawDefinition:o,event:i}=t;for(let s of r.matchUps)e[s.matchUpId]&&(s.roundNumber=e[s.matchUpId],It({tournamentId:n?.tournamentId,eventId:i?.eventId,drawDefinition:o,matchUp:s}))}function Jh(t,e){let r=[{drawDefinition:!0,structureId:!0}];Array.isArray(e)&&r.push(...e);let n=ut(t,r);if(n.error)return n;let o=st(t);if(o.error)return o;let i=o.structure;if(!gr({structure:i}))return _({result:{error:Ci,message:"structure must be adHoc"}});let{roundMatchUps:a=[],roundNumbers:c}=qe({matchUps:i?.matchUps});return c?.length?{valid:!0,structure:i,roundMatchUps:a,roundNumbers:c}:{error:An}}function _U(t){let e=Jh(t,[{targetRoundNumber:!0,roundNumber:!0,[dn]:lR}]);if(e.error)return e;let{structure:r,roundMatchUps:n,roundNumbers:o}=e,{targetRoundNumber:i,roundNumber:s}=t;if(!o?.includes(s)||!o?.includes(i))return _({result:{error:G},info:"roundNumbers must be valid rounds"});let a=i>s,c=a?Z(s+1,i+1):Z(i,s),u={};return c.forEach(p=>(n?.[p]??[]).forEach(({matchUpId:m})=>{u[m]=p-(a?1:-1)})),n?.[s]?.forEach(({matchUpId:p})=>u[p]=i),Xh({params:t,modMap:u,structure:r}),{...R}}function xU({structurePositionAssignments:t,provisionalPositioning:e,tournamentRecord:r,drawDefinition:n,event:o}){if(!n)return{error:X};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:Gt};let d=Ct({structure:m}).positionAssignments?.map(({drawPosition:I})=>I),l=u?.map(({drawPosition:I})=>I);if(jt(d,l).length!==d?.length)return _({result:{error:G},info:"drawPositions do not match",stack:i});let f=ye({drawDefinition:n}),{matchUps:g}=ne({inContext:!0,drawDefinition:n,matchUpsMap:f});for(let I of u||[]){let{drawPosition:h,participantId:S,bye:T,qualifier:y}=I;if(T){let N=Cr({tournamentRecord:r,drawDefinition:n,drawPosition:h,matchUpsMap:f,structureId:c,structure:m,event:o});if(N?.error)return N}else if(y)u.forEach(N=>{N.drawPosition===h&&(N.qualifier=!0,delete N.participantId,delete N.bye)});else if(S){let N=bn({provisionalPositioning:e,inContextDrawMatchUps:g,tournamentRecord:r,drawDefinition:n,participantId:S,drawPosition:h,matchUpsMap:f,structureId:c,event:o});if(N?.error)return N}}Mo({tournamentId:r?.tournamentId,drawDefinition:n,structure:m,event:o})}let s=t.map(({structureId:a})=>a);return Ot({tournamentId:r?.tournamentId,eventId:o?.eventId,drawDefinition:n,structureIds:s}),{...R}}function wU(t){let e=Jh(t,[{roundNumbers:!0,[dn]:Dr,[Pn]:s=>s.length===2&&s.every(Jt)}]);if(e.error)return e;let{structure:r,roundMatchUps:n,roundNumbers:o}=e;if(!t.roundNumbers.every(s=>o?.includes(s)))return _({result:{error:G,message:"roundNumbers must be valid rounds"}});let i={};return t.roundNumbers.forEach((s,a)=>(n?.[s]??[]).forEach(({matchUpId:c})=>{i[c]=t.roundNumbers[1-a]})),Xh({params:t,modMap:i,structure:r}),{...R}}function jb({qualifyingParticipantId:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,structureId:o}){return id({positionActionName:"qualifierDrawPositionAssignment",participantId:t,isQualifierPosition:!0,tournamentRecord:e,drawDefinition:r,drawPosition:n,structureId:o})}function LU(t){return jb(t)}function Yb({tournamentRecord:t,drawDefinition:e,drawPositions:r,structureId:n,event:o}){if(!e)return{error:X};if(!n)return{error:Sr};if(r?.length!==2)return{error:G,drawPositions:r};let i=ye({drawDefinition:e}),{matchUps:s}=ne({inContext:!0,drawDefinition:e,matchUpsMap:i}),{structure:a}=st({drawDefinition:e,structureId:n});if(!a)return{error:Gt};let c=ht({tournamentRecord:t,drawDefinition:e,event:o}).appliedPolicies??{},u;if(a.structureType===ke?u=eG({inContextDrawMatchUps:s,tournamentRecord:t,drawDefinition:e,drawPositions:r,matchUpsMap:i,structure:a,event:o}):u=ZF({inContextDrawMatchUps:s,tournamentRecord:t,drawDefinition:e,drawPositions:r,matchUpsMap:i,structure:a,event:o}),u.error)return u;if(wm({structure:a,drawPositions:r}),ru({appliedPolicies:c,drawDefinition:e,positionAction:{name:"swapDrawPositionAssignments",drawPositions:r,structureId:n}}),Mo({tournamentId:t?.tournamentId,drawDefinition:e,structure:a,event:o}),o.eventType===jr){let m=At({matchUpFilters:{matchUpTypes:[gn]},inContext:!0,structure:a}).matchUps.filter(l=>l.drawPositions?.some(f=>r.includes(f))),d=At({matchUpFilters:{matchUpTypes:[gn]},structure:a}).matchUps;m.forEach(l=>{(l.sides||[]).forEach(f=>{let g=f?.drawPosition;if(r.includes(g)){let I=f.participantId,h=d.find(({matchUpId:T})=>T===l.matchUpId),S=l?.sides?.reduce((T,y,N)=>y.drawPosition===g?N:T,void 0);ed({inContextTargetMatchUp:l,drawPositionSideIndex:S,teamParticipantId:I,tournamentRecord:t,drawDefinition:e,matchUp:h,event:o})}})})}return Ot({drawDefinition:e,structureIds:[n]}),{...R}}function ZF({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?qb({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,assignments:a,matchUpsMap:o,structure:i,event:s}):tG({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,assignments:a,matchUpsMap:o,structure:i,event:s})}function qb({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=Iu({drawPosition:u,inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,structureId:d,matchUpsMap:o});return l.error||(l=Iu({drawPosition:m,inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,structureId:d,matchUpsMap:o}),l.error)||(Cr({drawPosition:m,tournamentRecord:e,drawDefinition:r,structureId:d,matchUpsMap:o,event:s}),l=bn({drawPosition:u,inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,structureId:d,participantId:p,matchUpsMap:o,event:s}),l.error)?l:{...R}}function tG({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),eg({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,matchUpsMap:o,assignments:n,structure:i,event:s}),{...R}}function eG({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};eg({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)qb({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 FU(t){return Yb(t)}function GU({validation:t=!0,tournamentRecord:e,drawDefinition:r,participantId:n,structureId:o,seedValue:i,event:s}){if(!r)return{error:X};if(!o)return{error:Sr};let a=(e?.participants??[]).find(l=>l.participantId===n);if(e&&!a)return{error:Zr};let{structure:c}=st({drawDefinition:r,structureId:o});if(!c)return{error:Gt};if(!(!t||Jt(i)||i===void 0||i===""||typeof i=="string"&&i.split("-").every(l=>Jt(l)&&ct(l)>0)))return{error:G};let{seedAssignments:p}=Hr({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 ph({tournamentId:e?.tournamentId,eventId:s?.eventId,drawDefinition:r,structure:c}),{...R}}function Zh({drawDefinition:t,structureId:e}){if(!t)return{error:X};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 rg({withStageGrouping:t,stageSequences:e,stageSequence:r,roundTarget:n,stages:o,event:i,stage:s}){if(!i)return{error:Dt};let a={},c=[];for(let u of i.drawDefinitions||[]){let{structures:p,stageStructures:m}=Gn({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 tS({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}=rg({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 ei(t){if(!t?.drawDefinition)return!1;let e=lu(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 eS(t){let{drawDefinition:e,structureId:r}=t;if(!e)return{error:X};let{playoffStructures:n}=Zh({drawDefinition:e,structureId:r});if(!n?.length)return!1;let o=e?.entries?.filter(c=>c?.entryStatus&&wr.includes(c.entryStatus))?.length??0,i=0;return(n||[]).reduce((c,u)=>!!((Ct({structure:u}).positionAssignments??[])?.filter(d=>(d.participantId&&i++,d?.bye??d?.participantId)).length&&c),!!n.length)||i===o}function rS({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=rS({accessors:s,significantCharacters:t,value:c});n.push(...u)});else if(r=r[o],s.length){let a=rS({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 $b({targetParticipantIds:t,policyAttributes:e,idCollections:r,participants:n}){if(!Array.isArray(e))return{error:AI};if(!Array.isArray(n))return{error:Ka};let o={};return t.forEach(i=>{let s=n.find(c=>c.participantId===i),{values:a}=kU({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 kU({policyAttributes:t,idCollections:e,participants:r,participant:n}){if(!Array.isArray(t))return{error:AI};if(!n)return{error:vi};let o=[];return t.forEach(s=>{let{directive:a,groupings:c,key:u,significantCharacters:p}=s||{};if(u){let m=u.split(".");o.push(...rS({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:pt(o)}}function VU({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}=kU({participants:e,policyAttributes:r,idCollections:n,participant:s});return{...i,values:a}})}function zb({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 Qb(t){let{unfilledPositions:e,chunkedDrawPositions:r}=t,n=zb(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=Kb(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=Kb(c);return!s.includes(u)}}}function Xb(t){let{unfilledPositions:e,chunkedDrawPositions:r}=t,n=zb(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 Kb(t){return Number(t%2?t+1:t-1)}function Jb({allGroups:t,participantId:e}){return Object.keys(t).filter(r=>t[r].includes(e))}function Zb({selectedParticipantGroups:t,participantIdGroups:e,positionAssignments:r,drawPositionChunks:n,unfilledPositions:o,isRoundRobin:i}){let s=n.map(a=>i?Xb({groupsToAvoid:t,chunkedDrawPositions:a,participantIdGroups:e,positionAssignments:r,unfilledPositions:o}):Qb({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 nS({positionAssignments:t,participantIds:e}){let r=t.map(n=>n.participantId);return e.filter(n=>!r.includes(n))}function tv({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?cn(a):cn(Object.keys(i));return o=t&&i[o]?.length?o:c,{participantId:o&&i[o]?cn(i[o]):cn(e),groupKey:o}}function ev({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 rv({candidatePositionAssignments:t,unseededParticipantIds:e,participantIdGroups:r,drawPositionChunks:n,drawPositionGroups:o,pairedPriority:i,allGroups:s,groupKey:a}){let u=o.reduce((C,P)=>P.length>C?P.length:C,0)<=2,p=nS({positionAssignments:t,participantIds:e}),m=ev({positionAssignments:t,drawPositionGroups:o}),{participantId:d,groupKey:l}=tv({targetParticipantIds:p,useSpecifiedGroupKey:u,allGroups:s,groupKey:a}),f=Jb({participantId:d,allGroups:s}),g=Zb({positionAssignments:t,isRoundRobin:u,selectedParticipantGroups:f,participantIdGroups:r,drawPositionChunks:n,unfilledPositions:m}),{unassigned:I,unpaired:h,pairedNoConflict:S}=g,T=S?.length&&S[0],y=h?.length&&h[0],N=i&&T?T:y,E=i?y:T,A=N?.length&&N||E?.length&&E,U;if(A?.length){let C=Gr(A);U=Gr(C)}else{let C=Gr(I[0]);U=Gr(C)}return{newGroupKey:l,selectedParticipantId:d,targetDrawPosition:U}}function sd({isRoundRobin:t,groupedParticipants:e}){let r=[];return t?e.forEach(n=>{let o=n.map(a=>a.drawPosition),i=Xf({drawPositions:o}).uniqueMatchUpGroupings??[],s=Object.assign({},...n.map(a=>({[a.drawPosition]:a})));i.forEach(a=>{Fe(s[a[0]].values||[],s[a[1]].values||[])&&(r.push(a),n.conflict=!0)})}):e.forEach(n=>{Fe(n[0]?.values||[],n[1]?.values||[])&&(r.push(n),n.conflict=!0)}),r}function nv({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=sd({isRoundRobin:o,groupedParticipants:[[c,l]]}),h=[t.find(T=>T.drawPosition===m),l],S=sd({isRoundRobin:o,groupedParticipants:[h]});return!g.length&&!S.length});if(p.length)return{drawPosition:c.drawPosition,possibleDrawPositions:p}}).filter(Boolean)}).flat(1)}function BU(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:y,targetDrawPosition:N}=rv({...t,candidatePositionAssignments:l,allGroups:c,groupKey:p});p=T,l.forEach(E=>{E.drawPosition===N&&(E.participantId=y)})});let g=VU({candidatePositionAssignments:l,participantsWithGroupings:r,policyAttributes:s,idCollections:a}),I=Te(g,m),h=sd({groupedParticipants:I,isRoundRobin:d}),S=0;for(;S<20&&h.length;){let T=nv({positionedParticipants:g,potentialDrawPositions:f,avoidanceConflicts:h,drawPositionGroups:i,isRoundRobin:d});if(T.length){let y=rG({candidatePositionAssignments:l,swapOptions:T});y.error&&console.log({result:y}),g=VU({candidatePositionAssignments:l,participantsWithGroupings:r,policyAttributes:s,idCollections:a}),I=Te(g,m),h=sd({groupedParticipants:I,isRoundRobin:d}),S++}else S=20}return l.forEach(T=>{if(T.bye&&T.participantId){let y=hI;u.push(y)}if(T.qualifier&&T.participantId){let y=hI;u.push(y)}}),{positionAssignments:l,conflicts:h.length,groupedParticipants:I,errors:u}}function rG({candidatePositionAssignments:t,swapOptions:e}){let r=Gr(e);if(!r)return{error:{message:"No swap options"}};let n=r.drawPosition,o=Gr(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 ov({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:CA};let{candidatesCount:l=1,policyAttributes:f,targetDivisions:g}=p,{roundsToSeparate:I}=p,h="randomUnseededSeparation",{structure:S}=st({drawDefinition:i,structureId:u}),{matchUps:T}=At({provisionalPositioning:t,matchUpsMap:c,structure:S,event:d});if(g&&En(g)&&!I){let H=qC(g)||0,W=T.reduce((V,Y)=>Y.roundNumber>V?Y.roundNumber:V,0);I=W<H?1:W-H+1}let{positionAssignments:y}=de({structure:S}),N=Lm({participantsProfile:{convertExtensions:!0},deepCopy:!1,participants:a}).participantsWithGroupings,E=y?.filter(H=>!H.participantId),A=y?.map(H=>H.drawPosition),U=S?.structureType===ke,C=U?{structure:S,matchUps:T,allDrawPositions:A,roundsToSeparate:I}:{matchUps:T,allDrawPositions:A,roundsToSeparate:I},{drawPositionGroups:P,drawPositionChunks:D}=U?nG(C):oG(C),M={groupParticipants:a.filter(H=>H.participantType===Er).map(H=>H.participantId),teamParticipants:a.filter(H=>H.participantType===xt).map(H=>H.participantId),pairParticipants:a.filter(H=>H.participantType===lt).map(H=>H.participantId)},b=$b({targetParticipantIds:e,policyAttributes:f,idCollections:M,participants:a});if(b.error)return _({result:b,stack:h});let v=Object.assign({},...e.map(H=>{let W=Object.keys(b).filter(V=>(b[V]??[]).includes(H));return{[H]:W}})),O=nS({participantIds:e,positionAssignments:y});if(O.length>(E?.length||0))return{error:_l};let w,F=O.length,L=Z(0,l).map(()=>BU({initialPositionAssignments:y,participantsWithGroupings:N,unseededParticipantIds:e,opponentsToPlaceCount:F,pairedPriority:!1,unseededByePositions:n,participantIdGroups:v,drawPositionChunks:D,drawPositionGroups:P,policyAttributes:f,idCollections:M,allGroups:b,drawSize:m}));if(w=L.reduce((H,W)=>!H||(W.conflicts||0)<(H.conflicts||0)?W:H,void 0),!w||w.conflicts){let H=Z(0,l).map(()=>BU({initialPositionAssignments:y,participantsWithGroupings:N,unseededParticipantIds:e,opponentsToPlaceCount:F,pairedPriority:!0,unseededByePositions:n,participantIdGroups:v,drawPositionChunks:D,drawPositionGroups:P,policyAttributes:f,idCollections:M,allGroups:b,drawSize:m}));w=L.concat(...H).filter(V=>!V.errors?.length).reduce((V,Y)=>!V||(Y.conflicts||0)<(V.conflicts||0)?Y:V,void 0)}if(!w)return{error:$u};let x=(Ct({structure:S})?.positionAssignments??[]).filter(H=>H.participantId).map(H=>H.participantId),B=w.positionAssignments.filter(H=>!x.includes(H.participantId));for(let H of B)if(H.bye){let W=Cr({tournamentRecord:o,drawDefinition:i,seedBlockInfo:s,structureId:u,matchUpsMap:c,event:d,...H});if(W.error)return _({result:W,stack:h})}else if(H.participantId){let W=bn({automaticPlacement:!0,inContextDrawMatchUps:r,tournamentRecord:o,drawDefinition:i,seedBlockInfo:s,structureId:u,matchUpsMap:c,event:d,...H});if(W.error)return _({result:W,stack:h,context:{assignment:H}})}return{...R}}function nG(t){let{structure:{structures:e}}=t,r=e.map(n=>n.positionAssignments.map(o=>o.drawPosition));return{drawPositionGroups:r,drawPositionChunks:[r]}}function oG({allDrawPositions:t,roundsToSeparate:e,matchUps:r}){let n=r.filter(d=>d.roundNumber===1).map(d=>d.drawPositions),o=n.flat().sort(se),i=Math.max(...o),s=t.filter(d=>d>i),a=o.length,u=Z(a===2?1:2,a).filter(d=>d===fm(d)),m=u.slice(0,e||u.length).reverse().map(d=>Te(o,d));return s.length&&console.log({fedDrawPositions:s}),{drawPositionGroups:n,drawPositionChunks:m}}function iv({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}=Hr({provisionalPositioning:t,drawDefinition:i,structure:p}),I=g?.map(D=>D.participantId).filter(Boolean),{stage:h,stageSequence:S}=p,T=h===at?dt({element:p,name:ln})?.extension?.value:void 0,N=Ii({provisionalPositioning:t,drawDefinition:i,stageSequence:S,entryStatuses:Qo,structureId:u,roundTarget:T,stage:h}),A=N.filter(D=>!I?.includes(D.participantId)).map(D=>D.participantId),U=f?.filter(D=>!D.participantId&&!D.bye&&!D.qualifier).map(D=>D.drawPosition);if(!n&&A.length>(U?.length||0))return _({result:{error:_l},context:{unseededParticipantsCount:A.length,unfilledDrawPositionsCount:U?.length},stack:l});let{appliedPolicies:C}=ht({tournamentRecord:o,drawDefinition:i,event:d}),P=C?.[Yc];if(p.stage===ue){let D=N.reduce((M,b)=>(M[b.groupingValue]||(M[b.groupingValue]=[]),M[b.groupingValue].push(b.participantId),M),{});Object.keys(D).length&&(P||(P={policyName:"Playoff Avoidance"}),P.policyAttributes||(P.policyAttributes=[]),P.policyAttributes.push({groupings:D}))}return P&&a?ov({provisionalPositioning:t,unseededParticipantIds:A,inContextDrawMatchUps:e,unseededByePositions:r,tournamentRecord:o,drawDefinition:i,seedBlockInfo:s,participants:a,matchUpsMap:c,structureId:u,avoidance:P,drawSize:m,entries:N}):iG({provisionalPositioning:t,unseededParticipantIds:A,inContextDrawMatchUps:e,unfilledDrawPositions:U,multipleStructures:n,tournamentRecord:o,drawDefinition:i,seedBlockInfo:s,structureId:u,matchUpsMap:c,drawSize:m,event:d})}function iG({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?pr(n):n.reverse();for(let l of e){let f=d.pop();if(!o||f){let g=bn({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 _({result:g,stack:"randomUnseededDistribution"})}}return{...R}}function sv(t){let e=t.structure??st(t).structure,r="positionQualifiers",n=[];if(e.stage===He)return _({result:{error:Ri},stack:r});let{unplacedRoundQualifierCounts:o,positionAssignments:i,roundDrawPositions:s}=sG(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 _({result:{error:YA},context:{unfilledDrawPositions:c},stack:r});Z(0,o[a]).forEach(()=>{let u=Gr(c);n.push(u),i?.forEach(p=>{p.drawPosition===u&&(p.qualifier=!0,delete p.participantId,delete p.bye)})})}return{...R,qualifierDrawPositions:n}}function sG({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}=ms({drawDefinition:t,stageSequence:i,structureId:r,stage:o}),u=(a?Object.keys(a):[]).map(h=>ct(h)),{matchUps:p}=At({structure:e}),{roundProfile:m}=qe({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 HU({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=ht({drawDefinition:i}).appliedPolicies),!o){let h=d&&fs({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=aG({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 aG({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}=qh({provisionalPositioning:t,randomize:!0,drawDefinition:n,seedingProfile:o,seedBlockInfo:i,structureId:a,event:u}),{appliedPolicies:d}=ht({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:Ns};f.push(I);let h=bn({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 av({provisionalPositioning:t,drawDefinition:e,structure:r}){let{positionAssignments:n}=de({structure:r}),{seedAssignments:o}=Hr({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 cv({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=WU(Te(i.drawPositions,2)),c,u=t[n.length];for(;c=ng(a,u);)n.push(c),u=t[n.length]}});let o=n.map(i=>Array.isArray(i)?pr(i):i).flat(1/0);return CI(r)&&e.map(s=>s.seedNumbers[0]).includes(r)?t:o}function ng(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 ng(e?o:t[Math.round(Math.random())],e)}return r<n?ng(t[1],e):ng(t[0],e)}function WU(t){let e=Math.floor(t.length/2);return t.length>2?[WU(t.slice(0,e)),WU(t.slice(e))]:t}function pv({provisionalPositioning:t,relevantMatchUps:e,appliedPolicies:r,drawDefinition:n,seedingProfile:o,seedBlockInfo:i,byesToPlace:s,structure:a}){i||(i=fs({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=av({provisionalPositioning:t,drawDefinition:n,structure:a})??[],l=pt([].concat(...e.map(N=>N.drawPositions))),f=d.filter(N=>l.includes(N.drawPosition)),g=(N,E)=>Ic(N.seedValue)-Ic(E.seedValue),h=m.reduce((N,E)=>{let A=f.filter(U=>E.drawPositions?.includes(U.drawPosition)).sort(g);return N.concat(...A)},[]).map(N=>N.drawPosition),S=cv({orderedSortedFirstRoundSeededDrawPositions:h,validSeedBlocks:m,byesToPlace:s}),T=uv({orderedSeedDrawPositions:h,relevantMatchUps:e}).slice(0,s),y=uv({orderedSeedDrawPositions:S,relevantMatchUps:e}).slice(0,s);return{strictSeedOrderByePositions:T,blockSeedOrderByePositions:y,isLuckyStructure:u,positionedSeeds:d,isContainer:p,isFeedIn:c}}function uv({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 mv({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(O=>O.participantId).map(O=>O.drawPosition),d={isCollectionMatchUp:!1},{matchUps:l,roundMatchUps:f}=At({provisionalPositioning:t,matchUpFilters:d,structure:s}),g=f?.[1]||[],I=s.structureType===ke?l:g,h=pt([].concat(...I.map(O=>O.drawPositions))),S=Math.min(...h)-1,T=m?.filter(O=>h.includes(O)),y=O=>{let w=Math.ceil(O.length/2),F=[O.slice(0,w),O.slice(w)],L=F.map(k=>[].concat(...k.flat(1/0)).length),x=Math.min(...L.flat(1/0)),B=Math.max(...L.flat(1/0)),H=L.indexOf(B),W=x!==B,V=pr(F),[Y,$]=!x||W?[F[H],F[1-H]]:[V[0],V[1]];return{greaterHalf:Y,lesserHalf:$}},N=O=>{let{greaterHalf:w,lesserHalf:F}=y(O),{greaterHalf:L,lesserHalf:x}=y(w),H=pr(L.flat(1/0)).pop(),W=L.flat().filter(Y=>Y!==H);return{newlyFilteredChunks:[...F,...x,W],drawPosition:H}},E=O=>!e.includes(O),A=O=>!T?.includes(O),U=O=>{let F=Te(O.sort(se),Math.ceil(O.length/4)).map(B=>B.filter(A)),L=[].concat(...F.flat(1/0)).length,x=[];for(let B=0;B<L;B++){let{newlyFilteredChunks:H,drawPosition:W}=N(F);x.push(W),F=H}return x},{validSeedBlocks:C}=fs({provisionalPositioning:t,allPositions:!0,appliedPolicies:n,drawDefinition:o,structure:s}),P=C?.map(O=>O.drawPositions?.map(w=>w+S)),D;if(a){let O=h.length,{seedBlocks:w}=Zf({cluster:Pp(c)===Xc,participantsCount:O});D=w.map(L=>L.map(x=>x+S)).map(U).filter(L=>L.length)}else u?D=P?.map(O=>O.filter(A)):D=P?.map(U).filter(O=>O.length);let M=I.map(O=>O.drawPositions).map(O=>O?.sort((w,F)=>w-F)).filter(O=>O?.[0]+1===O?.[1]),b=O=>M.reduce((w,F)=>F.includes(O)?F.reduce((L,x)=>x!==O?x:L,void 0):w,void 0),v=D.map(O=>O.map(b)).flat(1/0).filter(A).filter(E).filter(Boolean);if(u&&!s.structures){let O=i%4,w=v.slice(0,O),F=f[s.roundLimit]?.length,L=Te(v.slice(O),F).map(pr).flat();v=w.concat(L)}return{unseededByePositions:v}}function dv({provisionalPositioning:t,drawDefinition:e,matchUpsMap:r,structure:n,event:o}){let i={isCollectionMatchUp:!1},{matchUps:s,roundMatchUps:a}=At({afterRecoveryTimes:!1,provisionalPositioning:t,drawDefinition:e,matchUpFilters:i,matchUpsMap:r,structure:n,event:o}),c=a?.[1]||[],u=n?.structureType===ke,p=u?s:c,m=u?n?.structures?.length||0:s.length,{structureId:d,stage:l,stageSequence:f}=n,g=Ii({entryStatuses:wr,provisionalPositioning:t,drawDefinition:e,stageSequence:f,structureId:d,stage:l}),{qualifiersCount:I}=ms({provisionalPositioning:t,drawDefinition:e,stageSequence:f,structureId:d,stage:l}),h=g.length+I,{positionAssignments:S,unassignedPositions:T}=de({structure:n}),y=T?.map(P=>P.drawPosition),N=S?.filter(P=>P.bye).length,E=S?.filter(P=>P.bye).map(P=>P.drawPosition),A=p.map(P=>P.drawPositions).filter(P=>P?.reduce((D,M)=>!E?.includes(M)&&D,!0)).flat(1/0).filter(P=>y?.includes(P)),U=S?.length,C=U?U-h:0;return C>m&&n.stageSequence===1&&n.stage!==He&&(C=m),{placedByes:N,byesCount:C,relevantMatchUps:p,placedByePositions:E,roundMatchUps:a,positionsToAvoidDoubleBye:A}}function jU({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}=dv({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:y}=pv({provisionalPositioning:t,relevantMatchUps:g,appliedPolicies:r,drawDefinition:n,seedingProfile:i,seedBlockInfo:o,byesToPlace:I,structure:c}),N=c?.structureType&&[ke,cp].includes(c.structureType)&&r?.seeding?.containerByesIgnoreSeeding,E=d&&S?.length?S:h,{unseededByePositions:A}=mv({provisionalPositioning:t,seedOrderByePositions:E,isLuckyStructure:T,appliedPolicies:r,drawDefinition:n,seedLimit:u,structure:c,isFeedIn:y}),U=M=>M%2,C=(M,b)=>(M||[]).every(v=>U(v)?b!==v+1:b!==v-1),P=[].concat(...E);if(!p)for(;A.length;){let M=A.find(b=>C(P,b));M?(P.push(M),A=A.filter(b=>b!==M)):(P.push(...A),A=[])}N&&(P=pr(P),Pr({ignoreSeededByes:N})&&console.log({byePositions:P}));let D=P.slice(0,I);for(let M of D){let b=Cr({provisionalPositioning:t,tournamentRecord:e,drawDefinition:n,drawPosition:M,matchUpsMap:s,structureId:a,structure:c,event:m});if(b?.error)return b}return{...R,unseededByePositions:A,byeDrawPositions:D}}function Sc(t){let{drawDefinition:e}=t,{applyPositioning:r=!0,provisionalPositioning:n,multipleStructures:o,placeByes:i=!0,tournamentRecord:s,placementGroup:a,seedingProfile:c,structureId:u,seedLimit:p,seedsOnly:m,drawType:d,drawSize:l,event:f}=t,g=[];r||(SE(),e=J(e,!1,!0));let I=w=>(r||jl(),_({result:w,stack:"automatedPositioning"})),h=w=>(r||jl(),w),S=st({drawDefinition:e,structureId:u});if(S.error)return I(S);let T=S.structure;if(!T)return{error:Gt};let y=t.appliedPolicies||ht({drawDefinition:e,structure:T,event:f})?.appliedPolicies,{qualifiersCount:N}=ms({stageSequence:T.stageSequence,provisionalPositioning:n,stage:T.stage,drawDefinition:e,structureId:u}),E=Qo;if(!Ii({stageSequence:T.stageSequence,provisionalPositioning:n,stage:T.stage,placementGroup:a,drawDefinition:e,entryStatuses:E,structureId:u})?.length&&!N)return h({...R});let U=t.matchUpsMap??ye({drawDefinition:e}),C=t.inContextDrawMatchUps??ne({inContext:!0,drawDefinition:e,matchUpsMap:U})?.matchUps,P=[],D=fs({provisionalPositioning:n,appliedPolicies:y,drawDefinition:e,seedingProfile:c,structure:T});if(D.error)return D;let{validSeedBlocks:M}=D;g.push({validSeedBlocks:M});let b=t.participants||(s?Yt({withIndividualParticipants:!0,convertExtensions:!0,tournamentRecord:s})?.participants:[]);if(Pp(T.seedingProfile||c)===pi){let w=i?jU({provisionalPositioning:n,tournamentRecord:s,appliedPolicies:y,drawDefinition:e,seedBlockInfo:D,matchUpsMap:U,structure:T,seedLimit:p,seedsOnly:m,event:f}):void 0;if(w?.error)return I(w);P=w.unseededByePositions,g.push({action:"positionByes",unseededByePositions:P});let F=T.seedingProfile?{positioning:T.seedingProfile}:c;if(w=HU({seedingProfile:F,provisionalPositioning:n,inContextDrawMatchUps:C,tournamentRecord:s,appliedPolicies:y,validSeedBlocks:M,drawDefinition:e,seedBlockInfo:D,participants:b,matchUpsMap:U,structure:T,event:f}),w.error)return I(w);g.push({seedPositions:w.seedPositions,action:"positionSeedBlocks"})}else{if(d!==xi){let F=T.seedingProfile?{positioning:T.seedingProfile}:c,L=HU({seedingProfile:F,provisionalPositioning:n,inContextDrawMatchUps:C,tournamentRecord:s,appliedPolicies:y,validSeedBlocks:M,drawDefinition:e,seedBlockInfo:D,participants:b,matchUpsMap:U,structure:T,event:f});if(L.error)return I(L);g.push({action:"positionSeedBlocks",seedPositions:L.seedPositions})}let w=i?jU({provisionalPositioning:n,tournamentRecord:s,appliedPolicies:y,drawDefinition:e,seedBlockInfo:D,matchUpsMap:U,structure:T,seedLimit:p,seedsOnly:m,event:f}):void 0;if(w?.error)return I(w);P=w?.unseededByePositions,g.push({action:"positionByes",byeDrawPositions:w?.byeDrawPositions,unseededByePositions:P})}let v={};if(!m){let w=sv({inContextDrawMatchUps:C,tournamentRecord:s,appliedPolicies:y,validSeedBlocks:M,drawDefinition:e,seedBlockInfo:D,participants:b,matchUpsMap:U,structure:T});if(w.error||(w.conflicts&&(v.qualifierConflicts=w.conflicts),g.push({action:"positionQualifiers",qualifierDrawPositions:w.qualifierDrawPositions}),w=iv({provisionalPositioning:n,inContextDrawMatchUps:C,unseededByePositions:P,multipleStructures:o,tournamentRecord:s,drawDefinition:e,seedBlockInfo:D,participants:b,matchUpsMap:U,structureId:u,structure:T,drawSize:l,event:f}),w.error))return I(w);w.conflicts&&(v.unseededConflicts=w.conflicts),g.push({action:"positionUnseededParticipants"})}let{positionAssignments:O}=Ct({drawDefinition:e,structure:T});return Ot({drawDefinition:e,structureIds:[u]}),r||jl(),{positionAssignments:O,conflicts:v,...R,positioningReport:g}}function Tc(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:lr};if(!o)return{error:dr};if(!ei({drawDefinition:o,structureId:s})&&!r)return{error:hl};let m=Zh({drawDefinition:o,structureId:s}).playoffStructures?.sort((f,g)=>lf(f)-lf(g)),d=[],l=[];if(m)for(let f of m){let{structureId:g}=f,I=Sc({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 YU({drawDefinition:t,orderMap:e}){return t?((typeof e!="object"||!Object.values(e).every(r=>ft(r)))&&_({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)=>Xa(r.structureOrder)-Xa(n.structureOrder)),{...R}):{error:X}}function hu({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),y=o(S);return[mi,pn,up,pi].includes(I.target.feedProfile)?(T?.targets.push(S),y?.sources.push(h)):I.target.feedProfile===tn&&(y?.drawSources.push(h),T?.drawTargets.push(S)),s[S]=s[S]||I.target.feedProfile===tn,i[S]=pt([...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(),y=T&&n[T];y?.targets?.length?S.push(...y.targets):y&&(h.rootStage=y.stage)}if(h.rootStage||(h.rootStage=h.stage),!h.targets?.length){let T=h.sources??[];for(;T.length;){let y=T.pop(),N=y&&n[y];if(N?.sources?.length){for(let E of N.sources)h.progeny?.includes(E)||h.progeny?.push(E);T.push(...N.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 y=S.pop(),N=y?n.get(y):void 0;N?.drawTargets?.length&&S.push(N.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,y)=>Fe(h,y)?T.concat(...y):T,[])||[];return pt(h.concat(...S))})});let p=a[0],m=(I,h)=>jt(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(y=>y.includes(h))||(l.push([h]),S!==We&&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 oS({drawDefinition:t}){let{maxQualifyingDepth:e,structureProfiles:r}=hu({drawDefinition:t});for(let n of t.structures){let o=r[n.structureId];o.distanceFromMain&&(n.stageSequence=e+1-o.distanceFromMain)}return{...R}}function Ui(t){let{duplicateValues:e=!0,creationTime:r=!0,removePriorValues:n,timeItem:o}=t;if(!o)return{error:Ll};let i=dh(t);if(i.error)return i;if(!(Pt(o)&&Re(o.itemType)&&Object.keys(o).includes("itemValue")))return{error:wl};if(!i.timeItems)i.timeItems=[];else if(cG({element:i,duplicateValues:e,timeItem:o}))return{...R};if(o.itemSubTypes&&!o.itemSubTypes.length&&delete o.itemSubTypes,r){let c=new Date().toISOString();Object.assign(o,{createdAt:c})}return n&&(i.timeItems=i.timeItems.filter(({itemType:c})=>o.itemType!==c)),n&&!o.itemValue||i.timeItems.push(o),{...R}}function cG({element:t,duplicateValues:e,timeItem:r}){let{itemType:n,itemSubTypes:o,itemValue:i}=r,s=n&&Vn({itemSubTypes:o,itemType:n,element:t})?.timeItem;return s&&JSON.stringify(s?.itemValue)===JSON.stringify(i)&&!e}function og({creationTime:t=!0,removePriorValues:e,tournamentRecord:r,duplicateValues:n,participantId:o,timeItem:i}){if(!r)return{error:j};if(!o)return{error:ee};let s=fo({tournamentRecord:r,participantId:o});return s.error?s:Ui({element:s.participant,removePriorValues:e,duplicateValues:n,creationTime:t,timeItem:i})}function Bi(t){let{removePriorValues:e,tournamentRecord:r,duplicateValues:n,creationTime:o,timeItem:i}=t;return r?Ui({element:r,removePriorValues:e,duplicateValues:n,creationTime:o,timeItem:i}):{error:j}}function Hi(t){let{removePriorValues:e,duplicateValues:r,creationTime:n,timeItem:o,event:i}=t;return i?Ui({removePriorValues:e,duplicateValues:r,element:i,creationTime:n,timeItem:o}):{error:lr}}function ig({tournamentRecord:t,drawDefinition:e,structure:r,link:n}){if(!t)return{error:j};if(!e)return{error:X};let o=uG({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 Bi({tournamentRecord:t,timeItem:s}),o}function uG({drawDefinition:t,tournamentId:e,structure:r,eventId:n,link:o}){if(!t)return{error:X};if(!r)return{error:Oo};if(!o)return{error:yl};let i=o.target.structureId,s=st({drawDefinition:t,structureId:i});if(s.error)return _({stack:"attachQualifyingStructure",context:{targetStructureId:i},result:s});t.structures||(t.structures=[]),t.links||(t.links=[]),t.structures.push(r),t.links.push(o),oS({drawDefinition:t});let a=At({structure:r})?.matchUps||[];return No({drawDefinition:t,tournamentId:e,matchUps:a,eventId:n}),Ot({drawDefinition:t,structureIds:[r.structureId]}),{...R}}function qU({drawDefinition:t,structureDetails:e}){if(!Array.isArray(e))return{error:G};if(!t)return{error:X};let r=Object.assign({},...e.map(n=>{if(!Pt(n))return;let{structureId:o,structureName:i}=n||{};if(!(!o||!i))return{[o]:i}}).filter(Boolean));if(!Object.values(r).length)return{error:rt};for(let n of t.structures||[]){let o=r[n.structureId];o&&(n.structureName=o)}return{...R}}function sg({drawDefinition:t,timeItem:e}){if(!t)return{error:dr};if(!e)return{error:Ll};let r=e&&Object.keys(e),n=["itemType","itemValue"];if(!(n.filter(s=>r.includes(s)).length===n.length))return{error:wl};t.timeItems||(t.timeItems=[]);let i=new Date().toISOString();return Object.assign(e,{createdAt:i}),t.timeItems.push(e),Sa({drawDefinition:t}),{...R}}function $U(t){let{tournamentRecord:e,drawDefinition:r,structureId:n,event:o}=t,i=ut(t,[{drawDefinition:!0,structureId:!0}]);if(i.error)return i;let s=r.structures??[],a=s.find(h=>h.structureId===n);if(!a)return{error:Gt};let c=s.find(({stage:h,stageSequence:S})=>h===tt&&S===1),u=n===c?.structureId,p=s.filter(({stage:h})=>h===at).map(Mr("structureId"));if(u&&!p.length)return{error:aA};let m=p.includes(n),d=pG({isQualifyingStructure:m,structure:a,...t});if(d?.error)return d;let{structureIdsToRemove:l,relatedStructureIdsMap:f}=dG({qualifyingStructureIds:p,isQualifyingStructure:m,isMainStageSequence1:u,mainStageSequence1:c,drawDefinition:r,structureId:n}),{removedMatchUpIds:g,removedStructureIds:I}=lG({relatedStructureIdsMap:f,qualifyingStructureIds:p,isMainStageSequence1:u,mainStageSequence1:c,drawDefinition:r,structureIdsToRemove:l,structureId:n});if(mG({removedMatchUpIds:g,drawDefinition:r}),u){let h=(c.matchUps??[])?.map(Mr("matchUpId"));g.push(...h),c.positionAssignments=[],c.seedAssignments=[],c.matchUps=[],c.extensions&&(c.extensions=[])}return m&&oS({drawDefinition:r}),kn({tournamentId:e?.tournamentId,matchUpIds:g,action:"removeStructure",eventId:o?.eventId,drawDefinition:r}),Ot({drawDefinition:r,eventId:o?.eventId}),{...R,removedMatchUpIds:g,removedStructureIds:I}}function pG({isQualifyingStructure:t,tournamentRecord:e,drawDefinition:r,structureId:n,structure:o,event:i,force:s}){let a=[n];if(t){let p=d=>r.links?.find(l=>l.target.structureId===d),m=p(n)?.source.structureId;for(;m;)a.push(m),m=p(m)?.source.structureId}if(ne({matchUpFilters:{structureIds:a},drawDefinition:r}).matchUps?.some(({score:p})=>Ie({score:p}))){let p=ht({tournamentRecord:e,drawDefinition:r,structure:o,event:i})?.appliedPolicies;if(!(s??p?.[Ln]?.allowDeletionWithScoresPresent?.structures))return{error:Qu}}return{...R}}function mG({removedMatchUpIds:t,drawDefinition:e}){let{matchUps:r}=ne({drawDefinition:e});r?.forEach(n=>{n.winnerMatchUpId&&t.includes(n.winnerMatchUpId)&&delete n.winnerMatchUpId,n.loserMatchUpId&&t.includes(n.loserMatchUpId)&&delete n.loserMatchUpId})}function dG({qualifyingStructureIds:t,isQualifyingStructure:e,isMainStageSequence1:r,mainStageSequence1:n,drawDefinition:o,structureId:i}){let a=(o.structures??[]).map(Mr("structureId")),c=d=>o.links?.map(l=>l.source.structureId===d&&l.target.structureId!==n?.structureId&&l.target.structureId).filter(Boolean)??[],u=d=>o.links?.map(l=>t.includes(l.source.structureId)&&l.target.structureId===d&&l.source.structureId).filter(Boolean)??[],p=new Map;return a.forEach(d=>p.set(d,e?u(d):c(d))),{structureIdsToRemove:r?p.get(i):[i],relatedStructureIdsMap:p}}function lG({relatedStructureIdsMap:t,qualifyingStructureIds:e,isMainStageSequence1:r,mainStageSequence1:n,drawDefinition:o,structureIdsToRemove:i,structureId:s}){let a=[],c=[];for(;i?.length;){let u=i.pop();c.push(...IG({idBeingRemoved:u,drawDefinition:o}));let p=gG({qualifyingStructureIds:e,isMainStageSequence1:r,idBeingRemoved:u,drawDefinition:o,structureId:s});a.push(...p.removedStructureIds);let m=fG({relatedStructureIdsMap:t,mainStageSequence1:n,idBeingRemoved:u,structureId:s});m?.length&&i.push(...m)}return{removedMatchUpIds:c,removedStructureIds:a}}function fG({idBeingRemoved:t,relatedStructureIdsMap:e,mainStageSequence1:r,structureId:n}){return t&&e.get(t)?.filter(o=>o!==r?.structureId||n===r.structureId)}function gG({qualifyingStructureIds:t,isMainStageSequence1:e,idBeingRemoved:r,drawDefinition:n,structureId:o}){let i=[];return n.links=n.links?.filter(s=>s.source.structureId!==r&&s.target.structureId!==r)??[],(!e||e&&t.length||r!==o)&&(n.structures=(n.structures??[]).filter(s=>(r&&r===s.structureId&&i.push(r),s.structureId!==r))),{removedStructureIds:i}}function IG({idBeingRemoved:t,drawDefinition:e}){let{structure:r}=st({structureId:t,drawDefinition:e}),n=At({structure:r}).matchUps;return Mm(n)}function Dp({stageSequence:t=1,drawDefinition:e,drawSize:r,stage:n}){if(!e)return{error:X};if(!_f({drawDefinition:e,stage:n}))return{error:Ri};let o=VR({drawDefinition:e,stage:n}),{qualifiersCount:i}=ms({drawDefinition:e,stageSequence:t,stage:n}),s=o+i;if(r<s)return{error:II};let{entryProfile:a}=Mf({attributes:[{[n]:{drawSize:r}}],drawDefinition:e});return Ot({drawDefinition:e}),{...R,entryProfile:a}}function iS({qualifiersCount:t=0,drawDefinition:e,stage:r}){return e?_f({drawDefinition:e,stage:r})?r!==tt?{error:II,info:"qualifiersCount can only be set for main stage"}:(Mf({attributes:[{[r]:{qualifiersCount:t}}],drawDefinition:e}),Ot({drawDefinition:e}),{...R}):{error:Ri}:{error:X}}function lv({drawDefinition:t,drawSize:e}){if(!t)return{error:X};let r=Dp({stage:We,stageSequence:1,drawDefinition:t,drawSize:e});return r.error?r:(Ot({drawDefinition:t}),{...R})}function KU(t){return lv(t)}function zU({tournamentRecord:t,drawDefinition:e,participantId:r,structureId:n}){let o="removeSeededParticipant";if(!t)return{error:j};if(!e)return{error:X};let i=(e.structures??[]).find(a=>a.structureId===n);return i?!i.stage||![tt,at].includes(i.stage)||i.stage===tt&&i.stageSequence!==1?_({result:{error:Ci},stack:o}):i.seedAssignments?.find(a=>a.participantId===r)?{...R}:_({info:"participant not seeded",result:{error:Le},context:{participantId:r}}):_({result:{error:Gt},stack:o})}function Ca({targetEntryRound:t=1,finishingPositions:e,sourceRoundNumber:r,sourceStructureId:n,targetStructureId:o,linkType:i=po}){return!n||!o?{error:Sr}:{link:nt({linkType:i,source:{roundNumber:r,structureId:n,finishingPositions:e},target:{feedProfile:tn,roundNumber:t,structureId:o}})}}function ad({roundPosition:t,roundNumber:e,idPrefix:r,uuids:n}){return r?`${r}-${e}-${t}`:n?.pop()||Mt()}function Np({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=ad({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:Qt,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 hn({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&&(!En(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(!En(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}=Np({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}=Np({nodes:d,matchUpType:o,roundNumber:f,idPrefix:s,matchUps:l,isMock:c,uuids:u}),f++;let g=f-1;return l=Ua({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 cd(t){let e="generateQualifyingStructure";if(!t.drawDefinition)return _({result:{error:X},stack:e});if(t.drawSize&&!ft(t.drawSize)||t.participantsCount&&!ft(t.participantsCount)||t.qualifyingPositions&&!ft(t.qualifyingPositions))return _({result:{error:G},stack:e});let r=t.drawSize??lm(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 _({result:{error:qa},context:{drawSize:r},stack:e});if(o&&o>=t.drawSize)return _({result:{error:G},context:{drawSize:r,qualifyingPositions:o},stack:e});let h,S,T,y,N=0,E,A=1,{structureProfiles:U}=hu({drawDefinition:c}),C=U[i];if(!C)return _({result:{error:Gt},context:{targetStructureId:i},stack:e});let P=c.matchUpType,D=d?`${d}-`:"",M=C.stage===at,b=a?.[da]?.namingConventions?.pre??cb[da]?.namingConventions?.pre,v=M&&b?`${b}-`:"",O=p??(D?`${v}${$e(at)} ${D}`:`${v}${$e(at)}`);if(l===fn){let{maxRoundNumber:L,structures:x,groupCount:B}=Ma({structureName:p??O,structureId:m??I?.pop(),stage:at,structureOptions:s,appliedPolicies:a,stageSequence:A,matchUpType:P,roundTarget:d,idPrefix:f,drawSize:r,isMock:g,uuids:I});N=B,h=L,T=x[0],E=[1]}else({drawSize:r,matchUps:y,roundLimit:h,roundsCount:S}=hn({qualifyingRoundNumber:n,qualifyingPositions:o,matchUpType:P,idPrefix:f,drawSize:r,isMock:g,uuids:I})),h||(h=S),T=on({structureName:p??O,structureId:m??I?.pop(),qualifyingRoundNumber:h,stage:at,matchUpFormat:u,stageSequence:A,matchUpType:P,roundLimit:h,matchUps:y}),d&&yt({extension:{name:ln,value:d},element:T}),N=y?.filter(L=>L.roundNumber===h)?.length;let w=l===fn?zn:po,F=T&&h&&Ca({sourceStructureId:T.structureId,sourceRoundNumber:h,targetStructureId:i,finishingPositions:E,linkType:w})?.link;return{qualifyingDrawPositionsCount:r,qualifiersCount:N,...R,structure:T,link:F}}function QU(t){let e=t.tournamentRecord;if(!e)return{error:j};let r=hG(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:nt({drawId:s.drawId,qualifyingRoundNumber:n,qualifyingPositions:o,targetStructureId:i,structureName:a,matchUpType:c,drawSize:u,drawType:p})};return Bi({tournamentRecord:e,timeItem:d}),r}function hG(t){if(!t.drawDefinition)return{error:X};if(!t.targetStructureId)return{error:Sr};let e=cd(t);if(e.error)return e;let{structure:r,link:n}=e;return!r||!n?{error:G}:ig({tournamentRecord:t.tournamentRecord,drawDefinition:t.drawDefinition,structure:r,link:n})}function fv({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=ad({roundPosition:S.roundPosition,roundNumber:r,idPrefix:o,uuids:a}),y={roundPosition:S.roundPosition,drawPositions:[I],matchUpStatus:Qt,roundNumber:r,matchUpId:T};t&&(y.matchUpType=n),s&&(y.isMock=!0),i.push(y);let N={children:[S,h]};l.push(N)}let f=e?e-p:void 0;return{roundNodes:l,matchUps:i,drawPosition:f}}function ri(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=SG({drawSize:i}),h=I.length,S=0;if(r?.length)S=r.reduce((L,x)=>L+x,0);else if(e){let L=e-i;r=I.filter(x=>x<=L?(L-=x,!0):!1),S=r.reduce((x,B)=>x+B,0),n=r.length}else o>=h?n=0:u&&(n=h-u,o=0),r=I.filter((L,x)=>u&&!n||n&&x>=o+n||x<o?0:L),S=r.reduce((L,x)=>L+x,0),n=r.length;let T=[...I,...r].sort((L,x)=>x-L),y=T.length,E=[...(c??[]).map(L=>L-1),...(s??[]).map(L=>y-L)].map(L=>T[L]).reduce((L,x)=>L+x,0);S=S-E;let A=0,U=[],C,P=1,M=Z(0,i).map((L,x)=>({drawPosition:x+1+S})),b=S+1;for(let L of I){if({roundNodes:C,matchUps:U}=Np({matchUpType:m,roundNumber:P,idPrefix:d,matchUps:U,isMock:l,nodes:M,uuids:f}),P++,r.includes(L)){let x=fr(r)[L],B=Z(0,x),H=y+1-P,W=s?.includes(H)??c?.includes(P);B.forEach(()=>{({roundNodes:C,matchUps:U,drawPosition:b}=fv({drawPosition:!W&&b||void 0,nodes:C,matchUpType:m,roundNumber:P,idPrefix:d,matchUps:U,isMock:l,uuids:f,fed:A})),P++,A+=1})}M=C}y!==P-1&&console.log("ERROR");let v=i-S;U=Ua({finishingPositionOffset:p?v:a,positionsFed:S,roundsCount:y,matchUps:U,fmlc:g});let w=C?.length?C[0]:C;return w&&(w.roundNumber=P-1,w.matchUps=U),{draw:w,matchUps:U,roundsCount:y};function F(L){let x=fm(L);return x>L?x/2:x}}function SG({drawSize:t}){let e=Math.ceil(Math.log(t)/Math.log(2));return Z(0,e).reverse().map(n=>Math.pow(2,n))}function yc(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 N=[],E=[],A=[],U=t.matchUpType??d?.matchUpType,C=e+1,P=e+I,D=`${C}-${P}`,M=s?.[c],b=n&&`${n} `||"",v=s?.[D]??o?.[D],O=t.structureName||v?.name||M?.name&&(r?`${b}${M?.name}`:M.name)||`${b}${D}`,w=v?.abbreviation??M?.abbreviation,F=t.structureId??M?.structureId??T?.pop(),L={idPrefix:h&&`${h}-${O}-RP`,finishingPositionOffset:e,matchUpType:U,drawSize:I,isMock:S,uuids:T},{matchUps:x}=l?ri(L):hn(L),B=on({structureAbbreviation:w,stageSequence:a,structureName:O,matchUpType:U,roundOffset:m,structureId:F,matchUps:x,stage:g});N.push(...x),E.push(B);let H=Math.ceil(Math.log(I)/Math.log(2)),W=p?Math.min(p-m,H):!i||C<i?H:0;return I>2&&Z(1,W+1).forEach(Y=>V(Y)),{structureId:B.structureId,matchUps:N,structureName:O,structures:E,links:A,...R};function V(Y){let $=I/Math.pow(2,Y);if($<2)return;let k=I/Math.pow(2,Y)+e;if(i&&k+1>i)return;let{structures:K,structureId:z,matchUps:q,links:et}=yc({finishingPositionOffset:k,exitProfile:`${c}-${Y}`,roundOffset:m+Y,stageSequence:a+1,drawSize:$,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(B.structureId&&z){let Q={linkType:Qn,source:{roundNumber:Y,structureId:B.structureId},target:{roundNumber:1,feedProfile:pn,structureId:z}};et&&B&&et.push(Q),et?.length&&A.push(...et)}return K?.length&&E.push(...K),q?.length&&N.push(...q),{structureId:z,childLinks:et,structures:E}}}function ud({drawDefinition:t,matchUpsMap:e,structureId:r}){let n=st({drawDefinition:t,structureId:r});if(n.error)return _({result:n});let{matchUps:o}=At({structure:n.structure,matchUpsMap:e});return{...qe({matchUps:o}),matchUps:o,matchUpsMap:e}}function XU({finishingPositions:t,drawDefinition:e,structureId:r}){let{roundProfile:n}=ud({drawDefinition:e,structureId:r});return(n&&Object.keys(n))?.reduce((i,s)=>(gv(n?.[s]).forEach(c=>{t.forEach(u=>{TG({position:u,rangeDefinition:c})&&(i[u]={roundNumber:s})})}),i),{})}function TG({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 gv(t){return[pt(t?.finishingPositionRange?.loser||[]),pt(t?.finishingPositionRange?.winner||[])]}function Iv(t){return gv(t).map(e=>Z(e[0],e[1]&&e[1]+1||e[0]+1))}function Ac({drawDefinition:t,structureIds:e,matchUpsMap:r}){if(e&&!Array.isArray(e))return{error:G,context:{structureIds:e}};if(!t)return{error:X};e=e??(t.structures??[]).filter(a=>a.stage!==at).map(({structureId:a})=>a);let n=e.map(a=>{let{roundProfile:c}=ud({drawDefinition:t,matchUpsMap:r,structureId:a});return(c&&Object.values(c))?.map(Iv).flat()}).flat(),o=n.filter(a=>a?.length===1).sort(se).flat();return{positionsNotPlayedOff:pt(n.flat()).filter(a=>!o.includes(a)),positionsPlayedOff:o}}function sS({excludeRoundNumbers:t=[],playoffPositions:e=[],drawDefinition:r,structureId:n}){if(!r)return{error:X};if(!n)return{error:Sr};if(!e)return{error:rt,info:"missing playoffPositions"};let o=Ac({drawDefinition:r});if(o.error)return o;let i=o.positionsPlayedOff,s=e.filter(S=>!i.includes(S)),a=XU({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=XU({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(se),{roundProfile:f}=ud({drawDefinition:r,structureId:n}),g=l.map(S=>{let T=f?.[S].finishingPositionRange.loser,[y,N]=T??[0,0];return Z(y,(N||y)+1)}).flat().sort(se),{playoffRoundsRanges:I}=yG({playoffSourceRounds:l,roundProfile:f}),h=[...l,...d];return{playoffPositionsReturned:g,playedOffSourceRounds:d,playoffRoundsRanges:I,playoffSourceRounds:l,sourceRounds:h,roundProfile:f}}function yG({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 Su({drawDefinition:t,structureId:e}){if(!t)return{error:X};let{matchUps:r,matchUpsMap:n}=or({inContext:!0,drawDefinition:t}),{positionsNotPlayedOff:o,positionsPlayedOff:i}=Ac({drawDefinition:t,matchUpsMap:n}),{structures:s}=Gn({drawDefinition:t}),a=s.filter(u=>!e&&u.stage!==We||u.structureId===e),c={};for(let u of a){let p=u?.structureId,m=AG({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 AG({playoffPositions:t,drawDefinition:e,structure:r,matchUps:n}){let o=r?.structureId,{links:i}=Ws({drawDefinition:e,structureId:o});if(r.structureType===ke||r.structures){let l=Ct({structure:r})?.positionAssignments?.length,f=r.structures.length,g=(l??0)/f,I=i.source?.flatMap(({source:P})=>P?.finishingPositions||[])||[],h=Z(1,g+1).filter(P=>!I.includes(P)),S=n.find(P=>P.containerStructureId===o&&P.finishingPositionRange)?.finishingPositionRange?.winner||[0,1],T=i?.source.map(({target:P})=>P.structureId),{positionsPlayedOff:y=[],positionsNotPlayedOff:N=[]}=Ac({structureIds:T,drawDefinition:e}),E=[...y,...N],A=Z(S[0],S[1]+1).filter(P=>!E.includes(P)),U=Te(A,A.length/h.length),C=h.map((P,D)=>{let M=U[D],b=[Math.min(...M||[]),Math.max(...M||[])].join("-");return{finishingPosition:P,finishingPositions:M,finishingPositionRange:b}});return{positionsNotPlayedOff:A,playoffFinishingPositionRanges:C,finishingPositionsAvailable:h,finishingPositionsPlayedOff:I,positionsPlayedOff:y,groupCount:f,groupSize:g}}let s=i?.source?.filter(l=>l.linkCondition!==Xn).map(l=>l.source?.roundNumber)||[],a=i?.source?.filter(l=>l.linkCondition===Xn).map(l=>l.source?.roundNumber)||[],c=sS({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:y})=>y===I&&T===g),S=h.filter(({sides:T})=>T.find(y=>y.participantFed&&!y.participantId)).length;if(u&&S===h.length){u.push(l);let T=m?.[l]?.finishingPositionRange?.loser;if(T){let y=Math.min(...T),N=y+S,E=Z(y,N),A={finishingPositionRange:[y,N-1].join("-"),finishingPositions:E,roundNumber:l};p.push(A)}}}return u&&u.sort(se),p.sort((l,f)=>l.roundNumber-f.roundNumber),{playoffRounds:u,playoffRoundsRanges:p,error:d}}function hv({playoffGroups:t,drawDefinition:e,structureId:r}){if(!e)return{error:X};if(typeof r!="string"||!Array.isArray(t))return{error:G};let n=t.map(({finishingPositions:a})=>a).flat();return{positionRangeMap:Su({drawDefinition:e,structureId:r}).playoffFinishingPositionRanges?.filter(a=>n.includes(a.finishingPosition))?.reduce((a,c)=>(a[c.finishingPosition]=c,a),{})}}function aS(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?ri(l):hn(l),g=on({structureName:i||r?.["0"]?.name||$e(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}=hn({finishingPositionOffset:e+S,idPrefix:u&&`${u}-c`,drawSize:S,matchUpType:a,isMock:m}),y=$e(He),N=r?.["0-1"]?.name??t.consolationStructureName??(i?`${i} ${y}`:y),E=on({structureName:N,matchUps:T,structureId:d?.pop(),stage:He,stageSequence:1,matchUpType:a});I.push(E);let A={linkType:Qn,source:{roundNumber:1,structureId:g.structureId},target:{roundNumber:1,feedProfile:pn,structureId:E.structureId}};h.push(A)}return{...R,structures:I,links:h}}function cS({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?pn:mi,d=p-e<=2?p-e:(p-e-2)*2+2,l={linkType:Qn,source:{roundNumber:p,structureId:r.structureId},target:{feedProfile:m,roundNumber:d,structureId:t.structureId}},f=c[p-1];return f&&(l.target.groupedOrder=f),Pr()&&(l.source.structureName=r.structureName,l.target.structureName=t.structureName),p===2&&i&&(l.linkCondition=Xn,l.target.feedProfile=pn),a.includes(d)?l:void 0}).filter(Boolean)}function uS(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?ri(f):hn(f),h=t.structureName??o?.["0"]?.name??$e(tt),S=ls({structureId:u||l?.pop(),structureName:h,stageSequence:n,matchUpType:c,matchUps:g,stage:a}),T=[S],y=[];if(p>2){let A=[0,2].slice(0,p/16).map((U,C)=>{let P=C+1,{consolationStructure:D}=EG({idPrefix:m&&`${m}-c${C}`,structureId:l?.pop(),playoffStructureNameBase:e,playoffAttributes:o,structureNameMap:i,stageSequence:P,roundOffset:U,matchUpType:c,drawSize:p,isMock:d,index:C,uuids:l});T.push(D);let M=cS({consolationStructure:D,roundsCount:2,mainStructure:S,roundOffset:U});return{consolationStructure:D,links:M}}).map(U=>U.links).flat();if(y.push(...A),p>=4&&p<=16||p>32){let{matchUps:U}=hn({idPrefix:m&&`${m}-p3t4`,finishingPositionOffset:2,drawSize:2,matchUpType:c,isMock:d}),C=o?.["3-4"]?.name??$e(ue),P=i?.[C]||C,D=e?`${e} ${P}`:P,M=ls({structureId:l?.pop(),matchUps:U,stageSequence:2,stage:ue,structureName:D,matchUpType:c}),b={linkType:Qn,source:{roundNumber:I-1,structureId:S.structureId},target:{structureId:M.structureId,feedProfile:pn,roundNumber:1}};T.push(M),y.push(b)}}return{structures:T,links:y,...R}}function EG({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}=ri({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||`${$e(He)} ${p+1}`,h=n?.[I]||I,S=t?`${t} ${h}`:h;return{consolationStructure:ls({matchUps:l,stage:He,structureName:S,stageSequence:e,matchUpType:i,structureId:s}),consolationRoundsCount:f}}function Ec(t){let{finishingPositionOffset:e,stageSequence:r=1,playoffAttributes:n,feedsFromFinal:o,staggeredEntry:i,structureName:s,stage:a=tt,structureId:c,matchUpType:u,skipRounds:p,feedRounds:m,idPrefix:d,drawSize:l,isMock:f,uuids:g,fmlc:I}=t,h=t.feedPolicy||t.policyDefinitions?.[rc]||t.appliedPolicies?.[rc],S={finishingPositionOffset:e,matchUpType:u,skipRounds:p,drawSize:l,idPrefix:d,isMock:f,uuids:g},{matchUps:T}=i?ri(S):hn(S),y=on({structureName:s||n?.["0"]?.name||$e(tt),structureId:c||g?.pop(),stageSequence:r,matchUpType:u,matchUps:T,stage:a}),N=[y],E=[],A=l/2,{matchUps:U,roundsCount:C}=ri({finishingPositionOffset:A,idPrefix:d&&`${d}-c`,isConsolation:!0,feedsFromFinal:o,baseDrawSize:A,matchUpType:u,feedRounds:m,skipRounds:p,isMock:f,uuids:g,fmlc:I});if(l>2){let P=n?.["0-1"]?.name??$e(He),D=t.playoffStructureNameBase?`${t.playoffStructureNameBase} ${P}`:P,M=on({matchUps:U,structureId:g?.pop(),stage:He,stageSequence:1,structureName:D,matchUpType:u});N.push(M);let b=cS({consolationStructure:M,mainStructure:y,roundsCount:C,feedPolicy:h,fmlc:I});E.push(...b)}return{...R,structures:N,links:E}}function mS({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?.[rc];let f="processPlayoffGroups",g=0,I=[],h=[],S=[],{error:T,positionRangeMap:y}=hv({structureId:n,drawDefinition:s,playoffGroups:a});if(T)return _({result:{error:T},stack:f});if(!(!y||a?.every(E=>{let{finishingPositions:A=[]}=E;if(!A.length)return!1;let U=[...A].sort(se).map((C,P)=>(A[P+1]||C)-C).every(C=>C<2);return(!t||U)&&A.every(C=>y[C])})))return _({context:{validFinishingPositions:Object.values(y)},result:{error:G},stack:f});for(let E of a){let A=E.finishingPositions,U=y&&A.map(F=>y[F]?.finishingPositions).flat(),C=p*A.length,P=Ki(C),D=P===2&&mo||E.drawType||mo;U&&(g=Math.min(...U)-1);let M=U&&`${Math.min(...U)}-${Math.max(...U)}`,b=E.structureName||M&&E.playoffAttributes?.[M]?.name||E.playoffAttributes?.["0"]?.name,O={...{addNameBaseToAttributeName:E.addNameBaseToAttributeName,playoffStructureNameBase:E.playoffStructureNameBase,finishingPositionNaming:E.finishingPositionNaming,finishingPositionLimit:E.finishingPositionLimit,structureId:E.structureId??l?.pop(),playoffAttributes:E.playoffAttributes,structureNameMap:E.structureNameMap,sequenceLimit:E.sequenceLimit,structureName:b},idPrefix:m&&`${m}-po`,appliedPolicies:o,finishingPositionOffset:g,stage:ue,stageSequence:i,matchUpType:c,drawSize:P,isMock:d,uuids:l},w=({playoffStructures:F,playoffLinks:L})=>{let[x]=F,B=pS({playoffStructureId:x.structureId,finishingPositions:A,sourceStructureId:n});S.push(B),S.push(...L),h.push(...F),I.push({structureId:x.structureId,finishingPositions:A}),g+=C};if(D===mo){let{matchUps:F}=hn({finishingPositionLimit:g+C,idPrefix:m&&`${m}-po`,finishingPositionOffset:g,matchUpType:c,drawSize:P,isMock:d,uuids:l}),L=on({structureId:E.structureId??l?.pop(),matchUpFormat:e,stage:ue,structureName:b,stageSequence:i,matchUps:F});h.push(L);let x=pS({playoffStructureId:L.structureId,finishingPositions:A,sourceStructureId:n});S.push(x),g+=C,I.push({structureId:L.structureId,finishingPositions:A})}else if([Jc,Zc,ue].includes(D)){let F={playoffAttributes:E.playoffAttributes??r,playoffStructureNameBase:E.playoffStructureNameBase,structureId:E.structureId??l?.pop(),structureName:E.structureName,idPrefix:m&&`${m}-po`,addNameBaseToAttributeName:!0,finishingPositionOffset:g,stage:ue,roundOffset:0,stageSequence:i,drawSize:P,isMock:d,uuids:l};D===Jc?Object.assign(F,{playoffAttributes:E?.playoffAttributes??r??mf,roundOffsetLimit:3}):D===Zc&&Object.assign(F,{playoffAttributes:E?.playoffAttributes??r??df,roundOffsetLimit:2});let L=yc(F);if(L.error)return L;if(L.links?.length&&S.push(...L.links),L.structures?.length&&h.push(...L.structures),h.sort(di),L.structureId){let x=pS({playoffStructureId:L.structureId,finishingPositions:A,sourceStructureId:n});S.push(x),I.push({structureId:L.structureId,finishingPositions:A})}g+=C}else if([eu,mp,Om,vm,bm,_m].includes(D)){let F=[l?.pop(),l?.pop()],L={playoffStructureNameBase:E.playoffStructureNameBase,structureId:E.structureId??l?.pop(),playoffAttributes:E.playoffAttributes,idPrefix:m&&`${m}-po`,finishingPositionOffset:g,uuids:F,stage:ue,structureName:b,matchUpType:c,feedPolicy:u,drawSize:P,isMock:d},x={[eu]:{fmlc:!0,feedRounds:1},[_m]:{feedRounds:1},[Om]:{feedsFromFinal:3},[vm]:{feedsFromFinal:2},[bm]:{feedsFromFinal:1}};Object.assign(L,x[D]||{});let{structures:B,links:H}=Ec(L),[W]=B,V=pS({playoffStructureId:W.structureId,finishingPositions:A,sourceStructureId:n});S.push(V),S.push(...H),h.push(...B),I.push({structureId:W.structureId,finishingPositions:A}),g+=C}else if([fn].includes(D)){let{structures:F,links:L}=Ma({...O,structureOptions:E.structureOptions||{groupSize:4}});w({playoffStructures:F,playoffLinks:L})}else if([pp].includes(D)){let{structures:F,links:L}=aS(O);w({playoffStructures:F,playoffLinks:L})}else if([MR].includes(D)){let{structures:F,links:L}=uS(O);w({playoffStructures:F,playoffLinks:L})}else if([Xr].includes(D)){let F=on({structureId:E.structureId??l?.pop(),structureName:E.structureName,finishingPosition:Gm,stage:ue,stageSequence:i,matchUps:[]});w({playoffStructures:[F],playoffLinks:[]})}}return{finishingPositionTargets:I,positionRangeMap:y,structures:h,links:S}}function pS({playoffStructureId:t,finishingPositions:e,sourceStructureId:r}){return{linkType:zn,source:{structureId:r,finishingPositions:e},target:{structureId:t,feedProfile:tn,roundNumber:1}}}function Ra({matchUp:t,tieFormat:e,isMock:r,uuids:n}){let{collectionDefinitions:o}=e??{};return{tieMatchUps:(o??[]).map(s=>Tu({matchUp:t,collectionDefinition:s,uuids:n,isMock:r})).filter(Boolean).flat()}}function Tu({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:Qt,collectionPosition:l,collectionId:c,processCodes:u,matchUpType:a,isMock:o}})}function Sv(t){let e="generateAndPopulateRRplayoffStructures";if(!t.playoffGroups)return _({result:{error:rt},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}=mS({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}=ne({inContext:!0,drawDefinition:i}),S=p.map(({structureId:U})=>U),T=I?.filter(({structureId:U})=>S.includes(U)).map(fe),y=h?.drawMatchUps?.filter(({matchUpId:U})=>T?.includes(U));if(y?.length){let U=Ye({drawDefinition:i,event:u})?.tieFormat;U&&y.forEach(C=>{let{tieMatchUps:P}=Ra({isMock:t.isMock,tieFormat:U,matchUp:C});Object.assign(C,{tieMatchUps:P,matchUpType:gn})})}let{positionAssignments:N}=Ct({structureId:r,drawDefinition:i}),E={};N?.forEach(U=>{let D=dt({element:U,name:qo})?.extension?.value?.groupOrder;D&&(E[D]||(E[D]=[]),E[D].push(U.participantId))});let A=Tc({provisionalPositioning:t.provisionalPositioning,structureId:r,applyPositioning:!0,event:t.event,tournamentRecord:o,drawDefinition:i});return A.error&&A.error?.code!==hl.code?_({result:A,stack:e}):{structures:p,links:m,positionsPlayedOff:g,drawDefinition:i,...R}}var Sn="SET3-S:6/TB7",UG="SET3-S:6NOAD",JU="SET3-S:6/TB7-F:TB10",PG="SET3-S:4/TB7",DG="SET3-S:4/TB5@3",NG="SET1-S:T20",MG="SET1-S:8/TB7",CG="SET1-S:8/TB7@7",Tv={FORMAT_STANDARD:Sn,FORMAT_STANDARD_NOAD:UG,FORMAT_ATP_DOUBLES:JU,FORMAT_SHORT_SETS:PG,FORMAT_FAST4:DG,FORMAT_PRO_SET:MG,FORMAT_COLLEGE_PRO_SET:CG,TIMED20:NG};function ag({winningSide:t,matchUpFormat:e=Sn,matchUpStatus:r,tallyPolicy:n,score:o}){let i=[0,0],s=o?.sets,a=typeof t=="number"&&t-1,c=rr(e),u=ZU(c?.bestOf??1);if(typeof a=="number"&&(r===bt&&n?.setsCreditForDefaults||r===vt&&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===er&&(+i[1-a]===u&&(i[1-a]-=1),n?.setsCreditForRetirements&&(i[a]=u)),i}function dS({matchUpFormat:t=Sn,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=rr(t),c=a?.bestOf??1,u=ZU(c),p=a?.setFormat?.tiebreakAt||0,m=[[],[]];if(typeof s=="number"&&(r===bt&&n?.gamesCreditForDefaults||r===vt&&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;yv(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===er&&typeof s=="number"){let d=i.length>u&&a?.finalSetFormat?"finalSetFormat":"setFormat",l=a?.[d];if(yv(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=ag({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 lS({matchUpFormat:t,score:e}){let r=t?rr(t):void 0,n=r?.bestOf??1,o=ZU(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(Av(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 ZU(t){return t&&Math.ceil(t/2)||1}function Av(t){return t==="P"}function yv(t){return!Av(t)}function Ev({participantResults:t,matchUpFormat:e,tallyPolicy:r,perPlayer:n,totalSets:o}){let i=e&&rr(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,y=S+T,N=Math.round(S/y*1e3)/1e3;(N===1/0||isNaN(N))&&(N=S);let E=t[u].gamesWon||0,A=t[u].gamesLost||0,U=(n||0)*(a||0)*(c||0),C=Math.max(U,E+A),P=Math.round(E/C*1e3)/1e3;(P===1/0||isNaN(P))&&(P=0);let D=Math.round(t[u].pointsWon/t[u].pointsLost*1e3)/1e3;(D===1/0||isNaN(D))&&(D=0),t[u].setsWon=p,t[u].setsLost=m,t[u].setsPct=l,t[u].tieMatchUpsWon=f,t[u].tieMatchUpsPct=h,t[u].matchUpsPct=N,t[u].gamesWon=E,t[u].gamesLost=A,t[u].gamesPct=P,t[u].pointsPct=D,t[u].result=`${t[u].matchUpsWon}/${t[u].matchUpsLost}`})}function yu({value:t,sourceRange:e,targetRange:r}){let n=Math.min(...e),o=Math.max(...e),i=Math.min(...r),s=Math.max(...r);return(t-n)*(s-i)/(o-n)+i}var To="ELO",tP="NTRP",RG="TRN",eP="UTR",cg="WTN",Uv={ELO:To,NTRP:tP,TRN:RG,UTR:eP,WTN:cg};var bG={[To]:{defaultInitialization:1500,decimalsCount:0,range:[0,3e3],ascending:!0},[tP]:{accessors:["ntrpRating","dntrpRatingHundredths"],attributes:{ustaRatingType:""},accessor:"dntrpRatingHundredths",defaultInitialization:3,decimalsCount:1,ascending:!0,range:[1,7]},[eP]:{defaultInitialization:6,accessors:["utrRating"],accessor:"utrRating",decimalsCount:2,ascending:!0,range:[1,16]},[cg]:{attributes:{confidence:{generator:!0,range:[60,100]}},accessors:["wtnRating","confidence"],defaultInitialization:23,accessor:"wtnRating",ascending:!1,decimalsCount:2,range:[40,1]}},Ke=bG;function Pv({sourceRatingType:t,sourceRating:e}){let r=Ke[t].range,n=r[0]>r[1],o=Ke[To].range;return yu({value:n?r[0]-e:e,sourceRange:r,targetRange:o})}function Dv({targetRatingType:t,sourceRating:e}){let r=Ke[t].decimalsCount||0,n=Ke[t].range,o=n[0]>n[1],i=Math.max(...n),s=Ke[To].range,a=yu({targetRange:n,sourceRange:s,value:e}),c=parseFloat(a.toFixed(r));return o?i-c:c}function rP(t){let e=ut(t,[{ratings:!0,[dn]:Yn}]);if(e.error)return e;let r=t.matchUpType&&[Kt,wt].includes(t.matchUpType)?t.matchUpType:Kt,n=Object.keys(Ke),o=t.targetRatingType&&n.includes(t.targetRatingType)?t.targetRatingType:To,i=t.ratings[r]?t.ratings[r].reduce((d,l)=>d.includes(l.scaleName)?d:d.concat(l.scaleName),[]):[];if(!i)return{error:Le};let s=t.ratings[r]?.find(d=>d.scaleName===o)??t.ratings[r][0];if(i[0]===o)return s;let a=s.scaleName,c=Ke[s.scaleName].accessor,u=c?s.scaleValue[c]:s.scaleValue,p=Pv({sourceRatingType:a,sourceRating:u});return{convertedRating:Dv({targetRatingType:o,sourceRating:p}),sourceRating:u}}function Au({participantIds:t,pressureRating:e,matchUpFormat:r,tallyPolicy:n,perPlayer:o,matchUps:i}){let s={},a=n?.excludeMatchUpStatuses||[],c=i?.filter(m=>(m.tieMatchUps||!a.includes(m.matchUpStatus))&&(!t?.length||jt(t,[pd(m,0),pd(m,1)]).length===2)),p=c?.flatMap(({score:m,tieMatchUps:d})=>d?d.filter(({matchUpStatus:l})=>!a.includes(l)).flatMap(({score:l})=>l?.sets?.length??0):m?.sets?.length??0)?.reduce((m,d)=>m+d,0);for(let m of c??[]){let{matchUpStatus:d,tieMatchUps:l,tieFormat:f,score:g,winningSide:I,sides:h}=m,S=f&&m._disableAutoCalc&&f.collectionDefinitions.every(({scoreValue:A})=>A),T=I&&vG(m),y=I&&OG(m);if(!T&&!y)if(d&&ae.includes(d)){let A=pd(m,0),U=pd(m,1);A&&(Uc(s,A),s[A].matchUpsCancelled+=1),U&&(Uc(s,U),s[U].matchUpsCancelled+=1)}else if(l?.length){o=0;for(let A of l){if(A.winningSide){let U=h?.find(({sideNumber:P})=>P===A.winningSide)?.participantId,C=h?.find(({sideNumber:P})=>P===A.winningSide)?.participantId;U&&C&&(Uc(s,U),Uc(s,C),s[U].tieMatchUpsWon+=1,s[C].tieMatchUpsLost+=1,ie(Kt)(A.matchUpType)?(s[U].tieSinglesWon+=1,s[C].tieSinglesLost+=1):ie(wt)(A.matchUpType)&&(s[U].tieDoublesWon+=1,s[C].tieDoublesLost+=1))}Nv({score:A.score,manualGamesOverride:S,participantResults:s,sides:h})}}else Nv({manualGamesOverride:S,participantResults:s,score:g,sides:h});else if(Uc(s,T),Uc(s,y),l?.length){o=0;for(let A of l){let{matchUpType:U}=A,C=ie(wt)(U),P=ie(Kt)(U);A.winningSide&&(A.winningSide===I?(T&&(s[T].tieMatchUpsWon+=1,P&&(s[T].tieSinglesWon+=1),C&&(s[T].tieDoublesWon+=1)),y&&(s[y].tieMatchUpsLost+=1,P&&(s[y].tieSinglesLost+=1),C&&(s[y].tieDoublesLost+=1))):A.winningSide!==I&&(y&&(s[y].tieMatchUpsWon+=1,P&&(s[y].tieSinglesWon+=1),C&&(s[y].tieDoublesWon+=1)),T&&(s[T].tieMatchUpsLost+=1,P&&(s[T].tieSinglesLost+=1),C&&(s[T].tieDoublesLost+=1)))),Mv({matchUpFormat:A.matchUpFormat,matchUpStatus:A.matchUpStatus,score:A.score,sides:A.sides,winningParticipantId:T,losingParticipantId:y,manualGamesOverride:S,participantResults:s,isTieMatchUp:!0,pressureRating:e,tallyPolicy:n,winningSide:I})}Cv({winningParticipantId:T,losingParticipantId:y,participantResults:s,matchUpStatus:d})}else Mv({matchUpFormat:m.matchUpFormat??r,isTieMatchUp:void 0,winningParticipantId:T,manualGamesOverride:S,losingParticipantId:y,participantResults:s,pressureRating:e,matchUpStatus:d,tallyPolicy:n,winningSide:I,score:g,sides:h});let N=g?.sets?.reduce((A,U)=>A+(U?.side1Score??0),0),E=g?.sets?.reduce((A,U)=>A+(U.side2Score??0),0);if(S){let A=h?.find(({sideNumber:C})=>C===1)?.participantId,U=h?.find(({sideNumber:C})=>C===2)?.participantId;Uc(s,A),Uc(s,U),A&&(s[A].gamesWon+=N,s[A].gamesLost+=E),U&&(s[U].gamesWon+=E,s[U].gamesLost+=N)}}return Ev({participantResults:s,matchUpFormat:r,tallyPolicy:n,perPlayer:o,totalSets:p}),{participantResults:s}}function vG(t){let e=t.winningSide-1;return pd(t,e)}function OG(t){let e=1-(t.winningSide-1);return pd(t,e)}function pd(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 Uc(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,pressureScores:[],ratingVariation:[],retirements:0,setsLost:0,setsWon:0,tieSinglesWon:0,tieSinglesLost:0,tieDoublesWon:0,tieDoublesLost:0,tieMatchUpsLost:0,tieMatchUpsWon:0,victories:[],walkovers:0})}function Nv({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&&(Uc(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 Mv({winningParticipantId:t,manualGamesOverride:e,losingParticipantId:r,participantResults:n,pressureRating:o,matchUpFormat:i,matchUpStatus:s,isTieMatchUp:a,tallyPolicy:c,winningSide:u,score:p,sides:m}){let d=u&&u-1,l=1-d;if(o){let h=D=>parseFloat(Number(Math.round(D*1e3)/1e3).toFixed(2)),S=p?.sets?.reduce((D,M)=>D+(M?.side1Score??0),0),T=p?.sets?.reduce((D,M)=>D+(M.side2Score??0),0),y=m.find(({sideNumber:D})=>D===1),N=m.find(({sideNumber:D})=>D===2),{convertedRating:E}=rP({ratings:y?.participant?.ratings}),{convertedRating:A}=rP({ratings:N?.participant?.ratings}),U=S*A,C=T*E;n[y?.participantId].pressureScores.push(h(U/(U+C))),n[N?.participantId].pressureScores.push(h(C/(U+C)));let P=Math.max(...Ke[To].range);n[y?.participantId].ratingVariation.push(h((E-A)/P)),n[N?.participantId].ratingVariation.push(h((A-E)/P))}a||Cv({winningParticipantId:t,losingParticipantId:r,participantResults:n,matchUpStatus:s});let f=ag({matchUpStatus:s,matchUpFormat:i,tallyPolicy:c,winningSide:u,score:p}),g=dS({matchUpStatus:s,matchUpFormat:i,tallyPolicy:c,winningSide:u,score:p}),{pointsTally:I}=lS({score:p,matchUpFormat:i});t&&(n[t].setsWon+=f[d],n[t].setsLost+=f[l],e||(n[t].gamesWon+=g[d],n[t].gamesLost+=g[l]),n[t].pointsWon+=I[d],n[t].pointsLost+=I[l]),r&&(n[r].setsWon+=f[l],n[r].setsLost+=f[d],e||(n[r].gamesWon+=g[l],n[r].gamesLost+=g[d]),n[r].pointsWon+=I[l],n[r].pointsLost+=I[d])}function Cv({winningParticipantId:t,losingParticipantId:e,participantResults:r,matchUpStatus:n}){e&&(n===vt&&(r[e].walkovers+=1),n===bt&&(r[e].defaults+=1),n===er&&(r[e].retirements+=1),[bt,er,vt].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 Rv({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
4
  `)}function nP({participantResults:t,participantIds:e,attribute:r}){return oP({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 oP(t){return(t.participantIds||Object.keys(t.participantResults)).reduce((r,n,o)=>(r.push({participantId:n,i:o,results:t.participantResults[n]}),r),[])}var _G=[{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}],iP={matchUpsPct:20,tieMatchUpsPct:16,setsPct:12,gamesPct:8,pointsPct:4};function sP(t){let{requireCompletion:e=!0,participantResults:r,subOrderMap:n,tallyPolicy:o}=t,i=[];if(e&&!xG(t))return{};let s=["tieMatchUpsWon","tieSinglesWon","tieDoublesWon","matchUpsWon","pointsWon","gamesWon","setsWon","gamesPct","setsPct","pointsPct","matchUpsPct"].includes(o?.groupOrderKey)?o.groupOrderKey:"matchUpsWon",a=nP({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=bv({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=fr(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(iP).filter(h=>o.GEMscore.includes(h)):Object.keys(iP)).map(h=>(f[h]||0)*Math.pow(10,iP[h].toFixed(3))).reduce((h,S)=>h+S,0)}}function xG({participantResults:t,participantsCount:e}){let n=oP({participantResults:t}).filter(o=>e-1===o.results.matchUpsWon+o.results.matchUpsLost+o.results.matchUpsCancelled);return e===n.length}function wG({disableHeadToHead:t,participantIds:e,matchUpFormat:r,tallyPolicy:n,attribute:o,idsFilter:i,matchUps:s,reversed:a}){let{participantResults:c}=Au({participantIds:i&&e,matchUpFormat:r,tallyPolicy:n,matchUps:s}),u=nP({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=bv({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 bv({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=LG({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||_G).filter(m=>{let d=!(Jt(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=wG({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 LG({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 ba({policyDefinitions:t,generateReport:e,pressureRating:r,matchUpFormat:n,matchUps:o=[],subOrderMap:i,perPlayer:s}){if(!o?.length||!Nr(o))return{error:An};let a=pt(o.map(({structureId:y})=>y));if(a.length!==1)return _({result:{error:G,info:"Maximum one structureId"},stack:"tallyParticipantResults",context:{structureIds:a}});let c=o.filter(y=>y&&y.matchUpStatus!==Nt),u=c.length&&pt(c.map(({drawPositions:y})=>y).flat()).length,p=c.filter(y=>as({matchUp:y})).length===c.length;p||(s=0);let m=o.every(({matchUpType:y,tieMatchUps:N})=>y===Bt&&N?.every(E=>as({matchUp:E}))),d=t?.[nf],l=o.filter(y=>as({matchUp:y})||y.matchUpType===Bt),{participantResults:f}=Au({matchUps:l,pressureRating:r,matchUpFormat:n,tallyPolicy:d,perPlayer:s}),g,I,{groupOrder:h,report:S}=sP({matchUps:l,participantResults:f,participantsCount:u,matchUpFormat:n,tallyPolicy:d,subOrderMap:i});if(p&&h)g=S,I=h,h.forEach(y=>{let{participantId:N,groupOrder:E,rankOrder:A,subOrder:U,ties:C,GEMscore:P}=y,D=f[N];Object.assign(D,{groupOrder:E,rankOrder:A,GEMscore:P,subOrder:U,ties:C})});else{let{groupOrder:y,report:N}=sP({requireCompletion:!1,participantResults:f,participantsCount:u,matchUpFormat:n,tallyPolicy:d,subOrderMap:i,matchUps:o});g=N,I=y,y&&y.forEach(E=>{let{participantId:A,groupOrder:U,GEMscore:C}=E,P=f[A];Object.assign(P,{provisionalOrder:U,GEMscore:C})})}let T={completedTieMatchUps:m,readableReport:"",participantResults:f,bracketComplete:p,order:[],report:g};if((p||m)&&(T.order=I),e||Pr({tally:!0})){let y=Rv({matchUps:o,report:g,order:I});Pr({tally:!0})&&console.log(y),T.readableReport=y}return T}function fS({positionAssignments:t}){let e=(t||[]).filter(Mr(jn)).map(i=>{let{extension:s}=dt({element:i,name:oc}),a=ct(s?.value),c=!isNaN(a)&&a;return c&&{participantId:i.participantId,subOrder:c}}).filter(Boolean),r=e.map(({subOrder:i})=>i),n=fr(r);return{subOrderMap:Object.assign({},...e.filter(({subOrder:i})=>n[i]===1).map(({participantId:i,subOrder:s})=>({[i]:s})))}}function md({positionAssignments:t,tournamentRecord:e,drawDefinition:r,matchUpFormat:n,matchUps:o,event:i}){if(!Nr(o))return{error:G};if(!t)return{error:G};let{policyDefinitions:s}=Co({policyTypes:[nf],tournamentRecord:e,drawDefinition:r,event:i}),{subOrderMap:a}=fS({positionAssignments:t}),c=o.length?ba({policyDefinitions:s,matchUpFormat:n,subOrderMap:a,matchUps:o}):void 0;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:qo};yt({element:l,extension:g}),u[f].ties||sr({element:l,name:oc})}else sr({element:l,name:qo}),sr({element:l,name:oc})}),Ot({drawDefinition:r}),{...R,participantResults:u,bracketComplete:p,report:m}}function gS({matchUps:t,matchUpId:e}){return{matchUp:(t||[]).find(n=>n.matchUpId===e)}}function Lt({tournamentParticipants:t,afterRecoveryTimes:e,contextContent:r,contextProfile:n,drawDefinition:o,matchUpsMap:i,matchUpId:s,inContext:a,context:c,event:u}){if(!o)return{error:X};if(!s)return{error:Be};if(typeof s!="string")return{error:G};let{structures:p=[]}=Gn({drawDefinition:o});n&&!r&&(r=Bn({contextProfile:n,drawDefinition:o}));for(let m of p){let{matchUps:d}=At({tournamentParticipants:t,afterRecoveryTimes:e,contextContent:r,drawDefinition:o,contextProfile:n,matchUpsMap:i,inContext:a,structure:m,context:c,event:u}),{matchUp:l}=gS({matchUps:d,matchUpId:s});if(l)return{matchUp:l,structure:m}}return{error:_e}}function Mp(t){return typeof t!="object"?{error:rt}: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:rt}}function aP(t){return typeof t!="object"?{error:rt}:typeof t.element!="object"?{error:G}:(t.element.notes&&delete t.element.notes,{...R})}var Eu={matchUpStatus:Qt,matchUpStatusCodes:[],score:{scoreStringSide1:"",scoreStringSide2:"",sets:void 0},matchUpFormat:void 0,winningSide:void 0};function vn(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:ht({policyTypes:[Ln],tournamentRecord:a,drawDefinition:c,structure:o,event:l})?.appliedPolicies,S=n.matchUpType===Bt;if(S&&c){if(d&&n.matchUpId!==d){let C=Lt({drawDefinition:c,matchUpId:d,event:l});if(!C.matchUp)return{error:_e};({matchUp:n,structure:o}=C)}}else n.matchUpId!==d&&console.log("!!!!!");u&&[vt,ge].includes(u)||p?Object.assign(n,{...Eu}):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}=Lt({drawDefinition:c,matchUpId:d,event:l})),u&&!n.winningSide&&Ie(n)&&!ae.includes(u)&&![ic,Zi].includes(u)&&(n.matchUpStatus=Cn);let y;if((T&&n?.processCodes?.length||u===bt)&&(y=h?.[Ln]?.processCodes?.incompleteAssignmentsOnDefault),!n.collectionId){let C=o?.structureType===ke,P=gr({structure:o});if(Km({drawDefinition:c,structure:o})||P||C){let D=v=>{r=S?"SET1-S:T100":r??n.matchUpFormat??v?.matchUpFormat??c?.matchUpFormat??l?.matchUpFormat;let O=S?{matchUpTypes:[Bt]}:void 0,{matchUps:w}=At({afterRecoveryTimes:!1,tournamentRecord:a,inContext:!0,matchUpFilters:O,drawDefinition:c,structure:v,event:l});return P&&(v.positionAssignments=pt(w.flatMap(F=>(F.sides??[]).map(L=>L.participantId)).filter(Boolean)).map(F=>({participantId:F}))),md({positionAssignments:v.positionAssignments,tournamentRecord:a,drawDefinition:c,matchUpFormat:r,matchUps:w,event:l})},M=C&&o.structures.find(v=>v?.matchUps.find(O=>O.matchUpId===d)),b=D(M||o);if(b.error)return _({result:b,stack:e})}}if(f){let C=Mp({element:n,notes:f});if(C.error)return _({result:C,stack:e})}let N=a?.tournamentId,E=vr().topics.includes(lp),A=(E||y)&&ye({drawDefinition:c}),U=A&&ne({matchUpFilters:{matchUpIds:[d]},nextMatchUps:!0,tournamentRecord:a,inContext:!0,drawDefinition:c,matchUpsMap:A}).matchUps?.[0];if(E&&U&&vR({tournamentId:N,inContextMatchUp:U}),Array.isArray(y)&&U&&!U.sides?.every(({participantId:C})=>C))if(u===bt)n.processCodes=pt([...n.processCodes??[],...y]);else for(let C of y||[]){let P=C&&n?.processCodes?.lastIndexOf(C);n?.processCodes?.splice(P,1)}return It({eventId:l?.eventId,context:e,drawDefinition:c,tournamentId:N,matchUp:n}),{...R}}function dd(t){let{dualWinningSideChange:e,matchUpStatusCodes:r,matchUpStatus:n,structure:o,matchUp:i}=t,s=Pa({matchUpStatus:n})||[Kn,Ar].includes(n)&&e,a="attemptToModifyScore",c=!!i.collectionId,u=gr({structure:o});if(!(c||u||FG({structure:o,matchUp:i})))return{error:El};let m=[vt].includes(n),d=vn({...t,matchUpStatusCodes:s&&r||[],matchUpStatus:s&&n||me,context:a,removeScore:m});return _({result:d,stack:a})}function FG({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 IS({collectionGroups:t=[]}){let e=Object.assign({},...t.filter(n=>ft(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 vv({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=>ae.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)}),ft(d)?i.forEach(S=>{S.winningSide&&(s[S.winningSide-1]+=d)}):ft(g)?i.forEach(S=>{S.score?.sets?.forEach(T=>{T.winningSide&&(s[T.winningSide-1]+=g)})}):ft(f)?i.forEach(S=>{S.score?.sets?.forEach(T=>{let{side1TiebreakScore:y=0,side2TiebreakScore:N=0,side1Score:E=0,side2Score:A=0}=T;(S.matchUpStatus===me||S.winningSide||T.winningSide)&&(E||A?(s[0]+=E,s[1]+=A):(y||N)&&T.winningSide&&(s[T.winningSide-1]+=1))})}):Array.isArray(u)&&i.forEach(S=>{if(S.winningSide){let T=S.collectionPosition,y=GG({collectionDefinition:t,collectionPosition:T});ft(y)&&(s[S.winningSide-1]+=y)}}),ft(m)){let S;if(l?.aggregateValue)c&&(ft(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,y,N)=>y>=l.valueGoal?N+1:T,0);else{let T=Math.floor(t.matchUpCount/2)+1;S=h.reduce((y,N,E)=>N>=T?E+1:y,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 GG({collectionDefinition:t,collectionPosition:e}){return(t.collectionValueProfiles||[])?.find(o=>o.collectionPosition===e)?.matchUpValue}function hS({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!==pt(n).length?(r.push("collectionPositions are not unique"),{errors:r}):{...R}}var kG="MIXED events can not contain mixed singles or { gender: ANY } collections",VG="events with { gender: ANY } can not contain MIXED singles collections";function ld(t){let e="tieFormatGenderValidityCheck",{referenceGender:r,matchUpType:n,gender:o}=t;return r&&o&&[te,ce].includes(r)&&r!==o?_({result:{valid:!1,error:Gl},context:{gender:o},stack:e}):r===Ur&&(o===In||o===Ur&&n!==wt)?_({result:{error:Gl,valid:!1},info:kG,stack:e}):r===In&&o===Ur&&n!==wt?_({result:{error:Gl,valid:!1},info:VG,stack:e}):{valid:!0}}function Cp(t,e){if(Pt(t),(t?.bestOf||t?.exactly)&&t?.setFormat)return BG(t,e)}function ug(t){return!isNaN(Number(t))&&Number(t)}function xv(t){let e=`T${t.minutes}`;return t.based&&(e+=t.based),t.modifier&&(e+=`@${t.modifier}`),e}function BG(t,e){let r=ug(t.bestOf)||void 0,n=ug(t.exactly)||void 0,o=r||n;if(t.setFormat?.timed&&t.simplified&&o===1)return xv(t.setFormat);let i=o&&`${Qm}${o}`||"",s=Ov(t.setFormat,e),a=s&&`S:${s}`||"",c=Ov(t.finalSetFormat,e),u=o&&o>1&&c&&s!==c&&`F:${c}`||"";if(i&&s)return[i,a,u].filter(m=>m).join("-")}function Ov(t,e){if(typeof t=="object"&&Object.keys(t).length){if(t.timed)return xv(t);if(t.tiebreakSet)return _v(t.tiebreakSet);let r=ug(t.setTo);if(r){let n=t.NoAD&&Hf||"",o=_v(t.tiebreakFormat),i=o&&`/${o}`||"",s=ug(t.tiebreakAt),a=s&&(s!==r||e)&&`@${s}`||"";if(o!==!1)return`${r}${n}${i}${a}`}}}function _v(t){if(t){if(typeof t=="object"&&!t.tiebreakTo)return"";if(typeof t=="object"&&ug(t.tiebreakTo)){let e=`TB${t.tiebreakTo}${t.NoAD?Hf:""}`;return t.modifier&&(e+=`@${t.modifier}`),e}else return!1}}function Tr({matchUpFormat:t}){if(!Re(t)||t==="")return!1;let e=rr(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 Cp(e,!!(r&&o&&n===i||s&&c&&a===u))===t}var HG=(t,e)=>t.filter(Boolean).every(r=>typeof r===e),WG=t=>t.filter(Boolean).every(Jt);function Uu(t){let e=t.category;if(typeof e!="object")return{error:dm};let{ageCategoryCode:r,ageMaxDate:n,ageMinDate:o,ageMax:i,ageMin:s}=e,a=e.categoryName,c;if(!HG([r,n,o,a],"string")||!WG([i,s]))return{error:dm};let u=t.consideredDate??Ut(new Date().toLocaleDateString("sv"));if(!_r(u))return{error:ur};let[p]=u.split("-").slice(0,3).map(x=>parseInt(x)),m=rp(u,-1),[d,l]=m.split("-").slice(1,3).map(x=>parseInt(x)),f=`${qn(d)}-${qn(l)}`,g=rp(u,1),[I,h]=g.split("-").slice(1,3).map(x=>parseInt(x)),S=`${qn(I)}-${qn(h)}`,T=s&&rp(u,-1*365*s),y=i&&rp(u,-1*365*i),N=[],E=x=>!N.includes(x)&&N.push(x);r=r??a;let A=/^([UO]?)(\d{1,2})([UO]?)$/,U=/^C(\d{1,2})-(\d{1,2})$/,C=r?.includes("-"),P=C&&r?.match(U),D=r?.match(A),M=(x,B)=>`${x}-${B}`,b=x=>{let B=p-x,H=M(B,S);e.ageMinDate&&e.ageMinDate!==H&&E(`Invalid submitted ageMinDate: ${o}`),o=H,r&&(e.ageMax&&e.ageMax!==x-1&&(E(`Invalid submitted ageMax: ${i}`),y=void 0),i=x-1)},v=x=>{let B=p-x-1,H=M(B,S);e.ageMin&&e.ageMin>x&&E(`Invalid submitted ageMin: ${s}`),e.ageMax&&e.ageMax>x&&E(`Invalid submitted ageMax: ${i}`),e.ageMinDate&&e.ageMinDate!==H&&E(`Invalid submitted ageMinDate: ${o}`),o=H,r&&(e.ageMax&&e.ageMax!==x&&(E(`Invalid submitted ageMax: ${i}`),T=void 0),i=x)},O=x=>{let B=p-x,H=M(B,f);e.ageMaxDate&&e.ageMaxDate!==H&&E(`Invalid submitted ageMaxDate: ${n}`),n=H,r&&(e.ageMin&&e.ageMin!==x+1&&(E(`Invalid submitted ageMin: ${s}`),T=void 0),s=x+1)},w=x=>{let B=p-x-1,H=M(B,f);e.ageMaxDate&&e.ageMaxDate!==H&&E(`Invalid submitted ageMaxDate: ${n}`),n=H,r&&(e.ageMin&&e.ageMin!==x&&(E(`Invalid submitted ageMin: ${s}`),T=void 0),s=x)},F=x=>{let[B,H,W]=(x.match(A)||[]).slice(1),V=parseInt(H);B==="U"?(e.ageMaxDate&&e.ageMaxDate!==n&&E(`Invalid submitted ageMaxDate: ${e.ageMaxDate}`),b(V)):B==="O"&&O(V),W==="U"?(e.ageMaxDate&&e.ageMaxDate!==n&&E(`Invalid submitted ageMaxDate: ${e.ageMaxDate}`),v(V)):W==="O"&&w(V),n=n??T,o=o??y};if(P){if(n=void 0,o=void 0,i=void 0,s=void 0,e.ageMin){let H=p-e.ageMin;n=M(H,f)}if(e.ageMax){let H=p-e.ageMax-1;o=M(H,S)}let[x,B]=(r?.match(U)??[]).slice(1).map(H=>parseInt(H));x<=B?(s=x,i=B,c=!0):E(`Invalid combined age range ${r}`)}else C?r?.split("-").forEach(F):D?F(r):(s&&O(s),i&&v(i));i&&e.ageMin&&e.ageMin>i&&(E(`Invalid submitted ageMin: ${e.ageMin}`),s=void 0);let L=nt({consideredDate:u,combinedAge:c,ageMaxDate:n,ageMinDate:o,ageMax:i,ageMin:s});return N.length&&(L.errors=N),L}function fd({category:t}){if(!Pt(t))return{error:G};let e=Uu({category:t});if(e.error)return{error:e};let{ratingMax:r,ratingMin:n}=t;return r&&!Jt(r)?_({result:{error:G},context:{ratingMax:r}}):n&&!Jt(n)?_({result:{error:G},context:{ratingMin:n}}):{...e}}function gd({childCategory:t,withDetails:e,category:r}){let n=fd({category:r}),o=fd({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=nt({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 Pu({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}`),_({result:{errors:c,error:no},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:y}=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&&!du([Kt,wt],I)&&c.push(`matchUpType must be SINGLES or DOUBLES: ${I}`),[!!u?.length].concat([g,m,h,S].map(ft)).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 E=hS({collectionValueProfiles:u,matchUpCount:l});E.errors&&c.push(...E.errors)}if(p&&typeof p!="number"&&c.push(`collectionGroupNumber is not type number: ${m}`),f&&!Tr({matchUpFormat:f})&&c.push(`Invalid matchUpFormat: ${f}`),n){let E=ld({referenceGender:i,matchUpType:I,gender:y});if(E.error)return _({context:{referenceGender:i,gender:y},result:E,stack:a})}if(t&&o&&T){let E=gd({category:o,childCategory:T});if(!E.valid)return _({result:{error:dm},context:E,stack:a})}return c.length?_({result:{errors:c,error:oE},stack:a}):{valid:!0}}function ar(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"),_({result:{error:ai},context:{tieFormat:o,errors:a},stack:s});if(typeof o.winCriteria!="object")return a.push("tieFormat.winCriteria must be an object"),_({result:{error:ai},context:{tieFormat:o,errors:a},stack:s});if(!Array.isArray(o.collectionDefinitions))return a.push(Rn("tieFormat.collectionDefinitions")),_({result:{error:ai},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:y}=Pu({referenceCategory:t.category,referenceGender:t.gender,collectionDefinition:g,checkCollectionIds:n,checkCategory:e,checkGender:r,event:i});return T?!0:(Array.isArray(y)&&a.push(...y),!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"),_({context:{tieFormat:o,errors:a,aggregateValueImperative:c},result:{error:ai},stack:s});let m=o.collectionDefinitions.map(({collectionId:g})=>g),d=!n||m.length===pt(m).length,l=u&&p&&d,f={valid:l,errors:a};return l?f:_({result:{error:ai},context:{tieFormat:o,errors:a},stack:s})}function Pc(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((y,N)=>y+N)))return{error:G};if(!s)return{error:cr};let c=Ye({matchUp:s,drawDefinition:n,structure:i,event:a})?.tieFormat||t?.tieFormat;if(!c)return{error:Ms};let u=ar({tieFormat:c});if(u.error)return u;let p=c?.collectionDefinitions||[],m=s?.tieMatchUps??[],d=[0,0],{groupValueGroups:l,groupValueNumbers:f}=IS(c);for(let y of p)vv({collectionDefinition:y,groupValueNumbers:f,groupValueGroups:l,sideTieValues:d,tieMatchUps:m});for(let y of f){let N=l[y],{allGroupMatchUpsCompleted:E,matchUpCount:A,winCriteria:U,groupValue:C,sideWins:P,values:D}=N,M;if(U?.aggregateValue)E&&D[0]!==D[1]&&(M=D[0]>D[1]?1:2);else if(U?.valueGoal)M=D.reduce((b,v,O)=>v>=U.valueGoal?O+1:b,void 0);else{let b=Math.floor(A/2)+1;M=P.reduce((v,O,w)=>O>=b?w+1:v,void 0)}M&&(d[M-1]+=C||0)}let g=d.map((y,N)=>(y||0)+e[N]),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:y,aggregateValue:N,tallyDirectives:E}=c.winCriteria;if(y?T=g.map((U,C)=>({sideNumber:C+1,points:U})).find(({points:U})=>U>=y)?.sideNumber:N&&m.every(U=>U.matchUpStatus&&ae.includes(U.matchUpStatus)||U.winningSide)&&g[0]!==g[1]&&(T=g[0]>g[1]?1:2),!T&&E){let A=s.matchUpId,U=s.hasContext?s:o?.drawMatchUps?.[A]||n&&Lt({inContext:!0,drawDefinition:n,matchUpId:A})?.matchUp;if(U){let{completedTieMatchUps:C,order:P}=ba({matchUps:[U]});if(C&&P?.length){let D=P[0].participantId;T=U.sides.find(({participantId:M})=>M===D)?.sideNumber}}}}return T&&(I.winningSide=T),{scoreStringSide1:h,scoreStringSide2:S,winningSide:T,set:I}}function va({inContextDualMatchUp:t,drawDefinition:e,tournamentId:r,dualMatchUp:n,eventId:o}){if(n){t||(t=Lt({matchUpId:n.matchUpId,inContext:!0,drawDefinition:e})?.matchUp);let{extension:i}=dt({element:e,name:Do}),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}}),It({context:"ensureSidLineUps",matchUp:n,drawDefinition:e,tournamentId:r,eventId:o})}}function Je(t){if(t)return J(t,!1,!0)}function pg(t){let e=ut(t,[{[Ae]:!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 SS({tournamentRecords:t,eventId:e,drawId:r}){let{tournamentIdMap:n}=pg({tournamentRecords:t});return(n?Object.keys(n):[]).find(i=>e&&n?.[i].includes(e)||r&&n?.[i].includes(r))}function eo(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&&SS({tournamentRecords:c,...t});let p=u&&c[u];if(!p)return{error:j};let m=Lt({drawDefinition:r,event:a,matchUpId:s});if(m.error)return m;if(!m.matchUp)return{error:_e};let{matchUp:d,structure:l}=m;if(!d.tieMatchUps)return{error:Ze};va({tournamentId:p?.tournamentId,eventId:a?.eventId,dualMatchUp:d,drawDefinition:r});let{extension:f}=dt({name:nc,element:d});if(f?.value)if(o)sr({element:d,name:nc});else return{...R,score:d.score};let g=Ye({drawDefinition:r,structure:l,matchUp:d,event:a})?.tieFormat;d.tieFormat=Je(g);let I=Pc({drawDefinition:r,matchUpsMap:i,structure:l,matchUp:d,event:a}),{winningSide:h,set:S,scoreStringSide1:T,scoreStringSide2:y}=I,N=S?.side1Score||S?.side2Score;if(e&&!d.score&&!N)return{...R};let E={scoreStringSide1:T,scoreStringSide2:y,sets:S?[S]:[]},A=h&&[1,2].includes(h),U=A&&me||Yf({matchUpStatus:n??d.matchUpStatus,tieMatchUps:d.tieMatchUps,winningSide:d.winningSide,score:E})&&Cn||Qt,C=!!(d.winningSide&&!A),P=d.tieMatchUps.find(({score:M,winningSide:b,matchUpStatus:v})=>M?.sets?.length&&(M.sets[0].side1Score||M.sets[0].side2Score)||v&&ae.includes(v)||b),D;if(d.tieFormat&&!A&&!P){let M=Ye({drawDefinition:r,structure:l,event:a})?.tieFormat;M&&JSON.stringify(g)===JSON.stringify(M)&&(d.tieFormatId=void 0,d.tieFormat=void 0,D=!0)}return vn({appliedPolicies:t.appliedPolicies,matchUpStatus:U,score:E,removeWinningSide:C,tournamentRecord:p,drawDefinition:r,removeScore:o,winningSide:h,matchUpId:s,matchUp:d,event:a}),{...R,score:E,removeWinningSide:C,tieFormatRemoved:D,winningSide:h}}function wv({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}),N=T?.find(M=>M.drawPosition===o)?.participantId,E=s.target.structureId,{positionAssignments:A}=de({structureId:E,drawDefinition:c}),C=A?.find(M=>M.participantId===N)?.drawPosition,P=A?.filter(M=>{let b=f.includes(M.drawPosition),v=!M.participantId&&!M.bye&&!M.qualifier;return b&&v}).map(M=>M.drawPosition),D=P?.includes(g);if(N&&s.target.roundNumber===1&&D)bn({drawPosition:g,participantId:N,structureId:E,inContextDrawMatchUps:e,sourceMatchUpStatus:n,tournamentRecord:i,drawDefinition:c,matchUpsMap:m,event:d});else if(N&&P?.length){let M=P.pop();M&&bn({participantId:N,structureId:E,inContextDrawMatchUps:e,sourceMatchUpStatus:n,tournamentRecord:i,drawDefinition:c,drawPosition:M,matchUpsMap:m,event:d})}else if(C){let M=hc({drawPosition:C,matchUpId:u.matchUpId,inContextDrawMatchUps:e,sourceMatchUpStatus:n,tournamentRecord:i,sourceMatchUpId:a,drawDefinition:c,matchUpsMap:m});if(M.error)return _({result:M,stack:l})}else if(S?.stage!==at){let M="winner target position unavaiallble";return console.log(M),{error:M}}if(S?.seedAssignments&&S.structureId!==E){let M=S.seedAssignments.find(({participantId:v})=>v===N),b=M?.participantId;M&&b&&$s({eventId:u?.eventId,structureId:E,...M,tournamentRecord:i,drawDefinition:c,participantId:b})}}else{let f=hc({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:N})=>N===u.matchUpId),T=[1,2].map(N=>({...S.sides?.find(A=>A.sideNumber===N)||{},sideNumber:N}));S.sides=T;let y=S.sides.find(N=>N.sideNumber===h);if(y){let N=f.lineUp?.filter(E=>E?.participantId);y.lineUp=nd({lineUp:N}),It({tournamentId:i?.tournamentId,eventId:u?.eventId,matchUp:S,context:l,drawDefinition:c})}}}return{...R}}function Lv(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===Xn&&u.roundNumber===2&&Math.min(...g.filter(Boolean)),h=I||g[e],S=I||g[1-e],T=a.source.structureId,{structure:y}=st({structureId:T,drawDefinition:c}),{matchUps:N}=At({afterRecoveryTimes:!1,inContext:!0,drawDefinition:c,structure:y,event:d}),A=N.filter(V=>V.drawPositions?.includes(i)).filter(V=>{let Y=V.sides.find(k=>k.drawPosition===i),$=V.matchUpStatus===vt||V.matchUpStatus===bt&&!Ie(V);return Y?.sideNumber===V.winningSide&&!$}),U=f===Xn&&A.length===0,{positionAssignments:C}=de({structureId:T,drawDefinition:c}),D=C?.find(V=>V.drawPosition===i)?.participantId,M=a.target.structureId,{positionAssignments:b}=de({structureId:M,drawDefinition:c}),v=b?.filter(({drawPosition:V})=>g.includes(V));if(v?.some(V=>V.participantId===D))return{...R};let w=v?.filter(V=>{let Y=g.includes(V.drawPosition),$=!V.participantId&&!V.bye&&!V.qualifier;return Y&&$}).map(V=>V.drawPosition),F=w?.includes(h),L=a.target.roundNumber>1&&w?.length,x=a.target.roundNumber===1&&F;if(I){let V=B();if(V.error)return _({result:V,stack:l})}else if(x){let V=W();if(V.error)return _({result:V,stack:l})}else if(D&&L){w.sort(se);let V=w[0],Y=bn({participantId:D,structureId:M,drawPosition:V,inContextDrawMatchUps:r,sourceMatchUpStatus:o,tournamentRecord:s,drawDefinition:c,matchUpsMap:m,event:d});if(Y.error)return _({result:Y,stack:l})}else return _({result:{error:Ds},context:{loserDrawPosition:i,loserTargetLink:a},stack:l});if(y?.seedAssignments&&y.structureId!==M){let V=y.seedAssignments.find(({participantId:$})=>$===D),Y=V?.participantId;V&&Y&&$s({eventId:u?.eventId,structureId:M,...V,tournamentRecord:s,drawDefinition:c,participantId:Y})}if(p&&n){let V=p.sides?.find(Y=>Y.sideNumber===3-n);if(V?.lineUp){let{roundNumber:Y,eventId:$}=u,{roundPosition:k}=p,K=Y===1?2-k%2:1,z=m?.drawMatchUps?.find(({matchUpId:Q})=>Q===u.matchUpId),q=[1,2].map(Q=>({...z.sides?.find(ot=>ot.sideNumber===Q)||{},sideNumber:Q}));z.sides=q;let et=z.sides.find(Q=>Q.sideNumber===K);et&&(et.lineUp=nd({lineUp:V.lineUp}),It({tournamentId:s?.tournamentId,matchUp:z,context:l,drawDefinition:c,eventId:$}))}}return{...R};function B(){let V="loserLinkFedFMLC";return U?_({result:W(),stack:V}):_({result:H(),stack:V})}function H(){let V=Cr({drawPosition:S,structureId:M,tournamentRecord:s,drawDefinition:c,event:d});return _({result:V,stack:"assignLoserPositionBye"})}function W(){let V=D?bn({drawPosition:h,participantId:D,structureId:M,inContextDrawMatchUps:r,sourceMatchUpStatus:o,tournamentRecord:s,drawDefinition:c,matchUpsMap:m,event:d}):{error:ee};return _({result:V,stack:"assignLoserDrawPosition"})}}function TS(t){let e=dd(t);if(e.error)return e;let r=Pa({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=gr({structure:f}),y=g.drawPositions,N;if(S){let{matchUpTieId:E,matchUpsMap:A}=t,U=eo({appliedPolicies:t.appliedPolicies,matchUpId:E,tournamentRecord:s,drawDefinition:a,matchUpsMap:A,event:I});if(N=U&&{tieMatchUpResult:U},y=i.find(({matchUpId:P})=>P===E)?.drawPositions,!n)return _({result:{...R,...N},stack:h})}if(T)return _({result:{...R,...N},stack:h});if(y){let E=o?o-1:m-1,A=1-E,U=y[E],C=y[A],{targetLinks:{loserTargetLink:P,winnerTargetLink:D,byeTargetLink:M},targetMatchUps:{winnerMatchUpDrawPositionIndex:b,loserMatchUpDrawPositionIndex:v,winnerMatchUp:O,loserMatchUp:w,byeMatchUp:F}}=d;if(O){let L=wv({sourceMatchUpStatus:r&&c||me,winnerMatchUpDrawPositionIndex:b,sourceMatchUpId:l,inContextDrawMatchUps:i,projectedWinningSide:o,winningDrawPosition:U,tournamentRecord:s,winnerTargetLink:D,drawDefinition:a,winnerMatchUp:O,dualMatchUp:u,matchUpsMap:p,event:I});if(L.error)return _({result:L,stack:h})}if(w){let L=Lv({sourceMatchUpStatus:r&&c||me,loserMatchUpDrawPositionIndex:v,sourceMatchUpId:l,inContextDrawMatchUps:i,projectedWinningSide:o,loserDrawPosition:C,tournamentRecord:s,loserTargetLink:P,drawDefinition:a,loserMatchUp:w,winningSide:m,matchUpsMap:p,dualMatchUp:u,event:I});if(L.error)return _({result:L,stack:h})}if(F){let L=F.drawPositions||[],x=Math.min(...L.filter(Boolean)),B=M.target.structureId,H=Cr({drawPosition:x,structureId:B,tournamentRecord:s,drawDefinition:a,event:I});if(H.error)return _({result:H,stack:h})}}else return _({result:{error:Ya},stack:h});return _({result:{...R,...N},stack:h})}function Id(t){let e="genPlayoffStructure";if(!t.drawDefinition)return _({result:{error:X},stack:e});let r=Su(t);if(r.error)return _({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:y}=st({structureId:n,drawDefinition:T});if(!y)return _({result:{error:Gt},stack:e});if(y.structureType===ke||y.structures)return Sv({sourceStructureId:y.structureId,...t,...r,drawDefinition:T});let{playoffRoundsRanges:N,playoffRounds:E}=r,{playoffPositionsReturned:A,error:U,playoffSourceRounds:C,playoffRoundsRanges:P}=sS(t);if(U)return _({result:{error:U},stack:e});let D=l?.length&&Object.assign({},...l),M=f||typeof l=="object"&&l.map(q=>Object.keys(q)).flat(),b=Array.isArray(M)&&M.map(q=>!isNaN(q)&&ct(q)).filter(Boolean);if(b){if(!Array.isArray(b))return _({result:{error:G},context:{validRoundNumbers:b},stack:e});b.forEach(q=>{if(!E?.includes(q))return _({result:{error:G},context:{roundNumber:q},stack:e})})}u&&u.forEach(q=>{if(!A?.includes(q))return _({result:{error:G},context:{playoffPosition:q},stack:e})});let v=b||C,O=b?N:P,w=[],F=[];for(let q of v??[]){let et=O?.find(Ee=>Ee.roundNumber===q);if(!et)return _({result:{error:G},context:{roundNumber:q},stack:e});let Q=et.finishingPositions.length,it=Math.min(...et.finishingPositions)-1,ot=2,mt=q&&D?.[q]&&ot+D[q]-1,Xt=yc({exitProfile:`0-${q}`,addNameBaseToAttributeName:o,playoffStructureNameBase:i,finishingPositionOffset:it,playoffAttributes:c,exitProfileLimit:d,stage:ue,roundOffset:0,drawDefinition:T,sequenceLimit:mt,stageSequence:ot,drawSize:Q,idPrefix:g,isMock:I,uuids:S,finishingPositionNaming:s,finishingPositionLimit:a,roundOffsetLimit:p});if(Xt.error)return _({result:Xt,stack:e});let{structures:Et,links:Me}=Xt;if(Et?.length&&w.push(...Et),Me?.length&&F.push(...Me),Xt.structureId&&q){let Ee={linkType:Qn,source:{structureId:n,roundNumber:q},target:{structureId:Xt.structureId,feedProfile:pn,roundNumber:1}};F.push(Ee)}}if(!w.length)return _({result:{error:G},info:"No structures generated",stack:e});T.structures.push(...w),T.links.push(...F);let{matchUps:L,matchUpsMap:x}=ne({inContext:!0,drawDefinition:T}),B=w.map(({structureId:q})=>q),H=L?.filter(({structureId:q})=>B.includes(q)).map(fe),W=x?.drawMatchUps?.filter(({matchUpId:q})=>H?.includes(q));if(W?.length){let q=Ye({drawDefinition:T,event:h})?.tieFormat;q&&W.forEach(et=>{let{tieMatchUps:Q}=Ra({matchUp:et,tieFormat:q,isMock:I});Object.assign(et,{tieMatchUps:Q,matchUpType:Bt})})}L?.filter(q=>as({matchUp:q})&&q.structureId===n)?.forEach(q=>{let{matchUpId:et,score:Q,winningSide:it}=q,ot=nr({inContextDrawMatchUps:L,drawDefinition:T,matchUpId:et}),mt=TS({inContextDrawMatchUps:L,tournamentRecord:m,drawDefinition:T,matchUpsMap:x,winningSide:it,targetData:ot,matchUpId:et,structure:y,matchUp:q,score:Q,event:h});mt.error&&console.log(mt.error)}),L?.filter(q=>q.matchUpStatus===Nt&&q.structureId===n)?.forEach(q=>{let{matchUpId:et}=q,Q=nr({inContextDrawMatchUps:L,drawDefinition:T,matchUpId:et}),{targetLinks:{loserTargetLink:it},targetMatchUps:{loserMatchUpDrawPositionIndex:ot,loserMatchUp:mt}}=Q;if(it&&mt){let Xt=it.target.structureId,Et=mt.drawPositions[ot],Me=Cr({drawPosition:Et,structureId:Xt,tournamentRecord:m,drawDefinition:T,event:h});Me.error&&console.log(Me.error)}});let $=[],k=Gi({inContextDrawMatchUps:L,drawDefinition:T,matchUpsMap:x}).goesToMap,{structure:K}=st({drawDefinition:t.drawDefinition,structureId:n}),{matchUps:z}=At({structure:K});return z.forEach(q=>{let et=k?.loserMatchUpIds[q.matchUpId];if(et&&q.loserMatchUpId!==et){q.loserMatchUpId=et;let it={tournamentId:m?.tournamentId,eventId:t.event?.eventId,context:e,matchUp:q};$.push(it)}let Q=k?.winnerMatchUpIds[q.matchUpId];if(Q&&q.winnerMatchUpId!==Q){q.winnerMatchUpId=Q;let it={tournamentId:m?.tournamentId,eventId:t.event?.eventId,context:e,matchUp:q};$.push(it)}}),{structures:w,matchUpModifications:$,links:F,drawDefinition:T,...R}}function cP(t){return dg({...t,itemType:"attachConsolationStructures"})}function mg(t){return dg({...t,itemType:"attachPlayoffStructures"})}function dg({itemType:t="attachStructures",matchUpModifications:e,tournamentRecord:r,drawDefinition:n,structures:o,links:i=[],event:s}){let a="attachStructures";if(!n)return{error:X};if(!Array.isArray(o)||!Array.isArray(i))return _({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 _({result:{error:Hl},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),Gi({drawDefinition:n});let f=o.map(h=>At({structure:h})?.matchUps||[]).flat();No({tournamentId:r?.tournamentId,eventId:s?.eventId,drawDefinition:n,matchUps:f});let g=o.map(({structureId:h})=>h);if(Ot({drawDefinition:n,structureIds:g}),e?.length){let h={};e.forEach(T=>{let y=T.matchUp?.matchUpId;y&&(h[y]=T)});let S=T=>{T.matchUps.forEach(y=>{if(h[y.matchUpId]){let{tieMatchUps:N,...E}=h[y.matchUpId].matchUp;if(Object.assign(y,E),N?.length){let A={};N.forEach(U=>h[U.matchUpId]=U),y.tieMatchUps.forEach(U=>Object.assign(U,A[U.matchUpId]))}h[y.matchUpId].matchUp=y,It(h[y.matchUpId])}})};n.structures.forEach(T=>{if(d?.includes(T.structureId))if(T.structures)for(let y of T.structures)S(y);else S(T)})}let I=l.map(Mr("structureId"));if(r){let S={itemValue:{structureIds:g,drawId:n.drawId},itemType:t};Ui({element:r,timeItem:S})}return{...R,addedStructureIds:I}}function Rp(t){let{structures:e,links:r,matchUpModifications:n,error:o}=Id(t);if(o)return{error:o};let i=t.drawDefinition;return mg({tournamentId:t.tournamentRecord?.tournamentId,eventId:t.event?.eventId||t.eventId,matchUpModifications:n,drawDefinition:i,structures:e,links:r})}function Wi(t){let e=ut(t,[{_anyOf:{[Ae]:!1,[un]:!1,[Or]:!1,[Os]:!1},[zl]:!0}]);if(e.error)return e;let r=[],n=t.drawDefinition??t.event??((t.tournamentId||!t.tournamentRecords)&&t.tournamentRecord);if(n){let o=Fv(t,n);if(o.error)return o;r.push(...o?.applied??[]),t.drawDefinition&&Ot({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=Fv(t,s);if(a.error)return a;r.push(...a?.applied??[])}}else return{error:j};return r.length?{...R,applied:r}:{error:EI}}function Fv(t,e){let r=ht(t).appliedPolicies??{};e.extensions||(e.extensions=[]);let n=[],o=Object.keys(t.policyDefinitions);if(!o.length)return{error:Wu};for(let i of o)if(!r[i]||t.allowReplacement){let s=t.policyDefinitions[i];if(!s)continue;if(!Pt(s))return{error:G};let{policyName:a,...c}=s;if(!c||!Object.keys(c).length||a&&!Re(a))return{error:G};r[i]=t.policyDefinitions[i],n.push(i)}return n?.length?{...yt({element:e,extension:{name:qc,value:r}}),applied:n}:{applied:n,error:EI}}function lg({tournamentRecord:t,drawDefinition:e,flightProfile:r,drawName:n,drawId:o,event:i}){if(!n||typeof n!="string")return _({result:{error:G},context:{drawName:n}});r||(r=Ht({event:i}).flightProfile);let s=r?.flights?.find(a=>a.drawId===o);if(s){s.drawName=n;let a={name:Qr,value:{...r,flights:r.flights}};Po({event:i,extension:a})}return e&&(e.drawName=n,Ot({tournamentId:t?.tournamentId,drawDefinition:e})),!s&&!e?{error:X}:{...R,flight:s}}function uP({tournamentRecord:t,drawDefinition:e,drawUpdates:r,drawId:n,event:o}){if(!Pt(r))return{error:G};let i=Ht({event:o}).flightProfile,s=r.drawName&&lg({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:X};if(a){let c={name:Qr,value:{...i,flights:i.flights}};Po({event:o,extension:c})}return e&&(r.policyDefinitions&&Wi({policyDefinitions:r.policyDefinitions,drawDefinition:e}),Ot({tournamentId:t?.tournamentId,drawDefinition:e})),{...R}}function pP({tournamentRecord:t,removeScheduling:e,drawDefinition:r}){if(!r)return{error:X};let n=ye({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(d=>(delete d.participantId,d)),s.seedAssignments=[]);let{matchUps:p,isRoundRobin:m}=At({afterRecoveryTimes:!1,inContext:!0,matchUpsMap:n,structure:s});for(let d of p){let{matchUpId:l,roundNumber:f}=d,g=d.sides||[],I=o(l);if(I){if(delete I.extensions,delete I.notes,I.matchUpStatus!==Nt&&Object.assign(I,Eu),f&&f>1&&I.drawPositions?.length&&!m){let h=g?.map(({drawPosition:T,participantFed:y})=>!y&&T).filter(Boolean),S=I.drawPositions.map(T=>h.includes(T)?void 0:T);I.drawPositions=S}e?delete I.timeItems:I.timeItems?.length&&(I.timeItems=I.timeItems.filter(h=>h.itemType&&![Ro,hi,Gs,oU,ks,Vs].includes(h.itemType))),It({tournamentId:t?.tournamentId,context:"resetDrawDefiniton",drawDefinition:r,matchUp:I})}}}let i=(r.structures||[]).map(({structureId:s})=>s);return Ot({drawDefinition:r,structureIds:i}),{...R}}function Du({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}=hu({drawDefinition:o}),p=r[i],d=(o?.structures||[]).map(N=>{let{stage:E,stageSequence:A,structureId:U}=N,C=Ls[E],{inContextStructureMatchUps:P}=Da({drawDefinition:o,structure:N,event:p}),D=P?.filter(({winningSide:Y})=>Y),M=D.filter(Boolean).length||0;a+=M,c+=P.length-a;let b=Math.max(D.filter(({roundNumber:Y})=>Y===1).map(({roundPosition:Y})=>Y)),{positionAssignments:v}=Ct({structure:N}),O=v?.filter(({participantId:Y})=>Y);s+=O?.length??0;let w=(v?.length??0)-(O?.length??0),{roundMatchUps:F,roundProfile:L,roundNumbers:x,maxMatchUpsCount:B}=qe({matchUps:P}),H=L&&Object.keys(L).filter(Y=>!L[Y].inactiveRound).map(Y=>parseInt(Y)),W=L&&Object.keys(L).filter(Y=>L[Y].inactiveRound).map(Y=>parseInt(Y)),V=L&&Object.values(L).every(Y=>Y.inactiveRound);return{positionsAssignedCount:O?.length??0,maxWinningSideFirstRoundPosition:b,unassignedPositionsCount:w,inactiveStructure:V,maxMatchUpsCount:B,inactiveRounds:W,roundMatchUps:F,activeRounds:H,roundNumbers:x,roundProfile:L,structureId:U,stageSequence:A,orderNumber:C,stage:E}}),l=d.find(N=>N.orderNumber===2&&N.stageSequence===1),f=d.filter(({inactiveStructure:N})=>!N).length,{links:g}=Ws({structureId:l.structureId,drawDefinition:o}),I=ct(l.activeRounds[0])===1&&l.activeRounds.length===1&&f===1,h=d?.every(({inactiveStructure:N})=>N),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 y={matchUpsWithWinningSideCount:a,matchUpsNoOutcomeCount:c,positionsAssignedCount:s,allStructuresLinked:u,structuresData:d,inactiveDraw:h,isMatchPlay:I,drawId:T};e.drawAnalysis[T]=y}),{...R,drawsAnalysis:e}}function mP({matchPlayDrawPositions:t=!0,tournamentRecord:e,drawDefinition:r,drawId:n}){if(!e)return{error:j};if(!r)return{error:X};let o=[],{drawsAnalysis:i}=Du({tournamentRecord:e});if(i.canBePruned.includes(n)){let s=i.matchPlay.includes(n),a=i.drawAnalysis[n],{structures:[c]}=Gn({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(fe),d=p.map(fe).filter(l=>!m.includes(l));if(s){let l=o.filter(({roundNumber:T})=>!u.inactiveRounds.includes(T)).filter(({winningSide:T})=>T),f=l.map(fe),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,y)=>({[T]:y+1})));if(l.forEach(T=>{t?T.drawPositions=T.drawPositions.map(y=>S[y]):delete T.drawPositions}),t){let T=c?.positionAssignments?.filter(y=>h.includes(y.drawPosition)).map(y=>(y.drawPosition=S[y.drawPosition],y));c.positionAssignments=T}else c.positionAssignments=[];c.matchUps=l,o=l}kn({tournamentId:e?.tournamentId,matchUpIds:d,drawDefinition:r}),Ot({drawDefinition:r})}return{...R,matchUps:o}}function dP({tournamentRecord:t,drawDefinition:e,participantId:r,drawPosition:n,structureId:o,qualifier:i,event:s,bye:a}){if(!e)return{error:X};if(!n)return{error:Ns};if(!o)return{error:Sr};if(a){let c=Cr({tournamentRecord:t,drawDefinition:e,drawPosition:n,structureId:o,event:s});if(c.error)return c}else{if(i)return{error:zu};{let c=bn({tournamentRecord:t,drawDefinition:e,participantId:r,drawPosition:n,structureId:o,event:s});if(c.error)return c}}return{...R}}function yS(t){let e=t.matchUpIds??[],{drawDefinition:r}=t,n=t.structureId??r?.structures?.find(c=>c.matchUps?.some(({matchUpId:u})=>e.includes(u)))?.structureId??r?.structures?.[0]?.structureId;if(!n)return{error:Gt};let o=r.structures?.find(c=>c.structureId===n);if(!o)return{error:Gt};let i=o?.matchUps,s=i?.find(c=>!!c.roundPosition);if(o.structures||s||o.finishingPosition===wi)return{error:Ci};let a=i.filter(({roundNumber:c})=>t.roundNumbers?.includes(c)).map(fe);return e=e.filter(c=>!a.includes(c)),t.roundNumbers&&!e.length&&(e=a),{existingMatchUps:i,matchUpIds:e,structureId:n,structure:o}}function lP(t){let e=ut(t,[{[Or]:!0},{[Za]:{[Ja]:!1,roundNumbers:!1},[Dn]:G,[dn]:Dr}]);if(e.error)return e;let{removeIncomplete:r=!1,removeUnAssigned:n=!0,removeCompleted:o=!1,tournamentRecord:i,drawDefinition:s,event:a}=t,c=yS(t);if(c.error)return c;let{structure:u,structureId:p,existingMatchUps:m,matchUpIds:d}=c,l=[],f=m?.filter(({matchUpId:h,score:S,winningSide:T})=>{if(T&&!o)return!1;if(T||Ie({score:S})){if(!T&&!r)return!1;l.push(h)}else if(!n)return!1;return d?.includes(h)})??[],g=f.map(fe),I=f.map(({tieMatchUps:h})=>h?.map(fe)).filter(Boolean).flat();if(g.length){u.matchUps=(u.matchUps??[]).filter(({matchUpId:T})=>!g.includes(T)),kn({tournamentId:i?.tournamentId,matchUpIds:[...I,...g],action:"deleteAdHocMatchUps",eventId:a?.eventId,drawDefinition:s});let h=pt(u.matchUps.map(Mr("roundNumber"))),S=ZC(h);if(S.length){S.reverse();for(let T of S)u.matchUps.forEach(y=>{y.roundNumber&&y.roundNumber>T&&(y.roundNumber-=1,It({tournamentId:i?.tournamentId,context:["adHoc round deletion"],eventId:a?.eventId,drawDefinition:s,matchUp:y}))})}if(l.length){u.positionAssignments=pt(u.matchUps.flatMap(E=>(E.sides??[]).map(A=>A.participantId)).filter(Boolean)).map(E=>({participantId:E}));let T=u?.matchUpFormat??s?.matchUpFormat??a?.matchUpFormat,{matchUps:y}=At({afterRecoveryTimes:!1,inContext:!0,structure:u,event:a}),N=md({positionAssignments:u.positionAssignments,tournamentRecord:i,drawDefinition:s,matchUpFormat:T,matchUps:y,event:a});N.error&&console.log(N)}Ot({structureIds:[p],eventId:a?.eventId,drawDefinition:s})}return!g.length&&d.length?{error:Qu}:{...R,deletedMatchUpsCount:[...g,...I].length}}function fP({removeCompletedMatchUps:t,tournamentRecord:e,drawDefinition:r,structureId:n,roundNumber:o,event:i}){if(!e)return{error:j};if(!r)return{error:X};if(!o)return _({result:{error:rt},info:"roundNumber required"});let s=st({drawDefinition:r,structureId:n});if(s.error)return s;let a=s.structure;return a?.structures?{error:Ci}:gr({structure:a})?jG({tournamentId:e.tournamentId,removeCompletedMatchUps:t,eventId:i.eventId,drawDefinition:r,roundNumber:o,structure:a}):(console.log("not implemented"),{...R})}function jG({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(se).includes(n)){let m=s.filter(d=>{let l=d.roundNumber===n&&(!ae.includes(d.matchUpStatus)||t);return l&&(c.push(d.matchUpId),d.tieMatchUps&&a.push(...d.tieMatchUps.map(fe))),!l});c.length&&(kn({matchUpIds:[...a,...c],drawDefinition:e,tournamentId:r,eventId:i}),m.some(l=>l.roundNumber===n)||(m.forEach(l=>{l.roundNumber>n&&(l.roundNumber-=1,It({drawDefinition:e,tournamentId:r,eventId:i,matchUp:l}))}),u=!0),o.matchUps=m)}return{deletedMatchUpsCount:c.length,roundRemoved:u,...R}}function hd(t){let{suppressNotifications:e,tournamentRecord:r,drawDefinition:n,matchUps:o,event:i}=t;if(typeof n!="object")return{error:X};let s=t?.structureId;if(!s&&n.structures?.length===1&&(s=n.structures?.[0]?.structureId),typeof s!="string")return{error:Sr};if(!Nr(o))return{error:G,info:Rn("matchUps")};let a=n.structures?.find(l=>l.structureId===s);if(!a)return{error:Gt};let u=(a?.matchUps).find(l=>!!l.roundPosition);if(a.structures||u||a.finishingPosition===wi)return{error:Ci};let p=le({tournamentRecord:r,inContext:!1})?.matchUps?.map(fe)??[],m=o.map(fe);if(Fe(p,m))return{error:uE,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||(No({tournamentId:r?.tournamentId,matchUps:[...d,...o],eventId:i?.eventId,drawDefinition:n}),Ot({drawDefinition:n,structureIds:[s]})),{...R}}function gP({tournamentRecord:t,drawDefinition:e,drawPosition:r,structureId:n,subOrder:o,event:i}){if(!e)return{error:X};if(!n)return{error:Sr};if(!r)return{error:Ns};let{structure:s}=st({drawDefinition:e,structureId:n});if(!s)return{error:Gt};let a=s;s.structures&&s.structureType===ke&&(a=s.structures?.find(g=>g.positionAssignments?.find(I=>I.drawPosition===r)));let c=a?.positionAssignments,u=c?.find(g=>g.drawPosition===r);u&&yt({element:u,extension:{name:oc,value:o}});let d=(i?.eventType===Bt||e.matchUpType===Bt||(i?.tieFormat??e?.tieFormat??s?.tieFormat))&&{matchUpTypes:[Bt]},{matchUps:l}=At({structure:a,afterRecoveryTimes:!1,inContext:!0,matchUpFilters:d,event:i}),f=s?.matchUpFormat??e.matchUpFormat;return md({positionAssignments:c,tournamentRecord:t,drawDefinition:e,matchUpFormat:f,matchUps:l,event:i}),Ot({drawDefinition:e,structureIds:[n]}),{...R}}var RP={};Zt(RP,{addGoesTo:()=>Gi,allPlayoffPositionsFilled:()=>eS,checkValidEntries:()=>Ad,findDrawDefinition:()=>PS,getAssignedParticipantIds:()=>Ei,getAvailableMatchUpsCount:()=>Sd,getAvailablePlayoffProfiles:()=>Su,getDrawDefinitionTimeItem:()=>lh,getDrawParticipantRepresentativeIds:()=>ES,getDrawTypeCoercion:()=>Mu,getEligibleVoluntaryConsolationParticipants:()=>AS,getMatchUpsMap:()=>ye,getParticipantIdFinishingPositions:()=>US,getPositionAssignments:()=>Op,getPositionsPlayedOff:()=>Ac,getSeedingThresholds:()=>Yh,getSeedsCount:()=>Cu,getStructureSeedAssignments:()=>Hr,getTeamLineUp:()=>is,getValidGroupSizes:()=>Ep,isAdHoc:()=>gr,isCompletedStructure:()=>ei,isValidForQualifying:()=>kS,positionActions:()=>GS});function AS({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:X};let f=[tt,ue];r&&f.push(at);let g=l?.eventType?{matchUpTypes:[l.eventType]}:void 0,I=a?.matchUpType?{matchUpTypes:[a.matchUpType]}:void 0,h=e&&l?ho({contextFilters:{stages:f},matchUpFilters:g,tournamentRecord:s,inContext:!0,event:l})?.matchUps??[]:or({contextFilters:{stages:f},matchUpFilters:I,tournamentRecord:s,inContext:!0,drawDefinition:a})?.matchUps??[],T=Ii({stage:We,drawDefinition:a}).map(({participantId:x})=>x),y={},N={},E={},A={};o||(o=Co({policyTypes:[qI],tournamentRecord:s,drawDefinition:a,event:l}).policyDefinitions);let U=o?.[qI];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!==ge||x.finishingRound&&n&&x.finishingRound>=n||x.finishingRound&&i&&x.finishingRound<=i)continue;let B=x.sides?.find(({sideNumber:W})=>x.winningSide&&W===3-x.winningSide),H=x.sides?.find(({sideNumber:W})=>x.winningSide&&W===x.winningSide);if(x.sides?.forEach(W=>{let V=W?.participant?.participantId;V&&(E[V]=W.participant,x.matchUpStatus===ge&&!u&&(N[V]=W.participant,y[V]||(y[V]=0),(!x.matchUpStatus||!t.includes(x.matchUpStatus))&&(y[V]+=1)))}),B?.participant){let W=B.participant.participantId;N[W]=B.participant,y[W]||(y[W]=0),x.matchUpStatus&&!t.includes(x.matchUpStatus)&&(y[W]+=1)}if(H?.participant){let W=H.participant.participantId;A[W]||(A[W]=0),A[W]+=1,y[W]||(y[W]=0),x.matchUpStatus&&!t.includes(x.matchUpStatus)&&(y[W]+=1)}}let C=s?.participants&&!u&&!p&&m,P=C?((e&&l?l.entries:a.entries)??[]).filter(x=>![Jn,Br].includes(x.entryStatus)).map(({participantId:x})=>x):[],D=Object.keys(N),M=C?(s?.participants??[]).filter(({participantId:x})=>P.includes(x)):p&&Object.values(N)||Object.values(E),b=x=>!p||D.includes(x),v=x=>!u||(y[x]||0)>=0,O=x=>!d||(A[x]||0)<=d,w=x=>!c||y[x]<=c,F=x=>!T.includes(x);return{eligibleParticipants:M.filter(x=>b(x.participantId)&&v(x.participantId)&&O(x.participantId)&&w(x.participantId)&&F(x.participantId)).map(x=>({...x,individualParticipants:x.individualParticipantIds?.map(B=>s?.participants?.find(H=>H.participantId===B))})),losingParticipantIds:D,...R}}function Sd(t){let e=ut(t,[{drawDefinition:!0}]);if(e.error)return e;let{drawDefinition:r,roundNumber:n}=t,o=t.structureId??(r.structures?.length===1&&r.structures?.[0]?.structureId);if(typeof o!="string")return{error:Sr};let i=r.structures?.find(g=>g.structureId===o);if(!i)return{error:Gt};let s,c=(i.matchUps??[])?.reduce((g,I)=>(I.roundPosition&&(s=!0),(I?.roundNumber||0)>g?I.roundNumber:g),0);if(i.structures||s||i.finishingPosition===wi)return{error:Ci};let u=r?.entries?.filter(g=>{let I=g.entryStatus;return wr.includes(I)})??[],p=Math.floor(u?.length/2)||1,m=n??c??1,d=i.matchUps?.filter(g=>g.roundNumber===m)?.length??0,l=p-d,f=l>0?l:0;return{...R,availableMatchUpsCount:f,lastRoundNumber:c,roundMatchUpsCount:p}}function ES({drawDefinition:t}){let e=dt({name:"participantRepresentatives",element:t});return e.error?e:{representativeParticipantIds:e.extension?.value||[]}}function Gv({tournamentParticipants:t,drawDefinition:e,event:r}){if(!e)return{error:X};let n=ne({tournamentParticipants:t,inContext:!0,drawDefinition:e,event:r}),o=J(n.matchUps,!1,!0),i=pt(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 US({byeAdvancements:t=!1,tournamentRecord:e,drawDefinition:r}){if(!r)return{error:X};let{participantIds:n,participantIdMatchUps:o}=Gv({tournamentParticipants:e?.participants,drawDefinition:r}),i=n?.map(s=>{let c=o[s].filter(d=>[me,Nt].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 vo({tournamentRecords:t,tournamentRecord:e,tournamentId:r,drawId:n}){if(!e&&!t)return{error:j};if(!n)return{error:$r};if(!e&&t){if(typeof r!="string"&&(r=SS({tournamentRecords:t,drawId:n}),!r))return{error:sa};if(e=t[r],!e)return{error:j}}let o=e&&je({tournamentRecord:e,drawId:n});return o?.drawDefinition?{drawDefinition:o.drawDefinition,event:o.event,tournamentRecord:e,...R}:_({result:{error:dr},stack:"findDrawDefinition"})}function PS(t){let{drawDefinition:e,error:r}=vo(t);return r?{error:r}:{drawDefinition:J(e)}}function fg({targetRoundNumber:t,finishingPosition:e,drawDefinition:r,structureId:n,linkType:o}){let{links:i}=Ws({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 kv="qualifierDrawPositionAssignment",Vv="withdrawParticipantAtDrawPosition",Bv="alternateDrawPositionAssignment",Hv="luckyLoserDrawPositionAssignment",hP="removeDrawPositionAssignment",Wv="swapDrawPositionAssignments",jv="modifyPairAssignment",Yv="modifyParticipantOtherName",SP="assignDrawPosition",qv="removeSeededParticipant",$v="assignDrawPositionBye",Kv="modifySeedAssignment",DS="addPenalty",gg="MODIFY_PAIR",bp="QUALIFIER",Ig="ALTERNATE",hg="WITHDRAW",gs="ASSIGN",NS="REMOVE",Sg="LUCKY",vp="REMOVE_SEED",Tg="SWAP",Nu="NICKNAME",Ks="SEED_VALUE",zs="PENALTY",Td="BYE",zv={MODIFY_PAIR_ASSIGNMENT:gg,QUALIFYING_PARTICIPANT:bp,ALTERNATE_PARTICIPANT:Ig,WITHDRAW_PARTICIPANT:hg,ASSIGN_PARTICIPANT:gs,LUCKY_PARTICIPANT:Sg,REMOVE_ASSIGNMENT:NS,SWAP_PARTICIPANTS:Tg,ADD_NICKNAME:Nu,REMOVE_SEED:vp,ADD_PENALTY:zs,ASSIGN_BYE:Td,SEED_VALUE:Ks};function Qv({tournamentParticipants:t,returnParticipants:e,drawPosition:r,participant:n,drawId:o,event:i}){let s=i?.entries?.filter(({entryStatus:a})=>[Br,gi].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:nt({payload:{participantId:n.participantId,replacementIndividualParticipantId:void 0,existingIndividualParticipantId:void 0,drawPosition:r,drawId:o},method:jv,availableIndividualParticipantIds:s,availableIndividualParticipants:c,existingIndividualParticipantIds:a,existingIndividualParticipants:u,type:gg},!1,!1,!0)}}return{}}function Pi(t){let{inContextDrawMatchUps:e,targetData:r,drawDefinition:n,relevantLink:o}=t;if(o?.linkCondition===Xn&&r?.matchUp?.matchUpStatus===Nt)return!1;let{targetMatchUps:{loserMatchUp:s,winnerMatchUp:a},targetLinks:c}=r,u=[bt,vt].includes(s?.matchUpStatus),p=a?.drawPositions?.filter(Boolean).length||0;if(s?.winningSide&&!u||a?.winningSide&&p===2&&(!a.feedRound||![vt,bt].includes(a?.matchUpStatus)))return!0;let m=s&&nr({matchUpId:s.matchUpId,inContextDrawMatchUps:e,drawDefinition:n}),d=a&&nr({matchUpId:a.matchUpId,inContextDrawMatchUps:e,drawDefinition:n}),l=m&&Pi({relevantLink:c?.loserTargetLink,targetData:m,inContextDrawMatchUps:e,drawDefinition:n});return!!(d&&Pi({targetData:d,inContextDrawMatchUps:e,drawDefinition:n})||l)}var MS={[uo]:{policyName:"positionActionsDefault",enabledStructures:[{stages:[at,tt],stageSequences:[1],enabledActions:[],disabledActions:[]},{stages:[],stageSequences:[],enabledActions:[Nu,zs,bp,Ks],disabledActions:[]}],disbledStructures:[],otherFlightEntries:!1,activePositionOverrides:[]}};var yg="positionAction",CS="matchUpAction";function RS({actionType:t=yg,appliedPolicies:e,drawDefinition:r,structure:n}){let o=t===yg&&uo||t===CS&&Qe,i=t===yg&&MS||t===CS&&AU,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 TP({activePositionOverrides:t,activeDrawPositions:e,action:r}){return r&&t.includes(r)?!0:!e.length}function bS({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 On({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 yP="replaceTieMatchUpParticipantId",AP="assignTieMatchUpParticipantId",vS="removeTieMatchUpParticipantId",EP="assignMatchUpSideParticipant",Xv="removeMatchUpSideParticipant",UP="substituteParticipant",OS="REMOVE_SUBSTITUTION",PP="REPLACE_PARTICIPANT",Ag="REMOVE_PARTICIPANT",_S="setMatchUpStatus",xS="SUBSTITUTION",DP="SCHEDULE",YG="PENALTY",wS="REFEREE",NP="STATUS",LS="START",MP="SCORE",FS="END",Jv={REPLACE_TEAM_POSITION_METHOD:yP,ASSIGN_TEAM_POSITION_METHOD:AP,REMOVE_TEAM_POSITION_METHOD:vS,REPLACE_PARTICIPANT:PP,SUBSTITUTION_METHOD:UP,REMOVE_SUBSTITUTION:OS,REMOVE_PARTICIPANT:Ag,SCHEDULE_METHOD:_S,SUBSTITUTION:xS,SCHEDULE:DP,PENALTY:YG,REFEREE:wS,STATUS:NP,SCORE:MP,START:LS,END:FS};function Zv({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===Ur&&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,y=o.sides?.flatMap(F=>F.participant?.individualParticipants||F.participant).filter(Boolean)?.map(gt),N=o.sides?.filter(F=>!c||F.sideNumber===c).flatMap(F=>F.participant?.individualParticipants||F.participant).filter(Boolean),E=N?.map(gt),U=e?.find(F=>F.matchUpId===o.matchUpTieId)?.sides?.map(F=>F.participant?.individualParticipants.filter(({participantId:L,person:x})=>!E?.includes(L)&&(!S||S===In||x.sex===S||S===Ur&&!g||g&&x.sex!==g))),C=c?U?.[c-1]:U?.map((F,L)=>({participants:F,sideNumber:L+1})),P=c?U?.[c-1]?.map(gt):U?.map((F,L)=>({participants:F?.map(gt),sideNumber:L+1})),D=c&&(ie(Ta)(I)&&!E?.length||ie(Li)(I)&&(E?.length??0)<2)||!c&&(ie(Ta)(I)&&(E?.length??0)<2||ie(Li)(I)&&(E?.length??0)<4),M=P?.filter(F=>!y?.includes(F)),b=C?.filter(({participantId:F})=>M.includes(F));if(D&&M?.length&&l.push({availableParticipantIds:M,method:AP,availableParticipants:b,type:gs,payload:{participantId:void 0,tieMatchUpId:u,sideNumber:c,drawId:m}}),E?.length&&(!Ie(p)||d?.substitutions?.length)&&l.push({method:vS,type:Ag,existingParticipantIds:E,payload:{participantId:void 0,tieMatchUpId:u,drawId:m}}),b?.length&&(!c&&E?.length||c&&d?.participant)&&l.push({availableParticipantIds:M,method:yP,availableParticipants:b,type:PP,existingParticipantIds:E,payload:{existingParticipantId:void 0,participantId:void 0,tieMatchUpId:u,drawId:m}}),On({policyActions:i,action:OS})&&d?.substitutions?.length){let F=d.participant?.participantType===Tt&&[d.participantId]||d.participant?.participantType===lt&&d.participant.individualParticipantIds||[],L=d.substitutions.map(x=>x.participantId).filter(x=>F.includes(x));(!a||L.includes(a))&&l.push({method:vS,type:OS,substitutedParticipantIds:L,payload:{participantId:void 0,tieMatchUpId:u,drawId:m}})}let v=t?.[Qe],O=v?.substituteWithoutScore,w=v?.substituteAfterCompleted;if(On({policyActions:i,action:xS})&&r.length===2&&(!c&&E?.length||c&&d?.participant)&&(O||Ie(p))&&(w||p.matchUpStatus&&!ae.includes(p.matchUpStatus))&&N?.length&&C.length){let F=N.map(gt);l.push({info:"list of team players available for substitution",method:UP,availableParticipantIds:P,existingParticipantIds:F,availableParticipants:C,existingParticipants:N,type:xS,payload:{substituteParticipantId:void 0,existingParticipantId:void 0,sideNumber:c,matchUpId:u,drawId:m}})}return l}function tO({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===gs)?.availableParticipantIds,f=i?.[uo]?.otherFlightEntries,g=i?.[uo]?.restrictQualifyingAlternates,I=(s.entries??[]).filter(({entryStage:U})=>!g||(p.stage===at?U===at:U!==at)).sort((U,C)=>(U.entryPosition??1/0)-(C.entryPosition??1/0)).map(({participantId:U})=>U).filter(Boolean),{allPositionedParticipantIds:h}=ih({drawDefinition:s}),S=n.map(U=>U.participantId).filter(Boolean),T=I.filter(U=>p.stage&&[at,tt,ue].includes(p.stage)?!h?.includes(U):!S.includes(U)),N=(d?.entries??[]).filter(U=>U.entryStatus===kr&&CP({restrictQualifyingAlternates:g,structure:p,entry:U})&&(p.stage&&[at,tt,ue].includes(p.stage)?!h?.includes(U.participantId):!S.includes(U.participantId))).sort((U,C)=>(U.entryPosition??1/0)-(C.entryPosition??1/0)).map(U=>U.participantId),E=pt(T.concat(N));if(f){let C=(d?Ht({event:d}).flightProfile:void 0)?.flights?.filter(P=>P.drawId!==m).map(P=>P.drawEntries.filter(D=>D.participantId&&![Jn,Br,gi].includes(D.entryStatus)&&!I.includes(D.participantId)).map(({participantId:D})=>D)).flat().filter(Boolean);C?.length&&E.push(...C)}l?.length&&(E=E.filter(U=>!l.includes(U)));let A=o?t?.filter(U=>E.includes(U.participantId)):void 0;return A?.forEach(U=>{let C=(s.entries??[]).find(P=>P.participantId===U.participantId);U.entryPosition=C?.entryPosition}),A?.sort((U,C)=>(U.entryPosition||1/0)-(C.entryPosition||1/0)),E.length?{validAlternatesAction:nt({payload:{drawId:m,structureId:u,drawPosition:a},willDisableLinks:e,method:Bv,availableAlternatesParticipantIds:E,type:Ig,availableAlternates:A})}:{}}function CP({restrictQualifyingAlternates:t,structure:e,entry:r}){let{stage:n}=e;if(!r.entryStage||r.entryStage===n||n===at&&!t||r.entryStage===tt&&n===He)return!0}function eO({eventEntries:t,structure:e}){let r=o=>o.entryStatus===kr&&CP({structure:e,entry:o}),n=(o,i)=>(o.entryPosition||1/0)-(i.entryPosition||1/0);return t.filter(r).sort(n).map(gt)}function rO({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:E})=>E===u.roundNumber),f=o?.entries?.filter(({entryStatus:E})=>E&&Qo.includes(E)).map(gt)??[],g=l.map(E=>(E.sides??[]).flatMap(gt)).flat().filter(Boolean),I=f.filter(E=>!r.includes(E)&&(!t||!g.includes(E))),h=e?.filter(E=>I?.includes(E.participantId)).map(E=>J(E,void 0,!0));h?.forEach(E=>{let A=(o.entries??[]).find(U=>U.participantId===E.participantId);E.entryPosition=A?.entryPosition}),I.length&&d.push({payload:{drawId:p,matchUpId:a,structureId:i,sideNumber:s},method:EP,type:gs,availableParticipantIds:I,participantsAvailable:h});let S=m?.entries??[],T=eO({eventEntries:S,structure:c}),y=pt(f.concat(T));if(n){let A=(m?Ht({event:m}):void 0)?.flights?.filter(U=>U.drawId!==p).flatMap(U=>U.drawEntries.filter(C=>C.participantId&&![Jn,Br,gi].includes(C.entryStatus)).map(({participantId:C})=>C)).filter(Boolean);A?.length&&y.push(...A)}y=y.filter(E=>!r.includes(E)&&!I.includes(E)&&(!t||!g.includes(E)));let N=e?.filter(E=>y.includes(E.participantId)).map(E=>J(E,void 0,!0));return N?.forEach(E=>{let A=(o.entries??[]).find(U=>U.participantId===E.participantId);E.entryPosition=A?.entryPosition}),N?.sort((E,A)=>(E.entryPosition||1/0)-(A.entryPosition||1/0)),y.length&&d.push({payload:{drawId:p,matchUpId:a,structureId:i,sideNumber:s},availableParticipantIds:y,participantsAvailable:N,method:EP,type:kr}),!Ie(u)&&s&&u.sides?.find(A=>A.sideNumber===s)?.participantId&&d.push({payload:{drawId:p,matchUpId:a,structureId:i,sideNumber:s},method:Xv,type:Ag}),d}function yd(t){if(!t)return{error:G};let{drawDefinition:e,event:r}=t,{restrictAdHocRoundParticipants:n=!0,policyDefinitions:o,enforceGender:i,participantId:s,sideNumber:a,matchUpId:c}=t,u=t.tournamentRecord??(t.tournamentId&&Re(t.tournamentId)&&t.tournamentRecords?.[t.tournamentId]);if(!u)return{error:j};if(!c||!Re(c))return{error:Be};if(a&&![1,2].includes(a))return _({result:{error:G},context:{sideNumber:a}});if(!e){let it=(le({tournamentRecord:u}).matchUps??[]).find(mt=>mt.matchUpId===c);r=(u?.events??[]).find(mt=>mt.eventId===it?.eventId);let ot=(r?.drawDefinitions??[]).find(mt=>mt.drawId===it?.drawId);ot&&(e=ot)}if(!e)return{error:X};let p=Yt({withIndividualParticipants:!0,tournamentRecord:u}).participants,{drawId:m}=e,{matchUp:d,structure:l}=Lt({drawDefinition:e,matchUpId:c,event:r});if(!d)return{error:_e};let f=ht({tournamentRecord:u,drawDefinition:e,structure:l,event:r}).appliedPolicies??{};Object.assign(f,o??{});let g=f?.[uo]?.otherFlightEntries,I=f?.[Qe]??ds[Qe],{enabledStructures:h}=RS({actionType:CS,appliedPolicies:f,drawDefinition:e,structure:l}),{policyActions:S}=bS({enabledStructures:h,drawDefinition:e,structure:l}),T=t.matchUpsMap??ye({drawDefinition:e}),y=t.inContextDrawMatchUps??ne({tournamentParticipants:p,inContext:!0,drawDefinition:e,matchUpsMap:T,event:r}).matchUps,N=y?.find(Q=>Q.matchUpId===c),E=a&&N?.sides?.find(Q=>Q.sideNumber===a),A=N?.sides?.map(Q=>Q.participantId||Q.participant?.participantid).filter(Boolean)??[],{assignedPositions:U,allPositionsAssigned:C}=de({structure:l}),{structureId:P}=l??{},D=[];if(!P)return{validActions:D};let M=gr({structure:l}),b=d.collectionId;if(M&&!b){let Q=rO({restrictAdHocRoundParticipants:n,tournamentParticipants:p,matchUpParticipantIds:A,otherFlightEntries:g,drawDefinition:e,structureId:P,sideNumber:a,matchUpId:c,structure:l,matchUp:d,drawId:m,event:r});D.push(...Q)}let v=ei({drawDefinition:e,structure:l}),O=U?.filter(Q=>Q.participantId).map(Q=>Q.drawPosition),w=U?.filter(Q=>Q.bye).map(Q=>Q.drawPosition),F=d.matchUpStatus===Nt||!b&&d.drawPositions?.reduce((Q,it)=>w?.includes(it)||Q,!1);if(F)return{validActions:D,isByeMatchUp:F};On({policyActions:S,action:wS})&&D.push({type:wS,payload:{matchUpId:c}});let L=!Pa({matchUpStatus:d.matchUpStatus}),x=f?.scoring?.structures,B=l?.stage&&x?.stage&&x?.stage[l.stage],H=l?.stageSequence&&B?.stageSequence&&B.stageSequence[l.stageSequence],V=!(f?.scoring?.requireAllPositionsAssigned||B?.requireAllPositionsAssigned||H?.requireAllPositionsAssigned)||C,Y=d.sides&&d.sides.filter(Q=>Q?.participantId).length===2,$=d.matchUpStatus&&[ge,Ne].includes(d.matchUpStatus),k=nr({inContextDrawMatchUps:y,drawDefinition:e,matchUpId:c}),K=Pi({inContextDrawMatchUps:y,drawDefinition:e,targetData:k}),q=(N?.drawPositions?.length===2&&N.drawPositions.every(Q=>O?.includes(Q))&&N?.sides?.length===2&&N.sides.every(({participantId:Q})=>Q)||Y)&&!($&&K),et={method:DS,type:zs,payload:{drawId:m,matchUpId:c,penaltyCode:void 0,penaltyType:void 0,participantIds:[],notes:void 0}};if(L&&D.push({payload:{drawId:m,matchUpId:c,schedule:{}},method:_S,type:DP}),On({policyActions:S,action:zs})&&(E?.participant||!a&&A?.length)&&D.push(et),L&&q&&D.push({type:NP}),V&&q){let{matchUpId:Q,matchUpFormat:it}=d,ot={drawId:m,matchUpId:Q,matchUpFormat:it,outcome:{scoreStringSide1:void 0,scoreStringSide2:void 0,sets:[]},winningSide:void 0};D.push({info:"set outcome and winningSide",method:_S,type:MP,payload:ot}),On({policyActions:S,action:LS})&&D.push({type:LS}),On({policyActions:S,action:FS})&&D.push({type:FS})}if(b&&N){let Q=Zv({specifiedPolicyDefinitions:o,inContextDrawMatchUps:y,matchUpParticipantIds:A,matchUpActionsPolicy:I,inContextMatchUp:N,policyActions:S,enforceGender:i,participantId:s,sideNumber:a,matchUpId:c,matchUp:d,drawId:m,side:E});D.push(...Q)}return{structureIsComplete:v,validActions:D,isDoubleExit:$,...R}}function nO({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,y=S.target?.structureId;return h.sourceStructureIds.includes(T)||h.sourceStructureIds.push(T),h.targetStructureIds.includes(y)||h.targetStructureIds.push(y),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}),y=T?.finishingPosition===wi&&(d?.length!==1||l?.length!==1),N={};if(y){let{matchUps:C}=At({drawDefinition:s,structure:u,event:m}),{initialRoundNumber:P}=us({drawPosition:a,matchUps:C}),M=s.links?.find(b=>b.target?.structureId===u?.structureId&&b.target.roundNumber===P)?.source?.roundNumber;N.roundNumbers=[M]}let{completedMatchUps:E}=lu({structureId:S,inContext:!0,matchUpFilters:N,drawDefinition:s}),A=i.map(C=>C.participantId).filter(Boolean);E?.filter(({matchUpType:C,winningSide:P})=>P&&(m?.eventType!==Ve||C===Ve)).map(({winningSide:C,sides:P})=>C&&P?.[1-(C-1)]).map(gt).filter(C=>C&&!A.includes(C))?.forEach(C=>{f.includes(C)||f.push(C)})}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:Sg,method:Hv,availableLuckyLosers:I,availableLuckyLoserParticipantIds:f,willDisableLinks:r,payload:{drawId:p,structureId:c,drawPosition:a}}}:{}}function oO({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=[],y=c?.[Nn]?.validSeedPositions?.ignore;if(y||({unplacedSeedParticipantIds:h,unplacedSeedAssignments:S,unfilledPositions:T}=qh({provisionalPositioning:n,returnAllProxies:!0,randomize:!0,drawDefinition:u,seedingProfile:p,structureId:l,event:f})),T?.length||(T=s.filter(N=>!N.participantId&&!N.bye&&!N.qualifier).map(N=>N.drawPosition)),m||I.push({payload:{drawId:g,structureId:l,drawPosition:d,isPositionAction:!0},willDisableLinks:r,method:$v,type:Td}),i&&y){let N=s.map(P=>P.participantId).filter(Boolean),E={structureIds:t},{completedMatchUps:A}=js({inContext:!0,matchUpFilters:E,drawDefinition:u}),U=pt((A??[]).filter(({matchUpType:P})=>f?.eventType!==Ve||P===Ve)?.map(({sides:P})=>P?.map(gt)).flat().filter(P=>P&&!N.includes(P))),C=a?o?.filter(P=>U?.includes(P.participantId)).map(P=>J(P,void 0,!0)):void 0;return C?.forEach(P=>{let D=(u.entries??[]).find(M=>M.participantId===P.participantId);P.entryPosition=D?.entryPosition}),C?.length&&I.push(nt({payload:{drawId:g,structureId:l,drawPosition:d},willDisableLinks:r,method:SP,type:gs,availableParticipantIds:U,participantsAvailable:C})),{validAssignmentActions:I}}if(T.includes(d)||m){let N;if(S?.length){let A=S.filter(U=>h?.includes(U.participantId));A.sort(qG),N=A.map(U=>U.participantId)}else N=e;let E=a?o?.filter(A=>N.includes(A.participantId)).map(A=>J(A,void 0,!0)):void 0;E?.length&&I.push(nt({payload:{drawId:g,structureId:l,drawPosition:d},willDisableLinks:r,method:SP,type:gs,availableParticipantIds:N,participantsAvailable:E}))}return{validAssignmentActions:I}}function qG(t,e){return t.bye||Ic(t.seedValue)<Ic(e.seedValue)||t.seedValue&&!e.seedValue?-1:(t.seedNumber||0)-(e.seedNumber||0)}function iO({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(N=>N.participantId).filter(Boolean),f=o?.[uo],g=!f?.disableRoundRestrictions&&t[s],I=f?.requireCompletedStructures,{sourceStructureIds:h,relevantLinks:S}=fg({targetRoundNumber:g,linkType:po,drawDefinition:i,structureId:a})||{};h?.length&&d.push(...h);let{sourceStructureIds:T,relevantLinks:y}=fg({targetRoundNumber:g,linkType:zn,drawDefinition:i,structureId:a})||{};T?.length&&d.push(...T);for(let N of S){let E=i.structures?.find(U=>U.structureId===N.source.structureId);if(E?.stage!==at)continue;let A=ei({structureId:N.source.structureId,drawDefinition:i});if(!I||A){let U=E.qualifyingRoundNumber,{matchUps:C}=At({matchUpFilters:{roundNumbers:[U],hasWinningSide:!0},afterRecoveryTimes:!1,tournamentParticipants:e,inContext:!0,structure:E});for(let P of C){let D=P.sides.find(b=>b?.sideNumber===P.winningSide),M=P.matchUpStatus===Nt&&P.sides?.find(({participantId:b})=>b);if(D||M){let{participantId:b,participant:v}=D||M||{};b&&!l.includes(b)&&(v&&n&&u.push(v),p.push(b))}}}}for(let N of y){let E=i.structures?.find(U=>U.structureId===N.source.structureId);if(E?.stage!==at)continue;let A=ei({structureId:N.source.structureId,drawDefinition:i});if(!I||A){let{positionAssignments:U}=Ct({structure:E}),C=U?.map(P=>{let D=P.participantId,M=dt({element:P,name:qo}).extension?.value;return M?{participantId:D,groupOrder:M?.groupOrder}:{}}).filter(({groupOrder:P,participantId:D})=>P===1&&!l.includes(D)).map(({participantId:P})=>P)??[];if(C&&p.push(...C),n){let P=e.filter(({participantId:D})=>C.includes(D));u.push(...P)}}}return p.length&&m.push(nt({payload:{qualifyingParticipantId:void 0,drawPosition:s,structureId:a,drawId:c},method:kv,type:bp,qualifyingParticipantIds:p,qualifyingParticipants:n?u:void 0})),{validAssignmentActions:m,sourceStructureIds:d}}function sO({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=P=>!t||P.participantId||P.qualifier||P.bye,I=n?.filter(P=>P!==p&&!(u&&a.includes(P))),h=i?.filter(P=>g(P)&&I?.includes(P.drawPosition))??[],S=h.map(({drawPosition:P})=>P),{matchUps:T}=At({afterRecoveryTimes:!1,inContext:!0,drawDefinition:c,structure:d,event:f}),y=T.filter(({drawPositions:P})=>Fe(P,S)),N=Object.assign({},...y.map(P=>P.sides?.filter(({sourceDrawPositionRange:D})=>D).map(({drawPosition:D,sourceDrawPositionRange:M})=>({[D]:M}))).flat()),E=h.map(P=>P.participantId).filter(Boolean),A=(r??[]).filter(P=>E.includes(P.participantId)),U=Object.assign({},...A.map(P=>({[P.participantId]:P}))),C=h.map(P=>{let D=U?.[P.participantId],M=N[P.drawPosition];return nt({...P,participant:s?J(D,!1,!0):void 0,sourceDrawPositionRange:M})});return C.length?{validSwapAction:{payload:{drawId:l,structureId:m,drawPositions:[p]},willDisableLinks:e,method:Wv,type:Tg,availableAssignments:C}}:{}}function GS(t){let e=ut(t,[{event:!0,drawDefinition:!0,structureId:!0}]);if(e.error)return e;let{policyDefinitions:r,returnParticipants:n=!0,provisionalPositioning:o,tournamentRecord:i,drawDefinition:s,drawPosition:a,event:c}=t,u=t.tournamentParticipants??(i&&Yt({withIndividualParticipants:!0,tournamentRecord:i}).participants)??[],p=st({structureId:t.structureId,drawDefinition:s});if(p.error)return p;let m=p.containingStructure||p.structure;if(!m)return{error:Gt};let d=m.structureId;if(p=Da({drawDefinition:s,structureId:d}),a===void 0&&!p.isAdHoc)return{error:Ns};if(p.isAdHoc)return yd(t);if(p.error)return p;let{drawPositionInitialRounds:l,inactiveDrawPositions:f,activeDrawPositions:g,byeDrawPositions:I}=p,h=ht({tournamentRecord:i,drawDefinition:s,structure:m,event:c}).appliedPolicies??{};Object.assign(h,r??{});let{actionsPolicy:S,enabledStructures:T,actionsDisabled:y}=RS({actionType:yg,appliedPolicies:h,drawDefinition:s,structure:m}),N=S?.activePositionOverrides||[],{sourceStructureIds:E}=fg({finishingPosition:Fs,targetRoundNumber:1,linkType:zn,drawDefinition:s,structureId:d})||{},A;E?.length&&(A=E.reduce((z,q)=>ei({structureId:q,drawDefinition:s})&&z,!0));let U=E.length,C=E.length&&!A,{policyActions:P}=bS({enabledStructures:T,drawDefinition:s,structure:m}),D=![at,tt].includes(m.stage)||m.stageSequence!==1,{drawId:M}=s,b=[],{assignedPositions:v,positionAssignments:O}=de({structure:m}),w=v?.find(z=>z.drawPosition===a);if(!O?.map(z=>z.drawPosition)?.includes(a))return{error:Ds};let{stage:L,stageSequence:x}=m,B=[L];L===He&&B.push(tt),L===tt&&B.push(He);let H=Ii({entryStatuses:Qo,provisionalPositioning:o,drawDefinition:s,stageSequence:x,structureId:d,stages:B}),W=Ei({drawDefinition:s,stages:B}).assignedParticipantIds??[],V=H.filter(z=>!W.includes(z.participantId)).map(z=>z.participantId),Y=I.includes(a),$=g.includes(a);if(y)return{hasPositionAssigned:!!w,info:"Actions Disabled for structure",isActiveDrawPosition:$,isDrawPosition:!0,validActions:[],isByePosition:Y};if(On({policyActions:P,action:gs})&&!$&&O&&!C&&(!w||Y)){let{validAssignmentActions:z}=oO({positionSourceStructureIds:E,unassignedParticipantIds:V,possiblyDisablingAction:D,isWinRatioFedStructure:U,tournamentParticipants:u,positionAssignments:O,returnParticipants:n,appliedPolicies:h,drawDefinition:s,isByePosition:Y,drawPosition:a,structureId:d,event:c});z?.forEach(q=>b.push(q))}if(On({policyActions:P,action:bp})){let{validAssignmentActions:z}=iO({drawPositionInitialRounds:l,tournamentParticipants:u,positionAssignments:O,returnParticipants:n,appliedPolicies:h,drawDefinition:s,drawPosition:a,structureId:d,drawId:M});z?.forEach(q=>b.push(q))}let{participantId:k}=w||{},K=k&&u.find(z=>z.participantId===k);if(w){On({policyActions:P,action:NS})&&!$&&(b.push({type:NS,method:hP,payload:{drawId:M,structureId:d,drawPosition:a},willDisableLinks:D}),Y||b.push({type:hg,method:Vv,payload:{drawId:M,structureId:d,drawPosition:a},willDisableLinks:D}),On({policyActions:P,action:Td})&&!Y&&b.push({type:Td,method:hP,payload:{drawId:M,structureId:d,drawPosition:a,replaceWithBye:!0},willDisableLinks:D}));let z=m.stage===at||m.stage===tt&&m.stageSequence===1;if(!Y&&TP({activePositionOverrides:N,activeDrawPositions:g,action:Ks})&&On({policyActions:P,action:Ks})&&Up({drawDefinition:s,structureId:d,drawPosition:a})&&z){let{seedAssignments:q}=Hr({returnAllProxies:!0,drawDefinition:s,structure:m}),{seedNumber:et,seedValue:Q}=q?.find(it=>it.participantId===k)??{};b.push({type:Ks,method:Kv,participant:K,seedNumber:et,payload:{drawId:M,structureId:d,participantId:k,seedValue:Q}})}if(!Y&&TP({activePositionOverrides:N,activeDrawPositions:g,action:vp})&&On({policyActions:P,action:vp})&&Up({drawDefinition:s,structureId:d,drawPosition:a})&&z){let{seedAssignments:q}=Hr({returnAllProxies:!0,drawDefinition:s,structure:m}),{seedNumber:et}=q?.find(Q=>Q.participantId===k)??{};b.push({method:qv,type:vp,participant:K,seedNumber:et,payload:{participantId:k,structureId:d,drawId:M}})}if(!Y&&k){if(On({policyActions:P,action:zs})){let q={type:zs,method:DS,participant:K,payload:{penaltyCode:void 0,penaltyType:void 0,participantIds:[],notes:void 0,drawId:M}};b.push(q)}if(On({policyActions:P,action:Nu})){let q={type:Nu,method:Yv,participant:K,payload:{participantId:k,otherName:void 0}};b.push(q)}}if(On({policyActions:P,action:Tg})){let{validSwapAction:q}=sO({possiblyDisablingAction:D,tournamentParticipants:u,inactiveDrawPositions:f,activeDrawPositions:g,positionAssignments:O,returnParticipants:n,byeDrawPositions:I,drawDefinition:s,isByePosition:Y,drawPosition:a,structureId:d,structure:m,drawId:M});q&&b.push(q)}}if(On({policyActions:P,action:Ig})&&!C){let{validAlternatesAction:z}=tO({possiblyDisablingAction:D,tournamentParticipants:u,positionAssignments:O,activeDrawPositions:g,returnParticipants:n,appliedPolicies:h,drawDefinition:s,drawPosition:a,validActions:b,structureId:d,structure:m,drawId:M,event:c});z&&b.push(z)}if(On({policyActions:P,action:Sg})&&!C&&O){let{validLuckyLosersAction:z}=nO({sourceStructuresComplete:A,possiblyDisablingAction:D,isWinRatioFedStructure:U,tournamentParticipants:u,activeDrawPositions:g,positionAssignments:O,drawDefinition:s,drawPosition:a,structureId:d,structure:m,drawId:M});z&&b.push(z)}if(K?.participantType===lt&&On({policyActions:P,action:gg})){let{validModifyAssignedPairAction:z}=Qv({tournamentParticipants:u,returnParticipants:n,drawPosition:a,participant:K,drawId:M,event:c});z&&b.push(z)}return{hasPositionAssigned:!!w,isActiveDrawPosition:$,isDrawPosition:!0,isByePosition:Y,validActions:b,...R}}function Mu({policyDefinitions:t,appliedPolicies:e,drawType:r}){let n=t?.[Em]?.drawTypeCoercion,o=e?.[Em]?.drawTypeCoercion;return(typeof n=="boolean"?n:void 0)??(r&&n?.[r])??(typeof o=="boolean"?o:void 0)??(r&&o?.[r])??!0}function Op({tournamentRecord:t,drawDefinition:e,stage:r=tt,structureId:n,structure:o}){if(!t)return{error:j};if(!o&&!e)return{error:X};if(!o&&!n&&e?.structures?.filter(a=>a.stage===r).length===1&&(o=e.structures.find(a=>a.stage===r)),!o&&!n)return{error:Sr};let{error:i,positionAssignments:s}=Ct({drawDefinition:e,structureId:n,structure:o});return{positionAssignments:s??[],structureId:o?.structureId,error:i}}function kS({structureId:t,drawDefinition:e}){if(!e)return{error:X};if(!Re(t))return{error:G};let r=Ws({drawDefinition:e,structureId:t});if(r.error)return r;let n=r.links.target.flatMap(i=>i.target.feedProfile).filter(Boolean),o=!jt([mi,pn,up,pi],n).length;return{...R,valid:o}}function VS({participantsCount:t,participantCount:e}){if(t=t??e,!t)return{error:G};let r=Ki(t);return r?{drawSize:r}:_({result:{error:G},stack:"getEliminationDrawSize",context:{participantsCount:t}})}function Cu(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=Co({tournamentRecord:i,drawDefinition:s,event:a});if(I.error)return _({result:I,stack:c});r=I.policyDefinitions}let p=ft(u);if(u&&!p)return _({result:{error:G},context:{participantsCount:u},stack:c});if(o&&!p)return _({result:{error:VA},stack:c});if(isNaN(n))if(u)({drawSize:n}=VS({participantsCount:u}));else return _({result:{error:qa},stack:c});let m=o&&u||n;if(m&&m>n)return{error:vl};let d=r?.[Nn];if(!d)return{error:RA};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:fA}}function Ad({consideredEntries:t,policyDefinitions:e,tournamentRecord:r,appliedPolicies:n,participantMap:o,enforceGender:i,participants:s,event:a}){if((!s||!o)&&r&&({participants:s,participantMap:o}=Yt({tournamentRecord:r})),!s)return{error:Ka};if(!Array.isArray(s))return{error:G};if(!a)return{error:Dt};let c=e?.[Qe]??n?.[Qe]??ds[Qe],u=(i??c?.participants?.enforceGender)!==!1,{eventType:p,gender:m}=a,d=p===yi,l=p===jr&&xt||d&&lt||Tt,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=$G({participant:S,participantType:l,eventType:p,entryStatusMap:f}),y=KG({genderEnforced:u,participantMap:o,eventGender:m,participant:S,isDoubles:d,mismatch:T});return T||!y});if(h.length){let S=h.map(T=>T.participantId);return{error:UA,invalidParticipantIds:S}}return{...R,valid:!0}}function $G({participant:t,participantType:e,eventType:r,entryStatusMap:n}){let o=n[t.participantId],i=r&&[yi,jr].includes(r)&&t.participantType===Tt&&(Ys(o)||o===Jn);return t.participantType!==e&&!i}function KG(t){let{participant:e,participantMap:r,eventGender:n,mismatch:o,isDoubles:i,genderEnforced:s}=t,a=!o&&i&&pt(e?.individualParticipantIds?.map(m=>r?.[m]?.participant?.person?.sex).filter(Boolean)??[])||[],c=!n||!a?.length||In===n||[te,ce].includes(n)&&a[0]===n||Ur===n&&(a.length==1&&e.individualParticipantIds?.length===1||a.length===2),u=e?.person?.sex,p=!e?.person||!n||[In,Ur].includes(n)||[te,ce].includes(n)&&u===n;return!s||c&&p}function BS({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,y,N;for(let E of(I||[]).sort(u)){let A=lm(E.drawSize||E.participantsCount),{qualifyingRoundNumber:U,structureOptions:C,matchUpFormat:P,structureName:D,structureId:M,drawType:b}=E,v=E.matchUpType,O=E.qualifyingPositions||zG({drawSize:A,qualifyingRoundNumber:U}),w,F,L;if(!ft(A))return _({result:{error:qa},stack:i});let x=t.length>1?`${f}-`:"",B=I.length>1||x?h:"",H=D||(x||B?`${$e(at)} ${x}${B}`:$e(at));if(b===fn){let{structures:W,groupCount:V,maxRoundNumber:Y}=Ma({structureName:E.structureName||H,structureId:M||o?.pop(),stage:at,structureOptions:C,appliedPolicies:e,stageSequence:h,matchUpType:v,roundTarget:f,drawSize:A,idPrefix:r,isMock:n,uuids:o});S=V,w=Y,F=W[0],l=[1]}else({drawSize:A,matchUps:L,roundLimit:w}=hn({qualifyingRoundNumber:U,qualifyingPositions:O,matchUpType:v,drawSize:A,idPrefix:r,isMock:n,uuids:o})),F=on({structureName:E.structureName||H,structureId:M||o?.pop(),qualifyingRoundNumber:w,stage:at,matchUpFormat:P,stageSequence:h,matchUpType:v,roundLimit:w,matchUps:L}),f&&yt({extension:{name:ln,value:f},element:F}),S=L?.filter(W=>W.roundNumber===w)?.length||0;if(h>1){let{link:W}=Ca({sourceStructureId:y,sourceRoundNumber:T,targetStructureId:F.structureId,finishingPositions:N===zn?[1]:void 0,linkType:N});c.push(W),m+=(A||0)-S}else m+=A||0;N=b===fn?zn:po,y=F.structureId,T=w,a.push(F),h+=1}d+=S,s.push({qualifiersCount:S,finalQualifyingRoundNumber:T,finalQualifyingStructureId:y,finishingPositions:l,roundTarget:f,linkType:N}),f+=1}return{qualifiersCount:d,qualifyingDrawPositionsCount:m,qualifyingDetails:s,structures:a,...R,links:c}}function zG({drawSize:t,qualifyingRoundNumber:e}){let r=t,n=0;for(;n<e;)r=Math.floor(r/2),n+=1;return r}function HS(t){let{drawTypeCoercion:e,enforceMinimumDrawSize:r}=t,n=ct(t.drawSize),o=e&&(typeof e=="boolean"||e<=2)&&n===2&&mo||t.drawType||mo,i=YE.includes(o);if(n&&i){if(e&&(typeof e=="boolean"&&n<4||n<=e))o=mo;else if(n<4&&r)return{..._({context:{enforceMinimumDrawSize:r,drawSize:n,drawType:o},result:{error:Hu},stack:"getCoercedDrawType"}),drawType:o}}return{drawType:o}}function aO(t){let{drawDefinition:e,structureOptions:r,requireSequential:n}=t,o={structureName:$e(tt),...t,stage:tt},{structures:i,groupCount:s,groupSize:a}=Ma(o);if(s<1)return{error:nE};let c=r?.playoffGroups||[{finishingPositions:[1],structureName:$e(ue)}],[u]=i,{structures:p,links:m}=mS({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 cO({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?pn:mi,f=1+m;return{linkType:Qn,source:{roundNumber:f,structureId:t.structureId},target:{feedProfile:l,roundNumber:p,structureId:e.structureId}}}),c={linkType:po,source:{roundNumber:s,structureId:e.structureId},target:{feedProfile:pn,roundNumber:i,structureId:t.structureId}},u=[{linkType:po,source:{roundNumber:i,structureId:t.structureId},target:{feedProfile:pn,roundNumber:1,structureId:r.structureId}},{linkType:Qn,source:{roundNumber:i,structureId:t.structureId},target:{feedProfile:pn,roundNumber:1,structureId:r.structureId}}];return[...a,c,...u]}function uO({structureName:t,matchUpType:e,idPrefix:r,drawSize:n,isMock:o,uuids:i}){let s=[],{matchUps:a}=ri({linkFedFinishingRoundNumbers:[1],drawSize:n+1,matchUpType:e,idPrefix:r,isMock:o}),c=ls({structureName:t||$e(tt),structureId:i?.pop(),stageSequence:1,stage:tt,matchUpType:e,matchUps:a});s.push(c);let u=n/2,{matchUps:p}=ri({finishingPositionOffset:u,idPrefix:r&&`${r}-c`,drawSize:n-1,isConsolation:!0,matchUpType:e,isMock:o,uuids:i}),m=ls({structureName:$e(jE),matchUps:p,structureId:i?.pop(),stage:He,stageSequence:2,matchUpType:e});s.push(m);let{matchUps:d}=hn({idPrefix:r&&`${r}-p1t2`,drawSize:2,matchUpType:e,isMock:o}),l=ls({structureName:$e(WE),matchUps:d,structureId:i?.pop(),stageSequence:3,stage:ue,matchUpType:e});s.push(l);let f=cO({mainStructure:c,consolationStructure:m,deciderStructure:l});return{structures:s,links:f,...R}}function pO(t){let{qualifyingRoundNumber:e,finishingPositionOffset:r,qualifyingPositions:n,matchUpType:o,idPrefix:i,drawSize:s,isMock:a,uuids:c}=t;if(!ft(s)||s<2)return{matchUps:[],roundsCount:0};if(En(s))return hn(t);let u=QG(s),p=u.shift(),m=Z(1,(p?.participantsCount||0)+1).map(I=>({drawPosition:I})),d=[],l=1;({matchUps:d}=Np({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(y=>{let N=ad({roundPosition:y,roundNumber:l,idPrefix:i,uuids:c});return{roundPosition:y,roundNumber:l,matchUpId:N}});d.push(...T),l++}let g=l-1;return d=Ua({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 QG(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 WS(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(),u=t.appliedPolicies??ht(t),p=t.policyDefinitions?.[rc]||u?.[rc];t.skipRounds=t.skipRounds||i<=4&&(p?.feedFromMainFinal?0:1)||0;let m=t.structureName??e?.["0"]?.name??$e(tt),d=()=>{let{matchUps:f}=hn(t);return{structures:[on({stageSequence:r,structureName:m,matchUpType:o,structureId:c,matchUps:f,stage:n})],links:[],...R}};return{generators:{[Xr]:()=>({structures:[on({finishingPosition:Fs,stageSequence:r,structureName:m,matchUps:[],matchUpType:o,structureId:c,stage:n})],links:[],...R}),[xi]:()=>{let{matchUps:f}=pO(t);return{structures:[on({stageSequence:r,structureName:m,matchUpType:o,structureId:c,matchUps:f,stage:n})],links:[],...R}},[mo]:()=>d(),[tu]:()=>uO(t),[Jc]:()=>yc({...t,roundOffsetLimit:3,playoffAttributes:e??mf}),[Zc]:()=>yc({...t,roundOffsetLimit:2,playoffAttributes:e??df}),[ue]:()=>yc(t),[Ia]:()=>{let{matchUps:f}=ri({drawSize:i,uuids:s,matchUpType:o});return{structures:[on({stageSequence:r,structureName:m,matchUpType:o,structureId:c,stage:tt,matchUps:f})],links:[],...R}},[pp]:()=>aS(t),[eu]:()=>Ec({...t,feedRounds:1,fmlc:!0}),[HE]:()=>Ec({...t,feedRounds:1}),[rh]:()=>Ec({...t,feedsFromFinal:1}),[nh]:()=>Ec({...t,feedsFromFinal:2}),[oh]:()=>Ec({...t,feedsFromFinal:3}),[mp]:()=>Ec(t),[pf]:()=>uS(t),[fn]:()=>Ma(t),[lo]:()=>aO(t)}}}function Ed(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??Mu({appliedPolicies:n,drawType:t.drawType}),m="generateDrawStructuresAndLinks",d=HS({drawType:t.drawType,enforceMinimumDrawSize:e,drawTypeCoercion:p,drawSize:u});if(d.error)return d;let l=d.drawType,f=[],g=[],I=t?.matchUpType??Kt,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:V})=>W===tt&&V===1),y=i?.links?.filter(W=>W.target.structureId===T?.structureId&&S?.includes(W.source.structureId)),N=(W,V)=>{if(W.linkType===zn&&V?.structures){let Y=W.source.finishingPositions||[];return V.structures.length*Y.length}else if(W.linkType===po&&V?.matchUps?.length){let Y=W.source.roundNumber;return V.matchUps.filter(({roundNumber:k})=>k===Y).length}},E=h?.map(W=>{let V=y?.find(z=>z.target.structureId===W.structureId),Y=Ct({structure:W})?.positionAssignments?.length??0;if(!V)return Y;let $=V?.source.structureId,k=i.structures?.find(z=>z.structureId===$),K=N(V,k)||0;return Y-K}).filter(Boolean).reduce((W,V)=>W+V,0),A=y?.map(W=>{let V=W.source.structureId,Y=h?.find($=>$.structureId===V);return N(W,Y)}).filter(Boolean).reduce((W,V)=>W+V,0),U=!!(T&&!T?.matchUps?.length);if(h?.length&&!U)return{error:MI};let C=!h?.length&&t.qualifyingProfiles,P=C?.length&&BS({idPrefix:t.idPrefix,qualifyingProfiles:C,appliedPolicies:n,isMock:a,uuids:c});if(P?.error)return P;let{qualifyingDrawPositionsCount:D,qualifyingDetails:M,qualifiersCount:b}=P||{qualifyingDrawPositionsCount:E,qualifiersCount:A};D&&(P?.structures&&f.push(...P.structures),P?.links&&g.push(...P.links)),Object.assign(t,nt({drawSize:u,matchUpType:I,tieFormat:s}));let v=l!==Xr&&(!u||u<2||!o&&![Ia,xi].includes(l)&&([lo,fn].includes(l)&&u<3||![fn,lo].includes(l)&&!En(u)));if(v&&!D)return _({context:{drawSize:u,invalidDrawSize:v},result:{error:Hu},stack:m});let{generators:O,error:w}=WS(t);if(w)return{error:w};let F=O[l];if(!F)return{error:Tl};let L=F?.();if(L.error)return L;let{structures:x,links:B}=L;if(x?.length){let W=x.find(({stage:V,stageSequence:Y})=>V===tt&&Y===1);if(T&&W){if(U){let V=W.structureId;if(W.structureId=T.structureId,B?.length)for(let Y of B)Y.source.structureId===V&&(Y.source.structureId=T.structureId),Y.target.structureId===V&&(Y.target.structureId=T.structureId)}else if(!r)return{error:MI}}f.push(...x)}f.sort(di),B?.length&&g.push(...B);let H=L.structures.find(({stage:W,stageSequence:V})=>W===tt&&V===1);for(let W of M||[]){let{finalQualifyingRoundNumber:V,finalQualifyingStructureId:Y,roundTarget:$,finishingPositions:k,linkType:K}=W,z=H&&Ca({targetStructureId:H.structureId,sourceStructureId:Y,sourceRoundNumber:V,finishingPositions:k,targetEntryRound:$,linkType:K})?.link;if(z?.error)return z;z&&g.push(z)}return y&&g.push(...y),{...R,qualifyingResult:{qualifyingDrawPositionsCount:D,qualifiersCount:b},structures:f,links:g}}function Ud(t){let{modifyOriginal:e=!0,stageSequence:r=1,isMock:n}=t||{},o="generateDrawTypeAndModifyDrawDefinition";if(!t.drawDefinition)return _({result:{error:X},stack:o});let i=e?t.drawDefinition:J(t.drawDefinition,!1,!0),{tieFormat:s,matchUpType:a}=t;if(s){let T=ar({tieFormat:s});if(T.error)return T}s=Je(s??Ye({drawDefinition:i})?.tieFormat),a=a??(i.matchUpType||Kt),t.tieFormat=s,t.matchUpType=a;let c=yp({drawDefinition:i,stage:tt});t.drawSize=t.drawSize??c,!c&&t.drawSize&&Dp({drawSize:t.drawSize,drawDefinition:i,stageSequence:r,stage:tt});let u=ye({drawDefinition:i}).drawMatchUps.map(fe),p=Ed(t);if(p.error)return _({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&&!yp({stage:at,drawDefinition:i})){let y=Dp({drawSize:l.qualifyingDrawPositionsCount,stage:at,drawDefinition:i});if(y.error)return y}if(f){let T=iS({qualifiersCount:f,drawDefinition:i,stage:tt});if(T.error)return T}let g=t.drawSize??c;Object.assign(t,nt({drawSize:g,matchUpType:a,tieFormat:s}));let{matchUps:I,matchUpsMap:h}=ne({drawDefinition:i});s&&I?.forEach(T=>{if(!u.includes(T.matchUpId)){let{tieMatchUps:y}=Ra({tieFormat:s,matchUp:T,isMock:n});Object.assign(T,{tieMatchUps:y,matchUpType:a})}});let{inContextDrawMatchUps:S}=Gi({drawDefinition:i,matchUpsMap:h});return Ot({tournamentId:t.tournamentRecord?.tournamentId,drawDefinition:i}),{inContextDrawMatchUps:S,drawDefinition:i,matchUpsMap:h,...R,structures:m,matchUps:I,links:d}}function Dc(t){let{tournamentRecord:e,scaleAttributes:r,participantId:n}=t,o=t.tournamentRecords||e&&{[e.tournamentId]:e}||{};if(!n)return{error:ee};let{participant:i,tournamentId:s}=fo({tournamentRecords:o,tournamentRecord:e,participantId:n});return i?{...So({participant:i,scaleAttributes:r}),tournamentId:s}:{error:re}}function Oa(t){let{removePriorValues:e,tournamentRecord:r,participantId:n,scaleItem:o}=t,i,s;if(!mO({scaleItem:o}))return{error:qu};if(n&&Array.isArray(r.participants)&&(s=r.participants.find(a=>a.participantId===n),s)){let a=dO({removePriorValues:e,participant:s,scaleItem:o});if(a.error)return a;i=!a.valueChanged;let{topics:c}=vr();c.includes(Xe)&&St({topic:Xe,payload:{tournamentId:r.tournamentId,participants:[s]}})}return i&&{...R,info:Vl,existingValue:o?.scaleValue}||s&&{...R,newValue:o?.scaleValue}||{error:re}}function bP(t){let{scaleItemsWithParticipantIds:e=[],removePriorValues:r,tournamentRecord:n,auditData:o,context:i}=t;if(!n)return{error:j};if(!n.participants)return{error:Ka};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(mO({scaleItem:l}))Array.isArray(a[d])||(a[d]=[]),a[d].push(l);else return{error:qu}}n.participants.forEach(m=>{let{participantId:d}=m||{};Array.isArray(a[d])&&a[d].forEach(l=>{dO({participant:m,scaleItem:l,removePriorValues:r}),c.push(m),s++})});let u=s?void 0:vs,{topics:p}=vr();if(p.includes(Xe)&&s&&St({topic:Xe,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:gf,itemValue:l};if(f&&(g.itemSubTypes=f),d||m){let{drawDefinition:I,event:h}=je({tournamentRecord:n,eventId:m,drawId:d});d&&sg({drawDefinition:I,timeItem:g}),m&&Hi({event:h,timeItem:g})}else Bi({tournamentRecord:n,timeItem:g})}}return o&&p.includes(ha)&&St({topic:ha,payload:o}),nt({...R,modificationsApplied:s,info:u})}function mO({scaleItem:t}){let e=t&&Object.keys(t),r=["scaleType","eventType","scaleName"];return!!(r.filter(o=>e?.includes(o)).length===r.length)}function dO({removePriorValues:t,participant:e,scaleItem:r}){if(!e)return{error:vi};let n=r&&Object.keys(r),o=["scaleType","eventType","scaleName"];if(!(o.filter(p=>n.includes(p)&&r[p]).length===o.length))return{error:qu};let s=new Date().toISOString();e.timeItems||(e.timeItems=[]);let{scaleItem:a}=So({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=[Ji,p,m,d].join("."),f=nt({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 XG=(t=0)=>250/Math.pow(t+5,.4),JG=()=>1;function ZG(t=3,e=2){let r=t/e;return isNaN(r)?Pd.kDefault():r}var Pd={nSpread:400,diffThreshold:.125,kCalc:XG,kMultiplier:ZG,kDefault:JG};function jS(t){let{winnerRating:e,loserRating:r}=t,{ratings:n=Ke,winnerCountables:o=1,loserCountables:i=0,ratingType:s=To,maxCountables:a,countables:c}=t||{},u=n?.[s];if(!u)return{error:rt};let p=u.range||t.ratingRange;e=e||u.defaultInitialization,r=r||u.defaultInitialization;let m=p[0]>p[1],d=u.decimalsCount||0,l=m?p.slice().reverse():p,f=(w,F)=>parseFloat(F)>=Math.min(...w)&&parseFloat(F)<=Math.max(...w);(!f(p,e)||!f(p,r))&&(f(p,e)||(e=u.defaultInitialization),f(p,r)||(r=u.defaultInitialization));let g=yu({targetRange:Ke[To].range,sourceRange:l,value:m?p[0]-e:e}),I=yu({targetRange:Ke[To].range,sourceRange:l,value:m?p[0]-r:r}),h=(w,F)=>1/(1+Math.pow(10,(F-w)/Pd.nSpread)),S=h(g,I),T=h(I,g),y=Pd.kCalc(o),N=Pd.kCalc(i),E=Pd.kMultiplier(a,c),A=g+E*y*(1-S),U=I+E*N*(0-T),C=yu({sourceRange:Ke[To].range,value:A,targetRange:l}),P=yu({sourceRange:Ke[To].range,value:U,targetRange:l}),D=m?p[0]-C:C,M=parseFloat(parseFloat(D).toFixed(d)),b=m?p[0]-P:P,v=parseFloat(parseFloat(b).toFixed(d)),O=Math.max(...p)?Math.abs(e-r)/Math.max(...p):0;return(C>P&&O>Pd.diffThreshold||M<0||v<0)&&(M=e,v=r),{newWinnerRating:M,newLoserRating:v}}var lO=t=>t?.reduce((e,r)=>(r.winningSide&&(e[r.winningSide-1]+=1),e),[0,0])||[0,0];function YS(t){let{removePriorValues:e=!0,tournamentRecord:r,ratingType:n=To,considerGames:o,matchUpIds:i,asDynamic:s}=t;if(!r)return{error:j};if(!Array.isArray(i))return{error:An};if(typeof n!="string")return{error:G,ratingType:n};if(!Ke[n])return{error:G};let a=Ke[n],{accessor:c}=a,u={},p=t.matchUps??le({matchUpFilters:{matchUpIds:i,matchUpStatuses:ae},tournamentRecord:r,inContext:!0}).matchUps??[];p.sort(Ai);for(let d of p){let{endDate:l,matchUpFormat:f,score:g,sides:I,winningSide:h}=d,S=d.matchUpType,T={eventType:S,scaleName:n,scaleType:Xi},y=`${n}.${VI}`,N={scaleName:y,eventType:S,scaleType:Xi},E=Object.assign({},...(I??[]).map(w=>{let{sideNumber:F,participant:L}=w;return F&&{[F]:[L?.participantId,...L?.individualParticipantIds??[]].filter(Boolean).flat()}})),A=s?y:n,U=Object.assign({},...Object.values(E).flat().map(w=>{let{scaleItem:F}=Dc({scaleAttributes:N,tournamentRecord:r,participantId:w}),{scaleItem:L}=Dc({tournamentRecord:r,scaleAttributes:T,participantId:w}),x=c?{[c]:void 0}:void 0;return w&&{[w]:F??L??{scaleName:A,eventType:S,scaleDate:l,scaleType:Xi,scaleValue:x}}})),C=f?rr(f):{},P=C?.bestOf||1,D=C?.setsTo||1,M=o?P&D:P,b=g?.sets&&lO(g.sets)||h===1&&[1,0]||[0,1],v=h?E[h]:[],O=h?E[3-h]:[];for(let w of v){let F=U[w]?.scaleValue,L=typeof F=="object"?F[c]:F;for(let x of O){let B=U[x]?.scaleValue,H=typeof B=="object"?B[c]:B,W=h?b[h]:[0,0],V=h?b[3-h]:[0,0],{newWinnerRating:Y,newLoserRating:$}=jS({winnerCountables:W,loserCountables:V,maxCountables:M,winnerRating:L,loserRating:H,ratingType:n}),k=c?{...F,[c]:Y}:Y,K=c?{...B,[c]:$}:$;U[w].scaleValue=k,U[x].scaleValue=K;let z=Oa({participantId:w,removePriorValues:e,tournamentRecord:r,scaleItem:{...U[w],scaleName:A}});if(z.error||(z=Oa({participantId:x,removePriorValues:e,tournamentRecord:r,scaleItem:{...U[x],scaleName:A}}),z.error))return z}}Object.assign(u,U)}let m=p.map(({matchUpId:d})=>d);return{...R,modifiedScaleValues:u,processedMatchUpIds:m}}function Ru(t){let{matchUpIds:e=[],drawDefinition:r,roundNumber:n,newRound:o,isMock:i,event:s}=t;if(typeof r!="object")return{error:X};let{participantIdPairings:a,matchUpsCount:c}=t,u=Sd(t);if(u.error)return _({result:u});let{lastRoundNumber:p,availableMatchUpsCount:m=0,roundMatchUpsCount:d=0}=u;if(!c)o?c=d:m>0&&(c=m);else if(c>d&&t.restrictMatchUpsCount!==!1)return _({result:{error:G,info:"matchUpsCount error",context:{roundMatchUpsCount:d}}});if(a&&!Array.isArray(a)||c&&!ft(c)||e&&!Array.isArray(e)||!a&&!c)return{error:G,info:"matchUpsCount or pairings error"};if(c&&t.restrictMatchUpsCount!==!1&&c>32)return{error:G,info:"matchUpsCount must be less than 33"};if(n&&!t.ignoreLastRoundNumber&&n-1>(p||0))return{error:G,info:"roundNumber error"};let l=n??(o&&(p??0)+1||p||1);a=a??Z(0,c).map(()=>({participantIds:[void 0,void 0]}));let f=I=>{if(!t.idPrefix)return;let h=r.drawId,S=t.idPrefix??"ah";return`${h}-${S}-${l}-${I}`},g=a?.map((I,h)=>{let S=I?.participantIds??[void 0,void 0];S.push(void 0,void 0);let y=S.slice(0,2).map((E,A)=>nt({sideNumber:A+1,participantId:E})),N=e[h]??f(h)??Mt();return{roundNumber:l,matchUpStatus:Qt,matchUpId:N,sides:y}});if(g?.length){let I=Ye({drawDefinition:r,event:s})?.tieFormat;I&&g.forEach(h=>{let{tieMatchUps:S}=Ra({tieFormat:I,matchUp:h,isMock:i});Object.assign(h,{tieMatchUps:S,matchUpType:Bt})})}return{roundNumber:l,matchUpsCount:g?.length??0,matchUps:g,...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=[vP(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(y=>{l+=1;let N=_a(S,y.opponent);if(!I.includes(N)){let E=fO({stipulated:[[S,y.opponent]],actorsCount:s.length,valueSortedPairings:e,pairingValueMap:i,deltaObjects:o,valueObjects:n});if(!u.includes(vP(E))){u.push(vP(E)),a.push(E);let{maxDelta:A,value:U}=E;A<m.maxDelta&&(m=E),(U<p||U===p&&Math.round(Math.random()))&&(p=U),I.push(N),d+=1}}}),a=a.filter(y=>Math.abs(y.value-p)<5)}),a.sort((S,T)=>S.maxDiff-T.maxDiff);let h=Gr(a);return{candidatesCount:d,deltaCandidate:m,maxIterations:t,iterations:l,candidate:h}}function vP(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=_a(l,f),I=r[g];a.push({participantIds:d,value:I}),c+=r[g]}),Te(t,i).map(d=>pr(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=_a(f,g),h=n[I];return h>d?h:d},0),m=a.reduce((d,l)=>{let[f,g]=l.participantIds,I=_a(f,g),h=o[I];return h>d?h:d},0);return{value:c,participantIdPairings:a,maxDelta:p,maxDiff:m}}function _a(t,e){return[t,e].sort(fu).join("|")}function OP({participantIds:t}){let e={},r=[];t.forEach(o=>{e[o]=t.filter(i=>i!==o),e[o].forEach(i=>{let s=_a(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(gt);if(n.length===2){let[o,i]=n,s=_a(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=_a(o,i);return{opponent:i,value:e[s]}}return{pairingValues:r}}var tk=0;function SO({tournamentParticipants:t,adHocRatings:e,eventType:r,scaleName:n,pairing:o}){let i=Ke[n]?.defaultInitialization??tk;return o.split("|").map(s=>{if(r===Jr){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 TO({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=SO({tournamentParticipants:t,adHocRatings:e,scaleName:c,eventType:a,pairing:h}),T=typeof u=="number"&&u||.5,y=u&&(Math.round(Math.random())?T:T*-1)||0,N=Math.abs(S[0]-S[1])+y,E=Math.abs(S[0]-S[1]);i[h]=E,s[h]||(s[h]=0),s[h]+=N?Math.pow(N,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 ek=100,rk=100,nk=4e3;function Dd({encounterValue:t=ek,sameTeamValue:e=rk,maxIterations:r=nk,generateMatchUps:n=!0,ignoreLastRoundNumber:o,iterationMatchUps:i,tournamentRecord:s,dynamicRatings:a,participantIds:c,drawDefinition:u,adHocRatings:p,salted:m=.5,roundNumber:d,structureId:l,matchUpIds:f,eventType:g,structure:I,scaleName:h,idPrefix:S,isMock:T,event:y}){if(!u)return{error:X};if(!I&&!l)return{error:Gt};if(I||(I=st({drawDefinition:u,structureId:l}).structure),!Pt(I))return{error:Oo};if(!c?.length)return{error:Eo};let N=[...i??[],...I?.matchUps??[]],{encounters:E}=IO({matchUps:N}),A=s?.participants??[];if(a){let H=pt(I?.matchUps?I.matchUps.map(({roundNumber:V})=>V):[]),W=Math.max(...H,0);if(W){let V=I?.matchUps?.filter(({roundNumber:Y})=>Y===W).map(({matchUpId:Y})=>Y);YS({ratingType:h||y?.category?.ratingType,tournamentRecord:s,asDynamic:!0,matchUpIds:V})}}let{valueObjects:U}=ok({tournamentParticipants:A,encounterValue:t,sameTeamValue:e,encounters:E}),{uniquePairings:C,possiblePairings:P,deltaObjects:D}=OP({participantIds:c}),M={tournamentParticipants:A,possiblePairings:P,drawDefinition:u,participantIds:c,uniquePairings:C,maxIterations:r,adHocRatings:p,deltaObjects:D,valueObjects:U,eventType:g,scaleName:h,structure:I,salted:m},{candidatesCount:b,participantIdPairings:v,iterations:O,candidate:w}=TO(M);if(!b)return{error:$u};let F,L;if(n){let H=Ru({structureId:I?.structureId,ignoreLastRoundNumber:o,participantIdPairings:v,newRound:!0,drawDefinition:u,roundNumber:d,matchUpIds:f,idPrefix:S,isMock:T,event:y});if(H.error)return H;F=H.roundNumber,L=H.matchUps}let{maxDelta:x,maxDiff:B}=w;return{roundNumber:F,participantIdPairings:v,candidatesCount:b,...R,iterations:O,matchUps:L,maxDelta:x,maxDiff:B}}function ok({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===xt);if(i)for(let s of i){let a=s.individualParticipantIds??[],{uniquePairings:c}=OP({participantIds:a});for(let u of c)o[u]||(o[u]=0),o[u]+=n}return{valueObjects:o}}function qS(t){let{drawType:e=mo,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:X};let m=We,d=Ii({stageSequence:1,drawDefinition:p,stage:m}),l=[fn,tu,lo].includes(e)?d.length:Ki(d.length);if(!i&&e===Ia&&d.length<2||e===fn&&d.length<3)return{error:Hu};let{tieFormat:f,matchUpType:g}=t;if(f){let M=ar({tieFormat:f});if(M.error)return M}f=Je(f??Ye({drawDefinition:p})?.tieFormat),g=g??p.matchUpType??Kt;let{structures:I}=Gn({stageSequence:1,drawDefinition:p,stage:m});if(I.length>1)return{error:PA};if(I?.[0]?.matchUps?.length)return{error:Hl};let S=I?.[0]?.structureId;Object.assign(t,nt({structureName:t.structureName??$e(We),structureId:S,matchUpType:g,tieFormat:f,drawSize:l,stage:m}));let T=WS(t);if(T.error)return T;let y=T.generators[e];if(!y)return{error:Tl};let N=y?.();if(N.error)return N;let{structures:E,links:A}=N,U=E.map(M=>At({structure:M}).matchUps).flat();f&&U.forEach(M=>{let{tieMatchUps:b}=Ra({matchUp:M,tieFormat:f,isMock:c});Object.assign(M,{tieMatchUps:b,matchUpType:g})}),(!n||!r)&&(p=J(p,!1,!0)),p.links||(p.links=[]),A.length&&p.links.push(...A);let C=E.map(({structureId:M})=>M);p.structures||(p.structures=[]);let P=p.structures.map(({structureId:M})=>M);p.structures=p.structures.map(M=>C.includes(M.structureId)?E.find(({structureId:b})=>b===M.structureId):M);let D=E.filter(({structureId:M})=>!P.includes(M));return D.length&&p.structures.push(...D),s&&Sc({seedingProfile:t.seedingProfile,applyPositioning:n,tournamentRecord:o,drawDefinition:p,structureId:S,placeByes:a,drawSize:l,event:u}),r&&Ot({drawDefinition:p}),{links:A,structures:E,...R}}var Mg={};Zt(Mg,{addGame:()=>kP,addPoint:()=>GP,addSet:()=>BP,addShot:()=>VP,analyzeSet:()=>Ou,calculateHistoryScore:()=>wP,checkScoreHasValue:()=>Ie,checkSetIsComplete:()=>wp,clearHistory:()=>FP,generate:()=>xP,generateScoreString:()=>Go,generateTieMatchUpScore:()=>Pc,getSetComplement:()=>Ng,getTiebreakComplement:()=>kp,helpers:()=>hD,isValidMatchUpFormat:()=>Tr,keyValueScore:()=>mD,mutate:()=>YP,parseMatchUpFormat:()=>rr,parseScoreString:()=>Od,query:()=>SD,redo:()=>HP,reverseScore:()=>_P,setServingSide:()=>LP,stringifyMatchUpFormat:()=>Cp,tidyScore:()=>ID,umo:()=>jP,undo:()=>WP,validateScore:()=>Dg,validateTieFormat:()=>ar});var xP={};Zt(xP,{generateScoreString:()=>Go,generateTieMatchUpScore:()=>Pc,reverseScore:()=>_P});function Go(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:rt,info:"missing sets"};let u=i&&rr(i),{bestOf:p,finalSetFormat:m,setFormat:d}=u??{},f=n||!(!e||!a||a===1),g=r?ik({matchUpStatus:o}):"",I=c?.sort(sk).map(h).filter(Boolean).join(" ")||"";if(!g)return I;if(a===2)return`${g} ${I}`;return`${I} ${g}`;function h(S){let y=p&&S.setNumber===p&&m?m:d,N=x=>Jt(x?.side1Score)||Jt(x?.side2Score),E=x=>Jt(x?.side1TiebreakScore)||Jt(x?.side2TiebreakScore),A=y?.tiebreakSet||!N(S)&&E(S),{side1Score:U,side2Score:C,side1TiebreakScore:P,side2TiebreakScore:D}=S,M=P||(Jt(P)||s?0:""),b=D||(Jt(D)||s?0:"");if(A)return`[${(f?[b,M]:[M,b]).join("-")}]`;let v=Math.min(M,b),O=v?`(${v})`:"",w=U||(Jt(U)||s?0:""),F=C||(Jt(C)||s?0:""),L=f?`${[F,w].join("-")}${O}`:`${[w,F].join("-")}${O}`;return["-"," "].includes(L)&&(L=""),L}}function ik({matchUpStatus:t}){let e={[er]:"RET",[vt]:"WO",[Ne]:"DF/DF",[ge]:"WO/WO",[Zi]:"SUS",[Ar]:"ABN",[bt]:"DEF",[Qc]:"DR"};return t&&e[t]||""}function sk(t,e){return t.setNumber-e.setNumber}function _P(t){if(!t?.score)return{error:rt};let{sets:e}=t.score,r=e.map(i=>{let{side1TiebreakScore:s,side2TiebreakScore:a,winningSide:c,side1Score:u,side2Score:p,setNumber:m}=i;return nt({winningSide:c?3-c:void 0,side1TiebreakScore:a,side2TiebreakScore:s,side1Score:p,side2Score:u,setNumber:m})}),n=Go({sets:r}),o=Go({sets:r,reversed:!0});return{reversedScore:{sets:r,scoreStringSide1:n,scoreStringSide2:o},...R}}var YP={};Zt(YP,{addGame:()=>kP,addPoint:()=>GP,addSet:()=>BP,addShot:()=>VP,calculateHistoryScore:()=>wP,clearHistory:()=>FP,redo:()=>HP,setServingSide:()=>LP,umo:()=>jP,undo:()=>WP});function ko({matchUp:t}){let{extension:e}=dt({name:Nm,element:t});if(!e)return{error:Le};let{history:r=[],undoHistory:n=[]}=e.value;return{history:r,undoHistory:n,...R}}function wP(t){if(!t)return{error:rt};let{matchUp:e,updateScore:r}=t;if(!e)return{error:cr};let n=ko({matchUp:e})?.history||[];if(!Array.isArray(n))return{error:G,info:"history is not an array"};let{matchUpFormat:o}=e;if(!o)return{error:Dl};if(!Tr({matchUpFormat:o}))return{error:Pl};let i=rr(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=P=>[1,2].includes(P),T=()=>(g+=1,{winningSide:void 0,side1Score:0,side2Score:0,setNumber:g,games:[]}),y=()=>({winningSide:void 0,points:[]}),N=()=>({winningSide:void 0,side1Score:"",side2Score:"",shots:[]}),E=N(),A=y(),U=T(),C=0;for(let P of n){C+=1,I=p.sets.length+1===s;let D=I&&a?a:c,{tiebreakAt:M,setTo:b,NoAD:v,tiebbreakFormat:O}=D,w=U.side1Score===M&&U.side1Score===U.side2Score,F=!!D.tiebreakSet,L=F?D.tiebreakSet:O,{tiebreakTo:x,NoAD:B}=L||{},H=()=>{d=void 0,l=[0,0],f=3-f,U.side1TiebreakScore=0,U.side2TiebreakScore=0,U.side1PointScore="",U.side2PointScore="",h=0},W=$=>{U.winningSide=$;let{s:k,...K}=U;p.sets.push(K),E=N(),A=y(),U=T(),H()},V=$=>{A.winningSide=$;let{g:k,...K}=A;U.games.push(K),E=N(),A=y(),H();let z=`side${$}Score`;U[z]+=1},Y=$=>{E.winningSide=$;let{p:k,...K}=E;A.points.push(K),E=N(),h=0;let z=()=>l.reduce((it,ot)=>it+ot)%4/4>.5?f:3-f,q=$-1;if(w||F){l[q]+=1,d=z(),U[`side${$}TiebreakScore`]=l[q],U[`side${3-$}TiebreakScore`]=l[1-q];let et=B?1:2;if(l[q]>=x&&l[q]>=l[1-q]+et)return V($),{gameCompleted:!0}}else if(l[1-q]===4&&l[q]===3?l[1-q]-=1:l[q]+=1,U.side1PointScore=u[l[0]],U.side2PointScore=u[l[1]],l[q]===5||l[q]===4&&l[1-q]<3||v&&l[q]===4)return V($),{gameCompleted:!0}};if(S(P.srv)&&(f=P.srv),["p","s","g","o"].includes(P.u)&&m.push(P.u),P.shotOutcome&&(E.shots.push(P),P.shotType==="SERVE"&&["OUT","NET"].includes(P.shotOutcome)&&(h+=1),h===2)){let k=3-f;Y(k)}if(S(P.p)||ft(P.pointNumber)){let $=P.winningSide||P.p;if(Y($)?.gameCompleted)continue}if(S(P.g)||ft(P.gameNumber)){let $=P.winningSide||P.g;A.winningSide=$;let k=`side${$}Score`,K=`side${3-$}Score`;if(m.length&&(m.includes("p"),m=[]),V($),U[k]===b&&U[k]-U[K]>=(v?1:2)&&(W($),I))break}if(S(P.s)||ft(P.setNumber)){let $=P.winningSide||P.s;if(W($),m.length&&(m.includes("p"),m.includes("g"),m=[]),I)break}}return C!==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=Go({...p,matchUpFormat:o}),p.scoreStringSide2=Go({...p,matchUpFormat:o,reversed:!0}),f=d||f,r&&(e.score=p),{...R,servingSide:f,score:p}}function Vo({undoHistory:t,history:e,matchUp:r}){return yt({element:r,extension:{value:{history:e,undoHistory:t},name:Nm}})}function LP({matchUp:t,sideNumber:e}){if(![1,2].includes(e))return{error:Nl};let{history:r=[]}=ko({matchUp:t});return r.push({srv:e}),Vo({matchUp:t,history:r})}function FP({matchUp:t}){return Vo({matchUp:t})}function GP({matchUp:t,point:e}){if(!e||!t)return{error:rt};if(typeof e!="object")return{error:G,context:{point:e}};let{history:r=[]}=ko({matchUp:t});return r.push(e),Vo({matchUp:t,history:r})}function kP({matchUp:t,game:e}){if(typeof e!="object")return{error:G,context:{game:e}};let{history:r=[]}=ko({matchUp:t});return r.push(e),Vo({matchUp:t,history:r})}function VP({matchUp:t,shot:e}){if(typeof e!="object")return{error:rt};let{history:r=[]}=ko({matchUp:t});return r.push(e),Vo({matchUp:t,history:r})}function BP({matchUp:t,set:e}){if(typeof e!="object")return{error:rt};let{history:r=[]}=ko({matchUp:t});return r.push(e),Vo({matchUp:t,history:r})}function HP({matchUp:t}){let{history:e=[],undoHistory:r=[]}=ko({matchUp:t});return r.length&&e.push(r.pop()),Vo({matchUp:t,history:e,undoHistory:r})}function WP({matchUp:t}){let{history:e=[],undoHistory:r=[]}=ko({matchUp:t});return r.push(e.pop()),Vo({matchUp:t,history:e,undoHistory:r})}var jP={};var hD={};Zt(hD,{keyValueScore:()=>mD,parseMatchUpFormat:()=>rr,stringifyMatchUpFormat:()=>Cp,tidyScore:()=>ID});var Xs=" ",$S="DEF",yO="COMPLETED",qP="WO",ak="WO/WO",$P="ABN",KP="SUS",zP="RET",QP="INT",KS=[zP,$S,qP,ak,$P,KP,QP];var zS="DEFAULTED";var XP="WALKOVER";var QS="ABANDONED",XS="SUSPENDED",JP="RETIRED",JS="INTERRUPTED";var AO=[JP,zS,XP],ck="Enter Score",Is="()",hs="[]",ZP=["up","left","shift+tab"],tD=["enter","down","tab","right"],Nd="backspace",eD="r",rD="s",nD="a",oD="d",iD="w",sD="i",Md=[eD,oD,iD,nD,rD,sD],_p="space",ZS=["[","("],Cd=[...ZP,...tD,_p,"]"],EO="-",uk="/",Js=EO,ni=EO,aD=[uk],UO=0,pk=["=","+","num_1","num_2","shift+=","shift+-"],Qs=["0","1","2","3","4","5","6","7","8","9"].concat(Md),PO=Qs.map(t=>`shift+${t}`),cD=[Js,Nd].concat(Cd,aD),uD=[Qs,PO,cD].join(","),mk=[uD,ZP,tD,pk].join(","),sNt=[].concat(...Qs,...Qs,...cD,...Qs,...Qs,...Qs,...Qs,...Qs,...Qs),DO={OUTCOMEKEYS:Md,SIDE1KEYS:Qs,SIDE2KEYS:PO,MODIFIERS:cD,PROMPT:ck,MOVEUP:ZP,MOVEDOWN:tD,HOTKEYS:mk};function xp({scoreString:t,lowSide:e,outcome:r}){if({scoreString:t}=NO({scoreString:t}),e===2){let o=(t&&t[t.length-1])!==Xs?Xs:"";return t+o+r}else return r+Xs+t}function NO({scoreString:t}){if(!t)return{scoreString:""};let e=!1;for(let r of KS){let n=t?.indexOf(r);n===0?t=t.slice(r.length+1).trim()+Xs:n>0&&(t=t.slice(0,n)),n>=0&&(e=!0)}return t?.trim()||(t=""),{scoreString:t,removed:e}}function Eg({analysis:t,scoreString:e,sets:r,lowSide:n}){let o,i;if(!e)return{scoreString:e,sets:r};let{scoreString:s,removed:a}=NO({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}=bu({brackets:hs,scoreString:e}),f=dk(e);if(f>=0){o=e.slice(0,f);let{isTiebreakEntry:g}=bu({brackets:Is,scoreString:o}),{lastOpenBracketIndex:I,isTiebreakEntry:h}=bu({brackets:hs,scoreString:o}),S=o&&o[o.length-1].trim(),T=o&&!isNaN(S),y=t.isIncompleteSetScore;if(l&&h){let E=o.slice(I+1).split(ni),A=E?.length>0&&E[0]!==void 0&&!isNaN(parseInt(E[0]))&&parseInt(E[0])||void 0,U=E?.length>1&&E[1]!==void 0&&parseInt(E[1])||void 0,C=[A,U];if(U){let P=n===1?1:0;C[P]=(C?.[1-P]||0)+(d?1:2),(C[P]||0)<m&&(C[P]=m),o=e.slice(0,I+1),o+=C.join(ni)}else A!==void 0?(o=e.slice(0,I+1),o+=A):(o=e.slice(0,I),y=!0);c.side1TiebreakScore=C[0]||0,c.side2TiebreakScore=C[1]||0}if(o.length||(o=void 0),y){let N=c.side1Score?.toString();if(N){let E=N?.slice(0,N.length-1);c.side1Score=!isNaN(E)&&parseInt(E)||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 N=c.side2Score?.toString(),E=c.side1Score?.toString();if(!t.isTiebreakEntry&&!t.isMatchTiebreak)if(c.side2Score){let A=N?.slice(0,N.length-1);c.side2Score=!isNaN(A)&&parseInt(A)||void 0}else{let A=E?.slice(0,E.length-1);c.side1Score=!isNaN(A)&&parseInt(A)||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 bu({brackets:t=Is,scoreString:e}){if(!e)return{};let[r,n]=t.split(""),o=e.split(""),i=Math.max(...io(r,o)),s=Math.max(...io(n,o));return{isTiebreakEntry:i>s,lastOpenBracketIndex:i}}function MO({scoreString:t}){if(!t)return!1;let e=t&&t[t.length-1].trim(),r=t&&!isNaN(e),[n,o]=hs.split(""),i=t.split(""),s=Math.max(...io(n,i)),a=Math.max(...io(o,i)),c=Math.max(...io(ni,i));return r&&s>a&&c>s}function dk(t){return t.split("").reduce((n,o,i)=>(o.match(/\d+/g)&&n.push(i),n),[]).pop()}function tT(t){let{lowValue:e=0,NoAD:r=!1,tiebreakTo:n}=t||{},o=r?1:2;return e+1>=n?e+o:parseInt(n)}function pD({matchUpFormat:t,matchUpStatus:e,winningSide:r,sets:n}){let o=rr(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 AO.includes(e)&&r&&(c=r),{matchUpWinningSide:c}}function wp({ignoreTiebreak:t=!1,matchUpScoringFormat:e,matchUpFormat:r,isTiebreakSet:n,isDecidingSet:o,set:i}){if(!i)return{error:rt,info:"missing set"};e=e||r&&rr(r);let s=o&&e.finalSetFormat||e?.setFormat||{},{side1Score:a,side2Score:c}=i,{setTo:u,tiebreakAt:p}=s,m=Lp({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 Lp({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 Rd({analysis:t,set:e}){let r=Lp({set:e}),{isDecidingSet:n,isTiebreakSet:o,matchUpScoringFormat:i}=t;return wp({matchUpScoringFormat:i,isDecidingSet:n,isTiebreakSet:o,set:e})&&r}function CO({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}=lk({analysis:t,set:i,value:n});if(s){o=!0,e=(e||"")+n,i.side2Score=n;let c=Rd({analysis:t,set:r[r.length-1]});if(i.winningSide=c||void 0,a){let u=Is.split("")[0];e+=u}else t.isDecidingSet||(e+=Xs)}return{sets:r,scoreString:e,updated:o}}function lk({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 eT({lowSide:t,value:e,sets:r,scoreString:n,winningSide:o,matchUpStatus:i}){let s;return e===eD?n?(s=!0,n=xp({scoreString:n,lowSide:t,outcome:zP}),o=t===2?1:2,i=JP):(s=!0,n=xp({scoreString:n,lowSide:t,outcome:$S}),o=t===2?1:2,i=zS):e===oD?(s=!0,n=xp({scoreString:n,lowSide:t,outcome:$S}),o=t===2?1:2,i=zS):e===iD?(s=!0,r=[],n=qP,o=t===2?1:2,i=XP):e===rD&&n?(s=!0,n=xp({scoreString:n,lowSide:t,outcome:KP}),i=XS,o=void 0):e===nD?(s=!0,n=xp({scoreString:n,lowSide:t,outcome:$P}),i=QS,o=void 0):e===sD&&n&&(s=!0,n=xp({scoreString:n,lowSide:t,outcome:QP}),i=JS,o=void 0),{updated:s,sets:r,scoreString:n,matchUpStatus:i,winningSide:o}}function RO(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!==Nd&&(e=[{setNumber:1}]);let m=e.length-1;if(Md.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}=eT({lowSide:a,value:c,sets:e,scoreString:n,matchUpStatus:i,winningSide:o}))}else if(c===Nd){if({scoreString:n,sets:e,outcomeRemoved:p}=Eg({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===Js&&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 bO({analysis:t,auto:e,lowSide:r,scoreString:n="",sets:o,value:i}){let s,a,{tiebreakSet:{tiebreakTo:c,NoAD:u}}=t.setFormat,[p]=hs.split("");if(t.isMatchTiebreakEntry||(n+=p),o[t.setNumber-1]){let{lastOpenBracketIndex:d}=bu({brackets:hs,scoreString:n}),f=(n.slice((d??0)+1)+(e?"":i)).split(ni);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(ni),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=tT({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(ni),s=!0}return{info:a,scoreString:n,sets:o,updated:s}}function vO({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=Is.split("")[0],d=u.join(Js)+(a?m:Xs);r=(r||"")+d;let l={side1Score:u[0],side2Score:u[1]},f=Rd({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 OO({matchUpFormat:t,scoreString:e,winningSide:r,value:n,sets:o}){let s=(o?.filter(V=>V?.winningSide)?.length||0)+(r?0:1),a=rr(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}=bu({brackets:Is,scoreString:e}),{isTiebreakEntry:f}=bu({brackets:hs,scoreString:e}),g=l||f,I=!!u.tiebreakSet,h=e?.[e.length-1]?.trim(),S=e&&!isNaN(h),T=!g&&h===Js,y=l&&ZS.includes(h),N=f&&ZS.includes(h),E=f&&h===ni,A=e?.split(""),[U]=hs.split(""),C=A&&Math.max(...io(U,A)),P=A&&Math.max(...io(ni,A)),D=A&&P>C,M=o[o.length-1]?.winningSide,b=o?.length&&!M,v=KS.find(V=>e?.indexOf(V)>=0),O=!isNaN(n),w=n===_p,F=Cd.includes(n),L=e?.split("").find(V=>ZS.includes(V)),x=F&&f&&!N&&(E||!MO({scoreString:e}));return{isTiebreakSetValue:I&&O,matchUpScoringFormat:a,setNumber:s,setFormat:u,matchTiebreakHasJoiner:D,isGameScoreEntry:b,isSpace:w,isCloser:F,isTiebreakCloser:F&&L&&g&&S,isDecidingSet:c,isTiebreakSet:I,isTimedSet:p,isNumericEnding:S,isNumericValue:O,hasOpener:L,hasOutcome:v,finalSet:m,finalSetIsComplete:d,lastSetIsComplete:M,isInvalidSetTiebreakValue:w&&g&&y,isInvalidMatchTiebreakValue:x,isTiebreakEntry:g,isSetTiebreakEntry:l,isMatchTiebreakEntry:f,isIncompleteSetScore:T,isIncompleteSetTiebreak:y,isIncompleteMatchTiebreak:N,isPartialMatchTiebreakValue:E}}function mD(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(!uD.includes(r))return{updated:!1,info:"invalid key"};c&&(e=3-e);let{matchUpWinningSide:l}=pD({sets:o,winningSide:i,matchUpStatus:s,matchUpFormat:a});i=l;let f=OO({value:r,winningSide:i,scoreString:n,sets:o,matchUpFormat:a});if(aD.includes(r)&&(r=Js),f.hasOpener&&f.isTiebreakEntry&&!f.isTiebreakSet&&d&&ct(r)===0&&(f.isTiebreakCloser=!0),Cd.includes(r)&&f.hasOpener&&(r=""),Cd.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}=RO({analysis:f,lowSide:e,scoreString:n,sets:o,matchUpStatus:s,winningSide:i,value:r}));else if(Md.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}=eT({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===Nd)p=!0,{scoreString:n,sets:o}=Eg({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===Js&&!f.isMatchTiebreakEntry)(!f.isSetTiebreakEntry||f.isSetTiebreakEntry&&!f.isNumericEnding)&&(p=!0,{scoreString:n,sets:o}=Eg({analysis:f,scoreString:n,sets:o,lowSide:e}),s=void 0);else if(r===ni&&f.isMatchTiebreakEntry&&!f.isSetTiebreakEntry)f.matchTiebreakHasJoiner?m="existing joiner":f.isNumericEnding&&(p=!0,n+=ni);else if([Js,ni].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}=CO({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?Is:hs,I=g.split("").reverse()[0],h=g.split("")[0],S=o[o.length-1],{tiebreakFormat:T}=f.setFormat,{tiebreakTo:y,NoAD:N}=T||{},E=Lp({set:S});if(!f.isTiebreakSet){let U=parseInt(n.split(h).reverse()[0]),C=tT({lowValue:U,tiebreakTo:y,NoAD:N});E===1?(S.side1TiebreakScore=C,S.side2TiebreakScore=U):(S.side1TiebreakScore=U,S.side2TiebreakScore=C)}n=(n||"")+I,f.isDecidingSet||(n+=Xs);let A=Rd({analysis:f,set:S});S.winningSide=A||void 0,p=!0}else if(f.isTiebreakSetValue)({info:m,scoreString:n,sets:o,updated:p}=bO({analysis:f,auto:u,lowSide:e,scoreString:n,sets:o,value:r}));else if(f.isSetTiebreakEntry){let[g]=Is.split(""),I=Math.max(...io(g,n.split(""))),h=n.slice(I+1),S=h&&ct(h)===UO,T=ct(h?h+r:r),{tiebreakFormat:y}=f.setFormat,{tiebreakTo:N,NoAD:E}=y||{};!S&&h.length<2?E&&T>N-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}=vO({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}=pD({sets:o,winningSide:i,matchUpStatus:s,matchUpFormat:a});return i=g,g&&(!s||[Qt,Fn].includes(s))?(s=yO,o=o.filter(I=>{let{side1Score:h,side2Score:S,side1TiebreakScore:T,side2TiebreakScore:y}=I;return h||S||T||y})):n&&!i&&![XS,QS,JS].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}}var bd="\\d+-\\d+",Fp="\\d+-\\d+\\(\\d+\\)",Ug="\\[\\d+-\\d+\\]",fk="\\d+-\\d+\\(\\d+-\\d+\\)",_O=new RegExp(`(${bd}),`,"g"),xO=new RegExp(`(${Fp}),`,"g"),gk=[bd,Fp,Ug,fk],Ik=["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"],hk=Ik.map(t=>{let r=t.split("").map(n=>gk[n]).join(" ");return new RegExp(`^${r}$`)});function dD(t){return!t||hk.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 vd(t){return/^\(\d+\)$/.test(t)||/^\(\d+$/.test(t)}function LO(t){return/^\(\d+-\d+\)$/.test(t)||/^\[\d+-\d+\]$/.test(t)}function xa(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 Gp(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 lD(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 E of t.match(r)){let A=E.replace(")",") ");t=t.replace(E,A)}t=t.replace(/\)\//g,") / "),t=t.replace(/\/\)/g,")");let n=/\(([\d- ]+)\)/g,o=/\(([\d- ]+)\)/,i=t.match(n);for(let E of i||[]){let[A]=E.match(o).slice(1),U=A.replace(/ /g,"");t=t.replace(E,`(${U})`)}let s=/\(\(\d-\d\)\)/g;if(s.test(t)){let E=t.match(s);E.length&&E.forEach(A=>{let U=A.match(/\((\(\d-\d\))\)/).slice(1)[0];t=t.replace(A,U)})}if(s=/\(\((\d)\)\)/g,s.test(t)){let E=t.match(s);E.length&&E.forEach(A=>{let U=A.match(/\((\(\d\))\)/).slice(1)[0];t=t.replace(A,U)})}/(^|\s)6-,/.test(t)&&(t=t.replace(/(^|\s)6-,/g,"6-0,"));let a=new RegExp(/[-,]{2,}/g);t=t.replace(a,"-"),["- "," -"].forEach(E=>{let A=new RegExp(`(\\d+)${E}(\\d+)`,"g"),U=t.match(A);U&&U.forEach(C=>t=t.replace(C,C.split(E).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(A=>{let[U]=A.match(/\((\d+), \)/).slice(1);U.length===2?t=t.replace(A,`(${U})`):U.length===1&&U==="6"&&(t=t.replace(A,"(6-0)"))});let u=/\((\d+)\/\)/g;u.test(t)&&t.match(u).forEach(A=>{let[U]=A.match(/\((\d+)\/\)/).slice(1);U.length===2?t=t.replace(A,`(${U})`):U.length===1&&U==="6"?t=t.replace(A,"(6-0)"):t=t.replace(A,`(${U})`)});let p=/\d\/\d\/,/g;p.test(t)&&t.match(p).forEach(A=>{let[U]=A.match(/(\d\/\d)\/,/).slice(1);t=t.replace(A,`${U},`),e.push("slashComma")});let m=/\(\/(\d+)\)/g;m.test(t)&&t.match(m).forEach(A=>{let[U]=A.match(/\(\/(\d+)\)/).slice(1);U.length===2?t=t.replace(A,`(${U})`):U.length===1&&parseInt(U)<6?t=t.replace(A,`(6-${U})`):t=t.replace(A,`(${U})`)});let d,l,f,g,I,h=()=>{I=fr(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[E]=t.match(S).slice(1);t=t.replace(S,E+")")}if(I["("]===I[")"]&&I["("]>1){let E=t.split(")(").join(") (").split(" ");E.every(FO)?t=E.map(A=>{let U=A.slice(1,A.length-1);return U.length>2?U:A}).join(" "):t=E.join(" ")}h();let T=/[A-Za-z]+/.test(t),y=/\d+/.test(t);if(!T&&!y)return{score:""};if(/^\[.+\]$/.test(t)&&"()/,- ".split("").some(E=>I[E])&&(t=t.slice(1,t.length-1)),/^\(.+\)$/.test(t)&&I["("]===1&&I[")"]===1&&"[]/,".split("").some(E=>I[E]>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 E=[],A=0;for(let U of t.split("").reverse())U===")"&&(A?E.push("("):A+=1),U==="("&&(A-=1),E.push(U);E.reverse(),t=E.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 E="",A=0;for(let U of t.split(""))U==="("&&(A?E+=")":A+=1),U===")"&&(A-=1),E+=U;t=E}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 N=E=>{let A=E.indexOf("("),U=E.indexOf(")");return A>=0&&U>=0&&A<U};if(/^\([\d ]+.*[\d ]+\)$/.test(t)&&I["("]===I[")"]){let E=t.slice(1,t.length-1);N(E)&&(t=E,h())}return{score:t,applied:e}}function vu(t){if(!/^[\d-]+(\(\d\))*$/.test(t))return t;let e=io("-",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(")")),[_O,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(vu).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(vd),i=0,s="";for(let d of o){let l=io(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,y)=>+T-+y));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 y=[6,4].includes(T)?T+1:T-1,N=[T,y].sort().reverse().join("-"),E=[f.join(" "),[N,d].join("")].join(" ");s+=E,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"||xa(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=io("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;!xa(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(Fp).test(d)&&"tiebreak"||new RegExp(bd).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 P of[".",","," ","/"]){let D=new RegExp(`^(\\d+)\\${P}(\\d+)$`);if(D.test(t)){let M=t.match(D).slice(1).map(v=>parseInt(v)),b=Math.abs(M[0]-M[1]);b<=10&&b>=2&&(t=t.split(P).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[P,D,M,b,v,O]=t.match(r).slice(1);t=t.replace(r,`${P}${D}-${M} ${b}-${v}${O}`),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(D=>(i.test(D)&&(D=D.replace("("," (")),s.test(D)&&(D=D.replace(")",") ")),D)).join(" "),e.push("spaceConsiderationPatterns")});let c=vu(t);c!==t&&(t=c,e.push("deDashMash"));let u=/^(\d)[-/,]+(\d{2})[-/,]+(\d)$/;if(u.test(t)){let[P,D,M]=t.match(u).slice(1),[b,v]=D.split("");t=`${P}-${b} ${v}-${M}`,e.push("smashSetPattern")}let p=/^(\d+)[ -](\d+)$/,m=/^([\d -]+)\/([\d -]+)$/;if(m.test(t)){let[P,D]=t.match(m).slice(1),M=P.trim(),b=D.trim();if(p.test(M)&&p.test(b)){let v=M.match(p).slice(1,3).join("-"),O=b.match(p).slice(1,3).join("-");t=`${v} ${O}`,e.push("slashSeparationPattern")}}let d=/^([\d -]+),([\d -]+)$/;if(d.test(t)){let[P,D]=t.match(d).slice(1),M=P.trim(),b=D.trim();if(p.test(M)&&p.test(b)){let v=M.match(p).slice(1,3).join("-"),O=b.match(p).slice(1,3).join("-");t=`${v} ${O}`,e.push("commaSeparationPattern")}}let l=/^\d \d,/;if(l.test(t)){let P=t.match(l)[0],D=P.slice(0,P.length-1).split(" ").join("-");t=t.replace(P,D),e.push("singleSetCommaSeparationPattern")}let f=0,g=/(\d+)-(\d{2})-(\d+)/;for(;g.test(t)&&f<3;){let[P,D,M]=t.match(g).slice(1),b=D.split(""),v=`${P}-${b[0]} ${b[1]}-${M}`;t=t.replace(g,v),e.push("noSetSeparationPattern"),f+=1}let I=/(^|\s)7-6\s(\d+)\s/g,h=t.match(I);if(h?.length){let P=/(^|\s)7-6\s(\d+)\s/;h.forEach(D=>{let M=D.match(P).slice(2)[0];t=t.replace(D,`7-6(${M}) `),e.push("floatingTiebreakPattern1")})}let S=t.match(/\d \d /);S?.forEach(P=>{let D=P.slice(0,P.length-1).split(" ").join("-");t=t.replace(P,D),e.push("spaceSeparatedSetPattern1")}),S=t.match(/ \d \d$/),S?.forEach(P=>{let D=" "+P.slice(1).split(" ").join("-");t=t.replace(P,D),e.push("spaceSeparatedSetPattern2")});let T=/^\d, *\d\/\d, *\d/;if(T.test(t)){let P=t.match(T)[0],D=P.split("/").map(M=>`(${M})`).join(" ")+" ";t=t.replace(P,D),e.push("slashCommaSetPattern")}let y=/\(6-\)/g;y.test(t)&&(t=t.replace(y,"(6-0)"),e.push("missingZeroPattern2"));let N=/(?<!-)(\d+)\/(\d+)(?!-)/g;if(N.test(t)){let P=t.match(N),D=/(?<!-)(\d+)\/(\d+)(?!-)/,M=t;P.forEach(b=>{let[v,O]=b.match(D).slice(1),w=`${v}-${O}`;M=M.replace(b,w)}),t=M,e.push("slashSetPattern")}let E=/(.*)\s(1\d)\s(\d+)$/;if(E.test(t)){let[P,D,M]=t.match(E).slice(1);P.replace(/\D/g,"").length>=4&&(t=P+` ${D}${M}`,e.push("spaceSeparatedSuperPattern"))}let A=/(^|\s)(\d+-\d+)\s(\d+)(\s|$)/g;for(let P of t.match(A)||[]){let[D,M,b,v]=P.match(/(^|\s)(\d+-\d+)\s(\d+)(\s|$)/).slice(1),[O,w]=M.split("-").map(L=>parseInt(L));Math.abs(O-w)===1&&(t=t.replace(P,`${D}${M}(${b})${v}`),e.push("spaceSeparatedSetPattern"))}let U=/\d-\d \(\d{1,2}\)(\s|$|,)/g;for(let P of t.match(U)||[]){let D=/(\d-\d) \((\d{1,2})\)(\s|$|,)/,[M,b,v]=P.match(D).slice(1),[O,w]=M.split("-").map(L=>parseInt(L));Math.abs(O-w)===1&&(t=t.replace(P,`${M}(${b})${v}`),e.push("floatingTiebreakPattern2"))}let C=/(^|\s)(\d \d)\(/g;for(let P of t.match(C)||[]){let D=/(^|\s)(\d \d)\(/,[M,b]=P.match(D).slice(1);t=t.replace(P,`${M}${b.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(xa(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(Jt(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=Gp(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 xa(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(y=>parseInt(y));if(Math.abs(S[0]-S[1])===1)continue}let I=lD(l),h=vu(I);t=t.replace(m,`(${h})`).trim()}let i=new RegExp(/\[[\d,/ ]+\]/g);t.match(i)?.forEach(m=>{let d=lD(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(",")||vd(h)),f=d.every(h=>h.includes("/")||vd(h)),g=d.every(h=>h.includes("-")||vd(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(N=>parseInt(N.trim())),y=Math.min(...T);h==="set"?m+=`(${y}) `:m+=`[${T.join("-")}] `,h="tiebreak"}}),t=m.trim()}}let u=fr(t.split(""));u["("]===1&&u[")"]===1&&t.startsWith("(")&&t.endsWith(")")&&(t=t.slice(1,t.length-1),u["-"]===1&&xa(t)&&Jt(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 rT({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=Jt(a)&&parseInt(a),u=n[0]!==void 0&&n[1]!==void 0;if(Jt(c)){if(n[0]===void 0){n[0]=c;continue}if(n[1]===void 0&&(n[1]=c,s())){r.push(i()),n=[void 0,void 0];continue}if(u&&e.length===1&&Jt(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=Gp(r,e);if(o)return o}if(n&&t.length===7&&e>3){let o=r.slice(4),i=Gp(o,e-4);if(i)return`${r[0]}-${r[1]} ${r[2]}-${r[3]} ${i}`}}function fD(t){let{score:e}=t,{applied:r,matchUpStatus:n}=t,o=e?.toString().split(""),i=o?.every(a=>Jt(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}=rT({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=Te(e.split(""),2).map(h=>h.join("")),p=u.map(h=>{let[S,T]=h.split("").map(E=>parseInt(E)),y=Math.abs(S-T),N=S>T?1:2;return y>1&&N||N*-1}),m=p.reduce((h,S)=>h>0&&S>0,1),d=fr(p),l=p.map(h=>Math.abs(h)),f=fr(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,y,N,E]=a,A=p.reduce((U,C,P)=>C<0?P:U,void 0);if(A===0){let U=Math.min(T,y);e=`${h}-${S}(${U}) ${N}-${E}`,r.push("chunkSplitTiebreak1")}else if(A===1){let U=Math.min(N,E);e=`${h}-${S} ${T}-${y}(${U})`,r.push("chunkSplitTiebreak2")}else e=`${h}-${S} ${T}-${y}`,r.push("chunkSplitTrimExtraneous")}}else if(a.length===8){let[h,S,T,y,N,E,A,U]=a;g||I?a[5]===1&&(g?e=`${h}-${S}(${T}) ${y}-${N} [${E}${A}-${U}]`:e=`${h}-${S} ${T}-${y}(${N}) [${E}${A}-${U}]`):(p[0],p[1])}}}return{score:e,applied:r,matchUpStatus:n}}function nT(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(Fp).test(p)){let l=p.slice(3),f=p.slice(0,3),g=f.split("-");if(!xa(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&&Jt(p))return p.split("").join("-");p=vu(p);let d=new RegExp(`^${Ug}$`).test(p)&&"super"||new RegExp(`^${Fp}$`).test(p)&&"tiebreak"||new RegExp(`^${bd}$`).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(""),y=T.find(N=>parseInt(N)>h||m&&parseInt(N)<=o)??T[0];y&&(p=S?[y,h].join("-"):[h,y].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}=nT(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}=nT(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=>Jt(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 Sk({score:t}){return t=t?.toString().toLowerCase()||"",{score:t}}function Tk({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 yk({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=Gp(r.split(""),n);return e.push("getSuper"),o}}else{let{score:o,applied:i}=fD({score:r,applied:[]});o!==r&&(r=o,e.push(...i))}}return r}).join(" "),{score:t,applied:e})}function Ak({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 Ek({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 Uk({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 Pk({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 Dk({score:t}){return new RegExp(/-\d+\/\d+-/).test(t)&&(t=t.split("/").join(" ")),{score:t}}function Nk({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 Mk({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 Ck({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=>Jt(n))&&e.length===4&&(t=e)}return{score:t}}function Rk({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:Mk,handleSetSlashSeparation:Dk,punctuationAdjustments:GO,handleGameSeparation:Nk,joinFloatingTiebreak:VO,handleBracketSpacing:kO,handleSpaceSeparator:Ck,separateScoreBlocks:yk,matchKnownPatterns:BO,removeDanglingBits:Pk,removeErroneous:Ak,handleWalkover:Ek,properTiebreak:HO,handleNumeric:fD,handleRetired:Uk,containedSets:WO,sensibleSets:jO,stringScore:Sk,superSquare:YO,setBuilder:rT,excisions:Rk,replaceOh:Tk};var gD={},bk=[],vk=["handleNumeric","handleWalkover","handleRetired","replaceOh","stringScore","punctuationAdjustments","excisions","handleSpaceSeparator","matchKnownPatterns","removeDanglingBits","handleBracketSpacing","matchKnownPatterns","containedSets","separateScoreBlocks","handleGameSeparation","removeErroneous","joinFloatingTiebreak","handleSetSlashSeparation","handleTiebreakSlashSeparation","properTiebreak","sensibleSets","superSquare"],Ok=["handleNumeric","separateScoreBlocks","sensibleSets","superSquare"];function ID(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(vk);let g=dD(l);return g||(l=e.toString().replace(/\D/g,""),m?.removed&&(m.removed=void 0),f(Ok),g=dD(l),g||(bk.push({score:l,fileName:o,sheetName:r}),l="")),p.forEach(I=>{gD[I]||(gD[I]=0),gD[I]+=1}),{matchUpStatus:u?.toUpperCase(),modifications:c,attributes:m,isValid:g,score:l}}var SD={};Zt(SD,{analyzeSet:()=>Ou,checkScoreHasValue:()=>Ie,checkSetIsComplete:()=>wp,getSetComplement:()=>Ng,getTiebreakComplement:()=>kp,isValidMatchUpFormat:()=>Tr,parseScoreString:()=>Od,validateScore:()=>Dg,validateTieFormat:()=>ar});function $O({existingMatchUpStatus:t,matchUpFormat:e,matchUpStatus:r,winningSide:n,score:o}){let i=o?.sets??[],a=(i?.filter(E=>E?.winningSide)||[]).reduce((E,A)=>{let{winningSide:U}=A;if(!U)return E;let C=U-1;return E[C]++,E},[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?rr(e):void 0,l=Math.max(...a),f=fr(a)[l],g=d?.bestOf,I=g&&Math.ceil(g/2)||1,h=r??t,S=h&&[bt,er,vt].includes(h),T=!d||!i.length||i.every((E,A)=>{let U=A+1,C=U===g,P=U===i.length,{side1Score:D,side2Score:M,side1TiebreakScore:b,side2TiebreakScore:v,winningSide:O}=E,w=Math.max(D??0,M??0),F=b??v,{finalSetFormat:L,setFormat:x}=d,B=C&&L||x;if(F){let{tiebreakTo:W,NoAD:V}=B?.tiebreakFormat||{},Y=Math.max(b??0,v??0);if(V&&Y>W||Y<W&&O&&(P&&!S||!P))return!1}return B.setTo?!(!B.noTiebreak&&w>B.setTo+1):!0}),y=(!e||l===I)&&f===1&&a.indexOf(l)+1||void 0;return{valid:T&&(n&&p>m&&n===y||!n&&!y||S)}}function Dg({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:Rn("sets")};if(i?.length){let u=i.map(m=>m?.setNumber).filter(Boolean);if(u.length!==pt(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(E=>E.some(A=>A!==void 0)).every(E=>E.every(A=>ft(A))))return{error:G,info:"non-numeric values"};if(![T,S].filter(E=>E!==void 0).every(E=>ft(E)))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}=$O({existingMatchUpStatus:t,matchUpStatus:r,matchUpFormat:e,winningSide:n,score:o});if(!p)return{error:xA,info:"score is invalid for matchUpFormat or winningSide does not match calculated winningSide"}}return{valid:!0}}var Ng=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]},kp=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=_k({lowValue:i,NoAD:o,tiebreakTo:n});return[e?i:s,e?s:i]};function _k(t){let{lowValue:e,NoAD:r,tiebreakTo:n}=t,o=r?1:2;return e+1>=n?e+o:n}function Od({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&&kp({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 KO({matchUpScoringFormat:t,isDecidingSet:e,isTiebreakSet:r,setObject:n}){if(!n)return;let o=Lp({set:n});return wp({matchUpScoringFormat:t,set:n,isDecidingSet:e,isTiebreakSet:r})&&o||void 0}function Ou(t){let{setObject:e,matchUpScoringFormat:r}=t;if(!e)return{error:Ml};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(w=>w!==void 0).length,g=d.filter(w=>w!==void 0).length,I=l.filter(w=>w!==void 0).length,h=m?.filter(w=>!isNaN(w)).length,S=l?.filter(w=>!isNaN(w)).length,{tiebreakAt:T}=s||{},y=T&&m.filter(w=>w>=T).length===2,N=y&&(m[0]>m[1]&&1||m[1]>m[0]&&2||void 0),E=!!(S&&!h),A=!!e?.winningSide,{error:U,result:C}=xk({setObject:e,setFormat:s,sideGameScores:m,sideTiebreakScores:l}),{error:P,result:D}=wk({setObject:e,setFormat:s,sideTiebreakScores:l}),M=u&&!E&&C||a&&E&&D,b=p&&!(a&&!E)&&!(u&&E)&&(!A||M),v=KO({isDecidingSet:i,isTiebreakSet:E,matchUpScoringFormat:r,setObject:e}),O={expectTiebreakSet:a,expectTimedSet:c,hasTiebreakCondition:y,isCompletedSet:A,isDecidingSet:i,isTiebreakSet:E,isValidSet:b,isValidSetNumber:p,isValidSetOutcome:M,leadingSide:N,setFormat:s,sideGameScores:m,sideGameScoresCount:f,sidePointScores:d,sidePointScoresCount:g,sideTiebreakScores:l,sideTiebreakScoresCount:I,winningSide:v};return e?.winningSide!==void 0&&(E?(O.isValidTiebreakSetOutcome=D,D||(O.tiebreakSetError=P)):(O.isValidStandardSetOutcome=C,C||(O.standardSetError=U))),O}function xk({setObject:t,setFormat:e,sideGameScores:r,sideTiebreakScores:n}){if(!t)return{result:!1,error:Ml};let o=!!e?.tiebreakSet,i=!!e?.timed;if(!e||o||i)return{result:!1,error:G};if(!(r?.filter(D=>!isNaN(D)).length===2))return{result:!1,error:UI};let{setTo:a,tiebreakAt:c,tiebreakFormat:u,NoAD:p}=e||{};if(!!!(a&&r?.find(D=>D>=a)))return{result:!1,error:UI};let d=[1,2].includes(t?.winningSide);if(!t||!d)return{result:!1,error:mm};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,y=n?.filter(D=>!isNaN(D)).length===2,N=n?.[l],E=n?.[f],A=c&&r.filter(D=>D>=c).length===2;if(T){let{NoAD:D,tiebreakTo:M}=u;if(A){if(h>1)return{result:!1,error:{message:"invalid winning game scoreString (5)"}};if(!y)return{result:!1,error:{message:"invalid tiebreak scores (1)"}};if(isNaN(M))return{result:!1,error:{message:"tiebreakTo error"}};if(!!!(M&&n?.find(B=>B>=M)))return{result:!1,error:{message:"invalid tiebreak scores (2)"}};let O=c<a?a:a+1;if(g>O)return{result:!1,error:{message:"invalid winning game scoreString (1)"}};if(!N||!E||N<E)return{result:!1,error:{message:"winningSide tiebreak value is not high"}};let w=D?1:2,F=N-E,L=E>=M-1;if(F&&L&&F<w)return{result:!1,error:{message:"invalid tiebreak scores (3)"}}}if(g>a&&!A)return{result:!1,error:{message:"invalid winning game scoreString (2)"}}}let U=p?1:2,C=I>=a-1;return h&&C&&!A&&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 wk({setObject:t,setFormat:e,sideTiebreakScores:r}){if(!t)return{result:!1,error:Ml};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:mm};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}}var oT={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 iT={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 sT={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 aT={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 cT={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 uT={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 pT={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 mT={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 dT={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 lT={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 fT={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 gT={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 IT={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 hT={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 ST={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 TT={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 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:"Overtime",matchUpCount:1,gender:"MIXED",matchUpFormat:"SET1-S:T20",matchUpType:"DOUBLES",scoreValue:1}],tieFormatName:"USTA_TOC",winCriteria:{aggregateValue:!0}};var _d="COLLEGE_DEFAULT",AT="COLLEGE_JUCO",ET="COLLEGE_D3",TD="DOMINANT_DUO",yD="DOMINANT_DUO_MIXED",AD="LAVER_CUP",ED="TEAM_DOUBLES_3_AGGREGATION",UD="TIME_TENNIS_DUAL",PD="TIME_TENNIS_PRO_CIRCUIT",DD="USTA_BREWER_CUP",ND="USTA_OZAKI_CUP",MD="USTA_COLLEGE",CD="USTA_GOLD_TEAM_CHALLENGE",RD="USTA_LEVEL_1",bD="USTA_INTERSECTIONAL",vD="USTA_SECTION_BATTLE",OD="USTA_SOUTHERN_LEVEL_5",_D="USTA_TOC",xD="USTA_WTT_ITT",wD="USTA_ZONAL",zO={COLLEGE_D3:ET,COLLEGE_DEFAULT:_d,COLLEGE_JUCO:AT,DOMINANT_DUO:TD,DOMINANT_DUO_MIXED:yD,LAVER_CUP:AD,TEAM_DOUBLES_3_AGGREGATION:ED,TIME_TENNIS_DUAL:UD,TIME_TENNIS_PRO_CIRCUIT:PD,USTA_BREWER_CUP:DD,USTA_OZAKI_CUP:ND,USTA_COLLEGE:MD,USTA_GOLD_TEAM_CHALLENGE:CD,USTA_INTERSECTIONAL:bD,USTA_LEVEL_1:RD,USTA_SECTION_BATTLE:vD,USTA_SOUTHERN_LEVEL_5:OD,USTA_TOC:_D,USTA_WTT_ITT:xD,USTA_ZONAL:wD};var XO="STANDARD",QO={[XO]:{hydrate:!0,doubles:{matchUpCount:3,matchUpValue:1},singles:{matchUpCount:6,matchUpValue:1},valueGoal:5},[ET]:{hydrate:!0,doubles:{matchUpFormat:"SET1-S:8/TB7@7",matchUpCount:3,matchUpValue:1},singles:{matchUpFormat:Sn,matchUpCount:6,matchUpValue:1},tieFormatName:ET,valueGoal:5},[_d]:{hydrate:!0,doubles:{matchUpFormat:"SET1-S:6/TB7",collectionValue:1,matchUpCount:3},singles:{matchUpFormat:Sn,matchUpCount:6,matchUpValue:1},tieFormatName:_d,valueGoal:4},[AT]:{hydrate:!0,doubles:{matchUpFormat:"SET1-S:8/TB7",matchUpCount:3,matchUpValue:1},singles:{matchUpFormat:Sn,matchUpCount:6,matchUpValue:1},tieFormatName:AT,valueGoal:5},[AD]:TT,[TD]:fT,[yD]:pT,[ED]:iT,[UD]:mT,[PD]:uT,[DD]:dT,[ND]:lT,[MD]:gT,[CD]:oT,[bD]:cT,[RD]:IT,[vD]:aT,[OD]:sT,[xD]:hT,[_D]:yT,[wD]:ST},Zk=t=>{let e=t?.namedFormat&&Object.keys(QO).includes(t.namedFormat)?t.namedFormat:XO,r=Array.isArray(t?.uuids)?t?.uuids:[],n,{category:o,gender:i}=t?.event??{},s=J(QO[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:JU,collectionName:"Doubles",matchUpType:wt,...s.doubles},{collectionId:a(1),matchUpFormat:Sn,collectionName:"Singles",matchUpType:Kt,...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},oi=Zk;function JO(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===Ve&&s===Ve){let m=e?.structures?.find(({stage:d})=>d===tt)?.tieFormat;u=u||m||o&&c?.tieFormat?.tieFormatName===o&&c.tieFormat||o&&oi({namedFormat:o,hydrateCollections:r,isMock:a,event:c})||c?.tieFormat||oi({event:c,isMock:a,hydrateCollections:r}),p=void 0}else p||(u=void 0,c?.matchUpFormat||(p=Sn));if(u){let m=ar({gender:c?.gender,enforceGender:n,tieFormat:u});if(m.error)return m}return{tieFormat:u,matchUpFormat:p}}function ZO(t){let e=t.drawDefinition,{existingQualifyingPlaceholderStructureId:r,appliedPolicies:n,drawEntries:o,structureId:i,idPrefix:s,isMock:a,event:c}=t,u=t.qualifyingProfiles,p=u?.length?BS({uuids:t.uuids,qualifyingProfiles:u,appliedPolicies:n,idPrefix:s,isMock:a}):void 0;if(p?.error)return p;e.structures=e.structures?.filter(({structureId:T})=>T!==r),e.links=e.links?.filter(({source:T})=>T.structureId!==r);let{qualifiersCount:m,qualifyingDrawPositionsCount:d,qualifyingDetails:l}=p??{};d&&(p?.structures&&e.structures?.push(...p.structures),p?.links&&e.links?.push(...p.links));let f=e.structures?.find(({stage:T,stageSequence:y})=>T===tt&&y===1),{qualifiersCount:g}=ms({stageSequence:1,drawDefinition:e,structureId:i,stage:tt}),I=Math.max(m??0,g??0),h=iS({qualifiersCount:I,drawDefinition:e,stage:tt});if(h.error||(h=Dp({drawSize:d,stage:at,drawDefinition:e}),h.error))return h;tV({drawDefinition:e,drawEntries:o,event:c});let S=eV({mainStructure:f,qualifyingDetails:l,drawDefinition:e});return S.error?S:{drawDefinition:e,structureId:i}}function tV({drawDefinition:t,drawEntries:e,event:r}){for(let n of(e??[]).filter(({entryStage:o})=>o===at)){let o={...n,entryStage:n.entryStage??tt,drawDefinition:t,event:r};Hh(o)}}function eV({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&&Ca({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 UT(t){let{participantIds:e}=t,r=t.drawDefinition?.entries?.filter(n=>{let o=n.entryStatus;return!t.restrictEntryStatus||wr.includes(o)}).map(gt)??[];if(e){let n=e.filter(o=>!r?.includes(o));if(n?.length)return _({result:{error:Zr},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.restrictRoundsCount!==!1&&t.roundsCount>31?{error:G,info:"roundsCount must be less than 32"}:{participantIds:e}}function xd(t){let e=[],{roundsCount:r=1,drawDefinition:n,matchUpsCount:o,structureId:i,idPrefix:s,isMock:a,event:c}=t,u,p=UT(t);if(p.error)return p;for(let m of Z(1,r+1)){let d=Ru({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 _({result:d,info:{iteration:m}});d.matchUps?.length&&e.push(...d.matchUps),u=(d?.roundNumber??1)+1}return{matchUps:e}}function e_(t){let{tournamentRecord:e,participantIds:r,scaleName:n,eventType:o,adHocRatings:i={}}=t,s=t.scaleAccessor??Ke[n]?.accessor,a=e.participants??[];for(let c of r??[]){let u=a?.find(m=>m.participantId===c),p=t_({scaleName:`${n}.${VI}`,participant:u,eventType:o});!p&&n&&(p=t_({scaleAccessor:s,participant:u,scaleName:n,eventType:o})),p&&!i[c]&&(i[c]=p)}return i}function t_({scaleType:t=Xi,scaleAccessor:e,participant:r,scaleName:n,eventType:o}){let a=(r&&So({scaleAttributes:{eventType:o??Bs,scaleType:t,scaleName:n},participant:r}))?.scaleItem?.scaleValue;return e&&Pt(a)?a[e]:a}function wd(t){let e=nV(t);if(e?.error)return e;let r=UT(t);if(r.error)return r;let n=rV(t);if(n.error)return n;let o=e_(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=Dd({...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 rV(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&&Ls[s.stage];return gr({structure:s})&&a>(Ls[i?.stage]||1)?s:i},void 0),n=e?.structures?.find(i=>i.structureId===r?.structureId);return n?gr({structure:n})?{structure:n}:{error:aa}:{error:Gt}}function nV(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!==Xr?{error:aa}:!Array.isArray(t.drawDefinition?.entries)&&t.participantIds&&!Array.isArray(t.participantIds)?{error:G,info:"Missing Entries"}:{error:void 0}}function r_(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&&wr.includes(m)),c=a?.map(gt),u=a?Math.floor(a.length/2):0;if(t.automated)return oV({...t,participantIds:c});{let p=xd({roundsCount:t.roundsCount,drawDefinition:r,matchUpsCount:u,idPrefix:o,isMock:i,event:s});if(p.error)return p;p.matchUps?.length&&hd({matchUps:p.matchUps,suppressNotifications:!0,tournamentRecord:e,drawDefinition:r,structureId:n,event:s})}return{...R}}function oV(t){let{restrictEntryStatus:e,generateMatchUps:r,structureId:n,matchUpIds:o,scaleName:i,scaleAccessor:s}=t.drawMatic??{},a=wd({...t,eventType:t.drawMatic?.eventType??t.matchUpType,generateMatchUps:r??!0,scaleAccessor:s??t.scaleAccessor,scaleName:i??t.scaleName,participantIds:t.participantIds,roundsCount:t.roundsCount,restrictEntryStatus:e,structureId:n,matchUpIds:o});return a.error?a:(a?.matchUps?.length&&hd({tournamentRecord:t.tournamentRecord,drawDefinition:t.drawDefinition,suppressNotifications:!0,matchUps:a.matchUps,event:t.event,structureId:n}),{...R})}function n_({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:Gt};let{positionAssignments:d}=de({structure:m}),l=d?.length||0;if(u>l)return{error:lA};let f=m.structures?.length,g=ft(a?.groupSeedingThreshold)&&a?.groupSeedingThreshold,I=tg({roundRobinGroupsCount:f,drawSize:l})?.seedGroups,{seedsCount:h}=Cu({policyDefinitions:i,requireParticipantCount:t,drawSizeProgression:r,participantsCount:n,drawSize:l});return h&&i?.[Nn]&&u>h&&e&&(u=h),m.seedLimit=u,m.seedAssignments=Z(1,u+1).map(S=>{let T=I?.find(E=>E.includes(S)),y=T&&Math.min(...T),N=g&&S>=g?y:S;return{participantId:void 0,seedNumber:S,seedValue:N}}),Ot({drawDefinition:s,structureIds:[c]}),{...R,seedLimit:u}}function Zs({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)&&wr.includes(d.entryStatus)).map(d=>{let{participantId:l}=d,{scaleItem:f}=Dc({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 PT(t){let e="prepareStage",{drawDefinition:r}=t,{structures:n}=Gn({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 _({result:{error:Gt},stack:e});let s=i?.structureId,{seedsCount:a,stageEntries:c,seedLimit:u}=dV({...t,structureId:s});(t.seededParticipants||t.event||t.seedingScaleName)&&aV({...t,seedsCount:a,structure:i,structureId:s});let p=t.automated!==!1&&t.drawType!==Xr&&!(t.qualifyingOnly&&t.stage!==at),m=(n?.length||0)>1,d=p?sV({...t,multipleStructures:m,seedLimit:u,structureId:s}):{};return d?.error?_({result:d,stack:e}):{...d,stageEntries:c,structureId:s,seedsCount:a}}function iV({entries:t,stage:e,stageSequence:r,roundTarget:n}){return t.filter(o=>{let i=dt({name:ln,element:o})?.extension?.value;return(!o.entryStage||o.entryStage===e)&&(!r||!o.entryStageSequence||o.entryStageSequence===r)&&(!n||!i||i===n)&&Qo.includes(o.entryStatus)})}function sV(t){let e=typeof t.automated=="object"&&t.automated.seedsOnly,r=Sc({...t,seedsOnly:e});if(r.error)return r;let n=r?.positionAssignments,o=r?.positioningReport;return{conflicts:r.conflicts,positionAssignments:n,positioningReport:o}}function aV(t){let{seededParticipants:e,seedingScaleName:r,entries:n,event:o}=t,i=n.map(gt);e?cV({...t,enteredParticipantIds:i}):(o||r)&&uV({...t,enteredParticipantIds:i})}function cV(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?fs({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;$s({provisionalPositioning:e,tournamentRecord:o,drawDefinition:s,seedingProfile:a,participantId:l,seedBlockInfo:m,structureId:c,seedNumber:f,seedValue:g,event:p})})}function uV(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=pV({...t,ageCategoryCode:l,categoryName:d,eventType:f})||c&&mV({...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:y,scaleValue:N}=h,E=o?.[T]||N||T;$s({provisionalPositioning:r,tournamentRecord:s,drawDefinition:a,seedingProfile:u,participantId:y,structureId:p,seedNumber:T,seedValue:E,event:m})})}function pV(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:ao,eventType:u};return Zs({scaleAttributes:p,tournamentRecord:e,stageSequence:n,entries:o,stage:i}).scaledEntries}function mV(t){let{tournamentRecord:e,stageSequence:r,event:n,entries:o,stage:i}=t,{categoryName:s,ageCategoryCode:a}=n?.category||{},c=n?.eventType;return Zs({scaleAttributes:{scaleName:s||a,scaleType:ci,eventType:c},tournamentRecord:e,stageSequence:r,entries:o,stage:i}).scaledEntries}function dV(t){let{seedsCount:e}=t;t.seededParticipants&&(e=t.seededParticipants.length),e>t.drawSize&&(e=t.drawSize);let r=iV(t);e>r.length&&(e=r.length);let{seedLimit:n}=n_({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 o_(t){let e=Ud({...t,modifyOriginal:!1});if(e.error)return e;let r=e.drawDefinition,{suppressDuplicateEntries:n=!0,ignoreStageSpace:o,appliedPolicies:i,qualifyingOnly:s,seedingProfile:a,participants:c,drawEntries:u,placeByes:p,drawSize:m,drawType:d,entries:l}=t,f=[],g=[],I=lV({suppressDuplicateEntries:n,ignoreStageSpace:o,drawDefinition:r,drawEntries:u,drawType:d,entries:l});if(I.error)return I;let h=d===xi?0:ct(t.seedsCount??0),S=PT({...t,qualifyingOnly:!m||s,appliedPolicies:i,drawDefinition:r,seedingProfile:a,participants:c,stage:tt,seedsCount:h,placeByes:p,drawSize:m,entries:l});if(S.error&&!S.conflicts)return S;S.positioningReport?.length&&f.push({[tt]:S.positioningReport});let T=S.structureId;return S.conflicts&&(g=S.conflicts),d===Xr&&t.roundsCount&&r_({...t,drawDefinition:r,structureId:T}),{drawDefinition:r,positioningReports:f,conflicts:g,structureId:T}}function lV(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===Xr,entryStage:s.entryStage??tt,event:t.event,drawDefinition:r,drawType:o},c=Hh(a);if(n&&c.error)return c}return{error:void 0}}var fV=()=>({matchUpType:void 0,drawName:void 0,drawId:void 0,structures:[],entries:[],links:[]});var i_=fV;function s_(t){let{drawId:e=Mt(),processCodes:r,matchUpType:n,drawType:o}=t??{},i=i_();return Object.assign(i,{processCodes:r,matchUpType:n,drawType:o,drawId:e})}function Ld(t){let e=t.structureIds,{tournamentRecord:r,drawDefinition:n,matchUpFormat:o,structureId:i,matchUpId:s,event:a}=t,c=ut(t,[{[Or]:!0,[hm]:!0}]);if(c.error)return c;if(!Tr({matchUpFormat:o}))return{error:$a};let u="setMatchUpFormat";if(s){let p=Lt({drawDefinition:n,matchUpId:s,event:a});if(p.error)return p;let m=p.matchUp;if(m?.matchUpType===Ve)return{info:"Cannot set matchUpFormat when { matchUpType: TEAM }",error:Ze};m&&(m.matchUpFormat=o,It({tournamentId:r?.tournamentId,eventId:a?.eventId,context:u,drawDefinition:n,matchUp:m}))}else if(Array.isArray(e)){if(a?.eventType===Ve)return{error:_o};for(let p of e){let m=st({drawDefinition:n,structureId:p});if(m.error)return m;m.structure&&(m.structure.matchUpFormat=o)}}else if(i){if(a?.eventType===Ve)return{error:_o};let p=st({drawDefinition:n,structureId:i});if(p.error)return p;p.structure&&(p.structure.matchUpFormat=o)}else n&&(n.matchUpFormat=o);return e=e??(i?[i]:void 0),Ot({drawDefinition:n,structureIds:e}),{...R}}function a_({tieFormat:t}){let e=ar({checkCollectionIds:!1,tieFormat:t});if(e.error)return e;for(let r of t.collectionDefinitions)r.collectionId||(r.collectionId=Mt());return{tieFormat:t}}function c_({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=a_({tieFormat:o});if(a.error)return a;e.tieFormat=a.tieFormat??o}else if(r){let a=Ld({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 kD={};Zt(kD,{attachPolicies:()=>Wi,findPolicy:()=>zo,getAppliedPolicies:()=>ht,getPolicyDefinitions:()=>Co,mutate:()=>FD,query:()=>GD,removePolicy:()=>LD});var FD={};Zt(FD,{attachPolicies:()=>Wi,removePolicy:()=>LD});function LD(t){let e=ut(t,[{[aR]:!0,_anyOf:{[Ae]:!1,[un]:!1,[Or]:!1,[Os]:!1}}]);if(e.error)return e;let r,n=t.drawDefinition??t.event??((t.tournamentId||!t.tournamentRecords)&&t.tournamentRecord);if(n)return u_(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=u_(t,s);if(a.error)return a;r=!0}}else return{error:j};return r?{...R}:{error:Fc}}function u_(t,e){let r=ht(t).appliedPolicies??{};return r[t.policyType]?(delete r[t.policyType],Object.keys(r).length?yt({element:e,extension:{name:qc,value:r}}):sr({element:e,name:qc}),{...R}):{error:Fc}}var GD={};Zt(GD,{findPolicy:()=>zo,getAppliedPolicies:()=>ht,getPolicyDefinitions:()=>Co});var VD={[Nn]:{validSeedPositions:{ignore:!0},duplicateSeedNumbers:!0,drawSizeProgression:!0,seedingProfile:{drawTypes:{[lo]:{positioning:pi},[fn]:{positioning:pi}},positioning:NR},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=VD;function p_({appliedPolicies:t,policyDefinitions:e,drawDefinition:r,stack:n}){if(e&&typeof e!="object")return _({info:"policyDefinitions must be an object",result:{error:G},stack:n});let o={[Yc]:t?.[Yc]};return e?gV({policyDefinitions:e,appliedPolicies:t,policiesToAttach:o,drawDefinition:r}):o.avoidance&&Wi({drawDefinition:r,policyDefinitions:o}),!t?.[Nn]&&!e?.[Nn]&&(Wi({policyDefinitions:Cg,drawDefinition:r}),t&&Object.assign(t,Cg)),{error:void 0}}function gV({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 m_(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??s_({processCodes:t.processCodes,drawId:t.drawId,drawType:a}),d=c_({tournamentRecord:e,drawDefinition:m,matchUpFormat:r,matchUpType:i,tieFormat:s,event:u});if(d.error)return _({result:d,stack:c});let l=p_({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 d_(t){let e="generateOrGetExisting",r=[],n=[],o=m_(t);if(o.error)return _({result:o,stack:e});let i=o.existingDrawDefinition,s=o.drawDefinition??{},a=o.structureId,c=t.drawEntries??t.eventEntries??[],u=o.existingQualifyingPlaceholderStructureId&&ZO({...t,...o})||o_({...t,...o,entries:c});return u.error?_({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 l_(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,y)=>T.stageSequence-y.stageSequence,I=(T,y)=>T.roundTarget-y.roundTarget,h=[],S=1;r.sort(I);for(let T of r){if(!Array.isArray(T.structureProfiles))return _({info:Rn("structureProfiles"),result:{error:rt},stack:d});S=T.roundTarget||S;let y=T.structureProfiles?.sort(g)||[],N=1;for(let E of y){let{qualifyingRoundNumber:A,qualifyingPositions:U,seededParticipants:C,seedingScaleName:P,seedsCount:D=0,seedByRanking:M,placeByes:b,drawSize:v}=E,O=PT({...t,seedingProfile:E.seedingProfile??c,stageSequence:N,qualifyingRoundNumber:A,preparedStructureIds:h,qualifyingPositions:U,seededParticipants:C,stage:at,seedingScaleName:P,appliedPolicies:i,drawDefinition:a,qualifyingOnly:s,seedByRanking:M,participants:u,roundTarget:S,seedsCount:D,placeByes:b,drawSize:v,entries:m});if(O.error)return O;O.structureId&&h.push(O.structureId),N+=1,O.conflicts?.length&&f.push(...O.conflicts),O.positioningReport?.length&&o.push({[at]:O.positioningReport})}S+=1}}else if(p&&l){let g=on({structureName:$e(at),stage:at}),{link:I}=Ca({sourceStructureId:g.structureId,targetStructureId:p,sourceRoundNumber:0,linkType:zn});a.structures||(a.structures=[]),a.structures.push(g),a.links||(a.links=[]),a.links.push(I)}return{qualifyingConflicts:f,error:void 0}}var iN={};Zt(iN,{addGoesTo:()=>Gi,allCompetitionMatchUps:()=>mn,allDrawMatchUps:()=>or,allEventMatchUps:()=>ho,allPlayoffPositionsFilled:()=>eS,allTournamentMatchUps:()=>le,analyzeDraws:()=>Du,analyzeMatchUp:()=>jp,analyzeTournament:()=>xT,bulkUpdatePublishedEventIds:()=>LT,calculateWinCriteria:()=>Ts,categoryCanContain:()=>gd,checkMatchUpIsComplete:()=>as,checkValidEntries:()=>Ad,compareTieFormats:()=>Bo,competitionScheduleMatchUps:()=>xu,credits:()=>f_,drawMatchUps:()=>JT,eventMatchUps:()=>$d,filterParticipants:()=>gu,findDrawDefinition:()=>PS,findExtension:()=>dt,getAllDrawMatchUps:()=>ne,getAllEventData:()=>FT,getAllStructureMatchUps:()=>At,getAllowedDrawTypes:()=>Fd,getAllowedMatchUpFormats:()=>bT,getAppliedPolicies:()=>ht,getAssignedParticipantIds:()=>Ei,getAvailableMatchUpsCount:()=>Sd,getAvailablePlayoffProfiles:()=>Su,getCategoryAgeDetails:()=>Uu,getCheckedInParticipantIds:()=>rs,getCompetitionDateRange:()=>kd,getCompetitionMatchUps:()=>Wp,getCompetitionParticipants:()=>DT,getCompetitionPenalties:()=>vT,getCompetitionVenues:()=>Vp,getCourtInfo:()=>jm,getCourts:()=>ZT,getDrawData:()=>Bd,getDrawDefinitionTimeItem:()=>lh,getDrawParticipantRepresentativeIds:()=>ES,getDrawTypeCoercion:()=>Mu,getEligibleVoluntaryConsolationParticipants:()=>AS,getEntriesAndSeedsCount:()=>jd,getEvent:()=>ry,getEventData:()=>Hd,getEventMatchUpFormatTiming:()=>jT,getEventProperties:()=>ty,getEventPublishStatus:()=>Lr,getEventStructures:()=>rg,getEventTimeItem:()=>su,getEvents:()=>ey,getFlightProfile:()=>Ht,getHomeParticipantId:()=>Ym,getLinkedTournamentIds:()=>Kc,getMatchUpCompetitiveProfile:()=>pu,getMatchUpContextIds:()=>KT,getMatchUpDailyLimits:()=>zd,getMatchUpDailyLimitsUpdate:()=>YT,getMatchUpDependencies:()=>Yr,getMatchUpFormat:()=>zT,getMatchUpFormatTiming:()=>mu,getMatchUpFormatTimingUpdate:()=>HT,getMatchUpScheduleDetails:()=>qm,getMatchUpType:()=>zm,getMatchUpsMap:()=>ye,getMatchUpsStats:()=>QT,getMaxEntryPosition:()=>VT,getModifiedMatchUpFormatTiming:()=>Yd,getPairedParticipant:()=>nn,getParticipantEventDetails:()=>NT,getParticipantIdFinishingPositions:()=>US,getParticipantMembership:()=>MT,getParticipantResults:()=>Au,getParticipantScaleItem:()=>Dc,getParticipantSchedules:()=>CT,getParticipantSignInStatus:()=>RT,getParticipantTimeItem:()=>fh,getParticipants:()=>Yt,getPersonRequests:()=>Di,getPolicyDefinitions:()=>Co,getPositionAssignments:()=>Op,getPositionsPlayedOff:()=>Ac,getPredictiveAccuracy:()=>$T,getProfileRounds:()=>Wd,getPublishState:()=>ps,getRoundMatchUps:()=>qe,getRounds:()=>XT,getScaleValues:()=>pa,getScaledEntries:()=>Zs,getScheduledRoundsDetails:()=>_u,getSchedulingProfile:()=>Ho,getSchedulingProfileIssues:()=>kT,getSeedingThresholds:()=>Yh,getSeedsCount:()=>Cu,getStructureSeedAssignments:()=>Hr,getTeamLineUp:()=>is,getTieFormat:()=>wT,getTimeItem:()=>Vn,getTournamentIds:()=>ip,getTournamentInfo:()=>Ss,getTournamentPenalties:()=>Gd,getTournamentPersons:()=>_T,getTournamentStructures:()=>tS,getTournamentTimeItem:()=>au,getValidGroupSizes:()=>Ep,getVenueData:()=>dc,getVenuesAndCourts:()=>yo,isAdHoc:()=>gr,isCompletedStructure:()=>ei,isValidForQualifying:()=>kS,isValidMatchUpFormat:()=>Tr,matchUpActions:()=>yd,participantScaleItem:()=>So,participantScheduledMatchUps:()=>qT,positionActions:()=>GS,publicFindVenue:()=>_h,tallyParticipantResults:()=>ba,tieFormatGenderValidityCheck:()=>ld,tournamentMatchUps:()=>Kd,validMatchUp:()=>Vf,validMatchUps:()=>Nr,validateCollectionDefinition:()=>Pu,validateLineUp:()=>od});function f_(){return`
5
5
  This project would not have been possible without the generous input and patience
6
6
  of tournament organizers and directors who worked with early versions of CourtHive/TMX.