tods-competition-factory 2.1.1 → 2.1.2
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 +2 -2
- package/dist/tods-competition-factory.development.cjs.js +5 -2
- package/dist/tods-competition-factory.development.cjs.js.map +1 -1
- package/dist/tods-competition-factory.production.cjs.min.js +1 -1
- package/dist/tods-competition-factory.production.cjs.min.js.map +1 -1
- package/package.json +1 -1
package/dist/index.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
var NL=Object.defineProperty;var Qt=(t,e)=>{for(var r in e)NL(t,r,{get:e[r],enumerable:!0})};function qa(){return"2.1.1"}var UA={};Qt(UA,{competitionGovernor:()=>gU,drawsGovernor:()=>_N,entriesGovernor:()=>VN,eventGovernor:()=>XN,generationGovernor:()=>rM,matchUpFormatGovernor:()=>ky,matchUpGovernor:()=>EM,mocksGovernor:()=>II,participantGovernor:()=>JM,policyGovernor:()=>pN,publishingGovernor:()=>aR,queryGovernor:()=>vN,reportGovernor:()=>cR,scheduleGovernor:()=>yR,scoreGovernor:()=>Wg,tieFormatGovernor:()=>bR,tournamentGovernor:()=>BR,venueGovernor:()=>XR});var gU={};Qt(gU,{getLinkedTournamentIds:()=>cu,getTournamentIds:()=>Ep,linkTournaments:()=>pU,mutate:()=>lU,query:()=>fU,unlinkTournament:()=>dU,unlinkTournaments:()=>mU});var lU={};Qt(lU,{linkTournaments:()=>pU,unlinkTournament:()=>dU,unlinkTournaments:()=>mU});var xC={};Qt(xC,{addNotice:()=>dt,callListener:()=>Cm,createInstanceState:()=>WE,cycleMutationStatus:()=>uf,deepCopyEnabled:()=>cf,deleteNotice:()=>zI,deleteNotices:()=>Bi,disableNotifications:()=>jE,enableNotifications:()=>af,getDevContext:()=>Sr,getMethods:()=>pf,getNotices:()=>KI,getProvider:()=>QI,getTopics:()=>xr,getTournamentId:()=>is,getTournamentRecord:()=>mf,getTournamentRecords:()=>Vo,globalLog:()=>$E,handleCaughtError:()=>mp,hasTopic:()=>up,removeTournamentRecord:()=>qE,setDeepCopy:()=>Kc,setDevContext:()=>$c,setGlobalLog:()=>vC,setGlobalMethods:()=>OC,setGlobalSubscriptions:()=>oF,setMethods:()=>_C,setStateMethods:()=>KE,setStateProvider:()=>rF,setSubscriptions:()=>iF,setTournamentId:()=>pp,setTournamentRecord:()=>YE,setTournamentRecords:()=>bm,timeKeeper:()=>nF});function Vr(t){return typeof t=="function"}function te(t){return typeof t=="string"}function It(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function dC(t,e){if(!It(t)||!It(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 CI(t,e){return Array.isArray(t)?Object.assign({},...(t??[]).filter(It).map(r=>r[e]&&{[r[e]]:r}).filter(Boolean)):{}}var lC=t=>e=>Object.keys(t).every(r=>e[r]===t[r]);function RI(t,e){if(t===void 0)return null;if(!It(t)||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=>RI(i))}:{[o]:e?n(t[o]):RI(t[o])}))}function CA(t){return Array.isArray(t)?t.length+t.map(CA).reduce((e,r)=>e+r,0):It(t)&&t!==null?Object.keys(t).length+Object.keys(t).map(e=>CA(t[e])).reduce((e,r)=>e+r,0):0}function fC(t){if(t===null||typeof t!="object")return;let e=JSON.stringify(t),r=CA(t),n=e.split("").reduce((o,i)=>o+i.charCodeAt(0),0);return[e.length,r,n].map(o=>o.toString(36)).join("")}var C={success:!0},bA="error",gC={SUCCESS:C,ERROR:bA};var bI={message:"Chronological error; time violation.",code:"ANACHRONISM"},Um={message:"Duplicate entry",code:"DUPLICATE_ENTRY"},vA={message:"Cannot remove main structure",code:"ERR_CANNOT_REMOVE_MAIN_STRUCTURE"},vI={message:"records must be an object with tournamentId keys",code:"ERR_INVALID_TOURNAMENTS"},wt={message:"Missing tournamentRecords",code:"ERR_MISSING_TOURNAMENTS"},j={message:"Missing tournamentRecord",code:"ERR_MISSING_TOURNAMENT"},$a={message:"Invalid tournamentRecord",code:"ERR_INVALID_TOURNAMENT"},la={message:"Missing tournamentId",code:"ERR_MISSING_TOURNAMENT_ID"},fa={message:"Invalid drawDefinition",code:"ERR_INVALID_DRAWDEF"},X={message:"Missing drawDefinition",code:"ERR_MISSING_DRAWDEF"},OA={message:"Existing drawDefinition(s)",code:"ERR_EXISTING_DRAWDEFS"},Dr={message:"drawDefinition not found",code:"ERR_NOT_FOUND_DRAWDEF"},Qo={message:"Invalid structure",code:"ERR_INVALID_STRUCTURE"},_l={message:"Incomplete source structure",code:"ERR_INCOMPLETE_STRUCTURE"},xl={message:"Invalid drawPosition for seedAssignment",code:"ERR_INVALID_SEEDING_POSITION"},Ka={message:"drawPosition already assigned",code:"ERR_EXISTING_POSITION_ASSIGNMENT"},_A={message:"Schedule not cleared",code:"ERR_UNCHANGED_SCHEDULE_NOT_CLEARED"},xA={message:"drawPosition not cleared",code:"ERR_FAILURE_POSITION_NOT_CLEARED"},ML={message:"drawPosition not found",code:"ERR_NOT_FOUND_DRAW_POSITION"},wl={message:"Unrecognized drawType",code:"ERR_UNRECOGNIZED_DRAW_TYPE"},za={message:"Missing drawPositions",code:"ERR_MISSING_DRAW_POSITIONS"},Xu={message:"drawPosition is active",code:"ERR_ACTIVE_DRAW_POSITION"},Os={message:"Invlid drawPosition",code:"ERR_INVALID_DRAW_POSITION"},_s={message:"Missing drawPosition",code:"ERR_MISSING_DRAW_POSITION"},Dm={message:"Invalid drawType",code:"ERR_INVALID_DRAW_TYPE"},Ju={message:"Invalid drawSize",code:"ERR_INVALID_DRAW_SIZE"},OI={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"},on={message:"Missing drawId",code:"ERR_MISSING_DRAW_ID"},wA={message:"drawId exists",code:"ERR_EXISTING_DRAW_ID"},LA={message:"participantId cannot be assigned to multiple seedNumbers",code:"INVALID_PARTICIPANT_SEEDING"},FA={message:"seedsCount greater than drawSize",code:"ERR_INVALID_SEED_COUNT"},kA={message:"Missing seedCountThresholds",code:"ERR_MISSING_SEED_COUNT_THRESHOLD"},GA={message:"Invalid action",code:"ERR_INVALID_ACTION"},_I={message:"Invalid assignment",code:"ERR_INVALID_ASSIGNMENT"},VA={message:"Missing seedAssignments",code:"ERR_MISSING_SEED_ASSIGNMENTS"},BA={message:"Invalid seedNumber",code:"ERR_INVALID_SEED_NUMBER"},HA={message:"Invalid seedPosition",code:"ERR_INVALID_SEED_POSITION"},Ll={message:"Missing targetLink",code:"ERR_MISSING_LINK_TARGET"},WA={message:"Existing round",code:"ERR_EXISTING_ROUND"},RL={message:"Missing roundNumber",code:"ERR_MISSING_ROUND_NUMBER"},hr={message:"Missing structureId",code:"ERR_MISSING_STRUCTURE_ID"},Lt={message:"structure not found",code:"ERR_NOT_FOUND_STRUCTURE"},Fl={message:"Missing structures",code:"ERR_MISSING_STRUCTURES"},di={message:"Missing structure",code:"ERR_MISSING_STRUCTURE"},jA={message:"drawDefinition contains unlinked structures",code:"ERR_MISSING_STRUCTURE_LINKS"},Bn={message:"Invalid eventType",code:"ERR_INVALID_EVENT_TYPE"};var bt={message:"Missing event / eventId",code:"ERR_MISSING_EVENT_ID"},Pr={message:"Event not found",code:"ERR_NOT_FOUND_EVENT"},YA={message:"Event exists",code:"ERR_EXISTING_EVENT"},qA={message:"Missing entries",code:"ERR_MISSING_ENTRIES"},$A={message:"Invalid entries",code:"ERR_INVALID_ENTRIES"},kl={message:"Missing assignments",code:"ERR_MISSING_ASSIGNMENTS"},KA={message:"Missing stage",code:"ERR_MISSING_STAGE"},Li={message:"Invalid stage",code:"ERR_INVALID_STAGE"},zA={message:"stageSequence limit",code:"ERR_LIMIT_STAGE_SEQUENCE"},QA={message:"Missing positionAssignments",code:"ERR_MISSING_POSITION_ASSIGNMENTS"},XA={message:"Cannot Assign BYE status if no assignment: { bye: true }",code:"ERR_UNCHANGED_CANNOT_ASSIGN_BYE"},xI={message:"Unrecognized matchUpStatus",code:"ERR_UNRECOGNIZED_MATCHUP_STATUS"},Xa={message:"Unrecognized matchUpFormat",code:"ERR_UNRECOGNIZED_MATCHUP_FORMAT"},Gl={message:"Incompatible matchUpStatus",code:"ERR_INCOMPATIBLE_MATCHUP_STATUS"},ga={message:"Invalid matchUpStatus",code:"ERR_INVALID_MATCHUP_STATUS"},li={message:"Invalid tieFormat",code:"ERR_INVALID_TIE_FORMAT"},Vl={message:"Invalid matchUpFormat",code:"ERR_INVALID_MATCHUP_FORMAT"},Bl={message:"Missing matchUpFormat",code:"ERR_MISSING_MATCHUP_FORMAT"},JA={message:"Missing collectionDefinition",code:"ERR_MISSING_COLLECTION_DEFINITION"},xs={message:"Missing tieFormat",code:"ERR_MISSING_TIE_FORMAT"},er={message:"Missing matchUpId",code:"ERR_MISSING_MATCHUP_ID"},ns={message:"Missing matchUpIds",code:"ERR_MISSING_MATCHUP_IDS"},_e={message:"matchUp not found",code:"ERR_NOT_FOUND_MATCHUP"},Xn={message:"Missing matchUps",code:"ERR_MISSING_MATCHUPS"},dr={message:"Missing matchUp",code:"ERR_MISSING_MATCHUP"},or={message:"Invalid matchUp",code:"ERR_INVALID_MATCHUP"},wI={message:"Missing policyType",code:"ERR_MISSING_POLICY_TYPE"},Zu={message:"Missing policyDefinitions",code:"ERR_MISSING_POLICY_DEFINITIONS"},CL={message:"Missing seeding policy",code:"ERR_MISSING_POLICY_SEEDING"},ZA={message:"Missing avoidance policy",code:"ERR_MISSING_POLICY_AVOIDANCE"},LI={message:"Missing policy attributes",code:"ERR_MISSING_POLICY_ATTRIBUTES"},tE={message:"Invalid policyDefinitions",code:"ERR_INVALID_POLICY_DEFINITIONS"},FI={message:"existing policyType",code:"ERR_EXISTING_POLICY_TYPE"},bL={message:"Policy not attached",code:"ERR_FAILURE_POLICY_NOT_ATTACHED"},Wc={message:"Policy not found",code:"ERR_NOT_FOUND_POLICY"},vL={message:"Missing scoring policy / matchUpFormats",code:"ERR_MISSING_POLICY_SCORING_MATCHUP_FORMATS"},Hl={message:"Invalid sideNumber",code:"ERR_INVALID_SIDE_NUMBER"},OL={message:"Invalid setNumber",code:"ERR_INVALID_SET_NUMBER"},Wl={message:"Missing setObject",code:"ERR_MISSING_SET_ATTRIBUTE"},_L={message:"Missing setNumber",code:"ERR_MISSING_SET_NUMBER"},xL={message:"Missing sideNumber",code:"ERR_MISSING_SIDE_NUMBER"},Fi={message:"Missing courtId",code:"ERR_MISSING_COURT_ID"},ot={message:"Missing value",code:"ERR_MISSING_VALUE"},eE={message:"Missing birthdate",code:"ERR_MISSING_BIRTH_DATE"},rE={message:"Missing date",code:"ERR_MISSING_DATE"},nE={message:"No valid dates",code:"ERR_NO_VALID_DATES"},Pm={message:"Invalid bookings",code:"ERR_INVALID_BOOKINGS"},jl={message:"Invalid dateAvailability",code:"ERR_INVALID_DATE_AVAILABILITY"},oE={message:"Missing dateAvailability",code:"ERR_MISSING_DATE_AVAILABILITY"},Ge={message:"Invalid Date",code:"ERR_INVALID_DATE"},Po={message:"Invalid time",code:"ERR_INVALID_TIME"},iE={message:"Invalid tournament dates",code:"ERR_INVALID_DATES_TOURNAMENT"};var kI={message:"Invalid game scores",code:"ERR_INVALID_SCORES_GAME"},sE={message:"Invalid score",code:"ERR_INVALID_SCORE"},Nm={message:"Invalid winningSide",code:"ERR_INVALID_WINNING_SIDE"};var IC={message:"No participants generated",code:"ERR_NO_PARTICIPANTS_GENERATED"},Yl={message:"Cannot modify tieFormat",code:"ERR_UNCHANGED_CANNOT_MODIFY_TIEFORMAT"},aE={message:"Cannot modify participantType",code:"ERR_UNCHANGED_CANNOT_MODIFY_PARTICIPANT_TYPE"},tp={message:"Cannot remove participants",code:"ERR_UNCHANGED_CANNOT_REMOVE_PARTICIPANTS"},GI={message:"Participant category mismatch",code:"ERR_CATEGORY_MISMATCH"},ql={message:"Cannot change winningSide",code:"ERR_UNCHANGED_CANNOT_CHANGE_WINNING_SIDE"},ki={message:"Invalid participant",code:"ERR_INVALID_PARTICIPANT"},pn={message:"Invalid participantId",code:"ERR_INVALID_PARTICIPANT_ID"},_r={message:"Invalid participantIds",code:"ERR_INVALID_PARTICIPANT_IDS"},cE={message:"Invalid participantRole",code:"ERR_INVALID_PARTICIPANT_ROLE"},Sn={message:"Invalid participantType",code:"ERR_INVALID_PARTICIPANT_TYPE"},uE={message:"Missing participantRole",code:"ERR_MISSING_PARTICIPANT_ROLE"},Gi={message:"Missing participant",code:"ERR_MISSING_PARTICIPANT"},Ja={message:"Missing participants",code:"ERR_MISSING_PARTICIPANTS"},ee={message:"Missing participantId",code:"ERR_MISSING_PARTICIPANT_ID"},Xt={message:"Participant Not Found",code:"ERR_NOT_FOUND_PARTICIPANT"},pE={message:"participantId exists",code:"ERR_EXISTING_PARTICIPANT_ID"},wL={message:"participant pair exists",code:"ERR_EXISTING_PARTICIPANT_PAIR"},mE={message:"No participant removed",code:"ERR_UNCHANGED_NO_PARTICIPANT_REMOVED"},No={message:"Missing participantIds",code:"ERR_MISSING_PARTICIPANT_IDS"},dE={message:"Missing participantsCount",code:"ERR_MISSING_PARTICIPANT_COUNT"},lE={message:"Participant not checked in",code:"ERR_UNCHANGED_PARTICIPANT_NOT_CHECKED_IN"},fE={message:"Missing person details",code:"ERR_MISSING_PERSON_DETAILS"},ws={message:"Existing participant drawPosition assignment",code:"ERR_EXISTING_PARTICIPANT_DRAW_POSITION_ASSIGNMENT"},ep={message:"Existing participant",code:"ERR_EXISTING_PARTICIPANT"},$l={message:"participantsCount exceeds drawSize",code:"ERR_INVALID_PARTICIPANT_COUNT"},Kl={message:"Invalid entry status",code:"ERR_INVALID_ENTRY_STATUS"},VI={message:"Participant Entry Not Found",code:"ERR_NOT_FOUND_PARTICIPANT_ENTRY"},hC={message:"Participant not entered in stage",code:"ERR_UNCHANGED_PARTICIPANT_NOT_ENTERED"},SC={message:"Participant not found in stageSequence",code:"ERR_NOT_FOUND_PARTICIPANT_IN_STAGE"},gE={message:"entryStatus not allowed in stage",code:"ERR_INVALID_ENTRY_STATUS_IN_STAGE"},IE={message:"entryStatus not allowed for event",code:"ERR_INVALID_ENTRY_STATUS_IN_EVENT"},BI={message:"No stage space available for entryStatus",code:"ERR_UNCHANGED_NO_AVAILABLE_STAGE_SPACE"},hE={message:"Insufficient drawPositions to accommodate qualifiers",code:"ERR_UNCHANGED_NO_DRAW_POSITIONS_FOR_QUALIFIERS"},zl={message:"Insufficient drawPositions to accommodate entries",code:"ERR_INSUFFICIENT_DRAW_POSITIONS"},SE={message:"Missing penaltyType",code:"ERR_MISSING_PENALTY_TYPE"},Ql={message:"Missing penaltyId",code:"ERR_MISSING_PENALTY_ID"},jc={message:"Penalty not found",code:"ERR_NOT_FOUND_PENALTY"},TE={message:"Missing courtsCount/courtNames",code:"ERR_MISSING_COURTS_INFO"},Ls={message:"Court not found",code:"ERR_NOT_FOUND_COURT"},yE={message:"Court exists",code:"ERR_EXISTING_COURT"},AE={message:"Venue exists",code:"ERR_EXISTING_VENUE"},Vi={message:"Venue not found",code:"ERR_NOT_FOUND_VENUE"},Xo={message:"Missing venueId",code:"ERR_MISSING_VENUE_ID"},EE={message:"Invalid endTime",code:"ERR_INVALID_END_TIME"},HI={message:"Existing endTime",code:"ERR_EXISTING_END_TIME"},UE={message:"Invalid stopTime",code:"ERR_INVALID_STOP_TIME"},DE={message:"Invalid startTime",code:"ERR_INVALID_START_TIME"},TC={message:"Invalid resumeTime",code:"ERR_INVALID_RESUME_TIME"},Xl={message:"Invalid timeItem",code:"ERR_INVALID_TIME_ITEMS"},PE={message:"Missing async state provider",code:"ERR_MISSING_ASYNC_STATE_PROVIDER"},Jl={message:"Missing timeItem",code:"ERR_MISSING_TIME_ITEM"},Zl={message:"Missing timeItems",code:"ERR_MISSING_TIME_ITEMS"},Yc={message:"Missing context",code:"ERR_MISSING_CONTEXT"},NE={message:"Missing schedule",code:"ERR_MISSING_SCHEDULE"},rp={message:"Invalid scaleItem",code:"ERR_INVALID_SCALE_ITEM"},ME={message:"Modifications failed",code:"ERR_FAILURE_MODIFICATIONS"},Fs={message:"No modifications applied",code:"ERR_UNCHANGED_NO_MODIFICATIONS_APPLIED"},RE={message:"Unable to assign court",code:"ERR_UNCHANGED_COURT_NOT_ASSIGNED"},np={message:"No Candidates",code:"ERR_UNCHANGED_NO_CANDIDATES"},CE={message:"Invalid configuration",code:"ERR_INVALID_CONFIG"},bE={message:"Invalid collectionDefinition",code:"ERR_INVALID_COLLECTION_DEFINITION"},po={message:"Invalid object",code:"ERR_INVALID_OBJECT"},op={message:"Invalid gender",code:"ERR_INVALID_GENDER"},qc={message:"Invalid category",code:"ERR_INVALID_CATEGORY"},k={message:"Invalid values",code:"ERR_INVALID_VALUES"},vE={message:"Duplicate value",code:"ERR_DUPLICATE_VALUE"},tf={message:"Team not found",code:"ERR_NOT_FOUND_TEAM"},OE={message:"No valid actions",code:"ERR_NO_VALID_ACTIONS"},ip={message:"No valid attributes",code:"ERR_NO_VALID_ATTRIBUTES"},ef={message:"Value unchanged",code:"ABORT_UNCHANGED"},Pe={message:"Not found",code:"ERR_NOT_FOUND"},sp={message:"Not implemented",code:"ERR_NOT_IMPLEMENTED"},_E={message:"Existing flight",code:"ERR_EXISTING_FLIGHT"},rf={message:"Existing flight profile",code:"ERR_EXISTING_FLIGHT_PROFILE"},xE={message:"Existing outcome",code:"ERR_EXISTING_OUTCOME"},wE={message:"Existing matchUpId",code:"ERR_EXISTING_MATCHUP_ID"},WI={message:"Existing stage",code:"ERR_EXISTING_STAGE"},nf={message:"Existing structure",code:"ERR_EXISTING_STRUCTURE"},Za={message:"Method not found",code:"ERR_NOT_FOUND_METHOD"},LE={message:"Scheduled matchUps",code:"ERR_SCHEDULED_MATCHUPS"},ap={message:"Scores present",code:"ERR_SCORES_PRESENT"},yC={ANACHRONISM:bI,CANNOT_CHANGE_WINNING_SIDE:ql,CANNOT_MODIFY_TIEFORMAT:Yl,CANNOT_MODIFY_PARTICIPANT_TYPE:aE,CANNOT_REMOVE_MAIN_STRUCTURE:vA,CANNOT_REMOVE_PARTICIPANTS:tp,CATEGORY_MISMATCH:GI,COURT_EXISTS:yE,COURT_NOT_FOUND:Ls,DRAW_DEFINITION_NOT_FOUND:Dr,DRAW_ID_EXISTS:wA,DRAW_POSITION_ACTIVE:Xu,DRAW_POSITION_ASSIGNED:Ka,DRAW_POSITION_NOT_CLEARED:xA,DRAW_POSITION_NOT_FOUND:ML,DRAW_SIZE_MISMATCH:OI,DUPLICATE_ENTRY:Um,DUPLICATE_VALUE:vE,ENTRY_STATUS_NOT_ALLOWED_FOR_EVENT:IE,ENTRY_STATUS_NOT_ALLOWED_IN_STAGE:gE,EVENT_EXISTS:YA,EVENT_NOT_FOUND:Pr,EXISTING_DRAW_DEFINITIONS:OA,EXISTING_END_TIME:HI,EXISTING_FLIGHT:_E,EXISTING_MATCHUP_ID:wE,EXISTING_OUTCOME:xE,EXISTING_PARTICIPANT_DRAW_POSITION_ASSIGNMENT:ws,EXISTING_PARTICIPANT:ep,EXISTING_POLICY_TYPE:FI,EXISTING_PROFILE:rf,EXISTING_ROUND:WA,EXISTING_STAGE:WI,EXISTING_STRUCTURE:nf,INCOMPATIBLE_MATCHUP_STATUS:Gl,INCOMPLETE_SOURCE_STRUCTURE:_l,INSUFFICIENT_DRAW_POSITIONS:zl,INVALID_ACTION:GA,INVALID_ASSIGNMENT:_I,INVALID_BOOKINGS:Pm,INVALID_CATEGORY:qc,INVALID_COLLECTION_DEFINITION:bE,INVALID_CONFIGURATION:CE,INVALID_DATE_AVAILABILITY:jl,INVALID_DATE:Ge,INVALID_DRAW_DEFINITION:fa,INVALID_DRAW_POSITION_FOR_SEEDING:xl,INVALID_DRAW_POSITION:Os,INVALID_DRAW_SIZE:Ju,INVALID_END_TIME:EE,INVALID_ENTRIES:$A,INVALID_EVENT_TYPE:Bn,INVALID_GAME_SCORES:kI,INVALID_GENDER:op,INVALID_MATCHUP_FORMAT:Vl,INVALID_MATCHUP_STATUS:ga,INVALID_MATCHUP_STATUS_BYE:XA,INVALID_MATCHUP:or,INVALID_OBJECT:po,INVALID_PARTICIPANT_ID:pn,INVALID_PARTICIPANT_IDS:_r,INVALID_PARTICIPANT_ROLE:cE,INVALID_PARTICIPANT_SEEDING:LA,INVALID_PARTICIPANT_TYPE:Sn,INVALID_PARTICIPANT:ki,INVALID_POLICY_DEFINITION:tE,INVALID_RECORDS:vI,INVALID_SCALE_ITEM:rp,INVALID_SEED_NUMBER:BA,INVALID_SEED_POSITION:HA,INVALID_SET_NUMBER:OL,INVALID_SIDE_NUMBER:Hl,INVALID_SCORE:sE,INVALID_STAGE:Li,INVALID_START_TIME:DE,INVALID_STRUCTURE:Qo,INVALID_STOP_TIME:UE,INVALID_TIE_FORMAT:li,INVALID_TIME:Po,INVALID_TIME_ITEM:Xl,INVALID_TOURNAMENT_DATES:iE,INVALID_TOURNAMENT_RECORD:$a,INVALID_VALUES:k,INVALID_WINNING_SIDE:Nm,MATCHUP_NOT_FOUND:_e,METHOD_NOT_FOUND:Za,MISSING_ASSIGNMENTS:kl,MISSING_ASYNC_STATE_PROVIDER:PE,MISSING_AVOIDANCE_POLICY:ZA,MISSING_BIRTH_DATE:eE,MISSING_COLLECTION_DEFINITION:JA,MISSING_COURT_ID:Fi,MISSING_COURTS_INFO:TE,MISSING_DATE_AVAILABILITY:oE,MISSING_DATE:rE,MISSING_DRAW_DEFINITION:X,MISSING_DRAW_ID:on,MISSING_DRAW_POSITION:_s,MISSING_DRAW_POSITIONS:za,MISSING_DRAW_SIZE:Qa,MISSING_ENTRIES:qA,MISSING_EVENT:bt,MISSING_MATCHUP_FORMAT:Bl,MISSING_MATCHUP_ID:er,MISSING_MATCHUP_IDS:ns,MISSING_MATCHUP:dr,MISSING_MATCHUPS:Xn,MISSING_PARTICIPANT_COUNT:dE,MISSING_PARTICIPANT_ID:ee,MISSING_PARTICIPANT_IDS:No,MISSING_PARTICIPANT_ROLE:uE,MISSING_PARTICIPANT:Gi,MISSING_PARTICIPANTS:Ja,MISSING_PENALTY_ID:Ql,MISSING_PENALTY_TYPE:SE,MISSING_PERSON_DETAILS:fE,MISSING_POLICY_ATTRIBUTES:LI,MISSING_POLICY_DEFINITION:Zu,MISSING_POLICY_TYPE:wI,MISSING_POSITION_ASSIGNMENTS:QA,MISSING_ROUND_NUMBER:RL,MISSING_SCHEDULE:NE,MISSING_SCORING_POLICY:vL,MISSING_SEED_ASSIGNMENTS:VA,MISSING_SEEDCOUNT_THRESHOLDS:kA,MISSING_SEEDING_POLICY:CL,MISSING_SET_NUMBER:_L,MISSING_SET_OBJECT:Wl,MISSING_SIDE_NUMBER:xL,MISSING_STAGE:KA,MISSING_STRUCTURE_ID:hr,MISSING_STRUCTURE:di,MISSING_STRUCTURES:Fl,MISSING_TARGET_LINK:Ll,MISSING_TIE_FORMAT:xs,MISSING_TIME_ITEM:Jl,MISSING_TIME_ITEMS:Zl,MISSING_TOURNAMENT_ID:la,MISSING_TOURNAMENT_RECORD:j,MISSING_TOURNAMENT_RECORDS:wt,MISSING_VALUE:ot,MISSING_VENUE_ID:Xo,MODIFICATIONS_FAILED:ME,NO_CANDIDATES:np,NO_DRAW_POSITIONS_AVAILABLE_FOR_QUALIFIERS:hE,NO_MODIFICATIONS_APPLIED:Fs,NO_STAGE_SPACE_AVAILABLE_FOR_ENTRY_STATUS:BI,NO_PARTICIPANT_REMOVED:mE,NO_VALID_ACTIONS:OE,NO_VALID_ATTRIBUTES:ip,NO_VALID_DATES:nE,NOT_FOUND:Pe,NOT_IMPLEMENTED:sp,PARTICIPANT_COUNT_EXCEEDS_DRAW_SIZE:$l,PARTICIPANT_ID_EXISTS:pE,PARTICIPANT_NOT_CHECKED_IN:lE,PARTICIPANT_NOT_FOUND:Xt,PARTICIPANT_PAIR_EXISTS:wL,PENALTY_NOT_FOUND:jc,POLICY_NOT_ATTACHED:bL,POLICY_NOT_FOUND:Wc,SCHEDULE_NOT_CLEARED:_A,SCHEDULED_MATCHUPS:LE,SCORES_PRESENT:ap,SEEDSCOUNT_GREATER_THAN_DRAW_SIZE:FA,STAGE_SEQUENCE_LIMIT:zA,STRUCTURE_NOT_FOUND:Lt,TEAM_NOT_FOUND:tf,UNABLE_TO_ASSIGN_COURT:RE,UNLINKED_STRUCTURES:jA,UNRECOGNIZED_DRAW_TYPE:wl,UNRECOGNIZED_MATCHUP_FORMAT:Xa,UNRECOGNIZED_MATCHUP_STATUS:xI,VALUE_UNCHANGED:ef,VENUE_EXISTS:AE};var Ke={disableNotifications:!1,tournamentId:void 0,tournamentRecords:{},subscriptions:{},modified:!1,methods:{},notices:[]},FE={addNotice:$L,callListener:JL,cycleMutationStatus:qL,deleteNotice:QL,deleteNotices:zL,disableNotifications:LL,enableNotifications:FL,getMethods:cp,getNotices:KL,getTopics:XL,getTournamentId:AC,getTournamentRecord:kL,getTournamentRecords:GL,removeTournamentRecord:WL,setMethods:YL,setSubscriptions:jL,setTournamentId:BL,setTournamentRecord:VL,setTournamentRecords:HL,handleCaughtError:ZL};function LL(){Ke.disableNotifications=!0}function FL(){Ke.disableNotifications=!1}function AC(){return Ke.tournamentId}function kL(t){return Ke.tournamentRecords[t]}function GL(){return Ke.tournamentRecords}function VL(t){let e=t?.tournamentId;return e?(Ke.tournamentRecords[e]=t,{success:!0}):{error:$a}}function BL(t){return t?Ke.tournamentRecords[t]?(Ke.tournamentId=t,{success:!0}):{error:j}:(Ke.tournamentId=void 0,{success:!0})}function HL(t){Ke.tournamentRecords=t;let e=Object.keys(t);e.length===1?Ke.tournamentId=e[0]:e.length||(Ke.tournamentId=void 0)}function WL(t){if(typeof t!="string")return{error:k};if(!Ke.tournamentRecords[t])return{error:Pe};delete Ke.tournamentRecords[t];let e=Object.keys(Ke.tournamentRecords);return e.length===1?Ke.tournamentId=e[0]:e.length||(Ke.tournamentId=void 0),{success:!0}}function jL(t){return typeof t.subscriptions!="object"?{error:k}:(Object.keys(t.subscriptions).forEach(e=>{typeof t.subscriptions[e]=="function"?Ke.subscriptions[e]=t.subscriptions[e]:delete Ke.subscriptions[e]}),{...C})}function YL(t){return typeof t!="object"?{error:k}:(Object.keys(t).forEach(e=>{typeof t[e]=="function"&&(Ke.methods[e]=t[e])}),{...C})}function qL(){let t=Ke.modified;return Ke.modified=!1,t}function $L({topic:t,payload:e,key:r},n){if(!(typeof t!="string"||typeof e!="object")&&(Ke.disableNotifications||(Ke.modified=!0),!(Ke.disableNotifications||!Ke.subscriptions[t]&&!n)))return r&&(Ke.notices=Ke.notices.filter(o=>!(o.topic===t&&o.key===r))),Ke.notices.push({topic:t,payload:e,key:r}),{...C}}function cp(){return Ke.methods??{}}function KL({topic:t}){return Ke.notices.filter(e=>e.topic===t).map(e=>e.payload)}function zL(){Ke.notices=[]}function QL({topic:t,key:e}){Ke.notices=Ke.notices.filter(r=>(!t||r.topic===t)&&r.key!==e)}function XL(){return{topics:Object.keys(Ke.subscriptions)}}function JL({topic:t,notices:e},r){let n=Ke.subscriptions[t];n&&typeof n=="function"&&n(e);let o=r?.[t];o&&typeof o=="function"&&o(e)}function ZL({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:AC(),params:JSON.stringify(r),engine:t,methodName:e,error:o}),{error:o}}function ae(t,e){return(t??0)-(e??0)}function ut(t){return typeof t=="number"?parseInt(t.toString()):typeof t=="string"?parseInt(t):0}function On(t){return isNaN(t)?!1:t&&(t&t-1)===0}function kE(t){if(!t.length)return;let e=[...t].sort(ae),r=Math.floor(e.length/2);return e.length%2?e[r]:(e[r-1]+e[r])/2}function EC(t){if(!On(t))return!1;let e=t,r=1;for(;e!==2;)r+=1,e=e/2;return r}function Mm(t){return isNaN(t)?0:t%2&&t+1||t}function Rm(t){return Math.pow(2,Math.round(Math.log(t)/Math.log(2)))}function Jt(t){return!isNaN(parseFloat(t))}function jI(t){let e=ut(t);if(!isNaN(e))return e===0?!1:(e&-e)===1}function os(t){if(isNaN(t))return!1;for(;!On(t);)t++;return t}function mo(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 UC(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 tF(t,e){e||(e=1);let r=1/e;return Math.round(t*r)/r}function GE(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=GE(t,e,r):(a=Math.pow(a,r),a*=e-t,a+=t),n&&(a=tF(a,n)),parseFloat(a.toFixed(o))}function of(t,e=2){return parseFloat(Number(Math.round(t*1e3)/1e3).toFixed(e))}function pt(t){return Array.isArray(t)?t?.filter((e,r,n)=>n.lastIndexOf(e)===r):[]}function DC(t){return Array.isArray(t)?t?.map(e=>e===null?void 0:e):t}function lr(t){return Array.isArray(t)?t.map(e=>[Math.random(),e]).sort((e,r)=>e[0]-r[0]).map(e=>e[1]):[]}function tc(t){return ft(t)?t:1/0}function gr(t){return Array.isArray(t)?t.reduce((e,r)=>(e[r]||(e[r]=0),e[r]++,e),{}):{}}function PC(t){return VE(gr(t))}function VE(t){return Object.keys(t).reduce((e,r)=>{let n=t[r];return e[n]?e[n].push(r):e[n]=[r],e},{})}function eF(t,e,r){return r.indexOf(t)===e}function YI(t){return t.filter(eF)}function $r(t){return Array.isArray(t)&&t.length?t.splice(Math.floor(Math.random()*t.length),1)[0]:void 0}function Tn(t){let e=Math.floor(Math.random()*t.length);return t[e]}function tt(t,e){return Array.from({length:e-t},(r,n)=>n+t)}function lo(t,e){return e.reduce((r,n,o)=>(n===t&&r.push(o),r),[])}function qt(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 BE(t,e){return!Array.isArray(t)||!Array.isArray(e)?[]:t.filter(r=>!e.includes(r))}function xe(t,e){return!Array.isArray(t)||!Array.isArray(e)?!1:t.some(r=>e.includes(r))}function NC(t,e){return Array.isArray(e)&&e.reduce((r,n)=>(r[n]=1+r[n]||1,r),{})[t]||0}function MC(t,e,r,n){return Array.isArray(t)?[].concat(...t.slice(0,e),...t.slice(e,e+r).sort(n),...t.slice(e+r,t.length)):[]}function Ae(t,e){return Array.isArray(t)?t.reduce((r,n,o)=>{let i=Math.floor(o/e);return r[i]=[].concat(r[i]||[],n),r},[]):[]}function HE(t,[e,...r]){return t.length?[t.slice(0,e),...HE(t.slice(e),[...r,e])]:[]}function RC(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 qI(t){return Array.isArray(t)?t.reduce((e,r)=>!isNaN(parseInt(r))&&e,!0):!1}function $I(t){return Array.isArray(t)?t.reduce((e,r)=>isNaN(parseInt(r))&&e,!0):!1}function sf(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 CC(t,e=1){if(!Array.isArray(t)||!t.every(ft))return[];let r=Math.min(...t,e),n=Math.max(...t);return tt(r,n+1).filter(o=>!t.includes(o))}var Ne={timers:{default:{elapsedTime:0}},globalSubscriptions:{},deepCopyAttributes:{stringify:[],ignore:[],toJSON:[]},globalMethods:[],deepCopy:!0},sn=FE,bC=["addNotice","callListener","cycleMutationStatus","deleteNotice","deleteNotices","disableNotifications","enableNotifications","getMethods","getNotices","getTopics","getTournamentId","getTournamentRecord","getTournamentRecords","removeTournamentRecord","setSubscriptions","setTournamentId","setTournamentRecord","setTournamentRecords"];function rF(t){if(typeof t!="object")throw new Error("Global state provider can not be undefined or null");if(qt(Object.keys(t),bC).length!==bC.length)throw new Error("Global state provider is missing required methods");return sn=t,{success:!0}}function WE(){if(sn.createInstanceState){try{sn.createInstanceState()}catch(t){return{error:t}}return{success:!0}}else return{error:PE}}function Sr(t){return!t||typeof t!="object"?Ne.devContext??!1:typeof Ne.devContext!="object"?!1:Object.keys(t).every(e=>Ne.devContext?.[e]===t[e])&&Ne.devContext}function nF(t="reset",e="default"){let r=Date.now();if(t==="report"){if(e==="allTimers")return Object.keys(Ne.timers).filter(o=>o!=="default"||Ne.timers[o].startTime).map(o=>{let i=Ne.timers[o],s=i.state==="stopped"?0:(r-(i?.startTime??0))/1e3,a=i.elapsedTime+s;return{state:Ne.timers[o].state,elapsedTime:a.toFixed(2),timer:o}});{let n=Ne.timers[e].state==="stopped"?0:(r-(Ne.timers[e]?.startTime??0))/1e3,o=Ne.timers[e].elapsedTime+n;return{state:Ne.timers[e].state,elapsedTime:o.toFixed(2),timer:e}}}if(!Ne.timers[e]||t==="reset"){if(e==="allTimers")return Ne.timers={default:{elapsedTime:0}},!0;Ne.timers[e]={startTime:r,state:"active",elapsedTime:0}}return Ne.timers[e].elapsedTime||(Ne.timers[e].elapsedTime=0),t==="stop"&&Ne.timers[e].state!=="stopped"&&(Ne.timers[e].state="stopped")&&(Ne.timers[e].elapsedTime+=(r-(Ne.timers[e]?.startTime??0))/1e3),t==="start"&&(Ne.timers[e].startTime=r)&&(Ne.timers[e].state="active"),Ne.timers[e]}function vC(t){Vr(t)?Ne.globalLog=t:delete Ne.globalLog}function $c(t){Ne.devContext=t}function jE(){sn.disableNotifications()}function af(){sn.enableNotifications()}function Kc(t,e){typeof t=="boolean"&&(Ne.deepCopy=t),typeof e=="object"&&(Array.isArray(e.ignore)&&(Ne.deepCopyAttributes.ignore=e.ignore),Array.isArray(e.toJSON)&&(Ne.deepCopyAttributes.toJSON=e.toJSON),Array.isArray(e.stringify)&&(Ne.deepCopyAttributes.stringify=e.stringify),e.threshold&&(Ne.deepCopyAttributes.threshold=e.threshold))}function cf(){return{enabled:Ne.deepCopy,...Ne.deepCopyAttributes}}function oF(t){return t?.subscriptions?(Object.keys(t.subscriptions).forEach(e=>{Ne.globalSubscriptions[e]=t.subscriptions[e]}),{...C}):{error:ot,info:"missing subscriptions"}}function iF(t){return t?.subscriptions?sn.setSubscriptions({subscriptions:t.subscriptions}):{error:ot,info:"missing subscriptions"}}function OC(t){return t?typeof t!="object"?{error:k}:(Object.keys(t).forEach(e=>{Vr(t[e])&&(Ne.globalMethods[e]=t[e])}),{...C}):{error:ot,info:"missing method declarations"}}function _C(t){return t?typeof t!="object"?{error:k}:sn.setMethods(t):{error:ot,info:"missing method declarations"}}function uf(){return sn.cycleMutationStatus()}function dt(t){if(typeof t?.topic!="string")return;let e=Ne.globalSubscriptions[t.topic];return sn.addNotice(t,e)}function pf(){return{...Ne.globalMethods,...sn.getMethods()}}function KI(t){return sn.getNotices(t)}function zI({key:t,topic:e}){return sn.deleteNotice({key:t,topic:e})}function Bi(){return sn.deleteNotices()}function xr(){return sn.getTopics()}function up(t){return xr()?.topics?.includes(t)}async function Cm(t){return sn.callListener(t,Ne.globalSubscriptions)}function is(){return sn.getTournamentId()}function mf(t){return sn.getTournamentRecord(t)}function Vo(){return sn.getTournamentRecords()}function YE(t){return sn.setTournamentRecord(t)}function bm(t){return sn.setTournamentRecords(t)}function pp(t){return sn.setTournamentId(t)}function qE(t){return sn.removeTournamentRecord(t)}function QI(){return sn}function mp({engineName:t,methodName:e,params:r,err:n}){return(Vr(sn.handleCaughtError)&&sn.handleCaughtError||FE.handleCaughtError)({engineName:t,methodName:e,params:r,err:n})}function $E(t,e){if(Ne.globalLog)try{Ne.globalLog({log:t,engine:e})}catch(r){console.log("globalLog error",r),console.log(e,t),vC()}else console.log(e,t)}function KE(t,e,r,n){if(!It(t))return{error:k};Jt||(r=1);let o=Array.isArray(e)?e:[],i={},s=(a,c=0)=>{Object.keys(a).forEach(u=>{Vr(a[u])?i[u]=a[u]:It(a[u])&&(e===!0||o?.includes(u))&&(r===void 0||c<r)&&s(a[u],c+1)})};return s(t),n?OC(i):_C(i),{methods:i}}function sF(t,e,r){return Object.keys(t).filter(n=>!e.includes(t[n])&&(!r||(Array.isArray(t[n])?t[n].length:!0)))}function rt(t,e,r,n){if(typeof t!="object"||t===null)return t;cf()?.enabled||(n=!0);let i=["",void 0,null];e&&i.push(!1);let s=sF(t,i,r);return Object.assign({},...s.map(a=>Array.isArray(t[a])?{[a]:n?t[a]:t[a].map(c=>rt(c))}:{[a]:n?t[a]:rt(t[a])}))}function _({context:t,result:e,stack:r,info:n}){return e&&!Array.isArray(e?.stack)&&(e.stack=[]),e&&Array.isArray(e?.stack)&&typeof r=="string"&&e.stack.push(r),e&&n&&(e.info=n),e&&typeof t=="object"&&Object.keys(t).length&&Object.assign(e,rt(t)),e&&!e?.error&&!e?.success&&Object.assign(e,{...C}),e??{success:!0}}var ec="resourceSubType",rc="resourceType",nc="identifier",wC={RESOURCE_SUB_TYPE:ec,RESOURCE_TYPE:rc,IDENTIFIER:nc};var Hn="SINGLES",ks="SINGLES",Br="DOUBLES",fi="DOUBLES",Me="TEAM",Kr="TEAM",aF="AGE",cF="RATING",uF="BOTH",LC={AGE:aF,BOTH:uF,DOUBLES:Br,DOUBLES_EVENT:fi,RATING:cF,SINGLES:Hn,SINGLES_EVENT:ks,TEAM_EVENT:Kr,TEAM:Me};var et="MAIN",ct="QUALIFYING",Ve="CONSOLATION",Be="VOLUNTARY_CONSOLATION",pe="PLAY_OFF",zc=[et,ct,Ve,pe,Be],Gs={[ct]:1,[et]:2,[pe]:3,[Ve]:3,[Be]:4},zE="finishingPositions",QE="aggregateEventStructures",XE={[et]:1,[pe]:2,[Ve]:3,[ct]:4,[Be]:5},FC={[pe]:1,[et]:2,[Ve]:3,[ct]:4,[Be]:5},Qc="CLUSTER",kC="SEPARATE",gi="WATERFALL",dp="ITEM",we="CONTAINER",mn="DRAW",lp="RANDOM",yn="TOP_DOWN",Ii="BOTTOM_UP",Jn="POSITION",fo="WINNER",Zn="LOSER",to="FIRST_MATCHUP",an="AD_HOC",pF="AD_HOC",Ia="FEED_IN",Xc="COMPASS",Jc="OLYMPIC",mF="SINGLE_ELIMINATION";var go="SINGLE_ELIMINATION",Zc="DOUBLE_ELIMINATION",tu="FIRST_MATCH_LOSER_CONSOLATION",fp="FIRST_ROUND_LOSER_CONSOLATION",Hi="LUCKY_DRAW",df="CURTIS_CONSOLATION",GC="CURTIS_CONSOLATION",XI="FEED_IN_CHAMPIONSHIP_TO_SF",vm="FEED_IN_CHAMPIONSHIP_TO_SF",JI="FEED_IN_CHAMPIONSHIP_TO_QF",Om="FEED_IN_CHAMPIONSHIP_TO_QF",ZI="FEED_IN_CHAMPIONSHIP_TO_R16",_m="FEED_IN_CHAMPIONSHIP_TO_R16",JE="MODIFIED_FEED_IN_CHAMPIONSHIP",xm="MODIFIED_FEED_IN_CHAMPIONSHIP",gp="FEED_IN_CHAMPIONSHIP",VC="DOUBLE_ROUND_ROBIN",Un="ROUND_ROBIN",Io="ROUND_ROBIN_WITH_PLAYOFF",ZE="DECIDER",tU="BACKDRAW",lf={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"}},ff={0:{name:"East",abbreviation:"E"},"0-1":{name:"West",abbreviation:"W"},"0-2":{name:"North",abbreviation:"N"},"0-1-1":{name:"South",abbreviation:"S"}},Vs="WIN_RATIO",Wi="ROUND_OUTCOME",eU=[Xc,df,Om,_m,vm,gp,JI,ZI,XI,tu,fp,Hi,xm,Jc,pe,Io],dF=[an,Xc,df,Zc,Om,_m,vm,gp,Ia,tu,fp,Hi,xm,Jc,pe,Un,Io,go],rU={MAIN:et,QUALIFYING:ct,CONSOLATION:Ve,ITEM:dp,CONTAINER:we,FIRST_MATCHUP:to,WINNER:fo,LOSER:Zn,AD_HOC:an,FEED_IN:Ia,FLEX_ROUNDS:pF,COMPASS:Xc,PLAY_OFF:pe,OLYMPIC:Jc,KNOCKOUT:mF,SINGLE_ELIMINATION:go,DOUBLE_ELIMINATION:Zc,CURTIS:df,FICSF:XI,FICQF:JI,FICR16:ZI,MFIC:JE,VOLUNTARY_CONSOLATION:Be,FIRST_MATCH_LOSER_CONSOLATION:tu,FIRST_ROUND_LOSER_CONSOLATION:fp,MODIFIED_FEED_IN_CHAMPIONSHIP:xm,FEED_IN_CHAMPIONSHIP_TO_R16:_m,FEED_IN_CHAMPIONSHIP_TO_QF:Om,FEED_IN_CHAMPIONSHIP_TO_SF:vm,FEED_IN_CHAMPIONSHIP:gp,LUCKY_DRAW:Hi,ROUND_ROBIN_WITH_PLAYOFF:Io,ROUND_ROBIN:Un,DECIDER:ZE,BACKDRAW:tU,COMPASS_ATTRIBUTES:lf,OLYMPIC_ATTRIBUTES:ff,DRAW:mn,RANDOM:lp,TOP_DOWN:yn,BOTTOM_UP:Ii,WATERFALL:gi,WIN_RATIO:Vs,ROUND_OUTCOME:Wi,MULTI_STRUCTURE_DRAWS:eU,generatedDrawTypes:dF,stageOrder:Gs,finishOrder:XE,AGGREGATE_EVENT_STRUCTURES:QE,FINISHING_POSITIONS:zE},BC=rU;var De="tournamentRecords",gf="policyDefinitions",Re="tournamentRecord",th="onlineResource",Le="drawDefinition",wm="matchUpFormat",eo="participantId",eh="scheduleDates",HC="tournamentId",WC="scheduleDate",jC="roundNumber",eu="structureId",If="participant",oc="matchUpIds",rh="entryStage",YC="policyType",nU="structures",dn="matchUpId",hf="eventType",ru="inContext",Ip="structure",hp="courtIds",qC="personId",Sp="venueIds",oU="matchUps",nh="courtId",oh="eventId",_n="matchUp",ih="drawId",ho="error",Jo="event",ss="param",$C="uuids",KC="averageMatchUpMinutes",zC="recoveryMinutes",QC="periodLength",XC="number";var zr="object",ir="array";var sr="_validate",sh="_message",wr="_invalid",ar="_ofType",ah="_anyOf",ic="_oneOf";var JC={[hf]:t=>[Hn,Br,Me].includes(t),[th]:t=>qt(Object.keys(t),[ec,rc,nc]).length===3,[rh]:t=>zc.includes(t)},lF={[De]:wt,[Re]:j,[gf]:Zu,[Le]:X,[eo]:ee,[wm]:Bl,[HC]:la,[eu]:hr,[oc]:ns,[If]:Gi,[th]:po,[hf]:Bn,[nU]:Fl,[dn]:er,[Ip]:di,[nh]:Fi,[oU]:Xn,[oh]:Pr,[_n]:dr,[hp]:ot,[Sp]:ot,[ih]:on,[Jo]:bt},fF={[De]:zr,[gf]:zr,[Re]:zr,[Le]:zr,[th]:zr,[eh]:ir,[If]:zr,[oc]:ir,[nU]:ir,[Ip]:zr,[hp]:ir,[Sp]:ir,[oU]:ir,[_n]:zr,[Jo]:zr,[$C]:ir};function nt(t,e,r){if(!t&&!It(t))return{error:k};if(!e?.length||t?._bypassParamCheck)return{valid:!0};if(!Array.isArray(e))return{error:k};let{paramError:n,errorParam:o}=hF(t,e);if(!n)return{valid:!0};let i=t?.[o]===void 0?lF[o]||n[ho]||n[wr]||k:n[sr]&&(n[ho]||n[wr])||k,s=o??(n[ic]&&Object.keys(n[ic]).join(", "));return _({info:{param:s,message:n[sh]},result:{error:i},stack:r})}function ZC(t,e){let r=Object.keys(t),n=Object.keys(e);return qt(r,n)}function gF(t,e){if(!e)return;let r=ZC(t,e);return r.length!==1?{error:k}:r.reduce((n,o)=>({...n,[o]:!0}),{})}function IF(t,e){if(!e)return;let r=ZC(t,e).filter(n=>t[n]);return r.length<1?{error:k}:r.reduce((n,o)=>({...n,[o]:!0}),{})}function hF(t,e){let r,n;return{paramError:e.find(({_ofType:i,_oneOf:s,_anyOf:a,_validate:c,_info:u,...p})=>{let m=s&&gF(t,s);if(m?.error)return m.error;m&&Object.assign(p,m);let d=a&&IF(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&&!Vr(c),h=t[g]!==void 0&&!c&&SF(t,g,i),S=p[g]&&[void 0,null].includes(t[g]),y=I||h||S||c&&t[g]!==void 0&&!TF(t[g],c)||JC[g]&&!JC[g](t[g]);return y&&(r=g,n=u),y});return!l.length||f}),errorParam:r,paramInfo:n}}function SF(t,e,r){return r=r||fF[e]||"string",r==="array"?!Array.isArray(t[e]):typeof t[e]!==r}function TF(t,e){return Vr(e)?e(t):!0}var Lm="DYNAMIC",hi="RANKING",Si="RATING",Ti="SCALE",So="SEEDING",tb={RANKING:hi,RATING:Si,SCALE:Ti,SEEDING:So};function ha(t){let e=nt(t,[{[If]:!0}]);if(e.error)return e;let r=t.participant.timeItems?.filter(({itemType:o})=>o?.startsWith(Ti)&&[hi,Si,So].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===So&&"seedings"||c===hi&&"rankings"||"ratings";n[l][u]||(n[l][u]=[]),n[l][u].push({scaleValue:a.itemValue,scaleDate:a.itemDate,scaleName:d})}}}return{...C,...n}}function ji(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 Fm=/^[\d]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][\d]|3[0-1])$/,ch=/^((0[\d]|1[\d]|2[0-3]):[0-5][\d](:[0-5][\d])?)([.,][0-9]{3})?$/,Mo=/^([\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?$/,Bs=/^([\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 km(t){let{scheduledDate:e}=t;if(!e&&t.scheduledTime&&(e=Dt(t.scheduledTime)),!e)return;let r=Kt(t.scheduledTime),n=Dt(e);return n&&r&&(n+=`T${r}`),n}function eb(t){return typeof t!="object"||Array.isArray(t)?!1:Object.prototype.toString.call(t)==="[object Date]"}function nu(t){let e=typeof t=="string"?t?.split(" "):[];return t&&e?.length>1&&!["AM","PM"].includes(e[1].toUpperCase())?!1:!!(!t||Bs.test(ac(t,!0,!0)))}function Nr(t){return sc(t)||Fm.test(t)}function yF(t){let e=new Date(t),r=e.getSeconds()+60*e.getMinutes()+60*60*e.getHours();return AF(r,{displaySeconds:!1})}function AF(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(ro).join(":")}var yf=t=>{let e=Sf(t)||sc(t)?new Date(t):new Date,r=e.getUTCMonth()+1,n=r<10?`0${r}`:`${r}`;return`${e.getUTCFullYear()}-${ro(n)}-${ro(e.getUTCDate())}`};function EF(t){let e=Sf(t)||sc(t)?new Date(t):new Date;return Date.UTC(e.getFullYear(),e.getMonth(),e.getDate())}function To(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 uh(t){let e=t?new Date(t):new Date,r=e.getTimezoneOffset();return new Date(e.getTime()-r*60*1e3)}function UF(t){return uh(t).getTime()}function Sf(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 Hs(t,e){if(!Nr(t)||!Nr(e))return[];let r=Dt(t)+"T00:00",n=Dt(e)+"T00:00",o=new Date(r),i=new Date(n),s=Sf(i)&&Sf(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=>To(p));function u(p,m){return p<=m}}var DF=/^([+-]?\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 sc(t){return typeof t!="string"?!1:DF.test(t)}function mh(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=Kt(t);if(!e)return 0;let[r,n]=e.split(":").map(o=>parseInt(o));return r*60+n}function rb(t){let e=Math.floor(t/60),r=t-e*60;return e>23&&(e=e%24),[ro(e),ro(r)].join(":")}function Tf(t){return mh(t)?t.split(":").slice(0,2).map(ro).join(":"):void 0}function Kt(t){return sc(t)&&t.indexOf("T")>0?Tf(t.split("T").reverse()[0]):Tf(t)}function Dt(t){return sc(t)||Mo.test(t)?t.split("T")[0]:void 0}function Tp(t,e){let r=new Date(t);return r.setDate(r.getDate()+e),Dt(r.toISOString())}function ph(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 PF(t){let e=ph(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(ro).join(":")}function NF(t){let e=ph(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 ac(t,e,r){let n=Dt(t),o=Kt(t),i=n?o:t;return t?e&&(n&&r&&t||PF(i))||NF(i):void 0}function dh(t,e){let r=ph(t),n=ph(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 nb(t,e=7){let r=Dt(t)+"T00:00",n=new Date(r),o=new Date(n.setDate(n.getDate()+e));return To(o)}function MF(t){return nb(t)}function RF(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())),To(o,r)}function ob(t,e,r){let n=new Date(t,0);return To(new Date(n.setDate(e)),r)}function Fe(t,e=void 0){let[r,n]=(t||"00:00").split(":").map(ro),o=uh(e).setHours(r,n,0,0);return uh(o)}function Sa(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 Hr(t,e){let r=Kt(t);if(!r)return"00:00";let n=isNaN(e)?0:e;return Kt(Af(Fe(r),n).toISOString())}function Af(t,e){let r=new Date(t);return new Date(r.getTime()+e*6e4)}function ro(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 lh={addDays:nb,addWeek:MF,addMinutesToTimeString:Hr,convertTime:ac,getIsoDateString:km,getUTCdateString:yf,DateHHMM:yF,extractDate:Dt,extractTime:Kt,formatDate:To,getDateByWeek:RF,isISODateString:sc,isDate:Sf,isTimeString:mh,offsetDate:uh,offsetTime:UF,sameDay:Wn,timeStringMinutes:Vt,timeToDate:Fe,timeUTC:EF,validTimeValue:nu,validDateString:Fm,timeValidation:Bs,dateValidation:Mo};function J(t,e,r,n,o=0){if(QI().makeDeepCopy)return QI().makeDeepCopy(t,e,r,n);let i=cf(),{stringify:s,toJSON:a,ignore:c,modulate:u}=i||{};if(!i?.enabled&&!r||typeof t!="object"||Vr(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)||Vr(c)&&!c(l)),d=(l,f)=>{p[l]=Vr(f?.toString)?f.toString():JSON.stringify(f)};for(let l of m){let f=t[l],g=Vr(u)?u(f):void 0;if(g!==void 0)p[l]=g;else if(e&&l==="extensions"&&Array.isArray(f)){let I=Ef(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)&&Vr(f?.toJSON)?p[l]=f.toJSON():f===null?p[l]=void 0:eb(f)?p[l]=new Date(f).toISOString():p[l]=J(f,e,r,n,o+1)}return p}function Ef(t){return t?.map(e=>{let{name:r,value:n}=e;return r&&n&&{[`_${r}`]:n}}).filter(Boolean)}var fh="voluntaryConsolation",yi="competitiveBands",Uf="roundRobinTally",yo="positionActions",ze="matchUpActions",Df="rankingPoints",Ta="roundNaming",Ws="participant",ou="progression",Ro="scheduling",iu="avoidance",CF="participant",bF="display",Qr="scoring",xn="seeding",cc="feedIn",vF="audit",Gm="draws",ib={POLICY_TYPE_VOLUNTARY_CONSOLATION:fh,POLICY_TYPE_COMPETITIVE_BANDS:yi,POLICY_TYPE_ROUND_ROBIN_TALLY:Uf,POLICY_TYPE_POSITION_ACTIONS:yo,POLICY_TYPE_MATCHUP_ACTIONS:ze,POLICY_TYPE_RANKING_POINTS:Df,POLICY_TYPE_ROUND_NAMING:Ta,POLICY_TYPE_PARTICIPANT:Ws,POLICY_TYPE_PROGRESSION:ou,POLICY_TYPE_SCHEDULING:Ro,POLICY_TYPE_AVOIDANCE:iu,POLICY_TYPE_DISPLAY:bF,POLICY_TYPE_PRIVACY:CF,POLICY_TYPE_FEED_IN:cc,POLICY_TYPE_SCORING:Qr,POLICY_TYPE_SEEDING:xn,POLICY_TYPE_AUDIT:vF,POLICY_TYPE_DRAWS:Gm};function Bo({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}=ha({participant:a});a.rankings=p,a.ratings=u}if(c?.participant)return ji({template:c.participant,source:a})}return a}var sb="element required",ab="missing name";function ur(t){if(!t||typeof t!="object")return{error:ot};if(t.element&&typeof t?.element!="object")return{error:k};if(!t?.name)return{error:ot,info:ab};if(!t?.element){if(t.discover&&t.tournamentRecords){for(let e of Object.keys(t.tournamentRecords)){let r=t.tournamentRecords[e],n=ur({element:r,name:t.name});if(n.error)return _({result:n,stack:"removeExtension"})}return{...C}}return{error:ot,info:sb}}return t?.element.extensions?(t.element.extensions=t.element.extensions.filter(e=>e?.name!==t.name),{...C}):{...C,info:Pe}}function wn({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 At(t){if(typeof t!="object")return{error:ot};let e="addExtension";if(t?.element&&typeof t.element!="object")return _({result:{error:k},stack:e});if(!wn({extension:t.extension}))return _({result:{error:k,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=At({extension:t.extension,element:o});if(i.error)return _({result:i,stack:e})}return{...C}}else return _({result:{error:ot},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),{...C}}function Pf(t){return!t||typeof t!="object"?{error:ot}:t.tournamentRecord?At({creationTime:t.creationTime,element:t.tournamentRecord,extension:t.extension}):{error:j}}function yp(t){return!t||typeof t!="object"?{error:ot}:t.drawDefinition?At({creationTime:t.creationTime,element:t.drawDefinition,extension:t.extension}):{error:Dr}}function Co(t){return!t||typeof t!="object"?{error:ot}:t.event?At({creationTime:t.creationTime,extension:t.extension,element:t.event}):{error:Pr}}function iU(t){if(!t||typeof t!="object")return{error:ot};if(!t.participantId)return{error:ee};let e=t.tournamentRecord?.participants||[],r=Bo({participantId:t.participantId,tournamentParticipants:e});return r?At({creationTime:t.creationTime,extension:t.extension,element:r}):{error:Xt}}function Nf(t){return!t||typeof t!="object"?{error:ot}:t.tournamentRecord?ur({element:t.tournamentRecord,name:t.name}):{error:j}}function sU(t){return!t||typeof t!="object"?{error:ot}:t.drawDefinition?ur({element:t.drawDefinition,name:t.name}):{error:Dr}}function Ap(t){return!t||typeof t!="object"?{error:ot}:t?.event?ur({element:t.event,name:t.name}):{error:Pr}}function aU(t){if(!t||typeof t!="object")return{error:ot};if(!t.participantId)return{error:ee};let e=t.tournamentRecord?.participants||[],r=Bo({participantId:t.participantId,tournamentParticipants:e});return r?ur({element:r,name:t.name}):{error:Xt}}function Ep({tournamentRecords:t}){return{tournamentIds:It(t)?Object.keys(t):[],...C}}var OF="extensionQueries";function mt({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:Pe}}return _({result:{error:ot},stack:OF})}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:Pe}}var _F="activeSuspension",su="appliedPolicies",cU="context",Vm="delegatedOutcome",no="disabled",ya="disableAutoCalc",Bm="disableLinks",Hm="display",Aa="drawDeletions",xF="drawProfile",Wm="entryProfile",wF="eventProfile",LF="eventWithdrawalRequests",FF="factory",cn="flightProfile",gh="groupingAttribute",bo="lineUps",js="linkedTournamentsIds",jm="matchUpHistory",Ih="participantRepresentatives",Ea="personRequests",Up="positionActions",kF="rankingPoints",GF="registration",Dn="roundTarget",au="scheduleLimits",Ho="scheduleTiming",Ua="schedulingProfile",VF="statusDetail",uc="subOrder",Zo="tally",Ym="tieFormatModification",hh={ACTIVE_SUSPENSION:_F,APPLIED_POLICIES:su,CONTEXT:cU,DELEGATED_OUTCOME:Vm,DISABLED:no,DISABLE_LINKS:Bm,DISABLE_AUTO_CALC:ya,DISPLAY:Hm,DRAW_DELETIONS:Aa,DRAW_PROFILE:xF,ENTRY_PROFILE:Wm,EVENT_PROFILE:wF,EVENT_WITHDRAWAL_REQUESTS:LF,FLIGHT_PROFILE:cn,GROUPING_ATTRIBUTE:gh,LINEUPS:bo,LINKED_TOURNAMENTS:js,MATCHUP_HISTORY:jm,PARTICIPANT_REPRESENTATIVES:Ih,PERSON_REQUESTS:Ea,POSITION_ACTIONS:Up,RANKING_POINTS:kF,REGISTRATION:GF,ROUND_TARGET:Dn,SCHEDULE_LIMITS:au,SCHEDULE_TIMING:Ho,SCHEDULING_PROFILE:Ua,STATUS_DETAIL:VF,SUB_ORDER:uc,TALLY:Zo,TIE_FORMAT_MODIFICATIONS:Ym,FACTORY:FF},uU=[Vm,no,ya,Bm,cn,bo,js,jm,Ih,Ea,Dn,au,Ho,Ua,uc,Zo,Ym];function pU({tournamentRecords:t}){if(typeof t!="object"||!Object.keys(t).length)return{error:wt};let e=Ep({tournamentRecords:t}),{tournamentIds:r}=e;return r?.length>1?At({tournamentRecords:t,discover:!0,extension:{name:js,value:{tournamentIds:r}}}):{...C}}function mU({tournamentRecords:t}){if(typeof t!="object"||!Object.keys(t).length)return{error:wt};let e=ur({name:js,tournamentRecords:t,discover:!0});return _({result:e,stack:"unlinkTournaments"})}function dU({tournamentRecords:t,tournamentId:e}){if(typeof t!="object")return{error:k};if(!e)return{error:la};let r=Ep({tournamentRecords:t}),{tournamentIds:n}=r;if(!n.includes(e))return{error:la};let o;return n.every(i=>{let s=t[i],{extension:a}=mt({element:s,name:js});if(!a)return!0;let c=a?.value?.tournamentIds||[];if(!c?.length||c.length===1&&c.includes(e)||i===e){let m=Nf({name:js,tournamentRecord:s});return m.error&&(o=m.error),m.success}let u=c.filter(m=>m!==e);a.value={tournamentIds:u};let p=Pf({tournamentRecord:s,extension:a});return p.error&&(o=p.error),p.success}),o?{error:o}:{...C}}var fU={};Qt(fU,{getLinkedTournamentIds:()=>cu,getTournamentIds:()=>Ep});function cu({tournamentRecords:t}){return typeof t!="object"||!Object.keys(t).length?{error:wt}:{linkedTournamentIds:Object.assign({},...Object.keys(t).map(r=>{let n=t[r],o=n?.tournamentId,{extension:i}=mt({element:n,name:js}),s=(i?.value?.tournamentIds||[]).filter(a=>a!==o);return{[r]:s}}))}}var _N={};Qt(_N,{adHocPositionSwap:()=>DD,addAdHocMatchUps:()=>vd,addDrawDefinitionTimeItem:()=>Tg,addFinishingRounds:()=>Ra,addGoesTo:()=>Ki,addPlayoffStructures:()=>Yp,addQualifyingStructure:()=>UD,addVoluntaryConsolationStage:()=>SD,addVoluntaryConsolationStructure:()=>pg,allPlayoffPositionsFilled:()=>AS,alternateDrawPositionAssignment:()=>nD,assignDrawPosition:()=>GD,assignDrawPositionBye:()=>kr,attachConsolationStructures:()=>wD,attachPlayoffStructures:()=>bg,attachQualifyingStructure:()=>Sg,attachStructures:()=>vg,autoSeeding:()=>ox,automatedPlayoffPositioning:()=>Dc,automatedPositioning:()=>Uc,checkValidEntries:()=>xd,deleteAdHocMatchUps:()=>VD,drawMatic:()=>Kd,findDrawDefinition:()=>KS,generateAdHocMatchUps:()=>Gu,generateAdHocRounds:()=>$d,generateAndPopulatePlayoffStructures:()=>bd,generateDrawDefinition:()=>Va,generateDrawMaticRound:()=>kd,generateDrawStructuresAndLinks:()=>wd,generateDrawTypeAndModifyDrawDefinition:()=>Ld,generateQualifyingStructure:()=>Dd,generateVoluntaryConsolation:()=>fT,getAssignedParticipantIds:()=>Oi,getAvailableMatchUpsCount:()=>Od,getAvailablePlayoffProfiles:()=>Ru,getDrawDefinitionTimeItem:()=>Oh,getDrawParticipantRepresentativeIds:()=>qS,getDrawStructures:()=>ln,getDrawTypeCoercion:()=>Fu,getEligibleVoluntaryConsolationParticipants:()=>YS,getMatchUpsMap:()=>Ee,getParticipantIdFinishingPositions:()=>$S,getPositionAssignments:()=>qp,getPositionsPlayedOff:()=>Nc,getSeedingThresholds:()=>mS,getSeedsCount:()=>ku,getStructureSeedAssignments:()=>en,getTeamLineUp:()=>ls,getValidGroupSizes:()=>wp,isAdHoc:()=>pr,isCompletedStructure:()=>si,isValidForQualifying:()=>aT,luckyLoserDrawPositionAssignment:()=>rD,modifyDrawDefinition:()=>LD,modifyDrawName:()=>Og,modifySeedAssignment:()=>cD,mutate:()=>WD,positionActions:()=>sT,pruneDrawDefinition:()=>kD,qualifierDrawPositionAssignment:()=>aD,query:()=>tP,removeDrawPositionAssignment:()=>Pu,removeRoundMatchUps:()=>BD,removeSeededParticipant:()=>ED,removeStructure:()=>hD,renameStructures:()=>ID,resetDrawDefinition:()=>FD,resetVoluntaryConsolationStructure:()=>DU,setDrawParticipantRepresentativeIds:()=>hU,setPositionAssignments:()=>iD,setStructureOrder:()=>gD,setSubOrder:()=>HD,shiftAdHocRounds:()=>oD,swapAdHocRounds:()=>sD,swapDrawPositionAssignments:()=>AD,updateTeamLineUp:()=>Qi,withdrawParticipantAtDrawPosition:()=>tD});var WD={};Qt(WD,{adHocPositionSwap:()=>DD,addAdHocMatchUps:()=>vd,addDrawDefinitionTimeItem:()=>Tg,addPlayoffStructures:()=>Yp,addQualifyingStructure:()=>UD,addVoluntaryConsolationStage:()=>SD,addVoluntaryConsolationStructure:()=>pg,alternateDrawPositionAssignment:()=>nD,assignDrawPosition:()=>GD,assignDrawPositionBye:()=>kr,attachConsolationStructures:()=>wD,attachPlayoffStructures:()=>bg,attachQualifyingStructure:()=>Sg,attachStructures:()=>vg,automatedPlayoffPositioning:()=>Dc,automatedPositioning:()=>Uc,deleteAdHocMatchUps:()=>VD,luckyLoserDrawPositionAssignment:()=>rD,modifyDrawDefinition:()=>LD,modifyDrawName:()=>Og,modifySeedAssignment:()=>cD,pruneDrawDefinition:()=>kD,qualifierDrawPositionAssignment:()=>aD,removeDrawPositionAssignment:()=>Pu,removeRoundMatchUps:()=>BD,removeSeededParticipant:()=>ED,removeStructure:()=>hD,renameStructures:()=>ID,resetDrawDefinition:()=>FD,resetVoluntaryConsolationStructure:()=>DU,setDrawParticipantRepresentativeIds:()=>hU,setPositionAssignments:()=>iD,setStructureOrder:()=>gD,setSubOrder:()=>HD,shiftAdHocRounds:()=>oD,swapAdHocRounds:()=>sD,swapDrawPositionAssignments:()=>AD,updateTeamLineUp:()=>Qi,withdrawParticipantAtDrawPosition:()=>tD});var IU=t=>e=>t[e],qm=(t=[])=>t.map(Ie).filter(Boolean),Mf=(t=[])=>t.map(ht).filter(Boolean),ht=(t={})=>IU(t)("participantId");var Ie=(t={})=>IU(t)("matchUpId"),uu=(t={})=>IU(t)("drawId");function hU({representativeParticipantIds:t,drawDefinition:e}){if(!e)return{error:Dr};if(!Array.isArray(t))return{error:k};let r=Mf(e?.entries||[]);return t.length&&qt(t,r).length<t.length?{error:k}:yp({drawDefinition:e,extension:{name:Ih,value:t}})}var Mr="ABANDONED",pc="AWAITING_RESULT",Pt="BYE",oo="CANCELLED",ue="COMPLETED",pu="DEAD_RUBBER",Mt="DEFAULTED",Ce="DOUBLE_DEFAULT",he="DOUBLE_WALKOVER",Ln="IN_PROGRESS",Pn="INCOMPLETE",SU="NOT_PLAYED",Qe="RETIRED",as="SUSPENDED",zt="TO_BE_PLAYED",vt="WALKOVER",cb=[pc,ue,Mt,Ln,Pn,Qe,as],Sh=[pc,ue,Mt,he,Ce,Ln,Pn,Qe,as,vt],Th=[Mr,pc,Pt,oo,ue,pu,Mt,he,Ce,Ln,Pn,SU,Qe,as,zt,vt],yh=[Pt,he,Ce,ue,Mt,Qe,vt],Ah=[Mr,pc,oo,pu,Ln,Pn,SU,as,zt,void 0],ie=[oo,Mr,ue,pu,Mt,he,Ce,Qe,vt],$m=[Mr,ue,Mt,he,Ce,Ln,Qe,vt],Eh=[Ln,Pn,as,zt],Uh={ABANDONED:Mr,AWAITING_RESULT:pc,BYE:Pt,CANCELLED:oo,COMPLETED:ue,DEAD_RUBBER:pu,DEFAULTED:Mt,DOUBLE_WALKOVER:he,DOUBLE_DEFAULT:Ce,IN_PROGRESS:Ln,INCOMPLETE:Pn,NOT_PLAYED:SU,RETIRED:Qe,SUSPENDED:as,TO_BE_PLAYED:zt,WALKOVER:vt};function Ai(t,e,r){let n=m=>mt({element:m,name:Dn})?.extension?.value,o=r?.deprioritizeCompleted,i=r?.mode===QE&&FC,s=r?.mode===zE&&XE,a=s||i||Gs,c=m=>m?.stage===et&&m?.stageSequence===1,u=m=>c(m)?-1:a[m?.stage],p=m=>m?.matchUps.every(({matchUpStatus:d})=>ie.includes(d)?1:-1);return o&&p(t)-p(e)||i&&u(t)-u(e)||(t?.stage&&a[t.stage]||0)-(e?.stage&&a[e.stage]||0)||(n(t)||0)-(n(e)||0)||!s&&!i&&(e?.positionAssignments?.length??1/0)-(t?.positionAssignments?.length??1/0)||(t?.stageSequence??0)-(e?.stageSequence??0)||(Rf(t)||0)-(Rf(e)||0)}function Rf(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 at(t){let e=nt(t,[{[Le]:!0,[eu]:!0}]);if(e.error)return e;let{drawDefinition:r,structureId:n}=t,{structures:o}=ln({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:Lt};let a=s.structureType===dp?i?.find(c=>c.structures?.some(u=>u.structureId===n)):void 0;return{structure:s,containingStructure:a}}function ln({withStageGrouping:t,drawDefinition:e,stageSequences:r,stageSequence:n,roundTarget:o,sortConfig:i,stages:s,stage:a}){let c=!e&&X||!e?.structures&&Fl||void 0;if(c)return{error:c,structures:[],stageStructures:{}};let u=f=>{let g=mt({element:f,name:Dn})?.extension?.value;return!o||o===g},p=e?.structures?.filter(d).filter(l).filter(u).sort((f,g)=>Ai(f,g,i))??[],m=t?Object.assign({},...zc.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 Dh({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(ht).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}=at({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=QA,{positionAssignments:o,error:n}}function le({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 Cf="addDrawDefinition",Dp="addMatchUps",ti="addParticipants",bf="addScaleItems",Ph="addVenue",Ei="audit",Nh="dataIssue",vf="deleteParticipants",Of="deleteVenue",_f="deletedDrawIds",xf="deletedMatchUpIds",wf="modifyDrawDefinition",TU="modifyDrawEntries",yU="modifyEventEntries",Lf="modifyMatchUp",Xe="modifyParticipants",Ff="modifyPositionAssignments",kf="modifySeedAssignments",Yi="modifyTournamentDetail",Ui="modifyVenue",Km="mutations",Mh="publishEvent",AU="publishEventSeeding",EU="publishOrderOfPlay",UU="publishParticipants",Gf="unPublishEvent",Vf="unPublishEventSeeding",Bf="unPublishOrderOfPlay",ub="unPublishParticipants",Pp="updateInContextMatchUp",pb={ADD_DRAW_DEFINITION:Cf,ADD_MATCHUPS:Dp,ADD_PARTICIPANTS:ti,ADD_SCALE_ITEMS:bf,ADD_VENUE:Ph,AUDIT:Ei,DATA_ISSUE:Nh,DELETE_PARTICIPANTS:vf,DELETE_VENUE:Of,DELETED_DRAW_IDS:_f,DELETED_MATCHUP_IDS:xf,MODIFY_DRAW_DEFINITION:wf,MODIFY_DRAW_ENTRIES:TU,MODIFY_EVENT_ENTRIES:yU,MODIFY_MATCHUP:Lf,MODIFY_PARTICIPANTS:Xe,MODIFY_POSITION_ASSIGNMENTS:Ff,MODIFY_SEED_ASSIGNMENTS:kf,MODIFY_TOURNAMENT_DETAIL:Yi,MODIFY_VENUE:Ui,MUTATIONS:Km,PUBLISH_EVENT_SEEDING:AU,PUBLISH_EVENT:Mh,PUBLISH_ORDER_OF_PLAY:EU,PUBLISH_PARTICIPANTS:UU,UNPUBLISH_EVENT_SEEDING:Vf,UNPUBLISH_EVENT:Gf,UNPUBLISH_ORDER_OF_PLAY:Bf,UPDATE_INCONTEXT_MATCHUP:Pp};function Rh(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)}),{...C}}function vo({drawDefinition:t,tournamentId:e,matchUps:r,eventId:n}){return t&&Rh(t),dt({payload:{matchUps:r,tournamentId:e,eventId:n},topic:Dp}),{...C}}function jn({drawDefinition:t,tournamentId:e,matchUpIds:r,eventId:n,action:o}){t&&Rh(t),dt({topic:xf,payload:{tournamentId:e,matchUpIds:r,eventId:n,action:o}});for(let i of r)zI({key:i});return{...C}}function gt({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}),dt({topic:Lf,payload:{matchUp:i,tournamentId:e,context:n},key:i.matchUpId}),{...C}):(console.log(dr),{error:dr})}function mb({tournamentId:t,inContextMatchUp:e}){return e?(dt({payload:{inContextMatchUp:e,tournamentId:t},topic:Pp,key:e.matchUpId}),{...C}):{error:dr}}function Da({tournamentId:t,eventId:e,drawDefinition:r}){return r?(Rh(r),dt({payload:{drawDefinition:r,tournamentId:t,eventId:e},topic:Cf,key:r.drawId}),{...C}):(console.log(X),{error:X})}function db({tournamentId:t,eventId:e,drawId:r}){return dt({payload:{drawId:r,tournamentId:t,eventId:e},topic:_f,key:r}),zI({key:r}),{...C}}function Ot({drawDefinition:t,tournamentId:e,structureIds:r,eventId:n}){return t?(Rh(t,r),dt({payload:{tournamentId:e,eventId:n,drawDefinition:t},topic:wf,key:t.drawId}),{...C}):{error:X}}function Ch({drawDefinition:t,tournamentId:e,structure:r,eventId:n}){if(!t)return{error:X};if(!r)return{error:di};let o=r.seedAssignments,i=r.structureId,s=t.drawId;return dt({payload:{tournamentId:e,eventId:n,drawId:s,structureId:i,seedAssignments:o},topic:kf,key:t.drawId}),Ot({structureIds:[i],drawDefinition:t,tournamentId:e,eventId:n}),{...C}}function Oo({drawDefinition:t,tournamentId:e,structure:r,event:n}){if(!t)return{error:X};if(!r)return{error:di};let o=Ct({structure:r}),i=r.structureId,s=t.drawId,a=n?.eventId;return dt({topic:Ff,payload:{positionAssignments:o,tournamentId:e,structureId:i,eventId:a,drawId:s},key:i}),Ot({structureIds:[i],drawDefinition:t,tournamentId:e,eventId:a}),{...C}}function DU({tournamentRecord:t,drawDefinition:e,resetEntries:r,event:n}){if(!e)return{error:X};let o=e.structures?.find(s=>s.stage===Be);if(!o)return{error:Lt};let i=o.matchUps?.map(({matchUpId:s})=>s)||[];return o.positionAssignments=[],o.seedAssignments=[],o.matchUps=[],jn({tournamentId:t?.tournamentId,action:"resetVoluntaryConsolationStructure",matchUpIds:i,drawDefinition:e}),r&&(e.entries=e.entries.filter(s=>s.entryStage!==Be)),Ot({tournamentId:t?.tournamentId,eventId:n?.eventId,drawDefinition:e,structureIds:[o.structureId]}),{...C}}function zm({drawPositions:t,structure:e}){if([ct,et].includes(e.stage)&&e.stageSequence===1)return;let{positionAssignments:r}=Ct({structure:e});r?.filter(({drawPosition:o})=>t?.includes(o))?.forEach(o=>{At({element:o,extension:{name:Bm,value:!0}})})}function mu(t){let{appliedPolicies:e,positionAction:r,drawDefinition:n}=t;if(e?.audit?.[Up]===!1)return;let{extension:o}=mt({name:Up,element:n}),i=Array.isArray(o?.value)?o?.value??[]:[];if(!i?.length){let a=n.structures.find(c=>c.stage===et);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:Up};At({element:n,extension:s})}function cs({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 Pa="SINGLES",Bt="SINGLES",qi="DOUBLES",kt="DOUBLES",Nn="TEAM",Ht="TEAM",lb={SINGLES_MATCHUP:Pa,SINGLES:Bt,DOUBLES_MATCHUP:qi,DOUBLES:kt,TEAM_MATCHUP:Nn,TEAM:Ht};function du(t){let{sides:e,matchUpType:r}=t||{},n=t.potentialParticipants?.length?t.potentialParticipants.flat().map(s=>r===kt?s?.individualParticipantIds||[]:s.participantId).flat():[],o=(e||[]).map(s=>r===kt&&(s?.participant?.individualParticipantIds||[])||s?.participantId&&[s.participantId]||[]).flat();return{individualParticipantIds:o.concat(n).flat(),enteredIndividualParticipantIds:o,potentialIndividualParticipantIds:n}}function Tr(t){return t?.tournamentRecords??(t?.tournamentRecord&&{[t.tournamentRecord.tournamentId]:t.tournamentRecord})??{}}var mc="SIGN_IN_STATUS",PU="SIGNED_OUT",lu="SIGNED_IN",fn="TEAM",Tt="INDIVIDUAL",Rr="GROUP",lt="PAIR",Ft="TEAM",fu={TEAM_PARTICIPANT:fn,INDIVIDUAL:Tt,GROUP:Rr,TEAM:Ft,PAIR:lt},fb={INDIVIDUAL:Tt,GROUP:Rr,PAIR:lt,TEAM:Ft,SIGN_IN_STATUS:mc,SIGNED_OUT:PU,SIGNED_IN:lu};function Qm({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===Ft),s=o.filter(c=>c.participantType===Rr),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 NU(t){return t&&typeof String.fromCodePoint<"u"?t.toUpperCase().replace(/./g,e=>String.fromCodePoint(e.charCodeAt(0)+127397)):t}function gb(t){let e=Object.assign({},...ei.filter(r=>r.ioc).map(r=>({[r.ioc]:r.iso})));return NU(e[t])}var ei=[{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 bh({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=ei.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 Ib({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?ji({template:e,source:s}):s)}}}}function Ao(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:Xt}}function vh(t){let{tournamentRecord:e,participantId:r}=t;if(r){let o=Ao({tournamentRecord:e,participantId:r});return o.participant??o}let n=t.element||t.drawDefinition||t.event||t.tournamentRecord;return n||{error:ot}}function Xr(t){let{returnPreviousValues:e,itemSubTypes:r,itemType:n}=t,o=vh(t);if(o.error)return o;if(r&&!Array.isArray(r))return{error:k,context:{itemSubTypes:r}};if(!Array.isArray(o.timeItems))return{error:Zl};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,...C};return e&&Object.assign(a,{previousItems:i}),a}else return{info:Pe}}function Oh({returnPreviousValues:t,drawDefinition:e,itemSubTypes:r,itemType:n}){if(!e)return{error:on};if(!e.timeItems)return{info:Pe};let{timeItem:o,previousItems:i,info:s}=Xr({element:e,returnPreviousValues:t,itemSubTypes:r,itemType:n});return o&&{timeItem:o,previousItems:i}||{info:s}}function gu({returnPreviousValues:t,itemSubTypes:e,itemType:r,event:n}){if(!n)return{error:bt};if(!n.timeItems)return{info:Pe};let{timeItem:o,previousItems:i,info:s}=Xr({returnPreviousValues:t,element:n,itemSubTypes:e,itemType:r});return o&&{timeItem:o,previousItems:i}||{info:s}}function Xm({returnPreviousValues:t,tournamentRecord:e,itemSubTypes:r,itemType:n}){if(!e)return{error:j};if(!e.timeItems)return{info:Pe};let{timeItem:o,previousItems:i,info:s}=Xr({element:e,returnPreviousValues:t,itemSubTypes:r,itemType:n});return o&&{timeItem:o,previousItems:i}||{info:s}}function _h({returnPreviousValues:t,tournamentRecord:e,participantId:r,itemSubTypes:n,itemType:o}){if(!e)return{error:j};if(!r)return{error:ee};let i=Ao({tournamentRecord:e,participantId:r});if(i.error)return i;let{participant:s}=i;if(!s?.timeItems)return{info:Pe};let{timeItem:a,previousItems:c,info:u}=Xr({element:i.participant,returnPreviousValues:t,itemSubTypes:n,itemType:o});return a&&{timeItem:a,previousItems:c}||{info:u}}var BF={[Rr]:"groupParticipantIds",[lt]:"pairParticipantIds",[Ft]:"teamParticipantIds"},HF={[Rr]:"groups",[Ft]:"teams"};function xh({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&&YF({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&&jF({individualParticipantIds:d,participantCopy:p,participantMap:c,participantType:l,participantId:m}),n&&(c[m].participant.signedIn=WF(p)),o){let{ratings:f,rankings:g,seedings:I}=ha({participant:p});c[m].participant.seedings=I,c[m].participant.rankings=g,c[m].participant.ratings=f}(a||s)&&bh({participant:c[m].participant,withISO2:s,withIOC:a})}if(t){let u=It(t)?t:void 0;Ib({participantMap:c,template:u})}return{participantMap:c}}function WF(t){let{timeItem:e}=Xr({itemType:mc,element:t});return e?.itemValue===lu}function jF({individualParticipantIds:t,participantCopy:e,participantMap:r,participantType:n,participantId:o}){for(let i of t){let s=r[i].participant;if(s[BF[n]].push(o),[Ft,Rr].includes(n)){let{participantRoleResponsibilities:a,participantOtherName:c,participantName:u,participantId:p,teamId:m}=e,d=HF[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 YF({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:{[Bt]:{...r},[kt]:{...r},[Ft]:{...r},...r}}}function Di({participantsProfile:t,useParticipantMap:e,tournamentRecord:r,contextProfile:n,inContext:o}){if(e)return{participantMap:xh({...t,...n,tournamentRecord:r})?.participantMap};let i=J(r.participants,!1,!0)||[];(t?.withIOC||t?.withISO2)&&i.forEach(a=>bh({participant:a,...t}));let s;if((o||t?.withGroupings)&&i?.length&&({participantsWithGroupings:i,groupInfo:s}=Qm({participantsProfile:t,deepCopy:!1,participants:i})),t?.withScaleValues&&i?.length)for(let a of i){let{ratings:c,rankings:u}=ha({participant:a});a.rankings=u,a.ratings=c}return{participants:i,groupInfo:s}}function yt({onlySpecifiedPolicyTypes:t=!1,policyTypes:e=[],tournamentRecord:r,drawDefinition:n,structure:o,event:i}){if(!Array.isArray(e))return{error:wI};let s={};return r&&a(r),i&&a(i),n&&a(n),o&&a(o),{appliedPolicies:s,...C};function a(c){let p=c?.extensions?.find(m=>m.name===su)?.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 _o({policyTypes:t=[],tournamentRecord:e,drawDefinition:r,structure:n,event:o}){if(!Array.isArray(t))return{error:wI};let{appliedPolicies:i}=yt({tournamentRecord:e,drawDefinition:r,structure:n,event:o}),s={};for(let a of t){let c=i?.[a];c&&(s[a]=c)}return Object.keys(s).length?{policyDefinitions:s}:{info:Wc.message}}var wh="WALKOVER",MU="RETIRED",Jm="COMPETITIVE",dc="ROUTINE",lc="DECISIVE",Zm="winRatio";var qF={[yi]:{policyName:"Competitive Bands Default",profileBands:{[lc]:20,[dc]:50}}},td=qF;function Yn({policyDefinitions:t,tournamentRecord:e,contextProfile:r,drawDefinition:n,event:o}){let i={policies:{}};if(!r)return i;let s=_o({tournamentRecord:e,drawDefinition:n,event:o}).policyDefinitions;if(r.withCompetitiveness){let a=t?.[yi]??s?.[yi]??td[yi];i.policies[yi]=a}return i}function ri({tournamentRecord:t,drawDefinition:e,policyType:r,structure:n,event:o}){if(!t)return{error:j};let{appliedPolicies:i}=yt({tournamentRecord:t,drawDefinition:e,structure:n,event:o});return i?.[r]?{policy:i[r]}:{info:Wc?.message}}function Na({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}=ri({policyType:Ro,tournamentRecord:t,event:n}),s=(t?mt({element:t,name:Ho}).extension:void 0)?.value,c=(n&&mt({name:Ho,element:n}).extension)?.value;return{scheduleTiming:{tournamentScheduling:s,eventScheduling:c,categoryName:e,categoryType:r,policy:o}}}function Hf({drawDefinition:t,attributes:e}){let{extension:r}=mt({element:t,name:Wm}),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:Wm,value:n},yp({drawDefinition:t,extension:r}),{entryProfile:n}}function Iu({drawDefinition:t}){let{extension:e}=mt({element:t,name:Wm});return{entryProfile:e?.value||{}}}var Jr="ALTERNATE",Wf="CONFIRMED",Zr="DIRECT_ACCEPTANCE",ed="FEED_IN",jf="JUNIOR_EXEMPT",us="LUCKY_LOSER",Yf="ORGANISER_ACCEPTANCE",rd="QUALIFIER",$F="REGISTERED",qf="SPECIAL_EXEMPT",tn="UNGROUPED",Pi="UNPAIRED",hu="WILDCARD",io="WITHDRAWN",$f=[Wf,Zr,jf,Yf,qf],RU=[ed,us,rd],ni=[Wf,Zr,ed,jf,Yf,qf,hu],Wr=[Wf,Zr,jf,us,rd,Yf,qf,hu],CU=[Jr,Wf,Zr,ed,jf,us,Yf,rd,$F,qf,tn,Pi,hu,io],hb={ALTERNATE:Jr,CONFIRMED:Wf,DIRECT_ACCEPTANCE:Zr,DIRECT_ENTRY_STATUSES:ni,DRAW_SPECIFIC_STATUSES:RU,EQUIVALENT_ACCEPTANCE_STATUSES:$f,FEED_IN:ed,JUNIOR_EXEMPT:jf,LUCKY_LOSER:us,ORGANISER_ACCEPTANCE:Yf,QUALIFIER:rd,SPECIAL_EXEMPT:qf,STRUCTURE_SELECTED_STATUSES:Wr,UNGROUPED:tn,UNPAIRED:Pi,VALID_ENTRY_STATUSES:CU,WILDCARD:hu,WITHDRAWN:io};function Kf({stage:t,drawDefinition:e}){let{entryProfile:r}=Iu({drawDefinition:e}),n=Object.keys(r).includes(t);if(!n&&zc.includes(t)){let o=[{[t]:{drawSize:void 0,alternates:!0}}];return Hf({drawDefinition:e,attributes:o}),!0}return n}function Sb({stage:t,drawDefinition:e}){let{entryProfile:r}=Iu({drawDefinition:e});return r[t]?.alternates||0}function Tb({stage:t,drawDefinition:e}){let{entryProfile:r}=Iu({drawDefinition:e});return r[t]?.wildcardsCount||0}function Lh({stage:t,drawDefinition:e,entryStatus:r}){return e.entries.reduce((n,o)=>o.entryStage===t&&o.entryStatus===r?n+1:n,0)}function Ni({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=mt({name:Dn,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===pe){let{playoffEntries:p,error:m}=KF({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 KF({provisionalPositioning:t,drawDefinition:e,structureId:r}){let n=[],o=(e.links??[]).find(i=>i.linkType===Jn&&i.target.structureId===r);if(o){let{finishingPositions:i,structureId:s}=o.source,{structure:a}=at({drawDefinition:e,structureId:s});a?.structureType===we&&(a.structures??[]).forEach(u=>{let p=u.positionAssignments??[],{structureId:m}=u,d=m,l=Object.assign({},...p.map(h=>{let{participantId:S}=h,T=mt({element:h,name:Zo}).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:D}=S,U=T||t&&y,A=[...i??[]].sort(ae).indexOf(U)+1;n.push({entryStage:pe,entryStatus:ed,placementGroup:A,groupingValue:d,participantId:h,GEMscore:D})})})}return{playoffEntries:n}}function yb({stage:t,drawDefinition:e}){return ni.reduce((r,n)=>(Lh({drawDefinition:e,entryStatus:n,stage:t})||0)+r,0)}function en({provisionalPositioning:t,returnAllProxies:e,drawDefinition:r,structureId:n,structure:o}){let i,s=[];o||({structure:o,error:i}=at({drawDefinition:r,structureId:n}));let a=Ct({structure:o}).positionAssignments;if(i||!o)return{seedAssignments:[],error:Lt};n||(n=o.structureId);let{stage:c,stageSequence:u}=o,m=c===pe&&r&&Ni({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=VA;let f=o.seedLimit??o?.positionAssignments?.length;return{seedAssignments:s,stageSequence:u,seedLimit:f,stage:c,error:i}}var zF=(t,e)=>(t||0)+(e||0);function Fh(t,e){let r=Array.isArray(t)?t[0]:t;return isNaN(r)&&wh||r<=e[lc]&&lc||r<=e[dc]&&dc||Jm}function kh({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(zF)&&(r[n[0]>n[1]?0:1]+=1),{sets:e,games:r,score:t}}function QF(t){let e=Math.min(...t.games),r=Math.max(...t.games);return Math.round(e/r*100)}function Gh(t){return t.map(QF).sort().map(e=>parseFloat(e.toFixed(2)))}function Su({tournamentRecord:t,profileBands:e,matchUp:r}){if(!r)return{error:dr};let{score:n,winningSide:o}=r;if(!o)return{error:k};let i=!e&&t&&ri({policyType:yi,tournamentRecord:t}).policy,s=e||i?.profileBands||td[yi].profileBands,a=kh({score:n}),c=Gh([a]),u=Fh(c,s),p=Array.isArray(c)?c[0]:c;return{...C,competitiveness:u,pctSpread:p}}function Vh({matchUp:t}){if(!t)return{error:dr};if(t&&!t.sides)return{error:or};if(t&&!t.hasContext)return{error:Yc};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,...C}}var nd="CHECK_IN",od="CHECK_OUT",Ab="SCHEDULE",Ys="SCHEDULE.ASSIGNMENT.VENUE",xo="SCHEDULE.ALLOCATION.COURTS",Mi="SCHEDULE.ASSIGNMENT.COURT",Np="SCHEDULE.COURT.ORDER",qs="SCHEDULE.DATE",XF="COMPLETED.DATE",Bh="HOME_PARTICIPANT_ID",bU="SCHEDULE.ASSIGN.OFFICIAL",$s="SCHEDULE.TIME.SCHEDULED",wo="SCHEDULE.TIME.START",$i="SCHEDULE.TIME.STOP",Ri="SCHEDULE.TIME.RESUME",Ci="SCHEDULE.TIME.END",zf="SCHEDULE.TIME.MODIFIERS",Eb="TO_BE_ANNOUNCED",Ub="NEXT_AVAILABLE",Db="FOLLOWED_BY",Pb="AFTER_REST",Nb="RAIN_DELAY",JF="NOT_BEFORE",Hh=[Eb,Ub,Db,Pb,Nb],ZF="ELIGIBILITY",tk="REGISTRATION",ek="SUSPENSION",rk="MEDICAL",nk="PENALTY",vU="SCALE",OU="RATING",_U="RANKING",Qf="SEEDING",Lo="PUBLISH",yr="PUBLIC",Fo="STATUS",ok="MODIFICATION",ik="RETRIEVAL",sk="other",Mb={MUTUALLY_EXCLUSIVE_TIME_MODIFIERS:Hh,AFTER_REST:Pb,ALLOCATE_COURTS:xo,ASSIGN_COURT:Mi,ASSIGN_OFFICIAL:bU,ASSIGN_VENUE:Ys,CHECK_IN:nd,CHECK_OUT:od,COMPLETED_DATE:XF,COURT_ORDER:Np,ELIGIBILITY:ZF,END_TIME:Ci,FOLLOWED_BY:Db,MEDICAL:rk,MODIFICATION:ok,NEXT_AVAILABLE:Ub,NOT_BEFORE:JF,OTHER:sk,PENALTY:nk,PUBLIC:yr,PUBLISH:Lo,RANKING:_U,RATING:OU,RAIN_DELAY:Nb,REGISTRATION:tk,RESUME_TIME:Ri,RETRIEVAL:ik,SCALE:vU,SCHEDULE:Ab,SCHEDULED_DATE:qs,SCHEDULED_TIME:$s,SEEDING:Qf,START_TIME:wo,STATUS:Fo,STOP_TIME:$i,SUSPENSION:ek,TIME_MODIFIERS:zf,TO_BE_ANNOUNCED:Eb};function ps({matchUp:t}){if(!t)return{error:dr};if(!t.hasContext)return{error:Yc};if(!t.sides||t.sides.filter(Boolean).length!==2)return{error:or};let{nestedIndividualParticipantIds:e,allRelevantParticipantIds:r,sideParticipantIds:n}=Vh({matchUp:t}),i=(t.timeItems??[]).filter(u=>u?.itemType&&[nd,od].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===nd);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,...C}}var Wh={[Bt]:[Bt,"S"],[kt]:[kt,"D"],[Ht]:[Ht,"T"],S:[Bt,"S"],D:[kt,"D"],T:[Ht,"T"]};var se=t=>e=>{let r=It(e)&&e?.matchUpType||te(e)&&e;return r&&Wh[t].includes(r)};function Mp(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 Rp(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 jh({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 Rb({tournamentScheduling:t,eventScheduling:e,averageMinutes:r,defaultTiming:n,matchUpFormat:o,categoryName:i,categoryType:s,policy:a}){let c=e?.matchUpRecoveryTimes&&Rp({...e,averageMinutes:r,matchUpFormat:o}),u=t?.matchUpRecoveryTimes&&Rp({...t,averageMinutes:r,matchUpFormat:o}),p=a?.matchUpRecoveryTimes&&Rp({...a,averageMinutes:r,matchUpFormat:o}),m=[c,u,p,a?.defaultTimes?.recoveryTimes,n?.recoveryTimes];return jh({categoryName:i,categoryType:s,timesBlockArray:m})}function Cb({matchUpFormat:t,categoryName:e,categoryType:r,defaultTiming:n,tournamentScheduling:o,eventScheduling:i,policy:s}){let a=i?.matchUpAverageTimes&&Mp({...i,matchUpFormat:t}),c=o?.matchUpAverageTimes&&Mp({...o,matchUpFormat:t}),u=s?.matchUpAverageTimes&&Mp({...s,matchUpFormat:t}),p=[a,c,u,s?.defaultTimes?.averageTimes,n?.averageTimes];return jh({categoryName:e,categoryType:r,timesBlockArray:p})}var xU="DOUBLES_SINGLES",wU="SINGLES_DOUBLES",so="total",Yh="participantConflict",Ma="matchUpConflict",LU="ISSUE_IDS",fc="CONFLICT",gc="WARNING",qh="ERROR",$h="ISSUE",Xf="STATE",bb={SINGLES_DOUBLES:wU,DOUBLES_SINGLES:xU,TOTAL:so,CONFLICT_MATCHUP_ORDER:Ma,CONFLICT_PARTICIPANTS:Yh,SCHEDULE_ISSUE_IDS:LU,SCHEDULE_CONFLICT:fc,SCHEDULE_WARNING:gc,SCHEDULE_ERROR:qh,SCHEDULE_ISSUE:$h,SCHEDULE_STATE:Xf};function Tu({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??ks;let c={averageTimes:[{minutes:{default:t}}],recoveryTimes:[{minutes:{default:e}}]},{scheduleTiming:u}=Na({tournamentRecord:r,categoryName:o,categoryType:i,event:a}),p={...u,matchUpFormat:n,categoryType:i,defaultTiming:c};return Cp({eventType:s,timingDetails:p})}function Cp({timingDetails:t,eventType:e}){let r=Cb(t),n=Object.keys(r?.minutes||{}),o=r?.minutes&&(n?.includes(e)&&r.minutes[e]||r.minutes.default),i=Rb({...t,averageMinutes:o}),s=Object.keys(i?.minutes||{}),a=i?.minutes&&(s?.includes(e)&&i.minutes[e]||i.minutes.default),c=se(ks)(e)?wU:xU,u=i?.minutes&&(s?.includes(c)&&i.minutes[c]||a);return{averageMinutes:o,recoveryMinutes:a,typeChangeRecoveryMinutes:u}}function Kh(t){return t.createdAt?new Date(t.createdAt).getTime():0}function Eo({visibilityThreshold:t,timeItems:e,itemType:r}){let n=e.filter(i=>i&&i.itemType===r&&(!t||Kh(i)<new Date(t).getTime())).sort((i,s)=>Kh(i)-Kh(s)).pop(),o=n&&Kh(n);return{itemValue:n?.itemValue,timeStamp:o}}function Jf({visibilityThreshold:t,timeStamp:e,schedule:r,matchUp:n}){let{itemValue:o,timeStamp:i}=Eo({timeItems:n?.timeItems||[],itemType:$s,visibilityThreshold:t});return!r||i&&e&&new Date(i).getTime()>new Date(e).getTime()?{scheduledTime:o}:r}function ms({visibilityThreshold:t,timeStamp:e,schedule:r,matchUp:n}){let{itemValue:o,timeStamp:i}=Eo({timeItems:n?.timeItems||[],itemType:qs,visibilityThreshold:t});return!r||i&&e&&new Date(i).getTime()>new Date(e).getTime()?{scheduledDate:o}:r}function zh({visibilityThreshold:t,timeStamp:e,schedule:r,matchUp:n}){let{itemValue:o,timeStamp:i}=Eo({timeItems:n?.timeItems||[],itemType:xo,visibilityThreshold:t});return!r||i&&e&&new Date(i).getTime()>new Date(e).getTime()?{allocatedCourts:J(o,!1,!0)}:r}function Qh({visibilityThreshold:t,timeStamp:e,schedule:r,matchUp:n}){let{itemValue:o,timeStamp:i}=Eo({timeItems:n?.timeItems||[],itemType:Mi,visibilityThreshold:t});return!r||i&&e&&new Date(i).getTime()>new Date(e).getTime()?{courtId:o}:r}function Xh({visibilityThreshold:t,timeStamp:e,schedule:r,matchUp:n}){let{itemValue:o,timeStamp:i}=Eo({timeItems:n?.timeItems||[],itemType:Ys,visibilityThreshold:t});return!r||i&&e&&new Date(i).getTime()>new Date(e).getTime()?{venueId:o}:r}function Zf({visibilityThreshold:t,timeStamp:e,schedule:r,matchUp:n}){let{itemValue:o,timeStamp:i}=Eo({timeItems:n?.timeItems||[],itemType:zf,visibilityThreshold:t});return!r||i&&e&&new Date(i).getTime()>new Date(e).getTime()?{timeModifiers:o}:r}function bp(t){if(ch.test(t)){let e=yf();return new Date(`${e}T${t}`)}else return new Date(t)}function vb({matchUp:t}){if(!t)return{error:dr};if(!t.timeItems)return{error:Zl};let e=t.timeItems.filter(n=>[wo,$i,Ri,Ci].includes(n?.itemType)).sort((n,o)=>bp(n.itemValue).getTime()-bp(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 wo:i=0;break;case Ci:if(n.lastValue&&[wo,Ri].includes(n.lastType)){let u=bp(o.itemValue).getTime()-bp(n.lastValue).getTime();i=n.milliseconds+u}else i=n.milliseconds;break;case $i:if([wo,"SCHECULE.TIME.RESUME"].includes(n.lastType)){let u=bp(o.itemValue).getTime()-bp(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([wo,Ri].includes(r.lastType)){let n=new Date().getTime()-bp(r.lastValue).getTime();r.milliseconds+=n}return{milliseconds:r.milliseconds,time:ak(r.milliseconds),relevantTimeItems:e}}function ak(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 Ob({visibilityThreshold:t,timeStamp:e,schedule:r,matchUp:n}){let{itemValue:o,timeStamp:i}=Eo({timeItems:n?.timeItems||[],itemType:Np,visibilityThreshold:t});return!r||i&&e&&new Date(i).getTime()>new Date(e).getTime()?{courtOrder:o}:r}function _b({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===wo&&s;return a&&(!i||r(a)<r(i))?a:i},void 0)?.itemValue}}function xb(t=1){return tt(0,t).map(Nt)}function Nt(){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 Ic(t){let{disableNotice:e,venue:r,context:n}=t;if(typeof r!="object")return{error:k};let o=Tr(t);r.venueId||(r.venueId=Nt());let i;for(let s of Object.values(o)){let a=ck({disableNotice:!0,tournamentRecord:s,context:n,venue:r});if(a?.error)return a;i=a.venue}return e||dt({topic:Ph,payload:{venue:r}}),rt({...C,venue:i})}function ck({tournamentRecord:t,disableNotice:e,context:r,venue:n}){return t?n?(t.venues||(t.venues=[]),n.venueId||(n.venueId=Nt()),t.venues.reduce((i,s)=>i||s.venueId===n.venueId,void 0)?{error:AE}:(r&&At({element:n,extension:{value:r,name:cU}}),t.venues.push(n),e||dt({payload:{venue:n,tournamentId:t.tournamentId},topic:Ph}),{...C,venue:J(n)})):{error:ot,info:"missing venue"}:{error:j}}function Wo({tournamentRecords:t,tournamentRecord:e,venueId:r}){if(!e)return{error:j};if(!r)return{error:Xo};let o=(e.venues??[]).reduce((i,s)=>s.venueId===r?s:i,void 0);if(!o&&t){let s=(cu({tournamentRecords:t}).linkedTournamentIds??[])[e.tournamentId];for(let a of s){let c=t[a],u=Wo({tournamentRecord:c,venueId:r});if(u.success&&u.venue)return Ic({tournamentRecord:e,venue:u.venue}),{...C,venue:o}}}return o?{...C,venue:o}:{error:Vi}}function Jh({convertExtensions:t,...e}){let{tournamentRecords:r,tournamentRecord:n,venueId:o}=e,i=Wo({tournamentRecords:r,tournamentRecord:n,venueId:o});return J(i,t,!0)}function ds({tournamentRecords:t,tournamentRecord:e,courtId:r}){if(!e)return{error:j};if(!r)return{error:Fi};let n="findCourt",o,i;if((e.venues??[]).forEach(s=>{(s.courts??[]).forEach(a=>{a.courtId===r&&(o=a,i=s)})}),o)return{...C,court:o,venue:i};if(t){let a=(cu({tournamentRecords:t}).linkedTournamentIds??[])[e.tournamentId];for(let c of a){let u=t[c],p=ds({tournamentRecord:u,courtId:r});if(p.success)return p.venue&&Ic({tournamentRecord:e,venue:p.venue}),{...C,court:o,venue:i}}}return _({result:{error:Ls},stack:n})}function Zh(t){return J(ds(t),!1,!0)}function id({tournamentRecord:t,internalUse:e,courtId:r}){if(!t)return{error:j};if(!r)return{error:Fi};let n=ds({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{...C,courtInfo:J(o,!1,e)}}function hc({tournamentRecord:t,venueId:e}){if(!t)return{error:j};if(!e)return{error:Xo};let r=Wo({tournamentRecord:t,venueId:e});if(r.error)return r;let o=(r.venue?.courts??[]).map(a=>(({courtInfo:c})=>({...c}))(id({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{...C,venueData:J(s,!1,!0)}}function wb({matchUp:t}){let e=t?.timeItems||[],r=i=>i.createdAt?new Date(i.createdAt).getTime():0;return{endTime:e.reduce((i,s)=>{let a=s.itemType===Ci&&s;return a&&(!i||r(a)>r(i))?a:i},void 0)?.itemValue}}function Wt({event:t,eventId:e}){if(!t)return{error:bt};let n=mt({name:cn,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 He(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&&Wt({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:Pr},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 sd(t){let{visibilityThreshold:e,timeStamp:r,schedule:n,matchUp:o}=t,i=nt(t,[{[_n]:!0}]);if(i.error)return i;let{itemValue:s,timeStamp:a}=Eo({timeItems:o?.timeItems||[],itemType:Bh,visibilityThreshold:e});return!n||a&&r&&new Date(a).getTime()>new Date(r).getTime()?{homeParticipantId:s}:n}function ad(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:dr};if(o&&!p.matchUpType&&!t.matchUpType&&(e||i)&&p.drawId){let A=e?.drawDefinitions?.find(M=>M.drawId===p.drawId);!A&&i&&({drawDefinition:A,event:e}=He({tournamentRecord:i,drawId:p.drawId}));let E=p.structureId&&A?.structures?.find(({structureId:M})=>M===p.structureId);r=t.matchUpType||E?.matchUpType||A?.matchUpType||e?.eventType!==Me&&e?.eventType}let{milliseconds:m,time:d}=vb({matchUp:p}),{startTime:l}=_b({matchUp:p}),{endTime:f}=wb({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:E}=zh(A),{homeParticipantId:M}=sd(A),{scheduledTime:P}=Jf(A),{timeModifiers:N}=Zf(A),{scheduledDate:R}=ms(A),{venueId:b}=Xh(A),{courtId:v}=Qh(A),{courtOrder:O}=Ob(A),x,F,L,w,B,G=p.matchUpType??r;if(a&&P&&o&&G){let Z={matchUpFormat:p.matchUpFormat??c,...a};({averageMinutes:F=0,recoveryMinutes:L=0,typeChangeRecoveryMinutes:w=0}=Cp({timingDetails:Z,eventType:G})),(F||L)&&(x=f?Hr(Kt(f),L):Hr(P,F+L)),w&&(B=f?Hr(Kt(f),w):Hr(P,F+w))}!R&&P&&(R=Dt(P));let W=km({scheduledDate:R,scheduledTime:P}),H={},q=(i&&b&&hc({tournamentRecord:i,venueId:b}))?.venueData||{};b&&(H[b]=q);let{venueName:$,venueAbbreviation:V,courtsInfo:K}=q,Y=(v&&K?.find(Z=>Z.courtId===v))?.courtName;for(let Z of E||[]){if(!i)break;Z.venueId&&!H[Z.venueid]&&(H[Z.venueId]=hc({venueId:Z.venueId,tournamentRecord:i})?.venueData);let Q=H[Z.venueId];Z.venueName=Q?.venueName;let st=Q?.courtsInfo?.find(St=>St.courtId===Z.courtId);Z.courtName=st?.courtName}g=rt({typeChangeTimeAfterRecovery:B,timeAfterRecovery:x,scheduledDate:R,scheduledTime:P,isoDateString:W,allocatedCourts:E,homeParticipantId:M,timeModifiers:N,venueAbbreviation:V,venueName:$,venueId:b,courtOrder:O,courtName:Y,courtId:v,typeChangeRecoveryMinutes:w,recoveryMinutes:L,averageMinutes:F,milliseconds:m,startTime:l,endTime:f,time:d})}else g=rt({milliseconds:m,startTime:l,endTime:f,time:d});let{scheduledDate:T}=ms({matchUp:p}),{scheduledTime:y}=Jf({matchUp:p});if(s&&u?.displaySettings?.draws){let A=u.displaySettings.draws,E=(A?.[p.drawId]??A?.default)?.scheduleDetails;if(E){let M=(E.find(P=>T&&P.dates?.includes(T))??E.find(P=>!P.dates?.length))?.attributes;if(M){let P=Object.assign({},...Object.keys(g).map(N=>({[N]:!0})),M);g=ji({source:g,template:P})}}}let U=p.matchUpStatus&&ie.includes(p.matchUpStatus)&&(Dt(f)||Dt(T)||Dt(y))||void 0;return{schedule:g,endDate:U}}function oi(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 vp({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 We({drawDefinition:t,structure:e,matchUp:r,event:n}){return{tieFormat:vp({item:r,drawDefinition:t,structure:e,event:n})||vp({item:e,drawDefinition:t,structure:e,event:n})||oi(t)||oi(n)}}function Lb({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 Ee({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 ii({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 tS({groupedOrder:t,roundPositionsCount:e}){if(!t||t?.length<=e)return t;let n=Ae(t,t.length/e).map(i=>i.reduce((s,a)=>s+a)),o=n.slice().sort(ae);return n.map(i=>o.indexOf(i)+1)}function tg(t){if(!It(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 Lr(t){return Array.isArray(t)?t.every(tg):!1}function je({matchUps:t=[],interpolate:e}){if(!Lr(t))return{roundMatchUps:[],error:k};let r=t.reduce((d,l)=>{let f=typeof l.roundNumber=="string"?ut(l.roundNumber):l.roundNumber;return!l.roundNumber||d.includes(f)?d:d.concat(f)},[]).sort(ae).map(d=>{let l=t.filter(h=>h.roundNumber===d),g=l.find(({matchUpType:h})=>h===Ht)?l.filter(({matchUpType:h})=>h===Ht):l,I=h=>h.sort((S,T)=>ae(S.roundPosition,T.roundPosition));return{[d]:I(g)}}),n=t.reduce((d,l)=>{let f=typeof l.roundNumber=="string"?ut(l.roundNumber):l.roundNumber;return d[f]||(d[f]=rt({abbreviatedRoundName:l.abbreviatedRoundName,finishingRound:l.finishingRound,roundName:l.roundName})),d},{}),o=Object.assign({},...r);if(e){let d=Math.max(...Object.keys(o).map(f=>ut(f)).filter(f=>!isNaN(f))),l=o[d]?.length;if(l>1&&On(l)){let f=d+1,g=f+l/2;tt(f,g).forEach((h,S)=>{o[h]=tt(0,l/(2+S*2)).map(()=>({}))})}}let i=0,s=Object.assign({},...Object.keys(o).map(d=>{let l=o[d]?.length,f=o[d]?.filter(I=>!ie.includes(I.matchUpStatus)&&!I.score?.scoreStringSide1)?.length,g=l&&l===f;return i=Math.max(i,l),{[d]:{matchUpsCount:l,inactiveCount:f,inactiveRound:g}}})),a=0,c=0,u=Object.keys(o).map(d=>ut(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(ae),I=Ae(g,2);s[d].drawPositions=g,s[d].pairedDrawPositions=I}else{let g=s[d-1],I=g.drawPositions,h=g.matchUpsCount/s[d].matchUpsCount,S=Ae(I,h),T=l.map(y=>{let{roundPosition:D}=y,U=[...y.drawPositions||[],void 0,void 0].slice(0,2);if(!D)return U;let A=U?.filter(Boolean)||[];if(!A?.length)return[void 0,void 0];if(d<3&&A?.length===2)return U?.slice().sort(ae);let E=qt(I,A).length!==A?.length;if(A?.length&&E)return A?.length===1?[A[0],void 0]:U?.slice().sort(ae);let M=(D-1)*2;return S.slice(M,M+2).map(N=>A?.find(R=>N.includes(R)))});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})=>!On(d));return{hasNoRoundPositions:t.some(d=>!d.roundPosition),roundsNotPowerOf2:p,maxMatchUpsCount:i,roundMatchUps:o,roundNumbers:u,roundProfile:s,...C}}function cd(t){if(!Array.isArray(t))return"";let e=t.filter(Jt);return e.length?pt([Math.min(...e),Math.max(...e)]).join("-"):""}function Fb({drawDefinition:t,structureId:e,matchUpsMap:r}){if(!t)return{error:X};if(!e)return{error:hr};let{structure:n}=at({drawDefinition:t,structureId:e});if(n?.stage!==Ve)return{error:Li,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=ii({structureId:m,matchUpsMap:r}),f=je({matchUps:d}).roundProfile;return{[m]:f}})),c=ii({matchUpsMap:r,structureId:e}),{roundProfile:u}=je({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,D=S[l]?.matchUpsCount;if(!D)return;let U=D?T.length/D:0,A=T.length/U,E=T.slice(),M=tS({roundPositionsCount:A,groupedOrder:g}),P=M?.length||1;if(P<=A){let v=T.length/P,O=Ae(E,v);f===Ii&&O.forEach(x=>x.reverse()),E=M?.length&&M?.map(x=>O[x-1]).flat()||E}let N=Ae(E,U);if(I){let v=tt(0,I.interleave).map(()=>{}),O=tt(0,I.offset).map(()=>{});N=N.map(F=>[F,...v]),N.unshift(O),N=N.flat(1);let x=N.length-I.offset;N=N.slice(0,x)}p[h]||(p[h]={});let b=u?.[h]?.feedRound?2:1;N.forEach((v,O)=>{let x=1+O*b;p[h][x]||(p[h][x]=cd(v))})}),{sourceDrawPositionRanges:p}}function kb({drawPositions:t,roundProfile:e,roundNumber:r}){let n=[void 0,void 0];if($I(t))return{orderedDrawPositions:n,displayOrder:n};let o=e?.[r],s=o?.pairedDrawPositions?.find(c=>xe(c||[],t.filter(Boolean)))??n,a=o?.feedRound;if(qI(t)){let c=[...t].sort(ae);return{orderedDrawPositions:c.length===2?c:s,displayOrder:a?c:s}}if(a){let u=[t.find(p=>!isNaN(ut(p))),void 0];return{orderedDrawPositions:u,displayOrder:u}}return{orderedDrawPositions:s,displayOrder:s}}function Op({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 gn({tournamentParticipants:t,tournamentRecord:e,participantIds:r}){let n="getPairedParticipant";if(!t&&!e)return{error:j};if(!Array.isArray(r)||r.length>2)return{error:_r};if(!r.length)return _({result:{error:No},stack:n});t=t??e?.participants??[];let o=t.filter(a=>a.participantType===lt&&qt(r,a.individualParticipantIds).length===r.length&&a.individualParticipantIds.length===r.length),i=o[0];if(!i)return _({result:{error:Xt},stack:n});let s=J(o.slice(1),!1,!0);return{participant:J(i),duplicatedPairParticipants:s,...C}}function ls({drawDefinition:t,participantId:e}){if(typeof t!="object")return{error:X};if(typeof e!="string")return{error:ee};let{extension:r}=mt({element:t,name:bo});return{lineUp:(r?.value||{})[e]}}function Gb({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}=Op({collectionPosition:r,collectionId:s,lineUp:d});if(c===kt){if(f?.length<=2){let I=o?.[f[0]]?.pairIdMap?.[f[1]],T=(I&&o[I]?.participant||gn({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||ls({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||ls({participantId:d,drawDefinition:i})?.lineUp;return u({attribute:m,lineUp:g,teamParticipant:f})}).filter(Boolean)||{};return{drawPositionCollectionAssignment:Object.assign({},...p)}}function eS({drawDefinition:t}){if(typeof t!="object")return{error:fa};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"&&[Ve,pe].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 Vb({drawDefinition:t,roundProfile:e,structureId:r,matchUpsMap:n}){if(!t)return{error:X};if(!r)return{error:hr};if(!e){let c=ii({matchUpsMap:n,structureId:r});if({roundProfile:e}=je({matchUps:c}),!e)return{error:ot}}let i=(Math.min(...e?.[1]?.drawPositions??[])||1)-1,s=Object.keys(e);return{drawPositionsRanges:Object.assign({},...(s||[]).map(c=>{let u=e?.[c]?.matchUpsCount,p=e?.[1]?.drawPositions??[],m=Ae(p,p.length/u),d=m.map(cd),l=m.map(S=>S.map(T=>T-i)).map(cd),f=s.map(S=>{if(S>c)return;let T=e?.[S]?.drawPositions??[];return Ae(T,T.length/u)}).filter(Boolean),g=tt(0,u).map(S=>f.map(T=>T[S]).flat().filter(Boolean).sort(ae)).map(S=>pt(S)),I=g.map(S=>RC(S).map(cd).join(", ")),h=Object.assign({},...tt(0,u).map(S=>({[S+1]:{firstRoundDrawPositionsRange:d[S],firstRoundOffsetDrawPositionsRange:l[S],possibleDrawPositions:g[S],drawPositionsRange:I[S]}})));return{[c]:h}}))}}function ud({roundsNotPowerOf2:t,drawDefinition:e,structure:r,matchUps:n}){if(!r)return!1;n=n??r.matchUps??[],t=t??je({matchUps:n}).roundsNotPowerOf2;let o=!!r.positionAssignments?.find(({drawPosition:i})=>i)||!!n?.find(({drawPositions:i})=>i?.length);return(!e?.drawType||e.drawType!==Hi)&&!r?.structures&&t&&o}function pr({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!==Be&&(!e.length||!r&&!n)}var eg={[Ta]:{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:{[et]:"",[pe]:"P",[ct]:"Q",[Ve]:"C"}}},Bb=eg;function Hb({roundNamingPolicy:t,drawDefinition:e,structure:r,matchUps:n}){let{roundProfile:o,roundMatchUps:i}=je({matchUps:n}),{structureAbbreviation:s,stage:a}=r,c=pr({structure:r}),u=ud({structure:r}),p=r.structures,m={},d=eg[Ta],l=r.stage===ct,f=l?Math.max(...(e?.structures??[]).filter(b=>b.stage===ct).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,U=(t?.namingConventions||d.namingConventions).round,A=a&&a!==et?a[0]:"",E=t?.stageConstants||d.stageConstants,M=a&&E?.[a]||A,P=`${I}${M}${g}`,N=o?Object.keys(o):[],R=l&&E?.[ct]?`${E?.[ct]}-`:"";if(p||c||u)Object.assign(m,...N.map(b=>{let v=`${R}${U} ${b}`,O=`${y}${b}`;return{[b]:{roundName:v,abbreviatedRoundName:O}}}));else{let b=l&&(t?.qualifyingFinishMap||d?.qualifyingFinishMap||{});Object.assign(m,...N.map(v=>{if(!o?.[v])return;let{matchUpsCount:O,preFeedRound:x}=o[v],F=O*2,L=b?.[o?.[v].finishingRound]||b&&`${y}${F}`||h[O]||`${y}${F}`,w=x?`-${T}`:"",B=`${L}${w}`,G=[P,s,B].filter(Boolean).join("-"),H=`${S[O]||`${y}${F}`}${w}`,q=[P,s,H].filter(Boolean).join("-");return{[v]:{abbreviatedRoundName:q,roundName:G}}}))}return{roundNamingProfile:m,roundProfile:o,roundMatchUps:i}}function pd(t){let e=nt(t,[{[_n]:!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&&Bt||s===lt&&kt||s===Ft&&Ft||void 0}return{matchUpType:n}}var uk="normal",FU="timed",pk="final",rg="NOAD",md="SET",Wb={S:uk,F:pk};function rr(t){if(typeof t=="string"){let e=t.startsWith("T")&&FU||t.startsWith(md)&&md||"";if(e===FU){let r=$b(t),n={simplified:!0,setFormat:r,bestOf:1};if(r)return n}if(e===md)return mk(t)}}function mk(t){let e=t.split("-"),r=ng(e[0].slice(3)),n=r===1||r%2!==0?r:void 0,o=r!==1&&r%2===0?r:void 0,i=e&&jb(e[1]),s=e&&jb(e[2]),a=i&&i.timed||s&&s.timed,c=n&&n<6||a&&o,u=!e[2]||s,p=i,m=rt({setFormat:i,exactly:o,bestOf:n});if(s&&(m.finalSetFormat=s),c&&p&&u)return m}function jb(t){if(t?.[1]===":"){let e=t.split(":"),r=Wb[e[0]],n=e[1];if(r&&n){if(n.startsWith("TB")){let I=Yb(n);return I===!1?!1:typeof I=="object"?{tiebreakSet:I}:void 0}if(n.startsWith("T"))return $b(n);let s=t.match(/^[FS]:(\d+)([A-Za-z]*)/),a=s&&Kb(s[2])||!1,c=!s?.[2]||a,u=s?ng(s[1]):void 0,p=qb(n),m=p!==!1,d=m&&p||u,l=Yb(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 qb(t,e=!0){let r=t?.indexOf("@")>0&&t.split("@");if(r)return(e?ng(r[1]):r[1])||!1}function Yb(t){if(t)if(t.startsWith("TB")){let e=qb(t,!1),r=t.match(/^TB(\d+)([A-Za-z]*)/),n=r?.[1],o=r&&Kb(r[2]),i=!r?.[2]||o,s=ng(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 $b(t){let e=t.slice(1),r=e.match(/^(\d+)(@?[A-Za-z]*)/),n=ng(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 Kb(t){return t&&t.indexOf(rg)>=0}function ng(t){return isNaN(Number(t))?0:Number(t)}function yu(t,e){return!Array.isArray(t)||!te(e)?!1:qt(t,Wh[e]).length}function bi(t){if(!Array.isArray(t.matchUps))return[];let{matchUps:e,excludeMatchUpStatuses:r,hasParticipantsCount:n,isCollectionMatchUp:o,matchUpStatuses:i,hasWinningSide:s,matchUpFormats:a,roundPositions:c,matchUpFormat:u,collectionIds:p,isMatchUpTie:m,roundNumbers:d,matchUpIds:l,roundNames:f,filterMatchUpTypes:g=!0,filterMatchUpIds:I=!0,stageSequences:h,scheduledDates:S,scheduledDate:T,participantIds:y,processContext:D,tournamentIds:U,matchUpTypes:A,structureIds:E,readyToScore:M,courtIds:P,eventIds:N,venueIds:R,drawIds:b,stages:v}=t,O=Array.isArray(y)?y.filter(Boolean):[],x=Array.isArray(i)?i.filter(Boolean):[],F=Array.isArray(r)?r.filter(Boolean):[],L=Array.isArray(v)?v.filter(Boolean):[],w=Array.isArray(h)?h.filter(Boolean):[],B=Array.isArray(p)?p.filter(Boolean):[],G=Array.isArray(f)?f.filter(Boolean):[],W=Array.isArray(d)?d.filter(Boolean):[],H=Array.isArray(c)?c.filter(Boolean):[],q=Array.isArray(l)&&I?l.filter(Boolean):[],$=Array.isArray(A)&&g?A.filter(Boolean):[],V=Array.isArray(P)?P.filter(Boolean):[],K=Array.isArray(R)?R.filter(Boolean):[],z=Array.isArray(a)&&a.filter(Boolean)||typeof u=="string"&&[u]||[],Y=Array.isArray(S)&&S.filter(Boolean)||typeof T=="string"&&T.length&&[T]||[],Z=Array.isArray(U)?U.filter(Boolean):[],Q=Array.isArray(N)?N.filter(Boolean):[],st=Array.isArray(b)?b.filter(Boolean):[],St=Array.isArray(E)?E.filter(Boolean):[];return e.filter(it=>{if(M&&!se(Nn)(it)&&!it.readyToScore||it.winningSide&&s&&![1,2].includes(it.winningSide)||m!==void 0&&(m&&!it.tieMatchUps||!m&&it.tieMatchUps)||o!==void 0&&(o&&!it.collectionId||!o&&it.collectionId)||L.length&&!L.includes(it.stage)||w.length&&!w.includes(it.stageSequence)||B.length&&(!it.collectionId||!B.includes(it.collectionId))||G.length&&(!it.roundName||!G.includes(it.roundName))||W.length&&(!it.roundNumber||!W.includes(it.roundNumber))||H.length&&(!it.roundPosition||!H.includes(it.roundPosition))||x.length&&(!it.matchUpStatus||!x.includes(it.matchUpStatus))||F.length&&it.matchUpStatus&&F.includes(it.matchUpStatus)||q.length&&!q.includes(it.matchUpId)||$.length&&(!it.matchUpType||!yu($,it.matchUpType))||z.length&&(!it.matchUpFormat||!z.includes(it.matchUpFormat)))return!1;if(Y?.length){let{scheduledTime:jt}=Jf({matchUp:it}),{scheduledDate:Ut}=ms({matchUp:it}),Se=Dt(jt)||Ut;if(!Y.find(Te=>Wn(Te,Se)))return!1}if(V.length){let{courtId:jt}=Qh({matchUp:it}),{allocatedCourts:Ut}=zh({matchUp:it}),Ue=Ut?.map(({courtId:Se})=>Se);if(!V.filter(Boolean).includes(jt)||Ue?.includes(jt))return!1}if(K.length){let{venueId:jt}=Xh({matchUp:it});if(!K.filter(Boolean).includes(jt))return!1}if(D){if(Z.length&&!Z.includes(it.tournamentId)||Q.length&&!Q.includes(it.eventId)||st.length&&!st.includes(it.drawId)||St.length&&!St.includes(it.structureId))return!1;let jt=it.sides?.map(({participantId:Ut})=>Ut).filter(Boolean)??[];if(n&&jt.length<n||O.length&&!O.some(Ue=>jt.includes(Ue)))return!1}return!0})}function zb({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?dk({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 dk({displaySideNumber:t,seedAssignments:e,participantId:r,assignment:n,sideNumber:o}){let i={drawPosition:n.drawPosition,displaySideNumber:t,sideNumber:o};if(r){let s=lk({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 lk({seedAssignments:t,participantId:e}){return t?.find(r=>!r.seedProxy&&r.participantId===e)}var Mn="ANY",Zt="MALE",Cr="MIXED",fs="OTHER",ce="FEMALE",dd={ANY:Mn,MALE:Zt,FEMALE:ce,MIXED:Cr,OTHER:fs};function Et({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:D,event:U}){let A={},E={};if(n=n??s?.participants,!y)return{collectionPositionMatchUps:A,error:di,roundMatchUps:E,matchUps:[]};let M=Array.isArray(m?.eventIds)?m?.eventIds.filter(Boolean):[],P=Array.isArray(m?.structureIds)?m?.structureIds.filter(Boolean):[],N=Array.isArray(m?.drawIds)?m?.drawIds.filter(Boolean):[],R=!h?.eventId||!M?.length&&!u?.eventIds?.filter(Boolean).length||M?.includes(h.eventId)||u?.eventIds?.includes(h.eventId),b=!P?.length||P.includes(y.structureId),v=!g||!N?.length||N.includes(g.drawId);if(!R||!b||!v)return{collectionPositionMatchUps:A,roundMatchUps:E,matchUps:[]};f&&!p&&(p=Yn({tournamentRecord:s,contextProfile:f,drawDefinition:g}));let{appliedPolicies:O}=yt({drawDefinition:g}),x={...e,...O,...i},F=x?.scoring?.structures,L=y.stage&&F?.stage&&F?.stage[y.stage],w=y.stageSequence&&L?.stageSequence&&L.stageSequence[y.stageSequence],B=x?.scoring?.requireAllPositionsAssigned||L?.requireAllPositionsAssigned||w?.requireAllPositionsAssigned;T||(T=Ee({drawDefinition:g,structure:y}));let{positionAssignments:G,allPositionsAssigned:W}=le({structure:y}),H=!B||W,{seedAssignments:q}=en({provisionalPositioning:r,drawDefinition:g,structure:y});a=a??q;let{roundOffset:$,structureId:V,structureName:K,stage:z,stageSequence:Y}=y,{drawId:Z,drawName:Q,drawType:st}=g??{};S=S||g&&eS({drawDefinition:g}).exitProfiles;let St=S?.[V],it=St?.length&&(St[0].split("-").map(ne=>parseInt(ne)).reduce((ne,_t)=>ne+_t)||0),jt=!!y.structures,Ut=ii({matchUpsMap:T,structureId:V,inContext:D}),Ue=x?.[Ta],Se=Hb({roundNamingPolicy:Ue,drawDefinition:g,structure:y,matchUps:Ut}),{roundNamingProfile:Te,roundProfile:Er}=Se;if(E=Se?.roundMatchUps??[],m&&(Ut=bi({matchUps:Ut,...m,filterMatchUpTypes:!1,filterMatchUpIds:!1})),D){let{sourceDrawPositionRanges:ne}=Fb({drawDefinition:g,matchUpsMap:T,structureId:V}),_t=g?Vb({drawDefinition:g,roundProfile:Er,matchUpsMap:T,structureId:V}).drawPositionsRanges:void 0;Ut=Ut.map(xt=>br({scheduleVisibilityFilters:t,sourceDrawPositionRanges:ne,drawPositionsRanges:_t,roundNamingProfile:Te,initialRoundOfPlay:it,appliedPolicies:x,usePublishState:c,publishStatus:I,isRoundRobin:jt,roundProfile:Er,matchUp:xt,event:U})),(Ut?.filter(xt=>Array.isArray(xt.tieMatchUps))).forEach(xt=>{let de=xt.tieMatchUps;Ut=Ut.concat(...de)}),u&&(Ut=bi({processContext:!0,...u,matchUps:Ut}))}else(Ut?.filter(_t=>Array.isArray(_t.tieMatchUps))).forEach(_t=>{let Rt=_t.tieMatchUps;Ut=Ut.concat(...Rt)});return m&&(Ut=bi({matchUps:Ut,...m,filterMatchUpTypes:!1,filterMatchUpIds:!1})),(m?.matchUpTypes||m?.matchUpIds)&&(Ut=bi({matchUpTypes:m.matchUpTypes,matchUpIds:m.matchUpIds,matchUps:Ut})),(m?.matchUpTypes||m?.matchUpIds||D)&&(E=je({matchUps:Ut}).roundMatchUps??[]),We({drawDefinition:g,structure:y,event:U})?.tieFormat&&({collectionPositionMatchUps:A}=Lb({matchUps:Ut})),{collectionPositionMatchUps:A,roundMatchUps:E,isRoundRobin:jt,roundProfile:Er,matchUpsMap:T,matchUps:Ut};function br({scheduleVisibilityFilters:ne,sourceDrawPositionRanges:_t,drawPositionsRanges:Rt,initialRoundOfPlay:xt,additionalContext:de,roundNamingProfile:oe,tieDrawPositions:ge,appliedPolicies:ye,isCollectionBye:cr,usePublishState:qe,publishStatus:Yt,matchUpTieId:$e,isRoundRobin:Gr,roundProfile:qr,sideLineUps:vr,matchUp:Oe,event:fr}){de=de??{};let un=We({drawDefinition:g,structure:y,matchUp:Oe,event:fr})?.tieFormat,En=un?.collectionDefinitions,tr=Oe.collectionId&&En?.find(uo=>uo.collectionId===Oe.collectionId),ke=Oe.collectionId?tr?.matchUpFormat:Oe.matchUpFormat??y?.matchUpFormat??g?.matchUpFormat??fr?.matchUpFormat,Or=Oe.matchUpType||tr?.matchUpType||y?.matchUpType||g?.matchUpType||!se(Me)(fr?.eventType)&&fr?.eventType,es=cr?Pt:Oe.matchUpStatus,{schedule:vn,endDate:ma}=ad({scheduleVisibilityFilters:ne,afterRecoveryTimes:o,tournamentRecord:s,usePublishState:qe,scheduleTiming:l,matchUpFormat:ke,publishStatus:Yt,matchUpType:Or,matchUp:Oe,event:fr}),mi=ge??Oe.drawPositions??[],{collectionPosition:DI,collectionId:aC,roundPosition:PI}=Oe,rs=Oe.roundNumber??de.roundNumber,uL=aC?Gb({tournamentParticipants:n,positionAssignments:G,collectionPosition:DI,drawDefinition:g,participantMap:d,drawPositions:mi,collectionId:aC,sideLineUps:vr,matchUpType:Or}):void 0,cC=oe?.[rs]?.roundName||de.roundName,uC=oe?.[rs]?.abbreviatedRoundName||de.abbreviatedRoundName,pL=qr?.[rs]?.feedRound,mL=qr?.[rs]?.preFeedRound,dL=qr?.[rs]?.roundFactor,lL=Rt?.[rs],fL=PI?lL?.[PI]:void 0,gL=_t?.[rs],IL=tr?.category?{...h?.category||{},...tr.category}:h?.category??fr?.category,hL=Oe.processCodes?.length&&Oe.processCodes||tr?.processCodes?.length&&tr?.processCodes||y?.processCodes?.length&&y?.processCodes||g?.processCodes?.length&&g?.processCodes||fr?.processCodes?.length&&fr?.processCodes||s?.processCodes,SL=f?.withCompetitiveness&&Su({...p,matchUp:Oe}),TL=Oe.finishingPositionRange??de.finishingPositionRange,NI=uo=>rt(uo,void 0,!0),Ir={...NI(h),...NI({matchUpFormat:Oe.matchUpType===Me?void 0:ke,tieFormat:Oe.matchUpType!==Me?void 0:un,gender:tr?.gender??fr?.gender,roundOfPlay:z!==ct&&ft(xt)&&xt+(rs||0),endDate:Oe.endDate??ma,discipline:fr?.discipline,category:IL,finishingPositionRange:TL,abbreviatedRoundName:uC,drawPositionsRange:fL,competitiveProfile:SL,structureName:K,stageSequence:Y,drawPositions:mi,matchUpStatus:es,processCodes:hL,isRoundRobin:Gr,matchUpTieId:$e,preFeedRound:mL,matchUpType:Or,roundFactor:dL,roundOffset:$,structureId:V,roundNumber:rs,feedRound:pL,roundName:cC,drawName:Q,drawType:st,schedule:vn,drawId:Z,stage:z}),...J(NI(Oe),!0,!0)};if(ke&&Oe.score?.scoreStringSide1){let uo=rr(ke),{bestOf:da,finalSetFormat:vs,setFormat:Ur}=uo??{};(vs?.tiebreakSet||Ur?.tiebreakSet||Ur?.timed)&&(Ir.score.sets=Ir.score.sets.sort((nn,Vn)=>nn.setNumber-Vn.setNumber).map((nn,Vn)=>(Vn+1===da?(vs?.tiebreakSet||vs?.timed)&&(nn.tiebreakSet=!0):(Ur?.tiebreakSet||Ur?.timed)&&(nn.tiebreakSet=!0),nn)))}if(Array.isArray(mi)){let{orderedDrawPositions:uo,displayOrder:da}=kb({drawPositions:mi,roundProfile:qr,roundNumber:rs}),vs=qr?.[rs]?.feedRound,Ur=da[0]!==uo[0],Vn=uo.concat(void 0,void 0).slice(0,2).map((wi,RA)=>{let MI=RA+1,AL=Ur?3-MI:MI,EL=zb({...uL,positionAssignments:G,displaySideNumber:AL,seedAssignments:a,drawPosition:wi,isFeedRound:vs,sideNumber:MI}),UL=Oe.sides?.find(PL=>PL.sideNumber===MI),mC=PI?(PI-1)*2+RA+1:void 0,DL=mC?gL?.[mC]:void 0;return NI({sourceDrawPositionRange:DL,...UL,...EL})});Object.assign(Ir,J({sides:Vn},!0,!0))}if(n&&Ir.sides){let uo=ye?.[Ws],da=Ur=>{let nn=d?.[Ur]?.participant;return nn&&ji({template:uo?.participant,source:nn})};if(Ir.sides.filter(Boolean).forEach(Ur=>{if(Ur.participantId){let nn=J(da(Ur.participantId)||n&&Bo({policyDefinitions:ye,participantId:Ur.participantId,tournamentParticipants:n,internalUse:!0,contextProfile:f}),void 0,!0);if(nn){if(g?.entries){let Vn=g.entries.find(wi=>wi.participantId===Ur.participantId);Vn?.entryStatus&&(nn.entryStatus=Vn.entryStatus),Vn?.entryStage&&(nn.entryStage=Vn.entryStage)}Object.assign(Ur,{participant:nn})}}if(Ur?.participant?.individualParticipantIds?.length&&!Ur.participant.individualParticipants?.length){let nn=Ur.participant.individualParticipantIds.map(Vn=>da(Vn)||n&&Bo({policyDefinitions:ye,tournamentParticipants:n,internalUse:!0,contextProfile:f,participantId:Vn}));Object.assign(Ur.participant,{individualParticipants:nn})}}),!Ir.matchUpType){let{matchUpType:Ur}=pd({matchUp:Ir});Ur&&Object.assign(Ir,{matchUpType:Ur})}if(f?.inferGender&&(!Ir.gender||Ir.gender===Cr)&&Ir.sides?.length===2&&Ir.matchUpType!==Me){let Ur=Ir.sides.map(nn=>{if(se(Bt)(Ir.matchUpType))return nn.participant?.person?.sex;if(nn.participant?.individualParticipants?.length===2){let Vn=pt(nn.participant.individualParticipants.map(wi=>wi.person?.sex)).filter(Boolean);if(Vn.length===1)return Vn[0]}});if(Ur.filter(Boolean).length===2&&pt(Ur).length===1){let nn=Ur[0];Ir.inferredGender=nn}}}if(Ir.tieMatchUps){let uo=Ir.matchUpStatus===Pt,da=Ir.sides?.map(({participant:vs,drawPosition:Ur,sideNumber:nn,lineUp:Vn})=>{let wi=vs?.participantType===Me&&vs;return{teamParticipant:wi&&rt({participantRoleResponsibilities:wi.participantRoleResponsibilities,participantOtherName:wi.participanOthertName,participantName:wi.participantName,participantId:wi.participantId,teamId:wi.teamId}),drawPosition:Ur,sideNumber:nn,lineUp:Vn}});Ir.tieMatchUps=Ir.tieMatchUps.map(vs=>{let Ur=Ir.matchUpId,Vn={finishingPositionRange:Ir.finishingPositionRange,abbreviatedRoundName:uC,roundNumber:rs,roundName:cC};return br({tieDrawPositions:mi,scheduleVisibilityFilters:ne,sourceDrawPositionRanges:_t,sideLineUps:da,drawPositionsRanges:Rt,initialRoundOfPlay:xt,roundNamingProfile:oe,additionalContext:Vn,appliedPolicies:ye,isCollectionBye:uo,usePublishState:qe,publishStatus:Yt,matchUpTieId:Ur,isRoundRobin:Gr,roundProfile:qr,matchUp:vs,event:fr})})}let pC=Ir.sides&&Ir.sides.filter(uo=>uo?.participantId).length===2,yL=!Ir.winningSide;if(Object.assign(Ir,{readyToScore:H&&pC&&yL,hasContext:!0}),pC){let{allParticipantsCheckedIn:uo,checkedInParticipantIds:da}=ps({matchUp:Ir});Object.assign(Ir,{allParticipantsCheckedIn:uo,checkedInParticipantIds:da})}return Array.isArray(f?.exclude)&&f?.exclude.forEach(uo=>delete Ir[uo]),Ir}}function gs({matchUp:t}){return t?ie.includes(t?.matchUpStatus)||t?.winningSide:!1}function Au({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:D,event:U}){!y&&S&&({structure:y}=at({drawDefinition:g,structureId:S}));let A=Et({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:D,event:U}),E=[],M=[],P=[],N=[],R=[];if(A.error)return A;let{matchUps:b}=A,{assignedPositions:v}=le({structure:y}),O=v?.filter(F=>F.participantId).map(F=>F.drawPosition),x;return b.filter(F=>{let L=c?.matchUpTypes?.length===1&&c.matchUpTypes[0]===Ht;return!(F.matchUpType!==Ht&&L)}).forEach(F=>{if(F.matchUpStatus===Mr){E.push(F);return}F.matchUpType===Ht&&(x=!0);let L=F.collectionId,w=L&&F.sides?.every(V=>V.participantId),B=!L&&F.drawPositions?.filter(Boolean).length===2,G=!L&&F.drawPositions?.every(V=>O?.includes(V)),W=v?.filter(V=>V.bye).map(V=>V.drawPosition),H=!L&&F.drawPositions?.find(V=>W?.includes(V)),$=Eh.includes(F.matchUpStatus)&&(w||B&&(!t||G));return H?R.push(F):gs({matchUp:F})?M.push(F):$?P.push(F):N.push(F)}),{includesTeamMatchUps:x,abandonedMatchUps:E,completedMatchUps:M,upcomingMatchUps:P,pendingMatchUps:N,byeMatchUps:R,structure:y}}function Qb({drawDefinition:t,roundNumber:e,structureId:r}){if(!t)return{error:X};if(!r)return{error:hr};let{links:n}=Ks({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 rS({finishingPositions:t,linkCondition:e,linkType:r,source:n}){let o=n.find(i=>{let s=!i.source?.finishingPositions||!t||xe(t,i.source?.finishingPositions);return e===i.linkCondition&&s&&i.linkType===r});return[fo,Zn].includes(o?.linkType)&&!o?.source?.roundNumber?_({result:{error:k},stack:"getTargetLink",context:o}):o}function Ks({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:hr}:{error:X}}function Xb({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 nS({sourceRoundMatchUpCount:t,inContextDrawMatchUps:e,sourceRoundPosition:r,drawDefinition:n,targetLink:o}){if(!o)return{error:Ll};let{target:{structureId:i,feedProfile:s,groupedOrder:a,roundNumber:c,positionInterleave:u}}=o,{structure:p}=at({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=tt(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,N=r+P;h=Math.ceil(N/2),S=1-N%2}let T=g,y=g[h-1],D=tS({roundPositionsCount:g.length,groupedOrder:a}),U=D?.length||1;if(U<=g.length){let P=f/U,N=Ae(g,P);s===Ii&&N.forEach(R=>R.reverse()),T=D?.length&&D?.map(R=>N[R-1]).flat()||T}s===yn?y=T[h-1]:s===Ii?((!D?.length||U>g.length)&&(h=l.length+1-h),y=T[h-1]):s===lp&&Sr()&&console.log(sp,{feedProfile:s});let A=y&&l.reduce((P,N)=>N.roundPosition===y?N:P,void 0),E;A?.feedRound?(S=0,E=Math.min(...(A.drawPositions||[]).filter(Boolean))):E=A?.drawPositions?.length===2&&A?.drawPositions[S];let M=m?.find(({drawPosition:P})=>P===E);if(M){let{extension:P}=mt({element:M,name:Bm});if(P?.value)return{disabledDrawPosition:E}}return{matchUp:A,targetDrawPosition:E,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}=at({structureId:i?.structureId,drawDefinition:n});return s?.finishingPosition===Wi?fk({inContextDrawMatchUps:t,useTargetMatchUpIds:e,drawDefinition:n,structure:s,matchUp:i}):gk({matchUp:i})}function fk({inContextDrawMatchUps:t,useTargetMatchUpIds:e,drawDefinition:r,structure:n,matchUp:o}){let{winnerMatchUpId:i,loserMatchUpId:s}=o,{links:a}=Qb({roundNumber:o.roundNumber,structureId:n.structureId,drawDefinition:r}),c=a?.source,u=rS({source:c,linkType:fo}),p=rS({linkCondition:to,linkType:Zn,source:c}),m=rS({source:c,linkType:Zn}),d=p&&m;m||(m=p);let l=u?.target?.feedProfile,f=m?.target?.feedProfile,g=p?.target?.feedProfile,I,h,S,T,y,D,U,A,E,M;if(e&&(i||s)&&(U=i&&l!==mn&&t.find(({matchUpId:R})=>R===i),T=s&&f!==mn&&t.find(({matchUpId:R})=>R===s),U||T))return{matchUp:o,targetLinks:{loserTargetLink:m,winnerTargetLink:u},targetMatchUps:{loserMatchUp:T,winnerMatchUp:U}};let{roundPosition:P}=o;M=M||t.filter(R=>R.structureId===n.structureId);let N=M.reduce((R,b)=>b.roundNumber===o.roundNumber&&!b.matchUpTieId?R+1:R,0);return m&&!T&&f!==mn&&({matchUpDrawPositionIndex:D,targetDrawPosition:y,matchUp:T}=nS({targetLink:m,sourceRoundMatchUpCount:N,inContextDrawMatchUps:t,sourceRoundPosition:P,drawDefinition:r})),d&&g!==mn&&({matchUpDrawPositionIndex:S,targetDrawPosition:h,matchUp:I}=nS({targetLink:p,sourceRoundMatchUpCount:N,inContextDrawMatchUps:t,sourceRoundPosition:P,drawDefinition:r})),u&&!U&&l!==mn&&({matchUpDrawPositionIndex:E,targetDrawPosition:A,matchUp:U}=nS({targetLink:u,sourceRoundMatchUpCount:N,inContextDrawMatchUps:t,sourceRoundPosition:P,drawDefinition:r})),U||(M=M||t.filter(R=>R.structureId===n.structureId),{matchUp:U}=Xb({structureMatchUps:M,matchUp:o})),rt({matchUp:o,targetLinks:{loserTargetLink:m,winnerTargetLink:u,byeTargetLink:p},targetMatchUps:{winnerMatchUpDrawPositionIndex:E,loserMatchUpDrawPositionIndex:D,byeMatchUpDrawPositionIndex:S,winnerTargetDrawPosition:A,loserTargetDrawPosition:y,byeTargetDrawPosition:h,winnerMatchUp:U,loserMatchUp:T,byeMatchUp:I},targetMatchUpIds:!!(i||s)})}function gk({matchUp:t}){return{targetLinks:{loserTargetLink:void 0,winnerTargetLink:void 0},targetMatchUps:{loserMatchUp:void 0,winnerMatchUp:void 0},matchUp:t}}function Jb({drawDefinition:t,inContextDrawMatchUps:e}){let r={};return e.forEach(n=>{let{matchUpId:o,structureId:i,drawPositions:s=[]}=n,{structure:a}=at({drawDefinition:t,structureId:i});if(a?.finishingPosition===Vs){let{roundNumber:c}=n,u=c&&ut(c)+1,p=a.matchUps??[],{roundMatchUps:m}=je({matchUps:p});if(u&&m?.[u]){let d=[...s].sort(ae).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=kU({upcomingMatchUp:u}),d=kU({upcomingMatchUp:p});if(n.matchUpStatus!==Pt&&p?.matchUpStatus===Pt){let{matchUp:f}=Zb({matchUp:p,drawDefinition:t,inContextDrawMatchUps:e})||{};d=f&&kU({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===to,I=Ik(n);if(I.length){let h=Mf(u?.sides),S=Mf(p?.sides),y=I.find(({participantId:A})=>h.includes(A))?[]:I,U=I.find(({participantId:A})=>S.includes(A))?[]:I;p&&g&&U.length<2&&U.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)),U?.length&&p&&(c.targetMatchUpIds||(u=e.find(({matchUpId:A})=>A===p.matchUpId)),p.potentialParticipants||(p.potentialParticipants=[]),p.potentialParticipants.push(U))}}}}),Object.keys(r).length&&e.forEach(n=>{Object.keys(r).includes(n.matchUpId)&&(n.schedule.scheduleConflict=r[n.matchUpId])}),{scheduleConflictMatchUpIds:r}}function Ik(t){return t?.sides?.map(({participant:e,participantId:r,qualifier:n})=>e||r&&{participantId:r}||n&&{qualifier:n}).filter(Boolean)||[]}function Zb({matchUp:t,drawDefinition:e,inContextDrawMatchUps:r}){let{matchUpId:n,matchUpStatus:o,structureId:i}=t||{};if(!t||!i||t?.matchUpStatus===zt)return{matchUp:t};if(o===Pt){let s;return t.winnerMatchUpId?s=r.find(({matchUpId:a})=>a===t.winnerMatchUpId):{winnerMatchUp:s}=nr({inContextDrawMatchUps:r,drawDefinition:e,matchUpId:n})?.targetMatchUps||{},Zb({matchUp:s,drawDefinition:e,inContextDrawMatchUps:r})}return{matchUp:void 0}}function kU(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 re(t){let e="getAllDrawMatchUps";Object.assign(t,{requireParticipants:!1});let r=zs(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 zs(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:D,event:U}=t,A=[],E=[],M=[],P=[],N=[];h&&!r&&(r=Yn({policyDefinitions:u,tournamentRecord:p,contextProfile:h,event:U}));let R;!e?.length&&p&&(e=p?.participants,(y||a?.withGroupings)&&e?.length&&({participantsWithGroupings:e,groupInfo:R}=Qm({participants:e,participantsProfile:a})));let{structures:b}=ln({drawDefinition:S});if(!b)return{error:Lt};n||(n=Ee({drawDefinition:S}));let v=S&&eS({drawDefinition:S}).exitProfiles;b.forEach(F=>{let{byeMatchUps:L=[],pendingMatchUps:w=[],upcomingMatchUps:B=[],completedMatchUps:G=[],abandonedMatchUps:W=[]}=Au({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:D,event:U});A=A.concat(...W),E=E.concat(...G),M=M.concat(...B),P=P.concat(...w),N=N.concat(...L)});let O=F=>(!l&&!T&&!d||(l&&(F=bi({matchUps:F,...l})),d&&(F=bi({matchUps:F,...d,processContext:!0}))),F),x={abandonedMatchUps:O(A),completedMatchUps:O(E),upcomingMatchUps:O(M),pendingMatchUps:O(P),byeMatchUps:O(N),matchUpsMap:n,...C,groupInfo:R};if(T){let F=typeof T=="object"||{abandoned:!0,completed:!0,upcoming:!0,pending:!0,bye:!0},{abandoned:L,completed:w,upcoming:B,pending:G,bye:W}=F,H=[].concat(...L&&A||[],...w&&E||[],...B&&M||[],...G&&P||[],...W&&N||[]);Jb({inContextDrawMatchUps:H,drawDefinition:S})}return x}function qn(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:bt};let{eventId:S,eventName:T,endDate:y,eventType:D,category:U,gender:A,matchUpFormat:E}=h??{},M={...I,...rt({indoorOutDoor:h.indoorOutdoor??p?.indoorOutdoor,surfaceCategory:h.surfaceCategory??p?.surfaceCategory,endDate:h.endDate??p?.endDate,tournamentId:p?.tournamentId,matchUpFormat:E,eventName:T,eventType:D,category:U,eventId:S,gender:A})};y&&(M.endDate=y),d&&!r&&(r=Yn({policyDefinitions:c,tournamentRecord:p,contextProfile:d,event:h}));let P;if(!e?.length&&!n&&p){let v=Di({participantsProfile:s,useParticipantMap:u,policyDefinitions:c,tournamentRecord:p,contextProfile:d,inContext:g});n=v.participantMap,e=v.participants??[],P=v.groupInfo}let N=h.drawDefinitions??[],R=Na({tournamentRecord:p,event:h}).scheduleTiming;return{matchUps:N.flatMap(v=>{let{matchUps:O}=re({tournamentParticipants:e,tournamentAppliedPolicies:i,scheduleVisibilityFilters:o,context:M,participantsProfile:s,afterRecoveryTimes:a,policyDefinitions:c,tournamentRecord:p,contextFilters:m,contextProfile:d,drawDefinition:v,contextContent:r,matchUpFilters:l,participantMap:n,scheduleTiming:R,nextMatchUps:f,inContext:g,event:h});return O??[]}),groupInfo:P}}function fe(t){let e=nt(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}=Di({participantsProfile:i,useParticipantMap:a,policyDefinitions:c,tournamentRecord:u,contextProfile:m,inContext:p}));let{appliedPolicies:S}=yt({tournamentRecord:u}),T={...g,tournamentId:I,indoorOutDoor:u.indoorOutdoor,surfaceCategory:u.surfaceCategory,endDate:u.endDate},y=Yn({policyDefinitions:c,tournamentRecord:u,contextProfile:m});return{matchUps:h.flatMap(U=>(T.eventDrawsCount=U.drawDefinitions?.length??0,qn({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:U}).matchUps??[])).concat(...u.matchUps??[])}}function An({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:wt};let p=Object.keys(n).map(m=>{let d=n[m];return fe({scheduleVisibilityFilters:t,afterRecoveryTimes:e,participantsProfile:r,policyDefinitions:o,tournamentRecord:d,matchUpFilters:i,contextFilters:s,nextMatchUps:a,inContext:c}).matchUps??[]}).flat();return{...C,matchUps:p}}function vi(t,e){return hk(t,e)||(t?.stageSequence||0)-(e?.stageSequence||0)||t?.roundNumber&&e.roundNumber&&t?.roundNumber-e?.roundNumber||(t?.roundPosition??0)-(e?.roundPosition??0)}function hk(t,e){return(Gs[t?.stage]||0)-(Gs[e?.stage]||0)}function Je(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:D,eventType:U,category:A,gender:E,matchUpFormat:M}=S??{},P={...h,surfaceCategory:S?.surfaceCategory??p?.surfaceCategory,indoorOutDoor:S?.indoorOutdoor??p?.indoorOutdoor,matchUpFormat:M,eventType:U,eventName:y,category:A,eventId:T,endDate:D,gender:E},N;return!e?.length&&!r&&p&&({participants:e=[],participantMap:r,groupInfo:N}=Di({participantsProfile:s,useParticipantMap:u,policyDefinitions:c,tournamentRecord:p,contextProfile:l,inContext:I})),l&&!n&&(n=Yn({policyDefinitions:c,tournamentRecord:p,contextProfile:l,drawDefinition:f,event:S})),{...re({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:N}}function Is({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 GU=t=>e=>!t||typeof e!="object"?void 0:Array.isArray(t)&&t.map(r=>({[r]:Is({element:e,accessor:r})?.value}))||typeof t=="object"&&Object.keys(t).map(r=>({[r]:Is({element:e,accessor:r})?.value}))||(typeof t=="string"&&Is({element:e,accessor:t}))?.value,Fr=GU;function Ra({finishingPositionOffset:t=0,finishingPositionLimit:e,positionsFed:r,roundsCount:n,roundLimit:o,matchUps:i,lucky:s,fmlc:a}){if(!Lr(i))return[];let{roundProfile:c,roundNumbers:u=[]}=je({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(Fr("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((R,b)=>R+(b||0),0),D=a&&I!==1,U=1+t+(D?r??0:0),A=1,E=tt(U,s?U+S*2:y+U+A),M=y+A-S,P=l(E.slice(M)),N=l(E.slice(0,M),!0);return T.finishingPositionRange={loser:P,winner:N},{[I]:T}})),g=Sr({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 Ki({inContextDrawMatchUps:t,drawDefinition:e,matchUpsMap:r}){if(!e)return{error:X};let n={loserMatchUpIds:{},winnerMatchUpIds:{}};if(t||({matchUps:t,matchUpsMap:r}=re({inContext:!0,drawDefinition:e,matchUpsMap:r})),!r?.drawMatchUps.some(i=>i.finishingPositionRange)&&e?.structures?.length===1&&!e?.structures[0].structures){let i=r?.drawMatchUps??[];Ra({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=ii({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 rn(t){let e=Tr(t),r=t.matchUps??[],n=t.drawIds??[],{includeParticipantDependencies:o,tournamentRecord:i,drawDefinition:s}=t;if(!Array.isArray(r))return{error:Xn};if(!Array.isArray(n))return{error:on};let a=t.matchUpIds?.length?t.matchUpIds:r.map(T=>T.matchUpId);if(!Array.isArray(a))return{error:ns};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(D=>(D.drawDefinitions||[]).map(U=>U.links||[])).flat(1/0),[]).filter(({linkType:T})=>T===Jn),g=r;if(f.length){g=An({nextMatchUps:!0,tournamentRecords:e}).matchUps;let T=f.reduce((y,D)=>{let U=D.source?.structureId,A=D.target?.structureId;return U&&A&&(p[A]=U),U&&!y.includes(U)&&y.push(U),y},[]);for(let y of T)c[y]=[];for(let y of g??[]){let D=y.containerStructureId||y.structureId;T.includes(D)&&c[D].push(y.matchUpId)}}let I=T=>{u[T]||(u[T]={dependentMatchUpIds:[],participantIds:[],matchUpIds:[],sources:[]},m[T]=[])},h=(T,y)=>{u[T].matchUpIds.forEach(U=>{u[y].matchUpIds.push(U)}),u[y].matchUpIds.push(T),u[T].dependentMatchUpIds.push(y),o&&u[T].participantIds.forEach(U=>u[y].participantIds.push(U))},S=T=>{let y=Object.keys(c).length;for(let D of T||[]){let{matchUpId:U,winnerMatchUpId:A,loserMatchUpId:E}=D;if(!a.length||a.includes(U)){if(I(U),o){let{individualParticipantIds:N}=du(D);u[U].participantIds=N}A&&(I(A),h(U,A),m[A].push(U)),E&&(I(E),h(U,E),m[E].push(U)),u[U].sources.push(m[U]);let M=m[U].map(N=>u[N].sources[0]).flat(),P=m[U].map(N=>u[N].sources[1]).flat();if(u[U].sources.push(M,P),y){let N=D.containerStructureId||D.structureId,R=p[N];if(c[R])for(let b of c[R])I(b),h(b,U),m[b].push(U)}}}};if(s)Ki({drawDefinition:s}),g?.length||(g=Je({drawDefinition:s}).matchUps),S(g);else{if(g?.length||(g=An({nextMatchUps:!0,tournamentRecords:e}).matchUps),!n.length){let T=d?.length?d.map(({events:y=[]})=>y.map(({drawDefinitions:D=[]})=>D.map(({drawId:U})=>U))).flat(1/0):[];T&&(n=T)}for(let T of n){let y=g?.filter(U=>U.drawId===T).sort(vi);if(!y?.find(({roundPosition:U})=>!U)){let U=y?.find(({tournamentId:E})=>E),{drawDefinition:A}=He({tournamentRecord:e[U?.tournamentId],drawId:T});A&&Ki({drawDefinition:A})}S(y)}}return{positionDependencies:c,matchUpDependencies:u,sourceMatchUpIds:m,matchUps:g,...C}}function me(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 Ca({matchUpStatus:t}){return yh.includes(t)}function tv({matchUpStatus:t}){return $m.includes(t)}function og({matchUpStatus:t}){return Ah.includes(t)}function ig({matchUpStatus:t,winningSide:e,tieMatchUps:r,sides:n,score:o}){let i=n?.find(({participantId:c})=>c),s=r?.filter(ig)?.length;return me({score:o})||s||e&&i||t&&tv({matchUpStatus:t})&&![Mt,vt,Ln].includes(t)}function ba(t){let{drawDefinition:e,findContainer:r,structureId:n,event:o}=t,i=t.structure,s={isCollectionMatchUp:!1},{containedStructures:a}=cs({drawDefinition:e}),c=n?a[n]||[]:[];if(!i){let A=at({drawDefinition:e,structureId:n});if(A.error)return A;i=r?A.containingStructure??A.structure:A.structure}if(pr({structure:i}))return{structure:i,isAdHoc:!0,error:Os};let{matchUps:u}=re({inContext:!0,matchUpFilters:s,drawDefinition:e,event:o}),p=u?.filter(A=>A.structureId===n||c.includes(A.structureId)),{matchUpDependencies:m}=rn({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 E=A.roundNumber;for(let M of(A.drawPositions??[]).filter(Boolean))(!f[M]||E&&f[M]>E)&&(f[M]=E)}ig(A)&&(g.push(A),d.push(A.matchUpId,...m?.[A?.matchUpId]?.matchUpIds||[]))}let I=pt(l.filter(Boolean)).sort(ae),h=pt(d),S=pt(p?.map(({matchUpId:A,drawPositions:E})=>h.includes(A)?E:[]).flat().filter(Boolean)).sort(ae),{positionAssignments:T}=Ct({drawDefinition:e,structure:i}),y=T?.filter(A=>A.bye).map(A=>A.drawPosition),D=T?.filter(A=>A.qualifier).map(A=>A.drawPosition),U=I?.filter(A=>!S.includes(A))||[];return{allDrawPositions:I,inContextStructureMatchUps:p,drawPositionInitialRounds:f,activeDependentMatchUpIds:h,qualifyingDrawPositions:D,inactiveDrawPositions:U,positionAssignments:T,activeDrawPositions:S,byeDrawPositions:y,activeMatchUps:g,structure:i}}function hs({drawPosition:t,matchUps:e=[]}){return{initialRoundNumber:e.filter(({drawPositions:n})=>t&&n?.includes(t)).map(({roundNumber:n})=>n).sort(ae)[0]}}var va={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 oS=[];function $n(t,e){typeof t=="string"&&(t={method:t}),(e||Sr())&&oS.push(t)}function Sk(t){let e=oS.slice();return t&&(oS.length=0),e}function ev(t){let r=Sk(t).map(n=>{let{color:o,keyColors:i,method:s,newline:a}=n,c=Object.keys(va).includes(o)?va[o]:va.cyan,p=Object.keys(n).filter(d=>!["color","keyColors","method","newline"].includes(d)).map(d=>{let l=i&&Object.keys(i).includes(d)&&va[i[d]]?va[i[d]]:va.brightwhite;return`${va.white}${d}: ${l}${n[d]}`}).join(", "),m=s?.length<15?" ":" ";return[a?`
|
|
1
|
+
var NL=Object.defineProperty;var Qt=(t,e)=>{for(var r in e)NL(t,r,{get:e[r],enumerable:!0})};function qa(){return"2.1.2"}var UA={};Qt(UA,{competitionGovernor:()=>gU,drawsGovernor:()=>_N,entriesGovernor:()=>VN,eventGovernor:()=>XN,generationGovernor:()=>rM,matchUpFormatGovernor:()=>ky,matchUpGovernor:()=>EM,mocksGovernor:()=>II,participantGovernor:()=>JM,policyGovernor:()=>pN,publishingGovernor:()=>aR,queryGovernor:()=>vN,reportGovernor:()=>cR,scheduleGovernor:()=>yR,scoreGovernor:()=>Wg,tieFormatGovernor:()=>bR,tournamentGovernor:()=>BR,venueGovernor:()=>XR});var gU={};Qt(gU,{getLinkedTournamentIds:()=>cu,getTournamentIds:()=>Ep,linkTournaments:()=>pU,mutate:()=>lU,query:()=>fU,unlinkTournament:()=>dU,unlinkTournaments:()=>mU});var lU={};Qt(lU,{linkTournaments:()=>pU,unlinkTournament:()=>dU,unlinkTournaments:()=>mU});var xC={};Qt(xC,{addNotice:()=>dt,callListener:()=>Cm,createInstanceState:()=>WE,cycleMutationStatus:()=>uf,deepCopyEnabled:()=>cf,deleteNotice:()=>zI,deleteNotices:()=>Bi,disableNotifications:()=>jE,enableNotifications:()=>af,getDevContext:()=>Sr,getMethods:()=>pf,getNotices:()=>KI,getProvider:()=>QI,getTopics:()=>xr,getTournamentId:()=>is,getTournamentRecord:()=>mf,getTournamentRecords:()=>Vo,globalLog:()=>$E,handleCaughtError:()=>mp,hasTopic:()=>up,removeTournamentRecord:()=>qE,setDeepCopy:()=>Kc,setDevContext:()=>$c,setGlobalLog:()=>vC,setGlobalMethods:()=>OC,setGlobalSubscriptions:()=>oF,setMethods:()=>_C,setStateMethods:()=>KE,setStateProvider:()=>rF,setSubscriptions:()=>iF,setTournamentId:()=>pp,setTournamentRecord:()=>YE,setTournamentRecords:()=>bm,timeKeeper:()=>nF});function Vr(t){return typeof t=="function"}function te(t){return typeof t=="string"}function It(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function dC(t,e){if(!It(t)||!It(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 CI(t,e){return Array.isArray(t)?Object.assign({},...(t??[]).filter(It).map(r=>r[e]&&{[r[e]]:r}).filter(Boolean)):{}}var lC=t=>e=>Object.keys(t).every(r=>e[r]===t[r]);function RI(t,e){if(t===void 0)return null;if(!It(t)||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=>RI(i))}:{[o]:e?n(t[o]):RI(t[o])}))}function CA(t){return Array.isArray(t)?t.length+t.map(CA).reduce((e,r)=>e+r,0):It(t)&&t!==null?Object.keys(t).length+Object.keys(t).map(e=>CA(t[e])).reduce((e,r)=>e+r,0):0}function fC(t){if(t===null||typeof t!="object")return;let e=JSON.stringify(t),r=CA(t),n=e.split("").reduce((o,i)=>o+i.charCodeAt(0),0);return[e.length,r,n].map(o=>o.toString(36)).join("")}var C={success:!0},bA="error",gC={SUCCESS:C,ERROR:bA};var bI={message:"Chronological error; time violation.",code:"ANACHRONISM"},Um={message:"Duplicate entry",code:"DUPLICATE_ENTRY"},vA={message:"Cannot remove main structure",code:"ERR_CANNOT_REMOVE_MAIN_STRUCTURE"},vI={message:"records must be an object with tournamentId keys",code:"ERR_INVALID_TOURNAMENTS"},wt={message:"Missing tournamentRecords",code:"ERR_MISSING_TOURNAMENTS"},j={message:"Missing tournamentRecord",code:"ERR_MISSING_TOURNAMENT"},$a={message:"Invalid tournamentRecord",code:"ERR_INVALID_TOURNAMENT"},la={message:"Missing tournamentId",code:"ERR_MISSING_TOURNAMENT_ID"},fa={message:"Invalid drawDefinition",code:"ERR_INVALID_DRAWDEF"},X={message:"Missing drawDefinition",code:"ERR_MISSING_DRAWDEF"},OA={message:"Existing drawDefinition(s)",code:"ERR_EXISTING_DRAWDEFS"},Dr={message:"drawDefinition not found",code:"ERR_NOT_FOUND_DRAWDEF"},Qo={message:"Invalid structure",code:"ERR_INVALID_STRUCTURE"},_l={message:"Incomplete source structure",code:"ERR_INCOMPLETE_STRUCTURE"},xl={message:"Invalid drawPosition for seedAssignment",code:"ERR_INVALID_SEEDING_POSITION"},Ka={message:"drawPosition already assigned",code:"ERR_EXISTING_POSITION_ASSIGNMENT"},_A={message:"Schedule not cleared",code:"ERR_UNCHANGED_SCHEDULE_NOT_CLEARED"},xA={message:"drawPosition not cleared",code:"ERR_FAILURE_POSITION_NOT_CLEARED"},ML={message:"drawPosition not found",code:"ERR_NOT_FOUND_DRAW_POSITION"},wl={message:"Unrecognized drawType",code:"ERR_UNRECOGNIZED_DRAW_TYPE"},za={message:"Missing drawPositions",code:"ERR_MISSING_DRAW_POSITIONS"},Xu={message:"drawPosition is active",code:"ERR_ACTIVE_DRAW_POSITION"},Os={message:"Invlid drawPosition",code:"ERR_INVALID_DRAW_POSITION"},_s={message:"Missing drawPosition",code:"ERR_MISSING_DRAW_POSITION"},Dm={message:"Invalid drawType",code:"ERR_INVALID_DRAW_TYPE"},Ju={message:"Invalid drawSize",code:"ERR_INVALID_DRAW_SIZE"},OI={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"},on={message:"Missing drawId",code:"ERR_MISSING_DRAW_ID"},wA={message:"drawId exists",code:"ERR_EXISTING_DRAW_ID"},LA={message:"participantId cannot be assigned to multiple seedNumbers",code:"INVALID_PARTICIPANT_SEEDING"},FA={message:"seedsCount greater than drawSize",code:"ERR_INVALID_SEED_COUNT"},kA={message:"Missing seedCountThresholds",code:"ERR_MISSING_SEED_COUNT_THRESHOLD"},GA={message:"Invalid action",code:"ERR_INVALID_ACTION"},_I={message:"Invalid assignment",code:"ERR_INVALID_ASSIGNMENT"},VA={message:"Missing seedAssignments",code:"ERR_MISSING_SEED_ASSIGNMENTS"},BA={message:"Invalid seedNumber",code:"ERR_INVALID_SEED_NUMBER"},HA={message:"Invalid seedPosition",code:"ERR_INVALID_SEED_POSITION"},Ll={message:"Missing targetLink",code:"ERR_MISSING_LINK_TARGET"},WA={message:"Existing round",code:"ERR_EXISTING_ROUND"},RL={message:"Missing roundNumber",code:"ERR_MISSING_ROUND_NUMBER"},hr={message:"Missing structureId",code:"ERR_MISSING_STRUCTURE_ID"},Lt={message:"structure not found",code:"ERR_NOT_FOUND_STRUCTURE"},Fl={message:"Missing structures",code:"ERR_MISSING_STRUCTURES"},di={message:"Missing structure",code:"ERR_MISSING_STRUCTURE"},jA={message:"drawDefinition contains unlinked structures",code:"ERR_MISSING_STRUCTURE_LINKS"},Bn={message:"Invalid eventType",code:"ERR_INVALID_EVENT_TYPE"};var bt={message:"Missing event / eventId",code:"ERR_MISSING_EVENT_ID"},Pr={message:"Event not found",code:"ERR_NOT_FOUND_EVENT"},YA={message:"Event exists",code:"ERR_EXISTING_EVENT"},qA={message:"Missing entries",code:"ERR_MISSING_ENTRIES"},$A={message:"Invalid entries",code:"ERR_INVALID_ENTRIES"},kl={message:"Missing assignments",code:"ERR_MISSING_ASSIGNMENTS"},KA={message:"Missing stage",code:"ERR_MISSING_STAGE"},Li={message:"Invalid stage",code:"ERR_INVALID_STAGE"},zA={message:"stageSequence limit",code:"ERR_LIMIT_STAGE_SEQUENCE"},QA={message:"Missing positionAssignments",code:"ERR_MISSING_POSITION_ASSIGNMENTS"},XA={message:"Cannot Assign BYE status if no assignment: { bye: true }",code:"ERR_UNCHANGED_CANNOT_ASSIGN_BYE"},xI={message:"Unrecognized matchUpStatus",code:"ERR_UNRECOGNIZED_MATCHUP_STATUS"},Xa={message:"Unrecognized matchUpFormat",code:"ERR_UNRECOGNIZED_MATCHUP_FORMAT"},Gl={message:"Incompatible matchUpStatus",code:"ERR_INCOMPATIBLE_MATCHUP_STATUS"},ga={message:"Invalid matchUpStatus",code:"ERR_INVALID_MATCHUP_STATUS"},li={message:"Invalid tieFormat",code:"ERR_INVALID_TIE_FORMAT"},Vl={message:"Invalid matchUpFormat",code:"ERR_INVALID_MATCHUP_FORMAT"},Bl={message:"Missing matchUpFormat",code:"ERR_MISSING_MATCHUP_FORMAT"},JA={message:"Missing collectionDefinition",code:"ERR_MISSING_COLLECTION_DEFINITION"},xs={message:"Missing tieFormat",code:"ERR_MISSING_TIE_FORMAT"},er={message:"Missing matchUpId",code:"ERR_MISSING_MATCHUP_ID"},ns={message:"Missing matchUpIds",code:"ERR_MISSING_MATCHUP_IDS"},_e={message:"matchUp not found",code:"ERR_NOT_FOUND_MATCHUP"},Xn={message:"Missing matchUps",code:"ERR_MISSING_MATCHUPS"},dr={message:"Missing matchUp",code:"ERR_MISSING_MATCHUP"},or={message:"Invalid matchUp",code:"ERR_INVALID_MATCHUP"},wI={message:"Missing policyType",code:"ERR_MISSING_POLICY_TYPE"},Zu={message:"Missing policyDefinitions",code:"ERR_MISSING_POLICY_DEFINITIONS"},CL={message:"Missing seeding policy",code:"ERR_MISSING_POLICY_SEEDING"},ZA={message:"Missing avoidance policy",code:"ERR_MISSING_POLICY_AVOIDANCE"},LI={message:"Missing policy attributes",code:"ERR_MISSING_POLICY_ATTRIBUTES"},tE={message:"Invalid policyDefinitions",code:"ERR_INVALID_POLICY_DEFINITIONS"},FI={message:"existing policyType",code:"ERR_EXISTING_POLICY_TYPE"},bL={message:"Policy not attached",code:"ERR_FAILURE_POLICY_NOT_ATTACHED"},Wc={message:"Policy not found",code:"ERR_NOT_FOUND_POLICY"},vL={message:"Missing scoring policy / matchUpFormats",code:"ERR_MISSING_POLICY_SCORING_MATCHUP_FORMATS"},Hl={message:"Invalid sideNumber",code:"ERR_INVALID_SIDE_NUMBER"},OL={message:"Invalid setNumber",code:"ERR_INVALID_SET_NUMBER"},Wl={message:"Missing setObject",code:"ERR_MISSING_SET_ATTRIBUTE"},_L={message:"Missing setNumber",code:"ERR_MISSING_SET_NUMBER"},xL={message:"Missing sideNumber",code:"ERR_MISSING_SIDE_NUMBER"},Fi={message:"Missing courtId",code:"ERR_MISSING_COURT_ID"},ot={message:"Missing value",code:"ERR_MISSING_VALUE"},eE={message:"Missing birthdate",code:"ERR_MISSING_BIRTH_DATE"},rE={message:"Missing date",code:"ERR_MISSING_DATE"},nE={message:"No valid dates",code:"ERR_NO_VALID_DATES"},Pm={message:"Invalid bookings",code:"ERR_INVALID_BOOKINGS"},jl={message:"Invalid dateAvailability",code:"ERR_INVALID_DATE_AVAILABILITY"},oE={message:"Missing dateAvailability",code:"ERR_MISSING_DATE_AVAILABILITY"},Ge={message:"Invalid Date",code:"ERR_INVALID_DATE"},Po={message:"Invalid time",code:"ERR_INVALID_TIME"},iE={message:"Invalid tournament dates",code:"ERR_INVALID_DATES_TOURNAMENT"};var kI={message:"Invalid game scores",code:"ERR_INVALID_SCORES_GAME"},sE={message:"Invalid score",code:"ERR_INVALID_SCORE"},Nm={message:"Invalid winningSide",code:"ERR_INVALID_WINNING_SIDE"};var IC={message:"No participants generated",code:"ERR_NO_PARTICIPANTS_GENERATED"},Yl={message:"Cannot modify tieFormat",code:"ERR_UNCHANGED_CANNOT_MODIFY_TIEFORMAT"},aE={message:"Cannot modify participantType",code:"ERR_UNCHANGED_CANNOT_MODIFY_PARTICIPANT_TYPE"},tp={message:"Cannot remove participants",code:"ERR_UNCHANGED_CANNOT_REMOVE_PARTICIPANTS"},GI={message:"Participant category mismatch",code:"ERR_CATEGORY_MISMATCH"},ql={message:"Cannot change winningSide",code:"ERR_UNCHANGED_CANNOT_CHANGE_WINNING_SIDE"},ki={message:"Invalid participant",code:"ERR_INVALID_PARTICIPANT"},pn={message:"Invalid participantId",code:"ERR_INVALID_PARTICIPANT_ID"},_r={message:"Invalid participantIds",code:"ERR_INVALID_PARTICIPANT_IDS"},cE={message:"Invalid participantRole",code:"ERR_INVALID_PARTICIPANT_ROLE"},Sn={message:"Invalid participantType",code:"ERR_INVALID_PARTICIPANT_TYPE"},uE={message:"Missing participantRole",code:"ERR_MISSING_PARTICIPANT_ROLE"},Gi={message:"Missing participant",code:"ERR_MISSING_PARTICIPANT"},Ja={message:"Missing participants",code:"ERR_MISSING_PARTICIPANTS"},ee={message:"Missing participantId",code:"ERR_MISSING_PARTICIPANT_ID"},Xt={message:"Participant Not Found",code:"ERR_NOT_FOUND_PARTICIPANT"},pE={message:"participantId exists",code:"ERR_EXISTING_PARTICIPANT_ID"},wL={message:"participant pair exists",code:"ERR_EXISTING_PARTICIPANT_PAIR"},mE={message:"No participant removed",code:"ERR_UNCHANGED_NO_PARTICIPANT_REMOVED"},No={message:"Missing participantIds",code:"ERR_MISSING_PARTICIPANT_IDS"},dE={message:"Missing participantsCount",code:"ERR_MISSING_PARTICIPANT_COUNT"},lE={message:"Participant not checked in",code:"ERR_UNCHANGED_PARTICIPANT_NOT_CHECKED_IN"},fE={message:"Missing person details",code:"ERR_MISSING_PERSON_DETAILS"},ws={message:"Existing participant drawPosition assignment",code:"ERR_EXISTING_PARTICIPANT_DRAW_POSITION_ASSIGNMENT"},ep={message:"Existing participant",code:"ERR_EXISTING_PARTICIPANT"},$l={message:"participantsCount exceeds drawSize",code:"ERR_INVALID_PARTICIPANT_COUNT"},Kl={message:"Invalid entry status",code:"ERR_INVALID_ENTRY_STATUS"},VI={message:"Participant Entry Not Found",code:"ERR_NOT_FOUND_PARTICIPANT_ENTRY"},hC={message:"Participant not entered in stage",code:"ERR_UNCHANGED_PARTICIPANT_NOT_ENTERED"},SC={message:"Participant not found in stageSequence",code:"ERR_NOT_FOUND_PARTICIPANT_IN_STAGE"},gE={message:"entryStatus not allowed in stage",code:"ERR_INVALID_ENTRY_STATUS_IN_STAGE"},IE={message:"entryStatus not allowed for event",code:"ERR_INVALID_ENTRY_STATUS_IN_EVENT"},BI={message:"No stage space available for entryStatus",code:"ERR_UNCHANGED_NO_AVAILABLE_STAGE_SPACE"},hE={message:"Insufficient drawPositions to accommodate qualifiers",code:"ERR_UNCHANGED_NO_DRAW_POSITIONS_FOR_QUALIFIERS"},zl={message:"Insufficient drawPositions to accommodate entries",code:"ERR_INSUFFICIENT_DRAW_POSITIONS"},SE={message:"Missing penaltyType",code:"ERR_MISSING_PENALTY_TYPE"},Ql={message:"Missing penaltyId",code:"ERR_MISSING_PENALTY_ID"},jc={message:"Penalty not found",code:"ERR_NOT_FOUND_PENALTY"},TE={message:"Missing courtsCount/courtNames",code:"ERR_MISSING_COURTS_INFO"},Ls={message:"Court not found",code:"ERR_NOT_FOUND_COURT"},yE={message:"Court exists",code:"ERR_EXISTING_COURT"},AE={message:"Venue exists",code:"ERR_EXISTING_VENUE"},Vi={message:"Venue not found",code:"ERR_NOT_FOUND_VENUE"},Xo={message:"Missing venueId",code:"ERR_MISSING_VENUE_ID"},EE={message:"Invalid endTime",code:"ERR_INVALID_END_TIME"},HI={message:"Existing endTime",code:"ERR_EXISTING_END_TIME"},UE={message:"Invalid stopTime",code:"ERR_INVALID_STOP_TIME"},DE={message:"Invalid startTime",code:"ERR_INVALID_START_TIME"},TC={message:"Invalid resumeTime",code:"ERR_INVALID_RESUME_TIME"},Xl={message:"Invalid timeItem",code:"ERR_INVALID_TIME_ITEMS"},PE={message:"Missing async state provider",code:"ERR_MISSING_ASYNC_STATE_PROVIDER"},Jl={message:"Missing timeItem",code:"ERR_MISSING_TIME_ITEM"},Zl={message:"Missing timeItems",code:"ERR_MISSING_TIME_ITEMS"},Yc={message:"Missing context",code:"ERR_MISSING_CONTEXT"},NE={message:"Missing schedule",code:"ERR_MISSING_SCHEDULE"},rp={message:"Invalid scaleItem",code:"ERR_INVALID_SCALE_ITEM"},ME={message:"Modifications failed",code:"ERR_FAILURE_MODIFICATIONS"},Fs={message:"No modifications applied",code:"ERR_UNCHANGED_NO_MODIFICATIONS_APPLIED"},RE={message:"Unable to assign court",code:"ERR_UNCHANGED_COURT_NOT_ASSIGNED"},np={message:"No Candidates",code:"ERR_UNCHANGED_NO_CANDIDATES"},CE={message:"Invalid configuration",code:"ERR_INVALID_CONFIG"},bE={message:"Invalid collectionDefinition",code:"ERR_INVALID_COLLECTION_DEFINITION"},po={message:"Invalid object",code:"ERR_INVALID_OBJECT"},op={message:"Invalid gender",code:"ERR_INVALID_GENDER"},qc={message:"Invalid category",code:"ERR_INVALID_CATEGORY"},k={message:"Invalid values",code:"ERR_INVALID_VALUES"},vE={message:"Duplicate value",code:"ERR_DUPLICATE_VALUE"},tf={message:"Team not found",code:"ERR_NOT_FOUND_TEAM"},OE={message:"No valid actions",code:"ERR_NO_VALID_ACTIONS"},ip={message:"No valid attributes",code:"ERR_NO_VALID_ATTRIBUTES"},ef={message:"Value unchanged",code:"ABORT_UNCHANGED"},Pe={message:"Not found",code:"ERR_NOT_FOUND"},sp={message:"Not implemented",code:"ERR_NOT_IMPLEMENTED"},_E={message:"Existing flight",code:"ERR_EXISTING_FLIGHT"},rf={message:"Existing flight profile",code:"ERR_EXISTING_FLIGHT_PROFILE"},xE={message:"Existing outcome",code:"ERR_EXISTING_OUTCOME"},wE={message:"Existing matchUpId",code:"ERR_EXISTING_MATCHUP_ID"},WI={message:"Existing stage",code:"ERR_EXISTING_STAGE"},nf={message:"Existing structure",code:"ERR_EXISTING_STRUCTURE"},Za={message:"Method not found",code:"ERR_NOT_FOUND_METHOD"},LE={message:"Scheduled matchUps",code:"ERR_SCHEDULED_MATCHUPS"},ap={message:"Scores present",code:"ERR_SCORES_PRESENT"},yC={ANACHRONISM:bI,CANNOT_CHANGE_WINNING_SIDE:ql,CANNOT_MODIFY_TIEFORMAT:Yl,CANNOT_MODIFY_PARTICIPANT_TYPE:aE,CANNOT_REMOVE_MAIN_STRUCTURE:vA,CANNOT_REMOVE_PARTICIPANTS:tp,CATEGORY_MISMATCH:GI,COURT_EXISTS:yE,COURT_NOT_FOUND:Ls,DRAW_DEFINITION_NOT_FOUND:Dr,DRAW_ID_EXISTS:wA,DRAW_POSITION_ACTIVE:Xu,DRAW_POSITION_ASSIGNED:Ka,DRAW_POSITION_NOT_CLEARED:xA,DRAW_POSITION_NOT_FOUND:ML,DRAW_SIZE_MISMATCH:OI,DUPLICATE_ENTRY:Um,DUPLICATE_VALUE:vE,ENTRY_STATUS_NOT_ALLOWED_FOR_EVENT:IE,ENTRY_STATUS_NOT_ALLOWED_IN_STAGE:gE,EVENT_EXISTS:YA,EVENT_NOT_FOUND:Pr,EXISTING_DRAW_DEFINITIONS:OA,EXISTING_END_TIME:HI,EXISTING_FLIGHT:_E,EXISTING_MATCHUP_ID:wE,EXISTING_OUTCOME:xE,EXISTING_PARTICIPANT_DRAW_POSITION_ASSIGNMENT:ws,EXISTING_PARTICIPANT:ep,EXISTING_POLICY_TYPE:FI,EXISTING_PROFILE:rf,EXISTING_ROUND:WA,EXISTING_STAGE:WI,EXISTING_STRUCTURE:nf,INCOMPATIBLE_MATCHUP_STATUS:Gl,INCOMPLETE_SOURCE_STRUCTURE:_l,INSUFFICIENT_DRAW_POSITIONS:zl,INVALID_ACTION:GA,INVALID_ASSIGNMENT:_I,INVALID_BOOKINGS:Pm,INVALID_CATEGORY:qc,INVALID_COLLECTION_DEFINITION:bE,INVALID_CONFIGURATION:CE,INVALID_DATE_AVAILABILITY:jl,INVALID_DATE:Ge,INVALID_DRAW_DEFINITION:fa,INVALID_DRAW_POSITION_FOR_SEEDING:xl,INVALID_DRAW_POSITION:Os,INVALID_DRAW_SIZE:Ju,INVALID_END_TIME:EE,INVALID_ENTRIES:$A,INVALID_EVENT_TYPE:Bn,INVALID_GAME_SCORES:kI,INVALID_GENDER:op,INVALID_MATCHUP_FORMAT:Vl,INVALID_MATCHUP_STATUS:ga,INVALID_MATCHUP_STATUS_BYE:XA,INVALID_MATCHUP:or,INVALID_OBJECT:po,INVALID_PARTICIPANT_ID:pn,INVALID_PARTICIPANT_IDS:_r,INVALID_PARTICIPANT_ROLE:cE,INVALID_PARTICIPANT_SEEDING:LA,INVALID_PARTICIPANT_TYPE:Sn,INVALID_PARTICIPANT:ki,INVALID_POLICY_DEFINITION:tE,INVALID_RECORDS:vI,INVALID_SCALE_ITEM:rp,INVALID_SEED_NUMBER:BA,INVALID_SEED_POSITION:HA,INVALID_SET_NUMBER:OL,INVALID_SIDE_NUMBER:Hl,INVALID_SCORE:sE,INVALID_STAGE:Li,INVALID_START_TIME:DE,INVALID_STRUCTURE:Qo,INVALID_STOP_TIME:UE,INVALID_TIE_FORMAT:li,INVALID_TIME:Po,INVALID_TIME_ITEM:Xl,INVALID_TOURNAMENT_DATES:iE,INVALID_TOURNAMENT_RECORD:$a,INVALID_VALUES:k,INVALID_WINNING_SIDE:Nm,MATCHUP_NOT_FOUND:_e,METHOD_NOT_FOUND:Za,MISSING_ASSIGNMENTS:kl,MISSING_ASYNC_STATE_PROVIDER:PE,MISSING_AVOIDANCE_POLICY:ZA,MISSING_BIRTH_DATE:eE,MISSING_COLLECTION_DEFINITION:JA,MISSING_COURT_ID:Fi,MISSING_COURTS_INFO:TE,MISSING_DATE_AVAILABILITY:oE,MISSING_DATE:rE,MISSING_DRAW_DEFINITION:X,MISSING_DRAW_ID:on,MISSING_DRAW_POSITION:_s,MISSING_DRAW_POSITIONS:za,MISSING_DRAW_SIZE:Qa,MISSING_ENTRIES:qA,MISSING_EVENT:bt,MISSING_MATCHUP_FORMAT:Bl,MISSING_MATCHUP_ID:er,MISSING_MATCHUP_IDS:ns,MISSING_MATCHUP:dr,MISSING_MATCHUPS:Xn,MISSING_PARTICIPANT_COUNT:dE,MISSING_PARTICIPANT_ID:ee,MISSING_PARTICIPANT_IDS:No,MISSING_PARTICIPANT_ROLE:uE,MISSING_PARTICIPANT:Gi,MISSING_PARTICIPANTS:Ja,MISSING_PENALTY_ID:Ql,MISSING_PENALTY_TYPE:SE,MISSING_PERSON_DETAILS:fE,MISSING_POLICY_ATTRIBUTES:LI,MISSING_POLICY_DEFINITION:Zu,MISSING_POLICY_TYPE:wI,MISSING_POSITION_ASSIGNMENTS:QA,MISSING_ROUND_NUMBER:RL,MISSING_SCHEDULE:NE,MISSING_SCORING_POLICY:vL,MISSING_SEED_ASSIGNMENTS:VA,MISSING_SEEDCOUNT_THRESHOLDS:kA,MISSING_SEEDING_POLICY:CL,MISSING_SET_NUMBER:_L,MISSING_SET_OBJECT:Wl,MISSING_SIDE_NUMBER:xL,MISSING_STAGE:KA,MISSING_STRUCTURE_ID:hr,MISSING_STRUCTURE:di,MISSING_STRUCTURES:Fl,MISSING_TARGET_LINK:Ll,MISSING_TIE_FORMAT:xs,MISSING_TIME_ITEM:Jl,MISSING_TIME_ITEMS:Zl,MISSING_TOURNAMENT_ID:la,MISSING_TOURNAMENT_RECORD:j,MISSING_TOURNAMENT_RECORDS:wt,MISSING_VALUE:ot,MISSING_VENUE_ID:Xo,MODIFICATIONS_FAILED:ME,NO_CANDIDATES:np,NO_DRAW_POSITIONS_AVAILABLE_FOR_QUALIFIERS:hE,NO_MODIFICATIONS_APPLIED:Fs,NO_STAGE_SPACE_AVAILABLE_FOR_ENTRY_STATUS:BI,NO_PARTICIPANT_REMOVED:mE,NO_VALID_ACTIONS:OE,NO_VALID_ATTRIBUTES:ip,NO_VALID_DATES:nE,NOT_FOUND:Pe,NOT_IMPLEMENTED:sp,PARTICIPANT_COUNT_EXCEEDS_DRAW_SIZE:$l,PARTICIPANT_ID_EXISTS:pE,PARTICIPANT_NOT_CHECKED_IN:lE,PARTICIPANT_NOT_FOUND:Xt,PARTICIPANT_PAIR_EXISTS:wL,PENALTY_NOT_FOUND:jc,POLICY_NOT_ATTACHED:bL,POLICY_NOT_FOUND:Wc,SCHEDULE_NOT_CLEARED:_A,SCHEDULED_MATCHUPS:LE,SCORES_PRESENT:ap,SEEDSCOUNT_GREATER_THAN_DRAW_SIZE:FA,STAGE_SEQUENCE_LIMIT:zA,STRUCTURE_NOT_FOUND:Lt,TEAM_NOT_FOUND:tf,UNABLE_TO_ASSIGN_COURT:RE,UNLINKED_STRUCTURES:jA,UNRECOGNIZED_DRAW_TYPE:wl,UNRECOGNIZED_MATCHUP_FORMAT:Xa,UNRECOGNIZED_MATCHUP_STATUS:xI,VALUE_UNCHANGED:ef,VENUE_EXISTS:AE};var Ke={disableNotifications:!1,tournamentId:void 0,tournamentRecords:{},subscriptions:{},modified:!1,methods:{},notices:[]},FE={addNotice:$L,callListener:JL,cycleMutationStatus:qL,deleteNotice:QL,deleteNotices:zL,disableNotifications:LL,enableNotifications:FL,getMethods:cp,getNotices:KL,getTopics:XL,getTournamentId:AC,getTournamentRecord:kL,getTournamentRecords:GL,removeTournamentRecord:WL,setMethods:YL,setSubscriptions:jL,setTournamentId:BL,setTournamentRecord:VL,setTournamentRecords:HL,handleCaughtError:ZL};function LL(){Ke.disableNotifications=!0}function FL(){Ke.disableNotifications=!1}function AC(){return Ke.tournamentId}function kL(t){return Ke.tournamentRecords[t]}function GL(){return Ke.tournamentRecords}function VL(t){let e=t?.tournamentId;return e?(Ke.tournamentRecords[e]=t,{success:!0}):{error:$a}}function BL(t){return t?Ke.tournamentRecords[t]?(Ke.tournamentId=t,{success:!0}):{error:j}:(Ke.tournamentId=void 0,{success:!0})}function HL(t){Ke.tournamentRecords=t;let e=Object.keys(t);e.length===1?Ke.tournamentId=e[0]:e.length||(Ke.tournamentId=void 0)}function WL(t){if(typeof t!="string")return{error:k};if(!Ke.tournamentRecords[t])return{error:Pe};delete Ke.tournamentRecords[t];let e=Object.keys(Ke.tournamentRecords);return e.length===1?Ke.tournamentId=e[0]:e.length||(Ke.tournamentId=void 0),{success:!0}}function jL(t){return typeof t.subscriptions!="object"?{error:k}:(Object.keys(t.subscriptions).forEach(e=>{typeof t.subscriptions[e]=="function"?Ke.subscriptions[e]=t.subscriptions[e]:delete Ke.subscriptions[e]}),{...C})}function YL(t){return typeof t!="object"?{error:k}:(Object.keys(t).forEach(e=>{typeof t[e]=="function"&&(Ke.methods[e]=t[e])}),{...C})}function qL(){let t=Ke.modified;return Ke.modified=!1,t}function $L({topic:t,payload:e,key:r},n){if(!(typeof t!="string"||typeof e!="object")&&(Ke.disableNotifications||(Ke.modified=!0),!(Ke.disableNotifications||!Ke.subscriptions[t]&&!n)))return r&&(Ke.notices=Ke.notices.filter(o=>!(o.topic===t&&o.key===r))),Ke.notices.push({topic:t,payload:e,key:r}),{...C}}function cp(){return Ke.methods??{}}function KL({topic:t}){return Ke.notices.filter(e=>e.topic===t).map(e=>e.payload)}function zL(){Ke.notices=[]}function QL({topic:t,key:e}){Ke.notices=Ke.notices.filter(r=>(!t||r.topic===t)&&r.key!==e)}function XL(){return{topics:Object.keys(Ke.subscriptions)}}function JL({topic:t,notices:e},r){let n=Ke.subscriptions[t];n&&typeof n=="function"&&n(e);let o=r?.[t];o&&typeof o=="function"&&o(e)}function ZL({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:AC(),params:JSON.stringify(r),engine:t,methodName:e,error:o}),{error:o}}function ae(t,e){return(t??0)-(e??0)}function ut(t){return typeof t=="number"?parseInt(t.toString()):typeof t=="string"?parseInt(t):0}function On(t){return isNaN(t)?!1:t&&(t&t-1)===0}function kE(t){if(!t.length)return;let e=[...t].sort(ae),r=Math.floor(e.length/2);return e.length%2?e[r]:(e[r-1]+e[r])/2}function EC(t){if(!On(t))return!1;let e=t,r=1;for(;e!==2;)r+=1,e=e/2;return r}function Mm(t){return isNaN(t)?0:t%2&&t+1||t}function Rm(t){return Math.pow(2,Math.round(Math.log(t)/Math.log(2)))}function Jt(t){return!isNaN(parseFloat(t))}function jI(t){let e=ut(t);if(!isNaN(e))return e===0?!1:(e&-e)===1}function os(t){if(isNaN(t))return!1;for(;!On(t);)t++;return t}function mo(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 UC(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 tF(t,e){e||(e=1);let r=1/e;return Math.round(t*r)/r}function GE(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=GE(t,e,r):(a=Math.pow(a,r),a*=e-t,a+=t),n&&(a=tF(a,n)),parseFloat(a.toFixed(o))}function of(t,e=2){return parseFloat(Number(Math.round(t*1e3)/1e3).toFixed(e))}function pt(t){return Array.isArray(t)?t?.filter((e,r,n)=>n.lastIndexOf(e)===r):[]}function DC(t){return Array.isArray(t)?t?.map(e=>e===null?void 0:e):t}function lr(t){return Array.isArray(t)?t.map(e=>[Math.random(),e]).sort((e,r)=>e[0]-r[0]).map(e=>e[1]):[]}function tc(t){return ft(t)?t:1/0}function gr(t){return Array.isArray(t)?t.reduce((e,r)=>(e[r]||(e[r]=0),e[r]++,e),{}):{}}function PC(t){return VE(gr(t))}function VE(t){return Object.keys(t).reduce((e,r)=>{let n=t[r];return e[n]?e[n].push(r):e[n]=[r],e},{})}function eF(t,e,r){return r.indexOf(t)===e}function YI(t){return t.filter(eF)}function $r(t){return Array.isArray(t)&&t.length?t.splice(Math.floor(Math.random()*t.length),1)[0]:void 0}function Tn(t){let e=Math.floor(Math.random()*t.length);return t[e]}function tt(t,e){return Array.from({length:e-t},(r,n)=>n+t)}function lo(t,e){return e.reduce((r,n,o)=>(n===t&&r.push(o),r),[])}function qt(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 BE(t,e){return!Array.isArray(t)||!Array.isArray(e)?[]:t.filter(r=>!e.includes(r))}function xe(t,e){return!Array.isArray(t)||!Array.isArray(e)?!1:t.some(r=>e.includes(r))}function NC(t,e){return Array.isArray(e)&&e.reduce((r,n)=>(r[n]=1+r[n]||1,r),{})[t]||0}function MC(t,e,r,n){return Array.isArray(t)?[].concat(...t.slice(0,e),...t.slice(e,e+r).sort(n),...t.slice(e+r,t.length)):[]}function Ae(t,e){return Array.isArray(t)?t.reduce((r,n,o)=>{let i=Math.floor(o/e);return r[i]=[].concat(r[i]||[],n),r},[]):[]}function HE(t,[e,...r]){return t.length?[t.slice(0,e),...HE(t.slice(e),[...r,e])]:[]}function RC(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 qI(t){return Array.isArray(t)?t.reduce((e,r)=>!isNaN(parseInt(r))&&e,!0):!1}function $I(t){return Array.isArray(t)?t.reduce((e,r)=>isNaN(parseInt(r))&&e,!0):!1}function sf(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 CC(t,e=1){if(!Array.isArray(t)||!t.every(ft))return[];let r=Math.min(...t,e),n=Math.max(...t);return tt(r,n+1).filter(o=>!t.includes(o))}var Ne={timers:{default:{elapsedTime:0}},globalSubscriptions:{},deepCopyAttributes:{stringify:[],ignore:[],toJSON:[]},globalMethods:[],deepCopy:!0},sn=FE,bC=["addNotice","callListener","cycleMutationStatus","deleteNotice","deleteNotices","disableNotifications","enableNotifications","getMethods","getNotices","getTopics","getTournamentId","getTournamentRecord","getTournamentRecords","removeTournamentRecord","setSubscriptions","setTournamentId","setTournamentRecord","setTournamentRecords"];function rF(t){if(typeof t!="object")throw new Error("Global state provider can not be undefined or null");if(qt(Object.keys(t),bC).length!==bC.length)throw new Error("Global state provider is missing required methods");return sn=t,{success:!0}}function WE(){if(sn.createInstanceState){try{sn.createInstanceState()}catch(t){return{error:t}}return{success:!0}}else return{error:PE}}function Sr(t){return!t||typeof t!="object"?Ne.devContext??!1:typeof Ne.devContext!="object"?!1:Object.keys(t).every(e=>Ne.devContext?.[e]===t[e])&&Ne.devContext}function nF(t="reset",e="default"){let r=Date.now();if(t==="report"){if(e==="allTimers")return Object.keys(Ne.timers).filter(o=>o!=="default"||Ne.timers[o].startTime).map(o=>{let i=Ne.timers[o],s=i.state==="stopped"?0:(r-(i?.startTime??0))/1e3,a=i.elapsedTime+s;return{state:Ne.timers[o].state,elapsedTime:a.toFixed(2),timer:o}});{let n=Ne.timers[e].state==="stopped"?0:(r-(Ne.timers[e]?.startTime??0))/1e3,o=Ne.timers[e].elapsedTime+n;return{state:Ne.timers[e].state,elapsedTime:o.toFixed(2),timer:e}}}if(!Ne.timers[e]||t==="reset"){if(e==="allTimers")return Ne.timers={default:{elapsedTime:0}},!0;Ne.timers[e]={startTime:r,state:"active",elapsedTime:0}}return Ne.timers[e].elapsedTime||(Ne.timers[e].elapsedTime=0),t==="stop"&&Ne.timers[e].state!=="stopped"&&(Ne.timers[e].state="stopped")&&(Ne.timers[e].elapsedTime+=(r-(Ne.timers[e]?.startTime??0))/1e3),t==="start"&&(Ne.timers[e].startTime=r)&&(Ne.timers[e].state="active"),Ne.timers[e]}function vC(t){Vr(t)?Ne.globalLog=t:delete Ne.globalLog}function $c(t){Ne.devContext=t}function jE(){sn.disableNotifications()}function af(){sn.enableNotifications()}function Kc(t,e){typeof t=="boolean"&&(Ne.deepCopy=t),typeof e=="object"&&(Array.isArray(e.ignore)&&(Ne.deepCopyAttributes.ignore=e.ignore),Array.isArray(e.toJSON)&&(Ne.deepCopyAttributes.toJSON=e.toJSON),Array.isArray(e.stringify)&&(Ne.deepCopyAttributes.stringify=e.stringify),e.threshold&&(Ne.deepCopyAttributes.threshold=e.threshold))}function cf(){return{enabled:Ne.deepCopy,...Ne.deepCopyAttributes}}function oF(t){return t?.subscriptions?(Object.keys(t.subscriptions).forEach(e=>{Ne.globalSubscriptions[e]=t.subscriptions[e]}),{...C}):{error:ot,info:"missing subscriptions"}}function iF(t){return t?.subscriptions?sn.setSubscriptions({subscriptions:t.subscriptions}):{error:ot,info:"missing subscriptions"}}function OC(t){return t?typeof t!="object"?{error:k}:(Object.keys(t).forEach(e=>{Vr(t[e])&&(Ne.globalMethods[e]=t[e])}),{...C}):{error:ot,info:"missing method declarations"}}function _C(t){return t?typeof t!="object"?{error:k}:sn.setMethods(t):{error:ot,info:"missing method declarations"}}function uf(){return sn.cycleMutationStatus()}function dt(t){if(typeof t?.topic!="string")return;let e=Ne.globalSubscriptions[t.topic];return sn.addNotice(t,e)}function pf(){return{...Ne.globalMethods,...sn.getMethods()}}function KI(t){return sn.getNotices(t)}function zI({key:t,topic:e}){return sn.deleteNotice({key:t,topic:e})}function Bi(){return sn.deleteNotices()}function xr(){return sn.getTopics()}function up(t){return xr()?.topics?.includes(t)}async function Cm(t){return sn.callListener(t,Ne.globalSubscriptions)}function is(){return sn.getTournamentId()}function mf(t){return sn.getTournamentRecord(t)}function Vo(){return sn.getTournamentRecords()}function YE(t){return sn.setTournamentRecord(t)}function bm(t){return sn.setTournamentRecords(t)}function pp(t){return sn.setTournamentId(t)}function qE(t){return sn.removeTournamentRecord(t)}function QI(){return sn}function mp({engineName:t,methodName:e,params:r,err:n}){return(Vr(sn.handleCaughtError)&&sn.handleCaughtError||FE.handleCaughtError)({engineName:t,methodName:e,params:r,err:n})}function $E(t,e){if(Ne.globalLog)try{Ne.globalLog({log:t,engine:e})}catch(r){console.log("globalLog error",r),console.log(e,t),vC()}else console.log(e,t)}function KE(t,e,r,n){if(!It(t))return{error:k};Jt||(r=1);let o=Array.isArray(e)?e:[],i={},s=(a,c=0)=>{Object.keys(a).forEach(u=>{Vr(a[u])?i[u]=a[u]:It(a[u])&&(e===!0||o?.includes(u))&&(r===void 0||c<r)&&s(a[u],c+1)})};return s(t),n?OC(i):_C(i),{methods:i}}function sF(t,e,r){return Object.keys(t).filter(n=>!e.includes(t[n])&&(!r||(Array.isArray(t[n])?t[n].length:!0)))}function rt(t,e,r,n){if(typeof t!="object"||t===null)return t;cf()?.enabled||(n=!0);let i=["",void 0,null];e&&i.push(!1);let s=sF(t,i,r);return Object.assign({},...s.map(a=>Array.isArray(t[a])?{[a]:n?t[a]:t[a].map(c=>rt(c))}:{[a]:n?t[a]:rt(t[a])}))}function _({context:t,result:e,stack:r,info:n}){return e&&!Array.isArray(e?.stack)&&(e.stack=[]),e&&Array.isArray(e?.stack)&&typeof r=="string"&&e.stack.push(r),e&&n&&(e.info=n),e&&typeof t=="object"&&Object.keys(t).length&&Object.assign(e,rt(t)),e&&!e?.error&&!e?.success&&Object.assign(e,{...C}),e??{success:!0}}var ec="resourceSubType",rc="resourceType",nc="identifier",wC={RESOURCE_SUB_TYPE:ec,RESOURCE_TYPE:rc,IDENTIFIER:nc};var Hn="SINGLES",ks="SINGLES",Br="DOUBLES",fi="DOUBLES",Me="TEAM",Kr="TEAM",aF="AGE",cF="RATING",uF="BOTH",LC={AGE:aF,BOTH:uF,DOUBLES:Br,DOUBLES_EVENT:fi,RATING:cF,SINGLES:Hn,SINGLES_EVENT:ks,TEAM_EVENT:Kr,TEAM:Me};var et="MAIN",ct="QUALIFYING",Ve="CONSOLATION",Be="VOLUNTARY_CONSOLATION",pe="PLAY_OFF",zc=[et,ct,Ve,pe,Be],Gs={[ct]:1,[et]:2,[pe]:3,[Ve]:3,[Be]:4},zE="finishingPositions",QE="aggregateEventStructures",XE={[et]:1,[pe]:2,[Ve]:3,[ct]:4,[Be]:5},FC={[pe]:1,[et]:2,[Ve]:3,[ct]:4,[Be]:5},Qc="CLUSTER",kC="SEPARATE",gi="WATERFALL",dp="ITEM",we="CONTAINER",mn="DRAW",lp="RANDOM",yn="TOP_DOWN",Ii="BOTTOM_UP",Jn="POSITION",fo="WINNER",Zn="LOSER",to="FIRST_MATCHUP",an="AD_HOC",pF="AD_HOC",Ia="FEED_IN",Xc="COMPASS",Jc="OLYMPIC",mF="SINGLE_ELIMINATION";var go="SINGLE_ELIMINATION",Zc="DOUBLE_ELIMINATION",tu="FIRST_MATCH_LOSER_CONSOLATION",fp="FIRST_ROUND_LOSER_CONSOLATION",Hi="LUCKY_DRAW",df="CURTIS_CONSOLATION",GC="CURTIS_CONSOLATION",XI="FEED_IN_CHAMPIONSHIP_TO_SF",vm="FEED_IN_CHAMPIONSHIP_TO_SF",JI="FEED_IN_CHAMPIONSHIP_TO_QF",Om="FEED_IN_CHAMPIONSHIP_TO_QF",ZI="FEED_IN_CHAMPIONSHIP_TO_R16",_m="FEED_IN_CHAMPIONSHIP_TO_R16",JE="MODIFIED_FEED_IN_CHAMPIONSHIP",xm="MODIFIED_FEED_IN_CHAMPIONSHIP",gp="FEED_IN_CHAMPIONSHIP",VC="DOUBLE_ROUND_ROBIN",Un="ROUND_ROBIN",Io="ROUND_ROBIN_WITH_PLAYOFF",ZE="DECIDER",tU="BACKDRAW",lf={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"}},ff={0:{name:"East",abbreviation:"E"},"0-1":{name:"West",abbreviation:"W"},"0-2":{name:"North",abbreviation:"N"},"0-1-1":{name:"South",abbreviation:"S"}},Vs="WIN_RATIO",Wi="ROUND_OUTCOME",eU=[Xc,df,Om,_m,vm,gp,JI,ZI,XI,tu,fp,Hi,xm,Jc,pe,Io],dF=[an,Xc,df,Zc,Om,_m,vm,gp,Ia,tu,fp,Hi,xm,Jc,pe,Un,Io,go],rU={MAIN:et,QUALIFYING:ct,CONSOLATION:Ve,ITEM:dp,CONTAINER:we,FIRST_MATCHUP:to,WINNER:fo,LOSER:Zn,AD_HOC:an,FEED_IN:Ia,FLEX_ROUNDS:pF,COMPASS:Xc,PLAY_OFF:pe,OLYMPIC:Jc,KNOCKOUT:mF,SINGLE_ELIMINATION:go,DOUBLE_ELIMINATION:Zc,CURTIS:df,FICSF:XI,FICQF:JI,FICR16:ZI,MFIC:JE,VOLUNTARY_CONSOLATION:Be,FIRST_MATCH_LOSER_CONSOLATION:tu,FIRST_ROUND_LOSER_CONSOLATION:fp,MODIFIED_FEED_IN_CHAMPIONSHIP:xm,FEED_IN_CHAMPIONSHIP_TO_R16:_m,FEED_IN_CHAMPIONSHIP_TO_QF:Om,FEED_IN_CHAMPIONSHIP_TO_SF:vm,FEED_IN_CHAMPIONSHIP:gp,LUCKY_DRAW:Hi,ROUND_ROBIN_WITH_PLAYOFF:Io,ROUND_ROBIN:Un,DECIDER:ZE,BACKDRAW:tU,COMPASS_ATTRIBUTES:lf,OLYMPIC_ATTRIBUTES:ff,DRAW:mn,RANDOM:lp,TOP_DOWN:yn,BOTTOM_UP:Ii,WATERFALL:gi,WIN_RATIO:Vs,ROUND_OUTCOME:Wi,MULTI_STRUCTURE_DRAWS:eU,generatedDrawTypes:dF,stageOrder:Gs,finishOrder:XE,AGGREGATE_EVENT_STRUCTURES:QE,FINISHING_POSITIONS:zE},BC=rU;var De="tournamentRecords",gf="policyDefinitions",Re="tournamentRecord",th="onlineResource",Le="drawDefinition",wm="matchUpFormat",eo="participantId",eh="scheduleDates",HC="tournamentId",WC="scheduleDate",jC="roundNumber",eu="structureId",If="participant",oc="matchUpIds",rh="entryStage",YC="policyType",nU="structures",dn="matchUpId",hf="eventType",ru="inContext",Ip="structure",hp="courtIds",qC="personId",Sp="venueIds",oU="matchUps",nh="courtId",oh="eventId",_n="matchUp",ih="drawId",ho="error",Jo="event",ss="param",$C="uuids",KC="averageMatchUpMinutes",zC="recoveryMinutes",QC="periodLength",XC="number";var zr="object",ir="array";var sr="_validate",sh="_message",wr="_invalid",ar="_ofType",ah="_anyOf",ic="_oneOf";var JC={[hf]:t=>[Hn,Br,Me].includes(t),[th]:t=>qt(Object.keys(t),[ec,rc,nc]).length===3,[rh]:t=>zc.includes(t)},lF={[De]:wt,[Re]:j,[gf]:Zu,[Le]:X,[eo]:ee,[wm]:Bl,[HC]:la,[eu]:hr,[oc]:ns,[If]:Gi,[th]:po,[hf]:Bn,[nU]:Fl,[dn]:er,[Ip]:di,[nh]:Fi,[oU]:Xn,[oh]:Pr,[_n]:dr,[hp]:ot,[Sp]:ot,[ih]:on,[Jo]:bt},fF={[De]:zr,[gf]:zr,[Re]:zr,[Le]:zr,[th]:zr,[eh]:ir,[If]:zr,[oc]:ir,[nU]:ir,[Ip]:zr,[hp]:ir,[Sp]:ir,[oU]:ir,[_n]:zr,[Jo]:zr,[$C]:ir};function nt(t,e,r){if(!t&&!It(t))return{error:k};if(!e?.length||t?._bypassParamCheck)return{valid:!0};if(!Array.isArray(e))return{error:k};let{paramError:n,errorParam:o}=hF(t,e);if(!n)return{valid:!0};let i=t?.[o]===void 0?lF[o]||n[ho]||n[wr]||k:n[sr]&&(n[ho]||n[wr])||k,s=o??(n[ic]&&Object.keys(n[ic]).join(", "));return _({info:{param:s,message:n[sh]},result:{error:i},stack:r})}function ZC(t,e){let r=Object.keys(t),n=Object.keys(e);return qt(r,n)}function gF(t,e){if(!e)return;let r=ZC(t,e);return r.length!==1?{error:k}:r.reduce((n,o)=>({...n,[o]:!0}),{})}function IF(t,e){if(!e)return;let r=ZC(t,e).filter(n=>t[n]);return r.length<1?{error:k}:r.reduce((n,o)=>({...n,[o]:!0}),{})}function hF(t,e){let r,n;return{paramError:e.find(({_ofType:i,_oneOf:s,_anyOf:a,_validate:c,_info:u,...p})=>{let m=s&&gF(t,s);if(m?.error)return m.error;m&&Object.assign(p,m);let d=a&&IF(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&&!Vr(c),h=t[g]!==void 0&&!c&&SF(t,g,i),S=p[g]&&[void 0,null].includes(t[g]),y=I||h||S||c&&t[g]!==void 0&&!TF(t[g],c)||JC[g]&&!JC[g](t[g]);return y&&(r=g,n=u),y});return!l.length||f}),errorParam:r,paramInfo:n}}function SF(t,e,r){return r=r||fF[e]||"string",r==="array"?!Array.isArray(t[e]):typeof t[e]!==r}function TF(t,e){return Vr(e)?e(t):!0}var Lm="DYNAMIC",hi="RANKING",Si="RATING",Ti="SCALE",So="SEEDING",tb={RANKING:hi,RATING:Si,SCALE:Ti,SEEDING:So};function ha(t){let e=nt(t,[{[If]:!0}]);if(e.error)return e;let r=t.participant.timeItems?.filter(({itemType:o})=>o?.startsWith(Ti)&&[hi,Si,So].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===So&&"seedings"||c===hi&&"rankings"||"ratings";n[l][u]||(n[l][u]=[]),n[l][u].push({scaleValue:a.itemValue,scaleDate:a.itemDate,scaleName:d})}}}return{...C,...n}}function ji(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 Fm=/^[\d]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][\d]|3[0-1])$/,ch=/^((0[\d]|1[\d]|2[0-3]):[0-5][\d](:[0-5][\d])?)([.,][0-9]{3})?$/,Mo=/^([\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?$/,Bs=/^([\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 km(t){let{scheduledDate:e}=t;if(!e&&t.scheduledTime&&(e=Dt(t.scheduledTime)),!e)return;let r=Kt(t.scheduledTime),n=Dt(e);return n&&r&&(n+=`T${r}`),n}function eb(t){return typeof t!="object"||Array.isArray(t)?!1:Object.prototype.toString.call(t)==="[object Date]"}function nu(t){let e=typeof t=="string"?t?.split(" "):[];return t&&e?.length>1&&!["AM","PM"].includes(e[1].toUpperCase())?!1:!!(!t||Bs.test(ac(t,!0,!0)))}function Nr(t){return sc(t)||Fm.test(t)}function yF(t){let e=new Date(t),r=e.getSeconds()+60*e.getMinutes()+60*60*e.getHours();return AF(r,{displaySeconds:!1})}function AF(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(ro).join(":")}var yf=t=>{let e=Sf(t)||sc(t)?new Date(t):new Date,r=e.getUTCMonth()+1,n=r<10?`0${r}`:`${r}`;return`${e.getUTCFullYear()}-${ro(n)}-${ro(e.getUTCDate())}`};function EF(t){let e=Sf(t)||sc(t)?new Date(t):new Date;return Date.UTC(e.getFullYear(),e.getMonth(),e.getDate())}function To(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 uh(t){let e=t?new Date(t):new Date,r=e.getTimezoneOffset();return new Date(e.getTime()-r*60*1e3)}function UF(t){return uh(t).getTime()}function Sf(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 Hs(t,e){if(!Nr(t)||!Nr(e))return[];let r=Dt(t)+"T00:00",n=Dt(e)+"T00:00",o=new Date(r),i=new Date(n),s=Sf(i)&&Sf(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=>To(p));function u(p,m){return p<=m}}var DF=/^([+-]?\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 sc(t){return typeof t!="string"?!1:DF.test(t)}function mh(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=Kt(t);if(!e)return 0;let[r,n]=e.split(":").map(o=>parseInt(o));return r*60+n}function rb(t){let e=Math.floor(t/60),r=t-e*60;return e>23&&(e=e%24),[ro(e),ro(r)].join(":")}function Tf(t){return mh(t)?t.split(":").slice(0,2).map(ro).join(":"):void 0}function Kt(t){return sc(t)&&t.indexOf("T")>0?Tf(t.split("T").reverse()[0]):Tf(t)}function Dt(t){return sc(t)||Mo.test(t)?t.split("T")[0]:void 0}function Tp(t,e){let r=new Date(t);return r.setDate(r.getDate()+e),Dt(r.toISOString())}function ph(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 PF(t){let e=ph(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(ro).join(":")}function NF(t){let e=ph(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 ac(t,e,r){let n=Dt(t),o=Kt(t),i=n?o:t;return t?e&&(n&&r&&t||PF(i))||NF(i):void 0}function dh(t,e){let r=ph(t),n=ph(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 nb(t,e=7){let r=Dt(t)+"T00:00",n=new Date(r),o=new Date(n.setDate(n.getDate()+e));return To(o)}function MF(t){return nb(t)}function RF(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())),To(o,r)}function ob(t,e,r){let n=new Date(t,0);return To(new Date(n.setDate(e)),r)}function Fe(t,e=void 0){let[r,n]=(t||"00:00").split(":").map(ro),o=uh(e).setHours(r,n,0,0);return uh(o)}function Sa(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 Hr(t,e){let r=Kt(t);if(!r)return"00:00";let n=isNaN(e)?0:e;return Kt(Af(Fe(r),n).toISOString())}function Af(t,e){let r=new Date(t);return new Date(r.getTime()+e*6e4)}function ro(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 lh={addDays:nb,addWeek:MF,addMinutesToTimeString:Hr,convertTime:ac,getIsoDateString:km,getUTCdateString:yf,DateHHMM:yF,extractDate:Dt,extractTime:Kt,formatDate:To,getDateByWeek:RF,isISODateString:sc,isDate:Sf,isTimeString:mh,offsetDate:uh,offsetTime:UF,sameDay:Wn,timeStringMinutes:Vt,timeToDate:Fe,timeUTC:EF,validTimeValue:nu,validDateString:Fm,timeValidation:Bs,dateValidation:Mo};function J(t,e,r,n,o=0){if(QI().makeDeepCopy)return QI().makeDeepCopy(t,e,r,n);let i=cf(),{stringify:s,toJSON:a,ignore:c,modulate:u}=i||{};if(!i?.enabled&&!r||typeof t!="object"||Vr(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)||Vr(c)&&!c(l)),d=(l,f)=>{p[l]=Vr(f?.toString)?f.toString():JSON.stringify(f)};for(let l of m){let f=t[l],g=Vr(u)?u(f):void 0;if(g!==void 0)p[l]=g;else if(e&&l==="extensions"&&Array.isArray(f)){let I=Ef(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)&&Vr(f?.toJSON)?p[l]=f.toJSON():f===null?p[l]=void 0:eb(f)?p[l]=new Date(f).toISOString():p[l]=J(f,e,r,n,o+1)}return p}function Ef(t){return t?.map(e=>{let{name:r,value:n}=e;return r&&n&&{[`_${r}`]:n}}).filter(Boolean)}var fh="voluntaryConsolation",yi="competitiveBands",Uf="roundRobinTally",yo="positionActions",ze="matchUpActions",Df="rankingPoints",Ta="roundNaming",Ws="participant",ou="progression",Ro="scheduling",iu="avoidance",CF="participant",bF="display",Qr="scoring",xn="seeding",cc="feedIn",vF="audit",Gm="draws",ib={POLICY_TYPE_VOLUNTARY_CONSOLATION:fh,POLICY_TYPE_COMPETITIVE_BANDS:yi,POLICY_TYPE_ROUND_ROBIN_TALLY:Uf,POLICY_TYPE_POSITION_ACTIONS:yo,POLICY_TYPE_MATCHUP_ACTIONS:ze,POLICY_TYPE_RANKING_POINTS:Df,POLICY_TYPE_ROUND_NAMING:Ta,POLICY_TYPE_PARTICIPANT:Ws,POLICY_TYPE_PROGRESSION:ou,POLICY_TYPE_SCHEDULING:Ro,POLICY_TYPE_AVOIDANCE:iu,POLICY_TYPE_DISPLAY:bF,POLICY_TYPE_PRIVACY:CF,POLICY_TYPE_FEED_IN:cc,POLICY_TYPE_SCORING:Qr,POLICY_TYPE_SEEDING:xn,POLICY_TYPE_AUDIT:vF,POLICY_TYPE_DRAWS:Gm};function Bo({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}=ha({participant:a});a.rankings=p,a.ratings=u}if(c?.participant)return ji({template:c.participant,source:a})}return a}var sb="element required",ab="missing name";function ur(t){if(!t||typeof t!="object")return{error:ot};if(t.element&&typeof t?.element!="object")return{error:k};if(!t?.name)return{error:ot,info:ab};if(!t?.element){if(t.discover&&t.tournamentRecords){for(let e of Object.keys(t.tournamentRecords)){let r=t.tournamentRecords[e],n=ur({element:r,name:t.name});if(n.error)return _({result:n,stack:"removeExtension"})}return{...C}}return{error:ot,info:sb}}return t?.element.extensions?(t.element.extensions=t.element.extensions.filter(e=>e?.name!==t.name),{...C}):{...C,info:Pe}}function wn({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 At(t){if(typeof t!="object")return{error:ot};let e="addExtension";if(t?.element&&typeof t.element!="object")return _({result:{error:k},stack:e});if(!wn({extension:t.extension}))return _({result:{error:k,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=At({extension:t.extension,element:o});if(i.error)return _({result:i,stack:e})}return{...C}}else return _({result:{error:ot},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),{...C}}function Pf(t){return!t||typeof t!="object"?{error:ot}:t.tournamentRecord?At({creationTime:t.creationTime,element:t.tournamentRecord,extension:t.extension}):{error:j}}function yp(t){return!t||typeof t!="object"?{error:ot}:t.drawDefinition?At({creationTime:t.creationTime,element:t.drawDefinition,extension:t.extension}):{error:Dr}}function Co(t){return!t||typeof t!="object"?{error:ot}:t.event?At({creationTime:t.creationTime,extension:t.extension,element:t.event}):{error:Pr}}function iU(t){if(!t||typeof t!="object")return{error:ot};if(!t.participantId)return{error:ee};let e=t.tournamentRecord?.participants||[],r=Bo({participantId:t.participantId,tournamentParticipants:e});return r?At({creationTime:t.creationTime,extension:t.extension,element:r}):{error:Xt}}function Nf(t){return!t||typeof t!="object"?{error:ot}:t.tournamentRecord?ur({element:t.tournamentRecord,name:t.name}):{error:j}}function sU(t){return!t||typeof t!="object"?{error:ot}:t.drawDefinition?ur({element:t.drawDefinition,name:t.name}):{error:Dr}}function Ap(t){return!t||typeof t!="object"?{error:ot}:t?.event?ur({element:t.event,name:t.name}):{error:Pr}}function aU(t){if(!t||typeof t!="object")return{error:ot};if(!t.participantId)return{error:ee};let e=t.tournamentRecord?.participants||[],r=Bo({participantId:t.participantId,tournamentParticipants:e});return r?ur({element:r,name:t.name}):{error:Xt}}function Ep({tournamentRecords:t}){return{tournamentIds:It(t)?Object.keys(t):[],...C}}var OF="extensionQueries";function mt({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:Pe}}return _({result:{error:ot},stack:OF})}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:Pe}}var _F="activeSuspension",su="appliedPolicies",cU="context",Vm="delegatedOutcome",no="disabled",ya="disableAutoCalc",Bm="disableLinks",Hm="display",Aa="drawDeletions",xF="drawProfile",Wm="entryProfile",wF="eventProfile",LF="eventWithdrawalRequests",FF="factory",cn="flightProfile",gh="groupingAttribute",bo="lineUps",js="linkedTournamentsIds",jm="matchUpHistory",Ih="participantRepresentatives",Ea="personRequests",Up="positionActions",kF="rankingPoints",GF="registration",Dn="roundTarget",au="scheduleLimits",Ho="scheduleTiming",Ua="schedulingProfile",VF="statusDetail",uc="subOrder",Zo="tally",Ym="tieFormatModification",hh={ACTIVE_SUSPENSION:_F,APPLIED_POLICIES:su,CONTEXT:cU,DELEGATED_OUTCOME:Vm,DISABLED:no,DISABLE_LINKS:Bm,DISABLE_AUTO_CALC:ya,DISPLAY:Hm,DRAW_DELETIONS:Aa,DRAW_PROFILE:xF,ENTRY_PROFILE:Wm,EVENT_PROFILE:wF,EVENT_WITHDRAWAL_REQUESTS:LF,FLIGHT_PROFILE:cn,GROUPING_ATTRIBUTE:gh,LINEUPS:bo,LINKED_TOURNAMENTS:js,MATCHUP_HISTORY:jm,PARTICIPANT_REPRESENTATIVES:Ih,PERSON_REQUESTS:Ea,POSITION_ACTIONS:Up,RANKING_POINTS:kF,REGISTRATION:GF,ROUND_TARGET:Dn,SCHEDULE_LIMITS:au,SCHEDULE_TIMING:Ho,SCHEDULING_PROFILE:Ua,STATUS_DETAIL:VF,SUB_ORDER:uc,TALLY:Zo,TIE_FORMAT_MODIFICATIONS:Ym,FACTORY:FF},uU=[Vm,no,ya,Bm,cn,bo,js,jm,Ih,Ea,Dn,au,Ho,Ua,uc,Zo,Ym];function pU({tournamentRecords:t}){if(typeof t!="object"||!Object.keys(t).length)return{error:wt};let e=Ep({tournamentRecords:t}),{tournamentIds:r}=e;return r?.length>1?At({tournamentRecords:t,discover:!0,extension:{name:js,value:{tournamentIds:r}}}):{...C}}function mU({tournamentRecords:t}){if(typeof t!="object"||!Object.keys(t).length)return{error:wt};let e=ur({name:js,tournamentRecords:t,discover:!0});return _({result:e,stack:"unlinkTournaments"})}function dU({tournamentRecords:t,tournamentId:e}){if(typeof t!="object")return{error:k};if(!e)return{error:la};let r=Ep({tournamentRecords:t}),{tournamentIds:n}=r;if(!n.includes(e))return{error:la};let o;return n.every(i=>{let s=t[i],{extension:a}=mt({element:s,name:js});if(!a)return!0;let c=a?.value?.tournamentIds||[];if(!c?.length||c.length===1&&c.includes(e)||i===e){let m=Nf({name:js,tournamentRecord:s});return m.error&&(o=m.error),m.success}let u=c.filter(m=>m!==e);a.value={tournamentIds:u};let p=Pf({tournamentRecord:s,extension:a});return p.error&&(o=p.error),p.success}),o?{error:o}:{...C}}var fU={};Qt(fU,{getLinkedTournamentIds:()=>cu,getTournamentIds:()=>Ep});function cu({tournamentRecords:t}){return typeof t!="object"||!Object.keys(t).length?{error:wt}:{linkedTournamentIds:Object.assign({},...Object.keys(t).map(r=>{let n=t[r],o=n?.tournamentId,{extension:i}=mt({element:n,name:js}),s=(i?.value?.tournamentIds||[]).filter(a=>a!==o);return{[r]:s}}))}}var _N={};Qt(_N,{adHocPositionSwap:()=>DD,addAdHocMatchUps:()=>vd,addDrawDefinitionTimeItem:()=>Tg,addFinishingRounds:()=>Ra,addGoesTo:()=>Ki,addPlayoffStructures:()=>Yp,addQualifyingStructure:()=>UD,addVoluntaryConsolationStage:()=>SD,addVoluntaryConsolationStructure:()=>pg,allPlayoffPositionsFilled:()=>AS,alternateDrawPositionAssignment:()=>nD,assignDrawPosition:()=>GD,assignDrawPositionBye:()=>kr,attachConsolationStructures:()=>wD,attachPlayoffStructures:()=>bg,attachQualifyingStructure:()=>Sg,attachStructures:()=>vg,autoSeeding:()=>ox,automatedPlayoffPositioning:()=>Dc,automatedPositioning:()=>Uc,checkValidEntries:()=>xd,deleteAdHocMatchUps:()=>VD,drawMatic:()=>Kd,findDrawDefinition:()=>KS,generateAdHocMatchUps:()=>Gu,generateAdHocRounds:()=>$d,generateAndPopulatePlayoffStructures:()=>bd,generateDrawDefinition:()=>Va,generateDrawMaticRound:()=>kd,generateDrawStructuresAndLinks:()=>wd,generateDrawTypeAndModifyDrawDefinition:()=>Ld,generateQualifyingStructure:()=>Dd,generateVoluntaryConsolation:()=>fT,getAssignedParticipantIds:()=>Oi,getAvailableMatchUpsCount:()=>Od,getAvailablePlayoffProfiles:()=>Ru,getDrawDefinitionTimeItem:()=>Oh,getDrawParticipantRepresentativeIds:()=>qS,getDrawStructures:()=>ln,getDrawTypeCoercion:()=>Fu,getEligibleVoluntaryConsolationParticipants:()=>YS,getMatchUpsMap:()=>Ee,getParticipantIdFinishingPositions:()=>$S,getPositionAssignments:()=>qp,getPositionsPlayedOff:()=>Nc,getSeedingThresholds:()=>mS,getSeedsCount:()=>ku,getStructureSeedAssignments:()=>en,getTeamLineUp:()=>ls,getValidGroupSizes:()=>wp,isAdHoc:()=>pr,isCompletedStructure:()=>si,isValidForQualifying:()=>aT,luckyLoserDrawPositionAssignment:()=>rD,modifyDrawDefinition:()=>LD,modifyDrawName:()=>Og,modifySeedAssignment:()=>cD,mutate:()=>WD,positionActions:()=>sT,pruneDrawDefinition:()=>kD,qualifierDrawPositionAssignment:()=>aD,query:()=>tP,removeDrawPositionAssignment:()=>Pu,removeRoundMatchUps:()=>BD,removeSeededParticipant:()=>ED,removeStructure:()=>hD,renameStructures:()=>ID,resetDrawDefinition:()=>FD,resetVoluntaryConsolationStructure:()=>DU,setDrawParticipantRepresentativeIds:()=>hU,setPositionAssignments:()=>iD,setStructureOrder:()=>gD,setSubOrder:()=>HD,shiftAdHocRounds:()=>oD,swapAdHocRounds:()=>sD,swapDrawPositionAssignments:()=>AD,updateTeamLineUp:()=>Qi,withdrawParticipantAtDrawPosition:()=>tD});var WD={};Qt(WD,{adHocPositionSwap:()=>DD,addAdHocMatchUps:()=>vd,addDrawDefinitionTimeItem:()=>Tg,addPlayoffStructures:()=>Yp,addQualifyingStructure:()=>UD,addVoluntaryConsolationStage:()=>SD,addVoluntaryConsolationStructure:()=>pg,alternateDrawPositionAssignment:()=>nD,assignDrawPosition:()=>GD,assignDrawPositionBye:()=>kr,attachConsolationStructures:()=>wD,attachPlayoffStructures:()=>bg,attachQualifyingStructure:()=>Sg,attachStructures:()=>vg,automatedPlayoffPositioning:()=>Dc,automatedPositioning:()=>Uc,deleteAdHocMatchUps:()=>VD,luckyLoserDrawPositionAssignment:()=>rD,modifyDrawDefinition:()=>LD,modifyDrawName:()=>Og,modifySeedAssignment:()=>cD,pruneDrawDefinition:()=>kD,qualifierDrawPositionAssignment:()=>aD,removeDrawPositionAssignment:()=>Pu,removeRoundMatchUps:()=>BD,removeSeededParticipant:()=>ED,removeStructure:()=>hD,renameStructures:()=>ID,resetDrawDefinition:()=>FD,resetVoluntaryConsolationStructure:()=>DU,setDrawParticipantRepresentativeIds:()=>hU,setPositionAssignments:()=>iD,setStructureOrder:()=>gD,setSubOrder:()=>HD,shiftAdHocRounds:()=>oD,swapAdHocRounds:()=>sD,swapDrawPositionAssignments:()=>AD,updateTeamLineUp:()=>Qi,withdrawParticipantAtDrawPosition:()=>tD});var IU=t=>e=>t[e],qm=(t=[])=>t.map(Ie).filter(Boolean),Mf=(t=[])=>t.map(ht).filter(Boolean),ht=(t={})=>IU(t)("participantId");var Ie=(t={})=>IU(t)("matchUpId"),uu=(t={})=>IU(t)("drawId");function hU({representativeParticipantIds:t,drawDefinition:e}){if(!e)return{error:Dr};if(!Array.isArray(t))return{error:k};let r=Mf(e?.entries||[]);return t.length&&qt(t,r).length<t.length?{error:k}:yp({drawDefinition:e,extension:{name:Ih,value:t}})}var Mr="ABANDONED",pc="AWAITING_RESULT",Pt="BYE",oo="CANCELLED",ue="COMPLETED",pu="DEAD_RUBBER",Mt="DEFAULTED",Ce="DOUBLE_DEFAULT",he="DOUBLE_WALKOVER",Ln="IN_PROGRESS",Pn="INCOMPLETE",SU="NOT_PLAYED",Qe="RETIRED",as="SUSPENDED",zt="TO_BE_PLAYED",vt="WALKOVER",cb=[pc,ue,Mt,Ln,Pn,Qe,as],Sh=[pc,ue,Mt,he,Ce,Ln,Pn,Qe,as,vt],Th=[Mr,pc,Pt,oo,ue,pu,Mt,he,Ce,Ln,Pn,SU,Qe,as,zt,vt],yh=[Pt,he,Ce,ue,Mt,Qe,vt],Ah=[Mr,pc,oo,pu,Ln,Pn,SU,as,zt,void 0],ie=[oo,Mr,ue,pu,Mt,he,Ce,Qe,vt],$m=[Mr,ue,Mt,he,Ce,Ln,Qe,vt],Eh=[Ln,Pn,as,zt],Uh={ABANDONED:Mr,AWAITING_RESULT:pc,BYE:Pt,CANCELLED:oo,COMPLETED:ue,DEAD_RUBBER:pu,DEFAULTED:Mt,DOUBLE_WALKOVER:he,DOUBLE_DEFAULT:Ce,IN_PROGRESS:Ln,INCOMPLETE:Pn,NOT_PLAYED:SU,RETIRED:Qe,SUSPENDED:as,TO_BE_PLAYED:zt,WALKOVER:vt};function Ai(t,e,r){let n=m=>mt({element:m,name:Dn})?.extension?.value,o=r?.deprioritizeCompleted,i=r?.mode===QE&&FC,s=r?.mode===zE&&XE,a=s||i||Gs,c=m=>m?.stage===et&&m?.stageSequence===1,u=m=>c(m)?-1:a[m?.stage],p=m=>m?.matchUps.every(({matchUpStatus:d})=>ie.includes(d)?1:-1);return o&&p(t)-p(e)||i&&u(t)-u(e)||(t?.stage&&a[t.stage]||0)-(e?.stage&&a[e.stage]||0)||(n(t)||0)-(n(e)||0)||!s&&!i&&(e?.positionAssignments?.length??1/0)-(t?.positionAssignments?.length??1/0)||(t?.stageSequence??0)-(e?.stageSequence??0)||(Rf(t)||0)-(Rf(e)||0)}function Rf(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 at(t){let e=nt(t,[{[Le]:!0,[eu]:!0}]);if(e.error)return e;let{drawDefinition:r,structureId:n}=t,{structures:o}=ln({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:Lt};let a=s.structureType===dp?i?.find(c=>c.structures?.some(u=>u.structureId===n)):void 0;return{structure:s,containingStructure:a}}function ln({withStageGrouping:t,drawDefinition:e,stageSequences:r,stageSequence:n,roundTarget:o,sortConfig:i,stages:s,stage:a}){let c=!e&&X||!e?.structures&&Fl||void 0;if(c)return{error:c,structures:[],stageStructures:{}};let u=f=>{let g=mt({element:f,name:Dn})?.extension?.value;return!o||o===g},p=e?.structures?.filter(d).filter(l).filter(u).sort((f,g)=>Ai(f,g,i))??[],m=t?Object.assign({},...zc.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 Dh({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(ht).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}=at({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=QA,{positionAssignments:o,error:n}}function le({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 Cf="addDrawDefinition",Dp="addMatchUps",ti="addParticipants",bf="addScaleItems",Ph="addVenue",Ei="audit",Nh="dataIssue",vf="deleteParticipants",Of="deleteVenue",_f="deletedDrawIds",xf="deletedMatchUpIds",wf="modifyDrawDefinition",TU="modifyDrawEntries",yU="modifyEventEntries",Lf="modifyMatchUp",Xe="modifyParticipants",Ff="modifyPositionAssignments",kf="modifySeedAssignments",Yi="modifyTournamentDetail",Ui="modifyVenue",Km="mutations",Mh="publishEvent",AU="publishEventSeeding",EU="publishOrderOfPlay",UU="publishParticipants",Gf="unPublishEvent",Vf="unPublishEventSeeding",Bf="unPublishOrderOfPlay",ub="unPublishParticipants",Pp="updateInContextMatchUp",pb={ADD_DRAW_DEFINITION:Cf,ADD_MATCHUPS:Dp,ADD_PARTICIPANTS:ti,ADD_SCALE_ITEMS:bf,ADD_VENUE:Ph,AUDIT:Ei,DATA_ISSUE:Nh,DELETE_PARTICIPANTS:vf,DELETE_VENUE:Of,DELETED_DRAW_IDS:_f,DELETED_MATCHUP_IDS:xf,MODIFY_DRAW_DEFINITION:wf,MODIFY_DRAW_ENTRIES:TU,MODIFY_EVENT_ENTRIES:yU,MODIFY_MATCHUP:Lf,MODIFY_PARTICIPANTS:Xe,MODIFY_POSITION_ASSIGNMENTS:Ff,MODIFY_SEED_ASSIGNMENTS:kf,MODIFY_TOURNAMENT_DETAIL:Yi,MODIFY_VENUE:Ui,MUTATIONS:Km,PUBLISH_EVENT_SEEDING:AU,PUBLISH_EVENT:Mh,PUBLISH_ORDER_OF_PLAY:EU,PUBLISH_PARTICIPANTS:UU,UNPUBLISH_EVENT_SEEDING:Vf,UNPUBLISH_EVENT:Gf,UNPUBLISH_ORDER_OF_PLAY:Bf,UPDATE_INCONTEXT_MATCHUP:Pp};function Rh(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)}),{...C}}function vo({drawDefinition:t,tournamentId:e,matchUps:r,eventId:n}){return t&&Rh(t),dt({payload:{matchUps:r,tournamentId:e,eventId:n},topic:Dp}),{...C}}function jn({drawDefinition:t,tournamentId:e,matchUpIds:r,eventId:n,action:o}){t&&Rh(t),dt({topic:xf,payload:{tournamentId:e,matchUpIds:r,eventId:n,action:o}});for(let i of r)zI({key:i});return{...C}}function gt({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}),dt({topic:Lf,payload:{matchUp:i,tournamentId:e,context:n},key:i.matchUpId}),{...C}):(console.log(dr),{error:dr})}function mb({tournamentId:t,inContextMatchUp:e}){return e?(dt({payload:{inContextMatchUp:e,tournamentId:t},topic:Pp,key:e.matchUpId}),{...C}):{error:dr}}function Da({tournamentId:t,eventId:e,drawDefinition:r}){return r?(Rh(r),dt({payload:{drawDefinition:r,tournamentId:t,eventId:e},topic:Cf,key:r.drawId}),{...C}):(console.log(X),{error:X})}function db({tournamentId:t,eventId:e,drawId:r}){return dt({payload:{drawId:r,tournamentId:t,eventId:e},topic:_f,key:r}),zI({key:r}),{...C}}function Ot({drawDefinition:t,tournamentId:e,structureIds:r,eventId:n}){return t?(Rh(t,r),dt({payload:{tournamentId:e,eventId:n,drawDefinition:t},topic:wf,key:t.drawId}),{...C}):{error:X}}function Ch({drawDefinition:t,tournamentId:e,structure:r,eventId:n}){if(!t)return{error:X};if(!r)return{error:di};let o=r.seedAssignments,i=r.structureId,s=t.drawId;return dt({payload:{tournamentId:e,eventId:n,drawId:s,structureId:i,seedAssignments:o},topic:kf,key:t.drawId}),Ot({structureIds:[i],drawDefinition:t,tournamentId:e,eventId:n}),{...C}}function Oo({drawDefinition:t,tournamentId:e,structure:r,event:n}){if(!t)return{error:X};if(!r)return{error:di};let o=Ct({structure:r}),i=r.structureId,s=t.drawId,a=n?.eventId;return dt({topic:Ff,payload:{positionAssignments:o,tournamentId:e,structureId:i,eventId:a,drawId:s},key:i}),Ot({structureIds:[i],drawDefinition:t,tournamentId:e,eventId:a}),{...C}}function DU({tournamentRecord:t,drawDefinition:e,resetEntries:r,event:n}){if(!e)return{error:X};let o=e.structures?.find(s=>s.stage===Be);if(!o)return{error:Lt};let i=o.matchUps?.map(({matchUpId:s})=>s)||[];return o.positionAssignments=[],o.seedAssignments=[],o.matchUps=[],jn({tournamentId:t?.tournamentId,action:"resetVoluntaryConsolationStructure",matchUpIds:i,drawDefinition:e}),r&&(e.entries=e.entries.filter(s=>s.entryStage!==Be)),Ot({tournamentId:t?.tournamentId,eventId:n?.eventId,drawDefinition:e,structureIds:[o.structureId]}),{...C}}function zm({drawPositions:t,structure:e}){if([ct,et].includes(e.stage)&&e.stageSequence===1)return;let{positionAssignments:r}=Ct({structure:e});r?.filter(({drawPosition:o})=>t?.includes(o))?.forEach(o=>{At({element:o,extension:{name:Bm,value:!0}})})}function mu(t){let{appliedPolicies:e,positionAction:r,drawDefinition:n}=t;if(e?.audit?.[Up]===!1)return;let{extension:o}=mt({name:Up,element:n}),i=Array.isArray(o?.value)?o?.value??[]:[];if(!i?.length){let a=n.structures.find(c=>c.stage===et);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:Up};At({element:n,extension:s})}function cs({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 Pa="SINGLES",Bt="SINGLES",qi="DOUBLES",kt="DOUBLES",Nn="TEAM",Ht="TEAM",lb={SINGLES_MATCHUP:Pa,SINGLES:Bt,DOUBLES_MATCHUP:qi,DOUBLES:kt,TEAM_MATCHUP:Nn,TEAM:Ht};function du(t){let{sides:e,matchUpType:r}=t||{},n=t.potentialParticipants?.length?t.potentialParticipants.flat().map(s=>r===kt?s?.individualParticipantIds||[]:s.participantId).flat():[],o=(e||[]).map(s=>r===kt&&(s?.participant?.individualParticipantIds||[])||s?.participantId&&[s.participantId]||[]).flat();return{individualParticipantIds:o.concat(n).flat(),enteredIndividualParticipantIds:o,potentialIndividualParticipantIds:n}}function Tr(t){return t?.tournamentRecords??(t?.tournamentRecord&&{[t.tournamentRecord.tournamentId]:t.tournamentRecord})??{}}var mc="SIGN_IN_STATUS",PU="SIGNED_OUT",lu="SIGNED_IN",fn="TEAM",Tt="INDIVIDUAL",Rr="GROUP",lt="PAIR",Ft="TEAM",fu={TEAM_PARTICIPANT:fn,INDIVIDUAL:Tt,GROUP:Rr,TEAM:Ft,PAIR:lt},fb={INDIVIDUAL:Tt,GROUP:Rr,PAIR:lt,TEAM:Ft,SIGN_IN_STATUS:mc,SIGNED_OUT:PU,SIGNED_IN:lu};function Qm({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===Ft),s=o.filter(c=>c.participantType===Rr),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 NU(t){return t&&typeof String.fromCodePoint<"u"?t.toUpperCase().replace(/./g,e=>String.fromCodePoint(e.charCodeAt(0)+127397)):t}function gb(t){let e=Object.assign({},...ei.filter(r=>r.ioc).map(r=>({[r.ioc]:r.iso})));return NU(e[t])}var ei=[{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 bh({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=ei.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 Ib({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?ji({template:e,source:s}):s)}}}}function Ao(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:Xt}}function vh(t){let{tournamentRecord:e,participantId:r}=t;if(r){let o=Ao({tournamentRecord:e,participantId:r});return o.participant??o}let n=t.element||t.drawDefinition||t.event||t.tournamentRecord;return n||{error:ot}}function Xr(t){let{returnPreviousValues:e,itemSubTypes:r,itemType:n}=t,o=vh(t);if(o.error)return o;if(r&&!Array.isArray(r))return{error:k,context:{itemSubTypes:r}};if(!Array.isArray(o.timeItems))return{error:Zl};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,...C};return e&&Object.assign(a,{previousItems:i}),a}else return{info:Pe}}function Oh({returnPreviousValues:t,drawDefinition:e,itemSubTypes:r,itemType:n}){if(!e)return{error:on};if(!e.timeItems)return{info:Pe};let{timeItem:o,previousItems:i,info:s}=Xr({element:e,returnPreviousValues:t,itemSubTypes:r,itemType:n});return o&&{timeItem:o,previousItems:i}||{info:s}}function gu({returnPreviousValues:t,itemSubTypes:e,itemType:r,event:n}){if(!n)return{error:bt};if(!n.timeItems)return{info:Pe};let{timeItem:o,previousItems:i,info:s}=Xr({returnPreviousValues:t,element:n,itemSubTypes:e,itemType:r});return o&&{timeItem:o,previousItems:i}||{info:s}}function Xm({returnPreviousValues:t,tournamentRecord:e,itemSubTypes:r,itemType:n}){if(!e)return{error:j};if(!e.timeItems)return{info:Pe};let{timeItem:o,previousItems:i,info:s}=Xr({element:e,returnPreviousValues:t,itemSubTypes:r,itemType:n});return o&&{timeItem:o,previousItems:i}||{info:s}}function _h({returnPreviousValues:t,tournamentRecord:e,participantId:r,itemSubTypes:n,itemType:o}){if(!e)return{error:j};if(!r)return{error:ee};let i=Ao({tournamentRecord:e,participantId:r});if(i.error)return i;let{participant:s}=i;if(!s?.timeItems)return{info:Pe};let{timeItem:a,previousItems:c,info:u}=Xr({element:i.participant,returnPreviousValues:t,itemSubTypes:n,itemType:o});return a&&{timeItem:a,previousItems:c}||{info:u}}var BF={[Rr]:"groupParticipantIds",[lt]:"pairParticipantIds",[Ft]:"teamParticipantIds"},HF={[Rr]:"groups",[Ft]:"teams"};function xh({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&&YF({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&&jF({individualParticipantIds:d,participantCopy:p,participantMap:c,participantType:l,participantId:m}),n&&(c[m].participant.signedIn=WF(p)),o){let{ratings:f,rankings:g,seedings:I}=ha({participant:p});c[m].participant.seedings=I,c[m].participant.rankings=g,c[m].participant.ratings=f}(a||s)&&bh({participant:c[m].participant,withISO2:s,withIOC:a})}if(t){let u=It(t)?t:void 0;Ib({participantMap:c,template:u})}return{participantMap:c}}function WF(t){let{timeItem:e}=Xr({itemType:mc,element:t});return e?.itemValue===lu}function jF({individualParticipantIds:t,participantCopy:e,participantMap:r,participantType:n,participantId:o}){for(let i of t){let s=r[i].participant;if(s[BF[n]].push(o),[Ft,Rr].includes(n)){let{participantRoleResponsibilities:a,participantOtherName:c,participantName:u,participantId:p,teamId:m}=e,d=HF[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 YF({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:{[Bt]:{...r},[kt]:{...r},[Ft]:{...r},...r}}}function Di({participantsProfile:t,useParticipantMap:e,tournamentRecord:r,contextProfile:n,inContext:o}){if(e)return{participantMap:xh({...t,...n,tournamentRecord:r})?.participantMap};let i=J(r.participants,!1,!0)||[];(t?.withIOC||t?.withISO2)&&i.forEach(a=>bh({participant:a,...t}));let s;if((o||t?.withGroupings)&&i?.length&&({participantsWithGroupings:i,groupInfo:s}=Qm({participantsProfile:t,deepCopy:!1,participants:i})),t?.withScaleValues&&i?.length)for(let a of i){let{ratings:c,rankings:u}=ha({participant:a});a.rankings=u,a.ratings=c}return{participants:i,groupInfo:s}}function yt({onlySpecifiedPolicyTypes:t=!1,policyTypes:e=[],tournamentRecord:r,drawDefinition:n,structure:o,event:i}){if(!Array.isArray(e))return{error:wI};let s={};return r&&a(r),i&&a(i),n&&a(n),o&&a(o),{appliedPolicies:s,...C};function a(c){let p=c?.extensions?.find(m=>m.name===su)?.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 _o({policyTypes:t=[],tournamentRecord:e,drawDefinition:r,structure:n,event:o}){if(!Array.isArray(t))return{error:wI};let{appliedPolicies:i}=yt({tournamentRecord:e,drawDefinition:r,structure:n,event:o}),s={};for(let a of t){let c=i?.[a];c&&(s[a]=c)}return Object.keys(s).length?{policyDefinitions:s}:{info:Wc.message}}var wh="WALKOVER",MU="RETIRED",Jm="COMPETITIVE",dc="ROUTINE",lc="DECISIVE",Zm="winRatio";var qF={[yi]:{policyName:"Competitive Bands Default",profileBands:{[lc]:20,[dc]:50}}},td=qF;function Yn({policyDefinitions:t,tournamentRecord:e,contextProfile:r,drawDefinition:n,event:o}){let i={policies:{}};if(!r)return i;let s=_o({tournamentRecord:e,drawDefinition:n,event:o}).policyDefinitions;if(r.withCompetitiveness){let a=t?.[yi]??s?.[yi]??td[yi];i.policies[yi]=a}return i}function ri({tournamentRecord:t,drawDefinition:e,policyType:r,structure:n,event:o}){if(!t)return{error:j};let{appliedPolicies:i}=yt({tournamentRecord:t,drawDefinition:e,structure:n,event:o});return i?.[r]?{policy:i[r]}:{info:Wc?.message}}function Na({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}=ri({policyType:Ro,tournamentRecord:t,event:n}),s=(t?mt({element:t,name:Ho}).extension:void 0)?.value,c=(n&&mt({name:Ho,element:n}).extension)?.value;return{scheduleTiming:{tournamentScheduling:s,eventScheduling:c,categoryName:e,categoryType:r,policy:o}}}function Hf({drawDefinition:t,attributes:e}){let{extension:r}=mt({element:t,name:Wm}),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:Wm,value:n},yp({drawDefinition:t,extension:r}),{entryProfile:n}}function Iu({drawDefinition:t}){let{extension:e}=mt({element:t,name:Wm});return{entryProfile:e?.value||{}}}var Jr="ALTERNATE",Wf="CONFIRMED",Zr="DIRECT_ACCEPTANCE",ed="FEED_IN",jf="JUNIOR_EXEMPT",us="LUCKY_LOSER",Yf="ORGANISER_ACCEPTANCE",rd="QUALIFIER",$F="REGISTERED",qf="SPECIAL_EXEMPT",tn="UNGROUPED",Pi="UNPAIRED",hu="WILDCARD",io="WITHDRAWN",$f=[Wf,Zr,jf,Yf,qf],RU=[ed,us,rd],ni=[Wf,Zr,ed,jf,Yf,qf,hu],Wr=[Wf,Zr,jf,us,rd,Yf,qf,hu],CU=[Jr,Wf,Zr,ed,jf,us,Yf,rd,$F,qf,tn,Pi,hu,io],hb={ALTERNATE:Jr,CONFIRMED:Wf,DIRECT_ACCEPTANCE:Zr,DIRECT_ENTRY_STATUSES:ni,DRAW_SPECIFIC_STATUSES:RU,EQUIVALENT_ACCEPTANCE_STATUSES:$f,FEED_IN:ed,JUNIOR_EXEMPT:jf,LUCKY_LOSER:us,ORGANISER_ACCEPTANCE:Yf,QUALIFIER:rd,SPECIAL_EXEMPT:qf,STRUCTURE_SELECTED_STATUSES:Wr,UNGROUPED:tn,UNPAIRED:Pi,VALID_ENTRY_STATUSES:CU,WILDCARD:hu,WITHDRAWN:io};function Kf({stage:t,drawDefinition:e}){let{entryProfile:r}=Iu({drawDefinition:e}),n=Object.keys(r).includes(t);if(!n&&zc.includes(t)){let o=[{[t]:{drawSize:void 0,alternates:!0}}];return Hf({drawDefinition:e,attributes:o}),!0}return n}function Sb({stage:t,drawDefinition:e}){let{entryProfile:r}=Iu({drawDefinition:e});return r[t]?.alternates||0}function Tb({stage:t,drawDefinition:e}){let{entryProfile:r}=Iu({drawDefinition:e});return r[t]?.wildcardsCount||0}function Lh({stage:t,drawDefinition:e,entryStatus:r}){return e.entries.reduce((n,o)=>o.entryStage===t&&o.entryStatus===r?n+1:n,0)}function Ni({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=mt({name:Dn,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===pe){let{playoffEntries:p,error:m}=KF({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 KF({provisionalPositioning:t,drawDefinition:e,structureId:r}){let n=[],o=(e.links??[]).find(i=>i.linkType===Jn&&i.target.structureId===r);if(o){let{finishingPositions:i,structureId:s}=o.source,{structure:a}=at({drawDefinition:e,structureId:s});a?.structureType===we&&(a.structures??[]).forEach(u=>{let p=u.positionAssignments??[],{structureId:m}=u,d=m,l=Object.assign({},...p.map(h=>{let{participantId:S}=h,T=mt({element:h,name:Zo}).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:D}=S,U=T||t&&y,A=[...i??[]].sort(ae).indexOf(U)+1;n.push({entryStage:pe,entryStatus:ed,placementGroup:A,groupingValue:d,participantId:h,GEMscore:D})})})}return{playoffEntries:n}}function yb({stage:t,drawDefinition:e}){return ni.reduce((r,n)=>(Lh({drawDefinition:e,entryStatus:n,stage:t})||0)+r,0)}function en({provisionalPositioning:t,returnAllProxies:e,drawDefinition:r,structureId:n,structure:o}){let i,s=[];o||({structure:o,error:i}=at({drawDefinition:r,structureId:n}));let a=Ct({structure:o}).positionAssignments;if(i||!o)return{seedAssignments:[],error:Lt};n||(n=o.structureId);let{stage:c,stageSequence:u}=o,m=c===pe&&r&&Ni({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=VA;let f=o.seedLimit??o?.positionAssignments?.length;return{seedAssignments:s,stageSequence:u,seedLimit:f,stage:c,error:i}}var zF=(t,e)=>(t||0)+(e||0);function Fh(t,e){let r=Array.isArray(t)?t[0]:t;return isNaN(r)&&wh||r<=e[lc]&&lc||r<=e[dc]&&dc||Jm}function kh({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(zF)&&(r[n[0]>n[1]?0:1]+=1),{sets:e,games:r,score:t}}function QF(t){let e=Math.min(...t.games),r=Math.max(...t.games);return Math.round(e/r*100)}function Gh(t){return t.map(QF).sort().map(e=>parseFloat(e.toFixed(2)))}function Su({tournamentRecord:t,profileBands:e,matchUp:r}){if(!r)return{error:dr};let{score:n,winningSide:o}=r;if(!o)return{error:k};let i=!e&&t&&ri({policyType:yi,tournamentRecord:t}).policy,s=e||i?.profileBands||td[yi].profileBands,a=kh({score:n}),c=Gh([a]),u=Fh(c,s),p=Array.isArray(c)?c[0]:c;return{...C,competitiveness:u,pctSpread:p}}function Vh({matchUp:t}){if(!t)return{error:dr};if(t&&!t.sides)return{error:or};if(t&&!t.hasContext)return{error:Yc};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,...C}}var nd="CHECK_IN",od="CHECK_OUT",Ab="SCHEDULE",Ys="SCHEDULE.ASSIGNMENT.VENUE",xo="SCHEDULE.ALLOCATION.COURTS",Mi="SCHEDULE.ASSIGNMENT.COURT",Np="SCHEDULE.COURT.ORDER",qs="SCHEDULE.DATE",XF="COMPLETED.DATE",Bh="HOME_PARTICIPANT_ID",bU="SCHEDULE.ASSIGN.OFFICIAL",$s="SCHEDULE.TIME.SCHEDULED",wo="SCHEDULE.TIME.START",$i="SCHEDULE.TIME.STOP",Ri="SCHEDULE.TIME.RESUME",Ci="SCHEDULE.TIME.END",zf="SCHEDULE.TIME.MODIFIERS",Eb="TO_BE_ANNOUNCED",Ub="NEXT_AVAILABLE",Db="FOLLOWED_BY",Pb="AFTER_REST",Nb="RAIN_DELAY",JF="NOT_BEFORE",Hh=[Eb,Ub,Db,Pb,Nb],ZF="ELIGIBILITY",tk="REGISTRATION",ek="SUSPENSION",rk="MEDICAL",nk="PENALTY",vU="SCALE",OU="RATING",_U="RANKING",Qf="SEEDING",Lo="PUBLISH",yr="PUBLIC",Fo="STATUS",ok="MODIFICATION",ik="RETRIEVAL",sk="other",Mb={MUTUALLY_EXCLUSIVE_TIME_MODIFIERS:Hh,AFTER_REST:Pb,ALLOCATE_COURTS:xo,ASSIGN_COURT:Mi,ASSIGN_OFFICIAL:bU,ASSIGN_VENUE:Ys,CHECK_IN:nd,CHECK_OUT:od,COMPLETED_DATE:XF,COURT_ORDER:Np,ELIGIBILITY:ZF,END_TIME:Ci,FOLLOWED_BY:Db,MEDICAL:rk,MODIFICATION:ok,NEXT_AVAILABLE:Ub,NOT_BEFORE:JF,OTHER:sk,PENALTY:nk,PUBLIC:yr,PUBLISH:Lo,RANKING:_U,RATING:OU,RAIN_DELAY:Nb,REGISTRATION:tk,RESUME_TIME:Ri,RETRIEVAL:ik,SCALE:vU,SCHEDULE:Ab,SCHEDULED_DATE:qs,SCHEDULED_TIME:$s,SEEDING:Qf,START_TIME:wo,STATUS:Fo,STOP_TIME:$i,SUSPENSION:ek,TIME_MODIFIERS:zf,TO_BE_ANNOUNCED:Eb};function ps({matchUp:t}){if(!t)return{error:dr};if(!t.hasContext)return{error:Yc};if(!t.sides||t.sides.filter(Boolean).length!==2)return{error:or};let{nestedIndividualParticipantIds:e,allRelevantParticipantIds:r,sideParticipantIds:n}=Vh({matchUp:t}),i=(t.timeItems??[]).filter(u=>u?.itemType&&[nd,od].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===nd);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,...C}}var Wh={[Bt]:[Bt,"S"],[kt]:[kt,"D"],[Ht]:[Ht,"T"],S:[Bt,"S"],D:[kt,"D"],T:[Ht,"T"]};var se=t=>e=>{let r=It(e)&&e?.matchUpType||te(e)&&e;return r&&Wh[t].includes(r)};function Mp(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 Rp(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 jh({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 Rb({tournamentScheduling:t,eventScheduling:e,averageMinutes:r,defaultTiming:n,matchUpFormat:o,categoryName:i,categoryType:s,policy:a}){let c=e?.matchUpRecoveryTimes&&Rp({...e,averageMinutes:r,matchUpFormat:o}),u=t?.matchUpRecoveryTimes&&Rp({...t,averageMinutes:r,matchUpFormat:o}),p=a?.matchUpRecoveryTimes&&Rp({...a,averageMinutes:r,matchUpFormat:o}),m=[c,u,p,a?.defaultTimes?.recoveryTimes,n?.recoveryTimes];return jh({categoryName:i,categoryType:s,timesBlockArray:m})}function Cb({matchUpFormat:t,categoryName:e,categoryType:r,defaultTiming:n,tournamentScheduling:o,eventScheduling:i,policy:s}){let a=i?.matchUpAverageTimes&&Mp({...i,matchUpFormat:t}),c=o?.matchUpAverageTimes&&Mp({...o,matchUpFormat:t}),u=s?.matchUpAverageTimes&&Mp({...s,matchUpFormat:t}),p=[a,c,u,s?.defaultTimes?.averageTimes,n?.averageTimes];return jh({categoryName:e,categoryType:r,timesBlockArray:p})}var xU="DOUBLES_SINGLES",wU="SINGLES_DOUBLES",so="total",Yh="participantConflict",Ma="matchUpConflict",LU="ISSUE_IDS",fc="CONFLICT",gc="WARNING",qh="ERROR",$h="ISSUE",Xf="STATE",bb={SINGLES_DOUBLES:wU,DOUBLES_SINGLES:xU,TOTAL:so,CONFLICT_MATCHUP_ORDER:Ma,CONFLICT_PARTICIPANTS:Yh,SCHEDULE_ISSUE_IDS:LU,SCHEDULE_CONFLICT:fc,SCHEDULE_WARNING:gc,SCHEDULE_ERROR:qh,SCHEDULE_ISSUE:$h,SCHEDULE_STATE:Xf};function Tu({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??ks;let c={averageTimes:[{minutes:{default:t}}],recoveryTimes:[{minutes:{default:e}}]},{scheduleTiming:u}=Na({tournamentRecord:r,categoryName:o,categoryType:i,event:a}),p={...u,matchUpFormat:n,categoryType:i,defaultTiming:c};return Cp({eventType:s,timingDetails:p})}function Cp({timingDetails:t,eventType:e}){let r=Cb(t),n=Object.keys(r?.minutes||{}),o=r?.minutes&&(n?.includes(e)&&r.minutes[e]||r.minutes.default),i=Rb({...t,averageMinutes:o}),s=Object.keys(i?.minutes||{}),a=i?.minutes&&(s?.includes(e)&&i.minutes[e]||i.minutes.default),c=se(ks)(e)?wU:xU,u=i?.minutes&&(s?.includes(c)&&i.minutes[c]||a);return{averageMinutes:o,recoveryMinutes:a,typeChangeRecoveryMinutes:u}}function Kh(t){return t.createdAt?new Date(t.createdAt).getTime():0}function Eo({visibilityThreshold:t,timeItems:e,itemType:r}){let n=e.filter(i=>i&&i.itemType===r&&(!t||Kh(i)<new Date(t).getTime())).sort((i,s)=>Kh(i)-Kh(s)).pop(),o=n&&Kh(n);return{itemValue:n?.itemValue,timeStamp:o}}function Jf({visibilityThreshold:t,timeStamp:e,schedule:r,matchUp:n}){let{itemValue:o,timeStamp:i}=Eo({timeItems:n?.timeItems||[],itemType:$s,visibilityThreshold:t});return!r||i&&e&&new Date(i).getTime()>new Date(e).getTime()?{scheduledTime:o}:r}function ms({visibilityThreshold:t,timeStamp:e,schedule:r,matchUp:n}){let{itemValue:o,timeStamp:i}=Eo({timeItems:n?.timeItems||[],itemType:qs,visibilityThreshold:t});return!r||i&&e&&new Date(i).getTime()>new Date(e).getTime()?{scheduledDate:o}:r}function zh({visibilityThreshold:t,timeStamp:e,schedule:r,matchUp:n}){let{itemValue:o,timeStamp:i}=Eo({timeItems:n?.timeItems||[],itemType:xo,visibilityThreshold:t});return!r||i&&e&&new Date(i).getTime()>new Date(e).getTime()?{allocatedCourts:J(o,!1,!0)}:r}function Qh({visibilityThreshold:t,timeStamp:e,schedule:r,matchUp:n}){let{itemValue:o,timeStamp:i}=Eo({timeItems:n?.timeItems||[],itemType:Mi,visibilityThreshold:t});return!r||i&&e&&new Date(i).getTime()>new Date(e).getTime()?{courtId:o}:r}function Xh({visibilityThreshold:t,timeStamp:e,schedule:r,matchUp:n}){let{itemValue:o,timeStamp:i}=Eo({timeItems:n?.timeItems||[],itemType:Ys,visibilityThreshold:t});return!r||i&&e&&new Date(i).getTime()>new Date(e).getTime()?{venueId:o}:r}function Zf({visibilityThreshold:t,timeStamp:e,schedule:r,matchUp:n}){let{itemValue:o,timeStamp:i}=Eo({timeItems:n?.timeItems||[],itemType:zf,visibilityThreshold:t});return!r||i&&e&&new Date(i).getTime()>new Date(e).getTime()?{timeModifiers:o}:r}function bp(t){if(ch.test(t)){let e=yf();return new Date(`${e}T${t}`)}else return new Date(t)}function vb({matchUp:t}){if(!t)return{error:dr};if(!t.timeItems)return{error:Zl};let e=t.timeItems.filter(n=>[wo,$i,Ri,Ci].includes(n?.itemType)).sort((n,o)=>bp(n.itemValue).getTime()-bp(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 wo:i=0;break;case Ci:if(n.lastValue&&[wo,Ri].includes(n.lastType)){let u=bp(o.itemValue).getTime()-bp(n.lastValue).getTime();i=n.milliseconds+u}else i=n.milliseconds;break;case $i:if([wo,"SCHECULE.TIME.RESUME"].includes(n.lastType)){let u=bp(o.itemValue).getTime()-bp(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([wo,Ri].includes(r.lastType)){let n=new Date().getTime()-bp(r.lastValue).getTime();r.milliseconds+=n}return{milliseconds:r.milliseconds,time:ak(r.milliseconds),relevantTimeItems:e}}function ak(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 Ob({visibilityThreshold:t,timeStamp:e,schedule:r,matchUp:n}){let{itemValue:o,timeStamp:i}=Eo({timeItems:n?.timeItems||[],itemType:Np,visibilityThreshold:t});return!r||i&&e&&new Date(i).getTime()>new Date(e).getTime()?{courtOrder:o}:r}function _b({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===wo&&s;return a&&(!i||r(a)<r(i))?a:i},void 0)?.itemValue}}function xb(t=1){return tt(0,t).map(Nt)}function Nt(){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 Ic(t){let{disableNotice:e,venue:r,context:n}=t;if(typeof r!="object")return{error:k};let o=Tr(t);r.venueId||(r.venueId=Nt());let i;for(let s of Object.values(o)){let a=ck({disableNotice:!0,tournamentRecord:s,context:n,venue:r});if(a?.error)return a;i=a.venue}return e||dt({topic:Ph,payload:{venue:r}}),rt({...C,venue:i})}function ck({tournamentRecord:t,disableNotice:e,context:r,venue:n}){return t?n?(t.venues||(t.venues=[]),n.venueId||(n.venueId=Nt()),t.venues.reduce((i,s)=>i||s.venueId===n.venueId,void 0)?{error:AE}:(r&&At({element:n,extension:{value:r,name:cU}}),t.venues.push(n),e||dt({payload:{venue:n,tournamentId:t.tournamentId},topic:Ph}),{...C,venue:J(n)})):{error:ot,info:"missing venue"}:{error:j}}function Wo({tournamentRecords:t,tournamentRecord:e,venueId:r}){if(!e)return{error:j};if(!r)return{error:Xo};let o=(e.venues??[]).reduce((i,s)=>s.venueId===r?s:i,void 0);if(!o&&t){let s=(cu({tournamentRecords:t}).linkedTournamentIds??[])[e.tournamentId];for(let a of s){let c=t[a],u=Wo({tournamentRecord:c,venueId:r});if(u.success&&u.venue)return Ic({tournamentRecord:e,venue:u.venue}),{...C,venue:o}}}return o?{...C,venue:o}:{error:Vi}}function Jh({convertExtensions:t,...e}){let{tournamentRecords:r,tournamentRecord:n,venueId:o}=e,i=Wo({tournamentRecords:r,tournamentRecord:n,venueId:o});return J(i,t,!0)}function ds({tournamentRecords:t,tournamentRecord:e,courtId:r}){if(!e)return{error:j};if(!r)return{error:Fi};let n="findCourt",o,i;if((e.venues??[]).forEach(s=>{(s.courts??[]).forEach(a=>{a.courtId===r&&(o=a,i=s)})}),o)return{...C,court:o,venue:i};if(t){let a=(cu({tournamentRecords:t}).linkedTournamentIds??[])[e.tournamentId];for(let c of a){let u=t[c],p=ds({tournamentRecord:u,courtId:r});if(p.success)return p.venue&&Ic({tournamentRecord:e,venue:p.venue}),{...C,court:o,venue:i}}}return _({result:{error:Ls},stack:n})}function Zh(t){return J(ds(t),!1,!0)}function id({tournamentRecord:t,internalUse:e,courtId:r}){if(!t)return{error:j};if(!r)return{error:Fi};let n=ds({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{...C,courtInfo:J(o,!1,e)}}function hc({tournamentRecord:t,venueId:e}){if(!t)return{error:j};if(!e)return{error:Xo};let r=Wo({tournamentRecord:t,venueId:e});if(r.error)return r;let o=(r.venue?.courts??[]).map(a=>(({courtInfo:c})=>({...c}))(id({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{...C,venueData:J(s,!1,!0)}}function wb({matchUp:t}){let e=t?.timeItems||[],r=i=>i.createdAt?new Date(i.createdAt).getTime():0;return{endTime:e.reduce((i,s)=>{let a=s.itemType===Ci&&s;return a&&(!i||r(a)>r(i))?a:i},void 0)?.itemValue}}function Wt({event:t,eventId:e}){if(!t)return{error:bt};let n=mt({name:cn,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 He(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&&Wt({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:Pr},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 sd(t){let{visibilityThreshold:e,timeStamp:r,schedule:n,matchUp:o}=t,i=nt(t,[{[_n]:!0}]);if(i.error)return i;let{itemValue:s,timeStamp:a}=Eo({timeItems:o?.timeItems||[],itemType:Bh,visibilityThreshold:e});return!n||a&&r&&new Date(a).getTime()>new Date(r).getTime()?{homeParticipantId:s}:n}function ad(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:dr};if(o&&!p.matchUpType&&!t.matchUpType&&(e||i)&&p.drawId){let A=e?.drawDefinitions?.find(M=>M.drawId===p.drawId);!A&&i&&({drawDefinition:A,event:e}=He({tournamentRecord:i,drawId:p.drawId}));let E=p.structureId&&A?.structures?.find(({structureId:M})=>M===p.structureId);r=t.matchUpType||E?.matchUpType||A?.matchUpType||e?.eventType!==Me&&e?.eventType}let{milliseconds:m,time:d}=vb({matchUp:p}),{startTime:l}=_b({matchUp:p}),{endTime:f}=wb({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:E}=zh(A),{homeParticipantId:M}=sd(A),{scheduledTime:P}=Jf(A),{timeModifiers:N}=Zf(A),{scheduledDate:R}=ms(A),{venueId:b}=Xh(A),{courtId:v}=Qh(A),{courtOrder:O}=Ob(A),x,F,L,w,B,G=p.matchUpType??r;if(a&&P&&o&&G){let Z={matchUpFormat:p.matchUpFormat??c,...a};({averageMinutes:F=0,recoveryMinutes:L=0,typeChangeRecoveryMinutes:w=0}=Cp({timingDetails:Z,eventType:G})),(F||L)&&(x=f?Hr(Kt(f),L):Hr(P,F+L)),w&&(B=f?Hr(Kt(f),w):Hr(P,F+w))}!R&&P&&(R=Dt(P));let W=km({scheduledDate:R,scheduledTime:P}),H={},q=(i&&b&&hc({tournamentRecord:i,venueId:b}))?.venueData||{};b&&(H[b]=q);let{venueName:$,venueAbbreviation:V,courtsInfo:K}=q,Y=(v&&K?.find(Z=>Z.courtId===v))?.courtName;for(let Z of E||[]){if(!i)break;Z.venueId&&!H[Z.venueid]&&(H[Z.venueId]=hc({venueId:Z.venueId,tournamentRecord:i})?.venueData);let Q=H[Z.venueId];Z.venueName=Q?.venueName;let st=Q?.courtsInfo?.find(St=>St.courtId===Z.courtId);Z.courtName=st?.courtName}g=rt({typeChangeTimeAfterRecovery:B,timeAfterRecovery:x,scheduledDate:R,scheduledTime:P,isoDateString:W,allocatedCourts:E,homeParticipantId:M,timeModifiers:N,venueAbbreviation:V,venueName:$,venueId:b,courtOrder:O,courtName:Y,courtId:v,typeChangeRecoveryMinutes:w,recoveryMinutes:L,averageMinutes:F,milliseconds:m,startTime:l,endTime:f,time:d})}else g=rt({milliseconds:m,startTime:l,endTime:f,time:d});let{scheduledDate:T}=ms({matchUp:p}),{scheduledTime:y}=Jf({matchUp:p});if(s&&u?.displaySettings?.draws){let A=u.displaySettings.draws,E=(A?.[p.drawId]??A?.default)?.scheduleDetails;if(E){let M=(E.find(P=>T&&P.dates?.includes(T))??E.find(P=>!P.dates?.length))?.attributes;if(M){let P=Object.assign({},...Object.keys(g).map(N=>({[N]:!0})),M);g=ji({source:g,template:P})}}}let U=p.matchUpStatus&&ie.includes(p.matchUpStatus)&&(Dt(f)||Dt(T)||Dt(y))||void 0;return{schedule:g,endDate:U}}function oi(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 vp({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 We({drawDefinition:t,structure:e,matchUp:r,event:n}){return{tieFormat:vp({item:r,drawDefinition:t,structure:e,event:n})||vp({item:e,drawDefinition:t,structure:e,event:n})||oi(t)||oi(n)}}function Lb({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 Ee({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 ii({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 tS({groupedOrder:t,roundPositionsCount:e}){if(!t||t?.length<=e)return t;let n=Ae(t,t.length/e).map(i=>i.reduce((s,a)=>s+a)),o=n.slice().sort(ae);return n.map(i=>o.indexOf(i)+1)}function tg(t){if(!It(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 Lr(t){return Array.isArray(t)?t.every(tg):!1}function je({matchUps:t=[],interpolate:e}){if(!Lr(t))return{roundMatchUps:[],error:k};let r=t.reduce((d,l)=>{let f=typeof l.roundNumber=="string"?ut(l.roundNumber):l.roundNumber;return!l.roundNumber||d.includes(f)?d:d.concat(f)},[]).sort(ae).map(d=>{let l=t.filter(h=>h.roundNumber===d),g=l.find(({matchUpType:h})=>h===Ht)?l.filter(({matchUpType:h})=>h===Ht):l,I=h=>h.sort((S,T)=>ae(S.roundPosition,T.roundPosition));return{[d]:I(g)}}),n=t.reduce((d,l)=>{let f=typeof l.roundNumber=="string"?ut(l.roundNumber):l.roundNumber;return d[f]||(d[f]=rt({abbreviatedRoundName:l.abbreviatedRoundName,finishingRound:l.finishingRound,roundName:l.roundName})),d},{}),o=Object.assign({},...r);if(e){let d=Math.max(...Object.keys(o).map(f=>ut(f)).filter(f=>!isNaN(f))),l=o[d]?.length;if(l>1&&On(l)){let f=d+1,g=f+l/2;tt(f,g).forEach((h,S)=>{o[h]=tt(0,l/(2+S*2)).map(()=>({}))})}}let i=0,s=Object.assign({},...Object.keys(o).map(d=>{let l=o[d]?.length,f=o[d]?.filter(I=>!ie.includes(I.matchUpStatus)&&!I.score?.scoreStringSide1)?.length,g=l&&l===f;return i=Math.max(i,l),{[d]:{matchUpsCount:l,inactiveCount:f,inactiveRound:g}}})),a=0,c=0,u=Object.keys(o).map(d=>ut(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(ae),I=Ae(g,2);s[d].drawPositions=g,s[d].pairedDrawPositions=I}else{let g=s[d-1],I=g.drawPositions,h=g.matchUpsCount/s[d].matchUpsCount,S=Ae(I,h),T=l.map(y=>{let{roundPosition:D}=y,U=[...y.drawPositions||[],void 0,void 0].slice(0,2);if(!D)return U;let A=U?.filter(Boolean)||[];if(!A?.length)return[void 0,void 0];if(d<3&&A?.length===2)return U?.slice().sort(ae);let E=qt(I,A).length!==A?.length;if(A?.length&&E)return A?.length===1?[A[0],void 0]:U?.slice().sort(ae);let M=(D-1)*2;return S.slice(M,M+2).map(N=>A?.find(R=>N.includes(R)))});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})=>!On(d));return{hasNoRoundPositions:t.some(d=>!d.roundPosition),roundsNotPowerOf2:p,maxMatchUpsCount:i,roundMatchUps:o,roundNumbers:u,roundProfile:s,...C}}function cd(t){if(!Array.isArray(t))return"";let e=t.filter(Jt);return e.length?pt([Math.min(...e),Math.max(...e)]).join("-"):""}function Fb({drawDefinition:t,structureId:e,matchUpsMap:r}){if(!t)return{error:X};if(!e)return{error:hr};let{structure:n}=at({drawDefinition:t,structureId:e});if(n?.stage!==Ve)return{error:Li,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=ii({structureId:m,matchUpsMap:r}),f=je({matchUps:d}).roundProfile;return{[m]:f}})),c=ii({matchUpsMap:r,structureId:e}),{roundProfile:u}=je({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,D=S[l]?.matchUpsCount;if(!D)return;let U=D?T.length/D:0,A=T.length/U,E=T.slice(),M=tS({roundPositionsCount:A,groupedOrder:g}),P=M?.length||1;if(P<=A){let v=T.length/P,O=Ae(E,v);f===Ii&&O.forEach(x=>x.reverse()),E=M?.length&&M?.map(x=>O[x-1]).flat()||E}let N=Ae(E,U);if(I){let v=tt(0,I.interleave).map(()=>{}),O=tt(0,I.offset).map(()=>{});N=N.map(F=>[F,...v]),N.unshift(O),N=N.flat(1);let x=N.length-I.offset;N=N.slice(0,x)}p[h]||(p[h]={});let b=u?.[h]?.feedRound?2:1;N.forEach((v,O)=>{let x=1+O*b;p[h][x]||(p[h][x]=cd(v))})}),{sourceDrawPositionRanges:p}}function kb({drawPositions:t,roundProfile:e,roundNumber:r}){let n=[void 0,void 0];if($I(t))return{orderedDrawPositions:n,displayOrder:n};let o=e?.[r],s=o?.pairedDrawPositions?.find(c=>xe(c||[],t.filter(Boolean)))??n,a=o?.feedRound;if(qI(t)){let c=[...t].sort(ae);return{orderedDrawPositions:c.length===2?c:s,displayOrder:a?c:s}}if(a){let u=[t.find(p=>!isNaN(ut(p))),void 0];return{orderedDrawPositions:u,displayOrder:u}}return{orderedDrawPositions:s,displayOrder:s}}function Op({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 gn({tournamentParticipants:t,tournamentRecord:e,participantIds:r}){let n="getPairedParticipant";if(!t&&!e)return{error:j};if(!Array.isArray(r)||r.length>2)return{error:_r};if(!r.length)return _({result:{error:No},stack:n});t=t??e?.participants??[];let o=t.filter(a=>a.participantType===lt&&qt(r,a.individualParticipantIds).length===r.length&&a.individualParticipantIds.length===r.length),i=o[0];if(!i)return _({result:{error:Xt},stack:n});let s=J(o.slice(1),!1,!0);return{participant:J(i),duplicatedPairParticipants:s,...C}}function ls({drawDefinition:t,participantId:e}){if(typeof t!="object")return{error:X};if(typeof e!="string")return{error:ee};let{extension:r}=mt({element:t,name:bo});return{lineUp:(r?.value||{})[e]}}function Gb({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}=Op({collectionPosition:r,collectionId:s,lineUp:d});if(c===kt){if(f?.length<=2){let I=o?.[f[0]]?.pairIdMap?.[f[1]],T=(I&&o[I]?.participant||gn({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||ls({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||ls({participantId:d,drawDefinition:i})?.lineUp;return u({attribute:m,lineUp:g,teamParticipant:f})}).filter(Boolean)||{};return{drawPositionCollectionAssignment:Object.assign({},...p)}}function eS({drawDefinition:t}){if(typeof t!="object")return{error:fa};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"&&[Ve,pe].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 Vb({drawDefinition:t,roundProfile:e,structureId:r,matchUpsMap:n}){if(!t)return{error:X};if(!r)return{error:hr};if(!e){let c=ii({matchUpsMap:n,structureId:r});if({roundProfile:e}=je({matchUps:c}),!e)return{error:ot}}let i=(Math.min(...e?.[1]?.drawPositions??[])||1)-1,s=Object.keys(e);return{drawPositionsRanges:Object.assign({},...(s||[]).map(c=>{let u=e?.[c]?.matchUpsCount,p=e?.[1]?.drawPositions??[],m=Ae(p,p.length/u),d=m.map(cd),l=m.map(S=>S.map(T=>T-i)).map(cd),f=s.map(S=>{if(S>c)return;let T=e?.[S]?.drawPositions??[];return Ae(T,T.length/u)}).filter(Boolean),g=tt(0,u).map(S=>f.map(T=>T[S]).flat().filter(Boolean).sort(ae)).map(S=>pt(S)),I=g.map(S=>RC(S).map(cd).join(", ")),h=Object.assign({},...tt(0,u).map(S=>({[S+1]:{firstRoundDrawPositionsRange:d[S],firstRoundOffsetDrawPositionsRange:l[S],possibleDrawPositions:g[S],drawPositionsRange:I[S]}})));return{[c]:h}}))}}function ud({roundsNotPowerOf2:t,drawDefinition:e,structure:r,matchUps:n}){if(!r)return!1;n=n??r.matchUps??[],t=t??je({matchUps:n}).roundsNotPowerOf2;let o=!!r.positionAssignments?.find(({drawPosition:i})=>i)||!!n?.find(({drawPositions:i})=>i?.length);return(!e?.drawType||e.drawType!==Hi)&&!r?.structures&&t&&o}function pr({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!==Be&&(!e.length||!r&&!n)}var eg={[Ta]:{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:{[et]:"",[pe]:"P",[ct]:"Q",[Ve]:"C"}}},Bb=eg;function Hb({roundNamingPolicy:t,drawDefinition:e,structure:r,matchUps:n}){let{roundProfile:o,roundMatchUps:i}=je({matchUps:n}),{structureAbbreviation:s,stage:a}=r,c=pr({structure:r}),u=ud({structure:r}),p=r.structures,m={},d=eg[Ta],l=r.stage===ct,f=l?Math.max(...(e?.structures??[]).filter(b=>b.stage===ct).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,U=(t?.namingConventions||d.namingConventions).round,A=a&&a!==et?a[0]:"",E=t?.stageConstants||d.stageConstants,M=a&&E?.[a]||A,P=`${I}${M}${g}`,N=o?Object.keys(o):[],R=l&&E?.[ct]?`${E?.[ct]}-`:"";if(p||c||u)Object.assign(m,...N.map(b=>{let v=`${R}${U} ${b}`,O=`${y}${b}`;return{[b]:{roundName:v,abbreviatedRoundName:O}}}));else{let b=l&&(t?.qualifyingFinishMap||d?.qualifyingFinishMap||{});Object.assign(m,...N.map(v=>{if(!o?.[v])return;let{matchUpsCount:O,preFeedRound:x}=o[v],F=O*2,L=b?.[o?.[v].finishingRound]||b&&`${y}${F}`||h[O]||`${y}${F}`,w=x?`-${T}`:"",B=`${L}${w}`,G=[P,s,B].filter(Boolean).join("-"),H=`${S[O]||`${y}${F}`}${w}`,q=[P,s,H].filter(Boolean).join("-");return{[v]:{abbreviatedRoundName:q,roundName:G}}}))}return{roundNamingProfile:m,roundProfile:o,roundMatchUps:i}}function pd(t){let e=nt(t,[{[_n]:!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&&Bt||s===lt&&kt||s===Ft&&Ft||void 0}return{matchUpType:n}}var uk="normal",FU="timed",pk="final",rg="NOAD",md="SET",Wb={S:uk,F:pk};function rr(t){if(typeof t=="string"){let e=t.startsWith("T")&&FU||t.startsWith(md)&&md||"";if(e===FU){let r=$b(t),n={simplified:!0,setFormat:r,bestOf:1};if(r)return n}if(e===md)return mk(t)}}function mk(t){let e=t.split("-"),r=ng(e[0].slice(3)),n=r===1||r%2!==0?r:void 0,o=r!==1&&r%2===0?r:void 0,i=e&&jb(e[1]),s=e&&jb(e[2]),a=i&&i.timed||s&&s.timed,c=n&&n<6||a&&o,u=!e[2]||s,p=i,m=rt({setFormat:i,exactly:o,bestOf:n});if(s&&(m.finalSetFormat=s),c&&p&&u)return m}function jb(t){if(t?.[1]===":"){let e=t.split(":"),r=Wb[e[0]],n=e[1];if(r&&n){if(n.startsWith("TB")){let I=Yb(n);return I===!1?!1:typeof I=="object"?{tiebreakSet:I}:void 0}if(n.startsWith("T"))return $b(n);let s=t.match(/^[FS]:(\d+)([A-Za-z]*)/),a=s&&Kb(s[2])||!1,c=!s?.[2]||a,u=s?ng(s[1]):void 0,p=qb(n),m=p!==!1,d=m&&p||u,l=Yb(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 qb(t,e=!0){let r=t?.indexOf("@")>0&&t.split("@");if(r)return(e?ng(r[1]):r[1])||!1}function Yb(t){if(t)if(t.startsWith("TB")){let e=qb(t,!1),r=t.match(/^TB(\d+)([A-Za-z]*)/),n=r?.[1],o=r&&Kb(r[2]),i=!r?.[2]||o,s=ng(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 $b(t){let e=t.slice(1),r=e.match(/^(\d+)(@?[A-Za-z]*)/),n=ng(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 Kb(t){return t&&t.indexOf(rg)>=0}function ng(t){return isNaN(Number(t))?0:Number(t)}function yu(t,e){return!Array.isArray(t)||!te(e)?!1:qt(t,Wh[e]).length}function bi(t){if(!Array.isArray(t.matchUps))return[];let{matchUps:e,excludeMatchUpStatuses:r,hasParticipantsCount:n,isCollectionMatchUp:o,matchUpStatuses:i,hasWinningSide:s,matchUpFormats:a,roundPositions:c,matchUpFormat:u,collectionIds:p,isMatchUpTie:m,roundNumbers:d,matchUpIds:l,roundNames:f,filterMatchUpTypes:g=!0,filterMatchUpIds:I=!0,stageSequences:h,scheduledDates:S,scheduledDate:T,participantIds:y,processContext:D,tournamentIds:U,matchUpTypes:A,structureIds:E,readyToScore:M,courtIds:P,eventIds:N,venueIds:R,drawIds:b,stages:v}=t,O=Array.isArray(y)?y.filter(Boolean):[],x=Array.isArray(i)?i.filter(Boolean):[],F=Array.isArray(r)?r.filter(Boolean):[],L=Array.isArray(v)?v.filter(Boolean):[],w=Array.isArray(h)?h.filter(Boolean):[],B=Array.isArray(p)?p.filter(Boolean):[],G=Array.isArray(f)?f.filter(Boolean):[],W=Array.isArray(d)?d.filter(Boolean):[],H=Array.isArray(c)?c.filter(Boolean):[],q=Array.isArray(l)&&I?l.filter(Boolean):[],$=Array.isArray(A)&&g?A.filter(Boolean):[],V=Array.isArray(P)?P.filter(Boolean):[],K=Array.isArray(R)?R.filter(Boolean):[],z=Array.isArray(a)&&a.filter(Boolean)||typeof u=="string"&&[u]||[],Y=Array.isArray(S)&&S.filter(Boolean)||typeof T=="string"&&T.length&&[T]||[],Z=Array.isArray(U)?U.filter(Boolean):[],Q=Array.isArray(N)?N.filter(Boolean):[],st=Array.isArray(b)?b.filter(Boolean):[],St=Array.isArray(E)?E.filter(Boolean):[];return e.filter(it=>{if(M&&!se(Nn)(it)&&!it.readyToScore||it.winningSide&&s&&![1,2].includes(it.winningSide)||m!==void 0&&(m&&!it.tieMatchUps||!m&&it.tieMatchUps)||o!==void 0&&(o&&!it.collectionId||!o&&it.collectionId)||L.length&&!L.includes(it.stage)||w.length&&!w.includes(it.stageSequence)||B.length&&(!it.collectionId||!B.includes(it.collectionId))||G.length&&(!it.roundName||!G.includes(it.roundName))||W.length&&(!it.roundNumber||!W.includes(it.roundNumber))||H.length&&(!it.roundPosition||!H.includes(it.roundPosition))||x.length&&(!it.matchUpStatus||!x.includes(it.matchUpStatus))||F.length&&it.matchUpStatus&&F.includes(it.matchUpStatus)||q.length&&!q.includes(it.matchUpId)||$.length&&(!it.matchUpType||!yu($,it.matchUpType))||z.length&&(!it.matchUpFormat||!z.includes(it.matchUpFormat)))return!1;if(Y?.length){let{scheduledTime:jt}=Jf({matchUp:it}),{scheduledDate:Ut}=ms({matchUp:it}),Se=Dt(jt)||Ut;if(!Y.find(Te=>Wn(Te,Se)))return!1}if(V.length){let{courtId:jt}=Qh({matchUp:it}),{allocatedCourts:Ut}=zh({matchUp:it}),Ue=Ut?.map(({courtId:Se})=>Se);if(!V.filter(Boolean).includes(jt)||Ue?.includes(jt))return!1}if(K.length){let{venueId:jt}=Xh({matchUp:it});if(!K.filter(Boolean).includes(jt))return!1}if(D){if(Z.length&&!Z.includes(it.tournamentId)||Q.length&&!Q.includes(it.eventId)||st.length&&!st.includes(it.drawId)||St.length&&!St.includes(it.structureId))return!1;let jt=it.sides?.map(({participantId:Ut})=>Ut).filter(Boolean)??[];if(n&&jt.length<n||O.length&&!O.some(Ue=>jt.includes(Ue)))return!1}return!0})}function zb({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?dk({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 dk({displaySideNumber:t,seedAssignments:e,participantId:r,assignment:n,sideNumber:o}){let i={drawPosition:n.drawPosition,displaySideNumber:t,sideNumber:o};if(r){let s=lk({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 lk({seedAssignments:t,participantId:e}){return t?.find(r=>!r.seedProxy&&r.participantId===e)}var Mn="ANY",Zt="MALE",Cr="MIXED",fs="OTHER",ce="FEMALE",dd={ANY:Mn,MALE:Zt,FEMALE:ce,MIXED:Cr,OTHER:fs};function Et({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:D,event:U}){let A={},E={};if(n=n??s?.participants,!y)return{collectionPositionMatchUps:A,error:di,roundMatchUps:E,matchUps:[]};let M=Array.isArray(m?.eventIds)?m?.eventIds.filter(Boolean):[],P=Array.isArray(m?.structureIds)?m?.structureIds.filter(Boolean):[],N=Array.isArray(m?.drawIds)?m?.drawIds.filter(Boolean):[],R=!h?.eventId||!M?.length&&!u?.eventIds?.filter(Boolean).length||M?.includes(h.eventId)||u?.eventIds?.includes(h.eventId),b=!P?.length||P.includes(y.structureId),v=!g||!N?.length||N.includes(g.drawId);if(!R||!b||!v)return{collectionPositionMatchUps:A,roundMatchUps:E,matchUps:[]};f&&!p&&(p=Yn({tournamentRecord:s,contextProfile:f,drawDefinition:g}));let{appliedPolicies:O}=yt({drawDefinition:g}),x={...e,...O,...i},F=x?.scoring?.structures,L=y.stage&&F?.stage&&F?.stage[y.stage],w=y.stageSequence&&L?.stageSequence&&L.stageSequence[y.stageSequence],B=x?.scoring?.requireAllPositionsAssigned||L?.requireAllPositionsAssigned||w?.requireAllPositionsAssigned;T||(T=Ee({drawDefinition:g,structure:y}));let{positionAssignments:G,allPositionsAssigned:W}=le({structure:y}),H=!B||W,{seedAssignments:q}=en({provisionalPositioning:r,drawDefinition:g,structure:y});a=a??q;let{roundOffset:$,structureId:V,structureName:K,stage:z,stageSequence:Y}=y,{drawId:Z,drawName:Q,drawType:st}=g??{};S=S||g&&eS({drawDefinition:g}).exitProfiles;let St=S?.[V],it=St?.length&&(St[0].split("-").map(ne=>parseInt(ne)).reduce((ne,_t)=>ne+_t)||0),jt=!!y.structures,Ut=ii({matchUpsMap:T,structureId:V,inContext:D}),Ue=x?.[Ta],Se=Hb({roundNamingPolicy:Ue,drawDefinition:g,structure:y,matchUps:Ut}),{roundNamingProfile:Te,roundProfile:Er}=Se;if(E=Se?.roundMatchUps??[],m&&(Ut=bi({matchUps:Ut,...m,filterMatchUpTypes:!1,filterMatchUpIds:!1})),D){let{sourceDrawPositionRanges:ne}=Fb({drawDefinition:g,matchUpsMap:T,structureId:V}),_t=g?Vb({drawDefinition:g,roundProfile:Er,matchUpsMap:T,structureId:V}).drawPositionsRanges:void 0;Ut=Ut.map(xt=>br({scheduleVisibilityFilters:t,sourceDrawPositionRanges:ne,drawPositionsRanges:_t,roundNamingProfile:Te,initialRoundOfPlay:it,appliedPolicies:x,usePublishState:c,publishStatus:I,isRoundRobin:jt,roundProfile:Er,matchUp:xt,event:U})),(Ut?.filter(xt=>Array.isArray(xt.tieMatchUps))).forEach(xt=>{let de=xt.tieMatchUps;Ut=Ut.concat(...de)}),u&&(Ut=bi({processContext:!0,...u,matchUps:Ut}))}else(Ut?.filter(_t=>Array.isArray(_t.tieMatchUps))).forEach(_t=>{let Rt=_t.tieMatchUps;Ut=Ut.concat(...Rt)});return m&&(Ut=bi({matchUps:Ut,...m,filterMatchUpTypes:!1,filterMatchUpIds:!1})),(m?.matchUpTypes||m?.matchUpIds)&&(Ut=bi({matchUpTypes:m.matchUpTypes,matchUpIds:m.matchUpIds,matchUps:Ut})),(m?.matchUpTypes||m?.matchUpIds||D)&&(E=je({matchUps:Ut}).roundMatchUps??[]),We({drawDefinition:g,structure:y,event:U})?.tieFormat&&({collectionPositionMatchUps:A}=Lb({matchUps:Ut})),{collectionPositionMatchUps:A,roundMatchUps:E,isRoundRobin:jt,roundProfile:Er,matchUpsMap:T,matchUps:Ut};function br({scheduleVisibilityFilters:ne,sourceDrawPositionRanges:_t,drawPositionsRanges:Rt,initialRoundOfPlay:xt,additionalContext:de,roundNamingProfile:oe,tieDrawPositions:ge,appliedPolicies:ye,isCollectionBye:cr,usePublishState:qe,publishStatus:Yt,matchUpTieId:$e,isRoundRobin:Gr,roundProfile:qr,sideLineUps:vr,matchUp:Oe,event:fr}){de=de??{};let un=We({drawDefinition:g,structure:y,matchUp:Oe,event:fr})?.tieFormat,En=un?.collectionDefinitions,tr=Oe.collectionId&&En?.find(uo=>uo.collectionId===Oe.collectionId),ke=Oe.collectionId?tr?.matchUpFormat:Oe.matchUpFormat??y?.matchUpFormat??g?.matchUpFormat??fr?.matchUpFormat,Or=Oe.matchUpType||tr?.matchUpType||y?.matchUpType||g?.matchUpType||!se(Me)(fr?.eventType)&&fr?.eventType,es=cr?Pt:Oe.matchUpStatus,{schedule:vn,endDate:ma}=ad({scheduleVisibilityFilters:ne,afterRecoveryTimes:o,tournamentRecord:s,usePublishState:qe,scheduleTiming:l,matchUpFormat:ke,publishStatus:Yt,matchUpType:Or,matchUp:Oe,event:fr}),mi=ge??Oe.drawPositions??[],{collectionPosition:DI,collectionId:aC,roundPosition:PI}=Oe,rs=Oe.roundNumber??de.roundNumber,uL=aC?Gb({tournamentParticipants:n,positionAssignments:G,collectionPosition:DI,drawDefinition:g,participantMap:d,drawPositions:mi,collectionId:aC,sideLineUps:vr,matchUpType:Or}):void 0,cC=oe?.[rs]?.roundName||de.roundName,uC=oe?.[rs]?.abbreviatedRoundName||de.abbreviatedRoundName,pL=qr?.[rs]?.feedRound,mL=qr?.[rs]?.preFeedRound,dL=qr?.[rs]?.roundFactor,lL=Rt?.[rs],fL=PI?lL?.[PI]:void 0,gL=_t?.[rs],IL=tr?.category?{...h?.category||{},...tr.category}:h?.category??fr?.category,hL=Oe.processCodes?.length&&Oe.processCodes||tr?.processCodes?.length&&tr?.processCodes||y?.processCodes?.length&&y?.processCodes||g?.processCodes?.length&&g?.processCodes||fr?.processCodes?.length&&fr?.processCodes||s?.processCodes,SL=f?.withCompetitiveness&&Su({...p,matchUp:Oe}),TL=Oe.finishingPositionRange??de.finishingPositionRange,NI=uo=>rt(uo,void 0,!0),Ir={...NI(h),...NI({matchUpFormat:Oe.matchUpType===Me?void 0:ke,tieFormat:Oe.matchUpType!==Me?void 0:un,gender:tr?.gender??fr?.gender,roundOfPlay:z!==ct&&ft(xt)&&xt+(rs||0),endDate:Oe.endDate??ma,discipline:fr?.discipline,category:IL,finishingPositionRange:TL,abbreviatedRoundName:uC,drawPositionsRange:fL,competitiveProfile:SL,structureName:K,stageSequence:Y,drawPositions:mi,matchUpStatus:es,processCodes:hL,isRoundRobin:Gr,matchUpTieId:$e,preFeedRound:mL,matchUpType:Or,roundFactor:dL,roundOffset:$,structureId:V,roundNumber:rs,feedRound:pL,roundName:cC,drawName:Q,drawType:st,schedule:vn,drawId:Z,stage:z}),...J(NI(Oe),!0,!0)};if(ke&&Oe.score?.scoreStringSide1){let uo=rr(ke),{bestOf:da,finalSetFormat:vs,setFormat:Ur}=uo??{};(vs?.tiebreakSet||Ur?.tiebreakSet||Ur?.timed)&&(Ir.score.sets=Ir.score.sets.sort((nn,Vn)=>nn.setNumber-Vn.setNumber).map((nn,Vn)=>(Vn+1===da?(vs?.tiebreakSet||vs?.timed)&&(nn.tiebreakSet=!0):(Ur?.tiebreakSet||Ur?.timed)&&(nn.tiebreakSet=!0),nn)))}if(Array.isArray(mi)){let{orderedDrawPositions:uo,displayOrder:da}=kb({drawPositions:mi,roundProfile:qr,roundNumber:rs}),vs=qr?.[rs]?.feedRound,Ur=da[0]!==uo[0],Vn=uo.concat(void 0,void 0).slice(0,2).map((wi,RA)=>{let MI=RA+1,AL=Ur?3-MI:MI,EL=zb({...uL,positionAssignments:G,displaySideNumber:AL,seedAssignments:a,drawPosition:wi,isFeedRound:vs,sideNumber:MI}),UL=Oe.sides?.find(PL=>PL.sideNumber===MI),mC=PI?(PI-1)*2+RA+1:void 0,DL=mC?gL?.[mC]:void 0;return NI({sourceDrawPositionRange:DL,...UL,...EL})});Object.assign(Ir,J({sides:Vn},!0,!0))}if(n&&Ir.sides){let uo=ye?.[Ws],da=Ur=>{let nn=d?.[Ur]?.participant;return nn&&ji({template:uo?.participant,source:nn})};if(Ir.sides.filter(Boolean).forEach(Ur=>{if(Ur.participantId){let nn=J(da(Ur.participantId)||n&&Bo({policyDefinitions:ye,participantId:Ur.participantId,tournamentParticipants:n,internalUse:!0,contextProfile:f}),void 0,!0);if(nn){if(g?.entries){let Vn=g.entries.find(wi=>wi.participantId===Ur.participantId);Vn?.entryStatus&&(nn.entryStatus=Vn.entryStatus),Vn?.entryStage&&(nn.entryStage=Vn.entryStage)}Object.assign(Ur,{participant:nn})}}if(Ur?.participant?.individualParticipantIds?.length&&!Ur.participant.individualParticipants?.length){let nn=Ur.participant.individualParticipantIds.map(Vn=>da(Vn)||n&&Bo({policyDefinitions:ye,tournamentParticipants:n,internalUse:!0,contextProfile:f,participantId:Vn}));Object.assign(Ur.participant,{individualParticipants:nn})}}),!Ir.matchUpType){let{matchUpType:Ur}=pd({matchUp:Ir});Ur&&Object.assign(Ir,{matchUpType:Ur})}if(f?.inferGender&&(!Ir.gender||Ir.gender===Cr)&&Ir.sides?.length===2&&Ir.matchUpType!==Me){let Ur=Ir.sides.map(nn=>{if(se(Bt)(Ir.matchUpType))return nn.participant?.person?.sex;if(nn.participant?.individualParticipants?.length===2){let Vn=pt(nn.participant.individualParticipants.map(wi=>wi.person?.sex)).filter(Boolean);if(Vn.length===1)return Vn[0]}});if(Ur.filter(Boolean).length===2&&pt(Ur).length===1){let nn=Ur[0];Ir.inferredGender=nn}}}if(Ir.tieMatchUps){let uo=Ir.matchUpStatus===Pt,da=Ir.sides?.map(({participant:vs,drawPosition:Ur,sideNumber:nn,lineUp:Vn})=>{let wi=vs?.participantType===Me&&vs;return{teamParticipant:wi&&rt({participantRoleResponsibilities:wi.participantRoleResponsibilities,participantOtherName:wi.participanOthertName,participantName:wi.participantName,participantId:wi.participantId,teamId:wi.teamId}),drawPosition:Ur,sideNumber:nn,lineUp:Vn}});Ir.tieMatchUps=Ir.tieMatchUps.map(vs=>{let Ur=Ir.matchUpId,Vn={finishingPositionRange:Ir.finishingPositionRange,abbreviatedRoundName:uC,roundNumber:rs,roundName:cC};return br({tieDrawPositions:mi,scheduleVisibilityFilters:ne,sourceDrawPositionRanges:_t,sideLineUps:da,drawPositionsRanges:Rt,initialRoundOfPlay:xt,roundNamingProfile:oe,additionalContext:Vn,appliedPolicies:ye,isCollectionBye:uo,usePublishState:qe,publishStatus:Yt,matchUpTieId:Ur,isRoundRobin:Gr,roundProfile:qr,matchUp:vs,event:fr})})}let pC=Ir.sides&&Ir.sides.filter(uo=>uo?.participantId).length===2,yL=!Ir.winningSide;if(Object.assign(Ir,{readyToScore:H&&pC&&yL,hasContext:!0}),pC){let{allParticipantsCheckedIn:uo,checkedInParticipantIds:da}=ps({matchUp:Ir});Object.assign(Ir,{allParticipantsCheckedIn:uo,checkedInParticipantIds:da})}return Array.isArray(f?.exclude)&&f?.exclude.forEach(uo=>delete Ir[uo]),Ir}}function gs({matchUp:t}){return t?ie.includes(t?.matchUpStatus)||t?.winningSide:!1}function Au({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:D,event:U}){!y&&S&&({structure:y}=at({drawDefinition:g,structureId:S}));let A=Et({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:D,event:U}),E=[],M=[],P=[],N=[],R=[];if(A.error)return A;let{matchUps:b}=A,{assignedPositions:v}=le({structure:y}),O=v?.filter(F=>F.participantId).map(F=>F.drawPosition),x;return b.filter(F=>{let L=c?.matchUpTypes?.length===1&&c.matchUpTypes[0]===Ht;return!(F.matchUpType!==Ht&&L)}).forEach(F=>{if(F.matchUpStatus===Mr){E.push(F);return}F.matchUpType===Ht&&(x=!0);let L=F.collectionId,w=L&&F.sides?.every(V=>V.participantId),B=!L&&F.drawPositions?.filter(Boolean).length===2,G=!L&&F.drawPositions?.every(V=>O?.includes(V)),W=v?.filter(V=>V.bye).map(V=>V.drawPosition),H=!L&&F.drawPositions?.find(V=>W?.includes(V)),$=Eh.includes(F.matchUpStatus)&&(w||B&&(!t||G));return H?R.push(F):gs({matchUp:F})?M.push(F):$?P.push(F):N.push(F)}),{includesTeamMatchUps:x,abandonedMatchUps:E,completedMatchUps:M,upcomingMatchUps:P,pendingMatchUps:N,byeMatchUps:R,structure:y}}function Qb({drawDefinition:t,roundNumber:e,structureId:r}){if(!t)return{error:X};if(!r)return{error:hr};let{links:n}=Ks({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 rS({finishingPositions:t,linkCondition:e,linkType:r,source:n}){let o=n.find(i=>{let s=!i.source?.finishingPositions||!t||xe(t,i.source?.finishingPositions);return e===i.linkCondition&&s&&i.linkType===r});return[fo,Zn].includes(o?.linkType)&&!o?.source?.roundNumber?_({result:{error:k},stack:"getTargetLink",context:o}):o}function Ks({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:hr}:{error:X}}function Xb({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 nS({sourceRoundMatchUpCount:t,inContextDrawMatchUps:e,sourceRoundPosition:r,drawDefinition:n,targetLink:o}){if(!o)return{error:Ll};let{target:{structureId:i,feedProfile:s,groupedOrder:a,roundNumber:c,positionInterleave:u}}=o,{structure:p}=at({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=tt(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,N=r+P;h=Math.ceil(N/2),S=1-N%2}let T=g,y=g[h-1],D=tS({roundPositionsCount:g.length,groupedOrder:a}),U=D?.length||1;if(U<=g.length){let P=f/U,N=Ae(g,P);s===Ii&&N.forEach(R=>R.reverse()),T=D?.length&&D?.map(R=>N[R-1]).flat()||T}s===yn?y=T[h-1]:s===Ii?((!D?.length||U>g.length)&&(h=l.length+1-h),y=T[h-1]):s===lp&&Sr()&&console.log(sp,{feedProfile:s});let A=y&&l.reduce((P,N)=>N.roundPosition===y?N:P,void 0),E;A?.feedRound?(S=0,E=Math.min(...(A.drawPositions||[]).filter(Boolean))):E=A?.drawPositions?.length===2&&A?.drawPositions[S];let M=m?.find(({drawPosition:P})=>P===E);if(M){let{extension:P}=mt({element:M,name:Bm});if(P?.value)return{disabledDrawPosition:E}}return{matchUp:A,targetDrawPosition:E,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}=at({structureId:i?.structureId,drawDefinition:n});return s?.finishingPosition===Wi?fk({inContextDrawMatchUps:t,useTargetMatchUpIds:e,drawDefinition:n,structure:s,matchUp:i}):gk({matchUp:i})}function fk({inContextDrawMatchUps:t,useTargetMatchUpIds:e,drawDefinition:r,structure:n,matchUp:o}){let{winnerMatchUpId:i,loserMatchUpId:s}=o,{links:a}=Qb({roundNumber:o.roundNumber,structureId:n.structureId,drawDefinition:r}),c=a?.source,u=rS({source:c,linkType:fo}),p=rS({linkCondition:to,linkType:Zn,source:c}),m=rS({source:c,linkType:Zn}),d=p&&m;m||(m=p);let l=u?.target?.feedProfile,f=m?.target?.feedProfile,g=p?.target?.feedProfile,I,h,S,T,y,D,U,A,E,M;if(e&&(i||s)&&(U=i&&l!==mn&&t.find(({matchUpId:R})=>R===i),T=s&&f!==mn&&t.find(({matchUpId:R})=>R===s),U||T))return{matchUp:o,targetLinks:{loserTargetLink:m,winnerTargetLink:u},targetMatchUps:{loserMatchUp:T,winnerMatchUp:U}};let{roundPosition:P}=o;M=M||t.filter(R=>R.structureId===n.structureId);let N=M.reduce((R,b)=>b.roundNumber===o.roundNumber&&!b.matchUpTieId?R+1:R,0);return m&&!T&&f!==mn&&({matchUpDrawPositionIndex:D,targetDrawPosition:y,matchUp:T}=nS({targetLink:m,sourceRoundMatchUpCount:N,inContextDrawMatchUps:t,sourceRoundPosition:P,drawDefinition:r})),d&&g!==mn&&({matchUpDrawPositionIndex:S,targetDrawPosition:h,matchUp:I}=nS({targetLink:p,sourceRoundMatchUpCount:N,inContextDrawMatchUps:t,sourceRoundPosition:P,drawDefinition:r})),u&&!U&&l!==mn&&({matchUpDrawPositionIndex:E,targetDrawPosition:A,matchUp:U}=nS({targetLink:u,sourceRoundMatchUpCount:N,inContextDrawMatchUps:t,sourceRoundPosition:P,drawDefinition:r})),U||(M=M||t.filter(R=>R.structureId===n.structureId),{matchUp:U}=Xb({structureMatchUps:M,matchUp:o})),rt({matchUp:o,targetLinks:{loserTargetLink:m,winnerTargetLink:u,byeTargetLink:p},targetMatchUps:{winnerMatchUpDrawPositionIndex:E,loserMatchUpDrawPositionIndex:D,byeMatchUpDrawPositionIndex:S,winnerTargetDrawPosition:A,loserTargetDrawPosition:y,byeTargetDrawPosition:h,winnerMatchUp:U,loserMatchUp:T,byeMatchUp:I},targetMatchUpIds:!!(i||s)})}function gk({matchUp:t}){return{targetLinks:{loserTargetLink:void 0,winnerTargetLink:void 0},targetMatchUps:{loserMatchUp:void 0,winnerMatchUp:void 0},matchUp:t}}function Jb({drawDefinition:t,inContextDrawMatchUps:e}){let r={};return e.forEach(n=>{let{matchUpId:o,structureId:i,drawPositions:s=[]}=n,{structure:a}=at({drawDefinition:t,structureId:i});if(a?.finishingPosition===Vs){let{roundNumber:c}=n,u=c&&ut(c)+1,p=a.matchUps??[],{roundMatchUps:m}=je({matchUps:p});if(u&&m?.[u]){let d=[...s].sort(ae).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=kU({upcomingMatchUp:u}),d=kU({upcomingMatchUp:p});if(n.matchUpStatus!==Pt&&p?.matchUpStatus===Pt){let{matchUp:f}=Zb({matchUp:p,drawDefinition:t,inContextDrawMatchUps:e})||{};d=f&&kU({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===to,I=Ik(n);if(I.length){let h=Mf(u?.sides),S=Mf(p?.sides),y=I.find(({participantId:A})=>h.includes(A))?[]:I,U=I.find(({participantId:A})=>S.includes(A))?[]:I;p&&g&&U.length<2&&U.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)),U?.length&&p&&(c.targetMatchUpIds||(u=e.find(({matchUpId:A})=>A===p.matchUpId)),p.potentialParticipants||(p.potentialParticipants=[]),p.potentialParticipants.push(U))}}}}),Object.keys(r).length&&e.forEach(n=>{Object.keys(r).includes(n.matchUpId)&&(n.schedule.scheduleConflict=r[n.matchUpId])}),{scheduleConflictMatchUpIds:r}}function Ik(t){return t?.sides?.map(({participant:e,participantId:r,qualifier:n})=>e||r&&{participantId:r}||n&&{qualifier:n}).filter(Boolean)||[]}function Zb({matchUp:t,drawDefinition:e,inContextDrawMatchUps:r}){let{matchUpId:n,matchUpStatus:o,structureId:i}=t||{};if(!t||!i||t?.matchUpStatus===zt)return{matchUp:t};if(o===Pt){let s;return t.winnerMatchUpId?s=r.find(({matchUpId:a})=>a===t.winnerMatchUpId):{winnerMatchUp:s}=nr({inContextDrawMatchUps:r,drawDefinition:e,matchUpId:n})?.targetMatchUps||{},Zb({matchUp:s,drawDefinition:e,inContextDrawMatchUps:r})}return{matchUp:void 0}}function kU(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 re(t){let e="getAllDrawMatchUps";Object.assign(t,{requireParticipants:!1});let r=zs(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 zs(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:D,event:U}=t,A=[],E=[],M=[],P=[],N=[];h&&!r&&(r=Yn({policyDefinitions:u,tournamentRecord:p,contextProfile:h,event:U}));let R;!e?.length&&p&&(e=p?.participants,(y||a?.withGroupings)&&e?.length&&({participantsWithGroupings:e,groupInfo:R}=Qm({participants:e,participantsProfile:a})));let{structures:b}=ln({drawDefinition:S});if(!b)return{error:Lt};n||(n=Ee({drawDefinition:S}));let v=S&&eS({drawDefinition:S}).exitProfiles;b.forEach(F=>{let{byeMatchUps:L=[],pendingMatchUps:w=[],upcomingMatchUps:B=[],completedMatchUps:G=[],abandonedMatchUps:W=[]}=Au({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:D,event:U});A=A.concat(...W),E=E.concat(...G),M=M.concat(...B),P=P.concat(...w),N=N.concat(...L)});let O=F=>(!l&&!T&&!d||(l&&(F=bi({matchUps:F,...l})),d&&(F=bi({matchUps:F,...d,processContext:!0}))),F),x={abandonedMatchUps:O(A),completedMatchUps:O(E),upcomingMatchUps:O(M),pendingMatchUps:O(P),byeMatchUps:O(N),matchUpsMap:n,...C,groupInfo:R};if(T){let F=typeof T=="object"||{abandoned:!0,completed:!0,upcoming:!0,pending:!0,bye:!0},{abandoned:L,completed:w,upcoming:B,pending:G,bye:W}=F,H=[].concat(...L&&A||[],...w&&E||[],...B&&M||[],...G&&P||[],...W&&N||[]);Jb({inContextDrawMatchUps:H,drawDefinition:S})}return x}function qn(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:bt};let{eventId:S,eventName:T,endDate:y,eventType:D,category:U,gender:A,matchUpFormat:E}=h??{},M={...I,...rt({indoorOutDoor:h.indoorOutdoor??p?.indoorOutdoor,surfaceCategory:h.surfaceCategory??p?.surfaceCategory,endDate:h.endDate??p?.endDate,tournamentId:p?.tournamentId,matchUpFormat:E,eventName:T,eventType:D,category:U,eventId:S,gender:A})};y&&(M.endDate=y),d&&!r&&(r=Yn({policyDefinitions:c,tournamentRecord:p,contextProfile:d,event:h}));let P;if(!e?.length&&!n&&p){let v=Di({participantsProfile:s,useParticipantMap:u,policyDefinitions:c,tournamentRecord:p,contextProfile:d,inContext:g});n=v.participantMap,e=v.participants??[],P=v.groupInfo}let N=h.drawDefinitions??[],R=Na({tournamentRecord:p,event:h}).scheduleTiming;return{matchUps:N.flatMap(v=>{let{matchUps:O}=re({tournamentParticipants:e,tournamentAppliedPolicies:i,scheduleVisibilityFilters:o,context:M,participantsProfile:s,afterRecoveryTimes:a,policyDefinitions:c,tournamentRecord:p,contextFilters:m,contextProfile:d,drawDefinition:v,contextContent:r,matchUpFilters:l,participantMap:n,scheduleTiming:R,nextMatchUps:f,inContext:g,event:h});return O??[]}),groupInfo:P}}function fe(t){let e=nt(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}=Di({participantsProfile:i,useParticipantMap:a,policyDefinitions:c,tournamentRecord:u,contextProfile:m,inContext:p}));let{appliedPolicies:S}=yt({tournamentRecord:u}),T={...g,tournamentId:I,indoorOutDoor:u.indoorOutdoor,surfaceCategory:u.surfaceCategory,endDate:u.endDate},y=Yn({policyDefinitions:c,tournamentRecord:u,contextProfile:m});return{matchUps:h.flatMap(U=>(T.eventDrawsCount=U.drawDefinitions?.length??0,qn({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:U}).matchUps??[])).concat(...u.matchUps??[])}}function An({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:wt};let p=Object.keys(n).map(m=>{let d=n[m];return fe({scheduleVisibilityFilters:t,afterRecoveryTimes:e,participantsProfile:r,policyDefinitions:o,tournamentRecord:d,matchUpFilters:i,contextFilters:s,nextMatchUps:a,inContext:c}).matchUps??[]}).flat();return{...C,matchUps:p}}function vi(t,e){return hk(t,e)||(t?.stageSequence||0)-(e?.stageSequence||0)||t?.roundNumber&&e.roundNumber&&t?.roundNumber-e?.roundNumber||(t?.roundPosition??0)-(e?.roundPosition??0)}function hk(t,e){return(Gs[t?.stage]||0)-(Gs[e?.stage]||0)}function Je(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:D,eventType:U,category:A,gender:E,matchUpFormat:M}=S??{},P={...h,surfaceCategory:S?.surfaceCategory??p?.surfaceCategory,indoorOutDoor:S?.indoorOutdoor??p?.indoorOutdoor,matchUpFormat:M,eventType:U,eventName:y,category:A,eventId:T,endDate:D,gender:E},N;return!e?.length&&!r&&p&&({participants:e=[],participantMap:r,groupInfo:N}=Di({participantsProfile:s,useParticipantMap:u,policyDefinitions:c,tournamentRecord:p,contextProfile:l,inContext:I})),l&&!n&&(n=Yn({policyDefinitions:c,tournamentRecord:p,contextProfile:l,drawDefinition:f,event:S})),{...re({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:N}}function Is({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 GU=t=>e=>!t||typeof e!="object"?void 0:Array.isArray(t)&&t.map(r=>({[r]:Is({element:e,accessor:r})?.value}))||typeof t=="object"&&Object.keys(t).map(r=>({[r]:Is({element:e,accessor:r})?.value}))||(typeof t=="string"&&Is({element:e,accessor:t}))?.value,Fr=GU;function Ra({finishingPositionOffset:t=0,finishingPositionLimit:e,positionsFed:r,roundsCount:n,roundLimit:o,matchUps:i,lucky:s,fmlc:a}){if(!Lr(i))return[];let{roundProfile:c,roundNumbers:u=[]}=je({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(Fr("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((R,b)=>R+(b||0),0),D=a&&I!==1,U=1+t+(D?r??0:0),A=1,E=tt(U,s?U+S*2:y+U+A),M=y+A-S,P=l(E.slice(M)),N=l(E.slice(0,M),!0);return T.finishingPositionRange={loser:P,winner:N},{[I]:T}})),g=Sr({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 Ki({inContextDrawMatchUps:t,drawDefinition:e,matchUpsMap:r}){if(!e)return{error:X};let n={loserMatchUpIds:{},winnerMatchUpIds:{}};if(t||({matchUps:t,matchUpsMap:r}=re({inContext:!0,drawDefinition:e,matchUpsMap:r})),!r?.drawMatchUps.some(i=>i.finishingPositionRange)&&e?.structures?.length===1&&!e?.structures[0].structures){let i=r?.drawMatchUps??[];Ra({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=ii({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 rn(t){let e=Tr(t),r=t.matchUps??[],n=t.drawIds??[],{includeParticipantDependencies:o,tournamentRecord:i,drawDefinition:s}=t;if(!Array.isArray(r))return{error:Xn};if(!Array.isArray(n))return{error:on};let a=t.matchUpIds?.length?t.matchUpIds:r.map(T=>T.matchUpId);if(!Array.isArray(a))return{error:ns};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(D=>(D.drawDefinitions||[]).map(U=>U.links||[])).flat(1/0),[]).filter(({linkType:T})=>T===Jn),g=r;if(f.length){g=An({nextMatchUps:!0,tournamentRecords:e}).matchUps;let T=f.reduce((y,D)=>{let U=D.source?.structureId,A=D.target?.structureId;return U&&A&&(p[A]=U),U&&!y.includes(U)&&y.push(U),y},[]);for(let y of T)c[y]=[];for(let y of g??[]){let D=y.containerStructureId||y.structureId;T.includes(D)&&c[D].push(y.matchUpId)}}let I=T=>{u[T]||(u[T]={dependentMatchUpIds:[],participantIds:[],matchUpIds:[],sources:[]},m[T]=[])},h=(T,y)=>{u[T].matchUpIds.forEach(U=>{u[y].matchUpIds.push(U)}),u[y].matchUpIds.push(T),u[T].dependentMatchUpIds.push(y),o&&u[T].participantIds.forEach(U=>u[y].participantIds.push(U))},S=T=>{let y=Object.keys(c).length;for(let D of T||[]){let{matchUpId:U,winnerMatchUpId:A,loserMatchUpId:E}=D;if(!a.length||a.includes(U)){if(I(U),o){let{individualParticipantIds:N}=du(D);u[U].participantIds=N}A&&(I(A),h(U,A),m[A].push(U)),E&&(I(E),h(U,E),m[E].push(U)),u[U].sources.push(m[U]);let M=m[U].map(N=>u[N].sources[0]).flat(),P=m[U].map(N=>u[N].sources[1]).flat();if(u[U].sources.push(M,P),y){let N=D.containerStructureId||D.structureId,R=p[N];if(c[R])for(let b of c[R])I(b),h(b,U),m[b].push(U)}}}};if(s)Ki({drawDefinition:s}),g?.length||(g=Je({drawDefinition:s}).matchUps),S(g);else{if(g?.length||(g=An({nextMatchUps:!0,tournamentRecords:e}).matchUps),!n.length){let T=d?.length?d.map(({events:y=[]})=>y.map(({drawDefinitions:D=[]})=>D.map(({drawId:U})=>U))).flat(1/0):[];T&&(n=T)}for(let T of n){let y=g?.filter(U=>U.drawId===T).sort(vi);if(!y?.find(({roundPosition:U})=>!U)){let U=y?.find(({tournamentId:E})=>E),{drawDefinition:A}=He({tournamentRecord:e[U?.tournamentId],drawId:T});A&&Ki({drawDefinition:A})}S(y)}}return{positionDependencies:c,matchUpDependencies:u,sourceMatchUpIds:m,matchUps:g,...C}}function me(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 Ca({matchUpStatus:t}){return yh.includes(t)}function tv({matchUpStatus:t}){return $m.includes(t)}function og({matchUpStatus:t}){return Ah.includes(t)}function ig({matchUpStatus:t,winningSide:e,tieMatchUps:r,sides:n,score:o}){let i=n?.find(({participantId:c})=>c),s=r?.filter(ig)?.length;return me({score:o})||s||e&&i||t&&tv({matchUpStatus:t})&&![Mt,vt,Ln].includes(t)}function ba(t){let{drawDefinition:e,findContainer:r,structureId:n,event:o}=t,i=t.structure,s={isCollectionMatchUp:!1},{containedStructures:a}=cs({drawDefinition:e}),c=n?a[n]||[]:[];if(!i){let A=at({drawDefinition:e,structureId:n});if(A.error)return A;i=r?A.containingStructure??A.structure:A.structure}if(pr({structure:i}))return{structure:i,isAdHoc:!0,error:Os};let{matchUps:u}=re({inContext:!0,matchUpFilters:s,drawDefinition:e,event:o}),p=u?.filter(A=>A.structureId===n||c.includes(A.structureId)),{matchUpDependencies:m}=rn({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 E=A.roundNumber;for(let M of(A.drawPositions??[]).filter(Boolean))(!f[M]||E&&f[M]>E)&&(f[M]=E)}ig(A)&&(g.push(A),d.push(A.matchUpId,...m?.[A?.matchUpId]?.matchUpIds||[]))}let I=pt(l.filter(Boolean)).sort(ae),h=pt(d),S=pt(p?.map(({matchUpId:A,drawPositions:E})=>h.includes(A)?E:[]).flat().filter(Boolean)).sort(ae),{positionAssignments:T}=Ct({drawDefinition:e,structure:i}),y=T?.filter(A=>A.bye).map(A=>A.drawPosition),D=T?.filter(A=>A.qualifier).map(A=>A.drawPosition),U=I?.filter(A=>!S.includes(A))||[];return{allDrawPositions:I,inContextStructureMatchUps:p,drawPositionInitialRounds:f,activeDependentMatchUpIds:h,qualifyingDrawPositions:D,inactiveDrawPositions:U,positionAssignments:T,activeDrawPositions:S,byeDrawPositions:y,activeMatchUps:g,structure:i}}function hs({drawPosition:t,matchUps:e=[]}){return{initialRoundNumber:e.filter(({drawPositions:n})=>t&&n?.includes(t)).map(({roundNumber:n})=>n).sort(ae)[0]}}var va={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 oS=[];function $n(t,e){typeof t=="string"&&(t={method:t}),(e||Sr())&&oS.push(t)}function Sk(t){let e=oS.slice();return t&&(oS.length=0),e}function ev(t){let r=Sk(t).map(n=>{let{color:o,keyColors:i,method:s,newline:a}=n,c=Object.keys(va).includes(o)?va[o]:va.cyan,p=Object.keys(n).filter(d=>!["color","keyColors","method","newline"].includes(d)).map(d=>{let l=i&&Object.keys(i).includes(d)&&va[i[d]]?va[i[d]]:va.brightwhite;return`${va.white}${d}: ${l}${n[d]}`}).join(", "),m=s?.length<15?" ":" ";return[a?`
|
|
2
2
|
`:"",c,s,m,va.white,p,va.reset,`
|
|
3
3
|
`].join("")});r?.length&&console.log(...r)}function rv(){oS.length=0}function kr({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}=at({drawDefinition:n,structureId:s})),!a)return{error:Lt};s||({structureId:s}=a);let u="assignDrawPositionBye";$n({method:u,color:"cyan",drawPosition:o}),i||(i=Ee({drawDefinition:n}));let{positionAssignments:p}=Ct({structure:a}),{activeDrawPositions:m}=ba({drawDefinition:n,structureId:s});if(p?.find(R=>R.drawPosition===o)?.bye)return{...C};if(m?.includes(o))return{error:Xu};let f=p?.find(R=>R.drawPosition===o);if(!f)return{error:Os};let{filled:g,containsBye:I,assignedParticipantId:h}=Tk(f);if(I)return{...C};if(g&&!I)return _({result:{error:Ka},stack:u});let S=yt({tournamentRecord:r,drawDefinition:n,event:c}).appliedPolicies??{},T=re({inContext:!0,drawDefinition:n,matchUpsMap:i}).matchUps??[],y={isCollectionMatchUp:!1},{matchUps:D}=Et({provisionalPositioning:t,drawDefinition:n,matchUpFilters:y,matchUpsMap:i,structure:a});if(p?.forEach(R=>{R.drawPosition===o&&(R.bye=!0)}),a.structureType===we)return yk({tournamentRecord:r,drawDefinition:n,drawPosition:o,matchUps:D}),Oo({tournamentId:r?.tournamentId,drawDefinition:n,structure:a,event:c}),nv({assignedParticipantId:h,isPositionAction:e,appliedPolicies:S,drawDefinition:n,drawPosition:o,structureId:s,stack:u});let{roundProfile:U,roundMatchUps:A}=je({matchUps:D}),M=(U&&Object.keys(U).map(R=>parseInt(R)).reverse())?.find(R=>U?.[R].drawPositions?.includes(o)),P=M?A?.[M].find(({drawPositions:R})=>R?.includes(o)):void 0;P&&ov({tournamentRecord:r,drawDefinition:n,matchUp:P,event:c});let N=P?.drawPositions?.find(R=>R!==o);if(P&&N){let R=iS({sourceDrawPositions:P.drawPositions,matchUpId:P.matchUpId,inContextDrawMatchUps:T,drawPositionToAdvance:N,tournamentRecord:r,drawDefinition:n,matchUpsMap:i});if(R.error)return R}return Oo({tournamentId:r?.tournamentId,drawDefinition:n,structure:a,event:c}),nv({assignedParticipantId:h,isPositionAction:e,appliedPolicies:S,drawDefinition:n,drawPosition:o,structureId:s,stack:u})}function nv({assignedParticipantId:t,isPositionAction:e,appliedPolicies:r,drawDefinition:n,drawPosition:o,structureId:i,stack:s}){return e&&mu({appliedPolicies:r,drawDefinition:n,positionAction:{removedParticipantId:t,drawPosition:o,structureId:i,name:s}}),_({result:{...C},stack:s})}function Tk(t){let e=t.bye,r=t.qualifier,n=t.participantId;return{containsBye:e,containsQualifier:r,assignedParticipantId:n,filled:e||r||n}}function ov({tournamentRecord:t,drawDefinition:e,eventId:r,matchUp:n,event:o}){Object.assign(n,{matchUpStatus:Pt,score:void 0,winningSide:void 0}),gt({tournamentId:t?.tournamentId,eventId:r??o?.eventId,context:"setMatchUpStatusBye",drawDefinition:e,matchUp:n})}function yk({tournamentRecord:t,drawDefinition:e,drawPosition:r,matchUps:n,event:o}){n.forEach(i=>{i.drawPositions?.includes(r)&&ov({eventId:o?.eventId,tournamentRecord:t,drawDefinition:e,matchUp:i})})}function iS({drawPositionToAdvance:t,inContextDrawMatchUps:e,sourceDrawPositions:r,tournamentRecord:n,drawDefinition:o,matchUpsMap:i,matchUpId:s,event:a}){$n({method:"advanceDrawPosition",color:"cyan",drawPositionToAdvance:t});let u=i.drawMatchUps.find(D=>D.matchUpId===s),m=e.find(D=>D.matchUpId===s)?.structureId,{structure:d}=at({drawDefinition:o,structureId:m}),{positionAssignments:l}=Ct({structure:d}),f=l?.filter(D=>D.bye).map(D=>D.drawPosition),g=u?.drawPositions?.find(D=>D!==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&&Ak({drawPositionToAdvance:t,inContextDrawMatchUps:e,sourceDrawPositions:r,tournamentRecord:n,drawDefinition:o,winnerMatchUp:T,matchUpsMap:i,event:a}),S&&I&&S.structureId!==d?.structureId){let{roundNumber:D}=S;if(D===1){let U=kr({structureId:h.target.structureId,drawPosition:y,tournamentRecord:n,drawDefinition:o,event:a});if(U.error)return U}else iv({loserTargetDrawPosition:y,tournamentRecord:n,loserTargetLink:h,drawDefinition:o,loserMatchUp:S,matchUpsMap:i,event:a})}return{...C}}function Ak({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}=at({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),D=(T&&h?.find(({drawPosition:L})=>L===T))?.bye,U=g&&D;if(U&&console.log({isByeAdvancedBye:U}),I?.length>1&&g&&!D)return _({result:{error:Ka},stack:c});let A=I?.find(L=>L!==t),E=U,M=[...(u.drawPositions||[]).filter(Boolean),void 0,void 0].slice(0,2),P=M.map(L=>!L&&!E||L===t?(E=!0,t):L).sort(ae);if(!E)return console.log("@@@@@@@",{advancingAssignmentIsBye:S,drawPositionToAdvance:t,existingAssignments:h}),_({result:{error:Ka},stack:c});let N=l?.find(({drawPosition:L})=>L===A)?.bye,R=l?.find(({drawPosition:L})=>L===t)?.bye;Object.assign(u,{matchUpStatus:R||N?Pt:zt,score:void 0,winningSide:void 0,drawPositions:P});let v=u.drawPositions.find(L=>!M.includes(L));$n({method:c,color:"brightyellow",changedDrawPosition:v,pairedDrawPositionIsBye:N,drawPositionIsBye:R}),gt({tournamentId:n?.tournamentId,matchUp:u,eventId:a?.eventId,context:c,drawDefinition:o});let{targetLinks:{loserTargetLink:O},targetMatchUps:{loserMatchUp:x,loserTargetDrawPosition:F}}=nr({matchUpId:i.matchUpId,inContextDrawMatchUps:e,drawDefinition:o});if(N||R){let L=N?t:A;if(L)iS({drawPositionToAdvance:L,matchUpId:i.matchUpId,inContextDrawMatchUps:e,tournamentRecord:n,drawDefinition:o,matchUpsMap:s});else if(R&&O&&x)if(x.feedRound)iv({loserTargetDrawPosition:F,tournamentRecord:n,loserTargetLink:O,drawDefinition:o,loserMatchUp:x,matchUpsMap:s});else{let B=1-i.roundPosition%2,G=x.drawPositions[B],W=kr({structureId:O.target.structureId,drawPosition:G,tournamentRecord:n,drawDefinition:o,event:a});if(W.error)return W}}}function iv({loserTargetDrawPosition:t,tournamentRecord:e,loserTargetLink:r,drawDefinition:n,loserMatchUp:o,matchUpsMap:i,event:s}){let{roundNumber:a}=o;$n({method:"assignFedDrawPositionBye",color:"cyan",loserTargetDrawPosition:t});let p=(i?.mappedMatchUps||{})[o.structureId].matchUps,{initialRoundNumber:m}=hs({drawPosition:t,matchUps:p});if(m===a){let d=kr({structureId:r.target.structureId,drawPosition:t,tournamentRecord:e,drawDefinition:n,event:s});if(d.error)return d}}function sS({positionAssignments:t,tournamentRecord:e,drawDefinition:r,matchUpsMap:n,structure:o,event:i}){let{matchUps:s}=Et({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?Pt:zt}),gt({tournamentId:e?.tournamentId,context:"modifyRoundRobinMatchUpsStatus",eventId:i?.eventId,drawDefinition:r,matchUp:a}))})}function Sc(t){let{inContextDrawMatchUps:e,participantId:r,drawPosition:n}=t,{tournamentRecord:o,drawDefinition:i,structureId:s,matchUpsMap:a,event:c}=t,{structure:u}=at({drawDefinition:i,structureId:s}),m=(le({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:_s};r||(r=m?.participantId);let{activeDrawPositions:d}=ba({drawDefinition:i,structureId:s});return d.includes(n)?{error:Xu}:(e||({matchUps:e}=re({inContext:!0,drawDefinition:i,matchUpsMap:a})),VU({inContextDrawMatchUps:e,tournamentRecord:o,drawDefinition:i,structureId:s,drawPosition:n,matchUpsMap:a,event:c}).drawPositionCleared?(Oo({tournamentId:o?.tournamentId,drawDefinition:i,structure:u,event:c}),{...C,participantId:r}):{error:xA})}function VU({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,matchUpsMap:o,structureId:i,event:s}){let{structure:a}=at({drawDefinition:r,structureId:i});if(!a)return{error:Lt};let c=le({drawDefinition:r,structure:a}).positionAssignments||[],u=c.some(T=>{if(T.drawPosition===n)return delete T.participantId,delete T.qualifier,delete T.bye,!0});if(a.structureType===we)return sS({positionAssignments:c,tournamentRecord:e,drawDefinition:r,matchUpsMap:o,structure:a}),{drawPositionCleared:u,...C};let p={isCollectionMatchUp:!1},{matchUps:m}=Et({drawDefinition:r,matchUpFilters:p,matchUpsMap:o,structure:a,event:s}),{roundProfile:d,roundMatchUps:l}=je({matchUps:m}),g=(d&&Object.keys(d))?.map(T=>ut(T)),I=n,S=g?.map(T=>{let D=d?.[T]?.pairedDrawPositions?.find(v=>v.includes(I)),U=D?.find(v=>v!==I),A=c.find(v=>v.drawPosition===U),E=d?.[T+1],M=A?.bye,P=E?.pairedDrawPositions?.find(v=>v.includes(U)),N=M&&P&&E&&E.drawPositions?.includes(U),b=D&&{pairedDrawPositionByeAdvancedPair:!N&&P,pairedDrawPosition:U,targetDrawPosition:I,relevantPair:D,roundNumber:T};return N&&(I=U),b}).filter(T=>T?.targetDrawPosition)?.reduce((T,y)=>{let{roundNumber:D,relevantPair:U,targetDrawPosition:A,pairedDrawPosition:E,pairedDrawPositionByeAdvancedPair:M}=y,P={roundNumber:D,targetDrawPosition:A,relevantPair:U},N=M&&{roundNumber:D+1,targetDrawPosition:E,relevantPair:M,subsequentRoundRemoval:!0},R=[P,N].filter(Boolean);return T.concat(...R)},[]);return S?.forEach(({roundNumber:T,targetDrawPosition:y,relevantPair:D})=>{let U=l?.[T].find(A=>xe(A.drawPositions?.filter(Boolean),D.filter(Boolean)));U&&(Ek({inContextDrawMatchUps:t,targetDrawPosition:y,tournamentRecord:e,drawDefinition:r,structureId:i,roundNumber:T,matchUpsMap:o}),sv({inContextDrawMatchUps:t,positionAssignments:c,tournamentRecord:e,drawDefinition:r,targetMatchUp:U,drawPosition:n,matchUpsMap:o,structure:a,event:s}))}),{tasks:S,drawPositionCleared:u,positionAssignments:c}}function Ek({inContextDrawMatchUps:t,targetDrawPosition:e,tournamentRecord:r,drawDefinition:n,matchUpsMap:o,roundNumber:i,structureId:s}){let{structure:a}=at({drawDefinition:n,structureId:s});if(!a)return{error:Lt};if(a.structureType===we)return;o=o||Ee({drawDefinition:n});let u=(o?.mappedMatchUps||{})[s].matchUps,{initialRoundNumber:p}=hs({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=>sv({drawPosition:e,targetMatchUp:l,inContextDrawMatchUps:t,positionAssignments:d,tournamentRecord:r,drawDefinition:n,matchUpsMap:o,structure:a})),{...C}}function sv({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??Ee({drawDefinition:n});let f=s.mappedMatchUps[a.structureId].matchUps,{initialRoundNumber:g}=hs({drawPosition:i,matchUps:f});if(o.roundNumber&&g&&o.roundNumber>g){let P=(o.drawPositions??[]).map(N=>N===i?void 0:N);o.drawPositions=P}if(o.matchUpType===Ht){let R=(t?.find(b=>b.matchUpId===o.matchUpId)?.sides??[]).reduce((b,v,O)=>v.drawPosition===i?O:b,void 0);R!==void 0&&o.sides?.[R]?.lineUp&&(delete o.sides?.[R].lineUp,gt({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,U=e.filter(({drawPosition:P})=>o.drawPositions?.includes(P)).filter(P=>P.bye).length,A=U&&Pt||o.matchUpStatus&&[Mt,vt].includes(o.matchUpStatus)&&o.matcHUpStatus||o.drawPositions?.length===2&&zt||void 0;o.matchUpStatus=A,o.matchUpStatus&&[vt,Mt].includes(o.matchUpStatus)&&(o.winningSide=void 0);let E=p?.find(P=>!o.drawPositions?.includes(P));if(p?.includes(i)&&m===o.matchUpStatus&&d===o.winningSide||(E&&$n({method:u,color:"brightyellow",removedDrawPosition:E}),gt({tournamentId:r?.tournamentId,eventId:c?.eventId,matchUp:o,context:`${u}-${i}`,drawDefinition:n})),S&&S.structureId!==I.matchUp.structureId&&!U){let{drawPositions:P,roundNumber:N}=S;if(N===1){let R=P[y];VU({structureId:S.structureId,drawPosition:R,inContextDrawMatchUps:t,tournamentRecord:r,drawDefinition:n,matchUpsMap:s})}else{let R=Math.min(...P.filter(Boolean)),b=Uk({loserMatchUpDrawPosition:R,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:x}=hs({drawPosition:R,matchUps:O});x===1&&($n({method:u,color:"brightyellow",loserMatchUpDrawPosition:R}),VU({structureId:S.structureId,drawPosition:R,inContextDrawMatchUps:t,tournamentRecord:r,drawDefinition:n,matchUpsMap:s}))}}return T&&T.structureId!==I.matchUp.structureId&&(h.target.feedProfile,mn),{...C}}function Uk({loserMatchUpDrawPosition:t,inContextDrawMatchUps:e,tournamentRecord:r,drawDefinition:n,loserMatchUp:o,matchUpsMap:i,event:s}){let{structure:a}=at({structureId:o.structureId,drawDefinition:n}),{positionAssignments:c}=Ct({structure:a});if(c?.find(p=>p.drawPosition===t)?.bye){let p=Sc({drawPosition:t,structureId:o.structureId,inContextDrawMatchUps:e,tournamentRecord:r,drawDefinition:n,matchUpsMap:i,event:s});if(p.error)return p}return{...C}}function Oi({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(ht):[]}).flat().filter(Boolean));return{...C,assignedParticipantIds:n}}function Kn(t){let e=(t?.entries??[]).filter(Boolean).reduce((n,o)=>{let{entryStage:i,entryStatus:s}=o,a=`_${i||et}${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 Qs(t){return[Pi,tn].includes(t)}function ld({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:pn,method:"modifyEntriesStatus",participantIds:o};if(!n&&!m)return{error:bt};if(i&&!CU.includes(i))return{error:Kl};if(s&&!zc.includes(s))return{error:Li};let d="modifyEntriesStatus",l=[];if(!i&&!a)return _({result:{error:ot},info:"Missing entryStatus",stack:d});if(a&&!wn({extension:a,requiredAttributes:["name"]}))return _({result:{error:k},info:"Invalid extension",context:{extension:a},stack:d});let f=[];m?.drawDefinitions?.forEach(P=>{let N=Oi({stages:p&&[p],drawDefinition:P}).assignedParticipantIds??[];f.push(...N)});let g=r?.participants??[];if(!o.every(P=>{let N=Bo({tournamentParticipants:g,participantId:P})?.participantType;return!(N&&[lt,fn].includes(N)&&Qs(i))&&!(i&&m?.eventType&&N===Tt&&[Br,Kr].includes(m.eventType)&&[Jr,...$f].includes(i))}))return{error:Kl};let h=m&&Wt({event:m}).flightProfile,S=h?.flights?.find(P=>P.drawId===u),T=P=>{let N=(P||[]).filter(v=>!p||!v.entryStage||p===v.entryStage).filter(({participantId:v})=>o.includes(v)),R=v=>i&&f.includes(v.participantId)&&!($f.includes(v.entryStatus)&&$f.includes(i));return N.every(v=>R(v)&&!e?!1:(i&&(v.entryStatus=i,delete v.entryPosition),s&&(v.entryStage=s,delete v.entryPosition),a&&(a.value?At({element:v,extension:a}):ur({element:v,name:a.name})),!0))?{...C}:{error:ws}},y=({flight:P,drawDefinition:N})=>{m&&(m.entries=Kn({entries:m.entries??[]})),P&&(P.drawEntries=Kn({entries:P.drawEntries})),N&&(N.entries=Kn({entries:N.entries}))},D=P=>{let{flight:N,drawDefinition:R}=P,b="updateDrawEntries";if(N){let v=T(N.drawEntries);if(v.error)return _({result:v,stack:b})}if(R){let v=T(R.entries);if(v.error)return _({result:v,stack:b});l.includes(R.drawId)||l.push(R.drawId)}return{...C}},U=m?.entries?.find(({entryPosition:P})=>P)??(S?.drawEntries?.find(({entryPosition:P})=>P)||n?.entries?.find(({entryPosition:P})=>P));if(t&&!U&&y({flight:S,drawDefinition:n}),S||n){let P=D({flight:S,drawDefinition:n});if(P.error)return _({result:P,stack:d})}let A=m?.drawDefinitions?.map(({drawId:P})=>P)??[],E=h?.flights?.filter(P=>!A.includes(P.drawId))||[];for(let P of E){let N=P&&D({flight:P});if(N?.error)return _({result:N,stack:d})}let M=h?.flights?.length===1&&(m?.drawDefinitions?.length??0)<=h?.flights?.length;if(!S&&!n&&i&&RU.includes(i))return{error:IE};if(!S&&!n||i===io||c&&M){let P=T(m?.entries);if(P?.error)return _({result:P,stack:d});let N;if(i===io&&(h?.flights?.every(R=>{let b=T(R.drawEntries);return b.error?(N=b.error,!1):(R.drawEntries=R.drawEntries.filter(({participantId:v})=>!o.includes(v)),!0)}),m?.drawDefinitions?.every(R=>{let b=T(R.entries);return b.error?(N=b.error,!1):(R.entries=R.entries?.filter(({participantId:v})=>!o.includes(v)),!0)})),N)return _({result:{error:N},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{...C}}function Uo({requireTimeStamp:t,scaleAttributes:e,participant:r}){if(!r)return{error:Gi};if(!It(e))return{error:k};if(r.timeItems||(r.timeItems=[]),Array.isArray(r.timeItems)){let{accessor:n,scaleType:o,eventType:i,scaleName:s}=e,a=[Ti,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!==Ti)return{error:rp};let g=(n&&Is({element:u.itemValue,accessor:n}))?.value||u.itemValue,I={eventType:d,scaleDate:u.itemDate,scaleValue:g,scaleName:l,scaleType:m};return{...C,scaleItem:I}}}return{...C,scaleItem:void 0}}function av({publishedSeeding:t,usePublishState:e,withSeeding:r,participant:n,event:o}){let i={},s=m=>[Ti,So,o.eventType,m].join("."),a=Object.assign({},...(n.timeItems||[]).filter(({itemType:m})=>m.split(".")[1]===So).map(({itemType:m,itemValue:d})=>({[m]:d}))),c=(t?.stageSeedingScaleNames&&Object.values(t?.stageSeedingScaleNames)||Array.isArray(t?.seedingScaleNames)&&t.seedingScaleNames||[]).map(s),u=qt(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:So,scaleName:g},h=Uo({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 cv({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({},...Ef(m??[])):{},l=Object.assign(d,{entryPosition:p,entryStatus:c,entryStage:u,ranking:s,eventId:i});r.events[i]=rt(l,!1,!1,!0),n&&(e&&(r.events[i].seedAssignments=e),o&&(r.events[i].seedValue=o))}function aS(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===Pt||e[r].scheduleItems.push({...p,scheduledDate:Dt(p?.scheduledDate),scheduledTime:Kt(p?.scheduledTime),checkScoreHasValue:me({score:d}),matchUpStatus:n,roundPosition:o,structureId:i,matchUpType:s,roundNumber:a,matchUpId:c,potential:u,drawId:m})}function Eu(t){let e=nt(t,[{[Re]:!0}]);if(e.error)return e;let{tournamentRecord:r,status:n=yr}=t,o=`${Lo}.${Fo}`;return J(Xm({tournamentRecord:r,itemType:o})?.timeItem?.itemValue?.[n],!1,!0)}function uv(t){let{tournamentId:e}=t??{};return!!e}function jr({event:t,status:e=yr}){let r=`${Lo}.${Fo}`;return gu({itemType:r,event:t})?.timeItem?.itemValue?.[e]}function fd({drawDetails:t,drawId:e}){return t?.[e]?.publishingDetail?.published}function Ss(t){let{tournamentRecord:e,drawDefinition:r,eventIds:n,eventId:o,drawIds:i,drawId:s,event:a}=t??{};if(e&&!uv(e))return{error:k};if(o&&!a)return{error:Pr};if(Array.isArray(n)&&n?.length){let m={};for(let d of n){if(!te(d))return{error:k};let l=He({tournamentRecord:e,eventId:d})?.event;if(!l)return{error:Pr};let f=BU({event:l});m[d]=f}return{...C,publishState:m}}if(a){let m=BU({event:a}),d={};if(s)return r?{publishState:{status:{published:!!m.status.publishedDrawIds?.includes(s),drawDetail:m.status.drawDetails?.[s]},...C}}:{error:Dr};if(Array.isArray(i)&&i?.length){let l=a.drawDefinitions?.map(uu)??[];for(let f of i){if(!te(f))return{error:k};if(!l.includes(f))return{error:Dr};d[f]={status:{published:!!m.status.publishedDrawIds.includes(f),drawDetail:m.status.drawDetails?.[f]}}}}else d=m;return{...C,publishState:d}}let c=[],u=!1,p={};for(let m of e?.events??[]){let d=BU({event:m});p[m.eventId]=d,d.status.published&&(c.push(m.eventId),u=!0);for(let{drawId:l}of m.drawDefinitions??[]){let f=d.status?.publishedDrawIds?.includes(l);f&&(p[l]={status:{published:f}})}}if(e){let m=Eu({tournamentRecord:e});p.tournament=m??{},(m?.orderOfPlay?.published||m?.participants?.published)&&(u=!0),p.tournament.status={published:u,publishedEventIds:c}}return{...C,publishState:p}}function BU({event:t}){let e=jr({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(uu)||[])n[i]||(n[i]={publishingDetail:{published:!1}});let o=n&&Object.keys(n).length&&Object.keys(n).filter(i=>fd({drawDetails:n,drawId:i}))||e.drawIds;return{status:{published:o&&o.length>0,publishedDrawIds:o,publishedSeeding:r,drawDetails:n}}}function Uu(t,e){return(t||"").localeCompare(e||"")}function pv({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===Mt&&(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:D,collectionId:U,matchUpType:A,winningSide:E,matchUpId:M,schedule:P,eventId:N,drawId:R,sides:b}=t,v=i&&b?.length===2&&Object.assign({},...b.map(({sideNumber:O},x)=>{let F=b[1-x].participantId;return O&&{[O]:F}}).filter(Boolean));for(let O of b){let{participantId:x,sideNumber:F,bye:L}=O;if(L)continue;let w=E===F,B=H=>{let q=o[H]?.participant,$=q?.participantType,V=[{participantId:H,participantType:$}];if($!==fn)for(let K of q?.individualParticipantIds||[]){let z=o[K]?.participant;V.push({participantType:z?.participantType,participantId:K})}return V},G=(H,q)=>{if(s){if(o[H].matchUps[M]={participantWon:w,matchUpType:A,structureId:f,sideNumber:F,matchUpId:M,eventId:N,drawId:R,stage:I},i){let $=B(q);o[H].matchUps[M].opponentParticipantInfo=$}U&&(o[H].matchUps[M].collectionId=U)}i&&q&&(o[H].opponents[q]={participantId:q,matchUpId:M,eventId:N,drawId:R}),h&&pv({finishingPositionRange:u,participantMap:o,participantWon:w,finishingRound:p,matchUpStatus:m,participantId:H,stageSequence:d,roundNumber:l,structureId:f,matchUpId:M,drawId:R,stage:I}),(r||e)&&aS({participantMap:o,participantId:H,matchUpStatus:m,roundPosition:T,matchUpType:A,roundNumber:l,structureId:f,matchUpId:M,schedule:P,drawId:R,score:g})},W=({participant:H,partnerParticipantId:q})=>{let $=(V,K)=>{V&&(V.partnerParticipantIds||(V.partnerParticipantIds=[]),V.partnerParticipantIds.includes(K)||V.partnerParticipantIds.push(K))};c&&$(H?.draws?.[R],q),a&&$(H?.events?.[N],q),s&&$(H?.matchUps?.[M],q)};if(x&&o[x]){let H=v?.[F];G(x,H);let q=o[x]?.participant.participantType===lt,$=o[x]?.participant.individualParticipantIds||[];if(y){if(n){let V=K=>o[K].matchUps[y]={participantWon:S===F,matchUpId:y,matchUpType:Ht,sideNumber:F};V(x),$.forEach(V)}if(c&&!o[x].draws[R]){let V=D.find(Y=>Y.sideNumber===F)?.participant?.participantId,K=o[V]?.draws?.[R]?.entryStatus,z=Y=>o[Y].draws[R]={entryStatus:K,eventId:N,drawId:R};z(x),$.forEach(z)}}if(q&&($.forEach(V=>o[V]&&G(V,H)),$.forEach((V,K)=>{let z=$[1-K],Y=o[V];Y&&W({participant:Y,partnerParticipantId:z})}),a&&D)){let V=D.find(K=>K.sideNumber===F)?.participant?.participantId;if(V){let K=o[V]?.events[N];K?(o[x].events[N]={...K},$.forEach(z=>o[z].events[N]={...K})):console.log("Missing teamEntry",{eventId:N,teamParticipantId:V})}}if(E){let V=K=>{w?(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===Mt&&(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===Mt&&(o[K].counters[A].defaults+=1,o[K].counters.defaults+=1))};V(x),$.forEach(V)}}}}function mv(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:[]},D={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},U=[],A={},E=[],M={},P={},N={},R=({eventType:b,scaleNames:v,participantId:O})=>a[O]?.participant?.rankings?.[b]?.find(x=>v.includes(x.scaleName))?.scaleValue;for(let b of o?.events||[]){if(e?.eventIds&&!e.eventIds.includes(b.eventId))continue;let{drawDefinitions:v=[],extensions:O=[],eventType:x,eventName:F,category:L,entries:w,eventId:B,gender:G}=b,{flightProfile:W}=Wt({event:b}),H=W?.flights??[],q=Ss({event:b}).publishState;q&&(M[B]=q);let $=q?.status?.publishedSeeding;if(h||I||u){let K=r?Object.assign({},...Ef(O??[])):{};P[B]={...K,eventName:F,eventType:x,category:L,eventId:B,gender:G};let z=[L?.categoryName,L?.ageCategoryCode].filter(Boolean);for(let Y of w){let{participantId:Z}=Y;if(!Z||!a[Z])continue;let Q=R({eventType:x,scaleNames:z,participantId:Z}),st,St;if(I){let Ut=a[Z].participant;({seedAssignments:st,seedValue:St}=av({publishedSeeding:$,usePublishState:i,withSeeding:I,participant:Ut,event:b}))}let it=Ut=>{if(a[Ut]?.events?.[B])return;let Ue=a[Ut];cv({convertExtensions:r,seedAssignments:st,participant:Ue,withSeeding:I,seedValue:St,eventId:B,ranking:Q,entry:Y})};it(Z),(a[Z].participant.individualParticipantIds||[]).forEach(it)}}let V=M?.[B]?.publishedSeeding;if(S||u||I){let K=Y=>Y?Object.assign({},...Y.map(({participantId:Z,seedValue:Q,seedNumber:st})=>({[Z]:{seedValue:Q,seedNumber:st}}))):void 0,z=pt([...v.map(uu),...H.map(uu)]);for(let Y of z){let Z=v.find(Yt=>Yt.drawId===Y),Q=H?.find(Yt=>Yt.drawId===Y),st=Z?.entries||Q?.drawEntries,{structures:St=[],drawOrder:it,drawName:jt,drawType:Ut}=Z??{},Ue=Q?.flightNumber,Se=[L?.categoryName,L?.ageCategoryCode].filter(Boolean),Te=(Z?.structures||[]).sort((Yt,$e)=>Ai(Yt,$e)).map(({structureId:Yt,structures:$e})=>[Yt,...($e||[]).map(({structureId:Gr})=>Gr)]).flat(1/0),Er,br,ne,_t,Rt=0,xt=St.filter(({stage:Yt,stageSequence:$e})=>Yt===et&&$e===1||Yt===ct).flatMap(Yt=>{let{seedAssignments:$e,stageSequence:Gr,stage:qr}=Yt,{positionAssignments:vr}=Ct({structure:Yt});return qr===et?(Rt=vr?.length??0,ne=vr,_t=$e):Gr===1&&(Er=vr,br=$e),vr}).map(({participantId:Yt})=>Yt).filter(Boolean),de=K(_t),oe=K(br),ge=Z?st.filter(({participantId:Yt})=>xt.includes(Yt)):st,ye=!i||V?.published&&(V?.drawIds?.length===0||V?.drawIds?.includes(Y));for(let Yt of ge){if(!a[Yt.participantId])continue;let{entryStatus:$e,entryStage:Gr,entryPosition:qr,participantId:vr}=Yt,Oe=R({participantId:vr,scaleNames:Se,eventType:x}),fr=un=>{if(!a[un]||a[un].draws?.[Y])return;let En=I&&ye,tr=En?{}:void 0,ke=En?de?.[vr]?.seedValue||de?.[vr]?.seedNumber:void 0,Or=ke?de?.[vr]:void 0,es=En?oe?.[vr]?.seedValue||oe?.[vr]?.seedNumber:void 0,vn=es?oe?.[vr]:void 0;tr&&ke&&(tr[et]=Or),tr&&es&&(tr[ct]=vn);let ma=ke||es;ma&&(a[un].participant.seedings[x]||(a[un].participant.seedings[x]=[]),Or&&a[un].participant.seedings[x].push({...Or,scaleName:Y}),vn&&a[un].participant.seedings[x].push({...vn,scaleName:Y}),tr&&(a[un].events[B].seedAssignments||(a[un].events[B].seedAssignments={}),Object.keys(tr).forEach(mi=>a[un].events[B].seedAssignments[mi]=tr[mi]))),(S||u)&&(a[un].draws[Y]=rt({seedAssignments:tr,entryPosition:qr,entryStatus:$e,entryStage:Gr,seedValue:ma,eventId:B,ranking:Oe,drawId:Y},!1,!1,!0))};[tn,Pi].includes($e)||(fr(vr),(a[vr].participant.individualParticipantIds||[])?.forEach(fr))}let cr=(Z?.structures??[]).reduce((Yt,$e)=>(Yt.includes($e.stage)||Yt.push($e.stage),Yt),[]),qe=(Z?.links??[]).length;N[Y]={qualifyingPositionAssignments:Er,qualifyingSeedAssignments:br,mainPositionAssignments:ne,qualifyingSeedingMap:oe,mainSeedAssignments:_t,orderedStructureIds:Te,mainSeedingMap:de,flightNumber:Ue,linksCount:qe,drawOrder:it,drawName:jt,drawType:Ut,drawSize:Rt,drawId:Y,stages:cr}}}if(u||m||d||l||f||g||S){let K=!!m||c,z=qn({afterRecoveryTimes:!!m,policyDefinitions:n,tournamentRecord:o,inContext:!0,contextProfile:s,participantMap:a,nextMatchUps:K,event:b})?.matchUps??[];for(let Y of z){let{finishingPositionRange:Z,potentialParticipants:Q,tieMatchUps:st=[],sides:St=[],winningSide:it,matchUpType:jt,matchUpId:Ut,eventId:Ue,drawId:Se,collectionId:Te,stageSequence:Er,finishingRound:br,matchUpStatus:ne,roundPosition:_t,roundNumber:Rt,structureId:xt,schedule:de,score:oe,stage:ge}=Y;A[Ut]=Y;let ye={finishingPositionRange:Z,finishingRound:br,stageSequence:Er,roundPosition:_t,collectionId:Te,roundNumber:Rt,structureId:xt,schedule:de,eventId:Ue,drawId:Se,score:oe,stage:ge};HU({...ye,...D,matchUpStatus:ne,winningSide:it,matchUpType:jt,matchUpId:Ut,sides:St});for(let cr of st){let{winningSide:qe,sides:Yt=[],matchUpId:$e,matchUpStatus:Gr,matchUpType:qr}=cr;HU({...ye,...D,winningSide:qe,tieWinningSide:it,matchUpTieId:Ut,matchUpId:$e,sides:Yt,matchUpSides:St,matchUpStatus:Gr,matchUpType:qr})}Array.isArray(Q)&&(K||m||p)&&Q.flat().map(ht).filter(Boolean)?.forEach(qe=>{y(qe)?.forEach($e=>{a[$e]&&(a[$e].potentialMatchUps[Ut]=rt({tournamentId:o?.tournamentId,matchUpId:Ut,eventId:Ue,drawId:Se}))}),(m||p)&&aS({potential:!0,participantMap:a,participantId:qe,matchUpStatus:ne,roundPosition:_t,structureId:xt,matchUpType:jt,roundNumber:Rt,matchUpId:Ut,schedule:de,drawId:Se,score:oe})})}E.push(...z)}}if(l||u||m){let b=Object.values(a);for(let v of b){let{wins:O,losses:x,[Bt]:{wins:F,losses:L},[kt]:{wins:w,losses:B}}=v.counters,G=(W,H,q)=>{let $=H+q,V=H,K=$&&V/$;v.statistics[W]={denominator:$,numerator:V,statValue:K,statCode:W}};if(l&&(G(Zm,O,x),G(`${Zm}.${Bt}`,F,L),G(`${Zm}.${kt}`,w,B)),u){let W=(H=[])=>Math.abs(H[0]-H[1]);for(let H of Object.keys(v.draws)){let{orderedStructureIds:q=[],flightNumber:$}=N[H]||{};if(v.structureParticipation&&q.length){let V,K=0,z=q.map(Y=>{let Z=v.structureParticipation[Y];if(!Z)return;V||(V=Z?.finishingPositionRange),W(V)>W(Z?.finishingPositionRange)&&(V=Z?.finishingPositionRange);let Q=Z.stage!==ct;return Q&&(K+=1),rt({...Z,participationOrder:Q?K:void 0,flightNumber:$})}).filter(Boolean);v.draws[H]&&(v.draws[H].finishingPositionRange=V,v.draws[H].structureParticipation=z)}}}if(m){let W=It(m)?m.scheduledMinutesDifference:0,H=v.scheduleItems||[],q=v.potentialMatchUps||{},$=H.reduce((K,z)=>{let{scheduledDate:Y,scheduledTime:Z}=z;return K[Y]||(K[Y]=[]),Z&&K[Y].push(z),K},{});Object.values($).forEach(K=>K.sort(dh));for(let K of H){let{typeChangeTimeAfterRecovery:z,timeAfterRecovery:Y,scheduledDate:Z,scheduledTime:Q}=K,st=$[Z],St=Vt(Q);for(let it of st){if(it.matchUpId===K.matchUpId||[vt,Mt].includes(it.matchUpStatus)&&!it.checkScoreHasValue)continue;let Ue=K.matchUpType!==it.matchUpType&&z||Y,Se=K.drawId===it.drawId,Te=q[K.matchUpId]&&q[it.matchUpId],Er=Vt(it.scheduledTime),br=Math.abs(Er-St),ne=Er>=St;if((W&&!isNaN(W)?br<=W:ne&&Vt(it.scheduledTime)<Vt(Ue))&&!(Te&&Se)&&ne){let Rt=[K.matchUpId,it.matchUpId].sort(Uu).join("|");v.scheduleConflicts[Rt]={priorScheduledMatchUpId:K.matchUpId,matchUpIdWithConflict:it.matchUpId}}}}let V=v.participant.participantId;Object.keys(v.scheduleConflicts).length&&U.push(V),a[V].scheduleConflicts=v.scheduleConflicts}}}return{participantIdsWithConflicts:U,eventsPublishStatuses:M,derivedEventInfo:P,derivedDrawInfo:N,mappedMatchUps:A,participantMap:a,matchUps:E}}function Du({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=Xs(l)&&e?.events?.filter(y=>l?.includes(y.eventId))||e?.events||[],I=o&&Dk({drawEntryStatuses:o,tournamentEvents:g}),h=s&&Pk({eventEntryStatuses:s,tournamentEvents:g}),S=i!==void 0&&[!0,!1].includes(i)&&g.reduce((y,D)=>y.concat(...(D.drawDefinitions||[]).map(U=>Dh({drawDefinition:U}).allPositionedParticipantIds).filter(Boolean)),[]),T=y=>n?.reduce((D,U)=>{let{accessor:A,value:E}=U,{values:M}=Is({element:y,accessor:A});return D&&M?.includes(E)},!0);if(r=r?.filter(y=>{let D=Xr({element:y,itemType:mc})?.timeItem?.itemValue,{participantRoleResponsibilities:U,participantType:A,participantRole:E,participantId:M,person:P}=y,N=Array.isArray(f)&&f?.length&&P?.sex&&f.includes(P.sex);return d?f&&N||i&&S.includes(M)||i===!1&&!S.includes(M)||I?.includes(M)||h?.includes(M)||p?.includes(M)||m&&D===m||u&&A&&Xs(u)&&u.includes(A)||a&&E&&Xs(a)&&a.includes(E)||c&&Xs(U)&&Xs(c)&&c.find(R=>U?.includes(R))||n?.length&&Xs(n)&&T(y):(!f||N)&&(i===void 0||i&&S.includes(M)||i===!1&&!S.includes(M))&&(!I||I.includes(M))&&(!h||h.includes(M))&&(!p||p.includes(M))&&(!m||D===m)&&(!u||A&&Xs(u)&&u.includes(A))&&(!a||E&&Xs(a)&&a.includes(E))&&(!c||Xs(U)&&Xs(c)&&c.find(R=>U?.includes(R)))&&(!n?.length||Xs(n)&&T(y))}),g.length&&l){let y=g.filter(D=>l.includes(D.eventId)).map(D=>{let U=(D.entries||[]).map(E=>E.participantId);if(se(Hn)(D.eventType))return U;let A=(e?.participants??[]).filter(E=>U.includes(E.participantId)).map(E=>E.individualParticipantIds).flat(1);return U.concat(...A)}).flat(1);r=r?.filter(D=>y.includes(D.participantId))}return r}function Xs(t){return t&&Array.isArray(t)&&t.length}function Dk({drawEntryStatuses:t,tournamentEvents:e}){let r=({entryStatus:n})=>Array.isArray(t)?t.includes(n):!0;return pt(e.reduce((n,o)=>{let{flightProfile:i}=Wt({event:o}),s=i?.flights?.map(({drawEntries:c})=>Array.isArray(c)?c.filter(r).map(ht):[]).flat()||[],a=o.drawDefinitions?.map(({entries:c})=>c?c.filter(r).map(ht):[])||[];return n.concat(...s,...a)},[]))}function Pk({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(ht);return r.concat(...o)},[]))}function $t(t){let{withIndividualParticipants:e,participantFilters:r={},withPotentialMatchUps:n,withRankingProfile:o,convertExtensions:i,policyDefinitions:s,withScheduleItems:a,tournamentRecord:c,scheduleAnalysis:u,withSignInStatus:p,withTeamMatchUps:m,withScaleValues:d,usePublishState:l,contextProfile:f,withStatistics:g,withOpponents:I,withMatchUps:h,internalUse:S,withSeeding:T,withEvents:y,withDraws:D,withISO2:U,withIOC:A}=t;if(!c)return{error:j};(h||o)&&rn({tournamentRecord:c});let{participantMap:E}=xh({convertExtensions:i,tournamentRecord:c,withSignInStatus:p,withScaleValues:d,internalUse:S,withISO2:U,withIOC:A}),M=mv({withMatchUps:h??o,withEvents:y??o,withDraws:D??o,withPotentialMatchUps:n,participantFilters:r,withRankingProfile:o,convertExtensions:i,withScheduleItems:a,policyDefinitions:s,tournamentRecord:c,scheduleAnalysis:u,withTeamMatchUps:m,usePublishState:l,withStatistics:g,participantMap:E,withOpponents:I,contextProfile:f,withSeeding:T}),{participantIdsWithConflicts:P,eventsPublishStatuses:N,derivedEventInfo:R,derivedDrawInfo:b,mappedMatchUps:v}=M,O=M.matchUps;E=M.participantMap;let x=u??n,F=({potentialMatchUps:q,scheduleConflicts:$,scheduleItems:V,participant:K,statistics:z,opponents:Y,matchUps:Z,events:Q,draws:st})=>{let St=Object.values(st),it=Object.values(Y);return I&&St?.forEach(jt=>{jt.opponents=it.filter(Ut=>Ut.drawId===jt.drawId)}),rt({...K,scheduleConflicts:u?Object.values($):void 0,draws:D||o?St:void 0,events:y||o?Object.values(Q):void 0,matchUps:h||o?Object.values(Z):void 0,opponents:I?it:void 0,potentialMatchUps:x?Object.values(q):void 0,statistics:g?Object.values(z):void 0,scheduleItems:a?V:void 0},!1,!1,!0)},L=new Map;for(let q of Object.keys(E))L.set(q,F(E[q]));let w=[...L.values()],G=s?.[Ws]?.participant,W=Du({participants:w,participantFilters:r,tournamentRecord:c});if(e){let q=It(e)?e:void 0;for(let $ of W)for(let V of $.individualParticipantIds??[]){$.individualParticipants||($.individualParticipants=[]);let K=L.get(V);$.individualParticipants.push(q?ji({template:q,source:K}):K)}}let H=G?W.map(q=>ji({source:q,template:G})):W;return{participantIdsWithConflicts:P,eventsPublishStatuses:N,derivedEventInfo:R,derivedDrawInfo:b,mappedMatchUps:v,participantMap:E,participants:H,...C,matchUps:O}}function Tc({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 Ts(t){let{provisionalPositioning:e,drawDefinition:r,stageSequence:n,structureId:o,stage:i}=t;if(!r)return{error:X};let{entryProfile:s}=Iu({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}=at({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=at({structureId:l.source.structureId,drawDefinition:r})?.structure;if(f?.stage===ct){let g=l.source.roundNumber,I=l.target.roundNumber,h=0;if(f.structureType===we){let S=f.structures?.length??0,T=l.source.finishingPositions?.length??0;h=S*T}else h=Et({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 _p({stage:t,drawDefinition:e}){let{entryProfile:r}=Iu({drawDefinition:e});return r?.[t]?.drawSize||0}function dv(t){let{provisionalPositioning:e,drawDefinition:r,stageSequence:n,stage:o}=t,i=_p({stage:o,drawDefinition:r}),{qualifiersCount:s}=Ts({provisionalPositioning:e,drawDefinition:r,stageSequence:n,stage:o});return i&&i-s}function WU({stage:t,drawDefinition:e}){return!!(t===Be||Kf({stage:t,drawDefinition:e})&&_p({stage:t,drawDefinition:e}))}function jU({entryStatus:t=Zr,drawDefinition:e,stageSequence:r,stage:n}){if(t===Jr)return Sb({stage:n,drawDefinition:e})?{positionsAvailable:1/0,...C}:{error:gE};let o=dv({drawDefinition:e,stageSequence:r,stage:n}),i=Tb({drawDefinition:e,stage:n}),s=Lh({entryStatus:hu,drawDefinition:e,stage:n}),a=Lh({entryStatus:Zr,drawDefinition:e,stage:n}),c=s+a,u=c>=o,p=o-c;return n!==Be&&u?{error:BI}:t===hu?s<i?{...C}:{error:BI}:{positionsAvailable:p,...C}}function cS(t){let e=nt(t,[{[Le]:!0,[rh]:!0}]);if(e.error)return e;let{suppressDuplicateEntries:r=!0,entryStatus:n=Zr,entryStageSequence:o,entryStage:i=et,ignoreStageSpace:s,drawDefinition:a,entryPosition:c,participant:u,roundTarget:p,extensions:m,extension:d,drawType:l,event:f}=t,g="addDrawEntry";if(l!==an&&!WU({stage:i,drawDefinition:a}))return _({result:{error:Li},stack:g});let I=jU({stageSequence:o,stage:i,drawDefinition:a,entryStatus:n});if(!s&&!I.success&&(!l||l!==an))return{error:I.error};if(d&&!wn({extension:d}))return _({result:{error:k},info:"Invalid extension",context:{extension:d},stack:g});let h=t.participantId||u?.participantId;if(!h)return _({result:{error:ee},stack:g});let S=n===us&&Tc({participantId:h,drawDefinition:a,entryStatus:n}),T=i===Be&&Tc({participantId:h,drawDefinition:a,entryStage:i}),y=Tc({participantId:h,drawDefinition:a}),D=n!==us&&i!==Be&&y;if(D)return r?(dt({payload:{drawId:a.drawId,eventId:f?.eventId,error:Um,participantId:h},topic:Nh}),{...C}):_({result:{error:Um},context:{participantId:h},stack:g});if(S||T)return _({context:{invalidEntry:D,invalidLuckyLoser:S,invalidVoluntaryConsolation:T},result:{error:ep},stack:g});let U=rt({entryStageSequence:o,participantId:h,entryPosition:c,entryStatus:n,entryStage:i,extensions:m});return d&&At({element:U,extension:d}),p&&At({extension:{name:"roundEntry",value:p},element:U}),a.entries||(a.entries=[]),a.entries.push(U),Ot({drawDefinition:a}),{...C}}function lv(t){let e="addDrawEntries",{suppressDuplicateEntries:r=!0,entryStatus:n=Zr,autoEntryPositions:o=!0,ignoreStageSpace:i,participantIds:s,drawDefinition:a,stageSequence:c,stage:u=et,roundTarget:p,extension:m,event:d}=t;if(!u)return{error:KA};if(!a)return{error:X};if(!Array.isArray(s))return{error:_r};if(!WU({stage:u,drawDefinition:a}))return{error:Li};if(m&&!wn({extension:m}))return _({result:{error:k},info:"Invalid extension",context:{extension:m},stack:e});let l=jU({drawDefinition:a,stageSequence:c,entryStatus:n,stage:u});if(!i&&!l.success)return{error:l.error};let f=l.positionsAvailable??0;if(!i&&u!==Be&&f<s.length)return{error:$l};let g=[],I=a.drawId,h=d?.eventId,S=s.reduce((T,y)=>{let D=n===us&&Tc({participantId:y,drawDefinition:a,entryStatus:n}),U=u===Be&&Tc({entryStage:u,drawDefinition:a,participantId:y}),A=Tc({participantId:y,drawDefinition:a});return n!==us&&u!==Be&&A&&(g.push(y),r&&dt({payload:{error:Um,participantId:y,eventId:h,drawId:I},topic:Nh})),D||U?T.concat(y):T},[]);return g.length&&r?_({context:{eventId:h,drawId:I,duplicateEntries:g},result:{error:Um},stack:e}):(s.filter(T=>T&&!S.includes(T)).forEach(T=>{let y={entryStageSequence:c,entryStage:u,participantId:T,entryStatus:n};m&&At({element:y,extension:m}),p&&At({extension:{name:Dn,value:p},element:y}),a.entries||(a.entries=[]),a.entries.push(y)}),o&&(a.entries=Kn({entries:a.entries})),Ot({drawDefinition:a}),S?.length||g?.length?{info:"some participantIds could not be added",participantIdsNotAdded:S,duplicateEntries:g,...C}:{...C})}function sg({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:No};if(!m)return{error:Pr};if(!p)return{error:on};let d=(m.entries||[]).map(ht);if(i.filter(I=>!d.includes(I)).length)return{error:qA};if(o){let I=lv({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}=Wt({event:m}),g=f?.flights.find(I=>I.drawId===p);return g?.drawEntries&&(i.forEach(I=>{let h=s===us&&YU({participantId:I,entryStatus:s,flight:g}),S=c===Be&&YU({participantId:I,entryStage:c,flight:g});!(s!==us&&c!==Be&&YU({flight:g,participantId:I}))&&!h&&!S&&g.drawEntries.push({participantId:I,entryStatus:s,entryStage:c})}),e&&(g.drawEntries=Kn({entries:g.drawEntries}))),{...C}}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 yc({autoEntryPositions:t=!0,participantIds:e=[],entryStatuses:r,stage:n,event:o}){let i="removeEventEntries";if(!o?.eventId)return{error:bt};if(!Array.isArray(e)||e.some(m=>!te(m)))return _({result:{error:pn},stack:i});let s=(o.drawDefinitions??[]).flatMap(m=>Oi({drawDefinition:m}).assignedParticipantIds??[]),a=(r?.length&&o.entries?.filter(m=>m.entryStatus&&r.includes(m.entryStatus))||[]).map(ht).filter(m=>!s.includes(m)),c=(n&&o.entries?.filter(m=>m.entryStage&&m.entryStage===n)||[]).map(ht).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=qt(a,c):a.length?e=a:c.length&&(e=c),e?.length&&s.some(m=>e.includes(m)))return _({result:{error:ws},stack:i});if(!e?.length)return{...C,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=Kn({entries:o.entries}));let{flightProfile:p}=Wt({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))}),{...C,participantIdsRemoved:u}}var qU={[ze]:{policyName:"matchUpActionsDefault",enabledStructures:[{stages:[],stageSequences:[],enabledActions:[],disabledActions:[]}],participants:{enforceCategory:!0,enforceGender:!0},processCodes:{substitution:["RANKING.IGNORE","RATING.IGNORE"]},substituteAfterCompleted:!1,substituteWithoutScore:!1}},ys=qU;function ao(t){let{suppressDuplicateEntries:e=!0,entryStatus:r=Zr,autoEntryPositions:n=!0,enforceGender:o=!0,entryStageSequence:i,policyDefinitions:s,entryStage:a=et,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:_r},stack:I});let h=pt(t.participantIds??[]);if(!g)return{error:bt};if(!h?.length)return _({result:{error:No},stack:I});if(!g?.eventId)return{error:Pr};let S=yt({tournamentRecord:c,event:g}).appliedPolicies??{},T=s?.[ze]??S?.[ze]??ys[ze],y=(o??T?.participants?.enforceGender)!==!1,D=[],U=[];if(d&&(!Array.isArray(d)||!d.every(x=>wn({extension:x})))||l&&!wn({extension:l}))return _({context:rt({extension:l,extensions:d}),result:{error:k},info:"Invalid extension(s)",stack:I});let A=!!c,E=[],M,P=c?.participants?.filter(x=>{if(!h.includes(x.participantId))return!1;let F=se(Bt)(g.eventType)&&x.participantType===Tt&&!Qs(r),L=g.eventType===kt&&x.participantType===lt;return F&&(!g.gender||!y||[Cr,Mn].includes(g.gender)||g.gender===x.person?.sex)||L&&!Qs(r)||g.eventType===kt&&x.participantType===Tt&&Qs(r)?!0:F&&g.gender&&y&&![Cr,Mn].includes(g.gender)&&g.gender!==x.person?.sex?(E.push({participantId:x.participantId,sex:x.person?.sex}),!1):g.eventType===Ft&&(x.participantType===Ft||Qs(r)&&x.participantType===Tt)}).map(x=>x.participantId)??[],N=h.filter(x=>!A||P.includes(x));g.entries||(g.entries=[]);let R=g.entries.map(x=>x.participantId||x.participant?.participantId);if(N.forEach(x=>{if(!R.includes(x)){let F=rt({participantId:x,entryStatus:r,entryStage:a,extensions:d});l&&At({element:F,extension:l}),m&&At({extension:{name:Dn,value:m},element:F}),i&&(F.entryStageSequence=i),D.push(F.participantId),g.entries?.push(F)}}),f&&!Qs(a)){let x=sg({participantIds:N,suppressDuplicateEntries:e,autoEntryPositions:n,entryStageSequence:i,ignoreStageSpace:u,drawDefinition:p,entryStatus:r,roundTarget:m,entryStage:a,extension:l,drawId:f,event:g});x.error&&(M=x.error)}if(g.eventType&&[fi,Kr].includes(g.eventType)){let x=(g.entries||[]).map(G=>G.participantId),F=(g.entries||[]).filter(G=>Qs(G.entryStatus)).map(G=>G.participantId),w=(c?.participants??[]).filter(G=>x.includes(G.participantId)&&G.participantType&&[lt,Ft].includes(G.participantType)).map(G=>G.individualParticipantIds).flat(1/0),B=F.filter(G=>w.includes(G));B.length&&(U.push(...B),yc({participantIds:B,autoEntryPositions:!1,event:g}))}if(N.length!==h.length)return _({context:{mismatchedGender:E,gender:g.gender},result:{error:_r},stack:I});n&&(g.entries=Kn({entries:g.entries||[]}));let v=D.length,O=U.length;return _({result:{...C,addedEntriesCount:v,removedEntriesCount:O},stack:I,info:M})}var $U="ADMINISTRATION",Nk="CAPTAIN",Mk="COACH",be="COMPETITOR",KU="MEDIA",zU="MEDICAL",ag="OFFICIAL",QU="OTHER",XU="SECURITY",gd={ADMINISTRATION:$U,CAPTAIN:Nk,COACH:Mk,COMPETITOR:be,MEDIA:KU,MEDICAL:zU,OFFICIAL:ag,OTHER:QU,SECURITY:XU};function cg({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:ot},stack:i});let a=(n.participants??[]).find(m=>m.participantId===r);if(!a)return _({result:{error:Xt},stack:i});if(![Ft,Rr].includes(a.participantType))return _({result:{participantType:a.participantType,error:Sn},stack:i});let c=fv({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));ao({participantIds:l,entryStatus:tn,tournamentRecord:n,event:m})}}return u&&dt({topic:Xe,payload:{tournamentId:n.tournamentId,participants:[a]}}),{...C,...c}}function fv({individualParticipantIds:t=[],groupingParticipant:e,tournamentRecord:r,suppressErrors:n,mappedMatchUps:o,participants:i}){let s=[];if(!e)return{removed:s};let a=[],c=[];i||({participants:i,mappedMatchUps:o}=$t({withMatchUps:!0,tournamentRecord:r,withEvents:!0}));let p=i?.find(({participantId:l})=>l===e.participantId)?.events?.map(({eventId:l})=>l),m=(e.individualParticipantIds??[]).filter(l=>{let f=t?.includes(l),g=f&&i?.find(h=>h.participantId===l)?.matchUps.filter(({eventId:h})=>p.includes(h)).map(({matchUpId:h})=>o?.[h]).filter(({winningSide:h,score:S})=>h||me({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}=mt({element:S,name:bo}),y=T?.value[e.participantId];T&&y&&(T.value[e.participantId]=y.filter(U=>U.participantId!==l),At({element:S,extension:T}),Da({drawDefinition:S}));let D=Je({drawDefinition:S,inContext:!1}).matchUps??[];for(let U of D){let A=U.sides??[];for(let E of A){let M=E.lineUp??[];M.find(N=>N.participantId===l)&&(E.lineUp=M.filter(N=>N.participantId!==l),gt({tournamentId:r?.tournamentId,drawDefinition:S,matchUp:U}))}}}}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:tp}||d}function xp({participantRole:t=be,individualParticipantIds:e=[],groupingTypes:r=[fn,Rr],tournamentRecord:n}){if(!n)return{error:j};let o=n.participants??[],{participants:i,mappedMatchUps:s}=$t({withMatchUps:!0,tournamentRecord:n,withEvents:!0}),a=0;return o.filter(c=>(c.participantRole===t||!c.participantRole)&&c.participantType&&r.includes(c.participantType)).forEach(c=>{let{removed:u}=fv({groupingParticipant:c,individualParticipantIds:e,tournamentRecord:n,mappedMatchUps:s,participants:i});u&&a++}),a?C:{error:mE}}function zi(t){if(!t?.tournamentRecord)return{error:j};if(!t?.participantIds?.length)return{error:No};let{addIndividualParticipantsToEvents:e,tournamentRecord:r,participantIds:n}=t,o=r.participants?.length||0;if(!o)return{...C};let i=(r.events||[])?.filter(({eventType:l})=>l===Me).map(l=>l?.drawDefinitions?.map(({drawId:f})=>f)).flat(1/0),s=$t({participantFilters:{participantIds:n},tournamentRecord:r,withDraws:!0}).participants??[],a=()=>{let f=(fe({matchUpFilters:{drawIds:i,matchUpTypes:[kt]},tournamentRecord:r}).matchUps??[]).map(({sides:g})=>g?.map(({participantId:I})=>I)).flat().filter(Boolean);return qt(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:ws};let p={},m={};for(let l of r.events||[]){let f=yc({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===Me&&l.individualParticipantIds.some(g=>n.includes(g))&&(l.individualParticipantIds=l.individualParticipantIds.filter(g=>!n.includes(g))),f&&e&&[lt,Ft].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(xp({individualParticipantIds:n,tournamentRecord:r}),e)for(let l of r.events||[]){let g=p[l.eventId].map(I=>m[I]||[]).flat();ao({participantIds:g,entryStatus:tn,tournamentRecord:r,event:l})}return d&&dt({payload:{participantIds:n,tournamentId:r.tournamentId},topic:vf}),d?{...C,participantsRemovedCount:d}:{error:tp}}function uS({selected:t=!0,drawDefinition:e,entryStatuses:r,drawId:n,event:o,stage:i}){let s=o.entries??[];if(n){let{flightProfile:c}=Wt({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 JU({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:bt};if(!s.eventType||![fi,Kr].includes(s.eventType))return _({result:{error:Bn},stack:a});let c=e.participants??[],u=c.find(S=>S.participantId===n);if(!u)return _({result:{error:Xt},stack:a});if(!u.participantType||![lt,fn].includes(u.participantType)||u.participantType===fn&&s.eventType!==Kr||u.participantType===lt&&s.eventType!==fi)return{error:Sn};let m=(s.entries??[]).find(S=>S.participantId===n);if(!m)return{error:VI};let{stageEntries:d}=uS({selected:!1,drawDefinition:r,drawId:o,event:s,stage:i}),l=d.map(ht),f=c.filter(({participantId:S})=>l.includes(S)).map(({individualParticipantIds:S})=>S).flat().filter(Boolean),g=u.individualParticipantIds?.filter(S=>lo(S,f).length===1),I=yc({participantIds:[n],event:s});if(I.error||g?.length&&(I=ao({participantIds:g,entryStatus:tn,entryStage:m.entryStage,tournamentRecord:e,drawDefinition:r,drawId:o,event:s}),I.error))return I;let h;return t&&zi({participantIds:[n],tournamentRecord:e}).success&&(h=!0),{...C,participantRemoved:h}}function ug({removeGroupParticipant:t,tournamentRecord:e,drawDefinition:r,participantId:n,drawId:o,event:i}){return JU({removeGroupParticipant:t,tournamentRecord:e,drawDefinition:r,participantId:n,drawId:o,event:i})}function ZU(t){if(!t.tournamentRecord)return{error:j};let{participantIds:e,...r}=t,n=0,o=[];for(let i of e){let s=JU({participantId:i,...r});s.success&&(n+=1),s.error&&o.push(s.error)}return n?{destroyedCount:n,...C}:{error:o}}function Pu(t){let{tournamentRecord:e,replaceWithBye:r,drawDefinition:n,destroyPair:o,entryStatus:i,matchUpsMap:s,drawId:a}=t,c="removeDrawPositionAssignment",u=Sc(t);if(u.error)return _({result:u,stack:c});let{participantId:p}=u,{drawPosition:m,event:d,structureId:l}=t,f=yt({tournamentRecord:e,drawDefinition:n,event:d}).appliedPolicies??{};if([Jr,io].includes(i)&&p){let{tournamentRecord:h}=t,{participant:S}=Ao({tournamentRecord:h,participantId:p}),{participantType:T,individualParticipantIds:y}=S??{};if(o&&T===lt){let D=ug({tournamentRecord:h,drawDefinition:n,participantId:p,event:d});if(D.error)return _({result:D,stack:c});y&&ld({participantIds:y,tournamentRecord:h,drawDefinition:n,entryStatus:i,drawId:a,event:d})}else ld({participantIds:[p],tournamentRecord:h,drawDefinition:n,entryStatus:i,drawId:a,event:d})}if(r){let h=kr({tournamentRecord:e,drawDefinition:n,drawPosition:m,structureId:l,matchUpsMap:s,event:d});if(h.error)return _({result:h,stack:c})}let{structure:g}=at({drawDefinition:n,structureId:l});return zm({structure:g,drawPositions:[m]}),mu({appliedPolicies:f,drawDefinition:n,positionAction:{name:"removeDrawPositionAssignment",replaceWithBye:r,drawPosition:m,entryStatus:i,structureId:l}}),u}function tD(t){return Object.assign(t,{entryStatus:io}),Pu(t)}function pS(t){return te(t)?t.split(" ").map(e=>e.split("").map((r,n)=>n?r.toLowerCase():r.toUpperCase()).join("")).join(" "):t}function Ye(t){return te(t)?pS(t.replace(/_/g," ")):""}var As=({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??Nt(),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,D)=>y-D).map(y=>({drawPosition:y}))),S},In=As;function pg({structureName:t=Ye(Be),structureAbbreviation:e,drawDefinition:r,matchUpType:n,structureId:o}){if(!r)return{error:X};let i=In({stage:Be,structureAbbreviation:e,structureName:t,matchUps:[],structureId:o,matchUpType:n});return r.structures||(r.structures=[]),r.structures.push(i),Ot({drawDefinition:r,structureIds:[i.structureId]}),{...C}}function mg({drawPositions:t}){if(!t?.length)return{error:za};let e=o=>t.filter(i=>i!==o).map(i=>[o,i]),r=[].concat(...(t??[]).map(e)),n=pt(r.map(dg)).map(o=>o.split("|").map(i=>+i));return{groupMatchUps:r,uniqueMatchUpGroupings:n}}function dg(t=[]){return!Array.isArray(t)||!t.length?"":[...t].sort(ae).join("|")}function eD({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 dg(l)}))}function Rk({rounds:t,hash:e}){return t?.length?t?.reduce((r,n,o)=>n.includes(e)?o+1:r,void 0):{error:ot}}var gv={getRoundRobinGroupMatchUps:mg,determineRoundNumber:Rk,drawPositionsHash:dg,groupRounds:eD};function Oa(t){let{groupNameBase:e="Group",playoffAttributes:r,stageSequence:n=1,structureOptions:o,appliedPolicies:i,seedingProfile:s,stage:a=et,matchUpType:c,roundTarget:u,structureId:p,groupNames:m,drawSize:d,idPrefix:l,isMock:f,uuids:g}=t,I=t.structureName??r?.["0"]?.name??Ye(et),{groupCount:h,groupSize:S}=Ck({structureOptions:o,appliedPolicies:i,drawSize:d}),T=Vs,y,D=tt(1,h+1).map(A=>{let E=bk({groupSize:S,structureOrder:A,matchUpType:c,drawSize:d,idPrefix:l,isMock:f});y=Array.isArray(E)?Math.max(...E.map(({roundNumber:P})=>P??0)):0;let M=m?.[A-1]??`${e} ${A}`;return As({structureId:g?.pop(),structureType:dp,finishingPosition:T,structureOrder:A,structureName:M,matchUps:E})}),U=As({structureId:p??g?.pop(),structureType:we,finishingPosition:T,seedingProfile:s,structureName:I,stageSequence:n,structures:D,stage:a});return u&&At({extension:{name:Dn,value:u},element:U}),{structures:[U],maxRoundNumber:y,groupCount:h,links:[],groupSize:S,...C}}function Ck({appliedPolicies:t,structureOptions:e,drawSize:r}){let n=e?.groupSize,o=e?.groupSizeLimit||8,{validGroupSizes:i}=wp({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 wp(t){let{groupSizeLimit:e=10,drawSize:r=0}=t??{},n=tt(3,e+1).filter(o=>{let i=Math.ceil(r/o),s=i*o-r,a=Math.ceil(r/i),c=Math.ceil(s/i);return(!s||s<o)&&a===o&&a>=3&&c<2});return{...C,validGroupSizes:n}}function bk({structureOrder:t,matchUpType:e,groupSize:r,drawSize:n,idPrefix:o,isMock:i,uuids:s}){let a=(t-1)*r,c=tt(1+a,r+1+a),u=mg({drawPositions:c}).uniqueMatchUpGroupings??[],p=eD({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=dg(f),I=d(g),h=[1,n],S=vk({structureOrder:t,drawPositions:f,roundNumber:I,idPrefix:o,uuids:s}),T={matchUpStatus:I?zt:Pt,matchUpType:e,finishingPositionRange:{winner:h,loser:h},drawPositions:f,roundNumber:I,matchUpId:S};return i&&(T.isMock=!0),T}}function vk({structureOrder:t,drawPositions:e,roundNumber:r,idPrefix:n,uuids:o}){return n?`${n}-${t}-${r}-DP-${e.join("-")}`:o?.pop()||Nt()}function lg(t){let{roundRobinGroupsCount:e,participantsCount:r,cluster:n}=t;if(!ft(r))return{seedBlocks:void 0,..._({result:{error:k},context:{participantsCount:r},stack:"getSeedBlocks"})};let o=os(r);if(e){let l=Math.min(e,o),f=[],g=1;for(tt(0,l).forEach(()=>{f.push([g]),g++});g<o;){let I=tt(g,g+l);g+=l,f.push(I)}return{...C,seedBlocks:f}}let i=tt(1,o+1),s=[],a=o/2;for(;a>1;){let l=Ae(i,a),f=l.length;l.forEach((g,I)=>{let h,S=I<f/2,T=I%2===0,y=g[0],D=g[g.length-1];n&&f>4?f===8?h=S?D:y:h=T?y:D:h=S?y:D,xe(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=tt(0,20).map(l=>Math.pow(2,l));u.unshift(1);let p=u.indexOf(o),m=0,d=[];return tt(0,p).forEach(l=>{d.push(s.slice(m,m+u[l])),m+=u[l]}),{...C,seedBlocks:d}}function fg({roundRobinGroupsCount:t,drawSize:e}){let r="getSeedGroups";if(!ft(e))return{seedGroups:void 0,..._({result:{error:k},context:{drawSize:e},stack:r})};if(t){if(!ft(t))return{seedGroups:void 0,..._({context:{roundRobinGroupsCount:t},result:{error:k},stack:r})};let n=1,o=Math.floor(e/t);return{seedGroups:tt(0,o).map(()=>{let s=tt(n,n+t);return n+=t,s})}}else{let{seedBlocks:n}=lg({participantsCount:e,roundRobinGroupsCount:t}),o=0;return{seedGroups:(n||[]).map(s=>(s||[]).map(()=>(o+=1,o)))}}}function mS({roundRobinGroupsCount:t,participantsCount:e}){if(t){let{validGroupSizes:o}=wp({drawSize:e});if(!o?.map(a=>Math.ceil(e/a))?.includes(t))return _({context:{roundRobinGroupsCount:t},result:{error:k}})}let{seedGroups:r}=fg({drawSize:e,roundRobinGroupsCount:t}),n=r?.map(o=>Math.min(...o))||[];return{...C,seedingThresholds:n}}function Ac(t){if(!t)return 1/0;if(ft(t))return ut(t);let e=t.split("-")[0];return ft(e)?ut(e):1/0}function Ok({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(ae),e.reverse(),e}function Iv({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 hv({positioning:t,size:e}){let r=Ok({size:e}),n=[],o=[],i=d=>d[0],s=d=>d[d.length-1],a=(d,l)=>(t&&[Qc,gi].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=tt(1,e+1);for(let d of r)if(d===1){let l=Ae(m,2),f=l.map(c).filter(Boolean);f.length&&n.push(f);let g=l.flatMap(u).filter(Boolean);g.length&&n.push(g)}else{let f=Ae(m,d).map(p).filter(Boolean);f.length&&n.push(f)}return{divisions:r,divisionGroupings:n}}function Es({provisionalPositioning:t,returnAllProxies:e,appliedPolicies:r,seedingProfile:n,drawDefinition:o,allPositions:i,structure:s}){let a=[];if(!s)return{error:di};let{matchUps:c,roundMatchUps:u}=Et({matchUpFilters:{roundNumbers:[1]},provisionalPositioning:t,structure:s}),{seedAssignments:p}=en({provisionalPositioning:t,returnAllProxies:e,drawDefinition:o,structure:s}),{positionAssignments:m}=le({structure:s}),d=m?.length,l=p?.length??0,f=[],I=Object.keys(u).map(L=>parseInt(L)).sort((L,w)=>L-w).map(L=>{let w=u[L].map(G=>G.drawPositions).flat(1/0).filter(Boolean),B=w.filter(G=>!f.includes(G));return f=f.concat(...w),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(w=>w<=l).length),{stage:D,structureType:U,roundLimit:A}=s,E=U===we,M=!E&&I?.length,P=!E&&D===ct&&A,N=y.flat(1/0),R=M?N?.length:0,b=i?d:l,v=ud({drawDefinition:o,structure:s,matchUps:c}),O=v?0:!M&&b||b&&N.length<b&&b-N.length||0;if(P){let L=s?.matchUps?s.matchUps.filter(({roundNumber:B})=>B===s.roundLimit).length:0,w=h.length/L;if(!M){let B=Fp(n),G=Ae(h,w),W=1,H=tt(0,G[0].length).map(()=>{let q=tt(W,W+G.length);return W+=G.length,q});({validSeedBlocks:a}=Sv({drawPositionBlocks:G,nonRandom:n?.nonRandom,positioning:B,seedGroups:H}))}}else E?{validSeedBlocks:a}=_k({nonRandom:n?.nonRandom,seedingProfile:n,structure:s}):M?a=y.map(L=>({seedNumbers:L,drawPositions:L})):v&&Ae(h,2).map((w,B)=>({drawPositions:[w[0]],seedNumbers:[B+1]})).forEach(w=>a.push(w));if(!E&&!v&&!P){let{blocks:L}=xk({drawPositionOffset:S,seedNumberOffset:R,seedCountGoal:O,seedingProfile:n,baseDrawSize:T});L.forEach(w=>a.push(w))}let F=a.flatMap(L=>L.drawPositions).reduce((L,w)=>h?.includes(w)&&L,!0);return!v&&!M&&!E&&!F?{error:HA,validSeedBlocks:[],isContainer:E,isFeedIn:M}:{isLuckyStructure:v,validSeedBlocks:a,isContainer:E,isFeedIn:M}}function _k({seedingProfile:t,structure:e,nonRandom:r}){let n=e.structures||[],o=n.length,i=Ct({structure:e})?.positionAssignments,s=Fp(t),a=i?.length??0,{seedGroups:c}=fg({roundRobinGroupsCount:o,drawSize:a}),u=n.map(p=>Ct({structure:p}).positionAssignments?.map(m=>m.drawPosition));return Sv({drawPositionBlocks:u,positioning:s,seedGroups:c,nonRandom:r})}function Sv({drawPositionBlocks:t,positioning:e,seedGroups:r,nonRandom:n}){let o=[],{divisionGroupings:i}=hv({size:r.length,positioning:e}),s=[];return r.forEach((a,c)=>{let u=Iv({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!==gi?f=n?f:lr(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 xk(t){let{drawPositionOffset:e=0,roundRobinGroupsCount:r,seedNumberOffset:n=0,seedingProfile:o,seedCountGoal:i,baseDrawSize:s}=t,a=1,c=[],{seedBlocks:u}=lg({cluster:Fp(o)===Qc,participantsCount:s,roundRobinGroupsCount:r});a=0;for(let m of u){if(a+1>i)break;let d=m.map(f=>f+e),l=p(a+1,m.length).map(f=>+f+n);a+=m.length,c.push({drawPositions:d,seedNumbers:l})}return{blocks:c};function p(m,d){return Array.from(new Array(d),(l,f)=>f+m)}}function Lp({appliedPolicies:t,drawDefinition:e,seedBlockInfo:r,drawPosition:n,structureId:o,seedNumber:i}){let{structure:s}=at({drawDefinition:e,structureId:o});t||(t=yt({drawDefinition:e}).appliedPolicies);let a=r?.validSeedBlocks;return!a&&s&&(a=Es({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 dS(t){let{provisionalPositioning:e,drawDefinition:r,seedingProfile:n,seedBlockInfo:o,structureId:i,randomize:s}=t,{structure:a}=at({drawDefinition:r,structureId:i}),{seedAssignments:c}=en({returnAllProxies:t.returnAllProxies,provisionalPositioning:e,drawDefinition:r,structure:a}),{positionAssignments:u}=le({structure:a}),m=u?.filter(w=>w.participantId??w.bye??w.qualifier)?.map(w=>w.drawPosition).filter(Boolean),{appliedPolicies:d}=yt({drawDefinition:r}),g=(o?.validSeedBlocks||a&&Es({returnAllProxies:t.returnAllProxies,provisionalPositioning:e,appliedPolicies:d,drawDefinition:r,seedingProfile:n,structure:a})?.validSeedBlocks||[]).filter(w=>w.drawPositions.filter(G=>!m?.includes(G)).length)[0],I=c?.map(w=>w.participantId).filter(Boolean),h=u?.map(w=>w.participantId).filter(Boolean),S=I?.filter(w=>h?.includes(w)),T=I?.filter(w=>!h?.includes(w)),y=c?.filter(w=>T?.includes(w.participantId)),D=c?.filter(w=>!w.participantId),A=(y?.length&&y.length>0?y.length:D?.length??0)&&g?.drawPositions.filter(w=>!m?.includes(w))||[],E=s?lr(A):A,M=[],P=E.map(()=>{let B=L(y,M)?.participantId;return B&&M.push(B),B}).filter(Boolean),N=c?.filter(w=>S?.includes(w.participantId)).map(w=>w.seedNumber),b=(g?.seedNumbers||[]).filter(w=>!N?.includes(w)),v=c?.filter(w=>b.includes(w.seedNumber)).map(w=>w.participantId),O=d?.seeding?.duplicateSeedNumbers;return{nextSeedBlock:g,unplacedSeedParticipantIds:(O!==void 0?O:!0)?P:v,unplacedSeedNumbers:b,unfilledPositions:E,unplacedSeedAssignments:y};function L(w,B){let G=w.filter($=>!B.includes($.participantId)),W=Math.min(...G.map($=>Ac($.seedValue))),H=G.filter($=>Ac($.seedValue)===W);return lr(H).pop()}}function Fp(t){if(typeof t=="string")return t;if(typeof t=="object")return t.positioning}function Js({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}=at({drawDefinition:r,structureId:s}),{positionAssignments:l}=le({structure:d}),f=en({provisionalPositioning:t,drawDefinition:r,structure:d}).seedAssignments,g=f.map(U=>U.seedNumber),I=Tc({drawDefinition:r,participantId:o});if(o&&!I)return _({result:{error:pn},context:{participantId:o},stack:m});let h=p?Wt({event:p}).flightProfile?.flights?.length:0,S=h&&h>1,y=l?.find(U=>U.participantId===o)?.drawPosition;if(y&&!Lp({drawPosition:y,drawDefinition:r,seedBlockInfo:i,structureId:s,seedNumber:a}))return _({result:{error:xl},context:{assignedDrawPosition:y},info:"invalid seed position",stack:m});g.includes(a)||f.push({seedNumber:a,seedValue:c});let D;return f.forEach(U=>{U.participantId===o&&U.seedNumber!==a&&(U.participantId=void 0),U.seedNumber===a&&(U.participantId=o,!n?.groupSeedingThreshold&&!S&&(U.seedValue=c??a),D=!0)}),D?(Ch({tournamentId:e?.tournamentId,drawDefinition:r,structure:d,eventId:u}),{...C}):_({result:{error:BA},stack:m})}function Id({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}=mt({element:o,name:bo}),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)}gt({tournamentId:n?.tournamentId,context:"updateSidLineUp",eventId:s?.eventId,drawDefinition:o,matchUp:i})}function lS(t){let{sourceMatchUp:e}=t,{targetMatchUp:r,structure:n,matchUpsMap:o,drawPosition:i}=t,s=r.roundNumber>1&&r.roundNumber-1,a=ii({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=[he,Ce].includes(d);return{pairedPreviousMatchUp:m,pairedPreviousMatchUpIsDoubleExit:l}}function Tv({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(ae).filter(Boolean),positionAdded:r,positionAssigned:n}}function fS({structureId:t,matchUpsMap:e,matchUp:r}){let n=r?.roundPosition,o=n%2?1:-1,i=n+o;return{pairedPreviousMatchUp:ii({matchUpsMap:e,structureId:t}).find(({roundNumber:c,roundPosition:u})=>c===r?.roundNumber&&u===i)}}function gS({inContextDrawMatchUps:t,sourceMatchUpStatus:e,sourceMatchUpId:r,matchUpsMap:n,matchUp:o}){let i=t.find(a=>a.matchUpId===r),{pairedPreviousMatchUp:s}=fS({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=te(p)||!isNaN(p)?{code:p}:p;return m.sideNumber===u?{...m,previousMatchUpStatus:e}:m})}}function hd({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 Ec({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=Ee({drawDefinition:o})),t||(t=re({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:Lt};let f=a?.drawMatchUps?.find(b=>b.matchUpId===c),g=f?.drawPositions??[],{positionAdded:I,positionAssigned:h,updatedDrawPositions:S}=Tv({drawPosition:s,drawPositions:g}),{positionAssignments:T}=Ct({drawDefinition:o,structure:l}),D=T?.filter(b=>S.includes(b.drawPosition))?.find(({bye:b})=>b),U=f?.matchUpStatus&&[vt,Mt].includes(f.matchUpStatus)&&S.filter(Boolean).length<2;if(i=D&&Pt||i||U&&f.matchUpStatus||f?.matchUpStatus&&[he,Ce].includes(f.matchUpStatus)&&f.matchUpStatus||zt,f&&I){t=re({inContext:!0,drawDefinition:o,matchUpsMap:a}).matchUps??[];let b=U&&hd({inContextDrawMatchUps:t,drawPosition:s,matchUpId:c})||void 0;f?.matchUpStatusCodes&&gS({inContextDrawMatchUps:t,sourceMatchUpStatus:e,sourceMatchUpId:n,matchUpsMap:a,matchUp:f}),Object.assign(f,{drawPositions:S,winningSide:b,matchUpStatus:i}),gt({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:E,loserMatchUp:M,loserTargetDrawPosition:P},targetLinks:{loserTargetLink:N}}=A,R=ii({structureId:l.structureId,matchUpsMap:a});if(h&&D){if(E)if([Pt,he,Ce].includes(i)){let b=Ec({matchUpId:E.matchUpId,inContextDrawMatchUps:t,tournamentRecord:r,drawDefinition:o,drawPosition:s,matchUpsMap:a});if(b.error)return b}else{let{structureId:b}=E;b!==l.structureId&&console.log("winnerMatchUp in different structure... participant is in different targetDrawPosition")}}else if(E&&m&&!m.feedRound){let{pairedPreviousMatchUpIsDoubleExit:b}=lS({targetMatchUp:f,drawPosition:s,matchUpsMap:a,structure:l});if(b){let v=Ec({matchUpId:E.matchUpId,inContextDrawMatchUps:t,tournamentRecord:r,drawDefinition:o,drawPosition:s,matchUpsMap:a});if(v.error)return v}}if(f?.matchUpType===Ht){let b=t?.find(({matchUpId:F})=>F===f.matchUpId),O=(b?.sides??[]).reduce((F,L,w)=>L.drawPosition===s?w:F,void 0),x=T?.find(F=>F.drawPosition===s)?.participantId;x&&O!==void 0&&Id({inContextTargetMatchUp:b,drawPositionSideIndex:O,teamParticipantId:x,tournamentRecord:r,drawDefinition:o,matchUp:f})}if(N?.linkCondition===to&&S.filter(Boolean).length===2&&!D&&R.filter(({drawPositions:O,roundNumber:x})=>x===1&&xe(O,S)).every(({matchUpStatus:O})=>[ue,Qe].includes(O))&&M){let{structureId:O}=M,x=kr({drawPosition:P,tournamentRecord:r,drawDefinition:o,structureId:O,matchUpsMap:a,event:u});if(x.error)return x}return h?{...C}:_({result:{error:Ka},context:{drawPosition:s},stack:p})}function IS({inContextDrawMatchUps:t,drawDefinition:e,assignments:r,matchUpsMap:n,structure:o}){let s=cs({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)&&qt(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 Sd({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}=Op({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 ko(t){return`${t} must be an array`}function Td({lineUp:t,tieFormat:e}){let r=[];if(!Array.isArray(t))return r.push(ko("lineUp")),{valid:!1,errors:r,error:k};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(ko("collectionAssignments")),!1):(r.push("Missing participantId"),!1)}),o=pt(t.map(ht)).length===t.length;return o||r.push("Duplicated participantId(s)"),{valid:n&&o,errors:r,error:r.length?k:void 0}}function Qi({drawDefinition:t,participantId:e,tieFormat:r,lineUp:n}){if(typeof t!="object")return{error:X};if(typeof e!="string")return{error:ee};let o=Td({lineUp:n,tieFormat:r});if(!o.valid)return o;let{extension:i}=mt({element:t,name:bo}),s=i?.value||{};return s[e]=Sd({lineUp:n}),At({element:t,extension:{name:bo,value:s}}),Da({drawDefinition:t}),{...C}}function gg({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}=IS({inContextDrawMatchUps:t,matchUpsMap:o,assignments:i,structure:s});for(let m of p)m.matchUpType===Nn&&(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&&Qi({drawDefinition:n,participantId:I,lineUp:[],tieFormat:g})}gt({tournamentId:r?.tournamentId,context:"resetLineUps",eventId:a?.eventId,drawDefinition:n,matchUp:f})}}});return{...C}}function Fn({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??Ee({drawDefinition:i}),e||({matchUps:e}=re({inContext:!0,drawDefinition:i,matchUpsMap:p}));let f=at({drawDefinition:i,structureId:m});if(f.error)return _({result:f,stack:l});let{structure:g}=f;if(!g)return{error:Lt};if(pr({structure:g}))return _({result:{error:or},stack:l});let{seedAssignments:I}=en({provisionalPositioning:t,drawDefinition:i,structure:g}),S=I?.find(N=>N.participantId===a)?.seedNumber,{appliedPolicies:T}=yt({tournamentRecord:o,drawDefinition:i,structure:g,event:d});if(S&&!Lp({seedNumber:S,appliedPolicies:T,drawDefinition:i,seedBlockInfo:c,drawPosition:u,structureId:m}))return _({result:{error:xl},context:{drawPosition:u},stack:l});let D=le({structure:g}).positionAssignments||[],U=D?.find(N=>N.drawPosition===u);if(!U)return _({result:{error:Os},context:{drawPosition:u},stack:l});if(D?.map(ht).includes(a))return _({result:{error:ws},context:{drawPosition:u},stack:l});let{containsParticipant:E,containsBye:M}=P(U);if(M){let N=Sc({inContextDrawMatchUps:e,tournamentRecord:o,drawDefinition:i,drawPosition:u,structureId:m,matchUpsMap:p,event:d});if(N.error)return _({result:N,stack:l})}if(E&&U.participantId!==a){let{activeDrawPositions:N}=ba({drawDefinition:i,structureId:m});if(N.includes(u))return _({result:{error:Xu},stack:l});gg({assignments:[U],inContextDrawMatchUps:e,tournamentRecord:o,drawDefinition:i,matchUpsMap:p,structure:g})}if(U.participantId=a,r&&(U.qualifier=!0),(g?.stageSequence||0)>1||g.stage&&[Ve,pe].includes(g.stage)){let N=g.stage===ct?ct:et,v=(i.structures?.find(O=>O?.stage===N&&O?.stageSequence===1)?.seedAssignments??[]).find(O=>O.participantId===a);if(v?.participantId){let{participantId:O,seedNumber:x,seedValue:F}=v;Js({eventId:d?.eventId,provisionalPositioning:t,tournamentRecord:o,drawDefinition:i,seedingProfile:s,participantId:O,seedNumber:x,seedValue:F,structureId:m,event:d})}}if(g.structureType!==we)wk({provisionalPositioning:t,inContextDrawMatchUps:e,sourceMatchUpStatus:n,tournamentRecord:o,drawDefinition:i,drawPosition:u,matchUpsMap:p,structure:g,event:d});else{sS({positionAssignments:D,tournamentRecord:o,drawDefinition:i,matchUpsMap:p,structure:g});let{drawPositions:N,matchUps:R,targetMatchUps:b}=IS({assignments:[U],inContextDrawMatchUps:e,drawDefinition:i,matchUpsMap:p,structure:g});if(N&&R?.length===1&&R[0].matchUpType===Ht){let O=(b?.[0].sides??[]).reduce((x,F,L)=>N?.includes(F.drawPosition)?L:x,void 0);Id({inContextTargetMatchUp:b[0],teamParticipantId:a,matchUp:R[0],drawPositionSideIndex:O,tournamentRecord:o,drawDefinition:i})}}return Oo({tournamentId:o?.tournamentId,drawDefinition:i,structure:g,event:d}),{positionAssignments:D,...C};function P(N){let R=N.bye,b=N.qualifier,v=N.participantId;return{containsBye:R,containsQualifier:b,containsParticipant:v,filled:R||b||v}}}function wk({provisionalPositioning:t,inContextDrawMatchUps:e,sourceMatchUpStatus:r,tournamentRecord:n,drawDefinition:o,drawPosition:i,matchUpsMap:s,structure:a,event:c}){let u={isCollectionMatchUp:!1},{matchUps:p}=Et({provisionalPositioning:t,matchUpFilters:u,drawDefinition:o,matchUpsMap:s,structure:a,event:c}),{roundMatchUps:m}=je({matchUps:p}),{initialRoundNumber:d}=hs({drawPosition:i,matchUps:p}),l=d&&m?.[d].find(f=>f.drawPositions?.includes(i));if(l){let f=Ec({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{...C}}function yd(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=yt({tournamentRecord:o,drawDefinition:i,event:u}).appliedPolicies??{},{inContextDrawMatchUps:d,matchUpsMap:l}=t;l||(l=Ee({drawDefinition:i}),Object.assign(t,{matchUpsMap:l})),d||({matchUps:d}=re({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,D=Fn({inContextDrawMatchUps:d,tournamentRecord:o,drawDefinition:i,participantId:s,drawPosition:a,structureId:c,matchUpsMap:l,event:u});return D.success?T({appliedPolicies:m,removedParticipantId:y}):_({result:D,stack:p})}let I=Sc({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=Fn({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:D}){let{structure:U}=at({drawDefinition:i,structureId:c});zm({drawPositions:[a],structure:U});let A={[e]:s,name:n,drawPosition:a,structureId:c};return mu({appliedPolicies:y,drawDefinition:i,positionAction:A}),_({context:{removedParticipantId:D},result:{...C},stack:p})}}function yv({luckyLoserParticipantId:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,structureId:o}){return yd({positionActionName:"luckyLoserDrawPositionAssignment",participantId:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,structureId:o})}function rD(t){return yv(t)}function Av({alternateParticipantId:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,structureId:o}){return yd({positionActionName:"alternateDrawPositionAssignment",participantIdAttributeName:"alternateParticipantid",participantId:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,structureId:o})}function nD(t){return Av(t)}function hS({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],gt({tournamentId:n?.tournamentId,eventId:i?.eventId,drawDefinition:o,matchUp:s}))}function SS(t,e){let r=[{drawDefinition:!0,structureId:!0}];Array.isArray(e)&&r.push(...e);let n=nt(t,r);if(n.error)return n;let o=at(t);if(o.error)return o;let i=o.structure;if(!pr({structure:i}))return _({result:{error:Qo,message:"structure must be adHoc"}});let{roundMatchUps:a=[],roundNumbers:c}=je({matchUps:i?.matchUps});return c?.length?{valid:!0,structure:i,roundMatchUps:a,roundNumbers:c}:{error:Xn}}function oD(t){let e=SS(t,[{targetRoundNumber:!0,roundNumber:!0,[ar]:XC}]);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:k},info:"roundNumbers must be valid rounds"});let a=i>s,c=a?tt(s+1,i+1):tt(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),hS({params:t,modMap:u,structure:r}),{...C}}function iD({structurePositionAssignments:t,provisionalPositioning:e,tournamentRecord:r,drawDefinition:n,event:o}){if(!n)return{error:X};if(!Array.isArray(t))return{error:k};let i="setPositionAssignments";for(let a of t){let{structureId:c,positionAssignments:u}=a;if(!u)continue;let p=at({drawDefinition:n,structureId:c});if(p.error)return p;let m=p.structure;if(!m)return{error:Lt};let d=Ct({structure:m}).positionAssignments?.map(({drawPosition:I})=>I),l=u?.map(({drawPosition:I})=>I);if(qt(d,l).length!==d?.length)return _({result:{error:k},info:"drawPositions do not match",stack:i});let f=Ee({drawDefinition:n}),{matchUps:g}=re({inContext:!0,drawDefinition:n,matchUpsMap:f});for(let I of u||[]){let{drawPosition:h,participantId:S,bye:T,qualifier:y}=I;if(T){let D=kr({tournamentRecord:r,drawDefinition:n,drawPosition:h,matchUpsMap:f,structureId:c,structure:m,event:o});if(D?.error)return D}else if(y)u.forEach(D=>{D.drawPosition===h&&(D.qualifier=!0,delete D.participantId,delete D.bye)});else if(S){let D=Fn({provisionalPositioning:e,inContextDrawMatchUps:g,tournamentRecord:r,drawDefinition:n,participantId:S,drawPosition:h,matchUpsMap:f,structureId:c,event:o});if(D?.error)return D}}Oo({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}),{...C}}function sD(t){let e=SS(t,[{roundNumbers:!0,[ar]:ir,[sr]: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:k,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]})),hS({params:t,modMap:i,structure:r}),{...C}}function Ev({qualifyingParticipantId:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,structureId:o}){return yd({positionActionName:"qualifierDrawPositionAssignment",participantId:t,isQualifierPosition:!0,tournamentRecord:e,drawDefinition:r,drawPosition:n,structureId:o})}function aD(t){return Ev(t)}function cD({validation:t=!0,tournamentRecord:e,drawDefinition:r,participantId:n,structureId:o,seedValue:i,event:s}){if(!r)return{error:X};if(!o)return{error:hr};let a=(e?.participants??[]).find(l=>l.participantId===n);if(e&&!a)return{error:pn};let{structure:c}=at({drawDefinition:r,structureId:o});if(!c)return{error:Lt};if(!(!t||Jt(i)||i===void 0||i===""||typeof i=="string"&&i.split("-").every(l=>Jt(l)&&ut(l)>0)))return{error:k};let{seedAssignments:p}=en({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 Ch({tournamentId:e?.tournamentId,eventId:s?.eventId,drawDefinition:r,structure:c}),{...C}}function TS({drawDefinition:t,structureId:e}){if(!t)return{error:X};let{structure:r}=at({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 Ig({withStageGrouping:t,stageSequences:e,stageSequence:r,roundTarget:n,stages:o,event:i,stage:s}){if(!i)return{error:bt};let a={},c=[];for(let u of i.drawDefinitions||[]){let{structures:p,stageStructures:m}=ln({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 yS({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}=Ig({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 si(t){if(!t?.drawDefinition)return!1;let e=Au(t),r=e?.includesTeamMatchUps,{completedMatchUps:n,pendingMatchUps:o,upcomingMatchUps:i}=e||{};return r&&(n=n?.filter(({matchUpType:a})=>a===Ht),o=o?.filter(({matchUpType:a})=>a===Ht),i=i?.filter(({matchUpType:a})=>a===Ht)),!!(n?.length&&!o?.length&&!i?.length)}function AS(t){let{drawDefinition:e,structureId:r}=t;if(!e)return{error:X};let{playoffStructures:n}=TS({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 ES({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=ES({accessors:s,significantCharacters:t,value:c});n.push(...u)});else if(r=r[o],s.length){let a=ES({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 Uv({targetParticipantIds:t,policyAttributes:e,idCollections:r,participants:n}){if(!Array.isArray(e))return{error:LI};if(!Array.isArray(n))return{error:Ja};let o={};return t.forEach(i=>{let s=n.find(c=>c.participantId===i),{values:a}=uD({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 uD({policyAttributes:t,idCollections:e,participants:r,participant:n}){if(!Array.isArray(t))return{error:LI};if(!n)return{error:Gi};let o=[];return t.forEach(s=>{let{directive:a,groupings:c,key:u,significantCharacters:p}=s||{};if(u){let m=u.split(".");o.push(...ES({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 pD({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}=uD({participants:e,policyAttributes:r,idCollections:n,participant:s});return{...i,values:a}})}function Pv({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 Nv(t){let{unfilledPositions:e,chunkedDrawPositions:r}=t,n=Pv(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=Dv(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=Dv(c);return!s.includes(u)}}}function Mv(t){let{unfilledPositions:e,chunkedDrawPositions:r}=t,n=Pv(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 Dv(t){return Number(t%2?t+1:t-1)}function Rv({allGroups:t,participantId:e}){return Object.keys(t).filter(r=>t[r].includes(e))}function Cv({selectedParticipantGroups:t,participantIdGroups:e,positionAssignments:r,drawPositionChunks:n,unfilledPositions:o,isRoundRobin:i}){let s=n.map(a=>i?Mv({groupsToAvoid:t,chunkedDrawPositions:a,participantIdGroups:e,positionAssignments:r,unfilledPositions:o}):Nv({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 US({positionAssignments:t,participantIds:e}){let r=t.map(n=>n.participantId);return e.filter(n=>!r.includes(n))}function bv({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?Tn(a):Tn(Object.keys(i));return o=t&&i[o]?.length?o:c,{participantId:o&&i[o]?Tn(i[o]):Tn(e),groupKey:o}}function vv({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 Ov({candidatePositionAssignments:t,unseededParticipantIds:e,participantIdGroups:r,drawPositionChunks:n,drawPositionGroups:o,pairedPriority:i,allGroups:s,groupKey:a}){let u=o.reduce((M,P)=>P.length>M?P.length:M,0)<=2,p=US({positionAssignments:t,participantIds:e}),m=vv({positionAssignments:t,drawPositionGroups:o}),{participantId:d,groupKey:l}=bv({targetParticipantIds:p,useSpecifiedGroupKey:u,allGroups:s,groupKey:a}),f=Rv({participantId:d,allGroups:s}),g=Cv({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],D=i&&T?T:y,U=i?y:T,A=D?.length&&D||U?.length&&U,E;if(A?.length){let M=$r(A);E=$r(M)}else{let M=$r(I[0]);E=$r(M)}return{newGroupKey:l,selectedParticipantId:d,targetDrawPosition:E}}function Ad({isRoundRobin:t,groupedParticipants:e}){let r=[];return t?e.forEach(n=>{let o=n.map(a=>a.drawPosition),i=mg({drawPositions:o}).uniqueMatchUpGroupings??[],s=Object.assign({},...n.map(a=>({[a.drawPosition]:a})));i.forEach(a=>{xe(s[a[0]].values||[],s[a[1]].values||[])&&(r.push(a),n.conflict=!0)})}):e.forEach(n=>{xe(n[0]?.values||[],n[1]?.values||[])&&(r.push(n),n.conflict=!0)}),r}function _v({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=Ad({isRoundRobin:o,groupedParticipants:[[c,l]]}),h=[t.find(T=>T.drawPosition===m),l],S=Ad({isRoundRobin:o,groupedParticipants:[h]});return!g.length&&!S.length});if(p.length)return{drawPosition:c.drawPosition,possibleDrawPositions:p}}).filter(Boolean)}).flat(1)}function mD(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);tt(0,n).forEach(()=>{let{newGroupKey:T,selectedParticipantId:y,targetDrawPosition:D}=Ov({...t,candidatePositionAssignments:l,allGroups:c,groupKey:p});p=T,l.forEach(U=>{U.drawPosition===D&&(U.participantId=y)})});let g=pD({candidatePositionAssignments:l,participantsWithGroupings:r,policyAttributes:s,idCollections:a}),I=Ae(g,m),h=Ad({groupedParticipants:I,isRoundRobin:d}),S=0;for(;S<20&&h.length;){let T=_v({positionedParticipants:g,potentialDrawPositions:f,avoidanceConflicts:h,drawPositionGroups:i,isRoundRobin:d});if(T.length){let y=Lk({candidatePositionAssignments:l,swapOptions:T});y.error&&console.log({result:y}),g=pD({candidatePositionAssignments:l,participantsWithGroupings:r,policyAttributes:s,idCollections:a}),I=Ae(g,m),h=Ad({groupedParticipants:I,isRoundRobin:d}),S++}else S=20}return l.forEach(T=>{if(T.bye&&T.participantId){let y=_I;u.push(y)}if(T.qualifier&&T.participantId){let y=_I;u.push(y)}}),{positionAssignments:l,conflicts:h.length,groupedParticipants:I,errors:u}}function Lk({candidatePositionAssignments:t,swapOptions:e}){let r=$r(e);if(!r)return{error:{message:"No swap options"}};let n=r.drawPosition,o=$r(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),{...C}}function xv({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:ZA};let{candidatesCount:l=1,policyAttributes:f,targetDivisions:g}=p,{roundsToSeparate:I}=p,h="randomUnseededSeparation",{structure:S}=at({drawDefinition:i,structureId:u}),{matchUps:T}=Et({provisionalPositioning:t,matchUpsMap:c,structure:S,event:d});if(g&&On(g)&&!I){let G=EC(g)||0,W=T.reduce((H,q)=>q.roundNumber>H?q.roundNumber:H,0);I=W<G?1:W-G+1}let{positionAssignments:y}=le({structure:S}),D=Qm({participantsProfile:{convertExtensions:!0},deepCopy:!1,participants:a}).participantsWithGroupings,U=y?.filter(G=>!G.participantId),A=y?.map(G=>G.drawPosition),E=S?.structureType===we,M=E?{structure:S,matchUps:T,allDrawPositions:A,roundsToSeparate:I}:{matchUps:T,allDrawPositions:A,roundsToSeparate:I},{drawPositionGroups:P,drawPositionChunks:N}=E?Fk(M):kk(M),R={groupParticipants:a.filter(G=>G.participantType===Rr).map(G=>G.participantId),teamParticipants:a.filter(G=>G.participantType===Ft).map(G=>G.participantId),pairParticipants:a.filter(G=>G.participantType===lt).map(G=>G.participantId)},b=Uv({targetParticipantIds:e,policyAttributes:f,idCollections:R,participants:a});if(b.error)return _({result:b,stack:h});let v=Object.assign({},...e.map(G=>{let W=Object.keys(b).filter(H=>(b[H]??[]).includes(G));return{[G]:W}})),O=US({participantIds:e,positionAssignments:y});if(O.length>(U?.length||0))return{error:zl};let x,F=O.length,L=tt(0,l).map(()=>mD({initialPositionAssignments:y,participantsWithGroupings:D,unseededParticipantIds:e,opponentsToPlaceCount:F,pairedPriority:!1,unseededByePositions:n,participantIdGroups:v,drawPositionChunks:N,drawPositionGroups:P,policyAttributes:f,idCollections:R,allGroups:b,drawSize:m}));if(x=L.reduce((G,W)=>!G||(W.conflicts||0)<(G.conflicts||0)?W:G,void 0),!x||x.conflicts){let G=tt(0,l).map(()=>mD({initialPositionAssignments:y,participantsWithGroupings:D,unseededParticipantIds:e,opponentsToPlaceCount:F,pairedPriority:!0,unseededByePositions:n,participantIdGroups:v,drawPositionChunks:N,drawPositionGroups:P,policyAttributes:f,idCollections:R,allGroups:b,drawSize:m}));x=L.concat(...G).filter(H=>!H.errors?.length).reduce((H,q)=>!H||(q.conflicts||0)<(H.conflicts||0)?q:H,void 0)}if(!x)return{error:np};let w=(Ct({structure:S})?.positionAssignments??[]).filter(G=>G.participantId).map(G=>G.participantId),B=x.positionAssignments.filter(G=>!w.includes(G.participantId));for(let G of B)if(G.bye){let W=kr({tournamentRecord:o,drawDefinition:i,seedBlockInfo:s,structureId:u,matchUpsMap:c,event:d,...G});if(W.error)return _({result:W,stack:h})}else if(G.participantId){let W=Fn({automaticPlacement:!0,inContextDrawMatchUps:r,tournamentRecord:o,drawDefinition:i,seedBlockInfo:s,structureId:u,matchUpsMap:c,event:d,...G});if(W.error)return _({result:W,stack:h,context:{assignment:G}})}return{...C}}function Fk(t){let{structure:{structures:e}}=t,r=e.map(n=>n.positionAssignments.map(o=>o.drawPosition));return{drawPositionGroups:r,drawPositionChunks:[r]}}function kk({allDrawPositions:t,roundsToSeparate:e,matchUps:r}){let n=r.filter(d=>d.roundNumber===1).map(d=>d.drawPositions),o=n.flat().sort(ae),i=Math.max(...o),s=t.filter(d=>d>i),a=o.length,u=tt(a===2?1:2,a).filter(d=>d===Rm(d)),m=u.slice(0,e||u.length).reverse().map(d=>Ae(o,d));return s.length&&console.log({fedDrawPositions:s}),{drawPositionGroups:n,drawPositionChunks:m}}function wv({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}=at({drawDefinition:i,structureId:u})),u||({structureId:u}=p);let{positionAssignments:f}=le({structure:p}),{seedAssignments:g}=en({provisionalPositioning:t,drawDefinition:i,structure:p}),I=g?.map(N=>N.participantId).filter(Boolean),{stage:h,stageSequence:S}=p,T=h===ct?mt({element:p,name:Dn})?.extension?.value:void 0,D=Ni({provisionalPositioning:t,drawDefinition:i,stageSequence:S,entryStatuses:ni,structureId:u,roundTarget:T,stage:h}),A=D.filter(N=>!I?.includes(N.participantId)).map(N=>N.participantId),E=f?.filter(N=>!N.participantId&&!N.bye&&!N.qualifier).map(N=>N.drawPosition);if(!n&&A.length>(E?.length||0))return _({result:{error:zl},context:{unseededParticipantsCount:A.length,unfilledDrawPositionsCount:E?.length},stack:l});let{appliedPolicies:M}=yt({tournamentRecord:o,drawDefinition:i,event:d}),P=M?.[iu];if(p.stage===pe){let N=D.reduce((R,b)=>(R[b.groupingValue]||(R[b.groupingValue]=[]),R[b.groupingValue].push(b.participantId),R),{});Object.keys(N).length&&(P||(P={policyName:"Playoff Avoidance"}),P.policyAttributes||(P.policyAttributes=[]),P.policyAttributes.push({groupings:N}))}return P&&a?xv({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:D}):Gk({provisionalPositioning:t,unseededParticipantIds:A,inContextDrawMatchUps:e,unfilledDrawPositions:E,multipleStructures:n,tournamentRecord:o,drawDefinition:i,seedBlockInfo:s,structureId:u,matchUpsMap:c,drawSize:m,event:d})}function Gk({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?lr(n):n.reverse();for(let l of e){let f=d.pop();if(!o||f){let g=Fn({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{...C}}function Lv(t){let e=t.structure??at(t).structure,r="positionQualifiers",n=[];if(e.stage===Ve)return _({result:{error:Li},stack:r});let{unplacedRoundQualifierCounts:o,positionAssignments:i,roundDrawPositions:s}=Vk(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:hE},context:{unfilledDrawPositions:c},stack:r});tt(0,o[a]).forEach(()=>{let u=$r(c);n.push(u),i?.forEach(p=>{p.drawPosition===u&&(p.qualifier=!0,delete p.participantId,delete p.bye)})})}return{...C,qualifierDrawPositions:n}}function Vk({drawDefinition:t,structure:e,structureId:r}){e||({structure:e}=at({drawDefinition:t,structureId:r})),r||({structureId:r}=e);let{positionAssignments:n}=le({structure:e}),{stage:o,stageSequence:i}=e,{qualifiersCount:s,roundQualifiersCounts:a}=Ts({drawDefinition:t,stageSequence:i,structureId:r,stage:o}),u=(a?Object.keys(a):[]).map(h=>ut(h)),{matchUps:p}=Et({structure:e}),{roundProfile:m}=je({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 dD({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}=at({drawDefinition:i,structureId:p})),p||(p=d?.structureId),n||(n=yt({drawDefinition:i}).appliedPolicies),!o){let h=d&&Es({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,tt(0,u).forEach(()=>{if(I<(u||0)){let h=Bk({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}:{...C,seedPositions:f}}function Bk({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}=dS({provisionalPositioning:t,randomize:!0,drawDefinition:n,seedingProfile:o,seedBlockInfo:i,structureId:a,event:u}),{appliedPolicies:d}=yt({drawDefinition:n}),{avoidance:l}=d??{};l&&s&&p?.length>2;let f=[];for(let g of p){let I=m.pop();if(!I)return{error:_s};f.push(I);let h=Fn({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{...C,seedPositions:f}}function Fv({provisionalPositioning:t,drawDefinition:e,structure:r}){let{positionAssignments:n}=le({structure:r}),{seedAssignments:o}=en({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 kv({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=lD(Ae(i.drawPositions,2)),c,u=t[n.length];for(;c=hg(a,u);)n.push(c),u=t[n.length]}});let o=n.map(i=>Array.isArray(i)?lr(i):i).flat(1/0);return jI(r)&&e.map(s=>s.seedNumbers[0]).includes(r)?t:o}function hg(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 hg(e?o:t[Math.round(Math.random())],e)}return r<n?hg(t[1],e):hg(t[0],e)}function lD(t){let e=Math.floor(t.length/2);return t.length>2?[lD(t.slice(0,e)),lD(t.slice(e))]:t}function Vv({provisionalPositioning:t,relevantMatchUps:e,appliedPolicies:r,drawDefinition:n,seedingProfile:o,seedBlockInfo:i,byesToPlace:s,structure:a}){i||(i=Es({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=Fv({provisionalPositioning:t,drawDefinition:n,structure:a})??[],l=pt([].concat(...e.map(D=>D.drawPositions))),f=d.filter(D=>l.includes(D.drawPosition)),g=(D,U)=>Ac(D.seedValue)-Ac(U.seedValue),h=m.reduce((D,U)=>{let A=f.filter(E=>U.drawPositions?.includes(E.drawPosition)).sort(g);return D.concat(...A)},[]).map(D=>D.drawPosition),S=kv({orderedSortedFirstRoundSeededDrawPositions:h,validSeedBlocks:m,byesToPlace:s}),T=Gv({orderedSeedDrawPositions:h,relevantMatchUps:e}).slice(0,s),y=Gv({orderedSeedDrawPositions:S,relevantMatchUps:e}).slice(0,s);return{strictSeedOrderByePositions:T,blockSeedOrderByePositions:y,isLuckyStructure:u,positionedSeeds:d,isContainer:p,isFeedIn:c}}function Gv({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 Bv({provisionalPositioning:t,seedOrderByePositions:e,isLuckyStructure:r,appliedPolicies:n,drawDefinition:o,seedLimit:i,structure:s,isFeedIn:a}){let c=n?.seeding?.seedingProfile,u=s.stage===ct,{positionAssignments:p}=le({structure:s}),m=p?.filter(O=>O.participantId).map(O=>O.drawPosition),d={isCollectionMatchUp:!1},{matchUps:l,roundMatchUps:f}=Et({provisionalPositioning:t,matchUpFilters:d,structure:s}),g=f?.[1]||[],I=s.structureType===we?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 x=Math.ceil(O.length/2),F=[O.slice(0,x),O.slice(x)],L=F.map(V=>[].concat(...V.flat(1/0)).length),w=Math.min(...L.flat(1/0)),B=Math.max(...L.flat(1/0)),G=L.indexOf(B),W=w!==B,H=lr(F),[q,$]=!w||W?[F[G],F[1-G]]:[H[0],H[1]];return{greaterHalf:q,lesserHalf:$}},D=O=>{let{greaterHalf:x,lesserHalf:F}=y(O),{greaterHalf:L,lesserHalf:w}=y(x),G=lr(L.flat(1/0)).pop(),W=L.flat().filter(q=>q!==G);return{newlyFilteredChunks:[...F,...w,W],drawPosition:G}},U=O=>!e.includes(O),A=O=>!T?.includes(O),E=O=>{let F=Ae(O.sort(ae),Math.ceil(O.length/4)).map(B=>B.filter(A)),L=[].concat(...F.flat(1/0)).length,w=[];for(let B=0;B<L;B++){let{newlyFilteredChunks:G,drawPosition:W}=D(F);w.push(W),F=G}return w},{validSeedBlocks:M}=Es({provisionalPositioning:t,allPositions:!0,appliedPolicies:n,drawDefinition:o,structure:s}),P=M?.map(O=>O.drawPositions?.map(x=>x+S)),N;if(a){let O=h.length,{seedBlocks:x}=lg({cluster:Fp(c)===Qc,participantsCount:O});N=x.map(L=>L.map(w=>w+S)).map(E).filter(L=>L.length)}else u?N=P?.map(O=>O.filter(A)):N=P?.map(E).filter(O=>O.length);let R=I.map(O=>O.drawPositions).map(O=>O?.sort((x,F)=>x-F)).filter(O=>O?.[0]+1===O?.[1]),b=O=>R.reduce((x,F)=>F.includes(O)?F.reduce((L,w)=>w!==O?w:L,void 0):x,void 0),v=N.map(O=>O.map(b)).flat(1/0).filter(A).filter(U).filter(Boolean);if(u&&!s.structures){let O=i%4,x=v.slice(0,O),F=f[s.roundLimit]?.length,L=Ae(v.slice(O),F).map(lr).flat();v=x.concat(L)}return{unseededByePositions:v}}function Hv({provisionalPositioning:t,drawDefinition:e,matchUpsMap:r,structure:n,event:o}){let i={isCollectionMatchUp:!1},{matchUps:s,roundMatchUps:a}=Et({afterRecoveryTimes:!1,provisionalPositioning:t,drawDefinition:e,matchUpFilters:i,matchUpsMap:r,structure:n,event:o}),c=a?.[1]||[],u=n?.structureType===we,p=u?s:c,m=u?n?.structures?.length||0:s.length,{structureId:d,stage:l,stageSequence:f}=n,g=Ni({entryStatuses:Wr,provisionalPositioning:t,drawDefinition:e,stageSequence:f,structureId:d,stage:l}),{qualifiersCount:I}=Ts({provisionalPositioning:t,drawDefinition:e,stageSequence:f,structureId:d,stage:l}),h=g.length+I,{positionAssignments:S,unassignedPositions:T}=le({structure:n}),y=T?.map(P=>P.drawPosition),D=S?.filter(P=>P.bye).length,U=S?.filter(P=>P.bye).map(P=>P.drawPosition),A=p.map(P=>P.drawPositions).filter(P=>P?.reduce((N,R)=>!U?.includes(R)&&N,!0)).flat(1/0).filter(P=>y?.includes(P)),E=S?.length,M=E?E-h:0;return M>m&&n.stageSequence===1&&n.stage!==Ve&&(M=m),{placedByes:D,byesCount:M,relevantMatchUps:p,placedByePositions:U,roundMatchUps:a,positionsToAvoidDoubleBye:A}}function fD({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}=at({drawDefinition:n,structureId:a})),a||(a=c?.structureId);let d=!(c?.structures??c?.stage===ct),{byesCount:l,placedByes:f,relevantMatchUps:g}=Hv({provisionalPositioning:t,drawDefinition:n,matchUpsMap:s,structure:c,event:m}),I=l-(f||0);if(I<=0)return{...C};let{strictSeedOrderByePositions:h,blockSeedOrderByePositions:S,isLuckyStructure:T,isFeedIn:y}=Vv({provisionalPositioning:t,relevantMatchUps:g,appliedPolicies:r,drawDefinition:n,seedingProfile:i,seedBlockInfo:o,byesToPlace:I,structure:c}),D=c?.structureType&&[we,dp].includes(c.structureType)&&r?.seeding?.containerByesIgnoreSeeding,U=d&&S?.length?S:h,{unseededByePositions:A}=Bv({provisionalPositioning:t,seedOrderByePositions:U,isLuckyStructure:T,appliedPolicies:r,drawDefinition:n,seedLimit:u,structure:c,isFeedIn:y}),E=R=>R%2,M=(R,b)=>(R||[]).every(v=>E(v)?b!==v+1:b!==v-1),P=[].concat(...U);if(!p)for(;A.length;){let R=A.find(b=>M(P,b));R?(P.push(R),A=A.filter(b=>b!==R)):(P.push(...A),A=[])}D&&(P=lr(P),Sr({ignoreSeededByes:D})&&console.log({byePositions:P}));let N=P.slice(0,I);for(let R of N){let b=kr({provisionalPositioning:t,tournamentRecord:e,drawDefinition:n,drawPosition:R,matchUpsMap:s,structureId:a,structure:c,event:m});if(b?.error)return b}return{...C,unseededByePositions:A,byeDrawPositions:N}}function Uc(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||(jE(),e=J(e,!1,!0));let I=x=>(r||af(),_({result:x,stack:"automatedPositioning"})),h=x=>(r||af(),x),S=at({drawDefinition:e,structureId:u});if(S.error)return I(S);let T=S.structure;if(!T)return{error:Lt};let y=t.appliedPolicies||yt({drawDefinition:e,structure:T,event:f})?.appliedPolicies,{qualifiersCount:D}=Ts({stageSequence:T.stageSequence,provisionalPositioning:n,stage:T.stage,drawDefinition:e,structureId:u}),U=ni;if(!Ni({stageSequence:T.stageSequence,provisionalPositioning:n,stage:T.stage,placementGroup:a,drawDefinition:e,entryStatuses:U,structureId:u})?.length&&!D)return h({...C});let E=t.matchUpsMap??Ee({drawDefinition:e}),M=t.inContextDrawMatchUps??re({inContext:!0,drawDefinition:e,matchUpsMap:E})?.matchUps,P=[],N=Es({provisionalPositioning:n,appliedPolicies:y,drawDefinition:e,seedingProfile:c,structure:T});if(N.error)return N;let{validSeedBlocks:R}=N;g.push({validSeedBlocks:R});let b=t.participants||(s?$t({withIndividualParticipants:!0,convertExtensions:!0,tournamentRecord:s})?.participants:[]);if(Fp(T.seedingProfile||c)===gi){let x=i?fD({provisionalPositioning:n,tournamentRecord:s,appliedPolicies:y,drawDefinition:e,seedBlockInfo:N,matchUpsMap:E,structure:T,seedLimit:p,seedsOnly:m,event:f}):void 0;if(x?.error)return I(x);P=x.unseededByePositions,g.push({action:"positionByes",unseededByePositions:P});let F=T.seedingProfile?{positioning:T.seedingProfile}:c;if(x=dD({seedingProfile:F,provisionalPositioning:n,inContextDrawMatchUps:M,tournamentRecord:s,appliedPolicies:y,validSeedBlocks:R,drawDefinition:e,seedBlockInfo:N,participants:b,matchUpsMap:E,structure:T,event:f}),x.error)return I(x);g.push({seedPositions:x.seedPositions,action:"positionSeedBlocks"})}else{if(d!==Hi){let F=T.seedingProfile?{positioning:T.seedingProfile}:c,L=dD({seedingProfile:F,provisionalPositioning:n,inContextDrawMatchUps:M,tournamentRecord:s,appliedPolicies:y,validSeedBlocks:R,drawDefinition:e,seedBlockInfo:N,participants:b,matchUpsMap:E,structure:T,event:f});if(L.error)return I(L);g.push({action:"positionSeedBlocks",seedPositions:L.seedPositions})}let x=i?fD({provisionalPositioning:n,tournamentRecord:s,appliedPolicies:y,drawDefinition:e,seedBlockInfo:N,matchUpsMap:E,structure:T,seedLimit:p,seedsOnly:m,event:f}):void 0;if(x?.error)return I(x);P=x?.unseededByePositions,g.push({action:"positionByes",byeDrawPositions:x?.byeDrawPositions,unseededByePositions:P})}let v={};if(!m){let x=Lv({inContextDrawMatchUps:M,tournamentRecord:s,appliedPolicies:y,validSeedBlocks:R,drawDefinition:e,seedBlockInfo:N,participants:b,matchUpsMap:E,structure:T});if(x.error||(x.conflicts&&(v.qualifierConflicts=x.conflicts),g.push({action:"positionQualifiers",qualifierDrawPositions:x.qualifierDrawPositions}),x=wv({provisionalPositioning:n,inContextDrawMatchUps:M,unseededByePositions:P,multipleStructures:o,tournamentRecord:s,drawDefinition:e,seedBlockInfo:N,participants:b,matchUpsMap:E,structureId:u,structure:T,drawSize:l,event:f}),x.error))return I(x);x.conflicts&&(v.unseededConflicts=x.conflicts),g.push({action:"positionUnseededParticipants"})}let{positionAssignments:O}=Ct({drawDefinition:e,structure:T});return Ot({drawDefinition:e,structureIds:[u]}),r||af(),{positionAssignments:O,conflicts:v,...C,positioningReport:g}}function Dc(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:Pr};if(!o)return{error:Dr};if(!si({drawDefinition:o,structureId:s})&&!r)return{error:_l};let m=TS({drawDefinition:o,structureId:s}).playoffStructures?.sort((f,g)=>Rf(f)-Rf(g)),d=[],l=[];if(m)for(let f of m){let{structureId:g}=f,I=Uc({structureId:g,provisionalPositioning:r,applyPositioning:e,tournamentRecord:n,drawDefinition:o,seedingProfile:i,placeByes:a,seedsOnly:c});if(I.error)return I;I.positionAssignments&&d.push({positionAssignments:I.positionAssignments,structureId:g}),I.positioningReport&&l.push(I.positioningReport)}return{...C,structurePositionAssignments:d,positioningReports:l}}function gD({drawDefinition:t,orderMap:e}){return t?((typeof e!="object"||!Object.values(e).every(r=>ft(r)))&&_({result:{error:k},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)=>tc(r.structureOrder)-tc(n.structureOrder)),{...C}):{error:X}}function Nu({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[Ii,yn,lp,gi].includes(I.target.feedProfile)?(T?.targets.push(S),y?.sources.push(h)):I.target.feedProfile===mn&&(y?.drawSources.push(h),T?.drawTargets.push(S)),s[S]=s[S]||I.target.feedProfile===mn,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(),D=y&&n[y];if(D?.sources?.length){for(let U of D.sources)h.progeny?.includes(U)||h.progeny?.push(U);T.push(...D.sources)}}}}}let c=0;for(let I of n.keys()){let h=n.get(I);if(h&&h.rootStage===ct){let S=[h.drawTargets?.[0]],T=0;for(;S.length;){T+=1;let y=S.pop(),D=y?n.get(y):void 0;D?.drawTargets?.length&&S.push(D.drawTargets[0])}h.distanceFromMain=T,T>c&&(c=T)}}let u=a.length;tt(0,Math.ceil(u/2)).forEach(()=>{a=tt(0,u).map(I=>{let h=a[I],S=a.reduce((T,y)=>xe(h,y)?T.concat(...y):T,[])||[];return pt(h.concat(...S))})});let p=a[0],m=(I,h)=>qt(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!==Be&&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 DS({drawDefinition:t}){let{maxQualifyingDepth:e,structureProfiles:r}=Nu({drawDefinition:t});for(let n of t.structures){let o=r[n.structureId];o.distanceFromMain&&(n.stageSequence=e+1-o.distanceFromMain)}return{...C}}function Sg(t){let e=nt(t,[{[Re]:!0,[Le]:!0}]);if(e.error)return e;let{tournamentRecord:r,drawDefinition:n,structure:o,link:i}=t;return Hk({tournamentId:r.tournamentId,drawDefinition:n,structure:o,link:i})}function Hk(t){let e=nt(t,[{[Le]:!0,[Ip]:!0},{link:!0,[ar]:zr,[bA]:Ll}]);if(e.error)return e;let{drawDefinition:r,tournamentId:n,structure:o,eventId:i,link:s}=t,a=s.target.structureId,c=at({drawDefinition:r,structureId:a});if(c.error)return _({stack:"attachQualifyingStructure",context:{targetStructureId:a},result:c});r.structures||(r.structures=[]),r.links||(r.links=[]),r.structures.push(o),r.links.push(s),DS({drawDefinition:r});let u=Et({structure:o})?.matchUps||[];return vo({drawDefinition:r,tournamentId:n,matchUps:u,eventId:i}),Ot({drawDefinition:r,structureIds:[o.structureId]}),{...C}}function ID({drawDefinition:t,structureDetails:e}){if(!Array.isArray(e))return{error:k};if(!t)return{error:X};let r=Object.assign({},...e.map(n=>{if(!It(n))return;let{structureId:o,structureName:i}=n||{};if(!(!o||!i))return{[o]:i}}).filter(Boolean));if(!Object.values(r).length)return{error:ot};for(let n of t.structures||[]){let o=r[n.structureId];if(o&&(n.structureName=o),n.structures)for(let i of n.structures){let s=r[i.structureId];s&&(i.structureName=s)}}return{...C}}function Tg({drawDefinition:t,timeItem:e}){if(!t)return{error:Dr};if(!e)return{error:Jl};let r=e&&Object.keys(e),n=["itemType","itemValue"];if(!(n.filter(s=>r.includes(s)).length===n.length))return{error:Xl};t.timeItems||(t.timeItems=[]);let i=new Date().toISOString();return Object.assign(e,{createdAt:i}),t.timeItems.push(e),Da({drawDefinition:t}),{...C}}function hD(t){let{tournamentRecord:e,drawDefinition:r,structureId:n,event:o}=t,i=nt(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:Lt};let c=s.find(({stage:h,stageSequence:S})=>h===et&&S===1),u=n===c?.structureId,p=s.filter(({stage:h})=>h===ct).map(Fr("structureId"));if(u&&!p.length)return{error:vA};let m=p.includes(n),d=Wk({isQualifyingStructure:m,structure:a,...t});if(d?.error)return d;let{structureIdsToRemove:l,relatedStructureIdsMap:f}=Yk({qualifyingStructureIds:p,isQualifyingStructure:m,isMainStageSequence1:u,mainStageSequence1:c,drawDefinition:r,structureId:n}),{removedMatchUpIds:g,removedStructureIds:I}=qk({relatedStructureIdsMap:f,qualifyingStructureIds:p,isMainStageSequence1:u,mainStageSequence1:c,drawDefinition:r,structureIdsToRemove:l,structureId:n});if(jk({removedMatchUpIds:g,drawDefinition:r}),u){let h=(c.matchUps??[])?.map(Fr("matchUpId"));g.push(...h),c.positionAssignments=[],c.seedAssignments=[],c.matchUps=[],c.extensions&&(c.extensions=[])}return m&&DS({drawDefinition:r}),jn({tournamentId:e?.tournamentId,matchUpIds:g,action:"removeStructure",eventId:o?.eventId,drawDefinition:r}),Ot({drawDefinition:r,eventId:o?.eventId}),{...C,removedMatchUpIds:g,removedStructureIds:I}}function Wk({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(re({matchUpFilters:{structureIds:a},drawDefinition:r}).matchUps?.some(({score:p})=>me({score:p}))){let p=yt({tournamentRecord:e,drawDefinition:r,structure:o,event:i})?.appliedPolicies;if(!(s??p?.[Qr]?.allowDeletionWithScoresPresent?.structures))return{error:ap}}return{...C}}function jk({removedMatchUpIds:t,drawDefinition:e}){let{matchUps:r}=re({drawDefinition:e});r?.forEach(n=>{n.winnerMatchUpId&&t.includes(n.winnerMatchUpId)&&delete n.winnerMatchUpId,n.loserMatchUpId&&t.includes(n.loserMatchUpId)&&delete n.loserMatchUpId})}function Yk({qualifyingStructureIds:t,isQualifyingStructure:e,isMainStageSequence1:r,mainStageSequence1:n,drawDefinition:o,structureId:i}){let a=(o.structures??[]).map(Fr("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 qk({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(...zk({idBeingRemoved:u,drawDefinition:o}));let p=Kk({qualifyingStructureIds:e,isMainStageSequence1:r,idBeingRemoved:u,drawDefinition:o,structureId:s});a.push(...p.removedStructureIds);let m=$k({relatedStructureIdsMap:t,mainStageSequence1:n,idBeingRemoved:u,structureId:s});m?.length&&i.push(...m)}return{removedMatchUpIds:c,removedStructureIds:a}}function $k({idBeingRemoved:t,relatedStructureIdsMap:e,mainStageSequence1:r,structureId:n}){return t&&e.get(t)?.filter(o=>o!==r?.structureId||n===r.structureId)}function Kk({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 zk({idBeingRemoved:t,drawDefinition:e}){let{structure:r}=at({structureId:t,drawDefinition:e}),n=Et({structure:r}).matchUps;return qm(n)}function kp({stageSequence:t=1,drawDefinition:e,drawSize:r,stage:n}){if(!e)return{error:X};if(!Kf({drawDefinition:e,stage:n}))return{error:Li};let o=yb({drawDefinition:e,stage:n}),{qualifiersCount:i}=Ts({drawDefinition:e,stageSequence:t,stage:n}),s=o+i;if(r<s)return{error:OI};let{entryProfile:a}=Hf({attributes:[{[n]:{drawSize:r}}],drawDefinition:e});return Ot({drawDefinition:e}),{...C,entryProfile:a}}function PS({qualifiersCount:t=0,drawDefinition:e,stage:r}){return e?Kf({drawDefinition:e,stage:r})?r!==et?{error:OI,info:"qualifiersCount can only be set for main stage"}:(Hf({attributes:[{[r]:{qualifiersCount:t}}],drawDefinition:e}),Ot({drawDefinition:e}),{...C}):{error:Li}:{error:X}}function Wv({drawDefinition:t,drawSize:e}){if(!t)return{error:X};let r=kp({stage:Be,stageSequence:1,drawDefinition:t,drawSize:e});return r.error?r:(Ot({drawDefinition:t}),{...C})}function SD(t){return Wv(t)}var jv="qualifierDrawPositionAssignment",Yv="withdrawParticipantAtDrawPosition",qv="alternateDrawPositionAssignment",$v="luckyLoserDrawPositionAssignment",TD="removeDrawPositionAssignment",NS="swapDrawPositionAssignments",Kv="modifyPairAssignment",zv="adHocPositionSwap",Qv="modifyParticipantOtherName",yD="assignDrawPosition",Xv="removeSeededParticipant",Jv="assignDrawPositionBye",Zv="modifySeedAssignment",MS="addPenalty",yg="MODIFY_PAIR",Gp="QUALIFIER",Ag="ALTERNATE",Eg="WITHDRAW",Us="ASSIGN",RS="REMOVE",Ug="LUCKY",Vp="REMOVE_SEED",Bp="SWAP",Mu="NICKNAME",Zs="SEED_VALUE",ta="PENALTY",Ed="BYE",tO={MODIFY_PAIR_ASSIGNMENT:yg,QUALIFYING_PARTICIPANT:Gp,ALTERNATE_PARTICIPANT:Ag,WITHDRAW_PARTICIPANT:Eg,ASSIGN_PARTICIPANT:Us,LUCKY_PARTICIPANT:Ug,REMOVE_ASSIGNMENT:RS,SWAP_PARTICIPANTS:Bp,ADD_NICKNAME:Mu,REMOVE_SEED:Vp,ADD_PENALTY:ta,ASSIGN_BYE:Ed,SEED_VALUE:Zs};function AD({tournamentRecord:t,drawDefinition:e,drawPositions:r,structureId:n,event:o}){if(!e)return{error:X};if(!n)return{error:hr};if(r?.length!==2)return{error:k,drawPositions:r};let i=Ee({drawDefinition:e}),{matchUps:s}=re({inContext:!0,drawDefinition:e,matchUpsMap:i}),{structure:a}=at({drawDefinition:e,structureId:n});if(!a)return{error:Lt};let c=yt({tournamentRecord:t,drawDefinition:e,event:o}).appliedPolicies??{},u;if(a.structureType===we?u=Jk({inContextDrawMatchUps:s,tournamentRecord:t,drawDefinition:e,drawPositions:r,matchUpsMap:i,structure:a,event:o}):u=Qk({inContextDrawMatchUps:s,tournamentRecord:t,drawDefinition:e,drawPositions:r,matchUpsMap:i,structure:a,event:o}),u.error)return u;if(zm({structure:a,drawPositions:r}),mu({appliedPolicies:c,drawDefinition:e,positionAction:{name:NS,drawPositions:r,structureId:n}}),Oo({tournamentId:t?.tournamentId,drawDefinition:e,structure:a,event:o}),o.eventType===Kr){let m=Et({matchUpFilters:{matchUpTypes:[Nn]},inContext:!0,structure:a}).matchUps.filter(l=>l.drawPositions?.some(f=>r.includes(f))),d=Et({matchUpFilters:{matchUpTypes:[Nn]},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,D)=>y.drawPosition===g?D:T,void 0);Id({inContextTargetMatchUp:l,drawPositionSideIndex:S,teamParticipantId:I,tournamentRecord:t,drawDefinition:e,matchUp:h,event:o})}})})}return Ot({drawDefinition:e,structureIds:[n]}),{...C}}function Qk({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:k,structure:i,info:"Missing positionAssignments"};if(a.filter(({bye:p})=>p).length===2)return{...C};if(a.filter(({qualifier:p})=>p).length===2)return{...C};let c=a.some(({qualifier:p})=>p);return a.some(({bye:p})=>p)&&!c?eO({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,assignments:a,matchUpsMap:o,structure:i,event:s}):Xk({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,assignments:a,matchUpsMap:o,structure:i,event:s})}function eO({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=Pu({drawPosition:u,inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,structureId:d,matchUpsMap:o});return l.error||(l=Pu({drawPosition:m,inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,structureId:d,matchUpsMap:o}),l.error)||(kr({drawPosition:m,tournamentRecord:e,drawDefinition:r,structureId:d,matchUpsMap:o,event:s}),l=Fn({drawPosition:u,inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,structureId:d,participantId:p,matchUpsMap:o,event:s}),l.error)?l:{...C}}function Xk({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),gg({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,matchUpsMap:o,assignments:n,structure:i,event:s}),{...C}}function Jk({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{...C};if(a.filter(({qualifier:p})=>p).length===2)return{...C};gg({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)eO({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{...C}}function ED({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||![et,ct].includes(i.stage)||i.stage===et&&i.stageSequence!==1?_({result:{error:Qo},stack:o}):i.seedAssignments?.find(a=>a.participantId===r)?{...C}:_({info:"participant not seeded",result:{error:Pe},context:{participantId:r}}):_({result:{error:Lt},stack:o})}function _a({targetEntryRound:t=1,finishingPositions:e,sourceRoundNumber:r,sourceStructureId:n,targetStructureId:o,linkType:i=fo}){return!n||!o?{error:hr}:{link:rt({linkType:i,source:{roundNumber:r,structureId:n,finishingPositions:e},target:{feedProfile:mn,roundNumber:t,structureId:o}})}}function Ud({roundPosition:t,roundNumber:e,idPrefix:r,uuids:n}){return r?`${r}-${e}-${t}`:n?.pop()||Nt()}function Hp({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=Ud({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:zt,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 Rn({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&&(!On(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(!On(a)&&!p)return{matchUps:[],roundsCount:0};let m=tt(1,a+1).map(I=>({drawPosition:I})),d,l=[],f=1;for({roundNodes:d,matchUps:l}=Hp({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}=Hp({nodes:d,matchUpType:o,roundNumber:f,idPrefix:s,matchUps:l,isMock:c,uuids:u}),f++;let g=f-1;return l=Ra({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 Dd(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:k},stack:e});let r=t.drawSize??Mm(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:k},context:{drawSize:r,qualifyingPositions:o},stack:e});let h,S,T,y,D=0,U,A=1,{structureProfiles:E}=Nu({drawDefinition:c}),M=E[i];if(!M)return _({result:{error:Lt},context:{targetStructureId:i},stack:e});let P=c.matchUpType,N=d?`${d}-`:"",R=M.stage===ct,b=a?.[Ta]?.namingConventions?.pre??Bb[Ta]?.namingConventions?.pre,v=R&&b?`${b}-`:"",O=p??(N?`${v}${Ye(ct)} ${N}`:`${v}${Ye(ct)}`);if(l===Un){let{maxRoundNumber:L,structures:w,groupCount:B}=Oa({structureName:p??O,structureId:m??I?.pop(),stage:ct,structureOptions:s,appliedPolicies:a,stageSequence:A,matchUpType:P,roundTarget:d,idPrefix:f,drawSize:r,isMock:g,uuids:I});D=B,h=L,T=w[0],U=[1]}else({drawSize:r,matchUps:y,roundLimit:h,roundsCount:S}=Rn({qualifyingRoundNumber:n,qualifyingPositions:o,matchUpType:P,idPrefix:f,drawSize:r,isMock:g,uuids:I})),h||(h=S),T=In({structureName:p??O,structureId:m??I?.pop(),qualifyingRoundNumber:h,stage:ct,matchUpFormat:u,stageSequence:A,matchUpType:P,roundLimit:h,matchUps:y}),d&&At({extension:{name:Dn,value:d},element:T}),D=y?.filter(L=>L.roundNumber===h)?.length;let x=l===Un?Jn:fo,F=T&&h&&_a({sourceStructureId:T.structureId,sourceRoundNumber:h,targetStructureId:i,finishingPositions:U,linkType:x})?.link;return{qualifyingDrawPositionsCount:r,qualifiersCount:D,...C,structure:T,link:F}}function UD(t){if(!t.tournamentRecord)return{error:j};let r=Zk(t);return r.error,r}function Zk(t){if(!t.drawDefinition)return{error:X};if(!t.targetStructureId)return{error:hr};let e=Dd(t);if(e.error)return e;let{structure:r,link:n}=e;return!r||!n?{error:k}:Sg({tournamentRecord:t.tournamentRecord,drawDefinition:t.drawDefinition,structure:r,link:n})}function DD(t){let e=nt(t,[{[Le]:!0,[eu]:!0,[dn]:!0},{[jC]:!0,[sr]:m=>Number.isInteger(m)&&m>0},{[sr]:m=>Array.isArray(m)&&m.length===2&&m.every(te),[wr]:_r,participantIds:!0}]);if(e.error)return e;let{drawDefinition:r,structureId:n,tournamentRecord:o,event:i}=t,{structure:s}=at({drawDefinition:r,structureId:n});if(!s)return{error:Lt};if(!pr({structure:s}))return{error:Qo};let a=m=>m.sides?.map(d=>d.participantId).some(d=>t.participantIds.includes(d)),c=m=>m.roundNumber===t.roundNumber,u=m=>!me(m),p=(s?.matchUps??[]).filter(c).filter(u).filter(a);if(p.length!==2)return{error:_r};for(let m of p){let d=m?.sides?.find(l=>t.participantIds.includes(l?.participantId));if(d){let l=t.participantIds.find(f=>f!==d?.participantId);d.participantId=l,gt({tournamentId:o?.tournamentId,eventId:i?.eventId,drawDefinition:r,matchUp:m})}}return Ot({drawDefinition:r,structureIds:[n]}),{...C}}function rO({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=tt(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=Ud({roundPosition:S.roundPosition,roundNumber:r,idPrefix:o,uuids:a}),y={roundPosition:S.roundPosition,drawPositions:[I],matchUpStatus:zt,roundNumber:r,matchUpId:T};t&&(y.matchUpType=n),s&&(y.isMock=!0),i.push(y);let D={children:[S,h]};l.push(D)}let f=e?e-p:void 0;return{roundNodes:l,matchUps:i,drawPosition:f}}function ai(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=tG({drawSize:i}),h=I.length,S=0;if(r?.length)S=r.reduce((L,w)=>L+w,0);else if(e){let L=e-i;r=I.filter(w=>w<=L?(L-=w,!0):!1),S=r.reduce((w,B)=>w+B,0),n=r.length}else o>=h?n=0:u&&(n=h-u,o=0),r=I.filter((L,w)=>u&&!n||n&&w>=o+n||w<o?0:L),S=r.reduce((L,w)=>L+w,0),n=r.length;let T=[...I,...r].sort((L,w)=>w-L),y=T.length,U=[...(c??[]).map(L=>L-1),...(s??[]).map(L=>y-L)].map(L=>T[L]).reduce((L,w)=>L+w,0);S=S-U;let A=0,E=[],M,P=1,R=tt(0,i).map((L,w)=>({drawPosition:w+1+S})),b=S+1;for(let L of I){if({roundNodes:M,matchUps:E}=Hp({matchUpType:m,roundNumber:P,idPrefix:d,matchUps:E,isMock:l,nodes:R,uuids:f}),P++,r.includes(L)){let w=gr(r)[L],B=tt(0,w),G=y+1-P,W=s?.includes(G)??c?.includes(P);B.forEach(()=>{({roundNodes:M,matchUps:E,drawPosition:b}=rO({drawPosition:!W&&b||void 0,nodes:M,matchUpType:m,roundNumber:P,idPrefix:d,matchUps:E,isMock:l,uuids:f,fed:A})),P++,A+=1})}R=M}y!==P-1&&console.log("ERROR");let v=i-S;E=Ra({finishingPositionOffset:p?v:a,positionsFed:S,roundsCount:y,matchUps:E,fmlc:g});let x=M?.length?M[0]:M;return x&&(x.roundNumber=P-1,x.matchUps=E),{draw:x,matchUps:E,roundsCount:y};function F(L){let w=Rm(L);return w>L?w/2:w}}function tG({drawSize:t}){let e=Math.ceil(Math.log(t)/Math.log(2));return tt(0,e).reverse().map(n=>Math.pow(2,n))}function Pc(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=et,drawSize:I,idPrefix:h,isMock:S,uuids:T}=t;if(!(!s||!u||s?.[c])||I<2||f&&a>f)return{};let D=[],U=[],A=[],E=t.matchUpType??d?.matchUpType,M=e+1,P=e+I,N=`${M}-${P}`,R=s?.[c],b=n&&`${n} `||"",v=s?.[N]??o?.[N],O=t.structureName||v?.name||R?.name&&(r?`${b}${R?.name}`:R.name)||`${b}${N}`,x=v?.abbreviation??R?.abbreviation,F=t.structureId??R?.structureId??T?.pop(),L={idPrefix:h&&`${h}-${O}-RP`,finishingPositionOffset:e,matchUpType:E,drawSize:I,isMock:S,uuids:T},{matchUps:w}=l?ai(L):Rn(L),B=In({structureAbbreviation:x,stageSequence:a,structureName:O,matchUpType:E,roundOffset:m,structureId:F,matchUps:w,stage:g});D.push(...w),U.push(B);let G=Math.ceil(Math.log(I)/Math.log(2)),W=p?Math.min(p-m,G):!i||M<i?G:0;return I>2&&tt(1,W+1).forEach(q=>H(q)),{structureId:B.structureId,matchUps:D,structureName:O,structures:U,links:A,...C};function H(q){let $=I/Math.pow(2,q);if($<2)return;let V=I/Math.pow(2,q)+e;if(i&&V+1>i)return;let{structures:K,structureId:z,matchUps:Y,links:Z}=Pc({finishingPositionOffset:V,exitProfile:`${c}-${q}`,roundOffset:m+q,stageSequence:a+1,drawSize:$,addNameBaseToAttributeName:r,playoffStructureNameBase:n,finishingPositionNaming:o,finishingPositionLimit:i,playoffAttributes:s,exitProfileLimit:u,roundOffsetLimit:p,drawDefinition:d,sequenceLimit:f,matchUpType:E,idPrefix:h,uuids:T,stage:g});if(B.structureId&&z){let Q={linkType:Zn,source:{roundNumber:q,structureId:B.structureId},target:{roundNumber:1,feedProfile:yn,structureId:z}};Z&&B&&Z.push(Q),Z?.length&&A.push(...Z)}return K?.length&&U.push(...K),Y?.length&&D.push(...Y),{structureId:z,childLinks:Z,structures:U}}}function Pd({drawDefinition:t,matchUpsMap:e,structureId:r}){let n=at({drawDefinition:t,structureId:r});if(n.error)return _({result:n});let{matchUps:o}=Et({structure:n.structure,matchUpsMap:e});return{...je({matchUps:o}),matchUps:o,matchUpsMap:e}}function PD({finishingPositions:t,drawDefinition:e,structureId:r}){let{roundProfile:n}=Pd({drawDefinition:e,structureId:r});return(n&&Object.keys(n))?.reduce((i,s)=>(nO(n?.[s]).forEach(c=>{t.forEach(u=>{eG({position:u,rangeDefinition:c})&&(i[u]={roundNumber:s})})}),i),{})}function eG({position:t,rangeDefinition:e}){if(!Array.isArray(e)||e.reduce((i,s)=>i||isNaN(s),!1))return!1;let[r,n]=e;return tt(r,(n||r)+1).includes(t)}function nO(t){return[pt(t?.finishingPositionRange?.loser||[]),pt(t?.finishingPositionRange?.winner||[])]}function oO(t){return nO(t).map(e=>tt(e[0],e[1]&&e[1]+1||e[0]+1))}function Nc({drawDefinition:t,structureIds:e,matchUpsMap:r}){if(e&&!Array.isArray(e))return{error:k,context:{structureIds:e}};if(!t)return{error:X};e=e??(t.structures??[]).filter(a=>a.stage!==ct).map(({structureId:a})=>a);let n=e.map(a=>{let{roundProfile:c}=Pd({drawDefinition:t,matchUpsMap:r,structureId:a});return(c&&Object.values(c))?.map(oO).flat()}).flat(),o=n.filter(a=>a?.length===1).sort(ae).flat();return{positionsNotPlayedOff:pt(n.flat()).filter(a=>!o.includes(a)),positionsPlayedOff:o}}function CS({excludeRoundNumbers:t=[],playoffPositions:e=[],drawDefinition:r,structureId:n}){if(!r)return{error:X};if(!n)return{error:hr};if(!e)return{error:ot,info:"missing playoffPositions"};let o=Nc({drawDefinition:r});if(o.error)return o;let i=o.positionsPlayedOff,s=e.filter(S=>!i.includes(S)),a=PD({finishingPositions:s,drawDefinition:r,structureId:n}),u=Object.values(a).reduce((S,T)=>S.includes(T.roundNumber)?S:S.concat(T.roundNumber),[]).map(S=>ut(S)).filter(S=>!t.includes(S)),p=PD({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=>ut(S)):[],l=u.filter(S=>!d.includes(S)).sort(ae),{roundProfile:f}=Pd({drawDefinition:r,structureId:n}),g=l.map(S=>{let T=f?.[S].finishingPositionRange.loser,[y,D]=T??[0,0];return tt(y,(D||y)+1)}).flat().sort(ae),{playoffRoundsRanges:I}=rG({playoffSourceRounds:l,roundProfile:f}),h=[...l,...d];return{playoffPositionsReturned:g,playedOffSourceRounds:d,playoffRoundsRanges:I,playoffSourceRounds:l,sourceRounds:h,roundProfile:f}}function rG({playoffSourceRounds:t,roundProfile:e}){return{playoffRoundsRanges:t.map(n=>{let o=e[n].finishingPositionRange.loser,[i,s]=o,a=tt(i,(s||i)+1);return{finishingPositionRange:o.join("-"),finishingPositions:a,roundNumber:n}})}}function Ru({drawDefinition:t,structureId:e}){if(!t)return{error:X};let{matchUps:r,matchUpsMap:n}=Je({inContext:!0,drawDefinition:t}),{positionsNotPlayedOff:o,positionsPlayedOff:i}=Nc({drawDefinition:t,matchUpsMap:n}),{structures:s}=ln({drawDefinition:t}),a=s.filter(u=>!e&&u.stage!==Be||u.structureId===e),c={};for(let u of a){let p=u?.structureId,m=nG({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 nG({playoffPositions:t,drawDefinition:e,structure:r,matchUps:n}){let o=r?.structureId,{links:i}=Ks({drawDefinition:e,structureId:o});if(r.structureType===we||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=tt(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:D=[]}=Nc({structureIds:T,drawDefinition:e}),U=[...y,...D],A=tt(S[0],S[1]+1).filter(P=>!U.includes(P)),E=Ae(A,A.length/h.length),M=h.map((P,N)=>{let R=E[N],b=[Math.min(...R||[]),Math.max(...R||[])].join("-");return{finishingPosition:P,finishingPositions:R,finishingPositionRange:b}});return{positionsNotPlayedOff:A,playoffFinishingPositionRanges:M,finishingPositionsAvailable:h,finishingPositionsPlayedOff:I,positionsPlayedOff:y,groupCount:f,groupSize:g}}let s=i?.source?.filter(l=>l.linkCondition!==to).map(l=>l.source?.roundNumber)||[],a=i?.source?.filter(l=>l.linkCondition===to).map(l=>l.source?.roundNumber)||[],c=CS({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),D=y+S,U=tt(y,D),A={finishingPositionRange:[y,D-1].join("-"),finishingPositions:U,roundNumber:l};p.push(A)}}}return u&&u.sort(ae),p.sort((l,f)=>l.roundNumber-f.roundNumber),{playoffRounds:u,playoffRoundsRanges:p,error:d}}function iO({playoffGroups:t,drawDefinition:e,structureId:r}){if(!e)return{error:X};if(typeof r!="string"||!Array.isArray(t))return{error:k};let n=t.map(({finishingPositions:a})=>a).flat();return{positionRangeMap:Ru({drawDefinition:e,structureId:r}).playoffFinishingPositionRanges?.filter(a=>n.includes(a.finishingPosition))?.reduce((a,c)=>(a[c.finishingPosition]=c,a),{})}}function bS(t){let{finishingPositionOffset:e=0,playoffAttributes:r,stageSequence:n=1,staggeredEntry:o,structureName:i,stage:s=et,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?ai(l):Rn(l),g=In({structureName:i||r?.["0"]?.name||Ye(et),structureId:c||d?.pop(),stageSequence:n,matchUpType:a,matchUps:f,stage:s}),I=[g],h=[];if(p>2){let S=p/2,{matchUps:T}=Rn({finishingPositionOffset:e+S,idPrefix:u&&`${u}-c`,drawSize:S,matchUpType:a,isMock:m}),y=Ye(Ve),D=r?.["0-1"]?.name??t.consolationStructureName??(i?`${i} ${y}`:y),U=In({structureName:D,matchUps:T,structureId:d?.pop(),stage:Ve,stageSequence:1,matchUpType:a});I.push(U);let A={linkType:Zn,source:{roundNumber:1,structureId:g.structureId},target:{roundNumber:1,feedProfile:yn,structureId:U.structureId}};h.push(A)}return{...C,structures:I,links:h}}function vS({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 tt(1+e,n+1+e).map(p=>{let m=u&&u[p-1]?u[p-1]:p%2?yn:Ii,d=p-e<=2?p-e:(p-e-2)*2+2,l={linkType:Zn,source:{roundNumber:p,structureId:r.structureId},target:{feedProfile:m,roundNumber:d,structureId:t.structureId}},f=c[p-1];return f&&(l.target.groupedOrder=f),Sr()&&(l.source.structureName=r.structureName,l.target.structureName=t.structureName),p===2&&i&&(l.linkCondition=to,l.target.feedProfile=yn),a.includes(d)?l:void 0}).filter(Boolean)}function OS(t){let{playoffStructureNameBase:e,finishingPositionOffset:r,stageSequence:n=1,playoffAttributes:o,structureNameMap:i,staggeredEntry:s,stage:a=et,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?ai(f):Rn(f),h=t.structureName??o?.["0"]?.name??Ye(et),S=As({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((E,M)=>{let P=M+1,{consolationStructure:N}=oG({idPrefix:m&&`${m}-c${M}`,structureId:l?.pop(),playoffStructureNameBase:e,playoffAttributes:o,structureNameMap:i,stageSequence:P,roundOffset:E,matchUpType:c,drawSize:p,isMock:d,index:M,uuids:l});T.push(N);let R=vS({consolationStructure:N,roundsCount:2,mainStructure:S,roundOffset:E});return{consolationStructure:N,links:R}}).map(E=>E.links).flat();if(y.push(...A),p>=4&&p<=16||p>32){let{matchUps:E}=Rn({idPrefix:m&&`${m}-p3t4`,finishingPositionOffset:2,drawSize:2,matchUpType:c,isMock:d}),M=o?.["3-4"]?.name??Ye(pe),P=i?.[M]||M,N=e?`${e} ${P}`:P,R=As({structureId:l?.pop(),matchUps:E,stageSequence:2,stage:pe,structureName:N,matchUpType:c}),b={linkType:Zn,source:{roundNumber:I-1,structureId:S.structureId},target:{structureId:R.structureId,feedProfile:yn,roundNumber:1}};T.push(R),y.push(b)}}return{structures:T,links:y,...C}}function oG({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}=ai({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||`${Ye(Ve)} ${p+1}`,h=n?.[I]||I,S=t?`${t} ${h}`:h;return{consolationStructure:As({matchUps:l,stage:Ve,structureName:S,stageSequence:e,matchUpType:i,structureId:s}),consolationRoundsCount:f}}function Mc(t){let{finishingPositionOffset:e,stageSequence:r=1,playoffAttributes:n,feedsFromFinal:o,staggeredEntry:i,structureName:s,stage:a=et,structureId:c,matchUpType:u,skipRounds:p,feedRounds:m,idPrefix:d,drawSize:l,isMock:f,uuids:g,fmlc:I}=t,h=t.feedPolicy||t.policyDefinitions?.[cc]||t.appliedPolicies?.[cc],S={finishingPositionOffset:e,matchUpType:u,skipRounds:p,drawSize:l,idPrefix:d,isMock:f,uuids:g},{matchUps:T}=i?ai(S):Rn(S),y=In({structureName:s||n?.["0"]?.name||Ye(et),structureId:c||g?.pop(),stageSequence:r,matchUpType:u,matchUps:T,stage:a}),D=[y],U=[],A=l/2,{matchUps:E,roundsCount:M}=ai({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??Ye(Ve),N=t.playoffStructureNameBase?`${t.playoffStructureNameBase} ${P}`:P,R=In({matchUps:E,structureId:g?.pop(),stage:Ve,stageSequence:1,structureName:N,matchUpType:u});D.push(R);let b=vS({consolationStructure:R,mainStructure:y,roundsCount:M,feedPolicy:h,fmlc:I});U.push(...b)}return{...C,structures:D,links:U}}function xS({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?.[cc];let f="processPlayoffGroups",g=0,I=[],h=[],S=[],{error:T,positionRangeMap:y}=iO({structureId:n,drawDefinition:s,playoffGroups:a});if(T)return _({result:{error:T},stack:f});if(!(!y||a?.every(U=>{let{finishingPositions:A=[]}=U;if(!A.length)return!1;let E=[...A].sort(ae).map((M,P)=>(A[P+1]||M)-M).every(M=>M<2);return(!t||E)&&A.every(M=>y[M])})))return _({context:{validFinishingPositions:Object.values(y)},result:{error:k},stack:f});for(let U of a){let A=U.finishingPositions,E=y&&A.map(F=>y[F]?.finishingPositions).flat(),M=p*A.length,P=os(M),N=P===2&&go||U.drawType||go;E&&(g=Math.min(...E)-1);let R=E&&`${Math.min(...E)}-${Math.max(...E)}`,b=U.structureName||R&&U.playoffAttributes?.[R]?.name||U.playoffAttributes?.["0"]?.name,O={...{addNameBaseToAttributeName:U.addNameBaseToAttributeName,playoffStructureNameBase:U.playoffStructureNameBase,finishingPositionNaming:U.finishingPositionNaming,finishingPositionLimit:U.finishingPositionLimit,structureId:U.structureId??l?.pop(),playoffAttributes:U.playoffAttributes,structureNameMap:U.structureNameMap,sequenceLimit:U.sequenceLimit,structureName:b},idPrefix:m&&`${m}-po`,appliedPolicies:o,finishingPositionOffset:g,stage:pe,stageSequence:i,matchUpType:c,drawSize:P,isMock:d,uuids:l},x=({playoffStructures:F,playoffLinks:L})=>{let[w]=F,B=_S({playoffStructureId:w.structureId,finishingPositions:A,sourceStructureId:n});S.push(B),S.push(...L),h.push(...F),I.push({structureId:w.structureId,finishingPositions:A}),g+=M};if(N===go){let{matchUps:F}=Rn({finishingPositionLimit:g+M,idPrefix:m&&`${m}-po`,finishingPositionOffset:g,matchUpType:c,drawSize:P,isMock:d,uuids:l}),L=In({structureId:U.structureId??l?.pop(),matchUpFormat:e,stage:pe,structureName:b,stageSequence:i,matchUps:F});h.push(L);let w=_S({playoffStructureId:L.structureId,finishingPositions:A,sourceStructureId:n});S.push(w),g+=M,I.push({structureId:L.structureId,finishingPositions:A})}else if([Xc,Jc,pe].includes(N)){let F={playoffAttributes:U.playoffAttributes??r,playoffStructureNameBase:U.playoffStructureNameBase,structureId:U.structureId??l?.pop(),structureName:U.structureName,idPrefix:m&&`${m}-po`,addNameBaseToAttributeName:!0,finishingPositionOffset:g,stage:pe,roundOffset:0,stageSequence:i,drawSize:P,isMock:d,uuids:l};N===Xc?Object.assign(F,{playoffAttributes:U?.playoffAttributes??r??lf,roundOffsetLimit:3}):N===Jc&&Object.assign(F,{playoffAttributes:U?.playoffAttributes??r??ff,roundOffsetLimit:2});let L=Pc(F);if(L.error)return L;if(L.links?.length&&S.push(...L.links),L.structures?.length&&h.push(...L.structures),h.sort(Ai),L.structureId){let w=_S({playoffStructureId:L.structureId,finishingPositions:A,sourceStructureId:n});S.push(w),I.push({structureId:L.structureId,finishingPositions:A})}g+=M}else if([tu,gp,_m,Om,vm,xm].includes(N)){let F=[l?.pop(),l?.pop()],L={playoffStructureNameBase:U.playoffStructureNameBase,structureId:U.structureId??l?.pop(),playoffAttributes:U.playoffAttributes,idPrefix:m&&`${m}-po`,finishingPositionOffset:g,uuids:F,stage:pe,structureName:b,matchUpType:c,feedPolicy:u,drawSize:P,isMock:d},w={[tu]:{fmlc:!0,feedRounds:1},[xm]:{feedRounds:1},[_m]:{feedsFromFinal:3},[Om]:{feedsFromFinal:2},[vm]:{feedsFromFinal:1}};Object.assign(L,w[N]||{});let{structures:B,links:G}=Mc(L),[W]=B,H=_S({playoffStructureId:W.structureId,finishingPositions:A,sourceStructureId:n});S.push(H),S.push(...G),h.push(...B),I.push({structureId:W.structureId,finishingPositions:A}),g+=M}else if([Un].includes(N)){let{structures:F,links:L}=Oa({...O,structureOptions:U.structureOptions||{groupSize:4}});x({playoffStructures:F,playoffLinks:L})}else if([fp].includes(N)){let{structures:F,links:L}=bS(O);x({playoffStructures:F,playoffLinks:L})}else if([GC].includes(N)){let{structures:F,links:L}=OS(O);x({playoffStructures:F,playoffLinks:L})}else if([an].includes(N)){let F=In({structureId:U.structureId??l?.pop(),structureName:U.structureName,finishingPosition:Zm,stage:pe,stageSequence:i,matchUps:[]});x({playoffStructures:[F],playoffLinks:[]})}}return{finishingPositionTargets:I,positionRangeMap:y,structures:h,links:S}}function _S({playoffStructureId:t,finishingPositions:e,sourceStructureId:r}){return{linkType:Jn,source:{structureId:r,finishingPositions:e},target:{structureId:t,feedProfile:mn,roundNumber:1}}}function xa({matchUp:t,tieFormat:e,isMock:r,uuids:n}){let{collectionDefinitions:o}=e??{};return{tieMatchUps:(o??[]).map(s=>Cu({matchUp:t,collectionDefinition:s,uuids:n,isMock:r})).filter(Boolean).flat()}}function Cu({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()??Nt();let l=e?.collectionId;return i?.pop()??`${n?.matchUpId}-${l}-TMU-${d+1}`};return tt(0,p).map(d=>{let l=t+d+1;return{sides:[{sideNumber:1},{sideNumber:2}],matchUpId:m(d),matchUpStatus:zt,collectionPosition:l,collectionId:c,processCodes:u,matchUpType:a,isMock:o}})}function sO(t){let e="generateAndPopulateRRplayoffStructures";if(!t.playoffGroups)return _({result:{error:ot},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}=xS({requireSequential:n,sourceStructureId:r,playoffGroups:s,groupCount:a,groupSize:c,...t});if(f)return{error:f};let g=d?.map(({finishingPositions:E})=>E).flat().map(E=>l[E].finishingPositions).flat();i.structures.push(...p),i.links.push(...m);let{matchUps:I,matchUpsMap:h}=re({inContext:!0,drawDefinition:i}),S=p.map(({structureId:E})=>E),T=I?.filter(({structureId:E})=>S.includes(E)).map(Ie),y=h?.drawMatchUps?.filter(({matchUpId:E})=>T?.includes(E));if(y?.length){let E=We({drawDefinition:i,event:u})?.tieFormat;E&&y.forEach(M=>{let{tieMatchUps:P}=xa({isMock:t.isMock,tieFormat:E,matchUp:M});Object.assign(M,{tieMatchUps:P,matchUpType:Nn})})}let{positionAssignments:D}=Ct({structureId:r,drawDefinition:i}),U={};D?.forEach(E=>{let N=mt({element:E,name:Zo})?.extension?.value?.groupOrder;N&&(U[N]||(U[N]=[]),U[N].push(E.participantId))});let A=Dc({provisionalPositioning:t.provisionalPositioning,structureId:r,applyPositioning:!0,event:t.event,tournamentRecord:o,drawDefinition:i});return A.error&&A.error?.code!==_l.code?_({result:A,stack:e}):{structures:p,links:m,positionsPlayedOff:g,drawDefinition:i,...C}}function bu({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 zn="ELO",ND="NTRP",iG="TRN",MD="UTR",Dg="WTN",aO={ELO:zn,NTRP:ND,TRN:iG,UTR:MD,WTN:Dg};var sG={[zn]:{defaultInitialization:1500,decimalsCount:0,range:[0,3e3],ascending:!0},[ND]:{accessors:["ntrpRating","dntrpRatingHundredths"],attributes:{ustaRatingType:""},accessor:"dntrpRatingHundredths",defaultInitialization:3,decimalsCount:1,ascending:!0,range:[1,7]},[MD]:{defaultInitialization:6,accessors:["utrRating"],accessor:"utrRating",decimalsCount:2,ascending:!0,range:[1,16]},[Dg]:{attributes:{confidence:{generator:!0,range:[60,100]}},accessors:["wtnRating","confidence"],defaultInitialization:23,accessor:"wtnRating",ascending:!1,decimalsCount:2,range:[40,1]}},ve=sG;function cO({sourceRatingType:t,sourceRating:e}){let r=ve[t].range,n=r[0]>r[1],o=ve[zn].range;return bu({value:n?r[0]-e:e,sourceRange:r,targetRange:o})}function uO({targetRatingType:t,sourceRating:e}){let r=ve[t].decimalsCount||0,n=ve[t].range,o=n[0]>n[1],i=Math.max(...n),s=ve[zn].range,a=bu({targetRange:n,sourceRange:s,value:e}),c=parseFloat(a.toFixed(r));return o?i-c:c}function RD(t){let e=nt(t,[{ratings:!0,[ar]:zr}]);if(e.error)return e;let r=t.matchUpType&&[Bt,kt].includes(t.matchUpType)?t.matchUpType:Bt,n=Object.keys(ve),o=t.targetRatingType&&n.includes(t.targetRatingType)?t.targetRatingType:zn,i=t.ratings[r]?t.ratings[r].reduce((d,l)=>d.includes(l.scaleName)?d:d.concat(l.scaleName),[]):[];if(!i)return{error:Pe};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=ve[s.scaleName].accessor,u=c?s.scaleValue[c]:s.scaleValue,p=cO({sourceRatingType:a,sourceRating:u});return{convertedRating:uO({targetRatingType:o,sourceRating:p}),sourceRating:u}}function pO({participantResults:t,sides:e,score:r}){let n=e.find(({sideNumber:a})=>a===1),o=e.find(({sideNumber:a})=>a===2),i=n?.participant?.ratings,s=o?.participant?.ratings;if(i?.[Bt]&&s?.[Bt]){let a=zn,{convertedRating:c}=RD({ratings:i,targetRatingType:a}),{convertedRating:u}=RD({ratings:s,targetRatingType:a}),{side1pressure:p,side2pressure:m}=aG({side1ConvertedRating:c,side2ConvertedRating:u,score:r});p&&t[n?.participantId].pressureScores.push(p),m&&t[o?.participantId].pressureScores.push(m);let d=Math.max(...ve[zn].range),l=of((u-c)/d),f=of((c-u)/d);t[n?.participantId].ratingVariation.push(l),t[o?.participantId].ratingVariation.push(f)}}function aG({side1ConvertedRating:t,side2ConvertedRating:e,score:r}){let n=t>e?t:e,o=t>e?e:t,i=Math.abs(t-e),s=ve[zn].range,a=Math.max(...s),c=(a-n)*0,p=(n+c)/a*i,m=r?.sets?.reduce((T,y)=>T+(y?.side1Score??0),0),d=r?.sets?.reduce((T,y)=>T+(y.side2Score??0),0),l=t>e?2:1,f=(m||0)*(o+(l===1?p:0)),g=(d||0)*(o+(l===2?p:0)),I=f+g,h=I?of(f/I):0,S=I?of(g/I):0;return{side1pressure:h,side2pressure:S}}var Cn="SET3-S:6/TB7",cG="SET3-S:6NOAD",CD="SET3-S:6/TB7-F:TB10",uG="SET3-S:4/TB7",pG="SET3-S:4/TB5@3",mG="SET1-S:T20",dG="SET1-S:8/TB7",lG="SET1-S:8/TB7@7",mO={FORMAT_STANDARD:Cn,FORMAT_STANDARD_NOAD:cG,FORMAT_ATP_DOUBLES:CD,FORMAT_SHORT_SETS:uG,FORMAT_FAST4:pG,FORMAT_PRO_SET:dG,FORMAT_COLLEGE_PRO_SET:lG,TIMED20:mG};function Pg({winningSide:t,matchUpFormat:e=Cn,matchUpStatus:r,tallyPolicy:n,score:o}){let i=[0,0],s=o?.sets,a=typeof t=="number"&&t-1,c=rr(e),u=bD(c?.bestOf??1);if(typeof a=="number"&&(r===Mt&&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===Qe&&(+i[1-a]===u&&(i[1-a]-=1),n?.setsCreditForRetirements&&(i[a]=u)),i}function wS({matchUpFormat:t=Cn,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=bD(c),p=a?.setFormat?.tiebreakAt||0,m=[[],[]];if(typeof s=="number"&&(r===Mt&&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;dO(I)&&(m[0].push(ut(S||0)),m[1].push(ut(T||0))),h&&d.winningSide&&n?.gamesCreditForTiebreakSets!==!1&&m[d.winningSide-1].push(1)});if(r===Qe&&typeof s=="number"){let d=i.length>u&&a?.finalSetFormat?"finalSetFormat":"setFormat",l=a?.[d];if(dO(l.based)){let f=l?.setTo||0,g=S=>{if(!(!a||S===""))return+S===p-1||+S===p?ut(p||0)+1:+S<p?f:p},I=Pg({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=bD(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(lO(m)){let{side1Score:d,side2Score:l}=a;d&&(s[0]+=ut(d||0)),l&&(s[1]+=ut(l||0))}else a.side1TiebreakScore&&(s[0]+=ut(a.side1TiebreakScore||0)),a.side2TiebreakScore&&(s[1]+=ut(a.side2TiebreakScore||0)),(a.side1TiebreakScore||a.side2TiebreakScore)&&a.winningSide&&(i[a.winningSide-1]+=1)}),{pointsTally:s,tiebreaksTally:i}}function bD(t){return t&&Math.ceil(t/2)||1}function lO(t){return t==="P"}function dO(t){return!lO(t)}function fO({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,D=Math.round(S/y*1e3)/1e3;(D===1/0||isNaN(D))&&(D=S);let U=t[u].gamesWon||0,A=t[u].gamesLost||0,E=(n||0)*(a||0)*(c||0),M=Math.max(E,U+A),P=Math.round(U/M*1e3)/1e3;(P===1/0||isNaN(P))&&(P=0);let N=t[u].pointsWon+t[u].pointsLost,R=Math.round(t[u].pointsWon/N*1e3)/1e3;(R===1/0||isNaN(R))&&(R=0),t[u].setsWon=p,t[u].setsLost=m,t[u].setsPct=l,t[u].tieMatchUpsWon=f,t[u].tieMatchUpsPct=h,t[u].matchUpsPct=D,t[u].gamesWon=U,t[u].gamesLost=A,t[u].gamesPct=P,t[u].pointsPct=R,t[u].result=`${t[u].matchUpsWon}/${t[u].matchUpsLost}`})}function vu({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||qt(t,[Nd(m,0),Nd(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&&fG(m),y=I&&gG(m);if(!T&&!y)if(d&&ie.includes(d)){let A=Nd(m,0),E=Nd(m,1);A&&(Rc(s,A),s[A].matchUpsCancelled+=1),E&&(Rc(s,E),s[E].matchUpsCancelled+=1)}else if(l?.length){o=0;for(let A of l){if(A.winningSide){let E=h?.find(({sideNumber:P})=>P===A.winningSide)?.participantId,M=h?.find(({sideNumber:P})=>P===A.winningSide)?.participantId;E&&M&&(Rc(s,E),Rc(s,M),s[E].tieMatchUpsWon+=1,s[M].tieMatchUpsLost+=1,se(Bt)(A.matchUpType)?(s[E].tieSinglesWon+=1,s[M].tieSinglesLost+=1):se(kt)(A.matchUpType)&&(s[E].tieDoublesWon+=1,s[M].tieDoublesLost+=1))}gO({score:A.score,manualGamesOverride:S,participantResults:s,sides:h})}}else gO({manualGamesOverride:S,participantResults:s,score:g,sides:h});else if(Rc(s,T),Rc(s,y),l?.length){o=0;for(let A of l){let{matchUpType:E}=A,M=se(kt)(E),P=se(Bt)(E);A.winningSide&&(A.winningSide===I?(T&&(s[T].tieMatchUpsWon+=1,P&&(s[T].tieSinglesWon+=1),M&&(s[T].tieDoublesWon+=1)),y&&(s[y].tieMatchUpsLost+=1,P&&(s[y].tieSinglesLost+=1),M&&(s[y].tieDoublesLost+=1))):A.winningSide!==I&&(y&&(s[y].tieMatchUpsWon+=1,P&&(s[y].tieSinglesWon+=1),M&&(s[y].tieDoublesWon+=1)),T&&(s[T].tieMatchUpsLost+=1,P&&(s[T].tieSinglesLost+=1),M&&(s[T].tieDoublesLost+=1)))),IO({matchUpFormat:A.matchUpFormat,matchUpStatus:A.matchUpStatus,matchUpType:A.matchUpType,score:A.score,sides:A.sides,winningParticipantId:T,losingParticipantId:y,manualGamesOverride:S,participantResults:s,isTieMatchUp:!0,pressureRating:e,tallyPolicy:n,winningSide:I})}hO({winningParticipantId:T,losingParticipantId:y,participantResults:s,matchUpStatus:d})}else IO({matchUpFormat:m.matchUpFormat??r,matchUpType:m.matchUpType,isTieMatchUp:void 0,winningParticipantId:T,manualGamesOverride:S,losingParticipantId:y,participantResults:s,pressureRating:e,matchUpStatus:d,tallyPolicy:n,winningSide:I,score:g,sides:h});let D=g?.sets?.reduce((A,E)=>A+(E?.side1Score??0),0),U=g?.sets?.reduce((A,E)=>A+(E.side2Score??0),0);if(S){let A=h?.find(({sideNumber:M})=>M===1)?.participantId,E=h?.find(({sideNumber:M})=>M===2)?.participantId;Rc(s,A),Rc(s,E),A&&(s[A].gamesWon+=D,s[A].gamesLost+=U),E&&(s[E].gamesWon+=U,s[E].gamesLost+=D)}}return fO({participantResults:s,matchUpFormat:r,tallyPolicy:n,perPlayer:o,totalSets:p}),{participantResults:s}}function fG(t){let e=t.winningSide-1;return Nd(t,e)}function gG(t){let e=1-(t.winningSide-1);return Nd(t,e)}function Nd(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 Rc(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 gO({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(ut(p||0)),i[1].push(ut(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&&(Rc(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 IO({winningParticipantId:t,manualGamesOverride:e,losingParticipantId:r,participantResults:n,pressureRating:o,matchUpFormat:i,matchUpStatus:s,isTieMatchUp:a,matchUpType:c,tallyPolicy:u,winningSide:p,score:m,sides:d}){let l=p&&p-1,f=1-l;o&&c===Bt&&pO({participantResults:n,sides:d,score:m}),a||hO({winningParticipantId:t,losingParticipantId:r,participantResults:n,matchUpStatus:s});let g=Pg({matchUpStatus:s,matchUpFormat:i,tallyPolicy:u,winningSide:p,score:m}),I=wS({matchUpStatus:s,matchUpFormat:i,tallyPolicy:u,winningSide:p,score:m}),{pointsTally:h}=LS({score:m,matchUpFormat:i});t&&(n[t].setsWon+=g[l],n[t].setsLost+=g[f],e||(n[t].gamesWon+=I[l],n[t].gamesLost+=I[f]),n[t].pointsWon+=h[l],n[t].pointsLost+=h[f]),r&&(n[r].setsWon+=g[f],n[r].setsLost+=g[l],e||(n[r].gamesWon+=I[f],n[r].gamesLost+=I[l]),n[r].pointsWon+=h[f],n[r].pointsLost+=h[l])}function hO({winningParticipantId:t,losingParticipantId:e,participantResults:r,matchUpStatus:n}){e&&(n===vt&&(r[e].walkovers+=1),n===Mt&&(r[e].defaults+=1),n===Qe&&(r[e].retirements+=1),[Mt,Qe,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 SO({matchUps:t,order:e,report:r}){let n={};t.forEach(({sides:i})=>{i.forEach(s=>{s.participantId&&s.participant&&(n[s.participantId]=s.participant.participantName)})});let o=[];return Array.isArray(r)&&r.forEach((i,s)=>{if(i.excludedDirectives?.length){let a=i.excludedDirectives.map(({attribute:p})=>p).join(", "),c=`${a.length} directives were excluded due to participants limit}`;o.push(c);let u=`Excluded: ${a}`;o.push(u)}else{let a=(l,f)=>parseFloat(i.reversed?l:f)-parseFloat(i.reversed?f:l),c=i.groups?Object.values(i.groups).flat(1/0).length:i.participantIds?.length??0,u=l=>{l.groups&&Object.keys(l.groups).sort(a).forEach(f=>{let g=l.groups[f].map(h=>n[h]).join(", "),I=`${f} ${l.attribute}: ${g}`;o.push(I)})},p=i.reversed?" in reverse order":"",m=i.groups?"grouped":"separated",d=`Step ${s+1}: ${c} particiants were ${m}${p} by ${i.attribute}`;if(o.push(d),i.idsFilter){let l=`${i.attribute} was calculated considering ONLY TIED PARTICIPANTS`;o.push(l)}u(i)}o.push("----------------------")}),o.push("Final Order:"),e.forEach(i=>{let{participantId:s,resolved:a}=i,c=i.groupOrder||i.provisionalOrder;o.push(`${c}: ${n[s]} => resolved: ${!!a}`)}),o.join(`\r
|
|
4
|
-
`)}function vD({participantResults:t,participantIds:e,attribute:r}){return OD({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 OD(t){return(t.participantIds||Object.keys(t.participantResults)).reduce((r,n,o)=>(r.push({participantId:n,i:o,results:t.participantResults[n]}),r),[])}var IG=[{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}],_D={matchUpsPct:20,tieMatchUpsPct:16,pointsPct:4,gamesPct:8,setsPct:12};function xD(t){let{requireCompletion:e=!0,participantResults:r,subOrderMap:n,tallyPolicy:o}=t,i=[];if(e&&!hG(t))return{};let s=["tieMatchUpsWon","tieSinglesWon","tieDoublesWon","matchUpsWon","pointsWon","gamesWon","setsWon","gamesPct","setsPct","pointsPct","matchUpsPct"].includes(o?.groupOrderKey)?o.groupOrderKey:"matchUpsWon",a=vD({participantResults:r,attribute:s});i.push({attribute:s,groups:a});let p=Object.keys(a).map(S=>parseFloat(S)).sort((S,T)=>T-S).map(S=>a[S]).map(S=>{let T=TO({participantIds:S,...t});return i.push(...T.report??[]),T.order}).map((S,T)=>S.map(y=>y.resolved?y:{...y,subGroup:[T].concat(...y.subGroup??[])})).flat(),m,d=0,l=1,f;p.forEach((S,T)=>{T&&(S.resolved||f&&!S.resolved)&&(l+=1),f=S.resolved;let y=parseInt(S.subGroup?.join("")||0);S.resolved?(S.position=T+1,l=S.position):(m&&y>m&&(l+=d,d=0),S.position=l,d+=1),m=y});let g=p.map(({position:S})=>S),I=gr(g);return p.forEach(S=>{let{participantId:T,position:y}=S||{},D=r[T];S.GEMscore=h(D);let U=I[y];S?.position!==void 0&&(U>1&&(S.ties=U,n&&(S.subOrder=n[T])),S.rankOrder=y,S.groupOrder=y+(S.subOrder||1)-1)}),{groupOrder:p,report:i.flat(1/0).filter(Boolean)};function h(S){return(Array.isArray(o?.GEMscore)?Object.keys(_D).filter(D=>o.GEMscore.includes(D)):Object.keys(_D)).map(D=>(S[D]||0)*Math.pow(10,_D[D].toFixed(3))).reduce((D,U)=>D+U,0)}}function hG({participantResults:t,participantsCount:e}){let n=OD({participantResults:t}).filter(o=>e-1===o.results.matchUpsWon+o.results.matchUpsLost+o.results.matchUpsCancelled);return e===n.length}function SG({disableHeadToHead:t,participantIds:e,matchUpFormat:r,tallyPolicy:n,attribute:o,idsFilter:i,matchUps:s,reversed:a}){let{participantResults:c}=vu({participantIds:i&&e,matchUpFormat:r,tallyPolicy:n,matchUps:s}),u=vD({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(f=>parseFloat(f)).sort((f,g)=>a?f-g:g-f).map(f=>u[f]).map(f=>{let g=TO({participantResults:c,disableHeadToHead:t,participantIds:f,matchUpFormat:r,tallyPolicy:n,matchUps:s});return p.push(...g.report??[]),g.order}).map((f,g)=>f.map(I=>I.resolved?I:{...I,subGroup:[g].concat(...I.subGroup??[])})).flat()),{order:m,report:p}}function TO({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=TG({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||IG).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=SG({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 TG({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 wa({policyDefinitions:t,generateReport:e,pressureRating:r,matchUpFormat:n,matchUps:o=[],subOrderMap:i,perPlayer:s}){if(!o?.length||!Lr(o))return{error:Xn};let a=pt(o.map(({structureId:y})=>y));if(a.length!==1)return _({result:{error:k,info:"Maximum one structureId"},stack:"tallyParticipantResults",context:{structureIds:a}});let c=o.filter(y=>y&&y.matchUpStatus!==Pt),u=c.length&&pt(c.map(({drawPositions:y})=>y).flat()).length,p=c.filter(y=>gs({matchUp:y})).length===c.length;p||(s=0);let m=o.every(({matchUpType:y,tieMatchUps:D})=>y===Ht&&D?.every(U=>gs({matchUp:U}))),d=t?.[Uf],l=o.filter(y=>gs({matchUp:y})||y.matchUpType===Ht),{participantResults:f}=vu({matchUps:l,pressureRating:r,matchUpFormat:n,tallyPolicy:d,perPlayer:s}),g,I,{groupOrder:h,report:S}=xD({matchUps:l,participantResults:f,participantsCount:u,matchUpFormat:n,tallyPolicy:d,subOrderMap:i});if(r&&yG({participantResults:f}),p&&h)g=S,I=h,h.forEach(y=>{let{participantId:D,groupOrder:U,rankOrder:A,subOrder:E,ties:M,GEMscore:P}=y,N=f[D];Object.assign(N,{groupOrder:U,rankOrder:A,GEMscore:P,subOrder:E,ties:M})});else{let{groupOrder:y,report:D}=xD({requireCompletion:!1,participantResults:f,participantsCount:u,matchUpFormat:n,tallyPolicy:d,subOrderMap:i,matchUps:o});g=D,I=y,y&&y.forEach(U=>{let{participantId:A,groupOrder:E,GEMscore:M}=U,P=f[A];Object.assign(P,{provisionalOrder:E,GEMscore:M})})}let T={completedTieMatchUps:m,readableReport:"",participantResults:f,bracketComplete:p,order:[],report:g};if((p||m)&&(T.order=I),e||Sr({tally:!0})){let y=SO({matchUps:o,report:g,order:I});Sr({tally:!0})&&console.log(y),T.readableReport=y}return T}function yG({participantResults:t}){let e=o=>o.reduce((i,s)=>i+parseFloat(s),0),r=o=>parseFloat((e(o)/o.length).toFixed(2)),n=Object.keys(t).map(o=>{let i=t[o],{pressureScores:s}=i,a=s?.length?r(s):0;return{participantId:o,averagePressure:a}}).sort((o,i)=>(i.averagePressure||0)-(o.averagePressure||0)).map((o,i)=>({...o,order:i+1}));for(let o of n)t[o.participantId].pressureOrder=o.order}function FS({positionAssignments:t}){let e=(t||[]).filter(Fr(eo)).map(i=>{let{extension:s}=mt({element:i,name:uc}),a=ut(s?.value),c=!isNaN(a)&&a;return c&&{participantId:i.participantId,subOrder:c}}).filter(Boolean),r=e.map(({subOrder:i})=>i),n=gr(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(!Lr(o))return{error:k};if(!t)return{error:k};let{policyDefinitions:s}=_o({policyTypes:[Uf],tournamentRecord:e,drawDefinition:r,event:i}),{subOrderMap:a}=FS({positionAssignments:t}),c=o.length?wa({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:Zo};At({element:l,extension:g}),u[f].ties||ur({element:l,name:uc})}else ur({element:l,name:Zo}),ur({element:l,name:uc})}),Ot({drawDefinition:r}),{...C,participantResults:u,bracketComplete:p,report:m}}function kS({matchUps:t,matchUpId:e}){return{matchUp:(t||[]).find(n=>n.matchUpId===e)}}function Gt(t){let e=nt(t,[{[Le]:!0,[dn]:!0}]);if(e.error)return e;let{tournamentParticipants:r,afterRecoveryTimes:n,contextProfile:o,drawDefinition:i,matchUpsMap:s,matchUpId:a,inContext:c,context:u,event:p}=t,{structures:m=[]}=ln({drawDefinition:i}),d=t.contextContent||o&&Yn({contextProfile:o,drawDefinition:i});for(let l of m){let{matchUps:f}=Et({tournamentParticipants:r,afterRecoveryTimes:n,contextContent:d,drawDefinition:i,contextProfile:o,matchUpsMap:s,inContext:c,structure:l,context:u,event:p}),{matchUp:g}=kS({matchUps:f,matchUpId:a});if(g)return{matchUp:g,structure:l}}return{error:_e}}function Wp(t){return!It(t)||!t.notes?{error:ot}:It(t.element)?!te(t.notes)&&!t.notes?.testing?{error:k}:(Object.assign(t.element,{notes:t.notes}),{...C}):{error:k}}function Ng(t){return It(t)?It(t.element)?(t.element.notes&&delete t.element.notes,{...C}):{error:k}:{error:ot}}var Ou={matchUpStatus:zt,matchUpStatusCodes:[],score:{scoreStringSide1:"",scoreStringSide2:"",sets:void 0},matchUpFormat:void 0,winningSide:void 0};function kn(t){let e="modifyMatchUpScore",r=t.matchUpFormat,n=t.matchUp,o,{matchUpStatusCodes:i,removeWinningSide:s,tournamentRecord:a,drawDefinition:c,matchUpStatus:u,removeScore:p,winningSide:m,matchUpId:d,event:l,notes:f,score:g}=t,h=t.appliedPolicies&&Object.keys(t.appliedPolicies).length?t.appliedPolicies:yt({policyTypes:[Qr],tournamentRecord:a,drawDefinition:c,structure:o,event:l})?.appliedPolicies,S=n.matchUpType===Ht;if(S&&c){if(d&&n.matchUpId!==d){let M=Gt({drawDefinition:c,matchUpId:d,event:l});if(!M.matchUp)return{error:_e};({matchUp:n,structure:o}=M)}}else n.matchUpId!==d&&console.log("!!!!!");u&&[vt,he].includes(u)||p?Object.assign(n,{...Ou}):g&&(n.score=g);let T=u&&n?.matchUpStatus===Mt&&u!==Mt;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}=Gt({drawDefinition:c,matchUpId:d,event:l})),u&&!n.winningSide&&me(n)&&!ie.includes(u)&&![pc,as].includes(u)&&(n.matchUpStatus=Ln);let y;if((T&&n?.processCodes?.length||u===Mt)&&(y=h?.[Qr]?.processCodes?.incompleteAssignmentsOnDefault),!n.collectionId){let M=o?.structureType===we,P=pr({structure:o});if(ud({drawDefinition:c,structure:o})||P||M){let N=v=>{r=S?"SET1-S:T100":r??n.matchUpFormat??v?.matchUpFormat??c?.matchUpFormat??l?.matchUpFormat;let O=S?{matchUpTypes:[Ht]}:void 0,{matchUps:x}=Et({afterRecoveryTimes:!1,tournamentRecord:a,inContext:!0,matchUpFilters:O,drawDefinition:c,structure:v,event:l});return P&&(v.positionAssignments=pt(x.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:x,event:l})},R=M&&o.structures.find(v=>v?.matchUps.find(O=>O.matchUpId===d)),b=N(R||o);if(b.error)return _({result:b,stack:e})}}if(f){let M=Wp({element:n,notes:f});if(M.error)return _({result:M,stack:e})}let D=a?.tournamentId,U=xr().topics.includes(Pp),A=(U||y)&&Ee({drawDefinition:c}),E=A&&re({matchUpFilters:{matchUpIds:[d]},nextMatchUps:!0,tournamentRecord:a,inContext:!0,drawDefinition:c,matchUpsMap:A}).matchUps?.[0];if(U&&E&&mb({tournamentId:D,inContextMatchUp:E}),Array.isArray(y)&&E&&!E.sides?.every(({participantId:M})=>M))if(u===Mt)n.processCodes=pt([...n.processCodes??[],...y]);else for(let M of y||[]){let P=M&&n?.processCodes?.lastIndexOf(M);n?.processCodes?.splice(P,1)}return gt({eventId:l?.eventId,context:e,drawDefinition:c,tournamentId:D,matchUp:n}),{...C}}function Rd(t){let{matchUpStatusCodes:e,matchUpStatus:r,structure:n,matchUp:o,dualMatchUp:i,inContextMatchUp:s}=t,a=Ca({matchUpStatus:r})||[oo,Mr].includes(r)&&i,c=o?.sides?.map(g=>g.participantId).filter(Boolean).length||s?.sides?.map(g=>g.participantId).filter(Boolean).length,u="attemptToModifyScore";if(!(pr({structure:n})&&c===1||r===Mt&&c||AG({structure:n,matchUp:o,inContextMatchUp:s})||t.appliedPolicies?.[Qr]?.requireParticipantsForScoring===!1))return _({result:{error:kl},stack:u});let d=[vt].includes(r),l=a?r:t.winningSide&&ue||Pn,f=kn({...t,matchUpStatusCodes:a&&e||[],matchUpStatus:l,context:u,removeScore:d});return _({result:f,stack:u})}function AG({structure:t,matchUp:e,inContextMatchUp:r}){let{drawPositions:n}=e,{positionAssignments:o}=le({structure:t}),i=o?.filter(a=>n?.includes(a.drawPosition)&&a.participantId),s=r?.sides?.every(a=>a.participantId);return i?.length===2||s}function GS({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=>ut(n));return{groupValueGroups:e,groupValueNumbers:r}}function yO({collectionDefinition:t,groupValueNumbers:e,groupValueGroups:r,sideTieValues:n,tieMatchUps:o}){let i=o.filter(S=>S.collectionId===t.collectionId),s=[0,0],a=[0,0],c=i.every(S=>ie.includes(S.matchUpStatus)),{collectionValueProfiles:u,collectionGroupNumber:p,collectionValue:m,matchUpValue:d,winCriteria:l,scoreValue:f,setValue:g}=t,I=p&&e.includes(p),h=[0,0];if(i.forEach(S=>{S.winningSide&&(h[S.winningSide-1]+=1)}),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:D=0,side1Score:U=0,side2Score:A=0}=T;(S.matchUpStatus===ue||S.winningSide||T.winningSide)&&(U||A?(s[0]+=U,s[1]+=A):(y||D)&&T.winningSide&&(s[T.winningSide-1]+=1))})}):Array.isArray(u)&&i.forEach(S=>{if(S.winningSide){let T=S.collectionPosition,y=EG({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,D)=>y>=l.valueGoal?D+1:T,0);else{let T=Math.floor(t.matchUpCount/2)+1;S=h.reduce((y,D,U)=>D>=T?U+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 EG({collectionDefinition:t,collectionPosition:e}){return(t.collectionValueProfiles||[])?.find(o=>o.collectionPosition===e)?.matchUpValue}function VS({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}):{...C}}var UG="MIXED events can not contain mixed singles or { gender: ANY } collections",DG="events with { gender: ANY } can not contain MIXED singles collections";function Cd(t){let e="tieFormatGenderValidityCheck",{referenceGender:r,matchUpType:n,gender:o}=t;return r&&o&&[Zt,ce].includes(r)&&r!==o?_({result:{valid:!1,error:op},context:{gender:o},stack:e}):r===Cr&&(o===Mn||o===Cr&&n!==kt)?_({result:{error:op,valid:!1},info:UG,stack:e}):r===Mn&&o===Cr&&n!==kt?_({result:{error:op,valid:!1},info:DG,stack:e}):{valid:!0}}function jp(t,e){if(It(t),(t?.bestOf||t?.exactly)&&t?.setFormat)return PG(t,e)}function Mg(t){return!isNaN(Number(t))&&Number(t)}function UO(t){let e=`T${t.minutes}`;return t.based&&(e+=t.based),t.modifier&&(e+=`@${t.modifier}`),e}function PG(t,e){let r=Mg(t.bestOf)||void 0,n=Mg(t.exactly)||void 0,o=r||n;if(t.setFormat?.timed&&t.simplified&&o===1)return UO(t.setFormat);let i=o&&`${md}${o}`||"",s=AO(t.setFormat,e),a=s&&`S:${s}`||"",c=AO(t.finalSetFormat,e),u=o&&o>1&&c&&s!==c&&`F:${c}`||"";if(i&&s)return[i,a,u].filter(m=>m).join("-")}function AO(t,e){if(typeof t=="object"&&Object.keys(t).length){if(t.timed)return UO(t);if(t.tiebreakSet)return EO(t.tiebreakSet);let r=Mg(t.setTo);if(r){let n=t.NoAD&&rg||"",o=EO(t.tiebreakFormat),i=o&&`/${o}`||"",s=Mg(t.tiebreakAt),a=s&&(s!==r||e)&&`@${s}`||"";if(o!==!1)return`${r}${n}${i}${a}`}}}function EO(t){if(t){if(typeof t=="object"&&!t.tiebreakTo)return"";if(typeof t=="object"&&Mg(t.tiebreakTo)){let e=`TB${t.tiebreakTo}${t.NoAD?rg:""}`;return t.modifier&&(e+=`@${t.modifier}`),e}else return!1}}function Ar({matchUpFormat:t}){if(!te(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 jp(e,!!(r&&o&&n===i||s&&c&&a===u))===t}var NG=(t,e)=>t.filter(Boolean).every(r=>typeof r===e),MG=t=>t.filter(Boolean).every(Jt);function ea(t){let e=t.category;if(typeof e!="object")return{error:qc};let{ageCategoryCode:r,ageMaxDate:n,ageMinDate:o,ageMax:i,ageMin:s}=e,a=e.categoryName,c;if(!NG([r,n,o,a],"string")||!MG([i,s]))return{error:qc};let u=t.consideredDate??Dt(new Date().toLocaleDateString("sv"));if(!Nr(u))return{error:Ge};let[p]=u.split("-").slice(0,3).map(w=>parseInt(w)),m=Tp(u,-1),[d,l]=m.split("-").slice(1,3).map(w=>parseInt(w)),f=`${ro(d)}-${ro(l)}`,g=Tp(u,1),[I,h]=g.split("-").slice(1,3).map(w=>parseInt(w)),S=`${ro(I)}-${ro(h)}`,T=s&&Tp(u,-1*365*s),y=i&&Tp(u,-1*365*i),D=[],U=w=>!D.includes(w)&&D.push(w);r=r??a;let A=/^([UO]?)(\d{1,2})([UO]?)$/,E=/^C(\d{1,2})-(\d{1,2})$/,M=r?.includes("-"),P=M&&r?.match(E),N=r?.match(A),R=(w,B)=>`${w}-${B}`,b=w=>{let B=p-w,G=R(B,S);e.ageMinDate&&e.ageMinDate!==G&&U(`Invalid submitted ageMinDate: ${o}`),o=G,r&&(e.ageMax&&e.ageMax!==w-1&&(U(`Invalid submitted ageMax: ${i}`),y=void 0),i=w-1)},v=w=>{let B=p-w-1,G=R(B,S);e.ageMin&&e.ageMin>w&&U(`Invalid submitted ageMin: ${s}`),e.ageMax&&e.ageMax>w&&U(`Invalid submitted ageMax: ${i}`),e.ageMinDate&&e.ageMinDate!==G&&U(`Invalid submitted ageMinDate: ${o}`),o=G,r&&(e.ageMax&&e.ageMax!==w&&(U(`Invalid submitted ageMax: ${i}`),T=void 0),i=w)},O=w=>{let B=p-w,G=R(B,f);e.ageMaxDate&&e.ageMaxDate!==G&&U(`Invalid submitted ageMaxDate: ${n}`),n=G,r&&(e.ageMin&&e.ageMin!==w+1&&(U(`Invalid submitted ageMin: ${s}`),T=void 0),s=w+1)},x=w=>{let B=p-w-1,G=R(B,f);e.ageMaxDate&&e.ageMaxDate!==G&&U(`Invalid submitted ageMaxDate: ${n}`),n=G,r&&(e.ageMin&&e.ageMin!==w&&(U(`Invalid submitted ageMin: ${s}`),T=void 0),s=w)},F=w=>{let[B,G,W]=(w.match(A)||[]).slice(1),H=parseInt(G);B==="U"?(e.ageMaxDate&&e.ageMaxDate!==n&&U(`Invalid submitted ageMaxDate: ${e.ageMaxDate}`),b(H)):B==="O"&&O(H),W==="U"?(e.ageMaxDate&&e.ageMaxDate!==n&&U(`Invalid submitted ageMaxDate: ${e.ageMaxDate}`),v(H)):W==="O"&&x(H),n=n??T,o=o??y};if(P){if(n=void 0,o=void 0,i=void 0,s=void 0,e.ageMin){let G=p-e.ageMin;n=R(G,f)}if(e.ageMax){let G=p-e.ageMax-1;o=R(G,S)}let[w,B]=(r?.match(E)??[]).slice(1).map(G=>parseInt(G));w<=B?(s=w,i=B,c=!0):U(`Invalid combined age range ${r}`)}else M?r?.split("-").forEach(F):N?F(r):(s&&O(s),i&&v(i));i&&e.ageMin&&e.ageMin>i&&(U(`Invalid submitted ageMin: ${e.ageMin}`),s=void 0);let L=rt({consideredDate:u,combinedAge:c,ageMaxDate:n,ageMinDate:o,ageMax:i,ageMin:s});return D.length&&(L.errors=D),L}function _u({category:t}){if(!It(t))return{error:k};let e=ea({category:t});if(e.error)return{error:e};let{ratingMax:r,ratingMin:n}=t;return r&&!Jt(r)?_({result:{error:k},context:{ratingMax:r}}):n&&!Jt(n)?_({result:{error:k},context:{ratingMin:n}}):{...e}}function xu({childCategory:t,withDetails:e,category:r}){let n=_u({category:r}),o=_u({category:t}),i=o.ageMin&&(n.ageMin&&o.ageMin<n.ageMin||n.ageMax&&o.ageMin>n.ageMax),s=o.ageMax&&(n.ageMax&&o.ageMax>n.ageMax||n.ageMin&&o.ageMax<n.ageMin),a=o.ageMinDate&&n.ageMaxDate&&new Date(o.ageMinDate)>new Date(n.ageMaxDate),c=o.ageMaxDate&&n.ageMinDate&&new Date(o.ageMaxDate)<new Date(n.ageMinDate),p=r?.ratingType&&t?.ratingType&&r.ratingType===t.ratingType&&(r.ratingMin&&t.ratingMin&&t.ratingMin<r.ratingMin||r.ratingMax&&t.ratingMax&&t.ratingMax>r.ratingMax||r.ratingMin&&t.ratingMax&&t.ratingMax<r.ratingMin||r.ratingMax&&t.ratingMin&&t.ratingMin>r.ratingMax),m=r?.ballType&&t?.ballType&&r.ballType!==t.ballType,f=rt({invalidRatingRange:p,invalidAgeMinDate:a,invalidAgeMaxDate:c,invalidBallType:m,invalidAgeMax:s,invalidAgeMin:i,valid:!p&&!a&&!c&&!m&&!s&&!i},!0);return e&&Object.assign(f,{categoryDetails:n,childCategoryDetails:o}),f}function wu({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:po},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&&!yu([Bt,kt],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 U=VS({collectionValueProfiles:u,matchUpCount:l});U.errors&&c.push(...U.errors)}if(p&&typeof p!="number"&&c.push(`collectionGroupNumber is not type number: ${m}`),f&&!Ar({matchUpFormat:f})&&c.push(`Invalid matchUpFormat: ${f}`),n){let U=Cd({referenceGender:i,matchUpType:I,gender:y});if(U.error)return _({context:{referenceGender:i,gender:y},result:U,stack:a})}if(t&&o&&T){let U=xu({category:o,childCategory:T});if(!U.valid)return _({result:{error:qc},context:U,stack:a})}return c.length?_({result:{errors:c,error:bE},stack:a}):{valid:!0}}function mr(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=[],c=RG({...t,stack:s});if(c?.error)return c;let u,p=o.collectionDefinitions.every(I=>{let{setValue:h,scoreValue:S,collectionValue:T}=I;(h||S)&&!T&&(u=!0);let{valid:y,errors:D}=wu({referenceCategory:t.category,referenceGender:t.gender,collectionDefinition:I,checkCollectionIds:n,checkCategory:e,checkGender:r,event:i});return y?!0:(Array.isArray(D)&&a.push(...D),!1)}),m=typeof o.winCriteria?.valueGoal=="number"&&o.winCriteria?.valueGoal>0&&!u||o.winCriteria?.aggregateValue;if(!(m||o.winCriteria?.aggregateValue))return u?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:u},result:{error:li},stack:s});let d=o.collectionDefinitions.map(({collectionId:I})=>I),l=!n||d.length===pt(d).length,f=p&&m&&l,g={valid:f,errors:a};return f?g:_({result:{error:li},context:{tieFormat:o,errors:a},stack:s})}function RG(t){let{tieFormat:e,stack:r}=t;return!t||!e||!It(e)?_({result:{error:li},context:{tieFormat:e,message:"tieformat must be an object"},stack:r}):It(e.winCriteria)?Array.isArray(e.collectionDefinitions)?{...C}:_({result:{error:li},context:{tieFormat:e,message:"collectionDefinitions must be an array"},stack:r}):_({result:{error:li},context:{tieFormat:e,message:"tieformat.winCritiera must be an object"},stack:r})}function Cc(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,D)=>y+D)))return{error:k};if(!s)return{error:dr};let c=We({matchUp:s,drawDefinition:n,structure:i,event:a})?.tieFormat||t?.tieFormat;if(!c)return{error:xs};let u=mr({tieFormat:c});if(u.error)return u;let p=c?.collectionDefinitions||[],m=s?.tieMatchUps??[],d=[0,0],{groupValueGroups:l,groupValueNumbers:f}=GS(c);for(let y of p)yO({collectionDefinition:y,groupValueNumbers:f,groupValueGroups:l,sideTieValues:d,tieMatchUps:m});for(let y of f){let D=l[y],{allGroupMatchUpsCompleted:U,matchUpCount:A,winCriteria:E,groupValue:M,sideWins:P,values:N}=D,R;if(E?.aggregateValue)U&&N[0]!==N[1]&&(R=N[0]>N[1]?1:2);else if(E?.valueGoal)R=N.reduce((b,v,O)=>v>=E.valueGoal?O+1:b,void 0);else{let b=Math.floor(A/2)+1;R=P.reduce((v,O,x)=>O>=b?x+1:v,void 0)}R&&(d[R-1]+=M||0)}let g=d.map((y,D)=>(y||0)+e[D]),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:D,tallyDirectives:U}=c.winCriteria;if(y?T=g.map((E,M)=>({sideNumber:M+1,points:E})).find(({points:E})=>E>=y)?.sideNumber:D&&m.every(E=>E.matchUpStatus&&ie.includes(E.matchUpStatus)||E.winningSide)&&g[0]!==g[1]&&(T=g[0]>g[1]?1:2),!T&&U){let A=s.matchUpId,E=s.hasContext?s:o?.drawMatchUps?.[A]||n&&Gt({inContext:!0,drawDefinition:n,matchUpId:A})?.matchUp;if(E){let{completedTieMatchUps:M,order:P}=wa({matchUps:[E]});if(M&&P?.length){let N=P[0].participantId;T=E.sides.find(({participantId:R})=>R===N)?.sideNumber}}}}return T&&(I.winningSide=T),{scoreStringSide1:h,scoreStringSide2:S,winningSide:T,set:I}}function La({inContextDualMatchUp:t,drawDefinition:e,tournamentId:r,dualMatchUp:n,eventId:o}){if(n){t||(t=Gt({matchUpId:n.matchUpId,inContext:!0,drawDefinition:e})?.matchUp);let{extension:i}=mt({element:e,name:bo}),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}}),gt({context:"ensureSidLineUps",matchUp:n,drawDefinition:e,tournamentId:r,eventId:o})}}function Ze(t){if(t)return J(t,!1,!0)}function Rg(t){let e=nt(t,[{[De]:!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 BS({tournamentRecords:t,eventId:e,drawId:r}){let{tournamentIdMap:n}=Rg({tournamentRecords:t});return(n?Object.keys(n):[]).find(i=>e&&n?.[i].includes(e)||r&&n?.[i].includes(r))}function co(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&&BS({tournamentRecords:c,...t});let p=u&&c[u];if(!p)return{error:j};let m=Gt({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:or};La({tournamentId:p?.tournamentId,eventId:a?.eventId,dualMatchUp:d,drawDefinition:r});let{extension:f}=mt({name:ya,element:d});if(f?.value)if(o)ur({element:d,name:ya});else return{...C,score:d.score};let g=We({drawDefinition:r,structure:l,matchUp:d,event:a})?.tieFormat;d.tieFormat=Ze(g);let I=Cc({drawDefinition:r,matchUpsMap:i,structure:l,matchUp:d,event:a}),{winningSide:h,set:S,scoreStringSide1:T,scoreStringSide2:y}=I,D=S?.side1Score||S?.side2Score;if(e&&!d.score&&!D)return{...C};let U={scoreStringSide1:T,scoreStringSide2:y,sets:S?[S]:[]},A=h&&[1,2].includes(h),E=A&&ue||ig({matchUpStatus:n??d.matchUpStatus,tieMatchUps:d.tieMatchUps,winningSide:d.winningSide,score:U})&&Ln||zt,M=!!(d.winningSide&&!A),P=d.tieMatchUps.find(({score:R,winningSide:b,matchUpStatus:v})=>R?.sets?.length&&(R.sets[0].side1Score||R.sets[0].side2Score)||v&&ie.includes(v)||b),N;if(d.tieFormat&&!A&&!P){let R=We({drawDefinition:r,structure:l,event:a})?.tieFormat;R&&JSON.stringify(g)===JSON.stringify(R)&&(d.tieFormatId=void 0,d.tieFormat=void 0,N=!0)}return kn({appliedPolicies:t.appliedPolicies,matchUpStatus:E,score:U,removeWinningSide:M,tournamentRecord:p,drawDefinition:r,removeScore:o,winningSide:h,matchUpId:s,matchUp:d,event:a}),{...C,score:U,removeWinningSide:M,tieFormatRemoved:N,winningSide:h}}function DO({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=at({structureId:I,drawDefinition:c});if(h.error)return h;let{structure:S}=h,{positionAssignments:T}=le({structureId:I,drawDefinition:c}),D=T?.find(R=>R.drawPosition===o)?.participantId,U=s.target.structureId,{positionAssignments:A}=le({structureId:U,drawDefinition:c}),M=A?.find(R=>R.participantId===D)?.drawPosition,P=A?.filter(R=>{let b=f.includes(R.drawPosition),v=!R.participantId&&!R.bye&&!R.qualifier;return b&&v}).map(R=>R.drawPosition),N=P?.includes(g);if(D&&s.target.roundNumber===1&&N)Fn({drawPosition:g,participantId:D,structureId:U,inContextDrawMatchUps:e,sourceMatchUpStatus:n,tournamentRecord:i,drawDefinition:c,matchUpsMap:m,event:d});else if(D&&P?.length){let R=P.pop();R&&Fn({participantId:D,structureId:U,inContextDrawMatchUps:e,sourceMatchUpStatus:n,tournamentRecord:i,drawDefinition:c,drawPosition:R,matchUpsMap:m,event:d})}else if(M){let R=Ec({drawPosition:M,matchUpId:u.matchUpId,inContextDrawMatchUps:e,sourceMatchUpStatus:n,tournamentRecord:i,sourceMatchUpId:a,drawDefinition:c,matchUpsMap:m});if(R.error)return _({result:R,stack:l})}else if(S?.stage!==ct){let R="winner target position unavaiallble";return console.log(R),{error:R}}if(S?.seedAssignments&&S.structureId!==U){let R=S.seedAssignments.find(({participantId:v})=>v===D),b=R?.participantId;R&&b&&Js({eventId:u?.eventId,structureId:U,...R,tournamentRecord:i,drawDefinition:c,participantId:b})}}else{let f=Ec({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:D})=>D===u.matchUpId),T=[1,2].map(D=>({...S.sides?.find(A=>A.sideNumber===D)||{},sideNumber:D}));S.sides=T;let y=S.sides.find(D=>D.sideNumber===h);if(y){let D=f.lineUp?.filter(U=>U?.participantId);y.lineUp=Sd({lineUp:D}),gt({tournamentId:i?.tournamentId,eventId:u?.eventId,matchUp:S,context:l,drawDefinition:c})}}}return{...C}}function PO(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===to&&u.roundNumber===2&&Math.min(...g.filter(Boolean)),h=I||g[e],S=I||g[1-e],T=a.source.structureId,{structure:y}=at({structureId:T,drawDefinition:c}),{matchUps:D}=Et({afterRecoveryTimes:!1,inContext:!0,drawDefinition:c,structure:y,event:d}),A=D.filter(H=>H.drawPositions?.includes(i)).filter(H=>{let q=H.sides.find(V=>V.drawPosition===i),$=H.matchUpStatus===vt||H.matchUpStatus===Mt&&!me(H);return q?.sideNumber===H.winningSide&&!$}),E=f===to&&A.length===0,{positionAssignments:M}=le({structureId:T,drawDefinition:c}),N=M?.find(H=>H.drawPosition===i)?.participantId,R=a.target.structureId,{positionAssignments:b}=le({structureId:R,drawDefinition:c}),v=b?.filter(({drawPosition:H})=>g.includes(H));if(v?.some(H=>H.participantId===N))return{...C};let x=v?.filter(H=>{let q=g.includes(H.drawPosition),$=!H.participantId&&!H.bye&&!H.qualifier;return q&&$}).map(H=>H.drawPosition),F=x?.includes(h),L=a.target.roundNumber>1&&x?.length,w=a.target.roundNumber===1&&F;if(I){let H=B();if(H.error)return _({result:H,stack:l})}else if(w){let H=W();if(H.error)return _({result:H,stack:l})}else if(N&&L){x.sort(ae);let H=x[0],q=Fn({participantId:N,structureId:R,drawPosition:H,inContextDrawMatchUps:r,sourceMatchUpStatus:o,tournamentRecord:s,drawDefinition:c,matchUpsMap:m,event:d});if(q.error)return _({result:q,stack:l})}else return _({result:{error:Os},context:{loserDrawPosition:i,loserTargetLink:a},stack:l});if(y?.seedAssignments&&y.structureId!==R){let H=y.seedAssignments.find(({participantId:$})=>$===N),q=H?.participantId;H&&q&&Js({eventId:u?.eventId,structureId:R,...H,tournamentRecord:s,drawDefinition:c,participantId:q})}if(p&&n){let H=p.sides?.find(q=>q.sideNumber===3-n);if(H?.lineUp){let{roundNumber:q,eventId:$}=u,{roundPosition:V}=p,K=q===1?2-V%2:1,z=m?.drawMatchUps?.find(({matchUpId:Q})=>Q===u.matchUpId),Y=[1,2].map(Q=>({...z.sides?.find(St=>St.sideNumber===Q)||{},sideNumber:Q}));z.sides=Y;let Z=z.sides.find(Q=>Q.sideNumber===K);Z&&(Z.lineUp=Sd({lineUp:H.lineUp}),gt({tournamentId:s?.tournamentId,matchUp:z,context:l,drawDefinition:c,eventId:$}))}}return{...C};function B(){let H="loserLinkFedFMLC";return E?_({result:W(),stack:H}):_({result:G(),stack:H})}function G(){let H=kr({drawPosition:S,structureId:R,tournamentRecord:s,drawDefinition:c,event:d});return _({result:H,stack:"assignLoserPositionBye"})}function W(){let H=N?Fn({drawPosition:h,participantId:N,structureId:R,inContextDrawMatchUps:r,sourceMatchUpStatus:o,tournamentRecord:s,drawDefinition:c,matchUpsMap:m,event:d}):{error:ee};return _({result:H,stack:"assignLoserDrawPosition"})}}function HS(t){let e="directParticipants",r=Rd(t);if(r.error)return _({result:r,stack:e});let n=Ca({matchUpStatus:t.matchUpStatus}),{dualWinningSideChange:o,projectedWinningSide:i,inContextDrawMatchUps:s,tournamentRecord:a,drawDefinition:c,matchUpStatus:u,dualMatchUp:p,matchUpsMap:m,winningSide:d,targetData:l,matchUpId:f,structure:g,matchUp:I,event:h}=t,S=!!I.collectionId,T=pr({structure:g}),y=I.drawPositions,D;if(S){let{matchUpTieId:U,matchUpsMap:A}=t,E=co({appliedPolicies:t.appliedPolicies,matchUpId:U,tournamentRecord:a,drawDefinition:c,matchUpsMap:A,event:h});if(D=E&&{tieMatchUpResult:E},y=s.find(({matchUpId:P})=>P===U)?.drawPositions,!o)return _({result:{...C,...D},stack:e})}if(T)return _({result:{...C,...D},stack:e});if(y){let U=i?i-1:d-1,A=1-U,E=y[U],M=y[A],{targetLinks:{loserTargetLink:P,winnerTargetLink:N,byeTargetLink:R},targetMatchUps:{winnerMatchUpDrawPositionIndex:b,loserMatchUpDrawPositionIndex:v,winnerMatchUp:O,loserMatchUp:x,byeMatchUp:F}}=l;if(O){let L=DO({sourceMatchUpStatus:n&&u||ue,winnerMatchUpDrawPositionIndex:b,sourceMatchUpId:f,inContextDrawMatchUps:s,projectedWinningSide:i,winningDrawPosition:E,tournamentRecord:a,winnerTargetLink:N,drawDefinition:c,winnerMatchUp:O,dualMatchUp:p,matchUpsMap:m,event:h});if(L.error)return _({result:L,stack:e})}if(x){let L=PO({sourceMatchUpStatus:n&&u||ue,loserMatchUpDrawPositionIndex:v,sourceMatchUpId:f,inContextDrawMatchUps:s,projectedWinningSide:i,loserDrawPosition:M,tournamentRecord:a,loserTargetLink:P,drawDefinition:c,loserMatchUp:x,winningSide:d,matchUpsMap:m,dualMatchUp:p,event:h});if(L.error)return _({result:L,stack:e})}if(F){let L=F.drawPositions||[],w=Math.min(...L.filter(Boolean)),B=R.target.structureId,G=kr({drawPosition:w,structureId:B,tournamentRecord:a,drawDefinition:c,event:h});if(G.error)return _({result:G,stack:e})}}else return _({result:{error:za},stack:e});return _({result:{...C,...D},stack:e})}function bd(t){let e="genPlayoffStructure";if(!t.drawDefinition)return _({result:{error:X},stack:e});let r=Ru(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}=at({structureId:n,drawDefinition:T});if(!y)return _({result:{error:Lt},stack:e});if(y.structureType===we||y.structures)return sO({sourceStructureId:y.structureId,...t,...r,drawDefinition:T});let{playoffRoundsRanges:D,playoffRounds:U}=r,{playoffPositionsReturned:A,error:E,playoffSourceRounds:M,playoffRoundsRanges:P}=CS(t);if(E)return _({result:{error:E},stack:e});let N=l?.length&&Object.assign({},...l),R=f||typeof l=="object"&&l.map(Y=>Object.keys(Y)).flat(),b=Array.isArray(R)&&R.map(Y=>!isNaN(Y)&&ut(Y)).filter(Boolean);if(b){if(!Array.isArray(b))return _({result:{error:k},context:{validRoundNumbers:b},stack:e});b.forEach(Y=>{if(!U?.includes(Y))return _({result:{error:k},context:{roundNumber:Y},stack:e})})}u&&u.forEach(Y=>{if(!A?.includes(Y))return _({result:{error:k},context:{playoffPosition:Y},stack:e})});let v=b||M,O=b?D:P,x=[],F=[];for(let Y of v??[]){let Z=O?.find(Se=>Se.roundNumber===Y);if(!Z)return _({result:{error:k},context:{roundNumber:Y},stack:e});let Q=Z.finishingPositions.length,st=Math.min(...Z.finishingPositions)-1,St=2,it=Y&&N?.[Y]&&St+N[Y]-1,jt=Pc({exitProfile:`0-${Y}`,addNameBaseToAttributeName:o,playoffStructureNameBase:i,finishingPositionOffset:st,playoffAttributes:c,exitProfileLimit:d,stage:pe,roundOffset:0,drawDefinition:T,sequenceLimit:it,stageSequence:St,drawSize:Q,idPrefix:g,isMock:I,uuids:S,finishingPositionNaming:s,finishingPositionLimit:a,roundOffsetLimit:p});if(jt.error)return _({result:jt,stack:e});let{structures:Ut,links:Ue}=jt;if(Ut?.length&&x.push(...Ut),Ue?.length&&F.push(...Ue),jt.structureId&&Y){let Se={linkType:Zn,source:{structureId:n,roundNumber:Y},target:{structureId:jt.structureId,feedProfile:yn,roundNumber:1}};F.push(Se)}}if(!x.length)return _({result:{error:k},info:"No structures generated",stack:e});T.structures.push(...x),T.links.push(...F);let{matchUps:L,matchUpsMap:w}=re({inContext:!0,drawDefinition:T}),B=x.map(({structureId:Y})=>Y),G=L?.filter(({structureId:Y})=>B.includes(Y)).map(Ie),W=w?.drawMatchUps?.filter(({matchUpId:Y})=>G?.includes(Y));if(W?.length){let Y=We({drawDefinition:T,event:h})?.tieFormat;Y&&W.forEach(Z=>{let{tieMatchUps:Q}=xa({matchUp:Z,tieFormat:Y,isMock:I});Object.assign(Z,{tieMatchUps:Q,matchUpType:Ht})})}L?.filter(Y=>gs({matchUp:Y})&&Y.structureId===n)?.forEach(Y=>{let{matchUpId:Z,score:Q,winningSide:st}=Y,St=nr({inContextDrawMatchUps:L,drawDefinition:T,matchUpId:Z}),it=HS({inContextDrawMatchUps:L,tournamentRecord:m,drawDefinition:T,matchUpsMap:w,winningSide:st,targetData:St,matchUpId:Z,structure:y,matchUp:Y,score:Q,event:h});it.error&&console.log(it.error)}),L?.filter(Y=>Y.matchUpStatus===Pt&&Y.structureId===n)?.forEach(Y=>{let{matchUpId:Z}=Y,Q=nr({inContextDrawMatchUps:L,drawDefinition:T,matchUpId:Z}),{targetLinks:{loserTargetLink:st},targetMatchUps:{loserMatchUpDrawPositionIndex:St,loserMatchUp:it}}=Q;if(st&&it){let jt=st.target.structureId,Ut=it.drawPositions[St],Ue=kr({drawPosition:Ut,structureId:jt,tournamentRecord:m,drawDefinition:T,event:h});Ue.error&&console.log(Ue.error)}});let $=[],V=Ki({inContextDrawMatchUps:L,drawDefinition:T,matchUpsMap:w}).goesToMap,{structure:K}=at({drawDefinition:t.drawDefinition,structureId:n}),{matchUps:z}=Et({structure:K});return z.forEach(Y=>{let Z=V?.loserMatchUpIds[Y.matchUpId];if(Z&&Y.loserMatchUpId!==Z){Y.loserMatchUpId=Z;let st={tournamentId:m?.tournamentId,eventId:t.event?.eventId,context:e,matchUp:Y};$.push(st)}let Q=V?.winnerMatchUpIds[Y.matchUpId];if(Q&&Y.winnerMatchUpId!==Q){Y.winnerMatchUpId=Q;let st={tournamentId:m?.tournamentId,eventId:t.event?.eventId,context:e,matchUp:Y};$.push(st)}}),{structures:x,matchUpModifications:$,links:F,drawDefinition:T,...C}}function WS({element:t}){if(!t)return{error:k};if(!t.timeItems)return{};if(!Array.isArray(t.timeItems))return{error:k};let e=(r,n)=>(o,i)=>(i[r]&&(o[i[r]]=i[n]),o);return t.timeItems.reduce(e("itemType","itemValue"),{})}function Qn(t){let{duplicateValues:e=!0,creationTime:r=!0,removePriorValues:n,timeItem:o}=t;if(!o)return{error:Jl};let i=vh(t);if(i.error)return i;if(!(It(o)&&te(o.itemType)&&Object.keys(o).includes("itemValue")))return{error:Xl};if(!i.timeItems)i.timeItems=[];else if(CG({element:i,duplicateValues:e,timeItem:o}))return{...C};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),{...C}}function CG({element:t,duplicateValues:e,timeItem:r}){let{itemType:n,itemSubTypes:o,itemValue:i}=r,s=n&&Xr({itemSubTypes:o,itemType:n,element:t})?.timeItem;return s&&JSON.stringify(s?.itemValue)===JSON.stringify(i)&&!e}function Cg({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=Ao({tournamentRecord:r,participantId:o});return s.error?s:Qn({element:s.participant,removePriorValues:e,duplicateValues:n,creationTime:t,timeItem:i})}function bc(t){let{removePriorValues:e,tournamentRecord:r,duplicateValues:n,creationTime:o,timeItem:i}=t;if(!r)return{error:j};let s=Qn({element:r,removePriorValues:e,duplicateValues:n,creationTime:o,timeItem:i});if(s.error)return s;let a=WS({element:r});return dt({topic:Yi,payload:{timeItemValues:a}}),s}function Xi(t){let{removePriorValues:e,duplicateValues:r,creationTime:n,timeItem:o,event:i}=t;return i?Qn({removePriorValues:e,duplicateValues:r,element:i,creationTime:n,timeItem:o}):{error:Pr}}function wD(t){return vg({...t,itemType:"attachConsolationStructures"})}function bg(t){return vg({...t,itemType:"attachPlayoffStructures"})}function vg({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:k},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:nf},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),Ki({drawDefinition:n});let f=o.map(h=>Et({structure:h})?.matchUps||[]).flat();vo({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:D,...U}=h[y.matchUpId].matchUp;if(Object.assign(y,U),D?.length){let A={};D.forEach(E=>h[E.matchUpId]=E),y.tieMatchUps.forEach(E=>Object.assign(E,A[E.matchUpId]))}h[y.matchUpId].matchUp=y,gt(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(Fr("structureId"));if(r){let S={itemValue:{structureIds:g,drawId:n.drawId},itemType:t};Qn({element:r,timeItem:S})}return{...C,addedStructureIds:I}}function Yp(t){let{structures:e,links:r,matchUpModifications:n,error:o}=bd(t);if(o)return{error:o};let i=t.drawDefinition;return bg({tournamentId:t.tournamentRecord?.tournamentId,eventId:t.event?.eventId||t.eventId,matchUpModifications:n,drawDefinition:i,structures:e,links:r})}function Ji(t){let e=nt(t,[{_anyOf:{[De]:!1,[Re]:!1,[Le]:!1,[Jo]:!1},[gf]:!0}]);if(e.error)return e;let r=[],n=t.drawDefinition??t.event??((t.tournamentId||!t.tournamentRecords)&&t.tournamentRecord);if(n){let o=NO(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=NO(t,s);if(a.error)return a;r.push(...a?.applied??[])}}else return{error:j};return r.length?{...C,applied:r}:{error:FI}}function NO(t,e){let r=yt(t).appliedPolicies??{};e.extensions||(e.extensions=[]);let n=[],o=Object.keys(t.policyDefinitions);if(!o.length)return{error:Zu};for(let i of o)if(!r[i]||t.allowReplacement){let s=t.policyDefinitions[i];if(!s)continue;if(!It(s))return{error:k};let{policyName:a,...c}=s;if(!c||!Object.keys(c).length||a&&!te(a))return{error:k};r[i]=t.policyDefinitions[i],n.push(i)}return n?.length?{...At({element:e,extension:{name:su,value:r}}),applied:n}:{applied:n,error:FI}}function Og({tournamentRecord:t,drawDefinition:e,flightProfile:r,drawName:n,drawId:o,event:i}){if(!n||typeof n!="string")return _({result:{error:k},context:{drawName:n}});r||(r=Wt({event:i}).flightProfile);let s=r?.flights?.find(a=>a.drawId===o);if(s){s.drawName=n;let a={name:cn,value:{...r,flights:r.flights}};Co({event:i,extension:a})}return e&&(e.drawName=n,Ot({tournamentId:t?.tournamentId,drawDefinition:e})),!s&&!e?{error:X}:{...C,flight:s}}function LD({tournamentRecord:t,drawDefinition:e,drawUpdates:r,drawId:n,event:o}){if(!It(r))return{error:k};let i=Wt({event:o}).flightProfile,s=r.drawName&&Og({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:cn,value:{...i,flights:i.flights}};Co({event:o,extension:c})}return e&&(r.policyDefinitions&&Ji({policyDefinitions:r.policyDefinitions,drawDefinition:e}),Ot({tournamentId:t?.tournamentId,drawDefinition:e})),{...C}}function FD({tournamentRecord:t,removeScheduling:e,drawDefinition:r}){if(!r)return{error:X};let n=Ee({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||![ct,et].includes(c))&&(s.positionAssignments=a.map(d=>(delete d.participantId,d)),s.seedAssignments=[]);let{matchUps:p,isRoundRobin:m}=Et({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!==Pt&&Object.assign(I,Ou),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&&![xo,Mi,Ys,bU,qs,$s].includes(h.itemType))),gt({tournamentId:t?.tournamentId,context:"resetDrawDefiniton",drawDefinition:r,matchUp:I})}}}let i=(r.structures||[]).map(({structureId:s})=>s);return Ot({drawDefinition:r,structureIds:i}),{...C}}function Lu({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}=Nu({drawDefinition:o}),p=r[i],d=(o?.structures||[]).map(D=>{let{stage:U,stageSequence:A,structureId:E}=D,M=Gs[U],{inContextStructureMatchUps:P}=ba({drawDefinition:o,structure:D,event:p}),N=P?.filter(({winningSide:q})=>q),R=N.filter(Boolean).length||0;a+=R,c+=P.length-a;let b=Math.max(N.filter(({roundNumber:q})=>q===1).map(({roundPosition:q})=>q)),{positionAssignments:v}=Ct({structure:D}),O=v?.filter(({participantId:q})=>q);s+=O?.length??0;let x=(v?.length??0)-(O?.length??0),{roundMatchUps:F,roundProfile:L,roundNumbers:w,maxMatchUpsCount:B}=je({matchUps:P}),G=L&&Object.keys(L).filter(q=>!L[q].inactiveRound).map(q=>parseInt(q)),W=L&&Object.keys(L).filter(q=>L[q].inactiveRound).map(q=>parseInt(q)),H=L&&Object.values(L).every(q=>q.inactiveRound);return{positionsAssignedCount:O?.length??0,maxWinningSideFirstRoundPosition:b,unassignedPositionsCount:x,inactiveStructure:H,maxMatchUpsCount:B,inactiveRounds:W,roundMatchUps:F,activeRounds:G,roundNumbers:w,roundProfile:L,structureId:E,stageSequence:A,orderNumber:M,stage:U}}),l=d.find(D=>D.orderNumber===2&&D.stageSequence===1),f=d.filter(({inactiveStructure:D})=>!D).length,{links:g}=Ks({structureId:l.structureId,drawDefinition:o}),I=ut(l.activeRounds[0])===1&&l.activeRounds.length===1&&f===1,h=d?.every(({inactiveStructure:D})=>D),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}),{...C,drawsAnalysis:e}}function kD({matchPlayDrawPositions:t=!0,tournamentRecord:e,drawDefinition:r,drawId:n}){if(!e)return{error:j};if(!r)return{error:X};let o=[],{drawsAnalysis:i}=Lu({tournamentRecord:e});if(i.canBePruned.includes(n)){let s=i.matchPlay.includes(n),a=i.drawAnalysis[n],{structures:[c]}=ln({stageSequence:1,drawDefinition:r,stage:et}),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(Ie),d=p.map(Ie).filter(l=>!m.includes(l));if(s){let l=o.filter(({roundNumber:T})=>!u.inactiveRounds.includes(T)).filter(({winningSide:T})=>T),f=l.map(Ie),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}jn({tournamentId:e?.tournamentId,matchUpIds:d,drawDefinition:r}),Ot({drawDefinition:r})}return{...C,matchUps:o}}function GD({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:_s};if(!o)return{error:hr};if(a){let c=kr({tournamentRecord:t,drawDefinition:e,drawPosition:n,structureId:o,event:s});if(c.error)return c}else{if(i)return{error:sp};{let c=Fn({tournamentRecord:t,drawDefinition:e,participantId:r,drawPosition:n,structureId:o,event:s});if(c.error)return c}}return{...C}}function jS(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:Lt};let o=r.structures?.find(c=>c.structureId===n);if(!o)return{error:Lt};let i=o?.matchUps,s=i?.find(c=>!!c.roundPosition);if(o.structures||s||o.finishingPosition===Wi)return{error:Qo};let a=i.filter(({roundNumber:c})=>t.roundNumbers?.includes(c)).map(Ie);return e=e.filter(c=>!a.includes(c)),t.roundNumbers&&!e.length&&(e=a),{existingMatchUps:i,matchUpIds:e,structureId:n,structure:o}}function VD(t){let e=nt(t,[{[Le]:!0},{[ic]:{[oc]:!1,roundNumbers:!1},[wr]:k,[ar]:ir}]);if(e.error)return e;let{removeIncomplete:r=!1,removeUnAssigned:n=!0,removeCompleted:o=!1,tournamentRecord:i,drawDefinition:s,event:a}=t,c=jS(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||me({score:S})){if(!T&&!r)return!1;l.push(h)}else if(!n)return!1;return d?.includes(h)})??[],g=f.map(Ie),I=f.map(({tieMatchUps:h})=>h?.map(Ie)).filter(Boolean).flat();if(g.length){u.matchUps=(u.matchUps??[]).filter(({matchUpId:T})=>!g.includes(T)),jn({tournamentId:i?.tournamentId,matchUpIds:[...I,...g],action:"deleteAdHocMatchUps",eventId:a?.eventId,drawDefinition:s});let h=pt(u.matchUps.map(Fr("roundNumber"))),S=CC(h);if(S.length){S.reverse();for(let T of S)u.matchUps.forEach(y=>{y.roundNumber&&y.roundNumber>T&&(y.roundNumber-=1,gt({tournamentId:i?.tournamentId,context:["adHoc round deletion"],eventId:a?.eventId,drawDefinition:s,matchUp:y}))})}if(l.length){u.positionAssignments=pt(u.matchUps.flatMap(U=>(U.sides??[]).map(A=>A.participantId)).filter(Boolean)).map(U=>({participantId:U}));let T=u?.matchUpFormat??s?.matchUpFormat??a?.matchUpFormat,{matchUps:y}=Et({afterRecoveryTimes:!1,inContext:!0,structure:u,event:a}),D=Md({positionAssignments:u.positionAssignments,tournamentRecord:i,drawDefinition:s,matchUpFormat:T,matchUps:y,event:a});D.error&&console.log(D)}Ot({structureIds:[p],eventId:a?.eventId,drawDefinition:s})}return!g.length&&d.length?{error:ap}:{...C,deletedMatchUpsCount:[...g,...I].length}}function BD({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:ot},info:"roundNumber required"});let s=at({drawDefinition:r,structureId:n});if(s.error)return s;let a=s.structure;return a?.structures?{error:Qo}:pr({structure:a})?bG({tournamentId:e.tournamentId,removeCompletedMatchUps:t,eventId:i.eventId,drawDefinition:r,roundNumber:o,structure:a}):(console.log("not implemented"),{...C})}function bG({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(ae).includes(n)){let m=s.filter(d=>{let l=d.roundNumber===n&&(!ie.includes(d.matchUpStatus)||t);return l&&(c.push(d.matchUpId),d.tieMatchUps&&a.push(...d.tieMatchUps.map(Ie))),!l});c.length&&(jn({matchUpIds:[...a,...c],drawDefinition:e,tournamentId:r,eventId:i}),m.some(l=>l.roundNumber===n)||(m.forEach(l=>{l.roundNumber>n&&(l.roundNumber-=1,gt({drawDefinition:e,tournamentId:r,eventId:i,matchUp:l}))}),u=!0),o.matchUps=m)}return{deletedMatchUpsCount:c.length,roundRemoved:u,...C}}function vd(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:hr};if(!Lr(o))return{error:k,info:ko("matchUps")};let a=n.structures?.find(l=>l.structureId===s);if(!a)return{error:Lt};let u=(a?.matchUps).find(l=>!!l.roundPosition);if(a.structures||u||a.finishingPosition===Wi)return{error:Qo};let p=fe({tournamentRecord:r,inContext:!1})?.matchUps?.map(Ie)??[],m=o.map(Ie);if(xe(p,m))return{error:wE,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||(vo({tournamentId:r?.tournamentId,matchUps:[...d,...o],eventId:i?.eventId,drawDefinition:n}),Ot({drawDefinition:n,structureIds:[s]})),{...C}}function HD({tournamentRecord:t,drawDefinition:e,drawPosition:r,structureId:n,subOrder:o,event:i}){if(!e)return{error:X};if(!n)return{error:hr};if(!r)return{error:_s};let{structure:s}=at({drawDefinition:e,structureId:n});if(!s)return{error:Lt};let a=s;s.structures&&s.structureType===we&&(a=s.structures?.find(g=>g.positionAssignments?.find(I=>I.drawPosition===r)));let c=a?.positionAssignments,u=c?.find(g=>g.drawPosition===r);u&&At({element:u,extension:{name:uc,value:o}});let d=(i?.eventType===Ht||e.matchUpType===Ht||(i?.tieFormat??e?.tieFormat??s?.tieFormat))&&{matchUpTypes:[Ht]},{matchUps:l}=Et({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]}),{...C}}var tP={};Qt(tP,{addGoesTo:()=>Ki,allPlayoffPositionsFilled:()=>AS,checkValidEntries:()=>xd,findDrawDefinition:()=>KS,getAssignedParticipantIds:()=>Oi,getAvailableMatchUpsCount:()=>Od,getAvailablePlayoffProfiles:()=>Ru,getDrawDefinitionTimeItem:()=>Oh,getDrawParticipantRepresentativeIds:()=>qS,getDrawStructures:()=>ln,getDrawTypeCoercion:()=>Fu,getEligibleVoluntaryConsolationParticipants:()=>YS,getMatchUpsMap:()=>Ee,getParticipantIdFinishingPositions:()=>$S,getPositionAssignments:()=>qp,getPositionsPlayedOff:()=>Nc,getSeedingThresholds:()=>mS,getSeedsCount:()=>ku,getStructureSeedAssignments:()=>en,getTeamLineUp:()=>ls,getValidGroupSizes:()=>wp,isAdHoc:()=>pr,isCompletedStructure:()=>si,isValidForQualifying:()=>aT,positionActions:()=>sT});function YS({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=[et,pe];r&&f.push(ct);let g=l?.eventType?{matchUpTypes:[l.eventType]}:void 0,I=a?.matchUpType?{matchUpTypes:[a.matchUpType]}:void 0,h=e&&l?qn({contextFilters:{stages:f},matchUpFilters:g,tournamentRecord:s,inContext:!0,event:l})?.matchUps??[]:Je({contextFilters:{stages:f},matchUpFilters:I,tournamentRecord:s,inContext:!0,drawDefinition:a})?.matchUps??[],T=Ni({stage:Be,drawDefinition:a}).map(({participantId:w})=>w),y={},D={},U={},A={};o||(o=_o({policyTypes:[fh],tournamentRecord:s,drawDefinition:a,event:l}).policyDefinitions);let E=o?.[fh];t=t.length&&t||E?.excludedMatchUpStatuses||[],e=e??E?.includeEventParticipants,m=m??E?.allEntries,n=n??E?.finishingRoundLimit,i=i??E?.roundNumberLimit,c=c??E?.matchUpsLimit,u===void 0&&(u=E?.requirePlay!==void 0?E.requirePlay:!0),p===void 0&&(p=E?.requireLoss!==void 0?E.requireLoss:!0),d=d??E?.winsLimit;for(let w of h){if(u&&w.winningSide&&![1,2].includes(w.winningSide)&&w.matchUpStatus!==he||w.finishingRound&&n&&w.finishingRound>=n||w.finishingRound&&i&&w.finishingRound<=i)continue;let B=w.sides?.find(({sideNumber:W})=>w.winningSide&&W===3-w.winningSide),G=w.sides?.find(({sideNumber:W})=>w.winningSide&&W===w.winningSide);if(w.sides?.forEach(W=>{let H=W?.participant?.participantId;H&&(U[H]=W.participant,w.matchUpStatus===he&&!u&&(D[H]=W.participant,y[H]||(y[H]=0),(!w.matchUpStatus||!t.includes(w.matchUpStatus))&&(y[H]+=1)))}),B?.participant){let W=B.participant.participantId;D[W]=B.participant,y[W]||(y[W]=0),w.matchUpStatus&&!t.includes(w.matchUpStatus)&&(y[W]+=1)}if(G?.participant){let W=G.participant.participantId;A[W]||(A[W]=0),A[W]+=1,y[W]||(y[W]=0),w.matchUpStatus&&!t.includes(w.matchUpStatus)&&(y[W]+=1)}}let M=s?.participants&&!u&&!p&&m,P=M?((e&&l?l.entries:a.entries)??[]).filter(w=>![io,tn].includes(w.entryStatus)).map(({participantId:w})=>w):[],N=Object.keys(D),R=M?(s?.participants??[]).filter(({participantId:w})=>P.includes(w)):p&&Object.values(D)||Object.values(U),b=w=>!p||N.includes(w),v=w=>!u||(y[w]||0)>=0,O=w=>!d||(A[w]||0)<=d,x=w=>!c||y[w]<=c,F=w=>!T.includes(w);return{eligibleParticipants:R.filter(w=>b(w.participantId)&&v(w.participantId)&&O(w.participantId)&&x(w.participantId)&&F(w.participantId)).map(w=>({...w,individualParticipants:w.individualParticipantIds?.map(B=>s?.participants?.find(G=>G.participantId===B))})),losingParticipantIds:N,...C}}function Od(t){let e=nt(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:hr};let i=r.structures?.find(g=>g.structureId===o);if(!i)return{error:Lt};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:Qo};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{...C,availableMatchUpsCount:f,lastRoundNumber:c,roundMatchUpsCount:p}}function qS({drawDefinition:t}){let e=mt({name:"participantRepresentatives",element:t});return e.error?e:{representativeParticipantIds:e.extension?.value||[]}}function MO({tournamentParticipants:t,drawDefinition:e,event:r}){if(!e)return{error:X};let n=re({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 $S({byeAdvancements:t=!1,tournamentRecord:e,drawDefinition:r}){if(!r)return{error:X};let{participantIds:n,participantIdMatchUps:o}=MO({tournamentParticipants:e?.participants,drawDefinition:r}),i=n?.map(s=>{let c=o[s].filter(d=>[ue,Pt].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 Go({tournamentRecords:t,tournamentRecord:e,tournamentId:r,drawId:n}){if(!e&&!t)return{error:j};if(!n)return{error:on};if(!e&&t){if(typeof r!="string"&&(r=BS({tournamentRecords:t,drawId:n}),!r))return{error:la};if(e=t[r],!e)return{error:j}}let o=e&&He({tournamentRecord:e,drawId:n});return o?.drawDefinition?{drawDefinition:o.drawDefinition,event:o.event,tournamentRecord:e,...C}:_({result:{error:Dr},stack:"findDrawDefinition"})}function KS(t){let{drawDefinition:e,error:r}=Go(t);return r?{error:r}:{drawDefinition:J(e)}}function _g({targetRoundNumber:t,finishingPosition:e,drawDefinition:r,structureId:n,linkType:o}){let{links:i}=Ks({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}=at({structureId:p,drawDefinition:r});if(!(e&&m?.finishingPosition!==e))return u}).filter(Boolean);return{sourceStructureIds:a.map(({source:u})=>u.structureId),relevantLinks:a}}function RO({tournamentParticipants:t,returnParticipants:e,drawPosition:r,participant:n,drawId:o,event:i}){let s=i?.entries?.filter(({entryStatus:a})=>[tn,Pi].includes(a)).map(({participantId:a})=>a)||[];if(s.length){let a=n.individualParticipantIds,c=e?t.filter(({participantId:m})=>s.includes(m)):void 0,u=e?t.filter(({participantId:m})=>a.includes(m)):void 0;return{validModifyAssignedPairAction:rt({payload:{participantId:n.participantId,replacementIndividualParticipantId:void 0,existingIndividualParticipantId:void 0,drawPosition:r,drawId:o},method:Kv,availableIndividualParticipantIds:s,availableIndividualParticipants:c,existingIndividualParticipantIds:a,existingIndividualParticipants:u,type:yg},!1,!1,!0)}}return{}}function _i(t){let{inContextDrawMatchUps:e,targetData:r,drawDefinition:n,relevantLink:o}=t;if(o?.linkCondition===to&&r?.matchUp?.matchUpStatus===Pt)return!1;let{targetMatchUps:{loserMatchUp:s,winnerMatchUp:a},targetLinks:c}=r,u=[Mt,vt].includes(s?.matchUpStatus),p=a?.drawPositions?.filter(Boolean).length||0;if(s?.winningSide&&!u||a?.winningSide&&p===2&&(!a.feedRound||![vt,Mt].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&&_i({relevantLink:c?.loserTargetLink,targetData:m,inContextDrawMatchUps:e,drawDefinition:n});return!!(d&&_i({targetData:d,inContextDrawMatchUps:e,drawDefinition:n})||l)}var zS={[yo]:{policyName:"positionActionsDefault",enabledStructures:[{stages:[ct,et],stageSequences:[1],enabledActions:[],disabledActions:[]},{stages:[],stageSequences:[],enabledActions:[Mu,ta,Gp,Zs],disabledActions:[]}],disbledStructures:[],otherFlightEntries:!1,activePositionOverrides:[]}};var xg="positionAction",QS="matchUpAction";function XS({actionType:t=xg,appliedPolicies:e,drawDefinition:r,structure:n}){let o=t===xg&&yo||t===QS&&ze,i=t===xg&&zS||t===QS&&qU,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 jD({activePositionOverrides:t,activeDrawPositions:e,action:r}){return r&&t.includes(r)?!0:!e.length}function JS({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 Gn({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 YD="replaceTieMatchUpParticipantId",qD="assignTieMatchUpParticipantId",ZS="removeTieMatchUpParticipantId",$D="assignMatchUpSideParticipant",CO="removeMatchUpSideParticipant",KD="substituteParticipant",tT="REMOVE_SUBSTITUTION",zD="REPLACE_PARTICIPANT",wg="REMOVE_PARTICIPANT",eT="setMatchUpStatus",rT="SUBSTITUTION",QD="SCHEDULE",vG="PENALTY",nT="REFEREE",XD="STATUS",oT="START",JD="SCORE",iT="END",bO={REPLACE_TEAM_POSITION_METHOD:YD,ASSIGN_TEAM_POSITION_METHOD:qD,REMOVE_TEAM_POSITION_METHOD:ZS,REPLACE_PARTICIPANT:zD,SUBSTITUTION_METHOD:KD,REMOVE_SUBSTITUTION:tT,REMOVE_PARTICIPANT:wg,SCHEDULE_METHOD:eT,SUBSTITUTION:rT,SCHEDULE:QD,PENALTY:vG,REFEREE:nT,STATUS:XD,SCORE:JD,START:oT,END:iT};function vO({specifiedPolicyDefinitions:t,inContextDrawMatchUps:e,matchUpParticipantIds:r,matchUpActionsPolicy:n,inContextMatchUp:o,policyActions:i,enforceGender:s,participantId:a,sideNumber:c,matchUpId:u,matchUp:p,drawId:m,side:d}){let l=[],f=o.sides?.find(F=>F.participant),g=o.gender===Cr&&o.sideNumber&&o.sides?.filter(F=>F.particiapntId).length===1&&f?.participant?.person?.sex,I=o.matchUpType,S=(s??n?.participants?.enforceGender)!==!1?o.gender:void 0,y=o.sides?.flatMap(F=>F.participant?.individualParticipants||F.participant).filter(Boolean)?.map(ht),D=o.sides?.filter(F=>!c||F.sideNumber===c).flatMap(F=>F.participant?.individualParticipants||F.participant).filter(Boolean),U=D?.map(ht),E=e?.find(F=>F.matchUpId===o.matchUpTieId)?.sides?.map(F=>F?.participant?.individualParticipants?.filter(({participantId:L,person:w})=>!U?.includes(L)&&(!S||S===Mn||w.sex===S||S===Cr&&!g||g&&w.sex!==g))),M=c?E?.[c-1]:E?.map((F,L)=>({participants:F,sideNumber:L+1})),P=c?E?.[c-1]?.map(ht):E?.map((F,L)=>({participants:F?.map(ht),sideNumber:L+1})),N=c&&(se(Pa)(I)&&!U?.length||se(qi)(I)&&(U?.length??0)<2)||!c&&(se(Pa)(I)&&(U?.length??0)<2||se(qi)(I)&&(U?.length??0)<4),R=P?.filter(F=>!y?.includes(F)),b=M?.filter(({participantId:F})=>R.includes(F));if(N&&R?.length&&l.push({availableParticipantIds:R,method:qD,availableParticipants:b,type:Us,payload:{participantId:void 0,tieMatchUpId:u,sideNumber:c,drawId:m}}),U?.length&&(!me(p)||d?.substitutions?.length)&&l.push({method:ZS,type:wg,existingParticipantIds:U,payload:{participantId:void 0,tieMatchUpId:u,drawId:m}}),b?.length&&(!c&&U?.length||c&&d?.participant)&&l.push({availableParticipantIds:R,method:YD,availableParticipants:b,type:zD,existingParticipantIds:U,payload:{existingParticipantId:void 0,participantId:void 0,tieMatchUpId:u,drawId:m}}),Gn({policyActions:i,action:tT})&&d?.substitutions?.length){let F=d.participant?.participantType===Tt&&[d.participantId]||d.participant?.participantType===lt&&d.participant.individualParticipantIds||[],L=d.substitutions.map(w=>w.participantId).filter(w=>F.includes(w));(!a||L.includes(a))&&l.push({method:ZS,type:tT,substitutedParticipantIds:L,payload:{participantId:void 0,tieMatchUpId:u,drawId:m}})}let v=t?.[ze],O=v?.substituteWithoutScore,x=v?.substituteAfterCompleted;if(Gn({policyActions:i,action:rT})&&r.length===2&&(!c&&U?.length||c&&d?.participant)&&(O||me(p))&&(x||p.matchUpStatus&&!ie.includes(p.matchUpStatus))&&D?.length&&M.length){let F=D.map(ht);l.push({info:"list of team players available for substitution",method:KD,availableParticipantIds:P,existingParticipantIds:F,availableParticipants:M,existingParticipants:D,type:rT,payload:{substituteParticipantId:void 0,existingParticipantId:void 0,sideNumber:c,matchUpId:u,drawId:m}})}return l}function OO({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(E=>E.type===Us)?.availableParticipantIds,f=i?.[yo]?.otherFlightEntries,g=i?.[yo]?.restrictQualifyingAlternates,I=(s.entries??[]).filter(({entryStage:E})=>!g||(p.stage===ct?E===ct:E!==ct)).sort((E,M)=>(E.entryPosition??1/0)-(M.entryPosition??1/0)).map(({participantId:E})=>E).filter(Boolean),{allPositionedParticipantIds:h}=Dh({drawDefinition:s}),S=n.map(E=>E.participantId).filter(Boolean),T=I.filter(E=>p.stage&&[ct,et,pe].includes(p.stage)?!h?.includes(E):!S.includes(E)),D=(d?.entries??[]).filter(E=>E.entryStatus===Jr&&ZD({restrictQualifyingAlternates:g,structure:p,entry:E})&&(p.stage&&[ct,et,pe].includes(p.stage)?!h?.includes(E.participantId):!S.includes(E.participantId))).sort((E,M)=>(E.entryPosition??1/0)-(M.entryPosition??1/0)).map(E=>E.participantId),U=pt(T.concat(D));if(f){let M=(d?Wt({event:d}).flightProfile:void 0)?.flights?.filter(P=>P.drawId!==m).map(P=>P.drawEntries.filter(N=>N.participantId&&![io,tn,Pi].includes(N.entryStatus)&&!I.includes(N.participantId)).map(({participantId:N})=>N)).flat().filter(Boolean);M?.length&&U.push(...M)}l?.length&&(U=U.filter(E=>!l.includes(E)));let A=o?t?.filter(E=>U.includes(E.participantId)):void 0;return A?.forEach(E=>{let M=(s.entries??[]).find(P=>P.participantId===E.participantId);E.entryPosition=M?.entryPosition}),A?.sort((E,M)=>(E.entryPosition||1/0)-(M.entryPosition||1/0)),U.length?{validAlternatesAction:rt({payload:{drawId:m,structureId:u,drawPosition:a},willDisableLinks:e,method:qv,availableAlternatesParticipantIds:U,type:Ag,availableAlternates:A})}:{}}function ZD({restrictQualifyingAlternates:t,structure:e,entry:r}){let{stage:n}=e;if(!r.entryStage||r.entryStage===n||n===ct&&!t||r.entryStage===et&&n===Ve)return!0}function _O({eventEntries:t,structure:e}){let r=o=>o.entryStatus===Jr&&ZD({structure:e,entry:o}),n=(o,i)=>(o.entryPosition||1/0)-(i.entryPosition||1/0);return t.filter(r).sort(n).map(ht)}function xO({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??[],g=u.sides?.find(M=>M.sideNumber===s)?.participantId,I=l.filter(({roundNumber:M})=>M===u.roundNumber),h=o?.entries?.filter(({entryStatus:M})=>M&&ni.includes(M)).map(ht)??[],S=I.map(M=>(M.sides??[]).flatMap(ht)).flat().filter(Boolean),T=h.filter(M=>!r.includes(M)&&(!t||!S.includes(M))),y=e?.filter(M=>T?.includes(M.participantId)).map(M=>J(M,void 0,!0));y?.forEach(M=>{let P=(o.entries??[]).find(N=>N.participantId===M.participantId);M.entryPosition=P?.entryPosition}),T.length&&d.push({payload:{drawId:p,matchUpId:a,structureId:i,sideNumber:s},method:$D,type:Us,availableParticipantIds:T,participantsAvailable:y});let D=m?.entries??[],U=_O({eventEntries:D,structure:c}),A=pt(h.concat(U));if(n){let P=(m?Wt({event:m}):void 0)?.flights?.filter(N=>N.drawId!==p).flatMap(N=>N.drawEntries.filter(R=>R.participantId&&![io,tn,Pi].includes(R.entryStatus)).map(({participantId:R})=>R)).filter(Boolean);P?.length&&A.push(...P)}A=A.filter(M=>!r.includes(M)&&!T.includes(M)&&(!t||!S.includes(M)));let E=e?.filter(M=>A.includes(M.participantId)).map(M=>J(M,void 0,!0));if(E?.forEach(M=>{let P=(o.entries??[]).find(N=>N.participantId===M.participantId);M.entryPosition=P?.entryPosition}),E?.sort((M,P)=>(M.entryPosition||1/0)-(P.entryPosition||1/0)),A.length&&d.push({payload:{drawId:p,matchUpId:a,structureId:i,sideNumber:s},availableParticipantIds:A,participantsAvailable:E,method:$D,type:Jr}),!me(u)&&s&&g){d.push({payload:{drawId:p,matchUpId:a,structureId:i,sideNumber:s},method:CO,type:wg});let M=L=>L.sides.map(ht),P=({matchUpId:L})=>L!==u.matchUpId,N=L=>!me(L),R=u.sides?.find(L=>L.sideNumber!==s)?.participantId,v=l.filter(({roundNumber:L})=>L!==u.roundNumber).filter(P).map(M),O=[R,...v.filter(L=>L.includes(g)).flat()].filter(Boolean),x=L=>!O.flat().includes(L),F=I.filter(N).filter(P).map(M).flat().filter(x);if(F.length){let L=e?.filter(w=>F.includes(w.participantId)).map(w=>J(w,void 0,!0));d.push({payload:{participantIds:[g],roundNumber:u.roundNumber,structureId:i,sideNumber:s,matchUpId:a,drawId:p},swappableParticipantIds:F,method:zv,type:Bp,swappableParticipants:L})}}return d}function _d(t){if(!t)return{error:k};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&&te(t.tournamentId)&&t.tournamentRecords?.[t.tournamentId]);if(!u)return{error:j};if(!c||!te(c))return{error:er};if(a&&![1,2].includes(a))return _({result:{error:k},context:{sideNumber:a}});if(!e){let st=(fe({tournamentRecord:u}).matchUps??[]).find(it=>it.matchUpId===c);r=(u?.events??[]).find(it=>it.eventId===st?.eventId);let St=(r?.drawDefinitions??[]).find(it=>it.drawId===st?.drawId);St&&(e=St)}if(!e)return{error:X};let p=$t({withIndividualParticipants:!0,tournamentRecord:u}).participants,{drawId:m}=e,{matchUp:d,structure:l}=Gt({drawDefinition:e,matchUpId:c,event:r});if(!d)return{error:_e};let f=yt({tournamentRecord:u,drawDefinition:e,structure:l,event:r}).appliedPolicies??{};Object.assign(f,o??{});let g=f?.[yo]?.otherFlightEntries,I=f?.[ze]??ys[ze],{enabledStructures:h}=XS({actionType:QS,appliedPolicies:f,drawDefinition:e,structure:l}),{policyActions:S}=JS({enabledStructures:h,drawDefinition:e,structure:l}),T=t.matchUpsMap??Ee({drawDefinition:e}),y=t.inContextDrawMatchUps??re({tournamentParticipants:p,inContext:!0,drawDefinition:e,matchUpsMap:T,event:r}).matchUps,D=y?.find(Q=>Q.matchUpId===c),U=a&&D?.sides?.find(Q=>Q.sideNumber===a),A=D?.sides?.map(Q=>Q.participantId||Q.participant?.participantid).filter(Boolean)??[],{assignedPositions:E,allPositionsAssigned:M}=le({structure:l}),{structureId:P}=l??{},N=[];if(!P)return{validActions:N};let R=pr({structure:l}),b=d.collectionId;if(R&&!b){let Q=xO({restrictAdHocRoundParticipants:n,tournamentParticipants:p,matchUpParticipantIds:A,otherFlightEntries:g,drawDefinition:e,structureId:P,sideNumber:a,matchUpId:c,structure:l,matchUp:d,drawId:m,event:r});N.push(...Q)}let v=si({drawDefinition:e,structure:l}),O=E?.filter(Q=>Q.participantId).map(Q=>Q.drawPosition),x=E?.filter(Q=>Q.bye).map(Q=>Q.drawPosition),F=d.matchUpStatus===Pt||!b&&d.drawPositions?.reduce((Q,st)=>x?.includes(st)||Q,!1);if(F)return{validActions:N,isByeMatchUp:F};Gn({policyActions:S,action:nT})&&N.push({type:nT,payload:{matchUpId:c}});let L=!Ca({matchUpStatus:d.matchUpStatus}),w=f?.scoring?.structures,B=l?.stage&&w?.stage&&w?.stage[l.stage],G=l?.stageSequence&&B?.stageSequence&&B.stageSequence[l.stageSequence],H=!(f?.scoring?.requireAllPositionsAssigned||B?.requireAllPositionsAssigned||G?.requireAllPositionsAssigned)||M,q=d.sides&&d.sides.filter(Q=>Q?.participantId).length===2,$=d.matchUpStatus&&[he,Ce].includes(d.matchUpStatus),V=nr({inContextDrawMatchUps:y,drawDefinition:e,matchUpId:c}),K=_i({inContextDrawMatchUps:y,drawDefinition:e,targetData:V}),Y=(D?.drawPositions?.length===2&&D.drawPositions.every(Q=>O?.includes(Q))&&D?.sides?.length===2&&D.sides.every(({participantId:Q})=>Q)||q)&&!($&&K),Z={method:MS,type:ta,payload:{drawId:m,matchUpId:c,penaltyCode:void 0,penaltyType:void 0,participantIds:[],notes:void 0}};if(L&&N.push({payload:{drawId:m,matchUpId:c,schedule:{}},method:eT,type:QD}),Gn({policyActions:S,action:ta})&&(U?.participant||!a&&A?.length)&&N.push(Z),L&&Y&&N.push({type:XD}),H&&Y){let{matchUpId:Q,matchUpFormat:st}=d,St={drawId:m,matchUpId:Q,matchUpFormat:st,outcome:{scoreStringSide1:void 0,scoreStringSide2:void 0,sets:[]},winningSide:void 0};N.push({info:"set outcome and winningSide",method:eT,type:JD,payload:St}),Gn({policyActions:S,action:oT})&&N.push({type:oT}),Gn({policyActions:S,action:iT})&&N.push({type:iT})}if(b&&D){let Q=vO({specifiedPolicyDefinitions:o,inContextDrawMatchUps:y,matchUpParticipantIds:A,matchUpActionsPolicy:I,inContextMatchUp:D,policyActions:S,enforceGender:i,participantId:s,sideNumber:a,matchUpId:c,matchUp:d,drawId:m,side:U});N.push(...Q)}return{structureIsComplete:v,validActions:N,isDoubleExit:$,...C}}function wO({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}=at({structureId:S,drawDefinition:s}),y=T?.finishingPosition===Wi&&(d?.length!==1||l?.length!==1),D={};if(y){let{matchUps:M}=Et({drawDefinition:s,structure:u,event:m}),{initialRoundNumber:P}=hs({drawPosition:a,matchUps:M}),R=s.links?.find(b=>b.target?.structureId===u?.structureId&&b.target.roundNumber===P)?.source?.roundNumber;D.roundNumbers=[R]}let{completedMatchUps:U}=Au({structureId:S,inContext:!0,matchUpFilters:D,drawDefinition:s}),A=i.map(M=>M.participantId).filter(Boolean);U?.filter(({matchUpType:M,winningSide:P})=>P&&(m?.eventType!==Me||M===Me)).map(({winningSide:M,sides:P})=>M&&P?.[1-(M-1)]).map(ht).filter(M=>M&&!A.includes(M))?.forEach(M=>{f.includes(M)||f.push(M)})}let I=t?.filter(h=>f?.includes(h.participantId));return I?.forEach(h=>{let S=(s.entries??[]).find(T=>T.participantId===h.participantId);h.entryPosition=S?.entryPosition}),f?.length?{validLuckyLosersAction:{type:Ug,method:$v,availableLuckyLosers:I,availableLuckyLoserParticipantIds:f,willDisableLinks:r,payload:{drawId:p,structureId:c,drawPosition:a}}}:{}}function LO({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?.[xn]?.validSeedPositions?.ignore;if(y||({unplacedSeedParticipantIds:h,unplacedSeedAssignments:S,unfilledPositions:T}=dS({provisionalPositioning:n,returnAllProxies:!0,randomize:!0,drawDefinition:u,seedingProfile:p,structureId:l,event:f})),T?.length||(T=s.filter(D=>!D.participantId&&!D.bye&&!D.qualifier).map(D=>D.drawPosition)),m||I.push({payload:{drawId:g,structureId:l,drawPosition:d,isPositionAction:!0},willDisableLinks:r,method:Jv,type:Ed}),i&&y){let D=s.map(P=>P.participantId).filter(Boolean),U={structureIds:t},{completedMatchUps:A}=zs({inContext:!0,matchUpFilters:U,drawDefinition:u}),E=pt((A??[]).filter(({matchUpType:P})=>f?.eventType!==Me||P===Me)?.map(({sides:P})=>P?.map(ht)).flat().filter(P=>P&&!D.includes(P))),M=a?o?.filter(P=>E?.includes(P.participantId)).map(P=>J(P,void 0,!0)):void 0;return M?.forEach(P=>{let N=(u.entries??[]).find(R=>R.participantId===P.participantId);P.entryPosition=N?.entryPosition}),M?.length&&I.push(rt({payload:{drawId:g,structureId:l,drawPosition:d},willDisableLinks:r,method:yD,type:Us,availableParticipantIds:E,participantsAvailable:M})),{validAssignmentActions:I}}if(T.includes(d)||m){let D;if(S?.length){let A=S.filter(E=>h?.includes(E.participantId));A.sort(OG),D=A.map(E=>E.participantId)}else D=e;let U=a?o?.filter(A=>D.includes(A.participantId)).map(A=>J(A,void 0,!0)):void 0;U?.length&&I.push(rt({payload:{drawId:g,structureId:l,drawPosition:d},willDisableLinks:r,method:yD,type:Us,availableParticipantIds:D,participantsAvailable:U}))}return{validAssignmentActions:I}}function OG(t,e){return t.bye||Ac(t.seedValue)<Ac(e.seedValue)||t.seedValue&&!e.seedValue?-1:(t.seedNumber||0)-(e.seedNumber||0)}function FO({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(D=>D.participantId).filter(Boolean),f=o?.[yo],g=!f?.disableRoundRestrictions&&t[s],I=f?.requireCompletedStructures,{sourceStructureIds:h,relevantLinks:S}=_g({targetRoundNumber:g,linkType:fo,drawDefinition:i,structureId:a})||{};h?.length&&d.push(...h);let{sourceStructureIds:T,relevantLinks:y}=_g({targetRoundNumber:g,linkType:Jn,drawDefinition:i,structureId:a})||{};T?.length&&d.push(...T);for(let D of S){let U=i.structures?.find(E=>E.structureId===D.source.structureId);if(U?.stage!==ct)continue;let A=si({structureId:D.source.structureId,drawDefinition:i});if(!I||A){let E=U.qualifyingRoundNumber,{matchUps:M}=Et({matchUpFilters:{roundNumbers:[E],hasWinningSide:!0},afterRecoveryTimes:!1,tournamentParticipants:e,inContext:!0,structure:U});for(let P of M){let N=P.sides.find(b=>b?.sideNumber===P.winningSide),R=P.matchUpStatus===Pt&&P.sides?.find(({participantId:b})=>b);if(N||R){let{participantId:b,participant:v}=N||R||{};b&&!l.includes(b)&&(v&&n&&u.push(v),p.push(b))}}}}for(let D of y){let U=i.structures?.find(E=>E.structureId===D.source.structureId);if(U?.stage!==ct)continue;let A=si({structureId:D.source.structureId,drawDefinition:i});if(!I||A){let{positionAssignments:E}=Ct({structure:U}),M=E?.map(P=>{let N=P.participantId,R=mt({element:P,name:Zo}).extension?.value;return R?{participantId:N,groupOrder:R?.groupOrder}:{}}).filter(({groupOrder:P,participantId:N})=>P===1&&!l.includes(N)).map(({participantId:P})=>P)??[];if(M&&p.push(...M),n){let P=e.filter(({participantId:N})=>M.includes(N));u.push(...P)}}}return p.length&&m.push(rt({payload:{qualifyingParticipantId:void 0,drawPosition:s,structureId:a,drawId:c},method:jv,type:Gp,qualifyingParticipantIds:p,qualifyingParticipants:n?u:void 0})),{validAssignmentActions:m,sourceStructureIds:d}}function kO({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}=Et({afterRecoveryTimes:!1,inContext:!0,drawDefinition:c,structure:d,event:f}),y=T.filter(({drawPositions:P})=>xe(P,S)),D=Object.assign({},...y.map(P=>P.sides?.filter(({sourceDrawPositionRange:N})=>N).map(({drawPosition:N,sourceDrawPositionRange:R})=>({[N]:R}))).flat()),U=h.map(P=>P.participantId).filter(Boolean),A=(r??[]).filter(P=>U.includes(P.participantId)),E=Object.assign({},...A.map(P=>({[P.participantId]:P}))),M=h.map(P=>{let N=E?.[P.participantId],R=D[P.drawPosition];return rt({...P,participant:s?J(N,!1,!0):void 0,sourceDrawPositionRange:R})});return M.length?{validSwapAction:{payload:{drawId:l,structureId:m,drawPositions:[p]},willDisableLinks:e,method:NS,type:Bp,availableAssignments:M}}:{}}function sT(t){let e=nt(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&&$t({withIndividualParticipants:!0,tournamentRecord:i}).participants)??[],p=at({structureId:t.structureId,drawDefinition:s});if(p.error)return p;let m=p.containingStructure||p.structure;if(!m)return{error:Lt};let d=m.structureId;if(p=ba({drawDefinition:s,structureId:d}),a===void 0&&!p.isAdHoc)return{error:_s};if(p.isAdHoc)return _d(t);if(p.error)return p;let{drawPositionInitialRounds:l,inactiveDrawPositions:f,activeDrawPositions:g,byeDrawPositions:I}=p,h=yt({tournamentRecord:i,drawDefinition:s,structure:m,event:c}).appliedPolicies??{};Object.assign(h,r??{});let{actionsPolicy:S,enabledStructures:T,actionsDisabled:y}=XS({actionType:xg,appliedPolicies:h,drawDefinition:s,structure:m}),D=S?.activePositionOverrides||[],{sourceStructureIds:U}=_g({finishingPosition:Vs,targetRoundNumber:1,linkType:Jn,drawDefinition:s,structureId:d})||{},A;U?.length&&(A=U.reduce((z,Y)=>si({structureId:Y,drawDefinition:s})&&z,!0));let E=U.length,M=U.length&&!A,{policyActions:P}=JS({enabledStructures:T,drawDefinition:s,structure:m}),N=![ct,et].includes(m.stage)||m.stageSequence!==1,{drawId:R}=s,b=[],{assignedPositions:v,positionAssignments:O}=le({structure:m}),x=v?.find(z=>z.drawPosition===a);if(!O?.map(z=>z.drawPosition)?.includes(a))return{error:Os};let{stage:L,stageSequence:w}=m,B=[L];L===Ve&&B.push(et),L===et&&B.push(Ve);let G=Ni({entryStatuses:ni,provisionalPositioning:o,drawDefinition:s,stageSequence:w,structureId:d,stages:B}),W=Oi({drawDefinition:s,stages:B}).assignedParticipantIds??[],H=G.filter(z=>!W.includes(z.participantId)).map(z=>z.participantId),q=I.includes(a),$=g.includes(a);if(y)return{hasPositionAssigned:!!x,info:"Actions Disabled for structure",isActiveDrawPosition:$,isDrawPosition:!0,validActions:[],isByePosition:q};if(Gn({policyActions:P,action:Us})&&!$&&O&&!M&&(!x||q)){let{validAssignmentActions:z}=LO({positionSourceStructureIds:U,unassignedParticipantIds:H,possiblyDisablingAction:N,isWinRatioFedStructure:E,tournamentParticipants:u,positionAssignments:O,returnParticipants:n,appliedPolicies:h,drawDefinition:s,isByePosition:q,drawPosition:a,structureId:d,event:c});z?.forEach(Y=>b.push(Y))}if(Gn({policyActions:P,action:Gp})){let{validAssignmentActions:z}=FO({drawPositionInitialRounds:l,tournamentParticipants:u,positionAssignments:O,returnParticipants:n,appliedPolicies:h,drawDefinition:s,drawPosition:a,structureId:d,drawId:R});z?.forEach(Y=>b.push(Y))}let{participantId:V}=x||{},K=V&&u.find(z=>z.participantId===V);if(x){Gn({policyActions:P,action:RS})&&!$&&(b.push({type:RS,method:TD,payload:{drawId:R,structureId:d,drawPosition:a},willDisableLinks:N}),q||b.push({type:Eg,method:Yv,payload:{drawId:R,structureId:d,drawPosition:a},willDisableLinks:N}),Gn({policyActions:P,action:Ed})&&!q&&b.push({type:Ed,method:TD,payload:{drawId:R,structureId:d,drawPosition:a,replaceWithBye:!0},willDisableLinks:N}));let z=m.stage===ct||m.stage===et&&m.stageSequence===1;if(!q&&jD({activePositionOverrides:D,activeDrawPositions:g,action:Zs})&&Gn({policyActions:P,action:Zs})&&Lp({drawDefinition:s,structureId:d,drawPosition:a})&&z){let{seedAssignments:Y}=en({returnAllProxies:!0,drawDefinition:s,structure:m}),{seedNumber:Z,seedValue:Q}=Y?.find(st=>st.participantId===V)??{};b.push({type:Zs,method:Zv,participant:K,seedNumber:Z,payload:{drawId:R,structureId:d,participantId:V,seedValue:Q}})}if(!q&&jD({activePositionOverrides:D,activeDrawPositions:g,action:Vp})&&Gn({policyActions:P,action:Vp})&&Lp({drawDefinition:s,structureId:d,drawPosition:a})&&z){let{seedAssignments:Y}=en({returnAllProxies:!0,drawDefinition:s,structure:m}),{seedNumber:Z}=Y?.find(Q=>Q.participantId===V)??{};b.push({method:Xv,type:Vp,participant:K,seedNumber:Z,payload:{participantId:V,structureId:d,drawId:R}})}if(!q&&V){if(Gn({policyActions:P,action:ta})){let Y={type:ta,method:MS,participant:K,payload:{penaltyCode:void 0,penaltyType:void 0,participantIds:[],notes:void 0,drawId:R}};b.push(Y)}if(Gn({policyActions:P,action:Mu})){let Y={type:Mu,method:Qv,participant:K,payload:{participantId:V,otherName:void 0}};b.push(Y)}}if(Gn({policyActions:P,action:Bp})){let{validSwapAction:Y}=kO({possiblyDisablingAction:N,tournamentParticipants:u,inactiveDrawPositions:f,activeDrawPositions:g,positionAssignments:O,returnParticipants:n,byeDrawPositions:I,drawDefinition:s,isByePosition:q,drawPosition:a,structureId:d,structure:m,drawId:R});Y&&b.push(Y)}}if(Gn({policyActions:P,action:Ag})&&!M){let{validAlternatesAction:z}=OO({possiblyDisablingAction:N,tournamentParticipants:u,positionAssignments:O,activeDrawPositions:g,returnParticipants:n,appliedPolicies:h,drawDefinition:s,drawPosition:a,validActions:b,structureId:d,structure:m,drawId:R,event:c});z&&b.push(z)}if(Gn({policyActions:P,action:Ug})&&!M&&O){let{validLuckyLosersAction:z}=wO({sourceStructuresComplete:A,possiblyDisablingAction:N,isWinRatioFedStructure:E,tournamentParticipants:u,activeDrawPositions:g,positionAssignments:O,drawDefinition:s,drawPosition:a,structureId:d,structure:m,drawId:R});z&&b.push(z)}if(K?.participantType===lt&&Gn({policyActions:P,action:yg})){let{validModifyAssignedPairAction:z}=RO({tournamentParticipants:u,returnParticipants:n,drawPosition:a,participant:K,drawId:R,event:c});z&&b.push(z)}return{hasPositionAssigned:!!x,isActiveDrawPosition:$,isDrawPosition:!0,isByePosition:q,validActions:b,...C}}function Fu({policyDefinitions:t,appliedPolicies:e,drawType:r}){let n=t?.[Gm]?.drawTypeCoercion,o=e?.[Gm]?.drawTypeCoercion;return(typeof n=="boolean"?n:void 0)??(r&&n?.[r])??(typeof o=="boolean"?o:void 0)??(r&&o?.[r])??!0}function qp({tournamentRecord:t,drawDefinition:e,stage:r=et,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:hr};let{error:i,positionAssignments:s}=Ct({drawDefinition:e,structureId:n,structure:o});return{positionAssignments:s??[],structureId:o?.structureId,error:i}}function aT({structureId:t,drawDefinition:e}){if(!e)return{error:X};if(!te(t))return{error:k};let r=Ks({drawDefinition:e,structureId:t});if(r.error)return r;let n=r.links.target.flatMap(i=>i.target.feedProfile).filter(Boolean),o=!qt([Ii,yn,lp,gi],n).length;return{...C,valid:o}}function cT({participantsCount:t,participantCount:e}){if(t=t??e,!t)return{error:k};let r=os(t);return r?{drawSize:r}:_({result:{error:k},stack:"getEliminationDrawSize",context:{participantsCount:t}})}function ku(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=_o({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:k},context:{participantsCount:u},stack:c});if(o&&!p)return _({result:{error:dE},stack:c});if(isNaN(n))if(u)({drawSize:n}=cT({participantsCount:u}));else return _({result:{error:Qa},stack:c});let m=o&&u||n;if(m&&m>n)return{error:$l};let d=r?.[xn];if(!d)return{error:tE};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:kA}}function xd({consideredEntries:t,policyDefinitions:e,tournamentRecord:r,appliedPolicies:n,participantMap:o,enforceGender:i,participants:s,event:a}){if((!s||!o)&&r&&({participants:s,participantMap:o}=$t({tournamentRecord:r})),!s)return{error:Ja};if(!Array.isArray(s))return{error:k};if(!a)return{error:bt};let c=e?.[ze]??n?.[ze]??ys[ze],u=(i??c?.participants?.enforceGender)!==!1,{eventType:p,gender:m}=a,d=p===fi,l=p===Kr&&Ft||d&<||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=xG({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:$A,invalidParticipantIds:S}}return{...C,valid:!0}}function _G({participant:t,participantType:e,eventType:r,entryStatusMap:n}){let o=n[t.participantId],i=r&&[fi,Kr].includes(r)&&t.participantType===Tt&&(Qs(o)||o===io);return t.participantType!==e&&!i}function xG(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||Mn===n||[Zt,ce].includes(n)&&a[0]===n||Cr===n&&(a.length==1&&e.individualParticipantIds?.length===1||a.length===2),u=e?.person?.sex,p=!e?.person||!n||[Mn,Cr].includes(n)||[Zt,ce].includes(n)&&u===n;return!s||c&&p}function uT({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,D;for(let U of(I||[]).sort(u)){let A=Mm(U.drawSize||U.participantsCount),{qualifyingRoundNumber:E,structureOptions:M,matchUpFormat:P,structureName:N,structureId:R,drawType:b}=U,v=U.matchUpType,O=U.qualifyingPositions||wG({drawSize:A,qualifyingRoundNumber:E}),x,F,L;if(!ft(A))return _({result:{error:Qa},stack:i});let w=t.length>1?`${f}-`:"",B=I.length>1||w?h:"",G=N||(w||B?`${Ye(ct)} ${w}${B}`:Ye(ct));if(b===Un){let{structures:W,groupCount:H,maxRoundNumber:q}=Oa({structureName:U.structureName||G,structureId:R||o?.pop(),stage:ct,structureOptions:M,appliedPolicies:e,stageSequence:h,matchUpType:v,roundTarget:f,drawSize:A,idPrefix:r,isMock:n,uuids:o});S=H,x=q,F=W[0],l=[1]}else({drawSize:A,matchUps:L,roundLimit:x}=Rn({qualifyingRoundNumber:E,qualifyingPositions:O,matchUpType:v,drawSize:A,idPrefix:r,isMock:n,uuids:o})),F=In({structureName:U.structureName||G,structureId:R||o?.pop(),qualifyingRoundNumber:x,stage:ct,matchUpFormat:P,stageSequence:h,matchUpType:v,roundLimit:x,matchUps:L}),f&&At({extension:{name:Dn,value:f},element:F}),S=L?.filter(W=>W.roundNumber===x)?.length||0;if(h>1){let{link:W}=_a({sourceStructureId:y,sourceRoundNumber:T,targetStructureId:F.structureId,finishingPositions:D===Jn?[1]:void 0,linkType:D});c.push(W),m+=(A||0)-S}else m+=A||0;D=b===Un?Jn:fo,y=F.structureId,T=x,a.push(F),h+=1}d+=S,s.push({qualifiersCount:S,finalQualifyingRoundNumber:T,finalQualifyingStructureId:y,finishingPositions:l,roundTarget:f,linkType:D}),f+=1}return{qualifiersCount:d,qualifyingDrawPositionsCount:m,qualifyingDetails:s,structures:a,...C,links:c}}function wG({drawSize:t,qualifyingRoundNumber:e}){let r=t,n=0;for(;n<e;)r=Math.floor(r/2),n+=1;return r}function pT(t){let{drawTypeCoercion:e,enforceMinimumDrawSize:r}=t,n=ut(t.drawSize),o=e&&(typeof e=="boolean"||e<=2)&&n===2&&go||t.drawType||go,i=eU.includes(o);if(n&&i){if(e&&(typeof e=="boolean"&&n<4||n<=e))o=go;else if(n<4&&r)return{..._({context:{enforceMinimumDrawSize:r,drawSize:n,drawType:o},result:{error:Ju},stack:"getCoercedDrawType"}),drawType:o}}return{drawType:o}}function GO(t){let{drawDefinition:e,structureOptions:r,requireSequential:n}=t,o={structureName:Ye(et),...t,stage:et},{structures:i,groupCount:s,groupSize:a}=Oa(o);if(s<1)return{error:CE};let c=r?.playoffGroups||[{finishingPositions:[1],structureName:Ye(pe)}],[u]=i,{structures:p,links:m}=xS({sourceStructureId:u.structureId,requireSequential:n,drawDefinition:e,playoffGroups:c,groupCount:s,groupSize:a,...t});return p&&i.push(...p),{...C,structures:i,links:m}}function VO({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?yn:Ii,f=1+m;return{linkType:Zn,source:{roundNumber:f,structureId:t.structureId},target:{feedProfile:l,roundNumber:p,structureId:e.structureId}}}),c={linkType:fo,source:{roundNumber:s,structureId:e.structureId},target:{feedProfile:yn,roundNumber:i,structureId:t.structureId}},u=[{linkType:fo,source:{roundNumber:i,structureId:t.structureId},target:{feedProfile:yn,roundNumber:1,structureId:r.structureId}},{linkType:Zn,source:{roundNumber:i,structureId:t.structureId},target:{feedProfile:yn,roundNumber:1,structureId:r.structureId}}];return[...a,c,...u]}function BO({structureName:t,matchUpType:e,idPrefix:r,drawSize:n,isMock:o,uuids:i}){let s=[],{matchUps:a}=ai({linkFedFinishingRoundNumbers:[1],drawSize:n+1,matchUpType:e,idPrefix:r,isMock:o}),c=As({structureName:t||Ye(et),structureId:i?.pop(),stageSequence:1,stage:et,matchUpType:e,matchUps:a});s.push(c);let u=n/2,{matchUps:p}=ai({finishingPositionOffset:u,idPrefix:r&&`${r}-c`,drawSize:n-1,isConsolation:!0,matchUpType:e,isMock:o,uuids:i}),m=As({structureName:Ye(tU),matchUps:p,structureId:i?.pop(),stage:Ve,stageSequence:2,matchUpType:e});s.push(m);let{matchUps:d}=Rn({idPrefix:r&&`${r}-p1t2`,drawSize:2,matchUpType:e,isMock:o}),l=As({structureName:Ye(ZE),matchUps:d,structureId:i?.pop(),stageSequence:3,stage:pe,matchUpType:e});s.push(l);let f=VO({mainStructure:c,consolationStructure:m,deciderStructure:l});return{structures:s,links:f,...C}}function HO(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(On(s))return Rn(t);let u=LG(s),p=u.shift(),m=tt(1,(p?.participantsCount||0)+1).map(I=>({drawPosition:I})),d=[],l=1;({matchUps:d}=Hp({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=tt(1,h+1);n&&h===n&&(f=l-1);let T=S.map(y=>{let D=Ud({roundPosition:y,roundNumber:l,idPrefix:i,uuids:c});return{roundPosition:y,roundNumber:l,matchUpId:D}});d.push(...T),l++}let g=l-1;return d=Ra({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 LG(t){let e=ut(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 mT(t){let{playoffAttributes:e,stageSequence:r=1,stage:n=et,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??yt(t),p=t.policyDefinitions?.[cc]||u?.[cc];t.skipRounds=t.skipRounds||i<=4&&(p?.feedFromMainFinal?0:1)||0;let m=t.structureName??e?.["0"]?.name??Ye(et),d=()=>{let{matchUps:f}=Rn(t);return{structures:[In({stageSequence:r,structureName:m,matchUpType:o,structureId:c,matchUps:f,stage:n})],links:[],...C}};return{generators:{[an]:()=>({structures:[In({finishingPosition:Vs,stageSequence:r,structureName:m,matchUps:[],matchUpType:o,structureId:c,stage:n})],links:[],...C}),[Hi]:()=>{let{matchUps:f}=HO(t);return{structures:[In({stageSequence:r,structureName:m,matchUpType:o,structureId:c,matchUps:f,stage:n})],links:[],...C}},[go]:()=>d(),[Zc]:()=>BO(t),[Xc]:()=>Pc({...t,roundOffsetLimit:3,playoffAttributes:e??lf}),[Jc]:()=>Pc({...t,roundOffsetLimit:2,playoffAttributes:e??ff}),[pe]:()=>Pc(t),[Ia]:()=>{let{matchUps:f}=ai({drawSize:i,uuids:s,matchUpType:o});return{structures:[In({stageSequence:r,structureName:m,matchUpType:o,structureId:c,stage:et,matchUps:f})],links:[],...C}},[fp]:()=>bS(t),[tu]:()=>Mc({...t,feedRounds:1,fmlc:!0}),[JE]:()=>Mc({...t,feedRounds:1}),[XI]:()=>Mc({...t,feedsFromFinal:1}),[JI]:()=>Mc({...t,feedsFromFinal:2}),[ZI]:()=>Mc({...t,feedsFromFinal:3}),[gp]:()=>Mc(t),[df]:()=>OS(t),[Un]:()=>Oa(t),[Io]:()=>GO(t)}}}function wd(t){let{enforceMinimumDrawSize:e=!0,overwriteExisting:r,appliedPolicies:n,staggeredEntry:o,drawDefinition:i,tieFormat:s,isMock:a,uuids:c}=t||{},u=ut(t.drawSize),p=t.drawTypeCoercion??Fu({appliedPolicies:n,drawType:t.drawType}),m="generateDrawStructuresAndLinks",d=pT({drawType:t.drawType,enforceMinimumDrawSize:e,drawTypeCoercion:p,drawSize:u});if(d.error)return d;let l=d.drawType,f=[],g=[],I=t?.matchUpType??Bt,h=i?.structures?.filter(({stage:W})=>W===ct);h&&f.push(...h);let S=h?.map(({structureId:W})=>W),T=i?.structures?.find(({stage:W,stageSequence:H})=>W===et&&H===1),y=i?.links?.filter(W=>W.target.structureId===T?.structureId&&S?.includes(W.source.structureId)),D=(W,H)=>{if(W.linkType===Jn&&H?.structures){let q=W.source.finishingPositions||[];return H.structures.length*q.length}else if(W.linkType===fo&&H?.matchUps?.length){let q=W.source.roundNumber;return H.matchUps.filter(({roundNumber:V})=>V===q).length}},U=h?.map(W=>{let H=y?.find(z=>z.target.structureId===W.structureId),q=Ct({structure:W})?.positionAssignments?.length??0;if(!H)return q;let $=H?.source.structureId,V=i.structures?.find(z=>z.structureId===$),K=D(H,V)||0;return q-K}).filter(Boolean).reduce((W,H)=>W+H,0),A=y?.map(W=>{let H=W.source.structureId,q=h?.find($=>$.structureId===H);return D(W,q)}).filter(Boolean).reduce((W,H)=>W+H,0),E=!!(T&&!T?.matchUps?.length);if(h?.length&&!E)return{error:WI};let M=!h?.length&&t.qualifyingProfiles,P=M?.length&&uT({idPrefix:t.idPrefix,qualifyingProfiles:M,appliedPolicies:n,isMock:a,uuids:c});if(P?.error)return P;let{qualifyingDrawPositionsCount:N,qualifyingDetails:R,qualifiersCount:b}=P||{qualifyingDrawPositionsCount:U,qualifiersCount:A};N&&(P?.structures&&f.push(...P.structures),P?.links&&g.push(...P.links)),Object.assign(t,rt({drawSize:u,matchUpType:I,tieFormat:s}));let v=l!==an&&(!u||u<2||!o&&![Ia,Hi].includes(l)&&([Io,Un].includes(l)&&u<3||![Un,Io].includes(l)&&!On(u)));if(v&&!N)return _({context:{drawSize:u,invalidDrawSize:v},result:{error:Ju},stack:m});let{generators:O,error:x}=mT(t);if(x)return{error:x};let F=O[l];if(!F)return{error:wl};let L=F?.();if(L.error)return L;let{structures:w,links:B}=L;if(w?.length){let W=w.find(({stage:H,stageSequence:q})=>H===et&&q===1);if(T&&W){if(E){let H=W.structureId;if(W.structureId=T.structureId,B?.length)for(let q of B)q.source.structureId===H&&(q.source.structureId=T.structureId),q.target.structureId===H&&(q.target.structureId=T.structureId)}else if(!r)return{error:WI}}f.push(...w)}f.sort(Ai),B?.length&&g.push(...B);let G=L.structures.find(({stage:W,stageSequence:H})=>W===et&&H===1);for(let W of R||[]){let{finalQualifyingRoundNumber:H,finalQualifyingStructureId:q,roundTarget:$,finishingPositions:V,linkType:K}=W,z=G&&_a({targetStructureId:G.structureId,sourceStructureId:q,sourceRoundNumber:H,finishingPositions:V,targetEntryRound:$,linkType:K})?.link;if(z?.error)return z;z&&g.push(z)}return y&&g.push(...y),{...C,qualifyingResult:{qualifyingDrawPositionsCount:N,qualifiersCount:b},structures:f,links:g}}function Ld(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=mr({tieFormat:s});if(T.error)return T}s=Ze(s??We({drawDefinition:i})?.tieFormat),a=a??(i.matchUpType||Bt),t.tieFormat=s,t.matchUpType=a;let c=_p({drawDefinition:i,stage:et});t.drawSize=t.drawSize??c,!c&&t.drawSize&&kp({drawSize:t.drawSize,drawDefinition:i,stageSequence:r,stage:et});let u=Ee({drawDefinition:i}).drawMatchUps.map(Ie),p=wd(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&&!_p({stage:ct,drawDefinition:i})){let y=kp({drawSize:l.qualifyingDrawPositionsCount,stage:ct,drawDefinition:i});if(y.error)return y}if(f){let T=PS({qualifiersCount:f,drawDefinition:i,stage:et});if(T.error)return T}let g=t.drawSize??c;Object.assign(t,rt({drawSize:g,matchUpType:a,tieFormat:s}));let{matchUps:I,matchUpsMap:h}=re({drawDefinition:i});s&&I?.forEach(T=>{if(!u.includes(T.matchUpId)){let{tieMatchUps:y}=xa({tieFormat:s,matchUp:T,isMock:n});Object.assign(T,{tieMatchUps:y,matchUpType:a})}});let{inContextDrawMatchUps:S}=Ki({drawDefinition:i,matchUpsMap:h});return Ot({tournamentId:t.tournamentRecord?.tournamentId,drawDefinition:i}),{inContextDrawMatchUps:S,drawDefinition:i,matchUpsMap:h,...C,structures:m,matchUps:I,links:d}}function vc(t){let{removePriorValues:e,tournamentRecord:r,participantId:n,scaleItem:o}=t,i,s;if(!WO({scaleItem:o}))return{error:rp};if(n&&Array.isArray(r.participants)&&(s=r.participants.find(a=>a.participantId===n),s)){let a=jO({removePriorValues:e,participant:s,scaleItem:o});if(a.error)return a;i=!a.valueChanged;let{topics:c}=xr();c.includes(Xe)&&dt({topic:Xe,payload:{tournamentId:r.tournamentId,participants:[s]}})}return i&&{...C,info:ef,existingValue:o?.scaleValue}||s&&{...C,newValue:o?.scaleValue}||{error:Xt}}function eP(t){let{scaleItemsWithParticipantIds:e=[],removePriorValues:r,tournamentRecord:n,auditData:o,context:i}=t;if(!n)return{error:j};if(!n.participants)return{error:Ja};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(WO({scaleItem:l}))Array.isArray(a[d])||(a[d]=[]),a[d].push(l);else return{error:rp}}n.participants.forEach(m=>{let{participantId:d}=m||{};Array.isArray(a[d])&&a[d].forEach(l=>{jO({participant:m,scaleItem:l,removePriorValues:r}),c.push(m),s++})});let u=s?void 0:Fs,{topics:p}=xr();if(p.includes(Xe)&&s&&dt({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:bf,itemValue:l};if(f&&(g.itemSubTypes=f),d||m){let{drawDefinition:I,event:h}=He({tournamentRecord:n,eventId:m,drawId:d});d&&Tg({drawDefinition:I,timeItem:g}),m&&Xi({event:h,timeItem:g})}else bc({tournamentRecord:n,timeItem:g})}}return o&&p.includes(Ei)&&dt({topic:Ei,payload:o}),rt({...C,modificationsApplied:s,info:u})}function WO({scaleItem:t}){let e=t&&Object.keys(t),r=["scaleType","eventType","scaleName"];return!!(r.filter(o=>e?.includes(o)).length===r.length)}function jO({removePriorValues:t,participant:e,scaleItem:r}){if(!e)return{error:Gi};let n=r&&Object.keys(r),o=["scaleType","eventType","scaleName"];if(!(o.filter(p=>n.includes(p)&&r[p]).length===o.length))return{error:rp};let s=new Date().toISOString();e.timeItems||(e.timeItems=[]);let{scaleItem:a}=Uo({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=[Ti,p,m,d].join("."),f=rt({itemValue:r.scaleValue,itemDate:r.scaleDate,createdAt:s,itemType:l});r.scaleId&&(f.itemSubTypes=[r.scaleId]),t&&(e.timeItems=e.timeItems.filter(g=>g.itemType!==l)),e.timeItems.push(f)}return{...C,valueChanged:u,newValue:r.scaleValue}}function Lg(t){let{tournamentRecord:e,modifiedScaleValues:r,removePriorValues:n}=t,o=nt(t,[{[Re]:!0},{modifiedScaleValues:!0,[ar]:zr}]);if(o.error)return o;for(let i in r){let s=vc({scaleItem:r[i],removePriorValues:n,tournamentRecord:e,participantId:i});if(s.error)return s}return{...C}}function Oc(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}=Ao({tournamentRecords:o,tournamentRecord:e,participantId:n});return i?{...Uo({participant:i,scaleAttributes:r}),tournamentId:s}:{error:Xt}}var FG=(t=0)=>250/Math.pow(t+5,.4),kG=()=>1;function GG(t=3,e=2){let r=t/e;return isNaN(r)?Fd.kDefault():r}var Fd={nSpread:400,diffThreshold:.125,kCalc:FG,kMultiplier:GG,kDefault:kG};function dT(t){let{winnerRating:e,loserRating:r}=t,{ratings:n=ve,winnerCountables:o=1,loserCountables:i=0,ratingType:s=zn,maxCountables:a,countables:c}=t||{},u=n?.[s];if(!u)return{error:ot};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=(x,F)=>parseFloat(F)>=Math.min(...x)&&parseFloat(F)<=Math.max(...x);(!f(p,e)||!f(p,r))&&(f(p,e)||(e=u.defaultInitialization),f(p,r)||(r=u.defaultInitialization));let g=bu({targetRange:ve[zn].range,sourceRange:l,value:m?p[0]-e:e}),I=bu({targetRange:ve[zn].range,sourceRange:l,value:m?p[0]-r:r}),h=(x,F)=>1/(1+Math.pow(10,(F-x)/Fd.nSpread)),S=h(g,I),T=h(I,g),y=Fd.kCalc(o),D=Fd.kCalc(i),U=Fd.kMultiplier(a,c),A=g+U*y*(1-S),E=I+U*D*(0-T),M=bu({sourceRange:ve[zn].range,value:A,targetRange:l}),P=bu({sourceRange:ve[zn].range,value:E,targetRange:l}),N=m?p[0]-M:M,R=parseFloat(N.toFixed(d)),b=m?p[0]-P:P,v=parseFloat(b.toFixed(d)),O=Math.max(...p)?Math.abs(e-r)/Math.max(...p):0;return(M>P&&O>Fd.diffThreshold||R<0||v<0)&&(R=e,v=r),{newWinnerRating:R,newLoserRating:v}}var YO=t=>t?.reduce((e,r)=>(r.winningSide&&(e[r.winningSide-1]+=1),e),[0,0])||[0,0];function lT(t){let e=nt(t,[{[Re]:!0},{matchUpIds:!0,[ar]:ir,[ho]:ns},{ratingType:!1,[sr]:S=>ve[S]}]);if(e.error)return e;let{updateParticipantRatings:r,removePriorValues:n=!0,tournamentRecord:o,ratingType:i=zn,refreshDynamic:s,considerGames:a,drawDefinition:c,matchUpIds:u,asDynamic:p}=t,m=ve[i],{accessor:d}=m,l={},f=(t.matchUps||s&&Je({drawDefinition:c,tournamentRecord:o,inContext:!0,matchUpFilters:{matchUpStatuses:ie}}).matchUps||fe({matchUpFilters:{matchUpIds:u,matchUpStatuses:ie},tournamentRecord:o,inContext:!0}).matchUps)??[],g=`${i}.${Lm}`,I=p?g:i;f.sort(vi);for(let S of f){let{endDate:T,matchUpFormat:y,score:D,sides:U,winningSide:A}=S,E=S.matchUpType,M={eventType:E,scaleName:i,scaleType:Si},P={scaleName:g,eventType:E,scaleType:Si},N=Object.assign({},...(U??[]).map(B=>{let{sideNumber:G,participant:W}=B;return G&&{[G]:[W?.participantId,...W?.individualParticipantIds??[]].filter(Boolean).flat()}})),R=Object.assign({},...Object.values(N).flat().map(B=>{let G=l[B],H=!s||G?Oc({scaleAttributes:P,tournamentRecord:o,participantId:B}).scaleItem:void 0,q=Oc({tournamentRecord:o,scaleAttributes:M,participantId:B}).scaleItem,$=d?{[d]:void 0}:void 0;return B&&{[B]:H??q??{scaleName:I,eventType:E,scaleDate:T,scaleType:Si,scaleValue:$}}})),b=y?rr(y):{},v=b?.bestOf||1,O=b?.setsTo||1,x=a?v&O:v,F=D?.sets&&YO(D.sets)||A===1&&[1,0]||[0,1],L=A?N[A]:[],w=A?N[3-A]:[];for(let B of L){let G=R[B]?.scaleValue,W=typeof G=="object"?G[d]:G;for(let H of w){let q=R[H]?.scaleValue,$=typeof q=="object"?q[d]:q,V=A?F[A]:[0,0],K=A?F[3-A]:[0,0],{newWinnerRating:z,newLoserRating:Y}=dT({winnerCountables:V,loserCountables:K,maxCountables:x,winnerRating:W,loserRating:$,ratingType:i}),Z=d?{...G,[d]:z}:z,Q=d?{...q,[d]:Y}:Y;R[B].scaleValue=Z,R[H].scaleValue=Q,R[B].scaleName=I,R[H].scaleName=I}}Object.assign(l,R),r&&Lg({tournamentRecord:o,modifiedScaleValues:l,removePriorValues:n})}let h=f.map(({matchUpId:S})=>S);return{...C,modifiedScaleValues:l,outputScaleName:I,processedMatchUpIds:h}}function Gu(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=Od(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:k,info:"matchUpsCount error",context:{roundMatchUpsCount:d}}});if(a&&!Array.isArray(a)||c&&!ft(c)||e&&!Array.isArray(e)||!a&&!c)return{error:k,info:"matchUpsCount or pairings error"};if(c&&t.restrictMatchUpsCount!==!1&&c>32)return{error:k,info:"matchUpsCount must be less than 33"};if(n&&!t.ignoreLastRoundNumber&&n-1>(p||0))return{error:k,info:"roundNumber error"};let l=n??(o&&(p??0)+1||p||1);a=a??tt(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((U,A)=>rt({sideNumber:A+1,participantId:U})),D=e[h]??f(h)??Nt();return{roundNumber:l,matchUpStatus:zt,matchUpId:D,sides:y}});if(g?.length){let I=We({drawDefinition:r,event:s})?.tieFormat;I&&g.forEach(h=>{let{tieMatchUps:S}=xa({tieFormat:I,matchUp:h,isMock:i});Object.assign(h,{tieMatchUps:S,matchUpType:Ht})})}return{roundNumber:l,matchUpsCount:g?.length??0,matchUps:g,...C}}function $O({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=qO({actorsCount:s.length,valueSortedPairings:e,pairingValueMap:i,deltaObjects:o,valueObjects:n}),u=[rP(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 D=Fa(S,y.opponent);if(!I.includes(D)){let U=qO({stipulated:[[S,y.opponent]],actorsCount:s.length,valueSortedPairings:e,pairingValueMap:i,deltaObjects:o,valueObjects:n});if(!u.includes(rP(U))){u.push(rP(U)),a.push(U);let{maxDelta:A,value:E}=U;A<m.maxDelta&&(m=U),(E<p||E===p&&Math.round(Math.random()))&&(p=E),I.push(D),d+=1}}}),a=a.filter(y=>Math.abs(y.value-p)<5)}),a.sort((S,T)=>S.maxDiff-T.maxDiff);let h=$r(a);return{candidatesCount:d,deltaCandidate:m,maxIterations:t,iterations:l,candidate:h}}function rP(t){return t.participantIdPairings.map(({participantIds:e})=>e.sort().join("|")).sort().join("/")}function qO({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=Fa(l,f),I=r[g];a.push({participantIds:d,value:I}),c+=r[g]}),Ae(t,i).map(d=>lr(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=Fa(f,g),h=n[I];return h>d?h:d},0),m=a.reduce((d,l)=>{let[f,g]=l.participantIds,I=Fa(f,g),h=o[I];return h>d?h:d},0);return{value:c,participantIdPairings:a,maxDelta:p,maxDiff:m}}function Fa(t,e){return[t,e].sort(Uu).join("|")}function nP({participantIds:t}){let e={},r=[];t.forEach(o=>{e[o]=t.filter(i=>i!==o),e[o].forEach(i=>{let s=Fa(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 KO({matchUps:t}){let e=[];for(let r of t){let n=r.sides.map(ht);if(n.length===2){let[o,i]=n,s=Fa(o,i);e.includes(s)||e.push(s)}}return{encounters:e}}function zO({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=Fa(o,i);return{opponent:i,value:e[s]}}return{pairingValues:r}}var VG=0;function QO({tournamentParticipants:t,adHocRatings:e,eventType:r,scaleName:n,pairing:o}){let i=ve[n]?.defaultInitialization??VG;return o.split("|").map(s=>{if(r===Br){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 XO(t){let{tournamentParticipants:e,adHocRatings:r={},possiblePairings:n,uniquePairings:o,maxIterations:i,minimizeDelta:s,deltaObjects:a,valueObjects:c,eventType:u,scaleName:p,salted:m}=t;o.forEach(T=>{let y=QO({tournamentParticipants:e,adHocRatings:r,scaleName:p,eventType:u,pairing:T}),D=typeof m=="number"&&m||.5,U=m&&(Math.round(Math.random())?D:D*-1)||0,A=Math.abs(y[0]-y[1])+U,E=Math.abs(y[0]-y[1]);a[T]=E,c[T]||(c[T]=0),c[T]+=A?Math.pow(A,2):0});let d=o.map(T=>({pairing:T,value:c[T]})).sort((T,y)=>T.value-y.value),{pairingValues:l}=zO({possiblePairings:n,valueObjects:c}),{candidate:f,candidatesCount:g,deltaCandidate:I,iterations:h}=$O({valueSortedPairings:d,maxIterations:i,pairingValues:l,deltaObjects:a,valueObjects:c}),{participantIdPairings:S}=s?I:f;return{participantIdPairings:S,candidatesCount:g,deltaCandidate:I,iterations:h,candidate:f}}var BG=100,HG=100,WG=4e3;function kd(t){let{encounterValue:e=BG,sameTeamValue:r=HG,maxIterations:n=WG,updateParticipantRatings:o,generateMatchUps:i=!0,ignoreLastRoundNumber:s,iterationMatchUps:a,tournamentRecord:c,dynamicRatings:u,refreshDynamic:p,participantIds:m,drawDefinition:d,roundNumber:l,structureId:f,matchUpIds:g,eventType:I,scaleName:h,idPrefix:S,isMock:T,salted:y,event:D}=t;if(!d)return{error:X};if(!t.structure&&!f)return{error:Lt};let U=t.structure||at({drawDefinition:d,structureId:f}).structure;if(!It(U))return{error:di};if(!m?.length)return{error:No};let A=[...a??[],...U?.matchUps??[]],{encounters:E}=KO({matchUps:A}),M=c?.participants??[],P={};if(u){let V=pt(U?.matchUps?U.matchUps.map(({roundNumber:z})=>z):[]),K=Math.max(...V,0);if(K){let z=U?.matchUps?.filter(({roundNumber:Z})=>Z===K).map(({matchUpId:Z})=>Z),Y=lT({ratingType:h??D?.category?.ratingType,updateParticipantRatings:o,tournamentRecord:c,asDynamic:!0,refreshDynamic:p,drawDefinition:d,matchUpIds:z});if(Y.error)return Y;Y.modifiedScaleValues&&(P=Y.modifiedScaleValues)}}let{valueObjects:N}=jG({tournamentParticipants:M,encounterValue:e,sameTeamValue:r,encounters:E}),{uniquePairings:R,possiblePairings:b,deltaObjects:v}=nP({participantIds:m}),O=Object.values(P).length?P:t.adHocRatings,x={tournamentParticipants:M,possiblePairings:b,participantIds:m,uniquePairings:R,drawDefinition:d,maxIterations:n,adHocRatings:O,deltaObjects:v,valueObjects:N,eventType:I,scaleName:h,structure:U,salted:y},{candidatesCount:F,participantIdPairings:L,deltaCandidate:w,iterations:B,candidate:G}=XO(x);if(!F)return{error:np};let W,H;if(i){let V=Gu({structureId:U?.structureId,ignoreLastRoundNumber:s,participantIdPairings:L,newRound:!0,drawDefinition:d,roundNumber:l,matchUpIds:g,idPrefix:S,isMock:T,event:D});if(V.error)return V;W=V.roundNumber,H=V.matchUps}let{maxDelta:q,maxDiff:$}=G;return{roundNumber:W,participantIdPairings:L,modifiedScaleValues:P,candidatesCount:F,deltaCandidate:w,...C,iterations:B,matchUps:H,maxDelta:q,maxDiff:$}}function jG({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===Ft);if(i)for(let s of i){let a=s.individualParticipantIds??[],{uniquePairings:c}=nP({participantIds:a});for(let u of c)o[u]||(o[u]=0),o[u]+=n}return{valueObjects:o}}function fT(t){let{drawType:e=go,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=Be,d=Ni({stageSequence:1,drawDefinition:p,stage:m}),l=[Un,Zc,Io].includes(e)?d.length:os(d.length);if(!i&&e===Ia&&d.length<2||e===Un&&d.length<3)return{error:Ju};let{tieFormat:f,matchUpType:g}=t;if(f){let R=mr({tieFormat:f});if(R.error)return R}f=Ze(f??We({drawDefinition:p})?.tieFormat),g=g??p.matchUpType??Bt;let{structures:I}=ln({stageSequence:1,drawDefinition:p,stage:m});if(I.length>1)return{error:zA};if(I?.[0]?.matchUps?.length)return{error:nf};let S=I?.[0]?.structureId;Object.assign(t,rt({structureName:t.structureName??Ye(Be),structureId:S,matchUpType:g,tieFormat:f,drawSize:l,stage:m}));let T=mT(t);if(T.error)return T;let y=T.generators[e];if(!y)return{error:wl};let D=y?.();if(D.error)return D;let{structures:U,links:A}=D,E=U.map(R=>Et({structure:R}).matchUps).flat();f&&E.forEach(R=>{let{tieMatchUps:b}=xa({matchUp:R,tieFormat:f,isMock:c});Object.assign(R,{tieMatchUps:b,matchUpType:g})}),(!n||!r)&&(p=J(p,!1,!0)),p.links||(p.links=[]),A.length&&p.links.push(...A);let M=U.map(({structureId:R})=>R);p.structures||(p.structures=[]);let P=p.structures.map(({structureId:R})=>R);p.structures=p.structures.map(R=>M.includes(R.structureId)?U.find(({structureId:b})=>b===R.structureId):R);let N=U.filter(({structureId:R})=>!P.includes(R));return N.length&&p.structures.push(...N),s&&Uc({seedingProfile:t.seedingProfile,applyPositioning:n,tournamentRecord:o,drawDefinition:p,structureId:S,placeByes:a,drawSize:l,event:u}),r&&Ot({drawDefinition:p}),{links:A,structures:U,...C}}var Wg={};Qt(Wg,{addGame:()=>pP,addPoint:()=>uP,addSet:()=>dP,addShot:()=>mP,analyzeScore:()=>Vg,analyzeSet:()=>Hu,calculateHistoryScore:()=>sP,checkScoreHasValue:()=>me,checkSetIsComplete:()=>zp,clearHistory:()=>cP,generate:()=>iP,generateScoreString:()=>jo,generateTieMatchUpScore:()=>Cc,getSetComplement:()=>Hg,getTiebreakComplement:()=>Zp,helpers:()=>HP,isValidMatchUpFormat:()=>Ar,keyValueScore:()=>LP,mutate:()=>IP,parseMatchUpFormat:()=>rr,parseScoreString:()=>Yd,query:()=>WP,redo:()=>lP,reverseScore:()=>oP,setServingSide:()=>aP,stringifyMatchUpFormat:()=>jp,tidyScore:()=>BP,umo:()=>gP,undo:()=>fP,validateScore:()=>Bg,validateTieFormat:()=>mr});var iP={};Qt(iP,{generateScoreString:()=>jo,generateTieMatchUpScore:()=>Cc,reverseScore:()=>oP});function jo(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:ot,info:"missing sets"};let u=i&&rr(i),{bestOf:p,finalSetFormat:m,setFormat:d}=u??{},f=n||!(!e||!a||a===1),g=r?YG({matchUpStatus:o}):"",I=c?.sort(qG).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,D=w=>Jt(w?.side1Score)||Jt(w?.side2Score),U=w=>Jt(w?.side1TiebreakScore)||Jt(w?.side2TiebreakScore),A=y?.tiebreakSet||!D(S)&&U(S),{side1Score:E,side2Score:M,side1TiebreakScore:P,side2TiebreakScore:N}=S,R=P||(Jt(P)||s?0:""),b=N||(Jt(N)||s?0:"");if(A)return`[${(f?[b,R]:[R,b]).join("-")}]`;let v=Math.min(R,b),O=v?`(${v})`:"",x=E||(Jt(E)||s?0:""),F=M||(Jt(M)||s?0:""),L=f?`${[F,x].join("-")}${O}`:`${[x,F].join("-")}${O}`;return["-"," "].includes(L)&&(L=""),L}}function YG({matchUpStatus:t}){let e={[Qe]:"RET",[vt]:"WO",[Ce]:"DF/DF",[he]:"WO/WO",[as]:"SUS",[Mr]:"ABN",[Mt]:"DEF",[pu]:"DR"};return t&&e[t]||""}function qG(t,e){return t.setNumber-e.setNumber}function oP(t){if(!t?.score)return{error:ot};let{sets:e}=t.score,r=e.map(i=>{let{side1TiebreakScore:s,side2TiebreakScore:a,winningSide:c,side1Score:u,side2Score:p,setNumber:m}=i;return rt({winningSide:c?3-c:void 0,side1TiebreakScore:a,side2TiebreakScore:s,side1Score:p,side2Score:u,setNumber:m})}),n=jo({sets:r}),o=jo({sets:r,reversed:!0});return{reversedScore:{sets:r,scoreStringSide1:n,scoreStringSide2:o},...C}}var IP={};Qt(IP,{addGame:()=>pP,addPoint:()=>uP,addSet:()=>dP,addShot:()=>mP,calculateHistoryScore:()=>sP,clearHistory:()=>cP,redo:()=>lP,setServingSide:()=>aP,umo:()=>gP,undo:()=>fP});function Yo({matchUp:t}){let{extension:e}=mt({name:jm,element:t});if(!e)return{error:Pe};let{history:r=[],undoHistory:n=[]}=e.value;return{history:r,undoHistory:n,...C}}function sP(t){if(!t)return{error:ot};let{matchUp:e,updateScore:r}=t;if(!e)return{error:dr};let n=Yo({matchUp:e})?.history||[];if(!Array.isArray(n))return{error:k,info:"history is not an array"};let{matchUpFormat:o}=e;if(!o)return{error:Bl};if(!Ar({matchUpFormat:o}))return{error:Vl};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:[]}),D=()=>({winningSide:void 0,side1Score:"",side2Score:"",shots:[]}),U=D(),A=y(),E=T(),M=0;for(let P of n){M+=1,I=p.sets.length+1===s;let N=I&&a?a:c,{tiebreakAt:R,setTo:b,NoAD:v,tiebbreakFormat:O}=N,x=E.side1Score===R&&E.side1Score===E.side2Score,F=!!N.tiebreakSet,L=F?N.tiebreakSet:O,{tiebreakTo:w,NoAD:B}=L||{},G=()=>{d=void 0,l=[0,0],f=3-f,E.side1TiebreakScore=0,E.side2TiebreakScore=0,E.side1PointScore="",E.side2PointScore="",h=0},W=$=>{E.winningSide=$;let{s:V,...K}=E;p.sets.push(K),U=D(),A=y(),E=T(),G()},H=$=>{A.winningSide=$;let{g:V,...K}=A;E.games.push(K),U=D(),A=y(),G();let z=`side${$}Score`;E[z]+=1},q=$=>{U.winningSide=$;let{p:V,...K}=U;A.points.push(K),U=D(),h=0;let z=()=>l.reduce((st,St)=>st+St)%4/4>.5?f:3-f,Y=$-1;if(x||F){l[Y]+=1,d=z(),E[`side${$}TiebreakScore`]=l[Y],E[`side${3-$}TiebreakScore`]=l[1-Y];let Z=B?1:2;if(l[Y]>=w&&l[Y]>=l[1-Y]+Z)return H($),{gameCompleted:!0}}else if(l[1-Y]===4&&l[Y]===3?l[1-Y]-=1:l[Y]+=1,E.side1PointScore=u[l[0]],E.side2PointScore=u[l[1]],l[Y]===5||l[Y]===4&&l[1-Y]<3||v&&l[Y]===4)return H($),{gameCompleted:!0}};if(S(P.srv)&&(f=P.srv),["p","s","g","o"].includes(P.u)&&m.push(P.u),P.shotOutcome&&(U.shots.push(P),P.shotType==="SERVE"&&["OUT","NET"].includes(P.shotOutcome)&&(h+=1),h===2)){let V=3-f;q(V)}if(S(P.p)||ft(P.pointNumber)){let $=P.winningSide||P.p;if(q($)?.gameCompleted)continue}if(S(P.g)||ft(P.gameNumber)){let $=P.winningSide||P.g;A.winningSide=$;let V=`side${$}Score`,K=`side${3-$}Score`;if(m.length&&(m.includes("p"),m=[]),H($),E[V]===b&&E[V]-E[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 M!==n.length&&console.log({error:"Match completed with excess history"}),(E.side1Score||E.side2Score||E.games.length||E.side1TiebreakScore||E.side2TiebreakScore)&&p.sets.push(E),p.scoreStringSide1=jo({...p,matchUpFormat:o}),p.scoreStringSide2=jo({...p,matchUpFormat:o,reversed:!0}),f=d||f,r&&(e.score=p),{...C,servingSide:f,score:p}}function qo({undoHistory:t,history:e,matchUp:r}){return At({element:r,extension:{value:{history:e,undoHistory:t},name:jm}})}function aP({matchUp:t,sideNumber:e}){if(![1,2].includes(e))return{error:Hl};let{history:r=[]}=Yo({matchUp:t});return r.push({srv:e}),qo({matchUp:t,history:r})}function cP({matchUp:t}){return qo({matchUp:t})}function uP({matchUp:t,point:e}){if(!e||!t)return{error:ot};if(typeof e!="object")return{error:k,context:{point:e}};let{history:r=[]}=Yo({matchUp:t});return r.push(e),qo({matchUp:t,history:r})}function pP({matchUp:t,game:e}){if(typeof e!="object")return{error:k,context:{game:e}};let{history:r=[]}=Yo({matchUp:t});return r.push(e),qo({matchUp:t,history:r})}function mP({matchUp:t,shot:e}){if(typeof e!="object")return{error:ot};let{history:r=[]}=Yo({matchUp:t});return r.push(e),qo({matchUp:t,history:r})}function dP({matchUp:t,set:e}){if(typeof e!="object")return{error:ot};let{history:r=[]}=Yo({matchUp:t});return r.push(e),qo({matchUp:t,history:r})}function lP({matchUp:t}){let{history:e=[],undoHistory:r=[]}=Yo({matchUp:t});return r.length&&e.push(r.pop()),qo({matchUp:t,history:e,undoHistory:r})}function fP({matchUp:t}){let{history:e=[],undoHistory:r=[]}=Yo({matchUp:t});return r.push(e.pop()),qo({matchUp:t,history:e,undoHistory:r})}var gP={};var HP={};Qt(HP,{keyValueScore:()=>LP,parseMatchUpFormat:()=>rr,stringifyMatchUpFormat:()=>jp,tidyScore:()=>BP});var na=" ",gT="DEF",JO="COMPLETED",hP="WO",$G="WO/WO",SP="ABN",TP="SUS",yP="RET",AP="INT",IT=[yP,gT,hP,$G,SP,TP,AP];var hT="DEFAULTED";var EP="WALKOVER";var ST="ABANDONED",TT="SUSPENDED",UP="RETIRED",yT="INTERRUPTED";var ZO=[UP,hT,EP],KG="Enter Score",Ds="()",Ps="[]",DP=["up","left","shift+tab"],PP=["enter","down","tab","right"],Gd="backspace",NP="r",MP="s",RP="a",CP="d",bP="w",vP="i",Vd=[NP,CP,bP,RP,MP,vP],$p="space",AT=["[","("],Bd=[...DP,...PP,$p,"]"],t_="-",zG="/",oa=t_,ci=t_,OP=[zG],e_=0,QG=["=","+","num_1","num_2","shift+=","shift+-"],ra=["0","1","2","3","4","5","6","7","8","9"].concat(Vd),r_=ra.map(t=>`shift+${t}`),_P=[oa,Gd].concat(Bd,OP),xP=[ra,r_,_P].join(","),XG=[xP,DP,PP,QG].join(","),QMt=[].concat(...ra,...ra,..._P,...ra,...ra,...ra,...ra,...ra,...ra),n_={OUTCOMEKEYS:Vd,SIDE1KEYS:ra,SIDE2KEYS:r_,MODIFIERS:_P,PROMPT:KG,MOVEUP:DP,MOVEDOWN:PP,HOTKEYS:XG};function Kp({scoreString:t,lowSide:e,outcome:r}){if({scoreString:t}=o_({scoreString:t}),e===2){let o=(t&&t[t.length-1])!==na?na:"";return t+o+r}else return r+na+t}function o_({scoreString:t}){if(!t)return{scoreString:""};let e=!1;for(let r of IT){let n=t?.indexOf(r);n===0?t=t.slice(r.length+1).trim()+na:n>0&&(t=t.slice(0,n)),n>=0&&(e=!0)}return t?.trim()||(t=""),{scoreString:t,removed:e}}function Fg({analysis:t,scoreString:e,sets:r,lowSide:n}){let o,i;if(!e)return{scoreString:e,sets:r};let{scoreString:s,removed:a}=o_({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}=Vu({brackets:Ps,scoreString:e}),f=JG(e);if(f>=0){o=e.slice(0,f);let{isTiebreakEntry:g}=Vu({brackets:Ds,scoreString:o}),{lastOpenBracketIndex:I,isTiebreakEntry:h}=Vu({brackets:Ps,scoreString:o}),S=o&&o[o.length-1].trim(),T=o&&!isNaN(S),y=t.isIncompleteSetScore;if(l&&h){let U=o.slice(I+1).split(ci),A=U?.length>0&&U[0]!==void 0&&!isNaN(parseInt(U[0]))&&parseInt(U[0])||void 0,E=U?.length>1&&U[1]!==void 0&&parseInt(U[1])||void 0,M=[A,E];if(E){let P=n===1?1:0;M[P]=(M?.[1-P]||0)+(d?1:2),(M[P]||0)<m&&(M[P]=m),o=e.slice(0,I+1),o+=M.join(ci)}else A!==void 0?(o=e.slice(0,I+1),o+=A):(o=e.slice(0,I),y=!0);c.side1TiebreakScore=M[0]||0,c.side2TiebreakScore=M[1]||0}if(o.length||(o=void 0),y){let D=c.side1Score?.toString();if(D){let U=D?.slice(0,D.length-1);c.side1Score=!isNaN(U)&&parseInt(U)||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 D=c.side2Score?.toString(),U=c.side1Score?.toString();if(!t.isTiebreakEntry&&!t.isMatchTiebreak)if(c.side2Score){let A=D?.slice(0,D.length-1);c.side2Score=!isNaN(A)&&parseInt(A)||void 0}else{let A=U?.slice(0,U.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 Vu({brackets:t=Ds,scoreString:e}){if(!e)return{};let[r,n]=t.split(""),o=e.split(""),i=Math.max(...lo(r,o)),s=Math.max(...lo(n,o));return{isTiebreakEntry:i>s,lastOpenBracketIndex:i}}function i_({scoreString:t}){if(!t)return!1;let e=t&&t[t.length-1].trim(),r=t&&!isNaN(e),[n,o]=Ps.split(""),i=t.split(""),s=Math.max(...lo(n,i)),a=Math.max(...lo(o,i)),c=Math.max(...lo(ci,i));return r&&s>a&&c>s}function JG(t){return t.split("").reduce((n,o,i)=>(o.match(/\d+/g)&&n.push(i),n),[]).pop()}function ET(t){let{lowValue:e=0,NoAD:r=!1,tiebreakTo:n}=t||{},o=r?1:2;return e+1>=n?e+o:parseInt(n)}function wP({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 ZO.includes(e)&&r&&(c=r),{matchUpWinningSide:c}}function zp({ignoreTiebreak:t=!1,matchUpScoringFormat:e,matchUpFormat:r,isTiebreakSet:n,isDecidingSet:o,set:i}){if(!i)return{error:ot,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=Qp({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 Qp({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 Hd({analysis:t,set:e}){let r=Qp({set:e}),{isDecidingSet:n,isTiebreakSet:o,matchUpScoringFormat:i}=t;return zp({matchUpScoringFormat:i,isDecidingSet:n,isTiebreakSet:o,set:e})&&r}function s_({analysis:t,scoreString:e,sets:r,value:n}){let o;if(!r?.length)return{sets:[]};let i=r[r.length-1];n=ut(n);let{validSide2Score:s,requiresTiebreak:a}=ZG({analysis:t,set:i,value:n});if(s){o=!0,e=(e||"")+n,i.side2Score=n;let c=Hd({analysis:t,set:r[r.length-1]});if(i.winningSide=c||void 0,a){let u=Ds.split("")[0];e+=u}else t.isDecidingSet||(e+=na)}return{sets:r,scoreString:e,updated:o}}function ZG({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 UT({lowSide:t,value:e,sets:r,scoreString:n,winningSide:o,matchUpStatus:i}){let s;return e===NP?n?(s=!0,n=Kp({scoreString:n,lowSide:t,outcome:yP}),o=t===2?1:2,i=UP):(s=!0,n=Kp({scoreString:n,lowSide:t,outcome:gT}),o=t===2?1:2,i=hT):e===CP?(s=!0,n=Kp({scoreString:n,lowSide:t,outcome:gT}),o=t===2?1:2,i=hT):e===bP?(s=!0,r=[],n=hP,o=t===2?1:2,i=EP):e===MP&&n?(s=!0,n=Kp({scoreString:n,lowSide:t,outcome:TP}),i=TT,o=void 0):e===RP?(s=!0,n=Kp({scoreString:n,lowSide:t,outcome:SP}),i=ST,o=void 0):e===vP&&n&&(s=!0,n=Kp({scoreString:n,lowSide:t,outcome:AP}),i=yT,o=void 0),{updated:s,sets:r,scoreString:n,matchUpStatus:i,winningSide:o}}function a_(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!==Gd&&(e=[{setNumber:1}]);let m=e.length-1;if(Vd.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}=UT({lowSide:a,value:c,sets:e,scoreString:n,matchUpStatus:i,winningSide:o}))}else if(c===Gd){if({scoreString:n,sets:e,outcomeRemoved:p}=Fg({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===oa&&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=ut((e[m].side1Score||0).toString()+c).toString().slice(0,2);e[m].side1Score=ut(l),d=e[m].side1Score.toString(),u=!0}else{let l=ut((e[m].side2Score||0).toString()+c).toString().slice(0,2);e[m].side2Score=ut(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 c_({analysis:t,auto:e,lowSide:r,scoreString:n="",sets:o,value:i}){let s,a,{tiebreakSet:{tiebreakTo:c,NoAD:u}}=t.setFormat,[p]=Ps.split("");if(t.isMatchTiebreakEntry||(n+=p),o[t.setNumber-1]){let{lastOpenBracketIndex:d}=Vu({brackets:Ps,scoreString:n}),f=(n.slice((d??0)+1)+(e?"":i)).split(ci);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=>ut(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(ci),s=!0}else{let I=[f[0]||0,f[1]||0].map(S=>ut(S)),h=o[o.length-1];h.side1TiebreakScore=I[0],h.side2TiebreakScore=I[1],n+=i,s=!0}}else{let d=ET({lowValue:ut(i||0),tiebreakTo:c,NoAD:u}),l=[ut(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(ci),s=!0}return{info:a,scoreString:n,sets:o,updated:s}}function u_({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=Ds.split("")[0],d=u.join(oa)+(a?m:na);r=(r||"")+d;let l={side1Score:u[0],side2Score:u[1]},f=Hd({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 p_({matchUpFormat:t,scoreString:e,winningSide:r,value:n,sets:o}){let s=(o?.filter(H=>H?.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}=Vu({brackets:Ds,scoreString:e}),{isTiebreakEntry:f}=Vu({brackets:Ps,scoreString:e}),g=l||f,I=!!u.tiebreakSet,h=e?.[e.length-1]?.trim(),S=e&&!isNaN(h),T=!g&&h===oa,y=l&&AT.includes(h),D=f&&AT.includes(h),U=f&&h===ci,A=e?.split(""),[E]=Ps.split(""),M=A&&Math.max(...lo(E,A)),P=A&&Math.max(...lo(ci,A)),N=A&&P>M,R=o[o.length-1]?.winningSide,b=o?.length&&!R,v=IT.find(H=>e?.indexOf(H)>=0),O=!isNaN(n),x=n===$p,F=Bd.includes(n),L=e?.split("").find(H=>AT.includes(H)),w=F&&f&&!D&&(U||!i_({scoreString:e}));return{isTiebreakSetValue:I&&O,matchUpScoringFormat:a,setNumber:s,setFormat:u,matchTiebreakHasJoiner:N,isGameScoreEntry:b,isSpace:x,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:R,isInvalidSetTiebreakValue:x&&g&&y,isInvalidMatchTiebreakValue:w,isTiebreakEntry:g,isSetTiebreakEntry:l,isMatchTiebreakEntry:f,isIncompleteSetScore:T,isIncompleteSetTiebreak:y,isIncompleteMatchTiebreak:D,isPartialMatchTiebreakValue:U}}function LP(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(!xP.includes(r))return{updated:!1,info:"invalid key"};c&&(e=3-e);let{matchUpWinningSide:l}=wP({sets:o,winningSide:i,matchUpStatus:s,matchUpFormat:a});i=l;let f=p_({value:r,winningSide:i,scoreString:n,sets:o,matchUpFormat:a});if(OP.includes(r)&&(r=oa),f.hasOpener&&f.isTiebreakEntry&&!f.isTiebreakSet&&d&&ut(r)===0&&(f.isTiebreakCloser=!0),Bd.includes(r)&&f.hasOpener&&(r=""),Bd.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}=a_({analysis:f,lowSide:e,scoreString:n,sets:o,matchUpStatus:s,winningSide:i,value:r}));else if(Vd.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}=UT({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===Gd)p=!0,{scoreString:n,sets:o}=Fg({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===oa&&!f.isMatchTiebreakEntry)(!f.isSetTiebreakEntry||f.isSetTiebreakEntry&&!f.isNumericEnding)&&(p=!0,{scoreString:n,sets:o}=Fg({analysis:f,scoreString:n,sets:o,lowSide:e}),s=void 0);else if(r===ci&&f.isMatchTiebreakEntry&&!f.isSetTiebreakEntry)f.matchTiebreakHasJoiner?m="existing joiner":f.isNumericEnding&&(p=!0,n+=ci);else if([oa,ci].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}=s_({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?Ds:Ps,I=g.split("").reverse()[0],h=g.split("")[0],S=o[o.length-1],{tiebreakFormat:T}=f.setFormat,{tiebreakTo:y,NoAD:D}=T||{},U=Qp({set:S});if(!f.isTiebreakSet){let E=parseInt(n.split(h).reverse()[0]),M=ET({lowValue:E,tiebreakTo:y,NoAD:D});U===1?(S.side1TiebreakScore=M,S.side2TiebreakScore=E):(S.side1TiebreakScore=E,S.side2TiebreakScore=M)}n=(n||"")+I,f.isDecidingSet||(n+=na);let A=Hd({analysis:f,set:S});S.winningSide=A||void 0,p=!0}else if(f.isTiebreakSetValue)({info:m,scoreString:n,sets:o,updated:p}=c_({analysis:f,auto:u,lowSide:e,scoreString:n,sets:o,value:r}));else if(f.isSetTiebreakEntry){let[g]=Ds.split(""),I=Math.max(...lo(g,n.split(""))),h=n.slice(I+1),S=h&&ut(h)===e_,T=ut(h?h+r:r),{tiebreakFormat:y}=f.setFormat,{tiebreakTo:D,NoAD:U}=y||{};!S&&h.length<2?U&&T>D-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}=u_({analysis:f,lowSide:e,scoreString:n,value:ut(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}=wP({sets:o,winningSide:i,matchUpStatus:s,matchUpFormat:a});return i=g,g&&(!s||[zt,Pn].includes(s))?(s=JO,o=o.filter(I=>{let{side1Score:h,side2Score:S,side1TiebreakScore:T,side2TiebreakScore:y}=I;return h||S||T||y})):n&&!i&&![TT,ST,yT].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 Wd="\\d+-\\d+",Xp="\\d+-\\d+\\(\\d+\\)",kg="\\[\\d+-\\d+\\]",tV="\\d+-\\d+\\(\\d+-\\d+\\)",m_=new RegExp(`(${Wd}),`,"g"),d_=new RegExp(`(${Xp}),`,"g"),eV=[Wd,Xp,kg,tV],rV=["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"],nV=rV.map(t=>{let r=t.split("").map(n=>eV[n]).join(" ");return new RegExp(`^${r}$`)});function FP(t){return!t||nV.some(e=>e.test(t))}function l_(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 jd(t){return/^\(\d+\)$/.test(t)||/^\(\d+$/.test(t)}function f_(t){return/^\(\d+-\d+\)$/.test(t)||/^\[\d+-\d+\]$/.test(t)}function ka(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 Jp(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 kP(t){return t.length===2?t.split("").join("-"):([", ",",","/"," "].forEach(e=>t=t.split(e).join("-")),t=t.replace(/-{2,}/,"-"),t)}function g_(t){return t.startsWith("(")&&t.endsWith(")")}function I_({score:t,applied:e}){t=l_(t);let r=/\)(\d+)/g;if(r.test(t))for(let U of t.match(r)){let A=U.replace(")",") ");t=t.replace(U,A)}t=t.replace(/\)\//g,") / "),t=t.replace(/\/\)/g,")");let n=/\(([\d- ]+)\)/g,o=/\(([\d- ]+)\)/,i=t.match(n);for(let U of i||[]){let[A]=U.match(o).slice(1),E=A.replace(/ /g,"");t=t.replace(U,`(${E})`)}let s=/\(\(\d-\d\)\)/g;if(s.test(t)){let U=t.match(s);U.length&&U.forEach(A=>{let E=A.match(/\((\(\d-\d\))\)/).slice(1)[0];t=t.replace(A,E)})}if(s=/\(\((\d)\)\)/g,s.test(t)){let U=t.match(s);U.length&&U.forEach(A=>{let E=A.match(/\((\(\d\))\)/).slice(1)[0];t=t.replace(A,E)})}/(^|\s)6-,/.test(t)&&(t=t.replace(/(^|\s)6-,/g,"6-0,"));let a=new RegExp(/[-,]{2,}/g);t=t.replace(a,"-"),["- "," -"].forEach(U=>{let A=new RegExp(`(\\d+)${U}(\\d+)`,"g"),E=t.match(A);E&&E.forEach(M=>t=t.replace(M,M.split(U).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[E]=A.match(/\((\d+), \)/).slice(1);E.length===2?t=t.replace(A,`(${E})`):E.length===1&&E==="6"&&(t=t.replace(A,"(6-0)"))});let u=/\((\d+)\/\)/g;u.test(t)&&t.match(u).forEach(A=>{let[E]=A.match(/\((\d+)\/\)/).slice(1);E.length===2?t=t.replace(A,`(${E})`):E.length===1&&E==="6"?t=t.replace(A,"(6-0)"):t=t.replace(A,`(${E})`)});let p=/\d\/\d\/,/g;p.test(t)&&t.match(p).forEach(A=>{let[E]=A.match(/(\d\/\d)\/,/).slice(1);t=t.replace(A,`${E},`),e.push("slashComma")});let m=/\(\/(\d+)\)/g;m.test(t)&&t.match(m).forEach(A=>{let[E]=A.match(/\(\/(\d+)\)/).slice(1);E.length===2?t=t.replace(A,`(${E})`):E.length===1&&parseInt(E)<6?t=t.replace(A,`(6-${E})`):t=t.replace(A,`(${E})`)});let d,l,f,g,I,h=()=>{I=gr(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[U]=t.match(S).slice(1);t=t.replace(S,U+")")}if(I["("]===I[")"]&&I["("]>1){let U=t.split(")(").join(") (").split(" ");U.every(g_)?t=U.map(A=>{let E=A.slice(1,A.length-1);return E.length>2?E:A}).join(" "):t=U.join(" ")}h();let T=/[A-Za-z]+/.test(t),y=/\d+/.test(t);if(!T&&!y)return{score:""};if(/^\[.+\]$/.test(t)&&"()/,- ".split("").some(U=>I[U])&&(t=t.slice(1,t.length-1)),/^\(.+\)$/.test(t)&&I["("]===1&&I[")"]===1&&"[]/,".split("").some(U=>I[U]>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 U=[],A=0;for(let E of t.split("").reverse())E===")"&&(A?U.push("("):A+=1),E==="("&&(A-=1),U.push(E);U.reverse(),t=U.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 U="",A=0;for(let E of t.split(""))E==="("&&(A?U+=")":A+=1),E===")"&&(A-=1),U+=E;t=U}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 D=U=>{let A=U.indexOf("("),E=U.indexOf(")");return A>=0&&E>=0&&A<E};if(/^\([\d ]+.*[\d ]+\)$/.test(t)&&I["("]===I[")"]){let U=t.slice(1,t.length-1);D(U)&&(t=U,h())}return{score:t,applied:e}}function Bu(t){if(!/^[\d-]+(\(\d\))*$/.test(t))return t;let e=lo("-",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 h_({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(")")),[m_,d_].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(Bu).join(" "),{score:t,applied:e}}function S_({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(jd),i=0,s="";for(let d of o){let l=lo(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,D=[T,y].sort().reverse().join("-"),U=[f.join(" "),[D,d].join("")].join(" ");s+=U,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=>f_(d)&&"bracket"||ka(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=lo("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;!ka(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(kg).test(d)&&"super"||new RegExp(Xp).test(d)&&"tiebreak"||new RegExp(Wd).test(d)&&"standard"||"unknown";return u.push(g),g==="standard"&&f?d.match(l)[1]:d}).join(" "),{score:t}}function T_({score:t,applied:e}){for(let P of[".",","," ","/"]){let N=new RegExp(`^(\\d+)\\${P}(\\d+)$`);if(N.test(t)){let R=t.match(N).slice(1).map(v=>parseInt(v)),b=Math.abs(R[0]-R[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,N,R,b,v,O]=t.match(r).slice(1);t=t.replace(r,`${P}${N}-${R} ${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(N=>(i.test(N)&&(N=N.replace("("," (")),s.test(N)&&(N=N.replace(")",") ")),N)).join(" "),e.push("spaceConsiderationPatterns")});let c=Bu(t);c!==t&&(t=c,e.push("deDashMash"));let u=/^(\d)[-/,]+(\d{2})[-/,]+(\d)$/;if(u.test(t)){let[P,N,R]=t.match(u).slice(1),[b,v]=N.split("");t=`${P}-${b} ${v}-${R}`,e.push("smashSetPattern")}let p=/^(\d+)[ -](\d+)$/,m=/^([\d -]+)\/([\d -]+)$/;if(m.test(t)){let[P,N]=t.match(m).slice(1),R=P.trim(),b=N.trim();if(p.test(R)&&p.test(b)){let v=R.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,N]=t.match(d).slice(1),R=P.trim(),b=N.trim();if(p.test(R)&&p.test(b)){let v=R.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],N=P.slice(0,P.length-1).split(" ").join("-");t=t.replace(P,N),e.push("singleSetCommaSeparationPattern")}let f=0,g=/(\d+)-(\d{2})-(\d+)/;for(;g.test(t)&&f<3;){let[P,N,R]=t.match(g).slice(1),b=N.split(""),v=`${P}-${b[0]} ${b[1]}-${R}`;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(N=>{let R=N.match(P).slice(2)[0];t=t.replace(N,`7-6(${R}) `),e.push("floatingTiebreakPattern1")})}let S=t.match(/\d \d /);S?.forEach(P=>{let N=P.slice(0,P.length-1).split(" ").join("-");t=t.replace(P,N),e.push("spaceSeparatedSetPattern1")}),S=t.match(/ \d \d$/),S?.forEach(P=>{let N=" "+P.slice(1).split(" ").join("-");t=t.replace(P,N),e.push("spaceSeparatedSetPattern2")});let T=/^\d, *\d\/\d, *\d/;if(T.test(t)){let P=t.match(T)[0],N=P.split("/").map(R=>`(${R})`).join(" ")+" ";t=t.replace(P,N),e.push("slashCommaSetPattern")}let y=/\(6-\)/g;y.test(t)&&(t=t.replace(y,"(6-0)"),e.push("missingZeroPattern2"));let D=/(?<!-)(\d+)\/(\d+)(?!-)/g;if(D.test(t)){let P=t.match(D),N=/(?<!-)(\d+)\/(\d+)(?!-)/,R=t;P.forEach(b=>{let[v,O]=b.match(N).slice(1),x=`${v}-${O}`;R=R.replace(b,x)}),t=R,e.push("slashSetPattern")}let U=/(.*)\s(1\d)\s(\d+)$/;if(U.test(t)){let[P,N,R]=t.match(U).slice(1);P.replace(/\D/g,"").length>=4&&(t=P+` ${N}${R}`,e.push("spaceSeparatedSuperPattern"))}let A=/(^|\s)(\d+-\d+)\s(\d+)(\s|$)/g;for(let P of t.match(A)||[]){let[N,R,b,v]=P.match(/(^|\s)(\d+-\d+)\s(\d+)(\s|$)/).slice(1),[O,x]=R.split("-").map(L=>parseInt(L));Math.abs(O-x)===1&&(t=t.replace(P,`${N}${R}(${b})${v}`),e.push("spaceSeparatedSetPattern"))}let E=/\d-\d \(\d{1,2}\)(\s|$|,)/g;for(let P of t.match(E)||[]){let N=/(\d-\d) \((\d{1,2})\)(\s|$|,)/,[R,b,v]=P.match(N).slice(1),[O,x]=R.split("-").map(L=>parseInt(L));Math.abs(O-x)===1&&(t=t.replace(P,`${R}(${b})${v}`),e.push("floatingTiebreakPattern2"))}let M=/(^|\s)(\d \d)\(/g;for(let P of t.match(M)||[]){let N=/(^|\s)(\d \d)\(/,[R,b]=P.match(N).slice(1);t=t.replace(P,`${R}${b.split(" ").join("-")}(`),e.push("spacedTiebreakPattern")}return{score:t,applied:e}}function y_({score:t,matchUpStatus:e}){let r=t?.split(" ");t=r.map(a=>{if(a.endsWith("]")){let c=a.split("[");if(ka(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=Jp(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 ka(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 A_({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=kP(l),h=Bu(I);t=t.replace(m,`(${h})`).trim()}let i=new RegExp(/\[[\d,/ ]+\]/g);t.match(i)?.forEach(m=>{let d=kP(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(",")||jd(h)),f=d.every(h=>h.includes("/")||jd(h)),g=d.every(h=>h.includes("-")||jd(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(D=>parseInt(D.trim())),y=Math.min(...T);h==="set"?m+=`(${y}) `:m+=`[${T.join("-")}] `,h="tiebreak"}}),t=m.trim()}}let u=gr(t.split(""));u["("]===1&&u[")"]===1&&t.startsWith("(")&&t.endsWith(")")&&(t=t.slice(1,t.length-1),u["-"]===1&&ka(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 DT({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 Gg(t){let e=t.indexOf("1"),r=t.split(""),n=r.every(o=>!isNaN(o));if(n&&t.length===3&&e===0){let o=Jp(r,e);if(o)return o}if(n&&t.length===7&&e>3){let o=r.slice(4),i=Jp(o,e-4);if(i)return`${r[0]}-${r[1]} ${r[2]}-${r[3]} ${i}`}}function GP(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}=DT({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=Gg(e);u&&e!==u&&r.push("parsedSuperPattern"),e=u??e}else{let u=Ae(e.split(""),2).map(h=>h.join("")),p=u.map(h=>{let[S,T]=h.split("").map(U=>parseInt(U)),y=Math.abs(S-T),D=S>T?1:2;return y>1&&D||D*-1}),m=p.reduce((h,S)=>h>0&&S>0,1),d=gr(p),l=p.map(h=>Math.abs(h)),f=gr(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,D,U]=a,A=p.reduce((E,M,P)=>M<0?P:E,void 0);if(A===0){let E=Math.min(T,y);e=`${h}-${S}(${E}) ${D}-${U}`,r.push("chunkSplitTiebreak1")}else if(A===1){let E=Math.min(D,U);e=`${h}-${S} ${T}-${y}(${E})`,r.push("chunkSplitTiebreak2")}else e=`${h}-${S} ${T}-${y}`,r.push("chunkSplitTrimExtraneous")}}else if(a.length===8){let[h,S,T,y,D,U,A,E]=a;g||I?a[5]===1&&(g?e=`${h}-${S}(${T}) ${y}-${D} [${U}${A}-${E}]`:e=`${h}-${S} ${T}-${y}(${D}) [${U}${A}-${E}]`):(p[0],p[1])}}}return{score:e,applied:r,matchUpStatus:n}}function PT(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 E_({score:t,matchUpStatus:e,attributes:r}){let n=[],o,i=t.split(" "),s=i.length;t=i.map((p,m)=>{if(new RegExp(Xp).test(p)){let l=p.slice(3),f=p.slice(0,3),g=f.split("-");if(!ka(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=Bu(p);let d=new RegExp(`^${kg}$`).test(p)&&"super"||new RegExp(`^${Xp}$`).test(p)&&"tiebreak"||new RegExp(`^${Wd}$`).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(D=>parseInt(D)>h||m&&parseInt(D)<=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}=PT(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 U_({score:t}){let{setsTied:e,winningSide:r}=PT(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 oV({score:t}){return t=t?.toString().toLowerCase()||"",{score:t}}function iV({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 sV({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=Jp(r.split(""),n);return e.push("getSuper"),o}}else{let{score:o,applied:i}=GP({score:r,applied:[]});o!==r&&(r=o,e.push(...i))}}return r}).join(" "),{score:t,applied:e})}function aV({score:t,applied:e}){return typeof t!="string"?{score:t}:[3,4].includes(t.length)&&Gg(t)?{score:Gg(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 cV({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 uV({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 pV({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 mV({score:t}){return new RegExp(/-\d+\/\d+-/).test(t)&&(t=t.split("/").join(" ")),{score:t}}function dV({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 lV({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 fV({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 gV({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 D_={handleTiebreakSlashSeparation:lV,handleSetSlashSeparation:mV,punctuationAdjustments:I_,handleGameSeparation:dV,joinFloatingTiebreak:S_,handleBracketSpacing:h_,handleSpaceSeparator:fV,separateScoreBlocks:sV,matchKnownPatterns:T_,removeDanglingBits:pV,removeErroneous:aV,handleWalkover:cV,properTiebreak:y_,handleNumeric:GP,handleRetired:uV,containedSets:A_,sensibleSets:E_,stringScore:oV,superSquare:U_,setBuilder:DT,excisions:gV,replaceOh:iV};var VP={},IV=[],hV=["handleNumeric","handleWalkover","handleRetired","replaceOh","stringScore","punctuationAdjustments","excisions","handleSpaceSeparator","matchKnownPatterns","removeDanglingBits","handleBracketSpacing","matchKnownPatterns","containedSets","separateScoreBlocks","handleGameSeparation","removeErroneous","joinFloatingTiebreak","handleSetSlashSeparation","handleTiebreakSlashSeparation","properTiebreak","sensibleSets","superSquare"],SV=["handleNumeric","separateScoreBlocks","sensibleSets","superSquare"];function BP(t){if(!t.score)return{error:k};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=D_[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(hV);let g=FP(l);return g||(l=e.toString().replace(/\D/g,""),m?.removed&&(m.removed=void 0),f(SV),g=FP(l),g||(IV.push({score:l,fileName:o,sheetName:r}),l="")),p.forEach(I=>{VP[I]||(VP[I]=0),VP[I]+=1}),{matchUpStatus:u?.toUpperCase(),modifications:c,attributes:m,isValid:g,score:l}}var WP={};Qt(WP,{analyzeScore:()=>Vg,analyzeSet:()=>Hu,checkScoreHasValue:()=>me,checkSetIsComplete:()=>zp,getSetComplement:()=>Hg,getTiebreakComplement:()=>Zp,isValidMatchUpFormat:()=>Ar,parseScoreString:()=>Yd,validateScore:()=>Bg,validateTieFormat:()=>mr});function Vg({existingMatchUpStatus:t,matchUpFormat:e,matchUpStatus:r,winningSide:n,score:o}){let i=o?.sets??[],a=(i?.filter(A=>A?.winningSide)||[]).reduce((A,E)=>{let{winningSide:M}=E;if(!M)return A;let P=M-1;return A[P]++,A},[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=gr(a)[l],g=d?.setFormat?.timed||d?.finalSetFormat?.timed,I=d?.bestOf,h=I&&Math.ceil(I/2)||1,S=r??t,T=S&&[Mt,Qe,vt].includes(S),y=!d||!i.length||i.every((A,E)=>{let M=E+1,P=M===I,N=M===i.length,{side1Score:R,side2Score:b,side1TiebreakScore:v,side2TiebreakScore:O,winningSide:x}=A,F=Math.max(R??0,b??0),L=v??O,{finalSetFormat:w,setFormat:B}=d,G=P&&w||B;if(L){let{tiebreakTo:H,NoAD:q}=G?.tiebreakFormat||{},$=Math.max(v??0,O??0);if(q&&$>H||$<H&&x&&(N&&!T||!N))return!1}return G.setTo?!(!G.noTiebreak&&F>G.setTo+1):!0}),D=(!e||l===h)&&f===1&&a.indexOf(l)+1||void 0;return{valid:!!(y&&(n&&p>m&&n===D||n&&T||!n&&!D&&(![ue,Mt,Qe,vt].includes(S)||g&&S===ue)))}}function Bg({existingMatchUpStatus:t,matchUpFormat:e,matchUpStatus:r,winningSide:n,score:o}){if(typeof o!="object")return{error:k};let{sets:i,scoreStringSide1:s,scoreStringSide2:a}=o,c="scoreString must be a string!";if(s!==void 0&&typeof s!="string")return{error:k,info:c};if(a!==void 0&&typeof a!="string")return{error:k,info:c};if(i!==void 0&&!Array.isArray(i))return{error:k,info:ko("sets")};if(i?.length){let u=i.map(m=>m?.setNumber).filter(Boolean);if(u.length!==pt(u).length)return{error:k,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(U=>U.some(A=>![void 0,null].includes(A))).every(U=>U.every(A=>ft(A))))return{error:k,info:"non-numeric values"};if(![T,S].filter(U=>![void 0,null].includes(U)).every(U=>ft(U)))return{error:k,info:"non-numeric values"};if(S&&![1,2].includes(S))return{error:k,info:"winningSide must be 1 or 2"}}let{valid:p}=Vg({existingMatchUpStatus:t,matchUpStatus:r,matchUpFormat:e,winningSide:n,score:o});if(!p)return{error:sE,info:"score is invalid for matchUpFormat or winningSide does not match calculated winningSide"}}return{valid:!0}}var Hg=t=>{let{isSide1:e,lowValue:r,setTo:n,tiebreakAt:o,NoAD:i}=t;if(r===void 0)return!1;let s=ut(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]},Zp=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=TV({lowValue:i,NoAD:o,tiebreakTo:n});return[e?i:s,e?s:i]};function TV(t){let{lowValue:e,NoAD:r,tiebreakTo:n}=t,o=r?1:2;return e+1>=n?e+o:n}function Yd({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&&Zp({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 P_({matchUpScoringFormat:t,isDecidingSet:e,isTiebreakSet:r,setObject:n}){if(!n)return;let o=Qp({set:n});return zp({matchUpScoringFormat:t,set:n,isDecidingSet:e,isTiebreakSet:r})&&o||void 0}function Hu(t){let{setObject:e,matchUpScoringFormat:r}=t;if(!e)return{error:Wl};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(x=>x!==void 0).length,g=d.filter(x=>x!==void 0).length,I=l.filter(x=>x!==void 0).length,h=m?.filter(x=>!isNaN(x)).length,S=l?.filter(x=>!isNaN(x)).length,{tiebreakAt:T}=s||{},y=T&&m.filter(x=>x>=T).length===2,D=y&&(m[0]>m[1]&&1||m[1]>m[0]&&2||void 0),U=!!(S&&!h),A=!!e?.winningSide,{error:E,result:M}=yV({setObject:e,setFormat:s,sideGameScores:m,sideTiebreakScores:l}),{error:P,result:N}=AV({setObject:e,setFormat:s,sideTiebreakScores:l}),R=u&&!U&&M||a&&U&&N,b=p&&!(a&&!U)&&!(u&&U)&&(!A||R),v=P_({isDecidingSet:i,isTiebreakSet:U,matchUpScoringFormat:r,setObject:e}),O={expectTiebreakSet:a,expectTimedSet:c,hasTiebreakCondition:y,isCompletedSet:A,isDecidingSet:i,isTiebreakSet:U,isValidSet:b,isValidSetNumber:p,isValidSetOutcome:R,leadingSide:D,setFormat:s,sideGameScores:m,sideGameScoresCount:f,sidePointScores:d,sidePointScoresCount:g,sideTiebreakScores:l,sideTiebreakScoresCount:I,winningSide:v};return e?.winningSide!==void 0&&(U?(O.isValidTiebreakSetOutcome=N,N||(O.tiebreakSetError=P)):(O.isValidStandardSetOutcome=M,M||(O.standardSetError=E))),O}function yV({setObject:t,setFormat:e,sideGameScores:r,sideTiebreakScores:n}){if(!t)return{result:!1,error:Wl};let o=!!e?.tiebreakSet,i=!!e?.timed;if(!e||o||i)return{result:!1,error:k};if(!(r?.filter(N=>!isNaN(N)).length===2))return{result:!1,error:kI};let{setTo:a,tiebreakAt:c,tiebreakFormat:u,NoAD:p}=e||{};if(!!!(a&&r?.find(N=>N>=a)))return{result:!1,error:kI};let d=[1,2].includes(t?.winningSide);if(!t||!d)return{result:!1,error:Nm};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(N=>!isNaN(N)).length===2,D=n?.[l],U=n?.[f],A=c&&r.filter(N=>N>=c).length===2;if(T){let{NoAD:N,tiebreakTo:R}=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(R))return{result:!1,error:{message:"tiebreakTo error"}};if(!!!(R&&n?.find(B=>B>=R)))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(!D||!U||D<U)return{result:!1,error:{message:"winningSide tiebreak value is not high"}};let x=N?1:2,F=D-U,L=U>=R-1;if(F&&L&&F<x)return{result:!1,error:{message:"invalid tiebreak scores (3)"}}}if(g>a&&!A)return{result:!1,error:{message:"invalid winning game scoreString (2)"}}}let E=p?1:2,M=I>=a-1;return h&&M&&!A&&h<E?{result:!1,error:{message:"invalid winning game scoreString (3)"}}:h>E&&g>a?{result:!1,error:{message:"invalid winning game scoreString (4)"}}:{result:!0}}function AV({setObject:t,setFormat:e,sideTiebreakScores:r}){if(!t)return{result:!1,error:Wl};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:Nm};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 NT={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 MT={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 RT={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 CT={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 bT={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 vT={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 OT={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 _T={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 xT={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 wT={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 LT={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 FT={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 kT={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 GT={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 VT={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 BT={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 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:"Overtime",matchUpCount:1,gender:"MIXED",matchUpFormat:"SET1-S:T20",matchUpType:"DOUBLES",scoreValue:1}],tieFormatName:"USTA_TOC",winCriteria:{aggregateValue:!0}};var qd="COLLEGE_DEFAULT",WT="COLLEGE_JUCO",jT="COLLEGE_D3",jP="DOMINANT_DUO",YP="DOMINANT_DUO_MIXED",qP="LAVER_CUP",$P="TEAM_DOUBLES_3_AGGREGATION",KP="TIME_TENNIS_DUAL",zP="TIME_TENNIS_PRO_CIRCUIT",QP="USTA_BREWER_CUP",XP="USTA_OZAKI_CUP",JP="USTA_COLLEGE",ZP="USTA_GOLD_TEAM_CHALLENGE",tN="USTA_LEVEL_1",eN="USTA_INTERSECTIONAL",rN="USTA_SECTION_BATTLE",nN="USTA_SOUTHERN_LEVEL_5",oN="USTA_TOC",iN="USTA_WTT_ITT",sN="USTA_ZONAL",N_={COLLEGE_D3:jT,COLLEGE_DEFAULT:qd,COLLEGE_JUCO:WT,DOMINANT_DUO:jP,DOMINANT_DUO_MIXED:YP,LAVER_CUP:qP,TEAM_DOUBLES_3_AGGREGATION:$P,TIME_TENNIS_DUAL:KP,TIME_TENNIS_PRO_CIRCUIT:zP,USTA_BREWER_CUP:QP,USTA_OZAKI_CUP:XP,USTA_COLLEGE:JP,USTA_GOLD_TEAM_CHALLENGE:ZP,USTA_INTERSECTIONAL:eN,USTA_LEVEL_1:tN,USTA_SECTION_BATTLE:rN,USTA_SOUTHERN_LEVEL_5:nN,USTA_TOC:oN,USTA_WTT_ITT:iN,USTA_ZONAL:sN};var R_="STANDARD",M_={[R_]:{hydrate:!0,doubles:{matchUpCount:3,matchUpValue:1},singles:{matchUpCount:6,matchUpValue:1},valueGoal:5},[jT]:{hydrate:!0,doubles:{matchUpFormat:"SET1-S:8/TB7@7",matchUpCount:3,matchUpValue:1},singles:{matchUpFormat:Cn,matchUpCount:6,matchUpValue:1},tieFormatName:jT,valueGoal:5},[qd]:{hydrate:!0,doubles:{matchUpFormat:"SET1-S:6/TB7",collectionValue:1,matchUpCount:3},singles:{matchUpFormat:Cn,matchUpCount:6,matchUpValue:1},tieFormatName:qd,valueGoal:4},[WT]:{hydrate:!0,doubles:{matchUpFormat:"SET1-S:8/TB7",matchUpCount:3,matchUpValue:1},singles:{matchUpFormat:Cn,matchUpCount:6,matchUpValue:1},tieFormatName:WT,valueGoal:5},[qP]:BT,[jP]:LT,[YP]:OT,[$P]:MT,[KP]:_T,[zP]:vT,[QP]:xT,[XP]:wT,[JP]:FT,[ZP]:NT,[eN]:bT,[tN]:kT,[rN]:CT,[nN]:RT,[iN]:GT,[oN]:HT,[sN]:VT},GV=t=>{let e=t?.namedFormat&&Object.keys(M_).includes(t.namedFormat)?t.namedFormat:R_,r=Array.isArray(t?.uuids)?t?.uuids:[],n,{category:o,gender:i}=t?.event??{},s=J(M_[e],!1,!0),a=c=>{if(!t?.isMock&&!t?.event?.isMock||!t.event)return r?.pop()??Nt();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:CD,collectionName:"Doubles",matchUpType:kt,...s.doubles},{collectionId:a(1),matchUpFormat:Cn,collectionName:"Singles",matchUpType:Bt,...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},ui=GV;function C_(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===Me&&s===Me){let m=e?.structures?.find(({stage:d})=>d===et)?.tieFormat;u=u||m||o&&c?.tieFormat?.tieFormatName===o&&c.tieFormat||o&&ui({namedFormat:o,hydrateCollections:r,isMock:a,event:c})||c?.tieFormat||ui({event:c,isMock:a,hydrateCollections:r}),p=void 0}else p||(u=void 0,c?.matchUpFormat||(p=Cn));if(u){let m=mr({gender:c?.gender,enforceGender:n,tieFormat:u});if(m.error)return m}return{tieFormat:u,matchUpFormat:p}}function b_(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?uT({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===et&&y===1),{qualifiersCount:g}=Ts({stageSequence:1,drawDefinition:e,structureId:i,stage:et}),I=Math.max(m??0,g??0),h=PS({qualifiersCount:I,drawDefinition:e,stage:et});if(h.error||(h=kp({drawSize:d,stage:ct,drawDefinition:e}),h.error))return h;VV({drawDefinition:e,drawEntries:o,event:c});let S=BV({mainStructure:f,qualifyingDetails:l,drawDefinition:e});return S.error?S:{drawDefinition:e,structureId:i}}function VV({drawDefinition:t,drawEntries:e,event:r}){for(let n of(e??[]).filter(({entryStage:o})=>o===ct)){let o={...n,entryStage:n.entryStage??et,drawDefinition:t,event:r};cS(o)}}function BV({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&&_a({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 YT(t){let{participantIds:e}=t,r=t.drawDefinition?.entries?.filter(n=>{let o=n.entryStatus;return!t.restrictEntryStatus||Wr.includes(o)}).map(ht)??[];if(e){let n=e.filter(o=>!r?.includes(o));if(n?.length)return _({result:{error:pn},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:k,info:"Not enough participants for roundsCount"}:t.roundsCount&&t.restrictRoundsCount!==!1&&t.roundsCount>31?{error:k,info:"roundsCount must be less than 32"}:{participantIds:e}}function $d(t){let e=[],{roundsCount:r=1,drawDefinition:n,matchUpsCount:o,structureId:i,idPrefix:s,isMock:a,event:c}=t,u,p=YT(t);if(p.error)return p;for(let m of tt(1,r+1)){let d=Gu({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 O_(t){let{tournamentRecord:e,participantIds:r,scaleName:n,eventType:o,adHocRatings:i={}}=t,s=t.scaleAccessor??ve[n]?.accessor,a=e.participants??[];for(let c of r??[]){let u=a?.find(m=>m.participantId===c),p=v_({scaleName:`${n}.${Lm}`,participant:u,eventType:o});!p&&n&&(p=v_({scaleAccessor:s,participant:u,scaleName:n,eventType:o})),p&&!i[c]&&(i[c]=p)}return i}function v_({scaleType:t=Si,scaleAccessor:e,participant:r,scaleName:n,eventType:o}){let a=(r&&Uo({scaleAttributes:{eventType:o??ks,scaleType:t,scaleName:n},participant:r}))?.scaleItem?.scaleValue;return e&&It(a)?a[e]:a}function Kd(t){let e=WV(t);if(e?.error)return e;let r=YT(t);if(r.error)return r;let n=HV(t);if(n.error)return n;let o=O_(t),i=t.tournamentRecord?.isMock??t.isMock,s=t.eventType??t.event?.eventType,a=[],c=[],u;for(let p of tt(1,(t.roundsCount??1)+1)){let m=kd({...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;l.modifiedScaleValues&&(o=l.modifiedScaleValues),c.push({...l,iteration:p,matchUpsCount:d?.length}),u=(l?.roundNumber??1)+1,d?.length&&a.push(...d)}return{...C,matchUps:a,roundResults:c}}function HV(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&&Gs[s.stage];return pr({structure:s})&&a>(Gs[i?.stage]||1)?s:i},void 0),n=e?.structures?.find(i=>i.structureId===r?.structureId);return n?pr({structure:n})?{structure:n}:{error:fa}:{error:Lt}}function WV(t){return t.roundsCount&&typeof t.roundsCount!="number"?{error:k,info:"roundsCount must be a number"}:typeof t.drawDefinition!="object"||t.drawDefinition.drawType&&t.drawDefinition.drawType!==an?{error:fa}:!Array.isArray(t.drawDefinition?.entries)&&t.participantIds&&!Array.isArray(t.participantIds)?{error:k,info:"Missing Entries"}:{error:void 0}}function __(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===et)&&m&&Wr.includes(m)),c=a?.map(ht),u=a?Math.floor(a.length/2):0;if(t.automated)return jV({...t,participantIds:c});{let p=$d({roundsCount:t.roundsCount,drawDefinition:r,matchUpsCount:u,idPrefix:o,isMock:i,event:s});if(p.error)return p;p.matchUps?.length&&vd({matchUps:p.matchUps,suppressNotifications:!0,tournamentRecord:e,drawDefinition:r,structureId:n,event:s})}return{...C}}function jV(t){let{restrictEntryStatus:e,generateMatchUps:r,structureId:n,matchUpIds:o,scaleName:i,scaleAccessor:s}=t.drawMatic??{},a=Kd({...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&&vd({tournamentRecord:t.tournamentRecord,drawDefinition:t.drawDefinition,suppressNotifications:!0,matchUps:a.matchUps,event:t.event,structureId:n}),{...C})}function x_({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=at({drawDefinition:s,structureId:c});if(p.error)return p;let m=p.structure;if(!m)return{error:Lt};let{positionAssignments:d}=le({structure:m}),l=d?.length||0;if(u>l)return{error:FA};let f=m.structures?.length,g=ft(a?.groupSeedingThreshold)&&a?.groupSeedingThreshold,I=fg({roundRobinGroupsCount:f,drawSize:l})?.seedGroups,{seedsCount:h}=ku({policyDefinitions:i,requireParticipantCount:t,drawSizeProgression:r,participantsCount:n,drawSize:l});return h&&i?.[xn]&&u>h&&e&&(u=h),m.seedLimit=u,m.seedAssignments=tt(1,u+1).map(S=>{let T=I?.find(U=>U.includes(S)),y=T&&Math.min(...T),D=g&&S>=g?y:S;return{participantId:void 0,seedNumber:S,seedValue:D}}),Ot({drawDefinition:s,structureIds:[c]}),{...C,seedLimit:u}}function ia({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}=Oc({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 qT(t){let e="prepareStage",{drawDefinition:r}=t,{structures:n}=ln({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:Lt},stack:e});let s=i?.structureId,{seedsCount:a,stageEntries:c,seedLimit:u}=JV({...t,structureId:s});(t.seededParticipants||t.event||t.seedingScaleName)&&$V({...t,seedsCount:a,structure:i,structureId:s});let p=t.automated!==!1&&t.drawType!==an&&!(t.qualifyingOnly&&t.stage!==ct),m=(n?.length||0)>1,d=p?qV({...t,multipleStructures:m,seedLimit:u,structureId:s}):{};return d?.error?_({result:d,stack:e}):{...d,stageEntries:c,structureId:s,seedsCount:a}}function YV({entries:t,stage:e,stageSequence:r,roundTarget:n}){return t.filter(o=>{let i=mt({name:Dn,element:o})?.extension?.value;return(!o.entryStage||o.entryStage===e)&&(!r||!o.entryStageSequence||o.entryStageSequence===r)&&(!n||!i||i===n)&&ni.includes(o.entryStatus)})}function qV(t){let e=typeof t.automated=="object"&&t.automated.seedsOnly,r=Uc({...t,seedsOnly:e});if(r.error)return r;let n=r?.positionAssignments,o=r?.positioningReport;return{conflicts:r.conflicts,positionAssignments:n,positioningReport:o}}function $V(t){let{seededParticipants:e,seedingScaleName:r,entries:n,event:o}=t,i=n.map(ht);e?KV({...t,enteredParticipantIds:i}):(o||r)&&zV({...t,enteredParticipantIds:i})}function KV(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?Es({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;Js({provisionalPositioning:e,tournamentRecord:o,drawDefinition:s,seedingProfile:a,participantId:l,seedBlockInfo:m,structureId:c,seedNumber:f,seedValue:g,event:p})})}function zV(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=QV({...t,ageCategoryCode:l,categoryName:d,eventType:f})||c&&XV({...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:D}=h,U=o?.[T]||D||T;Js({provisionalPositioning:r,tournamentRecord:s,drawDefinition:a,seedingProfile:u,participantId:y,structureId:p,seedNumber:T,seedValue:U,event:m})})}function QV(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:So,eventType:u};return ia({scaleAttributes:p,tournamentRecord:e,stageSequence:n,entries:o,stage:i}).scaledEntries}function XV(t){let{tournamentRecord:e,stageSequence:r,event:n,entries:o,stage:i}=t,{categoryName:s,ageCategoryCode:a}=n?.category||{},c=n?.eventType;return ia({scaleAttributes:{scaleName:s||a,scaleType:hi,eventType:c},tournamentRecord:e,stageSequence:r,entries:o,stage:i}).scaledEntries}function JV(t){let{seedsCount:e}=t;t.seededParticipants&&(e=t.seededParticipants.length),e>t.drawSize&&(e=t.drawSize);let r=YV(t);e>r.length&&(e=r.length);let{seedLimit:n}=x_({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 w_(t){let e=Ld({...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=ZV({suppressDuplicateEntries:n,ignoreStageSpace:o,drawDefinition:r,drawEntries:u,drawType:d,entries:l});if(I.error)return I;let h=d===Hi?0:ut(t.seedsCount??0),S=qT({...t,qualifyingOnly:!m||s,appliedPolicies:i,drawDefinition:r,seedingProfile:a,participants:c,stage:et,seedsCount:h,placeByes:p,drawSize:m,entries:l});if(S.error&&!S.conflicts)return S;S.positioningReport?.length&&f.push({[et]:S.positioningReport});let T=S.structureId;return S.conflicts&&(g=S.conflicts),d===an&&t.roundsCount&&__({...t,drawDefinition:r,structureId:T}),{drawDefinition:r,positioningReports:f,conflicts:g,structureId:T}}function ZV(t){let{ignoreStageSpace:e,drawDefinition:r,drawEntries:n,drawType:o,entries:i}=t;for(let s of i){if(n&&s.entryStage&&s.entryStage!==et)continue;let a={...s,ignoreStageSpace:e??o===an,entryStage:s.entryStage??et,event:t.event,drawDefinition:r,drawType:o},c=cS(a);if(n&&c.error)return c}return{error:void 0}}var t1=()=>({matchUpType:void 0,drawName:void 0,drawId:void 0,structures:[],entries:[],links:[]});var L_=t1;function F_(t){let{drawId:e=Nt(),processCodes:r,matchUpType:n,drawType:o}=t??{},i=L_();return Object.assign(i,{processCodes:r,matchUpType:n,drawType:o,drawId:e})}function zd(t){let e=t.structureIds,{tournamentRecord:r,drawDefinition:n,matchUpFormat:o,structureId:i,matchUpId:s,event:a}=t,c=nt(t,[{[Le]:!0,[wm]:!0}]);if(c.error)return c;if(!Ar({matchUpFormat:o}))return{error:Xa};let u="setMatchUpFormat";if(s){let p=Gt({drawDefinition:n,matchUpId:s,event:a});if(p.error)return p;let m=p.matchUp;if(m?.matchUpType===Me)return{info:"Cannot set matchUpFormat when { matchUpType: TEAM }",error:or};m&&(m.matchUpFormat=o,gt({tournamentId:r?.tournamentId,eventId:a?.eventId,context:u,drawDefinition:n,matchUp:m}))}else if(Array.isArray(e)){if(a?.eventType===Me)return{error:Bn};for(let p of e){let m=at({drawDefinition:n,structureId:p});if(m.error)return m;m.structure&&(m.structure.matchUpFormat=o)}}else if(i){if(a?.eventType===Me)return{error:Bn};let p=at({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}),{...C}}function k_({tieFormat:t}){let e=mr({checkCollectionIds:!1,tieFormat:t});if(e.error)return e;for(let r of t.collectionDefinitions)r.collectionId||(r.collectionId=Nt());return{tieFormat:t}}function G_({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=k_({tieFormat:o});if(a.error)return a;e.tieFormat=a.tieFormat??o}else if(r){let a=zd({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 pN={};Qt(pN,{attachPolicies:()=>Ji,findPolicy:()=>ri,getAppliedPolicies:()=>yt,getPolicyDefinitions:()=>_o,mutate:()=>cN,query:()=>uN,removePolicy:()=>aN});var cN={};Qt(cN,{attachPolicies:()=>Ji,removePolicy:()=>aN});function aN(t){let e=nt(t,[{[YC]:!0,_anyOf:{[De]:!1,[Re]:!1,[Le]:!1,[Jo]:!1}}]);if(e.error)return e;let r,n=t.drawDefinition??t.event??((t.tournamentId||!t.tournamentRecords)&&t.tournamentRecord);if(n)return V_(t,n);if(t.tournamentRecords){let o=Object.keys(t.tournamentRecords);if(!o.length)return{error:j};for(let i of o){let s=t.tournamentRecords[i],a=V_(t,s);if(a.error)return a;r=!0}}else return{error:j};return r?{...C}:{error:Wc}}function V_(t,e){let r=yt(t).appliedPolicies??{};return r[t.policyType]?(delete r[t.policyType],Object.keys(r).length?At({element:e,extension:{name:su,value:r}}):ur({element:e,name:su}),{...C}):{error:Wc}}var uN={};Qt(uN,{findPolicy:()=>ri,getAppliedPolicies:()=>yt,getPolicyDefinitions:()=>_o});var mN={[xn]:{validSeedPositions:{ignore:!0},duplicateSeedNumbers:!0,drawSizeProgression:!0,seedingProfile:{drawTypes:{[Io]:{positioning:gi},[Un]:{positioning:gi}},positioning:kC},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}]}},jg=mN;function B_({appliedPolicies:t,policyDefinitions:e,drawDefinition:r,stack:n}){if(e&&typeof e!="object")return _({info:"policyDefinitions must be an object",result:{error:k},stack:n});let o={[iu]:t?.[iu]};return e?e1({policyDefinitions:e,appliedPolicies:t,policiesToAttach:o,drawDefinition:r}):o.avoidance&&Ji({drawDefinition:r,policyDefinitions:o}),!t?.[xn]&&!e?.[xn]&&(Ji({policyDefinitions:jg,drawDefinition:r}),t&&Object.assign(t,jg)),{error:void 0}}function e1({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&&(Ji({policyDefinitions:r,drawDefinition:n}),e&&Object.assign(e,r))}function H_(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??F_({processCodes:t.processCodes,drawId:t.drawId,drawType:a}),d=G_({tournamentRecord:e,drawDefinition:m,matchUpFormat:r,matchUpType:i,tieFormat:s,event:u});if(d.error)return _({result:d,stack:c});let l=B_({appliedPolicies:n,policyDefinitions:o,drawDefinition:m,stack:c});if(l.error)return l;let f=p?.structures?.find(h=>h.stage===et&&h.stageSequence===1)?.structureId,g=p?p.structures?.filter(h=>h.stage===ct):[],I=g?.length===1&&!g[0].matchUps?.length&&g[0].structureId;return{drawDefinition:m,structureId:f,existingDrawDefinition:p,existingQualifyingPlaceholderStructureId:I}}function W_(t){let e="generateOrGetExisting",r=[],n=[],o=H_(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&&b_({...t,...o})||w_({...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 j_(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:ko("structureProfiles"),result:{error:ot},stack:d});S=T.roundTarget||S;let y=T.structureProfiles?.sort(g)||[],D=1;for(let U of y){let{qualifyingRoundNumber:A,qualifyingPositions:E,seededParticipants:M,seedingScaleName:P,seedsCount:N=0,seedByRanking:R,placeByes:b,drawSize:v}=U,O=qT({...t,seedingProfile:U.seedingProfile??c,stageSequence:D,qualifyingRoundNumber:A,preparedStructureIds:h,qualifyingPositions:E,seededParticipants:M,stage:ct,seedingScaleName:P,appliedPolicies:i,drawDefinition:a,qualifyingOnly:s,seedByRanking:R,participants:u,roundTarget:S,seedsCount:N,placeByes:b,drawSize:v,entries:m});if(O.error)return O;O.structureId&&h.push(O.structureId),D+=1,O.conflicts?.length&&f.push(...O.conflicts),O.positioningReport?.length&&o.push({[ct]:O.positioningReport})}S+=1}}else if(p&&l){let g=In({structureName:Ye(ct),stage:ct}),{link:I}=_a({sourceStructureId:g.structureId,targetStructureId:p,sourceRoundNumber:0,linkType:Jn});a.structures||(a.structures=[]),a.structures.push(g),a.links||(a.links=[]),a.links.push(I)}return{qualifyingConflicts:f,error:void 0}}var vN={};Qt(vN,{addGoesTo:()=>Ki,allCompetitionMatchUps:()=>An,allDrawMatchUps:()=>Je,allEventMatchUps:()=>qn,allPlayoffPositionsFilled:()=>AS,allTournamentMatchUps:()=>fe,analyzeDraws:()=>Lu,analyzeMatchUp:()=>om,analyzeTournament:()=>ry,bulkUpdatePublishedEventIds:()=>oy,calculateWinCriteria:()=>Ms,categoryCanContain:()=>xu,checkMatchUpIsComplete:()=>gs,checkValidEntries:()=>xd,compareTieFormats:()=>$o,competitionScheduleMatchUps:()=>ju,courtGridRows:()=>nl,credits:()=>Y_,drawMatchUps:()=>yy,eventMatchUps:()=>al,filterMatchUps:()=>bi,filterParticipants:()=>Du,findDrawDefinition:()=>KS,findExtension:()=>mt,findVenue:()=>Wo,getAllDrawMatchUps:()=>re,getAllEventData:()=>iy,getAllStructureMatchUps:()=>Et,getAllowedDrawTypes:()=>Qd,getAllowedMatchUpFormats:()=>JT,getAppliedPolicies:()=>yt,getAssignedParticipantIds:()=>Oi,getAvailableMatchUpsCount:()=>Od,getAvailablePlayoffProfiles:()=>Ru,getCategoryAgeDetails:()=>ea,getCheckedInParticipantIds:()=>ps,getCompetitionDateRange:()=>Jd,getCompetitionMatchUps:()=>nm,getCompetitionParticipants:()=>$T,getCompetitionPenalties:()=>ZT,getCompetitionVenues:()=>tm,getCourtInfo:()=>id,getCourts:()=>Ay,getDrawData:()=>tl,getDrawDefinitionTimeItem:()=>Oh,getDrawParticipantRepresentativeIds:()=>qS,getDrawStructures:()=>ln,getDrawTypeCoercion:()=>Fu,getEligibleVoluntaryConsolationParticipants:()=>YS,getEntriesAndSeedsCount:()=>ol,getEvent:()=>Dy,getEventData:()=>el,getEventMatchUpFormatTiming:()=>dy,getEventProperties:()=>Ey,getEventPublishStatus:()=>jr,getEventStructures:()=>Ig,getEventTimeItem:()=>gu,getEvents:()=>Uy,getFlightProfile:()=>Wt,getHomeParticipantId:()=>sd,getLinkedTournamentIds:()=>cu,getMatchUpCompetitiveProfile:()=>Su,getMatchUpContextIds:()=>Iy,getMatchUpDailyLimits:()=>ul,getMatchUpDailyLimitsUpdate:()=>ly,getMatchUpDependencies:()=>rn,getMatchUpFormat:()=>hy,getMatchUpFormatTiming:()=>Tu,getMatchUpFormatTimingUpdate:()=>py,getMatchUpScheduleDetails:()=>ad,getMatchUpType:()=>pd,getMatchUpsMap:()=>Ee,getMatchUpsStats:()=>Sy,getMaxEntryPosition:()=>cy,getModifiedMatchUpFormatTiming:()=>il,getPairedParticipant:()=>gn,getParticipantEventDetails:()=>KT,getParticipantIdFinishingPositions:()=>$S,getParticipantMembership:()=>zT,getParticipantResults:()=>vu,getParticipantScaleItem:()=>Oc,getParticipantSchedules:()=>QT,getParticipantSignInStatus:()=>XT,getParticipantTimeItem:()=>_h,getParticipants:()=>$t,getPersonRequests:()=>xi,getPolicyDefinitions:()=>_o,getPositionAssignments:()=>qp,getPositionsPlayedOff:()=>Nc,getPredictiveAccuracy:()=>gy,getProfileRounds:()=>rl,getPublishState:()=>Ss,getRoundMatchUps:()=>je,getRounds:()=>Ty,getScaleValues:()=>ha,getScaledEntries:()=>ia,getScheduledRoundsDetails:()=>Wu,getSchedulingProfile:()=>Ko,getSchedulingProfileIssues:()=>ay,getSeedingThresholds:()=>mS,getSeedsCount:()=>ku,getStructureSeedAssignments:()=>en,getTeamLineUp:()=>ls,getTieFormat:()=>ny,getTimeItem:()=>Xr,getTournamentIds:()=>Ep,getTournamentInfo:()=>Ns,getTournamentPenalties:()=>Xd,getTournamentPersons:()=>ey,getTournamentPublishStatus:()=>Eu,getTournamentStructures:()=>yS,getTournamentTimeItem:()=>Xm,getValidGroupSizes:()=>wp,getVenueData:()=>hc,getVenuesAndCourts:()=>Do,isAdHoc:()=>pr,isCompletedStructure:()=>si,isValidForQualifying:()=>aT,isValidMatchUpFormat:()=>Ar,matchUpActions:()=>_d,participantScaleItem:()=>Uo,participantScheduledMatchUps:()=>fy,positionActions:()=>sT,publicFindCourt:()=>Zh,publicFindVenue:()=>Jh,tallyParticipantResults:()=>wa,tieFormatGenderValidityCheck:()=>Cd,tournamentMatchUps:()=>cl,validMatchUp:()=>tg,validMatchUps:()=>Lr,validateCollectionDefinition:()=>wu,validateLineUp:()=>Td});function Y_(){return`
|
|
4
|
+
`)}function vD({participantResults:t,participantIds:e,attribute:r}){return OD({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 OD(t){return(t.participantIds||Object.keys(t.participantResults)).reduce((r,n,o)=>(r.push({participantId:n,i:o,results:t.participantResults[n]}),r),[])}var IG=[{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}],_D={matchUpsPct:20,tieMatchUpsPct:16,pointsPct:4,gamesPct:8,setsPct:12};function xD(t){let{requireCompletion:e=!0,participantResults:r,subOrderMap:n,tallyPolicy:o}=t,i=[];if(e&&!hG(t))return{};let s=["tieMatchUpsWon","tieSinglesWon","tieDoublesWon","matchUpsWon","pointsWon","gamesWon","setsWon","gamesPct","setsPct","pointsPct","matchUpsPct"].includes(o?.groupOrderKey)?o.groupOrderKey:"matchUpsWon",a=vD({participantResults:r,attribute:s});i.push({attribute:s,groups:a});let p=Object.keys(a).map(S=>parseFloat(S)).sort((S,T)=>T-S).map(S=>a[S]).map(S=>{let T=TO({participantIds:S,...t});return i.push(...T.report??[]),T.order}).map((S,T)=>S.map(y=>y.resolved?y:{...y,subGroup:[T].concat(...y.subGroup??[])})).flat(),m,d=0,l=1,f;p.forEach((S,T)=>{T&&(S.resolved||f&&!S.resolved)&&(l+=1),f=S.resolved;let y=parseInt(S.subGroup?.join("")||0);S.resolved?(S.position=T+1,l=S.position):(m&&y>m&&(l+=d,d=0),S.position=l,d+=1),m=y});let g=p.map(({position:S})=>S),I=gr(g);return p.forEach(S=>{let{participantId:T,position:y}=S||{},D=r[T];S.GEMscore=h(D);let U=I[y];S?.position!==void 0&&(U>1&&(S.ties=U,n&&(S.subOrder=n[T])),S.rankOrder=y,S.groupOrder=y+(S.subOrder||1)-1)}),{groupOrder:p,report:i.flat(1/0).filter(Boolean)};function h(S){return(Array.isArray(o?.GEMscore)?Object.keys(_D).filter(D=>o.GEMscore.includes(D)):Object.keys(_D)).map(D=>(S[D]||0)*Math.pow(10,_D[D].toFixed(3))).reduce((D,U)=>D+U,0)}}function hG({participantResults:t,participantsCount:e}){let n=OD({participantResults:t}).filter(o=>e-1===o.results.matchUpsWon+o.results.matchUpsLost+o.results.matchUpsCancelled);return e===n.length}function SG({disableHeadToHead:t,participantIds:e,matchUpFormat:r,tallyPolicy:n,attribute:o,idsFilter:i,matchUps:s,reversed:a}){let{participantResults:c}=vu({participantIds:i&&e,matchUpFormat:r,tallyPolicy:n,matchUps:s}),u=vD({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(f=>parseFloat(f)).sort((f,g)=>a?f-g:g-f).map(f=>u[f]).map(f=>{let g=TO({participantResults:c,disableHeadToHead:t,participantIds:f,matchUpFormat:r,tallyPolicy:n,matchUps:s});return p.push(...g.report??[]),g.order}).map((f,g)=>f.map(I=>I.resolved?I:{...I,subGroup:[g].concat(...I.subGroup??[])})).flat()),{order:m,report:p}}function TO({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=TG({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||IG).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=SG({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 TG({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 wa({policyDefinitions:t,generateReport:e,pressureRating:r,matchUpFormat:n,matchUps:o=[],subOrderMap:i,perPlayer:s}){if(!o?.length||!Lr(o))return{error:Xn};let a=pt(o.map(({structureId:y})=>y));if(a.length!==1)return _({result:{error:k,info:"Maximum one structureId"},stack:"tallyParticipantResults",context:{structureIds:a}});let c=o.filter(y=>y&&y.matchUpStatus!==Pt),u=c.length&&pt(c.map(({drawPositions:y})=>y).flat()).length,p=c.filter(y=>gs({matchUp:y})).length===c.length;p||(s=0);let m=o.every(({matchUpType:y,tieMatchUps:D})=>y===Ht&&D?.every(U=>gs({matchUp:U}))),d=t?.[Uf],l=o.filter(y=>gs({matchUp:y})||y.matchUpType===Ht),{participantResults:f}=vu({matchUps:l,pressureRating:r,matchUpFormat:n,tallyPolicy:d,perPlayer:s}),g,I,{groupOrder:h,report:S}=xD({matchUps:l,participantResults:f,participantsCount:u,matchUpFormat:n,tallyPolicy:d,subOrderMap:i});if(r&&yG({participantResults:f}),p&&h)g=S,I=h,h.forEach(y=>{let{participantId:D,groupOrder:U,rankOrder:A,subOrder:E,ties:M,GEMscore:P}=y,N=f[D];Object.assign(N,{groupOrder:U,rankOrder:A,GEMscore:P,subOrder:E,ties:M})});else{let{groupOrder:y,report:D}=xD({requireCompletion:!1,participantResults:f,participantsCount:u,matchUpFormat:n,tallyPolicy:d,subOrderMap:i,matchUps:o});g=D,I=y,y&&y.forEach(U=>{let{participantId:A,groupOrder:E,GEMscore:M}=U,P=f[A];Object.assign(P,{provisionalOrder:E,GEMscore:M})})}let T={completedTieMatchUps:m,readableReport:"",participantResults:f,bracketComplete:p,order:[],report:g};if((p||m)&&(T.order=I),e||Sr({tally:!0})){let y=SO({matchUps:o,report:g,order:I});Sr({tally:!0})&&console.log(y),T.readableReport=y}return T}function yG({participantResults:t}){let e=o=>o.reduce((i,s)=>i+parseFloat(s),0),r=o=>parseFloat((e(o)/o.length).toFixed(2)),n=Object.keys(t).map(o=>{let i=t[o],{pressureScores:s}=i,a=s?.length?r(s):0;return{participantId:o,averagePressure:a}}).sort((o,i)=>(i.averagePressure||0)-(o.averagePressure||0)).map((o,i)=>({...o,order:i+1}));for(let o of n)t[o.participantId].pressureOrder=o.order}function FS({positionAssignments:t}){let e=(t||[]).filter(Fr(eo)).map(i=>{let{extension:s}=mt({element:i,name:uc}),a=ut(s?.value),c=!isNaN(a)&&a;return c&&{participantId:i.participantId,subOrder:c}}).filter(Boolean),r=e.map(({subOrder:i})=>i),n=gr(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(!Lr(o))return{error:k};if(!t)return{error:k};let{policyDefinitions:s}=_o({policyTypes:[Uf],tournamentRecord:e,drawDefinition:r,event:i}),{subOrderMap:a}=FS({positionAssignments:t}),c=o.length?wa({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:Zo};At({element:l,extension:g}),u[f].ties||ur({element:l,name:uc})}else ur({element:l,name:Zo}),ur({element:l,name:uc})}),Ot({drawDefinition:r}),{...C,participantResults:u,bracketComplete:p,report:m}}function kS({matchUps:t,matchUpId:e}){return{matchUp:(t||[]).find(n=>n.matchUpId===e)}}function Gt(t){let e=nt(t,[{[Le]:!0,[dn]:!0}]);if(e.error)return e;let{tournamentParticipants:r,afterRecoveryTimes:n,contextProfile:o,drawDefinition:i,matchUpsMap:s,matchUpId:a,inContext:c,context:u,event:p}=t,{structures:m=[]}=ln({drawDefinition:i}),d=t.contextContent||o&&Yn({contextProfile:o,drawDefinition:i});for(let l of m){let{matchUps:f}=Et({tournamentParticipants:r,afterRecoveryTimes:n,contextContent:d,drawDefinition:i,contextProfile:o,matchUpsMap:s,inContext:c,structure:l,context:u,event:p}),{matchUp:g}=kS({matchUps:f,matchUpId:a});if(g)return{matchUp:g,structure:l}}return{error:_e}}function Wp(t){return!It(t)||!t.notes?{error:ot}:It(t.element)?!te(t.notes)&&!t.notes?.testing?{error:k}:(Object.assign(t.element,{notes:t.notes}),{...C}):{error:k}}function Ng(t){return It(t)?It(t.element)?(t.element.notes&&delete t.element.notes,{...C}):{error:k}:{error:ot}}var Ou={matchUpStatus:zt,matchUpStatusCodes:[],score:{scoreStringSide1:"",scoreStringSide2:"",sets:void 0},matchUpFormat:void 0,winningSide:void 0};function kn(t){let e="modifyMatchUpScore",r=t.matchUpFormat,n=t.matchUp,o,{matchUpStatusCodes:i,removeWinningSide:s,tournamentRecord:a,drawDefinition:c,matchUpStatus:u,removeScore:p,winningSide:m,matchUpId:d,event:l,notes:f,score:g}=t,h=t.appliedPolicies&&Object.keys(t.appliedPolicies).length?t.appliedPolicies:yt({policyTypes:[Qr],tournamentRecord:a,drawDefinition:c,structure:o,event:l})?.appliedPolicies,S=n.matchUpType===Ht;if(S&&c){if(d&&n.matchUpId!==d){let M=Gt({drawDefinition:c,matchUpId:d,event:l});if(!M.matchUp)return{error:_e};({matchUp:n,structure:o}=M)}}else n.matchUpId!==d&&console.log("!!!!!");u&&[vt,he].includes(u)||p?Object.assign(n,{...Ou}):g&&(n.score=g);let T=u&&n?.matchUpStatus===Mt&&u!==Mt;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}=Gt({drawDefinition:c,matchUpId:d,event:l})),u&&!n.winningSide&&me(n)&&!ie.includes(u)&&![pc,as].includes(u)&&(n.matchUpStatus=Ln);let y;if((T&&n?.processCodes?.length||u===Mt)&&(y=h?.[Qr]?.processCodes?.incompleteAssignmentsOnDefault),!n.collectionId){let M=o?.structureType===we,P=pr({structure:o});if(ud({drawDefinition:c,structure:o})||P||M){let N=v=>{r=S?"SET1-S:T100":r??n.matchUpFormat??v?.matchUpFormat??c?.matchUpFormat??l?.matchUpFormat;let O=S?{matchUpTypes:[Ht]}:void 0,{matchUps:x}=Et({afterRecoveryTimes:!1,tournamentRecord:a,inContext:!0,matchUpFilters:O,drawDefinition:c,structure:v,event:l});return P&&(v.positionAssignments=pt(x.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:x,event:l})},R=M&&o.structures.find(v=>v?.matchUps.find(O=>O.matchUpId===d)),b=N(R||o);if(b.error)return _({result:b,stack:e})}}if(f){let M=Wp({element:n,notes:f});if(M.error)return _({result:M,stack:e})}let D=a?.tournamentId,U=xr().topics.includes(Pp),A=(U||y)&&Ee({drawDefinition:c}),E=A&&re({matchUpFilters:{matchUpIds:[d]},nextMatchUps:!0,tournamentRecord:a,inContext:!0,drawDefinition:c,matchUpsMap:A}).matchUps?.[0];if(U&&E&&mb({tournamentId:D,inContextMatchUp:E}),Array.isArray(y)&&E&&!E.sides?.every(({participantId:M})=>M))if(u===Mt)n.processCodes=pt([...n.processCodes??[],...y]);else for(let M of y||[]){let P=M&&n?.processCodes?.lastIndexOf(M);n?.processCodes?.splice(P,1)}return gt({eventId:l?.eventId,context:e,drawDefinition:c,tournamentId:D,matchUp:n}),{...C}}function Rd(t){let{matchUpStatusCodes:e,matchUpStatus:r,structure:n,matchUp:o,dualMatchUp:i,inContextMatchUp:s}=t,a=Ca({matchUpStatus:r})||[oo,Mr].includes(r)&&i,c=o?.sides?.map(g=>g.participantId).filter(Boolean).length||s?.sides?.map(g=>g.participantId).filter(Boolean).length,u="attemptToModifyScore";if(!(pr({structure:n})&&c===1||r===Mt&&c||AG({structure:n,matchUp:o,inContextMatchUp:s})||t.appliedPolicies?.[Qr]?.requireParticipantsForScoring===!1))return _({result:{error:kl},stack:u});let d=[vt].includes(r),l=a?r:t.winningSide&&ue||Pn,f=kn({...t,matchUpStatusCodes:a&&e||[],matchUpStatus:l,context:u,removeScore:d});return _({result:f,stack:u})}function AG({structure:t,matchUp:e,inContextMatchUp:r}){let{drawPositions:n}=e,{positionAssignments:o}=le({structure:t}),i=o?.filter(a=>n?.includes(a.drawPosition)&&a.participantId),s=r?.sides?.every(a=>a.participantId);return i?.length===2||s}function GS({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=>ut(n));return{groupValueGroups:e,groupValueNumbers:r}}function yO({collectionDefinition:t,groupValueNumbers:e,groupValueGroups:r,sideTieValues:n,tieMatchUps:o}){let i=o.filter(S=>S.collectionId===t.collectionId),s=[0,0],a=[0,0],c=i.every(S=>ie.includes(S.matchUpStatus)),{collectionValueProfiles:u,collectionGroupNumber:p,collectionValue:m,matchUpValue:d,winCriteria:l,scoreValue:f,setValue:g}=t,I=p&&e.includes(p),h=[0,0];if(i.forEach(S=>{S.winningSide&&(h[S.winningSide-1]+=1)}),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:D=0,side1Score:U=0,side2Score:A=0}=T;(S.matchUpStatus===ue||S.winningSide||T.winningSide)&&(U||A?(s[0]+=U,s[1]+=A):(y||D)&&T.winningSide&&(s[T.winningSide-1]+=1))})}):Array.isArray(u)&&i.forEach(S=>{if(S.winningSide){let T=S.collectionPosition,y=EG({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,D)=>y>=l.valueGoal?D+1:T,0);else{let T=Math.floor(t.matchUpCount/2)+1;S=h.reduce((y,D,U)=>D>=T?U+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 EG({collectionDefinition:t,collectionPosition:e}){return(t.collectionValueProfiles||[])?.find(o=>o.collectionPosition===e)?.matchUpValue}function VS({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}):{...C}}var UG="MIXED events can not contain mixed singles or { gender: ANY } collections",DG="events with { gender: ANY } can not contain MIXED singles collections";function Cd(t){let e="tieFormatGenderValidityCheck",{referenceGender:r,matchUpType:n,gender:o}=t;return r&&o&&[Zt,ce].includes(r)&&r!==o?_({result:{valid:!1,error:op},context:{gender:o},stack:e}):r===Cr&&(o===Mn||o===Cr&&n!==kt)?_({result:{error:op,valid:!1},info:UG,stack:e}):r===Mn&&o===Cr&&n!==kt?_({result:{error:op,valid:!1},info:DG,stack:e}):{valid:!0}}function jp(t,e){if(It(t),(t?.bestOf||t?.exactly)&&t?.setFormat)return PG(t,e)}function Mg(t){return!isNaN(Number(t))&&Number(t)}function UO(t){let e=`T${t.minutes}`;return t.based&&(e+=t.based),t.modifier&&(e+=`@${t.modifier}`),e}function PG(t,e){let r=Mg(t.bestOf)||void 0,n=Mg(t.exactly)||void 0,o=r||n;if(t.setFormat?.timed&&t.simplified&&o===1)return UO(t.setFormat);let i=o&&`${md}${o}`||"",s=AO(t.setFormat,e),a=s&&`S:${s}`||"",c=AO(t.finalSetFormat,e),u=o&&o>1&&c&&s!==c&&`F:${c}`||"";if(i&&s)return[i,a,u].filter(m=>m).join("-")}function AO(t,e){if(typeof t=="object"&&Object.keys(t).length){if(t.timed)return UO(t);if(t.tiebreakSet)return EO(t.tiebreakSet);let r=Mg(t.setTo);if(r){let n=t.NoAD&&rg||"",o=EO(t.tiebreakFormat),i=o&&`/${o}`||"",s=Mg(t.tiebreakAt),a=s&&(s!==r||e)&&`@${s}`||"";if(o!==!1)return`${r}${n}${i}${a}`}}}function EO(t){if(t){if(typeof t=="object"&&!t.tiebreakTo)return"";if(typeof t=="object"&&Mg(t.tiebreakTo)){let e=`TB${t.tiebreakTo}${t.NoAD?rg:""}`;return t.modifier&&(e+=`@${t.modifier}`),e}else return!1}}function Ar({matchUpFormat:t}){if(!te(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 jp(e,!!(r&&o&&n===i||s&&c&&a===u))===t}var NG=(t,e)=>t.filter(Boolean).every(r=>typeof r===e),MG=t=>t.filter(Boolean).every(Jt);function ea(t){let e=t.category;if(typeof e!="object")return{error:qc};let{ageCategoryCode:r,ageMaxDate:n,ageMinDate:o,ageMax:i,ageMin:s}=e,a=e.categoryName,c;if(!NG([r,n,o,a],"string")||!MG([i,s]))return{error:qc};let u=t.consideredDate??Dt(new Date().toLocaleDateString("sv"));if(!Nr(u))return{error:Ge};let[p]=u.split("-").slice(0,3).map(w=>parseInt(w)),m=Tp(u,-1),[d,l]=m.split("-").slice(1,3).map(w=>parseInt(w)),f=`${ro(d)}-${ro(l)}`,g=Tp(u,1),[I,h]=g.split("-").slice(1,3).map(w=>parseInt(w)),S=`${ro(I)}-${ro(h)}`,T=s&&Tp(u,-1*365*s),y=i&&Tp(u,-1*365*i),D=[],U=w=>!D.includes(w)&&D.push(w);r=r??a;let A=/^([UO]?)(\d{1,2})([UO]?)$/,E=/^C(\d{1,2})-(\d{1,2})$/,M=r?.includes("-"),P=M&&r?.match(E),N=r?.match(A),R=(w,B)=>`${w}-${B}`,b=w=>{let B=p-w,G=R(B,S);e.ageMinDate&&e.ageMinDate!==G&&U(`Invalid submitted ageMinDate: ${o}`),o=G,r&&(e.ageMax&&e.ageMax!==w-1&&(U(`Invalid submitted ageMax: ${i}`),y=void 0),i=w-1)},v=w=>{let B=p-w-1,G=R(B,S);e.ageMin&&e.ageMin>w&&U(`Invalid submitted ageMin: ${s}`),e.ageMax&&e.ageMax>w&&U(`Invalid submitted ageMax: ${i}`),e.ageMinDate&&e.ageMinDate!==G&&U(`Invalid submitted ageMinDate: ${o}`),o=G,r&&(e.ageMax&&e.ageMax!==w&&(U(`Invalid submitted ageMax: ${i}`),T=void 0),i=w)},O=w=>{let B=p-w,G=R(B,f);e.ageMaxDate&&e.ageMaxDate!==G&&U(`Invalid submitted ageMaxDate: ${n}`),n=G,r&&(e.ageMin&&e.ageMin!==w+1&&(U(`Invalid submitted ageMin: ${s}`),T=void 0),s=w+1)},x=w=>{let B=p-w-1,G=R(B,f);e.ageMaxDate&&e.ageMaxDate!==G&&U(`Invalid submitted ageMaxDate: ${n}`),n=G,r&&(e.ageMin&&e.ageMin!==w&&(U(`Invalid submitted ageMin: ${s}`),T=void 0),s=w)},F=w=>{let[B,G,W]=(w.match(A)||[]).slice(1),H=parseInt(G);B==="U"?(e.ageMaxDate&&e.ageMaxDate!==n&&U(`Invalid submitted ageMaxDate: ${e.ageMaxDate}`),b(H)):B==="O"&&O(H),W==="U"?(e.ageMaxDate&&e.ageMaxDate!==n&&U(`Invalid submitted ageMaxDate: ${e.ageMaxDate}`),v(H)):W==="O"&&x(H),n=n??T,o=o??y};if(P){if(n=void 0,o=void 0,i=void 0,s=void 0,e.ageMin){let G=p-e.ageMin;n=R(G,f)}if(e.ageMax){let G=p-e.ageMax-1;o=R(G,S)}let[w,B]=(r?.match(E)??[]).slice(1).map(G=>parseInt(G));w<=B?(s=w,i=B,c=!0):U(`Invalid combined age range ${r}`)}else M?r?.split("-").forEach(F):N?F(r):(s&&O(s),i&&v(i));i&&e.ageMin&&e.ageMin>i&&(U(`Invalid submitted ageMin: ${e.ageMin}`),s=void 0);let L=rt({consideredDate:u,combinedAge:c,ageMaxDate:n,ageMinDate:o,ageMax:i,ageMin:s});return D.length&&(L.errors=D),L}function _u({category:t}){if(!It(t))return{error:k};let e=ea({category:t});if(e.error)return{error:e};let{ratingMax:r,ratingMin:n}=t;return r&&!Jt(r)?_({result:{error:k},context:{ratingMax:r}}):n&&!Jt(n)?_({result:{error:k},context:{ratingMin:n}}):{...e}}function xu({childCategory:t,withDetails:e,category:r}){let n=_u({category:r}),o=_u({category:t}),i=o.ageMin&&(n.ageMin&&o.ageMin<n.ageMin||n.ageMax&&o.ageMin>n.ageMax),s=o.ageMax&&(n.ageMax&&o.ageMax>n.ageMax||n.ageMin&&o.ageMax<n.ageMin),a=o.ageMinDate&&n.ageMaxDate&&new Date(o.ageMinDate)>new Date(n.ageMaxDate),c=o.ageMaxDate&&n.ageMinDate&&new Date(o.ageMaxDate)<new Date(n.ageMinDate),p=r?.ratingType&&t?.ratingType&&r.ratingType===t.ratingType&&(r.ratingMin&&t.ratingMin&&t.ratingMin<r.ratingMin||r.ratingMax&&t.ratingMax&&t.ratingMax>r.ratingMax||r.ratingMin&&t.ratingMax&&t.ratingMax<r.ratingMin||r.ratingMax&&t.ratingMin&&t.ratingMin>r.ratingMax),m=r?.ballType&&t?.ballType&&r.ballType!==t.ballType,f=rt({invalidRatingRange:p,invalidAgeMinDate:a,invalidAgeMaxDate:c,invalidBallType:m,invalidAgeMax:s,invalidAgeMin:i,valid:!p&&!a&&!c&&!m&&!s&&!i},!0);return e&&Object.assign(f,{categoryDetails:n,childCategoryDetails:o}),f}function wu({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:po},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&&!yu([Bt,kt],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 U=VS({collectionValueProfiles:u,matchUpCount:l});U.errors&&c.push(...U.errors)}if(p&&typeof p!="number"&&c.push(`collectionGroupNumber is not type number: ${m}`),f&&!Ar({matchUpFormat:f})&&c.push(`Invalid matchUpFormat: ${f}`),n){let U=Cd({referenceGender:i,matchUpType:I,gender:y});if(U.error)return _({context:{referenceGender:i,gender:y},result:U,stack:a})}if(t&&o&&T){let U=xu({category:o,childCategory:T});if(!U.valid)return _({result:{error:qc},context:U,stack:a})}return c.length?_({result:{errors:c,error:bE},stack:a}):{valid:!0}}function mr(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=[],c=RG({...t,stack:s});if(c?.error)return c;let u,p=o.collectionDefinitions.every(I=>{let{setValue:h,scoreValue:S,collectionValue:T}=I;(h||S)&&!T&&(u=!0);let{valid:y,errors:D}=wu({referenceCategory:t.category,referenceGender:t.gender,collectionDefinition:I,checkCollectionIds:n,checkCategory:e,checkGender:r,event:i});return y?!0:(Array.isArray(D)&&a.push(...D),!1)}),m=typeof o.winCriteria?.valueGoal=="number"&&o.winCriteria?.valueGoal>0&&!u||o.winCriteria?.aggregateValue;if(!(m||o.winCriteria?.aggregateValue))return u?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:u},result:{error:li},stack:s});let d=o.collectionDefinitions.map(({collectionId:I})=>I),l=!n||d.length===pt(d).length,f=p&&m&&l,g={valid:f,errors:a};return f?g:_({result:{error:li},context:{tieFormat:o,errors:a},stack:s})}function RG(t){let{tieFormat:e,stack:r}=t;return!t||!e||!It(e)?_({result:{error:li},context:{tieFormat:e,message:"tieformat must be an object"},stack:r}):It(e.winCriteria)?Array.isArray(e.collectionDefinitions)?{...C}:_({result:{error:li},context:{tieFormat:e,message:"collectionDefinitions must be an array"},stack:r}):_({result:{error:li},context:{tieFormat:e,message:"tieformat.winCritiera must be an object"},stack:r})}function Cc(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,D)=>y+D)))return{error:k};if(!s)return{error:dr};let c=We({matchUp:s,drawDefinition:n,structure:i,event:a})?.tieFormat||t?.tieFormat;if(!c)return{error:xs};let u=mr({tieFormat:c});if(u.error)return u;let p=c?.collectionDefinitions||[],m=s?.tieMatchUps??[],d=[0,0],{groupValueGroups:l,groupValueNumbers:f}=GS(c);for(let y of p)yO({collectionDefinition:y,groupValueNumbers:f,groupValueGroups:l,sideTieValues:d,tieMatchUps:m});for(let y of f){let D=l[y],{allGroupMatchUpsCompleted:U,matchUpCount:A,winCriteria:E,groupValue:M,sideWins:P,values:N}=D,R;if(E?.aggregateValue)U&&N[0]!==N[1]&&(R=N[0]>N[1]?1:2);else if(E?.valueGoal)R=N.reduce((b,v,O)=>v>=E.valueGoal?O+1:b,void 0);else{let b=Math.floor(A/2)+1;R=P.reduce((v,O,x)=>O>=b?x+1:v,void 0)}R&&(d[R-1]+=M||0)}let g=d.map((y,D)=>(y||0)+e[D]),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:D,tallyDirectives:U}=c.winCriteria;if(y?T=g.map((E,M)=>({sideNumber:M+1,points:E})).find(({points:E})=>E>=y)?.sideNumber:D&&m.every(E=>E.matchUpStatus&&ie.includes(E.matchUpStatus)||E.winningSide)&&g[0]!==g[1]&&(T=g[0]>g[1]?1:2),!T&&U){let A=s.matchUpId,E=s.hasContext?s:o?.drawMatchUps?.[A]||n&&Gt({inContext:!0,drawDefinition:n,matchUpId:A})?.matchUp;if(E){let{completedTieMatchUps:M,order:P}=wa({matchUps:[E]});if(M&&P?.length){let N=P[0].participantId;T=E.sides.find(({participantId:R})=>R===N)?.sideNumber}}}}return T&&(I.winningSide=T),{scoreStringSide1:h,scoreStringSide2:S,winningSide:T,set:I}}function La({inContextDualMatchUp:t,drawDefinition:e,tournamentId:r,dualMatchUp:n,eventId:o}){if(n){t||(t=Gt({matchUpId:n.matchUpId,inContext:!0,drawDefinition:e})?.matchUp);let{extension:i}=mt({element:e,name:bo}),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}}),gt({context:"ensureSidLineUps",matchUp:n,drawDefinition:e,tournamentId:r,eventId:o})}}function Ze(t){if(t)return J(t,!1,!0)}function Rg(t){let e=nt(t,[{[De]:!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 BS({tournamentRecords:t,eventId:e,drawId:r}){let{tournamentIdMap:n}=Rg({tournamentRecords:t});return(n?Object.keys(n):[]).find(i=>e&&n?.[i].includes(e)||r&&n?.[i].includes(r))}function co(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&&BS({tournamentRecords:c,...t});let p=u&&c[u];if(!p)return{error:j};let m=Gt({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:or};La({tournamentId:p?.tournamentId,eventId:a?.eventId,dualMatchUp:d,drawDefinition:r});let{extension:f}=mt({name:ya,element:d});if(f?.value)if(o)ur({element:d,name:ya});else return{...C,score:d.score};let g=We({drawDefinition:r,structure:l,matchUp:d,event:a})?.tieFormat;d.tieFormat=Ze(g);let I=Cc({drawDefinition:r,matchUpsMap:i,structure:l,matchUp:d,event:a}),{winningSide:h,set:S,scoreStringSide1:T,scoreStringSide2:y}=I,D=S?.side1Score||S?.side2Score;if(e&&!d.score&&!D)return{...C};let U={scoreStringSide1:T,scoreStringSide2:y,sets:S?[S]:[]},A=h&&[1,2].includes(h),E=A&&ue||ig({matchUpStatus:n??d.matchUpStatus,tieMatchUps:d.tieMatchUps,winningSide:d.winningSide,score:U})&&Ln||zt,M=!!(d.winningSide&&!A),P=d.tieMatchUps.find(({score:R,winningSide:b,matchUpStatus:v})=>R?.sets?.length&&(R.sets[0].side1Score||R.sets[0].side2Score)||v&&ie.includes(v)||b),N;if(d.tieFormat&&!A&&!P){let R=We({drawDefinition:r,structure:l,event:a})?.tieFormat;R&&JSON.stringify(g)===JSON.stringify(R)&&(d.tieFormatId=void 0,d.tieFormat=void 0,N=!0)}return kn({appliedPolicies:t.appliedPolicies,matchUpStatus:E,score:U,removeWinningSide:M,tournamentRecord:p,drawDefinition:r,removeScore:o,winningSide:h,matchUpId:s,matchUp:d,event:a}),{...C,score:U,removeWinningSide:M,tieFormatRemoved:N,winningSide:h}}function DO({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=at({structureId:I,drawDefinition:c});if(h.error)return h;let{structure:S}=h,{positionAssignments:T}=le({structureId:I,drawDefinition:c}),D=T?.find(R=>R.drawPosition===o)?.participantId,U=s.target.structureId,{positionAssignments:A}=le({structureId:U,drawDefinition:c}),M=A?.find(R=>R.participantId===D)?.drawPosition,P=A?.filter(R=>{let b=f.includes(R.drawPosition),v=!R.participantId&&!R.bye&&!R.qualifier;return b&&v}).map(R=>R.drawPosition),N=P?.includes(g);if(D&&s.target.roundNumber===1&&N)Fn({drawPosition:g,participantId:D,structureId:U,inContextDrawMatchUps:e,sourceMatchUpStatus:n,tournamentRecord:i,drawDefinition:c,matchUpsMap:m,event:d});else if(D&&P?.length){let R=P.pop();R&&Fn({participantId:D,structureId:U,inContextDrawMatchUps:e,sourceMatchUpStatus:n,tournamentRecord:i,drawDefinition:c,drawPosition:R,matchUpsMap:m,event:d})}else if(M){let R=Ec({drawPosition:M,matchUpId:u.matchUpId,inContextDrawMatchUps:e,sourceMatchUpStatus:n,tournamentRecord:i,sourceMatchUpId:a,drawDefinition:c,matchUpsMap:m});if(R.error)return _({result:R,stack:l})}else if(S?.stage!==ct){let R="winner target position unavaiallble";return console.log(R),{error:R}}if(S?.seedAssignments&&S.structureId!==U){let R=S.seedAssignments.find(({participantId:v})=>v===D),b=R?.participantId;R&&b&&Js({eventId:u?.eventId,structureId:U,...R,tournamentRecord:i,drawDefinition:c,participantId:b})}}else{let f=Ec({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:D})=>D===u.matchUpId),T=[1,2].map(D=>({...S.sides?.find(A=>A.sideNumber===D)||{},sideNumber:D}));S.sides=T;let y=S.sides.find(D=>D.sideNumber===h);if(y){let D=f.lineUp?.filter(U=>U?.participantId);y.lineUp=Sd({lineUp:D}),gt({tournamentId:i?.tournamentId,eventId:u?.eventId,matchUp:S,context:l,drawDefinition:c})}}}return{...C}}function PO(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===to&&u.roundNumber===2&&Math.min(...g.filter(Boolean)),h=I||g[e],S=I||g[1-e],T=a.source.structureId,{structure:y}=at({structureId:T,drawDefinition:c}),{matchUps:D}=Et({afterRecoveryTimes:!1,inContext:!0,drawDefinition:c,structure:y,event:d}),A=D.filter(H=>H.drawPositions?.includes(i)).filter(H=>{let q=H.sides.find(V=>V.drawPosition===i),$=H.matchUpStatus===vt||H.matchUpStatus===Mt&&!me(H);return q?.sideNumber===H.winningSide&&!$}),E=f===to&&A.length===0,{positionAssignments:M}=le({structureId:T,drawDefinition:c}),N=M?.find(H=>H.drawPosition===i)?.participantId,R=a.target.structureId,{positionAssignments:b}=le({structureId:R,drawDefinition:c}),v=b?.filter(({drawPosition:H})=>g.includes(H));if(v?.some(H=>H.participantId===N))return{...C};let x=v?.filter(H=>{let q=g.includes(H.drawPosition),$=!H.participantId&&!H.bye&&!H.qualifier;return q&&$}).map(H=>H.drawPosition),F=x?.includes(h),L=a.target.roundNumber>1&&x?.length,w=a.target.roundNumber===1&&F;if(I){let H=B();if(H.error)return _({result:H,stack:l})}else if(w){let H=W();if(H.error)return _({result:H,stack:l})}else if(N&&L){x.sort(ae);let H=x[0],q=Fn({participantId:N,structureId:R,drawPosition:H,inContextDrawMatchUps:r,sourceMatchUpStatus:o,tournamentRecord:s,drawDefinition:c,matchUpsMap:m,event:d});if(q.error)return _({result:q,stack:l})}else return _({result:{error:Os},context:{loserDrawPosition:i,loserTargetLink:a},stack:l});if(y?.seedAssignments&&y.structureId!==R){let H=y.seedAssignments.find(({participantId:$})=>$===N),q=H?.participantId;H&&q&&Js({eventId:u?.eventId,structureId:R,...H,tournamentRecord:s,drawDefinition:c,participantId:q})}if(p&&n){let H=p.sides?.find(q=>q.sideNumber===3-n);if(H?.lineUp){let{roundNumber:q,eventId:$}=u,{roundPosition:V}=p,K=q===1?2-V%2:1,z=m?.drawMatchUps?.find(({matchUpId:Q})=>Q===u.matchUpId),Y=[1,2].map(Q=>({...z.sides?.find(St=>St.sideNumber===Q)||{},sideNumber:Q}));z.sides=Y;let Z=z.sides.find(Q=>Q.sideNumber===K);Z&&(Z.lineUp=Sd({lineUp:H.lineUp}),gt({tournamentId:s?.tournamentId,matchUp:z,context:l,drawDefinition:c,eventId:$}))}}return{...C};function B(){let H="loserLinkFedFMLC";return E?_({result:W(),stack:H}):_({result:G(),stack:H})}function G(){let H=kr({drawPosition:S,structureId:R,tournamentRecord:s,drawDefinition:c,event:d});return _({result:H,stack:"assignLoserPositionBye"})}function W(){let H=N?Fn({drawPosition:h,participantId:N,structureId:R,inContextDrawMatchUps:r,sourceMatchUpStatus:o,tournamentRecord:s,drawDefinition:c,matchUpsMap:m,event:d}):{error:ee};return _({result:H,stack:"assignLoserDrawPosition"})}}function HS(t){let e="directParticipants",r=Rd(t);if(r.error)return _({result:r,stack:e});let n=Ca({matchUpStatus:t.matchUpStatus}),{dualWinningSideChange:o,projectedWinningSide:i,inContextDrawMatchUps:s,tournamentRecord:a,drawDefinition:c,matchUpStatus:u,dualMatchUp:p,matchUpsMap:m,winningSide:d,targetData:l,matchUpId:f,structure:g,matchUp:I,event:h}=t,S=!!I.collectionId,T=pr({structure:g}),y=I.drawPositions,D;if(S){let{matchUpTieId:U,matchUpsMap:A}=t,E=co({appliedPolicies:t.appliedPolicies,matchUpId:U,tournamentRecord:a,drawDefinition:c,matchUpsMap:A,event:h});if(D=E&&{tieMatchUpResult:E},y=s.find(({matchUpId:P})=>P===U)?.drawPositions,!o)return _({result:{...C,...D},stack:e})}if(T)return _({result:{...C,...D},stack:e});if(y){let U=i?i-1:d-1,A=1-U,E=y[U],M=y[A],{targetLinks:{loserTargetLink:P,winnerTargetLink:N,byeTargetLink:R},targetMatchUps:{winnerMatchUpDrawPositionIndex:b,loserMatchUpDrawPositionIndex:v,winnerMatchUp:O,loserMatchUp:x,byeMatchUp:F}}=l;if(O){let L=DO({sourceMatchUpStatus:n&&u||ue,winnerMatchUpDrawPositionIndex:b,sourceMatchUpId:f,inContextDrawMatchUps:s,projectedWinningSide:i,winningDrawPosition:E,tournamentRecord:a,winnerTargetLink:N,drawDefinition:c,winnerMatchUp:O,dualMatchUp:p,matchUpsMap:m,event:h});if(L.error)return _({result:L,stack:e})}if(x){let L=PO({sourceMatchUpStatus:n&&u||ue,loserMatchUpDrawPositionIndex:v,sourceMatchUpId:f,inContextDrawMatchUps:s,projectedWinningSide:i,loserDrawPosition:M,tournamentRecord:a,loserTargetLink:P,drawDefinition:c,loserMatchUp:x,winningSide:d,matchUpsMap:m,dualMatchUp:p,event:h});if(L.error)return _({result:L,stack:e})}if(F){let L=F.drawPositions||[],w=Math.min(...L.filter(Boolean)),B=R.target.structureId,G=kr({drawPosition:w,structureId:B,tournamentRecord:a,drawDefinition:c,event:h});if(G.error)return _({result:G,stack:e})}}else return _({result:{error:za},stack:e});return _({result:{...C,...D},stack:e})}function bd(t){let e="genPlayoffStructure";if(!t.drawDefinition)return _({result:{error:X},stack:e});let r=Ru(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}=at({structureId:n,drawDefinition:T});if(!y)return _({result:{error:Lt},stack:e});if(y.structureType===we||y.structures)return sO({sourceStructureId:y.structureId,...t,...r,drawDefinition:T});let{playoffRoundsRanges:D,playoffRounds:U}=r,{playoffPositionsReturned:A,error:E,playoffSourceRounds:M,playoffRoundsRanges:P}=CS(t);if(E)return _({result:{error:E},stack:e});let N=l?.length&&Object.assign({},...l),R=f||typeof l=="object"&&l.map(Y=>Object.keys(Y)).flat(),b=Array.isArray(R)&&R.map(Y=>!isNaN(Y)&&ut(Y)).filter(Boolean);if(b){if(!Array.isArray(b))return _({result:{error:k},context:{validRoundNumbers:b},stack:e});b.forEach(Y=>{if(!U?.includes(Y))return _({result:{error:k},context:{roundNumber:Y},stack:e})})}u&&u.forEach(Y=>{if(!A?.includes(Y))return _({result:{error:k},context:{playoffPosition:Y},stack:e})});let v=b||M,O=b?D:P,x=[],F=[];for(let Y of v??[]){let Z=O?.find(Se=>Se.roundNumber===Y);if(!Z)return _({result:{error:k},context:{roundNumber:Y},stack:e});let Q=Z.finishingPositions.length,st=Math.min(...Z.finishingPositions)-1,St=2,it=Y&&N?.[Y]&&St+N[Y]-1,jt=Pc({exitProfile:`0-${Y}`,addNameBaseToAttributeName:o,playoffStructureNameBase:i,finishingPositionOffset:st,playoffAttributes:c,exitProfileLimit:d,stage:pe,roundOffset:0,drawDefinition:T,sequenceLimit:it,stageSequence:St,drawSize:Q,idPrefix:g,isMock:I,uuids:S,finishingPositionNaming:s,finishingPositionLimit:a,roundOffsetLimit:p});if(jt.error)return _({result:jt,stack:e});let{structures:Ut,links:Ue}=jt;if(Ut?.length&&x.push(...Ut),Ue?.length&&F.push(...Ue),jt.structureId&&Y){let Se={linkType:Zn,source:{structureId:n,roundNumber:Y},target:{structureId:jt.structureId,feedProfile:yn,roundNumber:1}};F.push(Se)}}if(!x.length)return _({result:{error:k},info:"No structures generated",stack:e});T.structures.push(...x),T.links.push(...F);let{matchUps:L,matchUpsMap:w}=re({inContext:!0,drawDefinition:T}),B=x.map(({structureId:Y})=>Y),G=L?.filter(({structureId:Y})=>B.includes(Y)).map(Ie),W=w?.drawMatchUps?.filter(({matchUpId:Y})=>G?.includes(Y));if(W?.length){let Y=We({drawDefinition:T,event:h})?.tieFormat;Y&&W.forEach(Z=>{let{tieMatchUps:Q}=xa({matchUp:Z,tieFormat:Y,isMock:I});Object.assign(Z,{tieMatchUps:Q,matchUpType:Ht})})}L?.filter(Y=>gs({matchUp:Y})&&Y.structureId===n)?.forEach(Y=>{let{matchUpId:Z,score:Q,winningSide:st}=Y,St=nr({inContextDrawMatchUps:L,drawDefinition:T,matchUpId:Z}),it=HS({inContextDrawMatchUps:L,tournamentRecord:m,drawDefinition:T,matchUpsMap:w,winningSide:st,targetData:St,matchUpId:Z,structure:y,matchUp:Y,score:Q,event:h});it.error&&console.log(it.error)}),L?.filter(Y=>Y.matchUpStatus===Pt&&Y.structureId===n)?.forEach(Y=>{let{matchUpId:Z}=Y,Q=nr({inContextDrawMatchUps:L,drawDefinition:T,matchUpId:Z}),{targetLinks:{loserTargetLink:st},targetMatchUps:{loserMatchUpDrawPositionIndex:St,loserMatchUp:it}}=Q;if(st&&it){let jt=st.target.structureId,Ut=it.drawPositions[St],Ue=kr({drawPosition:Ut,structureId:jt,tournamentRecord:m,drawDefinition:T,event:h});Ue.error&&console.log(Ue.error)}});let $=[],V=Ki({inContextDrawMatchUps:L,drawDefinition:T,matchUpsMap:w}).goesToMap,{structure:K}=at({drawDefinition:t.drawDefinition,structureId:n}),{matchUps:z}=Et({structure:K});return z.forEach(Y=>{let Z=V?.loserMatchUpIds[Y.matchUpId];if(Z&&Y.loserMatchUpId!==Z){Y.loserMatchUpId=Z;let st={tournamentId:m?.tournamentId,eventId:t.event?.eventId,context:e,matchUp:Y};$.push(st)}let Q=V?.winnerMatchUpIds[Y.matchUpId];if(Q&&Y.winnerMatchUpId!==Q){Y.winnerMatchUpId=Q;let st={tournamentId:m?.tournamentId,eventId:t.event?.eventId,context:e,matchUp:Y};$.push(st)}}),{structures:x,matchUpModifications:$,links:F,drawDefinition:T,...C}}function WS({element:t}){if(!t)return{error:k};if(!t.timeItems)return{};if(!Array.isArray(t.timeItems))return{error:k};let e=(r,n)=>(o,i)=>(i[r]&&(o[i[r]]=i[n]),o);return t.timeItems.reduce(e("itemType","itemValue"),{})}function Qn(t){let{duplicateValues:e=!0,creationTime:r=!0,removePriorValues:n,timeItem:o}=t;if(!o)return{error:Jl};let i=vh(t);if(i.error)return i;if(!(It(o)&&te(o.itemType)&&Object.keys(o).includes("itemValue")))return{error:Xl};if(!i.timeItems)i.timeItems=[];else if(CG({element:i,duplicateValues:e,timeItem:o}))return{...C};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),{...C}}function CG({element:t,duplicateValues:e,timeItem:r}){let{itemType:n,itemSubTypes:o,itemValue:i}=r,s=n&&Xr({itemSubTypes:o,itemType:n,element:t})?.timeItem;return s&&JSON.stringify(s?.itemValue)===JSON.stringify(i)&&!e}function Cg({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=Ao({tournamentRecord:r,participantId:o});return s.error?s:Qn({element:s.participant,removePriorValues:e,duplicateValues:n,creationTime:t,timeItem:i})}function bc(t){let{removePriorValues:e,tournamentRecord:r,duplicateValues:n,creationTime:o,timeItem:i}=t;if(!r)return{error:j};let s=Qn({element:r,removePriorValues:e,duplicateValues:n,creationTime:o,timeItem:i});if(s.error)return s;let a=WS({element:r});return dt({payload:{timeItemValues:a,tournamentId:r.tournamentId},topic:Yi}),s}function Xi(t){let{removePriorValues:e,duplicateValues:r,creationTime:n,timeItem:o,event:i}=t;return i?Qn({removePriorValues:e,duplicateValues:r,element:i,creationTime:n,timeItem:o}):{error:Pr}}function wD(t){return vg({...t,itemType:"attachConsolationStructures"})}function bg(t){return vg({...t,itemType:"attachPlayoffStructures"})}function vg({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:k},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:nf},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),Ki({drawDefinition:n});let f=o.map(h=>Et({structure:h})?.matchUps||[]).flat();vo({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:D,...U}=h[y.matchUpId].matchUp;if(Object.assign(y,U),D?.length){let A={};D.forEach(E=>h[E.matchUpId]=E),y.tieMatchUps.forEach(E=>Object.assign(E,A[E.matchUpId]))}h[y.matchUpId].matchUp=y,gt(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(Fr("structureId"));if(r){let S={itemValue:{structureIds:g,drawId:n.drawId},itemType:t};Qn({element:r,timeItem:S})}return{...C,addedStructureIds:I}}function Yp(t){let{structures:e,links:r,matchUpModifications:n,error:o}=bd(t);if(o)return{error:o};let i=t.drawDefinition;return bg({tournamentId:t.tournamentRecord?.tournamentId,eventId:t.event?.eventId||t.eventId,matchUpModifications:n,drawDefinition:i,structures:e,links:r})}function Ji(t){let e=nt(t,[{_anyOf:{[De]:!1,[Re]:!1,[Le]:!1,[Jo]:!1},[gf]:!0}]);if(e.error)return e;let r=[],n=t.drawDefinition??t.event??((t.tournamentId||!t.tournamentRecords)&&t.tournamentRecord);if(n){let o=NO(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=NO(t,s);if(a.error)return a;r.push(...a?.applied??[])}}else return{error:j};return r.length?{...C,applied:r}:{error:FI}}function NO(t,e){let r=yt(t).appliedPolicies??{};e.extensions||(e.extensions=[]);let n=[],o=Object.keys(t.policyDefinitions);if(!o.length)return{error:Zu};for(let i of o)if(!r[i]||t.allowReplacement){let s=t.policyDefinitions[i];if(!s)continue;if(!It(s))return{error:k};let{policyName:a,...c}=s;if(!c||!Object.keys(c).length||a&&!te(a))return{error:k};r[i]=t.policyDefinitions[i],n.push(i)}return n?.length?{...At({element:e,extension:{name:su,value:r}}),applied:n}:{applied:n,error:FI}}function Og({tournamentRecord:t,drawDefinition:e,flightProfile:r,drawName:n,drawId:o,event:i}){if(!n||typeof n!="string")return _({result:{error:k},context:{drawName:n}});r||(r=Wt({event:i}).flightProfile);let s=r?.flights?.find(a=>a.drawId===o);if(s){s.drawName=n;let a={name:cn,value:{...r,flights:r.flights}};Co({event:i,extension:a})}return e&&(e.drawName=n,Ot({tournamentId:t?.tournamentId,drawDefinition:e})),!s&&!e?{error:X}:{...C,flight:s}}function LD({tournamentRecord:t,drawDefinition:e,drawUpdates:r,drawId:n,event:o}){if(!It(r))return{error:k};let i=Wt({event:o}).flightProfile,s=r.drawName&&Og({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:cn,value:{...i,flights:i.flights}};Co({event:o,extension:c})}return e&&(r.policyDefinitions&&Ji({policyDefinitions:r.policyDefinitions,drawDefinition:e}),Ot({tournamentId:t?.tournamentId,drawDefinition:e})),{...C}}function FD({tournamentRecord:t,removeScheduling:e,drawDefinition:r}){if(!r)return{error:X};let n=Ee({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||![ct,et].includes(c))&&(s.positionAssignments=a.map(d=>(delete d.participantId,d)),s.seedAssignments=[]);let{matchUps:p,isRoundRobin:m}=Et({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!==Pt&&Object.assign(I,Ou),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&&![xo,Mi,Ys,bU,qs,$s].includes(h.itemType))),gt({tournamentId:t?.tournamentId,context:"resetDrawDefiniton",drawDefinition:r,matchUp:I})}}}let i=(r.structures||[]).map(({structureId:s})=>s);return Ot({drawDefinition:r,structureIds:i}),{...C}}function Lu({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}=Nu({drawDefinition:o}),p=r[i],d=(o?.structures||[]).map(D=>{let{stage:U,stageSequence:A,structureId:E}=D,M=Gs[U],{inContextStructureMatchUps:P}=ba({drawDefinition:o,structure:D,event:p}),N=P?.filter(({winningSide:q})=>q),R=N.filter(Boolean).length||0;a+=R,c+=P.length-a;let b=Math.max(N.filter(({roundNumber:q})=>q===1).map(({roundPosition:q})=>q)),{positionAssignments:v}=Ct({structure:D}),O=v?.filter(({participantId:q})=>q);s+=O?.length??0;let x=(v?.length??0)-(O?.length??0),{roundMatchUps:F,roundProfile:L,roundNumbers:w,maxMatchUpsCount:B}=je({matchUps:P}),G=L&&Object.keys(L).filter(q=>!L[q].inactiveRound).map(q=>parseInt(q)),W=L&&Object.keys(L).filter(q=>L[q].inactiveRound).map(q=>parseInt(q)),H=L&&Object.values(L).every(q=>q.inactiveRound);return{positionsAssignedCount:O?.length??0,maxWinningSideFirstRoundPosition:b,unassignedPositionsCount:x,inactiveStructure:H,maxMatchUpsCount:B,inactiveRounds:W,roundMatchUps:F,activeRounds:G,roundNumbers:w,roundProfile:L,structureId:E,stageSequence:A,orderNumber:M,stage:U}}),l=d.find(D=>D.orderNumber===2&&D.stageSequence===1),f=d.filter(({inactiveStructure:D})=>!D).length,{links:g}=Ks({structureId:l.structureId,drawDefinition:o}),I=ut(l.activeRounds[0])===1&&l.activeRounds.length===1&&f===1,h=d?.every(({inactiveStructure:D})=>D),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}),{...C,drawsAnalysis:e}}function kD({matchPlayDrawPositions:t=!0,tournamentRecord:e,drawDefinition:r,drawId:n}){if(!e)return{error:j};if(!r)return{error:X};let o=[],{drawsAnalysis:i}=Lu({tournamentRecord:e});if(i.canBePruned.includes(n)){let s=i.matchPlay.includes(n),a=i.drawAnalysis[n],{structures:[c]}=ln({stageSequence:1,drawDefinition:r,stage:et}),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(Ie),d=p.map(Ie).filter(l=>!m.includes(l));if(s){let l=o.filter(({roundNumber:T})=>!u.inactiveRounds.includes(T)).filter(({winningSide:T})=>T),f=l.map(Ie),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}jn({tournamentId:e?.tournamentId,matchUpIds:d,drawDefinition:r}),Ot({drawDefinition:r})}return{...C,matchUps:o}}function GD({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:_s};if(!o)return{error:hr};if(a){let c=kr({tournamentRecord:t,drawDefinition:e,drawPosition:n,structureId:o,event:s});if(c.error)return c}else{if(i)return{error:sp};{let c=Fn({tournamentRecord:t,drawDefinition:e,participantId:r,drawPosition:n,structureId:o,event:s});if(c.error)return c}}return{...C}}function jS(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:Lt};let o=r.structures?.find(c=>c.structureId===n);if(!o)return{error:Lt};let i=o?.matchUps,s=i?.find(c=>!!c.roundPosition);if(o.structures||s||o.finishingPosition===Wi)return{error:Qo};let a=i.filter(({roundNumber:c})=>t.roundNumbers?.includes(c)).map(Ie);return e=e.filter(c=>!a.includes(c)),t.roundNumbers&&!e.length&&(e=a),{existingMatchUps:i,matchUpIds:e,structureId:n,structure:o}}function VD(t){let e=nt(t,[{[Le]:!0},{[ic]:{[oc]:!1,roundNumbers:!1},[wr]:k,[ar]:ir}]);if(e.error)return e;let{removeIncomplete:r=!1,removeUnAssigned:n=!0,removeCompleted:o=!1,tournamentRecord:i,drawDefinition:s,event:a}=t,c=jS(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||me({score:S})){if(!T&&!r)return!1;l.push(h)}else if(!n)return!1;return d?.includes(h)})??[],g=f.map(Ie),I=f.map(({tieMatchUps:h})=>h?.map(Ie)).filter(Boolean).flat();if(g.length){u.matchUps=(u.matchUps??[]).filter(({matchUpId:T})=>!g.includes(T)),jn({tournamentId:i?.tournamentId,matchUpIds:[...I,...g],action:"deleteAdHocMatchUps",eventId:a?.eventId,drawDefinition:s});let h=pt(u.matchUps.map(Fr("roundNumber"))),S=CC(h);if(S.length){S.reverse();for(let T of S)u.matchUps.forEach(y=>{y.roundNumber&&y.roundNumber>T&&(y.roundNumber-=1,gt({tournamentId:i?.tournamentId,context:["adHoc round deletion"],eventId:a?.eventId,drawDefinition:s,matchUp:y}))})}if(l.length){u.positionAssignments=pt(u.matchUps.flatMap(U=>(U.sides??[]).map(A=>A.participantId)).filter(Boolean)).map(U=>({participantId:U}));let T=u?.matchUpFormat??s?.matchUpFormat??a?.matchUpFormat,{matchUps:y}=Et({afterRecoveryTimes:!1,inContext:!0,structure:u,event:a}),D=Md({positionAssignments:u.positionAssignments,tournamentRecord:i,drawDefinition:s,matchUpFormat:T,matchUps:y,event:a});D.error&&console.log(D)}Ot({structureIds:[p],eventId:a?.eventId,drawDefinition:s})}return!g.length&&d.length?{error:ap}:{...C,deletedMatchUpsCount:[...g,...I].length}}function BD({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:ot},info:"roundNumber required"});let s=at({drawDefinition:r,structureId:n});if(s.error)return s;let a=s.structure;return a?.structures?{error:Qo}:pr({structure:a})?bG({tournamentId:e.tournamentId,removeCompletedMatchUps:t,eventId:i.eventId,drawDefinition:r,roundNumber:o,structure:a}):(console.log("not implemented"),{...C})}function bG({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(ae).includes(n)){let m=s.filter(d=>{let l=d.roundNumber===n&&(!ie.includes(d.matchUpStatus)||t);return l&&(c.push(d.matchUpId),d.tieMatchUps&&a.push(...d.tieMatchUps.map(Ie))),!l});c.length&&(jn({matchUpIds:[...a,...c],drawDefinition:e,tournamentId:r,eventId:i}),m.some(l=>l.roundNumber===n)||(m.forEach(l=>{l.roundNumber>n&&(l.roundNumber-=1,gt({drawDefinition:e,tournamentId:r,eventId:i,matchUp:l}))}),u=!0),o.matchUps=m)}return{deletedMatchUpsCount:c.length,roundRemoved:u,...C}}function vd(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:hr};if(!Lr(o))return{error:k,info:ko("matchUps")};let a=n.structures?.find(l=>l.structureId===s);if(!a)return{error:Lt};let u=(a?.matchUps).find(l=>!!l.roundPosition);if(a.structures||u||a.finishingPosition===Wi)return{error:Qo};let p=fe({tournamentRecord:r,inContext:!1})?.matchUps?.map(Ie)??[],m=o.map(Ie);if(xe(p,m))return{error:wE,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||(vo({tournamentId:r?.tournamentId,matchUps:[...d,...o],eventId:i?.eventId,drawDefinition:n}),Ot({drawDefinition:n,structureIds:[s]})),{...C}}function HD({tournamentRecord:t,drawDefinition:e,drawPosition:r,structureId:n,subOrder:o,event:i}){if(!e)return{error:X};if(!n)return{error:hr};if(!r)return{error:_s};let{structure:s}=at({drawDefinition:e,structureId:n});if(!s)return{error:Lt};let a=s;s.structures&&s.structureType===we&&(a=s.structures?.find(g=>g.positionAssignments?.find(I=>I.drawPosition===r)));let c=a?.positionAssignments,u=c?.find(g=>g.drawPosition===r);u&&At({element:u,extension:{name:uc,value:o}});let d=(i?.eventType===Ht||e.matchUpType===Ht||(i?.tieFormat??e?.tieFormat??s?.tieFormat))&&{matchUpTypes:[Ht]},{matchUps:l}=Et({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]}),{...C}}var tP={};Qt(tP,{addGoesTo:()=>Ki,allPlayoffPositionsFilled:()=>AS,checkValidEntries:()=>xd,findDrawDefinition:()=>KS,getAssignedParticipantIds:()=>Oi,getAvailableMatchUpsCount:()=>Od,getAvailablePlayoffProfiles:()=>Ru,getDrawDefinitionTimeItem:()=>Oh,getDrawParticipantRepresentativeIds:()=>qS,getDrawStructures:()=>ln,getDrawTypeCoercion:()=>Fu,getEligibleVoluntaryConsolationParticipants:()=>YS,getMatchUpsMap:()=>Ee,getParticipantIdFinishingPositions:()=>$S,getPositionAssignments:()=>qp,getPositionsPlayedOff:()=>Nc,getSeedingThresholds:()=>mS,getSeedsCount:()=>ku,getStructureSeedAssignments:()=>en,getTeamLineUp:()=>ls,getValidGroupSizes:()=>wp,isAdHoc:()=>pr,isCompletedStructure:()=>si,isValidForQualifying:()=>aT,positionActions:()=>sT});function YS({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=[et,pe];r&&f.push(ct);let g=l?.eventType?{matchUpTypes:[l.eventType]}:void 0,I=a?.matchUpType?{matchUpTypes:[a.matchUpType]}:void 0,h=e&&l?qn({contextFilters:{stages:f},matchUpFilters:g,tournamentRecord:s,inContext:!0,event:l})?.matchUps??[]:Je({contextFilters:{stages:f},matchUpFilters:I,tournamentRecord:s,inContext:!0,drawDefinition:a})?.matchUps??[],T=Ni({stage:Be,drawDefinition:a}).map(({participantId:w})=>w),y={},D={},U={},A={};o||(o=_o({policyTypes:[fh],tournamentRecord:s,drawDefinition:a,event:l}).policyDefinitions);let E=o?.[fh];t=t.length&&t||E?.excludedMatchUpStatuses||[],e=e??E?.includeEventParticipants,m=m??E?.allEntries,n=n??E?.finishingRoundLimit,i=i??E?.roundNumberLimit,c=c??E?.matchUpsLimit,u===void 0&&(u=E?.requirePlay!==void 0?E.requirePlay:!0),p===void 0&&(p=E?.requireLoss!==void 0?E.requireLoss:!0),d=d??E?.winsLimit;for(let w of h){if(u&&w.winningSide&&![1,2].includes(w.winningSide)&&w.matchUpStatus!==he||w.finishingRound&&n&&w.finishingRound>=n||w.finishingRound&&i&&w.finishingRound<=i)continue;let B=w.sides?.find(({sideNumber:W})=>w.winningSide&&W===3-w.winningSide),G=w.sides?.find(({sideNumber:W})=>w.winningSide&&W===w.winningSide);if(w.sides?.forEach(W=>{let H=W?.participant?.participantId;H&&(U[H]=W.participant,w.matchUpStatus===he&&!u&&(D[H]=W.participant,y[H]||(y[H]=0),(!w.matchUpStatus||!t.includes(w.matchUpStatus))&&(y[H]+=1)))}),B?.participant){let W=B.participant.participantId;D[W]=B.participant,y[W]||(y[W]=0),w.matchUpStatus&&!t.includes(w.matchUpStatus)&&(y[W]+=1)}if(G?.participant){let W=G.participant.participantId;A[W]||(A[W]=0),A[W]+=1,y[W]||(y[W]=0),w.matchUpStatus&&!t.includes(w.matchUpStatus)&&(y[W]+=1)}}let M=s?.participants&&!u&&!p&&m,P=M?((e&&l?l.entries:a.entries)??[]).filter(w=>![io,tn].includes(w.entryStatus)).map(({participantId:w})=>w):[],N=Object.keys(D),R=M?(s?.participants??[]).filter(({participantId:w})=>P.includes(w)):p&&Object.values(D)||Object.values(U),b=w=>!p||N.includes(w),v=w=>!u||(y[w]||0)>=0,O=w=>!d||(A[w]||0)<=d,x=w=>!c||y[w]<=c,F=w=>!T.includes(w);return{eligibleParticipants:R.filter(w=>b(w.participantId)&&v(w.participantId)&&O(w.participantId)&&x(w.participantId)&&F(w.participantId)).map(w=>({...w,individualParticipants:w.individualParticipantIds?.map(B=>s?.participants?.find(G=>G.participantId===B))})),losingParticipantIds:N,...C}}function Od(t){let e=nt(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:hr};let i=r.structures?.find(g=>g.structureId===o);if(!i)return{error:Lt};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:Qo};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{...C,availableMatchUpsCount:f,lastRoundNumber:c,roundMatchUpsCount:p}}function qS({drawDefinition:t}){let e=mt({name:"participantRepresentatives",element:t});return e.error?e:{representativeParticipantIds:e.extension?.value||[]}}function MO({tournamentParticipants:t,drawDefinition:e,event:r}){if(!e)return{error:X};let n=re({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 $S({byeAdvancements:t=!1,tournamentRecord:e,drawDefinition:r}){if(!r)return{error:X};let{participantIds:n,participantIdMatchUps:o}=MO({tournamentParticipants:e?.participants,drawDefinition:r}),i=n?.map(s=>{let c=o[s].filter(d=>[ue,Pt].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 Go({tournamentRecords:t,tournamentRecord:e,tournamentId:r,drawId:n}){if(!e&&!t)return{error:j};if(!n)return{error:on};if(!e&&t){if(typeof r!="string"&&(r=BS({tournamentRecords:t,drawId:n}),!r))return{error:la};if(e=t[r],!e)return{error:j}}let o=e&&He({tournamentRecord:e,drawId:n});return o?.drawDefinition?{drawDefinition:o.drawDefinition,event:o.event,tournamentRecord:e,...C}:_({result:{error:Dr},stack:"findDrawDefinition"})}function KS(t){let{drawDefinition:e,error:r}=Go(t);return r?{error:r}:{drawDefinition:J(e)}}function _g({targetRoundNumber:t,finishingPosition:e,drawDefinition:r,structureId:n,linkType:o}){let{links:i}=Ks({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}=at({structureId:p,drawDefinition:r});if(!(e&&m?.finishingPosition!==e))return u}).filter(Boolean);return{sourceStructureIds:a.map(({source:u})=>u.structureId),relevantLinks:a}}function RO({tournamentParticipants:t,returnParticipants:e,drawPosition:r,participant:n,drawId:o,event:i}){let s=i?.entries?.filter(({entryStatus:a})=>[tn,Pi].includes(a)).map(({participantId:a})=>a)||[];if(s.length){let a=n.individualParticipantIds,c=e?t.filter(({participantId:m})=>s.includes(m)):void 0,u=e?t.filter(({participantId:m})=>a.includes(m)):void 0;return{validModifyAssignedPairAction:rt({payload:{participantId:n.participantId,replacementIndividualParticipantId:void 0,existingIndividualParticipantId:void 0,drawPosition:r,drawId:o},method:Kv,availableIndividualParticipantIds:s,availableIndividualParticipants:c,existingIndividualParticipantIds:a,existingIndividualParticipants:u,type:yg},!1,!1,!0)}}return{}}function _i(t){let{inContextDrawMatchUps:e,targetData:r,drawDefinition:n,relevantLink:o}=t;if(o?.linkCondition===to&&r?.matchUp?.matchUpStatus===Pt)return!1;let{targetMatchUps:{loserMatchUp:s,winnerMatchUp:a},targetLinks:c}=r,u=[Mt,vt].includes(s?.matchUpStatus),p=a?.drawPositions?.filter(Boolean).length||0;if(s?.winningSide&&!u||a?.winningSide&&p===2&&(!a.feedRound||![vt,Mt].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&&_i({relevantLink:c?.loserTargetLink,targetData:m,inContextDrawMatchUps:e,drawDefinition:n});return!!(d&&_i({targetData:d,inContextDrawMatchUps:e,drawDefinition:n})||l)}var zS={[yo]:{policyName:"positionActionsDefault",enabledStructures:[{stages:[ct,et],stageSequences:[1],enabledActions:[],disabledActions:[]},{stages:[],stageSequences:[],enabledActions:[Mu,ta,Gp,Zs],disabledActions:[]}],disbledStructures:[],otherFlightEntries:!1,activePositionOverrides:[]}};var xg="positionAction",QS="matchUpAction";function XS({actionType:t=xg,appliedPolicies:e,drawDefinition:r,structure:n}){let o=t===xg&&yo||t===QS&&ze,i=t===xg&&zS||t===QS&&qU,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 jD({activePositionOverrides:t,activeDrawPositions:e,action:r}){return r&&t.includes(r)?!0:!e.length}function JS({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 Gn({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 YD="replaceTieMatchUpParticipantId",qD="assignTieMatchUpParticipantId",ZS="removeTieMatchUpParticipantId",$D="assignMatchUpSideParticipant",CO="removeMatchUpSideParticipant",KD="substituteParticipant",tT="REMOVE_SUBSTITUTION",zD="REPLACE_PARTICIPANT",wg="REMOVE_PARTICIPANT",eT="setMatchUpStatus",rT="SUBSTITUTION",QD="SCHEDULE",vG="PENALTY",nT="REFEREE",XD="STATUS",oT="START",JD="SCORE",iT="END",bO={REPLACE_TEAM_POSITION_METHOD:YD,ASSIGN_TEAM_POSITION_METHOD:qD,REMOVE_TEAM_POSITION_METHOD:ZS,REPLACE_PARTICIPANT:zD,SUBSTITUTION_METHOD:KD,REMOVE_SUBSTITUTION:tT,REMOVE_PARTICIPANT:wg,SCHEDULE_METHOD:eT,SUBSTITUTION:rT,SCHEDULE:QD,PENALTY:vG,REFEREE:nT,STATUS:XD,SCORE:JD,START:oT,END:iT};function vO({specifiedPolicyDefinitions:t,inContextDrawMatchUps:e,matchUpParticipantIds:r,matchUpActionsPolicy:n,inContextMatchUp:o,policyActions:i,enforceGender:s,participantId:a,sideNumber:c,matchUpId:u,matchUp:p,drawId:m,side:d}){let l=[],f=o.sides?.find(F=>F.participant),g=o.gender===Cr&&o.sideNumber&&o.sides?.filter(F=>F.particiapntId).length===1&&f?.participant?.person?.sex,I=o.matchUpType,S=(s??n?.participants?.enforceGender)!==!1?o.gender:void 0,y=o.sides?.flatMap(F=>F.participant?.individualParticipants||F.participant).filter(Boolean)?.map(ht),D=o.sides?.filter(F=>!c||F.sideNumber===c).flatMap(F=>F.participant?.individualParticipants||F.participant).filter(Boolean),U=D?.map(ht),E=e?.find(F=>F.matchUpId===o.matchUpTieId)?.sides?.map(F=>F?.participant?.individualParticipants?.filter(({participantId:L,person:w})=>!U?.includes(L)&&(!S||S===Mn||w.sex===S||S===Cr&&!g||g&&w.sex!==g))),M=c?E?.[c-1]:E?.map((F,L)=>({participants:F,sideNumber:L+1})),P=c?E?.[c-1]?.map(ht):E?.map((F,L)=>({participants:F?.map(ht),sideNumber:L+1})),N=c&&(se(Pa)(I)&&!U?.length||se(qi)(I)&&(U?.length??0)<2)||!c&&(se(Pa)(I)&&(U?.length??0)<2||se(qi)(I)&&(U?.length??0)<4),R=P?.filter(F=>!y?.includes(F)),b=M?.filter(({participantId:F})=>R.includes(F));if(N&&R?.length&&l.push({availableParticipantIds:R,method:qD,availableParticipants:b,type:Us,payload:{participantId:void 0,tieMatchUpId:u,sideNumber:c,drawId:m}}),U?.length&&(!me(p)||d?.substitutions?.length)&&l.push({method:ZS,type:wg,existingParticipantIds:U,payload:{participantId:void 0,tieMatchUpId:u,drawId:m}}),b?.length&&(!c&&U?.length||c&&d?.participant)&&l.push({availableParticipantIds:R,method:YD,availableParticipants:b,type:zD,existingParticipantIds:U,payload:{existingParticipantId:void 0,participantId:void 0,tieMatchUpId:u,drawId:m}}),Gn({policyActions:i,action:tT})&&d?.substitutions?.length){let F=d.participant?.participantType===Tt&&[d.participantId]||d.participant?.participantType===lt&&d.participant.individualParticipantIds||[],L=d.substitutions.map(w=>w.participantId).filter(w=>F.includes(w));(!a||L.includes(a))&&l.push({method:ZS,type:tT,substitutedParticipantIds:L,payload:{participantId:void 0,tieMatchUpId:u,drawId:m}})}let v=t?.[ze],O=v?.substituteWithoutScore,x=v?.substituteAfterCompleted;if(Gn({policyActions:i,action:rT})&&r.length===2&&(!c&&U?.length||c&&d?.participant)&&(O||me(p))&&(x||p.matchUpStatus&&!ie.includes(p.matchUpStatus))&&D?.length&&M.length){let F=D.map(ht);l.push({info:"list of team players available for substitution",method:KD,availableParticipantIds:P,existingParticipantIds:F,availableParticipants:M,existingParticipants:D,type:rT,payload:{substituteParticipantId:void 0,existingParticipantId:void 0,sideNumber:c,matchUpId:u,drawId:m}})}return l}function OO({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(E=>E.type===Us)?.availableParticipantIds,f=i?.[yo]?.otherFlightEntries,g=i?.[yo]?.restrictQualifyingAlternates,I=(s.entries??[]).filter(({entryStage:E})=>!g||(p.stage===ct?E===ct:E!==ct)).sort((E,M)=>(E.entryPosition??1/0)-(M.entryPosition??1/0)).map(({participantId:E})=>E).filter(Boolean),{allPositionedParticipantIds:h}=Dh({drawDefinition:s}),S=n.map(E=>E.participantId).filter(Boolean),T=I.filter(E=>p.stage&&[ct,et,pe].includes(p.stage)?!h?.includes(E):!S.includes(E)),D=(d?.entries??[]).filter(E=>E.entryStatus===Jr&&ZD({restrictQualifyingAlternates:g,structure:p,entry:E})&&(p.stage&&[ct,et,pe].includes(p.stage)?!h?.includes(E.participantId):!S.includes(E.participantId))).sort((E,M)=>(E.entryPosition??1/0)-(M.entryPosition??1/0)).map(E=>E.participantId),U=pt(T.concat(D));if(f){let M=(d?Wt({event:d}).flightProfile:void 0)?.flights?.filter(P=>P.drawId!==m).map(P=>P.drawEntries.filter(N=>N.participantId&&![io,tn,Pi].includes(N.entryStatus)&&!I.includes(N.participantId)).map(({participantId:N})=>N)).flat().filter(Boolean);M?.length&&U.push(...M)}l?.length&&(U=U.filter(E=>!l.includes(E)));let A=o?t?.filter(E=>U.includes(E.participantId)):void 0;return A?.forEach(E=>{let M=(s.entries??[]).find(P=>P.participantId===E.participantId);E.entryPosition=M?.entryPosition}),A?.sort((E,M)=>(E.entryPosition||1/0)-(M.entryPosition||1/0)),U.length?{validAlternatesAction:rt({payload:{drawId:m,structureId:u,drawPosition:a},willDisableLinks:e,method:qv,availableAlternatesParticipantIds:U,type:Ag,availableAlternates:A})}:{}}function ZD({restrictQualifyingAlternates:t,structure:e,entry:r}){let{stage:n}=e;if(!r.entryStage||r.entryStage===n||n===ct&&!t||r.entryStage===et&&n===Ve)return!0}function _O({eventEntries:t,structure:e}){let r=o=>o.entryStatus===Jr&&ZD({structure:e,entry:o}),n=(o,i)=>(o.entryPosition||1/0)-(i.entryPosition||1/0);return t.filter(r).sort(n).map(ht)}function xO({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??[],g=u.sides?.find(M=>M.sideNumber===s)?.participantId,I=l.filter(({roundNumber:M})=>M===u.roundNumber),h=o?.entries?.filter(({entryStatus:M})=>M&&ni.includes(M)).map(ht)??[],S=I.map(M=>(M.sides??[]).flatMap(ht)).flat().filter(Boolean),T=h.filter(M=>!r.includes(M)&&(!t||!S.includes(M))),y=e?.filter(M=>T?.includes(M.participantId)).map(M=>J(M,void 0,!0));y?.forEach(M=>{let P=(o.entries??[]).find(N=>N.participantId===M.participantId);M.entryPosition=P?.entryPosition}),T.length&&d.push({payload:{drawId:p,matchUpId:a,structureId:i,sideNumber:s},method:$D,type:Us,availableParticipantIds:T,participantsAvailable:y});let D=m?.entries??[],U=_O({eventEntries:D,structure:c}),A=pt(h.concat(U));if(n){let P=(m?Wt({event:m}):void 0)?.flights?.filter(N=>N.drawId!==p).flatMap(N=>N.drawEntries.filter(R=>R.participantId&&![io,tn,Pi].includes(R.entryStatus)).map(({participantId:R})=>R)).filter(Boolean);P?.length&&A.push(...P)}A=A.filter(M=>!r.includes(M)&&!T.includes(M)&&(!t||!S.includes(M)));let E=e?.filter(M=>A.includes(M.participantId)).map(M=>J(M,void 0,!0));if(E?.forEach(M=>{let P=(o.entries??[]).find(N=>N.participantId===M.participantId);M.entryPosition=P?.entryPosition}),E?.sort((M,P)=>(M.entryPosition||1/0)-(P.entryPosition||1/0)),A.length&&d.push({payload:{drawId:p,matchUpId:a,structureId:i,sideNumber:s},availableParticipantIds:A,participantsAvailable:E,method:$D,type:Jr}),!me(u)&&s&&g){d.push({payload:{drawId:p,matchUpId:a,structureId:i,sideNumber:s},method:CO,type:wg});let M=L=>L.sides.map(ht),P=({matchUpId:L})=>L!==u.matchUpId,N=L=>!me(L),R=u.sides?.find(L=>L.sideNumber!==s)?.participantId,v=l.filter(({roundNumber:L})=>L!==u.roundNumber).filter(P).map(M),O=[R,...v.filter(L=>L.includes(g)).flat()].filter(Boolean),x=L=>!O.flat().includes(L),F=I.filter(N).filter(P).map(M).flat().filter(x);if(F.length){let L=e?.filter(w=>F.includes(w.participantId)).map(w=>J(w,void 0,!0));d.push({payload:{participantIds:[g],roundNumber:u.roundNumber,structureId:i,sideNumber:s,matchUpId:a,drawId:p},swappableParticipantIds:F,method:zv,type:Bp,swappableParticipants:L})}}return d}function _d(t){if(!t)return{error:k};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&&te(t.tournamentId)&&t.tournamentRecords?.[t.tournamentId]);if(!u)return{error:j};if(!c||!te(c))return{error:er};if(a&&![1,2].includes(a))return _({result:{error:k},context:{sideNumber:a}});if(!e){let st=(fe({tournamentRecord:u}).matchUps??[]).find(it=>it.matchUpId===c);r=(u?.events??[]).find(it=>it.eventId===st?.eventId);let St=(r?.drawDefinitions??[]).find(it=>it.drawId===st?.drawId);St&&(e=St)}if(!e)return{error:X};let p=$t({withIndividualParticipants:!0,tournamentRecord:u}).participants,{drawId:m}=e,{matchUp:d,structure:l}=Gt({drawDefinition:e,matchUpId:c,event:r});if(!d)return{error:_e};let f=yt({tournamentRecord:u,drawDefinition:e,structure:l,event:r}).appliedPolicies??{};Object.assign(f,o??{});let g=f?.[yo]?.otherFlightEntries,I=f?.[ze]??ys[ze],{enabledStructures:h}=XS({actionType:QS,appliedPolicies:f,drawDefinition:e,structure:l}),{policyActions:S}=JS({enabledStructures:h,drawDefinition:e,structure:l}),T=t.matchUpsMap??Ee({drawDefinition:e}),y=t.inContextDrawMatchUps??re({tournamentParticipants:p,inContext:!0,drawDefinition:e,matchUpsMap:T,event:r}).matchUps,D=y?.find(Q=>Q.matchUpId===c),U=a&&D?.sides?.find(Q=>Q.sideNumber===a),A=D?.sides?.map(Q=>Q.participantId||Q.participant?.participantid).filter(Boolean)??[],{assignedPositions:E,allPositionsAssigned:M}=le({structure:l}),{structureId:P}=l??{},N=[];if(!P)return{validActions:N};let R=pr({structure:l}),b=d.collectionId;if(R&&!b){let Q=xO({restrictAdHocRoundParticipants:n,tournamentParticipants:p,matchUpParticipantIds:A,otherFlightEntries:g,drawDefinition:e,structureId:P,sideNumber:a,matchUpId:c,structure:l,matchUp:d,drawId:m,event:r});N.push(...Q)}let v=si({drawDefinition:e,structure:l}),O=E?.filter(Q=>Q.participantId).map(Q=>Q.drawPosition),x=E?.filter(Q=>Q.bye).map(Q=>Q.drawPosition),F=d.matchUpStatus===Pt||!b&&d.drawPositions?.reduce((Q,st)=>x?.includes(st)||Q,!1);if(F)return{validActions:N,isByeMatchUp:F};Gn({policyActions:S,action:nT})&&N.push({type:nT,payload:{matchUpId:c}});let L=!Ca({matchUpStatus:d.matchUpStatus}),w=f?.scoring?.structures,B=l?.stage&&w?.stage&&w?.stage[l.stage],G=l?.stageSequence&&B?.stageSequence&&B.stageSequence[l.stageSequence],H=!(f?.scoring?.requireAllPositionsAssigned||B?.requireAllPositionsAssigned||G?.requireAllPositionsAssigned)||M,q=d.sides&&d.sides.filter(Q=>Q?.participantId).length===2,$=d.matchUpStatus&&[he,Ce].includes(d.matchUpStatus),V=nr({inContextDrawMatchUps:y,drawDefinition:e,matchUpId:c}),K=_i({inContextDrawMatchUps:y,drawDefinition:e,targetData:V}),Y=(D?.drawPositions?.length===2&&D.drawPositions.every(Q=>O?.includes(Q))&&D?.sides?.length===2&&D.sides.every(({participantId:Q})=>Q)||q)&&!($&&K),Z={method:MS,type:ta,payload:{drawId:m,matchUpId:c,penaltyCode:void 0,penaltyType:void 0,participantIds:[],notes:void 0}};if(L&&N.push({payload:{drawId:m,matchUpId:c,schedule:{}},method:eT,type:QD}),Gn({policyActions:S,action:ta})&&(U?.participant||!a&&A?.length)&&N.push(Z),L&&Y&&N.push({type:XD}),H&&Y){let{matchUpId:Q,matchUpFormat:st}=d,St={drawId:m,matchUpId:Q,matchUpFormat:st,outcome:{scoreStringSide1:void 0,scoreStringSide2:void 0,sets:[]},winningSide:void 0};N.push({info:"set outcome and winningSide",method:eT,type:JD,payload:St}),Gn({policyActions:S,action:oT})&&N.push({type:oT}),Gn({policyActions:S,action:iT})&&N.push({type:iT})}if(b&&D){let Q=vO({specifiedPolicyDefinitions:o,inContextDrawMatchUps:y,matchUpParticipantIds:A,matchUpActionsPolicy:I,inContextMatchUp:D,policyActions:S,enforceGender:i,participantId:s,sideNumber:a,matchUpId:c,matchUp:d,drawId:m,side:U});N.push(...Q)}return{structureIsComplete:v,validActions:N,isDoubleExit:$,...C}}function wO({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}=at({structureId:S,drawDefinition:s}),y=T?.finishingPosition===Wi&&(d?.length!==1||l?.length!==1),D={};if(y){let{matchUps:M}=Et({drawDefinition:s,structure:u,event:m}),{initialRoundNumber:P}=hs({drawPosition:a,matchUps:M}),R=s.links?.find(b=>b.target?.structureId===u?.structureId&&b.target.roundNumber===P)?.source?.roundNumber;D.roundNumbers=[R]}let{completedMatchUps:U}=Au({structureId:S,inContext:!0,matchUpFilters:D,drawDefinition:s}),A=i.map(M=>M.participantId).filter(Boolean);U?.filter(({matchUpType:M,winningSide:P})=>P&&(m?.eventType!==Me||M===Me)).map(({winningSide:M,sides:P})=>M&&P?.[1-(M-1)]).map(ht).filter(M=>M&&!A.includes(M))?.forEach(M=>{f.includes(M)||f.push(M)})}let I=t?.filter(h=>f?.includes(h.participantId));return I?.forEach(h=>{let S=(s.entries??[]).find(T=>T.participantId===h.participantId);h.entryPosition=S?.entryPosition}),f?.length?{validLuckyLosersAction:{type:Ug,method:$v,availableLuckyLosers:I,availableLuckyLoserParticipantIds:f,willDisableLinks:r,payload:{drawId:p,structureId:c,drawPosition:a}}}:{}}function LO({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?.[xn]?.validSeedPositions?.ignore;if(y||({unplacedSeedParticipantIds:h,unplacedSeedAssignments:S,unfilledPositions:T}=dS({provisionalPositioning:n,returnAllProxies:!0,randomize:!0,drawDefinition:u,seedingProfile:p,structureId:l,event:f})),T?.length||(T=s.filter(D=>!D.participantId&&!D.bye&&!D.qualifier).map(D=>D.drawPosition)),m||I.push({payload:{drawId:g,structureId:l,drawPosition:d,isPositionAction:!0},willDisableLinks:r,method:Jv,type:Ed}),i&&y){let D=s.map(P=>P.participantId).filter(Boolean),U={structureIds:t},{completedMatchUps:A}=zs({inContext:!0,matchUpFilters:U,drawDefinition:u}),E=pt((A??[]).filter(({matchUpType:P})=>f?.eventType!==Me||P===Me)?.map(({sides:P})=>P?.map(ht)).flat().filter(P=>P&&!D.includes(P))),M=a?o?.filter(P=>E?.includes(P.participantId)).map(P=>J(P,void 0,!0)):void 0;return M?.forEach(P=>{let N=(u.entries??[]).find(R=>R.participantId===P.participantId);P.entryPosition=N?.entryPosition}),M?.length&&I.push(rt({payload:{drawId:g,structureId:l,drawPosition:d},willDisableLinks:r,method:yD,type:Us,availableParticipantIds:E,participantsAvailable:M})),{validAssignmentActions:I}}if(T.includes(d)||m){let D;if(S?.length){let A=S.filter(E=>h?.includes(E.participantId));A.sort(OG),D=A.map(E=>E.participantId)}else D=e;let U=a?o?.filter(A=>D.includes(A.participantId)).map(A=>J(A,void 0,!0)):void 0;U?.length&&I.push(rt({payload:{drawId:g,structureId:l,drawPosition:d},willDisableLinks:r,method:yD,type:Us,availableParticipantIds:D,participantsAvailable:U}))}return{validAssignmentActions:I}}function OG(t,e){return t.bye||Ac(t.seedValue)<Ac(e.seedValue)||t.seedValue&&!e.seedValue?-1:(t.seedNumber||0)-(e.seedNumber||0)}function FO({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(D=>D.participantId).filter(Boolean),f=o?.[yo],g=!f?.disableRoundRestrictions&&t[s],I=f?.requireCompletedStructures,{sourceStructureIds:h,relevantLinks:S}=_g({targetRoundNumber:g,linkType:fo,drawDefinition:i,structureId:a})||{};h?.length&&d.push(...h);let{sourceStructureIds:T,relevantLinks:y}=_g({targetRoundNumber:g,linkType:Jn,drawDefinition:i,structureId:a})||{};T?.length&&d.push(...T);for(let D of S){let U=i.structures?.find(E=>E.structureId===D.source.structureId);if(U?.stage!==ct)continue;let A=si({structureId:D.source.structureId,drawDefinition:i});if(!I||A){let E=U.qualifyingRoundNumber,{matchUps:M}=Et({matchUpFilters:{roundNumbers:[E],hasWinningSide:!0},afterRecoveryTimes:!1,tournamentParticipants:e,inContext:!0,structure:U});for(let P of M){let N=P.sides.find(b=>b?.sideNumber===P.winningSide),R=P.matchUpStatus===Pt&&P.sides?.find(({participantId:b})=>b);if(N||R){let{participantId:b,participant:v}=N||R||{};b&&!l.includes(b)&&(v&&n&&u.push(v),p.push(b))}}}}for(let D of y){let U=i.structures?.find(E=>E.structureId===D.source.structureId);if(U?.stage!==ct)continue;let A=si({structureId:D.source.structureId,drawDefinition:i});if(!I||A){let{positionAssignments:E}=Ct({structure:U}),M=E?.map(P=>{let N=P.participantId,R=mt({element:P,name:Zo}).extension?.value;return R?{participantId:N,groupOrder:R?.groupOrder}:{}}).filter(({groupOrder:P,participantId:N})=>P===1&&!l.includes(N)).map(({participantId:P})=>P)??[];if(M&&p.push(...M),n){let P=e.filter(({participantId:N})=>M.includes(N));u.push(...P)}}}return p.length&&m.push(rt({payload:{qualifyingParticipantId:void 0,drawPosition:s,structureId:a,drawId:c},method:jv,type:Gp,qualifyingParticipantIds:p,qualifyingParticipants:n?u:void 0})),{validAssignmentActions:m,sourceStructureIds:d}}function kO({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}=Et({afterRecoveryTimes:!1,inContext:!0,drawDefinition:c,structure:d,event:f}),y=T.filter(({drawPositions:P})=>xe(P,S)),D=Object.assign({},...y.map(P=>P.sides?.filter(({sourceDrawPositionRange:N})=>N).map(({drawPosition:N,sourceDrawPositionRange:R})=>({[N]:R}))).flat()),U=h.map(P=>P.participantId).filter(Boolean),A=(r??[]).filter(P=>U.includes(P.participantId)),E=Object.assign({},...A.map(P=>({[P.participantId]:P}))),M=h.map(P=>{let N=E?.[P.participantId],R=D[P.drawPosition];return rt({...P,participant:s?J(N,!1,!0):void 0,sourceDrawPositionRange:R})});return M.length?{validSwapAction:{payload:{drawId:l,structureId:m,drawPositions:[p]},willDisableLinks:e,method:NS,type:Bp,availableAssignments:M}}:{}}function sT(t){let e=nt(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&&$t({withIndividualParticipants:!0,tournamentRecord:i}).participants)??[],p=at({structureId:t.structureId,drawDefinition:s});if(p.error)return p;let m=p.containingStructure||p.structure;if(!m)return{error:Lt};let d=m.structureId;if(p=ba({drawDefinition:s,structureId:d}),a===void 0&&!p.isAdHoc)return{error:_s};if(p.isAdHoc)return _d(t);if(p.error)return p;let{drawPositionInitialRounds:l,inactiveDrawPositions:f,activeDrawPositions:g,byeDrawPositions:I}=p,h=yt({tournamentRecord:i,drawDefinition:s,structure:m,event:c}).appliedPolicies??{};Object.assign(h,r??{});let{actionsPolicy:S,enabledStructures:T,actionsDisabled:y}=XS({actionType:xg,appliedPolicies:h,drawDefinition:s,structure:m}),D=S?.activePositionOverrides||[],{sourceStructureIds:U}=_g({finishingPosition:Vs,targetRoundNumber:1,linkType:Jn,drawDefinition:s,structureId:d})||{},A;U?.length&&(A=U.reduce((z,Y)=>si({structureId:Y,drawDefinition:s})&&z,!0));let E=U.length,M=U.length&&!A,{policyActions:P}=JS({enabledStructures:T,drawDefinition:s,structure:m}),N=![ct,et].includes(m.stage)||m.stageSequence!==1,{drawId:R}=s,b=[],{assignedPositions:v,positionAssignments:O}=le({structure:m}),x=v?.find(z=>z.drawPosition===a);if(!O?.map(z=>z.drawPosition)?.includes(a))return{error:Os};let{stage:L,stageSequence:w}=m,B=[L];L===Ve&&B.push(et),L===et&&B.push(Ve);let G=Ni({entryStatuses:ni,provisionalPositioning:o,drawDefinition:s,stageSequence:w,structureId:d,stages:B}),W=Oi({drawDefinition:s,stages:B}).assignedParticipantIds??[],H=G.filter(z=>!W.includes(z.participantId)).map(z=>z.participantId),q=I.includes(a),$=g.includes(a);if(y)return{hasPositionAssigned:!!x,info:"Actions Disabled for structure",isActiveDrawPosition:$,isDrawPosition:!0,validActions:[],isByePosition:q};if(Gn({policyActions:P,action:Us})&&!$&&O&&!M&&(!x||q)){let{validAssignmentActions:z}=LO({positionSourceStructureIds:U,unassignedParticipantIds:H,possiblyDisablingAction:N,isWinRatioFedStructure:E,tournamentParticipants:u,positionAssignments:O,returnParticipants:n,appliedPolicies:h,drawDefinition:s,isByePosition:q,drawPosition:a,structureId:d,event:c});z?.forEach(Y=>b.push(Y))}if(Gn({policyActions:P,action:Gp})){let{validAssignmentActions:z}=FO({drawPositionInitialRounds:l,tournamentParticipants:u,positionAssignments:O,returnParticipants:n,appliedPolicies:h,drawDefinition:s,drawPosition:a,structureId:d,drawId:R});z?.forEach(Y=>b.push(Y))}let{participantId:V}=x||{},K=V&&u.find(z=>z.participantId===V);if(x){Gn({policyActions:P,action:RS})&&!$&&(b.push({type:RS,method:TD,payload:{drawId:R,structureId:d,drawPosition:a},willDisableLinks:N}),q||b.push({type:Eg,method:Yv,payload:{drawId:R,structureId:d,drawPosition:a},willDisableLinks:N}),Gn({policyActions:P,action:Ed})&&!q&&b.push({type:Ed,method:TD,payload:{drawId:R,structureId:d,drawPosition:a,replaceWithBye:!0},willDisableLinks:N}));let z=m.stage===ct||m.stage===et&&m.stageSequence===1;if(!q&&jD({activePositionOverrides:D,activeDrawPositions:g,action:Zs})&&Gn({policyActions:P,action:Zs})&&Lp({drawDefinition:s,structureId:d,drawPosition:a})&&z){let{seedAssignments:Y}=en({returnAllProxies:!0,drawDefinition:s,structure:m}),{seedNumber:Z,seedValue:Q}=Y?.find(st=>st.participantId===V)??{};b.push({type:Zs,method:Zv,participant:K,seedNumber:Z,payload:{drawId:R,structureId:d,participantId:V,seedValue:Q}})}if(!q&&jD({activePositionOverrides:D,activeDrawPositions:g,action:Vp})&&Gn({policyActions:P,action:Vp})&&Lp({drawDefinition:s,structureId:d,drawPosition:a})&&z){let{seedAssignments:Y}=en({returnAllProxies:!0,drawDefinition:s,structure:m}),{seedNumber:Z}=Y?.find(Q=>Q.participantId===V)??{};b.push({method:Xv,type:Vp,participant:K,seedNumber:Z,payload:{participantId:V,structureId:d,drawId:R}})}if(!q&&V){if(Gn({policyActions:P,action:ta})){let Y={type:ta,method:MS,participant:K,payload:{penaltyCode:void 0,penaltyType:void 0,participantIds:[],notes:void 0,drawId:R}};b.push(Y)}if(Gn({policyActions:P,action:Mu})){let Y={type:Mu,method:Qv,participant:K,payload:{participantId:V,otherName:void 0}};b.push(Y)}}if(Gn({policyActions:P,action:Bp})){let{validSwapAction:Y}=kO({possiblyDisablingAction:N,tournamentParticipants:u,inactiveDrawPositions:f,activeDrawPositions:g,positionAssignments:O,returnParticipants:n,byeDrawPositions:I,drawDefinition:s,isByePosition:q,drawPosition:a,structureId:d,structure:m,drawId:R});Y&&b.push(Y)}}if(Gn({policyActions:P,action:Ag})&&!M){let{validAlternatesAction:z}=OO({possiblyDisablingAction:N,tournamentParticipants:u,positionAssignments:O,activeDrawPositions:g,returnParticipants:n,appliedPolicies:h,drawDefinition:s,drawPosition:a,validActions:b,structureId:d,structure:m,drawId:R,event:c});z&&b.push(z)}if(Gn({policyActions:P,action:Ug})&&!M&&O){let{validLuckyLosersAction:z}=wO({sourceStructuresComplete:A,possiblyDisablingAction:N,isWinRatioFedStructure:E,tournamentParticipants:u,activeDrawPositions:g,positionAssignments:O,drawDefinition:s,drawPosition:a,structureId:d,structure:m,drawId:R});z&&b.push(z)}if(K?.participantType===lt&&Gn({policyActions:P,action:yg})){let{validModifyAssignedPairAction:z}=RO({tournamentParticipants:u,returnParticipants:n,drawPosition:a,participant:K,drawId:R,event:c});z&&b.push(z)}return{hasPositionAssigned:!!x,isActiveDrawPosition:$,isDrawPosition:!0,isByePosition:q,validActions:b,...C}}function Fu({policyDefinitions:t,appliedPolicies:e,drawType:r}){let n=t?.[Gm]?.drawTypeCoercion,o=e?.[Gm]?.drawTypeCoercion;return(typeof n=="boolean"?n:void 0)??(r&&n?.[r])??(typeof o=="boolean"?o:void 0)??(r&&o?.[r])??!0}function qp({tournamentRecord:t,drawDefinition:e,stage:r=et,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:hr};let{error:i,positionAssignments:s}=Ct({drawDefinition:e,structureId:n,structure:o});return{positionAssignments:s??[],structureId:o?.structureId,error:i}}function aT({structureId:t,drawDefinition:e}){if(!e)return{error:X};if(!te(t))return{error:k};let r=Ks({drawDefinition:e,structureId:t});if(r.error)return r;let n=r.links.target.flatMap(i=>i.target.feedProfile).filter(Boolean),o=!qt([Ii,yn,lp,gi],n).length;return{...C,valid:o}}function cT({participantsCount:t,participantCount:e}){if(t=t??e,!t)return{error:k};let r=os(t);return r?{drawSize:r}:_({result:{error:k},stack:"getEliminationDrawSize",context:{participantsCount:t}})}function ku(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=_o({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:k},context:{participantsCount:u},stack:c});if(o&&!p)return _({result:{error:dE},stack:c});if(isNaN(n))if(u)({drawSize:n}=cT({participantsCount:u}));else return _({result:{error:Qa},stack:c});let m=o&&u||n;if(m&&m>n)return{error:$l};let d=r?.[xn];if(!d)return{error:tE};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:kA}}function xd({consideredEntries:t,policyDefinitions:e,tournamentRecord:r,appliedPolicies:n,participantMap:o,enforceGender:i,participants:s,event:a}){if((!s||!o)&&r&&({participants:s,participantMap:o}=$t({tournamentRecord:r})),!s)return{error:Ja};if(!Array.isArray(s))return{error:k};if(!a)return{error:bt};let c=e?.[ze]??n?.[ze]??ys[ze],u=(i??c?.participants?.enforceGender)!==!1,{eventType:p,gender:m}=a,d=p===fi,l=p===Kr&&Ft||d&<||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=xG({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:$A,invalidParticipantIds:S}}return{...C,valid:!0}}function _G({participant:t,participantType:e,eventType:r,entryStatusMap:n}){let o=n[t.participantId],i=r&&[fi,Kr].includes(r)&&t.participantType===Tt&&(Qs(o)||o===io);return t.participantType!==e&&!i}function xG(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||Mn===n||[Zt,ce].includes(n)&&a[0]===n||Cr===n&&(a.length==1&&e.individualParticipantIds?.length===1||a.length===2),u=e?.person?.sex,p=!e?.person||!n||[Mn,Cr].includes(n)||[Zt,ce].includes(n)&&u===n;return!s||c&&p}function uT({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,D;for(let U of(I||[]).sort(u)){let A=Mm(U.drawSize||U.participantsCount),{qualifyingRoundNumber:E,structureOptions:M,matchUpFormat:P,structureName:N,structureId:R,drawType:b}=U,v=U.matchUpType,O=U.qualifyingPositions||wG({drawSize:A,qualifyingRoundNumber:E}),x,F,L;if(!ft(A))return _({result:{error:Qa},stack:i});let w=t.length>1?`${f}-`:"",B=I.length>1||w?h:"",G=N||(w||B?`${Ye(ct)} ${w}${B}`:Ye(ct));if(b===Un){let{structures:W,groupCount:H,maxRoundNumber:q}=Oa({structureName:U.structureName||G,structureId:R||o?.pop(),stage:ct,structureOptions:M,appliedPolicies:e,stageSequence:h,matchUpType:v,roundTarget:f,drawSize:A,idPrefix:r,isMock:n,uuids:o});S=H,x=q,F=W[0],l=[1]}else({drawSize:A,matchUps:L,roundLimit:x}=Rn({qualifyingRoundNumber:E,qualifyingPositions:O,matchUpType:v,drawSize:A,idPrefix:r,isMock:n,uuids:o})),F=In({structureName:U.structureName||G,structureId:R||o?.pop(),qualifyingRoundNumber:x,stage:ct,matchUpFormat:P,stageSequence:h,matchUpType:v,roundLimit:x,matchUps:L}),f&&At({extension:{name:Dn,value:f},element:F}),S=L?.filter(W=>W.roundNumber===x)?.length||0;if(h>1){let{link:W}=_a({sourceStructureId:y,sourceRoundNumber:T,targetStructureId:F.structureId,finishingPositions:D===Jn?[1]:void 0,linkType:D});c.push(W),m+=(A||0)-S}else m+=A||0;D=b===Un?Jn:fo,y=F.structureId,T=x,a.push(F),h+=1}d+=S,s.push({qualifiersCount:S,finalQualifyingRoundNumber:T,finalQualifyingStructureId:y,finishingPositions:l,roundTarget:f,linkType:D}),f+=1}return{qualifiersCount:d,qualifyingDrawPositionsCount:m,qualifyingDetails:s,structures:a,...C,links:c}}function wG({drawSize:t,qualifyingRoundNumber:e}){let r=t,n=0;for(;n<e;)r=Math.floor(r/2),n+=1;return r}function pT(t){let{drawTypeCoercion:e,enforceMinimumDrawSize:r}=t,n=ut(t.drawSize),o=e&&(typeof e=="boolean"||e<=2)&&n===2&&go||t.drawType||go,i=eU.includes(o);if(n&&i){if(e&&(typeof e=="boolean"&&n<4||n<=e))o=go;else if(n<4&&r)return{..._({context:{enforceMinimumDrawSize:r,drawSize:n,drawType:o},result:{error:Ju},stack:"getCoercedDrawType"}),drawType:o}}return{drawType:o}}function GO(t){let{drawDefinition:e,structureOptions:r,requireSequential:n}=t,o={structureName:Ye(et),...t,stage:et},{structures:i,groupCount:s,groupSize:a}=Oa(o);if(s<1)return{error:CE};let c=r?.playoffGroups||[{finishingPositions:[1],structureName:Ye(pe)}],[u]=i,{structures:p,links:m}=xS({sourceStructureId:u.structureId,requireSequential:n,drawDefinition:e,playoffGroups:c,groupCount:s,groupSize:a,...t});return p&&i.push(...p),{...C,structures:i,links:m}}function VO({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?yn:Ii,f=1+m;return{linkType:Zn,source:{roundNumber:f,structureId:t.structureId},target:{feedProfile:l,roundNumber:p,structureId:e.structureId}}}),c={linkType:fo,source:{roundNumber:s,structureId:e.structureId},target:{feedProfile:yn,roundNumber:i,structureId:t.structureId}},u=[{linkType:fo,source:{roundNumber:i,structureId:t.structureId},target:{feedProfile:yn,roundNumber:1,structureId:r.structureId}},{linkType:Zn,source:{roundNumber:i,structureId:t.structureId},target:{feedProfile:yn,roundNumber:1,structureId:r.structureId}}];return[...a,c,...u]}function BO({structureName:t,matchUpType:e,idPrefix:r,drawSize:n,isMock:o,uuids:i}){let s=[],{matchUps:a}=ai({linkFedFinishingRoundNumbers:[1],drawSize:n+1,matchUpType:e,idPrefix:r,isMock:o}),c=As({structureName:t||Ye(et),structureId:i?.pop(),stageSequence:1,stage:et,matchUpType:e,matchUps:a});s.push(c);let u=n/2,{matchUps:p}=ai({finishingPositionOffset:u,idPrefix:r&&`${r}-c`,drawSize:n-1,isConsolation:!0,matchUpType:e,isMock:o,uuids:i}),m=As({structureName:Ye(tU),matchUps:p,structureId:i?.pop(),stage:Ve,stageSequence:2,matchUpType:e});s.push(m);let{matchUps:d}=Rn({idPrefix:r&&`${r}-p1t2`,drawSize:2,matchUpType:e,isMock:o}),l=As({structureName:Ye(ZE),matchUps:d,structureId:i?.pop(),stageSequence:3,stage:pe,matchUpType:e});s.push(l);let f=VO({mainStructure:c,consolationStructure:m,deciderStructure:l});return{structures:s,links:f,...C}}function HO(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(On(s))return Rn(t);let u=LG(s),p=u.shift(),m=tt(1,(p?.participantsCount||0)+1).map(I=>({drawPosition:I})),d=[],l=1;({matchUps:d}=Hp({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=tt(1,h+1);n&&h===n&&(f=l-1);let T=S.map(y=>{let D=Ud({roundPosition:y,roundNumber:l,idPrefix:i,uuids:c});return{roundPosition:y,roundNumber:l,matchUpId:D}});d.push(...T),l++}let g=l-1;return d=Ra({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 LG(t){let e=ut(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 mT(t){let{playoffAttributes:e,stageSequence:r=1,stage:n=et,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??yt(t),p=t.policyDefinitions?.[cc]||u?.[cc];t.skipRounds=t.skipRounds||i<=4&&(p?.feedFromMainFinal?0:1)||0;let m=t.structureName??e?.["0"]?.name??Ye(et),d=()=>{let{matchUps:f}=Rn(t);return{structures:[In({stageSequence:r,structureName:m,matchUpType:o,structureId:c,matchUps:f,stage:n})],links:[],...C}};return{generators:{[an]:()=>({structures:[In({finishingPosition:Vs,stageSequence:r,structureName:m,matchUps:[],matchUpType:o,structureId:c,stage:n})],links:[],...C}),[Hi]:()=>{let{matchUps:f}=HO(t);return{structures:[In({stageSequence:r,structureName:m,matchUpType:o,structureId:c,matchUps:f,stage:n})],links:[],...C}},[go]:()=>d(),[Zc]:()=>BO(t),[Xc]:()=>Pc({...t,roundOffsetLimit:3,playoffAttributes:e??lf}),[Jc]:()=>Pc({...t,roundOffsetLimit:2,playoffAttributes:e??ff}),[pe]:()=>Pc(t),[Ia]:()=>{let{matchUps:f}=ai({drawSize:i,uuids:s,matchUpType:o});return{structures:[In({stageSequence:r,structureName:m,matchUpType:o,structureId:c,stage:et,matchUps:f})],links:[],...C}},[fp]:()=>bS(t),[tu]:()=>Mc({...t,feedRounds:1,fmlc:!0}),[JE]:()=>Mc({...t,feedRounds:1}),[XI]:()=>Mc({...t,feedsFromFinal:1}),[JI]:()=>Mc({...t,feedsFromFinal:2}),[ZI]:()=>Mc({...t,feedsFromFinal:3}),[gp]:()=>Mc(t),[df]:()=>OS(t),[Un]:()=>Oa(t),[Io]:()=>GO(t)}}}function wd(t){let{enforceMinimumDrawSize:e=!0,overwriteExisting:r,appliedPolicies:n,staggeredEntry:o,drawDefinition:i,tieFormat:s,isMock:a,uuids:c}=t||{},u=ut(t.drawSize),p=t.drawTypeCoercion??Fu({appliedPolicies:n,drawType:t.drawType}),m="generateDrawStructuresAndLinks",d=pT({drawType:t.drawType,enforceMinimumDrawSize:e,drawTypeCoercion:p,drawSize:u});if(d.error)return d;let l=d.drawType,f=[],g=[],I=t?.matchUpType??Bt,h=i?.structures?.filter(({stage:W})=>W===ct);h&&f.push(...h);let S=h?.map(({structureId:W})=>W),T=i?.structures?.find(({stage:W,stageSequence:H})=>W===et&&H===1),y=i?.links?.filter(W=>W.target.structureId===T?.structureId&&S?.includes(W.source.structureId)),D=(W,H)=>{if(W.linkType===Jn&&H?.structures){let q=W.source.finishingPositions||[];return H.structures.length*q.length}else if(W.linkType===fo&&H?.matchUps?.length){let q=W.source.roundNumber;return H.matchUps.filter(({roundNumber:V})=>V===q).length}},U=h?.map(W=>{let H=y?.find(z=>z.target.structureId===W.structureId),q=Ct({structure:W})?.positionAssignments?.length??0;if(!H)return q;let $=H?.source.structureId,V=i.structures?.find(z=>z.structureId===$),K=D(H,V)||0;return q-K}).filter(Boolean).reduce((W,H)=>W+H,0),A=y?.map(W=>{let H=W.source.structureId,q=h?.find($=>$.structureId===H);return D(W,q)}).filter(Boolean).reduce((W,H)=>W+H,0),E=!!(T&&!T?.matchUps?.length);if(h?.length&&!E)return{error:WI};let M=!h?.length&&t.qualifyingProfiles,P=M?.length&&uT({idPrefix:t.idPrefix,qualifyingProfiles:M,appliedPolicies:n,isMock:a,uuids:c});if(P?.error)return P;let{qualifyingDrawPositionsCount:N,qualifyingDetails:R,qualifiersCount:b}=P||{qualifyingDrawPositionsCount:U,qualifiersCount:A};N&&(P?.structures&&f.push(...P.structures),P?.links&&g.push(...P.links)),Object.assign(t,rt({drawSize:u,matchUpType:I,tieFormat:s}));let v=l!==an&&(!u||u<2||!o&&![Ia,Hi].includes(l)&&([Io,Un].includes(l)&&u<3||![Un,Io].includes(l)&&!On(u)));if(v&&!N)return _({context:{drawSize:u,invalidDrawSize:v},result:{error:Ju},stack:m});let{generators:O,error:x}=mT(t);if(x)return{error:x};let F=O[l];if(!F)return{error:wl};let L=F?.();if(L.error)return L;let{structures:w,links:B}=L;if(w?.length){let W=w.find(({stage:H,stageSequence:q})=>H===et&&q===1);if(T&&W){if(E){let H=W.structureId;if(W.structureId=T.structureId,B?.length)for(let q of B)q.source.structureId===H&&(q.source.structureId=T.structureId),q.target.structureId===H&&(q.target.structureId=T.structureId)}else if(!r)return{error:WI}}f.push(...w)}f.sort(Ai),B?.length&&g.push(...B);let G=L.structures.find(({stage:W,stageSequence:H})=>W===et&&H===1);for(let W of R||[]){let{finalQualifyingRoundNumber:H,finalQualifyingStructureId:q,roundTarget:$,finishingPositions:V,linkType:K}=W,z=G&&_a({targetStructureId:G.structureId,sourceStructureId:q,sourceRoundNumber:H,finishingPositions:V,targetEntryRound:$,linkType:K})?.link;if(z?.error)return z;z&&g.push(z)}return y&&g.push(...y),{...C,qualifyingResult:{qualifyingDrawPositionsCount:N,qualifiersCount:b},structures:f,links:g}}function Ld(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=mr({tieFormat:s});if(T.error)return T}s=Ze(s??We({drawDefinition:i})?.tieFormat),a=a??(i.matchUpType||Bt),t.tieFormat=s,t.matchUpType=a;let c=_p({drawDefinition:i,stage:et});t.drawSize=t.drawSize??c,!c&&t.drawSize&&kp({drawSize:t.drawSize,drawDefinition:i,stageSequence:r,stage:et});let u=Ee({drawDefinition:i}).drawMatchUps.map(Ie),p=wd(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&&!_p({stage:ct,drawDefinition:i})){let y=kp({drawSize:l.qualifyingDrawPositionsCount,stage:ct,drawDefinition:i});if(y.error)return y}if(f){let T=PS({qualifiersCount:f,drawDefinition:i,stage:et});if(T.error)return T}let g=t.drawSize??c;Object.assign(t,rt({drawSize:g,matchUpType:a,tieFormat:s}));let{matchUps:I,matchUpsMap:h}=re({drawDefinition:i});s&&I?.forEach(T=>{if(!u.includes(T.matchUpId)){let{tieMatchUps:y}=xa({tieFormat:s,matchUp:T,isMock:n});Object.assign(T,{tieMatchUps:y,matchUpType:a})}});let{inContextDrawMatchUps:S}=Ki({drawDefinition:i,matchUpsMap:h});return Ot({tournamentId:t.tournamentRecord?.tournamentId,drawDefinition:i}),{inContextDrawMatchUps:S,drawDefinition:i,matchUpsMap:h,...C,structures:m,matchUps:I,links:d}}function vc(t){let{removePriorValues:e,tournamentRecord:r,participantId:n,scaleItem:o}=t,i,s;if(!WO({scaleItem:o}))return{error:rp};if(n&&Array.isArray(r.participants)&&(s=r.participants.find(a=>a.participantId===n),s)){let a=jO({removePriorValues:e,participant:s,scaleItem:o});if(a.error)return a;i=!a.valueChanged;let{topics:c}=xr();c.includes(Xe)&&dt({topic:Xe,payload:{tournamentId:r.tournamentId,participants:[s]}})}return i&&{...C,info:ef,existingValue:o?.scaleValue}||s&&{...C,newValue:o?.scaleValue}||{error:Xt}}function eP(t){let{scaleItemsWithParticipantIds:e=[],removePriorValues:r,tournamentRecord:n,auditData:o,context:i}=t;if(!n)return{error:j};if(!n.participants)return{error:Ja};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(WO({scaleItem:l}))Array.isArray(a[d])||(a[d]=[]),a[d].push(l);else return{error:rp}}n.participants.forEach(m=>{let{participantId:d}=m||{};Array.isArray(a[d])&&a[d].forEach(l=>{jO({participant:m,scaleItem:l,removePriorValues:r}),c.push(m),s++})});let u=s?void 0:Fs,{topics:p}=xr();if(p.includes(Xe)&&s&&dt({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:bf,itemValue:l};if(f&&(g.itemSubTypes=f),d||m){let{drawDefinition:I,event:h}=He({tournamentRecord:n,eventId:m,drawId:d});d&&Tg({drawDefinition:I,timeItem:g}),m&&Xi({event:h,timeItem:g})}else bc({tournamentRecord:n,timeItem:g})}}return o&&p.includes(Ei)&&dt({topic:Ei,payload:o}),rt({...C,modificationsApplied:s,info:u})}function WO({scaleItem:t}){let e=t&&Object.keys(t),r=["scaleType","eventType","scaleName"];return!!(r.filter(o=>e?.includes(o)).length===r.length)}function jO({removePriorValues:t,participant:e,scaleItem:r}){if(!e)return{error:Gi};let n=r&&Object.keys(r),o=["scaleType","eventType","scaleName"];if(!(o.filter(p=>n.includes(p)&&r[p]).length===o.length))return{error:rp};let s=new Date().toISOString();e.timeItems||(e.timeItems=[]);let{scaleItem:a}=Uo({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=[Ti,p,m,d].join("."),f=rt({itemValue:r.scaleValue,itemDate:r.scaleDate,createdAt:s,itemType:l});r.scaleId&&(f.itemSubTypes=[r.scaleId]),t&&(e.timeItems=e.timeItems.filter(g=>g.itemType!==l)),e.timeItems.push(f)}return{...C,valueChanged:u,newValue:r.scaleValue}}function Lg(t){let{tournamentRecord:e,modifiedScaleValues:r,removePriorValues:n}=t,o=nt(t,[{[Re]:!0},{modifiedScaleValues:!0,[ar]:zr}]);if(o.error)return o;for(let i in r){let s=vc({scaleItem:r[i],removePriorValues:n,tournamentRecord:e,participantId:i});if(s.error)return s}return{...C}}function Oc(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}=Ao({tournamentRecords:o,tournamentRecord:e,participantId:n});return i?{...Uo({participant:i,scaleAttributes:r}),tournamentId:s}:{error:Xt}}var FG=(t=0)=>250/Math.pow(t+5,.4),kG=()=>1;function GG(t=3,e=2){let r=t/e;return isNaN(r)?Fd.kDefault():r}var Fd={nSpread:400,diffThreshold:.125,kCalc:FG,kMultiplier:GG,kDefault:kG};function dT(t){let{winnerRating:e,loserRating:r}=t,{ratings:n=ve,winnerCountables:o=1,loserCountables:i=0,ratingType:s=zn,maxCountables:a,countables:c}=t||{},u=n?.[s];if(!u)return{error:ot};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=(x,F)=>parseFloat(F)>=Math.min(...x)&&parseFloat(F)<=Math.max(...x);(!f(p,e)||!f(p,r))&&(f(p,e)||(e=u.defaultInitialization),f(p,r)||(r=u.defaultInitialization));let g=bu({targetRange:ve[zn].range,sourceRange:l,value:m?p[0]-e:e}),I=bu({targetRange:ve[zn].range,sourceRange:l,value:m?p[0]-r:r}),h=(x,F)=>1/(1+Math.pow(10,(F-x)/Fd.nSpread)),S=h(g,I),T=h(I,g),y=Fd.kCalc(o),D=Fd.kCalc(i),U=Fd.kMultiplier(a,c),A=g+U*y*(1-S),E=I+U*D*(0-T),M=bu({sourceRange:ve[zn].range,value:A,targetRange:l}),P=bu({sourceRange:ve[zn].range,value:E,targetRange:l}),N=m?p[0]-M:M,R=parseFloat(N.toFixed(d)),b=m?p[0]-P:P,v=parseFloat(b.toFixed(d)),O=Math.max(...p)?Math.abs(e-r)/Math.max(...p):0;return(M>P&&O>Fd.diffThreshold||R<0||v<0)&&(R=e,v=r),{newWinnerRating:R,newLoserRating:v}}var YO=t=>t?.reduce((e,r)=>(r.winningSide&&(e[r.winningSide-1]+=1),e),[0,0])||[0,0];function lT(t){let e=nt(t,[{[Re]:!0},{matchUpIds:!0,[ar]:ir,[ho]:ns},{ratingType:!1,[sr]:S=>ve[S]}]);if(e.error)return e;let{updateParticipantRatings:r,removePriorValues:n=!0,tournamentRecord:o,ratingType:i=zn,refreshDynamic:s,considerGames:a,drawDefinition:c,matchUpIds:u,asDynamic:p}=t,m=ve[i],{accessor:d}=m,l={},f=(t.matchUps||s&&Je({drawDefinition:c,tournamentRecord:o,inContext:!0,matchUpFilters:{matchUpStatuses:ie}}).matchUps||fe({matchUpFilters:{matchUpIds:u,matchUpStatuses:ie},tournamentRecord:o,inContext:!0}).matchUps)??[],g=`${i}.${Lm}`,I=p?g:i;f.sort(vi);for(let S of f){let{endDate:T,matchUpFormat:y,score:D,sides:U,winningSide:A}=S,E=S.matchUpType,M={eventType:E,scaleName:i,scaleType:Si},P={scaleName:g,eventType:E,scaleType:Si},N=Object.assign({},...(U??[]).map(B=>{let{sideNumber:G,participant:W}=B;return G&&{[G]:[W?.participantId,...W?.individualParticipantIds??[]].filter(Boolean).flat()}})),R=Object.assign({},...Object.values(N).flat().map(B=>{let G=l[B],H=!s||G?Oc({scaleAttributes:P,tournamentRecord:o,participantId:B}).scaleItem:void 0,q=Oc({tournamentRecord:o,scaleAttributes:M,participantId:B}).scaleItem,$=d?{[d]:void 0}:void 0;return B&&{[B]:H??q??{scaleName:I,eventType:E,scaleDate:T,scaleType:Si,scaleValue:$}}})),b=y?rr(y):{},v=b?.bestOf||1,O=b?.setsTo||1,x=a?v&O:v,F=D?.sets&&YO(D.sets)||A===1&&[1,0]||[0,1],L=A?N[A]:[],w=A?N[3-A]:[];for(let B of L){let G=R[B]?.scaleValue,W=typeof G=="object"?G[d]:G;for(let H of w){let q=R[H]?.scaleValue,$=typeof q=="object"?q[d]:q,V=A?F[A]:[0,0],K=A?F[3-A]:[0,0],{newWinnerRating:z,newLoserRating:Y}=dT({winnerCountables:V,loserCountables:K,maxCountables:x,winnerRating:W,loserRating:$,ratingType:i}),Z=d?{...G,[d]:z}:z,Q=d?{...q,[d]:Y}:Y;R[B].scaleValue=Z,R[H].scaleValue=Q,R[B].scaleName=I,R[H].scaleName=I}}Object.assign(l,R),r&&Lg({tournamentRecord:o,modifiedScaleValues:l,removePriorValues:n})}let h=f.map(({matchUpId:S})=>S);return{...C,modifiedScaleValues:l,outputScaleName:I,processedMatchUpIds:h}}function Gu(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=Od(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:k,info:"matchUpsCount error",context:{roundMatchUpsCount:d}}});if(a&&!Array.isArray(a)||c&&!ft(c)||e&&!Array.isArray(e)||!a&&!c)return{error:k,info:"matchUpsCount or pairings error"};if(c&&t.restrictMatchUpsCount!==!1&&c>32)return{error:k,info:"matchUpsCount must be less than 33"};if(n&&!t.ignoreLastRoundNumber&&n-1>(p||0))return{error:k,info:"roundNumber error"};let l=n??(o&&(p??0)+1||p||1);a=a??tt(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((U,A)=>rt({sideNumber:A+1,participantId:U})),D=e[h]??f(h)??Nt();return{roundNumber:l,matchUpStatus:zt,matchUpId:D,sides:y}});if(g?.length){let I=We({drawDefinition:r,event:s})?.tieFormat;I&&g.forEach(h=>{let{tieMatchUps:S}=xa({tieFormat:I,matchUp:h,isMock:i});Object.assign(h,{tieMatchUps:S,matchUpType:Ht})})}return{roundNumber:l,matchUpsCount:g?.length??0,matchUps:g,...C}}function $O({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=qO({actorsCount:s.length,valueSortedPairings:e,pairingValueMap:i,deltaObjects:o,valueObjects:n}),u=[rP(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 D=Fa(S,y.opponent);if(!I.includes(D)){let U=qO({stipulated:[[S,y.opponent]],actorsCount:s.length,valueSortedPairings:e,pairingValueMap:i,deltaObjects:o,valueObjects:n});if(!u.includes(rP(U))){u.push(rP(U)),a.push(U);let{maxDelta:A,value:E}=U;A<m.maxDelta&&(m=U),(E<p||E===p&&Math.round(Math.random()))&&(p=E),I.push(D),d+=1}}}),a=a.filter(y=>Math.abs(y.value-p)<5)}),a.sort((S,T)=>S.maxDiff-T.maxDiff);let h=$r(a);return{candidatesCount:d,deltaCandidate:m,maxIterations:t,iterations:l,candidate:h}}function rP(t){return t.participantIdPairings.map(({participantIds:e})=>e.sort().join("|")).sort().join("/")}function qO({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=Fa(l,f),I=r[g];a.push({participantIds:d,value:I}),c+=r[g]}),Ae(t,i).map(d=>lr(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=Fa(f,g),h=n[I];return h>d?h:d},0),m=a.reduce((d,l)=>{let[f,g]=l.participantIds,I=Fa(f,g),h=o[I];return h>d?h:d},0);return{value:c,participantIdPairings:a,maxDelta:p,maxDiff:m}}function Fa(t,e){return[t,e].sort(Uu).join("|")}function nP({participantIds:t}){let e={},r=[];t.forEach(o=>{e[o]=t.filter(i=>i!==o),e[o].forEach(i=>{let s=Fa(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 KO({matchUps:t}){let e=[];for(let r of t){let n=r.sides.map(ht);if(n.length===2){let[o,i]=n,s=Fa(o,i);e.includes(s)||e.push(s)}}return{encounters:e}}function zO({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=Fa(o,i);return{opponent:i,value:e[s]}}return{pairingValues:r}}var VG=0;function QO({tournamentParticipants:t,adHocRatings:e,eventType:r,scaleName:n,pairing:o}){let i=ve[n]?.defaultInitialization??VG;return o.split("|").map(s=>{if(r===Br){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 XO(t){let{tournamentParticipants:e,adHocRatings:r={},possiblePairings:n,uniquePairings:o,maxIterations:i,minimizeDelta:s,deltaObjects:a,valueObjects:c,eventType:u,scaleName:p,salted:m}=t;o.forEach(T=>{let y=QO({tournamentParticipants:e,adHocRatings:r,scaleName:p,eventType:u,pairing:T}),D=typeof m=="number"&&m||.5,U=m&&(Math.round(Math.random())?D:D*-1)||0,A=Math.abs(y[0]-y[1])+U,E=Math.abs(y[0]-y[1]);a[T]=E,c[T]||(c[T]=0),c[T]+=A?Math.pow(A,2):0});let d=o.map(T=>({pairing:T,value:c[T]})).sort((T,y)=>T.value-y.value),{pairingValues:l}=zO({possiblePairings:n,valueObjects:c}),{candidate:f,candidatesCount:g,deltaCandidate:I,iterations:h}=$O({valueSortedPairings:d,maxIterations:i,pairingValues:l,deltaObjects:a,valueObjects:c}),{participantIdPairings:S}=s?I:f;return{participantIdPairings:S,candidatesCount:g,deltaCandidate:I,iterations:h,candidate:f}}var BG=100,HG=100,WG=4e3;function kd(t){let{encounterValue:e=BG,sameTeamValue:r=HG,maxIterations:n=WG,updateParticipantRatings:o,generateMatchUps:i=!0,ignoreLastRoundNumber:s,iterationMatchUps:a,tournamentRecord:c,dynamicRatings:u,refreshDynamic:p,participantIds:m,drawDefinition:d,roundNumber:l,structureId:f,matchUpIds:g,eventType:I,scaleName:h,idPrefix:S,isMock:T,salted:y,event:D}=t;if(!d)return{error:X};if(!t.structure&&!f)return{error:Lt};let U=t.structure||at({drawDefinition:d,structureId:f}).structure;if(!It(U))return{error:di};if(!m?.length)return{error:No};let A=[...a??[],...U?.matchUps??[]],{encounters:E}=KO({matchUps:A}),M=c?.participants??[],P={};if(u){let V=pt(U?.matchUps?U.matchUps.map(({roundNumber:z})=>z):[]),K=Math.max(...V,0);if(K){let z=U?.matchUps?.filter(({roundNumber:Z})=>Z===K).map(({matchUpId:Z})=>Z),Y=lT({ratingType:h??D?.category?.ratingType,updateParticipantRatings:o,tournamentRecord:c,asDynamic:!0,refreshDynamic:p,drawDefinition:d,matchUpIds:z});if(Y.error)return Y;Y.modifiedScaleValues&&(P=Y.modifiedScaleValues)}}let{valueObjects:N}=jG({tournamentParticipants:M,encounterValue:e,sameTeamValue:r,encounters:E}),{uniquePairings:R,possiblePairings:b,deltaObjects:v}=nP({participantIds:m}),O=Object.values(P).length?P:t.adHocRatings,x={tournamentParticipants:M,possiblePairings:b,participantIds:m,uniquePairings:R,drawDefinition:d,maxIterations:n,adHocRatings:O,deltaObjects:v,valueObjects:N,eventType:I,scaleName:h,structure:U,salted:y},{candidatesCount:F,participantIdPairings:L,deltaCandidate:w,iterations:B,candidate:G}=XO(x);if(!F)return{error:np};let W,H;if(i){let V=Gu({structureId:U?.structureId,ignoreLastRoundNumber:s,participantIdPairings:L,newRound:!0,drawDefinition:d,roundNumber:l,matchUpIds:g,idPrefix:S,isMock:T,event:D});if(V.error)return V;W=V.roundNumber,H=V.matchUps}let{maxDelta:q,maxDiff:$}=G;return{roundNumber:W,participantIdPairings:L,modifiedScaleValues:P,candidatesCount:F,deltaCandidate:w,...C,iterations:B,matchUps:H,maxDelta:q,maxDiff:$}}function jG({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===Ft);if(i)for(let s of i){let a=s.individualParticipantIds??[],{uniquePairings:c}=nP({participantIds:a});for(let u of c)o[u]||(o[u]=0),o[u]+=n}return{valueObjects:o}}function fT(t){let{drawType:e=go,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=Be,d=Ni({stageSequence:1,drawDefinition:p,stage:m}),l=[Un,Zc,Io].includes(e)?d.length:os(d.length);if(!i&&e===Ia&&d.length<2||e===Un&&d.length<3)return{error:Ju};let{tieFormat:f,matchUpType:g}=t;if(f){let R=mr({tieFormat:f});if(R.error)return R}f=Ze(f??We({drawDefinition:p})?.tieFormat),g=g??p.matchUpType??Bt;let{structures:I}=ln({stageSequence:1,drawDefinition:p,stage:m});if(I.length>1)return{error:zA};if(I?.[0]?.matchUps?.length)return{error:nf};let S=I?.[0]?.structureId;Object.assign(t,rt({structureName:t.structureName??Ye(Be),structureId:S,matchUpType:g,tieFormat:f,drawSize:l,stage:m}));let T=mT(t);if(T.error)return T;let y=T.generators[e];if(!y)return{error:wl};let D=y?.();if(D.error)return D;let{structures:U,links:A}=D,E=U.map(R=>Et({structure:R}).matchUps).flat();f&&E.forEach(R=>{let{tieMatchUps:b}=xa({matchUp:R,tieFormat:f,isMock:c});Object.assign(R,{tieMatchUps:b,matchUpType:g})}),(!n||!r)&&(p=J(p,!1,!0)),p.links||(p.links=[]),A.length&&p.links.push(...A);let M=U.map(({structureId:R})=>R);p.structures||(p.structures=[]);let P=p.structures.map(({structureId:R})=>R);p.structures=p.structures.map(R=>M.includes(R.structureId)?U.find(({structureId:b})=>b===R.structureId):R);let N=U.filter(({structureId:R})=>!P.includes(R));return N.length&&p.structures.push(...N),s&&Uc({seedingProfile:t.seedingProfile,applyPositioning:n,tournamentRecord:o,drawDefinition:p,structureId:S,placeByes:a,drawSize:l,event:u}),r&&Ot({drawDefinition:p}),{links:A,structures:U,...C}}var Wg={};Qt(Wg,{addGame:()=>pP,addPoint:()=>uP,addSet:()=>dP,addShot:()=>mP,analyzeScore:()=>Vg,analyzeSet:()=>Hu,calculateHistoryScore:()=>sP,checkScoreHasValue:()=>me,checkSetIsComplete:()=>zp,clearHistory:()=>cP,generate:()=>iP,generateScoreString:()=>jo,generateTieMatchUpScore:()=>Cc,getSetComplement:()=>Hg,getTiebreakComplement:()=>Zp,helpers:()=>HP,isValidMatchUpFormat:()=>Ar,keyValueScore:()=>LP,mutate:()=>IP,parseMatchUpFormat:()=>rr,parseScoreString:()=>Yd,query:()=>WP,redo:()=>lP,reverseScore:()=>oP,setServingSide:()=>aP,stringifyMatchUpFormat:()=>jp,tidyScore:()=>BP,umo:()=>gP,undo:()=>fP,validateScore:()=>Bg,validateTieFormat:()=>mr});var iP={};Qt(iP,{generateScoreString:()=>jo,generateTieMatchUpScore:()=>Cc,reverseScore:()=>oP});function jo(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:ot,info:"missing sets"};let u=i&&rr(i),{bestOf:p,finalSetFormat:m,setFormat:d}=u??{},f=n||!(!e||!a||a===1),g=r?YG({matchUpStatus:o}):"",I=c?.sort(qG).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,D=w=>Jt(w?.side1Score)||Jt(w?.side2Score),U=w=>Jt(w?.side1TiebreakScore)||Jt(w?.side2TiebreakScore),A=y?.tiebreakSet||!D(S)&&U(S),{side1Score:E,side2Score:M,side1TiebreakScore:P,side2TiebreakScore:N}=S,R=P||(Jt(P)||s?0:""),b=N||(Jt(N)||s?0:"");if(A)return`[${(f?[b,R]:[R,b]).join("-")}]`;let v=Math.min(R,b),O=v?`(${v})`:"",x=E||(Jt(E)||s?0:""),F=M||(Jt(M)||s?0:""),L=f?`${[F,x].join("-")}${O}`:`${[x,F].join("-")}${O}`;return["-"," "].includes(L)&&(L=""),L}}function YG({matchUpStatus:t}){let e={[Qe]:"RET",[vt]:"WO",[Ce]:"DF/DF",[he]:"WO/WO",[as]:"SUS",[Mr]:"ABN",[Mt]:"DEF",[pu]:"DR"};return t&&e[t]||""}function qG(t,e){return t.setNumber-e.setNumber}function oP(t){if(!t?.score)return{error:ot};let{sets:e}=t.score,r=e.map(i=>{let{side1TiebreakScore:s,side2TiebreakScore:a,winningSide:c,side1Score:u,side2Score:p,setNumber:m}=i;return rt({winningSide:c?3-c:void 0,side1TiebreakScore:a,side2TiebreakScore:s,side1Score:p,side2Score:u,setNumber:m})}),n=jo({sets:r}),o=jo({sets:r,reversed:!0});return{reversedScore:{sets:r,scoreStringSide1:n,scoreStringSide2:o},...C}}var IP={};Qt(IP,{addGame:()=>pP,addPoint:()=>uP,addSet:()=>dP,addShot:()=>mP,calculateHistoryScore:()=>sP,clearHistory:()=>cP,redo:()=>lP,setServingSide:()=>aP,umo:()=>gP,undo:()=>fP});function Yo({matchUp:t}){let{extension:e}=mt({name:jm,element:t});if(!e)return{error:Pe};let{history:r=[],undoHistory:n=[]}=e.value;return{history:r,undoHistory:n,...C}}function sP(t){if(!t)return{error:ot};let{matchUp:e,updateScore:r}=t;if(!e)return{error:dr};let n=Yo({matchUp:e})?.history||[];if(!Array.isArray(n))return{error:k,info:"history is not an array"};let{matchUpFormat:o}=e;if(!o)return{error:Bl};if(!Ar({matchUpFormat:o}))return{error:Vl};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:[]}),D=()=>({winningSide:void 0,side1Score:"",side2Score:"",shots:[]}),U=D(),A=y(),E=T(),M=0;for(let P of n){M+=1,I=p.sets.length+1===s;let N=I&&a?a:c,{tiebreakAt:R,setTo:b,NoAD:v,tiebbreakFormat:O}=N,x=E.side1Score===R&&E.side1Score===E.side2Score,F=!!N.tiebreakSet,L=F?N.tiebreakSet:O,{tiebreakTo:w,NoAD:B}=L||{},G=()=>{d=void 0,l=[0,0],f=3-f,E.side1TiebreakScore=0,E.side2TiebreakScore=0,E.side1PointScore="",E.side2PointScore="",h=0},W=$=>{E.winningSide=$;let{s:V,...K}=E;p.sets.push(K),U=D(),A=y(),E=T(),G()},H=$=>{A.winningSide=$;let{g:V,...K}=A;E.games.push(K),U=D(),A=y(),G();let z=`side${$}Score`;E[z]+=1},q=$=>{U.winningSide=$;let{p:V,...K}=U;A.points.push(K),U=D(),h=0;let z=()=>l.reduce((st,St)=>st+St)%4/4>.5?f:3-f,Y=$-1;if(x||F){l[Y]+=1,d=z(),E[`side${$}TiebreakScore`]=l[Y],E[`side${3-$}TiebreakScore`]=l[1-Y];let Z=B?1:2;if(l[Y]>=w&&l[Y]>=l[1-Y]+Z)return H($),{gameCompleted:!0}}else if(l[1-Y]===4&&l[Y]===3?l[1-Y]-=1:l[Y]+=1,E.side1PointScore=u[l[0]],E.side2PointScore=u[l[1]],l[Y]===5||l[Y]===4&&l[1-Y]<3||v&&l[Y]===4)return H($),{gameCompleted:!0}};if(S(P.srv)&&(f=P.srv),["p","s","g","o"].includes(P.u)&&m.push(P.u),P.shotOutcome&&(U.shots.push(P),P.shotType==="SERVE"&&["OUT","NET"].includes(P.shotOutcome)&&(h+=1),h===2)){let V=3-f;q(V)}if(S(P.p)||ft(P.pointNumber)){let $=P.winningSide||P.p;if(q($)?.gameCompleted)continue}if(S(P.g)||ft(P.gameNumber)){let $=P.winningSide||P.g;A.winningSide=$;let V=`side${$}Score`,K=`side${3-$}Score`;if(m.length&&(m.includes("p"),m=[]),H($),E[V]===b&&E[V]-E[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 M!==n.length&&console.log({error:"Match completed with excess history"}),(E.side1Score||E.side2Score||E.games.length||E.side1TiebreakScore||E.side2TiebreakScore)&&p.sets.push(E),p.scoreStringSide1=jo({...p,matchUpFormat:o}),p.scoreStringSide2=jo({...p,matchUpFormat:o,reversed:!0}),f=d||f,r&&(e.score=p),{...C,servingSide:f,score:p}}function qo({undoHistory:t,history:e,matchUp:r}){return At({element:r,extension:{value:{history:e,undoHistory:t},name:jm}})}function aP({matchUp:t,sideNumber:e}){if(![1,2].includes(e))return{error:Hl};let{history:r=[]}=Yo({matchUp:t});return r.push({srv:e}),qo({matchUp:t,history:r})}function cP({matchUp:t}){return qo({matchUp:t})}function uP({matchUp:t,point:e}){if(!e||!t)return{error:ot};if(typeof e!="object")return{error:k,context:{point:e}};let{history:r=[]}=Yo({matchUp:t});return r.push(e),qo({matchUp:t,history:r})}function pP({matchUp:t,game:e}){if(typeof e!="object")return{error:k,context:{game:e}};let{history:r=[]}=Yo({matchUp:t});return r.push(e),qo({matchUp:t,history:r})}function mP({matchUp:t,shot:e}){if(typeof e!="object")return{error:ot};let{history:r=[]}=Yo({matchUp:t});return r.push(e),qo({matchUp:t,history:r})}function dP({matchUp:t,set:e}){if(typeof e!="object")return{error:ot};let{history:r=[]}=Yo({matchUp:t});return r.push(e),qo({matchUp:t,history:r})}function lP({matchUp:t}){let{history:e=[],undoHistory:r=[]}=Yo({matchUp:t});return r.length&&e.push(r.pop()),qo({matchUp:t,history:e,undoHistory:r})}function fP({matchUp:t}){let{history:e=[],undoHistory:r=[]}=Yo({matchUp:t});return r.push(e.pop()),qo({matchUp:t,history:e,undoHistory:r})}var gP={};var HP={};Qt(HP,{keyValueScore:()=>LP,parseMatchUpFormat:()=>rr,stringifyMatchUpFormat:()=>jp,tidyScore:()=>BP});var na=" ",gT="DEF",JO="COMPLETED",hP="WO",$G="WO/WO",SP="ABN",TP="SUS",yP="RET",AP="INT",IT=[yP,gT,hP,$G,SP,TP,AP];var hT="DEFAULTED";var EP="WALKOVER";var ST="ABANDONED",TT="SUSPENDED",UP="RETIRED",yT="INTERRUPTED";var ZO=[UP,hT,EP],KG="Enter Score",Ds="()",Ps="[]",DP=["up","left","shift+tab"],PP=["enter","down","tab","right"],Gd="backspace",NP="r",MP="s",RP="a",CP="d",bP="w",vP="i",Vd=[NP,CP,bP,RP,MP,vP],$p="space",AT=["[","("],Bd=[...DP,...PP,$p,"]"],t_="-",zG="/",oa=t_,ci=t_,OP=[zG],e_=0,QG=["=","+","num_1","num_2","shift+=","shift+-"],ra=["0","1","2","3","4","5","6","7","8","9"].concat(Vd),r_=ra.map(t=>`shift+${t}`),_P=[oa,Gd].concat(Bd,OP),xP=[ra,r_,_P].join(","),XG=[xP,DP,PP,QG].join(","),QMt=[].concat(...ra,...ra,..._P,...ra,...ra,...ra,...ra,...ra,...ra),n_={OUTCOMEKEYS:Vd,SIDE1KEYS:ra,SIDE2KEYS:r_,MODIFIERS:_P,PROMPT:KG,MOVEUP:DP,MOVEDOWN:PP,HOTKEYS:XG};function Kp({scoreString:t,lowSide:e,outcome:r}){if({scoreString:t}=o_({scoreString:t}),e===2){let o=(t&&t[t.length-1])!==na?na:"";return t+o+r}else return r+na+t}function o_({scoreString:t}){if(!t)return{scoreString:""};let e=!1;for(let r of IT){let n=t?.indexOf(r);n===0?t=t.slice(r.length+1).trim()+na:n>0&&(t=t.slice(0,n)),n>=0&&(e=!0)}return t?.trim()||(t=""),{scoreString:t,removed:e}}function Fg({analysis:t,scoreString:e,sets:r,lowSide:n}){let o,i;if(!e)return{scoreString:e,sets:r};let{scoreString:s,removed:a}=o_({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}=Vu({brackets:Ps,scoreString:e}),f=JG(e);if(f>=0){o=e.slice(0,f);let{isTiebreakEntry:g}=Vu({brackets:Ds,scoreString:o}),{lastOpenBracketIndex:I,isTiebreakEntry:h}=Vu({brackets:Ps,scoreString:o}),S=o&&o[o.length-1].trim(),T=o&&!isNaN(S),y=t.isIncompleteSetScore;if(l&&h){let U=o.slice(I+1).split(ci),A=U?.length>0&&U[0]!==void 0&&!isNaN(parseInt(U[0]))&&parseInt(U[0])||void 0,E=U?.length>1&&U[1]!==void 0&&parseInt(U[1])||void 0,M=[A,E];if(E){let P=n===1?1:0;M[P]=(M?.[1-P]||0)+(d?1:2),(M[P]||0)<m&&(M[P]=m),o=e.slice(0,I+1),o+=M.join(ci)}else A!==void 0?(o=e.slice(0,I+1),o+=A):(o=e.slice(0,I),y=!0);c.side1TiebreakScore=M[0]||0,c.side2TiebreakScore=M[1]||0}if(o.length||(o=void 0),y){let D=c.side1Score?.toString();if(D){let U=D?.slice(0,D.length-1);c.side1Score=!isNaN(U)&&parseInt(U)||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 D=c.side2Score?.toString(),U=c.side1Score?.toString();if(!t.isTiebreakEntry&&!t.isMatchTiebreak)if(c.side2Score){let A=D?.slice(0,D.length-1);c.side2Score=!isNaN(A)&&parseInt(A)||void 0}else{let A=U?.slice(0,U.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 Vu({brackets:t=Ds,scoreString:e}){if(!e)return{};let[r,n]=t.split(""),o=e.split(""),i=Math.max(...lo(r,o)),s=Math.max(...lo(n,o));return{isTiebreakEntry:i>s,lastOpenBracketIndex:i}}function i_({scoreString:t}){if(!t)return!1;let e=t&&t[t.length-1].trim(),r=t&&!isNaN(e),[n,o]=Ps.split(""),i=t.split(""),s=Math.max(...lo(n,i)),a=Math.max(...lo(o,i)),c=Math.max(...lo(ci,i));return r&&s>a&&c>s}function JG(t){return t.split("").reduce((n,o,i)=>(o.match(/\d+/g)&&n.push(i),n),[]).pop()}function ET(t){let{lowValue:e=0,NoAD:r=!1,tiebreakTo:n}=t||{},o=r?1:2;return e+1>=n?e+o:parseInt(n)}function wP({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 ZO.includes(e)&&r&&(c=r),{matchUpWinningSide:c}}function zp({ignoreTiebreak:t=!1,matchUpScoringFormat:e,matchUpFormat:r,isTiebreakSet:n,isDecidingSet:o,set:i}){if(!i)return{error:ot,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=Qp({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 Qp({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 Hd({analysis:t,set:e}){let r=Qp({set:e}),{isDecidingSet:n,isTiebreakSet:o,matchUpScoringFormat:i}=t;return zp({matchUpScoringFormat:i,isDecidingSet:n,isTiebreakSet:o,set:e})&&r}function s_({analysis:t,scoreString:e,sets:r,value:n}){let o;if(!r?.length)return{sets:[]};let i=r[r.length-1];n=ut(n);let{validSide2Score:s,requiresTiebreak:a}=ZG({analysis:t,set:i,value:n});if(s){o=!0,e=(e||"")+n,i.side2Score=n;let c=Hd({analysis:t,set:r[r.length-1]});if(i.winningSide=c||void 0,a){let u=Ds.split("")[0];e+=u}else t.isDecidingSet||(e+=na)}return{sets:r,scoreString:e,updated:o}}function ZG({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 UT({lowSide:t,value:e,sets:r,scoreString:n,winningSide:o,matchUpStatus:i}){let s;return e===NP?n?(s=!0,n=Kp({scoreString:n,lowSide:t,outcome:yP}),o=t===2?1:2,i=UP):(s=!0,n=Kp({scoreString:n,lowSide:t,outcome:gT}),o=t===2?1:2,i=hT):e===CP?(s=!0,n=Kp({scoreString:n,lowSide:t,outcome:gT}),o=t===2?1:2,i=hT):e===bP?(s=!0,r=[],n=hP,o=t===2?1:2,i=EP):e===MP&&n?(s=!0,n=Kp({scoreString:n,lowSide:t,outcome:TP}),i=TT,o=void 0):e===RP?(s=!0,n=Kp({scoreString:n,lowSide:t,outcome:SP}),i=ST,o=void 0):e===vP&&n&&(s=!0,n=Kp({scoreString:n,lowSide:t,outcome:AP}),i=yT,o=void 0),{updated:s,sets:r,scoreString:n,matchUpStatus:i,winningSide:o}}function a_(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!==Gd&&(e=[{setNumber:1}]);let m=e.length-1;if(Vd.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}=UT({lowSide:a,value:c,sets:e,scoreString:n,matchUpStatus:i,winningSide:o}))}else if(c===Gd){if({scoreString:n,sets:e,outcomeRemoved:p}=Fg({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===oa&&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=ut((e[m].side1Score||0).toString()+c).toString().slice(0,2);e[m].side1Score=ut(l),d=e[m].side1Score.toString(),u=!0}else{let l=ut((e[m].side2Score||0).toString()+c).toString().slice(0,2);e[m].side2Score=ut(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 c_({analysis:t,auto:e,lowSide:r,scoreString:n="",sets:o,value:i}){let s,a,{tiebreakSet:{tiebreakTo:c,NoAD:u}}=t.setFormat,[p]=Ps.split("");if(t.isMatchTiebreakEntry||(n+=p),o[t.setNumber-1]){let{lastOpenBracketIndex:d}=Vu({brackets:Ps,scoreString:n}),f=(n.slice((d??0)+1)+(e?"":i)).split(ci);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=>ut(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(ci),s=!0}else{let I=[f[0]||0,f[1]||0].map(S=>ut(S)),h=o[o.length-1];h.side1TiebreakScore=I[0],h.side2TiebreakScore=I[1],n+=i,s=!0}}else{let d=ET({lowValue:ut(i||0),tiebreakTo:c,NoAD:u}),l=[ut(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(ci),s=!0}return{info:a,scoreString:n,sets:o,updated:s}}function u_({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=Ds.split("")[0],d=u.join(oa)+(a?m:na);r=(r||"")+d;let l={side1Score:u[0],side2Score:u[1]},f=Hd({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 p_({matchUpFormat:t,scoreString:e,winningSide:r,value:n,sets:o}){let s=(o?.filter(H=>H?.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}=Vu({brackets:Ds,scoreString:e}),{isTiebreakEntry:f}=Vu({brackets:Ps,scoreString:e}),g=l||f,I=!!u.tiebreakSet,h=e?.[e.length-1]?.trim(),S=e&&!isNaN(h),T=!g&&h===oa,y=l&&AT.includes(h),D=f&&AT.includes(h),U=f&&h===ci,A=e?.split(""),[E]=Ps.split(""),M=A&&Math.max(...lo(E,A)),P=A&&Math.max(...lo(ci,A)),N=A&&P>M,R=o[o.length-1]?.winningSide,b=o?.length&&!R,v=IT.find(H=>e?.indexOf(H)>=0),O=!isNaN(n),x=n===$p,F=Bd.includes(n),L=e?.split("").find(H=>AT.includes(H)),w=F&&f&&!D&&(U||!i_({scoreString:e}));return{isTiebreakSetValue:I&&O,matchUpScoringFormat:a,setNumber:s,setFormat:u,matchTiebreakHasJoiner:N,isGameScoreEntry:b,isSpace:x,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:R,isInvalidSetTiebreakValue:x&&g&&y,isInvalidMatchTiebreakValue:w,isTiebreakEntry:g,isSetTiebreakEntry:l,isMatchTiebreakEntry:f,isIncompleteSetScore:T,isIncompleteSetTiebreak:y,isIncompleteMatchTiebreak:D,isPartialMatchTiebreakValue:U}}function LP(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(!xP.includes(r))return{updated:!1,info:"invalid key"};c&&(e=3-e);let{matchUpWinningSide:l}=wP({sets:o,winningSide:i,matchUpStatus:s,matchUpFormat:a});i=l;let f=p_({value:r,winningSide:i,scoreString:n,sets:o,matchUpFormat:a});if(OP.includes(r)&&(r=oa),f.hasOpener&&f.isTiebreakEntry&&!f.isTiebreakSet&&d&&ut(r)===0&&(f.isTiebreakCloser=!0),Bd.includes(r)&&f.hasOpener&&(r=""),Bd.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}=a_({analysis:f,lowSide:e,scoreString:n,sets:o,matchUpStatus:s,winningSide:i,value:r}));else if(Vd.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}=UT({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===Gd)p=!0,{scoreString:n,sets:o}=Fg({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===oa&&!f.isMatchTiebreakEntry)(!f.isSetTiebreakEntry||f.isSetTiebreakEntry&&!f.isNumericEnding)&&(p=!0,{scoreString:n,sets:o}=Fg({analysis:f,scoreString:n,sets:o,lowSide:e}),s=void 0);else if(r===ci&&f.isMatchTiebreakEntry&&!f.isSetTiebreakEntry)f.matchTiebreakHasJoiner?m="existing joiner":f.isNumericEnding&&(p=!0,n+=ci);else if([oa,ci].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}=s_({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?Ds:Ps,I=g.split("").reverse()[0],h=g.split("")[0],S=o[o.length-1],{tiebreakFormat:T}=f.setFormat,{tiebreakTo:y,NoAD:D}=T||{},U=Qp({set:S});if(!f.isTiebreakSet){let E=parseInt(n.split(h).reverse()[0]),M=ET({lowValue:E,tiebreakTo:y,NoAD:D});U===1?(S.side1TiebreakScore=M,S.side2TiebreakScore=E):(S.side1TiebreakScore=E,S.side2TiebreakScore=M)}n=(n||"")+I,f.isDecidingSet||(n+=na);let A=Hd({analysis:f,set:S});S.winningSide=A||void 0,p=!0}else if(f.isTiebreakSetValue)({info:m,scoreString:n,sets:o,updated:p}=c_({analysis:f,auto:u,lowSide:e,scoreString:n,sets:o,value:r}));else if(f.isSetTiebreakEntry){let[g]=Ds.split(""),I=Math.max(...lo(g,n.split(""))),h=n.slice(I+1),S=h&&ut(h)===e_,T=ut(h?h+r:r),{tiebreakFormat:y}=f.setFormat,{tiebreakTo:D,NoAD:U}=y||{};!S&&h.length<2?U&&T>D-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}=u_({analysis:f,lowSide:e,scoreString:n,value:ut(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}=wP({sets:o,winningSide:i,matchUpStatus:s,matchUpFormat:a});return i=g,g&&(!s||[zt,Pn].includes(s))?(s=JO,o=o.filter(I=>{let{side1Score:h,side2Score:S,side1TiebreakScore:T,side2TiebreakScore:y}=I;return h||S||T||y})):n&&!i&&![TT,ST,yT].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 Wd="\\d+-\\d+",Xp="\\d+-\\d+\\(\\d+\\)",kg="\\[\\d+-\\d+\\]",tV="\\d+-\\d+\\(\\d+-\\d+\\)",m_=new RegExp(`(${Wd}),`,"g"),d_=new RegExp(`(${Xp}),`,"g"),eV=[Wd,Xp,kg,tV],rV=["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"],nV=rV.map(t=>{let r=t.split("").map(n=>eV[n]).join(" ");return new RegExp(`^${r}$`)});function FP(t){return!t||nV.some(e=>e.test(t))}function l_(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 jd(t){return/^\(\d+\)$/.test(t)||/^\(\d+$/.test(t)}function f_(t){return/^\(\d+-\d+\)$/.test(t)||/^\[\d+-\d+\]$/.test(t)}function ka(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 Jp(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 kP(t){return t.length===2?t.split("").join("-"):([", ",",","/"," "].forEach(e=>t=t.split(e).join("-")),t=t.replace(/-{2,}/,"-"),t)}function g_(t){return t.startsWith("(")&&t.endsWith(")")}function I_({score:t,applied:e}){t=l_(t);let r=/\)(\d+)/g;if(r.test(t))for(let U of t.match(r)){let A=U.replace(")",") ");t=t.replace(U,A)}t=t.replace(/\)\//g,") / "),t=t.replace(/\/\)/g,")");let n=/\(([\d- ]+)\)/g,o=/\(([\d- ]+)\)/,i=t.match(n);for(let U of i||[]){let[A]=U.match(o).slice(1),E=A.replace(/ /g,"");t=t.replace(U,`(${E})`)}let s=/\(\(\d-\d\)\)/g;if(s.test(t)){let U=t.match(s);U.length&&U.forEach(A=>{let E=A.match(/\((\(\d-\d\))\)/).slice(1)[0];t=t.replace(A,E)})}if(s=/\(\((\d)\)\)/g,s.test(t)){let U=t.match(s);U.length&&U.forEach(A=>{let E=A.match(/\((\(\d\))\)/).slice(1)[0];t=t.replace(A,E)})}/(^|\s)6-,/.test(t)&&(t=t.replace(/(^|\s)6-,/g,"6-0,"));let a=new RegExp(/[-,]{2,}/g);t=t.replace(a,"-"),["- "," -"].forEach(U=>{let A=new RegExp(`(\\d+)${U}(\\d+)`,"g"),E=t.match(A);E&&E.forEach(M=>t=t.replace(M,M.split(U).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[E]=A.match(/\((\d+), \)/).slice(1);E.length===2?t=t.replace(A,`(${E})`):E.length===1&&E==="6"&&(t=t.replace(A,"(6-0)"))});let u=/\((\d+)\/\)/g;u.test(t)&&t.match(u).forEach(A=>{let[E]=A.match(/\((\d+)\/\)/).slice(1);E.length===2?t=t.replace(A,`(${E})`):E.length===1&&E==="6"?t=t.replace(A,"(6-0)"):t=t.replace(A,`(${E})`)});let p=/\d\/\d\/,/g;p.test(t)&&t.match(p).forEach(A=>{let[E]=A.match(/(\d\/\d)\/,/).slice(1);t=t.replace(A,`${E},`),e.push("slashComma")});let m=/\(\/(\d+)\)/g;m.test(t)&&t.match(m).forEach(A=>{let[E]=A.match(/\(\/(\d+)\)/).slice(1);E.length===2?t=t.replace(A,`(${E})`):E.length===1&&parseInt(E)<6?t=t.replace(A,`(6-${E})`):t=t.replace(A,`(${E})`)});let d,l,f,g,I,h=()=>{I=gr(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[U]=t.match(S).slice(1);t=t.replace(S,U+")")}if(I["("]===I[")"]&&I["("]>1){let U=t.split(")(").join(") (").split(" ");U.every(g_)?t=U.map(A=>{let E=A.slice(1,A.length-1);return E.length>2?E:A}).join(" "):t=U.join(" ")}h();let T=/[A-Za-z]+/.test(t),y=/\d+/.test(t);if(!T&&!y)return{score:""};if(/^\[.+\]$/.test(t)&&"()/,- ".split("").some(U=>I[U])&&(t=t.slice(1,t.length-1)),/^\(.+\)$/.test(t)&&I["("]===1&&I[")"]===1&&"[]/,".split("").some(U=>I[U]>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 U=[],A=0;for(let E of t.split("").reverse())E===")"&&(A?U.push("("):A+=1),E==="("&&(A-=1),U.push(E);U.reverse(),t=U.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 U="",A=0;for(let E of t.split(""))E==="("&&(A?U+=")":A+=1),E===")"&&(A-=1),U+=E;t=U}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 D=U=>{let A=U.indexOf("("),E=U.indexOf(")");return A>=0&&E>=0&&A<E};if(/^\([\d ]+.*[\d ]+\)$/.test(t)&&I["("]===I[")"]){let U=t.slice(1,t.length-1);D(U)&&(t=U,h())}return{score:t,applied:e}}function Bu(t){if(!/^[\d-]+(\(\d\))*$/.test(t))return t;let e=lo("-",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 h_({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(")")),[m_,d_].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(Bu).join(" "),{score:t,applied:e}}function S_({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(jd),i=0,s="";for(let d of o){let l=lo(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,D=[T,y].sort().reverse().join("-"),U=[f.join(" "),[D,d].join("")].join(" ");s+=U,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=>f_(d)&&"bracket"||ka(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=lo("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;!ka(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(kg).test(d)&&"super"||new RegExp(Xp).test(d)&&"tiebreak"||new RegExp(Wd).test(d)&&"standard"||"unknown";return u.push(g),g==="standard"&&f?d.match(l)[1]:d}).join(" "),{score:t}}function T_({score:t,applied:e}){for(let P of[".",","," ","/"]){let N=new RegExp(`^(\\d+)\\${P}(\\d+)$`);if(N.test(t)){let R=t.match(N).slice(1).map(v=>parseInt(v)),b=Math.abs(R[0]-R[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,N,R,b,v,O]=t.match(r).slice(1);t=t.replace(r,`${P}${N}-${R} ${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(N=>(i.test(N)&&(N=N.replace("("," (")),s.test(N)&&(N=N.replace(")",") ")),N)).join(" "),e.push("spaceConsiderationPatterns")});let c=Bu(t);c!==t&&(t=c,e.push("deDashMash"));let u=/^(\d)[-/,]+(\d{2})[-/,]+(\d)$/;if(u.test(t)){let[P,N,R]=t.match(u).slice(1),[b,v]=N.split("");t=`${P}-${b} ${v}-${R}`,e.push("smashSetPattern")}let p=/^(\d+)[ -](\d+)$/,m=/^([\d -]+)\/([\d -]+)$/;if(m.test(t)){let[P,N]=t.match(m).slice(1),R=P.trim(),b=N.trim();if(p.test(R)&&p.test(b)){let v=R.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,N]=t.match(d).slice(1),R=P.trim(),b=N.trim();if(p.test(R)&&p.test(b)){let v=R.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],N=P.slice(0,P.length-1).split(" ").join("-");t=t.replace(P,N),e.push("singleSetCommaSeparationPattern")}let f=0,g=/(\d+)-(\d{2})-(\d+)/;for(;g.test(t)&&f<3;){let[P,N,R]=t.match(g).slice(1),b=N.split(""),v=`${P}-${b[0]} ${b[1]}-${R}`;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(N=>{let R=N.match(P).slice(2)[0];t=t.replace(N,`7-6(${R}) `),e.push("floatingTiebreakPattern1")})}let S=t.match(/\d \d /);S?.forEach(P=>{let N=P.slice(0,P.length-1).split(" ").join("-");t=t.replace(P,N),e.push("spaceSeparatedSetPattern1")}),S=t.match(/ \d \d$/),S?.forEach(P=>{let N=" "+P.slice(1).split(" ").join("-");t=t.replace(P,N),e.push("spaceSeparatedSetPattern2")});let T=/^\d, *\d\/\d, *\d/;if(T.test(t)){let P=t.match(T)[0],N=P.split("/").map(R=>`(${R})`).join(" ")+" ";t=t.replace(P,N),e.push("slashCommaSetPattern")}let y=/\(6-\)/g;y.test(t)&&(t=t.replace(y,"(6-0)"),e.push("missingZeroPattern2"));let D=/(?<!-)(\d+)\/(\d+)(?!-)/g;if(D.test(t)){let P=t.match(D),N=/(?<!-)(\d+)\/(\d+)(?!-)/,R=t;P.forEach(b=>{let[v,O]=b.match(N).slice(1),x=`${v}-${O}`;R=R.replace(b,x)}),t=R,e.push("slashSetPattern")}let U=/(.*)\s(1\d)\s(\d+)$/;if(U.test(t)){let[P,N,R]=t.match(U).slice(1);P.replace(/\D/g,"").length>=4&&(t=P+` ${N}${R}`,e.push("spaceSeparatedSuperPattern"))}let A=/(^|\s)(\d+-\d+)\s(\d+)(\s|$)/g;for(let P of t.match(A)||[]){let[N,R,b,v]=P.match(/(^|\s)(\d+-\d+)\s(\d+)(\s|$)/).slice(1),[O,x]=R.split("-").map(L=>parseInt(L));Math.abs(O-x)===1&&(t=t.replace(P,`${N}${R}(${b})${v}`),e.push("spaceSeparatedSetPattern"))}let E=/\d-\d \(\d{1,2}\)(\s|$|,)/g;for(let P of t.match(E)||[]){let N=/(\d-\d) \((\d{1,2})\)(\s|$|,)/,[R,b,v]=P.match(N).slice(1),[O,x]=R.split("-").map(L=>parseInt(L));Math.abs(O-x)===1&&(t=t.replace(P,`${R}(${b})${v}`),e.push("floatingTiebreakPattern2"))}let M=/(^|\s)(\d \d)\(/g;for(let P of t.match(M)||[]){let N=/(^|\s)(\d \d)\(/,[R,b]=P.match(N).slice(1);t=t.replace(P,`${R}${b.split(" ").join("-")}(`),e.push("spacedTiebreakPattern")}return{score:t,applied:e}}function y_({score:t,matchUpStatus:e}){let r=t?.split(" ");t=r.map(a=>{if(a.endsWith("]")){let c=a.split("[");if(ka(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=Jp(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 ka(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 A_({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=kP(l),h=Bu(I);t=t.replace(m,`(${h})`).trim()}let i=new RegExp(/\[[\d,/ ]+\]/g);t.match(i)?.forEach(m=>{let d=kP(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(",")||jd(h)),f=d.every(h=>h.includes("/")||jd(h)),g=d.every(h=>h.includes("-")||jd(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(D=>parseInt(D.trim())),y=Math.min(...T);h==="set"?m+=`(${y}) `:m+=`[${T.join("-")}] `,h="tiebreak"}}),t=m.trim()}}let u=gr(t.split(""));u["("]===1&&u[")"]===1&&t.startsWith("(")&&t.endsWith(")")&&(t=t.slice(1,t.length-1),u["-"]===1&&ka(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 DT({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 Gg(t){let e=t.indexOf("1"),r=t.split(""),n=r.every(o=>!isNaN(o));if(n&&t.length===3&&e===0){let o=Jp(r,e);if(o)return o}if(n&&t.length===7&&e>3){let o=r.slice(4),i=Jp(o,e-4);if(i)return`${r[0]}-${r[1]} ${r[2]}-${r[3]} ${i}`}}function GP(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}=DT({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=Gg(e);u&&e!==u&&r.push("parsedSuperPattern"),e=u??e}else{let u=Ae(e.split(""),2).map(h=>h.join("")),p=u.map(h=>{let[S,T]=h.split("").map(U=>parseInt(U)),y=Math.abs(S-T),D=S>T?1:2;return y>1&&D||D*-1}),m=p.reduce((h,S)=>h>0&&S>0,1),d=gr(p),l=p.map(h=>Math.abs(h)),f=gr(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,D,U]=a,A=p.reduce((E,M,P)=>M<0?P:E,void 0);if(A===0){let E=Math.min(T,y);e=`${h}-${S}(${E}) ${D}-${U}`,r.push("chunkSplitTiebreak1")}else if(A===1){let E=Math.min(D,U);e=`${h}-${S} ${T}-${y}(${E})`,r.push("chunkSplitTiebreak2")}else e=`${h}-${S} ${T}-${y}`,r.push("chunkSplitTrimExtraneous")}}else if(a.length===8){let[h,S,T,y,D,U,A,E]=a;g||I?a[5]===1&&(g?e=`${h}-${S}(${T}) ${y}-${D} [${U}${A}-${E}]`:e=`${h}-${S} ${T}-${y}(${D}) [${U}${A}-${E}]`):(p[0],p[1])}}}return{score:e,applied:r,matchUpStatus:n}}function PT(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 E_({score:t,matchUpStatus:e,attributes:r}){let n=[],o,i=t.split(" "),s=i.length;t=i.map((p,m)=>{if(new RegExp(Xp).test(p)){let l=p.slice(3),f=p.slice(0,3),g=f.split("-");if(!ka(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=Bu(p);let d=new RegExp(`^${kg}$`).test(p)&&"super"||new RegExp(`^${Xp}$`).test(p)&&"tiebreak"||new RegExp(`^${Wd}$`).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(D=>parseInt(D)>h||m&&parseInt(D)<=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}=PT(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 U_({score:t}){let{setsTied:e,winningSide:r}=PT(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 oV({score:t}){return t=t?.toString().toLowerCase()||"",{score:t}}function iV({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 sV({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=Jp(r.split(""),n);return e.push("getSuper"),o}}else{let{score:o,applied:i}=GP({score:r,applied:[]});o!==r&&(r=o,e.push(...i))}}return r}).join(" "),{score:t,applied:e})}function aV({score:t,applied:e}){return typeof t!="string"?{score:t}:[3,4].includes(t.length)&&Gg(t)?{score:Gg(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 cV({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 uV({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 pV({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 mV({score:t}){return new RegExp(/-\d+\/\d+-/).test(t)&&(t=t.split("/").join(" ")),{score:t}}function dV({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 lV({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 fV({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 gV({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 D_={handleTiebreakSlashSeparation:lV,handleSetSlashSeparation:mV,punctuationAdjustments:I_,handleGameSeparation:dV,joinFloatingTiebreak:S_,handleBracketSpacing:h_,handleSpaceSeparator:fV,separateScoreBlocks:sV,matchKnownPatterns:T_,removeDanglingBits:pV,removeErroneous:aV,handleWalkover:cV,properTiebreak:y_,handleNumeric:GP,handleRetired:uV,containedSets:A_,sensibleSets:E_,stringScore:oV,superSquare:U_,setBuilder:DT,excisions:gV,replaceOh:iV};var VP={},IV=[],hV=["handleNumeric","handleWalkover","handleRetired","replaceOh","stringScore","punctuationAdjustments","excisions","handleSpaceSeparator","matchKnownPatterns","removeDanglingBits","handleBracketSpacing","matchKnownPatterns","containedSets","separateScoreBlocks","handleGameSeparation","removeErroneous","joinFloatingTiebreak","handleSetSlashSeparation","handleTiebreakSlashSeparation","properTiebreak","sensibleSets","superSquare"],SV=["handleNumeric","separateScoreBlocks","sensibleSets","superSquare"];function BP(t){if(!t.score)return{error:k};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=D_[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(hV);let g=FP(l);return g||(l=e.toString().replace(/\D/g,""),m?.removed&&(m.removed=void 0),f(SV),g=FP(l),g||(IV.push({score:l,fileName:o,sheetName:r}),l="")),p.forEach(I=>{VP[I]||(VP[I]=0),VP[I]+=1}),{matchUpStatus:u?.toUpperCase(),modifications:c,attributes:m,isValid:g,score:l}}var WP={};Qt(WP,{analyzeScore:()=>Vg,analyzeSet:()=>Hu,checkScoreHasValue:()=>me,checkSetIsComplete:()=>zp,getSetComplement:()=>Hg,getTiebreakComplement:()=>Zp,isValidMatchUpFormat:()=>Ar,parseScoreString:()=>Yd,validateScore:()=>Bg,validateTieFormat:()=>mr});function Vg({existingMatchUpStatus:t,matchUpFormat:e,matchUpStatus:r,winningSide:n,score:o}){let i=o?.sets??[],a=(i?.filter(A=>A?.winningSide)||[]).reduce((A,E)=>{let{winningSide:M}=E;if(!M)return A;let P=M-1;return A[P]++,A},[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=gr(a)[l],g=d?.setFormat?.timed||d?.finalSetFormat?.timed,I=d?.bestOf,h=I&&Math.ceil(I/2)||1,S=r??t,T=S&&[Mt,Qe,vt].includes(S),y=!d||!i.length||i.every((A,E)=>{let M=E+1,P=M===I,N=M===i.length,{side1Score:R,side2Score:b,side1TiebreakScore:v,side2TiebreakScore:O,winningSide:x}=A,F=Math.max(R??0,b??0),L=v??O,{finalSetFormat:w,setFormat:B}=d,G=P&&w||B;if(L){let{tiebreakTo:H,NoAD:q}=G?.tiebreakFormat||{},$=Math.max(v??0,O??0);if(q&&$>H||$<H&&x&&(N&&!T||!N))return!1}return G.setTo?!(!G.noTiebreak&&F>G.setTo+1):!0}),D=(!e||l===h)&&f===1&&a.indexOf(l)+1||void 0;return{valid:!!(y&&(n&&p>m&&n===D||n&&T||!n&&!D&&(![ue,Mt,Qe,vt].includes(S)||g&&S===ue)))}}function Bg({existingMatchUpStatus:t,matchUpFormat:e,matchUpStatus:r,winningSide:n,score:o}){if(typeof o!="object")return{error:k};let{sets:i,scoreStringSide1:s,scoreStringSide2:a}=o,c="scoreString must be a string!";if(s!==void 0&&typeof s!="string")return{error:k,info:c};if(a!==void 0&&typeof a!="string")return{error:k,info:c};if(i!==void 0&&!Array.isArray(i))return{error:k,info:ko("sets")};if(i?.length){let u=i.map(m=>m?.setNumber).filter(Boolean);if(u.length!==pt(u).length)return{error:k,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(U=>U.some(A=>![void 0,null].includes(A))).every(U=>U.every(A=>ft(A))))return{error:k,info:"non-numeric values"};if(![T,S].filter(U=>![void 0,null].includes(U)).every(U=>ft(U)))return{error:k,info:"non-numeric values"};if(S&&![1,2].includes(S))return{error:k,info:"winningSide must be 1 or 2"}}let{valid:p}=Vg({existingMatchUpStatus:t,matchUpStatus:r,matchUpFormat:e,winningSide:n,score:o});if(!p)return{error:sE,info:"score is invalid for matchUpFormat or winningSide does not match calculated winningSide"}}return{valid:!0}}var Hg=t=>{let{isSide1:e,lowValue:r,setTo:n,tiebreakAt:o,NoAD:i}=t;if(r===void 0)return!1;let s=ut(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]},Zp=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=TV({lowValue:i,NoAD:o,tiebreakTo:n});return[e?i:s,e?s:i]};function TV(t){let{lowValue:e,NoAD:r,tiebreakTo:n}=t,o=r?1:2;return e+1>=n?e+o:n}function Yd({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&&Zp({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 P_({matchUpScoringFormat:t,isDecidingSet:e,isTiebreakSet:r,setObject:n}){if(!n)return;let o=Qp({set:n});return zp({matchUpScoringFormat:t,set:n,isDecidingSet:e,isTiebreakSet:r})&&o||void 0}function Hu(t){let{setObject:e,matchUpScoringFormat:r}=t;if(!e)return{error:Wl};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(x=>x!==void 0).length,g=d.filter(x=>x!==void 0).length,I=l.filter(x=>x!==void 0).length,h=m?.filter(x=>!isNaN(x)).length,S=l?.filter(x=>!isNaN(x)).length,{tiebreakAt:T}=s||{},y=T&&m.filter(x=>x>=T).length===2,D=y&&(m[0]>m[1]&&1||m[1]>m[0]&&2||void 0),U=!!(S&&!h),A=!!e?.winningSide,{error:E,result:M}=yV({setObject:e,setFormat:s,sideGameScores:m,sideTiebreakScores:l}),{error:P,result:N}=AV({setObject:e,setFormat:s,sideTiebreakScores:l}),R=u&&!U&&M||a&&U&&N,b=p&&!(a&&!U)&&!(u&&U)&&(!A||R),v=P_({isDecidingSet:i,isTiebreakSet:U,matchUpScoringFormat:r,setObject:e}),O={expectTiebreakSet:a,expectTimedSet:c,hasTiebreakCondition:y,isCompletedSet:A,isDecidingSet:i,isTiebreakSet:U,isValidSet:b,isValidSetNumber:p,isValidSetOutcome:R,leadingSide:D,setFormat:s,sideGameScores:m,sideGameScoresCount:f,sidePointScores:d,sidePointScoresCount:g,sideTiebreakScores:l,sideTiebreakScoresCount:I,winningSide:v};return e?.winningSide!==void 0&&(U?(O.isValidTiebreakSetOutcome=N,N||(O.tiebreakSetError=P)):(O.isValidStandardSetOutcome=M,M||(O.standardSetError=E))),O}function yV({setObject:t,setFormat:e,sideGameScores:r,sideTiebreakScores:n}){if(!t)return{result:!1,error:Wl};let o=!!e?.tiebreakSet,i=!!e?.timed;if(!e||o||i)return{result:!1,error:k};if(!(r?.filter(N=>!isNaN(N)).length===2))return{result:!1,error:kI};let{setTo:a,tiebreakAt:c,tiebreakFormat:u,NoAD:p}=e||{};if(!!!(a&&r?.find(N=>N>=a)))return{result:!1,error:kI};let d=[1,2].includes(t?.winningSide);if(!t||!d)return{result:!1,error:Nm};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(N=>!isNaN(N)).length===2,D=n?.[l],U=n?.[f],A=c&&r.filter(N=>N>=c).length===2;if(T){let{NoAD:N,tiebreakTo:R}=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(R))return{result:!1,error:{message:"tiebreakTo error"}};if(!!!(R&&n?.find(B=>B>=R)))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(!D||!U||D<U)return{result:!1,error:{message:"winningSide tiebreak value is not high"}};let x=N?1:2,F=D-U,L=U>=R-1;if(F&&L&&F<x)return{result:!1,error:{message:"invalid tiebreak scores (3)"}}}if(g>a&&!A)return{result:!1,error:{message:"invalid winning game scoreString (2)"}}}let E=p?1:2,M=I>=a-1;return h&&M&&!A&&h<E?{result:!1,error:{message:"invalid winning game scoreString (3)"}}:h>E&&g>a?{result:!1,error:{message:"invalid winning game scoreString (4)"}}:{result:!0}}function AV({setObject:t,setFormat:e,sideTiebreakScores:r}){if(!t)return{result:!1,error:Wl};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:Nm};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 NT={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 MT={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 RT={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 CT={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 bT={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 vT={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 OT={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 _T={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 xT={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 wT={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 LT={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 FT={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 kT={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 GT={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 VT={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 BT={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 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:"Overtime",matchUpCount:1,gender:"MIXED",matchUpFormat:"SET1-S:T20",matchUpType:"DOUBLES",scoreValue:1}],tieFormatName:"USTA_TOC",winCriteria:{aggregateValue:!0}};var qd="COLLEGE_DEFAULT",WT="COLLEGE_JUCO",jT="COLLEGE_D3",jP="DOMINANT_DUO",YP="DOMINANT_DUO_MIXED",qP="LAVER_CUP",$P="TEAM_DOUBLES_3_AGGREGATION",KP="TIME_TENNIS_DUAL",zP="TIME_TENNIS_PRO_CIRCUIT",QP="USTA_BREWER_CUP",XP="USTA_OZAKI_CUP",JP="USTA_COLLEGE",ZP="USTA_GOLD_TEAM_CHALLENGE",tN="USTA_LEVEL_1",eN="USTA_INTERSECTIONAL",rN="USTA_SECTION_BATTLE",nN="USTA_SOUTHERN_LEVEL_5",oN="USTA_TOC",iN="USTA_WTT_ITT",sN="USTA_ZONAL",N_={COLLEGE_D3:jT,COLLEGE_DEFAULT:qd,COLLEGE_JUCO:WT,DOMINANT_DUO:jP,DOMINANT_DUO_MIXED:YP,LAVER_CUP:qP,TEAM_DOUBLES_3_AGGREGATION:$P,TIME_TENNIS_DUAL:KP,TIME_TENNIS_PRO_CIRCUIT:zP,USTA_BREWER_CUP:QP,USTA_OZAKI_CUP:XP,USTA_COLLEGE:JP,USTA_GOLD_TEAM_CHALLENGE:ZP,USTA_INTERSECTIONAL:eN,USTA_LEVEL_1:tN,USTA_SECTION_BATTLE:rN,USTA_SOUTHERN_LEVEL_5:nN,USTA_TOC:oN,USTA_WTT_ITT:iN,USTA_ZONAL:sN};var R_="STANDARD",M_={[R_]:{hydrate:!0,doubles:{matchUpCount:3,matchUpValue:1},singles:{matchUpCount:6,matchUpValue:1},valueGoal:5},[jT]:{hydrate:!0,doubles:{matchUpFormat:"SET1-S:8/TB7@7",matchUpCount:3,matchUpValue:1},singles:{matchUpFormat:Cn,matchUpCount:6,matchUpValue:1},tieFormatName:jT,valueGoal:5},[qd]:{hydrate:!0,doubles:{matchUpFormat:"SET1-S:6/TB7",collectionValue:1,matchUpCount:3},singles:{matchUpFormat:Cn,matchUpCount:6,matchUpValue:1},tieFormatName:qd,valueGoal:4},[WT]:{hydrate:!0,doubles:{matchUpFormat:"SET1-S:8/TB7",matchUpCount:3,matchUpValue:1},singles:{matchUpFormat:Cn,matchUpCount:6,matchUpValue:1},tieFormatName:WT,valueGoal:5},[qP]:BT,[jP]:LT,[YP]:OT,[$P]:MT,[KP]:_T,[zP]:vT,[QP]:xT,[XP]:wT,[JP]:FT,[ZP]:NT,[eN]:bT,[tN]:kT,[rN]:CT,[nN]:RT,[iN]:GT,[oN]:HT,[sN]:VT},GV=t=>{let e=t?.namedFormat&&Object.keys(M_).includes(t.namedFormat)?t.namedFormat:R_,r=Array.isArray(t?.uuids)?t?.uuids:[],n,{category:o,gender:i}=t?.event??{},s=J(M_[e],!1,!0),a=c=>{if(!t?.isMock&&!t?.event?.isMock||!t.event)return r?.pop()??Nt();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:CD,collectionName:"Doubles",matchUpType:kt,...s.doubles},{collectionId:a(1),matchUpFormat:Cn,collectionName:"Singles",matchUpType:Bt,...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},ui=GV;function C_(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===Me&&s===Me){let m=e?.structures?.find(({stage:d})=>d===et)?.tieFormat;u=u||m||o&&c?.tieFormat?.tieFormatName===o&&c.tieFormat||o&&ui({namedFormat:o,hydrateCollections:r,isMock:a,event:c})||c?.tieFormat||ui({event:c,isMock:a,hydrateCollections:r}),p=void 0}else p||(u=void 0,c?.matchUpFormat||(p=Cn));if(u){let m=mr({gender:c?.gender,enforceGender:n,tieFormat:u});if(m.error)return m}return{tieFormat:u,matchUpFormat:p}}function b_(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?uT({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===et&&y===1),{qualifiersCount:g}=Ts({stageSequence:1,drawDefinition:e,structureId:i,stage:et}),I=Math.max(m??0,g??0),h=PS({qualifiersCount:I,drawDefinition:e,stage:et});if(h.error||(h=kp({drawSize:d,stage:ct,drawDefinition:e}),h.error))return h;VV({drawDefinition:e,drawEntries:o,event:c});let S=BV({mainStructure:f,qualifyingDetails:l,drawDefinition:e});return S.error?S:{drawDefinition:e,structureId:i}}function VV({drawDefinition:t,drawEntries:e,event:r}){for(let n of(e??[]).filter(({entryStage:o})=>o===ct)){let o={...n,entryStage:n.entryStage??et,drawDefinition:t,event:r};cS(o)}}function BV({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&&_a({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 YT(t){let{participantIds:e}=t,r=t.drawDefinition?.entries?.filter(n=>{let o=n.entryStatus;return!t.restrictEntryStatus||Wr.includes(o)}).map(ht)??[];if(e){let n=e.filter(o=>!r?.includes(o));if(n?.length)return _({result:{error:pn},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:k,info:"Not enough participants for roundsCount"}:t.roundsCount&&t.restrictRoundsCount!==!1&&t.roundsCount>31?{error:k,info:"roundsCount must be less than 32"}:{participantIds:e}}function $d(t){let e=[],{roundsCount:r=1,drawDefinition:n,matchUpsCount:o,structureId:i,idPrefix:s,isMock:a,event:c}=t,u,p=YT(t);if(p.error)return p;for(let m of tt(1,r+1)){let d=Gu({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 O_(t){let{tournamentRecord:e,participantIds:r,scaleName:n,eventType:o,adHocRatings:i={}}=t,s=t.scaleAccessor??ve[n]?.accessor,a=e.participants??[];for(let c of r??[]){let u=a?.find(m=>m.participantId===c),p=v_({scaleName:`${n}.${Lm}`,participant:u,eventType:o});!p&&n&&(p=v_({scaleAccessor:s,participant:u,scaleName:n,eventType:o})),p&&!i[c]&&(i[c]=p)}return i}function v_({scaleType:t=Si,scaleAccessor:e,participant:r,scaleName:n,eventType:o}){let a=(r&&Uo({scaleAttributes:{eventType:o??ks,scaleType:t,scaleName:n},participant:r}))?.scaleItem?.scaleValue;return e&&It(a)?a[e]:a}function Kd(t){let e=WV(t);if(e?.error)return e;let r=YT(t);if(r.error)return r;let n=HV(t);if(n.error)return n;let o=O_(t),i=t.tournamentRecord?.isMock??t.isMock,s=t.eventType??t.event?.eventType,a=[],c=[],u;for(let p of tt(1,(t.roundsCount??1)+1)){let m=kd({...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;l.modifiedScaleValues&&(o=l.modifiedScaleValues),c.push({...l,iteration:p,matchUpsCount:d?.length}),u=(l?.roundNumber??1)+1,d?.length&&a.push(...d)}return{...C,matchUps:a,roundResults:c}}function HV(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&&Gs[s.stage];return pr({structure:s})&&a>(Gs[i?.stage]||1)?s:i},void 0),n=e?.structures?.find(i=>i.structureId===r?.structureId);return n?pr({structure:n})?{structure:n}:{error:fa}:{error:Lt}}function WV(t){return t.roundsCount&&typeof t.roundsCount!="number"?{error:k,info:"roundsCount must be a number"}:typeof t.drawDefinition!="object"||t.drawDefinition.drawType&&t.drawDefinition.drawType!==an?{error:fa}:!Array.isArray(t.drawDefinition?.entries)&&t.participantIds&&!Array.isArray(t.participantIds)?{error:k,info:"Missing Entries"}:{error:void 0}}function __(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===et)&&m&&Wr.includes(m)),c=a?.map(ht),u=a?Math.floor(a.length/2):0;if(t.automated)return jV({...t,participantIds:c});{let p=$d({roundsCount:t.roundsCount,drawDefinition:r,matchUpsCount:u,idPrefix:o,isMock:i,event:s});if(p.error)return p;p.matchUps?.length&&vd({matchUps:p.matchUps,suppressNotifications:!0,tournamentRecord:e,drawDefinition:r,structureId:n,event:s})}return{...C}}function jV(t){let{restrictEntryStatus:e,generateMatchUps:r,structureId:n,matchUpIds:o,scaleName:i,scaleAccessor:s}=t.drawMatic??{},a=Kd({...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&&vd({tournamentRecord:t.tournamentRecord,drawDefinition:t.drawDefinition,suppressNotifications:!0,matchUps:a.matchUps,event:t.event,structureId:n}),{...C})}function x_({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=at({drawDefinition:s,structureId:c});if(p.error)return p;let m=p.structure;if(!m)return{error:Lt};let{positionAssignments:d}=le({structure:m}),l=d?.length||0;if(u>l)return{error:FA};let f=m.structures?.length,g=ft(a?.groupSeedingThreshold)&&a?.groupSeedingThreshold,I=fg({roundRobinGroupsCount:f,drawSize:l})?.seedGroups,{seedsCount:h}=ku({policyDefinitions:i,requireParticipantCount:t,drawSizeProgression:r,participantsCount:n,drawSize:l});return h&&i?.[xn]&&u>h&&e&&(u=h),m.seedLimit=u,m.seedAssignments=tt(1,u+1).map(S=>{let T=I?.find(U=>U.includes(S)),y=T&&Math.min(...T),D=g&&S>=g?y:S;return{participantId:void 0,seedNumber:S,seedValue:D}}),Ot({drawDefinition:s,structureIds:[c]}),{...C,seedLimit:u}}function ia({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}=Oc({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 qT(t){let e="prepareStage",{drawDefinition:r}=t,{structures:n}=ln({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:Lt},stack:e});let s=i?.structureId,{seedsCount:a,stageEntries:c,seedLimit:u}=JV({...t,structureId:s});(t.seededParticipants||t.event||t.seedingScaleName)&&$V({...t,seedsCount:a,structure:i,structureId:s});let p=t.automated!==!1&&t.drawType!==an&&!(t.qualifyingOnly&&t.stage!==ct),m=(n?.length||0)>1,d=p?qV({...t,multipleStructures:m,seedLimit:u,structureId:s}):{};return d?.error?_({result:d,stack:e}):{...d,stageEntries:c,structureId:s,seedsCount:a}}function YV({entries:t,stage:e,stageSequence:r,roundTarget:n}){return t.filter(o=>{let i=mt({name:Dn,element:o})?.extension?.value;return(!o.entryStage||o.entryStage===e)&&(!r||!o.entryStageSequence||o.entryStageSequence===r)&&(!n||!i||i===n)&&ni.includes(o.entryStatus)})}function qV(t){let e=typeof t.automated=="object"&&t.automated.seedsOnly,r=Uc({...t,seedsOnly:e});if(r.error)return r;let n=r?.positionAssignments,o=r?.positioningReport;return{conflicts:r.conflicts,positionAssignments:n,positioningReport:o}}function $V(t){let{seededParticipants:e,seedingScaleName:r,entries:n,event:o}=t,i=n.map(ht);e?KV({...t,enteredParticipantIds:i}):(o||r)&&zV({...t,enteredParticipantIds:i})}function KV(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?Es({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;Js({provisionalPositioning:e,tournamentRecord:o,drawDefinition:s,seedingProfile:a,participantId:l,seedBlockInfo:m,structureId:c,seedNumber:f,seedValue:g,event:p})})}function zV(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=QV({...t,ageCategoryCode:l,categoryName:d,eventType:f})||c&&XV({...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:D}=h,U=o?.[T]||D||T;Js({provisionalPositioning:r,tournamentRecord:s,drawDefinition:a,seedingProfile:u,participantId:y,structureId:p,seedNumber:T,seedValue:U,event:m})})}function QV(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:So,eventType:u};return ia({scaleAttributes:p,tournamentRecord:e,stageSequence:n,entries:o,stage:i}).scaledEntries}function XV(t){let{tournamentRecord:e,stageSequence:r,event:n,entries:o,stage:i}=t,{categoryName:s,ageCategoryCode:a}=n?.category||{},c=n?.eventType;return ia({scaleAttributes:{scaleName:s||a,scaleType:hi,eventType:c},tournamentRecord:e,stageSequence:r,entries:o,stage:i}).scaledEntries}function JV(t){let{seedsCount:e}=t;t.seededParticipants&&(e=t.seededParticipants.length),e>t.drawSize&&(e=t.drawSize);let r=YV(t);e>r.length&&(e=r.length);let{seedLimit:n}=x_({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 w_(t){let e=Ld({...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=ZV({suppressDuplicateEntries:n,ignoreStageSpace:o,drawDefinition:r,drawEntries:u,drawType:d,entries:l});if(I.error)return I;let h=d===Hi?0:ut(t.seedsCount??0),S=qT({...t,qualifyingOnly:!m||s,appliedPolicies:i,drawDefinition:r,seedingProfile:a,participants:c,stage:et,seedsCount:h,placeByes:p,drawSize:m,entries:l});if(S.error&&!S.conflicts)return S;S.positioningReport?.length&&f.push({[et]:S.positioningReport});let T=S.structureId;return S.conflicts&&(g=S.conflicts),d===an&&t.roundsCount&&__({...t,drawDefinition:r,structureId:T}),{drawDefinition:r,positioningReports:f,conflicts:g,structureId:T}}function ZV(t){let{ignoreStageSpace:e,drawDefinition:r,drawEntries:n,drawType:o,entries:i}=t;for(let s of i){if(n&&s.entryStage&&s.entryStage!==et)continue;let a={...s,ignoreStageSpace:e??o===an,entryStage:s.entryStage??et,event:t.event,drawDefinition:r,drawType:o},c=cS(a);if(n&&c.error)return c}return{error:void 0}}var t1=()=>({matchUpType:void 0,drawName:void 0,drawId:void 0,structures:[],entries:[],links:[]});var L_=t1;function F_(t){let{drawId:e=Nt(),processCodes:r,matchUpType:n,drawType:o}=t??{},i=L_();return Object.assign(i,{processCodes:r,matchUpType:n,drawType:o,drawId:e})}function zd(t){let e=t.structureIds,{tournamentRecord:r,drawDefinition:n,matchUpFormat:o,structureId:i,matchUpId:s,event:a}=t,c=nt(t,[{[Le]:!0,[wm]:!0}]);if(c.error)return c;if(!Ar({matchUpFormat:o}))return{error:Xa};let u="setMatchUpFormat";if(s){let p=Gt({drawDefinition:n,matchUpId:s,event:a});if(p.error)return p;let m=p.matchUp;if(m?.matchUpType===Me)return{info:"Cannot set matchUpFormat when { matchUpType: TEAM }",error:or};m&&(m.matchUpFormat=o,gt({tournamentId:r?.tournamentId,eventId:a?.eventId,context:u,drawDefinition:n,matchUp:m}))}else if(Array.isArray(e)){if(a?.eventType===Me)return{error:Bn};for(let p of e){let m=at({drawDefinition:n,structureId:p});if(m.error)return m;m.structure&&(m.structure.matchUpFormat=o)}}else if(i){if(a?.eventType===Me)return{error:Bn};let p=at({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}),{...C}}function k_({tieFormat:t}){let e=mr({checkCollectionIds:!1,tieFormat:t});if(e.error)return e;for(let r of t.collectionDefinitions)r.collectionId||(r.collectionId=Nt());return{tieFormat:t}}function G_({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=k_({tieFormat:o});if(a.error)return a;e.tieFormat=a.tieFormat??o}else if(r){let a=zd({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 pN={};Qt(pN,{attachPolicies:()=>Ji,findPolicy:()=>ri,getAppliedPolicies:()=>yt,getPolicyDefinitions:()=>_o,mutate:()=>cN,query:()=>uN,removePolicy:()=>aN});var cN={};Qt(cN,{attachPolicies:()=>Ji,removePolicy:()=>aN});function aN(t){let e=nt(t,[{[YC]:!0,_anyOf:{[De]:!1,[Re]:!1,[Le]:!1,[Jo]:!1}}]);if(e.error)return e;let r,n=t.drawDefinition??t.event??((t.tournamentId||!t.tournamentRecords)&&t.tournamentRecord);if(n)return V_(t,n);if(t.tournamentRecords){let o=Object.keys(t.tournamentRecords);if(!o.length)return{error:j};for(let i of o){let s=t.tournamentRecords[i],a=V_(t,s);if(a.error)return a;r=!0}}else return{error:j};return r?{...C}:{error:Wc}}function V_(t,e){let r=yt(t).appliedPolicies??{};return r[t.policyType]?(delete r[t.policyType],Object.keys(r).length?At({element:e,extension:{name:su,value:r}}):ur({element:e,name:su}),{...C}):{error:Wc}}var uN={};Qt(uN,{findPolicy:()=>ri,getAppliedPolicies:()=>yt,getPolicyDefinitions:()=>_o});var mN={[xn]:{validSeedPositions:{ignore:!0},duplicateSeedNumbers:!0,drawSizeProgression:!0,seedingProfile:{drawTypes:{[Io]:{positioning:gi},[Un]:{positioning:gi}},positioning:kC},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}]}},jg=mN;function B_({appliedPolicies:t,policyDefinitions:e,drawDefinition:r,stack:n}){if(e&&typeof e!="object")return _({info:"policyDefinitions must be an object",result:{error:k},stack:n});let o={[iu]:t?.[iu]};return e?e1({policyDefinitions:e,appliedPolicies:t,policiesToAttach:o,drawDefinition:r}):o.avoidance&&Ji({drawDefinition:r,policyDefinitions:o}),!t?.[xn]&&!e?.[xn]&&(Ji({policyDefinitions:jg,drawDefinition:r}),t&&Object.assign(t,jg)),{error:void 0}}function e1({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&&(Ji({policyDefinitions:r,drawDefinition:n}),e&&Object.assign(e,r))}function H_(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??F_({processCodes:t.processCodes,drawId:t.drawId,drawType:a}),d=G_({tournamentRecord:e,drawDefinition:m,matchUpFormat:r,matchUpType:i,tieFormat:s,event:u});if(d.error)return _({result:d,stack:c});let l=B_({appliedPolicies:n,policyDefinitions:o,drawDefinition:m,stack:c});if(l.error)return l;let f=p?.structures?.find(h=>h.stage===et&&h.stageSequence===1)?.structureId,g=p?p.structures?.filter(h=>h.stage===ct):[],I=g?.length===1&&!g[0].matchUps?.length&&g[0].structureId;return{drawDefinition:m,structureId:f,existingDrawDefinition:p,existingQualifyingPlaceholderStructureId:I}}function W_(t){let e="generateOrGetExisting",r=[],n=[],o=H_(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&&b_({...t,...o})||w_({...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 j_(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:ko("structureProfiles"),result:{error:ot},stack:d});S=T.roundTarget||S;let y=T.structureProfiles?.sort(g)||[],D=1;for(let U of y){let{qualifyingRoundNumber:A,qualifyingPositions:E,seededParticipants:M,seedingScaleName:P,seedsCount:N=0,seedByRanking:R,placeByes:b,drawSize:v}=U,O=qT({...t,seedingProfile:U.seedingProfile??c,stageSequence:D,qualifyingRoundNumber:A,preparedStructureIds:h,qualifyingPositions:E,seededParticipants:M,stage:ct,seedingScaleName:P,appliedPolicies:i,drawDefinition:a,qualifyingOnly:s,seedByRanking:R,participants:u,roundTarget:S,seedsCount:N,placeByes:b,drawSize:v,entries:m});if(O.error)return O;O.structureId&&h.push(O.structureId),D+=1,O.conflicts?.length&&f.push(...O.conflicts),O.positioningReport?.length&&o.push({[ct]:O.positioningReport})}S+=1}}else if(p&&l){let g=In({structureName:Ye(ct),stage:ct}),{link:I}=_a({sourceStructureId:g.structureId,targetStructureId:p,sourceRoundNumber:0,linkType:Jn});a.structures||(a.structures=[]),a.structures.push(g),a.links||(a.links=[]),a.links.push(I)}return{qualifyingConflicts:f,error:void 0}}var vN={};Qt(vN,{addGoesTo:()=>Ki,allCompetitionMatchUps:()=>An,allDrawMatchUps:()=>Je,allEventMatchUps:()=>qn,allPlayoffPositionsFilled:()=>AS,allTournamentMatchUps:()=>fe,analyzeDraws:()=>Lu,analyzeMatchUp:()=>om,analyzeTournament:()=>ry,bulkUpdatePublishedEventIds:()=>oy,calculateWinCriteria:()=>Ms,categoryCanContain:()=>xu,checkMatchUpIsComplete:()=>gs,checkValidEntries:()=>xd,compareTieFormats:()=>$o,competitionScheduleMatchUps:()=>ju,courtGridRows:()=>nl,credits:()=>Y_,drawMatchUps:()=>yy,eventMatchUps:()=>al,filterMatchUps:()=>bi,filterParticipants:()=>Du,findDrawDefinition:()=>KS,findExtension:()=>mt,findVenue:()=>Wo,getAllDrawMatchUps:()=>re,getAllEventData:()=>iy,getAllStructureMatchUps:()=>Et,getAllowedDrawTypes:()=>Qd,getAllowedMatchUpFormats:()=>JT,getAppliedPolicies:()=>yt,getAssignedParticipantIds:()=>Oi,getAvailableMatchUpsCount:()=>Od,getAvailablePlayoffProfiles:()=>Ru,getCategoryAgeDetails:()=>ea,getCheckedInParticipantIds:()=>ps,getCompetitionDateRange:()=>Jd,getCompetitionMatchUps:()=>nm,getCompetitionParticipants:()=>$T,getCompetitionPenalties:()=>ZT,getCompetitionVenues:()=>tm,getCourtInfo:()=>id,getCourts:()=>Ay,getDrawData:()=>tl,getDrawDefinitionTimeItem:()=>Oh,getDrawParticipantRepresentativeIds:()=>qS,getDrawStructures:()=>ln,getDrawTypeCoercion:()=>Fu,getEligibleVoluntaryConsolationParticipants:()=>YS,getEntriesAndSeedsCount:()=>ol,getEvent:()=>Dy,getEventData:()=>el,getEventMatchUpFormatTiming:()=>dy,getEventProperties:()=>Ey,getEventPublishStatus:()=>jr,getEventStructures:()=>Ig,getEventTimeItem:()=>gu,getEvents:()=>Uy,getFlightProfile:()=>Wt,getHomeParticipantId:()=>sd,getLinkedTournamentIds:()=>cu,getMatchUpCompetitiveProfile:()=>Su,getMatchUpContextIds:()=>Iy,getMatchUpDailyLimits:()=>ul,getMatchUpDailyLimitsUpdate:()=>ly,getMatchUpDependencies:()=>rn,getMatchUpFormat:()=>hy,getMatchUpFormatTiming:()=>Tu,getMatchUpFormatTimingUpdate:()=>py,getMatchUpScheduleDetails:()=>ad,getMatchUpType:()=>pd,getMatchUpsMap:()=>Ee,getMatchUpsStats:()=>Sy,getMaxEntryPosition:()=>cy,getModifiedMatchUpFormatTiming:()=>il,getPairedParticipant:()=>gn,getParticipantEventDetails:()=>KT,getParticipantIdFinishingPositions:()=>$S,getParticipantMembership:()=>zT,getParticipantResults:()=>vu,getParticipantScaleItem:()=>Oc,getParticipantSchedules:()=>QT,getParticipantSignInStatus:()=>XT,getParticipantTimeItem:()=>_h,getParticipants:()=>$t,getPersonRequests:()=>xi,getPolicyDefinitions:()=>_o,getPositionAssignments:()=>qp,getPositionsPlayedOff:()=>Nc,getPredictiveAccuracy:()=>gy,getProfileRounds:()=>rl,getPublishState:()=>Ss,getRoundMatchUps:()=>je,getRounds:()=>Ty,getScaleValues:()=>ha,getScaledEntries:()=>ia,getScheduledRoundsDetails:()=>Wu,getSchedulingProfile:()=>Ko,getSchedulingProfileIssues:()=>ay,getSeedingThresholds:()=>mS,getSeedsCount:()=>ku,getStructureSeedAssignments:()=>en,getTeamLineUp:()=>ls,getTieFormat:()=>ny,getTimeItem:()=>Xr,getTournamentIds:()=>Ep,getTournamentInfo:()=>Ns,getTournamentPenalties:()=>Xd,getTournamentPersons:()=>ey,getTournamentPublishStatus:()=>Eu,getTournamentStructures:()=>yS,getTournamentTimeItem:()=>Xm,getValidGroupSizes:()=>wp,getVenueData:()=>hc,getVenuesAndCourts:()=>Do,isAdHoc:()=>pr,isCompletedStructure:()=>si,isValidForQualifying:()=>aT,isValidMatchUpFormat:()=>Ar,matchUpActions:()=>_d,participantScaleItem:()=>Uo,participantScheduledMatchUps:()=>fy,positionActions:()=>sT,publicFindCourt:()=>Zh,publicFindVenue:()=>Jh,tallyParticipantResults:()=>wa,tieFormatGenderValidityCheck:()=>Cd,tournamentMatchUps:()=>cl,validMatchUp:()=>tg,validMatchUps:()=>Lr,validateCollectionDefinition:()=>wu,validateLineUp:()=>Td});function Y_(){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.
|
|
7
7
|
|