tods-competition-factory 2.0.28 → 2.0.29
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 +3 -3
- package/dist/tods-competition-factory.development.cjs.js +8 -4
- 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 +5 -5
package/dist/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var Ow=Object.defineProperty;var Jt=(t,e)=>{for(var r in e)Ow(t,r,{get:e[r],enumerable:!0})};function Va(){return"2.0.28"}var $A={};Jt($A,{competitionGovernor:()=>CE,drawsGovernor:()=>ZD,entriesGovernor:()=>sN,eventGovernor:()=>TN,generationGovernor:()=>PN,matchUpFormatGovernor:()=>iA,matchUpGovernor:()=>jN,mocksGovernor:()=>$g,participantGovernor:()=>TM,policyGovernor:()=>OD,publishingGovernor:()=>NM,queryGovernor:()=>XD,reportGovernor:()=>MM,scheduleGovernor:()=>kM,scoreGovernor:()=>yg,tieFormatGovernor:()=>zM,tournamentGovernor:()=>oC,venueGovernor:()=>fC});var CE={};Jt(CE,{getLinkedTournamentIds:()=>qc,getTournamentIds:()=>np,linkTournaments:()=>UE,mutate:()=>NE,query:()=>ME,unlinkTournament:()=>DE,unlinkTournaments:()=>PE});var NE={};Jt(NE,{linkTournaments:()=>UE,unlinkTournament:()=>DE,unlinkTournaments:()=>PE});var QC={};Jt(QC,{addNotice:()=>Tt,callListener:()=>um,createInstanceState:()=>pE,cycleMutationStatus:()=>Bl,deepCopyEnabled:()=>Vl,deleteNotice:()=>NI,deleteNotices:()=>Ci,disableNotifications:()=>mE,enableNotifications:()=>kl,getDevContext:()=>yr,getMethods:()=>Hl,getNotices:()=>DI,getProvider:()=>MI,getTopics:()=>Cr,getTournamentId:()=>$i,getTournamentRecord:()=>Wl,getTournamentRecords:()=>Mo,globalLog:()=>fE,handleCaughtError:()=>Xu,removeTournamentRecord:()=>lE,setDeepCopy:()=>Vc,setDevContext:()=>kc,setGlobalLog:()=>$C,setGlobalMethods:()=>KC,setGlobalSubscriptions:()=>pL,setMethods:()=>zC,setStateMethods:()=>gE,setStateProvider:()=>cL,setSubscriptions:()=>mL,setTournamentId:()=>Qu,setTournamentRecord:()=>dE,setTournamentRecords:()=>pm,timeKeeper:()=>uL});function Mr(t){return typeof t=="function"}function $e(t){return typeof t=="string"}function Rt(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function CC(t,e){if(!Rt(t)||!Rt(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 sI(t,e){return Array.isArray(t)?Object.assign({},...(t??[]).filter(Rt).map(r=>r[e]&&{[r[e]]:r}).filter(Boolean)):{}}var RC=t=>e=>Object.keys(t).every(r=>e[r]===t[r]);function iI(t,e){if(t===void 0)return null;if(typeof t!="object"||t===null)return t;let r=Object.keys(t),n=o=>o===void 0?null:o;return Object.assign({},...r.map(o=>Array.isArray(t[o])?{[o]:e?t[o]:t[o].map(i=>iI(i))}:{[o]:e?n(t[o]):iI(t[o])}))}function ZA(t){return Array.isArray(t)?t.length+t.map(ZA).reduce((e,r)=>e+r,0):typeof t=="object"&&t!==null?Object.keys(t).length+Object.keys(t).map(e=>ZA(t[e])).reduce((e,r)=>e+r,0):0}function bC(t){if(t===null||typeof t!="object")return;let e=JSON.stringify(t),r=ZA(t),n=e.split("").reduce((o,i)=>o+i.charCodeAt(0),0);return[e.length,r,n].map(o=>o.toString(36)).join("")}var R={success:!0},_w="error",OC={SUCCESS:R,ERROR:_w};var aI={message:"Chronological error; time violation.",code:"ANACHRONISM"},ty={message:"Cannot remove main structure",code:"ERR_CANNOT_REMOVE_MAIN_STRUCTURE"},cI={message:"records must be an object with tournamentId keys",code:"ERR_INVALID_TOURNAMENTS"},Ft={message:"Missing tournamentRecords",code:"ERR_MISSING_TOURNAMENTS"},W={message:"Missing tournamentRecord",code:"ERR_MISSING_TOURNAMENT"},Ba={message:"Invalid tournamentRecord",code:"ERR_INVALID_TOURNAMENT"},ra={message:"Missing tournamentId",code:"ERR_MISSING_TOURNAMENT_ID"},na={message:"Invalid drawDefinition",code:"ERR_INVALID_DRAWDEF"},X={message:"Missing drawDefinition",code:"ERR_MISSING_DRAWDEF"},ey={message:"Existing drawDefinition(s)",code:"ERR_EXISTING_DRAWDEFS"},pr={message:"drawDefinition not found",code:"ERR_NOT_FOUND_DRAWDEF"},Pi={message:"Invalid structure",code:"ERR_INVALID_STRUCTURE"},dl={message:"Incomplete source structure",code:"ERR_INCOMPLETE_STRUCTURE"},ll={message:"Invalid drawPosition for seedAssignment",code:"ERR_INVALID_SEEDING_POSITION"},Ha={message:"drawPosition already assigned",code:"ERR_EXISTING_POSITION_ASSIGNMENT"},ry={message:"Schedule not cleared",code:"ERR_UNCHANGED_SCHEDULE_NOT_CLEARED"},ny={message:"drawPosition not cleared",code:"ERR_FAILURE_POSITION_NOT_CLEARED"},vw={message:"drawPosition not found",code:"ERR_NOT_FOUND_DRAW_POSITION"},fl={message:"Unrecognized drawType",code:"ERR_UNRECOGNIZED_DRAW_TYPE"},Wa={message:"Missing drawPositions",code:"ERR_MISSING_DRAW_POSITIONS"},ku={message:"drawPosition is active",code:"ERR_ACTIVE_DRAW_POSITION"},ys={message:"Invlid drawPosition",code:"ERR_INVALID_DRAW_POSITION"},Es={message:"Missing drawPosition",code:"ERR_MISSING_DRAW_POSITION"},nm={message:"Invalid drawType",code:"ERR_INVALID_DRAW_TYPE"},Vu={message:"Invalid drawSize",code:"ERR_INVALID_DRAW_SIZE"},uI={message:"Cannot set drawSize to be less than existing entries",code:"ERR_INVALID_DRAW_SIZE_MISMATCH"},ja={message:"Missing drawSize",code:"ERR_MISSING_DRAW_SIZE"},Wr={message:"Missing drawId",code:"ERR_MISSING_DRAW_ID"},oy={message:"drawId exists",code:"ERR_EXISTING_DRAW_ID"},iy={message:"participantId cannot be assigned to multiple seedNumbers",code:"INVALID_PARTICIPANT_SEEDING"},sy={message:"seedsCount greater than drawSize",code:"ERR_INVALID_SEED_COUNT"},ay={message:"Missing seedCountThresholds",code:"ERR_MISSING_SEED_COUNT_THRESHOLD"},cy={message:"Invalid action",code:"ERR_INVALID_ACTION"},pI={message:"Invalid assignment",code:"ERR_INVALID_ASSIGNMENT"},uy={message:"Missing seedAssignments",code:"ERR_MISSING_SEED_ASSIGNMENTS"},py={message:"Invalid seedNumber",code:"ERR_INVALID_SEED_NUMBER"},my={message:"Invalid seedPosition",code:"ERR_INVALID_SEED_POSITION"},gl={message:"Missing targetLink",code:"ERR_MISSING_LINK_TARGET"},dy={message:"Existing round",code:"ERR_EXISTING_ROUND"},xw={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"},Il={message:"Missing structures",code:"ERR_MISSING_STRUCTURES"},Do={message:"Missing structure",code:"ERR_MISSING_STRUCTURE"},ly={message:"drawDefinition contains unlinked structures",code:"ERR_MISSING_STRUCTURE_LINKS"},No={message:"Invalid eventType",code:"ERR_INVALID_EVENT_TYPE"};var Et={message:"Missing event / eventId",code:"ERR_MISSING_EVENT_ID"},mr={message:"Event not found",code:"ERR_NOT_FOUND_EVENT"},fy={message:"Event exists",code:"ERR_EXISTING_EVENT"},gy={message:"Missing entries",code:"ERR_MISSING_ENTRIES"},Iy={message:"Invalid entries",code:"ERR_INVALID_ENTRIES"},hl={message:"Missing assignments",code:"ERR_MISSING_ASSIGNMENTS"},mI={message:"Missing stage",code:"ERR_MISSING_STAGE"},Di={message:"Invalid stage",code:"ERR_INVALID_STAGE"},hy={message:"stageSequence limit",code:"ERR_LIMIT_STAGE_SEQUENCE"},Sy={message:"Missing positionAssignments",code:"ERR_MISSING_POSITION_ASSIGNMENTS"},Ty={message:"Cannot Assign BYE status if no assignment: { bye: true }",code:"ERR_UNCHANGED_CANNOT_ASSIGN_BYE"},dI={message:"Unrecognized matchUpStatus",code:"ERR_UNRECOGNIZED_MATCHUP_STATUS"},Ya={message:"Unrecognized matchUpFormat",code:"ERR_UNRECOGNIZED_MATCHUP_FORMAT"},Sl={message:"Incompatible matchUpStatus",code:"ERR_INCOMPATIBLE_MATCHUP_STATUS"},oa={message:"Invalid matchUpStatus",code:"ERR_INVALID_MATCHUP_STATUS"},ni={message:"Invalid tieFormat",code:"ERR_INVALID_TIE_FORMAT"},Tl={message:"Invalid matchUpFormat",code:"ERR_INVALID_MATCHUP_FORMAT"},Al={message:"Missing matchUpFormat",code:"ERR_MISSING_MATCHUP_FORMAT"},Ay={message:"Missing collectionDefinition",code:"ERR_MISSING_COLLECTION_DEFINITION"},qa={message:"Missing tieFormat",code:"ERR_MISSING_TIE_FORMAT"},ke={message:"Missing matchUpId",code:"ERR_MISSING_MATCHUP_ID"},ia={message:"Missing matchUpIds",code:"ERR_MISSING_MATCHUP_IDS"},Oe={message:"matchUp not found",code:"ERR_NOT_FOUND_MATCHUP"},Sn={message:"Missing matchUps",code:"ERR_MISSING_MATCHUPS"},sr={message:"Missing matchUp",code:"ERR_MISSING_MATCHUP"},Je={message:"Invalid matchUp",code:"ERR_INVALID_MATCHUP"},lI={message:"Missing policyType",code:"ERR_MISSING_POLICY_TYPE"},Bu={message:"Missing policyDefinitions",code:"ERR_MISSING_POLICY_DEFINITIONS"},ww={message:"Missing seeding policy",code:"ERR_MISSING_POLICY_SEEDING"},yy={message:"Missing avoidance policy",code:"ERR_MISSING_POLICY_AVOIDANCE"},fI={message:"Missing policy attributes",code:"ERR_MISSING_POLICY_ATTRIBUTES"},Ey={message:"Invalid policyDefinitions",code:"ERR_INVALID_POLICY_DEFINITIONS"},gI={message:"existing policyType",code:"ERR_EXISTING_POLICY_TYPE"},Lw={message:"Policy not attached",code:"ERR_FAILURE_POLICY_NOT_ATTACHED"},Lc={message:"Policy not found",code:"ERR_NOT_FOUND_POLICY"},Fw={message:"Missing scoring policy / matchUpFormats",code:"ERR_MISSING_POLICY_SCORING_MATCHUP_FORMATS"},yl={message:"Invalid sideNumber",code:"ERR_INVALID_SIDE_NUMBER"},Gw={message:"Invalid setNumber",code:"ERR_INVALID_SET_NUMBER"},El={message:"Missing setObject",code:"ERR_MISSING_SET_ATTRIBUTE"},kw={message:"Missing setNumber",code:"ERR_MISSING_SET_NUMBER"},Vw={message:"Missing sideNumber",code:"ERR_MISSING_SIDE_NUMBER"},Ni={message:"Missing courtId",code:"ERR_MISSING_COURT_ID"},et={message:"Missing value",code:"ERR_MISSING_VALUE"},Uy={message:"Missing date",code:"ERR_MISSING_DATE"},Py={message:"No valid dates",code:"ERR_NO_VALID_DATES"},om={message:"Invalid bookings",code:"ERR_INVALID_BOOKINGS"},Ul={message:"Invalid dateAvailability",code:"ERR_INVALID_DATE_AVAILABILITY"},Dy={message:"Missing dateAvailability",code:"ERR_MISSING_DATE_AVAILABILITY"},ar={message:"Invalid Date",code:"ERR_INVALID_DATE"},mo={message:"Invalid time",code:"ERR_INVALID_TIME"},Ny={message:"Invalid tournament dates",code:"ERR_INVALID_DATES_TOURNAMENT"};var II={message:"Invalid game scores",code:"ERR_INVALID_SCORES_GAME"},My={message:"Invalid score",code:"ERR_INVALID_SCORE"},im={message:"Invalid winningSide",code:"ERR_INVALID_WINNING_SIDE"};var _C={message:"No participants generated",code:"ERR_NO_PARTICIPANTS_GENERATED"},Pl={message:"Cannot modify tieFormat",code:"ERR_UNCHANGED_CANNOT_MODIFY_TIEFORMAT"},Cy={message:"Cannot modify participantType",code:"ERR_UNCHANGED_CANNOT_MODIFY_PARTICIPANT_TYPE"},Hu={message:"Cannot remove participants",code:"ERR_UNCHANGED_CANNOT_REMOVE_PARTICIPANTS"},Dl={message:"Cannot change winningSide",code:"ERR_UNCHANGED_CANNOT_CHANGE_WINNING_SIDE"},Us={message:"Invalid participant",code:"ERR_INVALID_PARTICIPANT"},pn={message:"Invalid participantId",code:"ERR_INVALID_PARTICIPANT_ID"},zr={message:"Invalid participantIds",code:"ERR_INVALID_PARTICIPANT_IDS"},Ry={message:"Invalid participantRole",code:"ERR_INVALID_PARTICIPANT_ROLE"},nn={message:"Invalid participantType",code:"ERR_INVALID_PARTICIPANT_TYPE"},by={message:"Missing participantRole",code:"ERR_MISSING_PARTICIPANT_ROLE"},Mi={message:"Missing participant",code:"ERR_MISSING_PARTICIPANT"},$a={message:"Missing participants",code:"ERR_MISSING_PARTICIPANTS"},oe={message:"Missing participantId",code:"ERR_MISSING_PARTICIPANT_ID"},Zt={message:"Participant Not Found",code:"ERR_NOT_FOUND_PARTICIPANT"},Oy={message:"participantId exists",code:"ERR_EXISTING_PARTICIPANT_ID"},Bw={message:"participant pair exists",code:"ERR_EXISTING_PARTICIPANT_PAIR"},_y={message:"No participant removed",code:"ERR_UNCHANGED_NO_PARTICIPANT_REMOVED"},lo={message:"Missing participantIds",code:"ERR_MISSING_PARTICIPANT_IDS"},vy={message:"Missing participantsCount",code:"ERR_MISSING_PARTICIPANT_COUNT"},xy={message:"Participant not checked in",code:"ERR_UNCHANGED_PARTICIPANT_NOT_CHECKED_IN"},wy={message:"Missing person details",code:"ERR_MISSING_PERSON_DETAILS"},Ps={message:"Existing participant drawPosition assignment",code:"ERR_EXISTING_PARTICIPANT_DRAW_POSITION_ASSIGNMENT"},Wu={message:"Existing participant",code:"ERR_EXISTING_PARTICIPANT"},Nl={message:"participantsCount exceeds drawSize",code:"ERR_INVALID_PARTICIPANT_COUNT"},Ml={message:"Invalid entry status",code:"ERR_INVALID_ENTRY_STATUS"},hI={message:"Participant Entry Not Found",code:"ERR_NOT_FOUND_PARTICIPANT_ENTRY"},vC={message:"Participant not entered in stage",code:"ERR_UNCHANGED_PARTICIPANT_NOT_ENTERED"},xC={message:"Participant not found in stageSequence",code:"ERR_NOT_FOUND_PARTICIPANT_IN_STAGE"},Ly={message:"entryStatus not allowed in stage",code:"ERR_INVALID_ENTRY_STATUS_IN_STAGE"},Fy={message:"entryStatus not allowed for event",code:"ERR_INVALID_ENTRY_STATUS_IN_EVENT"},SI={message:"No stage space available for entryStatus",code:"ERR_UNCHANGED_NO_AVAILABLE_STAGE_SPACE"},Gy={message:"Insufficient drawPositions to accommodate qualifiers",code:"ERR_UNCHANGED_NO_DRAW_POSITIONS_FOR_QUALIFIERS"},Cl={message:"Insufficient drawPositions to accommodate entries",code:"ERR_INSUFFICIENT_DRAW_POSITIONS"},ky={message:"Missing penaltyType",code:"ERR_MISSING_PENALTY_TYPE"},Rl={message:"Missing penaltyId",code:"ERR_MISSING_PENALTY_ID"},Fc={message:"Penalty not found",code:"ERR_NOT_FOUND_PENALTY"},Vy={message:"Missing courtsCount/courtNames",code:"ERR_MISSING_COURTS_INFO"},Ka={message:"Court not found",code:"ERR_NOT_FOUND_COURT"},By={message:"Court exists",code:"ERR_EXISTING_COURT"},Hy={message:"Venue exists",code:"ERR_EXISTING_VENUE"},Ds={message:"Venue not found",code:"ERR_NOT_FOUND_VENUE"},Bo={message:"Missing venueId",code:"ERR_MISSING_VENUE_ID"},Wy={message:"Invalid endTime",code:"ERR_INVALID_END_TIME"},TI={message:"Existing endTime",code:"ERR_EXISTING_END_TIME"},jy={message:"Invalid stopTime",code:"ERR_INVALID_STOP_TIME"},Yy={message:"Invalid startTime",code:"ERR_INVALID_START_TIME"},wC={message:"Invalid resumeTime",code:"ERR_INVALID_RESUME_TIME"},bl={message:"Invalid timeItem",code:"ERR_INVALID_TIME_ITEMS"},qy={message:"Missing async state provider",code:"ERR_MISSING_ASYNC_STATE_PROVIDER"},Ol={message:"Missing timeItem",code:"ERR_MISSING_TIME_ITEM"},_l={message:"Missing timeItems",code:"ERR_MISSING_TIME_ITEMS"},Gc={message:"Missing context",code:"ERR_MISSING_CONTEXT"},$y={message:"Missing schedule",code:"ERR_MISSING_SCHEDULE"},ju={message:"Invalid scaleItem",code:"ERR_INVALID_SCALE_ITEM"},Ky={message:"Modifications failed",code:"ERR_FAILURE_MODIFICATIONS"},Ns={message:"No modifications applied",code:"ERR_UNCHANGED_NO_MODIFICATIONS_APPLIED"},zy={message:"Unable to assign court",code:"ERR_UNCHANGED_COURT_NOT_ASSIGNED"},Yu={message:"No Candidates",code:"ERR_UNCHANGED_NO_CANDIDATES"},Qy={message:"Invalid configuration",code:"ERR_INVALID_CONFIG"},Xy={message:"Invalid collectionDefinition",code:"ERR_INVALID_COLLECTION_DEFINITION"},Xn={message:"Invalid object",code:"ERR_INVALID_OBJECT"},vl={message:"Invalid gender",code:"ERR_INVALID_GENDER"},sm={message:"Invalid category",code:"ERR_INVALID_CATEGORY"},G={message:"Invalid values",code:"ERR_INVALID_VALUES"},Jy={message:"Duplicate value",code:"ERR_DUPLICATE_VALUE"},xl={message:"Team not found",code:"ERR_NOT_FOUND_TEAM"},Zy={message:"No valid actions",code:"ERR_NO_VALID_ACTIONS"},qu={message:"No valid attributes",code:"ERR_NO_VALID_ATTRIBUTES"},wl={message:"Value unchanged",code:"ABORT_UNCHANGED"},Ke={message:"Not found",code:"ERR_NOT_FOUND"},$u={message:"Not implemented",code:"ERR_NOT_IMPLEMENTED"},tE={message:"Existing flight",code:"ERR_EXISTING_FLIGHT"},Ll={message:"Existing flight profile",code:"ERR_EXISTING_FLIGHT_PROFILE"},eE={message:"Existing outcome",code:"ERR_EXISTING_OUTCOME"},rE={message:"Existing matchUpId",code:"ERR_EXISTING_MATCHUP_ID"},AI={message:"Existing stage",code:"ERR_EXISTING_STAGE"},Fl={message:"Existing structure",code:"ERR_EXISTING_STRUCTURE"},za={message:"Method not found",code:"ERR_NOT_FOUND_METHOD"},nE={message:"Scheduled matchUps",code:"ERR_SCHEDULED_MATCHUPS"},Ku={message:"Scores present",code:"ERR_SCORES_PRESENT"},LC={ANACHRONISM:aI,CANNOT_CHANGE_WINNING_SIDE:Dl,CANNOT_MODIFY_TIEFORMAT:Pl,CANNOT_MODIFY_PARTICIPANT_TYPE:Cy,CANNOT_REMOVE_MAIN_STRUCTURE:ty,CANNOT_REMOVE_PARTICIPANTS:Hu,COURT_EXISTS:By,COURT_NOT_FOUND:Ka,DRAW_DEFINITION_NOT_FOUND:pr,DRAW_ID_EXISTS:oy,DRAW_POSITION_ACTIVE:ku,DRAW_POSITION_ASSIGNED:Ha,DRAW_POSITION_NOT_CLEARED:ny,DRAW_POSITION_NOT_FOUND:vw,DRAW_SIZE_MISMATCH:uI,DUPLICATE_VALUE:Jy,ENTRY_STATUS_NOT_ALLOWED_FOR_EVENT:Fy,ENTRY_STATUS_NOT_ALLOWED_IN_STAGE:Ly,EVENT_EXISTS:fy,EVENT_NOT_FOUND:mr,EXISTING_DRAW_DEFINITIONS:ey,EXISTING_END_TIME:TI,EXISTING_FLIGHT:tE,EXISTING_MATCHUP_ID:rE,EXISTING_OUTCOME:eE,EXISTING_PARTICIPANT_DRAW_POSITION_ASSIGNMENT:Ps,EXISTING_PARTICIPANT:Wu,EXISTING_POLICY_TYPE:gI,EXISTING_PROFILE:Ll,EXISTING_ROUND:dy,EXISTING_STAGE:AI,EXISTING_STRUCTURE:Fl,INCOMPATIBLE_MATCHUP_STATUS:Sl,INCOMPLETE_SOURCE_STRUCTURE:dl,INSUFFICIENT_DRAW_POSITIONS:Cl,INVALID_ACTION:cy,INVALID_ASSIGNMENT:pI,INVALID_BOOKINGS:om,INVALID_CATEGORY:sm,INVALID_COLLECTION_DEFINITION:Xy,INVALID_CONFIGURATION:Qy,INVALID_DATE_AVAILABILITY:Ul,INVALID_DATE:ar,INVALID_DRAW_DEFINITION:na,INVALID_DRAW_POSITION_FOR_SEEDING:ll,INVALID_DRAW_POSITION:ys,INVALID_DRAW_SIZE:Vu,INVALID_END_TIME:Wy,INVALID_ENTRIES:Iy,INVALID_EVENT_TYPE:No,INVALID_GAME_SCORES:II,INVALID_GENDER:vl,INVALID_MATCHUP_FORMAT:Tl,INVALID_MATCHUP_STATUS:oa,INVALID_MATCHUP_STATUS_BYE:Ty,INVALID_MATCHUP:Je,INVALID_OBJECT:Xn,INVALID_PARTICIPANT_ID:pn,INVALID_PARTICIPANT_IDS:zr,INVALID_PARTICIPANT_ROLE:Ry,INVALID_PARTICIPANT_SEEDING:iy,INVALID_PARTICIPANT_TYPE:nn,INVALID_PARTICIPANT:Us,INVALID_POLICY_DEFINITION:Ey,INVALID_RECORDS:cI,INVALID_SCALE_ITEM:ju,INVALID_SEED_NUMBER:py,INVALID_SEED_POSITION:my,INVALID_SET_NUMBER:Gw,INVALID_SIDE_NUMBER:yl,INVALID_SCORE:My,INVALID_STAGE:Di,INVALID_START_TIME:Yy,INVALID_STRUCTURE:Pi,INVALID_STOP_TIME:jy,INVALID_TIE_FORMAT:ni,INVALID_TIME:mo,INVALID_TIME_ITEM:bl,INVALID_TOURNAMENT_DATES:Ny,INVALID_TOURNAMENT_RECORD:Ba,INVALID_VALUES:G,INVALID_WINNING_SIDE:im,MATCHUP_NOT_FOUND:Oe,METHOD_NOT_FOUND:za,MISSING_ASSIGNMENTS:hl,MISSING_ASYNC_STATE_PROVIDER:qy,MISSING_AVOIDANCE_POLICY:yy,MISSING_COLLECTION_DEFINITION:Ay,MISSING_COURT_ID:Ni,MISSING_COURTS_INFO:Vy,MISSING_DATE_AVAILABILITY:Dy,MISSING_DATE:Uy,MISSING_DRAW_DEFINITION:X,MISSING_DRAW_ID:Wr,MISSING_DRAW_POSITION:Es,MISSING_DRAW_POSITIONS:Wa,MISSING_DRAW_SIZE:ja,MISSING_ENTRIES:gy,MISSING_EVENT:Et,MISSING_MATCHUP_FORMAT:Al,MISSING_MATCHUP_ID:ke,MISSING_MATCHUP_IDS:ia,MISSING_MATCHUP:sr,MISSING_MATCHUPS:Sn,MISSING_PARTICIPANT_COUNT:vy,MISSING_PARTICIPANT_ID:oe,MISSING_PARTICIPANT_IDS:lo,MISSING_PARTICIPANT_ROLE:by,MISSING_PARTICIPANT:Mi,MISSING_PARTICIPANTS:$a,MISSING_PENALTY_ID:Rl,MISSING_PENALTY_TYPE:ky,MISSING_PERSON_DETAILS:wy,MISSING_POLICY_ATTRIBUTES:fI,MISSING_POLICY_DEFINITION:Bu,MISSING_POLICY_TYPE:lI,MISSING_POSITION_ASSIGNMENTS:Sy,MISSING_ROUND_NUMBER:xw,MISSING_SCHEDULE:$y,MISSING_SCORING_POLICY:Fw,MISSING_SEED_ASSIGNMENTS:uy,MISSING_SEEDCOUNT_THRESHOLDS:ay,MISSING_SEEDING_POLICY:ww,MISSING_SET_NUMBER:kw,MISSING_SET_OBJECT:El,MISSING_SIDE_NUMBER:Vw,MISSING_STAGE:mI,MISSING_STRUCTURE_ID:hr,MISSING_STRUCTURE:Do,MISSING_STRUCTURES:Il,MISSING_TARGET_LINK:gl,MISSING_TIE_FORMAT:qa,MISSING_TIME_ITEM:Ol,MISSING_TIME_ITEMS:_l,MISSING_TOURNAMENT_ID:ra,MISSING_TOURNAMENT_RECORD:W,MISSING_TOURNAMENT_RECORDS:Ft,MISSING_VALUE:et,MISSING_VENUE_ID:Bo,MODIFICATIONS_FAILED:Ky,NO_CANDIDATES:Yu,NO_DRAW_POSITIONS_AVAILABLE_FOR_QUALIFIERS:Gy,NO_MODIFICATIONS_APPLIED:Ns,NO_STAGE_SPACE_AVAILABLE_FOR_ENTRY_STATUS:SI,NO_PARTICIPANT_REMOVED:_y,NO_VALID_ACTIONS:Zy,NO_VALID_ATTRIBUTES:qu,NO_VALID_DATES:Py,NOT_FOUND:Ke,NOT_IMPLEMENTED:$u,PARTICIPANT_COUNT_EXCEEDS_DRAW_SIZE:Nl,PARTICIPANT_ID_EXISTS:Oy,PARTICIPANT_NOT_CHECKED_IN:xy,PARTICIPANT_NOT_FOUND:Zt,PARTICIPANT_PAIR_EXISTS:Bw,PENALTY_NOT_FOUND:Fc,POLICY_NOT_ATTACHED:Lw,POLICY_NOT_FOUND:Lc,SCHEDULE_NOT_CLEARED:ry,SCHEDULED_MATCHUPS:nE,SCORES_PRESENT:Ku,SEEDSCOUNT_GREATER_THAN_DRAW_SIZE:sy,STAGE_SEQUENCE_LIMIT:hy,STRUCTURE_NOT_FOUND:Lt,TEAM_NOT_FOUND:xl,UNABLE_TO_ASSIGN_COURT:zy,UNLINKED_STRUCTURES:ly,UNRECOGNIZED_DRAW_TYPE:fl,UNRECOGNIZED_MATCHUP_FORMAT:Ya,UNRECOGNIZED_MATCHUP_STATUS:dI,VALUE_UNCHANGED:wl,VENUE_EXISTS:Hy};var Ze={disableNotifications:!1,tournamentId:void 0,tournamentRecords:{},subscriptions:{},modified:!1,methods:{},notices:[]},oE={addNotice:Zw,callListener:oL,cycleMutationStatus:Jw,deleteNotice:rL,deleteNotices:eL,disableNotifications:Hw,enableNotifications:Ww,getMethods:zu,getNotices:tL,getTopics:nL,getTournamentId:FC,getTournamentRecord:jw,getTournamentRecords:Yw,removeTournamentRecord:zw,setMethods:Xw,setSubscriptions:Qw,setTournamentId:$w,setTournamentRecord:qw,setTournamentRecords:Kw,handleCaughtError:iL};function Hw(){Ze.disableNotifications=!0}function Ww(){Ze.disableNotifications=!1}function FC(){return Ze.tournamentId}function jw(t){return Ze.tournamentRecords[t]}function Yw(){return Ze.tournamentRecords}function qw(t){let e=t?.tournamentId;return e?(Ze.tournamentRecords[e]=t,{success:!0}):{error:Ba}}function $w(t){return t?Ze.tournamentRecords[t]?(Ze.tournamentId=t,{success:!0}):{error:W}:(Ze.tournamentId=void 0,{success:!0})}function Kw(t){Ze.tournamentRecords=t;let e=Object.keys(t);e.length===1?Ze.tournamentId=e[0]:e.length||(Ze.tournamentId=void 0)}function zw(t){if(typeof t!="string")return{error:G};if(!Ze.tournamentRecords[t])return{error:Ke};delete Ze.tournamentRecords[t];let e=Object.keys(Ze.tournamentRecords);return e.length===1?Ze.tournamentId=e[0]:e.length||(Ze.tournamentId=void 0),{success:!0}}function Qw(t){return typeof t.subscriptions!="object"?{error:G}:(Object.keys(t.subscriptions).forEach(e=>{Ze.subscriptions[e]=t.subscriptions[e]}),{...R})}function Xw(t){return typeof t!="object"?{error:G}:(Object.keys(t).forEach(e=>{typeof t[e]=="function"&&(Ze.methods[e]=t[e])}),{...R})}function Jw(){let t=Ze.modified;return Ze.modified=!1,t}function Zw({topic:t,payload:e,key:r},n){if(!(typeof t!="string"||typeof e!="object")&&(Ze.disableNotifications||(Ze.modified=!0),!(Ze.disableNotifications||!Ze.subscriptions[t]&&!n)))return r&&(Ze.notices=Ze.notices.filter(o=>!(o.topic===t&&o.key===r))),Ze.notices.push({topic:t,payload:e,key:r}),{...R}}function zu(){return Ze.methods??{}}function tL({topic:t}){return Ze.notices.filter(e=>e.topic===t).map(e=>e.payload)}function eL(){Ze.notices=[]}function rL({topic:t,key:e}){Ze.notices=Ze.notices.filter(r=>(!t||r.topic===t)&&r.key!==e)}function nL(){return{topics:Object.keys(Ze.subscriptions)}}function oL({topic:t,notices:e},r){let n=Ze.subscriptions[t];n&&typeof n=="function"&&n(e);let o=r?.[t];o&&typeof o=="function"&&o(e)}function iL({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:FC(),params:JSON.stringify(r),engine:t,methodName:e,error:o}),{error:o}}function se(t,e){return(t??0)-(e??0)}function ct(t){return typeof t=="number"?parseInt(t.toString()):typeof t=="string"?parseInt(t):0}function Tn(t){return isNaN(t)?!1:t&&(t&t-1)===0}function iE(t){if(!t.length)return;let e=[...t].sort(se),r=Math.floor(e.length/2);return e.length%2?e[r]:(e[r-1]+e[r])/2}function GC(t){if(!Tn(t))return!1;let e=t,r=1;for(;e!==2;)r+=1,e=e/2;return r}function am(t){return isNaN(t)?0:t%2&&t+1||t}function cm(t){return Math.pow(2,Math.round(Math.log(t)/Math.log(2)))}function te(t){return!isNaN(parseFloat(t))}function yI(t){let e=ct(t);if(!isNaN(e))return e===0?!1:(e&-e)===1}function qi(t){if(isNaN(t))return!1;for(;!Tn(t);)t++;return t}function Jn(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 kC(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 sL(t,e){e||(e=1);let r=1/e;return Math.round(t*r)/r}function sE(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=sE(t,e,r):(a=Math.pow(a,r),a*=e-t,a+=t),n&&(a=sL(a,n)),parseFloat(a.toFixed(o))}function pt(t){return Array.isArray(t)?t?.filter((e,r,n)=>n.lastIndexOf(e)===r):[]}function VC(t){return Array.isArray(t)?t?.map(e=>e===null?void 0:e):t}function cr(t){return Array.isArray(t)?t.map(e=>[Math.random(),e]).sort((e,r)=>e[0]-r[0]).map(e=>e[1]):[]}function Qa(t){return ft(t)?t:1/0}function dr(t){return Array.isArray(t)?t.reduce((e,r)=>(e[r]||(e[r]=0),e[r]++,e),{}):{}}function BC(t){return aE(dr(t))}function aE(t){return Object.keys(t).reduce((e,r)=>{let n=t[r];return e[n]?e[n].push(r):e[n]=[r],e},{})}function aL(t,e,r){return r.indexOf(t)===e}function EI(t){return t.filter(aL)}function xr(t){return Array.isArray(t)&&t.length?t.splice(Math.floor(Math.random()*t.length),1)[0]:void 0}function on(t){let e=Math.floor(Math.random()*t.length);return t[e]}function Z(t,e){return Array.from({length:e-t},(r,n)=>n+t)}function Zn(t,e){return e.reduce((r,n,o)=>(n===t&&r.push(o),r),[])}function jt(t,e){return!Array.isArray(t)||!Array.isArray(e)?[]:t.filter(r=>e.indexOf(r)!==-1).filter((r,n,o)=>o.indexOf(r)===n)}function cE(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 HC(t,e){return Array.isArray(e)&&e.reduce((r,n)=>(r[n]=1+r[n]||1,r),{})[t]||0}function WC(t,e,r,n){return Array.isArray(t)?[].concat(...t.slice(0,e),...t.slice(e,e+r).sort(n),...t.slice(e+r,t.length)):[]}function Te(t,e){return Array.isArray(t)?t.reduce((r,n,o)=>{let i=Math.floor(o/e);return r[i]=[].concat(r[i]||[],n),r},[]):[]}function uE(t,[e,...r]){return t.length?[t.slice(0,e),...uE(t.slice(e),[...r,e])]:[]}function jC(t){return t.reduce((e,r)=>{let n=e[e.length-1];return(!n||n[n.length-1]!==r-1)&&e.push([]),e[e.length-1].push(r),e},[])}function UI(t){return Array.isArray(t)?t.reduce((e,r)=>!isNaN(parseInt(r))&&e,!0):!1}function PI(t){return Array.isArray(t)?t.reduce((e,r)=>isNaN(parseInt(r))&&e,!0):!1}function Gl(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 YC(t,e=1){if(!Array.isArray(t)||!t.every(ft))return[];let r=Math.min(...t,e),n=Math.max(...t);return Z(r,n+1).filter(o=>!t.includes(o))}var De={timers:{default:{elapsedTime:0}},globalSubscriptions:{},deepCopyAttributes:{stringify:[],ignore:[],toJSON:[]},globalMethods:[],deepCopy:!0},jr=oE,qC=["addNotice","callListener","cycleMutationStatus","deleteNotice","deleteNotices","disableNotifications","enableNotifications","getMethods","getNotices","getTopics","getTournamentId","getTournamentRecord","getTournamentRecords","removeTournamentRecord","setSubscriptions","setTournamentId","setTournamentRecord","setTournamentRecords"];function cL(t){if(typeof t!="object")throw new Error("Global state provider can not be undefined or null");if(jt(Object.keys(t),qC).length!==qC.length)throw new Error("Global state provider is missing required methods");return jr=t,{success:!0}}function pE(){if(jr.createInstanceState){try{jr.createInstanceState()}catch(t){return{error:t}}return{success:!0}}else return{error:qy}}function yr(t){return!t||typeof t!="object"?De.devContext??!1:typeof De.devContext!="object"?!1:Object.keys(t).every(e=>De.devContext?.[e]===t[e])&&De.devContext}function uL(t="reset",e="default"){let r=Date.now();if(t==="report"){if(e==="allTimers")return Object.keys(De.timers).filter(o=>o!=="default"||De.timers[o].startTime).map(o=>{let i=De.timers[o],s=i.state==="stopped"?0:(r-(i?.startTime??0))/1e3,a=i.elapsedTime+s;return{state:De.timers[o].state,elapsedTime:a.toFixed(2),timer:o}});{let n=De.timers[e].state==="stopped"?0:(r-(De.timers[e]?.startTime??0))/1e3,o=De.timers[e].elapsedTime+n;return{state:De.timers[e].state,elapsedTime:o.toFixed(2),timer:e}}}if(!De.timers[e]||t==="reset"){if(e==="allTimers")return De.timers={default:{elapsedTime:0}},!0;De.timers[e]={startTime:r,state:"active",elapsedTime:0}}return De.timers[e].elapsedTime||(De.timers[e].elapsedTime=0),t==="stop"&&De.timers[e].state!=="stopped"&&(De.timers[e].state="stopped")&&(De.timers[e].elapsedTime+=(r-(De.timers[e]?.startTime??0))/1e3),t==="start"&&(De.timers[e].startTime=r)&&(De.timers[e].state="active"),De.timers[e]}function $C(t){Mr(t)?De.globalLog=t:delete De.globalLog}function kc(t){De.devContext=t}function mE(){jr.disableNotifications()}function kl(){jr.enableNotifications()}function Vc(t,e){typeof t=="boolean"&&(De.deepCopy=t),typeof e=="object"&&(Array.isArray(e.ignore)&&(De.deepCopyAttributes.ignore=e.ignore),Array.isArray(e.toJSON)&&(De.deepCopyAttributes.toJSON=e.toJSON),Array.isArray(e.stringify)&&(De.deepCopyAttributes.stringify=e.stringify),e.threshold&&(De.deepCopyAttributes.threshold=e.threshold))}function Vl(){return{enabled:De.deepCopy,...De.deepCopyAttributes}}function pL(t){return t?.subscriptions?(Object.keys(t.subscriptions).forEach(e=>{De.globalSubscriptions[e]=t.subscriptions[e]}),{...R}):{error:et,info:"missing subscriptions"}}function mL(t){return t?.subscriptions?jr.setSubscriptions({subscriptions:t.subscriptions}):{error:et,info:"missing subscriptions"}}function KC(t){return t?typeof t!="object"?{error:G}:(Object.keys(t).forEach(e=>{Mr(t[e])&&(De.globalMethods[e]=t[e])}),{...R}):{error:et,info:"missing method declarations"}}function zC(t){return t?typeof t!="object"?{error:G}:jr.setMethods(t):{error:et,info:"missing method declarations"}}function Bl(){return jr.cycleMutationStatus()}function Tt(t){if(typeof t?.topic!="string")return;let e=De.globalSubscriptions[t.topic];return jr.addNotice(t,e)}function Hl(){return{...De.globalMethods,...jr.getMethods()}}function DI(t){return jr.getNotices(t)}function NI({key:t,topic:e}){return jr.deleteNotice({key:t,topic:e})}function Ci(){return jr.deleteNotices()}function Cr(){return jr.getTopics()}async function um(t){return jr.callListener(t,De.globalSubscriptions)}function $i(){return jr.getTournamentId()}function Wl(t){return jr.getTournamentRecord(t)}function Mo(){return jr.getTournamentRecords()}function dE(t){return jr.setTournamentRecord(t)}function pm(t){return jr.setTournamentRecords(t)}function Qu(t){return jr.setTournamentId(t)}function lE(t){return jr.removeTournamentRecord(t)}function MI(){return jr}function Xu({engineName:t,methodName:e,params:r,err:n}){return(Mr(jr.handleCaughtError)&&jr.handleCaughtError||oE.handleCaughtError)({engineName:t,methodName:e,params:r,err:n})}function fE(t,e){if(De.globalLog)try{De.globalLog({log:t,engine:e})}catch(r){console.log("globalLog error",r),console.log(e,t),$C()}else console.log(e,t)}function gE(t,e,r,n){if(!Rt(t))return{error:G};te||(r=1);let o=Array.isArray(e)?e:[],i={},s=(a,c=0)=>{Object.keys(a).forEach(u=>{Mr(a[u])?i[u]=a[u]:Rt(a[u])&&(e===!0||o?.includes(u))&&(r===void 0||c<r)&&s(a[u],c+1)})};return s(t),n?KC(i):zC(i),{methods:i}}function dL(t,e,r){return Object.keys(t).filter(n=>!e.includes(t[n])&&(!r||(Array.isArray(t[n])?t[n].length:!0)))}function rt(t,e,r,n){if(typeof t!="object"||t===null)return t;Vl()?.enabled||(n=!0);let i=["",void 0,null];e&&i.push(!1);let s=dL(t,i,r);return Object.assign({},...s.map(a=>Array.isArray(t[a])?{[a]:n?t[a]:t[a].map(c=>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,{...R}),e??{success:!0}}var ye="tournamentRecords",jl="policyDefinitions",An="tournamentRecord",Yr="drawDefinition",mm="matchUpFormat",Bn="participantId",CI="scheduleDates",XC="tournamentId",JC="scheduleDate",dm="structureId",Yl="participant",Xa="matchUpIds",ZC="policyType",IE="structures",Co="matchUpId",lm="inContext",ql="structure",Ju="courtIds",tR="personId",Zu="venueIds",hE="matchUps",RI="courtId",bI="eventId",fo="matchUp",OI="drawId",Ms="error",Cs="event",sa="param",eR="uuids",rR="averageMatchUpMinutes",nR="recoveryMinutes",oR="periodLength",iR="number";var Ri="object",Er="array";var yn="_validate",_I="_message",En="_invalid",to="_ofType",fm="_anyOf",Ja="_oneOf";var lL={[ye]:Ft,[An]:W,[jl]:Bu,[Yr]:X,[Bn]:oe,[mm]:Al,[XC]:ra,[dm]:hr,[Xa]:ia,[Yl]:Mi,[IE]:Il,[Co]:ke,[ql]:Do,[RI]:Ni,[hE]:Sn,[bI]:mr,[fo]:sr,[Ju]:et,[Zu]:et,[OI]:Wr,[Cs]:Et},fL={[ye]:Ri,[jl]:Ri,[An]:Ri,[Yr]:Ri,[CI]:Er,[Yl]:Ri,[Xa]:Er,[IE]:Er,[ql]:Ri,[Ju]:Er,[Zu]:Er,[hE]:Er,[fo]:Ri,[Cs]:Ri,[eR]:Er};function lt(t,e,r){if(!t&&!Rt(t))return{error:G};if(!e?.length||t?._bypassParamCheck)return{valid:!0};if(!Array.isArray(e))return{error:G};let{paramError:n,errorParam:o}=hL(t,e);if(!n)return{valid:!0};let i=t?.[o]===void 0?lL[o]||G:n[yn]&&n[En]||G,s=o??(n[Ja]&&Object.keys(n[Ja]).join(", "));return _({info:{param:s,message:n[_I]},result:{error:i},stack:r})}function sR(t,e){let r=Object.keys(t),n=Object.keys(e);return jt(r,n)}function gL(t,e){if(!e)return;let r=sR(t,e);return r.length!==1?{error:G}:r.reduce((n,o)=>({...n,[o]:!0}),{})}function IL(t,e){if(!e)return;let r=sR(t,e).filter(n=>t[n]);return r.length<1?{error:G}:r.reduce((n,o)=>({...n,[o]:!0}),{})}function hL(t,e){let r,n;return{paramError:e.find(({_ofType:i,_oneOf:s,_anyOf:a,_validate:c,_info:u,...p})=>{let m=s&&gL(t,s);if(m?.error)return m.error;m&&Object.assign(p,m);let d=a&&IL(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&&!Mr(c),h=t[g]&&!c&&SL(t,g,i),S=p[g]&&!t[g],A=I||h||S||c&&t[g]&&!TL(t[g],c);return A&&(r=g,n=u),A});return!l.length||f}),errorParam:r,paramInfo:n}}function SL(t,e,r){return r=r||fL[e]||"string",r==="array"?!Array.isArray(t[e]):typeof t[e]!==r}function TL(t,e){return Mr(e)?e(t):!0}var vI="DYNAMIC",oi="RANKING",Ki="RATING",zi="SCALE",eo="SEEDING",aR={RANKING:oi,RATING:Ki,SCALE:zi,SEEDING:eo};function aa(t){let e=lt(t,[{[Yl]:!0}]);if(e.error)return e;let r=t.participant.timeItems?.filter(({itemType:o})=>o?.startsWith(zi)&&[oi,Ki,eo].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===eo&&"seedings"||c===oi&&"rankings"||"ratings";n[l][u]||(n[l][u]=[]),n[l][u].push({scaleValue:a.itemValue,scaleDate:a.itemDate,scaleName:d})}}}return{...R,...n}}function bi(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 gm=/^[\d]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][\d]|3[0-1])$/,xI=/^((0[\d]|1[\d]|2[0-3]):[0-5][\d](:[0-5][\d])?)([.,][0-9]{3})?$/,Ro=/^([\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?$/,Rs=/^([\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 Im(t){let{scheduledDate:e}=t;if(!e&&t.scheduledTime&&(e=Ut(t.scheduledTime)),!e)return;let r=$t(t.scheduledTime),n=Ut(e);return n&&r&&(n+=`T${r}`),n}function cR(t){return typeof t!="object"||Array.isArray(t)?!1:Object.prototype.toString.call(t)==="[object Date]"}function Bc(t){let e=typeof t=="string"?t?.split(" "):[];return t&&e?.length>1&&!["AM","PM"].includes(e[1].toUpperCase())?!1:!!(!t||Rs.test(tc(t,!0,!0)))}function Rr(t){return Za(t)||gm.test(t)}function AL(t){let e=new Date(t),r=e.getSeconds()+60*e.getMinutes()+60*60*e.getHours();return yL(r,{displaySeconds:!1})}function yL(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(Hn).join(":")}var zl=t=>{let e=$l(t)||Za(t)?new Date(t):new Date,r=e.getUTCMonth()+1,n=r<10?`0${r}`:`${r}`;return`${e.getUTCFullYear()}-${Hn(n)}-${Hn(e.getUTCDate())}`};function EL(t){let e=$l(t)||Za(t)?new Date(t):new Date;return Date.UTC(e.getFullYear(),e.getMonth(),e.getDate())}function ro(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 wI(t){let e=t?new Date(t):new Date,r=e.getTimezoneOffset();return new Date(e.getTime()-r*60*1e3)}function UL(t){return wI(t).getTime()}function $l(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 bs(t,e){if(!Rr(t)||!Rr(e))return[];let r=Ut(t)+"T00:00",n=Ut(e)+"T00:00",o=new Date(r),i=new Date(n),s=$l(i)&&$l(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=>ro(p));function u(p,m){return p<=m}}var PL=/^([+-]?\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 Za(t){return typeof t!="string"?!1:PL.test(t)}function FI(t){if(typeof t!="string")return!1;let r=t.split("Z")[0].split(":"),n=r.every(i=>!isNaN(parseInt(i)));return!(r.length<2||!n||parseInt(r[0])>23||parseInt(r[1])>60)}function Vt(t){let e=$t(t);if(!e)return 0;let[r,n]=e.split(":").map(o=>parseInt(o));return r*60+n}function uR(t){let e=Math.floor(t/60),r=t-e*60;return e>23&&(e=e%24),[Hn(e),Hn(r)].join(":")}function Kl(t){return FI(t)?t.split(":").slice(0,2).map(Hn).join(":"):void 0}function $t(t){return Za(t)&&t.indexOf("T")>0?Kl(t.split("T").reverse()[0]):Kl(t)}function Ut(t){return Za(t)||Ro.test(t)?t.split("T")[0]:void 0}function tp(t,e){let r=new Date(t);return r.setDate(r.getDate()+e),Ut(r.toISOString())}function LI(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 DL(t){let e=LI(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(Hn).join(":")}function NL(t){let e=LI(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 tc(t,e,r){let n=Ut(t),o=$t(t),i=n?o:t;return t?e&&(n&&r&&t||DL(i))||NL(i):void 0}function GI(t,e){let r=LI(t),n=LI(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 pR(t,e=7){let r=Ut(t)+"T00:00",n=new Date(r),o=new Date(n.setDate(n.getDate()+e));return ro(o)}function ML(t){return pR(t)}function CL(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())),ro(o,r)}function mR(t,e,r){let n=new Date(t,0);return ro(new Date(n.setDate(e)),r)}function we(t,e=void 0){let[r,n]=(t||"00:00").split(":").map(Hn),o=wI(e).setHours(r,n,0,0);return wI(o)}function ca(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 br(t,e){let r=$t(t);if(!r)return"00:00";let n=isNaN(e)?0:e;return $t(Ql(we(r),n).toISOString())}function Ql(t,e){let r=new Date(t);return new Date(r.getTime()+e*6e4)}function Hn(t){return t.toString()[1]?t:"0"+t}function _n(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 dR={addDays:pR,addWeek:ML,addMinutesToTimeString:br,convertTime:tc,getIsoDateString:Im,getUTCdateString:zl,DateHHMM:AL,extractDate:Ut,extractTime:$t,formatDate:ro,getDateByWeek:CL,isISODateString:Za,isDate:$l,isTimeString:FI,offsetDate:wI,offsetTime:UL,sameDay:_n,timeStringMinutes:Vt,timeToDate:we,timeUTC:EL,validTimeValue:Bc,validDateString:gm,timeValidation:Rs,dateValidation:Ro};function J(t,e,r,n,o=0){if(MI().makeDeepCopy)return MI().makeDeepCopy(t,e,r,n);let i=Vl(),{stringify:s,toJSON:a,ignore:c,modulate:u}=i||{};if(!i?.enabled&&!r||typeof t!="object"||Mr(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)||Mr(c)&&!c(l)),d=(l,f)=>{p[l]=Mr(f?.toString)?f.toString():JSON.stringify(f)};for(let l of m){let f=t[l],g=Mr(u)?u(f):void 0;if(g!==void 0)p[l]=g;else if(e&&l==="extensions"&&Array.isArray(f)){let I=Xl(f);Object.assign(p,...I)}else n&&l==="extensions"?p[l]=[]:Array.isArray(s)&&s.includes(l)?d(l,f):Array.isArray(a)&&a.includes(l)&&Mr(f?.toJSON)?p[l]=f.toJSON():f===null?p[l]=void 0:cR(f)?p[l]=new Date(f).toISOString():p[l]=J(f,e,r,n,o+1)}return p}function Xl(t){return t?.map(e=>{let{name:r,value:n}=e;return r&&n&&{[`_${r}`]:n}}).filter(Boolean)}var kI="voluntaryConsolation",ii="competitiveBands",Jl="roundRobinTally",no="positionActions",ze="matchUpActions",Zl="rankingPoints",ua="roundNaming",Os="participant",Hc="progression",go="scheduling",Wc="avoidance",RL="display",vn="scoring",Un="seeding",ec="feedIn",bL="audit",hm="draws",lR={POLICY_TYPE_VOLUNTARY_CONSOLATION:kI,POLICY_TYPE_COMPETITIVE_BANDS:ii,POLICY_TYPE_ROUND_ROBIN_TALLY:Jl,POLICY_TYPE_POSITION_ACTIONS:no,POLICY_TYPE_MATCHUP_ACTIONS:ze,POLICY_TYPE_RANKING_POINTS:Zl,POLICY_TYPE_ROUND_NAMING:ua,POLICY_TYPE_PARTICIPANT:Os,POLICY_TYPE_PROGRESSION:Hc,POLICY_TYPE_SCHEDULING:go,POLICY_TYPE_AVOIDANCE:Wc,POLICY_TYPE_DISPLAY:RL,POLICY_TYPE_FEED_IN:ec,POLICY_TYPE_SCORING:vn,POLICY_TYPE_SEEDING:Un,POLICY_TYPE_AUDIT:bL,POLICY_TYPE_DRAWS:hm};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?.[Os];if(r?.withScaleValues){let{ratings:u,rankings:p}=aa({participant:a});a.rankings=p,a.ratings=u}if(c?.participant)return bi({template:c.participant,source:a})}return a}var Sm="element required",fR="missing name";function or(t){if(!t||typeof t!="object")return{error:et};if(t.element&&typeof t?.element!="object")return{error:G};if(!t?.name)return{error:et,info:fR};if(!t?.element){if(t.discover&&t.tournamentRecords){for(let e of Object.keys(t.tournamentRecords)){let r=t.tournamentRecords[e],n=or({element:r,name:t.name});if(n.error)return _({result:n,stack:"removeExtension"})}return{...R}}return{error:et,info:Sm}}return t?.element.extensions?(t.element.extensions=t.element.extensions.filter(e=>e?.name!==t.name),{...R}):{...R,info:Ke}}function Pn({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 St(t){if(typeof t!="object")return{error:et};let e="addExtension";if(t?.element&&typeof t.element!="object")return _({result:{error:G},stack:e});if(!Pn({extension:t.extension}))return _({result:{error:G,info:"invalid extension"},stack:e});if(!t.element)if(t.discover&&!t.tournamentId&&t.tournamentRecords){for(let o of Object.values(t.tournamentRecords)){let i=St({extension:t.extension,element:o});if(i.error)return _({result:i,stack:e})}return{...R}}else return _({result:{error:et},stack:e});if(t.element.extensions||(t.element.extensions=[]),t?.creationTime??!0){let o=new Date().toISOString();Object.assign(t.extension,{createdAt:o})}let n=t.element.extensions.find(({name:o})=>o===t.extension.name);return n?n.value=t.extension.value:t.extension.value&&t.element.extensions.push(t.extension),{...R}}function tf(t){return!t||typeof t!="object"?{error:et}:t.tournamentRecord?St({creationTime:t.creationTime,element:t.tournamentRecord,extension:t.extension}):{error:W}}function ep(t){return!t||typeof t!="object"?{error:et}:t.drawDefinition?St({creationTime:t.creationTime,element:t.drawDefinition,extension:t.extension}):{error:pr}}function Io(t){return!t||typeof t!="object"?{error:et}:t.event?St({creationTime:t.creationTime,extension:t.extension,element:t.event}):{error:mr}}function SE(t){if(!t||typeof t!="object")return{error:et};if(!t.participantId)return{error:oe};let e=t.tournamentRecord?.participants||[],r=bo({participantId:t.participantId,tournamentParticipants:e});return r?St({creationTime:t.creationTime,extension:t.extension,element:r}):{error:Zt}}function ef(t){return!t||typeof t!="object"?{error:et}:t.tournamentRecord?or({element:t.tournamentRecord,name:t.name}):{error:W}}function TE(t){return!t||typeof t!="object"?{error:et}:t.drawDefinition?or({element:t.drawDefinition,name:t.name}):{error:pr}}function rp(t){return!t||typeof t!="object"?{error:et}:t?.event?or({element:t.event,name:t.name}):{error:mr}}function AE(t){if(!t||typeof t!="object")return{error:et};if(!t.participantId)return{error:oe};let e=t.tournamentRecord?.participants||[],r=bo({participantId:t.participantId,tournamentParticipants:e});return r?or({element:r,name:t.name}):{error:Zt}}function np({tournamentRecords:t}){return{tournamentIds:Rt(t)?Object.keys(t):[],...R}}var OL="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:Ke}}return _({result:{error:et},stack:OL})}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:Ke}}var _L="activeSuspension",jc="appliedPolicies",Tm="positionActions",yE="context",Am="delegatedOutcome",Wn="disabled",ym="disableLinks",rc="disableAutoCalc",Em="drawDeletions",vL="drawProfile",Um="entryProfile",xL="eventProfile",wL="eventWithdrawalRequests",LL="factory",qr="flightProfile",VI="groupingAttribute",ho="lineUps",pa="linkedTournamentsIds",Pm="matchUpHistory",BI="participantRepresentatives",ma="personRequests",FL="rankingPoints";var mn="roundTarget",Yc="scheduleLimits",Oo="scheduleTiming",da="schedulingProfile",GL="statusDetail",nc="subOrder",Ho="tally",Qi="tieFormatModification",HI={ACTIVE_SUSPENSION:_L,APPLIED_POLICIES:jc,AUDIT_POSITION_ACTIONS:Tm,CONTEXT:yE,DELEGATED_OUTCOME:Am,DISABLED:Wn,DISABLE_LINKS:ym,DISABLE_AUTO_CALC:rc,DRAW_DELETIONS:Em,DRAW_PROFILE:vL,ENTRY_PROFILE:Um,EVENT_PROFILE:xL,EVENT_WITHDRAWAL_REQUESTS:wL,FLIGHT_PROFILE:qr,GROUPING_ATTRIBUTE:VI,LINEUPS:ho,LINKED_TOURNAMENTS:pa,MATCHUP_HISTORY:Pm,PARTICIPANT_REPRESENTATIVES:BI,PERSON_REQUESTS:ma,RANKING_POINTS:FL,ROUND_TARGET:mn,SCHEDULE_LIMITS:Yc,SCHEDULE_TIMING:Oo,SCHEDULING_PROFILE:da,STATUS_DETAIL:GL,SUB_ORDER:nc,TALLY:Ho,TIE_FORMAT_MODIFICATIONS:Qi,FACTORY:LL},EE=[Am,Wn,ym,qr,ho,Pm,BI,ma,mn,Yc,Oo,da,nc,Ho];function UE({tournamentRecords:t}){if(typeof t!="object"||!Object.keys(t).length)return{error:Ft};let e=np({tournamentRecords:t}),{tournamentIds:r}=e;return r?.length>1?St({tournamentRecords:t,discover:!0,extension:{name:pa,value:{tournamentIds:r}}}):{...R}}function PE({tournamentRecords:t}){if(typeof t!="object"||!Object.keys(t).length)return{error:Ft};let e=or({name:pa,tournamentRecords:t,discover:!0});return _({result:e,stack:"unlinkTournaments"})}function DE({tournamentRecords:t,tournamentId:e}){if(typeof t!="object")return{error:G};if(!e)return{error:ra};let r=np({tournamentRecords:t}),{tournamentIds:n}=r;if(!n.includes(e))return{error:ra};let o;return n.every(i=>{let s=t[i],{extension:a}=mt({element:s,name:pa});if(!a)return!0;let c=a?.value?.tournamentIds||[];if(!c?.length||c.length===1&&c.includes(e)||i===e){let m=ef({name:pa,tournamentRecord:s});return m.error&&(o=m.error),m.success}let u=c.filter(m=>m!==e);a.value={tournamentIds:u};let p=tf({tournamentRecord:s,extension:a});return p.error&&(o=p.error),p.success}),o?{error:o}:{...R}}var ME={};Jt(ME,{getLinkedTournamentIds:()=>qc,getTournamentIds:()=>np});function qc({tournamentRecords:t}){return typeof t!="object"||!Object.keys(t).length?{error:Ft}:{linkedTournamentIds:Object.assign({},...Object.keys(t).map(r=>{let n=t[r],o=n?.tournamentId,{extension:i}=mt({element:n,name:pa}),s=(i?.value?.tournamentIds||[]).filter(a=>a!==o);return{[r]:s}}))}}var ZD={};Jt(ZD,{addAdHocMatchUps:()=>fd,addDrawDefinitionTimeItem:()=>tg,addFinishingRounds:()=>ha,addGoesTo:()=>wi,addPlayoffStructures:()=>Dp,addQualifyingStructure:()=>WU,addVoluntaryConsolationStage:()=>BU,addVoluntaryConsolationStructure:()=>jf,allPlayoffPositionsFilled:()=>Yh,alternateDrawPositionAssignment:()=>DU,assignDrawPosition:()=>rP,assignDrawPositionBye:()=>Dr,attachConsolationStructures:()=>JU,attachPlayoffStructures:()=>og,attachQualifyingStructure:()=>Zf,attachStructures:()=>ig,autoSeeding:()=>fv,automatedPlayoffPositioning:()=>Sc,automatedPositioning:()=>hc,checkValidEntries:()=>Sd,deleteAdHocMatchUps:()=>nP,drawMatic:()=>Od,findDrawDefinition:()=>fS,generateAdHocMatchUps:()=>Nu,generateAdHocRounds:()=>bd,generateAndPopulatePlayoffStructures:()=>ld,generateDrawDefinition:()=>_u,generateDrawMaticRound:()=>Ed,generateDrawStructuresAndLinks:()=>Td,generateDrawTypeAndModifyDrawDefinition:()=>Ad,generateQualifyingStructure:()=>id,generateVoluntaryConsolation:()=>LS,getAssignedParticipantIds:()=>Si,getAvailableMatchUpsCount:()=>gd,getAvailablePlayoffProfiles:()=>Iu,getDrawDefinitionTimeItem:()=>Dh,getDrawParticipantRepresentativeIds:()=>dS,getDrawTypeCoercion:()=>Pu,getEligibleVoluntaryConsolationParticipants:()=>mS,getMatchUpsMap:()=>Ae,getParticipantIdFinishingPositions:()=>lS,getPositionAssignments:()=>Cp,getPositionsPlayedOff:()=>Ac,getSeedingThresholds:()=>wh,getSeedsCount:()=>Du,getStructureSeedAssignments:()=>Fr,getTeamLineUp:()=>os,getValidGroupSizes:()=>Sp,isAdHoc:()=>fr,isCompletedStructure:()=>Jo,isValidForQualifying:()=>RS,luckyLoserDrawPositionAssignment:()=>PU,modifyDrawDefinition:()=>ZU,modifyDrawName:()=>sg,modifySeedAssignment:()=>OU,mutate:()=>sP,positionActions:()=>CS,pruneDrawDefinition:()=>eP,qualifierDrawPositionAssignment:()=>RU,query:()=>TP,removeDrawPositionAssignment:()=>fu,removeRoundMatchUps:()=>oP,removeSeededParticipant:()=>HU,removeStructure:()=>VU,renameStructures:()=>kU,resetDrawDefinition:()=>tP,resetVoluntaryConsolationStructure:()=>YE,setDrawParticipantRepresentativeIds:()=>bE,setPositionAssignments:()=>MU,setStructureOrder:()=>GU,setSubOrder:()=>iP,shiftAdHocRounds:()=>NU,swapAdHocRounds:()=>CU,swapDrawPositionAssignments:()=>bU,updateTeamLineUp:()=>Fi,withdrawParticipantAtDrawPosition:()=>EU});var sP={};Jt(sP,{addAdHocMatchUps:()=>fd,addDrawDefinitionTimeItem:()=>tg,addPlayoffStructures:()=>Dp,addQualifyingStructure:()=>WU,addVoluntaryConsolationStage:()=>BU,addVoluntaryConsolationStructure:()=>jf,alternateDrawPositionAssignment:()=>DU,assignDrawPosition:()=>rP,assignDrawPositionBye:()=>Dr,attachConsolationStructures:()=>JU,attachPlayoffStructures:()=>og,attachQualifyingStructure:()=>Zf,attachStructures:()=>ig,automatedPlayoffPositioning:()=>Sc,automatedPositioning:()=>hc,deleteAdHocMatchUps:()=>nP,luckyLoserDrawPositionAssignment:()=>PU,modifyDrawDefinition:()=>ZU,modifyDrawName:()=>sg,modifySeedAssignment:()=>OU,pruneDrawDefinition:()=>eP,qualifierDrawPositionAssignment:()=>RU,removeDrawPositionAssignment:()=>fu,removeRoundMatchUps:()=>oP,removeSeededParticipant:()=>HU,removeStructure:()=>VU,renameStructures:()=>kU,resetDrawDefinition:()=>tP,resetVoluntaryConsolationStructure:()=>YE,setDrawParticipantRepresentativeIds:()=>bE,setPositionAssignments:()=>MU,setStructureOrder:()=>GU,setSubOrder:()=>iP,shiftAdHocRounds:()=>NU,swapAdHocRounds:()=>CU,swapDrawPositionAssignments:()=>bU,updateTeamLineUp:()=>Fi,withdrawParticipantAtDrawPosition:()=>EU});var RE=t=>e=>t[e],Dm=(t=[])=>t.map(fe).filter(Boolean),rf=(t=[])=>t.map(gt).filter(Boolean),gt=(t={})=>RE(t)("participantId");var fe=(t={})=>RE(t)("matchUpId"),$c=(t={})=>RE(t)("drawId");function bE({representativeParticipantIds:t,drawDefinition:e}){if(!e)return{error:pr};if(!Array.isArray(t))return{error:G};let r=rf(e?.entries||[]);return t.length&&jt(t,r).length<t.length?{error:G}:ep({drawDefinition:e,extension:{name:BI,value:t}})}var $r="ABANDONED",oc="AWAITING_RESULT",Dt="BYE",Wo="CANCELLED",me="COMPLETED",Kc="DEAD_RUBBER",Ot="DEFAULTED",Ne="DOUBLE_DEFAULT",ge="DOUBLE_WALKOVER",Dn="IN_PROGRESS",_o="INCOMPLETE",OE="NOT_PLAYED",lr="RETIRED",Xi="SUSPENDED",zt="TO_BE_PLAYED",_t="WALKOVER",gR=[oc,me,Ot,Dn,_o,lr,Xi],WI=[oc,me,Ot,ge,Ne,Dn,_o,lr,Xi,_t],jI=[$r,oc,Dt,Wo,me,Kc,Ot,ge,Ne,Dn,_o,OE,lr,Xi,zt,_t],YI=[Dt,ge,Ne,me,Ot,lr,_t],qI=[$r,oc,Wo,Kc,Dn,_o,OE,Xi,zt,void 0],ae=[Wo,$r,me,Kc,Ot,ge,Ne,lr,_t],Nm=[$r,me,Ot,ge,Ne,Dn,lr,_t],$I=[Dn,_o,Xi,zt],KI={ABANDONED:$r,AWAITING_RESULT:oc,BYE:Dt,CANCELLED:Wo,COMPLETED:me,DEAD_RUBBER:Kc,DEFAULTED:Ot,DOUBLE_WALKOVER:ge,DOUBLE_DEFAULT:Ne,IN_PROGRESS:Dn,INCOMPLETE:_o,NOT_PLAYED:OE,RETIRED:lr,SUSPENDED:Xi,TO_BE_PLAYED:zt,WALKOVER:_t};var tt="MAIN",at="QUALIFYING",Ve="CONSOLATION",Be="VOLUNTARY_CONSOLATION",ce="PLAY_OFF",Mm=[tt,at,Ve,ce,Be],_s={[at]:1,[tt]:2,[ce]:3,[Ve]:3,[Be]:4},_E="finishingPositions",vE="aggregateEventStructures",xE={[tt]:1,[ce]:2,[Ve]:3,[at]:4,[Be]:5},IR={[ce]:1,[tt]:2,[Ve]:3,[at]:4,[Be]:5},zc="CLUSTER",hR="SEPARATE",si="WATERFALL",op="ITEM",Le="CONTAINER",Qr="DRAW",ip="RANDOM",sn="TOP_DOWN",ai="BOTTOM_UP",jn="POSITION",oo="WINNER",Yn="LOSER",qn="FIRST_MATCHUP",an="AD_HOC",kL="AD_HOC",la="FEED_IN",Qc="COMPASS",Xc="OLYMPIC",VL="SINGLE_ELIMINATION";var io="SINGLE_ELIMINATION",Jc="DOUBLE_ELIMINATION",Zc="FIRST_MATCH_LOSER_CONSOLATION",sp="FIRST_ROUND_LOSER_CONSOLATION",Oi="LUCKY_DRAW",nf="CURTIS_CONSOLATION",SR="CURTIS_CONSOLATION",zI="FEED_IN_CHAMPIONSHIP_TO_SF",Cm="FEED_IN_CHAMPIONSHIP_TO_SF",QI="FEED_IN_CHAMPIONSHIP_TO_QF",Rm="FEED_IN_CHAMPIONSHIP_TO_QF",XI="FEED_IN_CHAMPIONSHIP_TO_R16",bm="FEED_IN_CHAMPIONSHIP_TO_R16",wE="MODIFIED_FEED_IN_CHAMPIONSHIP",Om="MODIFIED_FEED_IN_CHAMPIONSHIP",ap="FEED_IN_CHAMPIONSHIP",dn="ROUND_ROBIN",so="ROUND_ROBIN_WITH_PLAYOFF",LE="DECIDER",FE="BACKDRAW",of={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"}},sf={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",_i="ROUND_OUTCOME",GE=[Qc,nf,Rm,bm,Cm,ap,QI,XI,zI,Zc,sp,Oi,Om,Xc,ce,so],BL=[an,Qc,nf,Jc,Rm,bm,Cm,ap,la,Zc,sp,Oi,Om,Xc,ce,dn,so,io],kE={MAIN:tt,QUALIFYING:at,CONSOLATION:Ve,ITEM:op,CONTAINER:Le,FIRST_MATCHUP:qn,WINNER:oo,LOSER:Yn,AD_HOC:an,FEED_IN:la,FLEX_ROUNDS:kL,COMPASS:Qc,PLAY_OFF:ce,OLYMPIC:Xc,KNOCKOUT:VL,SINGLE_ELIMINATION:io,DOUBLE_ELIMINATION:Jc,CURTIS:nf,FICSF:zI,FICQF:QI,FICR16:XI,MFIC:wE,VOLUNTARY_CONSOLATION:Be,FIRST_MATCH_LOSER_CONSOLATION:Zc,FIRST_ROUND_LOSER_CONSOLATION:sp,MODIFIED_FEED_IN_CHAMPIONSHIP:Om,FEED_IN_CHAMPIONSHIP_TO_R16:bm,FEED_IN_CHAMPIONSHIP_TO_QF:Rm,FEED_IN_CHAMPIONSHIP_TO_SF:Cm,FEED_IN_CHAMPIONSHIP:ap,LUCKY_DRAW:Oi,ROUND_ROBIN_WITH_PLAYOFF:so,ROUND_ROBIN:dn,DECIDER:LE,BACKDRAW:FE,COMPASS_ATTRIBUTES:of,OLYMPIC_ATTRIBUTES:sf,DRAW:Qr,RANDOM:ip,TOP_DOWN:sn,BOTTOM_UP:ai,WATERFALL:si,WIN_RATIO:vs,ROUND_OUTCOME:_i,MULTI_STRUCTURE_DRAWS:GE,generatedDrawTypes:BL,stageOrder:_s,finishOrder:xE,AGGREGATE_EVENT_STRUCTURES:vE,FINISHING_POSITIONS:_E},TR=kE;function ci(t,e,r){let n=m=>mt({element:m,name:mn})?.extension?.value,o=r?.deprioritizeCompleted,i=r?.mode===vE&&IR,s=r?.mode===_E&&xE,a=s||i||_s,c=m=>m?.stage===tt&&m?.stageSequence===1,u=m=>c(m)?-1:a[m?.stage],p=m=>m?.matchUps.every(({matchUpStatus:d})=>ae.includes(d)?1:-1);return o&&p(t)-p(e)||i&&u(t)-u(e)||(t?.stage&&a[t.stage]||0)-(e?.stage&&a[e.stage]||0)||(n(t)||0)-(n(e)||0)||!s&&!i&&(e?.positionAssignments?.length??1/0)-(t?.positionAssignments?.length??1/0)||(t?.stageSequence??0)-(e?.stageSequence??0)||(af(t)||0)-(af(e)||0)}function af(t){return(t?.matchUps||[]).reduce((e,r)=>{let n=(r.finishingPositionRange?.winner||[]).reduce((o,i)=>o+i,0);return!e||n<e?n:e},void 0)}function st(t){let e=lt(t,[{[Yr]:!0,[dm]:!0}]);if(e.error)return e;let{drawDefinition:r,structureId:n}=t,{structures:o}=xn({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===op?i?.find(c=>c.structures?.some(u=>u.structureId===n)):void 0;return{structure:s,containingStructure:a}}function xn({withStageGrouping:t,drawDefinition:e,stageSequences:r,stageSequence:n,roundTarget:o,sortConfig:i,stages:s,stage:a}){let c=!e&&X||!e?.structures&&Il||void 0;if(c)return{error:c,structures:[],stageStructures:{}};let u=f=>{let g=mt({element:f,name:mn})?.extension?.value;return!o||o===g},p=e?.structures?.filter(d).filter(l).filter(u).sort((f,g)=>ci(f,g,i))??[],m=t?Object.assign({},...Mm.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 JI({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}=Nt({structure:n}),s=i?.map(gt).filter(Boolean)??[];return e[o].push(...s),s}).flat(),stagePositionedParticipantIds:e}}function Nt({drawDefinition:t,structureId:e,structure:r}){let n,o=[];if(!r){if(!t)return{positionAssignments:o,error:X};if({structure:r,error:n}=st({drawDefinition:t,structureId:e}),n)return{positionAssignments:o,error:n}}return r.structures?o=[].concat(...r.structures.map(i=>Nt({structure:i}).positionAssignments)):r.positionAssignments?o=r.positionAssignments:n=Sy,{positionAssignments:o,error:n}}function de({drawDefinition:t,structureId:e,structure:r}){let n=Nt({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",cp="addMatchUps",jo="addParticipants",uf="addScaleItems",ZI="addVenue",fa="audit",pf="deleteParticipants",mf="deleteVenue",df="deletedDrawIds",lf="deletedMatchUpIds",ff="modifyDrawDefinition",VE="modifyDrawEntries",BE="modifyEventEntries",gf="modifyMatchUp",Qe="modifyParticipants",If="modifyPositionAssignments",hf="modifySeedAssignments",HE="modifyTournamentDetail",ui="modifyVenue",_m="mutations",th="publishEvent",WE="publishEventSeeding",jE="publishOrderOfPlay",Sf="unPublishEvent",Tf="unPublishEventSeeding",Af="unPublishOrderOfPlay",up="updateInContextMatchUp",AR={ADD_DRAW_DEFINITION:cf,ADD_MATCHUPS:cp,ADD_PARTICIPANTS:jo,ADD_SCALE_ITEMS:uf,ADD_VENUE:ZI,AUDIT:fa,DELETE_PARTICIPANTS:pf,DELETE_VENUE:mf,DELETED_DRAW_IDS:df,DELETED_MATCHUP_IDS:lf,MODIFY_DRAW_DEFINITION:ff,MODIFY_DRAW_ENTRIES:VE,MODIFY_EVENT_ENTRIES:BE,MODIFY_MATCHUP:gf,MODIFY_PARTICIPANTS:Qe,MODIFY_POSITION_ASSIGNMENTS:If,MODIFY_SEED_ASSIGNMENTS:hf,MODIFY_TOURNAMENT_DETAIL:HE,MODIFY_VENUE:ui,MUTATIONS:_m,PUBLISH_EVENT_SEEDING:WE,PUBLISH_EVENT:th,PUBLISH_ORDER_OF_PLAY:jE,UNPUBLISH_EVENT_SEEDING:Tf,UNPUBLISH_EVENT:Sf,UNPUBLISH_ORDER_OF_PLAY:Af,UPDATE_INCONTEXT_MATCHUP:up};function eh(t,e){if(!t)return{error:X};let r=Date.now();t.updatedAt&&r===new Date(t.updatedAt).getTime()&&(r+=1);let n=new Date(r).toISOString(),o=e?.filter(Boolean);return t.updatedAt=n,t.structures?.filter(Boolean).forEach(i=>{(!o?.length||o?.includes(i.structureId))&&(i.updatedAt=n)}),{...R}}function So({drawDefinition:t,tournamentId:e,matchUps:r,eventId:n}){return t&&eh(t),Tt({payload:{matchUps:r,tournamentId:e,eventId:n},topic:cp}),{...R}}function wn({drawDefinition:t,tournamentId:e,matchUpIds:r,eventId:n,action:o}){t&&eh(t),Tt({topic:lf,payload:{tournamentId:e,matchUpIds:r,eventId:n,action:o}});for(let i of r)NI({key:i});return{...R}}function It({drawDefinition:t,tournamentId:e,structureId:r,context:n,eventId:o,matchUp:i}){return i?(t&&bt({drawDefinition:t,structureIds:r?[r]:void 0,tournamentId:e,eventId:o}),Tt({topic:gf,payload:{matchUp:i,tournamentId:e,context:n},key:i.matchUpId}),{...R}):(console.log(sr),{error:sr})}function yR({tournamentId:t,inContextMatchUp:e}){return e?(Tt({payload:{inContextMatchUp:e,tournamentId:t},topic:up,key:e.matchUpId}),{...R}):{error:sr}}function ga({tournamentId:t,eventId:e,drawDefinition:r}){return r?(eh(r),Tt({payload:{drawDefinition:r,tournamentId:t,eventId:e},topic:cf,key:r.drawId}),{...R}):(console.log(X),{error:X})}function ER({tournamentId:t,eventId:e,drawId:r}){return Tt({payload:{drawId:r,tournamentId:t,eventId:e},topic:df,key:r}),NI({key:r}),{...R}}function bt({drawDefinition:t,tournamentId:e,structureIds:r,eventId:n}){return t?(eh(t,r),Tt({payload:{tournamentId:e,eventId:n,drawDefinition:t},topic:ff,key:t.drawId}),{...R}):{error:X}}function rh({drawDefinition:t,tournamentId:e,structure:r,eventId:n}){if(!t)return{error:X};if(!r)return{error:Do};let o=r.seedAssignments,i=r.structureId,s=t.drawId;return Tt({payload:{tournamentId:e,eventId:n,drawId:s,structureId:i,seedAssignments:o},topic:hf,key:t.drawId}),bt({structureIds:[i],drawDefinition:t,tournamentId:e,eventId:n}),{...R}}function To({drawDefinition:t,tournamentId:e,structure:r,event:n}){if(!t)return{error:X};if(!r)return{error:Do};let o=Nt({structure:r}),i=r.structureId,s=t.drawId,a=n?.eventId;return Tt({topic:If,payload:{positionAssignments:o,tournamentId:e,structureId:i,eventId:a,drawId:s},key:i}),bt({structureIds:[i],drawDefinition:t,tournamentId:e,eventId:a}),{...R}}function YE({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=[],wn({tournamentId:t?.tournamentId,action:"resetVoluntaryConsolationStructure",matchUpIds:i,drawDefinition:e}),r&&(e.entries=e.entries.filter(s=>s.entryStage!==Be)),bt({tournamentId:t?.tournamentId,eventId:n?.eventId,drawDefinition:e,structureIds:[o.structureId]}),{...R}}function vm({drawPositions:t,structure:e}){if([at,tt].includes(e.stage)&&e.stageSequence===1)return;let{positionAssignments:r}=Nt({structure:e});r?.filter(({drawPosition:o})=>t?.includes(o))?.forEach(o=>{St({element:o,extension:{name:ym,value:!0}})})}function tu({drawDefinition:t,positionAction:e}){let{extension:r}=mt({name:Tm,element:t}),n=Array.isArray(r?.value)?r?.value??[]:[];if(!n?.length){let i=t.structures.find(s=>s.stage===tt);if(i){let s=Nt({structure:i}).positionAssignments?.map(({drawPosition:a,participantId:c,bye:u,qualifier:p})=>({drawPosition:a,participantId:c,qualifier:p,bye:u}));n.push({name:"initialMainAssignments",initialAssignments:s})}}let o={name:Tm,value:n.concat(e)};St({element:t,extension:o})}function Ji({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 Ia="SINGLES",Xt="SINGLES",vi="DOUBLES",Gt="DOUBLES",ln="TEAM",Bt="TEAM",UR={SINGLES_MATCHUP:Ia,SINGLES:Xt,DOUBLES_MATCHUP:vi,DOUBLES:Gt,TEAM_MATCHUP:ln,TEAM:Bt};function eu(t){let{sides:e,matchUpType:r}=t||{},n=t.potentialParticipants?.length?t.potentialParticipants.flat().map(s=>r===Gt?s?.individualParticipantIds||[]:s.participantId).flat():[],o=(e||[]).map(s=>r===Gt&&(s?.participant?.individualParticipantIds||[])||s?.participantId&&[s.participantId]||[]).flat();return{individualParticipantIds:o.concat(n).flat(),enteredIndividualParticipantIds:o,potentialIndividualParticipantIds:n}}function Xr(t){return t?.tournamentRecords??(t?.tournamentRecord&&{[t.tournamentRecord.tournamentId]:t.tournamentRecord})??{}}function yf(t){if(!Rt(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 Ur(t){return Array.isArray(t)?t.every(yf):!1}function He({matchUps:t=[],interpolate:e}){if(!Ur(t))return{roundMatchUps:[],error:G};let r=t.reduce((d,l)=>{let f=typeof l.roundNumber=="string"?ct(l.roundNumber):l.roundNumber;return!l.roundNumber||d.includes(f)?d:d.concat(f)},[]).sort(se).map(d=>{let l=t.filter(h=>h.roundNumber===d),g=l.find(({matchUpType:h})=>h===Bt)?l.filter(({matchUpType:h})=>h===Bt):l,I=h=>h.sort((S,T)=>se(S.roundPosition,T.roundPosition));return{[d]:I(g)}}),n=t.reduce((d,l)=>{let f=typeof l.roundNumber=="string"?ct(l.roundNumber):l.roundNumber;return d[f]||(d[f]=rt({abbreviatedRoundName:l.abbreviatedRoundName,finishingRound:l.finishingRound,roundName:l.roundName})),d},{}),o=Object.assign({},...r);if(e){let d=Math.max(...Object.keys(o).map(f=>ct(f)).filter(f=>!isNaN(f))),l=o[d]?.length;if(l>1&&Tn(l)){let f=d+1,g=f+l/2;Z(f,g).forEach((h,S)=>{o[h]=Z(0,l/(2+S*2)).map(()=>({}))})}}let i=0,s=Object.assign({},...Object.keys(o).map(d=>{let l=o[d]?.length,f=o[d]?.filter(I=>!ae.includes(I.matchUpStatus)&&!I.score?.scoreStringSide1)?.length,g=l&&l===f;return i=Math.max(i,l),{[d]:{matchUpsCount:l,inactiveCount:f,inactiveRound:g}}})),a=0,c=0,u=Object.keys(o).map(d=>ct(d)).filter(d=>!isNaN(d));u.forEach(d=>{let l=o[d].sort((g,I)=>g.roundPosition-I.roundPosition),f=l.map(g=>g?.drawPositions||[]).flat();if(s[d].roundNumber=d,s[d].roundFactor=s[d].matchUpsCount?i/s[d].matchUpsCount:1,s[d].finishingRound=n[d]?.finishingRound,s[d].roundName=n[d]?.roundName,s[d].abbreviatedRoundName=n[d]?.abbreviatedRoundName,s[d].finishingPositionRange=o[d]?.[0]?.finishingPositionRange,d===1||!s[d-1]){let g=f.sort(se),I=Te(g,2);s[d].drawPositions=g,s[d].pairedDrawPositions=I}else{let g=s[d-1],I=g.drawPositions,h=g.matchUpsCount/s[d].matchUpsCount,S=Te(I,h),T=l.map(A=>{let{roundPosition:D}=A,y=[...A.drawPositions||[],void 0,void 0].slice(0,2);if(!D)return y;let E=y?.filter(Boolean)||[];if(!E?.length)return[void 0,void 0];if(d<3&&E?.length===2)return y?.slice().sort(se);let U=jt(I,E).length!==E?.length;if(E?.length&&U)return E?.length===1?[E[0],void 0]:y?.slice().sort(se);let M=(D-1)*2;return S.slice(M,M+2).map(N=>E?.find(C=>N.includes(C)))});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})=>!Tn(d));return{hasNoRoundPositions:t.some(d=>!d.roundPosition),roundsNotPowerOf2:p,maxMatchUpsCount:i,roundMatchUps:o,roundNumbers:u,roundProfile:s,...R}}function Zi({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 qE=t=>e=>!t||typeof e!="object"?void 0:Array.isArray(t)&&t.map(r=>({[r]:Zi({element:e,accessor:r})?.value}))||typeof t=="object"&&Object.keys(t).map(r=>({[r]:Zi({element:e,accessor:r})?.value}))||(typeof t=="string"&&Zi({element:e,accessor:t}))?.value,Pr=qE;function ha({finishingPositionOffset:t=0,finishingPositionLimit:e,positionsFed:r,roundsCount:n,roundLimit:o,matchUps:i,lucky:s,fmlc:a}){if(!Ur(i))return[];let{roundProfile:c,roundNumbers:u=[]}=He({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(Pr("matchUpsCount")),l=(I,h)=>{let S=Math.min(...I);m&&h&&S===1&&(S=m);let T=Math.max(...I);return e&&T>e&&(T=e),[S,T]},f=c&&Object.assign({},...u.map(I=>{let h=(n??0)+1-I-p,S=c[I].matchUpsCount,T={finishingPositionRange:{},finishingRound:h},A=d?.slice(I-1).reduce((C,O)=>C+(O||0),0),D=a&&I!==1,y=1+t+(D?r??0:0),E=1,U=Z(y,s?y+S*2:A+y+E),M=A+E-S,P=l(U.slice(M)),N=l(U.slice(0,M),!0);return T.finishingPositionRange={loser:P,winner:N},{[I]:T}})),g=yr({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 Ae({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 Yo({mappedMatchUps:t,matchUpsMap:e,structureId:r,inContext:n}){t=e?.mappedMatchUps??t;let o=t[r],i=(o?.itemStructureIds||[]).map(s=>{let{matchUps:a,structureName:c}=t[s];return n?a.map(u=>Object.assign(J(u,!0,!0),{containerStructureId:r,structureId:s,structureName:c})):a}).flat();return(o?.matchUps||[]).concat(...i)}var ic="SIGN_IN_STATUS",$E="SIGNED_OUT",ru="SIGNED_IN",Jr="TEAM",ht="INDIVIDUAL",Ar="GROUP",dt="PAIR",kt="TEAM",nu={TEAM_PARTICIPANT:Jr,INDIVIDUAL:ht,GROUP:Ar,TEAM:kt,PAIR:dt},PR={INDIVIDUAL:ht,GROUP:Ar,PAIR:dt,TEAM:kt,SIGN_IN_STATUS:ic,SIGNED_OUT:$E,SIGNED_IN:ru};function xm({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===kt),s=o.filter(c=>c.participantType===Ar),a=o.filter(c=>c.participantType===dt);return o.forEach(c=>{if(c.participantType===ht){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 Ef({drawDefinition:t,attributes:e}){let{extension:r}=mt({element:t,name:Um}),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:Um,value:n},ep({drawDefinition:t,extension:r}),{entryProfile:n}}function ou({drawDefinition:t}){let{extension:e}=mt({element:t,name:Um});return{entryProfile:e?.value||{}}}var wr="ALTERNATE",Uf="CONFIRMED",Zr="DIRECT_ACCEPTANCE",wm="FEED_IN",Pf="JUNIOR_EXEMPT",ts="LUCKY_LOSER",Df="ORGANISER_ACCEPTANCE",Lm="QUALIFIER",HL="REGISTERED",Nf="SPECIAL_EXEMPT",Lr="UNGROUPED",pi="UNPAIRED",iu="WILDCARD",Ao="WITHDRAWN",Mf=[Uf,Zr,Pf,Df,Nf],KE=[wm,ts,Lm],qo=[Uf,Zr,wm,Pf,Df,Nf,iu],Or=[Uf,Zr,Pf,ts,Lm,Df,Nf,iu],zE=[wr,Uf,Zr,wm,Pf,ts,Df,Lm,HL,Nf,Lr,pi,iu,Ao],DR={ALTERNATE:wr,CONFIRMED:Uf,DIRECT_ACCEPTANCE:Zr,DIRECT_ENTRY_STATUSES:qo,DRAW_SPECIFIC_STATUSES:KE,EQUIVALENT_ACCEPTANCE_STATUSES:Mf,FEED_IN:wm,JUNIOR_EXEMPT:Pf,LUCKY_LOSER:ts,ORGANISER_ACCEPTANCE:Df,QUALIFIER:Lm,SPECIAL_EXEMPT:Nf,STRUCTURE_SELECTED_STATUSES:Or,UNGROUPED:Lr,UNPAIRED:pi,VALID_ENTRY_STATUSES:zE,WILDCARD:iu,WITHDRAWN:Ao};function Cf({stage:t,drawDefinition:e}){let{entryProfile:r}=ou({drawDefinition:e}),n=Object.keys(r).includes(t);if(!n&&Mm.includes(t)){let o=[{[t]:{drawSize:void 0,alternates:!0}}];return Ef({drawDefinition:e,attributes:o}),!0}return n}function NR({stage:t,drawDefinition:e}){let{entryProfile:r}=ou({drawDefinition:e});return r[t]?.alternates||0}function MR({stage:t,drawDefinition:e}){let{entryProfile:r}=ou({drawDefinition:e});return r[t]?.wildcardsCount||0}function nh({stage:t,drawDefinition:e,entryStatus:r}){return e.entries.reduce((n,o)=>o.entryStage===t&&o.entryStatus===r?n+1:n,0)}function mi({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:mn,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===ce){let{playoffEntries:p,error:m}=WL({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 WL({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}=st({drawDefinition:e,structureId:s});a?.structureType===Le&&(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:Ho}).extension?.value;return T&&S?{[S]:T}:void 0}).filter(Boolean)),g=Object.keys(l).reduce((h,S)=>{let T=l[S],A=T.groupOrder||t&&T.provisionalOrder;return h.includes(A)||h.push(A),h},[]).length===Object.keys(l).length,I=Object.keys(l).filter(h=>{let S=l[h],T=S.groupOrder||t&&S.provisionalOrder;return i?.includes(T)});(!t||g)&&I.forEach(h=>{let S=l[h],{groupOrder:T,provisionalOrder:A,GEMscore:D}=S,y=T||t&&A,E=[...i??[]].sort(se).indexOf(y)+1;n.push({entryStage:ce,entryStatus:wm,placementGroup:E,groupingValue:d,participantId:h,GEMscore:D})})})}return{playoffEntries:n}}function CR({stage:t,drawDefinition:e}){return qo.reduce((r,n)=>(nh({drawDefinition:e,entryStatus:n,stage:t})||0)+r,0)}function Fr({provisionalPositioning:t,returnAllProxies:e,drawDefinition:r,structureId:n,structure:o}){let i,s=[];o||({structure:o,error:i}=st({drawDefinition:r,structureId:n}));let a=Nt({structure:o}).positionAssignments;if(i||!o)return{seedAssignments:[],error:Lt};n||(n=o.structureId);let{stage:c,stageSequence:u}=o,m=c===ce&&r&&mi({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=uy;let f=o.seedLimit??o?.positionAssignments?.length;return{seedAssignments:s,stageSequence:u,seedLimit:f,stage:c,error:i}}var oh="WALKOVER",QE="RETIRED",Fm="COMPETITIVE",sc="ROUTINE",ac="DECISIVE",Gm="winRatio";var jL=(t,e)=>(t||0)+(e||0);function ih(t,e){let r=Array.isArray(t)?t[0]:t;return isNaN(r)&&oh||r<=e[ac]&&ac||r<=e[sc]&&sc||Fm}function sh({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(jL)&&(r[n[0]>n[1]?0:1]+=1),{sets:e,games:r,score:t}}function YL(t){let e=Math.min(...t.games),r=Math.max(...t.games);return Math.round(e/r*100)}function ah(t){return t.map(YL).sort().map(e=>parseFloat(e.toFixed(2)))}function Pt({onlySpecifiedPolicyTypes:t=!1,policyTypes:e=[],tournamentRecord:r,drawDefinition:n,structure:o,event:i}){if(!Array.isArray(e))return{error:lI};let s={};return r&&a(r),i&&a(i),n&&a(n),o&&a(o),{appliedPolicies:s,...R};function a(c){let p=c?.extensions?.find(m=>m.name===jc)?.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 yo({policyTypes:t=[],tournamentRecord:e,drawDefinition:r,structure:n,event:o}){if(!Array.isArray(t))return{error:lI};let{appliedPolicies:i}=Pt({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:Lc.message}}function $o({tournamentRecord:t,drawDefinition:e,policyType:r,structure:n,event:o}){if(!t)return{error:W};let{appliedPolicies:i}=Pt({tournamentRecord:t,drawDefinition:e,structure:n,event:o});return i?.[r]?{policy:i[r]}:{info:Lc?.message}}var qL={[ii]:{policyName:"Competitive Bands Default",profileBands:{[ac]:20,[sc]:50}}},km=qL;function su({tournamentRecord:t,profileBands:e,matchUp:r}){if(!r)return{error:sr};let{score:n,winningSide:o}=r;if(!o)return{error:G};let i=!e&&t&&$o({policyType:ii,tournamentRecord:t}).policy,s=e||i?.profileBands||km[ii].profileBands,a=sh({score:n}),c=ah([a]),u=ih(c,s),p=Array.isArray(c)?c[0]:c;return{...R,competitiveness:u,pctSpread:p}}function ch({matchUp:t}){if(!t)return{error:sr};if(t&&!t.sides)return{error:Je};if(t&&!t.hasContext)return{error:Gc};let e=(t.sides??[])?.map(a=>a?.participantId).filter(Boolean),r=t.sides?.filter(a=>a.participant?.participantType===ht).map(a=>a.participantId).filter(Boolean)??[],o=((t.sides??[])?.map(a=>a.participant?.individualParticipants).filter(Boolean)??[]).map(a=>(a??[]).map(c=>c?.participantId).filter(Boolean)),i=[...r,...o.flat()].filter(Boolean)??[],s=pt(i.concat(e)).filter(Boolean)??[];return{nestedIndividualParticipantIds:o,allRelevantParticipantIds:s,individualParticipantIds:i,sideParticipantIds:e,...R}}var Vm="CHECK_IN",Bm="CHECK_OUT",RR="SCHEDULE",xs="SCHEDULE.ASSIGNMENT.VENUE",Eo="SCHEDULE.ALLOCATION.COURTS",di="SCHEDULE.ASSIGNMENT.COURT",Rf="SCHEDULE.COURT.ORDER",ws="SCHEDULE.DATE",$L="COMPLETED.DATE",XE="SCHEDULE.ASSIGN.OFFICIAL",Ls="SCHEDULE.TIME.SCHEDULED",Uo="SCHEDULE.TIME.START",xi="SCHEDULE.TIME.STOP",li="SCHEDULE.TIME.RESUME",fi="SCHEDULE.TIME.END",bf="SCHEDULE.TIME.MODIFIERS",bR="TO_BE_ANNOUNCED",OR="NEXT_AVAILABLE",_R="FOLLOWED_BY",vR="AFTER_REST",xR="RAIN_DELAY",KL="NOT_BEFORE",uh=[bR,OR,_R,vR,xR],zL="ELIGIBILITY",QL="REGISTRATION",XL="SUSPENSION",JL="MEDICAL",ZL="PENALTY",JE="SCALE",ZE="RATING",tU="RANKING",Of="SEEDING",Ko="PUBLISH",Gr="PUBLIC",zo="STATUS",tF="MODIFICATION",eF="RETRIEVAL",rF="other",wR={MUTUALLY_EXCLUSIVE_TIME_MODIFIERS:uh,AFTER_REST:vR,ALLOCATE_COURTS:Eo,ASSIGN_COURT:di,ASSIGN_OFFICIAL:XE,ASSIGN_VENUE:xs,CHECK_IN:Vm,CHECK_OUT:Bm,COMPLETED_DATE:$L,COURT_ORDER:Rf,ELIGIBILITY:zL,END_TIME:fi,FOLLOWED_BY:_R,MEDICAL:JL,MODIFICATION:tF,NEXT_AVAILABLE:OR,NOT_BEFORE:KL,OTHER:rF,PENALTY:ZL,PUBLIC:Gr,PUBLISH:Ko,RANKING:tU,RATING:ZE,RAIN_DELAY:xR,REGISTRATION:QL,RESUME_TIME:li,RETRIEVAL:eF,SCALE:JE,SCHEDULE:RR,SCHEDULED_DATE:ws,SCHEDULED_TIME:Ls,SEEDING:Of,START_TIME:Uo,STATUS:zo,STOP_TIME:xi,SUSPENSION:XL,TIME_MODIFIERS:bf,TO_BE_ANNOUNCED:bR};function es({matchUp:t}){if(!t)return{error:sr};if(!t.hasContext)return{error:Gc};if(!t.sides||t.sides.filter(Boolean).length!==2)return{error:Je};let{nestedIndividualParticipantIds:e,allRelevantParticipantIds:r,sideParticipantIds:n}=ch({matchUp:t}),i=(t.timeItems??[]).filter(u=>u?.itemType&&[Vm,Bm].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===Vm);e?.forEach((u,p)=>{let m=n?.[p],d=u?.length&&u.every(l=>a.includes(l));m&&d&&!a.includes(m)&&a.push(m)}),n?.forEach((u,p)=>{a.includes(u)&&(e?.[p]??[]).forEach(m=>{m&&!a.includes(m)&&a.push(m)})});let c=n?.reduce((u,p)=>a.includes(p)&&u,!0);return{allRelevantParticipantIds:r,allParticipantsCheckedIn:c,checkedInParticipantIds:a,...R}}var ph={[Xt]:[Xt,"S"],[Gt]:[Gt,"D"],[Bt]:[Bt,"T"],S:[Xt,"S"],D:[Gt,"D"],T:[Bt,"T"]};var ie=t=>e=>{let r=Rt(e)&&e?.matchUpType||$e(e)&&e;return r&&ph[t].includes(r)};function pp(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 mp(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 mh({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 LR({tournamentScheduling:t,eventScheduling:e,averageMinutes:r,defaultTiming:n,matchUpFormat:o,categoryName:i,categoryType:s,policy:a}){let c=e?.matchUpRecoveryTimes&&mp({...e,averageMinutes:r,matchUpFormat:o}),u=t?.matchUpRecoveryTimes&&mp({...t,averageMinutes:r,matchUpFormat:o}),p=a?.matchUpRecoveryTimes&&mp({...a,averageMinutes:r,matchUpFormat:o}),m=[c,u,p,a?.defaultTimes?.recoveryTimes,n?.recoveryTimes];return mh({categoryName:i,categoryType:s,timesBlockArray:m})}function FR({matchUpFormat:t,categoryName:e,categoryType:r,defaultTiming:n,tournamentScheduling:o,eventScheduling:i,policy:s}){let a=i?.matchUpAverageTimes&&pp({...i,matchUpFormat:t}),c=o?.matchUpAverageTimes&&pp({...o,matchUpFormat:t}),u=s?.matchUpAverageTimes&&pp({...s,matchUpFormat:t}),p=[a,c,u,s?.defaultTimes?.averageTimes,n?.averageTimes];return mh({categoryName:e,categoryType:r,timesBlockArray:p})}function Sa({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}=$o({policyType:go,tournamentRecord:t,event:n}),s=(t?mt({element:t,name:Oo}).extension:void 0)?.value,c=(n&&mt({name:Oo,element:n}).extension)?.value;return{scheduleTiming:{tournamentScheduling:s,eventScheduling:c,categoryName:e,categoryType:r,policy:o}}}var eU="DOUBLES_SINGLES",rU="SINGLES_DOUBLES",$n="total",dh="participantConflict",Ta="matchUpConflict",nU="ISSUE_IDS",cc="CONFLICT",uc="WARNING",lh="ERROR",fh="ISSUE",_f="STATE",GR={SINGLES_DOUBLES:rU,DOUBLES_SINGLES:eU,TOTAL:$n,CONFLICT_MATCHUP_ORDER:Ta,CONFLICT_PARTICIPANTS:dh,SCHEDULE_ISSUE_IDS:nU,SCHEDULE_CONFLICT:cc,SCHEDULE_WARNING:uc,SCHEDULE_ERROR:lh,SCHEDULE_ISSUE:fh,SCHEDULE_STATE:_f};var ao="SINGLES",Fs="SINGLES",Kr="DOUBLES",gi="DOUBLES",Fe="TEAM",kr="TEAM",nF="AGE",oF="RATING",iF="BOTH",kR={AGE:nF,BOTH:iF,DOUBLES:Kr,DOUBLES_EVENT:gi,RATING:oF,SINGLES:ao,SINGLES_EVENT:Fs,TEAM_EVENT:kr,TEAM:Fe};function au({defaultAverageMinutes:t=90,defaultRecoveryMinutes:e=0,tournamentRecord:r,matchUpFormat:n,categoryName:o,categoryType:i,eventType:s,event:a}){if(!r)return{error:W};s=s??a?.eventType??Fs;let c={averageTimes:[{minutes:{default:t}}],recoveryTimes:[{minutes:{default:e}}]},{scheduleTiming:u}=Sa({tournamentRecord:r,categoryName:o,categoryType:i,event:a}),p={...u,matchUpFormat:n,categoryType:i,defaultTiming:c};return dp({eventType:s,timingDetails:p})}function dp({timingDetails:t,eventType:e}){let r=FR(t),n=Object.keys(r?.minutes||{}),o=r?.minutes&&(n?.includes(e)&&r.minutes[e]||r.minutes.default),i=LR({...t,averageMinutes:o}),s=Object.keys(i?.minutes||{}),a=i?.minutes&&(s?.includes(e)&&i.minutes[e]||i.minutes.default),c=ie(Fs)(e)?rU:eU,u=i?.minutes&&(s?.includes(c)&&i.minutes[c]||a);return{averageMinutes:o,recoveryMinutes:a,typeChangeRecoveryMinutes:u}}function gh(t){return t.createdAt?new Date(t.createdAt).getTime():0}function vo({visibilityThreshold:t,timeItems:e,itemType:r}){let n=e.filter(i=>i&&i.itemType===r&&(!t||gh(i)<new Date(t).getTime())).sort((i,s)=>gh(i)-gh(s)).pop(),o=n&&gh(n);return{itemValue:n?.itemValue,timeStamp:o}}function vf({visibilityThreshold:t,timeStamp:e,schedule:r,matchUp:n}){let{itemValue:o,timeStamp:i}=vo({timeItems:n?.timeItems||[],itemType:Ls,visibilityThreshold:t});return!r||i&&e&&new Date(i).getTime()>new Date(e).getTime()?{scheduledTime:o}:r}function rs({visibilityThreshold:t,timeStamp:e,schedule:r,matchUp:n}){let{itemValue:o,timeStamp:i}=vo({timeItems:n?.timeItems||[],itemType:ws,visibilityThreshold:t});return!r||i&&e&&new Date(i).getTime()>new Date(e).getTime()?{scheduledDate:o}:r}function Ih({visibilityThreshold:t,timeStamp:e,schedule:r,matchUp:n}){let{itemValue:o,timeStamp:i}=vo({timeItems:n?.timeItems||[],itemType:Eo,visibilityThreshold:t});return!r||i&&e&&new Date(i).getTime()>new Date(e).getTime()?{allocatedCourts:J(o,!1,!0)}:r}function hh({visibilityThreshold:t,timeStamp:e,schedule:r,matchUp:n}){let{itemValue:o,timeStamp:i}=vo({timeItems:n?.timeItems||[],itemType:di,visibilityThreshold:t});return!r||i&&e&&new Date(i).getTime()>new Date(e).getTime()?{courtId:o}:r}function Sh({visibilityThreshold:t,timeStamp:e,schedule:r,matchUp:n}){let{itemValue:o,timeStamp:i}=vo({timeItems:n?.timeItems||[],itemType:xs,visibilityThreshold:t});return!r||i&&e&&new Date(i).getTime()>new Date(e).getTime()?{venueId:o}:r}function xf({visibilityThreshold:t,timeStamp:e,schedule:r,matchUp:n}){let{itemValue:o,timeStamp:i}=vo({timeItems:n?.timeItems||[],itemType:bf,visibilityThreshold:t});return!r||i&&e&&new Date(i).getTime()>new Date(e).getTime()?{timeModifiers:o}:r}function lp(t){if(xI.test(t)){let e=zl();return new Date(`${e}T${t}`)}else return new Date(t)}function VR({matchUp:t}){if(!t)return{error:sr};if(!t.timeItems)return{error:_l};let e=t.timeItems.filter(n=>[Uo,xi,li,fi].includes(n?.itemType)).sort((n,o)=>lp(n.itemValue).getTime()-lp(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 Uo:i=0;break;case fi:if(n.lastValue&&[Uo,li].includes(n.lastType)){let u=lp(o.itemValue).getTime()-lp(n.lastValue).getTime();i=n.milliseconds+u}else i=n.milliseconds;break;case xi:if([Uo,"SCHECULE.TIME.RESUME"].includes(n.lastType)){let u=lp(o.itemValue).getTime()-lp(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([Uo,li].includes(r.lastType)){let n=new Date().getTime()-lp(r.lastValue).getTime();r.milliseconds+=n}return{milliseconds:r.milliseconds,time:sF(r.milliseconds),relevantTimeItems:e}}function sF(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 BR({visibilityThreshold:t,timeStamp:e,schedule:r,matchUp:n}){let{itemValue:o,timeStamp:i}=vo({timeItems:n?.timeItems||[],itemType:Rf,visibilityThreshold:t});return!r||i&&e&&new Date(i).getTime()>new Date(e).getTime()?{courtOrder:o}:r}function HR({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===Uo&&s;return a&&(!i||r(a)<r(i))?a:i},void 0)?.itemValue}}function WR(t=1){return Z(0,t).map(Mt)}function Mt(){let t=[];for(let i=0;i<256;i++)t[i]=(i<16?"0":"")+i.toString(16);let e=Math.random()*4294967295|0,r=Math.random()*4294967295|0,n=Math.random()*4294967295|0,o=Math.random()*4294967295|0;return t[e&255]+t[e>>8&255]+t[e>>16&255]+t[e>>24&255]+"-"+t[r&255]+t[r>>8&255]+"-"+t[r>>16&15|64]+t[r>>24&255]+"-"+t[n&63|128]+t[n>>8&255]+"-"+t[n>>16&255]+t[n>>24&255]+t[o&255]+t[o>>8&255]+t[o>>16&255]+t[o>>24&255]}function pc(t){let{disableNotice:e,venue:r,context:n}=t;if(typeof r!="object")return{error:G};let o=Xr(t);r.venueId||(r.venueId=Mt());let i;for(let s of Object.values(o)){let a=aF({disableNotice:!0,tournamentRecord:s,context:n,venue:r});if(a?.error)return a;i=a.venue}return e||Tt({topic:ZI,payload:{venue:r}}),rt({...R,venue:i})}function aF({tournamentRecord:t,disableNotice:e,context:r,venue:n}){return t?n?(t.venues||(t.venues=[]),n.venueId||(n.venueId=Mt()),t.venues.reduce((i,s)=>i||s.venueId===n.venueId,void 0)?{error:Hy}:(r&&St({element:n,extension:{value:r,name:yE}}),t.venues.push(n),e||Tt({payload:{venue:n,tournamentId:t.tournamentId},topic:ZI}),{...R,venue:J(n)})):{error:et,info:"missing venue"}:{error:W}}function Qo({tournamentRecords:t,tournamentRecord:e,venueId:r}){if(!e)return{error:W};if(!r)return{error:Bo};let o=(e.venues??[]).reduce((i,s)=>s.venueId===r?s:i,void 0);if(!o&&t){let s=(qc({tournamentRecords:t}).linkedTournamentIds??[])[e.tournamentId];for(let a of s){let c=t[a],u=Qo({tournamentRecord:c,venueId:r});if(u.success&&u.venue)return pc({tournamentRecord:e,venue:u.venue}),{...R,venue:o}}}return o?{...R,venue:o}:{error:Ds}}function Th({convertExtensions:t,...e}){let{tournamentRecords:r,tournamentRecord:n,venueId:o}=e,i=Qo({tournamentRecords:r,tournamentRecord:n,venueId:o});return J(i,t,!0)}function ns({tournamentRecords:t,tournamentRecord:e,courtId:r}){if(!e)return{error:W};if(!r)return{error:Ni};let n="findCourt",o,i;if((e.venues??[]).forEach(s=>{(s.courts??[]).forEach(a=>{a.courtId===r&&(o=a,i=s)})}),o)return{...R,court:o,venue:i};if(t){let a=(qc({tournamentRecords:t}).linkedTournamentIds??[])[e.tournamentId];for(let c of a){let u=t[c],p=ns({tournamentRecord:u,courtId:r});if(p.success)return p.venue&&pc({tournamentRecord:e,venue:p.venue}),{...R,court:o,venue:i}}}return _({result:{error:Ka},stack:n})}function oU(t){return J(ns(t),!1,!0)}function Hm({tournamentRecord:t,internalUse:e,courtId:r}){if(!t)return{error:W};if(!r)return{error:Ni};let n=ns({tournamentRecord:t,courtId:r});if(n.error)return n;let o=n.court&&(({altitude:i,courtId:s,courtName:a,courtDimensions:c,latitude:u,longitude:p,surfaceCategory:m,surfaceType:d,surfacedDate:l,pace:f,notes:g})=>({altitude:i,courtId:s,courtName:a,courtDimensions:c,latitude:u,longitude:p,surfaceCategory:m,surfaceType:d,surfacedDate:l,pace:f,notes:g}))(n.court);return{...R,courtInfo:J(o,!1,e)}}function mc({tournamentRecord:t,venueId:e}){if(!t)return{error:W};if(!e)return{error:Bo};let r=Qo({tournamentRecord:t,venueId:e});if(r.error)return r;let o=(r.venue?.courts??[]).map(a=>(({courtInfo:c})=>({...c}))(Hm({courtId:a.courtId,internalUse:!0,tournamentRecord:t}))),i=r.venue&&(({venueId:a,venueName:c,venueAbbreviation:u})=>({venueAbbreviation:u,venueName:c,venueId:a}))(r.venue),s=i&&{...i,courtsInfo:o};return{...R,venueData:J(s,!1,!0)}}function jR({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===fi&&s;return a&&(!i||r(a)>r(i))?a:i},void 0)?.itemValue}}function Ht({event:t,eventId:e}){if(!t)return{error:Et};let n=mt({name:qr,element:t})?.extension,o=e?J(n?.value,!1,!0):n?.value;return e&&t.drawDefinitions?.forEach(i=>{o?.flights?.forEach(s=>{s.drawId===i.drawId&&Object.assign(s,{drawDefinition:i})})}),{flightProfile:o}}function We(t){let{tournamentRecord:e,eventId:r,drawId:n}=t,o="findEvent",i={},s=t.tournamentRecords??(e&&{[e.tournamentId]:e})??{},a=Object.values(s).map(({events:u,tournamentId:p})=>(u&&u.forEach(m=>{i[m.eventId]={tournamentId:p}}),u??[])).flat(),c;if(n){let u,p=a.find(m=>{let l=(m?.drawDefinitions??[]).find(f=>f.drawId===n);if(l)u=l,c=i[m.eventId].tournamentId;else{let g=(m&&Ht({event:m})?.flightProfile)?.flights?.find(I=>I.drawId===n);if(g)return c=i[m.eventId].tournamentId,{entries:g.drawEntries,drawName:g.drawName,tournamentId:c,drawId:n}}return l});if(p)return{event:p,drawDefinition:u,tournamentId:c}}if(r){let u=a.find(p=>p?.eventId===r);if(u)c=i[u.eventId].tournamentId;else return{event:void 0,drawDefinition:void 0,..._({result:{error:mr},stack:o})};return{event:u,drawDefinition:void 0,tournamentId:c}}return{event:void 0,drawDefinition:void 0,..._({result:{error:pr},context:{drawId:n,eventId:r},stack:o})}}function Wm(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:sr};if(o&&!p.matchUpType&&!t.matchUpType&&(e||i)&&p.drawId){let E=e?.drawDefinitions?.find(M=>M.drawId===p.drawId);!E&&i&&({drawDefinition:E,event:e}=We({tournamentRecord:i,drawId:p.drawId}));let U=p.structureId&&E?.structures?.find(({structureId:M})=>M===p.structureId);r=t.matchUpType||U?.matchUpType||E?.matchUpType||e?.eventType!==Fe&&e?.eventType}let{milliseconds:m,time:d}=VR({matchUp:p}),{startTime:l}=HR({matchUp:p}),{endTime:f}=jR({matchUp:p}),g,{visibilityThreshold:I,eventIds:h,drawIds:S}=n??{};if((!h||h.includes(p.eventId))&&(!S||S.includes(p.drawId))){let E={matchUp:p,visibilityThreshold:I},{allocatedCourts:U}=Ih(E),{scheduledTime:M}=vf(E),{scheduledDate:P}=rs(E),{venueId:N}=Sh(E),{courtId:C}=hh(E),{courtOrder:O}=BR(E),{timeModifiers:b}=xf(E),x,w,F,L,v,B=p.matchUpType??r;if(a&&M&&o&&B){let q={matchUpFormat:p.matchUpFormat??c,...a};({averageMinutes:w=0,recoveryMinutes:F=0,typeChangeRecoveryMinutes:L=0}=dp({timingDetails:q,eventType:B})),(w||F)&&(x=f?br($t(f),F):br(M,w+F)),L&&(v=f?br($t(f),L):br(M,w+L))}!P&&M&&(P=Ut(M));let H=Im({scheduledDate:P,scheduledTime:M}),j={},V=(i&&N&&mc({tournamentRecord:i,venueId:N}))?.venueData||{};N&&(j[N]=V);let{venueName:Y,venueAbbreviation:$,courtsInfo:k}=V,z=(C&&k?.find(q=>q.courtId===C))?.courtName;for(let q of U||[]){if(!i)break;q.venueId&&!j[q.venueid]&&(j[q.venueId]=mc({venueId:q.venueId,tournamentRecord:i})?.venueData);let nt=j[q.venueId];q.venueName=nt?.venueName;let Q=nt?.courtsInfo?.find(it=>it.courtId===q.courtId);q.courtName=Q?.courtName}g=rt({typeChangeTimeAfterRecovery:v,timeAfterRecovery:x,scheduledDate:P,scheduledTime:M,isoDateString:H,allocatedCourts:U,timeModifiers:b,venueAbbreviation:$,venueName:Y,venueId:N,courtOrder:O,courtName:z,courtId:C,typeChangeRecoveryMinutes:L,recoveryMinutes:F,averageMinutes:w,milliseconds:m,startTime:l,endTime:f,time:d})}else g=rt({milliseconds:m,startTime:l,endTime:f,time:d});let{scheduledDate:T}=rs({matchUp:p}),{scheduledTime:A}=vf({matchUp:p});if(s&&u?.displaySettings?.draws){let E=u.displaySettings.draws,U=(E?.[p.drawId]??E?.default)?.scheduleDetails;if(U){let M=(U.find(P=>T&&P.dates?.includes(T))??U.find(P=>!P.dates?.length))?.attributes;if(M){let P=Object.assign({},...Object.keys(g).map(N=>({[N]:!0})),M);g=bi({source:g,template:P})}}}let y=p.matchUpStatus&&ae.includes(p.matchUpStatus)&&(Ut(f)||Ut(T)||Ut(A))||void 0;return{schedule:g,endDate:y}}function Gs(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 fp({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 je({drawDefinition:t,structure:e,matchUp:r,event:n}){return{tieFormat:fp({item:r,drawDefinition:t,structure:e,event:n})||fp({item:e,drawDefinition:t,structure:e,event:n})||Gs(t)||Gs(n)}}function YR({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 Ah({groupedOrder:t,roundPositionsCount:e}){if(!t||t?.length<=e)return t;let n=Te(t,t.length/e).map(i=>i.reduce((s,a)=>s+a)),o=n.slice().sort(se);return n.map(i=>o.indexOf(i)+1)}function jm(t){if(!Array.isArray(t))return"";let e=t.filter(te);return e.length?pt([Math.min(...e),Math.max(...e)]).join("-"):""}function qR({drawDefinition:t,structureId:e,matchUpsMap:r}){if(!t)return{error:X};if(!e)return{error:hr};let{structure:n}=st({drawDefinition:t,structureId:e});if(n?.stage!==Ve)return{error:Di,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=Yo({structureId:m,matchUpsMap:r}),f=He({matchUps:d}).roundProfile;return{[m]:f}})),c=Yo({matchUpsMap:r,structureId:e}),{roundProfile:u}=He({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 y=D?T.length/D:0,E=T.length/y,U=T.slice(),M=Ah({roundPositionsCount:E,groupedOrder:g}),P=M?.length||1;if(P<=E){let b=T.length/P,x=Te(U,b);f===ai&&x.forEach(w=>w.reverse()),U=M?.length&&M?.map(w=>x[w-1]).flat()||U}let N=Te(U,y);if(I){let b=Z(0,I.interleave).map(()=>{}),x=Z(0,I.offset).map(()=>{});N=N.map(F=>[F,...b]),N.unshift(x),N=N.flat(1);let w=N.length-I.offset;N=N.slice(0,w)}p[h]||(p[h]={});let O=u?.[h]?.feedRound?2:1;N.forEach((b,x)=>{let w=1+x*O;p[h][w]||(p[h][w]=jm(b))})}),{sourceDrawPositionRanges:p}}function Ln({policyDefinitions:t,tournamentRecord:e,contextProfile:r,drawDefinition:n,event:o}){let i={policies:{}};if(!r)return i;let s=yo({tournamentRecord:e,drawDefinition:n,event:o}).policyDefinitions;if(r.withCompetitiveness){let a=t?.[ii]??s?.[ii]??km[ii];i.policies[ii]=a}return i}function $R({drawPositions:t,roundProfile:e,roundNumber:r}){let n=[void 0,void 0];if(PI(t))return{orderedDrawPositions:n,displayOrder:n};let o=e?.[r],s=o?.pairedDrawPositions?.find(c=>xe(c||[],t.filter(Boolean)))??n,a=o?.feedRound;if(UI(t)){let c=[...t].sort(se);return{orderedDrawPositions:c.length===2?c:s,displayOrder:a?c:s}}if(a){let u=[t.find(p=>!isNaN(ct(p))),void 0];return{orderedDrawPositions:u,displayOrder:u}}return{orderedDrawPositions:s,displayOrder:s}}function gp({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 tn({tournamentParticipants:t,tournamentRecord:e,participantIds:r}){let n="getPairedParticipant";if(!t&&!e)return{error:W};if(!Array.isArray(r)||r.length>2)return{error:zr};if(!r.length)return _({result:{error:lo},stack:n});t=t??e?.participants??[];let o=t.filter(a=>a.participantType===dt&&jt(r,a.individualParticipantIds).length===r.length&&a.individualParticipantIds.length===r.length),i=o[0];if(!i)return _({result:{error:Zt},stack:n});let s=J(o.slice(1),!1,!0);return{participant:J(i),duplicatedPairParticipants:s,...R}}function os({drawDefinition:t,participantId:e}){if(typeof t!="object")return{error:X};if(typeof e!="string")return{error:oe};let{extension:r}=mt({element:t,name:ho});return{lineUp:(r?.value||{})[e]}}function KR({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}=gp({collectionPosition:r,collectionId:s,lineUp:d});if(c===Gt){if(f?.length<=2){let I=o?.[f[0]]?.pairIdMap?.[f[1]],T=(I&&o[I]?.participant||tn({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||os({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||os({participantId:d,drawDefinition:i})?.lineUp;return u({attribute:m,lineUp:g,teamParticipant:f})}).filter(Boolean)||{};return{drawPositionCollectionAssignment:Object.assign({},...p)}}function yh({drawDefinition:t}){if(typeof t!="object")return{error:na};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,ce].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 zR({drawDefinition:t,roundProfile:e,structureId:r,matchUpsMap:n}){if(!t)return{error:X};if(!r)return{error:hr};if(!e){let c=Yo({matchUpsMap:n,structureId:r});if({roundProfile:e}=He({matchUps:c}),!e)return{error:et}}let i=(Math.min(...e?.[1]?.drawPositions??[])||1)-1,s=Object.keys(e);return{drawPositionsRanges:Object.assign({},...(s||[]).map(c=>{let u=e?.[c]?.matchUpsCount,p=e?.[1]?.drawPositions??[],m=Te(p,p.length/u),d=m.map(jm),l=m.map(S=>S.map(T=>T-i)).map(jm),f=s.map(S=>{if(S>c)return;let T=e?.[S]?.drawPositions??[];return Te(T,T.length/u)}).filter(Boolean),g=Z(0,u).map(S=>f.map(T=>T[S]).flat().filter(Boolean).sort(se)).map(S=>pt(S)),I=g.map(S=>jC(S).map(jm).join(", ")),h=Object.assign({},...Z(0,u).map(S=>({[S+1]:{firstRoundDrawPositionsRange:d[S],firstRoundOffsetDrawPositionsRange:l[S],possibleDrawPositions:g[S],drawPositionsRange:I[S]}})));return{[c]:h}}))}}function Ym({roundsNotPowerOf2:t,drawDefinition:e,structure:r,matchUps:n}){if(!r)return!1;n=n??r.matchUps??[],t=t??He({matchUps:n}).roundsNotPowerOf2;let o=!!r.positionAssignments?.find(({drawPosition:i})=>i)||!!n?.find(({drawPositions:i})=>i?.length);return(!e?.drawType||e.drawType!==Oi)&&!r?.structures&&t&&o}function fr({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 wf={[ua]:{policyName:"Round Naming Default",namingConventions:{round:"Round",pre:"Pre"},qualifyingFinishMap:{1:"Final"},abbreviatedRoundNamingMap:{1:"F",2:"SF",4:"QF"},roundNamingMap:{1:"Final",2:"Semifinal",4:"Quarterfinal"},affixes:{roundNumber:"R",preFeedRound:"Q",preQualifying:"P"},stageConstants:{[tt]:"",[ce]:"P",[at]:"Q",[Ve]:"C"}}},QR=wf;function XR({roundNamingPolicy:t,drawDefinition:e,structure:r,matchUps:n}){let{roundProfile:o,roundMatchUps:i}=He({matchUps:n}),{structureAbbreviation:s,stage:a}=r,c=fr({structure:r}),u=Ym({structure:r}),p=r.structures,m={},d=wf[ua],l=r.stage===at,f=l?Math.max(...(e?.structures??[]).filter(O=>O.stage===at).map(({stageSequence:O})=>O??1),0):0,g=(r.stageSequence??1)<f?r.stageSequence??1:"",I=g&&(t?.affixes?.preQualifying||d.affixes.preQualifying)||"",h=t?.roundNamingMap||d.roundNamingMap||{},S=t?.abbreviatedRoundNamingMap||d.abbreviatedRoundNamingMap||{},T=t?.affixes?.preFeedRound||d.affixes.preFeedRound,A=t?.affixes?.roundNumber||d.affixes.roundNumber,y=(t?.namingConventions||d.namingConventions).round,E=a&&a!==tt?a[0]:"",U=t?.stageConstants||d.stageConstants,M=a&&U?.[a]||E,P=`${I}${M}${g}`,N=o?Object.keys(o):[],C=l&&U?.[at]?`${U?.[at]}-`:"";if(p||c||u)Object.assign(m,...N.map(O=>{let b=`${C}${y} ${O}`,x=`${A}${O}`;return{[O]:{roundName:b,abbreviatedRoundName:x}}}));else{let O=l&&(t?.qualifyingFinishMap||d?.qualifyingFinishMap||{});Object.assign(m,...N.map(b=>{if(!o?.[b])return;let{matchUpsCount:x,preFeedRound:w}=o[b],F=x*2,L=O?.[o?.[b].finishingRound]||O&&`${A}${F}`||h[x]||`${A}${F}`,v=w?`-${T}`:"",B=`${L}${v}`,H=[P,s,B].filter(Boolean).join("-"),V=`${S[x]||`${A}${F}`}${v}`,Y=[P,s,V].filter(Boolean).join("-");return{[b]:{abbreviatedRoundName:Y,roundName:H}}}))}return{roundNamingProfile:m,roundProfile:o,roundMatchUps:i}}function qm(t){let e=lt(t,[{[fo]:!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===ht&&Xt||s===dt&&Gt||s===kt&&kt||void 0}return{matchUpType:n}}var cF="normal",iU="timed",uF="final",Lf="NOAD",$m="SET",JR={S:cF,F:uF};function tr(t){if(typeof t=="string"){let e=t.startsWith("T")&&iU||t.startsWith($m)&&$m||"";if(e===iU){let r=rb(t),n={simplified:!0,setFormat:r,bestOf:1};if(r)return n}if(e===$m)return pF(t)}}function pF(t){let e=t.split("-"),r=Ff(e[0].slice(3)),n=r===1||r%2!==0?r:void 0,o=r!==1&&r%2===0?r:void 0,i=e&&ZR(e[1]),s=e&&ZR(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 ZR(t){if(t?.[1]===":"){let e=t.split(":"),r=JR[e[0]],n=e[1];if(r&&n){if(n.startsWith("TB")){let I=tb(n);return I===!1?!1:typeof I=="object"?{tiebreakSet:I}:void 0}if(n.startsWith("T"))return rb(n);let s=t.match(/^[FS]:(\d+)([A-Za-z]*)/),a=s&&nb(s[2])||!1,c=!s?.[2]||a,u=s?Ff(s[1]):void 0,p=eb(n),m=p!==!1,d=m&&p||u,l=tb(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 eb(t,e=!0){let r=t?.indexOf("@")>0&&t.split("@");if(r)return(e?Ff(r[1]):r[1])||!1}function tb(t){if(t)if(t.startsWith("TB")){let e=eb(t,!1),r=t.match(/^TB(\d+)([A-Za-z]*)/),n=r?.[1],o=r&&nb(r[2]),i=!r?.[2]||o,s=Ff(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 rb(t){let e=t.slice(1),r=e.match(/^(\d+)(@?[A-Za-z]*)/),n=Ff(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 nb(t){return t&&t.indexOf(Lf)>=0}function Ff(t){return isNaN(Number(t))?0:Number(t)}function cu(t,e){return!Array.isArray(t)||!$e(e)?!1:jt(t,ph[e]).length}function Aa(t){let{matchUps:e,isCollectionMatchUp:r,excludeMatchUpStatuses:n,matchUpStatuses:o,hasWinningSide:i,matchUpFormats:s,roundPositions:a,matchUpFormat:c,collectionIds:u,isMatchUpTie:p,roundNumbers:m,matchUpIds:d,roundNames:l,stageSequences:f,scheduledDates:g,scheduledDate:I,participantIds:h,processContext:S,tournamentIds:T,matchUpTypes:A,structureIds:D,readyToScore:y,courtIds:E,eventIds:U,venueIds:M,drawIds:P,stages:N,filterMatchUpIds:C=!0,filterMatchUpTypes:O=!0}=t,b=Array.isArray(h)?h.filter(Boolean):[],x=Array.isArray(o)?o.filter(Boolean):[],w=Array.isArray(n)?n.filter(Boolean):[],F=Array.isArray(N)?N.filter(Boolean):[],L=Array.isArray(f)?f.filter(Boolean):[],v=Array.isArray(u)?u.filter(Boolean):[],B=Array.isArray(l)?l.filter(Boolean):[],H=Array.isArray(m)?m.filter(Boolean):[],j=Array.isArray(a)?a.filter(Boolean):[],V=Array.isArray(d)&&C?d.filter(Boolean):[],Y=Array.isArray(A)&&O?A.filter(Boolean):[],$=Array.isArray(E)?E.filter(Boolean):[],k=Array.isArray(M)?M.filter(Boolean):[],K=Array.isArray(s)&&s.filter(Boolean)||typeof c=="string"&&[c]||[],z=Array.isArray(g)&&g.filter(Boolean)||typeof I=="string"&&I.length&&[I]||[],q=Array.isArray(T)?T.filter(Boolean):[],nt=Array.isArray(U)?U.filter(Boolean):[],Q=Array.isArray(P)?P.filter(Boolean):[],it=Array.isArray(D)?D.filter(Boolean):[];return e.filter(ot=>{if(y&&!ie(ln)(ot)&&!ot.readyToScore||ot.winningSide&&i&&![1,2].includes(ot.winningSide)||p!==void 0&&(p&&!ot.tieMatchUps||!p&&ot.tieMatchUps)||r!==void 0&&(r&&!ot.collectionId||!r&&ot.collectionId)||F.length&&!F.includes(ot.stage)||L.length&&!L.includes(ot.stageSequence)||v.length&&(!ot.collectionId||!v.includes(ot.collectionId))||B.length&&(!ot.roundName||!B.includes(ot.roundName))||H.length&&(!ot.roundNumber||!H.includes(ot.roundNumber))||j.length&&(!ot.roundPosition||!j.includes(ot.roundPosition))||x.length&&(!ot.matchUpStatus||!x.includes(ot.matchUpStatus))||w.length&&ot.matchUpStatus&&w.includes(ot.matchUpStatus)||V.length&&!V.includes(ot.matchUpId)||Y.length&&(!ot.matchUpType||!cu(Y,ot.matchUpType))||K.length&&(!ot.matchUpFormat||!K.includes(ot.matchUpFormat)))return!1;if(z?.length){let{scheduledTime:ut}=vf({matchUp:ot}),{scheduledDate:Qt}=rs({matchUp:ot}),Me=Ut(ut)||Qt;if(!z.find(Ee=>_n(Ee,Me)))return!1}if($.length){let{courtId:ut}=hh({matchUp:ot}),{allocatedCourts:Qt}=Ih({matchUp:ot}),yt=Qt?.map(({courtId:Me})=>Me);if(!$.filter(Boolean).includes(ut)||yt?.includes(ut))return!1}if(k.length){let{venueId:ut}=Sh({matchUp:ot});if(!k.filter(Boolean).includes(ut))return!1}if(S){if(q.length&&!q.includes(ot.tournamentId)||nt.length&&!nt.includes(ot.eventId)||Q.length&&!Q.includes(ot.drawId)||it.length&&!it.includes(ot.structureId))return!1;if(b.length){let ut=ot.sides?.map(({participantId:yt})=>yt).filter(Boolean)??[];if(!b.some(yt=>ut.includes(yt)))return!1}}return!0})}function ob({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?mF({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 mF({displaySideNumber:t,seedAssignments:e,participantId:r,assignment:n,sideNumber:o}){let i={drawPosition:n.drawPosition,displaySideNumber:t,sideNumber:o};if(r){let s=dF({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 dF({seedAssignments:t,participantId:e}){return t?.find(r=>!r.seedProxy&&r.participantId===e)}var Fn="ANY",ee="MALE",_r="MIXED",ya="OTHER",ue="FEMALE",Km={ANY:Fn,MALE:ee,FEMALE:ue,MIXED:_r,OTHER:ya};function At({scheduleVisibilityFilters:t,tournamentAppliedPolicies:e,provisionalPositioning:r,tournamentParticipants:n,afterRecoveryTimes:o,policyDefinitions:i,tournamentRecord:s,seedAssignments:a,usePublishState:c,contextFilters:u,contextContent:p,matchUpFilters:m,participantMap:d,scheduleTiming:l,contextProfile:f,drawDefinition:g,publishStatus:I,context:h={},exitProfiles:S,matchUpsMap:T,structure:A,inContext:D,event:y}){let E={},U={};if(n=n??s?.participants,!A)return{collectionPositionMatchUps:E,error:Do,roundMatchUps:U,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):[],C=!h?.eventId||!M?.length&&!u?.eventIds?.filter(Boolean).length||M?.includes(h.eventId)||u?.eventIds?.includes(h.eventId),O=!P?.length||P.includes(A.structureId),b=!g||!N?.length||N.includes(g.drawId);if(!C||!O||!b)return{collectionPositionMatchUps:E,roundMatchUps:U,matchUps:[]};f&&!p&&(p=Ln({tournamentRecord:s,contextProfile:f,drawDefinition:g}));let{appliedPolicies:x}=Pt({drawDefinition:g}),w={...e,...x,...i},F=w?.scoring?.structures,L=A.stage&&F?.stage&&F?.stage[A.stage],v=A.stageSequence&&L?.stageSequence&&L.stageSequence[A.stageSequence],B=w?.scoring?.requireAllPositionsAssigned||L?.requireAllPositionsAssigned||v?.requireAllPositionsAssigned;T||(T=Ae({drawDefinition:g,structure:A}));let{positionAssignments:H,allPositionsAssigned:j}=de({structure:A}),V=!B||j,{seedAssignments:Y}=Fr({provisionalPositioning:r,drawDefinition:g,structure:A});a=a??Y;let{roundOffset:$,structureId:k,structureName:K,stage:z,stageSequence:q}=A,{drawId:nt,drawName:Q,drawType:it}=g??{};S=S||g&&yh({drawDefinition:g}).exitProfiles;let ot=S?.[k],ut=ot?.length&&(ot[0].split("-").map(wt=>parseInt(wt)).reduce((wt,Ue)=>wt+Ue)||0),Qt=!!A.structures,yt=Yo({matchUpsMap:T,structureId:k,inContext:D}),Me=w?.[ua],Ee=XR({roundNamingPolicy:Me,drawDefinition:g,structure:A,matchUps:yt}),{roundNamingProfile:Ce,roundProfile:Kt}=Ee;if(U=Ee?.roundMatchUps??[],m&&(yt=Aa({matchUps:yt,...m,filterMatchUpTypes:!1,filterMatchUpIds:!1})),D){let{sourceDrawPositionRanges:wt}=qR({drawDefinition:g,matchUpsMap:T,structureId:k}),Ue=g?zR({drawDefinition:g,roundProfile:Kt,matchUpsMap:T,structureId:k}).drawPositionsRanges:void 0;yt=yt.map(vt=>Re({scheduleVisibilityFilters:t,sourceDrawPositionRanges:wt,drawPositionsRanges:Ue,roundNamingProfile:Ce,initialRoundOfPlay:ut,appliedPolicies:w,usePublishState:c,publishStatus:I,isRoundRobin:Qt,roundProfile:Kt,matchUp:vt,event:y})),(yt?.filter(vt=>Array.isArray(vt.tieMatchUps))).forEach(vt=>{let ne=vt.tieMatchUps;yt=yt.concat(...ne)}),u&&(yt=Aa({processContext:!0,...u,matchUps:yt}))}else(yt?.filter(Ue=>Array.isArray(Ue.tieMatchUps))).forEach(Ue=>{let Ct=Ue.tieMatchUps;yt=yt.concat(...Ct)});return m&&(yt=Aa({matchUps:yt,...m,filterMatchUpTypes:!1,filterMatchUpIds:!1})),(m?.matchUpTypes||m?.matchUpIds)&&(yt=Aa({matchUpTypes:m.matchUpTypes,matchUpIds:m.matchUpIds,matchUps:yt})),(m?.matchUpTypes||m?.matchUpIds||D)&&(U=He({matchUps:yt}).roundMatchUps??[]),je({drawDefinition:g,structure:A,event:y})?.tieFormat&&({collectionPositionMatchUps:E}=YR({matchUps:yt})),{collectionPositionMatchUps:E,roundMatchUps:U,isRoundRobin:Qt,roundProfile:Kt,matchUpsMap:T,matchUps:yt};function Re({scheduleVisibilityFilters:wt,sourceDrawPositionRanges:Ue,drawPositionsRanges:Ct,initialRoundOfPlay:vt,additionalContext:ne,roundNamingProfile:qt,tieDrawPositions:pe,appliedPolicies:he,isCollectionBye:ur,usePublishState:_e,publishStatus:Wt,matchUpTieId:ve,isRoundRobin:nr,roundProfile:be,sideLineUps:Nr,matchUp:Se,event:Pe}){ne=ne??{};let gr=je({drawDefinition:g,structure:A,matchUp:Se,event:Pe})?.tieFormat,ri=gr?.collectionDefinitions,qe=Se.collectionId&&ri?.find(Qn=>Qn.collectionId===Se.collectionId),bn=Se.collectionId?qe?.matchUpFormat:Se.matchUpFormat??A?.matchUpFormat??g?.matchUpFormat??Pe?.matchUpFormat,Ei=Se.matchUpType||qe?.matchUpType||A?.matchUpType||g?.matchUpType||!ie(Fe)(Pe?.eventType)&&Pe?.eventType,Wi=ur?Dt:Se.matchUpStatus,{schedule:hn,endDate:wc}=Wm({scheduleVisibilityFilters:wt,afterRecoveryTimes:o,tournamentRecord:s,usePublishState:_e,scheduleTiming:l,matchUpFormat:bn,publishStatus:Wt,matchUpType:Ei,matchUp:Se,event:Pe}),ji=pe??Se.drawPositions??[],{collectionPosition:eI,collectionId:UC,roundPosition:rI}=Se,Yi=Se.roundNumber??ne.roundNumber,fw=UC?KR({tournamentParticipants:n,positionAssignments:H,collectionPosition:eI,drawDefinition:g,participantMap:d,drawPositions:ji,collectionId:UC,sideLineUps:Nr,matchUpType:Ei}):void 0,PC=qt?.[Yi]?.roundName||ne.roundName,DC=qt?.[Yi]?.abbreviatedRoundName||ne.abbreviatedRoundName,gw=be?.[Yi]?.feedRound,Iw=be?.[Yi]?.preFeedRound,hw=be?.[Yi]?.roundFactor,Sw=Ct?.[Yi],Tw=rI?Sw?.[rI]:void 0,Aw=Ue?.[Yi],yw=qe?.category?{...h?.category||{},...qe.category}:h?.category??Pe?.category,Ew=Se.processCodes?.length&&Se.processCodes||qe?.processCodes?.length&&qe?.processCodes||A?.processCodes?.length&&A?.processCodes||g?.processCodes?.length&&g?.processCodes||Pe?.processCodes?.length&&Pe?.processCodes||s?.processCodes,Uw=f?.withCompetitiveness&&su({...p,matchUp:Se}),Pw=Se.finishingPositionRange??ne.finishingPositionRange,nI=Qn=>rt(Qn,void 0,!0),Ir={...nI(h),...nI({matchUpFormat:Se.matchUpType===Fe?void 0:bn,tieFormat:Se.matchUpType!==Fe?void 0:gr,gender:qe?.gender??Pe?.gender,roundOfPlay:z!==at&&ft(vt)&&vt+(Yi||0),endDate:Se.endDate??wc,discipline:Pe?.discipline,category:yw,finishingPositionRange:Pw,abbreviatedRoundName:DC,drawPositionsRange:Tw,competitiveProfile:Uw,structureName:K,stageSequence:q,drawPositions:ji,matchUpStatus:Wi,processCodes:Ew,isRoundRobin:nr,matchUpTieId:ve,preFeedRound:Iw,matchUpType:Ei,roundFactor:hw,roundOffset:$,structureId:k,roundNumber:Yi,feedRound:gw,roundName:PC,drawName:Q,drawType:it,schedule:hn,drawId:nt,stage:z}),...J(nI(Se),!0,!0)};if(bn&&Se.score?.scoreStringSide1){let Qn=tr(bn),{bestOf:ea,finalSetFormat:As,setFormat:Tr}=Qn??{};(As?.tiebreakSet||Tr?.tiebreakSet||Tr?.timed)&&(Ir.score.sets=Ir.score.sets.sort((Hr,On)=>Hr.setNumber-On.setNumber).map((Hr,On)=>(On+1===ea?(As?.tiebreakSet||As?.timed)&&(Hr.tiebreakSet=!0):(Tr?.tiebreakSet||Tr?.timed)&&(Hr.tiebreakSet=!0),Hr)))}if(Array.isArray(ji)){let{orderedDrawPositions:Qn,displayOrder:ea}=$R({drawPositions:ji,roundProfile:be,roundNumber:Yi}),As=be?.[Yi]?.feedRound,Tr=ea[0]!==Qn[0],On=Qn.concat(void 0,void 0).slice(0,2).map((Ui,JA)=>{let oI=JA+1,Nw=Tr?3-oI:oI,Mw=ob({...fw,positionAssignments:H,displaySideNumber:Nw,seedAssignments:a,drawPosition:Ui,isFeedRound:As,sideNumber:oI}),Cw=Se.sides?.find(bw=>bw.sideNumber===oI),MC=rI?(rI-1)*2+JA+1:void 0,Rw=MC?Aw?.[MC]:void 0;return nI({sourceDrawPositionRange:Rw,...Cw,...Mw})});Object.assign(Ir,J({sides:On},!0,!0))}if(n&&Ir.sides){let Qn=he?.[Os],ea=Tr=>{let Hr=d?.[Tr]?.participant;return Hr&&bi({template:Qn?.participant,source:Hr})};if(Ir.sides.filter(Boolean).forEach(Tr=>{if(Tr.participantId){let Hr=J(ea(Tr.participantId)||n&&bo({policyDefinitions:he,participantId:Tr.participantId,tournamentParticipants:n,internalUse:!0,contextProfile:f}),void 0,!0);if(Hr){if(g?.entries){let On=g.entries.find(Ui=>Ui.participantId===Tr.participantId);On?.entryStatus&&(Hr.entryStatus=On.entryStatus),On?.entryStage&&(Hr.entryStage=On.entryStage)}Object.assign(Tr,{participant:Hr})}}if(Tr?.participant?.individualParticipantIds?.length&&!Tr.participant.individualParticipants?.length){let Hr=Tr.participant.individualParticipantIds.map(On=>ea(On)||n&&bo({policyDefinitions:he,tournamentParticipants:n,internalUse:!0,contextProfile:f,participantId:On}));Object.assign(Tr.participant,{individualParticipants:Hr})}}),!Ir.matchUpType){let{matchUpType:Tr}=qm({matchUp:Ir});Tr&&Object.assign(Ir,{matchUpType:Tr})}if(f?.inferGender&&(!Ir.gender||Ir.gender===_r)&&Ir.sides?.length===2&&Ir.matchUpType!==Fe){let Tr=Ir.sides.map(Hr=>{if(ie(Xt)(Ir.matchUpType))return Hr.participant?.person?.sex;if(Hr.participant?.individualParticipants?.length===2){let On=pt(Hr.participant.individualParticipants.map(Ui=>Ui.person?.sex)).filter(Boolean);if(On.length===1)return On[0]}});if(Tr.filter(Boolean).length===2&&pt(Tr).length===1){let Hr=Tr[0];Ir.inferredGender=Hr}}}if(Ir.tieMatchUps){let Qn=Ir.matchUpStatus===Dt,ea=Ir.sides?.map(({participant:As,drawPosition:Tr,sideNumber:Hr,lineUp:On})=>{let Ui=As?.participantType===Fe&&As;return{teamParticipant:Ui&&rt({participantRoleResponsibilities:Ui.participantRoleResponsibilities,participantOtherName:Ui.participanOthertName,participantName:Ui.participantName,participantId:Ui.participantId,teamId:Ui.teamId}),drawPosition:Tr,sideNumber:Hr,lineUp:On}});Ir.tieMatchUps=Ir.tieMatchUps.map(As=>{let Tr=Ir.matchUpId,On={finishingPositionRange:Ir.finishingPositionRange,abbreviatedRoundName:DC,roundNumber:Yi,roundName:PC};return Re({tieDrawPositions:ji,scheduleVisibilityFilters:wt,sourceDrawPositionRanges:Ue,sideLineUps:ea,drawPositionsRanges:Ct,initialRoundOfPlay:vt,roundNamingProfile:qt,additionalContext:On,appliedPolicies:he,isCollectionBye:Qn,usePublishState:_e,publishStatus:Wt,matchUpTieId:Tr,isRoundRobin:nr,roundProfile:be,matchUp:As,event:Pe})})}let NC=Ir.sides&&Ir.sides.filter(Qn=>Qn?.participantId).length===2,Dw=!Ir.winningSide;if(Object.assign(Ir,{readyToScore:V&&NC&&Dw,hasContext:!0}),NC){let{allParticipantsCheckedIn:Qn,checkedInParticipantIds:ea}=es({matchUp:Ir});Object.assign(Ir,{allParticipantsCheckedIn:Qn,checkedInParticipantIds:ea})}return Array.isArray(f?.exclude)&&f?.exclude.forEach(Qn=>delete Ir[Qn]),Ir}}function is({matchUp:t}){return t?ae.includes(t?.matchUpStatus)||t?.winningSide:!1}function uu({requireParticipants:t=!0,scheduleVisibilityFilters:e,tournamentAppliedPolicies:r,tournamentParticipants:n,afterRecoveryTimes:o,policyDefinitions:i,tournamentRecord:s,usePublishState:a,matchUpFilters:c,contextFilters:u,contextContent:p,participantMap:m,scheduleTiming:d,publishStatus:l,contextProfile:f,drawDefinition:g,exitProfiles:I,matchUpsMap:h,structureId:S,inContext:T,structure:A,context:D,event:y}){!A&&S&&({structure:A}=st({drawDefinition:g,structureId:S}));let E=At({tournamentAppliedPolicies:r,scheduleVisibilityFilters:e,tournamentParticipants:n,afterRecoveryTimes:o,policyDefinitions:i,tournamentRecord:s,usePublishState:a,matchUpFilters:c,contextFilters:u,contextContent:p,participantMap:m,scheduleTiming:d,publishStatus:l,contextProfile:f,drawDefinition:g,exitProfiles:I,matchUpsMap:h,structure:A,inContext:T,context:D,event:y}),U=[],M=[],P=[],N=[],C=[];if(E.error)return E;let{matchUps:O}=E,{assignedPositions:b}=de({structure:A}),x=b?.filter(F=>F.participantId).map(F=>F.drawPosition),w;return O.filter(F=>{let L=c?.matchUpTypes?.length===1&&c.matchUpTypes[0]===Bt;return!(F.matchUpType!==Bt&&L)}).forEach(F=>{if(F.matchUpStatus===$r){U.push(F);return}F.matchUpType===Bt&&(w=!0);let L=F.collectionId,v=L&&F.sides?.every(k=>k.participantId),B=!L&&F.drawPositions?.filter(Boolean).length===2,H=!L&&F.drawPositions?.every(k=>x?.includes(k)),j=b?.filter(k=>k.bye).map(k=>k.drawPosition),V=!L&&F.drawPositions?.find(k=>j?.includes(k)),$=$I.includes(F.matchUpStatus)&&(v||B&&(!t||H));return V?C.push(F):is({matchUp:F})?M.push(F):$?P.push(F):N.push(F)}),{includesTeamMatchUps:w,abandonedMatchUps:U,completedMatchUps:M,upcomingMatchUps:P,pendingMatchUps:N,byeMatchUps:C,structure:A}}function ib({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 Eh({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[oo,Yn].includes(o?.linkType)&&!o?.source?.roundNumber?_({result:{error:G},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 sb({structureMatchUps:t,matchUp:e}){let{roundNumber:r,roundPosition:n}=e,o=t.filter(s=>s.roundNumber===r&&!s.matchUpTieId),i=t.filter(s=>s.roundNumber===r+1&&!s.matchUpTieId);if(i.length){let s;return i.length===o.length?s=i.find(a=>a.roundPosition===n):i.length===o.length/2&&(s=i.find(a=>a.roundPosition===Math.ceil(n/2))),{matchUp:s}}return{message:"no progression found"}}function Uh({sourceRoundMatchUpCount:t,inContextDrawMatchUps:e,sourceRoundPosition:r,drawDefinition:n,targetLink:o}){if(!o)return{error:gl};let{target:{structureId:i,feedProfile:s,groupedOrder:a,roundNumber:c,positionInterleave:u}}=o,{structure:p}=st({drawDefinition:n,structureId:i}),{positionAssignments:m}=Nt({structure:p}),l=(e?.filter(P=>P.structureId===p?.structureId)).filter(P=>P.roundNumber===c&&!P.matchUpTieId),f=l.length,g=Z(1,f+1),I=f/t,h=Math.ceil(I*r),S=1-r%2;if(u?.interleave&&I!==.5){let P=u.offset+(r-1)*u.interleave,N=r+P;h=Math.ceil(N/2),S=1-N%2}let T=g,A=g[h-1],D=Ah({roundPositionsCount:g.length,groupedOrder:a}),y=D?.length||1;if(y<=g.length){let P=f/y,N=Te(g,P);s===ai&&N.forEach(C=>C.reverse()),T=D?.length&&D?.map(C=>N[C-1]).flat()||T}s===sn?A=T[h-1]:s===ai?((!D?.length||y>g.length)&&(h=l.length+1-h),A=T[h-1]):s===ip&&yr()&&console.log($u,{feedProfile:s});let E=A&&l.reduce((P,N)=>N.roundPosition===A?N:P,void 0),U;E?.feedRound?(S=0,U=Math.min(...(E.drawPositions||[]).filter(Boolean))):U=E?.drawPositions?.length===2&&E?.drawPositions[S];let M=m?.find(({drawPosition:P})=>P===U);if(M){let{extension:P}=mt({element:M,name:ym});if(P?.value)return{disabledDrawPosition:U}}return{matchUp:E,targetDrawPosition:U,matchUpDrawPositionIndex:S}}function er({inContextDrawMatchUps:t=[],useTargetMatchUpIds:e,inContextMatchUp:r,drawDefinition:n,matchUpId:o}){let i=r;t.length&&!i&&(i=t.find(c=>c.matchUpId===o));let{structure:s}=st({structureId:i?.structureId,drawDefinition:n});return s?.finishingPosition===_i?lF({inContextDrawMatchUps:t,useTargetMatchUpIds:e,drawDefinition:n,structure:s,matchUp:i}):fF({matchUp:i})}function lF({inContextDrawMatchUps:t,useTargetMatchUpIds:e,drawDefinition:r,structure:n,matchUp:o}){let{winnerMatchUpId:i,loserMatchUpId:s}=o,{links:a}=ib({roundNumber:o.roundNumber,structureId:n.structureId,drawDefinition:r}),c=a?.source,u=Eh({source:c,linkType:oo}),p=Eh({linkCondition:qn,linkType:Yn,source:c}),m=Eh({source:c,linkType:Yn}),d=p&&m;m||(m=p);let l=u?.target?.feedProfile,f=m?.target?.feedProfile,g=p?.target?.feedProfile,I,h,S,T,A,D,y,E,U,M;if(e&&(i||s)&&(y=i&&l!==Qr&&t.find(({matchUpId:C})=>C===i),T=s&&f!==Qr&&t.find(({matchUpId:C})=>C===s),y||T))return{matchUp:o,targetLinks:{loserTargetLink:m,winnerTargetLink:u},targetMatchUps:{loserMatchUp:T,winnerMatchUp:y}};let{roundPosition:P}=o;M=M||t.filter(C=>C.structureId===n.structureId);let N=M.reduce((C,O)=>O.roundNumber===o.roundNumber&&!O.matchUpTieId?C+1:C,0);return m&&!T&&f!==Qr&&({matchUpDrawPositionIndex:D,targetDrawPosition:A,matchUp:T}=Uh({targetLink:m,sourceRoundMatchUpCount:N,inContextDrawMatchUps:t,sourceRoundPosition:P,drawDefinition:r})),d&&g!==Qr&&({matchUpDrawPositionIndex:S,targetDrawPosition:h,matchUp:I}=Uh({targetLink:p,sourceRoundMatchUpCount:N,inContextDrawMatchUps:t,sourceRoundPosition:P,drawDefinition:r})),u&&!y&&l!==Qr&&({matchUpDrawPositionIndex:U,targetDrawPosition:E,matchUp:y}=Uh({targetLink:u,sourceRoundMatchUpCount:N,inContextDrawMatchUps:t,sourceRoundPosition:P,drawDefinition:r})),y||(M=M||t.filter(C=>C.structureId===n.structureId),{matchUp:y}=sb({structureMatchUps:M,matchUp:o})),rt({matchUp:o,targetLinks:{loserTargetLink:m,winnerTargetLink:u,byeTargetLink:p},targetMatchUps:{winnerMatchUpDrawPositionIndex:U,loserMatchUpDrawPositionIndex:D,byeMatchUpDrawPositionIndex:S,winnerTargetDrawPosition:E,loserTargetDrawPosition:A,byeTargetDrawPosition:h,winnerMatchUp:y,loserMatchUp:T,byeMatchUp:I},targetMatchUpIds:!!(i||s)})}function fF({matchUp:t}){return{targetLinks:{loserTargetLink:void 0,winnerTargetLink:void 0},targetMatchUps:{loserMatchUp:void 0,winnerMatchUp:void 0},matchUp:t}}function ab({drawDefinition:t,inContextDrawMatchUps:e}){let r={};return e.forEach(n=>{let{matchUpId:o,structureId:i,drawPositions:s=[]}=n,{structure:a}=st({drawDefinition:t,structureId:i});if(a?.finishingPosition===vs){let{roundNumber:c}=n,u=c&&ct(c)+1,p=a.matchUps??[],{roundMatchUps:m}=He({matchUps:p});if(u&&m?.[u]){let d=[...s].sort(se).map((l,f)=>{let g=m[u].find(I=>I.drawPositions?.includes(l));return{matchUpId:g?.matchUpId,roundNumber:u,schedule:g?.schedule,sideNumber:f+1,structureName:a.structureName}});Object.assign(n,{sidesTo:d})}}else{let c=er({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=sU({upcomingMatchUp:u}),d=sU({upcomingMatchUp:p});if(n.matchUpStatus!==Dt&&p?.matchUpStatus===Dt){let{matchUp:f}=cb({matchUp:p,drawDefinition:t,inContextDrawMatchUps:e})||{};d=f&&sU({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===qn,I=gF(n);if(I.length){let h=rf(u?.sides),S=rf(p?.sides),A=I.find(({participantId:E})=>h.includes(E))?[]:I,y=I.find(({participantId:E})=>S.includes(E))?[]:I;p&&g&&y.length<2&&y.push({bye:!0,tbd:!0}),A?.length&&u&&(!c.targetMatchUpIds&&u&&(u=e.find(({matchUpId:E})=>E===u.matchUpId)),u.potentialParticipants||(u.potentialParticipants=[]),u.potentialParticipants.push(A)),y?.length&&p&&(c.targetMatchUpIds||(u=e.find(({matchUpId:E})=>E===p.matchUpId)),p.potentialParticipants||(p.potentialParticipants=[]),p.potentialParticipants.push(y))}}}}),Object.keys(r).length&&e.forEach(n=>{Object.keys(r).includes(n.matchUpId)&&(n.schedule.scheduleConflict=r[n.matchUpId])}),{scheduleConflictMatchUpIds:r}}function gF(t){return t?.sides?.map(({participant:e,participantId:r,qualifier:n})=>e||r&&{participantId:r}||n&&{qualifier:n}).filter(Boolean)||[]}function cb({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===Dt){let s;return t.winnerMatchUpId?s=r.find(({matchUpId:a})=>a===t.winnerMatchUpId):{winnerMatchUp:s}=er({inContextDrawMatchUps:r,drawDefinition:e,matchUpId:n})?.targetMatchUps||{},cb({matchUp:s,drawDefinition:e,inContextDrawMatchUps:r})}return{matchUp:void 0}}function sU(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=Vs(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 Vs(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:A,context:D,event:y}=t,E=[],U=[],M=[],P=[],N=[];h&&!r&&(r=Ln({policyDefinitions:u,tournamentRecord:p,contextProfile:h,event:y}));let C;!e?.length&&p&&(e=p?.participants,(A||a?.withGroupings)&&e?.length&&({participantsWithGroupings:e,groupInfo:C}=xm({participants:e,participantsProfile:a})));let{structures:O}=xn({drawDefinition:S});if(!O)return{error:Lt};n||(n=Ae({drawDefinition:S}));let b=S&&yh({drawDefinition:S}).exitProfiles;O.forEach(F=>{let{byeMatchUps:L=[],pendingMatchUps:v=[],upcomingMatchUps:B=[],completedMatchUps:H=[],abandonedMatchUps:j=[]}=uu({matchUpFilters:T?void 0:l,contextFilters:T?void 0:d,inContext:A||T||d,tournamentAppliedPolicies:i,scheduleVisibilityFilters:o,tournamentParticipants:e,requireParticipants:s,afterRecoveryTimes:c,policyDefinitions:u,tournamentRecord:p,usePublishState:m,contextContent:r,participantMap:g,scheduleTiming:f,publishStatus:I,contextProfile:h,drawDefinition:S,exitProfiles:b,matchUpsMap:n,structure:F,context:D,event:y});E=E.concat(...j),U=U.concat(...H),M=M.concat(...B),P=P.concat(...v),N=N.concat(...L)});let x=F=>(!l&&!T&&!d||(l&&(F=Aa({matchUps:F,...l})),d&&(F=Aa({matchUps:F,...d,processContext:!0}))),F),w={abandonedMatchUps:x(E),completedMatchUps:x(U),upcomingMatchUps:x(M),pendingMatchUps:x(P),byeMatchUps:x(N),matchUpsMap:n,...R,groupInfo:C};if(T){let F=typeof T=="object"||{abandoned:!0,completed:!0,upcoming:!0,pending:!0,bye:!0},{abandoned:L,completed:v,upcoming:B,pending:H,bye:j}=F,V=[].concat(...L&&E||[],...v&&U||[],...B&&M||[],...H&&P||[],...j&&N||[]);ab({inContextDrawMatchUps:V,drawDefinition:S})}return w}function wi({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??[];ha({matchUps:i})}return(t??[]).filter(({collectionId:i})=>!i).forEach(i=>{let{matchUpId:s,structureId:a}=i,c=er({inContextDrawMatchUps:t,drawDefinition:e,matchUpId:s}),{winnerMatchUp:u,loserMatchUp:p}=c.targetMatchUps,m=u?.matchUpId,d=p?.matchUpId,f=Yo({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 aU(t){return t&&typeof String.fromCodePoint<"u"?t.toUpperCase().replace(/./g,e=>String.fromCodePoint(e.charCodeAt(0)+127397)):t}function ub(t){let e=Object.assign({},...Xo.filter(r=>r.ioc).map(r=>({[r.ioc]:r.iso})));return aU(e[t])}var Xo=[{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 Ph({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=Xo.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 pb({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?bi({template:e,source:s}):s)}}}}function xo(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:Zt}}function Gn({returnPreviousValues:t,itemSubTypes:e,itemType:r,element:n}){if(!n)return{error:et,info:Sm};if(e&&!Array.isArray(e))return{error:G,context:{itemSubTypes:e}};if(!Array.isArray(n.timeItems))return{error:_l};let o=n.timeItems.filter(s=>s?.itemType===r).filter(s=>!e?.length||e.some(a=>s?.itemSubTypes?.includes(a))).sort((s,a)=>{let c=new Date(s.createdAt||void 0).getTime(),u=new Date(a.createdAt||void 0).getTime();return c-u}),i=o.pop();if(i){let s={timeItem:i,...R};return t&&Object.assign(s,{previousItems:o}),s}else return{info:Ke}}function Dh({returnPreviousValues:t,drawDefinition:e,itemSubTypes:r,itemType:n}){if(!e)return{error:Wr};if(!e.timeItems)return{info:Ke};let{timeItem:o,previousItems:i,info:s}=Gn({element:e,returnPreviousValues:t,itemSubTypes:r,itemType:n});return o&&{timeItem:o,previousItems:i}||{info:s}}function pu({returnPreviousValues:t,itemSubTypes:e,itemType:r,event:n}){if(!n)return{error:Et};if(!n.timeItems)return{info:Ke};let{timeItem:o,previousItems:i,info:s}=Gn({returnPreviousValues:t,element:n,itemSubTypes:e,itemType:r});return o&&{timeItem:o,previousItems:i}||{info:s}}function mu({returnPreviousValues:t,tournamentRecord:e,itemSubTypes:r,itemType:n}){if(!e)return{error:W};if(!e.timeItems)return{info:Ke};let{timeItem:o,previousItems:i,info:s}=Gn({element:e,returnPreviousValues:t,itemSubTypes:r,itemType:n});return o&&{timeItem:o,previousItems:i}||{info:s}}function Nh({returnPreviousValues:t,tournamentRecord:e,participantId:r,itemSubTypes:n,itemType:o}){if(!e)return{error:W};if(!r)return{error:oe};let i=xo({tournamentRecord:e,participantId:r});if(i.error)return i;let{participant:s}=i;if(!s?.timeItems)return{info:Ke};let{timeItem:a,previousItems:c,info:u}=Gn({element:i.participant,returnPreviousValues:t,itemSubTypes:n,itemType:o});return a&&{timeItem:a,previousItems:c}||{info:u}}var IF={[Ar]:"groupParticipantIds",[dt]:"pairParticipantIds",[kt]:"teamParticipantIds"},hF={[Ar]:"groups",[kt]:"teams"};function Mh({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&&AF({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&&TF({individualParticipantIds:d,participantCopy:p,participantMap:c,participantType:l,participantId:m}),n&&(c[m].participant.signedIn=SF(p)),o){let{ratings:f,rankings:g,seedings:I}=aa({participant:p});c[m].participant.seedings=I,c[m].participant.rankings=g,c[m].participant.ratings=f}(a||s)&&Ph({participant:c[m].participant,withISO2:s,withIOC:a})}if(t){let u=Rt(t)?t:void 0;pb({participantMap:c,template:u})}return{participantMap:c}}function SF(t){let{timeItem:e}=Gn({itemType:ic,element:t});return e?.itemValue===ru}function TF({individualParticipantIds:t,participantCopy:e,participantMap:r,participantType:n,participantId:o}){for(let i of t){let s=r[i].participant;if(s[IF[n]].push(o),[kt,Ar].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===dt){let a=t.find(c=>c!==i);r[i].pairIdMap[o]=a,r[i].pairIdMap[a]=o}}}function AF({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:{[Xt]:{...r},[Gt]:{...r},[kt]:{...r},...r}}}function Ii({participantsProfile:t,useParticipantMap:e,tournamentRecord:r,contextProfile:n,inContext:o}){if(e)return{participantMap:Mh({...t,...n,tournamentRecord:r})?.participantMap};let i=J(r.participants,!1,!0)||[];(t?.withIOC||t?.withISO2)&&i.forEach(a=>Ph({participant:a,...t}));let s;if((o||t?.withGroupings)&&i?.length&&({participantsWithGroupings:i,groupInfo:s}=xm({participantsProfile:t,deepCopy:!1,participants:i})),t?.withScaleValues&&i?.length)for(let a of i){let{ratings:c,rankings:u}=aa({participant:a});a.rankings=u,a.ratings=c}return{participants:i,groupInfo:s}}function co(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:Et};let{eventId:S,eventName:T,endDate:A,eventType:D,category:y,gender:E,matchUpFormat:U}=h??{},M={...I,...rt({indoorOutDoor:h.indoorOutdoor??p?.indoorOutdoor,surfaceCategory:h.surfaceCategory??p?.surfaceCategory,endDate:h.endDate??p?.endDate,tournamentId:p?.tournamentId,matchUpFormat:U,eventName:T,eventType:D,category:y,eventId:S,gender:E})};A&&(M.endDate=A),d&&!r&&(r=Ln({policyDefinitions:c,tournamentRecord:p,contextProfile:d,event:h}));let P;if(!e?.length&&!n&&p){let b=Ii({participantsProfile:s,useParticipantMap:u,policyDefinitions:c,tournamentRecord:p,contextProfile:d,inContext:g});n=b.participantMap,e=b.participants??[],P=b.groupInfo}let N=h.drawDefinitions??[],C=Sa({tournamentRecord:p,event:h}).scheduleTiming;return{matchUps:N.flatMap(b=>{let{matchUps:x}=re({tournamentParticipants:e,tournamentAppliedPolicies:i,scheduleVisibilityFilters:o,context:M,participantsProfile:s,afterRecoveryTimes:a,policyDefinitions:c,tournamentRecord:p,contextFilters:m,contextProfile:d,drawDefinition:b,contextContent:r,matchUpFilters:l,participantMap:n,scheduleTiming:C,nextMatchUps:f,inContext:g,event:h});return x??[]}),groupInfo:P}}function le(t){let e=lt(t,[{tournamentRecord:!0}]);if(e.error)return e;if(!t?.tournamentRecord)return{error:W};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}=Ii({participantsProfile:i,useParticipantMap:a,policyDefinitions:c,tournamentRecord:u,contextProfile:m,inContext:p}));let{appliedPolicies:S}=Pt({tournamentRecord:u}),T={...g,tournamentId:I,indoorOutDoor:u.indoorOutdoor,surfaceCategory:u.surfaceCategory,endDate:u.endDate},A=Ln({policyDefinitions:c,tournamentRecord:u,contextProfile:m});return{matchUps:h.flatMap(y=>(T.eventDrawsCount=y.drawDefinitions?.length??0,co({context:T,scheduleVisibilityFilters:o,tournamentAppliedPolicies:S,participantsProfile:i,afterRecoveryTimes:s,policyDefinitions:c,tournamentRecord:u,contextContent:A,contextFilters:l,contextProfile:m,matchUpFilters:d,participantMap:r,nextMatchUps:f,participants:n,inContext:p,event:y}).matchUps??[])).concat(...u.matchUps??[])}}function cn({scheduleVisibilityFilters:t,afterRecoveryTimes:e,participantsProfile:r,tournamentRecords:n,policyDefinitions:o,matchUpFilters:i,contextFilters:s,nextMatchUps:a,inContext:c}){return typeof n!="object"||!Object.keys(n).length?{error:Ft}:{matchUps:Object.keys(n).map(m=>{let d=n[m];return le({scheduleVisibilityFilters:t,afterRecoveryTimes:e,participantsProfile:r,policyDefinitions:o,tournamentRecord:d,matchUpFilters:i,contextFilters:s,nextMatchUps:a,inContext:c}).matchUps??[]}).flat()}}function hi(t,e){return yF(t,e)||(t?.stageSequence||0)-(e?.stageSequence||0)||t?.roundNumber&&e.roundNumber&&t?.roundNumber-e?.roundNumber||(t?.roundPosition??0)-(e?.roundPosition??0)}function yF(t,e){return(_s[t?.stage]||0)-(_s[e?.stage]||0)}function rr(t){let{participants:e,participantMap:r,contextContent:n}=t,{scheduleVisibilityFilters:o,tournamentAppliedPolicies:i,participantsProfile:s,afterRecoveryTimes:a,policyDefinitions:c,useParticipantMap:u,tournamentRecord:p,matchUpFilters:m,contextFilters:d,contextProfile:l,drawDefinition:f,nextMatchUps:g,inContext:I,context:h,event:S}=t,{eventId:T,eventName:A,endDate:D,eventType:y,category:E,gender:U,matchUpFormat:M}=S??{},P={...h,surfaceCategory:S?.surfaceCategory??p?.surfaceCategory,indoorOutDoor:S?.indoorOutdoor??p?.indoorOutdoor,matchUpFormat:M,eventType:y,eventName:A,category:E,eventId:T,endDate:D,gender:U},N;return!e?.length&&!r&&p&&({participants:e=[],participantMap:r,groupInfo:N}=Ii({participantsProfile:s,useParticipantMap:u,policyDefinitions:c,tournamentRecord:p,contextProfile:l,inContext:I})),l&&!n&&(n=Ln({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 Vr(t){let e=Xr(t),r=t.matchUps??[],n=t.drawIds??[],{includeParticipantDependencies:o,tournamentRecord:i,drawDefinition:s}=t;if(!Array.isArray(r))return{error:Sn};if(!Array.isArray(n))return{error:Wr};let a=t.matchUpIds?.length?t.matchUpIds:r.map(T=>T.matchUpId);if(!Array.isArray(a))return{error:ia};let c={},u={},p={},m={};i&&!Object.keys(e).length&&(e={[i.tournamentId]:i});let d=Object.values(e),f=d.reduce((T,A)=>T.concat(A.events??[]).map(D=>(D.drawDefinitions||[]).map(y=>y.links||[])).flat(1/0),[]).filter(({linkType:T})=>T===jn),g=r;if(f.length){g=cn({nextMatchUps:!0,tournamentRecords:e}).matchUps;let T=f.reduce((A,D)=>{let y=D.source?.structureId,E=D.target?.structureId;return y&&E&&(p[E]=y),y&&!A.includes(y)&&A.push(y),A},[]);for(let A of T)c[A]=[];for(let A of g??[]){let D=A.containerStructureId||A.structureId;T.includes(D)&&c[D].push(A.matchUpId)}}let I=T=>{u[T]||(u[T]={dependentMatchUpIds:[],participantIds:[],matchUpIds:[],sources:[]},m[T]=[])},h=(T,A)=>{u[T].matchUpIds.forEach(y=>{u[A].matchUpIds.push(y)}),u[A].matchUpIds.push(T),u[T].dependentMatchUpIds.push(A),o&&u[T].participantIds.forEach(y=>u[A].participantIds.push(y))},S=T=>{let A=Object.keys(c).length;for(let D of T||[]){let{matchUpId:y,winnerMatchUpId:E,loserMatchUpId:U}=D;if(!a.length||a.includes(y)){if(I(y),o){let{individualParticipantIds:N}=eu(D);u[y].participantIds=N}E&&(I(E),h(y,E),m[E].push(y)),U&&(I(U),h(y,U),m[U].push(y)),u[y].sources.push(m[y]);let M=m[y].map(N=>u[N].sources[0]).flat(),P=m[y].map(N=>u[N].sources[1]).flat();if(u[y].sources.push(M,P),A){let N=D.containerStructureId||D.structureId,C=p[N];if(c[C])for(let O of c[C])I(O),h(O,y),m[O].push(y)}}}};if(s)wi({drawDefinition:s}),g?.length||(g=rr({drawDefinition:s}).matchUps),S(g);else{if(g?.length||(g=cn({nextMatchUps:!0,tournamentRecords:e}).matchUps),!n.length){let T=d?.length?d.map(({events:A=[]})=>A.map(({drawDefinitions:D=[]})=>D.map(({drawId:y})=>y))).flat(1/0):[];T&&(n=T)}for(let T of n){let A=g?.filter(y=>y.drawId===T).sort(hi);if(!A?.find(({roundPosition:y})=>!y)){let y=A?.find(({tournamentId:U})=>U),{drawDefinition:E}=We({tournamentRecord:e[y?.tournamentId],drawId:T});E&&wi({drawDefinition:E})}S(A)}}return{positionDependencies:c,matchUpDependencies:u,sourceMatchUpIds:m,matchUps:g,...R}}function Ie(t){let e=t?.matchUp,r=t?.score||e?.score,n=r?.sets?.[0],{side1Score:o,side2Score:i,side1TiebreakScore:s,side2TiebreakScore:a,side1PointScore:c,side2PointScore:u}=n||{},p=o||i||s||a||c||u;return!!(r?.sets?.length>1||p)}function Ea({matchUpStatus:t}){return YI.includes(t)}function mb({matchUpStatus:t}){return Nm.includes(t)}function Gf({matchUpStatus:t}){return qI.includes(t)}function kf({matchUpStatus:t,winningSide:e,tieMatchUps:r,sides:n,score:o}){let i=n?.find(({participantId:c})=>c),s=r?.filter(kf)?.length;return Ie({score:o})||s||e&&i||t&&mb({matchUpStatus:t})&&![Ot,_t,Dn].includes(t)}function Ua(t){let{drawDefinition:e,findContainer:r,structureId:n,event:o}=t,i=t.structure,s={isCollectionMatchUp:!1},{containedStructures:a}=Ji({drawDefinition:e}),c=n?a[n]||[]:[];if(!i){let E=st({drawDefinition:e,structureId:n});if(E.error)return E;i=r?E.containingStructure??E.structure:E.structure}if(fr({structure:i}))return{structure:i,isAdHoc:!0,error:ys};let{matchUps:u}=re({inContext:!0,matchUpFilters:s,drawDefinition:e,event:o}),p=u?.filter(E=>E.structureId===n||c.includes(E.structureId)),{matchUpDependencies:m}=Vr({drawIds:[e.drawId],matchUps:u,drawDefinition:e}),d=[],l=[],f={},g=[];for(let E of u??[]){if(E.structureId===n||c.includes(E.structureId)){l.push(...E.drawPositions??[]);let U=E.roundNumber;for(let M of(E.drawPositions??[]).filter(Boolean))(!f[M]||U&&f[M]>U)&&(f[M]=U)}kf(E)&&(g.push(E),d.push(E.matchUpId,...m?.[E?.matchUpId]?.matchUpIds||[]))}let I=pt(l.filter(Boolean)).sort(se),h=pt(d),S=pt(p?.map(({matchUpId:E,drawPositions:U})=>h.includes(E)?U:[]).flat().filter(Boolean)).sort(se),{positionAssignments:T}=Nt({drawDefinition:e,structure:i}),A=T?.filter(E=>E.bye).map(E=>E.drawPosition),D=T?.filter(E=>E.qualifier).map(E=>E.drawPosition),y=I?.filter(E=>!S.includes(E))||[];return{allDrawPositions:I,inContextStructureMatchUps:p,drawPositionInitialRounds:f,activeDependentMatchUpIds:h,qualifyingDrawPositions:D,inactiveDrawPositions:y,positionAssignments:T,activeDrawPositions:S,byeDrawPositions:A,activeMatchUps:g,structure:i}}function ss({drawPosition:t,matchUps:e=[]}){return{initialRoundNumber:e.filter(({drawPositions:n})=>t&&n?.includes(t)).map(({roundNumber:n})=>n).sort(se)[0]}}var Pa={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 Ch=[];function kn(t,e){typeof t=="string"&&(t={method:t}),(e||yr())&&Ch.push(t)}function EF(t){let e=Ch.slice();return t&&(Ch.length=0),e}function db(t){let r=EF(t).map(n=>{let{color:o,keyColors:i,method:s,newline:a}=n,c=Object.keys(Pa).includes(o)?Pa[o]:Pa.cyan,p=Object.keys(n).filter(d=>!["color","keyColors","method","newline"].includes(d)).map(d=>{let l=i&&Object.keys(i).includes(d)&&Pa[i[d]]?Pa[i[d]]:Pa.brightwhite;return`${Pa.white}${d}: ${l}${n[d]}`}).join(", "),m=s?.length<15?" ":" ";return[a?`
|
|
1
|
+
var Ow=Object.defineProperty;var Jt=(t,e)=>{for(var r in e)Ow(t,r,{get:e[r],enumerable:!0})};function Va(){return"2.0.29"}var $A={};Jt($A,{competitionGovernor:()=>CE,drawsGovernor:()=>ZD,entriesGovernor:()=>sN,eventGovernor:()=>TN,generationGovernor:()=>PN,matchUpFormatGovernor:()=>iA,matchUpGovernor:()=>jN,mocksGovernor:()=>$g,participantGovernor:()=>TM,policyGovernor:()=>OD,publishingGovernor:()=>NM,queryGovernor:()=>XD,reportGovernor:()=>MM,scheduleGovernor:()=>kM,scoreGovernor:()=>yg,tieFormatGovernor:()=>zM,tournamentGovernor:()=>oC,venueGovernor:()=>fC});var CE={};Jt(CE,{getLinkedTournamentIds:()=>qc,getTournamentIds:()=>np,linkTournaments:()=>UE,mutate:()=>NE,query:()=>ME,unlinkTournament:()=>DE,unlinkTournaments:()=>PE});var NE={};Jt(NE,{linkTournaments:()=>UE,unlinkTournament:()=>DE,unlinkTournaments:()=>PE});var QC={};Jt(QC,{addNotice:()=>Tt,callListener:()=>um,createInstanceState:()=>pE,cycleMutationStatus:()=>Bl,deepCopyEnabled:()=>Vl,deleteNotice:()=>NI,deleteNotices:()=>Ci,disableNotifications:()=>mE,enableNotifications:()=>kl,getDevContext:()=>yr,getMethods:()=>Hl,getNotices:()=>DI,getProvider:()=>MI,getTopics:()=>Cr,getTournamentId:()=>$i,getTournamentRecord:()=>Wl,getTournamentRecords:()=>Mo,globalLog:()=>fE,handleCaughtError:()=>Xu,removeTournamentRecord:()=>lE,setDeepCopy:()=>Vc,setDevContext:()=>kc,setGlobalLog:()=>$C,setGlobalMethods:()=>KC,setGlobalSubscriptions:()=>pL,setMethods:()=>zC,setStateMethods:()=>gE,setStateProvider:()=>cL,setSubscriptions:()=>mL,setTournamentId:()=>Qu,setTournamentRecord:()=>dE,setTournamentRecords:()=>pm,timeKeeper:()=>uL});function Mr(t){return typeof t=="function"}function $e(t){return typeof t=="string"}function Rt(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function CC(t,e){if(!Rt(t)||!Rt(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 sI(t,e){return Array.isArray(t)?Object.assign({},...(t??[]).filter(Rt).map(r=>r[e]&&{[r[e]]:r}).filter(Boolean)):{}}var RC=t=>e=>Object.keys(t).every(r=>e[r]===t[r]);function iI(t,e){if(t===void 0)return null;if(typeof t!="object"||t===null)return t;let r=Object.keys(t),n=o=>o===void 0?null:o;return Object.assign({},...r.map(o=>Array.isArray(t[o])?{[o]:e?t[o]:t[o].map(i=>iI(i))}:{[o]:e?n(t[o]):iI(t[o])}))}function ZA(t){return Array.isArray(t)?t.length+t.map(ZA).reduce((e,r)=>e+r,0):typeof t=="object"&&t!==null?Object.keys(t).length+Object.keys(t).map(e=>ZA(t[e])).reduce((e,r)=>e+r,0):0}function bC(t){if(t===null||typeof t!="object")return;let e=JSON.stringify(t),r=ZA(t),n=e.split("").reduce((o,i)=>o+i.charCodeAt(0),0);return[e.length,r,n].map(o=>o.toString(36)).join("")}var R={success:!0},_w="error",OC={SUCCESS:R,ERROR:_w};var aI={message:"Chronological error; time violation.",code:"ANACHRONISM"},ty={message:"Cannot remove main structure",code:"ERR_CANNOT_REMOVE_MAIN_STRUCTURE"},cI={message:"records must be an object with tournamentId keys",code:"ERR_INVALID_TOURNAMENTS"},Ft={message:"Missing tournamentRecords",code:"ERR_MISSING_TOURNAMENTS"},W={message:"Missing tournamentRecord",code:"ERR_MISSING_TOURNAMENT"},Ba={message:"Invalid tournamentRecord",code:"ERR_INVALID_TOURNAMENT"},ra={message:"Missing tournamentId",code:"ERR_MISSING_TOURNAMENT_ID"},na={message:"Invalid drawDefinition",code:"ERR_INVALID_DRAWDEF"},X={message:"Missing drawDefinition",code:"ERR_MISSING_DRAWDEF"},ey={message:"Existing drawDefinition(s)",code:"ERR_EXISTING_DRAWDEFS"},pr={message:"drawDefinition not found",code:"ERR_NOT_FOUND_DRAWDEF"},Pi={message:"Invalid structure",code:"ERR_INVALID_STRUCTURE"},dl={message:"Incomplete source structure",code:"ERR_INCOMPLETE_STRUCTURE"},ll={message:"Invalid drawPosition for seedAssignment",code:"ERR_INVALID_SEEDING_POSITION"},Ha={message:"drawPosition already assigned",code:"ERR_EXISTING_POSITION_ASSIGNMENT"},ry={message:"Schedule not cleared",code:"ERR_UNCHANGED_SCHEDULE_NOT_CLEARED"},ny={message:"drawPosition not cleared",code:"ERR_FAILURE_POSITION_NOT_CLEARED"},vw={message:"drawPosition not found",code:"ERR_NOT_FOUND_DRAW_POSITION"},fl={message:"Unrecognized drawType",code:"ERR_UNRECOGNIZED_DRAW_TYPE"},Wa={message:"Missing drawPositions",code:"ERR_MISSING_DRAW_POSITIONS"},ku={message:"drawPosition is active",code:"ERR_ACTIVE_DRAW_POSITION"},ys={message:"Invlid drawPosition",code:"ERR_INVALID_DRAW_POSITION"},Es={message:"Missing drawPosition",code:"ERR_MISSING_DRAW_POSITION"},nm={message:"Invalid drawType",code:"ERR_INVALID_DRAW_TYPE"},Vu={message:"Invalid drawSize",code:"ERR_INVALID_DRAW_SIZE"},uI={message:"Cannot set drawSize to be less than existing entries",code:"ERR_INVALID_DRAW_SIZE_MISMATCH"},ja={message:"Missing drawSize",code:"ERR_MISSING_DRAW_SIZE"},Wr={message:"Missing drawId",code:"ERR_MISSING_DRAW_ID"},oy={message:"drawId exists",code:"ERR_EXISTING_DRAW_ID"},iy={message:"participantId cannot be assigned to multiple seedNumbers",code:"INVALID_PARTICIPANT_SEEDING"},sy={message:"seedsCount greater than drawSize",code:"ERR_INVALID_SEED_COUNT"},ay={message:"Missing seedCountThresholds",code:"ERR_MISSING_SEED_COUNT_THRESHOLD"},cy={message:"Invalid action",code:"ERR_INVALID_ACTION"},pI={message:"Invalid assignment",code:"ERR_INVALID_ASSIGNMENT"},uy={message:"Missing seedAssignments",code:"ERR_MISSING_SEED_ASSIGNMENTS"},py={message:"Invalid seedNumber",code:"ERR_INVALID_SEED_NUMBER"},my={message:"Invalid seedPosition",code:"ERR_INVALID_SEED_POSITION"},gl={message:"Missing targetLink",code:"ERR_MISSING_LINK_TARGET"},dy={message:"Existing round",code:"ERR_EXISTING_ROUND"},xw={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"},Il={message:"Missing structures",code:"ERR_MISSING_STRUCTURES"},Do={message:"Missing structure",code:"ERR_MISSING_STRUCTURE"},ly={message:"drawDefinition contains unlinked structures",code:"ERR_MISSING_STRUCTURE_LINKS"},No={message:"Invalid eventType",code:"ERR_INVALID_EVENT_TYPE"};var Et={message:"Missing event / eventId",code:"ERR_MISSING_EVENT_ID"},mr={message:"Event not found",code:"ERR_NOT_FOUND_EVENT"},fy={message:"Event exists",code:"ERR_EXISTING_EVENT"},gy={message:"Missing entries",code:"ERR_MISSING_ENTRIES"},Iy={message:"Invalid entries",code:"ERR_INVALID_ENTRIES"},hl={message:"Missing assignments",code:"ERR_MISSING_ASSIGNMENTS"},mI={message:"Missing stage",code:"ERR_MISSING_STAGE"},Di={message:"Invalid stage",code:"ERR_INVALID_STAGE"},hy={message:"stageSequence limit",code:"ERR_LIMIT_STAGE_SEQUENCE"},Sy={message:"Missing positionAssignments",code:"ERR_MISSING_POSITION_ASSIGNMENTS"},Ty={message:"Cannot Assign BYE status if no assignment: { bye: true }",code:"ERR_UNCHANGED_CANNOT_ASSIGN_BYE"},dI={message:"Unrecognized matchUpStatus",code:"ERR_UNRECOGNIZED_MATCHUP_STATUS"},Ya={message:"Unrecognized matchUpFormat",code:"ERR_UNRECOGNIZED_MATCHUP_FORMAT"},Sl={message:"Incompatible matchUpStatus",code:"ERR_INCOMPATIBLE_MATCHUP_STATUS"},oa={message:"Invalid matchUpStatus",code:"ERR_INVALID_MATCHUP_STATUS"},ni={message:"Invalid tieFormat",code:"ERR_INVALID_TIE_FORMAT"},Tl={message:"Invalid matchUpFormat",code:"ERR_INVALID_MATCHUP_FORMAT"},Al={message:"Missing matchUpFormat",code:"ERR_MISSING_MATCHUP_FORMAT"},Ay={message:"Missing collectionDefinition",code:"ERR_MISSING_COLLECTION_DEFINITION"},qa={message:"Missing tieFormat",code:"ERR_MISSING_TIE_FORMAT"},ke={message:"Missing matchUpId",code:"ERR_MISSING_MATCHUP_ID"},ia={message:"Missing matchUpIds",code:"ERR_MISSING_MATCHUP_IDS"},Oe={message:"matchUp not found",code:"ERR_NOT_FOUND_MATCHUP"},Sn={message:"Missing matchUps",code:"ERR_MISSING_MATCHUPS"},sr={message:"Missing matchUp",code:"ERR_MISSING_MATCHUP"},Je={message:"Invalid matchUp",code:"ERR_INVALID_MATCHUP"},lI={message:"Missing policyType",code:"ERR_MISSING_POLICY_TYPE"},Bu={message:"Missing policyDefinitions",code:"ERR_MISSING_POLICY_DEFINITIONS"},ww={message:"Missing seeding policy",code:"ERR_MISSING_POLICY_SEEDING"},yy={message:"Missing avoidance policy",code:"ERR_MISSING_POLICY_AVOIDANCE"},fI={message:"Missing policy attributes",code:"ERR_MISSING_POLICY_ATTRIBUTES"},Ey={message:"Invalid policyDefinitions",code:"ERR_INVALID_POLICY_DEFINITIONS"},gI={message:"existing policyType",code:"ERR_EXISTING_POLICY_TYPE"},Lw={message:"Policy not attached",code:"ERR_FAILURE_POLICY_NOT_ATTACHED"},Lc={message:"Policy not found",code:"ERR_NOT_FOUND_POLICY"},Fw={message:"Missing scoring policy / matchUpFormats",code:"ERR_MISSING_POLICY_SCORING_MATCHUP_FORMATS"},yl={message:"Invalid sideNumber",code:"ERR_INVALID_SIDE_NUMBER"},Gw={message:"Invalid setNumber",code:"ERR_INVALID_SET_NUMBER"},El={message:"Missing setObject",code:"ERR_MISSING_SET_ATTRIBUTE"},kw={message:"Missing setNumber",code:"ERR_MISSING_SET_NUMBER"},Vw={message:"Missing sideNumber",code:"ERR_MISSING_SIDE_NUMBER"},Ni={message:"Missing courtId",code:"ERR_MISSING_COURT_ID"},et={message:"Missing value",code:"ERR_MISSING_VALUE"},Uy={message:"Missing date",code:"ERR_MISSING_DATE"},Py={message:"No valid dates",code:"ERR_NO_VALID_DATES"},om={message:"Invalid bookings",code:"ERR_INVALID_BOOKINGS"},Ul={message:"Invalid dateAvailability",code:"ERR_INVALID_DATE_AVAILABILITY"},Dy={message:"Missing dateAvailability",code:"ERR_MISSING_DATE_AVAILABILITY"},ar={message:"Invalid Date",code:"ERR_INVALID_DATE"},mo={message:"Invalid time",code:"ERR_INVALID_TIME"},Ny={message:"Invalid tournament dates",code:"ERR_INVALID_DATES_TOURNAMENT"};var II={message:"Invalid game scores",code:"ERR_INVALID_SCORES_GAME"},My={message:"Invalid score",code:"ERR_INVALID_SCORE"},im={message:"Invalid winningSide",code:"ERR_INVALID_WINNING_SIDE"};var _C={message:"No participants generated",code:"ERR_NO_PARTICIPANTS_GENERATED"},Pl={message:"Cannot modify tieFormat",code:"ERR_UNCHANGED_CANNOT_MODIFY_TIEFORMAT"},Cy={message:"Cannot modify participantType",code:"ERR_UNCHANGED_CANNOT_MODIFY_PARTICIPANT_TYPE"},Hu={message:"Cannot remove participants",code:"ERR_UNCHANGED_CANNOT_REMOVE_PARTICIPANTS"},Dl={message:"Cannot change winningSide",code:"ERR_UNCHANGED_CANNOT_CHANGE_WINNING_SIDE"},Us={message:"Invalid participant",code:"ERR_INVALID_PARTICIPANT"},pn={message:"Invalid participantId",code:"ERR_INVALID_PARTICIPANT_ID"},zr={message:"Invalid participantIds",code:"ERR_INVALID_PARTICIPANT_IDS"},Ry={message:"Invalid participantRole",code:"ERR_INVALID_PARTICIPANT_ROLE"},nn={message:"Invalid participantType",code:"ERR_INVALID_PARTICIPANT_TYPE"},by={message:"Missing participantRole",code:"ERR_MISSING_PARTICIPANT_ROLE"},Mi={message:"Missing participant",code:"ERR_MISSING_PARTICIPANT"},$a={message:"Missing participants",code:"ERR_MISSING_PARTICIPANTS"},oe={message:"Missing participantId",code:"ERR_MISSING_PARTICIPANT_ID"},Zt={message:"Participant Not Found",code:"ERR_NOT_FOUND_PARTICIPANT"},Oy={message:"participantId exists",code:"ERR_EXISTING_PARTICIPANT_ID"},Bw={message:"participant pair exists",code:"ERR_EXISTING_PARTICIPANT_PAIR"},_y={message:"No participant removed",code:"ERR_UNCHANGED_NO_PARTICIPANT_REMOVED"},lo={message:"Missing participantIds",code:"ERR_MISSING_PARTICIPANT_IDS"},vy={message:"Missing participantsCount",code:"ERR_MISSING_PARTICIPANT_COUNT"},xy={message:"Participant not checked in",code:"ERR_UNCHANGED_PARTICIPANT_NOT_CHECKED_IN"},wy={message:"Missing person details",code:"ERR_MISSING_PERSON_DETAILS"},Ps={message:"Existing participant drawPosition assignment",code:"ERR_EXISTING_PARTICIPANT_DRAW_POSITION_ASSIGNMENT"},Wu={message:"Existing participant",code:"ERR_EXISTING_PARTICIPANT"},Nl={message:"participantsCount exceeds drawSize",code:"ERR_INVALID_PARTICIPANT_COUNT"},Ml={message:"Invalid entry status",code:"ERR_INVALID_ENTRY_STATUS"},hI={message:"Participant Entry Not Found",code:"ERR_NOT_FOUND_PARTICIPANT_ENTRY"},vC={message:"Participant not entered in stage",code:"ERR_UNCHANGED_PARTICIPANT_NOT_ENTERED"},xC={message:"Participant not found in stageSequence",code:"ERR_NOT_FOUND_PARTICIPANT_IN_STAGE"},Ly={message:"entryStatus not allowed in stage",code:"ERR_INVALID_ENTRY_STATUS_IN_STAGE"},Fy={message:"entryStatus not allowed for event",code:"ERR_INVALID_ENTRY_STATUS_IN_EVENT"},SI={message:"No stage space available for entryStatus",code:"ERR_UNCHANGED_NO_AVAILABLE_STAGE_SPACE"},Gy={message:"Insufficient drawPositions to accommodate qualifiers",code:"ERR_UNCHANGED_NO_DRAW_POSITIONS_FOR_QUALIFIERS"},Cl={message:"Insufficient drawPositions to accommodate entries",code:"ERR_INSUFFICIENT_DRAW_POSITIONS"},ky={message:"Missing penaltyType",code:"ERR_MISSING_PENALTY_TYPE"},Rl={message:"Missing penaltyId",code:"ERR_MISSING_PENALTY_ID"},Fc={message:"Penalty not found",code:"ERR_NOT_FOUND_PENALTY"},Vy={message:"Missing courtsCount/courtNames",code:"ERR_MISSING_COURTS_INFO"},Ka={message:"Court not found",code:"ERR_NOT_FOUND_COURT"},By={message:"Court exists",code:"ERR_EXISTING_COURT"},Hy={message:"Venue exists",code:"ERR_EXISTING_VENUE"},Ds={message:"Venue not found",code:"ERR_NOT_FOUND_VENUE"},Bo={message:"Missing venueId",code:"ERR_MISSING_VENUE_ID"},Wy={message:"Invalid endTime",code:"ERR_INVALID_END_TIME"},TI={message:"Existing endTime",code:"ERR_EXISTING_END_TIME"},jy={message:"Invalid stopTime",code:"ERR_INVALID_STOP_TIME"},Yy={message:"Invalid startTime",code:"ERR_INVALID_START_TIME"},wC={message:"Invalid resumeTime",code:"ERR_INVALID_RESUME_TIME"},bl={message:"Invalid timeItem",code:"ERR_INVALID_TIME_ITEMS"},qy={message:"Missing async state provider",code:"ERR_MISSING_ASYNC_STATE_PROVIDER"},Ol={message:"Missing timeItem",code:"ERR_MISSING_TIME_ITEM"},_l={message:"Missing timeItems",code:"ERR_MISSING_TIME_ITEMS"},Gc={message:"Missing context",code:"ERR_MISSING_CONTEXT"},$y={message:"Missing schedule",code:"ERR_MISSING_SCHEDULE"},ju={message:"Invalid scaleItem",code:"ERR_INVALID_SCALE_ITEM"},Ky={message:"Modifications failed",code:"ERR_FAILURE_MODIFICATIONS"},Ns={message:"No modifications applied",code:"ERR_UNCHANGED_NO_MODIFICATIONS_APPLIED"},zy={message:"Unable to assign court",code:"ERR_UNCHANGED_COURT_NOT_ASSIGNED"},Yu={message:"No Candidates",code:"ERR_UNCHANGED_NO_CANDIDATES"},Qy={message:"Invalid configuration",code:"ERR_INVALID_CONFIG"},Xy={message:"Invalid collectionDefinition",code:"ERR_INVALID_COLLECTION_DEFINITION"},Xn={message:"Invalid object",code:"ERR_INVALID_OBJECT"},vl={message:"Invalid gender",code:"ERR_INVALID_GENDER"},sm={message:"Invalid category",code:"ERR_INVALID_CATEGORY"},G={message:"Invalid values",code:"ERR_INVALID_VALUES"},Jy={message:"Duplicate value",code:"ERR_DUPLICATE_VALUE"},xl={message:"Team not found",code:"ERR_NOT_FOUND_TEAM"},Zy={message:"No valid actions",code:"ERR_NO_VALID_ACTIONS"},qu={message:"No valid attributes",code:"ERR_NO_VALID_ATTRIBUTES"},wl={message:"Value unchanged",code:"ABORT_UNCHANGED"},Ke={message:"Not found",code:"ERR_NOT_FOUND"},$u={message:"Not implemented",code:"ERR_NOT_IMPLEMENTED"},tE={message:"Existing flight",code:"ERR_EXISTING_FLIGHT"},Ll={message:"Existing flight profile",code:"ERR_EXISTING_FLIGHT_PROFILE"},eE={message:"Existing outcome",code:"ERR_EXISTING_OUTCOME"},rE={message:"Existing matchUpId",code:"ERR_EXISTING_MATCHUP_ID"},AI={message:"Existing stage",code:"ERR_EXISTING_STAGE"},Fl={message:"Existing structure",code:"ERR_EXISTING_STRUCTURE"},za={message:"Method not found",code:"ERR_NOT_FOUND_METHOD"},nE={message:"Scheduled matchUps",code:"ERR_SCHEDULED_MATCHUPS"},Ku={message:"Scores present",code:"ERR_SCORES_PRESENT"},LC={ANACHRONISM:aI,CANNOT_CHANGE_WINNING_SIDE:Dl,CANNOT_MODIFY_TIEFORMAT:Pl,CANNOT_MODIFY_PARTICIPANT_TYPE:Cy,CANNOT_REMOVE_MAIN_STRUCTURE:ty,CANNOT_REMOVE_PARTICIPANTS:Hu,COURT_EXISTS:By,COURT_NOT_FOUND:Ka,DRAW_DEFINITION_NOT_FOUND:pr,DRAW_ID_EXISTS:oy,DRAW_POSITION_ACTIVE:ku,DRAW_POSITION_ASSIGNED:Ha,DRAW_POSITION_NOT_CLEARED:ny,DRAW_POSITION_NOT_FOUND:vw,DRAW_SIZE_MISMATCH:uI,DUPLICATE_VALUE:Jy,ENTRY_STATUS_NOT_ALLOWED_FOR_EVENT:Fy,ENTRY_STATUS_NOT_ALLOWED_IN_STAGE:Ly,EVENT_EXISTS:fy,EVENT_NOT_FOUND:mr,EXISTING_DRAW_DEFINITIONS:ey,EXISTING_END_TIME:TI,EXISTING_FLIGHT:tE,EXISTING_MATCHUP_ID:rE,EXISTING_OUTCOME:eE,EXISTING_PARTICIPANT_DRAW_POSITION_ASSIGNMENT:Ps,EXISTING_PARTICIPANT:Wu,EXISTING_POLICY_TYPE:gI,EXISTING_PROFILE:Ll,EXISTING_ROUND:dy,EXISTING_STAGE:AI,EXISTING_STRUCTURE:Fl,INCOMPATIBLE_MATCHUP_STATUS:Sl,INCOMPLETE_SOURCE_STRUCTURE:dl,INSUFFICIENT_DRAW_POSITIONS:Cl,INVALID_ACTION:cy,INVALID_ASSIGNMENT:pI,INVALID_BOOKINGS:om,INVALID_CATEGORY:sm,INVALID_COLLECTION_DEFINITION:Xy,INVALID_CONFIGURATION:Qy,INVALID_DATE_AVAILABILITY:Ul,INVALID_DATE:ar,INVALID_DRAW_DEFINITION:na,INVALID_DRAW_POSITION_FOR_SEEDING:ll,INVALID_DRAW_POSITION:ys,INVALID_DRAW_SIZE:Vu,INVALID_END_TIME:Wy,INVALID_ENTRIES:Iy,INVALID_EVENT_TYPE:No,INVALID_GAME_SCORES:II,INVALID_GENDER:vl,INVALID_MATCHUP_FORMAT:Tl,INVALID_MATCHUP_STATUS:oa,INVALID_MATCHUP_STATUS_BYE:Ty,INVALID_MATCHUP:Je,INVALID_OBJECT:Xn,INVALID_PARTICIPANT_ID:pn,INVALID_PARTICIPANT_IDS:zr,INVALID_PARTICIPANT_ROLE:Ry,INVALID_PARTICIPANT_SEEDING:iy,INVALID_PARTICIPANT_TYPE:nn,INVALID_PARTICIPANT:Us,INVALID_POLICY_DEFINITION:Ey,INVALID_RECORDS:cI,INVALID_SCALE_ITEM:ju,INVALID_SEED_NUMBER:py,INVALID_SEED_POSITION:my,INVALID_SET_NUMBER:Gw,INVALID_SIDE_NUMBER:yl,INVALID_SCORE:My,INVALID_STAGE:Di,INVALID_START_TIME:Yy,INVALID_STRUCTURE:Pi,INVALID_STOP_TIME:jy,INVALID_TIE_FORMAT:ni,INVALID_TIME:mo,INVALID_TIME_ITEM:bl,INVALID_TOURNAMENT_DATES:Ny,INVALID_TOURNAMENT_RECORD:Ba,INVALID_VALUES:G,INVALID_WINNING_SIDE:im,MATCHUP_NOT_FOUND:Oe,METHOD_NOT_FOUND:za,MISSING_ASSIGNMENTS:hl,MISSING_ASYNC_STATE_PROVIDER:qy,MISSING_AVOIDANCE_POLICY:yy,MISSING_COLLECTION_DEFINITION:Ay,MISSING_COURT_ID:Ni,MISSING_COURTS_INFO:Vy,MISSING_DATE_AVAILABILITY:Dy,MISSING_DATE:Uy,MISSING_DRAW_DEFINITION:X,MISSING_DRAW_ID:Wr,MISSING_DRAW_POSITION:Es,MISSING_DRAW_POSITIONS:Wa,MISSING_DRAW_SIZE:ja,MISSING_ENTRIES:gy,MISSING_EVENT:Et,MISSING_MATCHUP_FORMAT:Al,MISSING_MATCHUP_ID:ke,MISSING_MATCHUP_IDS:ia,MISSING_MATCHUP:sr,MISSING_MATCHUPS:Sn,MISSING_PARTICIPANT_COUNT:vy,MISSING_PARTICIPANT_ID:oe,MISSING_PARTICIPANT_IDS:lo,MISSING_PARTICIPANT_ROLE:by,MISSING_PARTICIPANT:Mi,MISSING_PARTICIPANTS:$a,MISSING_PENALTY_ID:Rl,MISSING_PENALTY_TYPE:ky,MISSING_PERSON_DETAILS:wy,MISSING_POLICY_ATTRIBUTES:fI,MISSING_POLICY_DEFINITION:Bu,MISSING_POLICY_TYPE:lI,MISSING_POSITION_ASSIGNMENTS:Sy,MISSING_ROUND_NUMBER:xw,MISSING_SCHEDULE:$y,MISSING_SCORING_POLICY:Fw,MISSING_SEED_ASSIGNMENTS:uy,MISSING_SEEDCOUNT_THRESHOLDS:ay,MISSING_SEEDING_POLICY:ww,MISSING_SET_NUMBER:kw,MISSING_SET_OBJECT:El,MISSING_SIDE_NUMBER:Vw,MISSING_STAGE:mI,MISSING_STRUCTURE_ID:hr,MISSING_STRUCTURE:Do,MISSING_STRUCTURES:Il,MISSING_TARGET_LINK:gl,MISSING_TIE_FORMAT:qa,MISSING_TIME_ITEM:Ol,MISSING_TIME_ITEMS:_l,MISSING_TOURNAMENT_ID:ra,MISSING_TOURNAMENT_RECORD:W,MISSING_TOURNAMENT_RECORDS:Ft,MISSING_VALUE:et,MISSING_VENUE_ID:Bo,MODIFICATIONS_FAILED:Ky,NO_CANDIDATES:Yu,NO_DRAW_POSITIONS_AVAILABLE_FOR_QUALIFIERS:Gy,NO_MODIFICATIONS_APPLIED:Ns,NO_STAGE_SPACE_AVAILABLE_FOR_ENTRY_STATUS:SI,NO_PARTICIPANT_REMOVED:_y,NO_VALID_ACTIONS:Zy,NO_VALID_ATTRIBUTES:qu,NO_VALID_DATES:Py,NOT_FOUND:Ke,NOT_IMPLEMENTED:$u,PARTICIPANT_COUNT_EXCEEDS_DRAW_SIZE:Nl,PARTICIPANT_ID_EXISTS:Oy,PARTICIPANT_NOT_CHECKED_IN:xy,PARTICIPANT_NOT_FOUND:Zt,PARTICIPANT_PAIR_EXISTS:Bw,PENALTY_NOT_FOUND:Fc,POLICY_NOT_ATTACHED:Lw,POLICY_NOT_FOUND:Lc,SCHEDULE_NOT_CLEARED:ry,SCHEDULED_MATCHUPS:nE,SCORES_PRESENT:Ku,SEEDSCOUNT_GREATER_THAN_DRAW_SIZE:sy,STAGE_SEQUENCE_LIMIT:hy,STRUCTURE_NOT_FOUND:Lt,TEAM_NOT_FOUND:xl,UNABLE_TO_ASSIGN_COURT:zy,UNLINKED_STRUCTURES:ly,UNRECOGNIZED_DRAW_TYPE:fl,UNRECOGNIZED_MATCHUP_FORMAT:Ya,UNRECOGNIZED_MATCHUP_STATUS:dI,VALUE_UNCHANGED:wl,VENUE_EXISTS:Hy};var Ze={disableNotifications:!1,tournamentId:void 0,tournamentRecords:{},subscriptions:{},modified:!1,methods:{},notices:[]},oE={addNotice:Zw,callListener:oL,cycleMutationStatus:Jw,deleteNotice:rL,deleteNotices:eL,disableNotifications:Hw,enableNotifications:Ww,getMethods:zu,getNotices:tL,getTopics:nL,getTournamentId:FC,getTournamentRecord:jw,getTournamentRecords:Yw,removeTournamentRecord:zw,setMethods:Xw,setSubscriptions:Qw,setTournamentId:$w,setTournamentRecord:qw,setTournamentRecords:Kw,handleCaughtError:iL};function Hw(){Ze.disableNotifications=!0}function Ww(){Ze.disableNotifications=!1}function FC(){return Ze.tournamentId}function jw(t){return Ze.tournamentRecords[t]}function Yw(){return Ze.tournamentRecords}function qw(t){let e=t?.tournamentId;return e?(Ze.tournamentRecords[e]=t,{success:!0}):{error:Ba}}function $w(t){return t?Ze.tournamentRecords[t]?(Ze.tournamentId=t,{success:!0}):{error:W}:(Ze.tournamentId=void 0,{success:!0})}function Kw(t){Ze.tournamentRecords=t;let e=Object.keys(t);e.length===1?Ze.tournamentId=e[0]:e.length||(Ze.tournamentId=void 0)}function zw(t){if(typeof t!="string")return{error:G};if(!Ze.tournamentRecords[t])return{error:Ke};delete Ze.tournamentRecords[t];let e=Object.keys(Ze.tournamentRecords);return e.length===1?Ze.tournamentId=e[0]:e.length||(Ze.tournamentId=void 0),{success:!0}}function Qw(t){return typeof t.subscriptions!="object"?{error:G}:(Object.keys(t.subscriptions).forEach(e=>{Ze.subscriptions[e]=t.subscriptions[e]}),{...R})}function Xw(t){return typeof t!="object"?{error:G}:(Object.keys(t).forEach(e=>{typeof t[e]=="function"&&(Ze.methods[e]=t[e])}),{...R})}function Jw(){let t=Ze.modified;return Ze.modified=!1,t}function Zw({topic:t,payload:e,key:r},n){if(!(typeof t!="string"||typeof e!="object")&&(Ze.disableNotifications||(Ze.modified=!0),!(Ze.disableNotifications||!Ze.subscriptions[t]&&!n)))return r&&(Ze.notices=Ze.notices.filter(o=>!(o.topic===t&&o.key===r))),Ze.notices.push({topic:t,payload:e,key:r}),{...R}}function zu(){return Ze.methods??{}}function tL({topic:t}){return Ze.notices.filter(e=>e.topic===t).map(e=>e.payload)}function eL(){Ze.notices=[]}function rL({topic:t,key:e}){Ze.notices=Ze.notices.filter(r=>(!t||r.topic===t)&&r.key!==e)}function nL(){return{topics:Object.keys(Ze.subscriptions)}}function oL({topic:t,notices:e},r){let n=Ze.subscriptions[t];n&&typeof n=="function"&&n(e);let o=r?.[t];o&&typeof o=="function"&&o(e)}function iL({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:FC(),params:JSON.stringify(r),engine:t,methodName:e,error:o}),{error:o}}function se(t,e){return(t??0)-(e??0)}function ct(t){return typeof t=="number"?parseInt(t.toString()):typeof t=="string"?parseInt(t):0}function Tn(t){return isNaN(t)?!1:t&&(t&t-1)===0}function iE(t){if(!t.length)return;let e=[...t].sort(se),r=Math.floor(e.length/2);return e.length%2?e[r]:(e[r-1]+e[r])/2}function GC(t){if(!Tn(t))return!1;let e=t,r=1;for(;e!==2;)r+=1,e=e/2;return r}function am(t){return isNaN(t)?0:t%2&&t+1||t}function cm(t){return Math.pow(2,Math.round(Math.log(t)/Math.log(2)))}function te(t){return!isNaN(parseFloat(t))}function yI(t){let e=ct(t);if(!isNaN(e))return e===0?!1:(e&-e)===1}function qi(t){if(isNaN(t))return!1;for(;!Tn(t);)t++;return t}function Jn(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 kC(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 sL(t,e){e||(e=1);let r=1/e;return Math.round(t*r)/r}function sE(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=sE(t,e,r):(a=Math.pow(a,r),a*=e-t,a+=t),n&&(a=sL(a,n)),parseFloat(a.toFixed(o))}function pt(t){return Array.isArray(t)?t?.filter((e,r,n)=>n.lastIndexOf(e)===r):[]}function VC(t){return Array.isArray(t)?t?.map(e=>e===null?void 0:e):t}function cr(t){return Array.isArray(t)?t.map(e=>[Math.random(),e]).sort((e,r)=>e[0]-r[0]).map(e=>e[1]):[]}function Qa(t){return ft(t)?t:1/0}function dr(t){return Array.isArray(t)?t.reduce((e,r)=>(e[r]||(e[r]=0),e[r]++,e),{}):{}}function BC(t){return aE(dr(t))}function aE(t){return Object.keys(t).reduce((e,r)=>{let n=t[r];return e[n]?e[n].push(r):e[n]=[r],e},{})}function aL(t,e,r){return r.indexOf(t)===e}function EI(t){return t.filter(aL)}function xr(t){return Array.isArray(t)&&t.length?t.splice(Math.floor(Math.random()*t.length),1)[0]:void 0}function on(t){let e=Math.floor(Math.random()*t.length);return t[e]}function Z(t,e){return Array.from({length:e-t},(r,n)=>n+t)}function Zn(t,e){return e.reduce((r,n,o)=>(n===t&&r.push(o),r),[])}function jt(t,e){return!Array.isArray(t)||!Array.isArray(e)?[]:t.filter(r=>e.indexOf(r)!==-1).filter((r,n,o)=>o.indexOf(r)===n)}function cE(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 HC(t,e){return Array.isArray(e)&&e.reduce((r,n)=>(r[n]=1+r[n]||1,r),{})[t]||0}function WC(t,e,r,n){return Array.isArray(t)?[].concat(...t.slice(0,e),...t.slice(e,e+r).sort(n),...t.slice(e+r,t.length)):[]}function Te(t,e){return Array.isArray(t)?t.reduce((r,n,o)=>{let i=Math.floor(o/e);return r[i]=[].concat(r[i]||[],n),r},[]):[]}function uE(t,[e,...r]){return t.length?[t.slice(0,e),...uE(t.slice(e),[...r,e])]:[]}function jC(t){return t.reduce((e,r)=>{let n=e[e.length-1];return(!n||n[n.length-1]!==r-1)&&e.push([]),e[e.length-1].push(r),e},[])}function UI(t){return Array.isArray(t)?t.reduce((e,r)=>!isNaN(parseInt(r))&&e,!0):!1}function PI(t){return Array.isArray(t)?t.reduce((e,r)=>isNaN(parseInt(r))&&e,!0):!1}function Gl(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 YC(t,e=1){if(!Array.isArray(t)||!t.every(ft))return[];let r=Math.min(...t,e),n=Math.max(...t);return Z(r,n+1).filter(o=>!t.includes(o))}var De={timers:{default:{elapsedTime:0}},globalSubscriptions:{},deepCopyAttributes:{stringify:[],ignore:[],toJSON:[]},globalMethods:[],deepCopy:!0},jr=oE,qC=["addNotice","callListener","cycleMutationStatus","deleteNotice","deleteNotices","disableNotifications","enableNotifications","getMethods","getNotices","getTopics","getTournamentId","getTournamentRecord","getTournamentRecords","removeTournamentRecord","setSubscriptions","setTournamentId","setTournamentRecord","setTournamentRecords"];function cL(t){if(typeof t!="object")throw new Error("Global state provider can not be undefined or null");if(jt(Object.keys(t),qC).length!==qC.length)throw new Error("Global state provider is missing required methods");return jr=t,{success:!0}}function pE(){if(jr.createInstanceState){try{jr.createInstanceState()}catch(t){return{error:t}}return{success:!0}}else return{error:qy}}function yr(t){return!t||typeof t!="object"?De.devContext??!1:typeof De.devContext!="object"?!1:Object.keys(t).every(e=>De.devContext?.[e]===t[e])&&De.devContext}function uL(t="reset",e="default"){let r=Date.now();if(t==="report"){if(e==="allTimers")return Object.keys(De.timers).filter(o=>o!=="default"||De.timers[o].startTime).map(o=>{let i=De.timers[o],s=i.state==="stopped"?0:(r-(i?.startTime??0))/1e3,a=i.elapsedTime+s;return{state:De.timers[o].state,elapsedTime:a.toFixed(2),timer:o}});{let n=De.timers[e].state==="stopped"?0:(r-(De.timers[e]?.startTime??0))/1e3,o=De.timers[e].elapsedTime+n;return{state:De.timers[e].state,elapsedTime:o.toFixed(2),timer:e}}}if(!De.timers[e]||t==="reset"){if(e==="allTimers")return De.timers={default:{elapsedTime:0}},!0;De.timers[e]={startTime:r,state:"active",elapsedTime:0}}return De.timers[e].elapsedTime||(De.timers[e].elapsedTime=0),t==="stop"&&De.timers[e].state!=="stopped"&&(De.timers[e].state="stopped")&&(De.timers[e].elapsedTime+=(r-(De.timers[e]?.startTime??0))/1e3),t==="start"&&(De.timers[e].startTime=r)&&(De.timers[e].state="active"),De.timers[e]}function $C(t){Mr(t)?De.globalLog=t:delete De.globalLog}function kc(t){De.devContext=t}function mE(){jr.disableNotifications()}function kl(){jr.enableNotifications()}function Vc(t,e){typeof t=="boolean"&&(De.deepCopy=t),typeof e=="object"&&(Array.isArray(e.ignore)&&(De.deepCopyAttributes.ignore=e.ignore),Array.isArray(e.toJSON)&&(De.deepCopyAttributes.toJSON=e.toJSON),Array.isArray(e.stringify)&&(De.deepCopyAttributes.stringify=e.stringify),e.threshold&&(De.deepCopyAttributes.threshold=e.threshold))}function Vl(){return{enabled:De.deepCopy,...De.deepCopyAttributes}}function pL(t){return t?.subscriptions?(Object.keys(t.subscriptions).forEach(e=>{De.globalSubscriptions[e]=t.subscriptions[e]}),{...R}):{error:et,info:"missing subscriptions"}}function mL(t){return t?.subscriptions?jr.setSubscriptions({subscriptions:t.subscriptions}):{error:et,info:"missing subscriptions"}}function KC(t){return t?typeof t!="object"?{error:G}:(Object.keys(t).forEach(e=>{Mr(t[e])&&(De.globalMethods[e]=t[e])}),{...R}):{error:et,info:"missing method declarations"}}function zC(t){return t?typeof t!="object"?{error:G}:jr.setMethods(t):{error:et,info:"missing method declarations"}}function Bl(){return jr.cycleMutationStatus()}function Tt(t){if(typeof t?.topic!="string")return;let e=De.globalSubscriptions[t.topic];return jr.addNotice(t,e)}function Hl(){return{...De.globalMethods,...jr.getMethods()}}function DI(t){return jr.getNotices(t)}function NI({key:t,topic:e}){return jr.deleteNotice({key:t,topic:e})}function Ci(){return jr.deleteNotices()}function Cr(){return jr.getTopics()}async function um(t){return jr.callListener(t,De.globalSubscriptions)}function $i(){return jr.getTournamentId()}function Wl(t){return jr.getTournamentRecord(t)}function Mo(){return jr.getTournamentRecords()}function dE(t){return jr.setTournamentRecord(t)}function pm(t){return jr.setTournamentRecords(t)}function Qu(t){return jr.setTournamentId(t)}function lE(t){return jr.removeTournamentRecord(t)}function MI(){return jr}function Xu({engineName:t,methodName:e,params:r,err:n}){return(Mr(jr.handleCaughtError)&&jr.handleCaughtError||oE.handleCaughtError)({engineName:t,methodName:e,params:r,err:n})}function fE(t,e){if(De.globalLog)try{De.globalLog({log:t,engine:e})}catch(r){console.log("globalLog error",r),console.log(e,t),$C()}else console.log(e,t)}function gE(t,e,r,n){if(!Rt(t))return{error:G};te||(r=1);let o=Array.isArray(e)?e:[],i={},s=(a,c=0)=>{Object.keys(a).forEach(u=>{Mr(a[u])?i[u]=a[u]:Rt(a[u])&&(e===!0||o?.includes(u))&&(r===void 0||c<r)&&s(a[u],c+1)})};return s(t),n?KC(i):zC(i),{methods:i}}function dL(t,e,r){return Object.keys(t).filter(n=>!e.includes(t[n])&&(!r||(Array.isArray(t[n])?t[n].length:!0)))}function rt(t,e,r,n){if(typeof t!="object"||t===null)return t;Vl()?.enabled||(n=!0);let i=["",void 0,null];e&&i.push(!1);let s=dL(t,i,r);return Object.assign({},...s.map(a=>Array.isArray(t[a])?{[a]:n?t[a]:t[a].map(c=>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,{...R}),e??{success:!0}}var ye="tournamentRecords",jl="policyDefinitions",An="tournamentRecord",Yr="drawDefinition",mm="matchUpFormat",Bn="participantId",CI="scheduleDates",XC="tournamentId",JC="scheduleDate",dm="structureId",Yl="participant",Xa="matchUpIds",ZC="policyType",IE="structures",Co="matchUpId",lm="inContext",ql="structure",Ju="courtIds",tR="personId",Zu="venueIds",hE="matchUps",RI="courtId",bI="eventId",fo="matchUp",OI="drawId",Ms="error",Cs="event",sa="param",eR="uuids",rR="averageMatchUpMinutes",nR="recoveryMinutes",oR="periodLength",iR="number";var Ri="object",Er="array";var yn="_validate",_I="_message",En="_invalid",to="_ofType",fm="_anyOf",Ja="_oneOf";var lL={[ye]:Ft,[An]:W,[jl]:Bu,[Yr]:X,[Bn]:oe,[mm]:Al,[XC]:ra,[dm]:hr,[Xa]:ia,[Yl]:Mi,[IE]:Il,[Co]:ke,[ql]:Do,[RI]:Ni,[hE]:Sn,[bI]:mr,[fo]:sr,[Ju]:et,[Zu]:et,[OI]:Wr,[Cs]:Et},fL={[ye]:Ri,[jl]:Ri,[An]:Ri,[Yr]:Ri,[CI]:Er,[Yl]:Ri,[Xa]:Er,[IE]:Er,[ql]:Ri,[Ju]:Er,[Zu]:Er,[hE]:Er,[fo]:Ri,[Cs]:Ri,[eR]:Er};function lt(t,e,r){if(!t&&!Rt(t))return{error:G};if(!e?.length||t?._bypassParamCheck)return{valid:!0};if(!Array.isArray(e))return{error:G};let{paramError:n,errorParam:o}=hL(t,e);if(!n)return{valid:!0};let i=t?.[o]===void 0?lL[o]||G:n[yn]&&n[En]||G,s=o??(n[Ja]&&Object.keys(n[Ja]).join(", "));return _({info:{param:s,message:n[_I]},result:{error:i},stack:r})}function sR(t,e){let r=Object.keys(t),n=Object.keys(e);return jt(r,n)}function gL(t,e){if(!e)return;let r=sR(t,e);return r.length!==1?{error:G}:r.reduce((n,o)=>({...n,[o]:!0}),{})}function IL(t,e){if(!e)return;let r=sR(t,e).filter(n=>t[n]);return r.length<1?{error:G}:r.reduce((n,o)=>({...n,[o]:!0}),{})}function hL(t,e){let r,n;return{paramError:e.find(({_ofType:i,_oneOf:s,_anyOf:a,_validate:c,_info:u,...p})=>{let m=s&&gL(t,s);if(m?.error)return m.error;m&&Object.assign(p,m);let d=a&&IL(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&&!Mr(c),h=t[g]&&!c&&SL(t,g,i),S=p[g]&&!t[g],A=I||h||S||c&&t[g]&&!TL(t[g],c);return A&&(r=g,n=u),A});return!l.length||f}),errorParam:r,paramInfo:n}}function SL(t,e,r){return r=r||fL[e]||"string",r==="array"?!Array.isArray(t[e]):typeof t[e]!==r}function TL(t,e){return Mr(e)?e(t):!0}var vI="DYNAMIC",oi="RANKING",Ki="RATING",zi="SCALE",eo="SEEDING",aR={RANKING:oi,RATING:Ki,SCALE:zi,SEEDING:eo};function aa(t){let e=lt(t,[{[Yl]:!0}]);if(e.error)return e;let r=t.participant.timeItems?.filter(({itemType:o})=>o?.startsWith(zi)&&[oi,Ki,eo].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===eo&&"seedings"||c===oi&&"rankings"||"ratings";n[l][u]||(n[l][u]=[]),n[l][u].push({scaleValue:a.itemValue,scaleDate:a.itemDate,scaleName:d})}}}return{...R,...n}}function bi(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 gm=/^[\d]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][\d]|3[0-1])$/,xI=/^((0[\d]|1[\d]|2[0-3]):[0-5][\d](:[0-5][\d])?)([.,][0-9]{3})?$/,Ro=/^([\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?$/,Rs=/^([\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 Im(t){let{scheduledDate:e}=t;if(!e&&t.scheduledTime&&(e=Ut(t.scheduledTime)),!e)return;let r=$t(t.scheduledTime),n=Ut(e);return n&&r&&(n+=`T${r}`),n}function cR(t){return typeof t!="object"||Array.isArray(t)?!1:Object.prototype.toString.call(t)==="[object Date]"}function Bc(t){let e=typeof t=="string"?t?.split(" "):[];return t&&e?.length>1&&!["AM","PM"].includes(e[1].toUpperCase())?!1:!!(!t||Rs.test(tc(t,!0,!0)))}function Rr(t){return Za(t)||gm.test(t)}function AL(t){let e=new Date(t),r=e.getSeconds()+60*e.getMinutes()+60*60*e.getHours();return yL(r,{displaySeconds:!1})}function yL(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(Hn).join(":")}var zl=t=>{let e=$l(t)||Za(t)?new Date(t):new Date,r=e.getUTCMonth()+1,n=r<10?`0${r}`:`${r}`;return`${e.getUTCFullYear()}-${Hn(n)}-${Hn(e.getUTCDate())}`};function EL(t){let e=$l(t)||Za(t)?new Date(t):new Date;return Date.UTC(e.getFullYear(),e.getMonth(),e.getDate())}function ro(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 wI(t){let e=t?new Date(t):new Date,r=e.getTimezoneOffset();return new Date(e.getTime()-r*60*1e3)}function UL(t){return wI(t).getTime()}function $l(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 bs(t,e){if(!Rr(t)||!Rr(e))return[];let r=Ut(t)+"T00:00",n=Ut(e)+"T00:00",o=new Date(r),i=new Date(n),s=$l(i)&&$l(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=>ro(p));function u(p,m){return p<=m}}var PL=/^([+-]?\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 Za(t){return typeof t!="string"?!1:PL.test(t)}function FI(t){if(typeof t!="string")return!1;let r=t.split("Z")[0].split(":"),n=r.every(i=>!isNaN(parseInt(i)));return!(r.length<2||!n||parseInt(r[0])>23||parseInt(r[1])>60)}function Vt(t){let e=$t(t);if(!e)return 0;let[r,n]=e.split(":").map(o=>parseInt(o));return r*60+n}function uR(t){let e=Math.floor(t/60),r=t-e*60;return e>23&&(e=e%24),[Hn(e),Hn(r)].join(":")}function Kl(t){return FI(t)?t.split(":").slice(0,2).map(Hn).join(":"):void 0}function $t(t){return Za(t)&&t.indexOf("T")>0?Kl(t.split("T").reverse()[0]):Kl(t)}function Ut(t){return Za(t)||Ro.test(t)?t.split("T")[0]:void 0}function tp(t,e){let r=new Date(t);return r.setDate(r.getDate()+e),Ut(r.toISOString())}function LI(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 DL(t){let e=LI(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(Hn).join(":")}function NL(t){let e=LI(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 tc(t,e,r){let n=Ut(t),o=$t(t),i=n?o:t;return t?e&&(n&&r&&t||DL(i))||NL(i):void 0}function GI(t,e){let r=LI(t),n=LI(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 pR(t,e=7){let r=Ut(t)+"T00:00",n=new Date(r),o=new Date(n.setDate(n.getDate()+e));return ro(o)}function ML(t){return pR(t)}function CL(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())),ro(o,r)}function mR(t,e,r){let n=new Date(t,0);return ro(new Date(n.setDate(e)),r)}function we(t,e=void 0){let[r,n]=(t||"00:00").split(":").map(Hn),o=wI(e).setHours(r,n,0,0);return wI(o)}function ca(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 br(t,e){let r=$t(t);if(!r)return"00:00";let n=isNaN(e)?0:e;return $t(Ql(we(r),n).toISOString())}function Ql(t,e){let r=new Date(t);return new Date(r.getTime()+e*6e4)}function Hn(t){return t.toString()[1]?t:"0"+t}function _n(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 dR={addDays:pR,addWeek:ML,addMinutesToTimeString:br,convertTime:tc,getIsoDateString:Im,getUTCdateString:zl,DateHHMM:AL,extractDate:Ut,extractTime:$t,formatDate:ro,getDateByWeek:CL,isISODateString:Za,isDate:$l,isTimeString:FI,offsetDate:wI,offsetTime:UL,sameDay:_n,timeStringMinutes:Vt,timeToDate:we,timeUTC:EL,validTimeValue:Bc,validDateString:gm,timeValidation:Rs,dateValidation:Ro};function J(t,e,r,n,o=0){if(MI().makeDeepCopy)return MI().makeDeepCopy(t,e,r,n);let i=Vl(),{stringify:s,toJSON:a,ignore:c,modulate:u}=i||{};if(!i?.enabled&&!r||typeof t!="object"||Mr(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)||Mr(c)&&!c(l)),d=(l,f)=>{p[l]=Mr(f?.toString)?f.toString():JSON.stringify(f)};for(let l of m){let f=t[l],g=Mr(u)?u(f):void 0;if(g!==void 0)p[l]=g;else if(e&&l==="extensions"&&Array.isArray(f)){let I=Xl(f);Object.assign(p,...I)}else n&&l==="extensions"?p[l]=[]:Array.isArray(s)&&s.includes(l)?d(l,f):Array.isArray(a)&&a.includes(l)&&Mr(f?.toJSON)?p[l]=f.toJSON():f===null?p[l]=void 0:cR(f)?p[l]=new Date(f).toISOString():p[l]=J(f,e,r,n,o+1)}return p}function Xl(t){return t?.map(e=>{let{name:r,value:n}=e;return r&&n&&{[`_${r}`]:n}}).filter(Boolean)}var kI="voluntaryConsolation",ii="competitiveBands",Jl="roundRobinTally",no="positionActions",ze="matchUpActions",Zl="rankingPoints",ua="roundNaming",Os="participant",Hc="progression",go="scheduling",Wc="avoidance",RL="display",vn="scoring",Un="seeding",ec="feedIn",bL="audit",hm="draws",lR={POLICY_TYPE_VOLUNTARY_CONSOLATION:kI,POLICY_TYPE_COMPETITIVE_BANDS:ii,POLICY_TYPE_ROUND_ROBIN_TALLY:Jl,POLICY_TYPE_POSITION_ACTIONS:no,POLICY_TYPE_MATCHUP_ACTIONS:ze,POLICY_TYPE_RANKING_POINTS:Zl,POLICY_TYPE_ROUND_NAMING:ua,POLICY_TYPE_PARTICIPANT:Os,POLICY_TYPE_PROGRESSION:Hc,POLICY_TYPE_SCHEDULING:go,POLICY_TYPE_AVOIDANCE:Wc,POLICY_TYPE_DISPLAY:RL,POLICY_TYPE_FEED_IN:ec,POLICY_TYPE_SCORING:vn,POLICY_TYPE_SEEDING:Un,POLICY_TYPE_AUDIT:bL,POLICY_TYPE_DRAWS:hm};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?.[Os];if(r?.withScaleValues){let{ratings:u,rankings:p}=aa({participant:a});a.rankings=p,a.ratings=u}if(c?.participant)return bi({template:c.participant,source:a})}return a}var Sm="element required",fR="missing name";function or(t){if(!t||typeof t!="object")return{error:et};if(t.element&&typeof t?.element!="object")return{error:G};if(!t?.name)return{error:et,info:fR};if(!t?.element){if(t.discover&&t.tournamentRecords){for(let e of Object.keys(t.tournamentRecords)){let r=t.tournamentRecords[e],n=or({element:r,name:t.name});if(n.error)return _({result:n,stack:"removeExtension"})}return{...R}}return{error:et,info:Sm}}return t?.element.extensions?(t.element.extensions=t.element.extensions.filter(e=>e?.name!==t.name),{...R}):{...R,info:Ke}}function Pn({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 St(t){if(typeof t!="object")return{error:et};let e="addExtension";if(t?.element&&typeof t.element!="object")return _({result:{error:G},stack:e});if(!Pn({extension:t.extension}))return _({result:{error:G,info:"invalid extension"},stack:e});if(!t.element)if(t.discover&&!t.tournamentId&&t.tournamentRecords){for(let o of Object.values(t.tournamentRecords)){let i=St({extension:t.extension,element:o});if(i.error)return _({result:i,stack:e})}return{...R}}else return _({result:{error:et},stack:e});if(t.element.extensions||(t.element.extensions=[]),t?.creationTime??!0){let o=new Date().toISOString();Object.assign(t.extension,{createdAt:o})}let n=t.element.extensions.find(({name:o})=>o===t.extension.name);return n?n.value=t.extension.value:t.extension.value&&t.element.extensions.push(t.extension),{...R}}function tf(t){return!t||typeof t!="object"?{error:et}:t.tournamentRecord?St({creationTime:t.creationTime,element:t.tournamentRecord,extension:t.extension}):{error:W}}function ep(t){return!t||typeof t!="object"?{error:et}:t.drawDefinition?St({creationTime:t.creationTime,element:t.drawDefinition,extension:t.extension}):{error:pr}}function Io(t){return!t||typeof t!="object"?{error:et}:t.event?St({creationTime:t.creationTime,extension:t.extension,element:t.event}):{error:mr}}function SE(t){if(!t||typeof t!="object")return{error:et};if(!t.participantId)return{error:oe};let e=t.tournamentRecord?.participants||[],r=bo({participantId:t.participantId,tournamentParticipants:e});return r?St({creationTime:t.creationTime,extension:t.extension,element:r}):{error:Zt}}function ef(t){return!t||typeof t!="object"?{error:et}:t.tournamentRecord?or({element:t.tournamentRecord,name:t.name}):{error:W}}function TE(t){return!t||typeof t!="object"?{error:et}:t.drawDefinition?or({element:t.drawDefinition,name:t.name}):{error:pr}}function rp(t){return!t||typeof t!="object"?{error:et}:t?.event?or({element:t.event,name:t.name}):{error:mr}}function AE(t){if(!t||typeof t!="object")return{error:et};if(!t.participantId)return{error:oe};let e=t.tournamentRecord?.participants||[],r=bo({participantId:t.participantId,tournamentParticipants:e});return r?or({element:r,name:t.name}):{error:Zt}}function np({tournamentRecords:t}){return{tournamentIds:Rt(t)?Object.keys(t):[],...R}}var OL="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:Ke}}return _({result:{error:et},stack:OL})}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:Ke}}var _L="activeSuspension",jc="appliedPolicies",Tm="positionActions",yE="context",Am="delegatedOutcome",Wn="disabled",ym="disableLinks",rc="disableAutoCalc",Em="drawDeletions",vL="drawProfile",Um="entryProfile",xL="eventProfile",wL="eventWithdrawalRequests",LL="factory",qr="flightProfile",VI="groupingAttribute",ho="lineUps",pa="linkedTournamentsIds",Pm="matchUpHistory",BI="participantRepresentatives",ma="personRequests",FL="rankingPoints";var mn="roundTarget",Yc="scheduleLimits",Oo="scheduleTiming",da="schedulingProfile",GL="statusDetail",nc="subOrder",Ho="tally",Qi="tieFormatModification",HI={ACTIVE_SUSPENSION:_L,APPLIED_POLICIES:jc,AUDIT_POSITION_ACTIONS:Tm,CONTEXT:yE,DELEGATED_OUTCOME:Am,DISABLED:Wn,DISABLE_LINKS:ym,DISABLE_AUTO_CALC:rc,DRAW_DELETIONS:Em,DRAW_PROFILE:vL,ENTRY_PROFILE:Um,EVENT_PROFILE:xL,EVENT_WITHDRAWAL_REQUESTS:wL,FLIGHT_PROFILE:qr,GROUPING_ATTRIBUTE:VI,LINEUPS:ho,LINKED_TOURNAMENTS:pa,MATCHUP_HISTORY:Pm,PARTICIPANT_REPRESENTATIVES:BI,PERSON_REQUESTS:ma,RANKING_POINTS:FL,ROUND_TARGET:mn,SCHEDULE_LIMITS:Yc,SCHEDULE_TIMING:Oo,SCHEDULING_PROFILE:da,STATUS_DETAIL:GL,SUB_ORDER:nc,TALLY:Ho,TIE_FORMAT_MODIFICATIONS:Qi,FACTORY:LL},EE=[Am,Wn,ym,qr,ho,Pm,BI,ma,mn,Yc,Oo,da,nc,Ho];function UE({tournamentRecords:t}){if(typeof t!="object"||!Object.keys(t).length)return{error:Ft};let e=np({tournamentRecords:t}),{tournamentIds:r}=e;return r?.length>1?St({tournamentRecords:t,discover:!0,extension:{name:pa,value:{tournamentIds:r}}}):{...R}}function PE({tournamentRecords:t}){if(typeof t!="object"||!Object.keys(t).length)return{error:Ft};let e=or({name:pa,tournamentRecords:t,discover:!0});return _({result:e,stack:"unlinkTournaments"})}function DE({tournamentRecords:t,tournamentId:e}){if(typeof t!="object")return{error:G};if(!e)return{error:ra};let r=np({tournamentRecords:t}),{tournamentIds:n}=r;if(!n.includes(e))return{error:ra};let o;return n.every(i=>{let s=t[i],{extension:a}=mt({element:s,name:pa});if(!a)return!0;let c=a?.value?.tournamentIds||[];if(!c?.length||c.length===1&&c.includes(e)||i===e){let m=ef({name:pa,tournamentRecord:s});return m.error&&(o=m.error),m.success}let u=c.filter(m=>m!==e);a.value={tournamentIds:u};let p=tf({tournamentRecord:s,extension:a});return p.error&&(o=p.error),p.success}),o?{error:o}:{...R}}var ME={};Jt(ME,{getLinkedTournamentIds:()=>qc,getTournamentIds:()=>np});function qc({tournamentRecords:t}){return typeof t!="object"||!Object.keys(t).length?{error:Ft}:{linkedTournamentIds:Object.assign({},...Object.keys(t).map(r=>{let n=t[r],o=n?.tournamentId,{extension:i}=mt({element:n,name:pa}),s=(i?.value?.tournamentIds||[]).filter(a=>a!==o);return{[r]:s}}))}}var ZD={};Jt(ZD,{addAdHocMatchUps:()=>fd,addDrawDefinitionTimeItem:()=>tg,addFinishingRounds:()=>ha,addGoesTo:()=>wi,addPlayoffStructures:()=>Dp,addQualifyingStructure:()=>WU,addVoluntaryConsolationStage:()=>BU,addVoluntaryConsolationStructure:()=>jf,allPlayoffPositionsFilled:()=>Yh,alternateDrawPositionAssignment:()=>DU,assignDrawPosition:()=>rP,assignDrawPositionBye:()=>Dr,attachConsolationStructures:()=>JU,attachPlayoffStructures:()=>og,attachQualifyingStructure:()=>Zf,attachStructures:()=>ig,autoSeeding:()=>fv,automatedPlayoffPositioning:()=>Sc,automatedPositioning:()=>hc,checkValidEntries:()=>Sd,deleteAdHocMatchUps:()=>nP,drawMatic:()=>Od,findDrawDefinition:()=>fS,generateAdHocMatchUps:()=>Nu,generateAdHocRounds:()=>bd,generateAndPopulatePlayoffStructures:()=>ld,generateDrawDefinition:()=>_u,generateDrawMaticRound:()=>Ed,generateDrawStructuresAndLinks:()=>Td,generateDrawTypeAndModifyDrawDefinition:()=>Ad,generateQualifyingStructure:()=>id,generateVoluntaryConsolation:()=>LS,getAssignedParticipantIds:()=>Si,getAvailableMatchUpsCount:()=>gd,getAvailablePlayoffProfiles:()=>Iu,getDrawDefinitionTimeItem:()=>Dh,getDrawParticipantRepresentativeIds:()=>dS,getDrawTypeCoercion:()=>Pu,getEligibleVoluntaryConsolationParticipants:()=>mS,getMatchUpsMap:()=>Ae,getParticipantIdFinishingPositions:()=>lS,getPositionAssignments:()=>Cp,getPositionsPlayedOff:()=>Ac,getSeedingThresholds:()=>wh,getSeedsCount:()=>Du,getStructureSeedAssignments:()=>Fr,getTeamLineUp:()=>os,getValidGroupSizes:()=>Sp,isAdHoc:()=>fr,isCompletedStructure:()=>Jo,isValidForQualifying:()=>RS,luckyLoserDrawPositionAssignment:()=>PU,modifyDrawDefinition:()=>ZU,modifyDrawName:()=>sg,modifySeedAssignment:()=>OU,mutate:()=>sP,positionActions:()=>CS,pruneDrawDefinition:()=>eP,qualifierDrawPositionAssignment:()=>RU,query:()=>TP,removeDrawPositionAssignment:()=>fu,removeRoundMatchUps:()=>oP,removeSeededParticipant:()=>HU,removeStructure:()=>VU,renameStructures:()=>kU,resetDrawDefinition:()=>tP,resetVoluntaryConsolationStructure:()=>YE,setDrawParticipantRepresentativeIds:()=>bE,setPositionAssignments:()=>MU,setStructureOrder:()=>GU,setSubOrder:()=>iP,shiftAdHocRounds:()=>NU,swapAdHocRounds:()=>CU,swapDrawPositionAssignments:()=>bU,updateTeamLineUp:()=>Fi,withdrawParticipantAtDrawPosition:()=>EU});var sP={};Jt(sP,{addAdHocMatchUps:()=>fd,addDrawDefinitionTimeItem:()=>tg,addPlayoffStructures:()=>Dp,addQualifyingStructure:()=>WU,addVoluntaryConsolationStage:()=>BU,addVoluntaryConsolationStructure:()=>jf,alternateDrawPositionAssignment:()=>DU,assignDrawPosition:()=>rP,assignDrawPositionBye:()=>Dr,attachConsolationStructures:()=>JU,attachPlayoffStructures:()=>og,attachQualifyingStructure:()=>Zf,attachStructures:()=>ig,automatedPlayoffPositioning:()=>Sc,automatedPositioning:()=>hc,deleteAdHocMatchUps:()=>nP,luckyLoserDrawPositionAssignment:()=>PU,modifyDrawDefinition:()=>ZU,modifyDrawName:()=>sg,modifySeedAssignment:()=>OU,pruneDrawDefinition:()=>eP,qualifierDrawPositionAssignment:()=>RU,removeDrawPositionAssignment:()=>fu,removeRoundMatchUps:()=>oP,removeSeededParticipant:()=>HU,removeStructure:()=>VU,renameStructures:()=>kU,resetDrawDefinition:()=>tP,resetVoluntaryConsolationStructure:()=>YE,setDrawParticipantRepresentativeIds:()=>bE,setPositionAssignments:()=>MU,setStructureOrder:()=>GU,setSubOrder:()=>iP,shiftAdHocRounds:()=>NU,swapAdHocRounds:()=>CU,swapDrawPositionAssignments:()=>bU,updateTeamLineUp:()=>Fi,withdrawParticipantAtDrawPosition:()=>EU});var RE=t=>e=>t[e],Dm=(t=[])=>t.map(fe).filter(Boolean),rf=(t=[])=>t.map(gt).filter(Boolean),gt=(t={})=>RE(t)("participantId");var fe=(t={})=>RE(t)("matchUpId"),$c=(t={})=>RE(t)("drawId");function bE({representativeParticipantIds:t,drawDefinition:e}){if(!e)return{error:pr};if(!Array.isArray(t))return{error:G};let r=rf(e?.entries||[]);return t.length&&jt(t,r).length<t.length?{error:G}:ep({drawDefinition:e,extension:{name:BI,value:t}})}var $r="ABANDONED",oc="AWAITING_RESULT",Dt="BYE",Wo="CANCELLED",me="COMPLETED",Kc="DEAD_RUBBER",Ot="DEFAULTED",Ne="DOUBLE_DEFAULT",ge="DOUBLE_WALKOVER",Dn="IN_PROGRESS",_o="INCOMPLETE",OE="NOT_PLAYED",lr="RETIRED",Xi="SUSPENDED",zt="TO_BE_PLAYED",_t="WALKOVER",gR=[oc,me,Ot,Dn,_o,lr,Xi],WI=[oc,me,Ot,ge,Ne,Dn,_o,lr,Xi,_t],jI=[$r,oc,Dt,Wo,me,Kc,Ot,ge,Ne,Dn,_o,OE,lr,Xi,zt,_t],YI=[Dt,ge,Ne,me,Ot,lr,_t],qI=[$r,oc,Wo,Kc,Dn,_o,OE,Xi,zt,void 0],ae=[Wo,$r,me,Kc,Ot,ge,Ne,lr,_t],Nm=[$r,me,Ot,ge,Ne,Dn,lr,_t],$I=[Dn,_o,Xi,zt],KI={ABANDONED:$r,AWAITING_RESULT:oc,BYE:Dt,CANCELLED:Wo,COMPLETED:me,DEAD_RUBBER:Kc,DEFAULTED:Ot,DOUBLE_WALKOVER:ge,DOUBLE_DEFAULT:Ne,IN_PROGRESS:Dn,INCOMPLETE:_o,NOT_PLAYED:OE,RETIRED:lr,SUSPENDED:Xi,TO_BE_PLAYED:zt,WALKOVER:_t};var tt="MAIN",at="QUALIFYING",Ve="CONSOLATION",Be="VOLUNTARY_CONSOLATION",ce="PLAY_OFF",Mm=[tt,at,Ve,ce,Be],_s={[at]:1,[tt]:2,[ce]:3,[Ve]:3,[Be]:4},_E="finishingPositions",vE="aggregateEventStructures",xE={[tt]:1,[ce]:2,[Ve]:3,[at]:4,[Be]:5},IR={[ce]:1,[tt]:2,[Ve]:3,[at]:4,[Be]:5},zc="CLUSTER",hR="SEPARATE",si="WATERFALL",op="ITEM",Le="CONTAINER",Qr="DRAW",ip="RANDOM",sn="TOP_DOWN",ai="BOTTOM_UP",jn="POSITION",oo="WINNER",Yn="LOSER",qn="FIRST_MATCHUP",an="AD_HOC",kL="AD_HOC",la="FEED_IN",Qc="COMPASS",Xc="OLYMPIC",VL="SINGLE_ELIMINATION";var io="SINGLE_ELIMINATION",Jc="DOUBLE_ELIMINATION",Zc="FIRST_MATCH_LOSER_CONSOLATION",sp="FIRST_ROUND_LOSER_CONSOLATION",Oi="LUCKY_DRAW",nf="CURTIS_CONSOLATION",SR="CURTIS_CONSOLATION",zI="FEED_IN_CHAMPIONSHIP_TO_SF",Cm="FEED_IN_CHAMPIONSHIP_TO_SF",QI="FEED_IN_CHAMPIONSHIP_TO_QF",Rm="FEED_IN_CHAMPIONSHIP_TO_QF",XI="FEED_IN_CHAMPIONSHIP_TO_R16",bm="FEED_IN_CHAMPIONSHIP_TO_R16",wE="MODIFIED_FEED_IN_CHAMPIONSHIP",Om="MODIFIED_FEED_IN_CHAMPIONSHIP",ap="FEED_IN_CHAMPIONSHIP",dn="ROUND_ROBIN",so="ROUND_ROBIN_WITH_PLAYOFF",LE="DECIDER",FE="BACKDRAW",of={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"}},sf={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",_i="ROUND_OUTCOME",GE=[Qc,nf,Rm,bm,Cm,ap,QI,XI,zI,Zc,sp,Oi,Om,Xc,ce,so],BL=[an,Qc,nf,Jc,Rm,bm,Cm,ap,la,Zc,sp,Oi,Om,Xc,ce,dn,so,io],kE={MAIN:tt,QUALIFYING:at,CONSOLATION:Ve,ITEM:op,CONTAINER:Le,FIRST_MATCHUP:qn,WINNER:oo,LOSER:Yn,AD_HOC:an,FEED_IN:la,FLEX_ROUNDS:kL,COMPASS:Qc,PLAY_OFF:ce,OLYMPIC:Xc,KNOCKOUT:VL,SINGLE_ELIMINATION:io,DOUBLE_ELIMINATION:Jc,CURTIS:nf,FICSF:zI,FICQF:QI,FICR16:XI,MFIC:wE,VOLUNTARY_CONSOLATION:Be,FIRST_MATCH_LOSER_CONSOLATION:Zc,FIRST_ROUND_LOSER_CONSOLATION:sp,MODIFIED_FEED_IN_CHAMPIONSHIP:Om,FEED_IN_CHAMPIONSHIP_TO_R16:bm,FEED_IN_CHAMPIONSHIP_TO_QF:Rm,FEED_IN_CHAMPIONSHIP_TO_SF:Cm,FEED_IN_CHAMPIONSHIP:ap,LUCKY_DRAW:Oi,ROUND_ROBIN_WITH_PLAYOFF:so,ROUND_ROBIN:dn,DECIDER:LE,BACKDRAW:FE,COMPASS_ATTRIBUTES:of,OLYMPIC_ATTRIBUTES:sf,DRAW:Qr,RANDOM:ip,TOP_DOWN:sn,BOTTOM_UP:ai,WATERFALL:si,WIN_RATIO:vs,ROUND_OUTCOME:_i,MULTI_STRUCTURE_DRAWS:GE,generatedDrawTypes:BL,stageOrder:_s,finishOrder:xE,AGGREGATE_EVENT_STRUCTURES:vE,FINISHING_POSITIONS:_E},TR=kE;function ci(t,e,r){let n=m=>mt({element:m,name:mn})?.extension?.value,o=r?.deprioritizeCompleted,i=r?.mode===vE&&IR,s=r?.mode===_E&&xE,a=s||i||_s,c=m=>m?.stage===tt&&m?.stageSequence===1,u=m=>c(m)?-1:a[m?.stage],p=m=>m?.matchUps.every(({matchUpStatus:d})=>ae.includes(d)?1:-1);return o&&p(t)-p(e)||i&&u(t)-u(e)||(t?.stage&&a[t.stage]||0)-(e?.stage&&a[e.stage]||0)||(n(t)||0)-(n(e)||0)||!s&&!i&&(e?.positionAssignments?.length??1/0)-(t?.positionAssignments?.length??1/0)||(t?.stageSequence??0)-(e?.stageSequence??0)||(af(t)||0)-(af(e)||0)}function af(t){return(t?.matchUps||[]).reduce((e,r)=>{let n=(r.finishingPositionRange?.winner||[]).reduce((o,i)=>o+i,0);return!e||n<e?n:e},void 0)}function st(t){let e=lt(t,[{[Yr]:!0,[dm]:!0}]);if(e.error)return e;let{drawDefinition:r,structureId:n}=t,{structures:o}=xn({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===op?i?.find(c=>c.structures?.some(u=>u.structureId===n)):void 0;return{structure:s,containingStructure:a}}function xn({withStageGrouping:t,drawDefinition:e,stageSequences:r,stageSequence:n,roundTarget:o,sortConfig:i,stages:s,stage:a}){let c=!e&&X||!e?.structures&&Il||void 0;if(c)return{error:c,structures:[],stageStructures:{}};let u=f=>{let g=mt({element:f,name:mn})?.extension?.value;return!o||o===g},p=e?.structures?.filter(d).filter(l).filter(u).sort((f,g)=>ci(f,g,i))??[],m=t?Object.assign({},...Mm.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 JI({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}=Nt({structure:n}),s=i?.map(gt).filter(Boolean)??[];return e[o].push(...s),s}).flat(),stagePositionedParticipantIds:e}}function Nt({drawDefinition:t,structureId:e,structure:r}){let n,o=[];if(!r){if(!t)return{positionAssignments:o,error:X};if({structure:r,error:n}=st({drawDefinition:t,structureId:e}),n)return{positionAssignments:o,error:n}}return r.structures?o=[].concat(...r.structures.map(i=>Nt({structure:i}).positionAssignments)):r.positionAssignments?o=r.positionAssignments:n=Sy,{positionAssignments:o,error:n}}function de({drawDefinition:t,structureId:e,structure:r}){let n=Nt({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",cp="addMatchUps",jo="addParticipants",uf="addScaleItems",ZI="addVenue",fa="audit",pf="deleteParticipants",mf="deleteVenue",df="deletedDrawIds",lf="deletedMatchUpIds",ff="modifyDrawDefinition",VE="modifyDrawEntries",BE="modifyEventEntries",gf="modifyMatchUp",Qe="modifyParticipants",If="modifyPositionAssignments",hf="modifySeedAssignments",HE="modifyTournamentDetail",ui="modifyVenue",_m="mutations",th="publishEvent",WE="publishEventSeeding",jE="publishOrderOfPlay",Sf="unPublishEvent",Tf="unPublishEventSeeding",Af="unPublishOrderOfPlay",up="updateInContextMatchUp",AR={ADD_DRAW_DEFINITION:cf,ADD_MATCHUPS:cp,ADD_PARTICIPANTS:jo,ADD_SCALE_ITEMS:uf,ADD_VENUE:ZI,AUDIT:fa,DELETE_PARTICIPANTS:pf,DELETE_VENUE:mf,DELETED_DRAW_IDS:df,DELETED_MATCHUP_IDS:lf,MODIFY_DRAW_DEFINITION:ff,MODIFY_DRAW_ENTRIES:VE,MODIFY_EVENT_ENTRIES:BE,MODIFY_MATCHUP:gf,MODIFY_PARTICIPANTS:Qe,MODIFY_POSITION_ASSIGNMENTS:If,MODIFY_SEED_ASSIGNMENTS:hf,MODIFY_TOURNAMENT_DETAIL:HE,MODIFY_VENUE:ui,MUTATIONS:_m,PUBLISH_EVENT_SEEDING:WE,PUBLISH_EVENT:th,PUBLISH_ORDER_OF_PLAY:jE,UNPUBLISH_EVENT_SEEDING:Tf,UNPUBLISH_EVENT:Sf,UNPUBLISH_ORDER_OF_PLAY:Af,UPDATE_INCONTEXT_MATCHUP:up};function eh(t,e){if(!t)return{error:X};let r=Date.now();t.updatedAt&&r===new Date(t.updatedAt).getTime()&&(r+=1);let n=new Date(r).toISOString(),o=e?.filter(Boolean);return t.updatedAt=n,t.structures?.filter(Boolean).forEach(i=>{(!o?.length||o?.includes(i.structureId))&&(i.updatedAt=n)}),{...R}}function So({drawDefinition:t,tournamentId:e,matchUps:r,eventId:n}){return t&&eh(t),Tt({payload:{matchUps:r,tournamentId:e,eventId:n},topic:cp}),{...R}}function wn({drawDefinition:t,tournamentId:e,matchUpIds:r,eventId:n,action:o}){t&&eh(t),Tt({topic:lf,payload:{tournamentId:e,matchUpIds:r,eventId:n,action:o}});for(let i of r)NI({key:i});return{...R}}function It({drawDefinition:t,tournamentId:e,structureId:r,context:n,eventId:o,matchUp:i}){return i?(t&&bt({drawDefinition:t,structureIds:r?[r]:void 0,tournamentId:e,eventId:o}),Tt({topic:gf,payload:{matchUp:i,tournamentId:e,context:n},key:i.matchUpId}),{...R}):(console.log(sr),{error:sr})}function yR({tournamentId:t,inContextMatchUp:e}){return e?(Tt({payload:{inContextMatchUp:e,tournamentId:t},topic:up,key:e.matchUpId}),{...R}):{error:sr}}function ga({tournamentId:t,eventId:e,drawDefinition:r}){return r?(eh(r),Tt({payload:{drawDefinition:r,tournamentId:t,eventId:e},topic:cf,key:r.drawId}),{...R}):(console.log(X),{error:X})}function ER({tournamentId:t,eventId:e,drawId:r}){return Tt({payload:{drawId:r,tournamentId:t,eventId:e},topic:df,key:r}),NI({key:r}),{...R}}function bt({drawDefinition:t,tournamentId:e,structureIds:r,eventId:n}){return t?(eh(t,r),Tt({payload:{tournamentId:e,eventId:n,drawDefinition:t},topic:ff,key:t.drawId}),{...R}):{error:X}}function rh({drawDefinition:t,tournamentId:e,structure:r,eventId:n}){if(!t)return{error:X};if(!r)return{error:Do};let o=r.seedAssignments,i=r.structureId,s=t.drawId;return Tt({payload:{tournamentId:e,eventId:n,drawId:s,structureId:i,seedAssignments:o},topic:hf,key:t.drawId}),bt({structureIds:[i],drawDefinition:t,tournamentId:e,eventId:n}),{...R}}function To({drawDefinition:t,tournamentId:e,structure:r,event:n}){if(!t)return{error:X};if(!r)return{error:Do};let o=Nt({structure:r}),i=r.structureId,s=t.drawId,a=n?.eventId;return Tt({topic:If,payload:{positionAssignments:o,tournamentId:e,structureId:i,eventId:a,drawId:s},key:i}),bt({structureIds:[i],drawDefinition:t,tournamentId:e,eventId:a}),{...R}}function YE({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=[],wn({tournamentId:t?.tournamentId,action:"resetVoluntaryConsolationStructure",matchUpIds:i,drawDefinition:e}),r&&(e.entries=e.entries.filter(s=>s.entryStage!==Be)),bt({tournamentId:t?.tournamentId,eventId:n?.eventId,drawDefinition:e,structureIds:[o.structureId]}),{...R}}function vm({drawPositions:t,structure:e}){if([at,tt].includes(e.stage)&&e.stageSequence===1)return;let{positionAssignments:r}=Nt({structure:e});r?.filter(({drawPosition:o})=>t?.includes(o))?.forEach(o=>{St({element:o,extension:{name:ym,value:!0}})})}function tu({drawDefinition:t,positionAction:e}){let{extension:r}=mt({name:Tm,element:t}),n=Array.isArray(r?.value)?r?.value??[]:[];if(!n?.length){let i=t.structures.find(s=>s.stage===tt);if(i){let s=Nt({structure:i}).positionAssignments?.map(({drawPosition:a,participantId:c,bye:u,qualifier:p})=>({drawPosition:a,participantId:c,qualifier:p,bye:u}));n.push({name:"initialMainAssignments",initialAssignments:s})}}let o={name:Tm,value:n.concat(e)};St({element:t,extension:o})}function Ji({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 Ia="SINGLES",Xt="SINGLES",vi="DOUBLES",Gt="DOUBLES",ln="TEAM",Bt="TEAM",UR={SINGLES_MATCHUP:Ia,SINGLES:Xt,DOUBLES_MATCHUP:vi,DOUBLES:Gt,TEAM_MATCHUP:ln,TEAM:Bt};function eu(t){let{sides:e,matchUpType:r}=t||{},n=t.potentialParticipants?.length?t.potentialParticipants.flat().map(s=>r===Gt?s?.individualParticipantIds||[]:s.participantId).flat():[],o=(e||[]).map(s=>r===Gt&&(s?.participant?.individualParticipantIds||[])||s?.participantId&&[s.participantId]||[]).flat();return{individualParticipantIds:o.concat(n).flat(),enteredIndividualParticipantIds:o,potentialIndividualParticipantIds:n}}function Xr(t){return t?.tournamentRecords??(t?.tournamentRecord&&{[t.tournamentRecord.tournamentId]:t.tournamentRecord})??{}}function yf(t){if(!Rt(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 Ur(t){return Array.isArray(t)?t.every(yf):!1}function He({matchUps:t=[],interpolate:e}){if(!Ur(t))return{roundMatchUps:[],error:G};let r=t.reduce((d,l)=>{let f=typeof l.roundNumber=="string"?ct(l.roundNumber):l.roundNumber;return!l.roundNumber||d.includes(f)?d:d.concat(f)},[]).sort(se).map(d=>{let l=t.filter(h=>h.roundNumber===d),g=l.find(({matchUpType:h})=>h===Bt)?l.filter(({matchUpType:h})=>h===Bt):l,I=h=>h.sort((S,T)=>se(S.roundPosition,T.roundPosition));return{[d]:I(g)}}),n=t.reduce((d,l)=>{let f=typeof l.roundNumber=="string"?ct(l.roundNumber):l.roundNumber;return d[f]||(d[f]=rt({abbreviatedRoundName:l.abbreviatedRoundName,finishingRound:l.finishingRound,roundName:l.roundName})),d},{}),o=Object.assign({},...r);if(e){let d=Math.max(...Object.keys(o).map(f=>ct(f)).filter(f=>!isNaN(f))),l=o[d]?.length;if(l>1&&Tn(l)){let f=d+1,g=f+l/2;Z(f,g).forEach((h,S)=>{o[h]=Z(0,l/(2+S*2)).map(()=>({}))})}}let i=0,s=Object.assign({},...Object.keys(o).map(d=>{let l=o[d]?.length,f=o[d]?.filter(I=>!ae.includes(I.matchUpStatus)&&!I.score?.scoreStringSide1)?.length,g=l&&l===f;return i=Math.max(i,l),{[d]:{matchUpsCount:l,inactiveCount:f,inactiveRound:g}}})),a=0,c=0,u=Object.keys(o).map(d=>ct(d)).filter(d=>!isNaN(d));u.forEach(d=>{let l=o[d].sort((g,I)=>g.roundPosition-I.roundPosition),f=l.map(g=>g?.drawPositions||[]).flat();if(s[d].roundNumber=d,s[d].roundFactor=s[d].matchUpsCount?i/s[d].matchUpsCount:1,s[d].finishingRound=n[d]?.finishingRound,s[d].roundName=n[d]?.roundName,s[d].abbreviatedRoundName=n[d]?.abbreviatedRoundName,s[d].finishingPositionRange=o[d]?.[0]?.finishingPositionRange,d===1||!s[d-1]){let g=f.sort(se),I=Te(g,2);s[d].drawPositions=g,s[d].pairedDrawPositions=I}else{let g=s[d-1],I=g.drawPositions,h=g.matchUpsCount/s[d].matchUpsCount,S=Te(I,h),T=l.map(A=>{let{roundPosition:D}=A,y=[...A.drawPositions||[],void 0,void 0].slice(0,2);if(!D)return y;let E=y?.filter(Boolean)||[];if(!E?.length)return[void 0,void 0];if(d<3&&E?.length===2)return y?.slice().sort(se);let U=jt(I,E).length!==E?.length;if(E?.length&&U)return E?.length===1?[E[0],void 0]:y?.slice().sort(se);let M=(D-1)*2;return S.slice(M,M+2).map(N=>E?.find(C=>N.includes(C)))});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})=>!Tn(d));return{hasNoRoundPositions:t.some(d=>!d.roundPosition),roundsNotPowerOf2:p,maxMatchUpsCount:i,roundMatchUps:o,roundNumbers:u,roundProfile:s,...R}}function Zi({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 qE=t=>e=>!t||typeof e!="object"?void 0:Array.isArray(t)&&t.map(r=>({[r]:Zi({element:e,accessor:r})?.value}))||typeof t=="object"&&Object.keys(t).map(r=>({[r]:Zi({element:e,accessor:r})?.value}))||(typeof t=="string"&&Zi({element:e,accessor:t}))?.value,Pr=qE;function ha({finishingPositionOffset:t=0,finishingPositionLimit:e,positionsFed:r,roundsCount:n,roundLimit:o,matchUps:i,lucky:s,fmlc:a}){if(!Ur(i))return[];let{roundProfile:c,roundNumbers:u=[]}=He({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(Pr("matchUpsCount")),l=(I,h)=>{let S=Math.min(...I);m&&h&&S===1&&(S=m);let T=Math.max(...I);return e&&T>e&&(T=e),[S,T]},f=c&&Object.assign({},...u.map(I=>{let h=(n??0)+1-I-p,S=c[I].matchUpsCount,T={finishingPositionRange:{},finishingRound:h},A=d?.slice(I-1).reduce((C,O)=>C+(O||0),0),D=a&&I!==1,y=1+t+(D?r??0:0),E=1,U=Z(y,s?y+S*2:A+y+E),M=A+E-S,P=l(U.slice(M)),N=l(U.slice(0,M),!0);return T.finishingPositionRange={loser:P,winner:N},{[I]:T}})),g=yr({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 Ae({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 Yo({mappedMatchUps:t,matchUpsMap:e,structureId:r,inContext:n}){t=e?.mappedMatchUps??t;let o=t[r],i=(o?.itemStructureIds||[]).map(s=>{let{matchUps:a,structureName:c}=t[s];return n?a.map(u=>Object.assign(J(u,!0,!0),{containerStructureId:r,structureId:s,structureName:c})):a}).flat();return(o?.matchUps||[]).concat(...i)}var ic="SIGN_IN_STATUS",$E="SIGNED_OUT",ru="SIGNED_IN",Jr="TEAM",ht="INDIVIDUAL",Ar="GROUP",dt="PAIR",kt="TEAM",nu={TEAM_PARTICIPANT:Jr,INDIVIDUAL:ht,GROUP:Ar,TEAM:kt,PAIR:dt},PR={INDIVIDUAL:ht,GROUP:Ar,PAIR:dt,TEAM:kt,SIGN_IN_STATUS:ic,SIGNED_OUT:$E,SIGNED_IN:ru};function xm({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===kt),s=o.filter(c=>c.participantType===Ar),a=o.filter(c=>c.participantType===dt);return o.forEach(c=>{if(c.participantType===ht){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 Ef({drawDefinition:t,attributes:e}){let{extension:r}=mt({element:t,name:Um}),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:Um,value:n},ep({drawDefinition:t,extension:r}),{entryProfile:n}}function ou({drawDefinition:t}){let{extension:e}=mt({element:t,name:Um});return{entryProfile:e?.value||{}}}var wr="ALTERNATE",Uf="CONFIRMED",Zr="DIRECT_ACCEPTANCE",wm="FEED_IN",Pf="JUNIOR_EXEMPT",ts="LUCKY_LOSER",Df="ORGANISER_ACCEPTANCE",Lm="QUALIFIER",HL="REGISTERED",Nf="SPECIAL_EXEMPT",Lr="UNGROUPED",pi="UNPAIRED",iu="WILDCARD",Ao="WITHDRAWN",Mf=[Uf,Zr,Pf,Df,Nf],KE=[wm,ts,Lm],qo=[Uf,Zr,wm,Pf,Df,Nf,iu],Or=[Uf,Zr,Pf,ts,Lm,Df,Nf,iu],zE=[wr,Uf,Zr,wm,Pf,ts,Df,Lm,HL,Nf,Lr,pi,iu,Ao],DR={ALTERNATE:wr,CONFIRMED:Uf,DIRECT_ACCEPTANCE:Zr,DIRECT_ENTRY_STATUSES:qo,DRAW_SPECIFIC_STATUSES:KE,EQUIVALENT_ACCEPTANCE_STATUSES:Mf,FEED_IN:wm,JUNIOR_EXEMPT:Pf,LUCKY_LOSER:ts,ORGANISER_ACCEPTANCE:Df,QUALIFIER:Lm,SPECIAL_EXEMPT:Nf,STRUCTURE_SELECTED_STATUSES:Or,UNGROUPED:Lr,UNPAIRED:pi,VALID_ENTRY_STATUSES:zE,WILDCARD:iu,WITHDRAWN:Ao};function Cf({stage:t,drawDefinition:e}){let{entryProfile:r}=ou({drawDefinition:e}),n=Object.keys(r).includes(t);if(!n&&Mm.includes(t)){let o=[{[t]:{drawSize:void 0,alternates:!0}}];return Ef({drawDefinition:e,attributes:o}),!0}return n}function NR({stage:t,drawDefinition:e}){let{entryProfile:r}=ou({drawDefinition:e});return r[t]?.alternates||0}function MR({stage:t,drawDefinition:e}){let{entryProfile:r}=ou({drawDefinition:e});return r[t]?.wildcardsCount||0}function nh({stage:t,drawDefinition:e,entryStatus:r}){return e.entries.reduce((n,o)=>o.entryStage===t&&o.entryStatus===r?n+1:n,0)}function mi({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:mn,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===ce){let{playoffEntries:p,error:m}=WL({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 WL({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}=st({drawDefinition:e,structureId:s});a?.structureType===Le&&(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:Ho}).extension?.value;return T&&S?{[S]:T}:void 0}).filter(Boolean)),g=Object.keys(l).reduce((h,S)=>{let T=l[S],A=T.groupOrder||t&&T.provisionalOrder;return h.includes(A)||h.push(A),h},[]).length===Object.keys(l).length,I=Object.keys(l).filter(h=>{let S=l[h],T=S.groupOrder||t&&S.provisionalOrder;return i?.includes(T)});(!t||g)&&I.forEach(h=>{let S=l[h],{groupOrder:T,provisionalOrder:A,GEMscore:D}=S,y=T||t&&A,E=[...i??[]].sort(se).indexOf(y)+1;n.push({entryStage:ce,entryStatus:wm,placementGroup:E,groupingValue:d,participantId:h,GEMscore:D})})})}return{playoffEntries:n}}function CR({stage:t,drawDefinition:e}){return qo.reduce((r,n)=>(nh({drawDefinition:e,entryStatus:n,stage:t})||0)+r,0)}function Fr({provisionalPositioning:t,returnAllProxies:e,drawDefinition:r,structureId:n,structure:o}){let i,s=[];o||({structure:o,error:i}=st({drawDefinition:r,structureId:n}));let a=Nt({structure:o}).positionAssignments;if(i||!o)return{seedAssignments:[],error:Lt};n||(n=o.structureId);let{stage:c,stageSequence:u}=o,m=c===ce&&r&&mi({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=uy;let f=o.seedLimit??o?.positionAssignments?.length;return{seedAssignments:s,stageSequence:u,seedLimit:f,stage:c,error:i}}var oh="WALKOVER",QE="RETIRED",Fm="COMPETITIVE",sc="ROUTINE",ac="DECISIVE",Gm="winRatio";var jL=(t,e)=>(t||0)+(e||0);function ih(t,e){let r=Array.isArray(t)?t[0]:t;return isNaN(r)&&oh||r<=e[ac]&&ac||r<=e[sc]&&sc||Fm}function sh({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(jL)&&(r[n[0]>n[1]?0:1]+=1),{sets:e,games:r,score:t}}function YL(t){let e=Math.min(...t.games),r=Math.max(...t.games);return Math.round(e/r*100)}function ah(t){return t.map(YL).sort().map(e=>parseFloat(e.toFixed(2)))}function Pt({onlySpecifiedPolicyTypes:t=!1,policyTypes:e=[],tournamentRecord:r,drawDefinition:n,structure:o,event:i}){if(!Array.isArray(e))return{error:lI};let s={};return r&&a(r),i&&a(i),n&&a(n),o&&a(o),{appliedPolicies:s,...R};function a(c){let p=c?.extensions?.find(m=>m.name===jc)?.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 yo({policyTypes:t=[],tournamentRecord:e,drawDefinition:r,structure:n,event:o}){if(!Array.isArray(t))return{error:lI};let{appliedPolicies:i}=Pt({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:Lc.message}}function $o({tournamentRecord:t,drawDefinition:e,policyType:r,structure:n,event:o}){if(!t)return{error:W};let{appliedPolicies:i}=Pt({tournamentRecord:t,drawDefinition:e,structure:n,event:o});return i?.[r]?{policy:i[r]}:{info:Lc?.message}}var qL={[ii]:{policyName:"Competitive Bands Default",profileBands:{[ac]:20,[sc]:50}}},km=qL;function su({tournamentRecord:t,profileBands:e,matchUp:r}){if(!r)return{error:sr};let{score:n,winningSide:o}=r;if(!o)return{error:G};let i=!e&&t&&$o({policyType:ii,tournamentRecord:t}).policy,s=e||i?.profileBands||km[ii].profileBands,a=sh({score:n}),c=ah([a]),u=ih(c,s),p=Array.isArray(c)?c[0]:c;return{...R,competitiveness:u,pctSpread:p}}function ch({matchUp:t}){if(!t)return{error:sr};if(t&&!t.sides)return{error:Je};if(t&&!t.hasContext)return{error:Gc};let e=(t.sides??[])?.map(a=>a?.participantId).filter(Boolean),r=t.sides?.filter(a=>a.participant?.participantType===ht).map(a=>a.participantId).filter(Boolean)??[],o=((t.sides??[])?.map(a=>a.participant?.individualParticipants).filter(Boolean)??[]).map(a=>(a??[]).map(c=>c?.participantId).filter(Boolean)),i=[...r,...o.flat()].filter(Boolean)??[],s=pt(i.concat(e)).filter(Boolean)??[];return{nestedIndividualParticipantIds:o,allRelevantParticipantIds:s,individualParticipantIds:i,sideParticipantIds:e,...R}}var Vm="CHECK_IN",Bm="CHECK_OUT",RR="SCHEDULE",xs="SCHEDULE.ASSIGNMENT.VENUE",Eo="SCHEDULE.ALLOCATION.COURTS",di="SCHEDULE.ASSIGNMENT.COURT",Rf="SCHEDULE.COURT.ORDER",ws="SCHEDULE.DATE",$L="COMPLETED.DATE",XE="SCHEDULE.ASSIGN.OFFICIAL",Ls="SCHEDULE.TIME.SCHEDULED",Uo="SCHEDULE.TIME.START",xi="SCHEDULE.TIME.STOP",li="SCHEDULE.TIME.RESUME",fi="SCHEDULE.TIME.END",bf="SCHEDULE.TIME.MODIFIERS",bR="TO_BE_ANNOUNCED",OR="NEXT_AVAILABLE",_R="FOLLOWED_BY",vR="AFTER_REST",xR="RAIN_DELAY",KL="NOT_BEFORE",uh=[bR,OR,_R,vR,xR],zL="ELIGIBILITY",QL="REGISTRATION",XL="SUSPENSION",JL="MEDICAL",ZL="PENALTY",JE="SCALE",ZE="RATING",tU="RANKING",Of="SEEDING",Ko="PUBLISH",Gr="PUBLIC",zo="STATUS",tF="MODIFICATION",eF="RETRIEVAL",rF="other",wR={MUTUALLY_EXCLUSIVE_TIME_MODIFIERS:uh,AFTER_REST:vR,ALLOCATE_COURTS:Eo,ASSIGN_COURT:di,ASSIGN_OFFICIAL:XE,ASSIGN_VENUE:xs,CHECK_IN:Vm,CHECK_OUT:Bm,COMPLETED_DATE:$L,COURT_ORDER:Rf,ELIGIBILITY:zL,END_TIME:fi,FOLLOWED_BY:_R,MEDICAL:JL,MODIFICATION:tF,NEXT_AVAILABLE:OR,NOT_BEFORE:KL,OTHER:rF,PENALTY:ZL,PUBLIC:Gr,PUBLISH:Ko,RANKING:tU,RATING:ZE,RAIN_DELAY:xR,REGISTRATION:QL,RESUME_TIME:li,RETRIEVAL:eF,SCALE:JE,SCHEDULE:RR,SCHEDULED_DATE:ws,SCHEDULED_TIME:Ls,SEEDING:Of,START_TIME:Uo,STATUS:zo,STOP_TIME:xi,SUSPENSION:XL,TIME_MODIFIERS:bf,TO_BE_ANNOUNCED:bR};function es({matchUp:t}){if(!t)return{error:sr};if(!t.hasContext)return{error:Gc};if(!t.sides||t.sides.filter(Boolean).length!==2)return{error:Je};let{nestedIndividualParticipantIds:e,allRelevantParticipantIds:r,sideParticipantIds:n}=ch({matchUp:t}),i=(t.timeItems??[]).filter(u=>u?.itemType&&[Vm,Bm].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===Vm);e?.forEach((u,p)=>{let m=n?.[p],d=u?.length&&u.every(l=>a.includes(l));m&&d&&!a.includes(m)&&a.push(m)}),n?.forEach((u,p)=>{a.includes(u)&&(e?.[p]??[]).forEach(m=>{m&&!a.includes(m)&&a.push(m)})});let c=n?.reduce((u,p)=>a.includes(p)&&u,!0);return{allRelevantParticipantIds:r,allParticipantsCheckedIn:c,checkedInParticipantIds:a,...R}}var ph={[Xt]:[Xt,"S"],[Gt]:[Gt,"D"],[Bt]:[Bt,"T"],S:[Xt,"S"],D:[Gt,"D"],T:[Bt,"T"]};var ie=t=>e=>{let r=Rt(e)&&e?.matchUpType||$e(e)&&e;return r&&ph[t].includes(r)};function pp(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 mp(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 mh({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 LR({tournamentScheduling:t,eventScheduling:e,averageMinutes:r,defaultTiming:n,matchUpFormat:o,categoryName:i,categoryType:s,policy:a}){let c=e?.matchUpRecoveryTimes&&mp({...e,averageMinutes:r,matchUpFormat:o}),u=t?.matchUpRecoveryTimes&&mp({...t,averageMinutes:r,matchUpFormat:o}),p=a?.matchUpRecoveryTimes&&mp({...a,averageMinutes:r,matchUpFormat:o}),m=[c,u,p,a?.defaultTimes?.recoveryTimes,n?.recoveryTimes];return mh({categoryName:i,categoryType:s,timesBlockArray:m})}function FR({matchUpFormat:t,categoryName:e,categoryType:r,defaultTiming:n,tournamentScheduling:o,eventScheduling:i,policy:s}){let a=i?.matchUpAverageTimes&&pp({...i,matchUpFormat:t}),c=o?.matchUpAverageTimes&&pp({...o,matchUpFormat:t}),u=s?.matchUpAverageTimes&&pp({...s,matchUpFormat:t}),p=[a,c,u,s?.defaultTimes?.averageTimes,n?.averageTimes];return mh({categoryName:e,categoryType:r,timesBlockArray:p})}function Sa({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}=$o({policyType:go,tournamentRecord:t,event:n}),s=(t?mt({element:t,name:Oo}).extension:void 0)?.value,c=(n&&mt({name:Oo,element:n}).extension)?.value;return{scheduleTiming:{tournamentScheduling:s,eventScheduling:c,categoryName:e,categoryType:r,policy:o}}}var eU="DOUBLES_SINGLES",rU="SINGLES_DOUBLES",$n="total",dh="participantConflict",Ta="matchUpConflict",nU="ISSUE_IDS",cc="CONFLICT",uc="WARNING",lh="ERROR",fh="ISSUE",_f="STATE",GR={SINGLES_DOUBLES:rU,DOUBLES_SINGLES:eU,TOTAL:$n,CONFLICT_MATCHUP_ORDER:Ta,CONFLICT_PARTICIPANTS:dh,SCHEDULE_ISSUE_IDS:nU,SCHEDULE_CONFLICT:cc,SCHEDULE_WARNING:uc,SCHEDULE_ERROR:lh,SCHEDULE_ISSUE:fh,SCHEDULE_STATE:_f};var ao="SINGLES",Fs="SINGLES",Kr="DOUBLES",gi="DOUBLES",Fe="TEAM",kr="TEAM",nF="AGE",oF="RATING",iF="BOTH",kR={AGE:nF,BOTH:iF,DOUBLES:Kr,DOUBLES_EVENT:gi,RATING:oF,SINGLES:ao,SINGLES_EVENT:Fs,TEAM_EVENT:kr,TEAM:Fe};function au({defaultAverageMinutes:t=90,defaultRecoveryMinutes:e=0,tournamentRecord:r,matchUpFormat:n,categoryName:o,categoryType:i,eventType:s,event:a}){if(!r)return{error:W};s=s??a?.eventType??Fs;let c={averageTimes:[{minutes:{default:t}}],recoveryTimes:[{minutes:{default:e}}]},{scheduleTiming:u}=Sa({tournamentRecord:r,categoryName:o,categoryType:i,event:a}),p={...u,matchUpFormat:n,categoryType:i,defaultTiming:c};return dp({eventType:s,timingDetails:p})}function dp({timingDetails:t,eventType:e}){let r=FR(t),n=Object.keys(r?.minutes||{}),o=r?.minutes&&(n?.includes(e)&&r.minutes[e]||r.minutes.default),i=LR({...t,averageMinutes:o}),s=Object.keys(i?.minutes||{}),a=i?.minutes&&(s?.includes(e)&&i.minutes[e]||i.minutes.default),c=ie(Fs)(e)?rU:eU,u=i?.minutes&&(s?.includes(c)&&i.minutes[c]||a);return{averageMinutes:o,recoveryMinutes:a,typeChangeRecoveryMinutes:u}}function gh(t){return t.createdAt?new Date(t.createdAt).getTime():0}function vo({visibilityThreshold:t,timeItems:e,itemType:r}){let n=e.filter(i=>i&&i.itemType===r&&(!t||gh(i)<new Date(t).getTime())).sort((i,s)=>gh(i)-gh(s)).pop(),o=n&&gh(n);return{itemValue:n?.itemValue,timeStamp:o}}function vf({visibilityThreshold:t,timeStamp:e,schedule:r,matchUp:n}){let{itemValue:o,timeStamp:i}=vo({timeItems:n?.timeItems||[],itemType:Ls,visibilityThreshold:t});return!r||i&&e&&new Date(i).getTime()>new Date(e).getTime()?{scheduledTime:o}:r}function rs({visibilityThreshold:t,timeStamp:e,schedule:r,matchUp:n}){let{itemValue:o,timeStamp:i}=vo({timeItems:n?.timeItems||[],itemType:ws,visibilityThreshold:t});return!r||i&&e&&new Date(i).getTime()>new Date(e).getTime()?{scheduledDate:o}:r}function Ih({visibilityThreshold:t,timeStamp:e,schedule:r,matchUp:n}){let{itemValue:o,timeStamp:i}=vo({timeItems:n?.timeItems||[],itemType:Eo,visibilityThreshold:t});return!r||i&&e&&new Date(i).getTime()>new Date(e).getTime()?{allocatedCourts:J(o,!1,!0)}:r}function hh({visibilityThreshold:t,timeStamp:e,schedule:r,matchUp:n}){let{itemValue:o,timeStamp:i}=vo({timeItems:n?.timeItems||[],itemType:di,visibilityThreshold:t});return!r||i&&e&&new Date(i).getTime()>new Date(e).getTime()?{courtId:o}:r}function Sh({visibilityThreshold:t,timeStamp:e,schedule:r,matchUp:n}){let{itemValue:o,timeStamp:i}=vo({timeItems:n?.timeItems||[],itemType:xs,visibilityThreshold:t});return!r||i&&e&&new Date(i).getTime()>new Date(e).getTime()?{venueId:o}:r}function xf({visibilityThreshold:t,timeStamp:e,schedule:r,matchUp:n}){let{itemValue:o,timeStamp:i}=vo({timeItems:n?.timeItems||[],itemType:bf,visibilityThreshold:t});return!r||i&&e&&new Date(i).getTime()>new Date(e).getTime()?{timeModifiers:o}:r}function lp(t){if(xI.test(t)){let e=zl();return new Date(`${e}T${t}`)}else return new Date(t)}function VR({matchUp:t}){if(!t)return{error:sr};if(!t.timeItems)return{error:_l};let e=t.timeItems.filter(n=>[Uo,xi,li,fi].includes(n?.itemType)).sort((n,o)=>lp(n.itemValue).getTime()-lp(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 Uo:i=0;break;case fi:if(n.lastValue&&[Uo,li].includes(n.lastType)){let u=lp(o.itemValue).getTime()-lp(n.lastValue).getTime();i=n.milliseconds+u}else i=n.milliseconds;break;case xi:if([Uo,"SCHECULE.TIME.RESUME"].includes(n.lastType)){let u=lp(o.itemValue).getTime()-lp(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([Uo,li].includes(r.lastType)){let n=new Date().getTime()-lp(r.lastValue).getTime();r.milliseconds+=n}return{milliseconds:r.milliseconds,time:sF(r.milliseconds),relevantTimeItems:e}}function sF(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 BR({visibilityThreshold:t,timeStamp:e,schedule:r,matchUp:n}){let{itemValue:o,timeStamp:i}=vo({timeItems:n?.timeItems||[],itemType:Rf,visibilityThreshold:t});return!r||i&&e&&new Date(i).getTime()>new Date(e).getTime()?{courtOrder:o}:r}function HR({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===Uo&&s;return a&&(!i||r(a)<r(i))?a:i},void 0)?.itemValue}}function WR(t=1){return Z(0,t).map(Mt)}function Mt(){let t=[];for(let i=0;i<256;i++)t[i]=(i<16?"0":"")+i.toString(16);let e=Math.random()*4294967295|0,r=Math.random()*4294967295|0,n=Math.random()*4294967295|0,o=Math.random()*4294967295|0;return t[e&255]+t[e>>8&255]+t[e>>16&255]+t[e>>24&255]+"-"+t[r&255]+t[r>>8&255]+"-"+t[r>>16&15|64]+t[r>>24&255]+"-"+t[n&63|128]+t[n>>8&255]+"-"+t[n>>16&255]+t[n>>24&255]+t[o&255]+t[o>>8&255]+t[o>>16&255]+t[o>>24&255]}function pc(t){let{disableNotice:e,venue:r,context:n}=t;if(typeof r!="object")return{error:G};let o=Xr(t);r.venueId||(r.venueId=Mt());let i;for(let s of Object.values(o)){let a=aF({disableNotice:!0,tournamentRecord:s,context:n,venue:r});if(a?.error)return a;i=a.venue}return e||Tt({topic:ZI,payload:{venue:r}}),rt({...R,venue:i})}function aF({tournamentRecord:t,disableNotice:e,context:r,venue:n}){return t?n?(t.venues||(t.venues=[]),n.venueId||(n.venueId=Mt()),t.venues.reduce((i,s)=>i||s.venueId===n.venueId,void 0)?{error:Hy}:(r&&St({element:n,extension:{value:r,name:yE}}),t.venues.push(n),e||Tt({payload:{venue:n,tournamentId:t.tournamentId},topic:ZI}),{...R,venue:J(n)})):{error:et,info:"missing venue"}:{error:W}}function Qo({tournamentRecords:t,tournamentRecord:e,venueId:r}){if(!e)return{error:W};if(!r)return{error:Bo};let o=(e.venues??[]).reduce((i,s)=>s.venueId===r?s:i,void 0);if(!o&&t){let s=(qc({tournamentRecords:t}).linkedTournamentIds??[])[e.tournamentId];for(let a of s){let c=t[a],u=Qo({tournamentRecord:c,venueId:r});if(u.success&&u.venue)return pc({tournamentRecord:e,venue:u.venue}),{...R,venue:o}}}return o?{...R,venue:o}:{error:Ds}}function Th({convertExtensions:t,...e}){let{tournamentRecords:r,tournamentRecord:n,venueId:o}=e,i=Qo({tournamentRecords:r,tournamentRecord:n,venueId:o});return J(i,t,!0)}function ns({tournamentRecords:t,tournamentRecord:e,courtId:r}){if(!e)return{error:W};if(!r)return{error:Ni};let n="findCourt",o,i;if((e.venues??[]).forEach(s=>{(s.courts??[]).forEach(a=>{a.courtId===r&&(o=a,i=s)})}),o)return{...R,court:o,venue:i};if(t){let a=(qc({tournamentRecords:t}).linkedTournamentIds??[])[e.tournamentId];for(let c of a){let u=t[c],p=ns({tournamentRecord:u,courtId:r});if(p.success)return p.venue&&pc({tournamentRecord:e,venue:p.venue}),{...R,court:o,venue:i}}}return _({result:{error:Ka},stack:n})}function oU(t){return J(ns(t),!1,!0)}function Hm({tournamentRecord:t,internalUse:e,courtId:r}){if(!t)return{error:W};if(!r)return{error:Ni};let n=ns({tournamentRecord:t,courtId:r});if(n.error)return n;let o=n.court&&(({altitude:i,courtId:s,courtName:a,courtDimensions:c,latitude:u,longitude:p,surfaceCategory:m,surfaceType:d,surfacedDate:l,pace:f,notes:g})=>({altitude:i,courtId:s,courtName:a,courtDimensions:c,latitude:u,longitude:p,surfaceCategory:m,surfaceType:d,surfacedDate:l,pace:f,notes:g}))(n.court);return{...R,courtInfo:J(o,!1,e)}}function mc({tournamentRecord:t,venueId:e}){if(!t)return{error:W};if(!e)return{error:Bo};let r=Qo({tournamentRecord:t,venueId:e});if(r.error)return r;let o=(r.venue?.courts??[]).map(a=>(({courtInfo:c})=>({...c}))(Hm({courtId:a.courtId,internalUse:!0,tournamentRecord:t}))),i=r.venue&&(({venueId:a,venueName:c,venueAbbreviation:u})=>({venueAbbreviation:u,venueName:c,venueId:a}))(r.venue),s=i&&{...i,courtsInfo:o};return{...R,venueData:J(s,!1,!0)}}function jR({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===fi&&s;return a&&(!i||r(a)>r(i))?a:i},void 0)?.itemValue}}function Ht({event:t,eventId:e}){if(!t)return{error:Et};let n=mt({name:qr,element:t})?.extension,o=e?J(n?.value,!1,!0):n?.value;return e&&t.drawDefinitions?.forEach(i=>{o?.flights?.forEach(s=>{s.drawId===i.drawId&&Object.assign(s,{drawDefinition:i})})}),{flightProfile:o}}function We(t){let{tournamentRecord:e,eventId:r,drawId:n}=t,o="findEvent",i={},s=t.tournamentRecords??(e&&{[e.tournamentId]:e})??{},a=Object.values(s).map(({events:u,tournamentId:p})=>(u&&u.forEach(m=>{i[m.eventId]={tournamentId:p}}),u??[])).flat(),c;if(n){let u,p=a.find(m=>{let l=(m?.drawDefinitions??[]).find(f=>f.drawId===n);if(l)u=l,c=i[m.eventId].tournamentId;else{let g=(m&&Ht({event:m})?.flightProfile)?.flights?.find(I=>I.drawId===n);if(g)return c=i[m.eventId].tournamentId,{entries:g.drawEntries,drawName:g.drawName,tournamentId:c,drawId:n}}return l});if(p)return{event:p,drawDefinition:u,tournamentId:c}}if(r){let u=a.find(p=>p?.eventId===r);if(u)c=i[u.eventId].tournamentId;else return{event:void 0,drawDefinition:void 0,..._({result:{error:mr},stack:o})};return{event:u,drawDefinition:void 0,tournamentId:c}}return{event:void 0,drawDefinition:void 0,..._({result:{error:pr},context:{drawId:n,eventId:r},stack:o})}}function Wm(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:sr};if(o&&!p.matchUpType&&!t.matchUpType&&(e||i)&&p.drawId){let E=e?.drawDefinitions?.find(M=>M.drawId===p.drawId);!E&&i&&({drawDefinition:E,event:e}=We({tournamentRecord:i,drawId:p.drawId}));let U=p.structureId&&E?.structures?.find(({structureId:M})=>M===p.structureId);r=t.matchUpType||U?.matchUpType||E?.matchUpType||e?.eventType!==Fe&&e?.eventType}let{milliseconds:m,time:d}=VR({matchUp:p}),{startTime:l}=HR({matchUp:p}),{endTime:f}=jR({matchUp:p}),g,{visibilityThreshold:I,eventIds:h,drawIds:S}=n??{};if((!h||h.includes(p.eventId))&&(!S||S.includes(p.drawId))){let E={matchUp:p,visibilityThreshold:I},{allocatedCourts:U}=Ih(E),{scheduledTime:M}=vf(E),{scheduledDate:P}=rs(E),{venueId:N}=Sh(E),{courtId:C}=hh(E),{courtOrder:O}=BR(E),{timeModifiers:b}=xf(E),x,w,F,L,v,B=p.matchUpType??r;if(a&&M&&o&&B){let q={matchUpFormat:p.matchUpFormat??c,...a};({averageMinutes:w=0,recoveryMinutes:F=0,typeChangeRecoveryMinutes:L=0}=dp({timingDetails:q,eventType:B})),(w||F)&&(x=f?br($t(f),F):br(M,w+F)),L&&(v=f?br($t(f),L):br(M,w+L))}!P&&M&&(P=Ut(M));let H=Im({scheduledDate:P,scheduledTime:M}),j={},V=(i&&N&&mc({tournamentRecord:i,venueId:N}))?.venueData||{};N&&(j[N]=V);let{venueName:Y,venueAbbreviation:$,courtsInfo:k}=V,z=(C&&k?.find(q=>q.courtId===C))?.courtName;for(let q of U||[]){if(!i)break;q.venueId&&!j[q.venueid]&&(j[q.venueId]=mc({venueId:q.venueId,tournamentRecord:i})?.venueData);let nt=j[q.venueId];q.venueName=nt?.venueName;let Q=nt?.courtsInfo?.find(it=>it.courtId===q.courtId);q.courtName=Q?.courtName}g=rt({typeChangeTimeAfterRecovery:v,timeAfterRecovery:x,scheduledDate:P,scheduledTime:M,isoDateString:H,allocatedCourts:U,timeModifiers:b,venueAbbreviation:$,venueName:Y,venueId:N,courtOrder:O,courtName:z,courtId:C,typeChangeRecoveryMinutes:L,recoveryMinutes:F,averageMinutes:w,milliseconds:m,startTime:l,endTime:f,time:d})}else g=rt({milliseconds:m,startTime:l,endTime:f,time:d});let{scheduledDate:T}=rs({matchUp:p}),{scheduledTime:A}=vf({matchUp:p});if(s&&u?.displaySettings?.draws){let E=u.displaySettings.draws,U=(E?.[p.drawId]??E?.default)?.scheduleDetails;if(U){let M=(U.find(P=>T&&P.dates?.includes(T))??U.find(P=>!P.dates?.length))?.attributes;if(M){let P=Object.assign({},...Object.keys(g).map(N=>({[N]:!0})),M);g=bi({source:g,template:P})}}}let y=p.matchUpStatus&&ae.includes(p.matchUpStatus)&&(Ut(f)||Ut(T)||Ut(A))||void 0;return{schedule:g,endDate:y}}function Gs(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 fp({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 je({drawDefinition:t,structure:e,matchUp:r,event:n}){return{tieFormat:fp({item:r,drawDefinition:t,structure:e,event:n})||fp({item:e,drawDefinition:t,structure:e,event:n})||Gs(t)||Gs(n)}}function YR({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 Ah({groupedOrder:t,roundPositionsCount:e}){if(!t||t?.length<=e)return t;let n=Te(t,t.length/e).map(i=>i.reduce((s,a)=>s+a)),o=n.slice().sort(se);return n.map(i=>o.indexOf(i)+1)}function jm(t){if(!Array.isArray(t))return"";let e=t.filter(te);return e.length?pt([Math.min(...e),Math.max(...e)]).join("-"):""}function qR({drawDefinition:t,structureId:e,matchUpsMap:r}){if(!t)return{error:X};if(!e)return{error:hr};let{structure:n}=st({drawDefinition:t,structureId:e});if(n?.stage!==Ve)return{error:Di,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=Yo({structureId:m,matchUpsMap:r}),f=He({matchUps:d}).roundProfile;return{[m]:f}})),c=Yo({matchUpsMap:r,structureId:e}),{roundProfile:u}=He({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 y=D?T.length/D:0,E=T.length/y,U=T.slice(),M=Ah({roundPositionsCount:E,groupedOrder:g}),P=M?.length||1;if(P<=E){let b=T.length/P,x=Te(U,b);f===ai&&x.forEach(w=>w.reverse()),U=M?.length&&M?.map(w=>x[w-1]).flat()||U}let N=Te(U,y);if(I){let b=Z(0,I.interleave).map(()=>{}),x=Z(0,I.offset).map(()=>{});N=N.map(F=>[F,...b]),N.unshift(x),N=N.flat(1);let w=N.length-I.offset;N=N.slice(0,w)}p[h]||(p[h]={});let O=u?.[h]?.feedRound?2:1;N.forEach((b,x)=>{let w=1+x*O;p[h][w]||(p[h][w]=jm(b))})}),{sourceDrawPositionRanges:p}}function Ln({policyDefinitions:t,tournamentRecord:e,contextProfile:r,drawDefinition:n,event:o}){let i={policies:{}};if(!r)return i;let s=yo({tournamentRecord:e,drawDefinition:n,event:o}).policyDefinitions;if(r.withCompetitiveness){let a=t?.[ii]??s?.[ii]??km[ii];i.policies[ii]=a}return i}function $R({drawPositions:t,roundProfile:e,roundNumber:r}){let n=[void 0,void 0];if(PI(t))return{orderedDrawPositions:n,displayOrder:n};let o=e?.[r],s=o?.pairedDrawPositions?.find(c=>xe(c||[],t.filter(Boolean)))??n,a=o?.feedRound;if(UI(t)){let c=[...t].sort(se);return{orderedDrawPositions:c.length===2?c:s,displayOrder:a?c:s}}if(a){let u=[t.find(p=>!isNaN(ct(p))),void 0];return{orderedDrawPositions:u,displayOrder:u}}return{orderedDrawPositions:s,displayOrder:s}}function gp({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 tn({tournamentParticipants:t,tournamentRecord:e,participantIds:r}){let n="getPairedParticipant";if(!t&&!e)return{error:W};if(!Array.isArray(r)||r.length>2)return{error:zr};if(!r.length)return _({result:{error:lo},stack:n});t=t??e?.participants??[];let o=t.filter(a=>a.participantType===dt&&jt(r,a.individualParticipantIds).length===r.length&&a.individualParticipantIds.length===r.length),i=o[0];if(!i)return _({result:{error:Zt},stack:n});let s=J(o.slice(1),!1,!0);return{participant:J(i),duplicatedPairParticipants:s,...R}}function os({drawDefinition:t,participantId:e}){if(typeof t!="object")return{error:X};if(typeof e!="string")return{error:oe};let{extension:r}=mt({element:t,name:ho});return{lineUp:(r?.value||{})[e]}}function KR({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}=gp({collectionPosition:r,collectionId:s,lineUp:d});if(c===Gt){if(f?.length<=2){let I=o?.[f[0]]?.pairIdMap?.[f[1]],T=(I&&o[I]?.participant||tn({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||os({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||os({participantId:d,drawDefinition:i})?.lineUp;return u({attribute:m,lineUp:g,teamParticipant:f})}).filter(Boolean)||{};return{drawPositionCollectionAssignment:Object.assign({},...p)}}function yh({drawDefinition:t}){if(typeof t!="object")return{error:na};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,ce].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 zR({drawDefinition:t,roundProfile:e,structureId:r,matchUpsMap:n}){if(!t)return{error:X};if(!r)return{error:hr};if(!e){let c=Yo({matchUpsMap:n,structureId:r});if({roundProfile:e}=He({matchUps:c}),!e)return{error:et}}let i=(Math.min(...e?.[1]?.drawPositions??[])||1)-1,s=Object.keys(e);return{drawPositionsRanges:Object.assign({},...(s||[]).map(c=>{let u=e?.[c]?.matchUpsCount,p=e?.[1]?.drawPositions??[],m=Te(p,p.length/u),d=m.map(jm),l=m.map(S=>S.map(T=>T-i)).map(jm),f=s.map(S=>{if(S>c)return;let T=e?.[S]?.drawPositions??[];return Te(T,T.length/u)}).filter(Boolean),g=Z(0,u).map(S=>f.map(T=>T[S]).flat().filter(Boolean).sort(se)).map(S=>pt(S)),I=g.map(S=>jC(S).map(jm).join(", ")),h=Object.assign({},...Z(0,u).map(S=>({[S+1]:{firstRoundDrawPositionsRange:d[S],firstRoundOffsetDrawPositionsRange:l[S],possibleDrawPositions:g[S],drawPositionsRange:I[S]}})));return{[c]:h}}))}}function Ym({roundsNotPowerOf2:t,drawDefinition:e,structure:r,matchUps:n}){if(!r)return!1;n=n??r.matchUps??[],t=t??He({matchUps:n}).roundsNotPowerOf2;let o=!!r.positionAssignments?.find(({drawPosition:i})=>i)||!!n?.find(({drawPositions:i})=>i?.length);return(!e?.drawType||e.drawType!==Oi)&&!r?.structures&&t&&o}function fr({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 wf={[ua]:{policyName:"Round Naming Default",namingConventions:{round:"Round",pre:"Pre"},qualifyingFinishMap:{1:"Final"},abbreviatedRoundNamingMap:{1:"F",2:"SF",4:"QF"},roundNamingMap:{1:"Final",2:"Semifinal",4:"Quarterfinal"},affixes:{roundNumber:"R",preFeedRound:"Q",preQualifying:"P"},stageConstants:{[tt]:"",[ce]:"P",[at]:"Q",[Ve]:"C"}}},QR=wf;function XR({roundNamingPolicy:t,drawDefinition:e,structure:r,matchUps:n}){let{roundProfile:o,roundMatchUps:i}=He({matchUps:n}),{structureAbbreviation:s,stage:a}=r,c=fr({structure:r}),u=Ym({structure:r}),p=r.structures,m={},d=wf[ua],l=r.stage===at,f=l?Math.max(...(e?.structures??[]).filter(O=>O.stage===at).map(({stageSequence:O})=>O??1),0):0,g=(r.stageSequence??1)<f?r.stageSequence??1:"",I=g&&(t?.affixes?.preQualifying||d.affixes.preQualifying)||"",h=t?.roundNamingMap||d.roundNamingMap||{},S=t?.abbreviatedRoundNamingMap||d.abbreviatedRoundNamingMap||{},T=t?.affixes?.preFeedRound||d.affixes.preFeedRound,A=t?.affixes?.roundNumber||d.affixes.roundNumber,y=(t?.namingConventions||d.namingConventions).round,E=a&&a!==tt?a[0]:"",U=t?.stageConstants||d.stageConstants,M=a&&U?.[a]||E,P=`${I}${M}${g}`,N=o?Object.keys(o):[],C=l&&U?.[at]?`${U?.[at]}-`:"";if(p||c||u)Object.assign(m,...N.map(O=>{let b=`${C}${y} ${O}`,x=`${A}${O}`;return{[O]:{roundName:b,abbreviatedRoundName:x}}}));else{let O=l&&(t?.qualifyingFinishMap||d?.qualifyingFinishMap||{});Object.assign(m,...N.map(b=>{if(!o?.[b])return;let{matchUpsCount:x,preFeedRound:w}=o[b],F=x*2,L=O?.[o?.[b].finishingRound]||O&&`${A}${F}`||h[x]||`${A}${F}`,v=w?`-${T}`:"",B=`${L}${v}`,H=[P,s,B].filter(Boolean).join("-"),V=`${S[x]||`${A}${F}`}${v}`,Y=[P,s,V].filter(Boolean).join("-");return{[b]:{abbreviatedRoundName:Y,roundName:H}}}))}return{roundNamingProfile:m,roundProfile:o,roundMatchUps:i}}function qm(t){let e=lt(t,[{[fo]:!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===ht&&Xt||s===dt&&Gt||s===kt&&kt||void 0}return{matchUpType:n}}var cF="normal",iU="timed",uF="final",Lf="NOAD",$m="SET",JR={S:cF,F:uF};function tr(t){if(typeof t=="string"){let e=t.startsWith("T")&&iU||t.startsWith($m)&&$m||"";if(e===iU){let r=rb(t),n={simplified:!0,setFormat:r,bestOf:1};if(r)return n}if(e===$m)return pF(t)}}function pF(t){let e=t.split("-"),r=Ff(e[0].slice(3)),n=r===1||r%2!==0?r:void 0,o=r!==1&&r%2===0?r:void 0,i=e&&ZR(e[1]),s=e&&ZR(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 ZR(t){if(t?.[1]===":"){let e=t.split(":"),r=JR[e[0]],n=e[1];if(r&&n){if(n.startsWith("TB")){let I=tb(n);return I===!1?!1:typeof I=="object"?{tiebreakSet:I}:void 0}if(n.startsWith("T"))return rb(n);let s=t.match(/^[FS]:(\d+)([A-Za-z]*)/),a=s&&nb(s[2])||!1,c=!s?.[2]||a,u=s?Ff(s[1]):void 0,p=eb(n),m=p!==!1,d=m&&p||u,l=tb(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 eb(t,e=!0){let r=t?.indexOf("@")>0&&t.split("@");if(r)return(e?Ff(r[1]):r[1])||!1}function tb(t){if(t)if(t.startsWith("TB")){let e=eb(t,!1),r=t.match(/^TB(\d+)([A-Za-z]*)/),n=r?.[1],o=r&&nb(r[2]),i=!r?.[2]||o,s=Ff(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 rb(t){let e=t.slice(1),r=e.match(/^(\d+)(@?[A-Za-z]*)/),n=Ff(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 nb(t){return t&&t.indexOf(Lf)>=0}function Ff(t){return isNaN(Number(t))?0:Number(t)}function cu(t,e){return!Array.isArray(t)||!$e(e)?!1:jt(t,ph[e]).length}function Aa(t){let{matchUps:e,isCollectionMatchUp:r,excludeMatchUpStatuses:n,matchUpStatuses:o,hasWinningSide:i,matchUpFormats:s,roundPositions:a,matchUpFormat:c,collectionIds:u,isMatchUpTie:p,roundNumbers:m,matchUpIds:d,roundNames:l,stageSequences:f,scheduledDates:g,scheduledDate:I,participantIds:h,processContext:S,tournamentIds:T,matchUpTypes:A,structureIds:D,readyToScore:y,courtIds:E,eventIds:U,venueIds:M,drawIds:P,stages:N,filterMatchUpIds:C=!0,filterMatchUpTypes:O=!0}=t,b=Array.isArray(h)?h.filter(Boolean):[],x=Array.isArray(o)?o.filter(Boolean):[],w=Array.isArray(n)?n.filter(Boolean):[],F=Array.isArray(N)?N.filter(Boolean):[],L=Array.isArray(f)?f.filter(Boolean):[],v=Array.isArray(u)?u.filter(Boolean):[],B=Array.isArray(l)?l.filter(Boolean):[],H=Array.isArray(m)?m.filter(Boolean):[],j=Array.isArray(a)?a.filter(Boolean):[],V=Array.isArray(d)&&C?d.filter(Boolean):[],Y=Array.isArray(A)&&O?A.filter(Boolean):[],$=Array.isArray(E)?E.filter(Boolean):[],k=Array.isArray(M)?M.filter(Boolean):[],K=Array.isArray(s)&&s.filter(Boolean)||typeof c=="string"&&[c]||[],z=Array.isArray(g)&&g.filter(Boolean)||typeof I=="string"&&I.length&&[I]||[],q=Array.isArray(T)?T.filter(Boolean):[],nt=Array.isArray(U)?U.filter(Boolean):[],Q=Array.isArray(P)?P.filter(Boolean):[],it=Array.isArray(D)?D.filter(Boolean):[];return e.filter(ot=>{if(y&&!ie(ln)(ot)&&!ot.readyToScore||ot.winningSide&&i&&![1,2].includes(ot.winningSide)||p!==void 0&&(p&&!ot.tieMatchUps||!p&&ot.tieMatchUps)||r!==void 0&&(r&&!ot.collectionId||!r&&ot.collectionId)||F.length&&!F.includes(ot.stage)||L.length&&!L.includes(ot.stageSequence)||v.length&&(!ot.collectionId||!v.includes(ot.collectionId))||B.length&&(!ot.roundName||!B.includes(ot.roundName))||H.length&&(!ot.roundNumber||!H.includes(ot.roundNumber))||j.length&&(!ot.roundPosition||!j.includes(ot.roundPosition))||x.length&&(!ot.matchUpStatus||!x.includes(ot.matchUpStatus))||w.length&&ot.matchUpStatus&&w.includes(ot.matchUpStatus)||V.length&&!V.includes(ot.matchUpId)||Y.length&&(!ot.matchUpType||!cu(Y,ot.matchUpType))||K.length&&(!ot.matchUpFormat||!K.includes(ot.matchUpFormat)))return!1;if(z?.length){let{scheduledTime:ut}=vf({matchUp:ot}),{scheduledDate:Qt}=rs({matchUp:ot}),Me=Ut(ut)||Qt;if(!z.find(Ee=>_n(Ee,Me)))return!1}if($.length){let{courtId:ut}=hh({matchUp:ot}),{allocatedCourts:Qt}=Ih({matchUp:ot}),yt=Qt?.map(({courtId:Me})=>Me);if(!$.filter(Boolean).includes(ut)||yt?.includes(ut))return!1}if(k.length){let{venueId:ut}=Sh({matchUp:ot});if(!k.filter(Boolean).includes(ut))return!1}if(S){if(q.length&&!q.includes(ot.tournamentId)||nt.length&&!nt.includes(ot.eventId)||Q.length&&!Q.includes(ot.drawId)||it.length&&!it.includes(ot.structureId))return!1;if(b.length){let ut=ot.sides?.map(({participantId:yt})=>yt).filter(Boolean)??[];if(!b.some(yt=>ut.includes(yt)))return!1}}return!0})}function ob({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?mF({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 mF({displaySideNumber:t,seedAssignments:e,participantId:r,assignment:n,sideNumber:o}){let i={drawPosition:n.drawPosition,displaySideNumber:t,sideNumber:o};if(r){let s=dF({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 dF({seedAssignments:t,participantId:e}){return t?.find(r=>!r.seedProxy&&r.participantId===e)}var Fn="ANY",ee="MALE",_r="MIXED",ya="OTHER",ue="FEMALE",Km={ANY:Fn,MALE:ee,FEMALE:ue,MIXED:_r,OTHER:ya};function At({scheduleVisibilityFilters:t,tournamentAppliedPolicies:e,provisionalPositioning:r,tournamentParticipants:n,afterRecoveryTimes:o,policyDefinitions:i,tournamentRecord:s,seedAssignments:a,usePublishState:c,contextFilters:u,contextContent:p,matchUpFilters:m,participantMap:d,scheduleTiming:l,contextProfile:f,drawDefinition:g,publishStatus:I,context:h={},exitProfiles:S,matchUpsMap:T,structure:A,inContext:D,event:y}){let E={},U={};if(n=n??s?.participants,!A)return{collectionPositionMatchUps:E,error:Do,roundMatchUps:U,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):[],C=!h?.eventId||!M?.length&&!u?.eventIds?.filter(Boolean).length||M?.includes(h.eventId)||u?.eventIds?.includes(h.eventId),O=!P?.length||P.includes(A.structureId),b=!g||!N?.length||N.includes(g.drawId);if(!C||!O||!b)return{collectionPositionMatchUps:E,roundMatchUps:U,matchUps:[]};f&&!p&&(p=Ln({tournamentRecord:s,contextProfile:f,drawDefinition:g}));let{appliedPolicies:x}=Pt({drawDefinition:g}),w={...e,...x,...i},F=w?.scoring?.structures,L=A.stage&&F?.stage&&F?.stage[A.stage],v=A.stageSequence&&L?.stageSequence&&L.stageSequence[A.stageSequence],B=w?.scoring?.requireAllPositionsAssigned||L?.requireAllPositionsAssigned||v?.requireAllPositionsAssigned;T||(T=Ae({drawDefinition:g,structure:A}));let{positionAssignments:H,allPositionsAssigned:j}=de({structure:A}),V=!B||j,{seedAssignments:Y}=Fr({provisionalPositioning:r,drawDefinition:g,structure:A});a=a??Y;let{roundOffset:$,structureId:k,structureName:K,stage:z,stageSequence:q}=A,{drawId:nt,drawName:Q,drawType:it}=g??{};S=S||g&&yh({drawDefinition:g}).exitProfiles;let ot=S?.[k],ut=ot?.length&&(ot[0].split("-").map(wt=>parseInt(wt)).reduce((wt,Ue)=>wt+Ue)||0),Qt=!!A.structures,yt=Yo({matchUpsMap:T,structureId:k,inContext:D}),Me=w?.[ua],Ee=XR({roundNamingPolicy:Me,drawDefinition:g,structure:A,matchUps:yt}),{roundNamingProfile:Ce,roundProfile:Kt}=Ee;if(U=Ee?.roundMatchUps??[],m&&(yt=Aa({matchUps:yt,...m,filterMatchUpTypes:!1,filterMatchUpIds:!1})),D){let{sourceDrawPositionRanges:wt}=qR({drawDefinition:g,matchUpsMap:T,structureId:k}),Ue=g?zR({drawDefinition:g,roundProfile:Kt,matchUpsMap:T,structureId:k}).drawPositionsRanges:void 0;yt=yt.map(vt=>Re({scheduleVisibilityFilters:t,sourceDrawPositionRanges:wt,drawPositionsRanges:Ue,roundNamingProfile:Ce,initialRoundOfPlay:ut,appliedPolicies:w,usePublishState:c,publishStatus:I,isRoundRobin:Qt,roundProfile:Kt,matchUp:vt,event:y})),(yt?.filter(vt=>Array.isArray(vt.tieMatchUps))).forEach(vt=>{let ne=vt.tieMatchUps;yt=yt.concat(...ne)}),u&&(yt=Aa({processContext:!0,...u,matchUps:yt}))}else(yt?.filter(Ue=>Array.isArray(Ue.tieMatchUps))).forEach(Ue=>{let Ct=Ue.tieMatchUps;yt=yt.concat(...Ct)});return m&&(yt=Aa({matchUps:yt,...m,filterMatchUpTypes:!1,filterMatchUpIds:!1})),(m?.matchUpTypes||m?.matchUpIds)&&(yt=Aa({matchUpTypes:m.matchUpTypes,matchUpIds:m.matchUpIds,matchUps:yt})),(m?.matchUpTypes||m?.matchUpIds||D)&&(U=He({matchUps:yt}).roundMatchUps??[]),je({drawDefinition:g,structure:A,event:y})?.tieFormat&&({collectionPositionMatchUps:E}=YR({matchUps:yt})),{collectionPositionMatchUps:E,roundMatchUps:U,isRoundRobin:Qt,roundProfile:Kt,matchUpsMap:T,matchUps:yt};function Re({scheduleVisibilityFilters:wt,sourceDrawPositionRanges:Ue,drawPositionsRanges:Ct,initialRoundOfPlay:vt,additionalContext:ne,roundNamingProfile:qt,tieDrawPositions:pe,appliedPolicies:he,isCollectionBye:ur,usePublishState:_e,publishStatus:Wt,matchUpTieId:ve,isRoundRobin:nr,roundProfile:be,sideLineUps:Nr,matchUp:Se,event:Pe}){ne=ne??{};let gr=je({drawDefinition:g,structure:A,matchUp:Se,event:Pe})?.tieFormat,ri=gr?.collectionDefinitions,qe=Se.collectionId&&ri?.find(Qn=>Qn.collectionId===Se.collectionId),bn=Se.collectionId?qe?.matchUpFormat:Se.matchUpFormat??A?.matchUpFormat??g?.matchUpFormat??Pe?.matchUpFormat,Ei=Se.matchUpType||qe?.matchUpType||A?.matchUpType||g?.matchUpType||!ie(Fe)(Pe?.eventType)&&Pe?.eventType,Wi=ur?Dt:Se.matchUpStatus,{schedule:hn,endDate:wc}=Wm({scheduleVisibilityFilters:wt,afterRecoveryTimes:o,tournamentRecord:s,usePublishState:_e,scheduleTiming:l,matchUpFormat:bn,publishStatus:Wt,matchUpType:Ei,matchUp:Se,event:Pe}),ji=pe??Se.drawPositions??[],{collectionPosition:eI,collectionId:UC,roundPosition:rI}=Se,Yi=Se.roundNumber??ne.roundNumber,fw=UC?KR({tournamentParticipants:n,positionAssignments:H,collectionPosition:eI,drawDefinition:g,participantMap:d,drawPositions:ji,collectionId:UC,sideLineUps:Nr,matchUpType:Ei}):void 0,PC=qt?.[Yi]?.roundName||ne.roundName,DC=qt?.[Yi]?.abbreviatedRoundName||ne.abbreviatedRoundName,gw=be?.[Yi]?.feedRound,Iw=be?.[Yi]?.preFeedRound,hw=be?.[Yi]?.roundFactor,Sw=Ct?.[Yi],Tw=rI?Sw?.[rI]:void 0,Aw=Ue?.[Yi],yw=qe?.category?{...h?.category||{},...qe.category}:h?.category??Pe?.category,Ew=Se.processCodes?.length&&Se.processCodes||qe?.processCodes?.length&&qe?.processCodes||A?.processCodes?.length&&A?.processCodes||g?.processCodes?.length&&g?.processCodes||Pe?.processCodes?.length&&Pe?.processCodes||s?.processCodes,Uw=f?.withCompetitiveness&&su({...p,matchUp:Se}),Pw=Se.finishingPositionRange??ne.finishingPositionRange,nI=Qn=>rt(Qn,void 0,!0),Ir={...nI(h),...nI({matchUpFormat:Se.matchUpType===Fe?void 0:bn,tieFormat:Se.matchUpType!==Fe?void 0:gr,gender:qe?.gender??Pe?.gender,roundOfPlay:z!==at&&ft(vt)&&vt+(Yi||0),endDate:Se.endDate??wc,discipline:Pe?.discipline,category:yw,finishingPositionRange:Pw,abbreviatedRoundName:DC,drawPositionsRange:Tw,competitiveProfile:Uw,structureName:K,stageSequence:q,drawPositions:ji,matchUpStatus:Wi,processCodes:Ew,isRoundRobin:nr,matchUpTieId:ve,preFeedRound:Iw,matchUpType:Ei,roundFactor:hw,roundOffset:$,structureId:k,roundNumber:Yi,feedRound:gw,roundName:PC,drawName:Q,drawType:it,schedule:hn,drawId:nt,stage:z}),...J(nI(Se),!0,!0)};if(bn&&Se.score?.scoreStringSide1){let Qn=tr(bn),{bestOf:ea,finalSetFormat:As,setFormat:Tr}=Qn??{};(As?.tiebreakSet||Tr?.tiebreakSet||Tr?.timed)&&(Ir.score.sets=Ir.score.sets.sort((Hr,On)=>Hr.setNumber-On.setNumber).map((Hr,On)=>(On+1===ea?(As?.tiebreakSet||As?.timed)&&(Hr.tiebreakSet=!0):(Tr?.tiebreakSet||Tr?.timed)&&(Hr.tiebreakSet=!0),Hr)))}if(Array.isArray(ji)){let{orderedDrawPositions:Qn,displayOrder:ea}=$R({drawPositions:ji,roundProfile:be,roundNumber:Yi}),As=be?.[Yi]?.feedRound,Tr=ea[0]!==Qn[0],On=Qn.concat(void 0,void 0).slice(0,2).map((Ui,JA)=>{let oI=JA+1,Nw=Tr?3-oI:oI,Mw=ob({...fw,positionAssignments:H,displaySideNumber:Nw,seedAssignments:a,drawPosition:Ui,isFeedRound:As,sideNumber:oI}),Cw=Se.sides?.find(bw=>bw.sideNumber===oI),MC=rI?(rI-1)*2+JA+1:void 0,Rw=MC?Aw?.[MC]:void 0;return nI({sourceDrawPositionRange:Rw,...Cw,...Mw})});Object.assign(Ir,J({sides:On},!0,!0))}if(n&&Ir.sides){let Qn=he?.[Os],ea=Tr=>{let Hr=d?.[Tr]?.participant;return Hr&&bi({template:Qn?.participant,source:Hr})};if(Ir.sides.filter(Boolean).forEach(Tr=>{if(Tr.participantId){let Hr=J(ea(Tr.participantId)||n&&bo({policyDefinitions:he,participantId:Tr.participantId,tournamentParticipants:n,internalUse:!0,contextProfile:f}),void 0,!0);if(Hr){if(g?.entries){let On=g.entries.find(Ui=>Ui.participantId===Tr.participantId);On?.entryStatus&&(Hr.entryStatus=On.entryStatus),On?.entryStage&&(Hr.entryStage=On.entryStage)}Object.assign(Tr,{participant:Hr})}}if(Tr?.participant?.individualParticipantIds?.length&&!Tr.participant.individualParticipants?.length){let Hr=Tr.participant.individualParticipantIds.map(On=>ea(On)||n&&bo({policyDefinitions:he,tournamentParticipants:n,internalUse:!0,contextProfile:f,participantId:On}));Object.assign(Tr.participant,{individualParticipants:Hr})}}),!Ir.matchUpType){let{matchUpType:Tr}=qm({matchUp:Ir});Tr&&Object.assign(Ir,{matchUpType:Tr})}if(f?.inferGender&&(!Ir.gender||Ir.gender===_r)&&Ir.sides?.length===2&&Ir.matchUpType!==Fe){let Tr=Ir.sides.map(Hr=>{if(ie(Xt)(Ir.matchUpType))return Hr.participant?.person?.sex;if(Hr.participant?.individualParticipants?.length===2){let On=pt(Hr.participant.individualParticipants.map(Ui=>Ui.person?.sex)).filter(Boolean);if(On.length===1)return On[0]}});if(Tr.filter(Boolean).length===2&&pt(Tr).length===1){let Hr=Tr[0];Ir.inferredGender=Hr}}}if(Ir.tieMatchUps){let Qn=Ir.matchUpStatus===Dt,ea=Ir.sides?.map(({participant:As,drawPosition:Tr,sideNumber:Hr,lineUp:On})=>{let Ui=As?.participantType===Fe&&As;return{teamParticipant:Ui&&rt({participantRoleResponsibilities:Ui.participantRoleResponsibilities,participantOtherName:Ui.participanOthertName,participantName:Ui.participantName,participantId:Ui.participantId,teamId:Ui.teamId}),drawPosition:Tr,sideNumber:Hr,lineUp:On}});Ir.tieMatchUps=Ir.tieMatchUps.map(As=>{let Tr=Ir.matchUpId,On={finishingPositionRange:Ir.finishingPositionRange,abbreviatedRoundName:DC,roundNumber:Yi,roundName:PC};return Re({tieDrawPositions:ji,scheduleVisibilityFilters:wt,sourceDrawPositionRanges:Ue,sideLineUps:ea,drawPositionsRanges:Ct,initialRoundOfPlay:vt,roundNamingProfile:qt,additionalContext:On,appliedPolicies:he,isCollectionBye:Qn,usePublishState:_e,publishStatus:Wt,matchUpTieId:Tr,isRoundRobin:nr,roundProfile:be,matchUp:As,event:Pe})})}let NC=Ir.sides&&Ir.sides.filter(Qn=>Qn?.participantId).length===2,Dw=!Ir.winningSide;if(Object.assign(Ir,{readyToScore:V&&NC&&Dw,hasContext:!0}),NC){let{allParticipantsCheckedIn:Qn,checkedInParticipantIds:ea}=es({matchUp:Ir});Object.assign(Ir,{allParticipantsCheckedIn:Qn,checkedInParticipantIds:ea})}return Array.isArray(f?.exclude)&&f?.exclude.forEach(Qn=>delete Ir[Qn]),Ir}}function is({matchUp:t}){return t?ae.includes(t?.matchUpStatus)||t?.winningSide:!1}function uu({requireParticipants:t=!0,scheduleVisibilityFilters:e,tournamentAppliedPolicies:r,tournamentParticipants:n,afterRecoveryTimes:o,policyDefinitions:i,tournamentRecord:s,usePublishState:a,matchUpFilters:c,contextFilters:u,contextContent:p,participantMap:m,scheduleTiming:d,publishStatus:l,contextProfile:f,drawDefinition:g,exitProfiles:I,matchUpsMap:h,structureId:S,inContext:T,structure:A,context:D,event:y}){!A&&S&&({structure:A}=st({drawDefinition:g,structureId:S}));let E=At({tournamentAppliedPolicies:r,scheduleVisibilityFilters:e,tournamentParticipants:n,afterRecoveryTimes:o,policyDefinitions:i,tournamentRecord:s,usePublishState:a,matchUpFilters:c,contextFilters:u,contextContent:p,participantMap:m,scheduleTiming:d,publishStatus:l,contextProfile:f,drawDefinition:g,exitProfiles:I,matchUpsMap:h,structure:A,inContext:T,context:D,event:y}),U=[],M=[],P=[],N=[],C=[];if(E.error)return E;let{matchUps:O}=E,{assignedPositions:b}=de({structure:A}),x=b?.filter(F=>F.participantId).map(F=>F.drawPosition),w;return O.filter(F=>{let L=c?.matchUpTypes?.length===1&&c.matchUpTypes[0]===Bt;return!(F.matchUpType!==Bt&&L)}).forEach(F=>{if(F.matchUpStatus===$r){U.push(F);return}F.matchUpType===Bt&&(w=!0);let L=F.collectionId,v=L&&F.sides?.every(k=>k.participantId),B=!L&&F.drawPositions?.filter(Boolean).length===2,H=!L&&F.drawPositions?.every(k=>x?.includes(k)),j=b?.filter(k=>k.bye).map(k=>k.drawPosition),V=!L&&F.drawPositions?.find(k=>j?.includes(k)),$=$I.includes(F.matchUpStatus)&&(v||B&&(!t||H));return V?C.push(F):is({matchUp:F})?M.push(F):$?P.push(F):N.push(F)}),{includesTeamMatchUps:w,abandonedMatchUps:U,completedMatchUps:M,upcomingMatchUps:P,pendingMatchUps:N,byeMatchUps:C,structure:A}}function ib({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 Eh({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[oo,Yn].includes(o?.linkType)&&!o?.source?.roundNumber?_({result:{error:G},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 sb({structureMatchUps:t,matchUp:e}){let{roundNumber:r,roundPosition:n}=e,o=t.filter(s=>s.roundNumber===r&&!s.matchUpTieId),i=t.filter(s=>s.roundNumber===r+1&&!s.matchUpTieId);if(i.length){let s;return i.length===o.length?s=i.find(a=>a.roundPosition===n):i.length===o.length/2&&(s=i.find(a=>a.roundPosition===Math.ceil(n/2))),{matchUp:s}}return{message:"no progression found"}}function Uh({sourceRoundMatchUpCount:t,inContextDrawMatchUps:e,sourceRoundPosition:r,drawDefinition:n,targetLink:o}){if(!o)return{error:gl};let{target:{structureId:i,feedProfile:s,groupedOrder:a,roundNumber:c,positionInterleave:u}}=o,{structure:p}=st({drawDefinition:n,structureId:i}),{positionAssignments:m}=Nt({structure:p}),l=(e?.filter(P=>P.structureId===p?.structureId)).filter(P=>P.roundNumber===c&&!P.matchUpTieId),f=l.length,g=Z(1,f+1),I=f/t,h=Math.ceil(I*r),S=1-r%2;if(u?.interleave&&I!==.5){let P=u.offset+(r-1)*u.interleave,N=r+P;h=Math.ceil(N/2),S=1-N%2}let T=g,A=g[h-1],D=Ah({roundPositionsCount:g.length,groupedOrder:a}),y=D?.length||1;if(y<=g.length){let P=f/y,N=Te(g,P);s===ai&&N.forEach(C=>C.reverse()),T=D?.length&&D?.map(C=>N[C-1]).flat()||T}s===sn?A=T[h-1]:s===ai?((!D?.length||y>g.length)&&(h=l.length+1-h),A=T[h-1]):s===ip&&yr()&&console.log($u,{feedProfile:s});let E=A&&l.reduce((P,N)=>N.roundPosition===A?N:P,void 0),U;E?.feedRound?(S=0,U=Math.min(...(E.drawPositions||[]).filter(Boolean))):U=E?.drawPositions?.length===2&&E?.drawPositions[S];let M=m?.find(({drawPosition:P})=>P===U);if(M){let{extension:P}=mt({element:M,name:ym});if(P?.value)return{disabledDrawPosition:U}}return{matchUp:E,targetDrawPosition:U,matchUpDrawPositionIndex:S}}function er({inContextDrawMatchUps:t=[],useTargetMatchUpIds:e,inContextMatchUp:r,drawDefinition:n,matchUpId:o}){let i=r;t.length&&!i&&(i=t.find(c=>c.matchUpId===o));let{structure:s}=st({structureId:i?.structureId,drawDefinition:n});return s?.finishingPosition===_i?lF({inContextDrawMatchUps:t,useTargetMatchUpIds:e,drawDefinition:n,structure:s,matchUp:i}):fF({matchUp:i})}function lF({inContextDrawMatchUps:t,useTargetMatchUpIds:e,drawDefinition:r,structure:n,matchUp:o}){let{winnerMatchUpId:i,loserMatchUpId:s}=o,{links:a}=ib({roundNumber:o.roundNumber,structureId:n.structureId,drawDefinition:r}),c=a?.source,u=Eh({source:c,linkType:oo}),p=Eh({linkCondition:qn,linkType:Yn,source:c}),m=Eh({source:c,linkType:Yn}),d=p&&m;m||(m=p);let l=u?.target?.feedProfile,f=m?.target?.feedProfile,g=p?.target?.feedProfile,I,h,S,T,A,D,y,E,U,M;if(e&&(i||s)&&(y=i&&l!==Qr&&t.find(({matchUpId:C})=>C===i),T=s&&f!==Qr&&t.find(({matchUpId:C})=>C===s),y||T))return{matchUp:o,targetLinks:{loserTargetLink:m,winnerTargetLink:u},targetMatchUps:{loserMatchUp:T,winnerMatchUp:y}};let{roundPosition:P}=o;M=M||t.filter(C=>C.structureId===n.structureId);let N=M.reduce((C,O)=>O.roundNumber===o.roundNumber&&!O.matchUpTieId?C+1:C,0);return m&&!T&&f!==Qr&&({matchUpDrawPositionIndex:D,targetDrawPosition:A,matchUp:T}=Uh({targetLink:m,sourceRoundMatchUpCount:N,inContextDrawMatchUps:t,sourceRoundPosition:P,drawDefinition:r})),d&&g!==Qr&&({matchUpDrawPositionIndex:S,targetDrawPosition:h,matchUp:I}=Uh({targetLink:p,sourceRoundMatchUpCount:N,inContextDrawMatchUps:t,sourceRoundPosition:P,drawDefinition:r})),u&&!y&&l!==Qr&&({matchUpDrawPositionIndex:U,targetDrawPosition:E,matchUp:y}=Uh({targetLink:u,sourceRoundMatchUpCount:N,inContextDrawMatchUps:t,sourceRoundPosition:P,drawDefinition:r})),y||(M=M||t.filter(C=>C.structureId===n.structureId),{matchUp:y}=sb({structureMatchUps:M,matchUp:o})),rt({matchUp:o,targetLinks:{loserTargetLink:m,winnerTargetLink:u,byeTargetLink:p},targetMatchUps:{winnerMatchUpDrawPositionIndex:U,loserMatchUpDrawPositionIndex:D,byeMatchUpDrawPositionIndex:S,winnerTargetDrawPosition:E,loserTargetDrawPosition:A,byeTargetDrawPosition:h,winnerMatchUp:y,loserMatchUp:T,byeMatchUp:I},targetMatchUpIds:!!(i||s)})}function fF({matchUp:t}){return{targetLinks:{loserTargetLink:void 0,winnerTargetLink:void 0},targetMatchUps:{loserMatchUp:void 0,winnerMatchUp:void 0},matchUp:t}}function ab({drawDefinition:t,inContextDrawMatchUps:e}){let r={};return e.forEach(n=>{let{matchUpId:o,structureId:i,drawPositions:s=[]}=n,{structure:a}=st({drawDefinition:t,structureId:i});if(a?.finishingPosition===vs){let{roundNumber:c}=n,u=c&&ct(c)+1,p=a.matchUps??[],{roundMatchUps:m}=He({matchUps:p});if(u&&m?.[u]){let d=[...s].sort(se).map((l,f)=>{let g=m[u].find(I=>I.drawPositions?.includes(l));return{matchUpId:g?.matchUpId,roundNumber:u,schedule:g?.schedule,sideNumber:f+1,structureName:a.structureName}});Object.assign(n,{sidesTo:d})}}else{let c=er({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=sU({upcomingMatchUp:u}),d=sU({upcomingMatchUp:p});if(n.matchUpStatus!==Dt&&p?.matchUpStatus===Dt){let{matchUp:f}=cb({matchUp:p,drawDefinition:t,inContextDrawMatchUps:e})||{};d=f&&sU({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===qn,I=gF(n);if(I.length){let h=rf(u?.sides),S=rf(p?.sides),A=I.find(({participantId:E})=>h.includes(E))?[]:I,y=I.find(({participantId:E})=>S.includes(E))?[]:I;p&&g&&y.length<2&&y.push({bye:!0,tbd:!0}),A?.length&&u&&(!c.targetMatchUpIds&&u&&(u=e.find(({matchUpId:E})=>E===u.matchUpId)),u.potentialParticipants||(u.potentialParticipants=[]),u.potentialParticipants.push(A)),y?.length&&p&&(c.targetMatchUpIds||(u=e.find(({matchUpId:E})=>E===p.matchUpId)),p.potentialParticipants||(p.potentialParticipants=[]),p.potentialParticipants.push(y))}}}}),Object.keys(r).length&&e.forEach(n=>{Object.keys(r).includes(n.matchUpId)&&(n.schedule.scheduleConflict=r[n.matchUpId])}),{scheduleConflictMatchUpIds:r}}function gF(t){return t?.sides?.map(({participant:e,participantId:r,qualifier:n})=>e||r&&{participantId:r}||n&&{qualifier:n}).filter(Boolean)||[]}function cb({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===Dt){let s;return t.winnerMatchUpId?s=r.find(({matchUpId:a})=>a===t.winnerMatchUpId):{winnerMatchUp:s}=er({inContextDrawMatchUps:r,drawDefinition:e,matchUpId:n})?.targetMatchUps||{},cb({matchUp:s,drawDefinition:e,inContextDrawMatchUps:r})}return{matchUp:void 0}}function sU(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=Vs(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 Vs(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:A,context:D,event:y}=t,E=[],U=[],M=[],P=[],N=[];h&&!r&&(r=Ln({policyDefinitions:u,tournamentRecord:p,contextProfile:h,event:y}));let C;!e?.length&&p&&(e=p?.participants,(A||a?.withGroupings)&&e?.length&&({participantsWithGroupings:e,groupInfo:C}=xm({participants:e,participantsProfile:a})));let{structures:O}=xn({drawDefinition:S});if(!O)return{error:Lt};n||(n=Ae({drawDefinition:S}));let b=S&&yh({drawDefinition:S}).exitProfiles;O.forEach(F=>{let{byeMatchUps:L=[],pendingMatchUps:v=[],upcomingMatchUps:B=[],completedMatchUps:H=[],abandonedMatchUps:j=[]}=uu({matchUpFilters:T?void 0:l,contextFilters:T?void 0:d,inContext:A||T||d,tournamentAppliedPolicies:i,scheduleVisibilityFilters:o,tournamentParticipants:e,requireParticipants:s,afterRecoveryTimes:c,policyDefinitions:u,tournamentRecord:p,usePublishState:m,contextContent:r,participantMap:g,scheduleTiming:f,publishStatus:I,contextProfile:h,drawDefinition:S,exitProfiles:b,matchUpsMap:n,structure:F,context:D,event:y});E=E.concat(...j),U=U.concat(...H),M=M.concat(...B),P=P.concat(...v),N=N.concat(...L)});let x=F=>(!l&&!T&&!d||(l&&(F=Aa({matchUps:F,...l})),d&&(F=Aa({matchUps:F,...d,processContext:!0}))),F),w={abandonedMatchUps:x(E),completedMatchUps:x(U),upcomingMatchUps:x(M),pendingMatchUps:x(P),byeMatchUps:x(N),matchUpsMap:n,...R,groupInfo:C};if(T){let F=typeof T=="object"||{abandoned:!0,completed:!0,upcoming:!0,pending:!0,bye:!0},{abandoned:L,completed:v,upcoming:B,pending:H,bye:j}=F,V=[].concat(...L&&E||[],...v&&U||[],...B&&M||[],...H&&P||[],...j&&N||[]);ab({inContextDrawMatchUps:V,drawDefinition:S})}return w}function wi({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??[];ha({matchUps:i})}return(t??[]).filter(({collectionId:i})=>!i).forEach(i=>{let{matchUpId:s,structureId:a}=i,c=er({inContextDrawMatchUps:t,drawDefinition:e,matchUpId:s}),{winnerMatchUp:u,loserMatchUp:p}=c.targetMatchUps,m=u?.matchUpId,d=p?.matchUpId,f=Yo({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 aU(t){return t&&typeof String.fromCodePoint<"u"?t.toUpperCase().replace(/./g,e=>String.fromCodePoint(e.charCodeAt(0)+127397)):t}function ub(t){let e=Object.assign({},...Xo.filter(r=>r.ioc).map(r=>({[r.ioc]:r.iso})));return aU(e[t])}var Xo=[{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 Ph({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=Xo.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 pb({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?bi({template:e,source:s}):s)}}}}function xo(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:Zt}}function Gn({returnPreviousValues:t,itemSubTypes:e,itemType:r,element:n}){if(!n)return{error:et,info:Sm};if(e&&!Array.isArray(e))return{error:G,context:{itemSubTypes:e}};if(!Array.isArray(n.timeItems))return{error:_l};let o=n.timeItems.filter(s=>s?.itemType===r).filter(s=>!e?.length||e.some(a=>s?.itemSubTypes?.includes(a))).sort((s,a)=>{let c=new Date(s.createdAt||void 0).getTime(),u=new Date(a.createdAt||void 0).getTime();return c-u}),i=o.pop();if(i){let s={timeItem:i,...R};return t&&Object.assign(s,{previousItems:o}),s}else return{info:Ke}}function Dh({returnPreviousValues:t,drawDefinition:e,itemSubTypes:r,itemType:n}){if(!e)return{error:Wr};if(!e.timeItems)return{info:Ke};let{timeItem:o,previousItems:i,info:s}=Gn({element:e,returnPreviousValues:t,itemSubTypes:r,itemType:n});return o&&{timeItem:o,previousItems:i}||{info:s}}function pu({returnPreviousValues:t,itemSubTypes:e,itemType:r,event:n}){if(!n)return{error:Et};if(!n.timeItems)return{info:Ke};let{timeItem:o,previousItems:i,info:s}=Gn({returnPreviousValues:t,element:n,itemSubTypes:e,itemType:r});return o&&{timeItem:o,previousItems:i}||{info:s}}function mu({returnPreviousValues:t,tournamentRecord:e,itemSubTypes:r,itemType:n}){if(!e)return{error:W};if(!e.timeItems)return{info:Ke};let{timeItem:o,previousItems:i,info:s}=Gn({element:e,returnPreviousValues:t,itemSubTypes:r,itemType:n});return o&&{timeItem:o,previousItems:i}||{info:s}}function Nh({returnPreviousValues:t,tournamentRecord:e,participantId:r,itemSubTypes:n,itemType:o}){if(!e)return{error:W};if(!r)return{error:oe};let i=xo({tournamentRecord:e,participantId:r});if(i.error)return i;let{participant:s}=i;if(!s?.timeItems)return{info:Ke};let{timeItem:a,previousItems:c,info:u}=Gn({element:i.participant,returnPreviousValues:t,itemSubTypes:n,itemType:o});return a&&{timeItem:a,previousItems:c}||{info:u}}var IF={[Ar]:"groupParticipantIds",[dt]:"pairParticipantIds",[kt]:"teamParticipantIds"},hF={[Ar]:"groups",[kt]:"teams"};function Mh({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&&AF({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&&TF({individualParticipantIds:d,participantCopy:p,participantMap:c,participantType:l,participantId:m}),n&&(c[m].participant.signedIn=SF(p)),o){let{ratings:f,rankings:g,seedings:I}=aa({participant:p});c[m].participant.seedings=I,c[m].participant.rankings=g,c[m].participant.ratings=f}(a||s)&&Ph({participant:c[m].participant,withISO2:s,withIOC:a})}if(t){let u=Rt(t)?t:void 0;pb({participantMap:c,template:u})}return{participantMap:c}}function SF(t){let{timeItem:e}=Gn({itemType:ic,element:t});return e?.itemValue===ru}function TF({individualParticipantIds:t,participantCopy:e,participantMap:r,participantType:n,participantId:o}){for(let i of t){let s=r[i].participant;if(s[IF[n]].push(o),[kt,Ar].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===dt){let a=t.find(c=>c!==i);r[i].pairIdMap[o]=a,r[i].pairIdMap[a]=o}}}function AF({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:{[Xt]:{...r},[Gt]:{...r},[kt]:{...r},...r}}}function Ii({participantsProfile:t,useParticipantMap:e,tournamentRecord:r,contextProfile:n,inContext:o}){if(e)return{participantMap:Mh({...t,...n,tournamentRecord:r})?.participantMap};let i=J(r.participants,!1,!0)||[];(t?.withIOC||t?.withISO2)&&i.forEach(a=>Ph({participant:a,...t}));let s;if((o||t?.withGroupings)&&i?.length&&({participantsWithGroupings:i,groupInfo:s}=xm({participantsProfile:t,deepCopy:!1,participants:i})),t?.withScaleValues&&i?.length)for(let a of i){let{ratings:c,rankings:u}=aa({participant:a});a.rankings=u,a.ratings=c}return{participants:i,groupInfo:s}}function co(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:Et};let{eventId:S,eventName:T,endDate:A,eventType:D,category:y,gender:E,matchUpFormat:U}=h??{},M={...I,...rt({indoorOutDoor:h.indoorOutdoor??p?.indoorOutdoor,surfaceCategory:h.surfaceCategory??p?.surfaceCategory,endDate:h.endDate??p?.endDate,tournamentId:p?.tournamentId,matchUpFormat:U,eventName:T,eventType:D,category:y,eventId:S,gender:E})};A&&(M.endDate=A),d&&!r&&(r=Ln({policyDefinitions:c,tournamentRecord:p,contextProfile:d,event:h}));let P;if(!e?.length&&!n&&p){let b=Ii({participantsProfile:s,useParticipantMap:u,policyDefinitions:c,tournamentRecord:p,contextProfile:d,inContext:g});n=b.participantMap,e=b.participants??[],P=b.groupInfo}let N=h.drawDefinitions??[],C=Sa({tournamentRecord:p,event:h}).scheduleTiming;return{matchUps:N.flatMap(b=>{let{matchUps:x}=re({tournamentParticipants:e,tournamentAppliedPolicies:i,scheduleVisibilityFilters:o,context:M,participantsProfile:s,afterRecoveryTimes:a,policyDefinitions:c,tournamentRecord:p,contextFilters:m,contextProfile:d,drawDefinition:b,contextContent:r,matchUpFilters:l,participantMap:n,scheduleTiming:C,nextMatchUps:f,inContext:g,event:h});return x??[]}),groupInfo:P}}function le(t){let e=lt(t,[{tournamentRecord:!0}]);if(e.error)return e;if(!t?.tournamentRecord)return{error:W};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}=Ii({participantsProfile:i,useParticipantMap:a,policyDefinitions:c,tournamentRecord:u,contextProfile:m,inContext:p}));let{appliedPolicies:S}=Pt({tournamentRecord:u}),T={...g,tournamentId:I,indoorOutDoor:u.indoorOutdoor,surfaceCategory:u.surfaceCategory,endDate:u.endDate},A=Ln({policyDefinitions:c,tournamentRecord:u,contextProfile:m});return{matchUps:h.flatMap(y=>(T.eventDrawsCount=y.drawDefinitions?.length??0,co({context:T,scheduleVisibilityFilters:o,tournamentAppliedPolicies:S,participantsProfile:i,afterRecoveryTimes:s,policyDefinitions:c,tournamentRecord:u,contextContent:A,contextFilters:l,contextProfile:m,matchUpFilters:d,participantMap:r,nextMatchUps:f,participants:n,inContext:p,event:y}).matchUps??[])).concat(...u.matchUps??[])}}function cn({scheduleVisibilityFilters:t,afterRecoveryTimes:e,participantsProfile:r,tournamentRecords:n,policyDefinitions:o,matchUpFilters:i,contextFilters:s,nextMatchUps:a,inContext:c}){return typeof n!="object"||!Object.keys(n).length?{error:Ft}:{matchUps:Object.keys(n).map(m=>{let d=n[m];return le({scheduleVisibilityFilters:t,afterRecoveryTimes:e,participantsProfile:r,policyDefinitions:o,tournamentRecord:d,matchUpFilters:i,contextFilters:s,nextMatchUps:a,inContext:c}).matchUps??[]}).flat()}}function hi(t,e){return yF(t,e)||(t?.stageSequence||0)-(e?.stageSequence||0)||t?.roundNumber&&e.roundNumber&&t?.roundNumber-e?.roundNumber||(t?.roundPosition??0)-(e?.roundPosition??0)}function yF(t,e){return(_s[t?.stage]||0)-(_s[e?.stage]||0)}function rr(t){let{participants:e,participantMap:r,contextContent:n}=t,{scheduleVisibilityFilters:o,tournamentAppliedPolicies:i,participantsProfile:s,afterRecoveryTimes:a,policyDefinitions:c,useParticipantMap:u,tournamentRecord:p,matchUpFilters:m,contextFilters:d,contextProfile:l,drawDefinition:f,nextMatchUps:g,inContext:I,context:h,event:S}=t,{eventId:T,eventName:A,endDate:D,eventType:y,category:E,gender:U,matchUpFormat:M}=S??{},P={...h,surfaceCategory:S?.surfaceCategory??p?.surfaceCategory,indoorOutDoor:S?.indoorOutdoor??p?.indoorOutdoor,matchUpFormat:M,eventType:y,eventName:A,category:E,eventId:T,endDate:D,gender:U},N;return!e?.length&&!r&&p&&({participants:e=[],participantMap:r,groupInfo:N}=Ii({participantsProfile:s,useParticipantMap:u,policyDefinitions:c,tournamentRecord:p,contextProfile:l,inContext:I})),l&&!n&&(n=Ln({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 Vr(t){let e=Xr(t),r=t.matchUps??[],n=t.drawIds??[],{includeParticipantDependencies:o,tournamentRecord:i,drawDefinition:s}=t;if(!Array.isArray(r))return{error:Sn};if(!Array.isArray(n))return{error:Wr};let a=t.matchUpIds?.length?t.matchUpIds:r.map(T=>T.matchUpId);if(!Array.isArray(a))return{error:ia};let c={},u={},p={},m={};i&&!Object.keys(e).length&&(e={[i.tournamentId]:i});let d=Object.values(e),f=d.reduce((T,A)=>T.concat(A.events??[]).map(D=>(D.drawDefinitions||[]).map(y=>y.links||[])).flat(1/0),[]).filter(({linkType:T})=>T===jn),g=r;if(f.length){g=cn({nextMatchUps:!0,tournamentRecords:e}).matchUps;let T=f.reduce((A,D)=>{let y=D.source?.structureId,E=D.target?.structureId;return y&&E&&(p[E]=y),y&&!A.includes(y)&&A.push(y),A},[]);for(let A of T)c[A]=[];for(let A of g??[]){let D=A.containerStructureId||A.structureId;T.includes(D)&&c[D].push(A.matchUpId)}}let I=T=>{u[T]||(u[T]={dependentMatchUpIds:[],participantIds:[],matchUpIds:[],sources:[]},m[T]=[])},h=(T,A)=>{u[T].matchUpIds.forEach(y=>{u[A].matchUpIds.push(y)}),u[A].matchUpIds.push(T),u[T].dependentMatchUpIds.push(A),o&&u[T].participantIds.forEach(y=>u[A].participantIds.push(y))},S=T=>{let A=Object.keys(c).length;for(let D of T||[]){let{matchUpId:y,winnerMatchUpId:E,loserMatchUpId:U}=D;if(!a.length||a.includes(y)){if(I(y),o){let{individualParticipantIds:N}=eu(D);u[y].participantIds=N}E&&(I(E),h(y,E),m[E].push(y)),U&&(I(U),h(y,U),m[U].push(y)),u[y].sources.push(m[y]);let M=m[y].map(N=>u[N].sources[0]).flat(),P=m[y].map(N=>u[N].sources[1]).flat();if(u[y].sources.push(M,P),A){let N=D.containerStructureId||D.structureId,C=p[N];if(c[C])for(let O of c[C])I(O),h(O,y),m[O].push(y)}}}};if(s)wi({drawDefinition:s}),g?.length||(g=rr({drawDefinition:s}).matchUps),S(g);else{if(g?.length||(g=cn({nextMatchUps:!0,tournamentRecords:e}).matchUps),!n.length){let T=d?.length?d.map(({events:A=[]})=>A.map(({drawDefinitions:D=[]})=>D.map(({drawId:y})=>y))).flat(1/0):[];T&&(n=T)}for(let T of n){let A=g?.filter(y=>y.drawId===T).sort(hi);if(!A?.find(({roundPosition:y})=>!y)){let y=A?.find(({tournamentId:U})=>U),{drawDefinition:E}=We({tournamentRecord:e[y?.tournamentId],drawId:T});E&&wi({drawDefinition:E})}S(A)}}return{positionDependencies:c,matchUpDependencies:u,sourceMatchUpIds:m,matchUps:g,...R}}function Ie(t){let e=t?.matchUp,r=t?.score||e?.score,n=r?.sets?.[0],{side1Score:o,side2Score:i,side1TiebreakScore:s,side2TiebreakScore:a,side1PointScore:c,side2PointScore:u}=n||{},p=o||i||s||a||c||u;return!!(r?.sets?.length>1||p)}function Ea({matchUpStatus:t}){return YI.includes(t)}function mb({matchUpStatus:t}){return Nm.includes(t)}function Gf({matchUpStatus:t}){return qI.includes(t)}function kf({matchUpStatus:t,winningSide:e,tieMatchUps:r,sides:n,score:o}){let i=n?.find(({participantId:c})=>c),s=r?.filter(kf)?.length;return Ie({score:o})||s||e&&i||t&&mb({matchUpStatus:t})&&![Ot,_t,Dn].includes(t)}function Ua(t){let{drawDefinition:e,findContainer:r,structureId:n,event:o}=t,i=t.structure,s={isCollectionMatchUp:!1},{containedStructures:a}=Ji({drawDefinition:e}),c=n?a[n]||[]:[];if(!i){let E=st({drawDefinition:e,structureId:n});if(E.error)return E;i=r?E.containingStructure??E.structure:E.structure}if(fr({structure:i}))return{structure:i,isAdHoc:!0,error:ys};let{matchUps:u}=re({inContext:!0,matchUpFilters:s,drawDefinition:e,event:o}),p=u?.filter(E=>E.structureId===n||c.includes(E.structureId)),{matchUpDependencies:m}=Vr({drawIds:[e.drawId],matchUps:u,drawDefinition:e}),d=[],l=[],f={},g=[];for(let E of u??[]){if(E.structureId===n||c.includes(E.structureId)){l.push(...E.drawPositions??[]);let U=E.roundNumber;for(let M of(E.drawPositions??[]).filter(Boolean))(!f[M]||U&&f[M]>U)&&(f[M]=U)}kf(E)&&(g.push(E),d.push(E.matchUpId,...m?.[E?.matchUpId]?.matchUpIds||[]))}let I=pt(l.filter(Boolean)).sort(se),h=pt(d),S=pt(p?.map(({matchUpId:E,drawPositions:U})=>h.includes(E)?U:[]).flat().filter(Boolean)).sort(se),{positionAssignments:T}=Nt({drawDefinition:e,structure:i}),A=T?.filter(E=>E.bye).map(E=>E.drawPosition),D=T?.filter(E=>E.qualifier).map(E=>E.drawPosition),y=I?.filter(E=>!S.includes(E))||[];return{allDrawPositions:I,inContextStructureMatchUps:p,drawPositionInitialRounds:f,activeDependentMatchUpIds:h,qualifyingDrawPositions:D,inactiveDrawPositions:y,positionAssignments:T,activeDrawPositions:S,byeDrawPositions:A,activeMatchUps:g,structure:i}}function ss({drawPosition:t,matchUps:e=[]}){return{initialRoundNumber:e.filter(({drawPositions:n})=>t&&n?.includes(t)).map(({roundNumber:n})=>n).sort(se)[0]}}var Pa={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 Ch=[];function kn(t,e){typeof t=="string"&&(t={method:t}),(e||yr())&&Ch.push(t)}function EF(t){let e=Ch.slice();return t&&(Ch.length=0),e}function db(t){let r=EF(t).map(n=>{let{color:o,keyColors:i,method:s,newline:a}=n,c=Object.keys(Pa).includes(o)?Pa[o]:Pa.cyan,p=Object.keys(n).filter(d=>!["color","keyColors","method","newline"].includes(d)).map(d=>{let l=i&&Object.keys(i).includes(d)&&Pa[i[d]]?Pa[i[d]]:Pa.brightwhite;return`${Pa.white}${d}: ${l}${n[d]}`}).join(", "),m=s?.length<15?" ":" ";return[a?`
|
|
2
2
|
`:"",c,s,m,Pa.white,p,Pa.reset,`
|
|
3
3
|
`].join("")});r?.length&&console.log(...r)}function lb(){Ch.length=0}function Dr({provisionalPositioning:t,isPositionAction:e,tournamentRecord:r,drawDefinition:n,drawPosition:o,matchUpsMap:i,structureId:s,structure:a,event:c}){if(!n)return{error:X};if(a||({structure:a}=st({drawDefinition:n,structureId:s})),!a)return{error:Lt};s||({structureId:s}=a);let u="assignDrawPositionBye";kn({method:u,color:"cyan",drawPosition:o}),i||(i=Ae({drawDefinition:n}));let{positionAssignments:p}=Nt({structure:a}),{activeDrawPositions:m}=Ua({drawDefinition:n,structureId:s});if(p?.find(N=>N.drawPosition===o)?.bye)return{...R};if(m?.includes(o))return{error:ku};let f=p?.find(N=>N.drawPosition===o);if(!f)return{error:ys};let{filled:g,containsBye:I,assignedParticipantId:h}=UF(f);if(I)return{...R};if(g&&!I)return _({result:{error:Ha},stack:u});let S=re({inContext:!0,drawDefinition:n,matchUpsMap:i}).matchUps??[],T={isCollectionMatchUp:!1},{matchUps:A}=At({provisionalPositioning:t,drawDefinition:n,matchUpFilters:T,matchUpsMap:i,structure:a});if(p?.forEach(N=>{N.drawPosition===o&&(N.bye=!0)}),a.structureType===Le)return PF({tournamentRecord:r,drawDefinition:n,drawPosition:o,matchUps:A}),To({tournamentId:r?.tournamentId,drawDefinition:n,structure:a,event:c}),fb({assignedParticipantId:h,isPositionAction:e,drawDefinition:n,drawPosition:o,structureId:s,stack:u});let{roundProfile:D,roundMatchUps:y}=He({matchUps:A}),U=(D&&Object.keys(D).map(N=>parseInt(N)).reverse())?.find(N=>D?.[N].drawPositions?.includes(o)),M=U?y?.[U].find(({drawPositions:N})=>N?.includes(o)):void 0;M&&gb({tournamentRecord:r,drawDefinition:n,matchUp:M,event:c});let P=M?.drawPositions?.find(N=>N!==o);if(M&&P){let N=Rh({sourceDrawPositions:M.drawPositions,matchUpId:M.matchUpId,inContextDrawMatchUps:S,drawPositionToAdvance:P,tournamentRecord:r,drawDefinition:n,matchUpsMap:i});if(N.error)return N}return To({tournamentId:r?.tournamentId,drawDefinition:n,structure:a,event:c}),fb({assignedParticipantId:h,isPositionAction:e,drawDefinition:n,drawPosition:o,structureId:s,stack:u})}function fb({assignedParticipantId:t,isPositionAction:e,drawDefinition:r,drawPosition:n,structureId:o,stack:i}){return e&&tu({drawDefinition:r,positionAction:{removedParticipantId:t,drawPosition:n,structureId:o,name:i}}),_({result:{...R},stack:i})}function UF(t){let e=t.bye,r=t.qualifier,n=t.participantId;return{containsBye:e,containsQualifier:r,assignedParticipantId:n,filled:e||r||n}}function gb({tournamentRecord:t,drawDefinition:e,eventId:r,matchUp:n,event:o}){Object.assign(n,{matchUpStatus:Dt,score:void 0,winningSide:void 0}),It({tournamentId:t?.tournamentId,eventId:r??o?.eventId,context:"setMatchUpStatusBye",drawDefinition:e,matchUp:n})}function PF({tournamentRecord:t,drawDefinition:e,drawPosition:r,matchUps:n,event:o}){n.forEach(i=>{i.drawPositions?.includes(r)&&gb({eventId:o?.eventId,tournamentRecord:t,drawDefinition:e,matchUp:i})})}function Rh({drawPositionToAdvance:t,inContextDrawMatchUps:e,sourceDrawPositions:r,tournamentRecord:n,drawDefinition:o,matchUpsMap:i,matchUpId:s,event:a}){kn({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}=st({drawDefinition:o,structureId:m}),{positionAssignments:l}=Nt({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:A}}=er({inContextDrawMatchUps:e,drawDefinition:o,matchUpId:s});if(T&&T.structureId===d?.structureId&&DF({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 y=Dr({structureId:h.target.structureId,drawPosition:A,tournamentRecord:n,drawDefinition:o,event:a});if(y.error)return y}else Ib({loserTargetDrawPosition:A,tournamentRecord:n,loserTargetLink:h,drawDefinition:o,loserMatchUp:S,matchUpsMap:i,event:a})}return{...R}}function DF({drawPositionToAdvance:t,inContextDrawMatchUps:e,sourceDrawPositions:r,tournamentRecord:n,drawDefinition:o,winnerMatchUp:i,matchUpsMap:s,event:a}){let c="advanceWinner",u=s.drawMatchUps.find(L=>L.matchUpId===i.matchUpId),m=e.find(L=>L.matchUpId===i.matchUpId)?.structureId,{structure:d}=st({drawDefinition:o,structureId:m}),{positionAssignments:l}=Nt({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,y=g&&D;if(y&&console.log({isByeAdvancedBye:y}),I?.length>1&&g&&!D)return _({result:{error:Ha},stack:c});let E=I?.find(L=>L!==t),U=y,M=[...(u.drawPositions||[]).filter(Boolean),void 0,void 0].slice(0,2),P=M.map(L=>!L&&!U||L===t?(U=!0,t):L).sort(se);if(!U)return console.log("@@@@@@@",{advancingAssignmentIsBye:S,drawPositionToAdvance:t,existingAssignments:h}),_({result:{error:Ha},stack:c});let N=l?.find(({drawPosition:L})=>L===E)?.bye,C=l?.find(({drawPosition:L})=>L===t)?.bye;Object.assign(u,{matchUpStatus:C||N?Dt:zt,score:void 0,winningSide:void 0,drawPositions:P});let b=u.drawPositions.find(L=>!M.includes(L));kn({method:c,color:"brightyellow",changedDrawPosition:b,pairedDrawPositionIsBye:N,drawPositionIsBye:C}),It({tournamentId:n?.tournamentId,matchUp:u,eventId:a?.eventId,context:c,drawDefinition:o});let{targetLinks:{loserTargetLink:x},targetMatchUps:{loserMatchUp:w,loserTargetDrawPosition:F}}=er({matchUpId:i.matchUpId,inContextDrawMatchUps:e,drawDefinition:o});if(N||C){let L=N?t:E;if(L)Rh({drawPositionToAdvance:L,matchUpId:i.matchUpId,inContextDrawMatchUps:e,tournamentRecord:n,drawDefinition:o,matchUpsMap:s});else if(C&&x&&w)if(w.feedRound)Ib({loserTargetDrawPosition:F,tournamentRecord:n,loserTargetLink:x,drawDefinition:o,loserMatchUp:w,matchUpsMap:s});else{let B=1-i.roundPosition%2,H=w.drawPositions[B],j=Dr({structureId:x.target.structureId,drawPosition:H,tournamentRecord:n,drawDefinition:o,event:a});if(j.error)return j}}}function Ib({loserTargetDrawPosition:t,tournamentRecord:e,loserTargetLink:r,drawDefinition:n,loserMatchUp:o,matchUpsMap:i,event:s}){let{roundNumber:a}=o;kn({method:"assignFedDrawPositionBye",color:"cyan",loserTargetDrawPosition:t});let p=(i?.mappedMatchUps||{})[o.structureId].matchUps,{initialRoundNumber:m}=ss({drawPosition:t,matchUps:p});if(m===a){let d=Dr({structureId:r.target.structureId,drawPosition:t,tournamentRecord:e,drawDefinition:n,event:s});if(d.error)return d}}function bh({positionAssignments:t,tournamentRecord:e,drawDefinition:r,matchUpsMap:n,structure:o,event:i}){let{matchUps:s}=At({drawDefinition:r,matchUpsMap:n,structure:o,event:i});s.forEach(a=>{let u=t.filter(({drawPosition:p})=>a.drawPositions?.includes(p)).filter(p=>p.bye).length;a.winningSide||(Object.assign(a,{matchUpStatus:u?Dt:zt}),It({tournamentId:e?.tournamentId,context:"modifyRoundRobinMatchUpsStatus",eventId:i?.eventId,drawDefinition:r,matchUp:a}))})}function dc(t){let{inContextDrawMatchUps:e,participantId:r,drawPosition:n}=t,{tournamentRecord:o,drawDefinition:i,structureId:s,matchUpsMap:a,event:c}=t,{structure:u}=st({drawDefinition:i,structureId:s}),m=(de({drawDefinition:i,structure:u}).positionAssignments||[]).find(g=>r&&g.participantId===r||n&&g.drawPosition===n);if(m&&r&&!n&&(n=m?.drawPosition),!n)return{error:Es};r||(r=m?.participantId);let{activeDrawPositions:d}=Ua({drawDefinition:i,structureId:s});return d.includes(n)?{error:ku}:(e||({matchUps:e}=re({inContext:!0,drawDefinition:i,matchUpsMap:a})),cU({inContextDrawMatchUps:e,tournamentRecord:o,drawDefinition:i,structureId:s,drawPosition:n,matchUpsMap:a,event:c}).drawPositionCleared?(To({tournamentId:o?.tournamentId,drawDefinition:i,structure:u,event:c}),{...R,participantId:r}):{error:ny})}function cU({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,matchUpsMap:o,structureId:i,event:s}){let{structure:a}=st({drawDefinition:r,structureId:i});if(!a)return{error:Lt};let c=de({drawDefinition:r,structure:a}).positionAssignments||[],u=c.some(T=>{if(T.drawPosition===n)return delete T.participantId,delete T.qualifier,delete T.bye,!0});if(a.structureType===Le)return bh({positionAssignments:c,tournamentRecord:e,drawDefinition:r,matchUpsMap:o,structure:a}),{drawPositionCleared:u,...R};let p={isCollectionMatchUp:!1},{matchUps:m}=At({drawDefinition:r,matchUpFilters:p,matchUpsMap:o,structure:a,event:s}),{roundProfile:d,roundMatchUps:l}=He({matchUps:m}),g=(d&&Object.keys(d))?.map(T=>ct(T)),I=n,S=g?.map(T=>{let D=d?.[T]?.pairedDrawPositions?.find(b=>b.includes(I)),y=D?.find(b=>b!==I),E=c.find(b=>b.drawPosition===y),U=d?.[T+1],M=E?.bye,P=U?.pairedDrawPositions?.find(b=>b.includes(y)),N=M&&P&&U&&U.drawPositions?.includes(y),O=D&&{pairedDrawPositionByeAdvancedPair:!N&&P,pairedDrawPosition:y,targetDrawPosition:I,relevantPair:D,roundNumber:T};return N&&(I=y),O}).filter(T=>T?.targetDrawPosition)?.reduce((T,A)=>{let{roundNumber:D,relevantPair:y,targetDrawPosition:E,pairedDrawPosition:U,pairedDrawPositionByeAdvancedPair:M}=A,P={roundNumber:D,targetDrawPosition:E,relevantPair:y},N=M&&{roundNumber:D+1,targetDrawPosition:U,relevantPair:M,subsequentRoundRemoval:!0},C=[P,N].filter(Boolean);return T.concat(...C)},[]);return S?.forEach(({roundNumber:T,targetDrawPosition:A,relevantPair:D})=>{let y=l?.[T].find(E=>xe(E.drawPositions?.filter(Boolean),D.filter(Boolean)));y&&(NF({inContextDrawMatchUps:t,targetDrawPosition:A,tournamentRecord:e,drawDefinition:r,structureId:i,roundNumber:T,matchUpsMap:o}),hb({inContextDrawMatchUps:t,positionAssignments:c,tournamentRecord:e,drawDefinition:r,targetMatchUp:y,drawPosition:n,matchUpsMap:o,structure:a,event:s}))}),{tasks:S,drawPositionCleared:u,positionAssignments:c}}function NF({inContextDrawMatchUps:t,targetDrawPosition:e,tournamentRecord:r,drawDefinition:n,matchUpsMap:o,roundNumber:i,structureId:s}){let{structure:a}=st({drawDefinition:n,structureId:s});if(!a)return{error:Lt};if(a.structureType===Le)return;o=o||Ae({drawDefinition:n});let u=(o?.mappedMatchUps||{})[s].matchUps,{initialRoundNumber:p}=ss({drawPosition:e,matchUps:u}),m=u?.filter(l=>l.roundNumber>=i&&l.roundNumber!==p&&l.drawPositions?.includes(e)),d=Nt({drawDefinition:n,structureId:s}).positionAssignments??[];return m?.forEach(l=>hb({drawPosition:e,targetMatchUp:l,inContextDrawMatchUps:t,positionAssignments:d,tournamentRecord:r,drawDefinition:n,matchUpsMap:o,structure:a})),{...R}}function hb({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??Ae({drawDefinition:n});let f=s.mappedMatchUps[a.structureId].matchUps,{initialRoundNumber:g}=ss({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===Bt){let C=(t?.find(O=>O.matchUpId===o.matchUpId)?.sides??[]).reduce((O,b,x)=>b.drawPosition===i?x:O,void 0);C!==void 0&&o.sides?.[C]?.lineUp&&(delete o.sides?.[C].lineUp,It({tournamentId:r?.tournamentId,context:`${u}-TEAM`,eventId:c?.eventId,matchUp:o,drawDefinition:n}))}let I=er({matchUpId:o.matchUpId,inContextDrawMatchUps:t,drawDefinition:n}),{targetLinks:{winnerTargetLink:h},targetMatchUps:{loserMatchUp:S,winnerMatchUp:T,loserMatchUpDrawPositionIndex:A}}=I,y=e.filter(({drawPosition:P})=>o.drawPositions?.includes(P)).filter(P=>P.bye).length,E=y&&Dt||o.matchUpStatus&&[Ot,_t].includes(o.matchUpStatus)&&o.matcHUpStatus||o.drawPositions?.length===2&&zt||void 0;o.matchUpStatus=E,o.matchUpStatus&&[_t,Ot].includes(o.matchUpStatus)&&(o.winningSide=void 0);let U=p?.find(P=>!o.drawPositions?.includes(P));if(p?.includes(i)&&m===o.matchUpStatus&&d===o.winningSide||(U&&kn({method:u,color:"brightyellow",removedDrawPosition:U}),It({tournamentId:r?.tournamentId,eventId:c?.eventId,matchUp:o,context:`${u}-${i}`,drawDefinition:n})),S&&S.structureId!==I.matchUp.structureId&&!y){let{drawPositions:P,roundNumber:N}=S;if(N===1){let C=P[A];cU({structureId:S.structureId,drawPosition:C,inContextDrawMatchUps:t,tournamentRecord:r,drawDefinition:n,matchUpsMap:s})}else{let C=Math.min(...P.filter(Boolean)),O=MF({loserMatchUpDrawPosition:C,inContextDrawMatchUps:t,tournamentRecord:r,drawDefinition:n,loserMatchUp:S,matchUpsMap:s,event:c});if(O.error)return _({result:O,stack:u});let x=(s?.mappedMatchUps||{})[S.structureId].matchUps,{initialRoundNumber:w}=ss({drawPosition:C,matchUps:x});w===1&&(kn({method:u,color:"brightyellow",loserMatchUpDrawPosition:C}),cU({structureId:S.structureId,drawPosition:C,inContextDrawMatchUps:t,tournamentRecord:r,drawDefinition:n,matchUpsMap:s}))}}return T&&T.structureId!==I.matchUp.structureId&&(h.target.feedProfile,Qr),{...R}}function MF({loserMatchUpDrawPosition:t,inContextDrawMatchUps:e,tournamentRecord:r,drawDefinition:n,loserMatchUp:o,matchUpsMap:i,event:s}){let{structure:a}=st({structureId:o.structureId,drawDefinition:n}),{positionAssignments:c}=Nt({structure:a});if(c?.find(p=>p.drawPosition===t)?.bye){let p=dc({drawPosition:t,structureId:o.structureId,inContextDrawMatchUps:e,tournamentRecord:r,drawDefinition:n,matchUpsMap:i,event:s});if(p.error)return p}return{...R}}function Si({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}=Nt({structure:o});return i?i.map(gt):[]}).flat().filter(Boolean));return{...R,assignedParticipantIds:n}}function Vn(t){let e=(t?.entries??[]).filter(Boolean).reduce((n,o)=>{let{entryStage:i,entryStatus:s}=o,a=`_${i||tt}${s||""}`;return n[a]||(n[a]=[]),n[a].push(o),n},{}),r=n=>isNaN(n)?1/0:n;return Object.keys(e).map(n=>e[n].sort((o,i)=>r(o.entryPosition)-r(i.entryPosition)).map((o,i)=>{let s=i+1;return{...o,entryPosition:s}})).flat()}function Bs(t){return[pi,Lr].includes(t)}function zm({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:Et};if(i&&!zE.includes(i))return{error:Ml};if(s&&!Mm.includes(s))return{error:Di};let d="modifyEntriesStatus",l=[];if(!i&&!a)return _({result:{error:et},info:"Missing entryStatus",stack:d});if(a&&!Pn({extension:a,requiredAttributes:["name"]}))return _({result:{error:G},info:"Invalid extension",context:{extension:a},stack:d});let f=[];m?.drawDefinitions?.forEach(P=>{let N=Si({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&&[dt,Jr].includes(N)&&Bs(i))&&!(i&&m?.eventType&&N===ht&&[Kr,kr].includes(m.eventType)&&[wr,...Mf].includes(i))}))return{error:Ml};let h=m&&Ht({event:m}).flightProfile,S=h?.flights?.find(P=>P.drawId===u),T=P=>{let N=(P||[]).filter(b=>!p||!b.entryStage||p===b.entryStage).filter(({participantId:b})=>o.includes(b)),C=b=>i&&f.includes(b.participantId)&&!(Mf.includes(b.entryStatus)&&Mf.includes(i));return N.every(b=>C(b)&&!e?!1:(i&&(b.entryStatus=i,delete b.entryPosition),s&&(b.entryStage=s,delete b.entryPosition),a&&(a.value?St({element:b,extension:a}):or({element:b,name:a.name})),!0))?{...R}:{error:Ps}},A=({flight:P,drawDefinition:N})=>{m&&(m.entries=Vn({entries:m.entries??[]})),P&&(P.drawEntries=Vn({entries:P.drawEntries})),N&&(N.entries=Vn({entries:N.entries}))},D=P=>{let{flight:N,drawDefinition:C}=P,O="updateDrawEntries";if(N){let b=T(N.drawEntries);if(b.error)return _({result:b,stack:O})}if(C){let b=T(C.entries);if(b.error)return _({result:b,stack:O});l.includes(C.drawId)||l.push(C.drawId)}return{...R}},y=m?.entries?.find(({entryPosition:P})=>P)??(S?.drawEntries?.find(({entryPosition:P})=>P)||n?.entries?.find(({entryPosition:P})=>P));if(t&&!y&&A({flight:S,drawDefinition:n}),S||n){let P=D({flight:S,drawDefinition:n});if(P.error)return _({result:P,stack:d})}let E=m?.drawDefinitions?.map(({drawId:P})=>P)??[],U=h?.flights?.filter(P=>!E.includes(P.drawId))||[];for(let P of U){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&&KE.includes(i))return{error:Fy};if(!S&&!n||i===Ao||c&&M){let P=T(m?.entries);if(P?.error)return _({result:P,stack:d});let N;if(i===Ao&&(h?.flights?.every(C=>{let O=T(C.drawEntries);return O.error?(N=O.error,!1):(C.drawEntries=C.drawEntries.filter(({participantId:b})=>!o.includes(b)),!0)}),m?.drawDefinitions?.every(C=>{let O=T(C.entries);return O.error?(N=O.error,!1):(C.entries=C.entries?.filter(({participantId:b})=>!o.includes(b)),!0)})),N)return _({result:{error:N},stack:d})}t&&A({flight:S,drawDefinition:n});for(let P of m?.drawDefinitions??[])l.length&&!l.includes(P.drawId)||bt({tournamentId:r.tournamentId,eventId:m?.eventId,drawDefinition:P});return{...R}}function Oh(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===Dt||e[r].scheduleItems.push({...p,scheduledDate:Ut(p?.scheduledDate),scheduledTime:$t(p?.scheduledTime),checkScoreHasValue:Ie({score:d}),matchUpStatus:n,roundPosition:o,structureId:i,matchUpType:s,roundNumber:a,matchUpId:c,potential:u,drawId:m})}function uo({requireTimeStamp:t,scaleAttributes:e,participant:r}){if(!r)return{error:Mi};if(!Rt(e))return{error:G};if(r.timeItems||(r.timeItems=[]),Array.isArray(r.timeItems)){let{accessor:n,scaleType:o,eventType:i,scaleName:s}=e,a=[zi,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!==zi)return{error:ju};let g=(n&&Zi({element:u.itemValue,accessor:n}))?.value||u.itemValue,I={eventType:d,scaleDate:u.itemDate,scaleValue:g,scaleName:l,scaleType:m};return{...R,scaleItem:I}}}return{...R,scaleItem:void 0}}function Sb({publishedSeeding:t,usePublishState:e,withSeeding:r,participant:n,event:o}){let i={},s=m=>[zi,eo,o.eventType,m].join("."),a=Object.assign({},...(n.timeItems||[]).filter(({itemType:m})=>m.split(".")[1]===eo).map(({itemType:m,itemValue:d})=>({[m]:d}))),c=(t?.stageSeedingScaleNames&&Object.values(t?.stageSeedingScaleNames)||Array.isArray(t?.seedingScaleNames)&&t.seedingScaleNames||[]).map(s),u=jt(Object.keys(a),c);if(!!(!e||!Object.keys(a).length&&!t?.drawIds?.length||u.length)&&u.length){if(t?.stageSeedingScaleNames){let m=Object.keys(t.stageSeedingScaleNames).map(l=>{let f=s(t.stageSeedingScaleNames[l]),g=a[f];return[l,g]}).filter(l=>l[1]).map(l=>({[l[0]]:{seedValue:l[1]}})),d=Object.assign({},...m);i.seedAssignments=d}else if(u){let m=u.map(d=>a[d]);i.seedValue=m.pop()}}else if(!e&&typeof r=="object"){let m=Object.keys(r).map(l=>{let f=s(r[l]),g=a[f];return[l,g]}).filter(l=>l[1]).map(l=>({[l[0]]:{seedValue:l[1]}})),d=Object.assign({},...m);i.seedAssignments=d}else{let{categoryName:m,ageCategoryCode:d}=o.category||{},l=[d,o.eventId,m].filter(Boolean),f;for(let g of l){let I={eventType:o.eventType,scaleType:eo,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 Tb({convertExtensions:t,seedAssignments:e,participant:r,withSeeding:n,seedValue:o,eventId:i,ranking:s,entry:a}){let{entryStatus:c,entryStage:u,entryPosition:p,extensions:m}=a,d=m?.length&&t?Object.assign({},...Xl(m??[])):{},l=Object.assign(d,{entryPosition:p,entryStatus:c,entryStage:u,ranking:s,eventId:i});r.events[i]=rt(l,!1,!1,!0),n&&(e&&(r.events[i].seedAssignments=e),o&&(r.events[i].seedValue=o))}function du(t,e){return(t||"").localeCompare(e||"")}function Ab({tournamentRecord:t,status:e=Gr}){let r=`${Ko}.${zo}`;return mu({tournamentRecord:t,itemType:r})?.timeItem?.itemValue?.[e]}function yb(t){let{tournamentId:e}=t??{};return!!e}function vr({event:t,status:e=Gr}){let r=`${Ko}.${zo}`;return pu({itemType:r,event:t})?.timeItem?.itemValue?.[e]}function Qm({drawDetails:t,drawId:e}){return t?.[e]?.publishingDetail?.published}function as(t){let{tournamentRecord:e,drawDefinition:r,eventIds:n,eventId:o,drawIds:i,drawId:s,event:a}=t??{};if(e&&!yb(e))return{error:G};if(o&&!a)return{error:mr};if(Array.isArray(n)&&n?.length){let d={};for(let l of n){if(!$e(l))return{error:G};let f=We({tournamentRecord:e,eventId:l})?.event;if(!f)return{error:mr};let g=uU({event:f});d[l]=g}return{...R,publishState:d}}if(a){let d=uU({event:a}),l={};if(s)return r?{publishState:{status:{published:!!d.status.publishedDrawIds?.includes(s),drawDetail:d.status.drawDetails?.[s]},...R}}:{error:pr};if(Array.isArray(i)&&i?.length){let f=a.drawDefinitions?.map($c)??[];for(let g of i){if(!$e(g))return{error:G};if(!f.includes(g))return{error:pr};l[g]={status:{published:!!d.status.publishedDrawIds.includes(g),drawDetail:d.status.drawDetails?.[g]}}}}else l=d;return{...R,publishState:l}}let c=[],u=!1,p={},m=Ab({tournamentRecord:e});p.tournament=m??{};for(let d of e?.events??[]){let l=uU({event:d});p[d.eventId]=l,l.status.published&&(c.push(d.eventId),u=!0);for(let{drawId:f}of d.drawDefinitions??[]){let g=l.status?.publishedDrawIds?.includes(f);g&&(p[f]={status:{published:g}})}}return e&&(p.tournament.status={published:u,publishedEventIds:c}),{...R,publishState:p}}function uU({event:t}){let e=vr({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($c)||[])n[i]||(n[i]={publishingDetail:{published:!1}});let o=n&&Object.keys(n).length&&Object.keys(n).filter(i=>Qm({drawDetails:n,drawId:i}))||e.drawIds;return{status:{published:o&&o.length>0,publishedDrawIds:o,publishedSeeding:r,drawDetails:n}}}function Eb({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===_t&&(f.walkoverWinCount+=1),o===Ot&&(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 pU(t){let{withScheduleItems:e,scheduleAnalysis:r,withTeamMatchUps:n,participantMap:o,withOpponents:i,withMatchUps:s,withEvents:a,withDraws:c,finishingPositionRange:u,finishingRound:p,matchUpStatus:m,stageSequence:d,roundNumber:l,structureId:f,score:g,stage:I,withRankingProfile:h,tieWinningSide:S,roundPosition:T,matchUpTieId:A,matchUpSides:D,collectionId:y,matchUpType:E,winningSide:U,matchUpId:M,schedule:P,eventId:N,drawId:C,sides:O}=t,b=i&&O?.length===2&&Object.assign({},...O.map(({sideNumber:x},w)=>{let F=O[1-w].participantId;return x&&{[x]:F}}).filter(Boolean));for(let x of O){let{participantId:w,sideNumber:F,bye:L}=x;if(L)continue;let v=U===F,B=V=>{let Y=o[V]?.participant,$=Y?.participantType,k=[{participantId:V,participantType:$}];if($!==Jr)for(let K of Y?.individualParticipantIds||[]){let z=o[K]?.participant;k.push({participantType:z?.participantType,participantId:K})}return k},H=(V,Y)=>{if(s){if(o[V].matchUps[M]={participantWon:v,matchUpType:E,structureId:f,sideNumber:F,matchUpId:M,eventId:N,drawId:C,stage:I},i){let $=B(Y);o[V].matchUps[M].opponentParticipantInfo=$}y&&(o[V].matchUps[M].collectionId=y)}i&&Y&&(o[V].opponents[Y]={participantId:Y,matchUpId:M,eventId:N,drawId:C}),h&&Eb({finishingPositionRange:u,participantMap:o,participantWon:v,finishingRound:p,matchUpStatus:m,participantId:V,stageSequence:d,roundNumber:l,structureId:f,matchUpId:M,drawId:C,stage:I}),(r||e)&&Oh({participantMap:o,participantId:V,matchUpStatus:m,roundPosition:T,matchUpType:E,roundNumber:l,structureId:f,matchUpId:M,schedule:P,drawId:C,score:g})},j=({participant:V,partnerParticipantId:Y})=>{let $=(k,K)=>{k&&(k.partnerParticipantIds||(k.partnerParticipantIds=[]),k.partnerParticipantIds.includes(K)||k.partnerParticipantIds.push(K))};c&&$(V?.draws?.[C],Y),a&&$(V?.events?.[N],Y),s&&$(V?.matchUps?.[M],Y)};if(w&&o[w]){let V=b?.[F];H(w,V);let Y=o[w]?.participant.participantType===dt,$=o[w]?.participant.individualParticipantIds||[];if(A){if(n){let k=K=>o[K].matchUps[A]={participantWon:S===F,matchUpId:A,matchUpType:Bt,sideNumber:F};k(w),$.forEach(k)}if(c&&!o[w].draws[C]){let k=D.find(q=>q.sideNumber===F)?.participant?.participantId,K=o[k]?.draws?.[C]?.entryStatus,z=q=>o[q].draws[C]={entryStatus:K,eventId:N,drawId:C};z(w),$.forEach(z)}}if(Y&&($.forEach(k=>o[k]&&H(k,V)),$.forEach((k,K)=>{let z=$[1-K],q=o[k];q&&j({participant:q,partnerParticipantId:z})}),a&&D)){let k=D.find(K=>K.sideNumber===F)?.participant?.participantId;if(k){let K=o[k]?.events[N];K?(o[w].events[N]={...K},$.forEach(z=>o[z].events[N]={...K})):console.log("Missing teamEntry",{eventId:N,teamParticipantId:k})}}if(U){let k=K=>{v?(o[K].counters[E].wins+=1,o[K].counters.wins+=1,m===_t&&(o[K].counters[E].walkoverWins+=1,o[K].counters.walkoverWins+=1),m===Ot&&(o[K].counters[E].defaultWins+=1,o[K].counters.defaultWins+=1)):(o[K].counters[E].losses+=1,o[K].counters.losses+=1,m===_t&&(o[K].counters[E].walkovers+=1,o[K].counters.walkovers+=1),m===Ot&&(o[K].counters[E].defaults+=1,o[K].counters.defaults+=1))};k(w),$.forEach(k)}}}}function Ub(t){let{participantFilters:e,convertExtensions:r,policyDefinitions:n,tournamentRecord:o,usePublishState:i,contextProfile:s,participantMap:a,withPotentialMatchUps:c,withRankingProfile:u,withScheduleItems:p,scheduleAnalysis:m,withTeamMatchUps:d,withStatistics:l,withOpponents:f,withMatchUps:g,withSeeding:I,withEvents:h,withDraws:S}=t,T=e?.participantIds,A=O=>{let b=[O];return a[O]?.participant.individualParticipantIds?.forEach(x=>b.push(x)),b.some(x=>!T?.length||T.includes(x))?b:[]},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},y=[],E={},U=[],M={},P={},N={},C=({eventType:O,scaleNames:b,participantId:x})=>a[x].participant?.rankings?.[O]?.find(w=>b.includes(w.scaleName))?.scaleValue;for(let O of o?.events||[]){if(e?.eventIds&&!e.eventIds.includes(O.eventId))continue;let{drawDefinitions:b=[],extensions:x=[],eventType:w,eventName:F,category:L,entries:v,eventId:B,gender:H}=O,{flightProfile:j}=Ht({event:O}),V=j?.flights??[],Y=as({event:O}).publishState;Y&&(M[B]=Y);let $=Y?.status?.publishedSeeding;if(h||I||u){let K=r?Object.assign({},...Xl(x??[])):{};P[B]={...K,eventName:F,eventType:w,category:L,eventId:B,gender:H};let z=[L?.categoryName,L?.ageCategoryCode].filter(Boolean);for(let q of v){let{participantId:nt}=q;if(!nt||!a[nt])continue;let Q=C({eventType:w,scaleNames:z,participantId:nt}),it,ot;if(I){let yt=a[nt].participant;({seedAssignments:it,seedValue:ot}=Sb({publishedSeeding:$,usePublishState:i,withSeeding:I,participant:yt,event:O}))}let ut=yt=>{if(a[yt]?.events?.[B])return;let Me=a[yt];Tb({convertExtensions:r,seedAssignments:it,participant:Me,withSeeding:I,seedValue:ot,eventId:B,ranking:Q,entry:q})};ut(nt),(a[nt].participant.individualParticipantIds||[]).forEach(ut)}}let k=M?.[B]?.publishedSeeding;if(S||u||I){let K=q=>q?Object.assign({},...q.map(({participantId:nt,seedValue:Q,seedNumber:it})=>({[nt]:{seedValue:Q,seedNumber:it}}))):void 0,z=pt([...b.map($c),...V.map($c)]);for(let q of z){let nt=b.find(Wt=>Wt.drawId===q),Q=V?.find(Wt=>Wt.drawId===q),it=nt?.entries||Q?.drawEntries,{structures:ot=[],drawOrder:ut,drawName:Qt,drawType:yt}=nt??{},Me=Q?.flightNumber,Ee=[L?.categoryName,L?.ageCategoryCode].filter(Boolean),Ce=(nt?.structures||[]).sort((Wt,ve)=>ci(Wt,ve)).map(({structureId:Wt,structures:ve})=>[Wt,...(ve||[]).map(({structureId:nr})=>nr)]).flat(1/0),Kt,Re,wt,Ue,Ct=0,vt=ot.filter(({stage:Wt,stageSequence:ve})=>Wt===tt&&ve===1||Wt===at).flatMap(Wt=>{let{seedAssignments:ve,stageSequence:nr,stage:be}=Wt,{positionAssignments:Nr}=Nt({structure:Wt});return be===tt?(Ct=Nr?.length??0,wt=Nr,Ue=ve):nr===1&&(Kt=Nr,Re=ve),Nr}).map(({participantId:Wt})=>Wt).filter(Boolean),ne=K(Ue),qt=K(Re),pe=nt?it.filter(({participantId:Wt})=>vt.includes(Wt)):it,he=!i||k?.published&&(k?.drawIds?.length===0||k?.drawIds?.includes(q));for(let Wt of pe){let{entryStatus:ve,entryStage:nr,entryPosition:be,participantId:Nr}=Wt,Se=C({participantId:Nr,scaleNames:Ee,eventType:w}),Pe=gr=>{if(a[gr].draws?.[q])return;let ri=I&&he,qe=ri?{}:void 0,bn=ri?ne?.[Nr]?.seedValue||ne?.[Nr]?.seedNumber:void 0,Ei=bn?ne?.[Nr]:void 0,Wi=ri?qt?.[Nr]?.seedValue||qt?.[Nr]?.seedNumber:void 0,hn=Wi?qt?.[Nr]:void 0;qe&&bn&&(qe[tt]=Ei),qe&&Wi&&(qe[at]=hn);let wc=bn||Wi;wc&&(a[gr].participant.seedings[w]||(a[gr].participant.seedings[w]=[]),Ei&&a[gr].participant.seedings[w].push({...Ei,scaleName:q}),hn&&a[gr].participant.seedings[w].push({...hn,scaleName:q}),qe&&(a[gr].events[B].seedAssignments||(a[gr].events[B].seedAssignments={}),Object.keys(qe).forEach(ji=>a[gr].events[B].seedAssignments[ji]=qe[ji]))),(S||u)&&(a[gr].draws[q]=rt({seedAssignments:qe,entryPosition:be,entryStatus:ve,entryStage:nr,seedValue:wc,eventId:B,ranking:Se,drawId:q},!1,!1,!0))};[Lr,pi].includes(ve)||(Pe(Nr),(a[Nr].participant.individualParticipantIds||[])?.forEach(Pe))}let ur=(nt?.structures??[]).reduce((Wt,ve)=>(Wt.includes(ve.stage)||Wt.push(ve.stage),Wt),[]),_e=(nt?.links??[]).length;N[q]={qualifyingPositionAssignments:Kt,qualifyingSeedAssignments:Re,mainPositionAssignments:wt,qualifyingSeedingMap:qt,mainSeedAssignments:Ue,orderedStructureIds:Ce,mainSeedingMap:ne,flightNumber:Me,linksCount:_e,drawOrder:ut,drawName:Qt,drawType:yt,drawSize:Ct,drawId:q,stages:ur}}}if(u||m||d||l||f||g||S){let K=!!m||c,z=co({afterRecoveryTimes:!!m,policyDefinitions:n,tournamentRecord:o,inContext:!0,contextProfile:s,participantMap:a,nextMatchUps:K,event:O})?.matchUps??[];for(let q of z){let{finishingPositionRange:nt,potentialParticipants:Q,tieMatchUps:it=[],sides:ot=[],winningSide:ut,matchUpType:Qt,matchUpId:yt,eventId:Me,drawId:Ee,collectionId:Ce,stageSequence:Kt,finishingRound:Re,matchUpStatus:wt,roundPosition:Ue,roundNumber:Ct,structureId:vt,schedule:ne,score:qt,stage:pe}=q;E[yt]=q;let he={finishingPositionRange:nt,finishingRound:Re,stageSequence:Kt,roundPosition:Ue,collectionId:Ce,roundNumber:Ct,structureId:vt,schedule:ne,eventId:Me,drawId:Ee,score:qt,stage:pe};pU({...he,...D,matchUpStatus:wt,winningSide:ut,matchUpType:Qt,matchUpId:yt,sides:ot});for(let ur of it){let{winningSide:_e,sides:Wt=[],matchUpId:ve,matchUpStatus:nr,matchUpType:be}=ur;pU({...he,...D,winningSide:_e,tieWinningSide:ut,matchUpTieId:yt,matchUpId:ve,sides:Wt,matchUpSides:ot,matchUpStatus:nr,matchUpType:be})}Array.isArray(Q)&&(K||m||p)&&Q.flat().map(gt).filter(Boolean)?.forEach(_e=>{A(_e)?.forEach(ve=>{a[ve]&&(a[ve].potentialMatchUps[yt]=rt({tournamentId:o?.tournamentId,matchUpId:yt,eventId:Me,drawId:Ee}))}),(m||p)&&Oh({potential:!0,participantMap:a,participantId:_e,matchUpStatus:wt,roundPosition:Ue,structureId:vt,matchUpType:Qt,roundNumber:Ct,matchUpId:yt,schedule:ne,drawId:Ee,score:qt})})}U.push(...z)}}if(l||u||m){let O=Object.values(a);for(let b of O){let{wins:x,losses:w,[Xt]:{wins:F,losses:L},[Gt]:{wins:v,losses:B}}=b.counters,H=(j,V,Y)=>{let $=V+Y,k=V,K=$&&k/$;b.statistics[j]={denominator:$,numerator:k,statValue:K,statCode:j}};if(l&&(H(Gm,x,w),H(`${Gm}.${Xt}`,F,L),H(`${Gm}.${Gt}`,v,B)),u){let j=(V=[])=>Math.abs(V[0]-V[1]);for(let V of Object.keys(b.draws)){let{orderedStructureIds:Y=[],flightNumber:$}=N[V]||{};if(b.structureParticipation&&Y.length){let k,K=0,z=Y.map(q=>{let nt=b.structureParticipation[q];if(!nt)return;k||(k=nt?.finishingPositionRange),j(k)>j(nt?.finishingPositionRange)&&(k=nt?.finishingPositionRange);let Q=nt.stage!==at;return Q&&(K+=1),rt({...nt,participationOrder:Q?K:void 0,flightNumber:$})}).filter(Boolean);b.draws[V]&&(b.draws[V].finishingPositionRange=k,b.draws[V].structureParticipation=z)}}}if(m){let j=Rt(m)?m.scheduledMinutesDifference:0,V=b.scheduleItems||[],Y=b.potentialMatchUps||{},$=V.reduce((K,z)=>{let{scheduledDate:q,scheduledTime:nt}=z;return K[q]||(K[q]=[]),nt&&K[q].push(z),K},{});Object.values($).forEach(K=>K.sort(GI));for(let K of V){let{typeChangeTimeAfterRecovery:z,timeAfterRecovery:q,scheduledDate:nt,scheduledTime:Q}=K,it=$[nt],ot=Vt(Q);for(let ut of it){if(ut.matchUpId===K.matchUpId||[_t,Ot].includes(ut.matchUpStatus)&&!ut.checkScoreHasValue)continue;let Me=K.matchUpType!==ut.matchUpType&&z||q,Ee=K.drawId===ut.drawId,Ce=Y[K.matchUpId]&&Y[ut.matchUpId],Kt=Vt(ut.scheduledTime),Re=Math.abs(Kt-ot),wt=Kt>=ot;if((j&&!isNaN(j)?Re<=j:wt&&Vt(ut.scheduledTime)<Vt(Me))&&!(Ce&&Ee)&&wt){let Ct=[K.matchUpId,ut.matchUpId].sort(du).join("|");b.scheduleConflicts[Ct]={priorScheduledMatchUpId:K.matchUpId,matchUpIdWithConflict:ut.matchUpId}}}}let k=b.participant.participantId;Object.keys(b.scheduleConflicts).length&&y.push(k),a[k].scheduleConflicts=b.scheduleConflicts}}}return{participantIdsWithConflicts:y,eventsPublishStatuses:M,derivedEventInfo:P,derivedDrawInfo:N,mappedMatchUps:E,participantMap:a,matchUps:U}}function lu({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=Hs(l)&&e?.events?.filter(A=>l?.includes(A.eventId))||e?.events||[],I=o&&CF({drawEntryStatuses:o,tournamentEvents:g}),h=s&&RF({eventEntryStatuses:s,tournamentEvents:g}),S=i!==void 0&&[!0,!1].includes(i)&&g.reduce((A,D)=>A.concat(...(D.drawDefinitions||[]).map(y=>JI({drawDefinition:y}).allPositionedParticipantIds).filter(Boolean)),[]),T=A=>n?.reduce((D,y)=>{let{accessor:E,value:U}=y,{values:M}=Zi({element:A,accessor:E});return D&&M?.includes(U)},!0);if(r=r?.filter(A=>{let D=Gn({element:A,itemType:ic})?.timeItem?.itemValue,{participantRoleResponsibilities:y,participantType:E,participantRole:U,participantId:M,person:P}=A,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&&E&&Hs(u)&&u.includes(E)||a&&U&&Hs(a)&&a.includes(U)||c&&Hs(y)&&Hs(c)&&c.find(C=>y?.includes(C))||n?.length&&Hs(n)&&T(A):(!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||E&&Hs(u)&&u.includes(E))&&(!a||U&&Hs(a)&&a.includes(U))&&(!c||Hs(y)&&Hs(c)&&c.find(C=>y?.includes(C)))&&(!n?.length||Hs(n)&&T(A))}),g.length&&l){let A=g.filter(D=>l.includes(D.eventId)).map(D=>{let y=(D.entries||[]).map(U=>U.participantId);if(ie(ao)(D.eventType))return y;let E=(e?.participants??[]).filter(U=>y.includes(U.participantId)).map(U=>U.individualParticipantIds).flat(1);return y.concat(...E)}).flat(1);r=r?.filter(D=>A.includes(D.participantId))}return r}function Hs(t){return t&&Array.isArray(t)&&t.length}function CF({drawEntryStatuses:t,tournamentEvents:e}){let r=({entryStatus:n})=>Array.isArray(t)?t.includes(n):!0;return pt(e.reduce((n,o)=>{let{flightProfile:i}=Ht({event:o}),s=i?.flights?.map(({drawEntries:c})=>Array.isArray(c)?c.filter(r).map(gt):[]).flat()||[],a=o.drawDefinitions?.map(({entries:c})=>c?c.filter(r).map(gt):[])||[];return n.concat(...s,...a)},[]))}function RF({eventEntryStatuses:t,tournamentEvents:e}){return pt(e.reduce((r,n)=>{let o=(n.entries||[]).filter(({entryStatus:i})=>Array.isArray(t)?t.includes(i):!0).map(gt);return r.concat(...o)},[]))}function Yt(t){let{withIndividualParticipants:e,participantFilters:r={},withPotentialMatchUps:n,withRankingProfile:o,convertExtensions:i,policyDefinitions:s,withScheduleItems:a,tournamentRecord:c,scheduleAnalysis:u,withSignInStatus:p,withTeamMatchUps:m,withScaleValues:d,usePublishState:l,contextProfile:f,withStatistics:g,withOpponents:I,withMatchUps:h,internalUse:S,withSeeding:T,withEvents:A,withDraws:D,withISO2:y,withIOC:E}=t;if(!c)return{error:W};(h||o)&&Vr({tournamentRecord:c});let{participantMap:U}=Mh({convertExtensions:i,tournamentRecord:c,withSignInStatus:p,withScaleValues:d,internalUse:S,withISO2:y,withIOC:E}),M=Ub({withMatchUps:h??o,withEvents:A??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:U,withOpponents:I,contextProfile:f,withSeeding:T}),{participantIdsWithConflicts:P,eventsPublishStatuses:N,derivedEventInfo:C,derivedDrawInfo:O,mappedMatchUps:b}=M,x=M.matchUps;U=M.participantMap;let w=u??n,F=({potentialMatchUps:Y,scheduleConflicts:$,scheduleItems:k,participant:K,statistics:z,opponents:q,matchUps:nt,events:Q,draws:it})=>{let ot=Object.values(it),ut=Object.values(q);return I&&ot?.forEach(Qt=>{Qt.opponents=ut.filter(yt=>yt.drawId===Qt.drawId)}),rt({...K,scheduleConflicts:u?Object.values($):void 0,draws:D||o?ot:void 0,events:A||o?Object.values(Q):void 0,matchUps:h||o?Object.values(nt):void 0,opponents:I?ut:void 0,potentialMatchUps:w?Object.values(Y):void 0,statistics:g?Object.values(z):void 0,scheduleItems:a?k:void 0},!1,!1,!0)},L=new Map;for(let Y of Object.keys(U))L.set(Y,F(U[Y]));let v=[...L.values()],H=s?.[Os]?.participant,j=lu({participants:v,participantFilters:r,tournamentRecord:c});if(e){let Y=Rt(e)?e:void 0;for(let $ of j)for(let k of $.individualParticipantIds??[]){$.individualParticipants||($.individualParticipants=[]);let K=L.get(k);$.individualParticipants.push(Y?bi({template:Y,source:K}):K)}}let V=H?j.map(Y=>bi({source:Y,template:H})):j;return{participantIdsWithConflicts:P,eventsPublishStatuses:N,derivedEventInfo:C,derivedDrawInfo:O,mappedMatchUps:b,participantMap:U,participants:V,...R,matchUps:x}}function lc({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 cs(t){let{provisionalPositioning:e,drawDefinition:r,stageSequence:n,structureId:o,stage:i}=t;if(!r)return{error:X};let{entryProfile:s}=ou({drawDefinition:r}),a=i&&n&&s?.[i]?.stageSequence?.[n]?.qualifiersCount||i&&s?.[i]?.qualifiersCount||0,c={};if(!o)return{qualifiersCount:a,roundQualifiersCounts:c};let{structure:u}=st({drawDefinition:r,structureId:o}),p=r.links?.filter(l=>l?.target?.structureId===u?.structureId),m=0;if(p?.length)for(let l of p){let f=st({structureId:l.source.structureId,drawDefinition:r})?.structure;if(f?.stage===at){let g=l.source.roundNumber,I=l.target.roundNumber,h=0;if(f.structureType===Le){let S=f.structures?.length??0,T=l.source.finishingPositions?.length??0;h=S*T}else h=At({matchUpFilters:{roundNumbers:[g]},structure:f,afterRecoveryTimes:!1,provisionalPositioning:e,inContext:!1}).matchUps?.length||0;c[I]||(c[I]=0),c[I]+=h,m+=h}}let d=Object.keys(c);if(d.length<=1){let l=d[0]||1;c[l]=Math.max(c[l]||0,a)}return m=Math.max(m,a),{qualifiersCount:m,roundQualifiersCounts:c}}function Ip({stage:t,drawDefinition:e}){let{entryProfile:r}=ou({drawDefinition:e});return r?.[t]?.drawSize||0}function Pb(t){let{provisionalPositioning:e,drawDefinition:r,stageSequence:n,stage:o}=t,i=Ip({stage:o,drawDefinition:r}),{qualifiersCount:s}=cs({provisionalPositioning:e,drawDefinition:r,stageSequence:n,stage:o});return i&&i-s}function mU({stage:t,drawDefinition:e}){return!!(t===Be||Cf({stage:t,drawDefinition:e})&&Ip({stage:t,drawDefinition:e}))}function dU({entryStatus:t=Zr,drawDefinition:e,stageSequence:r,stage:n}){if(t===wr)return NR({stage:n,drawDefinition:e})?{positionsAvailable:1/0,...R}:{error:Ly};let o=Pb({drawDefinition:e,stageSequence:r,stage:n}),i=MR({drawDefinition:e,stage:n}),s=nh({entryStatus:iu,drawDefinition:e,stage:n}),a=nh({entryStatus:Zr,drawDefinition:e,stage:n}),c=s+a,u=c>=o,p=o-c;return n!==Be&&u?{error:SI}:t===iu?s<i?{...R}:{error:SI}:{positionsAvailable:p,...R}}function _h(t){let{entryStatus:e=Zr,entryStageSequence:r,entryStage:n=tt,ignoreStageSpace:o,drawDefinition:i,entryPosition:s,participant:a,roundTarget:c,extensions:u,extension:p,drawType:m}=t,d="addDrawEntry";if(!i)return{error:X};if(!n)return{error:mI};if(m!==an&&!mU({stage:n,drawDefinition:i}))return _({result:{error:Di},stack:d});let l=dU({stageSequence:r,stage:n,drawDefinition:i,entryStatus:e});if(!o&&!l.success&&(!m||m!==an))return{error:l.error};if(p&&!Pn({extension:p}))return _({result:{error:G},info:"Invalid extension",context:{extension:p},stack:d});let f=t.participantId||a?.participantId;if(!f)return _({result:{error:oe},stack:d});let g=e===ts&&lc({participantId:f,drawDefinition:i,entryStatus:e}),I=n===Be&&lc({participantId:f,drawDefinition:i,entryStage:n}),h=e!==ts&&n!==Be&&lc({drawDefinition:i,participantId:f});if(h||g||I)return _({context:{invalidEntry:h,invalidLuckyLoser:g,invalidVoluntaryConsolation:I},result:{error:Wu},stack:d});let S=rt({entryStageSequence:r,participantId:f,entryPosition:s,entryStatus:e,entryStage:n,extensions:u});return p&&St({element:S,extension:p}),c&&St({extension:{name:"roundEntry",value:c},element:S}),i.entries||(i.entries=[]),i.entries.push(S),bt({drawDefinition:i}),{...R}}function Db(t){let e="addDrawEntries",{entryStatus:r=Zr,stage:n=tt,autoEntryPositions:o=!0,ignoreStageSpace:i,drawDefinition:s,participantIds:a,stageSequence:c,roundTarget:u,extension:p}=t;if(!n)return{error:mI};if(!s)return{error:X};if(!Array.isArray(a))return{error:zr};if(!mU({stage:n,drawDefinition:s}))return{error:Di};if(p&&!Pn({extension:p}))return _({result:{error:G},info:"Invalid extension",context:{extension:p},stack:e});let m=dU({drawDefinition:s,stageSequence:c,entryStatus:r,stage:n});if(!i&&!m.success)return{error:m.error};let d=m.positionsAvailable??0;if(!i&&n!==Be&&d<a.length)return{error:Nl};let l=a.reduce((f,g)=>{let I=r===ts&&lc({participantId:g,drawDefinition:s,entryStatus:r}),h=n===Be&&lc({entryStage:n,drawDefinition:s,participantId:g});return r!==ts&&n!==Be&&lc({drawDefinition:s,participantId:g})||I||h?f.concat(g):f},[]);return a.filter(f=>f&&!l.includes(f)).forEach(f=>{let g={entryStageSequence:c,entryStage:n,participantId:f,entryStatus:r};p&&St({element:g,extension:p}),u&&St({extension:{name:mn,value:u},element:g}),s.entries||(s.entries=[]),s.entries.push(g)}),o&&(s.entries=Vn({entries:s.entries})),bt({drawDefinition:s}),l?.length?{info:"some participantIds could not be added",participantIdsNotAdded:l,...R}:{...R}}function Vf({autoEntryPositions:t=!0,entryStageSequence:e,ignoreStageSpace:r,drawDefinition:n,participantIds:o,entryStatus:i,roundTarget:s,entryStage:a,extension:c,drawId:u,event:p}){if(!o?.length)return{error:lo};if(!p)return{error:mr};if(!u)return{error:Wr};let m=(p.entries||[]).map(gt);if(o.filter(g=>!m.includes(g)).length)return{error:gy};if(n){let g=Db({stageSequence:e,autoEntryPositions:t,stage:a,ignoreStageSpace:r,drawDefinition:n,participantIds:o,entryStatus:i,roundTarget:s,extension:c});if(g.error)return g}let{flightProfile:l}=Ht({event:p}),f=l?.flights.find(g=>g.drawId===u);return f?.drawEntries&&(o.forEach(g=>{let I=i===ts&&lU({participantId:g,entryStatus:i,flight:f}),h=a===Be&&lU({participantId:g,entryStage:a,flight:f});!(i!==ts&&a!==Be&&lU({flight:f,participantId:g}))&&!I&&!h&&f.drawEntries.push({participantId:g,entryStatus:i,entryStage:a})}),t&&(f.drawEntries=Vn({entries:f.drawEntries}))),{...R}}function lU({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 fc({autoEntryPositions:t=!0,participantIds:e=[],entryStatuses:r,stage:n,event:o}){let i="removeEventEntries";if(!o?.eventId)return{error:Et};if(!Array.isArray(e)||e.some(m=>!$e(m)))return _({result:{error:pn},stack:i});let s=(o.drawDefinitions??[]).flatMap(m=>Si({drawDefinition:m}).assignedParticipantIds??[]),a=(r?.length&&o.entries?.filter(m=>m.entryStatus&&r.includes(m.entryStatus))||[]).map(gt).filter(m=>!s.includes(m)),c=(n&&o.entries?.filter(m=>m.entryStage&&m.entryStage===n)||[]).map(gt).filter(m=>!s.includes(m));if(e.length?e=e.filter(m=>(!r?.length||a.includes(m))&&(!n||c.includes(m))):a.length&&c.length?e=jt(a,c):a.length?e=a:c.length&&(e=c),e?.length&&s.some(m=>e.includes(m)))return _({result:{error:Ps},stack:i});if(!e?.length)return{...R,participantIdsRemoved:[]};let u=[];o.entries=(o.entries??[]).filter(m=>{let d=!e.includes(m?.participantId);return d||u.push(m.participantId),d}),t&&(o.entries=Vn({entries:o.entries}));let{flightProfile:p}=Ht({event:o});return p?.flights?.forEach(m=>{m.drawEntries=(m.drawEntries||[]).filter(d=>!e.includes(d.participantId))}),o.drawDefinitions?.forEach(m=>{m.entries=(m.entries??[]).filter(d=>!e.includes(d.participantId))}),{...R,participantIdsRemoved:u}}var fU={[ze]:{policyName:"matchUpActionsDefault",enabledStructures:[{stages:[],stageSequences:[],enabledActions:[],disabledActions:[]}],participants:{enforceCategory:!0,enforceGender:!0},processCodes:{substitution:["RANKING.IGNORE","RATING.IGNORE"]},substituteAfterCompleted:!1,substituteWithoutScore:!1}},us=fU;function Kn(t){let{entryStatus:e=Zr,autoEntryPositions:r=!0,enforceGender:n=!0,participantIds:o=[],entryStageSequence:i,policyDefinitions:s,entryStage:a=tt,tournamentRecord:c,ignoreStageSpace:u,drawDefinition:p,roundTarget:m,extensions:d,extension:l,drawId:f,event:g}=t,I="addEventEntries";if(!g)return{error:Et};if(!o?.length)return _({result:{error:lo},stack:I});if(!g?.eventId)return{error:mr};let h=Pt({tournamentRecord:c,event:g}).appliedPolicies??{},S=s?.[ze]??h?.[ze]??us[ze],T=(n??S?.participants?.enforceGender)!==!1,A=[],D=[];if(d&&(!Array.isArray(d)||!d.every(b=>Pn({extension:b})))||l&&!Pn({extension:l}))return _({context:rt({extension:l,extensions:d}),result:{error:G},info:"Invalid extension(s)",stack:I});let y=!!c,E=[],U,M=c?.participants?.filter(b=>{if(!o.includes(b.participantId))return!1;let x=ie(Xt)(g.eventType)&&b.participantType===ht&&!Bs(e),w=g.eventType===Gt&&b.participantType===dt;return x&&(!g.gender||!T||[_r,Fn].includes(g.gender)||g.gender===b.person?.sex)||w&&!Bs(e)||g.eventType===Gt&&b.participantType===ht&&Bs(e)?!0:x&&g.gender&&T&&![_r,Fn].includes(g.gender)&&g.gender!==b.person?.sex?(E.push({participantId:b.participantId,sex:b.person?.sex}),!1):g.eventType===kt&&(b.participantType===kt||Bs(e)&&b.participantType===ht)}).map(b=>b.participantId)??[],P=o.filter(b=>!y||M.includes(b));g.entries||(g.entries=[]);let N=g.entries.map(b=>b.participantId||b.participant?.participantId);if(P.forEach(b=>{if(!N.includes(b)){let x=rt({participantId:b,entryStatus:e,entryStage:a,extensions:d});l&&St({element:x,extension:l}),m&&St({extension:{name:mn,value:m},element:x}),i&&(x.entryStageSequence=i),A.push(x.participantId),g.entries?.push(x)}}),f&&!Bs(a)){let b=Vf({participantIds:P,autoEntryPositions:r,entryStageSequence:i,ignoreStageSpace:u,drawDefinition:p,entryStatus:e,roundTarget:m,entryStage:a,extension:l,drawId:f,event:g});b.error&&(U=b.error)}if(g.eventType&&[gi,kr].includes(g.eventType)){let b=(g.entries||[]).map(v=>v.participantId),x=(g.entries||[]).filter(v=>Bs(v.entryStatus)).map(v=>v.participantId),F=(c?.participants??[]).filter(v=>b.includes(v.participantId)&&v.participantType&&[dt,kt].includes(v.participantType)).map(v=>v.individualParticipantIds).flat(1/0),L=x.filter(v=>F.includes(v));L.length&&(D.push(...L),fc({participantIds:L,autoEntryPositions:!1,event:g}))}if(P.length!==o.length)return _({context:{mismatchedGender:E,gender:g.gender},result:{error:zr},stack:I});r&&(g.entries=Vn({entries:g.entries||[]}));let O=A.length-D.length;return _({result:{...R,addedEntriesCount:O},stack:I,info:U})}var gU="ADMINISTRATION",bF="CAPTAIN",OF="COACH",Ge="COMPETITOR",IU="MEDIA",hU="MEDICAL",Bf="OFFICIAL",SU="OTHER",TU="SECURITY",Xm={ADMINISTRATION:gU,CAPTAIN:bF,COACH:OF,COMPETITOR:Ge,MEDIA:IU,MEDICAL:hU,OFFICIAL:Bf,OTHER:SU,SECURITY:TU};function Hf({addIndividualParticipantsToEvents:t,individualParticipantIds:e,groupingParticipantId:r,tournamentRecord:n,suppressErrors:o}){let i="removeIndividualParticipantIds";if(!n)return _({result:{error:W},stack:i});if(!r||!e)return _({result:{error:et},stack:i});let a=(n.participants??[]).find(m=>m.participantId===r);if(!a)return _({result:{error:Zt},stack:i});if(![kt,Ar].includes(a.participantType))return _({result:{participantType:a.participantType,error:nn},stack:i});let c=Nb({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));Kn({participantIds:l,entryStatus:Lr,tournamentRecord:n,event:m})}}return u&&Tt({topic:Qe,payload:{tournamentId:n.tournamentId,participants:[a]}}),{...R,...c}}function Nb({individualParticipantIds:t=[],groupingParticipant:e,tournamentRecord:r,suppressErrors:n,mappedMatchUps:o,participants:i}){let s=[];if(!e)return{removed:s};let a=[],c=[];i||({participants:i,mappedMatchUps:o}=Yt({withMatchUps:!0,tournamentRecord:r,withEvents:!0}));let p=i?.find(({participantId:l})=>l===e.participantId)?.events?.map(({eventId:l})=>l),m=(e.individualParticipantIds??[]).filter(l=>{let f=t?.includes(l),g=f&&i?.find(h=>h.participantId===l)?.matchUps.filter(({eventId:h})=>p.includes(h)).map(({matchUpId:h})=>o?.[h]).filter(({winningSide:h,score:S})=>h||Ie({score:S})),I=f&&!g?.length;if(f&&!I&&c.push(l),I){s.push(l);for(let h of r.events??[])for(let S of h.drawDefinitions??[]){let{extension:T}=mt({element:S,name:ho}),A=T?.value[e.participantId];T&&A&&(T.value[e.participantId]=A.filter(y=>y.participantId!==l),St({element:S,extension:T}),ga({drawDefinition:S}));let D=rr({drawDefinition:S,inContext:!1}).matchUps??[];for(let y of D){let E=y.sides??[];for(let U of E){let M=U.lineUp??[];M.find(N=>N.participantId===l)&&(U.lineUp=M.filter(N=>N.participantId!==l),It({tournamentId:r?.tournamentId,drawDefinition:S,matchUp:y}))}}}}else a.push(l);return!I});e.individualParticipantIds=m;let d={groupingParticipantId:e.participantId,cannotRemove:c,notRemoved:a,removed:s};return c.length&&!n&&{...d,cannotRemove:c,error:Hu}||d}function hp({participantRole:t=Ge,individualParticipantIds:e=[],groupingTypes:r=[Jr,Ar],tournamentRecord:n}){if(!n)return{error:W};let o=n.participants??[],{participants:i,mappedMatchUps:s}=Yt({withMatchUps:!0,tournamentRecord:n,withEvents:!0}),a=0;return o.filter(c=>(c.participantRole===t||!c.participantRole)&&c.participantType&&r.includes(c.participantType)).forEach(c=>{let{removed:u}=Nb({groupingParticipant:c,individualParticipantIds:e,tournamentRecord:n,mappedMatchUps:s,participants:i});u&&a++}),a?R:{error:_y}}function Li(t){if(!t?.tournamentRecord)return{error:W};if(!t?.participantIds?.length)return{error:lo};let{addIndividualParticipantsToEvents:e,tournamentRecord:r,participantIds:n}=t,o=r.participants?.length||0;if(!o)return{...R};let i=(r.events||[])?.filter(({eventType:l})=>l===Fe).map(l=>l?.drawDefinitions?.map(({drawId:f})=>f)).flat(1/0),s=Yt({participantFilters:{participantIds:n},tournamentRecord:r,withDraws:!0}).participants??[],a=()=>{let f=(le({matchUpFilters:{drawIds:i,matchUpTypes:[Gt]},tournamentRecord:r}).matchUps??[]).map(({sides:g})=>g?.map(({participantId:I})=>I)).flat().filter(Boolean);return jt(f,n)},c=i?.length&&a(),u=s.filter(l=>l.draws?.filter(f=>(!i?.length||!i?.includes(f.drawId))&&f.positionAssignments).length);if(c?.length||u.length)return{error:Ps};let p={},m={};for(let l of r.events||[]){let f=fc({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===dt&&l.individualParticipantIds.some(g=>n.includes(g));if(!f&&l.participantType===Fe&&l.individualParticipantIds.some(g=>n.includes(g))&&(l.individualParticipantIds=l.individualParticipantIds.filter(g=>!n.includes(g))),f&&e&&[dt,kt].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(hp({individualParticipantIds:n,tournamentRecord:r}),e)for(let l of r.events||[]){let g=p[l.eventId].map(I=>m[I]||[]).flat();Kn({participantIds:g,entryStatus:Lr,tournamentRecord:r,event:l})}return d&&Tt({payload:{participantIds:n,tournamentId:r.tournamentId},topic:pf}),d?{...R,participantsRemovedCount:d}:{error:Hu}}function vh({selected:t=!0,drawDefinition:e,entryStatuses:r,drawId:n,event:o,stage:i}){let s=o.entries??[];if(n){let{flightProfile:c}=Ht({event:o}),u=c?.flights?.find(p=>p.drawId===n);u?s=u.drawEntries:e.entries&&(s=e?.entries)}let a=s.filter(c=>(!r?.length||!c.entryStatus||r.includes(c.entryStatus))&&(!i||!c.entryStage||c.entryStage===i)&&(!t||c.entryStatus&&Or.includes(c.entryStatus)));return{entries:s,stageEntries:a}}function AU({removeGroupParticipant:t,tournamentRecord:e,drawDefinition:r,participantId:n,drawId:o,stage:i,event:s}){let a="destroyGroupEntry";if(!e)return{error:W};if(!n)return _({result:{error:oe},stack:a});if(!s)return{error:Et};if(!s.eventType||![gi,kr].includes(s.eventType))return _({result:{error:No},stack:a});let c=e.participants??[],u=c.find(S=>S.participantId===n);if(!u)return _({result:{error:Zt},stack:a});if(!u.participantType||![dt,Jr].includes(u.participantType)||u.participantType===Jr&&s.eventType!==kr||u.participantType===dt&&s.eventType!==gi)return{error:nn};let m=(s.entries??[]).find(S=>S.participantId===n);if(!m)return{error:hI};let{stageEntries:d}=vh({selected:!1,drawDefinition:r,drawId:o,event:s,stage:i}),l=d.map(gt),f=c.filter(({participantId:S})=>l.includes(S)).map(({individualParticipantIds:S})=>S).flat().filter(Boolean),g=u.individualParticipantIds?.filter(S=>Zn(S,f).length===1),I=fc({participantIds:[n],event:s});if(I.error||g?.length&&(I=Kn({participantIds:g,entryStatus:Lr,entryStage:m.entryStage,tournamentRecord:e,drawDefinition:r,drawId:o,event:s}),I.error))return I;let h;return t&&Li({participantIds:[n],tournamentRecord:e}).success&&(h=!0),{...R,participantRemoved:h}}function Wf({removeGroupParticipant:t,tournamentRecord:e,drawDefinition:r,participantId:n,drawId:o,event:i}){return AU({removeGroupParticipant:t,tournamentRecord:e,drawDefinition:r,participantId:n,drawId:o,event:i})}function yU(t){if(!t.tournamentRecord)return{error:W};let{participantIds:e,...r}=t,n=0,o=[];for(let i of e){let s=AU({participantId:i,...r});s.success&&(n+=1),s.error&&o.push(s.error)}return n?{destroyedCount:n,...R}:{error:o}}function fu(t){let{tournamentRecord:e,replaceWithBye:r,drawDefinition:n,destroyPair:o,entryStatus:i,matchUpsMap:s,drawId:a}=t,c="removeDrawPositionAssignment",u=dc(t);if(u.error)return _({result:u,stack:c});let{participantId:p}=u,{drawPosition:m,event:d,structureId:l}=t;if([wr,Ao].includes(i)&&p){let{tournamentRecord:I}=t,{participant:h}=xo({tournamentRecord:I,participantId:p}),{participantType:S,individualParticipantIds:T}=h??{};if(o&&S===dt){let A=Wf({tournamentRecord:I,drawDefinition:n,participantId:p,event:d});if(A.error)return _({result:A,stack:c});T&&zm({participantIds:T,tournamentRecord:I,drawDefinition:n,entryStatus:i,drawId:a,event:d})}else zm({participantIds:[p],tournamentRecord:I,drawDefinition:n,entryStatus:i,drawId:a,event:d})}if(r){let I=Dr({tournamentRecord:e,drawDefinition:n,drawPosition:m,structureId:l,matchUpsMap:s,event:d});if(I.error)return _({result:I,stack:c})}let{structure:f}=st({drawDefinition:n,structureId:l});return vm({structure:f,drawPositions:[m]}),tu({drawDefinition:n,positionAction:{name:"removeDrawPositionAssignment",replaceWithBye:r,drawPosition:m,entryStatus:i,structureId:l}}),u}function EU(t){return Object.assign(t,{entryStatus:Ao}),fu(t)}function xh(t){return $e(t)?t.split(" ").map(e=>e.split("").map((r,n)=>n?r.toLowerCase():r.toUpperCase()).join("")).join(" "):t}function Ye(t){return $e(t)?xh(t.replace(/_/g," ")):""}var ps=({finishingPosition:t=_i,qualifyingRoundNumber:e,structureAbbreviation:r,seedAssignments:n=[],stageSequence:o=1,structureOrder:i,seedingProfile:s,matchUpFormat:a,structureType:c,structureName:u,matchUpType:p,matchUps:m=[],structureId:d,roundOffset:l,roundLimit:f,stageOrder:g,structures:I,stage:h})=>{let S={structureId:d??Mt(),structureAbbreviation:r,finishingPosition:t,seedAssignments:n,matchUpFormat:a,stageSequence:o,structureName:u};i&&(S.structureOrder=i),c&&(S.structureType=c),s&&(typeof s=="string"?S.seedingProfile=s:typeof s=="object"&&typeof s.positioning=="string"&&(S.seedingProfile=s.positioning)),p&&(S.matchUpType=p),l&&(S.roundOffset=l),g&&(S.stageOrder=g),f&&(S.roundLimit=f),h&&(S.stage=h),e&&(S.qualifyingRoundNumber=e);let T=m.flatMap(({drawPositions:A})=>A).filter(Boolean);return I?S.structures=I:(S.matchUps=m,S.positionAssignments=pt(T).sort((A,D)=>A-D).map(A=>({drawPosition:A}))),S},en=ps;function jf({structureName:t=Ye(Be),structureAbbreviation:e,drawDefinition:r,matchUpType:n,structureId:o}){if(!r)return{error:X};let i=en({stage:Be,structureAbbreviation:e,structureName:t,matchUps:[],structureId:o,matchUpType:n});return r.structures||(r.structures=[]),r.structures.push(i),bt({drawDefinition:r,structureIds:[i.structureId]}),{...R}}function Yf({drawPositions:t}){if(!t?.length)return{error:Wa};let e=o=>t.filter(i=>i!==o).map(i=>[o,i]),r=[].concat(...(t??[]).map(e)),n=pt(r.map(qf)).map(o=>o.split("|").map(i=>+i));return{groupMatchUps:r,uniqueMatchUpGroupings:n}}function qf(t=[]){return!Array.isArray(t)||!t.length?"":[...t].sort(se).join("|")}function UU({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 qf(l)}))}function _F({rounds:t,hash:e}){return t?.length?t?.reduce((r,n,o)=>n.includes(e)?o+1:r,void 0):{error:et}}var Mb={getRoundRobinGroupMatchUps:Yf,determineRoundNumber:_F,drawPositionsHash:qf,groupRounds:UU};function Da(t){let{groupNameBase:e="Group",playoffAttributes:r,stageSequence:n=1,structureOptions:o,appliedPolicies:i,seedingProfile:s,stage:a=tt,matchUpType:c,roundTarget:u,structureId:p,groupNames:m,drawSize:d,idPrefix:l,isMock:f,uuids:g}=t,I=t.structureName??r?.["0"]?.name??Ye(tt),{groupCount:h,groupSize:S}=vF({structureOptions:o,appliedPolicies:i,drawSize:d}),T=vs,A,D=Z(1,h+1).map(E=>{let U=xF({groupSize:S,structureOrder:E,matchUpType:c,drawSize:d,idPrefix:l,isMock:f});A=Array.isArray(U)?Math.max(...U.map(({roundNumber:P})=>P??0)):0;let M=m?.[E-1]??`${e} ${E}`;return ps({structureId:g?.pop(),structureType:op,finishingPosition:T,structureOrder:E,structureName:M,matchUps:U})}),y=ps({structureId:p??g?.pop(),structureType:Le,finishingPosition:T,seedingProfile:s,structureName:I,stageSequence:n,structures:D,stage:a});return u&&St({extension:{name:mn,value:u},element:y}),{structures:[y],maxRoundNumber:A,groupCount:h,links:[],groupSize:S,...R}}function vF({appliedPolicies:t,structureOptions:e,drawSize:r}){let n=e?.groupSize,o=e?.groupSizeLimit||8,{validGroupSizes:i}=Sp({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 Sp({drawSize:t,groupSizeLimit:e=10}){let r=Z(3,e+1).filter(n=>{let o=Math.ceil(t/n),i=o*n-t,s=Math.ceil(t/o),a=Math.ceil(i/o);return(!i||i<n)&&s===n&&s>=3&&a<2});return{...R,validGroupSizes:r}}function xF({structureOrder:t,matchUpType:e,groupSize:r,drawSize:n,idPrefix:o,isMock:i,uuids:s}){let a=(t-1)*r,c=Z(1+a,r+1+a),u=Yf({drawPositions:c}).uniqueMatchUpGroupings??[],p=UU({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=qf(f),I=d(g),h=[1,n],S=wF({structureOrder:t,drawPositions:f,roundNumber:I,idPrefix:o,uuids:s}),T={matchUpStatus:I?zt:Dt,matchUpType:e,finishingPositionRange:{winner:h,loser:h},drawPositions:f,roundNumber:I,matchUpId:S};return i&&(T.isMock=!0),T}}function wF({structureOrder:t,drawPositions:e,roundNumber:r,idPrefix:n,uuids:o}){return n?`${n}-${t}-${r}-DP-${e.join("-")}`:o?.pop()||Mt()}function $f(t){let{roundRobinGroupsCount:e,participantsCount:r,cluster:n}=t;if(!ft(r))return{seedBlocks:void 0,..._({result:{error:G},context:{participantsCount:r},stack:"getSeedBlocks"})};let o=qi(r);if(e){let l=Math.min(e,o),f=[],g=1;for(Z(0,l).forEach(()=>{f.push([g]),g++});g<o;){let I=Z(g,g+l);g+=l,f.push(I)}return{...R,seedBlocks:f}}let i=Z(1,o+1),s=[],a=o/2;for(;a>1;){let l=Te(i,a),f=l.length;l.forEach((g,I)=>{let h,S=I<f/2,T=I%2===0,A=g[0],D=g[g.length-1];n&&f>4?f===8?h=S?D:A:h=T?A:D:h=S?A: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=Z(0,20).map(l=>Math.pow(2,l));u.unshift(1);let p=u.indexOf(o),m=0,d=[];return Z(0,p).forEach(l=>{d.push(s.slice(m,m+u[l])),m+=u[l]}),{...R,seedBlocks:d}}function Kf({roundRobinGroupsCount:t,drawSize:e}){let r="getSeedGroups";if(!ft(e))return{seedGroups:void 0,..._({result:{error:G},context:{drawSize:e},stack:r})};if(t){if(!ft(t))return{seedGroups:void 0,..._({context:{roundRobinGroupsCount:t},result:{error:G},stack:r})};let n=1,o=Math.floor(e/t);return{seedGroups:Z(0,o).map(()=>{let s=Z(n,n+t);return n+=t,s})}}else{let{seedBlocks:n}=$f({participantsCount:e,roundRobinGroupsCount:t}),o=0;return{seedGroups:(n||[]).map(s=>(s||[]).map(()=>(o+=1,o)))}}}function wh({roundRobinGroupsCount:t,participantsCount:e}){if(t){let{validGroupSizes:o}=Sp({drawSize:e});if(!o?.map(a=>Math.ceil(e/a))?.includes(t))return _({context:{roundRobinGroupsCount:t},result:{error:G}})}let{seedGroups:r}=Kf({drawSize:e,roundRobinGroupsCount:t}),n=r?.map(o=>Math.min(...o))||[];return{...R,seedingThresholds:n}}function gc(t){if(!t)return 1/0;if(ft(t))return ct(t);let e=t.split("-")[0];return ft(e)?ct(e):1/0}function LF({size:t}){let e=[t],r=t;for(;r/2===Math.floor(r/2);)r=r/2,e.push(r);return e.includes(1)||e.push(1),e.sort(se),e.reverse(),e}function Cb({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 Rb({positioning:t,size:e}){let r=LF({size:e}),n=[],o=[],i=d=>d[0],s=d=>d[d.length-1],a=(d,l)=>(t&&[zc,si].includes(t)&&l%2?s(d):i(d))||i(d),c=(d,l)=>{if(d.every(f=>!o.includes(f))){let f=a(d,l);return o.push(f),f}},u=d=>{let l=d.filter(f=>!o.includes(f));if(l.length)return o.push(...l),l},p=(d,l)=>{let f=a(d,l);if(!o.includes(f))return o.push(f),f},m=Z(1,e+1);for(let d of r)if(d===1){let l=Te(m,2),f=l.map(c).filter(Boolean);f.length&&n.push(f);let g=l.flatMap(u).filter(Boolean);g.length&&n.push(g)}else{let f=Te(m,d).map(p).filter(Boolean);f.length&&n.push(f)}return{divisions:r,divisionGroupings:n}}function ms({provisionalPositioning:t,returnAllProxies:e,appliedPolicies:r,seedingProfile:n,drawDefinition:o,allPositions:i,structure:s}){let a=[];if(!s)return{error:Do};let{matchUps:c,roundMatchUps:u}=At({matchUpFilters:{roundNumbers:[1]},provisionalPositioning:t,structure:s}),{seedAssignments:p}=Fr({provisionalPositioning:t,returnAllProxies:e,drawDefinition:o,structure:s}),{positionAssignments:m}=de({structure:s}),d=m?.length,l=p?.length??0,f=[],I=Object.keys(u).map(L=>parseInt(L)).sort((L,v)=>L-v).map(L=>{let v=u[L].map(H=>H.drawPositions).flat(1/0).filter(Boolean),B=v.filter(H=>!f.includes(H));return f=f.concat(...v),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,A=I.filter(L=>L.filter(v=>v<=l).length),{stage:D,structureType:y,roundLimit:E}=s,U=y===Le,M=!U&&I?.length,P=!U&&D===at&&E,N=A.flat(1/0),C=M?N?.length:0,O=i?d:l,b=Ym({drawDefinition:o,structure:s,matchUps:c}),x=b?0:!M&&O||O&&N.length<O&&O-N.length||0;if(P){let L=s?.matchUps?s.matchUps.filter(({roundNumber:B})=>B===s.roundLimit).length:0,v=h.length/L;if(!M){let B=Ap(n),H=Te(h,v),j=1,V=Z(0,H[0].length).map(()=>{let Y=Z(j,j+H.length);return j+=H.length,Y});({validSeedBlocks:a}=bb({drawPositionBlocks:H,nonRandom:n?.nonRandom,positioning:B,seedGroups:V}))}}else U?{validSeedBlocks:a}=FF({nonRandom:n?.nonRandom,seedingProfile:n,structure:s}):M?a=A.map(L=>({seedNumbers:L,drawPositions:L})):b&&Te(h,2).map((v,B)=>({drawPositions:[v[0]],seedNumbers:[B+1]})).forEach(v=>a.push(v));if(!U&&!b&&!P){let{blocks:L}=GF({drawPositionOffset:S,seedNumberOffset:C,seedCountGoal:x,seedingProfile:n,baseDrawSize:T});L.forEach(v=>a.push(v))}let F=a.flatMap(L=>L.drawPositions).reduce((L,v)=>h?.includes(v)&&L,!0);return!b&&!M&&!U&&!F?{error:my,validSeedBlocks:[],isContainer:U,isFeedIn:M}:{isLuckyStructure:b,validSeedBlocks:a,isContainer:U,isFeedIn:M}}function FF({seedingProfile:t,structure:e,nonRandom:r}){let n=e.structures||[],o=n.length,i=Nt({structure:e})?.positionAssignments,s=Ap(t),a=i?.length??0,{seedGroups:c}=Kf({roundRobinGroupsCount:o,drawSize:a}),u=n.map(p=>Nt({structure:p}).positionAssignments?.map(m=>m.drawPosition));return bb({drawPositionBlocks:u,positioning:s,seedGroups:c,nonRandom:r})}function bb({drawPositionBlocks:t,positioning:e,seedGroups:r,nonRandom:n}){let o=[],{divisionGroupings:i}=Rb({size:r.length,positioning:e}),s=[];return r.forEach((a,c)=>{let u=Cb({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!==si?f=n?f:cr(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 GF(t){let{drawPositionOffset:e=0,roundRobinGroupsCount:r,seedNumberOffset:n=0,seedingProfile:o,seedCountGoal:i,baseDrawSize:s}=t,a=1,c=[],{seedBlocks:u}=$f({cluster:Ap(o)===zc,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 Tp({appliedPolicies:t,drawDefinition:e,seedBlockInfo:r,drawPosition:n,structureId:o,seedNumber:i}){let{structure:s}=st({drawDefinition:e,structureId:o});t||(t=Pt({drawDefinition:e}).appliedPolicies);let a=r?.validSeedBlocks;return!a&&s&&(a=ms({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 Lh(t){let{provisionalPositioning:e,drawDefinition:r,seedingProfile:n,seedBlockInfo:o,structureId:i,randomize:s}=t,{structure:a}=st({drawDefinition:r,structureId:i}),{seedAssignments:c}=Fr({returnAllProxies:t.returnAllProxies,provisionalPositioning:e,drawDefinition:r,structure:a}),{positionAssignments:u}=de({structure:a}),m=u?.filter(v=>v.participantId??v.bye??v.qualifier)?.map(v=>v.drawPosition).filter(Boolean),{appliedPolicies:d}=Pt({drawDefinition:r}),g=(o?.validSeedBlocks||a&&ms({returnAllProxies:t.returnAllProxies,provisionalPositioning:e,appliedPolicies:d,drawDefinition:r,seedingProfile:n,structure:a})?.validSeedBlocks||[]).filter(v=>v.drawPositions.filter(H=>!m?.includes(H)).length)[0],I=c?.map(v=>v.participantId).filter(Boolean),h=u?.map(v=>v.participantId).filter(Boolean),S=I?.filter(v=>h?.includes(v)),T=I?.filter(v=>!h?.includes(v)),A=c?.filter(v=>T?.includes(v.participantId)),D=c?.filter(v=>!v.participantId),E=(A?.length&&A.length>0?A.length:D?.length??0)&&g?.drawPositions.filter(v=>!m?.includes(v))||[],U=s?cr(E):E,M=[],P=U.map(()=>{let B=L(A,M)?.participantId;return B&&M.push(B),B}).filter(Boolean),N=c?.filter(v=>S?.includes(v.participantId)).map(v=>v.seedNumber),O=(g?.seedNumbers||[]).filter(v=>!N?.includes(v)),b=c?.filter(v=>O.includes(v.seedNumber)).map(v=>v.participantId),x=d?.seeding?.duplicateSeedNumbers;return{nextSeedBlock:g,unplacedSeedParticipantIds:(x!==void 0?x:!0)?P:b,unplacedSeedNumbers:O,unfilledPositions:U,unplacedSeedAssignments:A};function L(v,B){let H=v.filter($=>!B.includes($.participantId)),j=Math.min(...H.map($=>gc($.seedValue))),V=H.filter($=>gc($.seedValue)===j);return cr(V).pop()}}function Ap(t){if(typeof t=="string")return t;if(typeof t=="object")return t.positioning}function Ws({provisionalPositioning:t,tournamentRecord:e,drawDefinition:r,seedingProfile:n,participantId:o,seedBlockInfo:i,structureId:s,seedNumber:a,seedValue:c,eventId:u,event:p}){let m="assignSeed",{structure:d}=st({drawDefinition:r,structureId:s}),{positionAssignments:l}=de({structure:d}),f=Fr({provisionalPositioning:t,drawDefinition:r,structure:d}).seedAssignments,g=f.map(y=>y.seedNumber),I=lc({drawDefinition:r,participantId:o});if(o&&!I)return _({result:{error:pn},context:{participantId:o},stack:m});let h=p?Ht({event:p}).flightProfile?.flights?.length:0,S=h&&h>1,A=l?.find(y=>y.participantId===o)?.drawPosition;if(A&&!Tp({drawPosition:A,drawDefinition:r,seedBlockInfo:i,structureId:s,seedNumber:a}))return _({result:{error:ll},context:{assignedDrawPosition:A},info:"invalid seed position",stack:m});g.includes(a)||f.push({seedNumber:a,seedValue:c});let D;return f.forEach(y=>{y.participantId===o&&y.seedNumber!==a&&(y.participantId=void 0),y.seedNumber===a&&(y.participantId=o,!n?.groupSeedingThreshold&&!S&&(y.seedValue=c??a),D=!0)}),D?(rh({tournamentId:e?.tournamentId,drawDefinition:r,structure:d,eventId:u}),{...R}):_({result:{error:py},stack:m})}function Jm({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:ho}),p=u?.value||{},m=J(p[r],!1,!0);if(c)i?.sides?.forEach(d=>{d.sideNumber===a&&(d.lineUp=m)});else{i.sides=[1,2].map(l=>({...i.sides?.find(g=>g.sideNumber===l)??{},sideNumber:l}));let d=i.sides.find(l=>l.sideNumber===a);d&&(d.lineUp=m)}It({tournamentId:n?.tournamentId,context:"updateSidLineUp",eventId:s?.eventId,drawDefinition:o,matchUp:i})}function Fh(t){let{sourceMatchUp:e}=t,{targetMatchUp:r,structure:n,matchUpsMap:o,drawPosition:i}=t,s=r.roundNumber>1&&r.roundNumber-1,a=Yo({structureId:n.structureId,matchUpsMap:o});!e&&i&&(e=a.find(({drawPositions:f,roundNumber:g})=>g===s&&f?.includes(i)));let c=e?.roundPosition,u=c%2?1:-1,p=c+u,m=s&&a.find(({roundNumber:f,roundPosition:g})=>f===s&&g===p),d=m?.matchUpStatus,l=[ge,Ne].includes(d);return{pairedPreviousMatchUp:m,pairedPreviousMatchUpIsDoubleExit:l}}function Ob({drawPosition:t,drawPositions:e}){let r=!1,n=!!e?.includes(t);return{updatedDrawPositions:n?e||[]:[...e,void 0,void 0].slice(0,2).map(s=>!s&&!n?(n=!0,r=!0,t):s).sort(se).filter(Boolean),positionAdded:r,positionAssigned:n}}function Gh({structureId:t,matchUpsMap:e,matchUp:r}){let n=r?.roundPosition,o=n%2?1:-1,i=n+o;return{pairedPreviousMatchUp:Yo({matchUpsMap:e,structureId:t}).find(({roundNumber:c,roundPosition:u})=>c===r?.roundNumber&&u===i)}}function kh({inContextDrawMatchUps:t,sourceMatchUpStatus:e,sourceMatchUpId:r,matchUpsMap:n,matchUp:o}){let i=t.find(a=>a.matchUpId===r),{pairedPreviousMatchUp:s}=Gh({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=$e(p)||!isNaN(p)?{code:p}:p;return m.sideNumber===u?{...m,previousMatchUpStatus:e}:m})}}function Zm({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 Ic({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=Ae({drawDefinition:o})),t||(t=re({inContext:!0,drawDefinition:o,matchUpsMap:a}).matchUps??[]);let m=t.find(O=>O.matchUpId===c),d=m?.structureId,l=o?.structures?.find(O=>O.structureId===d);if(!l)return{error:Lt};let f=a?.drawMatchUps?.find(O=>O.matchUpId===c),g=f?.drawPositions??[],{positionAdded:I,positionAssigned:h,updatedDrawPositions:S}=Ob({drawPosition:s,drawPositions:g}),{positionAssignments:T}=Nt({drawDefinition:o,structure:l}),D=T?.filter(O=>S.includes(O.drawPosition))?.find(({bye:O})=>O),y=f?.matchUpStatus&&[_t,Ot].includes(f.matchUpStatus)&&S.filter(Boolean).length<2;if(i=D&&Dt||i||y&&f.matchUpStatus||f?.matchUpStatus&&[ge,Ne].includes(f.matchUpStatus)&&f.matchUpStatus||zt,f&&I){t=re({inContext:!0,drawDefinition:o,matchUpsMap:a}).matchUps??[];let O=y&&Zm({inContextDrawMatchUps:t,drawPosition:s,matchUpId:c})||void 0;f?.matchUpStatusCodes&&kh({inContextDrawMatchUps:t,sourceMatchUpStatus:e,sourceMatchUpId:n,matchUpsMap:a,matchUp:f}),Object.assign(f,{drawPositions:S,winningSide:O,matchUpStatus:i}),It({tournamentId:r?.tournamentId,eventId:m?.eventId,context:p,drawDefinition:o,matchUp:f})}let E=er({inContextDrawMatchUps:t,inContextMatchUp:m,drawDefinition:o,matchUpId:c}),{targetMatchUps:{winnerMatchUp:U,loserMatchUp:M,loserTargetDrawPosition:P},targetLinks:{loserTargetLink:N}}=E,C=Yo({structureId:l.structureId,matchUpsMap:a});if(h&&D){if(U)if([Dt,ge,Ne].includes(i)){let O=Ic({matchUpId:U.matchUpId,inContextDrawMatchUps:t,tournamentRecord:r,drawDefinition:o,drawPosition:s,matchUpsMap:a});if(O.error)return O}else{let{structureId:O}=U;O!==l.structureId&&console.log("winnerMatchUp in different structure... participant is in different targetDrawPosition")}}else if(U&&m&&!m.feedRound){let{pairedPreviousMatchUpIsDoubleExit:O}=Fh({targetMatchUp:f,drawPosition:s,matchUpsMap:a,structure:l});if(O){let b=Ic({matchUpId:U.matchUpId,inContextDrawMatchUps:t,tournamentRecord:r,drawDefinition:o,drawPosition:s,matchUpsMap:a});if(b.error)return b}}if(f?.matchUpType===Bt){let O=t?.find(({matchUpId:F})=>F===f.matchUpId),x=(O?.sides??[]).reduce((F,L,v)=>L.drawPosition===s?v:F,void 0),w=T?.find(F=>F.drawPosition===s)?.participantId;w&&x!==void 0&&Jm({inContextTargetMatchUp:O,drawPositionSideIndex:x,teamParticipantId:w,tournamentRecord:r,drawDefinition:o,matchUp:f})}if(N?.linkCondition===qn&&S.filter(Boolean).length===2&&!D&&C.filter(({drawPositions:x,roundNumber:w})=>w===1&&xe(x,S)).every(({matchUpStatus:x})=>[me,lr].includes(x))&&M){let{structureId:x}=M,w=Dr({drawPosition:P,tournamentRecord:r,drawDefinition:o,structureId:x,matchUpsMap:a,event:u});if(w.error)return w}return h?{...R}:_({result:{error:Ha},context:{drawPosition:s},stack:p})}function Vh({inContextDrawMatchUps:t,drawDefinition:e,assignments:r,matchUpsMap:n,structure:o}){let s=Ji({drawDefinition:e})?.containedStructures?.[o.structureId]?.map(({structureId:m})=>m)||[];s.push(o?.structureId);let a=r?.map(({drawPosition:m})=>m)||[],c=t?.filter(m=>s.includes(m.structureId)&&jt(m.drawPositions??[],a).length)??[],u=c.map(({matchUpId:m})=>m),p=n?.drawMatchUps?.filter(m=>u.includes(m.matchUpId))??[];return{drawPositions:a,matchUps:p,targetMatchUps:c}}function td({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}=gp({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 Nn(t){return`${t} must be an array`}function ed({lineUp:t,tieFormat:e}){let r=[];if(!Array.isArray(t))return r.push(Nn("lineUp")),{valid:!1,errors:r,error:G};let n=t.every(s=>{if(typeof s!="object")return r.push("lineUp entries must be objects"),!1;let{participantId:a,collectionAssignments:c}=s;return a?typeof a!="string"?(r.push("participantIds must be strings"),!1):Array.isArray(c)?c.every(u=>{if(typeof u!="object")return r.push("collectionAssignments must be objects"),!1;let{collectionPosition:p}=u;return typeof p!="number"?(r.push("collectionPosition must be a number"),!1):!0}):(r.push(Nn("collectionAssignments")),!1):(r.push("Missing participantId"),!1)}),o=pt(t.map(gt)).length===t.length;return o||r.push("Duplicated participantId(s)"),{valid:n&&o,errors:r,error:r.length?G:void 0}}function Fi({drawDefinition:t,participantId:e,tieFormat:r,lineUp:n}){if(typeof t!="object")return{error:X};if(typeof e!="string")return{error:oe};let o=ed({lineUp:n,tieFormat:r});if(!o.valid)return o;let{extension:i}=mt({element:t,name:ho}),s=i?.value||{};return s[e]=td({lineUp:n}),St({element:t,extension:{name:ho,value:s}}),ga({drawDefinition:t}),{...R}}function zf({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}=Vh({inContextDrawMatchUps:t,matchUpsMap:o,assignments:i,structure:s});for(let m of p)m.matchUpType===ln&&(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&&Fi({drawDefinition:n,participantId:I,lineUp:[],tieFormat:g})}It({tournamentId:r?.tournamentId,context:"resetLineUps",eventId:a?.eventId,drawDefinition:n,matchUp:f})}}});return{...R}}function Mn({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:oe},stack:l});p=p??Ae({drawDefinition:i}),e||({matchUps:e}=re({inContext:!0,drawDefinition:i,matchUpsMap:p}));let f=st({drawDefinition:i,structureId:m});if(f.error)return _({result:f,stack:l});let{structure:g}=f;if(!g)return{error:Lt};if(fr({structure:g}))return _({result:{error:Je},stack:l});let{seedAssignments:I}=Fr({provisionalPositioning:t,drawDefinition:i,structure:g}),S=I?.find(N=>N.participantId===a)?.seedNumber,{appliedPolicies:T}=Pt({tournamentRecord:o,drawDefinition:i,structure:g,event:d});if(S&&!Tp({seedNumber:S,appliedPolicies:T,drawDefinition:i,seedBlockInfo:c,drawPosition:u,structureId:m}))return _({result:{error:ll},context:{drawPosition:u},stack:l});let D=de({structure:g}).positionAssignments||[],y=D?.find(N=>N.drawPosition===u);if(!y)return _({result:{error:ys},context:{drawPosition:u},stack:l});if(D?.map(gt).includes(a))return _({result:{error:Ps},context:{drawPosition:u},stack:l});let{containsParticipant:U,containsBye:M}=P(y);if(M){let N=dc({inContextDrawMatchUps:e,tournamentRecord:o,drawDefinition:i,drawPosition:u,structureId:m,matchUpsMap:p,event:d});if(N.error)return _({result:N,stack:l})}if(U&&y.participantId!==a){let{activeDrawPositions:N}=Ua({drawDefinition:i,structureId:m});if(N.includes(u))return _({result:{error:ku},stack:l});zf({assignments:[y],inContextDrawMatchUps:e,tournamentRecord:o,drawDefinition:i,matchUpsMap:p,structure:g})}if(y.participantId=a,r&&(y.qualifier=!0),(g?.stageSequence||0)>1||g.stage&&[Ve,ce].includes(g.stage)){let N=g.stage===at?at:tt,b=(i.structures?.find(x=>x?.stage===N&&x?.stageSequence===1)?.seedAssignments??[]).find(x=>x.participantId===a);if(b?.participantId){let{participantId:x,seedNumber:w,seedValue:F}=b;Ws({eventId:d?.eventId,provisionalPositioning:t,tournamentRecord:o,drawDefinition:i,seedingProfile:s,participantId:x,seedNumber:w,seedValue:F,structureId:m,event:d})}}if(g.structureType!==Le)kF({provisionalPositioning:t,inContextDrawMatchUps:e,sourceMatchUpStatus:n,tournamentRecord:o,drawDefinition:i,drawPosition:u,matchUpsMap:p,structure:g,event:d});else{bh({positionAssignments:D,tournamentRecord:o,drawDefinition:i,matchUpsMap:p,structure:g});let{drawPositions:N,matchUps:C,targetMatchUps:O}=Vh({assignments:[y],inContextDrawMatchUps:e,drawDefinition:i,matchUpsMap:p,structure:g});if(N&&C?.length===1&&C[0].matchUpType===Bt){let x=(O?.[0].sides??[]).reduce((w,F,L)=>N?.includes(F.drawPosition)?L:w,void 0);Jm({inContextTargetMatchUp:O[0],teamParticipantId:a,matchUp:C[0],drawPositionSideIndex:x,tournamentRecord:o,drawDefinition:i})}}return To({tournamentId:o?.tournamentId,drawDefinition:i,structure:g,event:d}),{positionAssignments:D,...R};function P(N){let C=N.bye,O=N.qualifier,b=N.participantId;return{containsBye:C,containsQualifier:O,containsParticipant:b,filled:C||O||b}}}function kF({provisionalPositioning:t,inContextDrawMatchUps:e,sourceMatchUpStatus:r,tournamentRecord:n,drawDefinition:o,drawPosition:i,matchUpsMap:s,structure:a,event:c}){let u={isCollectionMatchUp:!1},{matchUps:p}=At({provisionalPositioning:t,matchUpFilters:u,drawDefinition:o,matchUpsMap:s,structure:a,event:c}),{roundMatchUps:m}=He({matchUps:p}),{initialRoundNumber:d}=ss({drawPosition:i,matchUps:p}),l=d&&m?.[d].find(f=>f.drawPositions?.includes(i));if(l){let f=Ic({matchUpId:l.matchUpId,inContextDrawMatchUps:e,sourceMatchUpStatus:r,tournamentRecord:n,drawDefinition:o,drawPosition:i,matchUpsMap:s});if(f.error)return _({stack:"assignDrawPositionToMatchUps",context:{drawPosition:i},result:f})}return{...R}}function rd(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{inContextDrawMatchUps:m,matchUpsMap:d}=t;d||(d=Ae({drawDefinition:i}),Object.assign(t,{matchUpsMap:d})),m||({matchUps:m}=re({inContext:!0,drawDefinition:i,matchUpsMap:d}),Object.assign(t,{inContextDrawMatchUps:m}));let{positionAssignments:l}=Nt({drawDefinition:i,structureId:c}),f=l?.find(T=>T.drawPosition===a);if(f?.participantId){let T=f.participantId,A=Mn({inContextDrawMatchUps:m,tournamentRecord:o,drawDefinition:i,participantId:s,drawPosition:a,structureId:c,matchUpsMap:d,event:u});return A.success?S({removedParticipantId:T}):_({result:A,stack:p})}let g=dc({inContextDrawMatchUps:m,tournamentRecord:o,drawDefinition:i,drawPosition:a,structureId:c,matchUpsMap:d,event:u});if(g.error)return _({result:g,stack:p});let I=g.participantId,h=Mn({inContextDrawMatchUps:m,isQualifierPosition:r,tournamentRecord:o,drawDefinition:i,participantId:s,drawPosition:a,structureId:c,matchUpsMap:d,event:u});if(!h.success)return _({result:h,stack:p});return S({removedParticipantId:I});function S({removedParticipantId:T}){let{structure:A}=st({drawDefinition:i,structureId:c});vm({drawPositions:[a],structure:A});let D={[e]:s,name:n,drawPosition:a,structureId:c};return tu({drawDefinition:i,positionAction:D}),_({context:{removedParticipantId:T},result:{...R},stack:p})}}function _b({luckyLoserParticipantId:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,structureId:o}){return rd({positionActionName:"luckyLoserDrawPositionAssignment",participantId:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,structureId:o})}function PU(t){return _b(t)}function vb({alternateParticipantId:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,structureId:o}){return rd({positionActionName:"alternateDrawPositionAssignment",participantIdAttributeName:"alternateParticipantid",participantId:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,structureId:o})}function DU(t){return vb(t)}function Bh({params:t,modMap:e,structure:r}){let{tournamentRecord:n,drawDefinition:o,event:i}=t;for(let s of r.matchUps)e[s.matchUpId]&&(s.roundNumber=e[s.matchUpId],It({tournamentId:n?.tournamentId,eventId:i?.eventId,drawDefinition:o,matchUp:s}))}function Hh(t,e){let r=[{drawDefinition:!0,structureId:!0}];Array.isArray(e)&&r.push(...e);let n=lt(t,r);if(n.error)return n;let o=st(t);if(o.error)return o;let i=o.structure;if(!fr({structure:i}))return _({result:{error:Pi,message:"structure must be adHoc"}});let{roundMatchUps:a=[],roundNumbers:c}=He({matchUps:i?.matchUps});return c?.length?{valid:!0,structure:i,roundMatchUps:a,roundNumbers:c}:{error:Sn}}function NU(t){let e=Hh(t,[{targetRoundNumber:!0,roundNumber:!0,[to]:iR}]);if(e.error)return e;let{structure:r,roundMatchUps:n,roundNumbers:o}=e,{targetRoundNumber:i,roundNumber:s}=t;if(!o?.includes(s)||!o?.includes(i))return _({result:{error:G},info:"roundNumbers must be valid rounds"});let a=i>s,c=a?Z(s+1,i+1):Z(i,s),u={};return c.forEach(p=>(n?.[p]??[]).forEach(({matchUpId:m})=>{u[m]=p-(a?1:-1)})),n?.[s]?.forEach(({matchUpId:p})=>u[p]=i),Bh({params:t,modMap:u,structure:r}),{...R}}function MU({structurePositionAssignments:t,provisionalPositioning:e,tournamentRecord:r,drawDefinition:n,event:o}){if(!n)return{error:X};if(!Array.isArray(t))return{error:G};let i="setPositionAssignments";for(let a of t){let{structureId:c,positionAssignments:u}=a;if(!u)continue;let p=st({drawDefinition:n,structureId:c});if(p.error)return p;let m=p.structure;if(!m)return{error:Lt};let d=Nt({structure:m}).positionAssignments?.map(({drawPosition:I})=>I),l=u?.map(({drawPosition:I})=>I);if(jt(d,l).length!==d?.length)return _({result:{error:G},info:"drawPositions do not match",stack:i});let f=Ae({drawDefinition:n}),{matchUps:g}=re({inContext:!0,drawDefinition:n,matchUpsMap:f});for(let I of u||[]){let{drawPosition:h,participantId:S,bye:T,qualifier:A}=I;if(T){let D=Dr({tournamentRecord:r,drawDefinition:n,drawPosition:h,matchUpsMap:f,structureId:c,structure:m,event:o});if(D?.error)return D}else if(A)u.forEach(D=>{D.drawPosition===h&&(D.qualifier=!0,delete D.participantId,delete D.bye)});else if(S){let D=Mn({provisionalPositioning:e,inContextDrawMatchUps:g,tournamentRecord:r,drawDefinition:n,participantId:S,drawPosition:h,matchUpsMap:f,structureId:c,event:o});if(D?.error)return D}}To({tournamentId:r?.tournamentId,drawDefinition:n,structure:m,event:o})}let s=t.map(({structureId:a})=>a);return bt({tournamentId:r?.tournamentId,eventId:o?.eventId,drawDefinition:n,structureIds:s}),{...R}}function CU(t){let e=Hh(t,[{roundNumbers:!0,[to]:Er,[yn]:s=>s.length===2&&s.every(te)}]);if(e.error)return e;let{structure:r,roundMatchUps:n,roundNumbers:o}=e;if(!t.roundNumbers.every(s=>o?.includes(s)))return _({result:{error:G,message:"roundNumbers must be valid rounds"}});let i={};return t.roundNumbers.forEach((s,a)=>(n?.[s]??[]).forEach(({matchUpId:c})=>{i[c]=t.roundNumbers[1-a]})),Bh({params:t,modMap:i,structure:r}),{...R}}function xb({qualifyingParticipantId:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,structureId:o}){return rd({positionActionName:"qualifierDrawPositionAssignment",participantId:t,isQualifierPosition:!0,tournamentRecord:e,drawDefinition:r,drawPosition:n,structureId:o})}function RU(t){return xb(t)}function wb({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:G,drawPositions:r};let i=Ae({drawDefinition:e}),{matchUps:s}=re({inContext:!0,drawDefinition:e,matchUpsMap:i}),{structure:a}=st({drawDefinition:e,structureId:n});if(!a)return{error:Lt};let c;if(a.structureType===Le?c=HF({inContextDrawMatchUps:s,tournamentRecord:t,drawDefinition:e,drawPositions:r,matchUpsMap:i,structure:a,event:o}):c=VF({inContextDrawMatchUps:s,tournamentRecord:t,drawDefinition:e,drawPositions:r,matchUpsMap:i,structure:a,event:o}),c.error)return c;if(vm({structure:a,drawPositions:r}),tu({drawDefinition:e,positionAction:{name:"swapDrawPositionAssignments",drawPositions:r,structureId:n}}),To({tournamentId:t?.tournamentId,drawDefinition:e,structure:a,event:o}),o.eventType===kr){let p=At({matchUpFilters:{matchUpTypes:[ln]},inContext:!0,structure:a}).matchUps.filter(d=>d.drawPositions?.some(l=>r.includes(l))),m=At({matchUpFilters:{matchUpTypes:[ln]},structure:a}).matchUps;p.forEach(d=>{(d.sides||[]).forEach(l=>{let f=l?.drawPosition;if(r.includes(f)){let g=l.participantId,I=m.find(({matchUpId:S})=>S===d.matchUpId),h=d?.sides?.reduce((S,T,A)=>T.drawPosition===f?A:S,void 0);Jm({inContextTargetMatchUp:d,drawPositionSideIndex:h,teamParticipantId:g,tournamentRecord:t,drawDefinition:e,matchUp:I,event:o})}})})}return bt({drawDefinition:e,structureIds:[n]}),{...R}}function VF({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,drawPositions:n,matchUpsMap:o,structure:i,event:s}){let a=i?.positionAssignments.filter(p=>n?.includes(p.drawPosition));if(!a)return{error:G,structure:i,info:"Missing positionAssignments"};if(a.filter(({bye:p})=>p).length===2)return{...R};if(a.filter(({qualifier:p})=>p).length===2)return{...R};let c=a.some(({qualifier:p})=>p);return a.some(({bye:p})=>p)&&!c?Lb({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,assignments:a,matchUpsMap:o,structure:i,event:s}):BF({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,assignments:a,matchUpsMap:o,structure:i,event:s})}function Lb({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=fu({drawPosition:u,inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,structureId:d,matchUpsMap:o});return l.error||(l=fu({drawPosition:m,inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,structureId:d,matchUpsMap:o}),l.error)||(Dr({drawPosition:m,tournamentRecord:e,drawDefinition:r,structureId:d,matchUpsMap:o,event:s}),l=Mn({drawPosition:u,inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,structureId:d,participantId:p,matchUpsMap:o,event:s}),l.error)?l:{...R}}function BF({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),zf({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,matchUpsMap:o,assignments:n,structure:i,event:s}),{...R}}function HF({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,drawPositions:n,matchUpsMap:o,structure:i,event:s}){let a=i.structures?.reduce((p,m)=>{let d=m?.positionAssignments.filter(l=>n?.includes(l.drawPosition));return d&&p.push(...d),p},[]);if(a.filter(({bye:p})=>p).length===2)return{...R};if(a.filter(({qualifier:p})=>p).length===2)return{...R};zf({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)Lb({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,assignments:a,matchUpsMap:o,structure:i,event:s});else{let p=J(a,!1,!0);a.forEach((m,d)=>{let l=p[1-d].participantId;m.qualifier=p[1-d].qualifier,m.participantId=l})}return{...R}}function bU(t){return wb(t)}function OU({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}=st({drawDefinition:r,structureId:o});if(!c)return{error:Lt};if(!(!t||te(i)||i===void 0||i===""||typeof i=="string"&&i.split("-").every(l=>te(l)&&ct(l)>0)))return{error:G};let{seedAssignments:p}=Fr({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 rh({tournamentId:e?.tournamentId,eventId:s?.eventId,drawDefinition:r,structure:c}),{...R}}function Wh({drawDefinition:t,structureId:e}){if(!t)return{error:X};let{structure:r}=st({drawDefinition:t,structureId:e}),n=(t?.links||[]).filter(i=>i.source?.structureId===e).map(i=>i.target?.structureId);return{playoffStructures:(t?.structures||[]).filter(i=>n.includes(i.structureId)),structure:r}}function Qf({withStageGrouping:t,stageSequences:e,stageSequence:r,roundTarget:n,stages:o,event:i,stage:s}){if(!i)return{error:Et};let a={},c=[];for(let u of i.drawDefinitions||[]){let{structures:p,stageStructures:m}=xn({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 jh({withStageGrouping:t,tournamentRecord:e,stageSequences:r,stageSequence:n,roundTarget:o,stages:i,stage:s}){if(!e)return{error:W};let a={},c=[];for(let u of e.events||[]){let{structures:p,stageStructures:m}=Qf({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 Jo(t){if(!t?.drawDefinition)return!1;let e=uu(t),r=e?.includesTeamMatchUps,{completedMatchUps:n,pendingMatchUps:o,upcomingMatchUps:i}=e||{};return r&&(n=n?.filter(({matchUpType:a})=>a===Bt),o=o?.filter(({matchUpType:a})=>a===Bt),i=i?.filter(({matchUpType:a})=>a===Bt)),!!(n?.length&&!o?.length&&!i?.length)}function Yh(t){let{drawDefinition:e,structureId:r}=t;if(!e)return{error:X};let{playoffStructures:n}=Wh({drawDefinition:e,structureId:r});if(!n?.length)return!1;let o=e?.entries?.filter(c=>c?.entryStatus&&Or.includes(c.entryStatus))?.length??0,i=0;return(n||[]).reduce((c,u)=>!!((Nt({structure:u}).positionAssignments??[])?.filter(d=>(d.participantId&&i++,d?.bye??d?.participantId)).length&&c),!!n.length)||i===o}function qh({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=qh({accessors:s,significantCharacters:t,value:c});n.push(...u)});else if(r=r[o],s.length){let a=qh({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 Fb({targetParticipantIds:t,policyAttributes:e,idCollections:r,participants:n}){if(!Array.isArray(e))return{error:fI};if(!Array.isArray(n))return{error:$a};let o={};return t.forEach(i=>{let s=n.find(c=>c.participantId===i),{values:a}=_U({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 _U({policyAttributes:t,idCollections:e,participants:r,participant:n}){if(!Array.isArray(t))return{error:fI};if(!n)return{error:Mi};let o=[];return t.forEach(s=>{let{directive:a,groupings:c,key:u,significantCharacters:p}=s||{};if(u){let m=u.split(".");o.push(...qh({significantCharacters:p,value:n,accessors:m}))}else if(a){let m=s?.includeIds,d=(e?.[a]||[]).filter(l=>!m||m.includes(l));d?.length&&r?.length&&d.forEach(l=>{let f=r.find(g=>g.participantId===l);if(f?.individualParticipantIds?.includes(n.participantId)){let g=f?.participantId;o.push(g)}})}else c&&Object.keys(c).forEach(m=>{c[m].includes(n.participantId)&&o.push(m)})}),{values:pt(o)}}function vU({candidatePositionAssignments:t,participantsWithGroupings:e,policyAttributes:r,idCollections:n}){let o=Object.assign({},...e.map(i=>({[i.participantId]:i})));return t.map(i=>{let s=o[i.participantId],{values:a}=_U({participants:e,policyAttributes:r,idCollections:n,participant:s});return{...i,values:a}})}function kb({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 Vb(t){let{unfilledPositions:e,chunkedDrawPositions:r}=t,n=kb(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=Gb(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=Gb(c);return!s.includes(u)}}}function Bb(t){let{unfilledPositions:e,chunkedDrawPositions:r}=t,n=kb(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 Gb(t){return Number(t%2?t+1:t-1)}function Hb({allGroups:t,participantId:e}){return Object.keys(t).filter(r=>t[r].includes(e))}function Wb({selectedParticipantGroups:t,participantIdGroups:e,positionAssignments:r,drawPositionChunks:n,unfilledPositions:o,isRoundRobin:i}){let s=n.map(a=>i?Bb({groupsToAvoid:t,chunkedDrawPositions:a,participantIdGroups:e,positionAssignments:r,unfilledPositions:o}):Vb({groupsToAvoid:t,chunkedDrawPositions:a,participantIdGroups:e,positionAssignments:r,unfilledPositions:o}));if(i){let a=s.map(p=>p.map(m=>m.unassigned).filter(m=>m?.length)).filter(p=>p?.length).sort((p,m)=>(m.length||0)-(p.length||0)),c=s.map(p=>p.map(m=>m.unpaired).filter(m=>m?.length)).filter(p=>p?.length),u=s.map(p=>p.map(m=>m.pairedNoConflict).filter(m=>m?.length)).filter(p=>p?.length).sort((p,m)=>(m.length||0)-(p.length||0));return{unassigned:a,unpaired:c,pairedNoConflict:u}}else{let a=s.map(p=>p.map(m=>m.unassigned).filter(m=>m?.length)).filter(p=>p?.length),c=s.map(p=>p.map(m=>m.unpaired).filter(m=>m?.length)).filter(p=>p?.length),u=s.map(p=>p.map(m=>m.pairedNoConflict).filter(m=>m?.length)).filter(p=>p?.length);return{unassigned:a,unpaired:c,pairedNoConflict:u}}}function $h({positionAssignments:t,participantIds:e}){let r=t.map(n=>n.participantId);return e.filter(n=>!r.includes(n))}function jb({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?on(a):on(Object.keys(i));return o=t&&i[o]?.length?o:c,{participantId:o&&i[o]?on(i[o]):on(e),groupKey:o}}function Yb({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 qb({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=$h({positionAssignments:t,participantIds:e}),m=Yb({positionAssignments:t,drawPositionGroups:o}),{participantId:d,groupKey:l}=jb({targetParticipantIds:p,useSpecifiedGroupKey:u,allGroups:s,groupKey:a}),f=Hb({participantId:d,allGroups:s}),g=Wb({positionAssignments:t,isRoundRobin:u,selectedParticipantGroups:f,participantIdGroups:r,drawPositionChunks:n,unfilledPositions:m}),{unassigned:I,unpaired:h,pairedNoConflict:S}=g,T=S?.length&&S[0],A=h?.length&&h[0],D=i&&T?T:A,y=i?A:T,E=D?.length&&D||y?.length&&y,U;if(E?.length){let M=xr(E);U=xr(M)}else{let M=xr(I[0]);U=xr(M)}return{newGroupKey:l,selectedParticipantId:d,targetDrawPosition:U}}function nd({isRoundRobin:t,groupedParticipants:e}){let r=[];return t?e.forEach(n=>{let o=n.map(a=>a.drawPosition),i=Yf({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 $b({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=nd({isRoundRobin:o,groupedParticipants:[[c,l]]}),h=[t.find(T=>T.drawPosition===m),l],S=nd({isRoundRobin:o,groupedParticipants:[h]});return!g.length&&!S.length});if(p.length)return{drawPosition:c.drawPosition,possibleDrawPositions:p}}).filter(Boolean)}).flat(1)}function xU(t){let{initialPositionAssignments:e,participantsWithGroupings:r,opponentsToPlaceCount:n,unseededByePositions:o,drawPositionGroups:i,policyAttributes:s,idCollections:a,allGroups:c}=t,u=[],p,m=Math.min(...(i||[]).map(T=>T?.length).filter(Boolean)),d=m>2,l=J(e,!1,!0).filter(T=>!T.qualifier),f=e.filter(T=>!T.participantId&&(!T.bye||o?.includes(T.drawPosition))).map(T=>T.drawPosition);Z(0,n).forEach(()=>{let{newGroupKey:T,selectedParticipantId:A,targetDrawPosition:D}=qb({...t,candidatePositionAssignments:l,allGroups:c,groupKey:p});p=T,l.forEach(y=>{y.drawPosition===D&&(y.participantId=A)})});let g=vU({candidatePositionAssignments:l,participantsWithGroupings:r,policyAttributes:s,idCollections:a}),I=Te(g,m),h=nd({groupedParticipants:I,isRoundRobin:d}),S=0;for(;S<20&&h.length;){let T=$b({positionedParticipants:g,potentialDrawPositions:f,avoidanceConflicts:h,drawPositionGroups:i,isRoundRobin:d});if(T.length){let A=WF({candidatePositionAssignments:l,swapOptions:T});A.error&&console.log({result:A}),g=vU({candidatePositionAssignments:l,participantsWithGroupings:r,policyAttributes:s,idCollections:a}),I=Te(g,m),h=nd({groupedParticipants:I,isRoundRobin:d}),S++}else S=20}return l.forEach(T=>{if(T.bye&&T.participantId){let A=pI;u.push(A)}if(T.qualifier&&T.participantId){let A=pI;u.push(A)}}),{positionAssignments:l,conflicts:h.length,groupedParticipants:I,errors:u}}function WF({candidatePositionAssignments:t,swapOptions:e}){let r=xr(e);if(!r)return{error:{message:"No swap options"}};let n=r.drawPosition,o=xr(r.possibleDrawPositions),i=t.find(u=>u.drawPosition===n),s=t.find(u=>u.drawPosition===o)??{},a={participantId:s?.participantId,qualifier:s?.qualifier,bye:s?.bye},c={participantId:i.participantId,qualifier:i.qualifier,bye:i.bye};return Object.assign(i,a),Object.assign(s,c),{...R}}function Kb({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:yy};let{candidatesCount:l=1,policyAttributes:f,targetDivisions:g}=p,{roundsToSeparate:I}=p,h="randomUnseededSeparation",{structure:S}=st({drawDefinition:i,structureId:u}),{matchUps:T}=At({provisionalPositioning:t,matchUpsMap:c,structure:S,event:d});if(g&&Tn(g)&&!I){let H=GC(g)||0,j=T.reduce((V,Y)=>Y.roundNumber>V?Y.roundNumber:V,0);I=j<H?1:j-H+1}let{positionAssignments:A}=de({structure:S}),D=xm({participantsProfile:{convertExtensions:!0},deepCopy:!1,participants:a}).participantsWithGroupings,y=A?.filter(H=>!H.participantId),E=A?.map(H=>H.drawPosition),U=S?.structureType===Le,M=U?{structure:S,matchUps:T,allDrawPositions:E,roundsToSeparate:I}:{matchUps:T,allDrawPositions:E,roundsToSeparate:I},{drawPositionGroups:P,drawPositionChunks:N}=U?jF(M):YF(M),C={groupParticipants:a.filter(H=>H.participantType===Ar).map(H=>H.participantId),teamParticipants:a.filter(H=>H.participantType===kt).map(H=>H.participantId),pairParticipants:a.filter(H=>H.participantType===dt).map(H=>H.participantId)},O=Fb({targetParticipantIds:e,policyAttributes:f,idCollections:C,participants:a});if(O.error)return _({result:O,stack:h});let b=Object.assign({},...e.map(H=>{let j=Object.keys(O).filter(V=>(O[V]??[]).includes(H));return{[H]:j}})),x=$h({participantIds:e,positionAssignments:A});if(x.length>(y?.length||0))return{error:Cl};let w,F=x.length,L=Z(0,l).map(()=>xU({initialPositionAssignments:A,participantsWithGroupings:D,unseededParticipantIds:e,opponentsToPlaceCount:F,pairedPriority:!1,unseededByePositions:n,participantIdGroups:b,drawPositionChunks:N,drawPositionGroups:P,policyAttributes:f,idCollections:C,allGroups:O,drawSize:m}));if(w=L.reduce((H,j)=>!H||(j.conflicts||0)<(H.conflicts||0)?j:H,void 0),!w||w.conflicts){let H=Z(0,l).map(()=>xU({initialPositionAssignments:A,participantsWithGroupings:D,unseededParticipantIds:e,opponentsToPlaceCount:F,pairedPriority:!0,unseededByePositions:n,participantIdGroups:b,drawPositionChunks:N,drawPositionGroups:P,policyAttributes:f,idCollections:C,allGroups:O,drawSize:m}));w=L.concat(...H).filter(V=>!V.errors?.length).reduce((V,Y)=>!V||(Y.conflicts||0)<(V.conflicts||0)?Y:V,void 0)}if(!w)return{error:Yu};let v=(Nt({structure:S})?.positionAssignments??[]).filter(H=>H.participantId).map(H=>H.participantId),B=w.positionAssignments.filter(H=>!v.includes(H.participantId));for(let H of B)if(H.bye){let j=Dr({tournamentRecord:o,drawDefinition:i,seedBlockInfo:s,structureId:u,matchUpsMap:c,event:d,...H});if(j.error)return _({result:j,stack:h})}else if(H.participantId){let j=Mn({automaticPlacement:!0,inContextDrawMatchUps:r,tournamentRecord:o,drawDefinition:i,seedBlockInfo:s,structureId:u,matchUpsMap:c,event:d,...H});if(j.error)return _({result:j,stack:h,context:{assignment:H}})}return{...R}}function jF(t){let{structure:{structures:e}}=t,r=e.map(n=>n.positionAssignments.map(o=>o.drawPosition));return{drawPositionGroups:r,drawPositionChunks:[r]}}function YF({allDrawPositions:t,roundsToSeparate:e,matchUps:r}){let n=r.filter(d=>d.roundNumber===1).map(d=>d.drawPositions),o=n.flat().sort(se),i=Math.max(...o),s=t.filter(d=>d>i),a=o.length,u=Z(a===2?1:2,a).filter(d=>d===cm(d)),m=u.slice(0,e||u.length).reverse().map(d=>Te(o,d));return s.length&&console.log({fedDrawPositions:s}),{drawPositionGroups:n,drawPositionChunks:m}}function zb({provisionalPositioning:t,inContextDrawMatchUps:e,unseededByePositions:r,multipleStructures:n,tournamentRecord:o,drawDefinition:i,seedBlockInfo:s,participants:a,matchUpsMap:c,structureId:u,structure:p,drawSize:m,event:d}){let l="positionUnseededParticipants";p||({structure:p}=st({drawDefinition:i,structureId:u})),u||({structureId:u}=p);let{positionAssignments:f}=de({structure:p}),{seedAssignments:g}=Fr({provisionalPositioning:t,drawDefinition:i,structure:p}),I=g?.map(N=>N.participantId).filter(Boolean),{stage:h,stageSequence:S}=p,T=h===at?mt({element:p,name:mn})?.extension?.value:void 0,D=mi({provisionalPositioning:t,drawDefinition:i,stageSequence:S,entryStatuses:qo,structureId:u,roundTarget:T,stage:h}),E=D.filter(N=>!I?.includes(N.participantId)).map(N=>N.participantId),U=f?.filter(N=>!N.participantId&&!N.bye&&!N.qualifier).map(N=>N.drawPosition);if(!n&&E.length>(U?.length||0))return _({result:{error:Cl},context:{unseededParticipantsCount:E.length,unfilledDrawPositionsCount:U?.length},stack:l});let{appliedPolicies:M}=Pt({tournamentRecord:o,drawDefinition:i,event:d}),P=M?.[Wc];if(p.stage===ce){let N=D.reduce((C,O)=>(C[O.groupingValue]||(C[O.groupingValue]=[]),C[O.groupingValue].push(O.participantId),C),{});Object.keys(N).length&&(P||(P={policyName:"Playoff Avoidance"}),P.policyAttributes||(P.policyAttributes=[]),P.policyAttributes.push({groupings:N}))}return P&&a?Kb({provisionalPositioning:t,unseededParticipantIds:E,inContextDrawMatchUps:e,unseededByePositions:r,tournamentRecord:o,drawDefinition:i,seedBlockInfo:s,participants:a,matchUpsMap:c,structureId:u,avoidance:P,drawSize:m,entries:D}):qF({provisionalPositioning:t,unseededParticipantIds:E,inContextDrawMatchUps:e,unfilledDrawPositions:U,multipleStructures:n,tournamentRecord:o,drawDefinition:i,seedBlockInfo:s,structureId:u,matchUpsMap:c,drawSize:m,event:d})}function qF({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?cr(n):n.reverse();for(let l of e){let f=d.pop();if(!o||f){let g=Mn({provisionalPositioning:t,inContextDrawMatchUps:r,tournamentRecord:i,drawDefinition:s,seedBlockInfo:a,participantId:l,drawPosition:f,matchUpsMap:c,structureId:u,event:m});if(g?.error&&console.log("!!!!!",{result:g}),g?.error)return _({result:g,stack:"randomUnseededDistribution"})}}return{...R}}function Qb(t){let e=t.structure??st(t).structure,r="positionQualifiers",n=[];if(e.stage===Ve)return _({result:{error:Di},stack:r});let{unplacedRoundQualifierCounts:o,positionAssignments:i,roundDrawPositions:s}=$F(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:Gy},context:{unfilledDrawPositions:c},stack:r});Z(0,o[a]).forEach(()=>{let u=xr(c);n.push(u),i?.forEach(p=>{p.drawPosition===u&&(p.qualifier=!0,delete p.participantId,delete p.bye)})})}return{...R,qualifierDrawPositions:n}}function $F({drawDefinition:t,structure:e,structureId:r}){e||({structure:e}=st({drawDefinition:t,structureId:r})),r||({structureId:r}=e);let{positionAssignments:n}=de({structure:e}),{stage:o,stageSequence:i}=e,{qualifiersCount:s,roundQualifiersCounts:a}=cs({drawDefinition:t,stageSequence:i,structureId:r,stage:o}),u=(a?Object.keys(a):[]).map(h=>ct(h)),{matchUps:p}=At({structure:e}),{roundProfile:m}=He({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 wU({provisionalPositioning:t,inContextDrawMatchUps:e,tournamentRecord:r,appliedPolicies:n,validSeedBlocks:o,drawDefinition:i,seedingProfile:s,seedBlockInfo:a,participants:c,groupsCount:u,structureId:p,matchUpsMap:m,structure:d,event:l}){let f=[],g=[],I=0;if(d||({structure:d}=st({drawDefinition:i,structureId:p})),p||(p=d?.structureId),n||(n=Pt({drawDefinition:i}).appliedPolicies),!o){let h=d&&ms({provisionalPositioning:t,appliedPolicies:n,drawDefinition:i,seedingProfile:s,structure:d});h?.error&&g.push(h.error),o=h?.validSeedBlocks}return u=u??o?.length??0,Z(0,u).forEach(()=>{if(I<(u||0)){let h=KF({provisionalPositioning:t,inContextDrawMatchUps:e,tournamentRecord:r,drawDefinition:i,seedingProfile:s,seedBlockInfo:a,participants:c,structureId:p,matchUpsMap:m,event:l});h?.success&&(I++,f.push(...h.seedPositions??[])),h.error&&g.push({seedPositionError:h.error})}}),g.length?{error:g}:{...R,seedPositions:f}}function KF({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}=Lh({provisionalPositioning:t,randomize:!0,drawDefinition:n,seedingProfile:o,seedBlockInfo:i,structureId:a,event:u}),{appliedPolicies:d}=Pt({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:Es};f.push(I);let h=Mn({provisionalPositioning:t,inContextDrawMatchUps:e,tournamentRecord:r,drawDefinition:n,seedingProfile:o,participantId:g,seedBlockInfo:i,drawPosition:I,matchUpsMap:c,structureId:a,event:u});if(!h.success)return h}return{...R,seedPositions:f}}function Xb({provisionalPositioning:t,drawDefinition:e,structure:r}){let{positionAssignments:n}=de({structure:r}),{seedAssignments:o}=Fr({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 Jb({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=LU(Te(i.drawPositions,2)),c,u=t[n.length];for(;c=Xf(a,u);)n.push(c),u=t[n.length]}});let o=n.map(i=>Array.isArray(i)?cr(i):i).flat(1/0);return yI(r)&&e.map(s=>s.seedNumbers[0]).includes(r)?t:o}function Xf(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 Xf(e?o:t[Math.round(Math.random())],e)}return r<n?Xf(t[1],e):Xf(t[0],e)}function LU(t){let e=Math.floor(t.length/2);return t.length>2?[LU(t.slice(0,e)),LU(t.slice(e))]:t}function tO({provisionalPositioning:t,relevantMatchUps:e,appliedPolicies:r,drawDefinition:n,seedingProfile:o,seedBlockInfo:i,byesToPlace:s,structure:a}){i||(i=ms({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=Xb({provisionalPositioning:t,drawDefinition:n,structure:a})??[],l=pt([].concat(...e.map(D=>D.drawPositions))),f=d.filter(D=>l.includes(D.drawPosition)),g=(D,y)=>gc(D.seedValue)-gc(y.seedValue),h=m.reduce((D,y)=>{let E=f.filter(U=>y.drawPositions?.includes(U.drawPosition)).sort(g);return D.concat(...E)},[]).map(D=>D.drawPosition),S=Jb({orderedSortedFirstRoundSeededDrawPositions:h,validSeedBlocks:m,byesToPlace:s}),T=Zb({orderedSeedDrawPositions:h,relevantMatchUps:e}).slice(0,s),A=Zb({orderedSeedDrawPositions:S,relevantMatchUps:e}).slice(0,s);return{strictSeedOrderByePositions:T,blockSeedOrderByePositions:A,isLuckyStructure:u,positionedSeeds:d,isContainer:p,isFeedIn:c}}function Zb({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 eO({provisionalPositioning:t,seedOrderByePositions:e,isLuckyStructure:r,appliedPolicies:n,drawDefinition:o,seedLimit:i,structure:s,isFeedIn:a}){let c=n?.seeding?.seedingProfile,u=s.stage===at,{positionAssignments:p}=de({structure:s}),m=p?.filter(x=>x.participantId).map(x=>x.drawPosition),d={isCollectionMatchUp:!1},{matchUps:l,roundMatchUps:f}=At({provisionalPositioning:t,matchUpFilters:d,structure:s}),g=f?.[1]||[],I=s.structureType===Le?l:g,h=pt([].concat(...I.map(x=>x.drawPositions))),S=Math.min(...h)-1,T=m?.filter(x=>h.includes(x)),A=x=>{let w=Math.ceil(x.length/2),F=[x.slice(0,w),x.slice(w)],L=F.map(k=>[].concat(...k.flat(1/0)).length),v=Math.min(...L.flat(1/0)),B=Math.max(...L.flat(1/0)),H=L.indexOf(B),j=v!==B,V=cr(F),[Y,$]=!v||j?[F[H],F[1-H]]:[V[0],V[1]];return{greaterHalf:Y,lesserHalf:$}},D=x=>{let{greaterHalf:w,lesserHalf:F}=A(x),{greaterHalf:L,lesserHalf:v}=A(w),H=cr(L.flat(1/0)).pop(),j=L.flat().filter(Y=>Y!==H);return{newlyFilteredChunks:[...F,...v,j],drawPosition:H}},y=x=>!e.includes(x),E=x=>!T?.includes(x),U=x=>{let F=Te(x.sort(se),Math.ceil(x.length/4)).map(B=>B.filter(E)),L=[].concat(...F.flat(1/0)).length,v=[];for(let B=0;B<L;B++){let{newlyFilteredChunks:H,drawPosition:j}=D(F);v.push(j),F=H}return v},{validSeedBlocks:M}=ms({provisionalPositioning:t,allPositions:!0,appliedPolicies:n,drawDefinition:o,structure:s}),P=M?.map(x=>x.drawPositions?.map(w=>w+S)),N;if(a){let x=h.length,{seedBlocks:w}=$f({cluster:Ap(c)===zc,participantsCount:x});N=w.map(L=>L.map(v=>v+S)).map(U).filter(L=>L.length)}else u?N=P?.map(x=>x.filter(E)):N=P?.map(U).filter(x=>x.length);let C=I.map(x=>x.drawPositions).map(x=>x?.sort((w,F)=>w-F)).filter(x=>x?.[0]+1===x?.[1]),O=x=>C.reduce((w,F)=>F.includes(x)?F.reduce((L,v)=>v!==x?v:L,void 0):w,void 0),b=N.map(x=>x.map(O)).flat(1/0).filter(E).filter(y).filter(Boolean);if(u&&!s.structures){let x=i%4,w=b.slice(0,x),F=f[s.roundLimit]?.length,L=Te(b.slice(x),F).map(cr).flat();b=w.concat(L)}return{unseededByePositions:b}}function rO({provisionalPositioning:t,drawDefinition:e,matchUpsMap:r,structure:n,event:o}){let i={isCollectionMatchUp:!1},{matchUps:s,roundMatchUps:a}=At({afterRecoveryTimes:!1,provisionalPositioning:t,drawDefinition:e,matchUpFilters:i,matchUpsMap:r,structure:n,event:o}),c=a?.[1]||[],u=n?.structureType===Le,p=u?s:c,m=u?n?.structures?.length||0:s.length,{structureId:d,stage:l,stageSequence:f}=n,g=mi({entryStatuses:Or,provisionalPositioning:t,drawDefinition:e,stageSequence:f,structureId:d,stage:l}),{qualifiersCount:I}=cs({provisionalPositioning:t,drawDefinition:e,stageSequence:f,structureId:d,stage:l}),h=g.length+I,{positionAssignments:S,unassignedPositions:T}=de({structure:n}),A=T?.map(P=>P.drawPosition),D=S?.filter(P=>P.bye).length,y=S?.filter(P=>P.bye).map(P=>P.drawPosition),E=p.map(P=>P.drawPositions).filter(P=>P?.reduce((N,C)=>!y?.includes(C)&&N,!0)).flat(1/0).filter(P=>A?.includes(P)),U=S?.length,M=U?U-h:0;return M>m&&n.stageSequence===1&&n.stage!==Ve&&(M=m),{placedByes:D,byesCount:M,relevantMatchUps:p,placedByePositions:y,roundMatchUps:a,positionsToAvoidDoubleBye:E}}function FU({provisionalPositioning:t,tournamentRecord:e,appliedPolicies:r,drawDefinition:n,seedBlockInfo:o,seedingProfile:i,matchUpsMap:s,structureId:a,structure:c,seedLimit:u,seedsOnly:p,event:m}){c||({structure:c}=st({drawDefinition:n,structureId:a})),a||(a=c?.structureId);let d=!(c?.structures??c?.stage===at),{byesCount:l,placedByes:f,relevantMatchUps:g}=rO({provisionalPositioning:t,drawDefinition:n,matchUpsMap:s,structure:c,event:m}),I=l-(f||0);if(I<=0)return{...R};let{strictSeedOrderByePositions:h,blockSeedOrderByePositions:S,isLuckyStructure:T,isFeedIn:A}=tO({provisionalPositioning:t,relevantMatchUps:g,appliedPolicies:r,drawDefinition:n,seedingProfile:i,seedBlockInfo:o,byesToPlace:I,structure:c}),D=c?.structureType&&[Le,op].includes(c.structureType)&&r?.seeding?.containerByesIgnoreSeeding,y=d&&S?.length?S:h,{unseededByePositions:E}=eO({provisionalPositioning:t,seedOrderByePositions:y,isLuckyStructure:T,appliedPolicies:r,drawDefinition:n,seedLimit:u,structure:c,isFeedIn:A}),U=C=>C%2,M=(C,O)=>(C||[]).every(b=>U(b)?O!==b+1:O!==b-1),P=[].concat(...y);if(!p)for(;E.length;){let C=E.find(O=>M(P,O));C?(P.push(C),E=E.filter(O=>O!==C)):(P.push(...E),E=[])}D&&(P=cr(P),yr({ignoreSeededByes:D})&&console.log({byePositions:P}));let N=P.slice(0,I);for(let C of N){let O=Dr({provisionalPositioning:t,tournamentRecord:e,drawDefinition:n,drawPosition:C,matchUpsMap:s,structureId:a,structure:c,event:m});if(O?.error)return O}return{...R,unseededByePositions:E,byeDrawPositions:N}}function hc(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||(mE(),e=J(e,!1,!0));let I=w=>(r||kl(),_({result:w,stack:"automatedPositioning"})),h=w=>(r||kl(),w),S=st({drawDefinition:e,structureId:u});if(S.error)return I(S);let T=S.structure;if(!T)return{error:Lt};let A=t.appliedPolicies||Pt({drawDefinition:e,structure:T,event:f})?.appliedPolicies,{qualifiersCount:D}=cs({stageSequence:T.stageSequence,provisionalPositioning:n,stage:T.stage,drawDefinition:e,structureId:u}),y=qo;if(!mi({stageSequence:T.stageSequence,provisionalPositioning:n,stage:T.stage,placementGroup:a,drawDefinition:e,entryStatuses:y,structureId:u})?.length&&!D)return h({...R});let U=t.matchUpsMap??Ae({drawDefinition:e}),M=t.inContextDrawMatchUps??re({inContext:!0,drawDefinition:e,matchUpsMap:U})?.matchUps,P=[],N=ms({provisionalPositioning:n,appliedPolicies:A,drawDefinition:e,seedingProfile:c,structure:T});if(N.error)return N;let{validSeedBlocks:C}=N;g.push({validSeedBlocks:C});let O=t.participants||(s?Yt({withIndividualParticipants:!0,convertExtensions:!0,tournamentRecord:s})?.participants:[]);if(Ap(T.seedingProfile||c)===si){let w=i?FU({provisionalPositioning:n,tournamentRecord:s,appliedPolicies:A,drawDefinition:e,seedBlockInfo:N,matchUpsMap:U,structure:T,seedLimit:p,seedsOnly:m,event:f}):void 0;if(w?.error)return I(w);P=w.unseededByePositions,g.push({action:"positionByes",unseededByePositions:P});let F=T.seedingProfile?{positioning:T.seedingProfile}:c;if(w=wU({seedingProfile:F,provisionalPositioning:n,inContextDrawMatchUps:M,tournamentRecord:s,appliedPolicies:A,validSeedBlocks:C,drawDefinition:e,seedBlockInfo:N,participants:O,matchUpsMap:U,structure:T,event:f}),w.error)return I(w);g.push({seedPositions:w.seedPositions,action:"positionSeedBlocks"})}else{if(d!==Oi){let F=T.seedingProfile?{positioning:T.seedingProfile}:c,L=wU({seedingProfile:F,provisionalPositioning:n,inContextDrawMatchUps:M,tournamentRecord:s,appliedPolicies:A,validSeedBlocks:C,drawDefinition:e,seedBlockInfo:N,participants:O,matchUpsMap:U,structure:T,event:f});if(L.error)return I(L);g.push({action:"positionSeedBlocks",seedPositions:L.seedPositions})}let w=i?FU({provisionalPositioning:n,tournamentRecord:s,appliedPolicies:A,drawDefinition:e,seedBlockInfo:N,matchUpsMap:U,structure:T,seedLimit:p,seedsOnly:m,event:f}):void 0;if(w?.error)return I(w);P=w?.unseededByePositions,g.push({action:"positionByes",byeDrawPositions:w?.byeDrawPositions,unseededByePositions:P})}let b={};if(!m){let w=Qb({inContextDrawMatchUps:M,tournamentRecord:s,appliedPolicies:A,validSeedBlocks:C,drawDefinition:e,seedBlockInfo:N,participants:O,matchUpsMap:U,structure:T});if(w.error||(w.conflicts&&(b.qualifierConflicts=w.conflicts),g.push({action:"positionQualifiers",qualifierDrawPositions:w.qualifierDrawPositions}),w=zb({provisionalPositioning:n,inContextDrawMatchUps:M,unseededByePositions:P,multipleStructures:o,tournamentRecord:s,drawDefinition:e,seedBlockInfo:N,participants:O,matchUpsMap:U,structureId:u,structure:T,drawSize:l,event:f}),w.error))return I(w);w.conflicts&&(b.unseededConflicts=w.conflicts),g.push({action:"positionUnseededParticipants"})}let{positionAssignments:x}=Nt({drawDefinition:e,structure:T});return bt({drawDefinition:e,structureIds:[u]}),r||kl(),{positionAssignments:x,conflicts:b,...R,positioningReport:g}}function Sc(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:mr};if(!o)return{error:pr};if(!Jo({drawDefinition:o,structureId:s})&&!r)return{error:dl};let m=Wh({drawDefinition:o,structureId:s}).playoffStructures?.sort((f,g)=>af(f)-af(g)),d=[],l=[];if(m)for(let f of m){let{structureId:g}=f,I=hc({structureId:g,provisionalPositioning:r,applyPositioning:e,tournamentRecord:n,drawDefinition:o,seedingProfile:i,placeByes:a,seedsOnly:c});if(I.error)return I;I.positionAssignments&&d.push({positionAssignments:I.positionAssignments,structureId:g}),I.positioningReport&&l.push(I.positioningReport)}return{...R,structurePositionAssignments:d,positioningReports:l}}function GU({drawDefinition:t,orderMap:e}){return t?((typeof e!="object"||!Object.values(e).every(r=>ft(r)))&&_({result:{error:G},context:{orderMap:e}}),t.structures||(t.structures=[]),t.structures.forEach(r=>{let n=e[r.structureId];n&&(r.structureOrder=n)}),t.structures.sort((r,n)=>Qa(r.structureOrder)-Qa(n.structureOrder)),{...R}):{error:X}}function gu({drawDefinition:t}){let e=t.structures??[],r=t.links??[],n=new Map,o=I=>{let h=n.get(I)||n.set(I,{drawSources:[],drawTargets:[],progeny:[],sources:[],targets:[]})&&n.get(I);if(h&&!h?.stage){let S=e.find(T=>T.structureId===I);h.stage=S?.stage}return h},i={},s={},a=r.map(I=>{let h=I.source.structureId,S=I.target.structureId,T=o(h),A=o(S);return[ai,sn,ip,si].includes(I.target.feedProfile)?(T?.targets.push(S),A?.sources.push(h)):I.target.feedProfile===Qr&&(A?.drawSources.push(h),T?.drawTargets.push(S)),s[S]=s[S]||I.target.feedProfile===Qr,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(),A=T&&n[T];A?.targets?.length?S.push(...A.targets):A&&(h.rootStage=A.stage)}if(h.rootStage||(h.rootStage=h.stage),!h.targets?.length){let T=h.sources??[];for(;T.length;){let A=T.pop(),D=A&&n[A];if(D?.sources?.length){for(let y of D.sources)h.progeny?.includes(y)||h.progeny?.push(y);T.push(...D.sources)}}}}}let c=0;for(let I of n.keys()){let h=n.get(I);if(h&&h.rootStage===at){let S=[h.drawTargets?.[0]],T=0;for(;S.length;){T+=1;let A=S.pop(),D=A?n.get(A):void 0;D?.drawTargets?.length&&S.push(D.drawTargets[0])}h.distanceFromMain=T,T>c&&(c=T)}}let u=a.length;Z(0,Math.ceil(u/2)).forEach(()=>{a=Z(0,u).map(I=>{let h=a[I],S=a.reduce((T,A)=>xe(h,A)?T.concat(...A):T,[])||[];return pt(h.concat(...S))})});let p=a[0],m=(I,h)=>jt(I,h).length===I.length,d=a.slice(1).reduce((I,h)=>I&&m(h,p),!0),l=[p].filter(Boolean),f=[p].filter(Boolean);e.forEach(I=>{let{structureId:h,stage:S}=I;l.find(A=>A.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 Kh({drawDefinition:t}){let{maxQualifyingDepth:e,structureProfiles:r}=gu({drawDefinition:t});for(let n of t.structures){let o=r[n.structureId];o.distanceFromMain&&(n.stageSequence=e+1-o.distanceFromMain)}return{...R}}function Ti(t){let{duplicateValues:e=!0,creationTime:r=!0,removePriorValues:n,timeItem:o,element:i}=t;if(!o)return{error:Ol};if(!i)return{error:et,info:Sm};let s=o&&Object.keys(o),a=["itemType","itemValue"];if(!(a.filter(p=>s.includes(p)).length===a.length))return{error:bl};if(!i.timeItems)i.timeItems=[];else{let{itemType:p,itemSubTypes:m,itemValue:d}=o,l=p&&Gn({itemSubTypes:m,itemType:p,element:i})?.timeItem;if(l&&JSON.stringify(l?.itemValue)===JSON.stringify(d)&&!e)return{...R}}if(o.itemSubTypes&&!o.itemSubTypes.length&&delete o.itemSubTypes,r){let p=new Date().toISOString();Object.assign(o,{createdAt:p})}return n&&(i.timeItems=i.timeItems.filter(({itemType:p})=>o.itemType!==p)),n&&!o.itemValue||i.timeItems.push(o),{...R}}function Jf({creationTime:t=!0,removePriorValues:e,tournamentRecord:r,duplicateValues:n,participantId:o,timeItem:i}){if(!r)return{error:W};if(!o)return{error:oe};let s=xo({tournamentRecord:r,participantId:o});return s.error?s:Ti({element:s.participant,removePriorValues:e,duplicateValues:n,creationTime:t,timeItem:i})}function Gi(t){let{removePriorValues:e,tournamentRecord:r,duplicateValues:n,creationTime:o,timeItem:i}=t;return r?Ti({element:r,removePriorValues:e,duplicateValues:n,creationTime:o,timeItem:i}):{error:W}}function ki(t){let{removePriorValues:e,duplicateValues:r,creationTime:n,timeItem:o,event:i}=t;return i?Ti({removePriorValues:e,duplicateValues:r,element:i,creationTime:n,timeItem:o}):{error:mr}}function Zf({tournamentRecord:t,drawDefinition:e,structure:r,link:n}){if(!t)return{error:W};if(!e)return{error:X};let o=zF({tournamentId:t.tournamentId,drawDefinition:e,structure:r,link:n});if(o.error)return o;let s={itemType:"attachQualifyingStructures",itemValue:{structureId:r.structureId,drawId:e.drawId}};return Gi({tournamentRecord:t,timeItem:s}),o}function zF({drawDefinition:t,tournamentId:e,structure:r,eventId:n,link:o}){if(!t)return{error:X};if(!r)return{error:Do};if(!o)return{error:gl};let i=o.target.structureId,s=st({drawDefinition:t,structureId:i});if(s.error)return _({stack:"attachQualifyingStructure",context:{targetStructureId:i},result:s});t.structures||(t.structures=[]),t.links||(t.links=[]),t.structures.push(r),t.links.push(o),Kh({drawDefinition:t});let a=At({structure:r})?.matchUps||[];return So({drawDefinition:t,tournamentId:e,matchUps:a,eventId:n}),bt({drawDefinition:t,structureIds:[r.structureId]}),{...R}}function kU({drawDefinition:t,structureDetails:e}){if(!Array.isArray(e))return{error:G};if(!t)return{error:X};let r=Object.assign({},...e.map(n=>{if(!Rt(n))return;let{structureId:o,structureName:i}=n||{};if(!(!o||!i))return{[o]:i}}).filter(Boolean));if(!Object.values(r).length)return{error:et};for(let n of t.structures||[]){let o=r[n.structureId];o&&(n.structureName=o)}return{...R}}function tg({drawDefinition:t,timeItem:e}){if(!t)return{error:pr};if(!e)return{error:Ol};let r=e&&Object.keys(e),n=["itemType","itemValue"];if(!(n.filter(s=>r.includes(s)).length===n.length))return{error:bl};t.timeItems||(t.timeItems=[]);let i=new Date().toISOString();return Object.assign(e,{createdAt:i}),t.timeItems.push(e),ga({drawDefinition:t}),{...R}}function VU(t){let{tournamentRecord:e,drawDefinition:r,structureId:n,event:o}=t,i=lt(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===tt&&S===1),u=n===c?.structureId,p=s.filter(({stage:h})=>h===at).map(Pr("structureId"));if(u&&!p.length)return{error:ty};let m=p.includes(n),d=QF({isQualifyingStructure:m,structure:a,...t});if(d?.error)return d;let{structureIdsToRemove:l,relatedStructureIdsMap:f}=JF({qualifyingStructureIds:p,isQualifyingStructure:m,isMainStageSequence1:u,mainStageSequence1:c,drawDefinition:r,structureId:n}),{removedMatchUpIds:g,removedStructureIds:I}=ZF({relatedStructureIdsMap:f,qualifyingStructureIds:p,isMainStageSequence1:u,mainStageSequence1:c,drawDefinition:r,structureIdsToRemove:l,structureId:n});if(XF({removedMatchUpIds:g,drawDefinition:r}),u){let h=(c.matchUps??[])?.map(Pr("matchUpId"));g.push(...h),c.positionAssignments=[],c.seedAssignments=[],c.matchUps=[],c.extensions&&(c.extensions=[])}return m&&Kh({drawDefinition:r}),wn({tournamentId:e?.tournamentId,matchUpIds:g,action:"removeStructure",eventId:o?.eventId,drawDefinition:r}),bt({drawDefinition:r,eventId:o?.eventId}),{...R,removedMatchUpIds:g,removedStructureIds:I}}function QF({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})=>Ie({score:p}))){let p=Pt({tournamentRecord:e,drawDefinition:r,structure:o,event:i})?.appliedPolicies;if(!(s??p?.[vn]?.allowDeletionWithScoresPresent?.structures))return{error:Ku}}return{...R}}function XF({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 JF({qualifyingStructureIds:t,isQualifyingStructure:e,isMainStageSequence1:r,mainStageSequence1:n,drawDefinition:o,structureId:i}){let a=(o.structures??[]).map(Pr("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 ZF({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(...rG({idBeingRemoved:u,drawDefinition:o}));let p=eG({qualifyingStructureIds:e,isMainStageSequence1:r,idBeingRemoved:u,drawDefinition:o,structureId:s});a.push(...p.removedStructureIds);let m=tG({relatedStructureIdsMap:t,mainStageSequence1:n,idBeingRemoved:u,structureId:s});m?.length&&i.push(...m)}return{removedMatchUpIds:c,removedStructureIds:a}}function tG({idBeingRemoved:t,relatedStructureIdsMap:e,mainStageSequence1:r,structureId:n}){return t&&e.get(t)?.filter(o=>o!==r?.structureId||n===r.structureId)}function eG({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 rG({idBeingRemoved:t,drawDefinition:e}){let{structure:r}=st({structureId:t,drawDefinition:e}),n=At({structure:r}).matchUps;return Dm(n)}function yp({stageSequence:t=1,drawDefinition:e,drawSize:r,stage:n}){if(!e)return{error:X};if(!Cf({drawDefinition:e,stage:n}))return{error:Di};let o=CR({drawDefinition:e,stage:n}),{qualifiersCount:i}=cs({drawDefinition:e,stageSequence:t,stage:n}),s=o+i;if(r<s)return{error:uI};let{entryProfile:a}=Ef({attributes:[{[n]:{drawSize:r}}],drawDefinition:e});return bt({drawDefinition:e}),{...R,entryProfile:a}}function zh({qualifiersCount:t=0,drawDefinition:e,stage:r}){return e?Cf({drawDefinition:e,stage:r})?r!==tt?{error:uI,info:"qualifiersCount can only be set for main stage"}:(Ef({attributes:[{[r]:{qualifiersCount:t}}],drawDefinition:e}),bt({drawDefinition:e}),{...R}):{error:Di}:{error:X}}function nO({drawDefinition:t,drawSize:e}){if(!t)return{error:X};let r=yp({stage:Be,stageSequence:1,drawDefinition:t,drawSize:e});return r.error?r:(bt({drawDefinition:t}),{...R})}function BU(t){return nO(t)}function HU({tournamentRecord:t,drawDefinition:e,participantId:r,structureId:n}){let o="removeSeededParticipant";if(!t)return{error:W};if(!e)return{error:X};let i=(e.structures??[]).find(a=>a.structureId===n);return i?!i.stage||![tt,at].includes(i.stage)||i.stage===tt&&i.stageSequence!==1?_({result:{error:Pi},stack:o}):i.seedAssignments?.find(a=>a.participantId===r)?{...R}:_({info:"participant not seeded",result:{error:Ke},context:{participantId:r}}):_({result:{error:Lt},stack:o})}function Na({targetEntryRound:t=1,finishingPositions:e,sourceRoundNumber:r,sourceStructureId:n,targetStructureId:o,linkType:i=oo}){return!n||!o?{error:hr}:{link:rt({linkType:i,source:{roundNumber:r,structureId:n,finishingPositions:e},target:{feedProfile:Qr,roundNumber:t,structureId:o}})}}function od({roundPosition:t,roundNumber:e,idPrefix:r,uuids:n}){return r?`${r}-${e}-${t}`:n?.pop()||Mt()}function Ep({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=od({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 fn({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&&(!Tn(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(!Tn(a)&&!p)return{matchUps:[],roundsCount:0};let m=Z(1,a+1).map(I=>({drawPosition:I})),d,l=[],f=1;for({roundNodes:d,matchUps:l}=Ep({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}=Ep({nodes:d,matchUpType:o,roundNumber:f,idPrefix:s,matchUps:l,isMock:c,uuids:u}),f++;let g=f-1;return l=ha({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 id(t){let e="generateQualifyingStructure";if(!t.drawDefinition)return _({result:{error:X},stack:e});if(t.drawSize&&!ft(t.drawSize)||t.participantsCount&&!ft(t.participantsCount)||t.qualifyingPositions&&!ft(t.qualifyingPositions))return _({result:{error:G},stack:e});let r=t.drawSize??am(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:ja},context:{drawSize:r},stack:e});if(o&&o>=t.drawSize)return _({result:{error:G},context:{drawSize:r,qualifyingPositions:o},stack:e});let h,S,T,A,D=0,y,E=1,{structureProfiles:U}=gu({drawDefinition:c}),M=U[i];if(!M)return _({result:{error:Lt},context:{targetStructureId:i},stack:e});let P=c.matchUpType,N=d?`${d}-`:"",C=M.stage===at,O=a?.[ua]?.namingConventions?.pre??QR[ua]?.namingConventions?.pre,b=C&&O?`${O}-`:"",x=p??(N?`${b}${Ye(at)} ${N}`:`${b}${Ye(at)}`);if(l===dn){let{maxRoundNumber:L,structures:v,groupCount:B}=Da({structureName:p??x,structureId:m??I?.pop(),stage:at,structureOptions:s,appliedPolicies:a,stageSequence:E,matchUpType:P,roundTarget:d,idPrefix:f,drawSize:r,isMock:g,uuids:I});D=B,h=L,T=v[0],y=[1]}else({drawSize:r,matchUps:A,roundLimit:h,roundsCount:S}=fn({qualifyingRoundNumber:n,qualifyingPositions:o,matchUpType:P,idPrefix:f,drawSize:r,isMock:g,uuids:I})),h||(h=S),T=en({structureName:p??x,structureId:m??I?.pop(),qualifyingRoundNumber:h,stage:at,matchUpFormat:u,stageSequence:E,matchUpType:P,roundLimit:h,matchUps:A}),d&&St({extension:{name:mn,value:d},element:T}),D=A?.filter(L=>L.roundNumber===h)?.length;let w=l===dn?jn:oo,F=T&&h&&Na({sourceStructureId:T.structureId,sourceRoundNumber:h,targetStructureId:i,finishingPositions:y,linkType:w})?.link;return{qualifyingDrawPositionsCount:r,qualifiersCount:D,...R,structure:T,link:F}}function WU(t){let e=t.tournamentRecord;if(!e)return{error:W};let r=nG(t);if(r.error)return r;let{qualifyingRoundNumber:n,qualifyingPositions:o,targetStructureId:i,drawDefinition:s,structureName:a,matchUpType:c,drawSize:u,drawType:p}=t,d={itemType:"addQualifyingStructures",itemValue:rt({drawId:s.drawId,qualifyingRoundNumber:n,qualifyingPositions:o,targetStructureId:i,structureName:a,matchUpType:c,drawSize:u,drawType:p})};return Gi({tournamentRecord:e,timeItem:d}),r}function nG(t){if(!t.drawDefinition)return{error:X};if(!t.targetStructureId)return{error:hr};let e=id(t);if(e.error)return e;let{structure:r,link:n}=e;return!r||!n?{error:G}:Zf({tournamentRecord:t.tournamentRecord,drawDefinition:t.drawDefinition,structure:r,link:n})}function oO({includeMatchUpType:t,drawPosition:e,roundNumber:r,matchUpType:n,idPrefix:o,matchUps:i,isMock:s,uuids:a,nodes:c,fed:u}){let p=c.length,m=e?e-p:void 0,d=Z(0,p).map(g=>m?m+g:void 0),l=[];for(let g=0;g<p;g++){let I=d.shift(),h={drawPosition:I,fed:u+1,feed:!0},S=c[g];S.roundNumber=r-1;let T=od({roundPosition:S.roundPosition,roundNumber:r,idPrefix:o,uuids:a}),A={roundPosition:S.roundPosition,drawPositions:[I],matchUpStatus:zt,roundNumber:r,matchUpId:T};t&&(A.matchUpType=n),s&&(A.isMock=!0),i.push(A);let D={children:[S,h]};l.push(D)}let f=e?e-p:void 0;return{roundNodes:l,matchUps:i,drawPosition:f}}function Zo(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=oG({drawSize:i}),h=I.length,S=0;if(r?.length)S=r.reduce((L,v)=>L+v,0);else if(e){let L=e-i;r=I.filter(v=>v<=L?(L-=v,!0):!1),S=r.reduce((v,B)=>v+B,0),n=r.length}else o>=h?n=0:u&&(n=h-u,o=0),r=I.filter((L,v)=>u&&!n||n&&v>=o+n||v<o?0:L),S=r.reduce((L,v)=>L+v,0),n=r.length;let T=[...I,...r].sort((L,v)=>v-L),A=T.length,y=[...(c??[]).map(L=>L-1),...(s??[]).map(L=>A-L)].map(L=>T[L]).reduce((L,v)=>L+v,0);S=S-y;let E=0,U=[],M,P=1,C=Z(0,i).map((L,v)=>({drawPosition:v+1+S})),O=S+1;for(let L of I){if({roundNodes:M,matchUps:U}=Ep({matchUpType:m,roundNumber:P,idPrefix:d,matchUps:U,isMock:l,nodes:C,uuids:f}),P++,r.includes(L)){let v=dr(r)[L],B=Z(0,v),H=A+1-P,j=s?.includes(H)??c?.includes(P);B.forEach(()=>{({roundNodes:M,matchUps:U,drawPosition:O}=oO({drawPosition:!j&&O||void 0,nodes:M,matchUpType:m,roundNumber:P,idPrefix:d,matchUps:U,isMock:l,uuids:f,fed:E})),P++,E+=1})}C=M}A!==P-1&&console.log("ERROR");let b=i-S;U=ha({finishingPositionOffset:p?b:a,positionsFed:S,roundsCount:A,matchUps:U,fmlc:g});let w=M?.length?M[0]:M;return w&&(w.roundNumber=P-1,w.matchUps=U),{draw:w,matchUps:U,roundsCount:A};function F(L){let v=cm(L);return v>L?v/2:v}}function oG({drawSize:t}){let e=Math.ceil(Math.log(t)/Math.log(2));return Z(0,e).reverse().map(n=>Math.pow(2,n))}function Tc(t){let{finishingPositionOffset:e=0,addNameBaseToAttributeName:r,playoffStructureNameBase:n,finishingPositionNaming:o,finishingPositionLimit:i,playoffAttributes:s,stageSequence:a=1,exitProfile:c="0",exitProfileLimit:u,roundOffsetLimit:p,roundOffset:m=0,drawDefinition:d,staggeredEntry:l,sequenceLimit:f,stage:g=tt,drawSize:I,idPrefix:h,isMock:S,uuids:T}=t;if(!(!s||!u||s?.[c])||I<2||f&&a>f)return{};let D=[],y=[],E=[],U=t.matchUpType??d?.matchUpType,M=e+1,P=e+I,N=`${M}-${P}`,C=s?.[c],O=n&&`${n} `||"",b=s?.[N]??o?.[N],x=t.structureName||b?.name||C?.name&&(r?`${O}${C?.name}`:C.name)||`${O}${N}`,w=b?.abbreviation??C?.abbreviation,F=t.structureId??C?.structureId??T?.pop(),L={idPrefix:h&&`${h}-${x}-RP`,finishingPositionOffset:e,matchUpType:U,drawSize:I,isMock:S,uuids:T},{matchUps:v}=l?Zo(L):fn(L),B=en({structureAbbreviation:w,stageSequence:a,structureName:x,matchUpType:U,roundOffset:m,structureId:F,matchUps:v,stage:g});D.push(...v),y.push(B);let H=Math.ceil(Math.log(I)/Math.log(2)),j=p?Math.min(p-m,H):!i||M<i?H:0;return I>2&&Z(1,j+1).forEach(Y=>V(Y)),{structureId:B.structureId,matchUps:D,structureName:x,structures:y,links:E,...R};function V(Y){let $=I/Math.pow(2,Y);if($<2)return;let k=I/Math.pow(2,Y)+e;if(i&&k+1>i)return;let{structures:K,structureId:z,matchUps:q,links:nt}=Tc({finishingPositionOffset:k,exitProfile:`${c}-${Y}`,roundOffset:m+Y,stageSequence:a+1,drawSize:$,addNameBaseToAttributeName:r,playoffStructureNameBase:n,finishingPositionNaming:o,finishingPositionLimit:i,playoffAttributes:s,exitProfileLimit:u,roundOffsetLimit:p,drawDefinition:d,sequenceLimit:f,matchUpType:U,idPrefix:h,uuids:T,stage:g});if(B.structureId&&z){let Q={linkType:Yn,source:{roundNumber:Y,structureId:B.structureId},target:{roundNumber:1,feedProfile:sn,structureId:z}};nt&&B&&nt.push(Q),nt?.length&&E.push(...nt)}return K?.length&&y.push(...K),q?.length&&D.push(...q),{structureId:z,childLinks:nt,structures:y}}}function sd({drawDefinition:t,matchUpsMap:e,structureId:r}){let n=st({drawDefinition:t,structureId:r});if(n.error)return _({result:n});let{matchUps:o}=At({structure:n.structure,matchUpsMap:e});return{...He({matchUps:o}),matchUps:o,matchUpsMap:e}}function jU({finishingPositions:t,drawDefinition:e,structureId:r}){let{roundProfile:n}=sd({drawDefinition:e,structureId:r});return(n&&Object.keys(n))?.reduce((i,s)=>(iO(n?.[s]).forEach(c=>{t.forEach(u=>{iG({position:u,rangeDefinition:c})&&(i[u]={roundNumber:s})})}),i),{})}function iG({position:t,rangeDefinition:e}){if(!Array.isArray(e)||e.reduce((i,s)=>i||isNaN(s),!1))return!1;let[r,n]=e;return Z(r,(n||r)+1).includes(t)}function iO(t){return[pt(t?.finishingPositionRange?.loser||[]),pt(t?.finishingPositionRange?.winner||[])]}function sO(t){return iO(t).map(e=>Z(e[0],e[1]&&e[1]+1||e[0]+1))}function Ac({drawDefinition:t,structureIds:e,matchUpsMap:r}){if(e&&!Array.isArray(e))return{error:G,context:{structureIds:e}};if(!t)return{error:X};e=e??(t.structures??[]).filter(a=>a.stage!==at).map(({structureId:a})=>a);let n=e.map(a=>{let{roundProfile:c}=sd({drawDefinition:t,matchUpsMap:r,structureId:a});return(c&&Object.values(c))?.map(sO).flat()}).flat(),o=n.filter(a=>a?.length===1).sort(se).flat();return{positionsNotPlayedOff:pt(n.flat()).filter(a=>!o.includes(a)),positionsPlayedOff:o}}function Qh({excludeRoundNumbers:t=[],playoffPositions:e=[],drawDefinition:r,structureId:n}){if(!r)return{error:X};if(!n)return{error:hr};if(!e)return{error:et,info:"missing playoffPositions"};let o=Ac({drawDefinition:r});if(o.error)return o;let i=o.positionsPlayedOff,s=e.filter(S=>!i.includes(S)),a=jU({finishingPositions:s,drawDefinition:r,structureId:n}),u=Object.values(a).reduce((S,T)=>S.includes(T.roundNumber)?S:S.concat(T.roundNumber),[]).map(S=>ct(S)).filter(S=>!t.includes(S)),p=jU({finishingPositions:i,drawDefinition:r,structureId:n}),m=p?Object.values(p):[],d=p?m.reduce((S,T)=>S.includes(T.roundNumber)?S:S.concat(T.roundNumber),[]).map(S=>ct(S)):[],l=u.filter(S=>!d.includes(S)).sort(se),{roundProfile:f}=sd({drawDefinition:r,structureId:n}),g=l.map(S=>{let T=f?.[S].finishingPositionRange.loser,[A,D]=T??[0,0];return Z(A,(D||A)+1)}).flat().sort(se),{playoffRoundsRanges:I}=sG({playoffSourceRounds:l,roundProfile:f}),h=[...l,...d];return{playoffPositionsReturned:g,playedOffSourceRounds:d,playoffRoundsRanges:I,playoffSourceRounds:l,sourceRounds:h,roundProfile:f}}function sG({playoffSourceRounds:t,roundProfile:e}){return{playoffRoundsRanges:t.map(n=>{let o=e[n].finishingPositionRange.loser,[i,s]=o,a=Z(i,(s||i)+1);return{finishingPositionRange:o.join("-"),finishingPositions:a,roundNumber:n}})}}function Iu({drawDefinition:t,structureId:e}){if(!t)return{error:X};let{matchUps:r,matchUpsMap:n}=rr({inContext:!0,drawDefinition:t}),{positionsNotPlayedOff:o,positionsPlayedOff:i}=Ac({drawDefinition:t,matchUpsMap:n}),{structures:s}=xn({drawDefinition:t}),a=s.filter(u=>!e&&u.stage!==Be||u.structureId===e),c={};for(let u of a){let p=u?.structureId,m=aG({playoffPositions:o,drawDefinition:t,structure:u,matchUps:r}),{error:d,...l}=m;if(d)return m;c[p]={structureId:p,...l}}return e?{positionsPlayedOff:i,...c[e]}:{availablePlayoffProfiles:Object.values(c),availablePlayoffRounds:Object.values(c),positionsPlayedOff:i}}function aG({playoffPositions:t,drawDefinition:e,structure:r,matchUps:n}){let o=r?.structureId,{links:i}=ks({drawDefinition:e,structureId:o});if(r.structureType===Le||r.structures){let l=Nt({structure:r})?.positionAssignments?.length,f=r.structures.length,g=(l??0)/f,I=i.source?.flatMap(({source:P})=>P?.finishingPositions||[])||[],h=Z(1,g+1).filter(P=>!I.includes(P)),S=n.find(P=>P.containerStructureId===o&&P.finishingPositionRange)?.finishingPositionRange?.winner||[0,1],T=i?.source.map(({target:P})=>P.structureId),{positionsPlayedOff:A=[],positionsNotPlayedOff:D=[]}=Ac({structureIds:T,drawDefinition:e}),y=[...A,...D],E=Z(S[0],S[1]+1).filter(P=>!y.includes(P)),U=Te(E,E.length/h.length),M=h.map((P,N)=>{let C=U[N],O=[Math.min(...C||[]),Math.max(...C||[])].join("-");return{finishingPosition:P,finishingPositions:C,finishingPositionRange:O}});return{positionsNotPlayedOff:E,playoffFinishingPositionRanges:M,finishingPositionsAvailable:h,finishingPositionsPlayedOff:I,positionsPlayedOff:A,groupCount:f,groupSize:g}}let s=i?.source?.filter(l=>l.linkCondition!==qn).map(l=>l.source?.roundNumber)||[],a=i?.source?.filter(l=>l.linkCondition===qn).map(l=>l.source?.roundNumber)||[],c=Qh({excludeRoundNumbers:s,playoffPositions:t,drawDefinition:e,structureId:o}),u=c?.playoffSourceRounds?[...c?.playoffSourceRounds||[]]:void 0,p=[...c?.playoffRoundsRanges||[]],{roundProfile:m,error:d}=c;for(let l of a){let f=i?.source.find(T=>T.source.roundNumber===l),g=f?.target.roundNumber,I=f?.target.structureId,h=n.filter(({roundNumber:T,structureId:A})=>A===I&&T===g),S=h.filter(({sides:T})=>T.find(A=>A.participantFed&&!A.participantId)).length;if(u&&S===h.length){u.push(l);let T=m?.[l]?.finishingPositionRange?.loser;if(T){let A=Math.min(...T),D=A+S,y=Z(A,D),E={finishingPositionRange:[A,D-1].join("-"),finishingPositions:y,roundNumber:l};p.push(E)}}}return u&&u.sort(se),p.sort((l,f)=>l.roundNumber-f.roundNumber),{playoffRounds:u,playoffRoundsRanges:p,error:d}}function aO({playoffGroups:t,drawDefinition:e,structureId:r}){if(!e)return{error:X};if(typeof r!="string"||!Array.isArray(t))return{error:G};let n=t.map(({finishingPositions:a})=>a).flat();return{positionRangeMap:Iu({drawDefinition:e,structureId:r}).playoffFinishingPositionRanges?.filter(a=>n.includes(a.finishingPosition))?.reduce((a,c)=>(a[c.finishingPosition]=c,a),{})}}function Xh(t){let{finishingPositionOffset:e=0,playoffAttributes:r,stageSequence:n=1,staggeredEntry:o,structureName:i,stage:s=tt,matchUpType:a,structureId:c,idPrefix:u,drawSize:p,isMock:m,uuids:d}=t,l={finishingPositionOffset:e,matchUpType:a,drawSize:p,idPrefix:u,isMock:m,uuids:d},{matchUps:f}=o?Zo(l):fn(l),g=en({structureName:i||r?.["0"]?.name||Ye(tt),structureId:c||d?.pop(),stageSequence:n,matchUpType:a,matchUps:f,stage:s}),I=[g],h=[];if(p>2){let S=p/2,{matchUps:T}=fn({finishingPositionOffset:e+S,idPrefix:u&&`${u}-c`,drawSize:S,matchUpType:a,isMock:m}),A=Ye(Ve),D=r?.["0-1"]?.name??t.consolationStructureName??(i?`${i} ${A}`:A),y=en({structureName:D,matchUps:T,structureId:d?.pop(),stage:Ve,stageSequence:1,matchUpType:a});I.push(y);let E={linkType:Yn,source:{roundNumber:1,structureId:g.structureId},target:{roundNumber:1,feedProfile:sn,structureId:y.structureId}};h.push(E)}return{...R,structures:I,links:h}}function Jh({consolationStructure:t,roundOffset:e=0,mainStructure:r,roundsCount:n,feedPolicy:o,fmlc:i}){let a=t.matchUps.reduce((p,m)=>(m.drawPositions||[]).filter(Boolean).length&&!p.includes(m.roundNumber)?p.concat(m.roundNumber):p,[]),c=o?.roundGroupedOrder||[],u=o?.roundFeedProfiles;return Z(1+e,n+1+e).map(p=>{let m=u&&u[p-1]?u[p-1]:p%2?sn:ai,d=p-e<=2?p-e:(p-e-2)*2+2,l={linkType:Yn,source:{roundNumber:p,structureId:r.structureId},target:{feedProfile:m,roundNumber:d,structureId:t.structureId}},f=c[p-1];return f&&(l.target.groupedOrder=f),yr()&&(l.source.structureName=r.structureName,l.target.structureName=t.structureName),p===2&&i&&(l.linkCondition=qn,l.target.feedProfile=sn),a.includes(d)?l:void 0}).filter(Boolean)}function Zh(t){let{playoffStructureNameBase:e,finishingPositionOffset:r,stageSequence:n=1,playoffAttributes:o,structureNameMap:i,staggeredEntry:s,stage:a=tt,matchUpType:c,structureId:u,drawSize:p,idPrefix:m,isMock:d,uuids:l}=t,f={finishingPositionOffset:r,matchUpType:c,drawSize:p,idPrefix:m,isMock:d,uuids:l},{matchUps:g,roundsCount:I}=s?Zo(f):fn(f),h=t.structureName??o?.["0"]?.name??Ye(tt),S=ps({structureId:u||l?.pop(),structureName:h,stageSequence:n,matchUpType:c,matchUps:g,stage:a}),T=[S],A=[];if(p>2){let E=[0,2].slice(0,p/16).map((U,M)=>{let P=M+1,{consolationStructure:N}=cG({idPrefix:m&&`${m}-c${M}`,structureId:l?.pop(),playoffStructureNameBase:e,playoffAttributes:o,structureNameMap:i,stageSequence:P,roundOffset:U,matchUpType:c,drawSize:p,isMock:d,index:M,uuids:l});T.push(N);let C=Jh({consolationStructure:N,roundsCount:2,mainStructure:S,roundOffset:U});return{consolationStructure:N,links:C}}).map(U=>U.links).flat();if(A.push(...E),p>=4&&p<=16||p>32){let{matchUps:U}=fn({idPrefix:m&&`${m}-p3t4`,finishingPositionOffset:2,drawSize:2,matchUpType:c,isMock:d}),M=o?.["3-4"]?.name??Ye(ce),P=i?.[M]||M,N=e?`${e} ${P}`:P,C=ps({structureId:l?.pop(),matchUps:U,stageSequence:2,stage:ce,structureName:N,matchUpType:c}),O={linkType:Yn,source:{roundNumber:I-1,structureId:S.structureId},target:{structureId:C.structureId,feedProfile:sn,roundNumber:1}};T.push(C),A.push(O)}}return{structures:T,links:A,...R}}function cG({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}=Zo({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:ps({matchUps:l,stage:Ve,structureName:S,stageSequence:e,matchUpType:i,structureId:s}),consolationRoundsCount:f}}function yc(t){let{finishingPositionOffset:e,stageSequence:r=1,playoffAttributes:n,feedsFromFinal:o,staggeredEntry:i,structureName:s,stage:a=tt,structureId:c,matchUpType:u,skipRounds:p,feedRounds:m,idPrefix:d,drawSize:l,isMock:f,uuids:g,fmlc:I}=t,h=t.feedPolicy||t.policyDefinitions?.[ec]||t.appliedPolicies?.[ec],S={finishingPositionOffset:e,matchUpType:u,skipRounds:p,drawSize:l,idPrefix:d,isMock:f,uuids:g},{matchUps:T}=i?Zo(S):fn(S),A=en({structureName:s||n?.["0"]?.name||Ye(tt),structureId:c||g?.pop(),stageSequence:r,matchUpType:u,matchUps:T,stage:a}),D=[A],y=[],E=l/2,{matchUps:U,roundsCount:M}=Zo({finishingPositionOffset:E,idPrefix:d&&`${d}-c`,isConsolation:!0,feedsFromFinal:o,baseDrawSize:E,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,C=en({matchUps:U,structureId:g?.pop(),stage:Ve,stageSequence:1,structureName:N,matchUpType:u});D.push(C);let O=Jh({consolationStructure:C,mainStructure:A,roundsCount:M,feedPolicy:h,fmlc:I});y.push(...O)}return{...R,structures:D,links:y}}function eS({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?.[ec];let f="processPlayoffGroups",g=0,I=[],h=[],S=[],{error:T,positionRangeMap:A}=aO({structureId:n,drawDefinition:s,playoffGroups:a});if(T)return _({result:{error:T},stack:f});if(!(!A||a?.every(y=>{let{finishingPositions:E=[]}=y;if(!E.length)return!1;let U=[...E].sort(se).map((M,P)=>(E[P+1]||M)-M).every(M=>M<2);return(!t||U)&&E.every(M=>A[M])})))return _({context:{validFinishingPositions:Object.values(A)},result:{error:G},stack:f});for(let y of a){let E=y.finishingPositions,U=A&&E.map(F=>A[F]?.finishingPositions).flat(),M=p*E.length,P=qi(M),N=P===2&&io||y.drawType||io;U&&(g=Math.min(...U)-1);let C=U&&`${Math.min(...U)}-${Math.max(...U)}`,O=y.structureName||C&&y.playoffAttributes?.[C]?.name||y.playoffAttributes?.["0"]?.name,x={...{addNameBaseToAttributeName:y.addNameBaseToAttributeName,playoffStructureNameBase:y.playoffStructureNameBase,finishingPositionNaming:y.finishingPositionNaming,finishingPositionLimit:y.finishingPositionLimit,structureId:y.structureId??l?.pop(),playoffAttributes:y.playoffAttributes,structureNameMap:y.structureNameMap,sequenceLimit:y.sequenceLimit,structureName:O},idPrefix:m&&`${m}-po`,appliedPolicies:o,finishingPositionOffset:g,stage:ce,stageSequence:i,matchUpType:c,drawSize:P,isMock:d,uuids:l},w=({playoffStructures:F,playoffLinks:L})=>{let[v]=F,B=tS({playoffStructureId:v.structureId,finishingPositions:E,sourceStructureId:n});S.push(B),S.push(...L),h.push(...F),I.push({structureId:v.structureId,finishingPositions:E}),g+=M};if(N===io){let{matchUps:F}=fn({finishingPositionLimit:g+M,idPrefix:m&&`${m}-po`,finishingPositionOffset:g,matchUpType:c,drawSize:P,isMock:d,uuids:l}),L=en({structureId:y.structureId??l?.pop(),matchUpFormat:e,stage:ce,structureName:O,stageSequence:i,matchUps:F});h.push(L);let v=tS({playoffStructureId:L.structureId,finishingPositions:E,sourceStructureId:n});S.push(v),g+=M,I.push({structureId:L.structureId,finishingPositions:E})}else if([Qc,Xc,ce].includes(N)){let F={playoffAttributes:y.playoffAttributes??r,playoffStructureNameBase:y.playoffStructureNameBase,structureId:y.structureId??l?.pop(),structureName:y.structureName,idPrefix:m&&`${m}-po`,addNameBaseToAttributeName:!0,finishingPositionOffset:g,stage:ce,roundOffset:0,stageSequence:i,drawSize:P,isMock:d,uuids:l};N===Qc?Object.assign(F,{playoffAttributes:y?.playoffAttributes??r??of,roundOffsetLimit:3}):N===Xc&&Object.assign(F,{playoffAttributes:y?.playoffAttributes??r??sf,roundOffsetLimit:2});let L=Tc(F);if(L.error)return L;if(L.links?.length&&S.push(...L.links),L.structures?.length&&h.push(...L.structures),h.sort(ci),L.structureId){let v=tS({playoffStructureId:L.structureId,finishingPositions:E,sourceStructureId:n});S.push(v),I.push({structureId:L.structureId,finishingPositions:E})}g+=M}else if([Zc,ap,bm,Rm,Cm,Om].includes(N)){let F=[l?.pop(),l?.pop()],L={playoffStructureNameBase:y.playoffStructureNameBase,structureId:y.structureId??l?.pop(),playoffAttributes:y.playoffAttributes,idPrefix:m&&`${m}-po`,finishingPositionOffset:g,uuids:F,stage:ce,structureName:O,matchUpType:c,feedPolicy:u,drawSize:P,isMock:d},v={[Zc]:{fmlc:!0,feedRounds:1},[Om]:{feedRounds:1},[bm]:{feedsFromFinal:3},[Rm]:{feedsFromFinal:2},[Cm]:{feedsFromFinal:1}};Object.assign(L,v[N]||{});let{structures:B,links:H}=yc(L),[j]=B,V=tS({playoffStructureId:j.structureId,finishingPositions:E,sourceStructureId:n});S.push(V),S.push(...H),h.push(...B),I.push({structureId:j.structureId,finishingPositions:E}),g+=M}else if([dn].includes(N)){let{structures:F,links:L}=Da({...x,structureOptions:y.structureOptions||{groupSize:4}});w({playoffStructures:F,playoffLinks:L})}else if([sp].includes(N)){let{structures:F,links:L}=Xh(x);w({playoffStructures:F,playoffLinks:L})}else if([SR].includes(N)){let{structures:F,links:L}=Zh(x);w({playoffStructures:F,playoffLinks:L})}else if([an].includes(N)){let F=en({structureId:y.structureId??l?.pop(),structureName:y.structureName,finishingPosition:Gm,stage:ce,stageSequence:i,matchUps:[]});w({playoffStructures:[F],playoffLinks:[]})}}return{finishingPositionTargets:I,positionRangeMap:A,structures:h,links:S}}function tS({playoffStructureId:t,finishingPositions:e,sourceStructureId:r}){return{linkType:jn,source:{structureId:r,finishingPositions:e},target:{structureId:t,feedProfile:Qr,roundNumber:1}}}function Ma({matchUp:t,tieFormat:e,isMock:r,uuids:n}){let{collectionDefinitions:o}=e??{};return{tieMatchUps:(o??[]).map(s=>hu({matchUp:t,collectionDefinition:s,uuids:n,isMock:r})).filter(Boolean).flat()}}function hu({collectionPositionOffset:t=0,collectionDefinition:e,matchUpsLimit:r,matchUp:n,isMock:o,uuids:i}){let{matchUpCount:s,matchUpType:a,collectionId:c,processCodes:u}=e||{},p=r??s??0,m=d=>{if(!o&&!n?.isMock)return i?.pop()??Mt();let l=e?.collectionId;return i?.pop()??`${n?.matchUpId}-${l}-TMU-${d+1}`};return Z(0,p).map(d=>{let l=t+d+1;return{sides:[{sideNumber:1},{sideNumber:2}],matchUpId:m(d),matchUpStatus:zt,collectionPosition:l,collectionId:c,processCodes:u,matchUpType:a,isMock:o}})}function cO(t){let e="generateAndPopulateRRplayoffStructures";if(!t.playoffGroups)return _({result:{error:et},info:"playoffGroups required",stack:e});let{sourceStructureId:r,requireSequential:n,tournamentRecord:o,drawDefinition:i,playoffGroups:s,groupCount:a,groupSize:c,event:u}=t,{structures:p=[],links:m=[],finishingPositionTargets:d,positionRangeMap:l,error:f}=eS({requireSequential:n,sourceStructureId:r,playoffGroups:s,groupCount:a,groupSize:c,...t});if(f)return{error:f};let g=d?.map(({finishingPositions:U})=>U).flat().map(U=>l[U].finishingPositions).flat();i.structures.push(...p),i.links.push(...m);let{matchUps:I,matchUpsMap:h}=re({inContext:!0,drawDefinition:i}),S=p.map(({structureId:U})=>U),T=I?.filter(({structureId:U})=>S.includes(U)).map(fe),A=h?.drawMatchUps?.filter(({matchUpId:U})=>T?.includes(U));if(A?.length){let U=je({drawDefinition:i,event:u})?.tieFormat;U&&A.forEach(M=>{let{tieMatchUps:P}=Ma({isMock:t.isMock,tieFormat:U,matchUp:M});Object.assign(M,{tieMatchUps:P,matchUpType:ln})})}let{positionAssignments:D}=Nt({structureId:r,drawDefinition:i}),y={};D?.forEach(U=>{let N=mt({element:U,name:Ho})?.extension?.value?.groupOrder;N&&(y[N]||(y[N]=[]),y[N].push(U.participantId))});let E=Sc({provisionalPositioning:t.provisionalPositioning,structureId:r,applyPositioning:!0,event:t.event,tournamentRecord:o,drawDefinition:i});return E.error&&E.error?.code!==dl.code?_({result:E,stack:e}):{structures:p,links:m,positionsPlayedOff:g,drawDefinition:i,...R}}var un="SET3-S:6/TB7",uG="SET3-S:6NOAD",YU="SET3-S:6/TB7-F:TB10",pG="SET3-S:4/TB7",mG="SET3-S:4/TB5@3",dG="SET1-S:T20",lG="SET1-S:8/TB7",fG="SET1-S:8/TB7@7",uO={FORMAT_STANDARD:un,FORMAT_STANDARD_NOAD:uG,FORMAT_ATP_DOUBLES:YU,FORMAT_SHORT_SETS:pG,FORMAT_FAST4:mG,FORMAT_PRO_SET:lG,FORMAT_COLLEGE_PRO_SET:fG,TIMED20:dG};function eg({winningSide:t,matchUpFormat:e=un,matchUpStatus:r,tallyPolicy:n,score:o}){let i=[0,0],s=o?.sets,a=typeof t=="number"&&t-1,c=tr(e),u=qU(c?.bestOf??1);if(typeof a=="number"&&(r===Ot&&n?.setsCreditForDefaults||r===_t&&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===lr&&(+i[1-a]===u&&(i[1-a]-=1),n?.setsCreditForRetirements&&(i[a]=u)),i}function rS({matchUpFormat:t=un,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=tr(t),c=a?.bestOf??1,u=qU(c),p=a?.setFormat?.tiebreakAt||0,m=[[],[]];if(typeof s=="number"&&(r===Ot&&n?.gamesCreditForDefaults||r===_t&&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;pO(I)&&(m[0].push(ct(S||0)),m[1].push(ct(T||0))),h&&d.winningSide&&n?.gamesCreditForTiebreakSets!==!1&&m[d.winningSide-1].push(1)});if(r===lr&&typeof s=="number"){let d=i.length>u&&a?.finalSetFormat?"finalSetFormat":"setFormat",l=a?.[d];if(pO(l.based)){let f=l?.setTo||0,g=S=>{if(!(!a||S===""))return+S===p-1||+S===p?ct(p||0)+1:+S<p?f:p},I=eg({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 nS({matchUpFormat:t,score:e}){let r=t?tr(t):void 0,n=r?.bestOf??1,o=qU(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(mO(m)){let{side1Score:d,side2Score:l}=a;d&&(s[0]+=ct(d||0)),l&&(s[1]+=ct(l||0))}else a.side1TiebreakScore&&(s[0]+=ct(a.side1TiebreakScore||0)),a.side2TiebreakScore&&(s[1]+=ct(a.side2TiebreakScore||0)),(a.side1TiebreakScore||a.side2TiebreakScore)&&a.winningSide&&(i[a.winningSide-1]+=1)}),{pointsTally:s,tiebreaksTally:i}}function qU(t){return t&&Math.ceil(t/2)||1}function mO(t){return t==="P"}function pO(t){return!mO(t)}function dO({participantResults:t,matchUpFormat:e,tallyPolicy:r,perPlayer:n,totalSets:o}){let i=e&&tr(e)||{},s=i.bestOf,a=s&&Math.ceil(s/2)||1,c=i.setFormat?.setTo;Object.keys(t).forEach(u=>{let p=t[u].setsWon,m=t[u].setsLost,d=r?.groupTotalSetsPlayed?o:n*(a||0)||p+m,l=Math.round(p/d*1e3)/1e3;(l===1/0||isNaN(l))&&(l=d);let f=t[u].tieMatchUpsWon,g=t[u].tieMatchUpsLost,I=f+g,h=Math.round(f/I*1e3)/1e3;(h===1/0||isNaN(h))&&(h=f);let S=t[u].matchUpsWon,T=t[u].matchUpsLost,A=S+T,D=Math.round(S/A*1e3)/1e3;(D===1/0||isNaN(D))&&(D=S);let y=t[u].gamesWon||0,E=t[u].gamesLost||0,U=(n||0)*(a||0)*(c||0),M=Math.max(U,y+E),P=Math.round(y/M*1e3)/1e3;(P===1/0||isNaN(P))&&(P=0);let N=Math.round(t[u].pointsWon/t[u].pointsLost*1e3)/1e3;(N===1/0||isNaN(N))&&(N=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=y,t[u].gamesLost=E,t[u].gamesPct=P,t[u].pointsPct=N,t[u].result=`${t[u].matchUpsWon}/${t[u].matchUpsLost}`})}function Su({participantIds:t,matchUpFormat:e,tallyPolicy:r,perPlayer:n,matchUps:o}){let i={},s=r?.excludeMatchUpStatuses||[],a=o?.filter(p=>(p.tieMatchUps||!s.includes(p.matchUpStatus))&&(!t?.length||jt(t,[ad(p,0),ad(p,1)]).length===2)),u=a?.flatMap(({score:p,tieMatchUps:m})=>m?m.filter(({matchUpStatus:d})=>!s.includes(d)).flatMap(({score:d})=>d?.sets?.length??0):p?.sets?.length??0)?.reduce((p,m)=>p+m,0);for(let p of a??[]){let{matchUpStatus:m,tieMatchUps:d,tieFormat:l,score:f,winningSide:g,sides:I}=p,h=l&&p._disableAutoCalc&&l.collectionDefinitions.every(({scoreValue:A})=>A),S=g&&gG(p),T=g&&IG(p);if(!S&&!T)if(m&&ae.includes(m)){let A=ad(p,0),D=ad(p,1);A&&(Ec(i,A),i[A].matchUpsCancelled+=1),D&&(Ec(i,D),i[D].matchUpsCancelled+=1)}else if(d?.length){n=0;for(let A of d){if(A.winningSide){let D=I?.find(({sideNumber:E})=>E===A.winningSide)?.participantId,y=I?.find(({sideNumber:E})=>E===A.winningSide)?.participantId;D&&y&&(Ec(i,D),Ec(i,y),i[D].tieMatchUpsWon+=1,i[y].tieMatchUpsLost+=1,ie(Xt)(A.matchUpType)?(i[D].tieSinglesWon+=1,i[y].tieSinglesLost+=1):ie(Gt)(A.matchUpType)&&(i[D].tieDoublesWon+=1,i[y].tieDoublesLost+=1))}lO({score:A.score,manualGamesOverride:h,participantResults:i,sides:I})}}else lO({manualGamesOverride:h,participantResults:i,score:f,sides:I});else if(Ec(i,S),Ec(i,T),d?.length){n=0;for(let A of d){let{matchUpType:D}=A,y=ie(Gt)(D),E=ie(Xt)(D);A.winningSide&&(A.winningSide===g?(S&&(i[S].tieMatchUpsWon+=1,E&&(i[S].tieSinglesWon+=1),y&&(i[S].tieDoublesWon+=1)),T&&(i[T].tieMatchUpsLost+=1,E&&(i[T].tieSinglesLost+=1),y&&(i[T].tieDoublesLost+=1))):A.winningSide!==g&&(T&&(i[T].tieMatchUpsWon+=1,E&&(i[T].tieSinglesWon+=1),y&&(i[T].tieDoublesWon+=1)),S&&(i[S].tieMatchUpsLost+=1,E&&(i[S].tieSinglesLost+=1),y&&(i[S].tieDoublesLost+=1)))),fO({matchUpFormat:A.matchUpFormat,matchUpStatus:A.matchUpStatus,score:A.score,winningParticipantId:S,losingParticipantId:T,participantResults:i,isTieMatchUp:!0,manualGamesOverride:h,tallyPolicy:r,winningSide:g})}gO({winningParticipantId:S,losingParticipantId:T,participantResults:i,matchUpStatus:m})}else fO({matchUpFormat:p.matchUpFormat??e,isTieMatchUp:void 0,winningParticipantId:S,manualGamesOverride:h,losingParticipantId:T,participantResults:i,matchUpStatus:m,tallyPolicy:r,winningSide:g,score:f});if(h){let A=I?.find(({sideNumber:U})=>U===1)?.participantId,D=I?.find(({sideNumber:U})=>U===2)?.participantId;Ec(i,A),Ec(i,D);let y=f?.sets?.reduce((U,M)=>U+(M?.side1Score??0),0),E=f?.sets?.reduce((U,M)=>U+(M.side2Score??0),0);A&&(i[A].gamesWon+=y,i[A].gamesLost+=E),D&&(i[D].gamesWon+=E,i[D].gamesLost+=y)}}return dO({participantResults:i,matchUpFormat:e,tallyPolicy:r,perPlayer:n,totalSets:u}),{participantResults:i}}function gG(t){let e=t.winningSide-1;return ad(t,e)}function IG(t){let e=1-(t.winningSide-1);return ad(t,e)}function ad(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 Ec(t,e){e&&!t[e]&&(t[e]={allDefaults:0,defaults:0,defeats:[],gamesLost:0,gamesWon:0,matchUpsCancelled:0,matchUpsLost:0,matchUpsWon:0,pointsLost:0,pointsWon:0,retirements:0,setsLost:0,setsWon:0,tieSinglesWon:0,tieSinglesLost:0,tieDoublesWon:0,tieDoublesLost:0,tieMatchUpsLost:0,tieMatchUpsWon:0,victories:[],walkovers:0})}function lO({manualGamesOverride:t,participantResults:e,score:r,sides:n}){let{sets:o}=r||{},i=[[],[]],s=[0,0];for(let c of o||[]){let{winningSide:u,side1Score:p,side2Score:m}=c;u&&(s[u-1]+=1),i[0].push(ct(p||0)),i[1].push(ct(m||0))}let a=[i[0].reduce((c,u)=>c+u,0),i[1].reduce((c,u)=>c+u,0)];n.forEach((c,u)=>{let{participantId:p}=c;p&&(Ec(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 fO({winningParticipantId:t,losingParticipantId:e,participantResults:r,manualGamesOverride:n,matchUpFormat:o,matchUpStatus:i,isTieMatchUp:s,tallyPolicy:a,winningSide:c,score:u}){let p=c&&c-1,m=1-p;s||gO({winningParticipantId:t,losingParticipantId:e,participantResults:r,matchUpStatus:i});let d=eg({matchUpStatus:i,matchUpFormat:o,tallyPolicy:a,winningSide:c,score:u}),l=rS({matchUpStatus:i,matchUpFormat:o,tallyPolicy:a,winningSide:c,score:u}),{pointsTally:f}=nS({score:u,matchUpFormat:o});t&&(r[t].setsWon+=d[p],r[t].setsLost+=d[m],n||(r[t].gamesWon+=l[p],r[t].gamesLost+=l[m]),r[t].pointsWon+=f[p],r[t].pointsLost+=f[m]),e&&(r[e].setsWon+=d[m],r[e].setsLost+=d[p],n||(r[e].gamesWon+=l[m],r[e].gamesLost+=l[p]),r[e].pointsWon+=f[m],r[e].pointsLost+=f[p])}function gO({winningParticipantId:t,losingParticipantId:e,participantResults:r,matchUpStatus:n}){e&&(n===_t&&(r[e].walkovers+=1),n===Ot&&(r[e].defaults+=1),n===lr&&(r[e].retirements+=1),[Ot,lr,_t].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 IO({matchUps:t,order:e,report:r}){let n={};t.forEach(({sides:i})=>{i.forEach(s=>{s.participantId&&s.participant&&(n[s.participantId]=s.participant.participantName)})});let o=[];return Array.isArray(r)&&r.forEach((i,s)=>{if(i.excludedDirectives?.length){let a=i.excludedDirectives.map(({attribute:p})=>p).join(", "),c=`${a.length} directives were excluded due to participants limit}`;o.push(c);let u=`Excluded: ${a}`;o.push(u)}else{let a=(l,f)=>parseFloat(i.reversed?l:f)-parseFloat(i.reversed?f:l),c=i.groups?Object.values(i.groups).flat(1/0).length:i.participantIds?.length??0,u=l=>{l.groups&&Object.keys(l.groups).sort(a).forEach(f=>{let g=l.groups[f].map(h=>n[h]).join(", "),I=`${f} ${l.attribute}: ${g}`;o.push(I)})},p=i.reversed?" in reverse order":"",m=i.groups?"grouped":"separated",d=`Step ${s+1}: ${c} particiants were ${m}${p} by ${i.attribute}`;if(o.push(d),i.idsFilter){let l=`${i.attribute} was calculated considering ONLY TIED PARTICIPANTS`;o.push(l)}u(i)}o.push("----------------------")}),o.push("Final Order:"),e.forEach(i=>{let{participantId:s,resolved:a}=i,c=i.groupOrder||i.provisionalOrder;o.push(`${c}: ${n[s]} => resolved: ${!!a}`)}),o.join(`\r
|
|
4
4
|
`)}function $U({participantResults:t,participantIds:e,attribute:r}){return KU({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 KU(t){return(t.participantIds||Object.keys(t.participantResults)).reduce((r,n,o)=>(r.push({participantId:n,i:o,results:t.participantResults[n]}),r),[])}var hG=[{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}],zU={matchUpsPct:20,tieMatchUpsPct:16,setsPct:12,gamesPct:8,pointsPct:4};function QU(t){let{requireCompletion:e=!0,participantResults:r,subOrderMap:n,tallyPolicy:o}=t,i=[];if(e&&!SG(t))return{};let s=["tieMatchUpsWon","tieSinglesWon","tieDoublesWon","matchUpsWon","pointsWon","gamesWon","setsWon","gamesPct","setsPct","pointsPct","matchUpsPct"].includes(o?.groupOrderKey)?o.groupOrderKey:"matchUpsWon",a=$U({participantResults:r,attribute:s});i.push({attribute:s,groups:a});let c=Object.keys(a).map(f=>parseFloat(f)).sort((f,g)=>g-f).map(f=>a[f]).map(f=>{let g=hO({participantIds:f,...t});return i.push(...g.report??[]),g.order}).flat(1/0),u=1,p;c.forEach((f,g)=>{g&&(f.resolved||p&&!f.resolved)&&(u+=1),p=f.resolved,f.resolved?(f.position=g+1,u=f.position):f.position=u});let m=c.map(({position:f})=>f),d=dr(m);return c.forEach(f=>{let{participantId:g,position:I}=f||{},h=r[g];f.GEMscore=l(h);let S=d[I];f?.position!==void 0&&(S>1&&(f.ties=S,n&&(f.subOrder=n[g])),f.rankOrder=I,f.groupOrder=I+(f.subOrder||1)-1)}),{groupOrder:c,report:i.flat(1/0).filter(Boolean)};function l(f){return(Array.isArray(o?.GEMscore)?Object.keys(zU).filter(h=>o.GEMscore.includes(h)):Object.keys(zU)).map(h=>(f[h]||0)*Math.pow(10,zU[h].toFixed(3))).reduce((h,S)=>h+S,0)}}function SG({participantResults:t,participantsCount:e}){let n=KU({participantResults:t}).filter(o=>e-1===o.results.matchUpsWon+o.results.matchUpsLost+o.results.matchUpsCancelled);return e===n.length}function TG({disableHeadToHead:t,participantIds:e,matchUpFormat:r,tallyPolicy:n,attribute:o,idsFilter:i,matchUps:s,reversed:a}){let{participantResults:c}=Su({participantIds:i&&e,matchUpFormat:r,tallyPolicy:n,matchUps:s}),u=$U({participantResults:c,participantIds:e,attribute:o}),p=[{attribute:o,reversed:a,groups:u,idsFilter:i}],m;return Object.keys(u).length>1&&e.length&&(m=Object.keys(u).map(d=>parseFloat(d)).sort((d,l)=>a?d-l:l-d).map(d=>u[d]).map(d=>{let l=hO({participantResults:c,disableHeadToHead:t,participantIds:d,matchUpFormat:r,tallyPolicy:n,matchUps:s});return p.push(...l.report??[]),l.order}).flat(1/0)),{order:m,report:p}}function hO({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=AG({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||hG).filter(m=>{let d=!(te(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=TG({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 AG({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 Ca({policyDefinitions:t,generateReport:e,matchUpFormat:r,matchUps:n=[],subOrderMap:o,perPlayer:i}){if(!n?.length||!Ur(n))return{error:Sn};let s=pt(n.map(({structureId:T})=>T));if(s.length!==1)return _({result:{error:G,info:"Maximum one structureId"},stack:"tallyParticipantResults",context:{structureIds:s}});let a=n.filter(T=>T&&T.matchUpStatus!==Dt),c=a.length&&pt(a.map(({drawPositions:T})=>T).flat()).length,u=a.filter(T=>is({matchUp:T})).length===a.length;u||(i=0);let p=n.every(({matchUpType:T,tieMatchUps:A})=>T===Bt&&A?.every(D=>is({matchUp:D}))),m=t?.[Jl],d=n.filter(T=>is({matchUp:T})||T.matchUpType===Bt),{participantResults:l}=Su({matchUps:d,matchUpFormat:r,tallyPolicy:m,perPlayer:i}),f,g,{groupOrder:I,report:h}=QU({matchUps:d,participantResults:l,participantsCount:c,matchUpFormat:r,tallyPolicy:m,subOrderMap:o});if(u&&I)f=h,g=I,I.forEach(T=>{let{participantId:A,groupOrder:D,rankOrder:y,subOrder:E,ties:U,GEMscore:M}=T,P=l[A];Object.assign(P,{groupOrder:D,rankOrder:y,GEMscore:M,subOrder:E,ties:U})});else{let{groupOrder:T,report:A}=QU({requireCompletion:!1,participantResults:l,participantsCount:c,matchUpFormat:r,tallyPolicy:m,subOrderMap:o,matchUps:n});f=A,g=T,T&&T.forEach(D=>{let{participantId:y,groupOrder:E,GEMscore:U}=D,M=l[y];Object.assign(M,{provisionalOrder:E,GEMscore:U})})}let S={completedTieMatchUps:p,readableReport:"",participantResults:l,bracketComplete:u,order:[],report:f};if((u||p)&&(S.order=g),e||yr({tally:!0})){let T=IO({matchUps:n,report:f,order:g});yr({tally:!0})&&console.log(T),S.readableReport=T}return S}function oS({positionAssignments:t}){let e=(t||[]).filter(Pr(Bn)).map(i=>{let{extension:s}=mt({element:i,name:nc}),a=ct(s?.value),c=!isNaN(a)&&a;return c&&{participantId:i.participantId,subOrder:c}}).filter(Boolean),r=e.map(({subOrder:i})=>i),n=dr(r);return{subOrderMap:Object.assign({},...e.filter(({subOrder:i})=>n[i]===1).map(({participantId:i,subOrder:s})=>({[i]:s})))}}function cd({positionAssignments:t,tournamentRecord:e,drawDefinition:r,matchUpFormat:n,matchUps:o,event:i}){if(!Ur(o))return{error:G};if(!t)return{error:G};let{policyDefinitions:s}=yo({policyTypes:[Jl],tournamentRecord:e,drawDefinition:r,event:i}),{subOrderMap:a}=oS({positionAssignments:t}),c=o.length?Ca({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:Ho};St({element:l,extension:g}),u[f].ties||or({element:l,name:nc})}else or({element:l,name:Ho}),or({element:l,name:nc})}),bt({drawDefinition:r}),{...R,participantResults:u,bracketComplete:p,report:m}}function iS({matchUps:t,matchUpId:e}){return{matchUp:(t||[]).find(n=>n.matchUpId===e)}}function xt({tournamentParticipants:t,afterRecoveryTimes:e,contextContent:r,contextProfile:n,drawDefinition:o,matchUpsMap:i,matchUpId:s,inContext:a,context:c,event:u}){if(!o)return{error:X};if(!s)return{error:ke};if(typeof s!="string")return{error:G};let{structures:p=[]}=xn({drawDefinition:o});n&&!r&&(r=Ln({contextProfile:n,drawDefinition:o}));for(let m of p){let{matchUps:d}=At({tournamentParticipants:t,afterRecoveryTimes:e,contextContent:r,drawDefinition:o,contextProfile:n,matchUpsMap:i,inContext:a,structure:m,context:c,event:u}),{matchUp:l}=iS({matchUps:d,matchUpId:s});if(l)return{matchUp:l,structure:m}}return{error:Oe}}function Up(t){return typeof t!="object"?{error:et}:typeof t.element!="object"?{error:G}:t.notes?typeof t.notes!="string"&&!t.notes?.testing?{error:G}:(Object.assign(t.element,{notes:t.notes}),{...R}):{error:et}}function XU(t){return typeof t!="object"?{error:et}:typeof t.element!="object"?{error:G}:(t.element.notes&&delete t.element.notes,{...R})}var Tu={matchUpStatus:zt,matchUpStatusCodes:[],score:{scoreStringSide1:"",scoreStringSide2:"",sets:void 0},matchUpFormat:void 0,winningSide:void 0};function Cn(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:Pt({policyTypes:[vn],tournamentRecord:a,drawDefinition:c,structure:o,event:l})?.appliedPolicies,S=n.matchUpType===Bt;if(S&&c){if(d&&n.matchUpId!==d){let M=xt({drawDefinition:c,matchUpId:d,event:l});if(!M.matchUp)return{error:Oe};({matchUp:n,structure:o}=M)}}else n.matchUpId!==d&&console.log("!!!!!");u&&[_t,ge].includes(u)||p?Object.assign(n,{...Tu}):g&&(n.score=g);let T=u&&n?.matchUpStatus===Ot&&u!==Ot;u&&(n.matchUpStatus=u),r&&(n.matchUpFormat=r),i&&(n.matchUpStatusCodes=i),m&&(n.winningSide=m),s&&(n.winningSide=void 0),!o&&c&&({structure:o}=xt({drawDefinition:c,matchUpId:d,event:l})),u&&!n.winningSide&&Ie(n)&&!ae.includes(u)&&![oc,Xi].includes(u)&&(n.matchUpStatus=Dn);let A;if((T&&n?.processCodes?.length||u===Ot)&&(A=h?.[vn]?.processCodes?.incompleteAssignmentsOnDefault),!n.collectionId){let M=o?.structureType===Le,P=fr({structure:o});if(Ym({drawDefinition:c,structure:o})||P||M){let N=b=>{r=S?"SET1-S:T100":r??n.matchUpFormat??b?.matchUpFormat??c?.matchUpFormat??l?.matchUpFormat;let x=S?{matchUpTypes:[Bt]}:void 0,{matchUps:w}=At({afterRecoveryTimes:!1,tournamentRecord:a,inContext:!0,matchUpFilters:x,drawDefinition:c,structure:b,event:l});return P&&(b.positionAssignments=pt(w.flatMap(F=>(F.sides??[]).map(L=>L.participantId)).filter(Boolean)).map(F=>({participantId:F}))),cd({positionAssignments:b.positionAssignments,tournamentRecord:a,drawDefinition:c,matchUpFormat:r,matchUps:w,event:l})},C=M&&o.structures.find(b=>b?.matchUps.find(x=>x.matchUpId===d)),O=N(C||o);if(O.error)return _({result:O,stack:e})}}if(f){let M=Up({element:n,notes:f});if(M.error)return _({result:M,stack:e})}let D=a?.tournamentId,y=Cr().topics.includes(up),E=(y||A)&&Ae({drawDefinition:c}),U=E&&re({matchUpFilters:{matchUpIds:[d]},nextMatchUps:!0,tournamentRecord:a,inContext:!0,drawDefinition:c,matchUpsMap:E}).matchUps?.[0];if(y&&U&&yR({tournamentId:D,inContextMatchUp:U}),Array.isArray(A)&&U&&!U.sides?.every(({participantId:M})=>M))if(u===Ot)n.processCodes=pt([...n.processCodes??[],...A]);else for(let M of A||[]){let P=M&&n?.processCodes?.lastIndexOf(M);n?.processCodes?.splice(P,1)}return It({eventId:l?.eventId,context:e,drawDefinition:c,tournamentId:D,matchUp:n}),{...R}}function ud(t){let{dualWinningSideChange:e,matchUpStatusCodes:r,matchUpStatus:n,structure:o,matchUp:i}=t,s=Ea({matchUpStatus:n})||[Wo,$r].includes(n)&&e,a="attemptToModifyScore",c=!!i.collectionId,u=fr({structure:o});if(!(c||u||yG({structure:o,matchUp:i})))return{error:hl};let m=[_t].includes(n),d=Cn({...t,matchUpStatusCodes:s&&r||[],matchUpStatus:s&&n||me,context:a,removeScore:m});return _({result:d,stack:a})}function yG({structure:t,matchUp:e}){let{drawPositions:r}=e,{positionAssignments:n}=de({structure:t});return n?.filter(i=>r?.includes(i.drawPosition)&&i.participantId)?.length===2}function sS({collectionGroups:t=[]}){let e=Object.assign({},...t.filter(n=>ft(n?.groupValue)&&n?.groupNumber).map(n=>({[n.groupNumber]:{...n,allGroupMatchUpsCompleted:!0,matchUpsCount:0,sideWins:[0,0],values:[0,0]}}))),r=Object.keys(e).map(n=>ct(n));return{groupValueGroups:e,groupValueNumbers:r}}function SO({collectionDefinition:t,groupValueNumbers:e,groupValueGroups:r,sideTieValues:n,tieMatchUps:o}){let i=o.filter(S=>S.collectionId===t.collectionId),s=[0,0],a=[0,0],c=i.every(S=>ae.includes(S.matchUpStatus)),{collectionValueProfiles:u,collectionGroupNumber:p,collectionValue:m,matchUpValue:d,winCriteria:l,scoreValue:f,setValue:g}=t,I=p&&e.includes(p),h=[0,0];if(i.forEach(S=>{S.winningSide&&(h[S.winningSide-1]+=1)}),ft(d)?i.forEach(S=>{S.winningSide&&(s[S.winningSide-1]+=d)}):ft(g)?i.forEach(S=>{S.score?.sets?.forEach(T=>{T.winningSide&&(s[T.winningSide-1]+=g)})}):ft(f)?i.forEach(S=>{S.score?.sets?.forEach(T=>{let{side1TiebreakScore:A=0,side2TiebreakScore:D=0,side1Score:y=0,side2Score:E=0}=T;(S.matchUpStatus===me||S.winningSide||T.winningSide)&&(y||E?(s[0]+=y,s[1]+=E):(A||D)&&T.winningSide&&(s[T.winningSide-1]+=1))})}):Array.isArray(u)&&i.forEach(S=>{if(S.winningSide){let T=S.collectionPosition,A=EG({collectionDefinition:t,collectionPosition:T});ft(A)&&(s[S.winningSide-1]+=A)}}),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,A,D)=>A>=l.valueGoal?D+1:T,0);else{let T=Math.floor(t.matchUpCount/2)+1;S=h.reduce((A,D,y)=>D>=T?y+1:A,0)}S&&(I?r[p].values[S-1]+=m:a[S-1]+=m)}else I?(r[p].values[0]+=s[0]||0,r[p].values[1]+=s[1]||0):a=s;I?(r[p].sideWins[0]+=h[0]||0,r[p].sideWins[1]+=h[1]||0,r[p].allGroupMatchUpsCompleted=r[p].allGroupMatchUpsCompleted&&c,r[p].matchUpsCount+=i.length):a.forEach((S,T)=>n[T]+=S||0)}function EG({collectionDefinition:t,collectionPosition:e}){return(t.collectionValueProfiles||[])?.find(o=>o.collectionPosition===e)?.matchUpValue}function aS({collectionValueProfiles:t,matchUpCount:e}){let r=[];if(!Array.isArray(t))return r.push(`collectionValueProfiles is not an array: ${t}`),{errors:r};if(t.length&&t.length!==e)return r.push("collectionValueProfiles do not align with matchUpsCount"),{errors:r};for(let o of t){if(typeof o!="object")return r.push(`valueProfile is not type object: ${o}`),{errors:r};let{matchUpValue:i,collectionPosition:s}=o;if(typeof i!="number"||typeof s!="number"||s>e||s<1)return r.push("Invalid value profile: value and collectionPosition must be numeric. collectionPosition cannot be greater than matchUpCount"),{errors:r}}let n=t.map(o=>o.collectionPosition);return n.length!==pt(n).length?(r.push("collectionPositions are not unique"),{errors:r}):{...R}}var UG="MIXED events can not contain mixed singles or { gender: ANY } collections",PG="events with { gender: ANY } can not contain MIXED singles collections";function pd(t){let e="tieFormatGenderValidityCheck",{referenceGender:r,matchUpType:n,gender:o}=t;return r&&o&&[ee,ue].includes(r)&&r!==o?_({result:{valid:!1,error:vl},context:{gender:o},stack:e}):r===_r&&(o===Fn||o===_r&&n!==Gt)?_({result:{error:vl,valid:!1},info:UG,stack:e}):r===Fn&&o===_r&&n!==Gt?_({result:{error:vl,valid:!1},info:PG,stack:e}):{valid:!0}}function Pp(t,e){if(Rt(t),(t?.bestOf||t?.exactly)&&t?.setFormat)return DG(t,e)}function rg(t){return!isNaN(Number(t))&&Number(t)}function yO(t){let e=`T${t.minutes}`;return t.based&&(e+=t.based),t.modifier&&(e+=`@${t.modifier}`),e}function DG(t,e){let r=rg(t.bestOf)||void 0,n=rg(t.exactly)||void 0,o=r||n;if(t.setFormat?.timed&&t.simplified&&o===1)return yO(t.setFormat);let i=o&&`${$m}${o}`||"",s=TO(t.setFormat,e),a=s&&`S:${s}`||"",c=TO(t.finalSetFormat,e),u=o&&o>1&&c&&s!==c&&`F:${c}`||"";if(i&&s)return[i,a,u].filter(m=>m).join("-")}function TO(t,e){if(typeof t=="object"&&Object.keys(t).length){if(t.timed)return yO(t);if(t.tiebreakSet)return AO(t.tiebreakSet);let r=rg(t.setTo);if(r){let n=t.NoAD&&Lf||"",o=AO(t.tiebreakFormat),i=o&&`/${o}`||"",s=rg(t.tiebreakAt),a=s&&(s!==r||e)&&`@${s}`||"";if(o!==!1)return`${r}${n}${i}${a}`}}}function AO(t){if(t){if(typeof t=="object"&&!t.tiebreakTo)return"";if(typeof t=="object"&&rg(t.tiebreakTo)){let e=`TB${t.tiebreakTo}${t.NoAD?Lf:""}`;return t.modifier&&(e+=`@${t.modifier}`),e}else return!1}}function Sr({matchUpFormat:t}){if(typeof t!="string")return!1;let e=tr(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 Pp(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(te);function Au(t){let e=t.category;if(typeof e!="object")return{error:sm};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:sm};let u=t.consideredDate??Ut(new Date().toLocaleDateString("sv"));if(!Rr(u))return{error:ar};let[p]=u.split("-").slice(0,3).map(v=>parseInt(v)),m=tp(u,-1),[d,l]=m.split("-").slice(1,3).map(v=>parseInt(v)),f=`${Hn(d)}-${Hn(l)}`,g=tp(u,1),[I,h]=g.split("-").slice(1,3).map(v=>parseInt(v)),S=`${Hn(I)}-${Hn(h)}`,T=s&&tp(u,-1*365*s),A=i&&tp(u,-1*365*i),D=[],y=v=>!D.includes(v)&&D.push(v);r=r??a;let E=/^([UO]?)(\d{1,2})([UO]?)$/,U=/^C(\d{1,2})-(\d{1,2})$/,M=r?.includes("-"),P=M&&r?.match(U),N=r?.match(E),C=(v,B)=>`${v}-${B}`,O=v=>{let B=p-v,H=C(B,S);e.ageMinDate&&e.ageMinDate!==H&&y(`Invalid submitted ageMinDate: ${o}`),o=H,r&&(e.ageMax&&e.ageMax!==v-1&&(y(`Invalid submitted ageMax: ${i}`),A=void 0),i=v-1)},b=v=>{let B=p-v-1,H=C(B,S);e.ageMin&&e.ageMin>v&&y(`Invalid submitted ageMin: ${s}`),e.ageMax&&e.ageMax>v&&y(`Invalid submitted ageMax: ${i}`),e.ageMinDate&&e.ageMinDate!==H&&y(`Invalid submitted ageMinDate: ${o}`),o=H,r&&(e.ageMax&&e.ageMax!==v&&(y(`Invalid submitted ageMax: ${i}`),T=void 0),i=v)},x=v=>{let B=p-v,H=C(B,f);e.ageMaxDate&&e.ageMaxDate!==H&&y(`Invalid submitted ageMaxDate: ${n}`),n=H,r&&(e.ageMin&&e.ageMin!==v+1&&(y(`Invalid submitted ageMin: ${s}`),T=void 0),s=v+1)},w=v=>{let B=p-v-1,H=C(B,f);e.ageMaxDate&&e.ageMaxDate!==H&&y(`Invalid submitted ageMaxDate: ${n}`),n=H,r&&(e.ageMin&&e.ageMin!==v&&(y(`Invalid submitted ageMin: ${s}`),T=void 0),s=v)},F=v=>{let[B,H,j]=(v.match(E)||[]).slice(1),V=parseInt(H);B==="U"?(e.ageMaxDate&&e.ageMaxDate!==n&&y(`Invalid submitted ageMaxDate: ${e.ageMaxDate}`),O(V)):B==="O"&&x(V),j==="U"?(e.ageMaxDate&&e.ageMaxDate!==n&&y(`Invalid submitted ageMaxDate: ${e.ageMaxDate}`),b(V)):j==="O"&&w(V),n=n??T,o=o??A};if(P){if(n=void 0,o=void 0,i=void 0,s=void 0,e.ageMin){let H=p-e.ageMin;n=C(H,f)}if(e.ageMax){let H=p-e.ageMax-1;o=C(H,S)}let[v,B]=(r?.match(U)??[]).slice(1).map(H=>parseInt(H));v<=B?(s=v,i=B,c=!0):y(`Invalid combined age range ${r}`)}else M?r?.split("-").forEach(F):N?F(r):(s&&x(s),i&&b(i));i&&e.ageMin&&e.ageMin>i&&(y(`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 md({category:t}){if(!Rt(t))return{error:G};let e=Au({category:t});if(e.error)return{error:e};let{ratingMax:r,ratingMin:n}=t;return r&&!te(r)?_({result:{error:G},context:{ratingMax:r}}):n&&!te(n)?_({result:{error:G},context:{ratingMin:n}}):{...e}}function dd({childCategory:t,withDetails:e,category:r}){let n=md({category:r}),o=md({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 yu({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:Xn},stack:a});let{collectionValueProfiles:u,collectionGroupNumber:p,collectionValue:m,collectionId:d,matchUpCount:l,matchUpFormat:f,matchUpValue:g,matchUpType:I,scoreValue:h,setValue:S,category:T,gender:A}=e;if(r&&typeof d!="string"&&c.push(`collectionId is not type string: ${d}`),typeof l!="number"&&c.push(`matchUpCount is not type number: ${l}`),I&&!cu([Xt,Gt],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 y=aS({collectionValueProfiles:u,matchUpCount:l});y.errors&&c.push(...y.errors)}if(p&&typeof p!="number"&&c.push(`collectionGroupNumber is not type number: ${m}`),f&&!Sr({matchUpFormat:f})&&c.push(`Invalid matchUpFormat: ${f}`),n){let y=pd({referenceGender:i,matchUpType:I,gender:A});if(y.error)return _({context:{referenceGender:i,gender:A},result:y,stack:a})}if(t&&o&&T){let y=dd({category:o,childCategory:T});if(!y.valid)return _({result:{error:sm},context:y,stack:a})}return c.length?_({result:{errors:c,error:Xy},stack:a}):{valid:!0}}function ir(t){let e=!!(t?.enforceCategory!==!1&&t?.category),r=!!(t?.enforceGender!==!1&&t?.gender),n=t?.checkCollectionIds,o=t?.tieFormat,i=t?.event,s="validateTieFormat",a=[];if(!t||!o||typeof o!="object")return a.push("tieFormat must be an object"),_({result:{error:ni},context:{tieFormat:o,errors:a},stack:s});if(typeof o.winCriteria!="object")return a.push("tieFormat.winCriteria must be an object"),_({result:{error:ni},context:{tieFormat:o,errors:a},stack:s});if(!Array.isArray(o.collectionDefinitions))return a.push(Nn("tieFormat.collectionDefinitions")),_({result:{error:ni},context:{tieFormat:o,errors:a},stack:s});let c,u=o.collectionDefinitions.every(g=>{let{setValue:I,scoreValue:h,collectionValue:S}=g;(I||h)&&!S&&(c=!0);let{valid:T,errors:A}=yu({referenceCategory:t.category,referenceGender:t.gender,collectionDefinition:g,checkCollectionIds:n,checkCategory:e,checkGender:r,event:i});return T?!0:(Array.isArray(A)&&a.push(...A),!1)}),p=typeof o.winCriteria?.valueGoal=="number"&&o.winCriteria?.valueGoal>0&&!c||o.winCriteria?.aggregateValue;if(!(p||o.winCriteria?.aggregateValue))return c?a.push("aggregateValue is required"):a.push("Either non-zero valueGoal, or { aggregateValue: true } must be specified in winCriteria"),_({context:{tieFormat:o,errors:a,aggregateValueImperative:c},result:{error:ni},stack:s});let m=o.collectionDefinitions.map(({collectionId:g})=>g),d=!n||m.length===pt(m).length,l=u&&p&&d,f={valid:l,errors:a};return l?f:_({result:{error:ni},context:{tieFormat:o,errors:a},stack:s})}function Uc(t){let{sideAdjustments:e=[0,0],separator:r="-",drawDefinition:n,matchUpsMap:o,structure:i,matchUp:s,event:a}=t;if(!Array.isArray(e)||e.length!==2||isNaN(e.reduce((A,D)=>A+D)))return{error:G};if(!s)return{error:sr};let c=je({matchUp:s,drawDefinition:n,structure:i,event:a})?.tieFormat||t?.tieFormat;if(!c)return{error:qa};let u=ir({tieFormat:c});if(u.error)return u;let p=c?.collectionDefinitions||[],m=s?.tieMatchUps??[],d=[0,0],{groupValueGroups:l,groupValueNumbers:f}=sS(c);for(let A of p)SO({collectionDefinition:A,groupValueNumbers:f,groupValueGroups:l,sideTieValues:d,tieMatchUps:m});for(let A of f){let D=l[A],{allGroupMatchUpsCompleted:y,matchUpCount:E,winCriteria:U,groupValue:M,sideWins:P,values:N}=D,C;if(U?.aggregateValue)y&&N[0]!==N[1]&&(C=N[0]>N[1]?1:2);else if(U?.valueGoal)C=N.reduce((O,b,x)=>b>=U.valueGoal?x+1:O,void 0);else{let O=Math.floor(E/2)+1;C=P.reduce((b,x,w)=>x>=O?w+1:b,void 0)}C&&(d[C-1]+=M||0)}let g=d.map((A,D)=>(A||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:A,aggregateValue:D,tallyDirectives:y}=c.winCriteria;if(A?T=g.map((U,M)=>({sideNumber:M+1,points:U})).find(({points:U})=>U>=A)?.sideNumber:D&&m.every(U=>U.matchUpStatus&&ae.includes(U.matchUpStatus)||U.winningSide)&&g[0]!==g[1]&&(T=g[0]>g[1]?1:2),!T&&y){let E=s.matchUpId,U=s.hasContext?s:o?.drawMatchUps?.[E]||n&&xt({inContext:!0,drawDefinition:n,matchUpId:E})?.matchUp;if(U){let{completedTieMatchUps:M,order:P}=Ca({matchUps:[U]});if(M&&P?.length){let N=P[0].participantId;T=U.sides.find(({participantId:C})=>C===N)?.sideNumber}}}}return T&&(I.winningSide=T),{scoreStringSide1:h,scoreStringSide2:S,winningSide:T,set:I}}function Ra({inContextDualMatchUp:t,drawDefinition:e,tournamentId:r,dualMatchUp:n,eventId:o}){if(n){t||(t=xt({matchUpId:n.matchUpId,inContext:!0,drawDefinition:e})?.matchUp);let{extension:i}=mt({element:e,name:ho}),s=J(i?.value||{},!1,!0),a=({displaySideNumber:c,drawPosition:u,sideNumber:p})=>({drawPosition:u,sideNumber:p,displaySideNumber:c});n.sides=t?.sides?.map(c=>{let u=c.participantId,p=u&&s[u]||void 0,{lineUp:m,...d}=n.sides?.find(({sideNumber:f})=>f===c.sideNumber)??{},l=m?.length?m:p;return{...a(c),...d,lineUp:l}}),It({context:"ensureSidLineUps",matchUp:n,drawDefinition:e,tournamentId:r,eventId:o})}}function Xe(t){if(t)return J(t,!1,!0)}function ng(t){let e=lt(t,[{[ye]:!0}]);return e.error?e:Object.keys(t.tournamentRecords).reduce((n,o)=>{n.tournamentIdMap[o]=[];let s=t.tournamentRecords[o].events??[],a=s.map(({eventId:u})=>u),c=s.map(u=>(u.drawDefinitions??[]).map(({drawId:p})=>p)).flat();return n.tournamentIdMap[o].push(...a,...c),n.eventIds.push(...a),n.drawIds.push(...c),n},{eventIds:[],drawIds:[],tournamentIdMap:{}})}function cS({tournamentRecords:t,eventId:e,drawId:r}){let{tournamentIdMap:n}=ng({tournamentRecords:t});return(n?Object.keys(n):[]).find(i=>e&&n?.[i].includes(e)||r&&n?.[i].includes(r))}function zn(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&&cS({tournamentRecords:c,...t});let p=u&&c[u];if(!p)return{error:W};let m=xt({drawDefinition:r,event:a,matchUpId:s});if(m.error)return m;if(!m.matchUp)return{error:Oe};let{matchUp:d,structure:l}=m;if(!d.tieMatchUps)return{error:Je};Ra({tournamentId:p?.tournamentId,eventId:a?.eventId,dualMatchUp:d,drawDefinition:r});let{extension:f}=mt({name:rc,element:d});if(f?.value)if(o)or({element:d,name:rc});else return{...R,score:d.score};let g=je({drawDefinition:r,structure:l,matchUp:d,event:a})?.tieFormat;d.tieFormat=Xe(g);let I=Uc({drawDefinition:r,matchUpsMap:i,structure:l,matchUp:d,event:a}),{winningSide:h,set:S,scoreStringSide1:T,scoreStringSide2:A}=I,D=S?.side1Score||S?.side2Score;if(e&&!d.score&&!D)return{...R};let y={scoreStringSide1:T,scoreStringSide2:A,sets:S?[S]:[]},E=h&&[1,2].includes(h),U=E&&me||kf({matchUpStatus:n??d.matchUpStatus,tieMatchUps:d.tieMatchUps,winningSide:d.winningSide,score:y})&&Dn||zt,M=!!(d.winningSide&&!E),P=d.tieMatchUps.find(({score:C,winningSide:O,matchUpStatus:b})=>C?.sets?.length&&(C.sets[0].side1Score||C.sets[0].side2Score)||b&&ae.includes(b)||O),N;if(d.tieFormat&&!E&&!P){let C=je({drawDefinition:r,structure:l,event:a})?.tieFormat;C&&JSON.stringify(g)===JSON.stringify(C)&&(d.tieFormatId=void 0,d.tieFormat=void 0,N=!0)}return Cn({appliedPolicies:t.appliedPolicies,matchUpStatus:U,score:y,removeWinningSide:M,tournamentRecord:p,drawDefinition:r,removeScore:o,winningSide:h,matchUpId:s,matchUp:d,event:a}),{...R,score:y,removeWinningSide:M,tieFormatRemoved:N,winningSide:h}}function EO({winnerMatchUpDrawPositionIndex:t,inContextDrawMatchUps:e,projectedWinningSide:r,sourceMatchUpStatus:n,winningDrawPosition:o,tournamentRecord:i,winnerTargetLink:s,sourceMatchUpId:a,drawDefinition:c,winnerMatchUp:u,dualMatchUp:p,matchUpsMap:m,event:d}){let l="directWinner";if(s){let f=u.drawPositions||[],g=f[t],I=s.source.structureId,h=st({structureId:I,drawDefinition:c});if(h.error)return h;let{structure:S}=h,{positionAssignments:T}=de({structureId:I,drawDefinition:c}),D=T?.find(C=>C.drawPosition===o)?.participantId,y=s.target.structureId,{positionAssignments:E}=de({structureId:y,drawDefinition:c}),M=E?.find(C=>C.participantId===D)?.drawPosition,P=E?.filter(C=>{let O=f.includes(C.drawPosition),b=!C.participantId&&!C.bye&&!C.qualifier;return O&&b}).map(C=>C.drawPosition),N=P?.includes(g);if(D&&s.target.roundNumber===1&&N)Mn({drawPosition:g,participantId:D,structureId:y,inContextDrawMatchUps:e,sourceMatchUpStatus:n,tournamentRecord:i,drawDefinition:c,matchUpsMap:m,event:d});else if(D&&P?.length){let C=P.pop();C&&Mn({participantId:D,structureId:y,inContextDrawMatchUps:e,sourceMatchUpStatus:n,tournamentRecord:i,drawDefinition:c,drawPosition:C,matchUpsMap:m,event:d})}else if(M){let C=Ic({drawPosition:M,matchUpId:u.matchUpId,inContextDrawMatchUps:e,sourceMatchUpStatus:n,tournamentRecord:i,sourceMatchUpId:a,drawDefinition:c,matchUpsMap:m});if(C.error)return _({result:C,stack:l})}else if(S?.stage!==at){let C="winner target position unavaiallble";return console.log(C),{error:C}}if(S?.seedAssignments&&S.structureId!==y){let C=S.seedAssignments.find(({participantId:b})=>b===D),O=C?.participantId;C&&O&&Ws({eventId:u?.eventId,structureId:y,...C,tournamentRecord:i,drawDefinition:c,participantId:O})}}else{let f=Ic({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(E=>E.sideNumber===D)||{},sideNumber:D}));S.sides=T;let A=S.sides.find(D=>D.sideNumber===h);if(A){let D=f.lineUp?.filter(y=>y?.participantId);A.lineUp=td({lineUp:D}),It({tournamentId:i?.tournamentId,eventId:u?.eventId,matchUp:S,context:l,drawDefinition:c})}}}return{...R}}function UO(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===qn&&u.roundNumber===2&&Math.min(...g.filter(Boolean)),h=I||g[e],S=I||g[1-e],T=a.source.structureId,{structure:A}=st({structureId:T,drawDefinition:c}),{matchUps:D}=At({afterRecoveryTimes:!1,inContext:!0,drawDefinition:c,structure:A,event:d}),E=D.filter(V=>V.drawPositions?.includes(i)).filter(V=>{let Y=V.sides.find(k=>k.drawPosition===i),$=V.matchUpStatus===_t||V.matchUpStatus===Ot&&!Ie(V);return Y?.sideNumber===V.winningSide&&!$}),U=f===qn&&E.length===0,{positionAssignments:M}=de({structureId:T,drawDefinition:c}),N=M?.find(V=>V.drawPosition===i)?.participantId,C=a.target.structureId,{positionAssignments:O}=de({structureId:C,drawDefinition:c}),b=O?.filter(({drawPosition:V})=>g.includes(V));if(b?.some(V=>V.participantId===N))return{...R};let w=b?.filter(V=>{let Y=g.includes(V.drawPosition),$=!V.participantId&&!V.bye&&!V.qualifier;return Y&&$}).map(V=>V.drawPosition),F=w?.includes(h),L=a.target.roundNumber>1&&w?.length,v=a.target.roundNumber===1&&F;if(I){let V=B();if(V.error)return _({result:V,stack:l})}else if(v){let V=j();if(V.error)return _({result:V,stack:l})}else if(N&&L){w.sort(se);let V=w[0],Y=Mn({participantId:N,structureId:C,drawPosition:V,inContextDrawMatchUps:r,sourceMatchUpStatus:o,tournamentRecord:s,drawDefinition:c,matchUpsMap:m,event:d});if(Y.error)return _({result:Y,stack:l})}else return _({result:{error:ys},context:{loserDrawPosition:i,loserTargetLink:a},stack:l});if(A?.seedAssignments&&A.structureId!==C){let V=A.seedAssignments.find(({participantId:$})=>$===N),Y=V?.participantId;V&&Y&&Ws({eventId:u?.eventId,structureId:C,...V,tournamentRecord:s,drawDefinition:c,participantId:Y})}if(p&&n){let V=p.sides?.find(Y=>Y.sideNumber===3-n);if(V?.lineUp){let{roundNumber:Y,eventId:$}=u,{roundPosition:k}=p,K=Y===1?2-k%2:1,z=m?.drawMatchUps?.find(({matchUpId:Q})=>Q===u.matchUpId),q=[1,2].map(Q=>({...z.sides?.find(ot=>ot.sideNumber===Q)||{},sideNumber:Q}));z.sides=q;let nt=z.sides.find(Q=>Q.sideNumber===K);nt&&(nt.lineUp=td({lineUp:V.lineUp}),It({tournamentId:s?.tournamentId,matchUp:z,context:l,drawDefinition:c,eventId:$}))}}return{...R};function B(){let V="loserLinkFedFMLC";return U?_({result:j(),stack:V}):_({result:H(),stack:V})}function H(){let V=Dr({drawPosition:S,structureId:C,tournamentRecord:s,drawDefinition:c,event:d});return _({result:V,stack:"assignLoserPositionBye"})}function j(){let V=N?Mn({drawPosition:h,participantId:N,structureId:C,inContextDrawMatchUps:r,sourceMatchUpStatus:o,tournamentRecord:s,drawDefinition:c,matchUpsMap:m,event:d}):{error:oe};return _({result:V,stack:"assignLoserDrawPosition"})}}function uS(t){let e=ud(t);if(e.error)return e;let r=Ea({matchUpStatus:t.matchUpStatus}),{dualWinningSideChange:n,projectedWinningSide:o,inContextDrawMatchUps:i,tournamentRecord:s,drawDefinition:a,matchUpStatus:c,dualMatchUp:u,matchUpsMap:p,winningSide:m,targetData:d,matchUpId:l,structure:f,matchUp:g,event:I}=t,h="directParticipants",S=!!g.collectionId,T=fr({structure:f}),A=g.drawPositions,D;if(S){let{matchUpTieId:y,matchUpsMap:E}=t,U=zn({appliedPolicies:t.appliedPolicies,matchUpId:y,tournamentRecord:s,drawDefinition:a,matchUpsMap:E,event:I});if(D=U&&{tieMatchUpResult:U},A=i.find(({matchUpId:P})=>P===y)?.drawPositions,!n)return _({result:{...R,...D},stack:h})}if(T)return _({result:{...R,...D},stack:h});if(A){let y=o?o-1:m-1,E=1-y,U=A[y],M=A[E],{targetLinks:{loserTargetLink:P,winnerTargetLink:N,byeTargetLink:C},targetMatchUps:{winnerMatchUpDrawPositionIndex:O,loserMatchUpDrawPositionIndex:b,winnerMatchUp:x,loserMatchUp:w,byeMatchUp:F}}=d;if(x){let L=EO({sourceMatchUpStatus:r&&c||me,winnerMatchUpDrawPositionIndex:O,sourceMatchUpId:l,inContextDrawMatchUps:i,projectedWinningSide:o,winningDrawPosition:U,tournamentRecord:s,winnerTargetLink:N,drawDefinition:a,winnerMatchUp:x,dualMatchUp:u,matchUpsMap:p,event:I});if(L.error)return _({result:L,stack:h})}if(w){let L=UO({sourceMatchUpStatus:r&&c||me,loserMatchUpDrawPositionIndex:b,sourceMatchUpId:l,inContextDrawMatchUps:i,projectedWinningSide:o,loserDrawPosition:M,tournamentRecord:s,loserTargetLink:P,drawDefinition:a,loserMatchUp:w,winningSide:m,matchUpsMap:p,dualMatchUp:u,event:I});if(L.error)return _({result:L,stack:h})}if(F){let L=F.drawPositions||[],v=Math.min(...L.filter(Boolean)),B=C.target.structureId,H=Dr({drawPosition:v,structureId:B,tournamentRecord:s,drawDefinition:a,event:I});if(H.error)return _({result:H,stack:h})}}else return _({result:{error:Wa},stack:h});return _({result:{...R,...D},stack:h})}function ld(t){let e="genPlayoffStructure";if(!t.drawDefinition)return _({result:{error:X},stack:e});let r=Iu(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:A}=st({structureId:n,drawDefinition:T});if(!A)return _({result:{error:Lt},stack:e});if(A.structureType===Le||A.structures)return cO({sourceStructureId:A.structureId,...t,...r,drawDefinition:T});let{playoffRoundsRanges:D,playoffRounds:y}=r,{playoffPositionsReturned:E,error:U,playoffSourceRounds:M,playoffRoundsRanges:P}=Qh(t);if(U)return _({result:{error:U},stack:e});let N=l?.length&&Object.assign({},...l),C=f||typeof l=="object"&&l.map(q=>Object.keys(q)).flat(),O=Array.isArray(C)&&C.map(q=>!isNaN(q)&&ct(q)).filter(Boolean);if(O){if(!Array.isArray(O))return _({result:{error:G},context:{validRoundNumbers:O},stack:e});O.forEach(q=>{if(!y?.includes(q))return _({result:{error:G},context:{roundNumber:q},stack:e})})}u&&u.forEach(q=>{if(!E?.includes(q))return _({result:{error:G},context:{playoffPosition:q},stack:e})});let b=O||M,x=O?D:P,w=[],F=[];for(let q of b??[]){let nt=x?.find(Ee=>Ee.roundNumber===q);if(!nt)return _({result:{error:G},context:{roundNumber:q},stack:e});let Q=nt.finishingPositions.length,it=Math.min(...nt.finishingPositions)-1,ot=2,ut=q&&N?.[q]&&ot+N[q]-1,Qt=Tc({exitProfile:`0-${q}`,addNameBaseToAttributeName:o,playoffStructureNameBase:i,finishingPositionOffset:it,playoffAttributes:c,exitProfileLimit:d,stage:ce,roundOffset:0,drawDefinition:T,sequenceLimit:ut,stageSequence:ot,drawSize:Q,idPrefix:g,isMock:I,uuids:S,finishingPositionNaming:s,finishingPositionLimit:a,roundOffsetLimit:p});if(Qt.error)return _({result:Qt,stack:e});let{structures:yt,links:Me}=Qt;if(yt?.length&&w.push(...yt),Me?.length&&F.push(...Me),Qt.structureId&&q){let Ee={linkType:Yn,source:{structureId:n,roundNumber:q},target:{structureId:Qt.structureId,feedProfile:sn,roundNumber:1}};F.push(Ee)}}if(!w.length)return _({result:{error:G},info:"No structures generated",stack:e});T.structures.push(...w),T.links.push(...F);let{matchUps:L,matchUpsMap:v}=re({inContext:!0,drawDefinition:T}),B=w.map(({structureId:q})=>q),H=L?.filter(({structureId:q})=>B.includes(q)).map(fe),j=v?.drawMatchUps?.filter(({matchUpId:q})=>H?.includes(q));if(j?.length){let q=je({drawDefinition:T,event:h})?.tieFormat;q&&j.forEach(nt=>{let{tieMatchUps:Q}=Ma({matchUp:nt,tieFormat:q,isMock:I});Object.assign(nt,{tieMatchUps:Q,matchUpType:Bt})})}L?.filter(q=>is({matchUp:q})&&q.structureId===n)?.forEach(q=>{let{matchUpId:nt,score:Q,winningSide:it}=q,ot=er({inContextDrawMatchUps:L,drawDefinition:T,matchUpId:nt}),ut=uS({inContextDrawMatchUps:L,tournamentRecord:m,drawDefinition:T,matchUpsMap:v,winningSide:it,targetData:ot,matchUpId:nt,structure:A,matchUp:q,score:Q,event:h});ut.error&&console.log(ut.error)}),L?.filter(q=>q.matchUpStatus===Dt&&q.structureId===n)?.forEach(q=>{let{matchUpId:nt}=q,Q=er({inContextDrawMatchUps:L,drawDefinition:T,matchUpId:nt}),{targetLinks:{loserTargetLink:it},targetMatchUps:{loserMatchUpDrawPositionIndex:ot,loserMatchUp:ut}}=Q;if(it&&ut){let Qt=it.target.structureId,yt=ut.drawPositions[ot],Me=Dr({drawPosition:yt,structureId:Qt,tournamentRecord:m,drawDefinition:T,event:h});Me.error&&console.log(Me.error)}});let $=[],k=wi({inContextDrawMatchUps:L,drawDefinition:T,matchUpsMap:v}).goesToMap,{structure:K}=st({drawDefinition:t.drawDefinition,structureId:n}),{matchUps:z}=At({structure:K});return z.forEach(q=>{let nt=k?.loserMatchUpIds[q.matchUpId];if(nt&&q.loserMatchUpId!==nt){q.loserMatchUpId=nt;let it={tournamentId:m?.tournamentId,eventId:t.event?.eventId,context:e,matchUp:q};$.push(it)}let Q=k?.winnerMatchUpIds[q.matchUpId];if(Q&&q.winnerMatchUpId!==Q){q.winnerMatchUpId=Q;let it={tournamentId:m?.tournamentId,eventId:t.event?.eventId,context:e,matchUp:q};$.push(it)}}),{structures:w,matchUpModifications:$,links:F,drawDefinition:T,...R}}function JU(t){return ig({...t,itemType:"attachConsolationStructures"})}function og(t){return ig({...t,itemType:"attachPlayoffStructures"})}function ig({itemType:t="attachStructures",matchUpModifications:e,tournamentRecord:r,drawDefinition:n,structures:o,links:i=[],event:s}){let a="attachStructures";if(!n)return{error:X};if(!Array.isArray(o)||!Array.isArray(i))return _({result:{error:G},stack:a});let c=h=>[h.source.structureId,h.source.roundNumber||h.source.finishingPositions?.join("|"),h.target.roundNumber].join("|"),u=n.links?.map(c);if(i.some(h=>{let S=c(h);return u?.includes(S)}))return _({result:{error:Fl},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),wi({drawDefinition:n});let f=o.map(h=>At({structure:h})?.matchUps||[]).flat();So({tournamentId:r?.tournamentId,eventId:s?.eventId,drawDefinition:n,matchUps:f});let g=o.map(({structureId:h})=>h);if(bt({drawDefinition:n,structureIds:g}),e?.length){let h={};e.forEach(T=>{let A=T.matchUp?.matchUpId;A&&(h[A]=T)});let S=T=>{T.matchUps.forEach(A=>{if(h[A.matchUpId]){let{tieMatchUps:D,...y}=h[A.matchUpId].matchUp;if(Object.assign(A,y),D?.length){let E={};D.forEach(U=>h[U.matchUpId]=U),A.tieMatchUps.forEach(U=>Object.assign(U,E[U.matchUpId]))}h[A.matchUpId].matchUp=A,It(h[A.matchUpId])}})};n.structures.forEach(T=>{if(d?.includes(T.structureId))if(T.structures)for(let A of T.structures)S(A);else S(T)})}let I=l.map(Pr("structureId"));if(r){let S={itemValue:{structureIds:g,drawId:n.drawId},itemType:t};Ti({element:r,timeItem:S})}return{...R,addedStructureIds:I}}function Dp(t){let{structures:e,links:r,matchUpModifications:n,error:o}=ld(t);if(o)return{error:o};let i=t.drawDefinition;return og({tournamentId:t.tournamentRecord?.tournamentId,eventId:t.event?.eventId||t.eventId,matchUpModifications:n,drawDefinition:i,structures:e,links:r})}function Vi(t){let e=lt(t,[{_anyOf:{[ye]:!1,[An]:!1,[Yr]:!1,[Cs]:!1},[jl]:!0}]);if(e.error)return e;let r=[],n=t.drawDefinition??t.event??((t.tournamentId||!t.tournamentRecords)&&t.tournamentRecord);if(n){let o=PO(t,n);if(o.error)return o;r.push(...o?.applied??[]),t.drawDefinition&&bt({drawDefinition:t.drawDefinition,tournamentId:t.tournamentId})}else if(t.tournamentRecords){let o=Object.keys(t.tournamentRecords);if(!o.length)return{error:W};for(let i of o){let s=t.tournamentRecords[i],a=PO(t,s);if(a.error)return a;r.push(...a?.applied??[])}}else return{error:W};return r.length?{...R,applied:r}:{error:gI}}function PO(t,e){let r=Pt(t).appliedPolicies??{};e.extensions||(e.extensions=[]);let n=[],o=Object.keys(t.policyDefinitions);if(!o.length)return{error:Bu};for(let i of o)if(!r[i]||t.allowReplacement){let s=t.policyDefinitions[i];if(!s)continue;if(!Rt(s))return{error:G};let{policyName:a,...c}=s;if(!c||!Object.keys(c).length||a&&!$e(a))return{error:G};r[i]=t.policyDefinitions[i],n.push(i)}return n?.length?{...St({element:e,extension:{name:jc,value:r}}),applied:n}:{applied:n,error:gI}}function sg({tournamentRecord:t,drawDefinition:e,flightProfile:r,drawName:n,drawId:o,event:i}){if(!n||typeof n!="string")return _({result:{error:G},context:{drawName:n}});r||(r=Ht({event:i}).flightProfile);let s=r?.flights?.find(a=>a.drawId===o);if(s){s.drawName=n;let a={name:qr,value:{...r,flights:r.flights}};Io({event:i,extension:a})}return e&&(e.drawName=n,bt({tournamentId:t?.tournamentId,drawDefinition:e})),!s&&!e?{error:X}:{...R,flight:s}}function ZU({tournamentRecord:t,drawDefinition:e,drawUpdates:r,drawId:n,event:o}){if(!Rt(r))return{error:G};let i=Ht({event:o}).flightProfile,s=r.drawName&&sg({drawName:r.drawName,tournamentRecord:t,drawDefinition:e,flightProfile:i,drawId:n,event:o});if(s?.error)return s?.error;let a=s?.flight||i?.flights?.find(c=>c.drawId===n);if(!a&&!e)return{error:X};if(a){let c={name:qr,value:{...i,flights:i.flights}};Io({event:o,extension:c})}return e&&(r.policyDefinitions&&Vi({policyDefinitions:r.policyDefinitions,drawDefinition:e}),bt({tournamentId:t?.tournamentId,drawDefinition:e})),{...R}}function tP({tournamentRecord:t,removeScheduling:e,drawDefinition:r}){if(!r)return{error:X};let n=Ae({drawDefinition:r}),o=s=>n?.drawMatchUps?.find(a=>a.matchUpId===s);for(let s of r.structures||[]){let{positionAssignments:a,stage:c,stageSequence:u}=s;a&&(u!==1||![at,tt].includes(c))&&(s.positionAssignments=a.map(d=>(delete d.participantId,d)),s.seedAssignments=[]);let{matchUps:p,isRoundRobin:m}=At({afterRecoveryTimes:!1,inContext:!0,matchUpsMap:n,structure:s});for(let d of p){let{matchUpId:l,roundNumber:f}=d,g=d.sides||[],I=o(l);if(I){if(delete I.extensions,delete I.notes,I.matchUpStatus!==Dt&&Object.assign(I,Tu),f&&f>1&&I.drawPositions?.length&&!m){let h=g?.map(({drawPosition:T,participantFed:A})=>!A&&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&&![Eo,di,xs,XE,ws,Ls].includes(h.itemType))),It({tournamentId:t?.tournamentId,context:"resetDrawDefiniton",drawDefinition:r,matchUp:I})}}}let i=(r.structures||[]).map(({structureId:s})=>s);return bt({drawDefinition:r,structureIds:i}),{...R}}function Eu({tournamentRecord:t}){if(!t)return{error:W};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}=gu({drawDefinition:o}),p=r[i],d=(o?.structures||[]).map(D=>{let{stage:y,stageSequence:E,structureId:U}=D,M=_s[y],{inContextStructureMatchUps:P}=Ua({drawDefinition:o,structure:D,event:p}),N=P?.filter(({winningSide:Y})=>Y),C=N.filter(Boolean).length||0;a+=C,c+=P.length-a;let O=Math.max(N.filter(({roundNumber:Y})=>Y===1).map(({roundPosition:Y})=>Y)),{positionAssignments:b}=Nt({structure:D}),x=b?.filter(({participantId:Y})=>Y);s+=x?.length??0;let w=(b?.length??0)-(x?.length??0),{roundMatchUps:F,roundProfile:L,roundNumbers:v,maxMatchUpsCount:B}=He({matchUps:P}),H=L&&Object.keys(L).filter(Y=>!L[Y].inactiveRound).map(Y=>parseInt(Y)),j=L&&Object.keys(L).filter(Y=>L[Y].inactiveRound).map(Y=>parseInt(Y)),V=L&&Object.values(L).every(Y=>Y.inactiveRound);return{positionsAssignedCount:x?.length??0,maxWinningSideFirstRoundPosition:O,unassignedPositionsCount:w,inactiveStructure:V,maxMatchUpsCount:B,inactiveRounds:j,roundMatchUps:F,activeRounds:H,roundNumbers:v,roundProfile:L,structureId:U,stageSequence:E,orderNumber:M,stage:y}}),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=ct(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 A={matchUpsWithWinningSideCount:a,matchUpsNoOutcomeCount:c,positionsAssignedCount:s,allStructuresLinked:u,structuresData:d,inactiveDraw:h,isMatchPlay:I,drawId:T};e.drawAnalysis[T]=A}),{...R,drawsAnalysis:e}}function eP({matchPlayDrawPositions:t=!0,tournamentRecord:e,drawDefinition:r,drawId:n}){if(!e)return{error:W};if(!r)return{error:X};let o=[],{drawsAnalysis:i}=Eu({tournamentRecord:e});if(i.canBePruned.includes(n)){let s=i.matchPlay.includes(n),a=i.drawAnalysis[n],{structures:[c]}=xn({stageSequence:1,drawDefinition:r,stage:tt}),u=a.structuresData.find(({structureId:l})=>c.structureId===l),p=(c.matchUps??[]).sort((l,f)=>l.roundPosition-f.roundPosition);o=p.filter(({roundNumber:l})=>!u.inactiveRounds.includes(l));let m=o.map(fe),d=p.map(fe).filter(l=>!m.includes(l));if(s){let l=o.filter(({roundNumber:T})=>!u.inactiveRounds.includes(T)).filter(({winningSide:T})=>T),f=l.map(fe),g=m.filter(T=>!f.includes(T));d.push(...g);let h=l.flatMap(T=>T.drawPositions??[]).filter(Boolean).flat(),S=Object.assign({},...h.map((T,A)=>({[T]:A+1})));if(l.forEach(T=>{t?T.drawPositions=T.drawPositions.map(A=>S[A]):delete T.drawPositions}),t){let T=c?.positionAssignments?.filter(A=>h.includes(A.drawPosition)).map(A=>(A.drawPosition=S[A.drawPosition],A));c.positionAssignments=T}else c.positionAssignments=[];c.matchUps=l,o=l}wn({tournamentId:e?.tournamentId,matchUpIds:d,drawDefinition:r}),bt({drawDefinition:r})}return{...R,matchUps:o}}function rP({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:Es};if(!o)return{error:hr};if(a){let c=Dr({tournamentRecord:t,drawDefinition:e,drawPosition:n,structureId:o,event:s});if(c.error)return c}else{if(i)return{error:$u};{let c=Mn({tournamentRecord:t,drawDefinition:e,participantId:r,drawPosition:n,structureId:o,event:s});if(c.error)return c}}return{...R}}function pS(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===_i)return{error:Pi};let a=i.filter(({roundNumber:c})=>t.roundNumbers?.includes(c)).map(fe);return e=e.filter(c=>!a.includes(c)),t.roundNumbers&&!e.length&&(e=a),{existingMatchUps:i,matchUpIds:e,structureId:n,structure:o}}function nP(t){let e=lt(t,[{[Yr]:!0},{[Ja]:{[Xa]:!1,roundNumbers:!1},[En]:G,[to]:Er}]);if(e.error)return e;let{removeIncomplete:r=!1,removeUnAssigned:n=!0,removeCompleted:o=!1,tournamentRecord:i,drawDefinition:s,event:a}=t,c=pS(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(Ie({score:S})){if(!T&&!r)return!1;l.push(h)}else if(!n)return!1;return d?.includes(h)})??[],g=f.map(fe),I=f.map(({tieMatchUps:h})=>h?.map(fe)).filter(Boolean).flat();if(g.length){u.matchUps=(u.matchUps??[]).filter(({matchUpId:T})=>!g.includes(T)),wn({tournamentId:i?.tournamentId,matchUpIds:[...I,...g],action:"deleteAdHocMatchUps",eventId:a?.eventId,drawDefinition:s});let h=pt(u.matchUps.map(Pr("roundNumber"))),S=YC(h);if(S.length){S.reverse();for(let T of S)u.matchUps.forEach(A=>{A.roundNumber&&A.roundNumber>T&&(A.roundNumber-=1,It({tournamentId:i?.tournamentId,context:["adHoc round deletion"],eventId:a?.eventId,drawDefinition:s,matchUp:A}))})}if(l.length){u.positionAssignments=pt(u.matchUps.flatMap(y=>(y.sides??[]).map(E=>E.participantId)).filter(Boolean)).map(y=>({participantId:y}));let T=u?.matchUpFormat??s?.matchUpFormat??a?.matchUpFormat,{matchUps:A}=At({afterRecoveryTimes:!1,inContext:!0,structure:u,event:a}),D=cd({positionAssignments:u.positionAssignments,tournamentRecord:i,drawDefinition:s,matchUpFormat:T,matchUps:A,event:a});D.error&&console.log(D)}bt({structureIds:[p],eventId:a?.eventId,drawDefinition:s})}return!g.length&&d.length?{error:Ku}:{...R,deletedMatchUpsCount:[...g,...I].length}}function oP({removeCompletedMatchUps:t,tournamentRecord:e,drawDefinition:r,structureId:n,roundNumber:o,event:i}){if(!e)return{error:W};if(!r)return{error:X};if(!o)return _({result:{error:et},info:"roundNumber required"});let s=st({drawDefinition:r,structureId:n});if(s.error)return s;let a=s.structure;return a?.structures?{error:Pi}:fr({structure:a})?CG({tournamentId:e.tournamentId,removeCompletedMatchUps:t,eventId:i.eventId,drawDefinition:r,roundNumber:o,structure:a}):(console.log("not implemented"),{...R})}function CG({removeCompletedMatchUps:t,drawDefinition:e,tournamentId:r,roundNumber:n,structure:o,eventId:i}){let s=o?.matchUps??[],a=[],c=[],u=!1;if(s.reduce((m,d)=>{let l=d?.roundNumber;return l?m.includes(l)?m:m.concat(l):m},[]).sort(se).includes(n)){let m=s.filter(d=>{let l=d.roundNumber===n&&(!ae.includes(d.matchUpStatus)||t);return l&&(c.push(d.matchUpId),d.tieMatchUps&&a.push(...d.tieMatchUps.map(fe))),!l});c.length&&(wn({matchUpIds:[...a,...c],drawDefinition:e,tournamentId:r,eventId:i}),m.some(l=>l.roundNumber===n)||(m.forEach(l=>{l.roundNumber>n&&(l.roundNumber-=1,It({drawDefinition:e,tournamentId:r,eventId:i,matchUp:l}))}),u=!0),o.matchUps=m)}return{deletedMatchUpsCount:c.length,roundRemoved:u,...R}}function fd(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(!Ur(o))return{error:G,info:Nn("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===_i)return{error:Pi};let p=le({tournamentRecord:r,inContext:!1})?.matchUps?.map(fe)??[],m=o.map(fe);if(xe(p,m))return{error:rE,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||(So({tournamentId:r?.tournamentId,matchUps:[...d,...o],eventId:i?.eventId,drawDefinition:n}),bt({drawDefinition:n,structureIds:[s]})),{...R}}function iP({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:Es};let{structure:s}=st({drawDefinition:e,structureId:n});if(!s)return{error:Lt};let a=s;s.structures&&s.structureType===Le&&(a=s.structures?.find(g=>g.positionAssignments?.find(I=>I.drawPosition===r)));let c=a?.positionAssignments,u=c?.find(g=>g.drawPosition===r);u&&St({element:u,extension:{name:nc,value:o}});let d=(i?.eventType===Bt||e.matchUpType===Bt||(i?.tieFormat??e?.tieFormat??s?.tieFormat))&&{matchUpTypes:[Bt]},{matchUps:l}=At({structure:a,afterRecoveryTimes:!1,inContext:!0,matchUpFilters:d,event:i}),f=s?.matchUpFormat??e.matchUpFormat;return cd({positionAssignments:c,tournamentRecord:t,drawDefinition:e,matchUpFormat:f,matchUps:l,event:i}),bt({drawDefinition:e,structureIds:[n]}),{...R}}var TP={};Jt(TP,{addGoesTo:()=>wi,allPlayoffPositionsFilled:()=>Yh,checkValidEntries:()=>Sd,findDrawDefinition:()=>fS,getAssignedParticipantIds:()=>Si,getAvailableMatchUpsCount:()=>gd,getAvailablePlayoffProfiles:()=>Iu,getDrawDefinitionTimeItem:()=>Dh,getDrawParticipantRepresentativeIds:()=>dS,getDrawTypeCoercion:()=>Pu,getEligibleVoluntaryConsolationParticipants:()=>mS,getMatchUpsMap:()=>Ae,getParticipantIdFinishingPositions:()=>lS,getPositionAssignments:()=>Cp,getPositionsPlayedOff:()=>Ac,getSeedingThresholds:()=>wh,getSeedsCount:()=>Du,getStructureSeedAssignments:()=>Fr,getTeamLineUp:()=>os,getValidGroupSizes:()=>Sp,isAdHoc:()=>fr,isCompletedStructure:()=>Jo,isValidForQualifying:()=>RS,positionActions:()=>CS});function mS({excludedMatchUpStatuses:t=[],includeEventParticipants:e,includeQualifyingStage:r,finishingRoundLimit:n,policyDefinitions:o,roundNumberLimit:i,tournamentRecord:s,drawDefinition:a,matchUpsLimit:c,requirePlay:u,requireLoss:p,allEntries:m,winsLimit:d,event:l}){if(!a)return{error:X};let f=[tt,ce];r&&f.push(at);let g=l?.eventType?{matchUpTypes:[l.eventType]}:void 0,I=a?.matchUpType?{matchUpTypes:[a.matchUpType]}:void 0,h=e&&l?co({contextFilters:{stages:f},matchUpFilters:g,tournamentRecord:s,inContext:!0,event:l})?.matchUps??[]:rr({contextFilters:{stages:f},matchUpFilters:I,tournamentRecord:s,inContext:!0,drawDefinition:a})?.matchUps??[],T=mi({stage:Be,drawDefinition:a}).map(({participantId:v})=>v),A={},D={},y={},E={};o||(o=yo({policyTypes:[kI],tournamentRecord:s,drawDefinition:a,event:l}).policyDefinitions);let U=o?.[kI];t=t.length&&t||U?.excludedMatchUpStatuses||[],e=e??U?.includeEventParticipants,m=m??U?.allEntries,n=n??U?.finishingRoundLimit,i=i??U?.roundNumberLimit,c=c??U?.matchUpsLimit,u===void 0&&(u=U?.requirePlay!==void 0?U.requirePlay:!0),p===void 0&&(p=U?.requireLoss!==void 0?U.requireLoss:!0),d=d??U?.winsLimit;for(let v of h){if(u&&v.winningSide&&![1,2].includes(v.winningSide)&&v.matchUpStatus!==ge||v.finishingRound&&n&&v.finishingRound>=n||v.finishingRound&&i&&v.finishingRound<=i)continue;let B=v.sides?.find(({sideNumber:j})=>v.winningSide&&j===3-v.winningSide),H=v.sides?.find(({sideNumber:j})=>v.winningSide&&j===v.winningSide);if(v.sides?.forEach(j=>{let V=j?.participant?.participantId;V&&(y[V]=j.participant,v.matchUpStatus===ge&&!u&&(D[V]=j.participant,A[V]||(A[V]=0),(!v.matchUpStatus||!t.includes(v.matchUpStatus))&&(A[V]+=1)))}),B?.participant){let j=B.participant.participantId;D[j]=B.participant,A[j]||(A[j]=0),v.matchUpStatus&&!t.includes(v.matchUpStatus)&&(A[j]+=1)}if(H?.participant){let j=H.participant.participantId;E[j]||(E[j]=0),E[j]+=1,A[j]||(A[j]=0),v.matchUpStatus&&!t.includes(v.matchUpStatus)&&(A[j]+=1)}}let M=s?.participants&&!u&&!p&&m,P=M?((e&&l?l.entries:a.entries)??[]).filter(v=>![Ao,Lr].includes(v.entryStatus)).map(({participantId:v})=>v):[],N=Object.keys(D),C=M?(s?.participants??[]).filter(({participantId:v})=>P.includes(v)):p&&Object.values(D)||Object.values(y),O=v=>!p||N.includes(v),b=v=>!u||(A[v]||0)>=0,x=v=>!d||(E[v]||0)<=d,w=v=>!c||A[v]<=c,F=v=>!T.includes(v);return{eligibleParticipants:C.filter(v=>O(v.participantId)&&b(v.participantId)&&x(v.participantId)&&w(v.participantId)&&F(v.participantId)).map(v=>({...v,individualParticipants:v.individualParticipantIds?.map(B=>s?.participants?.find(H=>H.participantId===B))})),losingParticipantIds:N,...R}}function gd(t){let e=lt(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===_i)return{error:Pi};let u=r?.entries?.filter(g=>{let I=g.entryStatus;return Or.includes(I)})??[],p=Math.floor(u?.length/2)||1,m=n??c??1,d=i.matchUps?.filter(g=>g.roundNumber===m)?.length??0,l=p-d,f=l>0?l:0;return{...R,availableMatchUpsCount:f,lastRoundNumber:c,roundMatchUpsCount:p}}function dS({drawDefinition:t}){let e=mt({name:"participantRepresentatives",element:t});return e.error?e:{representativeParticipantIds:e.extension?.value||[]}}function DO({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 lS({byeAdvancements:t=!1,tournamentRecord:e,drawDefinition:r}){if(!r)return{error:X};let{participantIds:n,participantIdMatchUps:o}=DO({tournamentParticipants:e?.participants,drawDefinition:r}),i=n?.map(s=>{let c=o[s].filter(d=>[me,Dt].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 Po({tournamentRecords:t,tournamentRecord:e,tournamentId:r,drawId:n}){if(!e&&!t)return{error:W};if(!n)return{error:Wr};if(!e&&t){if(typeof r!="string"&&(r=cS({tournamentRecords:t,drawId:n}),!r))return{error:ra};if(e=t[r],!e)return{error:W}}let o=e&&We({tournamentRecord:e,drawId:n});return o?.drawDefinition?{drawDefinition:o.drawDefinition,event:o.event,tournamentRecord:e,...R}:_({result:{error:pr},stack:"findDrawDefinition"})}function fS(t){let{drawDefinition:e,error:r}=Po(t);return r?{error:r}:{drawDefinition:J(e)}}function ag({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}=st({structureId:p,drawDefinition:r});if(!(e&&m?.finishingPosition!==e))return u}).filter(Boolean);return{sourceStructureIds:a.map(({source:u})=>u.structureId),relevantLinks:a}}var NO="qualifierDrawPositionAssignment",MO="withdrawParticipantAtDrawPosition",CO="alternateDrawPositionAssignment",RO="luckyLoserDrawPositionAssignment",aP="removeDrawPositionAssignment",bO="swapDrawPositionAssignments",OO="modifyPairAssignment",_O="modifyParticipantOtherName",cP="assignDrawPosition",vO="removeSeededParticipant",xO="assignDrawPositionBye",wO="modifySeedAssignment",gS="addPenalty",cg="MODIFY_PAIR",Np="QUALIFIER",ug="ALTERNATE",pg="WITHDRAW",ds="ASSIGN",IS="REMOVE",mg="LUCKY",Mp="REMOVE_SEED",dg="SWAP",Uu="NICKNAME",js="SEED_VALUE",Ys="PENALTY",Id="BYE",LO={MODIFY_PAIR_ASSIGNMENT:cg,QUALIFYING_PARTICIPANT:Np,ALTERNATE_PARTICIPANT:ug,WITHDRAW_PARTICIPANT:pg,ASSIGN_PARTICIPANT:ds,LUCKY_PARTICIPANT:mg,REMOVE_ASSIGNMENT:IS,SWAP_PARTICIPANTS:dg,ADD_NICKNAME:Uu,REMOVE_SEED:Mp,ADD_PENALTY:Ys,ASSIGN_BYE:Id,SEED_VALUE:js};function FO({tournamentParticipants:t,returnParticipants:e,drawPosition:r,participant:n,drawId:o,event:i}){let s=i?.entries?.filter(({entryStatus:a})=>[Lr,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:OO,availableIndividualParticipantIds:s,availableIndividualParticipants:c,existingIndividualParticipantIds:a,existingIndividualParticipants:u,type:cg},!1,!1,!0)}}return{}}function Ai(t){let{inContextDrawMatchUps:e,targetData:r,drawDefinition:n,relevantLink:o}=t;if(o?.linkCondition===qn&&r?.matchUp?.matchUpStatus===Dt)return!1;let{targetMatchUps:{loserMatchUp:s,winnerMatchUp:a},targetLinks:c}=r,u=[Ot,_t].includes(s?.matchUpStatus),p=a?.drawPositions?.filter(Boolean).length||0;if(s?.winningSide&&!u||a?.winningSide&&p===2&&(!a.feedRound||![_t,Ot].includes(a?.matchUpStatus)))return!0;let m=s&&er({matchUpId:s.matchUpId,inContextDrawMatchUps:e,drawDefinition:n}),d=a&&er({matchUpId:a.matchUpId,inContextDrawMatchUps:e,drawDefinition:n}),l=m&&Ai({relevantLink:c?.loserTargetLink,targetData:m,inContextDrawMatchUps:e,drawDefinition:n});return!!(d&&Ai({targetData:d,inContextDrawMatchUps:e,drawDefinition:n})||l)}var hS={[no]:{policyName:"positionActionsDefault",enabledStructures:[{stages:[at,tt],stageSequences:[1],enabledActions:[],disabledActions:[]},{stages:[],stageSequences:[],enabledActions:[Uu,Ys,Np,js],disabledActions:[]}],disbledStructures:[],otherFlightEntries:!1,activePositionOverrides:[]}};var lg="positionAction",SS="matchUpAction";function TS({actionType:t=lg,appliedPolicies:e,drawDefinition:r,structure:n}){let o=t===lg&&no||t===SS&&ze,i=t===lg&&hS||t===SS&&fU,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 uP({activePositionOverrides:t,activeDrawPositions:e,action:r}){return r&&t.includes(r)?!0:!e.length}function AS({enabledStructures:t,drawDefinition:e,structure:r}){if(t===!1)return{};if(!t?.length)return{policyActions:{enabledActions:[],disabledActions:[]}};let{stage:n,stageSequence:o,structureType:i}=r||{},a=e.links?.filter(u=>u?.target?.structureId===r?.structureId)?.map(({target:u})=>u.feedProfile)||[];return{policyActions:t.find(u=>{let{stages:p,stageSequences:m,structureTypes:d,feedProfiles:l}=u||{},f=!p?.length||Array.isArray(p)&&p.includes(n),g=!m?.length||Array.isArray(m)&&m.includes(o),I=!d?.length||Array.isArray(d)&&d.includes(i),h=!l?.length||Array.isArray(l)&&l.some(S=>a.includes(S));return g&&I&&h&&u&&f})}}function Rn({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 pP="replaceTieMatchUpParticipantId",mP="assignTieMatchUpParticipantId",yS="removeTieMatchUpParticipantId",dP="assignMatchUpSideParticipant",GO="removeMatchUpSideParticipant",lP="substituteParticipant",ES="REMOVE_SUBSTITUTION",fP="REPLACE_PARTICIPANT",fg="REMOVE_PARTICIPANT",US="setMatchUpStatus",PS="SUBSTITUTION",gP="SCHEDULE",RG="PENALTY",DS="REFEREE",IP="STATUS",NS="START",hP="SCORE",MS="END",kO={REPLACE_TEAM_POSITION_METHOD:pP,ASSIGN_TEAM_POSITION_METHOD:mP,REMOVE_TEAM_POSITION_METHOD:yS,REPLACE_PARTICIPANT:fP,SUBSTITUTION_METHOD:lP,REMOVE_SUBSTITUTION:ES,REMOVE_PARTICIPANT:fg,SCHEDULE_METHOD:US,SUBSTITUTION:PS,SCHEDULE:gP,PENALTY:RG,REFEREE:DS,STATUS:IP,SCORE:hP,START:NS,END:MS};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===_r&&o.sideNumber&&o.sides?.filter(F=>F.particiapntId).length===1&&f?.participant?.person?.sex,I=o.matchUpType,S=(s??n?.participants?.enforceGender)!==!1?o.gender:void 0,A=o.sides?.flatMap(F=>F.participant?.individualParticipants||F.participant).filter(Boolean)?.map(gt),D=o.sides?.filter(F=>!c||F.sideNumber===c).flatMap(F=>F.participant?.individualParticipants||F.participant).filter(Boolean),y=D?.map(gt),U=e?.find(F=>F.matchUpId===o.matchUpTieId)?.sides?.map(F=>F.participant?.individualParticipants.filter(({participantId:L,person:v})=>!y?.includes(L)&&(!S||S===Fn||v.sex===S||S===_r&&!g||g&&v.sex!==g))),M=c?U?.[c-1]:U?.map((F,L)=>({participants:F,sideNumber:L+1})),P=c?U?.[c-1]?.map(gt):U?.map((F,L)=>({participants:F?.map(gt),sideNumber:L+1})),N=c&&(ie(Ia)(I)&&!y?.length||ie(vi)(I)&&(y?.length??0)<2)||!c&&(ie(Ia)(I)&&(y?.length??0)<2||ie(vi)(I)&&(y?.length??0)<4),C=P?.filter(F=>!A?.includes(F)),O=M?.filter(({participantId:F})=>C.includes(F));if(N&&C?.length&&l.push({availableParticipantIds:C,method:mP,availableParticipants:O,type:ds,payload:{participantId:void 0,tieMatchUpId:u,sideNumber:c,drawId:m}}),y?.length&&(!Ie(p)||d?.substitutions?.length)&&l.push({method:yS,type:fg,existingParticipantIds:y,payload:{participantId:void 0,tieMatchUpId:u,drawId:m}}),O?.length&&(!c&&y?.length||c&&d?.participant)&&l.push({availableParticipantIds:C,method:pP,availableParticipants:O,type:fP,existingParticipantIds:y,payload:{existingParticipantId:void 0,participantId:void 0,tieMatchUpId:u,drawId:m}}),Rn({policyActions:i,action:ES})&&d?.substitutions?.length){let F=d.participant?.participantType===ht&&[d.participantId]||d.participant?.participantType===dt&&d.participant.individualParticipantIds||[],L=d.substitutions.map(v=>v.participantId).filter(v=>F.includes(v));(!a||L.includes(a))&&l.push({method:yS,type:ES,substitutedParticipantIds:L,payload:{participantId:void 0,tieMatchUpId:u,drawId:m}})}let b=t?.[ze],x=b?.substituteWithoutScore,w=b?.substituteAfterCompleted;if(Rn({policyActions:i,action:PS})&&r.length===2&&(!c&&y?.length||c&&d?.participant)&&(x||Ie(p))&&(w||p.matchUpStatus&&!ae.includes(p.matchUpStatus))&&D?.length&&M.length){let F=D.map(gt);l.push({info:"list of team players available for substitution",method:lP,availableParticipantIds:P,existingParticipantIds:F,availableParticipants:M,existingParticipants:D,type:PS,payload:{substituteParticipantId:void 0,existingParticipantId:void 0,sideNumber:c,matchUpId:u,drawId:m}})}return l}function BO({tournamentParticipants:t=[],possiblyDisablingAction:e,activeDrawPositions:r,positionAssignments:n,returnParticipants:o,appliedPolicies:i,drawDefinition:s,drawPosition:a,validActions:c,structureId:u,structure:p,drawId:m,event:d}){if(r.includes(a))return{};let l=c.find(U=>U.type===ds)?.availableParticipantIds,f=i?.[no]?.otherFlightEntries,g=i?.[no]?.restrictQualifyingAlternates,I=(s.entries??[]).filter(({entryStage:U})=>!g||(p.stage===at?U===at:U!==at)).sort((U,M)=>(U.entryPosition??1/0)-(M.entryPosition??1/0)).map(({participantId:U})=>U).filter(Boolean),{allPositionedParticipantIds:h}=JI({drawDefinition:s}),S=n.map(U=>U.participantId).filter(Boolean),T=I.filter(U=>p.stage&&[at,tt,ce].includes(p.stage)?!h?.includes(U):!S.includes(U)),D=(d?.entries??[]).filter(U=>U.entryStatus===wr&&SP({restrictQualifyingAlternates:g,structure:p,entry:U})&&(p.stage&&[at,tt,ce].includes(p.stage)?!h?.includes(U.participantId):!S.includes(U.participantId))).sort((U,M)=>(U.entryPosition??1/0)-(M.entryPosition??1/0)).map(U=>U.participantId),y=pt(T.concat(D));if(f){let M=(d?Ht({event:d}).flightProfile:void 0)?.flights?.filter(P=>P.drawId!==m).map(P=>P.drawEntries.filter(N=>N.participantId&&![Ao,Lr,pi].includes(N.entryStatus)&&!I.includes(N.participantId)).map(({participantId:N})=>N)).flat().filter(Boolean);M?.length&&y.push(...M)}l?.length&&(y=y.filter(U=>!l.includes(U)));let E=o?t?.filter(U=>y.includes(U.participantId)):void 0;return E?.forEach(U=>{let M=(s.entries??[]).find(P=>P.participantId===U.participantId);U.entryPosition=M?.entryPosition}),E?.sort((U,M)=>(U.entryPosition||1/0)-(M.entryPosition||1/0)),y.length?{validAlternatesAction:rt({payload:{drawId:m,structureId:u,drawPosition:a},willDisableLinks:e,method:CO,availableAlternatesParticipantIds:y,type:ug,availableAlternates:E})}:{}}function SP({restrictQualifyingAlternates:t,structure:e,entry:r}){let{stage:n}=e;if(!r.entryStage||r.entryStage===n||n===at&&!t||r.entryStage===tt&&n===Ve)return!0}function HO({eventEntries:t,structure:e}){let r=o=>o.entryStatus===wr&&SP({structure:e,entry:o}),n=(o,i)=>(o.entryPosition||1/0)-(i.entryPosition||1/0);return t.filter(r).sort(n).map(gt)}function WO({restrictAdHocRoundParticipants:t,tournamentParticipants:e,matchUpParticipantIds:r,otherFlightEntries:n,drawDefinition:o,structureId:i,sideNumber:s,matchUpId:a,structure:c,matchUp:u,drawId:p,event:m}){let d=[],l=(c?.matchUps??[]).filter(({roundNumber:y})=>y===u.roundNumber),f=o?.entries?.filter(({entryStatus:y})=>y&&qo.includes(y)).map(gt)??[],g=l.map(y=>(y.sides??[]).flatMap(gt)).flat().filter(Boolean),I=f.filter(y=>!r.includes(y)&&(!t||!g.includes(y))),h=e?.filter(y=>I?.includes(y.participantId)).map(y=>J(y,void 0,!0));h?.forEach(y=>{let E=(o.entries??[]).find(U=>U.participantId===y.participantId);y.entryPosition=E?.entryPosition}),I.length&&d.push({payload:{drawId:p,matchUpId:a,structureId:i,sideNumber:s},method:dP,type:ds,availableParticipantIds:I,participantsAvailable:h});let S=m?.entries??[],T=HO({eventEntries:S,structure:c}),A=pt(f.concat(T));if(n){let E=(m?Ht({event:m}):void 0)?.flights?.filter(U=>U.drawId!==p).flatMap(U=>U.drawEntries.filter(M=>M.participantId&&![Ao,Lr,pi].includes(M.entryStatus)).map(({participantId:M})=>M)).filter(Boolean);E?.length&&A.push(...E)}A=A.filter(y=>!r.includes(y)&&!I.includes(y)&&(!t||!g.includes(y)));let D=e?.filter(y=>A.includes(y.participantId)).map(y=>J(y,void 0,!0));return D?.forEach(y=>{let E=(o.entries??[]).find(U=>U.participantId===y.participantId);y.entryPosition=E?.entryPosition}),D?.sort((y,E)=>(y.entryPosition||1/0)-(E.entryPosition||1/0)),A.length&&d.push({payload:{drawId:p,matchUpId:a,structureId:i,sideNumber:s},availableParticipantIds:A,participantsAvailable:D,method:dP,type:wr}),!Ie(u)&&s&&u.sides?.find(E=>E.sideNumber===s)?.participantId&&d.push({payload:{drawId:p,matchUpId:a,structureId:i,sideNumber:s},method:GO,type:fg}),d}function hd(t){if(!t)return{error:G};let{drawDefinition:e,event:r}=t,{restrictAdHocRoundParticipants:n=!0,policyDefinitions:o,enforceGender:i,participantId:s,sideNumber:a,matchUpId:c}=t,u=t.tournamentRecord??(t.tournamentId&&$e(t.tournamentId)&&t.tournamentRecords?.[t.tournamentId]);if(!u)return{error:W};if(!c||!$e(c))return{error:ke};if(a&&![1,2].includes(a))return _({result:{error:G},context:{sideNumber:a}});if(!e){let it=(le({tournamentRecord:u}).matchUps??[]).find(ut=>ut.matchUpId===c);r=(u?.events??[]).find(ut=>ut.eventId===it?.eventId);let ot=(r?.drawDefinitions??[]).find(ut=>ut.drawId===it?.drawId);ot&&(e=ot)}if(!e)return{error:X};let p=Yt({withIndividualParticipants:!0,tournamentRecord:u}).participants,{drawId:m}=e,{matchUp:d,structure:l}=xt({drawDefinition:e,matchUpId:c,event:r});if(!d)return{error:Oe};let f=Pt({tournamentRecord:u,drawDefinition:e,structure:l,event:r}).appliedPolicies??{};Object.assign(f,o??{});let g=f?.[no]?.otherFlightEntries,I=f?.[ze]??us[ze],{enabledStructures:h}=TS({actionType:SS,appliedPolicies:f,drawDefinition:e,structure:l}),{policyActions:S}=AS({enabledStructures:h,drawDefinition:e,structure:l}),T=t.matchUpsMap??Ae({drawDefinition:e}),A=t.inContextDrawMatchUps??re({tournamentParticipants:p,inContext:!0,drawDefinition:e,matchUpsMap:T,event:r}).matchUps,D=A?.find(Q=>Q.matchUpId===c),y=a&&D?.sides?.find(Q=>Q.sideNumber===a),E=D?.sides?.map(Q=>Q.participantId||Q.participant?.participantid).filter(Boolean)??[],{assignedPositions:U,allPositionsAssigned:M}=de({structure:l}),{structureId:P}=l??{},N=[];if(!P)return{validActions:N};let C=fr({structure:l}),O=d.collectionId;if(C&&!O){let Q=WO({restrictAdHocRoundParticipants:n,tournamentParticipants:p,matchUpParticipantIds:E,otherFlightEntries:g,drawDefinition:e,structureId:P,sideNumber:a,matchUpId:c,structure:l,matchUp:d,drawId:m,event:r});N.push(...Q)}let b=Jo({drawDefinition:e,structure:l}),x=U?.filter(Q=>Q.participantId).map(Q=>Q.drawPosition),w=U?.filter(Q=>Q.bye).map(Q=>Q.drawPosition),F=d.matchUpStatus===Dt||!O&&d.drawPositions?.reduce((Q,it)=>w?.includes(it)||Q,!1);if(F)return{validActions:N,isByeMatchUp:F};Rn({policyActions:S,action:DS})&&N.push({type:DS,payload:{matchUpId:c}});let L=!Ea({matchUpStatus:d.matchUpStatus}),v=f?.scoring?.structures,B=l?.stage&&v?.stage&&v?.stage[l.stage],H=l?.stageSequence&&B?.stageSequence&&B.stageSequence[l.stageSequence],V=!(f?.scoring?.requireAllPositionsAssigned||B?.requireAllPositionsAssigned||H?.requireAllPositionsAssigned)||M,Y=d.sides&&d.sides.filter(Q=>Q?.participantId).length===2,$=d.matchUpStatus&&[ge,Ne].includes(d.matchUpStatus),k=er({inContextDrawMatchUps:A,drawDefinition:e,matchUpId:c}),K=Ai({inContextDrawMatchUps:A,drawDefinition:e,targetData:k}),q=(D?.drawPositions?.length===2&&D.drawPositions.every(Q=>x?.includes(Q))&&D?.sides?.length===2&&D.sides.every(({participantId:Q})=>Q)||Y)&&!($&&K),nt={method:gS,type:Ys,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:US,type:gP}),Rn({policyActions:S,action:Ys})&&(y?.participant||!a&&E?.length)&&N.push(nt),L&&q&&N.push({type:IP}),V&&q){let{matchUpId:Q,matchUpFormat:it}=d,ot={drawId:m,matchUpId:Q,matchUpFormat:it,outcome:{scoreStringSide1:void 0,scoreStringSide2:void 0,sets:[]},winningSide:void 0};N.push({info:"set outcome and winningSide",method:US,type:hP,payload:ot}),Rn({policyActions:S,action:NS})&&N.push({type:NS}),Rn({policyActions:S,action:MS})&&N.push({type:MS})}if(O&&D){let Q=VO({specifiedPolicyDefinitions:o,inContextDrawMatchUps:A,matchUpParticipantIds:E,matchUpActionsPolicy:I,inContextMatchUp:D,policyActions:S,enforceGender:i,participantId:s,sideNumber:a,matchUpId:c,matchUp:d,drawId:m,side:y});N.push(...Q)}return{structureIsComplete:b,validActions:N,isDoubleExit:$,...R}}function jO({tournamentParticipants:t=[],sourceStructuresComplete:e,possiblyDisablingAction:r,isWinRatioFedStructure:n,activeDrawPositions:o,positionAssignments:i,drawDefinition:s,drawPosition:a,structureId:c,structure:u,drawId:p,event:m}){if(o.includes(a)||n&&!e)return{};let{sourceStructureIds:d,targetStructureIds:l}=s.links?.reduce((h,S)=>{let T=S.source?.structureId,A=S.target?.structureId;return h.sourceStructureIds.includes(T)||h.sourceStructureIds.push(T),h.targetStructureIds.includes(A)||h.targetStructureIds.push(A),h},{sourceStructureIds:[],targetStructureIds:[]})||{},f=[],g=s.links?.filter(h=>h.target?.structureId===u.structureId)??[];for(let h of g){let S=h?.source?.structureId,{structure:T}=st({structureId:S,drawDefinition:s}),A=T?.finishingPosition===_i&&(d?.length!==1||l?.length!==1),D={};if(A){let{matchUps:M}=At({drawDefinition:s,structure:u,event:m}),{initialRoundNumber:P}=ss({drawPosition:a,matchUps:M}),C=s.links?.find(O=>O.target?.structureId===u?.structureId&&O.target.roundNumber===P)?.source?.roundNumber;D.roundNumbers=[C]}let{completedMatchUps:y}=uu({structureId:S,inContext:!0,matchUpFilters:D,drawDefinition:s}),E=i.map(M=>M.participantId).filter(Boolean);y?.filter(({matchUpType:M,winningSide:P})=>P&&(m?.eventType!==Fe||M===Fe)).map(({winningSide:M,sides:P})=>M&&P?.[1-(M-1)]).map(gt).filter(M=>M&&!E.includes(M))?.forEach(M=>{f.includes(M)||f.push(M)})}let I=t?.filter(h=>f?.includes(h.participantId));return I?.forEach(h=>{let S=(s.entries??[]).find(T=>T.participantId===h.participantId);h.entryPosition=S?.entryPosition}),f?.length?{validLuckyLosersAction:{type:mg,method:RO,availableLuckyLosers:I,availableLuckyLoserParticipantIds:f,willDisableLinks:r,payload:{drawId:p,structureId:c,drawPosition:a}}}:{}}function YO({positionSourceStructureIds:t,unassignedParticipantIds:e,possiblyDisablingAction:r,provisionalPositioning:n,tournamentParticipants:o,isWinRatioFedStructure:i,positionAssignments:s,returnParticipants:a,appliedPolicies:c,drawDefinition:u,seedingProfile:p,isByePosition:m,drawPosition:d,structureId:l,event:f}){let{drawId:g}=u,I=[],h,S,T=[],A=c?.[Un]?.validSeedPositions?.ignore;if(A||({unplacedSeedParticipantIds:h,unplacedSeedAssignments:S,unfilledPositions:T}=Lh({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:xO,type:Id}),i&&A){let D=s.map(P=>P.participantId).filter(Boolean),y={structureIds:t},{completedMatchUps:E}=Vs({inContext:!0,matchUpFilters:y,drawDefinition:u}),U=pt((E??[]).filter(({matchUpType:P})=>f?.eventType!==Fe||P===Fe)?.map(({sides:P})=>P?.map(gt)).flat().filter(P=>P&&!D.includes(P))),M=a?o?.filter(P=>U?.includes(P.participantId)).map(P=>J(P,void 0,!0)):void 0;return M?.forEach(P=>{let N=(u.entries??[]).find(C=>C.participantId===P.participantId);P.entryPosition=N?.entryPosition}),M?.length&&I.push(rt({payload:{drawId:g,structureId:l,drawPosition:d},willDisableLinks:r,method:cP,type:ds,availableParticipantIds:U,participantsAvailable:M})),{validAssignmentActions:I}}if(T.includes(d)||m){let D;if(S?.length){let E=S.filter(U=>h?.includes(U.participantId));E.sort(bG),D=E.map(U=>U.participantId)}else D=e;let y=a?o?.filter(E=>D.includes(E.participantId)).map(E=>J(E,void 0,!0)):void 0;y?.length&&I.push(rt({payload:{drawId:g,structureId:l,drawPosition:d},willDisableLinks:r,method:cP,type:ds,availableParticipantIds:D,participantsAvailable:y}))}return{validAssignmentActions:I}}function bG(t,e){return t.bye||gc(t.seedValue)<gc(e.seedValue)||t.seedValue&&!e.seedValue?-1:(t.seedNumber||0)-(e.seedNumber||0)}function qO({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?.[no],g=!f?.disableRoundRestrictions&&t[s],I=f?.requireCompletedStructures,{sourceStructureIds:h,relevantLinks:S}=ag({targetRoundNumber:g,linkType:oo,drawDefinition:i,structureId:a})||{};h?.length&&d.push(...h);let{sourceStructureIds:T,relevantLinks:A}=ag({targetRoundNumber:g,linkType:jn,drawDefinition:i,structureId:a})||{};T?.length&&d.push(...T);for(let D of S){let y=i.structures?.find(U=>U.structureId===D.source.structureId);if(y?.stage!==at)continue;let E=Jo({structureId:D.source.structureId,drawDefinition:i});if(!I||E){let U=y.qualifyingRoundNumber,{matchUps:M}=At({matchUpFilters:{roundNumbers:[U],hasWinningSide:!0},afterRecoveryTimes:!1,tournamentParticipants:e,inContext:!0,structure:y});for(let P of M){let N=P.sides.find(O=>O?.sideNumber===P.winningSide),C=P.matchUpStatus===Dt&&P.sides?.find(({participantId:O})=>O);if(N||C){let{participantId:O,participant:b}=N||C||{};O&&!l.includes(O)&&(b&&n&&u.push(b),p.push(O))}}}}for(let D of A){let y=i.structures?.find(U=>U.structureId===D.source.structureId);if(y?.stage!==at)continue;let E=Jo({structureId:D.source.structureId,drawDefinition:i});if(!I||E){let{positionAssignments:U}=Nt({structure:y}),M=U?.map(P=>{let N=P.participantId,C=mt({element:P,name:Ho}).extension?.value;return C?{participantId:N,groupOrder:C?.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:NO,type:Np,qualifyingParticipantIds:p,qualifyingParticipants:n?u:void 0})),{validAssignmentActions:m,sourceStructureIds:d}}function $O({onlyAssignedPositions:t=!0,possiblyDisablingAction:e,tournamentParticipants:r,inactiveDrawPositions:n,activeDrawPositions:o,positionAssignments:i,returnParticipants:s,byeDrawPositions:a,drawDefinition:c,isByePosition:u,drawPosition:p,structureId:m,structure:d,drawId:l,event:f}){if(o.includes(p))return{};let g=P=>!t||P.participantId||P.qualifier||P.bye,I=n?.filter(P=>P!==p&&!(u&&a.includes(P))),h=i?.filter(P=>g(P)&&I?.includes(P.drawPosition))??[],S=h.map(({drawPosition:P})=>P),{matchUps:T}=At({afterRecoveryTimes:!1,inContext:!0,drawDefinition:c,structure:d,event:f}),A=T.filter(({drawPositions:P})=>xe(P,S)),D=Object.assign({},...A.map(P=>P.sides?.filter(({sourceDrawPositionRange:N})=>N).map(({drawPosition:N,sourceDrawPositionRange:C})=>({[N]:C}))).flat()),y=h.map(P=>P.participantId).filter(Boolean),E=(r??[]).filter(P=>y.includes(P.participantId)),U=Object.assign({},...E.map(P=>({[P.participantId]:P}))),M=h.map(P=>{let N=U?.[P.participantId],C=D[P.drawPosition];return rt({...P,participant:s?J(N,!1,!0):void 0,sourceDrawPositionRange:C})});return M.length?{validSwapAction:{payload:{drawId:l,structureId:m,drawPositions:[p]},willDisableLinks:e,method:bO,type:dg,availableAssignments:M}}:{}}function CS(t){let e=lt(t,[{event:!0,drawDefinition:!0,structureId:!0}]);if(e.error)return e;let{policyDefinitions:r,returnParticipants:n=!0,provisionalPositioning:o,tournamentRecord:i,drawDefinition:s,drawPosition:a,event:c}=t,u=t.tournamentParticipants??(i&&Yt({withIndividualParticipants:!0,tournamentRecord:i}).participants)??[],p=st({structureId:t.structureId,drawDefinition:s});if(p.error)return p;let m=p.containingStructure||p.structure;if(!m)return{error:Lt};let d=m.structureId;if(p=Ua({drawDefinition:s,structureId:d}),a===void 0&&!p.isAdHoc)return{error:Es};if(p.isAdHoc)return hd(t);if(p.error)return p;let{drawPositionInitialRounds:l,inactiveDrawPositions:f,activeDrawPositions:g,byeDrawPositions:I}=p,h=Pt({tournamentRecord:i,drawDefinition:s,structure:m,event:c}).appliedPolicies??{};Object.assign(h,r??{});let{actionsPolicy:S,enabledStructures:T,actionsDisabled:A}=TS({actionType:lg,appliedPolicies:h,drawDefinition:s,structure:m}),D=S?.activePositionOverrides||[],{sourceStructureIds:y}=ag({finishingPosition:vs,targetRoundNumber:1,linkType:jn,drawDefinition:s,structureId:d})||{},E;y?.length&&(E=y.reduce((z,q)=>Jo({structureId:q,drawDefinition:s})&&z,!0));let U=y.length,M=y.length&&!E,{policyActions:P}=AS({enabledStructures:T,drawDefinition:s,structure:m}),N=![at,tt].includes(m.stage)||m.stageSequence!==1,{drawId:C}=s,O=[],{assignedPositions:b,positionAssignments:x}=de({structure:m}),w=b?.find(z=>z.drawPosition===a);if(!x?.map(z=>z.drawPosition)?.includes(a))return{error:ys};let{stage:L,stageSequence:v}=m,B=[L];L===Ve&&B.push(tt),L===tt&&B.push(Ve);let H=mi({entryStatuses:qo,provisionalPositioning:o,drawDefinition:s,stageSequence:v,structureId:d,stages:B}),j=Si({drawDefinition:s,stages:B}).assignedParticipantIds??[],V=H.filter(z=>!j.includes(z.participantId)).map(z=>z.participantId),Y=I.includes(a),$=g.includes(a);if(A)return{hasPositionAssigned:!!w,info:"Actions Disabled for structure",isActiveDrawPosition:$,isDrawPosition:!0,validActions:[],isByePosition:Y};if(Rn({policyActions:P,action:ds})&&!$&&x&&!M&&(!w||Y)){let{validAssignmentActions:z}=YO({positionSourceStructureIds:y,unassignedParticipantIds:V,possiblyDisablingAction:N,isWinRatioFedStructure:U,tournamentParticipants:u,positionAssignments:x,returnParticipants:n,appliedPolicies:h,drawDefinition:s,isByePosition:Y,drawPosition:a,structureId:d,event:c});z?.forEach(q=>O.push(q))}if(Rn({policyActions:P,action:Np})){let{validAssignmentActions:z}=qO({drawPositionInitialRounds:l,tournamentParticipants:u,positionAssignments:x,returnParticipants:n,appliedPolicies:h,drawDefinition:s,drawPosition:a,structureId:d,drawId:C});z?.forEach(q=>O.push(q))}let{participantId:k}=w||{},K=k&&u.find(z=>z.participantId===k);if(w){Rn({policyActions:P,action:IS})&&!$&&(O.push({type:IS,method:aP,payload:{drawId:C,structureId:d,drawPosition:a},willDisableLinks:N}),Y||O.push({type:pg,method:MO,payload:{drawId:C,structureId:d,drawPosition:a},willDisableLinks:N}),Rn({policyActions:P,action:Id})&&!Y&&O.push({type:Id,method:aP,payload:{drawId:C,structureId:d,drawPosition:a,replaceWithBye:!0},willDisableLinks:N}));let z=m.stage===at||m.stage===tt&&m.stageSequence===1;if(!Y&&uP({activePositionOverrides:D,activeDrawPositions:g,action:js})&&Rn({policyActions:P,action:js})&&Tp({drawDefinition:s,structureId:d,drawPosition:a})&&z){let{seedAssignments:q}=Fr({returnAllProxies:!0,drawDefinition:s,structure:m}),{seedNumber:nt,seedValue:Q}=q?.find(it=>it.participantId===k)??{};O.push({type:js,method:wO,participant:K,seedNumber:nt,payload:{drawId:C,structureId:d,participantId:k,seedValue:Q}})}if(!Y&&uP({activePositionOverrides:D,activeDrawPositions:g,action:Mp})&&Rn({policyActions:P,action:Mp})&&Tp({drawDefinition:s,structureId:d,drawPosition:a})&&z){let{seedAssignments:q}=Fr({returnAllProxies:!0,drawDefinition:s,structure:m}),{seedNumber:nt}=q?.find(Q=>Q.participantId===k)??{};O.push({method:vO,type:Mp,participant:K,seedNumber:nt,payload:{participantId:k,structureId:d,drawId:C}})}if(!Y&&k){if(Rn({policyActions:P,action:Ys})){let q={type:Ys,method:gS,participant:K,payload:{penaltyCode:void 0,penaltyType:void 0,participantIds:[],notes:void 0,drawId:C}};O.push(q)}if(Rn({policyActions:P,action:Uu})){let q={type:Uu,method:_O,participant:K,payload:{participantId:k,otherName:void 0}};O.push(q)}}if(Rn({policyActions:P,action:dg})){let{validSwapAction:q}=$O({possiblyDisablingAction:N,tournamentParticipants:u,inactiveDrawPositions:f,activeDrawPositions:g,positionAssignments:x,returnParticipants:n,byeDrawPositions:I,drawDefinition:s,isByePosition:Y,drawPosition:a,structureId:d,structure:m,drawId:C});q&&O.push(q)}}if(Rn({policyActions:P,action:ug})&&!M){let{validAlternatesAction:z}=BO({possiblyDisablingAction:N,tournamentParticipants:u,positionAssignments:x,activeDrawPositions:g,returnParticipants:n,appliedPolicies:h,drawDefinition:s,drawPosition:a,validActions:O,structureId:d,structure:m,drawId:C,event:c});z&&O.push(z)}if(Rn({policyActions:P,action:mg})&&!M&&x){let{validLuckyLosersAction:z}=jO({sourceStructuresComplete:E,possiblyDisablingAction:N,isWinRatioFedStructure:U,tournamentParticipants:u,activeDrawPositions:g,positionAssignments:x,drawDefinition:s,drawPosition:a,structureId:d,structure:m,drawId:C});z&&O.push(z)}if(K?.participantType===dt&&Rn({policyActions:P,action:cg})){let{validModifyAssignedPairAction:z}=FO({tournamentParticipants:u,returnParticipants:n,drawPosition:a,participant:K,drawId:C,event:c});z&&O.push(z)}return{hasPositionAssigned:!!w,isActiveDrawPosition:$,isDrawPosition:!0,isByePosition:Y,validActions:O,...R}}function Pu({policyDefinitions:t,appliedPolicies:e,drawType:r}){let n=t?.[hm]?.drawTypeCoercion,o=e?.[hm]?.drawTypeCoercion;return(typeof n=="boolean"?n:void 0)??(r&&n?.[r])??(typeof o=="boolean"?o:void 0)??(r&&o?.[r])??!0}function Cp({tournamentRecord:t,drawDefinition:e,stage:r=tt,structureId:n,structure:o}){if(!t)return{error:W};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}=Nt({drawDefinition:e,structureId:n,structure:o});return{positionAssignments:s??[],structureId:o?.structureId,error:i}}function RS({structureId:t,drawDefinition:e}){if(!e)return{error:X};if(!$e(t))return{error:G};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=!jt([ai,sn,ip,si],n).length;return{...R,valid:o}}function bS({participantsCount:t,participantCount:e}){if(t=t??e,!t)return{error:G};let r=qi(t);return r?{drawSize:r}:_({result:{error:G},stack:"getEliminationDrawSize",context:{participantsCount:t}})}function Du(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=yo({tournamentRecord:i,drawDefinition:s,event:a});if(I.error)return _({result:I,stack:c});r=I.policyDefinitions}let p=ft(u);if(u&&!p)return _({result:{error:G},context:{participantsCount:u},stack:c});if(o&&!p)return _({result:{error:vy},stack:c});if(isNaN(n))if(u)({drawSize:n}=bS({participantsCount:u}));else return _({result:{error:ja},stack:c});let m=o&&u||n;if(m&&m>n)return{error:Nl};let d=r?.[Un];if(!d)return{error:Ey};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:ay}}function Sd({consideredEntries:t,policyDefinitions:e,tournamentRecord:r,appliedPolicies:n,participantMap:o,enforceGender:i,participants:s,event:a}){if((!s||!o)&&r&&({participants:s,participantMap:o}=Yt({tournamentRecord:r})),!s)return{error:$a};if(!Array.isArray(s))return{error:G};if(!a)return{error:Et};let c=e?.[ze]??n?.[ze]??us[ze],u=(i??c?.participants?.enforceGender)!==!1,{eventType:p,gender:m}=a,d=p===gi,l=p===kr&&kt||d&&dt||ht,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=OG({participant:S,participantType:l,eventType:p,entryStatusMap:f}),A=_G({genderEnforced:u,participantMap:o,eventGender:m,participant:S,isDoubles:d,mismatch:T});return T||!A});if(h.length){let S=h.map(T=>T.participantId);return{error:Iy,invalidParticipantIds:S}}return{...R,valid:!0}}function OG({participant:t,participantType:e,eventType:r,entryStatusMap:n}){let o=n[t.participantId],i=r&&[gi,kr].includes(r)&&t.participantType===ht&&(Bs(o)||o===Ao);return t.participantType!==e&&!i}function _G(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||Fn===n||[ee,ue].includes(n)&&a[0]===n||_r===n&&(a.length==1&&e.individualParticipantIds?.length===1||a.length===2),u=e?.person?.sex,p=!e?.person||!n||[Fn,_r].includes(n)||[ee,ue].includes(n)&&u===n;return!s||c&&p}function OS({qualifyingProfiles:t,appliedPolicies:e,idPrefix:r,isMock:n,uuids:o}){let i="generateQualifyingSTructures",s=[],a=[],c=[],u=(g,I)=>g.stageSequence-I.stageSequence,p=(g,I)=>g.roundTarget-I.roundTarget,m=0,d=0,l,f=1;for(let g of t.sort(p)){let I=g.structureProfiles||[];f=g.roundTarget||f;let h=1,S=0,T,A,D;for(let y of(I||[]).sort(u)){let E=am(y.drawSize||y.participantsCount),{qualifyingRoundNumber:U,structureOptions:M,matchUpFormat:P,structureName:N,structureId:C,drawType:O}=y,b=y.matchUpType,x=y.qualifyingPositions||vG({drawSize:E,qualifyingRoundNumber:U}),w,F,L;if(!ft(E))return _({result:{error:ja},stack:i});let v=t.length>1?`${f}-`:"",B=I.length>1||v?h:"",H=N||(v||B?`${Ye(at)} ${v}${B}`:Ye(at));if(O===dn){let{structures:j,groupCount:V,maxRoundNumber:Y}=Da({structureName:y.structureName||H,structureId:C||o?.pop(),stage:at,structureOptions:M,appliedPolicies:e,stageSequence:h,matchUpType:b,roundTarget:f,drawSize:E,idPrefix:r,isMock:n,uuids:o});S=V,w=Y,F=j[0],l=[1]}else({drawSize:E,matchUps:L,roundLimit:w}=fn({qualifyingRoundNumber:U,qualifyingPositions:x,matchUpType:b,drawSize:E,idPrefix:r,isMock:n,uuids:o})),F=en({structureName:y.structureName||H,structureId:C||o?.pop(),qualifyingRoundNumber:w,stage:at,matchUpFormat:P,stageSequence:h,matchUpType:b,roundLimit:w,matchUps:L}),f&&St({extension:{name:mn,value:f},element:F}),S=L?.filter(j=>j.roundNumber===w)?.length||0;if(h>1){let{link:j}=Na({sourceStructureId:A,sourceRoundNumber:T,targetStructureId:F.structureId,finishingPositions:D===jn?[1]:void 0,linkType:D});c.push(j),m+=(E||0)-S}else m+=E||0;D=O===dn?jn:oo,A=F.structureId,T=w,a.push(F),h+=1}d+=S,s.push({qualifiersCount:S,finalQualifyingRoundNumber:T,finalQualifyingStructureId:A,finishingPositions:l,roundTarget:f,linkType:D}),f+=1}return{qualifiersCount:d,qualifyingDrawPositionsCount:m,qualifyingDetails:s,structures:a,...R,links:c}}function vG({drawSize:t,qualifyingRoundNumber:e}){let r=t,n=0;for(;n<e;)r=Math.floor(r/2),n+=1;return r}function _S(t){let{drawTypeCoercion:e,enforceMinimumDrawSize:r}=t,n=ct(t.drawSize),o=e&&(typeof e=="boolean"||e<=2)&&n===2&&io||t.drawType||io,i=GE.includes(o);if(n&&i){if(e&&(typeof e=="boolean"&&n<4||n<=e))o=io;else if(n<4&&r)return{..._({context:{enforceMinimumDrawSize:r,drawSize:n,drawType:o},result:{error:Vu},stack:"getCoercedDrawType"}),drawType:o}}return{drawType:o}}function KO(t){let{drawDefinition:e,structureOptions:r,requireSequential:n}=t,o={structureName:Ye(tt),...t,stage:tt},{structures:i,groupCount:s,groupSize:a}=Da(o);if(s<1)return{error:Qy};let c=r?.playoffGroups||[{finishingPositions:[1],structureName:Ye(ce)}],[u]=i,{structures:p,links:m}=eS({sourceStructureId:u.structureId,requireSequential:n,drawDefinition:e,playoffGroups:c,groupCount:s,groupSize:a,...t});return p&&i.push(...p),{...R,structures:i,links:m}}function zO({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?sn:ai,f=1+m;return{linkType:Yn,source:{roundNumber:f,structureId:t.structureId},target:{feedProfile:l,roundNumber:p,structureId:e.structureId}}}),c={linkType:oo,source:{roundNumber:s,structureId:e.structureId},target:{feedProfile:sn,roundNumber:i,structureId:t.structureId}},u=[{linkType:oo,source:{roundNumber:i,structureId:t.structureId},target:{feedProfile:sn,roundNumber:1,structureId:r.structureId}},{linkType:Yn,source:{roundNumber:i,structureId:t.structureId},target:{feedProfile:sn,roundNumber:1,structureId:r.structureId}}];return[...a,c,...u]}function QO({structureName:t,matchUpType:e,idPrefix:r,drawSize:n,isMock:o,uuids:i}){let s=[],{matchUps:a}=Zo({linkFedFinishingRoundNumbers:[1],drawSize:n+1,matchUpType:e,idPrefix:r,isMock:o}),c=ps({structureName:t||Ye(tt),structureId:i?.pop(),stageSequence:1,stage:tt,matchUpType:e,matchUps:a});s.push(c);let u=n/2,{matchUps:p}=Zo({finishingPositionOffset:u,idPrefix:r&&`${r}-c`,drawSize:n-1,isConsolation:!0,matchUpType:e,isMock:o,uuids:i}),m=ps({structureName:Ye(FE),matchUps:p,structureId:i?.pop(),stage:Ve,stageSequence:2,matchUpType:e});s.push(m);let{matchUps:d}=fn({idPrefix:r&&`${r}-p1t2`,drawSize:2,matchUpType:e,isMock:o}),l=ps({structureName:Ye(LE),matchUps:d,structureId:i?.pop(),stageSequence:3,stage:ce,matchUpType:e});s.push(l);let f=zO({mainStructure:c,consolationStructure:m,deciderStructure:l});return{structures:s,links:f,...R}}function XO(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(Tn(s))return fn(t);let u=xG(s),p=u.shift(),m=Z(1,(p?.participantsCount||0)+1).map(I=>({drawPosition:I})),d=[],l=1;({matchUps:d}=Ep({roundNumber:l,matchUpType:o,idPrefix:i,matchUps:d,isMock:a,nodes:m,uuids:c})),l++;let f=t.roundLimit||e;for(let I of u){let h=I.participantsCount/2,S=Z(1,h+1);n&&h===n&&(f=l-1);let T=S.map(A=>{let D=od({roundPosition:A,roundNumber:l,idPrefix:i,uuids:c});return{roundPosition:A,roundNumber:l,matchUpId:D}});d.push(...T),l++}let g=l-1;return d=ha({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 xG(t){let e=ct(t),r=e%2?e+1:e,n=!!(Math.ceil(r/2)%2),o=[{participantsCount:r,preFeedRound:n}];for(;r>2;){let i=Math.ceil(r/2),s=i===1,a=!!(!s&&i%2);r=!s&&a?i+1:i;let c=!!(r!==2&&Math.ceil(r/2)%2);o.push({participantsCount:r,preFeedRound:c,feedRound:a})}return o}function vS(t){let{playoffAttributes:e,stageSequence:r=1,stage:n=tt,matchUpType:o,drawSize:i,uuids:s}=t,a=()=>!t.isMock&&!t.idPrefix?void 0:`${t.drawDefinition.drawId}-s-0`,c=t.structureId||a()||s?.pop(),u=t.appliedPolicies??Pt(t),p=t.policyDefinitions?.[ec]||u?.[ec];t.skipRounds=t.skipRounds||i<=4&&(p?.feedFromMainFinal?0:1)||0;let m=t.structureName??e?.["0"]?.name??Ye(tt),d=()=>{let{matchUps:f}=fn(t);return{structures:[en({stageSequence:r,structureName:m,matchUpType:o,structureId:c,matchUps:f,stage:n})],links:[],...R}};return{generators:{[an]:()=>({structures:[en({finishingPosition:vs,stageSequence:r,structureName:m,matchUps:[],matchUpType:o,structureId:c,stage:n})],links:[],...R}),[Oi]:()=>{let{matchUps:f}=XO(t);return{structures:[en({stageSequence:r,structureName:m,matchUpType:o,structureId:c,matchUps:f,stage:n})],links:[],...R}},[io]:()=>d(),[Jc]:()=>QO(t),[Qc]:()=>Tc({...t,roundOffsetLimit:3,playoffAttributes:e??of}),[Xc]:()=>Tc({...t,roundOffsetLimit:2,playoffAttributes:e??sf}),[ce]:()=>Tc(t),[la]:()=>{let{matchUps:f}=Zo({drawSize:i,uuids:s,matchUpType:o});return{structures:[en({stageSequence:r,structureName:m,matchUpType:o,structureId:c,stage:tt,matchUps:f})],links:[],...R}},[sp]:()=>Xh(t),[Zc]:()=>yc({...t,feedRounds:1,fmlc:!0}),[wE]:()=>yc({...t,feedRounds:1}),[zI]:()=>yc({...t,feedsFromFinal:1}),[QI]:()=>yc({...t,feedsFromFinal:2}),[XI]:()=>yc({...t,feedsFromFinal:3}),[ap]:()=>yc(t),[nf]:()=>Zh(t),[dn]:()=>Da(t),[so]:()=>KO(t)}}}function Td(t){let{enforceMinimumDrawSize:e=!0,overwriteExisting:r,appliedPolicies:n,staggeredEntry:o,drawDefinition:i,tieFormat:s,isMock:a,uuids:c}=t||{},u=ct(t.drawSize),p=t.drawTypeCoercion??Pu({appliedPolicies:n,drawType:t.drawType}),m="generateDrawStructuresAndLinks",d=_S({drawType:t.drawType,enforceMinimumDrawSize:e,drawTypeCoercion:p,drawSize:u});if(d.error)return d;let l=d.drawType,f=[],g=[],I=t?.matchUpType??Xt,h=i?.structures?.filter(({stage:j})=>j===at);h&&f.push(...h);let S=h?.map(({structureId:j})=>j),T=i?.structures?.find(({stage:j,stageSequence:V})=>j===tt&&V===1),A=i?.links?.filter(j=>j.target.structureId===T?.structureId&&S?.includes(j.source.structureId)),D=(j,V)=>{if(j.linkType===jn&&V?.structures){let Y=j.source.finishingPositions||[];return V.structures.length*Y.length}else if(j.linkType===oo&&V?.matchUps?.length){let Y=j.source.roundNumber;return V.matchUps.filter(({roundNumber:k})=>k===Y).length}},y=h?.map(j=>{let V=A?.find(z=>z.target.structureId===j.structureId),Y=Nt({structure:j})?.positionAssignments?.length??0;if(!V)return Y;let $=V?.source.structureId,k=i.structures?.find(z=>z.structureId===$),K=D(V,k)||0;return Y-K}).filter(Boolean).reduce((j,V)=>j+V,0),E=A?.map(j=>{let V=j.source.structureId,Y=h?.find($=>$.structureId===V);return D(j,Y)}).filter(Boolean).reduce((j,V)=>j+V,0),U=!!(T&&!T?.matchUps?.length);if(h?.length&&!U)return{error:AI};let M=!h?.length&&t.qualifyingProfiles,P=M?.length&&OS({idPrefix:t.idPrefix,qualifyingProfiles:M,appliedPolicies:n,isMock:a,uuids:c});if(P?.error)return P;let{qualifyingDrawPositionsCount:N,qualifyingDetails:C,qualifiersCount:O}=P||{qualifyingDrawPositionsCount:y,qualifiersCount:E};N&&(P?.structures&&f.push(...P.structures),P?.links&&g.push(...P.links)),Object.assign(t,rt({drawSize:u,matchUpType:I,tieFormat:s}));let b=l!==an&&(!u||u<2||!o&&![la,Oi].includes(l)&&([so,dn].includes(l)&&u<3||![dn,so].includes(l)&&!Tn(u)));if(b&&!N)return _({context:{drawSize:u,invalidDrawSize:b},result:{error:Vu},stack:m});let{generators:x,error:w}=vS(t);if(w)return{error:w};let F=x[l];if(!F)return{error:fl};let L=F?.();if(L.error)return L;let{structures:v,links:B}=L;if(v?.length){let j=v.find(({stage:V,stageSequence:Y})=>V===tt&&Y===1);if(T&&j){if(U){let V=j.structureId;if(j.structureId=T.structureId,B?.length)for(let Y of B)Y.source.structureId===V&&(Y.source.structureId=T.structureId),Y.target.structureId===V&&(Y.target.structureId=T.structureId)}else if(!r)return{error:AI}}f.push(...v)}f.sort(ci),B?.length&&g.push(...B);let H=L.structures.find(({stage:j,stageSequence:V})=>j===tt&&V===1);for(let j of C||[]){let{finalQualifyingRoundNumber:V,finalQualifyingStructureId:Y,roundTarget:$,finishingPositions:k,linkType:K}=j,z=H&&Na({targetStructureId:H.structureId,sourceStructureId:Y,sourceRoundNumber:V,finishingPositions:k,targetEntryRound:$,linkType:K})?.link;if(z?.error)return z;z&&g.push(z)}return A&&g.push(...A),{...R,qualifyingResult:{qualifyingDrawPositionsCount:N,qualifiersCount:O},structures:f,links:g}}function Ad(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=ir({tieFormat:s});if(T.error)return T}s=Xe(s??je({drawDefinition:i})?.tieFormat),a=a??(i.matchUpType||Xt),t.tieFormat=s,t.matchUpType=a;let c=Ip({drawDefinition:i,stage:tt});t.drawSize=t.drawSize??c,!c&&t.drawSize&&yp({drawSize:t.drawSize,drawDefinition:i,stageSequence:r,stage:tt});let u=Ae({drawDefinition:i}).drawMatchUps.map(fe),p=Td(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&&!Ip({stage:at,drawDefinition:i})){let A=yp({drawSize:l.qualifyingDrawPositionsCount,stage:at,drawDefinition:i});if(A.error)return A}if(f){let T=zh({qualifiersCount:f,drawDefinition:i,stage:tt});if(T.error)return T}let g=t.drawSize??c;Object.assign(t,rt({drawSize:g,matchUpType:a,tieFormat:s}));let{matchUps:I,matchUpsMap:h}=re({drawDefinition:i});s&&I?.forEach(T=>{if(!u.includes(T.matchUpId)){let{tieMatchUps:A}=Ma({tieFormat:s,matchUp:T,isMock:n});Object.assign(T,{tieMatchUps:A,matchUpType:a})}});let{inContextDrawMatchUps:S}=wi({drawDefinition:i,matchUpsMap:h});return bt({tournamentId:t.tournamentRecord?.tournamentId,drawDefinition:i}),{inContextDrawMatchUps:S,drawDefinition:i,matchUpsMap:h,...R,structures:m,matchUps:I,links:d}}function Pc(t){let{tournamentRecord:e,scaleAttributes:r,participantId:n}=t,o=t.tournamentRecords||e&&{[e.tournamentId]:e}||{};if(!n)return{error:oe};let{participant:i,tournamentId:s}=xo({tournamentRecords:o,tournamentRecord:e,participantId:n});return i?{...uo({participant:i,scaleAttributes:r}),tournamentId:s}:{error:Zt}}function ba(t){let{removePriorValues:e,tournamentRecord:r,participantId:n,scaleItem:o}=t,i,s;if(!JO({scaleItem:o}))return{error:ju};if(n&&Array.isArray(r.participants)&&(s=r.participants.find(a=>a.participantId===n),s)){let a=ZO({removePriorValues:e,participant:s,scaleItem:o});if(a.error)return a;i=!a.valueChanged;let{topics:c}=Cr();c.includes(Qe)&&Tt({topic:Qe,payload:{tournamentId:r.tournamentId,participants:[s]}})}return i&&{...R,info:wl,existingValue:o?.scaleValue}||s&&{...R,newValue:o?.scaleValue}||{error:Zt}}function AP(t){let{scaleItemsWithParticipantIds:e=[],removePriorValues:r,tournamentRecord:n,auditData:o,context:i}=t;if(!n)return{error:W};if(!n.participants)return{error:$a};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(JO({scaleItem:l}))Array.isArray(a[d])||(a[d]=[]),a[d].push(l);else return{error:ju}}n.participants.forEach(m=>{let{participantId:d}=m||{};Array.isArray(a[d])&&a[d].forEach(l=>{ZO({participant:m,scaleItem:l,removePriorValues:r}),c.push(m),s++})});let u=s?void 0:Ns,{topics:p}=Cr();if(p.includes(Qe)&&s&&Tt({topic:Qe,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:uf,itemValue:l};if(f&&(g.itemSubTypes=f),d||m){let{drawDefinition:I,event:h}=We({tournamentRecord:n,eventId:m,drawId:d});d&&tg({drawDefinition:I,timeItem:g}),m&&ki({event:h,timeItem:g})}else Gi({tournamentRecord:n,timeItem:g})}}return o&&p.includes(fa)&&Tt({topic:fa,payload:o}),rt({...R,modificationsApplied:s,info:u})}function JO({scaleItem:t}){let e=t&&Object.keys(t),r=["scaleType","eventType","scaleName"];return!!(r.filter(o=>e?.includes(o)).length===r.length)}function ZO({removePriorValues:t,participant:e,scaleItem:r}){if(!e)return{error:Mi};let n=r&&Object.keys(r),o=["scaleType","eventType","scaleName"];if(!(o.filter(p=>n.includes(p)&&r[p]).length===o.length))return{error:ju};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=[zi,p,m,d].join("."),f=rt({itemValue:r.scaleValue,itemDate:r.scaleDate,createdAt:s,itemType:l});r.scaleId&&(f.itemSubTypes=[r.scaleId]),t&&(e.timeItems=e.timeItems.filter(g=>g.itemType!==l)),e.timeItems.push(f)}return{...R,valueChanged:u,newValue:r.scaleValue}}var qs="ELO",yP="NTRP",wG="TRN",EP="UTR",gg="WTN",t_={ELO:qs,NTRP:yP,TRN:wG,UTR:EP,WTN:gg};var LG={[qs]:{defaultInitialization:1500,decimalsCount:0,range:[0,3e3],ascending:!0},[yP]:{accessors:["ntrpRating","dntrpRatingHundredths"],attributes:{ustaRatingType:""},accessor:"dntrpRatingHundredths",defaultInitialization:3,decimalsCount:1,ascending:!0,range:[1,7]},[EP]:{defaultInitialization:6,accessors:["utrRating"],accessor:"utrRating",decimalsCount:2,ascending:!0,range:[1,16]},[gg]:{attributes:{confidence:{generator:!0,range:[60,100]}},accessors:["wtnRating","confidence"],defaultInitialization:23,accessor:"wtnRating",ascending:!1,decimalsCount:2,range:[40,1]}},Br=LG;var FG=t=>250/Math.pow(t+5,.4),GG=()=>1;function kG(t=3,e=2){let r=t/e;return isNaN(r)?yd.kDefault():r}var yd={nSpread:400,diffThreshold:.125,kCalc:FG,kMultiplier:kG,kDefault:GG};function xS(t){let{winnerRating:e,loserRating:r,ratingRange:n}=t,{ratings:o=Br,winnerCountables:i=1,loserCountables:s=0,ratingType:a=qs,maxCountables:c,countables:u}=t||{},p=o?.[a];if(!p)return{error:et};n=p.range||n,e=e||p.defaultInitialization,r=r||p.defaultInitialization;let m=n[0]>n[1],d=p.decimalsCount||0,l=m?n.slice().reverse():n,f=(F,L)=>parseFloat(L)>=Math.min(...F)&&parseFloat(L)<=Math.max(...F);(!f(n,e)||!f(n,r))&&(f(n,e)||(e=p.defaultInitialization),f(n,r)||(r=p.defaultInitialization));let g=({value:F,sourceRange:L,targetRange:v})=>(F-L[0])*(v[1]-v[0])/(L[1]-L[0])+v[0],I=g({targetRange:Br[qs].range,sourceRange:l,value:m?n[0]-e:e}),h=g({targetRange:Br[qs].range,sourceRange:l,value:m?n[0]-r:r}),S=(F,L)=>1/(1+Math.pow(10,(L-F)/yd.nSpread)),T=S(I,h),A=S(h,I),D=yd.kCalc(i),y=yd.kCalc(s),E=yd.kMultiplier(c,u),U=I+E*D*(1-T),M=h+E*y*(0-A),P=g({sourceRange:Br[qs].range,value:U,targetRange:l}),N=g({sourceRange:Br[qs].range,value:M,targetRange:l}),C=m?n[0]-P:P,O=parseFloat(parseFloat(C).toFixed(d)),b=m?n[0]-N:N,x=parseFloat(parseFloat(b).toFixed(d)),w=Math.max(...n)?Math.abs(e-r)/Math.max(...n):0;return(P>N&&w>yd.diffThreshold||O<0||x<0)&&(O=e,x=r),{newWinnerRating:O,newLoserRating:x}}var e_=t=>t?.reduce((e,r)=>(r.winningSide&&(e[r.winningSide-1]+=1),e),[0,0])||[0,0];function wS(t){let{removePriorValues:e=!0,tournamentRecord:r,ratingType:n=qs,considerGames:o,matchUpIds:i,asDynamic:s}=t;if(!r)return{error:W};if(!Array.isArray(i))return{error:Sn};if(typeof n!="string")return{error:G,ratingType:n};if(!Br[n])return{error:G};let a=Br[n],{accessor:c}=a,u={},p=t.matchUps??le({matchUpFilters:{matchUpIds:i,matchUpStatuses:ae},tournamentRecord:r,inContext:!0}).matchUps??[];p.sort(hi);for(let d of p){let{endDate:l,matchUpFormat:f,score:g,sides:I,winningSide:h}=d,S=d.matchUpType,T={eventType:S,scaleName:n,scaleType:Ki},A=`${n}.${vI}`,D={scaleName:A,eventType:S,scaleType:Ki},y=Object.assign({},...(I??[]).map(w=>{let{sideNumber:F,participant:L}=w;return F&&{[F]:[L?.participantId,...L?.individualParticipantIds??[]].filter(Boolean).flat()}})),E=s?A:n,U=Object.assign({},...Object.values(y).flat().map(w=>{let{scaleItem:F}=Pc({scaleAttributes:D,tournamentRecord:r,participantId:w}),{scaleItem:L}=Pc({tournamentRecord:r,scaleAttributes:T,participantId:w}),v=c?{[c]:void 0}:void 0;return w&&{[w]:F??L??{scaleName:E,eventType:S,scaleDate:l,scaleType:Ki,scaleValue:v}}})),M=f?tr(f):{},P=M?.bestOf||1,N=M?.setsTo||1,C=o?P&N:P,O=g?.sets&&e_(g.sets)||h===1&&[1,0]||[0,1],b=h?y[h]:[],x=h?y[3-h]:[];for(let w of b){let F=U[w]?.scaleValue,L=typeof F=="object"?F[c]:F;for(let v of x){let B=U[v]?.scaleValue,H=typeof B=="object"?B[c]:B,j=h?O[h]:[0,0],V=h?O[3-h]:[0,0],{newWinnerRating:Y,newLoserRating:$}=xS({winnerCountables:j,loserCountables:V,maxCountables:C,winnerRating:L,loserRating:H,ratingType:n}),k=c?{...F,[c]:Y}:Y,K=c?{...B,[c]:$}:$;U[w].scaleValue=k,U[v].scaleValue=K;let z=ba({participantId:w,removePriorValues:e,tournamentRecord:r,scaleItem:{...U[w],scaleName:E}});if(z.error||(z=ba({participantId:v,removePriorValues:e,tournamentRecord:r,scaleItem:{...U[v],scaleName:E}}),z.error))return z}}Object.assign(u,U)}let m=p.map(({matchUpId:d})=>d);return{...R,modifiedScaleValues:u,processedMatchUpIds:m}}function Nu(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=gd(t);if(u.error)return _({result:u});let{lastRoundNumber:p,availableMatchUpsCount:m=0,roundMatchUpsCount:d=0}=u;if(!c)o?c=d:m>0&&(c=m);else if(c>d&&t.restrictMatchUpsCount!==!1)return _({result:{error:G,info:"matchUpsCount error",context:{roundMatchUpsCount:d}}});if(a&&!Array.isArray(a)||c&&!ft(c)||e&&!Array.isArray(e)||!a&&!c)return{error:G,info:"matchUpsCount or pairings error"};if(c&&t.restrictMatchUpsCount!==!1&&c>32)return{error:G,info:"matchUpsCount must be less than 33"};if(n&&!t.ignoreLastRoundNumber&&n-1>(p||0))return{error:G,info:"roundNumber error"};let l=n??(o&&(p??0)+1||p||1);a=a??Z(0,c).map(()=>({participantIds:[void 0,void 0]}));let f=I=>{if(!t.idPrefix)return;let h=r.drawId,S=t.idPrefix??"ah";return`${h}-${S}-${l}-${I}`},g=a?.map((I,h)=>{let S=I?.participantIds??[void 0,void 0];S.push(void 0,void 0);let A=S.slice(0,2).map((y,E)=>rt({sideNumber:E+1,participantId:y})),D=e[h]??f(h)??Mt();return{roundNumber:l,matchUpStatus:zt,matchUpId:D,sides:A}});if(g?.length){let I=je({drawDefinition:r,event:s})?.tieFormat;I&&g.forEach(h=>{let{tieMatchUps:S}=Ma({tieFormat:I,matchUp:h,isMock:i});Object.assign(h,{tieMatchUps:S,matchUpType:Bt})})}return{roundNumber:l,matchUpsCount:g?.length??0,matchUps:g,...R}}function n_({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=r_({actorsCount:s.length,valueSortedPairings:e,pairingValueMap:i,deltaObjects:o,valueObjects:n}),u=[UP(c)];a.push(c);let p=c.value,m=c,d=0,l=0,f=s.length,g;do f-=1,g=s.length*r[s[0]].length;while(g>t&&f>5);let I=[];s.forEach(S=>{r[S].slice(0,f).forEach(A=>{l+=1;let D=Oa(S,A.opponent);if(!I.includes(D)){let y=r_({stipulated:[[S,A.opponent]],actorsCount:s.length,valueSortedPairings:e,pairingValueMap:i,deltaObjects:o,valueObjects:n});if(!u.includes(UP(y))){u.push(UP(y)),a.push(y);let{maxDelta:E,value:U}=y;E<m.maxDelta&&(m=y),(U<p||U===p&&Math.round(Math.random()))&&(p=U),I.push(D),d+=1}}}),a=a.filter(A=>Math.abs(A.value-p)<5)}),a.sort((S,T)=>S.maxDiff-T.maxDiff);let h=xr(a);return{candidatesCount:d,deltaCandidate:m,maxIterations:t,iterations:l,candidate:h}}function UP(t){return t.participantIdPairings.map(({participantIds:e})=>e.sort().join("|")).sort().join("/")}function r_({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=Oa(l,f),I=r[g];a.push({participantIds:d,value:I}),c+=r[g]}),Te(t,i).map(d=>cr(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=Oa(f,g),h=n[I];return h>d?h:d},0),m=a.reduce((d,l)=>{let[f,g]=l.participantIds,I=Oa(f,g),h=o[I];return h>d?h:d},0);return{value:c,participantIdPairings:a,maxDelta:p,maxDiff:m}}function Oa(t,e){return[t,e].sort(du).join("|")}function PP({participantIds:t}){let e={},r=[];t.forEach(o=>{e[o]=t.filter(i=>i!==o),e[o].forEach(i=>{let s=Oa(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 o_({matchUps:t}){let e=[];for(let r of t){let n=r.sides.map(gt);if(n.length===2){let[o,i]=n,s=Oa(o,i);e.includes(s)||e.push(s)}}return{encounters:e}}function i_({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=Oa(o,i);return{opponent:i,value:e[s]}}return{pairingValues:r}}var VG=0;function s_({tournamentParticipants:t,adHocRatings:e,eventType:r,scaleName:n,pairing:o}){let i=Br[n]?.defaultInitialization??VG;return o.split("|").map(s=>{if(r===Kr){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 a_({tournamentParticipants:t,adHocRatings:e={},possiblePairings:r,uniquePairings:n,maxIterations:o,deltaObjects:i,valueObjects:s,eventType:a,scaleName:c,salted:u}){n.forEach(h=>{let S=s_({tournamentParticipants:t,adHocRatings:e,scaleName:c,eventType:a,pairing:h}),T=typeof u=="number"&&u||.5,A=u&&(Math.round(Math.random())?T:T*-1)||0,D=Math.abs(S[0]-S[1])+A,y=Math.abs(S[0]-S[1]);i[h]=y,s[h]||(s[h]=0),s[h]+=D?Math.pow(D,2):0});let p=n.map(h=>({pairing:h,value:s[h]})).sort((h,S)=>h.value-S.value),{pairingValues:m}=i_({possiblePairings:r,valueObjects:s}),{candidate:d,candidatesCount:l,deltaCandidate:f,iterations:g}=n_({valueSortedPairings:p,maxIterations:o,pairingValues:m,deltaObjects:i,valueObjects:s}),{participantIdPairings:I}=d;return{participantIdPairings:I,candidatesCount:l,deltaCandidate:f,iterations:g,candidate:d}}var BG=100,HG=100,WG=4e3;function Ed({encounterValue:t=BG,sameTeamValue:e=HG,maxIterations:r=WG,generateMatchUps:n=!0,ignoreLastRoundNumber:o,iterationMatchUps:i,tournamentRecord:s,dynamicRatings:a,participantIds:c,drawDefinition:u,adHocRatings:p,salted:m=.5,roundNumber:d,structureId:l,matchUpIds:f,eventType:g,structure:I,scaleName:h,idPrefix:S,isMock:T,event:A}){if(!u)return{error:X};if(!I&&!l)return{error:Lt};if(I||(I=st({drawDefinition:u,structureId:l}).structure),!Rt(I))return{error:Do};if(!c?.length)return{error:lo};let D=[...i??[],...I?.matchUps??[]],{encounters:y}=o_({matchUps:D}),E=s?.participants??[];if(a){let H=pt(I?.matchUps?I.matchUps.map(({roundNumber:V})=>V):[]),j=Math.max(...H,0);if(j){let V=I?.matchUps?.filter(({roundNumber:Y})=>Y===j).map(({matchUpId:Y})=>Y);wS({ratingType:h||A?.category?.ratingType,tournamentRecord:s,asDynamic:!0,matchUpIds:V})}}let{valueObjects:U}=jG({tournamentParticipants:E,encounterValue:t,sameTeamValue:e,encounters:y}),{uniquePairings:M,possiblePairings:P,deltaObjects:N}=PP({participantIds:c}),C={tournamentParticipants:E,possiblePairings:P,drawDefinition:u,participantIds:c,uniquePairings:M,maxIterations:r,adHocRatings:p,deltaObjects:N,valueObjects:U,eventType:g,scaleName:h,structure:I,salted:m},{candidatesCount:O,participantIdPairings:b,iterations:x,candidate:w}=a_(C);if(!O)return{error:Yu};let F,L;if(n){let H=Nu({structureId:I?.structureId,ignoreLastRoundNumber:o,participantIdPairings:b,newRound:!0,drawDefinition:u,roundNumber:d,matchUpIds:f,idPrefix:S,isMock:T,event:A});if(H.error)return H;F=H.roundNumber,L=H.matchUps}let{maxDelta:v,maxDiff:B}=w;return{roundNumber:F,participantIdPairings:b,candidatesCount:O,...R,iterations:x,matchUps:L,maxDelta:v,maxDiff:B}}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===kt);if(i)for(let s of i){let a=s.individualParticipantIds??[],{uniquePairings:c}=PP({participantIds:a});for(let u of c)o[u]||(o[u]=0),o[u]+=n}return{valueObjects:o}}function LS(t){let{drawType:e=io,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=mi({stageSequence:1,drawDefinition:p,stage:m}),l=[dn,Jc,so].includes(e)?d.length:qi(d.length);if(!i&&e===la&&d.length<2||e===dn&&d.length<3)return{error:Vu};let{tieFormat:f,matchUpType:g}=t;if(f){let C=ir({tieFormat:f});if(C.error)return C}f=Xe(f??je({drawDefinition:p})?.tieFormat),g=g??p.matchUpType??Xt;let{structures:I}=xn({stageSequence:1,drawDefinition:p,stage:m});if(I.length>1)return{error:hy};if(I?.[0]?.matchUps?.length)return{error:Fl};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=vS(t);if(T.error)return T;let A=T.generators[e];if(!A)return{error:fl};let D=A?.();if(D.error)return D;let{structures:y,links:E}=D,U=y.map(C=>At({structure:C}).matchUps).flat();f&&U.forEach(C=>{let{tieMatchUps:O}=Ma({matchUp:C,tieFormat:f,isMock:c});Object.assign(C,{tieMatchUps:O,matchUpType:g})}),(!n||!r)&&(p=J(p,!1,!0)),p.links||(p.links=[]),E.length&&p.links.push(...E);let M=y.map(({structureId:C})=>C);p.structures||(p.structures=[]);let P=p.structures.map(({structureId:C})=>C);p.structures=p.structures.map(C=>M.includes(C.structureId)?y.find(({structureId:O})=>O===C.structureId):C);let N=y.filter(({structureId:C})=>!P.includes(C));return N.length&&p.structures.push(...N),s&&hc({seedingProfile:t.seedingProfile,applyPositioning:n,tournamentRecord:o,drawDefinition:p,structureId:S,placeByes:a,drawSize:l,event:u}),r&&bt({drawDefinition:p}),{links:E,structures:y,...R}}var yg={};Jt(yg,{addGame:()=>OP,addPoint:()=>bP,addSet:()=>vP,addShot:()=>_P,analyzeSet:()=>Ru,calculateHistoryScore:()=>MP,checkScoreHasValue:()=>Ie,checkSetIsComplete:()=>Op,clearHistory:()=>RP,generate:()=>NP,generateScoreString:()=>wo,generateTieMatchUpScore:()=>Uc,getSetComplement:()=>Ag,getTiebreakComplement:()=>wp,helpers:()=>uD,isValidMatchUpFormat:()=>Sr,keyValueScore:()=>nD,mutate:()=>FP,parseMatchUpFormat:()=>tr,parseScoreString:()=>Rd,query:()=>pD,redo:()=>xP,reverseScore:()=>DP,setServingSide:()=>CP,stringifyMatchUpFormat:()=>Pp,tidyScore:()=>cD,umo:()=>LP,undo:()=>wP,validateScore:()=>Tg,validateTieFormat:()=>ir});var NP={};Jt(NP,{generateScoreString:()=>wo,generateTieMatchUpScore:()=>Uc,reverseScore:()=>DP});function wo(t){let{winnerFirst:e=!0,addOutcomeString:r,reversed:n=!1,matchUpStatus:o,matchUpFormat:i,autoComplete:s,winningSide:a,sets:c}=t;if(!c)return{error:et,info:"missing sets"};let u=i&&tr(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 A=p&&S.setNumber===p&&m?m:d,D=v=>te(v?.side1Score)||te(v?.side2Score),y=v=>te(v?.side1TiebreakScore)||te(v?.side2TiebreakScore),E=A?.tiebreakSet||!D(S)&&y(S),{side1Score:U,side2Score:M,side1TiebreakScore:P,side2TiebreakScore:N}=S,C=P||(te(P)||s?0:""),O=N||(te(N)||s?0:"");if(E)return`[${(f?[O,C]:[C,O]).join("-")}]`;let b=Math.min(C,O),x=b?`(${b})`:"",w=U||(te(U)||s?0:""),F=M||(te(M)||s?0:""),L=f?`${[F,w].join("-")}${x}`:`${[w,F].join("-")}${x}`;return["-"," "].includes(L)&&(L=""),L}}function YG({matchUpStatus:t}){let e={[lr]:"RET",[_t]:"WO",[Ne]:"DF/DF",[ge]:"WO/WO",[Xi]:"SUS",[$r]:"ABN",[Ot]:"DEF",[Kc]:"DR"};return t&&e[t]||""}function qG(t,e){return t.setNumber-e.setNumber}function DP(t){if(!t?.score)return{error:et};let{sets:e}=t.score,r=e.map(i=>{let{side1TiebreakScore:s,side2TiebreakScore:a,winningSide:c,side1Score:u,side2Score:p,setNumber:m}=i;return rt({winningSide:c?3-c:void 0,side1TiebreakScore:a,side2TiebreakScore:s,side1Score:p,side2Score:u,setNumber:m})}),n=wo({sets:r}),o=wo({sets:r,reversed:!0});return{reversedScore:{sets:r,scoreStringSide1:n,scoreStringSide2:o},...R}}var FP={};Jt(FP,{addGame:()=>OP,addPoint:()=>bP,addSet:()=>vP,addShot:()=>_P,calculateHistoryScore:()=>MP,clearHistory:()=>RP,redo:()=>xP,setServingSide:()=>CP,umo:()=>LP,undo:()=>wP});function Lo({matchUp:t}){let{extension:e}=mt({name:Pm,element:t});if(!e)return{error:Ke};let{history:r=[],undoHistory:n=[]}=e.value;return{history:r,undoHistory:n,...R}}function MP(t){if(!t)return{error:et};let{matchUp:e,updateScore:r}=t;if(!e)return{error:sr};let n=Lo({matchUp:e})?.history||[];if(!Array.isArray(n))return{error:G,info:"history is not an array"};let{matchUpFormat:o}=e;if(!o)return{error:Al};if(!Sr({matchUpFormat:o}))return{error:Tl};let i=tr(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:[]}),A=()=>({winningSide:void 0,points:[]}),D=()=>({winningSide:void 0,side1Score:"",side2Score:"",shots:[]}),y=D(),E=A(),U=T(),M=0;for(let P of n){M+=1,I=p.sets.length+1===s;let N=I&&a?a:c,{tiebreakAt:C,setTo:O,NoAD:b,tiebbreakFormat:x}=N,w=U.side1Score===C&&U.side1Score===U.side2Score,F=!!N.tiebreakSet,L=F?N.tiebreakSet:x,{tiebreakTo:v,NoAD:B}=L||{},H=()=>{d=void 0,l=[0,0],f=3-f,U.side1TiebreakScore=0,U.side2TiebreakScore=0,U.side1PointScore="",U.side2PointScore="",h=0},j=$=>{U.winningSide=$;let{s:k,...K}=U;p.sets.push(K),y=D(),E=A(),U=T(),H()},V=$=>{E.winningSide=$;let{g:k,...K}=E;U.games.push(K),y=D(),E=A(),H();let z=`side${$}Score`;U[z]+=1},Y=$=>{y.winningSide=$;let{p:k,...K}=y;E.points.push(K),y=D(),h=0;let z=()=>l.reduce((it,ot)=>it+ot)%4/4>.5?f:3-f,q=$-1;if(w||F){l[q]+=1,d=z(),U[`side${$}TiebreakScore`]=l[q],U[`side${3-$}TiebreakScore`]=l[1-q];let nt=B?1:2;if(l[q]>=v&&l[q]>=l[1-q]+nt)return V($),{gameCompleted:!0}}else if(l[1-q]===4&&l[q]===3?l[1-q]-=1:l[q]+=1,U.side1PointScore=u[l[0]],U.side2PointScore=u[l[1]],l[q]===5||l[q]===4&&l[1-q]<3||b&&l[q]===4)return V($),{gameCompleted:!0}};if(S(P.srv)&&(f=P.srv),["p","s","g","o"].includes(P.u)&&m.push(P.u),P.shotOutcome&&(y.shots.push(P),P.shotType==="SERVE"&&["OUT","NET"].includes(P.shotOutcome)&&(h+=1),h===2)){let k=3-f;Y(k)}if(S(P.p)||ft(P.pointNumber)){let $=P.winningSide||P.p;if(Y($)?.gameCompleted)continue}if(S(P.g)||ft(P.gameNumber)){let $=P.winningSide||P.g;E.winningSide=$;let k=`side${$}Score`,K=`side${3-$}Score`;if(m.length&&(m.includes("p"),m=[]),V($),U[k]===O&&U[k]-U[K]>=(b?1:2)&&(j($),I))break}if(S(P.s)||ft(P.setNumber)){let $=P.winningSide||P.s;if(j($),m.length&&(m.includes("p"),m.includes("g"),m=[]),I)break}}return M!==n.length&&console.log({error:"Match completed with excess history"}),(U.side1Score||U.side2Score||U.games.length||U.side1TiebreakScore||U.side2TiebreakScore)&&p.sets.push(U),p.scoreStringSide1=wo({...p,matchUpFormat:o}),p.scoreStringSide2=wo({...p,matchUpFormat:o,reversed:!0}),f=d||f,r&&(e.score=p),{...R,servingSide:f,score:p}}function Fo({undoHistory:t,history:e,matchUp:r}){return St({element:r,extension:{value:{history:e,undoHistory:t},name:Pm}})}function CP({matchUp:t,sideNumber:e}){if(![1,2].includes(e))return{error:yl};let{history:r=[]}=Lo({matchUp:t});return r.push({srv:e}),Fo({matchUp:t,history:r})}function RP({matchUp:t}){return Fo({matchUp:t})}function bP({matchUp:t,point:e}){if(!e||!t)return{error:et};if(typeof e!="object")return{error:G,context:{point:e}};let{history:r=[]}=Lo({matchUp:t});return r.push(e),Fo({matchUp:t,history:r})}function OP({matchUp:t,game:e}){if(typeof e!="object")return{error:G,context:{game:e}};let{history:r=[]}=Lo({matchUp:t});return r.push(e),Fo({matchUp:t,history:r})}function _P({matchUp:t,shot:e}){if(typeof e!="object")return{error:et};let{history:r=[]}=Lo({matchUp:t});return r.push(e),Fo({matchUp:t,history:r})}function vP({matchUp:t,set:e}){if(typeof e!="object")return{error:et};let{history:r=[]}=Lo({matchUp:t});return r.push(e),Fo({matchUp:t,history:r})}function xP({matchUp:t}){let{history:e=[],undoHistory:r=[]}=Lo({matchUp:t});return r.length&&e.push(r.pop()),Fo({matchUp:t,history:e,undoHistory:r})}function wP({matchUp:t}){let{history:e=[],undoHistory:r=[]}=Lo({matchUp:t});return r.push(e.pop()),Fo({matchUp:t,history:e,undoHistory:r})}var LP={};var uD={};Jt(uD,{keyValueScore:()=>nD,parseMatchUpFormat:()=>tr,stringifyMatchUpFormat:()=>Pp,tidyScore:()=>cD});var Ks=" ",FS="DEF",c_="COMPLETED",GP="WO",$G="WO/WO",kP="ABN",VP="SUS",BP="RET",HP="INT",GS=[BP,FS,GP,$G,kP,VP,HP];var kS="DEFAULTED";var WP="WALKOVER";var VS="ABANDONED",BS="SUSPENDED",jP="RETIRED",HS="INTERRUPTED";var u_=[jP,kS,WP],KG="Enter Score",ls="()",fs="[]",YP=["up","left","shift+tab"],qP=["enter","down","tab","right"],Ud="backspace",$P="r",KP="s",zP="a",QP="d",XP="w",JP="i",Pd=[$P,QP,XP,zP,KP,JP],Rp="space",WS=["[","("],Dd=[...YP,...qP,Rp,"]"],p_="-",zG="/",zs=p_,ti=p_,ZP=[zG],m_=0,QG=["=","+","num_1","num_2","shift+=","shift+-"],$s=["0","1","2","3","4","5","6","7","8","9"].concat(Pd),d_=$s.map(t=>`shift+${t}`),tD=[zs,Ud].concat(Dd,ZP),eD=[$s,d_,tD].join(","),XG=[eD,YP,qP,QG].join(","),aDt=[].concat(...$s,...$s,...tD,...$s,...$s,...$s,...$s,...$s,...$s),l_={OUTCOMEKEYS:Pd,SIDE1KEYS:$s,SIDE2KEYS:d_,MODIFIERS:tD,PROMPT:KG,MOVEUP:YP,MOVEDOWN:qP,HOTKEYS:XG};function bp({scoreString:t,lowSide:e,outcome:r}){if({scoreString:t}=f_({scoreString:t}),e===2){let o=(t&&t[t.length-1])!==Ks?Ks:"";return t+o+r}else return r+Ks+t}function f_({scoreString:t}){if(!t)return{scoreString:""};let e=!1;for(let r of GS){let n=t?.indexOf(r);n===0?t=t.slice(r.length+1).trim()+Ks:n>0&&(t=t.slice(0,n)),n>=0&&(e=!0)}return t?.trim()||(t=""),{scoreString:t,removed:e}}function Ig({analysis:t,scoreString:e,sets:r,lowSide:n}){let o,i;if(!e)return{scoreString:e,sets:r};let{scoreString:s,removed:a}=f_({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}=Mu({brackets:fs,scoreString:e}),f=JG(e);if(f>=0){o=e.slice(0,f);let{isTiebreakEntry:g}=Mu({brackets:ls,scoreString:o}),{lastOpenBracketIndex:I,isTiebreakEntry:h}=Mu({brackets:fs,scoreString:o}),S=o&&o[o.length-1].trim(),T=o&&!isNaN(S),A=t.isIncompleteSetScore;if(l&&h){let y=o.slice(I+1).split(ti),E=y?.length>0&&y[0]!==void 0&&!isNaN(parseInt(y[0]))&&parseInt(y[0])||void 0,U=y?.length>1&&y[1]!==void 0&&parseInt(y[1])||void 0,M=[E,U];if(U){let 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(ti)}else E!==void 0?(o=e.slice(0,I+1),o+=E):(o=e.slice(0,I),A=!0);c.side1TiebreakScore=M[0]||0,c.side2TiebreakScore=M[1]||0}if(o.length||(o=void 0),A){let D=c.side1Score?.toString();if(D){let y=D?.slice(0,D.length-1);c.side1Score=!isNaN(y)&&parseInt(y)||void 0,c.side1Score===void 0&&(c.side2Score=void 0)}t.isTimedSet?(i=c.side1Score?r:r?.slice(0,r.length-1)||[],i[r.length-1]=c):i=r?.slice(0,r.length-1)||[]}else if(T){let D=c.side2Score?.toString(),y=c.side1Score?.toString();if(!t.isTiebreakEntry&&!t.isMatchTiebreak)if(c.side2Score){let E=D?.slice(0,D.length-1);c.side2Score=!isNaN(E)&&parseInt(E)||void 0}else{let E=y?.slice(0,y.length-1);c.side1Score=!isNaN(E)&&parseInt(E)||void 0}t.isTimedSet?c.side1Score?(i=r||[],i[r.length-1]=c):i=r?.slice(0,r.length-1)||[]:(i=r||[],i[r.length-1]=c),i[i.length-1]&&Object.assign(i[i.length-1],{winningSide:void 0})}else g?(i=r||[],Object.assign(i[i.length-1]||{},{winningSide:void 0,side1TiebreakScore:void 0,side2TiebreakScore:void 0})):(l&&!h?i=r?.slice(0,r.length-1)||[]:(i=r,i[r.length-1]=c),l||(i[i.length-1].side2Score=0,i[i.length-1].winningSide=void 0));return{scoreString:o,sets:i}}return{scoreString:e,sets:r}}function Mu({brackets:t=ls,scoreString:e}){if(!e)return{};let[r,n]=t.split(""),o=e.split(""),i=Math.max(...Zn(r,o)),s=Math.max(...Zn(n,o));return{isTiebreakEntry:i>s,lastOpenBracketIndex:i}}function g_({scoreString:t}){if(!t)return!1;let e=t&&t[t.length-1].trim(),r=t&&!isNaN(e),[n,o]=fs.split(""),i=t.split(""),s=Math.max(...Zn(n,i)),a=Math.max(...Zn(o,i)),c=Math.max(...Zn(ti,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 jS(t){let{lowValue:e=0,NoAD:r=!1,tiebreakTo:n}=t||{},o=r?1:2;return e+1>=n?e+o:parseInt(n)}function rD({matchUpFormat:t,matchUpStatus:e,winningSide:r,sets:n}){let o=tr(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 u_.includes(e)&&r&&(c=r),{matchUpWinningSide:c}}function Op({ignoreTiebreak:t=!1,matchUpScoringFormat:e,matchUpFormat:r,isTiebreakSet:n,isDecidingSet:o,set:i}){if(!i)return{error:et,info:"missing set"};e=e||r&&tr(r);let s=o&&e.finalSetFormat||e?.setFormat||{},{side1Score:a,side2Score:c}=i,{setTo:u,tiebreakAt:p}=s,m=_p({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 _p({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 Nd({analysis:t,set:e}){let r=_p({set:e}),{isDecidingSet:n,isTiebreakSet:o,matchUpScoringFormat:i}=t;return Op({matchUpScoringFormat:i,isDecidingSet:n,isTiebreakSet:o,set:e})&&r}function I_({analysis:t,scoreString:e,sets:r,value:n}){let o;if(!r?.length)return{sets:[]};let i=r[r.length-1];n=ct(n);let{validSide2Score:s,requiresTiebreak:a}=ZG({analysis:t,set:i,value:n});if(s){o=!0,e=(e||"")+n,i.side2Score=n;let c=Nd({analysis:t,set:r[r.length-1]});if(i.winningSide=c||void 0,a){let u=ls.split("")[0];e+=u}else t.isDecidingSet||(e+=Ks)}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 YS({lowSide:t,value:e,sets:r,scoreString:n,winningSide:o,matchUpStatus:i}){let s;return e===$P?n?(s=!0,n=bp({scoreString:n,lowSide:t,outcome:BP}),o=t===2?1:2,i=jP):(s=!0,n=bp({scoreString:n,lowSide:t,outcome:FS}),o=t===2?1:2,i=kS):e===QP?(s=!0,n=bp({scoreString:n,lowSide:t,outcome:FS}),o=t===2?1:2,i=kS):e===XP?(s=!0,r=[],n=GP,o=t===2?1:2,i=WP):e===KP&&n?(s=!0,n=bp({scoreString:n,lowSide:t,outcome:VP}),i=BS,o=void 0):e===zP?(s=!0,n=bp({scoreString:n,lowSide:t,outcome:kP}),i=VS,o=void 0):e===JP&&n&&(s=!0,n=bp({scoreString:n,lowSide:t,outcome:HP}),i=HS,o=void 0),{updated:s,sets:r,scoreString:n,matchUpStatus:i,winningSide:o}}function h_(t){let{sets:e,info:r,scoreString:n,winningSide:o,matchUpStatus:i}=t,{analysis:s,lowSide:a,value:c}=t,u,p;!e?.length&&c!==Ud&&(e=[{setNumber:1}]);let m=e.length-1;if(Pd.includes(c)){let d=e[e.length-1]||{},{side1Score:l,side2Score:f}=d;l&&!f?r="missing side2Score":s.finalSetIsComplete||o?r="final set is already complete":s.isIncompleteSetScore?r="incomplete set scoreString":s.isIncompleteSetScore||({sets:e,scoreString:n,winningSide:o,matchUpStatus:i,updated:u}=YS({lowSide:a,value:c,sets:e,scoreString:n,matchUpStatus:i,winningSide:o}))}else if(c===Ud){if({scoreString:n,sets:e,outcomeRemoved:p}=Ig({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===Rp){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===zs&&e[m].side1Score!==void 0&&e[m].side2Score===void 0&&n&&s.isNumericEnding)n+="-",e[m].side2Score=0,i=void 0,o=void 0,u=!0;else if(!isNaN(c)){let d;if(e[m].side2Score===void 0){let l=ct((e[m].side1Score||0).toString()+c).toString().slice(0,2);e[m].side1Score=ct(l),d=e[m].side1Score.toString(),u=!0}else{let l=ct((e[m].side2Score||0).toString()+c).toString().slice(0,2);e[m].side2Score=ct(l),d=[e[m].side1Score,e[m].side2Score].join("-"),u=!0}if(u){let l=(e.slice(0,m)||[]).filter(f=>f).map(f=>{let{side1Score:g,side2Score:I}=f;return[g,I].join("-")}).join(" ");l?n=l+" "+d:n=d}}}return{sets:e,scoreString:n,winningSide:o,matchUpStatus:i,info:r,updated:u}}function S_({analysis:t,auto:e,lowSide:r,scoreString:n="",sets:o,value:i}){let s,a,{tiebreakSet:{tiebreakTo:c,NoAD:u}}=t.setFormat,[p]=fs.split("");if(t.isMatchTiebreakEntry||(n+=p),o[t.setNumber-1]){let{lastOpenBracketIndex:d}=Mu({brackets:fs,scoreString:n}),f=(n.slice((d??0)+1)+(e?"":i)).split(ti);if((f[r-1]?.length||0)>=2)a="tiebreak digit limit";else if(e){r===1&&(f[0]=(f[0]||"")+i),r===2&&(f[1]=(f[1]||"")+i);let I=[f[0]||0,f[1]||0].map(T=>ct(T)),h=r===1?1:0;I[h]=I[1-h]+(u?1:2),I[h]<c&&(I[h]=c);let S=o[o.length-1];S.side1TiebreakScore=I[0],S.side2TiebreakScore=I[1],n=n.slice(0,(d??0)+1),n+=I.join(ti),s=!0}else{let I=[f[0]||0,f[1]||0].map(S=>ct(S)),h=o[o.length-1];h.side1TiebreakScore=I[0],h.side2TiebreakScore=I[1],n+=i,s=!0}}else{let d=jS({lowValue:ct(i||0),tiebreakTo:c,NoAD:u}),l=[ct(i),d];r===2&&l.reverse();let f={side1TiebreakScore:l[0],side2TiebreakScore:l[1],setNumber:o?.length+1||1};o.push(f),n+=l.join(ti),s=!0}return{info:a,scoreString:n,sets:o,updated:s}}function T_({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=ls.split("")[0],d=u.join(zs)+(a?m:Ks);r=(r||"")+d;let l={side1Score:u[0],side2Score:u[1]},f=Nd({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 A_({matchUpFormat:t,scoreString:e,winningSide:r,value:n,sets:o}){let s=(o?.filter(V=>V?.winningSide)?.length||0)+(r?0:1),a=tr(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}=Mu({brackets:ls,scoreString:e}),{isTiebreakEntry:f}=Mu({brackets:fs,scoreString:e}),g=l||f,I=!!u.tiebreakSet,h=e?.[e.length-1]?.trim(),S=e&&!isNaN(h),T=!g&&h===zs,A=l&&WS.includes(h),D=f&&WS.includes(h),y=f&&h===ti,E=e?.split(""),[U]=fs.split(""),M=E&&Math.max(...Zn(U,E)),P=E&&Math.max(...Zn(ti,E)),N=E&&P>M,C=o[o.length-1]?.winningSide,O=o?.length&&!C,b=GS.find(V=>e?.indexOf(V)>=0),x=!isNaN(n),w=n===Rp,F=Dd.includes(n),L=e?.split("").find(V=>WS.includes(V)),v=F&&f&&!D&&(y||!g_({scoreString:e}));return{isTiebreakSetValue:I&&x,matchUpScoringFormat:a,setNumber:s,setFormat:u,matchTiebreakHasJoiner:N,isGameScoreEntry:O,isSpace:w,isCloser:F,isTiebreakCloser:F&&L&&g&&S,isDecidingSet:c,isTiebreakSet:I,isTimedSet:p,isNumericEnding:S,isNumericValue:x,hasOpener:L,hasOutcome:b,finalSet:m,finalSetIsComplete:d,lastSetIsComplete:C,isInvalidSetTiebreakValue:w&&g&&A,isInvalidMatchTiebreakValue:v,isTiebreakEntry:g,isSetTiebreakEntry:l,isMatchTiebreakEntry:f,isIncompleteSetScore:T,isIncompleteSetTiebreak:A,isIncompleteMatchTiebreak:D,isPartialMatchTiebreakValue:y}}function nD(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(!eD.includes(r))return{updated:!1,info:"invalid key"};c&&(e=3-e);let{matchUpWinningSide:l}=rD({sets:o,winningSide:i,matchUpStatus:s,matchUpFormat:a});i=l;let f=A_({value:r,winningSide:i,scoreString:n,sets:o,matchUpFormat:a});if(ZP.includes(r)&&(r=zs),f.hasOpener&&f.isTiebreakEntry&&!f.isTiebreakSet&&d&&ct(r)===0&&(f.isTiebreakCloser=!0),Dd.includes(r)&&f.hasOpener&&(r=""),Dd.includes(r)&&(r=Rp),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}=h_({analysis:f,lowSide:e,scoreString:n,sets:o,matchUpStatus:s,winningSide:i,value:r}));else if(Pd.includes(r))f.finalSetIsComplete||i?m="final set is already complete":!f.isTiebreakEntry&&!f.isIncompleteSetScore?{sets:o,scoreString:n,matchUpStatus:s,winningSide:i,updated:p}=YS({lowSide:e,sets:o,scoreString:n,matchUpStatus:s,winningSide:i,value:r}):f.isTiebreakEntry||f.isIncompleteSetScore?m="incomplete set scoreString or tiebreak entry":console.log("handle case",{value:r});else if(r===Ud)p=!0,{scoreString:n,sets:o}=Ig({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===zs&&!f.isMatchTiebreakEntry)(!f.isSetTiebreakEntry||f.isSetTiebreakEntry&&!f.isNumericEnding)&&(p=!0,{scoreString:n,sets:o}=Ig({analysis:f,scoreString:n,sets:o,lowSide:e}),s=void 0);else if(r===ti&&f.isMatchTiebreakEntry&&!f.isSetTiebreakEntry)f.matchTiebreakHasJoiner?m="existing joiner":f.isNumericEnding&&(p=!0,n+=ti);else if([zs,ti].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}=I_({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?ls:fs,I=g.split("").reverse()[0],h=g.split("")[0],S=o[o.length-1],{tiebreakFormat:T}=f.setFormat,{tiebreakTo:A,NoAD:D}=T||{},y=_p({set:S});if(!f.isTiebreakSet){let U=parseInt(n.split(h).reverse()[0]),M=jS({lowValue:U,tiebreakTo:A,NoAD:D});y===1?(S.side1TiebreakScore=M,S.side2TiebreakScore=U):(S.side1TiebreakScore=U,S.side2TiebreakScore=M)}n=(n||"")+I,f.isDecidingSet||(n+=Ks);let E=Nd({analysis:f,set:S});S.winningSide=E||void 0,p=!0}else if(f.isTiebreakSetValue)({info:m,scoreString:n,sets:o,updated:p}=S_({analysis:f,auto:u,lowSide:e,scoreString:n,sets:o,value:r}));else if(f.isSetTiebreakEntry){let[g]=ls.split(""),I=Math.max(...Zn(g,n.split(""))),h=n.slice(I+1),S=h&&ct(h)===m_,T=ct(h?h+r:r),{tiebreakFormat:A}=f.setFormat,{tiebreakTo:D,NoAD:y}=A||{};!S&&h.length<2?y&&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}=T_({analysis:f,lowSide:e,scoreString:n,value:ct(r)});I&&(I.setNumber=o?.length+1||1),o=o?.concat(I).filter(Boolean)||[I],n=g||void 0}else console.log("error: unknown outcome")}if(p){o=o?.filter(Boolean);let{matchUpWinningSide:g}=rD({sets:o,winningSide:i,matchUpStatus:s,matchUpFormat:a});return i=g,g&&(!s||[zt,_o].includes(s))?(s=c_,o=o.filter(I=>{let{side1Score:h,side2Score:S,side1TiebreakScore:T,side2TiebreakScore:A}=I;return h||S||T||A})):n&&!i&&![BS,VS,HS].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 Md="\\d+-\\d+",vp="\\d+-\\d+\\(\\d+\\)",hg="\\[\\d+-\\d+\\]",tk="\\d+-\\d+\\(\\d+-\\d+\\)",y_=new RegExp(`(${Md}),`,"g"),E_=new RegExp(`(${vp}),`,"g"),ek=[Md,vp,hg,tk],rk=["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"],nk=rk.map(t=>{let r=t.split("").map(n=>ek[n]).join(" ");return new RegExp(`^${r}$`)});function oD(t){return!t||nk.some(e=>e.test(t))}function U_(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 Cd(t){return/^\(\d+\)$/.test(t)||/^\(\d+$/.test(t)}function P_(t){return/^\(\d+-\d+\)$/.test(t)||/^\[\d+-\d+\]$/.test(t)}function _a(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 xp(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 iD(t){return t.length===2?t.split("").join("-"):([", ",",","/"," "].forEach(e=>t=t.split(e).join("-")),t=t.replace(/-{2,}/,"-"),t)}function D_(t){return t.startsWith("(")&&t.endsWith(")")}function N_({score:t,applied:e}){t=U_(t);let r=/\)(\d+)/g;if(r.test(t))for(let y of t.match(r)){let E=y.replace(")",") ");t=t.replace(y,E)}t=t.replace(/\)\//g,") / "),t=t.replace(/\/\)/g,")");let n=/\(([\d- ]+)\)/g,o=/\(([\d- ]+)\)/,i=t.match(n);for(let y of i||[]){let[E]=y.match(o).slice(1),U=E.replace(/ /g,"");t=t.replace(y,`(${U})`)}let s=/\(\(\d-\d\)\)/g;if(s.test(t)){let y=t.match(s);y.length&&y.forEach(E=>{let U=E.match(/\((\(\d-\d\))\)/).slice(1)[0];t=t.replace(E,U)})}if(s=/\(\((\d)\)\)/g,s.test(t)){let y=t.match(s);y.length&&y.forEach(E=>{let U=E.match(/\((\(\d\))\)/).slice(1)[0];t=t.replace(E,U)})}/(^|\s)6-,/.test(t)&&(t=t.replace(/(^|\s)6-,/g,"6-0,"));let a=new RegExp(/[-,]{2,}/g);t=t.replace(a,"-"),["- "," -"].forEach(y=>{let E=new RegExp(`(\\d+)${y}(\\d+)`,"g"),U=t.match(E);U&&U.forEach(M=>t=t.replace(M,M.split(y).join("-")))}),/^[(-/,]+$/.test(t)&&(t=""),/\)[-/,]+$/.test(t)&&(t=t.slice(0,t.length-1)),/\d \/\d/.test(t)&&(t=t.replace(/ \//g,"/")),t.includes(" /")&&(t=t.replace(/ \//g," "));let c=/\(\d+, \)/g;c.test(t)&&t.match(c).forEach(E=>{let[U]=E.match(/\((\d+), \)/).slice(1);U.length===2?t=t.replace(E,`(${U})`):U.length===1&&U==="6"&&(t=t.replace(E,"(6-0)"))});let u=/\((\d+)\/\)/g;u.test(t)&&t.match(u).forEach(E=>{let[U]=E.match(/\((\d+)\/\)/).slice(1);U.length===2?t=t.replace(E,`(${U})`):U.length===1&&U==="6"?t=t.replace(E,"(6-0)"):t=t.replace(E,`(${U})`)});let p=/\d\/\d\/,/g;p.test(t)&&t.match(p).forEach(E=>{let[U]=E.match(/(\d\/\d)\/,/).slice(1);t=t.replace(E,`${U},`),e.push("slashComma")});let m=/\(\/(\d+)\)/g;m.test(t)&&t.match(m).forEach(E=>{let[U]=E.match(/\(\/(\d+)\)/).slice(1);U.length===2?t=t.replace(E,`(${U})`):U.length===1&&parseInt(U)<6?t=t.replace(E,`(6-${U})`):t=t.replace(E,`(${U})`)});let d,l,f,g,I,h=()=>{I=dr(t.split("")),l=I["("]===(I[")"]||0)+1,d=(I["("]||0)+1===I[")"],f=I["["]===I["]"]+1,g=l&&!f};h();let S=/(\d+-\d+\(\d+)0,/;if(S.test(t)){let[y]=t.match(S).slice(1);t=t.replace(S,y+")")}if(I["("]===I[")"]&&I["("]>1){let y=t.split(")(").join(") (").split(" ");y.every(D_)?t=y.map(E=>{let U=E.slice(1,E.length-1);return U.length>2?U:E}).join(" "):t=y.join(" ")}h();let T=/[A-Za-z]+/.test(t),A=/\d+/.test(t);if(!T&&!A)return{score:""};if(/^\[.+\]$/.test(t)&&"()/,- ".split("").some(y=>I[y])&&(t=t.slice(1,t.length-1)),/^\(.+\)$/.test(t)&&I["("]===1&&I[")"]===1&&"[]/,".split("").some(y=>I[y]>1)&&(t=t.slice(1,t.length-1)),t.startsWith("(")&&t.endsWith("))")&&(t=t.slice(1,t.length-1)),I["("]>(I[")"]||0)&&t[t.length-1]==="("&&(t=t.slice(0,t.length-1)+")",h()),I["("]===1&&!I[")"]&&t[0]==="("&&(t=t+")",h()),I["("]>(I[")"]||0)&&t.slice(0,2)==="(("&&(t=t.slice(1)),d){if(/^9\d/.test(t))t="("+t.slice(1);else if(t[0]!=="(")t="("+t;else{let y=[],E=0;for(let U of t.split("").reverse())U===")"&&(E?y.push("("):E+=1),U==="("&&(E-=1),y.push(U);y.reverse(),t=y.join("")}h()}if(I[")"]>(I["("]||0)&&t[0]===")"&&(t="("+t.slice(1),h()),g&&(t.endsWith(9)||/\d+0$/.test(t))&&(t=t.slice(0,t.length-1)+")",h()),g&&(!t.endsWith(")")||t.startsWith("(("))&&(t=t+")",h()),g){let y="",E=0;for(let U of t.split(""))U==="("&&(E?y+=")":E+=1),U===")"&&(E-=1),y+=U;t=y}h(),f&&!l&&(t=t+"]"),t.includes("([")&&t.includes("])")&&(t=t.split("([").join("[").split("])").join("]"),h()),/\(\d+0$/.test(t)&&(t=t.slice(0,t.length-1)+")"),h(),I[")"]===1&&!I["("]&&t.endsWith(")")&&(t=t.slice(0,t.length-1)),t.startsWith("(")&&t.endsWith(")")&&I["("]===1&&I[")"]===1&&(t=t.slice(1,t.length-1),h());let D=y=>{let E=y.indexOf("("),U=y.indexOf(")");return E>=0&&U>=0&&E<U};if(/^\([\d ]+.*[\d ]+\)$/.test(t)&&I["("]===I[")"]){let y=t.slice(1,t.length-1);D(y)&&(t=y,h())}return{score:t,applied:e}}function Cu(t){if(!/^[\d-]+(\(\d\))*$/.test(t))return t;let e=Zn("-",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 M_({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(")")),[y_,E_].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(Cu).join(" "),{score:t,applied:e}}function C_({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(Cd),i=0,s="";for(let d of o){let l=Zn(d,n).filter(h=>!i||h>i)[0],f=n.slice(i,l-1),g=n[l-1],I=e(g);if(/^\d+$/.test(I)&&I.length===2){let h=I.split(""),S=Math.abs(h.reduce((T,A)=>+T-+A));if(S===1){let T=[f.join(" "),[g,d].join("")].join(" ");s+=T,i=l+1}else if(S===0){let T=Math.max(...h);if([4,5,6,7,8,9].includes(T)){let A=[6,4].includes(T)?T+1:T-1,D=[T,A].sort().reverse().join("-"),y=[f.join(" "),[D,d].join("")].join(" ");s+=y,i=l+1}}}}if(o.length&&s.length){let d=n.slice(i).join(" ");return s=[s,d].join(" "),{score:s.trim()}}if(n.length===2&&["(","["].some(d=>n[1].includes(d))){let l=e(n[0]).split("");if(Math.abs(l.reduce((g,I)=>+g-+I,0))===1)return n[1]=r(n[1]),{score:n.join("")}}let a=n.map(d=>P_(d)&&"bracket"||_a(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=Zn("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;!_a(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(hg).test(d)&&"super"||new RegExp(vp).test(d)&&"tiebreak"||new RegExp(Md).test(d)&&"standard"||"unknown";return u.push(g),g==="standard"&&f?d.match(l)[1]:d}).join(" "),{score:t}}function R_({score:t,applied:e}){for(let P of[".",","," ","/"]){let N=new RegExp(`^(\\d+)\\${P}(\\d+)$`);if(N.test(t)){let C=t.match(N).slice(1).map(b=>parseInt(b)),O=Math.abs(C[0]-C[1]);O<=10&&O>=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,C,O,b,x]=t.match(r).slice(1);t=t.replace(r,`${P}${N}-${C} ${O}-${b}${x}`),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=Cu(t);c!==t&&(t=c,e.push("deDashMash"));let u=/^(\d)[-/,]+(\d{2})[-/,]+(\d)$/;if(u.test(t)){let[P,N,C]=t.match(u).slice(1),[O,b]=N.split("");t=`${P}-${O} ${b}-${C}`,e.push("smashSetPattern")}let p=/^(\d+)[ -](\d+)$/,m=/^([\d -]+)\/([\d -]+)$/;if(m.test(t)){let[P,N]=t.match(m).slice(1),C=P.trim(),O=N.trim();if(p.test(C)&&p.test(O)){let b=C.match(p).slice(1,3).join("-"),x=O.match(p).slice(1,3).join("-");t=`${b} ${x}`,e.push("slashSeparationPattern")}}let d=/^([\d -]+),([\d -]+)$/;if(d.test(t)){let[P,N]=t.match(d).slice(1),C=P.trim(),O=N.trim();if(p.test(C)&&p.test(O)){let b=C.match(p).slice(1,3).join("-"),x=O.match(p).slice(1,3).join("-");t=`${b} ${x}`,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,C]=t.match(g).slice(1),O=N.split(""),b=`${P}-${O[0]} ${O[1]}-${C}`;t=t.replace(g,b),e.push("noSetSeparationPattern"),f+=1}let I=/(^|\s)7-6\s(\d+)\s/g,h=t.match(I);if(h?.length){let P=/(^|\s)7-6\s(\d+)\s/;h.forEach(N=>{let C=N.match(P).slice(2)[0];t=t.replace(N,`7-6(${C}) `),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(C=>`(${C})`).join(" ")+" ";t=t.replace(P,N),e.push("slashCommaSetPattern")}let A=/\(6-\)/g;A.test(t)&&(t=t.replace(A,"(6-0)"),e.push("missingZeroPattern2"));let D=/(?<!-)(\d+)\/(\d+)(?!-)/g;if(D.test(t)){let P=t.match(D),N=/(?<!-)(\d+)\/(\d+)(?!-)/,C=t;P.forEach(O=>{let[b,x]=O.match(N).slice(1),w=`${b}-${x}`;C=C.replace(O,w)}),t=C,e.push("slashSetPattern")}let y=/(.*)\s(1\d)\s(\d+)$/;if(y.test(t)){let[P,N,C]=t.match(y).slice(1);P.replace(/\D/g,"").length>=4&&(t=P+` ${N}${C}`,e.push("spaceSeparatedSuperPattern"))}let E=/(^|\s)(\d+-\d+)\s(\d+)(\s|$)/g;for(let P of t.match(E)||[]){let[N,C,O,b]=P.match(/(^|\s)(\d+-\d+)\s(\d+)(\s|$)/).slice(1),[x,w]=C.split("-").map(L=>parseInt(L));Math.abs(x-w)===1&&(t=t.replace(P,`${N}${C}(${O})${b}`),e.push("spaceSeparatedSetPattern"))}let U=/\d-\d \(\d{1,2}\)(\s|$|,)/g;for(let P of t.match(U)||[]){let N=/(\d-\d) \((\d{1,2})\)(\s|$|,)/,[C,O,b]=P.match(N).slice(1),[x,w]=C.split("-").map(L=>parseInt(L));Math.abs(x-w)===1&&(t=t.replace(P,`${C}(${O})${b}`),e.push("floatingTiebreakPattern2"))}let M=/(^|\s)(\d \d)\(/g;for(let P of t.match(M)||[]){let N=/(^|\s)(\d \d)\(/,[C,O]=P.match(N).slice(1);t=t.replace(P,`${C}${O.split(" ").join("-")}(`),e.push("spacedTiebreakPattern")}return{score:t,applied:e}}function b_({score:t,matchUpStatus:e}){let r=t?.split(" ");t=r.map(a=>{if(a.endsWith("]")){let c=a.split("[");if(_a(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(te(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=xp(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 _a(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 O_({score:t,attributes:e,identifier:r}){if(typeof t!="string")return{score:t,identifier:r};let n=new RegExp(/\([\d,/ ]+\)/g),o=t.match(n);for(let m of o||[]){let l=m.match(/^\((.*)\)$/)?.slice(1)?.[0],g=t.split(m)[0].split(")").reverse()[0].replace(/\D/g,"");if(l?.length===2&&g?.length>=2){let S=g.slice(g.length-2).split("").map(A=>parseInt(A));if(Math.abs(S[0]-S[1])===1)continue}let I=iD(l),h=Cu(I);t=t.replace(m,`(${h})`).trim()}let i=new RegExp(/\[[\d,/ ]+\]/g);t.match(i)?.forEach(m=>{let d=iD(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(",")||Cd(h)),f=d.every(h=>h.includes("/")||Cd(h)),g=d.every(h=>h.includes("-")||Cd(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())),A=Math.min(...T);h==="set"?m+=`(${A}) `:m+=`[${T.join("-")}] `,h="tiebreak"}}),t=m.trim()}}let u=dr(t.split(""));u["("]===1&&u[")"]===1&&t.startsWith("(")&&t.endsWith(")")&&(t=t.slice(1,t.length-1),u["-"]===1&&_a(t)&&te(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 qS({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=te(a)&&parseInt(a),u=n[0]!==void 0&&n[1]!==void 0;if(te(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&&te(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 Sg(t){let e=t.indexOf("1"),r=t.split(""),n=r.every(o=>!isNaN(o));if(n&&t.length===3&&e===0){let o=xp(r,e);if(o)return o}if(n&&t.length===7&&e>3){let o=r.slice(4),i=xp(o,e-4);if(i)return`${r[0]}-${r[1]} ${r[2]}-${r[3]} ${i}`}}function sD(t){let{score:e}=t,{applied:r,matchUpStatus:n}=t,o=e?.toString().split(""),i=o?.every(a=>te(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}=qS({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=Sg(e);u&&e!==u&&r.push("parsedSuperPattern"),e=u??e}else{let u=Te(e.split(""),2).map(h=>h.join("")),p=u.map(h=>{let[S,T]=h.split("").map(y=>parseInt(y)),A=Math.abs(S-T),D=S>T?1:2;return A>1&&D||D*-1}),m=p.reduce((h,S)=>h>0&&S>0,1),d=dr(p),l=p.map(h=>Math.abs(h)),f=dr(l),g=p[0]<0,I=!g&&p[1]<0;if(p[0]>0&&p[1]>0&&p[0]!==p[1])e=[u.slice(0,2).join(" "),u.slice(2).join("-")].join(" "),r.push("numeric3rdSetTiebreakPattern");else if(m)e=u.join(" "),r.push("chunkSplit");else if(a.length==6){if(d[1]==2||d[2]===2)if(!Object.values(f).includes(3))e=u.join(" "),r.push("chunkSplit");else{let[h,S,T,A,D,y]=a,E=p.reduce((U,M,P)=>M<0?P:U,void 0);if(E===0){let U=Math.min(T,A);e=`${h}-${S}(${U}) ${D}-${y}`,r.push("chunkSplitTiebreak1")}else if(E===1){let U=Math.min(D,y);e=`${h}-${S} ${T}-${A}(${U})`,r.push("chunkSplitTiebreak2")}else e=`${h}-${S} ${T}-${A}`,r.push("chunkSplitTrimExtraneous")}}else if(a.length===8){let[h,S,T,A,D,y,E,U]=a;g||I?a[5]===1&&(g?e=`${h}-${S}(${T}) ${A}-${D} [${y}${E}-${U}]`:e=`${h}-${S} ${T}-${A}(${D}) [${y}${E}-${U}]`):(p[0],p[1])}}}return{score:e,applied:r,matchUpStatus:n}}function $S(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 __({score:t,matchUpStatus:e,attributes:r}){let n=[],o,i=t.split(" "),s=i.length;t=i.map((p,m)=>{if(new RegExp(vp).test(p)){let l=p.slice(3),f=p.slice(0,3),g=f.split("-");if(!_a(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&&te(p))return p.split("").join("-");p=Cu(p);let d=new RegExp(`^${hg}$`).test(p)&&"super"||new RegExp(`^${vp}$`).test(p)&&"tiebreak"||new RegExp(`^${Md}$`).test(p)&&"standard"||"unknown";if(n.push(d),s>1&&d==="standard"&&m<2){let[l,f]=p.split("-"),g=Math.abs(parseInt(l)-parseInt(f)),I=Math.max(l,f),h=Math.min(l,f),S=[parseInt(l),parseInt(f)].indexOf(h);if(I>9&&g>2){let T=I.toString().split(""),A=T.find(D=>parseInt(D)>h||m&&parseInt(D)<=o)??T[0];A&&(p=S?[A,h].join("-"):[h,A].join("-"))}I>(o||0)&&(o=I)}if(d==="standard"){let[l,f]=p.split("-");if(!Math.abs(parseInt(l)-parseInt(f))&&e!=="RETIRED")return""}return p}).filter(Boolean).join(" ");let{setsWon:a,setWinners:c,totalSets:u}=$S(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 v_({score:t}){let{setsTied:e,winningSide:r}=$S(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=>te(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 ok({score:t}){return t=t?.toString().toLowerCase()||"",{score:t}}function ik({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 sk({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=xp(r.split(""),n);return e.push("getSuper"),o}}else{let{score:o,applied:i}=sD({score:r,applied:[]});o!==r&&(r=o,e.push(...i))}}return r}).join(" "),{score:t,applied:e})}function ak({score:t,applied:e}){return typeof t!="string"?{score:t}:[3,4].includes(t.length)&&Sg(t)?{score:Sg(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 ck({score:t,applied:e}){return["walkover","wo","w/o","w-o"].includes(t?.toString().toLowerCase())?(e.push("handleWalkover"),{matchUpStatus:"walkover",score:"",applied:e}):{score:t}}function uk({score:t,profile:e,applied:r}){t=t?.toString().toLowerCase();let n=/^(.*\d+.*)(ret|con)+[A-Za-z ]*$/;if(n.test(t)){let[a]=t.match(n).slice(1);return r.push("handleRetired"),{score:a.trim(),matchUpStatus:"retired",applied:r}}let o=e?.matchUpStatuses?.retired,s=["rtd",...Array.isArray(o)?o:[o].filter(Boolean)].find(a=>t?.endsWith(a));return s?(r.push("handleRetired"),{matchUpStatus:"retired",score:t?.replace(s,"").trim(),applied:r}):{score:t}}function pk({score:t,attributes:e}){(t.endsWith(" am")||t.endsWith(" pm"))&&(t=""),t=t.replace(/[A-Za-z]+/g,"").trim(),[".",","].some(o=>t.endsWith(o))&&(t=t.slice(0,t.length-1));let r="()/-".split("").some(o=>t.includes(o));/ \d$/.test(t)&&r&&(e={removed:t.slice(t.length-2).trim()},t=t.slice(0,t.length-2));let n=/(.*)[A-Za-z]+$/;return n.test(t)&&(t=t.match(n).slice(1)[0].trim()),{score:t,attributes:e}}function mk({score:t}){return new RegExp(/-\d+\/\d+-/).test(t)&&(t=t.split("/").join(" ")),{score:t}}function dk({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 lk({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 fk({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=>te(n))&&e.length===4&&(t=e)}return{score:t}}function gk({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 x_={handleTiebreakSlashSeparation:lk,handleSetSlashSeparation:mk,punctuationAdjustments:N_,handleGameSeparation:dk,joinFloatingTiebreak:C_,handleBracketSpacing:M_,handleSpaceSeparator:fk,separateScoreBlocks:sk,matchKnownPatterns:R_,removeDanglingBits:pk,removeErroneous:ak,handleWalkover:ck,properTiebreak:b_,handleNumeric:sD,handleRetired:uk,containedSets:O_,sensibleSets:__,stringScore:ok,superSquare:v_,setBuilder:qS,excisions:gk,replaceOh:ik};var aD={},Ik=[],hk=["handleNumeric","handleWalkover","handleRetired","replaceOh","stringScore","punctuationAdjustments","excisions","handleSpaceSeparator","matchKnownPatterns","removeDanglingBits","handleBracketSpacing","matchKnownPatterns","containedSets","separateScoreBlocks","handleGameSeparation","removeErroneous","joinFloatingTiebreak","handleSetSlashSeparation","handleTiebreakSlashSeparation","properTiebreak","sensibleSets","superSquare"],Sk=["handleNumeric","separateScoreBlocks","sensibleSets","superSquare"];function cD(t){if(!t.score)return{error:G};let{score:e,sheetName:r,identifier:n,fileName:o,stepLog:i,fullLog:s,profile:a}=t,c=[],u,p=[],m,d,l=e,f=I=>{I.forEach(h=>{d=x_[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(hk);let g=oD(l);return g||(l=e.toString().replace(/\D/g,""),m?.removed&&(m.removed=void 0),f(Sk),g=oD(l),g||(Ik.push({score:l,fileName:o,sheetName:r}),l="")),p.forEach(I=>{aD[I]||(aD[I]=0),aD[I]+=1}),{matchUpStatus:u?.toUpperCase(),modifications:c,attributes:m,isValid:g,score:l}}var pD={};Jt(pD,{analyzeSet:()=>Ru,checkScoreHasValue:()=>Ie,checkSetIsComplete:()=>Op,getSetComplement:()=>Ag,getTiebreakComplement:()=>wp,isValidMatchUpFormat:()=>Sr,parseScoreString:()=>Rd,validateScore:()=>Tg,validateTieFormat:()=>ir});function w_({existingMatchUpStatus:t,matchUpFormat:e,matchUpStatus:r,winningSide:n,score:o}){let i=o?.sets??[],a=(i?.filter(y=>y?.winningSide)||[]).reduce((y,E)=>{let{winningSide:U}=E;if(!U)return y;let M=U-1;return y[M]++,y},[0,0]),c=n?n-1:void 0,u=c!==void 0?1-c:void 0,p=c!==void 0&&a[c],m=u!==void 0&&a[u],d=e?tr(e):void 0,l=Math.max(...a),f=dr(a)[l],g=d?.bestOf,I=g&&Math.ceil(g/2)||1,h=r??t,S=h&&[Ot,lr,_t].includes(h),T=!d||!i.length||i.every((y,E)=>{let U=E+1,M=U===g,P=U===i.length,{side1Score:N,side2Score:C,side1TiebreakScore:O,side2TiebreakScore:b,winningSide:x}=y,w=Math.max(N??0,C??0),F=O??b,{finalSetFormat:L,setFormat:v}=d,B=M&&L||v;if(F){let{tiebreakTo:j,NoAD:V}=B?.tiebreakFormat||{},Y=Math.max(O??0,b??0);if(V&&Y>j||Y<j&&x&&(P&&!S||!P))return!1}return B.setTo?!(!B.noTiebreak&&w>B.setTo+1):!0}),A=(!e||l===I)&&f===1&&a.indexOf(l)+1||void 0;return{valid:T&&(n&&p>m&&n===A||!n&&!A||S)}}function Tg({existingMatchUpStatus:t,matchUpFormat:e,matchUpStatus:r,winningSide:n,score:o}){if(typeof o!="object")return{error:G};let{sets:i,scoreStringSide1:s,scoreStringSide2:a}=o,c="scoreString must be a string!";if(s!==void 0&&typeof s!="string")return{error:G,info:c};if(a!==void 0&&typeof a!="string")return{error:G,info:c};if(i!==void 0&&!Array.isArray(i))return{error:G,info:Nn("sets")};if(i?.length){let u=i.map(m=>m?.setNumber).filter(Boolean);if(u.length!==pt(u).length)return{error:G,info:"setNumbers not unique"};for(let m of i){let{side1Score:d,side2Score:l,side1TiebreakScore:f,side2TiebreakScore:g,side1PointScore:I,side2PointScore:h,winningSide:S,setNumber:T}=m;if(![[d,l],[f,g],[I,h]].filter(y=>y.some(E=>E!==void 0)).every(y=>y.every(E=>ft(E))))return{error:G,info:"non-numeric values"};if(![T,S].filter(y=>y!==void 0).every(y=>ft(y)))return{error:G,info:"non-numeric values"};if(S&&![1,2].includes(S))return{error:G,info:"winningSide must be 1 or 2"}}let{valid:p}=w_({existingMatchUpStatus:t,matchUpStatus:r,matchUpFormat:e,winningSide:n,score:o});if(!p)return{error:My,info:"score is invalid for matchUpFormat or winningSide does not match calculated winningSide"}}return{valid:!0}}var Ag=t=>{let{isSide1:e,lowValue:r,setTo:n,tiebreakAt:o,NoAD:i}=t;if(r===void 0)return!1;let s=ct(r);s?.toString().length>2&&(s=parseInt(s.toString().slice(0,2))),o&&o<n&&s>o&&(s=o);let a;return i&&!o?(s>n&&(a=n),a=s<n?n:n-1):a=s+1<n&&n||o&&o<n&&s===o&&n||!o&&s+2||n+1,[e?s:a,e?a:s]},wp=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=Tk({lowValue:i,NoAD:o,tiebreakTo:n});return[e?i:s,e?s:i]};function Tk(t){let{lowValue:e,NoAD:r,tiebreakTo:n}=t,o=r?1:2;return e+1>=n?e+o:n}function Rd({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&&wp({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 L_({matchUpScoringFormat:t,isDecidingSet:e,isTiebreakSet:r,setObject:n}){if(!n)return;let o=_p({set:n});return Op({matchUpScoringFormat:t,set:n,isDecidingSet:e,isTiebreakSet:r})&&o||void 0}function Ru(t){let{setObject:e,matchUpScoringFormat:r}=t;if(!e)return{error:El};let{setNumber:n}=e||{},{bestOf:o}=r||{},i=!!(n&&o&&n===o),s=i&&r?.finalSetFormat||r?.setFormat,a=!!s?.tiebreakSet,c=!!s?.timed,u=!a&&!c,p=!!(n&&o&&n<=o),m=[e?.side1Score,e?.side2Score],d=[e?.side1PointScore,e?.side2PointScore],l=[e?.side1TiebreakScore,e?.side2TiebreakScore],f=m.filter(w=>w!==void 0).length,g=d.filter(w=>w!==void 0).length,I=l.filter(w=>w!==void 0).length,h=m?.filter(w=>!isNaN(w)).length,S=l?.filter(w=>!isNaN(w)).length,{tiebreakAt:T}=s||{},A=T&&m.filter(w=>w>=T).length===2,D=A&&(m[0]>m[1]&&1||m[1]>m[0]&&2||void 0),y=!!(S&&!h),E=!!e?.winningSide,{error:U,result:M}=Ak({setObject:e,setFormat:s,sideGameScores:m,sideTiebreakScores:l}),{error:P,result:N}=yk({setObject:e,setFormat:s,sideTiebreakScores:l}),C=u&&!y&&M||a&&y&&N,O=p&&!(a&&!y)&&!(u&&y)&&(!E||C),b=L_({isDecidingSet:i,isTiebreakSet:y,matchUpScoringFormat:r,setObject:e}),x={expectTiebreakSet:a,expectTimedSet:c,hasTiebreakCondition:A,isCompletedSet:E,isDecidingSet:i,isTiebreakSet:y,isValidSet:O,isValidSetNumber:p,isValidSetOutcome:C,leadingSide:D,setFormat:s,sideGameScores:m,sideGameScoresCount:f,sidePointScores:d,sidePointScoresCount:g,sideTiebreakScores:l,sideTiebreakScoresCount:I,winningSide:b};return e?.winningSide!==void 0&&(y?(x.isValidTiebreakSetOutcome=N,N||(x.tiebreakSetError=P)):(x.isValidStandardSetOutcome=M,M||(x.standardSetError=U))),x}function Ak({setObject:t,setFormat:e,sideGameScores:r,sideTiebreakScores:n}){if(!t)return{result:!1,error:El};let o=!!e?.tiebreakSet,i=!!e?.timed;if(!e||o||i)return{result:!1,error:G};if(!(r?.filter(N=>!isNaN(N)).length===2))return{result:!1,error:II};let{setTo:a,tiebreakAt:c,tiebreakFormat:u,NoAD:p}=e||{};if(!!!(a&&r?.find(N=>N>=a)))return{result:!1,error:II};let d=[1,2].includes(t?.winningSide);if(!t||!d)return{result:!1,error:im};let l=t?.winningSide-1,f=1-l,g=r[l],I=r[f],h=g-I;if(!(g>I))return{result:!1,error:{message:"winningSide game scoreString is not high"}};let T=c&&u,A=n?.filter(N=>!isNaN(N)).length===2,D=n?.[l],y=n?.[f],E=c&&r.filter(N=>N>=c).length===2;if(T){let{NoAD:N,tiebreakTo:C}=u;if(E){if(h>1)return{result:!1,error:{message:"invalid winning game scoreString (5)"}};if(!A)return{result:!1,error:{message:"invalid tiebreak scores (1)"}};if(isNaN(C))return{result:!1,error:{message:"tiebreakTo error"}};if(!!!(C&&n?.find(B=>B>=C)))return{result:!1,error:{message:"invalid tiebreak scores (2)"}};let x=c<a?a:a+1;if(g>x)return{result:!1,error:{message:"invalid winning game scoreString (1)"}};if(!D||!y||D<y)return{result:!1,error:{message:"winningSide tiebreak value is not high"}};let w=N?1:2,F=D-y,L=y>=C-1;if(F&&L&&F<w)return{result:!1,error:{message:"invalid tiebreak scores (3)"}}}if(g>a&&!E)return{result:!1,error:{message:"invalid winning game scoreString (2)"}}}let U=p?1:2,M=I>=a-1;return h&&M&&!E&&h<U?{result:!1,error:{message:"invalid winning game scoreString (3)"}}:h>U&&g>a?{result:!1,error:{message:"invalid winning game scoreString (4)"}}:{result:!0}}function yk({setObject:t,setFormat:e,sideTiebreakScores:r}){if(!t)return{result:!1,error:El};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:im};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 KS={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 zS={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 QS={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 XS={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 JS={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 ZS={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 tT={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 eT={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 rT={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 nT={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 oT={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 iT={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 sT={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 aT={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 cT={collectionDefinitions:[{collectionName:"Male Singles",gender:"MALE",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{collectionName:"Female Singles",gender:"FEMALE",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{collectionName:"Male Doubles",gender:"MALE",matchUpCount:3,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1},{collectionName:"Female Doubles",gender:"FEMALE",matchUpCount:3,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1},{collectionName:"Mixed Doubles",gender:"MIXED",matchUpCount:1,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1}],tieFormatName:"USTA_ZONAL",winCriteria:{valueGoal:10}};var uT={collectionDefinitions:[{collectionGroupNumber:1,matchUpType:"DOUBLES",matchUpCount:1,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpValue:1},{collectionGroupNumber:1,matchUpType:"SINGLES",matchUpCount:3,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpValue:1},{collectionGroupNumber:2,matchUpType:"DOUBLES",matchUpCount:1,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpValue:2},{collectionGroupNumber:2,matchUpType:"SINGLES",matchUpCount:3,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpValue:2},{collectionGroupNumber:3,matchUpType:"DOUBLES",matchUpCount:1,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpValue:3},{collectionGroupNumber:3,matchUpType:"SINGLES",matchUpCount:3,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpValue:3}],collectionGroups:[{groupNumber:1,groupName:"Day 1"},{groupNumber:2,groupName:"Day 2"},{groupNumber:3,groupName:"Day 3"}],tieFormatName:"LAVER_CUP",winCriteria:{valueGoal:13}};var pT={collectionDefinitions:[{collectionName:"Female Doubles",gender:"FEMALE",matchUpCount:1,matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Male Doubles",gender:"MALE",matchUpCount:1,matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Female Singles",gender:"FEMALE",matchUpCount:1,matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"SINGLES",scoreValue:1},{collectionName:"Male Singles",matchUpCount:1,gender:"MALE",matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"SINGLES",scoreValue:1},{collectionName:"Mixed Doubles",matchUpCount:1,gender:"MIXED",matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Overtime",matchUpCount:1,gender:"MIXED",matchUpFormat:"SET1-S:T20",matchUpType:"DOUBLES",scoreValue:1}],tieFormatName:"USTA_TOC",winCriteria:{aggregateValue:!0}};var mT="COLLEGE_DEFAULT",dT="COLLEGE_JUCO",lT="COLLEGE_D3",mD="DOMINANT_DUO",dD="DOMINANT_DUO_MIXED",lD="LAVER_CUP",fD="TEAM_DOUBLES_3_AGGREGATION",gD="TIME_TENNIS_DUAL",ID="TIME_TENNIS_PRO_CIRCUIT",hD="USTA_BREWER_CUP",SD="USTA_OZAKI_CUP",TD="USTA_COLLEGE",AD="USTA_GOLD_TEAM_CHALLENGE",yD="USTA_LEVEL_1",ED="USTA_INTERSECTIONAL",UD="USTA_SECTION_BATTLE",PD="USTA_SOUTHERN_LEVEL_5",DD="USTA_TOC",ND="USTA_WTT_ITT",MD="USTA_ZONAL",F_={COLLEGE_D3:lT,COLLEGE_DEFAULT:mT,COLLEGE_JUCO:dT,DOMINANT_DUO:mD,DOMINANT_DUO_MIXED:dD,LAVER_CUP:lD,TEAM_DOUBLES_3_AGGREGATION:fD,TIME_TENNIS_DUAL:gD,TIME_TENNIS_PRO_CIRCUIT:ID,USTA_BREWER_CUP:hD,USTA_OZAKI_CUP:SD,USTA_COLLEGE:TD,USTA_GOLD_TEAM_CHALLENGE:AD,USTA_INTERSECTIONAL:ED,USTA_LEVEL_1:yD,USTA_SECTION_BATTLE:UD,USTA_SOUTHERN_LEVEL_5:PD,USTA_TOC:DD,USTA_WTT_ITT:ND,USTA_ZONAL:MD};var k_="STANDARD",G_={[k_]:{hydrate:!0,doubles:{matchUpCount:3,matchUpValue:1},singles:{matchUpCount:6,matchUpValue:1},valueGoal:5},[lT]:{hydrate:!0,doubles:{matchUpCount:3,matchUpValue:1,matchUpFormat:"SET1-S:8/TB7@7"},singles:{matchUpFormat:un,matchUpCount:6,matchUpValue:1},tieFormatName:lT,valueGoal:5},[mT]:{hydrate:!0,doubles:{matchUpCount:3,collectionValue:1,matchUpFormat:un},singles:{matchUpCount:6,matchUpValue:1,matchUpFormat:un},tieFormatName:mT,valueGoal:4},[dT]:{hydrate:!0,doubles:{matchUpCount:3,matchUpValue:1,matchUpFormat:"SET1-S:8/TB7"},singles:{matchUpCount:6,matchUpValue:1,matchUpFormat:un},tieFormatName:dT,valueGoal:5},[lD]:uT,[mD]:oT,[dD]:tT,[fD]:zS,[gD]:eT,[ID]:ZS,[hD]:rT,[SD]:nT,[TD]:iT,[AD]:KS,[ED]:JS,[yD]:sT,[UD]:XS,[PD]:QS,[ND]:aT,[DD]:pT,[MD]:cT},kk=t=>{let e=t?.namedFormat&&Object.keys(G_).includes(t.namedFormat)?t.namedFormat:k_,r=Array.isArray(t?.uuids)?t?.uuids:[],n,{category:o,gender:i}=t?.event??{},s=J(G_[e],!1,!0),a=c=>{if(!t?.isMock&&!t?.event?.isMock||!t.event)return r?.pop()??Mt();let u=t?.event?.eventId;return r.pop()??`${u}-COL-${c+1}`};return s.hydrate?(n={winCriteria:{valueGoal:s.valueGoal},collectionDefinitions:[{collectionId:a(0),matchUpFormat:YU,collectionName:"Doubles",matchUpType:Gt,...s.doubles},{collectionId:a(1),matchUpFormat:un,collectionName:"Singles",matchUpType:Xt,...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},Bi=kk;function V_(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===Fe&&s===Fe){let m=e?.structures?.find(({stage:d})=>d===tt)?.tieFormat;u=u||m||o&&c?.tieFormat?.tieFormatName===o&&c.tieFormat||o&&Bi({namedFormat:o,hydrateCollections:r,isMock:a,event:c})||c?.tieFormat||Bi({event:c,isMock:a,hydrateCollections:r}),p=void 0}else p||(u=void 0,c?.matchUpFormat||(p=un));if(u){let m=ir({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,drawEntries:n,appliedPolicies:o,structureId:i,idPrefix:s,isMock:a}=t,c=t.qualifyingProfiles,u=c?.length?OS({uuids:t.uuids,qualifyingProfiles:c,appliedPolicies:o,idPrefix:s,isMock:a}):void 0;if(u?.error)return u;e.structures=e.structures?.filter(({structureId:S})=>S!==r),e.links=e.links?.filter(({source:S})=>S.structureId!==r);let{qualifiersCount:p,qualifyingDrawPositionsCount:m,qualifyingDetails:d}=u??{};m&&(u?.structures&&e.structures?.push(...u.structures),u?.links&&e.links?.push(...u.links));let l=e.structures?.find(({stage:S,stageSequence:T})=>S===tt&&T===1),{qualifiersCount:f}=cs({stageSequence:1,drawDefinition:e,structureId:i,stage:tt}),g=Math.max(p??0,f??0),I=zh({qualifiersCount:g,drawDefinition:e,stage:tt});if(I.error||(I=yp({drawSize:m,stage:at,drawDefinition:e}),I.error))return I;Vk({drawDefinition:e,drawEntries:n});let h=Bk({mainStructure:l,qualifyingDetails:d,drawDefinition:e});return h.error?h:{drawDefinition:e,structureId:i}}function Vk({drawDefinition:t,drawEntries:e}){for(let r of(e??[]).filter(({entryStage:n})=>n===at)){let n={...r,entryStage:r.entryStage??tt,drawDefinition:t};_h(n)}}function Bk({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&&Na({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 fT(t){let{participantIds:e}=t,r=t.drawDefinition?.entries?.filter(n=>{let o=n.entryStatus;return!t.restrictEntryStatus||Or.includes(o)}).map(gt)??[];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:G,info:"Not enough participants for roundsCount"}:t.roundsCount&&t.restrictRoundsCount!==!1&&t.roundsCount>31?{error:G,info:"roundsCount must be less than 32"}:{participantIds:e}}function bd(t){let e=[],{roundsCount:r=1,drawDefinition:n,matchUpsCount:o,structureId:i,idPrefix:s,isMock:a,event:c}=t,u,p=fT(t);if(p.error)return p;for(let m of Z(1,r+1)){let d=Nu({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 W_(t){let{tournamentRecord:e,participantIds:r,scaleName:n,eventType:o,adHocRatings:i={}}=t,s=t.scaleAccessor??Br[n]?.accessor,a=e.participants??[];for(let c of r??[]){let u=a?.find(m=>m.participantId===c),p=H_({scaleName:`${n}.${vI}`,participant:u,eventType:o});!p&&n&&(p=H_({scaleAccessor:s,participant:u,scaleName:n,eventType:o})),p&&!i[c]&&(i[c]=p)}return i}function H_({scaleType:t=Ki,scaleAccessor:e,participant:r,scaleName:n,eventType:o}){let a=(r&&uo({scaleAttributes:{eventType:o??Fs,scaleType:t,scaleName:n},participant:r}))?.scaleItem?.scaleValue;return e&&Rt(a)?a[e]:a}function Od(t){let e=Wk(t);if(e?.error)return e;let r=fT(t);if(r.error)return r;let n=Hk(t);if(n.error)return n;let o=W_(t),i=t.tournamentRecord?.isMock??t.isMock,s=t.eventType??t.event?.eventType,a=[],c=[],u;for(let p of Z(1,(t.roundsCount??1)+1)){let m=Ed({...t,participantIds:r.participantIds,structure:n.structure,ignoreLastRoundNumber:!0,iterationMatchUps:a,adHocRatings:o,roundNumber:u,eventType:s,isMock:i});if(m.error)return m;let{matchUps:d,...l}=m;c.push({...l,iteration:p,matchUpsCount:d?.length}),u=(l?.roundNumber??1)+1,d?.length&&a.push(...d)}return{...R,matchUps:a,roundResults:c}}function Hk(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&&_s[s.stage];return fr({structure:s})&&a>(_s[i?.stage]||1)?s:i},void 0),n=e?.structures?.find(i=>i.structureId===r?.structureId);return n?fr({structure:n})?{structure:n}:{error:na}:{error:Lt}}function Wk(t){return t.roundsCount&&typeof t.roundsCount!="number"?{error:G,info:"roundsCount must be a number"}:typeof t.drawDefinition!="object"||t.drawDefinition.drawType&&t.drawDefinition.drawType!==an?{error:na}:!Array.isArray(t.drawDefinition?.entries)&&t.participantIds&&!Array.isArray(t.participantIds)?{error:G,info:"Missing Entries"}:{error:void 0}}function j_(t){let{tournamentRecord:e,drawDefinition:r,structureId:n,idPrefix:o,isMock:i,event:s}=t,a=s?.entries?.filter(({entryStage:p,entryStatus:m})=>(!p||p===tt)&&m&&Or.includes(m)),c=a?.map(gt),u=a?Math.floor(a.length/2):0;if(t.automated)return jk({...t,participantIds:c});{let p=bd({roundsCount:t.roundsCount,drawDefinition:r,matchUpsCount:u,idPrefix:o,isMock:i,event:s});if(p.error)return p;p.matchUps?.length&&fd({matchUps:p.matchUps,suppressNotifications:!0,tournamentRecord:e,drawDefinition:r,structureId:n,event:s})}return{...R}}function jk(t){let{restrictEntryStatus:e,generateMatchUps:r,structureId:n,matchUpIds:o,scaleName:i,scaleAccessor:s}=t.drawMatic??{},a=Od({...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&&fd({tournamentRecord:t.tournamentRecord,drawDefinition:t.drawDefinition,suppressNotifications:!0,matchUps:a.matchUps,event:t.event,structureId:n}),{...R})}function Y_({requireParticipantCount:t=!0,enforcePolicyLimits:e=!0,drawSizeProgression:r,participantsCount:n,participantCount:o,appliedPolicies:i,drawDefinition:s,seedingProfile:a,structureId:c,seedsCount:u}){n=n??o;let p=st({drawDefinition:s,structureId:c});if(p.error)return p;let m=p.structure;if(!m)return{error:Lt};let{positionAssignments:d}=de({structure:m}),l=d?.length||0;if(u>l)return{error:sy};let f=m.structures?.length,g=ft(a?.groupSeedingThreshold)&&a?.groupSeedingThreshold,I=Kf({roundRobinGroupsCount:f,drawSize:l})?.seedGroups,{seedsCount:h}=Du({policyDefinitions:i,requireParticipantCount:t,drawSizeProgression:r,participantsCount:n,drawSize:l});return h&&i?.[Un]&&u>h&&e&&(u=h),m.seedLimit=u,m.seedAssignments=Z(1,u+1).map(S=>{let T=I?.find(y=>y.includes(S)),A=T&&Math.min(...T),D=g&&S>=g?A:S;return{participantId:void 0,seedNumber:S,seedValue:D}}),bt({drawDefinition:s,structureIds:[c]}),{...R,seedLimit:u}}function Qs({sortDescending:t=!1,tournamentRecord:e,scaleAttributes:r,scaleSortMethod:n,stageSequence:o,entries:i,event:s,stage:a}){if(!e)return{error:W};return i=i??s?.entries??[],{scaledEntries:i.filter(d=>(!a||!d.entryStage||d.entryStage===a)&&(!o||!d.entryStageSequence||d.entryStageSequence===o)&&Or.includes(d.entryStatus)).map(d=>{let{participantId:l}=d,{scaleItem:f}=Pc({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 gT(t){let e="prepareStage",{drawDefinition:r}=t,{structures:n}=xn({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}=Jk({...t,structureId:s});(t.seededParticipants||t.event||t.seedingScaleName)&&$k({...t,seedsCount:a,structure:i,structureId:s});let p=t.automated!==!1&&t.drawType!==an&&!(t.qualifyingOnly&&t.stage!==at),m=(n?.length||0)>1,d=p?qk({...t,multipleStructures:m,seedLimit:u,structureId:s}):{};return d?.error?_({result:d,stack:e}):{...d,stageEntries:c,structureId:s,seedsCount:a}}function Yk({entries:t,stage:e,stageSequence:r,roundTarget:n}){return t.filter(o=>{let i=mt({name:mn,element:o})?.extension?.value;return(!o.entryStage||o.entryStage===e)&&(!r||!o.entryStageSequence||o.entryStageSequence===r)&&(!n||!i||i===n)&&qo.includes(o.entryStatus)})}function qk(t){let e=typeof t.automated=="object"&&t.automated.seedsOnly,r=hc({...t,seedsOnly:e});if(r.error)return r;let n=r?.positionAssignments,o=r?.positioningReport;return{conflicts:r.conflicts,positionAssignments:n,positioningReport:o}}function $k(t){let{seededParticipants:e,seedingScaleName:r,entries:n,event:o}=t,i=n.map(gt);e?Kk({...t,enteredParticipantIds:i}):(o||r)&&zk({...t,enteredParticipantIds:i})}function Kk(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?ms({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;Ws({provisionalPositioning:e,tournamentRecord:o,drawDefinition:s,seedingProfile:a,participantId:l,seedBlockInfo:m,structureId:c,seedNumber:f,seedValue:g,event:p})})}function zk(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=Qk({...t,ageCategoryCode:l,categoryName:d,eventType:f})||c&&Xk({...t,ageCategoryCode:l,categoryName:d,eventType:f}),I=g?.length??0;I<e&&(e=I),g?.filter(({participantId:h})=>n.includes(h)).slice(0,i||e).forEach((h,S)=>{let T=S+1,{participantId:A,scaleValue:D}=h,y=o?.[T]||D||T;Ws({provisionalPositioning:r,tournamentRecord:s,drawDefinition:a,seedingProfile:u,participantId:A,structureId:p,seedNumber:T,seedValue:y,event:m})})}function Qk(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:eo,eventType:u};return Qs({scaleAttributes:p,tournamentRecord:e,stageSequence:n,entries:o,stage:i}).scaledEntries}function Xk(t){let{tournamentRecord:e,stageSequence:r,event:n,entries:o,stage:i}=t,{categoryName:s,ageCategoryCode:a}=n?.category||{},c=n?.eventType;return Qs({scaleAttributes:{scaleName:s||a,scaleType:oi,eventType:c},tournamentRecord:e,stageSequence:r,entries:o,stage:i}).scaledEntries}function Jk(t){let{seedsCount:e}=t;t.seededParticipants&&(e=t.seededParticipants.length),e>t.drawSize&&(e=t.drawSize);let r=Yk(t);e>r.length&&(e=r.length);let{seedLimit:n}=Y_({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 q_(t){let e=Ad({...t,modifyOriginal:!1});if(e.error)return e;let r=e.drawDefinition,{ignoreStageSpace:n,appliedPolicies:o,qualifyingOnly:i,seedingProfile:s,participants:a,drawEntries:c,placeByes:u,drawSize:p,drawType:m,entries:d}=t,l=[],f=[],g=Zk({ignoreStageSpace:n,drawDefinition:r,drawEntries:c,drawType:m,entries:d});if(g.error)return g;let I=m===Oi?0:ct(t.seedsCount??0),h=gT({...t,qualifyingOnly:!p||i,appliedPolicies:o,drawDefinition:r,seedingProfile:s,participants:a,stage:tt,seedsCount:I,placeByes:u,drawSize:p,entries:d});if(h.error&&!h.conflicts)return h;h.positioningReport?.length&&l.push({[tt]:h.positioningReport});let S=h.structureId;return h.conflicts&&(f=h.conflicts),m===an&&t.roundsCount&&j_({...t,drawDefinition:r,structureId:S}),{drawDefinition:r,positioningReports:l,conflicts:f,structureId:S}}function Zk(t){let{ignoreStageSpace:e,drawDefinition:r,drawEntries:n,drawType:o,entries:i}=t;for(let s of i){if(n&&s.entryStage&&s.entryStage!==tt)continue;let a={...s,ignoreStageSpace:e??o===an,entryStage:s.entryStage??tt,drawDefinition:r,drawType:o},c=_h(a);if(n&&c.error)return c}return{error:void 0}}var tV=()=>({matchUpType:void 0,drawName:void 0,drawId:void 0,structures:[],entries:[],links:[]});var $_=tV;function K_(t){let{drawId:e=Mt(),processCodes:r,matchUpType:n,drawType:o}=t??{},i=$_();return Object.assign(i,{processCodes:r,matchUpType:n,drawType:o,drawId:e})}function _d(t){let e=t.structureIds,{tournamentRecord:r,drawDefinition:n,matchUpFormat:o,structureId:i,matchUpId:s,event:a}=t,c=lt(t,[{[Yr]:!0,[mm]:!0}]);if(c.error)return c;if(!Sr({matchUpFormat:o}))return{error:Ya};let u="setMatchUpFormat";if(s){let p=xt({drawDefinition:n,matchUpId:s,event:a});if(p.error)return p;let m=p.matchUp;if(m?.matchUpType===Fe)return{info:"Cannot set matchUpFormat when { matchUpType: TEAM }",error:Je};m&&(m.matchUpFormat=o,It({tournamentId:r?.tournamentId,eventId:a?.eventId,context:u,drawDefinition:n,matchUp:m}))}else if(Array.isArray(e)){if(a?.eventType===Fe)return{error:No};for(let p of e){let m=st({drawDefinition:n,structureId:p});if(m.error)return m;m.structure&&(m.structure.matchUpFormat=o)}}else if(i){if(a?.eventType===Fe)return{error:No};let p=st({drawDefinition:n,structureId:i});if(p.error)return p;p.structure&&(p.structure.matchUpFormat=o)}else n&&(n.matchUpFormat=o);return e=e??(i?[i]:void 0),bt({drawDefinition:n,structureIds:e}),{...R}}function z_({tieFormat:t}){let e=ir({checkCollectionIds:!1,tieFormat:t});if(e.error)return e;for(let r of t.collectionDefinitions)r.collectionId||(r.collectionId=Mt());return{tieFormat:t}}function Q_({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=z_({tieFormat:o});if(a.error)return a;e.tieFormat=a.tieFormat??o}else if(r){let a=_d({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 OD={};Jt(OD,{attachPolicies:()=>Vi,findPolicy:()=>$o,getAppliedPolicies:()=>Pt,getPolicyDefinitions:()=>yo,mutate:()=>RD,query:()=>bD,removePolicy:()=>CD});var RD={};Jt(RD,{attachPolicies:()=>Vi,removePolicy:()=>CD});function CD(t){let e=lt(t,[{[ZC]:!0,_anyOf:{[ye]:!1,[An]:!1,[Yr]:!1,[Cs]:!1}}]);if(e.error)return e;let r,n=t.drawDefinition??t.event??((t.tournamentId||!t.tournamentRecords)&&t.tournamentRecord);if(n)return X_(t,n);if(t.tournamentRecords){let o=Object.keys(t.tournamentRecords);if(!o.length)return{error:W};for(let i of o){let s=t.tournamentRecords[i],a=X_(t,s);if(a.error)return a;r=!0}}else return{error:W};return r?{...R}:{error:Lc}}function X_(t,e){let r=Pt(t).appliedPolicies??{};return r[t.policyType]?(delete r[t.policyType],Object.keys(r).length?St({element:e,extension:{name:jc,value:r}}):or({element:e,name:jc}),{...R}):{error:Lc}}var bD={};Jt(bD,{findPolicy:()=>$o,getAppliedPolicies:()=>Pt,getPolicyDefinitions:()=>yo});var _D={[Un]:{validSeedPositions:{ignore:!0},duplicateSeedNumbers:!0,drawSizeProgression:!0,seedingProfile:{drawTypes:{[so]:{positioning:si},[dn]:{positioning:si}},positioning:hR},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}]}},Eg=_D;function J_({appliedPolicies:t,policyDefinitions:e,drawDefinition:r,stack:n}){if(e&&typeof e!="object")return _({info:"policyDefinitions must be an object",result:{error:G},stack:n});let o={[Wc]:t?.[Wc]};return e?eV({policyDefinitions:e,appliedPolicies:t,policiesToAttach:o,drawDefinition:r}):o.avoidance&&Vi({drawDefinition:r,policyDefinitions:o}),!t?.[Un]&&!e?.[Un]&&(Vi({policyDefinitions:Eg,drawDefinition:r}),t&&Object.assign(t,Eg)),{error:void 0}}function eV({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&&(Vi({policyDefinitions:r,drawDefinition:n}),e&&Object.assign(e,r))}function Z_(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??K_({processCodes:t.processCodes,drawId:t.drawId,drawType:a}),d=Q_({tournamentRecord:e,drawDefinition:m,matchUpFormat:r,matchUpType:i,tieFormat:s,event:u});if(d.error)return _({result:d,stack:c});let l=J_({appliedPolicies:n,policyDefinitions:o,drawDefinition:m,stack:c});if(l.error)return l;let f=p?.structures?.find(h=>h.stage===tt&&h.stageSequence===1)?.structureId,g=p?p.structures?.filter(h=>h.stage===at):[],I=g?.length===1&&!g[0].matchUps?.length&&g[0].structureId;return{drawDefinition:m,structureId:f,existingDrawDefinition:p,existingQualifyingPlaceholderStructureId:I}}function tv(t){let e="generateOrGetExisting",r=[],n=[],o=Z_(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})||q_({...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 ev(t){let{qualifyingPlaceholder:e,qualifyingProfiles:r,existingDrawDefinition:n,positioningReports:o,appliedPolicies:i,qualifyingOnly:s,drawDefinition:a,seedingProfile:c,participants:u,structureId:p,entries:m,stack:d}=t,l=e&&!r?.length&&!n,f=[];if(r){let g=(T,A)=>T.stageSequence-A.stageSequence,I=(T,A)=>T.roundTarget-A.roundTarget,h=[],S=1;r.sort(I);for(let T of r){if(!Array.isArray(T.structureProfiles))return _({info:Nn("structureProfiles"),result:{error:et},stack:d});S=T.roundTarget||S;let A=T.structureProfiles?.sort(g)||[],D=1;for(let y of A){let{qualifyingRoundNumber:E,qualifyingPositions:U,seededParticipants:M,seedingScaleName:P,seedsCount:N=0,seedByRanking:C,placeByes:O,drawSize:b}=y,x=gT({...t,seedingProfile:y.seedingProfile??c,stageSequence:D,qualifyingRoundNumber:E,preparedStructureIds:h,qualifyingPositions:U,seededParticipants:M,stage:at,seedingScaleName:P,appliedPolicies:i,drawDefinition:a,qualifyingOnly:s,seedByRanking:C,participants:u,roundTarget:S,seedsCount:N,placeByes:O,drawSize:b,entries:m});if(x.error)return x;x.structureId&&h.push(x.structureId),D+=1,x.conflicts?.length&&f.push(...x.conflicts),x.positioningReport?.length&&o.push({[at]:x.positioningReport})}S+=1}}else if(p&&l){let g=en({structureName:Ye(at),stage:at}),{link:I}=Na({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 XD={};Jt(XD,{addGoesTo:()=>wi,allCompetitionMatchUps:()=>cn,allDrawMatchUps:()=>rr,allEventMatchUps:()=>co,allPlayoffPositionsFilled:()=>Yh,allTournamentMatchUps:()=>le,analyzeDraws:()=>Eu,analyzeMatchUp:()=>Vp,analyzeTournament:()=>DT,bulkUpdatePublishedEventIds:()=>MT,calculateWinCriteria:()=>Is,categoryCanContain:()=>dd,checkMatchUpIsComplete:()=>is,checkValidEntries:()=>Sd,compareTieFormats:()=>Go,competitionScheduleMatchUps:()=>Ou,credits:()=>rv,drawMatchUps:()=>WT,eventMatchUps:()=>Wd,filterParticipants:()=>lu,findDrawDefinition:()=>fS,findExtension:()=>mt,getAllDrawMatchUps:()=>re,getAllEventData:()=>CT,getAllStructureMatchUps:()=>At,getAllowedDrawTypes:()=>vd,getAllowedMatchUpFormats:()=>yT,getAppliedPolicies:()=>Pt,getAssignedParticipantIds:()=>Si,getAvailableMatchUpsCount:()=>gd,getAvailablePlayoffProfiles:()=>Iu,getCategoryAgeDetails:()=>Au,getCheckedInParticipantIds:()=>es,getCompetitionDateRange:()=>wd,getCompetitionMatchUps:()=>kp,getCompetitionParticipants:()=>IT,getCompetitionPenalties:()=>ET,getCompetitionVenues:()=>Lp,getCourtInfo:()=>Hm,getCourts:()=>jT,getDrawData:()=>Fd,getDrawDefinitionTimeItem:()=>Dh,getDrawParticipantRepresentativeIds:()=>dS,getDrawTypeCoercion:()=>Pu,getEligibleVoluntaryConsolationParticipants:()=>mS,getEntriesAndSeedsCount:()=>Vd,getEvent:()=>$T,getEventData:()=>Gd,getEventMatchUpFormatTiming:()=>wT,getEventProperties:()=>YT,getEventPublishStatus:()=>vr,getEventStructures:()=>Qf,getEventTimeItem:()=>pu,getEvents:()=>qT,getFlightProfile:()=>Ht,getLinkedTournamentIds:()=>qc,getMatchUpCompetitiveProfile:()=>su,getMatchUpContextIds:()=>kT,getMatchUpDailyLimits:()=>Yd,getMatchUpDailyLimitsUpdate:()=>LT,getMatchUpDependencies:()=>Vr,getMatchUpFormat:()=>VT,getMatchUpFormatTiming:()=>au,getMatchUpFormatTimingUpdate:()=>vT,getMatchUpScheduleDetails:()=>Wm,getMatchUpType:()=>qm,getMatchUpsMap:()=>Ae,getMatchUpsStats:()=>BT,getMaxEntryPosition:()=>OT,getModifiedMatchUpFormatTiming:()=>Bd,getPairedParticipant:()=>tn,getParticipantEventDetails:()=>hT,getParticipantIdFinishingPositions:()=>lS,getParticipantMembership:()=>ST,getParticipantResults:()=>Su,getParticipantScaleItem:()=>Pc,getParticipantSchedules:()=>TT,getParticipantSignInStatus:()=>AT,getParticipantTimeItem:()=>Nh,getParticipants:()=>Yt,getPersonRequests:()=>yi,getPolicyDefinitions:()=>yo,getPositionAssignments:()=>Cp,getPositionsPlayedOff:()=>Ac,getPredictiveAccuracy:()=>GT,getProfileRounds:()=>kd,getPublishState:()=>as,getRoundMatchUps:()=>He,getRounds:()=>HT,getScaleValues:()=>aa,getScaledEntries:()=>Qs,getScheduledRoundsDetails:()=>bu,getSchedulingProfile:()=>ko,getSchedulingProfileIssues:()=>bT,getSeedingThresholds:()=>wh,getSeedsCount:()=>Du,getStructureSeedAssignments:()=>Fr,getTeamLineUp:()=>os,getTieFormat:()=>NT,getTimeItem:()=>Gn,getTournamentIds:()=>np,getTournamentInfo:()=>gs,getTournamentPenalties:()=>xd,getTournamentPersons:()=>PT,getTournamentStructures:()=>jh,getTournamentTimeItem:()=>mu,getValidGroupSizes:()=>Sp,getVenueData:()=>mc,getVenuesAndCourts:()=>po,isAdHoc:()=>fr,isCompletedStructure:()=>Jo,isValidForQualifying:()=>RS,isValidMatchUpFormat:()=>Sr,matchUpActions:()=>hd,participantScaleItem:()=>uo,participantScheduledMatchUps:()=>FT,positionActions:()=>CS,publicFindVenue:()=>Th,tallyParticipantResults:()=>Ca,tieFormatGenderValidityCheck:()=>pd,tournamentMatchUps:()=>jd,validMatchUp:()=>yf,validMatchUps:()=>Ur,validateCollectionDefinition:()=>yu,validateLineUp:()=>ed});function rv(){return`
|
|
@@ -20,5 +20,5 @@ var Ow=Object.defineProperty;var Jt=(t,e)=>{for(var r in e)Ow(t,r,{get:e[r],enum
|
|
|
20
20
|
|
|
21
21
|
And a special thanks to my family for putting up with the long days and weeks and months of coding
|
|
22
22
|
and conversations at all hours.
|
|
23
|
-
`}var vD={};Jt(vD,{filterParticipants:()=>lu,getCompetitionParticipants:()=>IT,getPairedParticipant:()=>tn,getParticipantEventDetails:()=>hT,getParticipantMembership:()=>ST,getParticipantScaleItem:()=>Pc,getParticipantSchedules:()=>TT,getParticipantSignInStatus:()=>AT,getParticipantTimeItem:()=>Nh,getParticipants:()=>Yt,getScaleValues:()=>aa,participantScaleItem:()=>uo,validateLineUp:()=>ed});function IT(t){let{tournamentRecords:e}=t||{};if(typeof e!="object"||!Object.keys(e).length)return{error:Ft};let r=[],n={},o={},i={},s=[],a={},c=[];for(let u of Object.values(e)){let{participantIdsWithConflicts:p,mappedMatchUps:m,participantMap:d,participants:l,matchUps:f,derivedEventInfo:g,derivedDrawInfo:I}=Yt({...t,tournamentRecord:u});Object.assign(a,m),Object.assign(n,d),Object.assign(o,g),Object.assign(i,I),r.push(...l??[]),s.push(...f??[]),p?.forEach(h=>{c.includes(h)||c.push(h)})}return{participantIdsWithConflicts:c,derivedEventInfo:o,derivedDrawInfo:i,participantMap:n,mappedMatchUps:a,participants:r,...R,matchUps:s}}function hT({tournamentRecord:t,participantId:e}){if(!t)return{error:W};if(!e)return{error:oe};let r=[e].concat((t.participants??[]).filter(o=>o?.participantType&&[kt,dt].includes(o.participantType)&&o.individualParticipantIds?.includes(e)).map(o=>o.participantId));return{eventDetails:(t.events??[]).filter(o=>{let i=(o?.entries??[]).map(s=>s.participantId);return xe(i,r)}).map(o=>({eventName:o.eventName,eventId:o.eventId}))}}function ST({tournamentRecord:t,participantId:e}){if(!t)return{error:W};if(!e)return{error:oe};let{participants:r}=Yt({participantFilters:{participantTypes:[kt,dt,Ar]},tournamentRecord:t});return(r??[]).filter(o=>o.individualParticipantIds?.includes(e)).reduce((o,i)=>{let s=i.participantType;return s&&(o[s]||(o[s]=[]),o[s].push(i)),o},{})}function TT({participantFilters:t={},tournamentRecord:e}){if(!e)return{error:W};if(typeof t!="object")return{error:Xn,context:{participantFilters:t}};let r={eventIds:t.eventIds},n=le({tournamentRecord:e,contextFilters:r}).matchUps??[],o=Object.assign({},...n.map(p=>({[p.matchUpId]:p}))),i=n.filter(({schedule:p})=>p&&Object.keys(p).length),s=Vr({tournamentRecord:e,matchUps:n}).sourceMatchUpIds??[],a={};for(let p of i){let{sides:m}=p,d,l=m?.map(g=>{if(g.participant)return[g.participant].concat(...g.participant.individualParticipants||[]);s[p.matchUpId]&&!d&&(d=(s[p.matchUpId]||[]).map(I=>o[I]).filter(({winningSide:I,bye:h})=>!I&&!h))}).filter(Boolean).flat()??[];for(let g of l){let{participantId:I}=g;a[I]||(a[I]={potentialMatchUps:[],participant:g,matchUps:[]}),a[I].matchUps.push(p)}let f=d?.map(({sides:g})=>g).flat().map(({participant:g})=>g&&[g].concat(...g.individualParticipants||[])).filter(Boolean).flat()||[];for(let g of f){let{participantId:I}=g;a[I]||(a[I]={potentialMatchUps:[],participant:g,matchUps:[]}),a[I].potentialMatchUps.push(p)}}return{participantSchedules:Object.values(a).filter(({participant:p})=>!(t.participantIds&&!t.participantIds.includes(p.participantId)||t.participantTypes&&!t.participantTypes.includes(p.participantType))),...R}}function AT({tournamentRecord:t,participantId:e}){if(!t)return{error:W};if(!e)return{error:oe};let{participant:r}=xo({tournamentRecord:t,participantId:e});if(!r)return{error:Zt};let{timeItem:n}=Gn({itemType:ic,element:r});return n&&n.itemValue===ru&&ru}var xD={};Jt(xD,{analyzeDraws:()=>Eu,analyzeTournament:()=>DT,getAllowedDrawTypes:()=>vd,getAllowedMatchUpFormats:()=>yT,getAppliedPolicies:()=>Pt,getCompetitionDateRange:()=>wd,getCompetitionPenalties:()=>ET,getPolicyDefinitions:()=>yo,getTournamentInfo:()=>gs,getTournamentPenalties:()=>xd,getTournamentPersons:()=>PT,getTournamentStructures:()=>jh,getTournamentTimeItem:()=>mu});function yT({tournamentRecord:t,categoryName:e,categoryType:r}){if(!t)return{error:W};let{appliedPolicies:n}=Pt({tournamentRecord:t});return(n?.[vn]?.matchUpFormats||[]).filter(({categoryNames:s,categoryTypes:a})=>!e&&!a||e&&s?.includes(e)||r&&a?.includes(r))}function vd({tournamentRecord:t,categoryName:e,categoryType:r}){if(!t)return{error:W};let{appliedPolicies:n}=Pt({tournamentRecord:t});return(n?.[hm]?.allowedDrawTypes||[]).filter(({categoryNames:s,categoryTypes:a})=>!e&&!a||e&&s?.includes(e)||r&&a?.includes(r))}function xd({tournamentRecord:t}){if(!t)return{error:W};let r=(t?.participants??[]).reduce((n,o)=>{let{participantId:i}=o;return(o.penalties??[]).forEach(s=>{let{penaltyId:a}=s||{};n[a]?n[a].participants.push(i):n[a]={...s,participantIds:[i]}}),n},{});return{penalties:Object.values(r)}}function ET({tournamentRecords:t}){if(typeof t!="object"||!Object.keys(t).length)return{error:Ft};let e=[];for(let r of Object.values(t)){let{penalties:n}=xd({tournamentRecord:r});e.push(...n??[])}return{penalties:e}}function UT({event:t}){return{eventInfo:(({eventId:r,eventName:n,eventType:o,eventLevel:i,surfaceCategory:s,matchUpFormat:a,category:c,gender:u,startDate:p,endDate:m,ballType:d,discipline:l,onlineResources:f,notes:g})=>({eventId:r,eventName:n,eventType:o,eventLevel:i,surfaceCategory:s,matchUpFormat:a,category:c,gender:u,startDate:p,endDate:m,ballType:d,discipline:l,onlineResources:f,notes:g}))(t)}}var rV={[Os]:{policyName:"Staff Privacy Policy",participant:{contacts:!1,individualParticipants:!1,individualParticipantIds:!1,onlineResources:!1,participantName:!0,participantOtherName:!0,participantId:!0,participantRole:!0,participantRoleResponsibilities:!0,participantStatus:!0,penalties:!1,representing:!0,participantType:!0,person:{addresses:!1,biographicalInformation:!1,birthDate:!1,contacts:!1,nationalityCode:!0,nativeFamilyName:!1,nativeGivenName:!1,onlineResources:!1,otherNames:!0,parentOrganisationId:!1,passportFamilyName:!1,passportGivenName:!1,personId:!1,personOtherIds:!1,previousNames:!1,sex:!1,standardFamilyName:!0,standardGivenName:!0,status:!1,tennisId:!1,wheelchair:!0}}}},nv=rV;function gs(t){let{tournamentRecord:e}=t??{};if(!e)return{error:W};let r=(({tournamentId:a,tournamentRank:c,tournamentStatus:u,formalName:p,tournamentName:m,promotionalName:d,onlineResources:l,localTimeZone:f,startDate:g,endDate:I,hostCountryCode:h,venues:S,notes:T,updatedAt:A})=>({tournamentId:a,tournamentRank:c,tournamentStatus:u,formalName:p,tournamentName:m,promotionalName:d,onlineResources:l,localTimeZone:f,startDate:g,endDate:I,hostCountryCode:h,venues:S,notes:T,updatedAt:A}))(e),n=Yt({participantFilters:{participantRoles:[gU,Bf,IU,hU,TU]},policyDefinitions:nv,tournamentRecord:e}).participants;n&&(r.tournamentContacts=n);let i=as({tournamentRecord:e})?.publishState?.tournament?.status?.publishedEventIds||[],s=[];for(let a of e.events??[])if(!t?.usePublishState||i.includes(a.eventId)){let c=UT({event:a}).eventInfo;c&&s.push(c)}return r.eventInfo=s,{tournamentInfo:J(r,!1,!0),...R}}function wd({tournamentRecords:t}){if(!Rt(t))return{error:Ft};let r=Object.keys(t??{}).reduce((i,s)=>{let a=t[s],{tournamentInfo:{startDate:c,endDate:u}}=gs({tournamentRecord:a}),p=c&&new Date(Ut(c));(!i.startDate||p&&p<i.startDate)&&(i.startDate=p);let m=u&&new Date(Ut(u));return(!i.endDate||m&&m>i.endDate)&&(i.endDate=m),i},{startDate:void 0,endDate:void 0}),n=r.startDate&&Ut(r.startDate.toISOString()),o=r.endDate&&Ut(r.endDate.toISOString());return!n||!o?{error:Uy}:{startDate:n,endDate:o}}function PT({tournamentRecord:t,participantFilters:e}){if(!t)return{error:W};let r=t.participants||[];e&&(r=lu({participants:r,participantFilters:e,tournamentRecord:t}));let n={},o=i=>{if(i.person){let{personId:s}=i.person;n[s]?n[s].participantIds.push(i.participantId):n[s]={...i.person,participantIds:[i.participantId]}}};return r.forEach(i=>{i.person&&o(i)}),{tournamentPersons:Object.values(n)}}function ov(t){let r=t.participants?.filter(({participantType:a})=>a===kt)?.length===2,n=t.events?.length===1&&t.events[0],o=n?.drawDefinitions?.length===1&&n.drawDefinitions[0],s=(o?.structures?.length===1&&o.structures[0])?.positionAssignments?.length===2;return!!(n.tieFormat&&r&&s)}function DT({tournamentRecord:t}){if(!t)return{error:W};let{drawsAnalysis:e}=Eu({tournamentRecord:t}),r={isDual:ov(t),drawsAnalysis:e};return{...R,analysis:r}}var LD={};Jt(LD,{compareTieFormats:()=>Go,getTieFormat:()=>NT,tieFormatGenderValidityCheck:()=>pd,validateCollectionDefinition:()=>yu});function Ld(t){if(!t)return{};let e=[],r=t.tieFormatName,n=t.collectionDefinitions?.map(o=>{let{matchUpType:i,matchUpFormat:s,matchUpCount:a,category:c,gender:u}=o;e.includes(s)||e.push(s);let p=c?.ageCategoryCode;return[a,i===vi?"D":"S",p,s,u].join(";")}).join("|");return{tieFormatName:t&&r||"UNNAMED",matchUpFormats:e,tieFormatDesc:n}}function Go({considerations:t={},descendant:e,ancestor:r}){let n={},o={},{matchUpFormats:i,tieFormatDesc:s}=Ld(e),{matchUpFormats:a,tieFormatDesc:c}=Ld(r),u=pt((i??[]).filter(D=>!(a??[]).includes(D)).concat((a??[]).filter(D=>!(i??[]).includes(D)))),p=!!(t?.collectionName&&e.collectionDefinitions.map(({collectionName:D})=>D).join("|")!==r.collectionDefinitions.map(({collectionName:D})=>D).join("|")),m=!!(t?.collectionOrder&&e.collectionDefinitions.map(({collectionOrder:D})=>D).join("|")!==r.collectionDefinitions.map(({collectionOrder:D})=>D).join("|")),d=Object.assign({},...(e?.collectionDefinitions||[]).map(D=>({[D.collectionId]:D}))),l=Object.assign({},...(r?.collectionDefinitions||[]).map(D=>({[D.collectionId]:D})));n.collectionIds=cE(Object.keys(d),Object.keys(l)),o.collectionIds=cE(Object.keys(l),Object.keys(d)),n.collectionsValue=iv(d),o.collectionsValue=iv(l),n.groupsCount=r?.collectionGroups?.length??(0-(e?.collectionGroups?.length??0)||0),o.groupsCount=n.groupsCount?-1*n.groupsCount:0;let f=n.collectionsValue.totalValue-o.collectionsValue.totalValue,g=n.collectionsValue.totalMatchUps-o.collectionsValue.totalMatchUps,I=o.collectionsValue.assignmentValues.length!==n.collectionsValue.assignmentValues.length,h=o.collectionsValue.assignmentValues.some((D,y)=>{let E=n.collectionsValue.assignmentValues[y];return!E||D.valueKey!==E.valueKey||D.value!==E.value?!0:Array.isArray(D.value)?D.value.every((U,M)=>E.value[M]===U):!1}),S=p||m||c!==s||I||h||f!==0,T=[...o.collectionsValue.invalidValues,...n.collectionsValue.invalidValues],A=T.length&&T;return{matchUpFormatDifferences:u,matchUpCountDifference:g,descendantDifferences:n,ancestorDifferences:o,orderDifference:m,valueDifference:f,nameDifference:p,descendantDesc:s,ancestorDesc:c,...R,different:S,invalid:A}}function iv(t){let e=[],r=[],n=0;return{totalValue:Object.keys(t).sort(du).reduce((s,a)=>{let c=t[a],{collectionValueProfiles:u,collectionValue:p,matchUpCount:m,matchUpValue:d,scoreValue:l,setValue:f}=c,g={collectionValueProfiles:u,collectionValue:p,matchUpValue:d,scoreValue:l,setValue:f},I=Object.keys(g).filter(S=>![void 0,null].includes(g[S]));I.length!==1&&e.push({collectionId:a});let h=I[0];if(h){let S=h==="collectionValueProfiles"?Object.values(u):g[h];r.push({valueKey:h,value:S})}return n+=m,u?s+u.reduce((S,T)=>S+T.value,0):m?ft(d)?s+d*m:ft(l)?s+l*m:ft(f)?s+f*m:s+p:s},0),totalMatchUps:n,invalidValues:e,assignmentValues:r}}function Ug(t){Object.assign(t,{inContext:!0});let{matchUp:e,error:r}=wD(t);return{matchUp:J(e,!0,!0),error:r}}function wD({participantsProfile:t,afterRecoveryTimes:e,tournamentRecord:r,contextContent:n,contextProfile:o,drawDefinition:i,nextMatchUps:s,matchUpId:a,inContext:c,eventId:u,drawId:p,event:m}){if(!r)return{error:W};if(typeof a!="string")return{error:ke};if(!i||!m){let g=(le({tournamentRecord:r,nextMatchUps:s}).matchUps??[]).find(I=>I.matchUpId===a);if(!g)return{error:Oe};({eventId:u,drawId:p}=g),{event:m,drawDefinition:i}=We({tournamentRecord:r,eventId:u,drawId:p})}if(!i)return{error:pr};o&&!n&&(n=Ln({tournamentRecord:r,contextProfile:o}));let d={surfaceCategory:m?.surfaceCategory??r.surfaceCategory,indoorOutDoor:m?.indoorOutdoor??r.indoorOutdoor,endDate:m?.endDate??r.endDate,tournamentId:r.tournamentId,eventId:u??m?.eventId,drawId:p},{participants:l=[]}=Ii({participantsProfile:t,tournamentRecord:r,contextProfile:o,inContext:c});if(s){let g=(rr({context:c?d:void 0,participants:l,afterRecoveryTimes:e,contextContent:n,contextProfile:o,drawDefinition:i,nextMatchUps:s,inContext:c,event:m}).matchUps??[]).find(h=>h.matchUpId===a);if(!g)return{error:Oe};let I=i?.structures?.find(h=>h.structureId===g.structureId);return{drawDefinition:i,structure:I,matchUp:g}}else{let{matchUp:f,structure:g}=xt({context:c?d:void 0,tournamentParticipants:l,afterRecoveryTimes:e,contextContent:n,drawDefinition:i,contextProfile:o,matchUpId:a,inContext:c,event:m});return{matchUp:f,structure:g,drawDefinition:i}}}function NT({tournamentRecord:t,drawDefinition:e,structureId:r,matchUpId:n,structure:o,eventId:i,drawId:s,event:a}){if(!t)return{error:W};if(!s&&!a&&!r&&!n)return _({result:{error:et},stack:"getTieFormat"});i&&!a&&(a=t.events?.find(l=>l.eventId===i));let c=Ug({tournamentRecord:t,drawDefinition:e,matchUpId:n,drawId:s,event:a});if(n&&c?.error)return c;if(!e&&c?.drawDefinition&&(e=c?.drawDefinition),o=o??c?.structure,!o&&r&&!n){if(!e)return{error:Wr};let l=st({drawDefinition:e,structureId:r});if(l.error)return l;o=l.structure}let u=(o?.tieFormat||o?.tieFormatId)&&je({structure:o,drawDefinition:e,event:a})?.tieFormat,p=(e?.tieFormat||e?.tieFormatId)&&je({drawDefinition:e,event:a})?.tieFormat,m=je({event:a})?.tieFormat,d=je({matchUp:c?.matchUp,drawDefinition:e,structure:o,event:a})?.tieFormat;return{...R,matchUp:c?.matchUp,structureDefaultTieFormat:Xe(u),eventDefaultTieFormat:Xe(m),drawDefaultTieFormat:Xe(p),tieFormat:Xe(d),structure:o}}var kD={};Jt(kD,{bulkUpdatePublishedEventIds:()=>MT,getAllEventData:()=>CT,getCourtInfo:()=>Hm,getDrawData:()=>Fd,getEventData:()=>Gd,getEventPublishStatus:()=>vr,getPublishState:()=>as,getVenueData:()=>mc});function MT({tournamentRecord:t,outcomes:e}){if(!t)return{error:W};if(!e?.length)return{error:et,info:"Missing outcomes"};let r=e.reduce((s,a)=>{let{drawId:c,eventId:u}=a;return u&&c&&(s[u]?s[u].includes(c)||s[u].push(c):s[u]=[c]),s},{}),n=Object.keys(r);return{publishedEventIds:(t.events?.filter(s=>n.includes(s.eventId))).filter(s=>{let a=vr({event:s}),{drawDetails:c,drawIds:u}=a??{},{eventId:p}=s;return r[p].filter(d=>{let l=c?Object.keys(a.drawDetails).filter(f=>Qm({drawId:f,drawDetails:c})):[];return u?.includes(d)||l.includes(d)}).length}).map(s=>s.eventId),eventIdPublishedDrawIdsMap:r}}function FD({dates:t=[],extension:e}){if(!e)return!1;if(typeof e.value=="boolean"&&e.value)return!0;if(!t.length)return!1;let r=Rt(e.value)?e.value?.dates:void 0;if(Array.isArray(r))return r?.length?!!r.filter(o=>!t.length||t.includes(o)).length:!1}function GD({convertExtensions:t,ignoreDisabled:e,venue:r,court:n}){let o={...J(n,t,!0),venueId:r.venueId},{extension:i}=mt({name:Wn,element:n});if(e&&i){let s=Rt(i.value)?i.value?.dates:void 0,a=i?.value===!0?[]:o.dateAvailability.map(c=>{let u=c.date;if(!(!u||s.includes(u)))return c}).filter(Boolean);o.dateAvailability=a}return{inContextCourt:o}}function po(t){let{convertExtensions:e,ignoreDisabled:r,venueIds:n=[],dates:o}=t,i=t.tournamentRecords||t.tournamentRecord&&{[t.tournamentRecord.tournamentId]:t.tournamentRecord}||{},s=[],a=[],c=[],u=[];return Object.keys(i).filter(m=>!t.tournamentId||m===t.tournamentId).forEach(m=>{let d=i[m];for(let l of d.venues??[])if(!(n.length&&!n.includes(l.venueId))){if(r){let{extension:f}=mt({name:Wn,element:l});if(f?.value)continue}s.includes(l.venueId)||(u.push(J(l,e,!0)),s.push(l.venueId));for(let f of l.courts??[])if(!a.includes(f.courtId)){if(r){let{extension:I}=mt({name:Wn,element:f});if(FD({extension:I,dates:o}))continue}let{inContextCourt:g}=GD({convertExtensions:e,ignoreDisabled:r,venue:l,court:f});c.push(g),a.push(f.courtId)}}}),{courts:c,venues:u,...R}}function nV({convertExtensions:t,tournamentRecord:e,ignoreDisabled:r,dates:n}){if(!e)return{error:Ft};let o=J(e.venues??[],t).filter(s=>{if(!r)return s;let{extension:a}=mt({name:Wn,element:s});return!a?.value&&s}).filter(Boolean),i=o.reduce((s,a)=>{let c=(a?.courts||[]).filter(u=>{if(!r&&!n?.length)return u;let{extension:p}=mt({name:Wn,element:u});return FD({extension:p,dates:n})}).filter(Boolean).map(u=>{let{inContextCourt:p}=GD({convertExtensions:t,ignoreDisabled:r,venue:a,court:u});return p});return c.length?s.concat(c):s},[]);return{venues:o,courts:i}}function Lp({tournamentRecords:t,requireCourts:e,dates:r}){return typeof t!="object"||!Object.keys(t).length?{error:Ft}:Object.keys(t).reduce((o,i)=>{let s=t[i],{venues:a}=nV({tournamentRecord:s,dates:r});return a?.forEach(c=>{let{venueId:u,courts:p}=c;(!e||p?.length)&&!o.venueIds.includes(u)&&(o.venues.push(c),o.venueIds.push(u))}),o},{venues:[],venueIds:[]})}function CT({tournamentRecord:t,policyDefinitions:e}){if(!t)return{error:W};let r=t.events||[],n=t?.participants||[],{tournamentInfo:o}=gs({tournamentRecord:t}),{venues:i}=po({tournamentRecord:t}),s=r.map(c=>{let{eventId:u}=c,p=UT({event:c}).eventInfo,m=Sa({tournamentRecord:t,event:c}).scheduleTiming,d=(c.drawDefinitions||[]).map(f=>{let g=(({drawId:A,drawName:D,matchUpFormat:y,updatedAt:E})=>({matchUpFormat:y,updatedAt:E,drawName:D,drawId:A}))(f),{abandonedMatchUps:I,completedMatchUps:h,upcomingMatchUps:S,pendingMatchUps:T}=Vs({requireParticipants:!0,tournamentParticipants:n,context:{eventId:u},policyDefinitions:e,tournamentRecord:t,inContext:!0,scheduleTiming:m,drawDefinition:f,event:c});return{drawInfo:g,matchUps:{abandonedMatchUps:I,completedMatchUps:h,upcomingMatchUps:S,pendingMatchUps:T}}}),l=vr({event:c});return Object.assign(p,{drawsData:d,publish:l}),p});return{allEventData:{tournamentInfo:o,venuesData:i,eventsData:s}}}function RT({publishStatus:t,drawId:e}){return t?.drawDetails?t.drawDetails?.[e]?.publishingDetail?.published:t?.drawIds?t.drawIds.includes(e):!0}function Fd(t){let{tournamentParticipants:e=[],includePositionAssignments:r,policyDefinitions:n,tournamentRecord:o,inContext:i=!0,usePublishState:s,status:a=Gr,drawDefinition:c,noDeepCopy:u,sortConfig:p,context:m,event:d}=t;if(!c)return{error:X};let l=(({matchUpFormat:P,updatedAt:N,drawType:C,drawName:O,drawId:b})=>({matchUpFormat:P,updatedAt:N,drawName:O,drawType:C,drawId:b}))(c),f,g,{allStructuresLinked:I,sourceStructureIds:h,hasDrawFeedProfile:S,structureGroups:T}=gu({drawDefinition:c});if(!I)return{error:ly};let A=t?.publishStatus??vr({event:d,status:a}),D=t.eventPublished??!!as({event:d}).publishState?.status?.published,y=!1,E=!1,M=T.map(P=>{let N={},C=P.map(O=>{let{structure:b}=st({drawDefinition:c,structureId:O}),{seedAssignments:x}=Fr({drawDefinition:c,structure:b});return b?.stage===tt&&b.stageSequence===1&&(f=x),b?.stage===at&&b.stageSequence===1&&(g=x),b}).sort((O,b)=>ci(O,b,p)).map(O=>{if(!O)return;let b=O?.structureId,x=[];O.stage&&[tt,Ve,ce].includes(O.stage)&&(x=f),O?.stage===at&&(x=g);let{matchUps:w,roundMatchUps:F,roundProfile:L}=At({seedAssignments:O?.seedAssignments?.length?void 0:x,context:{drawId:l.drawId,...m},tournamentParticipants:e,policyDefinitions:n,tournamentRecord:o,usePublishState:s,publishStatus:A,drawDefinition:c,inContext:i,structure:O,event:d}),{positionAssignments:v}=Nt({structure:O}),B=v?.filter(Pr(Bn)).map(V=>{let{drawPosition:Y,participantId:$}=V,{extension:k}=mt({element:V,name:Ho});return E=!0,{participantResult:k?.value,participantId:$,drawPosition:Y}});if(!B?.length&&w.length&&t.allParticipantResults){let{subOrderMap:V}=oS({positionAssignments:v}),Y=Ca({matchUpFormat:O.matchUpFormat,policyDefinitions:n,subOrderMap:V,matchUps:w});B=v?.filter(Pr(Bn)).map($=>{let{drawPosition:k,participantId:K}=$;return E=!0,{participantResult:K&&Y.participantResults[K],participantId:K,drawPosition:k}})}let H=O?(({stageSequence:V,structureName:Y,structureType:$,matchUpFormat:k,stage:K})=>({stageSequence:V,structureName:Y,structureType:$,matchUpFormat:k,stage:K}))(O):{};H.sourceStructureIds=h[b],H.hasDrawFeedProfile=S[b],H.positionAssignments=v,H.structureActive=w.reduce((V,Y)=>{let $=[me,Wo,Ot,lr,_t,Dn,Ne,ge].includes(Y.matchUpStatus);return V||$||!!Y.winningSide||!!Y.score?.scoreStringSide1},!1);let j=w.reduce((V,Y)=>V&&[Dt,me,lr,_t,Ot,$r].includes(Y.matchUpStatus),!!w.length);return H.structureCompleted=j,N[b]=j,H.structureActive&&(y=!0),{...H,participantResults:B,seedAssignments:x,roundMatchUps:F,roundProfile:L,structureId:b}});return C.forEach(O=>{r||delete O.positionAssignments,O.sourceStructuresComplete=O.sourceStructureIds?.every(b=>N[b])}),C}).flat();return l.drawActive=y,l.participantPlacements=E,l.drawGenerated=M?.reduce((P,N)=>P||!!N?.roundMatchUps,!1),l.drawCompleted=M?.reduce((P,N)=>P&&N.structureCompleted,!0),l.drawPublished=s?D&&RT({publishStatus:A,drawId:l.drawId}):void 0,{structures:!s||l.drawPublished?u?M:J(M,!1,!0):void 0,drawInfo:u?l:J(l,!1,!0),...R}}function Gd(t){let{includePositionAssignments:e,participantsProfile:r,policyDefinitions:n,usePublishState:o,status:i=Gr,sortConfig:s}=t,a=lt(t,[{tournamentRecord:!0},{[fm]:{event:!1,eventId:!1}}]);if(a.error)return a;let c=J(t.tournamentRecord,!1,!0),u=t.event?void 0:We({tournamentRecord:c,eventId:t.eventId}).event,p=t.event?J(t.event,!1,!0):u&&J(u,!1,!0)||void 0;if(!p)return{error:mr};let{eventId:m}=p,{tournamentId:d,endDate:l}=c,f=vr({event:p,status:i}),g=as({event:p}).publishState??{},I=!!g?.status?.published,{participants:h}=Yt({withGroupings:!0,withEvents:!1,withDraws:!1,policyDefinitions:n,...r,tournamentRecord:c}),S=({stage:O,drawId:b})=>{if(!o)return!0;let x=f?.drawDetails?.[b]?.stageDetails;return!x||!Object.keys(x).length?!0:x[O]?.published},T=({structureId:O,drawId:b})=>{if(!o)return!0;let x=f?.drawDetails?.[b]?.structureDetails;return!x||!Object.keys(x).length?!0:x[O]?.published},A=({drawId:O})=>o?RT({publishStatus:f,drawId:O}):!0,D=({drawId:O,structure:b})=>{if(!o)return b;let x=f?.drawDetails?.[O]?.structureDetails?.[b.structureId]?.roundLimit;if(ft(x)){let w=Z(1,x+1),F={},L={};for(let v of w)b.roundMatchUps[v]&&(F[v]=b.roundMatchUps[v],L[v]=b.roundProfile[v]);b.roundMatchUps=F,b.roundProfile=L}return b},y=p.drawDefinitions||[],E=!o||I?y.filter(A).map(O=>(({drawInfo:b,structures:x})=>({...b,structures:x}))(Fd({allParticipantResults:t.allParticipantResults,context:{eventId:m,tournamentId:d,endDate:l},includePositionAssignments:e,tournamentParticipants:h,noDeepCopy:!0,policyDefinitions:n,tournamentRecord:c,usePublishState:o,drawDefinition:O,publishStatus:f,sortConfig:s,event:p}))).map(({structures:O,...b})=>{let x=O?.filter(({stage:w,structureId:F})=>T({structureId:F,drawId:b.drawId})&&S({stage:w,drawId:b.drawId})).map(w=>D({drawId:b.drawId,structure:w}));return{...b,structures:x}}).filter(O=>O.structures?.length):void 0,{tournamentInfo:U}=gs({tournamentRecord:c}),P=(c.venues||[]).map(O=>(({venueData:b})=>({...b}))(mc({tournamentRecord:c,venueId:O.venueId}))),N=(({eventId:O,eventName:b,eventType:x,eventLevel:w,surfaceCategory:F,matchUpFormat:L,category:v,gender:B,startDate:H,endDate:j,ballType:V,discipline:Y})=>({eventId:O,eventName:b,eventType:x,eventLevel:w,surfaceCategory:F,matchUpFormat:L,category:v,gender:B,startDate:H,endDate:j,ballType:V,discipline:Y}))(p),C={tournamentInfo:U,venuesData:P,eventInfo:N,drawsData:E};return C.eventInfo.publishState=g,C.eventInfo.published=g?.status?.published,{...R,eventData:C,participants:h}}var WD={};Jt(WD,{getPersonRequests:()=>yi,getProfileRounds:()=>kd,getScheduledRoundsDetails:()=>bu,getSchedulingProfile:()=>ko,getSchedulingProfileIssues:()=>bT});function Fp({defaultRecoveryMinutes:t=0,defaultAverageMinutes:e,tournamentRecords:r,matchUpFormat:n,categoryName:o,categoryType:i,tournamentId:s,eventType:a,eventId:c}){if(!Sr({matchUpFormat:n}))return{error:Ya};let u=Object.keys(r).filter(m=>!s||m===s),p;return u.forEach(m=>{if(p)return;let d=r[m],l=c?We({tournamentRecord:d,eventId:c})?.event:void 0;return p=au({tournamentRecord:d,matchUpFormat:n,categoryName:o,categoryType:i,eventType:a,event:l}),p?.averageMinutes||p?.recoveryMinutes}),{recoveryMinutes:p?.recoveryMinutes||t,averageMinutes:p?.averageMinutes||e,typeChangeRecoveryMinutes:p?.typeChangeRecoveryMinutes||p?.recoveryMinutes||t}}function bu({scheduleCompletedMatchUps:t,containedStructureIds:e,tournamentRecords:r,periodLength:n=30,matchUps:o,rounds:i}){if(typeof r!="object")return{error:Ft};if(!Array.isArray(i))return{error:et,info:Nn("rounds")};let s={},a=[],c=[];i.sort((f,g)=>(f.sortOrder??0)-(g.sortOrder??0)),e=e??Object.assign({},...Object.values(r).map(f=>Ji({tournamentRecord:f}).containedStructures)),o||({matchUps:o}=cn({nextMatchUps:!0,tournamentRecords:r}));let u=0,p={},m={},d={};return{scheduledRoundsDetails:i.flatMap(f=>{let g=f.periodLength||n,I=[];e?.[f.structureId]?I.push(...e[f.structureId]):I.push(f.structureId);let h=o?Aa({tournamentIds:[f.tournamentId],roundNumbers:[f.roundNumber],matchUpIds:f.matchUpIds,eventIds:[f.eventId],drawIds:[f.drawId],processContext:!0,structureIds:I,matchUps:o}).sort(hi):[],{segmentNumber:S,segmentsCount:T}=f.roundSegment||{};if(ft(S)&&Tn(h?.length)&&Tn(T)&&S>0&&S<=T&&T<h?.length&&!f.matchUpIds?.length){let E=h.length/T,U=E*(S-1);h=h.slice(U,U+E)}let A=r[f.tournamentId],D=We({drawId:f.drawId,tournamentRecord:A}).event,y=[];for(let E of h){let U=E.matchUpFormat;U&&(s[U]||(s[U]=[],s[U].push(E)),y.push(U))}for(let E of y){let{eventType:U,category:M}=D??{},{categoryName:P,ageCategoryCode:N}=M??{},{typeChangeRecoveryMinutes:C,recoveryMinutes:O,averageMinutes:b,error:x}=Fp({categoryName:P??N,categoryType:M?.categoryType,tournamentId:f.tournamentId,eventId:f.eventId,tournamentRecords:r,matchUpFormat:E,eventType:U});if(x)return{error:x,round:f};let w=h.filter(L=>(t||!ae.includes(L.matchUpStatus))&&L.matchUpStatus!==Dt).map(fe);w.forEach(L=>{d[L]={typeChangeRecoveryMinutes:C,recoveryMinutes:O,averageMinutes:b},p[L]=O,m[L]=b}),c.push(...w),u=Math.max(b||0,u);let F=`${b}|${g}`;return a.includes(F)||a.push(F),{roundPeriodLength:g,recoveryMinutes:O,averageMinutes:b,matchUpIds:w,hash:F}}}),greatestAverageMinutes:u,matchUpFormatCohorts:s,recoveryMinutesMap:p,averageMinutesMap:m,orderedMatchUpIds:c,minutesMap:d,...R}}function VD({schedulingProfile:t,venueIds:e,eventIds:r,drawIds:n}){let o=[],i=t?.map(a=>{let c=Ut(a?.scheduleDate);if(!c){o.push(`Invalid date: ${a?.scheduledDate}`);return}let u=(a?.venues||[]).map(p=>{let{rounds:m,venueId:d}=p;if(!e?.includes(d)){o.push(`Missing venueId: ${d}`);return}let f=m.filter(g=>{let I=r.includes(g.eventId)&&n.includes(g.drawId);return I||o.push(`Invalid eventId: ${g.eventId} or drawId: ${g.drawId}`),I});if(f.length)return{venueId:d,rounds:f}}).filter(Boolean);return u.length&&c&&{...a,venues:u}}).filter(Boolean),s=o.length;return{updatedSchedulingProfile:i,modifications:s,issues:o}}function Gp({tournamentRecords:t,schedulingProfile:e}){if(!e)return{valid:!0};if(!Array.isArray(e))return{valid:!1,error:G};let{venueIds:r,tournamentsMap:n}=iV({tournamentRecords:t}),o,i,s=e.every(a=>{let{scheduleDate:c,venues:u}=a;return Rr(c)?u.every(p=>{let{venueId:m,rounds:d}=p;return typeof m!="string"?(i="venueId should be a string",!1):Array.isArray(d)?r.includes(m)?!!d.every(f=>{if(!f)return i="empty round",!1;let{roundSegment:g,tournamentId:I,structureId:h,roundNumber:S,eventId:T,drawId:A}=f,y=n?.[I]?.[T]?.[A]?.[h]?.includes(S);y||(i="Invalid rounds");let{segmentNumber:E,segmentsCount:U}=g||{},M=!g||ft(E)&&Tn(U)&&E<=U;return M||(i="Invalid segment"),y&&M}):(o=Ds,!1):(i="rounds should be an array",!1)}):!1});return!s&&!o&&(o=G),{valid:!!s,error:o,info:i}}function oV(t){let{tournamentRecord:e={},tournamentMap:r={},requireCourts:n}=t,o=[],i=[],s=[],a=[],c=(e?.venues||[]).map(({venueId:p,courts:m})=>(!n||m?.length)&&p),u=e?.tournamentId;return u&&(o.push(u),r[u]={},(e?.events||[]).forEach(m=>{let d=m.eventId;s.push(d),r[u][d]={},(m.drawDefinitions||[]).forEach(l=>{let f=l.drawId;a.push(f),r[u][d][f]={};let{structures:g}=xn({drawDefinition:l});(g||[]).forEach(I=>{let h=I.structureId,{matchUps:S}=At({structure:I}),{roundMatchUps:T}=He({matchUps:S}),A=T&&Object.keys(T).map(D=>parseInt(D));r[u][d][f][h]=A,i.push(h),I.structures?.length&&I.structures.forEach(D=>{i.push(D.structureId),r[u][d][f][D.structureId]=A})})})})),{tournamentMap:r,tournamentIds:o,structureIds:i,venueIds:c,eventIds:s,drawIds:a}}function iV(t){let e=t?.tournamentRecords&&Object.values(t?.tournamentRecords)||[],r={},{venueIds:n,eventIds:o,drawIds:i,structureIds:s,tournamentIds:a}=e.reduce((c,u)=>{let{tournamentIds:p,tournamentMap:m,structureIds:d,venueIds:l,eventIds:f,drawIds:g}=oV({tournamentRecord:u});return l.forEach(I=>{c.venueIds.includes(I)||c.venueIds.push(I)}),c.tournamentIds.push(...p),c.structureIds.push(...d),c.eventIds.push(...f),c.drawIds.push(...g),Object.assign(r,m),c},{tournamentIds:[],structureIds:[],venueIds:[],eventIds:[],drawIds:[]});return{tournamentsMap:r,tournamentIds:a,structureIds:s,venueIds:n,eventIds:o,drawIds:i}}function ko({tournamentRecords:t,tournamentRecord:e}){if(typeof t!="object"||!Object.keys(t).length)return{error:Ft};let{extension:r}=mt({element:e,name:da,tournamentRecords:t,discover:!0}),n=r?.value||[];if(n.length){let{venueIds:o}=Lp({requireCourts:!0,tournamentRecords:t}),{eventIds:i,drawIds:s}=ng({tournamentRecords:t}),{updatedSchedulingProfile:a,modifications:c,issues:u}=VD({schedulingProfile:n,venueIds:o,eventIds:i,drawIds:s});if(c){n=a;let p=Dc({tournamentRecords:t,tournamentRecord:e,schedulingProfile:n});return p.error?p:{schedulingProfile:n,modifications:c,issues:u}}}return{schedulingProfile:n,modifications:0}}function Dc({tournamentRecords:t,tournamentRecord:e,schedulingProfile:r}){let n=Gp({tournamentRecords:t,schedulingProfile:r});return n.error?n:r?St({tournamentRecords:t,discover:!0,extension:{name:da,value:r}}):or({element:e,name:da,tournamentRecords:t,discover:!0})}function Nc(t){let{tournamentRecord:e}=t,r=t.tournamentRecords||e&&{[e.tournamentId]:e}||{};if(!t.schedulingProfile){let{modifications:u,issues:p}=ko({tournamentRecords:r,tournamentRecord:e});return{success:!u,modifications:u,issues:p}}let{venueIds:n}=Lp({tournamentRecords:r}),{eventIds:o,drawIds:i}=ng({tournamentRecords:r}),{updatedSchedulingProfile:s,modifications:a,issues:c}=VD({schedulingProfile:t.schedulingProfile,venueIds:n,eventIds:o,drawIds:i});return a?{...Dc({schedulingProfile:s,tournamentRecords:r}),modifications:a,issues:c}:{...R,modifications:a,issues:c}}function bT(t){let{scheduleDates:e=[],tournamentRecords:r,periodLength:n=30}=t??{};if(typeof r!="object")return{error:Ba};if(!Array.isArray(e))return{error:G};if(!e.every(Rr))return{error:ar};let i=[],s=0,a={},{schedulingProfile:c}=ko({tournamentRecords:r});if(!c)return{issues:i,...R};let{matchUps:u}=cn({nextMatchUps:!0,tournamentRecords:r});for(let m of c){let{scheduleDate:d,venues:l=[]}=m;if(!e?.length||e.includes(d)){for(let f of l||[])if(f){let{rounds:g}=f,I=[],{orderedMatchUpIds:h,scheduledRoundsDetails:S}=bu({tournamentRecords:r,periodLength:n,matchUps:u,rounds:g}),{matchUpDependencies:T}=Vr({tournamentRecords:r,matchUps:u}),A=D=>{let y;return S?.find((E,U)=>{let M=E.matchUpIds.includes(D);return M&&(y=U),M}),y};if(h?.forEach((D,y)=>{let E=h.slice(y+1),U=jt(E,T?.[D]?.matchUpIds||[]);U.length&&I.push({matchUpId:D,shouldBeAfter:U})}),I.length){s+=I.length;let D=I.map(({matchUpId:y,shouldBeAfter:E})=>{let U=A(y),M=pt(E.map(A));return a[d]||(a[d]={}),a[d][U]||(a[d][U]=[]),M.forEach(P=>{a[d][U].includes(P)||a[d][U].push(P)}),{matchUpId:y,matchUpRoundIndex:U,earlierRoundIndices:M,shouldBeAfter:E}});i.push(...D)}}}}let p={matchUpIdShouldBeAfter:Object.assign({},...i.map(m=>{let{matchUpId:d,shouldBeAfter:l,earlierRoundIndices:f}=m;return{[d]:{earlierRoundIndices:f,shouldBeAfter:l}}}))};return{issuesCount:s,profileIssues:p,roundIndexShouldBeAfter:a,...R}}function yi(t){let{tournamentRecords:e,requestType:r}=t,n=lt(t,[{[ye]:!0}]);if(n.error)return n;let o={};for(let i of Object.values(e)){let{extension:s}=mt({element:i,name:ma}),a=s?.value||[];for(let c of a){let{personId:u,requests:p}=c||{};o[u]||(o[u]=[]);for(let m of p)r&&m.requestType!==r||o[u].push(m)}}return{personRequests:o,...R}}function Pg(t){let{containerStructureId:e,roundSegment:r,isRoundRobin:n,tournamentId:o,roundNumber:i,structureId:s,eventId:a,drawId:c}=t,u=n?e:s,p=[o,a,c,u,i].join("|");return rt({structureId:u,roundSegment:r,tournamentId:o,roundNumber:i,eventId:a,drawId:c,id:p})}function BD({round:t,matchUps:e,events:r,tournamentRecords:n}){let o=r.find(d=>d.eventId===t.eventId),{eventType:i,category:s,categoryType:a}=o||{},{categoryName:c,ageCategoryCode:u}=s||{},p=dr(e.map(({matchUpFormat:d})=>d)),m=0;return Object.keys(p).forEach(d=>{let l=p[d],f=Fp({categoryName:c||u,tournamentId:t.tournamentId,eventId:t.eventId,tournamentRecords:n,matchUpFormat:d,categoryType:a,eventType:i});if(f.error)return f;let g=f.averageMinutes*l;isNaN(m)||(m+=g)}),{roundMinutes:m}}function sv(t){return(t||[]).reduce((e,r)=>{let n=(r.finishingPositionRange?.winner||[]).reduce((i,s)=>i+s,0),o=(r.finishingPositionRange?.winner||[]).join("-")||"";return!e.minFinishingSum||n<e.minFinishingSum?{minFinishingSum:n,winnerFinishingPositionRange:o}:e},{minFinishingSum:0,winnerFinishingPositionRange:""})}function HD(t){let e=t.length,r=t.filter(({sides:p})=>p?.some(({bye:m})=>m)).length||0,n=t.filter(({winningSide:p,matchUpStatus:m})=>p||ae.includes(m)).length||0,o=t.filter(({schedule:p,matchUpStatus:m})=>p?.scheduledDate&&p?.scheduledTime&&m!==Dt).length||0,i=e-r,s=i===n,a=i-o,c=i-o;return{unscheduledCount:a,incompleteCount:c,scheduledCount:o,completedCount:n,matchUpsCount:e,isScheduled:i===o,isComplete:s,byeCount:r}}function kd({tournamentRecords:t,schedulingProfile:e,tournamentRecord:r,withRoundId:n}){if(r&&!t){if(typeof r!="object")return{error:Ba};t={[r.tournamentId]:r}}if(e){let s=Gp({tournamentRecords:t,schedulingProfile:e});if(s.error)return s}if(!e&&t){let s=ko({tournamentRecords:t});if(s.error)return s;e=s.schedulingProfile}if(!e)return{error:Ke};let o={};return{profileRounds:e.map(({venues:s,scheduleDate:a})=>s.map(({rounds:c})=>c.map(u=>{let p=Pg(u);return p.roundSegment?.segmentsCount&&(o[p.id]=p.roundSegment.segmentsCount),rt({id:n?p.id:void 0,scheduleDate:a,...p})}))).flat(1/0),segmentedRounds:o}}var jD={};Jt(jD,{getEntriesAndSeedsCount:()=>Vd,getMaxEntryPosition:()=>OT});function Vd({policyDefinitions:t,drawDefinition:e,drawSize:r,drawId:n,event:o,stage:i}){if(!o)return{error:Et};let{entries:s,stageEntries:a}=vh({drawDefinition:e,drawId:n,stage:i,event:o}),c=a.length,{drawSize:u}=bS({participantsCount:c}),p=Du({drawSize:r??u,participantsCount:c,policyDefinitions:t});if(p.error)return _({result:p,stack:"getEntriesAndSeedsCount"});let{seedsCount:m}=p;return{entries:s,seedsCount:m,stageEntries:a}}function OT(t){let{entries:e=[],entryStatus:r,stage:n}=t;return Math.max(...e.filter(o=>(!n||n===o.entryStage)&&(!r||o.entryStatus===r)&&!isNaN(o.entryPosition)).map(({entryPosition:o})=>ct(o||0)),0)}var KD={};Jt(KD,{allCompetitionMatchUps:()=>cn,allDrawMatchUps:()=>rr,allEventMatchUps:()=>co,allTournamentMatchUps:()=>le,analyzeMatchUp:()=>Vp,calculateWinCriteria:()=>Is,checkMatchUpIsComplete:()=>is,competitionScheduleMatchUps:()=>Ou,drawMatchUps:()=>WT,eventMatchUps:()=>Wd,getAllDrawMatchUps:()=>re,getAllStructureMatchUps:()=>At,getCheckedInParticipantIds:()=>es,getCompetitionMatchUps:()=>kp,getEventMatchUpFormatTiming:()=>wT,getMatchUpCompetitiveProfile:()=>su,getMatchUpContextIds:()=>kT,getMatchUpDailyLimits:()=>Yd,getMatchUpDailyLimitsUpdate:()=>LT,getMatchUpDependencies:()=>Vr,getMatchUpFormat:()=>VT,getMatchUpFormatTiming:()=>au,getMatchUpFormatTimingUpdate:()=>vT,getMatchUpScheduleDetails:()=>Wm,getMatchUpType:()=>qm,getMatchUpsStats:()=>BT,getModifiedMatchUpFormatTiming:()=>Bd,getParticipantResults:()=>Su,getPredictiveAccuracy:()=>GT,getRoundMatchUps:()=>He,getRounds:()=>HT,isValidMatchUpFormat:()=>Sr,matchUpActions:()=>hd,participantScheduledMatchUps:()=>FT,tallyParticipantResults:()=>Ca,tournamentMatchUps:()=>jd,validMatchUp:()=>yf,validMatchUps:()=>Ur});function _T({tournamentRecords:t,extensionName:e}){if(typeof t!="object"||!Object.keys(t).length)return{error:Ft};let r=[],n;for(let o of Object.values(t)){let{extension:i}=mt({element:o,name:e});i&&!n&&(r.push({params:{extension:i,discover:!0},method:"addExtension"}),n=!0);let s=o.events??[];for(let a of s){let{eventId:c}=a,{extension:u}=mt({name:e,element:a});u&&r.push({params:{eventId:c,extension:u},method:"addEventExtension"})}}return{methods:r}}function vT({tournamentRecords:t}){return _T({extensionName:Oo,tournamentRecords:t})}var YD="ADULT",qD="JUNIOR",xT="WHEELCHAIR",$D={[go]:{allowModificationWhenMatchUpsScheduled:{courts:!1,venues:!1},defaultTimes:{averageTimes:[{categoryNames:[],minutes:{default:90}}],recoveryTimes:[{minutes:{[Gt]:30,default:60}}]},defaultDailyLimits:{[Xt]:2,[Gt]:2,total:3},matchUpAverageTimes:[{matchUpFormatCodes:[un],averageTimes:[{categoryNames:[],minutes:{default:90}},{categoryTypes:[xT],minutes:{default:120}}]},{matchUpFormatCodes:["SET3-S:6/TB7-F:TB10"],averageTimes:[{categoryNames:[],minutes:{default:85}}]},{matchUpFormatCodes:["SET3-S:6/TB7-F:TB7"],averageTimes:[{categoryNames:[],minutes:{default:70}}]},{matchUpFormatCodes:["SET3-S:4NOAD-F:TB7"],averageTimes:[{categoryNames:[],minutes:{default:55}}]},{matchUpFormatCodes:["SET3-S:4/TB7"],averageTimes:[{categoryNames:[],minutes:{default:60}}]},{matchUpFormatCodes:["SET3-S:4/TB7-F:TB7"],averageTimes:[{categoryNames:[],minutes:{default:50}}]},{matchUpFormatCodes:["SET3-S:4/TB7-F:TB10"],averageTimes:[{categoryNames:[],minutes:{default:55}}]},{matchUpFormatCodes:["SET3-S:4/TB5@3"],averageTimes:[{categoryNames:[],minutes:{default:45}}]},{matchUpFormatCodes:["SET1-S:8/TB7","SET1-S:8/TB7@7"],averageTimes:[{categoryNames:[],minutes:{default:40}}]},{matchUpFormatCodes:["SET1-S:5/TB9@4"],averageTimes:[{categoryNames:[],minutes:{default:30}}]},{matchUpFormatCodes:["SET1-S:6/TB7"],averageTimes:[{categoryNames:[],minutes:{default:30}}]},{matchUpFormatCodes:["SET1-S:6NOAD"],averageTimes:[{categoryNames:[],minutes:{default:30}}]},{matchUpFormatCodes:["SET1-S:4/TB7","SET1-S:4/TB5@3","SET3-S:TB10","SET1-S:T20"],averageTimes:[{categoryNames:[],minutes:{default:20}}]},{matchUpFormatCodes:["SET1-S:4NOAD"],averageTimes:[{categoryNames:[],minutes:{default:20}}]},{matchUpFormatCodes:["SET1-S:TB10"],averageTimes:[{categoryNames:[],minutes:{default:10}}]}],matchUpRecoveryTimes:[{matchUpFormatCodes:["SET3-S:6/TB7","SET3-S:6/TB7-F:TB10","SET3-S:6/TB7-F:TB7"],recoveryTimes:[{categoryTypes:[YD,xT],minutes:{default:60,[Gt]:30}},{categoryTypes:[qD],minutes:{default:60,[Gt]:60}}]},{matchUpFormatCodes:["SET3-S:4/TB7-F:TB7","SET3-S:4/TB7-F:TB10","SET3-S:4NOAD-F:TB7","SET3-S:4/TB7","SET3-S:4/TB5@3"],recoveryTimes:[{categoryTypes:[YD,xT],minutes:{default:30}},{categoryTypes:[qD],minutes:{default:60}}]},{matchUpFormatCodes:["SET1-S:8/TB7","SET1-S:8/TB7@7","SET1-S:5/TB9@4","SET1-S:6/TB7","SET1-S:6NOAD","SET1-S:4/TB7","SET1-S:4NOAD","SET3-S:TB10","SET1-S:T20"],recoveryTimes:[{categoryNames:[],minutes:{default:30}}]},{matchUpFormatCodes:["SET1-S:4/TB5@3"],recoveryTimes:[{categoryTypes:[YD,qD],minutes:{default:30}},{categoryTypes:[xT],minutes:{default:15}}]},{matchUpFormatCodes:["SET1-S:TB10"],recoveryTimes:[{categoryNames:[],minutes:{default:15}}]}],matchUpDailyLimits:[]}},av=$D;function wT({tournamentRecord:t,matchUpFormats:e,categoryType:r,event:n}){if(!n)return{error:Et};let o=[],i;if(e?.length){let m=[];o=e.map(d=>{let l=typeof d=="string"?{matchUpFormat:d}:d;if(!m.includes(l?.matchUpFormat)&&Sr({matchUpFormat:l?.matchUpFormat}))return m.push(l.matchUpFormat),l}).filter(Boolean)}else{let{policy:m}=$o({policyType:vn,tournamentRecord:t,event:n});if(m?.matchUpFormats)o=m?.matchUpFormats;else{let{extension:d}=mt({name:Oo,element:n}),l,f;d?.value?{matchUpAverageTimes:l,matchUpRecoveryTimes:f}=d.value:{matchUpAverageTimes:l,matchUpRecoveryTimes:f}=av[go],o=pt([...(l||[]).map(g=>g.matchUpFormatCodes),...(f||[]).map(g=>g.matchUpFormatCodes)].flat()).map(g=>({matchUpFormat:g})),i="default scheduling policy in use"}}let{eventType:s,eventId:a,category:c}=n,u=c?.categoryName??c?.ageCategoryCode??a;if(!a)return{error:Et};let p=o.map(({matchUpFormat:m,description:d})=>{let l=au({tournamentRecord:t,matchUpFormat:m,categoryName:u,categoryType:r,eventType:s,event:n});return{matchUpFormat:m,description:d,...l}});return rt({eventMatchUpFormatTiming:p,info:i})}function Bd(t){let e=lt(t,[{[An]:!0},{[yn]:g=>Sr({matchUpFormat:g}),[En]:Ya,[mm]:!0}]);if(e.error)return e;let{tournamentRecord:r,matchUpFormat:n,event:o}=t,{extension:i}=mt({name:Oo,element:o}),s=i?.value,{extension:a}=mt({element:r,name:Oo}),c=a?.value,u=s?.matchUpAverageTimes&&pp({...s,matchUpFormat:n}),p=c?.matchUpAverageTimes&&pp({...c,matchUpFormat:n}),m=[u,p].find(g=>g),d=s?.matchUpRecoveryTimes&&mp({...s,matchUpFormat:n}),l=c?.matchUpRecoveryTimes&&mp({...c,matchUpFormat:n}),f=[d,l].find(g=>g);return{matchUpFormat:n,recoveryTimes:f,averageTimes:m}}function LT({tournamentRecords:t}){return _T({extensionName:Yc,tournamentRecords:t})}var va=({scheduleAttributes:t=["scheduledDate","scheduledTime"],schedule:e={}})=>!!Object.keys(e).filter(n=>t.includes(n)).filter(n=>e[n]).length;function FT({scheduleAttributes:t=["scheduledDate","scheduledTime"],matchUps:e=[]}){if(!Ur(e))return{error:Sn};if(!Array.isArray(t))return{error:G};let r=e.filter(Boolean).filter(({schedule:o})=>va({schedule:o,scheduleAttributes:t})).reduce((o,i)=>{let{schedule:s}=i,a=Ut(s?.scheduledDate),c=$t(s?.scheduledTime);return a&&c&&(o[a]?o[a].push(i):o[a]=[i]),o},{});return Object.keys(r).forEach(o=>{r[o].sort((i,s)=>GI($t(i.schedule?.scheduledTime),$t(s.schedule?.scheduledTime)))}),{...R,scheduledMatchUps:r}}function cv({tournamentRecords:t}){let e=[],r={};for(let n of Object.values(t))for(let o of n.events??[]){let i=vr({event:o}),s=i?.drawDetails;Rt(s)?(Object.assign(r,s),e.push(...Object.keys(s).filter(a=>Qm({drawId:a,drawDetails:s})))):i?.drawIds?.length&&e.push(...i.drawIds)}return{drawIds:e,detailsMap:r}}function Hd({schedulingProfile:t,matchUps:e=[]}){let r={},n=({eventId:a,drawId:c,structureId:u,roundNumber:p})=>`${a}|${c}|${u}${p}`;t?.length&&t.map(({venues:c})=>c.map(({rounds:u})=>u)).flat().forEach(c=>{c.sort((p,m)=>(p.sortOrder||0)-(m.sortOrder||0)).forEach(({eventId:p,drawId:m,structureId:d,roundNumber:l},f)=>{let g=n({eventId:p,drawId:m,structureId:d,roundNumber:l});r[g]=f})});let o=[],i={noScheduledDate:[]};for(let a of e){let c=a.schedule||{},u=c.scheduledDate&&Ut(c.scheduledDate)||c.scheduledTime&&Ut(c.scheduledTime)||"noScheduledDate";i[u]||(i[u]=[]),i[u].push(a)}let s=Object.keys(i).sort();for(let a of s){let c=i[a],u={noScheduledTime:[]};for(let m of c){let d=m.schedule||{},l=d.scheduledTime&&$t(d.scheduledTime)||"noScheduledTime";u[l]||(u[l]=[]),u[l].push(m)}let p=Object.keys(u).sort();for(let m of p){let d=u[m];d.sort((l,f)=>{let g=r[n(l)]||0,I=r[n(f)]||0;return g-I}),o.push(...d)}}return o}function Dg({courtPrefix:t="C|",minRowsCount:e,courtsData:r}){if(!Array.isArray(r))return{error:G};let n=r?.reduce((s,a)=>{let c=a.matchUps||[],u=Math.max(0,...c.map(p=>p.schedule.courtOrder||0));return u>s?u:s},1),o=e?Math.max(e,n):n,i=Z(0,o).map(s=>({matchUps:Z(0,r.length).map(a=>{let c=r[a],{courtId:u,venueId:p}=c;return{schedule:{courtOrder:s+1,venueId:p,courtId:u}}})}));return r.forEach((s,a)=>{for(let c of s.matchUps){let u=c.schedule?.courtOrder;u&&(i[u-1].matchUps[a]=c)}}),{courtPrefix:t,rows:i.map((s,a)=>Object.assign({rowId:`rowId-${a+1}`},...s.matchUps.map((c,u)=>({[`${t}${u}`]:c}))))}}function Wd(t){let{participants:e,contextContent:r,participantMap:n}=t,{tournamentAppliedPolicies:o,scheduleVisibilityFilters:i,participantsProfile:s,afterRecoveryTimes:a,policyDefinitions:c,useParticipantMap:u,tournamentRecord:p,usePublishState:m,contextFilters:d,matchUpFilters:l,contextProfile:f,nextMatchUps:g,tournamentId:I,inContext:h,context:S,event:T}=t;if(!T)return{error:Et};let{eventId:A,eventName:D,endDate:y,eventType:E,category:U,gender:M}=T??{},P={...S,...rt({surfaceCategory:T.surfaceCategory??p?.surfaceCategory,indoorOutDoor:T.indoorOutdoor??p?.indoorOutdoor,tournamentId:I??p?.tournamentId,endDate:y??p?.endDate,eventName:D,eventType:E,category:U,eventId:A,gender:M})},N;!e&&p&&({participants:e,participantMap:n,groupInfo:N}=Ii({participantsProfile:s,policyDefinitions:c,useParticipantMap:u,tournamentRecord:p,contextProfile:f,inContext:h})),f&&!r&&(r=Ln({policyDefinitions:c,tournamentRecord:p,contextProfile:f,event:T}));let C=vr({event:T});return{...(T.drawDefinitions??[]).reduce((x,w)=>{let F=Vs({context:P,tournamentAppliedPolicies:o,scheduleVisibilityFilters:i,tournamentParticipants:e,participantsProfile:s,afterRecoveryTimes:a,policyDefinitions:c,tournamentRecord:p,usePublishState:m,contextContent:r,contextFilters:d,matchUpFilters:l,participantMap:n,publishStatus:C,contextProfile:f,drawDefinition:w,nextMatchUps:g,inContext:h,event:T});return Object.keys(F)?.forEach(v=>{Array.isArray(F[v])&&(x[v]||(x[v]=[]),x[v]=x[v].concat(F[v]))}),x},{}),...R,groupInfo:N}}function jd(t){if(!t?.tournamentRecord)return{error:W};let e=t.contextContent,{scheduleVisibilityFilters:r,participantsProfile:n,afterRecoveryTimes:o,policyDefinitions:i,useParticipantMap:s,tournamentRecord:a,inContext:c=!0,usePublishState:u,contextFilters:p,matchUpFilters:m,contextProfile:d,nextMatchUps:l,context:f}=t,g=t.tournamentId??a.tournamentId,I=a?.events??[],{participants:h,participantMap:S,groupInfo:T}=Ii({participantsProfile:n,policyDefinitions:i,useParticipantMap:s,tournamentRecord:a,contextProfile:d,inContext:c});d&&!e&&(e=Ln({policyDefinitions:i,tournamentRecord:a,contextProfile:d}));let{appliedPolicies:A}=Pt({tournamentRecord:a}),D=p?.eventIds??[];return{...I.filter(U=>!D.includes(U.eventId)).map(U=>{let P={eventDrawsCount:Ht({event:U}).flightProfile?.flights?.length||U.drawDefinitions?.length||0,...f};return Wd({context:P,tournamentAppliedPolicies:A,scheduleVisibilityFilters:r,participantsProfile:n,afterRecoveryTimes:o,policyDefinitions:i,tournamentRecord:a,usePublishState:u,contextFilters:p,contextProfile:d,contextContent:e,matchUpFilters:m,participantMap:S,participants:h,tournamentId:g,nextMatchUps:l,inContext:c,event:U})}).reduce((U,M)=>((M&&Object.keys(M).filter(N=>!["success","matchUpsMap"].includes(N)))?.forEach(N=>{Array.isArray(M[N])&&(U[N]||(U[N]=[]),U[N]=U[N].concat(M[N]),U.matchUpsCount+=M[N].length)}),U),{matchUpsCount:0}),groupInfo:T}}function kp({scheduleVisibilityFilters:t,participantsProfile:e,tournamentRecords:r,policyDefinitions:n,usePublishState:o,matchUpFilters:i,contextFilters:s,nextMatchUps:a,inContext:c}){if(typeof r!="object"||!Object.keys(r).length)return{error:Ft};let p=Object.keys(r).map(l=>{let f=r[l];return jd({scheduleVisibilityFilters:t,participantsProfile:e,policyDefinitions:n,tournamentRecord:f,usePublishState:o,matchUpFilters:i,contextFilters:s,nextMatchUps:a,inContext:c})}),m={};return{...p.reduce((l,f)=>(Object.keys(f).forEach(I=>{Array.isArray(f[I])&&(l[I]||(l[I]=[]),l[I]=l[I].concat(f[I])),I==="groupInfo"&&Object.assign(m,f[I])}),l),{}),groupInfo:m}}function Ou(t){if(typeof t?.tournamentRecords!="object"||!Object.keys(t?.tournamentRecords).length)return{error:Ft};let{courts:e,venues:r}=po(t),o=ko(t).schedulingProfile,{sortDateMatchUps:i=!0,courtCompletedMatchUps:s,alwaysReturnCompleted:a,activeTournamentId:c,tournamentRecords:u,withCourtGridRows:p,minCourtGridRows:m,usePublishState:d,status:l=Gr,sortCourtsData:f}=t,g=d?mu({tournamentRecord:u[c??$i()],itemType:`${Ko}.${zo}`}).timeItem?.itemValue?.[l]:void 0,I=a?kp({...t,matchUpFilters:{...t.matchUpFilters,matchUpStatuses:[me]},contextFilters:t.contextFilters}).completedMatchUps:[];if(d&&(!g||!Object.keys(g).length))return{completedMatchUps:I,dateMatchUps:[],courtsData:[],venues:r};let h,S;d&&({drawIds:h,detailsMap:S}=cv({tournamentRecords:u})),h?.length&&(t.contextFilters||(t.contextFilters={}),t.contextFilters?.drawIds?t.contextFilters.drawIds=t.contextFilters.drawIds.filter(C=>h.includes(C)):t.contextFilters.drawIds=h),g?.eventIds?.length&&(t.matchUpFilters||(t.matchUpFilters={}),t.matchUpFilters?.eventIds&&t.matchUpFilters.eventIds.length?t.matchUpFilters.eventIds=t.matchUpFilters.eventIds.filter(C=>g.eventIds.includes(C)):t.matchUpFilters.eventIds=g.eventIds),g?.scheduledDates?.length&&(t.matchUpFilters||(t.matchUpFilters={}),t.matchUpFilters.scheduledDates&&t.matchUpFilters.scheduledDates.length?t.matchUpFilters.scheduledDates=t.matchUpFilters.scheduledDates.filter(C=>g.scheduledDates.includes(C)):t.matchUpFilters.scheduledDates=g.scheduledDates),a&&(t.matchUpFilters||(t.matchUpFilters={}),t.matchUpFilters?.excludeMatchUpStatuses?.length?t.matchUpFilters.excludeMatchUpStatuses.includes(me)||t.matchUpFilters.excludeMatchUpStatuses.push(me):t.matchUpFilters.excludeMatchUpStatuses=[me]);let{completedMatchUps:T,upcomingMatchUps:A,pendingMatchUps:D,groupInfo:y}=kp({...t,matchUpFilters:t.matchUpFilters,contextFilters:t.contextFilters}),E=[...A??[],...D??[]];S&&Object.keys(S).length&&(E=E.filter(C=>{let{drawId:O,structureId:b,stage:x}=C;if(!S[O])return!1;if(S[O].stageDetails){let w=Object.keys(S[O].stageDetails),F=w.filter(v=>!S[O].stageDetails[v].published),L=w.filter(v=>S[O].stageDetails[v].published);return F.length&&F.includes(x)?!1:L.length&&L.includes(x)?!0:F.length&&!F.includes(x)&&!L.length}if(S[O].structureDetails){let w=Object.keys(S[O].structureDetails),F=w.filter(v=>!S[O].structureDetails[v].published),L=w.filter(v=>S[O].structureDetails[v].published);return F.length&&F.includes(b)?!1:L.length&&L.includes(b)?!0:F.length&&!F.includes(b)&&!L.length}return!0}));let U=i?Hd({matchUps:E,schedulingProfile:o}):E,M=e?.map(C=>{let O=N(C);return{surfaceCategory:C?.surfaceCategory??"",matchUps:O,...C}}),P={completedMatchUps:a?I:T,dateMatchUps:U,courtsData:M,groupInfo:y,venues:r};if(p){let{rows:C,courtPrefix:O}=Dg({minRowsCount:m,courtsData:M});P.courtPrefix=O,P.rows=C}return{...P,...R};function N({courtId:C}){let b=(s?U.concat(T??[]):U).filter(x=>x.schedule?.courtId===C||x.schedule?.allocatedCourts?.map(({courtId:w})=>w).includes(C));return f?Hd({matchUps:b,schedulingProfile:o}):b}}function Yd({tournamentRecords:t,tournamentId:e}){if(typeof t!="object"||!Object.keys(t).length)return{error:Ft};let r=Object.keys(t).filter(o=>!e||o===e),n;return r.forEach(o=>{let i=t[o],{matchUpDailyLimits:s}=sV({tournamentRecord:i});n=s}),{matchUpDailyLimits:n}}function sV(t){let e=lt(t,[{[An]:!0}]);if(e.error)return e;let{tournamentRecord:r}=t,{policy:n}=$o({policyType:go,tournamentRecord:r}),{extension:o}=mt({element:r,name:Yc}),i=o?.value?.dailyLimits,s=n?.defaultDailyLimits;return{matchUpDailyLimits:i||s}}function GT(t){let{matchUps:e}=t,{singlesForDoubles:r,tournamentRecord:n,drawDefinition:o,excludeMargin:i,exclusionRule:s,zoneDoubling:a,matchUpType:c,scaleName:u,eventId:p,zonePct:m,drawId:d,event:l}=t;if(!n&&!e)return{error:W};if(c&&![Xt,Gt].includes(c))return{error:G,info:{matchUpType:c}};if(e&&!Ur(e))return{error:G,context:{matchUps:e}};let f=Br[u],g=f?.ascending??t.ascending??!1,I=f?.accessor??t.valueAccessor,h=Array.isArray(f?.range)?Math.abs(f.range[0]-f.range[1]):0,S=ft(m)&&h?(m??0/100)*h:t.zoneMargin??h,T={withScaleValues:!0,withCompetitiveness:!0},A={matchUpTypes:c?[c]:[Xt,Gt]},D=n?.participants;e?.[0]?.hasContext?d?e=e.filter(b=>b.drawId===d):p&&(e=e.filter(b=>b.eventId===p)):e===void 0&&(e=d&&!o&&[]||!d&&p&&!l&&[]||d&&rr({inContext:!0,drawDefinition:o,contextFilters:A,contextProfile:T,participants:D})?.matchUps||!d&&p&&co({inContext:!0,contextFilters:A,contextProfile:T,participants:D,event:l})?.matchUps||le({tournamentRecord:n,contextFilters:A,contextProfile:T})?.matchUps||[]),c&&(e=e.filter(b=>b.matchUpType===c));let y=e.filter(({winningSide:b,score:x,sides:w,matchUpStatus:F})=>![lr,Ot,_t,Kc,$r].includes(F??"")&&Ie({score:x})&&w?.length===2&&b),E=cV({matchUps:y,excludeMargin:i,exclusionRule:s,valueAccessor:I,ascending:g,scaleName:u}),U=!a||ie(Xt)(c)?S:(S||0)*2,M=S?y.map(({competitiveProfile:b,matchUpType:x,score:w,sides:F})=>{let L=pv({singlesForDoubles:r,valueAccessor:I,matchUpType:x,scaleName:u,sides:F}),v=Math.abs(L[0].value-L[1].value);return{competitiveness:b?.competitiveness,valuesGap:v,score:w}}).filter(({valuesGap:b})=>b<=U):[],P=aV({zoneData:M}),N=P&&[].concat(Object.values(P)).flat().length,C=N&&Object.assign({},...Object.keys(P).map(b=>({[b]:Math.round(1e4*P[b].length/N)/100}))),O=y.length-(M?.length||0);return{...R,relevantMatchUps:y,zoneDistribution:C,zoneData:M,accuracy:E,nonZone:O}}function aV({zoneData:t}){let e={[Fm]:[],[sc]:[],[ac]:[]};for(let r of t){let{competitiveness:n,score:o,valuesGap:i}=r;e[n]&&e[n].push({score:o,valuesGap:i})}return e}function pv({singlesForDoubles:t,exclusionRule:e,valueAccessor:r,matchUpType:n,scaleName:o,sides:i}){let s=e?.range.sort(),a=c=>{let u=c?.[e?.valueAccessor];return{exclude:e&&u>=s[0]&&u<=s[1],exclusionValue:u}};return i.sort((c,u)=>c.sideNumber-u.sideNumber).map(({participant:c})=>{let u=[],p=c?.individualParticipants;if(p?.length){let m=[],d=0;for(let l of p){let{scaleValue:f,value:g}=uv({singlesForDoubles:t,valueAccessor:r,participant:l,matchUpType:n,scaleName:o}),{exclude:I,exclusionValue:h}=a(f);I&&u.push(h),m.push(f),g&&!isNaN(d)?d+=g:d=void 0}return{participantName:c.participantName,exclusionValues:u,scaleValues:m,value:d}}else if(c){let{scaleValue:m,value:d}=uv({singlesForDoubles:t,valueAccessor:r,matchUpType:n,participant:c,scaleName:o}),{exclude:l,exclusionValue:f}=a(m);return l&&u.push(f),{participantName:c.participantName,exclusionValues:u,scaleValue:m,value:d}}else return{}})}function uv({singlesForDoubles:t,valueAccessor:e,matchUpType:r,participant:n,scaleName:o}){let i=t?Xt:r,s=n?.rankings?.[i]?.find(p=>p.scaleName===o),c=(n?.ratings?.[i]?.find(p=>p.scaleName===o)||s)?.scaleValue,u=e?c?.[e]:c;return{scaleValue:c,value:u}}function cV({excludeMargin:t,exclusionRule:e,valueAccessor:r,ascending:n,scaleName:o,matchUps:i}){let s={affirmative:[],negative:[],excluded:[]};for(let u of i){let{matchUpType:p,sides:m,score:d,winningSide:l}=u;if(!l)continue;if(e&&(!e.valueAccessor||!e.range))return{info:"exclusionRule requires valueAccessor and range",error:et};let f=l-1,g=pv({exclusionRule:e,valueAccessor:r,matchUpType:p,scaleName:o,sides:m});if(e){let D=g.map(({exclusionValues:y})=>y).flat();if(D.length){s.excluded.push({scoreString:d?.scoreStringSide1,exclusionValues:D,winningSide:l,sideValues:g});continue}}if(g.filter(D=>![void 0,"",null].includes(D.value)).length<2){s.excluded.push({scoreString:d?.scoreStringSide1,missingValues:!0,winningSide:l,sideValues:g});continue}let I=g[f].value-g[1-f].value,h=parseFloat(t||0),S=h&&Math.abs(I)<h;if(S){s.excluded.push({scoreString:d?.scoreStringSide1,excludeMargin:t,winningSide:l,excludeGap:S,sideValues:g,valuesGap:I});continue}let T=n?I:I*-1,A=l===1?d?.scoreStringSide1:d?.scoreStringSide2;T>0?s.affirmative.push({winningScoreString:A,winningSide:l,sideValues:g,valuesGap:I,score:d}):s.negative.push({winningScoreString:A,winningSide:l,sideValues:g,valuesGap:I,score:d})}let a=s.affirmative.length+s.negative.length,c=a&&s.affirmative.length/a*100;return s.percent=c?Math.round(100*c)/100:0,s}function Is({collectionDefinitions:t=[],collectionGroups:e=[]}){let r=0,{groupValueNumbers:n}=sS({collectionGroups:e}),o;for(let s of t||[]){let{collectionValueProfiles:a,collectionGroupNumber:c,collectionValue:u,matchUpCount:p,matchUpValue:m,scoreValue:d,setValue:l}=s,f=c&&n.includes(c);if(ft(l||d))o=!0;else{if(f)continue;if(typeof u=="number"&&ft(u))r+=u;else if(a?.length)for(let g of a)r+=g.matchUpValue;else typeof m=="number"&&ft(m)&&(r+=(p??0)*m)}}for(let s of e)r+=s.groupValue??0;return o||!r?{aggregateValue:!0,...R}:{valueGoal:Math.floor(r/2)+1,...R}}function kT({matchUps:t,matchUpId:e}){if(!Ur(t))return{error:G};let r=t.find(a=>a.matchUpId===e),{drawId:n,eventId:o,structureId:i,tournamentId:s}=r||{};return{matchUpId:e,drawId:n,eventId:o,structureId:i,tournamentId:s}}function xa(t,e){if(!Rt(t))return{error:G};if(!Array.isArray(e))return{error:G};let r={};for(let{param:n,error:o,attr:i}of e){let s=uV({params:t,param:n,attr:i,error:o});if(s?.error)return s;r[n]=s}return r}function uV({params:t,param:e,attr:r,error:n}){if(e===ql&&Rt(t.drawDefinition)&&$e(t.structureId)){let o=(t.drawDefinition.structures??[]).find(({structureId:i})=>i===t.structureId);return!o.length&&n?{error:n}:{structure:o}}if(e===fo){let o=wD({...t,...r});return o.error&&n?{...o,error:n}:o}return{error:Ke,info:{param:e}}}function VT(t){let{structureId:e,matchUpId:r,event:n}=t,o=t.drawDefinition,i=lt(t,[{[An]:!0},{[fm]:{[dm]:!1,[Co]:!1,[OI]:!1,[Cs]:!1}}]);if(i[Ms])return i;let a=xa(t,[{[sa]:fo,[Ms]:et}])?.matchUp;if(r&&a?.error)return a;!o&&a?.drawDefinition&&(o=a?.drawDefinition);let c=a?.structure;if(!c&&e&&!r){if(!o)return{error:Wr};let l=st({drawDefinition:o,structureId:e});if(l.error)return l;c=l.structure}let u=c?.matchUpFormat,p=o?.matchUpFormat,m=n?.matchUpFormat,d=a?.matchUp?.matchUpFormat||u||p||m;return{structureDefaultMatchUpFormat:u,eventDefaultMatchUpFormat:m,drawDefaultMatchUpFormat:p,matchUpFormat:d}}function BT({profileBands:t,tournamentRecord:e,matchUps:r}){if(!Ur(r))return{error:Sn};let n=!t&&$o({policyType:ii,tournamentRecord:e}).policy,o=t||n?.profileBands||km[ii].profileBands,i=r.filter(({winningSide:d})=>d),s=i.map(sh),a=(d,l)=>{let f=ih(l,o);return d[f]+=1,d},c=ah(s).reduce((d,l)=>a(d,l),{[Fm]:0,[sc]:0,[ac]:0,[oh]:0}),u=Object.keys(c).reduce((d,l)=>(c[l]||0)+d,0),p=Object.keys(c).map(d=>{let l=parseFloat((c[d]/u).toFixed(4));return{[d]:l*100}}),m=i.filter(({matchUpStatus:d})=>d===QE).length;return p.push({[QE]:parseFloat((m/u).toFixed(4))*100}),{competitiveBands:Object.assign({},...p),...R}}var{stageOrder:mv}=TR;function dv(t,e){return t.eventName.localeCompare(e.eventName)||t.eventId.localeCompare(e.eventId)||(mv[t?.stage]||0)-(mv[e?.stage]||0)||e.matchUpsCount-t.matchUpsCount||`${t.stageSequence}-${t.roundNumber}-${t.minFinishingSum}`.localeCompare(`${e.stageSequence}-${e.roundNumber}-${e.minFinishingSum}`)}function HT({excludeScheduleDateProfileRounds:t,excludeScheduledRounds:e,excludeCompletedRounds:r,inContextMatchUps:n,tournamentRecords:o,schedulingProfile:i,tournamentRecord:s,withSplitRounds:a,matchUpFilters:c,scheduleDate:u,withRoundId:p,venueId:m,context:d}){if(n&&!Array.isArray(n||typeof n[0]!="object"))return{error:G,inContextMatchUps:n};if(s&&!o){if(typeof s!="object")return{error:Ba};o={[s.tournamentId]:s}}let l=typeof o!="object"||!Object.keys(o).length;if((m||u||!n||!i&&(t||r||i||a))&&l)return{error:Ft};let g=Object.assign({},...Object.values(o??{}).map(({venues:E=[],tournamentId:U})=>({[U]:E?.map(({venueId:M})=>M)}))),I=Object.values(o??{}).map(({events:E=[],tournamentId:U,startDate:M,endDate:P})=>E.map(N=>({...N,validVenueIds:g[U],startDate:N.startDate??M,endDate:N.endDate??P}))).flat(),{segmentedRounds:h,profileRounds:S}=o&&(t||r||i||a)&&kd({tournamentRecords:o,schedulingProfile:i})||{},T=t&&Object.assign({},...S.map(E=>({[E.id]:E}))),A=n||o&&cn({tournamentRecords:o,matchUpFilters:c})?.matchUps||[],D=[],y=A&&Object.values(A.reduce((E,U)=>{let M=Pg(U).id,P=h?.[M],N=[...E[M]?.matchUps??[],U],{containerStructureId:C,stageSequence:O,structureName:b,tournamentId:x,isRoundRobin:w,matchUpType:F,roundNumber:L,roundOffset:v,structureId:B,eventName:H,roundName:j,drawName:V,eventId:Y,drawId:$}=U,k=w?C:B;return{...E,[M]:{id:p?M:void 0,structureId:k,stageSequence:O,segmentsCount:P,structureName:b,tournamentId:x,matchUpType:F,roundNumber:L,roundOffset:v,eventName:H,roundName:j,drawName:V,matchUps:N,eventId:Y,drawId:$}}},{})).map(E=>{let{minFinishingSum:U,winnerFinishingPositionRange:M}=sv(E.matchUps),P=E.segmentsCount;if(P){let L=E.matchUps.length/P;return Te(E.matchUps.sort((B,H)=>B.roundPosition-H.roundPosition),L).map((B,H)=>{let{unscheduledCount:j,incompleteCount:V,matchUpsCount:Y,isScheduled:$,isComplete:k,byeCount:K}=HD(B),z=BD({matchUps:E.matchUps,tournamentRecords:o,events:I,round:E});return rt({...E,...d,roundSegment:{segmentsCount:P,segmentNumber:H+1},winnerFinishingPositionRange:M,unscheduledCount:j,incompleteCount:V,minFinishingSum:U,matchUpsCount:Y,isScheduled:$,roundTiming:z,isComplete:k,byeCount:K,matchUps:B})})}let{unscheduledCount:N,incompleteCount:C,matchUpsCount:O,isScheduled:b,isComplete:x,byeCount:w}=HD(E.matchUps),F=BD({matchUps:E.matchUps,tournamentRecords:o,events:I,round:E});return rt({...E,...d,winnerFinishingPositionRange:M,unscheduledCount:N,incompleteCount:C,minFinishingSum:U,matchUpsCount:O,isScheduled:b,roundTiming:F,isComplete:x,byeCount:w})}).flat().filter(E=>{if(t){let B=Ut(t),H=p?E.id:Pg(E).id;if(B&&T[H]&&Ut(T[H].scheduleDate)===B)return!1}let{isComplete:U,isScheduled:M}=E,P=!r||!U,N=!e||!M,C=m||u?I?.find(({eventId:B})=>B===E.eventId):void 0,O=C?.startDate??s?.startDate,b=C?.endDate??s?.endDate,x=!u||!O||new Date(u)>=new Date(O),w=!u||!b||new Date(u)<=new Date(b),F=x&&w,L=!m||C?.validVenueIds.includes(m),v=P&&N&&L&&F;return v||D.push(E),v}).sort(dv)||[];return{...R,rounds:y,excludedRounds:D}}function Vp(t){let{matchUp:e,sideNumber:r,setNumber:n,isTiebreakValue:o,isPointValue:i}=t||{},{matchUpFormat:s}=t||{};if(!e)return{error:sr};s=s||e?.matchUpFormat;let a=tr(s),c=!!e?.winningSide,u=e.score?.sets,p=u?.length,m=n&&n-1,d=!!u?.find(($,k)=>$.setNumber===n&&k===m),l=u?.filter($=>$?.winningSide)||[],f=l?.length||0,g=n&&u?.slice(n)||[],I=!!(p&&n&&g?.reduce(($,k)=>(!k||!k.side1Score&&!k.side2Score&&!k.side1TiebreakScore&&!k.side2TiebreakScore&&!k.side1PointScore&&!k.side2PointScore)&&$,!0)),h=n<=p&&u.find($=>$.setNumber===n),S=h&&Ru({setObject:h,matchUpScoringFormat:a}),{isCompletedSet:T,sideGameScores:A,sideTiebreakScores:D}=S||{},y=!!(h&&!T&&I||n&&n===p+1&&!c),E=[1,2].includes(r),U=E?r-1:0,M=h&&E&&(!o&&!i&&A[U]!==void 0&&A[U]||o&&D[U]!==void 0&&D[U]),P=!!M,N=l?.map($=>Ru({setObject:$,matchUpScoringFormat:a}).isValidSetOutcome).reduce(($,k)=>$&&k,!0),C=l.reduce(($,k)=>{let{winningSide:K}=k,z=K-1;return $[z]++,$},[0,0]),O=e?.winningSide,b=O&&O-1,x=1-b,w=C[b],F=C[x],L=Math.max(...C),v=dr(C)[L],{bestOf:B}=a??{},H=B&&Math.ceil(B/2)||1,j=L===H&&v===1&&C.indexOf(L)+1||void 0,V=w>F&&O===j;return{completedSetsHaveValidOutcomes:N,validMatchUpWinningSide:V,calculatedWinningSide:j,matchUpScoringFormat:a,validMatchUpOutcome:j&&N&&V,isLastSetWithValues:I,completedSetsCount:f,isCompletedMatchUp:c,isValidSideNumber:E,hasExistingValue:P,existingValue:M,isExistingSet:d,isActiveSet:y,...S}}function WT({participants:t,tournamentAppliedPolicies:e,scheduleVisibilityFilters:r,participantsProfile:n,afterRecoveryTimes:o,policyDefinitions:i,useParticipantMap:s,tournamentRecord:a,usePublishState:c,contextFilters:u,contextContent:p,matchUpFilters:m,participantMap:d,publishStatus:l,contextProfile:f,drawDefinition:g,nextMatchUps:I,tournamentId:h,inContext:S,context:T,event:A}){let{eventId:D,eventName:y,endDate:E,eventType:U,category:M,gender:P}=A??{},N={...T,...rt({surfaceCategory:A?.surfaceCategory??a?.surfaceCategory,indoorOutDoor:A?.indoorOutdoor??a?.indoorOutdoor,endDate:E??A?.endDate??a?.endDate,tournamentId:h??a?.tournamentId,eventName:y,eventType:U,category:M,eventId:D,gender:P})},C;return!t?.length&&a&&({participants:t,participantMap:d,groupInfo:C}=Ii({participantsProfile:n,policyDefinitions:i,useParticipantMap:s,tournamentRecord:a,contextProfile:f,inContext:S})),A&&f&&!p&&(p=Ln({policyDefinitions:i,tournamentRecord:a,contextProfile:f,drawDefinition:g,event:A})),{...Vs({context:N,tournamentAppliedPolicies:e,scheduleVisibilityFilters:r,tournamentParticipants:t,participantsProfile:n,afterRecoveryTimes:o,policyDefinitions:i,tournamentRecord:a,usePublishState:c,participantMap:d,contextContent:p,contextFilters:u,matchUpFilters:m,publishStatus:l,contextProfile:f,drawDefinition:g,nextMatchUps:I,inContext:S,event:A}),groupInfo:C}}var zD={};Jt(zD,{getCompetitionVenues:()=>Lp,getCourts:()=>jT,getVenuesAndCourts:()=>po,publicFindVenue:()=>Th});function jT({tournamentRecord:t,venueId:e,venueIds:r}){return t?{courts:(t.venues||[]).filter(o=>e?o.venueId===e:r?r.includes(o.venueId):!0).map(o=>{let{venueId:i}=o,s=J(o.courts||[]);return s.forEach(a=>Object.assign(a,{venueId:i})),s}).flat()}:{error:W}}var QD={};Jt(QD,{categoryCanContain:()=>dd,getCategoryAgeDetails:()=>Au,getEvent:()=>$T,getEventProperties:()=>YT,getEventStructures:()=>Qf,getEventTimeItem:()=>pu,getEvents:()=>qT,getFlightProfile:()=>Ht,getScaledEntries:()=>Qs});function YT({tournamentRecord:t,event:e}){if(!t)return{error:W};if(!e)return{error:Et};let r=e.entries||[],n=t.participants||[],o=e.category?.categoryName||e.category?.ageCategoryCode,{eventType:i}=e,s=r.map(d=>d.participantId),a=n.filter(d=>s.includes(d.participantId)),c,u,p;return{entryScaleAttributes:a.map(d=>{let{participantId:l,participantName:f,name:g}=d,I={scaleType:Of,eventType:i,scaleName:o},h=uo({participant:d,scaleAttributes:I})?.scaleItem?.scaleValue;I={scaleType:tU,eventType:i,scaleName:o};let S=uo({participant:d,scaleAttributes:I})?.scaleItem?.scaleValue;I={scaleType:ZE,eventType:i,scaleName:o};let T=uo({participant:d,scaleAttributes:I})?.scaleItem?.scaleValue;return c=!!(c||h),u=!!(u||S),p=!!(p||T),{participantId:l,participantName:f||g,seed:h,ranking:S,rating:T}}),hasSeededParticipants:c,hasRankedParticipants:u,hasRatedParticipants:p}}function qT({tournamentRecord:t,withScaleValues:e,scaleEventType:r,inContext:n,eventIds:o,drawIds:i,context:s}){if(!t)return{error:W};let{tournamentId:a}=t,c=(t.events??[]).filter(({eventId:p})=>!o||Array.isArray(o)&&o.includes(p)).map(p=>{let m=p.drawDefinitions?.map($c);if(i?.length&&!jt(i,m).length)return;let d=J(p);return n&&Object.assign(d,{tournamentId:a}),s&&Object.assign(d,s),d}).filter(Boolean),u={};if(e){let p=Yt({withScaleValues:!0,tournamentRecord:t}).participantMap,m=d=>d.reduce((l,f)=>l+parseFloat(f),0);for(let d of c){let l=r??d.eventType,f=d.eventId;u[f]||(u[f]={ratingsStats:{},ratings:{},ranking:{},draws:{}});let I=(d.entries??[]).filter(({entryStatus:E})=>Or.includes(E)).map(gt),h=E=>{if(E?.ratings?.[l])for(let U of E?.ratings?.[l]??[]){let M=U.scaleName;u[f].ratings[M]||(u[f].ratings[M]=[]);let P=Br[M]?.accessor;if(P){let N=parseFloat(U.scaleValue?.[P]);N&&u[f].ratings[M].push(N)}}if(E?.rankings?.[l])for(let U of E?.rankings?.[l]??[]){let M=U.scaleName;u[f].ranking[M]||(u[f].ranking[M]=[]),U.scaleValue&&u[f].ranking[M].push(U.scaleValue)}};for(let E of I){let U=p?.[E]?.participant;if(U?.participantType!==ht)for(let M of U?.individualParticipantIds??[]){let P=p?.[M]?.participant;h(P)}else h(U)}let S=u[f].ratings;for(let E of Object.keys(S)){let U=S[E];if(!U.length)continue;let M=iE(U)?.toFixed(2);u[f].ratingsStats[E]={avg:parseFloat((m(U)/U.length).toFixed(2)),median:M?parseFloat(M):void 0,max:Math.max(...U),min:Math.min(...U)}}let T=(E,U)=>{let M=P=>{if(u[f].draws?.[E]&&P?.ratings?.[l])for(let N of P?.ratings?.[l]??[]){let C=N.scaleName;u[f].draws[E]?.ratings[C]||(u[f].draws[E].ratings[C]=[]);let O=Br[C]?.accessor;if(O){let b=parseFloat(N.scaleValue?.[O]);b&&u[f].draws[E].ratings[C].push(b)}}if(u[f].draws?.[E]&&P?.rankings?.[l])for(let N of P?.rankings?.[l]??[]){let C=N.scaleName;u[f].draws[E]?.ranking[C]||(u[f].draws[E].ranking[C]=[]);let O=N.scaleValue;O&&u[f].draws[E].ranking[C].push(O)}};for(let P of U.filter(Boolean)){let N=p?.[P]?.participant;if(N?.participantType!==ht)for(let C of N?.individualParticipantIds??[]){let O=p?.[C]?.participant;M(O)}else M(N)}},A=[],D=E=>i?.length&&i.includes(E)||A.includes(E);for(let E of d.drawDefinitions??[]){let U=E.drawId;if(D(U))continue;let M=Si({drawDefinition:E}).assignedParticipantIds??[];u[f].draws[U]||(u[f].draws[U]={ratingsStats:{},ratings:{},ranking:{}}),A.push(U),T(U,M)}let y=Ht({event:d}).flightProfile;for(let E of y?.flights??[]){let U=E.drawId;if(D(U))continue;let M=E.drawEntries.map(gt);T(U,M)}for(let E of A){let U=u[f].draws[E].ratings;for(let M of Object.keys(U)){let P=U[M];if(!P.length)continue;let N=iE(P)?.toFixed(2);u[f].draws[E].ratingsStats[M]={avg:parseFloat((m(P)/P.length).toFixed(2)),median:N?parseFloat(N):void 0,max:Math.max(...P),min:Math.min(...P)}}}}}return rt({eventScaleValues:u,events:c,...R})}function $T({tournamentRecord:t,drawDefinition:e,context:r,event:n}){if(!t)return{error:W};if(!n)return{error:Et};let o=J(n);r&&Object.assign(o,r);let i=e&&o.drawDefinitions?.find(({drawId:s})=>e.drawId===s);return rt({drawDefinition:i,event:o})}function lv(t){let e="validateAndDeriveDrawValues",{appliedPolicies:r,policyDefinitions:n}=dV(t),o=lV({...t,policyDefinitions:n,appliedPolicies:r}),i=mV(t),s=fV({...t,consideredEntries:i,appliedPolicies:r});if(s?.error)return _({result:s,stack:e});let a=gV({...t,consideredEntries:i}),c=pV({...t,appliedPolicies:r,policyDefinitions:n,drawSize:a});if(c.error)return _({result:c,stack:e});let u=c.drawType;if(isNaN(a)&&u!==an)return _({result:{error:ja},stack:e});let p=n?.[Un]??r?.[Un],m=t.seedingProfile??p?.seedingProfile?.drawTypes?.[u??""]??p?.seedingProfile;t.seedingProfile&&(n[Un]||(n[Un]={...Eg[Un]}),n[Un].seedingProfile=m);let d=IV({...t,drawType:u});return d?.error?_({result:d,stack:e}):{drawSize:a,drawType:u,enforceGender:o,seedingProfile:m,appliedPolicies:r,policyDefinitions:n}}function pV(t){let{policyDefinitions:e,appliedPolicies:r,enforceMinimumDrawSize:n=!0,drawSize:o}=t,i=t.drawTypeCoercion??Pu({drawType:t.drawType,policyDefinitions:e,appliedPolicies:r}),s=_S({drawType:t.drawType,enforceMinimumDrawSize:n,drawTypeCoercion:i,drawSize:o});return s.error?s:{drawType:s.drawType}}function JD(t){return t?.filter(e=>e.entryStatus&&[...Or,Lm].includes(e.entryStatus))}function mV({considerEventEntries:t=!0,drawEntries:e,eventEntries:r,qualifyingOnly:n}){return(n&&[]||JD(e)||(t?r:[])).filter(({entryStage:o})=>!o||o===tt)}function dV(t){let{tournamentRecord:e,event:r}=t,n=Pt({tournamentRecord:e,event:r}).appliedPolicies??{},o=J(t.policyDefinitions??{},!1,!0);return{appliedPolicies:n,policyDefinitions:o}}function lV({enforceGender:t,policyDefinitions:e,appliedPolicies:r}){return t??e?.[ze]?.participants?.enforceGender??r?.[ze]?.participants?.enforceGender}function fV(t){let{consideredEntries:e,appliedPolicies:r,policyDefinitions:n,enforceGender:o,participantMap:i,participants:s,event:a}=t;return a&&s&&Sd({consideredEntries:e,policyDefinitions:n,appliedPolicies:r,participantMap:i,enforceGender:o,participants:s,event:a})}function gV(t){return!t.drawSize&&t.consideredEntries.length&&![an,Jc,la,dn,so].includes(t.drawType??"")&&qi(t.consideredEntries.length)||t.drawSize&&ct(t.drawSize)||!1}function IV(t){let{tournamentRecord:e,event:r,ignoreAllowedDrawTypes:n,drawType:o}=t,i=!n&&e&&vd({tournamentRecord:e,categoryType:r?.category?.categoryType,categoryName:r?.category?.categoryName});return i?.length&&!i.includes(o)?{error:nm}:{...R}}function _u(t){let{voluntaryConsolation:e,tournamentRecord:r,event:n}=t,o="generateDrawDefinition",{participants:i,participantMap:s}=Yt({withIndividualParticipants:!0,convertExtensions:!0,internalUse:!0,tournamentRecord:r}),a=JD(n?.entries)??[],c=lv({...t,participantMap:s,participants:i,eventEntries:a});if(c.error)return _({result:c,stack:o});let{appliedPolicies:u,policyDefinitions:p,drawSize:m,drawType:d,enforceGender:l,seedingProfile:f}=c,g=n?.eventType,I=t.matchUpType??g,h=V_({...t,enforceGender:l,eventType:g,matchUpType:I});if(h.error)return _({result:h,stack:o});let{matchUpFormat:S,tieFormat:T}=h;if(t.drawId&&typeof t.drawId!="string")return _({result:{error:G},stack:o});let D=tv({...t,isMock:t.isMock??!0,policyDefinitions:p,tournamentRecord:r,appliedPolicies:u,matchUpFormat:S,seedingProfile:f,participants:i,eventEntries:a,matchUpType:I,tieFormat:T,drawSize:m,drawType:d,event:n});if(D.error)return _({result:D,stack:o});let{existingDrawDefinition:y,positioningReports:E,drawDefinition:U,structureId:M,conflicts:P,entries:N}=D;if(!U)return _({result:{error:G},stack:o});let C=ev({...t,existingDrawDefinition:y,positioningReports:E,appliedPolicies:u,drawDefinition:U,seedingProfile:f,participants:i,structureId:M,entries:N,params:t,stack:o});if(C.error)return C;let{qualifyingConflicts:O}=C;return U.drawName=t.drawName??(d&&Ye(d)),m&&typeof e=="object"&&m>=4&&jf({...e,drawDefinition:U,matchUpType:I}),{existingDrawDefinition:!!y,qualifyingConflicts:O,positioningReports:E,drawDefinition:U,structureId:M,...R,conflicts:P}}function KT({scaleAttributes:t,scaledEntries:e,stageEntries:r,seedsCount:n,scaleName:o}){if(!t)return{error:et,info:"missing scaleAttributes"};let i=Object.assign({},...(e||[]).slice(0,n).map(({participantId:c},u)=>({[c]:u+1})));o=o||t.scaleName;let s=new Date().toISOString();return{scaleItemsWithParticipantIds:r.map(({participantId:c})=>({scaleItems:[{scaleValue:i[c],eventType:t.eventType,scaleType:eo,scaleName:o,scaleDate:s}],participantId:c}))}}function fv({tournamentRecord:t,drawDefinition:e,policyDefinitions:r,scaleAttributes:n,scaleName:o,drawSize:i,drawId:s,event:a,stage:c,sortDescending:u,scaleSortMethod:p}){let m=Vd({policyDefinitions:r,drawDefinition:e,drawSize:i,drawId:s,event:a,stage:c});if(m.error)return m;let{entries:d,seedsCount:l,stageEntries:f}=m;if(!f||!l)return{error:G};let g=Qs({tournamentRecord:t,scaleAttributes:n,scaleSortMethod:p,sortDescending:u,entries:d,stage:c}).scaledEntries??[],{scaleItemsWithParticipantIds:I}=KT({scaleAttributes:n,scaledEntries:g,stageEntries:f,seedsCount:l,scaleName:o});return{scaleItemsWithParticipantIds:I}}var sN={};Jt(sN,{addDrawEntries:()=>Vf,addEventEntries:()=>Kn,addEventEntryPairs:()=>nN,destroyPairEntries:()=>yU,destroyPairEntry:()=>Wf,getEntriesAndSeedsCount:()=>Vd,getMaxEntryPosition:()=>OT,modifyEntriesStatus:()=>zm,modifyEventEntries:()=>oN,mutate:()=>iN,promoteAlternate:()=>eN,promoteAlternates:()=>QT,query:()=>jD,removeDrawEntries:()=>rN,removeEventEntries:()=>fc,setEntryPosition:()=>zT,setEntryPositions:()=>tN});var iN={};Jt(iN,{addDrawEntries:()=>Vf,addEventEntries:()=>Kn,addEventEntryPairs:()=>nN,destroyPairEntries:()=>yU,destroyPairEntry:()=>Wf,modifyEntriesStatus:()=>zm,modifyEventEntries:()=>oN,promoteAlternate:()=>eN,promoteAlternates:()=>QT,removeDrawEntries:()=>rN,removeEventEntries:()=>fc,setEntryPosition:()=>zT,setEntryPositions:()=>tN});function zT({tournamentRecord:t,drawDefinition:e,participantId:r,entryPosition:n,skipRefresh:o,event:i}){let s="setEntryPositions";if(!t)return{error:W};if(!r)return _({result:{error:oe},stack:s});if(n!==void 0&&!Number.isSafeInteger(n))return{error:G,entryPosition:n};(i?.entries||[]).forEach(c=>{c.participantId===r&&(c.entryPosition=n)}),(e?.entries||[]).forEach(c=>{c.participantId===r&&(c.entryPosition=n)});let a=c=>{c.entries.forEach(u=>{u.entryPosition===n&&u.participantId!==r&&(u.entryPosition+=.1)})};return o||(i?.entries&&(a(i),i.entries=Vn({entries:i.entries})),e?.entries&&(a(e),e.entries=Vn({entries:e.entries}))),{...R}}function tN({tournamentRecord:t,entryPositions:e,drawDefinition:r,event:n}){if(!t)return{error:W};if(!Array.isArray(e))return{error:G};for(let o of e){let{participantId:i,entryPosition:s}=o,a=zT({skipRefresh:!0,tournamentRecord:t,drawDefinition:r,participantId:i,entryPosition:s,event:n});if(a.error)return a}return n?.entries&&(n.entries=Vn({entries:n.entries})),r?.entries&&(r.entries=Vn({entries:r.entries})),{...R}}function eN(t){let{participantId:e}=t;return e&&typeof e!="string"?{error:G,participantId:e}:QT({...t,participantIds:[e].filter(Boolean)})}function QT({tournamentRecord:t,drawDefinition:e,participantIds:r,stageSequence:n,stage:o=tt,eventId:i,event:s}){if(!t)return{error:W};if(!Array.isArray(r))return{error:G,participantIds:r};if(!s)return{error:Et};let a="promoteAlternates";if(s){let c=gv({element:s,participantIds:r,stageSequence:n,stage:o});if(c.error)return c}if(e){let c=gv({element:e,participantIds:r,stageSequence:n,stage:o});if(c.error)return i?_({context:{drawPromotionError:c.error,drawId:e.drawId},result:{...R},stack:a}):c}return{...R}}function gv({participantIds:t,stageSequence:e,element:r,stage:n}){let o=(r.entries||[]).filter(m=>m.entryStatus===wr),i=(r.entries||[]).filter(m=>t.includes(m.participantId)),s=o.reduce((m,d)=>{let{entryPosition:l}=d;return isNaN(l)&&m||(!m||l<m.entryPosition)&&d||m},void 0),a=i.length?i:[s].filter(Boolean);if(!a?.length)return{error:hI};let c=a.filter(({entryStatus:m})=>m!==wr);if(c.length)return{error:Ml,invalidEntryStatus:c};let u=a.filter(({entryStage:m})=>m&&m!==n);if(u.length)return{error:vC,invalidStage:u};let p=e&&a.filter(m=>m.stageSequence!==e);if(p?.length)return{error:xC,invalidStageSequence:p};for(let m of a){m.entryStatus=Zr;let d=m?.entryPosition;isNaN(d)||r.entries.forEach(f=>{f.entryStatus===wr&&f.entryPosition>d&&(f.entryPosition=f.entryPosition-1)});let l=Math.max(...r.entries.filter(f=>f.entryStatus===Zr&&!isNaN(f.entryPosition)).map(({entryPosition:f})=>ct(f||0)),0);m.entryPosition=l||0}return{...R}}function rN({autoEntryPositions:t=!0,participantIds:e,drawDefinition:r,drawId:n,stages:o,event:i}){if(!i)return{error:Et};if(!n)return{error:Wr};if(!e?.length)return{error:lo};let s=Si({drawDefinition:r,stages:o}).assignedParticipantIds??[];if(xe(s,e))return{error:Ps};let c=m=>{let d=m.participantId;return!e.includes(d)},{flightProfile:u}=Ht({event:i}),p=u?.flights?.find(m=>m.drawId===n);return p?.drawEntries&&(p.drawEntries=p.drawEntries.filter(c),t&&(p.drawEntries=Vn({entries:p.drawEntries}))),r?.entries&&(r.entries=r.entries.filter(c),t&&(r.entries=Vn({entries:r.entries}))),{...R}}function gn(t){let e="addParticipant",{allowDuplicateParticipantIdPairs:r,returnParticipant:n,disableNotice:o,pairOverride:i,participant:s}=t,a=t.tournamentId?t.tournamentRecords?.[t.tournamentId]:t.tournamentRecord??(t.activeTournamentId&&t.tournamentRecords?.[t.activeTournamentId]);if(!a)return{error:W};if(!s)return _({result:{error:Mi},stack:e});s.participantId||(s.participantId=Mt()),a.participants||(a.participants=[]);let{participantId:c,individualParticipantIds:u}=s;if(a.participants.reduce((I,h)=>h.participantId===c||I,!1))return{error:Oy};let{participantType:m,participantRole:d}=s;if(!m||!Object.keys(nu).includes(m))return{error:nn,participantType:m};if(!d)return{error:by};let l=a.participants||[],f=l.filter(I=>I.participantType===ht).map(I=>I.participantId);if(m!==ht&&s.person)return{error:G,person:s.person};if(u&&!Array.isArray(u))return{error:G,individualParticipantIds:u};if(m===dt){if(s.person)return{error:G,person:s.person};if(s.individualParticipantIds){if(s.individualParticipantIds.length!==2&&!i)return _({info:"PAIR must be 2 individualParticipantIds",result:{error:zr},stack:e});{let S=l.filter(A=>A.participantType===ht).map(A=>A.participantId);if(!Array.isArray(s.individualParticipantIds))return _({result:{error:zr},stack:e});if(!s.individualParticipantIds.reduce((A,D)=>S.includes(D)&&A,!0))return _({result:{error:zr},stack:e})}}else return _({result:{error:lo},stack:e});let I=l.filter(S=>S.participantType===dt).map(S=>({individualParticipantIds:S.individualParticipantIds,participant:S})),h=s.participantType===dt&&I.find(S=>jt(S.individualParticipantIds,s.individualParticipantIds).length===2);if(h&&!r)return{...R,existingParticipant:!0,participant:n&&J(h.participant)};if(!s.participantName){let S=l.filter(A=>s.individualParticipantIds?.includes(A.participantId)),T=S.map(A=>A.person?.standardFamilyName).filter(Boolean).join("/");S.length===1&&(T+="/Unknown"),s.participantName=T}}else if(m===ht){if(!s.person?.standardFamilyName||!s.person?.standardGivenName)return{error:wy};if(!s.participantName){let I=`${s.person.standardFamilyName.toUpperCase()}, ${s.person.standardGivenName}`;s.participantName=I}}else if(m&&[kt,Ar].includes(m)){if(u||(s.individualParticipantIds=[]),s.individualParticipantIds?.length)for(let I of s.individualParticipantIds){if(typeof I!="string")return _({result:{participantId:I,error:G},stack:e});if(!f.includes(I))return _({result:{participantId:I,error:Zt},stack:e})}}else return{error:nn};a.participants.push(s),o||Tt({payload:{tournamentId:a.tournamentId,participants:[s]},topic:jo});let g={participant:n&&J(s),...R};return rt(g)}function In({allowDuplicateParticipantIdPairs:t,returnParticipants:e,tournamentRecord:r,participants:n=[]}){if(!r)return{error:W};r.participants||(r.participants=[]);let i=r.participants.map(d=>d.participantId)||[];n.forEach(d=>{d.participantId||(d.participantId=Mt())});let s=n.filter(d=>!i.includes(d.participantId)),a=n.filter(d=>i.includes(d.participantId)),c=s.filter(d=>d.participantType===ht),u=s.filter(d=>d.participantType!==ht),p=c.concat(...u),m=[];if(p.length){for(let l of p){let f=gn({allowDuplicateParticipantIdPairs:t,returnParticipant:!0,disableNotice:!0,tournamentRecord:r,participant:l});if(f.error)return f;f.success&&!f.existingParticipant&&m.push(f.participant)}m.length&&Tt({topic:jo,payload:{tournamentId:r.tournamentId,participants:m}});let d={participants:e&&J(m),addedCount:m.length,...R};return a.length&&Object.assign(d,{notAdded:a,info:Wu}),rt(d)}else return{info:"No new participants to add",addedCount:0,...R}}function nN({allowDuplicateParticipantIdPairs:t,entryStage:e=tt,entryStatus:r=wr,participantIdPairs:n=[],tournamentRecord:o,drawDefinition:i,event:s,uuids:a}){if(!o)return{error:W};if(!s)return{error:Et};if(s.eventType!==Gt)return{error:No};let c=[],u=new Map;for(let S of o.participants??[]){let{participantType:T,participantId:A,person:D,individualParticipantIds:y}=S;T===ht&&D?.sex?u.set(A,D.sex):T===dt&&y&&c.push(y)}let p=n.filter(S=>{if(S.length!==2||!u.has(S[0])||!u.has(S[1]))return!0;if(!s.gender||s.gender===Fn)return!1;let T=S.map(D=>u.get(D)),A=s.gender===ee&&(T[0]!==ee||T[1]!==ee)||s.gender===ue&&(T[0]!==ue||T[1]!==ue);return s.gender===_r&&(T.sort(du),(T[0]!==ue||T[1]!==ee)&&(A=!0)),A});if(p.length)return{error:zr,invalidParticipantIdPairs:p};let m=n.map(S=>({participantId:a?.pop()??Mt(),participantRole:Ge,individualParticipantIds:S,participantType:dt})),d=t?m:m.filter(S=>!c.find(T=>jt(T,S.individualParticipantIds).length===2)),l,f=[];if(d){let S=In({allowDuplicateParticipantIdPairs:t,participants:d,returnParticipants:!0,tournamentRecord:o});if(S.error)return S;f=S.participants||[],l=S.info}let g=n.map(S=>{let T=f.find(D=>jt(D.individualParticipantIds,S).length===2);if(T)return T;let{participant:A}=tn({tournamentRecord:o,participantIds:S});return A}).map(S=>S.participantId),I=Kn({participantIds:g,tournamentRecord:o,drawDefinition:i,entryStatus:r,entryStage:e,event:s});d.length&&Tt({payload:{participants:d},topic:jo});let h=d.map(gt);return{...I,info:l,newParticipantIds:h}}function oN({entryStatus:t=Zr,unpairedParticipantIds:e=[],participantIdPairs:r=[],entryStage:n=tt,tournamentRecord:o,event:i}){if(!o)return{error:W};if(!i)return{error:Et};let s=o.participants??[],a=s.filter(h=>h.participantType===ht).map(h=>h.participantId),u=e.concat(...r).flat(1/0).filter(h=>!a.includes(h));if(u.length)return{error:zr,invalidParticipantIds:u};let p=r.filter(h=>h.length!==2);if(p.length)return{error:zr,invalidParticipantIdPairs:p};let m=s.filter(h=>h.participantType===dt).map(h=>h.individualParticipantIds),l=r.filter(h=>!m.find(S=>jt(S,h).length===2)).map(h=>({participantType:dt,participantRole:Ge,individualParticipantIds:h})),f=In({participants:l,tournamentRecord:o});if(f.error)return f;let g=r.map(h=>{let{participant:S}=tn({tournamentRecord:o,participantIds:h});return S}).map(h=>({participantId:h,entryStatus:t,entryStage:n})),I=e.map(h=>({entryStatus:Lr,participantId:h,entryStage:n}));return i.entries=(i.entries??[]).filter(h=>h.entryStage===n),i.entries=i.entries.concat(...g,...I),{...R}}var TN={};Jt(TN,{addDrawDefinition:()=>Hp,addEvent:()=>Mc,addFlight:()=>Wp,assignSeedPositions:()=>fN,attachFlightProfile:()=>Rg,categoryCanContain:()=>dd,deleteDrawDefinitions:()=>Bp,deleteEvents:()=>IN,deleteFlightAndFlightDraw:()=>dN,deleteFlightProfileAndFlightDraws:()=>uN,getCategoryAgeDetails:()=>Au,getEvent:()=>$T,getEventProperties:()=>YT,getEventStructures:()=>Qf,getEventTimeItem:()=>pu,getEvents:()=>qT,getFlightProfile:()=>Ht,getScaledEntries:()=>Qs,modifyEvent:()=>hN,modifyEventMatchUpFormatTiming:()=>pN,modifyPairAssignment:()=>lN,mutate:()=>SN,query:()=>QD,refreshEventDrawOrder:()=>Cg,removeEventMatchUpFormatTiming:()=>qd,removeScaleValues:()=>bg,removeSeeding:()=>gN,setEventDates:()=>mN,setEventDisplay:()=>$d,setEventEndDate:()=>ZT,setEventStartDate:()=>JT,updateDrawIdsOrder:()=>Mg,validateCategory:()=>md});var SN={};Jt(SN,{addDrawDefinition:()=>Hp,addEvent:()=>Mc,addFlight:()=>Wp,assignSeedPositions:()=>fN,attachFlightProfile:()=>Rg,deleteDrawDefinitions:()=>Bp,deleteEvents:()=>IN,deleteFlightAndFlightDraw:()=>dN,deleteFlightProfileAndFlightDraws:()=>uN,modifyEvent:()=>hN,modifyEventMatchUpFormatTiming:()=>pN,modifyPairAssignment:()=>lN,refreshEventDrawOrder:()=>Cg,removeEventMatchUpFormatTiming:()=>qd,removeScaleValues:()=>bg,removeSeeding:()=>gN,setEventDates:()=>mN,setEventDisplay:()=>$d,setEventEndDate:()=>ZT,setEventStartDate:()=>JT,updateDrawIdsOrder:()=>Mg,validateCategory:()=>md});function Xs({removePriorValues:t=!0,status:e=Gr,statusObject:r,event:n}){if(!Rt(r))return{error:G};let o=vr({event:n,status:e}),i=`${Ko}.${zo}`,s={itemValue:{[e]:{...o,...r}},itemType:i};return ki({timeItem:s,removePriorValues:t,event:n})}function Js(t){let{includePositionAssignments:e,removePriorValues:r,tournamentRecord:n,status:o=Gr,event:i,drawIdsToRemove:s,drawIdsToAdd:a}=t;if(!n)return{error:W};if(!i)return{error:Et};let{appliedPolicies:c}=Pt({tournamentRecord:n,event:i}),u={...c,...t.policyDefinitions},p=i.drawDefinitions?.map(({drawId:A})=>A)??[],m=t.drawDetails?Object.keys(t.drawDetails):[],d=m.length?[]:t.drawIds,l=(a??[]).concat(...s??[],...d??[],...m),f=l.filter(A=>!p.includes(A));if(f.length)return _({result:{error:pr},context:{invalidDrawIds:f}});let g=vr({event:i,status:o}),I=Object.keys(g?.drawDetails||{}).filter(A=>p.includes(A)).reduce((A,D)=>(A[D]=g.drawDetails[D],A),{});for(let A of p)if((!l.length||l.includes(A))&&(s?.includes(A)||d?.length&&!d.includes(A)?I[A]={...I[A],publishingDetail:{published:!1}}:(a?.includes(A)||d?.includes(A)||!d?.length)&&(I[A]={...I[A],publishingDetail:{published:!0}})),t.drawDetails?.[A]){let D=t.drawDetails[A],y=D.structureDetails??I[A].structureDetails,E=D.stageDetails??I[A].stageDetails??{},{structureIdsToRemove:U=[],structureIdsToAdd:M=[],publishingDetail:P={},stagesToRemove:N=[],stagesToAdd:C=[]}=D;if((M||C)&&(P.published=!0),I[A]={publishingDetail:P,structureDetails:y,stageDetails:E},M.length||U.length){let b=(i.drawDefinitions?.find(F=>F.drawId===A)?.structures??[]).map(({structureId:F})=>F),w=(M??[]).concat(U??[]).filter(F=>!b.includes(F));if(w.length)return _({result:{error:Lt},context:{invalidStructureIds:w}});y=y??{};for(let F of b)U.includes(F)?y[F]={published:!1}:y[F]={published:!0};I[A].structureDetails=y}let O=(i.drawDefinitions?.find(b=>b.drawId===A)?.structures??[]).map(({stage:b})=>b);if(C.length){for(let b of C)E[b]={published:!0};for(let b of O)E[b]||(E[b]={published:!1})}if(C.length||N.length){for(let b of N)E[b]={published:!1};for(let b of O)E[b]||(E[b]={published:!0})}(C.length||N.length)&&(I[A].stageDetails=E)}Xs({statusObject:{drawDetails:I},removePriorValues:r,status:o,event:i});let{topics:h}=Cr(),S=h.includes(th),T=S||t.returnEventData?Gd({includePositionAssignments:e,usePublishState:!0,tournamentRecord:n,policyDefinitions:u,event:i})?.eventData:void 0;return S&&Tt({payload:{eventData:T,tournamentId:n.tournamentId},topic:th}),{...R,eventData:T}}var aN="deleteDrawDefinitions",cN="autoSchedulingAudit",XT="deleteEvents",Iv={AUTO_SCHEDULING_AUDIT:cN,DELETE_EVENTS:XT,DELETE_DRAW_DEFINITIONS:aN};function Bp(t){if(!t.tournamentRecord)return{error:W};let e="deleteDrawDefinitions",r=t.drawIds??[],n=t.event,{autoPublish:o=!0,tournamentRecord:i,auditData:s,eventId:a,force:c}=t,{appliedPolicies:u}=Pt({tournamentRecord:i,event:n}),p={...u,...t.policyDefinitions},m=Array.isArray(r)?r[0]:void 0;if(!n){let U=We({tournamentRecord:i,eventId:a,drawId:m});if(U.error)return U;n=U.event}let d=[],l=[],f=[];if(!n?.drawDefinitions)return _({info:"event has no drawDefinition",result:{...R},stack:e});let g=n.drawDefinitions.map(({drawId:U})=>U);if(r.length||(r=g),r=r.filter(U=>g.includes(U)),!r.length)return _({info:"nothing to do; no matching drawIds in event.",result:{...R},stack:e});let I=J(Ht({event:n}).flightProfile,!1,!0),h=({participantId:U,drawPosition:M,qualifier:P,bye:N})=>({bye:N,qualifier:P,drawPosition:M,participantId:U}),S=c??u?.[vn]?.allowDeletionWithScoresPresent?.drawDefinitions,T=vr({event:n})??{},A=T.drawIds??(T.drawDetails&&Object.keys(T.drawDetails))??[],D,y=[],E=n.drawDefinitions.filter(U=>{if(r.includes(U.drawId)){let M=rr({event:n,drawDefinition:U})?.matchUps??[];if(M.some(({score:H})=>Ie({score:H}))&&!S)return y.push(U.drawId),!0;let{drawId:N,drawType:C,drawName:O}=U,b=I?.flights?.find(H=>H.drawId===U.drawId);b&&(b.drawEntries=b.drawEntries?.filter(H=>Or.includes(H.entryStatus))),A.includes(N)&&(A=A.filter(H=>H!==N),D=!0);let x=xn({stageSequence:1,drawDefinition:U,stage:tt})?.structures?.[0],F=(x?Cp({structureId:x.structureId,tournamentRecord:i,drawDefinition:U}):void 0)?.positionAssignments?.map(h),L=xn({stage:at,drawDefinition:U})?.structures,v=L?.length?L.map(H=>{let j=H.stageSequence;return{positionAssignments:Cp({structureId:H.structureId,tournamentRecord:i,drawDefinition:U})?.positionAssignments.map(h),stageSequence:j}}):void 0,B={action:aN,payload:{drawDefinitions:[U],eventId:a??n?.eventId,auditData:s}};f.push(B),d.push(rt({tournamentId:i.tournamentId,eventId:a??n?.eventId,qualifyingPositionAssignments:v,positionAssignments:F,auditData:s,drawType:C,drawName:O,drawId:N})),M?.forEach(({matchUpId:H})=>l.push(H))}return!r.includes(U.drawId)});if(y.length&&!c)return _({context:{drawIdsWithScoresPresent:y},result:{error:Ku},stack:e});if(n.drawDefinitions=E,I&&Io({event:n,extension:{name:qr,value:I}}),Nc({tournamentRecord:i}),D){let U={};for(let P of A)U[P]=T.drawDetails?.[P]??{published:!0};let M=Xs({statusObject:{drawDetails:U},event:n});if(M.error)return{error:M.error}}if(f.length&&Tt({topic:fa,payload:f}),l.length&&wn({tournamentId:i?.tournamentId,matchUpIds:l}),r.forEach(U=>{ER({drawId:U})}),hV({event:n,deletedDrawsDetail:d,auditData:s}),o&&D){let U=Js({drawIdsToRemove:r,policyDefinitions:p,tournamentRecord:i,event:n});if(U.error)return{...R,info:U.error}}return{...R}}function hV({event:t,deletedDrawsDetail:e,auditData:r}){let{extension:n}=mt({name:Em,element:t}),o={...r,deletedDrawsDetail:e},i={name:Em,value:Array.isArray(n?.value)?n?.value.concat(o):[o]};St({element:t,extension:i})}function uN({autoPublish:t=!0,tournamentRecord:e,auditData:r,event:n,force:o}){if(!e)return{error:W};if(!n)return{error:Et};let{flightProfile:i}=Ht({event:n});if(i){let s=i.flights?.map(({drawId:c})=>c).filter(Boolean),a=Bp({eventId:n.eventId,tournamentRecord:e,autoPublish:t,auditData:r,drawIds:s,event:n,force:o});return a.error?a:rp({event:n,name:qr})}return{...R}}function Ng(t){let{matchUpFormat:e,recoveryTimes:r,averageTimes:n,tournamentId:o,eventId:i}=t,s=t?.tournamentRecords??(t?.tournamentRecord&&{[t.tournamentRecord.tournamentId]:t.tournamentRecord})??{};if(!Object.keys(s).length)return{error:Ft};let a=Object.keys(s).filter(u=>!o||o===u);if(o&&!a.includes(o))return{error:G};let c;for(let u of a){let p=s[u],{event:m}=We({tournamentRecord:p,eventId:i});i&&m&&(c=!0);let d=SV({tournamentRecord:p,event:m,matchUpFormat:e,averageTimes:n,recoveryTimes:r});if(d.error)return d}return!i||c?{...R}:{error:mr}}function SV({tournamentRecord:t,recoveryTimes:e,matchUpFormat:r,averageTimes:n,event:o}){if(!t)return{error:W};if(n&&!Array.isArray(n))return{error:G};if(e&&!Array.isArray(e))return{error:G};let i=Oo;if(o){let{extension:s}=mt({element:o,name:i}),a=s?.value||{},c=hv({...a,matchUpFormat:r,averageTimes:n,recoveryTimes:e});St({element:o,extension:{name:i,value:c}})}else{let{extension:s}=mt({element:t,name:i}),a=s?.value||{},c=hv({...a,matchUpFormat:r,averageTimes:n,recoveryTimes:e});St({extension:{name:i,value:c},element:t})}return{...R}}function hv(t){let{matchUpRecoveryTimes:e=[],matchUpAverageTimes:r=[],matchUpFormat:n}=t,{averageTimes:o,recoveryTimes:i}=t;o=(o||[]).filter(c=>c?.categoryNames?.length||c?.categoryTypes?.length);let s=o?.length&&r.map(c=>c?.matchUpFormatCodes.includes(n)?{...c,matchUpFormatCodes:c.matchUpFormatCodes?.filter(u=>u!==n)}:c).filter(({matchUpFormatCodes:c})=>c?.length).concat({matchUpFormatCodes:[n],averageTimes:o});i=(i||[]).filter(c=>c?.categoryNames?.length||c?.categoryTypes?.length);let a=i?.length&&e.map(c=>c?.matchUpFormatCodes.includes(n)?{...c,matchUpFormatCodes:c.matchUpFormatCodes?.filter(u=>u!==n)}:c).filter(({matchUpFormatCodes:c,averageTimes:u})=>c?.length||u).concat({matchUpFormatCodes:[n],recoveryTimes:i});return{matchUpAverageTimes:s?.length&&s||r,matchUpRecoveryTimes:a?.length&&a||e}}function pN(t){let{tournamentRecord:e,recoveryMinutes:r,averageMinutes:n,matchUpFormat:o,categoryType:i,eventId:s,event:a}=t;if(!e)return{error:W};if(!Sr({matchUpFormat:o}))return{error:G};if(!a)return{error:Et};let{averageTimes:c=[],recoveryTimes:u=[]}=Bd({tournamentRecord:e,matchUpFormat:o,event:a}),p=a.category,m=p?.categoryName||p?.ageCategoryCode||a?.eventId,d={categoryNames:[m],minutes:{}},l={categoryNames:[m],minutes:{}},f=T=>{if(T.categoryTypes?.includes(i)&&console.log("encountered:",{categoryType:i}),!(T.categoryNames?.includes(m)&&(T.categoryNames=T.categoryNames.filter(A=>A!==m),d={minutes:T.minutes,categoryNames:[m]},!T.categoryNames.length)))return T},g=n&&!isNaN(ct(n)),I=r&&!isNaN(ct(r)),h=c.map(f).filter(T=>T?.categoryNames?.length),S=u.map(f).filter(T=>T?.categoryNames?.length);return g&&(Object.assign(d.minutes,{[a?.eventType||Xt]:n}),h.push(d)),I&&(Object.assign(l.minutes,{[a?.eventType||Xt]:r}),S.push(l)),!g&&!I?{error:G}:Ng({averageTimes:g&&h,recoveryTimes:I&&S,tournamentRecord:e,matchUpFormat:o,eventId:s,event:a})}function qd(t){if(t.event)return Sv({event:t.event});{t.tournamentRecord&&!t.tournamentRecords&&(t.tournamentRecords={[t.tournamentRecord.tournamentId]:t.tournamentRecord});let e=lt(t,[{[ye]:!0,[bI]:!0}]);if(e.error)return e;let{tournamentRecords:r,eventId:n}=t;for(let o of Object.values(r??{})){let{event:i}=We({tournamentRecord:o,eventId:n});if(i)return Sv({event:i})}}return{error:mr}}function Sv({event:t}){return rp({event:t,name:Oo})}function JT({tournamentRecord:t,event:e,startDate:r}){if(!t)return{error:W};if(!e)return{error:Et};if(!Ro.test(r))return{error:ar};let n=Tv(t);if(n.error)return n;let{tournamentStartDate:o,tournamentEndDate:i}=n,s=new Date(Ut(r)).getTime();if(!o||!i||s<o||s>i)return{error:ar};let a=e.endDate&&new Date(Ut(e.endDate)).getTime();return a&&s>a&&(e.endDate=r),e.startDate=r,{...R}}function ZT({tournamentRecord:t,event:e,endDate:r}){if(!t)return{error:W};if(!e)return{error:Et};if(!Ro.test(r))return{error:ar};let n=Tv(t);if(n.error)return n;let{tournamentStartDate:o,tournamentEndDate:i}=n,s=new Date(Ut(r)).getTime();if(!o||!i||s<o||s>i)return{error:ar};let a=e.startDate&&new Date(Ut(e.startDate)).getTime();return a&&s<a&&(e.startDate=r),e.endDate=r,{...R}}function mN({tournamentRecord:t,event:e,startDate:r,endDate:n}){if(!t)return{error:W};if(!e)return{error:Et};if(!r&&!n)return{error:et,info:"missing date"};if(r&&!Ro.test(r))return{error:ar};if(n&&!Ro.test(n))return{error:ar};if(r&&n){let o=new Date(Ut(r)).getTime(),i=new Date(Ut(n)).getTime();if(o>i)return{error:G}}if(r){let o=JT({tournamentRecord:t,event:e,startDate:r});if(o.error)return o}if(n){let o=ZT({tournamentRecord:t,event:e,endDate:n});if(o.error)return o}return{...R}}function Tv(t){let{startDate:e,endDate:r}=t;return!Ro.test(e)||!Ro.test(r)?_({result:{error:Ny},context:{startDate:e,endDate:r}}):{tournamentStartDate:new Date(Ut(e)).getTime(),tournamentEndDate:new Date(Ut(r)).getTime()}}function Mg({event:t,orderedDrawIdsMap:e}){if(typeof t!="object")return{error:Et};if(!e)return{error:et,info:"Missing drawIdsOrderMap"};if(typeof e!="object")return{error:G,info:"orderedDrawIdsMap must be an object"};let r=Object.values(e);if(!r.every(i=>!isNaN(i)))return{error:G,info:"drawOrder must be numeric"};if(pt(r).length!==r.length)return{error:G,info:"drawOrder values must be unique"};if(t.drawDefinitions?.length){let i=(t.drawDefinitions||[]).map(({drawId:a})=>a),s=Object.keys(e);if(s?.length&&jt(i,s).length!==i.length)return{error:G,info:"Missing drawIds"};t.drawDefinitions.forEach(a=>{a.drawOrder=e[a.drawId]})}let{flightProfile:o}=Ht({event:t});return o?.flights?.forEach(i=>{i.flightNumber=e[i.drawId]}),{...R}}function Cg({tournamentRecord:t,event:e}){if(!t)return{error:W};if(!e)return{error:Et};let{flightProfile:r}=Ht({event:e}),n=r?.flights&&Object.assign({},...r.flights.sort((o,i)=>o.flightNumber-i.flightNumber).map((o,i)=>({[o.drawId]:i+1})))||e.drawDefinitions?.length&&Object.assign({},...e.drawDefinitions.sort((o,i)=>o.drawOrder-i.drawOrder).map((o,i)=>({[o.drawId]:i+1})))||void 0;return n?Mg({event:e,orderedDrawIdsMap:n}):{...R}}function dN({autoPublish:t=!0,tournamentRecord:e,auditData:r,drawId:n,event:o,force:i}){if(!e)return{error:W};if(!n)return{error:Wr};if(!o)return{error:Et};let{flightProfile:s}=Ht({event:o});if(s&&s.flights?.find(u=>u.drawId===n)){let u=s.flights.filter(m=>m.drawId!==n),p={name:qr,value:{...s,flights:u}};Io({event:o,extension:p})}if(o.drawDefinitions?.find(c=>c.drawId===n)){let c=Bp({drawIds:[n],eventId:o.eventId,tournamentRecord:e,autoPublish:t,auditData:r,event:o,force:i});if(c.error)return c}return Cg({tournamentRecord:e,event:o})}function lN({replacementIndividualParticipantId:t,existingIndividualParticipantId:e,tournamentRecord:r,drawDefinition:n,participantId:o,event:i,uuids:s}){if(!i)return{error:Et};if(i?.eventType!==Kr)return{error:No};if(s&&!Array.isArray(s))return{error:G};if(!r)return{error:W};if(![t,e,o].every(g=>typeof g=="string"))return{error:oe};if(!(i?.entries?.filter(({entryStatus:g})=>[Lr,pi].includes(g)).map(({participantId:g})=>g)||[]).includes(t))return{error:pn};let c=(r.participants||[]).find(g=>g.participantId===o);if(c?.participantType!==dt)return{error:Us,participant:c};let u=c.individualParticipantIds,p=[t,...u.filter(g=>g!==e)],{participant:m}=tn({participantIds:p,tournamentRecord:r}),d;if(m)d=m.participantId;else{let g={participantId:s?.pop(),participantRole:Ge,individualParticipantIds:p,participantType:dt},I=gn({participant:g,returnParticipant:!0,tournamentRecord:r});if(I.error)return I;d=I.participant.participantId}let{flightProfile:l}=Ht({event:i});if(n){let g=l?.flights?.find(({drawId:I})=>I===n.drawId);g&&(g.drawEntries=g.drawEntries.map(I=>I.participantId===o?{...I,participantId:d}:I)),n.entries=n.entries.map(I=>I.participantId===o?{...I,participantId:d}:I);for(let I of n.structures||[])if(I.positionAssignments)I.positionAssignments=I.positionAssignments.map(h=>h.participantId===o?{...h,participantId:d}:h);else if(I.structures)for(let h of I.structures)h.positionAssignments=h.positionAssignments.map(S=>S.participantId===o?{...S,participantId:d}:S)}i.entries=i.entries.map(g=>g.participantId===o&&{...g,participantId:d}||g.participantId===t&&{...g,participantId:e}||g);let f=r.events.some(({entries:g,eventId:I,drawDefinitions:h})=>i.eventId===I?h.some(({drawId:S,entries:T})=>S===n?.drawId?!1:T?.find(A=>A.participantId===o)):g?.find(S=>S.participantId===o));if(!f){let g=Li({addIndividualParticipantsToEvents:!1,participantIds:[o],tournamentRecord:r});if(g.error)return g}return{...R,participantOtherEntries:f,newPairParticipantId:d}}function Hp(t){let{flight:e,suppressNotifications:r,modifyEventEntries:n,existingDrawCount:o,allowReplacement:i,checkEntryStatus:s,tournamentRecord:a,drawDefinition:c,event:u}=t;if(!c)return{error:X};if(!u)return{error:Et};u.drawDefinitions||(u.drawDefinitions=[]);let{drawId:p,drawName:m,entries:d}=c,{entries:l}=u,f=0;if(o!==void 0&&o!==u.drawDefinitions.length)return{error:G,info:"drawDefintions count mismatch"};let{flightProfile:g}=Ht({event:u}),I=e&&g?.flights?.find(b=>b.flightNumber===e.flightNumber),h=g?.links?.find(b=>b?.target?.drawId===p)?.source?.drawId;if(h&&!u.drawDefinitions.find(b=>b.drawId===h))return _({result:{error:X},info:{sourceDrawId:h}});if(I&&I.drawId!==c.drawId)return _({result:{error:na},info:{relevantFlight:I}});let A=d?.every(({participantId:b,entryStatus:x})=>{let w=I?.drawEntries.find(F=>F.participantId===b);return!x||w?.entryStatus===x}),D=!s||l&&d?.every(({participantId:b,entryStatus:x,entryStage:w})=>l.find(L=>L.participantId===b&&(!L.entryStage||L.entryStage===w))?.entryStatus===x);if(I&&!A)return _({result:{error:na},context:{drawEntriesPresentInFlight:A,matchingEventEntries:D,relevantFlight:I},info:"Draw entries are not present in flight or do not match entryStatuses"});if(n&&d?.filter(Boolean).forEach(b=>{if(b?.entryStatus&&Or.includes(b?.entryStatus)){let x=l?.filter(Boolean).find(w=>w.participantId===b.participantId);x&&b.entryStatus&&x?.entryStatus!==b.entryStatus&&(x.entryStatus=b.entryStatus,f+=1)}}),l&&!D)return _({result:{info:"Draw entries do not match event entryStatuses",context:{matchingEventEntries:D,eventEntries:l},error:na}});let y=g?.flights?.map(({flightNumber:b})=>!isNaN(b)&&ct(b))?.filter(Boolean)||[],E=u.drawDefinitions.map(({drawOrder:b})=>b&&ct(b))?.filter(Boolean)||[],U=Math.max(0,...E,...y)+1,M=g?.flights?.find(b=>b.drawId===p),P;if(M){M.drawName=c.drawName,P={name:qr,value:{...g,flights:g.flights}};let b=M.flightNumber;b&&!E.includes(b)?U=b:M.flightNumber=U}else{let b=g?.flights||[];b.push({manuallyAdded:!0,flightNumber:U,drawEntries:d,drawName:m,drawId:p}),P={name:qr,value:{...g||{},flights:b}}}Io({event:u,extension:P}),Object.assign(c,{drawOrder:U});let N=u.drawDefinitions.find(b=>b.drawId===p),C=a?.tournamentId,O=u.eventId;if(N){if(!i)return{error:oy};let x=rr({drawDefinition:N})?.matchUps?.map(fe)??[],w=rr({drawDefinition:c})?.matchUps;if(!r){x?.length&&wn({matchUpIds:x,action:"modifyDrawDefinition",tournamentId:C,eventId:O}),w?.length&&So({matchUps:w,tournamentId:C,eventId:O}),u.drawDefinitions=u.drawDefinitions.map(L=>L.drawId===p?c:L);let F=c.structures?.map(({structureId:L})=>L);bt({drawDefinition:c,tournamentId:C,structureIds:F,eventId:O})}}else if(u.drawDefinitions.push(c),!r){let{matchUps:b}=rr({drawDefinition:c,event:u});b&&So({tournamentId:a?.tournamentId,matchUps:b}),ga({drawDefinition:c,tournamentId:C,eventId:O})}return{...R,modifiedEventEntryStatusCount:f}}function fN(t){let{provisionalPositioning:e,useExistingSeedLimit:r,tournamentRecord:n,drawDefinition:o,seedingProfile:i,structureId:s,assignments:a,drawId:c,event:u}=t,p=0;if(!a?.length)return{error:hl};if(!n)return{error:W};if(!c)return{error:Wr};let m=Fr({provisionalPositioning:e,drawDefinition:o,structureId:s});if(m.error)return m;let{seedAssignments:d,seedLimit:l}=m,f=Object.assign({},...(d??[]).filter(h=>h.seedNumber).map(h=>({[h.seedNumber]:h})));a.forEach(h=>{let{seedNumber:S}=h;l&&S<=l&&(!r||f[S])&&(f[S]=h)});let g=Object.values(f),I=g.map(h=>h?.participantId).filter(Boolean);if(I.length!==EI(I).length)return{error:iy};for(let h of g){let S=Ws({...h,provisionalPositioning:e,tournamentRecord:n,drawDefinition:o,seedingProfile:i,structureId:s,event:u});if(S?.error)return S;S?.success&&p++}return p?{...R,modifications:p}:{error:Ns}}function Rg({deleteExisting:t,event:e,flightProfile:r}){let n="attachFlightProfile";if(!r)return _({result:{error:et},stack:n});if(!e)return _({result:{error:Et},stack:n});let{flightProfile:o}=Ht({event:e});return o&&!t?_({result:{error:Ll},stack:n}):e.drawDefinitions?.length?_({result:{error:ey},stack:n}):(Io({event:e,extension:{name:qr,value:r}}),{flightProfile:J(r,!1,!0),...R})}function Av({tournamentRecord:t,scaleAttributes:e,participantIds:r}){if(!t)return{error:W};if(!r)return{error:lo};if(!e)return{error:et,info:"scaleAttributes required"};let{scaleType:n,eventType:o,scaleName:i}=e,s=[JE,n,o,i].join(".");return t.participants?.forEach(a=>{r.includes(a.participantId)&&a.timeItems&&(a.timeItems=a.timeItems.filter(c=>c&&c?.itemType!==s))}),{...R}}function bg({tournamentRecord:t,scaleAttributes:e,drawDefinition:r,entryStatuses:n,drawId:o,event:i,stage:s}){if(!i)return{error:Et};if(n&&!Array.isArray(n))return _({result:{error:G},info:Nn("entryStatus"),stack:"removeScaleValues"});let a=i.entries;if(o){let{flightProfile:p}=Ht({event:i}),m=p?.flights?.find(d=>d.drawId===o);m?a=m.drawEntries:a=r?.entries}let u=(a||[]).filter(p=>(!s||!p.entryStage||p.entryStage===s)&&(!n||n.includes(p.entryStatus))).map(gt);return Av({tournamentRecord:t,scaleAttributes:e,participantIds:u})}function $d({removePriorValues:t,tournamentRecord:e,displaySettings:r,status:n=Gr,event:o}){if(!e)return _({result:{error:W}});if(!o)return _({result:{error:Et}});if(!Rt(r))return _({result:{error:et}});if(Rt(r.draws))for(let s of Object.keys(r.draws)){let a=r.draws[s].scheduleDetails??[];if(a.length){let c=[];for(let u of a){let p=c.find(m=>CC(m.attributes,u.attributes));p?.dates&&u.dates?p.dates.push(...u.dates):c.push(u)}r.draws[s].scheduleDetails=c}}let i=Xs({statusObject:{displaySettings:r},removePriorValues:t,status:n,event:o});return i.error?i:{...R}}function gN({tournamentRecord:t,drawDefinition:e,entryStatuses:r,scaleName:n,drawId:o,event:i,stage:s}){if(!t)return{error:W};if(!i)return{error:Et};n=n||i.category?.categoryName||i.category?.ageCategoryCode;let a={eventType:i.eventType,scaleType:eo,scaleName:n};return bg({tournamentRecord:t,scaleAttributes:a,drawDefinition:e,entryStatuses:r,drawId:o,event:i,stage:s})}function IN({removePairParticipants:t,tournamentRecord:e,eventIds:r}){if(!e)return{error:W};if(!e.events)return{error:mr};if(!Array.isArray(r))return{error:et,info:Nn("drawIds")};let n=[],o=[],i=[],s=[];if(e.events=(e.events||[]).filter(a=>{if(r.includes(a.eventId)){let p={action:XT,payload:{events:[a]}};n.push(p),o.push({tournamentId:e.tournamentId,eventName:a.eventName,eventType:a.eventType,category:a.category,eventId:a.eventId,gender:a.gender})}let c=a.eventType===Kr?(a.entries||[]).map(({entryStatus:p,participantId:m})=>p!==Lr&&m).filter(Boolean):[],u=r.includes(a.eventId);return u?s.push(...c):i.push(...c),!u}),t){let a=s.filter(c=>!i.includes(c));e.participants=e.participants.filter(({participantId:c})=>!a.includes(c))}return Nc({tournamentRecord:e}),n.length&&(Tt({topic:fa,payload:n}),Gi({tournamentRecord:e,timeItem:{itemType:XT,itemValue:o}})),{...R}}function hN({tournamentRecord:t,eventUpdates:e,eventId:r,event:n}){let o="modifyEvent";if(!t)return _({result:{error:W},stack:o});if(!$e(r))return _({result:{error:Et},context:{eventId:r},stack:o});if(!Rt(e))return _({result:{error:G},context:{eventUpdates:e},stack:o});let i=n?.entries?.filter(({entryStatus:l})=>{let f=l;return[...Or,wr].includes(f)}).map(({participantId:l})=>l)??[],s=i?Yt({participantFilters:{participantIds:i},withIndividualParticipants:!0,tournamentRecord:t}).participants??[]:[],a=[],c=s.reduce((l,f)=>{let g=f.person?.sex?[f.person.sex]:f.individualParticpants?.map(I=>I.person?.sex)||[];return a.push(...g),l.includes(f.participantType)?l:l.concat(f.participantType)},[]),u=pt(a),p=!u.length||[_r,Fn].includes(e.gender??"")||u.length===1&&u[0]===e.gender;if(e.gender&&!p)return _({context:{gender:e.gender,validGender:p},result:{error:G},stack:o});let d=(c.includes(Fe)&&[Fe]||c.includes(ht)&&[ao]||c.includes(dt)&&[Kr]||[Kr,ao,Fe]).includes(e.eventType??"");return e.eventType&&!d?_({context:{participantType:e.eventType,validEventType:d},result:{error:G},stack:o}):(e.eventType&&(n.eventType=e.eventType),e.eventName&&(n.eventName=e.eventName),e.gender&&(n.gender=e.gender),{...R})}function Wp({qualifyingPositions:t,drawEntries:e=[],drawName:r,drawId:n,event:o,stage:i}){let s="addFlight";if(!o)return _({result:{error:Et},stack:s});if(!r)return _({result:{error:et},stack:s});if(e?.length){let g=(o.entries??[]).map(gt),I=e.map(gt);if(jt(I,g).length!==I.length)return _({result:{error:G},stack:s})}let a=Ht({event:o})?.flightProfile,c=a?.flights?.map(({flightNumber:g})=>!isNaN(g)&&ct(g))?.filter(Boolean)||[],u=Math.max(0,...c)+1,m={drawId:n||Mt(),flightNumber:u,drawEntries:e,drawName:r};if(i&&(m.stage=i),t&&(m.qualifyingPositions=t),(a?.flights||[]).find(({drawId:g})=>g===m.drawId))return _({result:{error:tE},stack:s});let l=(a?.flights||[]).concat(m),f={name:qr,value:{...a||{},flights:l}};return Io({event:o,extension:f})}var yv={collectionDefinitions:[{collectionName:"Doubles",matchUpCount:3,matchUpFormat:"SET1-S:8/TB7@7",matchUpType:"DOUBLES",matchUpValue:1},{collectionName:"Singles",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7",matchUpType:"SINGLES",matchUpValue:1}],tieFormatName:"COLLEGE_D3",winCriteria:{valueGoal:5}};var Ev={collectionDefinitions:[{collectionName:"Doubles",collectionValue:1,matchUpCount:3,matchUpFormat:"SET1-S:6/TB7",matchUpType:"DOUBLES"},{collectionName:"Singles",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7",matchUpType:"SINGLES",matchUpValue:1}],tieFormatName:"COLLEGE_DEFAULT",winCriteria:{valueGoal:5}};var Uv={collectionDefinitions:[{collectionName:"Doubles",matchUpCount:3,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1},{collectionName:"Singles",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7",matchUpType:"SINGLES",matchUpValue:1}],tieFormatName:"COLLEGE_JUCO",winCriteria:{valueGoal:5}};var tA={COLLEGE_D3:yv,COLLEGE_DEFAULT:Ev,COLLEGE_JUCO:Uv,DOMINANT_DUO:oT,DOMINANT_DUO_MIXED:tT,LAVER_CUP:uT,TEAM_DOUBLES_3_AGGREGATION:zS,TIME_TENNIS_DUAL:eT,TIME_TENNIS_PRO_CIRCUIT:ZS,USTA_BREWER_CUP:rT,USTA_OZAKI_CUP:nT,USTA_COLLEGE:iT,USTA_GOLD_TEAM_CHALLENGE:KS,USTA_INTERSECTIONAL:JS,USTA_LEVEL_1:sT,USTA_SECTION_BATTLE:XS,USTA_SOUTHERN_LEVEL_5:QS,USTA_TOC:pT,USTA_WTT_ITT:aT,USTA_ZONAL:cT};function Mc({suppressNotifications:t,tournamentRecord:e,internalUse:r,event:n}){if(!e)return{error:W};if(e.events||(e.events=[]),!n)return{error:Et};let{startDate:o,endDate:i}=e;if(!r&&(n.entries?.length||n.drawDefinitions?.length)){let c=rt({drawDefinitions:!!n.drawDefinitions?.length,entries:!!n.entries?.length});return{info:"entries/drawDefinitions cannot exist",error:G,context:c}}let s={eventType:Fs,drawDefinitions:[],entries:[],startDate:o,endDate:i,...n};if(n.eventType===kr){if(n.tieFormat){let c=ir({tieFormat:n.tieFormat});if(c.error)return c}else if(n.tieFormatName){if(!tA[n.tieFormatName])return{context:{tieFormatName:n.tieFormatName},error:G};let c=Bi({isMock:e?.isMock,namedFormat:n.tieFormatName,event:n});s.tieFormat=c}}if(s.eventId||(s.eventId=Mt()),e.events.reduce((c,u)=>c||u.eventId===s.eventId,void 0))return{error:fy};{let c=s;if(e.events.push(c),!t){let{topics:u}=Cr();if(u.includes(cp)){let p=co({event:n}).matchUps??[];So({tournamentId:e?.tournamentId,eventId:n.eventId,matchUps:p})}for(let p of n.drawDefinitions||[])ga({drawDefinition:p})}return{...R,event:s}}}var PN={};Jt(PN,{drawMatic:()=>Od,garman:()=>UN,generateAdHocMatchUps:()=>Nu,generateAdHocRounds:()=>bd,generateAndPopulatePlayoffStructures:()=>ld,generateCourts:()=>Og,generateDrawDefinition:()=>_u,generateDrawMaticRound:()=>Ed,generateDrawStructuresAndLinks:()=>Td,generateDrawTypeAndModifyDrawDefinition:()=>Ad,generateFlightProfile:()=>Dv,generateLineUps:()=>rA,generateQualifyingStructure:()=>id,generateSeedingScaleItems:()=>KT,generateVoluntaryConsolation:()=>LS,roundRobinGroups:()=>Mb});var EV="splitLevelBased",AN="splitWaterfall",yN="splitShuttle",Pv={SPLIT_LEVEL_BASED:EV,SPLIT_WATERFALL:AN,SPLIT_SHUTTLE:yN};function Dv(t){let{drawNameRoot:e="Flight",attachFlightProfile:r,tournamentRecord:n,scaleAttributes:o,scaleSortMethod:i,deleteExisting:s,sortDescending:a,drawNames:c=[],flightsCount:u,splitMethod:p,uuids:m=[],event:d,stage:l}=t;if(!d)return{error:Et};let f=d.entries??[],{flightProfile:g}=Ht({event:d});if(g&&r&&!s)return{error:Ll};let I=t.scaledEntries??Qs({tournamentRecord:n,scaleAttributes:o,scaleSortMethod:i,sortDescending:a,event:d,stage:l}).scaledEntries,h=I.map(gt),S=cr(f.filter(({participantId:P})=>!h.includes(P)).filter(P=>(!l||!P.entryStage||P.entryStage===l)&&(!P.entryStatus||qo.includes(P.entryStatus)))),T=I.concat(...S),A=T.length,D=Math.ceil(A/u),y=Te(T,D);p===AN?y=Gl(T,u):p===yN&&(y=Gl(T,u,!0));function E(P){return(P||[]).map(({participantId:N,scaleValue:C})=>{let O=f.find(b=>b.participantId===N);return O?.scaleValue&&C&&(O.scaleValue=C),O}).sort((N,C)=>N.scaleValue-C.scaleValue).map((N,C)=>(N.scaleValue&&(N.seedNumber=C+1),N))}let U=Z(0,u).map(P=>{let N=P+1;return{flightNumber:N,drawId:m?.pop()??Mt(),drawEntries:E(y[P]),drawName:c?.length&&c[P]||`${e} ${N}`}}),M={scaleAttributes:o,splitMethod:p,flights:U};if(r){let P=Rg({flightProfile:M,deleteExisting:s,event:d});return{splitEntries:yr()&&y||void 0,...P}}else return{flightProfile:M,...R}}var UV="ASC",EN="ASC",PV="DESC",eA="DESC",Nv={ASC:UV,ASCENDING:EN,DESC:PV,DESCENDING:eA};function rA(t){let{tieFormat:e}=t,{useDefaultEventRanking:r,tournamentRecord:n,drawDefinition:o,scaleAccessor:i,singlesOnly:s,attach:a,event:c}=t;if(c?.eventType!==kr)return{error:No};if(!n)return{error:W};if(!e&&!o)return{error:pr};if(e=e??je({drawDefinition:o,event:c})?.tieFormat,ir({tieFormat:e}).error)return{error:ni};if(typeof i!="object"&&!r)return{error:G,context:{scaleAccessor:i}};let u={},m=(o?.entries??c?.entries??[]).filter(C=>C?.entryStatus===Zr).map(gt),{participants:d=[]}=Yt({withIndividualParticipants:!0,withScaleValues:!0,tournamentRecord:n}),l=d.filter(({participantId:C})=>m.includes(C)),f=C=>C===oi?"rankings":"ratings",g=c?.category?.categoryName??c?.category?.ageCategoryCode,{scaleName:I=g,scaleType:h=oi,sortOrder:S,accessor:T}=i||{},A=f(h),D=(C,O)=>{let b=C[A]?.[O];if(!b&&r&&(b=C[A]?.[Ia]),Array.isArray(b)){let x=b.find(w=>w.scaleName===I)?.scaleValue;if(te(x))return x;if(T&&typeof x=="object")return x[T]}return 0},y=(C,O,b)=>{let x=S===eA?O:C,w=S===eA?C:O;return D(x,b)-D(w,b)},E=(C,O)=>y(C,O,Ia),U=(C,O)=>y(C,O,vi),M=[],P=e?.collectionDefinitions??[];for(let C of l){let O=C.individualParticipants?.sort(E)??[],b=s?O:C.individualParticipants?.sort(U)??[],x={};for(let F of P){let L=[],{collectionId:v,matchUpCount:B,matchUpType:H,gender:j}=F,V=ie(Ia)(H);Z(0,B).forEach(Y=>{let $=V?O:b??[],k=Y+1,K=[];Z(0,V?1:2).forEach(z=>{let q=$?.find(nt=>{let Q=j&&([ee,ue].includes(j)&&j||j===_r&&[ee,ue][z]);return(!Q||Q===nt.person?.sex)&&!L.includes(nt.participantId)})?.participantId;q&&(K.push(q),L.push(q),x[q]||(x[q]=[]),x[q].push({collectionPosition:k,collectionId:v}))}),V||M.push(K)})}let w=Object.keys(x).map(F=>({collectionAssignments:x[F],participantId:F}));u[C.participantId]=w}let N=[];for(let C of M){let{participant:O}=tn({tournamentParticipants:d,participantIds:C});if(!O){let b={individualParticipantIds:C,participantRole:Ge,participantType:dt};N.push(b)}}if(a){for(;N.length;)gn({participant:N.pop(),tournamentRecord:n});St({element:o,extension:{name:ho,value:u}})}return{...R,lineUps:u,participantsToAdd:N}}function Og(t){if(!t)return{error:et};let e=lt(t,[{dates:!1,[yn]:s=>Array.isArray(s)&&s.every(Rr)},{uuids:!1,[yn]:s=>Array.isArray(s)&&s.every($e)},{startTime:!1,endTime:!1,[yn]:FI},{idPrefix:!1,namePrefix:!1,[yn]:$e},{count:!0,[yn]:te}]);if(e.error)return e;let{startDate:r,endDate:n}=t.tournamentRecord??{},o=t.dates||r&&n&&bs(r,n)||[],i=Z(1,t.count+1).map(s=>rt({courtId:t.uuids?.pop()??(t.idPrefix&&`${t.idPrefix}-${s}`)??Mt(),courtName:t.courtNames?.pop()??(t.namePrefix&&`${t.namePrefix} ${s}`),dateAvailability:o.map(a=>({startTime:t.startTime??"08:00",endTime:t.endTime??"20:00",date:a}))}));return{...R,courts:i}}var UN={};Jt(UN,{default:()=>DV,garman:()=>Rv});function wa({court:t,date:e}){let r=e&&t.dateAvailability.find(o=>_n(o.date,e)),n=t.dateAvailability.find(o=>!o.date);return r||n}function hs(t){let e=lt(t,[{courtDate:!0,_ofType:Ri}]);if(e.error)return e;let{includeBookingTypes:r=[],courtDate:n}=t,o=[],i=we(n.startTime);(n.bookings||[]).filter(a=>!a.bookingType||!r.includes(a.bookingType)).sort((a,c)=>Kl(a.startTime).localeCompare(Kl(c.startTime))).forEach(a=>{let c={startTime:$t(i.toISOString()),endTime:a.startTime};we(a.startTime)>i&&o.push(c),we(a.endTime)>i&&(i=we(a.endTime))});let s={startTime:$t(i.toISOString()),endTime:n.endTime};return we(n.endTime)>i&&o.push(s),{timeSlots:o}}function Mv({averageMatchUpMinutes:t,includeBookingTypes:e,periodStartTime:r,periodEndTime:n}){let o=s=>{let{timeSlots:a}=hs({includeBookingTypes:e,courtDate:s});return!!a?.filter(i)?.length};function i(s){let a=we(s.startTime),c=we(s.endTime);return a>r||c<n?!1:ca(r,c)>=t}return{enoughTime:o}}function nA(t){let e=lt(t,[{periodStart:!0,date:!0},{courts:!0,_ofType:Er}]);if(e.error)return e;let{averageMatchUpMinutes:r,includeBookingTypes:n,periodStart:o,date:i}=t,s=t.courts,a=we(o),c=Ql(a,r),{enoughTime:u}=Mv({averageMatchUpMinutes:r,includeBookingTypes:n,periodStartTime:a,periodEndTime:c});return{availableToScheduleCount:(s?.filter(m=>{if(!Array.isArray(m.dateAvailability))return!1;let d=wa({date:i,court:m});return!!(d&&u(d))})||[]).length,...R}}function jp(t){let{remainingScheduleTimes:e=[],clearScheduleDates:r,periodLength:n=30,scheduleDate:o,courts:i=[]}=t,{bookings:s=[]}=t;if(!Array.isArray(i)||!i.length)return{error:G,courts:i};if(!Array.isArray(s))return{error:om};if(!Rr(o))return{error:ar};r&&(Array.isArray(r)?r.includes(o)&&(s=[]):s=[]);let{courtBookings:a,unassignedBookings:c}=s.reduce((l,f)=>{let{courtId:g}=f;return g?l.courtBookings[g]?l.courtBookings[g].push(f):l.courtBookings[g]=[f]:l.unassignedBookings.push(f),l},{courtBookings:{},unassignedBookings:[]}),u=i.map((l,f)=>{let{courtId:g,courtName:I}=l,h=a[g]||[],S=wa({date:o,court:l})||{},{bookings:T=[],startTime:A,endTime:D,date:y}=S,U=[e[f]&&{startTime:A,endTime:e[f]},...J(T,!1,!0),...h].filter(Boolean);return{courtId:g,courtName:I,dateAvailability:{bookings:U,startTime:A,endTime:D,date:y}}});c.sort((l,f)=>Vt(l.startTime)-Vt(f.startTime));let p=()=>u.map(l=>{let f=l.dateAvailability,{timeSlots:g=[]}=hs({courtDate:f});return{courtName:l.courtName,courtId:l.courtId,timeSlots:g}}).flat(),m=[];for(let l of c){let{startTime:f,endTime:g,averageMinutes:I,recoveryMinutes:h,matchUpId:S}=l,T=Vt(f),A=Vt(g),y=p().reduce((E,{courtId:U,courtName:M,timeSlots:P})=>{let N;return P.find(({startTime:O,endTime:b})=>{N=Vt(O)-T;let x=T>=Vt(O);return A<=Vt(b)&&E.startDifference!==0&&((N===0||N+n>=0)&&(E.startDifference===void 0||N<E.startDifference)||x)})?{courtName:M,courtId:U,startDifference:N}:E},{});if(y.courtId){let E={averageMinutes:I,recoveryMinutes:h,matchUpId:S,startTime:f,endTime:g};m.push(E),u.find(({courtId:M})=>M===y.courtId)?.dateAvailability.bookings.push(E)}else console.log({unassignedBooking:l})}return{virtualCourts:u.map(({courtId:l,courtName:f,dateAvailability:g})=>({dateAvailability:[g],courtName:f,courtId:l})),assignedBookings:m}}function vu({averageMatchUpMinutes:t,periodLength:e=30,recoveryMinutes:r}){let n=(t||90)+(r||0);return e>n?n:e||30}function oA(t){let{startTime:e="8:00",endTime:r="20:30",count:n=10,date:o}=t??{};return Z(0,n).map(()=>({dateAvailability:[{date:o,startTime:e,endTime:r}]}))}function Cc({scheduleDate:t,startTime:e,endTime:r,courts:n}){let o=e&&"startTime"||r&&"endTime"||void 0;return n.reduce((i,s)=>{let a=wa({date:t,court:s}),c=o&&(a?.[o]||s[o]);return c&&(!i||e&&Vt(c)<Vt(i)||r&&Vt(c)>Vt(i))?c:i},void 0)}function Cv({averageMinutes:t,startTime:e,endTime:r,courts:n,date:o}){e=e||Cc({courts:n,scheduleDate:o,startTime:!0}),r=r||Cc({courts:n,scheduleDate:o,endTime:!0});let i;if(e&&r){let s=we(e),a=we(r);for(let c of n||[]){if(!Array.isArray(c.dateAvailability))continue;let u=wa({court:c,date:o}),{timeSlots:p}=hs({courtDate:u});p?.forEach(m=>{let d=we(m.startTime),l=we(m.endTime);if(d>a||d<s||l<s)return!1;if(ca(d,l)>=t){let I=$t(d.toISOString());(!i||I<i)&&(i=I)}})}}return{firstTimeSlotStartTime:i}}function Kd(t){let e=lt(t,[{courts:!0,_ofType:Er}]);if(e.error)return e;let{date:r=zl(),startTime:n="08:00",endTime:o="19:00",periodLength:i,courts:s}=t,{calculateStartTimeFromCourts:a=!0,remainingScheduleTimes:c,averageMatchUpMinutes:u,clearScheduleDates:p,courtsCount:m,bookings:d}=t;i=i||vu({averageMatchUpMinutes:u}),r=Ut(r),n=$t(n),o=$t(o);let l=0,f=0,g=0,I=0,h=0;!s&&m&&(s=oA({startTime:n,endTime:o,count:m,date:r}));let{virtualCourts:S}=jp({remainingScheduleTimes:c,clearScheduleDates:p,scheduleDate:r,periodLength:i,bookings:d,courts:s}),{firstTimeSlotStartTime:T}=Cv({averageMinutes:u,courts:S,startTime:n,endTime:o,date:r});a&&T&&(n=T||n);let A=Vt(n),y=Vt(o)-A,E=Math.floor(y/i),M=Z(0,E+1).map(N=>{let C=A+N*i,O=uR(C),b=nA({courts:S??[],averageMatchUpMinutes:u,periodStart:O,date:r});if(b.error)return{error:b.error};let{availableToScheduleCount:x=0}=b,w=x>f?x-f:0;h+=N?x:0;let F=N?h/N:x,v=i*F/u,B=N?v*(N-1)+F:F,H=x?f&&B-l||w:0;l=B,f=x,g+=H;let j=ct(g)-I;return I+=j,{periodStart:O,add:j,availableToScheduleCount:x,newCourts:w,totalMatchUps:I}});return{scheduleTimes:M.reduce((N,C)=>{let b=Z(0,C.add).map(()=>({scheduleTime:C.periodStart}));return N.concat(...b)},[]).flat(),timingProfile:M,totalMatchUps:I}}var Rv={getCourtsAvailableAtPeriodStart:nA,generateTimeSlots:hs,getScheduleTimes:Kd,courtGenerator:oA},DV=Rv;var iA={};Jt(iA,{isValid:()=>Sr,isValidMatchUpFormat:()=>Sr,parse:()=>tr,stringify:()=>Pp});var jN={};Jt(jN,{allCompetitionMatchUps:()=>cn,allDrawMatchUps:()=>rr,allEventMatchUps:()=>co,allTournamentMatchUps:()=>le,analyzeMatchUp:()=>Vp,applyLineUps:()=>HN,assignMatchUpSideParticipant:()=>DN,assignTieMatchUpParticipantId:()=>Xd,bulkMatchUpStatusUpdate:()=>GN,calculateWinCriteria:()=>Is,checkInParticipant:()=>vg,checkMatchUpIsComplete:()=>is,checkOutParticipant:()=>_g,competitionScheduleMatchUps:()=>Ou,disableTieAutoCalc:()=>LN,drawMatchUps:()=>WT,enableTieAutoCalc:()=>vN,eventMatchUps:()=>Wd,findMatchUp:()=>Ug,getAllDrawMatchUps:()=>re,getAllStructureMatchUps:()=>At,getCheckedInParticipantIds:()=>es,getCompetitionMatchUps:()=>kp,getEventMatchUpFormatTiming:()=>wT,getMatchUpCompetitiveProfile:()=>su,getMatchUpContextIds:()=>kT,getMatchUpDailyLimits:()=>Yd,getMatchUpDailyLimitsUpdate:()=>LT,getMatchUpDependencies:()=>Vr,getMatchUpFormat:()=>VT,getMatchUpFormatTiming:()=>au,getMatchUpFormatTimingUpdate:()=>vT,getMatchUpScheduleDetails:()=>Wm,getMatchUpType:()=>qm,getMatchUpsStats:()=>BT,getModifiedMatchUpFormatTiming:()=>Bd,getParticipantResults:()=>Su,getPredictiveAccuracy:()=>GT,getRoundMatchUps:()=>He,getRounds:()=>HT,isValidMatchUpFormat:()=>Sr,matchUpActions:()=>hd,mutate:()=>WN,participantScheduledMatchUps:()=>FT,query:()=>KD,removeDelegatedOutcome:()=>xN,removeMatchUpSideParticipant:()=>wg,removeTieMatchUpParticipantId:()=>MN,replaceTieMatchUpParticipantId:()=>xg,resetAdHocMatchUps:()=>VN,resetMatchUpLineUps:()=>Lg,resetScorecard:()=>Gg,resetTieFormat:()=>Fg,setDelegatedOutcome:()=>kN,setMatchUpFormat:()=>FN,setMatchUpStatus:()=>xu,setOrderOfFinish:()=>BN,substituteParticipant:()=>wN,tallyParticipantResults:()=>Ca,toggleParticipantCheckInState:()=>zd,tournamentMatchUps:()=>jd,updateTieMatchUpScore:()=>zn,validMatchUp:()=>yf,validMatchUps:()=>Ur});var WN={};Jt(WN,{applyLineUps:()=>HN,assignMatchUpSideParticipant:()=>DN,assignTieMatchUpParticipantId:()=>Xd,bulkMatchUpStatusUpdate:()=>GN,checkInParticipant:()=>vg,checkOutParticipant:()=>_g,disableTieAutoCalc:()=>LN,enableTieAutoCalc:()=>vN,findMatchUp:()=>Ug,removeDelegatedOutcome:()=>xN,removeMatchUpSideParticipant:()=>wg,removeTieMatchUpParticipantId:()=>MN,replaceTieMatchUpParticipantId:()=>xg,resetAdHocMatchUps:()=>VN,resetMatchUpLineUps:()=>Lg,resetScorecard:()=>Gg,resetTieFormat:()=>Fg,setDelegatedOutcome:()=>kN,setMatchUpFormat:()=>FN,setMatchUpStatus:()=>xu,setOrderOfFinish:()=>BN,substituteParticipant:()=>wN,toggleParticipantCheckInState:()=>zd,updateTieMatchUpScore:()=>zn});function DN({tournamentRecord:t,drawDefinition:e,participantId:r,sideNumber:n,matchUpId:o,event:i}){if(r&&typeof r!="string")return{error:pn};if(!e)return{error:X};if(!o)return{error:ke};let s=n===void 0;if(s&&(n=1),![1,2].includes(n))return _({result:{error:G,context:{sideNumber:n}}});let{matchUp:a,structure:c}=xt({drawDefinition:e,matchUpId:o,event:i});if(!a)return{error:Oe};if(!(!c?.structures&&!(e.drawType&&e.drawType!==an)&&!c?.matchUps?.find(({roundPosition:p})=>!!p)))return{error:nm};if(!r&&(a?.score?.scoreStringSide1||ae.includes(a?.matchUpstatus)||a?.matchUpStatus&&[ge,Ne].includes(a.matchUpStatus)))return{error:Hu,info:"matchUp has completed status or score"};if(a){if(a.sides=[1,2].map(p=>{let m=a.sides?.find(d=>d.sideNumber===p)??{sideNumber:p};return n===p?{...m,participantId:r}:m}),s)for(let p of a.sides)p.sideNumber&&(p.sideNumber=3-p.sideNumber);It({tournamentId:t?.tournamentId,context:"assignSideParticipant",drawDefinition:e,matchUp:a})}return{...R,sidesSwapped:s}}function rn({removePriorValues:t,tournamentRecord:e,duplicateValues:r,drawDefinition:n,disableNotice:o,matchUpId:i,timeItem:s,event:a}){let{matchUp:c}=xt({drawDefinition:n,event:a,matchUpId:i});if(!c)return{error:Oe};let u=Ti({removePriorValues:t,element:c,duplicateValues:r,timeItem:s});return o||It({tournamentId:e?.tournamentId,eventId:a?.eventId,context:"addTimeItem",drawDefinition:n,matchUp:c}),u}function _g(t){let e=[{[An]:!0},{[Yr]:!0},{[Bn]:!0},{[Co]:!0}],r=lt(t,e);if(r.error)return r;let n=xa(t,[{[sa]:fo,attr:{[lm]:!0}}]);if(n.error)return n;let{tournamentRecord:o,drawDefinition:i,participantId:s,matchUpId:a}=t,c=n?.matchUp?.matchUp,{matchUpStatus:u,score:p}=c??{};if(u&&Nm.includes(u)||u&&ae.includes(u)||Ie({score:p}))return{error:cy};let m=es({matchUp:c});if(m?.error)return m;let{checkedInParticipantIds:d,allRelevantParticipantIds:l}=m??{};if(!l?.includes(s))return{error:pn};if(!d?.includes(s))return{error:xy};let f=ch({matchUp:c});if(f?.error)return f;let{sideParticipantIds:g,nestedIndividualParticipantIds:I}=f??{},h=g?.indexOf(s);return h!==void 0&&[0,1].includes(h)&&(I?.[h]??[]).forEach(T=>{rn({drawDefinition:i,matchUpId:a,timeItem:{itemType:Bm,itemValue:T}})}),rn({tournamentRecord:o,drawDefinition:i,matchUpId:a,timeItem:{itemValue:s,itemType:Bm}}),{...R,checkedOut:!0}}function vg(t){let e=[{[An]:!0},{[Yr]:!0},{[Bn]:!0},{[Co]:!0}],r=lt(t,e);if(r[Ms])return r;let n=xa(t,[{[sa]:fo,attr:{[lm]:!0}}]);if(n[Ms])return n;let{tournamentRecord:o,drawDefinition:i,participantId:s,matchUpId:a}=t,c=es({matchUp:n?.matchUp?.matchUp});if(c?.error)return c;let{checkedInParticipantIds:u,allRelevantParticipantIds:p}=c??{};if(!p?.includes(s))return{[Ms]:pn};let m={...R,checkedIn:!0};return u?.includes(s)||rn({tournamentRecord:o,drawDefinition:i,matchUpId:a,timeItem:{itemValue:s,itemType:Vm}}),m}function zd(t){let e=lt(t,[{[Bn]:!0,[Yr]:!0,[Co]:!0}]);if(e.error)return e;let r=t.tournamentId??t.activeTournamentId,n=t.tournamentRecord??(r&&t.tournamentRecords?.[r]);if(!n)return{error:W};let i=xa(t,[{[sa]:fo,attr:{[lm]:!0},[Ms]:Oe}]).matchUp?.matchUp;if(!i)return{error:Oe};let{checkedInParticipantIds:s=[]}=es({matchUp:i}),{participantId:a,matchUpId:c,drawDefinition:u}=t;return a&&s.includes(a)?_g({tournamentRecord:n,drawDefinition:u,participantId:a,matchUpId:c,matchUp:i}):vg({tournamentRecord:n,drawDefinition:u,participantId:a,matchUpId:c,matchUp:i})}function Qd({tournamentRecord:t,drawDefinition:e,tieMatchUpId:r,event:n}){if(!t)return{error:W};if(!e)return{error:Wr};if(!n)return{error:mr};let o=Ae({drawDefinition:e}),{matchUp:i}=xt({matchUpId:r,drawDefinition:e,matchUpsMap:o});if(!i)return{error:Oe};let{matchUp:s,structure:a}=xt({tournamentParticipants:t.participants,matchUpId:r,inContext:!0,drawDefinition:e,matchUpsMap:o,event:n});if(!s)return{error:Oe};let{collectionPosition:c,drawPositions:u,collectionId:p,matchUpTieId:m,matchUpType:d}=s;if(d&&!cu([Xt,Gt],d))return{error:Je};let{positionAssignments:l}=Nt({structure:a}),f=l?.filter(y=>u?.includes(y.drawPosition)),{matchUp:g}=xt({matchUpId:m,drawDefinition:e,matchUpsMap:o}),I=g?.sides?.map(gt)??[],h=f?.map(gt)??[],S=[...I,...h],{participants:T}=Yt({tournamentRecord:t,participantFilters:{participantTypes:[kt],participantIds:S}}),{matchUp:A}=xt({matchUpId:m,inContext:!0,drawDefinition:e,matchUpsMap:o}),D=je({matchUp:g,drawDefinition:e,structure:a,event:n})?.tieFormat;return{inContextDualMatchUp:A,inContextTieMatchUp:s,relevantAssignments:f,collectionPosition:c,teamParticipants:T,collectionId:p,matchUpType:d,dualMatchUp:g,tieMatchUp:i,tieFormat:D,structure:a,...R}}function xg(t){let e=Qd(t);if(e.error)return e;let r="replaceTieMatchUpParticipantid",{existingParticipantId:n,tournamentRecord:o,newParticipantId:i,drawDefinition:s,substitution:a,event:c}=t;if(!n||!i)return _({result:{error:oe},stack:r});if(n===i)return{...R};let{inContextDualMatchUp:u,inContextTieMatchUp:p,collectionPosition:m,collectionId:d,dualMatchUp:l,tieMatchUp:f,tieFormat:g}=e,I=p?.matchUpType,h=p?.sides?.find(B=>B.participant?.participantId===n||B.participant?.individualParticipantIds?.includes(n));if(!h)return{error:Zt};let S=Yt({tournamentRecord:o,participantFilters:{participantIds:[n,i]}})?.participants??[];if(S.length!==2)return _({result:{error:oe},stack:r});if(S[0].participantType!==S[1].participantType)return _({result:{error:nn},stack:r});let{appliedPolicies:T}=Pt({tournamentRecord:o,drawDefinition:s,event:c}),A=t.policyDefinitions?.[ze]??T?.[ze]??us[ze],D=S.find(({participantId:B})=>B===i);if((t.enforceGender??A?.participants?.enforceGender)!==!1&&[ee,ue].includes(p?.gender)&&p?.gender!==D?.person?.sex)return{error:Us,info:"Gender mismatch"};let E=A?.processCodes?.substitution;Ra({tournamentId:o.tournamentId,eventId:c.eventId,inContextDualMatchUp:u,drawDefinition:s,dualMatchUp:l});let U=l?.sides?.find(({sideNumber:B})=>B===h.sideNumber);if(!U)return _({result:{sideNumber:h.sideNumber,existingParticipantId:n,error:Ke},stack:r});if(p?.sides?.flatMap(B=>B.participant?.individualParticipantIds||B.participant?.participantId||[])?.includes(i))return _({result:{error:Wu},stack:r});let P=u?.sides?.find(({sideNumber:B})=>B===h.sideNumber)?.participantId,N=U.lineUp,C=N?.find(({participantId:B})=>i===B),O=N?.reduce((B,H)=>H.substitutionOrder>B?H.substitutionOrder:B,0),b=N?.map(B=>{let H=J(B,!1,!0);if(![n,i].includes(H.participantId))return H;if(!a&&[n,i].includes(H.participantId)&&(H.collectionAssignments=H.collectionAssignments?.filter(j=>!(j.collectionPosition===m&&j.collectionId===d))),a&&n===H.participantId&&(H.collectionAssignments=H.collectionAssignments.map(j=>j.collectionPosition===m&&j.collectionId===d&&j.substitutionOrder===void 0?{...j,substitutionOrder:O}:j)),H.participantId===i){H.collectionAssignments||(H.collectionAssignments=[]);let j={collectionId:d,collectionPosition:m};a&&(j.previousParticipantId=n,j.substitutionOrder=(O??0)+1),H.collectionAssignments.push(j)}return H})??[];if(!C){let B={collectionId:d,collectionPosition:m};a&&(B.substitutionOrder=(O??0)+1,B.previousParticipantId=n);let H={collectionAssignments:[B],participantId:i};b.push(H)}let x=I===Gt,{assignedParticipantIds:w}=gp({lineUp:N,collectionPosition:m,collectionId:d}),{assignedParticipantIds:F}=gp({lineUp:b,collectionPosition:m,collectionId:d});if(U.lineUp=b,P&&g){let B=Fi({participantId:P,lineUp:b,drawDefinition:s,tieFormat:g});if(B.error)return _({result:B,stack:r})}else console.log("team participantId not found");let L,v;if(x){let{tournamentRecord:B}=t,H=tn({participantIds:F,tournamentRecord:B});if(!H.participant){let Y=gn({returnParticipant:!0,pairOverride:!0,tournamentRecord:B,participant:{participantRole:Ge,individualParticipantIds:F,participantType:dt}});if(Y.error)return _({result:Y,stack:r});L=Y.participant?.participantId}H=tn({participantIds:w,tournamentRecord:B});let j=H.participant?.participantId;j&&Li({participantIds:[j],tournamentRecord:B}).success&&(v=j)}if(a||h.substitutions?.length===1){if(a)E&&f&&(f.processCodes=pt([...f?.processCodes??[],...E]));else for(let B of E||[]){let H=f?.processCodes?.lastIndexOf(B);H!==void 0&&f?.processCodes?.splice(H,1)}f&&It({tournamentId:o?.tournamentId,matchUp:f,context:r,drawDefinition:s})}return l&&It({tournamentId:o?.tournamentId,matchUp:l,context:r,drawDefinition:s}),{...R,modifiedLineUp:b,participantRemoved:v,participantAdded:L}}function sA({collectionPosition:t,teamParticipantId:e,dualMatchUpSide:r,drawDefinition:n,participantIds:o,collectionId:i}){if(!i||!t||!Array.isArray(o))return{modifiedLineUp:r?.lineUp||[],error:G};let s=r?.lineUp||os({participantId:e,drawDefinition:n})?.lineUp,a=[],c=[];return{modifiedLineUp:s?.map(p=>{if(!o.includes(p.participantId))return p;let m=p.collectionAssignments?.filter(d=>{let l=d.collectionId===i&&d.collectionPosition===t;return l&&(d.previousParticipantId&&a.push(d.previousParticipantId),c.push({participantId:p.participantId,...d})),!l});return{participantId:p.participantId,collectionAssignments:m}}).filter(Boolean)||[],assignmentsRemoved:c,previousParticipantIds:a}}function bv({individualParticipantIds:t,groupingParticipantId:e,tournamentRecord:r}){let n=(r.events||[]).filter(i=>i?.eventType===Fe&&i?.entries?.some(s=>s.participantId===e)),o=i=>!t.includes(i.participantId);for(let i of n){i.entries=(i.entries||[]).filter(o);let{flightProfile:s}=Ht({event:i});s?.flights?.forEach(a=>{a.drawEntries=(a.drawEntries||[]).filter(o)}),i?.drawDefinitions?.forEach(a=>{a.entries=(a.entries||[]).filter(o)})}return{...R}}function Yp({individualParticipantIds:t,groupingParticipantId:e,removeFromOtherTeams:r,tournamentRecord:n}){let o="addIndividualParticipantIds";if(!n)return _({result:{error:W},stack:o});if(!e||!t)return _({result:{error:et},stack:o});let i=n.participants??[],s=i.find(m=>m.participantId===e);if(!s)return _({result:{error:Zt},stack:o});if(s?.participantType&&![kt,Ar].includes(s.participantType))return _({context:{participantType:s.participantType},result:{error:nn},stack:o});let a=t.filter(m=>i.find(l=>l.participantId===m)?.participantType!==ht);if(a.length)return _({result:{error:zr,invalidParticipantIds:a},stack:o});s.individualParticipantIds||(s.individualParticipantIds=[]);let c=s.individualParticipantIds,u=t.filter(m=>!c.includes(m));u.length&&(r&&hp({individualParticipantIds:u,tournamentRecord:n}),s.individualParticipantIds=s.individualParticipantIds.concat(...u));let{topics:p}=Cr();if(p.includes(Qe)){let m=i.find(({participantId:d})=>d===e);Tt({topic:Qe,payload:{participants:[m]}})}return bv({individualParticipantIds:t,groupingParticipantId:e,tournamentRecord:n}),{groupingParticipant:J(s,!1,!0),added:u.length,...R}}function qp(t){let{updateParticipantName:e=!0,groupingParticipantId:r,removeFromOtherTeams:n,tournamentRecord:o,pairOverride:i,participant:s}=t;if(!o)return{error:W};if(!s)return{error:Mi};if(!s.participantId)return gn({tournamentRecord:o,participant:s});let{participant:a}=xo({participantId:s.participantId,tournamentRecord:o});if(!a)return gn({tournamentRecord:o,participant:s});let{participantRoleResponsibilties:c,individualParticipantIds:u,participantOtherName:p,participantName:m,participantRole:d,participantType:l,onlineResources:f,contacts:g,person:I}=s;if(l&&a.participantType!==l)return{error:Cy};let h={};if(g&&(h.contacts=g),f&&(h.onlineResources=f),m&&typeof m=="string"&&(h.participantName=m),p&&typeof p=="string"&&(h.participantOtherName=p),Array.isArray(u)){let{participants:S}=Yt({participantFilters:{participantTypes:[ht]},tournamentRecord:o}),T=S?.map(gt);if(T){let A=u.filter(D=>typeof D=="string"&&T.includes(D));([Ar,Bt].includes(l||a.participantType)||l===dt&&(A.length===2||i))&&(h.individualParticipantIds=A),a.participantType===nu.PAIR&&e&&(h.participantName=NV({individualParticipants:S,newValues:h}))}}return Object.keys(Xm).includes(d)&&(h.participantRole=d),Object.keys(nu).includes(l)&&(h.participantType=l),Array.isArray(c)&&(h.participantRoleResponsibilties=c),a.participantType===nu.INDIVIDUAL&&I&&MV({updateParticipantName:e,existingParticipant:a,newValues:h,person:I}),Object.assign(a,rt(h)),r&&Yp({individualParticipantIds:[a.participantId],groupingParticipantId:r,removeFromOtherTeams:n,tournamentRecord:o}),Tt({topic:Qe,payload:{tournamentId:o.tournamentId,participants:[a]}}),{participant:J(a),...R}}function NV({individualParticipants:t,newValues:e}){let r=e.individualParticipantIds,n=t.filter(({participantId:o})=>r.includes(o)).map(({person:o})=>o?.standardFamilyName).filter(Boolean).sort().join("/");return r.length===1&&(n+="/Unknown"),n}function MV({updateParticipantName:t,existingParticipant:e,newValues:r,person:n}){let o={},{standardFamilyName:i,standardGivenName:s,nationalityCode:a,personId:c,sex:u}=n;u&&Object.keys(Km).includes(u)&&(o.sex=u);let p;if(c&&typeof c=="string"&&(o.personId=c),a&&typeof a=="string"&&(CV(a)||a==="")&&(o.nationalityCode=a),i&&typeof i=="string"&&i.length>1&&(o.standardFamilyName=i,p=!0),s&&typeof s=="string"&&s.length>1&&(o.standardGivenName=s,p=!0),p&&t){let m=`${o.standardGivenName} ${o.standardFamilyName}`;r.participantName=m}Object.assign(e.person,o)}function CV(t){return Xo.flatMap(({iso:e,ioc:r})=>[e,r]).filter(Boolean).includes(t)}function Xd(t){let e=Qd(t);if(e.error)return e;let r="assignTieMatchUpParticipantId",n=t.teamParticipantId,{tournamentRecord:o,drawDefinition:i,participantId:s,event:a}=t;if(!s)return _({result:{error:oe},stack:r});if(t.sideNumber&&![1,2].includes(t.sideNumber))return _({result:{error:yl},stack:r});let{inContextDualMatchUp:c,inContextTieMatchUp:u,relevantAssignments:p,collectionPosition:m,teamParticipants:d,collectionId:l,matchUpType:f,dualMatchUp:g,tieFormat:I}=e;if(u?.sides?.flatMap(k=>k.participant?.individualParticipantIds||k.participant?.participantId||[])?.includes(s))return _({result:{...R},stack:r});n=n??(t.sideNumber?c?.sides?.find(k=>k.sideNumber===t.sideNumber)?.participantId:void 0);let S=Yt({participantFilters:{participantIds:[s]},tournamentRecord:o})?.participants?.[0];if(!S)return _({result:{error:Zt},stack:r});let{appliedPolicies:T}=Pt({tournamentRecord:o,drawDefinition:i,event:a}),A=t.policyDefinitions?.[ze]??T?.[ze]??us[ze];if((t.enforceGender??A?.participants?.enforceGender)!==!1&&[ee,ue].includes(u?.gender)&&u?.gender!==S.person?.sex)return{error:Us,info:"Gender mismatch"};let{individualParticipantIds:y,participantType:E}=S;if(ie(Xt)(f)&&E!==ht)return{error:nn};let U=E===ht?[s]:y,M=n&&d?.find(({participantId:k})=>k===n)||d?.find(({individualParticipantIds:k})=>xe(U,k));if(!M)return{error:xl};if(n||(n=M.participantId),!n)return{error:Zt};let N=p?.find(k=>k.participantId===M?.participantId)?.drawPosition,C=g?.sides?.find(k=>k.participantId===n)?.sideNumber,O=u?.sides?.find(k=>N&&k.drawPosition===N)?.sideNumber,b=C??O??t.sideNumber;if(!I)return{error:qa};if(!I.collectionDefinitions?.find(k=>k.collectionId===l))return{error:Ay};Ra({tournamentId:o.tournamentId,eventId:a.eventId,inContextDualMatchUp:c,drawDefinition:i,dualMatchUp:g});let w=g?.sides?.find(k=>k.sideNumber===b),F=u?.sides?.find(k=>k.sideNumber===b),B=(w?.lineUp??os({participantId:n,drawDefinition:i})?.lineUp)?.filter(k=>k.collectionAssignments?.find(K=>K.collectionPosition===m&&K.collectionId===l&&!K.previousParticipantId))?.map(k=>k?.participantId),H=B?.length>1&&B||(E===dt?S.individualParticipantIds:[s]),j=sA({collectionPosition:m,teamParticipantId:n,dualMatchUpSide:w,drawDefinition:i,participantIds:H,collectionId:l});if(j.error)return _({result:j,stack:r});let{modifiedLineUp:V}=j,Y;if(f===Gt){if(E!==dt){let k=NN({collectionPosition:m,teamParticipantId:n,drawDefinition:i,modifiedLineUp:V,participantId:s,collectionId:l,tieFormat:I});if(k?.error)return _({result:k,stack:r});if(k=$({side:F}),k.error)return k;Y=k.deletedParticipantId,w&&(w.lineUp=V),g&&It({tournamentId:o?.tournamentId,matchUp:g,context:r,drawDefinition:i})}else if(E===dt)for(let k of H)NN({collectionPosition:m,teamParticipantId:n,drawDefinition:i,modifiedLineUp:V,participantId:k,collectionId:l,tieFormat:I})}else{let k=NN({collectionPosition:m,teamParticipantId:n,drawDefinition:i,modifiedLineUp:V,participantId:s,collectionId:l,tieFormat:I});if(k?.error)return k}if(w&&(w.lineUp=V),g&&It({tournamentId:o?.tournamentId,matchUp:g,context:r,drawDefinition:i}),Y){let{error:k}=Li({participantIds:[Y],tournamentRecord:o});k&&console.log("cleanup")}return{...R,modifiedLineUp:V};function $({side:k}){let K;if(k.participant){let z=k.participant.individualParticipantIds||[];if(z.filter(Boolean).length===1){let{participant:nt}=tn({participantIds:z,tournamentRecord:o});z.push(s);let{participant:Q}=tn({participantIds:z,tournamentRecord:o});if(!Q&&nt){nt.individualParticipantIds=z;let it=qp({pairOverride:!0,tournamentRecord:o,participant:nt});if(it.error)return it}else K=nt?.participantId}}else{let q=gn({participant:{individualParticipantIds:[s],participantRole:Ge,participantType:dt},pairOverride:!0,tournamentRecord:o});if(q.error)return q}return{...R,deletedParticipantId:K}}}function NN({collectionPosition:t,teamParticipantId:e,drawDefinition:r,modifiedLineUp:n,participantId:o,collectionId:i,tieFormat:s}){let a=os({participantId:e,drawDefinition:r})?.lineUp,c=(n||a)?.find(p=>p?.participantId===o),u={collectionId:i,collectionPosition:t};if(c)c.collectionAssignments.push(u);else{let p={collectionAssignments:[u],participantId:o};n.push(p)}return Fi({participantId:e,lineUp:n,drawDefinition:r,tieFormat:s})}function MN(t){let{tournamentRecord:e,drawDefinition:r,participantId:n,event:o}=t,i="removeTieMatchUpParticiapantId";if(!n)return _({result:{error:oe},stack:i});let s=Qd(t);if(s.error)return s;let{appliedPolicies:a}=Pt({tournamentRecord:e,drawDefinition:r,event:o}),u=(t.policyDefinitions?.[ze]??a?.[ze]??us[ze])?.processCodes?.substitution,{inContextDualMatchUp:p,inContextTieMatchUp:m,relevantAssignments:d,collectionPosition:l,teamParticipants:f,collectionId:g,matchUpType:I,dualMatchUp:h,tieMatchUp:S,tieFormat:T}=s;if(!h)return _({result:{error:sr},stack:i});let A=m?.sides?.find(N=>N.participant?.participantId===n||N.participant?.individualParticipantIds?.includes(n));if(!A)return _({result:{error:Zt},stack:i});if(!A.substitutions?.length&&(Ie({score:m?.score})||m?.winningSide))return _({result:{error:eE},stack:i});let D=p?.sides?.find(({sideNumber:N})=>N===A.sideNumber)?.participantId;if(!D)return _({result:{error:Zt},stack:i});let y=Yt({participantFilters:{participantIds:[n]},tournamentRecord:e})?.participants?.[0];if(!y)return _({result:{error:Zt},stack:i});if(I===Xt&&y.participantType===dt)return _({result:{error:Us},stack:i});let E=y.participantType===ht?[n]:y.individualParticipantIds;Ra({tournamentId:e.tournamentId,eventId:o.eventId,inContextDualMatchUp:p,drawDefinition:r,dualMatchUp:h});let U=h.sides?.find(({sideNumber:N})=>N===A.sideNumber);if(!U&&(h.sides?.filter(({lineUp:N})=>!N).length||0)<2){let N=f?.map(({participantId:C})=>({drawPosition:d?.find(O=>O.participantId===C)?.drawPosition,teamParticipantId:C}));U=h.sides?.find(C=>N?.find(({drawPosition:O})=>O===C.drawPosition)?.teamParticipantId===D)}if(!U)return _({result:{error:Zt,context:{participantId:n}}});let{modifiedLineUp:M,previousParticipantIds:P}=sA({collectionPosition:l,teamParticipantId:D,dualMatchUpSide:U,participantIds:E,drawDefinition:r,collectionId:g});if(U.lineUp=M,D&&T&&Fi({participantId:D,lineUp:M,drawDefinition:r,tieFormat:T}),I===Gt&&y.participantType===ht){let N=m?.sides?.find(b=>b.sideNumber===U?.sideNumber),{participantId:C}=N??{},O=C&&Yt({participantFilters:{participantIds:[C]},tournamentRecord:e,withDraws:!0})?.participants?.[0];if(O){let b=O?.individualParticipantIds?.filter(x=>x!==n)??[];if(P&&b.push(...P),b.length>2)return _({result:{error:zr},stack:i});if(O.draws?.length){if(b.length===1){let{participant:x}=tn({participantIds:b,tournamentRecord:e});if(!x){let F=gn({participant:{participantRole:Ge,individualParticipantIds:b,participantType:dt},pairOverride:!0,tournamentRecord:e});if(F.error)return _({result:F,stack:i})}}}else if(b.length){O.individualParticipantIds=b;let x=qp({participant:O,pairOverride:!0,tournamentRecord:e});if(x.error)return _({result:x,stack:i})}else{let x=Li({participantIds:[C],tournamentRecord:e});x.error&&console.log("cleanup",{result:x})}}else return _({result:{error:Zt},stack:i})}if(A.substitutions?.length===1&&!m?.sides?.find(C=>C.sideNumber!==A.sideNumber)?.substitutions?.length&&S?.processCodes?.length){for(let C of u||[]){let O=S.processCodes.lastIndexOf(C);S.processCodes.splice(O,1)}It({tournamentId:e?.tournamentId,matchUp:S,context:i,drawDefinition:r})}return It({tournamentId:e?.tournamentId,matchUp:h,context:i,drawDefinition:r}),{...R,modifiedLineUp:M}}function wg(t){let e=lt(t,[{[An]:!0,[Yr]:!0,[Co]:!0}]);if(e.error)return e;let{drawDefinition:r,sideNumber:n,matchUpId:o,event:i}=t;if(n&&![1,2].includes(n))return{error:G,sideNumber:n};let{matchUp:s,structure:a}=xt({drawDefinition:r,matchUpId:o,event:i});return s?fr({structure:a})?(s.sides?.forEach(c=>{(!n||c.sideNumber===n)&&delete c.participantId}),It({tournamentId:t.tournamentRecord?.tournamentId,context:"assignSideParticipant",drawDefinition:r,matchUp:s}),{...R}):{error:nm}:{error:Oe}}function Ov({drawDefinition:t,matchUpStatus:e,matchUpsMap:r,winningSide:n,dualMatchUp:o,tieFormat:i,structure:s,matchUp:a,event:c,score:u}){let p=J(o,void 0,!0);for(let d of p?.tieMatchUps||[])d.matchUpId===a.matchUpId&&(d.winningSide=n,d.score=u,!Ie({score:u})&&!e?Object.assign(d,{...Tu}):e&&(d.matchUpStatus=e));i=i??je({matchUp:a,structure:s,drawDefinition:t,event:c})?.tieFormat;let{winningSide:m}=Uc({matchUp:p,drawDefinition:t,matchUpsMap:r,structure:s,tieFormat:i,event:c});return{projectedWinningSide:m}}function _v({matchUpStatuses:t=[Dt,_t,Ot],drawPositionMatchUps:e,loserDrawPosition:r,sourceMatchUps:n}){let o=e?.reduce((p,m)=>!p||m.roundNumber>p.roundNumber?m:p,void 0),i=o?.drawPositions?.find(p=>p!==r),s=n.filter(p=>p?.drawPositions?.includes(i)).map(p=>p.matchUpStatus),a=n.filter(p=>p?.drawPositions?.includes(r)).map(p=>p.matchUpStatus),c=xe(s||[],t),u=xe(a||[],t);return{sourceMatchUp:o,winnerHadMatchUpStatus:c,winnerMatchUpStatuses:s,loserHadMatchUpStatus:u,loserMatchUpStatuses:a}}function vv({inContextDrawMatchUps:t,sourceMatchUpStatus:e,targetDrawPosition:r,tournamentRecord:n,sourceMatchUpId:o,drawDefinition:i,structureId:s,dualMatchUp:a,roundNumber:c,matchUpsMap:u,event:p}){let{structure:m}=st({drawDefinition:i,structureId:s});if(m?.structureType===Le)return{...R};u=u??Ae({drawDefinition:i});let l=(u?.mappedMatchUps||{})[s].matchUps,{initialRoundNumber:f}=ss({drawPosition:r,matchUps:l}),g=l?.filter(h=>h.roundNumber>=c&&h.roundNumber!==f&&h.drawPositions?.includes(r)),{positionAssignments:I}=Nt({drawDefinition:i,structureId:s});for(let h of g??[])RV({inContextDrawMatchUps:t,sourceMatchUpStatus:e,positionAssignments:I,targetDrawPosition:r,tournamentRecord:n,sourceMatchUpId:o,drawDefinition:i,dualMatchUp:a,matchUpsMap:u,matchUp:h,event:p});return{...R}}function RV({inContextDrawMatchUps:t,positionAssignments:e,sourceMatchUpStatus:r,targetDrawPosition:n,tournamentRecord:o,sourceMatchUpId:i,drawDefinition:s,dualMatchUp:a,matchUpsMap:c,matchUp:u,event:p}){let m="removeSubsequentDrawPosition";if(a){let g=t.find(({matchUpId:h})=>u.matchUpId===h).sides?.find(h=>h.drawPosition===n)?.sideNumber,I=u.sides?.find(h=>h.sideNumber===g);I&&delete I.lineUp}u.drawPositions=(u.drawPositions||[]).map(f=>f===n?void 0:f).filter(Boolean);let l=e.filter(({drawPosition:f})=>u.drawPositions?.includes(f)).filter(f=>f.bye).length;return u.matchUpStatus=l&&Dt||[Ot,_t].includes(u.matchUpStatus)&&u.matchUpStatus||zt,[_t,Ot].includes(u.matchUpStatus)&&(u.winningSide=void 0),u.matchUpStatusCodes&&kh({inContextDrawMatchUps:t,sourceMatchUpStatus:r,sourceMatchUpId:i,matchUpsMap:c,matchUp:u}),It({tournamentId:o?.tournamentId,eventId:p?.eventId,context:`${m}-${n}`,drawDefinition:s,matchUp:u}),{...R}}function Rc(t){let{dualWinningSideChange:e,inContextDrawMatchUps:r,tournamentRecord:n,drawDefinition:o,matchUpStatus:i,matchUpsMap:s,dualMatchUp:a,targetData:c,matchUpId:u,structure:p,event:m}=t,d=!!t.matchUp.collectionId,l=fr({structure:p}),{drawPositions:f,winningSide:g}=c.matchUp||{};if(!l&&!f)return{error:Wa};let{targetLinks:{loserTargetLink:I,winnerTargetLink:h,byeTargetLink:S},targetMatchUps:{loserMatchUp:T,winnerMatchUp:A,byeMatchUp:D}}=c,y=Cn({...t,matchUpStatus:i||zt,removeWinningSide:!0});if(y.error)return y;let E;if(d){let{matchUpTieId:L,matchUpsMap:v}=t;if(E=zn({appliedPolicies:t.appliedPolicies,matchUpId:L,tournamentRecord:n,drawDefinition:o,matchUpsMap:v,event:m}),!e&&!E.removeWinningSide)return{...R}}if(l)return{...R};let{matchUps:U}=At({afterRecoveryTimes:!1,inContext:!0,drawDefinition:o,matchUpsMap:s,structure:p}),{positionAssignments:M}=de({structure:p}),P=g-1,N=1-P,C=f[P],O=f[N],{winnerParticipantId:b,loserParticipantId:x}=M?.reduce((L,v)=>(v.drawPosition===O&&(L.loserParticipantId=v.participantId),v.drawPosition===C&&(L.winnerParticipantId=v.participantId),L),{winnerParticipantId:void 0,loserParticipantId:void 0})||{},w=U.filter(L=>L.drawPositions?.includes(O));if(A&&CN({sourceMatchUpStatus:i,sourceMatchUpId:u,inContextDrawMatchUps:r,winningDrawPosition:C,winnerParticipantId:b,tournamentRecord:n,winnerTargetLink:h,drawDefinition:o,winnerMatchUp:A,dualMatchUp:a,matchUpsMap:s}),T){let{winnerHadMatchUpStatus:L}=_v({drawPositionMatchUps:w,loserDrawPosition:O,sourceMatchUps:U}),B=I.linkCondition===qn;if(L&&B){let j=Math.min(...T.drawPositions);aA({targetLink:I,inContextDrawMatchUps:r,drawDefinition:o,drawPosition:j,matchUpsMap:s,event:m})}let H=bV({sourceMatchUpStatus:i,sourceMatchUpId:u,loserParticipantId:x,tournamentRecord:n,loserTargetLink:I,drawDefinition:o,loserMatchUp:T,dualMatchUp:a,matchUpsMap:s,event:m});if(H.error)return H}if(D){let L=Math.min(...D.drawPositions);aA({sourceMatchUpId:u,targetLink:S,inContextDrawMatchUps:r,drawDefinition:o,drawPosition:L,matchUpsMap:s,event:m})}return{...R,...E&&{tieMatchUpResult:E}}}function CN({inContextDrawMatchUps:t,winningDrawPosition:e,sourceMatchUpStatus:r,winnerParticipantId:n,tournamentRecord:o,winnerTargetLink:i,sourceMatchUpId:s,drawDefinition:a,winnerMatchUp:c,matchUpsMap:u,dualMatchUp:p,event:m}){let{structureId:d,roundNumber:l}=c,f="removeDirectedWinner";if(i){let g=i.target.structureId,{structure:I}=st({drawDefinition:a,structureId:g});if(!I)return{error:Lt};let{positionAssignments:h}=de({structure:I});I.seedAssignments=(I.seedAssignments??[]).filter(M=>M.participantId!==n);let T=h?.find(M=>M.participantId===n)?.drawPosition,{matchUps:A}=At({drawDefinition:a,structure:I,event:m}),D=A.map(M=>M.drawPositions).flat(1/0).filter(Boolean),y=dr(D);if((T?y[T]:void 0)===1)h?.forEach(M=>{M.participantId===n&&delete M.participantId});else{let M=A.filter(({drawPositions:P})=>P.includes(T));console.log("not removing from position assignments since instances > 1",{drawPositionMatchUps:M,winnerTargetLink:i})}let U=u?.drawMatchUps?.find(({matchUpId:M})=>M===c.matchUpId);U&&It({tournamentId:o?.tournamentId,eventId:m?.eventId,matchUp:U,context:f,drawDefinition:a})}return l&&vv({targetDrawPosition:e,inContextDrawMatchUps:t,sourceMatchUpStatus:r,tournamentRecord:o,sourceMatchUpId:s,drawDefinition:a,dualMatchUp:p,matchUpsMap:u,roundNumber:l,structureId:d}),{...R}}function bV({sourceMatchUpStatus:t,loserParticipantId:e,tournamentRecord:r,loserTargetLink:n,sourceMatchUpId:o,drawDefinition:i,loserMatchUp:s,matchUpsMap:a,dualMatchUp:c,event:u}){let p="removeDirectedLoser",m=n.target.structureId,{structure:d}=st({drawDefinition:i,structureId:m});if(!d)return{error:Lt};let{positionAssignments:l}=de({structure:d}),f=l?.find(g=>g.participantId===e)?.drawPosition;if(l?.forEach(g=>{g.participantId===e&&delete g.participantId}),d.seedAssignments=(d.seedAssignments??[]).filter(g=>g.participantId!==e),c){let g=s?.sides.reduce((S,T,A)=>T.drawPosition===f?A:S,void 0),I=a?.drawMatchUps?.find(({matchUpId:S})=>S===s.matchUpId),h=I?.sides?.[g];h&&(delete h.lineUp,It({tournamentId:r?.tournamentId,eventId:u?.eventId,matchUp:I,context:p,drawDefinition:i}))}return{...R}}function aA({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,matchUpsMap:o,targetLink:i,event:s}){let a=i.target.structureId;return dc({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,matchUpsMap:o,drawPosition:n,structureId:a,event:s}),{...R}}function xv(t){let{matchUpFormat:e,score:r}=t,n=r?.sets?.length,o=e&&tr(e),{setFormat:i,finalSetFormat:s,bestOf:a}=o??{};return(a&&n===a&&s||i)?.timed||!1}function wv({tournamentRecord:t,drawDefinition:e,structure:r,matchUp:n}){let o="attemptToSetMatchUpStatusBYE";if(n?.winningSide)return _({result:{error:oa},context:{matchUpStatus:Dt},stack:o});let{positionAssignments:i}=de({structure:r}),s=i?.filter(c=>c.bye).map(c=>c.drawPosition);return n.drawPositions?.some(c=>s?.includes(c))?(n.matchUpStatus=Dt,n.matchUpStatusCodes=[],It({tournamentId:t?.tournamentId,context:o,drawDefinition:e,matchUp:n}),{...R}):_({result:{error:Ty},info:"matchUp does not include BYE",stack:o})}function Jd(t){let{tournamentRecord:e,appliedPolicies:r,drawDefinition:n,matchUpsMap:o,targetData:i,structure:s,event:a}=t,c="doubleExitAdvancement";if(s.structureType===Le)return _({result:{...R},stack:c});let{matchUp:u,targetMatchUps:p,targetLinks:m}=i,{loserMatchUp:d,winnerMatchUp:l,loserTargetDrawPosition:f}=p;if(d&&d.matchUpStatus!==Dt){let{loserTargetLink:g}=m;if(r?.progression?.doubleExitPropagateBye){let I=Fv({loserTargetDrawPosition:f,tournamentRecord:e,loserTargetLink:g,drawDefinition:n,loserMatchUp:d,matchUpsMap:o,event:a});if(I.error)return _({result:I,stack:c})}else{let{feedRound:I,drawPositions:h,matchUpId:S}=d,T=I?2:2-h.indexOf(f),A=Lv({...t,targetMatchUp:d,walkoverWinningSide:T,tournamentRecord:e,sourceMatchUp:u,matchUpId:S});if(A.error)return _({result:A,stack:c})}}if(l){let g=Lv({...t,matchUpId:l.matchUpId,targetMatchUp:l,tournamentRecord:e,sourceMatchUp:u});if(g.error)return _({result:g,stack:c})}return _({result:{...R},stack:c})}function Lv(t){let{inContextDrawMatchUps:e,tournamentRecord:r,drawDefinition:n,sourceMatchUp:o,targetMatchUp:i,matchUpsMap:s}=t,a=n.structures.find(({structureId:$})=>$===i.structureId),c=t.matchUpStatus===Ne?Ne:ge,u=t.matchUpStatus===Ne?Ot:_t,p="conditionallyAdvanceDrawPosition",m=s.drawMatchUps.find($=>$.matchUpId===i.matchUpId);if(!m)return{error:sr};let d=o?.drawPositions||[],l=m.drawPositions?.filter(Boolean),f=o?.structureId===i.structureId;if(f&&xe(d,l)&&(l=l.filter($=>!d.includes($))),f&&l.length>1)return _({result:{error:Ha},stack:p});let{pairedPreviousMatchUpIsDoubleExit:g,pairedPreviousMatchUp:I}=Fh(t),h=er({matchUpId:i.matchUpId,inContextDrawMatchUps:e,drawDefinition:n}),{targetMatchUps:S,targetLinks:T}=h,{loserTargetDrawPosition:A,winnerMatchUp:D,loserMatchUp:y}=S;if(y){let{loserTargetLink:$}=T,k=Fv({loserTargetDrawPosition:A,loserMatchUp:y,tournamentRecord:r,loserTargetLink:$,drawDefinition:n,matchUpsMap:s});if(k.error)return _({result:k,stack:p})}let E=m.drawPositions?.filter(Boolean)||[],U=E.length===1,M=t.walkoverWinningSide||U&&Zm({drawPosition:E[0],matchUpId:i.matchUpId,inContextDrawMatchUps:e})||void 0,P=[_t,Ot].includes(m.matchUpStatus)&&!E.length,N=m.finishingRound===1,C=P&&!N?c:u,O=e.find($=>$.matchUpId===I.matchUpId),b=[],x;o&&(o?.structureId===O?.structureId?o.roundPosition<I?.roundPosition?x=1:x=2:i.feedRound?o.structureId===i.structureId?x=2:x=1:M&&(x=3-M));let w=t.matchUpStatus,F=I?.matchUpStatus;x===1?b=[{matchUpStatus:cA(w),previousMatchUpStatus:w,sideNumber:1},{matchUpStatus:cA(F),previousMatchUpStatus:F,sideNumber:2}]:x===2&&(b=[{matchUpStatus:cA(F),previousMatchUpStatus:F,sideNumber:1},{matchUpStatus:cA(w),previousMatchUpStatus:w,sideNumber:2}]),b.length&&(b=b.map($=>rt($)));let L=Cn({...t,winningSide:M,matchUp:m,matchUpStatusCodes:b,context:p,matchUpStatus:C});if(L.error)return _({result:L,stack:p});if(P)return Jd({...t,matchUpStatus:C,targetData:h});if(!D)return _({result:{...R},stack:p});let v=l.length===2?l[M-1]:l[0],{positionAssignments:B}=Nt({structure:a}),H=B?.find($=>$.drawPosition===v),j=s.drawMatchUps.find($=>$.matchUpId===D.matchUpId),V=j?.drawPositions?.filter(Boolean),Y=V.length===1;if(v){if(H?.bye){let $=er({matchUpId:j.matchUpId,inContextDrawMatchUps:e,drawDefinition:n});if(Y){let k=V.filter(Boolean)[0],K=Zm({drawPosition:k,matchUpId:j.matchUpId,inContextDrawMatchUps:e}),z=Cn({appliedPolicies:t.appliedPolicies,matchUpId:j.matchUpId,matchUp:j,matchUpStatus:u,matchUpStatusCodes:[],removeScore:!0,context:p,drawDefinition:n,winningSide:K});return z.error?_({result:z,stack:p}):Rh({drawPositionToAdvance:k,matchUpId:j.matchUpId,inContextDrawMatchUps:e,drawDefinition:n,matchUpsMap:s})}else if([_t,Ot].includes(D.matchUpStatus)){let k=Jd({...t,matchUpId:j.matchUpId,matchUpStatus:C,targetData:$});if(k.error)return _({result:k,stack:p})}return _({result:{...R},stack:p})}return Ic({matchUpId:D.matchUpId,drawPosition:v,inContextDrawMatchUps:e,drawDefinition:n})}else if(g){if(!j)return{error:sr};if(Y){let K=V[0],z=Zm({matchUpId:i.matchUpId,inContextDrawMatchUps:e,drawPosition:K});console.log("existing drawPosition is winningSide",{walkoverWinningSide:z})}let $=[_t,Ot].includes(j.matchUpStatus)?u:c,k=Cn({matchUpId:j.matchUpId,appliedPolicies:t.appliedPolicies,matchUp:j,matchUpStatusCodes:[],removeScore:!0,context:p,drawDefinition:n,matchUpStatus:$});if(k.error)return _({result:k,stack:p});if($===c){let K=Jd({...t,matchUpId:i.matchUpId,matchUpStatus:$,targetData:h});if(K.error)return K}}return _({result:{...R},stack:p})}function Fv(t){let{loserTargetDrawPosition:e,tournamentRecord:r,loserTargetLink:n,drawDefinition:o,matchUpsMap:i,event:s}=t,a=n?.target?.structureId,{structure:c}=st({drawDefinition:o,structureId:a});return c?Dr({drawPosition:e,tournamentRecord:r,drawDefinition:o,structureId:a,matchUpsMap:i,event:s}):{error:Do}}function cA(t){return t===ge?_t:t===Ne?Ot:t}function Gv(t){let{tournamentRecord:e,drawDefinition:r,matchUpStatus:n,structure:o,matchUp:i}=t,s=!!(i.tieMatchUps&&!i.rondPosition&&t.inContextDrawMatchUps.find(h=>h.matchUpId===i.matchUpId).containerStructureId),a="attemptToSetMatchUpStatus",c=n===Dt,u=i.winningSide,p=[ge,Ne].includes(n),m=Ea({matchUpStatus:n}),d=Gf({matchUpStatus:n}),l=!m&&!d,f=t.matchUpTieId||u&&m&&!p,g=u&&p,I=()=>Cn({...t,removeScore:[Wo,_t].includes(n),matchUpStatus:n||zt});return l&&{error:dI}||f&&RN(t)||g&&OV(t)||u&&Rc(t)||d&&I()||c&&wv({tournamentRecord:e,drawDefinition:r,structure:o,matchUp:i})||!m&&{error:dI}||p&&_V(t)||s&&RN(t)||_({result:{error:oa},stack:a})}function OV(t){let e=Rc(t);return e.error?e:Jd(t)}function _V(t){let e=RN({...t,removeScore:!0});return e.error?e:Jd(t)}function RN(t){let e="scoreModification";if(t.isCollectionMatchUp&&t.dualMatchUp?.winningSide&&!t.projectedWinningSide){let i=Rc(t);if(i.error)return _({result:i,stack:e})}let n=!!t.matchUp.collectionId,o=Cn({...t,context:e});if(n){let{matchUpTieId:i,drawDefinition:s,matchUpsMap:a}=t,c=zn({tournamentRecord:t.tournamentRecord,appliedPolicies:t.appliedPolicies,matchUpId:i,event:t.event,drawDefinition:s,matchUpsMap:a});if(c.error)return _({result:c,stack:e});Object.assign(o,{tieMatchUpResult:c})}return _({result:o,stack:e})}function kv({drawDefinition:t,structure:e,matchUp:r}){let{drawPositions:n}=r,{positionAssignments:o}=Nt({drawDefinition:t,structure:e}),s=o?.filter(({drawPosition:m})=>n?.includes(m))?.map(m=>{let{extension:d}=mt({element:m,name:Ho});return d?.value?.groupOrder}),{containerStructures:a}=Ji({drawDefinition:t}),c=a[e.structureId];return{structureIds:ks({drawDefinition:t,structureId:c})?.links?.source?.filter(m=>xe(s,m.source?.finishingPositions||[])).map(m=>m.source.structureId)}}function uA({drawDefinition:t,structure:e,matchUp:r}){let n=[];if(e.finishingPosition===vs&&Jo({drawDefinition:t,structure:e})){let{structureIds:i}=kv({drawDefinition:t,structure:e,matchUp:r});i?.length&&n.push(...i)}return{connectedStructureIds:n}}function Vv(t){let e,{inContextDrawMatchUps:r,inContextMatchUp:n,drawDefinition:o,winningSide:i}=t,s=t.targetData.targetLinks?.winnerTargetLink;if(s.target.feedProfile===Qr){let a=n.sides.find(({sideNumber:u})=>u!==i).participantId,c=r.find(u=>u.structureId===s.target.structureId&&u.roundNumber===s.target.roundNumber&&u.sides.some(({participantId:p})=>p===a));if(c?.matchUpStatus===zt){let u=er({matchUpId:c.matchUpId,inContextDrawMatchUps:r,drawDefinition:o});if(!Ai({inContextDrawMatchUps:r,drawDefinition:o,targetData:u})){let{structure:m}=st({structureId:c.structureId,drawDefinition:o}),d=Nt({structure:m}).positionAssignments;for(let l of d||[])if(l.participantId===a){let f=n.sides.find(({sideNumber:g})=>g===i).participantId;if(l.participantId=f,m?.positionAssignments)m.positionAssignments=d;else if(m?.structures){let g=Object.assign({},...(d||[]).map(I=>({[I.drawPosition]:I.participantId})));for(let I of m.structures)I.positionAssignments?.forEach(h=>h.participantId=g[h.drawPosition])}To({tournamentId:t.tournamentRecord?.tournamentId,event:t.event,drawDefinition:o,structure:m}),e=!0}}}}return{...R,qualifierReplaced:e}}function Bv(t){let e,{inContextDrawMatchUps:r,inContextMatchUp:n,drawDefinition:o,winningSide:i}=t,s=t.targetData.targetLinks?.winnerTargetLink;if(s.target.feedProfile===Qr){let a=n.sides.find(({sideNumber:p})=>p===i)?.participantId,c=r.filter(p=>p.structureId===s.target.structureId&&p.roundNumber===s.target.roundNumber&&p.sides.some(({participantId:m,qualifier:d})=>d&&!m)),u=on(c);if(u?.matchUpStatus===zt){let p=er({matchUpId:u.matchUpId,inContextDrawMatchUps:r,drawDefinition:o});if(!Ai({inContextDrawMatchUps:r,drawDefinition:o,targetData:p})){let d=u.sides.find(g=>g.qualifier&&!g.participantId)?.drawPosition,{structure:l}=st({structureId:u.structureId,drawDefinition:o});if(!l)return{error:Lt};let f=Nt({structure:l}).positionAssignments;for(let g of f||[])if(g.drawPosition===d&&!g.participantId){if(g.participantId=a,l.positionAssignments)l.positionAssignments=f;else if(l.structures){let I=Object.assign({},...(f||[]).map(h=>({[h.drawPosition]:h.participantId})));for(let h of l.structures)h.positionAssignments?.forEach(S=>S.participantId=I[S.drawPosition])}To({tournamentId:t.tournamentRecord?.tournamentId,event:t.event,drawDefinition:o,structure:l}),e=!0}}}}return{...R,qualifierPlaced:e}}function Hv(t){let e="attemptToSetWinningSide",r,{appliedPolicies:n,disableAutoCalc:o,drawDefinition:i,dualMatchUp:s,winningSide:a,structure:c,matchUp:u}=t;if(s?._disableAutoCalc&&o!==!1)return ud(t);if(u.winningSide&&u.winningSide!==a){let{connectedStructureIds:l}=uA({drawDefinition:i,structure:c,matchUp:u});l.length&&(console.log({connectedStructureIds:l}),r=!0);let f=Rc(t);if(f.error)return f}let p=uS(t);if(p.error)return _({result:p,stack:e});let m,d;return t.qualifierChanging&&n?.[Hc]?.autoReplaceQualifiers&&(m=Vv(t).qualifierReplaced),t.qualifierAdvancing&&n?.[Hc]?.autoPlaceQualifiers&&(d=Bv(t).qualifierPlaced),_({result:rt({...R,...p,connectedStructures:r,qualifierReplaced:m,qualifierPlaced:d}),stack:e})}var pA={drawPositionToRemove:"green",iteration:"brightred",winner:"green",loser:"brightred"};function bN(t){let{inContextDrawMatchUps:e,appliedPolicies:r,drawDefinition:n,matchUpsMap:o,targetData:i,matchUp:s}=t,{iteration:a=0}=t;a+=1;let c="removeDoubleExit";kn({method:c,color:"brightyellow",iteration:a,keyColors:pA});let{targetLinks:{loserTargetLink:u},targetMatchUps:{loserMatchUp:p,winnerMatchUp:m,loserTargetDrawPosition:d}}=i;if(m&&m.matchUpStatus!==Dt){let{stage:l,roundNumber:f,roundPosition:g}=m;kn({winner:"winner",stage:l,roundNumber:f,roundPosition:g,keyColors:pA}),Wv({...t,targetMatchUp:m,sourceMatchUp:s,iteration:a})}if(p&&p.matchUpStatus!==Dt){let l=e.find(({matchUpId:T})=>T===p.matchUpId),{structure:f}=st({drawDefinition:n,structureId:l.structureId}),{stage:g,roundNumber:I,roundPosition:h,feedRound:S}=p;if(kn({loser:"loser",stage:g,roundNumber:I,roundPosition:h,keyColors:pA,feedRound:S}),r?.progression?.doubleExitPropagateBye)aA({drawPosition:d,targetLink:u,inContextDrawMatchUps:e,drawDefinition:n,matchUpsMap:o});else{let T=Wv({...t,structure:f,targetMatchUp:p,iteration:a});if(T.error)return _({result:T,stack:c})}}return _({result:{...R},stack:c})}function Wv(t){let{inContextDrawMatchUps:e,appliedPolicies:r,drawDefinition:n,sourceMatchUp:o,targetMatchUp:i,matchUpsMap:s,structure:a,iteration:c}=t,u="conditionallyRemoveDrawPosition";kn({method:u});let p=er({matchUpId:i.matchUpId,inContextDrawMatchUps:e,drawDefinition:n}),{targetMatchUps:{winnerMatchUp:m}}=p,d=s?.drawMatchUps.find(A=>A.matchUpId===i.matchUpId),l=[],f,g,I;if(i.feedRound)I=m?.drawPositions?.filter(Boolean)?.find(D=>i.drawPositions.includes(D));else if(!o)I=jt(i?.drawPositions||[],m?.drawPositions||[])?.[0];else if(g=Gh({structureId:a.structureId,matchUp:o,matchUpsMap:s})?.pairedPreviousMatchUp,f=[ge,Ne].includes(g?.matchUpStatus),l=g?.drawPositions?.filter(Boolean)||[],[...ae,Dt].includes(g?.matchUpStatus)||g?.winningSide){let D=o.drawPositions||[],y=i.drawPositions?.filter(Boolean);xe(D,y)&&(y=y?.filter(U=>!D.includes(U))),I=D.concat(l).find(U=>y?.includes(U))}if(m&&I){let{stage:A,roundNumber:D,roundPosition:y}=m;kn({method:"removeDirectedWinner",drawPositionToRemove:I,keyColors:pA,color:"brightgreen",stage:A,roundNumber:D,roundPosition:y}),CN({winningDrawPosition:I,winnerMatchUp:m,inContextDrawMatchUps:e,drawDefinition:n,matchUpsMap:s})}let h=bN({targetData:p,matchUp:i,inContextDrawMatchUps:e,appliedPolicies:r,drawDefinition:n,matchUpsMap:s,structure:a,iteration:c});if(h.error)return _({result:h,stack:u});let S=vV({pairedPreviousDoubleExit:f,noContextTargetMatchUp:d}),T=!f;return h=Cn({...t,matchUpId:i.matchUpId,matchUp:d,removeWinningSide:!0,matchUpStatusCodes:[],context:u,matchUpStatus:S,removeScore:T,score:{scoreStringSide1:"",scoreStringSide2:"",sets:void 0}}),h.error?_({result:h,stack:u}):{...R}}function vV({pairedPreviousDoubleExit:t,noContextTargetMatchUp:e}){return e.matchUpStatus===Dt?Dt:t?[Ne,Ot].includes(e?.matchUpStatus)?Ot:_t:zt}function jv(t){let e,{inContextDrawMatchUps:r,inContextMatchUp:n,drawDefinition:o}=t,i=t.targetData.targetLinks?.winnerTargetLink;if(i.target.feedProfile===Qr){let s=n.sides?.find(({sideNumber:c})=>c===n.winningSide)?.participantId,a=r.find(c=>c.structureId===i.target.structureId&&c.roundNumber===i.target.roundNumber&&c.sides?.some(({participantId:u})=>u===s));if(a&&a.matchUpStatus===zt){let c=er({matchUpId:a.matchUpId,inContextDrawMatchUps:r,drawDefinition:o});if(!Ai({inContextDrawMatchUps:r,drawDefinition:o,targetData:c})){let{structure:p}=st({structureId:a.structureId,drawDefinition:o}),m=Nt({structure:p}).positionAssignments;for(let d of m||[])if(d.participantId===s){if(d.participantId=void 0,p?.positionAssignments)p.positionAssignments=m;else if(p?.structures){let l=Object.assign({},...(m||[]).map(f=>({[f.drawPosition]:f.participantId})));for(let f of p?.structures||[])f.positionAssignments?.forEach(g=>g.participantId=l[g.drawPosition])}To({tournamentId:t.tournamentRecord?.tournamentId,event:t.event,drawDefinition:o,structure:p}),e=!0}}}}return{qualifierRemoved:e}}function qv(t){let{matchUp:e,matchUpStatus:r,score:n,winningSide:o}=t,i="noDownStreamDependencies";if([ge,Ne].includes(e?.matchUpStatus)&&![ge,Ne].includes(r)){let I=bN(t);if(I.error)return _({result:I,stack:i})}let a=r===ge,c=Ie({score:n})&&!a&&(t.isCollectionMatchUp&&!t.projectedWinningSide||!o),u=t?.inContextMatchUp?.collectionId&&xv(t.inContextMatchUp),p=t.removeScore||!u&&![_o,$r].includes(r||_o),m=t.isCollectionMatchUp&&t.dualMatchUp.winningSide&&!t.projectedWinningSide||e.winningSide&&!o&&!Ie({score:n}),d=r&&r!==zt,l=I=>{let h,{structure:S,drawDefinition:T,dualMatchUp:A,disableAutoCalc:D}=t;if(A?._disableAutoCalc&&D!==!1)return ud(t);let{connectedStructureIds:y}=uA({drawDefinition:T,structure:S,matchUp:e});y.length&&(console.log({connectedStructureIds:y}),h=!0),Object.assign(t,{removeScore:I});let E=Rc(t);if(E.error)return E;if(t.removingQualifier&&t.appliedPolicies?.[Hc]?.autoRemoveQualifiers){let U=jv(t);return{...R,connectedStructures:h,...U}}return{...R,connectedStructures:h}};if(m&&o&&t.isCollectionMatchUp)return Yv(t);let f=[Wo,$r].includes(r)&&t.dualWinningSideChange,g=(o||f)&&Hv(t)||c&&l(p)||d&&Gv(t)||m&&l(p)||e&&Yv({...t,removeScore:!0})||{...R};return _({result:g,stack:i})}function Yv(t){let e="scoreModification";if(t.isCollectionMatchUp&&t.dualMatchUp?.winningSide&&!t.projectedWinningSide){let o=Rc(t);if(o.error)return o}let n=Cn({...t,context:e});if(t.isCollectionMatchUp){let{matchUpTieId:o,drawDefinition:i,event:s,matchUpsMap:a}=t,{removeWinningSide:c}=zn({tournamentRecord:t.tournamentRecord,appliedPolicies:t.appliedPolicies,matchUpId:o,drawDefinition:i,matchUpsMap:a,event:s});c&&console.log("REMOVE WINNING SIDE")}return _({result:n,stack:e})}function Vo(t){let e="addMatchUpScheduledTime",r=t.matchUp,{removePriorValues:n,tournamentRecord:o,drawDefinition:i,disableNotice:s,scheduledTime:a,matchUpId:c}=t;if(!c)return _({result:{error:ke},stack:e});if(!Bc(a))return _({result:{error:mo},stack:e});if(!r){let I=xt({drawDefinition:i,matchUpId:c});if(I.error)return _({result:I,stack:e});r=I.matchUp}let u=Ut(a),p=rs({matchUp:r}).scheduledDate,m=u&&!p;if((xf({matchUp:r}).timeModifiers||[])?.length){let I=ON({disableNotice:!0,removePriorValues:n,tournamentRecord:o,timeModifiers:[],drawDefinition:i,matchUpId:c,matchUp:r});if(I?.error)return _({result:I,stack:e})}let f=tc(a,!0,m);return rn({duplicateValues:!1,removePriorValues:n,tournamentRecord:o,drawDefinition:i,disableNotice:s,matchUpId:c,timeItem:{itemType:Ls,itemValue:f}})}function ON({removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,timeModifiers:o,matchUpId:i,matchUp:s}){let a="addMatchUpTimeModifiers";if(!i)return _({result:{error:ke},stack:a});if(o!==void 0&&!Array.isArray(o))return _({info:Nn("timeModifiers"),result:{error:G},stack:a});if(!s){let l=xt({drawDefinition:r,matchUpId:i});if(l.error)return _({result:l,stack:a});s=l.matchUp}let c=xf({matchUp:s}).timeModifiers||[],u=o.filter(l=>!c.includes(l));if(o.length&&!u.length)return{...R};if(u.some(l=>uh.includes(l))){c=c.filter(f=>!uh.includes(f));let l=Vo({disableNotice:!0,removePriorValues:t,scheduledTime:"",tournamentRecord:e,drawDefinition:r,matchUpId:i});if(l.error)return _({result:l,stack:a})}let m=o?.length?[...u,...c]:void 0;return rn({duplicateValues:!1,removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,matchUpId:i,timeItem:{itemType:bf,itemValue:m}})}function $p({removePriorValues:t,tournamentRecords:e,tournamentRecord:r,drawDefinition:n,disableNotice:o,courtDayDate:i,matchUpId:s,courtIds:a}){if(!r&&!e)return{error:W};if(!s)return{error:ke};let c=xt({drawDefinition:n,matchUpId:s});if(c.error)return c;if(c?.matchUp?.matchUpType!==ln)return{error:Je};if(!(a===void 0||Array.isArray(a)&&a.length&&a.every(d=>typeof d=="string")))return{error:G,context:{courtIds:a}};let p;if(a){let d=e||r&&{[r.tournamentId]:r},l=po({tournamentRecords:d});if(l.error)return l;let f=l.courts?.filter(g=>a.includes(g.courtId));if(f?.length!==a.length)return{error:G,context:{courtIds:a}};p=f?.map(g=>({venueId:g.venueId,courtId:g.courtId}))}return rn({duplicateValues:!1,removePriorValues:t,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:s,timeItem:{itemType:Eo,itemDate:i,itemValue:p}})}function Zs({removePriorValues:t,tournamentRecords:e,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:i,venueId:s}){if(!r)return{error:W};if(!i)return{error:ke};if(s){let c=Qo({tournamentRecords:e,tournamentRecord:r,venueId:s});if(c.error)return c}return rn({duplicateValues:!1,removePriorValues:t,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:i,timeItem:{itemType:xs,itemValue:s}})}function Hi({removePriorValues:t,tournamentRecords:e,tournamentRecord:r,drawDefinition:n,disableNotice:o,courtDayDate:i,matchUpId:s,courtId:a}){if(!r&&!e)return{error:W};if(!s)return{error:ke};if(a){let u=ns({tournamentRecords:e,tournamentRecord:r,courtId:a});if(u.error)return u;let p=u.venue?.venueId;Zs({tournamentRecords:e,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:s,venueId:p})}return rn({duplicateValues:!1,removePriorValues:t,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:s,timeItem:{itemType:di,itemDate:i,itemValue:a}})}function Ss(t,e){let r=xI.test(t)?t:$t(t),n=Ut(t)||Ut(e)||ro(new Date);return new Date(`${n}T${r}`).getTime()}function Kp({errorOnAnachronism:t=!1,checkChronology:e=!0,matchUpDependencies:r,inContextMatchUps:n,removePriorValues:o,tournamentRecords:i,tournamentRecord:s,drawDefinition:a,disableNotice:c,drawMatchUps:u,matchUpId:p,schedule:m,event:d}){if(!m)return{error:et,info:"Missing schedule"};if(!a)return{error:X};if(!p)return{error:ke};let l="addMatchUpScheduleItems",f,g;if(u)f=u.find(C=>C.matchUpId===p);else{let C=xt({drawDefinition:a,event:d,matchUpId:p});if(C.error)return C;f=C.matchUp}let{endTime:I,courtId:h,courtIds:S,courtOrder:T,resumeTime:A,scheduledDate:D,scheduledTime:y,startTime:E,stopTime:U,timeModifiers:M,venueId:P}=m;e&&(!r||!n)&&({matchUpDependencies:r,matchUps:n}=Vr({drawDefinition:a}));let N=r?.[p]?.matchUpIds;if(m.scheduledDate&&e&&N){let C=n?.filter(O=>(O.schedule?.scheduledDate||Ut(O.schedule?.scheduledTime))&&N.includes(O.matchUpId)).map(({schedule:O})=>{let b=Im(O);return new Date(b).getTime()});if(C?.length){let O=Im(m),b=new Date(O).getTime();if(Math.max(...C)>=b){if(t)return _({result:{error:aI},stack:l});g=aI}}}if(D!==void 0){let C=Zd({disableNotice:!0,removePriorValues:o,tournamentRecord:s,drawDefinition:a,scheduledDate:D,matchUpId:p});if(C?.error)return _({result:C,stack:l,context:{scheduledDate:D}})}if(y!==void 0){let C=Vo({disableNotice:!0,removePriorValues:o,tournamentRecord:s,drawDefinition:a,scheduledTime:y,matchUpId:p,matchUp:f});if(C?.error)return _({result:C,stack:l,context:{scheduledTime:y}})}if(E!==void 0){let C=dA({disableNotice:!0,removePriorValues:o,tournamentRecord:s,drawDefinition:a,matchUpId:p,startTime:E,event:d});if(C?.error)return _({result:C,stack:l,context:{startTime:E}})}if(U!==void 0){let C=fA({disableNotice:!0,removePriorValues:o,tournamentRecord:s,drawDefinition:a,matchUpId:p,stopTime:U,event:d});if(C?.error)return _({result:C,stack:l,context:{stopTime:U}})}if(A!==void 0){let C=gA({disableNotice:!0,removePriorValues:o,tournamentRecord:s,drawDefinition:a,resumeTime:A,matchUpId:p,event:d});if(C?.error)return _({result:C,stack:l,context:{resumeTime:A}})}if(I!==void 0){let C=lA({disableNotice:!0,removePriorValues:o,tournamentRecord:s,drawDefinition:a,matchUpId:p,endTime:I,event:d});if(C?.error)return _({result:C,stack:l,context:{endTime:I}})}if(S!==void 0){let C=$p({disableNotice:!0,removePriorValues:o,tournamentRecord:s,drawDefinition:a,matchUpId:p,courtIds:S});if(C?.error)return _({result:C,stack:l,context:{courtIds:S}})}if(h!==void 0&&D!==void 0){let C=Hi({courtDayDate:D,disableNotice:!0,removePriorValues:o,tournamentRecords:i,tournamentRecord:s,drawDefinition:a,matchUpId:p,courtId:h});if(C?.error)return _({result:C,stack:l,context:{courtId:h}})}if(P!==void 0){let C=Zs({disableNotice:!0,removePriorValues:o,tournamentRecords:i,tournamentRecord:s,drawDefinition:a,matchUpId:p,venueId:P});if(C?.error)return _({result:C,stack:l,context:{venueId:P}})}if(T!==void 0&&ft(T)){let C=mA({disableNotice:!0,removePriorValues:o,tournamentRecord:s,drawDefinition:a,courtOrder:T,matchUpId:p});if(C?.error)return _({result:C,stack:l,context:{courtOrder:T}})}if(M!==void 0){let C=ON({disableNotice:!0,removePriorValues:o,tournamentRecord:s,drawDefinition:a,timeModifiers:M,matchUpId:p,matchUp:f});if(C?.error)return _({result:C,stack:l,context:{timeModifiers:M}})}return c||It({tournamentId:s?.tournamentId,eventId:d?.eventId,context:l,drawDefinition:a,matchUp:f}),g?{...R,warnings:[g]}:{...R}}function Zd({scheduledDate:t,removePriorValues:e,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:i}){if(!i)return{error:ke};let s=t&&Ro.test(t);if(t&&!s)return{error:ar};let c={itemValue:Ut(t),itemType:ws};return rn({duplicateValues:!1,removePriorValues:e,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:i,timeItem:c})}function mA({removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,courtOrder:o,matchUpId:i}){if(!i)return{error:ke};if(o&&!ft(o))return{error:G,info:"courtOrder must be numeric"};let s=o&&ct(o);return rn({duplicateValues:!1,removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,matchUpId:i,timeItem:{itemType:Rf,itemValue:s}})}function _N({removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,participantId:o,officialType:i,matchUpId:s}){if(!s)return{error:ke};if(!o)return{error:oe};if(e){let c=Yt({tournamentRecord:e,participantFilters:{participantTypes:[ht],participantRoles:[Bf]}}).participants??[];if(!bo({tournamentParticipants:c,participantId:o}))return{error:Zt}}let a={itemType:"SCHEDULE.ASSIGNMENT.OFFICIAL",itemValue:o};return i&&(a.itemSubTypes=[i]),rn({duplicateValues:!1,removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,matchUpId:s,timeItem:a})}function dA({removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,matchUpId:o,startTime:i,event:s}){if(!o)return{error:ke};if(!Bc(i))return{error:mo};let{matchUp:a}=xt({drawDefinition:r,event:s,matchUpId:o}),{scheduledDate:c}=rs({matchUp:a}),p=(a?.timeItems??[]).filter(m=>[xi,li,fi].includes(m?.itemType)).map(m=>Ss(m.itemValue,c)).reduce((m,d)=>!m||d<m?d:m,void 0);if(!p||Ss(i,c)<p){a?.timeItems&&(a.timeItems=a.timeItems.filter(l=>l.itemType!==Uo));let m=tc(i,!0,!0);return rn({duplicateValues:!1,removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,matchUpId:o,timeItem:{itemType:Uo,itemValue:m}})}else return{error:Yy}}function lA({validateTimeSeries:t=!0,removePriorValues:e,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:i,endTime:s,event:a}){if(!i)return{error:ke};if(!Bc(s))return{error:mo};let{matchUp:c}=xt({drawDefinition:n,event:a,matchUpId:i}),{scheduledDate:u}=rs({matchUp:c}),m=(c?.timeItems??[]).filter(d=>[Uo,li,xi].includes(d?.itemType)).map(d=>Ss(d.itemValue,u)).reduce((d,l)=>!d||l>d?l:d,void 0);if(!t||!m||Ss(s,u)>m){c?.timeItems&&(c.timeItems=c.timeItems.filter(f=>f.itemType!==fi));let d=tc(s,!0,!0);return rn({duplicateValues:!1,removePriorValues:e,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:i,timeItem:{itemType:fi,itemValue:d}})}else return{error:Wy}}function fA({removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,matchUpId:o,stopTime:i,event:s}){if(!o)return{error:ke};if(!Bc(i))return{error:mo};let{matchUp:a}=xt({drawDefinition:r,event:s,matchUpId:o}),{scheduledDate:c}=rs({matchUp:a}),u=a?.timeItems??[];if(u.reduce((g,I)=>I.itemType===fi||g,void 0))return{error:TI};let m=u.filter(g=>[Uo,li,xi].includes(g?.itemType)).sort((g,I)=>Ss(g.itemValue,c)-Ss(I.itemValue,c)),d=m[m.length-1],l=d&&d.itemType===xi,f=m.filter(g=>!l||g.createdAt!==d.createdAt).map(g=>Ss(g.itemValue,c)).reduce((g,I)=>!g||I>g?I:g,void 0);if(Ss(i,c)>f){if(a?.timeItems&&l){let h=d.createdAt;a.timeItems=a.timeItems.filter(S=>S.createdAt!==h)}let I={itemValue:tc(i,!0,!0),itemType:xi};return rn({duplicateValues:!0,removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,matchUpId:o,timeItem:I})}else return{error:jy}}function gA({removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,resumeTime:o,matchUpId:i,event:s}){if(!i)return{error:ke};if(!Bc(o))return{error:mo};let{matchUp:a}=xt({drawDefinition:r,event:s,matchUpId:i}),{scheduledDate:c}=rs({matchUp:a}),u=a?.timeItems??[];if(u.reduce((g,I)=>I.itemType===fi||g,void 0))return{error:TI};let m=u.filter(g=>[Uo,li,xi].includes(g?.itemType)).sort((g,I)=>Ss(g.itemValue,c)-Ss(I.itemValue,c)),d=m[m.length-1],l=d&&d.itemType===li,f=m.filter(g=>!l||g.createdAt!==d.createdAt).map(g=>Ss(g.itemValue,c)).reduce((g,I)=>!g||I>g?I:g,void 0);if(Ss(o,c)>f){if(a?.timeItems&&l){let h=d.createdAt;a.timeItems=a.timeItems.filter(S=>S.createdAt!==h)}let I={itemValue:tc(o,!0,!0),itemType:li};return rn({duplicateValues:!0,removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,matchUpId:i,timeItem:I})}else return{error:wC}}function $v(t){let{tournamentRecord:e,inContextMatchUp:r,structure:n,drawDefinition:o}=t,i=r.roundNumber,s=r.sides.find(y=>y.sideNumber===r.winningSide),a=r.sides.find(y=>y.sideNumber!==r.winningSide),{drawPosition:c,participantId:u}=s,{drawPosition:p,participantId:m}=a,d="swapWinnerLoser",{matchUps:l}=At(t),f=l.filter(({drawPositions:y,roundNumber:E})=>y?.includes(c)&&E>i);yr({changeWinner:!0})&&console.log({existingWinnerSubsequentMatchUps:f}),f.forEach(y=>{y.drawPositions=y.drawPositions?.map(E=>E===c?p:E)||[],It({tournamentId:e?.tournamentId,eventId:t.event?.eventId,context:d,drawDefinition:o,matchUp:y})});let{stage:g,stageSequence:I}=n,h=o.structures.filter(({stage:y,stageSequence:E})=>y===g&&E>I).map(({structureId:y})=>y),{targetLinks:{loserTargetLink:S,winnerTargetLink:T}}=t.targetData,A=[S?.target.structureId,T?.target?.structureId].filter(Boolean);return o.structures.filter(({stage:y,structureId:E})=>y!==g&&A.includes(E)).forEach(({stage:y,stageSequence:E,structureId:U})=>{h.includes(U)||h.push(U),o.structures.filter(({stage:M,stageSequence:P})=>M===y&&P>E).forEach(({structureId:M})=>{h.includes(M)||h.push(M)})}),o.structures.filter(({structureId:y})=>h.includes(y)).forEach(y=>{let{positionAssignments:E}=Nt({structure:y}),U=E?.find(({participantId:P})=>P===u),M=E?.find(({participantId:P})=>P===m);U&&(U.participantId=m),M&&(M.participantId=u)}),Cn({...t,context:d})}function La(t){let e="setMatchUpStatus";t.matchUpStatus&&[_t,ge].includes(t.matchUpStatus)&&(t.score=void 0);let{allowChangePropagation:r,disableScoreValidation:n,tournamentRecords:o,tournamentRecord:i,disableAutoCalc:s,enableAutoCalc:a,drawDefinition:c,matchUpStatus:u,winningSide:p,matchUpId:m,event:d,score:l}=t;if(!c)return{error:X};if(u&&[Wo,_o,$r,zt].includes(u)&&p)return{error:G,winningSide:p,matchUpStatus:u};if(![void 0,...jI].includes(u))return _({result:{error:oa},info:"matchUpStatus does not exist",stack:"setMatchUpStatus"});let f=Ae({drawDefinition:c}),{matchUps:g}=re({nextMatchUps:!0,tournamentRecord:i,inContext:!0,drawDefinition:c,matchUpsMap:f,event:d}),I=f.drawMatchUps.find(V=>V.matchUpId===m),h=g?.find(V=>V.matchUpId===m);if(!I||!g)return{error:Oe};if((I.winningSide||p)&&u===Dt)return{context:"Cannot have Bye with winningSide",error:Sl,matchUpStatus:u};let S=h?.structureId,{structure:T}=st({drawDefinition:c,structureId:S}),A=ie(Bt)(I.matchUpType),D=h?.drawPositions?.filter(Boolean),y;if(A){if(s)St({extension:{name:rc,value:!0},element:I});else if(a){let V=I.winningSide;or({name:rc,element:I});let{winningSide:Y,scoreStringSide1:$,scoreStringSide2:k,set:K}=Uc({drawDefinition:c,matchUpsMap:f,structure:T,matchUp:I,event:d}),z={scoreStringSide1:$,scoreStringSide2:k,sets:K?[K]:[]};y=Y!==V,Object.assign(t,{winningSide:Y,dualWinningSideChange:y,projectedWinningSide:Y,score:z})}Ra({tournamentId:i?.tournamentId,inContextDualMatchUp:h,eventId:d?.eventId,dualMatchUp:I,drawDefinition:c})}if(A&&u&&[oc].includes(u))return{error:G,info:"Not supported for matchUpType: TEAM"};let E=h?.matchUpTieId,U=er({matchUpId:E||m,inContextDrawMatchUps:g,drawDefinition:c});if(l&&!A&&!n){let V=I.matchUpFormat??T?.matchUpFormat??c?.matchUpFormat??d?.matchUpFormat,Y=Tg({existingMatchUpStatus:I.matchUpStatus,matchUpFormat:V,matchUpStatus:u,winningSide:p,score:l});if(Y.error)return Y}let M=I?.sides?[]:Nt({drawDefinition:c,structureId:S}).positionAssignments,P=h?.sides?.map(V=>V.participantId).filter(Boolean).length,N=P&&P===2||I.collectionId&&fr({structure:T})&&P&&P>=1||D?.length===2&&M?.filter(V=>D.includes(V.drawPosition)).every(V=>V.participantId);if(u&&WI.includes(u)&&!N)return _({info:"present in participantsRequiredMatchUpStatuses",context:{matchUpStatus:u,requiredParticipants:N},result:{error:oa}});let C=Pt({policyTypes:[Hc,vn],tournamentRecord:i,drawDefinition:c,event:d})?.appliedPolicies??{};typeof t.policyDefinitions=="object"&&Object.assign(C,t.policyDefinitions);let O=h?.stage===at&&h.finishingRound===1,b=O&&p,x=O&&I.winningSide&&!p&&(!t.matchUpStatus||t.matchUpStatus&&Gf({matchUpStatus:t.matchUpStatus}))&&(!t.outcome||!Ie({outcome:t.outcome})),w=b&&p!==I.winningSide&&I.winningSide;if(Object.assign(t,{inContextDrawMatchUps:g,qualifierAdvancing:b,qualifierChanging:w,removingQualifier:x,inContextMatchUp:h,appliedPolicies:C,matchUpTieId:E,matchUpsMap:f,targetData:U,structure:T,matchUp:I}),E){let{matchUp:V}=xt({matchUpId:E,inContext:!0,drawDefinition:c,matchUpsMap:f,event:d});if(V){let Y=je({matchUp:V,drawDefinition:c,structure:T,event:d})?.tieFormat,{projectedWinningSide:$}=Ov({drawDefinition:c,matchUpStatus:u,dualMatchUp:V,matchUpsMap:f,winningSide:p,tieFormat:Y,structure:T,matchUp:I,event:d,score:l}),k=V.winningSide;y=$!==k,Object.assign(t,{isCollectionMatchUp:!0,dualWinningSideChange:y,projectedWinningSide:$,matchUpTieId:E,dualMatchUp:V,tieFormat:Y})}}let F=Ai(t),L=Ea({matchUpStatus:u});if(!E){if(F&&!p&&(u&&Gf({matchUpStatus:u})||u&&[ge,Ne].includes(u)))return{error:Sl,activeDownstream:F,winningSide:p};if(p&&p===I.winningSide&&u&&!L)return{context:"winningSide must include directing matchUpStatus",error:Sl,directingMatchUpStatus:L,matchUpStatus:u}}let{schedule:v}=t;if(v){let V=Kp({disableNotice:!0,tournamentRecords:o,tournamentRecord:i,drawDefinition:c,matchUpId:m,schedule:v});if(V.error)return V}let B=!A&&!y&&p&&I.winningSide&&I.winningSide!==p;if(r&&B&&I.roundPosition)return $v(t);let H=p&&!E||t.projectedWinningSide;kn({activeDownstream:F,matchUpWinner:H,method:e,winningSide:p});let j=!F&&qv(t)||H&&xV(t)||L&&Kv(t)||{error:Zy};return _({result:j,stack:e})}function xV(t){let{matchUp:e,winningSide:r,matchUpTieId:n,dualWinningSideChange:o}=t;return r===e.winningSide||n&&!o?Kv(t):_({stack:"winningSideWithDownstreamDependencies",result:{error:Dl},context:{winningSide:r,matchUp:e}})}function Kv(t){let{tournamentRecord:e,matchUp:r,event:n}=t,o=t.isCollectionMatchUp&&r.winningSide&&!t.winningSide&&!Ie({score:t.score}),i=t.isCollectionMatchUp?t.matchUpStatus||o&&zt||me:t.matchUpStatus||me,s=t.removeScore||[Wo,_t].includes(i)&&![_o,$r].includes(i),a=Cn({...t,matchUpStatus:i,removeWinningSide:o,context:"sms",removeScore:s});if(a.error)return a;if(t.isCollectionMatchUp){let{matchUpTieId:c,drawDefinition:u,matchUpsMap:p}=t,m=zn({appliedPolicies:t.appliedPolicies,matchUpId:c,tournamentRecord:e,drawDefinition:u,matchUpsMap:p,event:n});if(m.error)return m;Object.assign(a,{tieMatchUpResult:m})}return a}function vN({tournamentRecord:t,drawDefinition:e,matchUpId:r,event:n}){if(!e)return{error:X};let{matchUp:o}=xt({drawDefinition:e,matchUpId:r,event:n});return o?.matchUpType!==ln?{error:Je}:La({enableAutoCalc:!0,tournamentRecord:t,drawDefinition:e,matchUpId:r,event:n})}function xN({drawDefinition:t,event:e,matchUpId:r}){if(!t)return{error:X};if(!r)return{error:ke};let{matchUp:n}=xt({drawDefinition:t,event:e,matchUpId:r});return n?or({name:Am,element:n}):{error:Oe}}function zv({substituteParticipantId:t,existingParticipantId:e,tournamentRecord:r,drawDefinition:n,sideNumber:o,matchUpId:i,event:s}){let a="substituteParticipant";if(!n)return{error:X};if(!i)return{error:ke};if(!e||!t)return _({result:{error:oe},stack:a});let{matchUp:c}=xt({drawDefinition:n,matchUpId:i,event:s});if(!c)return{error:Oe};if(!c.collectionId)return _({result:{error:Je},stack:a});let u=Ae({drawDefinition:n}),{matchUps:p}=re({tournamentParticipants:r?.participants,inContext:!0,drawDefinition:n,matchUpsMap:u}),m=p?.find(g=>g.matchUpId===i),l=p?.find(g=>g.matchUpId===m?.matchUpTieId)?.sides?.find(g=>g.participant.individualParticipants.some(({participantId:I})=>I===e));return!l||o&&l.sideNumber!==o?{error:pn}:l.participant?.individualParticipants?.map(gt).filter(g=>g!==e)?.includes(t)?xg({newParticipantId:t,tieMatchUpId:i,existingParticipantId:e,substitution:!0,tournamentRecord:r,drawDefinition:n,event:s}):_({result:{error:pn},stack:a})}function wN(t){return zv(t)}function LN({drawDefinition:t,matchUpId:e,event:r}){if(!t)return{error:X};let{matchUp:n}=xt({drawDefinition:t,matchUpId:e,event:r});return St({extension:{name:rc,value:!0},element:n})}function FN(t){let e="setMatchUpFormat",r=lt(t,[{tournamentRecord:!0},{[yn]:D=>Sr({matchUpFormat:D}),[En]:Ya,matchUpFormat:!0}]);if(r.error)return _({result:r,stack:e});let{tournamentRecord:n,drawDefinition:o,scheduledDates:i,stageSequences:s,matchUpFormat:a,structureId:c,eventType:u,matchUpId:p,eventId:m,stages:d,drawId:l,event:f,force:g}=t;if(i&&!Array.isArray(i))return _({result:{error:G,scheduledDates:i},stack:e});if(u&&!cu([ao,Kr],u))return _({result:{error:No},stack:e});let I=0,h=t.structureIds||c&&[c].filter(Boolean)||[],S=t.eventIds||m&&[m].filter(Boolean)||[],T=t.drawIds||l&&[l].filter(Boolean)||[];if((c||h?.length)&&!o)return _({result:{error:X},stack:e});if(l&&p&&o){let D=_d({tournamentRecord:n,drawDefinition:o,matchUpFormat:a,structureIds:h,structureId:c,matchUpId:p});if(D.error)return D;I+=1}let A=D=>{let y=[];for(let E of D.structures||[]){if(Array.isArray(d)&&!d.includes(E.stage)||Array.isArray(s)&&!s.includes(E.stageSequence)||h?.length&&!h.includes(E.structureId))continue;h?.length&&E.matchUpFormat!==a&&(E.matchUpFormat=a,y.push(E.structureId),I+=1);let U=((g||i)&&At({matchUpFilters:{matchUpStatuses:[zt]},structure:E}).matchUps)??[],M=(i&&At({matchUpFilters:{matchUpStatuses:[zt]},contextFilters:{scheduledDates:i},afterRecoveryTimes:!1,inContext:!0,structure:E}).matchUps)??[];if(U?.length){let P=M?M.map(fe):U.map(fe);for(let N of U)P.includes(N.matchUpId)&&(N.matchUpFormat=i?.length?a:void 0,It({tournamentId:n?.tournamentId,eventId:f?.eventId,context:e,drawDefinition:D,matchUp:N}))}}return!y.length&&D.matchUpFormat!==a&&(D.matchUpFormat=a,I+=1),y};for(let D of n?.events||[])if(!(S?.length&&!S.includes(D.eventId)||u&&u!==D.eventType||u===Fe))if(Array.isArray(s)||Array.isArray(d)||h?.length||T?.length)for(let y of D.drawDefinitions||[]){if(Array.isArray(T)&&!T.includes(y.drawId))continue;let E=A(y);bt({structureIds:E,drawDefinition:y})}else D.matchUpFormat!==a&&(D.matchUpFormat=a,I+=1);return I?{...R,modificationsCount:I}:{...R,info:Ns}}function Lg({inheritance:t=!0,tournamentRecord:e,drawDefinition:r,matchUpId:n,event:o}){if(!r)return{error:X};let i=xt({drawDefinition:r,matchUpId:n})?.matchUp;if(!i?.tieMatchUps)return{error:Je};let s=xt({inContext:!0,drawDefinition:r,matchUpId:n,event:o})?.matchUp,a=0;return(i?.sides||[]).forEach(c=>{c.lineUp&&delete c.lineUp}),(s?.sides||[]).forEach(c=>{if(a+=1,t===!1){let u=s?.tieFormat,p=c.participantId;u&&p&&Fi({drawDefinition:r,participantId:p,lineUp:[],tieFormat:u})}It({tournamentId:e?.tournamentId,context:"resetMatchUpLineUps",eventId:o?.eventId,drawDefinition:r,matchUp:i})}),{...R,modificationsCount:a}}function IA(t){let{matchUpFormat:e,matchUpStatus:r,winningSide:n,score:o}=t;if(!o)return{sets:[]};let i=o.sets||[],s=wo({winnerFirst:!1,matchUpFormat:e,matchUpStatus:r,sets:i}),a=wo({winnerFirst:!1,reversed:!0,matchUpFormat:e,matchUpStatus:r,sets:i}),c=wo({matchUpFormat:e,matchUpStatus:r,winningSide:n,sets:i}),u=s===c?a:s;return n&&(s=n===1?c:u,a=n===2?c:u),{score:{sets:i,scoreStringSide1:s,scoreStringSide2:a}}}function xu(t){let e=lt(t,[{[Co]:!0,[Yr]:!0}]);if(e.error)return e;let r=Xr(t);if(!t.drawDefinition){let h=t.tournamentRecord??(t.tournamentId&&r[t.tournamentId]);t.tournamentRecord||(t.tournamentRecord=h);let S=We({eventId:t.eventId,drawId:t.drawId,tournamentRecord:h});if(S.error)return S;S.drawDefinition&&(t.drawDefinition=S.drawDefinition),t.event=S.event}let{disableScoreValidation:n,policyDefinitions:o,tournamentRecord:i,disableAutoCalc:s,enableAutoCalc:a,drawDefinition:c,matchUpFormat:u,matchUpId:p,schedule:m,event:d,notes:l}=t,{policy:f}=$o({policyType:vn,tournamentRecord:i,event:d}),g=t.allowChangePropagation!==void 0&&t.allowChangePropagation||f?.allowChangePropagation!==void 0&&f.allowChangePropagation||void 0,{outcome:I}=t;if(I?.winningSide&&![1,2].includes(I.winningSide))return{error:im};if(u){let h=_d({tournamentRecord:i,drawDefinition:c,matchUpFormat:u,matchUpId:p,event:d});if(h.error)return h}if(I?.score?.sets&&!I.score.scoreStringSide1){let{score:h}=IA(I);I.score=h,I.score.sets=I.score.sets.filter(S=>S.side1Score||S.side2Score||S.side1TiebreakScore||S.side2TiebreakScore)}return La({matchUpStatusCodes:I?.matchUpStatusCodes,matchUpStatus:I?.matchUpStatus,winningSide:I?.winningSide,allowChangePropagation:g,disableScoreValidation:n,score:I?.score,tournamentRecords:r,policyDefinitions:o,tournamentRecord:i,disableAutoCalc:s,enableAutoCalc:a,drawDefinition:c,matchUpFormat:u,matchUpId:p,schedule:m,event:d,notes:l})}function GN(t){if(!t?.outcomes)return{error:et};if(!Array.isArray(t.outcomes))return{error:et,info:{outcomes:t.outcomes}};let e=t.tournamentRecords||t.tournamentRecord&&{[t.tournamentRecord.tournamentId]:t.tournamentRecord}||{},r=t.outcomes??[],n=r.reduce((o,i)=>o.includes(i.tournamentId)?o:o.concat(i.tournamentId),[]);for(let o of n){let i=e[o];if(!i)return{error:W};let s=r.filter(a=>a.tournamentId===o);if(s.length){let a=wV({outcomes:s,tournamentRecord:i});if(a.error)return a}}return{...R}}function wV(t){let{tournamentRecords:e,tournamentRecord:r,outcomes:n,policyDefinitions:o}=t,i={};n.forEach(s=>{let{eventId:a}=s;i[a]||(i[a]=[]),i[a].push(s)});for(let s of Object.keys(i)){let{event:a}=We({tournamentRecord:r,eventId:s});for(let c of i[s]){let{drawId:u}=c,p=a?.drawDefinitions?.find(m=>m.drawId===u);if(p&&u){let{matchUpFormat:m,matchUpId:d}=c,l=xu({schedule:c?.schedule,tournamentRecords:e,policyDefinitions:o,tournamentRecord:r,drawDefinition:p,matchUpFormat:m,matchUpId:d,outcome:c,drawId:u,event:a});if(l.error)return l}}}return{...R}}function Qv({drawDefinition:t,matchUpId:e,outcome:r,matchUp:n}){if(!n&&!t)return{error:X};if(!r)return{error:et,info:"missing outcome"};if(!n&&!e)return{error:sr};if(!n){let i=xt({drawDefinition:t,matchUpId:e});if(i.error)return i;n=i.matchUp}return typeof r!="object"||!r.score?.scoreStringSide1||!r.score?.scoreStringSide2?{error:G}:St({element:n,extension:{name:Am,value:r}})}function kN(t){return Qv(t)}function Fg(t){let e="resetTieFormat",{drawDefinition:r,event:n,uuids:o}=t,i=lt(t,[{[An]:!0,[Co]:!0}],e);if(i.error)return i;let s=xa(t,[{[sa]:fo}]);if(s[Ms])return s;let a=t.tournamentRecord?.tournamentId,{matchUp:c,structure:u}=s?.matchUp??{};if(!c?.tieMatchUps)return _({result:{error:Je},info:"Must be a TEAM matchUp",stack:e});if(!c.tieFormat)return{...R};let p=je({structure:u,drawDefinition:r,event:n})?.tieFormat;if(!p)return _({result:{error:Ke},info:"No inherited tieFormat",stack:e});let m=[],d=[],l=[],f=[];for(let g of p.collectionDefinitions){let{matchUpCount:I,collectionId:h}=g;d.push(h);let S=(c.tieMatchUps||[]).filter(T=>T.collectionId===h);if(S.length>I)S.sort((T,A)=>(T.matchUpStatus===zt?1:0)-(A.matchUpStatus===zt?1:0)),l.push(...S.slice(0,I)),m.push(...S.slice(3).map(fe));else if(l.push(...S),S.length<I){let T=I-S.length,A=hu({collectionDefinition:g,matchUpsLimit:T,matchUp:c,uuids:o});f.push(...A)}}for(let g of c?.tieMatchUps||[])g.collectionId&&!d.includes(g.collectionId)&&m.push(g.matchUpId);return f.length&&(l.push(...f),So({eventId:n?.eventId,matchUps:f,drawDefinition:r,tournamentId:a})),m.length&&wn({matchUpIds:m,eventId:n?.eventId,drawDefinition:r,tournamentId:a}),c&&(c.tieMatchUps=l,c.tieFormatId=void 0,c.tieFormat=void 0,It({structureId:u?.structureId,eventId:n?.eventId,context:e,drawDefinition:r,tournamentId:a,matchUp:c})),{...R,newMatchUps:f,deletedMatchUpIds:m}}function Gg(t){let{tournamentRecord:e,drawDefinition:r,matchUpId:n,event:o}=t,i="resetScorecard";if(!r)return _({result:{error:X},stack:i});if(!n)return _({result:{error:ke},stack:i});if(!$e(n))return _({result:{error:G,matchUpId:n},stack:i});let s=Ae({drawDefinition:r}),{matchUps:a}=re({nextMatchUps:!0,inContext:!0,drawDefinition:r,matchUpsMap:s}),c=s.drawMatchUps.find(I=>I.matchUpId===n),u=a?.find(I=>I.matchUpId===n);if(!c||!a)return{error:Oe};if(c.matchUpType!==kr)return{error:Je};let p=er({inContextDrawMatchUps:a,drawDefinition:r,matchUpId:n}),m=u?.structureId,{structure:d}=st({drawDefinition:r,structureId:m});if(Object.assign(t,{inContextDrawMatchUps:a,inContextMatchUp:u,matchUpsMap:s,targetData:p,structure:d,matchUp:c}),Ai(t))return{error:Dl};if(c.tieMatchUps?.length)for(let I of c.tieMatchUps){let h=La({matchUpId:I.matchUpId,matchUpTieId:n,winningSide:void 0,removeScore:!0,tournamentRecord:e,drawDefinition:r,event:o});if(h.error)return _({result:h,stack:i})}let f=Pt({tournamentRecord:e,drawDefinition:r,event:o})?.appliedPolicies,g=zn({event:t.event,removeScore:!0,tournamentRecord:e,appliedPolicies:f,drawDefinition:r,matchUpsMap:s,matchUpId:n});if(g.error)return _({result:g,stack:i});if(t.tiebreakReset&&!g.tieFormatRemoved){let I=je({drawDefinition:r,structure:d,event:o})?.tieFormat;if(c.tieFormat&&I){let{matchUpCountDifference:h,descendantDifferences:S,ancestorDifferences:T,valueDifference:A}=Go({descendant:c.tieFormat,ancestor:I});if(S.collectionIds.length===1&&!T.collectionIds.length&&!T.groupsCount&&h===1&&A===1){let D=Fg({tournamentRecord:e,drawDefinition:r,matchUpId:n,event:o});if(D.error)return D}}}return{...R}}function VN(t){let e=lt(t,[{[Yr]:!0,[Cs]:!0},{[Ja]:{[Xa]:!1,roundNumbers:!1},[_I]:"At least one must be provided",[to]:Er}]);if(e.error)return e;let r=pS(t);if(r.error)return r;let{matchUpIds:n}=r,o=ie(kr)(t.event.eventType),{tournamentRecord:i,drawDefinition:s,event:a}=t;for(let c of n){if(o){let p=Gg({tiebreakReset:!0,tournamentRecord:i,drawDefinition:s,matchUpId:c,event:a});if(p.error||t.removeAssignments&&Lg({inheritance:!1,drawDefinition:s,matchUpId:c}).error)return p}let u=La({winningSide:void 0,removeScore:!0,tournamentRecord:i,drawDefinition:s,matchUpId:c,event:a});if(u.error)return u;if(t.removeAssignments){let p=wg({...t,matchUpId:c});if(p.error)return p}}return{...R}}function Xv({drawDefinition:t,finishingOrder:e}){if(!t)return{error:X};let r="setOrderOfFinish";if(!Array.isArray(e))return _({info:Nn("finishingOrder"),result:{error:G},stack:r});let{completedMatchUps:n,matchUpsMap:o}=Vs({inContext:!0,drawDefinition:t}),i=n?.map(fe)??[],s=e.map(fe),{matchUpTypes:a,roundNumbers:c,structureIds:u,matchUpTieIds:p}=(n??[]).filter(({matchUpId:S})=>s.includes(S)).reduce((S,T)=>{let{matchUpTieId:A,matchUpType:D,roundNumber:y,structureId:E}=T;return S.matchUpTypes.includes(D)||S.matchUpTypes.push(D),S.roundNumbers.includes(y)||S.roundNumbers.push(y),S.structureIds.includes(E)||S.structureIds.push(E),S.matchUpTieIds.includes(A)||S.matchUpTieIds.push(A),S},{matchUpTypes:[],roundNumbers:[],structureIds:[],matchUpTieIds:[]});if(a.length>1||p.length>1||c.length>1||u.length>1)return _({info:"matchUpType, structureId and roundNumber must be equivalent",result:{error:G},stack:r});let m,d,l={},f=[],g=[];if(!e.every(({orderOfFinish:S,matchUpId:T})=>(f.push(T),S&&g.push(S),l[T]=S,m=i.includes(T),d=S===void 0||ft(S)&&Math.floor(S)>0,m&&d)))return _({result:{error:m?G:oa},info:!m&&"matchUps must be completed"||!d&&"orderOfFinish must be integer > 0 or undefined"||void 0,stack:r});let h=n?.filter(S=>S.structureId===u[0]&&S.roundNumber===c[0]&&S.matchUpType===a[0]&&S.matchUpTieId===p[0]&&!f.includes(S.matchUpId));for(let S of h??[]){let{orderOfFinish:T}=S||{};if(T){if(!ft(T))return _({context:{orderOfFinish:T,matchUp:S},result:{error:G},stack:r});g.push(T)}}if(EI(g).length!==g.length||Math.max(...g)>g.length)return _({info:"Values not unique or greater than expected number of values",result:{error:G},stack:r});if(u.length){let S=uu({matchUpFilters:{matchUpIds:s},structureId:u[0],drawDefinition:t,matchUpsMap:o});if(S.error)return _({result:S,stack:r});S.completedMatchUps?.forEach(T=>T.orderOfFinish=l[T.matchUpId])}return{...R}}function BN(t){return Xv(t)}function HN({tournamentRecord:t,drawDefinition:e,matchUpId:r,lineUps:n,event:o}){if(!t)return{error:W};if(!e)return{error:pr};if(typeof r!="string")return{error:Je};if(!Array.isArray(n))return{error:G,lineUps:n};let i="applyLineUps",s=t.participants||[],a=xt({tournamentParticipants:s,inContext:!0,drawDefinition:e,matchUpId:r});if(a.error)return a;if(!a.matchUp)return{error:Oe};let{matchUp:c,structure:u}=a,{drawPositions:p,matchUpType:m}=c;if(m!==Bt)return{error:Je};if(!p?.length)return{error:Wa};let d=je({matchUp:c,drawDefinition:e,structure:u,event:o})?.tieFormat,l={};for(let g of n){if(!Array.isArray(g))return{error:G,lineUp:g};let I={},h=[];for(let y of g){if(typeof y!="object")return{error:G,lineUpAssignment:y};let{participantId:E,collectionAssignments:U=[]}=y;if(!Array.isArray(U))return{error:G,collectionAssignments:U};let M=s.find(N=>N.participantId===E);if(!M)return{error:Zt};if(M.participantType!==ht)return{error:nn};let P=c.sides?.find(N=>N.participant?.individualParticipantIds?.includes(E))?.sideNumber;P&&h.push(P);for(let N of U){if(typeof N!="object")return{error:G,collectionAssignment:N};let{collectionId:C,collectionPosition:O}=N,b=d?.collectionDefinitions?.find(F=>F.collectionId===C);if(!b)return{error:G,collectionId:C};let x=`${C}-${O}`;I[x]||(I[x]=[]);let w=I[x].length;if(ie(Xt)(b.matchUpType)&&w||b.matchUpType===Gt&&w>1)return{info:"Excessive collectionPosition assignments",error:G};I[x].push(E)}}let S=Object.values(I);for(let y of S)if(y.length===2){let{participant:E}=tn({tournamentParticipants:s,participantIds:y});if(!E){let M=gn({participant:{participantType:dt,participantRole:Ge,individualParticipantIds:y},pairOverride:!0,tournamentRecord:t});if(M.error)return M}}let T=dr(h),A=(T[1]||0)>(T[2]||0)&&1||(T[2]||0)>(T[1]||0)&&2||void 0,D=Object.keys(l).map(y=>parseInt(y));A&&!D.includes(A)&&(l[A]=g)}if(!Object.keys(l).length)return{error:wl};if(a=xt({drawDefinition:e,matchUpId:r}),a.error)return a;if(!a.matchUp)return{error:Oe};let{matchUp:f}=a;f.sides||(f.sides=[]);for(let g of[1,2]){let I=f.sides.find(S=>S.sideNumber===g),h=l[g];if(h)I?I.lineUp=h:f.sides.push({lineUp:h,sideNumber:g});else continue}return It({tournamentId:t?.tournamentId,context:i,drawDefinition:e,matchUp:f}),{...R}}var $g={};Jt($g,{anonymizeTournamentRecord:()=>XN,generate:()=>QN,generateEventWithDraw:()=>Jp,generateOutcome:()=>jg,generateOutcomeFromScoreString:()=>kg,generateParticipants:()=>vc,generateTournamentRecord:()=>zN,modifyTournamentRecord:()=>JN,mutate:()=>ZN});var QN={};Jt(QN,{generateEventWithDraw:()=>Jp,generateOutcome:()=>jg,generateOutcomeFromScoreString:()=>kg,generateParticipants:()=>vc,generateTournamentRecord:()=>zN});function kg(t){let{matchUpFormat:e,matchUpStatus:r,winningSide:n,scoreString:o}=t;if(!o)return{outcome:{...Tu,winningSide:n,matchUpStatus:r}};if(n&&![1,2,void 0].includes(n))return{error:G,winningSide:n};let i=o&&Rd({scoreString:o}),s={},a=wo({sets:i,matchUpFormat:e}),c=wo({sets:i,reversed:!0,matchUpFormat:e});return n===2?(s.scoreStringSide1=c,s.scoreStringSide2=a):(s.scoreStringSide1=a,s.scoreStringSide2=c),s.sets=Rd({scoreString:s.scoreStringSide1}),rt({outcome:{matchUpStatus:r,winningSide:n,score:s}})}function tl({matchUpScheduleTimes:t,matchUpDependencies:e,allDateMatchUpIds:r,matchUp:n}){let i=(e?.[n.matchUpId]?.matchUpIds||[]).filter(a=>r.includes(a)).filter(a=>!t[a]);return{dependenciesScheduled:!i?.length,remainingDependencies:i}}function ta({matchUpPotentialParticipantIds:t,matchUpNotBeforeTimes:e,timeAfterRecovery:r,matchUp:n}){let{individualParticipantIds:o}=eu(n);r=r??n.schedule?.timeAfterRecovery;let i=u=>{t[u]||(t[u]=[]),t[u]=pt(t[u].concat(...o))},s=u=>{r&&(!e[u]||r>e[u])&&(e[u]=r)},a=n.winnerTo?.matchUpId||n.winnerMatchUpId;a&&(r&&s(a),i(a));let c=n.loserTo?.matchUpId||n.loserMatchUpId;c&&(r&&s(c),i(c)),n.sidesTo?.length&&n.sidesTo.forEach(({matchUpId:u})=>{u&&(r&&s(u),i(u))})}function Fa({individualParticipantProfiles:t,participantId:e}){t[e]||(t[e]={typeChangeTimeAfterRecovery:void 0,timeAfterRecovery:void 0,priorMatchUpType:void 0,potentialRecovery:{},potentialCounted:{},potentialBookings:{},bookings:[],counters:{}})}function Jv({individualParticipantProfiles:t,recoveryValue:e,participantId:r,scheduleTime:n,drawId:o}){t[r].potentialRecovery[o]||(t[r].potentialRecovery[o]=[]),t[r].potentialRecovery[o].push(e),t[r].potentialBookings[o]||(t[r].potentialBookings[o]=[]),t[r].potentialBookings[o].push({timeAfterRecovery:e,scheduleTime:n})}function bc({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,typeChangeRecoveryMinutes:r,averageMatchUpMinutes:n=0,matchUpNotBeforeTimes:o,matchUpDependencies:i,recoveryMinutes:s=0,scheduleTime:a,matchUp:c}){let u=$t(c?.schedule?.endTime),p=u?br(u,ct(s)):br(a,ct(n)+ct(s)),m=r&&(u?br($t(u),r):br(a,ct(n)+ct(r))),d=i?.[c.matchUpId]?.participantIds||[],l=(c.roundPosition&&t[c.matchUpId]||[]).flat();d.forEach(f=>{Fa({individualParticipantProfiles:e,participantId:f});let I=e[f].priorMatchUpType!==c.matchUpType&&m||p;l.includes(f)?Jv({individualParticipantProfiles:e,drawId:c.drawId,recoveryValue:I,participantId:f,scheduleTime:a}):(e[f].timeAfterRecovery=I,e[f].bookings.push({scheduleTime:a,timeAfterRecovery:I}))}),ta({matchUpPotentialParticipantIds:t,matchUpNotBeforeTimes:o,timeAfterRecovery:p,matchUp:c})}function hA({matchUpScheduleTimes:t,matchUpDependencies:e,scheduleTime:r,matchUpId:n,details:o}){let i,s=o.minutesMap?.[n]?.recoveryMinutes,c=(o.minutesMap?.[n]?.averageMinutes||0)+(s||0),u=br(r,c),p=e?.[n]?.dependentMatchUpIds||[];if(p.length){let m=p.reduce((d,l)=>{let f=t[l];if(!f)return d;let g={scheduleTime:f,matchUpId:l};return f&&!d.matchUpId||Vt(f)<Vt(d.scheduleTime)?g:d},{});m.scheduleTime&&Vt(u)>Vt(m.scheduleTime)&&(i=m)}return{scheduledDependent:i}}function Zv(t){let{sides:e,matchUpType:r}=t||{};return(e||[]).map(n=>r===Gt&&(n?.participant?.individualParticipants||[])||n?.participant&&[n.participant]||[]).flat()}var Oc="DO_NOT_SCHEDULE",tx={DO_NOT_SCHEDULE:Oc};function el({averageMatchUpMinutes:t=90,requestConflicts:e={},potentials:r=!0,personRequests:n,scheduleTime:o,scheduleDate:i,matchUp:s}){let a=Zv(s).map(({person:l})=>l?.personId);if(r){let l=(s?.potentialParticipants||[]).flat().map(({person:f})=>f?.personId);a.push(...l)}let c=a.map(l=>n[l]?.map(f=>({...f,personId:l}))).filter(Boolean).flat().filter(l=>l.requestType===Oc&&_n(i,l.date)),u=[],p=s?.matchUpId,m=we($t(o),Ut(i)),d=$t(Ql(m,t).toISOString());for(let l of c){let{requestId:f,startTime:g,endTime:I}=l;(o>g&&o<I||d>g&&d<I)&&(u.push({matchUpId:p,request:l,scheduleTime:o}),e[f]?(e[f].scheduleTimes.includes(o)||e[f].scheduleTimes.push(o),e[f].matchUpIds.includes(p)||e[f].matchUpIds.push(p)):e[f]={request:l,scheduleTimes:[o],matchUpIds:[p]})}return{conflicts:u}}function Vg({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,matchUp:r,value:n}){let{matchUpType:o}=r,{individualParticipantIds:i}=eu(r),a=(t[r.matchUpId]||[]).filter(u=>!xe(u,i)).flat();[...i,...a].forEach(u=>{if(Fa({individualParticipantProfiles:e,participantId:u}),!e[u].potentialCounted[r.drawId]){let p=e[u].counters;p[o]?p[o]+=n:n>0&&(p[o]=n),p[$n]?p[$n]+=n:n>0&&(p[$n]=n),a.includes(u)&&(e[u].potentialCounted[r.drawId]=!0)}})}function ex({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,dateScheduledMatchUpIds:r,greatestAverageMinutes:n,dateScheduledMatchUps:o,matchUpNotBeforeTimes:i,matchUpScheduleTimes:s,matchUpDependencies:a,clearScheduleDates:c,scheduleDate:u,minutesMap:p,matchUps:m}){let d=[];r||(o=m?.filter(g=>{let I=g.schedule||{},h=g.matchUpStatus===Dt;return h&&d.push({tournamentId:g.tournamentId,matchUpId:g.matchUpId}),!h&&va({schedule:I})&&(!u||g.schedule.scheduledDate===u)}),r=o.map(fe));let l=Array.isArray(c)?c.includes(u):c,f=l?[]:m.filter(({matchUpId:g})=>r.includes(g));for(let g of f){Vg({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,value:1,matchUp:g});let I=g.schedule?.scheduledTime;if(I){s[g.matchUpId]=I;let h=p?.[g.matchUpId]?.recoveryMinutes;bc({individualParticipantProfiles:e,matchUpPotentialParticipantIds:t,matchUpNotBeforeTimes:i,matchUpDependencies:a,averageMatchUpMinutes:n,recoveryMinutes:h,scheduleTime:I,matchUp:g})}}return{dateScheduledMatchUpIds:r,byeScheduledMatchUpDetails:d,dateScheduledMatchUps:o,clearDate:l}}function rx({matchUpPotentialParticipantIds:t,scheduleCompletedMatchUps:e,dateScheduledMatchUpIds:r,matchUpNotBeforeTimes:n,matchUpScheduleTimes:o,orderedMatchUpIds:i,clearDate:s,matchUps:a}){let c=Object.keys(o),u=i.map(m=>a.find(d=>d.matchUpId===m)).filter(Boolean).filter(m=>{let d=!s&&(r.includes(m.matchUpId)||c.includes(m.matchUpId)),l=[Dt,Ot,me,$r,lr,_t,ge,Ne].includes(m?.matchUpStatus);return e||!d&&!m.winningSide&&!l}),{matchUpMap:p}=u.reduce((m,d)=>{let{drawId:l,tournamentId:f}=d;return m.matchUpMap[f]||(m.matchUpMap[f]={}),m.matchUpMap[f][l]?m.matchUpMap[f][l].push(d):m.matchUpMap[f][l]=[d],ta({matchUpPotentialParticipantIds:t,matchUpNotBeforeTimes:n,matchUp:d}),m},{matchUpMap:{}});return{matchUpsToSchedule:u,matchUpMap:p}}function zp({defaultRecoveryMinutes:t=0,averageMatchUpMinutes:e=90,dateScheduledMatchUps:r,tournamentRecords:n,venueIds:o=[],periodLength:i,scheduleDate:s,matchUps:a}){if(typeof n!="object")return{error:Ft};if(!Ur(a)&&!Array.isArray(r))return{error:Sn};i=i??vu({recoveryMinutes:t,averageMatchUpMinutes:e});let c=Object.assign({},...Object.values(n).map(d=>(d.events??[]).map(l=>{let{scheduleTiming:f}=Sa({tournamentRecord:d,event:l});return{[l.eventId]:{event:l,scheduleTiming:f}}})).flat()),u={averageTimes:[{minutes:{default:e}}],recoveryTimes:[{minutes:{default:t}}]};r||(r=a?.filter(d=>{let l=d.schedule;return va({schedule:l})&&(!s||d.schedule.scheduledDate===s)}));let p=r?.filter(d=>(!o.length||o.includes(d.schedule.venueId))&&d.matchUpStatus!==Dt);return{bookings:p?.map(({eventId:d,schedule:l,matchUpFormat:f})=>{let{event:g,scheduleTiming:I}=c[d],h=g?.eventType,S={...I,defaultTiming:u,matchUpFormat:f},{averageMinutes:T,recoveryMinutes:A}=dp({timingDetails:S,eventType:h}),{courtId:D,venueId:y}=l,E=$t(l.scheduledTime),U=br(E,T);return{recoveryMinutes:A,averageMinutes:T,periodLength:i,startTime:E,courtId:D,endTime:U,venueId:y}}).filter(Boolean),relevantMatchUps:p,dateScheduledMatchUps:r}}function nx({calculateStartTimeFromCourts:t=!0,remainingScheduleTimes:e,defaultRecoveryMinutes:r,averageMatchUpMinutes:n,clearScheduleDates:o,tournamentRecords:i,tournamentRecord:s,periodLength:a,scheduleDate:c,startTime:u,venueIds:p,matchUps:m,endTime:d}){if(s&&!i&&(i={[s.tournamentId]:s}),typeof i!="object"||!Object.keys(i).length)return{error:Ft};a=a??vu({recoveryMinutes:r,averageMatchUpMinutes:n});let{courts:l,venues:f}=po({dates:[c],ignoreDisabled:!0,tournamentRecords:i}),g=l?.filter(y=>!p||p.includes(y.venueId))??[];u=u??Cc({courts:g,scheduleDate:c,startTime:!0}),d=d??Cc({courts:g,scheduleDate:c,endTime:!0});let{bookings:I,dateScheduledMatchUps:h}=zp({defaultRecoveryMinutes:r,averageMatchUpMinutes:n,tournamentRecords:i,scheduleDate:c,periodLength:a,venueIds:p,matchUps:m}),S={calculateStartTimeFromCourts:t,remainingScheduleTimes:e,averageMatchUpMinutes:n,clearScheduleDates:o,date:c,periodLength:a,startTime:u,bookings:I,endTime:d,courts:g},{scheduleTimes:T}=Kd(S),A=p?.length===1&&p[0]||f?.length===1&&f[0].venueId||void 0;return{dateScheduledMatchUpIds:h?.map(Pr("matchUpId")),dateScheduledMatchUps:h,scheduleTimes:T,venueId:A}}function ox({scheduledRoundsDetails:t,greatestAverageMinutes:e,garmanSinglePass:r}){let n=[],o=[],i,s,a,c;for(let u of t.filter(Boolean))c||(c=u.hash),(u.hash===c||r)&&(o=o.concat(u.matchUpIds)),u.hash!==c&&!r&&(c=u.hash,n.push({averageMinutes:a,recoveryMinutes:s,roundPeriodLength:i,matchUpIds:o}),o=u.matchUpIds),a=r?e:u.averageMinutes,s=u.recoveryMinutes,i=u.roundPeriodLength;return o.length&&n.push({matchUpIds:o,roundPeriodLength:i,recoveryMinutes:s,averageMinutes:a}),{groupedRounds:n}}function SA({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,scheduleCompletedMatchUps:r,containedStructureIds:n,matchUpNotBeforeTimes:o,matchUpScheduleTimes:i,matchUpDependencies:s,clearScheduleDates:a,tournamentRecords:c,periodLength:u,scheduleDate:p,useGarman:m,matchUps:d,courts:l,venues:f}){let g={},I=[],h=[],S=[];for(let T of f){let{rounds:A=[],venueId:D}=T,{scheduledRoundsDetails:y,greatestAverageMinutes:E,orderedMatchUpIds:U,minutesMap:M}=bu({scheduleCompletedMatchUps:r,containedStructureIds:n,tournamentRecords:c,periodLength:u,matchUps:d,rounds:A});S.push(...U??[]);let{groupedRounds:P}=ox({scheduledRoundsDetails:y,greatestAverageMinutes:E,garmanSinglePass:!0}),N,C,O=[];m&&({scheduleTimes:O,dateScheduledMatchUpIds:N,dateScheduledMatchUps:C}=nx({averageMatchUpMinutes:P[0]?.averageMinutes,scheduleDate:Ut(p),venueIds:[T.venueId],clearScheduleDates:a,tournamentRecords:c,periodLength:u,matchUps:d}));let b=ex({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,dateScheduledMatchUpIds:N,greatestAverageMinutes:E,matchUpNotBeforeTimes:o,matchUpScheduleTimes:i,matchUpDependencies:s,clearScheduleDates:a,scheduleDate:p,minutesMap:M,matchUps:d});({dateScheduledMatchUpIds:N,dateScheduledMatchUps:C}=b);let{byeScheduledMatchUpDetails:x,clearDate:w}=b;x?.length&&h.push(...x);let{matchUpsToSchedule:F,matchUpMap:L}=rx({matchUpPotentialParticipantIds:t,scheduleCompletedMatchUps:r,dateScheduledMatchUpIds:N,matchUpNotBeforeTimes:o,matchUpScheduleTimes:i,orderedMatchUpIds:U,clearDate:w,matchUps:d}),v=l.filter(B=>B.venueId===D);g[D]={previousRemainingScheduleTimes:[],courtsCount:v.length,greatestAverageMinutes:E,scheduledRoundsDetails:y,dateScheduledMatchUps:C,matchUpsToSchedule:F,scheduleTimes:O,groupedRounds:P,venueCourts:v,minutesMap:M,matchUpMap:L},a||I.push(...N)}return{allDateScheduledByeMatchUpDetails:h,allDateScheduledMatchUpIds:I,venueScheduledRoundDetails:g,allDateMatchUpIds:S}}function ix(t,e){let r=Vt(t.scheduleTime),n=Vt(t.timeAfterRecovery),o=Vt(e.scheduleTime),i=Vt(e.timeAfterRecovery),s=r===o||n===i,a=r>o&&r<i,c=o>r&&o<n,u=n>o&&n<i,p=i>r&&i<n;return rt({hasOverlap:s||a||u||c||p,startAisContained:a,endAisContained:u,startBisContained:c,endBisContained:p},!0)}function rl({individualParticipantProfiles:t,matchUpNotBeforeTimes:e,matchUpDependencies:r,scheduleTime:n,matchUp:o,details:i}){let s=(r?.[o.matchUpId]?.participantIds||[]).flat(),a=i?.minutesMap?.[o.matchUpId]?.averageMinutes||0,c=i?.minutesMap?.[o.matchUpId]?.recoveryMinutes||0,u=s.every(f=>{Fa({individualParticipantProfiles:t,participantId:f});let g=t[f];if(!g.timeAfterRecovery)return!0;let I=$t(o?.schedule?.endTime),h=I?br(I,ct(c)):br(n,ct(a)+ct(c));return!!![...Object.keys(g.potentialBookings).filter(D=>D!==o.drawId).map(D=>g.potentialBookings[D]).flat(),...g.bookings].find(D=>ix({scheduleTime:n,timeAfterRecovery:h},D).hasOverlap)}),p=e[o.matchUpId],d=(p?ca(we(p),we(n),!1):0)>=0;return{enoughTime:u&&d}}function nl({individualParticipantProfiles:t,matchUpPotentialParticipantIds:e,matchUpDailyLimits:r={},matchUp:n}){let{enteredIndividualParticipantIds:o}=eu(n),{matchUpId:i,matchUpType:s}=n,a=(n.roundPosition&&e[i]||[]).flat(),c=pt(o.concat(...a));return c.forEach(p=>{Fa({individualParticipantProfiles:t,participantId:p})}),{participantIdsAtLimit:c.filter(p=>{let m=t[p];if(m)return[s,$n].find(d=>{let l=m.counters?.[d]||0,f=r[d]||0;return l&&f&&l>=f})}),relevantParticipantIds:c}}function wu({scheduleCompletedMatchUps:t=!1,scheduleByeMatchUps:e=!1,errorOnAnachronism:r=!1,checkChronology:n=!0,matchUpDependencies:o,removePriorValues:i,tournamentRecords:s,tournamentRecord:a,matchUpDetails:c,matchUpIds:u,schedule:p}){if(!a)return{error:W};if(!c&&(!u||!Array.isArray(u)))return{error:ia};if(!c&&(!p||typeof p!="object"))return{error:$y};let m,d=[],l=0;if(n&&!o){let I=Vr({tournamentRecords:s,tournamentRecord:a});o=I.matchUpDependencies,m=I.matchUps}m||(m=le({tournamentRecord:a})?.matchUps??[]);let f=m.reduce((I,h)=>{let{matchUpId:S,drawId:T,matchUpStatus:A}=h;return(e||A!==Dt)&&(t||!ae.includes(A))&&(I[T]?I[T].push(S):I[T]=[S]),I},{}),g=c?.map(I=>I.matchUpId);for(let I of Object.keys(f)){let{drawDefinition:h}=Po({tournamentRecord:a,drawId:I});if(!h)continue;let S=f[I].filter(A=>u?.includes(A)??g?.includes(A)),T=rr({inContext:!1,drawDefinition:h}).matchUps;for(let A of S){let D=c?.find(E=>E.matchUpId===A)?.schedule||p,y=Kp({schedule:D,matchUpDependencies:o,errorOnAnachronism:r,removePriorValues:i,inContextMatchUps:m,tournamentRecords:s,tournamentRecord:a,checkChronology:n,drawDefinition:h,drawMatchUps:T,matchUpId:A});if(y?.warnings?.length&&d.push(...y.warnings),y?.success&&(l+=1),y.error)return y}}return d.length?{...R,scheduled:l,warnings:d}:{...R,scheduled:l}}function _c(t){let{scheduleCompletedMatchUps:e=!1,scheduleByeMatchUps:r=!1,errorOnAnachronism:n,matchUpContextIds:o,removePriorValues:i,tournamentRecords:s,checkChronology:a,matchUpDetails:c,schedule:u}=t;if(t.matchUpIds&&!o)return wu(t);let p=lt(t,[{[ye]:!0},{[Ja]:{matchUpContextIds:!1,matchUpDetails:!1},[En]:G,[to]:Er}]);if(p.error)return p;if((!c||o)&&!u)return{error:et,info:"schedule is required"};let m=[],d=0,{matchUpDependencies:l}=Vr({tournamentRecords:s});for(let f of Object.values(s)){let{tournamentId:g}=f,I=o?.filter(S=>S.tournamentId===g).map(fe),h=c?.filter(S=>S?.tournamentId===g);if(I?.length||h?.length){let S=wu({matchUpDetails:h,scheduleCompletedMatchUps:e,scheduleByeMatchUps:r,matchUpDependencies:l,errorOnAnachronism:n,removePriorValues:i,tournamentRecords:s,tournamentRecord:f,checkChronology:a,matchUpIds:I,schedule:u});if(S.warnings?.length&&m.push(...S.warnings),S.scheduled&&(d+=S.scheduled),S.error)return S}}return m.length?{...R,scheduled:d,warnings:m}:{...R,scheduled:d}}function TA({autoSchedulingAudit:t,tournamentRecords:e}){Tt({topic:fa,payload:t});let r=s=>s?Object.values(s).reduce((c,u)=>c+u.length||0,0):0,n=(t?.schedulingProfile||[]).reduce((s,a)=>s+a.venues.reduce((c,u)=>c+u.rounds.length,0),0),o={scheduledDatesCount:t.scheduledDates?.length,noTimeMatchUpIdsCount:r(t?.noTimeMatchUpIds),scheduledMatchUpIdsCount:r(t?.scheduledMatchUpIds),overLimitMatchUpIdsCount:r(t?.overLimitMatchUpIds),requestConflictsCount:r(t?.requestConflicts),profileRoundsCount:n},i={itemType:cN,itemValue:o};for(let s of Object.values(e))Gi({tournamentRecord:s,timeItem:i})}function sx({schedulingProfileModifications:t,checkPotentialRequestConflicts:e,scheduleCompletedMatchUps:r,schedulingProfileIssues:n,dateSchedulingProfiles:o,containedStructureIds:i,matchUpDependencies:s,matchUpDailyLimits:a,clearScheduleDates:c,tournamentRecords:u,schedulingProfile:p,personRequests:m,periodLength:d,matchUps:l,courts:f,dryRun:g}){let I={},h={},S={},T={},A={},D={},y={},E={},U={},M={};for(let C of o){let O=Ut(C?.scheduleDate),b=C?.venues||[],x={},w={},F=(k,K)=>{k.forEach(z=>{let q=w[z].counters;q[K]?q[K]+=1:q[K]=1,q[$n]?q[$n]+=1:q[$n]=1})};S[O]={},T[O]={},I[O]={},h[O]={},y[O]=[],E[O]=[],U[O]=[],M[O]=[];let L={};l.forEach(k=>{k.schedule?.scheduledDate&&_n(O,Ut(k.schedule.scheduledDate))&&ta({matchUpPotentialParticipantIds:x,matchUpNotBeforeTimes:L,matchUp:k})});let{allDateScheduledByeMatchUpDetails:v,venueScheduledRoundDetails:B,allDateMatchUpIds:H}=SA({matchUpPotentialParticipantIds:x,individualParticipantProfiles:w,scheduleCompletedMatchUps:r,containedStructureIds:i,matchUpNotBeforeTimes:L,matchUpScheduleTimes:D,matchUpDependencies:s,clearScheduleDates:c,tournamentRecords:u,useGarman:!0,periodLength:d,scheduleDate:O,matchUps:l,courts:f,venues:b}),j=10,V=0,Y,$=10;for(;!Y;){for(let{venueId:k}of b){let K=0,z=B[k];for(;z.courtsCount&&z.scheduleTimes?.length&&z.matchUpsToSchedule?.length&&K<=z.courtsCount;){let{scheduleTime:q,attempts:nt=0}=z.scheduleTimes.shift(),Q=z.matchUpsToSchedule.find(it=>{let{matchUpId:ot,matchUpType:ut}=it,{participantIdsAtLimit:Qt,relevantParticipantIds:yt}=nl({matchUpPotentialParticipantIds:x,individualParticipantProfiles:w,matchUpDailyLimits:a,matchUp:it});if(Qt.length)return E[O].includes(ot)||E[O].push(ot),!1;let{scheduledDependent:Me}=hA({matchUpScheduleTimes:D,matchUpDependencies:s,scheduleTime:q,matchUpId:ot,details:z});if(Me)return!1;let{dependenciesScheduled:Ee,remainingDependencies:Ce}=tl({matchUpScheduleTimes:D,matchUpDependencies:s,allDateMatchUpIds:H,matchUp:it});if(!Ee)return T[O][ot]||(T[O][ot]=[]),T[O][ot].push({scheduleTime:q,remainingDependencies:Ce}),!1;let{enoughTime:Kt}=rl({individualParticipantProfiles:w,matchUpNotBeforeTimes:L,matchUpDependencies:s,scheduleTime:q,details:z,matchUp:it});if(!Kt)return S[O][ot]||(S[O][ot]=[]),S[O][ot].push({scheduleTime:q}),!1;let Re=z.greatestAverageMinutes,{conflicts:wt}=el({potentials:e,averageMatchUpMinutes:Re,requestConflicts:M,personRequests:m,scheduleTime:q,scheduleDate:O,matchUp:it});if(wt?.length)return A[O]||(A[O]=[]),A[O].push(...wt),!1;F(yt,ut);let Ue=z.minutesMap?.[ot]?.recoveryMinutes;return bc({matchUpPotentialParticipantIds:x,individualParticipantProfiles:w,matchUpNotBeforeTimes:L,averageMatchUpMinutes:Re,matchUpDependencies:s,recoveryMinutes:Ue,scheduleTime:q,matchUp:it}),D[ot]=q,!0});z.matchUpsToSchedule=z.matchUpsToSchedule.filter(({matchUpId:it})=>it!==Q?.matchUpId),Q?K+=1:(h[O][k]||(h[O][k]=[]),h[O][k].push({scheduleTime:q,attempts:nt+1}))}z.matchUpsToSchedule?.length&&(h[O][k]=h[O][k]?.filter(q=>{let nt=q.attempts<j;return nt&&z.scheduleTimes.push(q),!nt})),(!z.scheduleTimes?.length||!z.matchUpsToSchedule?.length)&&(z.complete=!0)}V+=1,Y=b.every(({venueId:k})=>B[k].complete)||V===$}for(let{venueId:k}of b){let K=B[k].matchUpMap;Object.keys(K).forEach(z=>{let q=u[z];q&&Object.keys(K[z]).forEach(nt=>{let{drawDefinition:Q}=Po({tournamentRecord:q,drawId:nt});Q&&K[z][nt].forEach(({matchUpId:ot})=>{let ut=D[ot];if(ut){let Qt=ut.split(":").map(Hn).join(":"),yt=`${Ut(O)}T${Qt}`;g?y[O].push(ot):(Vo({drawDefinition:Q,scheduledTime:yt,matchUpId:ot}).success&&y[O].push(ot),k&&Zs({tournamentRecord:q,drawDefinition:Q,matchUpId:ot,venueId:k}))}})})}),U[O]=B[k].matchUpsToSchedule.map(fe),I[O][k]=B[k].scheduleTimes.sort((z,q)=>Vt(z.scheduleTime)-Vt(q.scheduleTime))}!g&&v?.length&&_c({matchUpDetails:v,scheduleByeMatchUps:!0,removePriorValues:!0,tournamentRecords:u,schedule:{scheduledDate:"",scheduledTime:"",courtOrder:"",courtId:"",venueId:""}});for(let k of C.venues)for(let K of k.rounds){let q=(K.matchUps?.map(({matchUpId:Q})=>Q)||[]).filter(Q=>y[O].includes(Q));K.canScheduledMatchUpIds=q;let nt=Math.round(q.length/K.matchUpsCount*1e4)/100;(nt===1/0||isNaN(nt))&&(nt=0),K.possibleToSchedulePct=nt,K.matchUpsCount===q.length&&(K.possibleToSchedule=!0)}}let P=o.map(({scheduleDate:C})=>C),N={timeStamp:Date.now(),overLimitMatchUpIds:E,scheduledMatchUpIds:y,schedulingProfile:p,noTimeMatchUpIds:U,requestConflicts:M,scheduledDates:P};return TA({tournamentRecords:u,autoSchedulingAudit:N}),{...R,schedulingProfileModifications:t,schedulingProfileIssues:n,scheduleTimesRemaining:I,dateSchedulingProfiles:o,skippedScheduleTimes:h,recoveryTimeDeferredMatchUpIds:S,dependencyDeferredMatchUpIds:T,matchUpScheduleTimes:D,overLimitMatchUpIds:E,scheduledMatchUpIds:y,noTimeMatchUpIds:U,requestConflicts:M,scheduledDates:P}}function YN({averageMinutes:t,startTime:e,endTime:r,court:n,date:o}){if(!Array.isArray(n.dateAvailability))return{error:et,stack:"getEarliestCourtTime"};let i=Cc({scheduleDate:o,courts:[n],startTime:!0}),s=Cc({scheduleDate:o,courts:[n],endTime:!0});e=e||i,r=r||s;let a=wa({court:n,date:o}),{timeSlots:c}=hs({courtDate:a}),u=we(e),p=we(r);return{earliestCourtTime:c?.reduce((d,l)=>{let f=we(l.startTime),g=we(l.endTime);if(f>p||g<u)return d;let I=u>f?u:f;if(ca(I,g)>=t){let T=$t(I.toISOString());(!d||T<d)&&(d=T)}return d},void 0),courtStartTime:i,courtEndTime:s}}function ax({schedulingProfileModifications:t,checkPotentialRequestConflicts:e,scheduleCompletedMatchUps:r,schedulingProfileIssues:n,dateSchedulingProfiles:o,containedStructureIds:i,matchUpDependencies:s,matchUpDailyLimits:a,clearScheduleDates:c,tournamentRecords:u,periodLength:p=30,schedulingProfile:m,personRequests:d,matchUps:l=[],courts:f,dryRun:g}){let I={},h={},S={},T={},A={},D={},y={},E={},U={};for(let N of o??[]){let C=Ut(N?.scheduleDate),O=N?.venues||[],b={},x={},w=(Q,it)=>{Q.forEach(ot=>{let ut=x[ot].counters;ut[it]?ut[it]+=1:ut[it]=1,ut[$n]?ut[$n]+=1:ut[$n]=1})};I[C]={},h[C]={},D[C]=[],y[C]=[],E[C]=[],U[C]=[];let F={};l?.forEach(Q=>{Q.schedule?.scheduledDate&&_n(C,Ut(Q.schedule.scheduledDate))&&ta({matchUpPotentialParticipantIds:b,matchUpNotBeforeTimes:F,matchUp:Q})});let{allDateScheduledByeMatchUpDetails:L,allDateScheduledMatchUpIds:v,venueScheduledRoundDetails:B,allDateMatchUpIds:H}=SA({matchUpPotentialParticipantIds:b,individualParticipantProfiles:x,scheduleCompletedMatchUps:r,containedStructureIds:i,matchUpNotBeforeTimes:F,matchUpScheduleTimes:A,matchUpDependencies:s,clearScheduleDates:c,tournamentRecords:u,periodLength:p,scheduleDate:C,matchUps:l,courts:f,venues:O}),j=l?.filter(({matchUpId:Q})=>v.includes(Q)),{bookings:V}=zp({dateScheduledMatchUps:j,tournamentRecords:u,scheduleDate:C,periodLength:p}),{virtualCourts:Y}=jp({scheduleDate:C,periodLength:p,bookings:V,courts:f}),$=Y?.reduce((Q,it)=>{let{earliestCourtTime:ot,courtEndTime:ut}=YN({date:C,averageMinutes:0,court:it});return(!Q.startTime||we(ot)<we(Q.startTime))&&(Q.startTime=ot),(!Q.endTime||we(ut)>we(Q.endTime))&&(Q.endTime=ut),Q},{}),k=$.startTime,K=({courtId:Q,booking:it})=>Y?.find(ot=>ot.courtId===Q)?.dateAvailability[0].bookings.push(it),z=10,q=0,nt;for(;!nt;){for(let{venueId:Q}of O){let it=B[Q],ot=it.matchUpsToSchedule.length,ut=[],Qt=[],yt,Me=0;for(;!yt;){for(let Ee of it.matchUpsToSchedule){if(Qt.length===it.courtsCount||ut.length===it.courtsCount){yt=!0;break}let{matchUpId:Ce,matchUpType:Kt}=Ee,{participantIdsAtLimit:Re,relevantParticipantIds:wt}=nl({matchUpPotentialParticipantIds:b,individualParticipantProfiles:x,matchUpDailyLimits:a,matchUp:Ee});if(Re.length){y[C].includes(Ce)||y[C].push(Ce);continue}let{dependenciesScheduled:Ue,remainingDependencies:Ct}=tl({matchUpScheduleTimes:A,matchUpDependencies:s,allDateMatchUpIds:H,matchUp:Ee});if(!Ue){h[C][Ce]||(h[C][Ce]=[]),h[C][Ce].push({remainingDependencies:Ct});continue}let vt=[],ne=Y?.reduce((qt,pe)=>{if(Qt.includes(pe.courtId))return qt;let{earliestCourtTime:he}=YN({averageMinutes:it.greatestAverageMinutes,startTime:k,date:C,court:pe});if(qt.scheduleTime&&Vt(he)>=Vt(qt.scheduleTime))return qt;let{scheduledDependent:ur}=hA({matchUpScheduleTimes:A,matchUpDependencies:s,scheduleTime:he,matchUpId:Ce,details:it});if(ur)return qt;let{enoughTime:_e}=rl({individualParticipantProfiles:x,matchUpNotBeforeTimes:F,matchUpDependencies:s,scheduleTime:he,details:it,matchUp:Ee});if(!_e)return I[C][Ce]||(I[C][Ce]=[]),I[C][Ce].includes(he)||I[C][Ce].push(he),qt;let Wt=it.minutesMap?.[Ce]?.averageMinutes||it.greatestAverageMinutes,{conflicts:ve}=el({potentials:e,averageMatchUpMinutes:Wt,requestConflicts:U,personRequests:d,scheduleTime:he,scheduleDate:C,matchUp:Ee});if(ve?.length)return vt.push(...ve),!1;w(wt,Kt);let nr=it.minutesMap?.[Ce]?.recoveryMinutes;return bc({matchUpPotentialParticipantIds:b,individualParticipantProfiles:x,matchUpNotBeforeTimes:F,averageMatchUpMinutes:Wt,matchUpDependencies:s,recoveryMinutes:nr,scheduleTime:he,matchUp:Ee}),(!qt.scheduleTime||Vt(he)<Vt(qt.scheduleTime))&&(qt.averageMatchUpMinutes=Wt,qt.recoveryMinutes=nr,qt.scheduleTime=he,qt.courtName=pe.courtName,qt.courtId=pe.courtId),qt},{});if(ne.scheduleTime){let{averageMatchUpMinutes:qt,recoveryMinutes:pe,scheduleTime:he,courtId:ur}=ne;A[Ce]=he,T[Ce]=ur,ut.push(Ce),Qt.push(ur);let _e=he,Wt=br(_e,qt);K({courtId:ur,booking:{averageMatchUpMinutes:qt,recoveryMinutes:pe,periodLength:p,matchUpId:Ce,startTime:_e,courtId:ur,endTime:Wt,venueId:Q}}),it.matchUpsToSchedule=it.matchUpsToSchedule.filter(nr=>nr.matchUpId!==Ce)}else vt?.length&&(S[C]||(S[C]=[]),S[C].push(...vt))}(Qt.length===it.courtsCount||ut.length===it.courtsCount||!it.matchUpsToSchedule.length)&&(yt=!0),it.matchUpsToSchedule.length&&ut<it.courtsCount&&(we(k)<we($.endTime)?k=br(k,p):(yt=!0,it.complete=!0)),Me+=1,!yt&&Me>=ot&&(yt=!0)}it.matchUpsToSchedule?.length||(it.complete=!0)}q+=1,nt=O.every(({venueId:Q})=>B[Q].complete)||q===z}for(let{venueId:Q}of O){let it=B[Q].matchUpMap;Object.keys(it).forEach(ot=>{let ut=u[ot];ut&&Object.keys(it[ot]).forEach(Qt=>{let{drawDefinition:yt}=Po({tournamentRecord:ut,drawId:Qt});yt&&it[ot][Qt].forEach(({matchUpId:Ee})=>{let Ce=A[Ee],Kt=T[Ee];if(Ce){let Re=Ce.split(":").map(Hn).join(":"),wt=`${Ut(C)}T${Re}`;g||(Vo({drawDefinition:yt,scheduledTime:wt,matchUpId:Ee}),Hi({courtDayDate:C,tournamentRecords:u,tournamentRecord:ut,drawDefinition:yt,matchUpId:Ee,courtId:Kt})),D[C].push(Ee)}})})}),E[C]=B[Q].matchUpsToSchedule.map(fe)}!g&&L?.length&&_c({matchUpDetails:L,scheduleByeMatchUps:!0,removePriorValues:!0,tournamentRecords:u,schedule:{scheduledDate:"",scheduledTime:"",courtOrder:"",courtId:"",venueId:""}});for(let Q of N.venues)for(let it of Q.rounds){let ut=(it.matchUps??[]).map(({matchUpId:yt})=>yt)?.filter(yt=>D[C].includes(yt));it.canScheduledMatchUpIds=ut;let Qt=Math.round((ut?.length||0)/it.matchUpsCount*1e4)/100;(Qt===1/0||isNaN(Qt))&&(Qt=void 0),it.possibleToSchedulePct=Qt,it.matchUpsCount===ut?.length&&(it.possibleToSchedule=!0)}}let M=(o??[]).map(({scheduleDate:N})=>N),P={timeStamp:Date.now(),overLimitMatchUpIds:y,scheduledMatchUpIds:D,schedulingProfile:m,noTimeMatchUpIds:E,requestConflicts:U,scheduledDates:M};return TA({tournamentRecords:u,autoSchedulingAudit:P}),{...R,schedulingProfileModifications:t,schedulingProfileIssues:n,dateSchedulingProfiles:o,recoveryTimeDeferredMatchUpIds:I,dependencyDeferredMatchUpIds:h,matchUpScheduleTimes:A,overLimitMatchUpIds:y,scheduledMatchUpIds:D,noTimeMatchUpIds:E,requestConflicts:U,scheduledDates:M}}function Qp(t){let{scheduleAttributes:e=["scheduledDate","scheduledTime"],ignoreMatchUpStatuses:r=ae,scheduledDates:n,venueIds:o}=t,i=Xr(t),s=Rt(i)?Object.values(i).map(({tournamentId:c})=>c).filter(Boolean):[];if(!s?.length)return{error:Ft};let a=0;for(let c of s){let u=i[c],p=LV({ignoreMatchUpStatuses:r,scheduleAttributes:e,tournamentRecord:u,scheduledDates:n,venueIds:o});if(p.error)return p;a+=p.clearedScheduleCount??0}return{...R,clearedScheduleCount:a}}function LV({scheduleAttributes:t=["scheduledDate","scheduledTime"],ignoreMatchUpStatuses:e=ae,tournamentRecord:r,scheduledDates:n,venueIds:o=[]}){if(typeof r!="object")return{error:W};if(!Array.isArray(e)||!Array.isArray(o))return{error:G};o.length&&t.push("venueId");let i=le({matchUpFilters:{scheduledDates:n},tournamentRecord:r}).matchUps??[],s={};i.forEach(({matchUpStatus:u,schedule:p,drawId:m,matchUpId:d})=>{(!u||!e.includes(u))&&va({schedule:p,scheduleAttributes:t})&&(!o?.length||o.includes(p.venueId))&&(s[m]||(s[m]=[]),s[m].push(d))});let a=r.tournamentId,c=0;for(let u in s){let{event:p,drawDefinition:m}=We({tournamentRecord:r,drawId:u}),d=rr({drawDefinition:m,matchUpFilters:{matchUpIds:s[u]}}).matchUps??[];for(let l of d){let f=!1;l.timeItems=(l.timeItems??[]).filter(g=>{let I=g?.itemType&&![Eo,di,xs,ws,Ls].includes(g?.itemType);return I||(f=!0),I}),f&&(It({context:"clear schedules",eventId:p?.eventId,drawDefinition:m,tournamentId:a,matchUp:l}),c+=1)}}return{...R,clearedScheduleCount:c}}function Xp(t){let{checkPotentialRequestConflicts:e=!0,scheduleCompletedMatchUps:r,clearScheduleDates:n,scheduleDates:o=[],tournamentRecords:i,periodLength:s,useGarman:a,dryRun:c,pro:u}=t,p=lt(t,[{[ye]:!0},{[yn]:M=>!M||Array.isArray(M)&&M.every(Rr),[CI]:!1,[to]:Er}]);if(p.error)return p;let m=ko({tournamentRecords:i});if(m.error)return m;if(!m.schedulingProfile.length)return{...R};let{modifications:d,issues:l=[],schedulingProfile:f=[]}=m,g=Object.assign({},...Object.values(i).map(M=>Ji({tournamentRecord:M}).containedStructures)),I=o.map(M=>{if(Rr(M))return Ut(M)}).filter(Boolean),h=f.map(M=>M.scheduleDate).map(M=>Rr(M)&&Ut(M)).filter(M=>M&&(!o.length||I.includes(M)));if(!h.length)return{error:Py};if(n&&!c){let M=Array.isArray(n)?n:[];Qp({tournamentRecords:i,scheduledDates:M})}let S=po({ignoreDisabled:!1,tournamentRecords:i}).courts,{matchUps:T}=cn({matchUpFilters:{matchUpTypes:[Xt,Gt]},afterRecoveryTimes:!0,nextMatchUps:!0,tournamentRecords:i}),{matchUpDependencies:A}=Vr({includeParticipantDependencies:!0,tournamentRecords:i,matchUps:T}),{matchUpDailyLimits:D}=Yd({tournamentRecords:i}),{personRequests:y}=yi({requestType:Oc,tournamentRecords:i}),E=f.filter(M=>{let P=Ut(M?.scheduleDate);return h.includes(P)}).sort((M,P)=>new Date(M.scheduleDate).getTime()-new Date(P.scheduleDate).getTime()),U={schedulingProfileModifications:d,checkPotentialRequestConflicts:e,scheduleCompletedMatchUps:r,schedulingProfileIssues:l,dateSchedulingProfiles:E,containedStructureIds:g,matchUpDependencies:A,matchUpDailyLimits:D,clearScheduleDates:n,tournamentRecords:i,schedulingProfile:f,personRequests:y,periodLength:s,useGarman:a,matchUps:T,dryRun:c,courts:S};return u?ax(U):sx(U)}function AA(t){let e=t||{};return e.tournamentId||(e.tournamentId=Mt()),e.startDate&&!Za(e.startDate)&&!gm.test(e.startDate)?{error:ar}:e.endDate&&!Za(e.endDate)&&!gm.test(e.endDate)?{error:ar}:(e.extensions&&(e.extensions=e.extensions.filter(Pn)),{...e})}function Bg({addParticipants:t=!0,participantAttribute:e,tournamentRecord:r,personAttribute:n,teamNames:o,accessor:i,uuids:s}){if(!r)return{error:W};let a={},c=(r.participants??[]).filter(({participantType:f,participantRole:g})=>f===ht&&g===Ge),u=0;for(let f of c){let I=i&&Zi({element:f,accessor:i})?.value||n&&f.person?.[n]||e&&f[e];if(I){if(!Object.keys(a).includes(I)){a[I]={participantName:o?.[u]??I,participantId:s?.pop()??Mt(),individualParticipantIds:[],participantRole:Ge,participantType:kt};let h={value:n??e,name:VI};St({element:a[I],extension:h}),u+=1}a[I].individualParticipantIds.push(f.participantId)}}let p=Object.keys(a),m=(r.participants??[]).map(f=>{if(f.participantType!==kt||f.participantRole!==Ge)return;let{extension:g}=mt({name:VI,element:f}),I=g?.value;if(p.includes(I))return f.participantId}).filter(Boolean),d=0,l=[];return Object.keys(a).forEach(f=>{let g=a[f],{participantId:I}=g;m.includes(I)||(r.participants||(r.participants=[]),t&&r.participants.push(g),l.push(g),d++)}),t&&d?(Tt({payload:{tournamentId:r.tournamentId,participants:l},topic:jo}),{...R,participantsAdded:d}):l.length?{...R,newParticipants:l}:{error:_C}}var cx=[{AA:"Annexia"},{BA:"Bacteria"},{BO:"Borduria"},{BM:"Bensalem"},{BS:"Basenji"},{BI:"Balnibarbi"},{BV:"Bartovia"},{BZ:"Berzerkistan"},{CA:"Caldonia"},{CC:"Concordia"},{CH:"Chula"},{DA:"Deltora"},{DW:"Discworld"},{EA:"Eastasia"},{EP:"Ecotopia"},{ER:"Erewhon"},{FA:"Freedonia"},{FN:"Florin"},{FG:"Fogg"},{FK:"Fourecks"},{GA:"Genovia"},{GL:"Gilead"},{GD:"Gilead"},{GL:"Gondal"},{GO:"Gondor"},{GR:"Gruzinia"},{GT:"Goritania"},{GU:"Guilder"},{HA:"Heldscalla"},{HO:"Hidalgo"},{IL:"Illyria"},{KA:"Kinakuta"},{KG:"Kangan"},{KN:"Kreplachistan"},{KS:"Kallipolis"},{LH:"Lugash"},{LI:"Listenbourg"},{LT:"Lilliput"},{LU:"Luggnagg"},{LV:"Lichtenslava"},{MR:"Moher"},{NA:"Narnia"},{NV:"Novaria"},{OA:"Oceania"},{OS:"Orsinia"},{OV:"Octavia"},{PA:"Palombia"},{PG:"Penguina"},{QA:"Qasha"},{PM:"Panem"},{SA:"Solymbria"},{SD:"Syldavia"},{SG:"San Glucose"},{SL:"San Lorenzo"},{SR:"Sontar"},{SY:"Sylvania"},{TF:"Tralfamadore"},{TH:"Themyscira"},{UA:"Utopia"},{VA:"Vespugia"},{WA:"Wakanda"},{WX:"Wessex"},{ZA:"Zamunda"},{ZK:"Zubrowka"}];var ux=["Amber","Ansul","Atlantis","Braavos","Busytown","Castle Rock","Centralia","Coober Pedy","Chefchaouen","Chronopolis","Damanhur","Diaspar","Dictionopolis","Diomira","El Dorado","Elista","Ephesus","Gotham","Hadleyburg","Hallstatt","Hierusalem","Ilium","Inverness","Kowloon","Laputa","Longyearbyen","Lys","Matmata","Maycomb","Metropolis","Miyake-jima","Monowi","Nagoro","Navarre","New New York","Nimbin","Pemberley","Pseudopolis","Rivendell","Roswell","Shangri-La","Springfield","Supilinn","Thneedville","Trantor","Wobegon","Yonwood","Xanadu","Xylar","Zion"];function yA({count:t=1,participantsCount:e=32}={}){let r=cr(ux),n=r.slice(0,t);return{cities:Z(0,e).map(i=>i<Math.min(t,r.length)?n[i]:on(n))}}function EA({count:t=1,participantsCount:e=32}={}){let r=cr(cx),n=r.slice(0,t).map(i=>Object.keys(i)).flat();return{states:Z(0,e).map(i=>i<Math.min(t,r.length)?n[i]:on(n))}}function UA({count:t=1,participantsCount:e=32}={}){let r=Z(0,t).map(()=>Z(0,5).map(()=>Jn(0,9)).join(""));return{postalCodes:Z(0,e).map(o=>o<t?r[o]:on(r))}}function PA(t){let{cities:e,states:r,postalCodes:n,nationalityCode:o,participantIndex:i}=t;return{postalCode:n?.[i],state:r?.[i],city:e?.[i],countryCode:o}}var px={lastNames:["Abbey","Ahern","Ampleforth","Ananiadis","Andelic","Assange","Atreides","Austen","Bach","Banks","Barrington","Batty","Bauers","Beals","Beer","Bennett","Berry","Bonaparte","Brockovich","Bukowski","Cassidy","Catton","Calvino","Carson","Chip","Constant","Crane","Crowne","Cummings","Curie","Dallas","Diamond","Deckard","Drazic","Dunbar","Earhart","Eisenstein","Eldritch","Elliot","Escher","Eyre","Faulkner","Fulcher","Fukuoka","Godel","Goldstein","Greer","Hedges","Herbert","Holmgren","Humperdinck","Huxley","Illich","Jeffers","Jensen","Jevons","Johnson","Johnstone","Jovovich","Kingsnorth","Langer","Fernwright","Fuller","Le Guin","Lem","Lovelace","Mander","Midgely","Mond","Montoya","Moore","Murry","Nagle","Nearing","Ogden","Ophuls","Parks","Paz","Peet","Perfect","Pendejo","Pevensie","Postman","Ripley","Rodda","Rumfoord","Runciter","Rugen","Sale","Schumacher","Shaftoe","Shelley","Shepard","Smith","Stratton","Stewart","Swift","Tillich","Turing","Tyrell","Twain","Yeats","Veblen","Yates","Vonnegut","Waterhouse","Watson","Wolin","Wirt","Waschuk","Wormwood"],firstFemale:["Ada","Amelia","Amelie","America","Anne","Antonia","Aravis","Astrid","Beatrice","Brienne","Buttercup","Caitlin","Cimorene","Cordelia","Desdemona","Ellen","Elizabeth","Emily","Emmie","Erin","Eva","Evelyn","Heather","Helen","Hermia","Hypatia","Imogen","Jane","Jasmine","Juliana","Juliet","Katniss","Leeloo","Lenina","Lilith","Linda","Lizzie","Louise","Lucy","Marie","Mary","Martha","Matilda","Milla","Miranda","Meg","Melba","Nicole","Ola","Portia","Pris","Rachael","Rachel","Rebecca","River","Rosa","Rosalind","Scout","Sharn","Susanne","Titania","Uhura","Ursula","Valentina","Viola","Virginia","Xena","Zoe"],firstMale:["Alan","Aldous","August","Axel","Barda","Barry","Bill","Bruce","Charles","Chris","Constantine","Darwin","David","Derrick","Edward","Emmanuel","Ernst","Estlin","Fezzik","Filby","Frank","Frito","George","Glen","Helmholtz","Inigo","Italo","Ivan","James","Jared","Jerry","Joe","Johann","Julian","John Michael","Jonathan","Korben","Kirkpatrick","Kurt","Lief","Malachi","Mark","Masanobu","Maurits","Michael","Mustapha","Neil","Nikola","Octavio","Palmer","Paul","Pierre","Robinson","Rick","Rincewind","Roy","Shannon","Sheldon","Stafford","Stanislaw","Stanley","Syme","Thorstein","Thomas","Tyrone","Vizzini","Walton","Walker","Warren","Wendell","Westley","William","Winston","Zoran"]};function DA(t){let{count:e=100,sex:r}=t||{};if(!e||r&&![ee,ue].includes(r))return{personData:[],error:G};let n=Math.ceil(e*1.3),{lastNames:o,firstFemale:i,firstMale:s}=px,a=Xo.map(({iso:I})=>I).filter(Boolean),c=Math.ceil(n/o.length),u=Math.ceil(n/i.length),p=Math.ceil(n/s.length),m=Z(0,c).flatMap(()=>{let I=J(o,!1,!0);return Z(0,o.length).map(()=>xr(I))}),d=Z(0,u).flatMap(()=>{let I=J(i,!1,!0);return Z(0,i.length).map(()=>xr(I))}),l=Z(0,p).flatMap(()=>{let I=J(s,!1,!0);return Z(0,s.length).map(()=>xr(I))}),f={};for(let I=0;I<n;I++){let h=m.pop(),S=r||on([ee,ue]),T=S===ee?l.pop():d.pop(),A=on(a);f[`${T}${h}`]={nationalityCode:A,sex:S,firstName:T,lastName:h}}return{personData:Object.values(f).slice(0,e)}}function NA(t){let e=t?.count||1,{personExtensions:r,consideredDate:n,isMock:o=!0,gendersCount:i,personData:s,category:a,sex:c}=t||{};if(isNaN(e))return{error:G};let u=i?.[ee]||c===ee&&e||0,p=i?.[ue]||c===ue&&e||0;e=Math.max(e,u+p);let m=e-(u+p),d=u&&DA({count:u,sex:ee}).personData||[],l=p&&DA({count:p,sex:ue}).personData||[],f=[...d,...l,...m&&DA({count:m}).personData||[]],g=f.filter(U=>!c||u&&p||U.sex===c),I=[];if(Array.isArray(s)){let U=s.filter(M=>typeof M.firstName!="string"||typeof M.lastName!="string"||M.sex&&![ee,ue].includes(M.sex)||M.nationalityCode&&(typeof M.nationalityCode!="string"||M.nationalityCode.length>3||!Xo.find(({iso:P,ioc:N})=>[P,N].includes(M.nationalityCode)))?!1:(M.nationalityCode&&I.push(M.nationalityCode),!0));if(U.length)g=U;else return{error:G}}let h=s?g:cr(g);if(h.length<e){let{maleFirstNames:U,maleLastNames:M,femaleFirstNames:P,femaleLastNames:N,nationalityCodes:C}=f.reduce((O,b)=>{let{firstName:x,lastName:w,nationalityCode:F}=b;return b.sex===ee?(O.maleFirstNames.includes(x)||O.maleFirstNames.push(x),O.maleLastNames.includes(w)||O.maleLastNames.push(w)):(O.femaleFirstNames.includes(x)||O.femaleFirstNames.push(x),O.femaleLastNames.includes(w)||O.femaleLastNames.push(w)),O.nationalityCodes.includes(F)||O.nationalityCodes.push(F),O},{maleFirstNames:[],maleLastNames:[],femaleFirstNames:[],femaleLastNames:[],nationalityCodes:[]});Z(0,e-h.length).forEach(()=>{let O=c||on([ee,ue]),b=on(C),x=O===ee?on(U):on(P),w=O===ee?on(M):on(N),F={firstName:x,lastName:w,sex:O,nationalityCode:b};h.push(F)})}let{ageMinDate:S,ageMaxDate:T}=Au({consideredDate:n,category:a}),A=ct(S?.slice(0,4)||0)||ct(T?.slice(0,4)||0)-3,D=ct(T?.slice(0,4)||0)||ct(S?.slice(0,4)||0)+3,y=(S||T)&&[A,D],E=h.slice(0,e).map((U,M)=>{let[P,N]=y||[],C=y&&xr(Z(P,N)),O=xr(Z(0,365)),b=C&&mR(C,O);return Object.assign(rt({extensions:r||[{name:"regionCode",value:M+1}],birthDate:b,isMock:o}),U)});return{persons:E.length&&E||h[0],nationalityCodes:I}}var mx=["Ace Academy","Avengers","Ball Bouncers","Baseliners","Captivators","Civil Disobedients","Continentals","Court Royal","Court Sharks","Diamond Dogs","Danger Zone","Doubles Dominators","Double Faults","Tricksters","Eliminators","Court Crusaders","Fuzz Busters","Game Changers","Goal Gurus","Good Volley","Green Machine","Hawk Eyes","Inside Outers","Killer Instinct","Line Toers","Masters of Mayhem","Matter Catchers","Cheap Shot","Mean Machines","Mindspace Invaders","Net Centric","Net Positive","Smash Mullet","Over Your Head","Spin Meisters","Aggressors","Racket Machine","Slice Happy","Refs Nightmare","Sandeaters","Sun Seekers","Slicer Dicers","Sparkle Soul Tribe","Stacked Deck","Cross Stringers","The Emergence","Total Demolition","Touch and Go","Upside Downers","Vertically Challenged","Visual Spectacle"];function Hg({nameRoot:t="TEAM",count:e=1}={}){let n=cr(mx).slice(0,e);return n.length<e&&Z(0,e-n.length).forEach(o=>n.push(`${t} ${o+1}`)),{names:n}}function Wg({idPrefix:t,participantType:e,index:r,uuids:n}){return t?`${t}-${e===ht?"I":dt?"P":kt?"T":Ar?"G":"X"}-${r}`:n?.pop()||Mt()}function vc(t){let{rankingRange:e,scaledParticipantsCount:r}=t,{ratingsParameters:n=Br,valuesInstanceLimit:o,consideredDate:i,category:s,nationalityCodesCount:a,nationalityCodeType:c,nationalityCodes:u,participantsCount:p=32,participantType:m,personIds:d,idPrefix:l,uuids:f,personExtensions:g,addressProps:I,gendersCount:h,matchUpType:S,personData:T,sex:A,inContext:D,withISO2:y,withIOC:E,scaleAllParticipants:U}=t,M=m===dt||S===vi,P=m===kt||S===kt;e&&(!Array.isArray(e)||!e.every(Kt=>te(Kt))||e.length!==2)&&(e=void 0),r=U?p:r;let N=1e3,C=r&&r>N?r:N;e=e||[1,C],e[1]+=1;let O=p*(M?2:P?8:1),b=NA({count:O,personExtensions:g,consideredDate:i,gendersCount:h,personData:T,category:s,sex:A});if(b.error)return b;let{nationalityCodes:x,persons:w}=b,F=[],L=[],v=[],B=[];if(typeof s=="object"){let{categoryName:Kt,ageCategoryCode:Re,ratingType:wt}=s;if((Kt||Re)&&!wt){let[Ue,Ct]=e||[];if(L=cr(Z(Ue,Ct)).slice(0,r||Jn(20,30)),[dt,kt].includes(m)){let[vt,ne]=e||[];F=cr(Z(vt,ne)).slice(0,r||Jn(20,30))}}if(wt&&n[wt]){let{ratingMax:Ue,ratingMin:Ct,ratingAttributes:vt}=s,ne={...n[wt],...vt||{}},{attributes:qt={},decimalsCount:pe,accessors:he,range:ur,step:_e}=ne,Wt=Pe=>{let gr={},ri=Object.keys(Pe||{});for(let qe of ri){let bn=Pe[qe];if(typeof bn=="object"&&bn.generator){let{range:Ei}=bn,[Wi,hn]=Ei.slice().sort();gr[qe]=Jn(Wi,hn)}else gr[qe]=bn}return gr},nr=ur[0]>ur[1]?2:.5,[be,Nr]=ur.slice().sort(),Se=()=>Z(0,2e3).map(()=>sE(be,Nr,nr,_e,pe)).filter(Pe=>(!Ue||Pe<=Ue)&&(!Ct||Pe>=Ct)).slice(0,r||Jn(20,30)).map(Pe=>he?Object.assign({},...he.map(gr=>({[gr]:Pe})),Wt(qt)):Pe);v=Se(),[dt,kt].includes(m)&&(B=Se())}}let H=Xo.filter(Kt=>c==="IOC"&&Kt.ioc||Kt.iso);function j(Kt){let Re=Math.ceil(O/Kt);return o&&Re>o?Math.ceil(O/o):Kt}let{postalCodesProfile:V,postalCodesCount:Y,statesProfile:$,citiesProfile:k,citiesCount:K,statesCount:z}=I||{},q=Kt=>Object.keys(Kt).map(Re=>Z(0,$[Re]).map(()=>Re)).flat(),nt=k&&q(k)||I?.cities||yA({count:K||O,participantsCount:O}).cities,Q=$&&q($)||I?.states||EA({count:z||O,participantsCount:O}).states,it=V&&q(V)||I?.postalCodes||UA({count:Y||O,participantsCount:O}).postalCodes,ot={cities:nt,states:Q,postalCodes:it},ut=j(a),Qt=ut?cr(H).slice(0,a):u?H.filter(Kt=>u.includes(Kt.iso)):H,yt=cr(Z(0,Math.ceil(O/(ut||1))).map(()=>Qt).flat(1/0)),Me=Hg({count:p}).names;return{participants:Z(0,p).map(Kt=>{let Re=M?2:P?8:1,wt=Z(0,Re).map(qt=>{let pe=Kt*Re+qt;return Ce(pe)}),Ue=wt.map(qt=>qt.participantId),Ct=wt.map(qt=>qt.person.standardFamilyName).join("/"),vt=M?dt:kt,ne={participantId:Wg({participantType:vt,idPrefix:l,index:Kt,uuids:f}),participantRole:Ge,participantName:M?Ct:Me[Kt],individualParticipantIds:Ue,participantType:vt};return D&&(ne.individualParticipants=wt),M||P?[ne,...wt]:wt}).flat(),...R};function Ce(Kt){let Re=w[Kt],{nationalityCode:wt,participantExtensions:Ue,participantTimeItems:Ct,extensions:vt,firstName:ne,birthDate:qt,lastName:pe,personId:he,sex:ur}=Re||{},_e=ne||"GivenName",Wt=pe||"FamilyName",ve=`${_e} ${Wt}`,nr=yt[Kt],be=x?.length&&wt||nr&&(c==="IOC"?nr.ioc||nr.iso:nr.iso||nr.ioc)||wt;yt?.length&&!be&&!wt&&console.log("%c Invalid Nationality Code",{participantIndex:Kt,country:nr});let Nr=PA({...ot,participantIndex:Kt,nationalityCode:be}),Se=rt({participantId:Wg({participantType:ht,index:Kt,idPrefix:l,uuids:f}),extensions:Ue,timeItems:Ct,participantRole:Ge,participantType:ht,participantName:ve,person:{addresses:[Nr],personId:he||d?.length&&d[Kt]||Mt(),standardFamilyName:Wt,standardGivenName:_e,nationalityCode:be,extensions:vt,birthDate:Rr(qt)?qt:void 0,sex:ur}});if(E&&be){let Pe=Xo.find(({iso:gr})=>gr===be);Pe?.ioc&&(Se.person.iocNationalityCode=Pe.ioc),Pe?.label&&(Se.person.countryName=Pe.label)}if(y&&be){let Pe=Xo.find(({iso:gr})=>gr===be);Pe?.iso2&&(Se.person.iso2NationalityCode=Pe.iso2),Pe?.label&&(Se.person.countryName=Pe.label)}if(s){let Pe=L[Kt],gr=F[Kt];MA({scaleValue:Pe,eventType:Fs,scaleType:oi,participant:Se,category:s}),MA({scaleValue:gr,eventType:gi,scaleType:oi,participant:Se,category:s});let ri=v[Kt],qe=B[Kt];MA({scaleValue:ri,eventType:Fs,scaleType:Ki,participant:Se,category:s}),MA({scaleValue:qe,eventType:gi,scaleType:Ki,participant:Se,category:s})}return Se}}function MA({scaleValue:t,participant:e,eventType:r,scaleType:n,category:o}){let i=o.categoryName||o.ratingType||o.ageCategoryCode,s=[zi,n,r,i].join("."),a={itemValue:t,itemType:s};i&&t&&(e.timeItems||(e.timeItems=[]),e.timeItems.push(a))}function CA({alternatesCount:t=0,tieFormatName:e,tieFormat:r,drawSize:n}){let o=0,i=0,s=0,a=0,c={},u={[ee]:0,[ue]:0,[_r]:0,[ya]:0,[Fn]:0};r=typeof r=="object"?r:Bi({namedFormat:e}),r?.collectionDefinitions?.filter(Boolean).forEach(l=>{let{category:f,collectionId:g,matchUpType:I,matchUpCount:h,gender:S}=l;if([ee,ue].includes(S)){let T=h*(I===Gt?2:1);u[S]<T&&(u[S]=T)}else S===_r&&(u[ee]<h&&(u[ee]=h),u[ue]<h&&(u[ue]=h));if(f){let T=JSON.stringify(f);c[T]=f}if(g||(l.collectionId=Mt()),ie(Gt)(I)){let T=h;a+=h,o=Math.max(o,T)}if(ie(Xt)(I)){let T=h;s+=h,i=Math.max(i,T)}});let p=Object.keys(c).length?Math.max(s,a*2):Math.max(i,o*2),m=o*(n+t),d=i*(n+t);return{maxDoublesDraw:m,maxSinglesDraw:d,teamSize:p,genders:u}}function dx({participantsProfile:t,eventProfiles:e,drawProfiles:r}){let{participantsCount:n,participantType:o=ht}=t||{},i=n||0,s={[ue]:0,[_r]:0,[ya]:0,[ee]:0,[Fn]:0},a=0,c=0,u=0,p=0,m=0,d=({alternatesCount:f=0,uniqueParticipants:g,tieFormatName:I,drawSize:h=0,eventType:S,tieFormat:T,category:A,gender:D,stage:y})=>{let E=S===Kr,U=S===Fe,M=!!(g||y===at||A||D);if(U){p=Math.max(p,h+f),T=typeof T=="object"?T:Bi({namedFormat:I});let{teamSize:P,maxDoublesDraw:N,maxSinglesDraw:C,genders:O}=CA({alternatesCount:f,tieFormatName:I,tieFormat:T,drawSize:h});u=Math.max(u,P),c=Math.max(c,C),M||(a=Math.max(a,N)),Object.keys(O).forEach(b=>s[b]+=O[b])}else if(E)if(M){let P=(h+f)*2;m+=P,D&&(s[D]+=P)}else h+f&&h+f>a&&(a=h+f);else if(M){let P=h+f;D&&(s[D]+=P),m+=P}else h&&h>c&&(c=h+f)};if(e?.forEach(f=>{let{tieFormatName:g,tieFormat:I,drawProfiles:h,eventType:S,category:T,gender:A}=f;if(h)for(let D of h){let{tieFormatName:y,tieFormat:E}=D;d({...D,tieFormatName:y||g,tieFormat:E||I,eventType:S,category:T,gender:A})}}),Array.isArray(r))for(let f of r)d(f);let l=Math.max(p*u,a*2,c);return a&&(o=dt),(n||i)<l&&(n=l),n&&a&&[dt,Fe].includes(o)&&(c&&Math.floor(c/2)>a?n=Math.floor(c/2):(!c||a*2>=c)&&(n=Math.ceil(n/2))),n===void 0&&(n=!e?.length&&!r?.length?32:0),n<i&&(n=i),{uniqueParticipantsCount:m,participantsCount:n,largestTeamDraw:p,largestTeamSize:u,participantType:o,gendersCount:s}}function RA({participantsProfile:t,tournamentRecord:e,eventProfiles:r,drawProfiles:n,startDate:o,uuids:i}){let{participantsCount:s,participantType:a,largestTeamDraw:c,largestTeamSize:u,gendersCount:p}=dx({participantsProfile:t,eventProfiles:r,drawProfiles:n}),m=t?.teamKey,d=vc({uuids:i,...t,consideredDate:o,participantsCount:s,participantType:a,gendersCount:p}).participants,l=0,f=In({tournamentRecord:e,participants:d});if(f.error)return f;if(l+=f.addedCount,m){let S=Bg({tournamentRecord:e,...m});if(S.error)return S}let g=d.filter(({participantType:S})=>S===ht).map(gt),I=t?.idPrefix?`${kt}-${t.idPrefix}`:void 0,h=Z(0,c).map(S=>{let T=g.slice(S*u,(S+1)*u),A=Wg({index:S,participantType:a,idPrefix:I,uuids:i});return{participantName:`Team ${S+1}`,participantRole:Ge,individualParticipantIds:T,participantType:kt,participantId:A}});return f=In({participants:h,tournamentRecord:e}),f.error?f:(l+=f.addedCount,{addedCount:l,...R})}function bA({drawProfiles:t,category:e,gender:r}){let n={},o=t?.reduce((s,a)=>{let{qualifyingPositions:c=0,participantsCount:u=0,uniqueParticipants:p,stage:m=tt,drawSize:d=0}=a||{};Object.keys(s).includes(m)||(s[m]=0);let l=(u||d)-c;return p||r||e||m===at?(Object.keys(n).includes(m)||(n[m]=0),n[m]+=l):s[m]=Math.max(s[m],l),s},{}),i=Object.keys(n);return i.forEach(s=>o[s]+=n[s]),{stageParticipantsCount:o,uniqueParticipantsCount:n,uniqueParticipantStages:i}}function OA({allUniqueParticipantIds:t,stageParticipantsCount:e,eventParticipantType:r,targetParticipants:n}){let o=e[tt]||0,i=e[at]||0;return{stageParticipants:{QUALIFYING:n.filter(({participantType:a})=>a===r).filter(({participantId:a})=>!t.includes(a)).slice(0,i),MAIN:n.filter(({participantType:a})=>a===r).filter(({participantId:a})=>!t.includes(a)).slice(i,i+o)}}}var BV={[_t]:2,[ge]:1,[Ne]:1,[lr]:1,[Ot]:4};function jg(t){let{defaultWithScorePercent:e=2,winningSide:r}=t,{matchUpStatusProfile:n=BV,matchUpFormat:o=un,pointsPerMinute:i=1,sideWeight:s=4}=t;if(!Sr({matchUpFormat:o}))return{error:Tl};if(typeof n!="object")return{error:G};if(e>100&&(e=100),isNaN(e)||isNaN(i)||isNaN(s))return{error:G};let a=Object.keys(n).filter(N=>Object.keys(KI).includes(N)&&N!==me);if(Object.keys(a).reduce((N,C)=>N+n[C],0)>100)return{error:G,matchUpStatusProfile:n};let u=a.reduce((N,C)=>(N.pointer=N.pointer+n[C],N.valueMap.push([N.pointer,C]),N),{pointer:0,valueMap:[]}),p=Jn(1,100),m=(u.valueMap.find(N=>p<=N[0])??[100,me])[1],d={sets:[],scoreStringSide1:"",side2ScoreString:""};if([_t,Ot].includes(m)){r=r||Jn(1,2);let N={score:d,winningSide:r,matchUpStatus:m};if(!(m===Ot&&Jn(1,100)>100-e))return{outcome:N}}else if([ge,Ne].includes(m))return{outcome:{score:d,matchUpStatus:m}};let l=tr(o),{bestOf:f,setFormat:g,finalSetFormat:I}=l??{},h=[],S=Jn(0,1),T=r?[r-1]:[...Z(0,s).map(()=>S),1-S],D=[lr,Ot,_o,Xi].includes(m)&&(xr(Z(1,f))||1),y;for(let N of Z(1,(f??0)+1)){let C=N===f,{set:O,incomplete:b,winningSideNumber:x}=HV({incomplete:D===N,matchUpStatus:m,pointsPerMinute:i,setFormat:C&&I||g,setNumber:N,weightedRange:T});if(h.push(O),b){y=x;break}if(Vp({matchUp:{score:{sets:h},matchUpFormat:o}}).calculatedWinningSide)break}let E=Vp({matchUp:{score:{sets:h},matchUpFormat:o}}),U=y?r||y:E.calculatedWinningSide,{score:M}=IA({score:{sets:h},winningSide:U,matchUpStatus:m});return{outcome:{score:M,winningSide:U,matchUpStatus:m}}}function HV({weightedRange:t=[0,1],pointsPerMinute:e,matchUpStatus:r,incomplete:n,setFormat:o,setNumber:i}){let s={setNumber:i},{setTo:a,tiebreakFormat:c,tiebreakAt:u,tiebreakSet:p,timed:m,minutes:d}=o,l=Jn(0,t.length-1),f=t[l],g;if(m){let I=d*e,h=Math.round(I*.2),S=I+xr([1,-1])*h,T=kC(S,2),A=[T,S-T];f&&A.reverse(),g=t[l]+1;let D=A[0]>A[1]&&1||A[1]>A[0]&&2||0;if(n){let[U,M]=A;return Object.assign(s,{side1Score:U,side2Score:M}),ae.includes(r)?{set:s,incomplete:n,winningSideNumber:g}:{set:s,incomplete:n}}D||(A[Jn(0,1)]+=1),D=A[0]>A[1]?1:2,D!==g&&A.reverse();let[y,E]=A;return Object.assign(s,{side1Score:y,side2Score:E,winningSide:g}),{set:s}}else{if(n)return s.side1Score=Jn(0,u),s.side2Score=Jn(0,u),ae.includes(r)&&(g=t[l]+1),{set:s,incomplete:n,winningSideNumber:g};{let I=Z(1,a+1).map(E=>Z(0,a+2-E).map(()=>E)).flat(),h=I[Jn(0,I.length-1)],S=a&&Ag({isSide1:!0,tiebreakAt:u,lowValue:h,setTo:a}),T=!S,A=t.length===1&&t[l]+1;if(!T){A?(S[0]>S[1]?1:2)!==A&&S.reverse():f&&S.reverse();let[E,U]=S;Object.assign(s,{side1Score:E,side2Score:U})}let D=Ru({matchUpScoringFormat:{setFormat:o},setObject:s}),y;if(D.hasTiebreakCondition||T){let{NoAD:E,tiebreakTo:U}=c||p||{},M=Z(1,U+1).map(C=>Z(0,U+2-C).map(()=>C)).flat(),P=M[Jn(0,M.length-1)],N=wp({isSide1:!0,tiebreakNoAd:E,tiebreakTo:U,lowValue:P});if(N)if(T){let C=N[0]>N[1]?1:2;A?C!==A&&N.reverse():f&&N.reverse(),[s.side1TiebreakScore,s.side2TiebreakScore]=N,y=N[0]>N[1]&&1||N[1]>N[0]&&2||void 0}else D.leadingSide===2?[s.side1TiebreakScore,s.side2TiebreakScore]=N:[s.side2TiebreakScore,s.side1TiebreakScore]=N}s.winningSide=D.winningSide||D.leadingSide||A||y}}return{set:s}}function ol(t){let{matchUpStatusProfile:e,completeAllMatchUps:r,randomWinningSide:n,tournamentRecord:o,completionGoal:i,drawDefinition:s,event:a}=t;if(!s)return{error:X};let c=t.matchUpFormat||s.matchUpFormat||a?.matchUpFormat,u=s.structures.slice().sort(ci),p=0,{matchUps:m,matchUpsMap:d}=re({contextFilters:{stages:[tt,at]},matchUpFilters:{matchUpTypes:[Bt],roundNumbers:[1]},inContext:!0,drawDefinition:s});if(m?.length){let g=a?.category?.ageCategoryCode||a?.category?.categoryName;if(g){let h=rA({singlesOnly:!0,tournamentRecord:o,drawDefinition:s,scaleAccessor:{scaleName:g,sortOrder:EN,scaleType:oi},event:a});if(h.error)return h;let{lineUps:S,participantsToAdd:T}=h;In({tournamentRecord:o,participants:T}),St({element:s,extension:{name:ho,value:S}})}else{let I=m[0]?.structureId,{positionAssignments:h}=Nt({drawDefinition:s,structureId:I});if(h?.length){let{participants:S}=Yt({participantFilters:{participantTypes:[Bt]},tournamentRecord:o}),T=A=>{let D=A.tieMatchUps.filter(ie(Xt)),y=A.tieMatchUps.filter(ie(Gt));D.forEach((E,U)=>{let M=E.matchUpId;E.sides.forEach(P=>{let{drawPosition:N}=P,C=S?.find(O=>{let{participantId:b}=O;return h.find(w=>w.participantId===b)?.drawPosition===N});if(C){let O=C.individualParticipantIds?.[U];O&&Xd({teamParticipantId:C.participantId,participantId:O,tournamentRecord:o,drawDefinition:s,tieMatchUpId:M,event:a})}})}),y.forEach((E,U)=>{let M=E.matchUpId;E.sides.forEach(P=>{let{drawPosition:N}=P,C=S?.find(O=>{let{participantId:b}=O;return h.find(w=>w.participantId===b)?.drawPosition===N});C&&C.individualParticipantIds?.slice(U*2,U*2+2)?.forEach(b=>{Xd({teamParticipantId:C.participantId,participantId:b,tournamentRecord:o,drawDefinition:s,tieMatchUpId:M,event:a})})})})};m.forEach(T)}}}let l=typeof r=="string"&&r,f=l&&me;for(let g of u){if(p>=i)break;let{matchUps:I}=At({matchUpFilters:{matchUpTypes:[Gt,Xt]},afterRecoveryTimes:!1,tournamentRecord:o,inContext:!0,drawDefinition:s,matchUpsMap:d,structure:g,event:a}),h=I.filter(({winningSide:S})=>!S).sort(hi).map(fe);for(let S of h){if(!isNaN(i)&&p>=i)break;let{matchUps:T}=At({matchUpFilters:{matchUpTypes:[Gt,Xt]},afterRecoveryTimes:!1,tournamentRecord:o,inContext:!0,drawDefinition:s,matchUpsMap:d,structure:g,event:a}),A=T.find(y=>y.matchUpId===S),D=[ge,Ne].includes(A.matchUpStatus);if(A?.readyToScore&&!D){let y=WV({winningSide:!n&&1,matchUpStatusProfile:e,tournamentRecord:o,drawDefinition:s,targetMatchUp:A,matchUpFormat:c,matchUpStatus:f,scoreString:l,event:a});if(y?.error)return y;p+=1}}}return{...R,completedCount:p}}function qN(t){let{matchUpStatusCodes:e,policyDefinitions:r,tournamentRecord:n,drawDefinition:o,targetMatchUp:i,matchUpStatus:s,matchUpFormat:a,scoreString:c,winningSide:u,event:p}=t;if(!i||i.matchUpStatus===Dt)return;let{matchUpId:m}=i||{},{outcome:d}=kg({matchUpFormat:a,matchUpStatus:s,scoreString:c,winningSide:u});return e&&(d.matchUpStatusCodes=e),xu({tournamentRecord:n,policyDefinitions:r,drawDefinition:o,matchUpFormat:a,matchUpId:m,outcome:d,event:p})}function WV(t){let{matchUpStatusProfile:e={},tournamentRecord:r,policyDefinitions:n,drawDefinition:o,matchUpStatus:i,matchUpFormat:s,targetMatchUp:a,scoreString:c,winningSide:u,event:p}=t;if(c||i)return qN(t);let{matchUpId:m}=a||{},{outcome:d}=jg({matchUpStatusProfile:e,matchUpFormat:s,winningSide:u});return xu({policyDefinitions:n,tournamentRecord:r,drawDefinition:o,matchUpFormat:s,matchUpId:m,outcome:d,event:p})}function _A({matchUpStatusProfile:t,completeAllMatchUps:e,randomWinningSide:r,tournamentRecord:n,drawProfiles:o,event:i}){let s=Ht({event:i}).flightProfile,{eventName:a,eventType:c,category:u}=i,{startDate:p}=n,m=[],d=u?.categoryName||u?.ageCategoryCode||u?.ratingType,l=i.drawDefinitions?.map(({drawId:f})=>f);if(Array.isArray(s?.flights))for(let[f,g]of s.flights.entries()){let{drawId:I,stage:h,drawName:S,drawEntries:T}=g;m.push(g.drawId);let A=o[f],{seedsCount:D,generate:y=!0}=A||{};if(y){let E=T.filter(Pr(Bn)).map(Pr(Bn)),U=d||a;if(n&&D&&D<=E.length&&Z(1,D+1).forEach((x,w)=>{let F={scaleValue:x,scaleName:U,scaleType:eo,eventType:c,scaleDate:p},L=E[w];ba({tournamentRecord:n,participantId:L,scaleItem:F})}),l?.includes(I))break;let M=_u({...A,matchUpType:c,seedingScaleName:U,tournamentRecord:n,isMock:!0,drawEntries:T,drawName:S,drawId:I,event:i,stage:h});if(M.error)return{error:M.error,drawIds:[]};let{drawDefinition:P}=M;if(!P)return{error:pr};let N=o[f]?.drawExtensions;if(Array.isArray(N)&&N.filter(Pn).forEach(b=>St({element:P,extension:b})),M=Hp({suppressNotifications:!0,tournamentRecord:n,drawDefinition:P,event:i}),M.error)return{error:M.error,drawIds:[]};if(A?.withPlayoffs){let b=P.structures?.[0].structureId,x=Dp({idPrefix:A.idPrefix,...A.withPlayoffs,tournamentRecord:n,drawDefinition:P,isMock:!0,structureId:b,event:i});if(x?.error)return x}let C=A?.completionGoal;if(!(A?.automated===!1)&&(e||C)){let b=A?.matchUpFormat,x=ol({completeAllMatchUps:!C&&e,matchUpStatusProfile:t,randomWinningSide:r,tournamentRecord:n,completionGoal:C,drawDefinition:P,matchUpFormat:b,event:i});if(x.error)return{error:x.error,drawIds:[]};let w=x.completedCount;if(A?.drawType===so){let F=P.structures?.find(B=>B.stage===tt);if(!F)return{error:Lt};let L=Sc({structureId:F.structureId,tournamentRecord:n,drawDefinition:P,event:i});if(L.error)return{error:L.error,drawIds:[]};let v=C?C-(w??0):void 0;if(L=ol({completeAllMatchUps:!C&&e,completionGoal:C?v:void 0,matchUpStatusProfile:t,randomWinningSide:r,tournamentRecord:n,drawDefinition:P,matchUpFormat:b,event:i}),L.error)return{error:L.error,drawIds:[]}}}}}return{...R,drawIds:m}}function vA(t){let{participantsProfile:e={},uniqueParticipantsCount:r,ratingsParameters:n,tournamentRecord:o,eventProfile:i,eventIndex:s,event:a,uuids:c}=t,{category:u,gender:p,eventType:m}=a,d=ie(ao)(m)&&ht||ie(Kr)(m)&&dt||m,l=r[tt]||0,f=r[at]||0,g=i.drawProfiles?.length?l+f:i.participantsProfile?.participantsCount??0,I=[ee,ue].includes(p)?p:void 0,h=e?.idPrefix?`E-${s}-${e?.idPrefix}`:void 0,{participants:S}=vc({uuids:i.uuids||c,...e,scaledParticipantsCount:i.scaledParticipantsCount,consideredDate:o?.startDate,rankingRange:i.rankingRange,participantType:d,participantsCount:g,ratingsParameters:n,category:u,idPrefix:h,sex:I}),A=In({tournamentRecord:o,participants:S});if(A.error)return A;let D=S?.filter(({participantType:E})=>E===d),y=S?.map(gt);return{uniqueDrawParticipants:D,uniqueParticipantIds:y}}function lx({autoEntryPositions:t,tournamentRecord:e,drawParticipants:r,drawProfile:n,event:o}){let{drawType:i=io,qualifyingPositions:s=0,stage:a=tt,drawSize:c=0,drawName:u,drawId:p}=n,m=c-s,d=r.slice(0,m).map(gt);if(d.length){let g=Kn({participantIds:d,autoEntryPositions:t,entryStage:a,tournamentRecord:e,event:o});if(g.error)return g}let l=d.map(g=>({entryStatus:Zr,entryStage:a,participantId:g})),f=Wp({drawName:u||i,qualifyingPositions:s,drawEntries:l,drawId:p,event:o,stage:a});return f.error?f:{...R}}function xA({uniqueDrawParticipants:t,autoEntryPositions:e,stageParticipants:r,tournamentRecord:n,drawProfiles:o,category:i,gender:s,event:a}){let c=0;for(let u of o){let{qualifyingPositions:p=0,uniqueParticipants:m,stage:d=tt,drawSize:l=0}=u,f=l-p,g=m||s||i||d===at,I=g?t.slice(c,c+f):r[d||tt]||[];g&&(c+=f);let h=lx({autoEntryPositions:e,drawParticipants:I,tournamentRecord:n,drawProfile:u,event:a});if(h.error)return h}return{...R}}function wA(t){let{allUniqueParticipantIds:e,matchUpStatusProfile:r,participantsProfile:n,completeAllMatchUps:o,autoEntryPositions:i,hydrateCollections:s,randomWinningSide:a,ratingsParameters:c,tournamentRecord:u,eventProfile:p,eventIndex:m,publish:d,isMock:l,uuids:f}=t,g=p.gender,I=p.eventName,{eventType:h=ao,policyDefinitions:S,drawProfiles:T=[],eventExtensions:A,surfaceCategory:D,tieFormatName:y,processCodes:E,discipline:U,eventLevel:M,timeItems:P,ballType:N,category:C}=p,O=p.eventId||Mt(),b=p.tieFormat||(h===Fe?Bi({namedFormat:y,event:{eventId:O,category:C,gender:g},hydrateCollections:s,isMock:l}):void 0),x=u.participants;for(let q of T)!g&&q.gender&&(g=q?.gender);let{stageParticipantsCount:w,uniqueParticipantsCount:F,uniqueParticipantStages:L}=bA({drawProfiles:T,category:C,gender:g}),v=ie(ao)(h)&&ht||ie(Kr)(h)&&dt||h,{uniqueDrawParticipants:B=[],uniqueParticipantIds:H=[]}=L?vA({event:{eventType:h,category:C,gender:g},uniqueParticipantsCount:F,participantsProfile:n,ratingsParameters:c,tournamentRecord:u,eventProfile:p,eventIndex:m,uuids:f}):{},{eventAttributes:j}=p;typeof j!="object"&&(j={});let V=C?.categoryName||C?.ageCategoryCode||C?.ratingType;I=I||V||"Generated Event";let Y={...j,surfaceCategory:D,processCodes:E,discipline:U,eventLevel:M,eventName:I,eventType:h,tieFormat:b,ballType:N,category:C,eventId:O,gender:g};if(A?.length&&Array.isArray(A)){let q=A.filter(Pn);q?.length&&Object.assign(Y,{extensions:q})}if(Array.isArray(P)&&P.forEach(q=>ki({event:K,timeItem:q})),typeof S=="object")for(let q of Object.keys(S))Vi({policyDefinitions:{[q]:S[q]},event:Y});Y.category&&(Y.category.categoryName=V);let $,k=Mc({suppressNotifications:!1,internalUse:!0,tournamentRecord:u,event:Y});if(k.error)return k;let K=k?.event,{stageParticipants:z}=OA({allUniqueParticipantIds:e,stageParticipantsCount:w,eventParticipantType:v,targetParticipants:x});if(T?.length){let q=xA({uniqueDrawParticipants:B,autoEntryPositions:i,stageParticipants:z,tournamentRecord:u,drawProfiles:T,category:C,gender:g,event:K});if(q.error)return q;let nt=_A({matchUpStatusProfile:r,completeAllMatchUps:o,randomWinningSide:a,tournamentRecord:u,drawProfiles:T,event:K});if(nt.error)return nt;$=nt.drawIds}else if(p?.participantsProfile?.participantsCount){let q=B.map(gt);if(q.length){let nt=Kn({participantIds:q,autoEntryPositions:i,tournamentRecord:u,entryStage:tt,event:K});if(nt.error)return nt}}return d&&Js({tournamentRecord:u,event:K}),{drawIds:$,eventId:O,uniqueParticipantIds:H}}function Yg({tournamentRecords:t,scheduleDate:e,venueId:r,round:n}){if(!Rr(e))return{error:ar};let o="addSchedulingProfileRound",{extension:i}=mt({name:da,tournamentRecords:t,discover:!0}),s=i?.value||[],a=s.find(l=>_n(e,l.scheduleDate));if(!a){let{startDate:l,endDate:f}=wd({tournamentRecords:t}),g=new Date(e);if(l&&g<new Date(l)||f&&g>new Date(f))return{error:ar};a={scheduleDate:e,venues:[]},s.push(a)}let c=a.venues.find(l=>l.venueId===r);c||(c={venueId:r,rounds:[]},a.venues.push(c));let u=["notBeforeTime"],p=l=>Object.keys(l).filter(f=>!u.includes(f)).sort().map(f=>Rt(l[f])?p(l[f]):l[f]).flat().join("|");if(c.rounds.find(l=>p(l)===p(n)))return _({result:{error:dy},stack:o});c.rounds.push(n);let d=Dc({tournamentRecords:t,schedulingProfile:s});return d.error?d:{...R}}function fx({schedulingProfile:t,tournamentRecord:e}){if(typeof t!="object")return{error:G};let r=Ji({tournamentRecord:e}).containedStructures,n=le({tournamentRecord:e}).matchUps??[],{tournamentId:o}=e,i=[];for(let s of t){let{scheduleDate:a,venues:c=[]}=s;for(let u of c){let{rounds:p,venueId:m}=u;for(let d of p){let{drawId:l,winnerFinishingPositionRange:f,roundSegment:g}=d,h=n.filter(S=>{let T=f?.indexOf("-")>0&&f.split("-").map(D=>+D),A=S.finishingPositionRange?.winner;return S.drawId===l&&(!d.roundNumber||S.roundNumber===d.roundNumber)&&(!A||!T||jt(A,T).length===2||pt(A).length===pt(T).length&&jt(A,T).length===pt(A).length)})[0];if(h){let{eventId:S,roundNumber:T,drawName:A,structureName:D,roundName:y}=h,E=h.structureId;T&&!f&&(E=Object.keys(r).find(P=>r[P].includes(E))??E);let U={tournamentId:o,structureId:E,roundNumber:T,roundSegment:g,eventId:S,drawId:l},M=Yg({tournamentRecords:{[o]:e},round:U,scheduleDate:a,venueId:m});if(M.error)return M;i.push({structureName:D,roundName:y,drawName:A,...U})}}}}return{scheduledRounds:i}}function Jp(t){let e=lt(t,[{drawProfile:!0,_ofType:Ri}]);if(e.error)return e;let{allUniqueParticipantIds:r=[],participantsProfile:n={},matchUpStatusProfile:o,completeAllMatchUps:i,autoEntryPositions:s,hydrateCollections:a,randomWinningSide:c,ratingsParameters:u,tournamentRecord:p,isMock:m=!0,drawProfile:d,startDate:l,drawIndex:f,uuids:g}=t,I=J(d,!1,!0),{excessParticipantAlternates:h=!0,matchUpFormat:S=un,drawType:T=io,tournamentAlternates:A=0,alternatesCount:D=0,qualifyingPositions:y,qualifyingProfiles:E,generate:U=!0,eventExtensions:M,drawExtensions:P,completionGoal:N,tieFormatName:C,seedsCount:O,timeItems:b,drawName:x,category:w,idPrefix:F,publish:L,gender:v,stage:B}=I,H=I.drawSize||(I.ignoreDefaults?void 0:32),j=I.eventId||Mt(),V=d.eventType||d.matchUpType||ao,Y=V===Kr?dt:ht,$=typeof d.tieFormat=="object"&&d.tieFormat||V===kt&&Bi({event:{eventId:j,category:w,gender:v},namedFormat:C,hydrateCollections:a,isMock:m})||void 0,k=w?.categoryName||w?.ageCategoryCode||w?.ratingType,K=d.eventName||k||`Generated ${V}`,z=p?.participants||[],q=(E?.map(Ct=>Ct.structureProfiles||[]).flat().reduce((Ct,vt)=>{let ne=!vt.participantsCount||vt.participantsCount>vt.drawSize?vt.drawSize:vt.participantsCount||0;return Ct+ne},0)||0)*(Y===dt?2:1),nt=(!d.participantsCount||d.participantsCount>H?H:d.participantsCount)||0,Q={eventName:K,eventType:V,tieFormat:$,category:w,eventId:j,gender:v};Array.isArray(b)&&b.forEach(Ct=>ki({event:Q,timeItem:Ct}));let{eventAttributes:it}=d;if(typeof it!="object"&&(it={}),Object.assign(Q,it),M?.length&&Array.isArray(M)){let Ct=M.filter(Pn);Ct?.length&&Object.assign(Q,{extensions:Ct})}let ot=[];if(q||d.uniqueParticipants||!p||v||w){let Ct=(nt||0)+D+q,vt=Ct,ne={[ee]:0,[ue]:0},qt,pe;V===kt&&({teamSize:qt,genders:pe}=CA({alternatesCount:D,tieFormatName:C,tieFormat:$,drawSize:H}),Object.keys(pe).forEach(Wt=>{[ee,ue].includes(Wt)&&pe[Wt]&&(ne[Wt]=H*pe[Wt])}),vt=qt*((H||0)+q));let he=n?.idPrefix?`D-${f}-${n?.idPrefix}`:void 0,_e=vc({...n,scaledParticipantsCount:d.scaledParticipantsCount||n.scaledParticipantsCount,participantsCount:vt,consideredDate:p?.startDate,sex:v||n?.sex,rankingRange:d.rankingRange,uuids:d.uuids||g,ratingsParameters:u,participantType:Y,gendersCount:ne,idPrefix:he,category:w}).participants;if(Q.category&&(Q.category.categoryName=k),p){let Wt=In({participants:_e,tournamentRecord:p});if(Wt.error)return Wt}if(_e.forEach(({participantId:Wt})=>ot.push(Wt)),z=_e,V===kt){let Wt=pe[ee]?_e.filter(({participantType:qe,person:bn})=>qe===ht&&bn?.sex===ee).map(gt):[],ve=pe[ue]?_e.filter(({participantType:qe,person:bn})=>qe===ht&&bn?.sex===ue).map(gt):[],nr=_e.filter(({participantType:qe})=>qe===ht).map(gt).filter(qe=>!Wt.includes(qe)&&!ve.includes(qe)),be=qt-(pe[ee]+pe[ue]),Nr=0,Se=0,Pe=0,gr=Z(0,Ct).map(qe=>{let bn=ve.slice(Nr,Nr+pe[ue]),Ei=Wt.slice(Se,Se+pe[ee]),Wi=nr.slice(Pe,Pe+be);return Nr+=pe[ue],Se+=pe[ee],Pe+=be,{individualParticipantIds:[...bn,...Ei,...Wi],participantOtherName:`TM${qe+1}`,participantName:`Team ${qe+1}`,participantRole:Ge,participantType:kt,participantId:Mt()}}),ri=In({participants:gr,tournamentRecord:p});if(!ri.success)return ri;z=gr}}let ut=Ct=>{let{participantType:vt}=Ct;return ie(ao)(V)&&vt===ht||ie(Kr)(V)&&vt===dt?!0:V===kt&&vt===kt},Qt=Ct=>!d.gender||Ct.person?.sex===d.gender?!0:Ct.individualParticipantIds?.some(vt=>{let ne=z.find(qt=>qt.participantId===vt);return ne&&Qt(ne)}),yt=z.filter(ut).filter(Qt).filter(({participantId:Ct})=>!r.includes(Ct)),Me=yt.slice(0,nt).map(Ct=>Ct.participantId);if(m&&Me?.length){let Ct=Kn({autoEntryPositions:s,entryStage:B,tournamentRecord:p,participantIds:Me,event:Q});if(Ct.error)return Ct}let Ee=q?yt.slice(nt,nt+q).map(Ct=>Ct.participantId):0;if(m&&Ee?.length){let Ct=0,vt=1,ne=(pe,he)=>pe.stageSequence-he.stageSequence,qt=(pe,he)=>pe.roundTarget-he.roundTarget;for(let pe of E.sort(qt)){vt=pe.roundTarget||vt;let he=1,ur;for(let _e of pe.structureProfiles.sort(ne)){let ve=(_e.drawSize||am(_e.participantsCount))-(ur||0),nr=Ee.slice(Ct,Ct+ve),be=Kn({entryStage:at,entryStageSequence:he,autoEntryPositions:s,tournamentRecord:p,participantIds:nr,roundTarget:vt,event:Q});if(be.error)return be;ur=_e.qualifyingPositions,Ct+=ve,he+=1}vt+=1}}let Ce=h&&p?.participants?.filter(({participantId:Ct})=>!Me.includes(Ct)).filter(ut).filter(Qt).slice(0,D||H-nt||A).map(Ct=>Ct.participantId);if(m&&Ce?.length){let Ct=Kn({participantIds:Ce,autoEntryPositions:!1,entryStatus:wr,tournamentRecord:p,event:Q});if(Ct.error)return Ct.error}let Kt=k||K;p&&O&&O<=Me.length&&Z(1,O+1).forEach((vt,ne)=>{let qt={scaleName:Kt,scaleDate:l,scaleType:Of,scaleValue:vt,eventType:V},pe=Me[ne];ba({tournamentRecord:p,participantId:pe,scaleItem:qt})});let Re=_u({...J(d,!1,!0),tournamentRecord:p,seedingScaleName:Kt,matchUpFormat:S,eventId:j,isMock:m,event:Q});if(Re.error)return Re;if(!Re.drawDefinition)return{error:pr};let{drawDefinition:wt}=Re,Ue=wt.drawId;if(Array.isArray(P)&&P.filter(Pn).forEach(Ct=>St({element:wt,extension:Ct})),U){if(Hp({drawDefinition:wt,event:Q,suppressNotifications:!0}),d.withPlayoffs){let vt=wt.structures?.[0].structureId,ne=Dp({...d.withPlayoffs,tournamentRecord:p,drawDefinition:wt,structureId:vt,idPrefix:F,isMock:m,event:Q});if(ne?.error)return ne}let Ct=d.automated===!1;if(m&&!Ct){let vt=ne=>{let qt=ol({completeAllMatchUps:ne.completeAllMatchUps,completionGoal:ne.completionGoal,matchUpStatusProfile:o,randomWinningSide:c,tournamentRecord:p,drawDefinition:wt,matchUpFormat:S,event:Q});if(qt.error)return qt;let pe=qt.completedCount;if(T===so){let he=wt.structures?.find(Wt=>Wt.stage===tt);if(!he)return{error:Lt};Sc({structureId:he.structureId,tournamentRecord:p,drawDefinition:wt,event:Q});let ur=N?N-(pe??0):void 0,_e=ol({completionGoal:N?ur:void 0,matchUpStatusProfile:o,completeAllMatchUps:i,randomWinningSide:c,tournamentRecord:p,drawDefinition:wt,matchUpFormat:S,event:Q});if(_e.error)return _e}};if(N&&vt({completionGoal:N}),d.outcomes){let{matchUps:ne}=rr({inContext:!0,drawDefinition:wt,event:Q});for(let qt of d.outcomes){let{matchUpStatus:pe=me,matchUpStatusCodes:he,stageSequence:ur=1,matchUpIndex:_e=0,structureOrder:Wt,matchUpFormat:ve,drawPositions:nr,roundPosition:be,stage:Nr=tt,roundNumber:Se,winningSide:Pe,scoreString:gr}=qt,ri=ne?.reduce((hn,wc)=>{let{structureId:ji,matchUpId:eI}=wc;return hn[ji]?hn[ji].push(eI):hn[ji]=[eI],hn},{})??[],qe=Object.assign({},...Object.keys(ri).map((hn,wc)=>({[hn]:wc+1}))),Ei=ne?.filter(hn=>(!Nr||hn.stage===Nr)&&(!ur||hn.stageSequence===ur)&&(!Se||hn.roundNumber===Se)&&(!be||hn.roundPosition===be)&&(!Wt||qe[hn.structureId]===Wt)&&(!nr||jt(nr,hn.drawPositions).length===2))?.[_e],Wi=qN({matchUpStatusCodes:he,tournamentRecord:p,drawDefinition:wt,targetMatchUp:Ei,matchUpFormat:ve,matchUpStatus:pe,scoreString:gr,winningSide:Pe});if(Wi?.error)return Wi}}i&&vt({completeAllMatchUps:i})}L&&Js({tournamentRecord:p,event:Q})}else{let Ct=Wp({drawEntries:wt.entries,drawName:x||T,qualifyingPositions:y,drawId:Ue,event:Q,stage:B});if(Ct.error)return Ct}return{...R,event:rt(Q),uniqueParticipantIds:ot,targetParticipants:z,drawDefinition:wt,eventId:j,drawId:Ue}}var $N=()=>({altitude:void 0,courtId:void 0,courtName:"",courtDimensions:void 0,latitude:void 0,longitude:void 0,surfaceCategory:void 0,surfaceType:void 0,surfacedDate:void 0,dateAvailability:[],onlineResources:[],pace:void 0,notes:void 0}),gx=$N;function LA(t){return parseInt(t)}function KN({startTime:t="",endTime:e=""}={}){if(!t||!e||!Rs.test(t)||!Rs.test(e))return!1;let[r,n]=t.split(":").map(LA),[o,i]=e.split(":").map(LA);return o<r?!1:!(r===o&&i<n)}function Ix(t,e){let[r,n]=t.startTime.split(":").map(LA),[o,i]=e.startTime.split(":").map(LA);return r<o?-1:r>o?1:n<i?-1:n>i?1:0}function FA({dateAvailability:t}){if(!t)return{error:Dy};if(!Array.isArray(t))return{error:Ul};let e="Dates must be formated => YYYY-MM-DD",r="Times must be 24 hour => 00:00";for(let n of t){if(typeof n!="object")return{error:Ul};let{date:o,startTime:i,endTime:s,bookings:a=[]}=n;if(!i||!s)return{error:Ul};if(o&&!Ro.test(o))return{error:ar,dateAvailability:{date:o},info:e};if(!Rs.test(i))return{error:mo,dateAvailability:{startTime:i},info:r};if(!Rs.test(s))return{error:mo,dateAvailability:{endTime:s},info:r};if(i===s)return{error:mo,dateAvailability:{startTime:i,endTime:s},info:"startTime and endTime are equivalent"};if(!KN({startTime:i,endTime:s}))return{error:mo,dateAvailability:{startTime:i,endTime:s},info:"endTime must be after startTime"};if(a){if(!Array.isArray(a))return{error:om};for(let c of a){if(typeof c!="object")return{error:om};let{startTime:u,endTime:p}=c;if(!Rs.test(u))return{error:mo,booking:{startTime:u},info:r};if(!Rs.test(p))return{error:mo,booking:{endTime:p},info:r};if(u===p)return{error:mo,dateAvailability:{startTime:u,endTime:p},info:"startTime and endTime are equivalent"};if(!KN({startTime:u,endTime:p}))return{error:mo,dateAvailability:{startTime:u,endTime:p},info:"endTime must be after startTime"}}}}return{valid:!0}}function il({tournamentRecord:t,disableNotice:e,venueId:r,courtId:n,court:o}){let{venue:i}=Qo({tournamentRecord:t,venueId:r});if(!i)return{error:Ds};i.courts||(i.courts=[]);let s={...$N(),venueId:r,courtId:n};if(s.courtId||(s.courtId=Mt()),i.courts.some(c=>c.courtId===s.courtId))return{error:By};{let c=(o?.dateAvailability||[]).map(m=>({...m,date:Ut(m.date),startTime:$t(m.startTime),endTime:$t(m.endTime),bookings:m.bookings?.map(({startTime:d,endTime:l,bookingType:f})=>({startTime:$t(d),endTime:$t(l),bookingType:f}))})),u=Object.keys(s);for(let m of u)if(o?.[m])if(m==="dateAvailability"){let d=FA({dateAvailability:c});if(!d.valid&&d.error)return d;s.dateAvailability=c}else s[m]=o[m];let p=s;return i.courts.push(p),e||Tt({payload:{venue:i,tournamentId:t.tournamentId},topic:ui,key:i.venueId}),{...R,court:J(s),venueId:r}}}function qg(t){let{tournamentRecord:e,venueId:r}=t;if(typeof r!="string"||!r)return{error:Bo};let n=t.tournamentRecords??(e&&{[e.tournamentId]:e})??{},o=[],i;for(let s of Object.values(n)){let{venue:a}=Qo({tournamentRecord:s,venueId:r});if(a){let c=jV({...t,tournamentRecord:s});for(let u of c?.courts??[])o.push(u?.courtId);if(c.error)return c;i=!0}}return i?{...R,courtIds:o}:{error:Ds}}function jV({courtNameRoot:t="Court",dateAvailability:e=[],venueAbbreviationRoot:r,tournamentRecord:n,courtNames:o=[],courtTimings:i,courtsCount:s,startTime:a,courtIds:c,endTime:u,idPrefix:p,venueId:m,dates:d}){if(!m)return{error:Bo};let l=Qo({tournamentRecord:n,venueId:m});if(l.error)return l;let{venue:f}=l;if(!te(s)||!o)return{error:Vy};s=s??o.length;let h=Z(0,s).map(S=>{let T=i?.[S],A=T?d.map(D=>({date:ro(D),startTime:a,endTime:u,...T})):e;return T&&a&&u&&A.push({startTime:a,endTime:u}),{courtName:o[S]||r&&f?.venueAbbreviation&&`${f?.venueAbbreviation} ${S+1}`||`${t} ${S+1}`,dateAvailability:A}}).map((S,T)=>{let A=c?.pop()||p&&`${p}-${T+1}`;return il({disableNotice:!0,tournamentRecord:n,courtId:A,venueId:m,court:S})}).map(S=>S.court).filter(Boolean);return h.length!==s?_({info:"not all courts could be generated",result:{error:G}}):(f&&Tt({payload:{venue:f,tournamentId:n.tournamentId},topic:ui,key:f.venueId}),{...R,courts:J(h)})}function GA({tournamentRecord:t,venueProfiles:e,uuids:r}){let{startDate:n,endDate:o}=t,i=[];for(let[s,a]of e.entries()){let{venueAbbreviation:c,venueId:u=r?.pop()??Mt(),dateAvailability:p,startTime:m="07:00",endTime:d="19:00",courtTimings:l,courtsCount:f,courtNames:g,venueName:I,idPrefix:h,courtIds:S}=a,T={venueName:I||`Venue ${s+1}`,venueAbbreviation:c,venueId:u},A=pc({tournamentRecord:t,venue:T});if(A.error)return A;i.push(u);let D=bs(n,o),y=!Array.isArray(p)&&[{startTime:m,endTime:d}].concat(D.map(U=>({date:ro(U),startTime:m,endTime:d}))),E=qg({dateAvailability:p||y,tournamentRecord:t,courtTimings:l,courtsCount:f,courtNames:g,startTime:m,idPrefix:h,courtIds:S,endTime:d,venueId:u,dates:D});if(E.error)return E}return i}var YV=["Mock Tournament","CourtHive Challenge","Racket Rally","Generated Tournament","Factory Follies","Open Competition"];function zN(t){let{tournamentAttributes:e,startDate:r,endDate:n}=t??{},{tournamentName:o=xr(YV),ratingsParameters:i=Br,scheduleCompletedMatchUps:s,tournamentExtensions:a,matchUpStatusProfile:c,completeAllMatchUps:u,participantsProfile:p,autoEntryPositions:m,hydrateCollections:d,randomWinningSide:l,policyDefinitions:f,schedulingProfile:g,periodLength:I,autoSchedule:h,eventProfiles:S,venueProfiles:T,drawProfiles:A,uuids:D}=t??{};if(r&&!Rr(r)||n&&!Rr(n))return{error:ar};if(S&&!Array.isArray(S))return{error:G};if(!r){let b=new Date;r=ro(n??b),n=ro(b.setDate(b.getDate()+7))}if(!n){let b=new Date(r);n=ro(b.setDate(b.getDate()+7))}typeof e!="object"&&(e={});let y=AA({...e,tournamentName:o,isMock:!0,startDate:r,endDate:n});if(a?.length&&Array.isArray(a)){let b=a.filter(x=>Pn({extension:x}));b?.length&&Object.assign(y,{extensions:b,isMock:!0})}if(typeof f=="object")for(let b of Object.keys(f))Vi({policyDefinitions:{[b]:f[b]},tournamentRecord:y});let E=RA({participantsProfile:p,tournamentRecord:y,eventProfiles:S,drawProfiles:A,startDate:r,uuids:D});if(!E.success)return E;let U=[],M=[],P=[];if(Array.isArray(A)){let b=0;for(let x of A){let w=Jp({allUniqueParticipantIds:U,matchUpStatusProfile:c,completeAllMatchUps:u,autoEntryPositions:m,hydrateCollections:d,participantsProfile:p,randomWinningSide:l,ratingsParameters:i,tournamentRecord:y,isMock:!0,drawProfile:x,startDate:r,drawIndex:b,uuids:D});if(w.error)return w;let{drawId:F,eventId:L,event:v,uniqueParticipantIds:B}=w;if(w=Mc({suppressNotifications:!1,internalUse:!0,tournamentRecord:y,event:v}),w.error)return w;F&&P.push(F),M.push(L),B?.length&&U.push(...B),b+=1}}if(S){let b=0;for(let x of S){let w=wA({allUniqueParticipantIds:U,matchUpStatusProfile:c,participantsProfile:p,completeAllMatchUps:u,autoEntryPositions:m,hydrateCollections:d,randomWinningSide:l,ratingsParameters:i,tournamentRecord:y,eventProfile:x,eventIndex:b,startDate:r,uuids:D});if(w.error)return w;let{eventId:F,drawIds:L,uniqueParticipantIds:v}=w;L&&P.push(...L),M.push(F),v?.length&&U.push(...v),b+=1}}let N=T?.length?GA({tournamentRecord:y,venueProfiles:T,uuids:D}):[],C,O={};if(g){let b=fx({schedulingProfile:g,tournamentRecord:y});if(b.error)return b;if(C=b.scheduledRounds,h){let{tournamentId:x}=y,w={[x]:y};O=Xp({scheduleCompletedMatchUps:s,tournamentRecords:w,periodLength:I})}}return Bl(),rt({...R,tournamentRecord:y,scheduledRounds:C,schedulerResult:O,eventIds:M,venueIds:N,drawIds:P})}var ZN={};Jt(ZN,{anonymizeTournamentRecord:()=>XN,modifyTournamentRecord:()=>JN});function XN({keepExtensions:t=[],anonymizeParticipantNames:e=!0,tournamentRecord:r,tournamentName:n,personIds:o=[],tournamentId:i}){if(!r)return{error:W};let s=Array.isArray(t)?EE.concat(...t):EE,a=v=>Array.isArray(t)?v?.extensions?.filter(B=>s.includes(B.name)):v?.extensions,c={};r.extensions=a(r);let u=i||Mt();c[r.tournamentId]=u,r.tournamentId=u,r.createdAt=new Date().toISOString(),r.tournamentName=n||`Anonymized: ${ro(new Date)}`,r.isMock=!0,delete r.parentOrganisation;for(let v of r.participants||[]){let B=Mt();c[v.participantId]=B,v.participantId=B}for(let v of r.participants||[])Array.isArray(v.individualParticipantIds)&&(v.individualParticipantIds=v.individualParticipantIds.map(B=>c[B]));let p=0;for(let v of r.venues||[]){v.extensions=a(v),v.venueName=`Venue #${p}`,v.venueAbbreviation=`V${p}`;let B=Mt();c[v.venueId]=B,v.isMock=!0,p+=1}let m=1;for(let v of r.events||[]){v.extensions=a(v),v.isMock=!0;let B=Mt();c[v.eventId]=B,v.eventId=B;let H=v.category?.categoryName||v.category?.ageCategoryCode||v.category?.ratingType||v.gender;if(v.eventName=`Event ${m} ${H}`,Array.isArray(v.entries))for(let V of v.entries)V.participantId=c[V.participantId];for(let V of v.drawDefinitions||[]){V.extensions=a(V);let Y=Mt();if(c[V.drawId]=Y,V.drawId=Y,V.isMock=!0,Array.isArray(V.entries))for(let k of V.entries)k.participantId=c[k.participantId];let $=k=>{k.extensions=a(k);let K=Mt();c[k.structureId]=K,k.structureId=K;for(let z of k.positionAssignments||[])z.participantId&&(z.participantId=c[z.participantId]);for(let z of k.seedAssignments||[])z.participantId&&(z.participantId=c[z.participantId]);for(let z of k.matchUps||[]){z.isMock=!0;for(let q of z.sides||[])q.lineUp&&(q.lineUp=q.lineUp.map(({participantId:nt,collectionAssignments:Q})=>({participantId:c[nt],collectionAssignments:Q})))}};for(let k of V.structures||[])if($(k),Array.isArray(k.structures))for(let K of k.structures)$(K);for(let k of V.links||[])k.source.structureId=c[k.source.structureId],k.target.structureId=c[k.target.structureId]}let{extension:j}=mt({name:qr,element:v});Array.isArray(j?.value?.flights)&&j?.value.flights?.forEach(V=>{if(V.drawId=c[V.drawId],Array.isArray(V.drawEntries))for(let Y of V.drawEntries)Y.participantId=c[Y.participantId]}),m+=1}let d=r.startDate||ro(new Date),l=(r.participants||[]).filter(({participantType:v})=>v===ht),f=l.reduce((v,B)=>{let H=B.person?.sex;return[ee,ue].includes(H)?v[H]+=1:v[ya]+=1,v},{[ee]:0,[ue]:0,[ya]:0}),g=Object.assign({},...Object.keys(f).map(v=>({[v]:NA({category:{ageCategoryCode:"O18"},count:f[v],addressProps:{citiesCount:10},personExtensions:[],consideredDate:d,sex:v})?.persons||[]}))),I={[ee]:0,[ue]:0,[ya]:0},h=l.length,S=l.reduce((v,B)=>{let H=B.person?.addresses?.[0]||{},{city:j,state:V,postalCode:Y}=H;return v.cities.includes(j)||v.cities.push(j),v.states.includes(V)||v.states.push(V),v.postalCodes.includes(Y)||v.postalCodes.push(Y),v},{cities:[],postalCodes:[],states:[]}),T=S.postalCodes.length,A=S.cities.length,D=S.states.length,{cities:y}=yA({count:A||h,participantsCount:h}),{states:E}=EA({count:D||h,participantsCount:h}),{postalCodes:U}=UA({count:T||h,participantsCount:h}),M={cities:y,states:E,postalCodes:U};l.forEach((v,B)=>{let H=v?.person,j=H?.sex||ya,V=Ut(H?.birthDate)?.split("-")[0],Y=I[j],$=g[j][Y];if(I[j]+=1,V){let[,k,K]=$?.birthDate?.split("-")||[],z=[V,k,K].join("-");$.birthDate=z}if(H?.addresses){let k=PA({...M,participantIndex:B,nationalityCode:$.nationalityCode});$.addresses=[k]}$.personId=o?.[B]||Mt(),e?($.standardFamilyName=$.lastName,$.standardGivenName=$.firstName,v.participantName=`${$.standardGivenName} ${$.standardFamilyName}`):($.standardFamilyName=H?.standardFamilyName,$.standardGivenName=H?.standardGivenName),delete $.firstName,delete $.lastName,$.extensions=a(H),v.person=$,c[H?.personId]=$.personId}),(r.participants||[]).filter(({participantType:v})=>v===dt).forEach(v=>{let{individualParticipantIds:B}=v;v.participantName=qV({individualParticipantIds:B,individualParticipants:l})});let N=(r.participants||[]).filter(({participantType:v})=>v===kt),C=N.length,O=Hg({count:C}).names;N.forEach((v,B)=>{v.participantName=O[B]});let b=(r.participants||[]).filter(({participantType:v})=>v===Ar),x=b.length,w=Hg({count:x,nameRoot:"Group"}).names;b.forEach((v,B)=>{v.participantName=w[B]});let{extension:F}=mt({element:r,name:da});Array.isArray(F?.value)&&F?.value.forEach(v=>{v.tournamentId=c[v.tournamentId],v.structureId=c[v.structureId],v.eventId=c[v.eventId],v.drawId=c[v.drawId]});let{extension:L}=mt({element:r,name:ma});return Array.isArray(L?.value)&&L?.value.forEach(v=>{v.personId=c[v.personId]}),{...R}}function qV({individualParticipantIds:t,individualParticipants:e}){let r=e.filter(({participantId:n})=>t.includes(n)).map(({person:n})=>n?.standardFamilyName).filter(Boolean).sort().join("/");return t.length===1&&(r+="/Unknown"),r}function JN(t){let{ratingsParameters:e=Br,participantsProfile:r={},matchUpStatusProfile:n,completeAllMatchUps:o,autoEntryPositions:i,hydrateCollections:s,randomWinningSide:a,schedulingProfile:c,tournamentRecord:u,eventProfiles:p,periodLength:m,venueProfiles:d,autoSchedule:l,drawProfiles:f,uuids:g}=t;if(!u)return{error:W};let I=[],h=[],S=[];p?.forEach(M=>{let P=u.events?.find((N,C)=>M.eventIndex!==void 0&&C===M.eventIndex||M.eventName&&N.eventName===M.eventName||M.eventId&&N.eventId===M.eventId);P?.gender&&(M.gender=P.gender)});let T=u.participants?.length||void 0;T&&r?.idPrefix&&(r.idPrefix=`${r.idPrefix}-${T}`);let A=RA({startDate:u.startDate,participantsProfile:r,tournamentRecord:u,eventProfiles:p,drawProfiles:f,uuids:g});if(!A.success)return A;if(p){let M=u.events?.length||0;for(let P of p){let{ratingsParameters:N}=P,C=u.events?.find((O,b)=>P.eventIndex!==void 0&&b===P.eventIndex||P.eventName&&O.eventName===P.eventName||P.eventId&&O.eventId===P.eventId);if(C){let{gender:O,category:b,eventType:x}=C,{drawProfiles:w,publish:F}=P,L=ie(ao)(x)&&ht||ie(Kr)(x)&&dt||x;if(w){let{stageParticipantsCount:v,uniqueParticipantsCount:B,uniqueParticipantStages:H}=bA({drawProfiles:w,category:b,gender:O}),{uniqueDrawParticipants:j=[],uniqueParticipantIds:V=[]}=H?vA({event:{eventType:x,category:b,gender:O},uniqueParticipantsCount:B,participantsProfile:r,ratingsParameters:N,tournamentRecord:u,eventProfile:P,uuids:g}):{};I.push(...V);let{stageParticipants:Y}=OA({targetParticipants:u.participants||[],allUniqueParticipantIds:I,stageParticipantsCount:v,eventParticipantType:L}),$=xA({uniqueDrawParticipants:j,autoEntryPositions:i,stageParticipants:Y,tournamentRecord:u,drawProfiles:w,category:b,gender:O,event:C});if($.error||($=_A({matchUpStatusProfile:n,completeAllMatchUps:o,randomWinningSide:a,tournamentRecord:u,drawProfiles:w,event:C}),$.error))return $;S.push(...$.drawIds)}F&&Js({tournamentRecord:u,event:C})}else{let O=wA({startDate:u.startDate,allUniqueParticipantIds:I,matchUpStatusProfile:n,participantsProfile:r,completeAllMatchUps:o,autoEntryPositions:i,randomWinningSide:a,ratingsParameters:N,tournamentRecord:u,eventProfile:P,eventIndex:M,uuids:g});if(O.error)return O;let{eventId:b,drawIds:x,uniqueParticipantIds:w}=O;x&&S.push(...x),h.push(b),w?.length&&I.push(...w),M+=1}}}if(f){let M=(u.events||[]).map(P=>P.drawDefinitions?.map(()=>1)||[]).flat().reduce((P,N)=>P+N,0);for(let P of f){let N=Jp({startDate:u.startDate,allUniqueParticipantIds:I,matchUpStatusProfile:n,participantsProfile:r,completeAllMatchUps:o,autoEntryPositions:i,hydrateCollections:s,randomWinningSide:a,ratingsParameters:e,tournamentRecord:u,drawProfile:P,drawIndex:M,uuids:g});if(N.error)return N;let{drawId:C,eventId:O,event:b,uniqueParticipantIds:x}=N;if(N=Mc({tournamentRecord:u,event:b,internalUse:!0}),N.error)return N;C&&S.push(C),h.push(O),x?.length&&I.push(...x),M+=1}}let D=d?.length?GA({tournamentRecord:u,venueProfiles:d}):[],y,E={};if(c?.length){let M={[u.tournamentId]:u},P=Dc({tournamentRecords:M,schedulingProfile:c});if(P.error)return P;if(l){let{tournamentId:N}=u,C={[N]:u};E=Xp({tournamentRecords:C,periodLength:m})}}return{totalParticipantsCount:u.participants.length,scheduledRounds:y,schedulerResult:E,...R,eventIds:h,venueIds:D,drawIds:S}}var TM={};Jt(TM,{addIndividualParticipantIds:()=>Yp,addParticipant:()=>gn,addParticipants:()=>In,addPenalty:()=>IM,addPersonRequests:()=>rM,addPersons:()=>hM,createGroupParticipant:()=>uM,createTeamsFromParticipantAttributes:()=>Bg,deleteParticipants:()=>Li,filterParticipants:()=>lu,findParticipant:()=>cM,getCompetitionParticipants:()=>IT,getPairedParticipant:()=>tn,getParticipantEventDetails:()=>hT,getParticipantMembership:()=>ST,getParticipantScaleItem:()=>Pc,getParticipantSchedules:()=>TT,getParticipantSignInStatus:()=>AT,getParticipantTimeItem:()=>Nh,getParticipants:()=>Yt,getScaleValues:()=>aa,mergeParticipants:()=>gM,modifyIndividualParticipantIds:()=>nM,modifyParticipant:()=>qp,modifyParticipantName:()=>pM,modifyParticipantOtherName:()=>iM,modifyParticipantsSignInStatus:()=>oM,modifyPenalty:()=>lM,modifyPersonRequests:()=>tM,mutate:()=>SM,participantScaleItem:()=>uo,query:()=>vD,regenerateParticipantNames:()=>aM,removeIndividualParticipantIds:()=>Hf,removeParticipantIdsFromAllTeams:()=>hp,removePenalty:()=>dM,removePersonRequests:()=>eM,scaledTeamAssignment:()=>mM,setParticipantScaleItem:()=>ba,setParticipantScaleItems:()=>AP,validateLineUp:()=>ed});var SM={};Jt(SM,{addIndividualParticipantIds:()=>Yp,addParticipant:()=>gn,addParticipants:()=>In,addPenalty:()=>IM,addPersonRequests:()=>rM,addPersons:()=>hM,createGroupParticipant:()=>uM,createTeamsFromParticipantAttributes:()=>Bg,deleteParticipants:()=>Li,findParticipant:()=>cM,mergeParticipants:()=>gM,modifyIndividualParticipantIds:()=>nM,modifyParticipant:()=>qp,modifyParticipantName:()=>pM,modifyParticipantOtherName:()=>iM,modifyParticipantsSignInStatus:()=>oM,modifyPenalty:()=>lM,modifyPersonRequests:()=>tM,regenerateParticipantNames:()=>aM,removeIndividualParticipantIds:()=>Hf,removeParticipantIdsFromAllTeams:()=>hp,removePenalty:()=>dM,removePersonRequests:()=>eM,scaledTeamAssignment:()=>mM,setParticipantScaleItem:()=>ba,setParticipantScaleItems:()=>AP});function kA(t=0){(typeof t!="number"||isNaN(t))&&(t=0);let e=new Date;return e.setHours(e.getHours()+t),e.getTime().toString(36).slice(-6).toUpperCase()}function VA({personRequests:t,personId:e,requests:r}){t[e]||(t[e]=[]);let n=r.filter(({requestType:o})=>o).map(o=>{let{date:i,startTime:s,endTime:a}=o;return o.requestType===Oc&&(i=Ut(i),s=$t(s),a=$t(a),i&&s&&a)?{date:i,startTime:s,endTime:a,requestType:o.requestType}:o}).filter(Boolean);for(let o of n)o.requestId=kA(),t[e].push(o);return{mergeCount:n.length}}function sl(t){let{tournamentRecords:e,personRequests:r}=t,n=lt(t,[{[ye]:!0}]);if(n.error)return n;if(!r)return{...R};let o=Object.values(e);for(let i of o){let s=i.participants??[],a=[];for(let c of Object.keys(r))if(bo({tournamentParticipants:s,personId:c})){let u=r[c];u.length&&a.push({personId:c,requests:u})}Object.keys(a).length&&St({element:i,extension:{value:a,name:ma}})}return{...R}}function tM(t){let{tournamentRecords:e,requests:r,personId:n}=t,o=lt(t,[{[ye]:!0},{requests:!0,[to]:Er,[En]:G}]);if(o.error)return o;let i=r.map(({requestId:u})=>u).filter(Boolean),{personRequests:s}=yi({tournamentRecords:e}),a=u=>{s&&(s[u]=s[u].map(p=>{if(!i.includes(p.requestId))return p;let m=r.find(d=>d.requestId===p.requestId);if(m.requestType)return Object.assign(p,m)}).filter(Boolean))};if(n&&s?.[n])a(n);else if(s)for(let u of Object.keys(s))a(u);let c=r.filter(u=>!u.requestId);return c.length&&VA({personRequests:s,personId:n,requests:c}),sl({tournamentRecords:e,personRequests:s})}function eM(t){let{tournamentRecords:e,requestType:r,requestId:n,personId:o,date:i}=t,s=lt(t,[{[ye]:!0}]);if(s.error)return s;let{personRequests:a}=yi({tournamentRecords:e}),c=p=>{a&&(a[p]=a[p].filter(m=>(!r||m.requestType!==r)&&(!n||m.requestId!==n)&&(!i||m.date!==i)),a?.[p]?.length||delete a[p])},u=!r&&!n&&!o&&!i;if(!u){if(o&&a?.[o])c(o);else if(a)for(let p of Object.keys(a))c(p)}return u||!a||!Object.keys(a).length?or({name:ma,tournamentRecords:e,discover:!0}):sl({tournamentRecords:e,personRequests:a})}function rM(t){let{tournamentRecords:e,personId:r,requests:n}=t,o=lt(t,[{[ye]:!0,[tR]:!0},{requests:!0,[to]:Er,[En]:G}]);if(o.error)return o;let{personRequests:i}=yi({tournamentRecords:e}),{mergeCount:s}=VA({personRequests:i,personId:r,requests:n});return s&&i?sl({tournamentRecords:e,personRequests:i}):{error:G}}function nM({individualParticipantIds:t,groupingParticipantId:e,tournamentRecord:r}){let n="modifyIndividualParticipantIds";if(!r)return _({result:{error:W},stack:n});if(!e||!t)return _({result:{error:et},stack:n});let o=r.participants||[],i=o.find(l=>l.participantId===e);if(!i)return _({result:{error:Zt},stack:n});if(![kt,Ar].includes(i.participantType))return _({result:{error:nn},context:{participantType:i.participantType},stack:n});let s=t.filter(l=>o.find(g=>g.participantId===l)?.participantType!==ht);if(s.length)return _({result:{error:zr,invalidParticipantIds:s},stack:n});let a=i.individualParticipantIds||[],c=t.filter(l=>!a.includes(l)),u=a.filter(l=>!t.includes(l)),p=Yp({individualParticipantIds:c,groupingParticipantId:e,tournamentRecord:r});if(p.error)return _({result:p,stack:n});let m=Hf({individualParticipantIds:u,groupingParticipantId:e,tournamentRecord:r});if(m.error)return _({result:m,stack:n});let{topics:d}=Cr();if(d.includes(Qe)){let l=o.find(({participantId:f})=>f===e);Tt({topic:Qe,payload:{tournamentId:r.tournamentId,participants:[l]}})}return{...p,...m}}function oM({tournamentRecord:t,participantIds:e,signInState:r}){if(!t)return{error:W};if(!Array.isArray(e))return{error:et};if(![ru,$E].includes(r))return{error:G,signInState:r};let o=t.participants||[];if(!o.length)return{error:$a};let i=o.map(gt),s=e.filter(p=>!i.includes(p));if(s.length)return{error:G,context:{invalidParticipantIds:s}};let a=[],c=new Date().toISOString();for(let p of o){let{participantId:m}=p;if(e.includes(m)){let l=Jf({duplicateValues:!1,tournamentRecord:t,participantId:m,timeItem:{itemType:ic,itemValue:r,createdAt:c}});if(l.error)return l;a.push(p)}}let{topics:u}=Cr();return a.length&&u.includes(Qe)&&Tt({topic:Qe,payload:{tournamentId:t.tournamentId,participants:a}}),{...R}}function iM({tournamentRecord:t,participantId:e,participantOtherName:r}){if(!t)return{error:W};if(!e)return{error:oe};let{participant:n}=xo({tournamentRecord:t,participantId:e});if(!n)return{error:Zt};n.participantOtherName=r;let{topics:o}=Cr();return o.includes(Qe)&&Tt({topic:Qe,payload:{tournamentId:t.tournamentId,participants:[n]}}),{...R}}function sM({personFormat:t,person:e}){let r=g=>g.replace(/\W/g,""),n=g=>/^[a-z]*$/.test(r(g)),o=g=>/^[A-Z]*$/.test(r(g)),i=g=>/^[LAST]{4}/.test(r(g)),s=g=>g.toLowerCase().indexOf("l")<g.toLowerCase().indexOf("f"),a=g=>g.indexOf(",")>=0,c=g=>g.toLowerCase().indexOf("f.")>=0,u=g=>g.toLowerCase().indexOf("f")<0,p=g=>g.indexOf(" ")>0;if(!e)return;let m=p(t)?" ":"",d=xh(e?.standardGivenName??""),l=xh(e?.standardFamilyName??"");if(!t)return`${d}${m}${l}`;c(t)&&!a(t)&&!s(t)&&(d=`${d[0]}.`),n(t)?(d=d.toLowerCase(),l=l.toLowerCase()):o(t)?(d=d.toUpperCase(),l=l.toUpperCase()):i(t)&&(l=l.toUpperCase());let f=`${d}${m}${l}`;return u(t)?f=l:s(t)&&(a(t)?f=`${l},${m}${d}`:f=`${l}${m}${d}`),f}function hx({participantMap:t,participant:e,formats:r}){let{participantType:n,individualParticipantIds:o,person:i}=e,s=n&&r[n];if(n!==Jr&&s){let{personFormat:a,doublesJoiner:c}=s;n===ht&&(e.participantName=sM({person:i,personFormat:a})),n===dt&&(e.participantName=o?.map(u=>{let p=t[u]?.person;return sM({person:p,personFormat:a})}).filter(Boolean).join(c??"/"))}}function aM({tournamentRecord:t,formats:e}){if(!t)return{error:W};if(!Rt(e))return{error:et};let r=t.participants??[],n=sI(r,"participantId");for(let o of r)hx({participant:o,participantMap:n,formats:e});return{...R}}function cM(t){let{tournamentRecord:e,policyDefinitions:r,contextProfile:n,participantId:o,personId:i}=t,s=t.tournamentRecords||e&&{[e.tournamentId]:e}||{};if(typeof o!="string"&&typeof i!="string")return{error:et,stack:"publicFindParticipant"};let a,c;for(let u of Object.values(s)){c=u.tournamentId;let p=u.participants||[];if(a=bo({tournamentParticipants:p,internalUse:!0,policyDefinitions:r,contextProfile:n,participantId:o,personId:i}),a)break}return{participant:a,tournamentId:c,...R}}function uM({individualParticipantIds:t=[],participantRoleResponsibilities:e,participantRole:r=SU,tournamentRecord:n,participantId:o,groupName:i}){if(!n)return{error:W};if(!i)return{error:et,info:"Missing groupName"};if(!Array.isArray(t))return{info:"Invalid individualParticipantIds",error:G};let a=(Yt({participantFilters:{participantTypes:[ht]},tournamentRecord:n}).participants??[]).map(m=>m.participantId);for(let m of t)if(!a.includes(m))return{error:nn,participantId:m};let c=rt({participantId:o||Mt(),participantRoleResponsibilities:e,participantName:i,individualParticipantIds:t,participantType:Ar,participantRole:r}),u=gn({participant:c,tournamentRecord:n});if(u.error)return u;let{topics:p}=Cr();return p.includes(jo)&&Tt({topic:jo,payload:{tournamentId:n.tournamentId,participants:[c]}}),{...R,participant:J(c)}}function pM({tournamentRecord:t,participantName:e,participantId:r}){if(!t)return{error:W};if(!r)return{error:oe};if(!e)return{error:et,info:"Missing participantName"};let{participant:n}=xo({tournamentRecord:t,participantId:r});if(!n)return{error:Zt};n.participantName=e;let{topics:o}=Cr();return o.includes(Qe)&&Tt({topic:Qe,payload:{tournamentId:t.tournamentId,participants:[n]}}),{...R}}function mM({clearExistingAssignments:t=!0,individualParticipantIds:e,reverseAssignmentOrder:r,initialTeamIndex:n=0,scaledParticipants:o=[],teamParticipantIds:i,tournamentRecord:s,scaleAttributes:a,teamNameBase:c,teamsCount:u,eventId:p,event:m}){if(!s)return{error:W};if(!Array.isArray(i)&&!ft(u)&&!p||!ft(n)||o&&!Array.isArray(o)||a&&(typeof a!="object"||!Object.keys(a).length))return{error:G};if(!a&&!o.length||!o&&!(e&&a))return{error:et,info:"Missing scaling details"};if(p&&!i){if(m?.eventType!==kr)return{error:No};i=m?.entries?.filter(({entryStatus:h})=>h===Zr).map(gt)}if(!i?.length&&!u)return{info:"Missing teamParticipantIds or teamsCount",error:et};let d=e??o.map(({participantId:h})=>h);r&&(i?.reverse(),n+=1),n>(i?.length||0)-1&&(n=0);let l=i?.slice(n).concat(...i.slice(0,n))??[],f=[];for(let h of s.participants??[]){let{participantId:S,participantType:T}=h;if(l.includes(S)){if(T!==Jr)return{error:nn,participant:h};f.push(h)}}if(u&&f.length<u){let h=u-(f?.length||0),S=c??"Team",T=Z(0,h).map(E=>({participantName:`${S} ${E+1}`,participantType:Jr,participantRole:Ge})),{participants:A=[]}=In({participants:T,returnParticipants:!0,tournamentRecord:s}),D=A.map(gt),y=s.participants?.filter(({participantId:E})=>D.includes(E))??[];f.push(...y)}if(!f.length)return{error:xl};if(t)for(let h of f)h.individualParticipantIds=[];else{let h=f.map(S=>S).flat();e?.length?d=d.filter(S=>!h.includes(S)):o=o?.filter(({participantId:S})=>!h.includes(S))}if(!e?.length&&!o?.length)return{error:Yu,info:"Nothing to be done"};if(!o.length){for(let h of s.participants??[]){let{participantId:S,participantType:T}=h;if(!d.includes(S))continue;if(T!==ht)return{error:nn,participant:h};let A=uo({scaleAttributes:a,participant:h})?.scaleItem,D=a?.accessor?A?.scaleValue?.[a?.accessor]:A?.scaleValue,y={participantId:S,scaleValue:D};o.push(y)}if(!o.length)return{error:Zt}}o.sort((h,S)=>a?.sortOrder?(S?.scaleValue||0)-(h?.scaleValue||0):(h?.scaleValue||1/0)-(S?.scaleValue||1/0));for(let h of o)if(!h.participantId)return{error:G,scaledParticipant:h};let g=0;for(;g<o.length;){for(let h of f){if(g+1>o.length)break;let S=o[g];h.individualParticipantIds.push(S.participantId),g++}f.reverse()}let I=f.map(gt);for(let h of s.events??[]){if(h.eventType!==kr)continue;let S=(h.entries??[]).filter(T=>I.includes(T.participantId));for(let T of S){let A=T.participantId,y=f.find(U=>U.participantId===A)?.individualParticipantIds;h.entries=(h.entries??[]).filter(U=>!y.includes(U.participantId)),(h.drawDefinitions??[]).forEach(U=>{U.entries=(U.entries??[]).filter(M=>!y.includes(M.participantId))});let{flightProfile:E}=Ht({event:h});(E?.flights||[]).forEach(U=>{U.drawEntries=(U.drawEntries||[]).filter(M=>!y.includes(M.participantId))})}}return{...R,scaledParticipants:o}}function dM(t){let{tournamentRecords:e}=t;if(typeof e!="object"||!Object.keys(e).length)return{error:Ft};for(let r of Object.values(e)){let n=$V({...t,tournamentRecord:r});if(n.error&&n.error!==Fc)return n}return{...R}}function $V({tournamentRecord:t,penaltyId:e}){if(!t)return{error:W};if(!e)return{error:Rl};let r=t?.participants??[],n=[],o=!1,i;return r.forEach(s=>{let a=!1;s.penalties=(s.penalties??[]).filter(c=>(c.penaltyId===e&&(a=!0,o||(i=c,o=!0)),a&&n.push(s),c.penaltyId!==e))}),i&&Tt({topic:Qe,payload:{tournamentId:t.tournamentId,participants:n}}),i?{...R,penalty:i}:{error:Fc}}var KV=({penaltyId:t=Mt()}={})=>({refereeParticipantId:void 0,penaltyCode:void 0,penaltyType:void 0,extensions:void 0,matchUpId:void 0,createdAt:void 0,issuedAt:void 0,notes:void 0,penaltyId:t}),BA=KV;function lM(t){let{tournamentRecords:e}=t;if(typeof e!="object"||!Object.keys(e).length)return{error:Ft};for(let r of Object.values(e)){let n=zV({...t,tournamentRecord:r});if(n.error&&n.error!==Fc||n.success)return n}return{error:Fc}}function zV({tournamentRecord:t,modifications:e,penaltyId:r}){if(!t)return{error:W};if(!e)return{error:G,modifications:e};if(!r)return{error:Rl};let n=t?.participants??[],o=Object.keys(BA()).filter(c=>c!=="penaltyId"),i=Object.keys(e).filter(c=>o.includes(c));if(!i.length)return{error:qu};let s,a=[];return n.forEach(c=>{let u=!1;c.penalties=(c.penalties??[]).map(p=>(p.penaltyId===r&&(u=!0,i.forEach(m=>Object.assign(p,{[m]:e[m]})),s||(s=p)),p)),u&&a.push(c)}),s&&Tt({topic:Qe,payload:{tournamentId:t.tournamentId,participants:a}}),s?{...R,penalty:s}:{error:Fc}}function fM(t,e,r){return!t&&e?e:t&&!e||typeof t!="object"||typeof e!="object"?t:pt(Object.keys(t).concat(Object.keys(e))).reduce((o,i)=>{if(!e[i])o[i]=t[i];else if(!t[i])o[i]=e[i];else if(typeof t[i]!=typeof e[i])o[i]=e[i];else if(Array.isArray(t[i]))if(r===!0||Array.isArray(r)&&r.includes(i)){let s=pt(t[i].map(a=>JSON.stringify(a)).concat(e[i].map(a=>JSON.stringify(a)))).map(a=>JSON.parse(a));o[i]=s}else o[i]=e[i];else typeof t[i]=="object"?o[i]=fM(t[i],e[i],r):o[i]=e[i];return o},{})}function gM({participants:t=[],tournamentRecord:e,arraysToMerge:r}){if(!e)return{error:W};e.participants||(e.participants=[]);let n=t.filter(Pr(Bn)).map(u=>({[u.participantId]:u})),o=Object.assign({},...n),i=[];e.participants=e.participants.map(u=>{if(o[u.participantId]){let p=fM(u,o[u.participantId],r);return i.push(p),p}return u});let s=e.participants.map(Pr(Bn))||[],a=t.filter(({participantId:u})=>!s.includes(u)),{topics:c}=Cr();return a.length&&(e.participants=e.participants.concat(...a),c.includes(jo)&&Tt({topic:jo,payload:{participants:a}})),i.length&&c.includes(Qe)&&Tt({topic:Qe,payload:{tournamentId:e.tournamentId,participants:i}}),{modifiedParticipantsCount:i.length,newParticipantsCount:a.length,...R}}function IM(t){let{tournamentRecord:e,participantIds:r}=t,n=t.tournamentRecords??(e&&{[e.tournamentId]:e})??{},o;for(let i of Object.values(n)){let a=(Yt({tournamentRecord:i}).participants??[])?.map(gt).filter(c=>r.includes(c));a.length&&(o=QV({...t,penaltyId:t.penaltyId??o,tournamentRecord:i,participantIds:a}).penaltyId)}return o?{...R,penaltyId:o}:{error:Zt}}function QV({refereeParticipantId:t,tournamentRecord:e,participantIds:r,penaltyCode:n,penaltyType:o,extensions:i,penaltyId:s,matchUpId:a,issuedAt:c,notes:u}){if(!e)return{error:W};if(!r)return{error:oe};if(!o)return{error:ky};let m=(e?.participants??[]).filter(f=>r.includes(f.participantId));if(!m.length)return{error:Zt};let d=new Date().toISOString(),l=Object.assign(BA({penaltyId:s}),{refereeParticipantId:t,penaltyCode:n,penaltyType:o,matchUpId:a,createdAt:d,issuedAt:c,notes:u});return Array.isArray(i)&&i.forEach(f=>St({element:l,extension:f})),m.forEach(f=>{f.penalties||(f.penalties=[]),f.penalties.push(l)}),Tt({topic:Qe,payload:{tournamentId:e.tournamentId,participants:m}}),{...R,penaltyId:l.penaltyId}}function hM({participantRole:t=Ge,tournamentRecord:e,persons:r}){if(!e)return{error:W};if(!Array.isArray(r))return{error:G};if(!Object.keys(Xm).includes(t))return{error:Ry};let n=(e.participants||[]).map(({person:f})=>f?.personId).filter(Boolean),o=[],i=r.filter(f=>f&&(!f.personId||!n.includes(f.personId))).map(f=>(f.personId||(f.personId=Mt()),o.push(f.personId),f)),s=(f,g)=>Object.assign({},...Object.keys(f).filter(I=>!g.includes(I)).map(I=>({[I]:f[I]}))),a=i.map(f=>rt({extensions:f.participantExtensions,timeItems:f.participantTimeItems,participantType:ht,participantRole:t,person:s(f,["participantExtensions","participantTimeItems","pairedPersons"])})),c=0,u=0,p=In({participants:a,tournamentRecord:e});if(p.error)return p;u=p.addedCount||0;let m=[],d=Yt({participantFilters:{participantTypes:[ht]},tournamentRecord:e})?.participants??[];if(t===Ge&&r.filter(({pairedPersons:f})=>f).forEach(({personId:f,pairedPersons:g})=>{Array.isArray(g)&&g.forEach(I=>{let h=[f,I.personId].map(S=>bo({tournamentParticipants:d,personId:S})).filter(Boolean);if(h.length===2){let S=h.map(gt);m.push(rt({extensions:I.participantExtensions,timeItems:I.timeItems,participantRole:Ge,individualParticipantIds:S,participantType:dt}))}})}),m.length){if(p=In({participants:m,tournamentRecord:e}),p.error)return p;c=p.addedCount||0}let l=u+c;return{...R,addedCount:l,newPersonIds:o}}var NM={};Jt(NM,{bulkUpdatePublishedEventIds:()=>MT,getAllEventData:()=>CT,getCourtInfo:()=>Hm,getDrawData:()=>Fd,getEventData:()=>Gd,getEventPublishStatus:()=>vr,getPublishState:()=>as,getVenueData:()=>mc,mutate:()=>DM,publishEvent:()=>Js,publishEventSeeding:()=>AM,publishOrderOfPlay:()=>UM,query:()=>kD,setEventDisplay:()=>$d,unPublishEvent:()=>PM,unPublishEventSeeding:()=>yM,unPublishOrderOfPlay:()=>EM});var DM={};Jt(DM,{publishEvent:()=>Js,publishEventSeeding:()=>AM,publishOrderOfPlay:()=>UM,setEventDisplay:()=>$d,unPublishEvent:()=>PM,unPublishEventSeeding:()=>yM,unPublishOrderOfPlay:()=>EM});function AM({removePriorValues:t=!0,stageSeedingScaleNames:e,seedingScaleNames:r,tournamentRecord:n,status:o=Gr,drawIds:i=[],event:s}){if(!n)return{error:W};if(!s)return{error:Et};let a=vr({event:s,status:o}),c=(a?.seeding?.seedingScaleNames||r)&&{...a?.seeding?.seedingScaleNames,...r},u=(a?.seeding?.stageSeedingScaleNames||e)&&{...a?.seeding?.stageSeedingScaleNames,...e},p=rt({stageSeedingScaleNames:u,seedingScaleNames:c,published:!0,drawIds:i});return Xs({statusObject:{seeding:p},removePriorValues:t,status:o,event:s}),Tt({topic:WE,payload:{tournamentId:n.tournamentId,eventId:s.eventId,drawIds:i}}),{...R}}function yM({removePriorValues:t=!0,seedingScaleNames:e,tournamentRecord:r,status:n=Gr,drawIds:o,stages:i,event:s}){if(!r)return{error:W};if(!s)return{error:Et};let a=vr({event:s});if(a){let c=a.seeding;if(Array.isArray(i)&&c.stageSeedingScaleNames)for(let u of i)c.stageSeedingScaleNames[u]&&delete c.stageSeedingScaleNames[u];Array.isArray(e)&&c?.seedingScaleNames&&(c.seedingScaleNames=c.seedingScaleNames.filter(u=>!e.includes(u))),Array.isArray(o)&&c?.drawIds&&(c.drawIds=c.drawIds.filter(u=>!o.includes(u))),(!Object.values(c.stageSeedingScaleNames??{}).length&&!c.seedingScaleNames?.length&&!c.drawIds?.length||!i&&!e&&!o?.length)&&(delete c.stageSeedingScaleNames,delete c.seedingScaleNames,delete c.drawIds,c.published=!1),Xs({statusObject:{seeding:c},removePriorValues:t,status:n,event:s})}return Tt({topic:Tf,payload:{tournamentId:r.tournamentId,eventId:s.eventId}}),{...R}}function EM(t){let e=t?.tournamentRecords??(t?.tournamentRecord&&{[t.tournamentRecord.tournamentId]:t.tournamentRecord})??{};if(!Object.keys(e).length)return{error:Ft};for(let r of Object.values(e)){let n=XV({tournamentRecord:r,...t});if(n.error)return n}return{...R}}function XV({removePriorValues:t=!0,tournamentRecord:e,status:r=Gr}){if(!e)return{error:W};let n=`${Ko}.${zo}`,{timeItem:o}=Gn({element:e,itemType:n}),i=o?.itemValue||{[r]:{}};return i[r]&&delete i[r].orderOfPlay,Ti({timeItem:{itemValue:i,itemType:n},element:e,removePriorValues:t}),Tt({topic:Af,payload:{tournamentId:e.tournamentId}}),{...R}}function UM(t){let e=Xr(t);if(!Object.keys(e).length)return{error:Ft};for(let r of Object.values(e)){let n=JV({tournamentRecord:r,...t});if(n.error)return n}return{...R}}function JV({scheduledDates:t=[],removePriorValues:e,tournamentRecord:r,status:n=Gr,eventIds:o=[]}){if(!r)return{error:W};let i=`${Ko}.${zo}`,{timeItem:s}=Gn({element:r,itemType:i}),a=s?.itemValue||{[n]:{}};return a[n].orderOfPlay={published:!0,scheduledDates:t,eventIds:o},Ti({timeItem:{itemValue:a,itemType:i},element:r,removePriorValues:e}),Tt({topic:jE,payload:{tournamentId:r.tournamentId,scheduledDates:t,eventIds:o}}),{...R}}function PM({removePriorValues:t=!0,tournamentRecord:e,status:r=Gr,event:n}){if(!e)return{error:W};if(!n)return{error:Et};let o=`${Ko}.${zo}`,{timeItem:i}=pu({itemType:o,event:n}),s=i?.itemValue||{[r]:{}};return delete s[r].structureIds,delete s[r].drawDetails,delete s[r].drawIds,ki({event:n,timeItem:{itemValue:s,itemType:o},removePriorValues:t}),Xs({statusObject:{structureIds:void 0,drawIds:void 0,seeding:void 0},removePriorValues:t,status:r,event:n}),Tt({topic:Sf,payload:{tournamentId:e.tournamentId,eventId:n.eventId}}),{eventId:n.eventId,...R}}var MM={};Jt(MM,{getEntryStatusReports:()=>Tx,getParticipantStats:()=>Sx,getStructureReports:()=>yx,getVenuesReport:()=>Ex});function Sx({withCompetitiveProfiles:t,opponentParticipantId:e,withIndividualStats:r,teamParticipantId:n,tournamentRecord:o,withScaleValues:i,tallyPolicy:s,matchUps:a}){if(!o)return{error:W};if(a&&!Array.isArray(a))return{error:Je};if(a=a??le({tournamentRecord:o,participantsProfile:i?{withScaleValues:i}:void 0}).matchUps,!a?.length)return{error:Sn};let u=[];e&&u.push(e),n&&u.push(n);let p=u.length?{participantIds:u}:{participantTypes:[Jr]},m=Yt({participantFilters:p,tournamentRecord:o}).participants??[];if(!m.every(({participantType:U})=>U===Jr))return{error:zr};u.length||u.push(...m.map(gt));let d=new Map,l=new Map,f=new Map,g=new Map,I=(U,M="")=>l.get(U)||l.set(U,{participantName:M,participantId:U,competitorIds:[],competitiveness:{},matchUpStatuses:{},tiebreaks:[0,0],matchUps:[0,0],points:[0,0],games:[0,0],sets:[0,0]})&&l.get(U);for(let U of m){let{participantId:M,individualParticipantIds:P}=U;g.set(M,P??[]),I(M,U.participantName)}if(n&&!g.get(n))return _({result:{error:Zt},context:{teamParticipantId:n}});if(e&&!g.get(e))return _({result:{error:Zt},context:{opponentParticipantId:e}});let h=[],S=U=>{let M=[[],[]];for(let N of U){let C=N.participant;if(C?.participantName){d.set(C.participantId,{participantName:C.participantName,ratings:C.ratings});let O=l.get(C.participantId);O&&(O.participantName=C.participantName)}}let P=({side:N,individualParticipantIds:C})=>N.participantId&&(!C?.length||C.includes(N.participantId))&&[N.participantId]||N.participant?.individualParticipantIds?.length&&(!C?.length||jt(C,N.participant?.individualParticipantIds).length===N.participant?.individualParticipantIds?.length)&&N.participant.individualParticipantIds;if(g.size){let N=(C,O)=>{for(let b of U){if(!b.participant)continue;let x=P({individualParticipantIds:O,side:b});if(x?.length){let w=b.sideNumber;if(!w)continue;let F=[C];r&&F.push(...x),M[w-1]=F;let L=l.get(C);for(let v of x.filter(Boolean))L&&!L.competitorIds.includes(v)&&L.competitorIds.push(v)}}};if(n)(!e||U.every(O=>O.participant&&(P({individualParticipantIds:g.get(n),side:O})||P({individualParticipantIds:g.get(e),side:O}))))&&N(n,g.get(n));else for(let[C,O]of g)N(C,O)}else if(r)for(let N of U){if(!N.participant)continue;let C=P({individualParticipantIds:[],side:N}),O=N.sideNumber;O&&(M[O-1]=C)}return M};for(let U of a){if(!Rt(U))return{error:Je};let{matchUpStatus:M,matchUpFormat:P,matchUpType:N,winningSide:C,score:O,sides:b}=U;if(!b||!O||N===ln||M===Dt)continue;let x=S(b);if(!x.filter(Boolean).length)continue;let w=t&&C&&su({matchUp:U})?.competitiveness;h.push(U);let F=eg({matchUpStatus:M,matchUpFormat:P,tallyPolicy:s,winningSide:C,score:O}),L=rS({matchUpStatus:M,matchUpFormat:P,tallyPolicy:s,winningSide:C,score:O}),{pointsTally:v,tiebreaksTally:B}=nS({matchUpFormat:P,score:O});x.forEach((H,j)=>{for(let V of H){let Y=d.get(V)?.participantName,$=I(V,Y);if($){let k=(Q,it)=>it.forEach((ot,ut)=>$[Q][ut]+=ot),K=j?[...B].reverse():B,z=j?[...v].reverse():v,q=j?[...L].reverse():L,nt=j?[...F].reverse():F;if(k("tiebreaks",K),k("points",z),k("games",q),k("sets",nt),C){let Q=C-1===j?0:1;$.matchUps[Q]+=1}if(w){let Q=w.toLowerCase();$.competitiveness[Q]||($.competitiveness[Q]=[0,0]),$.competitiveness[Q][j]+=1}if(M){let Q=M.toLowerCase();$.matchUpStatuses[Q]||($.matchUpStatuses[Q]=0),$.matchUpStatuses[Q]+=1}}}})}let T=["tiebreaks","matchUps","points","games","sets"],A=["competitive","routine","decisive"],D=new Map,y=(U,M)=>(U??0)+(M??0);for(let[U,M]of l.entries()){for(let P of T){let N=M[P].reduce(y);if(N){let C=M[P][0]/N,O=`${P}Ratio`,b=parseFloat(C.toFixed(2));M[O]=b,f.set(U,!0),D.has(O)||D.set(O,[]),D.get(O)?.push(b)}}for(let P of A){let N=M.competitiveness?.[P]?.reduce(y);if(N){let C=M.competitiveness[P][0]/N,O=`${P}Ratio`,b=parseFloat(C.toFixed(2));M[O]=b}}}if(!n){let U=(M,P)=>P-M;for(let M of l.values())for(let P of T){let N=`${P}Ratio`;if(typeof M[N]=="number"){let C=D.get(N)?.sort(U).indexOf(M[N]);if(typeof C=="number"&&C>=0){let O=`${P}Rank`;M[O]=C+1}}}}let E={relevantMatchUps:h,...R};return n?(E.teamStats=l.get(n),e&&(E.opponentStats=l.get(e))):E.participatingTeamsCount=f.size,E.allParticipantStats=[...l.values()],E}function Zp({participant:t,eventType:e}){let r=t?.person?.personId,n=t?.person?.personOtherIds?.[0],o=t?.person?.tennisId,i=t?.ratings?.[e]?.find(({scaleName:u})=>u===gg),s=i?.scaleValue,{wtnRating:a,confidence:c}=s||{};return{timeStamp:i?.scaleDate,personOtherId:n,confidence:c,wtnRating:a,personId:r,tennisId:o}}function Tx({tournamentRecord:t}){if(!t)return{error:W};let e=t.tournamentId,{participantMap:r}=Yt({withScaleValues:!0,withEvents:!0,withSeeding:!0,tournamentRecord:t,withDraws:!0}),o=(le({matchUpFilters:{matchUpTypes:[Ia,vi]},tournamentRecord:t}).matchUps??[]).flatMap(({sides:f,matchUpType:g})=>f?.flatMap(I=>g===vi?I?.participant?.individualParticipantIds:I?.participant?.participantId||I.participantId).filter(Boolean)).filter(Boolean),i=[],s={},a={},c={},u=0,p=({id:f,entry:g,eventId:I,eventType:h})=>{let{qualifyingSeeding:S,mainSeeding:T,entryStatus:A,entryStage:D,drawId:y}=g;s[f]||(s[f]=[]);let{participant:E,events:U}=r?.[f]??{},M=Zp({participant:E,eventType:h}),P=U?.[I]?.ranking;A===pg&&i.push(f),s[f].push({participantType:E?.participantType,participantId:f,tournamentId:e,eventType:h,eventId:I,drawId:y,entryStatus:A,entryStage:D,...M,ranking:P,mainSeeding:T,qualifyingSeeding:S})};for(let f of t.events??[]){let g={},I=M=>{g[M]||(g[M]={count:0}),g[M].count+=1},{drawDefinitions:h=[],eventType:S,eventId:T}=f,A=h.flatMap(M=>{let{drawId:P,entries:N}=M;u+=1;let C=({stage:F,stageSequence:L})=>F===tt&&L===1||F===at,b=(M.structures??[]).filter(C).flatMap(({positionAssignments:F})=>F).filter(Boolean).map(({participantId:F})=>F),x=({participantId:F})=>b.includes(F),w=F=>{let{participantId:L,entryStatus:v,entryStage:B}=F;I(v);let H=r?.[L]?.draws?.[P]?.seedAssignments?.[tt];return{qualifyingSeeding:r?.[L]?.draws?.[P]?.seedAssignments?.[at],participantId:L,mainSeeding:H,entryStatus:v,entryStage:B,drawId:P}};return N?.filter(x).map(w)}),D=M=>{let P=M.participantId,N=r?.[P].participant.individualParticipantIds?.filter(C=>o.includes(C));return P&&{[P]:{individualParticipantIds:N}}};S===gi?(()=>{let M=Object.assign({},...A.map(D).filter(Boolean)),P=N=>{M[N.participantId].individualParticipantIds.forEach(C=>{p({id:C,eventType:S,eventId:T,entry:N})})};A.forEach(P)})():A.forEach(M=>{p({id:M?.participantId,eventType:S,eventId:T,entry:M})});let E=Object.values(g).reduce((M,P)=>M+P.count,0);Object.keys(g).forEach(M=>{g[M].pct=g[M].count/E*100}),c[T]={tournamentId:e,eventId:T,entries:A,entryStatuses:g};let U=Object.assign({},...Or.flatMap(M=>[{[M+"_count"]:g[M]?.count},{[M+"_pct"]:g[M]?.pct}]));a[T]={tournamentId:e,eventId:T,...U}}let m=Object.values(r??{}).filter(({participant:{participantType:f,participantRole:g}})=>f===ht&&g===Ge),d=m.filter(({participant:f})=>!o.includes(f.participantId)).map(({participant:f})=>f.participantId),l={nonParticipatingEntriesCount:d.length,individualParticipantsCount:m.length,eventsCount:Object.values(c).length,nonParticipatingParticipantIds:d,drawDefinitionsCount:u,tournamentId:e};return{entryStatusReports:Object.values(a).flat(),participantEntryReports:Object.values(s).flat(),eventReports:Object.values(c).flat(),withDrawnParticipantIds:i,tournamentEntryReport:l}}function Ax({eventType:t,matchUps:e,eventId:r,drawId:n}){let o={},i=g=>{let I=g?.matchUpFormat;I&&(o[I]||(o[I]=0),o[I]+=1)},s=e.filter(g=>r?g.eventId===r:g.drawId===n).reduce((g,I)=>(i(I),(I.sides??[]).flatMap(h=>(h?.participant?.individualParticipants||[h?.participant]).filter(Boolean)).forEach(h=>g[h.participantId]=h),g),{}),a=Object.values(s),c=a.map(g=>Zp({participant:g,eventType:t})).filter(({wtnRating:g})=>g),u=(a.length-c.length)/a.length*100,p=c.reduce((g,I)=>{let{wtnRating:h,confidence:S}=I;return g.totalWTN+=h,g.totalConfidence+=S,g},{totalWTN:0,totalConfidence:0}),m=c?.length?p.totalWTN/c.length:0,d=c?.length?p.totalConfidence/c.length:0,f=Object.values(o).reduce((g,I)=>g+(I||0),0);return{matchUpFormatCounts:o,matchUpsCount:f,avgConfidence:d,pctNoRating:u,avgWTN:m}}function yx({firstFlightOnly:t=!0,extensionProfiles:e,tournamentRecord:r}){if(!r)return{error:ra};let n={},o=Object.assign({},...(e??[]).map(({name:p,label:m,accessor:d})=>{let l=mt({element:r,name:p})?.extension?.value,f=d?Zi({element:l,accessor:d})?.value:l;return{[m||p]:f}})),i=r?.tournamentId,a=le({participantsProfile:{withScaleValues:!0},tournamentRecord:r}).matchUps??[],c=p=>Gn({itemType:uf,itemSubTypes:[eo],element:{timeItems:p}})?.timeItem?.itemValue?.scaleBasis,u=r?.events?.flatMap(({timeItems:p,drawDefinitions:m=[],extensions:d,eventType:l,eventId:f,category:g})=>{let h=d?.find(E=>E.name===qr)?.value?.flights?.map(E=>({[E.drawId]:E.flightNumber})),S=h&&Object.assign({},...h),T=d?.find(E=>E.name===Em)?.value?.length||0,A=Object.values(S),D=S&&Math.min(...A),y=c(p);return n[f]={totalPositionManipulations:0,maxPositionManipulations:0,generatedDrawsCount:0,drawDeletionsCount:T,seedingBasis:y?JSON.stringify(y):void 0,tournamentId:i,eventId:f},m.filter(E=>!t||!h||S[E.drawId]===D).flatMap(E=>{let{matchUpFormat:U,tieFormat:M,timeItems:P,extensions:N,structures:C,drawType:O,drawId:b}=E,{matchUpFormatCounts:x,matchUpsCount:w,avgConfidence:F,pctNoRating:L,avgWTN:v}=Ax({eventType:l,matchUps:a,drawId:b}),B=c(P)||y,H=ZV({extensions:N}),j=H?.length||0;return n[f].totalPositionManipulations+=j,n[f].generatedDrawsCount+=1,j>n[f].maxPositionManipulations&&(n[f].maxPositionManipulations=j),C?.filter(V=>V.stageSequence===1&&[at,tt,Ve,ce].includes(V.stage)).map(V=>{let Y=[tt,ce].includes(V.stage)?a.find(be=>be.structureId===V.structureId&&be.finishingRound===1&&be.winningSide):void 0,k=Y?.sides?.find(be=>be.sideNumber===Y.winningSide)?.participant,K=k?.participantType===Jr&&k.participantId,z=k?.participantType===dt?k.individualParticipants:[],q=Zp({participant:z?.[0]||k,eventType:l}),{personId:nt,personOtherId:Q,tennisId:it,confidence:ot,wtnRating:ut}=q||{},Qt=Zp({participant:z?.[1],eventType:l}),{personId:yt,personOtherId:Me,tennisId:Ee,confidence:Ce,wtnRating:Kt}=Qt||{},{ageCategoryCode:Re,categoryName:wt,subType:Ue}=g??{},Ct=V.matchUpFormat||U,ne=(x[Ct]||0)/w*100,{tieFormatName:qt,tieFormatDesc:pe}=Ld(M),{tieFormatName:he,tieFormatDesc:ur}=Ld(V.tieFormat),_e=pe===ur,Wt=!_e&&he,ve=V.tieFormat&&!_e&&ur,nr=H?.filter(be=>be.structureId===V.structureId)?.length||0;return{...o,tournamentId:i,eventId:f,structureId:V.structureId,drawId:b,eventType:l,category:Ue,categoryName:wt,ageCategoryCode:Re,flightNumber:S[b],drawType:O,stage:V.stage,seedingBasis:B?JSON.stringify(B):void 0,winningPersonId:nt,winningPersonOtherId:Q,winningPersonTennisId:it,winningPersonWTNrating:ut,winningPersonWTNconfidence:ot,winningPerson2Id:yt,winningPerson2OtherId:Me,winningPerson2TennisId:Ee,winningPerson2WTNrating:Kt,winningPerson2WTNconfidence:Ce,winningTeamId:K,positionManipulations:nr,pctNoRating:L,matchUpFormat:Ct,pctInitialMatchUpFormat:ne,matchUpsCount:w,drawTieFormatName:qt,drawTieFormatDesc:pe,tieFormatName:Wt,tieFormatDesc:ve,avgConfidence:F,avgWTN:v}})})});return{eventStructureReports:Object.values(n),structureReports:u}}function ZV({extensions:t}){return t?.find(({name:e})=>e===Tm)?.value?.slice(1)}function Ex({ignoreDisabled:t=!0,tournamentRecords:e,tournamentId:r,venueIds:n=[],dates:o=[]}){if(!Array.isArray(o))return{error:G,dates:o};if(!Array.isArray(n))return{error:G,venueIds:n};if(!(e&&Object.keys(e).filter(l=>!r||l===r)||[]).length)return{error:Ft};if(!o.every(Rr))return{error:ar};let a=po({tournamentRecords:e,ignoreDisabled:t,dates:o});if(a.error)return a;let c=a?.venues?.filter(({venueId:l})=>!n?.length||n.includes(l)),u=a.courts?.reduce((l,f)=>(f.dateAvailability?.forEach(g=>{let I=g.date;l.includes(I)||l.push(I)}),l),[]).filter(l=>!o.length||o.includes(l)),p={venueIds:c?.map(({venueId:l})=>l)},{matchUps:m}=cn({afterRecoveryTimes:!0,tournamentRecords:e,matchUpFilters:p});return{venuesReport:c?.map(l=>t1(u,l,m))}}function t1(t,e,r){let{venueId:n,courts:o,venueName:i}=e,s={};return t.forEach(a=>{let c=0,u=0,p=0;for(let l of o){let f=l.dateAvailability.find(h=>h.date===a),I=(f&&hs({courtDate:f}).timeSlots)?.reduce((h,S)=>{let{startTime:T,endTime:A}=S,D=Vt(A)-Vt(T);return h+D},0);I&&(p+=1),c+=I}let m=r.filter(({schedule:l})=>l.venueId===n&&_n(a,l.scheduledDate));m.forEach(({schedule:l})=>{let f=$t(l.scheduledTime),g=br(f,l.averageMinutes),I=Vt(g)-Vt(f);u+=I});let d=c?(u/c*100).toFixed(2):"100";s[a]={scheduledMatchUpsCount:m.length,availableCourts:p,availableMinutes:c,scheduledMinutes:u,percentUtilization:d}}),{venueId:n,venueName:i,venueReport:s}}var kM={};Jt(kM,{addMatchUpCourtOrder:()=>mA,addMatchUpEndTime:()=>lA,addMatchUpOfficial:()=>_N,addMatchUpResumeTime:()=>gA,addMatchUpScheduleItems:()=>Kp,addMatchUpScheduledDate:()=>Zd,addMatchUpScheduledTime:()=>Vo,addMatchUpStartTime:()=>dA,addMatchUpStopTime:()=>fA,addSchedulingProfileRound:()=>Yg,allocateTeamMatchUpCourts:()=>$p,assignMatchUpCourt:()=>Hi,assignMatchUpVenue:()=>Zs,bulkRescheduleMatchUps:()=>xM,bulkScheduleMatchUps:()=>_c,bulkScheduleTournamentMatchUps:()=>wu,bulkUpdateCourtAssignments:()=>bM,calculateScheduleTimes:()=>Kg,clearMatchUpSchedule:()=>LM,clearScheduledMatchUps:()=>Qp,courtGridRows:()=>Dg,findMatchUpFormatTiming:()=>Fp,findVenue:()=>Qo,generateBookings:()=>zp,generateVirtualCourts:()=>jp,getPersonRequests:()=>yi,getProfileRounds:()=>kd,getScheduledRoundsDetails:()=>bu,getSchedulingProfile:()=>ko,getSchedulingProfileIssues:()=>bT,matchUpScheduleChange:()=>wM,modifyMatchUpFormatTiming:()=>Ng,mutate:()=>GM,proAutoSchedule:()=>RM,proConflicts:()=>_M,publicFindCourt:()=>oU,query:()=>WD,removeEventMatchUpFormatTiming:()=>qd,removeMatchUpCourtAssignment:()=>CM,reorderUpcomingMatchUps:()=>vM,scheduleMatchUps:()=>OM,scheduleProfileRounds:()=>Xp,setMatchUpDailyLimits:()=>FM,setSchedulingProfile:()=>Dc,toggleParticipantCheckInState:()=>zd,validateSchedulingProfile:()=>Gp});var GM={};Jt(GM,{addMatchUpCourtOrder:()=>mA,addMatchUpEndTime:()=>lA,addMatchUpOfficial:()=>_N,addMatchUpResumeTime:()=>gA,addMatchUpScheduleItems:()=>Kp,addMatchUpScheduledDate:()=>Zd,addMatchUpScheduledTime:()=>Vo,addMatchUpStartTime:()=>dA,addMatchUpStopTime:()=>fA,addSchedulingProfileRound:()=>Yg,allocateTeamMatchUpCourts:()=>$p,assignMatchUpCourt:()=>Hi,assignMatchUpVenue:()=>Zs,bulkRescheduleMatchUps:()=>xM,bulkScheduleMatchUps:()=>_c,bulkScheduleTournamentMatchUps:()=>wu,bulkUpdateCourtAssignments:()=>bM,calculateScheduleTimes:()=>Kg,clearMatchUpSchedule:()=>LM,clearScheduledMatchUps:()=>Qp,courtGridRows:()=>Dg,findMatchUpFormatTiming:()=>Fp,findVenue:()=>Qo,generateBookings:()=>zp,generateVirtualCourts:()=>jp,matchUpScheduleChange:()=>wM,modifyMatchUpFormatTiming:()=>Ng,proAutoSchedule:()=>RM,proConflicts:()=>_M,publicFindCourt:()=>oU,removeEventMatchUpFormatTiming:()=>qd,removeMatchUpCourtAssignment:()=>CM,reorderUpcomingMatchUps:()=>vM,scheduleMatchUps:()=>OM,scheduleProfileRounds:()=>Xp,setMatchUpDailyLimits:()=>FM,setSchedulingProfile:()=>Dc,toggleParticipantCheckInState:()=>zd,validateSchedulingProfile:()=>Gp});function Kg({calculateStartTimeFromCourts:t=!0,defaultRecoveryMinutes:e=0,averageMatchUpMinutes:r=90,remainingScheduleTimes:n,clearScheduleDates:o,tournamentRecords:i,periodLength:s,scheduleDate:a,startTime:c,venueIds:u,endTime:p}){if(typeof i!="object"||!Object.keys(i).length)return{error:Ft};s=s??vu({recoveryMinutes:e,averageMatchUpMinutes:r});let{courts:m,venues:d}=po({dates:[a],ignoreDisabled:!0,tournamentRecords:i}),l=m?.filter(N=>!u||u.includes(N.venueId));c||(c=l?.reduce((N,C)=>{let b=C.dateAvailability?.find(x=>!x.date||_n(a,x.date))?.startTime??C.startTime;return b&&(!N||Vt(b)<Vt(N))?b:N},void 0)),p||(p=l?.reduce((N,C)=>{let b=C.dateAvailability?.find(x=>!x.date||_n(a,x.date))?.endTime??C.endTime;return b&&(!N||Vt(b)>Vt(N))?b:N},void 0));let f=Object.values(i),g=Object.assign({},...f.map(N=>(N.events??[]).map(C=>{let{scheduleTiming:O}=Sa({tournamentRecord:N,event:C});return{[C.eventId]:{event:C,scheduleTiming:O}}})).flat()),h=Ou({sortDateMatchUps:!1,tournamentRecords:i,matchUpFilters:{scheduledDate:a,venueIds:u}}),S=h?.dateMatchUps??[],T=h?.completedMatchUps??[],A=[];A.push(...S),A.push(...T);let D={averageTimes:[{minutes:{default:r}}],recoveryTimes:[{minutes:{default:e}}]},y=A?.map(({eventId:N,schedule:C,matchUpFormat:O})=>{let{event:b,scheduleTiming:x}=g[N],w=b?.eventType,F={...x,defaultTiming:D,matchUpFormat:O},{averageMinutes:L,recoveryMinutes:v}=dp({eventType:w,timingDetails:F}),{courtId:B,venueId:H}=C,j=$t(C.scheduledTime),V=br(j,L);return{recoveryMinutes:v,averageMinutes:L,periodLength:s,startTime:j,endTime:V,courtId:B,venueId:H}}),E={calculateStartTimeFromCourts:t,remainingScheduleTimes:n,averageMatchUpMinutes:r,date:a,clearScheduleDates:o,periodLength:s,startTime:c,endTime:p,bookings:y,courts:l},{scheduleTimes:U}=Kd(E),M=u?.length===1&&u[0]||d?.length===1&&d[0].venueId||void 0,P=A.map(fe);return{venueId:M,scheduleTimes:U,dateScheduledMatchUpIds:P}}function CM(t){let e=lt(t,[{[ye]:!0}]);if(e.error)return e;let{removePriorValues:r,tournamentRecords:n,tournamentId:o,courtDayDate:i,matchUpId:s,courtId:a,drawId:c}=t,u=n[o];if(!u)return{error:W};let{drawDefinition:p,event:m}=Po({tournamentRecord:u,drawId:c});if(!p)return{error:X};let d=xt({drawDefinition:p,event:m,matchUpId:s});if(d.error)return d;if(d?.matchUp?.matchUpType===ln){let{itemValue:l}=vo({timeItems:d.matchUp.timeItems??[],itemType:Eo}),f=a&&l.filter(I=>I.courtId!==a);return rn({duplicateValues:!1,removePriorValues:r,tournamentRecord:u,drawDefinition:p,matchUpId:s,timeItem:{itemType:Eo,itemValue:f}})}else return Hi({tournamentRecord:u,drawDefinition:p,courtDayDate:i,courtId:"",matchUpId:s})}function RM({scheduleCompletedMatchUps:t,tournamentRecords:e,scheduledDate:r,matchUps:n}){if(!Ur(n))return{error:G};if(n.some(({hasContext:g})=>!g))return{info:"matchUps must have { inContext: true, nextMatchUps: true }",error:Gc};let i=Ou({courtCompletedMatchUps:!0,withCourtGridRows:!0,minCourtGridRows:10,tournamentRecords:e,matchUpFilters:{localPerspective:!0,scheduledDate:r}});if(i.error)return i;let{rows:s}=i,a=[],c=g=>[(g.sides||[]).map(I=>[I.participantId,I.participant?.individualParticipantIds]),(g.potentialParticipants||[]).flat().map(I=>[I.participantId,I.individualParticipantIds])].flat(1/0).filter(Boolean),u=s?.reduce((g,I)=>{let h=[],S=[];Object.values(I).forEach(A=>{if(Rt(A)&&(A.matchUpId&&(h.push(A.matchUpId),a.push(A)),A.sides)){let D=c(A);S.push(...D)}});let T=Object.values(I).filter(A=>Rt(A)&&!A.matchUpId);return g.concat({matchUpIds:h,availableCourts:T,rowId:I.rowId,participantIds:S})},[]);n.filter(({matchUpStatus:g})=>g&&g!==Dt&&(t||!ae.includes(g))).sort(hi);let p=Vr({matchUps:n.concat(a),includeParticipantDependencies:!0,tournamentRecords:e}).matchUpDependencies,m=[],d=[];for(;n.length&&u.length;){let g=u.shift(),I=[];for(;n.length&&g.availableCourts.length;){let h=n.concat(I).map(P=>P.matchUpId),S=n.shift(),T=S?.matchUpId,A=T&&p[T].matchUpIds.concat(p[T].dependentMatchUpIds),D=T&&h.some(P=>p[T].matchUpIds.includes(P)),y=T&&d.some(P=>p[T].dependentMatchUpIds.includes(P)),E=g.matchUpIds.some(P=>A.includes(P)),U=c(S),M=g.participantIds.some(P=>U.includes(P));if(S&&!E&&!D&&!M&&!y){let P=g.availableCourts.shift();Object.assign(S.schedule,P.schedule),Object.assign(P,S),m.push(S),g.participantIds.push(...U),g.matchUpIds.push(T)}else S&&I.push(S)}n.push(...I),d.push(...g.matchUpIds)}let l=m.map(({matchUpId:g,tournamentId:I,schedule:h,drawId:S})=>({tournamentId:I,matchUpId:g,drawId:S,schedule:{...h,scheduledDate:r}}));return i=_c({tournamentRecords:e,matchUpDetails:l}),{...i,scheduled:m,notScheduled:n}}function bM(t){let{courtDayDate:e}=t,r=lt(t,[{courtAssignments:!0,[to]:Er,[En]:et},{[ye]:!0}]);if(r.error)return r;let n=t.courtAssignments.reduce((s,a)=>{let{tournamentId:c}=a;return s[c]||(s[c]=[]),s[c].push(a),s},{}),o;return Object.keys(n).every(s=>{let a=t[ye][s];if(!a)return o={error:W},!1;let c=n[s].reduce((p,m)=>{let{drawId:d}=m;return p[d]||(p[d]=[]),p[d].push(m),p},{});Object.keys(c).every(p=>{let{drawDefinition:m}=We({tournamentRecord:a,drawId:p});return m?(c[p].every(d=>{let{matchUpId:l,courtId:f}=d,g=Hi({tournamentRecord:a,drawDefinition:m,courtDayDate:e,matchUpId:l,courtId:f});if(g.success)return g?.success;o={error:zy}}),!0):(o={error:X},!1)})}),o||R}function OM(t){let{tournamentRecords:e,allDateMatchUpIds:r=[],averageMatchUpMinutes:n=90,recoveryMinutes:o=0,recoveryMinutesMap:i,matchUpPotentialParticipantIds:s={},individualParticipantProfiles:a={},matchUpNotBeforeTimes:c={},matchUpDailyLimits:u={},checkPotentialRequestConflicts:p=!0,remainingScheduleTimes:m,clearScheduleDates:d,periodLength:l=30,scheduleDate:f,matchUpIds:g,venueIds:I,startTime:h,endTime:S,dryRun:T}=t,A=lt(t,[{[ye]:!0,[Xa]:!0},{[yn]:Rr,[En]:ar,[JC]:!0},{[yn]:k=>!k||!isNaN(k),[rR]:!1,[En]:G,[nR]:!1,[oR]:!1}]);if(A.error)return A;let D=t.competitionMatchUps??cn({nextMatchUps:!0,tournamentRecords:e}).matchUps??[],y=t.matchUpDependencies??Vr({includeParticipantDependencies:!0,matchUps:D,tournamentRecords:e}).matchUpDependencies;D.forEach(k=>{k.schedule?.scheduledDate&&_n(f,Ut(k.schedule.scheduledDate))&&ta({matchUpPotentialParticipantIds:s,matchUpNotBeforeTimes:c,matchUp:k})});let E=g.map(k=>D.find(K=>K.matchUpId===k)).filter(Boolean),{venueId:U,scheduleTimes:M,dateScheduledMatchUpIds:P}=Kg({tournamentRecords:e,remainingScheduleTimes:m,startTime:$t(h),endTime:$t(S),scheduleDate:Ut(f),averageMatchUpMinutes:n,clearScheduleDates:d,periodLength:l,venueIds:I}),N={},C=[],O={},b={},x={};D.filter(({matchUpId:k})=>P?.includes(k)).forEach(k=>{Vg({matchUpPotentialParticipantIds:s,individualParticipantProfiles:a,matchUp:k,value:1});let K=k.schedule?.scheduledTime;if(K){O[k.matchUpId]=K;let z=i?.[k.matchUpId];bc({recoveryMinutes:z||o,matchUpPotentialParticipantIds:s,individualParticipantProfiles:a,matchUpNotBeforeTimes:c,averageMatchUpMinutes:n,matchUpDependencies:y,scheduleTime:K,matchUp:k})}});let F=E.filter(k=>{let K=P?.includes(k.matchUpId),z=[Dt,Ot,me,$r,lr,_t].includes(k?.matchUpStatus);return!K&&!k.winningSide&&!z}),{matchUpMap:L,overLimitMatchUpIds:v,participantIdsAtLimit:B}=F.reduce((k,K)=>{let{drawId:z,tournamentId:q,matchUpType:nt}=K,{participantIdsAtLimit:Q,relevantParticipantIds:it}=nl({individualParticipantProfiles:a,matchUpPotentialParticipantIds:s,matchUpDailyLimits:u,matchUp:K});return Q?.length?(k.overLimitMatchUpIds.push(K.matchUpId),k.participantIdsAtLimit.push(...Q),k):(it.forEach(ot=>{Fa({individualParticipantProfiles:a,participantId:ot});let ut=a[ot].counters;ut[nt]?ut[nt]+=1:ut[nt]=1,ut[$n]?ut[$n]+=1:ut[$n]=1}),k.matchUpMap[q]||(k.matchUpMap[q]={}),k.matchUpMap[q][z]?k.matchUpMap[q][z].push(K):k.matchUpMap[q][z]=[K],ta({matchUpPotentialParticipantIds:s,matchUpNotBeforeTimes:c,matchUp:K}),k)},{matchUpMap:{},overLimitMatchUpIds:[],participantIdsAtLimit:[]});F=F.filter(({matchUpId:k})=>!v.includes(k));let H=0,j=M?.length??0,{personRequests:V}=yi({tournamentRecords:e,requestType:Oc});for(;M?.length&&F.length&&H<=j;){H++;let{scheduleTime:k}=M.shift(),K=F.find(z=>{let{matchUpId:q}=z,{dependenciesScheduled:nt,remainingDependencies:Q}=tl({matchUpScheduleTimes:O,matchUpDependencies:y,allDateMatchUpIds:r,matchUp:z});if(!nt)return x[q]||(x[q]=[]),x[q].push({scheduleTime:k,remainingDependencies:Q}),!1;let{enoughTime:it}=rl({individualParticipantProfiles:a,matchUpNotBeforeTimes:c,matchUpDependencies:y,scheduleTime:k,matchUp:z});if(!it)return b[q]||(b[q]=[]),b[q].push({scheduleTime:k}),!1;let{conflicts:ot}=el({potentials:p,averageMatchUpMinutes:n,requestConflicts:N,personRequests:V,scheduleTime:k,scheduleDate:f,matchUp:z});if(ot?.length)return!1;let ut=i?.[z.matchUpId];return bc({recoveryMinutes:ut||o,matchUpPotentialParticipantIds:s,individualParticipantProfiles:a,matchUpNotBeforeTimes:c,averageMatchUpMinutes:n,matchUpDependencies:y,scheduleTime:k,matchUp:z}),O[z.matchUpId]=k,!0});F=F.filter(({matchUpId:z})=>z!==K?.matchUpId),K||C.push(k)}F.forEach(k=>{Vg({individualParticipantProfiles:a,matchUpPotentialParticipantIds:s,value:-1,matchUp:k})});let Y=[];Object.keys(L).forEach(k=>{let K=e[k];K&&Object.keys(L[k]).forEach(z=>{let{drawDefinition:q}=Po({tournamentRecord:K,drawId:z});q&&L[k][z].forEach(({matchUpId:Q})=>{let it=O[Q];if(it){let ot=it.split(":").map(Hn).join(":"),ut=`${Ut(f)}T${ot}`;T?Y.push(Q):(Vo({drawDefinition:q,matchUpId:Q,scheduledTime:ut}).success&&Y.push(Q),U&&Zs({tournamentRecords:e,tournamentRecord:K,drawDefinition:q,matchUpId:Q,venueId:U}))}})})});let $=Dm(F);return{...R,requestConflicts:Object.values(N),remainingScheduleTimes:M?.map(({scheduleTime:k})=>k),individualParticipantProfiles:a,matchUpNotBeforeTimes:c,participantIdsAtLimit:B,skippedScheduleTimes:C,overLimitMatchUpIds:v,scheduledMatchUpIds:Y,noTimeMatchUpIds:$,recoveryTimeDeferred:b,dependencyDeferred:x}}function _M({tournamentRecords:t,matchUps:e}){if(!Ur(e))return{error:Sn};if(e.some(({matchUpId:f,hasContext:g})=>f&&!g))return{info:"matchUps must have { inContext: true, nextMatchUps: true }",error:Gc};let r=Math.max(...e.map(({schedule:f})=>f?.courtOrder||1).map(f=>ct(f))),n=Z(1,r+1).map(f=>e.filter(g=>ct(g.schedule?.courtOrder)===f)),o={},i={},s={};n.flat().filter(Boolean).sort(hi).forEach(({schedule:f})=>delete f[_f]);let c=pt(e.map(({drawId:f})=>f)),u=Vr({includeParticipantDependencies:!0,tournamentRecords:t,drawIds:c}).matchUpDependencies,p=n.map((f,g)=>f.reduce((I,h)=>{if(!h.matchUpId)return I;let{matchUpId:S,winnerMatchUpId:T,loserMatchUpId:A,schedule:D,sides:y,potentialParticipants:E}=h,U=D?.courtId;o[S]=g,i[U]=[],I.matchUpIds.push(S),s[S]=h;let M=u[S].matchUpIds;M.length&&I.sourceMatchUpIds.push(...M);let P=y?.map(C=>[C.participant?.individualParticipantIds,C.participantId]).flat().filter(Boolean)??[],N=E?.flat().map(({individualParticipantIds:C,participantId:O})=>[C,O]).flat().filter(Boolean)||[];return I.participantIds.push(...N,...P),T&&I.targetMatchUpIds.push(T),A&&I.targetMatchUpIds.push(A),I},{sourceMatchUpIds:[],targetMatchUpIds:[],participantIds:[],matchUpIds:[]})),m=(f,g)=>u[f].sources.reduce((I,h,S)=>h.includes(g)&&S+1||I,0),d=p.map(()=>[]),l=(f,g,I,h)=>{if(!s[f].schedule[_f]){s[f].schedule[_f]=g,s[f].schedule[nU]=h,d[o[f]].push({matchUpId:f,issueType:I,issueIds:h,issue:g});let S=s[f].schedule.courtId;i[S]||(i[S]=[]),i[S].push({matchUpId:f,issue:g,issueType:I,issueIds:h})}};return p.forEach((f,g)=>{let I=g?p[g-1]:void 0,h=p.slice(g+1),S={},T=dr(f.participantIds),A=Object.keys(T).filter(E=>T[E]>1),D=f.matchUpIds.filter(E=>u[E].participantIds.some(U=>A.includes(U)));D.forEach(E=>{S[E]||(S[E]={}),S[E][cc]||(S[E][cc]=D.filter(U=>U!==E))});let y=I&&f.participantIds.filter(E=>I.participantIds.includes(E));y&&y.forEach(E=>{let U=f.matchUpIds.concat(I.matchUpIds).filter(M=>u[M].participantIds.includes(E));U.forEach(M=>{S[M]||(S[M]={}),S[M][uc]||(S[M][uc]=U.filter(P=>P!==M))})}),f.matchUpIds.forEach(E=>{let U=u[E].matchUpIds;for(let P of h){let N=P.matchUpIds.filter(C=>U.includes(C));N?.length&&(N.forEach(C=>l(C,lh,Ta,[E])),l(E,lh,Ta,N))}if(S[E]?.[cc]&&l(E,cc,dh,S[E][cc]),f.sourceMatchUpIds.includes(E)){let P=f.matchUpIds.filter(N=>u[N].matchUpIds.includes(E));l(E,cc,Ta,P),f.matchUpIds.filter(N=>u[N].matchUpIds.includes(E)).forEach(N=>l(N,cc,Ta,[E]))}let M=I?.matchUpIds?.filter(P=>m(E,P)>1);if(M?.length&&(l(E,fh,Ta,M),M.forEach(P=>l(P,fh,Ta,[E]))),S[E]?.[uc]&&l(E,uc,dh,S[E][uc]),I?.targetMatchUpIds?.includes(E)){let P=s[E].schedule.courtId,N=U.filter(O=>I.matchUpIds.includes(O));N.some(O=>s[O].schedule.courtId===P)||(N.forEach(O=>l(O,uc,Ta,[E])),l(E,uc,Ta,N))}})}),{courtIssues:i,rowIssues:d}}function vM(t){let e="reorderUpcomingMatchUps",{tournamentRecords:r}=t;if(typeof r!="object"||!Object.keys(r).length)return _({result:{error:Ft},stack:e});let{matchUpsContextIds:n,firstToLast:o}=t;if(!n)return _({result:{error:et},stack:e});let i=n?.length;if(!i)return{...R};let s=0;return n.forEach((c,u)=>{let{tournamentId:p,drawId:m,matchUpId:d}=c,l=u+(o?-1:1);l<0&&(l=i-1),l===i&&(l=0);let f=n[l].schedule.scheduledTime,g=a({tournamentId:p,scheduledTime:f,matchUpId:d,drawId:m});if(g.success)s++;else return g}),s===i?R:_({result:{error:Ky},stack:e});function a({tournamentId:c,scheduledTime:u,matchUpId:p,drawId:m}){let d=r[c],{drawDefinition:l}=Po({tournamentRecord:d,drawId:m});return l?Vo({drawDefinition:l,scheduledTime:u,matchUpId:p}):{error:pr}}}function xM(t){let{scheduleChange:e,matchUpIds:r,dryRun:n}=t;if(!r||!Array.isArray(r))return{error:ia};if(typeof e!="object")return{error:G};let o=Xr(t),i=[],s=[];for(let c of Object.values(o)){let u=e1({tournamentRecord:c,scheduleChange:e,matchUpIds:r,dryRun:n});if(u.error)return u;Array.isArray(u.notRescheduled)&&s.push(...u.notRescheduled);let p=Dm(u.notRescheduled),m=[];u.rescheduled?.forEach(d=>{let{matchUpId:l}=d;p.includes(l)&&m.push(l),i.push(d)}),m.length&&(s=u?.notRescheduled?.filter(({matchUpId:d})=>!m.includes(d))||[])}let a=!!(i.length&&!s.length);return{...R,rescheduled:i,notRescheduled:s,allRescheduled:a}}function e1({tournamentRecord:t,scheduleChange:e,matchUpIds:r,dryRun:n}){if(!t)return{error:W};if(!r||!Array.isArray(r))return{error:ia};if(typeof e!="object")return{error:G};let o=[],i=[],{minutesChange:s,daysChange:a}=e;if(!s&&!a)return{...R};if(s&&isNaN(s))return{error:G};if(a&&isNaN(a))return{error:G};let{matchUps:c}=le({matchUpFilters:{matchUpIds:r},tournamentRecord:t}),u=({matchUpStatus:A})=>!ae.includes(A),p=c?.filter(A=>va({schedule:A.schedule})).filter(A=>u({matchUpStatus:A.matchUpStatus}));if(!p?.length)return{...R};let{tournamentInfo:m}=gs({tournamentRecord:t}),{startDate:d,endDate:l}=m,f=p?.reduce((A,D)=>{let{matchUpId:y,drawId:E}=D;return A[E]?A[E].push(y):A[E]=[y],A},{}),g=1440;for(let A of Object.keys(f)){let D=Po({tournamentRecord:t,drawId:A});if(D.error)return D;let y=D.drawDefinition,E=f[A].filter(U=>r.includes(U));for(let U of E)if(U&&y){let P=p.find(w=>w.matchUpId===U)?.schedule,{scheduledTime:N,scheduledDate:C}=P,O,b,x;if(!O&&a&&C){let w=Ut(C);x=tp(w,a),O=new Date(x)<new Date(d)||new Date(x)>new Date(l)}if(s&&N){let w=Ut(N),L=Vt($t(N))+s;if(O=L<0||L>g,!O){let v=br(N,s),B=w&&x||C===w&&w;b=B?`${B}T${v}`:v}}if(O)i.push(U);else{if(!n){if(b){let w=Vo({scheduledTime:b,drawDefinition:y,matchUpId:U});if(w.error)return w}if(x){let w=Zd({scheduledDate:x,drawDefinition:y,matchUpId:U});if(w.error)return w}}(b||x)&&o.push(U)}}}let I=le({matchUpFilters:{matchUpIds:r},tournamentRecord:t}).matchUps??[],h=I.filter(({matchUpId:A})=>o.includes(A)),S=I.filter(({matchUpId:A})=>i.includes(A)),T=h.length&&!S.length;return{...R,rescheduled:h,notRescheduled:S,allRescheduled:T}}function wM(t){let e="matchUpScheduleChange",{tournamentRecords:r}=t;if(typeof r!="object"||!Object.keys(r).length)return{error:Ft};let{sourceMatchUpContextIds:n,targetMatchUpContextIds:o,sourceCourtId:i,targetCourtId:s,courtDayDate:a}=t||{},{drawId:c,matchUpId:u,tournamentId:p}=n||{},{drawId:m,matchUpId:d,tournamentId:l}=o||{};if(!u&&!d)return _({result:{error:et},stack:e});let{matchUps:f}=cn({matchUpFilters:{matchUpIds:[u,d].filter(Boolean),drawIds:[c,m].filter(Boolean)},tournamentRecords:t.tournamentRecords}),g=f?.find(({matchUpId:A})=>A===u),I=f?.find(({matchUpId:A})=>A===d),h=0;if(s&&u&&!d){let A=S({tournamentId:p,matchUpId:u,courtId:s,matchUp:g,drawId:c,tournamentRecords:r,sourceCourtId:i,courtDayDate:a});if(A?.success&&h++,A.error)return _({result:A,stack:e})}else if(i&&s&&u&&d){let A=S({tournamentId:p,matchUpId:u,courtId:s,matchUp:g,drawId:c,tournamentRecords:r,sourceCourtId:i,courtDayDate:a});if(A.success&&h++,A.error)return _({result:A,stack:e,info:"source"});let D=S({tournamentId:l,sourceCourtId:s,matchUpId:d,matchUp:I,courtId:i,drawId:m,tournamentRecords:r,courtDayDate:a});if(D.success&&h++,D.error)return _({result:D,stack:e,info:"target"})}else return{error:et};return h?R:_({result:{error:Ns},stack:e});function S(A){let{tournamentRecords:D,tournamentId:y,matchUp:E,drawId:U}=A,M=D[y],{drawDefinition:P}=Po({tournamentRecord:M,drawId:U});return E.matchUpType===Bt?T({...A,tournamentRecord:M,drawDefinition:P}):Hi({...A,tournamentRecord:M,drawDefinition:P})}function T({removePriorValues:A,tournamentRecords:D,tournamentRecord:y,drawDefinition:E,sourceCourtId:U,courtDayDate:M,matchUpId:P,matchUp:N,courtId:C}){let O=[C].concat(N.schedule.allocatedCourts.map(({courtId:b})=>b).filter(b=>b!==U));return $p({removePriorValues:A,tournamentRecords:D,tournamentRecord:y,drawDefinition:E,courtDayDate:M,matchUpId:P,courtIds:O})}}function LM({scheduleAttributes:t=[Eo,di,xs,ws,Ls,Uo,fi,li,xi],tournamentRecord:e,drawDefinition:r,matchUpId:n}){let o="clearMatchUpSchedule",i=r?rr({matchUpFilters:{matchUpIds:[n]},inContext:!1,drawDefinition:r}).matchUps?.[0]:le({matchUpFilters:{matchUpIds:[n]},tournamentRecord:e,inContext:!1}).matchUps?.[0];if(!i)return{error:Oe};let s=(i.timeItems??[]).filter(a=>a?.itemType&&!t.includes(a?.itemType));return i.timeItems=s,It({tournamentId:e.tournamentId,context:o,drawDefinition:r,matchUp:i}),{...R}}function FM(t){let{tournamentRecord:e,tournamentId:r,dailyLimits:n}=t,o=t.tournamentRecords||e&&{[e.tournamentId]:e}||{};if(typeof o!="object"||!Object.keys(o).length)return{error:Ft};if(typeof n!="object")return{error:Xn};let i=Object.keys(o).filter(s=>!r||r===s);if(r&&!i.includes(r))return{error:G};for(let s of i){let a=o[s],c=St({element:a,extension:{name:Yc,value:{dailyLimits:n}}});if(c.error)return c}return{...R}}var zM={};Jt(zM,{addCollectionDefinition:()=>Xg,addCollectionGroup:()=>jM,aggregateTieFormats:()=>$M,compareTieFormats:()=>Go,getTieFormat:()=>NT,modifyCollectionDefinition:()=>zg,modifyTieFormat:()=>qM,mutate:()=>KM,orderCollectionDefinitions:()=>WM,query:()=>LD,removeCollectionDefinition:()=>Qg,removeCollectionGroup:()=>BM,tieFormatGenderValidityCheck:()=>pd,validateCollectionDefinition:()=>yu});var KM={};Jt(KM,{addCollectionDefinition:()=>Xg,addCollectionGroup:()=>jM,aggregateTieFormats:()=>$M,modifyCollectionDefinition:()=>zg,modifyTieFormat:()=>qM,orderCollectionDefinitions:()=>WM,removeCollectionDefinition:()=>Qg,removeCollectionGroup:()=>BM});function ei({drawDefinition:t,structureId:e,matchUpId:r,structure:n,matchUp:o,eventId:i,event:s}){let a="getTieFormat",c;if(e=n?.structureId??e,r=o?.matchUpId??r,(r||e)&&!t)return{error:X};if(i&&s)c=Gs(s);else if(r){if(t&&(!o||!n)){let u=xt({drawDefinition:t,matchUpId:r});if(u.error)return u;if(u.matchUp?.matchUpType!==ln)return _({result:{error:Je},stack:a});n||(n=u.structure),o||(o=u.matchUp)}c=fp({item:o,drawDefinition:t,structure:n,event:s})||fp({item:n,drawDefinition:t,structure:n,event:s})||Gs(t)||Gs(s)}else if(t&&e){if(!n){let u=st({drawDefinition:t,structureId:e});if(u.error)return u;n=u?.structure}c=fp({item:n,drawDefinition:t,structure:n,event:s})||Gs(t)||Gs(s)}else c=Gs(t)||Gs(s);return c?{...R,structure:n,tieFormat:c,matchUp:o}:_({result:{error:qa},stack:a})}function al({matchUp:t,updateInProgressMatchUps:e}){return!t.winningSide&&![ae].includes(t.matchUpStatus)&&(e||t.matchUpStatus!==Dn&&!Ie(t))}function VM({from:t,to:e}){let r=Object.keys(t),n=jt(r,Object.keys(e)).length===r.length,i=r.filter(c=>t[c]!==e[c]).map(c=>({countChange:e[c]-t[c],collectionId:c})),s=r.every(c=>t[c]===e[c]);return{equivalent:n&&s,matchUpsCountChanges:i}}function Px({updateInProgressMatchUps:t,tournamentRecord:e,drawDefinition:r,structure:n,tieFormat:o,eventId:i,matchUp:s,event:a,uuids:c}){let u="updateTieFormat",p=e?.tournamentId,m=0,d=0,l=0,f=0,g=o?.collectionDefinitions.reduce((y,E)=>(y[E.collectionId]=(y[E.collectionId]||0)+E.matchUpCount,y),{}),I=({tieFormat:y})=>{let E=y?.collectionDefinitions.reduce((U,M)=>(U[M.collectionId]=(U[M.collectionId]||0)+M.matchUpCount,U),{});return VM({from:E,to:g}).equivalent},h=ei({drawDefinition:r})?.tieFormat,S=ei({event:a})?.tieFormat;if(a&&i){for(let y of a.drawDefinitions??[])T({drawDefinition:y});a.tieFormat=Xe(o),f+=1}else if(s){if(!s.tieMatchUps)return _({result:{error:Je},stack:u});let y=dr(s.tieMatchUps?.map(({collectionId:N})=>N)),E=VM({to:g,from:y}),{changes:U,changesArePossible:M,cannotChangeReaon:P}=Ux({matchUp:s,check:E});if(E.equivalent)if(al({matchUp:s,updateInProgressMatchUps:t}))s.tieFormat=Xe(o),f+=1;else return _({result:{error:Pl},info:"matchUp is IN_PROGRESS or COMPLETE",stack:u});else if(M)D({tieFormat:o,matchUp:s,changes:U,uuids:c});else return _({context:{collectionMap:g,matchUpMap:y},result:{error:ni},info:P||"specified changes not possible",stack:u});d+=1,It({eventId:a?.eventId,context:u,drawDefinition:r,tournamentId:p,matchUp:s})}else if(n){let E=A({inheritedTieFormat:h??S,structure:n})?.modifiedMatchUpsCount;E&&(d+=E,m+=1,f+=1);let U=!n.tieFormat||Go({ancestor:n.tieFormat,descendant:o}).different;U&&(n.tieFormat=Xe(o),m+=1,f+=1),(E||U)&&r&&bt({structureIds:[n.structureId],eventId:a?.eventId,drawDefinition:r})}else if(r)T({drawDefinition:r}),r.tieFormat=Xe(o),f+=1;else return{error:X};return{modifiedStructuresCount:m,modifiedMatchUpsCount:d,addedMatchUpsCount:l,modifiedCount:f,...R,tieFormat:o};function T({drawDefinition:y}){let E=y.structures||[],U=[];for(let M of E){if(M.tieFormat)continue;let N=A({inheritedTieFormat:S,structure:M})?.modifiedMatchUpsCount;if(N){m+=1,d+=N;let C=M.structureId;U.push(C)}}return bt({structureIds:U,eventId:a?.eventId,drawDefinition:y}),U.length}function A({inheritedTieFormat:y,structure:E}){let U=0,M=At({matchUpFilters:{matchUpTypes:[Bt]},structure:E})?.matchUps||[];for(let P of M){let N=al({matchUp:P,updateInProgressMatchUps:t}),C=!1,O=dr(P.tieMatchUps?.map(({collectionId:x})=>x)),b=VM({from:O,to:g});if(b.equivalent)P.tieFormat&&I(P)&&N&&(P.tieFormat=Xe(o),C=!0);else{let{changes:x,changesArePossible:w}=Ux({matchUp:P,check:b});if(w&&!P.tieFormat)D({changes:x,matchUp:P,tieFormat:o,uuids:c});else if(y)(!P.tieFormat||Go({ancestor:y,descendant:P.tieFormat}).different)&&(P.tieFormat=y,C=!0);else return _({result:{error:qa},stack:u})}C&&(U+=1,It({tournamentId:e?.tournamentId,drawDefinition:r,context:u,eventId:i,matchUp:P}))}return{modifiedMatchUpsCount:U}}function D({uuids:y,matchUp:E,tieFormat:U,changes:M}){E.tieFormat=Xe(U);let P=[],N=[];return M.forEach(C=>{if(C.countChange>0){let O=Math.max(0,...E.tieMatchUps.filter(w=>w.collectionId===C.collectionId).map(Pr("collectionPosition"))),b=U.collectionDefinitions.find(w=>w.collectionId===C.collectionId),x=hu({matchUpsLimit:C.countChange,collectionPositionOffset:O,collectionDefinition:b,matchUp:E,uuids:y});N.push(...J(x,!1,!0)),l+=N.length,E.tieMatchUps.push(...x)}else{let O=C.toBePlayedTieMatchUpIds.slice(0,Math.abs(C.countChange));console.log("remove",O.length),P.push(...O),E.tieMatchUps=E.tieMatchUps.filter(({matchUpId:b})=>!O.includes(b))}}),N.length&&So({matchUps:N,drawDefinition:r,tournamentId:p,eventId:i}),P.length&&wn({matchUpIds:P,action:"updateTieFormat",drawDefinition:r,tournamentId:p,eventId:i}),{matchUpIdsRemoved:P,matchUpsAdded:N}}}function Ux({check:t,matchUp:e}){let r="",n=[];return{changesArePossible:t.matchUpsCountChanges.every(({collectionId:i,countChange:s})=>{let a=e.tieMatchUps.filter(u=>u.collectionId===i&&u.matchUpStatus===zt).map(Pr("matchUpId")),c=a.length+s>=0||s>0;return!c&&s<0&&(r="Insufficient TO_BE_PLAYED matchUps"),n.push({toBePlayedTieMatchUpIds:a,collectionId:i,countChange:s}),c}),changes:n,cannotChangeReaon:r}}function Lu({drawDefinition:t,auditData:e}){let{extension:r}=mt({name:Qi,element:t}),n={name:Qi,value:Array.isArray(r?.value)?r?.value.concat(e):[e]};St({element:t,extension:n})}function zg({updateInProgressMatchUps:t=!1,tournamentRecord:e,collectionOrder:r,collectionName:n,tieFormatName:o,drawDefinition:i,matchUpFormat:s,matchUpCount:a,collectionId:c,matchUpType:u,structureId:p,matchUpId:m,category:d,eventId:l,gender:f,event:g,collectionValueProfiles:I,collectionValue:h,matchUpValue:S,scoreValue:T,setValue:A}){let D="modifyCollectionDefinition";if(s&&!Sr({matchUpFormat:s}))return _({result:{error:G},context:{matchUpFormat:s},stack:D});if(n&&typeof n!="string")return _({result:{error:G},context:{collectionName:n},stack:D});if(f&&!Object.values(Km).includes(f))return _({result:{error:G},context:{gender:f},stack:D});if(d&&typeof d!="object")return _({result:{error:G},context:{category:d},stack:D});let y={collectionValueProfiles:I,collectionValue:h,matchUpValue:S,scoreValue:T,setValue:A};if(!Object.values(y).filter(Boolean).length&&!r&&!n&&!s&&!a&&!u)return _({result:{error:et},stack:D});if(Object.values(y).filter(Boolean).length>1)return _({info:"Only one value assignment allowed per collectionDefinition",result:{error:G},stack:D});let E=ei({drawDefinition:i,structureId:p,matchUpId:m,eventId:l,event:g});if(E.error)return _({result:E,stack:D});let{matchUp:U,structure:M,tieFormat:P}=E,N=Xe(P),C=P?.collectionDefinitions.find(Y=>Y.collectionId===c),O=N?.collectionDefinitions.find(Y=>Y.collectionId===c);if(!C)return _({info:"source collectionDefinition",result:{error:Ke},context:{collectionId:c},stack:D});let b=h??S??T??A;if(I){let Y=aS({matchUpCount:a??C?.matchUpCount??0,collectionValueProfiles:I});if(Y.errors)return _({result:{error:G},info:Y.errors,stack:D})}else if(b&&!ft(b))return _({result:{error:G},info:"value is not an integer",context:{value:b},stack:D});let x=(Y,$)=>jt(Object.keys(Y),Object.keys($)).length===Object.keys(Y).length&&jt(Object.values(Y),Object.values($)).length===Object.values(Y).length,w=I&&(!C.collectionValueProfiles||!x(C.collectionValueProfiles,I)),F=ft(h)&&C.collectionValue!==h||ft(S)&&C.matchUpValue!==S||ft(T)&&C.scoreValue!==T||ft(A)&&C.setValue!==A||w,L=[];if(F&&(O.collectionValueProfiles=void 0,O.collectionValue=void 0,O.matchUpValue=void 0,O.scoreValue=void 0,O.setValue=void 0,Object.assign(O,y),L.push({collectionId:c,...rt(y)})),(ft(T)||ft(A))&&O.collectionGroupNumber){let Y=O.collectionGroupNumber;N.collectionDefinitions=N.collectionDefinitions.map($=>{let{collectionGroupNumber:k,...K}=$;return k===Y?K:$}),N.collectionGroups=N.collectionGroups.filter(({groupNumber:$})=>$!==Y),L.push({collectionId:c,change:"collectionGroupNumber removed"})}let{aggregateValue:v,valueGoal:B}=Is(N),H=rt({aggregateValue:v,valueGoal:B});if((H.aggregateValue!==P?.winCriteria.aggregateValue||H.valueGoal!==P?.winCriteria.valueGoal)&&(N.winCriteria=H,L.push({collectionId:c,winCriteria:H})),ft(r)&&C.collectionOrder!==r&&(O.collectionOrder=r,L.push({collectionId:c,collectionOrder:r})),n&&C.collectionName!==n&&(O.collectionName=n,L.push({collectionId:c,collectionName:n})),s&&C.matchUpFormat!==s&&(O.matchUpFormat=s,L.push({collectionId:c,matchUpFormat:s})),ft(a)&&C.matchUpCount!==a&&(O.matchUpCount=a,L.push({collectionId:c,matchUpCount:a})),u&&C.matchUpType!==u)return _({result:{error:$u},context:{matchUpType:u},stack:D});d&&C.category!==d&&(O.category=d,L.push({collectionId:c,category:d})),f&&C.gender!==f&&(O.gender=f,L.push({collectionId:c,gender:f}));let j=rt(N);if(E=ir({tieFormat:j}),E.error)return _({result:E,stack:D});if(!L.length)return _({result:{...R,modifications:L}});if(P?.tieFormatName!==o?(j.tieFormatName=o,L.push({tieFormatName:o})):L.length&&(delete j.tieFormatName,L.push("tieFormatName removed: modifications without new tieFormatName")),E=Px({tieFormat:j,updateInProgressMatchUps:t,tournamentRecord:e,drawDefinition:i,structure:M,eventId:l,matchUp:U,event:g}),!E.error){let{appliedPolicies:Y}=Pt({tournamentRecord:e});if(Y?.audit?.[Qi]){let $=rt({collectionDefinition:O,drawId:i?.drawId,action:D,structureId:p,matchUpId:m,eventId:l});Lu({drawDefinition:i,auditData:$})}}return _({result:{...E,modifications:L},stack:D})}function Dx({updateInProgressMatchUps:t,drawDefinition:e,structureId:r,structure:n,matchUpId:o,matchUp:i}){let s=[];return o&&i?s=[i]:r&&n?s=At({matchUpFilters:{matchUpTypes:[Bt]},structure:n})?.matchUps??[]:e&&(s=rr({matchUpFilters:{matchUpTypes:[Bt]},drawDefinition:e})?.matchUps??[]),{targetMatchUps:s.filter(c=>!c.winningSide&&c.matchUpStatus!==me&&(t||c.matchUpStatus!==Dn&&!Ie(c)))}}function Nx({updateInProgressMatchUps:t,tournamentRecord:e,drawDefinition:r,targetMatchUps:n,tieFormat:o,event:i}){for(let s of n){let a=!!s.tieFormat;a&&(s.tieFormat=Xe(o));let c;if(t){let u=Pt({tournamentRecord:e,drawDefinition:r,event:i}).appliedPolicies,p=zn({matchUpId:s.matchUpId,exitWhenNoValues:!0,tournamentRecord:e,appliedPolicies:u,drawDefinition:r,event:i});if(p.error)return p;c=p.score}a&&!c&&It({tournamentId:e?.tournamentId,context:"updateTargetTeamMatchUps",eventId:i?.eventId,matchUp:s,drawDefinition:r})}return{...R}}function HA({updateInProgressMatchUps:t,originalValueGoal:e,tournamentRecord:r,wasAggregateValue:n,tieFormatName:o,drawDefinition:i,structureId:s,structure:a,tieFormat:c,matchUpId:u,matchUp:p,eventId:m,event:d}){let{aggregateValue:l,valueGoal:f}=Is(c);c.winCriteria=rt({aggregateValue:l,valueGoal:f}),(e&&e!==f||l&&!n)&&(o?c.tieFormatName=o:delete c.tieFormatName);let{targetMatchUps:g}=Dx({updateInProgressMatchUps:t,drawDefinition:i,structureId:s,structure:a,matchUpId:u,matchUp:p});Nx({updateInProgressMatchUps:t,tournamentRecord:r,targetMatchUps:g,drawDefinition:i,tieFormat:c,event:d});let I=rt(c),h=ir({tieFormat:I});if(h.error)return h;if(m&&d)d.tieFormat=I;else if(u&&p)p.tieFormat=c;else if(a)a.tieFormat=I;else if(i)i.tieFormat=I;else if(!p||!i)return{error:X};return bt({drawDefinition:i,eventId:d?.eventId}),{...R}}function BM({updateInProgressMatchUps:t=!0,collectionGroupNumber:e,tournamentRecord:r,drawDefinition:n,tieFormatName:o,structureId:i,matchUpId:s,matchUp:a,eventId:c,event:u}){if(!e)return{error:et};if(isNaN(e))return{error:G};let p="removeCollectionGroup",m=a?void 0:ei({drawDefinition:n,structureId:i,matchUpId:s,eventId:c,event:u});if(m?.error)return _({result:m,stack:p});let d=m?.structure;a=a??m?.matchUp;let l=m?.tieFormat,f=l?.winCriteria.valueGoal,g=l?.winCriteria.aggregateValue,I=Xe(l);if(m=ir({tieFormat:I}),m.error)return _({result:m,stack:p});let h=[];if(I.collectionDefinitions=I.collectionDefinitions.map(S=>{let{collectionGroupNumber:T,...A}=S;return T!==e?S:(h.push(S.collectionId),A)}),I.collectionGroups=I.collectionGroups.filter(({groupNumber:S})=>S!==e),m=HA({updateInProgressMatchUps:t,originalValueGoal:f,wasAggregateValue:g,tournamentRecord:r,drawDefinition:n,tieFormatName:o,structureId:i,structure:d,tieFormat:I,matchUpId:s,matchUp:a,eventId:c,event:u}),!m.error){let{appliedPolicies:S}=Pt({tournamentRecord:r});if(S?.audit?.[Qi]){let T=rt({drawId:n?.drawId,collectionGroupNumber:e,action:p,structureId:i,matchUpId:s,eventId:c});Lu({drawDefinition:n,auditData:T})}}return _({result:{...m,modifiedCollectionIds:h},stack:p})}function cl({tieFormat:t,orderMap:e}){let r=Xe(t);return r.collectionDefinitions.forEach(n=>{let o=e[n.collectionId];o&&(n.collectionOrder=o)}),r.collectionDefinitions.sort((n,o)=>Qa(n.collectionOrder)-Qa(o.collectionOrder)),r}function WM({tournamentRecord:t,drawDefinition:e,structureId:r,matchUpId:n,orderMap:o,eventId:i,matchUp:s,event:a}){if(typeof o!="object"||!Object.values(o).every(c=>ft(c)))return _({result:{error:G},context:{orderMap:o}});if(i&&a?.tieFormat)Mx({tournamentRecord:t,event:a,orderMap:o});else if(n){let c=e&&xt({drawDefinition:e,matchUpId:n});if(c?.error)return c;if(s=c.matchUp,!s)return{error:sr};s?.tieFormat&&(s.tieFormat=cl({tieFormat:s.tieFormat,orderMap:o}),It({tournamentId:t?.tournamentId,eventId:a?.eventId,drawDefinition:e,matchUp:s}))}else if(r){let c=st({drawDefinition:e,structureId:r});if(c.error)return c;let u=c.structure;if(u?.tieFormat)u.tieFormat=cl({tieFormat:u.tieFormat,orderMap:o}),Cx({eventId:a?.eventId,tournamentRecord:t,drawDefinition:e,structure:u,orderMap:o}),bt({drawDefinition:e,structureIds:[u.structureId]});else if(e.tieFormat)HM({structureIds:[r],tournamentRecord:t,drawDefinition:e,orderMap:o,event:a});else if(a?.tieFormat)Mx({structureIds:[r],tournamentRecord:t,orderMap:o,event:a});else return{error:Ke}}else if(e?.tieFormat)HM({tournamentRecord:t,drawDefinition:e,orderMap:o,event:a});else return{error:Ke};return{...R}}function Mx({tournamentRecord:t,structureIds:e,orderMap:r,event:n}){let o=cl({tieFormat:n.tieFormat,orderMap:r});e?.length||(n.tieFormat=o);for(let i of n.drawDefinitions??[])HM({tournamentRecord:t,drawDefinition:i,structureIds:e,orderMap:r,event:n})}function HM({tournamentRecord:t,drawDefinition:e,structureIds:r,orderMap:n,event:o}){let i=e.tieFormat??o?.tieFormat,s=cl({tieFormat:i,orderMap:n});r?.length||(e.tieFormat=s);let a=[];for(let c of e.structures??[])r?.length&&!r.includes(c.structureId)||((c.tieFormat||r?.includes(c.structureId))&&(c.tieFormat=cl({tieFormat:c.tieFormat??e.tieFormat??o?.tieFormat,orderMap:n})),Cx({eventId:o?.eventId,tournamentRecord:t,drawDefinition:e,structure:c,orderMap:n}),a.push(c.structureId));bt({drawDefinition:e,structureIds:a})}function Cx({tournamentRecord:t,drawDefinition:e,structure:r,orderMap:n,eventId:o}){let i=At({matchUpFilters:{matchUpTypes:[Bt]},structure:r})?.matchUps;for(let s of i)s.tieFormat&&(s.tieFormat=cl({tieFormat:s.tieFormat,orderMap:n}),It({tournamentId:t?.tournamentId,drawDefinition:e,eventId:o,matchUp:s}))}function Qg({updateInProgressMatchUps:t=!0,tieFormatComparison:e,tournamentRecord:r,drawDefinition:n,tieFormatName:o,collectionId:i,structureId:s,matchUpId:a,eventId:c,matchUp:u,event:p}){let m="removeCollectionDefinition",d=u?void 0:ei({drawDefinition:n,structureId:s,matchUpId:a,eventId:c,event:p});if(d?.error)return _({result:d,stack:m});let l=d?.structure;u=u??d?.matchUp;let f=d?.tieFormat,g=Xe(f);if(d=ir({tieFormat:g}),d.error)return _({result:d,stack:m});let I=g?.collectionDefinitions?.find(P=>P.collectionId===i);if(!I)return _({result:{error:Ke,collectionId:i}});g.collectionDefinitions=g.collectionDefinitions.filter(P=>P.collectionId!==i),I.collectionGroupNumber&&(g.collectionDefinitions=g.collectionDefinitions.map(P=>{let{collectionGroupNumber:N,...C}=P;return C}),g.collectionGroups=g.collectionGroups.filter(({groupNumber:P})=>P!==I.collectionGroupNumber));let{aggregateValue:h,valueGoal:S}=Is(g);g.winCriteria=rt({aggregateValue:h,valueGoal:S});let T=f?.winCriteria.valueGoal,A=f?.winCriteria.aggregateValue;(T&&T!==S||h&&!A)&&(o?g.tieFormatName=o:delete g.tieFormatName);let D=[];a&&u?D=[u]:s&&l?D=At({matchUpFilters:{matchUpTypes:[Bt]},structure:l})?.matchUps??[]:n?D=rr({matchUpFilters:{matchUpTypes:[Bt]},drawDefinition:n})?.matchUps??[]:p&&(D=co({matchUpFilters:{matchUpTypes:[Bt]},drawDefinition:n})?.matchUps??[]);let y=(D||[]).filter(P=>{let C=P.tieMatchUps?.filter(b=>b.collectionId===i)?.some(Ie),O=e&&P.tieFormat?Go({descendant:P.tieFormat,ancestor:g})?.different:!1;return t&&!C||!P.winningSide&&P.matchUpStatus!==me&&(t||P.matchUpStatus!==Dn&&!Ie(P)&&!O)});if(!y.length)return{error:Ns};let{appliedPolicies:E}=Pt({tournamentRecord:r});if(a&&u&&t){let P=u.tieMatchUps?.filter(N=>N.collectionId===i);for(let N of P??[]){let C=La({matchUpId:N.matchUpId,tieMatchUpId:u?.matchUpId,winningSide:void 0,removeScore:!0,tournamentRecord:r,appliedPolicies:E,drawDefinition:n,event:p});if(C.error||(C=xt({drawDefinition:n,matchUpId:a}),C.error))return C;u=C?.matchUp}}let U=[];for(let P of y){for(let N of P?.sides??[])N.lineUp=(N.lineUp??[]).map(C=>({participantId:C.participantId,collectionAssignments:(C?.collectionAssignments??[]).filter(O=>O.collectionId!==i)}));if(P.tieMatchUps=(P.tieMatchUps??[]).filter(N=>{let C=N.collectionId===i;return C&&U.push(N.matchUpId),!C}),P.tieFormat&&(P.tieFormat=Xe(g)),t){let N=zn({matchUpId:P.matchUpId,exitWhenNoValues:!0,tournamentRecord:r,appliedPolicies:E,drawDefinition:n,event:p});if(N.error)return N}It({tournamentId:r?.tournamentId,eventId:p?.eventId,drawDefinition:n,context:m,matchUp:P})}U.length&&wn({tournamentId:r?.tournamentId,matchUpIds:U,eventId:p?.eventId,drawDefinition:n});let M=rt(g);if(d=ir({tieFormat:M}),d.error)return _({result:d,stack:m});if(c&&p)p.tieFormat=M;else if(a&&u)u.tieFormat=M;else if(l)l.tieFormat=M;else if(n)n.tieFormat=M;else if(!u||!n)return{error:X};if(bt({drawDefinition:n,eventId:p?.eventId}),E?.audit?.[Qi]){let P=rt({drawId:n?.drawId,action:m,collectionId:i,structureId:s,matchUpId:a,eventId:c});Lu({drawDefinition:n,auditData:P})}return{tieFormat:M,deletedMatchUpIds:U,targetMatchUps:y,...R}}function jM({updateInProgressMatchUps:t=!0,tournamentRecord:e,groupDefinition:r,drawDefinition:n,collectionIds:o,tieFormatName:i,structureId:s,matchUpId:a,matchUp:c,eventId:u,event:p}){let m="addCollectionGroup";if(!Array.isArray(o))return _({result:{error:et},stack:m});let d=c?void 0:ei({drawDefinition:n,structureId:s,matchUpId:a,eventId:u,event:p});if(d?.error)return _({result:d,stack:m});let l=d?.structure;c=c||d?.matchUp;let f=d?.tieFormat,g=f?.winCriteria.valueGoal,I=Xe(f);if(d=ir({tieFormat:I}),d.error)return _({result:d,stack:m});for(let T of I.collectionDefinitions){let{collectionId:A,collectionGroupNumber:D}=T;if(D&&o.includes(A))return _({info:"collectionIds cannot be part of other collectionGroups",result:{error:G},stack:m})}let S=(I.collectionGroups||[]).reduce((T,A)=>A.groupNumber>T?A.groupNumber:T,0)+1;return r.groupNumber=S,I.collectionDefinitions=I.collectionDefinitions.map(T=>o.includes(T.collectionId)?{...T,collectionGroupNumber:S}:T),I.collectionGroups=[...I.collecitonGroups||[],r],HA({updateInProgressMatchUps:t,originalValueGoal:g,tournamentRecord:e,drawDefinition:n,tieFormatName:i,structureId:s,structure:l,tieFormat:I,matchUpId:a,matchUp:c,eventId:u,event:p})}function Xg({updateInProgressMatchUps:t=!0,collectionDefinition:e,referenceCategory:r,tournamentRecord:n,policyDefinitions:o,enforceCategory:i,referenceGender:s,drawDefinition:a,tieFormatName:c,enforceGender:u,structureId:p,matchUpId:m,matchUp:d,eventId:l,uuids:f,event:g}){let I="addCollectionDefinition",h=Pt({tournamentRecord:n,drawDefinition:a,event:g}).appliedPolicies??{},S=o?.[ze]??h?.[ze];i=i??S?.participants?.enforceCategory;let T=(u??S?.participants?.enforceGender)!==!1,A=!!((r??g?.category)&&i!==!1),D=!!((s??g?.gender)&&T),y=yu({referenceCategory:r??g?.category,collectionDefinition:e,referenceGender:s,checkCategory:A,checkGender:D,event:g});if(y.error)return _({result:y,stack:I});let E=d?.tieFormat?void 0:ei({drawDefinition:a,structureId:p,matchUpId:m,eventId:l,event:g});if(E?.error)return _({result:{error:E.error},stack:I});let U=E?.structure;d=d??E?.matchUp;let M=d?.tieFormat??E?.tieFormat,P=Xe(M);if(E=ir({tieFormat:P}),E?.error)return _({result:{error:E.error},stack:I});if(!e.collectionId)e.collectionId=Mt();else if(P.collectionDefinitions.map(({collectionId:B})=>B).includes(e.collectionId))return _({context:{collectionId:e.collectionId},result:{error:Jy}});P.collectionDefinitions.push(e),P.collectionDefinitions.sort((v,B)=>(v.collectionOrder||0)-(B.collectionOrder||0)).forEach((v,B)=>v.collectionOrder=B+1);let{aggregateValue:N,valueGoal:C}=Is(P);P.winCriteria=rt({aggregateValue:N,valueGoal:C});let O=M?.winCriteria.valueGoal,b=M?.winCriteria.aggregateValue;(O&&O!==C||N&&!b)&&(c?P.tieFormatName=c:delete P.tieFormatName);let x=[],w=[],F=[],L=rt(P);if(E=ir({tieFormat:L}),E?.error)return _({result:{error:E.error},stack:I});if(l&&g){g.tieFormat=L;for(let v of g.drawDefinitions??[])if(!v.tieFormat)for(let B of v.structures??[]){if(B.tieFormat)continue;let H=YM({updateInProgressMatchUps:t,collectionDefinition:e,structure:B,uuids:f});w.push(...H.newMatchUps),F.push(...H.targetMatchUps),x.push(B.structureId)}WA({modifiedMatchUps:F,eventId:g?.eventId,modifiedStructureIds:x,tournamentRecord:n,drawDefinition:a,addedMatchUps:w,stack:I})}else if(p&&U){U.tieFormat=L;let v=YM({updateInProgressMatchUps:t,collectionDefinition:e,structure:U,uuids:f});w.push(...v.newMatchUps),F=v.targetMatchUps,WA({modifiedMatchUps:F,eventId:g?.eventId,modifiedStructureIds:x,tournamentRecord:n,drawDefinition:a,addedMatchUps:w,stack:I})}else if(m&&d){if(!al({matchUp:d,updateInProgressMatchUps:t}))return _({result:{error:Pl},stack:I});d.tieFormat=L;let v=hu({collectionDefinition:e,matchUp:d,uuids:f});Array.isArray(d.tieMatchUps)||(d.tieMatchUps=[]),d.tieMatchUps.push(...v),w.push(...v),WA({modifiedMatchUps:[d],eventId:g?.eventId,modifiedStructureIds:x,tournamentRecord:n,drawDefinition:a,addedMatchUps:w,stack:I})}else if(a){a.tieFormat=L;for(let v of a.structures??[]){let B=YM({updateInProgressMatchUps:t,collectionDefinition:e,structure:v,uuids:f});x.push(v.structureId),w.push(...B.newMatchUps),F.push(...B.targetMatchUps)}WA({modifiedMatchUps:F,eventId:g?.eventId,tournamentRecord:n,drawDefinition:a,addedMatchUps:w,stack:I})}else return{error:X};if(h?.audit?.[Qi]){let v=rt({drawId:a?.drawId,collectionDefinition:e,action:I,structureId:p,matchUpId:m,eventId:l});Lu({drawDefinition:a,auditData:v})}return{tieFormat:L,targetMatchUps:F,addedMatchUps:w,...R}}function YM({updateInProgressMatchUps:t,collectionDefinition:e,structure:r,uuids:n}){let o=[],s=(At({matchUpFilters:{matchUpTypes:[Bt]},structure:r})?.matchUps).filter(a=>al({matchUp:a,updateInProgressMatchUps:t})&&!a.tieFormat);for(let a of s){let c=hu({collectionDefinition:e,matchUp:a,uuids:n});Array.isArray(a.tieMatchUps)||(a.tieMatchUps=[]),a.tieMatchUps.push(...c),o.push(...c)}return{newMatchUps:o,targetMatchUps:s}}function WA({modifiedStructureIds:t,tournamentRecord:e,modifiedMatchUps:r,drawDefinition:n,addedMatchUps:o,eventId:i,stack:s}){So({tournamentId:e?.tournamentId,matchUps:o,drawDefinition:n,eventId:i}),r?.forEach(a=>{It({tournamentId:e?.tournamentId,drawDefinition:n,context:s,matchUp:a,eventId:i})}),bt({structureIds:t,drawDefinition:n,eventId:i})}function qM({updateInProgressMatchUps:t=!1,tieFormatComparison:e,modifiedTieFormat:r,tournamentRecord:n,drawDefinition:o,structureId:i,matchUpId:s,eventId:a,uuids:c,event:u}){let p="modifyTieFormat";if(!ir({tieFormat:r}).valid)return _({result:{error:ni},info:"falied validation",stack:p});let m=ei({drawDefinition:o,structureId:i,matchUpId:s,eventId:a,event:u});if(m.error)return _({result:m,stack:p});let{matchUp:d,tieFormat:l}=m,f=Xe(l),g=Go({descendant:r,ancestor:f});if(g.invalid)return _({context:{invalid:g.invalid},result:{error:ni},stack:p});if(!g?.different)return _({result:{...R},info:"Nothing to do",stack:p});let I=f.collectionDefinitions.map(({collectionId:M})=>M),h=r.collectionDefinitions.map(({collectionId:M})=>M),S=I.filter(M=>!h.includes(M)),T=r.collectionDefinitions.filter(({collectionId:M})=>!I.includes(M)),A=T.map(Pr("collectionId")),D=[],y,E=r.tieFormatName;for(let M of r.collectionDefinitions){if(A.includes(M.collectionId))continue;let P=zg({updateInProgressMatchUps:t,...M,tournamentRecord:n,tieFormatName:E,drawDefinition:o,structureId:i,matchUpId:s,eventId:a,event:u});if(P.modifications&&D.push(...P.modifications),P.error)return _({result:P,stack:p});P.tieFormat&&(y=P.tieFormat)}for(let M of T){let P=Xg({updateInProgressMatchUps:t,collectionDefinition:M,tournamentRecord:n,drawDefinition:o,tieFormatName:E,structureId:i,matchUpId:s,matchUp:d,eventId:a,uuids:c,event:u});if(P.error)return _({result:P,stack:p});P.tieFormat&&(y=P.tieFormat)}for(let M of S){let P=Qg({updateInProgressMatchUps:t,tieFormatComparison:e,tournamentRecord:n,drawDefinition:o,tieFormatName:E,collectionId:M,structureId:i,matchUpId:s,eventId:a,matchUp:d,event:u});if(P.error)return _({result:P,stack:p});P.tieFormat&&(y=P.tieFormat)}return l?.tieFormatName!==E?(y.tieFormatName=E,D.push({tieFormatName:E})):(D.length||A.length||S.length)&&(delete y.tieFormatName,D.push("tieFormatName removed: modifications without new tieFormatName")),y.collectionDefinitions=y.collectionDefinitions.sort((M,P)=>Qa(M.collectionOrder)-Qa(P.collectionOrder)).map((M,P)=>({...M,collectionOrder:P+1})),{processedTieFormat:Xe(y),modifications:D,...R}}function $M({tournamentRecord:t}){if(!t)return{error:W};let e=0;for(let r of t.events??[]){let n=r.tieFormats??[],o=p=>{if(!p.tieFormat)return;let m;for(let d of n)Go({descendant:p.tieFormat,ancestor:d}).different||(m=d.tieFormatId);if(m)p.tieFormatId=m,delete p.tieFormat;else{let d=J(p.tieFormat,void 0,!0);d.tieFormatId||(d.tieFormatId=Mt()),p.tieFormatId=d.tieFormatId,delete p.tieFormat,n.push(d),e+=1}},i=r.eventType;o({tieFormat:r.tieFormat,eventType:i});for(let p of r.drawDefinitions??[]){o({tieFormat:p.tieFormat,eventType:i});for(let m of p.structures??[])o({tieFormat:m.tieFormat,eventType:i})}let s=(p,m)=>{let d=c.matchUps?.find(l=>l.matchUpId===p);d&&(d.tieFormatId=m,delete d.tieFormat,It({tournamentId:t?.tournamentId,eventId:r.eventId,matchUp:d}))},a=p=>{let m=J(p.tieFormat,void 0,!0);m.tieFormatId||(m.tieFormatId=Mt()),n.push(m),e+=1,s(p.matchUpId,m.tieFormatId)},c=co({matchUpFilters:{matchUpTypes:[ln]},event:r}),u=c.matchUps??[];for(let p of u){let m;for(let d of n)p.tieFormat&&Go({descendant:p.tieFormat,ancestor:d}).different||(m=d.tieFormatId);m?s(p.matchUpId,m):a(p)}n.length&&(r.tieFormats=n)}return{...R,addedCount:e}}var oC={};Jt(oC,{addDrawDefinitionExtension:()=>ep,addEventExtension:()=>Io,addEventTimeItem:()=>ki,addExtension:()=>St,addNotes:()=>Up,addOnlineResource:()=>XM,addParticipantExtension:()=>SE,addParticipantTimeItem:()=>Jf,addTimeItem:()=>Ti,addTournamentExtension:()=>tf,addTournamentTimeItem:()=>Gi,analyzeDraws:()=>Eu,analyzeTournament:()=>DT,getAllowedDrawTypes:()=>vd,getAllowedMatchUpFormats:()=>yT,getAppliedPolicies:()=>Pt,getCompetitionDateRange:()=>wd,getCompetitionPenalties:()=>ET,getPolicyDefinitions:()=>yo,getTournamentInfo:()=>gs,getTournamentPenalties:()=>xd,getTournamentPersons:()=>PT,getTournamentStructures:()=>jh,getTournamentTimeItem:()=>mu,mutate:()=>nC,query:()=>xD,removeDrawDefinitionExtension:()=>TE,removeEventExtension:()=>rp,removeExtension:()=>or,removeNotes:()=>XU,removeParticipantExtension:()=>AE,removeTournamentExtension:()=>ef,setTournamentCategories:()=>tC,setTournamentDates:()=>Jg,setTournamentEndDate:()=>rC,setTournamentName:()=>JM,setTournamentNotes:()=>ZM,setTournamentStartDate:()=>eC,setTournamentStatus:()=>QM});var nC={};Jt(nC,{addDrawDefinitionExtension:()=>ep,addEventExtension:()=>Io,addEventTimeItem:()=>ki,addExtension:()=>St,addNotes:()=>Up,addOnlineResource:()=>XM,addParticipantExtension:()=>SE,addParticipantTimeItem:()=>Jf,addTimeItem:()=>Ti,addTournamentExtension:()=>tf,addTournamentTimeItem:()=>Gi,removeDrawDefinitionExtension:()=>TE,removeEventExtension:()=>rp,removeExtension:()=>or,removeNotes:()=>XU,removeParticipantExtension:()=>AE,removeTournamentExtension:()=>ef,setTournamentCategories:()=>tC,setTournamentDates:()=>Jg,setTournamentEndDate:()=>rC,setTournamentName:()=>JM,setTournamentNotes:()=>ZM,setTournamentStartDate:()=>eC,setTournamentStatus:()=>QM});var r1="ABANDONED",n1="ACTIVE",o1="CANCELLED",i1="COMPLETED",s1="IN_PROGRESS",jA={ABANDONED:r1,ACTIVE:n1,CANCELLED:o1,COMPLETED:i1,IN_PROGRESS:s1};function QM({tournamentRecord:t,status:e}){return t?e&&!Object.keys(jA).includes(e)?{error:G,info:"Unknown status"}:(t.tournamentStatus=e,{...R}):{error:W}}function XM({tournamentRecord:t,onlineResource:e,organisationId:r,participantId:n,personId:o,courtId:i,venueId:s}){if(!t)return{error:W};if(!Rt(e))return{error:et};if(jt(Object.keys(e),["resourceSubType","resourceType","identifier"]).length!==3)return _({result:{error:Xn},context:{onlineResource:e}});if(r){if(t.parentOrganisation?.parentOrganisationId!==r)return _({result:{error:Ke}});t.parentOrganisation.onlineResources||(t.parentOrganisation.onlineResources=[]),t.parentOrganisation.onlineResources.push(e)}else if(n||o){let a=(t.participants??[]).find(c=>o&&c.person?.personId===o||c.participantId===n);if(!a)return o?_({result:{error:Ke}}):_({result:{error:Zt}});if(o){if(a.person?.personId!==o)return _({result:{error:Us}});a.person.onlineResources||(a.person.onlineResources=[]),a.person.onlineResources.push(e)}else a.onlineResources||(a.onlineResources=[]),a.onlineResources.push(e)}else if(i){let a=(t.venues??[]).filter(c=>!s||c.venueId===s).flatMap(c=>(c.courts??[]).filter(u=>u.courtId===i))?.[0];if(!a)return _({result:{error:Ka}});a.onlineResources||(a.onlineResources=[]),a.onlineResources.push(e)}else if(s){let a=(t.venues??[]).find(c=>c.venueId===s);if(!a)return _({result:{error:Ds}});a.onlineResources||(a.onlineResources=[]),a.onlineResources.push(e)}else t.onlineResources||(t.onlineResources=[]),t.onlineResources.push(e);return{...R}}function JM({tournamentRecord:t,promotionalName:e,tournamentName:r,formalName:n}){return t?(r&&(t.tournamentName=r),e&&(t.promotionalName=e),n&&(t.formalName=n),t.promotionalName===t.tournamentName&&delete t.promotionalName,t.formalName===t.tournamentName&&delete t.formalName,{...R}):{error:W}}function ZM({tournamentRecord:t,notes:e}){return t?Up({element:t,notes:e}):{error:W}}function tC({tournamentRecord:t,categories:e}){return t?(e=(e||[]).filter(r=>r.categoryName&&r.type),t.tournamentCategories=e,{...R}):{error:W}}function Rx({tournamentRecord:t}){if(!t)return{error:W};let{startDate:e,endDate:r}=t,n=bs(e,r),o=[];for(let i of t.venues||[])i?.courts?.length&&o.push(...i.courts);for(let i of o){let{startTime:s,endTime:a}=(i.dateAvailability??[]).reduce((p,m)=>{let d=Vt(p.startTime),l=Vt(p.endTime);return m.startTime&&Vt(m.startTime)<d&&(p.startTime=m.startTime),m.endTime&&Vt(m.endTime)>l&&(p.endTime=m.endTime),p},{startTime:"08:00",endTime:"18:00"}),c=n.map(p=>i.dateAvailability?.find(d=>d.date===p)??{date:p,startTime:s,endTime:a}),u=i.dateAvailability?.find(p=>!p.date);u&&c.unshift(u),i.dateAvailability=c}return{...R}}function Jg(t){let{tournamentRecord:e,startDate:r,endDate:n}=t,o=lt(t,[{tournamentRecord:!0},{[fm]:{startDate:!1,endDate:!1},[En]:ar,[yn]:m=>Ro.test(m)}]);if(o.error)return o;if(n&&r&&new Date(n)<new Date(r))return{error:G};let i;(r&&e.startDate&&new Date(r)>new Date(e.startDate)||n&&e.endDate&&new Date(n)<new Date(e.endDate))&&(i=!0);let s=bs(e.startDate,e.endDate);r&&(e.startDate=r),n&&(e.endDate=n);let a=bs(e.startDate,e.endDate),c=s.filter(m=>!a.includes(m)),u=a.filter(m=>!s.includes(m));for(let m of e.events??[])r&&m.startDate&&new Date(r)>new Date(m.startDate)&&(m.startDate=r),n&&m.endDate&&new Date(n)<new Date(m.endDate)&&(m.endDate=n);r&&e.endDate&&new Date(r)>new Date(e.endDate)&&(e.endDate=r),n&&e.startDate&&new Date(n)<new Date(e.startDate)&&(e.startDate=n);let p=i&&a1({tournamentRecord:e})?.unscheduledMatchUpIds;return Rx({tournamentRecord:e}),Tt({topic:HE,payload:{startDate:r,endDate:n}}),{...R,unscheduledMatchUpIds:p,datesAdded:u,datesRemoved:c}}function eC({tournamentRecord:t,startDate:e}){return Jg({tournamentRecord:t,startDate:e})}function rC({tournamentRecord:t,endDate:e}){return Jg({tournamentRecord:t,endDate:e})}function a1({tournamentRecord:t}){let e=le({tournamentRecord:t}).matchUps??[],r=t.startDate&&new Date(t.startDate),n=t.endDate&&new Date(t.endDate),o=[],i=[];for(let s of e){let{schedule:a,matchUpId:c}=s;if(a&&a.scheduledDate){let u=new Date(a.scheduledDate);(r&&u<r||n&&u>n)&&(i.push(c),o.includes(a.scheduledDate)||o.push(a.scheduledDate))}}return o.length&&!Qp({scheduledDates:o,tournamentRecord:t}).clearedScheduleCount?{error:ry}:{unscheduledMatchUpIds:i}}var fC={};Jt(fC,{addCourt:()=>il,addCourts:()=>qg,addVenue:()=>pc,deleteCourt:()=>mC,deleteVenue:()=>qA,deleteVenues:()=>sC,disableCourts:()=>aC,disableVenues:()=>cC,enableCourts:()=>uC,enableVenues:()=>pC,generate:()=>iC,generateCourts:()=>Og,getCompetitionVenues:()=>Lp,getCourts:()=>jT,getVenuesAndCourts:()=>po,modifyCourt:()=>tI,modifyCourtAvailability:()=>Zg,modifyVenue:()=>dC,mutate:()=>lC,publicFindVenue:()=>Th,query:()=>zD});var iC={};Jt(iC,{generateCourts:()=>Og});var lC={};Jt(lC,{addCourt:()=>il,addCourts:()=>qg,addVenue:()=>pc,deleteCourt:()=>mC,deleteVenue:()=>qA,deleteVenues:()=>sC,disableCourts:()=>aC,disableVenues:()=>cC,enableCourts:()=>uC,enableVenues:()=>pC,modifyCourt:()=>tI,modifyCourtAvailability:()=>Zg,modifyVenue:()=>dC});function ul(t){if(!t?.tournamentRecord&&!Array.isArray(t?.venueMatchUps))return{error:W};if(!t?.courtId)return{error:Ni};let{scheduleVisibilityFilters:e,tournamentRecord:r,matchUpFilters:n,venueMatchUps:o,courtId:i}=t,{schedulingProfile:s}=ko({tournamentRecord:r});if(Array.isArray(o))return{matchUps:u({matchUps:o,courtId:i})};let{matchUps:a}=le({scheduleVisibilityFilters:e,tournamentRecord:r,matchUpFilters:n});return{matchUps:u({matchUps:a,courtId:i})};function u({matchUps:p,courtId:m}){let d=p.filter(l=>{let f=l.schedule?.allocatedCourts?.map(({courtId:g})=>g);return l.schedule?.courtId===m||f?.includes(m)});return Hd({matchUps:d,schedulingProfile:s})}}function bx({scheduleVisibilityFilters:t,tournamentRecord:e,matchUpFilters:r,venueId:n}){if(!e)return{error:W};if(!n)return{error:Bo};let{schedulingProfile:o}=ko({tournamentRecord:e}),{matchUps:i}=le({scheduleVisibilityFilters:t,tournamentRecord:e,matchUpFilters:r});return{matchUps:a({matchUps:i,venueId:n})};function a({matchUps:c,venueId:u}){let p=c.filter(m=>{let d=m.schedule?.allocatedCourts?.map(({venueId:l})=>l);return m.schedule?.venueId===u||d?.includes(u)});return Hd({matchUps:p,schedulingProfile:o})}}function Zg({tournamentRecord:t,dateAvailability:e,disableNotice:r,venueMatchUps:n,courtId:o,force:i}){if(!t)return{error:W};if(!o)return{error:Ni};let s=FA({dateAvailability:e});if(s.error)return s;let{updatedDateAvailability:a,totalMergeCount:c}=c1(e);e=a;let u=ns({tournamentRecord:t,courtId:o});if(u.error)return u;let{court:p,venue:m}=u,{matchUps:d}=ul({tournamentRecord:t,venueMatchUps:n,courtId:o});if(d?.length){let l=Pt({tournamentRecord:t})?.appliedPolicies,f=i??l?.[go]?.allowDeletionWithScoresPresent?.courts,g=[];g.length&&(f||console.log("throw error: scheduled court matchUps",g.length))}return p&&(p.dateAvailability=e,!r&&m&&Tt({payload:{venue:m,tournamentId:t.tournamentId},topic:ui,key:m.venueId})),{...R,totalMergeCount:c}}function c1(t){let e=0,r=t.reduce((o,i)=>{let{date:s,startTime:a,endTime:c,bookings:u}=i;return o[s]||(o[s]=[]),o[s].push({startTime:a,endTime:c,bookings:u}),o},{}),n=[];return Object.keys(r).forEach(o=>{r[o].sort(Ix);let{mergedAvailability:i,mergeCount:s}=u1(r[o]);n.push(...i.map(a=>({date:o,...a}))),e+=s}),{updatedDateAvailability:n,totalMergeCount:e}}function u1(t){let e,r,n,o=t.length,i=0,s=[];for(;t.length&&o;){let c=t.shift(),{startTime:u,endTime:p,bookings:m}=c;if(o-=1,!e)e=u,n=m,r=p;else if(ca(we(r),we(u),!1)>0){let l={startTime:e,endTime:r};n?.length&&(l.bookings=n),s.push(l),e=u,n=m,r=p}else m&&(n?n.push(m):n=m),r=p,i+=1}let a={startTime:e,endTime:r};return n?.length&&(a.bookings=n),s.push(a),{mergedAvailability:s,mergeCount:i}}function pl({matchUpsCount:t=0}){let r=`Schedule would be deleted from ${t} ${t===1?"matchUp":"matchUps"}; use { force: true }`;return{error:nE,info:r}}function YA({tournamentRecord:t,drawDefinition:e,matchUpId:r,drawId:n}){let o="removeCourtAssignment";if(!r)return{error:ke};if(!e&&!n)return{error:Wr};let i;if(!e){if(!t)return{error:W};({drawDefinition:e}=We({tournamentRecord:t,drawId:n}))}if(e)({matchUp:i}=xt({drawDefinition:e,matchUpId:r}));else{if(!t)return{error:W};let s=le({tournamentRecord:t,inContext:!1}).matchUps??[];({matchUp:i}=iS({matchUps:s,matchUpId:r}))}return i?(i.timeItems&&i.timeItems.find(a=>[di,Eo].includes(a.itemType))&&(i.timeItems=i.timeItems.filter(({itemType:a})=>![di,Eo].includes(a)),It({tournamentId:t?.tournamentId,context:o,drawDefinition:e,matchUp:i})),{...R}):{error:Oe}}function qA(t){if(typeof t?.venueId!="string")return{error:Bo};let{tournamentRecord:e,venueId:r,force:n}=t,o=t.tournamentRecords||e&&{[e.tournamentId]:e}||{};if(!Object.keys(o).length)return{error:W};let s=cn({tournamentRecords:o,contextFilters:{venueIds:[r]}}).matchUps??[],a=Pt({tournamentRecord:e})?.appliedPolicies,c=n??a?.[go]?.allowDeletionWithScoresPresent?.venues;if(!s.length||c)for(let u of Object.values(o)){for(let m of s){let d=YA({matchUpId:m.matchUpId,drawId:m.drawId,tournamentRecord:u});if(d.error)return d}let p;u.venues=(u.venues??[]).filter(m=>m?.venueId!==r?!0:(p=!0,!1)),p&&Tt({payload:{venueId:r,tournamentId:u.tournamentId},topic:mf,key:r})}else return pl({matchUpsCount:s.length});return Nc({tournamentRecords:o}),{...R}}function sC({tournamentRecord:t,venueIds:e,force:r}){if(!t)return{error:W};if(!Array.isArray(e))return{error:G};for(let n of t.venues||[]){let{venueId:o}=n;if(e.includes(o)){let{venueId:i}=n,s=qA({tournamentRecord:t,venueId:i,force:r});if(s.error)return s}}return{...R}}function aC(t){let{courtIds:e,dates:r}=t,n=Xr(t),o=[{[ye]:!0,[Ju]:!0}],i=lt(t,o);if(i.error)return i;for(let s of Object.values(n))p1({tournamentRecord:s,courtIds:e,dates:r});return{...R}}function p1({tournamentRecord:t,courtIds:e,dates:r}){let n=Array.isArray(r)&&r.length?{dates:r}:!0,o=i=>St({extension:{value:n,name:Wn},creationTime:!1,element:i});for(let i of t.venues||[])for(let s of i.courts||[])if(e?.includes(s.courtId)){let a=o(s);if(a.error)return a}return{...R}}function cC(t){let{tournamentRecords:e,tournamentId:r,venueIds:n}=t,o=[{[ye]:!0,[Zu]:!0}],i=lt(t,o);if(i.error)return i;let s=Object.keys(e).filter(a=>!r||a===r);for(let a of s){let c=e[a];m1({tournamentRecord:c,venueIds:n})}return{...R}}function m1({tournamentRecord:t,venueIds:e}){for(let r of t.venues||[])if(e?.includes(r.venueId)){let n=St({creationTime:!1,element:r,extension:{name:Wn,value:!0}});if(n.error)return n}return{...R}}function uC(t){let e=Xr(t),r=[{[ye]:!0}];!t.enableAll&&r.push({[Ju]:!0});let n=lt(t,r);if(n.error)return n;let{enableAll:o,courtIds:i,dates:s}=t;for(let a of Object.values(e))d1({tournamentRecord:a,courtIds:i,enableAll:o,dates:s});return{...R}}function d1({tournamentRecord:t,courtIds:e,enableAll:r,dates:n}){for(let o of t.venues||[])for(let i of o.courts||[])if(r||e?.includes(i.courtId))if(Array.isArray(n)){let{extension:s}=mt({element:i,name:Wn});if(s){let a=s.value;Array.isArray(a.dates)&&(a.dates=a.dates.filter(c=>!n.includes(c))),St({extension:{name:Wn,value:a},creationTime:!1,element:i})}}else or({element:i,name:Wn});return{...R}}function pC(t){let e=Xr(t),r=[{[ye]:!0}];!t.enableAll&&r.push({[Zu]:!0});let n=lt(t,r);if(n.error)return n;let{venueIds:o,enableAll:i}=t;for(let s of Object.values(e))for(let a of s.venues||[])(i||o?.includes(a.venueId))&&or({element:a,name:Wn});return{...R}}function mC(t){let{courtId:e,disableNotice:r,force:n}=t,o=Xr(t),i=lt(t,[{[ye]:!0,[RI]:!0}]);if(i.error)return i;let s,a;for(let c of Object.values(o)){if(a=l1({tournamentRecord:c,disableNotice:r,courtId:e,force:n}),a.error&&a.error!==Ka)return a;a.success&&(s=!0)}return s?{...R}:a}function l1({tournamentRecord:t,disableNotice:e,courtId:r,force:n}){let o=ns({tournamentRecord:t,courtId:r});if(o.error)return o;let i=o.venue,{matchUps:s}=ul({tournamentRecord:t,courtId:r}),a=Pt({tournamentRecord:t})?.appliedPolicies,c=n??a?.[go]?.allowDeletionWithScoresPresent?.courts;if(!s?.length||c){for(let u of s??[]){let p=YA({matchUpId:u.matchUpId,drawId:u.drawId,tournamentRecord:t});if(p.error)return p}i&&(i.courts=(i.courts??[]).filter(u=>u.courtId!==r),e||Tt({payload:{venue:i,tournamentId:t.tournamentId},topic:ui,key:i.venueId}))}else return pl({matchUpsCount:s.length});return{...R}}function tI(t){let{disableNotice:e,modifications:r,courtId:n,force:o,venueMatchUps:i}=t,s=Xr(t);if(!Object.keys(s).length)return{error:Ft};let a,c;for(let u of Object.values(s)){let p=f1({tournamentRecord:u,disableNotice:e,venueMatchUps:i,modifications:r,courtId:n,force:o});if(p?.error)return p;a=!0}return a?{...R}:c}function f1({tournamentRecord:t,disableNotice:e,venueMatchUps:r,modifications:n,courtId:o,force:i}){if(!t)return{error:W};if(!o)return{error:Ni};if(!n||typeof n!="object")return{error:Xn};let s=ns({tournamentRecord:t,courtId:o});if(s.error)return s;let{venue:a,court:c}=s,u=Object.keys(gx()).filter(l=>l!=="courtId");if(!Object.keys(n).filter(l=>u.includes(l)).length)return{error:qu};let m=u.filter(l=>!["dateAvailability"].includes(l)),d=Object.keys(n).filter(l=>m.includes(l));if(c&&d.forEach(l=>Object.assign(c,{[l]:n[l]})),n.dateAvailability){let l=Zg({dateAvailability:n.dateAvailability,tournamentRecord:t,venueMatchUps:r,disableNotice:e,courtId:o,force:i});if(l.error)return l}return e||Tt({payload:{venue:a,tournamentId:t.tournamentId},topic:ui,key:a?.venueId}),{...R,court:J(c)}}var g1=()=>({venueId:void 0,venueName:"",venueAbbreviation:"",onlineResources:[],venueType:void 0,addresses:[],contacts:[],courts:[],roles:[]}),Ox=g1;function dC(t){let{modifications:e,venueId:r,force:n}=t,o=Xr(t);if(!Object.keys(o).length)return{error:Ft};if(typeof r!="string")return{error:Bo};let i,s;for(let a of Object.values(o)){let c=I1({tournamentRecord:a,modifications:e,venueId:r,force:n});if(c.success&&(s=!0),c.error&&(i=c.error),c.error&&c.error!==Ds)return c}return Nc({tournamentRecords:o}),s?{...R}:{error:i}}function I1({tournamentRecord:t,modifications:e,venueId:r,force:n}){if(!t)return{error:W};if(!e||typeof e!="object")return{error:Xn};if(!r)return{error:Bo};let o=Pt({tournamentRecord:t})?.appliedPolicies,i=n??o?.[go]?.allowDeletionWithScoresPresent?.venues,{matchUps:s}=bx({tournamentRecord:t,venueId:r}),a=Qo({tournamentRecord:t,venueId:r});if(a.error)return a;let c=a.venue,u=Object.keys(Ox()).filter(h=>h!=="venueId");if(!Object.keys(e).filter(h=>u.includes(h)).length)return{error:qu};let m=u.filter(h=>!["courts","onlineResources"].includes(h)),d=Object.keys(e).filter(h=>m.includes(h));c&&d.forEach(h=>Object.assign(c,{[h]:e[h]}));let l=c?.courts?.map(h=>h.courtId)??[],f=e.courts?.map(h=>h.courtId)||[],g=f.length?l.filter(h=>!f.includes(h)):e?.courts&&l,I=[];if(g?.length){let S=c?.courts?.filter(T=>g.includes(T.courtId))?.map(T=>{let A=ul({courtId:T.courtId,tournamentRecord:t,venueMatchUps:s});for(let D of A.matchUps??[])I.push({matchUpId:D.matchUpId,drawId:D.drawId});return A.matchUps?.length??0}).reduce((T,A)=>T+A);if(c&&(!S||i))c.courts=c.courts?.filter(T=>f.includes(T.courtId)),wu({schedule:{courtId:"",scheduledDate:""},matchUpDetails:I,removePriorValues:!0,tournamentRecord:t});else return pl({matchUpsCount:S})}if(e.courts)for(let h of e.courts){let{courtId:S}=h||{},T=tI({modifications:h,disableNotice:!0,tournamentRecord:t,venueMatchUps:s,courtId:S,force:n});if(T.error===Ka&&(T=il({disableNotice:!0,tournamentRecord:t,venueId:r,court:h})),T.error)return T}return Nc({tournamentRecord:t}),c&&Tt({payload:{venue:c,tournamentId:t.tournamentId},topic:ui,key:c?.venueId}),{...R,venue:J(c)}}var gC={};Jt(gC,{JSON2CSV:()=>xx,UUID:()=>Mt,UUIDS:()=>WR,allNumeric:()=>UI,attributeFilter:()=>bi,chunkArray:()=>Te,chunkByNth:()=>Gl,chunkSizeProfile:()=>uE,constantToString:()=>Ye,countValues:()=>BC,createMap:()=>sI,dateTime:()=>dR,definedAttributes:()=>rt,dehydrateMatchUps:()=>vx,extractAttributes:()=>qE,flattenJSON:()=>KA,generateDateRange:()=>bs,generateHashCode:()=>bC,generateRange:()=>Z,generateTimeCode:()=>kA,groupValues:()=>aE,hasAttributeValues:()=>RC,instanceCount:()=>dr,intersection:()=>jt,isConvertableInteger:()=>ft,isNumeric:()=>te,isOdd:()=>yI,isPowerOf2:()=>Tn,makeDeepCopy:()=>J,matchUpSort:()=>hi,nearestPowerOf2:()=>cm,nextPowerOf2:()=>qi,noNulls:()=>VC,noNumeric:()=>PI,numericSort:()=>se,occurrences:()=>HC,overlap:()=>xe,randomMember:()=>on,randomPop:()=>xr,shuffleArray:()=>cr,structureSort:()=>ci,subSort:()=>WC,undefinedToNull:()=>iI,unique:()=>pt,visualizeScheduledMatchUps:()=>_x});function _x({scheduledMatchUps:t,showGlobalLog:e}){lb();let r=t?.reduce((o,{structureId:i})=>o.includes(i)?o:o.concat(i),[]),n=Array.isArray(r)&&{...r.map(o=>{let{structureName:i,matchUpType:s}=t.find(a=>a.structureId===o);return{[o]:`${i} ${s}`}})};r?.forEach(o=>{kn({color:"blue",method:"draw",structure:n[o],keyColors:{structure:"magenta"}},!0);let i=t.filter(a=>a.structureId===o),s=He({matchUps:i})?.roundMatchUps||[];Object.keys(s).forEach(a=>{kn({roundNumber:a,keyColors:{roundNumber:"brightcyan"}},!0),s[a].forEach(({matchUpId:c,schedule:u})=>{let p=$t(u.scheduledTime);kn({matchUpId:c,time:p,date:u.scheduledDate,venue:u.venueId,keyColors:{time:"brightcyan",date:"brightcyan",matchUpId:"yellow",venue:"magenta"}},!0)})})}),e&&db()}function vx({tournamentRecord:t}){if(!t)return{error:W};if(typeof t!="object"||!t.tournamentId)return{error:G};let{matchUps:e}=le({tournamentRecord:t,inContext:!1});if(e?.length){let r=h1({tournamentRecord:t});T1(e,r)}return{...R}}function h1({tournamentRecord:t}){let e={};for(let r of t.events||[]){r.matchUpFormat&&(e[r.eventId]=r.matchUpFormat);for(let n of r.drawDefinitions||[]){n.matchUpFormat&&(e[n.drawId]=n.matchUpFormat);for(let o of n.structures||[]){o.matchUpFormat&&(e[o.structureId]=o.matchUpFormat);for(let i of o.structures||[])i.matchUpFormat&&(e[i.structureId]=i.matchUpFormat)}}}return e}var S1=["collectionId","collectionPosition","drawPositions","extensions","finishingPositionRange","finishingRound","isMock","matchUpId","matchUpStatus","matchUpStatusCodes","orderOfFinish","processCodes","roundNumber","tieFormat","tieMatchUps","roundPosition","score","sides","winnerMatchUpId","loserMatchUpId","matchUpDuration","winningSide"];function T1(t,e={}){for(let r of t){let{structureId:n,drawId:o,eventId:i}=r,s=e[n]||e[o]||e[i],a=r.matchUpFormat===s?void 0:r.matchUpFormat;for(let c of Object.keys(r))S1.includes(c)||delete r[c];r.sides&&r.drawPositions&&!r.tieMatchUps&&delete r.sides,a&&(r.matchUpFormat=a)}}function xx(t,e){if(e&&typeof e!="object")return{error:G};let{columnTransform:r={}}=e||{},{includeTransformAccessors:n,includeHeaderRow:o=!0,returnTransformedJSON:i,removeEmptyColumns:s,onlyHeaderRow:a,columnAccessors:c=[],functionMap:u={},columnMap:p={},valuesMap:m={},context:d={},delimiter:l='"',columnJoiner:f=",",rowJoiner:g=`\r
|
|
24
|
-
`,keyJoiner:I="."}=e||{};if(!Array.isArray(t)||!Array.isArray(c)||typeof d!="object"||typeof p!="object"||typeof r!="object"||typeof u!="object"||typeof m!="object"||typeof f!="string"||typeof g!="string"||typeof I!="string"||typeof l!="string")return{error:G};r=Object.assign({},...Object.keys(r).reverse().map(b=>({[b]:Array.isArray(r[b])?r[b]:[typeof r[b]=="string"&&r[b]].filter(Boolean)})));let h=t.filter(Boolean).map(b=>KA(b,I)),S=Object.values(r).flat();n&&c.push(...S);let T=h.reduce((b,x)=>Object.keys(x).every(w=>!b.includes(w)&&b.push(w)||!0)&&b,[]).filter(b=>!c?.length||c.includes(b)),A=Object.assign({},...Object.keys(r).reverse().map(b=>r[b].map(x=>({[x]:b})).flat()).flat()),D=(b,x)=>e?.sortOrder?e.sortOrder.includes(b)&&e.sortOrder.includes(x)&&e.sortOrder.indexOf(b)-e.sortOrder.indexOf(x)||!e.sortOrder.includes(x)&&-1:0,y=T.reduce((b,x)=>{let w=A[x];return w?b.includes(w)||b.push(w):b.push(x),b},[]).sort(D);Object.keys(p).forEach(b=>!y.includes(b)&&y.unshift(b)),Object.keys(r).forEach(b=>!y.includes(b)&&y.unshift(b)),typeof d=="object"&&Object.keys(d).forEach(b=>!y.includes(b)&&y.unshift(b));let E=y.map(b=>p[b]||b);if(a)return[E];let U=b=>`${l}${b}${l}`,M=[],P=b=>Object.values(y.reduce((x,w,F)=>{let L=r[w],v=(L?.length?b[L.find(j=>b[j])]:b[w])||d?.[w]||"",B=m[w]?.[v]||v,H=Mr(u[w])?u[w](B):B;return x[w]=U(H),H&&(M[F]=(M[F]||0)+1),x},{})),N=h.map(P),C=s&&[...M].map((b,x)=>!b&&x).filter(te).reverse();if(C){let b=x=>x.filter((w,F)=>!C.includes(F));N=N.map(b),E=b(E)}let O=N.map(b=>b.join(f));return i?O.map(b=>{let x=b.split(f);return Object.assign({},...x.map((w,F)=>({[E[F]]:w})))}):o?[E.map(U).join(f),...O].join(g):O.join(g)}function KA(t,e=".",r=[]){return typeof t=="object"&&Object.keys(t).reduce((n,o)=>typeof t[o]!="object"?(n[r.concat(o).join(e)]=t[o],n):Object.assign(n,KA(t[o],e,r.concat(o))),{})}var A1={};var{FACTORY:wx}=HI;function Lx({tournamentRecord:t,value:e}){let{extension:r}=mt({element:t,name:wx}),n={name:wx,value:{...r?.value,...e}};St({element:t,extension:n})}function Fu({timeStamp:t}){let e=Mo(),r=Bl();return r&&Object.values(e).forEach(n=>{Lx({tournamentRecord:n,value:{version:Va(),timeStamp:t}})}),r}function zA({engineType:t,methodName:e,elapsed:r,params:n,result:o}){let i=yr();if(typeof i!="object")return;let s={method:e},a=o?.error&&(i.errors===!0||Array.isArray(i.errors)&&i.errors.includes(e)),c=Array.isArray(i.params)&&i.params?.includes(e),u=i.params&&!Array.isArray(i.params)||c,p=Array.isArray(i.exclude)&&i.exclude.includes(e);!p&&![void 0,!1].includes(i.perf)&&!isNaN(i.perf)&&r>=i.perf&&(s.elapsed=r),!p&&(a||u)&&(s.params=n),!p&&(a||i.result&&!Array.isArray(i.result)&&(!Array.isArray(i.params)||c)||Array.isArray(i.result)&&i.result?.includes(e))&&(s.result=o),Object.keys(s).length>1&&fE(s,t)}function Ga({methodName:t,params:e,start:r}){let n={error:za,methodName:t},o=r?Date.now()-r:0;return zA({result:n,methodName:t,elapsed:o,params:e,engineType:"sync"}),n}function Fx(t,e){if(e._middleware===!1)return e;if(e.tournamentId&&!t[e.tournamentId])return{error:W};let r=e.drawId||e.matchUp?.drawId;if(r){let{event:i,drawDefinition:s,tournamentId:a}=We({tournamentRecords:t,drawId:r});s&&(e.drawDefinition=s),a&&(e.tournamentId=a),i&&(e.event=i)}if(e.eventId&&!e.event){let{event:i,tournamentId:s}=We({eventId:e.eventId,tournamentRecords:t});if(!i)return{error:mr};e.tournamentId=s,e.event=i}let n=e.tournamentId??$i();if(!n&&e)return e;let o=t[n];return n&&!o?{error:W}:(o&&(e.tournamentRecord=o),e)}function ka(t,e,r,n,o){delete t.success,delete t.error;let i=Date.now(),s=$i();r&&(r.activeTournamentId=s);let a=r?.tournamentRecord||Wl(s),c=typeof r?.tournamentRecord=="object"&&{[r?.tournamentRecord.tournamentId]:r.tournamentRecord}||Mo(),u=r?J(r,void 0,!0):void 0,p=r?Fx(c,r):void 0;if(p?.error)return p;let m=y1({params:p,tournamentRecords:c,tournamentRecord:a,methodName:n,method:e}),d=Date.now()-i;return zA({result:m,methodName:n,elapsed:d,params:u,engineType:o}),m}function y1({tournamentRecords:t,tournamentRecord:e,params:r,methodName:n,method:o}){if(yr())return o({tournamentRecords:t,tournamentRecord:e,...r});try{return o({tournamentRecords:t,tournamentRecord:e,...r})}catch(i){return Xu({engineName:"engine",methodName:n,params:r,err:i})}}function Gu(t){let{mutationStatus:e,tournamentId:r,directives:n,timeStamp:o}=t||{},{topics:i}=Cr();for(let s of[...i].sort(kx)){let a=DI({topic:s});a?.length&&um({topic:s,notices:a})}e&&o&&i.includes(_m)&&um({notices:[{tournamentId:r,directives:n,timeStamp:o}],topic:_m})}async function QA(t){let{mutationStatus:e,tournamentId:r,directives:n,timeStamp:o}=t||{},{topics:i}=Cr();for(let s of[...i].sort(kx)){let a=DI({topic:s});a&&await um({topic:s,notices:a})}e&&o&&i.includes(_m)&&um({notices:[{tournamentId:r,directives:n,timeStamp:o}],topic:_m})}var Gx={[Tf]:5,[Sf]:5,[Af]:5,[hf]:5,[If]:5,[ff]:5,[VE]:5,[BE]:5,[gf]:1,[up]:1,[Qe]:5,[ui]:5,[lf]:4,[pf]:4,[mf]:4,[df]:4,[cp]:3,[cf]:2};function kx(t,e){return(Gx[e]||0)-(Gx[t]||0)}function Vx({convertExtensions:t,removeExtensions:e}){let r=Mo();return{tournamentId:$i(),tournamentRecords:J(r,t,!1,e)}}function Bx(t){let{convertExtensions:e=!1,removeExtensions:r=!1}=t??{},n=t?.tournamentId??$i();if(typeof n!="string")return{};let o=Wl(n);return{tournamentRecord:J(o,e,!1,r)}}function Hx(){let t=Mo(),{extension:e}=mt({name:pa,tournamentRecords:t,discover:!0}),r=e?.value?.tournamentIds||[];return Object.keys(t).forEach(n=>{r.includes(n)||delete t[n]}),pm(t)}function IC(t,e=!0){return typeof t!="object"||Array.isArray(t)?{error:Xn}:t?.tournamentId?dE(e?J(t):t):{error:G}}function Ts(t,e=!0){if(typeof t!="object")return{error:Xn};if(Qu(),Array.isArray(t)){if(!(t.filter(n=>n?.tournamentId).length===t.length))return{error:cI};t=Object.assign({},...t.map(n=>({[n.tournamentId]:n})))}else if(t?.tournamentId)t={[t.tournamentId]:t},Qu(t.tournamentId);else if(!Object.keys(t).every(n=>t[n].tournamentId===n))return{error:cI};return pm(e?J(t):t)}async function Wx(t,e,r){if(!Array.isArray(e))return{error:G,message:"directives must be an array"};let n=Hl(),o=Date.now(),i=r&&J(Mo(),!1,!0),s=[];for(let p of e){if(typeof p!="object")return{error:G,message:"directive must be an object"};let{method:m,pipe:d}=p,l=p.params?{...p.params}:{};if(!n[m])return Ga({methodName:m,start:o,params:l});if(d){let g=s[s.length-1],I=Object.keys(d);for(let h of I)g[h]&&(l[h]=g[h])}let f=ka(t,n[m],l,m,"async");if(f?.error)return i&&Ts(i),{...f,rolledBack:!!i};s.push({...f,methodName:m})}let a=Date.now(),c=Fu({timeStamp:a});return QA({directives:e,mutationStatus:c,timeStamp:a}),Ci(),{success:s.every(p=>p.success),results:s}}async function hC(t,e){if(!Rt(e))return{error:G,message:"args must be an object"};let r=Object.values(e).filter(Mr).length;if(r>1)return{message:"there must be only one arg with typeof function",error:G};let n=r?Object.keys(e).find(l=>Mr(e[l])):$e(e.method)&&e.method;if(!n)return{error:za};let{[n]:o,...i}=e,s=e?.params?{...e.params}:{...i},a=s.rollbackOnError&&J(Mo(),!1,!0),c=o||t[n]||zu()[n];if(!c)return Ga({methodName:n,params:s});let u=await ka(t,c,s,n,"async")??{};u?.error&&a&&Ts(a);let p=Date.now(),m=Fu({timeStamp:p}),d=u?.success&&s?.delayNotify!==!0&&s?.doNotNotify!==!0;return d&&await QA({directives:[{method:c,params:s}],mutationStatus:m,timeStamp:p}),(d||!u?.success||s?.doNotNotify)&&Ci(),u}function jx(t,e,r,n,o,i){let s=gE(r,n,o,i);if(s.error)return s;let a=s.methods??[];return Object.keys(a).filter(u=>Mr(a[u])).forEach(u=>{t[u]=p=>{let m=()=>e(t,{[u]:a[u],...p});if(yr())return m();try{return m()}catch(d){Xu({engineName:"engine",methodName:u,params:p,err:d})}}}),{...R,...t}}function tm(t,e){return e?.error?(t.error=e.error,t.success=!1):(t.error=void 0,t.success=!0),t}function ml(t,e){t.importMethods=(r,n,o,i)=>jx(t,e,r,n,o,i),t.getTournament=r=>Bx(r),t.getState=r=>Vx({convertExtensions:r?.convertExtensions,removeExtensions:r?.removeExtensions}),t.version=()=>Va(),t.reset=()=>(pm({}),tm(t)),t.devContext=r=>(kc(r),tm(t)),t.getDevContext=r=>yr(r),t.newTournamentRecord=(r={})=>{let n=AA(r),o=n.tournamentId;return n.error?n:(IC(n),Qu(o),{...R,tournamentId:o})},t.setState=(r,n,o)=>{Vc(n,o);let i=Ts(r,n);return tm(t,i)},t.setTournamentId=r=>Qu(r),t.getTournamentId=()=>$i(),t.setTournamentRecord=(r,n,o)=>{Vc(n,o);let i=IC(r,n);return tm(t,i)},t.removeTournamentRecord=r=>{let n=lE(r);return tm(t,n)},t.removeUnlinkedTournamentRecords=()=>{let r=Hx();return tm(t,r)}}function E1(t){let e=pE();if(e.error&&!t)return e;let r={executionQueue:(n,o)=>Wx(r,n,o),execute:n=>hC(r,n)};return ml(r,hC),r}function Yx(t,e,r){if(!Array.isArray(e))return{error:G,message:"directives must be an array"};let n=Hl(),o=Date.now(),i=r&&J(Mo(),!1,!0),s=[];for(let p of e){if(typeof p!="object")return{error:G,message:"directive must be an object"};if(p.params&&typeof p.params!="object")return{error:G,message:"params must be an object"};let{method:m,pipe:d}=p,l=p.params?{...p.params}:{};if(!n[m])return Ga({methodName:m,start:o,params:l});if(d){let g=s[s.length-1],I=Object.keys(d);for(let h of I)g[h]&&(l[h]=g[h])}let f=ka(t,n[m],l,m,"sync");if(f?.error)return i&&Ts(i),{...f,rolledBack:!!i};s.push({...f,methodName:m})}let a=Date.now(),c=Fu({timeStamp:a});return Gu({directives:e,mutationStatus:c,timeStamp:a}),Ci(),{success:s.every(p=>p.success),results:s}}function SC(t,e){if(!Rt(e))return{error:G,message:"args must be an object"};let r=Object.values(e).filter(Mr).length;if(r>1)return{message:"there must be only one arg with typeof function",error:G};let n=r?Object.keys(e).find(l=>Mr(e[l])):$e(e.method)&&e.method;if(!n)return{error:za};let{[n]:o,...i}=e,s=e?.params?{...e.params}:{...i},a=s.rollbackOnError&&J(Mo(),!1,!0),c=o||t[n]||zu()[n];if(!c)return Ga({methodName:n,params:s});let u=ka(t,c,s,n,"sync")??{};u?.error&&a&&Ts(a);let p=Date.now(),m=Fu({timeStamp:p}),d=u?.success&&s?.delayNotify!==!0&&s?.doNotNotify!==!0;return d&&Gu({directives:[{method:c,params:s}],mutationStatus:m,timeStamp:p}),(d||!u?.success||s?.doNotNotify)&&Ci(),u}var qx=(()=>{let t={executionQueue:(e,r)=>Yx(t,e,r),execute:e=>SC(t,e)};return ml(t,SC),t})(),em=qx;function TC(t,e){if(!Rt(e))return{error:G,message:"args must be an object"};let r=Object.values(e).filter(Mr).length;if(r>1)return{message:"there must be only one arg with typeof function",error:G};let n=r?Object.keys(e).find(c=>Mr(e[c])):$e(e.method)&&e.method;if(!n)return{error:za};let{[n]:o,...i}=e,s=e?.params?{...e.params}:{...i},a=o||t[n]||zu()[n];return a?ka(t,a,s,n,"ask"):Ga({methodName:n,params:s})}var U1=(()=>{let t={execute:e=>TC(t,e)};return ml(t,TC),t})();var rm={},xc;function AC(t,e=!0){if(!t)return{error:et};if(typeof t!="object")return{error:Xn};if(t.matchUpId)xc=t.matchUpId,rm[xc]=e?J(t):t;else if(Array.isArray(t))for(let r of t.reverse())r.matchUpId&&(rm[r.matchUpId]=e?J(r):r,xc||(xc=r.matchUpId));else for(let r of Object.values(t))r.matchUpId&&(rm[r.matchUpId]=e?J(r):r,xc||(xc=r.matchUpId));return e?J(t):t}function $x(){return rm[xc]}function Kx(){return Object.values(rm)}function zx(){xc=void 0,rm={}}function Qx(t){return J(rm[xc],t?.convertExtensions,!1,t?.removeExtensions)}var P1=(()=>{let t={getState:o=>Qx(o),version:()=>Va(),reset:()=>(zx(),{...R}),drawId:void 0,error:void 0,success:!1,devContext:o=>(kc(o),t),setState:(o,i,s)=>{Vc(i,s);let a=AC(o);return e(a)}};function e(o){return o?.error?(t.error=o.error,t.success=!1):(t.error=void 0,t.success=!0,t.drawId=o.drawId),t}return r([yg]),t;function r(o){o.forEach(i=>{Object.keys(i).forEach(s=>{t[s]=a=>{if(yr())return n({params:a,governor:i,methodName:s});try{return n({params:a,governor:i,methodName:s})}catch(c){Xu({engineName:"matchUpEngine",methodName:s,params:a,err:c})}}})})}function n({params:o,governor:i,methodName:s}){t.error=void 0,t.success=!1;let a=o?.matchUp||$x(),c=o?.matchUps||Kx(),u=o?.rollbackOnError&&J(a,!1,!0);o={...o,matchUpId:a?.matchUpId,matchUps:c,matchUp:a};let p=i[s](o);if(p?.error)return u&&AC(u),{...p,rolledBack:!!u};let m=p?.success&&o?.delayNotify!==!0&&o?.doNotNotify!==!0;return m&&Gu(),(m||!p?.success||o?.doNotNotify)&&Ci(),p}})();var yC=!1,D1=(()=>{let t={version:()=>Va(),setDeepCopy:(n,o)=>(Vc(n,o),t),devContext:n=>(kc(n),yC=!0,t)};return r([$g]),t;function e(n,o){let i=n({...o});return i?.error||Gu(),Ci(),yC&&(kc(!1),yC=!1),i}function r(n){n.forEach(o=>{Object.keys(o).forEach(i=>{t[i]=s=>{try{let a=e(o[i],s);return!a?.error&&s?.setState&&a?.tournamentRecord&&Ts(a.tournamentRecord),a}catch(a){let c;typeof a=="string"?c=a.toUpperCase():a instanceof Error&&(c=a.message),console.log("ERROR",{params:JSON.stringify(s),method:i,error:c})}}})})}})();em.importMethods($A,!0,1);var N1=em,M1=em;function XA(t,e){return t&&e&&Array.isArray(e)&&e[t-1]||typeof e=="object"&&e[t]}function Xx(t){let{participation:e={},awardProfiles:r,startDate:n,eventType:o,drawSize:i,drawType:s,category:a,endDate:c,level:u}=t,{participationOrder:p,flightNumber:m,rankingStage:d}=e,l=g=>!n&&!c||!g.dateRanges?!0:g.dateRanges.some(I=>{let h=!n||!I.startDate||new Date(n)>new Date(I.startDate),S=!c||!I.endDate||new Date(c)<=new Date(I.endDate);return h&&S});return{awardProfile:r.find(g=>l(g)&&(!g.maxFlightNumber||m<=g.maxFlightNumber)&&(!g.drawTypes?.length||g.drawTypes?.includes(s))&&(!g.drawSizes?.length||g.drawSizes.includes(i))&&(!g.stages?.length||g.stages.includes(d))&&(!g.levels?.length||g.levels.includes(u))&&(!g.maxDrawSize||i<=g.maxDrawSize)&&(!g.drawSize||g.drawSize===i)&&(!g.maxLevel||u<=g.maxLevel)&&(!m||!g.flights?.flightNumbers?.length||g.flights.flightNumbers.includes(m))&&(!g.participationOrder||g.participationOrder===p)&&(!g.category?.ageCategoryCodes||g.category.ageCategoryCodes.includes(a?.ageCategoryCode))&&(!g.eventTypes?.length||g.eventTypes?.includes(o)))}}function EC({participantWon:t,flightNumber:e,valueObj:r,drawSize:n,flights:o,level:i}){let s=(f,g)=>{if(f){if(Array.isArray(g)){let I=g.find(h=>h.flight===f||h.f===f);return I.value||I.v}if(typeof g=="object"){let I=g.flights||g.f;if(Array.isArray(I))return I[f-1]}}},a=(f,g)=>{let I=f?.value||f?.v||(ft(f)?f:0),h=XA(i,f?.level);return{value:s(g,h)||ft(h)&&h||I}},c=0,u,p,m,d,l=t&&"won"||t===!1&&"lost"||void 0;if(Array.isArray(r)){let f=r.find(h=>h.drawSize===n||h.drawSizes?.includes(n)),g=r.find(h=>h.drawSize&&h.threshold&&n>h.drawSize),I=r.find(h=>!h.drawSize&&!h.drawSizes?.length);l!==void 0&&(f=f?.[l],g=g?.[l],I=I?.[l]),p=a(f,e).value,m=a(g,e).value,d=a(I,e).value,c=p||m||d,u=p&&f.requireWin||m&&g.requireWin||I?.requireWin}else if(typeof r=="object"){let f=r?.drawSizes?.[n],g=r;l!==void 0&&(f=f?.[l],g=g?.[l]),p=a(f,e).value,d=a(g,e).value,c=p||d,u=p?f.requireWin:g?.requireWin}else ft(r)&&l===void 0&&(c=r);return e&&o?.pct?.[e]&&(c=Math.round(c*o.pct[e])),{awardPoints:c,requireWin:u}}function Jx({participantFilters:t,policyDefinitions:e,tournamentRecord:r,level:n}){if(!r)return{error:W};let{policyDefinitions:o}=yo({policyTypes:[Zl],tournamentRecord:r}),i=e?.[Zl]??o?.[Zl];if(!i)return{error:Bu};let s=i.awardProfiles,a=i.requireWinFirstRound,c=i.requireWinForPoints,{participants:u,derivedEventInfo:p,derivedDrawInfo:m,mappedMatchUps:d}=Yt({withRankingProfile:!0,participantFilters:t,tournamentRecord:r}),l=u?.filter(h=>h.draws?.length),f={},g={},I={};for(let h of l??[]){let{participantType:S,participantId:T,person:A,draws:D}=h;for(let y of D){let{drawId:E,structureParticipation:U,eventId:M}=y,P=p[M],N=m[E],C=N?.drawType,{category:O,eventType:b}=P||{},x=y.startDate||P.startDate||r.startDate,w=y.endDate||P.endDate||r.endDate;if(b===kr&&T!==Jr)continue;let F;if(s){let L=c,v=0,B=0,H=0,j;for(let V of U){let{finishingPositionRange:Y,participationOrder:$,participantWon:k,flightNumber:K,rankingStage:z,winCount:q}=V;v+=q||0;let nt=N?.drawSize,{awardProfile:Q}=Xx({awardProfiles:s,participation:V,eventType:b,startDate:x,category:O,drawSize:nt,drawType:C,endDate:w,level:n});if(Q){if(!nt)continue;let it=Array.isArray(Y)&&Math.max(...Y),ot=pt(Y||[]).join("-"),ut=it&&z!==at&&Y?.includes(nt);Q.requireWinForPoints!==void 0&&(L=Q.requireWinForPoints),Q.requireWinFirstRound!==void 0&&(a=Q.requireWinFirstRound);let{finishingPositionPoints:Qt={},finishingPositionRanges:yt,finishingRound:Me,pointsPerWin:Ee,flights:Ce}=Q,Kt=Array.isArray(Q.perWinPoints)?Q.perWinPoints?.find(vt=>vt.participationOrders?.includes($)):Q.perWinPoints,Re=Qt.participationOrders,wt=0,Ue;if((!Re||Re.includes($))&&yt&&it){let vt=yt[it];vt&&({awardPoints:wt,requireWin:Ue}=EC({flightNumber:K,valueObj:vt,drawSize:nt,flights:Ce,level:n}))}if(!wt&&Me&&$===1&&it){let vt=Me[it];vt&&({awardPoints:wt,requireWin:Ue}=EC({participantWon:k,flightNumber:K,valueObj:vt,drawSize:nt,flights:Ce,level:n}))}if(ut&&a!==void 0&&(L=a),Ue!==void 0&&(L=Ue),wt>B&&(!L||q)&&(B=wt,j=it),!wt&&Ee&&q&&(H+=q*Ee,j=ot),!wt&&q&&Kt){let vt=XA(n,Kt?.level);vt?H+=q*vt:Kt.value&&(H+=q*Kt.value)}}if(F=B+H,S===Jr){let it=(h.matchUps||[]).filter(({structureId:ot})=>ot===V.structureId);for(let{matchUpId:ot}of it){let ut=d[ot],Qt=ut.sides.find(yt=>yt.participantId===T).sideNumber;if(ut.winningSice===Qt)for(let yt of ut.tieMatchUps)yt.winningSide}}}if(H||B){let V={winCount:v,positionPoints:B,rangeAccessor:j,perWinPoints:H,eventType:b,drawId:E,points:F},Y=A?.personId;Y?(f[Y]||(f[Y]=[]),f[Y].push(V)):S===dt?(I[T]||(I[T]=[]),I[T].push(V)):S===Jr&&(g[T]||(g[T]=[]),g[T].push(V))}}}}return{participantsWithOutcomes:l,personPoints:f,pairPoints:I,teamPoints:g,...R}}var C1={getTournamentPoints:Jx},Zx=C1;var R1={calculateNewRatings:xS,generateDynamicRatings:wS},tw=R1;var b1={...Zx,...tw};em.importMethods(b1);var O1=em;var ew={[Wc]:{roundsToSeparate:void 0,policyName:"Nationality Code",policyAttributes:[{key:"person.nationalityCode"},{key:"individualParticipants.person.nationalityCode"}]}};var rw={[no]:{policyName:"positionActionsUnrestricted",enabledStructures:[],otherFlightEntries:!0,disableRoundRestrictions:!0,activePositionOverrides:[js,Mp]}};var nw={[no]:{policyName:"positionActionsNoMovement",enabledStructures:[{stages:[],stageSequences:[],enabledActions:[js,Uu,Ys],disabledActions:[]}]}};var ow={[no]:{policyName:"positionActionsDisabled",enabledStructures:!1}};var iw={[Os]:{policyName:"Participant Privacy Policy",participant:{contacts:!1,individualParticipants:{onlineResources:!1,participantName:!0,participantOtherName:!0,participantId:!0,participantRole:!0,participantStatus:!0,penalties:!1,representing:!0,participantRoleResponsibilities:!1,participantType:!0,person:{addresses:!1,biographicalInformation:!1,birthDate:!1,contacts:!1,nationalityCode:!0,nativeFamilyName:!1,nativeGivenName:!1,onlineResources:!1,otherNames:!0,parentOrganisationId:!1,passportFamilyName:!1,passportGivenName:!1,personId:!1,personOtherIds:!1,previousNames:!1,sex:!1,standardFamilyName:!0,standardGivenName:!0,status:!1,tennisId:!1,wheelchair:!0}},individualParticipantIds:!0,onlineResources:!1,participantName:!0,participantOtherName:!0,participantId:!0,participantRole:!0,participantStatus:!0,penalties:!1,representing:!0,participantRoleResponsibilities:!1,participantType:!0,person:{addresses:!1,biographicalInformation:!1,birthDate:!1,contacts:!1,nationalityCode:!0,nativeFamilyName:!1,nativeGivenName:!1,onlineResources:!1,otherNames:!0,parentOrganisationId:!1,passportFamilyName:!1,passportGivenName:!1,personId:!1,personOtherIds:!1,previousNames:!1,sex:!1,standardFamilyName:!0,standardGivenName:!0,status:!1,tennisId:!1,wheelchair:!0}}}};var sw={[vn]:{defaultMatchUpFormat:un,allowDeletionWithScoresPresent:{drawDefinitions:!1,structures:!1},requireAllPositionsAssigned:!1,processCodes:{incompleteAssignmentsOnDefault:["RANKING.IGNORE"]},stage:{[tt]:{stageSequence:{1:{requireAllPositionsAssigned:!0}}}}}};var aw={[vn]:{requireAllPositionsAssigned:!1,stage:{[tt]:{stageSequence:{1:{requireAllPositionsAssigned:!0}}}},defaultMatchUpFormat:un,matchUpFormats:[{description:"Best of 3 tiebreak sets",matchUpFormat:un,categoryNames:[],categoryTypes:[]},{description:"Two tiebreak sets, 7-point match tiebreak at one set all",matchUpFormat:"SET3-S:6/TB7-F:TB7"},{description:"Two tiebreak sets, 10-point match tiebreak at one set all",matchUpFormat:"SET3-S:6/TB7-F:TB10"},{description:"One standard tiebreak set to 6, 7-point tiebreak at 6 games all",matchUpFormat:"SET1-S:6/TB7"},{description:"Best of 3 sets to 4",matchUpFormat:"SET3-S:4/TB7"},{description:"Two out of three short sets to 4 with 5-point tiebreak at 3 games all",matchUpFormat:"SET3-S:4/TB5@3"},{description:"One short set to 4, 7-point tiebreak at 4 games all",matchUpFormat:"SET1-S:4/TB7"},{description:"One short set to 4, 5-point tiebreak at 3 games all",matchUpFormat:"SET1-S:4/TB5@3"},{description:"Two short sets to 4, 10-point match tiebreak at one set all",matchUpFormat:"SET3-S:4/TB7-F:TB10"},{description:"Two short sets to 4, 7-point match tiebreak at one set all",matchUpFormat:"SET3-S:4/TB7-F:TB7"},{description:"One no advantage set to 5, tiebreak to 9 at 4-4",matchUpFormat:"SET1-S:5/TB9@4"},{description:"One set to 6 with deciding game at 5 games all",matchUpFormat:"SET1-S:6NOAD"},{description:"One short set to 4, deciding game is played at 3 games all",matchUpFormat:"SET1-S:4NOAD"},{description:"Two short sets to 4 with deciding game at 3-3, 7-point match tiebreak at one set all",matchUpFormat:"SET3-S:4NOAD-F:TB7"},{description:"8 game pro-set with 7 point tiebreak at 8 games all",matchUpFormat:"SET1-S:8/TB7"},{description:"8 game pro-set with 7 point tiebreak at 7 games all",matchUpFormat:"SET1-S:8/TB7@7"},{description:"Best of 3 10-point tiebreak games",matchUpFormat:"SET3-S:TB10"},{description:"One 10-point tiebreak game",matchUpFormat:"SET1-S:TB10"},{description:"Timed 20 minute game - game based",matchUpFormat:"SET1-S:T20"}]}};var cw={[Un]:{seedingProfile:{positioning:zc},validSeedPositions:{ignore:!0},duplicateSeedNumbers:!0,drawSizeProgression:!0,policyName:"ITF SEEDING",seedsCountThresholds:[{drawSize:4,minimumParticipantCount:3,seedsCount:2},{drawSize:16,minimumParticipantCount:12,seedsCount:4},{drawSize:32,minimumParticipantCount:24,seedsCount:8},{drawSize:64,minimumParticipantCount:48,seedsCount:16},{drawSize:128,minimumParticipantCount:97,seedsCount:32},{drawSize:256,minimumParticipantCount:192,seedsCount:64}]}};var uw={POLICY_AVOIDANCE_COUNTRY:ew,POLICY_POSITION_ACTIONS_DEFAULT:hS,POLICY_POSITION_ACTIONS_DISABLED:ow,POLICY_POSITION_ACTIONS_NO_MOVEMENT:nw,POLICY_POSITION_ACTIONS_UNRESTRICTED:rw,POLICY_PRIVACY_DEFAULT:iw,POLICY_ROUND_NAMING_DEFAULT:wf,POLICY_SCHEDULING_DEFAULT:$D,POLICY_SCORING_DEFAULT:sw,POLICY_SCORING_USTA:aw,POLICY_SEEDING_ITF:cw,POLICY_SEEDING_DEFAULT:_D};var _1={ratingsParameters:Br,matchUpFormats:uO,countryToFlag:aU,tieFormats:tA,countries:Xo,policies:uw,flagIOC:ub};var lw={};Jt(lw,{activeMatchUpStatuses:()=>Nm,auditConstants:()=>Iv,completedMatchUpStatuses:()=>ae,directingMatchUpStatuses:()=>YI,drawDefinitionConstants:()=>kE,entryStatusConstants:()=>DR,errorConditionConstants:()=>LC,eventConstants:()=>kR,extensionConstants:()=>HI,flightConstants:()=>Pv,genderConstants:()=>Km,keyValueConstants:()=>l_,matchUpActionConstants:()=>kO,matchUpStatusConstants:()=>KI,matchUpTypes:()=>UR,nonDirectingMatchUpStatuses:()=>qI,particicipantsRequiredMatchUpStatuses:()=>WI,participantConstants:()=>PR,participantRoles:()=>Xm,participantTypes:()=>nu,penaltyConstants:()=>pw,policyConstants:()=>lR,positionActionConstants:()=>LO,ratingConstants:()=>t_,recoveryTimeRequiredMatchUpStatuses:()=>gR,requestConstants:()=>tx,resultConstants:()=>OC,scaleConstants:()=>aR,scheduleConstants:()=>GR,sortingConstants:()=>Nv,surfaceConstants:()=>mw,tieFormatConstants:()=>F_,timeItemConstants:()=>wR,topicConstants:()=>AR,tournamentConstants:()=>jA,upcomingMatchUpStatuses:()=>$I,validMatchUpStatuses:()=>jI,venueConstants:()=>dw});var v1="Coaching",x1="Ball Abuse",w1="Racket Abuse",L1="Verbal Abuse",F1="INELIGIBILITY",G1="Physical Abuse",k1="Unsportmanlike Conduct",V1="Dress Code Violation",B1="Equipment Violation",H1="Leaving the court",W1="Failure to complete",j1="No Show",Y1="Other",q1="REFUSAL_TO_PLAY",$1="PROHIBITED_SUBSTANCE",K1="Puncuality",z1="Failure to sign in",pw={COACHING:v1,BALL_ABUSE:x1,RACKET_ABUSE:w1,VERBAL_ABUSE:L1,PHYSICAL_ABUSE:G1,INELIGIBILITY:F1,UNSPORTSMANLIKE_CONDUCT:k1,PROHIBITED_SUBSTANCE:$1,DRESS_CODE_VIOLATION:V1,EQUIMENT_VIOLATION:B1,LEAVING_THE_COURT:H1,REFUSAL_TO_PLAY:q1,FAILURE_TO_COMPLETE:W1,NO_SHOW:j1,OTHER:Y1,PUNCTUALITY:K1,FAILUIRE_TO_SIGN_IN:z1};var Q1="CLAY",X1="HARD",J1="GRASS",Z1="CARPET",t0="ARTIFICIAL",mw={CLAY:Q1,HARD:X1,GRASS:J1,CARPET:Z1,ARTIFICIAL:t0};var e0="INDOOR",r0="OUTDOOR",dw={INDOOR:e0,OUTDOOR:r0};export{Nm as activeMatchUpStatuses,U1 as askEngine,E1 as asyncEngine,Iv as auditConstants,N1 as competitionEngine,CE as competitionGovernor,ae as completedMatchUpStatuses,YI as directingMatchUpStatuses,kE as drawDefinitionConstants,ZD as drawsGovernor,sN as entriesGovernor,DR as entryStatusConstants,LC as errorConditionConstants,kR as eventConstants,TN as eventGovernor,HI as extensionConstants,lw as factoryConstants,_1 as fixtures,Pv as flightConstants,A1 as forge,Km as genderConstants,PN as generationGovernor,QC as globalState,$A as governors,l_ as keyValueConstants,kO as matchUpActionConstants,P1 as matchUpEngine,iA as matchUpFormatCode,iA as matchUpFormatGovernor,jN as matchUpGovernor,KI as matchUpStatusConstants,UR as matchUpTypes,D1 as mocksEngine,$g as mocksGovernor,qI as nonDirectingMatchUpStatuses,WI as particicipantsRequiredMatchUpStatuses,PR as participantConstants,TM as participantGovernor,Xm as participantRoles,nu as participantTypes,pw as penaltyConstants,lR as policyConstants,OD as policyGovernor,LO as positionActionConstants,NM as publishingGovernor,XD as queryGovernor,t_ as ratingConstants,gR as recoveryTimeRequiredMatchUpStatuses,MM as reportGovernor,tx as requestConstants,OC as resultConstants,aR as scaleConstants,O1 as scaleEngine,GR as scheduleConstants,kM as scheduleGovernor,yg as scoreGovernor,Nv as sortingConstants,mw as surfaceConstants,qx as syncEngine,F_ as tieFormatConstants,zM as tieFormatGovernor,wR as timeItemConstants,gC as tools,AR as topicConstants,jA as tournamentConstants,M1 as tournamentEngine,oC as tournamentGovernor,$I as upcomingMatchUpStatuses,gC as utilities,jI as validMatchUpStatuses,dw as venueConstants,fC as venueGovernor,Va as version};
|
|
23
|
+
`}var vD={};Jt(vD,{filterParticipants:()=>lu,getCompetitionParticipants:()=>IT,getPairedParticipant:()=>tn,getParticipantEventDetails:()=>hT,getParticipantMembership:()=>ST,getParticipantScaleItem:()=>Pc,getParticipantSchedules:()=>TT,getParticipantSignInStatus:()=>AT,getParticipantTimeItem:()=>Nh,getParticipants:()=>Yt,getScaleValues:()=>aa,participantScaleItem:()=>uo,validateLineUp:()=>ed});function IT(t){let{tournamentRecords:e}=t||{};if(typeof e!="object"||!Object.keys(e).length)return{error:Ft};let r=[],n={},o={},i={},s=[],a={},c=[];for(let u of Object.values(e)){let{participantIdsWithConflicts:p,mappedMatchUps:m,participantMap:d,participants:l,matchUps:f,derivedEventInfo:g,derivedDrawInfo:I}=Yt({...t,tournamentRecord:u});Object.assign(a,m),Object.assign(n,d),Object.assign(o,g),Object.assign(i,I),r.push(...l??[]),s.push(...f??[]),p?.forEach(h=>{c.includes(h)||c.push(h)})}return{participantIdsWithConflicts:c,derivedEventInfo:o,derivedDrawInfo:i,participantMap:n,mappedMatchUps:a,participants:r,...R,matchUps:s}}function hT({tournamentRecord:t,participantId:e}){if(!t)return{error:W};if(!e)return{error:oe};let r=[e].concat((t.participants??[]).filter(o=>o?.participantType&&[kt,dt].includes(o.participantType)&&o.individualParticipantIds?.includes(e)).map(o=>o.participantId));return{eventDetails:(t.events??[]).filter(o=>{let i=(o?.entries??[]).map(s=>s.participantId);return xe(i,r)}).map(o=>({eventName:o.eventName,eventId:o.eventId}))}}function ST({tournamentRecord:t,participantId:e}){if(!t)return{error:W};if(!e)return{error:oe};let{participants:r}=Yt({participantFilters:{participantTypes:[kt,dt,Ar]},tournamentRecord:t});return(r??[]).filter(o=>o.individualParticipantIds?.includes(e)).reduce((o,i)=>{let s=i.participantType;return s&&(o[s]||(o[s]=[]),o[s].push(i)),o},{})}function TT({participantFilters:t={},tournamentRecord:e}){if(!e)return{error:W};if(typeof t!="object")return{error:Xn,context:{participantFilters:t}};let r={eventIds:t.eventIds},n=le({tournamentRecord:e,contextFilters:r}).matchUps??[],o=Object.assign({},...n.map(p=>({[p.matchUpId]:p}))),i=n.filter(({schedule:p})=>p&&Object.keys(p).length),s=Vr({tournamentRecord:e,matchUps:n}).sourceMatchUpIds??[],a={};for(let p of i){let{sides:m}=p,d,l=m?.map(g=>{if(g.participant)return[g.participant].concat(...g.participant.individualParticipants||[]);s[p.matchUpId]&&!d&&(d=(s[p.matchUpId]||[]).map(I=>o[I]).filter(({winningSide:I,bye:h})=>!I&&!h))}).filter(Boolean).flat()??[];for(let g of l){let{participantId:I}=g;a[I]||(a[I]={potentialMatchUps:[],participant:g,matchUps:[]}),a[I].matchUps.push(p)}let f=d?.map(({sides:g})=>g).flat().map(({participant:g})=>g&&[g].concat(...g.individualParticipants||[])).filter(Boolean).flat()||[];for(let g of f){let{participantId:I}=g;a[I]||(a[I]={potentialMatchUps:[],participant:g,matchUps:[]}),a[I].potentialMatchUps.push(p)}}return{participantSchedules:Object.values(a).filter(({participant:p})=>!(t.participantIds&&!t.participantIds.includes(p.participantId)||t.participantTypes&&!t.participantTypes.includes(p.participantType))),...R}}function AT({tournamentRecord:t,participantId:e}){if(!t)return{error:W};if(!e)return{error:oe};let{participant:r}=xo({tournamentRecord:t,participantId:e});if(!r)return{error:Zt};let{timeItem:n}=Gn({itemType:ic,element:r});return n&&n.itemValue===ru&&ru}var xD={};Jt(xD,{analyzeDraws:()=>Eu,analyzeTournament:()=>DT,getAllowedDrawTypes:()=>vd,getAllowedMatchUpFormats:()=>yT,getAppliedPolicies:()=>Pt,getCompetitionDateRange:()=>wd,getCompetitionPenalties:()=>ET,getPolicyDefinitions:()=>yo,getTournamentInfo:()=>gs,getTournamentPenalties:()=>xd,getTournamentPersons:()=>PT,getTournamentStructures:()=>jh,getTournamentTimeItem:()=>mu});function yT({tournamentRecord:t,categoryName:e,categoryType:r}){if(!t)return{error:W};let{appliedPolicies:n}=Pt({tournamentRecord:t});return(n?.[vn]?.matchUpFormats||[]).filter(({categoryNames:s,categoryTypes:a})=>!e&&!a||e&&s?.includes(e)||r&&a?.includes(r))}function vd({tournamentRecord:t,categoryName:e,categoryType:r}){if(!t)return{error:W};let{appliedPolicies:n}=Pt({tournamentRecord:t});return(n?.[hm]?.allowedDrawTypes||[]).filter(({categoryNames:s,categoryTypes:a})=>!e&&!a||e&&s?.includes(e)||r&&a?.includes(r))}function xd({tournamentRecord:t}){if(!t)return{error:W};let r=(t?.participants??[]).reduce((n,o)=>{let{participantId:i}=o;return(o.penalties??[]).forEach(s=>{let{penaltyId:a}=s||{};n[a]?n[a].participants.push(i):n[a]={...s,participantIds:[i]}}),n},{});return{penalties:Object.values(r)}}function ET({tournamentRecords:t}){if(typeof t!="object"||!Object.keys(t).length)return{error:Ft};let e=[];for(let r of Object.values(t)){let{penalties:n}=xd({tournamentRecord:r});e.push(...n??[])}return{penalties:e}}function UT({event:t}){return{eventInfo:(({eventId:r,eventName:n,eventType:o,eventLevel:i,surfaceCategory:s,matchUpFormat:a,category:c,gender:u,startDate:p,endDate:m,ballType:d,discipline:l,onlineResources:f,notes:g})=>({eventId:r,eventName:n,eventType:o,eventLevel:i,surfaceCategory:s,matchUpFormat:a,category:c,gender:u,startDate:p,endDate:m,ballType:d,discipline:l,onlineResources:f,notes:g}))(t)}}var rV={[Os]:{policyName:"Staff Privacy Policy",participant:{contacts:!1,individualParticipants:!1,individualParticipantIds:!1,onlineResources:!1,participantName:!0,participantOtherName:!0,participantId:!0,participantRole:!0,participantRoleResponsibilities:!0,participantStatus:!0,penalties:!1,representing:!0,participantType:!0,person:{addresses:!1,biographicalInformation:!1,birthDate:!1,contacts:!1,nationalityCode:!0,nativeFamilyName:!1,nativeGivenName:!1,onlineResources:!1,otherNames:!0,parentOrganisationId:!1,passportFamilyName:!1,passportGivenName:!1,personId:!1,personOtherIds:!1,previousNames:!1,sex:!1,standardFamilyName:!0,standardGivenName:!0,status:!1,tennisId:!1,wheelchair:!0}}}},nv=rV;function gs(t){let{tournamentRecord:e}=t??{};if(!e)return{error:W};let r=(({tournamentId:a,tournamentRank:c,tournamentStatus:u,formalName:p,tournamentName:m,promotionalName:d,onlineResources:l,localTimeZone:f,startDate:g,endDate:I,hostCountryCode:h,venues:S,notes:T,updatedAt:A})=>({tournamentId:a,tournamentRank:c,tournamentStatus:u,formalName:p,tournamentName:m,promotionalName:d,onlineResources:l,localTimeZone:f,startDate:g,endDate:I,hostCountryCode:h,venues:S,notes:T,updatedAt:A}))(e),n=Yt({participantFilters:{participantRoles:[gU,Bf,IU,hU,TU]},policyDefinitions:nv,tournamentRecord:e}).participants;n&&(r.tournamentContacts=n);let i=as({tournamentRecord:e})?.publishState?.tournament?.status?.publishedEventIds||[],s=[];for(let a of e.events??[])if(!t?.usePublishState||i.includes(a.eventId)){let c=UT({event:a}).eventInfo;c&&s.push(c)}return r.eventInfo=s,{tournamentInfo:J(r,!1,!0),...R}}function wd({tournamentRecords:t}){if(!Rt(t))return{error:Ft};let r=Object.keys(t??{}).reduce((i,s)=>{let a=t[s],{tournamentInfo:{startDate:c,endDate:u}}=gs({tournamentRecord:a}),p=c&&new Date(Ut(c));(!i.startDate||p&&p<i.startDate)&&(i.startDate=p);let m=u&&new Date(Ut(u));return(!i.endDate||m&&m>i.endDate)&&(i.endDate=m),i},{startDate:void 0,endDate:void 0}),n=r.startDate&&Ut(r.startDate.toISOString()),o=r.endDate&&Ut(r.endDate.toISOString());return!n||!o?{error:Uy}:{startDate:n,endDate:o}}function PT({tournamentRecord:t,participantFilters:e}){if(!t)return{error:W};let r=t.participants||[];e&&(r=lu({participants:r,participantFilters:e,tournamentRecord:t}));let n={},o=i=>{if(i.person){let{personId:s}=i.person;n[s]?n[s].participantIds.push(i.participantId):n[s]={...i.person,participantIds:[i.participantId]}}};return r.forEach(i=>{i.person&&o(i)}),{tournamentPersons:Object.values(n)}}function ov(t){let r=t.participants?.filter(({participantType:a})=>a===kt)?.length===2,n=t.events?.length===1&&t.events[0],o=n?.drawDefinitions?.length===1&&n.drawDefinitions[0],s=(o?.structures?.length===1&&o.structures[0])?.positionAssignments?.length===2;return!!(n.tieFormat&&r&&s)}function DT({tournamentRecord:t}){if(!t)return{error:W};let{drawsAnalysis:e}=Eu({tournamentRecord:t}),r={isDual:ov(t),drawsAnalysis:e};return{...R,analysis:r}}var LD={};Jt(LD,{compareTieFormats:()=>Go,getTieFormat:()=>NT,tieFormatGenderValidityCheck:()=>pd,validateCollectionDefinition:()=>yu});function Ld(t){if(!t)return{};let e=[],r=t.tieFormatName,n=t.collectionDefinitions?.map(o=>{let{matchUpType:i,matchUpFormat:s,matchUpCount:a,category:c,gender:u}=o;e.includes(s)||e.push(s);let p=c?.ageCategoryCode;return[a,i===vi?"D":"S",p,s,u].join(";")}).join("|");return{tieFormatName:t&&r||"UNNAMED",matchUpFormats:e,tieFormatDesc:n}}function Go({considerations:t={},descendant:e,ancestor:r}){let n={},o={},{matchUpFormats:i,tieFormatDesc:s}=Ld(e),{matchUpFormats:a,tieFormatDesc:c}=Ld(r),u=pt((i??[]).filter(D=>!(a??[]).includes(D)).concat((a??[]).filter(D=>!(i??[]).includes(D)))),p=!!(t?.collectionName&&e.collectionDefinitions.map(({collectionName:D})=>D).join("|")!==r.collectionDefinitions.map(({collectionName:D})=>D).join("|")),m=!!(t?.collectionOrder&&e.collectionDefinitions.map(({collectionOrder:D})=>D).join("|")!==r.collectionDefinitions.map(({collectionOrder:D})=>D).join("|")),d=Object.assign({},...(e?.collectionDefinitions||[]).map(D=>({[D.collectionId]:D}))),l=Object.assign({},...(r?.collectionDefinitions||[]).map(D=>({[D.collectionId]:D})));n.collectionIds=cE(Object.keys(d),Object.keys(l)),o.collectionIds=cE(Object.keys(l),Object.keys(d)),n.collectionsValue=iv(d),o.collectionsValue=iv(l),n.groupsCount=r?.collectionGroups?.length??(0-(e?.collectionGroups?.length??0)||0),o.groupsCount=n.groupsCount?-1*n.groupsCount:0;let f=n.collectionsValue.totalValue-o.collectionsValue.totalValue,g=n.collectionsValue.totalMatchUps-o.collectionsValue.totalMatchUps,I=o.collectionsValue.assignmentValues.length!==n.collectionsValue.assignmentValues.length,h=o.collectionsValue.assignmentValues.some((D,y)=>{let E=n.collectionsValue.assignmentValues[y];return!E||D.valueKey!==E.valueKey||D.value!==E.value?!0:Array.isArray(D.value)?D.value.every((U,M)=>E.value[M]===U):!1}),S=p||m||c!==s||I||h||f!==0,T=[...o.collectionsValue.invalidValues,...n.collectionsValue.invalidValues],A=T.length&&T;return{matchUpFormatDifferences:u,matchUpCountDifference:g,descendantDifferences:n,ancestorDifferences:o,orderDifference:m,valueDifference:f,nameDifference:p,descendantDesc:s,ancestorDesc:c,...R,different:S,invalid:A}}function iv(t){let e=[],r=[],n=0;return{totalValue:Object.keys(t).sort(du).reduce((s,a)=>{let c=t[a],{collectionValueProfiles:u,collectionValue:p,matchUpCount:m,matchUpValue:d,scoreValue:l,setValue:f}=c,g={collectionValueProfiles:u,collectionValue:p,matchUpValue:d,scoreValue:l,setValue:f},I=Object.keys(g).filter(S=>![void 0,null].includes(g[S]));I.length!==1&&e.push({collectionId:a});let h=I[0];if(h){let S=h==="collectionValueProfiles"?Object.values(u):g[h];r.push({valueKey:h,value:S})}return n+=m,u?s+u.reduce((S,T)=>S+T.value,0):m?ft(d)?s+d*m:ft(l)?s+l*m:ft(f)?s+f*m:s+p:s},0),totalMatchUps:n,invalidValues:e,assignmentValues:r}}function Ug(t){Object.assign(t,{inContext:!0});let{matchUp:e,error:r}=wD(t);return{matchUp:J(e,!0,!0),error:r}}function wD({participantsProfile:t,afterRecoveryTimes:e,tournamentRecord:r,contextContent:n,contextProfile:o,drawDefinition:i,nextMatchUps:s,matchUpId:a,inContext:c,eventId:u,drawId:p,event:m}){if(!r)return{error:W};if(typeof a!="string")return{error:ke};if(!i||!m){let g=(le({tournamentRecord:r,nextMatchUps:s}).matchUps??[]).find(I=>I.matchUpId===a);if(!g)return{error:Oe};({eventId:u,drawId:p}=g),{event:m,drawDefinition:i}=We({tournamentRecord:r,eventId:u,drawId:p})}if(!i)return{error:pr};o&&!n&&(n=Ln({tournamentRecord:r,contextProfile:o}));let d={surfaceCategory:m?.surfaceCategory??r.surfaceCategory,indoorOutDoor:m?.indoorOutdoor??r.indoorOutdoor,endDate:m?.endDate??r.endDate,tournamentId:r.tournamentId,eventId:u??m?.eventId,drawId:p},{participants:l=[]}=Ii({participantsProfile:t,tournamentRecord:r,contextProfile:o,inContext:c});if(s){let g=(rr({context:c?d:void 0,participants:l,afterRecoveryTimes:e,contextContent:n,contextProfile:o,drawDefinition:i,nextMatchUps:s,inContext:c,event:m}).matchUps??[]).find(h=>h.matchUpId===a);if(!g)return{error:Oe};let I=i?.structures?.find(h=>h.structureId===g.structureId);return{drawDefinition:i,structure:I,matchUp:g}}else{let{matchUp:f,structure:g}=xt({context:c?d:void 0,tournamentParticipants:l,afterRecoveryTimes:e,contextContent:n,drawDefinition:i,contextProfile:o,matchUpId:a,inContext:c,event:m});return{matchUp:f,structure:g,drawDefinition:i}}}function NT({tournamentRecord:t,drawDefinition:e,structureId:r,matchUpId:n,structure:o,eventId:i,drawId:s,event:a}){if(!t)return{error:W};if(!s&&!a&&!r&&!n)return _({result:{error:et},stack:"getTieFormat"});i&&!a&&(a=t.events?.find(l=>l.eventId===i));let c=Ug({tournamentRecord:t,drawDefinition:e,matchUpId:n,drawId:s,event:a});if(n&&c?.error)return c;if(!e&&c?.drawDefinition&&(e=c?.drawDefinition),o=o??c?.structure,!o&&r&&!n){if(!e)return{error:Wr};let l=st({drawDefinition:e,structureId:r});if(l.error)return l;o=l.structure}let u=(o?.tieFormat||o?.tieFormatId)&&je({structure:o,drawDefinition:e,event:a})?.tieFormat,p=(e?.tieFormat||e?.tieFormatId)&&je({drawDefinition:e,event:a})?.tieFormat,m=je({event:a})?.tieFormat,d=je({matchUp:c?.matchUp,drawDefinition:e,structure:o,event:a})?.tieFormat;return{...R,matchUp:c?.matchUp,structureDefaultTieFormat:Xe(u),eventDefaultTieFormat:Xe(m),drawDefaultTieFormat:Xe(p),tieFormat:Xe(d),structure:o}}var kD={};Jt(kD,{bulkUpdatePublishedEventIds:()=>MT,getAllEventData:()=>CT,getCourtInfo:()=>Hm,getDrawData:()=>Fd,getEventData:()=>Gd,getEventPublishStatus:()=>vr,getPublishState:()=>as,getVenueData:()=>mc});function MT({tournamentRecord:t,outcomes:e}){if(!t)return{error:W};if(!e?.length)return{error:et,info:"Missing outcomes"};let r=e.reduce((s,a)=>{let{drawId:c,eventId:u}=a;return u&&c&&(s[u]?s[u].includes(c)||s[u].push(c):s[u]=[c]),s},{}),n=Object.keys(r);return{publishedEventIds:(t.events?.filter(s=>n.includes(s.eventId))).filter(s=>{let a=vr({event:s}),{drawDetails:c,drawIds:u}=a??{},{eventId:p}=s;return r[p].filter(d=>{let l=c?Object.keys(a.drawDetails).filter(f=>Qm({drawId:f,drawDetails:c})):[];return u?.includes(d)||l.includes(d)}).length}).map(s=>s.eventId),eventIdPublishedDrawIdsMap:r}}function FD({dates:t=[],extension:e}){if(!e)return!1;if(typeof e.value=="boolean"&&e.value)return!0;if(!t.length)return!1;let r=Rt(e.value)?e.value?.dates:void 0;if(Array.isArray(r))return r?.length?!!r.filter(o=>!t.length||t.includes(o)).length:!1}function GD({convertExtensions:t,ignoreDisabled:e,venue:r,court:n}){let o={...J(n,t,!0),venueId:r.venueId},{extension:i}=mt({name:Wn,element:n});if(e&&i){let s=Rt(i.value)?i.value?.dates:void 0,a=i?.value===!0?[]:o.dateAvailability.map(c=>{let u=c.date;if(!(!u||s.includes(u)))return c}).filter(Boolean);o.dateAvailability=a}return{inContextCourt:o}}function po(t){let{convertExtensions:e,ignoreDisabled:r,venueIds:n=[],dates:o}=t,i=t.tournamentRecords||t.tournamentRecord&&{[t.tournamentRecord.tournamentId]:t.tournamentRecord}||{},s=[],a=[],c=[],u=[];return Object.keys(i).filter(m=>!t.tournamentId||m===t.tournamentId).forEach(m=>{let d=i[m];for(let l of d.venues??[])if(!(n.length&&!n.includes(l.venueId))){if(r){let{extension:f}=mt({name:Wn,element:l});if(f?.value)continue}s.includes(l.venueId)||(u.push(J(l,e,!0)),s.push(l.venueId));for(let f of l.courts??[])if(!a.includes(f.courtId)){if(r){let{extension:I}=mt({name:Wn,element:f});if(FD({extension:I,dates:o}))continue}let{inContextCourt:g}=GD({convertExtensions:e,ignoreDisabled:r,venue:l,court:f});c.push(g),a.push(f.courtId)}}}),{courts:c,venues:u,...R}}function nV({convertExtensions:t,tournamentRecord:e,ignoreDisabled:r,dates:n}){if(!e)return{error:Ft};let o=J(e.venues??[],t).filter(s=>{if(!r)return s;let{extension:a}=mt({name:Wn,element:s});return!a?.value&&s}).filter(Boolean),i=o.reduce((s,a)=>{let c=(a?.courts||[]).filter(u=>{if(!r&&!n?.length)return u;let{extension:p}=mt({name:Wn,element:u});return FD({extension:p,dates:n})}).filter(Boolean).map(u=>{let{inContextCourt:p}=GD({convertExtensions:t,ignoreDisabled:r,venue:a,court:u});return p});return c.length?s.concat(c):s},[]);return{venues:o,courts:i}}function Lp({tournamentRecords:t,requireCourts:e,dates:r}){return typeof t!="object"||!Object.keys(t).length?{error:Ft}:Object.keys(t).reduce((o,i)=>{let s=t[i],{venues:a}=nV({tournamentRecord:s,dates:r});return a?.forEach(c=>{let{venueId:u,courts:p}=c;(!e||p?.length)&&!o.venueIds.includes(u)&&(o.venues.push(c),o.venueIds.push(u))}),o},{venues:[],venueIds:[]})}function CT({tournamentRecord:t,policyDefinitions:e}){if(!t)return{error:W};let r=t.events||[],n=t?.participants||[],{tournamentInfo:o}=gs({tournamentRecord:t}),{venues:i}=po({tournamentRecord:t}),s=r.map(c=>{let{eventId:u}=c,p=UT({event:c}).eventInfo,m=Sa({tournamentRecord:t,event:c}).scheduleTiming,d=(c.drawDefinitions||[]).map(f=>{let g=(({drawId:A,drawName:D,matchUpFormat:y,updatedAt:E})=>({matchUpFormat:y,updatedAt:E,drawName:D,drawId:A}))(f),{abandonedMatchUps:I,completedMatchUps:h,upcomingMatchUps:S,pendingMatchUps:T}=Vs({requireParticipants:!0,tournamentParticipants:n,context:{eventId:u},policyDefinitions:e,tournamentRecord:t,inContext:!0,scheduleTiming:m,drawDefinition:f,event:c});return{drawInfo:g,matchUps:{abandonedMatchUps:I,completedMatchUps:h,upcomingMatchUps:S,pendingMatchUps:T}}}),l=vr({event:c});return Object.assign(p,{drawsData:d,publish:l}),p});return{allEventData:{tournamentInfo:o,venuesData:i,eventsData:s}}}function RT({publishStatus:t,drawId:e}){return t?.drawDetails?t.drawDetails?.[e]?.publishingDetail?.published:t?.drawIds?t.drawIds.includes(e):!0}function Fd(t){let{tournamentParticipants:e=[],includePositionAssignments:r,policyDefinitions:n,tournamentRecord:o,inContext:i=!0,usePublishState:s,status:a=Gr,drawDefinition:c,noDeepCopy:u,sortConfig:p,context:m,event:d}=t;if(!c)return{error:X};let l=(({matchUpFormat:P,updatedAt:N,drawType:C,drawName:O,drawId:b})=>({matchUpFormat:P,updatedAt:N,drawName:O,drawType:C,drawId:b}))(c),f,g,{allStructuresLinked:I,sourceStructureIds:h,hasDrawFeedProfile:S,structureGroups:T}=gu({drawDefinition:c});if(!I)return{error:ly};let A=t?.publishStatus??vr({event:d,status:a}),D=t.eventPublished??!!as({event:d}).publishState?.status?.published,y=!1,E=!1,M=T.map(P=>{let N={},C=P.map(O=>{let{structure:b}=st({drawDefinition:c,structureId:O}),{seedAssignments:x}=Fr({drawDefinition:c,structure:b});return b?.stage===tt&&b.stageSequence===1&&(f=x),b?.stage===at&&b.stageSequence===1&&(g=x),b}).sort((O,b)=>ci(O,b,p)).map(O=>{if(!O)return;let b=O?.structureId,x=[];O.stage&&[tt,Ve,ce].includes(O.stage)&&(x=f),O?.stage===at&&(x=g);let{matchUps:w,roundMatchUps:F,roundProfile:L}=At({seedAssignments:O?.seedAssignments?.length?void 0:x,context:{drawId:l.drawId,...m},tournamentParticipants:e,policyDefinitions:n,tournamentRecord:o,usePublishState:s,publishStatus:A,drawDefinition:c,inContext:i,structure:O,event:d}),{positionAssignments:v}=Nt({structure:O}),B=v?.filter(Pr(Bn)).map(V=>{let{drawPosition:Y,participantId:$}=V,{extension:k}=mt({element:V,name:Ho});return E=!0,{participantResult:k?.value,participantId:$,drawPosition:Y}});if(!B?.length&&w.length&&t.allParticipantResults){let{subOrderMap:V}=oS({positionAssignments:v}),Y=Ca({matchUpFormat:O.matchUpFormat,policyDefinitions:n,subOrderMap:V,matchUps:w});B=v?.filter(Pr(Bn)).map($=>{let{drawPosition:k,participantId:K}=$;return E=!0,{participantResult:K&&Y.participantResults[K],participantId:K,drawPosition:k}})}let H=O?(({stageSequence:V,structureName:Y,structureType:$,matchUpFormat:k,stage:K})=>({stageSequence:V,structureName:Y,structureType:$,matchUpFormat:k,stage:K}))(O):{};H.sourceStructureIds=h[b],H.hasDrawFeedProfile=S[b],H.positionAssignments=v,H.structureActive=w.reduce((V,Y)=>{let $=[me,Wo,Ot,lr,_t,Dn,Ne,ge].includes(Y.matchUpStatus);return V||$||!!Y.winningSide||!!Y.score?.scoreStringSide1},!1);let j=w.reduce((V,Y)=>V&&[Dt,me,lr,_t,Ot,$r].includes(Y.matchUpStatus),!!w.length);return H.structureCompleted=j,N[b]=j,H.structureActive&&(y=!0),{...H,participantResults:B,seedAssignments:x,roundMatchUps:F,roundProfile:L,structureId:b}});return C.forEach(O=>{r||delete O.positionAssignments,O.sourceStructuresComplete=O.sourceStructureIds?.every(b=>N[b])}),C}).flat();return l.drawActive=y,l.participantPlacements=E,l.drawGenerated=M?.reduce((P,N)=>P||!!N?.roundMatchUps,!1),l.drawCompleted=M?.reduce((P,N)=>P&&N.structureCompleted,!0),l.drawPublished=s?D&&RT({publishStatus:A,drawId:l.drawId}):void 0,{structures:!s||l.drawPublished?u?M:J(M,!1,!0):void 0,drawInfo:u?l:J(l,!1,!0),...R}}function Gd(t){let{includePositionAssignments:e,participantsProfile:r,policyDefinitions:n,usePublishState:o,status:i=Gr,sortConfig:s}=t,a=lt(t,[{tournamentRecord:!0},{[fm]:{event:!1,eventId:!1}}]);if(a.error)return a;let c=J(t.tournamentRecord,!1,!0),u=t.event?void 0:We({tournamentRecord:c,eventId:t.eventId}).event,p=t.event?J(t.event,!1,!0):u&&J(u,!1,!0)||void 0;if(!p)return{error:mr};let{eventId:m}=p,{tournamentId:d,endDate:l}=c,f=vr({event:p,status:i}),g=as({event:p}).publishState??{},I=!!g?.status?.published,{participants:h}=Yt({withGroupings:!0,withEvents:!1,withDraws:!1,policyDefinitions:n,...r,tournamentRecord:c}),S=({stage:O,drawId:b})=>{if(!o)return!0;let x=f?.drawDetails?.[b]?.stageDetails;return!x||!Object.keys(x).length?!0:x[O]?.published},T=({structureId:O,drawId:b})=>{if(!o)return!0;let x=f?.drawDetails?.[b]?.structureDetails;return!x||!Object.keys(x).length?!0:x[O]?.published},A=({drawId:O})=>o?RT({publishStatus:f,drawId:O}):!0,D=({drawId:O,structure:b})=>{if(!o)return b;let x=f?.drawDetails?.[O]?.structureDetails?.[b.structureId]?.roundLimit;if(ft(x)){let w=Z(1,x+1),F={},L={};for(let v of w)b.roundMatchUps[v]&&(F[v]=b.roundMatchUps[v],L[v]=b.roundProfile[v]);b.roundMatchUps=F,b.roundProfile=L}return b},y=p.drawDefinitions||[],E=!o||I?y.filter(A).map(O=>(({drawInfo:b,structures:x})=>({...b,structures:x}))(Fd({allParticipantResults:t.allParticipantResults,context:{eventId:m,tournamentId:d,endDate:l},includePositionAssignments:e,tournamentParticipants:h,noDeepCopy:!0,policyDefinitions:n,tournamentRecord:c,usePublishState:o,drawDefinition:O,publishStatus:f,sortConfig:s,event:p}))).map(({structures:O,...b})=>{let x=O?.filter(({stage:w,structureId:F})=>T({structureId:F,drawId:b.drawId})&&S({stage:w,drawId:b.drawId})).map(w=>D({drawId:b.drawId,structure:w}));return{...b,structures:x}}).filter(O=>O.structures?.length):void 0,{tournamentInfo:U}=gs({tournamentRecord:c}),P=(c.venues||[]).map(O=>(({venueData:b})=>({...b}))(mc({tournamentRecord:c,venueId:O.venueId}))),N=(({eventId:O,eventName:b,eventType:x,eventLevel:w,surfaceCategory:F,matchUpFormat:L,category:v,gender:B,startDate:H,endDate:j,ballType:V,discipline:Y})=>({eventId:O,eventName:b,eventType:x,eventLevel:w,surfaceCategory:F,matchUpFormat:L,category:v,gender:B,startDate:H,endDate:j,ballType:V,discipline:Y}))(p),C={tournamentInfo:U,venuesData:P,eventInfo:N,drawsData:E};return C.eventInfo.publishState=g,C.eventInfo.published=g?.status?.published,{...R,eventData:C,participants:h}}var WD={};Jt(WD,{getPersonRequests:()=>yi,getProfileRounds:()=>kd,getScheduledRoundsDetails:()=>bu,getSchedulingProfile:()=>ko,getSchedulingProfileIssues:()=>bT});function Fp({defaultRecoveryMinutes:t=0,defaultAverageMinutes:e,tournamentRecords:r,matchUpFormat:n,categoryName:o,categoryType:i,tournamentId:s,eventType:a,eventId:c}){if(!Sr({matchUpFormat:n}))return{error:Ya};let u=Object.keys(r).filter(m=>!s||m===s),p;return u.forEach(m=>{if(p)return;let d=r[m],l=c?We({tournamentRecord:d,eventId:c})?.event:void 0;return p=au({tournamentRecord:d,matchUpFormat:n,categoryName:o,categoryType:i,eventType:a,event:l}),p?.averageMinutes||p?.recoveryMinutes}),{recoveryMinutes:p?.recoveryMinutes||t,averageMinutes:p?.averageMinutes||e,typeChangeRecoveryMinutes:p?.typeChangeRecoveryMinutes||p?.recoveryMinutes||t}}function bu({scheduleCompletedMatchUps:t,containedStructureIds:e,tournamentRecords:r,periodLength:n=30,matchUps:o,rounds:i}){if(typeof r!="object")return{error:Ft};if(!Array.isArray(i))return{error:et,info:Nn("rounds")};let s={},a=[],c=[];i.sort((f,g)=>(f.sortOrder??0)-(g.sortOrder??0)),e=e??Object.assign({},...Object.values(r).map(f=>Ji({tournamentRecord:f}).containedStructures)),o||({matchUps:o}=cn({nextMatchUps:!0,tournamentRecords:r}));let u=0,p={},m={},d={};return{scheduledRoundsDetails:i.flatMap(f=>{let g=f.periodLength||n,I=[];e?.[f.structureId]?I.push(...e[f.structureId]):I.push(f.structureId);let h=o?Aa({tournamentIds:[f.tournamentId],roundNumbers:[f.roundNumber],matchUpIds:f.matchUpIds,eventIds:[f.eventId],drawIds:[f.drawId],processContext:!0,structureIds:I,matchUps:o}).sort(hi):[],{segmentNumber:S,segmentsCount:T}=f.roundSegment||{};if(ft(S)&&Tn(h?.length)&&Tn(T)&&S>0&&S<=T&&T<h?.length&&!f.matchUpIds?.length){let E=h.length/T,U=E*(S-1);h=h.slice(U,U+E)}let A=r[f.tournamentId],D=We({drawId:f.drawId,tournamentRecord:A}).event,y=[];for(let E of h){let U=E.matchUpFormat;U&&(s[U]||(s[U]=[],s[U].push(E)),y.push(U))}for(let E of y){let{eventType:U,category:M}=D??{},{categoryName:P,ageCategoryCode:N}=M??{},{typeChangeRecoveryMinutes:C,recoveryMinutes:O,averageMinutes:b,error:x}=Fp({categoryName:P??N,categoryType:M?.categoryType,tournamentId:f.tournamentId,eventId:f.eventId,tournamentRecords:r,matchUpFormat:E,eventType:U});if(x)return{error:x,round:f};let w=h.filter(L=>(t||!ae.includes(L.matchUpStatus))&&L.matchUpStatus!==Dt).map(fe);w.forEach(L=>{d[L]={typeChangeRecoveryMinutes:C,recoveryMinutes:O,averageMinutes:b},p[L]=O,m[L]=b}),c.push(...w),u=Math.max(b||0,u);let F=`${b}|${g}`;return a.includes(F)||a.push(F),{roundPeriodLength:g,recoveryMinutes:O,averageMinutes:b,matchUpIds:w,hash:F}}}),greatestAverageMinutes:u,matchUpFormatCohorts:s,recoveryMinutesMap:p,averageMinutesMap:m,orderedMatchUpIds:c,minutesMap:d,...R}}function VD({schedulingProfile:t,venueIds:e,eventIds:r,drawIds:n}){let o=[],i=t?.map(a=>{let c=Ut(a?.scheduleDate);if(!c){o.push(`Invalid date: ${a?.scheduledDate}`);return}let u=(a?.venues||[]).map(p=>{let{rounds:m,venueId:d}=p;if(!e?.includes(d)){o.push(`Missing venueId: ${d}`);return}let f=m.filter(g=>{let I=r.includes(g.eventId)&&n.includes(g.drawId);return I||o.push(`Invalid eventId: ${g.eventId} or drawId: ${g.drawId}`),I});if(f.length)return{venueId:d,rounds:f}}).filter(Boolean);return u.length&&c&&{...a,venues:u}}).filter(Boolean),s=o.length;return{updatedSchedulingProfile:i,modifications:s,issues:o}}function Gp({tournamentRecords:t,schedulingProfile:e}){if(!e)return{valid:!0};if(!Array.isArray(e))return{valid:!1,error:G};let{venueIds:r,tournamentsMap:n}=iV({tournamentRecords:t}),o,i,s=e.every(a=>{let{scheduleDate:c,venues:u}=a;return Rr(c)?u.every(p=>{let{venueId:m,rounds:d}=p;return typeof m!="string"?(i="venueId should be a string",!1):Array.isArray(d)?r.includes(m)?!!d.every(f=>{if(!f)return i="empty round",!1;let{roundSegment:g,tournamentId:I,structureId:h,roundNumber:S,eventId:T,drawId:A}=f,y=n?.[I]?.[T]?.[A]?.[h]?.includes(S);y||(i="Invalid rounds");let{segmentNumber:E,segmentsCount:U}=g||{},M=!g||ft(E)&&Tn(U)&&E<=U;return M||(i="Invalid segment"),y&&M}):(o=Ds,!1):(i="rounds should be an array",!1)}):!1});return!s&&!o&&(o=G),{valid:!!s,error:o,info:i}}function oV(t){let{tournamentRecord:e={},tournamentMap:r={},requireCourts:n}=t,o=[],i=[],s=[],a=[],c=(e?.venues||[]).map(({venueId:p,courts:m})=>(!n||m?.length)&&p),u=e?.tournamentId;return u&&(o.push(u),r[u]={},(e?.events||[]).forEach(m=>{let d=m.eventId;s.push(d),r[u][d]={},(m.drawDefinitions||[]).forEach(l=>{let f=l.drawId;a.push(f),r[u][d][f]={};let{structures:g}=xn({drawDefinition:l});(g||[]).forEach(I=>{let h=I.structureId,{matchUps:S}=At({structure:I}),{roundMatchUps:T}=He({matchUps:S}),A=T&&Object.keys(T).map(D=>parseInt(D));r[u][d][f][h]=A,i.push(h),I.structures?.length&&I.structures.forEach(D=>{i.push(D.structureId),r[u][d][f][D.structureId]=A})})})})),{tournamentMap:r,tournamentIds:o,structureIds:i,venueIds:c,eventIds:s,drawIds:a}}function iV(t){let e=t?.tournamentRecords&&Object.values(t?.tournamentRecords)||[],r={},{venueIds:n,eventIds:o,drawIds:i,structureIds:s,tournamentIds:a}=e.reduce((c,u)=>{let{tournamentIds:p,tournamentMap:m,structureIds:d,venueIds:l,eventIds:f,drawIds:g}=oV({tournamentRecord:u});return l.forEach(I=>{c.venueIds.includes(I)||c.venueIds.push(I)}),c.tournamentIds.push(...p),c.structureIds.push(...d),c.eventIds.push(...f),c.drawIds.push(...g),Object.assign(r,m),c},{tournamentIds:[],structureIds:[],venueIds:[],eventIds:[],drawIds:[]});return{tournamentsMap:r,tournamentIds:a,structureIds:s,venueIds:n,eventIds:o,drawIds:i}}function ko({tournamentRecords:t,tournamentRecord:e}){if(typeof t!="object"||!Object.keys(t).length)return{error:Ft};let{extension:r}=mt({element:e,name:da,tournamentRecords:t,discover:!0}),n=r?.value||[];if(n.length){let{venueIds:o}=Lp({requireCourts:!0,tournamentRecords:t}),{eventIds:i,drawIds:s}=ng({tournamentRecords:t}),{updatedSchedulingProfile:a,modifications:c,issues:u}=VD({schedulingProfile:n,venueIds:o,eventIds:i,drawIds:s});if(c){n=a;let p=Dc({tournamentRecords:t,tournamentRecord:e,schedulingProfile:n});return p.error?p:{schedulingProfile:n,modifications:c,issues:u}}}return{schedulingProfile:n,modifications:0}}function Dc({tournamentRecords:t,tournamentRecord:e,schedulingProfile:r}){let n=Gp({tournamentRecords:t,schedulingProfile:r});return n.error?n:r?St({tournamentRecords:t,discover:!0,extension:{name:da,value:r}}):or({element:e,name:da,tournamentRecords:t,discover:!0})}function Nc(t){let{tournamentRecord:e}=t,r=t.tournamentRecords||e&&{[e.tournamentId]:e}||{};if(!t.schedulingProfile){let{modifications:u,issues:p}=ko({tournamentRecords:r,tournamentRecord:e});return{success:!u,modifications:u,issues:p}}let{venueIds:n}=Lp({tournamentRecords:r}),{eventIds:o,drawIds:i}=ng({tournamentRecords:r}),{updatedSchedulingProfile:s,modifications:a,issues:c}=VD({schedulingProfile:t.schedulingProfile,venueIds:n,eventIds:o,drawIds:i});return a?{...Dc({schedulingProfile:s,tournamentRecords:r}),modifications:a,issues:c}:{...R,modifications:a,issues:c}}function bT(t){let{scheduleDates:e=[],tournamentRecords:r,periodLength:n=30}=t??{};if(typeof r!="object")return{error:Ba};if(!Array.isArray(e))return{error:G};if(!e.every(Rr))return{error:ar};let i=[],s=0,a={},{schedulingProfile:c}=ko({tournamentRecords:r});if(!c)return{issues:i,...R};let{matchUps:u}=cn({nextMatchUps:!0,tournamentRecords:r});for(let m of c){let{scheduleDate:d,venues:l=[]}=m;if(!e?.length||e.includes(d)){for(let f of l||[])if(f){let{rounds:g}=f,I=[],{orderedMatchUpIds:h,scheduledRoundsDetails:S}=bu({tournamentRecords:r,periodLength:n,matchUps:u,rounds:g}),{matchUpDependencies:T}=Vr({tournamentRecords:r,matchUps:u}),A=D=>{let y;return S?.find((E,U)=>{let M=E.matchUpIds.includes(D);return M&&(y=U),M}),y};if(h?.forEach((D,y)=>{let E=h.slice(y+1),U=jt(E,T?.[D]?.matchUpIds||[]);U.length&&I.push({matchUpId:D,shouldBeAfter:U})}),I.length){s+=I.length;let D=I.map(({matchUpId:y,shouldBeAfter:E})=>{let U=A(y),M=pt(E.map(A));return a[d]||(a[d]={}),a[d][U]||(a[d][U]=[]),M.forEach(P=>{a[d][U].includes(P)||a[d][U].push(P)}),{matchUpId:y,matchUpRoundIndex:U,earlierRoundIndices:M,shouldBeAfter:E}});i.push(...D)}}}}let p={matchUpIdShouldBeAfter:Object.assign({},...i.map(m=>{let{matchUpId:d,shouldBeAfter:l,earlierRoundIndices:f}=m;return{[d]:{earlierRoundIndices:f,shouldBeAfter:l}}}))};return{issuesCount:s,profileIssues:p,roundIndexShouldBeAfter:a,...R}}function yi(t){let{tournamentRecords:e,requestType:r}=t,n=lt(t,[{[ye]:!0}]);if(n.error)return n;let o={};for(let i of Object.values(e)){let{extension:s}=mt({element:i,name:ma}),a=s?.value||[];for(let c of a){let{personId:u,requests:p}=c||{};o[u]||(o[u]=[]);for(let m of p)r&&m.requestType!==r||o[u].push(m)}}return{personRequests:o,...R}}function Pg(t){let{containerStructureId:e,roundSegment:r,isRoundRobin:n,tournamentId:o,roundNumber:i,structureId:s,eventId:a,drawId:c}=t,u=n?e:s,p=[o,a,c,u,i].join("|");return rt({structureId:u,roundSegment:r,tournamentId:o,roundNumber:i,eventId:a,drawId:c,id:p})}function BD({round:t,matchUps:e,events:r,tournamentRecords:n}){let o=r.find(d=>d.eventId===t.eventId),{eventType:i,category:s,categoryType:a}=o||{},{categoryName:c,ageCategoryCode:u}=s||{},p=dr(e.map(({matchUpFormat:d})=>d)),m=0;return Object.keys(p).forEach(d=>{let l=p[d],f=Fp({categoryName:c||u,tournamentId:t.tournamentId,eventId:t.eventId,tournamentRecords:n,matchUpFormat:d,categoryType:a,eventType:i});if(f.error)return f;let g=f.averageMinutes*l;isNaN(m)||(m+=g)}),{roundMinutes:m}}function sv(t){return(t||[]).reduce((e,r)=>{let n=(r.finishingPositionRange?.winner||[]).reduce((i,s)=>i+s,0),o=(r.finishingPositionRange?.winner||[]).join("-")||"";return!e.minFinishingSum||n<e.minFinishingSum?{minFinishingSum:n,winnerFinishingPositionRange:o}:e},{minFinishingSum:0,winnerFinishingPositionRange:""})}function HD(t){let e=t.length,r=t.filter(({sides:p})=>p?.some(({bye:m})=>m)).length||0,n=t.filter(({winningSide:p,matchUpStatus:m})=>p||ae.includes(m)).length||0,o=t.filter(({schedule:p,matchUpStatus:m})=>p?.scheduledDate&&p?.scheduledTime&&m!==Dt).length||0,i=e-r,s=i===n,a=i-o,c=i-o;return{unscheduledCount:a,incompleteCount:c,scheduledCount:o,completedCount:n,matchUpsCount:e,isScheduled:i===o,isComplete:s,byeCount:r}}function kd({tournamentRecords:t,schedulingProfile:e,tournamentRecord:r,withRoundId:n}){if(r&&!t){if(typeof r!="object")return{error:Ba};t={[r.tournamentId]:r}}if(e){let s=Gp({tournamentRecords:t,schedulingProfile:e});if(s.error)return s}if(!e&&t){let s=ko({tournamentRecords:t});if(s.error)return s;e=s.schedulingProfile}if(!e)return{error:Ke};let o={};return{profileRounds:e.map(({venues:s,scheduleDate:a})=>s.map(({rounds:c})=>c.map(u=>{let p=Pg(u);return p.roundSegment?.segmentsCount&&(o[p.id]=p.roundSegment.segmentsCount),rt({id:n?p.id:void 0,scheduleDate:a,...p})}))).flat(1/0),segmentedRounds:o}}var jD={};Jt(jD,{getEntriesAndSeedsCount:()=>Vd,getMaxEntryPosition:()=>OT});function Vd({policyDefinitions:t,drawDefinition:e,drawSize:r,drawId:n,event:o,stage:i}){if(!o)return{error:Et};let{entries:s,stageEntries:a}=vh({drawDefinition:e,drawId:n,stage:i,event:o}),c=a.length,{drawSize:u}=bS({participantsCount:c}),p=Du({drawSize:r??u,participantsCount:c,policyDefinitions:t});if(p.error)return _({result:p,stack:"getEntriesAndSeedsCount"});let{seedsCount:m}=p;return{entries:s,seedsCount:m,stageEntries:a}}function OT(t){let{entries:e=[],entryStatus:r,stage:n}=t;return Math.max(...e.filter(o=>(!n||n===o.entryStage)&&(!r||o.entryStatus===r)&&!isNaN(o.entryPosition)).map(({entryPosition:o})=>ct(o||0)),0)}var KD={};Jt(KD,{allCompetitionMatchUps:()=>cn,allDrawMatchUps:()=>rr,allEventMatchUps:()=>co,allTournamentMatchUps:()=>le,analyzeMatchUp:()=>Vp,calculateWinCriteria:()=>Is,checkMatchUpIsComplete:()=>is,competitionScheduleMatchUps:()=>Ou,drawMatchUps:()=>WT,eventMatchUps:()=>Wd,getAllDrawMatchUps:()=>re,getAllStructureMatchUps:()=>At,getCheckedInParticipantIds:()=>es,getCompetitionMatchUps:()=>kp,getEventMatchUpFormatTiming:()=>wT,getMatchUpCompetitiveProfile:()=>su,getMatchUpContextIds:()=>kT,getMatchUpDailyLimits:()=>Yd,getMatchUpDailyLimitsUpdate:()=>LT,getMatchUpDependencies:()=>Vr,getMatchUpFormat:()=>VT,getMatchUpFormatTiming:()=>au,getMatchUpFormatTimingUpdate:()=>vT,getMatchUpScheduleDetails:()=>Wm,getMatchUpType:()=>qm,getMatchUpsStats:()=>BT,getModifiedMatchUpFormatTiming:()=>Bd,getParticipantResults:()=>Su,getPredictiveAccuracy:()=>GT,getRoundMatchUps:()=>He,getRounds:()=>HT,isValidMatchUpFormat:()=>Sr,matchUpActions:()=>hd,participantScheduledMatchUps:()=>FT,tallyParticipantResults:()=>Ca,tournamentMatchUps:()=>jd,validMatchUp:()=>yf,validMatchUps:()=>Ur});function _T({tournamentRecords:t,extensionName:e}){if(typeof t!="object"||!Object.keys(t).length)return{error:Ft};let r=[],n;for(let o of Object.values(t)){let{extension:i}=mt({element:o,name:e});i&&!n&&(r.push({params:{extension:i,discover:!0},method:"addExtension"}),n=!0);let s=o.events??[];for(let a of s){let{eventId:c}=a,{extension:u}=mt({name:e,element:a});u&&r.push({params:{eventId:c,extension:u},method:"addEventExtension"})}}return{methods:r}}function vT({tournamentRecords:t}){return _T({extensionName:Oo,tournamentRecords:t})}var YD="ADULT",qD="JUNIOR",xT="WHEELCHAIR",$D={[go]:{allowModificationWhenMatchUpsScheduled:{courts:!1,venues:!1},defaultTimes:{averageTimes:[{categoryNames:[],minutes:{default:90}}],recoveryTimes:[{minutes:{[Gt]:30,default:60}}]},defaultDailyLimits:{[Xt]:2,[Gt]:2,total:3},matchUpAverageTimes:[{matchUpFormatCodes:[un],averageTimes:[{categoryNames:[],minutes:{default:90}},{categoryTypes:[xT],minutes:{default:120}}]},{matchUpFormatCodes:["SET3-S:6/TB7-F:TB10"],averageTimes:[{categoryNames:[],minutes:{default:85}}]},{matchUpFormatCodes:["SET3-S:6/TB7-F:TB7"],averageTimes:[{categoryNames:[],minutes:{default:70}}]},{matchUpFormatCodes:["SET3-S:4NOAD-F:TB7"],averageTimes:[{categoryNames:[],minutes:{default:55}}]},{matchUpFormatCodes:["SET3-S:4/TB7"],averageTimes:[{categoryNames:[],minutes:{default:60}}]},{matchUpFormatCodes:["SET3-S:4/TB7-F:TB7"],averageTimes:[{categoryNames:[],minutes:{default:50}}]},{matchUpFormatCodes:["SET3-S:4/TB7-F:TB10"],averageTimes:[{categoryNames:[],minutes:{default:55}}]},{matchUpFormatCodes:["SET3-S:4/TB5@3"],averageTimes:[{categoryNames:[],minutes:{default:45}}]},{matchUpFormatCodes:["SET1-S:8/TB7","SET1-S:8/TB7@7"],averageTimes:[{categoryNames:[],minutes:{default:40}}]},{matchUpFormatCodes:["SET1-S:5/TB9@4"],averageTimes:[{categoryNames:[],minutes:{default:30}}]},{matchUpFormatCodes:["SET1-S:6/TB7"],averageTimes:[{categoryNames:[],minutes:{default:30}}]},{matchUpFormatCodes:["SET1-S:6NOAD"],averageTimes:[{categoryNames:[],minutes:{default:30}}]},{matchUpFormatCodes:["SET1-S:4/TB7","SET1-S:4/TB5@3","SET3-S:TB10","SET1-S:T20"],averageTimes:[{categoryNames:[],minutes:{default:20}}]},{matchUpFormatCodes:["SET1-S:4NOAD"],averageTimes:[{categoryNames:[],minutes:{default:20}}]},{matchUpFormatCodes:["SET1-S:TB10"],averageTimes:[{categoryNames:[],minutes:{default:10}}]}],matchUpRecoveryTimes:[{matchUpFormatCodes:["SET3-S:6/TB7","SET3-S:6/TB7-F:TB10","SET3-S:6/TB7-F:TB7"],recoveryTimes:[{categoryTypes:[YD,xT],minutes:{default:60,[Gt]:30}},{categoryTypes:[qD],minutes:{default:60,[Gt]:60}}]},{matchUpFormatCodes:["SET3-S:4/TB7-F:TB7","SET3-S:4/TB7-F:TB10","SET3-S:4NOAD-F:TB7","SET3-S:4/TB7","SET3-S:4/TB5@3"],recoveryTimes:[{categoryTypes:[YD,xT],minutes:{default:30}},{categoryTypes:[qD],minutes:{default:60}}]},{matchUpFormatCodes:["SET1-S:8/TB7","SET1-S:8/TB7@7","SET1-S:5/TB9@4","SET1-S:6/TB7","SET1-S:6NOAD","SET1-S:4/TB7","SET1-S:4NOAD","SET3-S:TB10","SET1-S:T20"],recoveryTimes:[{categoryNames:[],minutes:{default:30}}]},{matchUpFormatCodes:["SET1-S:4/TB5@3"],recoveryTimes:[{categoryTypes:[YD,qD],minutes:{default:30}},{categoryTypes:[xT],minutes:{default:15}}]},{matchUpFormatCodes:["SET1-S:TB10"],recoveryTimes:[{categoryNames:[],minutes:{default:15}}]}],matchUpDailyLimits:[]}},av=$D;function wT({tournamentRecord:t,matchUpFormats:e,categoryType:r,event:n}){if(!n)return{error:Et};let o=[],i;if(e?.length){let m=[];o=e.map(d=>{let l=typeof d=="string"?{matchUpFormat:d}:d;if(!m.includes(l?.matchUpFormat)&&Sr({matchUpFormat:l?.matchUpFormat}))return m.push(l.matchUpFormat),l}).filter(Boolean)}else{let{policy:m}=$o({policyType:vn,tournamentRecord:t,event:n});if(m?.matchUpFormats)o=m?.matchUpFormats;else{let{extension:d}=mt({name:Oo,element:n}),l,f;d?.value?{matchUpAverageTimes:l,matchUpRecoveryTimes:f}=d.value:{matchUpAverageTimes:l,matchUpRecoveryTimes:f}=av[go],o=pt([...(l||[]).map(g=>g.matchUpFormatCodes),...(f||[]).map(g=>g.matchUpFormatCodes)].flat()).map(g=>({matchUpFormat:g})),i="default scheduling policy in use"}}let{eventType:s,eventId:a,category:c}=n,u=c?.categoryName??c?.ageCategoryCode??a;if(!a)return{error:Et};let p=o.map(({matchUpFormat:m,description:d})=>{let l=au({tournamentRecord:t,matchUpFormat:m,categoryName:u,categoryType:r,eventType:s,event:n});return{matchUpFormat:m,description:d,...l}});return rt({eventMatchUpFormatTiming:p,info:i})}function Bd(t){let e=lt(t,[{[An]:!0},{[yn]:g=>Sr({matchUpFormat:g}),[En]:Ya,[mm]:!0}]);if(e.error)return e;let{tournamentRecord:r,matchUpFormat:n,event:o}=t,{extension:i}=mt({name:Oo,element:o}),s=i?.value,{extension:a}=mt({element:r,name:Oo}),c=a?.value,u=s?.matchUpAverageTimes&&pp({...s,matchUpFormat:n}),p=c?.matchUpAverageTimes&&pp({...c,matchUpFormat:n}),m=[u,p].find(g=>g),d=s?.matchUpRecoveryTimes&&mp({...s,matchUpFormat:n}),l=c?.matchUpRecoveryTimes&&mp({...c,matchUpFormat:n}),f=[d,l].find(g=>g);return{matchUpFormat:n,recoveryTimes:f,averageTimes:m}}function LT({tournamentRecords:t}){return _T({extensionName:Yc,tournamentRecords:t})}var va=({scheduleAttributes:t=["scheduledDate","scheduledTime"],schedule:e={}})=>!!Object.keys(e).filter(n=>t.includes(n)).filter(n=>e[n]).length;function FT({scheduleAttributes:t=["scheduledDate","scheduledTime"],matchUps:e=[]}){if(!Ur(e))return{error:Sn};if(!Array.isArray(t))return{error:G};let r=e.filter(Boolean).filter(({schedule:o})=>va({schedule:o,scheduleAttributes:t})).reduce((o,i)=>{let{schedule:s}=i,a=Ut(s?.scheduledDate),c=$t(s?.scheduledTime);return a&&c&&(o[a]?o[a].push(i):o[a]=[i]),o},{});return Object.keys(r).forEach(o=>{r[o].sort((i,s)=>GI($t(i.schedule?.scheduledTime),$t(s.schedule?.scheduledTime)))}),{...R,scheduledMatchUps:r}}function cv({tournamentRecords:t}){let e=[],r={};for(let n of Object.values(t))for(let o of n.events??[]){let i=vr({event:o}),s=i?.drawDetails;Rt(s)?(Object.assign(r,s),e.push(...Object.keys(s).filter(a=>Qm({drawId:a,drawDetails:s})))):i?.drawIds?.length&&e.push(...i.drawIds)}return{drawIds:e,detailsMap:r}}function Hd({schedulingProfile:t,matchUps:e=[]}){let r={},n=({eventId:a,drawId:c,structureId:u,roundNumber:p})=>`${a}|${c}|${u}${p}`;t?.length&&t.map(({venues:c})=>c.map(({rounds:u})=>u)).flat().forEach(c=>{c.sort((p,m)=>(p.sortOrder||0)-(m.sortOrder||0)).forEach(({eventId:p,drawId:m,structureId:d,roundNumber:l},f)=>{let g=n({eventId:p,drawId:m,structureId:d,roundNumber:l});r[g]=f})});let o=[],i={noScheduledDate:[]};for(let a of e){let c=a.schedule||{},u=c.scheduledDate&&Ut(c.scheduledDate)||c.scheduledTime&&Ut(c.scheduledTime)||"noScheduledDate";i[u]||(i[u]=[]),i[u].push(a)}let s=Object.keys(i).sort();for(let a of s){let c=i[a],u={noScheduledTime:[]};for(let m of c){let d=m.schedule||{},l=d.scheduledTime&&$t(d.scheduledTime)||"noScheduledTime";u[l]||(u[l]=[]),u[l].push(m)}let p=Object.keys(u).sort();for(let m of p){let d=u[m];d.sort((l,f)=>{let g=r[n(l)]||0,I=r[n(f)]||0;return g-I}),o.push(...d)}}return o}function Dg({courtPrefix:t="C|",minRowsCount:e,courtsData:r}){if(!Array.isArray(r))return{error:G};let n=r?.reduce((s,a)=>{let c=a.matchUps||[],u=Math.max(0,...c.map(p=>p.schedule.courtOrder||0));return u>s?u:s},1),o=e?Math.max(e,n):n,i=Z(0,o).map(s=>({matchUps:Z(0,r.length).map(a=>{let c=r[a],{courtId:u,venueId:p}=c;return{schedule:{courtOrder:s+1,venueId:p,courtId:u}}})}));return r.forEach((s,a)=>{for(let c of s.matchUps){let u=c.schedule?.courtOrder;u&&(i[u-1].matchUps[a]=c)}}),{courtPrefix:t,rows:i.map((s,a)=>Object.assign({rowId:`rowId-${a+1}`},...s.matchUps.map((c,u)=>({[`${t}${u}`]:c}))))}}function Wd(t){let{participants:e,contextContent:r,participantMap:n}=t,{tournamentAppliedPolicies:o,scheduleVisibilityFilters:i,participantsProfile:s,afterRecoveryTimes:a,policyDefinitions:c,useParticipantMap:u,tournamentRecord:p,usePublishState:m,contextFilters:d,matchUpFilters:l,contextProfile:f,nextMatchUps:g,tournamentId:I,inContext:h,context:S,event:T}=t;if(!T)return{error:Et};let{eventId:A,eventName:D,endDate:y,eventType:E,category:U,gender:M}=T??{},P={...S,...rt({surfaceCategory:T.surfaceCategory??p?.surfaceCategory,indoorOutDoor:T.indoorOutdoor??p?.indoorOutdoor,tournamentId:I??p?.tournamentId,endDate:y??p?.endDate,eventName:D,eventType:E,category:U,eventId:A,gender:M})},N;!e&&p&&({participants:e,participantMap:n,groupInfo:N}=Ii({participantsProfile:s,policyDefinitions:c,useParticipantMap:u,tournamentRecord:p,contextProfile:f,inContext:h})),f&&!r&&(r=Ln({policyDefinitions:c,tournamentRecord:p,contextProfile:f,event:T}));let C=vr({event:T});return{...(T.drawDefinitions??[]).reduce((x,w)=>{let F=Vs({context:P,tournamentAppliedPolicies:o,scheduleVisibilityFilters:i,tournamentParticipants:e,participantsProfile:s,afterRecoveryTimes:a,policyDefinitions:c,tournamentRecord:p,usePublishState:m,contextContent:r,contextFilters:d,matchUpFilters:l,participantMap:n,publishStatus:C,contextProfile:f,drawDefinition:w,nextMatchUps:g,inContext:h,event:T});return Object.keys(F)?.forEach(v=>{Array.isArray(F[v])&&(x[v]||(x[v]=[]),x[v]=x[v].concat(F[v]))}),x},{}),...R,groupInfo:N}}function jd(t){if(!t?.tournamentRecord)return{error:W};let e=t.contextContent,{scheduleVisibilityFilters:r,participantsProfile:n,afterRecoveryTimes:o,policyDefinitions:i,useParticipantMap:s,tournamentRecord:a,inContext:c=!0,usePublishState:u,contextFilters:p,matchUpFilters:m,contextProfile:d,nextMatchUps:l,context:f}=t,g=t.tournamentId??a.tournamentId,I=a?.events??[],{participants:h,participantMap:S,groupInfo:T}=Ii({participantsProfile:n,policyDefinitions:i,useParticipantMap:s,tournamentRecord:a,contextProfile:d,inContext:c});d&&!e&&(e=Ln({policyDefinitions:i,tournamentRecord:a,contextProfile:d}));let{appliedPolicies:A}=Pt({tournamentRecord:a}),D=p?.eventIds??[];return{...I.filter(U=>!D.includes(U.eventId)).map(U=>{let P={eventDrawsCount:Ht({event:U}).flightProfile?.flights?.length||U.drawDefinitions?.length||0,...f};return Wd({context:P,tournamentAppliedPolicies:A,scheduleVisibilityFilters:r,participantsProfile:n,afterRecoveryTimes:o,policyDefinitions:i,tournamentRecord:a,usePublishState:u,contextFilters:p,contextProfile:d,contextContent:e,matchUpFilters:m,participantMap:S,participants:h,tournamentId:g,nextMatchUps:l,inContext:c,event:U})}).reduce((U,M)=>((M&&Object.keys(M).filter(N=>!["success","matchUpsMap"].includes(N)))?.forEach(N=>{Array.isArray(M[N])&&(U[N]||(U[N]=[]),U[N]=U[N].concat(M[N]),U.matchUpsCount+=M[N].length)}),U),{matchUpsCount:0}),groupInfo:T}}function kp({scheduleVisibilityFilters:t,participantsProfile:e,tournamentRecords:r,policyDefinitions:n,usePublishState:o,matchUpFilters:i,contextFilters:s,nextMatchUps:a,inContext:c}){if(typeof r!="object"||!Object.keys(r).length)return{error:Ft};let p=Object.keys(r).map(l=>{let f=r[l];return jd({scheduleVisibilityFilters:t,participantsProfile:e,policyDefinitions:n,tournamentRecord:f,usePublishState:o,matchUpFilters:i,contextFilters:s,nextMatchUps:a,inContext:c})}),m={};return{...p.reduce((l,f)=>(Object.keys(f).forEach(I=>{Array.isArray(f[I])&&(l[I]||(l[I]=[]),l[I]=l[I].concat(f[I])),I==="groupInfo"&&Object.assign(m,f[I])}),l),{}),groupInfo:m}}function Ou(t){if(typeof t?.tournamentRecords!="object"||!Object.keys(t?.tournamentRecords).length)return{error:Ft};let{courts:e,venues:r}=po(t),o=ko(t).schedulingProfile,{sortDateMatchUps:i=!0,courtCompletedMatchUps:s,alwaysReturnCompleted:a,activeTournamentId:c,tournamentRecords:u,withCourtGridRows:p,minCourtGridRows:m,usePublishState:d,status:l=Gr,sortCourtsData:f}=t,g=d?mu({tournamentRecord:u[c??$i()],itemType:`${Ko}.${zo}`}).timeItem?.itemValue?.[l]:void 0,I=a?kp({...t,matchUpFilters:{...t.matchUpFilters,matchUpStatuses:[me]},contextFilters:t.contextFilters}).completedMatchUps:[];if(d&&(!g||!Object.keys(g).length))return{completedMatchUps:I,dateMatchUps:[],courtsData:[],venues:r};let h,S;d&&({drawIds:h,detailsMap:S}=cv({tournamentRecords:u})),h?.length&&(t.contextFilters||(t.contextFilters={}),t.contextFilters?.drawIds?t.contextFilters.drawIds=t.contextFilters.drawIds.filter(C=>h.includes(C)):t.contextFilters.drawIds=h),g?.eventIds?.length&&(t.matchUpFilters||(t.matchUpFilters={}),t.matchUpFilters?.eventIds&&t.matchUpFilters.eventIds.length?t.matchUpFilters.eventIds=t.matchUpFilters.eventIds.filter(C=>g.eventIds.includes(C)):t.matchUpFilters.eventIds=g.eventIds),g?.scheduledDates?.length&&(t.matchUpFilters||(t.matchUpFilters={}),t.matchUpFilters.scheduledDates&&t.matchUpFilters.scheduledDates.length?t.matchUpFilters.scheduledDates=t.matchUpFilters.scheduledDates.filter(C=>g.scheduledDates.includes(C)):t.matchUpFilters.scheduledDates=g.scheduledDates),a&&(t.matchUpFilters||(t.matchUpFilters={}),t.matchUpFilters?.excludeMatchUpStatuses?.length?t.matchUpFilters.excludeMatchUpStatuses.includes(me)||t.matchUpFilters.excludeMatchUpStatuses.push(me):t.matchUpFilters.excludeMatchUpStatuses=[me]);let{completedMatchUps:T,upcomingMatchUps:A,pendingMatchUps:D,groupInfo:y}=kp({...t,matchUpFilters:t.matchUpFilters,contextFilters:t.contextFilters}),E=[...A??[],...D??[]];S&&Object.keys(S).length&&(E=E.filter(C=>{let{drawId:O,structureId:b,stage:x}=C;if(!S[O])return!1;if(S[O].stageDetails){let w=Object.keys(S[O].stageDetails),F=w.filter(v=>!S[O].stageDetails[v].published),L=w.filter(v=>S[O].stageDetails[v].published);return F.length&&F.includes(x)?!1:L.length&&L.includes(x)?!0:F.length&&!F.includes(x)&&!L.length}if(S[O].structureDetails){let w=Object.keys(S[O].structureDetails),F=w.filter(v=>!S[O].structureDetails[v].published),L=w.filter(v=>S[O].structureDetails[v].published);return F.length&&F.includes(b)?!1:L.length&&L.includes(b)?!0:F.length&&!F.includes(b)&&!L.length}return!0}));let U=i?Hd({matchUps:E,schedulingProfile:o}):E,M=e?.map(C=>{let O=N(C);return{surfaceCategory:C?.surfaceCategory??"",matchUps:O,...C}}),P={completedMatchUps:a?I:T,dateMatchUps:U,courtsData:M,groupInfo:y,venues:r};if(p){let{rows:C,courtPrefix:O}=Dg({minRowsCount:m,courtsData:M});P.courtPrefix=O,P.rows=C}return{...P,...R};function N({courtId:C}){let b=(s?U.concat(T??[]):U).filter(x=>x.schedule?.courtId===C||x.schedule?.allocatedCourts?.map(({courtId:w})=>w).includes(C));return f?Hd({matchUps:b,schedulingProfile:o}):b}}function Yd({tournamentRecords:t,tournamentId:e}){if(typeof t!="object"||!Object.keys(t).length)return{error:Ft};let r=Object.keys(t).filter(o=>!e||o===e),n;return r.forEach(o=>{let i=t[o],{matchUpDailyLimits:s}=sV({tournamentRecord:i});n=s}),{matchUpDailyLimits:n}}function sV(t){let e=lt(t,[{[An]:!0}]);if(e.error)return e;let{tournamentRecord:r}=t,{policy:n}=$o({policyType:go,tournamentRecord:r}),{extension:o}=mt({element:r,name:Yc}),i=o?.value?.dailyLimits,s=n?.defaultDailyLimits;return{matchUpDailyLimits:i||s}}function GT(t){let{matchUps:e}=t,{singlesForDoubles:r,tournamentRecord:n,drawDefinition:o,excludeMargin:i,exclusionRule:s,zoneDoubling:a,matchUpType:c,scaleName:u,eventId:p,zonePct:m,drawId:d,event:l}=t;if(!n&&!e)return{error:W};if(c&&![Xt,Gt].includes(c))return{error:G,info:{matchUpType:c}};if(e&&!Ur(e))return{error:G,context:{matchUps:e}};let f=Br[u],g=f?.ascending??t.ascending??!1,I=f?.accessor??t.valueAccessor,h=Array.isArray(f?.range)?Math.abs(f.range[0]-f.range[1]):0,S=ft(m)&&h?(m??0/100)*h:t.zoneMargin??h,T={withScaleValues:!0,withCompetitiveness:!0},A={matchUpTypes:c?[c]:[Xt,Gt]},D=n?.participants;e?.[0]?.hasContext?d?e=e.filter(b=>b.drawId===d):p&&(e=e.filter(b=>b.eventId===p)):e===void 0&&(e=d&&!o&&[]||!d&&p&&!l&&[]||d&&rr({inContext:!0,drawDefinition:o,contextFilters:A,contextProfile:T,participants:D})?.matchUps||!d&&p&&co({inContext:!0,contextFilters:A,contextProfile:T,participants:D,event:l})?.matchUps||le({tournamentRecord:n,contextFilters:A,contextProfile:T})?.matchUps||[]),c&&(e=e.filter(b=>b.matchUpType===c));let y=e.filter(({winningSide:b,score:x,sides:w,matchUpStatus:F})=>![lr,Ot,_t,Kc,$r].includes(F??"")&&Ie({score:x})&&w?.length===2&&b),E=cV({matchUps:y,excludeMargin:i,exclusionRule:s,valueAccessor:I,ascending:g,scaleName:u}),U=!a||ie(Xt)(c)?S:(S||0)*2,M=S?y.map(({competitiveProfile:b,matchUpType:x,score:w,sides:F})=>{let L=pv({singlesForDoubles:r,valueAccessor:I,matchUpType:x,scaleName:u,sides:F}),v=Math.abs(L[0].value-L[1].value);return{competitiveness:b?.competitiveness,valuesGap:v,score:w}}).filter(({valuesGap:b})=>b<=U):[],P=aV({zoneData:M}),N=P&&[].concat(Object.values(P)).flat().length,C=N&&Object.assign({},...Object.keys(P).map(b=>({[b]:Math.round(1e4*P[b].length/N)/100}))),O=y.length-(M?.length||0);return{...R,relevantMatchUps:y,zoneDistribution:C,zoneData:M,accuracy:E,nonZone:O}}function aV({zoneData:t}){let e={[Fm]:[],[sc]:[],[ac]:[]};for(let r of t){let{competitiveness:n,score:o,valuesGap:i}=r;e[n]&&e[n].push({score:o,valuesGap:i})}return e}function pv({singlesForDoubles:t,exclusionRule:e,valueAccessor:r,matchUpType:n,scaleName:o,sides:i}){let s=e?.range.sort(),a=c=>{let u=c?.[e?.valueAccessor];return{exclude:e&&u>=s[0]&&u<=s[1],exclusionValue:u}};return i.sort((c,u)=>c.sideNumber-u.sideNumber).map(({participant:c})=>{let u=[],p=c?.individualParticipants;if(p?.length){let m=[],d=0;for(let l of p){let{scaleValue:f,value:g}=uv({singlesForDoubles:t,valueAccessor:r,participant:l,matchUpType:n,scaleName:o}),{exclude:I,exclusionValue:h}=a(f);I&&u.push(h),m.push(f),g&&!isNaN(d)?d+=g:d=void 0}return{participantName:c.participantName,exclusionValues:u,scaleValues:m,value:d}}else if(c){let{scaleValue:m,value:d}=uv({singlesForDoubles:t,valueAccessor:r,matchUpType:n,participant:c,scaleName:o}),{exclude:l,exclusionValue:f}=a(m);return l&&u.push(f),{participantName:c.participantName,exclusionValues:u,scaleValue:m,value:d}}else return{}})}function uv({singlesForDoubles:t,valueAccessor:e,matchUpType:r,participant:n,scaleName:o}){let i=t?Xt:r,s=n?.rankings?.[i]?.find(p=>p.scaleName===o),c=(n?.ratings?.[i]?.find(p=>p.scaleName===o)||s)?.scaleValue,u=e?c?.[e]:c;return{scaleValue:c,value:u}}function cV({excludeMargin:t,exclusionRule:e,valueAccessor:r,ascending:n,scaleName:o,matchUps:i}){let s={affirmative:[],negative:[],excluded:[]};for(let u of i){let{matchUpType:p,sides:m,score:d,winningSide:l}=u;if(!l)continue;if(e&&(!e.valueAccessor||!e.range))return{info:"exclusionRule requires valueAccessor and range",error:et};let f=l-1,g=pv({exclusionRule:e,valueAccessor:r,matchUpType:p,scaleName:o,sides:m});if(e){let D=g.map(({exclusionValues:y})=>y).flat();if(D.length){s.excluded.push({scoreString:d?.scoreStringSide1,exclusionValues:D,winningSide:l,sideValues:g});continue}}if(g.filter(D=>![void 0,"",null].includes(D.value)).length<2){s.excluded.push({scoreString:d?.scoreStringSide1,missingValues:!0,winningSide:l,sideValues:g});continue}let I=g[f].value-g[1-f].value,h=parseFloat(t||0),S=h&&Math.abs(I)<h;if(S){s.excluded.push({scoreString:d?.scoreStringSide1,excludeMargin:t,winningSide:l,excludeGap:S,sideValues:g,valuesGap:I});continue}let T=n?I:I*-1,A=l===1?d?.scoreStringSide1:d?.scoreStringSide2;T>0?s.affirmative.push({winningScoreString:A,winningSide:l,sideValues:g,valuesGap:I,score:d}):s.negative.push({winningScoreString:A,winningSide:l,sideValues:g,valuesGap:I,score:d})}let a=s.affirmative.length+s.negative.length,c=a&&s.affirmative.length/a*100;return s.percent=c?Math.round(100*c)/100:0,s}function Is({collectionDefinitions:t=[],collectionGroups:e=[]}){let r=0,{groupValueNumbers:n}=sS({collectionGroups:e}),o;for(let s of t||[]){let{collectionValueProfiles:a,collectionGroupNumber:c,collectionValue:u,matchUpCount:p,matchUpValue:m,scoreValue:d,setValue:l}=s,f=c&&n.includes(c);if(ft(l||d))o=!0;else{if(f)continue;if(typeof u=="number"&&ft(u))r+=u;else if(a?.length)for(let g of a)r+=g.matchUpValue;else typeof m=="number"&&ft(m)&&(r+=(p??0)*m)}}for(let s of e)r+=s.groupValue??0;return o||!r?{aggregateValue:!0,...R}:{valueGoal:Math.floor(r/2)+1,...R}}function kT({matchUps:t,matchUpId:e}){if(!Ur(t))return{error:G};let r=t.find(a=>a.matchUpId===e),{drawId:n,eventId:o,structureId:i,tournamentId:s}=r||{};return{matchUpId:e,drawId:n,eventId:o,structureId:i,tournamentId:s}}function xa(t,e){if(!Rt(t))return{error:G};if(!Array.isArray(e))return{error:G};let r={};for(let{param:n,error:o,attr:i}of e){let s=uV({params:t,param:n,attr:i,error:o});if(s?.error)return s;r[n]=s}return r}function uV({params:t,param:e,attr:r,error:n}){if(e===ql&&Rt(t.drawDefinition)&&$e(t.structureId)){let o=(t.drawDefinition.structures??[]).find(({structureId:i})=>i===t.structureId);return!o.length&&n?{error:n}:{structure:o}}if(e===fo){let o=wD({...t,...r});return o.error&&n?{...o,error:n}:o}return{error:Ke,info:{param:e}}}function VT(t){let{structureId:e,matchUpId:r,event:n}=t,o=t.drawDefinition,i=lt(t,[{[An]:!0},{[fm]:{[dm]:!1,[Co]:!1,[OI]:!1,[Cs]:!1}}]);if(i[Ms])return i;let a=xa(t,[{[sa]:fo,[Ms]:et}])?.matchUp;if(r&&a?.error)return a;!o&&a?.drawDefinition&&(o=a?.drawDefinition);let c=a?.structure;if(!c&&e&&!r){if(!o)return{error:Wr};let l=st({drawDefinition:o,structureId:e});if(l.error)return l;c=l.structure}let u=c?.matchUpFormat,p=o?.matchUpFormat,m=n?.matchUpFormat,d=a?.matchUp?.matchUpFormat||u||p||m;return{structureDefaultMatchUpFormat:u,eventDefaultMatchUpFormat:m,drawDefaultMatchUpFormat:p,matchUpFormat:d}}function BT({profileBands:t,tournamentRecord:e,matchUps:r}){if(!Ur(r))return{error:Sn};let n=!t&&$o({policyType:ii,tournamentRecord:e}).policy,o=t||n?.profileBands||km[ii].profileBands,i=r.filter(({winningSide:d})=>d),s=i.map(sh),a=(d,l)=>{let f=ih(l,o);return d[f]+=1,d},c=ah(s).reduce((d,l)=>a(d,l),{[Fm]:0,[sc]:0,[ac]:0,[oh]:0}),u=Object.keys(c).reduce((d,l)=>(c[l]||0)+d,0),p=Object.keys(c).map(d=>{let l=parseFloat((c[d]/u).toFixed(4));return{[d]:l*100}}),m=i.filter(({matchUpStatus:d})=>d===QE).length;return p.push({[QE]:parseFloat((m/u).toFixed(4))*100}),{competitiveBands:Object.assign({},...p),...R}}var{stageOrder:mv}=TR;function dv(t,e){return t.eventName.localeCompare(e.eventName)||t.eventId.localeCompare(e.eventId)||(mv[t?.stage]||0)-(mv[e?.stage]||0)||e.matchUpsCount-t.matchUpsCount||`${t.stageSequence}-${t.roundNumber}-${t.minFinishingSum}`.localeCompare(`${e.stageSequence}-${e.roundNumber}-${e.minFinishingSum}`)}function HT({excludeScheduleDateProfileRounds:t,excludeScheduledRounds:e,excludeCompletedRounds:r,inContextMatchUps:n,tournamentRecords:o,schedulingProfile:i,tournamentRecord:s,withSplitRounds:a,matchUpFilters:c,scheduleDate:u,withRoundId:p,venueId:m,context:d}){if(n&&!Array.isArray(n||typeof n[0]!="object"))return{error:G,inContextMatchUps:n};if(s&&!o){if(typeof s!="object")return{error:Ba};o={[s.tournamentId]:s}}let l=typeof o!="object"||!Object.keys(o).length;if((m||u||!n||!i&&(t||r||i||a))&&l)return{error:Ft};let g=Object.assign({},...Object.values(o??{}).map(({venues:E=[],tournamentId:U})=>({[U]:E?.map(({venueId:M})=>M)}))),I=Object.values(o??{}).map(({events:E=[],tournamentId:U,startDate:M,endDate:P})=>E.map(N=>({...N,validVenueIds:g[U],startDate:N.startDate??M,endDate:N.endDate??P}))).flat(),{segmentedRounds:h,profileRounds:S}=o&&(t||r||i||a)&&kd({tournamentRecords:o,schedulingProfile:i})||{},T=t&&Object.assign({},...S.map(E=>({[E.id]:E}))),A=n||o&&cn({tournamentRecords:o,matchUpFilters:c})?.matchUps||[],D=[],y=A&&Object.values(A.reduce((E,U)=>{let M=Pg(U).id,P=h?.[M],N=[...E[M]?.matchUps??[],U],{containerStructureId:C,stageSequence:O,structureName:b,tournamentId:x,isRoundRobin:w,matchUpType:F,roundNumber:L,roundOffset:v,structureId:B,eventName:H,roundName:j,drawName:V,eventId:Y,drawId:$}=U,k=w?C:B;return{...E,[M]:{id:p?M:void 0,structureId:k,stageSequence:O,segmentsCount:P,structureName:b,tournamentId:x,matchUpType:F,roundNumber:L,roundOffset:v,eventName:H,roundName:j,drawName:V,matchUps:N,eventId:Y,drawId:$}}},{})).map(E=>{let{minFinishingSum:U,winnerFinishingPositionRange:M}=sv(E.matchUps),P=E.segmentsCount;if(P){let L=E.matchUps.length/P;return Te(E.matchUps.sort((B,H)=>B.roundPosition-H.roundPosition),L).map((B,H)=>{let{unscheduledCount:j,incompleteCount:V,matchUpsCount:Y,isScheduled:$,isComplete:k,byeCount:K}=HD(B),z=BD({matchUps:E.matchUps,tournamentRecords:o,events:I,round:E});return rt({...E,...d,roundSegment:{segmentsCount:P,segmentNumber:H+1},winnerFinishingPositionRange:M,unscheduledCount:j,incompleteCount:V,minFinishingSum:U,matchUpsCount:Y,isScheduled:$,roundTiming:z,isComplete:k,byeCount:K,matchUps:B})})}let{unscheduledCount:N,incompleteCount:C,matchUpsCount:O,isScheduled:b,isComplete:x,byeCount:w}=HD(E.matchUps),F=BD({matchUps:E.matchUps,tournamentRecords:o,events:I,round:E});return rt({...E,...d,winnerFinishingPositionRange:M,unscheduledCount:N,incompleteCount:C,minFinishingSum:U,matchUpsCount:O,isScheduled:b,roundTiming:F,isComplete:x,byeCount:w})}).flat().filter(E=>{if(t){let B=Ut(t),H=p?E.id:Pg(E).id;if(B&&T[H]&&Ut(T[H].scheduleDate)===B)return!1}let{isComplete:U,isScheduled:M}=E,P=!r||!U,N=!e||!M,C=m||u?I?.find(({eventId:B})=>B===E.eventId):void 0,O=C?.startDate??s?.startDate,b=C?.endDate??s?.endDate,x=!u||!O||new Date(u)>=new Date(O),w=!u||!b||new Date(u)<=new Date(b),F=x&&w,L=!m||C?.validVenueIds.includes(m),v=P&&N&&L&&F;return v||D.push(E),v}).sort(dv)||[];return{...R,rounds:y,excludedRounds:D}}function Vp(t){let{matchUp:e,sideNumber:r,setNumber:n,isTiebreakValue:o,isPointValue:i}=t||{},{matchUpFormat:s}=t||{};if(!e)return{error:sr};s=s||e?.matchUpFormat;let a=tr(s),c=!!e?.winningSide,u=e.score?.sets,p=u?.length,m=n&&n-1,d=!!u?.find(($,k)=>$.setNumber===n&&k===m),l=u?.filter($=>$?.winningSide)||[],f=l?.length||0,g=n&&u?.slice(n)||[],I=!!(p&&n&&g?.reduce(($,k)=>(!k||!k.side1Score&&!k.side2Score&&!k.side1TiebreakScore&&!k.side2TiebreakScore&&!k.side1PointScore&&!k.side2PointScore)&&$,!0)),h=n<=p&&u.find($=>$.setNumber===n),S=h&&Ru({setObject:h,matchUpScoringFormat:a}),{isCompletedSet:T,sideGameScores:A,sideTiebreakScores:D}=S||{},y=!!(h&&!T&&I||n&&n===p+1&&!c),E=[1,2].includes(r),U=E?r-1:0,M=h&&E&&(!o&&!i&&A[U]!==void 0&&A[U]||o&&D[U]!==void 0&&D[U]),P=!!M,N=l?.map($=>Ru({setObject:$,matchUpScoringFormat:a}).isValidSetOutcome).reduce(($,k)=>$&&k,!0),C=l.reduce(($,k)=>{let{winningSide:K}=k,z=K-1;return $[z]++,$},[0,0]),O=e?.winningSide,b=O&&O-1,x=1-b,w=C[b],F=C[x],L=Math.max(...C),v=dr(C)[L],{bestOf:B}=a??{},H=B&&Math.ceil(B/2)||1,j=L===H&&v===1&&C.indexOf(L)+1||void 0,V=w>F&&O===j;return{completedSetsHaveValidOutcomes:N,validMatchUpWinningSide:V,calculatedWinningSide:j,matchUpScoringFormat:a,validMatchUpOutcome:j&&N&&V,isLastSetWithValues:I,completedSetsCount:f,isCompletedMatchUp:c,isValidSideNumber:E,hasExistingValue:P,existingValue:M,isExistingSet:d,isActiveSet:y,...S}}function WT({participants:t,tournamentAppliedPolicies:e,scheduleVisibilityFilters:r,participantsProfile:n,afterRecoveryTimes:o,policyDefinitions:i,useParticipantMap:s,tournamentRecord:a,usePublishState:c,contextFilters:u,contextContent:p,matchUpFilters:m,participantMap:d,publishStatus:l,contextProfile:f,drawDefinition:g,nextMatchUps:I,tournamentId:h,inContext:S,context:T,event:A}){let{eventId:D,eventName:y,endDate:E,eventType:U,category:M,gender:P}=A??{},N={...T,...rt({surfaceCategory:A?.surfaceCategory??a?.surfaceCategory,indoorOutDoor:A?.indoorOutdoor??a?.indoorOutdoor,endDate:E??A?.endDate??a?.endDate,tournamentId:h??a?.tournamentId,eventName:y,eventType:U,category:M,eventId:D,gender:P})},C;return!t?.length&&a&&({participants:t,participantMap:d,groupInfo:C}=Ii({participantsProfile:n,policyDefinitions:i,useParticipantMap:s,tournamentRecord:a,contextProfile:f,inContext:S})),A&&f&&!p&&(p=Ln({policyDefinitions:i,tournamentRecord:a,contextProfile:f,drawDefinition:g,event:A})),{...Vs({context:N,tournamentAppliedPolicies:e,scheduleVisibilityFilters:r,tournamentParticipants:t,participantsProfile:n,afterRecoveryTimes:o,policyDefinitions:i,tournamentRecord:a,usePublishState:c,participantMap:d,contextContent:p,contextFilters:u,matchUpFilters:m,publishStatus:l,contextProfile:f,drawDefinition:g,nextMatchUps:I,inContext:S,event:A}),groupInfo:C}}var zD={};Jt(zD,{getCompetitionVenues:()=>Lp,getCourts:()=>jT,getVenuesAndCourts:()=>po,publicFindVenue:()=>Th});function jT({tournamentRecord:t,venueId:e,venueIds:r}){return t?{courts:(t.venues||[]).filter(o=>e?o.venueId===e:r?r.includes(o.venueId):!0).map(o=>{let{venueId:i}=o,s=J(o.courts||[]);return s.forEach(a=>Object.assign(a,{venueId:i})),s}).flat()}:{error:W}}var QD={};Jt(QD,{categoryCanContain:()=>dd,getCategoryAgeDetails:()=>Au,getEvent:()=>$T,getEventProperties:()=>YT,getEventStructures:()=>Qf,getEventTimeItem:()=>pu,getEvents:()=>qT,getFlightProfile:()=>Ht,getScaledEntries:()=>Qs});function YT({tournamentRecord:t,event:e}){if(!t)return{error:W};if(!e)return{error:Et};let r=e.entries||[],n=t.participants||[],o=e.category?.categoryName||e.category?.ageCategoryCode,{eventType:i}=e,s=r.map(d=>d.participantId),a=n.filter(d=>s.includes(d.participantId)),c,u,p;return{entryScaleAttributes:a.map(d=>{let{participantId:l,participantName:f,name:g}=d,I={scaleType:Of,eventType:i,scaleName:o},h=uo({participant:d,scaleAttributes:I})?.scaleItem?.scaleValue;I={scaleType:tU,eventType:i,scaleName:o};let S=uo({participant:d,scaleAttributes:I})?.scaleItem?.scaleValue;I={scaleType:ZE,eventType:i,scaleName:o};let T=uo({participant:d,scaleAttributes:I})?.scaleItem?.scaleValue;return c=!!(c||h),u=!!(u||S),p=!!(p||T),{participantId:l,participantName:f||g,seed:h,ranking:S,rating:T}}),hasSeededParticipants:c,hasRankedParticipants:u,hasRatedParticipants:p}}function qT({tournamentRecord:t,withScaleValues:e,scaleEventType:r,inContext:n,eventIds:o,drawIds:i,context:s}){if(!t)return{error:W};let{tournamentId:a}=t,c=(t.events??[]).filter(({eventId:p})=>!o||Array.isArray(o)&&o.includes(p)).map(p=>{let m=p.drawDefinitions?.map($c);if(i?.length&&!jt(i,m).length)return;let d=J(p);return n&&Object.assign(d,{tournamentId:a}),s&&Object.assign(d,s),d}).filter(Boolean),u={};if(e){let p=Yt({withScaleValues:!0,tournamentRecord:t}).participantMap,m=d=>d.reduce((l,f)=>l+parseFloat(f),0);for(let d of c){let l=r??d.eventType,f=d.eventId;u[f]||(u[f]={ratingsStats:{},ratings:{},ranking:{},draws:{}});let I=(d.entries??[]).filter(({entryStatus:E})=>Or.includes(E)).map(gt),h=E=>{if(E?.ratings?.[l])for(let U of E?.ratings?.[l]??[]){let M=U.scaleName;u[f].ratings[M]||(u[f].ratings[M]=[]);let P=Br[M]?.accessor;if(P){let N=parseFloat(U.scaleValue?.[P]);N&&u[f].ratings[M].push(N)}}if(E?.rankings?.[l])for(let U of E?.rankings?.[l]??[]){let M=U.scaleName;u[f].ranking[M]||(u[f].ranking[M]=[]),U.scaleValue&&u[f].ranking[M].push(U.scaleValue)}};for(let E of I){let U=p?.[E]?.participant;if(U?.participantType!==ht)for(let M of U?.individualParticipantIds??[]){let P=p?.[M]?.participant;h(P)}else h(U)}let S=u[f].ratings;for(let E of Object.keys(S)){let U=S[E];if(!U.length)continue;let M=iE(U)?.toFixed(2);u[f].ratingsStats[E]={avg:parseFloat((m(U)/U.length).toFixed(2)),median:M?parseFloat(M):void 0,max:Math.max(...U),min:Math.min(...U)}}let T=(E,U)=>{let M=P=>{if(u[f].draws?.[E]&&P?.ratings?.[l])for(let N of P?.ratings?.[l]??[]){let C=N.scaleName;u[f].draws[E]?.ratings[C]||(u[f].draws[E].ratings[C]=[]);let O=Br[C]?.accessor;if(O){let b=parseFloat(N.scaleValue?.[O]);b&&u[f].draws[E].ratings[C].push(b)}}if(u[f].draws?.[E]&&P?.rankings?.[l])for(let N of P?.rankings?.[l]??[]){let C=N.scaleName;u[f].draws[E]?.ranking[C]||(u[f].draws[E].ranking[C]=[]);let O=N.scaleValue;O&&u[f].draws[E].ranking[C].push(O)}};for(let P of U.filter(Boolean)){let N=p?.[P]?.participant;if(N?.participantType!==ht)for(let C of N?.individualParticipantIds??[]){let O=p?.[C]?.participant;M(O)}else M(N)}},A=[],D=E=>i?.length&&i.includes(E)||A.includes(E);for(let E of d.drawDefinitions??[]){let U=E.drawId;if(D(U))continue;let M=Si({drawDefinition:E}).assignedParticipantIds??[];u[f].draws[U]||(u[f].draws[U]={ratingsStats:{},ratings:{},ranking:{}}),A.push(U),T(U,M)}let y=Ht({event:d}).flightProfile;for(let E of y?.flights??[]){let U=E.drawId;if(D(U))continue;let M=E.drawEntries.map(gt);T(U,M)}for(let E of A){let U=u[f].draws[E].ratings;for(let M of Object.keys(U)){let P=U[M];if(!P.length)continue;let N=iE(P)?.toFixed(2);u[f].draws[E].ratingsStats[M]={avg:parseFloat((m(P)/P.length).toFixed(2)),median:N?parseFloat(N):void 0,max:Math.max(...P),min:Math.min(...P)}}}}}return rt({eventScaleValues:u,events:c,...R})}function $T({tournamentRecord:t,drawDefinition:e,context:r,event:n}){if(!t)return{error:W};if(!n)return{error:Et};let o=J(n);r&&Object.assign(o,r);let i=e&&o.drawDefinitions?.find(({drawId:s})=>e.drawId===s);return rt({drawDefinition:i,event:o})}function lv(t){let e="validateAndDeriveDrawValues",{appliedPolicies:r,policyDefinitions:n}=dV(t),o=lV({...t,policyDefinitions:n,appliedPolicies:r}),i=mV(t),s=fV({...t,consideredEntries:i,appliedPolicies:r});if(s?.error)return _({result:s,stack:e});let a=gV({...t,consideredEntries:i}),c=pV({...t,appliedPolicies:r,policyDefinitions:n,drawSize:a});if(c.error)return _({result:c,stack:e});let u=c.drawType;if(isNaN(a)&&u!==an)return _({result:{error:ja},stack:e});let p=n?.[Un]??r?.[Un],m=t.seedingProfile??p?.seedingProfile?.drawTypes?.[u??""]??p?.seedingProfile;t.seedingProfile&&(n[Un]||(n[Un]={...Eg[Un]}),n[Un].seedingProfile=m);let d=IV({...t,drawType:u});return d?.error?_({result:d,stack:e}):{drawSize:a,drawType:u,enforceGender:o,seedingProfile:m,appliedPolicies:r,policyDefinitions:n}}function pV(t){let{policyDefinitions:e,appliedPolicies:r,enforceMinimumDrawSize:n=!0,drawSize:o}=t,i=t.drawTypeCoercion??Pu({drawType:t.drawType,policyDefinitions:e,appliedPolicies:r}),s=_S({drawType:t.drawType,enforceMinimumDrawSize:n,drawTypeCoercion:i,drawSize:o});return s.error?s:{drawType:s.drawType}}function JD(t){return t?.filter(e=>e.entryStatus&&[...Or,Lm].includes(e.entryStatus))}function mV({considerEventEntries:t=!0,drawEntries:e,eventEntries:r,qualifyingOnly:n}){return(n&&[]||JD(e)||(t?r:[])).filter(({entryStage:o})=>!o||o===tt)}function dV(t){let{tournamentRecord:e,event:r}=t,n=Pt({tournamentRecord:e,event:r}).appliedPolicies??{},o=J(t.policyDefinitions??{},!1,!0);return{appliedPolicies:n,policyDefinitions:o}}function lV({enforceGender:t,policyDefinitions:e,appliedPolicies:r}){return t??e?.[ze]?.participants?.enforceGender??r?.[ze]?.participants?.enforceGender}function fV(t){let{consideredEntries:e,appliedPolicies:r,policyDefinitions:n,enforceGender:o,participantMap:i,participants:s,event:a}=t;return a&&s&&Sd({consideredEntries:e,policyDefinitions:n,appliedPolicies:r,participantMap:i,enforceGender:o,participants:s,event:a})}function gV(t){return!t.drawSize&&t.consideredEntries.length&&![an,Jc,la,dn,so].includes(t.drawType??"")&&qi(t.consideredEntries.length)||t.drawSize&&ct(t.drawSize)||!1}function IV(t){let{tournamentRecord:e,event:r,ignoreAllowedDrawTypes:n,drawType:o}=t,i=!n&&e&&vd({tournamentRecord:e,categoryType:r?.category?.categoryType,categoryName:r?.category?.categoryName});return i?.length&&!i.includes(o)?{error:nm}:{...R}}function _u(t){let{voluntaryConsolation:e,tournamentRecord:r,event:n}=t,o="generateDrawDefinition",{participants:i,participantMap:s}=Yt({withIndividualParticipants:!0,convertExtensions:!0,internalUse:!0,tournamentRecord:r}),a=JD(n?.entries)??[],c=lv({...t,participantMap:s,participants:i,eventEntries:a});if(c.error)return _({result:c,stack:o});let{appliedPolicies:u,policyDefinitions:p,drawSize:m,drawType:d,enforceGender:l,seedingProfile:f}=c,g=n?.eventType,I=t.matchUpType??g,h=V_({...t,enforceGender:l,eventType:g,matchUpType:I});if(h.error)return _({result:h,stack:o});let{matchUpFormat:S,tieFormat:T}=h;if(t.drawId&&typeof t.drawId!="string")return _({result:{error:G},stack:o});let D=tv({...t,isMock:t.isMock??!0,policyDefinitions:p,tournamentRecord:r,appliedPolicies:u,matchUpFormat:S,seedingProfile:f,participants:i,eventEntries:a,matchUpType:I,tieFormat:T,drawSize:m,drawType:d,event:n});if(D.error)return _({result:D,stack:o});let{existingDrawDefinition:y,positioningReports:E,drawDefinition:U,structureId:M,conflicts:P,entries:N}=D;if(!U)return _({result:{error:G},stack:o});let C=ev({...t,existingDrawDefinition:y,positioningReports:E,appliedPolicies:u,drawDefinition:U,seedingProfile:f,participants:i,structureId:M,entries:N,params:t,stack:o});if(C.error)return C;let{qualifyingConflicts:O}=C;return U.drawName=t.drawName??(d&&Ye(d)),m&&typeof e=="object"&&m>=4&&jf({...e,drawDefinition:U,matchUpType:I}),{existingDrawDefinition:!!y,qualifyingConflicts:O,positioningReports:E,drawDefinition:U,structureId:M,...R,conflicts:P}}function KT({scaleAttributes:t,scaledEntries:e,stageEntries:r,seedsCount:n,scaleName:o}){if(!t)return{error:et,info:"missing scaleAttributes"};let i=Object.assign({},...(e||[]).slice(0,n).map(({participantId:c},u)=>({[c]:u+1})));o=o||t.scaleName;let s=new Date().toISOString();return{scaleItemsWithParticipantIds:r.map(({participantId:c})=>({scaleItems:[{scaleValue:i[c],eventType:t.eventType,scaleType:eo,scaleName:o,scaleDate:s}],participantId:c}))}}function fv({tournamentRecord:t,drawDefinition:e,policyDefinitions:r,scaleAttributes:n,scaleName:o,drawSize:i,drawId:s,event:a,stage:c,sortDescending:u,scaleSortMethod:p}){let m=Vd({policyDefinitions:r,drawDefinition:e,drawSize:i,drawId:s,event:a,stage:c});if(m.error)return m;let{entries:d,seedsCount:l,stageEntries:f}=m;if(!f||!l)return{error:G};let g=Qs({tournamentRecord:t,scaleAttributes:n,scaleSortMethod:p,sortDescending:u,entries:d,stage:c}).scaledEntries??[],{scaleItemsWithParticipantIds:I}=KT({scaleAttributes:n,scaledEntries:g,stageEntries:f,seedsCount:l,scaleName:o});return{scaleItemsWithParticipantIds:I}}var sN={};Jt(sN,{addDrawEntries:()=>Vf,addEventEntries:()=>Kn,addEventEntryPairs:()=>nN,destroyPairEntries:()=>yU,destroyPairEntry:()=>Wf,getEntriesAndSeedsCount:()=>Vd,getMaxEntryPosition:()=>OT,modifyEntriesStatus:()=>zm,modifyEventEntries:()=>oN,mutate:()=>iN,promoteAlternate:()=>eN,promoteAlternates:()=>QT,query:()=>jD,removeDrawEntries:()=>rN,removeEventEntries:()=>fc,setEntryPosition:()=>zT,setEntryPositions:()=>tN});var iN={};Jt(iN,{addDrawEntries:()=>Vf,addEventEntries:()=>Kn,addEventEntryPairs:()=>nN,destroyPairEntries:()=>yU,destroyPairEntry:()=>Wf,modifyEntriesStatus:()=>zm,modifyEventEntries:()=>oN,promoteAlternate:()=>eN,promoteAlternates:()=>QT,removeDrawEntries:()=>rN,removeEventEntries:()=>fc,setEntryPosition:()=>zT,setEntryPositions:()=>tN});function zT({tournamentRecord:t,drawDefinition:e,participantId:r,entryPosition:n,skipRefresh:o,event:i}){let s="setEntryPositions";if(!t)return{error:W};if(!r)return _({result:{error:oe},stack:s});if(n!==void 0&&!Number.isSafeInteger(n))return{error:G,entryPosition:n};(i?.entries||[]).forEach(c=>{c.participantId===r&&(c.entryPosition=n)}),(e?.entries||[]).forEach(c=>{c.participantId===r&&(c.entryPosition=n)});let a=c=>{c.entries.forEach(u=>{u.entryPosition===n&&u.participantId!==r&&(u.entryPosition+=.1)})};return o||(i?.entries&&(a(i),i.entries=Vn({entries:i.entries})),e?.entries&&(a(e),e.entries=Vn({entries:e.entries}))),{...R}}function tN({tournamentRecord:t,entryPositions:e,drawDefinition:r,event:n}){if(!t)return{error:W};if(!Array.isArray(e))return{error:G};for(let o of e){let{participantId:i,entryPosition:s}=o,a=zT({skipRefresh:!0,tournamentRecord:t,drawDefinition:r,participantId:i,entryPosition:s,event:n});if(a.error)return a}return n?.entries&&(n.entries=Vn({entries:n.entries})),r?.entries&&(r.entries=Vn({entries:r.entries})),{...R}}function eN(t){let{participantId:e}=t;return e&&typeof e!="string"?{error:G,participantId:e}:QT({...t,participantIds:[e].filter(Boolean)})}function QT({tournamentRecord:t,drawDefinition:e,participantIds:r,stageSequence:n,stage:o=tt,eventId:i,event:s}){if(!t)return{error:W};if(!Array.isArray(r))return{error:G,participantIds:r};if(!s)return{error:Et};let a="promoteAlternates";if(s){let c=gv({element:s,participantIds:r,stageSequence:n,stage:o});if(c.error)return c}if(e){let c=gv({element:e,participantIds:r,stageSequence:n,stage:o});if(c.error)return i?_({context:{drawPromotionError:c.error,drawId:e.drawId},result:{...R},stack:a}):c}return{...R}}function gv({participantIds:t,stageSequence:e,element:r,stage:n}){let o=(r.entries||[]).filter(m=>m.entryStatus===wr),i=(r.entries||[]).filter(m=>t.includes(m.participantId)),s=o.reduce((m,d)=>{let{entryPosition:l}=d;return isNaN(l)&&m||(!m||l<m.entryPosition)&&d||m},void 0),a=i.length?i:[s].filter(Boolean);if(!a?.length)return{error:hI};let c=a.filter(({entryStatus:m})=>m!==wr);if(c.length)return{error:Ml,invalidEntryStatus:c};let u=a.filter(({entryStage:m})=>m&&m!==n);if(u.length)return{error:vC,invalidStage:u};let p=e&&a.filter(m=>m.stageSequence!==e);if(p?.length)return{error:xC,invalidStageSequence:p};for(let m of a){m.entryStatus=Zr;let d=m?.entryPosition;isNaN(d)||r.entries.forEach(f=>{f.entryStatus===wr&&f.entryPosition>d&&(f.entryPosition=f.entryPosition-1)});let l=Math.max(...r.entries.filter(f=>f.entryStatus===Zr&&!isNaN(f.entryPosition)).map(({entryPosition:f})=>ct(f||0)),0);m.entryPosition=l||0}return{...R}}function rN({autoEntryPositions:t=!0,participantIds:e,drawDefinition:r,drawId:n,stages:o,event:i}){if(!i)return{error:Et};if(!n)return{error:Wr};if(!e?.length)return{error:lo};let s=Si({drawDefinition:r,stages:o}).assignedParticipantIds??[];if(xe(s,e))return{error:Ps};let c=m=>{let d=m.participantId;return!e.includes(d)},{flightProfile:u}=Ht({event:i}),p=u?.flights?.find(m=>m.drawId===n);return p?.drawEntries&&(p.drawEntries=p.drawEntries.filter(c),t&&(p.drawEntries=Vn({entries:p.drawEntries}))),r?.entries&&(r.entries=r.entries.filter(c),t&&(r.entries=Vn({entries:r.entries}))),{...R}}function gn(t){let e="addParticipant",{allowDuplicateParticipantIdPairs:r,returnParticipant:n,disableNotice:o,pairOverride:i,participant:s}=t,a=t.tournamentId?t.tournamentRecords?.[t.tournamentId]:t.tournamentRecord??(t.activeTournamentId&&t.tournamentRecords?.[t.activeTournamentId]);if(!a)return{error:W};if(!s)return _({result:{error:Mi},stack:e});s.participantId||(s.participantId=Mt()),a.participants||(a.participants=[]);let{participantId:c,individualParticipantIds:u}=s;if(a.participants.reduce((I,h)=>h.participantId===c||I,!1))return{error:Oy};let{participantType:m,participantRole:d}=s;if(!m||!Object.keys(nu).includes(m))return{error:nn,participantType:m};if(!d)return{error:by};let l=a.participants||[],f=l.filter(I=>I.participantType===ht).map(I=>I.participantId);if(m!==ht&&s.person)return{error:G,person:s.person};if(u&&!Array.isArray(u))return{error:G,individualParticipantIds:u};if(m===dt){if(s.person)return{error:G,person:s.person};if(s.individualParticipantIds){if(s.individualParticipantIds.length!==2&&!i)return _({info:"PAIR must be 2 individualParticipantIds",result:{error:zr},stack:e});{let S=l.filter(A=>A.participantType===ht).map(A=>A.participantId);if(!Array.isArray(s.individualParticipantIds))return _({result:{error:zr},stack:e});if(!s.individualParticipantIds.reduce((A,D)=>S.includes(D)&&A,!0))return _({result:{error:zr},stack:e})}}else return _({result:{error:lo},stack:e});let I=l.filter(S=>S.participantType===dt).map(S=>({individualParticipantIds:S.individualParticipantIds,participant:S})),h=s.participantType===dt&&I.find(S=>jt(S.individualParticipantIds,s.individualParticipantIds).length===2);if(h&&!r)return{...R,existingParticipant:!0,participant:n&&J(h.participant)};if(!s.participantName){let S=l.filter(A=>s.individualParticipantIds?.includes(A.participantId)),T=S.map(A=>A.person?.standardFamilyName).filter(Boolean).join("/");S.length===1&&(T+="/Unknown"),s.participantName=T}}else if(m===ht){if(!s.person?.standardFamilyName||!s.person?.standardGivenName)return{error:wy};if(!s.participantName){let I=`${s.person.standardFamilyName.toUpperCase()}, ${s.person.standardGivenName}`;s.participantName=I}}else if(m&&[kt,Ar].includes(m)){if(u||(s.individualParticipantIds=[]),s.individualParticipantIds?.length)for(let I of s.individualParticipantIds){if(typeof I!="string")return _({result:{participantId:I,error:G},stack:e});if(!f.includes(I))return _({result:{participantId:I,error:Zt},stack:e})}}else return{error:nn};a.participants.push(s),o||Tt({payload:{tournamentId:a.tournamentId,participants:[s]},topic:jo});let g={participant:n&&J(s),...R};return rt(g)}function In({allowDuplicateParticipantIdPairs:t,returnParticipants:e,tournamentRecord:r,participants:n=[]}){if(!r)return{error:W};r.participants||(r.participants=[]);let i=r.participants.map(d=>d.participantId)||[];n.forEach(d=>{d.participantId||(d.participantId=Mt())});let s=n.filter(d=>!i.includes(d.participantId)),a=n.filter(d=>i.includes(d.participantId)),c=s.filter(d=>d.participantType===ht),u=s.filter(d=>d.participantType!==ht),p=c.concat(...u),m=[];if(p.length){for(let l of p){let f=gn({allowDuplicateParticipantIdPairs:t,returnParticipant:!0,disableNotice:!0,tournamentRecord:r,participant:l});if(f.error)return f;f.success&&!f.existingParticipant&&m.push(f.participant)}m.length&&Tt({topic:jo,payload:{tournamentId:r.tournamentId,participants:m}});let d={participants:e&&J(m),addedCount:m.length,...R};return a.length&&Object.assign(d,{notAdded:a,info:Wu}),rt(d)}else return{info:"No new participants to add",addedCount:0,...R}}function nN({allowDuplicateParticipantIdPairs:t,entryStage:e=tt,entryStatus:r=wr,participantIdPairs:n=[],tournamentRecord:o,drawDefinition:i,event:s,uuids:a}){if(!o)return{error:W};if(!s)return{error:Et};if(s.eventType!==Gt)return{error:No};let c=[],u=new Map;for(let S of o.participants??[]){let{participantType:T,participantId:A,person:D,individualParticipantIds:y}=S;T===ht&&D?.sex?u.set(A,D.sex):T===dt&&y&&c.push(y)}let p=n.filter(S=>{if(S.length!==2||!u.has(S[0])||!u.has(S[1]))return!0;if(!s.gender||s.gender===Fn)return!1;let T=S.map(D=>u.get(D)),A=s.gender===ee&&(T[0]!==ee||T[1]!==ee)||s.gender===ue&&(T[0]!==ue||T[1]!==ue);return s.gender===_r&&(T.sort(du),(T[0]!==ue||T[1]!==ee)&&(A=!0)),A});if(p.length)return{error:zr,invalidParticipantIdPairs:p};let m=n.map(S=>({participantId:a?.pop()??Mt(),participantRole:Ge,individualParticipantIds:S,participantType:dt})),d=t?m:m.filter(S=>!c.find(T=>jt(T,S.individualParticipantIds).length===2)),l,f=[];if(d){let S=In({allowDuplicateParticipantIdPairs:t,participants:d,returnParticipants:!0,tournamentRecord:o});if(S.error)return S;f=S.participants||[],l=S.info}let g=n.map(S=>{let T=f.find(D=>jt(D.individualParticipantIds,S).length===2);if(T)return T;let{participant:A}=tn({tournamentRecord:o,participantIds:S});return A}).map(S=>S.participantId),I=Kn({participantIds:g,tournamentRecord:o,drawDefinition:i,entryStatus:r,entryStage:e,event:s});d.length&&Tt({payload:{participants:d},topic:jo});let h=d.map(gt);return{...I,info:l,newParticipantIds:h}}function oN({entryStatus:t=Zr,unpairedParticipantIds:e=[],participantIdPairs:r=[],entryStage:n=tt,tournamentRecord:o,event:i}){if(!o)return{error:W};if(!i)return{error:Et};let s=o.participants??[],a=s.filter(h=>h.participantType===ht).map(h=>h.participantId),u=e.concat(...r).flat(1/0).filter(h=>!a.includes(h));if(u.length)return{error:zr,invalidParticipantIds:u};let p=r.filter(h=>h.length!==2);if(p.length)return{error:zr,invalidParticipantIdPairs:p};let m=s.filter(h=>h.participantType===dt).map(h=>h.individualParticipantIds),l=r.filter(h=>!m.find(S=>jt(S,h).length===2)).map(h=>({participantType:dt,participantRole:Ge,individualParticipantIds:h})),f=In({participants:l,tournamentRecord:o});if(f.error)return f;let g=r.map(h=>{let{participant:S}=tn({tournamentRecord:o,participantIds:h});return S}).map(h=>({participantId:h,entryStatus:t,entryStage:n})),I=e.map(h=>({entryStatus:Lr,participantId:h,entryStage:n}));return i.entries=(i.entries??[]).filter(h=>h.entryStage===n),i.entries=i.entries.concat(...g,...I),{...R}}var TN={};Jt(TN,{addDrawDefinition:()=>Hp,addEvent:()=>Mc,addFlight:()=>Wp,assignSeedPositions:()=>fN,attachFlightProfile:()=>Rg,categoryCanContain:()=>dd,deleteDrawDefinitions:()=>Bp,deleteEvents:()=>IN,deleteFlightAndFlightDraw:()=>dN,deleteFlightProfileAndFlightDraws:()=>uN,getCategoryAgeDetails:()=>Au,getEvent:()=>$T,getEventProperties:()=>YT,getEventStructures:()=>Qf,getEventTimeItem:()=>pu,getEvents:()=>qT,getFlightProfile:()=>Ht,getScaledEntries:()=>Qs,modifyEvent:()=>hN,modifyEventMatchUpFormatTiming:()=>pN,modifyPairAssignment:()=>lN,mutate:()=>SN,query:()=>QD,refreshEventDrawOrder:()=>Cg,removeEventMatchUpFormatTiming:()=>qd,removeScaleValues:()=>bg,removeSeeding:()=>gN,setEventDates:()=>mN,setEventDisplay:()=>$d,setEventEndDate:()=>ZT,setEventStartDate:()=>JT,updateDrawIdsOrder:()=>Mg,validateCategory:()=>md});var SN={};Jt(SN,{addDrawDefinition:()=>Hp,addEvent:()=>Mc,addFlight:()=>Wp,assignSeedPositions:()=>fN,attachFlightProfile:()=>Rg,deleteDrawDefinitions:()=>Bp,deleteEvents:()=>IN,deleteFlightAndFlightDraw:()=>dN,deleteFlightProfileAndFlightDraws:()=>uN,modifyEvent:()=>hN,modifyEventMatchUpFormatTiming:()=>pN,modifyPairAssignment:()=>lN,refreshEventDrawOrder:()=>Cg,removeEventMatchUpFormatTiming:()=>qd,removeScaleValues:()=>bg,removeSeeding:()=>gN,setEventDates:()=>mN,setEventDisplay:()=>$d,setEventEndDate:()=>ZT,setEventStartDate:()=>JT,updateDrawIdsOrder:()=>Mg,validateCategory:()=>md});function Xs({removePriorValues:t=!0,status:e=Gr,statusObject:r,event:n}){if(!Rt(r))return{error:G};let o=vr({event:n,status:e}),i=`${Ko}.${zo}`,s={itemValue:{[e]:{...o,...r}},itemType:i};return ki({timeItem:s,removePriorValues:t,event:n})}function Js(t){let{includePositionAssignments:e,removePriorValues:r,tournamentRecord:n,status:o=Gr,event:i,drawIdsToRemove:s,drawIdsToAdd:a}=t;if(!n)return{error:W};if(!i)return{error:Et};let{appliedPolicies:c}=Pt({tournamentRecord:n,event:i}),u={...c,...t.policyDefinitions},p=i.drawDefinitions?.map(({drawId:A})=>A)??[],m=t.drawDetails?Object.keys(t.drawDetails):[],d=m.length?[]:t.drawIds,l=(a??[]).concat(...s??[],...d??[],...m),f=l.filter(A=>!p.includes(A));if(f.length)return _({result:{error:pr},context:{invalidDrawIds:f}});let g=vr({event:i,status:o}),I=Object.keys(g?.drawDetails||{}).filter(A=>p.includes(A)).reduce((A,D)=>(A[D]=g.drawDetails[D],A),{});for(let A of p)if((!l.length||l.includes(A))&&(s?.includes(A)||d?.length&&!d.includes(A)?I[A]={...I[A],publishingDetail:{published:!1}}:(a?.includes(A)||d?.includes(A)||!d?.length)&&(I[A]={...I[A],publishingDetail:{published:!0}})),t.drawDetails?.[A]){let D=t.drawDetails[A],y=D.structureDetails??I[A].structureDetails,E=D.stageDetails??I[A].stageDetails??{},{structureIdsToRemove:U=[],structureIdsToAdd:M=[],publishingDetail:P={},stagesToRemove:N=[],stagesToAdd:C=[]}=D;if((M||C)&&(P.published=!0),I[A]={publishingDetail:P,structureDetails:y,stageDetails:E},M.length||U.length){let b=(i.drawDefinitions?.find(F=>F.drawId===A)?.structures??[]).map(({structureId:F})=>F),w=(M??[]).concat(U??[]).filter(F=>!b.includes(F));if(w.length)return _({result:{error:Lt},context:{invalidStructureIds:w}});y=y??{};for(let F of b)U.includes(F)?y[F]={published:!1}:y[F]={published:!0};I[A].structureDetails=y}let O=(i.drawDefinitions?.find(b=>b.drawId===A)?.structures??[]).map(({stage:b})=>b);if(C.length){for(let b of C)E[b]={published:!0};for(let b of O)E[b]||(E[b]={published:!1})}if(C.length||N.length){for(let b of N)E[b]={published:!1};for(let b of O)E[b]||(E[b]={published:!0})}(C.length||N.length)&&(I[A].stageDetails=E)}Xs({statusObject:{drawDetails:I},removePriorValues:r,status:o,event:i});let{topics:h}=Cr(),S=h.includes(th),T=S||t.returnEventData?Gd({includePositionAssignments:e,usePublishState:!0,tournamentRecord:n,policyDefinitions:u,event:i})?.eventData:void 0;return S&&Tt({payload:{eventData:T,tournamentId:n.tournamentId},topic:th}),{...R,eventData:T}}var aN="deleteDrawDefinitions",cN="autoSchedulingAudit",XT="deleteEvents",Iv={AUTO_SCHEDULING_AUDIT:cN,DELETE_EVENTS:XT,DELETE_DRAW_DEFINITIONS:aN};function Bp(t){if(!t.tournamentRecord)return{error:W};let e="deleteDrawDefinitions",r=t.drawIds??[],n=t.event,{autoPublish:o=!0,tournamentRecord:i,auditData:s,eventId:a,force:c}=t,{appliedPolicies:u}=Pt({tournamentRecord:i,event:n}),p={...u,...t.policyDefinitions},m=Array.isArray(r)?r[0]:void 0;if(!n){let U=We({tournamentRecord:i,eventId:a,drawId:m});if(U.error)return U;n=U.event}let d=[],l=[],f=[];if(!n?.drawDefinitions)return _({info:"event has no drawDefinition",result:{...R},stack:e});let g=n.drawDefinitions.map(({drawId:U})=>U);if(r.length||(r=g),r=r.filter(U=>g.includes(U)),!r.length)return _({info:"nothing to do; no matching drawIds in event.",result:{...R},stack:e});let I=J(Ht({event:n}).flightProfile,!1,!0),h=({participantId:U,drawPosition:M,qualifier:P,bye:N})=>({bye:N,qualifier:P,drawPosition:M,participantId:U}),S=c??u?.[vn]?.allowDeletionWithScoresPresent?.drawDefinitions,T=vr({event:n})??{},A=T.drawIds??(T.drawDetails&&Object.keys(T.drawDetails))??[],D,y=[],E=n.drawDefinitions.filter(U=>{if(r.includes(U.drawId)){let M=rr({event:n,drawDefinition:U})?.matchUps??[];if(M.some(({score:H})=>Ie({score:H}))&&!S)return y.push(U.drawId),!0;let{drawId:N,drawType:C,drawName:O}=U,b=I?.flights?.find(H=>H.drawId===U.drawId);b&&(b.drawEntries=b.drawEntries?.filter(H=>Or.includes(H.entryStatus))),A.includes(N)&&(A=A.filter(H=>H!==N),D=!0);let x=xn({stageSequence:1,drawDefinition:U,stage:tt})?.structures?.[0],F=(x?Cp({structureId:x.structureId,tournamentRecord:i,drawDefinition:U}):void 0)?.positionAssignments?.map(h),L=xn({stage:at,drawDefinition:U})?.structures,v=L?.length?L.map(H=>{let j=H.stageSequence;return{positionAssignments:Cp({structureId:H.structureId,tournamentRecord:i,drawDefinition:U})?.positionAssignments.map(h),stageSequence:j}}):void 0,B={action:aN,payload:{drawDefinitions:[U],eventId:a??n?.eventId,auditData:s}};f.push(B),d.push(rt({tournamentId:i.tournamentId,eventId:a??n?.eventId,qualifyingPositionAssignments:v,positionAssignments:F,auditData:s,drawType:C,drawName:O,drawId:N})),M?.forEach(({matchUpId:H})=>l.push(H))}return!r.includes(U.drawId)});if(y.length&&!c)return _({context:{drawIdsWithScoresPresent:y},result:{error:Ku},stack:e});if(n.drawDefinitions=E,I&&Io({event:n,extension:{name:qr,value:I}}),Nc({tournamentRecord:i}),D){let U={};for(let P of A)U[P]=T.drawDetails?.[P]??{published:!0};let M=Xs({statusObject:{drawDetails:U},event:n});if(M.error)return{error:M.error}}if(f.length&&Tt({topic:fa,payload:f}),l.length&&wn({tournamentId:i?.tournamentId,matchUpIds:l}),r.forEach(U=>{ER({drawId:U})}),hV({event:n,deletedDrawsDetail:d,auditData:s}),o&&D){let U=Js({drawIdsToRemove:r,policyDefinitions:p,tournamentRecord:i,event:n});if(U.error)return{...R,info:U.error}}return{...R}}function hV({event:t,deletedDrawsDetail:e,auditData:r}){let{extension:n}=mt({name:Em,element:t}),o={...r,deletedDrawsDetail:e},i={name:Em,value:Array.isArray(n?.value)?n?.value.concat(o):[o]};St({element:t,extension:i})}function uN({autoPublish:t=!0,tournamentRecord:e,auditData:r,event:n,force:o}){if(!e)return{error:W};if(!n)return{error:Et};let{flightProfile:i}=Ht({event:n});if(i){let s=i.flights?.map(({drawId:c})=>c).filter(Boolean),a=Bp({eventId:n.eventId,tournamentRecord:e,autoPublish:t,auditData:r,drawIds:s,event:n,force:o});return a.error?a:rp({event:n,name:qr})}return{...R}}function Ng(t){let{matchUpFormat:e,recoveryTimes:r,averageTimes:n,tournamentId:o,eventId:i}=t,s=t?.tournamentRecords??(t?.tournamentRecord&&{[t.tournamentRecord.tournamentId]:t.tournamentRecord})??{};if(!Object.keys(s).length)return{error:Ft};let a=Object.keys(s).filter(u=>!o||o===u);if(o&&!a.includes(o))return{error:G};let c;for(let u of a){let p=s[u],{event:m}=We({tournamentRecord:p,eventId:i});i&&m&&(c=!0);let d=SV({tournamentRecord:p,event:m,matchUpFormat:e,averageTimes:n,recoveryTimes:r});if(d.error)return d}return!i||c?{...R}:{error:mr}}function SV({tournamentRecord:t,recoveryTimes:e,matchUpFormat:r,averageTimes:n,event:o}){if(!t)return{error:W};if(n&&!Array.isArray(n))return{error:G};if(e&&!Array.isArray(e))return{error:G};let i=Oo;if(o){let{extension:s}=mt({element:o,name:i}),a=s?.value||{},c=hv({...a,matchUpFormat:r,averageTimes:n,recoveryTimes:e});St({element:o,extension:{name:i,value:c}})}else{let{extension:s}=mt({element:t,name:i}),a=s?.value||{},c=hv({...a,matchUpFormat:r,averageTimes:n,recoveryTimes:e});St({extension:{name:i,value:c},element:t})}return{...R}}function hv(t){let{matchUpRecoveryTimes:e=[],matchUpAverageTimes:r=[],matchUpFormat:n}=t,{averageTimes:o,recoveryTimes:i}=t;o=(o||[]).filter(c=>c?.categoryNames?.length||c?.categoryTypes?.length);let s=o?.length&&r.map(c=>c?.matchUpFormatCodes.includes(n)?{...c,matchUpFormatCodes:c.matchUpFormatCodes?.filter(u=>u!==n)}:c).filter(({matchUpFormatCodes:c})=>c?.length).concat({matchUpFormatCodes:[n],averageTimes:o});i=(i||[]).filter(c=>c?.categoryNames?.length||c?.categoryTypes?.length);let a=i?.length&&e.map(c=>c?.matchUpFormatCodes.includes(n)?{...c,matchUpFormatCodes:c.matchUpFormatCodes?.filter(u=>u!==n)}:c).filter(({matchUpFormatCodes:c,averageTimes:u})=>c?.length||u).concat({matchUpFormatCodes:[n],recoveryTimes:i});return{matchUpAverageTimes:s?.length&&s||r,matchUpRecoveryTimes:a?.length&&a||e}}function pN(t){let{tournamentRecord:e,recoveryMinutes:r,averageMinutes:n,matchUpFormat:o,categoryType:i,eventId:s,event:a}=t;if(!e)return{error:W};if(!Sr({matchUpFormat:o}))return{error:G};if(!a)return{error:Et};let{averageTimes:c=[],recoveryTimes:u=[]}=Bd({tournamentRecord:e,matchUpFormat:o,event:a}),p=a.category,m=p?.categoryName||p?.ageCategoryCode||a?.eventId,d={categoryNames:[m],minutes:{}},l={categoryNames:[m],minutes:{}},f=T=>{if(T.categoryTypes?.includes(i)&&console.log("encountered:",{categoryType:i}),!(T.categoryNames?.includes(m)&&(T.categoryNames=T.categoryNames.filter(A=>A!==m),d={minutes:T.minutes,categoryNames:[m]},!T.categoryNames.length)))return T},g=n&&!isNaN(ct(n)),I=r&&!isNaN(ct(r)),h=c.map(f).filter(T=>T?.categoryNames?.length),S=u.map(f).filter(T=>T?.categoryNames?.length);return g&&(Object.assign(d.minutes,{[a?.eventType||Xt]:n}),h.push(d)),I&&(Object.assign(l.minutes,{[a?.eventType||Xt]:r}),S.push(l)),!g&&!I?{error:G}:Ng({averageTimes:g&&h,recoveryTimes:I&&S,tournamentRecord:e,matchUpFormat:o,eventId:s,event:a})}function qd(t){if(t.event)return Sv({event:t.event});{t.tournamentRecord&&!t.tournamentRecords&&(t.tournamentRecords={[t.tournamentRecord.tournamentId]:t.tournamentRecord});let e=lt(t,[{[ye]:!0,[bI]:!0}]);if(e.error)return e;let{tournamentRecords:r,eventId:n}=t;for(let o of Object.values(r??{})){let{event:i}=We({tournamentRecord:o,eventId:n});if(i)return Sv({event:i})}}return{error:mr}}function Sv({event:t}){return rp({event:t,name:Oo})}function JT({tournamentRecord:t,event:e,startDate:r}){if(!t)return{error:W};if(!e)return{error:Et};if(!Ro.test(r))return{error:ar};let n=Tv(t);if(n.error)return n;let{tournamentStartDate:o,tournamentEndDate:i}=n,s=new Date(Ut(r)).getTime();if(!o||!i||s<o||s>i)return{error:ar};let a=e.endDate&&new Date(Ut(e.endDate)).getTime();return a&&s>a&&(e.endDate=r),e.startDate=r,{...R}}function ZT({tournamentRecord:t,event:e,endDate:r}){if(!t)return{error:W};if(!e)return{error:Et};if(!Ro.test(r))return{error:ar};let n=Tv(t);if(n.error)return n;let{tournamentStartDate:o,tournamentEndDate:i}=n,s=new Date(Ut(r)).getTime();if(!o||!i||s<o||s>i)return{error:ar};let a=e.startDate&&new Date(Ut(e.startDate)).getTime();return a&&s<a&&(e.startDate=r),e.endDate=r,{...R}}function mN({tournamentRecord:t,event:e,startDate:r,endDate:n}){if(!t)return{error:W};if(!e)return{error:Et};if(!r&&!n)return{error:et,info:"missing date"};if(r&&!Ro.test(r))return{error:ar};if(n&&!Ro.test(n))return{error:ar};if(r&&n){let o=new Date(Ut(r)).getTime(),i=new Date(Ut(n)).getTime();if(o>i)return{error:G}}if(r){let o=JT({tournamentRecord:t,event:e,startDate:r});if(o.error)return o}if(n){let o=ZT({tournamentRecord:t,event:e,endDate:n});if(o.error)return o}return{...R}}function Tv(t){let{startDate:e,endDate:r}=t;return!Ro.test(e)||!Ro.test(r)?_({result:{error:Ny},context:{startDate:e,endDate:r}}):{tournamentStartDate:new Date(Ut(e)).getTime(),tournamentEndDate:new Date(Ut(r)).getTime()}}function Mg({event:t,orderedDrawIdsMap:e}){if(typeof t!="object")return{error:Et};if(!e)return{error:et,info:"Missing drawIdsOrderMap"};if(typeof e!="object")return{error:G,info:"orderedDrawIdsMap must be an object"};let r=Object.values(e);if(!r.every(i=>!isNaN(i)))return{error:G,info:"drawOrder must be numeric"};if(pt(r).length!==r.length)return{error:G,info:"drawOrder values must be unique"};if(t.drawDefinitions?.length){let i=(t.drawDefinitions||[]).map(({drawId:a})=>a),s=Object.keys(e);if(s?.length&&jt(i,s).length!==i.length)return{error:G,info:"Missing drawIds"};t.drawDefinitions.forEach(a=>{a.drawOrder=e[a.drawId]})}let{flightProfile:o}=Ht({event:t});return o?.flights?.forEach(i=>{i.flightNumber=e[i.drawId]}),{...R}}function Cg({tournamentRecord:t,event:e}){if(!t)return{error:W};if(!e)return{error:Et};let{flightProfile:r}=Ht({event:e}),n=r?.flights&&Object.assign({},...r.flights.sort((o,i)=>o.flightNumber-i.flightNumber).map((o,i)=>({[o.drawId]:i+1})))||e.drawDefinitions?.length&&Object.assign({},...e.drawDefinitions.sort((o,i)=>o.drawOrder-i.drawOrder).map((o,i)=>({[o.drawId]:i+1})))||void 0;return n?Mg({event:e,orderedDrawIdsMap:n}):{...R}}function dN({autoPublish:t=!0,tournamentRecord:e,auditData:r,drawId:n,event:o,force:i}){if(!e)return{error:W};if(!n)return{error:Wr};if(!o)return{error:Et};let{flightProfile:s}=Ht({event:o});if(s&&s.flights?.find(u=>u.drawId===n)){let u=s.flights.filter(m=>m.drawId!==n),p={name:qr,value:{...s,flights:u}};Io({event:o,extension:p})}if(o.drawDefinitions?.find(c=>c.drawId===n)){let c=Bp({drawIds:[n],eventId:o.eventId,tournamentRecord:e,autoPublish:t,auditData:r,event:o,force:i});if(c.error)return c}return Cg({tournamentRecord:e,event:o})}function lN({replacementIndividualParticipantId:t,existingIndividualParticipantId:e,tournamentRecord:r,drawDefinition:n,participantId:o,event:i,uuids:s}){if(!i)return{error:Et};if(i?.eventType!==Kr)return{error:No};if(s&&!Array.isArray(s))return{error:G};if(!r)return{error:W};if(![t,e,o].every(g=>typeof g=="string"))return{error:oe};if(!(i?.entries?.filter(({entryStatus:g})=>[Lr,pi].includes(g)).map(({participantId:g})=>g)||[]).includes(t))return{error:pn};let c=(r.participants||[]).find(g=>g.participantId===o);if(c?.participantType!==dt)return{error:Us,participant:c};let u=c.individualParticipantIds,p=[t,...u.filter(g=>g!==e)],{participant:m}=tn({participantIds:p,tournamentRecord:r}),d;if(m)d=m.participantId;else{let g={participantId:s?.pop(),participantRole:Ge,individualParticipantIds:p,participantType:dt},I=gn({participant:g,returnParticipant:!0,tournamentRecord:r});if(I.error)return I;d=I.participant.participantId}let{flightProfile:l}=Ht({event:i});if(n){let g=l?.flights?.find(({drawId:I})=>I===n.drawId);g&&(g.drawEntries=g.drawEntries.map(I=>I.participantId===o?{...I,participantId:d}:I)),n.entries=n.entries.map(I=>I.participantId===o?{...I,participantId:d}:I);for(let I of n.structures||[])if(I.positionAssignments)I.positionAssignments=I.positionAssignments.map(h=>h.participantId===o?{...h,participantId:d}:h);else if(I.structures)for(let h of I.structures)h.positionAssignments=h.positionAssignments.map(S=>S.participantId===o?{...S,participantId:d}:S)}i.entries=i.entries.map(g=>g.participantId===o&&{...g,participantId:d}||g.participantId===t&&{...g,participantId:e}||g);let f=r.events.some(({entries:g,eventId:I,drawDefinitions:h})=>i.eventId===I?h.some(({drawId:S,entries:T})=>S===n?.drawId?!1:T?.find(A=>A.participantId===o)):g?.find(S=>S.participantId===o));if(!f){let g=Li({addIndividualParticipantsToEvents:!1,participantIds:[o],tournamentRecord:r});if(g.error)return g}return{...R,participantOtherEntries:f,newPairParticipantId:d}}function Hp(t){let{flight:e,suppressNotifications:r,modifyEventEntries:n,existingDrawCount:o,allowReplacement:i,checkEntryStatus:s,tournamentRecord:a,drawDefinition:c,event:u}=t;if(!c)return{error:X};if(!u)return{error:Et};u.drawDefinitions||(u.drawDefinitions=[]);let{drawId:p,drawName:m,entries:d}=c,{entries:l}=u,f=0;if(o!==void 0&&o!==u.drawDefinitions.length)return{error:G,info:"drawDefintions count mismatch"};let{flightProfile:g}=Ht({event:u}),I=e&&g?.flights?.find(b=>b.flightNumber===e.flightNumber),h=g?.links?.find(b=>b?.target?.drawId===p)?.source?.drawId;if(h&&!u.drawDefinitions.find(b=>b.drawId===h))return _({result:{error:X},info:{sourceDrawId:h}});if(I&&I.drawId!==c.drawId)return _({result:{error:na},info:{relevantFlight:I}});let A=d?.every(({participantId:b,entryStatus:x})=>{let w=I?.drawEntries.find(F=>F.participantId===b);return!x||w?.entryStatus===x}),D=!s||l&&d?.every(({participantId:b,entryStatus:x,entryStage:w})=>l.find(L=>L.participantId===b&&(!L.entryStage||L.entryStage===w))?.entryStatus===x);if(I&&!A)return _({result:{error:na},context:{drawEntriesPresentInFlight:A,matchingEventEntries:D,relevantFlight:I},info:"Draw entries are not present in flight or do not match entryStatuses"});if(n&&d?.filter(Boolean).forEach(b=>{if(b?.entryStatus&&Or.includes(b?.entryStatus)){let x=l?.filter(Boolean).find(w=>w.participantId===b.participantId);x&&b.entryStatus&&x?.entryStatus!==b.entryStatus&&(x.entryStatus=b.entryStatus,f+=1)}}),l&&!D)return _({result:{info:"Draw entries do not match event entryStatuses",context:{matchingEventEntries:D,eventEntries:l},error:na}});let y=g?.flights?.map(({flightNumber:b})=>!isNaN(b)&&ct(b))?.filter(Boolean)||[],E=u.drawDefinitions.map(({drawOrder:b})=>b&&ct(b))?.filter(Boolean)||[],U=Math.max(0,...E,...y)+1,M=g?.flights?.find(b=>b.drawId===p),P;if(M){M.drawName=c.drawName,P={name:qr,value:{...g,flights:g.flights}};let b=M.flightNumber;b&&!E.includes(b)?U=b:M.flightNumber=U}else{let b=g?.flights||[];b.push({manuallyAdded:!0,flightNumber:U,drawEntries:d,drawName:m,drawId:p}),P={name:qr,value:{...g||{},flights:b}}}Io({event:u,extension:P}),Object.assign(c,{drawOrder:U});let N=u.drawDefinitions.find(b=>b.drawId===p),C=a?.tournamentId,O=u.eventId;if(N){if(!i)return{error:oy};let x=rr({drawDefinition:N})?.matchUps?.map(fe)??[],w=rr({drawDefinition:c})?.matchUps;if(!r){x?.length&&wn({matchUpIds:x,action:"modifyDrawDefinition",tournamentId:C,eventId:O}),w?.length&&So({matchUps:w,tournamentId:C,eventId:O}),u.drawDefinitions=u.drawDefinitions.map(L=>L.drawId===p?c:L);let F=c.structures?.map(({structureId:L})=>L);bt({drawDefinition:c,tournamentId:C,structureIds:F,eventId:O})}}else if(u.drawDefinitions.push(c),!r){let{matchUps:b}=rr({drawDefinition:c,event:u});b&&So({tournamentId:a?.tournamentId,matchUps:b}),ga({drawDefinition:c,tournamentId:C,eventId:O})}return{...R,modifiedEventEntryStatusCount:f}}function fN(t){let{provisionalPositioning:e,useExistingSeedLimit:r,tournamentRecord:n,drawDefinition:o,seedingProfile:i,structureId:s,assignments:a,drawId:c,event:u}=t,p=0;if(!a?.length)return{error:hl};if(!n)return{error:W};if(!c)return{error:Wr};let m=Fr({provisionalPositioning:e,drawDefinition:o,structureId:s});if(m.error)return m;let{seedAssignments:d,seedLimit:l}=m,f=Object.assign({},...(d??[]).filter(h=>h.seedNumber).map(h=>({[h.seedNumber]:h})));a.forEach(h=>{let{seedNumber:S}=h;l&&S<=l&&(!r||f[S])&&(f[S]=h)});let g=Object.values(f),I=g.map(h=>h?.participantId).filter(Boolean);if(I.length!==EI(I).length)return{error:iy};for(let h of g){let S=Ws({...h,provisionalPositioning:e,tournamentRecord:n,drawDefinition:o,seedingProfile:i,structureId:s,event:u});if(S?.error)return S;S?.success&&p++}return p?{...R,modifications:p}:{error:Ns}}function Rg({deleteExisting:t,event:e,flightProfile:r}){let n="attachFlightProfile";if(!r)return _({result:{error:et},stack:n});if(!e)return _({result:{error:Et},stack:n});let{flightProfile:o}=Ht({event:e});return o&&!t?_({result:{error:Ll},stack:n}):e.drawDefinitions?.length?_({result:{error:ey},stack:n}):(Io({event:e,extension:{name:qr,value:r}}),{flightProfile:J(r,!1,!0),...R})}function Av({tournamentRecord:t,scaleAttributes:e,participantIds:r}){if(!t)return{error:W};if(!r)return{error:lo};if(!e)return{error:et,info:"scaleAttributes required"};let{scaleType:n,eventType:o,scaleName:i}=e,s=[JE,n,o,i].join(".");return t.participants?.forEach(a=>{r.includes(a.participantId)&&a.timeItems&&(a.timeItems=a.timeItems.filter(c=>c&&c?.itemType!==s))}),{...R}}function bg({tournamentRecord:t,scaleAttributes:e,drawDefinition:r,entryStatuses:n,drawId:o,event:i,stage:s}){if(!i)return{error:Et};if(n&&!Array.isArray(n))return _({result:{error:G},info:Nn("entryStatus"),stack:"removeScaleValues"});let a=i.entries;if(o){let{flightProfile:p}=Ht({event:i}),m=p?.flights?.find(d=>d.drawId===o);m?a=m.drawEntries:a=r?.entries}let u=(a||[]).filter(p=>(!s||!p.entryStage||p.entryStage===s)&&(!n||n.includes(p.entryStatus))).map(gt);return Av({tournamentRecord:t,scaleAttributes:e,participantIds:u})}function $d({removePriorValues:t,tournamentRecord:e,displaySettings:r,status:n=Gr,event:o}){if(!e)return _({result:{error:W}});if(!o)return _({result:{error:Et}});if(!Rt(r))return _({result:{error:et}});if(Rt(r.draws))for(let s of Object.keys(r.draws)){let a=r.draws[s].scheduleDetails??[];if(a.length){let c=[];for(let u of a){let p=c.find(m=>CC(m.attributes,u.attributes));p?.dates&&u.dates?p.dates.push(...u.dates):c.push(u)}r.draws[s].scheduleDetails=c}}let i=Xs({statusObject:{displaySettings:r},removePriorValues:t,status:n,event:o});return i.error?i:{...R}}function gN({tournamentRecord:t,drawDefinition:e,entryStatuses:r,scaleName:n,drawId:o,event:i,stage:s}){if(!t)return{error:W};if(!i)return{error:Et};n=n||i.category?.categoryName||i.category?.ageCategoryCode;let a={eventType:i.eventType,scaleType:eo,scaleName:n};return bg({tournamentRecord:t,scaleAttributes:a,drawDefinition:e,entryStatuses:r,drawId:o,event:i,stage:s})}function IN({removePairParticipants:t,tournamentRecord:e,eventIds:r}){if(!e)return{error:W};if(!e.events)return{error:mr};if(!Array.isArray(r))return{error:et,info:Nn("drawIds")};let n=[],o=[],i=[],s=[];if(e.events=(e.events||[]).filter(a=>{if(r.includes(a.eventId)){let p={action:XT,payload:{events:[a]}};n.push(p),o.push({tournamentId:e.tournamentId,eventName:a.eventName,eventType:a.eventType,category:a.category,eventId:a.eventId,gender:a.gender})}let c=a.eventType===Kr?(a.entries||[]).map(({entryStatus:p,participantId:m})=>p!==Lr&&m).filter(Boolean):[],u=r.includes(a.eventId);return u?s.push(...c):i.push(...c),!u}),t){let a=s.filter(c=>!i.includes(c));e.participants=e.participants.filter(({participantId:c})=>!a.includes(c))}return Nc({tournamentRecord:e}),n.length&&(Tt({topic:fa,payload:n}),Gi({tournamentRecord:e,timeItem:{itemType:XT,itemValue:o}})),{...R}}function hN({tournamentRecord:t,eventUpdates:e,eventId:r,event:n}){let o="modifyEvent";if(!t)return _({result:{error:W},stack:o});if(!$e(r))return _({result:{error:Et},context:{eventId:r},stack:o});if(!Rt(e))return _({result:{error:G},context:{eventUpdates:e},stack:o});let i=n?.entries?.filter(({entryStatus:l})=>{let f=l;return[...Or,wr].includes(f)}).map(({participantId:l})=>l)??[],s=i?Yt({participantFilters:{participantIds:i},withIndividualParticipants:!0,tournamentRecord:t}).participants??[]:[],a=[],c=s.reduce((l,f)=>{let g=f.person?.sex?[f.person.sex]:f.individualParticpants?.map(I=>I.person?.sex)||[];return a.push(...g),l.includes(f.participantType)?l:l.concat(f.participantType)},[]),u=pt(a),p=!u.length||[_r,Fn].includes(e.gender??"")||u.length===1&&u[0]===e.gender;if(e.gender&&!p)return _({context:{gender:e.gender,validGender:p},result:{error:G},stack:o});let d=(c.includes(Fe)&&[Fe]||c.includes(ht)&&[ao]||c.includes(dt)&&[Kr]||[Kr,ao,Fe]).includes(e.eventType??"");return e.eventType&&!d?_({context:{participantType:e.eventType,validEventType:d},result:{error:G},stack:o}):(e.eventType&&(n.eventType=e.eventType),e.eventName&&(n.eventName=e.eventName),e.gender&&(n.gender=e.gender),{...R})}function Wp({qualifyingPositions:t,drawEntries:e=[],drawName:r,drawId:n,event:o,stage:i}){let s="addFlight";if(!o)return _({result:{error:Et},stack:s});if(!r)return _({result:{error:et},stack:s});if(e?.length){let g=(o.entries??[]).map(gt),I=e.map(gt);if(jt(I,g).length!==I.length)return _({result:{error:G},stack:s})}let a=Ht({event:o})?.flightProfile,c=a?.flights?.map(({flightNumber:g})=>!isNaN(g)&&ct(g))?.filter(Boolean)||[],u=Math.max(0,...c)+1,m={drawId:n||Mt(),flightNumber:u,drawEntries:e,drawName:r};if(i&&(m.stage=i),t&&(m.qualifyingPositions=t),(a?.flights||[]).find(({drawId:g})=>g===m.drawId))return _({result:{error:tE},stack:s});let l=(a?.flights||[]).concat(m),f={name:qr,value:{...a||{},flights:l}};return Io({event:o,extension:f})}var yv={collectionDefinitions:[{collectionName:"Doubles",matchUpCount:3,matchUpFormat:"SET1-S:8/TB7@7",matchUpType:"DOUBLES",matchUpValue:1},{collectionName:"Singles",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7",matchUpType:"SINGLES",matchUpValue:1}],tieFormatName:"COLLEGE_D3",winCriteria:{valueGoal:5}};var Ev={collectionDefinitions:[{collectionName:"Doubles",collectionValue:1,matchUpCount:3,matchUpFormat:"SET1-S:6/TB7",matchUpType:"DOUBLES"},{collectionName:"Singles",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7",matchUpType:"SINGLES",matchUpValue:1}],tieFormatName:"COLLEGE_DEFAULT",winCriteria:{valueGoal:5}};var Uv={collectionDefinitions:[{collectionName:"Doubles",matchUpCount:3,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1},{collectionName:"Singles",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7",matchUpType:"SINGLES",matchUpValue:1}],tieFormatName:"COLLEGE_JUCO",winCriteria:{valueGoal:5}};var tA={COLLEGE_D3:yv,COLLEGE_DEFAULT:Ev,COLLEGE_JUCO:Uv,DOMINANT_DUO:oT,DOMINANT_DUO_MIXED:tT,LAVER_CUP:uT,TEAM_DOUBLES_3_AGGREGATION:zS,TIME_TENNIS_DUAL:eT,TIME_TENNIS_PRO_CIRCUIT:ZS,USTA_BREWER_CUP:rT,USTA_OZAKI_CUP:nT,USTA_COLLEGE:iT,USTA_GOLD_TEAM_CHALLENGE:KS,USTA_INTERSECTIONAL:JS,USTA_LEVEL_1:sT,USTA_SECTION_BATTLE:XS,USTA_SOUTHERN_LEVEL_5:QS,USTA_TOC:pT,USTA_WTT_ITT:aT,USTA_ZONAL:cT};function Mc({suppressNotifications:t,tournamentRecord:e,internalUse:r,event:n}){if(!e)return{error:W};if(e.events||(e.events=[]),!n)return{error:Et};let{startDate:o,endDate:i}=e;if(!r&&(n.entries?.length||n.drawDefinitions?.length)){let c=rt({drawDefinitions:!!n.drawDefinitions?.length,entries:!!n.entries?.length});return{info:"entries/drawDefinitions cannot exist",error:G,context:c}}let s={eventType:Fs,drawDefinitions:[],entries:[],startDate:o,endDate:i,...n};if(n.eventType===kr){if(n.tieFormat){let c=ir({tieFormat:n.tieFormat});if(c.error)return c}else if(n.tieFormatName){if(!tA[n.tieFormatName])return{context:{tieFormatName:n.tieFormatName},error:G};let c=Bi({isMock:e?.isMock,namedFormat:n.tieFormatName,event:n});s.tieFormat=c}}if(s.eventId||(s.eventId=Mt()),e.events.reduce((c,u)=>c||u.eventId===s.eventId,void 0))return{error:fy};{let c=s;if(e.events.push(c),!t){let{topics:u}=Cr();if(u.includes(cp)){let p=co({event:n}).matchUps??[];So({tournamentId:e?.tournamentId,eventId:n.eventId,matchUps:p})}for(let p of n.drawDefinitions||[])ga({drawDefinition:p})}return{...R,event:s}}}var PN={};Jt(PN,{drawMatic:()=>Od,garman:()=>UN,generateAdHocMatchUps:()=>Nu,generateAdHocRounds:()=>bd,generateAndPopulatePlayoffStructures:()=>ld,generateCourts:()=>Og,generateDrawDefinition:()=>_u,generateDrawMaticRound:()=>Ed,generateDrawStructuresAndLinks:()=>Td,generateDrawTypeAndModifyDrawDefinition:()=>Ad,generateFlightProfile:()=>Dv,generateLineUps:()=>rA,generateQualifyingStructure:()=>id,generateSeedingScaleItems:()=>KT,generateVoluntaryConsolation:()=>LS,roundRobinGroups:()=>Mb});var EV="splitLevelBased",AN="splitWaterfall",yN="splitShuttle",Pv={SPLIT_LEVEL_BASED:EV,SPLIT_WATERFALL:AN,SPLIT_SHUTTLE:yN};function Dv(t){let{drawNameRoot:e="Flight",attachFlightProfile:r,tournamentRecord:n,scaleAttributes:o,scaleSortMethod:i,deleteExisting:s,sortDescending:a,drawNames:c=[],flightsCount:u,splitMethod:p,uuids:m=[],event:d,stage:l}=t;if(!d)return{error:Et};let f=d.entries??[],{flightProfile:g}=Ht({event:d});if(g&&r&&!s)return{error:Ll};let I=t.scaledEntries??Qs({tournamentRecord:n,scaleAttributes:o,scaleSortMethod:i,sortDescending:a,event:d,stage:l}).scaledEntries,h=I.map(gt),S=cr(f.filter(({participantId:P})=>!h.includes(P)).filter(P=>(!l||!P.entryStage||P.entryStage===l)&&(!P.entryStatus||qo.includes(P.entryStatus)))),T=I.concat(...S),A=T.length,D=Math.ceil(A/u),y=Te(T,D);p===AN?y=Gl(T,u):p===yN&&(y=Gl(T,u,!0));function E(P){return(P||[]).map(({participantId:N,scaleValue:C})=>{let O=f.find(b=>b.participantId===N);return O?.scaleValue&&C&&(O.scaleValue=C),O}).sort((N,C)=>N.scaleValue-C.scaleValue).map((N,C)=>(N.scaleValue&&(N.seedNumber=C+1),N))}let U=Z(0,u).map(P=>{let N=P+1;return{flightNumber:N,drawId:m?.pop()??Mt(),drawEntries:E(y[P]),drawName:c?.length&&c[P]||`${e} ${N}`}}),M={scaleAttributes:o,splitMethod:p,flights:U};if(r){let P=Rg({flightProfile:M,deleteExisting:s,event:d});return{splitEntries:yr()&&y||void 0,...P}}else return{flightProfile:M,...R}}var UV="ASC",EN="ASC",PV="DESC",eA="DESC",Nv={ASC:UV,ASCENDING:EN,DESC:PV,DESCENDING:eA};function rA(t){let{tieFormat:e}=t,{useDefaultEventRanking:r,tournamentRecord:n,drawDefinition:o,scaleAccessor:i,singlesOnly:s,attach:a,event:c}=t;if(c?.eventType!==kr)return{error:No};if(!n)return{error:W};if(!e&&!o)return{error:pr};if(e=e??je({drawDefinition:o,event:c})?.tieFormat,ir({tieFormat:e}).error)return{error:ni};if(typeof i!="object"&&!r)return{error:G,context:{scaleAccessor:i}};let u={},m=(o?.entries??c?.entries??[]).filter(C=>C?.entryStatus===Zr).map(gt),{participants:d=[]}=Yt({withIndividualParticipants:!0,withScaleValues:!0,tournamentRecord:n}),l=d.filter(({participantId:C})=>m.includes(C)),f=C=>C===oi?"rankings":"ratings",g=c?.category?.categoryName??c?.category?.ageCategoryCode,{scaleName:I=g,scaleType:h=oi,sortOrder:S,accessor:T}=i||{},A=f(h),D=(C,O)=>{let b=C[A]?.[O];if(!b&&r&&(b=C[A]?.[Ia]),Array.isArray(b)){let x=b.find(w=>w.scaleName===I)?.scaleValue;if(te(x))return x;if(T&&typeof x=="object")return x[T]}return 0},y=(C,O,b)=>{let x=S===eA?O:C,w=S===eA?C:O;return D(x,b)-D(w,b)},E=(C,O)=>y(C,O,Ia),U=(C,O)=>y(C,O,vi),M=[],P=e?.collectionDefinitions??[];for(let C of l){let O=C.individualParticipants?.sort(E)??[],b=s?O:C.individualParticipants?.sort(U)??[],x={};for(let F of P){let L=[],{collectionId:v,matchUpCount:B,matchUpType:H,gender:j}=F,V=ie(Ia)(H);Z(0,B).forEach(Y=>{let $=V?O:b??[],k=Y+1,K=[];Z(0,V?1:2).forEach(z=>{let q=$?.find(nt=>{let Q=j&&([ee,ue].includes(j)&&j||j===_r&&[ee,ue][z]);return(!Q||Q===nt.person?.sex)&&!L.includes(nt.participantId)})?.participantId;q&&(K.push(q),L.push(q),x[q]||(x[q]=[]),x[q].push({collectionPosition:k,collectionId:v}))}),V||M.push(K)})}let w=Object.keys(x).map(F=>({collectionAssignments:x[F],participantId:F}));u[C.participantId]=w}let N=[];for(let C of M){let{participant:O}=tn({tournamentParticipants:d,participantIds:C});if(!O){let b={individualParticipantIds:C,participantRole:Ge,participantType:dt};N.push(b)}}if(a){for(;N.length;)gn({participant:N.pop(),tournamentRecord:n});St({element:o,extension:{name:ho,value:u}})}return{...R,lineUps:u,participantsToAdd:N}}function Og(t){if(!t)return{error:et};let e=lt(t,[{dates:!1,[yn]:s=>Array.isArray(s)&&s.every(Rr)},{uuids:!1,[yn]:s=>Array.isArray(s)&&s.every($e)},{startTime:!1,endTime:!1,[yn]:FI},{idPrefix:!1,namePrefix:!1,[yn]:$e},{count:!0,[yn]:te}]);if(e.error)return e;let{startDate:r,endDate:n}=t.tournamentRecord??{},o=t.dates||r&&n&&bs(r,n)||[],i=Z(1,t.count+1).map(s=>rt({courtId:t.uuids?.pop()??(t.idPrefix&&`${t.idPrefix}-${s}`)??Mt(),courtName:t.courtNames?.pop()??(t.namePrefix&&`${t.namePrefix} ${s}`),dateAvailability:o.map(a=>({startTime:t.startTime??"08:00",endTime:t.endTime??"20:00",date:a}))}));return{...R,courts:i}}var UN={};Jt(UN,{default:()=>DV,garman:()=>Rv});function wa({court:t,date:e}){let r=e&&t.dateAvailability.find(o=>_n(o.date,e)),n=t.dateAvailability.find(o=>!o.date);return r||n}function hs(t){let e=lt(t,[{courtDate:!0,_ofType:Ri}]);if(e.error)return e;let{includeBookingTypes:r=[],courtDate:n}=t,o=[],i=we(n.startTime);(n.bookings||[]).filter(a=>!a.bookingType||!r.includes(a.bookingType)).sort((a,c)=>Kl(a.startTime).localeCompare(Kl(c.startTime))).forEach(a=>{let c={startTime:$t(i.toISOString()),endTime:a.startTime};we(a.startTime)>i&&o.push(c),we(a.endTime)>i&&(i=we(a.endTime))});let s={startTime:$t(i.toISOString()),endTime:n.endTime};return we(n.endTime)>i&&o.push(s),{timeSlots:o}}function Mv({averageMatchUpMinutes:t,includeBookingTypes:e,periodStartTime:r,periodEndTime:n}){let o=s=>{let{timeSlots:a}=hs({includeBookingTypes:e,courtDate:s});return!!a?.filter(i)?.length};function i(s){let a=we(s.startTime),c=we(s.endTime);return a>r||c<n?!1:ca(r,c)>=t}return{enoughTime:o}}function nA(t){let e=lt(t,[{periodStart:!0,date:!0},{courts:!0,_ofType:Er}]);if(e.error)return e;let{averageMatchUpMinutes:r,includeBookingTypes:n,periodStart:o,date:i}=t,s=t.courts,a=we(o),c=Ql(a,r),{enoughTime:u}=Mv({averageMatchUpMinutes:r,includeBookingTypes:n,periodStartTime:a,periodEndTime:c});return{availableToScheduleCount:(s?.filter(m=>{if(!Array.isArray(m.dateAvailability))return!1;let d=wa({date:i,court:m});return!!(d&&u(d))})||[]).length,...R}}function jp(t){let{remainingScheduleTimes:e=[],clearScheduleDates:r,periodLength:n=30,scheduleDate:o,courts:i=[]}=t,{bookings:s=[]}=t;if(!Array.isArray(i)||!i.length)return{error:G,courts:i};if(!Array.isArray(s))return{error:om};if(!Rr(o))return{error:ar};r&&(Array.isArray(r)?r.includes(o)&&(s=[]):s=[]);let{courtBookings:a,unassignedBookings:c}=s.reduce((l,f)=>{let{courtId:g}=f;return g?l.courtBookings[g]?l.courtBookings[g].push(f):l.courtBookings[g]=[f]:l.unassignedBookings.push(f),l},{courtBookings:{},unassignedBookings:[]}),u=i.map((l,f)=>{let{courtId:g,courtName:I}=l,h=a[g]||[],S=wa({date:o,court:l})||{},{bookings:T=[],startTime:A,endTime:D,date:y}=S,U=[e[f]&&{startTime:A,endTime:e[f]},...J(T,!1,!0),...h].filter(Boolean);return{courtId:g,courtName:I,dateAvailability:{bookings:U,startTime:A,endTime:D,date:y}}});c.sort((l,f)=>Vt(l.startTime)-Vt(f.startTime));let p=()=>u.map(l=>{let f=l.dateAvailability,{timeSlots:g=[]}=hs({courtDate:f});return{courtName:l.courtName,courtId:l.courtId,timeSlots:g}}).flat(),m=[];for(let l of c){let{startTime:f,endTime:g,averageMinutes:I,recoveryMinutes:h,matchUpId:S}=l,T=Vt(f),A=Vt(g),y=p().reduce((E,{courtId:U,courtName:M,timeSlots:P})=>{let N;return P.find(({startTime:O,endTime:b})=>{N=Vt(O)-T;let x=T>=Vt(O);return A<=Vt(b)&&E.startDifference!==0&&((N===0||N+n>=0)&&(E.startDifference===void 0||N<E.startDifference)||x)})?{courtName:M,courtId:U,startDifference:N}:E},{});if(y.courtId){let E={averageMinutes:I,recoveryMinutes:h,matchUpId:S,startTime:f,endTime:g};m.push(E),u.find(({courtId:M})=>M===y.courtId)?.dateAvailability.bookings.push(E)}else console.log({unassignedBooking:l})}return{virtualCourts:u.map(({courtId:l,courtName:f,dateAvailability:g})=>({dateAvailability:[g],courtName:f,courtId:l})),assignedBookings:m}}function vu({averageMatchUpMinutes:t,periodLength:e=30,recoveryMinutes:r}){let n=(t||90)+(r||0);return e>n?n:e||30}function oA(t){let{startTime:e="8:00",endTime:r="20:30",count:n=10,date:o}=t??{};return Z(0,n).map(()=>({dateAvailability:[{date:o,startTime:e,endTime:r}]}))}function Cc({scheduleDate:t,startTime:e,endTime:r,courts:n}){let o=e&&"startTime"||r&&"endTime"||void 0;return n.reduce((i,s)=>{let a=wa({date:t,court:s}),c=o&&(a?.[o]||s[o]);return c&&(!i||e&&Vt(c)<Vt(i)||r&&Vt(c)>Vt(i))?c:i},void 0)}function Cv({averageMinutes:t,startTime:e,endTime:r,courts:n,date:o}){e=e||Cc({courts:n,scheduleDate:o,startTime:!0}),r=r||Cc({courts:n,scheduleDate:o,endTime:!0});let i;if(e&&r){let s=we(e),a=we(r);for(let c of n||[]){if(!Array.isArray(c.dateAvailability))continue;let u=wa({court:c,date:o}),{timeSlots:p}=hs({courtDate:u});p?.forEach(m=>{let d=we(m.startTime),l=we(m.endTime);if(d>a||d<s||l<s)return!1;if(ca(d,l)>=t){let I=$t(d.toISOString());(!i||I<i)&&(i=I)}})}}return{firstTimeSlotStartTime:i}}function Kd(t){let e=lt(t,[{courts:!0,_ofType:Er}]);if(e.error)return e;let{date:r=zl(),startTime:n="08:00",endTime:o="19:00",periodLength:i,courts:s}=t,{calculateStartTimeFromCourts:a=!0,remainingScheduleTimes:c,averageMatchUpMinutes:u,clearScheduleDates:p,courtsCount:m,bookings:d}=t;i=i||vu({averageMatchUpMinutes:u}),r=Ut(r),n=$t(n),o=$t(o);let l=0,f=0,g=0,I=0,h=0;!s&&m&&(s=oA({startTime:n,endTime:o,count:m,date:r}));let{virtualCourts:S}=jp({remainingScheduleTimes:c,clearScheduleDates:p,scheduleDate:r,periodLength:i,bookings:d,courts:s}),{firstTimeSlotStartTime:T}=Cv({averageMinutes:u,courts:S,startTime:n,endTime:o,date:r});a&&T&&(n=T||n);let A=Vt(n),y=Vt(o)-A,E=Math.floor(y/i),M=Z(0,E+1).map(N=>{let C=A+N*i,O=uR(C),b=nA({courts:S??[],averageMatchUpMinutes:u,periodStart:O,date:r});if(b.error)return{error:b.error};let{availableToScheduleCount:x=0}=b,w=x>f?x-f:0;h+=N?x:0;let F=N?h/N:x,v=i*F/u,B=N?v*(N-1)+F:F,H=x?f&&B-l||w:0;l=B,f=x,g+=H;let j=ct(g)-I;return I+=j,{periodStart:O,add:j,availableToScheduleCount:x,newCourts:w,totalMatchUps:I}});return{scheduleTimes:M.reduce((N,C)=>{let b=Z(0,C.add).map(()=>({scheduleTime:C.periodStart}));return N.concat(...b)},[]).flat(),timingProfile:M,totalMatchUps:I}}var Rv={getCourtsAvailableAtPeriodStart:nA,generateTimeSlots:hs,getScheduleTimes:Kd,courtGenerator:oA},DV=Rv;var iA={};Jt(iA,{isValid:()=>Sr,isValidMatchUpFormat:()=>Sr,parse:()=>tr,stringify:()=>Pp});var jN={};Jt(jN,{allCompetitionMatchUps:()=>cn,allDrawMatchUps:()=>rr,allEventMatchUps:()=>co,allTournamentMatchUps:()=>le,analyzeMatchUp:()=>Vp,applyLineUps:()=>HN,assignMatchUpSideParticipant:()=>DN,assignTieMatchUpParticipantId:()=>Xd,bulkMatchUpStatusUpdate:()=>GN,calculateWinCriteria:()=>Is,checkInParticipant:()=>vg,checkMatchUpIsComplete:()=>is,checkOutParticipant:()=>_g,competitionScheduleMatchUps:()=>Ou,disableTieAutoCalc:()=>LN,drawMatchUps:()=>WT,enableTieAutoCalc:()=>vN,eventMatchUps:()=>Wd,findMatchUp:()=>Ug,getAllDrawMatchUps:()=>re,getAllStructureMatchUps:()=>At,getCheckedInParticipantIds:()=>es,getCompetitionMatchUps:()=>kp,getEventMatchUpFormatTiming:()=>wT,getMatchUpCompetitiveProfile:()=>su,getMatchUpContextIds:()=>kT,getMatchUpDailyLimits:()=>Yd,getMatchUpDailyLimitsUpdate:()=>LT,getMatchUpDependencies:()=>Vr,getMatchUpFormat:()=>VT,getMatchUpFormatTiming:()=>au,getMatchUpFormatTimingUpdate:()=>vT,getMatchUpScheduleDetails:()=>Wm,getMatchUpType:()=>qm,getMatchUpsStats:()=>BT,getModifiedMatchUpFormatTiming:()=>Bd,getParticipantResults:()=>Su,getPredictiveAccuracy:()=>GT,getRoundMatchUps:()=>He,getRounds:()=>HT,isValidMatchUpFormat:()=>Sr,matchUpActions:()=>hd,mutate:()=>WN,participantScheduledMatchUps:()=>FT,query:()=>KD,removeDelegatedOutcome:()=>xN,removeMatchUpSideParticipant:()=>wg,removeTieMatchUpParticipantId:()=>MN,replaceTieMatchUpParticipantId:()=>xg,resetAdHocMatchUps:()=>VN,resetMatchUpLineUps:()=>Lg,resetScorecard:()=>Gg,resetTieFormat:()=>Fg,setDelegatedOutcome:()=>kN,setMatchUpFormat:()=>FN,setMatchUpStatus:()=>xu,setOrderOfFinish:()=>BN,substituteParticipant:()=>wN,tallyParticipantResults:()=>Ca,toggleParticipantCheckInState:()=>zd,tournamentMatchUps:()=>jd,updateTieMatchUpScore:()=>zn,validMatchUp:()=>yf,validMatchUps:()=>Ur});var WN={};Jt(WN,{applyLineUps:()=>HN,assignMatchUpSideParticipant:()=>DN,assignTieMatchUpParticipantId:()=>Xd,bulkMatchUpStatusUpdate:()=>GN,checkInParticipant:()=>vg,checkOutParticipant:()=>_g,disableTieAutoCalc:()=>LN,enableTieAutoCalc:()=>vN,findMatchUp:()=>Ug,removeDelegatedOutcome:()=>xN,removeMatchUpSideParticipant:()=>wg,removeTieMatchUpParticipantId:()=>MN,replaceTieMatchUpParticipantId:()=>xg,resetAdHocMatchUps:()=>VN,resetMatchUpLineUps:()=>Lg,resetScorecard:()=>Gg,resetTieFormat:()=>Fg,setDelegatedOutcome:()=>kN,setMatchUpFormat:()=>FN,setMatchUpStatus:()=>xu,setOrderOfFinish:()=>BN,substituteParticipant:()=>wN,toggleParticipantCheckInState:()=>zd,updateTieMatchUpScore:()=>zn});function DN({tournamentRecord:t,drawDefinition:e,participantId:r,sideNumber:n,matchUpId:o,event:i}){if(r&&typeof r!="string")return{error:pn};if(!e)return{error:X};if(!o)return{error:ke};let s=n===void 0;if(s&&(n=1),![1,2].includes(n))return _({result:{error:G,context:{sideNumber:n}}});let{matchUp:a,structure:c}=xt({drawDefinition:e,matchUpId:o,event:i});if(!a)return{error:Oe};if(!(!c?.structures&&!(e.drawType&&e.drawType!==an)&&!c?.matchUps?.find(({roundPosition:p})=>!!p)))return{error:nm};if(!r&&(a?.score?.scoreStringSide1||ae.includes(a?.matchUpstatus)||a?.matchUpStatus&&[ge,Ne].includes(a.matchUpStatus)))return{error:Hu,info:"matchUp has completed status or score"};if(a){if(a.sides=[1,2].map(p=>{let m=a.sides?.find(d=>d.sideNumber===p)??{sideNumber:p};return n===p?{...m,participantId:r}:m}),s)for(let p of a.sides)p.sideNumber&&(p.sideNumber=3-p.sideNumber);It({tournamentId:t?.tournamentId,context:"assignSideParticipant",drawDefinition:e,matchUp:a})}return{...R,sidesSwapped:s}}function rn({removePriorValues:t,tournamentRecord:e,duplicateValues:r,drawDefinition:n,disableNotice:o,matchUpId:i,timeItem:s,event:a}){let{matchUp:c}=xt({drawDefinition:n,event:a,matchUpId:i});if(!c)return{error:Oe};let u=Ti({removePriorValues:t,element:c,duplicateValues:r,timeItem:s});return o||It({tournamentId:e?.tournamentId,eventId:a?.eventId,context:"addTimeItem",drawDefinition:n,matchUp:c}),u}function _g(t){let e=[{[An]:!0},{[Yr]:!0},{[Bn]:!0},{[Co]:!0}],r=lt(t,e);if(r.error)return r;let n=xa(t,[{[sa]:fo,attr:{[lm]:!0}}]);if(n.error)return n;let{tournamentRecord:o,drawDefinition:i,participantId:s,matchUpId:a}=t,c=n?.matchUp?.matchUp,{matchUpStatus:u,score:p}=c??{};if(u&&Nm.includes(u)||u&&ae.includes(u)||Ie({score:p}))return{error:cy};let m=es({matchUp:c});if(m?.error)return m;let{checkedInParticipantIds:d,allRelevantParticipantIds:l}=m??{};if(!l?.includes(s))return{error:pn};if(!d?.includes(s))return{error:xy};let f=ch({matchUp:c});if(f?.error)return f;let{sideParticipantIds:g,nestedIndividualParticipantIds:I}=f??{},h=g?.indexOf(s);return h!==void 0&&[0,1].includes(h)&&(I?.[h]??[]).forEach(T=>{rn({drawDefinition:i,matchUpId:a,timeItem:{itemType:Bm,itemValue:T}})}),rn({tournamentRecord:o,drawDefinition:i,matchUpId:a,timeItem:{itemValue:s,itemType:Bm}}),{...R,checkedOut:!0}}function vg(t){let e=[{[An]:!0},{[Yr]:!0},{[Bn]:!0},{[Co]:!0}],r=lt(t,e);if(r[Ms])return r;let n=xa(t,[{[sa]:fo,attr:{[lm]:!0}}]);if(n[Ms])return n;let{tournamentRecord:o,drawDefinition:i,participantId:s,matchUpId:a}=t,c=es({matchUp:n?.matchUp?.matchUp});if(c?.error)return c;let{checkedInParticipantIds:u,allRelevantParticipantIds:p}=c??{};if(!p?.includes(s))return{[Ms]:pn};let m={...R,checkedIn:!0};return u?.includes(s)||rn({tournamentRecord:o,drawDefinition:i,matchUpId:a,timeItem:{itemValue:s,itemType:Vm}}),m}function zd(t){let e=lt(t,[{[Bn]:!0,[Yr]:!0,[Co]:!0}]);if(e.error)return e;let r=t.tournamentId??t.activeTournamentId,n=t.tournamentRecord??(r&&t.tournamentRecords?.[r]);if(!n)return{error:W};let i=xa(t,[{[sa]:fo,attr:{[lm]:!0},[Ms]:Oe}]).matchUp?.matchUp;if(!i)return{error:Oe};let{checkedInParticipantIds:s=[]}=es({matchUp:i}),{participantId:a,matchUpId:c,drawDefinition:u}=t;return a&&s.includes(a)?_g({tournamentRecord:n,drawDefinition:u,participantId:a,matchUpId:c,matchUp:i}):vg({tournamentRecord:n,drawDefinition:u,participantId:a,matchUpId:c,matchUp:i})}function Qd({tournamentRecord:t,drawDefinition:e,tieMatchUpId:r,event:n}){if(!t)return{error:W};if(!e)return{error:Wr};if(!n)return{error:mr};let o=Ae({drawDefinition:e}),{matchUp:i}=xt({matchUpId:r,drawDefinition:e,matchUpsMap:o});if(!i)return{error:Oe};let{matchUp:s,structure:a}=xt({tournamentParticipants:t.participants,matchUpId:r,inContext:!0,drawDefinition:e,matchUpsMap:o,event:n});if(!s)return{error:Oe};let{collectionPosition:c,drawPositions:u,collectionId:p,matchUpTieId:m,matchUpType:d}=s;if(d&&!cu([Xt,Gt],d))return{error:Je};let{positionAssignments:l}=Nt({structure:a}),f=l?.filter(y=>u?.includes(y.drawPosition)),{matchUp:g}=xt({matchUpId:m,drawDefinition:e,matchUpsMap:o}),I=g?.sides?.map(gt)??[],h=f?.map(gt)??[],S=[...I,...h],{participants:T}=Yt({tournamentRecord:t,participantFilters:{participantTypes:[kt],participantIds:S}}),{matchUp:A}=xt({matchUpId:m,inContext:!0,drawDefinition:e,matchUpsMap:o}),D=je({matchUp:g,drawDefinition:e,structure:a,event:n})?.tieFormat;return{inContextDualMatchUp:A,inContextTieMatchUp:s,relevantAssignments:f,collectionPosition:c,teamParticipants:T,collectionId:p,matchUpType:d,dualMatchUp:g,tieMatchUp:i,tieFormat:D,structure:a,...R}}function xg(t){let e=Qd(t);if(e.error)return e;let r="replaceTieMatchUpParticipantid",{existingParticipantId:n,tournamentRecord:o,newParticipantId:i,drawDefinition:s,substitution:a,event:c}=t;if(!n||!i)return _({result:{error:oe},stack:r});if(n===i)return{...R};let{inContextDualMatchUp:u,inContextTieMatchUp:p,collectionPosition:m,collectionId:d,dualMatchUp:l,tieMatchUp:f,tieFormat:g}=e,I=p?.matchUpType,h=p?.sides?.find(B=>B.participant?.participantId===n||B.participant?.individualParticipantIds?.includes(n));if(!h)return{error:Zt};let S=Yt({tournamentRecord:o,participantFilters:{participantIds:[n,i]}})?.participants??[];if(S.length!==2)return _({result:{error:oe},stack:r});if(S[0].participantType!==S[1].participantType)return _({result:{error:nn},stack:r});let{appliedPolicies:T}=Pt({tournamentRecord:o,drawDefinition:s,event:c}),A=t.policyDefinitions?.[ze]??T?.[ze]??us[ze],D=S.find(({participantId:B})=>B===i);if((t.enforceGender??A?.participants?.enforceGender)!==!1&&[ee,ue].includes(p?.gender)&&p?.gender!==D?.person?.sex)return{error:Us,info:"Gender mismatch"};let E=A?.processCodes?.substitution;Ra({tournamentId:o.tournamentId,eventId:c.eventId,inContextDualMatchUp:u,drawDefinition:s,dualMatchUp:l});let U=l?.sides?.find(({sideNumber:B})=>B===h.sideNumber);if(!U)return _({result:{sideNumber:h.sideNumber,existingParticipantId:n,error:Ke},stack:r});if(p?.sides?.flatMap(B=>B.participant?.individualParticipantIds||B.participant?.participantId||[])?.includes(i))return _({result:{error:Wu},stack:r});let P=u?.sides?.find(({sideNumber:B})=>B===h.sideNumber)?.participantId,N=U.lineUp,C=N?.find(({participantId:B})=>i===B),O=N?.reduce((B,H)=>H.substitutionOrder>B?H.substitutionOrder:B,0),b=N?.map(B=>{let H=J(B,!1,!0);if(![n,i].includes(H.participantId))return H;if(!a&&[n,i].includes(H.participantId)&&(H.collectionAssignments=H.collectionAssignments?.filter(j=>!(j.collectionPosition===m&&j.collectionId===d))),a&&n===H.participantId&&(H.collectionAssignments=H.collectionAssignments.map(j=>j.collectionPosition===m&&j.collectionId===d&&j.substitutionOrder===void 0?{...j,substitutionOrder:O}:j)),H.participantId===i){H.collectionAssignments||(H.collectionAssignments=[]);let j={collectionId:d,collectionPosition:m};a&&(j.previousParticipantId=n,j.substitutionOrder=(O??0)+1),H.collectionAssignments.push(j)}return H})??[];if(!C){let B={collectionId:d,collectionPosition:m};a&&(B.substitutionOrder=(O??0)+1,B.previousParticipantId=n);let H={collectionAssignments:[B],participantId:i};b.push(H)}let x=I===Gt,{assignedParticipantIds:w}=gp({lineUp:N,collectionPosition:m,collectionId:d}),{assignedParticipantIds:F}=gp({lineUp:b,collectionPosition:m,collectionId:d});if(U.lineUp=b,P&&g){let B=Fi({participantId:P,lineUp:b,drawDefinition:s,tieFormat:g});if(B.error)return _({result:B,stack:r})}else console.log("team participantId not found");let L,v;if(x){let{tournamentRecord:B}=t,H=tn({participantIds:F,tournamentRecord:B});if(!H.participant){let Y=gn({returnParticipant:!0,pairOverride:!0,tournamentRecord:B,participant:{participantRole:Ge,individualParticipantIds:F,participantType:dt}});if(Y.error)return _({result:Y,stack:r});L=Y.participant?.participantId}H=tn({participantIds:w,tournamentRecord:B});let j=H.participant?.participantId;j&&Li({participantIds:[j],tournamentRecord:B}).success&&(v=j)}if(a||h.substitutions?.length===1){if(a)E&&f&&(f.processCodes=pt([...f?.processCodes??[],...E]));else for(let B of E||[]){let H=f?.processCodes?.lastIndexOf(B);H!==void 0&&f?.processCodes?.splice(H,1)}f&&It({tournamentId:o?.tournamentId,matchUp:f,context:r,drawDefinition:s})}return l&&It({tournamentId:o?.tournamentId,matchUp:l,context:r,drawDefinition:s}),{...R,modifiedLineUp:b,participantRemoved:v,participantAdded:L}}function sA({collectionPosition:t,teamParticipantId:e,dualMatchUpSide:r,drawDefinition:n,participantIds:o,collectionId:i}){if(!i||!t||!Array.isArray(o))return{modifiedLineUp:r?.lineUp||[],error:G};let s=r?.lineUp||os({participantId:e,drawDefinition:n})?.lineUp,a=[],c=[];return{modifiedLineUp:s?.map(p=>{if(!o.includes(p.participantId))return p;let m=p.collectionAssignments?.filter(d=>{let l=d.collectionId===i&&d.collectionPosition===t;return l&&(d.previousParticipantId&&a.push(d.previousParticipantId),c.push({participantId:p.participantId,...d})),!l});return{participantId:p.participantId,collectionAssignments:m}}).filter(Boolean)||[],assignmentsRemoved:c,previousParticipantIds:a}}function bv({individualParticipantIds:t,groupingParticipantId:e,tournamentRecord:r}){let n=(r.events||[]).filter(i=>i?.eventType===Fe&&i?.entries?.some(s=>s.participantId===e)),o=i=>!t.includes(i.participantId);for(let i of n){i.entries=(i.entries||[]).filter(o);let{flightProfile:s}=Ht({event:i});s?.flights?.forEach(a=>{a.drawEntries=(a.drawEntries||[]).filter(o)}),i?.drawDefinitions?.forEach(a=>{a.entries=(a.entries||[]).filter(o)})}return{...R}}function Yp({individualParticipantIds:t,groupingParticipantId:e,removeFromOtherTeams:r,tournamentRecord:n}){let o="addIndividualParticipantIds";if(!n)return _({result:{error:W},stack:o});if(!e||!t)return _({result:{error:et},stack:o});let i=n.participants??[],s=i.find(m=>m.participantId===e);if(!s)return _({result:{error:Zt},stack:o});if(s?.participantType&&![kt,Ar].includes(s.participantType))return _({context:{participantType:s.participantType},result:{error:nn},stack:o});let a=t.filter(m=>i.find(l=>l.participantId===m)?.participantType!==ht);if(a.length)return _({result:{error:zr,invalidParticipantIds:a},stack:o});s.individualParticipantIds||(s.individualParticipantIds=[]);let c=s.individualParticipantIds,u=t.filter(m=>!c.includes(m));u.length&&(r&&hp({individualParticipantIds:u,tournamentRecord:n}),s.individualParticipantIds=s.individualParticipantIds.concat(...u));let{topics:p}=Cr();if(p.includes(Qe)){let m=i.find(({participantId:d})=>d===e);Tt({topic:Qe,payload:{participants:[m]}})}return bv({individualParticipantIds:t,groupingParticipantId:e,tournamentRecord:n}),{groupingParticipant:J(s,!1,!0),added:u.length,...R}}function qp(t){let{updateParticipantName:e=!0,groupingParticipantId:r,removeFromOtherTeams:n,tournamentRecord:o,pairOverride:i,participant:s}=t;if(!o)return{error:W};if(!s)return{error:Mi};if(!s.participantId)return gn({tournamentRecord:o,participant:s});let{participant:a}=xo({participantId:s.participantId,tournamentRecord:o});if(!a)return gn({tournamentRecord:o,participant:s});let{participantRoleResponsibilties:c,individualParticipantIds:u,participantOtherName:p,participantName:m,participantRole:d,participantType:l,onlineResources:f,contacts:g,person:I}=s;if(l&&a.participantType!==l)return{error:Cy};let h={};if(g&&(h.contacts=g),f&&(h.onlineResources=f),m&&typeof m=="string"&&(h.participantName=m),p&&typeof p=="string"&&(h.participantOtherName=p),Array.isArray(u)){let{participants:S}=Yt({participantFilters:{participantTypes:[ht]},tournamentRecord:o}),T=S?.map(gt);if(T){let A=u.filter(D=>typeof D=="string"&&T.includes(D));([Ar,Bt].includes(l||a.participantType)||l===dt&&(A.length===2||i))&&(h.individualParticipantIds=A),a.participantType===nu.PAIR&&e&&(h.participantName=NV({individualParticipants:S,newValues:h}))}}return Object.keys(Xm).includes(d)&&(h.participantRole=d),Object.keys(nu).includes(l)&&(h.participantType=l),Array.isArray(c)&&(h.participantRoleResponsibilties=c),a.participantType===nu.INDIVIDUAL&&I&&MV({updateParticipantName:e,existingParticipant:a,newValues:h,person:I}),Object.assign(a,rt(h)),r&&Yp({individualParticipantIds:[a.participantId],groupingParticipantId:r,removeFromOtherTeams:n,tournamentRecord:o}),Tt({topic:Qe,payload:{tournamentId:o.tournamentId,participants:[a]}}),{participant:J(a),...R}}function NV({individualParticipants:t,newValues:e}){let r=e.individualParticipantIds,n=t.filter(({participantId:o})=>r.includes(o)).map(({person:o})=>o?.standardFamilyName).filter(Boolean).sort().join("/");return r.length===1&&(n+="/Unknown"),n}function MV({updateParticipantName:t,existingParticipant:e,newValues:r,person:n}){let o={},{standardFamilyName:i,standardGivenName:s,nationalityCode:a,personId:c,sex:u}=n;u&&Object.keys(Km).includes(u)&&(o.sex=u);let p;if(c&&typeof c=="string"&&(o.personId=c),a&&typeof a=="string"&&(CV(a)||a==="")&&(o.nationalityCode=a),i&&typeof i=="string"&&i.length>1&&(o.standardFamilyName=i,p=!0),s&&typeof s=="string"&&s.length>1&&(o.standardGivenName=s,p=!0),p&&t){let m=`${o.standardGivenName} ${o.standardFamilyName}`;r.participantName=m}Object.assign(e.person,o)}function CV(t){return Xo.flatMap(({iso:e,ioc:r})=>[e,r]).filter(Boolean).includes(t)}function Xd(t){let e=Qd(t);if(e.error)return e;let r="assignTieMatchUpParticipantId",n=t.teamParticipantId,{tournamentRecord:o,drawDefinition:i,participantId:s,event:a}=t;if(!s)return _({result:{error:oe},stack:r});if(t.sideNumber&&![1,2].includes(t.sideNumber))return _({result:{error:yl},stack:r});let{inContextDualMatchUp:c,inContextTieMatchUp:u,relevantAssignments:p,collectionPosition:m,teamParticipants:d,collectionId:l,matchUpType:f,dualMatchUp:g,tieFormat:I}=e;if(u?.sides?.flatMap(k=>k.participant?.individualParticipantIds||k.participant?.participantId||[])?.includes(s))return _({result:{...R},stack:r});n=n??(t.sideNumber?c?.sides?.find(k=>k.sideNumber===t.sideNumber)?.participantId:void 0);let S=Yt({participantFilters:{participantIds:[s]},tournamentRecord:o})?.participants?.[0];if(!S)return _({result:{error:Zt},stack:r});let{appliedPolicies:T}=Pt({tournamentRecord:o,drawDefinition:i,event:a}),A=t.policyDefinitions?.[ze]??T?.[ze]??us[ze];if((t.enforceGender??A?.participants?.enforceGender)!==!1&&[ee,ue].includes(u?.gender)&&u?.gender!==S.person?.sex)return{error:Us,info:"Gender mismatch"};let{individualParticipantIds:y,participantType:E}=S;if(ie(Xt)(f)&&E!==ht)return{error:nn};let U=E===ht?[s]:y,M=n&&d?.find(({participantId:k})=>k===n)||d?.find(({individualParticipantIds:k})=>xe(U,k));if(!M)return{error:xl};if(n||(n=M.participantId),!n)return{error:Zt};let N=p?.find(k=>k.participantId===M?.participantId)?.drawPosition,C=g?.sides?.find(k=>k.participantId===n)?.sideNumber,O=u?.sides?.find(k=>N&&k.drawPosition===N)?.sideNumber,b=C??O??t.sideNumber;if(!I)return{error:qa};if(!I.collectionDefinitions?.find(k=>k.collectionId===l))return{error:Ay};Ra({tournamentId:o.tournamentId,eventId:a.eventId,inContextDualMatchUp:c,drawDefinition:i,dualMatchUp:g});let w=g?.sides?.find(k=>k.sideNumber===b),F=u?.sides?.find(k=>k.sideNumber===b),B=(w?.lineUp??os({participantId:n,drawDefinition:i})?.lineUp)?.filter(k=>k.collectionAssignments?.find(K=>K.collectionPosition===m&&K.collectionId===l&&!K.previousParticipantId))?.map(k=>k?.participantId),H=B?.length>1&&B||(E===dt?S.individualParticipantIds:[s]),j=sA({collectionPosition:m,teamParticipantId:n,dualMatchUpSide:w,drawDefinition:i,participantIds:H,collectionId:l});if(j.error)return _({result:j,stack:r});let{modifiedLineUp:V}=j,Y;if(f===Gt){if(E!==dt){let k=NN({collectionPosition:m,teamParticipantId:n,drawDefinition:i,modifiedLineUp:V,participantId:s,collectionId:l,tieFormat:I});if(k?.error)return _({result:k,stack:r});if(k=$({side:F}),k.error)return k;Y=k.deletedParticipantId,w&&(w.lineUp=V),g&&It({tournamentId:o?.tournamentId,matchUp:g,context:r,drawDefinition:i})}else if(E===dt)for(let k of H)NN({collectionPosition:m,teamParticipantId:n,drawDefinition:i,modifiedLineUp:V,participantId:k,collectionId:l,tieFormat:I})}else{let k=NN({collectionPosition:m,teamParticipantId:n,drawDefinition:i,modifiedLineUp:V,participantId:s,collectionId:l,tieFormat:I});if(k?.error)return k}if(w&&(w.lineUp=V),g&&It({tournamentId:o?.tournamentId,matchUp:g,context:r,drawDefinition:i}),Y){let{error:k}=Li({participantIds:[Y],tournamentRecord:o});k&&console.log("cleanup")}return{...R,modifiedLineUp:V};function $({side:k}){let K;if(k.participant){let z=k.participant.individualParticipantIds||[];if(z.filter(Boolean).length===1){let{participant:nt}=tn({participantIds:z,tournamentRecord:o});z.push(s);let{participant:Q}=tn({participantIds:z,tournamentRecord:o});if(!Q&&nt){nt.individualParticipantIds=z;let it=qp({pairOverride:!0,tournamentRecord:o,participant:nt});if(it.error)return it}else K=nt?.participantId}}else{let q=gn({participant:{individualParticipantIds:[s],participantRole:Ge,participantType:dt},pairOverride:!0,tournamentRecord:o});if(q.error)return q}return{...R,deletedParticipantId:K}}}function NN({collectionPosition:t,teamParticipantId:e,drawDefinition:r,modifiedLineUp:n,participantId:o,collectionId:i,tieFormat:s}){let a=os({participantId:e,drawDefinition:r})?.lineUp,c=(n||a)?.find(p=>p?.participantId===o),u={collectionId:i,collectionPosition:t};if(c)c.collectionAssignments.push(u);else{let p={collectionAssignments:[u],participantId:o};n.push(p)}return Fi({participantId:e,lineUp:n,drawDefinition:r,tieFormat:s})}function MN(t){let{tournamentRecord:e,drawDefinition:r,participantId:n,event:o}=t,i="removeTieMatchUpParticiapantId";if(!n)return _({result:{error:oe},stack:i});let s=Qd(t);if(s.error)return s;let{appliedPolicies:a}=Pt({tournamentRecord:e,drawDefinition:r,event:o}),u=(t.policyDefinitions?.[ze]??a?.[ze]??us[ze])?.processCodes?.substitution,{inContextDualMatchUp:p,inContextTieMatchUp:m,relevantAssignments:d,collectionPosition:l,teamParticipants:f,collectionId:g,matchUpType:I,dualMatchUp:h,tieMatchUp:S,tieFormat:T}=s;if(!h)return _({result:{error:sr},stack:i});let A=m?.sides?.find(N=>N.participant?.participantId===n||N.participant?.individualParticipantIds?.includes(n));if(!A)return _({result:{error:Zt},stack:i});if(!A.substitutions?.length&&(Ie({score:m?.score})||m?.winningSide))return _({result:{error:eE},stack:i});let D=p?.sides?.find(({sideNumber:N})=>N===A.sideNumber)?.participantId;if(!D)return _({result:{error:Zt},stack:i});let y=Yt({participantFilters:{participantIds:[n]},tournamentRecord:e})?.participants?.[0];if(!y)return _({result:{error:Zt},stack:i});if(I===Xt&&y.participantType===dt)return _({result:{error:Us},stack:i});let E=y.participantType===ht?[n]:y.individualParticipantIds;Ra({tournamentId:e.tournamentId,eventId:o.eventId,inContextDualMatchUp:p,drawDefinition:r,dualMatchUp:h});let U=h.sides?.find(({sideNumber:N})=>N===A.sideNumber);if(!U&&(h.sides?.filter(({lineUp:N})=>!N).length||0)<2){let N=f?.map(({participantId:C})=>({drawPosition:d?.find(O=>O.participantId===C)?.drawPosition,teamParticipantId:C}));U=h.sides?.find(C=>N?.find(({drawPosition:O})=>O===C.drawPosition)?.teamParticipantId===D)}if(!U)return _({result:{error:Zt,context:{participantId:n}}});let{modifiedLineUp:M,previousParticipantIds:P}=sA({collectionPosition:l,teamParticipantId:D,dualMatchUpSide:U,participantIds:E,drawDefinition:r,collectionId:g});if(U.lineUp=M,D&&T&&Fi({participantId:D,lineUp:M,drawDefinition:r,tieFormat:T}),I===Gt&&y.participantType===ht){let N=m?.sides?.find(b=>b.sideNumber===U?.sideNumber),{participantId:C}=N??{},O=C&&Yt({participantFilters:{participantIds:[C]},tournamentRecord:e,withDraws:!0})?.participants?.[0];if(O){let b=O?.individualParticipantIds?.filter(x=>x!==n)??[];if(P&&b.push(...P),b.length>2)return _({result:{error:zr},stack:i});if(O.draws?.length){if(b.length===1){let{participant:x}=tn({participantIds:b,tournamentRecord:e});if(!x){let F=gn({participant:{participantRole:Ge,individualParticipantIds:b,participantType:dt},pairOverride:!0,tournamentRecord:e});if(F.error)return _({result:F,stack:i})}}}else if(b.length){O.individualParticipantIds=b;let x=qp({participant:O,pairOverride:!0,tournamentRecord:e});if(x.error)return _({result:x,stack:i})}else{let x=Li({participantIds:[C],tournamentRecord:e});x.error&&console.log("cleanup",{result:x})}}else return _({result:{error:Zt},stack:i})}if(A.substitutions?.length===1&&!m?.sides?.find(C=>C.sideNumber!==A.sideNumber)?.substitutions?.length&&S?.processCodes?.length){for(let C of u||[]){let O=S.processCodes.lastIndexOf(C);S.processCodes.splice(O,1)}It({tournamentId:e?.tournamentId,matchUp:S,context:i,drawDefinition:r})}return It({tournamentId:e?.tournamentId,matchUp:h,context:i,drawDefinition:r}),{...R,modifiedLineUp:M}}function wg(t){let e=lt(t,[{[An]:!0,[Yr]:!0,[Co]:!0}]);if(e.error)return e;let{drawDefinition:r,sideNumber:n,matchUpId:o,event:i}=t;if(n&&![1,2].includes(n))return{error:G,sideNumber:n};let{matchUp:s,structure:a}=xt({drawDefinition:r,matchUpId:o,event:i});return s?fr({structure:a})?(s.sides?.forEach(c=>{(!n||c.sideNumber===n)&&delete c.participantId}),It({tournamentId:t.tournamentRecord?.tournamentId,context:"assignSideParticipant",drawDefinition:r,matchUp:s}),{...R}):{error:nm}:{error:Oe}}function Ov({drawDefinition:t,matchUpStatus:e,matchUpsMap:r,winningSide:n,dualMatchUp:o,tieFormat:i,structure:s,matchUp:a,event:c,score:u}){let p=J(o,void 0,!0);for(let d of p?.tieMatchUps||[])d.matchUpId===a.matchUpId&&(d.winningSide=n,d.score=u,!Ie({score:u})&&!e?Object.assign(d,{...Tu}):e&&(d.matchUpStatus=e));i=i??je({matchUp:a,structure:s,drawDefinition:t,event:c})?.tieFormat;let{winningSide:m}=Uc({matchUp:p,drawDefinition:t,matchUpsMap:r,structure:s,tieFormat:i,event:c});return{projectedWinningSide:m}}function _v({matchUpStatuses:t=[Dt,_t,Ot],drawPositionMatchUps:e,loserDrawPosition:r,sourceMatchUps:n}){let o=e?.reduce((p,m)=>!p||m.roundNumber>p.roundNumber?m:p,void 0),i=o?.drawPositions?.find(p=>p!==r),s=n.filter(p=>p?.drawPositions?.includes(i)).map(p=>p.matchUpStatus),a=n.filter(p=>p?.drawPositions?.includes(r)).map(p=>p.matchUpStatus),c=xe(s||[],t),u=xe(a||[],t);return{sourceMatchUp:o,winnerHadMatchUpStatus:c,winnerMatchUpStatuses:s,loserHadMatchUpStatus:u,loserMatchUpStatuses:a}}function vv({inContextDrawMatchUps:t,sourceMatchUpStatus:e,targetDrawPosition:r,tournamentRecord:n,sourceMatchUpId:o,drawDefinition:i,structureId:s,dualMatchUp:a,roundNumber:c,matchUpsMap:u,event:p}){let{structure:m}=st({drawDefinition:i,structureId:s});if(m?.structureType===Le)return{...R};u=u??Ae({drawDefinition:i});let l=(u?.mappedMatchUps||{})[s].matchUps,{initialRoundNumber:f}=ss({drawPosition:r,matchUps:l}),g=l?.filter(h=>h.roundNumber>=c&&h.roundNumber!==f&&h.drawPositions?.includes(r)),{positionAssignments:I}=Nt({drawDefinition:i,structureId:s});for(let h of g??[])RV({inContextDrawMatchUps:t,sourceMatchUpStatus:e,positionAssignments:I,targetDrawPosition:r,tournamentRecord:n,sourceMatchUpId:o,drawDefinition:i,dualMatchUp:a,matchUpsMap:u,matchUp:h,event:p});return{...R}}function RV({inContextDrawMatchUps:t,positionAssignments:e,sourceMatchUpStatus:r,targetDrawPosition:n,tournamentRecord:o,sourceMatchUpId:i,drawDefinition:s,dualMatchUp:a,matchUpsMap:c,matchUp:u,event:p}){let m="removeSubsequentDrawPosition";if(a){let g=t.find(({matchUpId:h})=>u.matchUpId===h).sides?.find(h=>h.drawPosition===n)?.sideNumber,I=u.sides?.find(h=>h.sideNumber===g);I&&delete I.lineUp}u.drawPositions=(u.drawPositions||[]).map(f=>f===n?void 0:f).filter(Boolean);let l=e.filter(({drawPosition:f})=>u.drawPositions?.includes(f)).filter(f=>f.bye).length;return u.matchUpStatus=l&&Dt||[Ot,_t].includes(u.matchUpStatus)&&u.matchUpStatus||zt,[_t,Ot].includes(u.matchUpStatus)&&(u.winningSide=void 0),u.matchUpStatusCodes&&kh({inContextDrawMatchUps:t,sourceMatchUpStatus:r,sourceMatchUpId:i,matchUpsMap:c,matchUp:u}),It({tournamentId:o?.tournamentId,eventId:p?.eventId,context:`${m}-${n}`,drawDefinition:s,matchUp:u}),{...R}}function Rc(t){let{dualWinningSideChange:e,inContextDrawMatchUps:r,tournamentRecord:n,drawDefinition:o,matchUpStatus:i,matchUpsMap:s,dualMatchUp:a,targetData:c,matchUpId:u,structure:p,event:m}=t,d=!!t.matchUp.collectionId,l=fr({structure:p}),{drawPositions:f,winningSide:g}=c.matchUp||{};if(!l&&!f)return{error:Wa};let{targetLinks:{loserTargetLink:I,winnerTargetLink:h,byeTargetLink:S},targetMatchUps:{loserMatchUp:T,winnerMatchUp:A,byeMatchUp:D}}=c,y=Cn({...t,matchUpStatus:i||zt,removeWinningSide:!0});if(y.error)return y;let E;if(d){let{matchUpTieId:L,matchUpsMap:v}=t;if(E=zn({appliedPolicies:t.appliedPolicies,matchUpId:L,tournamentRecord:n,drawDefinition:o,matchUpsMap:v,event:m}),!e&&!E.removeWinningSide)return{...R}}if(l)return{...R};let{matchUps:U}=At({afterRecoveryTimes:!1,inContext:!0,drawDefinition:o,matchUpsMap:s,structure:p}),{positionAssignments:M}=de({structure:p}),P=g-1,N=1-P,C=f[P],O=f[N],{winnerParticipantId:b,loserParticipantId:x}=M?.reduce((L,v)=>(v.drawPosition===O&&(L.loserParticipantId=v.participantId),v.drawPosition===C&&(L.winnerParticipantId=v.participantId),L),{winnerParticipantId:void 0,loserParticipantId:void 0})||{},w=U.filter(L=>L.drawPositions?.includes(O));if(A&&CN({sourceMatchUpStatus:i,sourceMatchUpId:u,inContextDrawMatchUps:r,winningDrawPosition:C,winnerParticipantId:b,tournamentRecord:n,winnerTargetLink:h,drawDefinition:o,winnerMatchUp:A,dualMatchUp:a,matchUpsMap:s}),T){let{winnerHadMatchUpStatus:L}=_v({drawPositionMatchUps:w,loserDrawPosition:O,sourceMatchUps:U}),B=I.linkCondition===qn;if(L&&B){let j=Math.min(...T.drawPositions);aA({targetLink:I,inContextDrawMatchUps:r,drawDefinition:o,drawPosition:j,matchUpsMap:s,event:m})}let H=bV({sourceMatchUpStatus:i,sourceMatchUpId:u,loserParticipantId:x,tournamentRecord:n,loserTargetLink:I,drawDefinition:o,loserMatchUp:T,dualMatchUp:a,matchUpsMap:s,event:m});if(H.error)return H}if(D){let L=Math.min(...D.drawPositions);aA({sourceMatchUpId:u,targetLink:S,inContextDrawMatchUps:r,drawDefinition:o,drawPosition:L,matchUpsMap:s,event:m})}return{...R,...E&&{tieMatchUpResult:E}}}function CN({inContextDrawMatchUps:t,winningDrawPosition:e,sourceMatchUpStatus:r,winnerParticipantId:n,tournamentRecord:o,winnerTargetLink:i,sourceMatchUpId:s,drawDefinition:a,winnerMatchUp:c,matchUpsMap:u,dualMatchUp:p,event:m}){let{structureId:d,roundNumber:l}=c,f="removeDirectedWinner";if(i){let g=i.target.structureId,{structure:I}=st({drawDefinition:a,structureId:g});if(!I)return{error:Lt};let{positionAssignments:h}=de({structure:I});I.seedAssignments=(I.seedAssignments??[]).filter(M=>M.participantId!==n);let T=h?.find(M=>M.participantId===n)?.drawPosition,{matchUps:A}=At({drawDefinition:a,structure:I,event:m}),D=A.map(M=>M.drawPositions).flat(1/0).filter(Boolean),y=dr(D);if((T?y[T]:void 0)===1)h?.forEach(M=>{M.participantId===n&&delete M.participantId});else{let M=A.filter(({drawPositions:P})=>P.includes(T));console.log("not removing from position assignments since instances > 1",{drawPositionMatchUps:M,winnerTargetLink:i})}let U=u?.drawMatchUps?.find(({matchUpId:M})=>M===c.matchUpId);U&&It({tournamentId:o?.tournamentId,eventId:m?.eventId,matchUp:U,context:f,drawDefinition:a})}return l&&vv({targetDrawPosition:e,inContextDrawMatchUps:t,sourceMatchUpStatus:r,tournamentRecord:o,sourceMatchUpId:s,drawDefinition:a,dualMatchUp:p,matchUpsMap:u,roundNumber:l,structureId:d}),{...R}}function bV({sourceMatchUpStatus:t,loserParticipantId:e,tournamentRecord:r,loserTargetLink:n,sourceMatchUpId:o,drawDefinition:i,loserMatchUp:s,matchUpsMap:a,dualMatchUp:c,event:u}){let p="removeDirectedLoser",m=n.target.structureId,{structure:d}=st({drawDefinition:i,structureId:m});if(!d)return{error:Lt};let{positionAssignments:l}=de({structure:d}),f=l?.find(g=>g.participantId===e)?.drawPosition;if(l?.forEach(g=>{g.participantId===e&&delete g.participantId}),d.seedAssignments=(d.seedAssignments??[]).filter(g=>g.participantId!==e),c){let g=s?.sides.reduce((S,T,A)=>T.drawPosition===f?A:S,void 0),I=a?.drawMatchUps?.find(({matchUpId:S})=>S===s.matchUpId),h=I?.sides?.[g];h&&(delete h.lineUp,It({tournamentId:r?.tournamentId,eventId:u?.eventId,matchUp:I,context:p,drawDefinition:i}))}return{...R}}function aA({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,matchUpsMap:o,targetLink:i,event:s}){let a=i.target.structureId;return dc({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,matchUpsMap:o,drawPosition:n,structureId:a,event:s}),{...R}}function xv(t){let{matchUpFormat:e,score:r}=t,n=r?.sets?.length,o=e&&tr(e),{setFormat:i,finalSetFormat:s,bestOf:a}=o??{};return(a&&n===a&&s||i)?.timed||!1}function wv({tournamentRecord:t,drawDefinition:e,structure:r,matchUp:n}){let o="attemptToSetMatchUpStatusBYE";if(n?.winningSide)return _({result:{error:oa},context:{matchUpStatus:Dt},stack:o});let{positionAssignments:i}=de({structure:r}),s=i?.filter(c=>c.bye).map(c=>c.drawPosition);return n.drawPositions?.some(c=>s?.includes(c))?(n.matchUpStatus=Dt,n.matchUpStatusCodes=[],It({tournamentId:t?.tournamentId,context:o,drawDefinition:e,matchUp:n}),{...R}):_({result:{error:Ty},info:"matchUp does not include BYE",stack:o})}function Jd(t){let{tournamentRecord:e,appliedPolicies:r,drawDefinition:n,matchUpsMap:o,targetData:i,structure:s,event:a}=t,c="doubleExitAdvancement";if(s.structureType===Le)return _({result:{...R},stack:c});let{matchUp:u,targetMatchUps:p,targetLinks:m}=i,{loserMatchUp:d,winnerMatchUp:l,loserTargetDrawPosition:f}=p;if(d&&d.matchUpStatus!==Dt){let{loserTargetLink:g}=m;if(r?.progression?.doubleExitPropagateBye){let I=Fv({loserTargetDrawPosition:f,tournamentRecord:e,loserTargetLink:g,drawDefinition:n,loserMatchUp:d,matchUpsMap:o,event:a});if(I.error)return _({result:I,stack:c})}else{let{feedRound:I,drawPositions:h,matchUpId:S}=d,T=I?2:2-h.indexOf(f),A=Lv({...t,targetMatchUp:d,walkoverWinningSide:T,tournamentRecord:e,sourceMatchUp:u,matchUpId:S});if(A.error)return _({result:A,stack:c})}}if(l){let g=Lv({...t,matchUpId:l.matchUpId,targetMatchUp:l,tournamentRecord:e,sourceMatchUp:u});if(g.error)return _({result:g,stack:c})}return _({result:{...R},stack:c})}function Lv(t){let{inContextDrawMatchUps:e,tournamentRecord:r,drawDefinition:n,sourceMatchUp:o,targetMatchUp:i,matchUpsMap:s}=t,a=n.structures.find(({structureId:$})=>$===i.structureId),c=t.matchUpStatus===Ne?Ne:ge,u=t.matchUpStatus===Ne?Ot:_t,p="conditionallyAdvanceDrawPosition",m=s.drawMatchUps.find($=>$.matchUpId===i.matchUpId);if(!m)return{error:sr};let d=o?.drawPositions||[],l=m.drawPositions?.filter(Boolean),f=o?.structureId===i.structureId;if(f&&xe(d,l)&&(l=l.filter($=>!d.includes($))),f&&l.length>1)return _({result:{error:Ha},stack:p});let{pairedPreviousMatchUpIsDoubleExit:g,pairedPreviousMatchUp:I}=Fh(t),h=er({matchUpId:i.matchUpId,inContextDrawMatchUps:e,drawDefinition:n}),{targetMatchUps:S,targetLinks:T}=h,{loserTargetDrawPosition:A,winnerMatchUp:D,loserMatchUp:y}=S;if(y){let{loserTargetLink:$}=T,k=Fv({loserTargetDrawPosition:A,loserMatchUp:y,tournamentRecord:r,loserTargetLink:$,drawDefinition:n,matchUpsMap:s});if(k.error)return _({result:k,stack:p})}let E=m.drawPositions?.filter(Boolean)||[],U=E.length===1,M=t.walkoverWinningSide||U&&Zm({drawPosition:E[0],matchUpId:i.matchUpId,inContextDrawMatchUps:e})||void 0,P=[_t,Ot].includes(m.matchUpStatus)&&!E.length,N=m.finishingRound===1,C=P&&!N?c:u,O=e.find($=>$.matchUpId===I.matchUpId),b=[],x;o&&(o?.structureId===O?.structureId?o.roundPosition<I?.roundPosition?x=1:x=2:i.feedRound?o.structureId===i.structureId?x=2:x=1:M&&(x=3-M));let w=t.matchUpStatus,F=I?.matchUpStatus;x===1?b=[{matchUpStatus:cA(w),previousMatchUpStatus:w,sideNumber:1},{matchUpStatus:cA(F),previousMatchUpStatus:F,sideNumber:2}]:x===2&&(b=[{matchUpStatus:cA(F),previousMatchUpStatus:F,sideNumber:1},{matchUpStatus:cA(w),previousMatchUpStatus:w,sideNumber:2}]),b.length&&(b=b.map($=>rt($)));let L=Cn({...t,winningSide:M,matchUp:m,matchUpStatusCodes:b,context:p,matchUpStatus:C});if(L.error)return _({result:L,stack:p});if(P)return Jd({...t,matchUpStatus:C,targetData:h});if(!D)return _({result:{...R},stack:p});let v=l.length===2?l[M-1]:l[0],{positionAssignments:B}=Nt({structure:a}),H=B?.find($=>$.drawPosition===v),j=s.drawMatchUps.find($=>$.matchUpId===D.matchUpId),V=j?.drawPositions?.filter(Boolean),Y=V.length===1;if(v){if(H?.bye){let $=er({matchUpId:j.matchUpId,inContextDrawMatchUps:e,drawDefinition:n});if(Y){let k=V.filter(Boolean)[0],K=Zm({drawPosition:k,matchUpId:j.matchUpId,inContextDrawMatchUps:e}),z=Cn({appliedPolicies:t.appliedPolicies,matchUpId:j.matchUpId,matchUp:j,matchUpStatus:u,matchUpStatusCodes:[],removeScore:!0,context:p,drawDefinition:n,winningSide:K});return z.error?_({result:z,stack:p}):Rh({drawPositionToAdvance:k,matchUpId:j.matchUpId,inContextDrawMatchUps:e,drawDefinition:n,matchUpsMap:s})}else if([_t,Ot].includes(D.matchUpStatus)){let k=Jd({...t,matchUpId:j.matchUpId,matchUpStatus:C,targetData:$});if(k.error)return _({result:k,stack:p})}return _({result:{...R},stack:p})}return Ic({matchUpId:D.matchUpId,drawPosition:v,inContextDrawMatchUps:e,drawDefinition:n})}else if(g){if(!j)return{error:sr};if(Y){let K=V[0],z=Zm({matchUpId:i.matchUpId,inContextDrawMatchUps:e,drawPosition:K});console.log("existing drawPosition is winningSide",{walkoverWinningSide:z})}let $=[_t,Ot].includes(j.matchUpStatus)?u:c,k=Cn({matchUpId:j.matchUpId,appliedPolicies:t.appliedPolicies,matchUp:j,matchUpStatusCodes:[],removeScore:!0,context:p,drawDefinition:n,matchUpStatus:$});if(k.error)return _({result:k,stack:p});if($===c){let K=Jd({...t,matchUpId:i.matchUpId,matchUpStatus:$,targetData:h});if(K.error)return K}}return _({result:{...R},stack:p})}function Fv(t){let{loserTargetDrawPosition:e,tournamentRecord:r,loserTargetLink:n,drawDefinition:o,matchUpsMap:i,event:s}=t,a=n?.target?.structureId,{structure:c}=st({drawDefinition:o,structureId:a});return c?Dr({drawPosition:e,tournamentRecord:r,drawDefinition:o,structureId:a,matchUpsMap:i,event:s}):{error:Do}}function cA(t){return t===ge?_t:t===Ne?Ot:t}function Gv(t){let{tournamentRecord:e,drawDefinition:r,matchUpStatus:n,structure:o,matchUp:i}=t,s=!!(i.tieMatchUps&&!i.rondPosition&&t.inContextDrawMatchUps.find(h=>h.matchUpId===i.matchUpId).containerStructureId),a="attemptToSetMatchUpStatus",c=n===Dt,u=i.winningSide,p=[ge,Ne].includes(n),m=Ea({matchUpStatus:n}),d=Gf({matchUpStatus:n}),l=!m&&!d,f=t.matchUpTieId||u&&m&&!p,g=u&&p,I=()=>Cn({...t,removeScore:[Wo,_t].includes(n),matchUpStatus:n||zt});return l&&{error:dI}||f&&RN(t)||g&&OV(t)||u&&Rc(t)||d&&I()||c&&wv({tournamentRecord:e,drawDefinition:r,structure:o,matchUp:i})||!m&&{error:dI}||p&&_V(t)||s&&RN(t)||_({result:{error:oa},stack:a})}function OV(t){let e=Rc(t);return e.error?e:Jd(t)}function _V(t){let e=RN({...t,removeScore:!0});return e.error?e:Jd(t)}function RN(t){let e="scoreModification";if(t.isCollectionMatchUp&&t.dualMatchUp?.winningSide&&!t.projectedWinningSide){let i=Rc(t);if(i.error)return _({result:i,stack:e})}let n=!!t.matchUp.collectionId,o=Cn({...t,context:e});if(n){let{matchUpTieId:i,drawDefinition:s,matchUpsMap:a}=t,c=zn({tournamentRecord:t.tournamentRecord,appliedPolicies:t.appliedPolicies,matchUpId:i,event:t.event,drawDefinition:s,matchUpsMap:a});if(c.error)return _({result:c,stack:e});Object.assign(o,{tieMatchUpResult:c})}return _({result:o,stack:e})}function kv({drawDefinition:t,structure:e,matchUp:r}){let{drawPositions:n}=r,{positionAssignments:o}=Nt({drawDefinition:t,structure:e}),s=o?.filter(({drawPosition:m})=>n?.includes(m))?.map(m=>{let{extension:d}=mt({element:m,name:Ho});return d?.value?.groupOrder}),{containerStructures:a}=Ji({drawDefinition:t}),c=a[e.structureId];return{structureIds:ks({drawDefinition:t,structureId:c})?.links?.source?.filter(m=>xe(s,m.source?.finishingPositions||[])).map(m=>m.source.structureId)}}function uA({drawDefinition:t,structure:e,matchUp:r}){let n=[];if(e.finishingPosition===vs&&Jo({drawDefinition:t,structure:e})){let{structureIds:i}=kv({drawDefinition:t,structure:e,matchUp:r});i?.length&&n.push(...i)}return{connectedStructureIds:n}}function Vv(t){let e,{inContextDrawMatchUps:r,inContextMatchUp:n,drawDefinition:o,winningSide:i}=t,s=t.targetData.targetLinks?.winnerTargetLink;if(s.target.feedProfile===Qr){let a=n.sides.find(({sideNumber:u})=>u!==i).participantId,c=r.find(u=>u.structureId===s.target.structureId&&u.roundNumber===s.target.roundNumber&&u.sides.some(({participantId:p})=>p===a));if(c?.matchUpStatus===zt){let u=er({matchUpId:c.matchUpId,inContextDrawMatchUps:r,drawDefinition:o});if(!Ai({inContextDrawMatchUps:r,drawDefinition:o,targetData:u})){let{structure:m}=st({structureId:c.structureId,drawDefinition:o}),d=Nt({structure:m}).positionAssignments;for(let l of d||[])if(l.participantId===a){let f=n.sides.find(({sideNumber:g})=>g===i).participantId;if(l.participantId=f,m?.positionAssignments)m.positionAssignments=d;else if(m?.structures){let g=Object.assign({},...(d||[]).map(I=>({[I.drawPosition]:I.participantId})));for(let I of m.structures)I.positionAssignments?.forEach(h=>h.participantId=g[h.drawPosition])}To({tournamentId:t.tournamentRecord?.tournamentId,event:t.event,drawDefinition:o,structure:m}),e=!0}}}}return{...R,qualifierReplaced:e}}function Bv(t){let e,{inContextDrawMatchUps:r,inContextMatchUp:n,drawDefinition:o,winningSide:i}=t,s=t.targetData.targetLinks?.winnerTargetLink;if(s.target.feedProfile===Qr){let a=n.sides.find(({sideNumber:p})=>p===i)?.participantId,c=r.filter(p=>p.structureId===s.target.structureId&&p.roundNumber===s.target.roundNumber&&p.sides.some(({participantId:m,qualifier:d})=>d&&!m)),u=on(c);if(u?.matchUpStatus===zt){let p=er({matchUpId:u.matchUpId,inContextDrawMatchUps:r,drawDefinition:o});if(!Ai({inContextDrawMatchUps:r,drawDefinition:o,targetData:p})){let d=u.sides.find(g=>g.qualifier&&!g.participantId)?.drawPosition,{structure:l}=st({structureId:u.structureId,drawDefinition:o});if(!l)return{error:Lt};let f=Nt({structure:l}).positionAssignments;for(let g of f||[])if(g.drawPosition===d&&!g.participantId){if(g.participantId=a,l.positionAssignments)l.positionAssignments=f;else if(l.structures){let I=Object.assign({},...(f||[]).map(h=>({[h.drawPosition]:h.participantId})));for(let h of l.structures)h.positionAssignments?.forEach(S=>S.participantId=I[S.drawPosition])}To({tournamentId:t.tournamentRecord?.tournamentId,event:t.event,drawDefinition:o,structure:l}),e=!0}}}}return{...R,qualifierPlaced:e}}function Hv(t){let e="attemptToSetWinningSide",r,{appliedPolicies:n,disableAutoCalc:o,drawDefinition:i,dualMatchUp:s,winningSide:a,structure:c,matchUp:u}=t;if(s?._disableAutoCalc&&o!==!1)return ud(t);if(u.winningSide&&u.winningSide!==a){let{connectedStructureIds:l}=uA({drawDefinition:i,structure:c,matchUp:u});l.length&&(console.log({connectedStructureIds:l}),r=!0);let f=Rc(t);if(f.error)return f}let p=uS(t);if(p.error)return _({result:p,stack:e});let m,d;return t.qualifierChanging&&n?.[Hc]?.autoReplaceQualifiers&&(m=Vv(t).qualifierReplaced),t.qualifierAdvancing&&n?.[Hc]?.autoPlaceQualifiers&&(d=Bv(t).qualifierPlaced),_({result:rt({...R,...p,connectedStructures:r,qualifierReplaced:m,qualifierPlaced:d}),stack:e})}var pA={drawPositionToRemove:"green",iteration:"brightred",winner:"green",loser:"brightred"};function bN(t){let{inContextDrawMatchUps:e,appliedPolicies:r,drawDefinition:n,matchUpsMap:o,targetData:i,matchUp:s}=t,{iteration:a=0}=t;a+=1;let c="removeDoubleExit";kn({method:c,color:"brightyellow",iteration:a,keyColors:pA});let{targetLinks:{loserTargetLink:u},targetMatchUps:{loserMatchUp:p,winnerMatchUp:m,loserTargetDrawPosition:d}}=i;if(m&&m.matchUpStatus!==Dt){let{stage:l,roundNumber:f,roundPosition:g}=m;kn({winner:"winner",stage:l,roundNumber:f,roundPosition:g,keyColors:pA}),Wv({...t,targetMatchUp:m,sourceMatchUp:s,iteration:a})}if(p&&p.matchUpStatus!==Dt){let l=e.find(({matchUpId:T})=>T===p.matchUpId),{structure:f}=st({drawDefinition:n,structureId:l.structureId}),{stage:g,roundNumber:I,roundPosition:h,feedRound:S}=p;if(kn({loser:"loser",stage:g,roundNumber:I,roundPosition:h,keyColors:pA,feedRound:S}),r?.progression?.doubleExitPropagateBye)aA({drawPosition:d,targetLink:u,inContextDrawMatchUps:e,drawDefinition:n,matchUpsMap:o});else{let T=Wv({...t,structure:f,targetMatchUp:p,iteration:a});if(T.error)return _({result:T,stack:c})}}return _({result:{...R},stack:c})}function Wv(t){let{inContextDrawMatchUps:e,appliedPolicies:r,drawDefinition:n,sourceMatchUp:o,targetMatchUp:i,matchUpsMap:s,structure:a,iteration:c}=t,u="conditionallyRemoveDrawPosition";kn({method:u});let p=er({matchUpId:i.matchUpId,inContextDrawMatchUps:e,drawDefinition:n}),{targetMatchUps:{winnerMatchUp:m}}=p,d=s?.drawMatchUps.find(A=>A.matchUpId===i.matchUpId),l=[],f,g,I;if(i.feedRound)I=m?.drawPositions?.filter(Boolean)?.find(D=>i.drawPositions.includes(D));else if(!o)I=jt(i?.drawPositions||[],m?.drawPositions||[])?.[0];else if(g=Gh({structureId:a.structureId,matchUp:o,matchUpsMap:s})?.pairedPreviousMatchUp,f=[ge,Ne].includes(g?.matchUpStatus),l=g?.drawPositions?.filter(Boolean)||[],[...ae,Dt].includes(g?.matchUpStatus)||g?.winningSide){let D=o.drawPositions||[],y=i.drawPositions?.filter(Boolean);xe(D,y)&&(y=y?.filter(U=>!D.includes(U))),I=D.concat(l).find(U=>y?.includes(U))}if(m&&I){let{stage:A,roundNumber:D,roundPosition:y}=m;kn({method:"removeDirectedWinner",drawPositionToRemove:I,keyColors:pA,color:"brightgreen",stage:A,roundNumber:D,roundPosition:y}),CN({winningDrawPosition:I,winnerMatchUp:m,inContextDrawMatchUps:e,drawDefinition:n,matchUpsMap:s})}let h=bN({targetData:p,matchUp:i,inContextDrawMatchUps:e,appliedPolicies:r,drawDefinition:n,matchUpsMap:s,structure:a,iteration:c});if(h.error)return _({result:h,stack:u});let S=vV({pairedPreviousDoubleExit:f,noContextTargetMatchUp:d}),T=!f;return h=Cn({...t,matchUpId:i.matchUpId,matchUp:d,removeWinningSide:!0,matchUpStatusCodes:[],context:u,matchUpStatus:S,removeScore:T,score:{scoreStringSide1:"",scoreStringSide2:"",sets:void 0}}),h.error?_({result:h,stack:u}):{...R}}function vV({pairedPreviousDoubleExit:t,noContextTargetMatchUp:e}){return e.matchUpStatus===Dt?Dt:t?[Ne,Ot].includes(e?.matchUpStatus)?Ot:_t:zt}function jv(t){let e,{inContextDrawMatchUps:r,inContextMatchUp:n,drawDefinition:o}=t,i=t.targetData.targetLinks?.winnerTargetLink;if(i.target.feedProfile===Qr){let s=n.sides?.find(({sideNumber:c})=>c===n.winningSide)?.participantId,a=r.find(c=>c.structureId===i.target.structureId&&c.roundNumber===i.target.roundNumber&&c.sides?.some(({participantId:u})=>u===s));if(a&&a.matchUpStatus===zt){let c=er({matchUpId:a.matchUpId,inContextDrawMatchUps:r,drawDefinition:o});if(!Ai({inContextDrawMatchUps:r,drawDefinition:o,targetData:c})){let{structure:p}=st({structureId:a.structureId,drawDefinition:o}),m=Nt({structure:p}).positionAssignments;for(let d of m||[])if(d.participantId===s){if(d.participantId=void 0,p?.positionAssignments)p.positionAssignments=m;else if(p?.structures){let l=Object.assign({},...(m||[]).map(f=>({[f.drawPosition]:f.participantId})));for(let f of p?.structures||[])f.positionAssignments?.forEach(g=>g.participantId=l[g.drawPosition])}To({tournamentId:t.tournamentRecord?.tournamentId,event:t.event,drawDefinition:o,structure:p}),e=!0}}}}return{qualifierRemoved:e}}function qv(t){let{matchUp:e,matchUpStatus:r,score:n,winningSide:o}=t,i="noDownStreamDependencies";if([ge,Ne].includes(e?.matchUpStatus)&&![ge,Ne].includes(r)){let I=bN(t);if(I.error)return _({result:I,stack:i})}let a=r===ge,c=Ie({score:n})&&!a&&(t.isCollectionMatchUp&&!t.projectedWinningSide||!o),u=t?.inContextMatchUp?.collectionId&&xv(t.inContextMatchUp),p=t.removeScore||!u&&![_o,$r].includes(r||_o),m=t.isCollectionMatchUp&&t.dualMatchUp.winningSide&&!t.projectedWinningSide||e.winningSide&&!o&&!Ie({score:n}),d=r&&r!==zt,l=I=>{let h,{structure:S,drawDefinition:T,dualMatchUp:A,disableAutoCalc:D}=t;if(A?._disableAutoCalc&&D!==!1)return ud(t);let{connectedStructureIds:y}=uA({drawDefinition:T,structure:S,matchUp:e});y.length&&(console.log({connectedStructureIds:y}),h=!0),Object.assign(t,{removeScore:I});let E=Rc(t);if(E.error)return E;if(t.removingQualifier&&t.appliedPolicies?.[Hc]?.autoRemoveQualifiers){let U=jv(t);return{...R,connectedStructures:h,...U}}return{...R,connectedStructures:h}};if(m&&o&&t.isCollectionMatchUp)return Yv(t);let f=[Wo,$r].includes(r)&&t.dualWinningSideChange,g=(o||f)&&Hv(t)||c&&l(p)||d&&Gv(t)||m&&l(p)||e&&Yv({...t,removeScore:!0})||{...R};return _({result:g,stack:i})}function Yv(t){let e="scoreModification";if(t.isCollectionMatchUp&&t.dualMatchUp?.winningSide&&!t.projectedWinningSide){let o=Rc(t);if(o.error)return o}let n=Cn({...t,context:e});if(t.isCollectionMatchUp){let{matchUpTieId:o,drawDefinition:i,event:s,matchUpsMap:a}=t,{removeWinningSide:c}=zn({tournamentRecord:t.tournamentRecord,appliedPolicies:t.appliedPolicies,matchUpId:o,drawDefinition:i,matchUpsMap:a,event:s});c&&console.log("REMOVE WINNING SIDE")}return _({result:n,stack:e})}function Vo(t){let e="addMatchUpScheduledTime",r=t.matchUp,{removePriorValues:n,tournamentRecord:o,drawDefinition:i,disableNotice:s,scheduledTime:a,matchUpId:c}=t;if(!c)return _({result:{error:ke},stack:e});if(!Bc(a))return _({result:{error:mo},stack:e});if(!r){let I=xt({drawDefinition:i,matchUpId:c});if(I.error)return _({result:I,stack:e});r=I.matchUp}let u=Ut(a),p=rs({matchUp:r}).scheduledDate,m=u&&!p;if((xf({matchUp:r}).timeModifiers||[])?.length){let I=ON({disableNotice:!0,removePriorValues:n,tournamentRecord:o,timeModifiers:[],drawDefinition:i,matchUpId:c,matchUp:r});if(I?.error)return _({result:I,stack:e})}let f=tc(a,!0,m);return rn({duplicateValues:!1,removePriorValues:n,tournamentRecord:o,drawDefinition:i,disableNotice:s,matchUpId:c,timeItem:{itemType:Ls,itemValue:f}})}function ON({removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,timeModifiers:o,matchUpId:i,matchUp:s}){let a="addMatchUpTimeModifiers";if(!i)return _({result:{error:ke},stack:a});if(o!==void 0&&!Array.isArray(o))return _({info:Nn("timeModifiers"),result:{error:G},stack:a});if(!s){let l=xt({drawDefinition:r,matchUpId:i});if(l.error)return _({result:l,stack:a});s=l.matchUp}let c=xf({matchUp:s}).timeModifiers||[],u=o.filter(l=>!c.includes(l));if(o.length&&!u.length)return{...R};if(u.some(l=>uh.includes(l))){c=c.filter(f=>!uh.includes(f));let l=Vo({disableNotice:!0,removePriorValues:t,scheduledTime:"",tournamentRecord:e,drawDefinition:r,matchUpId:i});if(l.error)return _({result:l,stack:a})}let m=o?.length?[...u,...c]:void 0;return rn({duplicateValues:!1,removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,matchUpId:i,timeItem:{itemType:bf,itemValue:m}})}function $p({removePriorValues:t,tournamentRecords:e,tournamentRecord:r,drawDefinition:n,disableNotice:o,courtDayDate:i,matchUpId:s,courtIds:a}){if(!r&&!e)return{error:W};if(!s)return{error:ke};let c=xt({drawDefinition:n,matchUpId:s});if(c.error)return c;if(c?.matchUp?.matchUpType!==ln)return{error:Je};if(!(a===void 0||Array.isArray(a)&&a.length&&a.every(d=>typeof d=="string")))return{error:G,context:{courtIds:a}};let p;if(a){let d=e||r&&{[r.tournamentId]:r},l=po({tournamentRecords:d});if(l.error)return l;let f=l.courts?.filter(g=>a.includes(g.courtId));if(f?.length!==a.length)return{error:G,context:{courtIds:a}};p=f?.map(g=>({venueId:g.venueId,courtId:g.courtId}))}return rn({duplicateValues:!1,removePriorValues:t,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:s,timeItem:{itemType:Eo,itemDate:i,itemValue:p}})}function Zs({removePriorValues:t,tournamentRecords:e,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:i,venueId:s}){if(!r)return{error:W};if(!i)return{error:ke};if(s){let c=Qo({tournamentRecords:e,tournamentRecord:r,venueId:s});if(c.error)return c}return rn({duplicateValues:!1,removePriorValues:t,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:i,timeItem:{itemType:xs,itemValue:s}})}function Hi({removePriorValues:t,tournamentRecords:e,tournamentRecord:r,drawDefinition:n,disableNotice:o,courtDayDate:i,matchUpId:s,courtId:a}){if(!r&&!e)return{error:W};if(!s)return{error:ke};if(a){let u=ns({tournamentRecords:e,tournamentRecord:r,courtId:a});if(u.error)return u;let p=u.venue?.venueId;Zs({tournamentRecords:e,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:s,venueId:p})}return rn({duplicateValues:!1,removePriorValues:t,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:s,timeItem:{itemType:di,itemDate:i,itemValue:a}})}function Ss(t,e){let r=xI.test(t)?t:$t(t),n=Ut(t)||Ut(e)||ro(new Date);return new Date(`${n}T${r}`).getTime()}function Kp({errorOnAnachronism:t=!1,checkChronology:e=!0,matchUpDependencies:r,inContextMatchUps:n,removePriorValues:o,tournamentRecords:i,tournamentRecord:s,drawDefinition:a,disableNotice:c,drawMatchUps:u,matchUpId:p,schedule:m,event:d}){if(!m)return{error:et,info:"Missing schedule"};if(!a)return{error:X};if(!p)return{error:ke};let l="addMatchUpScheduleItems",f,g;if(u)f=u.find(C=>C.matchUpId===p);else{let C=xt({drawDefinition:a,event:d,matchUpId:p});if(C.error)return C;f=C.matchUp}let{endTime:I,courtId:h,courtIds:S,courtOrder:T,resumeTime:A,scheduledDate:D,scheduledTime:y,startTime:E,stopTime:U,timeModifiers:M,venueId:P}=m;e&&(!r||!n)&&({matchUpDependencies:r,matchUps:n}=Vr({drawDefinition:a}));let N=r?.[p]?.matchUpIds;if(m.scheduledDate&&e&&N){let C=n?.filter(O=>(O.schedule?.scheduledDate||Ut(O.schedule?.scheduledTime))&&N.includes(O.matchUpId)).map(({schedule:O})=>{let b=Im(O);return new Date(b).getTime()});if(C?.length){let O=Im(m),b=new Date(O).getTime();if(Math.max(...C)>=b){if(t)return _({result:{error:aI},stack:l});g=aI}}}if(D!==void 0){let C=Zd({disableNotice:!0,removePriorValues:o,tournamentRecord:s,drawDefinition:a,scheduledDate:D,matchUpId:p});if(C?.error)return _({result:C,stack:l,context:{scheduledDate:D}})}if(y!==void 0){let C=Vo({disableNotice:!0,removePriorValues:o,tournamentRecord:s,drawDefinition:a,scheduledTime:y,matchUpId:p,matchUp:f});if(C?.error)return _({result:C,stack:l,context:{scheduledTime:y}})}if(E!==void 0){let C=dA({disableNotice:!0,removePriorValues:o,tournamentRecord:s,drawDefinition:a,matchUpId:p,startTime:E,event:d});if(C?.error)return _({result:C,stack:l,context:{startTime:E}})}if(U!==void 0){let C=fA({disableNotice:!0,removePriorValues:o,tournamentRecord:s,drawDefinition:a,matchUpId:p,stopTime:U,event:d});if(C?.error)return _({result:C,stack:l,context:{stopTime:U}})}if(A!==void 0){let C=gA({disableNotice:!0,removePriorValues:o,tournamentRecord:s,drawDefinition:a,resumeTime:A,matchUpId:p,event:d});if(C?.error)return _({result:C,stack:l,context:{resumeTime:A}})}if(I!==void 0){let C=lA({disableNotice:!0,removePriorValues:o,tournamentRecord:s,drawDefinition:a,matchUpId:p,endTime:I,event:d});if(C?.error)return _({result:C,stack:l,context:{endTime:I}})}if(S!==void 0){let C=$p({disableNotice:!0,removePriorValues:o,tournamentRecord:s,drawDefinition:a,matchUpId:p,courtIds:S});if(C?.error)return _({result:C,stack:l,context:{courtIds:S}})}if(h!==void 0&&D!==void 0){let C=Hi({courtDayDate:D,disableNotice:!0,removePriorValues:o,tournamentRecords:i,tournamentRecord:s,drawDefinition:a,matchUpId:p,courtId:h});if(C?.error)return _({result:C,stack:l,context:{courtId:h}})}if(P!==void 0){let C=Zs({disableNotice:!0,removePriorValues:o,tournamentRecords:i,tournamentRecord:s,drawDefinition:a,matchUpId:p,venueId:P});if(C?.error)return _({result:C,stack:l,context:{venueId:P}})}if(T!==void 0&&ft(T)){let C=mA({disableNotice:!0,removePriorValues:o,tournamentRecord:s,drawDefinition:a,courtOrder:T,matchUpId:p});if(C?.error)return _({result:C,stack:l,context:{courtOrder:T}})}if(M!==void 0){let C=ON({disableNotice:!0,removePriorValues:o,tournamentRecord:s,drawDefinition:a,timeModifiers:M,matchUpId:p,matchUp:f});if(C?.error)return _({result:C,stack:l,context:{timeModifiers:M}})}return c||It({tournamentId:s?.tournamentId,eventId:d?.eventId,context:l,drawDefinition:a,matchUp:f}),g?{...R,warnings:[g]}:{...R}}function Zd({scheduledDate:t,removePriorValues:e,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:i}){if(!i)return{error:ke};let s=t&&Ro.test(t);if(t&&!s)return{error:ar};let c={itemValue:Ut(t),itemType:ws};return rn({duplicateValues:!1,removePriorValues:e,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:i,timeItem:c})}function mA({removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,courtOrder:o,matchUpId:i}){if(!i)return{error:ke};if(o&&!ft(o))return{error:G,info:"courtOrder must be numeric"};let s=o&&ct(o);return rn({duplicateValues:!1,removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,matchUpId:i,timeItem:{itemType:Rf,itemValue:s}})}function _N({removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,participantId:o,officialType:i,matchUpId:s}){if(!s)return{error:ke};if(!o)return{error:oe};if(e){let c=Yt({tournamentRecord:e,participantFilters:{participantTypes:[ht],participantRoles:[Bf]}}).participants??[];if(!bo({tournamentParticipants:c,participantId:o}))return{error:Zt}}let a={itemType:"SCHEDULE.ASSIGNMENT.OFFICIAL",itemValue:o};return i&&(a.itemSubTypes=[i]),rn({duplicateValues:!1,removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,matchUpId:s,timeItem:a})}function dA({removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,matchUpId:o,startTime:i,event:s}){if(!o)return{error:ke};if(!Bc(i))return{error:mo};let{matchUp:a}=xt({drawDefinition:r,event:s,matchUpId:o}),{scheduledDate:c}=rs({matchUp:a}),p=(a?.timeItems??[]).filter(m=>[xi,li,fi].includes(m?.itemType)).map(m=>Ss(m.itemValue,c)).reduce((m,d)=>!m||d<m?d:m,void 0);if(!p||Ss(i,c)<p){a?.timeItems&&(a.timeItems=a.timeItems.filter(l=>l.itemType!==Uo));let m=tc(i,!0,!0);return rn({duplicateValues:!1,removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,matchUpId:o,timeItem:{itemType:Uo,itemValue:m}})}else return{error:Yy}}function lA({validateTimeSeries:t=!0,removePriorValues:e,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:i,endTime:s,event:a}){if(!i)return{error:ke};if(!Bc(s))return{error:mo};let{matchUp:c}=xt({drawDefinition:n,event:a,matchUpId:i}),{scheduledDate:u}=rs({matchUp:c}),m=(c?.timeItems??[]).filter(d=>[Uo,li,xi].includes(d?.itemType)).map(d=>Ss(d.itemValue,u)).reduce((d,l)=>!d||l>d?l:d,void 0);if(!t||!m||Ss(s,u)>m){c?.timeItems&&(c.timeItems=c.timeItems.filter(f=>f.itemType!==fi));let d=tc(s,!0,!0);return rn({duplicateValues:!1,removePriorValues:e,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:i,timeItem:{itemType:fi,itemValue:d}})}else return{error:Wy}}function fA({removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,matchUpId:o,stopTime:i,event:s}){if(!o)return{error:ke};if(!Bc(i))return{error:mo};let{matchUp:a}=xt({drawDefinition:r,event:s,matchUpId:o}),{scheduledDate:c}=rs({matchUp:a}),u=a?.timeItems??[];if(u.reduce((g,I)=>I.itemType===fi||g,void 0))return{error:TI};let m=u.filter(g=>[Uo,li,xi].includes(g?.itemType)).sort((g,I)=>Ss(g.itemValue,c)-Ss(I.itemValue,c)),d=m[m.length-1],l=d&&d.itemType===xi,f=m.filter(g=>!l||g.createdAt!==d.createdAt).map(g=>Ss(g.itemValue,c)).reduce((g,I)=>!g||I>g?I:g,void 0);if(Ss(i,c)>f){if(a?.timeItems&&l){let h=d.createdAt;a.timeItems=a.timeItems.filter(S=>S.createdAt!==h)}let I={itemValue:tc(i,!0,!0),itemType:xi};return rn({duplicateValues:!0,removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,matchUpId:o,timeItem:I})}else return{error:jy}}function gA({removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,resumeTime:o,matchUpId:i,event:s}){if(!i)return{error:ke};if(!Bc(o))return{error:mo};let{matchUp:a}=xt({drawDefinition:r,event:s,matchUpId:i}),{scheduledDate:c}=rs({matchUp:a}),u=a?.timeItems??[];if(u.reduce((g,I)=>I.itemType===fi||g,void 0))return{error:TI};let m=u.filter(g=>[Uo,li,xi].includes(g?.itemType)).sort((g,I)=>Ss(g.itemValue,c)-Ss(I.itemValue,c)),d=m[m.length-1],l=d&&d.itemType===li,f=m.filter(g=>!l||g.createdAt!==d.createdAt).map(g=>Ss(g.itemValue,c)).reduce((g,I)=>!g||I>g?I:g,void 0);if(Ss(o,c)>f){if(a?.timeItems&&l){let h=d.createdAt;a.timeItems=a.timeItems.filter(S=>S.createdAt!==h)}let I={itemValue:tc(o,!0,!0),itemType:li};return rn({duplicateValues:!0,removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,matchUpId:i,timeItem:I})}else return{error:wC}}function $v(t){let{tournamentRecord:e,inContextMatchUp:r,structure:n,drawDefinition:o}=t,i=r.roundNumber,s=r.sides.find(y=>y.sideNumber===r.winningSide),a=r.sides.find(y=>y.sideNumber!==r.winningSide),{drawPosition:c,participantId:u}=s,{drawPosition:p,participantId:m}=a,d="swapWinnerLoser",{matchUps:l}=At(t),f=l.filter(({drawPositions:y,roundNumber:E})=>y?.includes(c)&&E>i);yr({changeWinner:!0})&&console.log({existingWinnerSubsequentMatchUps:f}),f.forEach(y=>{y.drawPositions=y.drawPositions?.map(E=>E===c?p:E)||[],It({tournamentId:e?.tournamentId,eventId:t.event?.eventId,context:d,drawDefinition:o,matchUp:y})});let{stage:g,stageSequence:I}=n,h=o.structures.filter(({stage:y,stageSequence:E})=>y===g&&E>I).map(({structureId:y})=>y),{targetLinks:{loserTargetLink:S,winnerTargetLink:T}}=t.targetData,A=[S?.target.structureId,T?.target?.structureId].filter(Boolean);return o.structures.filter(({stage:y,structureId:E})=>y!==g&&A.includes(E)).forEach(({stage:y,stageSequence:E,structureId:U})=>{h.includes(U)||h.push(U),o.structures.filter(({stage:M,stageSequence:P})=>M===y&&P>E).forEach(({structureId:M})=>{h.includes(M)||h.push(M)})}),o.structures.filter(({structureId:y})=>h.includes(y)).forEach(y=>{let{positionAssignments:E}=Nt({structure:y}),U=E?.find(({participantId:P})=>P===u),M=E?.find(({participantId:P})=>P===m);U&&(U.participantId=m),M&&(M.participantId=u)}),Cn({...t,context:d})}function La(t){let e="setMatchUpStatus";t.matchUpStatus&&[_t,ge].includes(t.matchUpStatus)&&(t.score=void 0);let{allowChangePropagation:r,disableScoreValidation:n,tournamentRecords:o,tournamentRecord:i,disableAutoCalc:s,enableAutoCalc:a,drawDefinition:c,matchUpStatus:u,winningSide:p,matchUpId:m,event:d,score:l}=t;if(!c)return{error:X};if(u&&[Wo,_o,$r,zt].includes(u)&&p)return{error:G,winningSide:p,matchUpStatus:u};if(![void 0,...jI].includes(u))return _({result:{error:oa},info:"matchUpStatus does not exist",stack:"setMatchUpStatus"});let f=Ae({drawDefinition:c}),{matchUps:g}=re({nextMatchUps:!0,tournamentRecord:i,inContext:!0,drawDefinition:c,matchUpsMap:f,event:d}),I=f.drawMatchUps.find(V=>V.matchUpId===m),h=g?.find(V=>V.matchUpId===m);if(!I||!g)return{error:Oe};if((I.winningSide||p)&&u===Dt)return{context:"Cannot have Bye with winningSide",error:Sl,matchUpStatus:u};let S=h?.structureId,{structure:T}=st({drawDefinition:c,structureId:S}),A=ie(Bt)(I.matchUpType),D=h?.drawPositions?.filter(Boolean),y;if(A){if(s)St({extension:{name:rc,value:!0},element:I});else if(a){let V=I.winningSide;or({name:rc,element:I});let{winningSide:Y,scoreStringSide1:$,scoreStringSide2:k,set:K}=Uc({drawDefinition:c,matchUpsMap:f,structure:T,matchUp:I,event:d}),z={scoreStringSide1:$,scoreStringSide2:k,sets:K?[K]:[]};y=Y!==V,Object.assign(t,{winningSide:Y,dualWinningSideChange:y,projectedWinningSide:Y,score:z})}Ra({tournamentId:i?.tournamentId,inContextDualMatchUp:h,eventId:d?.eventId,dualMatchUp:I,drawDefinition:c})}if(A&&u&&[oc].includes(u))return{error:G,info:"Not supported for matchUpType: TEAM"};let E=h?.matchUpTieId,U=er({matchUpId:E||m,inContextDrawMatchUps:g,drawDefinition:c});if(l&&!A&&!n){let V=I.matchUpFormat??T?.matchUpFormat??c?.matchUpFormat??d?.matchUpFormat,Y=Tg({existingMatchUpStatus:I.matchUpStatus,matchUpFormat:V,matchUpStatus:u,winningSide:p,score:l});if(Y.error)return Y}let M=I?.sides?[]:Nt({drawDefinition:c,structureId:S}).positionAssignments,P=h?.sides?.map(V=>V.participantId).filter(Boolean).length,N=P&&P===2||I.collectionId&&fr({structure:T})&&P&&P>=1||D?.length===2&&M?.filter(V=>D.includes(V.drawPosition)).every(V=>V.participantId);if(u&&WI.includes(u)&&!N)return _({info:"present in participantsRequiredMatchUpStatuses",context:{matchUpStatus:u,requiredParticipants:N},result:{error:oa}});let C=Pt({policyTypes:[Hc,vn],tournamentRecord:i,drawDefinition:c,event:d})?.appliedPolicies??{};typeof t.policyDefinitions=="object"&&Object.assign(C,t.policyDefinitions);let O=h?.stage===at&&h.finishingRound===1,b=O&&p,x=O&&I.winningSide&&!p&&(!t.matchUpStatus||t.matchUpStatus&&Gf({matchUpStatus:t.matchUpStatus}))&&(!t.outcome||!Ie({outcome:t.outcome})),w=b&&p!==I.winningSide&&I.winningSide;if(Object.assign(t,{inContextDrawMatchUps:g,qualifierAdvancing:b,qualifierChanging:w,removingQualifier:x,inContextMatchUp:h,appliedPolicies:C,matchUpTieId:E,matchUpsMap:f,targetData:U,structure:T,matchUp:I}),E){let{matchUp:V}=xt({matchUpId:E,inContext:!0,drawDefinition:c,matchUpsMap:f,event:d});if(V){let Y=je({matchUp:V,drawDefinition:c,structure:T,event:d})?.tieFormat,{projectedWinningSide:$}=Ov({drawDefinition:c,matchUpStatus:u,dualMatchUp:V,matchUpsMap:f,winningSide:p,tieFormat:Y,structure:T,matchUp:I,event:d,score:l}),k=V.winningSide;y=$!==k,Object.assign(t,{isCollectionMatchUp:!0,dualWinningSideChange:y,projectedWinningSide:$,matchUpTieId:E,dualMatchUp:V,tieFormat:Y})}}let F=Ai(t),L=Ea({matchUpStatus:u});if(!E){if(F&&!p&&(u&&Gf({matchUpStatus:u})||u&&[ge,Ne].includes(u)))return{error:Sl,activeDownstream:F,winningSide:p};if(p&&p===I.winningSide&&u&&!L)return{context:"winningSide must include directing matchUpStatus",error:Sl,directingMatchUpStatus:L,matchUpStatus:u}}let{schedule:v}=t;if(v){let V=Kp({disableNotice:!0,tournamentRecords:o,tournamentRecord:i,drawDefinition:c,matchUpId:m,schedule:v});if(V.error)return V}let B=!A&&!y&&p&&I.winningSide&&I.winningSide!==p;if(r&&B&&I.roundPosition)return $v(t);let H=p&&!E||t.projectedWinningSide;kn({activeDownstream:F,matchUpWinner:H,method:e,winningSide:p});let j=!F&&qv(t)||H&&xV(t)||L&&Kv(t)||{error:Zy};return _({result:j,stack:e})}function xV(t){let{matchUp:e,winningSide:r,matchUpTieId:n,dualWinningSideChange:o}=t;return r===e.winningSide||n&&!o?Kv(t):_({stack:"winningSideWithDownstreamDependencies",result:{error:Dl},context:{winningSide:r,matchUp:e}})}function Kv(t){let{tournamentRecord:e,matchUp:r,event:n}=t,o=t.isCollectionMatchUp&&r.winningSide&&!t.winningSide&&!Ie({score:t.score}),i=t.isCollectionMatchUp?t.matchUpStatus||o&&zt||me:t.matchUpStatus||me,s=t.removeScore||[Wo,_t].includes(i)&&![_o,$r].includes(i),a=Cn({...t,matchUpStatus:i,removeWinningSide:o,context:"sms",removeScore:s});if(a.error)return a;if(t.isCollectionMatchUp){let{matchUpTieId:c,drawDefinition:u,matchUpsMap:p}=t,m=zn({appliedPolicies:t.appliedPolicies,matchUpId:c,tournamentRecord:e,drawDefinition:u,matchUpsMap:p,event:n});if(m.error)return m;Object.assign(a,{tieMatchUpResult:m})}return a}function vN({tournamentRecord:t,drawDefinition:e,matchUpId:r,event:n}){if(!e)return{error:X};let{matchUp:o}=xt({drawDefinition:e,matchUpId:r,event:n});return o?.matchUpType!==ln?{error:Je}:La({enableAutoCalc:!0,tournamentRecord:t,drawDefinition:e,matchUpId:r,event:n})}function xN({drawDefinition:t,event:e,matchUpId:r}){if(!t)return{error:X};if(!r)return{error:ke};let{matchUp:n}=xt({drawDefinition:t,event:e,matchUpId:r});return n?or({name:Am,element:n}):{error:Oe}}function zv({substituteParticipantId:t,existingParticipantId:e,tournamentRecord:r,drawDefinition:n,sideNumber:o,matchUpId:i,event:s}){let a="substituteParticipant";if(!n)return{error:X};if(!i)return{error:ke};if(!e||!t)return _({result:{error:oe},stack:a});let{matchUp:c}=xt({drawDefinition:n,matchUpId:i,event:s});if(!c)return{error:Oe};if(!c.collectionId)return _({result:{error:Je},stack:a});let u=Ae({drawDefinition:n}),{matchUps:p}=re({tournamentParticipants:r?.participants,inContext:!0,drawDefinition:n,matchUpsMap:u}),m=p?.find(g=>g.matchUpId===i),l=p?.find(g=>g.matchUpId===m?.matchUpTieId)?.sides?.find(g=>g.participant.individualParticipants.some(({participantId:I})=>I===e));return!l||o&&l.sideNumber!==o?{error:pn}:l.participant?.individualParticipants?.map(gt).filter(g=>g!==e)?.includes(t)?xg({newParticipantId:t,tieMatchUpId:i,existingParticipantId:e,substitution:!0,tournamentRecord:r,drawDefinition:n,event:s}):_({result:{error:pn},stack:a})}function wN(t){return zv(t)}function LN({drawDefinition:t,matchUpId:e,event:r}){if(!t)return{error:X};let{matchUp:n}=xt({drawDefinition:t,matchUpId:e,event:r});return St({extension:{name:rc,value:!0},element:n})}function FN(t){let e="setMatchUpFormat",r=lt(t,[{tournamentRecord:!0},{[yn]:D=>Sr({matchUpFormat:D}),[En]:Ya,matchUpFormat:!0}]);if(r.error)return _({result:r,stack:e});let{tournamentRecord:n,drawDefinition:o,scheduledDates:i,stageSequences:s,matchUpFormat:a,structureId:c,eventType:u,matchUpId:p,eventId:m,stages:d,drawId:l,event:f,force:g}=t;if(i&&!Array.isArray(i))return _({result:{error:G,scheduledDates:i},stack:e});if(u&&!cu([ao,Kr],u))return _({result:{error:No},stack:e});let I=0,h=t.structureIds||c&&[c].filter(Boolean)||[],S=t.eventIds||m&&[m].filter(Boolean)||[],T=t.drawIds||l&&[l].filter(Boolean)||[];if((c||h?.length)&&!o)return _({result:{error:X},stack:e});if(l&&p&&o){let D=_d({tournamentRecord:n,drawDefinition:o,matchUpFormat:a,structureIds:h,structureId:c,matchUpId:p});if(D.error)return D;I+=1}let A=D=>{let y=[];for(let E of D.structures||[]){if(Array.isArray(d)&&!d.includes(E.stage)||Array.isArray(s)&&!s.includes(E.stageSequence)||h?.length&&!h.includes(E.structureId))continue;h?.length&&E.matchUpFormat!==a&&(E.matchUpFormat=a,y.push(E.structureId),I+=1);let U=((g||i)&&At({matchUpFilters:{matchUpStatuses:[zt]},structure:E}).matchUps)??[],M=(i&&At({matchUpFilters:{matchUpStatuses:[zt]},contextFilters:{scheduledDates:i},afterRecoveryTimes:!1,inContext:!0,structure:E}).matchUps)??[];if(U?.length){let P=M?M.map(fe):U.map(fe);for(let N of U)P.includes(N.matchUpId)&&(N.matchUpFormat=i?.length?a:void 0,It({tournamentId:n?.tournamentId,eventId:f?.eventId,context:e,drawDefinition:D,matchUp:N}))}}return!y.length&&D.matchUpFormat!==a&&(D.matchUpFormat=a,I+=1),y};for(let D of n?.events||[])if(!(S?.length&&!S.includes(D.eventId)||u&&u!==D.eventType||u===Fe))if(Array.isArray(s)||Array.isArray(d)||h?.length||T?.length)for(let y of D.drawDefinitions||[]){if(Array.isArray(T)&&!T.includes(y.drawId))continue;let E=A(y);bt({structureIds:E,drawDefinition:y})}else D.matchUpFormat!==a&&(D.matchUpFormat=a,I+=1);return I?{...R,modificationsCount:I}:{...R,info:Ns}}function Lg({inheritance:t=!0,tournamentRecord:e,drawDefinition:r,matchUpId:n,event:o}){if(!r)return{error:X};let i=xt({drawDefinition:r,matchUpId:n})?.matchUp;if(!i?.tieMatchUps)return{error:Je};let s=xt({inContext:!0,drawDefinition:r,matchUpId:n,event:o})?.matchUp,a=0;return(i?.sides||[]).forEach(c=>{c.lineUp&&delete c.lineUp}),(s?.sides||[]).forEach(c=>{if(a+=1,t===!1){let u=s?.tieFormat,p=c.participantId;u&&p&&Fi({drawDefinition:r,participantId:p,lineUp:[],tieFormat:u})}It({tournamentId:e?.tournamentId,context:"resetMatchUpLineUps",eventId:o?.eventId,drawDefinition:r,matchUp:i})}),{...R,modificationsCount:a}}function IA(t){let{matchUpFormat:e,matchUpStatus:r,winningSide:n,score:o}=t;if(!o)return{sets:[]};let i=o.sets||[],s=wo({winnerFirst:!1,matchUpFormat:e,matchUpStatus:r,sets:i}),a=wo({winnerFirst:!1,reversed:!0,matchUpFormat:e,matchUpStatus:r,sets:i}),c=wo({matchUpFormat:e,matchUpStatus:r,winningSide:n,sets:i}),u=s===c?a:s;return n&&(s=n===1?c:u,a=n===2?c:u),{score:{sets:i,scoreStringSide1:s,scoreStringSide2:a}}}function xu(t){let e=lt(t,[{[Co]:!0,[Yr]:!0}]);if(e.error)return e;let r=Xr(t);if(!t.drawDefinition){let h=t.tournamentRecord??(t.tournamentId&&r[t.tournamentId]);t.tournamentRecord||(t.tournamentRecord=h);let S=We({eventId:t.eventId,drawId:t.drawId,tournamentRecord:h});if(S.error)return S;S.drawDefinition&&(t.drawDefinition=S.drawDefinition),t.event=S.event}let{disableScoreValidation:n,policyDefinitions:o,tournamentRecord:i,disableAutoCalc:s,enableAutoCalc:a,drawDefinition:c,matchUpFormat:u,matchUpId:p,schedule:m,event:d,notes:l}=t,{policy:f}=$o({policyType:vn,tournamentRecord:i,event:d}),g=t.allowChangePropagation!==void 0&&t.allowChangePropagation||f?.allowChangePropagation!==void 0&&f.allowChangePropagation||void 0,{outcome:I}=t;if(I?.winningSide&&![1,2].includes(I.winningSide))return{error:im};if(u){let h=_d({tournamentRecord:i,drawDefinition:c,matchUpFormat:u,matchUpId:p,event:d});if(h.error)return h}if(I?.score?.sets&&!I.score.scoreStringSide1){let{score:h}=IA(I);I.score=h,I.score.sets=I.score.sets.filter(S=>S.side1Score||S.side2Score||S.side1TiebreakScore||S.side2TiebreakScore)}return La({matchUpStatusCodes:I?.matchUpStatusCodes,matchUpStatus:I?.matchUpStatus,winningSide:I?.winningSide,allowChangePropagation:g,disableScoreValidation:n,score:I?.score,tournamentRecords:r,policyDefinitions:o,tournamentRecord:i,disableAutoCalc:s,enableAutoCalc:a,drawDefinition:c,matchUpFormat:u,matchUpId:p,schedule:m,event:d,notes:l})}function GN(t){if(!t?.outcomes)return{error:et};if(!Array.isArray(t.outcomes))return{error:et,info:{outcomes:t.outcomes}};let e=t.tournamentRecords||t.tournamentRecord&&{[t.tournamentRecord.tournamentId]:t.tournamentRecord}||{},r=t.outcomes??[],n=r.reduce((o,i)=>o.includes(i.tournamentId)?o:o.concat(i.tournamentId),[]);for(let o of n){let i=e[o];if(!i)return{error:W};let s=r.filter(a=>a.tournamentId===o);if(s.length){let a=wV({outcomes:s,tournamentRecord:i});if(a.error)return a}}return{...R}}function wV(t){let{tournamentRecords:e,tournamentRecord:r,outcomes:n,policyDefinitions:o}=t,i={};n.forEach(s=>{let{eventId:a}=s;i[a]||(i[a]=[]),i[a].push(s)});for(let s of Object.keys(i)){let{event:a}=We({tournamentRecord:r,eventId:s});for(let c of i[s]){let{drawId:u}=c,p=a?.drawDefinitions?.find(m=>m.drawId===u);if(p&&u){let{matchUpFormat:m,matchUpId:d}=c,l=xu({schedule:c?.schedule,tournamentRecords:e,policyDefinitions:o,tournamentRecord:r,drawDefinition:p,matchUpFormat:m,matchUpId:d,outcome:c,drawId:u,event:a});if(l.error)return l}}}return{...R}}function Qv({drawDefinition:t,matchUpId:e,outcome:r,matchUp:n}){if(!n&&!t)return{error:X};if(!r)return{error:et,info:"missing outcome"};if(!n&&!e)return{error:sr};if(!n){let i=xt({drawDefinition:t,matchUpId:e});if(i.error)return i;n=i.matchUp}return typeof r!="object"||!r.score?.scoreStringSide1||!r.score?.scoreStringSide2?{error:G}:St({element:n,extension:{name:Am,value:r}})}function kN(t){return Qv(t)}function Fg(t){let e="resetTieFormat",{drawDefinition:r,event:n,uuids:o}=t,i=lt(t,[{[An]:!0,[Co]:!0}],e);if(i.error)return i;let s=xa(t,[{[sa]:fo}]);if(s[Ms])return s;let a=t.tournamentRecord?.tournamentId,{matchUp:c,structure:u}=s?.matchUp??{};if(!c?.tieMatchUps)return _({result:{error:Je},info:"Must be a TEAM matchUp",stack:e});if(!c.tieFormat)return{...R};let p=je({structure:u,drawDefinition:r,event:n})?.tieFormat;if(!p)return _({result:{error:Ke},info:"No inherited tieFormat",stack:e});let m=[],d=[],l=[],f=[];for(let g of p.collectionDefinitions){let{matchUpCount:I,collectionId:h}=g;d.push(h);let S=(c.tieMatchUps||[]).filter(T=>T.collectionId===h);if(S.length>I)S.sort((T,A)=>(T.matchUpStatus===zt?1:0)-(A.matchUpStatus===zt?1:0)),l.push(...S.slice(0,I)),m.push(...S.slice(3).map(fe));else if(l.push(...S),S.length<I){let T=I-S.length,A=hu({collectionDefinition:g,matchUpsLimit:T,matchUp:c,uuids:o});f.push(...A)}}for(let g of c?.tieMatchUps||[])g.collectionId&&!d.includes(g.collectionId)&&m.push(g.matchUpId);return f.length&&(l.push(...f),So({eventId:n?.eventId,matchUps:f,drawDefinition:r,tournamentId:a})),m.length&&wn({matchUpIds:m,eventId:n?.eventId,drawDefinition:r,tournamentId:a}),c&&(c.tieMatchUps=l,c.tieFormatId=void 0,c.tieFormat=void 0,It({structureId:u?.structureId,eventId:n?.eventId,context:e,drawDefinition:r,tournamentId:a,matchUp:c})),{...R,newMatchUps:f,deletedMatchUpIds:m}}function Gg(t){let{tournamentRecord:e,drawDefinition:r,matchUpId:n,event:o}=t,i="resetScorecard";if(!r)return _({result:{error:X},stack:i});if(!n)return _({result:{error:ke},stack:i});if(!$e(n))return _({result:{error:G,matchUpId:n},stack:i});let s=Ae({drawDefinition:r}),{matchUps:a}=re({nextMatchUps:!0,inContext:!0,drawDefinition:r,matchUpsMap:s}),c=s.drawMatchUps.find(I=>I.matchUpId===n),u=a?.find(I=>I.matchUpId===n);if(!c||!a)return{error:Oe};if(c.matchUpType!==kr)return{error:Je};let p=er({inContextDrawMatchUps:a,drawDefinition:r,matchUpId:n}),m=u?.structureId,{structure:d}=st({drawDefinition:r,structureId:m});if(Object.assign(t,{inContextDrawMatchUps:a,inContextMatchUp:u,matchUpsMap:s,targetData:p,structure:d,matchUp:c}),Ai(t))return{error:Dl};if(c.tieMatchUps?.length)for(let I of c.tieMatchUps){let h=La({matchUpId:I.matchUpId,matchUpTieId:n,winningSide:void 0,removeScore:!0,tournamentRecord:e,drawDefinition:r,event:o});if(h.error)return _({result:h,stack:i})}let f=Pt({tournamentRecord:e,drawDefinition:r,event:o})?.appliedPolicies,g=zn({event:t.event,removeScore:!0,tournamentRecord:e,appliedPolicies:f,drawDefinition:r,matchUpsMap:s,matchUpId:n});if(g.error)return _({result:g,stack:i});if(t.tiebreakReset&&!g.tieFormatRemoved){let I=je({drawDefinition:r,structure:d,event:o})?.tieFormat;if(c.tieFormat&&I){let{matchUpCountDifference:h,descendantDifferences:S,ancestorDifferences:T,valueDifference:A}=Go({descendant:c.tieFormat,ancestor:I});if(S.collectionIds.length===1&&!T.collectionIds.length&&!T.groupsCount&&h===1&&A===1){let D=Fg({tournamentRecord:e,drawDefinition:r,matchUpId:n,event:o});if(D.error)return D}}}return{...R}}function VN(t){let e=lt(t,[{[Yr]:!0,[Cs]:!0},{[Ja]:{[Xa]:!1,roundNumbers:!1},[_I]:"At least one must be provided",[to]:Er}]);if(e.error)return e;let r=pS(t);if(r.error)return r;let{matchUpIds:n}=r,o=ie(kr)(t.event.eventType),{tournamentRecord:i,drawDefinition:s,event:a}=t;for(let c of n){if(o){let p=Gg({tiebreakReset:!0,tournamentRecord:i,drawDefinition:s,matchUpId:c,event:a});if(p.error||t.removeAssignments&&Lg({inheritance:!1,drawDefinition:s,matchUpId:c}).error)return p}let u=La({winningSide:void 0,removeScore:!0,tournamentRecord:i,drawDefinition:s,matchUpId:c,event:a});if(u.error)return u;if(t.removeAssignments){let p=wg({...t,matchUpId:c});if(p.error)return p}}return{...R}}function Xv({drawDefinition:t,finishingOrder:e}){if(!t)return{error:X};let r="setOrderOfFinish";if(!Array.isArray(e))return _({info:Nn("finishingOrder"),result:{error:G},stack:r});let{completedMatchUps:n,matchUpsMap:o}=Vs({inContext:!0,drawDefinition:t}),i=n?.map(fe)??[],s=e.map(fe),{matchUpTypes:a,roundNumbers:c,structureIds:u,matchUpTieIds:p}=(n??[]).filter(({matchUpId:S})=>s.includes(S)).reduce((S,T)=>{let{matchUpTieId:A,matchUpType:D,roundNumber:y,structureId:E}=T;return S.matchUpTypes.includes(D)||S.matchUpTypes.push(D),S.roundNumbers.includes(y)||S.roundNumbers.push(y),S.structureIds.includes(E)||S.structureIds.push(E),S.matchUpTieIds.includes(A)||S.matchUpTieIds.push(A),S},{matchUpTypes:[],roundNumbers:[],structureIds:[],matchUpTieIds:[]});if(a.length>1||p.length>1||c.length>1||u.length>1)return _({info:"matchUpType, structureId and roundNumber must be equivalent",result:{error:G},stack:r});let m,d,l={},f=[],g=[];if(!e.every(({orderOfFinish:S,matchUpId:T})=>(f.push(T),S&&g.push(S),l[T]=S,m=i.includes(T),d=S===void 0||ft(S)&&Math.floor(S)>0,m&&d)))return _({result:{error:m?G:oa},info:!m&&"matchUps must be completed"||!d&&"orderOfFinish must be integer > 0 or undefined"||void 0,stack:r});let h=n?.filter(S=>S.structureId===u[0]&&S.roundNumber===c[0]&&S.matchUpType===a[0]&&S.matchUpTieId===p[0]&&!f.includes(S.matchUpId));for(let S of h??[]){let{orderOfFinish:T}=S||{};if(T){if(!ft(T))return _({context:{orderOfFinish:T,matchUp:S},result:{error:G},stack:r});g.push(T)}}if(EI(g).length!==g.length||Math.max(...g)>g.length)return _({info:"Values not unique or greater than expected number of values",result:{error:G},stack:r});if(u.length){let S=uu({matchUpFilters:{matchUpIds:s},structureId:u[0],drawDefinition:t,matchUpsMap:o});if(S.error)return _({result:S,stack:r});S.completedMatchUps?.forEach(T=>T.orderOfFinish=l[T.matchUpId])}return{...R}}function BN(t){return Xv(t)}function HN({tournamentRecord:t,drawDefinition:e,matchUpId:r,lineUps:n,event:o}){if(!t)return{error:W};if(!e)return{error:pr};if(typeof r!="string")return{error:Je};if(!Array.isArray(n))return{error:G,lineUps:n};let i="applyLineUps",s=t.participants||[],a=xt({tournamentParticipants:s,inContext:!0,drawDefinition:e,matchUpId:r});if(a.error)return a;if(!a.matchUp)return{error:Oe};let{matchUp:c,structure:u}=a,{drawPositions:p,matchUpType:m}=c;if(m!==Bt)return{error:Je};if(!p?.length)return{error:Wa};let d=je({matchUp:c,drawDefinition:e,structure:u,event:o})?.tieFormat,l={};for(let g of n){if(!Array.isArray(g))return{error:G,lineUp:g};let I={},h=[];for(let y of g){if(typeof y!="object")return{error:G,lineUpAssignment:y};let{participantId:E,collectionAssignments:U=[]}=y;if(!Array.isArray(U))return{error:G,collectionAssignments:U};let M=s.find(N=>N.participantId===E);if(!M)return{error:Zt};if(M.participantType!==ht)return{error:nn};let P=c.sides?.find(N=>N.participant?.individualParticipantIds?.includes(E))?.sideNumber;P&&h.push(P);for(let N of U){if(typeof N!="object")return{error:G,collectionAssignment:N};let{collectionId:C,collectionPosition:O}=N,b=d?.collectionDefinitions?.find(F=>F.collectionId===C);if(!b)return{error:G,collectionId:C};let x=`${C}-${O}`;I[x]||(I[x]=[]);let w=I[x].length;if(ie(Xt)(b.matchUpType)&&w||b.matchUpType===Gt&&w>1)return{info:"Excessive collectionPosition assignments",error:G};I[x].push(E)}}let S=Object.values(I);for(let y of S)if(y.length===2){let{participant:E}=tn({tournamentParticipants:s,participantIds:y});if(!E){let M=gn({participant:{participantType:dt,participantRole:Ge,individualParticipantIds:y},pairOverride:!0,tournamentRecord:t});if(M.error)return M}}let T=dr(h),A=(T[1]||0)>(T[2]||0)&&1||(T[2]||0)>(T[1]||0)&&2||void 0,D=Object.keys(l).map(y=>parseInt(y));A&&!D.includes(A)&&(l[A]=g)}if(!Object.keys(l).length)return{error:wl};if(a=xt({drawDefinition:e,matchUpId:r}),a.error)return a;if(!a.matchUp)return{error:Oe};let{matchUp:f}=a;f.sides||(f.sides=[]);for(let g of[1,2]){let I=f.sides.find(S=>S.sideNumber===g),h=l[g];if(h)I?I.lineUp=h:f.sides.push({lineUp:h,sideNumber:g});else continue}return It({tournamentId:t?.tournamentId,context:i,drawDefinition:e,matchUp:f}),{...R}}var $g={};Jt($g,{anonymizeTournamentRecord:()=>XN,generate:()=>QN,generateEventWithDraw:()=>Jp,generateOutcome:()=>jg,generateOutcomeFromScoreString:()=>kg,generateParticipants:()=>vc,generateTournamentRecord:()=>zN,modifyTournamentRecord:()=>JN,mutate:()=>ZN});var QN={};Jt(QN,{generateEventWithDraw:()=>Jp,generateOutcome:()=>jg,generateOutcomeFromScoreString:()=>kg,generateParticipants:()=>vc,generateTournamentRecord:()=>zN});function kg(t){let{matchUpFormat:e,matchUpStatus:r,winningSide:n,scoreString:o}=t;if(!o)return{outcome:{...Tu,winningSide:n,matchUpStatus:r}};if(n&&![1,2,void 0].includes(n))return{error:G,winningSide:n};let i=o&&Rd({scoreString:o}),s={},a=wo({sets:i,matchUpFormat:e}),c=wo({sets:i,reversed:!0,matchUpFormat:e});return n===2?(s.scoreStringSide1=c,s.scoreStringSide2=a):(s.scoreStringSide1=a,s.scoreStringSide2=c),s.sets=Rd({scoreString:s.scoreStringSide1}),rt({outcome:{matchUpStatus:r,winningSide:n,score:s}})}function tl({matchUpScheduleTimes:t,matchUpDependencies:e,allDateMatchUpIds:r,matchUp:n}){let i=(e?.[n.matchUpId]?.matchUpIds||[]).filter(a=>r.includes(a)).filter(a=>!t[a]);return{dependenciesScheduled:!i?.length,remainingDependencies:i}}function ta({matchUpPotentialParticipantIds:t,matchUpNotBeforeTimes:e,timeAfterRecovery:r,matchUp:n}){let{individualParticipantIds:o}=eu(n);r=r??n.schedule?.timeAfterRecovery;let i=u=>{t[u]||(t[u]=[]),t[u]=pt(t[u].concat(...o))},s=u=>{r&&(!e[u]||r>e[u])&&(e[u]=r)},a=n.winnerTo?.matchUpId||n.winnerMatchUpId;a&&(r&&s(a),i(a));let c=n.loserTo?.matchUpId||n.loserMatchUpId;c&&(r&&s(c),i(c)),n.sidesTo?.length&&n.sidesTo.forEach(({matchUpId:u})=>{u&&(r&&s(u),i(u))})}function Fa({individualParticipantProfiles:t,participantId:e}){t[e]||(t[e]={typeChangeTimeAfterRecovery:void 0,timeAfterRecovery:void 0,priorMatchUpType:void 0,potentialRecovery:{},potentialCounted:{},potentialBookings:{},bookings:[],counters:{}})}function Jv({individualParticipantProfiles:t,recoveryValue:e,participantId:r,scheduleTime:n,drawId:o}){t[r].potentialRecovery[o]||(t[r].potentialRecovery[o]=[]),t[r].potentialRecovery[o].push(e),t[r].potentialBookings[o]||(t[r].potentialBookings[o]=[]),t[r].potentialBookings[o].push({timeAfterRecovery:e,scheduleTime:n})}function bc({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,typeChangeRecoveryMinutes:r,averageMatchUpMinutes:n=0,matchUpNotBeforeTimes:o,matchUpDependencies:i,recoveryMinutes:s=0,scheduleTime:a,matchUp:c}){let u=$t(c?.schedule?.endTime),p=u?br(u,ct(s)):br(a,ct(n)+ct(s)),m=r&&(u?br($t(u),r):br(a,ct(n)+ct(r))),d=i?.[c.matchUpId]?.participantIds||[],l=(c.roundPosition&&t[c.matchUpId]||[]).flat();d.forEach(f=>{Fa({individualParticipantProfiles:e,participantId:f});let I=e[f].priorMatchUpType!==c.matchUpType&&m||p;l.includes(f)?Jv({individualParticipantProfiles:e,drawId:c.drawId,recoveryValue:I,participantId:f,scheduleTime:a}):(e[f].timeAfterRecovery=I,e[f].bookings.push({scheduleTime:a,timeAfterRecovery:I}))}),ta({matchUpPotentialParticipantIds:t,matchUpNotBeforeTimes:o,timeAfterRecovery:p,matchUp:c})}function hA({matchUpScheduleTimes:t,matchUpDependencies:e,scheduleTime:r,matchUpId:n,details:o}){let i,s=o.minutesMap?.[n]?.recoveryMinutes,c=(o.minutesMap?.[n]?.averageMinutes||0)+(s||0),u=br(r,c),p=e?.[n]?.dependentMatchUpIds||[];if(p.length){let m=p.reduce((d,l)=>{let f=t[l];if(!f)return d;let g={scheduleTime:f,matchUpId:l};return f&&!d.matchUpId||Vt(f)<Vt(d.scheduleTime)?g:d},{});m.scheduleTime&&Vt(u)>Vt(m.scheduleTime)&&(i=m)}return{scheduledDependent:i}}function Zv(t){let{sides:e,matchUpType:r}=t||{};return(e||[]).map(n=>r===Gt&&(n?.participant?.individualParticipants||[])||n?.participant&&[n.participant]||[]).flat()}var Oc="DO_NOT_SCHEDULE",tx={DO_NOT_SCHEDULE:Oc};function el({averageMatchUpMinutes:t=90,requestConflicts:e={},potentials:r=!0,personRequests:n,scheduleTime:o,scheduleDate:i,matchUp:s}){let a=Zv(s).map(({person:l})=>l?.personId);if(r){let l=(s?.potentialParticipants||[]).flat().map(({person:f})=>f?.personId);a.push(...l)}let c=a.map(l=>n[l]?.map(f=>({...f,personId:l}))).filter(Boolean).flat().filter(l=>l.requestType===Oc&&_n(i,l.date)),u=[],p=s?.matchUpId,m=we($t(o),Ut(i)),d=$t(Ql(m,t).toISOString());for(let l of c){let{requestId:f,startTime:g,endTime:I}=l;(o>g&&o<I||d>g&&d<I)&&(u.push({matchUpId:p,request:l,scheduleTime:o}),e[f]?(e[f].scheduleTimes.includes(o)||e[f].scheduleTimes.push(o),e[f].matchUpIds.includes(p)||e[f].matchUpIds.push(p)):e[f]={request:l,scheduleTimes:[o],matchUpIds:[p]})}return{conflicts:u}}function Vg({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,matchUp:r,value:n}){let{matchUpType:o}=r,{individualParticipantIds:i}=eu(r),a=(t[r.matchUpId]||[]).filter(u=>!xe(u,i)).flat();[...i,...a].forEach(u=>{if(Fa({individualParticipantProfiles:e,participantId:u}),!e[u].potentialCounted[r.drawId]){let p=e[u].counters;p[o]?p[o]+=n:n>0&&(p[o]=n),p[$n]?p[$n]+=n:n>0&&(p[$n]=n),a.includes(u)&&(e[u].potentialCounted[r.drawId]=!0)}})}function ex({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,dateScheduledMatchUpIds:r,greatestAverageMinutes:n,dateScheduledMatchUps:o,matchUpNotBeforeTimes:i,matchUpScheduleTimes:s,matchUpDependencies:a,clearScheduleDates:c,scheduleDate:u,minutesMap:p,matchUps:m}){let d=[];r||(o=m?.filter(g=>{let I=g.schedule||{},h=g.matchUpStatus===Dt;return h&&d.push({tournamentId:g.tournamentId,matchUpId:g.matchUpId}),!h&&va({schedule:I})&&(!u||g.schedule.scheduledDate===u)}),r=o.map(fe));let l=Array.isArray(c)?c.includes(u):c,f=l?[]:m.filter(({matchUpId:g})=>r.includes(g));for(let g of f){Vg({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,value:1,matchUp:g});let I=g.schedule?.scheduledTime;if(I){s[g.matchUpId]=I;let h=p?.[g.matchUpId]?.recoveryMinutes;bc({individualParticipantProfiles:e,matchUpPotentialParticipantIds:t,matchUpNotBeforeTimes:i,matchUpDependencies:a,averageMatchUpMinutes:n,recoveryMinutes:h,scheduleTime:I,matchUp:g})}}return{dateScheduledMatchUpIds:r,byeScheduledMatchUpDetails:d,dateScheduledMatchUps:o,clearDate:l}}function rx({matchUpPotentialParticipantIds:t,scheduleCompletedMatchUps:e,dateScheduledMatchUpIds:r,matchUpNotBeforeTimes:n,matchUpScheduleTimes:o,orderedMatchUpIds:i,clearDate:s,matchUps:a}){let c=Object.keys(o),u=i.map(m=>a.find(d=>d.matchUpId===m)).filter(Boolean).filter(m=>{let d=!s&&(r.includes(m.matchUpId)||c.includes(m.matchUpId)),l=[Dt,Ot,me,$r,lr,_t,ge,Ne].includes(m?.matchUpStatus);return e||!d&&!m.winningSide&&!l}),{matchUpMap:p}=u.reduce((m,d)=>{let{drawId:l,tournamentId:f}=d;return m.matchUpMap[f]||(m.matchUpMap[f]={}),m.matchUpMap[f][l]?m.matchUpMap[f][l].push(d):m.matchUpMap[f][l]=[d],ta({matchUpPotentialParticipantIds:t,matchUpNotBeforeTimes:n,matchUp:d}),m},{matchUpMap:{}});return{matchUpsToSchedule:u,matchUpMap:p}}function zp({defaultRecoveryMinutes:t=0,averageMatchUpMinutes:e=90,dateScheduledMatchUps:r,tournamentRecords:n,venueIds:o=[],periodLength:i,scheduleDate:s,matchUps:a}){if(typeof n!="object")return{error:Ft};if(!Ur(a)&&!Array.isArray(r))return{error:Sn};i=i??vu({recoveryMinutes:t,averageMatchUpMinutes:e});let c=Object.assign({},...Object.values(n).map(d=>(d.events??[]).map(l=>{let{scheduleTiming:f}=Sa({tournamentRecord:d,event:l});return{[l.eventId]:{event:l,scheduleTiming:f}}})).flat()),u={averageTimes:[{minutes:{default:e}}],recoveryTimes:[{minutes:{default:t}}]};r||(r=a?.filter(d=>{let l=d.schedule;return va({schedule:l})&&(!s||d.schedule.scheduledDate===s)}));let p=r?.filter(d=>(!o.length||o.includes(d.schedule.venueId))&&d.matchUpStatus!==Dt);return{bookings:p?.map(({eventId:d,schedule:l,matchUpFormat:f})=>{let{event:g,scheduleTiming:I}=c[d],h=g?.eventType,S={...I,defaultTiming:u,matchUpFormat:f},{averageMinutes:T,recoveryMinutes:A}=dp({timingDetails:S,eventType:h}),{courtId:D,venueId:y}=l,E=$t(l.scheduledTime),U=br(E,T);return{recoveryMinutes:A,averageMinutes:T,periodLength:i,startTime:E,courtId:D,endTime:U,venueId:y}}).filter(Boolean),relevantMatchUps:p,dateScheduledMatchUps:r}}function nx({calculateStartTimeFromCourts:t=!0,remainingScheduleTimes:e,defaultRecoveryMinutes:r,averageMatchUpMinutes:n,clearScheduleDates:o,tournamentRecords:i,tournamentRecord:s,periodLength:a,scheduleDate:c,startTime:u,venueIds:p,matchUps:m,endTime:d}){if(s&&!i&&(i={[s.tournamentId]:s}),typeof i!="object"||!Object.keys(i).length)return{error:Ft};a=a??vu({recoveryMinutes:r,averageMatchUpMinutes:n});let{courts:l,venues:f}=po({dates:[c],ignoreDisabled:!0,tournamentRecords:i}),g=l?.filter(y=>!p||p.includes(y.venueId))??[];u=u??Cc({courts:g,scheduleDate:c,startTime:!0}),d=d??Cc({courts:g,scheduleDate:c,endTime:!0});let{bookings:I,dateScheduledMatchUps:h}=zp({defaultRecoveryMinutes:r,averageMatchUpMinutes:n,tournamentRecords:i,scheduleDate:c,periodLength:a,venueIds:p,matchUps:m}),S={calculateStartTimeFromCourts:t,remainingScheduleTimes:e,averageMatchUpMinutes:n,clearScheduleDates:o,date:c,periodLength:a,startTime:u,bookings:I,endTime:d,courts:g},{scheduleTimes:T}=Kd(S),A=p?.length===1&&p[0]||f?.length===1&&f[0].venueId||void 0;return{dateScheduledMatchUpIds:h?.map(Pr("matchUpId")),dateScheduledMatchUps:h,scheduleTimes:T,venueId:A}}function ox({scheduledRoundsDetails:t,greatestAverageMinutes:e,garmanSinglePass:r}){let n=[],o=[],i,s,a,c;for(let u of t.filter(Boolean))c||(c=u.hash),(u.hash===c||r)&&(o=o.concat(u.matchUpIds)),u.hash!==c&&!r&&(c=u.hash,n.push({averageMinutes:a,recoveryMinutes:s,roundPeriodLength:i,matchUpIds:o}),o=u.matchUpIds),a=r?e:u.averageMinutes,s=u.recoveryMinutes,i=u.roundPeriodLength;return o.length&&n.push({matchUpIds:o,roundPeriodLength:i,recoveryMinutes:s,averageMinutes:a}),{groupedRounds:n}}function SA({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,scheduleCompletedMatchUps:r,containedStructureIds:n,matchUpNotBeforeTimes:o,matchUpScheduleTimes:i,matchUpDependencies:s,clearScheduleDates:a,tournamentRecords:c,periodLength:u,scheduleDate:p,useGarman:m,matchUps:d,courts:l,venues:f}){let g={},I=[],h=[],S=[];for(let T of f){let{rounds:A=[],venueId:D}=T,{scheduledRoundsDetails:y,greatestAverageMinutes:E,orderedMatchUpIds:U,minutesMap:M}=bu({scheduleCompletedMatchUps:r,containedStructureIds:n,tournamentRecords:c,periodLength:u,matchUps:d,rounds:A});S.push(...U??[]);let{groupedRounds:P}=ox({scheduledRoundsDetails:y,greatestAverageMinutes:E,garmanSinglePass:!0}),N,C,O=[];m&&({scheduleTimes:O,dateScheduledMatchUpIds:N,dateScheduledMatchUps:C}=nx({averageMatchUpMinutes:P[0]?.averageMinutes,scheduleDate:Ut(p),venueIds:[T.venueId],clearScheduleDates:a,tournamentRecords:c,periodLength:u,matchUps:d}));let b=ex({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,dateScheduledMatchUpIds:N,greatestAverageMinutes:E,matchUpNotBeforeTimes:o,matchUpScheduleTimes:i,matchUpDependencies:s,clearScheduleDates:a,scheduleDate:p,minutesMap:M,matchUps:d});({dateScheduledMatchUpIds:N,dateScheduledMatchUps:C}=b);let{byeScheduledMatchUpDetails:x,clearDate:w}=b;x?.length&&h.push(...x);let{matchUpsToSchedule:F,matchUpMap:L}=rx({matchUpPotentialParticipantIds:t,scheduleCompletedMatchUps:r,dateScheduledMatchUpIds:N,matchUpNotBeforeTimes:o,matchUpScheduleTimes:i,orderedMatchUpIds:U,clearDate:w,matchUps:d}),v=l.filter(B=>B.venueId===D);g[D]={previousRemainingScheduleTimes:[],courtsCount:v.length,greatestAverageMinutes:E,scheduledRoundsDetails:y,dateScheduledMatchUps:C,matchUpsToSchedule:F,scheduleTimes:O,groupedRounds:P,venueCourts:v,minutesMap:M,matchUpMap:L},a||I.push(...N)}return{allDateScheduledByeMatchUpDetails:h,allDateScheduledMatchUpIds:I,venueScheduledRoundDetails:g,allDateMatchUpIds:S}}function ix(t,e){let r=Vt(t.scheduleTime),n=Vt(t.timeAfterRecovery),o=Vt(e.scheduleTime),i=Vt(e.timeAfterRecovery),s=r===o||n===i,a=r>o&&r<i,c=o>r&&o<n,u=n>o&&n<i,p=i>r&&i<n;return rt({hasOverlap:s||a||u||c||p,startAisContained:a,endAisContained:u,startBisContained:c,endBisContained:p},!0)}function rl({individualParticipantProfiles:t,matchUpNotBeforeTimes:e,matchUpDependencies:r,scheduleTime:n,matchUp:o,details:i}){let s=(r?.[o.matchUpId]?.participantIds||[]).flat(),a=i?.minutesMap?.[o.matchUpId]?.averageMinutes||0,c=i?.minutesMap?.[o.matchUpId]?.recoveryMinutes||0,u=s.every(f=>{Fa({individualParticipantProfiles:t,participantId:f});let g=t[f];if(!g.timeAfterRecovery)return!0;let I=$t(o?.schedule?.endTime),h=I?br(I,ct(c)):br(n,ct(a)+ct(c));return!!![...Object.keys(g.potentialBookings).filter(D=>D!==o.drawId).map(D=>g.potentialBookings[D]).flat(),...g.bookings].find(D=>ix({scheduleTime:n,timeAfterRecovery:h},D).hasOverlap)}),p=e[o.matchUpId],d=(p?ca(we(p),we(n),!1):0)>=0;return{enoughTime:u&&d}}function nl({individualParticipantProfiles:t,matchUpPotentialParticipantIds:e,matchUpDailyLimits:r={},matchUp:n}){let{enteredIndividualParticipantIds:o}=eu(n),{matchUpId:i,matchUpType:s}=n,a=(n.roundPosition&&e[i]||[]).flat(),c=pt(o.concat(...a));return c.forEach(p=>{Fa({individualParticipantProfiles:t,participantId:p})}),{participantIdsAtLimit:c.filter(p=>{let m=t[p];if(m)return[s,$n].find(d=>{let l=m.counters?.[d]||0,f=r[d]||0;return l&&f&&l>=f})}),relevantParticipantIds:c}}function wu({scheduleCompletedMatchUps:t=!1,scheduleByeMatchUps:e=!1,errorOnAnachronism:r=!1,checkChronology:n=!0,matchUpDependencies:o,removePriorValues:i,tournamentRecords:s,tournamentRecord:a,matchUpDetails:c,matchUpIds:u,schedule:p}){if(!a)return{error:W};if(!c&&(!u||!Array.isArray(u)))return{error:ia};if(!c&&(!p||typeof p!="object"))return{error:$y};let m,d=[],l=0;if(n&&!o){let I=Vr({tournamentRecords:s,tournamentRecord:a});o=I.matchUpDependencies,m=I.matchUps}m||(m=le({tournamentRecord:a})?.matchUps??[]);let f=m.reduce((I,h)=>{let{matchUpId:S,drawId:T,matchUpStatus:A}=h;return(e||A!==Dt)&&(t||!ae.includes(A))&&(I[T]?I[T].push(S):I[T]=[S]),I},{}),g=c?.map(I=>I.matchUpId);for(let I of Object.keys(f)){let{drawDefinition:h}=Po({tournamentRecord:a,drawId:I});if(!h)continue;let S=f[I].filter(A=>u?.includes(A)??g?.includes(A)),T=rr({inContext:!1,drawDefinition:h}).matchUps;for(let A of S){let D=c?.find(E=>E.matchUpId===A)?.schedule||p,y=Kp({schedule:D,matchUpDependencies:o,errorOnAnachronism:r,removePriorValues:i,inContextMatchUps:m,tournamentRecords:s,tournamentRecord:a,checkChronology:n,drawDefinition:h,drawMatchUps:T,matchUpId:A});if(y?.warnings?.length&&d.push(...y.warnings),y?.success&&(l+=1),y.error)return y}}return d.length?{...R,scheduled:l,warnings:d}:{...R,scheduled:l}}function _c(t){let{scheduleCompletedMatchUps:e=!1,scheduleByeMatchUps:r=!1,errorOnAnachronism:n,matchUpContextIds:o,removePriorValues:i,tournamentRecords:s,checkChronology:a,matchUpDetails:c,schedule:u}=t;if(t.matchUpIds&&!o)return wu(t);let p=lt(t,[{[ye]:!0},{[Ja]:{matchUpContextIds:!1,matchUpDetails:!1},[En]:G,[to]:Er}]);if(p.error)return p;if((!c||o)&&!u)return{error:et,info:"schedule is required"};let m=[],d=0,{matchUpDependencies:l}=Vr({tournamentRecords:s});for(let f of Object.values(s)){let{tournamentId:g}=f,I=o?.filter(S=>S.tournamentId===g).map(fe),h=c?.filter(S=>S?.tournamentId===g);if(I?.length||h?.length){let S=wu({matchUpDetails:h,scheduleCompletedMatchUps:e,scheduleByeMatchUps:r,matchUpDependencies:l,errorOnAnachronism:n,removePriorValues:i,tournamentRecords:s,tournamentRecord:f,checkChronology:a,matchUpIds:I,schedule:u});if(S.warnings?.length&&m.push(...S.warnings),S.scheduled&&(d+=S.scheduled),S.error)return S}}return m.length?{...R,scheduled:d,warnings:m}:{...R,scheduled:d}}function TA({autoSchedulingAudit:t,tournamentRecords:e}){Tt({topic:fa,payload:t});let r=s=>s?Object.values(s).reduce((c,u)=>c+u.length||0,0):0,n=(t?.schedulingProfile||[]).reduce((s,a)=>s+a.venues.reduce((c,u)=>c+u.rounds.length,0),0),o={scheduledDatesCount:t.scheduledDates?.length,noTimeMatchUpIdsCount:r(t?.noTimeMatchUpIds),scheduledMatchUpIdsCount:r(t?.scheduledMatchUpIds),overLimitMatchUpIdsCount:r(t?.overLimitMatchUpIds),requestConflictsCount:r(t?.requestConflicts),profileRoundsCount:n},i={itemType:cN,itemValue:o};for(let s of Object.values(e))Gi({tournamentRecord:s,timeItem:i})}function sx({schedulingProfileModifications:t,checkPotentialRequestConflicts:e,scheduleCompletedMatchUps:r,schedulingProfileIssues:n,dateSchedulingProfiles:o,containedStructureIds:i,matchUpDependencies:s,matchUpDailyLimits:a,clearScheduleDates:c,tournamentRecords:u,schedulingProfile:p,personRequests:m,periodLength:d,matchUps:l,courts:f,dryRun:g}){let I={},h={},S={},T={},A={},D={},y={},E={},U={},M={};for(let C of o){let O=Ut(C?.scheduleDate),b=C?.venues||[],x={},w={},F=(k,K)=>{k.forEach(z=>{let q=w[z].counters;q[K]?q[K]+=1:q[K]=1,q[$n]?q[$n]+=1:q[$n]=1})};S[O]={},T[O]={},I[O]={},h[O]={},y[O]=[],E[O]=[],U[O]=[],M[O]=[];let L={};l.forEach(k=>{k.schedule?.scheduledDate&&_n(O,Ut(k.schedule.scheduledDate))&&ta({matchUpPotentialParticipantIds:x,matchUpNotBeforeTimes:L,matchUp:k})});let{allDateScheduledByeMatchUpDetails:v,venueScheduledRoundDetails:B,allDateMatchUpIds:H}=SA({matchUpPotentialParticipantIds:x,individualParticipantProfiles:w,scheduleCompletedMatchUps:r,containedStructureIds:i,matchUpNotBeforeTimes:L,matchUpScheduleTimes:D,matchUpDependencies:s,clearScheduleDates:c,tournamentRecords:u,useGarman:!0,periodLength:d,scheduleDate:O,matchUps:l,courts:f,venues:b}),j=10,V=0,Y,$=10;for(;!Y;){for(let{venueId:k}of b){let K=0,z=B[k];for(;z.courtsCount&&z.scheduleTimes?.length&&z.matchUpsToSchedule?.length&&K<=z.courtsCount;){let{scheduleTime:q,attempts:nt=0}=z.scheduleTimes.shift(),Q=z.matchUpsToSchedule.find(it=>{let{matchUpId:ot,matchUpType:ut}=it,{participantIdsAtLimit:Qt,relevantParticipantIds:yt}=nl({matchUpPotentialParticipantIds:x,individualParticipantProfiles:w,matchUpDailyLimits:a,matchUp:it});if(Qt.length)return E[O].includes(ot)||E[O].push(ot),!1;let{scheduledDependent:Me}=hA({matchUpScheduleTimes:D,matchUpDependencies:s,scheduleTime:q,matchUpId:ot,details:z});if(Me)return!1;let{dependenciesScheduled:Ee,remainingDependencies:Ce}=tl({matchUpScheduleTimes:D,matchUpDependencies:s,allDateMatchUpIds:H,matchUp:it});if(!Ee)return T[O][ot]||(T[O][ot]=[]),T[O][ot].push({scheduleTime:q,remainingDependencies:Ce}),!1;let{enoughTime:Kt}=rl({individualParticipantProfiles:w,matchUpNotBeforeTimes:L,matchUpDependencies:s,scheduleTime:q,details:z,matchUp:it});if(!Kt)return S[O][ot]||(S[O][ot]=[]),S[O][ot].push({scheduleTime:q}),!1;let Re=z.greatestAverageMinutes,{conflicts:wt}=el({potentials:e,averageMatchUpMinutes:Re,requestConflicts:M,personRequests:m,scheduleTime:q,scheduleDate:O,matchUp:it});if(wt?.length)return A[O]||(A[O]=[]),A[O].push(...wt),!1;F(yt,ut);let Ue=z.minutesMap?.[ot]?.recoveryMinutes;return bc({matchUpPotentialParticipantIds:x,individualParticipantProfiles:w,matchUpNotBeforeTimes:L,averageMatchUpMinutes:Re,matchUpDependencies:s,recoveryMinutes:Ue,scheduleTime:q,matchUp:it}),D[ot]=q,!0});z.matchUpsToSchedule=z.matchUpsToSchedule.filter(({matchUpId:it})=>it!==Q?.matchUpId),Q?K+=1:(h[O][k]||(h[O][k]=[]),h[O][k].push({scheduleTime:q,attempts:nt+1}))}z.matchUpsToSchedule?.length&&(h[O][k]=h[O][k]?.filter(q=>{let nt=q.attempts<j;return nt&&z.scheduleTimes.push(q),!nt})),(!z.scheduleTimes?.length||!z.matchUpsToSchedule?.length)&&(z.complete=!0)}V+=1,Y=b.every(({venueId:k})=>B[k].complete)||V===$}for(let{venueId:k}of b){let K=B[k].matchUpMap;Object.keys(K).forEach(z=>{let q=u[z];q&&Object.keys(K[z]).forEach(nt=>{let{drawDefinition:Q}=Po({tournamentRecord:q,drawId:nt});Q&&K[z][nt].forEach(({matchUpId:ot})=>{let ut=D[ot];if(ut){let Qt=ut.split(":").map(Hn).join(":"),yt=`${Ut(O)}T${Qt}`;g?y[O].push(ot):(Vo({drawDefinition:Q,scheduledTime:yt,matchUpId:ot}).success&&y[O].push(ot),k&&Zs({tournamentRecord:q,drawDefinition:Q,matchUpId:ot,venueId:k}))}})})}),U[O]=B[k].matchUpsToSchedule.map(fe),I[O][k]=B[k].scheduleTimes.sort((z,q)=>Vt(z.scheduleTime)-Vt(q.scheduleTime))}!g&&v?.length&&_c({matchUpDetails:v,scheduleByeMatchUps:!0,removePriorValues:!0,tournamentRecords:u,schedule:{scheduledDate:"",scheduledTime:"",courtOrder:"",courtId:"",venueId:""}});for(let k of C.venues)for(let K of k.rounds){let q=(K.matchUps?.map(({matchUpId:Q})=>Q)||[]).filter(Q=>y[O].includes(Q));K.canScheduledMatchUpIds=q;let nt=Math.round(q.length/K.matchUpsCount*1e4)/100;(nt===1/0||isNaN(nt))&&(nt=0),K.possibleToSchedulePct=nt,K.matchUpsCount===q.length&&(K.possibleToSchedule=!0)}}let P=o.map(({scheduleDate:C})=>C),N={timeStamp:Date.now(),overLimitMatchUpIds:E,scheduledMatchUpIds:y,schedulingProfile:p,noTimeMatchUpIds:U,requestConflicts:M,scheduledDates:P};return TA({tournamentRecords:u,autoSchedulingAudit:N}),{...R,schedulingProfileModifications:t,schedulingProfileIssues:n,scheduleTimesRemaining:I,dateSchedulingProfiles:o,skippedScheduleTimes:h,recoveryTimeDeferredMatchUpIds:S,dependencyDeferredMatchUpIds:T,matchUpScheduleTimes:D,overLimitMatchUpIds:E,scheduledMatchUpIds:y,noTimeMatchUpIds:U,requestConflicts:M,scheduledDates:P}}function YN({averageMinutes:t,startTime:e,endTime:r,court:n,date:o}){if(!Array.isArray(n.dateAvailability))return{error:et,stack:"getEarliestCourtTime"};let i=Cc({scheduleDate:o,courts:[n],startTime:!0}),s=Cc({scheduleDate:o,courts:[n],endTime:!0});e=e||i,r=r||s;let a=wa({court:n,date:o}),{timeSlots:c}=hs({courtDate:a}),u=we(e),p=we(r);return{earliestCourtTime:c?.reduce((d,l)=>{let f=we(l.startTime),g=we(l.endTime);if(f>p||g<u)return d;let I=u>f?u:f;if(ca(I,g)>=t){let T=$t(I.toISOString());(!d||T<d)&&(d=T)}return d},void 0),courtStartTime:i,courtEndTime:s}}function ax({schedulingProfileModifications:t,checkPotentialRequestConflicts:e,scheduleCompletedMatchUps:r,schedulingProfileIssues:n,dateSchedulingProfiles:o,containedStructureIds:i,matchUpDependencies:s,matchUpDailyLimits:a,clearScheduleDates:c,tournamentRecords:u,periodLength:p=30,schedulingProfile:m,personRequests:d,matchUps:l=[],courts:f,dryRun:g}){let I={},h={},S={},T={},A={},D={},y={},E={},U={};for(let N of o??[]){let C=Ut(N?.scheduleDate),O=N?.venues||[],b={},x={},w=(Q,it)=>{Q.forEach(ot=>{let ut=x[ot].counters;ut[it]?ut[it]+=1:ut[it]=1,ut[$n]?ut[$n]+=1:ut[$n]=1})};I[C]={},h[C]={},D[C]=[],y[C]=[],E[C]=[],U[C]=[];let F={};l?.forEach(Q=>{Q.schedule?.scheduledDate&&_n(C,Ut(Q.schedule.scheduledDate))&&ta({matchUpPotentialParticipantIds:b,matchUpNotBeforeTimes:F,matchUp:Q})});let{allDateScheduledByeMatchUpDetails:L,allDateScheduledMatchUpIds:v,venueScheduledRoundDetails:B,allDateMatchUpIds:H}=SA({matchUpPotentialParticipantIds:b,individualParticipantProfiles:x,scheduleCompletedMatchUps:r,containedStructureIds:i,matchUpNotBeforeTimes:F,matchUpScheduleTimes:A,matchUpDependencies:s,clearScheduleDates:c,tournamentRecords:u,periodLength:p,scheduleDate:C,matchUps:l,courts:f,venues:O}),j=l?.filter(({matchUpId:Q})=>v.includes(Q)),{bookings:V}=zp({dateScheduledMatchUps:j,tournamentRecords:u,scheduleDate:C,periodLength:p}),{virtualCourts:Y}=jp({scheduleDate:C,periodLength:p,bookings:V,courts:f}),$=Y?.reduce((Q,it)=>{let{earliestCourtTime:ot,courtEndTime:ut}=YN({date:C,averageMinutes:0,court:it});return(!Q.startTime||we(ot)<we(Q.startTime))&&(Q.startTime=ot),(!Q.endTime||we(ut)>we(Q.endTime))&&(Q.endTime=ut),Q},{}),k=$.startTime,K=({courtId:Q,booking:it})=>Y?.find(ot=>ot.courtId===Q)?.dateAvailability[0].bookings.push(it),z=10,q=0,nt;for(;!nt;){for(let{venueId:Q}of O){let it=B[Q],ot=it.matchUpsToSchedule.length,ut=[],Qt=[],yt,Me=0;for(;!yt;){for(let Ee of it.matchUpsToSchedule){if(Qt.length===it.courtsCount||ut.length===it.courtsCount){yt=!0;break}let{matchUpId:Ce,matchUpType:Kt}=Ee,{participantIdsAtLimit:Re,relevantParticipantIds:wt}=nl({matchUpPotentialParticipantIds:b,individualParticipantProfiles:x,matchUpDailyLimits:a,matchUp:Ee});if(Re.length){y[C].includes(Ce)||y[C].push(Ce);continue}let{dependenciesScheduled:Ue,remainingDependencies:Ct}=tl({matchUpScheduleTimes:A,matchUpDependencies:s,allDateMatchUpIds:H,matchUp:Ee});if(!Ue){h[C][Ce]||(h[C][Ce]=[]),h[C][Ce].push({remainingDependencies:Ct});continue}let vt=[],ne=Y?.reduce((qt,pe)=>{if(Qt.includes(pe.courtId))return qt;let{earliestCourtTime:he}=YN({averageMinutes:it.greatestAverageMinutes,startTime:k,date:C,court:pe});if(qt.scheduleTime&&Vt(he)>=Vt(qt.scheduleTime))return qt;let{scheduledDependent:ur}=hA({matchUpScheduleTimes:A,matchUpDependencies:s,scheduleTime:he,matchUpId:Ce,details:it});if(ur)return qt;let{enoughTime:_e}=rl({individualParticipantProfiles:x,matchUpNotBeforeTimes:F,matchUpDependencies:s,scheduleTime:he,details:it,matchUp:Ee});if(!_e)return I[C][Ce]||(I[C][Ce]=[]),I[C][Ce].includes(he)||I[C][Ce].push(he),qt;let Wt=it.minutesMap?.[Ce]?.averageMinutes||it.greatestAverageMinutes,{conflicts:ve}=el({potentials:e,averageMatchUpMinutes:Wt,requestConflicts:U,personRequests:d,scheduleTime:he,scheduleDate:C,matchUp:Ee});if(ve?.length)return vt.push(...ve),!1;w(wt,Kt);let nr=it.minutesMap?.[Ce]?.recoveryMinutes;return bc({matchUpPotentialParticipantIds:b,individualParticipantProfiles:x,matchUpNotBeforeTimes:F,averageMatchUpMinutes:Wt,matchUpDependencies:s,recoveryMinutes:nr,scheduleTime:he,matchUp:Ee}),(!qt.scheduleTime||Vt(he)<Vt(qt.scheduleTime))&&(qt.averageMatchUpMinutes=Wt,qt.recoveryMinutes=nr,qt.scheduleTime=he,qt.courtName=pe.courtName,qt.courtId=pe.courtId),qt},{});if(ne.scheduleTime){let{averageMatchUpMinutes:qt,recoveryMinutes:pe,scheduleTime:he,courtId:ur}=ne;A[Ce]=he,T[Ce]=ur,ut.push(Ce),Qt.push(ur);let _e=he,Wt=br(_e,qt);K({courtId:ur,booking:{averageMatchUpMinutes:qt,recoveryMinutes:pe,periodLength:p,matchUpId:Ce,startTime:_e,courtId:ur,endTime:Wt,venueId:Q}}),it.matchUpsToSchedule=it.matchUpsToSchedule.filter(nr=>nr.matchUpId!==Ce)}else vt?.length&&(S[C]||(S[C]=[]),S[C].push(...vt))}(Qt.length===it.courtsCount||ut.length===it.courtsCount||!it.matchUpsToSchedule.length)&&(yt=!0),it.matchUpsToSchedule.length&&ut<it.courtsCount&&(we(k)<we($.endTime)?k=br(k,p):(yt=!0,it.complete=!0)),Me+=1,!yt&&Me>=ot&&(yt=!0)}it.matchUpsToSchedule?.length||(it.complete=!0)}q+=1,nt=O.every(({venueId:Q})=>B[Q].complete)||q===z}for(let{venueId:Q}of O){let it=B[Q].matchUpMap;Object.keys(it).forEach(ot=>{let ut=u[ot];ut&&Object.keys(it[ot]).forEach(Qt=>{let{drawDefinition:yt}=Po({tournamentRecord:ut,drawId:Qt});yt&&it[ot][Qt].forEach(({matchUpId:Ee})=>{let Ce=A[Ee],Kt=T[Ee];if(Ce){let Re=Ce.split(":").map(Hn).join(":"),wt=`${Ut(C)}T${Re}`;g||(Vo({drawDefinition:yt,scheduledTime:wt,matchUpId:Ee}),Hi({courtDayDate:C,tournamentRecords:u,tournamentRecord:ut,drawDefinition:yt,matchUpId:Ee,courtId:Kt})),D[C].push(Ee)}})})}),E[C]=B[Q].matchUpsToSchedule.map(fe)}!g&&L?.length&&_c({matchUpDetails:L,scheduleByeMatchUps:!0,removePriorValues:!0,tournamentRecords:u,schedule:{scheduledDate:"",scheduledTime:"",courtOrder:"",courtId:"",venueId:""}});for(let Q of N.venues)for(let it of Q.rounds){let ut=(it.matchUps??[]).map(({matchUpId:yt})=>yt)?.filter(yt=>D[C].includes(yt));it.canScheduledMatchUpIds=ut;let Qt=Math.round((ut?.length||0)/it.matchUpsCount*1e4)/100;(Qt===1/0||isNaN(Qt))&&(Qt=void 0),it.possibleToSchedulePct=Qt,it.matchUpsCount===ut?.length&&(it.possibleToSchedule=!0)}}let M=(o??[]).map(({scheduleDate:N})=>N),P={timeStamp:Date.now(),overLimitMatchUpIds:y,scheduledMatchUpIds:D,schedulingProfile:m,noTimeMatchUpIds:E,requestConflicts:U,scheduledDates:M};return TA({tournamentRecords:u,autoSchedulingAudit:P}),{...R,schedulingProfileModifications:t,schedulingProfileIssues:n,dateSchedulingProfiles:o,recoveryTimeDeferredMatchUpIds:I,dependencyDeferredMatchUpIds:h,matchUpScheduleTimes:A,overLimitMatchUpIds:y,scheduledMatchUpIds:D,noTimeMatchUpIds:E,requestConflicts:U,scheduledDates:M}}function Qp(t){let{scheduleAttributes:e=["scheduledDate","scheduledTime"],ignoreMatchUpStatuses:r=ae,scheduledDates:n,venueIds:o}=t,i=Xr(t),s=Rt(i)?Object.values(i).map(({tournamentId:c})=>c).filter(Boolean):[];if(!s?.length)return{error:Ft};let a=0;for(let c of s){let u=i[c],p=LV({ignoreMatchUpStatuses:r,scheduleAttributes:e,tournamentRecord:u,scheduledDates:n,venueIds:o});if(p.error)return p;a+=p.clearedScheduleCount??0}return{...R,clearedScheduleCount:a}}function LV({scheduleAttributes:t=["scheduledDate","scheduledTime"],ignoreMatchUpStatuses:e=ae,tournamentRecord:r,scheduledDates:n,venueIds:o=[]}){if(typeof r!="object")return{error:W};if(!Array.isArray(e)||!Array.isArray(o))return{error:G};o.length&&t.push("venueId");let i=le({matchUpFilters:{scheduledDates:n},tournamentRecord:r}).matchUps??[],s={};i.forEach(({matchUpStatus:u,schedule:p,drawId:m,matchUpId:d})=>{(!u||!e.includes(u))&&va({schedule:p,scheduleAttributes:t})&&(!o?.length||o.includes(p.venueId))&&(s[m]||(s[m]=[]),s[m].push(d))});let a=r.tournamentId,c=0;for(let u in s){let{event:p,drawDefinition:m}=We({tournamentRecord:r,drawId:u}),d=rr({drawDefinition:m,matchUpFilters:{matchUpIds:s[u]}}).matchUps??[];for(let l of d){let f=!1;l.timeItems=(l.timeItems??[]).filter(g=>{let I=g?.itemType&&![Eo,di,xs,ws,Ls].includes(g?.itemType);return I||(f=!0),I}),f&&(It({context:"clear schedules",eventId:p?.eventId,drawDefinition:m,tournamentId:a,matchUp:l}),c+=1)}}return{...R,clearedScheduleCount:c}}function Xp(t){let{checkPotentialRequestConflicts:e=!0,scheduleCompletedMatchUps:r,clearScheduleDates:n,scheduleDates:o=[],tournamentRecords:i,periodLength:s,useGarman:a,dryRun:c,pro:u}=t,p=lt(t,[{[ye]:!0},{[yn]:M=>!M||Array.isArray(M)&&M.every(Rr),[CI]:!1,[to]:Er}]);if(p.error)return p;let m=ko({tournamentRecords:i});if(m.error)return m;if(!m.schedulingProfile.length)return{...R};let{modifications:d,issues:l=[],schedulingProfile:f=[]}=m,g=Object.assign({},...Object.values(i).map(M=>Ji({tournamentRecord:M}).containedStructures)),I=o.map(M=>{if(Rr(M))return Ut(M)}).filter(Boolean),h=f.map(M=>M.scheduleDate).map(M=>Rr(M)&&Ut(M)).filter(M=>M&&(!o.length||I.includes(M)));if(!h.length)return{error:Py};if(n&&!c){let M=Array.isArray(n)?n:[];Qp({tournamentRecords:i,scheduledDates:M})}let S=po({ignoreDisabled:!1,tournamentRecords:i}).courts,{matchUps:T}=cn({matchUpFilters:{matchUpTypes:[Xt,Gt]},afterRecoveryTimes:!0,nextMatchUps:!0,tournamentRecords:i}),{matchUpDependencies:A}=Vr({includeParticipantDependencies:!0,tournamentRecords:i,matchUps:T}),{matchUpDailyLimits:D}=Yd({tournamentRecords:i}),{personRequests:y}=yi({requestType:Oc,tournamentRecords:i}),E=f.filter(M=>{let P=Ut(M?.scheduleDate);return h.includes(P)}).sort((M,P)=>new Date(M.scheduleDate).getTime()-new Date(P.scheduleDate).getTime()),U={schedulingProfileModifications:d,checkPotentialRequestConflicts:e,scheduleCompletedMatchUps:r,schedulingProfileIssues:l,dateSchedulingProfiles:E,containedStructureIds:g,matchUpDependencies:A,matchUpDailyLimits:D,clearScheduleDates:n,tournamentRecords:i,schedulingProfile:f,personRequests:y,periodLength:s,useGarman:a,matchUps:T,dryRun:c,courts:S};return u?ax(U):sx(U)}function AA(t){let e=t||{};return e.tournamentId||(e.tournamentId=Mt()),e.startDate&&!Za(e.startDate)&&!gm.test(e.startDate)?{error:ar}:e.endDate&&!Za(e.endDate)&&!gm.test(e.endDate)?{error:ar}:(e.extensions&&(e.extensions=e.extensions.filter(Pn)),{...e})}function Bg({addParticipants:t=!0,participantAttribute:e,tournamentRecord:r,personAttribute:n,teamNames:o,accessor:i,uuids:s}){if(!r)return{error:W};let a={},c=(r.participants??[]).filter(({participantType:f,participantRole:g})=>f===ht&&g===Ge),u=0;for(let f of c){let I=i&&Zi({element:f,accessor:i})?.value||n&&f.person?.[n]||e&&f[e];if(I){if(!Object.keys(a).includes(I)){a[I]={participantName:o?.[u]??I,participantId:s?.pop()??Mt(),individualParticipantIds:[],participantRole:Ge,participantType:kt};let h={value:n??e,name:VI};St({element:a[I],extension:h}),u+=1}a[I].individualParticipantIds.push(f.participantId)}}let p=Object.keys(a),m=(r.participants??[]).map(f=>{if(f.participantType!==kt||f.participantRole!==Ge)return;let{extension:g}=mt({name:VI,element:f}),I=g?.value;if(p.includes(I))return f.participantId}).filter(Boolean),d=0,l=[];return Object.keys(a).forEach(f=>{let g=a[f],{participantId:I}=g;m.includes(I)||(r.participants||(r.participants=[]),t&&r.participants.push(g),l.push(g),d++)}),t&&d?(Tt({payload:{tournamentId:r.tournamentId,participants:l},topic:jo}),{...R,participantsAdded:d}):l.length?{...R,newParticipants:l}:{error:_C}}var cx=[{AA:"Annexia"},{BA:"Bacteria"},{BO:"Borduria"},{BM:"Bensalem"},{BS:"Basenji"},{BI:"Balnibarbi"},{BV:"Bartovia"},{BZ:"Berzerkistan"},{CA:"Caldonia"},{CC:"Concordia"},{CH:"Chula"},{DA:"Deltora"},{DW:"Discworld"},{EA:"Eastasia"},{EP:"Ecotopia"},{ER:"Erewhon"},{FA:"Freedonia"},{FN:"Florin"},{FG:"Fogg"},{FK:"Fourecks"},{GA:"Genovia"},{GL:"Gilead"},{GD:"Gilead"},{GL:"Gondal"},{GO:"Gondor"},{GR:"Gruzinia"},{GT:"Goritania"},{GU:"Guilder"},{HA:"Heldscalla"},{HO:"Hidalgo"},{IL:"Illyria"},{KA:"Kinakuta"},{KG:"Kangan"},{KN:"Kreplachistan"},{KS:"Kallipolis"},{LH:"Lugash"},{LI:"Listenbourg"},{LT:"Lilliput"},{LU:"Luggnagg"},{LV:"Lichtenslava"},{MR:"Moher"},{NA:"Narnia"},{NV:"Novaria"},{OA:"Oceania"},{OS:"Orsinia"},{OV:"Octavia"},{PA:"Palombia"},{PG:"Penguina"},{QA:"Qasha"},{PM:"Panem"},{SA:"Solymbria"},{SD:"Syldavia"},{SG:"San Glucose"},{SL:"San Lorenzo"},{SR:"Sontar"},{SY:"Sylvania"},{TF:"Tralfamadore"},{TH:"Themyscira"},{UA:"Utopia"},{VA:"Vespugia"},{WA:"Wakanda"},{WX:"Wessex"},{ZA:"Zamunda"},{ZK:"Zubrowka"}];var ux=["Amber","Ansul","Atlantis","Braavos","Busytown","Castle Rock","Centralia","Coober Pedy","Chefchaouen","Chronopolis","Damanhur","Diaspar","Dictionopolis","Diomira","El Dorado","Elista","Ephesus","Gotham","Hadleyburg","Hallstatt","Hierusalem","Ilium","Inverness","Kowloon","Laputa","Longyearbyen","Lys","Matmata","Maycomb","Metropolis","Miyake-jima","Monowi","Nagoro","Navarre","New New York","Nimbin","Pemberley","Pseudopolis","Rivendell","Roswell","Shangri-La","Springfield","Supilinn","Thneedville","Trantor","Wobegon","Yonwood","Xanadu","Xylar","Zion"];function yA({count:t=1,participantsCount:e=32}={}){let r=cr(ux),n=r.slice(0,t);return{cities:Z(0,e).map(i=>i<Math.min(t,r.length)?n[i]:on(n))}}function EA({count:t=1,participantsCount:e=32}={}){let r=cr(cx),n=r.slice(0,t).map(i=>Object.keys(i)).flat();return{states:Z(0,e).map(i=>i<Math.min(t,r.length)?n[i]:on(n))}}function UA({count:t=1,participantsCount:e=32}={}){let r=Z(0,t).map(()=>Z(0,5).map(()=>Jn(0,9)).join(""));return{postalCodes:Z(0,e).map(o=>o<t?r[o]:on(r))}}function PA(t){let{cities:e,states:r,postalCodes:n,nationalityCode:o,participantIndex:i}=t;return{postalCode:n?.[i],state:r?.[i],city:e?.[i],countryCode:o}}var px={lastNames:["Abbey","Ahern","Ampleforth","Ananiadis","Andelic","Assange","Atreides","Austen","Bach","Banks","Barrington","Batty","Bauers","Beals","Beer","Bennett","Berry","Bonaparte","Brockovich","Bukowski","Cassidy","Catton","Calvino","Carson","Chip","Constant","Crane","Crowne","Cummings","Curie","Dallas","Diamond","Deckard","Drazic","Dunbar","Earhart","Eisenstein","Eldritch","Elliot","Escher","Eyre","Faulkner","Fulcher","Fukuoka","Godel","Goldstein","Greer","Hedges","Herbert","Holmgren","Humperdinck","Huxley","Illich","Jeffers","Jensen","Jevons","Johnson","Johnstone","Jovovich","Kingsnorth","Langer","Fernwright","Fuller","Le Guin","Lem","Lovelace","Mander","Midgely","Mond","Montoya","Moore","Murry","Nagle","Nearing","Ogden","Ophuls","Parks","Paz","Peet","Perfect","Pendejo","Pevensie","Postman","Ripley","Rodda","Rumfoord","Runciter","Rugen","Sale","Schumacher","Shaftoe","Shelley","Shepard","Smith","Stratton","Stewart","Swift","Tillich","Turing","Tyrell","Twain","Yeats","Veblen","Yates","Vonnegut","Waterhouse","Watson","Wolin","Wirt","Waschuk","Wormwood"],firstFemale:["Ada","Amelia","Amelie","America","Anne","Antonia","Aravis","Astrid","Beatrice","Brienne","Buttercup","Caitlin","Cimorene","Cordelia","Desdemona","Ellen","Elizabeth","Emily","Emmie","Erin","Eva","Evelyn","Heather","Helen","Hermia","Hypatia","Imogen","Jane","Jasmine","Juliana","Juliet","Katniss","Leeloo","Lenina","Lilith","Linda","Lizzie","Louise","Lucy","Marie","Mary","Martha","Matilda","Milla","Miranda","Meg","Melba","Nicole","Ola","Portia","Pris","Rachael","Rachel","Rebecca","River","Rosa","Rosalind","Scout","Sharn","Susanne","Titania","Uhura","Ursula","Valentina","Viola","Virginia","Xena","Zoe"],firstMale:["Alan","Aldous","August","Axel","Barda","Barry","Bill","Bruce","Charles","Chris","Constantine","Darwin","David","Derrick","Edward","Emmanuel","Ernst","Estlin","Fezzik","Filby","Frank","Frito","George","Glen","Helmholtz","Inigo","Italo","Ivan","James","Jared","Jerry","Joe","Johann","Julian","John Michael","Jonathan","Korben","Kirkpatrick","Kurt","Lief","Malachi","Mark","Masanobu","Maurits","Michael","Mustapha","Neil","Nikola","Octavio","Palmer","Paul","Pierre","Robinson","Rick","Rincewind","Roy","Shannon","Sheldon","Stafford","Stanislaw","Stanley","Syme","Thorstein","Thomas","Tyrone","Vizzini","Walton","Walker","Warren","Wendell","Westley","William","Winston","Zoran"]};function DA(t){let{count:e=100,sex:r}=t||{};if(!e||r&&![ee,ue].includes(r))return{personData:[],error:G};let n=Math.ceil(e*1.3),{lastNames:o,firstFemale:i,firstMale:s}=px,a=Xo.map(({iso:I})=>I).filter(Boolean),c=Math.ceil(n/o.length),u=Math.ceil(n/i.length),p=Math.ceil(n/s.length),m=Z(0,c).flatMap(()=>{let I=J(o,!1,!0);return Z(0,o.length).map(()=>xr(I))}),d=Z(0,u).flatMap(()=>{let I=J(i,!1,!0);return Z(0,i.length).map(()=>xr(I))}),l=Z(0,p).flatMap(()=>{let I=J(s,!1,!0);return Z(0,s.length).map(()=>xr(I))}),f={};for(let I=0;I<n;I++){let h=m.pop(),S=r||on([ee,ue]),T=S===ee?l.pop():d.pop(),A=on(a);f[`${T}${h}`]={nationalityCode:A,sex:S,firstName:T,lastName:h}}return{personData:Object.values(f).slice(0,e)}}function NA(t){let e=t?.count||1,{personExtensions:r,consideredDate:n,isMock:o=!0,gendersCount:i,personData:s,category:a,sex:c}=t||{};if(isNaN(e))return{error:G};let u=i?.[ee]||c===ee&&e||0,p=i?.[ue]||c===ue&&e||0;e=Math.max(e,u+p);let m=e-(u+p),d=u&&DA({count:u,sex:ee}).personData||[],l=p&&DA({count:p,sex:ue}).personData||[],f=[...d,...l,...m&&DA({count:m}).personData||[]],g=f.filter(U=>!c||u&&p||U.sex===c),I=[];if(Array.isArray(s)){let U=s.filter(M=>typeof M.firstName!="string"||typeof M.lastName!="string"||M.sex&&![ee,ue].includes(M.sex)||M.nationalityCode&&(typeof M.nationalityCode!="string"||M.nationalityCode.length>3||!Xo.find(({iso:P,ioc:N})=>[P,N].includes(M.nationalityCode)))?!1:(M.nationalityCode&&I.push(M.nationalityCode),!0));if(U.length)g=U;else return{error:G}}let h=s?g:cr(g);if(h.length<e){let{maleFirstNames:U,maleLastNames:M,femaleFirstNames:P,femaleLastNames:N,nationalityCodes:C}=f.reduce((O,b)=>{let{firstName:x,lastName:w,nationalityCode:F}=b;return b.sex===ee?(O.maleFirstNames.includes(x)||O.maleFirstNames.push(x),O.maleLastNames.includes(w)||O.maleLastNames.push(w)):(O.femaleFirstNames.includes(x)||O.femaleFirstNames.push(x),O.femaleLastNames.includes(w)||O.femaleLastNames.push(w)),O.nationalityCodes.includes(F)||O.nationalityCodes.push(F),O},{maleFirstNames:[],maleLastNames:[],femaleFirstNames:[],femaleLastNames:[],nationalityCodes:[]});Z(0,e-h.length).forEach(()=>{let O=c||on([ee,ue]),b=on(C),x=O===ee?on(U):on(P),w=O===ee?on(M):on(N),F={firstName:x,lastName:w,sex:O,nationalityCode:b};h.push(F)})}let{ageMinDate:S,ageMaxDate:T}=Au({consideredDate:n,category:a}),A=ct(S?.slice(0,4)||0)||ct(T?.slice(0,4)||0)-3,D=ct(T?.slice(0,4)||0)||ct(S?.slice(0,4)||0)+3,y=(S||T)&&[A,D],E=h.slice(0,e).map((U,M)=>{let[P,N]=y||[],C=y&&xr(Z(P,N)),O=xr(Z(0,365)),b=C&&mR(C,O);return Object.assign(rt({extensions:r||[{name:"regionCode",value:M+1}],birthDate:b,isMock:o}),U)});return{persons:E.length&&E||h[0],nationalityCodes:I}}var mx=["Ace Academy","Avengers","Ball Bouncers","Baseliners","Captivators","Civil Disobedients","Continentals","Court Royal","Court Sharks","Diamond Dogs","Danger Zone","Doubles Dominators","Double Faults","Tricksters","Eliminators","Court Crusaders","Fuzz Busters","Game Changers","Goal Gurus","Good Volley","Green Machine","Hawk Eyes","Inside Outers","Killer Instinct","Line Toers","Masters of Mayhem","Matter Catchers","Cheap Shot","Mean Machines","Mindspace Invaders","Net Centric","Net Positive","Smash Mullet","Over Your Head","Spin Meisters","Aggressors","Racket Machine","Slice Happy","Refs Nightmare","Sandeaters","Sun Seekers","Slicer Dicers","Sparkle Soul Tribe","Stacked Deck","Cross Stringers","The Emergence","Total Demolition","Touch and Go","Upside Downers","Vertically Challenged","Visual Spectacle"];function Hg({nameRoot:t="TEAM",count:e=1}={}){let n=cr(mx).slice(0,e);return n.length<e&&Z(0,e-n.length).forEach(o=>n.push(`${t} ${o+1}`)),{names:n}}function Wg({idPrefix:t,participantType:e,index:r,uuids:n}){return t?`${t}-${e===ht?"I":dt?"P":kt?"T":Ar?"G":"X"}-${r}`:n?.pop()||Mt()}function vc(t){let{rankingRange:e,scaledParticipantsCount:r}=t,{ratingsParameters:n=Br,valuesInstanceLimit:o,consideredDate:i,category:s,nationalityCodesCount:a,nationalityCodeType:c,nationalityCodes:u,participantsCount:p=32,participantType:m,personIds:d,idPrefix:l,uuids:f,personExtensions:g,addressProps:I,gendersCount:h,matchUpType:S,personData:T,sex:A,inContext:D,withISO2:y,withIOC:E,scaleAllParticipants:U}=t,M=m===dt||S===vi,P=m===kt||S===kt;e&&(!Array.isArray(e)||!e.every(Kt=>te(Kt))||e.length!==2)&&(e=void 0),r=U?p:r;let N=1e3,C=r&&r>N?r:N;e=e||[1,C],e[1]+=1;let O=p*(M?2:P?8:1),b=NA({count:O,personExtensions:g,consideredDate:i,gendersCount:h,personData:T,category:s,sex:A});if(b.error)return b;let{nationalityCodes:x,persons:w}=b,F=[],L=[],v=[],B=[];if(typeof s=="object"){let{categoryName:Kt,ageCategoryCode:Re,ratingType:wt}=s;if((Kt||Re)&&!wt){let[Ue,Ct]=e||[];if(L=cr(Z(Ue,Ct)).slice(0,r||Jn(20,30)),[dt,kt].includes(m)){let[vt,ne]=e||[];F=cr(Z(vt,ne)).slice(0,r||Jn(20,30))}}if(wt&&n[wt]){let{ratingMax:Ue,ratingMin:Ct,ratingAttributes:vt}=s,ne={...n[wt],...vt||{}},{attributes:qt={},decimalsCount:pe,accessors:he,range:ur,step:_e}=ne,Wt=Pe=>{let gr={},ri=Object.keys(Pe||{});for(let qe of ri){let bn=Pe[qe];if(typeof bn=="object"&&bn.generator){let{range:Ei}=bn,[Wi,hn]=Ei.slice().sort();gr[qe]=Jn(Wi,hn)}else gr[qe]=bn}return gr},nr=ur[0]>ur[1]?2:.5,[be,Nr]=ur.slice().sort(),Se=()=>Z(0,2e3).map(()=>sE(be,Nr,nr,_e,pe)).filter(Pe=>(!Ue||Pe<=Ue)&&(!Ct||Pe>=Ct)).slice(0,r||Jn(20,30)).map(Pe=>he?Object.assign({},...he.map(gr=>({[gr]:Pe})),Wt(qt)):Pe);v=Se(),[dt,kt].includes(m)&&(B=Se())}}let H=Xo.filter(Kt=>c==="IOC"&&Kt.ioc||Kt.iso);function j(Kt){let Re=Math.ceil(O/Kt);return o&&Re>o?Math.ceil(O/o):Kt}let{postalCodesProfile:V,postalCodesCount:Y,statesProfile:$,citiesProfile:k,citiesCount:K,statesCount:z}=I||{},q=Kt=>Object.keys(Kt).map(Re=>Z(0,$[Re]).map(()=>Re)).flat(),nt=k&&q(k)||I?.cities||yA({count:K||O,participantsCount:O}).cities,Q=$&&q($)||I?.states||EA({count:z||O,participantsCount:O}).states,it=V&&q(V)||I?.postalCodes||UA({count:Y||O,participantsCount:O}).postalCodes,ot={cities:nt,states:Q,postalCodes:it},ut=j(a),Qt=ut?cr(H).slice(0,a):u?H.filter(Kt=>u.includes(Kt.iso)):H,yt=cr(Z(0,Math.ceil(O/(ut||1))).map(()=>Qt).flat(1/0)),Me=Hg({count:p}).names;return{participants:Z(0,p).map(Kt=>{let Re=M?2:P?8:1,wt=Z(0,Re).map(qt=>{let pe=Kt*Re+qt;return Ce(pe)}),Ue=wt.map(qt=>qt.participantId),Ct=wt.map(qt=>qt.person.standardFamilyName).join("/"),vt=M?dt:kt,ne={participantId:Wg({participantType:vt,idPrefix:l,index:Kt,uuids:f}),participantRole:Ge,participantName:M?Ct:Me[Kt],individualParticipantIds:Ue,participantType:vt};return D&&(ne.individualParticipants=wt),M||P?[ne,...wt]:wt}).flat(),...R};function Ce(Kt){let Re=w[Kt],{nationalityCode:wt,participantExtensions:Ue,participantTimeItems:Ct,extensions:vt,firstName:ne,birthDate:qt,lastName:pe,personId:he,sex:ur}=Re||{},_e=ne||"GivenName",Wt=pe||"FamilyName",ve=`${_e} ${Wt}`,nr=yt[Kt],be=x?.length&&wt||nr&&(c==="IOC"?nr.ioc||nr.iso:nr.iso||nr.ioc)||wt;yt?.length&&!be&&!wt&&console.log("%c Invalid Nationality Code",{participantIndex:Kt,country:nr});let Nr=PA({...ot,participantIndex:Kt,nationalityCode:be}),Se=rt({participantId:Wg({participantType:ht,index:Kt,idPrefix:l,uuids:f}),extensions:Ue,timeItems:Ct,participantRole:Ge,participantType:ht,participantName:ve,person:{addresses:[Nr],personId:he||d?.length&&d[Kt]||Mt(),standardFamilyName:Wt,standardGivenName:_e,nationalityCode:be,extensions:vt,birthDate:Rr(qt)?qt:void 0,sex:ur}});if(E&&be){let Pe=Xo.find(({iso:gr})=>gr===be);Pe?.ioc&&(Se.person.iocNationalityCode=Pe.ioc),Pe?.label&&(Se.person.countryName=Pe.label)}if(y&&be){let Pe=Xo.find(({iso:gr})=>gr===be);Pe?.iso2&&(Se.person.iso2NationalityCode=Pe.iso2),Pe?.label&&(Se.person.countryName=Pe.label)}if(s){let Pe=L[Kt],gr=F[Kt];MA({scaleValue:Pe,eventType:Fs,scaleType:oi,participant:Se,category:s}),MA({scaleValue:gr,eventType:gi,scaleType:oi,participant:Se,category:s});let ri=v[Kt],qe=B[Kt];MA({scaleValue:ri,eventType:Fs,scaleType:Ki,participant:Se,category:s}),MA({scaleValue:qe,eventType:gi,scaleType:Ki,participant:Se,category:s})}return Se}}function MA({scaleValue:t,participant:e,eventType:r,scaleType:n,category:o}){let i=o.categoryName||o.ratingType||o.ageCategoryCode,s=[zi,n,r,i].join("."),a={itemValue:t,itemType:s};i&&t&&(e.timeItems||(e.timeItems=[]),e.timeItems.push(a))}function CA({alternatesCount:t=0,tieFormatName:e,tieFormat:r,drawSize:n}){let o=0,i=0,s=0,a=0,c={},u={[ee]:0,[ue]:0,[_r]:0,[ya]:0,[Fn]:0};r=typeof r=="object"?r:Bi({namedFormat:e}),r?.collectionDefinitions?.filter(Boolean).forEach(l=>{let{category:f,collectionId:g,matchUpType:I,matchUpCount:h,gender:S}=l;if([ee,ue].includes(S)){let T=h*(I===Gt?2:1);u[S]<T&&(u[S]=T)}else S===_r&&(u[ee]<h&&(u[ee]=h),u[ue]<h&&(u[ue]=h));if(f){let T=JSON.stringify(f);c[T]=f}if(g||(l.collectionId=Mt()),ie(Gt)(I)){let T=h;a+=h,o=Math.max(o,T)}if(ie(Xt)(I)){let T=h;s+=h,i=Math.max(i,T)}});let p=Object.keys(c).length?Math.max(s,a*2):Math.max(i,o*2),m=o*(n+t),d=i*(n+t);return{maxDoublesDraw:m,maxSinglesDraw:d,teamSize:p,genders:u}}function dx({participantsProfile:t,eventProfiles:e,drawProfiles:r}){let{participantsCount:n,participantType:o=ht}=t||{},i=n||0,s={[ue]:0,[_r]:0,[ya]:0,[ee]:0,[Fn]:0},a=0,c=0,u=0,p=0,m=0,d=({alternatesCount:f=0,uniqueParticipants:g,tieFormatName:I,drawSize:h=0,eventType:S,tieFormat:T,category:A,gender:D,stage:y})=>{let E=S===Kr,U=S===Fe,M=!!(g||y===at||A||D);if(U){p=Math.max(p,h+f),T=typeof T=="object"?T:Bi({namedFormat:I});let{teamSize:P,maxDoublesDraw:N,maxSinglesDraw:C,genders:O}=CA({alternatesCount:f,tieFormatName:I,tieFormat:T,drawSize:h});u=Math.max(u,P),c=Math.max(c,C),M||(a=Math.max(a,N)),Object.keys(O).forEach(b=>s[b]+=O[b])}else if(E)if(M){let P=(h+f)*2;m+=P,D&&(s[D]+=P)}else h+f&&h+f>a&&(a=h+f);else if(M){let P=h+f;D&&(s[D]+=P),m+=P}else h&&h>c&&(c=h+f)};if(e?.forEach(f=>{let{tieFormatName:g,tieFormat:I,drawProfiles:h,eventType:S,category:T,gender:A}=f;if(h)for(let D of h){let{tieFormatName:y,tieFormat:E}=D;d({...D,tieFormatName:y||g,tieFormat:E||I,eventType:S,category:T,gender:A})}}),Array.isArray(r))for(let f of r)d(f);let l=Math.max(p*u,a*2,c);return a&&(o=dt),(n||i)<l&&(n=l),n&&a&&[dt,Fe].includes(o)&&(c&&Math.floor(c/2)>a?n=Math.floor(c/2):(!c||a*2>=c)&&(n=Math.ceil(n/2))),n===void 0&&(n=!e?.length&&!r?.length?32:0),n<i&&(n=i),{uniqueParticipantsCount:m,participantsCount:n,largestTeamDraw:p,largestTeamSize:u,participantType:o,gendersCount:s}}function RA({participantsProfile:t,tournamentRecord:e,eventProfiles:r,drawProfiles:n,startDate:o,uuids:i}){let{participantsCount:s,participantType:a,largestTeamDraw:c,largestTeamSize:u,gendersCount:p}=dx({participantsProfile:t,eventProfiles:r,drawProfiles:n}),m=t?.teamKey,d=vc({uuids:i,...t,consideredDate:o,participantsCount:s,participantType:a,gendersCount:p}).participants,l=0,f=In({tournamentRecord:e,participants:d});if(f.error)return f;if(l+=f.addedCount,m){let S=Bg({tournamentRecord:e,...m});if(S.error)return S}let g=d.filter(({participantType:S})=>S===ht).map(gt),I=t?.idPrefix?`${kt}-${t.idPrefix}`:void 0,h=Z(0,c).map(S=>{let T=g.slice(S*u,(S+1)*u),A=Wg({index:S,participantType:a,idPrefix:I,uuids:i});return{participantName:`Team ${S+1}`,participantRole:Ge,individualParticipantIds:T,participantType:kt,participantId:A}});return f=In({participants:h,tournamentRecord:e}),f.error?f:(l+=f.addedCount,{addedCount:l,...R})}function bA({drawProfiles:t,category:e,gender:r}){let n={},o=t?.reduce((s,a)=>{let{qualifyingPositions:c=0,participantsCount:u=0,uniqueParticipants:p,stage:m=tt,drawSize:d=0}=a||{};Object.keys(s).includes(m)||(s[m]=0);let l=(u||d)-c;return p||r||e||m===at?(Object.keys(n).includes(m)||(n[m]=0),n[m]+=l):s[m]=Math.max(s[m],l),s},{}),i=Object.keys(n);return i.forEach(s=>o[s]+=n[s]),{stageParticipantsCount:o,uniqueParticipantsCount:n,uniqueParticipantStages:i}}function OA({allUniqueParticipantIds:t,stageParticipantsCount:e,eventParticipantType:r,targetParticipants:n}){let o=e[tt]||0,i=e[at]||0;return{stageParticipants:{QUALIFYING:n.filter(({participantType:a})=>a===r).filter(({participantId:a})=>!t.includes(a)).slice(0,i),MAIN:n.filter(({participantType:a})=>a===r).filter(({participantId:a})=>!t.includes(a)).slice(i,i+o)}}}var BV={[_t]:2,[ge]:1,[Ne]:1,[lr]:1,[Ot]:4};function jg(t){let{defaultWithScorePercent:e=2,winningSide:r}=t,{matchUpStatusProfile:n=BV,matchUpFormat:o=un,pointsPerMinute:i=1,sideWeight:s=4}=t;if(!Sr({matchUpFormat:o}))return{error:Tl};if(typeof n!="object")return{error:G};if(e>100&&(e=100),isNaN(e)||isNaN(i)||isNaN(s))return{error:G};let a=Object.keys(n).filter(N=>Object.keys(KI).includes(N)&&N!==me);if(Object.keys(a).reduce((N,C)=>N+n[C],0)>100)return{error:G,matchUpStatusProfile:n};let u=a.reduce((N,C)=>(N.pointer=N.pointer+n[C],N.valueMap.push([N.pointer,C]),N),{pointer:0,valueMap:[]}),p=Jn(1,100),m=(u.valueMap.find(N=>p<=N[0])??[100,me])[1],d={sets:[],scoreStringSide1:"",side2ScoreString:""};if([_t,Ot].includes(m)){r=r||Jn(1,2);let N={score:d,winningSide:r,matchUpStatus:m};if(!(m===Ot&&Jn(1,100)>100-e))return{outcome:N}}else if([ge,Ne].includes(m))return{outcome:{score:d,matchUpStatus:m}};let l=tr(o),{bestOf:f,setFormat:g,finalSetFormat:I}=l??{},h=[],S=Jn(0,1),T=r?[r-1]:[...Z(0,s).map(()=>S),1-S],D=[lr,Ot,_o,Xi].includes(m)&&(xr(Z(1,f))||1),y;for(let N of Z(1,(f??0)+1)){let C=N===f,{set:O,incomplete:b,winningSideNumber:x}=HV({incomplete:D===N,matchUpStatus:m,pointsPerMinute:i,setFormat:C&&I||g,setNumber:N,weightedRange:T});if(h.push(O),b){y=x;break}if(Vp({matchUp:{score:{sets:h},matchUpFormat:o}}).calculatedWinningSide)break}let E=Vp({matchUp:{score:{sets:h},matchUpFormat:o}}),U=y?r||y:E.calculatedWinningSide,{score:M}=IA({score:{sets:h},winningSide:U,matchUpStatus:m});return{outcome:{score:M,winningSide:U,matchUpStatus:m}}}function HV({weightedRange:t=[0,1],pointsPerMinute:e,matchUpStatus:r,incomplete:n,setFormat:o,setNumber:i}){let s={setNumber:i},{setTo:a,tiebreakFormat:c,tiebreakAt:u,tiebreakSet:p,timed:m,minutes:d}=o,l=Jn(0,t.length-1),f=t[l],g;if(m){let I=d*e,h=Math.round(I*.2),S=I+xr([1,-1])*h,T=kC(S,2),A=[T,S-T];f&&A.reverse(),g=t[l]+1;let D=A[0]>A[1]&&1||A[1]>A[0]&&2||0;if(n){let[U,M]=A;return Object.assign(s,{side1Score:U,side2Score:M}),ae.includes(r)?{set:s,incomplete:n,winningSideNumber:g}:{set:s,incomplete:n}}D||(A[Jn(0,1)]+=1),D=A[0]>A[1]?1:2,D!==g&&A.reverse();let[y,E]=A;return Object.assign(s,{side1Score:y,side2Score:E,winningSide:g}),{set:s}}else{if(n)return s.side1Score=Jn(0,u),s.side2Score=Jn(0,u),ae.includes(r)&&(g=t[l]+1),{set:s,incomplete:n,winningSideNumber:g};{let I=Z(1,a+1).map(E=>Z(0,a+2-E).map(()=>E)).flat(),h=I[Jn(0,I.length-1)],S=a&&Ag({isSide1:!0,tiebreakAt:u,lowValue:h,setTo:a}),T=!S,A=t.length===1&&t[l]+1;if(!T){A?(S[0]>S[1]?1:2)!==A&&S.reverse():f&&S.reverse();let[E,U]=S;Object.assign(s,{side1Score:E,side2Score:U})}let D=Ru({matchUpScoringFormat:{setFormat:o},setObject:s}),y;if(D.hasTiebreakCondition||T){let{NoAD:E,tiebreakTo:U}=c||p||{},M=Z(1,U+1).map(C=>Z(0,U+2-C).map(()=>C)).flat(),P=M[Jn(0,M.length-1)],N=wp({isSide1:!0,tiebreakNoAd:E,tiebreakTo:U,lowValue:P});if(N)if(T){let C=N[0]>N[1]?1:2;A?C!==A&&N.reverse():f&&N.reverse(),[s.side1TiebreakScore,s.side2TiebreakScore]=N,y=N[0]>N[1]&&1||N[1]>N[0]&&2||void 0}else D.leadingSide===2?[s.side1TiebreakScore,s.side2TiebreakScore]=N:[s.side2TiebreakScore,s.side1TiebreakScore]=N}s.winningSide=D.winningSide||D.leadingSide||A||y}}return{set:s}}function ol(t){let{matchUpStatusProfile:e,completeAllMatchUps:r,randomWinningSide:n,tournamentRecord:o,completionGoal:i,drawDefinition:s,event:a}=t;if(!s)return{error:X};let c=t.matchUpFormat||s.matchUpFormat||a?.matchUpFormat,u=s.structures.slice().sort(ci),p=0,{matchUps:m,matchUpsMap:d}=re({contextFilters:{stages:[tt,at]},matchUpFilters:{matchUpTypes:[Bt],roundNumbers:[1]},inContext:!0,drawDefinition:s});if(m?.length){let g=a?.category?.ageCategoryCode||a?.category?.categoryName;if(g){let h=rA({singlesOnly:!0,tournamentRecord:o,drawDefinition:s,scaleAccessor:{scaleName:g,sortOrder:EN,scaleType:oi},event:a});if(h.error)return h;let{lineUps:S,participantsToAdd:T}=h;In({tournamentRecord:o,participants:T}),St({element:s,extension:{name:ho,value:S}})}else{let I=m[0]?.structureId,{positionAssignments:h}=Nt({drawDefinition:s,structureId:I});if(h?.length){let{participants:S}=Yt({participantFilters:{participantTypes:[Bt]},tournamentRecord:o}),T=A=>{let D=A.tieMatchUps.filter(ie(Xt)),y=A.tieMatchUps.filter(ie(Gt));D.forEach((E,U)=>{let M=E.matchUpId;E.sides.forEach(P=>{let{drawPosition:N}=P,C=S?.find(O=>{let{participantId:b}=O;return h.find(w=>w.participantId===b)?.drawPosition===N});if(C){let O=C.individualParticipantIds?.[U];O&&Xd({teamParticipantId:C.participantId,participantId:O,tournamentRecord:o,drawDefinition:s,tieMatchUpId:M,event:a})}})}),y.forEach((E,U)=>{let M=E.matchUpId;E.sides.forEach(P=>{let{drawPosition:N}=P,C=S?.find(O=>{let{participantId:b}=O;return h.find(w=>w.participantId===b)?.drawPosition===N});C&&C.individualParticipantIds?.slice(U*2,U*2+2)?.forEach(b=>{Xd({teamParticipantId:C.participantId,participantId:b,tournamentRecord:o,drawDefinition:s,tieMatchUpId:M,event:a})})})})};m.forEach(T)}}}let l=typeof r=="string"&&r,f=l&&me;for(let g of u){if(p>=i)break;let{matchUps:I}=At({matchUpFilters:{matchUpTypes:[Gt,Xt]},afterRecoveryTimes:!1,tournamentRecord:o,inContext:!0,drawDefinition:s,matchUpsMap:d,structure:g,event:a}),h=I.filter(({winningSide:S})=>!S).sort(hi).map(fe);for(let S of h){if(!isNaN(i)&&p>=i)break;let{matchUps:T}=At({matchUpFilters:{matchUpTypes:[Gt,Xt]},afterRecoveryTimes:!1,tournamentRecord:o,inContext:!0,drawDefinition:s,matchUpsMap:d,structure:g,event:a}),A=T.find(y=>y.matchUpId===S),D=[ge,Ne].includes(A.matchUpStatus);if(A?.readyToScore&&!D){let y=WV({winningSide:!n&&1,matchUpStatusProfile:e,tournamentRecord:o,drawDefinition:s,targetMatchUp:A,matchUpFormat:c,matchUpStatus:f,scoreString:l,event:a});if(y?.error)return y;p+=1}}}return{...R,completedCount:p}}function qN(t){let{matchUpStatusCodes:e,policyDefinitions:r,tournamentRecord:n,drawDefinition:o,targetMatchUp:i,matchUpStatus:s,matchUpFormat:a,scoreString:c,winningSide:u,event:p}=t;if(!i||i.matchUpStatus===Dt)return;let{matchUpId:m}=i||{},{outcome:d}=kg({matchUpFormat:a,matchUpStatus:s,scoreString:c,winningSide:u});return e&&(d.matchUpStatusCodes=e),xu({tournamentRecord:n,policyDefinitions:r,drawDefinition:o,matchUpFormat:a,matchUpId:m,outcome:d,event:p})}function WV(t){let{matchUpStatusProfile:e={},tournamentRecord:r,policyDefinitions:n,drawDefinition:o,matchUpStatus:i,matchUpFormat:s,targetMatchUp:a,scoreString:c,winningSide:u,event:p}=t;if(c||i)return qN(t);let{matchUpId:m}=a||{},{outcome:d}=jg({matchUpStatusProfile:e,matchUpFormat:s,winningSide:u});return xu({policyDefinitions:n,tournamentRecord:r,drawDefinition:o,matchUpFormat:s,matchUpId:m,outcome:d,event:p})}function _A({matchUpStatusProfile:t,completeAllMatchUps:e,randomWinningSide:r,tournamentRecord:n,drawProfiles:o,event:i}){let s=Ht({event:i}).flightProfile,{eventName:a,eventType:c,category:u}=i,{startDate:p}=n,m=[],d=u?.categoryName||u?.ageCategoryCode||u?.ratingType,l=i.drawDefinitions?.map(({drawId:f})=>f);if(Array.isArray(s?.flights))for(let[f,g]of s.flights.entries()){let{drawId:I,stage:h,drawName:S,drawEntries:T}=g;m.push(g.drawId);let A=o[f],{seedsCount:D,generate:y=!0}=A||{};if(y){let E=T.filter(Pr(Bn)).map(Pr(Bn)),U=d||a;if(n&&D&&D<=E.length&&Z(1,D+1).forEach((x,w)=>{let F={scaleValue:x,scaleName:U,scaleType:eo,eventType:c,scaleDate:p},L=E[w];ba({tournamentRecord:n,participantId:L,scaleItem:F})}),l?.includes(I))break;let M=_u({...A,matchUpType:c,seedingScaleName:U,tournamentRecord:n,isMock:!0,drawEntries:T,drawName:S,drawId:I,event:i,stage:h});if(M.error)return{error:M.error,drawIds:[]};let{drawDefinition:P}=M;if(!P)return{error:pr};let N=o[f]?.drawExtensions;if(Array.isArray(N)&&N.filter(Pn).forEach(b=>St({element:P,extension:b})),M=Hp({suppressNotifications:!0,tournamentRecord:n,drawDefinition:P,event:i}),M.error)return{error:M.error,drawIds:[]};if(A?.withPlayoffs){let b=P.structures?.[0].structureId,x=Dp({idPrefix:A.idPrefix,...A.withPlayoffs,tournamentRecord:n,drawDefinition:P,isMock:!0,structureId:b,event:i});if(x?.error)return x}let C=A?.completionGoal;if(!(A?.automated===!1)&&(e||C)){let b=A?.matchUpFormat,x=ol({completeAllMatchUps:!C&&e,matchUpStatusProfile:t,randomWinningSide:r,tournamentRecord:n,completionGoal:C,drawDefinition:P,matchUpFormat:b,event:i});if(x.error)return{error:x.error,drawIds:[]};let w=x.completedCount;if(A?.drawType===so){let F=P.structures?.find(B=>B.stage===tt);if(!F)return{error:Lt};let L=Sc({structureId:F.structureId,tournamentRecord:n,drawDefinition:P,event:i});if(L.error)return{error:L.error,drawIds:[]};let v=C?C-(w??0):void 0;if(L=ol({completeAllMatchUps:!C&&e,completionGoal:C?v:void 0,matchUpStatusProfile:t,randomWinningSide:r,tournamentRecord:n,drawDefinition:P,matchUpFormat:b,event:i}),L.error)return{error:L.error,drawIds:[]}}}}}return{...R,drawIds:m}}function vA(t){let{participantsProfile:e={},uniqueParticipantsCount:r,ratingsParameters:n,tournamentRecord:o,eventProfile:i,eventIndex:s,event:a,uuids:c}=t,{category:u,gender:p,eventType:m}=a,d=ie(ao)(m)&&ht||ie(Kr)(m)&&dt||m,l=r[tt]||0,f=r[at]||0,g=i.drawProfiles?.length?l+f:i.participantsProfile?.participantsCount??0,I=[ee,ue].includes(p)?p:void 0,h=e?.idPrefix?`E-${s}-${e?.idPrefix}`:void 0,{participants:S}=vc({uuids:i.uuids||c,...e,scaledParticipantsCount:i.scaledParticipantsCount,consideredDate:o?.startDate,rankingRange:i.rankingRange,participantType:d,participantsCount:g,ratingsParameters:n,category:u,idPrefix:h,sex:I}),A=In({tournamentRecord:o,participants:S});if(A.error)return A;let D=S?.filter(({participantType:E})=>E===d),y=S?.map(gt);return{uniqueDrawParticipants:D,uniqueParticipantIds:y}}function lx({autoEntryPositions:t,tournamentRecord:e,drawParticipants:r,drawProfile:n,event:o}){let{drawType:i=io,qualifyingPositions:s=0,stage:a=tt,drawSize:c=0,drawName:u,drawId:p}=n,m=c-s,d=r.slice(0,m).map(gt);if(d.length){let g=Kn({participantIds:d,autoEntryPositions:t,entryStage:a,tournamentRecord:e,event:o});if(g.error)return g}let l=d.map(g=>({entryStatus:Zr,entryStage:a,participantId:g})),f=Wp({drawName:u||i,qualifyingPositions:s,drawEntries:l,drawId:p,event:o,stage:a});return f.error?f:{...R}}function xA({uniqueDrawParticipants:t,autoEntryPositions:e,stageParticipants:r,tournamentRecord:n,drawProfiles:o,category:i,gender:s,event:a}){let c=0;for(let u of o){let{qualifyingPositions:p=0,uniqueParticipants:m,stage:d=tt,drawSize:l=0}=u,f=l-p,g=m||s||i||d===at,I=g?t.slice(c,c+f):r[d||tt]||[];g&&(c+=f);let h=lx({autoEntryPositions:e,drawParticipants:I,tournamentRecord:n,drawProfile:u,event:a});if(h.error)return h}return{...R}}function wA(t){let{allUniqueParticipantIds:e,matchUpStatusProfile:r,participantsProfile:n,completeAllMatchUps:o,autoEntryPositions:i,hydrateCollections:s,randomWinningSide:a,ratingsParameters:c,tournamentRecord:u,eventProfile:p,eventIndex:m,publish:d,isMock:l,uuids:f}=t,g=p.gender,I=p.eventName,{eventType:h=ao,policyDefinitions:S,drawProfiles:T=[],eventExtensions:A,surfaceCategory:D,tieFormatName:y,processCodes:E,discipline:U,eventLevel:M,timeItems:P,ballType:N,category:C}=p,O=p.eventId||Mt(),b=p.tieFormat||(h===Fe?Bi({namedFormat:y,event:{eventId:O,category:C,gender:g},hydrateCollections:s,isMock:l}):void 0),x=u.participants;for(let q of T)!g&&q.gender&&(g=q?.gender);let{stageParticipantsCount:w,uniqueParticipantsCount:F,uniqueParticipantStages:L}=bA({drawProfiles:T,category:C,gender:g}),v=ie(ao)(h)&&ht||ie(Kr)(h)&&dt||h,{uniqueDrawParticipants:B=[],uniqueParticipantIds:H=[]}=L?vA({event:{eventType:h,category:C,gender:g},uniqueParticipantsCount:F,participantsProfile:n,ratingsParameters:c,tournamentRecord:u,eventProfile:p,eventIndex:m,uuids:f}):{},{eventAttributes:j}=p;typeof j!="object"&&(j={});let V=C?.categoryName||C?.ageCategoryCode||C?.ratingType;I=I||V||"Generated Event";let Y={...j,surfaceCategory:D,processCodes:E,discipline:U,eventLevel:M,eventName:I,eventType:h,tieFormat:b,ballType:N,category:C,eventId:O,gender:g};if(A?.length&&Array.isArray(A)){let q=A.filter(Pn);q?.length&&Object.assign(Y,{extensions:q})}if(Array.isArray(P)&&P.forEach(q=>ki({event:K,timeItem:q})),typeof S=="object")for(let q of Object.keys(S))Vi({policyDefinitions:{[q]:S[q]},event:Y});Y.category&&(Y.category.categoryName=V);let $,k=Mc({suppressNotifications:!1,internalUse:!0,tournamentRecord:u,event:Y});if(k.error)return k;let K=k?.event,{stageParticipants:z}=OA({allUniqueParticipantIds:e,stageParticipantsCount:w,eventParticipantType:v,targetParticipants:x});if(T?.length){let q=xA({uniqueDrawParticipants:B,autoEntryPositions:i,stageParticipants:z,tournamentRecord:u,drawProfiles:T,category:C,gender:g,event:K});if(q.error)return q;let nt=_A({matchUpStatusProfile:r,completeAllMatchUps:o,randomWinningSide:a,tournamentRecord:u,drawProfiles:T,event:K});if(nt.error)return nt;$=nt.drawIds}else if(p?.participantsProfile?.participantsCount){let q=B.map(gt);if(q.length){let nt=Kn({participantIds:q,autoEntryPositions:i,tournamentRecord:u,entryStage:tt,event:K});if(nt.error)return nt}}return d&&Js({tournamentRecord:u,event:K}),{drawIds:$,eventId:O,uniqueParticipantIds:H}}function Yg({tournamentRecords:t,scheduleDate:e,venueId:r,round:n}){if(!Rr(e))return{error:ar};let o="addSchedulingProfileRound",{extension:i}=mt({name:da,tournamentRecords:t,discover:!0}),s=i?.value||[],a=s.find(l=>_n(e,l.scheduleDate));if(!a){let{startDate:l,endDate:f}=wd({tournamentRecords:t}),g=new Date(e);if(l&&g<new Date(l)||f&&g>new Date(f))return{error:ar};a={scheduleDate:e,venues:[]},s.push(a)}let c=a.venues.find(l=>l.venueId===r);c||(c={venueId:r,rounds:[]},a.venues.push(c));let u=["notBeforeTime"],p=l=>Object.keys(l).filter(f=>!u.includes(f)).sort().map(f=>Rt(l[f])?p(l[f]):l[f]).flat().join("|");if(c.rounds.find(l=>p(l)===p(n)))return _({result:{error:dy},stack:o});c.rounds.push(n);let d=Dc({tournamentRecords:t,schedulingProfile:s});return d.error?d:{...R}}function fx({schedulingProfile:t,tournamentRecord:e}){if(typeof t!="object")return{error:G};let r=Ji({tournamentRecord:e}).containedStructures,n=le({tournamentRecord:e}).matchUps??[],{tournamentId:o}=e,i=[];for(let s of t){let{scheduleDate:a,venues:c=[]}=s;for(let u of c){let{rounds:p,venueId:m}=u;for(let d of p){let{drawId:l,winnerFinishingPositionRange:f,roundSegment:g}=d,h=n.filter(S=>{let T=f?.indexOf("-")>0&&f.split("-").map(D=>+D),A=S.finishingPositionRange?.winner;return S.drawId===l&&(!d.roundNumber||S.roundNumber===d.roundNumber)&&(!A||!T||jt(A,T).length===2||pt(A).length===pt(T).length&&jt(A,T).length===pt(A).length)})[0];if(h){let{eventId:S,roundNumber:T,drawName:A,structureName:D,roundName:y}=h,E=h.structureId;T&&!f&&(E=Object.keys(r).find(P=>r[P].includes(E))??E);let U={tournamentId:o,structureId:E,roundNumber:T,roundSegment:g,eventId:S,drawId:l},M=Yg({tournamentRecords:{[o]:e},round:U,scheduleDate:a,venueId:m});if(M.error)return M;i.push({structureName:D,roundName:y,drawName:A,...U})}}}}return{scheduledRounds:i}}function Jp(t){let e=lt(t,[{drawProfile:!0,_ofType:Ri}]);if(e.error)return e;let{allUniqueParticipantIds:r=[],participantsProfile:n={},matchUpStatusProfile:o,completeAllMatchUps:i,autoEntryPositions:s,hydrateCollections:a,randomWinningSide:c,ratingsParameters:u,tournamentRecord:p,isMock:m=!0,drawProfile:d,startDate:l,drawIndex:f,uuids:g}=t,I=J(d,!1,!0),{excessParticipantAlternates:h=!0,matchUpFormat:S=un,drawType:T=io,tournamentAlternates:A=0,alternatesCount:D=0,qualifyingPositions:y,qualifyingProfiles:E,generate:U=!0,eventExtensions:M,drawExtensions:P,completionGoal:N,tieFormatName:C,seedsCount:O,timeItems:b,drawName:x,category:w,idPrefix:F,publish:L,gender:v,stage:B}=I,H=I.drawSize||(I.ignoreDefaults?void 0:32),j=I.eventId||Mt(),V=d.eventType||d.matchUpType||ao,Y=V===Kr?dt:ht,$=typeof d.tieFormat=="object"&&d.tieFormat||V===kt&&Bi({event:{eventId:j,category:w,gender:v},namedFormat:C,hydrateCollections:a,isMock:m})||void 0,k=w?.categoryName||w?.ageCategoryCode||w?.ratingType,K=d.eventName||k||`Generated ${V}`,z=p?.participants||[],q=(E?.map(Ct=>Ct.structureProfiles||[]).flat().reduce((Ct,vt)=>{let ne=!vt.participantsCount||vt.participantsCount>vt.drawSize?vt.drawSize:vt.participantsCount||0;return Ct+ne},0)||0)*(Y===dt?2:1),nt=(!d.participantsCount||d.participantsCount>H?H:d.participantsCount)||0,Q={eventName:K,eventType:V,tieFormat:$,category:w,eventId:j,gender:v};Array.isArray(b)&&b.forEach(Ct=>ki({event:Q,timeItem:Ct}));let{eventAttributes:it}=d;if(typeof it!="object"&&(it={}),Object.assign(Q,it),M?.length&&Array.isArray(M)){let Ct=M.filter(Pn);Ct?.length&&Object.assign(Q,{extensions:Ct})}let ot=[];if(q||d.uniqueParticipants||!p||v||w){let Ct=(nt||0)+D+q,vt=Ct,ne={[ee]:0,[ue]:0},qt,pe;V===kt&&({teamSize:qt,genders:pe}=CA({alternatesCount:D,tieFormatName:C,tieFormat:$,drawSize:H}),Object.keys(pe).forEach(Wt=>{[ee,ue].includes(Wt)&&pe[Wt]&&(ne[Wt]=H*pe[Wt])}),vt=qt*((H||0)+q));let he=n?.idPrefix?`D-${f}-${n?.idPrefix}`:void 0,_e=vc({...n,scaledParticipantsCount:d.scaledParticipantsCount||n.scaledParticipantsCount,participantsCount:vt,consideredDate:p?.startDate,sex:v||n?.sex,rankingRange:d.rankingRange,uuids:d.uuids||g,ratingsParameters:u,participantType:Y,gendersCount:ne,idPrefix:he,category:w}).participants;if(Q.category&&(Q.category.categoryName=k),p){let Wt=In({participants:_e,tournamentRecord:p});if(Wt.error)return Wt}if(_e.forEach(({participantId:Wt})=>ot.push(Wt)),z=_e,V===kt){let Wt=pe[ee]?_e.filter(({participantType:qe,person:bn})=>qe===ht&&bn?.sex===ee).map(gt):[],ve=pe[ue]?_e.filter(({participantType:qe,person:bn})=>qe===ht&&bn?.sex===ue).map(gt):[],nr=_e.filter(({participantType:qe})=>qe===ht).map(gt).filter(qe=>!Wt.includes(qe)&&!ve.includes(qe)),be=qt-(pe[ee]+pe[ue]),Nr=0,Se=0,Pe=0,gr=Z(0,Ct).map(qe=>{let bn=ve.slice(Nr,Nr+pe[ue]),Ei=Wt.slice(Se,Se+pe[ee]),Wi=nr.slice(Pe,Pe+be);return Nr+=pe[ue],Se+=pe[ee],Pe+=be,{individualParticipantIds:[...bn,...Ei,...Wi],participantOtherName:`TM${qe+1}`,participantName:`Team ${qe+1}`,participantRole:Ge,participantType:kt,participantId:Mt()}}),ri=In({participants:gr,tournamentRecord:p});if(!ri.success)return ri;z=gr}}let ut=Ct=>{let{participantType:vt}=Ct;return ie(ao)(V)&&vt===ht||ie(Kr)(V)&&vt===dt?!0:V===kt&&vt===kt},Qt=Ct=>!d.gender||Ct.person?.sex===d.gender?!0:Ct.individualParticipantIds?.some(vt=>{let ne=z.find(qt=>qt.participantId===vt);return ne&&Qt(ne)}),yt=z.filter(ut).filter(Qt).filter(({participantId:Ct})=>!r.includes(Ct)),Me=yt.slice(0,nt).map(Ct=>Ct.participantId);if(m&&Me?.length){let Ct=Kn({autoEntryPositions:s,entryStage:B,tournamentRecord:p,participantIds:Me,event:Q});if(Ct.error)return Ct}let Ee=q?yt.slice(nt,nt+q).map(Ct=>Ct.participantId):0;if(m&&Ee?.length){let Ct=0,vt=1,ne=(pe,he)=>pe.stageSequence-he.stageSequence,qt=(pe,he)=>pe.roundTarget-he.roundTarget;for(let pe of E.sort(qt)){vt=pe.roundTarget||vt;let he=1,ur;for(let _e of pe.structureProfiles.sort(ne)){let ve=(_e.drawSize||am(_e.participantsCount))-(ur||0),nr=Ee.slice(Ct,Ct+ve),be=Kn({entryStage:at,entryStageSequence:he,autoEntryPositions:s,tournamentRecord:p,participantIds:nr,roundTarget:vt,event:Q});if(be.error)return be;ur=_e.qualifyingPositions,Ct+=ve,he+=1}vt+=1}}let Ce=h&&p?.participants?.filter(({participantId:Ct})=>!Me.includes(Ct)).filter(ut).filter(Qt).slice(0,D||H-nt||A).map(Ct=>Ct.participantId);if(m&&Ce?.length){let Ct=Kn({participantIds:Ce,autoEntryPositions:!1,entryStatus:wr,tournamentRecord:p,event:Q});if(Ct.error)return Ct.error}let Kt=k||K;p&&O&&O<=Me.length&&Z(1,O+1).forEach((vt,ne)=>{let qt={scaleName:Kt,scaleDate:l,scaleType:Of,scaleValue:vt,eventType:V},pe=Me[ne];ba({tournamentRecord:p,participantId:pe,scaleItem:qt})});let Re=_u({...J(d,!1,!0),tournamentRecord:p,seedingScaleName:Kt,matchUpFormat:S,eventId:j,isMock:m,event:Q});if(Re.error)return Re;if(!Re.drawDefinition)return{error:pr};let{drawDefinition:wt}=Re,Ue=wt.drawId;if(Array.isArray(P)&&P.filter(Pn).forEach(Ct=>St({element:wt,extension:Ct})),U){if(Hp({drawDefinition:wt,event:Q,suppressNotifications:!0}),d.withPlayoffs){let vt=wt.structures?.[0].structureId,ne=Dp({...d.withPlayoffs,tournamentRecord:p,drawDefinition:wt,structureId:vt,idPrefix:F,isMock:m,event:Q});if(ne?.error)return ne}let Ct=d.automated===!1;if(m&&!Ct){let vt=ne=>{let qt=ol({completeAllMatchUps:ne.completeAllMatchUps,completionGoal:ne.completionGoal,matchUpStatusProfile:o,randomWinningSide:c,tournamentRecord:p,drawDefinition:wt,matchUpFormat:S,event:Q});if(qt.error)return qt;let pe=qt.completedCount;if(T===so){let he=wt.structures?.find(Wt=>Wt.stage===tt);if(!he)return{error:Lt};Sc({structureId:he.structureId,tournamentRecord:p,drawDefinition:wt,event:Q});let ur=N?N-(pe??0):void 0,_e=ol({completionGoal:N?ur:void 0,matchUpStatusProfile:o,completeAllMatchUps:i,randomWinningSide:c,tournamentRecord:p,drawDefinition:wt,matchUpFormat:S,event:Q});if(_e.error)return _e}};if(N&&vt({completionGoal:N}),d.outcomes){let{matchUps:ne}=rr({inContext:!0,drawDefinition:wt,event:Q});for(let qt of d.outcomes){let{matchUpStatus:pe=me,matchUpStatusCodes:he,stageSequence:ur=1,matchUpIndex:_e=0,structureOrder:Wt,matchUpFormat:ve,drawPositions:nr,roundPosition:be,stage:Nr=tt,roundNumber:Se,winningSide:Pe,scoreString:gr}=qt,ri=ne?.reduce((hn,wc)=>{let{structureId:ji,matchUpId:eI}=wc;return hn[ji]?hn[ji].push(eI):hn[ji]=[eI],hn},{})??[],qe=Object.assign({},...Object.keys(ri).map((hn,wc)=>({[hn]:wc+1}))),Ei=ne?.filter(hn=>(!Nr||hn.stage===Nr)&&(!ur||hn.stageSequence===ur)&&(!Se||hn.roundNumber===Se)&&(!be||hn.roundPosition===be)&&(!Wt||qe[hn.structureId]===Wt)&&(!nr||jt(nr,hn.drawPositions).length===2))?.[_e],Wi=qN({matchUpStatusCodes:he,tournamentRecord:p,drawDefinition:wt,targetMatchUp:Ei,matchUpFormat:ve,matchUpStatus:pe,scoreString:gr,winningSide:Pe});if(Wi?.error)return Wi}}i&&vt({completeAllMatchUps:i})}L&&Js({tournamentRecord:p,event:Q})}else{let Ct=Wp({drawEntries:wt.entries,drawName:x||T,qualifyingPositions:y,drawId:Ue,event:Q,stage:B});if(Ct.error)return Ct}return{...R,event:rt(Q),uniqueParticipantIds:ot,targetParticipants:z,drawDefinition:wt,eventId:j,drawId:Ue}}var $N=()=>({altitude:void 0,courtId:void 0,courtName:"",courtDimensions:void 0,latitude:void 0,longitude:void 0,surfaceCategory:void 0,surfaceType:void 0,surfacedDate:void 0,dateAvailability:[],onlineResources:[],pace:void 0,notes:void 0}),gx=$N;function LA(t){return parseInt(t)}function KN({startTime:t="",endTime:e=""}={}){if(!t||!e||!Rs.test(t)||!Rs.test(e))return!1;let[r,n]=t.split(":").map(LA),[o,i]=e.split(":").map(LA);return o<r?!1:!(r===o&&i<n)}function Ix(t,e){let[r,n]=t.startTime.split(":").map(LA),[o,i]=e.startTime.split(":").map(LA);return r<o?-1:r>o?1:n<i?-1:n>i?1:0}function FA({dateAvailability:t}){if(!t)return{error:Dy};if(!Array.isArray(t))return{error:Ul};let e="Dates must be formated => YYYY-MM-DD",r="Times must be 24 hour => 00:00";for(let n of t){if(typeof n!="object")return{error:Ul};let{date:o,startTime:i,endTime:s,bookings:a=[]}=n;if(!i||!s)return{error:Ul};if(o&&!Ro.test(o))return{error:ar,dateAvailability:{date:o},info:e};if(!Rs.test(i))return{error:mo,dateAvailability:{startTime:i},info:r};if(!Rs.test(s))return{error:mo,dateAvailability:{endTime:s},info:r};if(i===s)return{error:mo,dateAvailability:{startTime:i,endTime:s},info:"startTime and endTime are equivalent"};if(!KN({startTime:i,endTime:s}))return{error:mo,dateAvailability:{startTime:i,endTime:s},info:"endTime must be after startTime"};if(a){if(!Array.isArray(a))return{error:om};for(let c of a){if(typeof c!="object")return{error:om};let{startTime:u,endTime:p}=c;if(!Rs.test(u))return{error:mo,booking:{startTime:u},info:r};if(!Rs.test(p))return{error:mo,booking:{endTime:p},info:r};if(u===p)return{error:mo,dateAvailability:{startTime:u,endTime:p},info:"startTime and endTime are equivalent"};if(!KN({startTime:u,endTime:p}))return{error:mo,dateAvailability:{startTime:u,endTime:p},info:"endTime must be after startTime"}}}}return{valid:!0}}function il({tournamentRecord:t,disableNotice:e,venueId:r,courtId:n,court:o}){let{venue:i}=Qo({tournamentRecord:t,venueId:r});if(!i)return{error:Ds};i.courts||(i.courts=[]);let s={...$N(),venueId:r,courtId:n};if(s.courtId||(s.courtId=Mt()),i.courts.some(c=>c.courtId===s.courtId))return{error:By};{let c=(o?.dateAvailability||[]).map(m=>({...m,date:Ut(m.date),startTime:$t(m.startTime),endTime:$t(m.endTime),bookings:m.bookings?.map(({startTime:d,endTime:l,bookingType:f})=>({startTime:$t(d),endTime:$t(l),bookingType:f}))})),u=Object.keys(s);for(let m of u)if(o?.[m])if(m==="dateAvailability"){let d=FA({dateAvailability:c});if(!d.valid&&d.error)return d;s.dateAvailability=c}else s[m]=o[m];let p=s;return i.courts.push(p),e||Tt({payload:{venue:i,tournamentId:t.tournamentId},topic:ui,key:i.venueId}),{...R,court:J(s),venueId:r}}}function qg(t){let{tournamentRecord:e,venueId:r}=t;if(typeof r!="string"||!r)return{error:Bo};let n=t.tournamentRecords??(e&&{[e.tournamentId]:e})??{},o=[],i;for(let s of Object.values(n)){let{venue:a}=Qo({tournamentRecord:s,venueId:r});if(a){let c=jV({...t,tournamentRecord:s});for(let u of c?.courts??[])o.push(u?.courtId);if(c.error)return c;i=!0}}return i?{...R,courtIds:o}:{error:Ds}}function jV({courtNameRoot:t="Court",dateAvailability:e=[],venueAbbreviationRoot:r,tournamentRecord:n,courtNames:o=[],courtTimings:i,courtsCount:s,startTime:a,courtIds:c,endTime:u,idPrefix:p,venueId:m,dates:d}){if(!m)return{error:Bo};let l=Qo({tournamentRecord:n,venueId:m});if(l.error)return l;let{venue:f}=l;if(!te(s)||!o)return{error:Vy};s=s??o.length;let h=Z(0,s).map(S=>{let T=i?.[S],A=T?d.map(D=>({date:ro(D),startTime:a,endTime:u,...T})):e;return T&&a&&u&&A.push({startTime:a,endTime:u}),{courtName:o[S]||r&&f?.venueAbbreviation&&`${f?.venueAbbreviation} ${S+1}`||`${t} ${S+1}`,dateAvailability:A}}).map((S,T)=>{let A=c?.pop()||p&&`${p}-${T+1}`;return il({disableNotice:!0,tournamentRecord:n,courtId:A,venueId:m,court:S})}).map(S=>S.court).filter(Boolean);return h.length!==s?_({info:"not all courts could be generated",result:{error:G}}):(f&&Tt({payload:{venue:f,tournamentId:n.tournamentId},topic:ui,key:f.venueId}),{...R,courts:J(h)})}function GA({tournamentRecord:t,venueProfiles:e,uuids:r}){let{startDate:n,endDate:o}=t,i=[];for(let[s,a]of e.entries()){let{venueAbbreviation:c,venueId:u=r?.pop()??Mt(),dateAvailability:p,startTime:m="07:00",endTime:d="19:00",courtTimings:l,courtsCount:f,courtNames:g,venueName:I,idPrefix:h,courtIds:S}=a,T={venueName:I||`Venue ${s+1}`,venueAbbreviation:c,venueId:u},A=pc({tournamentRecord:t,venue:T});if(A.error)return A;i.push(u);let D=bs(n,o),y=!Array.isArray(p)&&[{startTime:m,endTime:d}].concat(D.map(U=>({date:ro(U),startTime:m,endTime:d}))),E=qg({dateAvailability:p||y,tournamentRecord:t,courtTimings:l,courtsCount:f,courtNames:g,startTime:m,idPrefix:h,courtIds:S,endTime:d,venueId:u,dates:D});if(E.error)return E}return i}var YV=["Mock Tournament","CourtHive Challenge","Racket Rally","Generated Tournament","Factory Follies","Open Competition"];function zN(t){let{tournamentAttributes:e,startDate:r,endDate:n}=t??{},{tournamentName:o=xr(YV),ratingsParameters:i=Br,scheduleCompletedMatchUps:s,tournamentExtensions:a,matchUpStatusProfile:c,completeAllMatchUps:u,participantsProfile:p,autoEntryPositions:m,hydrateCollections:d,randomWinningSide:l,policyDefinitions:f,schedulingProfile:g,periodLength:I,autoSchedule:h,eventProfiles:S,venueProfiles:T,drawProfiles:A,uuids:D}=t??{};if(r&&!Rr(r)||n&&!Rr(n))return{error:ar};if(S&&!Array.isArray(S))return{error:G};if(!r){let b=new Date;r=ro(n??b),n=ro(b.setDate(b.getDate()+7))}if(!n){let b=new Date(r);n=ro(b.setDate(b.getDate()+7))}typeof e!="object"&&(e={});let y=AA({...e,tournamentName:o,isMock:!0,startDate:r,endDate:n});if(a?.length&&Array.isArray(a)){let b=a.filter(x=>Pn({extension:x}));b?.length&&Object.assign(y,{extensions:b,isMock:!0})}if(typeof f=="object")for(let b of Object.keys(f))Vi({policyDefinitions:{[b]:f[b]},tournamentRecord:y});let E=RA({participantsProfile:p,tournamentRecord:y,eventProfiles:S,drawProfiles:A,startDate:r,uuids:D});if(!E.success)return E;let U=[],M=[],P=[];if(Array.isArray(A)){let b=0;for(let x of A){let w=Jp({allUniqueParticipantIds:U,matchUpStatusProfile:c,completeAllMatchUps:u,autoEntryPositions:m,hydrateCollections:d,participantsProfile:p,randomWinningSide:l,ratingsParameters:i,tournamentRecord:y,isMock:!0,drawProfile:x,startDate:r,drawIndex:b,uuids:D});if(w.error)return w;let{drawId:F,eventId:L,event:v,uniqueParticipantIds:B}=w;if(w=Mc({suppressNotifications:!1,internalUse:!0,tournamentRecord:y,event:v}),w.error)return w;F&&P.push(F),M.push(L),B?.length&&U.push(...B),b+=1}}if(S){let b=0;for(let x of S){let w=wA({allUniqueParticipantIds:U,matchUpStatusProfile:c,participantsProfile:p,completeAllMatchUps:u,autoEntryPositions:m,hydrateCollections:d,randomWinningSide:l,ratingsParameters:i,tournamentRecord:y,eventProfile:x,eventIndex:b,startDate:r,uuids:D});if(w.error)return w;let{eventId:F,drawIds:L,uniqueParticipantIds:v}=w;L&&P.push(...L),M.push(F),v?.length&&U.push(...v),b+=1}}let N=T?.length?GA({tournamentRecord:y,venueProfiles:T,uuids:D}):[],C,O={};if(g){let b=fx({schedulingProfile:g,tournamentRecord:y});if(b.error)return b;if(C=b.scheduledRounds,h){let{tournamentId:x}=y,w={[x]:y};O=Xp({scheduleCompletedMatchUps:s,tournamentRecords:w,periodLength:I})}}return Bl(),rt({...R,tournamentRecord:y,scheduledRounds:C,schedulerResult:O,eventIds:M,venueIds:N,drawIds:P})}var ZN={};Jt(ZN,{anonymizeTournamentRecord:()=>XN,modifyTournamentRecord:()=>JN});function XN({keepExtensions:t=[],anonymizeParticipantNames:e=!0,tournamentRecord:r,tournamentName:n,personIds:o=[],tournamentId:i}){if(!r)return{error:W};let s=Array.isArray(t)?EE.concat(...t):EE,a=v=>Array.isArray(t)?v?.extensions?.filter(B=>s.includes(B.name)):v?.extensions,c={};r.extensions=a(r);let u=i||Mt();c[r.tournamentId]=u,r.tournamentId=u,r.createdAt=new Date().toISOString(),r.tournamentName=n||`Anonymized: ${ro(new Date)}`,r.isMock=!0,delete r.parentOrganisation;for(let v of r.participants||[]){let B=Mt();c[v.participantId]=B,v.participantId=B}for(let v of r.participants||[])Array.isArray(v.individualParticipantIds)&&(v.individualParticipantIds=v.individualParticipantIds.map(B=>c[B]));let p=0;for(let v of r.venues||[]){v.extensions=a(v),v.venueName=`Venue #${p}`,v.venueAbbreviation=`V${p}`;let B=Mt();c[v.venueId]=B,v.isMock=!0,p+=1}let m=1;for(let v of r.events||[]){v.extensions=a(v),v.isMock=!0;let B=Mt();c[v.eventId]=B,v.eventId=B;let H=v.category?.categoryName||v.category?.ageCategoryCode||v.category?.ratingType||v.gender;if(v.eventName=`Event ${m} ${H}`,Array.isArray(v.entries))for(let V of v.entries)V.participantId=c[V.participantId];for(let V of v.drawDefinitions||[]){V.extensions=a(V);let Y=Mt();if(c[V.drawId]=Y,V.drawId=Y,V.isMock=!0,Array.isArray(V.entries))for(let k of V.entries)k.participantId=c[k.participantId];let $=k=>{k.extensions=a(k);let K=Mt();c[k.structureId]=K,k.structureId=K;for(let z of k.positionAssignments||[])z.participantId&&(z.participantId=c[z.participantId]);for(let z of k.seedAssignments||[])z.participantId&&(z.participantId=c[z.participantId]);for(let z of k.matchUps||[]){z.isMock=!0;for(let q of z.sides||[])q.lineUp&&(q.lineUp=q.lineUp.map(({participantId:nt,collectionAssignments:Q})=>({participantId:c[nt],collectionAssignments:Q})))}};for(let k of V.structures||[])if($(k),Array.isArray(k.structures))for(let K of k.structures)$(K);for(let k of V.links||[])k.source.structureId=c[k.source.structureId],k.target.structureId=c[k.target.structureId]}let{extension:j}=mt({name:qr,element:v});Array.isArray(j?.value?.flights)&&j?.value.flights?.forEach(V=>{if(V.drawId=c[V.drawId],Array.isArray(V.drawEntries))for(let Y of V.drawEntries)Y.participantId=c[Y.participantId]}),m+=1}let d=r.startDate||ro(new Date),l=(r.participants||[]).filter(({participantType:v})=>v===ht),f=l.reduce((v,B)=>{let H=B.person?.sex;return[ee,ue].includes(H)?v[H]+=1:v[ya]+=1,v},{[ee]:0,[ue]:0,[ya]:0}),g=Object.assign({},...Object.keys(f).map(v=>({[v]:NA({category:{ageCategoryCode:"O18"},count:f[v],addressProps:{citiesCount:10},personExtensions:[],consideredDate:d,sex:v})?.persons||[]}))),I={[ee]:0,[ue]:0,[ya]:0},h=l.length,S=l.reduce((v,B)=>{let H=B.person?.addresses?.[0]||{},{city:j,state:V,postalCode:Y}=H;return v.cities.includes(j)||v.cities.push(j),v.states.includes(V)||v.states.push(V),v.postalCodes.includes(Y)||v.postalCodes.push(Y),v},{cities:[],postalCodes:[],states:[]}),T=S.postalCodes.length,A=S.cities.length,D=S.states.length,{cities:y}=yA({count:A||h,participantsCount:h}),{states:E}=EA({count:D||h,participantsCount:h}),{postalCodes:U}=UA({count:T||h,participantsCount:h}),M={cities:y,states:E,postalCodes:U};l.forEach((v,B)=>{let H=v?.person,j=H?.sex||ya,V=Ut(H?.birthDate)?.split("-")[0],Y=I[j],$=g[j][Y];if(I[j]+=1,V){let[,k,K]=$?.birthDate?.split("-")||[],z=[V,k,K].join("-");$.birthDate=z}if(H?.addresses){let k=PA({...M,participantIndex:B,nationalityCode:$.nationalityCode});$.addresses=[k]}$.personId=o?.[B]||Mt(),e?($.standardFamilyName=$.lastName,$.standardGivenName=$.firstName,v.participantName=`${$.standardGivenName} ${$.standardFamilyName}`):($.standardFamilyName=H?.standardFamilyName,$.standardGivenName=H?.standardGivenName),delete $.firstName,delete $.lastName,$.extensions=a(H),v.person=$,c[H?.personId]=$.personId}),(r.participants||[]).filter(({participantType:v})=>v===dt).forEach(v=>{let{individualParticipantIds:B}=v;v.participantName=qV({individualParticipantIds:B,individualParticipants:l})});let N=(r.participants||[]).filter(({participantType:v})=>v===kt),C=N.length,O=Hg({count:C}).names;N.forEach((v,B)=>{v.participantName=O[B]});let b=(r.participants||[]).filter(({participantType:v})=>v===Ar),x=b.length,w=Hg({count:x,nameRoot:"Group"}).names;b.forEach((v,B)=>{v.participantName=w[B]});let{extension:F}=mt({element:r,name:da});Array.isArray(F?.value)&&F?.value.forEach(v=>{v.tournamentId=c[v.tournamentId],v.structureId=c[v.structureId],v.eventId=c[v.eventId],v.drawId=c[v.drawId]});let{extension:L}=mt({element:r,name:ma});return Array.isArray(L?.value)&&L?.value.forEach(v=>{v.personId=c[v.personId]}),{...R}}function qV({individualParticipantIds:t,individualParticipants:e}){let r=e.filter(({participantId:n})=>t.includes(n)).map(({person:n})=>n?.standardFamilyName).filter(Boolean).sort().join("/");return t.length===1&&(r+="/Unknown"),r}function JN(t){let{ratingsParameters:e=Br,participantsProfile:r={},matchUpStatusProfile:n,completeAllMatchUps:o,autoEntryPositions:i,hydrateCollections:s,randomWinningSide:a,schedulingProfile:c,tournamentRecord:u,eventProfiles:p,periodLength:m,venueProfiles:d,autoSchedule:l,drawProfiles:f,uuids:g}=t;if(!u)return{error:W};let I=[],h=[],S=[];p?.forEach(M=>{let P=u.events?.find((N,C)=>M.eventIndex!==void 0&&C===M.eventIndex||M.eventName&&N.eventName===M.eventName||M.eventId&&N.eventId===M.eventId);P?.gender&&(M.gender=P.gender)});let T=u.participants?.length||void 0;T&&r?.idPrefix&&(r.idPrefix=`${r.idPrefix}-${T}`);let A=RA({startDate:u.startDate,participantsProfile:r,tournamentRecord:u,eventProfiles:p,drawProfiles:f,uuids:g});if(!A.success)return A;if(p){let M=u.events?.length||0;for(let P of p){let{ratingsParameters:N}=P,C=u.events?.find((O,b)=>P.eventIndex!==void 0&&b===P.eventIndex||P.eventName&&O.eventName===P.eventName||P.eventId&&O.eventId===P.eventId);if(C){let{gender:O,category:b,eventType:x}=C,{drawProfiles:w,publish:F}=P,L=ie(ao)(x)&&ht||ie(Kr)(x)&&dt||x;if(w){let{stageParticipantsCount:v,uniqueParticipantsCount:B,uniqueParticipantStages:H}=bA({drawProfiles:w,category:b,gender:O}),{uniqueDrawParticipants:j=[],uniqueParticipantIds:V=[]}=H?vA({event:{eventType:x,category:b,gender:O},uniqueParticipantsCount:B,participantsProfile:r,ratingsParameters:N,tournamentRecord:u,eventProfile:P,uuids:g}):{};I.push(...V);let{stageParticipants:Y}=OA({targetParticipants:u.participants||[],allUniqueParticipantIds:I,stageParticipantsCount:v,eventParticipantType:L}),$=xA({uniqueDrawParticipants:j,autoEntryPositions:i,stageParticipants:Y,tournamentRecord:u,drawProfiles:w,category:b,gender:O,event:C});if($.error||($=_A({matchUpStatusProfile:n,completeAllMatchUps:o,randomWinningSide:a,tournamentRecord:u,drawProfiles:w,event:C}),$.error))return $;S.push(...$.drawIds)}F&&Js({tournamentRecord:u,event:C})}else{let O=wA({startDate:u.startDate,allUniqueParticipantIds:I,matchUpStatusProfile:n,participantsProfile:r,completeAllMatchUps:o,autoEntryPositions:i,randomWinningSide:a,ratingsParameters:N,tournamentRecord:u,eventProfile:P,eventIndex:M,uuids:g});if(O.error)return O;let{eventId:b,drawIds:x,uniqueParticipantIds:w}=O;x&&S.push(...x),h.push(b),w?.length&&I.push(...w),M+=1}}}if(f){let M=(u.events||[]).map(P=>P.drawDefinitions?.map(()=>1)||[]).flat().reduce((P,N)=>P+N,0);for(let P of f){let N=Jp({startDate:u.startDate,allUniqueParticipantIds:I,matchUpStatusProfile:n,participantsProfile:r,completeAllMatchUps:o,autoEntryPositions:i,hydrateCollections:s,randomWinningSide:a,ratingsParameters:e,tournamentRecord:u,drawProfile:P,drawIndex:M,uuids:g});if(N.error)return N;let{drawId:C,eventId:O,event:b,uniqueParticipantIds:x}=N;if(N=Mc({tournamentRecord:u,event:b,internalUse:!0}),N.error)return N;C&&S.push(C),h.push(O),x?.length&&I.push(...x),M+=1}}let D=d?.length?GA({tournamentRecord:u,venueProfiles:d}):[],y,E={};if(c?.length){let M={[u.tournamentId]:u},P=Dc({tournamentRecords:M,schedulingProfile:c});if(P.error)return P;if(l){let{tournamentId:N}=u,C={[N]:u};E=Xp({tournamentRecords:C,periodLength:m})}}return{totalParticipantsCount:u.participants.length,scheduledRounds:y,schedulerResult:E,...R,eventIds:h,venueIds:D,drawIds:S}}var TM={};Jt(TM,{addIndividualParticipantIds:()=>Yp,addParticipant:()=>gn,addParticipants:()=>In,addPenalty:()=>IM,addPersonRequests:()=>rM,addPersons:()=>hM,createGroupParticipant:()=>uM,createTeamsFromParticipantAttributes:()=>Bg,deleteParticipants:()=>Li,filterParticipants:()=>lu,findParticipant:()=>cM,getCompetitionParticipants:()=>IT,getPairedParticipant:()=>tn,getParticipantEventDetails:()=>hT,getParticipantMembership:()=>ST,getParticipantScaleItem:()=>Pc,getParticipantSchedules:()=>TT,getParticipantSignInStatus:()=>AT,getParticipantTimeItem:()=>Nh,getParticipants:()=>Yt,getScaleValues:()=>aa,mergeParticipants:()=>gM,modifyIndividualParticipantIds:()=>nM,modifyParticipant:()=>qp,modifyParticipantName:()=>pM,modifyParticipantOtherName:()=>iM,modifyParticipantsSignInStatus:()=>oM,modifyPenalty:()=>lM,modifyPersonRequests:()=>tM,mutate:()=>SM,participantScaleItem:()=>uo,query:()=>vD,regenerateParticipantNames:()=>aM,removeIndividualParticipantIds:()=>Hf,removeParticipantIdsFromAllTeams:()=>hp,removePenalty:()=>dM,removePersonRequests:()=>eM,scaledTeamAssignment:()=>mM,setParticipantScaleItem:()=>ba,setParticipantScaleItems:()=>AP,validateLineUp:()=>ed});var SM={};Jt(SM,{addIndividualParticipantIds:()=>Yp,addParticipant:()=>gn,addParticipants:()=>In,addPenalty:()=>IM,addPersonRequests:()=>rM,addPersons:()=>hM,createGroupParticipant:()=>uM,createTeamsFromParticipantAttributes:()=>Bg,deleteParticipants:()=>Li,findParticipant:()=>cM,mergeParticipants:()=>gM,modifyIndividualParticipantIds:()=>nM,modifyParticipant:()=>qp,modifyParticipantName:()=>pM,modifyParticipantOtherName:()=>iM,modifyParticipantsSignInStatus:()=>oM,modifyPenalty:()=>lM,modifyPersonRequests:()=>tM,regenerateParticipantNames:()=>aM,removeIndividualParticipantIds:()=>Hf,removeParticipantIdsFromAllTeams:()=>hp,removePenalty:()=>dM,removePersonRequests:()=>eM,scaledTeamAssignment:()=>mM,setParticipantScaleItem:()=>ba,setParticipantScaleItems:()=>AP});function kA(t=0){(typeof t!="number"||isNaN(t))&&(t=0);let e=new Date;return e.setHours(e.getHours()+t),e.getTime().toString(36).slice(-6).toUpperCase()}function VA({personRequests:t,personId:e,requests:r}){t[e]||(t[e]=[]);let n=r.filter(({requestType:o})=>o).map(o=>{let{date:i,startTime:s,endTime:a}=o;return o.requestType===Oc&&(i=Ut(i),s=$t(s),a=$t(a),i&&s&&a)?{date:i,startTime:s,endTime:a,requestType:o.requestType}:o}).filter(Boolean);for(let o of n)o.requestId=kA(),t[e].push(o);return{mergeCount:n.length}}function sl(t){let{tournamentRecords:e,personRequests:r}=t,n=lt(t,[{[ye]:!0}]);if(n.error)return n;if(!r)return{...R};let o=Object.values(e);for(let i of o){let s=i.participants??[],a=[];for(let c of Object.keys(r))if(bo({tournamentParticipants:s,personId:c})){let u=r[c];u.length&&a.push({personId:c,requests:u})}Object.keys(a).length&&St({element:i,extension:{value:a,name:ma}})}return{...R}}function tM(t){let{tournamentRecords:e,requests:r,personId:n}=t,o=lt(t,[{[ye]:!0},{requests:!0,[to]:Er,[En]:G}]);if(o.error)return o;let i=r.map(({requestId:u})=>u).filter(Boolean),{personRequests:s}=yi({tournamentRecords:e}),a=u=>{s&&(s[u]=s[u].map(p=>{if(!i.includes(p.requestId))return p;let m=r.find(d=>d.requestId===p.requestId);if(m.requestType)return Object.assign(p,m)}).filter(Boolean))};if(n&&s?.[n])a(n);else if(s)for(let u of Object.keys(s))a(u);let c=r.filter(u=>!u.requestId);return c.length&&VA({personRequests:s,personId:n,requests:c}),sl({tournamentRecords:e,personRequests:s})}function eM(t){let{tournamentRecords:e,requestType:r,requestId:n,personId:o,date:i}=t,s=lt(t,[{[ye]:!0}]);if(s.error)return s;let{personRequests:a}=yi({tournamentRecords:e}),c=p=>{a&&(a[p]=a[p].filter(m=>(!r||m.requestType!==r)&&(!n||m.requestId!==n)&&(!i||m.date!==i)),a?.[p]?.length||delete a[p])},u=!r&&!n&&!o&&!i;if(!u){if(o&&a?.[o])c(o);else if(a)for(let p of Object.keys(a))c(p)}return u||!a||!Object.keys(a).length?or({name:ma,tournamentRecords:e,discover:!0}):sl({tournamentRecords:e,personRequests:a})}function rM(t){let{tournamentRecords:e,personId:r,requests:n}=t,o=lt(t,[{[ye]:!0,[tR]:!0},{requests:!0,[to]:Er,[En]:G}]);if(o.error)return o;let{personRequests:i}=yi({tournamentRecords:e}),{mergeCount:s}=VA({personRequests:i,personId:r,requests:n});return s&&i?sl({tournamentRecords:e,personRequests:i}):{error:G}}function nM({individualParticipantIds:t,groupingParticipantId:e,tournamentRecord:r}){let n="modifyIndividualParticipantIds";if(!r)return _({result:{error:W},stack:n});if(!e||!t)return _({result:{error:et},stack:n});let o=r.participants||[],i=o.find(l=>l.participantId===e);if(!i)return _({result:{error:Zt},stack:n});if(![kt,Ar].includes(i.participantType))return _({result:{error:nn},context:{participantType:i.participantType},stack:n});let s=t.filter(l=>o.find(g=>g.participantId===l)?.participantType!==ht);if(s.length)return _({result:{error:zr,invalidParticipantIds:s},stack:n});let a=i.individualParticipantIds||[],c=t.filter(l=>!a.includes(l)),u=a.filter(l=>!t.includes(l)),p=Yp({individualParticipantIds:c,groupingParticipantId:e,tournamentRecord:r});if(p.error)return _({result:p,stack:n});let m=Hf({individualParticipantIds:u,groupingParticipantId:e,tournamentRecord:r});if(m.error)return _({result:m,stack:n});let{topics:d}=Cr();if(d.includes(Qe)){let l=o.find(({participantId:f})=>f===e);Tt({topic:Qe,payload:{tournamentId:r.tournamentId,participants:[l]}})}return{...p,...m}}function oM({tournamentRecord:t,participantIds:e,signInState:r}){if(!t)return{error:W};if(!Array.isArray(e))return{error:et};if(![ru,$E].includes(r))return{error:G,signInState:r};let o=t.participants||[];if(!o.length)return{error:$a};let i=o.map(gt),s=e.filter(p=>!i.includes(p));if(s.length)return{error:G,context:{invalidParticipantIds:s}};let a=[],c=new Date().toISOString();for(let p of o){let{participantId:m}=p;if(e.includes(m)){let l=Jf({duplicateValues:!1,tournamentRecord:t,participantId:m,timeItem:{itemType:ic,itemValue:r,createdAt:c}});if(l.error)return l;a.push(p)}}let{topics:u}=Cr();return a.length&&u.includes(Qe)&&Tt({topic:Qe,payload:{tournamentId:t.tournamentId,participants:a}}),{...R}}function iM({tournamentRecord:t,participantId:e,participantOtherName:r}){if(!t)return{error:W};if(!e)return{error:oe};let{participant:n}=xo({tournamentRecord:t,participantId:e});if(!n)return{error:Zt};n.participantOtherName=r;let{topics:o}=Cr();return o.includes(Qe)&&Tt({topic:Qe,payload:{tournamentId:t.tournamentId,participants:[n]}}),{...R}}function sM({personFormat:t,person:e}){let r=g=>g.replace(/\W/g,""),n=g=>/^[a-z]*$/.test(r(g)),o=g=>/^[A-Z]*$/.test(r(g)),i=g=>/^[LAST]{4}/.test(r(g)),s=g=>g.toLowerCase().indexOf("l")<g.toLowerCase().indexOf("f"),a=g=>g.indexOf(",")>=0,c=g=>g.toLowerCase().indexOf("f.")>=0,u=g=>g.toLowerCase().indexOf("f")<0,p=g=>g.indexOf(" ")>0;if(!e)return;let m=p(t)?" ":"",d=xh(e?.standardGivenName??""),l=xh(e?.standardFamilyName??"");if(!t)return`${d}${m}${l}`;c(t)&&!a(t)&&!s(t)&&(d=`${d[0]}.`),n(t)?(d=d.toLowerCase(),l=l.toLowerCase()):o(t)?(d=d.toUpperCase(),l=l.toUpperCase()):i(t)&&(l=l.toUpperCase());let f=`${d}${m}${l}`;return u(t)?f=l:s(t)&&(a(t)?f=`${l},${m}${d}`:f=`${l}${m}${d}`),f}function hx({participantMap:t,participant:e,formats:r}){let{participantType:n,individualParticipantIds:o,person:i}=e,s=n&&r[n];if(n!==Jr&&s){let{personFormat:a,doublesJoiner:c}=s;n===ht&&(e.participantName=sM({person:i,personFormat:a})),n===dt&&(e.participantName=o?.map(u=>{let p=t[u]?.person;return sM({person:p,personFormat:a})}).filter(Boolean).join(c??"/"))}}function aM({tournamentRecord:t,formats:e}){if(!t)return{error:W};if(!Rt(e))return{error:et};let r=t.participants??[],n=sI(r,"participantId");for(let o of r)hx({participant:o,participantMap:n,formats:e});return{...R}}function cM(t){let{tournamentRecord:e,policyDefinitions:r,contextProfile:n,participantId:o,personId:i}=t,s=t.tournamentRecords||e&&{[e.tournamentId]:e}||{};if(typeof o!="string"&&typeof i!="string")return{error:et,stack:"publicFindParticipant"};let a,c;for(let u of Object.values(s)){c=u.tournamentId;let p=u.participants||[];if(a=bo({tournamentParticipants:p,internalUse:!0,policyDefinitions:r,contextProfile:n,participantId:o,personId:i}),a)break}return{participant:a,tournamentId:c,...R}}function uM({individualParticipantIds:t=[],participantRoleResponsibilities:e,participantRole:r=SU,tournamentRecord:n,participantId:o,groupName:i}){if(!n)return{error:W};if(!i)return{error:et,info:"Missing groupName"};if(!Array.isArray(t))return{info:"Invalid individualParticipantIds",error:G};let a=(Yt({participantFilters:{participantTypes:[ht]},tournamentRecord:n}).participants??[]).map(m=>m.participantId);for(let m of t)if(!a.includes(m))return{error:nn,participantId:m};let c=rt({participantId:o||Mt(),participantRoleResponsibilities:e,participantName:i,individualParticipantIds:t,participantType:Ar,participantRole:r}),u=gn({participant:c,tournamentRecord:n});if(u.error)return u;let{topics:p}=Cr();return p.includes(jo)&&Tt({topic:jo,payload:{tournamentId:n.tournamentId,participants:[c]}}),{...R,participant:J(c)}}function pM({tournamentRecord:t,participantName:e,participantId:r}){if(!t)return{error:W};if(!r)return{error:oe};if(!e)return{error:et,info:"Missing participantName"};let{participant:n}=xo({tournamentRecord:t,participantId:r});if(!n)return{error:Zt};n.participantName=e;let{topics:o}=Cr();return o.includes(Qe)&&Tt({topic:Qe,payload:{tournamentId:t.tournamentId,participants:[n]}}),{...R}}function mM({clearExistingAssignments:t=!0,individualParticipantIds:e,reverseAssignmentOrder:r,initialTeamIndex:n=0,scaledParticipants:o=[],teamParticipantIds:i,tournamentRecord:s,scaleAttributes:a,teamNameBase:c,teamsCount:u,eventId:p,event:m}){if(!s)return{error:W};if(!Array.isArray(i)&&!ft(u)&&!p||!ft(n)||o&&!Array.isArray(o)||a&&(typeof a!="object"||!Object.keys(a).length))return{error:G};if(!a&&!o.length||!o&&!(e&&a))return{error:et,info:"Missing scaling details"};if(p&&!i){if(m?.eventType!==kr)return{error:No};i=m?.entries?.filter(({entryStatus:h})=>h===Zr).map(gt)}if(!i?.length&&!u)return{info:"Missing teamParticipantIds or teamsCount",error:et};let d=e??o.map(({participantId:h})=>h);r&&(i?.reverse(),n+=1),n>(i?.length||0)-1&&(n=0);let l=i?.slice(n).concat(...i.slice(0,n))??[],f=[];for(let h of s.participants??[]){let{participantId:S,participantType:T}=h;if(l.includes(S)){if(T!==Jr)return{error:nn,participant:h};f.push(h)}}if(u&&f.length<u){let h=u-(f?.length||0),S=c??"Team",T=Z(0,h).map(E=>({participantName:`${S} ${E+1}`,participantType:Jr,participantRole:Ge})),{participants:A=[]}=In({participants:T,returnParticipants:!0,tournamentRecord:s}),D=A.map(gt),y=s.participants?.filter(({participantId:E})=>D.includes(E))??[];f.push(...y)}if(!f.length)return{error:xl};if(t)for(let h of f)h.individualParticipantIds=[];else{let h=f.map(S=>S).flat();e?.length?d=d.filter(S=>!h.includes(S)):o=o?.filter(({participantId:S})=>!h.includes(S))}if(!e?.length&&!o?.length)return{error:Yu,info:"Nothing to be done"};if(!o.length){for(let h of s.participants??[]){let{participantId:S,participantType:T}=h;if(!d.includes(S))continue;if(T!==ht)return{error:nn,participant:h};let A=uo({scaleAttributes:a,participant:h})?.scaleItem,D=a?.accessor?A?.scaleValue?.[a?.accessor]:A?.scaleValue,y={participantId:S,scaleValue:D};o.push(y)}if(!o.length)return{error:Zt}}o.sort((h,S)=>a?.sortOrder?(S?.scaleValue||0)-(h?.scaleValue||0):(h?.scaleValue||1/0)-(S?.scaleValue||1/0));for(let h of o)if(!h.participantId)return{error:G,scaledParticipant:h};let g=0;for(;g<o.length;){for(let h of f){if(g+1>o.length)break;let S=o[g];h.individualParticipantIds.push(S.participantId),g++}f.reverse()}let I=f.map(gt);for(let h of s.events??[]){if(h.eventType!==kr)continue;let S=(h.entries??[]).filter(T=>I.includes(T.participantId));for(let T of S){let A=T.participantId,y=f.find(U=>U.participantId===A)?.individualParticipantIds;h.entries=(h.entries??[]).filter(U=>!y.includes(U.participantId)),(h.drawDefinitions??[]).forEach(U=>{U.entries=(U.entries??[]).filter(M=>!y.includes(M.participantId))});let{flightProfile:E}=Ht({event:h});(E?.flights||[]).forEach(U=>{U.drawEntries=(U.drawEntries||[]).filter(M=>!y.includes(M.participantId))})}}return{...R,scaledParticipants:o}}function dM(t){let{tournamentRecords:e}=t;if(typeof e!="object"||!Object.keys(e).length)return{error:Ft};for(let r of Object.values(e)){let n=$V({...t,tournamentRecord:r});if(n.error&&n.error!==Fc)return n}return{...R}}function $V({tournamentRecord:t,penaltyId:e}){if(!t)return{error:W};if(!e)return{error:Rl};let r=t?.participants??[],n=[],o=!1,i;return r.forEach(s=>{let a=!1;s.penalties=(s.penalties??[]).filter(c=>(c.penaltyId===e&&(a=!0,o||(i=c,o=!0)),a&&n.push(s),c.penaltyId!==e))}),i&&Tt({topic:Qe,payload:{tournamentId:t.tournamentId,participants:n}}),i?{...R,penalty:i}:{error:Fc}}var KV=({penaltyId:t=Mt()}={})=>({refereeParticipantId:void 0,penaltyCode:void 0,penaltyType:void 0,extensions:void 0,matchUpId:void 0,createdAt:void 0,issuedAt:void 0,notes:void 0,penaltyId:t}),BA=KV;function lM(t){let{tournamentRecords:e}=t;if(typeof e!="object"||!Object.keys(e).length)return{error:Ft};for(let r of Object.values(e)){let n=zV({...t,tournamentRecord:r});if(n.error&&n.error!==Fc||n.success)return n}return{error:Fc}}function zV({tournamentRecord:t,modifications:e,penaltyId:r}){if(!t)return{error:W};if(!e)return{error:G,modifications:e};if(!r)return{error:Rl};let n=t?.participants??[],o=Object.keys(BA()).filter(c=>c!=="penaltyId"),i=Object.keys(e).filter(c=>o.includes(c));if(!i.length)return{error:qu};let s,a=[];return n.forEach(c=>{let u=!1;c.penalties=(c.penalties??[]).map(p=>(p.penaltyId===r&&(u=!0,i.forEach(m=>Object.assign(p,{[m]:e[m]})),s||(s=p)),p)),u&&a.push(c)}),s&&Tt({topic:Qe,payload:{tournamentId:t.tournamentId,participants:a}}),s?{...R,penalty:s}:{error:Fc}}function fM(t,e,r){return!t&&e?e:t&&!e||typeof t!="object"||typeof e!="object"?t:pt(Object.keys(t).concat(Object.keys(e))).reduce((o,i)=>{if(!e[i])o[i]=t[i];else if(!t[i])o[i]=e[i];else if(typeof t[i]!=typeof e[i])o[i]=e[i];else if(Array.isArray(t[i]))if(r===!0||Array.isArray(r)&&r.includes(i)){let s=pt(t[i].map(a=>JSON.stringify(a)).concat(e[i].map(a=>JSON.stringify(a)))).map(a=>JSON.parse(a));o[i]=s}else o[i]=e[i];else typeof t[i]=="object"?o[i]=fM(t[i],e[i],r):o[i]=e[i];return o},{})}function gM({participants:t=[],tournamentRecord:e,arraysToMerge:r}){if(!e)return{error:W};e.participants||(e.participants=[]);let n=t.filter(Pr(Bn)).map(u=>({[u.participantId]:u})),o=Object.assign({},...n),i=[];e.participants=e.participants.map(u=>{if(o[u.participantId]){let p=fM(u,o[u.participantId],r);return i.push(p),p}return u});let s=e.participants.map(Pr(Bn))||[],a=t.filter(({participantId:u})=>!s.includes(u)),{topics:c}=Cr();return a.length&&(e.participants=e.participants.concat(...a),c.includes(jo)&&Tt({topic:jo,payload:{participants:a}})),i.length&&c.includes(Qe)&&Tt({topic:Qe,payload:{tournamentId:e.tournamentId,participants:i}}),{modifiedParticipantsCount:i.length,newParticipantsCount:a.length,...R}}function IM(t){let{tournamentRecord:e,participantIds:r}=t,n=t.tournamentRecords??(e&&{[e.tournamentId]:e})??{},o;for(let i of Object.values(n)){let a=(Yt({tournamentRecord:i}).participants??[])?.map(gt).filter(c=>r.includes(c));a.length&&(o=QV({...t,penaltyId:t.penaltyId??o,tournamentRecord:i,participantIds:a}).penaltyId)}return o?{...R,penaltyId:o}:{error:Zt}}function QV({refereeParticipantId:t,tournamentRecord:e,participantIds:r,penaltyCode:n,penaltyType:o,extensions:i,penaltyId:s,matchUpId:a,issuedAt:c,notes:u}){if(!e)return{error:W};if(!r)return{error:oe};if(!o)return{error:ky};let m=(e?.participants??[]).filter(f=>r.includes(f.participantId));if(!m.length)return{error:Zt};let d=new Date().toISOString(),l=Object.assign(BA({penaltyId:s}),{refereeParticipantId:t,penaltyCode:n,penaltyType:o,matchUpId:a,createdAt:d,issuedAt:c,notes:u});return Array.isArray(i)&&i.forEach(f=>St({element:l,extension:f})),m.forEach(f=>{f.penalties||(f.penalties=[]),f.penalties.push(l)}),Tt({topic:Qe,payload:{tournamentId:e.tournamentId,participants:m}}),{...R,penaltyId:l.penaltyId}}function hM({participantRole:t=Ge,tournamentRecord:e,persons:r}){if(!e)return{error:W};if(!Array.isArray(r))return{error:G};if(!Object.keys(Xm).includes(t))return{error:Ry};let n=(e.participants||[]).map(({person:f})=>f?.personId).filter(Boolean),o=[],i=r.filter(f=>f&&(!f.personId||!n.includes(f.personId))).map(f=>(f.personId||(f.personId=Mt()),o.push(f.personId),f)),s=(f,g)=>Object.assign({},...Object.keys(f).filter(I=>!g.includes(I)).map(I=>({[I]:f[I]}))),a=i.map(f=>rt({extensions:f.participantExtensions,timeItems:f.participantTimeItems,participantType:ht,participantRole:t,person:s(f,["participantExtensions","participantTimeItems","pairedPersons"])})),c=0,u=0,p=In({participants:a,tournamentRecord:e});if(p.error)return p;u=p.addedCount||0;let m=[],d=Yt({participantFilters:{participantTypes:[ht]},tournamentRecord:e})?.participants??[];if(t===Ge&&r.filter(({pairedPersons:f})=>f).forEach(({personId:f,pairedPersons:g})=>{Array.isArray(g)&&g.forEach(I=>{let h=[f,I.personId].map(S=>bo({tournamentParticipants:d,personId:S})).filter(Boolean);if(h.length===2){let S=h.map(gt);m.push(rt({extensions:I.participantExtensions,timeItems:I.timeItems,participantRole:Ge,individualParticipantIds:S,participantType:dt}))}})}),m.length){if(p=In({participants:m,tournamentRecord:e}),p.error)return p;c=p.addedCount||0}let l=u+c;return{...R,addedCount:l,newPersonIds:o}}var NM={};Jt(NM,{bulkUpdatePublishedEventIds:()=>MT,getAllEventData:()=>CT,getCourtInfo:()=>Hm,getDrawData:()=>Fd,getEventData:()=>Gd,getEventPublishStatus:()=>vr,getPublishState:()=>as,getVenueData:()=>mc,mutate:()=>DM,publishEvent:()=>Js,publishEventSeeding:()=>AM,publishOrderOfPlay:()=>UM,query:()=>kD,setEventDisplay:()=>$d,unPublishEvent:()=>PM,unPublishEventSeeding:()=>yM,unPublishOrderOfPlay:()=>EM});var DM={};Jt(DM,{publishEvent:()=>Js,publishEventSeeding:()=>AM,publishOrderOfPlay:()=>UM,setEventDisplay:()=>$d,unPublishEvent:()=>PM,unPublishEventSeeding:()=>yM,unPublishOrderOfPlay:()=>EM});function AM({removePriorValues:t=!0,stageSeedingScaleNames:e,seedingScaleNames:r,tournamentRecord:n,status:o=Gr,drawIds:i=[],event:s}){if(!n)return{error:W};if(!s)return{error:Et};let a=vr({event:s,status:o}),c=(a?.seeding?.seedingScaleNames||r)&&{...a?.seeding?.seedingScaleNames,...r},u=(a?.seeding?.stageSeedingScaleNames||e)&&{...a?.seeding?.stageSeedingScaleNames,...e},p=rt({stageSeedingScaleNames:u,seedingScaleNames:c,published:!0,drawIds:i});return Xs({statusObject:{seeding:p},removePriorValues:t,status:o,event:s}),Tt({topic:WE,payload:{tournamentId:n.tournamentId,eventId:s.eventId,drawIds:i}}),{...R}}function yM({removePriorValues:t=!0,seedingScaleNames:e,tournamentRecord:r,status:n=Gr,drawIds:o,stages:i,event:s}){if(!r)return{error:W};if(!s)return{error:Et};let a=vr({event:s});if(a){let c=a.seeding;if(Array.isArray(i)&&c.stageSeedingScaleNames)for(let u of i)c.stageSeedingScaleNames[u]&&delete c.stageSeedingScaleNames[u];Array.isArray(e)&&c?.seedingScaleNames&&(c.seedingScaleNames=c.seedingScaleNames.filter(u=>!e.includes(u))),Array.isArray(o)&&c?.drawIds&&(c.drawIds=c.drawIds.filter(u=>!o.includes(u))),(!Object.values(c.stageSeedingScaleNames??{}).length&&!c.seedingScaleNames?.length&&!c.drawIds?.length||!i&&!e&&!o?.length)&&(delete c.stageSeedingScaleNames,delete c.seedingScaleNames,delete c.drawIds,c.published=!1),Xs({statusObject:{seeding:c},removePriorValues:t,status:n,event:s})}return Tt({topic:Tf,payload:{tournamentId:r.tournamentId,eventId:s.eventId}}),{...R}}function EM(t){let e=t?.tournamentRecords??(t?.tournamentRecord&&{[t.tournamentRecord.tournamentId]:t.tournamentRecord})??{};if(!Object.keys(e).length)return{error:Ft};for(let r of Object.values(e)){let n=XV({tournamentRecord:r,...t});if(n.error)return n}return{...R}}function XV({removePriorValues:t=!0,tournamentRecord:e,status:r=Gr}){if(!e)return{error:W};let n=`${Ko}.${zo}`,{timeItem:o}=Gn({element:e,itemType:n}),i=o?.itemValue||{[r]:{}};return i[r]&&delete i[r].orderOfPlay,Ti({timeItem:{itemValue:i,itemType:n},element:e,removePriorValues:t}),Tt({topic:Af,payload:{tournamentId:e.tournamentId}}),{...R}}function UM(t){let e=Xr(t);if(!Object.keys(e).length)return{error:Ft};for(let r of Object.values(e)){let n=JV({tournamentRecord:r,...t});if(n.error)return n}return{...R}}function JV({scheduledDates:t=[],removePriorValues:e,tournamentRecord:r,status:n=Gr,eventIds:o=[]}){if(!r)return{error:W};let i=`${Ko}.${zo}`,{timeItem:s}=Gn({element:r,itemType:i}),a=s?.itemValue||{[n]:{}};return a[n].orderOfPlay={published:!0,scheduledDates:t,eventIds:o},Ti({timeItem:{itemValue:a,itemType:i},element:r,removePriorValues:e}),Tt({topic:jE,payload:{tournamentId:r.tournamentId,scheduledDates:t,eventIds:o}}),{...R}}function PM({removePriorValues:t=!0,tournamentRecord:e,status:r=Gr,event:n}){if(!e)return{error:W};if(!n)return{error:Et};let o=`${Ko}.${zo}`,{timeItem:i}=pu({itemType:o,event:n}),s=i?.itemValue||{[r]:{}};return delete s[r].structureIds,delete s[r].drawDetails,delete s[r].drawIds,ki({event:n,timeItem:{itemValue:s,itemType:o},removePriorValues:t}),Xs({statusObject:{structureIds:void 0,drawIds:void 0,seeding:void 0},removePriorValues:t,status:r,event:n}),Tt({topic:Sf,payload:{tournamentId:e.tournamentId,eventId:n.eventId}}),{eventId:n.eventId,...R}}var MM={};Jt(MM,{getEntryStatusReports:()=>Tx,getParticipantStats:()=>Sx,getStructureReports:()=>yx,getVenuesReport:()=>Ex});function Sx({withCompetitiveProfiles:t,opponentParticipantId:e,withIndividualStats:r,teamParticipantId:n,tournamentRecord:o,withScaleValues:i,tallyPolicy:s,matchUps:a}){if(!o)return{error:W};if(a&&!Array.isArray(a))return{error:Je};if(a=a??le({tournamentRecord:o,participantsProfile:i?{withScaleValues:i}:void 0}).matchUps,!a?.length)return{error:Sn};let u=[];e&&u.push(e),n&&u.push(n);let p=u.length?{participantIds:u}:{participantTypes:[Jr]},m=Yt({participantFilters:p,tournamentRecord:o}).participants??[];if(!m.every(({participantType:U})=>U===Jr))return{error:zr};u.length||u.push(...m.map(gt));let d=new Map,l=new Map,f=new Map,g=new Map,I=(U,M="")=>l.get(U)||l.set(U,{participantName:M,participantId:U,competitorIds:[],competitiveness:{},matchUpStatuses:{},tiebreaks:[0,0],matchUps:[0,0],points:[0,0],games:[0,0],sets:[0,0]})&&l.get(U);for(let U of m){let{participantId:M,individualParticipantIds:P}=U;g.set(M,P??[]),I(M,U.participantName)}if(n&&!g.get(n))return _({result:{error:Zt},context:{teamParticipantId:n}});if(e&&!g.get(e))return _({result:{error:Zt},context:{opponentParticipantId:e}});let h=[],S=U=>{let M=[[],[]];for(let N of U){let C=N.participant;if(C?.participantName){d.set(C.participantId,{participantName:C.participantName,ratings:C.ratings});let O=l.get(C.participantId);O&&(O.participantName=C.participantName)}}let P=({side:N,individualParticipantIds:C})=>N.participantId&&(!C?.length||C.includes(N.participantId))&&[N.participantId]||N.participant?.individualParticipantIds?.length&&(!C?.length||jt(C,N.participant?.individualParticipantIds).length===N.participant?.individualParticipantIds?.length)&&N.participant.individualParticipantIds;if(g.size){let N=(C,O)=>{for(let b of U){if(!b.participant)continue;let x=P({individualParticipantIds:O,side:b});if(x?.length){let w=b.sideNumber;if(!w)continue;let F=[C];r&&F.push(...x),M[w-1]=F;let L=l.get(C);for(let v of x.filter(Boolean))L&&!L.competitorIds.includes(v)&&L.competitorIds.push(v)}}};if(n)(!e||U.every(O=>O.participant&&(P({individualParticipantIds:g.get(n),side:O})||P({individualParticipantIds:g.get(e),side:O}))))&&N(n,g.get(n));else for(let[C,O]of g)N(C,O)}else if(r)for(let N of U){if(!N.participant)continue;let C=P({individualParticipantIds:[],side:N}),O=N.sideNumber;O&&(M[O-1]=C)}return M};for(let U of a){if(!Rt(U))return{error:Je};let{matchUpStatus:M,matchUpFormat:P,matchUpType:N,winningSide:C,score:O,sides:b}=U;if(!b||!O||N===ln||M===Dt)continue;let x=S(b);if(!x.filter(Boolean).length)continue;let w=t&&C&&su({matchUp:U})?.competitiveness;h.push(U);let F=eg({matchUpStatus:M,matchUpFormat:P,tallyPolicy:s,winningSide:C,score:O}),L=rS({matchUpStatus:M,matchUpFormat:P,tallyPolicy:s,winningSide:C,score:O}),{pointsTally:v,tiebreaksTally:B}=nS({matchUpFormat:P,score:O});x.forEach((H,j)=>{for(let V of H){let Y=d.get(V)?.participantName,$=I(V,Y);if($){let k=(Q,it)=>it.forEach((ot,ut)=>$[Q][ut]+=ot),K=j?[...B].reverse():B,z=j?[...v].reverse():v,q=j?[...L].reverse():L,nt=j?[...F].reverse():F;if(k("tiebreaks",K),k("points",z),k("games",q),k("sets",nt),C){let Q=C-1===j?0:1;$.matchUps[Q]+=1}if(w){let Q=w.toLowerCase();$.competitiveness[Q]||($.competitiveness[Q]=[0,0]),$.competitiveness[Q][j]+=1}if(M){let Q=M.toLowerCase();$.matchUpStatuses[Q]||($.matchUpStatuses[Q]=0),$.matchUpStatuses[Q]+=1}}}})}let T=["tiebreaks","matchUps","points","games","sets"],A=["competitive","routine","decisive"],D=new Map,y=(U,M)=>(U??0)+(M??0);for(let[U,M]of l.entries()){for(let P of T){let N=M[P].reduce(y);if(N){let C=M[P][0]/N,O=`${P}Ratio`,b=parseFloat(C.toFixed(2));M[O]=b,f.set(U,!0),D.has(O)||D.set(O,[]),D.get(O)?.push(b)}}for(let P of A){let N=M.competitiveness?.[P]?.reduce(y);if(N){let C=M.competitiveness[P][0]/N,O=`${P}Ratio`,b=parseFloat(C.toFixed(2));M[O]=b}}}if(!n){let U=(M,P)=>P-M;for(let M of l.values())for(let P of T){let N=`${P}Ratio`;if(typeof M[N]=="number"){let C=D.get(N)?.sort(U).indexOf(M[N]);if(typeof C=="number"&&C>=0){let O=`${P}Rank`;M[O]=C+1}}}}let E={relevantMatchUps:h,...R};return n?(E.teamStats=l.get(n),e&&(E.opponentStats=l.get(e))):E.participatingTeamsCount=f.size,E.allParticipantStats=[...l.values()],E}function Zp({participant:t,eventType:e}){let r=t?.person?.personId,n=t?.person?.personOtherIds?.[0],o=t?.person?.tennisId,i=t?.ratings?.[e]?.find(({scaleName:u})=>u===gg),s=i?.scaleValue,{wtnRating:a,confidence:c}=s||{};return{timeStamp:i?.scaleDate,personOtherId:n,confidence:c,wtnRating:a,personId:r,tennisId:o}}function Tx({tournamentRecord:t}){if(!t)return{error:W};let e=t.tournamentId,{participantMap:r}=Yt({withScaleValues:!0,withEvents:!0,withSeeding:!0,tournamentRecord:t,withDraws:!0}),o=(le({matchUpFilters:{matchUpTypes:[Ia,vi]},tournamentRecord:t}).matchUps??[]).flatMap(({sides:f,matchUpType:g})=>f?.flatMap(I=>g===vi?I?.participant?.individualParticipantIds:I?.participant?.participantId||I.participantId).filter(Boolean)).filter(Boolean),i=[],s={},a={},c={},u=0,p=({id:f,entry:g,eventId:I,eventType:h})=>{let{qualifyingSeeding:S,mainSeeding:T,entryStatus:A,entryStage:D,drawId:y}=g;s[f]||(s[f]=[]);let{participant:E,events:U}=r?.[f]??{},M=Zp({participant:E,eventType:h}),P=U?.[I]?.ranking;A===pg&&i.push(f),s[f].push({participantType:E?.participantType,participantId:f,tournamentId:e,eventType:h,eventId:I,drawId:y,entryStatus:A,entryStage:D,...M,ranking:P,mainSeeding:T,qualifyingSeeding:S})};for(let f of t.events??[]){let g={},I=M=>{g[M]||(g[M]={count:0}),g[M].count+=1},{drawDefinitions:h=[],eventType:S,eventId:T}=f,A=h.flatMap(M=>{let{drawId:P,entries:N}=M;u+=1;let C=({stage:F,stageSequence:L})=>F===tt&&L===1||F===at,b=(M.structures??[]).filter(C).flatMap(({positionAssignments:F})=>F).filter(Boolean).map(({participantId:F})=>F),x=({participantId:F})=>b.includes(F),w=F=>{let{participantId:L,entryStatus:v,entryStage:B}=F;I(v);let H=r?.[L]?.draws?.[P]?.seedAssignments?.[tt];return{qualifyingSeeding:r?.[L]?.draws?.[P]?.seedAssignments?.[at],participantId:L,mainSeeding:H,entryStatus:v,entryStage:B,drawId:P}};return N?.filter(x).map(w)}),D=M=>{let P=M.participantId,N=r?.[P].participant.individualParticipantIds?.filter(C=>o.includes(C));return P&&{[P]:{individualParticipantIds:N}}};S===gi?(()=>{let M=Object.assign({},...A.map(D).filter(Boolean)),P=N=>{M[N.participantId].individualParticipantIds.forEach(C=>{p({id:C,eventType:S,eventId:T,entry:N})})};A.forEach(P)})():A.forEach(M=>{p({id:M?.participantId,eventType:S,eventId:T,entry:M})});let E=Object.values(g).reduce((M,P)=>M+P.count,0);Object.keys(g).forEach(M=>{g[M].pct=g[M].count/E*100}),c[T]={tournamentId:e,eventId:T,entries:A,entryStatuses:g};let U=Object.assign({},...Or.flatMap(M=>[{[M+"_count"]:g[M]?.count},{[M+"_pct"]:g[M]?.pct}]));a[T]={tournamentId:e,eventId:T,...U}}let m=Object.values(r??{}).filter(({participant:{participantType:f,participantRole:g}})=>f===ht&&g===Ge),d=m.filter(({participant:f})=>!o.includes(f.participantId)).map(({participant:f})=>f.participantId),l={nonParticipatingEntriesCount:d.length,individualParticipantsCount:m.length,eventsCount:Object.values(c).length,nonParticipatingParticipantIds:d,drawDefinitionsCount:u,tournamentId:e};return{entryStatusReports:Object.values(a).flat(),participantEntryReports:Object.values(s).flat(),eventReports:Object.values(c).flat(),withDrawnParticipantIds:i,tournamentEntryReport:l}}function Ax({eventType:t,matchUps:e,eventId:r,drawId:n}){let o={},i=g=>{let I=g?.matchUpFormat;I&&(o[I]||(o[I]=0),o[I]+=1)},s=e.filter(g=>r?g.eventId===r:g.drawId===n).reduce((g,I)=>(i(I),(I.sides??[]).flatMap(h=>(h?.participant?.individualParticipants||[h?.participant]).filter(Boolean)).forEach(h=>g[h.participantId]=h),g),{}),a=Object.values(s),c=a.map(g=>Zp({participant:g,eventType:t})).filter(({wtnRating:g})=>g),u=(a.length-c.length)/a.length*100,p=c.reduce((g,I)=>{let{wtnRating:h,confidence:S}=I;return g.totalWTN+=h,g.totalConfidence+=S,g},{totalWTN:0,totalConfidence:0}),m=c?.length?p.totalWTN/c.length:0,d=c?.length?p.totalConfidence/c.length:0,f=Object.values(o).reduce((g,I)=>g+(I||0),0);return{matchUpFormatCounts:o,matchUpsCount:f,avgConfidence:d,pctNoRating:u,avgWTN:m}}function yx({firstFlightOnly:t=!0,extensionProfiles:e,tournamentRecord:r}){if(!r)return{error:ra};let n={},o=Object.assign({},...(e??[]).map(({name:p,label:m,accessor:d})=>{let l=mt({element:r,name:p})?.extension?.value,f=d?Zi({element:l,accessor:d})?.value:l;return{[m||p]:f}})),i=r?.tournamentId,a=le({participantsProfile:{withScaleValues:!0},tournamentRecord:r}).matchUps??[],c=p=>Gn({itemType:uf,itemSubTypes:[eo],element:{timeItems:p}})?.timeItem?.itemValue?.scaleBasis,u=r?.events?.flatMap(({timeItems:p,drawDefinitions:m=[],extensions:d,eventType:l,eventId:f,category:g})=>{let h=d?.find(E=>E.name===qr)?.value?.flights?.map(E=>({[E.drawId]:E.flightNumber})),S=h&&Object.assign({},...h),T=d?.find(E=>E.name===Em)?.value?.length||0,A=Object.values(S),D=S&&Math.min(...A),y=c(p);return n[f]={totalPositionManipulations:0,maxPositionManipulations:0,generatedDrawsCount:0,drawDeletionsCount:T,seedingBasis:y?JSON.stringify(y):void 0,tournamentId:i,eventId:f},m.filter(E=>!t||!h||S[E.drawId]===D).flatMap(E=>{let{matchUpFormat:U,tieFormat:M,timeItems:P,extensions:N,structures:C,drawType:O,drawId:b}=E,{matchUpFormatCounts:x,matchUpsCount:w,avgConfidence:F,pctNoRating:L,avgWTN:v}=Ax({eventType:l,matchUps:a,drawId:b}),B=c(P)||y,H=ZV({extensions:N}),j=H?.length||0;return n[f].totalPositionManipulations+=j,n[f].generatedDrawsCount+=1,j>n[f].maxPositionManipulations&&(n[f].maxPositionManipulations=j),C?.filter(V=>V.stageSequence===1&&[at,tt,Ve,ce].includes(V.stage)).map(V=>{let Y=[tt,ce].includes(V.stage)?a.find(be=>be.structureId===V.structureId&&be.finishingRound===1&&be.winningSide):void 0,k=Y?.sides?.find(be=>be.sideNumber===Y.winningSide)?.participant,K=k?.participantType===Jr&&k.participantId,z=k?.participantType===dt?k.individualParticipants:[],q=Zp({participant:z?.[0]||k,eventType:l}),{personId:nt,personOtherId:Q,tennisId:it,confidence:ot,wtnRating:ut}=q||{},Qt=Zp({participant:z?.[1],eventType:l}),{personId:yt,personOtherId:Me,tennisId:Ee,confidence:Ce,wtnRating:Kt}=Qt||{},{ageCategoryCode:Re,categoryName:wt,subType:Ue}=g??{},Ct=V.matchUpFormat||U,ne=(x[Ct]||0)/w*100,{tieFormatName:qt,tieFormatDesc:pe}=Ld(M),{tieFormatName:he,tieFormatDesc:ur}=Ld(V.tieFormat),_e=pe===ur,Wt=!_e&&he,ve=V.tieFormat&&!_e&&ur,nr=H?.filter(be=>be.structureId===V.structureId)?.length||0;return{...o,tournamentId:i,eventId:f,structureId:V.structureId,drawId:b,eventType:l,category:Ue,categoryName:wt,ageCategoryCode:Re,flightNumber:S[b],drawType:O,stage:V.stage,seedingBasis:B?JSON.stringify(B):void 0,winningPersonId:nt,winningPersonOtherId:Q,winningPersonTennisId:it,winningPersonWTNrating:ut,winningPersonWTNconfidence:ot,winningPerson2Id:yt,winningPerson2OtherId:Me,winningPerson2TennisId:Ee,winningPerson2WTNrating:Kt,winningPerson2WTNconfidence:Ce,winningTeamId:K,positionManipulations:nr,pctNoRating:L,matchUpFormat:Ct,pctInitialMatchUpFormat:ne,matchUpsCount:w,drawTieFormatName:qt,drawTieFormatDesc:pe,tieFormatName:Wt,tieFormatDesc:ve,avgConfidence:F,avgWTN:v}})})});return{eventStructureReports:Object.values(n),structureReports:u}}function ZV({extensions:t}){return t?.find(({name:e})=>e===Tm)?.value?.slice(1)}function Ex({ignoreDisabled:t=!0,tournamentRecords:e,tournamentId:r,venueIds:n=[],dates:o=[]}){if(!Array.isArray(o))return{error:G,dates:o};if(!Array.isArray(n))return{error:G,venueIds:n};if(!(e&&Object.keys(e).filter(l=>!r||l===r)||[]).length)return{error:Ft};if(!o.every(Rr))return{error:ar};let a=po({tournamentRecords:e,ignoreDisabled:t,dates:o});if(a.error)return a;let c=a?.venues?.filter(({venueId:l})=>!n?.length||n.includes(l)),u=a.courts?.reduce((l,f)=>(f.dateAvailability?.forEach(g=>{let I=g.date;l.includes(I)||l.push(I)}),l),[]).filter(l=>!o.length||o.includes(l)),p={venueIds:c?.map(({venueId:l})=>l)},{matchUps:m}=cn({afterRecoveryTimes:!0,tournamentRecords:e,matchUpFilters:p});return{venuesReport:c?.map(l=>t1(u,l,m))}}function t1(t,e,r){let{venueId:n,courts:o,venueName:i}=e,s={};return t.forEach(a=>{let c=0,u=0,p=0;for(let l of o){let f=l.dateAvailability.find(h=>h.date===a),I=(f&&hs({courtDate:f}).timeSlots)?.reduce((h,S)=>{let{startTime:T,endTime:A}=S,D=Vt(A)-Vt(T);return h+D},0);I&&(p+=1),c+=I}let m=r.filter(({schedule:l})=>l.venueId===n&&_n(a,l.scheduledDate));m.forEach(({schedule:l})=>{let f=$t(l.scheduledTime),g=br(f,l.averageMinutes),I=Vt(g)-Vt(f);u+=I});let d=c?(u/c*100).toFixed(2):"100";s[a]={scheduledMatchUpsCount:m.length,availableCourts:p,availableMinutes:c,scheduledMinutes:u,percentUtilization:d}}),{venueId:n,venueName:i,venueReport:s}}var kM={};Jt(kM,{addMatchUpCourtOrder:()=>mA,addMatchUpEndTime:()=>lA,addMatchUpOfficial:()=>_N,addMatchUpResumeTime:()=>gA,addMatchUpScheduleItems:()=>Kp,addMatchUpScheduledDate:()=>Zd,addMatchUpScheduledTime:()=>Vo,addMatchUpStartTime:()=>dA,addMatchUpStopTime:()=>fA,addSchedulingProfileRound:()=>Yg,allocateTeamMatchUpCourts:()=>$p,assignMatchUpCourt:()=>Hi,assignMatchUpVenue:()=>Zs,bulkRescheduleMatchUps:()=>xM,bulkScheduleMatchUps:()=>_c,bulkScheduleTournamentMatchUps:()=>wu,bulkUpdateCourtAssignments:()=>bM,calculateScheduleTimes:()=>Kg,clearMatchUpSchedule:()=>LM,clearScheduledMatchUps:()=>Qp,courtGridRows:()=>Dg,findMatchUpFormatTiming:()=>Fp,findVenue:()=>Qo,generateBookings:()=>zp,generateVirtualCourts:()=>jp,getPersonRequests:()=>yi,getProfileRounds:()=>kd,getScheduledRoundsDetails:()=>bu,getSchedulingProfile:()=>ko,getSchedulingProfileIssues:()=>bT,matchUpScheduleChange:()=>wM,modifyMatchUpFormatTiming:()=>Ng,mutate:()=>GM,proAutoSchedule:()=>RM,proConflicts:()=>_M,publicFindCourt:()=>oU,query:()=>WD,removeEventMatchUpFormatTiming:()=>qd,removeMatchUpCourtAssignment:()=>CM,reorderUpcomingMatchUps:()=>vM,scheduleMatchUps:()=>OM,scheduleProfileRounds:()=>Xp,setMatchUpDailyLimits:()=>FM,setSchedulingProfile:()=>Dc,toggleParticipantCheckInState:()=>zd,validateSchedulingProfile:()=>Gp});var GM={};Jt(GM,{addMatchUpCourtOrder:()=>mA,addMatchUpEndTime:()=>lA,addMatchUpOfficial:()=>_N,addMatchUpResumeTime:()=>gA,addMatchUpScheduleItems:()=>Kp,addMatchUpScheduledDate:()=>Zd,addMatchUpScheduledTime:()=>Vo,addMatchUpStartTime:()=>dA,addMatchUpStopTime:()=>fA,addSchedulingProfileRound:()=>Yg,allocateTeamMatchUpCourts:()=>$p,assignMatchUpCourt:()=>Hi,assignMatchUpVenue:()=>Zs,bulkRescheduleMatchUps:()=>xM,bulkScheduleMatchUps:()=>_c,bulkScheduleTournamentMatchUps:()=>wu,bulkUpdateCourtAssignments:()=>bM,calculateScheduleTimes:()=>Kg,clearMatchUpSchedule:()=>LM,clearScheduledMatchUps:()=>Qp,courtGridRows:()=>Dg,findMatchUpFormatTiming:()=>Fp,findVenue:()=>Qo,generateBookings:()=>zp,generateVirtualCourts:()=>jp,matchUpScheduleChange:()=>wM,modifyMatchUpFormatTiming:()=>Ng,proAutoSchedule:()=>RM,proConflicts:()=>_M,publicFindCourt:()=>oU,removeEventMatchUpFormatTiming:()=>qd,removeMatchUpCourtAssignment:()=>CM,reorderUpcomingMatchUps:()=>vM,scheduleMatchUps:()=>OM,scheduleProfileRounds:()=>Xp,setMatchUpDailyLimits:()=>FM,setSchedulingProfile:()=>Dc,toggleParticipantCheckInState:()=>zd,validateSchedulingProfile:()=>Gp});function Kg({calculateStartTimeFromCourts:t=!0,defaultRecoveryMinutes:e=0,averageMatchUpMinutes:r=90,remainingScheduleTimes:n,clearScheduleDates:o,tournamentRecords:i,periodLength:s,scheduleDate:a,startTime:c,venueIds:u,endTime:p}){if(typeof i!="object"||!Object.keys(i).length)return{error:Ft};s=s??vu({recoveryMinutes:e,averageMatchUpMinutes:r});let{courts:m,venues:d}=po({dates:[a],ignoreDisabled:!0,tournamentRecords:i}),l=m?.filter(N=>!u||u.includes(N.venueId));c||(c=l?.reduce((N,C)=>{let b=C.dateAvailability?.find(x=>!x.date||_n(a,x.date))?.startTime??C.startTime;return b&&(!N||Vt(b)<Vt(N))?b:N},void 0)),p||(p=l?.reduce((N,C)=>{let b=C.dateAvailability?.find(x=>!x.date||_n(a,x.date))?.endTime??C.endTime;return b&&(!N||Vt(b)>Vt(N))?b:N},void 0));let f=Object.values(i),g=Object.assign({},...f.map(N=>(N.events??[]).map(C=>{let{scheduleTiming:O}=Sa({tournamentRecord:N,event:C});return{[C.eventId]:{event:C,scheduleTiming:O}}})).flat()),h=Ou({sortDateMatchUps:!1,tournamentRecords:i,matchUpFilters:{scheduledDate:a,venueIds:u}}),S=h?.dateMatchUps??[],T=h?.completedMatchUps??[],A=[];A.push(...S),A.push(...T);let D={averageTimes:[{minutes:{default:r}}],recoveryTimes:[{minutes:{default:e}}]},y=A?.map(({eventId:N,schedule:C,matchUpFormat:O})=>{let{event:b,scheduleTiming:x}=g[N],w=b?.eventType,F={...x,defaultTiming:D,matchUpFormat:O},{averageMinutes:L,recoveryMinutes:v}=dp({eventType:w,timingDetails:F}),{courtId:B,venueId:H}=C,j=$t(C.scheduledTime),V=br(j,L);return{recoveryMinutes:v,averageMinutes:L,periodLength:s,startTime:j,endTime:V,courtId:B,venueId:H}}),E={calculateStartTimeFromCourts:t,remainingScheduleTimes:n,averageMatchUpMinutes:r,date:a,clearScheduleDates:o,periodLength:s,startTime:c,endTime:p,bookings:y,courts:l},{scheduleTimes:U}=Kd(E),M=u?.length===1&&u[0]||d?.length===1&&d[0].venueId||void 0,P=A.map(fe);return{venueId:M,scheduleTimes:U,dateScheduledMatchUpIds:P}}function CM(t){let e=lt(t,[{[ye]:!0}]);if(e.error)return e;let{removePriorValues:r,tournamentRecords:n,tournamentId:o,courtDayDate:i,matchUpId:s,courtId:a,drawId:c}=t,u=n[o];if(!u)return{error:W};let{drawDefinition:p,event:m}=Po({tournamentRecord:u,drawId:c});if(!p)return{error:X};let d=xt({drawDefinition:p,event:m,matchUpId:s});if(d.error)return d;if(d?.matchUp?.matchUpType===ln){let{itemValue:l}=vo({timeItems:d.matchUp.timeItems??[],itemType:Eo}),f=a&&l.filter(I=>I.courtId!==a);return rn({duplicateValues:!1,removePriorValues:r,tournamentRecord:u,drawDefinition:p,matchUpId:s,timeItem:{itemType:Eo,itemValue:f}})}else return Hi({tournamentRecord:u,drawDefinition:p,courtDayDate:i,courtId:"",matchUpId:s})}function RM({scheduleCompletedMatchUps:t,tournamentRecords:e,scheduledDate:r,matchUps:n}){if(!Ur(n))return{error:G};if(n.some(({hasContext:g})=>!g))return{info:"matchUps must have { inContext: true, nextMatchUps: true }",error:Gc};let i=Ou({courtCompletedMatchUps:!0,withCourtGridRows:!0,minCourtGridRows:10,tournamentRecords:e,matchUpFilters:{localPerspective:!0,scheduledDate:r}});if(i.error)return i;let{rows:s}=i,a=[],c=g=>[(g.sides||[]).map(I=>[I.participantId,I.participant?.individualParticipantIds]),(g.potentialParticipants||[]).flat().map(I=>[I.participantId,I.individualParticipantIds])].flat(1/0).filter(Boolean),u=s?.reduce((g,I)=>{let h=[],S=[];Object.values(I).forEach(A=>{if(Rt(A)&&(A.matchUpId&&(h.push(A.matchUpId),a.push(A)),A.sides)){let D=c(A);S.push(...D)}});let T=Object.values(I).filter(A=>Rt(A)&&!A.matchUpId);return g.concat({matchUpIds:h,availableCourts:T,rowId:I.rowId,participantIds:S})},[]);n.filter(({matchUpStatus:g})=>g&&g!==Dt&&(t||!ae.includes(g))).sort(hi);let p=Vr({matchUps:n.concat(a),includeParticipantDependencies:!0,tournamentRecords:e}).matchUpDependencies,m=[],d=[];for(;n.length&&u.length;){let g=u.shift(),I=[];for(;n.length&&g.availableCourts.length;){let h=n.concat(I).map(P=>P.matchUpId),S=n.shift(),T=S?.matchUpId,A=T&&p[T].matchUpIds.concat(p[T].dependentMatchUpIds),D=T&&h.some(P=>p[T].matchUpIds.includes(P)),y=T&&d.some(P=>p[T].dependentMatchUpIds.includes(P)),E=g.matchUpIds.some(P=>A.includes(P)),U=c(S),M=g.participantIds.some(P=>U.includes(P));if(S&&!E&&!D&&!M&&!y){let P=g.availableCourts.shift();Object.assign(S.schedule,P.schedule),Object.assign(P,S),m.push(S),g.participantIds.push(...U),g.matchUpIds.push(T)}else S&&I.push(S)}n.push(...I),d.push(...g.matchUpIds)}let l=m.map(({matchUpId:g,tournamentId:I,schedule:h,drawId:S})=>({tournamentId:I,matchUpId:g,drawId:S,schedule:{...h,scheduledDate:r}}));return i=_c({tournamentRecords:e,matchUpDetails:l}),{...i,scheduled:m,notScheduled:n}}function bM(t){let{courtDayDate:e}=t,r=lt(t,[{courtAssignments:!0,[to]:Er,[En]:et},{[ye]:!0}]);if(r.error)return r;let n=t.courtAssignments.reduce((s,a)=>{let{tournamentId:c}=a;return s[c]||(s[c]=[]),s[c].push(a),s},{}),o;return Object.keys(n).every(s=>{let a=t[ye][s];if(!a)return o={error:W},!1;let c=n[s].reduce((p,m)=>{let{drawId:d}=m;return p[d]||(p[d]=[]),p[d].push(m),p},{});Object.keys(c).every(p=>{let{drawDefinition:m}=We({tournamentRecord:a,drawId:p});return m?(c[p].every(d=>{let{matchUpId:l,courtId:f}=d,g=Hi({tournamentRecord:a,drawDefinition:m,courtDayDate:e,matchUpId:l,courtId:f});if(g.success)return g?.success;o={error:zy}}),!0):(o={error:X},!1)})}),o||R}function OM(t){let{tournamentRecords:e,allDateMatchUpIds:r=[],averageMatchUpMinutes:n=90,recoveryMinutes:o=0,recoveryMinutesMap:i,matchUpPotentialParticipantIds:s={},individualParticipantProfiles:a={},matchUpNotBeforeTimes:c={},matchUpDailyLimits:u={},checkPotentialRequestConflicts:p=!0,remainingScheduleTimes:m,clearScheduleDates:d,periodLength:l=30,scheduleDate:f,matchUpIds:g,venueIds:I,startTime:h,endTime:S,dryRun:T}=t,A=lt(t,[{[ye]:!0,[Xa]:!0},{[yn]:Rr,[En]:ar,[JC]:!0},{[yn]:k=>!k||!isNaN(k),[rR]:!1,[En]:G,[nR]:!1,[oR]:!1}]);if(A.error)return A;let D=t.competitionMatchUps??cn({nextMatchUps:!0,tournamentRecords:e}).matchUps??[],y=t.matchUpDependencies??Vr({includeParticipantDependencies:!0,matchUps:D,tournamentRecords:e}).matchUpDependencies;D.forEach(k=>{k.schedule?.scheduledDate&&_n(f,Ut(k.schedule.scheduledDate))&&ta({matchUpPotentialParticipantIds:s,matchUpNotBeforeTimes:c,matchUp:k})});let E=g.map(k=>D.find(K=>K.matchUpId===k)).filter(Boolean),{venueId:U,scheduleTimes:M,dateScheduledMatchUpIds:P}=Kg({tournamentRecords:e,remainingScheduleTimes:m,startTime:$t(h),endTime:$t(S),scheduleDate:Ut(f),averageMatchUpMinutes:n,clearScheduleDates:d,periodLength:l,venueIds:I}),N={},C=[],O={},b={},x={};D.filter(({matchUpId:k})=>P?.includes(k)).forEach(k=>{Vg({matchUpPotentialParticipantIds:s,individualParticipantProfiles:a,matchUp:k,value:1});let K=k.schedule?.scheduledTime;if(K){O[k.matchUpId]=K;let z=i?.[k.matchUpId];bc({recoveryMinutes:z||o,matchUpPotentialParticipantIds:s,individualParticipantProfiles:a,matchUpNotBeforeTimes:c,averageMatchUpMinutes:n,matchUpDependencies:y,scheduleTime:K,matchUp:k})}});let F=E.filter(k=>{let K=P?.includes(k.matchUpId),z=[Dt,Ot,me,$r,lr,_t].includes(k?.matchUpStatus);return!K&&!k.winningSide&&!z}),{matchUpMap:L,overLimitMatchUpIds:v,participantIdsAtLimit:B}=F.reduce((k,K)=>{let{drawId:z,tournamentId:q,matchUpType:nt}=K,{participantIdsAtLimit:Q,relevantParticipantIds:it}=nl({individualParticipantProfiles:a,matchUpPotentialParticipantIds:s,matchUpDailyLimits:u,matchUp:K});return Q?.length?(k.overLimitMatchUpIds.push(K.matchUpId),k.participantIdsAtLimit.push(...Q),k):(it.forEach(ot=>{Fa({individualParticipantProfiles:a,participantId:ot});let ut=a[ot].counters;ut[nt]?ut[nt]+=1:ut[nt]=1,ut[$n]?ut[$n]+=1:ut[$n]=1}),k.matchUpMap[q]||(k.matchUpMap[q]={}),k.matchUpMap[q][z]?k.matchUpMap[q][z].push(K):k.matchUpMap[q][z]=[K],ta({matchUpPotentialParticipantIds:s,matchUpNotBeforeTimes:c,matchUp:K}),k)},{matchUpMap:{},overLimitMatchUpIds:[],participantIdsAtLimit:[]});F=F.filter(({matchUpId:k})=>!v.includes(k));let H=0,j=M?.length??0,{personRequests:V}=yi({tournamentRecords:e,requestType:Oc});for(;M?.length&&F.length&&H<=j;){H++;let{scheduleTime:k}=M.shift(),K=F.find(z=>{let{matchUpId:q}=z,{dependenciesScheduled:nt,remainingDependencies:Q}=tl({matchUpScheduleTimes:O,matchUpDependencies:y,allDateMatchUpIds:r,matchUp:z});if(!nt)return x[q]||(x[q]=[]),x[q].push({scheduleTime:k,remainingDependencies:Q}),!1;let{enoughTime:it}=rl({individualParticipantProfiles:a,matchUpNotBeforeTimes:c,matchUpDependencies:y,scheduleTime:k,matchUp:z});if(!it)return b[q]||(b[q]=[]),b[q].push({scheduleTime:k}),!1;let{conflicts:ot}=el({potentials:p,averageMatchUpMinutes:n,requestConflicts:N,personRequests:V,scheduleTime:k,scheduleDate:f,matchUp:z});if(ot?.length)return!1;let ut=i?.[z.matchUpId];return bc({recoveryMinutes:ut||o,matchUpPotentialParticipantIds:s,individualParticipantProfiles:a,matchUpNotBeforeTimes:c,averageMatchUpMinutes:n,matchUpDependencies:y,scheduleTime:k,matchUp:z}),O[z.matchUpId]=k,!0});F=F.filter(({matchUpId:z})=>z!==K?.matchUpId),K||C.push(k)}F.forEach(k=>{Vg({individualParticipantProfiles:a,matchUpPotentialParticipantIds:s,value:-1,matchUp:k})});let Y=[];Object.keys(L).forEach(k=>{let K=e[k];K&&Object.keys(L[k]).forEach(z=>{let{drawDefinition:q}=Po({tournamentRecord:K,drawId:z});q&&L[k][z].forEach(({matchUpId:Q})=>{let it=O[Q];if(it){let ot=it.split(":").map(Hn).join(":"),ut=`${Ut(f)}T${ot}`;T?Y.push(Q):(Vo({drawDefinition:q,matchUpId:Q,scheduledTime:ut}).success&&Y.push(Q),U&&Zs({tournamentRecords:e,tournamentRecord:K,drawDefinition:q,matchUpId:Q,venueId:U}))}})})});let $=Dm(F);return{...R,requestConflicts:Object.values(N),remainingScheduleTimes:M?.map(({scheduleTime:k})=>k),individualParticipantProfiles:a,matchUpNotBeforeTimes:c,participantIdsAtLimit:B,skippedScheduleTimes:C,overLimitMatchUpIds:v,scheduledMatchUpIds:Y,noTimeMatchUpIds:$,recoveryTimeDeferred:b,dependencyDeferred:x}}function _M({tournamentRecords:t,matchUps:e}){if(!Ur(e))return{error:Sn};if(e.some(({matchUpId:f,hasContext:g})=>f&&!g))return{info:"matchUps must have { inContext: true, nextMatchUps: true }",error:Gc};let r=Math.max(...e.map(({schedule:f})=>f?.courtOrder||1).map(f=>ct(f))),n=Z(1,r+1).map(f=>e.filter(g=>ct(g.schedule?.courtOrder)===f)),o={},i={},s={};n.flat().filter(Boolean).sort(hi).forEach(({schedule:f})=>delete f[_f]);let c=pt(e.map(({drawId:f})=>f)),u=Vr({includeParticipantDependencies:!0,tournamentRecords:t,drawIds:c}).matchUpDependencies,p=n.map((f,g)=>f.reduce((I,h)=>{if(!h.matchUpId)return I;let{matchUpId:S,winnerMatchUpId:T,loserMatchUpId:A,schedule:D,sides:y,potentialParticipants:E}=h,U=D?.courtId;o[S]=g,i[U]=[],I.matchUpIds.push(S),s[S]=h;let M=u[S].matchUpIds;M.length&&I.sourceMatchUpIds.push(...M);let P=y?.map(C=>[C.participant?.individualParticipantIds,C.participantId]).flat().filter(Boolean)??[],N=E?.flat().map(({individualParticipantIds:C,participantId:O})=>[C,O]).flat().filter(Boolean)||[];return I.participantIds.push(...N,...P),T&&I.targetMatchUpIds.push(T),A&&I.targetMatchUpIds.push(A),I},{sourceMatchUpIds:[],targetMatchUpIds:[],participantIds:[],matchUpIds:[]})),m=(f,g)=>u[f].sources.reduce((I,h,S)=>h.includes(g)&&S+1||I,0),d=p.map(()=>[]),l=(f,g,I,h)=>{if(!s[f].schedule[_f]){s[f].schedule[_f]=g,s[f].schedule[nU]=h,d[o[f]].push({matchUpId:f,issueType:I,issueIds:h,issue:g});let S=s[f].schedule.courtId;i[S]||(i[S]=[]),i[S].push({matchUpId:f,issue:g,issueType:I,issueIds:h})}};return p.forEach((f,g)=>{let I=g?p[g-1]:void 0,h=p.slice(g+1),S={},T=dr(f.participantIds),A=Object.keys(T).filter(E=>T[E]>1),D=f.matchUpIds.filter(E=>u[E].participantIds.some(U=>A.includes(U)));D.forEach(E=>{S[E]||(S[E]={}),S[E][cc]||(S[E][cc]=D.filter(U=>U!==E))});let y=I&&f.participantIds.filter(E=>I.participantIds.includes(E));y&&y.forEach(E=>{let U=f.matchUpIds.concat(I.matchUpIds).filter(M=>u[M].participantIds.includes(E));U.forEach(M=>{S[M]||(S[M]={}),S[M][uc]||(S[M][uc]=U.filter(P=>P!==M))})}),f.matchUpIds.forEach(E=>{let U=u[E].matchUpIds;for(let P of h){let N=P.matchUpIds.filter(C=>U.includes(C));N?.length&&(N.forEach(C=>l(C,lh,Ta,[E])),l(E,lh,Ta,N))}if(S[E]?.[cc]&&l(E,cc,dh,S[E][cc]),f.sourceMatchUpIds.includes(E)){let P=f.matchUpIds.filter(N=>u[N].matchUpIds.includes(E));l(E,cc,Ta,P),f.matchUpIds.filter(N=>u[N].matchUpIds.includes(E)).forEach(N=>l(N,cc,Ta,[E]))}let M=I?.matchUpIds?.filter(P=>m(E,P)>1);if(M?.length&&(l(E,fh,Ta,M),M.forEach(P=>l(P,fh,Ta,[E]))),S[E]?.[uc]&&l(E,uc,dh,S[E][uc]),I?.targetMatchUpIds?.includes(E)){let P=s[E].schedule.courtId,N=U.filter(O=>I.matchUpIds.includes(O));N.some(O=>s[O].schedule.courtId===P)||(N.forEach(O=>l(O,uc,Ta,[E])),l(E,uc,Ta,N))}})}),{courtIssues:i,rowIssues:d}}function vM(t){let e="reorderUpcomingMatchUps",{tournamentRecords:r}=t;if(typeof r!="object"||!Object.keys(r).length)return _({result:{error:Ft},stack:e});let{matchUpsContextIds:n,firstToLast:o}=t;if(!n)return _({result:{error:et},stack:e});let i=n?.length;if(!i)return{...R};let s=0;return n.forEach((c,u)=>{let{tournamentId:p,drawId:m,matchUpId:d}=c,l=u+(o?-1:1);l<0&&(l=i-1),l===i&&(l=0);let f=n[l].schedule.scheduledTime,g=a({tournamentId:p,scheduledTime:f,matchUpId:d,drawId:m});if(g.success)s++;else return g}),s===i?R:_({result:{error:Ky},stack:e});function a({tournamentId:c,scheduledTime:u,matchUpId:p,drawId:m}){let d=r[c],{drawDefinition:l}=Po({tournamentRecord:d,drawId:m});return l?Vo({drawDefinition:l,scheduledTime:u,matchUpId:p}):{error:pr}}}function xM(t){let{scheduleChange:e,matchUpIds:r,dryRun:n}=t;if(!r||!Array.isArray(r))return{error:ia};if(typeof e!="object")return{error:G};let o=Xr(t),i=[],s=[];for(let c of Object.values(o)){let u=e1({tournamentRecord:c,scheduleChange:e,matchUpIds:r,dryRun:n});if(u.error)return u;Array.isArray(u.notRescheduled)&&s.push(...u.notRescheduled);let p=Dm(u.notRescheduled),m=[];u.rescheduled?.forEach(d=>{let{matchUpId:l}=d;p.includes(l)&&m.push(l),i.push(d)}),m.length&&(s=u?.notRescheduled?.filter(({matchUpId:d})=>!m.includes(d))||[])}let a=!!(i.length&&!s.length);return{...R,rescheduled:i,notRescheduled:s,allRescheduled:a}}function e1({tournamentRecord:t,scheduleChange:e,matchUpIds:r,dryRun:n}){if(!t)return{error:W};if(!r||!Array.isArray(r))return{error:ia};if(typeof e!="object")return{error:G};let o=[],i=[],{minutesChange:s,daysChange:a}=e;if(!s&&!a)return{...R};if(s&&isNaN(s))return{error:G};if(a&&isNaN(a))return{error:G};let{matchUps:c}=le({matchUpFilters:{matchUpIds:r},tournamentRecord:t}),u=({matchUpStatus:A})=>!ae.includes(A),p=c?.filter(A=>va({schedule:A.schedule})).filter(A=>u({matchUpStatus:A.matchUpStatus}));if(!p?.length)return{...R};let{tournamentInfo:m}=gs({tournamentRecord:t}),{startDate:d,endDate:l}=m,f=p?.reduce((A,D)=>{let{matchUpId:y,drawId:E}=D;return A[E]?A[E].push(y):A[E]=[y],A},{}),g=1440;for(let A of Object.keys(f)){let D=Po({tournamentRecord:t,drawId:A});if(D.error)return D;let y=D.drawDefinition,E=f[A].filter(U=>r.includes(U));for(let U of E)if(U&&y){let P=p.find(w=>w.matchUpId===U)?.schedule,{scheduledTime:N,scheduledDate:C}=P,O,b,x;if(!O&&a&&C){let w=Ut(C);x=tp(w,a),O=new Date(x)<new Date(d)||new Date(x)>new Date(l)}if(s&&N){let w=Ut(N),L=Vt($t(N))+s;if(O=L<0||L>g,!O){let v=br(N,s),B=w&&x||C===w&&w;b=B?`${B}T${v}`:v}}if(O)i.push(U);else{if(!n){if(b){let w=Vo({scheduledTime:b,drawDefinition:y,matchUpId:U});if(w.error)return w}if(x){let w=Zd({scheduledDate:x,drawDefinition:y,matchUpId:U});if(w.error)return w}}(b||x)&&o.push(U)}}}let I=le({matchUpFilters:{matchUpIds:r},tournamentRecord:t}).matchUps??[],h=I.filter(({matchUpId:A})=>o.includes(A)),S=I.filter(({matchUpId:A})=>i.includes(A)),T=h.length&&!S.length;return{...R,rescheduled:h,notRescheduled:S,allRescheduled:T}}function wM(t){let e="matchUpScheduleChange",{tournamentRecords:r}=t;if(typeof r!="object"||!Object.keys(r).length)return{error:Ft};let{sourceMatchUpContextIds:n,targetMatchUpContextIds:o,sourceCourtId:i,targetCourtId:s,courtDayDate:a}=t||{},{drawId:c,matchUpId:u,tournamentId:p}=n||{},{drawId:m,matchUpId:d,tournamentId:l}=o||{};if(!u&&!d)return _({result:{error:et},stack:e});let{matchUps:f}=cn({matchUpFilters:{matchUpIds:[u,d].filter(Boolean),drawIds:[c,m].filter(Boolean)},tournamentRecords:t.tournamentRecords}),g=f?.find(({matchUpId:A})=>A===u),I=f?.find(({matchUpId:A})=>A===d),h=0;if(s&&u&&!d){let A=S({tournamentId:p,matchUpId:u,courtId:s,matchUp:g,drawId:c,tournamentRecords:r,sourceCourtId:i,courtDayDate:a});if(A?.success&&h++,A.error)return _({result:A,stack:e})}else if(i&&s&&u&&d){let A=S({tournamentId:p,matchUpId:u,courtId:s,matchUp:g,drawId:c,tournamentRecords:r,sourceCourtId:i,courtDayDate:a});if(A.success&&h++,A.error)return _({result:A,stack:e,info:"source"});let D=S({tournamentId:l,sourceCourtId:s,matchUpId:d,matchUp:I,courtId:i,drawId:m,tournamentRecords:r,courtDayDate:a});if(D.success&&h++,D.error)return _({result:D,stack:e,info:"target"})}else return{error:et};return h?R:_({result:{error:Ns},stack:e});function S(A){let{tournamentRecords:D,tournamentId:y,matchUp:E,drawId:U}=A,M=D[y],{drawDefinition:P}=Po({tournamentRecord:M,drawId:U});return E.matchUpType===Bt?T({...A,tournamentRecord:M,drawDefinition:P}):Hi({...A,tournamentRecord:M,drawDefinition:P})}function T({removePriorValues:A,tournamentRecords:D,tournamentRecord:y,drawDefinition:E,sourceCourtId:U,courtDayDate:M,matchUpId:P,matchUp:N,courtId:C}){let O=[C].concat(N.schedule.allocatedCourts.map(({courtId:b})=>b).filter(b=>b!==U));return $p({removePriorValues:A,tournamentRecords:D,tournamentRecord:y,drawDefinition:E,courtDayDate:M,matchUpId:P,courtIds:O})}}function LM({scheduleAttributes:t=[Eo,di,xs,ws,Ls,Uo,fi,li,xi],tournamentRecord:e,drawDefinition:r,matchUpId:n}){let o="clearMatchUpSchedule",i=r?rr({matchUpFilters:{matchUpIds:[n]},inContext:!1,drawDefinition:r}).matchUps?.[0]:le({matchUpFilters:{matchUpIds:[n]},tournamentRecord:e,inContext:!1}).matchUps?.[0];if(!i)return{error:Oe};let s=(i.timeItems??[]).filter(a=>a?.itemType&&!t.includes(a?.itemType));return i.timeItems=s,It({tournamentId:e.tournamentId,context:o,drawDefinition:r,matchUp:i}),{...R}}function FM(t){let{tournamentRecord:e,tournamentId:r,dailyLimits:n}=t,o=t.tournamentRecords||e&&{[e.tournamentId]:e}||{};if(typeof o!="object"||!Object.keys(o).length)return{error:Ft};if(typeof n!="object")return{error:Xn};let i=Object.keys(o).filter(s=>!r||r===s);if(r&&!i.includes(r))return{error:G};for(let s of i){let a=o[s],c=St({element:a,extension:{name:Yc,value:{dailyLimits:n}}});if(c.error)return c}return{...R}}var zM={};Jt(zM,{addCollectionDefinition:()=>Xg,addCollectionGroup:()=>jM,aggregateTieFormats:()=>$M,compareTieFormats:()=>Go,getTieFormat:()=>NT,modifyCollectionDefinition:()=>zg,modifyTieFormat:()=>qM,mutate:()=>KM,orderCollectionDefinitions:()=>WM,query:()=>LD,removeCollectionDefinition:()=>Qg,removeCollectionGroup:()=>BM,tieFormatGenderValidityCheck:()=>pd,validateCollectionDefinition:()=>yu});var KM={};Jt(KM,{addCollectionDefinition:()=>Xg,addCollectionGroup:()=>jM,aggregateTieFormats:()=>$M,modifyCollectionDefinition:()=>zg,modifyTieFormat:()=>qM,orderCollectionDefinitions:()=>WM,removeCollectionDefinition:()=>Qg,removeCollectionGroup:()=>BM});function ei({drawDefinition:t,structureId:e,matchUpId:r,structure:n,matchUp:o,eventId:i,event:s}){let a="getTieFormat",c;if(e=n?.structureId??e,r=o?.matchUpId??r,(r||e)&&!t)return{error:X};if(i&&s)c=Gs(s);else if(r){if(t&&(!o||!n)){let u=xt({drawDefinition:t,matchUpId:r});if(u.error)return u;if(u.matchUp?.matchUpType!==ln)return _({result:{error:Je},stack:a});n||(n=u.structure),o||(o=u.matchUp)}c=fp({item:o,drawDefinition:t,structure:n,event:s})||fp({item:n,drawDefinition:t,structure:n,event:s})||Gs(t)||Gs(s)}else if(t&&e){if(!n){let u=st({drawDefinition:t,structureId:e});if(u.error)return u;n=u?.structure}c=fp({item:n,drawDefinition:t,structure:n,event:s})||Gs(t)||Gs(s)}else c=Gs(t)||Gs(s);return c?{...R,structure:n,tieFormat:c,matchUp:o}:_({result:{error:qa},stack:a})}function al({matchUp:t,updateInProgressMatchUps:e}){return!t.winningSide&&![ae].includes(t.matchUpStatus)&&(e||t.matchUpStatus!==Dn&&!Ie(t))}function VM({from:t,to:e}){let r=Object.keys(t),n=jt(r,Object.keys(e)).length===r.length,i=r.filter(c=>t[c]!==e[c]).map(c=>({countChange:e[c]-t[c],collectionId:c})),s=r.every(c=>t[c]===e[c]);return{equivalent:n&&s,matchUpsCountChanges:i}}function Px({updateInProgressMatchUps:t,tournamentRecord:e,drawDefinition:r,structure:n,tieFormat:o,eventId:i,matchUp:s,event:a,uuids:c}){let u="updateTieFormat",p=e?.tournamentId,m=0,d=0,l=0,f=0,g=o?.collectionDefinitions.reduce((y,E)=>(y[E.collectionId]=(y[E.collectionId]||0)+E.matchUpCount,y),{}),I=({tieFormat:y})=>{let E=y?.collectionDefinitions.reduce((U,M)=>(U[M.collectionId]=(U[M.collectionId]||0)+M.matchUpCount,U),{});return VM({from:E,to:g}).equivalent},h=ei({drawDefinition:r})?.tieFormat,S=ei({event:a})?.tieFormat;if(a&&i){for(let y of a.drawDefinitions??[])T({drawDefinition:y});a.tieFormat=Xe(o),f+=1}else if(s){if(!s.tieMatchUps)return _({result:{error:Je},stack:u});let y=dr(s.tieMatchUps?.map(({collectionId:N})=>N)),E=VM({to:g,from:y}),{changes:U,changesArePossible:M,cannotChangeReaon:P}=Ux({matchUp:s,check:E});if(E.equivalent)if(al({matchUp:s,updateInProgressMatchUps:t}))s.tieFormat=Xe(o),f+=1;else return _({result:{error:Pl},info:"matchUp is IN_PROGRESS or COMPLETE",stack:u});else if(M)D({tieFormat:o,matchUp:s,changes:U,uuids:c});else return _({context:{collectionMap:g,matchUpMap:y},result:{error:ni},info:P||"specified changes not possible",stack:u});d+=1,It({eventId:a?.eventId,context:u,drawDefinition:r,tournamentId:p,matchUp:s})}else if(n){let E=A({inheritedTieFormat:h??S,structure:n})?.modifiedMatchUpsCount;E&&(d+=E,m+=1,f+=1);let U=!n.tieFormat||Go({ancestor:n.tieFormat,descendant:o}).different;U&&(n.tieFormat=Xe(o),m+=1,f+=1),(E||U)&&r&&bt({structureIds:[n.structureId],eventId:a?.eventId,drawDefinition:r})}else if(r)T({drawDefinition:r}),r.tieFormat=Xe(o),f+=1;else return{error:X};return{modifiedStructuresCount:m,modifiedMatchUpsCount:d,addedMatchUpsCount:l,modifiedCount:f,...R,tieFormat:o};function T({drawDefinition:y}){let E=y.structures||[],U=[];for(let M of E){if(M.tieFormat)continue;let N=A({inheritedTieFormat:S,structure:M})?.modifiedMatchUpsCount;if(N){m+=1,d+=N;let C=M.structureId;U.push(C)}}return bt({structureIds:U,eventId:a?.eventId,drawDefinition:y}),U.length}function A({inheritedTieFormat:y,structure:E}){let U=0,M=At({matchUpFilters:{matchUpTypes:[Bt]},structure:E})?.matchUps||[];for(let P of M){let N=al({matchUp:P,updateInProgressMatchUps:t}),C=!1,O=dr(P.tieMatchUps?.map(({collectionId:x})=>x)),b=VM({from:O,to:g});if(b.equivalent)P.tieFormat&&I(P)&&N&&(P.tieFormat=Xe(o),C=!0);else{let{changes:x,changesArePossible:w}=Ux({matchUp:P,check:b});if(w&&!P.tieFormat)D({changes:x,matchUp:P,tieFormat:o,uuids:c});else if(y)(!P.tieFormat||Go({ancestor:y,descendant:P.tieFormat}).different)&&(P.tieFormat=y,C=!0);else return _({result:{error:qa},stack:u})}C&&(U+=1,It({tournamentId:e?.tournamentId,drawDefinition:r,context:u,eventId:i,matchUp:P}))}return{modifiedMatchUpsCount:U}}function D({uuids:y,matchUp:E,tieFormat:U,changes:M}){E.tieFormat=Xe(U);let P=[],N=[];return M.forEach(C=>{if(C.countChange>0){let O=Math.max(0,...E.tieMatchUps.filter(w=>w.collectionId===C.collectionId).map(Pr("collectionPosition"))),b=U.collectionDefinitions.find(w=>w.collectionId===C.collectionId),x=hu({matchUpsLimit:C.countChange,collectionPositionOffset:O,collectionDefinition:b,matchUp:E,uuids:y});N.push(...J(x,!1,!0)),l+=N.length,E.tieMatchUps.push(...x)}else{let O=C.toBePlayedTieMatchUpIds.slice(0,Math.abs(C.countChange));console.log("remove",O.length),P.push(...O),E.tieMatchUps=E.tieMatchUps.filter(({matchUpId:b})=>!O.includes(b))}}),N.length&&So({matchUps:N,drawDefinition:r,tournamentId:p,eventId:i}),P.length&&wn({matchUpIds:P,action:"updateTieFormat",drawDefinition:r,tournamentId:p,eventId:i}),{matchUpIdsRemoved:P,matchUpsAdded:N}}}function Ux({check:t,matchUp:e}){let r="",n=[];return{changesArePossible:t.matchUpsCountChanges.every(({collectionId:i,countChange:s})=>{let a=e.tieMatchUps.filter(u=>u.collectionId===i&&u.matchUpStatus===zt).map(Pr("matchUpId")),c=a.length+s>=0||s>0;return!c&&s<0&&(r="Insufficient TO_BE_PLAYED matchUps"),n.push({toBePlayedTieMatchUpIds:a,collectionId:i,countChange:s}),c}),changes:n,cannotChangeReaon:r}}function Lu({drawDefinition:t,auditData:e}){let{extension:r}=mt({name:Qi,element:t}),n={name:Qi,value:Array.isArray(r?.value)?r?.value.concat(e):[e]};St({element:t,extension:n})}function zg({updateInProgressMatchUps:t=!1,tournamentRecord:e,collectionOrder:r,collectionName:n,tieFormatName:o,drawDefinition:i,matchUpFormat:s,matchUpCount:a,collectionId:c,matchUpType:u,structureId:p,matchUpId:m,category:d,eventId:l,gender:f,event:g,collectionValueProfiles:I,collectionValue:h,matchUpValue:S,scoreValue:T,setValue:A}){let D="modifyCollectionDefinition";if(s&&!Sr({matchUpFormat:s}))return _({result:{error:G},context:{matchUpFormat:s},stack:D});if(n&&typeof n!="string")return _({result:{error:G},context:{collectionName:n},stack:D});if(f&&!Object.values(Km).includes(f))return _({result:{error:G},context:{gender:f},stack:D});if(d&&typeof d!="object")return _({result:{error:G},context:{category:d},stack:D});let y={collectionValueProfiles:I,collectionValue:h,matchUpValue:S,scoreValue:T,setValue:A};if(!Object.values(y).filter(Boolean).length&&!r&&!n&&!s&&!a&&!u)return _({result:{error:et},stack:D});if(Object.values(y).filter(Boolean).length>1)return _({info:"Only one value assignment allowed per collectionDefinition",result:{error:G},stack:D});let E=ei({drawDefinition:i,structureId:p,matchUpId:m,eventId:l,event:g});if(E.error)return _({result:E,stack:D});let{matchUp:U,structure:M,tieFormat:P}=E,N=Xe(P),C=P?.collectionDefinitions.find(Y=>Y.collectionId===c),O=N?.collectionDefinitions.find(Y=>Y.collectionId===c);if(!C)return _({info:"source collectionDefinition",result:{error:Ke},context:{collectionId:c},stack:D});let b=h??S??T??A;if(I){let Y=aS({matchUpCount:a??C?.matchUpCount??0,collectionValueProfiles:I});if(Y.errors)return _({result:{error:G},info:Y.errors,stack:D})}else if(b&&!ft(b))return _({result:{error:G},info:"value is not an integer",context:{value:b},stack:D});let x=(Y,$)=>jt(Object.keys(Y),Object.keys($)).length===Object.keys(Y).length&&jt(Object.values(Y),Object.values($)).length===Object.values(Y).length,w=I&&(!C.collectionValueProfiles||!x(C.collectionValueProfiles,I)),F=ft(h)&&C.collectionValue!==h||ft(S)&&C.matchUpValue!==S||ft(T)&&C.scoreValue!==T||ft(A)&&C.setValue!==A||w,L=[];if(F&&(O.collectionValueProfiles=void 0,O.collectionValue=void 0,O.matchUpValue=void 0,O.scoreValue=void 0,O.setValue=void 0,Object.assign(O,y),L.push({collectionId:c,...rt(y)})),(ft(T)||ft(A))&&O.collectionGroupNumber){let Y=O.collectionGroupNumber;N.collectionDefinitions=N.collectionDefinitions.map($=>{let{collectionGroupNumber:k,...K}=$;return k===Y?K:$}),N.collectionGroups=N.collectionGroups.filter(({groupNumber:$})=>$!==Y),L.push({collectionId:c,change:"collectionGroupNumber removed"})}let{aggregateValue:v,valueGoal:B}=Is(N),H=rt({aggregateValue:v,valueGoal:B});if((H.aggregateValue!==P?.winCriteria.aggregateValue||H.valueGoal!==P?.winCriteria.valueGoal)&&(N.winCriteria=H,L.push({collectionId:c,winCriteria:H})),ft(r)&&C.collectionOrder!==r&&(O.collectionOrder=r,L.push({collectionId:c,collectionOrder:r})),n&&C.collectionName!==n&&(O.collectionName=n,L.push({collectionId:c,collectionName:n})),s&&C.matchUpFormat!==s&&(O.matchUpFormat=s,L.push({collectionId:c,matchUpFormat:s})),ft(a)&&C.matchUpCount!==a&&(O.matchUpCount=a,L.push({collectionId:c,matchUpCount:a})),u&&C.matchUpType!==u)return _({result:{error:$u},context:{matchUpType:u},stack:D});d&&C.category!==d&&(O.category=d,L.push({collectionId:c,category:d})),f&&C.gender!==f&&(O.gender=f,L.push({collectionId:c,gender:f}));let j=rt(N);if(E=ir({tieFormat:j}),E.error)return _({result:E,stack:D});if(!L.length)return _({result:{...R,modifications:L}});if(P?.tieFormatName!==o?(j.tieFormatName=o,L.push({tieFormatName:o})):L.length&&(delete j.tieFormatName,L.push("tieFormatName removed: modifications without new tieFormatName")),E=Px({tieFormat:j,updateInProgressMatchUps:t,tournamentRecord:e,drawDefinition:i,structure:M,eventId:l,matchUp:U,event:g}),!E.error){let{appliedPolicies:Y}=Pt({tournamentRecord:e});if(Y?.audit?.[Qi]){let $=rt({collectionDefinition:O,drawId:i?.drawId,action:D,structureId:p,matchUpId:m,eventId:l});Lu({drawDefinition:i,auditData:$})}}return _({result:{...E,modifications:L},stack:D})}function Dx({updateInProgressMatchUps:t,drawDefinition:e,structureId:r,structure:n,matchUpId:o,matchUp:i}){let s=[];return o&&i?s=[i]:r&&n?s=At({matchUpFilters:{matchUpTypes:[Bt]},structure:n})?.matchUps??[]:e&&(s=rr({matchUpFilters:{matchUpTypes:[Bt]},drawDefinition:e})?.matchUps??[]),{targetMatchUps:s.filter(c=>!c.winningSide&&c.matchUpStatus!==me&&(t||c.matchUpStatus!==Dn&&!Ie(c)))}}function Nx({updateInProgressMatchUps:t,tournamentRecord:e,drawDefinition:r,targetMatchUps:n,tieFormat:o,event:i}){for(let s of n){let a=!!s.tieFormat;a&&(s.tieFormat=Xe(o));let c;if(t){let u=Pt({tournamentRecord:e,drawDefinition:r,event:i}).appliedPolicies,p=zn({matchUpId:s.matchUpId,exitWhenNoValues:!0,tournamentRecord:e,appliedPolicies:u,drawDefinition:r,event:i});if(p.error)return p;c=p.score}a&&!c&&It({tournamentId:e?.tournamentId,context:"updateTargetTeamMatchUps",eventId:i?.eventId,matchUp:s,drawDefinition:r})}return{...R}}function HA({updateInProgressMatchUps:t,originalValueGoal:e,tournamentRecord:r,wasAggregateValue:n,tieFormatName:o,drawDefinition:i,structureId:s,structure:a,tieFormat:c,matchUpId:u,matchUp:p,eventId:m,event:d}){let{aggregateValue:l,valueGoal:f}=Is(c);c.winCriteria=rt({aggregateValue:l,valueGoal:f}),(e&&e!==f||l&&!n)&&(o?c.tieFormatName=o:delete c.tieFormatName);let{targetMatchUps:g}=Dx({updateInProgressMatchUps:t,drawDefinition:i,structureId:s,structure:a,matchUpId:u,matchUp:p});Nx({updateInProgressMatchUps:t,tournamentRecord:r,targetMatchUps:g,drawDefinition:i,tieFormat:c,event:d});let I=rt(c),h=ir({tieFormat:I});if(h.error)return h;if(m&&d)d.tieFormat=I;else if(u&&p)p.tieFormat=c;else if(a)a.tieFormat=I;else if(i)i.tieFormat=I;else if(!p||!i)return{error:X};return bt({drawDefinition:i,eventId:d?.eventId}),{...R}}function BM({updateInProgressMatchUps:t=!0,collectionGroupNumber:e,tournamentRecord:r,drawDefinition:n,tieFormatName:o,structureId:i,matchUpId:s,matchUp:a,eventId:c,event:u}){if(!e)return{error:et};if(isNaN(e))return{error:G};let p="removeCollectionGroup",m=a?void 0:ei({drawDefinition:n,structureId:i,matchUpId:s,eventId:c,event:u});if(m?.error)return _({result:m,stack:p});let d=m?.structure;a=a??m?.matchUp;let l=m?.tieFormat,f=l?.winCriteria.valueGoal,g=l?.winCriteria.aggregateValue,I=Xe(l);if(m=ir({tieFormat:I}),m.error)return _({result:m,stack:p});let h=[];if(I.collectionDefinitions=I.collectionDefinitions.map(S=>{let{collectionGroupNumber:T,...A}=S;return T!==e?S:(h.push(S.collectionId),A)}),I.collectionGroups=I.collectionGroups.filter(({groupNumber:S})=>S!==e),m=HA({updateInProgressMatchUps:t,originalValueGoal:f,wasAggregateValue:g,tournamentRecord:r,drawDefinition:n,tieFormatName:o,structureId:i,structure:d,tieFormat:I,matchUpId:s,matchUp:a,eventId:c,event:u}),!m.error){let{appliedPolicies:S}=Pt({tournamentRecord:r});if(S?.audit?.[Qi]){let T=rt({drawId:n?.drawId,collectionGroupNumber:e,action:p,structureId:i,matchUpId:s,eventId:c});Lu({drawDefinition:n,auditData:T})}}return _({result:{...m,modifiedCollectionIds:h},stack:p})}function cl({tieFormat:t,orderMap:e}){let r=Xe(t);return r.collectionDefinitions.forEach(n=>{let o=e[n.collectionId];o&&(n.collectionOrder=o)}),r.collectionDefinitions.sort((n,o)=>Qa(n.collectionOrder)-Qa(o.collectionOrder)),r}function WM({tournamentRecord:t,drawDefinition:e,structureId:r,matchUpId:n,orderMap:o,eventId:i,matchUp:s,event:a}){if(typeof o!="object"||!Object.values(o).every(c=>ft(c)))return _({result:{error:G},context:{orderMap:o}});if(i&&a?.tieFormat)Mx({tournamentRecord:t,event:a,orderMap:o});else if(n){let c=e&&xt({drawDefinition:e,matchUpId:n});if(c?.error)return c;if(s=c.matchUp,!s)return{error:sr};s?.tieFormat&&(s.tieFormat=cl({tieFormat:s.tieFormat,orderMap:o}),It({tournamentId:t?.tournamentId,eventId:a?.eventId,drawDefinition:e,matchUp:s}))}else if(r){let c=st({drawDefinition:e,structureId:r});if(c.error)return c;let u=c.structure;if(u?.tieFormat)u.tieFormat=cl({tieFormat:u.tieFormat,orderMap:o}),Cx({eventId:a?.eventId,tournamentRecord:t,drawDefinition:e,structure:u,orderMap:o}),bt({drawDefinition:e,structureIds:[u.structureId]});else if(e.tieFormat)HM({structureIds:[r],tournamentRecord:t,drawDefinition:e,orderMap:o,event:a});else if(a?.tieFormat)Mx({structureIds:[r],tournamentRecord:t,orderMap:o,event:a});else return{error:Ke}}else if(e?.tieFormat)HM({tournamentRecord:t,drawDefinition:e,orderMap:o,event:a});else return{error:Ke};return{...R}}function Mx({tournamentRecord:t,structureIds:e,orderMap:r,event:n}){let o=cl({tieFormat:n.tieFormat,orderMap:r});e?.length||(n.tieFormat=o);for(let i of n.drawDefinitions??[])HM({tournamentRecord:t,drawDefinition:i,structureIds:e,orderMap:r,event:n})}function HM({tournamentRecord:t,drawDefinition:e,structureIds:r,orderMap:n,event:o}){let i=e.tieFormat??o?.tieFormat,s=cl({tieFormat:i,orderMap:n});r?.length||(e.tieFormat=s);let a=[];for(let c of e.structures??[])r?.length&&!r.includes(c.structureId)||((c.tieFormat||r?.includes(c.structureId))&&(c.tieFormat=cl({tieFormat:c.tieFormat??e.tieFormat??o?.tieFormat,orderMap:n})),Cx({eventId:o?.eventId,tournamentRecord:t,drawDefinition:e,structure:c,orderMap:n}),a.push(c.structureId));bt({drawDefinition:e,structureIds:a})}function Cx({tournamentRecord:t,drawDefinition:e,structure:r,orderMap:n,eventId:o}){let i=At({matchUpFilters:{matchUpTypes:[Bt]},structure:r})?.matchUps;for(let s of i)s.tieFormat&&(s.tieFormat=cl({tieFormat:s.tieFormat,orderMap:n}),It({tournamentId:t?.tournamentId,drawDefinition:e,eventId:o,matchUp:s}))}function Qg({updateInProgressMatchUps:t=!0,tieFormatComparison:e,tournamentRecord:r,drawDefinition:n,tieFormatName:o,collectionId:i,structureId:s,matchUpId:a,eventId:c,matchUp:u,event:p}){let m="removeCollectionDefinition",d=u?void 0:ei({drawDefinition:n,structureId:s,matchUpId:a,eventId:c,event:p});if(d?.error)return _({result:d,stack:m});let l=d?.structure;u=u??d?.matchUp;let f=d?.tieFormat,g=Xe(f);if(d=ir({tieFormat:g}),d.error)return _({result:d,stack:m});let I=g?.collectionDefinitions?.find(P=>P.collectionId===i);if(!I)return _({result:{error:Ke,collectionId:i}});g.collectionDefinitions=g.collectionDefinitions.filter(P=>P.collectionId!==i),I.collectionGroupNumber&&(g.collectionDefinitions=g.collectionDefinitions.map(P=>{let{collectionGroupNumber:N,...C}=P;return C}),g.collectionGroups=g.collectionGroups.filter(({groupNumber:P})=>P!==I.collectionGroupNumber));let{aggregateValue:h,valueGoal:S}=Is(g);g.winCriteria=rt({aggregateValue:h,valueGoal:S});let T=f?.winCriteria.valueGoal,A=f?.winCriteria.aggregateValue;(T&&T!==S||h&&!A)&&(o?g.tieFormatName=o:delete g.tieFormatName);let D=[];a&&u?D=[u]:s&&l?D=At({matchUpFilters:{matchUpTypes:[Bt]},structure:l})?.matchUps??[]:n?D=rr({matchUpFilters:{matchUpTypes:[Bt]},drawDefinition:n})?.matchUps??[]:p&&(D=co({matchUpFilters:{matchUpTypes:[Bt]},drawDefinition:n})?.matchUps??[]);let y=(D||[]).filter(P=>{let C=P.tieMatchUps?.filter(b=>b.collectionId===i)?.some(Ie),O=e&&P.tieFormat?Go({descendant:P.tieFormat,ancestor:g})?.different:!1;return t&&!C||!P.winningSide&&P.matchUpStatus!==me&&(t||P.matchUpStatus!==Dn&&!Ie(P)&&!O)});if(!y.length)return{error:Ns};let{appliedPolicies:E}=Pt({tournamentRecord:r});if(a&&u&&t){let P=u.tieMatchUps?.filter(N=>N.collectionId===i);for(let N of P??[]){let C=La({matchUpId:N.matchUpId,tieMatchUpId:u?.matchUpId,winningSide:void 0,removeScore:!0,tournamentRecord:r,appliedPolicies:E,drawDefinition:n,event:p});if(C.error||(C=xt({drawDefinition:n,matchUpId:a}),C.error))return C;u=C?.matchUp}}let U=[];for(let P of y){for(let N of P?.sides??[])N.lineUp=(N.lineUp??[]).map(C=>({participantId:C.participantId,collectionAssignments:(C?.collectionAssignments??[]).filter(O=>O.collectionId!==i)}));if(P.tieMatchUps=(P.tieMatchUps??[]).filter(N=>{let C=N.collectionId===i;return C&&U.push(N.matchUpId),!C}),P.tieFormat&&(P.tieFormat=Xe(g)),t){let N=zn({matchUpId:P.matchUpId,exitWhenNoValues:!0,tournamentRecord:r,appliedPolicies:E,drawDefinition:n,event:p});if(N.error)return N}It({tournamentId:r?.tournamentId,eventId:p?.eventId,drawDefinition:n,context:m,matchUp:P})}U.length&&wn({tournamentId:r?.tournamentId,matchUpIds:U,eventId:p?.eventId,drawDefinition:n});let M=rt(g);if(d=ir({tieFormat:M}),d.error)return _({result:d,stack:m});if(c&&p)p.tieFormat=M;else if(a&&u)u.tieFormat=M;else if(l)l.tieFormat=M;else if(n)n.tieFormat=M;else if(!u||!n)return{error:X};if(bt({drawDefinition:n,eventId:p?.eventId}),E?.audit?.[Qi]){let P=rt({drawId:n?.drawId,action:m,collectionId:i,structureId:s,matchUpId:a,eventId:c});Lu({drawDefinition:n,auditData:P})}return{tieFormat:M,deletedMatchUpIds:U,targetMatchUps:y,...R}}function jM({updateInProgressMatchUps:t=!0,tournamentRecord:e,groupDefinition:r,drawDefinition:n,collectionIds:o,tieFormatName:i,structureId:s,matchUpId:a,matchUp:c,eventId:u,event:p}){let m="addCollectionGroup";if(!Array.isArray(o))return _({result:{error:et},stack:m});let d=c?void 0:ei({drawDefinition:n,structureId:s,matchUpId:a,eventId:u,event:p});if(d?.error)return _({result:d,stack:m});let l=d?.structure;c=c||d?.matchUp;let f=d?.tieFormat,g=f?.winCriteria.valueGoal,I=Xe(f);if(d=ir({tieFormat:I}),d.error)return _({result:d,stack:m});for(let T of I.collectionDefinitions){let{collectionId:A,collectionGroupNumber:D}=T;if(D&&o.includes(A))return _({info:"collectionIds cannot be part of other collectionGroups",result:{error:G},stack:m})}let S=(I.collectionGroups||[]).reduce((T,A)=>A.groupNumber>T?A.groupNumber:T,0)+1;return r.groupNumber=S,I.collectionDefinitions=I.collectionDefinitions.map(T=>o.includes(T.collectionId)?{...T,collectionGroupNumber:S}:T),I.collectionGroups=[...I.collecitonGroups||[],r],HA({updateInProgressMatchUps:t,originalValueGoal:g,tournamentRecord:e,drawDefinition:n,tieFormatName:i,structureId:s,structure:l,tieFormat:I,matchUpId:a,matchUp:c,eventId:u,event:p})}function Xg({updateInProgressMatchUps:t=!0,collectionDefinition:e,referenceCategory:r,tournamentRecord:n,policyDefinitions:o,enforceCategory:i,referenceGender:s,drawDefinition:a,tieFormatName:c,enforceGender:u,structureId:p,matchUpId:m,matchUp:d,eventId:l,uuids:f,event:g}){let I="addCollectionDefinition",h=Pt({tournamentRecord:n,drawDefinition:a,event:g}).appliedPolicies??{},S=o?.[ze]??h?.[ze];i=i??S?.participants?.enforceCategory;let T=(u??S?.participants?.enforceGender)!==!1,A=!!((r??g?.category)&&i!==!1),D=!!((s??g?.gender)&&T),y=yu({referenceCategory:r??g?.category,collectionDefinition:e,referenceGender:s,checkCategory:A,checkGender:D,event:g});if(y.error)return _({result:y,stack:I});let E=d?.tieFormat?void 0:ei({drawDefinition:a,structureId:p,matchUpId:m,eventId:l,event:g});if(E?.error)return _({result:{error:E.error},stack:I});let U=E?.structure;d=d??E?.matchUp;let M=d?.tieFormat??E?.tieFormat,P=Xe(M);if(E=ir({tieFormat:P}),E?.error)return _({result:{error:E.error},stack:I});if(!e.collectionId)e.collectionId=Mt();else if(P.collectionDefinitions.map(({collectionId:B})=>B).includes(e.collectionId))return _({context:{collectionId:e.collectionId},result:{error:Jy}});P.collectionDefinitions.push(e),P.collectionDefinitions.sort((v,B)=>(v.collectionOrder||0)-(B.collectionOrder||0)).forEach((v,B)=>v.collectionOrder=B+1);let{aggregateValue:N,valueGoal:C}=Is(P);P.winCriteria=rt({aggregateValue:N,valueGoal:C});let O=M?.winCriteria.valueGoal,b=M?.winCriteria.aggregateValue;(O&&O!==C||N&&!b)&&(c?P.tieFormatName=c:delete P.tieFormatName);let x=[],w=[],F=[],L=rt(P);if(E=ir({tieFormat:L}),E?.error)return _({result:{error:E.error},stack:I});if(l&&g){g.tieFormat=L;for(let v of g.drawDefinitions??[])if(!v.tieFormat)for(let B of v.structures??[]){if(B.tieFormat)continue;let H=YM({updateInProgressMatchUps:t,collectionDefinition:e,structure:B,uuids:f});w.push(...H.newMatchUps),F.push(...H.targetMatchUps),x.push(B.structureId)}WA({modifiedMatchUps:F,eventId:g?.eventId,modifiedStructureIds:x,tournamentRecord:n,drawDefinition:a,addedMatchUps:w,stack:I})}else if(p&&U){U.tieFormat=L;let v=YM({updateInProgressMatchUps:t,collectionDefinition:e,structure:U,uuids:f});w.push(...v.newMatchUps),F=v.targetMatchUps,WA({modifiedMatchUps:F,eventId:g?.eventId,modifiedStructureIds:x,tournamentRecord:n,drawDefinition:a,addedMatchUps:w,stack:I})}else if(m&&d){if(!al({matchUp:d,updateInProgressMatchUps:t}))return _({result:{error:Pl},stack:I});d.tieFormat=L;let v=hu({collectionDefinition:e,matchUp:d,uuids:f});Array.isArray(d.tieMatchUps)||(d.tieMatchUps=[]),d.tieMatchUps.push(...v),w.push(...v),WA({modifiedMatchUps:[d],eventId:g?.eventId,modifiedStructureIds:x,tournamentRecord:n,drawDefinition:a,addedMatchUps:w,stack:I})}else if(a){a.tieFormat=L;for(let v of a.structures??[]){let B=YM({updateInProgressMatchUps:t,collectionDefinition:e,structure:v,uuids:f});x.push(v.structureId),w.push(...B.newMatchUps),F.push(...B.targetMatchUps)}WA({modifiedMatchUps:F,eventId:g?.eventId,tournamentRecord:n,drawDefinition:a,addedMatchUps:w,stack:I})}else return{error:X};if(h?.audit?.[Qi]){let v=rt({drawId:a?.drawId,collectionDefinition:e,action:I,structureId:p,matchUpId:m,eventId:l});Lu({drawDefinition:a,auditData:v})}return{tieFormat:L,targetMatchUps:F,addedMatchUps:w,...R}}function YM({updateInProgressMatchUps:t,collectionDefinition:e,structure:r,uuids:n}){let o=[],s=(At({matchUpFilters:{matchUpTypes:[Bt]},structure:r})?.matchUps).filter(a=>al({matchUp:a,updateInProgressMatchUps:t})&&!a.tieFormat);for(let a of s){let c=hu({collectionDefinition:e,matchUp:a,uuids:n});Array.isArray(a.tieMatchUps)||(a.tieMatchUps=[]),a.tieMatchUps.push(...c),o.push(...c)}return{newMatchUps:o,targetMatchUps:s}}function WA({modifiedStructureIds:t,tournamentRecord:e,modifiedMatchUps:r,drawDefinition:n,addedMatchUps:o,eventId:i,stack:s}){So({tournamentId:e?.tournamentId,matchUps:o,drawDefinition:n,eventId:i}),r?.forEach(a=>{It({tournamentId:e?.tournamentId,drawDefinition:n,context:s,matchUp:a,eventId:i})}),bt({structureIds:t,drawDefinition:n,eventId:i})}function qM({updateInProgressMatchUps:t=!1,tieFormatComparison:e,modifiedTieFormat:r,tournamentRecord:n,drawDefinition:o,structureId:i,matchUpId:s,eventId:a,uuids:c,event:u}){let p="modifyTieFormat";if(!ir({tieFormat:r}).valid)return _({result:{error:ni},info:"falied validation",stack:p});let m=ei({drawDefinition:o,structureId:i,matchUpId:s,eventId:a,event:u});if(m.error)return _({result:m,stack:p});let{matchUp:d,tieFormat:l}=m,f=Xe(l),g=Go({descendant:r,ancestor:f});if(g.invalid)return _({context:{invalid:g.invalid},result:{error:ni},stack:p});if(!g?.different)return _({result:{...R},info:"Nothing to do",stack:p});let I=f.collectionDefinitions.map(({collectionId:M})=>M),h=r.collectionDefinitions.map(({collectionId:M})=>M),S=I.filter(M=>!h.includes(M)),T=r.collectionDefinitions.filter(({collectionId:M})=>!I.includes(M)),A=T.map(Pr("collectionId")),D=[],y,E=r.tieFormatName;for(let M of r.collectionDefinitions){if(A.includes(M.collectionId))continue;let P=zg({updateInProgressMatchUps:t,...M,tournamentRecord:n,tieFormatName:E,drawDefinition:o,structureId:i,matchUpId:s,eventId:a,event:u});if(P.modifications&&D.push(...P.modifications),P.error)return _({result:P,stack:p});P.tieFormat&&(y=P.tieFormat)}for(let M of T){let P=Xg({updateInProgressMatchUps:t,collectionDefinition:M,tournamentRecord:n,drawDefinition:o,tieFormatName:E,structureId:i,matchUpId:s,matchUp:d,eventId:a,uuids:c,event:u});if(P.error)return _({result:P,stack:p});P.tieFormat&&(y=P.tieFormat)}for(let M of S){let P=Qg({updateInProgressMatchUps:t,tieFormatComparison:e,tournamentRecord:n,drawDefinition:o,tieFormatName:E,collectionId:M,structureId:i,matchUpId:s,eventId:a,matchUp:d,event:u});if(P.error)return _({result:P,stack:p});P.tieFormat&&(y=P.tieFormat)}return l?.tieFormatName!==E?(y.tieFormatName=E,D.push({tieFormatName:E})):(D.length||A.length||S.length)&&(delete y.tieFormatName,D.push("tieFormatName removed: modifications without new tieFormatName")),y.collectionDefinitions=y.collectionDefinitions.sort((M,P)=>Qa(M.collectionOrder)-Qa(P.collectionOrder)).map((M,P)=>({...M,collectionOrder:P+1})),{processedTieFormat:Xe(y),modifications:D,...R}}function $M({tournamentRecord:t}){if(!t)return{error:W};let e=0;for(let r of t.events??[]){let n=r.tieFormats??[],o=p=>{if(!p.tieFormat)return;let m;for(let d of n)Go({descendant:p.tieFormat,ancestor:d}).different||(m=d.tieFormatId);if(m)p.tieFormatId=m,delete p.tieFormat;else{let d=J(p.tieFormat,void 0,!0);d.tieFormatId||(d.tieFormatId=Mt()),p.tieFormatId=d.tieFormatId,delete p.tieFormat,n.push(d),e+=1}},i=r.eventType;o({tieFormat:r.tieFormat,eventType:i});for(let p of r.drawDefinitions??[]){o({tieFormat:p.tieFormat,eventType:i});for(let m of p.structures??[])o({tieFormat:m.tieFormat,eventType:i})}let s=(p,m)=>{let d=c.matchUps?.find(l=>l.matchUpId===p);d&&(d.tieFormatId=m,delete d.tieFormat,It({tournamentId:t?.tournamentId,eventId:r.eventId,matchUp:d}))},a=p=>{let m=J(p.tieFormat,void 0,!0);m.tieFormatId||(m.tieFormatId=Mt()),n.push(m),e+=1,s(p.matchUpId,m.tieFormatId)},c=co({matchUpFilters:{matchUpTypes:[ln]},event:r}),u=c.matchUps??[];for(let p of u){let m;for(let d of n)p.tieFormat&&Go({descendant:p.tieFormat,ancestor:d}).different||(m=d.tieFormatId);m?s(p.matchUpId,m):a(p)}n.length&&(r.tieFormats=n)}return{...R,addedCount:e}}var oC={};Jt(oC,{addDrawDefinitionExtension:()=>ep,addEventExtension:()=>Io,addEventTimeItem:()=>ki,addExtension:()=>St,addNotes:()=>Up,addOnlineResource:()=>XM,addParticipantExtension:()=>SE,addParticipantTimeItem:()=>Jf,addTimeItem:()=>Ti,addTournamentExtension:()=>tf,addTournamentTimeItem:()=>Gi,analyzeDraws:()=>Eu,analyzeTournament:()=>DT,getAllowedDrawTypes:()=>vd,getAllowedMatchUpFormats:()=>yT,getAppliedPolicies:()=>Pt,getCompetitionDateRange:()=>wd,getCompetitionPenalties:()=>ET,getPolicyDefinitions:()=>yo,getTournamentInfo:()=>gs,getTournamentPenalties:()=>xd,getTournamentPersons:()=>PT,getTournamentStructures:()=>jh,getTournamentTimeItem:()=>mu,mutate:()=>nC,query:()=>xD,removeDrawDefinitionExtension:()=>TE,removeEventExtension:()=>rp,removeExtension:()=>or,removeNotes:()=>XU,removeParticipantExtension:()=>AE,removeTournamentExtension:()=>ef,setTournamentCategories:()=>tC,setTournamentDates:()=>Jg,setTournamentEndDate:()=>rC,setTournamentName:()=>JM,setTournamentNotes:()=>ZM,setTournamentStartDate:()=>eC,setTournamentStatus:()=>QM});var nC={};Jt(nC,{addDrawDefinitionExtension:()=>ep,addEventExtension:()=>Io,addEventTimeItem:()=>ki,addExtension:()=>St,addNotes:()=>Up,addOnlineResource:()=>XM,addParticipantExtension:()=>SE,addParticipantTimeItem:()=>Jf,addTimeItem:()=>Ti,addTournamentExtension:()=>tf,addTournamentTimeItem:()=>Gi,removeDrawDefinitionExtension:()=>TE,removeEventExtension:()=>rp,removeExtension:()=>or,removeNotes:()=>XU,removeParticipantExtension:()=>AE,removeTournamentExtension:()=>ef,setTournamentCategories:()=>tC,setTournamentDates:()=>Jg,setTournamentEndDate:()=>rC,setTournamentName:()=>JM,setTournamentNotes:()=>ZM,setTournamentStartDate:()=>eC,setTournamentStatus:()=>QM});var r1="ABANDONED",n1="ACTIVE",o1="CANCELLED",i1="COMPLETED",s1="IN_PROGRESS",jA={ABANDONED:r1,ACTIVE:n1,CANCELLED:o1,COMPLETED:i1,IN_PROGRESS:s1};function QM({tournamentRecord:t,status:e}){return t?e&&!Object.keys(jA).includes(e)?{error:G,info:"Unknown status"}:(t.tournamentStatus=e,{...R}):{error:W}}function XM({tournamentRecord:t,onlineResource:e,organisationId:r,participantId:n,personId:o,courtId:i,venueId:s}){if(!t)return{error:W};if(!Rt(e))return{error:et};if(jt(Object.keys(e),["resourceSubType","resourceType","identifier"]).length!==3)return _({result:{error:Xn},context:{onlineResource:e}});if(r){if(t.parentOrganisation?.parentOrganisationId!==r)return _({result:{error:Ke}});t.parentOrganisation.onlineResources||(t.parentOrganisation.onlineResources=[]),t.parentOrganisation.onlineResources.push(e)}else if(n||o){let a=(t.participants??[]).find(c=>o&&c.person?.personId===o||c.participantId===n);if(!a)return o?_({result:{error:Ke}}):_({result:{error:Zt}});if(o){if(a.person?.personId!==o)return _({result:{error:Us}});a.person.onlineResources||(a.person.onlineResources=[]),a.person.onlineResources.push(e)}else a.onlineResources||(a.onlineResources=[]),a.onlineResources.push(e)}else if(i){let a=(t.venues??[]).filter(c=>!s||c.venueId===s).flatMap(c=>(c.courts??[]).filter(u=>u.courtId===i))?.[0];if(!a)return _({result:{error:Ka}});a.onlineResources||(a.onlineResources=[]),a.onlineResources.push(e)}else if(s){let a=(t.venues??[]).find(c=>c.venueId===s);if(!a)return _({result:{error:Ds}});a.onlineResources||(a.onlineResources=[]),a.onlineResources.push(e)}else t.onlineResources||(t.onlineResources=[]),t.onlineResources.push(e);return{...R}}function JM({tournamentRecord:t,promotionalName:e,tournamentName:r,formalName:n}){return t?(r&&(t.tournamentName=r),e&&(t.promotionalName=e),n&&(t.formalName=n),t.promotionalName===t.tournamentName&&delete t.promotionalName,t.formalName===t.tournamentName&&delete t.formalName,{...R}):{error:W}}function ZM({tournamentRecord:t,notes:e}){return t?Up({element:t,notes:e}):{error:W}}function tC({tournamentRecord:t,categories:e}){return t?(e=(e||[]).filter(r=>r.categoryName&&r.type),t.tournamentCategories=e,{...R}):{error:W}}function Rx({tournamentRecord:t}){if(!t)return{error:W};let{startDate:e,endDate:r}=t,n=bs(e,r),o=[];for(let i of t.venues||[])i?.courts?.length&&o.push(...i.courts);for(let i of o){let{startTime:s,endTime:a}=(i.dateAvailability??[]).reduce((p,m)=>{let d=Vt(p.startTime),l=Vt(p.endTime);return m.startTime&&Vt(m.startTime)<d&&(p.startTime=m.startTime),m.endTime&&Vt(m.endTime)>l&&(p.endTime=m.endTime),p},{startTime:"08:00",endTime:"18:00"}),c=n.map(p=>i.dateAvailability?.find(d=>d.date===p)??{date:p,startTime:s,endTime:a}),u=i.dateAvailability?.find(p=>!p.date);u&&c.unshift(u),i.dateAvailability=c}return{...R}}function Jg(t){let{tournamentRecord:e,startDate:r,endDate:n}=t,o=lt(t,[{tournamentRecord:!0},{[fm]:{startDate:!1,endDate:!1},[En]:ar,[yn]:m=>Ro.test(m)}]);if(o.error)return o;if(n&&r&&new Date(n)<new Date(r))return{error:G};let i;(r&&e.startDate&&new Date(r)>new Date(e.startDate)||n&&e.endDate&&new Date(n)<new Date(e.endDate))&&(i=!0);let s=bs(e.startDate,e.endDate);r&&(e.startDate=r),n&&(e.endDate=n);let a=bs(e.startDate,e.endDate),c=s.filter(m=>!a.includes(m)),u=a.filter(m=>!s.includes(m));for(let m of e.events??[])r&&m.startDate&&new Date(m.startDate)<new Date(r)&&(m.startDate=r),n&&m.startDate&&new Date(m.startDate)>new Date(n)&&(m.startDate=r??n),n&&m.endDate&&new Date(m.endDate)>new Date(n)&&(m.endDate=n),r&&m.endDate&&new Date(m.endDate)<new Date(r)&&(m.endDate=n??r);r&&e.endDate&&new Date(r)>new Date(e.endDate)&&(e.endDate=r),n&&e.startDate&&new Date(n)<new Date(e.startDate)&&(e.startDate=n);let p=i&&a1({tournamentRecord:e})?.unscheduledMatchUpIds;return Rx({tournamentRecord:e}),Tt({topic:HE,payload:{startDate:r,endDate:n}}),{...R,unscheduledMatchUpIds:p,datesAdded:u,datesRemoved:c}}function eC({tournamentRecord:t,startDate:e}){return Jg({tournamentRecord:t,startDate:e})}function rC({tournamentRecord:t,endDate:e}){return Jg({tournamentRecord:t,endDate:e})}function a1({tournamentRecord:t}){let e=le({tournamentRecord:t}).matchUps??[],r=t.startDate&&new Date(t.startDate),n=t.endDate&&new Date(t.endDate),o=[],i=[];for(let s of e){let{schedule:a,matchUpId:c}=s;if(a&&a.scheduledDate){let u=new Date(a.scheduledDate);(r&&u<r||n&&u>n)&&(i.push(c),o.includes(a.scheduledDate)||o.push(a.scheduledDate))}}return o.length&&!Qp({scheduledDates:o,tournamentRecord:t}).clearedScheduleCount?{error:ry}:{unscheduledMatchUpIds:i}}var fC={};Jt(fC,{addCourt:()=>il,addCourts:()=>qg,addVenue:()=>pc,deleteCourt:()=>mC,deleteVenue:()=>qA,deleteVenues:()=>sC,disableCourts:()=>aC,disableVenues:()=>cC,enableCourts:()=>uC,enableVenues:()=>pC,generate:()=>iC,generateCourts:()=>Og,getCompetitionVenues:()=>Lp,getCourts:()=>jT,getVenuesAndCourts:()=>po,modifyCourt:()=>tI,modifyCourtAvailability:()=>Zg,modifyVenue:()=>dC,mutate:()=>lC,publicFindVenue:()=>Th,query:()=>zD});var iC={};Jt(iC,{generateCourts:()=>Og});var lC={};Jt(lC,{addCourt:()=>il,addCourts:()=>qg,addVenue:()=>pc,deleteCourt:()=>mC,deleteVenue:()=>qA,deleteVenues:()=>sC,disableCourts:()=>aC,disableVenues:()=>cC,enableCourts:()=>uC,enableVenues:()=>pC,modifyCourt:()=>tI,modifyCourtAvailability:()=>Zg,modifyVenue:()=>dC});function ul(t){if(!t?.tournamentRecord&&!Array.isArray(t?.venueMatchUps))return{error:W};if(!t?.courtId)return{error:Ni};let{scheduleVisibilityFilters:e,tournamentRecord:r,matchUpFilters:n,venueMatchUps:o,courtId:i}=t,{schedulingProfile:s}=ko({tournamentRecord:r});if(Array.isArray(o))return{matchUps:u({matchUps:o,courtId:i})};let{matchUps:a}=le({scheduleVisibilityFilters:e,tournamentRecord:r,matchUpFilters:n});return{matchUps:u({matchUps:a,courtId:i})};function u({matchUps:p,courtId:m}){let d=p.filter(l=>{let f=l.schedule?.allocatedCourts?.map(({courtId:g})=>g);return l.schedule?.courtId===m||f?.includes(m)});return Hd({matchUps:d,schedulingProfile:s})}}function bx({scheduleVisibilityFilters:t,tournamentRecord:e,matchUpFilters:r,venueId:n}){if(!e)return{error:W};if(!n)return{error:Bo};let{schedulingProfile:o}=ko({tournamentRecord:e}),{matchUps:i}=le({scheduleVisibilityFilters:t,tournamentRecord:e,matchUpFilters:r});return{matchUps:a({matchUps:i,venueId:n})};function a({matchUps:c,venueId:u}){let p=c.filter(m=>{let d=m.schedule?.allocatedCourts?.map(({venueId:l})=>l);return m.schedule?.venueId===u||d?.includes(u)});return Hd({matchUps:p,schedulingProfile:o})}}function Zg({tournamentRecord:t,dateAvailability:e,disableNotice:r,venueMatchUps:n,courtId:o,force:i}){if(!t)return{error:W};if(!o)return{error:Ni};let s=FA({dateAvailability:e});if(s.error)return s;let{updatedDateAvailability:a,totalMergeCount:c}=c1(e);e=a;let u=ns({tournamentRecord:t,courtId:o});if(u.error)return u;let{court:p,venue:m}=u,{matchUps:d}=ul({tournamentRecord:t,venueMatchUps:n,courtId:o});if(d?.length){let l=Pt({tournamentRecord:t})?.appliedPolicies,f=i??l?.[go]?.allowDeletionWithScoresPresent?.courts,g=[];g.length&&(f||console.log("throw error: scheduled court matchUps",g.length))}return p&&(p.dateAvailability=e,!r&&m&&Tt({payload:{venue:m,tournamentId:t.tournamentId},topic:ui,key:m.venueId})),{...R,totalMergeCount:c}}function c1(t){let e=0,r=t.reduce((o,i)=>{let{date:s,startTime:a,endTime:c,bookings:u}=i;return o[s]||(o[s]=[]),o[s].push({startTime:a,endTime:c,bookings:u}),o},{}),n=[];return Object.keys(r).forEach(o=>{r[o].sort(Ix);let{mergedAvailability:i,mergeCount:s}=u1(r[o]);n.push(...i.map(a=>({date:o,...a}))),e+=s}),{updatedDateAvailability:n,totalMergeCount:e}}function u1(t){let e,r,n,o=t.length,i=0,s=[];for(;t.length&&o;){let c=t.shift(),{startTime:u,endTime:p,bookings:m}=c;if(o-=1,!e)e=u,n=m,r=p;else if(ca(we(r),we(u),!1)>0){let l={startTime:e,endTime:r};n?.length&&(l.bookings=n),s.push(l),e=u,n=m,r=p}else m&&(n?n.push(m):n=m),r=p,i+=1}let a={startTime:e,endTime:r};return n?.length&&(a.bookings=n),s.push(a),{mergedAvailability:s,mergeCount:i}}function pl({matchUpsCount:t=0}){let r=`Schedule would be deleted from ${t} ${t===1?"matchUp":"matchUps"}; use { force: true }`;return{error:nE,info:r}}function YA({tournamentRecord:t,drawDefinition:e,matchUpId:r,drawId:n}){let o="removeCourtAssignment";if(!r)return{error:ke};if(!e&&!n)return{error:Wr};let i;if(!e){if(!t)return{error:W};({drawDefinition:e}=We({tournamentRecord:t,drawId:n}))}if(e)({matchUp:i}=xt({drawDefinition:e,matchUpId:r}));else{if(!t)return{error:W};let s=le({tournamentRecord:t,inContext:!1}).matchUps??[];({matchUp:i}=iS({matchUps:s,matchUpId:r}))}return i?(i.timeItems&&i.timeItems.find(a=>[di,Eo].includes(a.itemType))&&(i.timeItems=i.timeItems.filter(({itemType:a})=>![di,Eo].includes(a)),It({tournamentId:t?.tournamentId,context:o,drawDefinition:e,matchUp:i})),{...R}):{error:Oe}}function qA(t){if(typeof t?.venueId!="string")return{error:Bo};let{tournamentRecord:e,venueId:r,force:n}=t,o=t.tournamentRecords||e&&{[e.tournamentId]:e}||{};if(!Object.keys(o).length)return{error:W};let s=cn({tournamentRecords:o,contextFilters:{venueIds:[r]}}).matchUps??[],a=Pt({tournamentRecord:e})?.appliedPolicies,c=n??a?.[go]?.allowDeletionWithScoresPresent?.venues;if(!s.length||c)for(let u of Object.values(o)){for(let m of s){let d=YA({matchUpId:m.matchUpId,drawId:m.drawId,tournamentRecord:u});if(d.error)return d}let p;u.venues=(u.venues??[]).filter(m=>m?.venueId!==r?!0:(p=!0,!1)),p&&Tt({payload:{venueId:r,tournamentId:u.tournamentId},topic:mf,key:r})}else return pl({matchUpsCount:s.length});return Nc({tournamentRecords:o}),{...R}}function sC({tournamentRecord:t,venueIds:e,force:r}){if(!t)return{error:W};if(!Array.isArray(e))return{error:G};for(let n of t.venues||[]){let{venueId:o}=n;if(e.includes(o)){let{venueId:i}=n,s=qA({tournamentRecord:t,venueId:i,force:r});if(s.error)return s}}return{...R}}function aC(t){let{courtIds:e,dates:r}=t,n=Xr(t),o=[{[ye]:!0,[Ju]:!0}],i=lt(t,o);if(i.error)return i;for(let s of Object.values(n))p1({tournamentRecord:s,courtIds:e,dates:r});return{...R}}function p1({tournamentRecord:t,courtIds:e,dates:r}){let n=Array.isArray(r)&&r.length?{dates:r}:!0,o=i=>St({extension:{value:n,name:Wn},creationTime:!1,element:i});for(let i of t.venues||[])for(let s of i.courts||[])if(e?.includes(s.courtId)){let a=o(s);if(a.error)return a}return{...R}}function cC(t){let{tournamentRecords:e,tournamentId:r,venueIds:n}=t,o=[{[ye]:!0,[Zu]:!0}],i=lt(t,o);if(i.error)return i;let s=Object.keys(e).filter(a=>!r||a===r);for(let a of s){let c=e[a];m1({tournamentRecord:c,venueIds:n})}return{...R}}function m1({tournamentRecord:t,venueIds:e}){for(let r of t.venues||[])if(e?.includes(r.venueId)){let n=St({creationTime:!1,element:r,extension:{name:Wn,value:!0}});if(n.error)return n}return{...R}}function uC(t){let e=Xr(t),r=[{[ye]:!0}];!t.enableAll&&r.push({[Ju]:!0});let n=lt(t,r);if(n.error)return n;let{enableAll:o,courtIds:i,dates:s}=t;for(let a of Object.values(e))d1({tournamentRecord:a,courtIds:i,enableAll:o,dates:s});return{...R}}function d1({tournamentRecord:t,courtIds:e,enableAll:r,dates:n}){for(let o of t.venues||[])for(let i of o.courts||[])if(r||e?.includes(i.courtId))if(Array.isArray(n)){let{extension:s}=mt({element:i,name:Wn});if(s){let a=s.value;Array.isArray(a.dates)&&(a.dates=a.dates.filter(c=>!n.includes(c))),St({extension:{name:Wn,value:a},creationTime:!1,element:i})}}else or({element:i,name:Wn});return{...R}}function pC(t){let e=Xr(t),r=[{[ye]:!0}];!t.enableAll&&r.push({[Zu]:!0});let n=lt(t,r);if(n.error)return n;let{venueIds:o,enableAll:i}=t;for(let s of Object.values(e))for(let a of s.venues||[])(i||o?.includes(a.venueId))&&or({element:a,name:Wn});return{...R}}function mC(t){let{courtId:e,disableNotice:r,force:n}=t,o=Xr(t),i=lt(t,[{[ye]:!0,[RI]:!0}]);if(i.error)return i;let s,a;for(let c of Object.values(o)){if(a=l1({tournamentRecord:c,disableNotice:r,courtId:e,force:n}),a.error&&a.error!==Ka)return a;a.success&&(s=!0)}return s?{...R}:a}function l1({tournamentRecord:t,disableNotice:e,courtId:r,force:n}){let o=ns({tournamentRecord:t,courtId:r});if(o.error)return o;let i=o.venue,{matchUps:s}=ul({tournamentRecord:t,courtId:r}),a=Pt({tournamentRecord:t})?.appliedPolicies,c=n??a?.[go]?.allowDeletionWithScoresPresent?.courts;if(!s?.length||c){for(let u of s??[]){let p=YA({matchUpId:u.matchUpId,drawId:u.drawId,tournamentRecord:t});if(p.error)return p}i&&(i.courts=(i.courts??[]).filter(u=>u.courtId!==r),e||Tt({payload:{venue:i,tournamentId:t.tournamentId},topic:ui,key:i.venueId}))}else return pl({matchUpsCount:s.length});return{...R}}function tI(t){let{disableNotice:e,modifications:r,courtId:n,force:o,venueMatchUps:i}=t,s=Xr(t);if(!Object.keys(s).length)return{error:Ft};let a,c;for(let u of Object.values(s)){let p=f1({tournamentRecord:u,disableNotice:e,venueMatchUps:i,modifications:r,courtId:n,force:o});if(p?.error)return p;a=!0}return a?{...R}:c}function f1({tournamentRecord:t,disableNotice:e,venueMatchUps:r,modifications:n,courtId:o,force:i}){if(!t)return{error:W};if(!o)return{error:Ni};if(!n||typeof n!="object")return{error:Xn};let s=ns({tournamentRecord:t,courtId:o});if(s.error)return s;let{venue:a,court:c}=s,u=Object.keys(gx()).filter(l=>l!=="courtId");if(!Object.keys(n).filter(l=>u.includes(l)).length)return{error:qu};let m=u.filter(l=>!["dateAvailability"].includes(l)),d=Object.keys(n).filter(l=>m.includes(l));if(c&&d.forEach(l=>Object.assign(c,{[l]:n[l]})),n.dateAvailability){let l=Zg({dateAvailability:n.dateAvailability,tournamentRecord:t,venueMatchUps:r,disableNotice:e,courtId:o,force:i});if(l.error)return l}return e||Tt({payload:{venue:a,tournamentId:t.tournamentId},topic:ui,key:a?.venueId}),{...R,court:J(c)}}var g1=()=>({venueId:void 0,venueName:"",venueAbbreviation:"",onlineResources:[],venueType:void 0,addresses:[],contacts:[],courts:[],roles:[]}),Ox=g1;function dC(t){let{modifications:e,venueId:r,force:n}=t,o=Xr(t);if(!Object.keys(o).length)return{error:Ft};if(typeof r!="string")return{error:Bo};let i,s;for(let a of Object.values(o)){let c=I1({tournamentRecord:a,modifications:e,venueId:r,force:n});if(c.success&&(s=!0),c.error&&(i=c.error),c.error&&c.error!==Ds)return c}return Nc({tournamentRecords:o}),s?{...R}:{error:i}}function I1({tournamentRecord:t,modifications:e,venueId:r,force:n}){if(!t)return{error:W};if(!e||typeof e!="object")return{error:Xn};if(!r)return{error:Bo};let o=Pt({tournamentRecord:t})?.appliedPolicies,i=n??o?.[go]?.allowDeletionWithScoresPresent?.venues,{matchUps:s}=bx({tournamentRecord:t,venueId:r}),a=Qo({tournamentRecord:t,venueId:r});if(a.error)return a;let c=a.venue,u=Object.keys(Ox()).filter(h=>h!=="venueId");if(!Object.keys(e).filter(h=>u.includes(h)).length)return{error:qu};let m=u.filter(h=>!["courts","onlineResources"].includes(h)),d=Object.keys(e).filter(h=>m.includes(h));c&&d.forEach(h=>Object.assign(c,{[h]:e[h]}));let l=c?.courts?.map(h=>h.courtId)??[],f=e.courts?.map(h=>h.courtId)||[],g=f.length?l.filter(h=>!f.includes(h)):e?.courts&&l,I=[];if(g?.length){let S=c?.courts?.filter(T=>g.includes(T.courtId))?.map(T=>{let A=ul({courtId:T.courtId,tournamentRecord:t,venueMatchUps:s});for(let D of A.matchUps??[])I.push({matchUpId:D.matchUpId,drawId:D.drawId});return A.matchUps?.length??0}).reduce((T,A)=>T+A);if(c&&(!S||i))c.courts=c.courts?.filter(T=>f.includes(T.courtId)),wu({schedule:{courtId:"",scheduledDate:""},matchUpDetails:I,removePriorValues:!0,tournamentRecord:t});else return pl({matchUpsCount:S})}if(e.courts)for(let h of e.courts){let{courtId:S}=h||{},T=tI({modifications:h,disableNotice:!0,tournamentRecord:t,venueMatchUps:s,courtId:S,force:n});if(T.error===Ka&&(T=il({disableNotice:!0,tournamentRecord:t,venueId:r,court:h})),T.error)return T}return Nc({tournamentRecord:t}),c&&Tt({payload:{venue:c,tournamentId:t.tournamentId},topic:ui,key:c?.venueId}),{...R,venue:J(c)}}var gC={};Jt(gC,{JSON2CSV:()=>xx,UUID:()=>Mt,UUIDS:()=>WR,allNumeric:()=>UI,attributeFilter:()=>bi,chunkArray:()=>Te,chunkByNth:()=>Gl,chunkSizeProfile:()=>uE,constantToString:()=>Ye,countValues:()=>BC,createMap:()=>sI,dateTime:()=>dR,definedAttributes:()=>rt,dehydrateMatchUps:()=>vx,extractAttributes:()=>qE,flattenJSON:()=>KA,generateDateRange:()=>bs,generateHashCode:()=>bC,generateRange:()=>Z,generateTimeCode:()=>kA,groupValues:()=>aE,hasAttributeValues:()=>RC,instanceCount:()=>dr,intersection:()=>jt,isConvertableInteger:()=>ft,isNumeric:()=>te,isOdd:()=>yI,isPowerOf2:()=>Tn,makeDeepCopy:()=>J,matchUpSort:()=>hi,nearestPowerOf2:()=>cm,nextPowerOf2:()=>qi,noNulls:()=>VC,noNumeric:()=>PI,numericSort:()=>se,occurrences:()=>HC,overlap:()=>xe,randomMember:()=>on,randomPop:()=>xr,shuffleArray:()=>cr,structureSort:()=>ci,subSort:()=>WC,undefinedToNull:()=>iI,unique:()=>pt,visualizeScheduledMatchUps:()=>_x});function _x({scheduledMatchUps:t,showGlobalLog:e}){lb();let r=t?.reduce((o,{structureId:i})=>o.includes(i)?o:o.concat(i),[]),n=Array.isArray(r)&&{...r.map(o=>{let{structureName:i,matchUpType:s}=t.find(a=>a.structureId===o);return{[o]:`${i} ${s}`}})};r?.forEach(o=>{kn({color:"blue",method:"draw",structure:n[o],keyColors:{structure:"magenta"}},!0);let i=t.filter(a=>a.structureId===o),s=He({matchUps:i})?.roundMatchUps||[];Object.keys(s).forEach(a=>{kn({roundNumber:a,keyColors:{roundNumber:"brightcyan"}},!0),s[a].forEach(({matchUpId:c,schedule:u})=>{let p=$t(u.scheduledTime);kn({matchUpId:c,time:p,date:u.scheduledDate,venue:u.venueId,keyColors:{time:"brightcyan",date:"brightcyan",matchUpId:"yellow",venue:"magenta"}},!0)})})}),e&&db()}function vx({tournamentRecord:t}){if(!t)return{error:W};if(typeof t!="object"||!t.tournamentId)return{error:G};let{matchUps:e}=le({tournamentRecord:t,inContext:!1});if(e?.length){let r=h1({tournamentRecord:t});T1(e,r)}return{...R}}function h1({tournamentRecord:t}){let e={};for(let r of t.events||[]){r.matchUpFormat&&(e[r.eventId]=r.matchUpFormat);for(let n of r.drawDefinitions||[]){n.matchUpFormat&&(e[n.drawId]=n.matchUpFormat);for(let o of n.structures||[]){o.matchUpFormat&&(e[o.structureId]=o.matchUpFormat);for(let i of o.structures||[])i.matchUpFormat&&(e[i.structureId]=i.matchUpFormat)}}}return e}var S1=["collectionId","collectionPosition","drawPositions","extensions","finishingPositionRange","finishingRound","isMock","matchUpId","matchUpStatus","matchUpStatusCodes","orderOfFinish","processCodes","roundNumber","tieFormat","tieMatchUps","roundPosition","score","sides","winnerMatchUpId","loserMatchUpId","matchUpDuration","winningSide"];function T1(t,e={}){for(let r of t){let{structureId:n,drawId:o,eventId:i}=r,s=e[n]||e[o]||e[i],a=r.matchUpFormat===s?void 0:r.matchUpFormat;for(let c of Object.keys(r))S1.includes(c)||delete r[c];r.sides&&r.drawPositions&&!r.tieMatchUps&&delete r.sides,a&&(r.matchUpFormat=a)}}function xx(t,e){if(e&&typeof e!="object")return{error:G};let{columnTransform:r={}}=e||{},{includeTransformAccessors:n,includeHeaderRow:o=!0,returnTransformedJSON:i,removeEmptyColumns:s,onlyHeaderRow:a,columnAccessors:c=[],functionMap:u={},columnMap:p={},valuesMap:m={},context:d={},delimiter:l='"',columnJoiner:f=",",rowJoiner:g=`\r
|
|
24
|
+
`,keyJoiner:I="."}=e||{};if(!Array.isArray(t)||!Array.isArray(c)||typeof d!="object"||typeof p!="object"||typeof r!="object"||typeof u!="object"||typeof m!="object"||typeof f!="string"||typeof g!="string"||typeof I!="string"||typeof l!="string")return{error:G};r=Object.assign({},...Object.keys(r).reverse().map(b=>({[b]:Array.isArray(r[b])?r[b]:[typeof r[b]=="string"&&r[b]].filter(Boolean)})));let h=t.filter(Boolean).map(b=>KA(b,I)),S=Object.values(r).flat();n&&c.push(...S);let T=h.reduce((b,x)=>Object.keys(x).every(w=>!b.includes(w)&&b.push(w)||!0)&&b,[]).filter(b=>!c?.length||c.includes(b)),A=Object.assign({},...Object.keys(r).reverse().map(b=>r[b].map(x=>({[x]:b})).flat()).flat()),D=(b,x)=>e?.sortOrder?e.sortOrder.includes(b)&&e.sortOrder.includes(x)&&e.sortOrder.indexOf(b)-e.sortOrder.indexOf(x)||!e.sortOrder.includes(x)&&-1:0,y=T.reduce((b,x)=>{let w=A[x];return w?b.includes(w)||b.push(w):b.push(x),b},[]).sort(D);Object.keys(p).forEach(b=>!y.includes(b)&&y.unshift(b)),Object.keys(r).forEach(b=>!y.includes(b)&&y.unshift(b)),typeof d=="object"&&Object.keys(d).forEach(b=>!y.includes(b)&&y.unshift(b));let E=y.map(b=>p[b]||b);if(a)return[E];let U=b=>`${l}${b}${l}`,M=[],P=b=>Object.values(y.reduce((x,w,F)=>{let L=r[w],v=(L?.length?b[L.find(j=>b[j])]:b[w])||d?.[w]||"",B=m[w]?.[v]||v,H=Mr(u[w])?u[w](B):B;return x[w]=U(H),H&&(M[F]=(M[F]||0)+1),x},{})),N=h.map(P),C=s&&[...M].map((b,x)=>!b&&x).filter(te).reverse();if(C){let b=x=>x.filter((w,F)=>!C.includes(F));N=N.map(b),E=b(E)}let O=N.map(b=>b.join(f));return i?O.map(b=>{let x=b.split(f);return Object.assign({},...x.map((w,F)=>({[E[F]]:w})))}):o?[E.map(U).join(f),...O].join(g):O.join(g)}function KA(t,e=".",r=[]){return typeof t=="object"&&Object.keys(t).reduce((n,o)=>typeof t[o]!="object"?(n[r.concat(o).join(e)]=t[o],n):Object.assign(n,KA(t[o],e,r.concat(o))),{})}var A1={};var{FACTORY:wx}=HI;function Lx({tournamentRecord:t,value:e}){let{extension:r}=mt({element:t,name:wx}),n={name:wx,value:{...r?.value,...e}};St({element:t,extension:n})}function Fu({timeStamp:t}){let e=Mo(),r=Bl();return r&&Object.values(e).forEach(n=>{Lx({tournamentRecord:n,value:{version:Va(),timeStamp:t}})}),r}function zA({engineType:t,methodName:e,elapsed:r,params:n,result:o}){let i=yr();if(typeof i!="object")return;let s={method:e},a=o?.error&&(i.errors===!0||Array.isArray(i.errors)&&i.errors.includes(e)),c=Array.isArray(i.params)&&i.params?.includes(e),u=i.params&&!Array.isArray(i.params)||c,p=Array.isArray(i.exclude)&&i.exclude.includes(e);!p&&![void 0,!1].includes(i.perf)&&!isNaN(i.perf)&&r>=i.perf&&(s.elapsed=r),!p&&(a||u)&&(s.params=n),!p&&(a||i.result&&!Array.isArray(i.result)&&(!Array.isArray(i.params)||c)||Array.isArray(i.result)&&i.result?.includes(e))&&(s.result=o),Object.keys(s).length>1&&fE(s,t)}function Ga({methodName:t,params:e,start:r}){let n={error:za,methodName:t},o=r?Date.now()-r:0;return zA({result:n,methodName:t,elapsed:o,params:e,engineType:"sync"}),n}function Fx(t,e){if(e._middleware===!1)return e;if(e.tournamentId&&!t[e.tournamentId])return{error:W};let r=e.drawId||e.matchUp?.drawId;if(r){let{event:i,drawDefinition:s,tournamentId:a}=We({tournamentRecords:t,drawId:r});s&&(e.drawDefinition=s),a&&(e.tournamentId=a),i&&(e.event=i)}if(e.eventId&&!e.event){let{event:i,tournamentId:s}=We({eventId:e.eventId,tournamentRecords:t});if(!i)return{error:mr};e.tournamentId=s,e.event=i}let n=e.tournamentId??$i();if(!n&&e)return e;let o=t[n];return n&&!o?{error:W}:(o&&(e.tournamentRecord=o),e)}function ka(t,e,r,n,o){delete t.success,delete t.error;let i=Date.now(),s=$i();r&&(r.activeTournamentId=s);let a=r?.tournamentRecord||Wl(s),c=typeof r?.tournamentRecord=="object"&&{[r?.tournamentRecord.tournamentId]:r.tournamentRecord}||Mo(),u=r?J(r,void 0,!0):void 0,p=r?Fx(c,r):void 0;if(p?.error)return p;let m=y1({params:p,tournamentRecords:c,tournamentRecord:a,methodName:n,method:e}),d=Date.now()-i;return zA({result:m,methodName:n,elapsed:d,params:u,engineType:o}),m}function y1({tournamentRecords:t,tournamentRecord:e,params:r,methodName:n,method:o}){if(yr())return o({tournamentRecords:t,tournamentRecord:e,...r});try{return o({tournamentRecords:t,tournamentRecord:e,...r})}catch(i){return Xu({engineName:"engine",methodName:n,params:r,err:i})}}function Gu(t){let{mutationStatus:e,tournamentId:r,directives:n,timeStamp:o}=t||{},{topics:i}=Cr();for(let s of[...i].sort(kx)){let a=DI({topic:s});a?.length&&um({topic:s,notices:a})}e&&o&&i.includes(_m)&&um({notices:[{tournamentId:r,directives:n,timeStamp:o}],topic:_m})}async function QA(t){let{mutationStatus:e,tournamentId:r,directives:n,timeStamp:o}=t||{},{topics:i}=Cr();for(let s of[...i].sort(kx)){let a=DI({topic:s});a&&await um({topic:s,notices:a})}e&&o&&i.includes(_m)&&um({notices:[{tournamentId:r,directives:n,timeStamp:o}],topic:_m})}var Gx={[Tf]:5,[Sf]:5,[Af]:5,[hf]:5,[If]:5,[ff]:5,[VE]:5,[BE]:5,[gf]:1,[up]:1,[Qe]:5,[ui]:5,[lf]:4,[pf]:4,[mf]:4,[df]:4,[cp]:3,[cf]:2};function kx(t,e){return(Gx[e]||0)-(Gx[t]||0)}function Vx({convertExtensions:t,removeExtensions:e}){let r=Mo();return{tournamentId:$i(),tournamentRecords:J(r,t,!1,e)}}function Bx(t){let{convertExtensions:e=!1,removeExtensions:r=!1}=t??{},n=t?.tournamentId??$i();if(typeof n!="string")return{};let o=Wl(n);return{tournamentRecord:J(o,e,!1,r)}}function Hx(){let t=Mo(),{extension:e}=mt({name:pa,tournamentRecords:t,discover:!0}),r=e?.value?.tournamentIds||[];return Object.keys(t).forEach(n=>{r.includes(n)||delete t[n]}),pm(t)}function IC(t,e=!0){return typeof t!="object"||Array.isArray(t)?{error:Xn}:t?.tournamentId?dE(e?J(t):t):{error:G}}function Ts(t,e=!0){if(typeof t!="object")return{error:Xn};if(Qu(),Array.isArray(t)){if(!(t.filter(n=>n?.tournamentId).length===t.length))return{error:cI};t=Object.assign({},...t.map(n=>({[n.tournamentId]:n})))}else if(t?.tournamentId)t={[t.tournamentId]:t},Qu(t.tournamentId);else if(!Object.keys(t).every(n=>t[n].tournamentId===n))return{error:cI};return pm(e?J(t):t)}async function Wx(t,e,r){if(!Array.isArray(e))return{error:G,message:"directives must be an array"};let n=Hl(),o=Date.now(),i=r&&J(Mo(),!1,!0),s=[];for(let p of e){if(typeof p!="object")return{error:G,message:"directive must be an object"};let{method:m,pipe:d}=p,l=p.params?{...p.params}:{};if(!n[m])return Ga({methodName:m,start:o,params:l});if(d){let g=s[s.length-1],I=Object.keys(d);for(let h of I)g[h]&&(l[h]=g[h])}let f=ka(t,n[m],l,m,"async");if(f?.error)return i&&Ts(i),{...f,rolledBack:!!i};s.push({...f,methodName:m})}let a=Date.now(),c=Fu({timeStamp:a});return await QA({directives:e,mutationStatus:c,timeStamp:a}),Ci(),{success:s.every(p=>p.success),results:s}}async function hC(t,e){if(!Rt(e))return{error:G,message:"args must be an object"};let r=Object.values(e).filter(Mr).length;if(r>1)return{message:"there must be only one arg with typeof function",error:G};let n=r?Object.keys(e).find(l=>Mr(e[l])):$e(e.method)&&e.method;if(!n)return{error:za};let{[n]:o,...i}=e,s=e?.params?{...e.params}:{...i},a=s.rollbackOnError&&J(Mo(),!1,!0),c=o||t[n]||zu()[n];if(!c)return Ga({methodName:n,params:s});let u=await ka(t,c,s,n,"async")??{};u?.error&&a&&Ts(a);let p=Date.now(),m=Fu({timeStamp:p}),d=u?.success&&s?.delayNotify!==!0&&s?.doNotNotify!==!0;return d&&await QA({directives:[{method:c,params:s}],mutationStatus:m,timeStamp:p}),(d||!u?.success||s?.doNotNotify)&&Ci(),u}function jx(t,e,r,n,o,i){let s=gE(r,n,o,i);if(s.error)return s;let a=s.methods??[];return Object.keys(a).filter(u=>Mr(a[u])).forEach(u=>{t[u]=p=>{let m=()=>e(t,{[u]:a[u],...p});if(yr())return m();try{return m()}catch(d){Xu({engineName:"engine",methodName:u,params:p,err:d})}}}),{...R,...t}}function tm(t,e){return e?.error?(t.error=e.error,t.success=!1):(t.error=void 0,t.success=!0),t}function ml(t,e){t.importMethods=(r,n,o,i)=>jx(t,e,r,n,o,i),t.getTournament=r=>Bx(r),t.getState=r=>Vx({convertExtensions:r?.convertExtensions,removeExtensions:r?.removeExtensions}),t.version=()=>Va(),t.reset=()=>(pm({}),tm(t)),t.devContext=r=>(kc(r),tm(t)),t.getDevContext=r=>yr(r),t.newTournamentRecord=(r={})=>{let n=AA(r),o=n.tournamentId;return n.error?n:(IC(n),Qu(o),{...R,tournamentId:o})},t.setState=(r,n,o)=>{Vc(n,o);let i=Ts(r,n);return tm(t,i)},t.setTournamentId=r=>Qu(r),t.getTournamentId=()=>$i(),t.setTournamentRecord=(r,n,o)=>{Vc(n,o);let i=IC(r,n);return tm(t,i)},t.removeTournamentRecord=r=>{let n=lE(r);return tm(t,n)},t.removeUnlinkedTournamentRecords=()=>{let r=Hx();return tm(t,r)}}function E1(t){let e=pE();if(e.error&&!t)return e;let r={executionQueue:(n,o)=>Wx(r,n,o),execute:n=>hC(r,n)};return ml(r,hC),r}function Yx(t,e,r){if(!Array.isArray(e))return{error:G,message:"directives must be an array"};let n=Hl(),o=Date.now(),i=r&&J(Mo(),!1,!0),s=[];for(let p of e){if(typeof p!="object")return{error:G,message:"directive must be an object"};if(p.params&&typeof p.params!="object")return{error:G,message:"params must be an object"};let{method:m,pipe:d}=p,l=p.params?{...p.params}:{};if(!n[m])return Ga({methodName:m,start:o,params:l});if(d){let g=s[s.length-1],I=Object.keys(d);for(let h of I)g[h]&&(l[h]=g[h])}let f=ka(t,n[m],l,m,"sync");if(f?.error)return i&&Ts(i),{...f,rolledBack:!!i};s.push({...f,methodName:m})}let a=Date.now(),c=Fu({timeStamp:a});return Gu({directives:e,mutationStatus:c,timeStamp:a}),Ci(),{success:s.every(p=>p.success),results:s}}function SC(t,e){if(!Rt(e))return{error:G,message:"args must be an object"};let r=Object.values(e).filter(Mr).length;if(r>1)return{message:"there must be only one arg with typeof function",error:G};let n=r?Object.keys(e).find(l=>Mr(e[l])):$e(e.method)&&e.method;if(!n)return{error:za};let{[n]:o,...i}=e,s=e?.params?{...e.params}:{...i},a=s.rollbackOnError&&J(Mo(),!1,!0),c=o||t[n]||zu()[n];if(!c)return Ga({methodName:n,params:s});let u=ka(t,c,s,n,"sync")??{};u?.error&&a&&Ts(a);let p=Date.now(),m=Fu({timeStamp:p}),d=u?.success&&s?.delayNotify!==!0&&s?.doNotNotify!==!0;return d&&Gu({directives:[{method:c,params:s}],mutationStatus:m,timeStamp:p}),(d||!u?.success||s?.doNotNotify)&&Ci(),u}var qx=(()=>{let t={executionQueue:(e,r)=>Yx(t,e,r),execute:e=>SC(t,e)};return ml(t,SC),t})(),em=qx;function TC(t,e){if(!Rt(e))return{error:G,message:"args must be an object"};let r=Object.values(e).filter(Mr).length;if(r>1)return{message:"there must be only one arg with typeof function",error:G};let n=r?Object.keys(e).find(c=>Mr(e[c])):$e(e.method)&&e.method;if(!n)return{error:za};let{[n]:o,...i}=e,s=e?.params?{...e.params}:{...i},a=o||t[n]||zu()[n];return a?ka(t,a,s,n,"ask"):Ga({methodName:n,params:s})}var U1=(()=>{let t={execute:e=>TC(t,e)};return ml(t,TC),t})();var rm={},xc;function AC(t,e=!0){if(!t)return{error:et};if(typeof t!="object")return{error:Xn};if(t.matchUpId)xc=t.matchUpId,rm[xc]=e?J(t):t;else if(Array.isArray(t))for(let r of t.reverse())r.matchUpId&&(rm[r.matchUpId]=e?J(r):r,xc||(xc=r.matchUpId));else for(let r of Object.values(t))r.matchUpId&&(rm[r.matchUpId]=e?J(r):r,xc||(xc=r.matchUpId));return e?J(t):t}function $x(){return rm[xc]}function Kx(){return Object.values(rm)}function zx(){xc=void 0,rm={}}function Qx(t){return J(rm[xc],t?.convertExtensions,!1,t?.removeExtensions)}var P1=(()=>{let t={getState:o=>Qx(o),version:()=>Va(),reset:()=>(zx(),{...R}),drawId:void 0,error:void 0,success:!1,devContext:o=>(kc(o),t),setState:(o,i,s)=>{Vc(i,s);let a=AC(o);return e(a)}};function e(o){return o?.error?(t.error=o.error,t.success=!1):(t.error=void 0,t.success=!0,t.drawId=o.drawId),t}return r([yg]),t;function r(o){o.forEach(i=>{Object.keys(i).forEach(s=>{t[s]=a=>{if(yr())return n({params:a,governor:i,methodName:s});try{return n({params:a,governor:i,methodName:s})}catch(c){Xu({engineName:"matchUpEngine",methodName:s,params:a,err:c})}}})})}function n({params:o,governor:i,methodName:s}){t.error=void 0,t.success=!1;let a=o?.matchUp||$x(),c=o?.matchUps||Kx(),u=o?.rollbackOnError&&J(a,!1,!0);o={...o,matchUpId:a?.matchUpId,matchUps:c,matchUp:a};let p=i[s](o);if(p?.error)return u&&AC(u),{...p,rolledBack:!!u};let m=p?.success&&o?.delayNotify!==!0&&o?.doNotNotify!==!0;return m&&Gu(),(m||!p?.success||o?.doNotNotify)&&Ci(),p}})();var yC=!1,D1=(()=>{let t={version:()=>Va(),setDeepCopy:(n,o)=>(Vc(n,o),t),devContext:n=>(kc(n),yC=!0,t)};return r([$g]),t;function e(n,o){let i=n({...o});return i?.error||Gu(),Ci(),yC&&(kc(!1),yC=!1),i}function r(n){n.forEach(o=>{Object.keys(o).forEach(i=>{t[i]=s=>{try{let a=e(o[i],s);return!a?.error&&s?.setState&&a?.tournamentRecord&&Ts(a.tournamentRecord),a}catch(a){let c;typeof a=="string"?c=a.toUpperCase():a instanceof Error&&(c=a.message),console.log("ERROR",{params:JSON.stringify(s),method:i,error:c})}}})})}})();em.importMethods($A,!0,1);var N1=em,M1=em;function XA(t,e){return t&&e&&Array.isArray(e)&&e[t-1]||typeof e=="object"&&e[t]}function Xx(t){let{participation:e={},awardProfiles:r,startDate:n,eventType:o,drawSize:i,drawType:s,category:a,endDate:c,level:u}=t,{participationOrder:p,flightNumber:m,rankingStage:d}=e,l=g=>!n&&!c||!g.dateRanges?!0:g.dateRanges.some(I=>{let h=!n||!I.startDate||new Date(n)>new Date(I.startDate),S=!c||!I.endDate||new Date(c)<=new Date(I.endDate);return h&&S});return{awardProfile:r.find(g=>l(g)&&(!g.maxFlightNumber||m<=g.maxFlightNumber)&&(!g.drawTypes?.length||g.drawTypes?.includes(s))&&(!g.drawSizes?.length||g.drawSizes.includes(i))&&(!g.stages?.length||g.stages.includes(d))&&(!g.levels?.length||g.levels.includes(u))&&(!g.maxDrawSize||i<=g.maxDrawSize)&&(!g.drawSize||g.drawSize===i)&&(!g.maxLevel||u<=g.maxLevel)&&(!m||!g.flights?.flightNumbers?.length||g.flights.flightNumbers.includes(m))&&(!g.participationOrder||g.participationOrder===p)&&(!g.category?.ageCategoryCodes||g.category.ageCategoryCodes.includes(a?.ageCategoryCode))&&(!g.eventTypes?.length||g.eventTypes?.includes(o)))}}function EC({participantWon:t,flightNumber:e,valueObj:r,drawSize:n,flights:o,level:i}){let s=(f,g)=>{if(f){if(Array.isArray(g)){let I=g.find(h=>h.flight===f||h.f===f);return I.value||I.v}if(typeof g=="object"){let I=g.flights||g.f;if(Array.isArray(I))return I[f-1]}}},a=(f,g)=>{let I=f?.value||f?.v||(ft(f)?f:0),h=XA(i,f?.level);return{value:s(g,h)||ft(h)&&h||I}},c=0,u,p,m,d,l=t&&"won"||t===!1&&"lost"||void 0;if(Array.isArray(r)){let f=r.find(h=>h.drawSize===n||h.drawSizes?.includes(n)),g=r.find(h=>h.drawSize&&h.threshold&&n>h.drawSize),I=r.find(h=>!h.drawSize&&!h.drawSizes?.length);l!==void 0&&(f=f?.[l],g=g?.[l],I=I?.[l]),p=a(f,e).value,m=a(g,e).value,d=a(I,e).value,c=p||m||d,u=p&&f.requireWin||m&&g.requireWin||I?.requireWin}else if(typeof r=="object"){let f=r?.drawSizes?.[n],g=r;l!==void 0&&(f=f?.[l],g=g?.[l]),p=a(f,e).value,d=a(g,e).value,c=p||d,u=p?f.requireWin:g?.requireWin}else ft(r)&&l===void 0&&(c=r);return e&&o?.pct?.[e]&&(c=Math.round(c*o.pct[e])),{awardPoints:c,requireWin:u}}function Jx({participantFilters:t,policyDefinitions:e,tournamentRecord:r,level:n}){if(!r)return{error:W};let{policyDefinitions:o}=yo({policyTypes:[Zl],tournamentRecord:r}),i=e?.[Zl]??o?.[Zl];if(!i)return{error:Bu};let s=i.awardProfiles,a=i.requireWinFirstRound,c=i.requireWinForPoints,{participants:u,derivedEventInfo:p,derivedDrawInfo:m,mappedMatchUps:d}=Yt({withRankingProfile:!0,participantFilters:t,tournamentRecord:r}),l=u?.filter(h=>h.draws?.length),f={},g={},I={};for(let h of l??[]){let{participantType:S,participantId:T,person:A,draws:D}=h;for(let y of D){let{drawId:E,structureParticipation:U,eventId:M}=y,P=p[M],N=m[E],C=N?.drawType,{category:O,eventType:b}=P||{},x=y.startDate||P.startDate||r.startDate,w=y.endDate||P.endDate||r.endDate;if(b===kr&&T!==Jr)continue;let F;if(s){let L=c,v=0,B=0,H=0,j;for(let V of U){let{finishingPositionRange:Y,participationOrder:$,participantWon:k,flightNumber:K,rankingStage:z,winCount:q}=V;v+=q||0;let nt=N?.drawSize,{awardProfile:Q}=Xx({awardProfiles:s,participation:V,eventType:b,startDate:x,category:O,drawSize:nt,drawType:C,endDate:w,level:n});if(Q){if(!nt)continue;let it=Array.isArray(Y)&&Math.max(...Y),ot=pt(Y||[]).join("-"),ut=it&&z!==at&&Y?.includes(nt);Q.requireWinForPoints!==void 0&&(L=Q.requireWinForPoints),Q.requireWinFirstRound!==void 0&&(a=Q.requireWinFirstRound);let{finishingPositionPoints:Qt={},finishingPositionRanges:yt,finishingRound:Me,pointsPerWin:Ee,flights:Ce}=Q,Kt=Array.isArray(Q.perWinPoints)?Q.perWinPoints?.find(vt=>vt.participationOrders?.includes($)):Q.perWinPoints,Re=Qt.participationOrders,wt=0,Ue;if((!Re||Re.includes($))&&yt&&it){let vt=yt[it];vt&&({awardPoints:wt,requireWin:Ue}=EC({flightNumber:K,valueObj:vt,drawSize:nt,flights:Ce,level:n}))}if(!wt&&Me&&$===1&&it){let vt=Me[it];vt&&({awardPoints:wt,requireWin:Ue}=EC({participantWon:k,flightNumber:K,valueObj:vt,drawSize:nt,flights:Ce,level:n}))}if(ut&&a!==void 0&&(L=a),Ue!==void 0&&(L=Ue),wt>B&&(!L||q)&&(B=wt,j=it),!wt&&Ee&&q&&(H+=q*Ee,j=ot),!wt&&q&&Kt){let vt=XA(n,Kt?.level);vt?H+=q*vt:Kt.value&&(H+=q*Kt.value)}}if(F=B+H,S===Jr){let it=(h.matchUps||[]).filter(({structureId:ot})=>ot===V.structureId);for(let{matchUpId:ot}of it){let ut=d[ot],Qt=ut.sides.find(yt=>yt.participantId===T).sideNumber;if(ut.winningSice===Qt)for(let yt of ut.tieMatchUps)yt.winningSide}}}if(H||B){let V={winCount:v,positionPoints:B,rangeAccessor:j,perWinPoints:H,eventType:b,drawId:E,points:F},Y=A?.personId;Y?(f[Y]||(f[Y]=[]),f[Y].push(V)):S===dt?(I[T]||(I[T]=[]),I[T].push(V)):S===Jr&&(g[T]||(g[T]=[]),g[T].push(V))}}}}return{participantsWithOutcomes:l,personPoints:f,pairPoints:I,teamPoints:g,...R}}var C1={getTournamentPoints:Jx},Zx=C1;var R1={calculateNewRatings:xS,generateDynamicRatings:wS},tw=R1;var b1={...Zx,...tw};em.importMethods(b1);var O1=em;var ew={[Wc]:{roundsToSeparate:void 0,policyName:"Nationality Code",policyAttributes:[{key:"person.nationalityCode"},{key:"individualParticipants.person.nationalityCode"}]}};var rw={[no]:{policyName:"positionActionsUnrestricted",enabledStructures:[],otherFlightEntries:!0,disableRoundRestrictions:!0,activePositionOverrides:[js,Mp]}};var nw={[no]:{policyName:"positionActionsNoMovement",enabledStructures:[{stages:[],stageSequences:[],enabledActions:[js,Uu,Ys],disabledActions:[]}]}};var ow={[no]:{policyName:"positionActionsDisabled",enabledStructures:!1}};var iw={[Os]:{policyName:"Participant Privacy Policy",participant:{contacts:!1,individualParticipants:{onlineResources:!1,participantName:!0,participantOtherName:!0,participantId:!0,participantRole:!0,participantStatus:!0,penalties:!1,representing:!0,participantRoleResponsibilities:!1,participantType:!0,person:{addresses:!1,biographicalInformation:!1,birthDate:!1,contacts:!1,nationalityCode:!0,nativeFamilyName:!1,nativeGivenName:!1,onlineResources:!1,otherNames:!0,parentOrganisationId:!1,passportFamilyName:!1,passportGivenName:!1,personId:!1,personOtherIds:!1,previousNames:!1,sex:!1,standardFamilyName:!0,standardGivenName:!0,status:!1,tennisId:!1,wheelchair:!0}},individualParticipantIds:!0,onlineResources:!1,participantName:!0,participantOtherName:!0,participantId:!0,participantRole:!0,participantStatus:!0,penalties:!1,representing:!0,participantRoleResponsibilities:!1,participantType:!0,person:{addresses:!1,biographicalInformation:!1,birthDate:!1,contacts:!1,nationalityCode:!0,nativeFamilyName:!1,nativeGivenName:!1,onlineResources:!1,otherNames:!0,parentOrganisationId:!1,passportFamilyName:!1,passportGivenName:!1,personId:!1,personOtherIds:!1,previousNames:!1,sex:!1,standardFamilyName:!0,standardGivenName:!0,status:!1,tennisId:!1,wheelchair:!0}}}};var sw={[vn]:{defaultMatchUpFormat:un,allowDeletionWithScoresPresent:{drawDefinitions:!1,structures:!1},requireAllPositionsAssigned:!1,processCodes:{incompleteAssignmentsOnDefault:["RANKING.IGNORE"]},stage:{[tt]:{stageSequence:{1:{requireAllPositionsAssigned:!0}}}}}};var aw={[vn]:{requireAllPositionsAssigned:!1,stage:{[tt]:{stageSequence:{1:{requireAllPositionsAssigned:!0}}}},defaultMatchUpFormat:un,matchUpFormats:[{description:"Best of 3 tiebreak sets",matchUpFormat:un,categoryNames:[],categoryTypes:[]},{description:"Two tiebreak sets, 7-point match tiebreak at one set all",matchUpFormat:"SET3-S:6/TB7-F:TB7"},{description:"Two tiebreak sets, 10-point match tiebreak at one set all",matchUpFormat:"SET3-S:6/TB7-F:TB10"},{description:"One standard tiebreak set to 6, 7-point tiebreak at 6 games all",matchUpFormat:"SET1-S:6/TB7"},{description:"Best of 3 sets to 4",matchUpFormat:"SET3-S:4/TB7"},{description:"Two out of three short sets to 4 with 5-point tiebreak at 3 games all",matchUpFormat:"SET3-S:4/TB5@3"},{description:"One short set to 4, 7-point tiebreak at 4 games all",matchUpFormat:"SET1-S:4/TB7"},{description:"One short set to 4, 5-point tiebreak at 3 games all",matchUpFormat:"SET1-S:4/TB5@3"},{description:"Two short sets to 4, 10-point match tiebreak at one set all",matchUpFormat:"SET3-S:4/TB7-F:TB10"},{description:"Two short sets to 4, 7-point match tiebreak at one set all",matchUpFormat:"SET3-S:4/TB7-F:TB7"},{description:"One no advantage set to 5, tiebreak to 9 at 4-4",matchUpFormat:"SET1-S:5/TB9@4"},{description:"One set to 6 with deciding game at 5 games all",matchUpFormat:"SET1-S:6NOAD"},{description:"One short set to 4, deciding game is played at 3 games all",matchUpFormat:"SET1-S:4NOAD"},{description:"Two short sets to 4 with deciding game at 3-3, 7-point match tiebreak at one set all",matchUpFormat:"SET3-S:4NOAD-F:TB7"},{description:"8 game pro-set with 7 point tiebreak at 8 games all",matchUpFormat:"SET1-S:8/TB7"},{description:"8 game pro-set with 7 point tiebreak at 7 games all",matchUpFormat:"SET1-S:8/TB7@7"},{description:"Best of 3 10-point tiebreak games",matchUpFormat:"SET3-S:TB10"},{description:"One 10-point tiebreak game",matchUpFormat:"SET1-S:TB10"},{description:"Timed 20 minute game - game based",matchUpFormat:"SET1-S:T20"}]}};var cw={[Un]:{seedingProfile:{positioning:zc},validSeedPositions:{ignore:!0},duplicateSeedNumbers:!0,drawSizeProgression:!0,policyName:"ITF SEEDING",seedsCountThresholds:[{drawSize:4,minimumParticipantCount:3,seedsCount:2},{drawSize:16,minimumParticipantCount:12,seedsCount:4},{drawSize:32,minimumParticipantCount:24,seedsCount:8},{drawSize:64,minimumParticipantCount:48,seedsCount:16},{drawSize:128,minimumParticipantCount:97,seedsCount:32},{drawSize:256,minimumParticipantCount:192,seedsCount:64}]}};var uw={POLICY_AVOIDANCE_COUNTRY:ew,POLICY_POSITION_ACTIONS_DEFAULT:hS,POLICY_POSITION_ACTIONS_DISABLED:ow,POLICY_POSITION_ACTIONS_NO_MOVEMENT:nw,POLICY_POSITION_ACTIONS_UNRESTRICTED:rw,POLICY_PRIVACY_DEFAULT:iw,POLICY_ROUND_NAMING_DEFAULT:wf,POLICY_SCHEDULING_DEFAULT:$D,POLICY_SCORING_DEFAULT:sw,POLICY_SCORING_USTA:aw,POLICY_SEEDING_ITF:cw,POLICY_SEEDING_DEFAULT:_D};var _1={ratingsParameters:Br,matchUpFormats:uO,countryToFlag:aU,tieFormats:tA,countries:Xo,policies:uw,flagIOC:ub};var lw={};Jt(lw,{activeMatchUpStatuses:()=>Nm,auditConstants:()=>Iv,completedMatchUpStatuses:()=>ae,directingMatchUpStatuses:()=>YI,drawDefinitionConstants:()=>kE,entryStatusConstants:()=>DR,errorConditionConstants:()=>LC,eventConstants:()=>kR,extensionConstants:()=>HI,flightConstants:()=>Pv,genderConstants:()=>Km,keyValueConstants:()=>l_,matchUpActionConstants:()=>kO,matchUpStatusConstants:()=>KI,matchUpTypes:()=>UR,nonDirectingMatchUpStatuses:()=>qI,particicipantsRequiredMatchUpStatuses:()=>WI,participantConstants:()=>PR,participantRoles:()=>Xm,participantTypes:()=>nu,penaltyConstants:()=>pw,policyConstants:()=>lR,positionActionConstants:()=>LO,ratingConstants:()=>t_,recoveryTimeRequiredMatchUpStatuses:()=>gR,requestConstants:()=>tx,resultConstants:()=>OC,scaleConstants:()=>aR,scheduleConstants:()=>GR,sortingConstants:()=>Nv,surfaceConstants:()=>mw,tieFormatConstants:()=>F_,timeItemConstants:()=>wR,topicConstants:()=>AR,tournamentConstants:()=>jA,upcomingMatchUpStatuses:()=>$I,validMatchUpStatuses:()=>jI,venueConstants:()=>dw});var v1="Coaching",x1="Ball Abuse",w1="Racket Abuse",L1="Verbal Abuse",F1="INELIGIBILITY",G1="Physical Abuse",k1="Unsportmanlike Conduct",V1="Dress Code Violation",B1="Equipment Violation",H1="Leaving the court",W1="Failure to complete",j1="No Show",Y1="Other",q1="REFUSAL_TO_PLAY",$1="PROHIBITED_SUBSTANCE",K1="Puncuality",z1="Failure to sign in",pw={COACHING:v1,BALL_ABUSE:x1,RACKET_ABUSE:w1,VERBAL_ABUSE:L1,PHYSICAL_ABUSE:G1,INELIGIBILITY:F1,UNSPORTSMANLIKE_CONDUCT:k1,PROHIBITED_SUBSTANCE:$1,DRESS_CODE_VIOLATION:V1,EQUIMENT_VIOLATION:B1,LEAVING_THE_COURT:H1,REFUSAL_TO_PLAY:q1,FAILURE_TO_COMPLETE:W1,NO_SHOW:j1,OTHER:Y1,PUNCTUALITY:K1,FAILUIRE_TO_SIGN_IN:z1};var Q1="CLAY",X1="HARD",J1="GRASS",Z1="CARPET",t0="ARTIFICIAL",mw={CLAY:Q1,HARD:X1,GRASS:J1,CARPET:Z1,ARTIFICIAL:t0};var e0="INDOOR",r0="OUTDOOR",dw={INDOOR:e0,OUTDOOR:r0};export{Nm as activeMatchUpStatuses,U1 as askEngine,E1 as asyncEngine,Iv as auditConstants,N1 as competitionEngine,CE as competitionGovernor,ae as completedMatchUpStatuses,YI as directingMatchUpStatuses,kE as drawDefinitionConstants,ZD as drawsGovernor,sN as entriesGovernor,DR as entryStatusConstants,LC as errorConditionConstants,kR as eventConstants,TN as eventGovernor,HI as extensionConstants,lw as factoryConstants,_1 as fixtures,Pv as flightConstants,A1 as forge,Km as genderConstants,PN as generationGovernor,QC as globalState,$A as governors,l_ as keyValueConstants,kO as matchUpActionConstants,P1 as matchUpEngine,iA as matchUpFormatCode,iA as matchUpFormatGovernor,jN as matchUpGovernor,KI as matchUpStatusConstants,UR as matchUpTypes,D1 as mocksEngine,$g as mocksGovernor,qI as nonDirectingMatchUpStatuses,WI as particicipantsRequiredMatchUpStatuses,PR as participantConstants,TM as participantGovernor,Xm as participantRoles,nu as participantTypes,pw as penaltyConstants,lR as policyConstants,OD as policyGovernor,LO as positionActionConstants,NM as publishingGovernor,XD as queryGovernor,t_ as ratingConstants,gR as recoveryTimeRequiredMatchUpStatuses,MM as reportGovernor,tx as requestConstants,OC as resultConstants,aR as scaleConstants,O1 as scaleEngine,GR as scheduleConstants,kM as scheduleGovernor,yg as scoreGovernor,Nv as sortingConstants,mw as surfaceConstants,qx as syncEngine,F_ as tieFormatConstants,zM as tieFormatGovernor,wR as timeItemConstants,gC as tools,AR as topicConstants,jA as tournamentConstants,M1 as tournamentEngine,oC as tournamentGovernor,$I as upcomingMatchUpStatuses,gC as utilities,jI as validMatchUpStatuses,dw as venueConstants,fC as venueGovernor,Va as version};
|