tods-competition-factory 3.2.1 → 3.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- var aH=Object.defineProperty;var Gt=(t,e)=>{for(var r in e)aH(t,r,{get:e[r],enumerable:!0})};var kx="3.2.1";function ns(){return kx}var qN={};Gt(qN,{competitionGovernor:()=>jR,drawsGovernor:()=>rv,entriesGovernor:()=>pv,eventGovernor:()=>Nv,generationGovernor:()=>Cv,matchUpFormatGovernor:()=>WP,matchUpGovernor:()=>zv,mocksGovernor:()=>Ch,officiatingGovernor:()=>rx,participantGovernor:()=>DO,policyGovernor:()=>OM,publishingGovernor:()=>wO,queryGovernor:()=>tv,rankingGovernor:()=>Mh,reportGovernor:()=>HO,scheduleGovernor:()=>r_,scoreGovernor:()=>th,temporalGovernor:()=>j_,tieFormatGovernor:()=>d_,tournamentGovernor:()=>M_,venueGovernor:()=>lx});var jR={};Gt(jR,{getCompetitionLeaderboard:()=>ky,getCompetitionParticipantState:()=>Fy,getCompetitionPolicy:()=>To,getCompetitionState:()=>Fo,getLinkedTournamentIds:()=>Np,getTournamentIds:()=>$m,initializeCompetitionState:()=>kR,linkTournaments:()=>NR,mutate:()=>WR,processCompetitionMatchUp:()=>Km,processCompetitionRound:()=>BR,query:()=>YR,resetCompetitionState:()=>HR,unlinkTournament:()=>DR,unlinkTournaments:()=>UR});var WR={};Gt(WR,{initializeCompetitionState:()=>kR,linkTournaments:()=>NR,processCompetitionMatchUp:()=>Km,processCompetitionRound:()=>BR,resetCompetitionState:()=>HR,unlinkTournament:()=>DR,unlinkTournaments:()=>UR});var bs="SINGLES",Ct="SINGLES",Qo="DOUBLES",Rt="DOUBLES",Ir="TEAM",Ot="TEAM",uH="HYBRID",Um="HYBRID",Gx={SINGLES_MATCHUP:bs,SINGLES:Ct,DOUBLES_MATCHUP:Qo,DOUBLES:Rt,TEAM_MATCHUP:Ir,TEAM:Ot,HYBRID_MATCHUP:uH,HYBRID:Um};var NT={[Ct]:[Ct,"S"],[Rt]:[Rt,"D"],[Ot]:[Ot,"T"],[Um]:[Um,"H"],S:[Ct,"S"],D:[Rt,"D"],T:[Ot,"T"],H:[Um,"H"]};function Zt(t,e){return(t??0)-(e??0)}function st(t){return typeof t=="number"?parseInt(t.toString()):typeof t=="string"?parseInt(t):0}function kr(t){return typeof t=="function"}function _t(t){return typeof t=="string"}function Tt(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Vx(t,e){if(!Tt(t)||!Tt(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 DT(t,e){return Array.isArray(t)?Object.assign({},...(t??[]).filter(Tt).map(r=>r[e]&&{[r[e]]:r}).filter(Boolean)):{}}var Bx=t=>e=>Object.keys(t).every(r=>e[r]===t[r]);function UT(t,e){if(t===void 0)return null;if(!Tt(t)||t===null)return t;let r=Object.keys(t),n=o=>o===void 0?null:o;return Object.assign({},...r.map(o=>Array.isArray(t[o])?{[o]:e?t[o]:t[o].map(i=>UT(i))}:{[o]:e?n(t[o]):UT(t[o])}))}function pU(t){return Array.isArray(t)?t.length+t.map(pU).reduce((e,r)=>e+r,0):Tt(t)&&t!==null?Object.keys(t).length+Object.keys(t).map(e=>pU(t[e])).reduce((e,r)=>e+r,0):0}function Hx(t){if(t===null||typeof t!="object")return;let e=JSON.stringify(t),r=pU(t),n=e.split("").reduce((o,i)=>o+i.charCodeAt(0),0);return[e.length,r,n].map(o=>o.toString(36)).join("")}function en(t){return Number.isNaN(Number(t))?!1:t>0&&(t&t-1)===0}function Wx(t){if(!t.length)return;let e=[...t].sort(Zt),r=Math.floor(e.length/2);return e.length%2?e[r]:(e[r-1]+e[r])/2}function Yx(t){if(t===1||Number.isNaN(Number(t))||!en(t))return!1;let e=t,r=1;for(;e!==2;)r+=1,e=e/2;return r}function Jd(t){return Number.isNaN(Number(t))?0:t%2&&t+1||t}function Zd(t){return Math.pow(2,Math.round(Math.log(t)/Math.log(2)))}function Le(t){return!Number.isNaN(Number.parseFloat(t))}function RT(t){let e=st(t);if(!Number.isNaN(e))return e===0?!1:(e&-e)===1}function Si(t){if(Number.isNaN(Number(t)))return!1;for(;!en(t);)t++;return t}function pn(t,e,r){return t=Math.ceil(t),e=Math.floor(e),Math.floor((r??Math.random)()*(e-t+1))+t}function yt(t){return _t(t)&&!t.trim().length?!1:Number.isSafeInteger(typeof t=="string"?+t:t)}function jx(t=1,e=3,r=!0,n){let o=n??Math.random,i=0;for(let s=0;s<e;s++)i+=o()*(t/e);return r&&t>1?Math.round(i):i}function pH(t,e){e||(e=1);let r=1/e;return Math.round(t*r)/r}function mU(t,e,r,n,o=2,i){let s=i??Math.random,a=1-s(),c=1-s(),u=Math.sqrt(-2*Math.log(a))*Math.cos(2*Math.PI*c);return u=u/10+.5,u>1||u<0?u=mU(t,e,r,void 0,2,i):(u=Math.pow(u,r),u*=e-t,u+=t),n&&(u=pH(u,n)),Number.parseFloat(u.toFixed(o))}function vg(t,e=2){return Number.parseFloat(Number(Math.round(t*1e3)/1e3).toFixed(e))}function pt(t){return Array.isArray(t)?t?.filter((e,r,n)=>n.lastIndexOf(e)===r):[]}function qx(t){return Array.isArray(t)?t?.map(e=>e===null?void 0:e):t}function ar(t,e){if(!Array.isArray(t))return[];let r=e??Math.random;return t.map(n=>[r(),n]).sort((n,o)=>n[0]-o[0]).map(n=>n[1])}function Lc(t){return yt(t)?t:1/0}function mn(t){return Array.isArray(t)?t.reduce((e,r)=>(e[r]||(e[r]=0),e[r]++,e),{}):{}}function $x(t){return dU(mn(t))}function dU(t){return Object.keys(t).reduce((e,r)=>{let n=t[r];return e[n]?e[n].push(r):e[n]=[r],e},{})}function mH(t,e,r){return r.indexOf(t)===e}function bT(t){return t.filter(mH)}function Sr(t,e){return Array.isArray(t)&&t.length?t.splice(Math.floor((e??Math.random)()*t.length),1)[0]:void 0}function An(t,e){let r=Math.floor((e??Math.random)()*t.length);return t[r]}function Q(t,e){return Array.from({length:e-t},(r,n)=>n+t)}function os(t,e){return e.reduce((r,n,o)=>(n===t&&r.push(o),r),[])}function Yt(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 lU(t,e){return!Array.isArray(t)||!Array.isArray(e)?[]:t.filter(r=>!e.includes(r))}function Re(t,e){return!Array.isArray(t)||!Array.isArray(e)?!1:t.some(r=>e.includes(r))}function Kx(t,e){return Array.isArray(e)&&e.reduce((r,n)=>(r[n]=1+r[n]||1,r),{})[t]||0}function zx(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 he(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 fU(t,[e,...r]){return t.length?[t.slice(0,e),...fU(t.slice(e),[...r,e])]:[]}function Qx(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 CT(t){return Array.isArray(t)?t.reduce((e,r)=>!isNaN(parseInt(r))&&e,!0):!1}function MT(t){return Array.isArray(t)?t.reduce((e,r)=>isNaN(parseInt(r))&&e,!0):!1}function Og(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 Xx(t,e=1){if(!Array.isArray(t)||!t.every(yt))return[];let r=Math.min(...t,e),n=Math.max(...t);return Q(r,n+1).filter(o=>!t.includes(o))}function Cs(t,e){return!Array.isArray(t)||!_t(e)?!1:Yt(t,NT[e]).length}var P={success:!0},gU="error",Jx={SUCCESS:P,ERROR:gU};function vT({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}):{...P}}var dw={};Gt(dw,{addNotice:()=>at,callListener:()=>il,createInstanceState:()=>wD,cycleMutationStatus:()=>aI,deepCopyEnabled:()=>sI,deleteNotice:()=>YT,deleteNotices:()=>ss,disableNotifications:()=>LD,enableNotifications:()=>iI,getDevContext:()=>je,getMethods:()=>cI,getNotices:()=>WT,getProvider:()=>jT,getTopics:()=>br,getTournamentId:()=>_s,getTournamentRecord:()=>uI,getTournamentRecords:()=>Zo,globalLog:()=>GD,handleCaughtError:()=>_m,hasTopic:()=>Kc,removeTournamentRecord:()=>kD,setDeepCopy:()=>op,setDevContext:()=>np,setGlobalLog:()=>uw,setGlobalMethods:()=>pw,setGlobalSubscriptions:()=>HH,setMethods:()=>mw,setStateMethods:()=>VD,setStateProvider:()=>VH,setSubscriptions:()=>WH,setTournamentId:()=>Om,setTournamentRecord:()=>FD,setTournamentRecords:()=>sl,timeKeeper:()=>BH});var OT={message:"Chronological error; time violation.",code:"ANACHRONISM"},tl={message:"Duplicate entry",code:"DUPLICATE_ENTRY"},IU={message:"Cannot remove main structure",code:"ERR_CANNOT_REMOVE_MAIN_STRUCTURE"},_T={message:"records must be an object with tournamentId keys",code:"ERR_INVALID_TOURNAMENTS"},kt={message:"Missing tournamentRecords",code:"ERR_MISSING_TOURNAMENTS"},j={message:"Missing tournamentRecord",code:"ERR_MISSING_TOURNAMENT"},Fc={message:"Invalid tournamentRecord",code:"ERR_INVALID_TOURNAMENT"},Za={message:"Missing tournamentId",code:"ERR_MISSING_TOURNAMENT_ID"},ma={message:"Invalid drawDefinition",code:"ERR_INVALID_DRAWDEF"},$={message:"Missing drawDefinition",code:"ERR_MISSING_DRAWDEF"},SU={message:"Existing drawDefinition(s)",code:"ERR_EXISTING_DRAWDEFS"},Rr={message:"drawDefinition not found",code:"ERR_NOT_FOUND_DRAWDEF"},Do={message:"Invalid structure",code:"ERR_INVALID_STRUCTURE"},_g={message:"Incomplete source structure",code:"ERR_INCOMPLETE_STRUCTURE"},xg={message:"Invalid drawPosition for seedAssignment",code:"ERR_INVALID_SEEDING_POSITION"},kc={message:"drawPosition already assigned",code:"ERR_EXISTING_POSITION_ASSIGNMENT"},hU={message:"Schedule not cleared",code:"ERR_UNCHANGED_SCHEDULE_NOT_CLEARED"},TU={message:"Schedule conflict: court slot already occupied",code:"ERR_SCHEDULE_CONFLICT_DOUBLE_BOOKING"},yU={message:"Schedule conflict: matchUps scheduled outside court availability",code:"ERR_SCHEDULE_CONFLICT_COURT_UNAVAILABLE"},EU={message:"drawPosition not cleared",code:"ERR_FAILURE_POSITION_NOT_CLEARED"},dH={message:"drawPosition not found",code:"ERR_NOT_FOUND_DRAW_POSITION"},Qu={message:"Unrecognized drawType",code:"ERR_UNRECOGNIZED_DRAW_TYPE"},Gc={message:"Missing drawPositions",code:"ERR_MISSING_DRAW_POSITIONS"},Vc={message:"drawPosition is active",code:"ERR_ACTIVE_DRAW_POSITION"},Zx={message:"drawPosition is occupied",code:"ERR_OCCUPIED_DRAW_POSITION"},is={message:"Invlid drawPosition",code:"ERR_INVALID_DRAW_POSITION"},da={message:"Missing drawPosition",code:"ERR_MISSING_DRAW_POSITION"},el={message:"Invalid drawType",code:"ERR_INVALID_DRAW_TYPE"},Dm={message:"Invalid drawSize",code:"ERR_INVALID_DRAW_SIZE"},lH={message:"Cannot set drawSize to be less than existing entries",code:"ERR_INVALID_DRAW_SIZE_MISMATCH"},Bc={message:"Missing drawSize",code:"ERR_MISSING_DRAW_SIZE"},Pn={message:"Missing drawId",code:"ERR_MISSING_DRAW_ID"},AU={message:"drawId exists",code:"ERR_EXISTING_DRAW_ID"},PU={message:"participantId cannot be assigned to multiple seedNumbers",code:"INVALID_PARTICIPANT_SEEDING"},NU={message:"seedsCount greater than drawSize",code:"ERR_INVALID_SEED_COUNT"},UU={message:"Missing seedCountThresholds",code:"ERR_MISSING_SEED_COUNT_THRESHOLD"},DU={message:"Invalid action",code:"ERR_INVALID_ACTION"},xT={message:"Invalid assignment",code:"ERR_INVALID_ASSIGNMENT"},RU={message:"Missing seedAssignments",code:"ERR_MISSING_SEED_ASSIGNMENTS"},bU={message:"Invalid seedNumber",code:"ERR_INVALID_SEED_NUMBER"},CU={message:"Invalid seedPosition",code:"ERR_INVALID_SEED_POSITION"},wg={message:"Missing targetLink",code:"ERR_MISSING_LINK_TARGET"},MU={message:"Existing round",code:"ERR_EXISTING_ROUND"},fH={message:"Missing roundNumber",code:"ERR_MISSING_ROUND_NUMBER"},dn={message:"Missing structureId",code:"ERR_MISSING_STRUCTURE_ID"},Nt={message:"structure not found",code:"ERR_NOT_FOUND_STRUCTURE"},Lg={message:"Missing structures",code:"ERR_MISSING_STRUCTURES"},bi={message:"Missing structure",code:"ERR_MISSING_STRUCTURE"},Fg={message:"Missing MAIN structure",code:"ERR_MISSING_MAIN_STRUCTURE"},vU={message:"drawDefinition contains unlinked structures",code:"ERR_MISSING_STRUCTURE_LINKS"},Kn={message:"Invalid eventType",code:"ERR_INVALID_EVENT_TYPE"};var le={message:"Missing event / eventId",code:"ERR_MISSING_EVENT_ID"},Gr={message:"Event not found",code:"ERR_NOT_FOUND_EVENT"},OU={message:"Event exists",code:"ERR_EXISTING_EVENT"},_U={message:"Missing entries",code:"ERR_MISSING_ENTRIES"},xU={message:"Invalid entries",code:"ERR_INVALID_ENTRIES"},kg={message:"Missing assignments",code:"ERR_MISSING_ASSIGNMENTS"},Gg={message:"Missing stage",code:"ERR_MISSING_STAGE"},tc={message:"Invalid stage",code:"ERR_INVALID_STAGE"},wU={message:"stageSequence limit",code:"ERR_LIMIT_STAGE_SEQUENCE"},LU={message:"Missing positionAssignments",code:"ERR_MISSING_POSITION_ASSIGNMENTS"},FU={message:"Cannot Assign BYE status if no assignment: { bye: true }",code:"ERR_UNCHANGED_CANNOT_ASSIGN_BYE"},kU={message:"Lucky draw first round allows at most one BYE",code:"ERR_LUCKY_DRAW_BYE_LIMIT"},wT={message:"Unrecognized matchUpStatus",code:"ERR_UNRECOGNIZED_MATCHUP_STATUS"},Hc={message:"Unrecognized matchUpFormat",code:"ERR_UNRECOGNIZED_MATCHUP_FORMAT"},Vg={message:"Incompatible matchUpStatus",code:"ERR_INCOMPATIBLE_MATCHUP_STATUS"},tw={message:"Propagated exits downstream",code:"ERR_PROPAGATED_EXITS_DOWNSTREAM"},ec={message:"Invalid matchUpStatus",code:"ERR_INVALID_MATCHUP_STATUS"},Xo={message:"Invalid tieFormat",code:"ERR_INVALID_TIE_FORMAT"},GU={message:"Invalid matchUpFormat",code:"ERR_INVALID_MATCHUP_FORMAT"},VU={message:"Missing matchUpFormat",code:"ERR_MISSING_MATCHUP_FORMAT"},BU={message:"Missing collectionDefinition",code:"ERR_MISSING_COLLECTION_DEFINITION"},la={message:"Missing tieFormat",code:"ERR_MISSING_TIE_FORMAT"},mr={message:"Missing matchUpId",code:"ERR_MISSING_MATCHUP_ID"},Ms={message:"Missing matchUpIds",code:"ERR_MISSING_MATCHUP_IDS"},Be={message:"matchUp not found",code:"ERR_NOT_FOUND_MATCHUP"},Vn={message:"Missing matchUps",code:"ERR_MISSING_MATCHUPS"},Xe={message:"Missing matchUp",code:"ERR_MISSING_MATCHUP"},cr={message:"Invalid matchUp",code:"ERR_INVALID_MATCHUP"},LT={message:"Missing policyType",code:"ERR_MISSING_POLICY_TYPE"},fa={message:"Missing policyDefinitions",code:"ERR_MISSING_POLICY_DEFINITIONS"},gH={message:"Missing seeding policy",code:"ERR_MISSING_POLICY_SEEDING"},HU={message:"Missing avoidance policy",code:"ERR_MISSING_POLICY_AVOIDANCE"},FT={message:"Missing policy attributes",code:"ERR_MISSING_POLICY_ATTRIBUTES"},WU={message:"Invalid policyDefinitions",code:"ERR_INVALID_POLICY_DEFINITIONS"},kT={message:"existing policyType",code:"ERR_EXISTING_POLICY_TYPE"},IH={message:"Policy not attached",code:"ERR_FAILURE_POLICY_NOT_ATTACHED"},Xu={message:"Policy not found",code:"ERR_NOT_FOUND_POLICY"},SH={message:"Missing scoring policy / matchUpFormats",code:"ERR_MISSING_POLICY_SCORING_MATCHUP_FORMATS"},YU={message:"Invalid sideNumber",code:"ERR_INVALID_SIDE_NUMBER"},hH={message:"Invalid setNumber",code:"ERR_INVALID_SET_NUMBER"},Bg={message:"Missing setObject",code:"ERR_MISSING_SET_ATTRIBUTE"},TH={message:"Missing setNumber",code:"ERR_MISSING_SET_NUMBER"},yH={message:"Missing sideNumber",code:"ERR_MISSING_SIDE_NUMBER"},Hg={message:"Missing courtId",code:"ERR_MISSING_COURT_ID"},nt={message:"Missing value",code:"ERR_MISSING_VALUE"},jU={message:"Missing birthdate",code:"ERR_MISSING_BIRTH_DATE"},qU={message:"Missing date",code:"ERR_MISSING_DATE"},Wg={message:"No valid dates",code:"ERR_NO_VALID_DATES"},rl={message:"Invalid bookings",code:"ERR_INVALID_BOOKINGS"},Yg={message:"Invalid dateAvailability",code:"ERR_INVALID_DATE_AVAILABILITY"},$U={message:"Missing dateAvailability",code:"ERR_MISSING_DATE_AVAILABILITY"},ae={message:"Invalid Date",code:"ERR_INVALID_DATE"},vs={message:"Invalid time",code:"ERR_INVALID_TIME"},KU={message:"Invalid tournament dates",code:"ERR_INVALID_DATES_TOURNAMENT"},ew={message:"Missing date range",info:"Event or tournament must have start and end dates",code:"ERR_MISSING_DATE_RANGE"},Ju={message:"Invalid Time Zone",code:"ERR_INVALID_TIME_ZONE"},Zu={message:"Invalid embargo: must be an ISO 8601 datetime with timezone (Z or \xB1HH:MM offset)",code:"ERR_INVALID_EMBARGO"},GT={message:"Invalid game scores",code:"ERR_INVALID_SCORES_GAME"},zU={message:"Invalid score",code:"ERR_INVALID_SCORE"},nl={message:"Invalid winningSide",code:"ERR_INVALID_WINNING_SIDE"};var rw={message:"No participants generated",code:"ERR_NO_PARTICIPANTS_GENERATED"},jg={message:"Cannot modify tieFormat",code:"ERR_UNCHANGED_CANNOT_MODIFY_TIEFORMAT"},QU={message:"Cannot modify participantType",code:"ERR_UNCHANGED_CANNOT_MODIFY_PARTICIPANT_TYPE"},Rm={message:"Cannot remove participants",code:"ERR_UNCHANGED_CANNOT_REMOVE_PARTICIPANTS"},XU={message:"Participant category mismatch",code:"ERR_CATEGORY_MISMATCH"},ol={message:"Cannot change winningSide",code:"ERR_UNCHANGED_CANNOT_CHANGE_WINNING_SIDE"},Ci={message:"Invalid participant",code:"ERR_INVALID_PARTICIPANT"},Vr={message:"Invalid participantId",code:"ERR_INVALID_PARTICIPANT_ID"},Mr={message:"Invalid participantIds",code:"ERR_INVALID_PARTICIPANT_IDS"},JU={message:"Invalid participantRole",code:"ERR_INVALID_PARTICIPANT_ROLE"},Nn={message:"Invalid participantType",code:"ERR_INVALID_PARTICIPANT_TYPE"},ZU={message:"Missing participantRole",code:"ERR_MISSING_PARTICIPANT_ROLE"},ga={message:"Missing participant",code:"ERR_MISSING_PARTICIPANT"},Wc={message:"Missing participants",code:"ERR_MISSING_PARTICIPANTS"},He={message:"Missing participantId",code:"ERR_MISSING_PARTICIPANT_ID"},tD={message:"Missing qualified participants",code:"ERR_MISSING_QUALIFIED_PARTICIPANTS"},ee={message:"Participant Not Found",code:"ERR_NOT_FOUND_PARTICIPANT"},eD={message:"participantId exists",code:"ERR_EXISTING_PARTICIPANT_ID"},EH={message:"participant pair exists",code:"ERR_EXISTING_PARTICIPANT_PAIR"},rD={message:"No participant removed",code:"ERR_UNCHANGED_NO_PARTICIPANT_REMOVED"},Ro={message:"Missing participantIds",code:"ERR_MISSING_PARTICIPANT_IDS"},nD={message:"Missing participantsCount",code:"ERR_MISSING_PARTICIPANT_COUNT"},oD={message:"Participant not checked in",code:"ERR_UNCHANGED_PARTICIPANT_NOT_CHECKED_IN"},iD={message:"Missing person details",code:"ERR_MISSING_PERSON_DETAILS"},Ia={message:"Existing participant drawPosition assignment",code:"ERR_EXISTING_PARTICIPANT_DRAW_POSITION_ASSIGNMENT"},bm={message:"Existing participant",code:"ERR_EXISTING_PARTICIPANT"},qg={message:"participantsCount exceeds drawSize",code:"ERR_INVALID_PARTICIPANT_COUNT"},$g={message:"Invalid entry status",code:"ERR_INVALID_ENTRY_STATUS"},VT={message:"Participant Entry Not Found",code:"ERR_NOT_FOUND_PARTICIPANT_ENTRY"},nw={message:"Participant not entered in stage",code:"ERR_UNCHANGED_PARTICIPANT_NOT_ENTERED"},ow={message:"Participant not found in stageSequence",code:"ERR_NOT_FOUND_PARTICIPANT_IN_STAGE"},sD={message:"entryStatus not allowed in stage",code:"ERR_INVALID_ENTRY_STATUS_IN_STAGE"},aD={message:"entryStatus not allowed for event",code:"ERR_INVALID_ENTRY_STATUS_IN_EVENT"},Kg={message:"No stage space available for entryStatus",code:"ERR_UNCHANGED_NO_AVAILABLE_STAGE_SPACE"},zg={message:"Insufficient drawPositions to accommodate qualifiers",code:"ERR_UNCHANGED_NO_DRAW_POSITIONS_FOR_QUALIFIERS"},Qg={message:"Insufficient drawPositions to accommodate entries",code:"ERR_INSUFFICIENT_DRAW_POSITIONS"},cD={message:"Missing penaltyType",code:"ERR_MISSING_PENALTY_TYPE"},uD={message:"Missing penaltyId",code:"ERR_MISSING_PENALTY_ID"},tp={message:"Penalty not found",code:"ERR_NOT_FOUND_PENALTY"},pD={message:"Missing courtsCount/courtNames",code:"ERR_MISSING_COURTS_INFO"},bo={message:"Court not found",code:"ERR_NOT_FOUND_COURT"},mD={message:"Court exists",code:"ERR_EXISTING_COURT"},BT={message:"Booking not found",code:"ERR_NOT_FOUND_BOOKING"},dD={message:"An active draft already exists for this draw",code:"ERR_EXISTING_DRAFT"},lD={message:"Existing matchUps conflict with booking",code:"ERR_EXISTING_MATCHUPS"},fD={message:"Venue exists",code:"ERR_EXISTING_VENUE"},Mi={message:"Venue not found",code:"ERR_NOT_FOUND_VENUE"},Os={message:"Missing venueId",code:"ERR_MISSING_VENUE_ID"},gD={message:"Invalid endTime",code:"ERR_INVALID_END_TIME"},ID={message:"Existing endTime",code:"ERR_EXISTING_END_TIME"},SD={message:"Invalid stopTime",code:"ERR_INVALID_STOP_TIME"},hD={message:"Invalid startTime",code:"ERR_INVALID_START_TIME"},iw={message:"Invalid resumeTime",code:"ERR_INVALID_RESUME_TIME"},Xg={message:"Invalid timeItem",code:"ERR_INVALID_TIME_ITEMS"},TD={message:"Missing async state provider",code:"ERR_MISSING_ASYNC_STATE_PROVIDER"},Jg={message:"Missing timeItem",code:"ERR_MISSING_TIME_ITEM"},Zg={message:"Missing timeItems",code:"ERR_MISSING_TIME_ITEMS"},ep={message:"Missing context",code:"ERR_MISSING_CONTEXT"},yD={message:"Missing schedule",code:"ERR_MISSING_SCHEDULE"},Yc={message:"Invalid scaleItem",code:"ERR_INVALID_SCALE_ITEM"},ED={message:"Modifications failed",code:"ERR_FAILURE_MODIFICATIONS"},Sa={message:"No modifications applied",code:"ERR_UNCHANGED_NO_MODIFICATIONS_APPLIED"},AD={message:"Unable to assign court",code:"ERR_UNCHANGED_COURT_NOT_ASSIGNED"},Cm={message:"No Candidates",code:"ERR_UNCHANGED_NO_CANDIDATES"},Jo={message:"Invalid configuration",code:"ERR_INVALID_CONFIG"},PD={message:"Invalid collectionDefinition",code:"ERR_INVALID_COLLECTION_DEFINITION"},So={message:"Invalid object",code:"ERR_INVALID_OBJECT"},Mm={message:"Invalid gender",code:"ERR_INVALID_GENDER"},rp={message:"Invalid category",code:"ERR_INVALID_CATEGORY"},O={message:"Invalid values",code:"ERR_INVALID_VALUES"},ND={message:"Duplicate value",code:"ERR_DUPLICATE_VALUE"},tI={message:"Team not found",code:"ERR_NOT_FOUND_TEAM"},UD={message:"No valid actions",code:"ERR_NO_VALID_ACTIONS"},jc={message:"No valid attributes",code:"ERR_NO_VALID_ATTRIBUTES"},eI={message:"Value unchanged",code:"ABORT_UNCHANGED"},fe={message:"Not found",code:"ERR_NOT_FOUND"},rI={message:"Not implemented",code:"ERR_NOT_IMPLEMENTED"},DD={message:"Existing flight",code:"ERR_EXISTING_FLIGHT"},nI={message:"Existing flight profile",code:"ERR_EXISTING_FLIGHT_PROFILE"},RD={message:"Existing outcome",code:"ERR_EXISTING_OUTCOME"},bD={message:"Existing matchUpId",code:"ERR_EXISTING_MATCHUP_ID"},HT={message:"Existing stage",code:"ERR_EXISTING_STAGE"},oI={message:"Existing structure",code:"ERR_EXISTING_STRUCTURE"},qc={message:"Method not found",code:"ERR_NOT_FOUND_METHOD"},CD={message:"Mutation blocked by active lock",code:"ERR_MUTATION_LOCKED"},MD={message:"Active mutation lock already exists for scope",code:"ERR_EXISTING_MUTATION_LOCK"},vD={message:"Mutation lock not found",code:"ERR_NOT_FOUND_MUTATION_LOCK"},OD={message:"Lock token does not match",code:"ERR_UNAUTHORIZED_LOCK_OPERATION"},_D={message:"Scheduled matchUps",code:"ERR_SCHEDULED_MATCHUPS"},$c={message:"Scores present",code:"ERR_SCORES_PRESENT"},sw={ANACHRONISM:OT,BOOKING_NOT_FOUND:BT,CANNOT_CHANGE_WINNING_SIDE:ol,CANNOT_MODIFY_TIEFORMAT:jg,CANNOT_MODIFY_PARTICIPANT_TYPE:QU,CANNOT_REMOVE_MAIN_STRUCTURE:IU,CANNOT_REMOVE_PARTICIPANTS:Rm,CATEGORY_MISMATCH:XU,COURT_EXISTS:mD,COURT_NOT_FOUND:bo,EXISTING_DRAFT:dD,EXISTING_MATCHUPS:lD,DRAW_DEFINITION_NOT_FOUND:Rr,DRAW_ID_EXISTS:AU,DRAW_POSITION_ACTIVE:Vc,DRAW_POSITION_ASSIGNED:kc,DRAW_POSITION_NOT_CLEARED:EU,DRAW_POSITION_NOT_FOUND:dH,DRAW_SIZE_MISMATCH:lH,DUPLICATE_ENTRY:tl,DUPLICATE_VALUE:ND,ENTRY_STATUS_NOT_ALLOWED_FOR_EVENT:aD,ENTRY_STATUS_NOT_ALLOWED_IN_STAGE:sD,EVENT_EXISTS:OU,EVENT_NOT_FOUND:Gr,EXISTING_DRAW_DEFINITIONS:SU,EXISTING_END_TIME:ID,EXISTING_FLIGHT:DD,EXISTING_MATCHUP_ID:bD,EXISTING_OUTCOME:RD,EXISTING_PARTICIPANT_DRAW_POSITION_ASSIGNMENT:Ia,EXISTING_PARTICIPANT:bm,EXISTING_POLICY_TYPE:kT,EXISTING_PROFILE:nI,EXISTING_ROUND:MU,EXISTING_STAGE:HT,EXISTING_STRUCTURE:oI,INCOMPATIBLE_MATCHUP_STATUS:Vg,INCOMPLETE_SOURCE_STRUCTURE:_g,INSUFFICIENT_DRAW_POSITIONS:Qg,INVALID_ACTION:DU,INVALID_ASSIGNMENT:xT,INVALID_BOOKINGS:rl,INVALID_CATEGORY:rp,INVALID_COLLECTION_DEFINITION:PD,INVALID_CONFIGURATION:Jo,INVALID_DATE_AVAILABILITY:Yg,INVALID_DATE:ae,INVALID_DRAW_DEFINITION:ma,INVALID_DRAW_POSITION_FOR_SEEDING:xg,INVALID_DRAW_POSITION:is,INVALID_DRAW_SIZE:Dm,INVALID_END_TIME:gD,INVALID_ENTRIES:xU,INVALID_EVENT_TYPE:Kn,INVALID_GAME_SCORES:GT,INVALID_GENDER:Mm,INVALID_MATCHUP_FORMAT:GU,INVALID_MATCHUP_STATUS:ec,INVALID_MATCHUP_STATUS_BYE:FU,INVALID_MATCHUP:cr,INVALID_OBJECT:So,INVALID_PARTICIPANT_ID:Vr,INVALID_PARTICIPANT_IDS:Mr,INVALID_PARTICIPANT_ROLE:JU,INVALID_PARTICIPANT_SEEDING:PU,INVALID_PARTICIPANT_TYPE:Nn,INVALID_PARTICIPANT:Ci,INVALID_POLICY_DEFINITION:WU,INVALID_RECORDS:_T,INVALID_SCALE_ITEM:Yc,INVALID_SEED_NUMBER:bU,INVALID_SEED_POSITION:CU,INVALID_SET_NUMBER:hH,INVALID_SIDE_NUMBER:YU,INVALID_SCORE:zU,INVALID_STAGE:tc,INVALID_START_TIME:hD,INVALID_STRUCTURE:Do,INVALID_STOP_TIME:SD,INVALID_TIE_FORMAT:Xo,INVALID_TIME:vs,INVALID_TIME_ITEM:Xg,INVALID_TOURNAMENT_DATES:KU,INVALID_TOURNAMENT_RECORD:Fc,INVALID_VALUES:O,INVALID_WINNING_SIDE:nl,LUCKY_DRAW_BYE_LIMIT:kU,MATCHUP_NOT_FOUND:Be,METHOD_NOT_FOUND:qc,MUTATION_LOCKED:CD,MUTATION_LOCK_EXISTS:MD,MUTATION_LOCK_NOT_FOUND:vD,MISSING_ASSIGNMENTS:kg,MISSING_ASYNC_STATE_PROVIDER:TD,MISSING_AVOIDANCE_POLICY:HU,MISSING_BIRTH_DATE:jU,MISSING_COLLECTION_DEFINITION:BU,MISSING_COURT_ID:Hg,MISSING_COURTS_INFO:pD,MISSING_DATE_AVAILABILITY:$U,MISSING_DATE:qU,MISSING_DRAW_DEFINITION:$,MISSING_DRAW_ID:Pn,MISSING_DRAW_POSITION:da,MISSING_DRAW_POSITIONS:Gc,MISSING_DRAW_SIZE:Bc,MISSING_ENTRIES:_U,MISSING_EVENT:le,MISSING_QUALIFIED_PARTICIPANTS:tD,MISSING_MATCHUP_FORMAT:VU,MISSING_MATCHUP_ID:mr,MISSING_MATCHUP_IDS:Ms,MISSING_MATCHUP:Xe,MISSING_MATCHUPS:Vn,MISSING_PARTICIPANT_COUNT:nD,MISSING_PARTICIPANT_ID:He,MISSING_PARTICIPANT_IDS:Ro,MISSING_PARTICIPANT_ROLE:ZU,MISSING_PARTICIPANT:ga,MISSING_PARTICIPANTS:Wc,MISSING_PENALTY_ID:uD,MISSING_PENALTY_TYPE:cD,MISSING_PERSON_DETAILS:iD,MISSING_POLICY_ATTRIBUTES:FT,MISSING_POLICY_DEFINITION:fa,MISSING_POLICY_TYPE:LT,MISSING_POSITION_ASSIGNMENTS:LU,MISSING_ROUND_NUMBER:fH,MISSING_SCHEDULE:yD,MISSING_SCORING_POLICY:SH,MISSING_SEED_ASSIGNMENTS:RU,MISSING_SEEDCOUNT_THRESHOLDS:UU,MISSING_SEEDING_POLICY:gH,MISSING_SET_NUMBER:TH,MISSING_SET_OBJECT:Bg,MISSING_SIDE_NUMBER:yH,MISSING_STAGE:Gg,MISSING_STRUCTURE_ID:dn,MISSING_STRUCTURE:bi,MISSING_MAIN_STRUCTURE:Fg,MISSING_STRUCTURES:Lg,MISSING_TARGET_LINK:wg,MISSING_TIE_FORMAT:la,MISSING_TIME_ITEM:Jg,MISSING_TIME_ITEMS:Zg,MISSING_TOURNAMENT_ID:Za,MISSING_TOURNAMENT_RECORD:j,MISSING_TOURNAMENT_RECORDS:kt,MISSING_VALUE:nt,MISSING_VENUE_ID:Os,MODIFICATIONS_FAILED:ED,NO_CANDIDATES:Cm,NO_DRAW_POSITIONS_AVAILABLE_FOR_QUALIFIERS:zg,NO_MODIFICATIONS_APPLIED:Sa,NO_STAGE_SPACE_AVAILABLE_FOR_ENTRY_STATUS:Kg,NO_PARTICIPANT_REMOVED:rD,NO_VALID_ACTIONS:UD,NO_VALID_ATTRIBUTES:jc,NO_VALID_DATES:Wg,NOT_FOUND:fe,NOT_IMPLEMENTED:rI,PARTICIPANT_COUNT_EXCEEDS_DRAW_SIZE:qg,PARTICIPANT_ID_EXISTS:eD,PARTICIPANT_NOT_CHECKED_IN:oD,PARTICIPANT_NOT_FOUND:ee,PARTICIPANT_PAIR_EXISTS:EH,PENALTY_NOT_FOUND:tp,POLICY_NOT_ATTACHED:IH,POLICY_NOT_FOUND:Xu,SCHEDULE_NOT_CLEARED:hU,SCHEDULE_CONFLICT_DOUBLE_BOOKING:TU,SCHEDULE_CONFLICT_COURT_UNAVAILABLE:yU,SCHEDULED_MATCHUPS:_D,SCORES_PRESENT:$c,SEEDSCOUNT_GREATER_THAN_DRAW_SIZE:NU,STAGE_SEQUENCE_LIMIT:wU,STRUCTURE_NOT_FOUND:Nt,TEAM_NOT_FOUND:tI,UNABLE_TO_ASSIGN_COURT:AD,UNAUTHORIZED_LOCK_OPERATION:OD,UNLINKED_STRUCTURES:vU,UNRECOGNIZED_DRAW_TYPE:Qu,UNRECOGNIZED_MATCHUP_FORMAT:Hc,UNRECOGNIZED_MATCHUP_STATUS:wT,VALUE_UNCHANGED:eI,VENUE_EXISTS:fD};var Qe={disableNotifications:!1,tournamentId:void 0,tournamentRecords:{},subscriptions:{},modified:!1,methods:{},notices:[]},xD={addNotice:_H,callListener:kH,cycleMutationStatus:OH,deleteNotice:LH,deleteNotices:wH,disableNotifications:AH,enableNotifications:PH,getMethods:vm,getNotices:xH,getTopics:FH,getTournamentId:aw,getTournamentRecord:NH,getTournamentRecords:UH,removeTournamentRecord:CH,setMethods:vH,setSubscriptions:MH,setTournamentId:RH,setTournamentRecord:DH,setTournamentRecords:bH,handleCaughtError:GH};function AH(){Qe.disableNotifications=!0}function PH(){Qe.disableNotifications=!1}function aw(){return Qe.tournamentId}function NH(t){return Qe.tournamentRecords[t]}function UH(){return Qe.tournamentRecords}function DH(t){let e=t?.tournamentId;return e?(Qe.tournamentRecords[e]=t,{success:!0}):{error:Fc}}function RH(t){return t?Qe.tournamentRecords[t]?(Qe.tournamentId=t,{success:!0}):{error:j}:(Qe.tournamentId=void 0,{success:!0})}function bH(t){Qe.tournamentRecords=t;let e=Object.keys(t);e.length===1?Qe.tournamentId=e[0]:e.length||(Qe.tournamentId=void 0)}function CH(t){if(typeof t!="string")return{error:O};if(!Qe.tournamentRecords[t])return{error:fe};delete Qe.tournamentRecords[t];let e=Object.keys(Qe.tournamentRecords);return e.length===1?Qe.tournamentId=e[0]:e.length||(Qe.tournamentId=void 0),{success:!0}}function MH(t){return t.subscriptions===null||Object.keys(t.subscriptions).length===0?(Qe.subscriptions={},{...P}):typeof t.subscriptions!="object"?{error:O}:(Object.keys(t.subscriptions).forEach(e=>{typeof t.subscriptions[e]=="function"?Qe.subscriptions[e]=t.subscriptions[e]:delete Qe.subscriptions[e]}),{...P})}function vH(t){return typeof t!="object"?{error:O}:(Object.keys(t).forEach(e=>{typeof t[e]=="function"&&(Qe.methods[e]=t[e])}),{...P})}function OH(){let t=Qe.modified;return Qe.modified=!1,t}function _H({topic:t,payload:e,key:r},n){if(!(typeof t!="string"||typeof e!="object")&&(Qe.disableNotifications||(Qe.modified=!0),!(Qe.disableNotifications||!Qe.subscriptions[t]&&!n)))return r&&(Qe.notices=Qe.notices.filter(o=>!(o.topic===t&&o.key===r))),Qe.notices.push({topic:t,payload:e,key:r}),{...P}}function vm(){return Qe.methods??{}}function xH({topic:t}){return Qe.notices.filter(e=>e.topic===t).map(e=>e.payload)}function wH(){Qe.notices=[]}function LH({topic:t,key:e}){Qe.notices=Qe.notices.filter(r=>(!t||r.topic===t)&&r.key!==e)}function FH(){return{topics:Object.keys(Qe.subscriptions)}}function kH({topic:t,notices:e},r){let n=Qe.subscriptions[t];n&&typeof n=="function"&&n(e);let o=r?.[t];o&&typeof o=="function"&&o(e)}function GH({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:aw(),params:JSON.stringify(r),engine:t,methodName:e,error:o}),{error:o}}var be={timers:{default:{elapsedTime:0}},globalSubscriptions:{},deepCopyAttributes:{stringify:[],ignore:[],toJSON:[]},globalMethods:[],deepCopy:!0},rn=xD,cw=["addNotice","callListener","cycleMutationStatus","deleteNotice","deleteNotices","disableNotifications","enableNotifications","getMethods","getNotices","getTopics","getTournamentId","getTournamentRecord","getTournamentRecords","removeTournamentRecord","setSubscriptions","setTournamentId","setTournamentRecord","setTournamentRecords"];function VH(t){if(typeof t!="object")throw new Error("Global state provider can not be undefined or null");if(Yt(Object.keys(t),cw).length!==cw.length)throw new Error("Global state provider is missing required methods");return rn=t,{success:!0}}function wD(){if(rn.createInstanceState){try{rn.createInstanceState()}catch(t){return{error:t}}return{success:!0}}else return{error:TD}}function je(t){return!t||typeof t!="object"?be.devContext??!1:typeof be.devContext!="object"?!1:Object.keys(t).every(e=>be.devContext?.[e]===t[e])&&be.devContext}function BH(t="reset",e="default"){let r=Date.now();if(t==="report"){if(e==="allTimers")return Object.keys(be.timers).filter(o=>o!=="default"||be.timers[o].startTime).map(o=>{let i=be.timers[o],s=i.state==="stopped"?0:(r-(i?.startTime??0))/1e3,a=i.elapsedTime+s;return{state:be.timers[o].state,elapsedTime:a.toFixed(2),timer:o}});{let n=be.timers[e].state==="stopped"?0:(r-(be.timers[e]?.startTime??0))/1e3,o=be.timers[e].elapsedTime+n;return{state:be.timers[e].state,elapsedTime:o.toFixed(2),timer:e}}}if(!be.timers[e]||t==="reset"){if(e==="allTimers")return be.timers={default:{elapsedTime:0}},!0;be.timers[e]={startTime:r,state:"active",elapsedTime:0}}return be.timers[e].elapsedTime||(be.timers[e].elapsedTime=0),t==="stop"&&be.timers[e].state!=="stopped"&&(be.timers[e].state="stopped")&&(be.timers[e].elapsedTime+=(r-(be.timers[e]?.startTime??0))/1e3),t==="start"&&(be.timers[e].startTime=r)&&(be.timers[e].state="active"),be.timers[e]}function uw(t){kr(t)?be.globalLog=t:delete be.globalLog}function np(t){be.devContext=t}function LD(){rn.disableNotifications()}function iI(){rn.enableNotifications()}function op(t,e){typeof t=="boolean"&&(be.deepCopy=t),typeof e=="object"&&(Array.isArray(e.ignore)&&(be.deepCopyAttributes.ignore=e.ignore),Array.isArray(e.toJSON)&&(be.deepCopyAttributes.toJSON=e.toJSON),Array.isArray(e.stringify)&&(be.deepCopyAttributes.stringify=e.stringify),e.threshold&&(be.deepCopyAttributes.threshold=e.threshold))}function sI(){return{enabled:be.deepCopy,...be.deepCopyAttributes}}function HH(t){return t?.subscriptions?(Object.keys(t.subscriptions).forEach(e=>{be.globalSubscriptions[e]=t.subscriptions[e]}),{...P}):{error:nt,info:"missing subscriptions"}}function WH(t){return t?.subscriptions?rn.setSubscriptions({subscriptions:t.subscriptions}):{error:nt,info:"missing subscriptions"}}function pw(t){return t?typeof t!="object"?{error:O}:(Object.keys(t).forEach(e=>{kr(t[e])&&(be.globalMethods[e]=t[e])}),{...P}):{error:nt,info:"missing method declarations"}}function mw(t){return t?typeof t!="object"?{error:O}:rn.setMethods(t):{error:nt,info:"missing method declarations"}}function aI(){return rn.cycleMutationStatus()}function at(t){if(typeof t?.topic!="string")return;let e=be.globalSubscriptions[t.topic];return rn.addNotice(t,e)}function cI(){return{...be.globalMethods,...rn.getMethods()}}function WT(t){return rn.getNotices(t)}function YT({key:t,topic:e}){return rn.deleteNotice({key:t,topic:e})}function ss(){return rn.deleteNotices()}function br(){return rn.getTopics()}function Kc(t){return br()?.topics?.includes(t)}async function il(t){return rn.callListener(t,be.globalSubscriptions)}function _s(){return rn.getTournamentId()}function uI(t){return rn.getTournamentRecord(t)}function Zo(){return rn.getTournamentRecords()}function FD(t){return rn.setTournamentRecord(t)}function sl(t){return rn.setTournamentRecords(t)}function Om(t){return rn.setTournamentId(t)}function kD(t){return rn.removeTournamentRecord(t)}function jT(){return rn}function _m({engineName:t,methodName:e,params:r,err:n}){let o=kr(rn.handleCaughtError)&&rn.handleCaughtError||xD.handleCaughtError,{tournamentRecord:i,...s}=r;return o({params:s,engineName:t,methodName:e,err:n})}function GD(t,e){if(be.globalLog)try{be.globalLog({log:t,engine:e})}catch(r){console.log("globalLog error",r),console.log(e,t),uw()}else console.log(e,t)}function VD(t,e,r,n){if(!Tt(t))return{error:O};Le||(r=1);let o=Array.isArray(e)?e:[],i={},s=(a,c=0)=>{Object.keys(a).forEach(u=>{kr(a[u])?i[u]=a[u]:Tt(a[u])&&(e===!0||o?.includes(u))&&(r===void 0||c<r)&&s(a[u],c+1)})};return s(t),n?pw(i):mw(i),{methods:i}}function YH(t,e,r){return Object.keys(t).filter(n=>!e.includes(t[n])&&(!r||(Array.isArray(t[n])?t[n].length:!0)))}function et(t,e,r,n){if(typeof t!="object"||t===null)return t;sI()?.enabled||(n=!0);let i=["",void 0,null];e&&i.push(!1);let s=YH(t,i,r);return Object.assign({},...s.map(a=>Array.isArray(t[a])?{[a]:n?t[a]:t[a].map(c=>et(c))}:{[a]:n?t[a]:et(t[a])}))}function M({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&&(e.context??={},Object.assign(e.context,et(t))),e&&!e?.error&&!e?.success&&Object.assign(e,{...P}),e??{success:!0}}var Je="FEMALE",ti="OTHER",as="MIXED",Ce="MALE";var al={FEMALE_ABBR:"F",OTHER_ABBR:"O",MIXED_ABBR:"X",MALE_ABBR:"M",ANY_ABBR:"A",FEMALE:Je,MIXED:as,OTHER:ti,MALE:Ce,ANY:"ANY"};function cs(t){return[Je,"F"].includes(t)}function ha(t){return[Ce,"M"].includes(t)}function nn(t){return[as,"X"].includes(t)}function Co(t){return["ANY","A"].includes(t)}function yr(t){if(t){if(cs(t))return Je;if(nn(t))return as;if(ha(t))return Ce;if(Co(t))return"ANY"}return ti}function Un(t){return cs(t)||ha(t)}var zH="MIXED events can not contain mixed singles or { gender: ANY } collections",QH="events with { gender: ANY } can not contain MIXED singles collections";function cl(t){let e="tieFormatGenderValidityCheck",{referenceGender:r,matchUpType:n,gender:o}=t;return r&&o&&Un(r)&&yr(r)!==yr(o)?M({result:{valid:!1,error:Mm},context:{gender:o},stack:e}):nn(r)&&(Co(o)||nn(o)&&n!==Rt)?M({result:{error:Mm,valid:!1},info:zH,stack:e}):Co(r)&&nn(o)&&n!==Rt?M({result:{error:Mm,valid:!1},info:QH,stack:e}):{valid:!0}}var XH="normal",BD="timed",JH="final",pI="NOAD";var HD=["SET","HAL","QTR","PER","INN","RND","FRM","MAP","MAT"],qT="CONSECUTIVE",$T="TRADITIONAL",ZH="game",tW="matchUp",lw={S:XH,F:JH,G:ZH,M:tW};function ip(t,e){if(Tt(t)&&(t?.bestOf||t?.exactly)&&t?.setFormat)return rW(t,e)}function mI(t){return!Number.isNaN(Number(t))&&Number(t)}function Iw(t){let e=`T${t.minutes}`;return t.based==="P"&&(e+="P"),t.tiebreakFormat?.tiebreakTo&&(e+=`/TB${t.tiebreakFormat.tiebreakTo}`),t.modifier&&(e+=`@${t.modifier}`),e}function eW(t){let e=t?.deuceAfter?`${t.deuceAfter}D`:"";if(t?.type===$T)return`TN${e}`;if(t?.type===qT&&Number.isInteger(t.count))return`${t.count}C${e}`}function rW(t,e){let r=mI(t.bestOf)||void 0,n=mI(t.exactly)||void 0,o=r||n;if(t.setFormat?.timed&&t.simplified&&o===1)return Iw(t.setFormat);let i=t.matchRoot||"SET",s=n&&n!==1?"X":"",a=t.aggregate?"A":"",c=o&&`${i}${o}${s}${a}`||"",u=fw(t.setFormat,e),p=u&&`S:${u}`||"",m=fw(t.finalSetFormat,e),d=o&&o>1&&m&&u!==m&&`F:${m}`||"",l=t.gameFormat?`G:${eW(t.gameFormat)}`:"",f=t.matchUpConstraint?.timed?`M:T${t.matchUpConstraint.minutes}`:"";if(c&&u)return[c,p,l,d,f].filter(Boolean).join("-")}function fw(t,e){if(typeof t=="object"&&Object.keys(t).length){if(t.timed)return Iw(t);if(t.outs)return`O${t.outs}`;if(t.tiebreakSet)return gw(t.tiebreakSet);let r=mI(t.setTo);if(r){let n=t.NoAD&&pI||"",o=gw(t.tiebreakFormat),i=o&&`/${o}`||"",s=mI(t.tiebreakAt),a=s&&(s!==r||e)&&`@${s}`||"";if(o!==!1)return`${r}${n}${i}${a}`}}}function gw(t){if(t){if(typeof t=="object"&&!t.tiebreakTo)return"";if(typeof t=="object"&&mI(t.tiebreakTo)){let e=`TB${t.tiebreakTo}${t.NoAD?pI:""}`;return t.modifier&&(e+=`@${t.modifier}`),e}else return!1}}function oe(t){if(_t(t)){let e=t.startsWith("T")&&BD||HD.some(r=>t.startsWith(r))&&"SET"||"";if(e===BD){let r=yw(t),n={simplified:!0,setFormat:r,bestOf:1};if(r)return n}if(e==="SET")return iW(t)}}function nW(t){let e=HD.find(u=>t.startsWith(u));if(!e)return;let r=t.slice(e.length),n=/^(\d+)([A-Z]*)$/.exec(r);if(!n)return;let o=xm(n[1]);if(!o)return;let i=n[2],s=!1,a=!1,c=[];for(let u of i)u==="X"?s=!0:u==="A"?a=!0:c.push(u);return{matchRoot:e,count:o,exactly:s,aggregate:a,matchMods:c}}function oW(t){let e=/^(.+?)(\d+D)$/.exec(t),r=e?e[1]:t,n=e?Number(e[2].slice(0,-1)):void 0;if(n!==void 0&&(n<1||!Number.isInteger(n)))return;if(r==="TN"){let i={type:$T};return n&&(i.deuceAfter=n),i}let o=/^([1-9]\d*)C$/.exec(r);if(o){let i={type:qT,count:Number(o[1])};return n&&(i.deuceAfter=n),i}}function iW(t){let e=t.split("-"),r=nW(e[0]);if(!r)return;let{matchRoot:n,count:o,exactly:i,aggregate:s,matchMods:a}=r,c=i&&o!==1?void 0:o,u=i&&o!==1?o:void 0,p,m,d,l,h={setFormat:p,finalSetFormat:m,gameFormat:d,matchUpConstraint:l,sCount:0,fCount:0,gCount:0,mCount:0};for(let T=1;T<e.length;T++)if(!sW(e[T],h))return;return{setFormat:p,finalSetFormat:m,gameFormat:d,matchUpConstraint:l}=h,aW({setFormat:p,finalSetFormat:m,gameFormat:d,matchUpConstraint:l,matchRoot:n,aggregate:s,matchMods:a,bestOf:c,exactly:u})}function sW(t,e){let r=t.indexOf(":");if(r<0)return!1;let n=t.slice(0,r),o=t.slice(r+1);if(!(n in lw))return!1;if(n==="S"){if(e.sCount++,e.sCount>1)return!1;e.setFormat=Sw(t,o)}else if(n==="F"){if(e.fCount++,e.fCount>1)return!1;e.finalSetFormat=Sw(t,o)}else if(n==="G"){if(e.gCount++,e.gCount>1||(e.gameFormat=oW(o),!e.gameFormat))return!1}else if(n==="M"&&(e.mCount++,e.mCount>1||(e.matchUpConstraint=lW(o),!e.matchUpConstraint)))return!1;return!0}function aW({setFormat:t,finalSetFormat:e,gameFormat:r,matchUpConstraint:n,matchRoot:o,aggregate:i,matchMods:s,bestOf:a,exactly:c}){let u=t&&t.timed||e&&e.timed;if(o==="SET"&&!(a&&a<6||u&&c)||!t||!(!e||e))return;let d=et({setFormat:t,exactly:c,bestOf:a});return o!=="SET"&&(d.matchRoot=o),i&&(d.aggregate=!0),s.length>0&&(d.matchMods=s),e&&(d.finalSetFormat=e),r&&(d.gameFormat=r),n&&(d.matchUpConstraint=n),d}function Sw(t,e){return e.startsWith("TB")?cW(e):e.startsWith("O")?uW(e):e.startsWith("T")?yw(e):pW(t,e)}function cW(t){let e=Tw(t);return e===!1?!1:typeof e=="object"?{tiebreakSet:e}:void 0}function uW(t){let e=/^O([1-9]\d*)$/.exec(t);if(e)return{outs:Number(e[1])}}function pW(t,e){let r=/^[FS]:(\d+)([A-Za-z]*)/.exec(t),n=r&&Ew(r[2])||!1,o=!r?.[2]||n,i=r?xm(r[1]):void 0,s=hw(e),a=s!==!1,c=a&&s||i,u=Tw(e.split("/")[1]);return!i||!o||!(u!==!1)||!a?!1:mW(i,n,u,c)}function mW(t,e,r,n){let o={setTo:t};return e&&(o.NoAD=!0),r?(o.tiebreakFormat=r,o.tiebreakAt=n):o.noTiebreak=!0,o}function hw(t,e=!0){let r=t?.indexOf("@")>0&&t.split("@");if(r)return(e?xm(r[1]):r[1])||!1}function Tw(t){if(t)return t.startsWith("TB")?dW(t):!1}function dW(t){let e=hw(t,!1),r=/^TB(\d+)([A-Za-z]*)/.exec(t),n=r?.[1],o=r&&Ew(r[2]),i=!r?.[2]||o,s=xm(n);if(!s||!i)return!1;let a={tiebreakTo:s};return e&&typeof e=="string"&&!yt(e)&&(a.modifier=e),o&&(a.NoAD=!0),a}function yw(t){let e=t.slice(1),r=/^(\d+)([PG])?(?:\/TB(\d+))?(@[A-Za-z]+)?$/.exec(e),n=xm(r?.[1]);if(!n)return;let o={timed:!0,minutes:n},i=r?.[2];i==="P"?o.based="P":i==="G"&&(o.based="G");let s=r?.[3];if(s){let u=xm(s);u&&(o.tiebreakFormat={tiebreakTo:u})}let a=r?.[4],c=[void 0,"P","G",""].includes(a);if(a&&!c){let u=/^(\d+)([PGA])?(?:\/TB\d+)?(@)([A-Za-z]+)$/.exec(e)?.[4];return u?(o.modifier=u,o):void 0}return a&&(o.based=a),o}function lW(t){let e=/^T(\d+)$/.exec(t);if(!e)return;let r=xm(e[1]);if(r)return{timed:!0,minutes:r}}function Ew(t){return t?.includes(pI)}function xm(t){let e=Number(t);return Number.isNaN(e)?0:e}function fW(t){return t.replaceAll(/T(\d+)G(?=\/TB|@|-|$)/g,"T$1")}function vr({matchUpFormat:t}){if(!_t(t)||t==="")return!1;let e=oe(t),r=/-S:(\d+)\/TB(\d{1,2})@?(\d?)/.exec(t),n=r?.[1],o=r?.[2],i=r?.[3],s=/-F:(\d+)\/TB(\d{1,2})@?(\d?)/.exec(t),a=s?.[1],c=s?.[2],u=s?.[3];return ip(e,!!(r&&o&&n===i||s&&c&&a===u))===fW(t)}var wm=/^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2]\d|3[0-1])$/,KT=/^((0\d|1\d|2[0-3]):[0-5]\d(:[0-5]\d)?)([.,]\d{3})?$/,Mo=/^(\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2]\d|3[0-1]))([ T](0\d|1\d|2[0-3]):[0-5]\d(:[0-5]\d)?)?([.,]\d{3})?Z?$/,Qc=/^(\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 pl(t){let{scheduledDate:e}=t;if(!e&&t.scheduledTime&&(e=mt(t.scheduledTime)),!e)return;let r=$t(t.scheduledTime),n=mt(e);return n&&r&&(n+=`T${r}`),n}function Aw(t){return typeof t!="object"||Array.isArray(t)?!1:Object.prototype.toString.call(t)==="[object Date]"}function Lm(t){let e=typeof t=="string"?t?.split(" "):[];if(t&&e?.length>1&&!["AM","PM"].includes(e[1].toUpperCase()))return!1;let r=sp(t,!0,!0);return!!(!t||r&&Qc.test(r))}function Me(t){return us(t)||wm.test(t)}function gW(t){let e=new Date(t),r=e.getSeconds()+60*e.getMinutes()+3600*e.getHours();return IW(r,{displaySeconds:!1})}function IW(t,e){let r=Number.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(ao).join(":")}var fI=t=>{let e=dI(t)||us(t)?new Date(t):new Date,r=e.getUTCMonth()+1,n=r<10?`0${r}`:`${r}`;return`${e.getUTCFullYear()}-${ao(n)}-${ao(e.getUTCDate())}`};function SW(t){let e=dI(t)||us(t)?new Date(t):new Date;return Date.UTC(e.getFullYear(),e.getMonth(),e.getDate())}function zn(t,e="-",r="YMD"){if(!t)return"";typeof t=="string"&&!t.includes("T")&&(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 zT(t){let e=t?new Date(t):new Date,r=e.getTimezoneOffset();return new Date(e.getTime()-r*60*1e3)}function hW(t){return zT(t).getTime()}function dI(t){if(typeof t=="boolean")return!1;let e=t instanceof Date&&t||!Number.isNaN(Number(t))&&new Date(t)||!1;return e&&!Number.isNaN(Number(e.valueOf()))}function TW(t,e){return t<=e}function Ta(t,e){if(!Me(t)||!Me(e))return[];let r=mt(t)+"T00:00",n=mt(e)+"T00:00",o=new Date(r),i=new Date(n),s=dI(i)&&dI(o)&&TW(o,i),a=[],c=0;if(s){let u=o,p=u.getTime();for(;p<=i.getTime()&&c<300;)c+=1,a.push(new Date(u)),p=u.setDate(u.getDate()+1)}return a.map(u=>zn(u))}var yW=/^([+-]?\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 us(t){return typeof t!="string"?!1:yW.test(t)}function ya(t){return typeof t!="string"||!us(t)?!1:/([zZ]|[+-]\d{2}:?\d{2})$/.test(t)}function XT(t){if(typeof t!="string")return!1;let r=t.split("Z")[0].split(":"),n=r.every(i=>!Number.isNaN(Number.parseInt(i)));return!(r.length<2||!n||Number.parseInt(r[0])>23||Number.parseInt(r[1])>60)}function jt(t){let e=$t(t);if(!e)return 0;let[r,n]=e.split(":").map(o=>Number.parseInt(o));return r*60+n}function Pw(t){let e=Math.floor(t/60),r=t-e*60;return e>23&&(e=e%24),[ao(e),ao(r)].join(":")}function lI(t){return XT(t)?t.split(":").slice(0,2).map(ao).join(":"):void 0}function $t(t){return us(t)&&t.indexOf("T")>0?lI(t.split("T").reverse()[0]):lI(t)}function mt(t){return us(t)||Mo.test(t)?t.split("T")[0]:""}function Fm(t,e){let r=new Date(t);return r.setUTCDate(r.getUTCDate()+e),mt(r.toISOString())}function QT(t){t=typeof t=="string"?t:"00:00";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,Number.isNaN(Number.parseInt(r.hours))||Number.isNaN(Number.parseInt(r.minutes))||r.ampm&&!["AM","PM"].includes(r.ampm.toUpperCase())?{}:r}function EW(t){let e=QT(t);return e.ampm&&e.hours&&(e.ampm.toLowerCase()==="pm"&&Number.parseInt(e.hours)<12&&(e.hours=(e.hours&&Number.parseInt(e.hours)||0)+12),e.ampm.toLowerCase()==="am"&&e.hours==="12"&&(e.hours="00")),`${e.hours||"12"}:${e.minutes||"00"}`.split(":").map(ao).join(":")}function AW(t){let e=QT(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 sp(t,e,r){let n=mt(t),o=$t(t),i=n?o:t;return t?e&&(n&&r&&t||EW(i))||AW(i):void 0}function JT(t,e){let r=QT(t),n=QT(e);if(Number.parseInt(r.hours)<Number.parseInt(n.hours))return-1;if(Number.parseInt(r.hours)>Number.parseInt(n.hours))return 1;if(r.hours===n.hours){if(Number.parseInt(r.minutes)<Number.parseInt(n.minutes))return-1;if(Number.parseInt(r.minutes)>Number.parseInt(n.minutes))return 1}return 0}function ZT(t,e=7){let r=mt(t)+"T00:00",n=new Date(r),o=new Date(n.setDate(n.getDate()+e));return zn(o)}function PW(t){return ZT(t)}function NW(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())),zn(o,r)}function Nw(t,e,r){let n=new Date(t,0);return zn(new Date(n.setDate(e)),r)}function ve(t,e=void 0){let[r,n]=(t||"00:00").split(":").map(ao),o=zT(e).setHours(r,n,0,0);return zT(o)}function xs(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=Number.isNaN(e)?0:e;return $t(gI(ve(r),n).toISOString())||"00:00"}function gI(t,e){let r=new Date(t);return new Date(r.getTime()+e*6e4)}function ao(t){return t.toString()[1]?t:"0"+t}function Qn(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 ty={addDays:ZT,addWeek:PW,addMinutesToTimeString:Br,convertTime:sp,getIsoDateString:pl,getUTCdateString:fI,DateHHMM:gW,extractDate:mt,extractTime:$t,formatDate:zn,getDateByWeek:NW,isISODateString:us,isValidEmbargoDate:ya,isDate:dI,isTimeString:XT,offsetDate:zT,offsetTime:hW,sameDay:Qn,timeStringMinutes:jt,timeToDate:ve,timeUTC:SW,validTimeValue:Lm,validDateString:wm,timeValidation:Qc,dateValidation:Mo};var UW=(t,e)=>t.filter(Boolean).every(r=>typeof r===e),DW=t=>t.filter(Boolean).every(Le);function ml(t,e){return`${t}-${e}`}function ps(t){let e=t.category;if(typeof e!="object"||!e)return{error:rp};let{ageCategoryCode:r,ageMaxDate:n,ageMinDate:o,ageMax:i,ageMin:s}=e,a=e.categoryName,c;if(!(UW([r,n,o,a],"string")&&DW([i,s])&&[n,o].filter(Boolean).every(Me)))return{error:rp};let p=t.consideredDate??mt(new Date().toLocaleDateString("sv"));if(!p||!Me(p))return{error:ae};let[m]=p.split("-").slice(0,3).map(B=>Number.parseInt(B)),d=Fm(p,-1);if(!d)return{error:ae};let[l,f]=d.split("-").slice(1,3).map(B=>Number.parseInt(B)),g=`${ao(l)}-${ao(f)}`,I=Fm(p,1);if(!I)return{error:ae};let[S,h]=I.split("-").slice(1,3).map(B=>Number.parseInt(B)),T=`${ao(S)}-${ao(h)}`,y=s&&Fm(p,-1*365*s),E=i&&Fm(p,-1*365*i),A=[],N=B=>!A.includes(B)&&A.push(B);r=r??a;let U=/^([UO]?)(\d{1,2})([UO]?)$/,R=/^C(\d{1,2})-(\d{1,2})$/,D=r?.includes("-"),b=D&&r?.match(R),C=r?.match(U);function _(B){let z=m-B,W=ml(z,T);e.ageMinDate&&e.ageMinDate!==W&&N(`Invalid submitted ageMinDate: ${o}`),o=W,r&&(e.ageMax&&e.ageMax!==B-1&&(N(`Invalid submitted ageMax: ${i}`),E=void 0),i=B-1)}function v(B){let z=m-B-1,W=ml(z,T);e.ageMin&&e.ageMin>B&&N(`Invalid submitted ageMin: ${s}`),e.ageMax&&e.ageMax>B&&N(`Invalid submitted ageMax: ${i}`),e.ageMinDate&&e.ageMinDate!==W&&N(`Invalid submitted ageMinDate: ${o}`),o=W,r&&(e.ageMax&&e.ageMax!==B&&(N(`Invalid submitted ageMax: ${i}`),y=void 0),i=B)}function w(B){let z=m-B,W=ml(z,g);e.ageMaxDate&&e.ageMaxDate!==W&&N(`Invalid submitted ageMaxDate: ${n}`),n=W,r&&(e.ageMin&&e.ageMin!==B+1&&(N(`Invalid submitted ageMin: ${s}`),y=void 0),s=B+1)}function L(B){let z=m-B-1,W=ml(z,g);e.ageMaxDate&&e.ageMaxDate!==W&&N(`Invalid submitted ageMaxDate: ${n}`),n=W,r&&(e.ageMin&&e.ageMin!==B&&(N(`Invalid submitted ageMin: ${s}`),y=void 0),s=B)}function F(B){let z=U.exec(B)??[],[W,K,Y]=z.slice(1),J=Number.parseInt(K);W==="U"?(e.ageMaxDate&&e.ageMaxDate!==n&&N(`Invalid submitted ageMaxDate: ${e.ageMaxDate}`),_(J)):W==="O"&&w(J),Y==="U"?(e.ageMaxDate&&e.ageMaxDate!==n&&N(`Invalid submitted ageMaxDate: ${e.ageMaxDate}`),v(J)):Y==="O"&&L(J),n=(n??y)||void 0,o=(o??E)||void 0}function x(){if(n=void 0,o=void 0,i=void 0,s=void 0,e.ageMin){let W=m-e.ageMin;n=ml(W,g)}if(e.ageMax){let W=m-e.ageMax-1;o=ml(W,T)}let[B,z]=(r?.match(R)??[]).slice(1).map(W=>Number.parseInt(W));B<=z?(s=B,i=z,c=!0):N(`Invalid combined age range ${r}`)}function k(){s&&w(s),i&&v(i)}function G(){b?x():D?r?.split("-").forEach(F):C&&r?F(r):k()}G(),i&&e?.ageMin&&e?.ageMin>i&&(N(`Invalid submitted ageMin: ${e?.ageMin}`),s=void 0);let V=et({consideredDate:p,combinedAge:c,ageMaxDate:n,ageMinDate:o,ageMax:i,ageMin:s});return A.length&&(V.errors=A),V}function ap({category:t}){if(!Tt(t))return{error:O};let e=ps({category:t});if(e.error)return{error:e};let{ratingMax:r,ratingMin:n}=t;return r&&!Le(r)?M({result:{error:O},context:{ratingMax:r}}):n&&!Le(n)?M({result:{error:O},context:{ratingMin:n}}):{...e}}function cp({childCategory:t,withDetails:e,category:r}){let n=ap({category:r}),o=ap({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=et({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 up({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}`),M({result:{errors:c,error:So},stack:a});let{collectionValueProfiles:u,collectionGroupNumber:p,collectionValue:m,collectionId:d,matchUpCount:l,matchUpFormat:f,matchUpValue:g,matchUpType:I,scoreValue:S,setValue:h,category:T,gender:y}=e;if(r&&typeof d!="string"&&c.push(`collectionId is not type string: ${d}`),typeof l!="number"&&c.push(`matchUpCount is not type number: ${l}`),I&&!Cs([Ct,Rt,Um],I)&&c.push(`matchUpType must be SINGLES, DOUBLES, or HYBRID: ${I}`),[!!u?.length].concat([g,m,S,h].map(yt)).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 A=vT({collectionValueProfiles:u,matchUpCount:l});A.errors&&c.push(...A.errors)}if(p&&typeof p!="number"&&c.push(`collectionGroupNumber is not type number: ${m}`),f&&!vr({matchUpFormat:f})&&c.push(`Invalid matchUpFormat: ${f}`),n){let A=cl({referenceGender:i,matchUpType:I,gender:y});if(A.error)return M({context:{referenceGender:i,gender:y},result:A,stack:a})}if(t&&o&&T){let A=cp({category:o,childCategory:T});if(!A.valid)return M({result:{error:rp},context:A,stack:a})}return c.length?M({result:{errors:c,error:PD},stack:a}):{valid:!0}}function or(t){let e=!!(t?.enforceCategory!==!1&&t?.category),r=!!(t?.enforceGender!==!1&&t?.gender),n=t?.checkCollectionIds,o=t?.tieFormat,i=t?.event,s="validateTieFormat",a=[],c=RW({...t,stack:s});if(c?.error)return c;let u,p=o.collectionDefinitions.every(I=>{let{setValue:S,scoreValue:h,collectionValue:T}=I;(S||h)&&!T&&(u=!0);let{valid:y,errors:E}=up({referenceCategory:t.category,referenceGender:t.gender,collectionDefinition:I,checkCollectionIds:n,checkCategory:e,checkGender:r,event:i});return y?!0:(Array.isArray(E)&&a.push(...E),!1)}),m=typeof o.winCriteria?.valueGoal=="number"&&o.winCriteria?.valueGoal>0&&!u||o.winCriteria?.aggregateValue;if(!(m||o.winCriteria?.aggregateValue))return u?a.push("aggregateValue is required"):a.push("Either non-zero valueGoal, or { aggregateValue: true } must be specified in winCriteria"),M({context:{tieFormat:o,errors:a,aggregateValueImperative:u},result:{error:Xo},stack:s});let d=o.collectionDefinitions.map(({collectionId:I})=>I),l=!n||d.length===pt(d).length,f=p&&m&&l,g={valid:f,errors:a};return f?g:M({result:{error:Xo},context:{tieFormat:o,errors:a},stack:s})}function RW(t){let{tieFormat:e,stack:r}=t;return!t||!e||!Tt(e)?M({result:{error:Xo},context:{tieFormat:e,message:"tieformat must be an object"},stack:r}):Tt(e.winCriteria)?Array.isArray(e.collectionDefinitions)?{...P}:M({result:{error:Xo},context:{tieFormat:e,message:"collectionDefinitions must be an array"},stack:r}):M({result:{error:Xo},context:{tieFormat:e,message:"tieformat.winCritiera must be an object"},stack:r})}var dl="resourceSubType",ll="resourceType",Xc="identifier",ey="name",Uw={RESOURCE_SUB_TYPE:dl,RESOURCE_TYPE:ll,IDENTIFIER:Xc,NAME:ey};function q(t,e,r,n,o=0){if(jT().makeDeepCopy)return jT().makeDeepCopy(t,e,r,n);let i=sI(),{stringify:s,toJSON:a,ignore:c,modulate:u}=i??{};if(!i?.enabled&&!r||typeof t!="object"||kr(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)||kr(c)&&!c(l)),d=(l,f)=>{p[l]=kr(f?.toString)?f.toString():JSON.stringify(f)};for(let l of m){let f=t[l],g=kr(u)?u(f):void 0;if(g!==void 0)p[l]=g;else if(e&&l==="extensions"&&Array.isArray(f)){let I=II(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)&&kr(f?.toJSON)?p[l]=f.toJSON():f===null?p[l]=void 0:Aw(f)?p[l]=new Date(f).toISOString():p[l]=q(f,e,r,n,o+1)}return p}function II(t){return t?.map(e=>{let{name:r,value:n}=e;return r&&n&&{[`_${r}`]:n}}).filter(Boolean)}function ry(t=1,e,r){return Q(0,t).map(()=>it(e,r))}function it(t,e){let r=e??Math.random,n=[];for(let u=0;u<256;u++)n[u]=(u<16?"0":"")+u.toString(16);let o=Math.trunc(r()*4294967295),i=Math.trunc(r()*4294967295),s=Math.trunc(r()*4294967295),a=Math.trunc(r()*4294967295),c=n[o&255]+n[o>>8&255]+n[o>>16&255]+n[o>>24&255]+"-"+n[i&255]+n[i>>8&255]+"-"+n[i>>16&15|64]+n[i>>24&255]+"-"+n[s&63|128]+n[s>>8&255]+"-"+n[s>>16&255]+n[s>>24&255]+n[a&255]+n[a>>8&255]+n[a>>16&255]+n[a>>24&255];return typeof t=="string"?`${t}_${c.replaceAll("-","")}`:c}var ny={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 oy={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 iy={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 sy={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 ay={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 cy={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 uy={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:"Brewer Cup",winCriteria:{valueGoal:4}};var py={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 _n="SET3-S:6/TB7",LW="SET3-S:6NOAD",WD="SET3-S:6NOAD/TB7-F:TB10",FW="SET3-S:4/TB7",kW="SET3-S:4/TB5@3",GW="SET5-S:6/TB7",VW="SET1-S:6/TB7",BW="SET1-S:TB10",HW="SET3-S:6/TB7-F:TB7",WW="SET1-S:T20",YW="SET1-S:8/TB7",jW="SET1-S:8/TB7@7",Dw={FORMAT_STANDARD:_n,FORMAT_STANDARD_NOAD:LW,FORMAT_ATP_DOUBLES:WD,FORMAT_SHORT_SETS:FW,FORMAT_FAST4:kW,FORMAT_GRAND_SLAM:GW,FORMAT_ONE_SET:VW,FORMAT_MATCH_TIEBREAK:BW,FORMAT_SET3_TB7:HW,FORMAT_PRO_SET:YW,FORMAT_COLLEGE_PRO_SET:jW,TIMED20:WW};var my={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 dy={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 Collegiate",winCriteria:{valueGoal:4}};var ly={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 fy={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:"World Team Tennis ITT",winCriteria:{aggregateValue:!0}};var Rw={tieFormatName:"INTENNSE 2026",winCriteria:{aggregateValue:!0},collectionDefinitions:[{collectionId:"intennse-ms",collectionName:"Men's Singles",matchUpType:"SINGLES",matchUpCount:2,matchUpFormat:"SET2XA-S:T10",scoreValue:1,gender:"MALE",category:{categoryName:"MS"}},{collectionId:"intennse-ws",collectionName:"Women's Singles",matchUpType:"SINGLES",matchUpCount:2,matchUpFormat:"SET2XA-S:T10",scoreValue:1,gender:"FEMALE",category:{categoryName:"WS"}},{collectionId:"intennse-md",collectionName:"Men's Doubles",matchUpType:"DOUBLES",matchUpCount:1,matchUpFormat:"SET1A-S:T10",scoreValue:1,gender:"MALE",category:{categoryName:"MD"}},{collectionId:"intennse-wd",collectionName:"Women's Doubles",matchUpType:"DOUBLES",matchUpCount:1,matchUpFormat:"SET1A-S:T10",scoreValue:1,gender:"FEMALE",category:{categoryName:"WD"}},{collectionId:"intennse-xd",collectionName:"Mixed Doubles",matchUpType:"DOUBLES",matchUpCount:1,matchUpFormat:"SET1A-S:T10",scoreValue:1,gender:"MIXED",category:{categoryName:"XD"}}]};var gy={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 Iy={collectionDefinitions:[{collectionGroupNumber:1,matchUpType:"DOUBLES",matchUpCount:1,matchUpFormat:"SET3-S:6NOAD/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:6NOAD/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:6NOAD/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 Sy={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 Tennis on Campus",winCriteria:{aggregateValue:!0}};var SI="COLLEGE_DEFAULT",YD="COLLEGE_JUCO",jD="COLLEGE_D3",qD="DOMINANT_DUO",$D="DOMINANT_DUO_MIXED",KD="INTENNSE_2026",zD="LAVER_CUP",QD="TEAM_DOUBLES_3_AGGREGATION",XD="USTA_BREWER_CUP",JD="USTA_OZAKI_CUP",ZD="USTA_COLLEGE",tR="USTA_GOLD_TEAM_CHALLENGE",eR="USTA_LEVEL_1",rR="USTA_INTERSECTIONAL",nR="USTA_SECTION_BATTLE",oR="USTA_SOUTHERN_LEVEL_5",iR="USTA_TOC",sR="USTA_WTT_ITT",aR="USTA_ZONAL",bw={COLLEGE_D3:jD,COLLEGE_DEFAULT:SI,COLLEGE_JUCO:YD,DOMINANT_DUO:qD,DOMINANT_DUO_MIXED:$D,INTENNSE_2026:KD,LAVER_CUP:zD,TEAM_DOUBLES_3_AGGREGATION:QD,USTA_BREWER_CUP:XD,USTA_OZAKI_CUP:JD,USTA_COLLEGE:ZD,USTA_GOLD_TEAM_CHALLENGE:tR,USTA_INTERSECTIONAL:rR,USTA_LEVEL_1:eR,USTA_SECTION_BATTLE:nR,USTA_SOUTHERN_LEVEL_5:oR,USTA_TOC:iR,USTA_WTT_ITT:sR,USTA_ZONAL:aR};var Mw="STANDARD",Cw={[Mw]:{hydrate:!0,doubles:{matchUpCount:3,matchUpValue:1},singles:{matchUpCount:6,matchUpValue:1},valueGoal:5},[jD]:{hydrate:!0,doubles:{matchUpFormat:"SET1-S:8/TB7@7",matchUpCount:3,matchUpValue:1},singles:{matchUpFormat:_n,matchUpCount:6,matchUpValue:1},tieFormatName:"College D3",valueGoal:5},[SI]:{hydrate:!0,doubles:{matchUpFormat:"SET1-S:6/TB7",collectionValue:1,matchUpCount:3},singles:{matchUpFormat:_n,matchUpCount:6,matchUpValue:1},tieFormatName:"College Default",valueGoal:4},[YD]:{hydrate:!0,doubles:{matchUpFormat:"SET1-S:8/TB7",matchUpCount:3,matchUpValue:1},singles:{matchUpFormat:_n,matchUpCount:6,matchUpValue:1},tieFormatName:"College JUCO",valueGoal:5},[zD]:Iy,[qD]:my,[$D]:cy,[KD]:Rw,[QD]:oy,[XD]:uy,[JD]:py,[ZD]:dy,[tR]:ny,[rR]:ay,[eR]:ly,[nR]:sy,[oR]:iy,[sR]:fy,[iR]:Sy,[aR]:gy},tY=t=>{let e=t?.namedFormat&&Object.keys(Cw).includes(t.namedFormat)?t.namedFormat:Mw,r=Array.isArray(t?.uuids)?t?.uuids:[],n,{category:o,gender:i}=t?.event??{},s=q(Cw[e],!1,!0),a=c=>{if(!t?.isMock&&!t?.event?.isMock||!t.event)return r?.pop()??it();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:WD,collectionName:"Doubles",matchUpType:Rt,...s.doubles},{collectionId:a(1),matchUpFormat:_n,collectionName:"Singles",matchUpType:Ct,...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},co=tY;var Ut="SINGLES",Ea="SINGLES",wt="DOUBLES",ei="DOUBLES",Oe="TEAM",Ze="TEAM",pp="HYBRID",hI="HYBRID";var eY="RATING",rY="BOTH",vw={AGE:"AGE",BOTH:rY,DOUBLES:wt,DOUBLES_EVENT:ei,HYBRID:pp,HYBRID_EVENT:hI,RATING:eY,SINGLES:Ut,SINGLES_EVENT:Ea,TEAM_EVENT:Ze,TEAM:Oe};var H="MAIN",Z="QUALIFYING",me="CONSOLATION",Fe="VOLUNTARY_CONSOLATION",Vt="PLAY_OFF",Jc=[H,Z,me,Vt,Fe],Aa={[Z]:1,[H]:2,[Vt]:3,[me]:3,[Fe]:4},cR="finishingPositions",uR="aggregateEventStructures",pR={[H]:1,[Vt]:2,[me]:3,[Z]:4,[Fe]:5},Ow={[Vt]:1,[H]:2,[me]:3,[Z]:4,[Fe]:5},Zc="CLUSTER",km="ADJACENT",mR="SEPARATE",vi="WATERFALL",tu="ITEM",de="CONTAINER",ln="DRAW",Gm="RANDOM",qe="TOP_DOWN",Oi="BOTTOM_UP",fn="POSITION",Er="WINNER",ir="LOSER",Bn="FIRST_MATCHUP",hi="AD_HOC",nY="AD_HOC",rc="FEED_IN",ms="COMPASS",mp="OLYMPIC",oY="SINGLE_ELIMINATION";var zr="SINGLE_ELIMINATION",dp="DOUBLE_ELIMINATION",ds="FIRST_MATCH_LOSER_CONSOLATION",Vm="FIRST_ROUND_LOSER_CONSOLATION",ws="LUCKY_DRAW",nc="ADAPTIVE",TI="CURTIS_CONSOLATION",yI="CURTIS_CONSOLATION",hy="FEED_IN_CHAMPIONSHIP_TO_SF",Pa="FEED_IN_CHAMPIONSHIP_TO_SF",Ty="FEED_IN_CHAMPIONSHIP_TO_QF",eu="FEED_IN_CHAMPIONSHIP_TO_QF",yy="FEED_IN_CHAMPIONSHIP_TO_R16",ru="FEED_IN_CHAMPIONSHIP_TO_R16",dR="MODIFIED_FEED_IN_CHAMPIONSHIP",Na="MODIFIED_FEED_IN_CHAMPIONSHIP",Ls="FEED_IN_CHAMPIONSHIP",Bm="PAGE_PLAYOFF",Hm="PLAYOFF",lp="SWISS",iY={0:{name:"Qualifier 1",abbreviation:"Q1"},"0-1":{name:"Eliminator",abbreviation:"EL"},"0-2":{name:"Final",abbreviation:"F"}},_w="DOUBLE_ROUND_ROBIN",Hr="ROUND_ROBIN",Wr="ROUND_ROBIN_WITH_PLAYOFF",lR="DECIDER",fR="BACKDRAW",EI={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"}},AI={0:{name:"East",abbreviation:"E"},"0-1":{name:"West",abbreviation:"W"},"0-2":{name:"North",abbreviation:"N"},"0-1-1":{name:"South",abbreviation:"S"}},PI={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"}},uo="WIN_RATIO",ls="ROUND_OUTCOME",gR=[nc,ms,TI,eu,ru,Pa,Ls,Ty,yy,hy,ds,Vm,ws,Na,mp,Bm,Hm,Wr],sY=[hi,nc,ms,TI,dp,eu,ru,Pa,Ls,rc,ds,Vm,ws,Na,mp,Bm,Hm,Hr,Wr,zr,lp],IR={MAIN:H,QUALIFYING:Z,CONSOLATION:me,ITEM:tu,CONTAINER:de,FIRST_MATCHUP:Bn,WINNER:Er,LOSER:ir,AD_HOC:hi,FEED_IN:rc,FLEX_ROUNDS:nY,COMPASS:ms,PLAY_OFF:Vt,PAGE_PLAYOFF:Bm,PAGE_PLAYOFF_ATTRIBUTES:iY,PLAYOFF:Hm,SWISS:lp,OLYMPIC:mp,KNOCKOUT:oY,SINGLE_ELIMINATION:zr,DOUBLE_ELIMINATION:dp,CURTIS:TI,FICSF:hy,FICQF:Ty,FICR16:yy,MFIC:dR,VOLUNTARY_CONSOLATION:Fe,FIRST_MATCH_LOSER_CONSOLATION:ds,FIRST_ROUND_LOSER_CONSOLATION:Vm,MODIFIED_FEED_IN_CHAMPIONSHIP:Na,FEED_IN_CHAMPIONSHIP_TO_R16:ru,FEED_IN_CHAMPIONSHIP_TO_QF:eu,FEED_IN_CHAMPIONSHIP_TO_SF:Pa,FEED_IN_CHAMPIONSHIP:Ls,LUCKY_DRAW:ws,ADAPTIVE:nc,ROUND_ROBIN_WITH_PLAYOFF:Wr,ROUND_ROBIN:Hr,DECIDER:lR,BACKDRAW:fR,COMPASS_ATTRIBUTES:EI,OLYMPIC_ATTRIBUTES:AI,ADAPTIVE_ATTRIBUTES:PI,DRAW:ln,RANDOM:Gm,TOP_DOWN:qe,BOTTOM_UP:Oi,CLUSTER:Zc,ADJACENT:km,SEPARATE:mR,WATERFALL:vi,WIN_RATIO:uo,ROUND_OUTCOME:ls,MULTI_STRUCTURE_DRAWS:gR,generatedDrawTypes:sY,stageOrder:Aa,finishOrder:pR,AGGREGATE_EVENT_STRUCTURES:uR,FINISHING_POSITIONS:cR},xw=IR;var Ee="tournamentRecords",NI="policyDefinitions",rt="tournamentRecord",Ey="onlineResource",Kt="drawDefinition",Ay="tieFormatName",fl="matchUpFormat",sr="participantId",gl="scheduleDates",ww="tournamentId",Lw="scheduleDate",Fw="roundNumber",po="structureId",Wm="participant",nu="matchUpIds",Py="entryStage",kw="policyType",SR="structures",UI="eventType",Or="matchUpId",Il="tieFormat",fp="inContext",oc="structure",Ym="courtIds",Gw="personId",jm="venueIds",DI="matchUps",Fs="courtId",Ny="eventId",Dn="matchUp",ic="drawId",Yr="error",ce="event",_i="param",RI="uuids",Uy="penaltyType",Sl="penaltyId",gp="venueId",Vw="stage",Bw="averageMatchUpMinutes",Hw="recoveryMinutes",Ww="periodLength",Yw="number";var jr="object",ke="array";var $e="_validate",Dy="_message",_r="_invalid",Ge="_ofType",Ip="_anyOf",Ua="_oneOf";var jw={[Ey]:t=>Yt(Object.keys(t),[dl,ll,Xc]).length===3,[Ay]:t=>t&&co({namedFormat:t}),[RI]:t=>!t||Array.isArray(t)&&t.every(_t),[Il]:t=>!or({tieFormat:t}).error,[UI]:t=>[Ut,wt,Oe].includes(t),[Py]:t=>Jc.includes(t)},aY={[Ee]:kt,[rt]:j,[NI]:fa,[Kt]:$,[sr]:He,[fl]:VU,[ww]:Za,[po]:dn,[nu]:Ms,[Wm]:ga,[Ey]:So,[UI]:Kn,[SR]:Lg,[Or]:mr,[Il]:Xo,[oc]:bi,[Fs]:Hg,[DI]:Vn,[Ny]:Gr,[Dn]:Xe,[Ym]:nt,[jm]:nt,[Uy]:cD,[Sl]:uD,[gp]:Os,[ic]:Pn,[ce]:le,[Vw]:Gg},cY={[Ee]:jr,[NI]:jr,[rt]:jr,[Kt]:jr,[Ey]:jr,[gl]:ke,[Wm]:jr,[nu]:ke,[SR]:ke,[Il]:jr,[oc]:jr,[Ym]:ke,[jm]:ke,[DI]:ke,[Dn]:jr,[ce]:jr,[RI]:ke};function X(t,e,r){if(!t&&!Tt(t))return{error:O};if(!e?.length||t?._bypassParamCheck)return{valid:!0};if(!Array.isArray(e))return{error:O};let{paramError:n,errorParam:o}=mY(t,e);if(!n)return{valid:!0};let i=n[$e]&&(n[Yr]||n[_r])||t?.[o]==null&&(n[Yr]||n[_r]||aY[o]||O)||O,s=o??(n[Ua]&&Object.keys(n[Ua]).join(", "));return M({info:{param:s,message:n[Dy]},result:{error:i},stack:r})}function qw(t,e){let r=Object.keys(t),n=Object.keys(e);return Yt(r,n)}function uY(t,e){if(!e)return;let r=qw(t,e);return r.length!==1?{error:O}:r.reduce((n,o)=>({...n,[o]:!0}),{})}function pY(t,e){if(!e)return;let r=qw(t,e).filter(n=>t[n]);return r.length<1?{error:O}:r.reduce((n,o)=>({...n,[o]:!0}),{})}function mY(t,e){let r,n;return{paramError:e.find(({_ofType:i,_oneOf:s,_anyOf:a,_validate:c,_info:u,...p})=>{let m=s&&uY(t,s);if(m?.error)return m.error;m&&Object.assign(p,m);let d=a&&pY(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&&!kr(c),S=t[g]!==void 0&&!c&&dY(t,g,i),h=p[g]&&t[g]==null,y=I||S||h||c&&t[g]!==void 0&&!lY(t[g],c)||jw[g]&&!jw[g](t[g]);return y&&(r=g,n=u),y});return!l.length||f}),errorParam:r,paramInfo:n}}function dY(t,e,r){return r=r||cY[e]||"string",r==="array"?!Array.isArray(t[e]):typeof t[e]!==r}function lY(t,e){return kr(e)?e(t):!0}var Sp="DYNAMIC",Xn="RANKING",vo="RATING",ri="SCALE",ho="SEEDING",$w={RANKING:Xn,RATING:vo,SCALE:ri,SEEDING:ho};function sc(t){let e=X(t,[{[Wm]:!0}]);if(e.error)return e;let r=t.participant.timeItems?.filter(({itemType:o})=>o?.startsWith(ri)&&[Xn,vo,ho].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===ho&&"seedings"||c===Xn&&"rankings"||"ratings";n[l][u]||(n[l][u]=[]),n[l][u].push({scaleValue:a.itemValue,scaleDate:a.itemDate,scaleName:d})}}}return{...P,...n}}function fs(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 S=I.map(h=>{let T={};return o(h,g,T)!==!1?T:void 0}).filter(Boolean);a[l]=S}else I&&(a[l]={},o(I,g,a[l]));else{let S=i[l];if(Array.isArray(g)&&!g.includes(S))return!1;(s[l]||d&&s[l]!==!1)&&(a[l]=S)}}}}var Ry="voluntaryConsolation",xi="competitiveBands",bI="roundRobinTally",Jn="positionActions",We="matchUpActions",gr="rankingPoints",Oo="roundNaming",Da="participant",hp="progression",_o="scheduling",ac="avoidance",fY="participant",gY="display",Qr="scoring",Hn="seeding",ou="feedIn",IY="sanctioning",SY="audit",iu="competition",hl="draws",Kw={POLICY_TYPE_VOLUNTARY_CONSOLATION:Ry,POLICY_TYPE_COMPETITIVE_BANDS:xi,POLICY_TYPE_ROUND_ROBIN_TALLY:bI,POLICY_TYPE_POSITION_ACTIONS:Jn,POLICY_TYPE_MATCHUP_ACTIONS:We,POLICY_TYPE_RANKING_POINTS:gr,POLICY_TYPE_ROUND_NAMING:Oo,POLICY_TYPE_PARTICIPANT:Da,POLICY_TYPE_PROGRESSION:hp,POLICY_TYPE_SCHEDULING:_o,POLICY_TYPE_AVOIDANCE:ac,POLICY_TYPE_COMPETITION:iu,POLICY_TYPE_DISPLAY:gY,POLICY_TYPE_PRIVACY:fY,POLICY_TYPE_FEED_IN:ou,POLICY_TYPE_SCORING:Qr,POLICY_TYPE_SEEDING:Hn,POLICY_TYPE_SANCTIONING:IY,POLICY_TYPE_AUDIT:SY,POLICY_TYPE_DRAWS:hl};function ni({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=q(s,!1,o);if(a){let c=e?.[Da];if(r?.withScaleValues){let{ratings:u,rankings:p}=sc({participant:a});a.rankings=p,a.ratings=u}if(c?.participant)return fs({template:c.participant,source:a})}return a}var zw="element required",Qw="missing name";function dr(t){if(!t||typeof t!="object")return{error:nt};if(t.element&&typeof t?.element!="object")return{error:O};if(!t?.name)return{error:nt,info:Qw};if(!t?.element){if(t.discover&&t.tournamentRecords){for(let e of Object.keys(t.tournamentRecords)){let r=t.tournamentRecords[e],n=dr({element:r,name:t.name});if(n.error)return M({result:n,stack:"removeExtension"})}return{...P}}return{error:nt,info:zw}}return t?.element.extensions?(t.element.extensions=t.element.extensions.filter(e=>e?.name!==t.name),{...P}):{...P,info:fe}}function Wn({requiredAttributes:t=["name","value"],extension:e}){if(!e||typeof e!="object"||typeof e.name!="string")return!1;let r=Object.keys(e);return t.filter(n=>r.includes(n)).length===t.length}function ut(t){if(typeof t!="object")return{error:nt};let e="addExtension";if(t?.element&&typeof t.element!="object")return M({result:{error:O},stack:e});if(!Wn({extension:t.extension}))return M({result:{error:O,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=ut({extension:t.extension,element:o});if(i.error)return M({result:i,stack:e})}return{...P}}else return M({result:{error:nt},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),{...P}}function CI(t){return!t||typeof t!="object"?{error:nt}:t.tournamentRecord?ut({creationTime:t.creationTime,element:t.tournamentRecord,extension:t.extension}):{error:j}}function MI(t){return!t||typeof t!="object"?{error:nt}:t.drawDefinition?ut({creationTime:t.creationTime,element:t.drawDefinition,extension:t.extension}):{error:Rr}}function xo(t){return!t||typeof t!="object"?{error:nt}:t.event?ut({creationTime:t.creationTime,extension:t.extension,element:t.event}):{error:Gr}}function hR(t){if(!t||typeof t!="object")return{error:nt};if(!t.participantId)return{error:He};let e=t.tournamentRecord?.participants??[],r=ni({participantId:t.participantId,tournamentParticipants:e});return r?ut({creationTime:t.creationTime,extension:t.extension,element:r}):{error:ee}}function vI(t){return!t||typeof t!="object"?{error:nt}:t.tournamentRecord?dr({element:t.tournamentRecord,name:t.name}):{error:j}}function TR(t){return!t||typeof t!="object"?{error:nt}:t.drawDefinition?dr({element:t.drawDefinition,name:t.name}):{error:Rr}}function qm(t){return!t||typeof t!="object"?{error:nt}:t?.event?dr({element:t.event,name:t.name}):{error:Gr}}function yR(t){if(!t||typeof t!="object")return{error:nt};if(!t.participantId)return{error:He};let e=t.tournamentRecord?.participants??[],r=ni({participantId:t.participantId,tournamentParticipants:e});return r?dr({element:r,name:t.name}):{error:ee}}function $m({tournamentRecords:t}){return{tournamentIds:Tt(t)?Object.keys(t):[],...P}}var hY="extensionQueries";function ot({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:fe}}return M({result:{error:nt},stack:hY})}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:fe}}var TY="activeSuspension",Tp="appliedPolicies",Ra="competitionState",ER="context",Tl="delegatedOutcome",mo="disabled",cc="disableAutoCalc",yl="disableLinks",El="display",wi="draftState",uc="drawDeletions",yY="drawProfile",EY="eventProfile",AY="eventWithdrawalRequests",PY="factory",on="flightProfile",by="groupingAttribute",wo="lineUps",ba="linkedTournamentsIds",sn="mutationLocks",Cy="participantRepresentatives",pc="personRequests",su="positionActions",NY="rankingPoints",UY="registration",Rn="roundTarget",AR="sanctioningConstraints",yp="scheduleLimits",oi="scheduleTiming",mc="schedulingProfile",DY="statusDetail",au="subOrder",Lo="tally",Al="tieFormatModification",My={ACTIVE_SUSPENSION:TY,APPLIED_POLICIES:Tp,COMPETITION_STATE:Ra,CONTEXT:ER,DELEGATED_OUTCOME:Tl,DISABLED:mo,DISABLE_LINKS:yl,DISABLE_AUTO_CALC:cc,DISPLAY:El,DRAFT_STATE:wi,DRAW_DELETIONS:uc,DRAW_PROFILE:yY,EVENT_PROFILE:EY,EVENT_WITHDRAWAL_REQUESTS:AY,FLIGHT_PROFILE:on,GROUPING_ATTRIBUTE:by,LINEUPS:wo,LINKED_TOURNAMENTS:ba,MUTATION_LOCKS:sn,PARTICIPANT_REPRESENTATIVES:Cy,PERSON_REQUESTS:pc,POSITION_ACTIONS:su,RANKING_POINTS:NY,REGISTRATION:UY,ROUND_TARGET:Rn,SANCTIONING_CONSTRAINTS:AR,SCHEDULE_LIMITS:yp,SCHEDULE_TIMING:oi,SCHEDULING_PROFILE:mc,STATUS_DETAIL:DY,SUB_ORDER:au,TALLY:Lo,TIE_FORMAT_MODIFICATIONS:Al,FACTORY:PY},PR=[Tl,mo,cc,yl,on,wo,ba,sn,Cy,pc,Rn,yp,oi,mc,au,Lo,Al];function NR({tournamentRecords:t}){if(typeof t!="object"||!Object.keys(t).length)return{error:kt};let e=$m({tournamentRecords:t}),{tournamentIds:r}=e;return r?.length>1?ut({tournamentRecords:t,discover:!0,extension:{name:ba,value:{tournamentIds:r}}}):{...P}}function UR({tournamentRecords:t}){if(typeof t!="object"||!Object.keys(t).length)return{error:kt};let e=dr({name:ba,tournamentRecords:t,discover:!0});return M({result:e,stack:"unlinkTournaments"})}function DR({tournamentRecords:t,tournamentId:e}){if(typeof t!="object")return{error:O};if(!e)return{error:Za};let r=$m({tournamentRecords:t}),{tournamentIds:n}=r;if(!n.includes(e))return{error:Za};let o;return n.every(i=>{let s=t[i],{extension:a}=ot({element:s,name:ba});if(!a)return!0;let c=a?.value?.tournamentIds??[];if(!c?.length||c.length===1&&c.includes(e)||i===e){let m=vI({name:ba,tournamentRecord:s});return m.error&&(o=m.error),m.success}let u=c.filter(m=>m!==e);a.value={tournamentIds:u};let p=CI({tournamentRecord:s,extension:a});return p.error&&(o=p.error),p.success}),o?{error:o}:{...P}}function It({onlySpecifiedPolicyTypes:t=!1,policyTypes:e=[],tournamentRecord:r,drawDefinition:n,structure:o,event:i}){if(!Array.isArray(e))return{error:LT};let s={};return r&&a(r),i&&a(i),n&&a(n),o&&a(o),{appliedPolicies:s,...P};function a(c){let p=c?.extensions?.find(m=>m.name===Tp)?.value;if(p)for(let m of Object.keys(p))(t?e.includes(m):!e.length||e.includes(m))&&(s[m]=q(p[m],!1,!0))}}function lo({policyTypes:t=[],tournamentRecord:e,drawDefinition:r,structure:n,event:o}){if(!Array.isArray(t))return{error:LT};let{appliedPolicies:i}=It({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:Xu.message}}function To(t){let{appliedPolicies:e}=It({tournamentRecord:t.tournamentRecord,drawDefinition:t.drawDefinition,event:t.event});return{competitionPolicy:e?.[iu]}}function Li({element:t,accessor:e}){if(typeof e!="string")return{values:[]};let r=q(t),n=e.split("."),o=[],i;a({targetElement:r,attributes:n});let s={value:i};return o.length&&(s.values=o),s;function a({targetElement:c,attributes:u=[],significantCharacters:p}){for(let[d,l]of u.entries())if(c?.[l]){let f=u.slice(d+1);f.length?Array.isArray(c[l])?c[l].forEach(I=>a({targetElement:I,attributes:f})):(c=c[l],m({targetElement:c,index:d})):(i||(i=c[l]),o.includes(c[l])||o.push(c[l]))}function m({targetElement:d,index:l}){if(d&&l===u.length-1&&["string","number"].includes(typeof d)){let f=p?d.slice(0,p):d;i?o.includes(f)||o.push(f):(i=f,o.push(f))}}}}function yo({requireTimeStamp:t,scaleAttributes:e,participant:r}){if(!r)return{error:ga};if(!Tt(e))return{error:O};if(r.timeItems??=[],Array.isArray(r.timeItems)){let{accessor:n,scaleType:o,eventType:i,scaleName:s}=e,a=[ri,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!==ri)return{error:Yc};let f=n&&Li({element:u.itemValue,accessor:n}),g=f?.value||u.itemValue,I={rawValue:f&&u.itemValue,eventType:d,scaleDate:u.itemDate,scaleValue:g,scaleName:l,scaleType:m};return{...P,scaleItem:I}}}return{...P,scaleItem:void 0}}function Ep({value:t,sourceRange:e,targetRange:r}){if(!Array.isArray(e)||e.length!==2)return 0;let n=Math.min(...e),o=Math.max(...e),i=Math.min(...r),s=Math.max(...r);return(t-n)*(s-i)/(o-n)+i}var RR="NTRP";var bR="DUPR",CR="UTR_P",MR="UTPR";var vR="SQUASH_LEVELS",OR="US_SQUASH",_R="USATT",xR="ITTF",wR="USAR";var Xw={ELO:"ELO",NTRP:RR,TRN:"TRN",UTR:"UTR",WTN:"WTN",DUPR:bR,UTR_P:CR,UTPR:MR,PSA:"PSA",SQUASH_LEVELS:vR,US_SQUASH:OR,USATT:_R,ITTF:xR,USAR:wR,BWF:"BWF"};var MY={ELO:{defaultInitialization:1500,decimalsCount:0,range:[0,3e3],ascending:!1},[RR]:{accessors:["ntrpRating","dntrpRatingHundredths"],attributes:{ustaRatingType:""},accessor:"dntrpRatingHundredths",defaultInitialization:3,decimalsCount:1,ascending:!1,range:[1,7]},UTR:{defaultInitialization:6,accessors:["utrRating"],accessor:"utrRating",decimalsCount:2,ascending:!1,range:[1,16]},WTN:{attributes:{confidence:{generator:!0,range:[60,100]}},accessors:["wtnRating","confidence"],defaultInitialization:23,accessor:"wtnRating",ascending:!0,decimalsCount:2,range:[40,1]},[bR]:{defaultInitialization:3.5,accessors:["duprRating","reliabilityScore"],accessor:"duprRating",attributes:{reliabilityScore:{generator:!0,range:[0,100]}},decimalsCount:3,ascending:!1,range:[2,8]},[CR]:{defaultInitialization:5,accessors:["utrpRating","verified"],accessor:"utrpRating",attributes:{verified:{type:"boolean"},provisional:{type:"string"}},decimalsCount:1,ascending:!1,range:[1,10]},[MR]:{defaultInitialization:3.5,accessor:"utprRating",decimalsCount:1,ascending:!1,range:[2,5],deprecated:!0},PSA:{defaultInitialization:500,accessor:"psaPoints",decimalsCount:0,ascending:!1,range:[0,3e3],attributes:{tournaments:{generator:!0,range:[1,20]},divisor:{generator:!0,range:[10,20]}}},[vR]:{defaultInitialization:2e3,accessor:"squashLevel",decimalsCount:0,ascending:!1,range:[0,7e3]},[OR]:{defaultInitialization:3.5,accessor:"usSquashRating",decimalsCount:1,ascending:!1,range:[2,6]},[_R]:{defaultInitialization:1e3,accessor:"usattRating",decimalsCount:0,ascending:!1,range:[200,3e3]},[xR]:{defaultInitialization:500,accessor:"ittfPoints",decimalsCount:0,ascending:!1,range:[0,2e4]},[wR]:{defaultInitialization:1e4,accessor:"usarRanking",decimalsCount:0,ascending:!0,range:[1,25e3]},BWF:{defaultInitialization:5e3,accessor:"bwfPoints",decimalsCount:0,ascending:!0,range:[0,15e4],attributes:{tournaments:{generator:!0,range:[1,10]}}}},Ke=MY;function Ap({sourceRatingType:t,sourceRating:e}){let r=Ke[t]?.range,n=r?.[0]>r?.[1],o=Ke["ELO"].range;return Ep({value:n?r[0]-e:e,sourceRange:r,targetRange:o})}function Jw({targetRatingType:t,sourceRating:e}){let r=Ke[t]?.decimalsCount||0,n=Ke[t]?.range,o=n?.[0]>n?.[1],i=Math.max(...n),s=Ke["ELO"]?.range,a=Ep({targetRange:n,sourceRange:s,value:e}),c=Number.parseFloat(a?.toFixed(r))||0;return o?i-c:c}function Pl(t){let{tournamentRecord:e,participantIds:r,scaleName:n,eventType:o,convertToELO:i,adHocRatings:s={}}=t,a=t.scaleAccessor??Ke[n]?.accessor,c=e.participants??[];for(let u of r??[]){let p=c?.find(d=>d.participantId===u),m;i&&(m=FR({scaleName:`${"ELO"}.${Sp}`,participant:p,eventType:o})),m||(m=FR({scaleName:`${n}.${Sp}`,participant:p,eventType:o}),m&&i&&n!=="ELO"&&(m=Ap({sourceRatingType:n,sourceRating:m}))),!m&&n&&(m=FR({scaleAccessor:a,participant:p,scaleName:n,eventType:o}),m&&i&&n!=="ELO"&&(m=Ap({sourceRatingType:n,sourceRating:m}))),m&&!s[u]&&(s[u]=m)}return s}function FR({scaleType:t=vo,scaleAccessor:e,participant:r,scaleName:n,eventType:o}){let a=(r&&yo({scaleAttributes:{eventType:o??Ea,scaleType:t,scaleName:n},participant:r}))?.scaleItem?.scaleValue;return e&&Tt(a)?a[e]:a}function kR(t){let{tournamentRecord:e,drawDefinition:r,participantIds:n,event:o}=t;if(!r)return{error:$};if(!n?.length)return{error:nt};let{competitionPolicy:i}=To({tournamentRecord:e,drawDefinition:r,event:o});if(!i)return{...P};let s=i.ratingPolicy,a=s.baselineRating.scaleName,c=s.ratingAggregation??"AVERAGE",u=o?.eventType,p=a?Pl({tournamentRecord:e,participantIds:n,scaleName:a,eventType:u}):{},m={};for(let l of n){let f=vY({tournamentRecord:e,participantId:l,adHocRatings:p,aggregation:c,eventType:u});m[l]={participantId:l,baselineRating:f,dynamicFormRating:f,pressureRating:0,roundsPlayed:0,wins:0,losses:0,draws:0,totalPointsWon:0,totalPointsLost:0,ratingHistory:[]}}let d={participantStates:m,roundStates:{}};return ut({element:r,extension:{name:Ra,value:d}}),{competitionState:d,...P}}function vY({tournamentRecord:t,participantId:e,adHocRatings:r,aggregation:n,eventType:o}){if(r[e]!==void 0)return r[e];if(o===wt){let s=t.participants?.find(a=>a.participantId===e)?.individualParticipantIds;if(s?.length){let a=s.map(c=>r[c]??0);return OY(a,n)}}return 0}function OY(t,e){if(!t.length)return 0;switch(e){case"MIN":return Math.min(...t);case"MAX":return Math.max(...t);case"SUM":return t.reduce((r,n)=>r+n,0);default:return t.reduce((r,n)=>r+n,0)/t.length}}function Fo({drawDefinition:t}){let{extension:e}=ot({element:t,name:Ra});return{competitionState:e?.value}}function tL(t){let e=t.score?.sets??[];if(!e.length)return Zw(t);let r=0,n=0;for(let o of e){let i=o.side1Score??0,s=o.side2Score??0;if(o.side1TiebreakScore!==void 0||o.side2TiebreakScore!==void 0){let a=o.side1TiebreakScore??0,c=o.side2TiebreakScore??0,u=a+c;if(u>0){r+=i-(o.winningSide===1?1:0)+a/u,n+=s-(o.winningSide===2?1:0)+c/u;continue}}r+=i,n+=s}return r>0||n>0?{side1Count:r,side2Count:n}:Zw(t)}function Zw(t){let{winningSide:e}=t;return e===1?{side1Count:1,side2Count:0}:e===2?{side1Count:0,side2Count:1}:{side1Count:0,side2Count:0}}function GR({pointsWon:t,pointsLost:e,competitionPolicy:r}){let n=t+e;if(n===0)return .5;let o=t/n,i=r.ratingPolicy.pressureRating;if(!i||i.actualOutputMethod==="POINT_SHARE")return o;let s=i.weights??{pointShare:1},a=(t-e)/n,c=0,u=s.pointShare??1,p=s.pointDifferential??0,m=s.contextFactor??0,d=u+p+m;return d===0?o:(u*o+p*a+m*c)/d}function OI(t,e,r){return 1/(1+Math.pow(10,(e-t)/r))}function Km(t){let{tournamentRecord:e,drawDefinition:r,matchUp:n,event:o}=t;if(!r)return{error:$};if(!n)return{error:Xe};let{competitionPolicy:i}=To({tournamentRecord:e,drawDefinition:r,event:o});if(!i)return{...P};let{competitionState:s}=Fo({drawDefinition:r});if(!s)return{...P};let a=n.sides??[],c=a[0]?.participantId,u=a[1]?.participantId;if(!c||!u)return{...P};let p=s.participantStates[c],m=s.participantStates[u];if(!p||!m)return{...P};let{winningSide:d}=n,{side1Count:l,side2Count:f}=tL(n),g=GR({pointsWon:l,pointsLost:f,competitionPolicy:i}),I=GR({pointsWon:f,pointsLost:l,competitionPolicy:i}),S=i.ratingPolicy.dynamicFormRating.logisticScale,h=i.ratingPolicy.dynamicFormRating.kFactor,T=OI(p.baselineRating,m.baselineRating,S),y=OI(m.baselineRating,p.baselineRating,S),E=OI(p.dynamicFormRating,m.dynamicFormRating,S),A=OI(m.dynamicFormRating,p.dynamicFormRating,S),N=i.ratingPolicy.pressureRating?.enabled,U=N?g-T:0,R=N?I-y:0,D=i.ratingPolicy.dynamicFormRating.enabled,b=D?p.dynamicFormRating+h*(g-E):p.dynamicFormRating,C=D?m.dynamicFormRating+h*(I-A):m.dynamicFormRating,_=n.roundNumber??0;return p.dynamicFormRating=b,p.pressureRating+=U,p.roundsPlayed+=1,p.wins+=d===1?1:0,p.losses+=d===2?1:0,p.draws+=d?0:1,p.totalPointsWon+=l,p.totalPointsLost+=f,p.ratingHistory.push({roundNumber:_,opponentParticipantId:u,dynamicFormRatingBefore:p.dynamicFormRating-h*(g-E),dynamicFormRatingAfter:b,pressureDelta:U,actualOutput:g,expectedOutput:T}),m.dynamicFormRating=C,m.pressureRating+=R,m.roundsPlayed+=1,m.wins+=d===2?1:0,m.losses+=d===1?1:0,m.draws+=d?0:1,m.totalPointsWon+=f,m.totalPointsLost+=l,m.ratingHistory.push({roundNumber:_,opponentParticipantId:c,dynamicFormRatingBefore:m.dynamicFormRating-h*(I-A),dynamicFormRatingAfter:C,pressureDelta:R,actualOutput:I,expectedOutput:y}),ut({element:r,extension:{name:Ra,value:s}}),{...P}}var xr="ABANDONED",cu="AWAITING_RESULT";var Zn="CANCELLED",ie="COMPLETED",Pp="DEAD_RUBBER",xt="DEFAULTED",ge="DOUBLE_DEFAULT",Qt="DOUBLE_WALKOVER",bn="IN_PROGRESS",Xr="INCOMPLETE",VR="NOT_PLAYED",Ue="RETIRED",Fi="SUSPENDED",zt="TO_BE_PLAYED",Lt="WALKOVER",eL=[cu,ie,xt,bn,Xr,Ue,Fi],vy=[cu,ie,xt,Qt,ge,bn,Xr,Ue,Fi,Lt],Oy=[xr,cu,"BYE",Zn,ie,Pp,xt,Qt,ge,bn,Xr,VR,Ue,Fi,zt,Lt],_y=["BYE",Qt,ge,ie,xt,Ue,Lt],xy=[xr,cu,Zn,Pp,bn,Xr,VR,Fi,zt,void 0],Mt=[Zn,xr,ie,Pp,xt,Qt,ge,Ue,Lt],Nl=[xr,ie,xt,Qt,ge,bn,Ue,Lt],wy=[bn,Xr,Fi,zt],Ly={ABANDONED:xr,AWAITING_RESULT:cu,BYE:"BYE",CANCELLED:Zn,COMPLETED:ie,DEAD_RUBBER:Pp,DEFAULTED:xt,DOUBLE_WALKOVER:Qt,DOUBLE_DEFAULT:ge,IN_PROGRESS:bn,INCOMPLETE:Xr,NOT_PLAYED:VR,RETIRED:Ue,SUSPENDED:Fi,TO_BE_PLAYED:zt,WALKOVER:Lt};function BR(t){let{tournamentRecord:e,drawDefinition:r,roundNumber:n,matchUps:o,event:i}=t;if(!r)return{error:$};let{competitionPolicy:s}=To({tournamentRecord:e,drawDefinition:r,event:i});if(!s)return{...P};let{competitionState:a}=Fo({drawDefinition:r});if(!a)return{...P};if(a.roundStates[n]?.processed)return{...P};let c=o.filter(p=>p.roundNumber===n&&(p.winningSide||Mt.includes(p.matchUpStatus)));for(let p of c)Km({tournamentRecord:e,drawDefinition:r,matchUp:p,event:i});let{competitionState:u}=Fo({drawDefinition:r});return u&&(u.roundStates[n]={roundNumber:n,processed:!0},ut({element:r,extension:{name:Ra,value:u}})),{...P}}function HR({drawDefinition:t}){return t?(ut({element:t,extension:{name:Ra,value:void 0}}),{...P}):{error:$}}var YR={};Gt(YR,{getCompetitionLeaderboard:()=>ky,getCompetitionParticipantState:()=>Fy,getCompetitionPolicy:()=>To,getCompetitionState:()=>Fo,getLinkedTournamentIds:()=>Np,getTournamentIds:()=>$m});function Fy({drawDefinition:t,participantId:e}){let{competitionState:r}=Fo({drawDefinition:t});return{participantState:r?.participantStates?.[e]}}function ky(t){let{tournamentRecord:e,drawDefinition:r,event:n}=t,{competitionPolicy:o}=To({tournamentRecord:e,drawDefinition:r,event:n}),{competitionState:i}=Fo({drawDefinition:r});if(!i||!o)return{leaderboard:[]};let s=o.victoryPolicy.primaryRanking;return{leaderboard:[...Object.values(i.participantStates)].sort((p,m)=>{let d=rL(m,s)-rL(p,s);if(d!==0)return d;for(let l of o.victoryPolicy.tiebreakOrder??[]){let f=_Y(p,m,l,i.participantStates);if(f!==0)return f}return 0}).map((p,m)=>({participantId:p.participantId,rank:m+1,baselineRating:p.baselineRating,dynamicFormRating:p.dynamicFormRating,pressureRating:p.pressureRating,wins:p.wins,losses:p.losses,draws:p.draws,pointsWon:p.totalPointsWon,pointsLost:p.totalPointsLost}))}}function rL(t,e){switch(e){case"PRESSURE_RATING":return t.pressureRating;case"DYNAMIC_FORM_RATING":return t.dynamicFormRating;case"WINS":return t.wins;case"POINTS":return t.totalPointsWon;default:return t.wins}}function _Y(t,e,r,n){switch(r){case"POINT_DIFFERENTIAL":return t.totalPointsWon-t.totalPointsLost-(e.totalPointsWon-e.totalPointsLost);case"DYNAMIC_FORM_RATING":return t.dynamicFormRating-e.dynamicFormRating;case"PRESSURE_RATING":return t.pressureRating-e.pressureRating;case"HEAD_TO_HEAD":{let o=t.ratingHistory.filter(c=>c.opponentParticipantId===e.participantId),i=e.ratingHistory.filter(c=>c.opponentParticipantId===t.participantId),s=o.filter(c=>c.actualOutput>.5).length,a=i.filter(c=>c.actualOutput>.5).length;return s-a}case"HEAD_TO_HEAD_PRESSURE":{let o=t.ratingHistory.filter(c=>c.opponentParticipantId===e.participantId),i=e.ratingHistory.filter(c=>c.opponentParticipantId===t.participantId),s=o.reduce((c,u)=>c+u.pressureDelta,0),a=i.reduce((c,u)=>c+u.pressureDelta,0);return s-a}case"STRENGTH_OF_OPPOSITION":{let o=t.ratingHistory.map(c=>n[c.opponentParticipantId]?.baselineRating??0),i=e.ratingHistory.map(c=>n[c.opponentParticipantId]?.baselineRating??0),s=o.length?o.reduce((c,u)=>c+u,0)/o.length:0,a=i.length?i.reduce((c,u)=>c+u,0)/i.length:0;return s-a}default:return 0}}function Np({tournamentRecords:t}){return typeof t!="object"||!Object.keys(t).length?{error:kt}:{linkedTournamentIds:Object.assign({},...Object.keys(t).map(r=>{let n=t[r],o=n?.tournamentId,{extension:i}=ot({element:n,name:ba}),s=(i?.value?.tournamentIds??[]).filter(a=>a!==o);return{[r]:s}}))}}var rv={};Gt(rv,{adHocPositionSwap:()=>TC,addAdHocMatchUps:()=>Kp,addDrawDefinitionTimeItem:()=>CS,addFinishingRounds:()=>hc,addGoesTo:()=>Ts,addLinkedConsolationStructure:()=>Qb,addPlayoffStructures:()=>LS,addQualifyingStructure:()=>SC,addVoluntaryConsolationStructure:()=>dS,allPlayoffPositionsFilled:()=>GE,alternateDrawPositionAssignment:()=>Jb,assignDrawPosition:()=>NC,assignDrawPositionBye:()=>Cr,attachConsolationStructures:()=>TS,attachPlayoffStructures:()=>yS,attachQualifyingStructure:()=>bS,attachStructures:()=>ES,autoSeeding:()=>A1,automatedPlayoffPositioning:()=>wa,automatedPositioning:()=>Ru,buildDrawHierarchy:()=>E1,checkValidEntries:()=>Ef,deleteAdHocMatchUps:()=>DC,drawMatic:()=>tm,findDrawDefinition:()=>iA,generateAdHocMatchUps:()=>Nc,generateAdHocRounds:()=>_f,generateAndPopulatePlayoffStructures:()=>gf,generateConsolationStructure:()=>zb,generateDrawDefinition:()=>bc,generateDrawMaticRound:()=>Uf,generateDrawStructuresAndLinks:()=>Af,generateDrawTypeAndModifyDrawDefinition:()=>Pf,generateQualifyingStructure:()=>mf,generateSwissRound:()=>T1,generateVoluntaryConsolation:()=>RA,getAssignedParticipantIds:()=>$i,getAvailableMatchUpsCount:()=>Sf,getAvailablePlayoffProfiles:()=>Hp,getDraftState:()=>yA,getDrawDefinitionTimeItem:()=>$y,getDrawParticipantRepresentativeIds:()=>eA,getDrawStructures:()=>In,getDrawTypeCoercion:()=>Qp,getEligibleVoluntaryConsolationParticipants:()=>JE,getLuckyDrawRoundStatus:()=>df,getMatchUpsMap:()=>Ie,getParticipantIdFinishingPositions:()=>Tf,getPositionAssignments:()=>Cu,getPositionsPlayedOff:()=>Pu,getRandomQualifierList:()=>hA,getSeedingThresholds:()=>EE,getSeedsCount:()=>Xp,getStructureSeedAssignments:()=>Pr,getSwissChart:()=>tA,getSwissStandings:()=>ZE,getTeamLineUp:()=>Ys,getValidGroupSizes:()=>id,hasLuckyRounds:()=>tS,initializeDraft:()=>UC,isAdHoc:()=>Ae,isCompletedStructure:()=>No,isValidForQualifying:()=>TA,luckyDrawAdvancement:()=>yC,luckyLoserDrawPositionAssignment:()=>Wb,modifyDrawDefinition:()=>EC,modifyDrawName:()=>FS,modifySeedAssignment:()=>sC,mutate:()=>CC,positionActions:()=>SA,pruneDrawDefinition:()=>PC,qualifierDrawPositionAssignment:()=>PS,qualifierProgression:()=>Zb,query:()=>WC,remapDrawDefinitionMatchUpIds:()=>AS,removeDrawPositionAssignment:()=>Bp,removeRoundMatchUps:()=>RC,removeSeededParticipant:()=>IC,removeStructure:()=>mC,renameStructures:()=>cC,resetDrawDefinition:()=>AC,resetQualifyingStructure:()=>pC,resetVoluntaryConsolationStructure:()=>tb,resolveDraftPositions:()=>uC,seedWithdrawalCascade:()=>hC,setDrawParticipantRepresentativeIds:()=>qR,setDrawPositionPreferences:()=>Xb,setPositionAssignments:()=>jb,setStructureOrder:()=>aC,setSubOrder:()=>bC,shiftAdHocRounds:()=>Yb,swapAdHocRounds:()=>qb,swapDrawPositionAssignments:()=>gC,updateTeamLineUp:()=>As,validatePlayoffGroups:()=>cf,withdrawParticipantAtDrawPosition:()=>Bb});var CC={};Gt(CC,{adHocPositionSwap:()=>TC,addAdHocMatchUps:()=>Kp,addDrawDefinitionTimeItem:()=>CS,addLinkedConsolationStructure:()=>Qb,addPlayoffStructures:()=>LS,addQualifyingStructure:()=>SC,addVoluntaryConsolationStructure:()=>dS,alternateDrawPositionAssignment:()=>Jb,assignDrawPosition:()=>NC,assignDrawPositionBye:()=>Cr,attachConsolationStructures:()=>TS,attachPlayoffStructures:()=>yS,attachQualifyingStructure:()=>bS,attachStructures:()=>ES,automatedPlayoffPositioning:()=>wa,automatedPositioning:()=>Ru,deleteAdHocMatchUps:()=>DC,initializeDraft:()=>UC,luckyDrawAdvancement:()=>yC,luckyLoserDrawPositionAssignment:()=>Wb,modifyDrawDefinition:()=>EC,modifyDrawName:()=>FS,modifySeedAssignment:()=>sC,pruneDrawDefinition:()=>PC,qualifierDrawPositionAssignment:()=>PS,qualifierProgression:()=>Zb,remapDrawDefinitionMatchUpIds:()=>AS,removeDrawPositionAssignment:()=>Bp,removeRoundMatchUps:()=>RC,removeSeededParticipant:()=>IC,removeStructure:()=>mC,renameStructures:()=>cC,resetDrawDefinition:()=>AC,resetQualifyingStructure:()=>pC,resetVoluntaryConsolationStructure:()=>tb,resolveDraftPositions:()=>uC,seedWithdrawalCascade:()=>hC,setDrawParticipantRepresentativeIds:()=>qR,setDrawPositionPreferences:()=>Xb,setPositionAssignments:()=>jb,setStructureOrder:()=>aC,setSubOrder:()=>bC,shiftAdHocRounds:()=>Yb,swapAdHocRounds:()=>qb,swapDrawPositionAssignments:()=>gC,updateTeamLineUp:()=>As,withdrawParticipantAtDrawPosition:()=>Bb});var Gy=t=>e=>t[e],Ul=(t=[])=>t.map(Te).filter(Boolean),_I=(t=[])=>t.map(ft).filter(Boolean),ft=(t={})=>Gy(t)("participantId"),nL=(t={})=>Gy(t)("drawPosition");var Te=(t={})=>Gy(t)("matchUpId"),dc=(t={})=>Gy(t)("drawId");function qR({representativeParticipantIds:t,drawDefinition:e}){if(!e)return{error:Rr};if(!Array.isArray(t))return{error:O};let r=_I(e?.entries??[]);return t.length&&Yt(t,r).length<t.length?{error:O}:MI({drawDefinition:e,extension:{name:Cy,value:t}})}function ki(t,e,r){let n=m=>ot({element:m,name:Rn})?.extension?.value,o=r?.deprioritizeCompleted,i=r?.mode===uR&&Ow,s=r?.mode===cR&&pR,a=s||i||Aa,c=m=>m?.stage===H&&m?.stageSequence===1,u=m=>c(m)?-1:a[m?.stage],p=m=>m?.matchUps.every(({matchUpStatus:d})=>Mt.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)||(xI(t)||0)-(xI(e)||0)}function xI(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 tt(t){let e=X(t,[{[Kt]:!0,[po]:!0}]);if(e.error)return e;let{drawDefinition:r,structureId:n}=t,{structures:o}=In({drawDefinition:r}),i=o?.flatMap(c=>c.structures?[...c.structures].concat(c):c),s=i?.find(c=>c.structureId===n);if(!s)return{error:Nt};let a=s.structureType===tu?i?.find(c=>c.structures?.some(u=>u.structureId===n)):void 0;return{structure:s,containingStructure:a}}function In({withStageGrouping:t,drawDefinition:e,stageSequences:r,stageSequence:n,roundTarget:o,sortConfig:i,stages:s,stage:a}){let c=!e&&$||!e?.structures&&Lg||void 0;if(c)return{error:c,structures:[],stageStructures:{}};let u=f=>{let g=ot({element:f,name:Rn})?.extension?.value;return!o||o===g},p=e?.structures?.filter(d).filter(l).filter(u).sort((f,g)=>ki(f,g,i))??[],m=t?Object.assign({},...Jc.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 Vy({drawDefinition:t}){if(!t)return{error:$};let e={};return{allPositionedParticipantIds:(t.structures??[]).map(n=>{let o=n.stage;e[o]||(e[o]=[]);let{positionAssignments:i}=Pt({structure:n}),s=i?.map(ft).filter(Boolean)??[];return e[o].push(...s),s}).flat(),stagePositionedParticipantIds:e}}function Pt({drawDefinition:t,structureId:e,structure:r}){let n,o=[];if(!r){if(!t)return{positionAssignments:o,error:$};if({structure:r,error:n}=tt({drawDefinition:t,structureId:e}),n)return{positionAssignments:o,error:n}}return r.structures?o=[].concat(...r.structures.map(i=>Pt({structure:i}).positionAssignments)):r.positionAssignments?o=r.positionAssignments:n=LU,{positionAssignments:o,error:n}}function se({drawDefinition:t,structureId:e,structure:r}){let n=Pt({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}}function dt(t,e,r){let n=e.reduce((o,i)=>(o[i]=!0,o),{});return X(t,[n],r)}var wI="addDrawDefinition",zm="addMatchUps",Ti="addParticipants",LI="addScaleItems",$R="addEvent",By="addVenue",Gi="audit",Hy="dataIssue",FI="deleteParticipants",kI="deleteVenue",GI="deletedDrawIds",VI="deletedMatchUpIds",BI="modifyDrawDefinition",KR="modifyDrawEntries",zR="modifyEventEntries",HI="modifyMatchUp",tr="modifyParticipants",WI="modifyPositionAssignments",YI="modifySeedAssignments",ii="modifyTournamentDetail",Eo="modifyVenue",Dl="mutations",Wy="publishEvent",QR="publishEventSeeding",XR="publishOrderOfPlay",JR="publishParticipants",jI="unPublishEvent",qI="unPublishEventSeeding",$I="unPublishOrderOfPlay",ZR="unPublishParticipants",Rl="unPublishTournament",Up="updateInContextMatchUp",oL={ADD_DRAW_DEFINITION:wI,ADD_MATCHUPS:zm,ADD_PARTICIPANTS:Ti,ADD_SCALE_ITEMS:LI,ADD_EVENT:$R,ADD_VENUE:By,AUDIT:Gi,DATA_ISSUE:Hy,DELETE_PARTICIPANTS:FI,DELETE_VENUE:kI,DELETED_DRAW_IDS:GI,DELETED_MATCHUP_IDS:VI,MODIFY_DRAW_DEFINITION:BI,MODIFY_DRAW_ENTRIES:KR,MODIFY_EVENT_ENTRIES:zR,MODIFY_MATCHUP:HI,MODIFY_PARTICIPANTS:tr,MODIFY_POSITION_ASSIGNMENTS:WI,MODIFY_SEED_ASSIGNMENTS:YI,MODIFY_TOURNAMENT_DETAIL:ii,MODIFY_VENUE:Eo,MUTATIONS:Dl,PUBLISH_EVENT_SEEDING:QR,PUBLISH_EVENT:Wy,PUBLISH_ORDER_OF_PLAY:XR,PUBLISH_PARTICIPANTS:JR,UNPUBLISH_EVENT_SEEDING:qI,UNPUBLISH_EVENT:jI,UNPUBLISH_ORDER_OF_PLAY:$I,UNPUBLISH_PARTICIPANTS:ZR,UNPUBLISH_TOURNAMENT:Rl,UPDATE_INCONTEXT_MATCHUP:Up};function Yy(t,e){if(!t)return{error:$};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)}),{...P}}function iL(t){if(!t)return;let e=Date.now(),r=t.updatedAt;if(r){let n=typeof r=="string"?new Date(r).getTime():r.getTime();!Number.isNaN(n)&&e<=n&&(e=n+1)}t.updatedAt=new Date(e).toISOString()}function ko({drawDefinition:t,tournamentId:e,matchUps:r,eventId:n}){if(t&&Yy(t),Array.isArray(r))for(let o of r)iL(o);return at({payload:{matchUps:r,tournamentId:e,eventId:n},topic:zm}),{...P}}function xn({drawDefinition:t,tournamentId:e,matchUpIds:r,eventId:n,action:o}){t&&Yy(t),at({topic:VI,payload:{tournamentId:e,matchUpIds:r,eventId:n,action:o}});for(let i of r)YT({key:i});return{...P}}function gt({drawDefinition:t,tournamentId:e,structureId:r,context:n,eventId:o,matchUp:i}){return i?(t&&Ft({drawDefinition:t,structureIds:r?[r]:void 0,tournamentId:e,eventId:o}),iL(i),at({topic:HI,payload:{matchUp:i,tournamentId:e,context:n},key:i.matchUpId}),{...P}):(console.log(Xe),{error:Xe})}function sL({tournamentId:t,inContextMatchUp:e}){return e?(at({payload:{inContextMatchUp:e,tournamentId:t},topic:Up,key:e.matchUpId}),{...P}):{error:Xe}}function lc({tournamentId:t,eventId:e,drawDefinition:r}){return r?(Yy(r),at({payload:{drawDefinition:r,tournamentId:t,eventId:e},topic:wI,key:r.drawId}),{...P}):(console.log($),{error:$})}function aL({tournamentId:t,eventId:e,drawId:r}){return at({payload:{drawId:r,tournamentId:t,eventId:e},topic:GI,key:r}),YT({key:r}),{...P}}function Ft({drawDefinition:t,tournamentId:e,structureIds:r,eventId:n}){return t?(Yy(t,r),at({payload:{tournamentId:e,eventId:n,drawDefinition:t},topic:BI,key:t.drawId}),{...P}):{error:$}}function bl({drawDefinition:t,tournamentId:e,structure:r,eventId:n}){let o=dt({drawDefinition:t,structure:r},[Kt,oc]);if(o.error)return o;let i=r.seedAssignments,s=r.structureId,a=t.drawId;return at({payload:{tournamentId:e,eventId:n,drawId:a,structureId:s,seedAssignments:i},topic:YI,key:t.drawId}),Ft({structureIds:[s],drawDefinition:t,tournamentId:e,eventId:n}),{...P}}function Sn({drawDefinition:t,tournamentId:e,structure:r,event:n}){let o=dt({drawDefinition:t,structure:r},[Kt,oc]);if(o.error)return o;let i=Pt({structure:r}),s=r.structureId,a=t.drawId,c=n?.eventId;return at({topic:WI,payload:{positionAssignments:i,tournamentId:e,structureId:s,eventId:c,drawId:a},key:s}),Ft({structureIds:[s],drawDefinition:t,tournamentId:e,eventId:c}),{...P}}function tb({tournamentRecord:t,drawDefinition:e,resetEntries:r,event:n}){if(!e)return{error:$};let o=e.structures?.find(s=>s.stage===Fe);if(!o)return{error:Nt};let i=o.matchUps?.map(({matchUpId:s})=>s)??[];return o.positionAssignments=[],o.seedAssignments=[],o.matchUps=[],xn({tournamentId:t?.tournamentId,action:"resetVoluntaryConsolationStructure",matchUpIds:i,drawDefinition:e}),r&&(e.entries=e.entries.filter(s=>s.entryStage!==Fe)),Ft({tournamentId:t?.tournamentId,eventId:n?.eventId,drawDefinition:e,structureIds:[o.structureId]}),{...P}}function Cl({drawPositions:t,structure:e}){if([Z,H].includes(e.stage)&&e.stageSequence===1)return;let{positionAssignments:r}=Pt({structure:e});r?.filter(({drawPosition:o})=>t?.includes(o))?.forEach(o=>{ut({element:o,extension:{name:yl,value:!0}})})}function fc(t){let{appliedPolicies:e,positionAction:r,drawDefinition:n}=t;if(e?.audit?.[su]===!1)return;let{extension:o}=ot({name:su,element:n}),i=Array.isArray(o?.value)?o?.value??[]:[];if(!i?.length){let a=n.structures.find(c=>c.stage===H);if(a){let c=Pt({structure:a}).positionAssignments?.map(({drawPosition:u,participantId:p,bye:m,qualifier:d})=>({drawPosition:u,participantId:p,qualifier:d,bye:m}));i.push({name:"initialMainAssignments",initialAssignments:c})}}let s={value:i.concat(r),name:su};ut({element:n,extension:s})}function Vi({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}}function Dp(t){let{sides:e,matchUpType:r}=t??{},n=t.potentialParticipants?.length?t.potentialParticipants.flat().map(s=>r===Rt?s?.individualParticipantIds??[]:s.participantId).flat():[],o=(e??[]).map(s=>r===Rt&&(s?.participant?.individualParticipantIds??[])||s?.participantId&&[s.participantId]||[]).flat();return{individualParticipantIds:o.concat(n).flat(),enteredIndividualParticipantIds:o,potentialIndividualParticipantIds:n}}function Ar(t){return t?.tournamentRecords??(t?.tournamentRecord&&{[t.tournamentRecord.tournamentId]:t.tournamentRecord})??{}}var uu="SIGN_IN_STATUS",eb="SIGNED_OUT",Rp="SIGNED_IN",ur="TEAM",St="INDIVIDUAL",qr="GROUP",lt="PAIR",vt="TEAM",bp={TEAM_PARTICIPANT:ur,INDIVIDUAL:St,GROUP:qr,TEAM:vt,PAIR:lt},cL={INDIVIDUAL:St,GROUP:qr,PAIR:lt,TEAM:vt,SIGN_IN_STATUS:uu,SIGNED_OUT:eb,SIGNED_IN:Rp};function Cp({participantsProfile:t,participants:e=[],deepCopy:r}){let n=new Map,o=r!==!1?q(e,t?.convertExtensions,!0):e,i=o.filter(c=>c.participantType===vt),s=o.filter(c=>c.participantType===qr),a=o.filter(c=>c.participantType===lt);return o.forEach(c=>{if(c.participantType===St){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 rb(t){return t&&typeof String.fromCodePoint<"u"?t.toUpperCase().replace(/./g,e=>String.fromCodePoint(e.charCodeAt(0)+127397)):t}function uL(t){let e=Object.assign({},...yi.filter(r=>r.ioc).map(r=>({[r.ioc]:r.iso})));return rb(e[t])}var yi=[{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 jy({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=yi.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 pL({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?fs({template:e,source:s}):s)}}}}function Ao(t){let{tournamentRecord:e,participantId:r}=t,n=t.tournamentRecords||e&&{[e.tournamentId]:e}||{};for(let o of Object.values(n)){let i=o.participants?.find(s=>s.participantId===r);if(i)return{participant:i,tournamentId:o.tournamentId}}return{error:ee}}function qy(t){let{tournamentRecord:e,participantId:r}=t;if(r){let o=Ao({tournamentRecord:e,participantId:r});return o.participant??o}let n=t.element||t.drawDefinition||t.event||t.tournamentRecord;return n||{error:nt}}function Jr(t){let{returnPreviousValues:e,itemSubTypes:r,itemType:n}=t,o=qy(t);if(o.error)return o;if(r&&!Array.isArray(r))return{error:O,context:{itemSubTypes:r}};if(!Array.isArray(o.timeItems))return{error:Zg};let i=o.timeItems.filter(a=>a?.itemType===n).filter(a=>!r?.length||r.some(c=>a?.itemSubTypes?.includes(c))).sort((a,c)=>{let u=new Date(a.createdAt||void 0).getTime(),p=new Date(c.createdAt||void 0).getTime();return u-p}),s=q(i.pop(),!1,!0);if(s){let a={timeItem:s,...P};return e&&Object.assign(a,{previousItems:i}),a}else return{info:fe}}function $y({returnPreviousValues:t,drawDefinition:e,itemSubTypes:r,itemType:n}){if(!e)return{error:Pn};if(!e.timeItems)return{info:fe};let{timeItem:o,previousItems:i,info:s}=Jr({element:e,returnPreviousValues:t,itemSubTypes:r,itemType:n});return o&&{timeItem:o,previousItems:i}||{info:s}}function Mp({returnPreviousValues:t,itemSubTypes:e,itemType:r,event:n}){if(!n)return{error:le};if(!n.timeItems)return{info:fe};let{timeItem:o,previousItems:i,info:s}=Jr({returnPreviousValues:t,element:n,itemSubTypes:e,itemType:r});return o&&{timeItem:o,previousItems:i}||{info:s}}function Ml({returnPreviousValues:t,tournamentRecord:e,itemSubTypes:r,itemType:n}){if(!e)return{error:j};if(!e.timeItems)return{info:fe};let{timeItem:o,previousItems:i,info:s}=Jr({element:e,returnPreviousValues:t,itemSubTypes:r,itemType:n});return o&&{timeItem:o,previousItems:i}||{info:s}}function Ky({returnPreviousValues:t,tournamentRecord:e,participantId:r,itemSubTypes:n,itemType:o}){let i=dt({tournamentRecord:e,participantId:r},[rt,sr]);if(i.error)return i;let s=Ao({tournamentRecord:e,participantId:r});if(s.error)return s;let{participant:a}=s;if(!a?.timeItems)return{info:fe};let{timeItem:c,previousItems:u,info:p}=Jr({element:s.participant,returnPreviousValues:t,itemSubTypes:n,itemType:o});return c&&{timeItem:c,previousItems:u}||{info:p}}var xY={[qr]:"groupParticipantIds",[lt]:"pairParticipantIds",[vt]:"teamParticipantIds"},wY={[qr]:"groups",[vt]:"teams"};function zy({withIndividualParticipants:t,convertExtensions:e,tournamentRecord:r,withSignInStatus:n,withScaleValues:o,withGroupings:i,internalUse:s,withISO2:a,withIOC:c}){let u=[],p={};for(let d of r.participants??[]){let l=d?.participantId;l&&kY({participantMap:p,participantId:l})}for(let d of r.participants??[]){let l=q(d,e,s),{participantId:f,individualParticipantIds:g,participantType:I}=l;if(!p[f]){u.push(f);continue}if(Object.assign(p[f].participant,l),g){let S=FY({individualParticipantIds:g,participantCopy:l,participantMap:p,participantType:I,participantId:f});S.missingParticipantIds.length&&u.push(...S.missingParticipantIds)}if(n&&(p[f].participant.signedIn=LY(l)),o){let{ratings:S,rankings:h,seedings:T}=sc({participant:l});p[f].participant.seedings=T,p[f].participant.rankings=h,p[f].participant.ratings=S}(c||a)&&jy({participant:p[f].participant,withISO2:a,withIOC:c})}if(t){let d=Tt(t)?t:void 0;pL({participantMap:p,template:d})}let m;return i&&(m=Cp({participants:Object.values(p).map(({participant:d})=>d),participantsProfile:{convertExtensions:e},deepCopy:!1}).groupInfo),{missingParticipantIds:u,participantMap:p,groupInfo:m}}function LY(t){let{timeItem:e}=Jr({itemType:uu,element:t});return e?.itemValue===Rp}function FY({individualParticipantIds:t,participantCopy:e,participantMap:r,participantType:n,participantId:o}){let i=[];for(let s of t){let a=r[s]?.participant;if(!a){i.push(s);continue}if(a[xY[n]].push(o),[vt,qr].includes(n)){let{participantRoleResponsibilities:c,participantOtherName:u,participantName:p,participantId:m,teamId:d}=e,l=wY[n];a[l].push({participantRoleResponsibilities:c,participantOtherName:u,participantName:p,participantId:m,teamId:d})}if(n===lt){let c=t.find(u=>u!==s);r[s].pairIdMap[o]=c,r[s].pairIdMap[c]=o}}return{missingParticipantIds:i}}function kY({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:{[Ct]:{...r},[Rt]:{...r},[vt]:{...r},...r}}}function si({participantsProfile:t,useParticipantMap:e,tournamentRecord:r,contextProfile:n,inContext:o}){if(e)return zy({...t,...n,tournamentRecord:r});let i=q(r.participants,!1,!0)??[];(t?.withIOC||t?.withISO2)&&i.forEach(a=>jy({participant:a,...t}));let s;if((o||t?.withGroupings)&&i?.length&&({participantsWithGroupings:i,groupInfo:s}=Cp({participantsProfile:t,deepCopy:!1,participants:i})),t?.withScaleValues&&i?.length)for(let a of i){let{ratings:c,rankings:u}=sc({participant:a});a.rankings=u,a.ratings=c}return{participants:i,groupInfo:s}}var Qy="WALKOVER",nb="RETIRED",vl="COMPETITIVE",pu="ROUTINE",mu="DECISIVE",Ol="winRatio";var GY={[xi]:{policyName:"Competitive Bands Default",profileBands:{[mu]:20,[pu]:50}}},_l=GY;function to({policyDefinitions:t,tournamentRecord:e,contextProfile:r,drawDefinition:n,event:o}){let i={policies:{}};if(!r)return i;let s=lo({tournamentRecord:e,drawDefinition:n,event:o}).policyDefinitions;if(r.withCompetitiveness){let a=t?.[xi]??s?.[xi]??_l[xi];i.policies[xi]=a}return i}function Ei({tournamentRecord:t,drawDefinition:e,policyType:r,structure:n,event:o}){if(!t)return{error:j};let{appliedPolicies:i}=It({tournamentRecord:t,drawDefinition:e,structure:n,event:o});return i?.[r]?{policy:i[r]}:{info:Xu?.message}}function gc({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}=Ei({policyType:_o,tournamentRecord:t,event:n}),s=(t?ot({element:t,name:oi}).extension:void 0)?.value,c=(n&&ot({name:oi,element:n}).extension)?.value;return{scheduleTiming:{tournamentScheduling:s,eventScheduling:c,categoryName:e,categoryType:r,policy:o}}}function KI({tournamentRecord:t,event:e}){if(!t)return{};let{extension:r}=ot({element:t,name:AR}),n=r?.value;if(!n?.events?.length)return{};let o=e?n.events.find(s=>s.eventType===e.eventType&&(!s.eventName||s.eventName===e.eventName)&&(!s.category?.categoryName||s.category?.categoryName===e.category?.categoryName)):void 0;if(!o)return{};let i={};return o.drawSize!==void 0&&(i.drawSize=o.drawSize),o.maxWildcards!==void 0&&(i.maxWildcards=o.maxWildcards),o.maxAlternates!==void 0&&(i.maxAlternates=o.maxAlternates),o.maxQualifiers!==void 0&&(i.maxQualifiers=o.maxQualifiers),Object.keys(i).length?{constraints:i}:{}}var du="GEMscore",mL={GEM_SCORE:du};function dL({provisionalPositioning:t,rankBy:e=du,finishingPositions:r,groupResults:n,bestOf:o}){let i=[],s=[],a=[...r].sort(Zt),c=Math.max(...a);for(let{structureId:d,results:l}of n)for(let[f,g]of Object.entries(l)){let I=g.groupOrder||t&&g.provisionalOrder;if(!I)continue;let S={groupingValue:d,GEMscore:g.GEMscore,isBestFinisher:!1,finishingPosition:I,participantId:f};a.includes(I)?s.push(S):I>c&&i.push(S)}let u=[...s],p=o-s.length;p>0&&i.length>0&&i.toSorted((f,g)=>f.finishingPosition!==g.finishingPosition?f.finishingPosition-g.finishingPosition:e===du?(g.GEMscore??0)-(f.GEMscore??0):0).slice(0,p).forEach(f=>{f.isBestFinisher=!0,u.push(f)});let m={};for(let d of u){let l=d.finishingPosition;m[l]=(m[l]||0)+1}return{selectedParticipants:u,consumedPositions:m}}var Zr="ALTERNATE",zI="CONFIRMED",wr="DIRECT_ACCEPTANCE",vp="FEED_IN",QI="JUNIOR_EXEMPT",ks="LUCKY_LOSER",XI="ORGANISER_ACCEPTANCE",xl="QUALIFIER",VY="REGISTERED",JI="SPECIAL_EXEMPT",Lr="UNGROUPED",Bi="UNPAIRED",Op="WILDCARD",Cn="WITHDRAWN",Qm=[zI,wr,QI,XI,JI],ob=[vp,ks,xl],Hi=[zI,wr,vp,QI,XI,JI,Op],hr=[zI,wr,QI,ks,xl,XI,JI,Op],ib=[Zr,zI,wr,vp,QI,ks,XI,xl,VY,JI,Lr,Bi,Op,Cn],lL={ALTERNATE:Zr,CONFIRMED:zI,DIRECT_ACCEPTANCE:wr,DIRECT_ENTRY_STATUSES:Hi,DRAW_SPECIFIC_STATUSES:ob,EQUIVALENT_ACCEPTANCE_STATUSES:Qm,FEED_IN:vp,JUNIOR_EXEMPT:QI,LUCKY_LOSER:ks,ORGANISER_ACCEPTANCE:XI,QUALIFIER:xl,SPECIAL_EXEMPT:JI,STRUCTURE_SELECTED_STATUSES:hr,UNGROUPED:Lr,UNPAIRED:Bi,VALID_ENTRY_STATUSES:ib,WILDCARD:Op,WITHDRAWN:Cn};function fL({stage:t,drawDefinition:e}){return Jc.includes(t)?e?.structures?.some(n=>n.stage===t)||Jc.includes(t):!1}function Xy({stage:t,drawDefinition:e,entryStatus:r}){return e.entries.reduce((n,o)=>o.entryStage===t&&o.entryStatus===r?n+1:n,0)}function Wi({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=ot({name:Rn,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===Vt){let{playoffEntries:p,error:m}=BY({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 BY({provisionalPositioning:t,drawDefinition:e,structureId:r}){let n=[],o=(e.links??[]).find(i=>i.linkType===fn&&i.target.structureId===r);if(o){let{finishingPositions:i,structureId:s,bestOf:a,rankBy:c}=o.source,{structure:u}=tt({drawDefinition:e,structureId:s});if(u?.structureType===de){let m=(u.structures??[]).map(d=>{let l=d.positionAssignments??[],{structureId:f}=d,g=Object.assign({},...l.map(I=>{let{participantId:S}=I,h=ot({element:I,name:Lo}).extension?.value;return h&&S?{[S]:h}:void 0}).filter(Boolean));return{structureId:f,results:g}});if(o.source.remainder)HY({provisionalPositioning:t,allGroupResults:m,drawDefinition:e,playoffEntries:n,inboundLink:o,structureId:s});else if(a!==void 0&&i){let{selectedParticipants:d}=dL({groupResults:m,provisionalPositioning:t,finishingPositions:i,bestOf:a,rankBy:c});d.forEach(l=>{let g=i.includes(l.finishingPosition)?[...i].sort(Zt).indexOf(l.finishingPosition)+1:[...i].sort(Zt).length+1;n.push({isBestFinisher:l.isBestFinisher,groupingValue:l.groupingValue,participantId:l.participantId,GEMscore:l.GEMscore,entryStatus:vp,entryStage:Vt,placementGroup:g})})}else WY({provisionalPositioning:t,finishingPositions:i,allGroupResults:m,playoffEntries:n})}}return{playoffEntries:n}}function HY({provisionalPositioning:t,allGroupResults:e,drawDefinition:r,playoffEntries:n,inboundLink:o,structureId:i}){let s=new Set,a=(r.links??[]).filter(c=>c.linkType===fn&&c.source.structureId===i&&c.target.structureId!==o.target.structureId&&c.source.bestOf!==void 0);for(let c of a){let{structure:u}=tt({structureId:c.target.structureId,drawDefinition:r});if(u)for(let p of u.positionAssignments??[])p.participantId&&s.add(p.participantId)}e.forEach(({structureId:c,results:u})=>{Object.keys(u).forEach(p=>{if(!s.has(p)){let m=u[p],{groupOrder:d,provisionalOrder:l,GEMscore:f}=m,g=d||t&&l;n.push({groupingValue:c,entryStage:Vt,entryStatus:vp,placementGroup:g||1,participantId:p,GEMscore:f})}})})}function WY({provisionalPositioning:t,finishingPositions:e,allGroupResults:r,playoffEntries:n}){r.forEach(({structureId:o,results:i})=>{let s=o,c=Object.keys(i).reduce((p,m)=>{let d=i[m],l=d.groupOrder||t&&d.provisionalOrder;return p.includes(l)||p.push(l),p},[]).length===Object.keys(i).length,u=Object.keys(i).filter(p=>{let m=i[p],d=m.groupOrder||t&&m.provisionalOrder;return e?.includes(d)});(!t||c)&&u.forEach(p=>{let m=i[p],{groupOrder:d,provisionalOrder:l,GEMscore:f}=m,g=d||t&&l,I=[...e??[]].sort(Zt).indexOf(g)+1;n.push({entryStage:Vt,entryStatus:vp,placementGroup:I,groupingValue:s,participantId:p,GEMscore:f})})})}function Pr({provisionalPositioning:t,returnAllProxies:e,drawDefinition:r,structureId:n,structure:o}){let i,s=[];o||({structure:o,error:i}=tt({drawDefinition:r,structureId:n}));let a=Pt({structure:o}).positionAssignments;if(i||!o)return{seedAssignments:[],error:Nt};n||(n=o.structureId);let{stage:c,stageSequence:u}=o,m=c===Vt&&r&&Wi({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 S=I+1;return{participantId:g.participantId,seedValue:S,seedProxy:!0,seedNumber:S}}):[],l=d?.slice(0,e?d.length:a.length/2);l.length?s=l:o.seedAssignments?s=o.seedAssignments:i=RU;let f=o.seedLimit??o?.positionAssignments?.length;return{seedAssignments:s,stageSequence:u,seedLimit:f,stage:c,error:i}}function Go(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 Xm({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 ze({drawDefinition:t,structure:e,matchUp:r,event:n}){return{tieFormat:Xm({item:r,drawDefinition:t,structure:e,event:n})||Xm({item:e,drawDefinition:t,structure:e,event:n})||Go(t)||Go(n)}}function gL({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 Ie({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 Vo({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(q(u,!0,!0),{containerStructureId:r,structureId:s,structureName:c})):a}).flat();return(o?.matchUps??[]).concat(...i)}function Jy({groupedOrder:t,roundPositionsCount:e}){if(!t||t?.length<=e)return t;let n=he(t,t.length/e).map(i=>i.reduce((s,a)=>s+a)),o=n.slice().sort(Zt);return n.map(i=>o.indexOf(i)+1)}function ZI(t){if(!Tt(t))return!1;let{matchUpId:e,drawPositions:r}=t,n=typeof e=="string",o=!r||Array.isArray(r)&&r.length<=2&&r.every(i=>yt(i)||i===void 0||i===null);return n&&o}function Nr(t){return Array.isArray(t)?t.every(ZI):!1}function YY(t,e){return e?.find(r=>t.includes(r))}function De({matchUps:t=[],interpolate:e}){if(!Nr(t))return{roundMatchUps:[],error:O};let r=t.reduce((d,l)=>{let f=typeof l.roundNumber=="string"?st(l.roundNumber):l.roundNumber;return!l.roundNumber||d.includes(f)?d:d.concat(f)},[]).sort(Zt).map(d=>{let l=t.filter(S=>S.roundNumber===d),g=l.find(({matchUpType:S})=>S===Ot)?l.filter(({matchUpType:S})=>S===Ot):l,I=S=>S.sort((h,T)=>Zt(h.roundPosition,T.roundPosition));return{[d]:I(g)}}),n=t.reduce((d,l)=>{let f=typeof l.roundNumber=="string"?st(l.roundNumber):l.roundNumber;return d[f]||(d[f]=et({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=>st(f)).filter(f=>!Number.isNaN(f))),l=o[d]?.length;if(l>1&&en(l)){let f=d+1,g=f+l/2;Q(f,g).forEach((S,h)=>{o[S]=Q(0,l/(2+h*2)).map(()=>({}))})}}let i=0,s=Object.assign({},...Object.keys(o).map(d=>{let l=o[d]?.length,f=o[d]?.filter(I=>!Mt.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=>st(d)).filter(d=>!Number.isNaN(d));u.forEach(d=>{let l=o[d].sort((g,I)=>g.roundPosition-I.roundPosition),f=l.flatMap(g=>g?.drawPositions??[]);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(Zt),I=he(g,2);s[d].drawPositions=g,s[d].pairedDrawPositions=I}else{let g=s[d-1],I=g.drawPositions,S=g.matchUpsCount/s[d].matchUpsCount,h=he(I,S),T=l.map(y=>{let{roundPosition:E}=y,A=[...y.drawPositions??[],void 0,void 0].slice(0,2);if(!E)return A;let N=A?.filter(Boolean)??[];if(!N?.length)return[void 0,void 0];if(d<3&&N?.length===2)return A?.slice().sort(Zt);let U=Yt(I,N).length!==N?.length;if(N?.length&&U)return N?.length===1?[N[0],void 0]:A?.slice().sort(Zt);let R=(E-1)*2;return h.slice(R,R+2).map(b=>YY(b,N))});s[d].drawPositions=T?.flat(),s[d].pairedDrawPositions=T}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).some(({matchUpsCount:d})=>!en(d));return{hasNoRoundPositions:t.some(d=>!d.roundPosition),roundsNotPowerOf2:p,maxMatchUpsCount:i,roundMatchUps:o,roundNumbers:u,roundProfile:s,...P}}function wl(t){if(!Array.isArray(t))return"";let e=t.filter(Le);return e.length?pt([Math.min(...e),Math.max(...e)]).join("-"):""}function IL({drawDefinition:t,structureId:e,matchUpsMap:r}){let n=dt({drawDefinition:t,structureId:e},[Kt,po]);if(n.error)return n;let{structure:o}=tt({drawDefinition:t,structureId:e});if(o?.stage!==me)return{error:tc,info:"Structure is not CONSOLATION stage"};let{links:i}=t,s=i?.filter(d=>d.target.structureId===e)??[],a=s?.reduce((d,l)=>{let{structureId:f}=l.source;return d.includes(f)?d:d.concat(f)},[])??[],c=Object.assign({},...a.map(d=>{let l=Vo({structureId:d,matchUpsMap:r}),g=De({matchUps:l}).roundProfile;return{[d]:g}})),u=Vo({matchUpsMap:r,structureId:e}),{roundProfile:p}=De({matchUps:u}),m={};return s?.forEach(d=>{let{structureId:l,roundNumber:f}=d.source,{feedProfile:g,groupedOrder:I,positionInterleave:S,roundNumber:h}=d.target,T=c[l],y=T[1]?.drawPositions,A=T[f]?.matchUpsCount;if(!A)return;let N=A?y.length/A:0,U=y.length/N,R=y.slice(),D=Jy({roundPositionsCount:U,groupedOrder:I}),b=D?.length||1;if(b<=U){let w=y.length/b,L=he(R,w);g===Oi&&L.forEach(F=>F.reverse()),R=D?.length&&D?.map(F=>L[F-1]).flat()||L.flat()}let C=he(R,N);if(S){let w=Q(0,S.interleave).map(()=>{}),L=Q(0,S.offset).map(()=>{});C=C.map(x=>[x,...w]),C.unshift(L),C=C.flat(1);let F=C.length-S.offset;C=C.slice(0,F)}m[h]||(m[h]={});let v=p?.[h]?.feedRound?2:1;C.forEach((w,L)=>{let F=1+L*v;m[h][F]||(m[h][F]=wl(w))})}),{sourceDrawPositionRanges:m}}function Ll({drawDefinition:t}){if(typeof t!="object")return{error:ma};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"&&[me,Vt].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,S=r.find(T=>T.structureId===I).stage,h=[S,I,g,f].join("|");if(p[h])return;p[h]=!0,i({exitProfile:`${a}-${f}`,structureId:I,exitProfiles:s,targetRound:g,aggregator:p,stage:S})}}}function SL({drawDefinition:t,roundProfile:e,structureId:r,matchUpsMap:n}){let o=dt({drawDefinition:t,structureId:r},[Kt,po]);if(o.error)return o;if(!e){let u=Vo({matchUpsMap:n,structureId:r});if({roundProfile:e}=De({matchUps:u}),!e)return{error:nt}}let s=(Math.min(...e?.[1]?.drawPositions??[])||1)-1,a=Object.keys(e);return{drawPositionsRanges:Object.assign({},...(a??[]).map(u=>{let p=e?.[u]?.matchUpsCount,m=e?.[1]?.drawPositions??[],d=he(m,m.length/p),l=d.map(wl),f=d.map(T=>T.map(y=>y-s)).map(wl),g=a.map(T=>{if(T>u)return;let y=e?.[T]?.drawPositions??[];return he(y,y.length/p)}).filter(Boolean),I=Q(0,p).map(T=>g.map(y=>y[T]).flat().filter(Boolean).sort(Zt)).map(T=>pt(T)),S=I.map(T=>Qx(T).map(wl).join(", ")),h=Object.assign({},...Q(0,p).map(T=>({[T+1]:{firstRoundDrawPositionsRange:l[T],firstRoundOffsetDrawPositionsRange:f[T],possibleDrawPositions:I[T],drawPositionsRange:S[T]}})));return{[u]:h}}))}}var jY=new Set([ws,nc]);function an(t){return!!t&&jY.has(t)}function tS({structure:t,matchUps:e}){e=e??t?.matchUps??[];let r=De({matchUps:e}),n=r.roundProfile,o=r.roundNumbers;if(!n||!o?.length||o.length<2)return!1;let i=[...o].sort((s,a)=>s-a);for(let s=0;s<i.length-1;s++){let a=n[i[s]]?.matchUpsCount??0,c=n[i[s+1]]?.matchUpsCount??0;if(a%2===1&&c%2===0)return!0}return!1}function Ic({roundsNotPowerOf2:t,drawDefinition:e,structure:r,matchUps:n}){return!r||(n=n??r.matchUps??[],t=t??De({matchUps:n}).roundsNotPowerOf2,!(!!r.positionAssignments?.find(({drawPosition:i})=>i)||!!n?.find(({drawPositions:i})=>i?.length))||r?.structures)||e?.drawType&&an(e.drawType)||!t?!1:tS({structure:r,matchUps:n})}function Ae({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?.stage===Fe?t?.structures||t?.structureType===tu&&n?!1:t?.finishingPosition===uo:!t?.structures&&(!e.length||!r&&!n)}var eS={[Oo]:{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:{[H]:"",[Vt]:"P",[Z]:"Q",[me]:"C"}}},hL=eS;function Zy({roundNamingPolicy:t,drawDefinition:e,structure:r,matchUps:n}){let{roundProfile:o,roundMatchUps:i}=De({matchUps:n}),{structureAbbreviation:s,stage:a}=r,c=Ae({structure:r}),u=Ic({structure:r}),p=r.structures,m={},d=eS[Oo],l=r.stage===Z,f=l?Math.max(...(e?.structures??[]).filter(_=>_.stage===Z).map(({stageSequence:_})=>_??1),0):0,g=(r.stageSequence??1)<f?r.stageSequence??1:"",I=g&&(t?.affixes?.preQualifying||d.affixes.preQualifying)||"",S=t?.roundNamingMap||(d.roundNamingMap??{}),h=t?.abbreviatedRoundNamingMap||(d.abbreviatedRoundNamingMap??{}),T=t?.affixes?.preFeedRound||d.affixes.preFeedRound,y=t?.affixes?.roundNumber||d.affixes.roundNumber,A=(t?.namingConventions||d.namingConventions).round,N=a&&a!==H?a[0]:"",U=t?.stageConstants||d.stageConstants,R=a&&U?.[a]||N,D=`${I}${R}${g}`,b=o?Object.keys(o):[],C=l&&U?.[Z]?`${U?.[Z]}-`:"";if(p||c||u)Object.assign(m,...b.map(_=>{let v=`${C}${A} ${_}`,w=`${y}${_}`;return{[_]:{roundName:v,abbreviatedRoundName:w}}}));else{let _=l&&(t?.qualifyingFinishMap||(d?.qualifyingFinishMap??{}));Object.assign(m,...b.map(v=>{if(!o?.[v])return;let{matchUpsCount:w,preFeedRound:L}=o[v],F=w*2,x=_?.[o?.[v].finishingRound]||_&&`${y}${F}`||S[w]||`${y}${F}`,k=L?`-${T}`:"",G=`${x}${k}`,V=[D,s,G].filter(Boolean).join("-"),z=`${h[w]||`${y}${F}`}${k}`,W=[D,s,z].filter(Boolean).join("-");return{[v]:{abbreviatedRoundName:W,roundName:V}}}))}return{roundNamingProfile:m,roundProfile:o,roundMatchUps:i}}var qY=(t,e)=>(t||0)+(e||0);function tE(t,e){let r=Array.isArray(t)?t[0]:t;return Number.isNaN(r)&&Qy||r<=e[mu]&&mu||r<=e[pu]&&pu||vl}function Fl({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(qY)&&(r[n[0]>n[1]?0:1]+=1),{sets:e,games:r,score:t}}function $Y(t){let e=Math.min(...t.games),r=Math.max(...t.games);return Math.round(e/r*100)}function eE(t){return t.map($Y).sort((e,r)=>e-r).map(e=>parseFloat(e.toFixed(2)))}function Sc({tournamentRecord:t,profileBands:e,matchUp:r}){if(!r)return{error:Xe};let{score:n,winningSide:o}=r;if(!o)return{error:O};let i=!e&&t&&Ei({policyType:xi,tournamentRecord:t}).policy,s=e||i?.profileBands||_l[xi].profileBands,a=Fl({score:n}),c=eE([a]),u=tE(c,s),p=Array.isArray(c)?c[0]:c;return{...P,competitiveness:u,pctSpread:p}}function rE({matchUp:t}){if(!t)return{error:Xe};if(t&&!t.sides)return{error:cr};if(t&&!t.hasContext)return{error:ep};let e=(t.sides??[])?.map(a=>a?.participantId).filter(Boolean),r=t.sides?.filter(a=>a.participant?.participantType===St).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,...P}}var kl="CHECK_IN",Gl="CHECK_OUT",KY="SCHEDULE",gs="SCHEDULE.ASSIGNMENT.VENUE",fo="SCHEDULE.ALLOCATION.COURTS",ai="SCHEDULE.ASSIGNMENT.COURT",lu="SCHEDULE.COURT.ORDER",fu="SCHEDULE.COURT.ANNOTATION",Is="SCHEDULE.DATE",zY="COMPLETED.DATE",Vl="HOME_PARTICIPANT_ID",rS="SCHEDULE.ASSIGNMENT.OFFICIAL",Ss="SCHEDULE.TIME.SCHEDULED",ci="SCHEDULE.TIME.START",Ca="SCHEDULE.TIME.STOP",Gs="SCHEDULE.TIME.RESUME",hs="SCHEDULE.TIME.END",Jm="SCHEDULE.TIME.MODIFIERS",TL="TO_BE_ANNOUNCED",yL="NEXT_AVAILABLE",EL="FOLLOWED_BY",AL="AFTER_REST",PL="RAIN_DELAY",QY="NOT_BEFORE",nE=[TL,yL,EL,AL,PL],XY="ELIGIBILITY",JY="REGISTRATION",ZY="SUSPENSION",tj="MEDICAL",ej="PENALTY",sb="SCALE",ab="RATING",cb="RANKING",nS="SEEDING",Bo="PUBLISH",Ur="PUBLIC",Ho="STATUS",rj="MODIFICATION",nj="RETRIEVAL",oj="other",NL={MUTUALLY_EXCLUSIVE_TIME_MODIFIERS:nE,AFTER_REST:AL,ALLOCATE_COURTS:fo,ASSIGN_COURT:ai,ASSIGN_OFFICIAL:rS,ASSIGN_VENUE:gs,CHECK_IN:kl,CHECK_OUT:Gl,COMPLETED_DATE:zY,COURT_ANNOTATION:fu,COURT_ORDER:lu,ELIGIBILITY:XY,END_TIME:hs,FOLLOWED_BY:EL,MEDICAL:tj,MODIFICATION:rj,NEXT_AVAILABLE:yL,NOT_BEFORE:QY,OTHER:oj,PENALTY:ej,PUBLIC:Ur,PUBLISH:Bo,RANKING:cb,RATING:ab,RAIN_DELAY:PL,REGISTRATION:JY,RESUME_TIME:Gs,RETRIEVAL:nj,SCALE:sb,SCHEDULE:KY,SCHEDULED_DATE:Is,SCHEDULED_TIME:Ss,SEEDING:nS,START_TIME:ci,STATUS:Ho,STOP_TIME:Ca,SUSPENSION:ZY,TIME_MODIFIERS:Jm,TO_BE_ANNOUNCED:TL};function Vs({matchUp:t}){if(!t)return{error:Xe};if(!t.hasContext)return{error:ep};if(!t.sides||t?.sides.filter(Boolean).length!==2)return{error:cr};let{nestedIndividualParticipantIds:e,allRelevantParticipantIds:r,sideParticipantIds:n}=rE({matchUp:t}),i=(t.timeItems??[]).filter(u=>u?.itemType&&[kl,Gl].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===kl);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,...P}}var re=t=>e=>{let r=Tt(e)&&e?.matchUpType||_t(e)&&e;return r&&NT[t].includes(r)};function Zm(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 td(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 oE({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 UL({tournamentScheduling:t,eventScheduling:e,averageMinutes:r,defaultTiming:n,matchUpFormat:o,categoryName:i,categoryType:s,policy:a}){let c=e?.matchUpRecoveryTimes&&td({...e,averageMinutes:r,matchUpFormat:o}),u=t?.matchUpRecoveryTimes&&td({...t,averageMinutes:r,matchUpFormat:o}),p=a?.matchUpRecoveryTimes&&td({...a,averageMinutes:r,matchUpFormat:o}),m=[c,u,p,a?.defaultTimes?.recoveryTimes,n?.recoveryTimes];return oE({categoryName:i,categoryType:s,timesBlockArray:m})}function DL({matchUpFormat:t,categoryName:e,categoryType:r,defaultTiming:n,tournamentScheduling:o,eventScheduling:i,policy:s}){let a=i?.matchUpAverageTimes&&Zm({...i,matchUpFormat:t}),c=o?.matchUpAverageTimes&&Zm({...o,matchUpFormat:t}),u=s?.matchUpAverageTimes&&Zm({...s,matchUpFormat:t}),p=[a,c,u,s?.defaultTimes?.averageTimes,n?.averageTimes];return oE({categoryName:e,categoryType:r,timesBlockArray:p})}var ub="DOUBLES_SINGLES",pb="SINGLES_DOUBLES",go="total",iE="participantConflict",sE="potentialParticipantConflict",ui="matchUpConflict",mb="courtDoubleBooking",db="positionLinkConflict",lb="ISSUE_IDS",Bs="CONFLICT",Hs="WARNING",Bl="ERROR",Hl="ISSUE",oS="STATE",ij="BLOCKED",sj="PRACTICE",aj="MAINTENANCE",RL={SINGLES_DOUBLES:pb,DOUBLES_SINGLES:ub,TOTAL:go,CONFLICT_MATCHUP_ORDER:ui,CONFLICT_PARTICIPANTS:iE,CONFLICT_POTENTIAL_PARTICIPANTS:sE,CONFLICT_COURT_DOUBLE_BOOKING:mb,CONFLICT_POSITION_LINK:db,SCHEDULE_ISSUE_IDS:lb,SCHEDULE_CONFLICT:Bs,SCHEDULE_WARNING:Hs,SCHEDULE_ERROR:Bl,SCHEDULE_ISSUE:Hl,SCHEDULE_STATE:oS,BLOCKED:ij,PRACTICE:sj,MAINTENANCE:aj};function _p({defaultAverageMinutes:t=90,defaultRecoveryMinutes:e=0,tournamentRecord:r,matchUpFormat:n,categoryName:o,categoryType:i,eventType:s,event:a}){if(!r)return{error:j};s=s??a?.eventType??Ea;let c={averageTimes:[{minutes:{default:t}}],recoveryTimes:[{minutes:{default:e}}]},{scheduleTiming:u}=gc({tournamentRecord:r,categoryName:o,categoryType:i,event:a}),p={...u,matchUpFormat:n,categoryType:i,defaultTiming:c};return ed({eventType:s,timingDetails:p})}function ed({timingDetails:t,eventType:e}){let r=DL(t),n=Object.keys(r?.minutes??{}),o=r?.minutes&&(n?.includes(e)&&r.minutes[e]||r.minutes.default),i=UL({...t,averageMinutes:o}),s=Object.keys(i?.minutes??{}),a=i?.minutes&&(s?.includes(e)&&i.minutes[e]||i.minutes.default),c=re(Ea)(e)?pb:ub,u=i?.minutes&&(s?.includes(c)&&i.minutes[c]||a);return{averageMinutes:o,recoveryMinutes:a,typeChangeRecoveryMinutes:u}}function fb(t){return t.createdAt?new Date(t.createdAt).getTime():0}function pi({timeItems:t,itemType:e}){let r=t.filter(o=>o&&o.itemType===e).sort((o,i)=>fb(o)-fb(i)).pop(),n=r&&fb(r);return{itemValue:r?.itemValue,timeStamp:n}}function Wl({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=pi({timeItems:r?.timeItems??[],itemType:Ss});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{scheduledTime:n}:e}function Ws({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=pi({timeItems:r?.timeItems??[],itemType:Is});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{scheduledDate:n}:e}function rd(t){if(KT.test(t)){let e=fI();return new Date(`${e}T${t}`)}else return new Date(t)}function bL({matchUp:t}){if(!t)return{error:Xe};if(!t.timeItems)return{error:Zg};let e=t.timeItems.filter(n=>[ci,Ca,Gs,hs].includes(n?.itemType)).sort((n,o)=>rd(n.itemValue).getTime()-rd(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 ci:i=0;break;case hs:if(n.lastValue&&[ci,Gs].includes(n.lastType)){let u=rd(o.itemValue).getTime()-rd(n.lastValue).getTime();i=n.milliseconds+u}else i=n.milliseconds;break;case Ca:if([ci,"SCHECULE.TIME.RESUME"].includes(n.lastType)){let u=rd(o.itemValue).getTime()-rd(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([ci,Gs].includes(r.lastType)){let n=new Date().getTime()-rd(r.lastValue).getTime();r.milliseconds+=n}return{milliseconds:r.milliseconds,time:cj(r.milliseconds),relevantTimeItems:e}}function cj(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 CL({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===ci&&s;return a&&(!i||r(a)<r(i))?a:i},void 0)?.itemValue}}function aE(t){return parseInt(t)}function Yl({startTime:t="",endTime:e=""}={}){if(!t||!e||!Qc.test(t)||!Qc.test(e))return!1;let[r,n]=t.split(":").map(aE),[o,i]=e.split(":").map(aE);return o<r?!1:!(r===o&&i<n)}function ML(t,e){let[r,n]=t.startTime.split(":").map(aE),[o,i]=e.startTime.split(":").map(aE);return r<o?-1:r>o?1:n<i?-1:n>i?1:0}function xp({dateAvailability:t}){if(!t)return{error:$U};if(!Array.isArray(t))return{error:Yg};for(let e of t){if(typeof e!="object")return{error:Yg};let{date:r,startTime:n,endTime:o,bookings:i=[]}=e;if(!n||!o)return{error:Yg};let s=pj(r);if(s)return s;let a=OL(n,o);if(a)return a;if(i){let c=mj(i);if(c)return c}}return{valid:!0}}var uj="Dates must be formated => YYYY-MM-DD",vL="Times must be 24 hour => 00:00";function pj(t){if(t&&!Mo.test(t))return{error:ae,dateAvailability:{date:t},info:uj}}function OL(t,e){if(!Qc.test(t))return{error:vs,dateAvailability:{startTime:t},info:vL};if(!Qc.test(e))return{error:vs,dateAvailability:{endTime:e},info:vL};if(t===e)return{error:vs,dateAvailability:{startTime:t,endTime:e},info:"startTime and endTime are equivalent"};if(!Yl({startTime:t,endTime:e}))return{error:vs,dateAvailability:{startTime:t,endTime:e},info:"endTime must be after startTime"}}function mj(t){if(!Array.isArray(t))return{error:rl};for(let e of t){if(typeof e!="object")return{error:rl};let{startTime:r,endTime:n}=e,o=OL(r,n);if(o)return o}}function cE({tournamentRecord:t}){for(let e of t.venues??[])e.isPrimary&&delete e.isPrimary}function gu(t){let{disableNotice:e,venue:r,context:n}=t;if(typeof r!="object")return{error:O};let o=Ar(t);r.venueId??=it();let i;for(let s of Object.values(o)){let a=dj({disableNotice:!0,tournamentRecord:s,context:n,venue:r});if(a?.error)return a;i=a.venue}return e||at({topic:By,payload:{venue:r}}),et({...P,venue:i})}function dj({tournamentRecord:t,disableNotice:e,context:r,venue:n}){let o=dt({tournamentRecord:t},[rt]);if(o.error)return o;if(!n)return{error:nt,info:"missing venue"};if(t.venues??=[],n.venueId??=it(),t.venues.reduce((s,a)=>s||a.venueId===n.venueId,void 0))return{error:fD};if(n.dateAvailability?.length){let s=xp({dateAvailability:n.dateAvailability});if(s.error)return s}if(n.defaultStartTime||n.defaultEndTime){if(!n.defaultStartTime||!n.defaultEndTime)return{error:O,info:"both defaultStartTime and defaultEndTime are required"};if(!Yl({startTime:n.defaultStartTime,endTime:n.defaultEndTime}))return{error:O,info:"defaultEndTime must be after defaultStartTime"}}return r&&ut({element:n,extension:{value:r,name:ER}}),n.isPrimary&&cE({tournamentRecord:t}),t.venues.push(n),e||at({payload:{venue:n,tournamentId:t.tournamentId},topic:By}),{...P,venue:q(n)}}function wn({tournamentRecords:t,tournamentRecord:e,venueId:r}){let n=dt({tournamentRecord:e,venueId:r},[rt,gp]);if(n.error)return n;let i=(e.venues??[]).reduce((s,a)=>a.venueId===r?a:s,void 0);if(!i&&t){let a=(Np({tournamentRecords:t}).linkedTournamentIds??[])[e.tournamentId];for(let c of a){let u=t[c],p=wn({tournamentRecord:u,venueId:r});if(p.success&&p.venue)return gu({tournamentRecord:e,venue:p.venue}),{...P,venue:i}}}return i?{...P,venue:i}:{error:Mi}}function uE({convertExtensions:t,...e}){let{tournamentRecords:r,tournamentRecord:n,venueId:o}=e,i=wn({tournamentRecords:r,tournamentRecord:n,venueId:o});return q(i,t,!0)}function mi({tournamentRecords:t,tournamentRecord:e,courtId:r}){let n=dt({tournamentRecord:e,courtId:r},[rt,Fs]);if(n.error)return n;let o="findCourt",i,s;if((e.venues??[]).forEach(a=>{(a.courts??[]).forEach(c=>{c.courtId===r&&(i=c,s=a)})}),i)return{...P,court:i,venue:s};if(t){let c=(Np({tournamentRecords:t}).linkedTournamentIds??[])[e.tournamentId];for(let u of c){let p=t[u],m=mi({tournamentRecord:p,courtId:r});if(m.success)return m.venue&&gu({tournamentRecord:e,venue:m.venue}),{...P,court:i,venue:s}}}return M({result:{error:bo},stack:o})}function pE(t){return q(mi(t),!1,!0)}function jl({tournamentRecord:t,internalUse:e,courtId:r}){let n=dt({tournamentRecord:t,courtId:r},[rt,Fs]);if(n.error)return n;let o=mi({tournamentRecord:t,courtId:r});if(o.error)return o;let i=o.court&&(({altitude:s,courtId:a,courtName:c,courtDimensions:u,latitude:p,longitude:m,surfaceCategory:d,surfaceType:l,surfacedDate:f,pace:g,notes:I})=>({altitude:s,courtId:a,courtName:c,courtDimensions:u,latitude:p,longitude:m,surfaceCategory:d,surfaceType:l,surfacedDate:f,pace:g,notes:I}))(o.court);return{...P,courtInfo:q(i,!1,e)}}function Iu(t){let e=X(t,[{[rt]:!0},{venueId:!0,[Yr]:Os}]);if(e.error)return e;let{tournamentRecord:r,venueId:n}=t,o=wn({tournamentRecord:r,venueId:n});if(o.error)return o;let s=(o.venue?.courts??[]).map(u=>(({courtInfo:p})=>({...p}))(jl({courtId:u.courtId,internalUse:!0,tournamentRecord:r}))),a=o.venue&&(({venueId:u,venueName:p,venueAbbreviation:m})=>({venueAbbreviation:m,venueName:p,venueId:u}))(o.venue),c=a&&{...a,courtsInfo:s};return{...P,venueData:q(c,!1,!0)}}function _L({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===hs&&s;return a&&(!i||r(a)>r(i))?a:i},void 0)?.itemValue}}function Bt({event:t,eventId:e}){if(!t)return{error:le};let n=ot({name:on,element:t})?.extension,o=e?q(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 _e(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&&Bt({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,...M({result:{error:Gr},stack:o})};return{event:u,drawDefinition:void 0,tournamentId:c}}return{event:void 0,drawDefinition:void 0,...M({result:{error:Rr},context:{drawId:n,eventId:r},stack:o})}}function ql(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:Xe};if(o&&!p.matchUpType&&!t.matchUpType&&(e||i)&&p.drawId){let N=t.drawDefinition||e?.drawDefinitions?.find(R=>R.drawId===p.drawId);!N&&i&&({drawDefinition:N,event:e}=_e({drawId:p.drawId,tournamentRecord:i}));let U=p.structureId&&N?.structures?.find(({structureId:R})=>R===p.structureId);r=t.matchUpType||U?.matchUpType||N?.matchUpType||e?.eventType!==Oe&&e?.eventType}let{milliseconds:m,time:d}=bL({matchUp:p}),{startTime:l}=CL({matchUp:p}),{endTime:f}=_L({matchUp:p}),{eventIds:g,drawIds:I}=n??{},h=(!g||g.includes(p.eventId))&&(!I||I.includes(p.drawId))?lj({tournamentRecord:i,scheduleTiming:a,afterRecoveryTimes:o,matchUpFormat:c,matchUpType:r,matchUp:p,endTime:f,startTime:l,milliseconds:m,time:d}):et({milliseconds:m,startTime:l,endTime:f,time:d}),{scheduledDate:T}=Ws({matchUp:p}),{scheduledTime:y}=Wl({matchUp:p});if(s&&u?.displaySettings?.draws){let N=u.displaySettings.draws,U=(N?.[p.drawId]??N?.default)?.scheduleDetails;if(U){let R=(U.find(D=>T&&D.dates?.includes(T))??U.find(D=>!D.dates?.length))?.attributes;if(R){let D=Object.assign({},...Object.keys(h).map(b=>({[b]:!0})),R);h=fs({source:h,template:D})}}}let A=p.matchUpStatus&&Mt.includes(p.matchUpStatus)&&(mt(f)||mt(T)||mt(y))||void 0;return{schedule:h,endDate:A}}function lj({tournamentRecord:t,scheduleTiming:e,afterRecoveryTimes:r,matchUpFormat:n,matchUpType:o,matchUp:i,endTime:s,startTime:a,milliseconds:c,time:u}){let p=C=>C.createdAt?new Date(C.createdAt).getTime():0,m=new Map,d=i.timeItems?.toSorted((C,_)=>p(C)-p(_))??[];for(let C of d)m.set(C.itemType,C.itemValue);let l=m.get(Vl),f=m.get(fu),g=m.get(fo),I=m.get(Ss),S=m.get(Jm),h=m.get(Is),T=m.get(rS),y=m.get(lu),E=m.get(gs),A=m.get(ai),N=fj({scheduleTiming:e,afterRecoveryTimes:r,matchUpFormat:n,matchUpType:o,matchUp:i,endTime:s,scheduledTime:I});!h&&I&&(h=mt(I));let U=pl({scheduledDate:h,scheduledTime:I}),{venueName:R,venueAbbreviation:D,courtName:b}=gj({tournamentRecord:t,allocatedCourts:g,venueId:E,courtId:A});return et({typeChangeTimeAfterRecovery:N.typeChangeTimeAfterRecovery,typeChangeRecoveryMinutes:N.typeChangeRecoveryMinutes,timeAfterRecovery:N.timeAfterRecovery,recoveryMinutes:N.recoveryMinutes,averageMinutes:N.averageMinutes,homeParticipantId:l,courtAnnotation:f,venueAbbreviation:D,allocatedCourts:g,scheduledDate:h,scheduledTime:I,isoDateString:U,timeModifiers:S,venueName:R,venueId:E,courtOrder:y,courtName:b,courtId:A,official:T,milliseconds:c,startTime:a,endTime:s,time:u})}function fj({scheduleTiming:t,afterRecoveryTimes:e,matchUpFormat:r,matchUpType:n,matchUp:o,endTime:i,scheduledTime:s}){let a,c,u,p,m,d=o.matchUpType??n;if(t&&s&&e&&d){let l={matchUpFormat:o.matchUpFormat??r,...t};({averageMinutes:c=0,recoveryMinutes:u=0,typeChangeRecoveryMinutes:p=0}=ed({timingDetails:l,eventType:d})),(c||u)&&(a=i?Br($t(i),u):Br(s,c+u)),p&&(m=i?Br($t(i),p):Br(s,c+p))}return{timeAfterRecovery:a,averageMinutes:c,recoveryMinutes:u,typeChangeRecoveryMinutes:p,typeChangeTimeAfterRecovery:m}}function gj({tournamentRecord:t,allocatedCourts:e,venueId:r,courtId:n}){let o={},i=(t&&r&&Iu({tournamentRecord:t,venueId:r}))?.venueData??{};r&&(o[r]=i);let{venueName:s,venueAbbreviation:a,courtsInfo:c}=i,p=(n&&c?.find(m=>m.courtId===n))?.courtName;for(let m of e??[]){if(!t)break;m.venueId&&!o[m.venueid]&&(o[m.venueId]=Iu({venueId:m.venueId,tournamentRecord:t})?.venueData);let d=o[m.venueId];m.venueName=d?.venueName;let l=d?.courtsInfo?.find(f=>f.courtId===m.courtId);m.courtName=l?.courtName}return{venueName:s,venueAbbreviation:a,courtName:p}}function xL({drawPositions:t,roundProfile:e,roundNumber:r}){let n=[void 0,void 0];if(MT(t))return{orderedDrawPositions:n,displayOrder:n};let o=e?.[r],s=o?.pairedDrawPositions?.find(c=>Re(c??[],t.filter(Boolean)))??n,a=o?.feedRound;if(CT(t)){let c=[...t].sort(Zt);return{orderedDrawPositions:c.length===2?c:s,displayOrder:a?c:s}}if(a){let u=[t.find(p=>!isNaN(st(p))),void 0];return{orderedDrawPositions:u,displayOrder:u}}return{orderedDrawPositions:s,displayOrder:s}}function nd({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 hn({tournamentParticipants:t,tournamentRecord:e,participantIds:r}){let n="getPairedParticipant";if(!t&&!e)return{error:j};if(!Array.isArray(r)||r.length>2)return{error:Mr};if(!r.length)return M({result:{error:Ro},stack:n});t=t??e?.participants??[];let o=t.filter(a=>a.participantType===lt&&Yt(r,a.individualParticipantIds).length===r.length&&a.individualParticipantIds.length===r.length),i=o[0];if(!i)return M({result:{error:ee},stack:n});let s=q(o.slice(1),!1,!0);return{participant:q(i),duplicatedPairParticipants:s,...P}}function Ys({drawDefinition:t,participantId:e}){if(typeof t!="object")return{error:$};if(typeof e!="string")return{error:He};let{extension:r}=ot({element:t,name:wo});return{lineUp:(r?.value??{})[e]}}function wL({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}=nd({collectionPosition:r,collectionId:s,lineUp:d});if(c===Rt){if(f?.length<=2){let I=o?.[f[0]]?.pairIdMap?.[f[1]],T=(I&&o[I]?.participant||hn({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||Ys({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||Ys({participantId:d,drawDefinition:i})?.lineUp;return u({attribute:m,lineUp:g,teamParticipant:f})}).filter(Boolean)??{};return{drawPositionCollectionAssignment:Object.assign({},...p)}}function $l(t){let e=X(t,[{[Dn]:!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===St&&Ct||s===lt&&Rt||s===vt&&vt||void 0}return{matchUpType:n}}function LL({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?Ij({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 Ij({displaySideNumber:t,seedAssignments:e,participantId:r,assignment:n,sideNumber:o}){let i={drawPosition:n.drawPosition,displaySideNumber:t,sideNumber:o};if(r){let s=Sj({seedAssignments:e,participantId:r});Object.assign(i,s,{participantId:r}),s?.seedNumber&&s?.seedValue===""&&(i.seedValue="~")}else n.bye&&Object.assign(i,{bye:!0});return n.qualifier&&Object.assign(i,{qualifier:!0}),i}function Sj({seedAssignments:t,participantId:e}){return t?.find(r=>!r.seedProxy&&r.participantId===e)}function Po(t){let e=t?.embargo;return!e||!us(e)?!1:new Date(e).getTime()>Date.now()}function eo(t){return!!t?.published&&!Po(t)}function hj({publishStatus:t,drawDefinition:e,structure:r,matchUp:n,schedule:o}){if(!t||!e?.drawId||!r?.structureId)return o;let i=t?.drawDetails?.[e.drawId]?.structureDetails?.[r.structureId];if(!i)return o;let s=n.roundNumber;if(!yt(s))return o;let a=i.scheduledRounds?.[s];if(!(a&&Po(a)))return o}function Tj({matchUp:t,collectionDefinition:e,structure:r,drawDefinition:n,event:o,tournamentRecord:i}){return t.processCodes?.length&&t.processCodes||e?.processCodes?.length&&e?.processCodes||r?.processCodes?.length&&r?.processCodes||n?.processCodes?.length&&n?.processCodes||o?.processCodes?.length&&o?.processCodes||i?.processCodes}function gb({scheduleVisibilityFilters:t,sourceDrawPositionRanges:e,tournamentParticipants:r,positionAssignments:n,drawPositionsRanges:o,hydrateParticipants:i,afterRecoveryTimes:s,initialRoundOfPlay:a,additionalContext:c,roundNamingProfile:u,tournamentRecord:p,tieDrawPositions:m,appliedPolicies:d,isCollectionBye:l,seedAssignments:f,usePublishState:g,participantMap:I,contextContent:S,scheduleTiming:h,contextProfile:T,drawDefinition:y,publishStatus:E,scoringActive:A,matchUpTieId:N,isRoundRobin:U,roundProfile:R,sideLineUps:D,structure:b,context:C,matchUp:_,event:v}){c=c??{};let w=ze({drawDefinition:y,structure:b,matchUp:_,event:v})?.tieFormat,{roundOffset:L,structureId:F,structureName:x,stage:k,stageSequence:G}=b,{drawId:V,drawName:B,drawType:z}=y??{},W=w?.collectionDefinitions,K=_.collectionId&&W?.find(Gn=>Gn.collectionId===_.collectionId),Y=_.collectionId?K?.matchUpFormat:_.matchUpFormat??b?.matchUpFormat??y?.matchUpFormat??v?.matchUpFormat,J=_.matchUpType||K?.matchUpType||b?.matchUpType||y?.matchUpType||!re(Oe)(v?.eventType)&&v?.eventType,ct=l?"BYE":_.matchUpStatus,{schedule:Et,endDate:Wt}=ql({scheduleVisibilityFilters:t,afterRecoveryTimes:s,tournamentRecord:p,usePublishState:g,scheduleTiming:h,drawDefinition:y,matchUpFormat:Y,publishStatus:E,matchUpType:J,matchUp:_,event:v});g&&Et&&(Et=hj({publishStatus:E,drawDefinition:y,structure:b,matchUp:_,schedule:Et}));let Dt=m??_.drawPositions??[],{collectionPosition:pe,collectionId:ye,roundPosition:Jt}=_,pr=_.roundNumber??c.roundNumber,$n=ye?wL({tournamentParticipants:r,positionAssignments:n,collectionPosition:pe,participantMap:I,drawDefinition:y,drawPositions:Dt,collectionId:ye,sideLineUps:D,matchUpType:J}):void 0,Kr=u?.[pr]?.roundName||c.roundName,io=u?.[pr]?.abbreviatedRoundName||c.abbreviatedRoundName,Ko=R?.[pr]?.feedRound,zo=R?.[pr]?.preFeedRound,sa=R?.[pr]?.roundFactor,aa=o?.[pr],ca=Jt?aa?.[Jt]:void 0,Pm=e?.[pr],_c=K?.category?{...C?.category,...K.category}:C?.category??v?.category,Nm=Tj({matchUp:_,collectionDefinition:K,structure:b,drawDefinition:y,event:v,tournamentRecord:p}),we=T?.withCompetitiveness&&Sc({...S,matchUp:_}),Ii=_.finishingPositionRange??c.finishingPositionRange,rs=k!==Z&&yt(a)&&a+(pr||0),Xa=Gn=>et(Gn,void 0,!0),En={...Xa(C),...Xa({matchUpFormat:J===Oe?void 0:Y,tieFormat:J===Oe?w:void 0,gender:K?.gender??v?.gender,endDate:_.endDate??Wt,discipline:v?.discipline,category:_c,finishingPositionRange:Ii,abbreviatedRoundName:io,drawPositionsRange:ca,competitiveProfile:we,structureName:x,stageSequence:G,drawPositions:Dt,matchUpStatus:ct,processCodes:Nm,isRoundRobin:U,matchUpTieId:N,preFeedRound:zo,matchUpType:J,roundFactor:sa,roundOffset:L,structureId:F,roundNumber:pr,roundOfPlay:rs,feedRound:Ko,roundName:Kr,drawName:B,drawType:z,schedule:Et,drawId:V,stage:k}),...q(Xa(_),!0,!0)};if(Y&&_.score?.scoreStringSide1&&yj(En,Y),Array.isArray(Dt)){let Gn=Ej({sourceDrawPositionRoundRanges:Pm,collectionAssignmentDetail:$n,positionAssignments:n,seedAssignments:f,drawPositions:Dt,roundPosition:Jt,roundProfile:R,roundNumber:pr,onlyDefined:Xa,matchUp:_});Object.assign(En,q({sides:Gn},!0,!0))}if(r&&En.sides){if(Aj({tournamentParticipants:r,hydrateParticipants:i,positionAssignments:n,appliedPolicies:d,drawDefinition:y,participantMap:I,contextProfile:T,matchUpWithContext:En,event:v}),!En.matchUpType){let{matchUpType:Gn}=$l({matchUp:En});Gn&&Object.assign(En,{matchUpType:Gn})}Nj({contextProfile:T,matchUpWithContext:En})}En.tieMatchUps&&Uj({matchUpWithContext:En,abbreviatedRoundName:io,roundNumber:pr,roundName:Kr,drawPositions:Dt,scheduleVisibilityFilters:t,sourceDrawPositionRanges:e,drawPositionsRanges:o,initialRoundOfPlay:a,roundNamingProfile:u,appliedPolicies:d,usePublishState:g,publishStatus:E,isRoundRobin:U,roundProfile:R,event:v,tournamentParticipants:r,positionAssignments:n,tournamentRecord:p,seedAssignments:f,participantMap:I,contextContent:S,scheduleTiming:h,contextProfile:T,drawDefinition:y,scoringActive:A,structure:b,context:C});let xc=En.sides?.filter(Gn=>Gn?.participantId).length===2,Ku=!En.winningSide;if(Object.assign(En,{readyToScore:A&&xc&&Ku,hasContext:!0}),xc){let{allParticipantsCheckedIn:Gn,checkedInParticipantIds:ET}=Vs({matchUp:En});Object.assign(En,{allParticipantsCheckedIn:Gn,checkedInParticipantIds:ET})}return Array.isArray(T?.exclude)&&T?.exclude.forEach(Gn=>delete En[Gn]),En}function yj(t,e){let r=oe(e),{bestOf:n,finalSetFormat:o,setFormat:i}=r??{};!o?.tiebreakSet&&!i?.tiebreakSet&&!i?.timed||(t.score.sets=t.score.sets.sort((s,a)=>s.setNumber-a.setNumber).map((s,a)=>{let p=a+1===n&&o?o:i,m=p?.tiebreakSet&&!p?.timed,d=p?.timed;return m?(s.tiebreakSet=!0,[1,2].includes(s.winningSide)&&(s.side1Score=s.winningSide===1?1:0,s.side2Score=s.winningSide===2?1:0)):d&&(s.timed=!0),s}))}function Ej({sourceDrawPositionRoundRanges:t,collectionAssignmentDetail:e,positionAssignments:r,seedAssignments:n,drawPositions:o,roundPosition:i,roundProfile:s,roundNumber:a,onlyDefined:c,matchUp:u}){let{orderedDrawPositions:p,displayOrder:m}=xL({drawPositions:o,roundProfile:s,roundNumber:a}),d=s?.[a]?.feedRound,l=m[0]!==p[0];return p.concat(void 0,void 0).slice(0,2).map((g,I)=>{let S=I+1,h=l?3-S:S,T=LL({...e,positionAssignments:r,displaySideNumber:h,seedAssignments:n,drawPosition:g,isFeedRound:d,sideNumber:S}),y=u.sides?.find(N=>N.sideNumber===S),E=i?(i-1)*2+I+1:void 0,A=E?t?.[E]:void 0;return c({sourceDrawPositionRange:A,...y,...T})})}function Aj({tournamentParticipants:t,hydrateParticipants:e,positionAssignments:r,appliedPolicies:n,drawDefinition:o,participantMap:i,contextProfile:s,matchUpWithContext:a,event:c}){let u=n?.[Da],p=m=>{let d=i?.[m]?.participant;return d&&fs({template:u?.participant,source:d})};a.sides.filter(Boolean).forEach(m=>{if(Pj({side:m,getMappedParticipant:p,tournamentParticipants:t,hydrateParticipants:e,positionAssignments:r,appliedPolicies:n,drawDefinition:o,contextProfile:s,event:c}),m?.participant?.individualParticipantIds?.length&&!m.participant.individualParticipants?.length){let d=m.participant.individualParticipantIds.map(l=>p(l)||(t?ni({policyDefinitions:n,tournamentParticipants:t,internalUse:!0,contextProfile:s,participantId:l}):void 0));e!==!1&&Object.assign(m.participant,{individualParticipants:d})}})}function Pj({side:t,getMappedParticipant:e,tournamentParticipants:r,hydrateParticipants:n,positionAssignments:o,appliedPolicies:i,drawDefinition:s,contextProfile:a,event:c}){if(!t.participantId)return;let u=q(e(t.participantId)||(r?ni({policyDefinitions:i,participantId:t.participantId,tournamentParticipants:r,internalUse:!0,contextProfile:a}):void 0),void 0,!0);if(!u)return;let p,m;if(s?.entries){let l=s.entries.find(g=>g.participantId===t.participantId),f=c?.entries?.find(g=>g.participantId===t.participantId);p=l?.entryStatus||f?.entryStatus,u.entryStatus=p,l?.entryStage&&(m=l.entryStage,u.entryStage=m)}let d;t.drawPosition&&o&&o.find(f=>f.drawPosition===t.drawPosition)?.extensions?.some(f=>f.name==="luckyAdvancement")&&(d=!0,u.luckyAdvancement=!0),n===!1?Object.assign(t,{participant:{entryStage:m,entryStatus:p,luckyAdvancement:d}}):Object.assign(t,{participant:u})}function Nj({contextProfile:t,matchUpWithContext:e}){if(!(t?.inferGender&&(!e.gender||e.gender===as)&&e.sides?.length===2&&e.matchUpType!==Oe))return;let n=e.sides.map(o=>{if(re(Ct)(e.matchUpType))return o.participant?.person?.sex;if(o.participant?.individualParticipants?.length===2){let i=pt(o.participant.individualParticipants.map(s=>s.person?.sex)).filter(Boolean);if(i.length===1)return i[0]}});n.filter(Boolean).length===2&&pt(n).length===1&&(e.inferredGender=n[0])}function Uj(t){let{matchUpWithContext:e}=t,r=e.matchUpStatus==="BYE",n=e.sides?.map(({participant:o,drawPosition:i,sideNumber:s,lineUp:a})=>{let c=o?.participantType===Oe&&o;return{teamParticipant:c&&et({participantRoleResponsibilities:c.participantRoleResponsibilities,participantOtherName:c.participantOtherName,participantName:c.participantName,participantId:c.participantId,teamId:c.teamId}),drawPosition:i,sideNumber:s,lineUp:a}});e.tieMatchUps=e.tieMatchUps.map(o=>{let i=e.matchUpId,a={finishingPositionRange:e.finishingPositionRange,abbreviatedRoundName:t.abbreviatedRoundName,roundNumber:t.roundNumber,roundName:t.roundName};return gb({tieDrawPositions:t.drawPositions,scheduleVisibilityFilters:t.scheduleVisibilityFilters,sourceDrawPositionRanges:t.sourceDrawPositionRanges,sideLineUps:n,drawPositionsRanges:t.drawPositionsRanges,initialRoundOfPlay:t.initialRoundOfPlay,roundNamingProfile:t.roundNamingProfile,additionalContext:a,appliedPolicies:t.appliedPolicies,isCollectionBye:r,usePublishState:t.usePublishState,publishStatus:t.publishStatus,matchUpTieId:i,isRoundRobin:t.isRoundRobin,roundProfile:t.roundProfile,matchUp:o,event:t.event,tournamentParticipants:t.tournamentParticipants,positionAssignments:t.positionAssignments,tournamentRecord:t.tournamentRecord,seedAssignments:t.seedAssignments,participantMap:t.participantMap,contextContent:t.contextContent,scheduleTiming:t.scheduleTiming,contextProfile:t.contextProfile,drawDefinition:t.drawDefinition,scoringActive:t.scoringActive,structure:t.structure,context:t.context})})}function FL({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=pi({timeItems:r?.timeItems??[],itemType:fo});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{allocatedCourts:q(n,!1,!0)}:e}function kL({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=pi({timeItems:r?.timeItems??[],itemType:ai});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{courtId:n}:e}function GL({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=pi({timeItems:r?.timeItems??[],itemType:gs});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{venueId:n}:e}function Yi(t){if(!Array.isArray(t.matchUps))return[];let{matchUps:e,excludeMatchUpStatuses:r,hasParticipantsCount:n,isCollectionMatchUp:o,matchUpStatuses:i,hasWinningSide:s,matchUpFormats:a,roundPositions:c,matchUpFormat:u,collectionIds:p,isMatchUpTie:m,roundNumbers:d,matchUpIds:l,roundNames:f,filterMatchUpTypes:g=!0,filterMatchUpIds:I=!0,stageSequences:S,scheduledDates:h,scheduledDate:T,participantIds:y,processContext:E,tournamentIds:A,matchUpTypes:N,structureIds:U,readyToScore:R,courtIds:D,eventIds:b,venueIds:C,drawIds:_,stages:v}=t,w=Array.isArray(y)?y.filter(Boolean):[],L=Array.isArray(i)?i.filter(Boolean):[],F=Array.isArray(r)?r.filter(Boolean):[],x=Array.isArray(v)?v.filter(Boolean):[],k=Array.isArray(S)?S.filter(Boolean):[],G=Array.isArray(p)?p.filter(Boolean):[],V=Array.isArray(f)?f.filter(Boolean):[],B=Array.isArray(d)?d.filter(Boolean):[],z=Array.isArray(c)?c.filter(Boolean):[],W=Array.isArray(l)&&I?l.filter(Boolean):[],K=Array.isArray(N)&&g?N.filter(Boolean):[],Y=Array.isArray(D)?D.filter(Boolean):[],J=Array.isArray(C)?C.filter(Boolean):[],ct=Array.isArray(a)&&a.filter(Boolean)||typeof u=="string"&&[u]||[],Et=Array.isArray(h)&&h.filter(Boolean).length&&h.filter(Boolean)||typeof T=="string"&&T.length&&[T]||[],Wt=Array.isArray(A)?A.filter(Boolean):[],Dt=Array.isArray(b)?b.filter(Boolean):[],pe=Array.isArray(_)?_.filter(Boolean):[],ye=Array.isArray(U)?U.filter(Boolean):[];return e.filter(Jt=>!(!Dj({matchUp:Jt,readyToScore:R,hasWinningSide:s,isMatchUpTie:m,isCollectionMatchUp:o})||!Rj({matchUp:Jt,targetStages:x,targetStageSequences:k,targetCollectionIds:G,targetRoundNames:V,targetRoundNumbers:B,targetRoundPositions:z,targetMatchUpStatuses:L,excludeTargetMatchUpStatuses:F,targetMatchUpIds:W,targetMatchUpTypes:K,targetMatchUpFormats:ct})||!bj({matchUp:Jt,targetScheduledDates:Et,targetCourtIds:Y,targetVenueIds:J})||E&&!Cj({matchUp:Jt,targetTournamentIds:Wt,targetEventIds:Dt,targetDrawIds:pe,targetStructureIds:ye,targetParticipantIds:w,hasParticipantsCount:n})))}function Dj({matchUp:t,readyToScore:e,hasWinningSide:r,isMatchUpTie:n,isCollectionMatchUp:o}){return!(e&&!re(Ir)(t)&&!t.readyToScore||t.winningSide&&r&&![1,2].includes(t.winningSide)||n!==void 0&&(n&&!t.tieMatchUps||!n&&t.tieMatchUps)||o!==void 0&&(o&&!t.collectionId||!o&&t.collectionId))}function Rj({matchUp:t,targetStages:e,targetStageSequences:r,targetCollectionIds:n,targetRoundNames:o,targetRoundNumbers:i,targetRoundPositions:s,targetMatchUpStatuses:a,excludeTargetMatchUpStatuses:c,targetMatchUpIds:u,targetMatchUpTypes:p,targetMatchUpFormats:m}){return!(e.length&&!e.includes(t.stage)||r.length&&!r.includes(t.stageSequence)||n.length&&(!t.collectionId||!n.includes(t.collectionId))||o.length&&(!t.roundName||!o.includes(t.roundName))||i.length&&(!t.roundNumber||!i.includes(t.roundNumber))||s.length&&(!t.roundPosition||!s.includes(t.roundPosition))||a.length&&(!t.matchUpStatus||!a.includes(t.matchUpStatus))||c.length&&t.matchUpStatus&&c.includes(t.matchUpStatus)||u.length&&!u.includes(t.matchUpId)||p.length&&(!t.matchUpType||!Cs(p,t.matchUpType))||m.length&&(!t.matchUpFormat||!m.includes(t.matchUpFormat)))}function bj({matchUp:t,targetScheduledDates:e,targetCourtIds:r,targetVenueIds:n}){if(e?.length){let{scheduledTime:o}=Wl({matchUp:t}),{scheduledDate:i}=Ws({matchUp:t}),a=mt(o)||i;if(!e.some(c=>Qn(c,a)))return!1}if(r.length){let{courtId:o}=kL({matchUp:t}),{allocatedCourts:i}=FL({matchUp:t}),s=i?.map(({courtId:a})=>a);if(!r.filter(Boolean).includes(o)||s?.includes(o))return!1}if(n.length){let{venueId:o}=GL({matchUp:t});if(!n.filter(Boolean).includes(o))return!1}return!0}function Cj({matchUp:t,targetTournamentIds:e,targetEventIds:r,targetDrawIds:n,targetStructureIds:o,targetParticipantIds:i,hasParticipantsCount:s}){if(e.length&&!e.includes(t.tournamentId)||r.length&&!r.includes(t.eventId)||n.length&&!n.includes(t.drawId)||o.length&&!o.includes(t.structureId))return!1;let a=t.sides?.map(({participantId:c})=>c).filter(Boolean)??[];return!(s&&a.length<s||i.length&&!i.some(u=>a.includes(u)))}function ht(t){let{provisionalPositioning:e,tournamentRecord:r,contextFilters:n,matchUpFilters:o,contextProfile:i,drawDefinition:s,context:a={},structure:c,inContext:u,event:p}=t,{seedAssignments:m,contextContent:d,exitProfiles:l,matchUpsMap:f}=t,g={},I={};if(!c)return{collectionPositionMatchUps:g,error:bi,roundMatchUps:I,matchUps:[]};let S=Array.isArray(o?.eventIds)?o?.eventIds.filter(Boolean):[],h=Array.isArray(o?.structureIds)?o?.structureIds.filter(Boolean):[],T=Array.isArray(o?.drawIds)?o?.drawIds.filter(Boolean):[],y=!a?.eventId||!S?.length&&!n?.eventIds?.filter(Boolean).length||S?.includes(a.eventId)||n?.eventIds?.includes(a.eventId),E=!h?.length||h.includes(c.structureId),A=!s||!T?.length||T.includes(s.drawId);if(!y||!E||!A)return{collectionPositionMatchUps:g,roundMatchUps:I,matchUps:[]};i&&!d&&(d=to({tournamentRecord:r,contextProfile:i,drawDefinition:s}));let{appliedPolicies:N}=It({drawDefinition:s}),U={...t.tournamentAppliedPolicies,...N,...t.policyDefinitions},R=U?.scoring?.structures,D=c.stage&&R?.stage?.[c.stage],b=c.stageSequence&&D?.stageSequence?.[c.stageSequence],C=U?.scoring?.requireAllPositionsAssigned||D?.requireAllPositionsAssigned||b?.requireAllPositionsAssigned;f??=Ie({drawDefinition:s,structure:c});let{positionAssignments:_,allPositionsAssigned:v}=se({structure:c}),w=!C||v,{seedAssignments:L}=Pr({provisionalPositioning:e,drawDefinition:s,structure:c});m=m??L;let{structureId:F}=c;l=l||s&&Ll({drawDefinition:s}).exitProfiles;let x=l?.[F],k=x?.length&&(x[0].split("-").map(Y=>Number.parseInt(Y)).reduce((Y,J)=>Y+J,0)||0),G=!!c.structures,V=Vo({matchUpsMap:f,structureId:F,inContext:u}),B=U?.[Oo],z=Zy({roundNamingPolicy:B,drawDefinition:s,structure:c,matchUps:V}),{roundNamingProfile:W,roundProfile:K}=z;if(I=z?.roundMatchUps??[],o){let Y=new Set(V.filter(J=>Array.isArray(J.tieMatchUps)).map(J=>J.matchUpId));V=Yi({matchUps:Y.size?V.filter(J=>!Y.has(J.matchUpId)):V,...o,filterMatchUpTypes:!1,filterMatchUpIds:!1}).concat(Y.size?V.filter(J=>Y.has(J.matchUpId)):[])}return u?V=Mj({positionAssignments:_,initialRoundOfPlay:k,roundNamingProfile:W,tournamentRecord:r,appliedPolicies:U,seedAssignments:m,contextContent:d,contextProfile:i,drawDefinition:s,contextFilters:n,scoringActive:w,isRoundRobin:G,roundProfile:K,matchUpsMap:f,structureId:F,structure:c,context:a,params:t,event:p,matchUps:V}):V=VL(V),o&&(V=Yi({matchUps:V,...o,filterMatchUpTypes:!1,filterMatchUpIds:!1})),(o?.matchUpTypes||o?.matchUpIds)&&(V=Yi({matchUpTypes:o.matchUpTypes,matchUpIds:o.matchUpIds,matchUps:V})),(o?.matchUpTypes||o?.matchUpIds||u)&&(I=De({matchUps:V}).roundMatchUps??[]),ze({drawDefinition:s,structure:c,event:p})?.tieFormat&&({collectionPositionMatchUps:g}=gL({matchUps:V})),{collectionPositionMatchUps:g,roundMatchUps:I,isRoundRobin:G,roundProfile:K,matchUpsMap:f,matchUps:V}}function VL(t){let e=t?.filter(n=>Array.isArray(n.tieMatchUps)),r=t;return e.forEach(n=>{r=r.concat(...n.tieMatchUps)}),r}function Mj({positionAssignments:t,initialRoundOfPlay:e,roundNamingProfile:r,tournamentRecord:n,appliedPolicies:o,seedAssignments:i,contextContent:s,contextProfile:a,drawDefinition:c,contextFilters:u,scoringActive:p,isRoundRobin:m,roundProfile:d,matchUpsMap:l,structureId:f,structure:g,context:I,params:S,event:h,matchUps:T}){let{sourceDrawPositionRanges:y}=IL({drawDefinition:c,matchUpsMap:l,structureId:f}),E=c?SL({drawDefinition:c,roundProfile:d,matchUpsMap:l,structureId:f}).drawPositionsRanges:void 0,A=S.tournamentParticipants,N=S.participantMap;!A?.length&&!N&&n&&({participants:A=[],participantMap:N}=si({participantsProfile:S.participantsProfile,useParticipantMap:S.useParticipantMap,policyDefinitions:S.policyDefinitions,tournamentRecord:n,contextProfile:a,inContext:!0}));let U=T.map(R=>gb({scheduleVisibilityFilters:S.scheduleVisibilityFilters,hydrateParticipants:S.hydrateParticipants,afterRecoveryTimes:S.afterRecoveryTimes,usePublishState:S.usePublishState,scheduleTiming:S.scheduleTiming,publishStatus:S.publishStatus,sourceDrawPositionRanges:y,tournamentParticipants:A,positionAssignments:t,drawPositionsRanges:E,initialRoundOfPlay:e,roundNamingProfile:r,tournamentRecord:n,appliedPolicies:o,seedAssignments:i,contextContent:s,participantMap:N,contextProfile:a,drawDefinition:c,scoringActive:p,isRoundRobin:m,roundProfile:d,structure:g,context:I,matchUp:R,event:h}));return U=VL(U),u&&(U=Yi({processContext:!0,...u,matchUps:U})),U}function js({matchUp:t}){return t?Mt.includes(t?.matchUpStatus)||t?.winningSide:!1}function wp({requireParticipants:t=!0,scheduleVisibilityFilters:e,tournamentAppliedPolicies:r,tournamentParticipants:n,hydrateParticipants:o,afterRecoveryTimes:i,policyDefinitions:s,tournamentRecord:a,usePublishState:c,matchUpFilters:u,contextFilters:p,contextContent:m,participantMap:d,scheduleTiming:l,publishStatus:f,contextProfile:g,drawDefinition:I,exitProfiles:S,matchUpsMap:h,structureId:T,inContext:y,structure:E,context:A,event:N}){!E&&T&&({structure:E}=tt({drawDefinition:I,structureId:T}));let U=ht({tournamentAppliedPolicies:r,scheduleVisibilityFilters:e,tournamentParticipants:n,hydrateParticipants:o,afterRecoveryTimes:i,policyDefinitions:s,tournamentRecord:a,usePublishState:c,matchUpFilters:u,contextFilters:p,contextContent:m,participantMap:d,scheduleTiming:l,publishStatus:f,contextProfile:g,drawDefinition:I,exitProfiles:S,matchUpsMap:h,structure:E,inContext:y,context:A,event:N}),R=[],D=[],b=[],C=[],_=[];if(U.error)return U;let{matchUps:v}=U,{assignedPositions:w}=se({structure:E}),L=w?.filter(x=>x.participantId).map(x=>x.drawPosition),F;return v.filter(x=>{let k=u?.matchUpTypes?.length===1&&u.matchUpTypes[0]===Ot;return!(x.matchUpType!==Ot&&k)}).forEach(x=>{if(x.matchUpStatus===xr){R.push(x);return}x.matchUpType===Ot&&(F=!0);let k=!!x.collectionId,G=k&&x.sides?.every(J=>J.participantId),V=!k&&x.drawPositions?.filter(Boolean).length===2,B=!k&&x.drawPositions?.every(J=>L?.includes(J)),z=w?.filter(J=>J.bye).map(J=>J.drawPosition),W=!k&&x.drawPositions?.find(J=>z?.includes(J)),Y=wy.includes(x.matchUpStatus)&&(G||V&&(!t||B));return W?_.push(x):js({matchUp:x})?D.push(x):Y?b.push(x):C.push(x)}),{includesTeamMatchUps:F,abandonedMatchUps:R,completedMatchUps:D,upcomingMatchUps:b,pendingMatchUps:C,byeMatchUps:_,structure:E}}function BL({drawDefinition:t,roundNumber:e,structureId:r}){let n=dt({drawDefinition:t,structureId:r},[Kt,po]);if(n.error)return n;let{links:o}=Ma({drawDefinition:t,structureId:r}),i=o.source.reduce((a,c)=>!c.source.roundNumber||c.source.roundNumber===e?a.concat(c):a,[]),s=o.target.reduce((a,c)=>!c.target.roundNumber||c.target.roundNumber===e?a.concat(c):a,[]);return{links:{source:i,target:s}}}function mE({finishingPositions:t,linkCondition:e,linkType:r,source:n}){let o=n.find(i=>{let s=!i.source?.finishingPositions||!t||Re(t,i.source?.finishingPositions);return e===i.linkCondition&&s&&i.linkType===r});return[Er,ir].includes(o?.linkType)&&!o?.source?.roundNumber?M({result:{error:O},stack:"getTargetLink",context:o}):o}function Ma({drawDefinition:t,structureId:e,roundNumber:r}){let n=dt({drawDefinition:t,structureId:e},[Kt,po]);return n.error?n:{links:(t.links??[]).filter(Boolean).reduce((s,a)=>(a.source?.structureId===e&&(!r||a.source.roundNumber===r)&&(s.source=s.source.concat(a)),a.target?.structureId===e&&(!r||a.target.roundNumber===r)&&(s.target=s.target.concat(a)),s),{source:[],target:[]})}}function HL({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 dE({sourceRoundMatchUpCount:t,inContextDrawMatchUps:e,sourceRoundPosition:r,drawDefinition:n,targetLink:o}){if(!o)return{error:wg};let{target:{structureId:i,feedProfile:s,groupedOrder:a,roundNumber:c,positionInterleave:u}}=o,{structure:p}=tt({drawDefinition:n,structureId:i}),{positionAssignments:m}=Pt({structure:p}),l=(e?.filter(D=>D.structureId===p?.structureId)).filter(D=>D.roundNumber===c&&!D.matchUpTieId),f=l.length,g=Q(1,f+1),I=f/t,S=Math.ceil(I*r),h=1-r%2;if(u?.interleave&&I!==.5){let D=u.offset+(r-1)*u.interleave,b=r+D;S=Math.ceil(b/2),h=1-b%2}let T=g,y=g[S-1],E=Jy({roundPositionsCount:g.length,groupedOrder:a}),A=E?.length||1;if(A<=g.length){let D=f/A,b=he(g,D);s===Oi&&b.forEach(C=>C.reverse()),T=E?.length&&E?.map(C=>b[C-1]).flat()||T}s===qe?y=T[S-1]:s===Oi?((!E?.length||A>g.length)&&(S=l.length+1-S),y=T[S-1]):s===Gm&&je()&&console.log(rI,{feedProfile:s});let N=y&&l.reduce((D,b)=>b.roundPosition===y?b:D,void 0),U;N?.feedRound?(h=0,U=Math.min(...(N.drawPositions??[]).filter(Boolean))):U=N?.drawPositions?.length===2&&N?.drawPositions[h];let R=m?.find(({drawPosition:D})=>D===U);if(R){let{extension:D}=ot({element:R,name:yl});if(D?.value)return{disabledDrawPosition:U}}return{matchUp:N,targetDrawPosition:U,matchUpDrawPositionIndex:h}}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}=tt({structureId:i?.structureId,drawDefinition:n});return s?.finishingPosition===ls?vj({inContextDrawMatchUps:t,useTargetMatchUpIds:e,drawDefinition:n,structure:s,matchUp:i}):Oj({matchUp:i})}function vj({inContextDrawMatchUps:t,useTargetMatchUpIds:e,drawDefinition:r,structure:n,matchUp:o}){let{winnerMatchUpId:i,loserMatchUpId:s}=o,{links:a}=BL({roundNumber:o.roundNumber,structureId:n.structureId,drawDefinition:r}),c=a?.source,u=mE({source:c,linkType:Er}),p=mE({linkCondition:Bn,linkType:ir,source:c}),m=mE({source:c,linkType:ir}),d=p&&m;m||(m=p);let l=u?.target?.feedProfile,f=m?.target?.feedProfile,g=p?.target?.feedProfile,I,S,h,T,y,E,A,N,U,R;if(e&&(i||s)&&(A=i&&l!==ln&&t.find(({matchUpId:C})=>C===i),T=s&&f!==ln&&t.find(({matchUpId:C})=>C===s),A||T))return{matchUp:o,targetLinks:{loserTargetLink:m,winnerTargetLink:u},targetMatchUps:{loserMatchUp:T,winnerMatchUp:A}};let{roundPosition:D}=o;R=R||t.filter(C=>C.structureId===n.structureId);let b=R.reduce((C,_)=>_.roundNumber===o.roundNumber&&!_.matchUpTieId?C+1:C,0);return m&&!T&&f!==ln&&({matchUpDrawPositionIndex:E,targetDrawPosition:y,matchUp:T}=dE({targetLink:m,sourceRoundMatchUpCount:b,inContextDrawMatchUps:t,sourceRoundPosition:D,drawDefinition:r})),d&&g!==ln&&({matchUpDrawPositionIndex:h,targetDrawPosition:S,matchUp:I}=dE({targetLink:p,sourceRoundMatchUpCount:b,inContextDrawMatchUps:t,sourceRoundPosition:D,drawDefinition:r})),u&&!A&&l!==ln&&({matchUpDrawPositionIndex:U,targetDrawPosition:N,matchUp:A}=dE({targetLink:u,sourceRoundMatchUpCount:b,inContextDrawMatchUps:t,sourceRoundPosition:D,drawDefinition:r})),A||(R=R||t.filter(C=>C.structureId===n.structureId),{matchUp:A}=HL({structureMatchUps:R,matchUp:o})),et({matchUp:o,targetLinks:{loserTargetLink:m,winnerTargetLink:u,byeTargetLink:p},targetMatchUps:{winnerMatchUpDrawPositionIndex:U,loserMatchUpDrawPositionIndex:E,byeMatchUpDrawPositionIndex:h,winnerTargetDrawPosition:N,loserTargetDrawPosition:y,byeTargetDrawPosition:S,winnerMatchUp:A,loserMatchUp:T,byeMatchUp:I},targetMatchUpIds:!!(i||s)})}function Oj({matchUp:t}){return{targetLinks:{loserTargetLink:void 0,winnerTargetLink:void 0},targetMatchUps:{loserMatchUp:void 0,winnerMatchUp:void 0},matchUp:t}}function YL({drawDefinition:t,inContextDrawMatchUps:e}){let r={};return e.forEach(n=>{let{matchUpId:o,structureId:i,drawPositions:s=[]}=n,{structure:a}=tt({drawDefinition:t,structureId:i});a?.finishingPosition===uo?_j({inContextMatchUp:n,structure:a,drawPositions:s}):xj({scheduleConflictMatchUpIds:r,inContextDrawMatchUps:e,inContextMatchUp:n,drawDefinition:t,matchUpId:o})}),Object.keys(r).length&&e.forEach(n=>{Object.keys(r).includes(n.matchUpId)&&(n.schedule.scheduleConflict=r[n.matchUpId])}),{scheduleConflictMatchUpIds:r}}function _j({inContextMatchUp:t,structure:e,drawPositions:r}){let{roundNumber:n}=t,o=n&&st(n)+1,i=e.matchUps??[],{roundMatchUps:s}=De({matchUps:i});if(o&&s?.[o]){let a=[...r].sort(Zt).map((c,u)=>{let p=s[o].find(m=>m.drawPositions?.includes(c));return{matchUpId:p?.matchUpId,roundNumber:o,schedule:p?.schedule,sideNumber:u+1,structureName:e.structureName}});Object.assign(t,{sidesTo:a})}}function xj({scheduleConflictMatchUpIds:t,inContextDrawMatchUps:e,inContextMatchUp:r,drawDefinition:n,matchUpId:o}){let i=er({useTargetMatchUpIds:!0,inContextDrawMatchUps:e,inContextMatchUp:r,drawDefinition:n,matchUpId:o}),{winnerMatchUp:s}=i.targetMatchUps,{loserMatchUp:a}=i.targetMatchUps;!r.winnerMatchUpId&&s&&(r.winnerMatchUpId=s.matchUpId),!r.loserMatchUpId&&a&&(r.loserMatchUpId=a.matchUpId);let c=Ib({upcomingMatchUp:s}),u=Ib({upcomingMatchUp:a});if(r.matchUpStatus!=="BYE"&&a?.matchUpStatus==="BYE"){let{matchUp:m}=jL({matchUp:a,drawDefinition:n,inContextDrawMatchUps:e})??{};u=m&&Ib({upcomingMatchUp:m})||u}let p=r.schedule?.timeAfterRecovery;p&&(WL({scheduleConflictMatchUpIds:t,inContextMatchUp:r,timeAfterRecovery:p,upcomingTo:c}),WL({scheduleConflictMatchUpIds:t,inContextMatchUp:r,timeAfterRecovery:p,upcomingTo:u})),Object.assign(r,{winnerTo:c,loserTo:u}),r.drawPositions?.filter(Boolean).length&&wj({inContextDrawMatchUps:e,inContextMatchUp:r,winnerMatchUp:s,loserMatchUp:a,targetData:i})}function WL({scheduleConflictMatchUpIds:t,inContextMatchUp:e,timeAfterRecovery:r,upcomingTo:n}){n?.schedule?.scheduledTime&&jt(n.schedule.scheduledTime)<jt(r)&&(t[n.matchUpId]=e.matchUpId,n.schedule.scheduleConflict=e.matchUpId)}function wj({inContextDrawMatchUps:t,inContextMatchUp:e,winnerMatchUp:r,loserMatchUp:n,targetData:o}){let s=o.targetLinks?.loserTargetLink?.linkCondition===Bn,a=Lj(e);if(!a.length)return;let c=_I(r?.sides),u=_I(n?.sides),m=a.find(({participantId:f})=>c.includes(f))?[]:a,l=a.find(({participantId:f})=>u.includes(f))?[]:a;n&&s&&l.length<2&&l.push({bye:!0,tbd:!0}),m?.length&&r&&(!o.targetMatchUpIds&&r&&(r=t.find(({matchUpId:f})=>f===r.matchUpId)),r.potentialParticipants??=[],r.potentialParticipants.push(m)),l?.length&&n&&(o.targetMatchUpIds||(r=t.find(({matchUpId:f})=>f===n.matchUpId)),n.potentialParticipants||(n.potentialParticipants=[]),n.potentialParticipants.push(l))}function Lj(t){return t?.sides?.map(({participant:e,participantId:r,qualifier:n})=>e||r&&{participantId:r}||n&&{qualifier:n}).filter(Boolean)??[]}function jL({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==="BYE"){let s;return t.winnerMatchUpId?s=r.find(({matchUpId:a})=>a===t.winnerMatchUpId):{winnerMatchUp:s}=er({inContextDrawMatchUps:r,drawDefinition:e,matchUpId:n})?.targetMatchUps??{},jL({matchUp:s,drawDefinition:e,inContextDrawMatchUps:r})}return{matchUp:void 0}}function Ib(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 te(t){let e="getAllDrawMatchUps";Object.assign(t,{requireParticipants:!1});let r=va(t);if(r.error)return M({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 va(t){if(!t?.drawDefinition)return{error:$};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:S,drawDefinition:h,nextMatchUps:T,inContext:y,context:E,event:A}=t,N=[],U=[],R=[],D=[],b=[];S&&!r&&(r=to({policyDefinitions:u,tournamentRecord:p,contextProfile:S,event:A}));let C;!e?.length&&p&&(e=p?.participants,(y||a?.withGroupings)&&e?.length&&({participantsWithGroupings:e,groupInfo:C}=Cp({participants:e,participantsProfile:a})));let{structures:_}=In({drawDefinition:h});if(!_)return{error:Nt};n||(n=Ie({drawDefinition:h}));let v=h&&Ll({drawDefinition:h}).exitProfiles;_.forEach(F=>{let{byeMatchUps:x=[],pendingMatchUps:k=[],upcomingMatchUps:G=[],completedMatchUps:V=[],abandonedMatchUps:B=[]}=wp({matchUpFilters:T?void 0:l,contextFilters:T?void 0:d,inContext:y||T||d,hydrateParticipants:t.hydrateParticipants,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:S,drawDefinition:h,exitProfiles:v,matchUpsMap:n,structure:F,context:E,event:A});N=N.concat(...B),U=U.concat(...V),R=R.concat(...G),D=D.concat(...k),b=b.concat(...x)});let w=F=>(!l&&!T&&!d||(l&&(F=Yi({matchUps:F,...l})),d&&(F=Yi({matchUps:F,...d,processContext:!0}))),F),L={abandonedMatchUps:w(N),completedMatchUps:w(U),upcomingMatchUps:w(R),pendingMatchUps:w(D),byeMatchUps:w(b),matchUpsMap:n,...P,groupInfo:C};if(T){let F=typeof T=="object"||{abandoned:!0,completed:!0,upcoming:!0,pending:!0,bye:!0},{abandoned:x,completed:k,upcoming:G,pending:V,bye:B}=F,z=[].concat(...(x&&N)??[],...(k&&U)??[],...(G&&R)??[],...(V&&D)??[],...(B&&b)??[]);YL({inContextDrawMatchUps:z,drawDefinition:h})}return L}function Mn(t){let{participants:e=[],contextContent:r,participantMap:n}=t,{scheduleVisibilityFilters:o,tournamentAppliedPolicies:i,participantsProfile:s,afterRecoveryTimes:a,policyDefinitions:c,useParticipantMap:u,tournamentRecord:p,usePublishState:m,contextFilters:d,matchUpFilters:l,contextProfile:f,nextMatchUps:g,inContext:I,context:S,event:h}=t;if(!h)return{error:le};let{eventId:T,eventName:y,endDate:E,eventType:A,category:N,gender:U,matchUpFormat:R}=h??{},D={...S,...et({indoorOutDoor:h.indoorOutdoor??p?.indoorOutdoor,surfaceCategory:h.surfaceCategory??p?.surfaceCategory,endDate:h.endDate??p?.endDate,tournamentId:p?.tournamentId,matchUpFormat:R,eventName:y,eventType:A,category:N,eventId:T,gender:U})};E&&(D.endDate=E),f&&!r&&(r=to({policyDefinitions:c,tournamentRecord:p,contextProfile:f,event:h}));let b;if(!e?.length&&!n&&p){let w=si({participantsProfile:s,useParticipantMap:u,policyDefinitions:c,tournamentRecord:p,contextProfile:f,inContext:I});n=w.participantMap,e=w.participants??[],b=w.groupInfo}let C=h.drawDefinitions??[],_=gc({tournamentRecord:p,event:h}).scheduleTiming;return{matchUps:C.flatMap(w=>{let{matchUps:L}=te({tournamentParticipants:e,tournamentAppliedPolicies:i,scheduleVisibilityFilters:o,context:D,participantsProfile:s,afterRecoveryTimes:a,policyDefinitions:c,tournamentRecord:p,usePublishState:m,contextFilters:d,contextProfile:f,drawDefinition:w,contextContent:r,matchUpFilters:l,participantMap:n,scheduleTiming:_,nextMatchUps:g,inContext:I,event:h});return L??[]}),groupInfo:b}}function qt(t){let e=X(t,[{tournamentRecord:!0}]);if(e.error)return e;if(!t?.tournamentRecord)return{error:j};let{participantMap:r,participants:n}=t,{scheduleVisibilityFilters:o,participantsProfile:i,afterRecoveryTimes:s,useParticipantMap:a,policyDefinitions:c,tournamentRecord:u,inContext:p=!0,usePublishState:m,contextProfile:d,matchUpFilters:l,contextFilters:f,nextMatchUps:g,context:I}=t,S=t.tournamentId??u.tournamentId,h=u?.events??[];n||({participants:n,participantMap:r}=si({participantsProfile:i,useParticipantMap:a,policyDefinitions:c,tournamentRecord:u,contextProfile:d,inContext:p}));let{appliedPolicies:T}=It({tournamentRecord:u}),y={...I,tournamentId:S,indoorOutDoor:u.indoorOutdoor,surfaceCategory:u.surfaceCategory,endDate:u.endDate},E=to({policyDefinitions:c,tournamentRecord:u,contextProfile:d});return{matchUps:h.flatMap(N=>(y.eventDrawsCount=N.drawDefinitions?.length??0,Mn({context:y,scheduleVisibilityFilters:o,tournamentAppliedPolicies:T,participantsProfile:i,afterRecoveryTimes:s,policyDefinitions:c,tournamentRecord:u,usePublishState:m,contextContent:E,contextFilters:f,contextProfile:d,matchUpFilters:l,participantMap:r,nextMatchUps:g,participants:n,inContext:p,event:N}).matchUps??[])).concat(...u.matchUps??[])}}function cn({scheduleVisibilityFilters:t,afterRecoveryTimes:e,participantsProfile:r,tournamentRecords:n,policyDefinitions:o,usePublishState:i,matchUpFilters:s,contextFilters:a,nextMatchUps:c,inContext:u}){if(typeof n!="object"||!Object.keys(n).length)return{error:kt};let m=Object.keys(n).map(d=>{let l=n[d];return qt({scheduleVisibilityFilters:t,afterRecoveryTimes:e,participantsProfile:r,policyDefinitions:o,tournamentRecord:l,usePublishState:i,matchUpFilters:s,contextFilters:a,nextMatchUps:c,inContext:u}).matchUps??[]}).flat();return{...P,matchUps:m}}function ji(t,e){return Fj(t,e)||(t?.stageSequence||0)-(e?.stageSequence||0)||t?.roundNumber&&e.roundNumber&&t?.roundNumber-e?.roundNumber||(t?.roundPosition??0)-(e?.roundPosition??0)}function Fj(t,e){return(Aa[t?.stage]||0)-(Aa[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:S,event:h}=t,{eventId:T,eventName:y,endDate:E,eventType:A,category:N,gender:U,matchUpFormat:R}=h??{},D={...S,surfaceCategory:h?.surfaceCategory??p?.surfaceCategory,indoorOutDoor:h?.indoorOutdoor??p?.indoorOutdoor,matchUpFormat:R,eventType:A,eventName:y,category:N,eventId:T,endDate:E,gender:U},b;return!e?.length&&!r&&p&&({participants:e=[],participantMap:r,groupInfo:b}=si({participantsProfile:s,useParticipantMap:u,policyDefinitions:c,tournamentRecord:p,contextProfile:l,inContext:I})),l&&!n&&(n=to({policyDefinitions:c,tournamentRecord:p,contextProfile:l,drawDefinition:f,event:h})),{...te({context:D,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:h}),groupInfo:b}}var Sb=t=>e=>!t||typeof e!="object"?void 0:Array.isArray(t)&&t.map(r=>({[r]:Li({element:e,accessor:r})?.value}))||typeof t=="object"&&Object.keys(t).map(r=>({[r]:Li({element:e,accessor:r})?.value}))||(typeof t=="string"&&Li({element:e,accessor:t}))?.value,Fr=Sb;function hc({finishingPositionOffset:t=0,finishingPositionLimit:e,positionsFed:r,roundsCount:n,roundLimit:o,matchUps:i,lucky:s,fmlc:a}){if(!Nr(i))return[];let{roundProfile:c,roundNumbers:u=[]}=De({interpolate:!0,matchUps:i});n=n??Math.max(...u,0);let p=o?n-o:0,m=p&&c?.[n-p]?.matchUpsCount,d=c&&Object.values(c).map(Fr("matchUpsCount")),l=(I,S)=>{let h=Math.min(...I);m&&S&&h===1&&(h=m);let T=Math.max(...I);return e&&T>e&&(T=e),[h,T]},f=c&&Object.assign({},...u.map(I=>{let S=(n??0)+1-I-p,h=c[I].matchUpsCount,T={finishingPositionRange:{},finishingRound:S},y=d?.slice(I-1).reduce((C,_)=>C+(_||0),0),E=a&&I!==1,A=1+t+(E?r??0:0),N=1,U=Q(A,s?A+h*2:y+A+N),R=y+N-h,D=l(U.slice(R)),b=l(U.slice(0,R),!0);return T.finishingPositionRange={loser:D,winner:b},{[I]:T}})),g=je({finishingRound:!0});return i.filter(Boolean).forEach(I=>{let S=I.roundNumber&&f[I.roundNumber];g&&!S&&console.log({roundFinishingData:f,matchUp:I}),I.finishingRound=S?.finishingRound,I.finishingPositionRange=S?.finishingPositionRange}),i}function Ts({inContextDrawMatchUps:t,drawDefinition:e,matchUpsMap:r}){if(!e)return{error:$};let n={loserMatchUpIds:{},winnerMatchUpIds:{}};if(t||({matchUps:t,matchUpsMap:r}=te({inContext:!0,drawDefinition:e,matchUpsMap:r})),!r?.drawMatchUps.some(i=>i.finishingPositionRange)&&e?.structures?.length===1&&!e?.structures[0].structures){let i=r?.drawMatchUps??[];hc({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=Vo({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 tn(t){let e=Ar(t),r=t.matchUps??[],n=t.drawIds??[],{includeParticipantDependencies:o,tournamentRecord:i,drawDefinition:s}=t;if(!Array.isArray(r))return{error:Vn};if(!Array.isArray(n))return{error:Pn};let a=t.matchUpIds?.length?t.matchUpIds:r.map(T=>T.matchUpId);if(!Array.isArray(a))return{error:Ms};let c={},u={},p={},m={};i&&!Object.keys(e).length&&(e={[i.tournamentId]:i});let d=Object.values(e),f=d.reduce((T,y)=>T.concat(y.events??[]).map(E=>(E.drawDefinitions??[]).map(A=>A.links??[])).flat(1/0),[]).filter(({linkType:T})=>T===fn),g=r;f.length&&(g=cn({nextMatchUps:!0,tournamentRecords:e}).matchUps,kj({positionLinks:f,sourceStructureIdMap:p,positionDependencies:c,matchUps:g}));let I=T=>{u[T]||(u[T]={dependentMatchUpIds:[],participantIds:[],matchUpIds:[],sources:[]},m[T]=[])},S=(T,y)=>{u[T].matchUpIds.forEach(A=>{u[y].matchUpIds.push(A)}),u[y].matchUpIds.push(T),u[T].dependentMatchUpIds.push(y),o&&u[T].participantIds.forEach(A=>u[y].participantIds.push(A))},h=T=>{let y=Object.keys(c).length;for(let E of T??[]){let{matchUpId:A,winnerMatchUpId:N,loserMatchUpId:U}=E;if(!a.length||a.includes(A)){if(I(A),o){let{individualParticipantIds:b}=Dp(E);u[A].participantIds=b}N&&(I(N),S(A,N),m[N].push(A)),U&&(I(U),S(A,U),m[U].push(A)),u[A].sources.push(m[A]);let R=m[A].map(b=>u[b].sources[0]).flat(),D=m[A].map(b=>u[b].sources[1]).flat();if(u[A].sources.push(R,D),y){let b=E.containerStructureId||E.structureId,C=p[b];if(c[C])for(let _ of c[C])I(_),S(_,A),m[_].push(A)}}}};if(s)Ts({drawDefinition:s}),g?.length||(g=rr({drawDefinition:s}).matchUps),h(g);else{g?.length||(g=cn({nextMatchUps:!0,tournamentRecords:e}).matchUps),n.length||(n=Gj(d));for(let T of n)Vj({matchUps:g,drawId:T,tournamentRecords:e,processMatchUps:h})}return{positionDependencies:c,matchUpDependencies:u,sourceMatchUpIds:m,matchUps:g,...P}}function kj({positionLinks:t,sourceStructureIdMap:e,positionDependencies:r,matchUps:n}){let o=t.reduce((i,s)=>{let a=s.source?.structureId,c=s.target?.structureId;return a&&c&&(e[c]=a),a&&!i.includes(a)&&i.push(a),i},[]);for(let i of o)r[i]=[];for(let i of n??[]){let s=i.containerStructureId||i.structureId;o.includes(s)&&r[s].push(i.matchUpId)}}function Gj(t){return t?.length?t.map(({events:e=[]})=>e.map(({drawDefinitions:r=[]})=>r.map(({drawId:n})=>n))).flat(1/0):[]}function Vj({matchUps:t,drawId:e,tournamentRecords:r,processMatchUps:n}){let o=t?.filter(s=>s.drawId===e).sort(ji);if(!o?.find(({roundPosition:s})=>!s)){let s=o?.find(({tournamentId:c})=>c),{drawDefinition:a}=_e({tournamentRecord:r[s?.tournamentId],drawId:e});a&&Ts({drawDefinition:a})}n(o)}function ue(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 Oa({matchUpStatus:t}){return _y.includes(t)}function qL({matchUpStatus:t}){return Nl.includes(t)}function iS({matchUpStatus:t}){return xy.includes(t)}function sS({matchUpStatus:t,winningSide:e,tieMatchUps:r,sides:n,score:o}){let i=n?.find(({participantId:c})=>c),s=r?.filter(sS)?.length;return ue({score:o})||s||e&&i||t&&qL({matchUpStatus:t})&&![xt,Lt,bn].includes(t)}function qi(t){let{drawDefinition:e,findContainer:r,structureId:n,event:o}=t,i=t.structure,{containedStructures:s}=Vi({drawDefinition:e}),a=n?s[n]??[]:[],c={isCollectionMatchUp:!1};if(!i){let N=tt({drawDefinition:e,structureId:n});if(N.error)return N;i=r?N.containingStructure??N.structure:N.structure}if(Ae({structure:i}))return{structure:i,isAdHoc:!0,error:is};let{matchUps:u}=te({inContext:!0,matchUpFilters:c,drawDefinition:e,event:o}),p=u?.filter(N=>N.structureId===n||a.includes(N.structureId)),{matchUpDependencies:m}=tn({drawIds:[e.drawId],matchUps:u,drawDefinition:e}),d=[],l=[],f={},g=[];for(let N of u??[]){if(N.structureId===n||a.includes(N.structureId)){l.push(...N.drawPositions??[]);let U=N.roundNumber;for(let R of(N.drawPositions??[]).filter(Boolean))(!f[R]||U&&f[R]>U)&&(f[R]=U)}sS(N)&&(g.push(N),d.push(N.matchUpId,...m?.[N?.matchUpId]?.matchUpIds??[]))}let I=pt(l.filter(Boolean)).sort(Zt),S=pt(d),h=pt(p?.map(({matchUpId:N,drawPositions:U})=>S.includes(N)?U:[]).flat().filter(Boolean)).sort(Zt),{positionAssignments:T}=Pt({drawDefinition:e,structure:i}),y=T?.filter(N=>N.bye).map(N=>N.drawPosition),E=T?.filter(N=>N.qualifier).map(N=>N.drawPosition),A=I?.filter(N=>!h.includes(N))??[];return{allDrawPositions:I,inContextStructureMatchUps:p,drawPositionInitialRounds:f,activeDependentMatchUpIds:S,qualifyingDrawPositions:E,inactiveDrawPositions:A,positionAssignments:T,activeDrawPositions:h,byeDrawPositions:y,activeMatchUps:g,structure:i}}function qs({drawPosition:t,matchUps:e=[]}){return{initialRoundNumber:e.filter(({drawPositions:n})=>t&&n?.includes(t)).map(({roundNumber:n})=>n).sort(Zt)[0]}}var Tc={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 lE=[];function Pe(t,e){_t(t)&&(t={method:t}),(e||je())&&lE.push(t)}function Bj(t){let e=lE.slice();return t&&(lE.length=0),e}function $L(t){let r=Bj(t).map(n=>{let{color:o,keyColors:i,method:s,newline:a}=n,c=Object.keys(Tc).includes(o)?Tc[o]:Tc.cyan,p=Object.keys(n).filter(d=>!["color","keyColors","method","newline"].includes(d)).map(d=>{let l=i&&Object.keys(i).includes(d)&&Tc[i[d]]?Tc[i[d]]:Tc.brightwhite;return`${Tc.white}${d}: ${l}${n[d]}`}).join(", "),m=s?.length<15?" ":" ";return[a?`
1
+ var aH=Object.defineProperty;var Gt=(t,e)=>{for(var r in e)aH(t,r,{get:e[r],enumerable:!0})};var kx="3.2.2";function ns(){return kx}var qN={};Gt(qN,{competitionGovernor:()=>jR,drawsGovernor:()=>rv,entriesGovernor:()=>pv,eventGovernor:()=>Nv,generationGovernor:()=>Cv,matchUpFormatGovernor:()=>WP,matchUpGovernor:()=>zv,mocksGovernor:()=>Ch,officiatingGovernor:()=>rx,participantGovernor:()=>DO,policyGovernor:()=>OM,publishingGovernor:()=>wO,queryGovernor:()=>tv,rankingGovernor:()=>Mh,reportGovernor:()=>HO,scheduleGovernor:()=>r_,scoreGovernor:()=>th,temporalGovernor:()=>j_,tieFormatGovernor:()=>d_,tournamentGovernor:()=>M_,venueGovernor:()=>lx});var jR={};Gt(jR,{getCompetitionLeaderboard:()=>ky,getCompetitionParticipantState:()=>Fy,getCompetitionPolicy:()=>To,getCompetitionState:()=>Fo,getLinkedTournamentIds:()=>Np,getTournamentIds:()=>$m,initializeCompetitionState:()=>kR,linkTournaments:()=>NR,mutate:()=>WR,processCompetitionMatchUp:()=>Km,processCompetitionRound:()=>BR,query:()=>YR,resetCompetitionState:()=>HR,unlinkTournament:()=>DR,unlinkTournaments:()=>UR});var WR={};Gt(WR,{initializeCompetitionState:()=>kR,linkTournaments:()=>NR,processCompetitionMatchUp:()=>Km,processCompetitionRound:()=>BR,resetCompetitionState:()=>HR,unlinkTournament:()=>DR,unlinkTournaments:()=>UR});var bs="SINGLES",Ct="SINGLES",Qo="DOUBLES",Rt="DOUBLES",Ir="TEAM",Ot="TEAM",uH="HYBRID",Um="HYBRID",Gx={SINGLES_MATCHUP:bs,SINGLES:Ct,DOUBLES_MATCHUP:Qo,DOUBLES:Rt,TEAM_MATCHUP:Ir,TEAM:Ot,HYBRID_MATCHUP:uH,HYBRID:Um};var NT={[Ct]:[Ct,"S"],[Rt]:[Rt,"D"],[Ot]:[Ot,"T"],[Um]:[Um,"H"],S:[Ct,"S"],D:[Rt,"D"],T:[Ot,"T"],H:[Um,"H"]};function Zt(t,e){return(t??0)-(e??0)}function st(t){return typeof t=="number"?parseInt(t.toString()):typeof t=="string"?parseInt(t):0}function kr(t){return typeof t=="function"}function _t(t){return typeof t=="string"}function Tt(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Vx(t,e){if(!Tt(t)||!Tt(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 DT(t,e){return Array.isArray(t)?Object.assign({},...(t??[]).filter(Tt).map(r=>r[e]&&{[r[e]]:r}).filter(Boolean)):{}}var Bx=t=>e=>Object.keys(t).every(r=>e[r]===t[r]);function UT(t,e){if(t===void 0)return null;if(!Tt(t)||t===null)return t;let r=Object.keys(t),n=o=>o===void 0?null:o;return Object.assign({},...r.map(o=>Array.isArray(t[o])?{[o]:e?t[o]:t[o].map(i=>UT(i))}:{[o]:e?n(t[o]):UT(t[o])}))}function pU(t){return Array.isArray(t)?t.length+t.map(pU).reduce((e,r)=>e+r,0):Tt(t)&&t!==null?Object.keys(t).length+Object.keys(t).map(e=>pU(t[e])).reduce((e,r)=>e+r,0):0}function Hx(t){if(t===null||typeof t!="object")return;let e=JSON.stringify(t),r=pU(t),n=e.split("").reduce((o,i)=>o+i.charCodeAt(0),0);return[e.length,r,n].map(o=>o.toString(36)).join("")}function en(t){return Number.isNaN(Number(t))?!1:t>0&&(t&t-1)===0}function Wx(t){if(!t.length)return;let e=[...t].sort(Zt),r=Math.floor(e.length/2);return e.length%2?e[r]:(e[r-1]+e[r])/2}function Yx(t){if(t===1||Number.isNaN(Number(t))||!en(t))return!1;let e=t,r=1;for(;e!==2;)r+=1,e=e/2;return r}function Jd(t){return Number.isNaN(Number(t))?0:t%2&&t+1||t}function Zd(t){return Math.pow(2,Math.round(Math.log(t)/Math.log(2)))}function Le(t){return!Number.isNaN(Number.parseFloat(t))}function RT(t){let e=st(t);if(!Number.isNaN(e))return e===0?!1:(e&-e)===1}function Si(t){if(Number.isNaN(Number(t)))return!1;for(;!en(t);)t++;return t}function pn(t,e,r){return t=Math.ceil(t),e=Math.floor(e),Math.floor((r??Math.random)()*(e-t+1))+t}function yt(t){return _t(t)&&!t.trim().length?!1:Number.isSafeInteger(typeof t=="string"?+t:t)}function jx(t=1,e=3,r=!0,n){let o=n??Math.random,i=0;for(let s=0;s<e;s++)i+=o()*(t/e);return r&&t>1?Math.round(i):i}function pH(t,e){e||(e=1);let r=1/e;return Math.round(t*r)/r}function mU(t,e,r,n,o=2,i){let s=i??Math.random,a=1-s(),c=1-s(),u=Math.sqrt(-2*Math.log(a))*Math.cos(2*Math.PI*c);return u=u/10+.5,u>1||u<0?u=mU(t,e,r,void 0,2,i):(u=Math.pow(u,r),u*=e-t,u+=t),n&&(u=pH(u,n)),Number.parseFloat(u.toFixed(o))}function vg(t,e=2){return Number.parseFloat(Number(Math.round(t*1e3)/1e3).toFixed(e))}function pt(t){return Array.isArray(t)?t?.filter((e,r,n)=>n.lastIndexOf(e)===r):[]}function qx(t){return Array.isArray(t)?t?.map(e=>e===null?void 0:e):t}function ar(t,e){if(!Array.isArray(t))return[];let r=e??Math.random;return t.map(n=>[r(),n]).sort((n,o)=>n[0]-o[0]).map(n=>n[1])}function Lc(t){return yt(t)?t:1/0}function mn(t){return Array.isArray(t)?t.reduce((e,r)=>(e[r]||(e[r]=0),e[r]++,e),{}):{}}function $x(t){return dU(mn(t))}function dU(t){return Object.keys(t).reduce((e,r)=>{let n=t[r];return e[n]?e[n].push(r):e[n]=[r],e},{})}function mH(t,e,r){return r.indexOf(t)===e}function bT(t){return t.filter(mH)}function Sr(t,e){return Array.isArray(t)&&t.length?t.splice(Math.floor((e??Math.random)()*t.length),1)[0]:void 0}function An(t,e){let r=Math.floor((e??Math.random)()*t.length);return t[r]}function Q(t,e){return Array.from({length:e-t},(r,n)=>n+t)}function os(t,e){return e.reduce((r,n,o)=>(n===t&&r.push(o),r),[])}function Yt(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 lU(t,e){return!Array.isArray(t)||!Array.isArray(e)?[]:t.filter(r=>!e.includes(r))}function Re(t,e){return!Array.isArray(t)||!Array.isArray(e)?!1:t.some(r=>e.includes(r))}function Kx(t,e){return Array.isArray(e)&&e.reduce((r,n)=>(r[n]=1+r[n]||1,r),{})[t]||0}function zx(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 he(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 fU(t,[e,...r]){return t.length?[t.slice(0,e),...fU(t.slice(e),[...r,e])]:[]}function Qx(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 CT(t){return Array.isArray(t)?t.reduce((e,r)=>!isNaN(parseInt(r))&&e,!0):!1}function MT(t){return Array.isArray(t)?t.reduce((e,r)=>isNaN(parseInt(r))&&e,!0):!1}function Og(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 Xx(t,e=1){if(!Array.isArray(t)||!t.every(yt))return[];let r=Math.min(...t,e),n=Math.max(...t);return Q(r,n+1).filter(o=>!t.includes(o))}function Cs(t,e){return!Array.isArray(t)||!_t(e)?!1:Yt(t,NT[e]).length}var P={success:!0},gU="error",Jx={SUCCESS:P,ERROR:gU};function vT({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}):{...P}}var dw={};Gt(dw,{addNotice:()=>at,callListener:()=>il,createInstanceState:()=>wD,cycleMutationStatus:()=>aI,deepCopyEnabled:()=>sI,deleteNotice:()=>YT,deleteNotices:()=>ss,disableNotifications:()=>LD,enableNotifications:()=>iI,getDevContext:()=>je,getMethods:()=>cI,getNotices:()=>WT,getProvider:()=>jT,getTopics:()=>br,getTournamentId:()=>_s,getTournamentRecord:()=>uI,getTournamentRecords:()=>Zo,globalLog:()=>GD,handleCaughtError:()=>_m,hasTopic:()=>Kc,removeTournamentRecord:()=>kD,setDeepCopy:()=>op,setDevContext:()=>np,setGlobalLog:()=>uw,setGlobalMethods:()=>pw,setGlobalSubscriptions:()=>HH,setMethods:()=>mw,setStateMethods:()=>VD,setStateProvider:()=>VH,setSubscriptions:()=>WH,setTournamentId:()=>Om,setTournamentRecord:()=>FD,setTournamentRecords:()=>sl,timeKeeper:()=>BH});var OT={message:"Chronological error; time violation.",code:"ANACHRONISM"},tl={message:"Duplicate entry",code:"DUPLICATE_ENTRY"},IU={message:"Cannot remove main structure",code:"ERR_CANNOT_REMOVE_MAIN_STRUCTURE"},_T={message:"records must be an object with tournamentId keys",code:"ERR_INVALID_TOURNAMENTS"},kt={message:"Missing tournamentRecords",code:"ERR_MISSING_TOURNAMENTS"},j={message:"Missing tournamentRecord",code:"ERR_MISSING_TOURNAMENT"},Fc={message:"Invalid tournamentRecord",code:"ERR_INVALID_TOURNAMENT"},Za={message:"Missing tournamentId",code:"ERR_MISSING_TOURNAMENT_ID"},ma={message:"Invalid drawDefinition",code:"ERR_INVALID_DRAWDEF"},$={message:"Missing drawDefinition",code:"ERR_MISSING_DRAWDEF"},SU={message:"Existing drawDefinition(s)",code:"ERR_EXISTING_DRAWDEFS"},Rr={message:"drawDefinition not found",code:"ERR_NOT_FOUND_DRAWDEF"},Do={message:"Invalid structure",code:"ERR_INVALID_STRUCTURE"},_g={message:"Incomplete source structure",code:"ERR_INCOMPLETE_STRUCTURE"},xg={message:"Invalid drawPosition for seedAssignment",code:"ERR_INVALID_SEEDING_POSITION"},kc={message:"drawPosition already assigned",code:"ERR_EXISTING_POSITION_ASSIGNMENT"},hU={message:"Schedule not cleared",code:"ERR_UNCHANGED_SCHEDULE_NOT_CLEARED"},TU={message:"Schedule conflict: court slot already occupied",code:"ERR_SCHEDULE_CONFLICT_DOUBLE_BOOKING"},yU={message:"Schedule conflict: matchUps scheduled outside court availability",code:"ERR_SCHEDULE_CONFLICT_COURT_UNAVAILABLE"},EU={message:"drawPosition not cleared",code:"ERR_FAILURE_POSITION_NOT_CLEARED"},dH={message:"drawPosition not found",code:"ERR_NOT_FOUND_DRAW_POSITION"},Qu={message:"Unrecognized drawType",code:"ERR_UNRECOGNIZED_DRAW_TYPE"},Gc={message:"Missing drawPositions",code:"ERR_MISSING_DRAW_POSITIONS"},Vc={message:"drawPosition is active",code:"ERR_ACTIVE_DRAW_POSITION"},Zx={message:"drawPosition is occupied",code:"ERR_OCCUPIED_DRAW_POSITION"},is={message:"Invlid drawPosition",code:"ERR_INVALID_DRAW_POSITION"},da={message:"Missing drawPosition",code:"ERR_MISSING_DRAW_POSITION"},el={message:"Invalid drawType",code:"ERR_INVALID_DRAW_TYPE"},Dm={message:"Invalid drawSize",code:"ERR_INVALID_DRAW_SIZE"},lH={message:"Cannot set drawSize to be less than existing entries",code:"ERR_INVALID_DRAW_SIZE_MISMATCH"},Bc={message:"Missing drawSize",code:"ERR_MISSING_DRAW_SIZE"},Pn={message:"Missing drawId",code:"ERR_MISSING_DRAW_ID"},AU={message:"drawId exists",code:"ERR_EXISTING_DRAW_ID"},PU={message:"participantId cannot be assigned to multiple seedNumbers",code:"INVALID_PARTICIPANT_SEEDING"},NU={message:"seedsCount greater than drawSize",code:"ERR_INVALID_SEED_COUNT"},UU={message:"Missing seedCountThresholds",code:"ERR_MISSING_SEED_COUNT_THRESHOLD"},DU={message:"Invalid action",code:"ERR_INVALID_ACTION"},xT={message:"Invalid assignment",code:"ERR_INVALID_ASSIGNMENT"},RU={message:"Missing seedAssignments",code:"ERR_MISSING_SEED_ASSIGNMENTS"},bU={message:"Invalid seedNumber",code:"ERR_INVALID_SEED_NUMBER"},CU={message:"Invalid seedPosition",code:"ERR_INVALID_SEED_POSITION"},wg={message:"Missing targetLink",code:"ERR_MISSING_LINK_TARGET"},MU={message:"Existing round",code:"ERR_EXISTING_ROUND"},fH={message:"Missing roundNumber",code:"ERR_MISSING_ROUND_NUMBER"},dn={message:"Missing structureId",code:"ERR_MISSING_STRUCTURE_ID"},Nt={message:"structure not found",code:"ERR_NOT_FOUND_STRUCTURE"},Lg={message:"Missing structures",code:"ERR_MISSING_STRUCTURES"},bi={message:"Missing structure",code:"ERR_MISSING_STRUCTURE"},Fg={message:"Missing MAIN structure",code:"ERR_MISSING_MAIN_STRUCTURE"},vU={message:"drawDefinition contains unlinked structures",code:"ERR_MISSING_STRUCTURE_LINKS"},Kn={message:"Invalid eventType",code:"ERR_INVALID_EVENT_TYPE"};var le={message:"Missing event / eventId",code:"ERR_MISSING_EVENT_ID"},Gr={message:"Event not found",code:"ERR_NOT_FOUND_EVENT"},OU={message:"Event exists",code:"ERR_EXISTING_EVENT"},_U={message:"Missing entries",code:"ERR_MISSING_ENTRIES"},xU={message:"Invalid entries",code:"ERR_INVALID_ENTRIES"},kg={message:"Missing assignments",code:"ERR_MISSING_ASSIGNMENTS"},Gg={message:"Missing stage",code:"ERR_MISSING_STAGE"},tc={message:"Invalid stage",code:"ERR_INVALID_STAGE"},wU={message:"stageSequence limit",code:"ERR_LIMIT_STAGE_SEQUENCE"},LU={message:"Missing positionAssignments",code:"ERR_MISSING_POSITION_ASSIGNMENTS"},FU={message:"Cannot Assign BYE status if no assignment: { bye: true }",code:"ERR_UNCHANGED_CANNOT_ASSIGN_BYE"},kU={message:"Lucky draw first round allows at most one BYE",code:"ERR_LUCKY_DRAW_BYE_LIMIT"},wT={message:"Unrecognized matchUpStatus",code:"ERR_UNRECOGNIZED_MATCHUP_STATUS"},Hc={message:"Unrecognized matchUpFormat",code:"ERR_UNRECOGNIZED_MATCHUP_FORMAT"},Vg={message:"Incompatible matchUpStatus",code:"ERR_INCOMPATIBLE_MATCHUP_STATUS"},tw={message:"Propagated exits downstream",code:"ERR_PROPAGATED_EXITS_DOWNSTREAM"},ec={message:"Invalid matchUpStatus",code:"ERR_INVALID_MATCHUP_STATUS"},Xo={message:"Invalid tieFormat",code:"ERR_INVALID_TIE_FORMAT"},GU={message:"Invalid matchUpFormat",code:"ERR_INVALID_MATCHUP_FORMAT"},VU={message:"Missing matchUpFormat",code:"ERR_MISSING_MATCHUP_FORMAT"},BU={message:"Missing collectionDefinition",code:"ERR_MISSING_COLLECTION_DEFINITION"},la={message:"Missing tieFormat",code:"ERR_MISSING_TIE_FORMAT"},mr={message:"Missing matchUpId",code:"ERR_MISSING_MATCHUP_ID"},Ms={message:"Missing matchUpIds",code:"ERR_MISSING_MATCHUP_IDS"},Be={message:"matchUp not found",code:"ERR_NOT_FOUND_MATCHUP"},Vn={message:"Missing matchUps",code:"ERR_MISSING_MATCHUPS"},Xe={message:"Missing matchUp",code:"ERR_MISSING_MATCHUP"},cr={message:"Invalid matchUp",code:"ERR_INVALID_MATCHUP"},LT={message:"Missing policyType",code:"ERR_MISSING_POLICY_TYPE"},fa={message:"Missing policyDefinitions",code:"ERR_MISSING_POLICY_DEFINITIONS"},gH={message:"Missing seeding policy",code:"ERR_MISSING_POLICY_SEEDING"},HU={message:"Missing avoidance policy",code:"ERR_MISSING_POLICY_AVOIDANCE"},FT={message:"Missing policy attributes",code:"ERR_MISSING_POLICY_ATTRIBUTES"},WU={message:"Invalid policyDefinitions",code:"ERR_INVALID_POLICY_DEFINITIONS"},kT={message:"existing policyType",code:"ERR_EXISTING_POLICY_TYPE"},IH={message:"Policy not attached",code:"ERR_FAILURE_POLICY_NOT_ATTACHED"},Xu={message:"Policy not found",code:"ERR_NOT_FOUND_POLICY"},SH={message:"Missing scoring policy / matchUpFormats",code:"ERR_MISSING_POLICY_SCORING_MATCHUP_FORMATS"},YU={message:"Invalid sideNumber",code:"ERR_INVALID_SIDE_NUMBER"},hH={message:"Invalid setNumber",code:"ERR_INVALID_SET_NUMBER"},Bg={message:"Missing setObject",code:"ERR_MISSING_SET_ATTRIBUTE"},TH={message:"Missing setNumber",code:"ERR_MISSING_SET_NUMBER"},yH={message:"Missing sideNumber",code:"ERR_MISSING_SIDE_NUMBER"},Hg={message:"Missing courtId",code:"ERR_MISSING_COURT_ID"},nt={message:"Missing value",code:"ERR_MISSING_VALUE"},jU={message:"Missing birthdate",code:"ERR_MISSING_BIRTH_DATE"},qU={message:"Missing date",code:"ERR_MISSING_DATE"},Wg={message:"No valid dates",code:"ERR_NO_VALID_DATES"},rl={message:"Invalid bookings",code:"ERR_INVALID_BOOKINGS"},Yg={message:"Invalid dateAvailability",code:"ERR_INVALID_DATE_AVAILABILITY"},$U={message:"Missing dateAvailability",code:"ERR_MISSING_DATE_AVAILABILITY"},ae={message:"Invalid Date",code:"ERR_INVALID_DATE"},vs={message:"Invalid time",code:"ERR_INVALID_TIME"},KU={message:"Invalid tournament dates",code:"ERR_INVALID_DATES_TOURNAMENT"},ew={message:"Missing date range",info:"Event or tournament must have start and end dates",code:"ERR_MISSING_DATE_RANGE"},Ju={message:"Invalid Time Zone",code:"ERR_INVALID_TIME_ZONE"},Zu={message:"Invalid embargo: must be an ISO 8601 datetime with timezone (Z or \xB1HH:MM offset)",code:"ERR_INVALID_EMBARGO"},GT={message:"Invalid game scores",code:"ERR_INVALID_SCORES_GAME"},zU={message:"Invalid score",code:"ERR_INVALID_SCORE"},nl={message:"Invalid winningSide",code:"ERR_INVALID_WINNING_SIDE"};var rw={message:"No participants generated",code:"ERR_NO_PARTICIPANTS_GENERATED"},jg={message:"Cannot modify tieFormat",code:"ERR_UNCHANGED_CANNOT_MODIFY_TIEFORMAT"},QU={message:"Cannot modify participantType",code:"ERR_UNCHANGED_CANNOT_MODIFY_PARTICIPANT_TYPE"},Rm={message:"Cannot remove participants",code:"ERR_UNCHANGED_CANNOT_REMOVE_PARTICIPANTS"},XU={message:"Participant category mismatch",code:"ERR_CATEGORY_MISMATCH"},ol={message:"Cannot change winningSide",code:"ERR_UNCHANGED_CANNOT_CHANGE_WINNING_SIDE"},Ci={message:"Invalid participant",code:"ERR_INVALID_PARTICIPANT"},Vr={message:"Invalid participantId",code:"ERR_INVALID_PARTICIPANT_ID"},Mr={message:"Invalid participantIds",code:"ERR_INVALID_PARTICIPANT_IDS"},JU={message:"Invalid participantRole",code:"ERR_INVALID_PARTICIPANT_ROLE"},Nn={message:"Invalid participantType",code:"ERR_INVALID_PARTICIPANT_TYPE"},ZU={message:"Missing participantRole",code:"ERR_MISSING_PARTICIPANT_ROLE"},ga={message:"Missing participant",code:"ERR_MISSING_PARTICIPANT"},Wc={message:"Missing participants",code:"ERR_MISSING_PARTICIPANTS"},He={message:"Missing participantId",code:"ERR_MISSING_PARTICIPANT_ID"},tD={message:"Missing qualified participants",code:"ERR_MISSING_QUALIFIED_PARTICIPANTS"},ee={message:"Participant Not Found",code:"ERR_NOT_FOUND_PARTICIPANT"},eD={message:"participantId exists",code:"ERR_EXISTING_PARTICIPANT_ID"},EH={message:"participant pair exists",code:"ERR_EXISTING_PARTICIPANT_PAIR"},rD={message:"No participant removed",code:"ERR_UNCHANGED_NO_PARTICIPANT_REMOVED"},Ro={message:"Missing participantIds",code:"ERR_MISSING_PARTICIPANT_IDS"},nD={message:"Missing participantsCount",code:"ERR_MISSING_PARTICIPANT_COUNT"},oD={message:"Participant not checked in",code:"ERR_UNCHANGED_PARTICIPANT_NOT_CHECKED_IN"},iD={message:"Missing person details",code:"ERR_MISSING_PERSON_DETAILS"},Ia={message:"Existing participant drawPosition assignment",code:"ERR_EXISTING_PARTICIPANT_DRAW_POSITION_ASSIGNMENT"},bm={message:"Existing participant",code:"ERR_EXISTING_PARTICIPANT"},qg={message:"participantsCount exceeds drawSize",code:"ERR_INVALID_PARTICIPANT_COUNT"},$g={message:"Invalid entry status",code:"ERR_INVALID_ENTRY_STATUS"},VT={message:"Participant Entry Not Found",code:"ERR_NOT_FOUND_PARTICIPANT_ENTRY"},nw={message:"Participant not entered in stage",code:"ERR_UNCHANGED_PARTICIPANT_NOT_ENTERED"},ow={message:"Participant not found in stageSequence",code:"ERR_NOT_FOUND_PARTICIPANT_IN_STAGE"},sD={message:"entryStatus not allowed in stage",code:"ERR_INVALID_ENTRY_STATUS_IN_STAGE"},aD={message:"entryStatus not allowed for event",code:"ERR_INVALID_ENTRY_STATUS_IN_EVENT"},Kg={message:"No stage space available for entryStatus",code:"ERR_UNCHANGED_NO_AVAILABLE_STAGE_SPACE"},zg={message:"Insufficient drawPositions to accommodate qualifiers",code:"ERR_UNCHANGED_NO_DRAW_POSITIONS_FOR_QUALIFIERS"},Qg={message:"Insufficient drawPositions to accommodate entries",code:"ERR_INSUFFICIENT_DRAW_POSITIONS"},cD={message:"Missing penaltyType",code:"ERR_MISSING_PENALTY_TYPE"},uD={message:"Missing penaltyId",code:"ERR_MISSING_PENALTY_ID"},tp={message:"Penalty not found",code:"ERR_NOT_FOUND_PENALTY"},pD={message:"Missing courtsCount/courtNames",code:"ERR_MISSING_COURTS_INFO"},bo={message:"Court not found",code:"ERR_NOT_FOUND_COURT"},mD={message:"Court exists",code:"ERR_EXISTING_COURT"},BT={message:"Booking not found",code:"ERR_NOT_FOUND_BOOKING"},dD={message:"An active draft already exists for this draw",code:"ERR_EXISTING_DRAFT"},lD={message:"Existing matchUps conflict with booking",code:"ERR_EXISTING_MATCHUPS"},fD={message:"Venue exists",code:"ERR_EXISTING_VENUE"},Mi={message:"Venue not found",code:"ERR_NOT_FOUND_VENUE"},Os={message:"Missing venueId",code:"ERR_MISSING_VENUE_ID"},gD={message:"Invalid endTime",code:"ERR_INVALID_END_TIME"},ID={message:"Existing endTime",code:"ERR_EXISTING_END_TIME"},SD={message:"Invalid stopTime",code:"ERR_INVALID_STOP_TIME"},hD={message:"Invalid startTime",code:"ERR_INVALID_START_TIME"},iw={message:"Invalid resumeTime",code:"ERR_INVALID_RESUME_TIME"},Xg={message:"Invalid timeItem",code:"ERR_INVALID_TIME_ITEMS"},TD={message:"Missing async state provider",code:"ERR_MISSING_ASYNC_STATE_PROVIDER"},Jg={message:"Missing timeItem",code:"ERR_MISSING_TIME_ITEM"},Zg={message:"Missing timeItems",code:"ERR_MISSING_TIME_ITEMS"},ep={message:"Missing context",code:"ERR_MISSING_CONTEXT"},yD={message:"Missing schedule",code:"ERR_MISSING_SCHEDULE"},Yc={message:"Invalid scaleItem",code:"ERR_INVALID_SCALE_ITEM"},ED={message:"Modifications failed",code:"ERR_FAILURE_MODIFICATIONS"},Sa={message:"No modifications applied",code:"ERR_UNCHANGED_NO_MODIFICATIONS_APPLIED"},AD={message:"Unable to assign court",code:"ERR_UNCHANGED_COURT_NOT_ASSIGNED"},Cm={message:"No Candidates",code:"ERR_UNCHANGED_NO_CANDIDATES"},Jo={message:"Invalid configuration",code:"ERR_INVALID_CONFIG"},PD={message:"Invalid collectionDefinition",code:"ERR_INVALID_COLLECTION_DEFINITION"},So={message:"Invalid object",code:"ERR_INVALID_OBJECT"},Mm={message:"Invalid gender",code:"ERR_INVALID_GENDER"},rp={message:"Invalid category",code:"ERR_INVALID_CATEGORY"},O={message:"Invalid values",code:"ERR_INVALID_VALUES"},ND={message:"Duplicate value",code:"ERR_DUPLICATE_VALUE"},tI={message:"Team not found",code:"ERR_NOT_FOUND_TEAM"},UD={message:"No valid actions",code:"ERR_NO_VALID_ACTIONS"},jc={message:"No valid attributes",code:"ERR_NO_VALID_ATTRIBUTES"},eI={message:"Value unchanged",code:"ABORT_UNCHANGED"},fe={message:"Not found",code:"ERR_NOT_FOUND"},rI={message:"Not implemented",code:"ERR_NOT_IMPLEMENTED"},DD={message:"Existing flight",code:"ERR_EXISTING_FLIGHT"},nI={message:"Existing flight profile",code:"ERR_EXISTING_FLIGHT_PROFILE"},RD={message:"Existing outcome",code:"ERR_EXISTING_OUTCOME"},bD={message:"Existing matchUpId",code:"ERR_EXISTING_MATCHUP_ID"},HT={message:"Existing stage",code:"ERR_EXISTING_STAGE"},oI={message:"Existing structure",code:"ERR_EXISTING_STRUCTURE"},qc={message:"Method not found",code:"ERR_NOT_FOUND_METHOD"},CD={message:"Mutation blocked by active lock",code:"ERR_MUTATION_LOCKED"},MD={message:"Active mutation lock already exists for scope",code:"ERR_EXISTING_MUTATION_LOCK"},vD={message:"Mutation lock not found",code:"ERR_NOT_FOUND_MUTATION_LOCK"},OD={message:"Lock token does not match",code:"ERR_UNAUTHORIZED_LOCK_OPERATION"},_D={message:"Scheduled matchUps",code:"ERR_SCHEDULED_MATCHUPS"},$c={message:"Scores present",code:"ERR_SCORES_PRESENT"},sw={ANACHRONISM:OT,BOOKING_NOT_FOUND:BT,CANNOT_CHANGE_WINNING_SIDE:ol,CANNOT_MODIFY_TIEFORMAT:jg,CANNOT_MODIFY_PARTICIPANT_TYPE:QU,CANNOT_REMOVE_MAIN_STRUCTURE:IU,CANNOT_REMOVE_PARTICIPANTS:Rm,CATEGORY_MISMATCH:XU,COURT_EXISTS:mD,COURT_NOT_FOUND:bo,EXISTING_DRAFT:dD,EXISTING_MATCHUPS:lD,DRAW_DEFINITION_NOT_FOUND:Rr,DRAW_ID_EXISTS:AU,DRAW_POSITION_ACTIVE:Vc,DRAW_POSITION_ASSIGNED:kc,DRAW_POSITION_NOT_CLEARED:EU,DRAW_POSITION_NOT_FOUND:dH,DRAW_SIZE_MISMATCH:lH,DUPLICATE_ENTRY:tl,DUPLICATE_VALUE:ND,ENTRY_STATUS_NOT_ALLOWED_FOR_EVENT:aD,ENTRY_STATUS_NOT_ALLOWED_IN_STAGE:sD,EVENT_EXISTS:OU,EVENT_NOT_FOUND:Gr,EXISTING_DRAW_DEFINITIONS:SU,EXISTING_END_TIME:ID,EXISTING_FLIGHT:DD,EXISTING_MATCHUP_ID:bD,EXISTING_OUTCOME:RD,EXISTING_PARTICIPANT_DRAW_POSITION_ASSIGNMENT:Ia,EXISTING_PARTICIPANT:bm,EXISTING_POLICY_TYPE:kT,EXISTING_PROFILE:nI,EXISTING_ROUND:MU,EXISTING_STAGE:HT,EXISTING_STRUCTURE:oI,INCOMPATIBLE_MATCHUP_STATUS:Vg,INCOMPLETE_SOURCE_STRUCTURE:_g,INSUFFICIENT_DRAW_POSITIONS:Qg,INVALID_ACTION:DU,INVALID_ASSIGNMENT:xT,INVALID_BOOKINGS:rl,INVALID_CATEGORY:rp,INVALID_COLLECTION_DEFINITION:PD,INVALID_CONFIGURATION:Jo,INVALID_DATE_AVAILABILITY:Yg,INVALID_DATE:ae,INVALID_DRAW_DEFINITION:ma,INVALID_DRAW_POSITION_FOR_SEEDING:xg,INVALID_DRAW_POSITION:is,INVALID_DRAW_SIZE:Dm,INVALID_END_TIME:gD,INVALID_ENTRIES:xU,INVALID_EVENT_TYPE:Kn,INVALID_GAME_SCORES:GT,INVALID_GENDER:Mm,INVALID_MATCHUP_FORMAT:GU,INVALID_MATCHUP_STATUS:ec,INVALID_MATCHUP_STATUS_BYE:FU,INVALID_MATCHUP:cr,INVALID_OBJECT:So,INVALID_PARTICIPANT_ID:Vr,INVALID_PARTICIPANT_IDS:Mr,INVALID_PARTICIPANT_ROLE:JU,INVALID_PARTICIPANT_SEEDING:PU,INVALID_PARTICIPANT_TYPE:Nn,INVALID_PARTICIPANT:Ci,INVALID_POLICY_DEFINITION:WU,INVALID_RECORDS:_T,INVALID_SCALE_ITEM:Yc,INVALID_SEED_NUMBER:bU,INVALID_SEED_POSITION:CU,INVALID_SET_NUMBER:hH,INVALID_SIDE_NUMBER:YU,INVALID_SCORE:zU,INVALID_STAGE:tc,INVALID_START_TIME:hD,INVALID_STRUCTURE:Do,INVALID_STOP_TIME:SD,INVALID_TIE_FORMAT:Xo,INVALID_TIME:vs,INVALID_TIME_ITEM:Xg,INVALID_TOURNAMENT_DATES:KU,INVALID_TOURNAMENT_RECORD:Fc,INVALID_VALUES:O,INVALID_WINNING_SIDE:nl,LUCKY_DRAW_BYE_LIMIT:kU,MATCHUP_NOT_FOUND:Be,METHOD_NOT_FOUND:qc,MUTATION_LOCKED:CD,MUTATION_LOCK_EXISTS:MD,MUTATION_LOCK_NOT_FOUND:vD,MISSING_ASSIGNMENTS:kg,MISSING_ASYNC_STATE_PROVIDER:TD,MISSING_AVOIDANCE_POLICY:HU,MISSING_BIRTH_DATE:jU,MISSING_COLLECTION_DEFINITION:BU,MISSING_COURT_ID:Hg,MISSING_COURTS_INFO:pD,MISSING_DATE_AVAILABILITY:$U,MISSING_DATE:qU,MISSING_DRAW_DEFINITION:$,MISSING_DRAW_ID:Pn,MISSING_DRAW_POSITION:da,MISSING_DRAW_POSITIONS:Gc,MISSING_DRAW_SIZE:Bc,MISSING_ENTRIES:_U,MISSING_EVENT:le,MISSING_QUALIFIED_PARTICIPANTS:tD,MISSING_MATCHUP_FORMAT:VU,MISSING_MATCHUP_ID:mr,MISSING_MATCHUP_IDS:Ms,MISSING_MATCHUP:Xe,MISSING_MATCHUPS:Vn,MISSING_PARTICIPANT_COUNT:nD,MISSING_PARTICIPANT_ID:He,MISSING_PARTICIPANT_IDS:Ro,MISSING_PARTICIPANT_ROLE:ZU,MISSING_PARTICIPANT:ga,MISSING_PARTICIPANTS:Wc,MISSING_PENALTY_ID:uD,MISSING_PENALTY_TYPE:cD,MISSING_PERSON_DETAILS:iD,MISSING_POLICY_ATTRIBUTES:FT,MISSING_POLICY_DEFINITION:fa,MISSING_POLICY_TYPE:LT,MISSING_POSITION_ASSIGNMENTS:LU,MISSING_ROUND_NUMBER:fH,MISSING_SCHEDULE:yD,MISSING_SCORING_POLICY:SH,MISSING_SEED_ASSIGNMENTS:RU,MISSING_SEEDCOUNT_THRESHOLDS:UU,MISSING_SEEDING_POLICY:gH,MISSING_SET_NUMBER:TH,MISSING_SET_OBJECT:Bg,MISSING_SIDE_NUMBER:yH,MISSING_STAGE:Gg,MISSING_STRUCTURE_ID:dn,MISSING_STRUCTURE:bi,MISSING_MAIN_STRUCTURE:Fg,MISSING_STRUCTURES:Lg,MISSING_TARGET_LINK:wg,MISSING_TIE_FORMAT:la,MISSING_TIME_ITEM:Jg,MISSING_TIME_ITEMS:Zg,MISSING_TOURNAMENT_ID:Za,MISSING_TOURNAMENT_RECORD:j,MISSING_TOURNAMENT_RECORDS:kt,MISSING_VALUE:nt,MISSING_VENUE_ID:Os,MODIFICATIONS_FAILED:ED,NO_CANDIDATES:Cm,NO_DRAW_POSITIONS_AVAILABLE_FOR_QUALIFIERS:zg,NO_MODIFICATIONS_APPLIED:Sa,NO_STAGE_SPACE_AVAILABLE_FOR_ENTRY_STATUS:Kg,NO_PARTICIPANT_REMOVED:rD,NO_VALID_ACTIONS:UD,NO_VALID_ATTRIBUTES:jc,NO_VALID_DATES:Wg,NOT_FOUND:fe,NOT_IMPLEMENTED:rI,PARTICIPANT_COUNT_EXCEEDS_DRAW_SIZE:qg,PARTICIPANT_ID_EXISTS:eD,PARTICIPANT_NOT_CHECKED_IN:oD,PARTICIPANT_NOT_FOUND:ee,PARTICIPANT_PAIR_EXISTS:EH,PENALTY_NOT_FOUND:tp,POLICY_NOT_ATTACHED:IH,POLICY_NOT_FOUND:Xu,SCHEDULE_NOT_CLEARED:hU,SCHEDULE_CONFLICT_DOUBLE_BOOKING:TU,SCHEDULE_CONFLICT_COURT_UNAVAILABLE:yU,SCHEDULED_MATCHUPS:_D,SCORES_PRESENT:$c,SEEDSCOUNT_GREATER_THAN_DRAW_SIZE:NU,STAGE_SEQUENCE_LIMIT:wU,STRUCTURE_NOT_FOUND:Nt,TEAM_NOT_FOUND:tI,UNABLE_TO_ASSIGN_COURT:AD,UNAUTHORIZED_LOCK_OPERATION:OD,UNLINKED_STRUCTURES:vU,UNRECOGNIZED_DRAW_TYPE:Qu,UNRECOGNIZED_MATCHUP_FORMAT:Hc,UNRECOGNIZED_MATCHUP_STATUS:wT,VALUE_UNCHANGED:eI,VENUE_EXISTS:fD};var Qe={disableNotifications:!1,tournamentId:void 0,tournamentRecords:{},subscriptions:{},modified:!1,methods:{},notices:[]},xD={addNotice:_H,callListener:kH,cycleMutationStatus:OH,deleteNotice:LH,deleteNotices:wH,disableNotifications:AH,enableNotifications:PH,getMethods:vm,getNotices:xH,getTopics:FH,getTournamentId:aw,getTournamentRecord:NH,getTournamentRecords:UH,removeTournamentRecord:CH,setMethods:vH,setSubscriptions:MH,setTournamentId:RH,setTournamentRecord:DH,setTournamentRecords:bH,handleCaughtError:GH};function AH(){Qe.disableNotifications=!0}function PH(){Qe.disableNotifications=!1}function aw(){return Qe.tournamentId}function NH(t){return Qe.tournamentRecords[t]}function UH(){return Qe.tournamentRecords}function DH(t){let e=t?.tournamentId;return e?(Qe.tournamentRecords[e]=t,{success:!0}):{error:Fc}}function RH(t){return t?Qe.tournamentRecords[t]?(Qe.tournamentId=t,{success:!0}):{error:j}:(Qe.tournamentId=void 0,{success:!0})}function bH(t){Qe.tournamentRecords=t;let e=Object.keys(t);e.length===1?Qe.tournamentId=e[0]:e.length||(Qe.tournamentId=void 0)}function CH(t){if(typeof t!="string")return{error:O};if(!Qe.tournamentRecords[t])return{error:fe};delete Qe.tournamentRecords[t];let e=Object.keys(Qe.tournamentRecords);return e.length===1?Qe.tournamentId=e[0]:e.length||(Qe.tournamentId=void 0),{success:!0}}function MH(t){return t.subscriptions===null||Object.keys(t.subscriptions).length===0?(Qe.subscriptions={},{...P}):typeof t.subscriptions!="object"?{error:O}:(Object.keys(t.subscriptions).forEach(e=>{typeof t.subscriptions[e]=="function"?Qe.subscriptions[e]=t.subscriptions[e]:delete Qe.subscriptions[e]}),{...P})}function vH(t){return typeof t!="object"?{error:O}:(Object.keys(t).forEach(e=>{typeof t[e]=="function"&&(Qe.methods[e]=t[e])}),{...P})}function OH(){let t=Qe.modified;return Qe.modified=!1,t}function _H({topic:t,payload:e,key:r},n){if(!(typeof t!="string"||typeof e!="object")&&(Qe.disableNotifications||(Qe.modified=!0),!(Qe.disableNotifications||!Qe.subscriptions[t]&&!n)))return r&&(Qe.notices=Qe.notices.filter(o=>!(o.topic===t&&o.key===r))),Qe.notices.push({topic:t,payload:e,key:r}),{...P}}function vm(){return Qe.methods??{}}function xH({topic:t}){return Qe.notices.filter(e=>e.topic===t).map(e=>e.payload)}function wH(){Qe.notices=[]}function LH({topic:t,key:e}){Qe.notices=Qe.notices.filter(r=>(!t||r.topic===t)&&r.key!==e)}function FH(){return{topics:Object.keys(Qe.subscriptions)}}function kH({topic:t,notices:e},r){let n=Qe.subscriptions[t];n&&typeof n=="function"&&n(e);let o=r?.[t];o&&typeof o=="function"&&o(e)}function GH({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:aw(),params:JSON.stringify(r),engine:t,methodName:e,error:o}),{error:o}}var be={timers:{default:{elapsedTime:0}},globalSubscriptions:{},deepCopyAttributes:{stringify:[],ignore:[],toJSON:[]},globalMethods:[],deepCopy:!0},rn=xD,cw=["addNotice","callListener","cycleMutationStatus","deleteNotice","deleteNotices","disableNotifications","enableNotifications","getMethods","getNotices","getTopics","getTournamentId","getTournamentRecord","getTournamentRecords","removeTournamentRecord","setSubscriptions","setTournamentId","setTournamentRecord","setTournamentRecords"];function VH(t){if(typeof t!="object")throw new Error("Global state provider can not be undefined or null");if(Yt(Object.keys(t),cw).length!==cw.length)throw new Error("Global state provider is missing required methods");return rn=t,{success:!0}}function wD(){if(rn.createInstanceState){try{rn.createInstanceState()}catch(t){return{error:t}}return{success:!0}}else return{error:TD}}function je(t){return!t||typeof t!="object"?be.devContext??!1:typeof be.devContext!="object"?!1:Object.keys(t).every(e=>be.devContext?.[e]===t[e])&&be.devContext}function BH(t="reset",e="default"){let r=Date.now();if(t==="report"){if(e==="allTimers")return Object.keys(be.timers).filter(o=>o!=="default"||be.timers[o].startTime).map(o=>{let i=be.timers[o],s=i.state==="stopped"?0:(r-(i?.startTime??0))/1e3,a=i.elapsedTime+s;return{state:be.timers[o].state,elapsedTime:a.toFixed(2),timer:o}});{let n=be.timers[e].state==="stopped"?0:(r-(be.timers[e]?.startTime??0))/1e3,o=be.timers[e].elapsedTime+n;return{state:be.timers[e].state,elapsedTime:o.toFixed(2),timer:e}}}if(!be.timers[e]||t==="reset"){if(e==="allTimers")return be.timers={default:{elapsedTime:0}},!0;be.timers[e]={startTime:r,state:"active",elapsedTime:0}}return be.timers[e].elapsedTime||(be.timers[e].elapsedTime=0),t==="stop"&&be.timers[e].state!=="stopped"&&(be.timers[e].state="stopped")&&(be.timers[e].elapsedTime+=(r-(be.timers[e]?.startTime??0))/1e3),t==="start"&&(be.timers[e].startTime=r)&&(be.timers[e].state="active"),be.timers[e]}function uw(t){kr(t)?be.globalLog=t:delete be.globalLog}function np(t){be.devContext=t}function LD(){rn.disableNotifications()}function iI(){rn.enableNotifications()}function op(t,e){typeof t=="boolean"&&(be.deepCopy=t),typeof e=="object"&&(Array.isArray(e.ignore)&&(be.deepCopyAttributes.ignore=e.ignore),Array.isArray(e.toJSON)&&(be.deepCopyAttributes.toJSON=e.toJSON),Array.isArray(e.stringify)&&(be.deepCopyAttributes.stringify=e.stringify),e.threshold&&(be.deepCopyAttributes.threshold=e.threshold))}function sI(){return{enabled:be.deepCopy,...be.deepCopyAttributes}}function HH(t){return t?.subscriptions?(Object.keys(t.subscriptions).forEach(e=>{be.globalSubscriptions[e]=t.subscriptions[e]}),{...P}):{error:nt,info:"missing subscriptions"}}function WH(t){return t?.subscriptions?rn.setSubscriptions({subscriptions:t.subscriptions}):{error:nt,info:"missing subscriptions"}}function pw(t){return t?typeof t!="object"?{error:O}:(Object.keys(t).forEach(e=>{kr(t[e])&&(be.globalMethods[e]=t[e])}),{...P}):{error:nt,info:"missing method declarations"}}function mw(t){return t?typeof t!="object"?{error:O}:rn.setMethods(t):{error:nt,info:"missing method declarations"}}function aI(){return rn.cycleMutationStatus()}function at(t){if(typeof t?.topic!="string")return;let e=be.globalSubscriptions[t.topic];return rn.addNotice(t,e)}function cI(){return{...be.globalMethods,...rn.getMethods()}}function WT(t){return rn.getNotices(t)}function YT({key:t,topic:e}){return rn.deleteNotice({key:t,topic:e})}function ss(){return rn.deleteNotices()}function br(){return rn.getTopics()}function Kc(t){return br()?.topics?.includes(t)}async function il(t){return rn.callListener(t,be.globalSubscriptions)}function _s(){return rn.getTournamentId()}function uI(t){return rn.getTournamentRecord(t)}function Zo(){return rn.getTournamentRecords()}function FD(t){return rn.setTournamentRecord(t)}function sl(t){return rn.setTournamentRecords(t)}function Om(t){return rn.setTournamentId(t)}function kD(t){return rn.removeTournamentRecord(t)}function jT(){return rn}function _m({engineName:t,methodName:e,params:r,err:n}){let o=kr(rn.handleCaughtError)&&rn.handleCaughtError||xD.handleCaughtError,{tournamentRecord:i,...s}=r;return o({params:s,engineName:t,methodName:e,err:n})}function GD(t,e){if(be.globalLog)try{be.globalLog({log:t,engine:e})}catch(r){console.log("globalLog error",r),console.log(e,t),uw()}else console.log(e,t)}function VD(t,e,r,n){if(!Tt(t))return{error:O};Le||(r=1);let o=Array.isArray(e)?e:[],i={},s=(a,c=0)=>{Object.keys(a).forEach(u=>{kr(a[u])?i[u]=a[u]:Tt(a[u])&&(e===!0||o?.includes(u))&&(r===void 0||c<r)&&s(a[u],c+1)})};return s(t),n?pw(i):mw(i),{methods:i}}function YH(t,e,r){return Object.keys(t).filter(n=>!e.includes(t[n])&&(!r||(Array.isArray(t[n])?t[n].length:!0)))}function et(t,e,r,n){if(typeof t!="object"||t===null)return t;sI()?.enabled||(n=!0);let i=["",void 0,null];e&&i.push(!1);let s=YH(t,i,r);return Object.assign({},...s.map(a=>Array.isArray(t[a])?{[a]:n?t[a]:t[a].map(c=>et(c))}:{[a]:n?t[a]:et(t[a])}))}function M({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&&(e.context??={},Object.assign(e.context,et(t))),e&&!e?.error&&!e?.success&&Object.assign(e,{...P}),e??{success:!0}}var Je="FEMALE",ti="OTHER",as="MIXED",Ce="MALE";var al={FEMALE_ABBR:"F",OTHER_ABBR:"O",MIXED_ABBR:"X",MALE_ABBR:"M",ANY_ABBR:"A",FEMALE:Je,MIXED:as,OTHER:ti,MALE:Ce,ANY:"ANY"};function cs(t){return[Je,"F"].includes(t)}function ha(t){return[Ce,"M"].includes(t)}function nn(t){return[as,"X"].includes(t)}function Co(t){return["ANY","A"].includes(t)}function yr(t){if(t){if(cs(t))return Je;if(nn(t))return as;if(ha(t))return Ce;if(Co(t))return"ANY"}return ti}function Un(t){return cs(t)||ha(t)}var zH="MIXED events can not contain mixed singles or { gender: ANY } collections",QH="events with { gender: ANY } can not contain MIXED singles collections";function cl(t){let e="tieFormatGenderValidityCheck",{referenceGender:r,matchUpType:n,gender:o}=t;return r&&o&&Un(r)&&yr(r)!==yr(o)?M({result:{valid:!1,error:Mm},context:{gender:o},stack:e}):nn(r)&&(Co(o)||nn(o)&&n!==Rt)?M({result:{error:Mm,valid:!1},info:zH,stack:e}):Co(r)&&nn(o)&&n!==Rt?M({result:{error:Mm,valid:!1},info:QH,stack:e}):{valid:!0}}var XH="normal",BD="timed",JH="final",pI="NOAD";var HD=["SET","HAL","QTR","PER","INN","RND","FRM","MAP","MAT"],qT="CONSECUTIVE",$T="TRADITIONAL",ZH="game",tW="matchUp",lw={S:XH,F:JH,G:ZH,M:tW};function ip(t,e){if(Tt(t)&&(t?.bestOf||t?.exactly)&&t?.setFormat)return rW(t,e)}function mI(t){return!Number.isNaN(Number(t))&&Number(t)}function Iw(t){let e=`T${t.minutes}`;return t.based==="P"&&(e+="P"),t.tiebreakFormat?.tiebreakTo&&(e+=`/TB${t.tiebreakFormat.tiebreakTo}`),t.modifier&&(e+=`@${t.modifier}`),e}function eW(t){let e=t?.deuceAfter?`${t.deuceAfter}D`:"";if(t?.type===$T)return`TN${e}`;if(t?.type===qT&&Number.isInteger(t.count))return`${t.count}C${e}`}function rW(t,e){let r=mI(t.bestOf)||void 0,n=mI(t.exactly)||void 0,o=r||n;if(t.setFormat?.timed&&t.simplified&&o===1)return Iw(t.setFormat);let i=t.matchRoot||"SET",s=n&&n!==1?"X":"",a=t.aggregate?"A":"",c=o&&`${i}${o}${s}${a}`||"",u=fw(t.setFormat,e),p=u&&`S:${u}`||"",m=fw(t.finalSetFormat,e),d=o&&o>1&&m&&u!==m&&`F:${m}`||"",l=t.gameFormat?`G:${eW(t.gameFormat)}`:"",f=t.matchUpConstraint?.timed?`M:T${t.matchUpConstraint.minutes}`:"";if(c&&u)return[c,p,l,d,f].filter(Boolean).join("-")}function fw(t,e){if(typeof t=="object"&&Object.keys(t).length){if(t.timed)return Iw(t);if(t.outs)return`O${t.outs}`;if(t.tiebreakSet)return gw(t.tiebreakSet);let r=mI(t.setTo);if(r){let n=t.NoAD&&pI||"",o=gw(t.tiebreakFormat),i=o&&`/${o}`||"",s=mI(t.tiebreakAt),a=s&&(s!==r||e)&&`@${s}`||"";if(o!==!1)return`${r}${n}${i}${a}`}}}function gw(t){if(t){if(typeof t=="object"&&!t.tiebreakTo)return"";if(typeof t=="object"&&mI(t.tiebreakTo)){let e=`TB${t.tiebreakTo}${t.NoAD?pI:""}`;return t.modifier&&(e+=`@${t.modifier}`),e}else return!1}}function oe(t){if(_t(t)){let e=t.startsWith("T")&&BD||HD.some(r=>t.startsWith(r))&&"SET"||"";if(e===BD){let r=yw(t),n={simplified:!0,setFormat:r,bestOf:1};if(r)return n}if(e==="SET")return iW(t)}}function nW(t){let e=HD.find(u=>t.startsWith(u));if(!e)return;let r=t.slice(e.length),n=/^(\d+)([A-Z]*)$/.exec(r);if(!n)return;let o=xm(n[1]);if(!o)return;let i=n[2],s=!1,a=!1,c=[];for(let u of i)u==="X"?s=!0:u==="A"?a=!0:c.push(u);return{matchRoot:e,count:o,exactly:s,aggregate:a,matchMods:c}}function oW(t){let e=/^(.+?)(\d+D)$/.exec(t),r=e?e[1]:t,n=e?Number(e[2].slice(0,-1)):void 0;if(n!==void 0&&(n<1||!Number.isInteger(n)))return;if(r==="TN"){let i={type:$T};return n&&(i.deuceAfter=n),i}let o=/^([1-9]\d*)C$/.exec(r);if(o){let i={type:qT,count:Number(o[1])};return n&&(i.deuceAfter=n),i}}function iW(t){let e=t.split("-"),r=nW(e[0]);if(!r)return;let{matchRoot:n,count:o,exactly:i,aggregate:s,matchMods:a}=r,c=i&&o!==1?void 0:o,u=i&&o!==1?o:void 0,p,m,d,l,h={setFormat:p,finalSetFormat:m,gameFormat:d,matchUpConstraint:l,sCount:0,fCount:0,gCount:0,mCount:0};for(let T=1;T<e.length;T++)if(!sW(e[T],h))return;return{setFormat:p,finalSetFormat:m,gameFormat:d,matchUpConstraint:l}=h,aW({setFormat:p,finalSetFormat:m,gameFormat:d,matchUpConstraint:l,matchRoot:n,aggregate:s,matchMods:a,bestOf:c,exactly:u})}function sW(t,e){let r=t.indexOf(":");if(r<0)return!1;let n=t.slice(0,r),o=t.slice(r+1);if(!(n in lw))return!1;if(n==="S"){if(e.sCount++,e.sCount>1)return!1;e.setFormat=Sw(t,o)}else if(n==="F"){if(e.fCount++,e.fCount>1)return!1;e.finalSetFormat=Sw(t,o)}else if(n==="G"){if(e.gCount++,e.gCount>1||(e.gameFormat=oW(o),!e.gameFormat))return!1}else if(n==="M"&&(e.mCount++,e.mCount>1||(e.matchUpConstraint=lW(o),!e.matchUpConstraint)))return!1;return!0}function aW({setFormat:t,finalSetFormat:e,gameFormat:r,matchUpConstraint:n,matchRoot:o,aggregate:i,matchMods:s,bestOf:a,exactly:c}){let u=t&&t.timed||e&&e.timed;if(o==="SET"&&!(a&&a<6||u&&c)||!t||!(!e||e))return;let d=et({setFormat:t,exactly:c,bestOf:a});return o!=="SET"&&(d.matchRoot=o),i&&(d.aggregate=!0),s.length>0&&(d.matchMods=s),e&&(d.finalSetFormat=e),r&&(d.gameFormat=r),n&&(d.matchUpConstraint=n),d}function Sw(t,e){return e.startsWith("TB")?cW(e):e.startsWith("O")?uW(e):e.startsWith("T")?yw(e):pW(t,e)}function cW(t){let e=Tw(t);return e===!1?!1:typeof e=="object"?{tiebreakSet:e}:void 0}function uW(t){let e=/^O([1-9]\d*)$/.exec(t);if(e)return{outs:Number(e[1])}}function pW(t,e){let r=/^[FS]:(\d+)([A-Za-z]*)/.exec(t),n=r&&Ew(r[2])||!1,o=!r?.[2]||n,i=r?xm(r[1]):void 0,s=hw(e),a=s!==!1,c=a&&s||i,u=Tw(e.split("/")[1]);return!i||!o||!(u!==!1)||!a?!1:mW(i,n,u,c)}function mW(t,e,r,n){let o={setTo:t};return e&&(o.NoAD=!0),r?(o.tiebreakFormat=r,o.tiebreakAt=n):o.noTiebreak=!0,o}function hw(t,e=!0){let r=t?.indexOf("@")>0&&t.split("@");if(r)return(e?xm(r[1]):r[1])||!1}function Tw(t){if(t)return t.startsWith("TB")?dW(t):!1}function dW(t){let e=hw(t,!1),r=/^TB(\d+)([A-Za-z]*)/.exec(t),n=r?.[1],o=r&&Ew(r[2]),i=!r?.[2]||o,s=xm(n);if(!s||!i)return!1;let a={tiebreakTo:s};return e&&typeof e=="string"&&!yt(e)&&(a.modifier=e),o&&(a.NoAD=!0),a}function yw(t){let e=t.slice(1),r=/^(\d+)([PG])?(?:\/TB(\d+))?(@[A-Za-z]+)?$/.exec(e),n=xm(r?.[1]);if(!n)return;let o={timed:!0,minutes:n},i=r?.[2];i==="P"?o.based="P":i==="G"&&(o.based="G");let s=r?.[3];if(s){let u=xm(s);u&&(o.tiebreakFormat={tiebreakTo:u})}let a=r?.[4],c=[void 0,"P","G",""].includes(a);if(a&&!c){let u=/^(\d+)([PGA])?(?:\/TB\d+)?(@)([A-Za-z]+)$/.exec(e)?.[4];return u?(o.modifier=u,o):void 0}return a&&(o.based=a),o}function lW(t){let e=/^T(\d+)$/.exec(t);if(!e)return;let r=xm(e[1]);if(r)return{timed:!0,minutes:r}}function Ew(t){return t?.includes(pI)}function xm(t){let e=Number(t);return Number.isNaN(e)?0:e}function fW(t){return t.replaceAll(/T(\d+)G(?=\/TB|@|-|$)/g,"T$1")}function vr({matchUpFormat:t}){if(!_t(t)||t==="")return!1;let e=oe(t),r=/-S:(\d+)\/TB(\d{1,2})@?(\d?)/.exec(t),n=r?.[1],o=r?.[2],i=r?.[3],s=/-F:(\d+)\/TB(\d{1,2})@?(\d?)/.exec(t),a=s?.[1],c=s?.[2],u=s?.[3];return ip(e,!!(r&&o&&n===i||s&&c&&a===u))===fW(t)}var wm=/^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2]\d|3[0-1])$/,KT=/^((0\d|1\d|2[0-3]):[0-5]\d(:[0-5]\d)?)([.,]\d{3})?$/,Mo=/^(\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2]\d|3[0-1]))([ T](0\d|1\d|2[0-3]):[0-5]\d(:[0-5]\d)?)?([.,]\d{3})?Z?$/,Qc=/^(\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 pl(t){let{scheduledDate:e}=t;if(!e&&t.scheduledTime&&(e=mt(t.scheduledTime)),!e)return;let r=$t(t.scheduledTime),n=mt(e);return n&&r&&(n+=`T${r}`),n}function Aw(t){return typeof t!="object"||Array.isArray(t)?!1:Object.prototype.toString.call(t)==="[object Date]"}function Lm(t){let e=typeof t=="string"?t?.split(" "):[];if(t&&e?.length>1&&!["AM","PM"].includes(e[1].toUpperCase()))return!1;let r=sp(t,!0,!0);return!!(!t||r&&Qc.test(r))}function Me(t){return us(t)||wm.test(t)}function gW(t){let e=new Date(t),r=e.getSeconds()+60*e.getMinutes()+3600*e.getHours();return IW(r,{displaySeconds:!1})}function IW(t,e){let r=Number.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(ao).join(":")}var fI=t=>{let e=dI(t)||us(t)?new Date(t):new Date,r=e.getUTCMonth()+1,n=r<10?`0${r}`:`${r}`;return`${e.getUTCFullYear()}-${ao(n)}-${ao(e.getUTCDate())}`};function SW(t){let e=dI(t)||us(t)?new Date(t):new Date;return Date.UTC(e.getFullYear(),e.getMonth(),e.getDate())}function zn(t,e="-",r="YMD"){if(!t)return"";typeof t=="string"&&!t.includes("T")&&(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 zT(t){let e=t?new Date(t):new Date,r=e.getTimezoneOffset();return new Date(e.getTime()-r*60*1e3)}function hW(t){return zT(t).getTime()}function dI(t){if(typeof t=="boolean")return!1;let e=t instanceof Date&&t||!Number.isNaN(Number(t))&&new Date(t)||!1;return e&&!Number.isNaN(Number(e.valueOf()))}function TW(t,e){return t<=e}function Ta(t,e){if(!Me(t)||!Me(e))return[];let r=mt(t)+"T00:00",n=mt(e)+"T00:00",o=new Date(r),i=new Date(n),s=dI(i)&&dI(o)&&TW(o,i),a=[],c=0;if(s){let u=o,p=u.getTime();for(;p<=i.getTime()&&c<300;)c+=1,a.push(new Date(u)),p=u.setDate(u.getDate()+1)}return a.map(u=>zn(u))}var yW=/^([+-]?\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 us(t){return typeof t!="string"?!1:yW.test(t)}function ya(t){return typeof t!="string"||!us(t)?!1:/([zZ]|[+-]\d{2}:?\d{2})$/.test(t)}function XT(t){if(typeof t!="string")return!1;let r=t.split("Z")[0].split(":"),n=r.every(i=>!Number.isNaN(Number.parseInt(i)));return!(r.length<2||!n||Number.parseInt(r[0])>23||Number.parseInt(r[1])>60)}function jt(t){let e=$t(t);if(!e)return 0;let[r,n]=e.split(":").map(o=>Number.parseInt(o));return r*60+n}function Pw(t){let e=Math.floor(t/60),r=t-e*60;return e>23&&(e=e%24),[ao(e),ao(r)].join(":")}function lI(t){return XT(t)?t.split(":").slice(0,2).map(ao).join(":"):void 0}function $t(t){return us(t)&&t.indexOf("T")>0?lI(t.split("T").reverse()[0]):lI(t)}function mt(t){return us(t)||Mo.test(t)?t.split("T")[0]:""}function Fm(t,e){let r=new Date(t);return r.setUTCDate(r.getUTCDate()+e),mt(r.toISOString())}function QT(t){t=typeof t=="string"?t:"00:00";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,Number.isNaN(Number.parseInt(r.hours))||Number.isNaN(Number.parseInt(r.minutes))||r.ampm&&!["AM","PM"].includes(r.ampm.toUpperCase())?{}:r}function EW(t){let e=QT(t);return e.ampm&&e.hours&&(e.ampm.toLowerCase()==="pm"&&Number.parseInt(e.hours)<12&&(e.hours=(e.hours&&Number.parseInt(e.hours)||0)+12),e.ampm.toLowerCase()==="am"&&e.hours==="12"&&(e.hours="00")),`${e.hours||"12"}:${e.minutes||"00"}`.split(":").map(ao).join(":")}function AW(t){let e=QT(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 sp(t,e,r){let n=mt(t),o=$t(t),i=n?o:t;return t?e&&(n&&r&&t||EW(i))||AW(i):void 0}function JT(t,e){let r=QT(t),n=QT(e);if(Number.parseInt(r.hours)<Number.parseInt(n.hours))return-1;if(Number.parseInt(r.hours)>Number.parseInt(n.hours))return 1;if(r.hours===n.hours){if(Number.parseInt(r.minutes)<Number.parseInt(n.minutes))return-1;if(Number.parseInt(r.minutes)>Number.parseInt(n.minutes))return 1}return 0}function ZT(t,e=7){let r=mt(t)+"T00:00",n=new Date(r),o=new Date(n.setDate(n.getDate()+e));return zn(o)}function PW(t){return ZT(t)}function NW(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())),zn(o,r)}function Nw(t,e,r){let n=new Date(t,0);return zn(new Date(n.setDate(e)),r)}function ve(t,e=void 0){let[r,n]=(t||"00:00").split(":").map(ao),o=zT(e).setHours(r,n,0,0);return zT(o)}function xs(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=Number.isNaN(e)?0:e;return $t(gI(ve(r),n).toISOString())||"00:00"}function gI(t,e){let r=new Date(t);return new Date(r.getTime()+e*6e4)}function ao(t){return t.toString()[1]?t:"0"+t}function Qn(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 ty={addDays:ZT,addWeek:PW,addMinutesToTimeString:Br,convertTime:sp,getIsoDateString:pl,getUTCdateString:fI,DateHHMM:gW,extractDate:mt,extractTime:$t,formatDate:zn,getDateByWeek:NW,isISODateString:us,isValidEmbargoDate:ya,isDate:dI,isTimeString:XT,offsetDate:zT,offsetTime:hW,sameDay:Qn,timeStringMinutes:jt,timeToDate:ve,timeUTC:SW,validTimeValue:Lm,validDateString:wm,timeValidation:Qc,dateValidation:Mo};var UW=(t,e)=>t.filter(Boolean).every(r=>typeof r===e),DW=t=>t.filter(Boolean).every(Le);function ml(t,e){return`${t}-${e}`}function ps(t){let e=t.category;if(typeof e!="object"||!e)return{error:rp};let{ageCategoryCode:r,ageMaxDate:n,ageMinDate:o,ageMax:i,ageMin:s}=e,a=e.categoryName,c;if(!(UW([r,n,o,a],"string")&&DW([i,s])&&[n,o].filter(Boolean).every(Me)))return{error:rp};let p=t.consideredDate??mt(new Date().toLocaleDateString("sv"));if(!p||!Me(p))return{error:ae};let[m]=p.split("-").slice(0,3).map(B=>Number.parseInt(B)),d=Fm(p,-1);if(!d)return{error:ae};let[l,f]=d.split("-").slice(1,3).map(B=>Number.parseInt(B)),g=`${ao(l)}-${ao(f)}`,I=Fm(p,1);if(!I)return{error:ae};let[S,h]=I.split("-").slice(1,3).map(B=>Number.parseInt(B)),T=`${ao(S)}-${ao(h)}`,y=s&&Fm(p,-1*365*s),E=i&&Fm(p,-1*365*i),A=[],N=B=>!A.includes(B)&&A.push(B);r=r??a;let U=/^([UO]?)(\d{1,2})([UO]?)$/,R=/^C(\d{1,2})-(\d{1,2})$/,D=r?.includes("-"),b=D&&r?.match(R),C=r?.match(U);function _(B){let z=m-B,W=ml(z,T);e.ageMinDate&&e.ageMinDate!==W&&N(`Invalid submitted ageMinDate: ${o}`),o=W,r&&(e.ageMax&&e.ageMax!==B-1&&(N(`Invalid submitted ageMax: ${i}`),E=void 0),i=B-1)}function v(B){let z=m-B-1,W=ml(z,T);e.ageMin&&e.ageMin>B&&N(`Invalid submitted ageMin: ${s}`),e.ageMax&&e.ageMax>B&&N(`Invalid submitted ageMax: ${i}`),e.ageMinDate&&e.ageMinDate!==W&&N(`Invalid submitted ageMinDate: ${o}`),o=W,r&&(e.ageMax&&e.ageMax!==B&&(N(`Invalid submitted ageMax: ${i}`),y=void 0),i=B)}function w(B){let z=m-B,W=ml(z,g);e.ageMaxDate&&e.ageMaxDate!==W&&N(`Invalid submitted ageMaxDate: ${n}`),n=W,r&&(e.ageMin&&e.ageMin!==B+1&&(N(`Invalid submitted ageMin: ${s}`),y=void 0),s=B+1)}function L(B){let z=m-B-1,W=ml(z,g);e.ageMaxDate&&e.ageMaxDate!==W&&N(`Invalid submitted ageMaxDate: ${n}`),n=W,r&&(e.ageMin&&e.ageMin!==B&&(N(`Invalid submitted ageMin: ${s}`),y=void 0),s=B)}function F(B){let z=U.exec(B)??[],[W,K,Y]=z.slice(1),J=Number.parseInt(K);W==="U"?(e.ageMaxDate&&e.ageMaxDate!==n&&N(`Invalid submitted ageMaxDate: ${e.ageMaxDate}`),_(J)):W==="O"&&w(J),Y==="U"?(e.ageMaxDate&&e.ageMaxDate!==n&&N(`Invalid submitted ageMaxDate: ${e.ageMaxDate}`),v(J)):Y==="O"&&L(J),n=(n??y)||void 0,o=(o??E)||void 0}function x(){if(n=void 0,o=void 0,i=void 0,s=void 0,e.ageMin){let W=m-e.ageMin;n=ml(W,g)}if(e.ageMax){let W=m-e.ageMax-1;o=ml(W,T)}let[B,z]=(r?.match(R)??[]).slice(1).map(W=>Number.parseInt(W));B<=z?(s=B,i=z,c=!0):N(`Invalid combined age range ${r}`)}function k(){s&&w(s),i&&v(i)}function G(){b?x():D?r?.split("-").forEach(F):C&&r?F(r):k()}G(),i&&e?.ageMin&&e?.ageMin>i&&(N(`Invalid submitted ageMin: ${e?.ageMin}`),s=void 0);let V=et({consideredDate:p,combinedAge:c,ageMaxDate:n,ageMinDate:o,ageMax:i,ageMin:s});return A.length&&(V.errors=A),V}function ap({category:t}){if(!Tt(t))return{error:O};let e=ps({category:t});if(e.error)return{error:e};let{ratingMax:r,ratingMin:n}=t;return r&&!Le(r)?M({result:{error:O},context:{ratingMax:r}}):n&&!Le(n)?M({result:{error:O},context:{ratingMin:n}}):{...e}}function cp({childCategory:t,withDetails:e,category:r}){let n=ap({category:r}),o=ap({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=et({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 up({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}`),M({result:{errors:c,error:So},stack:a});let{collectionValueProfiles:u,collectionGroupNumber:p,collectionValue:m,collectionId:d,matchUpCount:l,matchUpFormat:f,matchUpValue:g,matchUpType:I,scoreValue:S,setValue:h,category:T,gender:y}=e;if(r&&typeof d!="string"&&c.push(`collectionId is not type string: ${d}`),typeof l!="number"&&c.push(`matchUpCount is not type number: ${l}`),I&&!Cs([Ct,Rt,Um],I)&&c.push(`matchUpType must be SINGLES, DOUBLES, or HYBRID: ${I}`),[!!u?.length].concat([g,m,S,h].map(yt)).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 A=vT({collectionValueProfiles:u,matchUpCount:l});A.errors&&c.push(...A.errors)}if(p&&typeof p!="number"&&c.push(`collectionGroupNumber is not type number: ${m}`),f&&!vr({matchUpFormat:f})&&c.push(`Invalid matchUpFormat: ${f}`),n){let A=cl({referenceGender:i,matchUpType:I,gender:y});if(A.error)return M({context:{referenceGender:i,gender:y},result:A,stack:a})}if(t&&o&&T){let A=cp({category:o,childCategory:T});if(!A.valid)return M({result:{error:rp},context:A,stack:a})}return c.length?M({result:{errors:c,error:PD},stack:a}):{valid:!0}}function or(t){let e=!!(t?.enforceCategory!==!1&&t?.category),r=!!(t?.enforceGender!==!1&&t?.gender),n=t?.checkCollectionIds,o=t?.tieFormat,i=t?.event,s="validateTieFormat",a=[],c=RW({...t,stack:s});if(c?.error)return c;let u,p=o.collectionDefinitions.every(I=>{let{setValue:S,scoreValue:h,collectionValue:T}=I;(S||h)&&!T&&(u=!0);let{valid:y,errors:E}=up({referenceCategory:t.category,referenceGender:t.gender,collectionDefinition:I,checkCollectionIds:n,checkCategory:e,checkGender:r,event:i});return y?!0:(Array.isArray(E)&&a.push(...E),!1)}),m=typeof o.winCriteria?.valueGoal=="number"&&o.winCriteria?.valueGoal>0&&!u||o.winCriteria?.aggregateValue;if(!(m||o.winCriteria?.aggregateValue))return u?a.push("aggregateValue is required"):a.push("Either non-zero valueGoal, or { aggregateValue: true } must be specified in winCriteria"),M({context:{tieFormat:o,errors:a,aggregateValueImperative:u},result:{error:Xo},stack:s});let d=o.collectionDefinitions.map(({collectionId:I})=>I),l=!n||d.length===pt(d).length,f=p&&m&&l,g={valid:f,errors:a};return f?g:M({result:{error:Xo},context:{tieFormat:o,errors:a},stack:s})}function RW(t){let{tieFormat:e,stack:r}=t;return!t||!e||!Tt(e)?M({result:{error:Xo},context:{tieFormat:e,message:"tieformat must be an object"},stack:r}):Tt(e.winCriteria)?Array.isArray(e.collectionDefinitions)?{...P}:M({result:{error:Xo},context:{tieFormat:e,message:"collectionDefinitions must be an array"},stack:r}):M({result:{error:Xo},context:{tieFormat:e,message:"tieformat.winCritiera must be an object"},stack:r})}var dl="resourceSubType",ll="resourceType",Xc="identifier",ey="name",Uw={RESOURCE_SUB_TYPE:dl,RESOURCE_TYPE:ll,IDENTIFIER:Xc,NAME:ey};function q(t,e,r,n,o=0){if(jT().makeDeepCopy)return jT().makeDeepCopy(t,e,r,n);let i=sI(),{stringify:s,toJSON:a,ignore:c,modulate:u}=i??{};if(!i?.enabled&&!r||typeof t!="object"||kr(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)||kr(c)&&!c(l)),d=(l,f)=>{p[l]=kr(f?.toString)?f.toString():JSON.stringify(f)};for(let l of m){let f=t[l],g=kr(u)?u(f):void 0;if(g!==void 0)p[l]=g;else if(e&&l==="extensions"&&Array.isArray(f)){let I=II(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)&&kr(f?.toJSON)?p[l]=f.toJSON():f===null?p[l]=void 0:Aw(f)?p[l]=new Date(f).toISOString():p[l]=q(f,e,r,n,o+1)}return p}function II(t){return t?.map(e=>{let{name:r,value:n}=e;return r&&n&&{[`_${r}`]:n}}).filter(Boolean)}function ry(t=1,e,r){return Q(0,t).map(()=>it(e,r))}function it(t,e){let r=e??Math.random,n=[];for(let u=0;u<256;u++)n[u]=(u<16?"0":"")+u.toString(16);let o=Math.trunc(r()*4294967295),i=Math.trunc(r()*4294967295),s=Math.trunc(r()*4294967295),a=Math.trunc(r()*4294967295),c=n[o&255]+n[o>>8&255]+n[o>>16&255]+n[o>>24&255]+"-"+n[i&255]+n[i>>8&255]+"-"+n[i>>16&15|64]+n[i>>24&255]+"-"+n[s&63|128]+n[s>>8&255]+"-"+n[s>>16&255]+n[s>>24&255]+n[a&255]+n[a>>8&255]+n[a>>16&255]+n[a>>24&255];return typeof t=="string"?`${t}_${c.replaceAll("-","")}`:c}var ny={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 oy={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 iy={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 sy={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 ay={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 cy={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 uy={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:"Brewer Cup",winCriteria:{valueGoal:4}};var py={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 _n="SET3-S:6/TB7",LW="SET3-S:6NOAD",WD="SET3-S:6NOAD/TB7-F:TB10",FW="SET3-S:4/TB7",kW="SET3-S:4/TB5@3",GW="SET5-S:6/TB7",VW="SET1-S:6/TB7",BW="SET1-S:TB10",HW="SET3-S:6/TB7-F:TB7",WW="SET1-S:T20",YW="SET1-S:8/TB7",jW="SET1-S:8/TB7@7",Dw={FORMAT_STANDARD:_n,FORMAT_STANDARD_NOAD:LW,FORMAT_ATP_DOUBLES:WD,FORMAT_SHORT_SETS:FW,FORMAT_FAST4:kW,FORMAT_GRAND_SLAM:GW,FORMAT_ONE_SET:VW,FORMAT_MATCH_TIEBREAK:BW,FORMAT_SET3_TB7:HW,FORMAT_PRO_SET:YW,FORMAT_COLLEGE_PRO_SET:jW,TIMED20:WW};var my={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 dy={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 Collegiate",winCriteria:{valueGoal:4}};var ly={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 fy={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:"World Team Tennis ITT",winCriteria:{aggregateValue:!0}};var Rw={tieFormatName:"INTENNSE 2026",winCriteria:{aggregateValue:!0},collectionDefinitions:[{collectionId:"intennse-ms",collectionName:"Men's Singles",matchUpType:"SINGLES",matchUpCount:2,matchUpFormat:"SET2XA-S:T10",scoreValue:1,gender:"MALE",category:{categoryName:"MS"}},{collectionId:"intennse-ws",collectionName:"Women's Singles",matchUpType:"SINGLES",matchUpCount:2,matchUpFormat:"SET2XA-S:T10",scoreValue:1,gender:"FEMALE",category:{categoryName:"WS"}},{collectionId:"intennse-md",collectionName:"Men's Doubles",matchUpType:"DOUBLES",matchUpCount:1,matchUpFormat:"SET1A-S:T10",scoreValue:1,gender:"MALE",category:{categoryName:"MD"}},{collectionId:"intennse-wd",collectionName:"Women's Doubles",matchUpType:"DOUBLES",matchUpCount:1,matchUpFormat:"SET1A-S:T10",scoreValue:1,gender:"FEMALE",category:{categoryName:"WD"}},{collectionId:"intennse-xd",collectionName:"Mixed Doubles",matchUpType:"DOUBLES",matchUpCount:1,matchUpFormat:"SET1A-S:T10",scoreValue:1,gender:"MIXED",category:{categoryName:"XD"}}]};var gy={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 Iy={collectionDefinitions:[{collectionGroupNumber:1,matchUpType:"DOUBLES",matchUpCount:1,matchUpFormat:"SET3-S:6NOAD/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:6NOAD/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:6NOAD/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 Sy={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 Tennis on Campus",winCriteria:{aggregateValue:!0}};var SI="COLLEGE_DEFAULT",YD="COLLEGE_JUCO",jD="COLLEGE_D3",qD="DOMINANT_DUO",$D="DOMINANT_DUO_MIXED",KD="INTENNSE_2026",zD="LAVER_CUP",QD="TEAM_DOUBLES_3_AGGREGATION",XD="USTA_BREWER_CUP",JD="USTA_OZAKI_CUP",ZD="USTA_COLLEGE",tR="USTA_GOLD_TEAM_CHALLENGE",eR="USTA_LEVEL_1",rR="USTA_INTERSECTIONAL",nR="USTA_SECTION_BATTLE",oR="USTA_SOUTHERN_LEVEL_5",iR="USTA_TOC",sR="USTA_WTT_ITT",aR="USTA_ZONAL",bw={COLLEGE_D3:jD,COLLEGE_DEFAULT:SI,COLLEGE_JUCO:YD,DOMINANT_DUO:qD,DOMINANT_DUO_MIXED:$D,INTENNSE_2026:KD,LAVER_CUP:zD,TEAM_DOUBLES_3_AGGREGATION:QD,USTA_BREWER_CUP:XD,USTA_OZAKI_CUP:JD,USTA_COLLEGE:ZD,USTA_GOLD_TEAM_CHALLENGE:tR,USTA_INTERSECTIONAL:rR,USTA_LEVEL_1:eR,USTA_SECTION_BATTLE:nR,USTA_SOUTHERN_LEVEL_5:oR,USTA_TOC:iR,USTA_WTT_ITT:sR,USTA_ZONAL:aR};var Mw="STANDARD",Cw={[Mw]:{hydrate:!0,doubles:{matchUpCount:3,matchUpValue:1},singles:{matchUpCount:6,matchUpValue:1},valueGoal:5},[jD]:{hydrate:!0,doubles:{matchUpFormat:"SET1-S:8/TB7@7",matchUpCount:3,matchUpValue:1},singles:{matchUpFormat:_n,matchUpCount:6,matchUpValue:1},tieFormatName:"College D3",valueGoal:5},[SI]:{hydrate:!0,doubles:{matchUpFormat:"SET1-S:6/TB7",collectionValue:1,matchUpCount:3},singles:{matchUpFormat:_n,matchUpCount:6,matchUpValue:1},tieFormatName:"College Default",valueGoal:4},[YD]:{hydrate:!0,doubles:{matchUpFormat:"SET1-S:8/TB7",matchUpCount:3,matchUpValue:1},singles:{matchUpFormat:_n,matchUpCount:6,matchUpValue:1},tieFormatName:"College JUCO",valueGoal:5},[zD]:Iy,[qD]:my,[$D]:cy,[KD]:Rw,[QD]:oy,[XD]:uy,[JD]:py,[ZD]:dy,[tR]:ny,[rR]:ay,[eR]:ly,[nR]:sy,[oR]:iy,[sR]:fy,[iR]:Sy,[aR]:gy},tY=t=>{let e=t?.namedFormat&&Object.keys(Cw).includes(t.namedFormat)?t.namedFormat:Mw,r=Array.isArray(t?.uuids)?t?.uuids:[],n,{category:o,gender:i}=t?.event??{},s=q(Cw[e],!1,!0),a=c=>{if(!t?.isMock&&!t?.event?.isMock||!t.event)return r?.pop()??it();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:WD,collectionName:"Doubles",matchUpType:Rt,...s.doubles},{collectionId:a(1),matchUpFormat:_n,collectionName:"Singles",matchUpType:Ct,...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},co=tY;var Ut="SINGLES",Ea="SINGLES",wt="DOUBLES",ei="DOUBLES",Oe="TEAM",Ze="TEAM",pp="HYBRID",hI="HYBRID";var eY="RATING",rY="BOTH",vw={AGE:"AGE",BOTH:rY,DOUBLES:wt,DOUBLES_EVENT:ei,HYBRID:pp,HYBRID_EVENT:hI,RATING:eY,SINGLES:Ut,SINGLES_EVENT:Ea,TEAM_EVENT:Ze,TEAM:Oe};var H="MAIN",Z="QUALIFYING",me="CONSOLATION",Fe="VOLUNTARY_CONSOLATION",Vt="PLAY_OFF",Jc=[H,Z,me,Vt,Fe],Aa={[Z]:1,[H]:2,[Vt]:3,[me]:3,[Fe]:4},cR="finishingPositions",uR="aggregateEventStructures",pR={[H]:1,[Vt]:2,[me]:3,[Z]:4,[Fe]:5},Ow={[Vt]:1,[H]:2,[me]:3,[Z]:4,[Fe]:5},Zc="CLUSTER",km="ADJACENT",mR="SEPARATE",vi="WATERFALL",tu="ITEM",de="CONTAINER",ln="DRAW",Gm="RANDOM",qe="TOP_DOWN",Oi="BOTTOM_UP",fn="POSITION",Er="WINNER",ir="LOSER",Bn="FIRST_MATCHUP",hi="AD_HOC",nY="AD_HOC",rc="FEED_IN",ms="COMPASS",mp="OLYMPIC",oY="SINGLE_ELIMINATION";var zr="SINGLE_ELIMINATION",dp="DOUBLE_ELIMINATION",ds="FIRST_MATCH_LOSER_CONSOLATION",Vm="FIRST_ROUND_LOSER_CONSOLATION",ws="LUCKY_DRAW",nc="ADAPTIVE",TI="CURTIS_CONSOLATION",yI="CURTIS_CONSOLATION",hy="FEED_IN_CHAMPIONSHIP_TO_SF",Pa="FEED_IN_CHAMPIONSHIP_TO_SF",Ty="FEED_IN_CHAMPIONSHIP_TO_QF",eu="FEED_IN_CHAMPIONSHIP_TO_QF",yy="FEED_IN_CHAMPIONSHIP_TO_R16",ru="FEED_IN_CHAMPIONSHIP_TO_R16",dR="MODIFIED_FEED_IN_CHAMPIONSHIP",Na="MODIFIED_FEED_IN_CHAMPIONSHIP",Ls="FEED_IN_CHAMPIONSHIP",Bm="PAGE_PLAYOFF",Hm="PLAYOFF",lp="SWISS",iY={0:{name:"Qualifier 1",abbreviation:"Q1"},"0-1":{name:"Eliminator",abbreviation:"EL"},"0-2":{name:"Final",abbreviation:"F"}},_w="DOUBLE_ROUND_ROBIN",Hr="ROUND_ROBIN",Wr="ROUND_ROBIN_WITH_PLAYOFF",lR="DECIDER",fR="BACKDRAW",EI={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"}},AI={0:{name:"East",abbreviation:"E"},"0-1":{name:"West",abbreviation:"W"},"0-2":{name:"North",abbreviation:"N"},"0-1-1":{name:"South",abbreviation:"S"}},PI={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"}},uo="WIN_RATIO",ls="ROUND_OUTCOME",gR=[nc,ms,TI,eu,ru,Pa,Ls,Ty,yy,hy,ds,Vm,ws,Na,mp,Bm,Hm,Wr],sY=[hi,nc,ms,TI,dp,eu,ru,Pa,Ls,rc,ds,Vm,ws,Na,mp,Bm,Hm,Hr,Wr,zr,lp],IR={MAIN:H,QUALIFYING:Z,CONSOLATION:me,ITEM:tu,CONTAINER:de,FIRST_MATCHUP:Bn,WINNER:Er,LOSER:ir,AD_HOC:hi,FEED_IN:rc,FLEX_ROUNDS:nY,COMPASS:ms,PLAY_OFF:Vt,PAGE_PLAYOFF:Bm,PAGE_PLAYOFF_ATTRIBUTES:iY,PLAYOFF:Hm,SWISS:lp,OLYMPIC:mp,KNOCKOUT:oY,SINGLE_ELIMINATION:zr,DOUBLE_ELIMINATION:dp,CURTIS:TI,FICSF:hy,FICQF:Ty,FICR16:yy,MFIC:dR,VOLUNTARY_CONSOLATION:Fe,FIRST_MATCH_LOSER_CONSOLATION:ds,FIRST_ROUND_LOSER_CONSOLATION:Vm,MODIFIED_FEED_IN_CHAMPIONSHIP:Na,FEED_IN_CHAMPIONSHIP_TO_R16:ru,FEED_IN_CHAMPIONSHIP_TO_QF:eu,FEED_IN_CHAMPIONSHIP_TO_SF:Pa,FEED_IN_CHAMPIONSHIP:Ls,LUCKY_DRAW:ws,ADAPTIVE:nc,ROUND_ROBIN_WITH_PLAYOFF:Wr,ROUND_ROBIN:Hr,DECIDER:lR,BACKDRAW:fR,COMPASS_ATTRIBUTES:EI,OLYMPIC_ATTRIBUTES:AI,ADAPTIVE_ATTRIBUTES:PI,DRAW:ln,RANDOM:Gm,TOP_DOWN:qe,BOTTOM_UP:Oi,CLUSTER:Zc,ADJACENT:km,SEPARATE:mR,WATERFALL:vi,WIN_RATIO:uo,ROUND_OUTCOME:ls,MULTI_STRUCTURE_DRAWS:gR,generatedDrawTypes:sY,stageOrder:Aa,finishOrder:pR,AGGREGATE_EVENT_STRUCTURES:uR,FINISHING_POSITIONS:cR},xw=IR;var Ee="tournamentRecords",NI="policyDefinitions",rt="tournamentRecord",Ey="onlineResource",Kt="drawDefinition",Ay="tieFormatName",fl="matchUpFormat",sr="participantId",gl="scheduleDates",ww="tournamentId",Lw="scheduleDate",Fw="roundNumber",po="structureId",Wm="participant",nu="matchUpIds",Py="entryStage",kw="policyType",SR="structures",UI="eventType",Or="matchUpId",Il="tieFormat",fp="inContext",oc="structure",Ym="courtIds",Gw="personId",jm="venueIds",DI="matchUps",Fs="courtId",Ny="eventId",Dn="matchUp",ic="drawId",Yr="error",ce="event",_i="param",RI="uuids",Uy="penaltyType",Sl="penaltyId",gp="venueId",Vw="stage",Bw="averageMatchUpMinutes",Hw="recoveryMinutes",Ww="periodLength",Yw="number";var jr="object",ke="array";var $e="_validate",Dy="_message",_r="_invalid",Ge="_ofType",Ip="_anyOf",Ua="_oneOf";var jw={[Ey]:t=>Yt(Object.keys(t),[dl,ll,Xc]).length===3,[Ay]:t=>t&&co({namedFormat:t}),[RI]:t=>!t||Array.isArray(t)&&t.every(_t),[Il]:t=>!or({tieFormat:t}).error,[UI]:t=>[Ut,wt,Oe].includes(t),[Py]:t=>Jc.includes(t)},aY={[Ee]:kt,[rt]:j,[NI]:fa,[Kt]:$,[sr]:He,[fl]:VU,[ww]:Za,[po]:dn,[nu]:Ms,[Wm]:ga,[Ey]:So,[UI]:Kn,[SR]:Lg,[Or]:mr,[Il]:Xo,[oc]:bi,[Fs]:Hg,[DI]:Vn,[Ny]:Gr,[Dn]:Xe,[Ym]:nt,[jm]:nt,[Uy]:cD,[Sl]:uD,[gp]:Os,[ic]:Pn,[ce]:le,[Vw]:Gg},cY={[Ee]:jr,[NI]:jr,[rt]:jr,[Kt]:jr,[Ey]:jr,[gl]:ke,[Wm]:jr,[nu]:ke,[SR]:ke,[Il]:jr,[oc]:jr,[Ym]:ke,[jm]:ke,[DI]:ke,[Dn]:jr,[ce]:jr,[RI]:ke};function X(t,e,r){if(!t&&!Tt(t))return{error:O};if(!e?.length||t?._bypassParamCheck)return{valid:!0};if(!Array.isArray(e))return{error:O};let{paramError:n,errorParam:o}=mY(t,e);if(!n)return{valid:!0};let i=n[$e]&&(n[Yr]||n[_r])||t?.[o]==null&&(n[Yr]||n[_r]||aY[o]||O)||O,s=o??(n[Ua]&&Object.keys(n[Ua]).join(", "));return M({info:{param:s,message:n[Dy]},result:{error:i},stack:r})}function qw(t,e){let r=Object.keys(t),n=Object.keys(e);return Yt(r,n)}function uY(t,e){if(!e)return;let r=qw(t,e);return r.length!==1?{error:O}:r.reduce((n,o)=>({...n,[o]:!0}),{})}function pY(t,e){if(!e)return;let r=qw(t,e).filter(n=>t[n]);return r.length<1?{error:O}:r.reduce((n,o)=>({...n,[o]:!0}),{})}function mY(t,e){let r,n;return{paramError:e.find(({_ofType:i,_oneOf:s,_anyOf:a,_validate:c,_info:u,...p})=>{let m=s&&uY(t,s);if(m?.error)return m.error;m&&Object.assign(p,m);let d=a&&pY(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&&!kr(c),S=t[g]!==void 0&&!c&&dY(t,g,i),h=p[g]&&t[g]==null,y=I||S||h||c&&t[g]!==void 0&&!lY(t[g],c)||jw[g]&&!jw[g](t[g]);return y&&(r=g,n=u),y});return!l.length||f}),errorParam:r,paramInfo:n}}function dY(t,e,r){return r=r||cY[e]||"string",r==="array"?!Array.isArray(t[e]):typeof t[e]!==r}function lY(t,e){return kr(e)?e(t):!0}var Sp="DYNAMIC",Xn="RANKING",vo="RATING",ri="SCALE",ho="SEEDING",$w={RANKING:Xn,RATING:vo,SCALE:ri,SEEDING:ho};function sc(t){let e=X(t,[{[Wm]:!0}]);if(e.error)return e;let r=t.participant.timeItems?.filter(({itemType:o})=>o?.startsWith(ri)&&[Xn,vo,ho].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===ho&&"seedings"||c===Xn&&"rankings"||"ratings";n[l][u]||(n[l][u]=[]),n[l][u].push({scaleValue:a.itemValue,scaleDate:a.itemDate,scaleName:d})}}}return{...P,...n}}function fs(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 S=I.map(h=>{let T={};return o(h,g,T)!==!1?T:void 0}).filter(Boolean);a[l]=S}else I&&(a[l]={},o(I,g,a[l]));else{let S=i[l];if(Array.isArray(g)&&!g.includes(S))return!1;(s[l]||d&&s[l]!==!1)&&(a[l]=S)}}}}var Ry="voluntaryConsolation",xi="competitiveBands",bI="roundRobinTally",Jn="positionActions",We="matchUpActions",gr="rankingPoints",Oo="roundNaming",Da="participant",hp="progression",_o="scheduling",ac="avoidance",fY="participant",gY="display",Qr="scoring",Hn="seeding",ou="feedIn",IY="sanctioning",SY="audit",iu="competition",hl="draws",Kw={POLICY_TYPE_VOLUNTARY_CONSOLATION:Ry,POLICY_TYPE_COMPETITIVE_BANDS:xi,POLICY_TYPE_ROUND_ROBIN_TALLY:bI,POLICY_TYPE_POSITION_ACTIONS:Jn,POLICY_TYPE_MATCHUP_ACTIONS:We,POLICY_TYPE_RANKING_POINTS:gr,POLICY_TYPE_ROUND_NAMING:Oo,POLICY_TYPE_PARTICIPANT:Da,POLICY_TYPE_PROGRESSION:hp,POLICY_TYPE_SCHEDULING:_o,POLICY_TYPE_AVOIDANCE:ac,POLICY_TYPE_COMPETITION:iu,POLICY_TYPE_DISPLAY:gY,POLICY_TYPE_PRIVACY:fY,POLICY_TYPE_FEED_IN:ou,POLICY_TYPE_SCORING:Qr,POLICY_TYPE_SEEDING:Hn,POLICY_TYPE_SANCTIONING:IY,POLICY_TYPE_AUDIT:SY,POLICY_TYPE_DRAWS:hl};function ni({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=q(s,!1,o);if(a){let c=e?.[Da];if(r?.withScaleValues){let{ratings:u,rankings:p}=sc({participant:a});a.rankings=p,a.ratings=u}if(c?.participant)return fs({template:c.participant,source:a})}return a}var zw="element required",Qw="missing name";function dr(t){if(!t||typeof t!="object")return{error:nt};if(t.element&&typeof t?.element!="object")return{error:O};if(!t?.name)return{error:nt,info:Qw};if(!t?.element){if(t.discover&&t.tournamentRecords){for(let e of Object.keys(t.tournamentRecords)){let r=t.tournamentRecords[e],n=dr({element:r,name:t.name});if(n.error)return M({result:n,stack:"removeExtension"})}return{...P}}return{error:nt,info:zw}}return t?.element.extensions?(t.element.extensions=t.element.extensions.filter(e=>e?.name!==t.name),{...P}):{...P,info:fe}}function Wn({requiredAttributes:t=["name","value"],extension:e}){if(!e||typeof e!="object"||typeof e.name!="string")return!1;let r=Object.keys(e);return t.filter(n=>r.includes(n)).length===t.length}function ut(t){if(typeof t!="object")return{error:nt};let e="addExtension";if(t?.element&&typeof t.element!="object")return M({result:{error:O},stack:e});if(!Wn({extension:t.extension}))return M({result:{error:O,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=ut({extension:t.extension,element:o});if(i.error)return M({result:i,stack:e})}return{...P}}else return M({result:{error:nt},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),{...P}}function CI(t){return!t||typeof t!="object"?{error:nt}:t.tournamentRecord?ut({creationTime:t.creationTime,element:t.tournamentRecord,extension:t.extension}):{error:j}}function MI(t){return!t||typeof t!="object"?{error:nt}:t.drawDefinition?ut({creationTime:t.creationTime,element:t.drawDefinition,extension:t.extension}):{error:Rr}}function xo(t){return!t||typeof t!="object"?{error:nt}:t.event?ut({creationTime:t.creationTime,extension:t.extension,element:t.event}):{error:Gr}}function hR(t){if(!t||typeof t!="object")return{error:nt};if(!t.participantId)return{error:He};let e=t.tournamentRecord?.participants??[],r=ni({participantId:t.participantId,tournamentParticipants:e});return r?ut({creationTime:t.creationTime,extension:t.extension,element:r}):{error:ee}}function vI(t){return!t||typeof t!="object"?{error:nt}:t.tournamentRecord?dr({element:t.tournamentRecord,name:t.name}):{error:j}}function TR(t){return!t||typeof t!="object"?{error:nt}:t.drawDefinition?dr({element:t.drawDefinition,name:t.name}):{error:Rr}}function qm(t){return!t||typeof t!="object"?{error:nt}:t?.event?dr({element:t.event,name:t.name}):{error:Gr}}function yR(t){if(!t||typeof t!="object")return{error:nt};if(!t.participantId)return{error:He};let e=t.tournamentRecord?.participants??[],r=ni({participantId:t.participantId,tournamentParticipants:e});return r?dr({element:r,name:t.name}):{error:ee}}function $m({tournamentRecords:t}){return{tournamentIds:Tt(t)?Object.keys(t):[],...P}}var hY="extensionQueries";function ot({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:fe}}return M({result:{error:nt},stack:hY})}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:fe}}var TY="activeSuspension",Tp="appliedPolicies",Ra="competitionState",ER="context",Tl="delegatedOutcome",mo="disabled",cc="disableAutoCalc",yl="disableLinks",El="display",wi="draftState",uc="drawDeletions",yY="drawProfile",EY="eventProfile",AY="eventWithdrawalRequests",PY="factory",on="flightProfile",by="groupingAttribute",wo="lineUps",ba="linkedTournamentsIds",sn="mutationLocks",Cy="participantRepresentatives",pc="personRequests",su="positionActions",NY="rankingPoints",UY="registration",Rn="roundTarget",AR="sanctioningConstraints",yp="scheduleLimits",oi="scheduleTiming",mc="schedulingProfile",DY="statusDetail",au="subOrder",Lo="tally",Al="tieFormatModification",My={ACTIVE_SUSPENSION:TY,APPLIED_POLICIES:Tp,COMPETITION_STATE:Ra,CONTEXT:ER,DELEGATED_OUTCOME:Tl,DISABLED:mo,DISABLE_LINKS:yl,DISABLE_AUTO_CALC:cc,DISPLAY:El,DRAFT_STATE:wi,DRAW_DELETIONS:uc,DRAW_PROFILE:yY,EVENT_PROFILE:EY,EVENT_WITHDRAWAL_REQUESTS:AY,FLIGHT_PROFILE:on,GROUPING_ATTRIBUTE:by,LINEUPS:wo,LINKED_TOURNAMENTS:ba,MUTATION_LOCKS:sn,PARTICIPANT_REPRESENTATIVES:Cy,PERSON_REQUESTS:pc,POSITION_ACTIONS:su,RANKING_POINTS:NY,REGISTRATION:UY,ROUND_TARGET:Rn,SANCTIONING_CONSTRAINTS:AR,SCHEDULE_LIMITS:yp,SCHEDULE_TIMING:oi,SCHEDULING_PROFILE:mc,STATUS_DETAIL:DY,SUB_ORDER:au,TALLY:Lo,TIE_FORMAT_MODIFICATIONS:Al,FACTORY:PY},PR=[Tl,mo,cc,yl,on,wo,ba,sn,Cy,pc,Rn,yp,oi,mc,au,Lo,Al];function NR({tournamentRecords:t}){if(typeof t!="object"||!Object.keys(t).length)return{error:kt};let e=$m({tournamentRecords:t}),{tournamentIds:r}=e;return r?.length>1?ut({tournamentRecords:t,discover:!0,extension:{name:ba,value:{tournamentIds:r}}}):{...P}}function UR({tournamentRecords:t}){if(typeof t!="object"||!Object.keys(t).length)return{error:kt};let e=dr({name:ba,tournamentRecords:t,discover:!0});return M({result:e,stack:"unlinkTournaments"})}function DR({tournamentRecords:t,tournamentId:e}){if(typeof t!="object")return{error:O};if(!e)return{error:Za};let r=$m({tournamentRecords:t}),{tournamentIds:n}=r;if(!n.includes(e))return{error:Za};let o;return n.every(i=>{let s=t[i],{extension:a}=ot({element:s,name:ba});if(!a)return!0;let c=a?.value?.tournamentIds??[];if(!c?.length||c.length===1&&c.includes(e)||i===e){let m=vI({name:ba,tournamentRecord:s});return m.error&&(o=m.error),m.success}let u=c.filter(m=>m!==e);a.value={tournamentIds:u};let p=CI({tournamentRecord:s,extension:a});return p.error&&(o=p.error),p.success}),o?{error:o}:{...P}}function It({onlySpecifiedPolicyTypes:t=!1,policyTypes:e=[],tournamentRecord:r,drawDefinition:n,structure:o,event:i}){if(!Array.isArray(e))return{error:LT};let s={};return r&&a(r),i&&a(i),n&&a(n),o&&a(o),{appliedPolicies:s,...P};function a(c){let p=c?.extensions?.find(m=>m.name===Tp)?.value;if(p)for(let m of Object.keys(p))(t?e.includes(m):!e.length||e.includes(m))&&(s[m]=q(p[m],!1,!0))}}function lo({policyTypes:t=[],tournamentRecord:e,drawDefinition:r,structure:n,event:o}){if(!Array.isArray(t))return{error:LT};let{appliedPolicies:i}=It({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:Xu.message}}function To(t){let{appliedPolicies:e}=It({tournamentRecord:t.tournamentRecord,drawDefinition:t.drawDefinition,event:t.event});return{competitionPolicy:e?.[iu]}}function Li({element:t,accessor:e}){if(typeof e!="string")return{values:[]};let r=q(t),n=e.split("."),o=[],i;a({targetElement:r,attributes:n});let s={value:i};return o.length&&(s.values=o),s;function a({targetElement:c,attributes:u=[],significantCharacters:p}){for(let[d,l]of u.entries())if(c?.[l]){let f=u.slice(d+1);f.length?Array.isArray(c[l])?c[l].forEach(I=>a({targetElement:I,attributes:f})):(c=c[l],m({targetElement:c,index:d})):(i||(i=c[l]),o.includes(c[l])||o.push(c[l]))}function m({targetElement:d,index:l}){if(d&&l===u.length-1&&["string","number"].includes(typeof d)){let f=p?d.slice(0,p):d;i?o.includes(f)||o.push(f):(i=f,o.push(f))}}}}function yo({requireTimeStamp:t,scaleAttributes:e,participant:r}){if(!r)return{error:ga};if(!Tt(e))return{error:O};if(r.timeItems??=[],Array.isArray(r.timeItems)){let{accessor:n,scaleType:o,eventType:i,scaleName:s}=e,a=[ri,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!==ri)return{error:Yc};let f=n&&Li({element:u.itemValue,accessor:n}),g=f?.value||u.itemValue,I={rawValue:f&&u.itemValue,eventType:d,scaleDate:u.itemDate,scaleValue:g,scaleName:l,scaleType:m};return{...P,scaleItem:I}}}return{...P,scaleItem:void 0}}function Ep({value:t,sourceRange:e,targetRange:r}){if(!Array.isArray(e)||e.length!==2)return 0;let n=Math.min(...e),o=Math.max(...e),i=Math.min(...r),s=Math.max(...r);return(t-n)*(s-i)/(o-n)+i}var RR="NTRP";var bR="DUPR",CR="UTR_P",MR="UTPR";var vR="SQUASH_LEVELS",OR="US_SQUASH",_R="USATT",xR="ITTF",wR="USAR";var Xw={ELO:"ELO",NTRP:RR,TRN:"TRN",UTR:"UTR",WTN:"WTN",DUPR:bR,UTR_P:CR,UTPR:MR,PSA:"PSA",SQUASH_LEVELS:vR,US_SQUASH:OR,USATT:_R,ITTF:xR,USAR:wR,BWF:"BWF"};var MY={ELO:{defaultInitialization:1500,decimalsCount:0,range:[0,3e3],ascending:!1},[RR]:{accessors:["ntrpRating","dntrpRatingHundredths"],attributes:{ustaRatingType:""},accessor:"dntrpRatingHundredths",defaultInitialization:3,decimalsCount:1,ascending:!1,range:[1,7]},UTR:{defaultInitialization:6,accessors:["utrRating"],accessor:"utrRating",decimalsCount:2,ascending:!1,range:[1,16]},WTN:{attributes:{confidence:{generator:!0,range:[60,100]}},accessors:["wtnRating","confidence"],defaultInitialization:23,accessor:"wtnRating",ascending:!0,decimalsCount:2,range:[40,1]},[bR]:{defaultInitialization:3.5,accessors:["duprRating","reliabilityScore"],accessor:"duprRating",attributes:{reliabilityScore:{generator:!0,range:[0,100]}},decimalsCount:3,ascending:!1,range:[2,8]},[CR]:{defaultInitialization:5,accessors:["utrpRating","verified"],accessor:"utrpRating",attributes:{verified:{type:"boolean"},provisional:{type:"string"}},decimalsCount:1,ascending:!1,range:[1,10]},[MR]:{defaultInitialization:3.5,accessor:"utprRating",decimalsCount:1,ascending:!1,range:[2,5],deprecated:!0},PSA:{defaultInitialization:500,accessor:"psaPoints",decimalsCount:0,ascending:!1,range:[0,3e3],attributes:{tournaments:{generator:!0,range:[1,20]},divisor:{generator:!0,range:[10,20]}}},[vR]:{defaultInitialization:2e3,accessor:"squashLevel",decimalsCount:0,ascending:!1,range:[0,7e3]},[OR]:{defaultInitialization:3.5,accessor:"usSquashRating",decimalsCount:1,ascending:!1,range:[2,6]},[_R]:{defaultInitialization:1e3,accessor:"usattRating",decimalsCount:0,ascending:!1,range:[200,3e3]},[xR]:{defaultInitialization:500,accessor:"ittfPoints",decimalsCount:0,ascending:!1,range:[0,2e4]},[wR]:{defaultInitialization:1e4,accessor:"usarRanking",decimalsCount:0,ascending:!0,range:[1,25e3]},BWF:{defaultInitialization:5e3,accessor:"bwfPoints",decimalsCount:0,ascending:!0,range:[0,15e4],attributes:{tournaments:{generator:!0,range:[1,10]}}}},Ke=MY;function Ap({sourceRatingType:t,sourceRating:e}){let r=Ke[t]?.range,n=r?.[0]>r?.[1],o=Ke["ELO"].range;return Ep({value:n?r[0]-e:e,sourceRange:r,targetRange:o})}function Jw({targetRatingType:t,sourceRating:e}){let r=Ke[t]?.decimalsCount||0,n=Ke[t]?.range,o=n?.[0]>n?.[1],i=Math.max(...n),s=Ke["ELO"]?.range,a=Ep({targetRange:n,sourceRange:s,value:e}),c=Number.parseFloat(a?.toFixed(r))||0;return o?i-c:c}function Pl(t){let{tournamentRecord:e,participantIds:r,scaleName:n,eventType:o,convertToELO:i,adHocRatings:s={}}=t,a=t.scaleAccessor??Ke[n]?.accessor,c=e.participants??[];for(let u of r??[]){let p=c?.find(d=>d.participantId===u),m;i&&(m=FR({scaleName:`${"ELO"}.${Sp}`,participant:p,eventType:o})),m||(m=FR({scaleName:`${n}.${Sp}`,participant:p,eventType:o}),m&&i&&n!=="ELO"&&(m=Ap({sourceRatingType:n,sourceRating:m}))),!m&&n&&(m=FR({scaleAccessor:a,participant:p,scaleName:n,eventType:o}),m&&i&&n!=="ELO"&&(m=Ap({sourceRatingType:n,sourceRating:m}))),m&&!s[u]&&(s[u]=m)}return s}function FR({scaleType:t=vo,scaleAccessor:e,participant:r,scaleName:n,eventType:o}){let a=(r&&yo({scaleAttributes:{eventType:o??Ea,scaleType:t,scaleName:n},participant:r}))?.scaleItem?.scaleValue;return e&&Tt(a)?a[e]:a}function kR(t){let{tournamentRecord:e,drawDefinition:r,participantIds:n,event:o}=t;if(!r)return{error:$};if(!n?.length)return{error:nt};let{competitionPolicy:i}=To({tournamentRecord:e,drawDefinition:r,event:o});if(!i)return{...P};let s=i.ratingPolicy,a=s.baselineRating.scaleName,c=s.ratingAggregation??"AVERAGE",u=o?.eventType,p=a?Pl({tournamentRecord:e,participantIds:n,scaleName:a,eventType:u}):{},m={};for(let l of n){let f=vY({tournamentRecord:e,participantId:l,adHocRatings:p,aggregation:c,eventType:u});m[l]={participantId:l,baselineRating:f,dynamicFormRating:f,pressureRating:0,roundsPlayed:0,wins:0,losses:0,draws:0,totalPointsWon:0,totalPointsLost:0,ratingHistory:[]}}let d={participantStates:m,roundStates:{}};return ut({element:r,extension:{name:Ra,value:d}}),{competitionState:d,...P}}function vY({tournamentRecord:t,participantId:e,adHocRatings:r,aggregation:n,eventType:o}){if(r[e]!==void 0)return r[e];if(o===wt){let s=t.participants?.find(a=>a.participantId===e)?.individualParticipantIds;if(s?.length){let a=s.map(c=>r[c]??0);return OY(a,n)}}return 0}function OY(t,e){if(!t.length)return 0;switch(e){case"MIN":return Math.min(...t);case"MAX":return Math.max(...t);case"SUM":return t.reduce((r,n)=>r+n,0);default:return t.reduce((r,n)=>r+n,0)/t.length}}function Fo({drawDefinition:t}){let{extension:e}=ot({element:t,name:Ra});return{competitionState:e?.value}}function tL(t){let e=t.score?.sets??[];if(!e.length)return Zw(t);let r=0,n=0;for(let o of e){let i=o.side1Score??0,s=o.side2Score??0;if(o.side1TiebreakScore!==void 0||o.side2TiebreakScore!==void 0){let a=o.side1TiebreakScore??0,c=o.side2TiebreakScore??0,u=a+c;if(u>0){r+=i-(o.winningSide===1?1:0)+a/u,n+=s-(o.winningSide===2?1:0)+c/u;continue}}r+=i,n+=s}return r>0||n>0?{side1Count:r,side2Count:n}:Zw(t)}function Zw(t){let{winningSide:e}=t;return e===1?{side1Count:1,side2Count:0}:e===2?{side1Count:0,side2Count:1}:{side1Count:0,side2Count:0}}function GR({pointsWon:t,pointsLost:e,competitionPolicy:r}){let n=t+e;if(n===0)return .5;let o=t/n,i=r.ratingPolicy.pressureRating;if(!i||i.actualOutputMethod==="POINT_SHARE")return o;let s=i.weights??{pointShare:1},a=(t-e)/n,c=0,u=s.pointShare??1,p=s.pointDifferential??0,m=s.contextFactor??0,d=u+p+m;return d===0?o:(u*o+p*a+m*c)/d}function OI(t,e,r){return 1/(1+Math.pow(10,(e-t)/r))}function Km(t){let{tournamentRecord:e,drawDefinition:r,matchUp:n,event:o}=t;if(!r)return{error:$};if(!n)return{error:Xe};let{competitionPolicy:i}=To({tournamentRecord:e,drawDefinition:r,event:o});if(!i)return{...P};let{competitionState:s}=Fo({drawDefinition:r});if(!s)return{...P};let a=n.sides??[],c=a[0]?.participantId,u=a[1]?.participantId;if(!c||!u)return{...P};let p=s.participantStates[c],m=s.participantStates[u];if(!p||!m)return{...P};let{winningSide:d}=n,{side1Count:l,side2Count:f}=tL(n),g=GR({pointsWon:l,pointsLost:f,competitionPolicy:i}),I=GR({pointsWon:f,pointsLost:l,competitionPolicy:i}),S=i.ratingPolicy.dynamicFormRating.logisticScale,h=i.ratingPolicy.dynamicFormRating.kFactor,T=OI(p.baselineRating,m.baselineRating,S),y=OI(m.baselineRating,p.baselineRating,S),E=OI(p.dynamicFormRating,m.dynamicFormRating,S),A=OI(m.dynamicFormRating,p.dynamicFormRating,S),N=i.ratingPolicy.pressureRating?.enabled,U=N?g-T:0,R=N?I-y:0,D=i.ratingPolicy.dynamicFormRating.enabled,b=D?p.dynamicFormRating+h*(g-E):p.dynamicFormRating,C=D?m.dynamicFormRating+h*(I-A):m.dynamicFormRating,_=n.roundNumber??0;return p.dynamicFormRating=b,p.pressureRating+=U,p.roundsPlayed+=1,p.wins+=d===1?1:0,p.losses+=d===2?1:0,p.draws+=d?0:1,p.totalPointsWon+=l,p.totalPointsLost+=f,p.ratingHistory.push({roundNumber:_,opponentParticipantId:u,dynamicFormRatingBefore:p.dynamicFormRating-h*(g-E),dynamicFormRatingAfter:b,pressureDelta:U,actualOutput:g,expectedOutput:T}),m.dynamicFormRating=C,m.pressureRating+=R,m.roundsPlayed+=1,m.wins+=d===2?1:0,m.losses+=d===1?1:0,m.draws+=d?0:1,m.totalPointsWon+=f,m.totalPointsLost+=l,m.ratingHistory.push({roundNumber:_,opponentParticipantId:c,dynamicFormRatingBefore:m.dynamicFormRating-h*(I-A),dynamicFormRatingAfter:C,pressureDelta:R,actualOutput:I,expectedOutput:y}),ut({element:r,extension:{name:Ra,value:s}}),{...P}}var xr="ABANDONED",cu="AWAITING_RESULT";var Zn="CANCELLED",ie="COMPLETED",Pp="DEAD_RUBBER",xt="DEFAULTED",ge="DOUBLE_DEFAULT",Qt="DOUBLE_WALKOVER",bn="IN_PROGRESS",Xr="INCOMPLETE",VR="NOT_PLAYED",Ue="RETIRED",Fi="SUSPENDED",zt="TO_BE_PLAYED",Lt="WALKOVER",eL=[cu,ie,xt,bn,Xr,Ue,Fi],vy=[cu,ie,xt,Qt,ge,bn,Xr,Ue,Fi,Lt],Oy=[xr,cu,"BYE",Zn,ie,Pp,xt,Qt,ge,bn,Xr,VR,Ue,Fi,zt,Lt],_y=["BYE",Qt,ge,ie,xt,Ue,Lt],xy=[xr,cu,Zn,Pp,bn,Xr,VR,Fi,zt,void 0],Mt=[Zn,xr,ie,Pp,xt,Qt,ge,Ue,Lt],Nl=[xr,ie,xt,Qt,ge,bn,Ue,Lt],wy=[bn,Xr,Fi,zt],Ly={ABANDONED:xr,AWAITING_RESULT:cu,BYE:"BYE",CANCELLED:Zn,COMPLETED:ie,DEAD_RUBBER:Pp,DEFAULTED:xt,DOUBLE_WALKOVER:Qt,DOUBLE_DEFAULT:ge,IN_PROGRESS:bn,INCOMPLETE:Xr,NOT_PLAYED:VR,RETIRED:Ue,SUSPENDED:Fi,TO_BE_PLAYED:zt,WALKOVER:Lt};function BR(t){let{tournamentRecord:e,drawDefinition:r,roundNumber:n,matchUps:o,event:i}=t;if(!r)return{error:$};let{competitionPolicy:s}=To({tournamentRecord:e,drawDefinition:r,event:i});if(!s)return{...P};let{competitionState:a}=Fo({drawDefinition:r});if(!a)return{...P};if(a.roundStates[n]?.processed)return{...P};let c=o.filter(p=>p.roundNumber===n&&(p.winningSide||Mt.includes(p.matchUpStatus)));for(let p of c)Km({tournamentRecord:e,drawDefinition:r,matchUp:p,event:i});let{competitionState:u}=Fo({drawDefinition:r});return u&&(u.roundStates[n]={roundNumber:n,processed:!0},ut({element:r,extension:{name:Ra,value:u}})),{...P}}function HR({drawDefinition:t}){return t?(ut({element:t,extension:{name:Ra,value:void 0}}),{...P}):{error:$}}var YR={};Gt(YR,{getCompetitionLeaderboard:()=>ky,getCompetitionParticipantState:()=>Fy,getCompetitionPolicy:()=>To,getCompetitionState:()=>Fo,getLinkedTournamentIds:()=>Np,getTournamentIds:()=>$m});function Fy({drawDefinition:t,participantId:e}){let{competitionState:r}=Fo({drawDefinition:t});return{participantState:r?.participantStates?.[e]}}function ky(t){let{tournamentRecord:e,drawDefinition:r,event:n}=t,{competitionPolicy:o}=To({tournamentRecord:e,drawDefinition:r,event:n}),{competitionState:i}=Fo({drawDefinition:r});if(!i||!o)return{leaderboard:[]};let s=o.victoryPolicy.primaryRanking;return{leaderboard:[...Object.values(i.participantStates)].sort((p,m)=>{let d=rL(m,s)-rL(p,s);if(d!==0)return d;for(let l of o.victoryPolicy.tiebreakOrder??[]){let f=_Y(p,m,l,i.participantStates);if(f!==0)return f}return 0}).map((p,m)=>({participantId:p.participantId,rank:m+1,baselineRating:p.baselineRating,dynamicFormRating:p.dynamicFormRating,pressureRating:p.pressureRating,wins:p.wins,losses:p.losses,draws:p.draws,pointsWon:p.totalPointsWon,pointsLost:p.totalPointsLost}))}}function rL(t,e){switch(e){case"PRESSURE_RATING":return t.pressureRating;case"DYNAMIC_FORM_RATING":return t.dynamicFormRating;case"WINS":return t.wins;case"POINTS":return t.totalPointsWon;default:return t.wins}}function _Y(t,e,r,n){switch(r){case"POINT_DIFFERENTIAL":return t.totalPointsWon-t.totalPointsLost-(e.totalPointsWon-e.totalPointsLost);case"DYNAMIC_FORM_RATING":return t.dynamicFormRating-e.dynamicFormRating;case"PRESSURE_RATING":return t.pressureRating-e.pressureRating;case"HEAD_TO_HEAD":{let o=t.ratingHistory.filter(c=>c.opponentParticipantId===e.participantId),i=e.ratingHistory.filter(c=>c.opponentParticipantId===t.participantId),s=o.filter(c=>c.actualOutput>.5).length,a=i.filter(c=>c.actualOutput>.5).length;return s-a}case"HEAD_TO_HEAD_PRESSURE":{let o=t.ratingHistory.filter(c=>c.opponentParticipantId===e.participantId),i=e.ratingHistory.filter(c=>c.opponentParticipantId===t.participantId),s=o.reduce((c,u)=>c+u.pressureDelta,0),a=i.reduce((c,u)=>c+u.pressureDelta,0);return s-a}case"STRENGTH_OF_OPPOSITION":{let o=t.ratingHistory.map(c=>n[c.opponentParticipantId]?.baselineRating??0),i=e.ratingHistory.map(c=>n[c.opponentParticipantId]?.baselineRating??0),s=o.length?o.reduce((c,u)=>c+u,0)/o.length:0,a=i.length?i.reduce((c,u)=>c+u,0)/i.length:0;return s-a}default:return 0}}function Np({tournamentRecords:t}){return typeof t!="object"||!Object.keys(t).length?{error:kt}:{linkedTournamentIds:Object.assign({},...Object.keys(t).map(r=>{let n=t[r],o=n?.tournamentId,{extension:i}=ot({element:n,name:ba}),s=(i?.value?.tournamentIds??[]).filter(a=>a!==o);return{[r]:s}}))}}var rv={};Gt(rv,{adHocPositionSwap:()=>TC,addAdHocMatchUps:()=>Kp,addDrawDefinitionTimeItem:()=>CS,addFinishingRounds:()=>hc,addGoesTo:()=>Ts,addLinkedConsolationStructure:()=>Qb,addPlayoffStructures:()=>LS,addQualifyingStructure:()=>SC,addVoluntaryConsolationStructure:()=>dS,allPlayoffPositionsFilled:()=>GE,alternateDrawPositionAssignment:()=>Jb,assignDrawPosition:()=>NC,assignDrawPositionBye:()=>Cr,attachConsolationStructures:()=>TS,attachPlayoffStructures:()=>yS,attachQualifyingStructure:()=>bS,attachStructures:()=>ES,autoSeeding:()=>A1,automatedPlayoffPositioning:()=>wa,automatedPositioning:()=>Ru,buildDrawHierarchy:()=>E1,checkValidEntries:()=>Ef,deleteAdHocMatchUps:()=>DC,drawMatic:()=>tm,findDrawDefinition:()=>iA,generateAdHocMatchUps:()=>Nc,generateAdHocRounds:()=>_f,generateAndPopulatePlayoffStructures:()=>gf,generateConsolationStructure:()=>zb,generateDrawDefinition:()=>bc,generateDrawMaticRound:()=>Uf,generateDrawStructuresAndLinks:()=>Af,generateDrawTypeAndModifyDrawDefinition:()=>Pf,generateQualifyingStructure:()=>mf,generateSwissRound:()=>T1,generateVoluntaryConsolation:()=>RA,getAssignedParticipantIds:()=>$i,getAvailableMatchUpsCount:()=>Sf,getAvailablePlayoffProfiles:()=>Hp,getDraftState:()=>yA,getDrawDefinitionTimeItem:()=>$y,getDrawParticipantRepresentativeIds:()=>eA,getDrawStructures:()=>In,getDrawTypeCoercion:()=>Qp,getEligibleVoluntaryConsolationParticipants:()=>JE,getLuckyDrawRoundStatus:()=>df,getMatchUpsMap:()=>Ie,getParticipantIdFinishingPositions:()=>Tf,getPositionAssignments:()=>Cu,getPositionsPlayedOff:()=>Pu,getRandomQualifierList:()=>hA,getSeedingThresholds:()=>EE,getSeedsCount:()=>Xp,getStructureSeedAssignments:()=>Pr,getSwissChart:()=>tA,getSwissStandings:()=>ZE,getTeamLineUp:()=>Ys,getValidGroupSizes:()=>id,hasLuckyRounds:()=>tS,initializeDraft:()=>UC,isAdHoc:()=>Ae,isCompletedStructure:()=>No,isValidForQualifying:()=>TA,luckyDrawAdvancement:()=>yC,luckyLoserDrawPositionAssignment:()=>Wb,modifyDrawDefinition:()=>EC,modifyDrawName:()=>FS,modifySeedAssignment:()=>sC,mutate:()=>CC,positionActions:()=>SA,pruneDrawDefinition:()=>PC,qualifierDrawPositionAssignment:()=>PS,qualifierProgression:()=>Zb,query:()=>WC,remapDrawDefinitionMatchUpIds:()=>AS,removeDrawPositionAssignment:()=>Bp,removeRoundMatchUps:()=>RC,removeSeededParticipant:()=>IC,removeStructure:()=>mC,renameStructures:()=>cC,resetDrawDefinition:()=>AC,resetQualifyingStructure:()=>pC,resetVoluntaryConsolationStructure:()=>tb,resolveDraftPositions:()=>uC,seedWithdrawalCascade:()=>hC,setDrawParticipantRepresentativeIds:()=>qR,setDrawPositionPreferences:()=>Xb,setPositionAssignments:()=>jb,setStructureOrder:()=>aC,setSubOrder:()=>bC,shiftAdHocRounds:()=>Yb,swapAdHocRounds:()=>qb,swapDrawPositionAssignments:()=>gC,updateTeamLineUp:()=>As,validatePlayoffGroups:()=>cf,withdrawParticipantAtDrawPosition:()=>Bb});var CC={};Gt(CC,{adHocPositionSwap:()=>TC,addAdHocMatchUps:()=>Kp,addDrawDefinitionTimeItem:()=>CS,addLinkedConsolationStructure:()=>Qb,addPlayoffStructures:()=>LS,addQualifyingStructure:()=>SC,addVoluntaryConsolationStructure:()=>dS,alternateDrawPositionAssignment:()=>Jb,assignDrawPosition:()=>NC,assignDrawPositionBye:()=>Cr,attachConsolationStructures:()=>TS,attachPlayoffStructures:()=>yS,attachQualifyingStructure:()=>bS,attachStructures:()=>ES,automatedPlayoffPositioning:()=>wa,automatedPositioning:()=>Ru,deleteAdHocMatchUps:()=>DC,initializeDraft:()=>UC,luckyDrawAdvancement:()=>yC,luckyLoserDrawPositionAssignment:()=>Wb,modifyDrawDefinition:()=>EC,modifyDrawName:()=>FS,modifySeedAssignment:()=>sC,pruneDrawDefinition:()=>PC,qualifierDrawPositionAssignment:()=>PS,qualifierProgression:()=>Zb,remapDrawDefinitionMatchUpIds:()=>AS,removeDrawPositionAssignment:()=>Bp,removeRoundMatchUps:()=>RC,removeSeededParticipant:()=>IC,removeStructure:()=>mC,renameStructures:()=>cC,resetDrawDefinition:()=>AC,resetQualifyingStructure:()=>pC,resetVoluntaryConsolationStructure:()=>tb,resolveDraftPositions:()=>uC,seedWithdrawalCascade:()=>hC,setDrawParticipantRepresentativeIds:()=>qR,setDrawPositionPreferences:()=>Xb,setPositionAssignments:()=>jb,setStructureOrder:()=>aC,setSubOrder:()=>bC,shiftAdHocRounds:()=>Yb,swapAdHocRounds:()=>qb,swapDrawPositionAssignments:()=>gC,updateTeamLineUp:()=>As,withdrawParticipantAtDrawPosition:()=>Bb});var Gy=t=>e=>t[e],Ul=(t=[])=>t.map(Te).filter(Boolean),_I=(t=[])=>t.map(ft).filter(Boolean),ft=(t={})=>Gy(t)("participantId"),nL=(t={})=>Gy(t)("drawPosition");var Te=(t={})=>Gy(t)("matchUpId"),dc=(t={})=>Gy(t)("drawId");function qR({representativeParticipantIds:t,drawDefinition:e}){if(!e)return{error:Rr};if(!Array.isArray(t))return{error:O};let r=_I(e?.entries??[]);return t.length&&Yt(t,r).length<t.length?{error:O}:MI({drawDefinition:e,extension:{name:Cy,value:t}})}function ki(t,e,r){let n=m=>ot({element:m,name:Rn})?.extension?.value,o=r?.deprioritizeCompleted,i=r?.mode===uR&&Ow,s=r?.mode===cR&&pR,a=s||i||Aa,c=m=>m?.stage===H&&m?.stageSequence===1,u=m=>c(m)?-1:a[m?.stage],p=m=>m?.matchUps.every(({matchUpStatus:d})=>Mt.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)||(xI(t)||0)-(xI(e)||0)}function xI(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 tt(t){let e=X(t,[{[Kt]:!0,[po]:!0}]);if(e.error)return e;let{drawDefinition:r,structureId:n}=t,{structures:o}=In({drawDefinition:r}),i=o?.flatMap(c=>c.structures?[...c.structures].concat(c):c),s=i?.find(c=>c.structureId===n);if(!s)return{error:Nt};let a=s.structureType===tu?i?.find(c=>c.structures?.some(u=>u.structureId===n)):void 0;return{structure:s,containingStructure:a}}function In({withStageGrouping:t,drawDefinition:e,stageSequences:r,stageSequence:n,roundTarget:o,sortConfig:i,stages:s,stage:a}){let c=!e&&$||!e?.structures&&Lg||void 0;if(c)return{error:c,structures:[],stageStructures:{}};let u=f=>{let g=ot({element:f,name:Rn})?.extension?.value;return!o||o===g},p=e?.structures?.filter(d).filter(l).filter(u).sort((f,g)=>ki(f,g,i))??[],m=t?Object.assign({},...Jc.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 Vy({drawDefinition:t}){if(!t)return{error:$};let e={};return{allPositionedParticipantIds:(t.structures??[]).map(n=>{let o=n.stage;e[o]||(e[o]=[]);let{positionAssignments:i}=Pt({structure:n}),s=i?.map(ft).filter(Boolean)??[];return e[o].push(...s),s}).flat(),stagePositionedParticipantIds:e}}function Pt({drawDefinition:t,structureId:e,structure:r}){let n,o=[];if(!r){if(!t)return{positionAssignments:o,error:$};if({structure:r,error:n}=tt({drawDefinition:t,structureId:e}),n)return{positionAssignments:o,error:n}}return r.structures?o=[].concat(...r.structures.map(i=>Pt({structure:i}).positionAssignments)):r.positionAssignments?o=r.positionAssignments:n=LU,{positionAssignments:o,error:n}}function se({drawDefinition:t,structureId:e,structure:r}){let n=Pt({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}}function dt(t,e,r){let n=e.reduce((o,i)=>(o[i]=!0,o),{});return X(t,[n],r)}var wI="addDrawDefinition",zm="addMatchUps",Ti="addParticipants",LI="addScaleItems",$R="addEvent",By="addVenue",Gi="audit",Hy="dataIssue",FI="deleteParticipants",kI="deleteVenue",GI="deletedDrawIds",VI="deletedMatchUpIds",BI="modifyDrawDefinition",KR="modifyDrawEntries",zR="modifyEventEntries",HI="modifyMatchUp",tr="modifyParticipants",WI="modifyPositionAssignments",YI="modifySeedAssignments",ii="modifyTournamentDetail",Eo="modifyVenue",Dl="mutations",Wy="publishEvent",QR="publishEventSeeding",XR="publishOrderOfPlay",JR="publishParticipants",jI="unPublishEvent",qI="unPublishEventSeeding",$I="unPublishOrderOfPlay",ZR="unPublishParticipants",Rl="unPublishTournament",Up="updateInContextMatchUp",oL={ADD_DRAW_DEFINITION:wI,ADD_MATCHUPS:zm,ADD_PARTICIPANTS:Ti,ADD_SCALE_ITEMS:LI,ADD_EVENT:$R,ADD_VENUE:By,AUDIT:Gi,DATA_ISSUE:Hy,DELETE_PARTICIPANTS:FI,DELETE_VENUE:kI,DELETED_DRAW_IDS:GI,DELETED_MATCHUP_IDS:VI,MODIFY_DRAW_DEFINITION:BI,MODIFY_DRAW_ENTRIES:KR,MODIFY_EVENT_ENTRIES:zR,MODIFY_MATCHUP:HI,MODIFY_PARTICIPANTS:tr,MODIFY_POSITION_ASSIGNMENTS:WI,MODIFY_SEED_ASSIGNMENTS:YI,MODIFY_TOURNAMENT_DETAIL:ii,MODIFY_VENUE:Eo,MUTATIONS:Dl,PUBLISH_EVENT_SEEDING:QR,PUBLISH_EVENT:Wy,PUBLISH_ORDER_OF_PLAY:XR,PUBLISH_PARTICIPANTS:JR,UNPUBLISH_EVENT_SEEDING:qI,UNPUBLISH_EVENT:jI,UNPUBLISH_ORDER_OF_PLAY:$I,UNPUBLISH_PARTICIPANTS:ZR,UNPUBLISH_TOURNAMENT:Rl,UPDATE_INCONTEXT_MATCHUP:Up};function Yy(t,e){if(!t)return{error:$};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)}),{...P}}function iL(t){if(!t)return;let e=Date.now(),r=t.updatedAt;if(r){let n=typeof r=="string"?new Date(r).getTime():r.getTime();!Number.isNaN(n)&&e<=n&&(e=n+1)}t.updatedAt=new Date(e).toISOString()}function ko({drawDefinition:t,tournamentId:e,matchUps:r,eventId:n}){if(t&&Yy(t),Array.isArray(r))for(let o of r)iL(o);return at({payload:{matchUps:r,tournamentId:e,eventId:n},topic:zm}),{...P}}function xn({drawDefinition:t,tournamentId:e,matchUpIds:r,eventId:n,action:o}){t&&Yy(t),at({topic:VI,payload:{tournamentId:e,matchUpIds:r,eventId:n,action:o}});for(let i of r)YT({key:i});return{...P}}function gt({drawDefinition:t,tournamentId:e,structureId:r,context:n,eventId:o,matchUp:i}){return i?(t&&Ft({drawDefinition:t,structureIds:r?[r]:void 0,tournamentId:e,eventId:o}),iL(i),at({topic:HI,payload:{matchUp:i,tournamentId:e,context:n},key:i.matchUpId}),{...P}):(console.log(Xe),{error:Xe})}function sL({tournamentId:t,inContextMatchUp:e}){return e?(at({payload:{inContextMatchUp:e,tournamentId:t},topic:Up,key:e.matchUpId}),{...P}):{error:Xe}}function lc({tournamentId:t,eventId:e,drawDefinition:r}){return r?(Yy(r),at({payload:{drawDefinition:r,tournamentId:t,eventId:e},topic:wI,key:r.drawId}),{...P}):(console.log($),{error:$})}function aL({tournamentId:t,eventId:e,drawId:r}){return at({payload:{drawId:r,tournamentId:t,eventId:e},topic:GI,key:r}),YT({key:r}),{...P}}function Ft({drawDefinition:t,tournamentId:e,structureIds:r,eventId:n}){return t?(Yy(t,r),at({payload:{tournamentId:e,eventId:n,drawDefinition:t},topic:BI,key:t.drawId}),{...P}):{error:$}}function bl({drawDefinition:t,tournamentId:e,structure:r,eventId:n}){let o=dt({drawDefinition:t,structure:r},[Kt,oc]);if(o.error)return o;let i=r.seedAssignments,s=r.structureId,a=t.drawId;return at({payload:{tournamentId:e,eventId:n,drawId:a,structureId:s,seedAssignments:i},topic:YI,key:t.drawId}),Ft({structureIds:[s],drawDefinition:t,tournamentId:e,eventId:n}),{...P}}function Sn({drawDefinition:t,tournamentId:e,structure:r,event:n}){let o=dt({drawDefinition:t,structure:r},[Kt,oc]);if(o.error)return o;let i=Pt({structure:r}),s=r.structureId,a=t.drawId,c=n?.eventId;return at({topic:WI,payload:{positionAssignments:i,tournamentId:e,structureId:s,eventId:c,drawId:a},key:s}),Ft({structureIds:[s],drawDefinition:t,tournamentId:e,eventId:c}),{...P}}function tb({tournamentRecord:t,drawDefinition:e,resetEntries:r,event:n}){if(!e)return{error:$};let o=e.structures?.find(s=>s.stage===Fe);if(!o)return{error:Nt};let i=o.matchUps?.map(({matchUpId:s})=>s)??[];return o.positionAssignments=[],o.seedAssignments=[],o.matchUps=[],xn({tournamentId:t?.tournamentId,action:"resetVoluntaryConsolationStructure",matchUpIds:i,drawDefinition:e}),r&&(e.entries=e.entries.filter(s=>s.entryStage!==Fe)),Ft({tournamentId:t?.tournamentId,eventId:n?.eventId,drawDefinition:e,structureIds:[o.structureId]}),{...P}}function Cl({drawPositions:t,structure:e}){if([Z,H].includes(e.stage)&&e.stageSequence===1)return;let{positionAssignments:r}=Pt({structure:e});r?.filter(({drawPosition:o})=>t?.includes(o))?.forEach(o=>{ut({element:o,extension:{name:yl,value:!0}})})}function fc(t){let{appliedPolicies:e,positionAction:r,drawDefinition:n}=t;if(e?.audit?.[su]===!1)return;let{extension:o}=ot({name:su,element:n}),i=Array.isArray(o?.value)?o?.value??[]:[];if(!i?.length){let a=n.structures.find(c=>c.stage===H);if(a){let c=Pt({structure:a}).positionAssignments?.map(({drawPosition:u,participantId:p,bye:m,qualifier:d})=>({drawPosition:u,participantId:p,qualifier:d,bye:m}));i.push({name:"initialMainAssignments",initialAssignments:c})}}let s={value:i.concat(r),name:su};ut({element:n,extension:s})}function Vi({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}}function Dp(t){let{sides:e,matchUpType:r}=t??{},n=t.potentialParticipants?.length?t.potentialParticipants.flat().map(s=>r===Rt?s?.individualParticipantIds??[]:s.participantId).flat():[],o=(e??[]).map(s=>r===Rt&&(s?.participant?.individualParticipantIds??[])||s?.participantId&&[s.participantId]||[]).flat();return{individualParticipantIds:o.concat(n).flat(),enteredIndividualParticipantIds:o,potentialIndividualParticipantIds:n}}function Ar(t){return t?.tournamentRecords??(t?.tournamentRecord&&{[t.tournamentRecord.tournamentId]:t.tournamentRecord})??{}}var uu="SIGN_IN_STATUS",eb="SIGNED_OUT",Rp="SIGNED_IN",ur="TEAM",St="INDIVIDUAL",qr="GROUP",lt="PAIR",vt="TEAM",bp={TEAM_PARTICIPANT:ur,INDIVIDUAL:St,GROUP:qr,TEAM:vt,PAIR:lt},cL={INDIVIDUAL:St,GROUP:qr,PAIR:lt,TEAM:vt,SIGN_IN_STATUS:uu,SIGNED_OUT:eb,SIGNED_IN:Rp};function Cp({participantsProfile:t,participants:e=[],deepCopy:r}){let n=new Map,o=r!==!1?q(e,t?.convertExtensions,!0):e,i=o.filter(c=>c.participantType===vt),s=o.filter(c=>c.participantType===qr),a=o.filter(c=>c.participantType===lt);return o.forEach(c=>{if(c.participantType===St){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 rb(t){return t&&typeof String.fromCodePoint<"u"?t.toUpperCase().replace(/./g,e=>String.fromCodePoint(e.charCodeAt(0)+127397)):t}function uL(t){let e=Object.assign({},...yi.filter(r=>r.ioc).map(r=>({[r.ioc]:r.iso})));return rb(e[t])}var yi=[{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 jy({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=yi.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 pL({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?fs({template:e,source:s}):s)}}}}function Ao(t){let{tournamentRecord:e,participantId:r}=t,n=t.tournamentRecords||e&&{[e.tournamentId]:e}||{};for(let o of Object.values(n)){let i=o.participants?.find(s=>s.participantId===r);if(i)return{participant:i,tournamentId:o.tournamentId}}return{error:ee}}function qy(t){let{tournamentRecord:e,participantId:r}=t;if(r){let o=Ao({tournamentRecord:e,participantId:r});return o.participant??o}let n=t.element||t.drawDefinition||t.event||t.tournamentRecord;return n||{error:nt}}function Jr(t){let{returnPreviousValues:e,itemSubTypes:r,itemType:n}=t,o=qy(t);if(o.error)return o;if(r&&!Array.isArray(r))return{error:O,context:{itemSubTypes:r}};if(!Array.isArray(o.timeItems))return{error:Zg};let i=o.timeItems.filter(a=>a?.itemType===n).filter(a=>!r?.length||r.some(c=>a?.itemSubTypes?.includes(c))).sort((a,c)=>{let u=new Date(a.createdAt||void 0).getTime(),p=new Date(c.createdAt||void 0).getTime();return u-p}),s=q(i.pop(),!1,!0);if(s){let a={timeItem:s,...P};return e&&Object.assign(a,{previousItems:i}),a}else return{info:fe}}function $y({returnPreviousValues:t,drawDefinition:e,itemSubTypes:r,itemType:n}){if(!e)return{error:Pn};if(!e.timeItems)return{info:fe};let{timeItem:o,previousItems:i,info:s}=Jr({element:e,returnPreviousValues:t,itemSubTypes:r,itemType:n});return o&&{timeItem:o,previousItems:i}||{info:s}}function Mp({returnPreviousValues:t,itemSubTypes:e,itemType:r,event:n}){if(!n)return{error:le};if(!n.timeItems)return{info:fe};let{timeItem:o,previousItems:i,info:s}=Jr({returnPreviousValues:t,element:n,itemSubTypes:e,itemType:r});return o&&{timeItem:o,previousItems:i}||{info:s}}function Ml({returnPreviousValues:t,tournamentRecord:e,itemSubTypes:r,itemType:n}){if(!e)return{error:j};if(!e.timeItems)return{info:fe};let{timeItem:o,previousItems:i,info:s}=Jr({element:e,returnPreviousValues:t,itemSubTypes:r,itemType:n});return o&&{timeItem:o,previousItems:i}||{info:s}}function Ky({returnPreviousValues:t,tournamentRecord:e,participantId:r,itemSubTypes:n,itemType:o}){let i=dt({tournamentRecord:e,participantId:r},[rt,sr]);if(i.error)return i;let s=Ao({tournamentRecord:e,participantId:r});if(s.error)return s;let{participant:a}=s;if(!a?.timeItems)return{info:fe};let{timeItem:c,previousItems:u,info:p}=Jr({element:s.participant,returnPreviousValues:t,itemSubTypes:n,itemType:o});return c&&{timeItem:c,previousItems:u}||{info:p}}var xY={[qr]:"groupParticipantIds",[lt]:"pairParticipantIds",[vt]:"teamParticipantIds"},wY={[qr]:"groups",[vt]:"teams"};function zy({withIndividualParticipants:t,convertExtensions:e,tournamentRecord:r,withSignInStatus:n,withScaleValues:o,withGroupings:i,internalUse:s,withISO2:a,withIOC:c}){let u=[],p={};for(let d of r.participants??[]){let l=d?.participantId;l&&kY({participantMap:p,participantId:l})}for(let d of r.participants??[]){let l=q(d,e,s),{participantId:f,individualParticipantIds:g,participantType:I}=l;if(!p[f]){u.push(f);continue}if(Object.assign(p[f].participant,l),g){let S=FY({individualParticipantIds:g,participantCopy:l,participantMap:p,participantType:I,participantId:f});S.missingParticipantIds.length&&u.push(...S.missingParticipantIds)}if(n&&(p[f].participant.signedIn=LY(l)),o){let{ratings:S,rankings:h,seedings:T}=sc({participant:l});p[f].participant.seedings=T,p[f].participant.rankings=h,p[f].participant.ratings=S}(c||a)&&jy({participant:p[f].participant,withISO2:a,withIOC:c})}if(t){let d=Tt(t)?t:void 0;pL({participantMap:p,template:d})}let m;return i&&(m=Cp({participants:Object.values(p).map(({participant:d})=>d),participantsProfile:{convertExtensions:e},deepCopy:!1}).groupInfo),{missingParticipantIds:u,participantMap:p,groupInfo:m}}function LY(t){let{timeItem:e}=Jr({itemType:uu,element:t});return e?.itemValue===Rp}function FY({individualParticipantIds:t,participantCopy:e,participantMap:r,participantType:n,participantId:o}){let i=[];for(let s of t){let a=r[s]?.participant;if(!a){i.push(s);continue}if(a[xY[n]].push(o),[vt,qr].includes(n)){let{participantRoleResponsibilities:c,participantOtherName:u,participantName:p,participantId:m,teamId:d}=e,l=wY[n];a[l].push({participantRoleResponsibilities:c,participantOtherName:u,participantName:p,participantId:m,teamId:d})}if(n===lt){let c=t.find(u=>u!==s);r[s].pairIdMap[o]=c,r[s].pairIdMap[c]=o}}return{missingParticipantIds:i}}function kY({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:{[Ct]:{...r},[Rt]:{...r},[vt]:{...r},...r}}}function si({participantsProfile:t,useParticipantMap:e,tournamentRecord:r,contextProfile:n,inContext:o}){if(e)return zy({...t,...n,tournamentRecord:r});let i=q(r.participants,!1,!0)??[];(t?.withIOC||t?.withISO2)&&i.forEach(a=>jy({participant:a,...t}));let s;if((o||t?.withGroupings)&&i?.length&&({participantsWithGroupings:i,groupInfo:s}=Cp({participantsProfile:t,deepCopy:!1,participants:i})),t?.withScaleValues&&i?.length)for(let a of i){let{ratings:c,rankings:u}=sc({participant:a});a.rankings=u,a.ratings=c}return{participants:i,groupInfo:s}}var Qy="WALKOVER",nb="RETIRED",vl="COMPETITIVE",pu="ROUTINE",mu="DECISIVE",Ol="winRatio";var GY={[xi]:{policyName:"Competitive Bands Default",profileBands:{[mu]:20,[pu]:50}}},_l=GY;function to({policyDefinitions:t,tournamentRecord:e,contextProfile:r,drawDefinition:n,event:o}){let i={policies:{}};if(!r)return i;let s=lo({tournamentRecord:e,drawDefinition:n,event:o}).policyDefinitions;if(r.withCompetitiveness){let a=t?.[xi]??s?.[xi]??_l[xi];i.policies[xi]=a}return i}function Ei({tournamentRecord:t,drawDefinition:e,policyType:r,structure:n,event:o}){if(!t)return{error:j};let{appliedPolicies:i}=It({tournamentRecord:t,drawDefinition:e,structure:n,event:o});return i?.[r]?{policy:i[r]}:{info:Xu?.message}}function gc({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}=Ei({policyType:_o,tournamentRecord:t,event:n}),s=(t?ot({element:t,name:oi}).extension:void 0)?.value,c=(n&&ot({name:oi,element:n}).extension)?.value;return{scheduleTiming:{tournamentScheduling:s,eventScheduling:c,categoryName:e,categoryType:r,policy:o}}}function KI({tournamentRecord:t,event:e}){if(!t)return{};let{extension:r}=ot({element:t,name:AR}),n=r?.value;if(!n?.events?.length)return{};let o=e?n.events.find(s=>s.eventType===e.eventType&&(!s.eventName||s.eventName===e.eventName)&&(!s.category?.categoryName||s.category?.categoryName===e.category?.categoryName)):void 0;if(!o)return{};let i={};return o.drawSize!==void 0&&(i.drawSize=o.drawSize),o.maxWildcards!==void 0&&(i.maxWildcards=o.maxWildcards),o.maxAlternates!==void 0&&(i.maxAlternates=o.maxAlternates),o.maxQualifiers!==void 0&&(i.maxQualifiers=o.maxQualifiers),Object.keys(i).length?{constraints:i}:{}}var du="GEMscore",mL={GEM_SCORE:du};function dL({provisionalPositioning:t,rankBy:e=du,finishingPositions:r,groupResults:n,bestOf:o}){let i=[],s=[],a=[...r].sort(Zt),c=Math.max(...a);for(let{structureId:d,results:l}of n)for(let[f,g]of Object.entries(l)){let I=g.groupOrder||t&&g.provisionalOrder;if(!I)continue;let S={groupingValue:d,GEMscore:g.GEMscore,isBestFinisher:!1,finishingPosition:I,participantId:f};a.includes(I)?s.push(S):I>c&&i.push(S)}let u=[...s],p=o-s.length;p>0&&i.length>0&&i.toSorted((f,g)=>f.finishingPosition!==g.finishingPosition?f.finishingPosition-g.finishingPosition:e===du?(g.GEMscore??0)-(f.GEMscore??0):0).slice(0,p).forEach(f=>{f.isBestFinisher=!0,u.push(f)});let m={};for(let d of u){let l=d.finishingPosition;m[l]=(m[l]||0)+1}return{selectedParticipants:u,consumedPositions:m}}var Zr="ALTERNATE",zI="CONFIRMED",wr="DIRECT_ACCEPTANCE",vp="FEED_IN",QI="JUNIOR_EXEMPT",ks="LUCKY_LOSER",XI="ORGANISER_ACCEPTANCE",xl="QUALIFIER",VY="REGISTERED",JI="SPECIAL_EXEMPT",Lr="UNGROUPED",Bi="UNPAIRED",Op="WILDCARD",Cn="WITHDRAWN",Qm=[zI,wr,QI,XI,JI],ob=[vp,ks,xl],Hi=[zI,wr,vp,QI,XI,JI,Op],hr=[zI,wr,QI,ks,xl,XI,JI,Op],ib=[Zr,zI,wr,vp,QI,ks,XI,xl,VY,JI,Lr,Bi,Op,Cn],lL={ALTERNATE:Zr,CONFIRMED:zI,DIRECT_ACCEPTANCE:wr,DIRECT_ENTRY_STATUSES:Hi,DRAW_SPECIFIC_STATUSES:ob,EQUIVALENT_ACCEPTANCE_STATUSES:Qm,FEED_IN:vp,JUNIOR_EXEMPT:QI,LUCKY_LOSER:ks,ORGANISER_ACCEPTANCE:XI,QUALIFIER:xl,SPECIAL_EXEMPT:JI,STRUCTURE_SELECTED_STATUSES:hr,UNGROUPED:Lr,UNPAIRED:Bi,VALID_ENTRY_STATUSES:ib,WILDCARD:Op,WITHDRAWN:Cn};function fL({stage:t,drawDefinition:e}){return Jc.includes(t)?e?.structures?.some(n=>n.stage===t)||Jc.includes(t):!1}function Xy({stage:t,drawDefinition:e,entryStatus:r}){return e.entries.reduce((n,o)=>o.entryStage===t&&o.entryStatus===r?n+1:n,0)}function Wi({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=ot({name:Rn,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===Vt){let{playoffEntries:p,error:m}=BY({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 BY({provisionalPositioning:t,drawDefinition:e,structureId:r}){let n=[],o=(e.links??[]).find(i=>i.linkType===fn&&i.target.structureId===r);if(o){let{finishingPositions:i,structureId:s,bestOf:a,rankBy:c}=o.source,{structure:u}=tt({drawDefinition:e,structureId:s});if(u?.structureType===de){let m=(u.structures??[]).map(d=>{let l=d.positionAssignments??[],{structureId:f}=d,g=Object.assign({},...l.map(I=>{let{participantId:S}=I,h=ot({element:I,name:Lo}).extension?.value;return h&&S?{[S]:h}:void 0}).filter(Boolean));return{structureId:f,results:g}});if(o.source.remainder)HY({provisionalPositioning:t,allGroupResults:m,drawDefinition:e,playoffEntries:n,inboundLink:o,structureId:s});else if(a!==void 0&&i){let{selectedParticipants:d}=dL({groupResults:m,provisionalPositioning:t,finishingPositions:i,bestOf:a,rankBy:c});d.forEach(l=>{let g=i.includes(l.finishingPosition)?[...i].sort(Zt).indexOf(l.finishingPosition)+1:[...i].sort(Zt).length+1;n.push({isBestFinisher:l.isBestFinisher,groupingValue:l.groupingValue,participantId:l.participantId,GEMscore:l.GEMscore,entryStatus:vp,entryStage:Vt,placementGroup:g})})}else WY({provisionalPositioning:t,finishingPositions:i,allGroupResults:m,playoffEntries:n})}}return{playoffEntries:n}}function HY({provisionalPositioning:t,allGroupResults:e,drawDefinition:r,playoffEntries:n,inboundLink:o,structureId:i}){let s=new Set,a=(r.links??[]).filter(c=>c.linkType===fn&&c.source.structureId===i&&c.target.structureId!==o.target.structureId&&c.source.bestOf!==void 0);for(let c of a){let{structure:u}=tt({structureId:c.target.structureId,drawDefinition:r});if(u)for(let p of u.positionAssignments??[])p.participantId&&s.add(p.participantId)}e.forEach(({structureId:c,results:u})=>{Object.keys(u).forEach(p=>{if(!s.has(p)){let m=u[p],{groupOrder:d,provisionalOrder:l,GEMscore:f}=m,g=d||t&&l;n.push({groupingValue:c,entryStage:Vt,entryStatus:vp,placementGroup:g||1,participantId:p,GEMscore:f})}})})}function WY({provisionalPositioning:t,finishingPositions:e,allGroupResults:r,playoffEntries:n}){r.forEach(({structureId:o,results:i})=>{let s=o,c=Object.keys(i).reduce((p,m)=>{let d=i[m],l=d.groupOrder||t&&d.provisionalOrder;return p.includes(l)||p.push(l),p},[]).length===Object.keys(i).length,u=Object.keys(i).filter(p=>{let m=i[p],d=m.groupOrder||t&&m.provisionalOrder;return e?.includes(d)});(!t||c)&&u.forEach(p=>{let m=i[p],{groupOrder:d,provisionalOrder:l,GEMscore:f}=m,g=d||t&&l,I=[...e??[]].sort(Zt).indexOf(g)+1;n.push({entryStage:Vt,entryStatus:vp,placementGroup:I,groupingValue:s,participantId:p,GEMscore:f})})})}function Pr({provisionalPositioning:t,returnAllProxies:e,drawDefinition:r,structureId:n,structure:o}){let i,s=[];o||({structure:o,error:i}=tt({drawDefinition:r,structureId:n}));let a=Pt({structure:o}).positionAssignments;if(i||!o)return{seedAssignments:[],error:Nt};n||(n=o.structureId);let{stage:c,stageSequence:u}=o,m=c===Vt&&r&&Wi({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 S=I+1;return{participantId:g.participantId,seedValue:S,seedProxy:!0,seedNumber:S}}):[],l=d?.slice(0,e?d.length:a.length/2);l.length?s=l:o.seedAssignments?s=o.seedAssignments:i=RU;let f=o.seedLimit??o?.positionAssignments?.length;return{seedAssignments:s,stageSequence:u,seedLimit:f,stage:c,error:i}}function Go(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 Xm({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 ze({drawDefinition:t,structure:e,matchUp:r,event:n}){return{tieFormat:Xm({item:r,drawDefinition:t,structure:e,event:n})||Xm({item:e,drawDefinition:t,structure:e,event:n})||Go(t)||Go(n)}}function gL({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 Ie({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 Vo({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(q(u,!0,!0),{containerStructureId:r,structureId:s,structureName:c})):a}).flat();return(o?.matchUps??[]).concat(...i)}function Jy({groupedOrder:t,roundPositionsCount:e}){if(!t||t?.length<=e)return t;let n=he(t,t.length/e).map(i=>i.reduce((s,a)=>s+a)),o=n.slice().sort(Zt);return n.map(i=>o.indexOf(i)+1)}function ZI(t){if(!Tt(t))return!1;let{matchUpId:e,drawPositions:r}=t,n=typeof e=="string",o=!r||Array.isArray(r)&&r.length<=2&&r.every(i=>yt(i)||i===void 0||i===null);return n&&o}function Nr(t){return Array.isArray(t)?t.every(ZI):!1}function YY(t,e){return e?.find(r=>t.includes(r))}function De({matchUps:t=[],interpolate:e}){if(!Nr(t))return{roundMatchUps:[],error:O};let r=t.reduce((d,l)=>{let f=typeof l.roundNumber=="string"?st(l.roundNumber):l.roundNumber;return!l.roundNumber||d.includes(f)?d:d.concat(f)},[]).sort(Zt).map(d=>{let l=t.filter(S=>S.roundNumber===d),g=l.find(({matchUpType:S})=>S===Ot)?l.filter(({matchUpType:S})=>S===Ot):l,I=S=>S.sort((h,T)=>Zt(h.roundPosition,T.roundPosition));return{[d]:I(g)}}),n=t.reduce((d,l)=>{let f=typeof l.roundNumber=="string"?st(l.roundNumber):l.roundNumber;return d[f]||(d[f]=et({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=>st(f)).filter(f=>!Number.isNaN(f))),l=o[d]?.length;if(l>1&&en(l)){let f=d+1,g=f+l/2;Q(f,g).forEach((S,h)=>{o[S]=Q(0,l/(2+h*2)).map(()=>({}))})}}let i=0,s=Object.assign({},...Object.keys(o).map(d=>{let l=o[d]?.length,f=o[d]?.filter(I=>!Mt.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=>st(d)).filter(d=>!Number.isNaN(d));u.forEach(d=>{let l=o[d].sort((g,I)=>g.roundPosition-I.roundPosition),f=l.flatMap(g=>g?.drawPositions??[]);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(Zt),I=he(g,2);s[d].drawPositions=g,s[d].pairedDrawPositions=I}else{let g=s[d-1],I=g.drawPositions,S=g.matchUpsCount/s[d].matchUpsCount,h=he(I,S),T=l.map(y=>{let{roundPosition:E}=y,A=[...y.drawPositions??[],void 0,void 0].slice(0,2);if(!E)return A;let N=A?.filter(Boolean)??[];if(!N?.length)return[void 0,void 0];if(d<3&&N?.length===2)return A?.slice().sort(Zt);let U=Yt(I,N).length!==N?.length;if(N?.length&&U)return N?.length===1?[N[0],void 0]:A?.slice().sort(Zt);let R=(E-1)*2;return h.slice(R,R+2).map(b=>YY(b,N))});s[d].drawPositions=T?.flat(),s[d].pairedDrawPositions=T}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).some(({matchUpsCount:d})=>!en(d));return{hasNoRoundPositions:t.some(d=>!d.roundPosition),roundsNotPowerOf2:p,maxMatchUpsCount:i,roundMatchUps:o,roundNumbers:u,roundProfile:s,...P}}function wl(t){if(!Array.isArray(t))return"";let e=t.filter(Le);return e.length?pt([Math.min(...e),Math.max(...e)]).join("-"):""}function IL({drawDefinition:t,structureId:e,matchUpsMap:r}){let n=dt({drawDefinition:t,structureId:e},[Kt,po]);if(n.error)return n;let{structure:o}=tt({drawDefinition:t,structureId:e});if(o?.stage!==me)return{error:tc,info:"Structure is not CONSOLATION stage"};let{links:i}=t,s=i?.filter(d=>d.target.structureId===e)??[],a=s?.reduce((d,l)=>{let{structureId:f}=l.source;return d.includes(f)?d:d.concat(f)},[])??[],c=Object.assign({},...a.map(d=>{let l=Vo({structureId:d,matchUpsMap:r}),g=De({matchUps:l}).roundProfile;return{[d]:g}})),u=Vo({matchUpsMap:r,structureId:e}),{roundProfile:p}=De({matchUps:u}),m={};return s?.forEach(d=>{let{structureId:l,roundNumber:f}=d.source,{feedProfile:g,groupedOrder:I,positionInterleave:S,roundNumber:h}=d.target,T=c[l],y=T[1]?.drawPositions,A=T[f]?.matchUpsCount;if(!A)return;let N=A?y.length/A:0,U=y.length/N,R=y.slice(),D=Jy({roundPositionsCount:U,groupedOrder:I}),b=D?.length||1;if(b<=U){let w=y.length/b,L=he(R,w);g===Oi&&L.forEach(F=>F.reverse()),R=D?.length&&D?.map(F=>L[F-1]).flat()||L.flat()}let C=he(R,N);if(S){let w=Q(0,S.interleave).map(()=>{}),L=Q(0,S.offset).map(()=>{});C=C.map(x=>[x,...w]),C.unshift(L),C=C.flat(1);let F=C.length-S.offset;C=C.slice(0,F)}m[h]||(m[h]={});let v=p?.[h]?.feedRound?2:1;C.forEach((w,L)=>{let F=1+L*v;m[h][F]||(m[h][F]=wl(w))})}),{sourceDrawPositionRanges:m}}function Ll({drawDefinition:t}){if(typeof t!="object")return{error:ma};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"&&[me,Vt].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,S=r.find(T=>T.structureId===I).stage,h=[S,I,g,f].join("|");if(p[h])return;p[h]=!0,i({exitProfile:`${a}-${f}`,structureId:I,exitProfiles:s,targetRound:g,aggregator:p,stage:S})}}}function SL({drawDefinition:t,roundProfile:e,structureId:r,matchUpsMap:n}){let o=dt({drawDefinition:t,structureId:r},[Kt,po]);if(o.error)return o;if(!e){let u=Vo({matchUpsMap:n,structureId:r});if({roundProfile:e}=De({matchUps:u}),!e)return{error:nt}}let s=(Math.min(...e?.[1]?.drawPositions??[])||1)-1,a=Object.keys(e);return{drawPositionsRanges:Object.assign({},...(a??[]).map(u=>{let p=e?.[u]?.matchUpsCount,m=e?.[1]?.drawPositions??[],d=he(m,m.length/p),l=d.map(wl),f=d.map(T=>T.map(y=>y-s)).map(wl),g=a.map(T=>{if(T>u)return;let y=e?.[T]?.drawPositions??[];return he(y,y.length/p)}).filter(Boolean),I=Q(0,p).map(T=>g.map(y=>y[T]).flat().filter(Boolean).sort(Zt)).map(T=>pt(T)),S=I.map(T=>Qx(T).map(wl).join(", ")),h=Object.assign({},...Q(0,p).map(T=>({[T+1]:{firstRoundDrawPositionsRange:l[T],firstRoundOffsetDrawPositionsRange:f[T],possibleDrawPositions:I[T],drawPositionsRange:S[T]}})));return{[u]:h}}))}}var jY=new Set([ws,nc]);function an(t){return!!t&&jY.has(t)}function tS({structure:t,matchUps:e}){e=e??t?.matchUps??[];let r=De({matchUps:e}),n=r.roundProfile,o=r.roundNumbers;if(!n||!o?.length||o.length<2)return!1;let i=[...o].sort((s,a)=>s-a);for(let s=0;s<i.length-1;s++){let a=n[i[s]]?.matchUpsCount??0,c=n[i[s+1]]?.matchUpsCount??0;if(a%2===1&&c%2===0)return!0}return!1}function Ic({roundsNotPowerOf2:t,drawDefinition:e,structure:r,matchUps:n}){return!r||(n=n??r.matchUps??[],t=t??De({matchUps:n}).roundsNotPowerOf2,!(!!r.positionAssignments?.find(({drawPosition:i})=>i)||!!n?.find(({drawPositions:i})=>i?.length))||r?.structures)||e?.drawType&&an(e.drawType)||!t?!1:tS({structure:r,matchUps:n})}function Ae({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?.stage===Fe?t?.structures||t?.structureType===tu&&n?!1:t?.finishingPosition===uo:!t?.structures&&(!e.length||!r&&!n)}var eS={[Oo]:{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:{[H]:"",[Vt]:"P",[Z]:"Q",[me]:"C"}}},hL=eS;function Zy({roundNamingPolicy:t,drawDefinition:e,structure:r,matchUps:n}){let{roundProfile:o,roundMatchUps:i}=De({matchUps:n}),{structureAbbreviation:s,stage:a}=r,c=Ae({structure:r}),u=Ic({structure:r}),p=r.structures,m={},d=eS[Oo],l=r.stage===Z,f=l?Math.max(...(e?.structures??[]).filter(_=>_.stage===Z).map(({stageSequence:_})=>_??1),0):0,g=(r.stageSequence??1)<f?r.stageSequence??1:"",I=g&&(t?.affixes?.preQualifying||d.affixes.preQualifying)||"",S=t?.roundNamingMap||(d.roundNamingMap??{}),h=t?.abbreviatedRoundNamingMap||(d.abbreviatedRoundNamingMap??{}),T=t?.affixes?.preFeedRound||d.affixes.preFeedRound,y=t?.affixes?.roundNumber||d.affixes.roundNumber,A=(t?.namingConventions||d.namingConventions).round,N=a&&a!==H?a[0]:"",U=t?.stageConstants||d.stageConstants,R=a&&U?.[a]||N,D=`${I}${R}${g}`,b=o?Object.keys(o):[],C=l&&U?.[Z]?`${U?.[Z]}-`:"";if(p||c||u)Object.assign(m,...b.map(_=>{let v=`${C}${A} ${_}`,w=`${y}${_}`;return{[_]:{roundName:v,abbreviatedRoundName:w}}}));else{let _=l&&(t?.qualifyingFinishMap||(d?.qualifyingFinishMap??{}));Object.assign(m,...b.map(v=>{if(!o?.[v])return;let{matchUpsCount:w,preFeedRound:L}=o[v],F=w*2,x=_?.[o?.[v].finishingRound]||_&&`${y}${F}`||S[w]||`${y}${F}`,k=L?`-${T}`:"",G=`${x}${k}`,V=[D,s,G].filter(Boolean).join("-"),z=`${h[w]||`${y}${F}`}${k}`,W=[D,s,z].filter(Boolean).join("-");return{[v]:{abbreviatedRoundName:W,roundName:V}}}))}return{roundNamingProfile:m,roundProfile:o,roundMatchUps:i}}var qY=(t,e)=>(t||0)+(e||0);function tE(t,e){let r=Array.isArray(t)?t[0]:t;return Number.isNaN(r)&&Qy||r<=e[mu]&&mu||r<=e[pu]&&pu||vl}function Fl({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(qY)&&(r[n[0]>n[1]?0:1]+=1),{sets:e,games:r,score:t}}function $Y(t){let e=Math.min(...t.games),r=Math.max(...t.games);return Math.round(e/r*100)}function eE(t){return t.map($Y).sort((e,r)=>e-r).map(e=>parseFloat(e.toFixed(2)))}function Sc({tournamentRecord:t,profileBands:e,matchUp:r}){if(!r)return{error:Xe};let{score:n,winningSide:o}=r;if(!o)return{error:O};let i=!e&&t&&Ei({policyType:xi,tournamentRecord:t}).policy,s=e||i?.profileBands||_l[xi].profileBands,a=Fl({score:n}),c=eE([a]),u=tE(c,s),p=Array.isArray(c)?c[0]:c;return{...P,competitiveness:u,pctSpread:p}}function rE({matchUp:t}){if(!t)return{error:Xe};if(t&&!t.sides)return{error:cr};if(t&&!t.hasContext)return{error:ep};let e=(t.sides??[])?.map(a=>a?.participantId).filter(Boolean),r=t.sides?.filter(a=>a.participant?.participantType===St).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,...P}}var kl="CHECK_IN",Gl="CHECK_OUT",KY="SCHEDULE",gs="SCHEDULE.ASSIGNMENT.VENUE",fo="SCHEDULE.ALLOCATION.COURTS",ai="SCHEDULE.ASSIGNMENT.COURT",lu="SCHEDULE.COURT.ORDER",fu="SCHEDULE.COURT.ANNOTATION",Is="SCHEDULE.DATE",zY="COMPLETED.DATE",Vl="HOME_PARTICIPANT_ID",rS="SCHEDULE.ASSIGNMENT.OFFICIAL",Ss="SCHEDULE.TIME.SCHEDULED",ci="SCHEDULE.TIME.START",Ca="SCHEDULE.TIME.STOP",Gs="SCHEDULE.TIME.RESUME",hs="SCHEDULE.TIME.END",Jm="SCHEDULE.TIME.MODIFIERS",TL="TO_BE_ANNOUNCED",yL="NEXT_AVAILABLE",EL="FOLLOWED_BY",AL="AFTER_REST",PL="RAIN_DELAY",QY="NOT_BEFORE",nE=[TL,yL,EL,AL,PL],XY="ELIGIBILITY",JY="REGISTRATION",ZY="SUSPENSION",tj="MEDICAL",ej="PENALTY",sb="SCALE",ab="RATING",cb="RANKING",nS="SEEDING",Bo="PUBLISH",Ur="PUBLIC",Ho="STATUS",rj="MODIFICATION",nj="RETRIEVAL",oj="other",NL={MUTUALLY_EXCLUSIVE_TIME_MODIFIERS:nE,AFTER_REST:AL,ALLOCATE_COURTS:fo,ASSIGN_COURT:ai,ASSIGN_OFFICIAL:rS,ASSIGN_VENUE:gs,CHECK_IN:kl,CHECK_OUT:Gl,COMPLETED_DATE:zY,COURT_ANNOTATION:fu,COURT_ORDER:lu,ELIGIBILITY:XY,END_TIME:hs,FOLLOWED_BY:EL,MEDICAL:tj,MODIFICATION:rj,NEXT_AVAILABLE:yL,NOT_BEFORE:QY,OTHER:oj,PENALTY:ej,PUBLIC:Ur,PUBLISH:Bo,RANKING:cb,RATING:ab,RAIN_DELAY:PL,REGISTRATION:JY,RESUME_TIME:Gs,RETRIEVAL:nj,SCALE:sb,SCHEDULE:KY,SCHEDULED_DATE:Is,SCHEDULED_TIME:Ss,SEEDING:nS,START_TIME:ci,STATUS:Ho,STOP_TIME:Ca,SUSPENSION:ZY,TIME_MODIFIERS:Jm,TO_BE_ANNOUNCED:TL};function Vs({matchUp:t}){if(!t)return{error:Xe};if(!t.hasContext)return{error:ep};if(!t.sides||t?.sides.filter(Boolean).length!==2)return{error:cr};let{nestedIndividualParticipantIds:e,allRelevantParticipantIds:r,sideParticipantIds:n}=rE({matchUp:t}),i=(t.timeItems??[]).filter(u=>u?.itemType&&[kl,Gl].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===kl);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,...P}}var re=t=>e=>{let r=Tt(e)&&e?.matchUpType||_t(e)&&e;return r&&NT[t].includes(r)};function Zm(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 td(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 oE({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 UL({tournamentScheduling:t,eventScheduling:e,averageMinutes:r,defaultTiming:n,matchUpFormat:o,categoryName:i,categoryType:s,policy:a}){let c=e?.matchUpRecoveryTimes&&td({...e,averageMinutes:r,matchUpFormat:o}),u=t?.matchUpRecoveryTimes&&td({...t,averageMinutes:r,matchUpFormat:o}),p=a?.matchUpRecoveryTimes&&td({...a,averageMinutes:r,matchUpFormat:o}),m=[c,u,p,a?.defaultTimes?.recoveryTimes,n?.recoveryTimes];return oE({categoryName:i,categoryType:s,timesBlockArray:m})}function DL({matchUpFormat:t,categoryName:e,categoryType:r,defaultTiming:n,tournamentScheduling:o,eventScheduling:i,policy:s}){let a=i?.matchUpAverageTimes&&Zm({...i,matchUpFormat:t}),c=o?.matchUpAverageTimes&&Zm({...o,matchUpFormat:t}),u=s?.matchUpAverageTimes&&Zm({...s,matchUpFormat:t}),p=[a,c,u,s?.defaultTimes?.averageTimes,n?.averageTimes];return oE({categoryName:e,categoryType:r,timesBlockArray:p})}var ub="DOUBLES_SINGLES",pb="SINGLES_DOUBLES",go="total",iE="participantConflict",sE="potentialParticipantConflict",ui="matchUpConflict",mb="courtDoubleBooking",db="positionLinkConflict",lb="ISSUE_IDS",Bs="CONFLICT",Hs="WARNING",Bl="ERROR",Hl="ISSUE",oS="STATE",ij="BLOCKED",sj="PRACTICE",aj="MAINTENANCE",RL={SINGLES_DOUBLES:pb,DOUBLES_SINGLES:ub,TOTAL:go,CONFLICT_MATCHUP_ORDER:ui,CONFLICT_PARTICIPANTS:iE,CONFLICT_POTENTIAL_PARTICIPANTS:sE,CONFLICT_COURT_DOUBLE_BOOKING:mb,CONFLICT_POSITION_LINK:db,SCHEDULE_ISSUE_IDS:lb,SCHEDULE_CONFLICT:Bs,SCHEDULE_WARNING:Hs,SCHEDULE_ERROR:Bl,SCHEDULE_ISSUE:Hl,SCHEDULE_STATE:oS,BLOCKED:ij,PRACTICE:sj,MAINTENANCE:aj};function _p({defaultAverageMinutes:t=90,defaultRecoveryMinutes:e=0,tournamentRecord:r,matchUpFormat:n,categoryName:o,categoryType:i,eventType:s,event:a}){if(!r)return{error:j};s=s??a?.eventType??Ea;let c={averageTimes:[{minutes:{default:t}}],recoveryTimes:[{minutes:{default:e}}]},{scheduleTiming:u}=gc({tournamentRecord:r,categoryName:o,categoryType:i,event:a}),p={...u,matchUpFormat:n,categoryType:i,defaultTiming:c};return ed({eventType:s,timingDetails:p})}function ed({timingDetails:t,eventType:e}){let r=DL(t),n=Object.keys(r?.minutes??{}),o=r?.minutes&&(n?.includes(e)&&r.minutes[e]||r.minutes.default),i=UL({...t,averageMinutes:o}),s=Object.keys(i?.minutes??{}),a=i?.minutes&&(s?.includes(e)&&i.minutes[e]||i.minutes.default),c=re(Ea)(e)?pb:ub,u=i?.minutes&&(s?.includes(c)&&i.minutes[c]||a);return{averageMinutes:o,recoveryMinutes:a,typeChangeRecoveryMinutes:u}}function fb(t){return t.createdAt?new Date(t.createdAt).getTime():0}function pi({timeItems:t,itemType:e}){let r=t.filter(o=>o&&o.itemType===e).sort((o,i)=>fb(o)-fb(i)).pop(),n=r&&fb(r);return{itemValue:r?.itemValue,timeStamp:n}}function Wl({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=pi({timeItems:r?.timeItems??[],itemType:Ss});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{scheduledTime:n}:e}function Ws({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=pi({timeItems:r?.timeItems??[],itemType:Is});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{scheduledDate:n}:e}function rd(t){if(KT.test(t)){let e=fI();return new Date(`${e}T${t}`)}else return new Date(t)}function bL({matchUp:t}){if(!t)return{error:Xe};if(!t.timeItems)return{error:Zg};let e=t.timeItems.filter(n=>[ci,Ca,Gs,hs].includes(n?.itemType)).sort((n,o)=>rd(n.itemValue).getTime()-rd(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 ci:i=0;break;case hs:if(n.lastValue&&[ci,Gs].includes(n.lastType)){let u=rd(o.itemValue).getTime()-rd(n.lastValue).getTime();i=n.milliseconds+u}else i=n.milliseconds;break;case Ca:if([ci,"SCHECULE.TIME.RESUME"].includes(n.lastType)){let u=rd(o.itemValue).getTime()-rd(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([ci,Gs].includes(r.lastType)){let n=new Date().getTime()-rd(r.lastValue).getTime();r.milliseconds+=n}return{milliseconds:r.milliseconds,time:cj(r.milliseconds),relevantTimeItems:e}}function cj(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 CL({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===ci&&s;return a&&(!i||r(a)<r(i))?a:i},void 0)?.itemValue}}function aE(t){return parseInt(t)}function Yl({startTime:t="",endTime:e=""}={}){if(!t||!e||!Qc.test(t)||!Qc.test(e))return!1;let[r,n]=t.split(":").map(aE),[o,i]=e.split(":").map(aE);return o<r?!1:!(r===o&&i<n)}function ML(t,e){let[r,n]=t.startTime.split(":").map(aE),[o,i]=e.startTime.split(":").map(aE);return r<o?-1:r>o?1:n<i?-1:n>i?1:0}function xp({dateAvailability:t}){if(!t)return{error:$U};if(!Array.isArray(t))return{error:Yg};for(let e of t){if(typeof e!="object")return{error:Yg};let{date:r,startTime:n,endTime:o,bookings:i=[]}=e;if(!n||!o)return{error:Yg};let s=pj(r);if(s)return s;let a=OL(n,o);if(a)return a;if(i){let c=mj(i);if(c)return c}}return{valid:!0}}var uj="Dates must be formated => YYYY-MM-DD",vL="Times must be 24 hour => 00:00";function pj(t){if(t&&!Mo.test(t))return{error:ae,dateAvailability:{date:t},info:uj}}function OL(t,e){if(!Qc.test(t))return{error:vs,dateAvailability:{startTime:t},info:vL};if(!Qc.test(e))return{error:vs,dateAvailability:{endTime:e},info:vL};if(t===e)return{error:vs,dateAvailability:{startTime:t,endTime:e},info:"startTime and endTime are equivalent"};if(!Yl({startTime:t,endTime:e}))return{error:vs,dateAvailability:{startTime:t,endTime:e},info:"endTime must be after startTime"}}function mj(t){if(!Array.isArray(t))return{error:rl};for(let e of t){if(typeof e!="object")return{error:rl};let{startTime:r,endTime:n}=e,o=OL(r,n);if(o)return o}}function cE({tournamentRecord:t}){for(let e of t.venues??[])e.isPrimary&&delete e.isPrimary}function gu(t){let{disableNotice:e,venue:r,context:n}=t;if(typeof r!="object")return{error:O};let o=Ar(t);r.venueId??=it();let i;for(let s of Object.values(o)){let a=dj({disableNotice:!0,tournamentRecord:s,context:n,venue:r});if(a?.error)return a;i=a.venue}return e||at({topic:By,payload:{venue:r}}),et({...P,venue:i})}function dj({tournamentRecord:t,disableNotice:e,context:r,venue:n}){let o=dt({tournamentRecord:t},[rt]);if(o.error)return o;if(!n)return{error:nt,info:"missing venue"};if(t.venues??=[],n.venueId??=it(),t.venues.reduce((s,a)=>s||a.venueId===n.venueId,void 0))return{error:fD};if(n.dateAvailability?.length){let s=xp({dateAvailability:n.dateAvailability});if(s.error)return s}if(n.defaultStartTime||n.defaultEndTime){if(!n.defaultStartTime||!n.defaultEndTime)return{error:O,info:"both defaultStartTime and defaultEndTime are required"};if(!Yl({startTime:n.defaultStartTime,endTime:n.defaultEndTime}))return{error:O,info:"defaultEndTime must be after defaultStartTime"}}return r&&ut({element:n,extension:{value:r,name:ER}}),n.isPrimary&&cE({tournamentRecord:t}),t.venues.push(n),e||at({payload:{venue:n,tournamentId:t.tournamentId},topic:By}),{...P,venue:q(n)}}function wn({tournamentRecords:t,tournamentRecord:e,venueId:r}){let n=dt({tournamentRecord:e,venueId:r},[rt,gp]);if(n.error)return n;let i=(e.venues??[]).reduce((s,a)=>a.venueId===r?a:s,void 0);if(!i&&t){let a=(Np({tournamentRecords:t}).linkedTournamentIds??[])[e.tournamentId];for(let c of a){let u=t[c],p=wn({tournamentRecord:u,venueId:r});if(p.success&&p.venue)return gu({tournamentRecord:e,venue:p.venue}),{...P,venue:i}}}return i?{...P,venue:i}:{error:Mi}}function uE({convertExtensions:t,...e}){let{tournamentRecords:r,tournamentRecord:n,venueId:o}=e,i=wn({tournamentRecords:r,tournamentRecord:n,venueId:o});return q(i,t,!0)}function mi({tournamentRecords:t,tournamentRecord:e,courtId:r}){let n=dt({tournamentRecord:e,courtId:r},[rt,Fs]);if(n.error)return n;let o="findCourt",i,s;if((e.venues??[]).forEach(a=>{(a.courts??[]).forEach(c=>{c.courtId===r&&(i=c,s=a)})}),i)return{...P,court:i,venue:s};if(t){let c=(Np({tournamentRecords:t}).linkedTournamentIds??[])[e.tournamentId];for(let u of c){let p=t[u],m=mi({tournamentRecord:p,courtId:r});if(m.success)return m.venue&&gu({tournamentRecord:e,venue:m.venue}),{...P,court:i,venue:s}}}return M({result:{error:bo},stack:o})}function pE(t){return q(mi(t),!1,!0)}function jl({tournamentRecord:t,internalUse:e,courtId:r}){let n=dt({tournamentRecord:t,courtId:r},[rt,Fs]);if(n.error)return n;let o=mi({tournamentRecord:t,courtId:r});if(o.error)return o;let i=o.court&&(({altitude:s,courtId:a,courtName:c,courtDimensions:u,latitude:p,longitude:m,surfaceCategory:d,surfaceType:l,surfacedDate:f,pace:g,notes:I})=>({altitude:s,courtId:a,courtName:c,courtDimensions:u,latitude:p,longitude:m,surfaceCategory:d,surfaceType:l,surfacedDate:f,pace:g,notes:I}))(o.court);return{...P,courtInfo:q(i,!1,e)}}function Iu(t){let e=X(t,[{[rt]:!0},{venueId:!0,[Yr]:Os}]);if(e.error)return e;let{tournamentRecord:r,venueId:n}=t,o=wn({tournamentRecord:r,venueId:n});if(o.error)return o;let s=(o.venue?.courts??[]).map(u=>(({courtInfo:p})=>({...p}))(jl({courtId:u.courtId,internalUse:!0,tournamentRecord:r}))),a=o.venue&&(({venueId:u,venueName:p,venueAbbreviation:m})=>({venueAbbreviation:m,venueName:p,venueId:u}))(o.venue),c=a&&{...a,courtsInfo:s};return{...P,venueData:q(c,!1,!0)}}function _L({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===hs&&s;return a&&(!i||r(a)>r(i))?a:i},void 0)?.itemValue}}function Bt({event:t,eventId:e}){if(!t)return{error:le};let n=ot({name:on,element:t})?.extension,o=e?q(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 _e(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&&Bt({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,...M({result:{error:Gr},stack:o})};return{event:u,drawDefinition:void 0,tournamentId:c}}return{event:void 0,drawDefinition:void 0,...M({result:{error:Rr},context:{drawId:n,eventId:r},stack:o})}}function ql(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:Xe};if(o&&!p.matchUpType&&!t.matchUpType&&(e||i)&&p.drawId){let N=t.drawDefinition||e?.drawDefinitions?.find(R=>R.drawId===p.drawId);!N&&i&&({drawDefinition:N,event:e}=_e({drawId:p.drawId,tournamentRecord:i}));let U=p.structureId&&N?.structures?.find(({structureId:R})=>R===p.structureId);r=t.matchUpType||U?.matchUpType||N?.matchUpType||e?.eventType!==Oe&&e?.eventType}let{milliseconds:m,time:d}=bL({matchUp:p}),{startTime:l}=CL({matchUp:p}),{endTime:f}=_L({matchUp:p}),{eventIds:g,drawIds:I}=n??{},h=(!g||g.includes(p.eventId))&&(!I||I.includes(p.drawId))?lj({tournamentRecord:i,scheduleTiming:a,afterRecoveryTimes:o,matchUpFormat:c,matchUpType:r,matchUp:p,endTime:f,startTime:l,milliseconds:m,time:d}):et({milliseconds:m,startTime:l,endTime:f,time:d}),{scheduledDate:T}=Ws({matchUp:p}),{scheduledTime:y}=Wl({matchUp:p});if(s&&u?.displaySettings?.draws){let N=u.displaySettings.draws,U=(N?.[p.drawId]??N?.default)?.scheduleDetails;if(U){let R=(U.find(D=>T&&D.dates?.includes(T))??U.find(D=>!D.dates?.length))?.attributes;if(R){let D=Object.assign({},...Object.keys(h).map(b=>({[b]:!0})),R);h=fs({source:h,template:D})}}}let A=p.matchUpStatus&&Mt.includes(p.matchUpStatus)&&(mt(f)||mt(T)||mt(y))||void 0;return{schedule:h,endDate:A}}function lj({tournamentRecord:t,scheduleTiming:e,afterRecoveryTimes:r,matchUpFormat:n,matchUpType:o,matchUp:i,endTime:s,startTime:a,milliseconds:c,time:u}){let p=C=>C.createdAt?new Date(C.createdAt).getTime():0,m=new Map,d=i.timeItems?.toSorted((C,_)=>p(C)-p(_))??[];for(let C of d)m.set(C.itemType,C.itemValue);let l=m.get(Vl),f=m.get(fu),g=m.get(fo),I=m.get(Ss),S=m.get(Jm),h=m.get(Is),T=m.get(rS),y=m.get(lu),E=m.get(gs),A=m.get(ai),N=fj({scheduleTiming:e,afterRecoveryTimes:r,matchUpFormat:n,matchUpType:o,matchUp:i,endTime:s,scheduledTime:I});!h&&I&&(h=mt(I));let U=pl({scheduledDate:h,scheduledTime:I}),{venueName:R,venueAbbreviation:D,courtName:b}=gj({tournamentRecord:t,allocatedCourts:g,venueId:E,courtId:A});return et({typeChangeTimeAfterRecovery:N.typeChangeTimeAfterRecovery,typeChangeRecoveryMinutes:N.typeChangeRecoveryMinutes,timeAfterRecovery:N.timeAfterRecovery,recoveryMinutes:N.recoveryMinutes,averageMinutes:N.averageMinutes,homeParticipantId:l,courtAnnotation:f,venueAbbreviation:D,allocatedCourts:g,scheduledDate:h,scheduledTime:I,isoDateString:U,timeModifiers:S,venueName:R,venueId:E,courtOrder:y,courtName:b,courtId:A,official:T,milliseconds:c,startTime:a,endTime:s,time:u})}function fj({scheduleTiming:t,afterRecoveryTimes:e,matchUpFormat:r,matchUpType:n,matchUp:o,endTime:i,scheduledTime:s}){let a,c,u,p,m,d=o.matchUpType??n;if(t&&s&&e&&d){let l={matchUpFormat:o.matchUpFormat??r,...t};({averageMinutes:c=0,recoveryMinutes:u=0,typeChangeRecoveryMinutes:p=0}=ed({timingDetails:l,eventType:d})),(c||u)&&(a=i?Br($t(i),u):Br(s,c+u)),p&&(m=i?Br($t(i),p):Br(s,c+p))}return{timeAfterRecovery:a,averageMinutes:c,recoveryMinutes:u,typeChangeRecoveryMinutes:p,typeChangeTimeAfterRecovery:m}}function gj({tournamentRecord:t,allocatedCourts:e,venueId:r,courtId:n}){let o={},i=(t&&r&&Iu({tournamentRecord:t,venueId:r}))?.venueData??{};r&&(o[r]=i);let{venueName:s,venueAbbreviation:a,courtsInfo:c}=i,p=(n&&c?.find(m=>m.courtId===n))?.courtName;for(let m of e??[]){if(!t)break;m.venueId&&!o[m.venueid]&&(o[m.venueId]=Iu({venueId:m.venueId,tournamentRecord:t})?.venueData);let d=o[m.venueId];m.venueName=d?.venueName;let l=d?.courtsInfo?.find(f=>f.courtId===m.courtId);m.courtName=l?.courtName}return{venueName:s,venueAbbreviation:a,courtName:p}}function xL({drawPositions:t,roundProfile:e,roundNumber:r}){let n=[void 0,void 0];if(MT(t))return{orderedDrawPositions:n,displayOrder:n};let o=e?.[r],s=o?.pairedDrawPositions?.find(c=>Re(c??[],t.filter(Boolean)))??n,a=o?.feedRound;if(CT(t)){let c=[...t].sort(Zt);return{orderedDrawPositions:c.length===2?c:s,displayOrder:a?c:s}}if(a){let u=[t.find(p=>!isNaN(st(p))),void 0];return{orderedDrawPositions:u,displayOrder:u}}return{orderedDrawPositions:s,displayOrder:s}}function nd({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 hn({tournamentParticipants:t,tournamentRecord:e,participantIds:r}){let n="getPairedParticipant";if(!t&&!e)return{error:j};if(!Array.isArray(r)||r.length>2)return{error:Mr};if(!r.length)return M({result:{error:Ro},stack:n});t=t??e?.participants??[];let o=t.filter(a=>a.participantType===lt&&Yt(r,a.individualParticipantIds).length===r.length&&a.individualParticipantIds.length===r.length),i=o[0];if(!i)return M({result:{error:ee},stack:n});let s=q(o.slice(1),!1,!0);return{participant:q(i),duplicatedPairParticipants:s,...P}}function Ys({drawDefinition:t,participantId:e}){if(typeof t!="object")return{error:$};if(typeof e!="string")return{error:He};let{extension:r}=ot({element:t,name:wo});return{lineUp:(r?.value??{})[e]}}function wL({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}=nd({collectionPosition:r,collectionId:s,lineUp:d});if(c===Rt){if(f?.length<=2){let I=o?.[f[0]]?.pairIdMap?.[f[1]],T=(I&&o[I]?.participant||hn({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||Ys({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||Ys({participantId:d,drawDefinition:i})?.lineUp;return u({attribute:m,lineUp:g,teamParticipant:f})}).filter(Boolean)??{};return{drawPositionCollectionAssignment:Object.assign({},...p)}}function $l(t){let e=X(t,[{[Dn]:!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===St&&Ct||s===lt&&Rt||s===vt&&vt||void 0}return{matchUpType:n}}function LL({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?Ij({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 Ij({displaySideNumber:t,seedAssignments:e,participantId:r,assignment:n,sideNumber:o}){let i={drawPosition:n.drawPosition,displaySideNumber:t,sideNumber:o};if(r){let s=Sj({seedAssignments:e,participantId:r});Object.assign(i,s,{participantId:r}),s?.seedNumber&&s?.seedValue===""&&(i.seedValue="~")}else n.bye&&Object.assign(i,{bye:!0});return n.qualifier&&Object.assign(i,{qualifier:!0}),i}function Sj({seedAssignments:t,participantId:e}){return t?.find(r=>!r.seedProxy&&r.participantId===e)}function Po(t){let e=t?.embargo;return!e||!us(e)?!1:new Date(e).getTime()>Date.now()}function eo(t){return!!t?.published&&!Po(t)}function hj({publishStatus:t,drawDefinition:e,structure:r,matchUp:n,schedule:o}){if(!t||!e?.drawId||!r?.structureId)return o;let i=t?.drawDetails?.[e.drawId]?.structureDetails?.[r.structureId];if(!i)return o;let s=n.roundNumber;if(!yt(s))return o;let a=i.scheduledRounds?.[s];if(!(a&&Po(a)))return o}function Tj({matchUp:t,collectionDefinition:e,structure:r,drawDefinition:n,event:o,tournamentRecord:i}){return t.processCodes?.length&&t.processCodes||e?.processCodes?.length&&e?.processCodes||r?.processCodes?.length&&r?.processCodes||n?.processCodes?.length&&n?.processCodes||o?.processCodes?.length&&o?.processCodes||i?.processCodes}function gb({scheduleVisibilityFilters:t,sourceDrawPositionRanges:e,tournamentParticipants:r,positionAssignments:n,drawPositionsRanges:o,hydrateParticipants:i,afterRecoveryTimes:s,initialRoundOfPlay:a,additionalContext:c,roundNamingProfile:u,tournamentRecord:p,tieDrawPositions:m,appliedPolicies:d,isCollectionBye:l,seedAssignments:f,usePublishState:g,participantMap:I,contextContent:S,scheduleTiming:h,contextProfile:T,drawDefinition:y,publishStatus:E,scoringActive:A,matchUpTieId:N,isRoundRobin:U,roundProfile:R,sideLineUps:D,structure:b,context:C,matchUp:_,event:v}){c=c??{};let w=ze({drawDefinition:y,structure:b,matchUp:_,event:v})?.tieFormat,{roundOffset:L,structureId:F,structureName:x,stage:k,stageSequence:G}=b,{drawId:V,drawName:B,drawType:z}=y??{},W=w?.collectionDefinitions,K=_.collectionId&&W?.find(Gn=>Gn.collectionId===_.collectionId),Y=_.collectionId?K?.matchUpFormat:_.matchUpFormat??b?.matchUpFormat??y?.matchUpFormat??v?.matchUpFormat,J=_.matchUpType||K?.matchUpType||b?.matchUpType||y?.matchUpType||!re(Oe)(v?.eventType)&&v?.eventType,ct=l?"BYE":_.matchUpStatus,{schedule:Et,endDate:Wt}=ql({scheduleVisibilityFilters:t,afterRecoveryTimes:s,tournamentRecord:p,usePublishState:g,scheduleTiming:h,drawDefinition:y,matchUpFormat:Y,publishStatus:E,matchUpType:J,matchUp:_,event:v});g&&Et&&(Et=hj({publishStatus:E,drawDefinition:y,structure:b,matchUp:_,schedule:Et}));let Dt=m??_.drawPositions??[],{collectionPosition:pe,collectionId:ye,roundPosition:Jt}=_,pr=_.roundNumber??c.roundNumber,$n=ye?wL({tournamentParticipants:r,positionAssignments:n,collectionPosition:pe,participantMap:I,drawDefinition:y,drawPositions:Dt,collectionId:ye,sideLineUps:D,matchUpType:J}):void 0,Kr=u?.[pr]?.roundName||c.roundName,io=u?.[pr]?.abbreviatedRoundName||c.abbreviatedRoundName,Ko=R?.[pr]?.feedRound,zo=R?.[pr]?.preFeedRound,sa=R?.[pr]?.roundFactor,aa=o?.[pr],ca=Jt?aa?.[Jt]:void 0,Pm=e?.[pr],_c=K?.category?{...C?.category,...K.category}:C?.category??v?.category,Nm=Tj({matchUp:_,collectionDefinition:K,structure:b,drawDefinition:y,event:v,tournamentRecord:p}),we=T?.withCompetitiveness&&Sc({...S,matchUp:_}),Ii=_.finishingPositionRange??c.finishingPositionRange,rs=k!==Z&&yt(a)&&a+(pr||0),Xa=Gn=>et(Gn,void 0,!0),En={...Xa(C),...Xa({matchUpFormat:J===Oe?void 0:Y,tieFormat:J===Oe?w:void 0,gender:K?.gender??v?.gender,endDate:_.endDate??Wt,discipline:v?.discipline,category:_c,finishingPositionRange:Ii,abbreviatedRoundName:io,drawPositionsRange:ca,competitiveProfile:we,structureName:x,stageSequence:G,drawPositions:Dt,matchUpStatus:ct,processCodes:Nm,isRoundRobin:U,matchUpTieId:N,preFeedRound:zo,matchUpType:J,roundFactor:sa,roundOffset:L,structureId:F,roundNumber:pr,roundOfPlay:rs,feedRound:Ko,roundName:Kr,drawName:B,drawType:z,schedule:Et,drawId:V,stage:k}),...q(Xa(_),!0,!0)};if(Y&&_.score?.scoreStringSide1&&yj(En,Y),Array.isArray(Dt)){let Gn=Ej({sourceDrawPositionRoundRanges:Pm,collectionAssignmentDetail:$n,positionAssignments:n,seedAssignments:f,drawPositions:Dt,roundPosition:Jt,roundProfile:R,roundNumber:pr,onlyDefined:Xa,matchUp:_});Object.assign(En,q({sides:Gn},!0,!0))}if(r&&En.sides){if(Aj({tournamentParticipants:r,hydrateParticipants:i,positionAssignments:n,appliedPolicies:d,drawDefinition:y,participantMap:I,contextProfile:T,matchUpWithContext:En,event:v}),!En.matchUpType){let{matchUpType:Gn}=$l({matchUp:En});Gn&&Object.assign(En,{matchUpType:Gn})}Nj({contextProfile:T,matchUpWithContext:En})}En.tieMatchUps&&Uj({matchUpWithContext:En,abbreviatedRoundName:io,roundNumber:pr,roundName:Kr,drawPositions:Dt,scheduleVisibilityFilters:t,sourceDrawPositionRanges:e,drawPositionsRanges:o,initialRoundOfPlay:a,roundNamingProfile:u,appliedPolicies:d,usePublishState:g,publishStatus:E,isRoundRobin:U,roundProfile:R,event:v,tournamentParticipants:r,positionAssignments:n,tournamentRecord:p,seedAssignments:f,participantMap:I,contextContent:S,scheduleTiming:h,contextProfile:T,drawDefinition:y,scoringActive:A,structure:b,context:C});let xc=En.sides?.filter(Gn=>Gn?.participantId).length===2,Ku=!En.winningSide;if(Object.assign(En,{readyToScore:A&&xc&&Ku,hasContext:!0}),xc){let{allParticipantsCheckedIn:Gn,checkedInParticipantIds:ET}=Vs({matchUp:En});Object.assign(En,{allParticipantsCheckedIn:Gn,checkedInParticipantIds:ET})}return Array.isArray(T?.exclude)&&T?.exclude.forEach(Gn=>delete En[Gn]),En}function yj(t,e){let r=oe(e),{bestOf:n,finalSetFormat:o,setFormat:i}=r??{};!o?.tiebreakSet&&!i?.tiebreakSet&&!i?.timed||(t.score.sets=t.score.sets.sort((s,a)=>s.setNumber-a.setNumber).map((s,a)=>{let p=a+1===n&&o?o:i,m=p?.tiebreakSet&&!p?.timed,d=p?.timed;return m?(s.tiebreakSet=!0,[1,2].includes(s.winningSide)&&(s.side1Score=s.winningSide===1?1:0,s.side2Score=s.winningSide===2?1:0)):d&&(s.timed=!0),s}))}function Ej({sourceDrawPositionRoundRanges:t,collectionAssignmentDetail:e,positionAssignments:r,seedAssignments:n,drawPositions:o,roundPosition:i,roundProfile:s,roundNumber:a,onlyDefined:c,matchUp:u}){let{orderedDrawPositions:p,displayOrder:m}=xL({drawPositions:o,roundProfile:s,roundNumber:a}),d=s?.[a]?.feedRound,l=m[0]!==p[0];return p.concat(void 0,void 0).slice(0,2).map((g,I)=>{let S=I+1,h=l?3-S:S,T=LL({...e,positionAssignments:r,displaySideNumber:h,seedAssignments:n,drawPosition:g,isFeedRound:d,sideNumber:S}),y=u.sides?.find(N=>N.sideNumber===S),E=i?(i-1)*2+I+1:void 0,A=E?t?.[E]:void 0;return c({sourceDrawPositionRange:A,...y,...T})})}function Aj({tournamentParticipants:t,hydrateParticipants:e,positionAssignments:r,appliedPolicies:n,drawDefinition:o,participantMap:i,contextProfile:s,matchUpWithContext:a,event:c}){let u=n?.[Da],p=m=>{let d=i?.[m]?.participant;return d&&fs({template:u?.participant,source:d})};a.sides.filter(Boolean).forEach(m=>{if(Pj({side:m,getMappedParticipant:p,tournamentParticipants:t,hydrateParticipants:e,positionAssignments:r,appliedPolicies:n,drawDefinition:o,contextProfile:s,event:c}),m?.participant?.individualParticipantIds?.length&&!m.participant.individualParticipants?.length){let d=m.participant.individualParticipantIds.map(l=>p(l)||(t?ni({policyDefinitions:n,tournamentParticipants:t,internalUse:!0,contextProfile:s,participantId:l}):void 0));e!==!1&&Object.assign(m.participant,{individualParticipants:d})}})}function Pj({side:t,getMappedParticipant:e,tournamentParticipants:r,hydrateParticipants:n,positionAssignments:o,appliedPolicies:i,drawDefinition:s,contextProfile:a,event:c}){if(!t.participantId)return;let u=q(e(t.participantId)||(r?ni({policyDefinitions:i,participantId:t.participantId,tournamentParticipants:r,internalUse:!0,contextProfile:a}):void 0),void 0,!0);if(!u)return;let p,m;if(s?.entries){let l=s.entries.find(g=>g.participantId===t.participantId),f=c?.entries?.find(g=>g.participantId===t.participantId);p=l?.entryStatus||f?.entryStatus,u.entryStatus=p,l?.entryStage&&(m=l.entryStage,u.entryStage=m)}let d;t.drawPosition&&o&&o.find(f=>f.drawPosition===t.drawPosition)?.extensions?.some(f=>f.name==="luckyAdvancement")&&(d=!0,u.luckyAdvancement=!0),n===!1?Object.assign(t,{participant:{entryStage:m,entryStatus:p,luckyAdvancement:d}}):Object.assign(t,{participant:u})}function Nj({contextProfile:t,matchUpWithContext:e}){if(!(t?.inferGender&&(!e.gender||e.gender===as)&&e.sides?.length===2&&e.matchUpType!==Oe))return;let n=e.sides.map(o=>{if(re(Ct)(e.matchUpType))return o.participant?.person?.sex;if(o.participant?.individualParticipants?.length===2){let i=pt(o.participant.individualParticipants.map(s=>s.person?.sex)).filter(Boolean);if(i.length===1)return i[0]}});n.filter(Boolean).length===2&&pt(n).length===1&&(e.inferredGender=n[0])}function Uj(t){let{matchUpWithContext:e}=t,r=e.matchUpStatus==="BYE",n=e.sides?.map(({participant:o,drawPosition:i,sideNumber:s,lineUp:a})=>{let c=o?.participantType===Oe&&o;return{teamParticipant:c&&et({participantRoleResponsibilities:c.participantRoleResponsibilities,participantOtherName:c.participantOtherName,participantName:c.participantName,participantId:c.participantId,teamId:c.teamId}),drawPosition:i,sideNumber:s,lineUp:a}});e.tieMatchUps=e.tieMatchUps.map(o=>{let i=e.matchUpId,a={finishingPositionRange:e.finishingPositionRange,abbreviatedRoundName:t.abbreviatedRoundName,roundNumber:t.roundNumber,roundName:t.roundName};return gb({tieDrawPositions:t.drawPositions,scheduleVisibilityFilters:t.scheduleVisibilityFilters,sourceDrawPositionRanges:t.sourceDrawPositionRanges,sideLineUps:n,drawPositionsRanges:t.drawPositionsRanges,initialRoundOfPlay:t.initialRoundOfPlay,roundNamingProfile:t.roundNamingProfile,additionalContext:a,appliedPolicies:t.appliedPolicies,isCollectionBye:r,usePublishState:t.usePublishState,publishStatus:t.publishStatus,matchUpTieId:i,isRoundRobin:t.isRoundRobin,roundProfile:t.roundProfile,matchUp:o,event:t.event,tournamentParticipants:t.tournamentParticipants,positionAssignments:t.positionAssignments,tournamentRecord:t.tournamentRecord,seedAssignments:t.seedAssignments,participantMap:t.participantMap,contextContent:t.contextContent,scheduleTiming:t.scheduleTiming,contextProfile:t.contextProfile,drawDefinition:t.drawDefinition,scoringActive:t.scoringActive,structure:t.structure,context:t.context})})}function FL({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=pi({timeItems:r?.timeItems??[],itemType:fo});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{allocatedCourts:q(n,!1,!0)}:e}function kL({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=pi({timeItems:r?.timeItems??[],itemType:ai});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{courtId:n}:e}function GL({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=pi({timeItems:r?.timeItems??[],itemType:gs});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{venueId:n}:e}function Yi(t){if(!Array.isArray(t.matchUps))return[];let{matchUps:e,excludeMatchUpStatuses:r,hasParticipantsCount:n,isCollectionMatchUp:o,matchUpStatuses:i,hasWinningSide:s,matchUpFormats:a,roundPositions:c,matchUpFormat:u,collectionIds:p,isMatchUpTie:m,roundNumbers:d,matchUpIds:l,roundNames:f,filterMatchUpTypes:g=!0,filterMatchUpIds:I=!0,stageSequences:S,scheduledDates:h,scheduledDate:T,participantIds:y,processContext:E,tournamentIds:A,matchUpTypes:N,structureIds:U,readyToScore:R,courtIds:D,eventIds:b,venueIds:C,drawIds:_,stages:v}=t,w=Array.isArray(y)?y.filter(Boolean):[],L=Array.isArray(i)?i.filter(Boolean):[],F=Array.isArray(r)?r.filter(Boolean):[],x=Array.isArray(v)?v.filter(Boolean):[],k=Array.isArray(S)?S.filter(Boolean):[],G=Array.isArray(p)?p.filter(Boolean):[],V=Array.isArray(f)?f.filter(Boolean):[],B=Array.isArray(d)?d.filter(Boolean):[],z=Array.isArray(c)?c.filter(Boolean):[],W=Array.isArray(l)&&I?l.filter(Boolean):[],K=Array.isArray(N)&&g?N.filter(Boolean):[],Y=Array.isArray(D)?D.filter(Boolean):[],J=Array.isArray(C)?C.filter(Boolean):[],ct=Array.isArray(a)&&a.filter(Boolean)||typeof u=="string"&&[u]||[],Et=Array.isArray(h)&&h.filter(Boolean).length&&h.filter(Boolean)||typeof T=="string"&&T.length&&[T]||[],Wt=Array.isArray(A)?A.filter(Boolean):[],Dt=Array.isArray(b)?b.filter(Boolean):[],pe=Array.isArray(_)?_.filter(Boolean):[],ye=Array.isArray(U)?U.filter(Boolean):[];return e.filter(Jt=>!(!Dj({matchUp:Jt,readyToScore:R,hasWinningSide:s,isMatchUpTie:m,isCollectionMatchUp:o})||!Rj({matchUp:Jt,targetStages:x,targetStageSequences:k,targetCollectionIds:G,targetRoundNames:V,targetRoundNumbers:B,targetRoundPositions:z,targetMatchUpStatuses:L,excludeTargetMatchUpStatuses:F,targetMatchUpIds:W,targetMatchUpTypes:K,targetMatchUpFormats:ct})||!bj({matchUp:Jt,targetScheduledDates:Et,targetCourtIds:Y,targetVenueIds:J})||E&&!Cj({matchUp:Jt,targetTournamentIds:Wt,targetEventIds:Dt,targetDrawIds:pe,targetStructureIds:ye,targetParticipantIds:w,hasParticipantsCount:n})))}function Dj({matchUp:t,readyToScore:e,hasWinningSide:r,isMatchUpTie:n,isCollectionMatchUp:o}){return!(e&&!re(Ir)(t)&&!t.readyToScore||t.winningSide&&r&&![1,2].includes(t.winningSide)||n!==void 0&&(n&&!t.tieMatchUps||!n&&t.tieMatchUps)||o!==void 0&&(o&&!t.collectionId||!o&&t.collectionId))}function Rj({matchUp:t,targetStages:e,targetStageSequences:r,targetCollectionIds:n,targetRoundNames:o,targetRoundNumbers:i,targetRoundPositions:s,targetMatchUpStatuses:a,excludeTargetMatchUpStatuses:c,targetMatchUpIds:u,targetMatchUpTypes:p,targetMatchUpFormats:m}){return!(e.length&&!e.includes(t.stage)||r.length&&!r.includes(t.stageSequence)||n.length&&(!t.collectionId||!n.includes(t.collectionId))||o.length&&(!t.roundName||!o.includes(t.roundName))||i.length&&(!t.roundNumber||!i.includes(t.roundNumber))||s.length&&(!t.roundPosition||!s.includes(t.roundPosition))||a.length&&(!t.matchUpStatus||!a.includes(t.matchUpStatus))||c.length&&t.matchUpStatus&&c.includes(t.matchUpStatus)||u.length&&!u.includes(t.matchUpId)||p.length&&(!t.matchUpType||!Cs(p,t.matchUpType))||m.length&&(!t.matchUpFormat||!m.includes(t.matchUpFormat)))}function bj({matchUp:t,targetScheduledDates:e,targetCourtIds:r,targetVenueIds:n}){if(e?.length){let{scheduledTime:o}=Wl({matchUp:t}),{scheduledDate:i}=Ws({matchUp:t}),a=mt(o)||i;if(!e.some(c=>Qn(c,a)))return!1}if(r.length){let{courtId:o}=kL({matchUp:t}),{allocatedCourts:i}=FL({matchUp:t}),s=i?.map(({courtId:a})=>a);if(!r.filter(Boolean).includes(o)||s?.includes(o))return!1}if(n.length){let{venueId:o}=GL({matchUp:t});if(!n.filter(Boolean).includes(o))return!1}return!0}function Cj({matchUp:t,targetTournamentIds:e,targetEventIds:r,targetDrawIds:n,targetStructureIds:o,targetParticipantIds:i,hasParticipantsCount:s}){if(e.length&&!e.includes(t.tournamentId)||r.length&&!r.includes(t.eventId)||n.length&&!n.includes(t.drawId)||o.length&&!o.includes(t.structureId))return!1;let a=t.sides?.map(({participantId:c})=>c).filter(Boolean)??[];return!(s&&a.length<s||i.length&&!i.some(u=>a.includes(u)))}function ht(t){let{provisionalPositioning:e,tournamentRecord:r,contextFilters:n,matchUpFilters:o,contextProfile:i,drawDefinition:s,context:a={},structure:c,inContext:u,event:p}=t,{seedAssignments:m,contextContent:d,exitProfiles:l,matchUpsMap:f}=t,g={},I={};if(!c)return{collectionPositionMatchUps:g,error:bi,roundMatchUps:I,matchUps:[]};let S=Array.isArray(o?.eventIds)?o?.eventIds.filter(Boolean):[],h=Array.isArray(o?.structureIds)?o?.structureIds.filter(Boolean):[],T=Array.isArray(o?.drawIds)?o?.drawIds.filter(Boolean):[],y=!a?.eventId||!S?.length&&!n?.eventIds?.filter(Boolean).length||S?.includes(a.eventId)||n?.eventIds?.includes(a.eventId),E=!h?.length||h.includes(c.structureId),A=!s||!T?.length||T.includes(s.drawId);if(!y||!E||!A)return{collectionPositionMatchUps:g,roundMatchUps:I,matchUps:[]};i&&!d&&(d=to({tournamentRecord:r,contextProfile:i,drawDefinition:s}));let{appliedPolicies:N}=It({drawDefinition:s}),U={...t.tournamentAppliedPolicies,...N,...t.policyDefinitions},R=U?.scoring?.structures,D=c.stage&&R?.stage?.[c.stage],b=c.stageSequence&&D?.stageSequence?.[c.stageSequence],C=U?.scoring?.requireAllPositionsAssigned||D?.requireAllPositionsAssigned||b?.requireAllPositionsAssigned;f??=Ie({drawDefinition:s,structure:c});let{positionAssignments:_,allPositionsAssigned:v}=se({structure:c}),w=!C||v,{seedAssignments:L}=Pr({provisionalPositioning:e,drawDefinition:s,structure:c});m=m??L;let{structureId:F}=c;l=l||s&&Ll({drawDefinition:s}).exitProfiles;let x=l?.[F],k=x?.length&&(x[0].split("-").map(Y=>Number.parseInt(Y)).reduce((Y,J)=>Y+J,0)||0),G=!!c.structures,V=Vo({matchUpsMap:f,structureId:F,inContext:u}),B=U?.[Oo],z=Zy({roundNamingPolicy:B,drawDefinition:s,structure:c,matchUps:V}),{roundNamingProfile:W,roundProfile:K}=z;if(I=z?.roundMatchUps??[],o){let Y=new Set(V.filter(J=>Array.isArray(J.tieMatchUps)).map(J=>J.matchUpId));V=Yi({matchUps:Y.size?V.filter(J=>!Y.has(J.matchUpId)):V,...o,filterMatchUpTypes:!1,filterMatchUpIds:!1}).concat(Y.size?V.filter(J=>Y.has(J.matchUpId)):[])}return u?V=Mj({positionAssignments:_,initialRoundOfPlay:k,roundNamingProfile:W,tournamentRecord:r,appliedPolicies:U,seedAssignments:m,contextContent:d,contextProfile:i,drawDefinition:s,contextFilters:n,scoringActive:w,isRoundRobin:G,roundProfile:K,matchUpsMap:f,structureId:F,structure:c,context:a,params:t,event:p,matchUps:V}):V=VL(V),o&&(V=Yi({matchUps:V,...o,filterMatchUpTypes:!1,filterMatchUpIds:!1})),(o?.matchUpTypes||o?.matchUpIds)&&(V=Yi({matchUpTypes:o.matchUpTypes,matchUpIds:o.matchUpIds,matchUps:V})),(o?.matchUpTypes||o?.matchUpIds||u)&&(I=De({matchUps:V}).roundMatchUps??[]),ze({drawDefinition:s,structure:c,event:p})?.tieFormat&&({collectionPositionMatchUps:g}=gL({matchUps:V})),{collectionPositionMatchUps:g,roundMatchUps:I,isRoundRobin:G,roundProfile:K,matchUpsMap:f,matchUps:V}}function VL(t){let e=t?.filter(n=>Array.isArray(n.tieMatchUps)),r=t;return e.forEach(n=>{r=r.concat(...n.tieMatchUps)}),r}function Mj({positionAssignments:t,initialRoundOfPlay:e,roundNamingProfile:r,tournamentRecord:n,appliedPolicies:o,seedAssignments:i,contextContent:s,contextProfile:a,drawDefinition:c,contextFilters:u,scoringActive:p,isRoundRobin:m,roundProfile:d,matchUpsMap:l,structureId:f,structure:g,context:I,params:S,event:h,matchUps:T}){let{sourceDrawPositionRanges:y}=IL({drawDefinition:c,matchUpsMap:l,structureId:f}),E=c?SL({drawDefinition:c,roundProfile:d,matchUpsMap:l,structureId:f}).drawPositionsRanges:void 0,A=S.tournamentParticipants,N=S.participantMap;!A?.length&&!N&&n&&({participants:A=[],participantMap:N}=si({participantsProfile:S.participantsProfile,useParticipantMap:S.useParticipantMap,policyDefinitions:S.policyDefinitions,tournamentRecord:n,contextProfile:a,inContext:!0}));let U=T.map(R=>gb({scheduleVisibilityFilters:S.scheduleVisibilityFilters,hydrateParticipants:S.hydrateParticipants,afterRecoveryTimes:S.afterRecoveryTimes,usePublishState:S.usePublishState,scheduleTiming:S.scheduleTiming,publishStatus:S.publishStatus,sourceDrawPositionRanges:y,tournamentParticipants:A,positionAssignments:t,drawPositionsRanges:E,initialRoundOfPlay:e,roundNamingProfile:r,tournamentRecord:n,appliedPolicies:o,seedAssignments:i,contextContent:s,participantMap:N,contextProfile:a,drawDefinition:c,scoringActive:p,isRoundRobin:m,roundProfile:d,structure:g,context:I,matchUp:R,event:h}));return U=VL(U),u&&(U=Yi({processContext:!0,...u,matchUps:U})),U}function js({matchUp:t}){return t?Mt.includes(t?.matchUpStatus)||t?.winningSide:!1}function wp({requireParticipants:t=!0,scheduleVisibilityFilters:e,tournamentAppliedPolicies:r,tournamentParticipants:n,hydrateParticipants:o,afterRecoveryTimes:i,policyDefinitions:s,tournamentRecord:a,usePublishState:c,matchUpFilters:u,contextFilters:p,contextContent:m,participantMap:d,scheduleTiming:l,publishStatus:f,contextProfile:g,drawDefinition:I,exitProfiles:S,matchUpsMap:h,structureId:T,inContext:y,structure:E,context:A,event:N}){!E&&T&&({structure:E}=tt({drawDefinition:I,structureId:T}));let U=ht({tournamentAppliedPolicies:r,scheduleVisibilityFilters:e,tournamentParticipants:n,hydrateParticipants:o,afterRecoveryTimes:i,policyDefinitions:s,tournamentRecord:a,usePublishState:c,matchUpFilters:u,contextFilters:p,contextContent:m,participantMap:d,scheduleTiming:l,publishStatus:f,contextProfile:g,drawDefinition:I,exitProfiles:S,matchUpsMap:h,structure:E,inContext:y,context:A,event:N}),R=[],D=[],b=[],C=[],_=[];if(U.error)return U;let{matchUps:v}=U,{assignedPositions:w}=se({structure:E}),L=w?.filter(x=>x.participantId).map(x=>x.drawPosition),F;return v.filter(x=>{let k=u?.matchUpTypes?.length===1&&u.matchUpTypes[0]===Ot;return!(x.matchUpType!==Ot&&k)}).forEach(x=>{if(x.matchUpStatus===xr){R.push(x);return}x.matchUpType===Ot&&(F=!0);let k=!!x.collectionId,G=k&&x.sides?.every(J=>J.participantId),V=!k&&x.drawPositions?.filter(Boolean).length===2,B=!k&&x.drawPositions?.every(J=>L?.includes(J)),z=w?.filter(J=>J.bye).map(J=>J.drawPosition),W=!k&&x.drawPositions?.find(J=>z?.includes(J)),Y=wy.includes(x.matchUpStatus)&&(G||V&&(!t||B));return W?_.push(x):js({matchUp:x})?D.push(x):Y?b.push(x):C.push(x)}),{includesTeamMatchUps:F,abandonedMatchUps:R,completedMatchUps:D,upcomingMatchUps:b,pendingMatchUps:C,byeMatchUps:_,structure:E}}function BL({drawDefinition:t,roundNumber:e,structureId:r}){let n=dt({drawDefinition:t,structureId:r},[Kt,po]);if(n.error)return n;let{links:o}=Ma({drawDefinition:t,structureId:r}),i=o.source.reduce((a,c)=>!c.source.roundNumber||c.source.roundNumber===e?a.concat(c):a,[]),s=o.target.reduce((a,c)=>!c.target.roundNumber||c.target.roundNumber===e?a.concat(c):a,[]);return{links:{source:i,target:s}}}function mE({finishingPositions:t,linkCondition:e,linkType:r,source:n}){let o=n.find(i=>{let s=!i.source?.finishingPositions||!t||Re(t,i.source?.finishingPositions);return e===i.linkCondition&&s&&i.linkType===r});return[Er,ir].includes(o?.linkType)&&!o?.source?.roundNumber?M({result:{error:O},stack:"getTargetLink",context:o}):o}function Ma({drawDefinition:t,structureId:e,roundNumber:r}){let n=dt({drawDefinition:t,structureId:e},[Kt,po]);return n.error?n:{links:(t.links??[]).filter(Boolean).reduce((s,a)=>(a.source?.structureId===e&&(!r||a.source.roundNumber===r)&&(s.source=s.source.concat(a)),a.target?.structureId===e&&(!r||a.target.roundNumber===r)&&(s.target=s.target.concat(a)),s),{source:[],target:[]})}}function HL({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 dE({sourceRoundMatchUpCount:t,inContextDrawMatchUps:e,sourceRoundPosition:r,drawDefinition:n,targetLink:o}){if(!o)return{error:wg};let{target:{structureId:i,feedProfile:s,groupedOrder:a,roundNumber:c,positionInterleave:u}}=o,{structure:p}=tt({drawDefinition:n,structureId:i}),{positionAssignments:m}=Pt({structure:p}),l=(e?.filter(D=>D.structureId===p?.structureId)).filter(D=>D.roundNumber===c&&!D.matchUpTieId),f=l.length,g=Q(1,f+1),I=f/t,S=Math.ceil(I*r),h=1-r%2;if(u?.interleave&&I!==.5){let D=u.offset+(r-1)*u.interleave,b=r+D;S=Math.ceil(b/2),h=1-b%2}let T=g,y=g[S-1],E=Jy({roundPositionsCount:g.length,groupedOrder:a}),A=E?.length||1;if(A<=g.length){let D=f/A,b=he(g,D);s===Oi&&b.forEach(C=>C.reverse()),T=E?.length&&E?.map(C=>b[C-1]).flat()||T}s===qe?y=T[S-1]:s===Oi?((!E?.length||A>g.length)&&(S=l.length+1-S),y=T[S-1]):s===Gm&&je()&&console.log(rI,{feedProfile:s});let N=y&&l.reduce((D,b)=>b.roundPosition===y?b:D,void 0),U;N?.feedRound?(h=0,U=Math.min(...(N.drawPositions??[]).filter(Boolean))):U=N?.drawPositions?.length===2&&N?.drawPositions[h];let R=m?.find(({drawPosition:D})=>D===U);if(R){let{extension:D}=ot({element:R,name:yl});if(D?.value)return{disabledDrawPosition:U}}return{matchUp:N,targetDrawPosition:U,matchUpDrawPositionIndex:h}}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}=tt({structureId:i?.structureId,drawDefinition:n});return s?.finishingPosition===ls?vj({inContextDrawMatchUps:t,useTargetMatchUpIds:e,drawDefinition:n,structure:s,matchUp:i}):Oj({matchUp:i})}function vj({inContextDrawMatchUps:t,useTargetMatchUpIds:e,drawDefinition:r,structure:n,matchUp:o}){let{winnerMatchUpId:i,loserMatchUpId:s}=o,{links:a}=BL({roundNumber:o.roundNumber,structureId:n.structureId,drawDefinition:r}),c=a?.source,u=mE({source:c,linkType:Er}),p=mE({linkCondition:Bn,linkType:ir,source:c}),m=mE({source:c,linkType:ir}),d=p&&m;m||(m=p);let l=u?.target?.feedProfile,f=m?.target?.feedProfile,g=p?.target?.feedProfile,I,S,h,T,y,E,A,N,U,R;if(e&&(i||s)&&(A=i&&l!==ln&&t.find(({matchUpId:C})=>C===i),T=s&&f!==ln&&t.find(({matchUpId:C})=>C===s),A||T))return{matchUp:o,targetLinks:{loserTargetLink:m,winnerTargetLink:u},targetMatchUps:{loserMatchUp:T,winnerMatchUp:A}};let{roundPosition:D}=o;R=R||t.filter(C=>C.structureId===n.structureId);let b=R.reduce((C,_)=>_.roundNumber===o.roundNumber&&!_.matchUpTieId?C+1:C,0);return m&&!T&&f!==ln&&({matchUpDrawPositionIndex:E,targetDrawPosition:y,matchUp:T}=dE({targetLink:m,sourceRoundMatchUpCount:b,inContextDrawMatchUps:t,sourceRoundPosition:D,drawDefinition:r})),d&&g!==ln&&({matchUpDrawPositionIndex:h,targetDrawPosition:S,matchUp:I}=dE({targetLink:p,sourceRoundMatchUpCount:b,inContextDrawMatchUps:t,sourceRoundPosition:D,drawDefinition:r})),u&&!A&&l!==ln&&({matchUpDrawPositionIndex:U,targetDrawPosition:N,matchUp:A}=dE({targetLink:u,sourceRoundMatchUpCount:b,inContextDrawMatchUps:t,sourceRoundPosition:D,drawDefinition:r})),A||(R=R||t.filter(C=>C.structureId===n.structureId),{matchUp:A}=HL({structureMatchUps:R,matchUp:o})),et({matchUp:o,targetLinks:{loserTargetLink:m,winnerTargetLink:u,byeTargetLink:p},targetMatchUps:{winnerMatchUpDrawPositionIndex:U,loserMatchUpDrawPositionIndex:E,byeMatchUpDrawPositionIndex:h,winnerTargetDrawPosition:N,loserTargetDrawPosition:y,byeTargetDrawPosition:S,winnerMatchUp:A,loserMatchUp:T,byeMatchUp:I},targetMatchUpIds:!!(i||s)})}function Oj({matchUp:t}){return{targetLinks:{loserTargetLink:void 0,winnerTargetLink:void 0},targetMatchUps:{loserMatchUp:void 0,winnerMatchUp:void 0},matchUp:t}}function YL({drawDefinition:t,inContextDrawMatchUps:e}){let r={};return e.forEach(n=>{let{matchUpId:o,structureId:i,drawPositions:s=[]}=n,{structure:a}=tt({drawDefinition:t,structureId:i});a?.finishingPosition===uo?_j({inContextMatchUp:n,structure:a,drawPositions:s}):xj({scheduleConflictMatchUpIds:r,inContextDrawMatchUps:e,inContextMatchUp:n,drawDefinition:t,matchUpId:o})}),Object.keys(r).length&&e.forEach(n=>{Object.keys(r).includes(n.matchUpId)&&(n.schedule.scheduleConflict=r[n.matchUpId])}),{scheduleConflictMatchUpIds:r}}function _j({inContextMatchUp:t,structure:e,drawPositions:r}){let{roundNumber:n}=t,o=n&&st(n)+1,i=e.matchUps??[],{roundMatchUps:s}=De({matchUps:i});if(o&&s?.[o]){let a=[...r].sort(Zt).map((c,u)=>{let p=s[o].find(m=>m.drawPositions?.includes(c));return{matchUpId:p?.matchUpId,roundNumber:o,schedule:p?.schedule,sideNumber:u+1,structureName:e.structureName}});Object.assign(t,{sidesTo:a})}}function xj({scheduleConflictMatchUpIds:t,inContextDrawMatchUps:e,inContextMatchUp:r,drawDefinition:n,matchUpId:o}){let i=er({useTargetMatchUpIds:!0,inContextDrawMatchUps:e,inContextMatchUp:r,drawDefinition:n,matchUpId:o}),{winnerMatchUp:s}=i.targetMatchUps,{loserMatchUp:a}=i.targetMatchUps;!r.winnerMatchUpId&&s&&(r.winnerMatchUpId=s.matchUpId),!r.loserMatchUpId&&a&&(r.loserMatchUpId=a.matchUpId);let c=Ib({upcomingMatchUp:s}),u=Ib({upcomingMatchUp:a});if(r.matchUpStatus!=="BYE"&&a?.matchUpStatus==="BYE"){let{matchUp:m}=jL({matchUp:a,drawDefinition:n,inContextDrawMatchUps:e})??{};u=m&&Ib({upcomingMatchUp:m})||u}let p=r.schedule?.timeAfterRecovery;p&&(WL({scheduleConflictMatchUpIds:t,inContextMatchUp:r,timeAfterRecovery:p,upcomingTo:c}),WL({scheduleConflictMatchUpIds:t,inContextMatchUp:r,timeAfterRecovery:p,upcomingTo:u})),Object.assign(r,{winnerTo:c,loserTo:u}),r.drawPositions?.filter(Boolean).length&&wj({inContextDrawMatchUps:e,inContextMatchUp:r,winnerMatchUp:s,loserMatchUp:a,targetData:i})}function WL({scheduleConflictMatchUpIds:t,inContextMatchUp:e,timeAfterRecovery:r,upcomingTo:n}){n?.schedule?.scheduledTime&&jt(n.schedule.scheduledTime)<jt(r)&&(t[n.matchUpId]=e.matchUpId,n.schedule.scheduleConflict=e.matchUpId)}function wj({inContextDrawMatchUps:t,inContextMatchUp:e,winnerMatchUp:r,loserMatchUp:n,targetData:o}){let s=o.targetLinks?.loserTargetLink?.linkCondition===Bn,a=Lj(e);if(!a.length)return;let c=_I(r?.sides),u=_I(n?.sides),m=a.find(({participantId:f})=>c.includes(f))?[]:a,l=a.find(({participantId:f})=>u.includes(f))?[]:a;n&&s&&l.length<2&&l.push({bye:!0,tbd:!0}),m?.length&&r&&(!o.targetMatchUpIds&&r&&(r=t.find(({matchUpId:f})=>f===r.matchUpId)),r.potentialParticipants??=[],r.potentialParticipants.push(m)),l?.length&&n&&(o.targetMatchUpIds||(r=t.find(({matchUpId:f})=>f===n.matchUpId)),n.potentialParticipants||(n.potentialParticipants=[]),n.potentialParticipants.push(l))}function Lj(t){return t?.sides?.map(({participant:e,participantId:r,qualifier:n})=>e||r&&{participantId:r}||n&&{qualifier:n}).filter(Boolean)??[]}function jL({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==="BYE"){let s;return t.winnerMatchUpId?s=r.find(({matchUpId:a})=>a===t.winnerMatchUpId):{winnerMatchUp:s}=er({inContextDrawMatchUps:r,drawDefinition:e,matchUpId:n})?.targetMatchUps??{},jL({matchUp:s,drawDefinition:e,inContextDrawMatchUps:r})}return{matchUp:void 0}}function Ib(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 te(t){let e="getAllDrawMatchUps";Object.assign(t,{requireParticipants:!1});let r=va(t);if(r.error)return M({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 va(t){if(!t?.drawDefinition)return{error:$};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:S,drawDefinition:h,nextMatchUps:T,inContext:y,context:E,event:A}=t,N=[],U=[],R=[],D=[],b=[];S&&!r&&(r=to({policyDefinitions:u,tournamentRecord:p,contextProfile:S,event:A}));let C;!e?.length&&p&&(e=p?.participants,(y||a?.withGroupings)&&e?.length&&({participantsWithGroupings:e,groupInfo:C}=Cp({participants:e,participantsProfile:a})));let{structures:_}=In({drawDefinition:h});if(!_)return{error:Nt};n||(n=Ie({drawDefinition:h}));let v=h&&Ll({drawDefinition:h}).exitProfiles;_.forEach(F=>{let{byeMatchUps:x=[],pendingMatchUps:k=[],upcomingMatchUps:G=[],completedMatchUps:V=[],abandonedMatchUps:B=[]}=wp({matchUpFilters:T?void 0:l,contextFilters:T?void 0:d,inContext:y||T||d,hydrateParticipants:t.hydrateParticipants,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:S,drawDefinition:h,exitProfiles:v,matchUpsMap:n,structure:F,context:E,event:A});N=N.concat(...B),U=U.concat(...V),R=R.concat(...G),D=D.concat(...k),b=b.concat(...x)});let w=F=>(!l&&!T&&!d||(l&&(F=Yi({matchUps:F,...l})),d&&(F=Yi({matchUps:F,...d,processContext:!0}))),F),L={abandonedMatchUps:w(N),completedMatchUps:w(U),upcomingMatchUps:w(R),pendingMatchUps:w(D),byeMatchUps:w(b),matchUpsMap:n,...P,groupInfo:C};if(T){let F=typeof T=="object"||{abandoned:!0,completed:!0,upcoming:!0,pending:!0,bye:!0},{abandoned:x,completed:k,upcoming:G,pending:V,bye:B}=F,z=[].concat(...(x&&N)??[],...(k&&U)??[],...(G&&R)??[],...(V&&D)??[],...(B&&b)??[]);YL({inContextDrawMatchUps:z,drawDefinition:h})}return L}function Mn(t){let{participants:e=[],contextContent:r,participantMap:n}=t,{scheduleVisibilityFilters:o,tournamentAppliedPolicies:i,participantsProfile:s,afterRecoveryTimes:a,policyDefinitions:c,useParticipantMap:u,tournamentRecord:p,usePublishState:m,contextFilters:d,matchUpFilters:l,contextProfile:f,nextMatchUps:g,inContext:I,context:S,event:h}=t;if(!h)return{error:le};let{eventId:T,eventName:y,endDate:E,eventType:A,category:N,gender:U,matchUpFormat:R}=h??{},D={...S,...et({indoorOutDoor:h.indoorOutdoor??p?.indoorOutdoor,surfaceCategory:h.surfaceCategory??p?.surfaceCategory,endDate:h.endDate??p?.endDate,tournamentId:p?.tournamentId,matchUpFormat:R,eventName:y,eventType:A,category:N,eventId:T,gender:U})};E&&(D.endDate=E),f&&!r&&(r=to({policyDefinitions:c,tournamentRecord:p,contextProfile:f,event:h}));let b;if(!e?.length&&!n&&p){let w=si({participantsProfile:s,useParticipantMap:u,policyDefinitions:c,tournamentRecord:p,contextProfile:f,inContext:I});n=w.participantMap,e=w.participants??[],b=w.groupInfo}let C=h.drawDefinitions??[],_=gc({tournamentRecord:p,event:h}).scheduleTiming;return{matchUps:C.flatMap(w=>{let{matchUps:L}=te({tournamentParticipants:e,tournamentAppliedPolicies:i,scheduleVisibilityFilters:o,context:D,participantsProfile:s,afterRecoveryTimes:a,policyDefinitions:c,tournamentRecord:p,usePublishState:m,contextFilters:d,contextProfile:f,drawDefinition:w,contextContent:r,matchUpFilters:l,participantMap:n,scheduleTiming:_,nextMatchUps:g,inContext:I,event:h});return L??[]}),groupInfo:b}}function qt(t){let e=X(t,[{tournamentRecord:!0}]);if(e.error)return e;if(!t?.tournamentRecord)return{error:j};let{participantMap:r,participants:n}=t,{scheduleVisibilityFilters:o,participantsProfile:i,afterRecoveryTimes:s,useParticipantMap:a,policyDefinitions:c,tournamentRecord:u,inContext:p=!0,usePublishState:m,contextProfile:d,matchUpFilters:l,contextFilters:f,nextMatchUps:g,context:I}=t,S=t.tournamentId??u.tournamentId,h=u?.events??[];n||({participants:n,participantMap:r}=si({participantsProfile:i,useParticipantMap:a,policyDefinitions:c,tournamentRecord:u,contextProfile:d,inContext:p}));let{appliedPolicies:T}=It({tournamentRecord:u}),y={...I,tournamentId:S,indoorOutDoor:u.indoorOutdoor,surfaceCategory:u.surfaceCategory,endDate:u.endDate},E=to({policyDefinitions:c,tournamentRecord:u,contextProfile:d});return{matchUps:h.flatMap(N=>(y.eventDrawsCount=N.drawDefinitions?.length??0,Mn({context:y,scheduleVisibilityFilters:o,tournamentAppliedPolicies:T,participantsProfile:i,afterRecoveryTimes:s,policyDefinitions:c,tournamentRecord:u,usePublishState:m,contextContent:E,contextFilters:f,contextProfile:d,matchUpFilters:l,participantMap:r,nextMatchUps:g,participants:n,inContext:p,event:N}).matchUps??[])).concat(...u.matchUps??[])}}function cn({scheduleVisibilityFilters:t,afterRecoveryTimes:e,participantsProfile:r,tournamentRecords:n,policyDefinitions:o,usePublishState:i,matchUpFilters:s,contextFilters:a,nextMatchUps:c,inContext:u}){if(typeof n!="object"||!Object.keys(n).length)return{error:kt};let m=Object.keys(n).map(d=>{let l=n[d];return qt({scheduleVisibilityFilters:t,afterRecoveryTimes:e,participantsProfile:r,policyDefinitions:o,tournamentRecord:l,usePublishState:i,matchUpFilters:s,contextFilters:a,nextMatchUps:c,inContext:u}).matchUps??[]}).flat();return{...P,matchUps:m}}function ji(t,e){return Fj(t,e)||(t?.stageSequence||0)-(e?.stageSequence||0)||t?.roundNumber&&e.roundNumber&&t?.roundNumber-e?.roundNumber||(t?.roundPosition??0)-(e?.roundPosition??0)}function Fj(t,e){return(Aa[t?.stage]||0)-(Aa[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:S,event:h}=t,{eventId:T,eventName:y,endDate:E,eventType:A,category:N,gender:U,matchUpFormat:R}=h??{},D={...S,surfaceCategory:h?.surfaceCategory??p?.surfaceCategory,indoorOutDoor:h?.indoorOutdoor??p?.indoorOutdoor,matchUpFormat:R,eventType:A,eventName:y,category:N,eventId:T,endDate:E,gender:U},b;return!e?.length&&!r&&p&&({participants:e=[],participantMap:r,groupInfo:b}=si({participantsProfile:s,useParticipantMap:u,policyDefinitions:c,tournamentRecord:p,contextProfile:l,inContext:I})),l&&!n&&(n=to({policyDefinitions:c,tournamentRecord:p,contextProfile:l,drawDefinition:f,event:h})),{...te({context:D,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:h}),groupInfo:b}}var Sb=t=>e=>!t||typeof e!="object"?void 0:Array.isArray(t)&&t.map(r=>({[r]:Li({element:e,accessor:r})?.value}))||typeof t=="object"&&Object.keys(t).map(r=>({[r]:Li({element:e,accessor:r})?.value}))||(typeof t=="string"&&Li({element:e,accessor:t}))?.value,Fr=Sb;function hc({finishingPositionOffset:t=0,finishingPositionLimit:e,positionsFed:r,roundsCount:n,roundLimit:o,matchUps:i,lucky:s,fmlc:a}){if(!Nr(i))return[];let{roundProfile:c,roundNumbers:u=[]}=De({interpolate:!0,matchUps:i});n=n??Math.max(...u,0);let p=o?n-o:0,m=p&&c?.[n-p]?.matchUpsCount,d=c&&Object.values(c).map(Fr("matchUpsCount")),l=(I,S)=>{let h=Math.min(...I);m&&S&&h===1&&(h=m);let T=Math.max(...I);return e&&T>e&&(T=e),[h,T]},f=c&&Object.assign({},...u.map(I=>{let S=(n??0)+1-I-p,h=c[I].matchUpsCount,T={finishingPositionRange:{},finishingRound:S},y=d?.slice(I-1).reduce((C,_)=>C+(_||0),0),E=a&&I!==1,A=1+t+(E?r??0:0),N=1,U=Q(A,s?A+h*2:y+A+N),R=y+N-h,D=l(U.slice(R)),b=l(U.slice(0,R),!0);return T.finishingPositionRange={loser:D,winner:b},{[I]:T}})),g=je({finishingRound:!0});return i.filter(Boolean).forEach(I=>{let S=I.roundNumber&&f[I.roundNumber];g&&!S&&console.log({roundFinishingData:f,matchUp:I}),I.finishingRound=S?.finishingRound,I.finishingPositionRange=S?.finishingPositionRange}),i}function Ts({inContextDrawMatchUps:t,drawDefinition:e,matchUpsMap:r}){if(!e)return{error:$};let n={loserMatchUpIds:{},winnerMatchUpIds:{}};if(t||({matchUps:t,matchUpsMap:r}=te({inContext:!0,drawDefinition:e,matchUpsMap:r})),!r?.drawMatchUps.some(i=>i.finishingPositionRange)&&e?.structures?.length===1&&!e?.structures[0].structures){let i=r?.drawMatchUps??[];hc({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=Vo({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 tn(t){let e=Ar(t),r=t.matchUps??[],n=t.drawIds??[],{includeParticipantDependencies:o,tournamentRecord:i,drawDefinition:s}=t;if(!Array.isArray(r))return{error:Vn};if(!Array.isArray(n))return{error:Pn};let a=t.matchUpIds?.length?t.matchUpIds:r.map(T=>T.matchUpId);if(!Array.isArray(a))return{error:Ms};let c={},u={},p={},m={};i&&!Object.keys(e).length&&(e={[i.tournamentId]:i});let d=Object.values(e),f=d.reduce((T,y)=>T.concat(y.events??[]).map(E=>(E.drawDefinitions??[]).map(A=>A.links??[])).flat(1/0),[]).filter(({linkType:T})=>T===fn),g=r;f.length&&(g=cn({nextMatchUps:!0,tournamentRecords:e}).matchUps,kj({positionLinks:f,sourceStructureIdMap:p,positionDependencies:c,matchUps:g}));let I=T=>{u[T]||(u[T]={dependentMatchUpIds:[],participantIds:[],matchUpIds:[],sources:[]},m[T]=[])},S=(T,y)=>{u[T].matchUpIds.forEach(A=>{u[y].matchUpIds.push(A)}),u[y].matchUpIds.push(T),u[T].dependentMatchUpIds.push(y),o&&u[T].participantIds.forEach(A=>u[y].participantIds.push(A))},h=T=>{let y=Object.keys(c).length;for(let E of T??[]){let{matchUpId:A,winnerMatchUpId:N,loserMatchUpId:U}=E;if(!a.length||a.includes(A)){if(I(A),o){let{individualParticipantIds:b}=Dp(E);u[A].participantIds=b}N&&(I(N),S(A,N),m[N].push(A)),U&&(I(U),S(A,U),m[U].push(A)),u[A].sources.push(m[A]);let R=m[A].map(b=>u[b].sources[0]).flat(),D=m[A].map(b=>u[b].sources[1]).flat();if(u[A].sources.push(R,D),y){let b=E.containerStructureId||E.structureId,C=p[b];if(c[C])for(let _ of c[C])I(_),S(_,A),m[_].push(A)}}}};if(s)Ts({drawDefinition:s}),g?.length||(g=rr({drawDefinition:s}).matchUps),h(g);else{g?.length||(g=cn({nextMatchUps:!0,tournamentRecords:e}).matchUps),n.length||(n=Gj(d));for(let T of n)Vj({matchUps:g,drawId:T,tournamentRecords:e,processMatchUps:h})}return{positionDependencies:c,matchUpDependencies:u,sourceMatchUpIds:m,matchUps:g,...P}}function kj({positionLinks:t,sourceStructureIdMap:e,positionDependencies:r,matchUps:n}){let o=t.reduce((i,s)=>{let a=s.source?.structureId,c=s.target?.structureId;return a&&c&&(e[c]=a),a&&!i.includes(a)&&i.push(a),i},[]);for(let i of o)r[i]=[];for(let i of n??[]){let s=i.containerStructureId||i.structureId;o.includes(s)&&r[s].push(i.matchUpId)}}function Gj(t){return t?.length?t.map(({events:e=[]})=>e.map(({drawDefinitions:r=[]})=>r.map(({drawId:n})=>n))).flat(1/0):[]}function Vj({matchUps:t,drawId:e,tournamentRecords:r,processMatchUps:n}){let o=t?.filter(s=>s.drawId===e).sort(ji);if(!o?.find(({roundPosition:s})=>!s)){let s=o?.find(({tournamentId:c})=>c),{drawDefinition:a}=_e({tournamentRecord:r[s?.tournamentId],drawId:e});a&&Ts({drawDefinition:a})}n(o)}function ue(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 Oa({matchUpStatus:t}){return _y.includes(t)}function qL({matchUpStatus:t}){return Nl.includes(t)}function iS({matchUpStatus:t}){return xy.includes(t)}function sS({matchUpStatus:t,winningSide:e,tieMatchUps:r,sides:n,score:o}){let i=n?.find(({participantId:c})=>c),s=r?.filter(sS)?.length;return ue({score:o})||s||e&&i||t&&qL({matchUpStatus:t})&&![xt,Lt,bn].includes(t)}function qi(t){let{drawDefinition:e,findContainer:r,structureId:n,event:o}=t,i=t.structure,{containedStructures:s}=Vi({drawDefinition:e}),a=n?s[n]??[]:[],c={isCollectionMatchUp:!1};if(!i){let N=tt({drawDefinition:e,structureId:n});if(N.error)return N;i=r?N.containingStructure??N.structure:N.structure}if(Ae({structure:i}))return{structure:i,isAdHoc:!0,error:is};let{matchUps:u}=te({inContext:!0,matchUpFilters:c,drawDefinition:e,event:o}),p=u?.filter(N=>N.structureId===n||a.includes(N.structureId)),{matchUpDependencies:m}=tn({drawIds:[e.drawId],matchUps:u,drawDefinition:e}),d=[],l=[],f={},g=[];for(let N of u??[]){if(N.structureId===n||a.includes(N.structureId)){l.push(...N.drawPositions??[]);let U=N.roundNumber;for(let R of(N.drawPositions??[]).filter(Boolean))(!f[R]||U&&f[R]>U)&&(f[R]=U)}sS(N)&&(g.push(N),d.push(N.matchUpId,...m?.[N?.matchUpId]?.matchUpIds??[]))}let I=pt(l.filter(Boolean)).sort(Zt),S=pt(d),h=pt(p?.map(({matchUpId:N,drawPositions:U})=>S.includes(N)?U:[]).flat().filter(Boolean)).sort(Zt),{positionAssignments:T}=Pt({drawDefinition:e,structure:i}),y=T?.filter(N=>N.bye).map(N=>N.drawPosition),E=T?.filter(N=>N.qualifier).map(N=>N.drawPosition),A=I?.filter(N=>!h.includes(N))??[];return{allDrawPositions:I,inContextStructureMatchUps:p,drawPositionInitialRounds:f,activeDependentMatchUpIds:S,qualifyingDrawPositions:E,inactiveDrawPositions:A,positionAssignments:T,activeDrawPositions:h,byeDrawPositions:y,activeMatchUps:g,structure:i}}function qs({drawPosition:t,matchUps:e=[]}){return{initialRoundNumber:e.filter(({drawPositions:n})=>t&&n?.includes(t)).map(({roundNumber:n})=>n).sort(Zt)[0]}}var Tc={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 lE=[];function Pe(t,e){_t(t)&&(t={method:t}),(e||je())&&lE.push(t)}function Bj(t){let e=lE.slice();return t&&(lE.length=0),e}function $L(t){let r=Bj(t).map(n=>{let{color:o,keyColors:i,method:s,newline:a}=n,c=Object.keys(Tc).includes(o)?Tc[o]:Tc.cyan,p=Object.keys(n).filter(d=>!["color","keyColors","method","newline"].includes(d)).map(d=>{let l=i&&Object.keys(i).includes(d)&&Tc[i[d]]?Tc[i[d]]:Tc.brightwhite;return`${Tc.white}${d}: ${l}${n[d]}`}).join(", "),m=s?.length<15?" ":" ";return[a?`
2
2
  `:"",c,s,m,Tc.white,p,Tc.reset,`
3
3
  `].join("")});r?.length&&console.log(...r)}function KL(){lE.length=0}function Kl(t){let e=t.bye,r=t.qualifier,n=t.participantId;return{containsBye:e,containsQualifier:r,containsParticipant:n,filled:e||r||n}}function Ye(t){return[xt,Lt,Ue].includes(t)}function Cr({provisionalPositioning:t,isPositionAction:e,tournamentRecord:r,drawDefinition:n,drawPosition:o,loserMatchUp:i,matchUpsMap:s,structureId:a,structure:c,event:u}){if(!n)return{error:$};if(c||({structure:c}=tt({drawDefinition:n,structureId:a})),!c)return{error:Nt};a||({structureId:a}=c);let p="assignDrawPositionBye";Pe({method:p,color:"cyan",drawPosition:o}),s??=Ie({drawDefinition:n});let{positionAssignments:m}=Pt({structure:c}),{activeDrawPositions:d}=qi({drawDefinition:n,structureId:a});if(m?.find(v=>v.drawPosition===o)?.bye)return{...P};if(an(n.drawType)&&m?.filter(w=>w.bye&&w.drawPosition!==o)?.length)return M({result:{error:kU},stack:p});let f=!!(i&&s.drawMatchUps.some(v=>v.loserMatchUpId===i?.matchUpId&&Ye(v.matchUpStatus)));if(d?.includes(o)&&!f)return{error:Vc};let I=m?.find(v=>v.drawPosition===o);I||(I={drawPosition:o},m?.push(I));let{filled:S,containsBye:h,containsParticipant:T}=Kl(I);if(h)return{...P};if(S&&!h&&!f)return M({result:{error:kc},stack:p});let y=It({tournamentRecord:r,drawDefinition:n,event:u}).appliedPolicies??{},E=te({inContext:!0,drawDefinition:n,matchUpsMap:s}).matchUps??[],A={isCollectionMatchUp:!1},{matchUps:N}=ht({provisionalPositioning:t,drawDefinition:n,matchUpFilters:A,matchUpsMap:s,structure:c});if(m?.forEach(v=>{v.drawPosition===o&&(v.bye=!0,f&&(v.participantId=void 0))}),c.structureType===de)return Hj({tournamentRecord:r,drawDefinition:n,drawPosition:o,matchUps:N}),Sn({tournamentId:r?.tournamentId,drawDefinition:n,structure:c,event:u}),zL({assignedParticipantId:T,isPositionAction:e,appliedPolicies:y,drawDefinition:n,drawPosition:o,structureId:a,stack:p});let{roundProfile:U,roundMatchUps:R}=De({matchUps:N}),b=(U&&Object.keys(U).map(v=>Number.parseInt(v)).reverse())?.find(v=>U?.[v].drawPositions?.includes(o)),C=b?R?.[b].find(({drawPositions:v})=>v?.includes(o)):void 0;C&&QL({tournamentRecord:r,drawDefinition:n,matchUp:C,event:u});let _=C?.drawPositions?.find(v=>v!==o);if(C&&_){let v=fE({sourceDrawPositions:C.drawPositions,matchUpId:C.matchUpId,inContextDrawMatchUps:E,drawPositionToAdvance:_,tournamentRecord:r,drawDefinition:n,matchUpsMap:s});if(v.error)return v}return Sn({tournamentId:r?.tournamentId,drawDefinition:n,structure:c,event:u}),zL({assignedParticipantId:T,isPositionAction:e,appliedPolicies:y,drawDefinition:n,drawPosition:o,structureId:a,stack:p})}function zL({assignedParticipantId:t,isPositionAction:e,appliedPolicies:r,drawDefinition:n,drawPosition:o,structureId:i,stack:s}){return e&&fc({appliedPolicies:r,drawDefinition:n,positionAction:{removedParticipantId:t,drawPosition:o,structureId:i,name:s}}),M({result:{...P},stack:s})}function QL({tournamentRecord:t,drawDefinition:e,eventId:r,matchUp:n,event:o}){Object.assign(n,{matchUpStatus:"BYE",score:void 0,winningSide:void 0}),gt({tournamentId:t?.tournamentId,eventId:r??o?.eventId,context:"setMatchUpStatusBye",drawDefinition:e,matchUp:n})}function Hj({tournamentRecord:t,drawDefinition:e,drawPosition:r,matchUps:n,event:o}){n.forEach(i=>{i.drawPositions?.includes(r)&&QL({eventId:o?.eventId,tournamentRecord:t,drawDefinition:e,matchUp:i})})}function fE({drawPositionToAdvance:t,inContextDrawMatchUps:e,sourceDrawPositions:r,tournamentRecord:n,drawDefinition:o,matchUpsMap:i,matchUpId:s,event:a}){Pe({method:"advanceDrawPosition",color:"cyan",drawPositionToAdvance:t});let u=i.drawMatchUps.find(N=>N.matchUpId===s),m=e.find(N=>N.matchUpId===s)?.structureId,{structure:d}=tt({drawDefinition:o,structureId:m}),{positionAssignments:l}=Pt({structure:d}),f=l?.filter(N=>N.bye).map(N=>N.drawPosition),g=u?.drawPositions?.find(N=>N!==t),I=g&&f?.includes(g),{targetLinks:{loserTargetLink:S},targetMatchUps:{loserMatchUp:h,winnerMatchUp:T,loserTargetDrawPosition:y}}=er({inContextDrawMatchUps:e,drawDefinition:o,matchUpId:s}),E=an(o?.drawType),A=!E||!u?.roundNumber||!d?.matchUps?!1:d.matchUps.filter(U=>U.roundNumber===u.roundNumber).length%2!==0;if(T&&T.structureId===d?.structureId&&(!E||!A)&&Wj({drawPositionToAdvance:t,inContextDrawMatchUps:e,sourceDrawPositions:r,tournamentRecord:n,drawDefinition:o,winnerMatchUp:T,matchUpsMap:i,event:a}),h&&I&&h.structureId!==d?.structureId){let{roundNumber:N}=h;if(N===1){let U=Cr({structureId:S.target.structureId,drawPosition:y,tournamentRecord:n,drawDefinition:o,event:a});if(U.error)return U}else XL({loserTargetDrawPosition:y,tournamentRecord:n,loserTargetLink:S,drawDefinition:o,loserMatchUp:h,matchUpsMap:i,event:a})}return{...P}}function Wj({drawPositionToAdvance:t,inContextDrawMatchUps:e,sourceDrawPositions:r,tournamentRecord:n,drawDefinition:o,winnerMatchUp:i,matchUpsMap:s,event:a}){let c="advanceWinner",u=s.drawMatchUps.find(x=>x.matchUpId===i.matchUpId),m=e.find(x=>x.matchUpId===i.matchUpId)?.structureId,{structure:d}=tt({drawDefinition:o,structureId:m}),{positionAssignments:l}=Pt({structure:d}),g=l?.find(({drawPosition:x})=>x===t)?.bye,I=u.drawPositions?.filter(Boolean),S=l?.filter(x=>I?.includes(x.drawPosition)),h=l?.find(({drawPosition:x})=>x===t),T=r?.find(x=>x!==t),E=(T&&S?.find(({drawPosition:x})=>x===T))?.bye,A=g&&E;if(A&&console.log({isByeAdvancedBye:A}),I?.length>1&&g&&!E)return M({result:{error:kc},stack:c});let N=I?.find(x=>x!==t),U=A,R=[...(u.drawPositions??[]).filter(Boolean),void 0,void 0].slice(0,2),D=R.map(x=>!x&&!U||x===t?(U=!0,t):x).sort(Zt);if(!U)return console.log("@@@@@@@",{advancingAssignmentIsBye:h,drawPositionToAdvance:t,existingAssignments:S}),M({result:{error:kc},stack:c});let b=l?.find(({drawPosition:x})=>x===N)?.bye,C=l?.find(({drawPosition:x})=>x===t)?.bye;Object.assign(u,{matchUpStatus:C||b?"BYE":zt,score:void 0,winningSide:void 0,drawPositions:D});let v=u.drawPositions.find(x=>!R.includes(x));Pe({method:c,color:"brightyellow",changedDrawPosition:v,pairedDrawPositionIsBye:b,drawPositionIsBye:C}),gt({tournamentId:n?.tournamentId,matchUp:u,eventId:a?.eventId,context:c,drawDefinition:o});let{targetLinks:{loserTargetLink:w},targetMatchUps:{loserMatchUp:L,loserTargetDrawPosition:F}}=er({matchUpId:i.matchUpId,inContextDrawMatchUps:e,drawDefinition:o});if(b||C){let x=b?t:N;if(x)fE({drawPositionToAdvance:x,matchUpId:i.matchUpId,inContextDrawMatchUps:e,tournamentRecord:n,drawDefinition:o,matchUpsMap:s});else if(C&&w&&L)if(L.feedRound)XL({loserTargetDrawPosition:F,tournamentRecord:n,loserTargetLink:w,drawDefinition:o,loserMatchUp:L,matchUpsMap:s});else{let G=1-i.roundPosition%2,V=L.drawPositions[G],B=Cr({structureId:w.target.structureId,drawPosition:V,tournamentRecord:n,drawDefinition:o,event:a});if(B.error)return B}}}function XL({loserTargetDrawPosition:t,tournamentRecord:e,loserTargetLink:r,drawDefinition:n,loserMatchUp:o,matchUpsMap:i,event:s}){let{roundNumber:a}=o;Pe({method:"assignFedDrawPositionBye",color:"cyan",loserTargetDrawPosition:t});let p=(i?.mappedMatchUps??{})[o.structureId].matchUps,{initialRoundNumber:m}=qs({drawPosition:t,matchUps:p});if(m===a){let d=Cr({structureId:r.target.structureId,drawPosition:t,tournamentRecord:e,drawDefinition:n,event:s});if(d.error)return d}}function gE({positionAssignments:t,tournamentRecord:e,drawDefinition:r,matchUpsMap:n,structure:o,event:i}){let{matchUps:s}=ht({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?"BYE":zt}),gt({tournamentId:e?.tournamentId,context:"modifyRoundRobinMatchUpsStatus",eventId:i?.eventId,drawDefinition:r,matchUp:a}))})}function Su(t){let{inContextDrawMatchUps:e,participantId:r,drawPosition:n}=t,{tournamentRecord:o,drawDefinition:i,structureId:s,matchUpsMap:a,event:c}=t,{structure:u}=tt({drawDefinition:i,structureId:s}),m=(se({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:da};r||(r=m?.participantId);let{activeDrawPositions:d}=qi({drawDefinition:i,structureId:s});return d.includes(n)?{error:Vc}:(e||({matchUps:e}=te({inContext:!0,drawDefinition:i,matchUpsMap:a})),hb({inContextDrawMatchUps:e,tournamentRecord:o,drawDefinition:i,structureId:s,drawPosition:n,matchUpsMap:a,event:c}).drawPositionCleared?(Sn({tournamentId:o?.tournamentId,drawDefinition:i,structure:u,event:c}),{...P,participantId:r}):{error:EU})}function hb({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,matchUpsMap:o,structureId:i,event:s}){let{structure:a}=tt({drawDefinition:r,structureId:i});if(!a)return{error:Nt};let c=se({drawDefinition:r,structure:a}).positionAssignments??[],u=c.some(h=>{if(h.drawPosition===n)return delete h.participantId,delete h.qualifier,delete h.bye,!0});if(a.structureType===de)return gE({positionAssignments:c,tournamentRecord:e,drawDefinition:r,matchUpsMap:o,structure:a}),{drawPositionCleared:u,...P};let p={isCollectionMatchUp:!1},{matchUps:m}=ht({drawDefinition:r,matchUpFilters:p,matchUpsMap:o,structure:a,event:s}),{roundProfile:d,roundMatchUps:l}=De({matchUps:m}),g=(d&&Object.keys(d))?.map(h=>st(h)),I=jj({roundNumbers:g,roundProfile:d,positionAssignments:c,drawPosition:n}),S=qj(I);return S?.forEach(({roundNumber:h,targetDrawPosition:T,relevantPair:y})=>{let E=l?.[h].find(A=>Re(A.drawPositions?.filter(Boolean),y.filter(Boolean)));E&&(Yj({inContextDrawMatchUps:t,targetDrawPosition:T,tournamentRecord:e,drawDefinition:r,structureId:i,roundNumber:h,matchUpsMap:o}),JL({inContextDrawMatchUps:t,positionAssignments:c,tournamentRecord:e,drawDefinition:r,targetMatchUp:E,drawPosition:n,matchUpsMap:o,structure:a,event:s}))}),{tasks:S,drawPositionCleared:u,positionAssignments:c}}function Yj({inContextDrawMatchUps:t,targetDrawPosition:e,tournamentRecord:r,drawDefinition:n,matchUpsMap:o,roundNumber:i,structureId:s}){let{structure:a}=tt({drawDefinition:n,structureId:s});if(!a)return{error:Nt};if(a.structureType===de)return;o=o||Ie({drawDefinition:n});let u=(o?.mappedMatchUps??{})[s].matchUps,{initialRoundNumber:p}=qs({drawPosition:e,matchUps:u}),m=u?.filter(l=>l.roundNumber>=i&&l.roundNumber!==p&&l.drawPositions?.includes(e)),d=Pt({drawDefinition:n,structureId:s}).positionAssignments??[];return m?.forEach(l=>JL({drawPosition:e,targetMatchUp:l,inContextDrawMatchUps:t,positionAssignments:d,tournamentRecord:r,drawDefinition:n,matchUpsMap:o,structure:a})),{...P}}function JL({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??Ie({drawDefinition:n});let f=s.mappedMatchUps[a.structureId].matchUps,{initialRoundNumber:g}=qs({drawPosition:i,matchUps:f});if(o.roundNumber&&g&&o.roundNumber>g){let A=(o.drawPositions??[]).map(N=>N===i?void 0:N);o.drawPositions=A}$j({inContextDrawMatchUps:t,tournamentRecord:r,drawDefinition:n,targetMatchUp:o,drawPosition:i,event:c,stack:u});let I=er({matchUpId:o.matchUpId,inContextDrawMatchUps:t,drawDefinition:n}),{targetLinks:{winnerTargetLink:S},targetMatchUps:{loserMatchUp:h,winnerMatchUp:T,loserMatchUpDrawPositionIndex:y}}=I,E=Kj({initialDrawPositions:p,initialMatchUpStatus:m,initialWinningSide:d,positionAssignments:e,tournamentRecord:r,drawDefinition:n,targetMatchUp:o,drawPosition:i,event:c,stack:u});if(h&&h.structureId!==I.matchUp.structureId&&!E){let A=zj({loserMatchUpDrawPositionIndex:y,inContextDrawMatchUps:t,tournamentRecord:r,drawDefinition:n,loserMatchUp:h,matchUpsMap:s,event:c,stack:u});if(A?.error)return A}return T&&T.structureId!==I.matchUp.structureId&&(S.target.feedProfile,ln),{...P}}function jj({roundNumbers:t,roundProfile:e,positionAssignments:r,drawPosition:n}){let o=n;return t?.map(i=>{let a=e?.[i]?.pairedDrawPositions?.find(I=>I.includes(o)),c=a?.find(I=>I!==o),u=r.find(I=>I.drawPosition===c),p=e?.[i+1],m=u?.bye,d=p?.pairedDrawPositions?.find(I=>I.includes(c)),l=m&&d&&p?.drawPositions?.includes(c),g=a&&{pairedDrawPositionByeAdvancedPair:!l&&d,pairedDrawPosition:c,targetDrawPosition:o,relevantPair:a,roundNumber:i};return l&&(o=c),g}).filter(i=>i?.targetDrawPosition)}function qj(t){return t?.reduce((e,r)=>{let{roundNumber:n,relevantPair:o,targetDrawPosition:i,pairedDrawPosition:s,pairedDrawPositionByeAdvancedPair:a}=r,c={roundNumber:n,targetDrawPosition:i,relevantPair:o},u=a&&{roundNumber:n+1,targetDrawPosition:s,relevantPair:a,subsequentRoundRemoval:!0},p=[c,u].filter(Boolean);return e.concat(...p)},[])}function $j({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,targetMatchUp:n,drawPosition:o,event:i,stack:s}){if(n.matchUpType!==Ot)return;let u=(t?.find(p=>p.matchUpId===n.matchUpId)?.sides??[]).reduce((p,m,d)=>m.drawPosition===o?d:p,void 0);u!==void 0&&n.sides?.[u]?.lineUp&&(delete n.sides?.[u].lineUp,gt({tournamentId:e?.tournamentId,context:`${s}-TEAM`,eventId:i?.eventId,matchUp:n,drawDefinition:r}))}function Kj({initialDrawPositions:t,initialMatchUpStatus:e,initialWinningSide:r,positionAssignments:n,tournamentRecord:o,drawDefinition:i,targetMatchUp:s,drawPosition:a,event:c,stack:u}){let m=n.filter(({drawPosition:g})=>s.drawPositions?.includes(g)).filter(g=>g.bye).length,d=m&&"BYE"||s.matchUpStatus&&Ye(s.matchUpStatus)&&s.matcHUpStatus||zt;s.matchUpStatus=d,s.matchUpStatus&&Ye(s.matchUpStatus)&&(s.winningSide=void 0);let l=t?.find(g=>!s.drawPositions?.includes(g));return t?.includes(a)&&e===s.matchUpStatus&&r===s.winningSide||(l&&Pe({method:u,color:"brightyellow",removedDrawPosition:l}),gt({tournamentId:o?.tournamentId,context:`${u}-${a}`,eventId:c?.eventId,matchUp:s,drawDefinition:i})),m}function zj({loserMatchUpDrawPositionIndex:t,inContextDrawMatchUps:e,tournamentRecord:r,drawDefinition:n,loserMatchUp:o,matchUpsMap:i,event:s,stack:a}){let{drawPositions:c,roundNumber:u}=o;if(u===1){let g=c[t];hb({structureId:o.structureId,drawPosition:g,inContextDrawMatchUps:e,tournamentRecord:r,drawDefinition:n,matchUpsMap:i});return}let p=Math.min(...c.filter(Boolean)),m=Qj({loserMatchUpDrawPosition:p,inContextDrawMatchUps:e,tournamentRecord:r,drawDefinition:n,loserMatchUp:o,matchUpsMap:i,event:s});if(m.error)return M({result:m,stack:a});let l=(i?.mappedMatchUps??{})[o.structureId].matchUps,{initialRoundNumber:f}=qs({drawPosition:p,matchUps:l});f===1&&(Pe({method:a,color:"brightyellow",loserMatchUpDrawPosition:p}),hb({structureId:o.structureId,drawPosition:p,inContextDrawMatchUps:e,tournamentRecord:r,drawDefinition:n,matchUpsMap:i}))}function Qj({loserMatchUpDrawPosition:t,inContextDrawMatchUps:e,tournamentRecord:r,drawDefinition:n,loserMatchUp:o,matchUpsMap:i,event:s}){let{structure:a}=tt({structureId:o.structureId,drawDefinition:n}),{positionAssignments:c}=Pt({structure:a});if(c?.find(p=>p.drawPosition===t)?.bye){let p=Su({drawPosition:t,structureId:o.structureId,inContextDrawMatchUps:e,tournamentRecord:r,drawDefinition:n,matchUpsMap:i,event:s});if(p.error)return p}return{...P}}function $i({drawDefinition:t,stages:e}){if(!t)return{error:$};let r=(t?.structures??[]).filter(o=>!e?.length||o.stage&&e.includes(o.stage)),n=pt(r.map(o=>{let{positionAssignments:i}=Pt({structure:o});return i?i.map(ft):[]}).flat().filter(Boolean));return{...P,assignedParticipantIds:n}}function ro(t){let e=(t?.entries??[]).filter(Boolean).reduce((n,o)=>{let{entryStage:i,entryStatus:s}=o,a=`_${i||H}${s||""}`;return n[a]||(n[a]=[]),n[a].push(o),n},{}),r=n=>Number.isNaN(Number(n))?1/0:n;return Object.keys(e).flatMap(n=>e[n].sort((o,i)=>r(o.entryPosition)-r(i.entryPosition)).map((o,i)=>{let s=i+1;return{...o,entryPosition:s}}))}function $s(t){return[Bi,Lr].includes(t)}function zl({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}){let d=Xj({participantIds:o,drawDefinition:n,entryStatus:i,entryStage:s,extension:a,event:m});if(d)return d;let l="modifyEntriesStatus",f=[],g=Jj({event:m,stage:p}),I=r?.participants??[];if(!Zj({participantIds:o,tournamentParticipants:I,entryStatus:i,event:m}))return{error:$g};let S=m&&Bt({event:m}).flightProfile,h=S?.flights?.find(D=>D.drawId===u),T=tq({assignedParticipantIds:g,ignoreAssignment:e,participantIds:o,entryStatus:i,entryStage:s,extension:a,stage:p}),y=({flight:D,drawDefinition:b})=>{m&&(m.entries=ro({entries:m.entries??[]})),D&&(D.drawEntries=ro({entries:D.drawEntries})),b&&(b.entries=ro({entries:b.entries}))},E=({flight:D,drawDefinition:b})=>{let C="updateDrawEntries";if(D){let _=T(D.drawEntries);if(_.error)return M({result:_,stack:C})}if(b){let _=T(b.entries);if(_.error)return M({result:_,stack:C});f.includes(b.drawId)||f.push(b.drawId)}return{...P}},A=m?.entries?.find(({entryPosition:D})=>D)??(h?.drawEntries?.find(({entryPosition:D})=>D)||n?.entries?.find(({entryPosition:D})=>D));if(t&&!A&&y({flight:h,drawDefinition:n}),h||n){let D=E({flight:h,drawDefinition:n});if(D.error)return M({result:D,stack:l})}let N=m?.drawDefinitions?.map(({drawId:D})=>D)??[],U=S?.flights?.filter(D=>!N.includes(D.drawId))??[];for(let D of U){let b=D&&E({flight:D,drawDefinition:void 0});if(b?.error)return M({result:b,stack:l})}let R=S?.flights?.length===1&&(m?.drawDefinitions?.length??0)<=S?.flights?.length;if(!h&&!n&&i&&ob.includes(i))return{error:aD};if(!h&&!n||i===Cn||c&&R){let D=T(m?.entries);if(D?.error)return M({result:D,stack:l});if(i===Cn){let b=eq({updateEntryStatus:T,participantIds:o,flightProfile:S,event:m});if(b)return M({result:{error:b},stack:l})}}t&&y({flight:h,drawDefinition:n});for(let D of m?.drawDefinitions??[])f.length&&!f.includes(D.drawId)||Ft({tournamentId:r.tournamentId,eventId:m?.eventId,drawDefinition:D});return{...P}}function Xj({participantIds:t,drawDefinition:e,entryStatus:r,entryStage:n,extension:o,event:i}){if(!t||!Array.isArray(t))return{error:Vr,method:"modifyEntriesStatus",participantIds:t};if(!e&&!i)return{error:le};if(r&&!ib.includes(r))return{error:$g};if(n&&!Jc.includes(n))return{error:tc};let s="modifyEntriesStatus";if(!r&&!o)return M({result:{error:nt},info:"Missing entryStatus",stack:s});if(o&&!Wn({extension:o,requiredAttributes:["name"]}))return M({result:{error:O},info:"Invalid extension",context:{extension:o},stack:s})}function Jj({event:t,stage:e}){let r=[];return t?.drawDefinitions?.forEach(n=>{let o=$i({stages:e&&[e],drawDefinition:n}).assignedParticipantIds??[];r.push(...o)}),r}function Zj({participantIds:t,tournamentParticipants:e,entryStatus:r,event:n}){return t.every(o=>{let i=ni({tournamentParticipants:e,participantId:o})?.participantType;return!(i&&[lt,ur].includes(i)&&$s(r))&&!(r&&n?.eventType&&i===St&&[wt,Ze].includes(n.eventType)&&[Zr,...Qm].includes(r))})}function tq({assignedParticipantIds:t,ignoreAssignment:e,participantIds:r,entryStatus:n,entryStage:o,extension:i,stage:s}){return a=>{let c=(a??[]).filter(m=>!s||!m.entryStage||s===m.entryStage).filter(({participantId:m})=>r.includes(m)),u=m=>n&&t.includes(m.participantId)&&!(Qm.includes(m.entryStatus)&&Qm.includes(n));return c.every(m=>u(m)&&!e?!1:(n&&(m.entryStatus=n,delete m.entryPosition),o&&(m.entryStage=o,delete m.entryPosition),i&&(i.value?ut({element:m,extension:i}):dr({element:m,name:i.name})),!0))?{...P}:{error:Ia}}}function eq({updateEntryStatus:t,participantIds:e,flightProfile:r,event:n}){let o=new Set(e);for(let i of r?.flights??[]){let s=t(i.drawEntries);if(s.error)return s.error;i.drawEntries=i.drawEntries.filter(({participantId:a})=>!o.has(a))}for(let i of n?.drawDefinitions??[]){let s=t(i.entries);if(s.error)return s.error;i.entries=i.entries?.filter(({participantId:a})=>!o.has(a))}}function Tb(t){let e=X(t,[{ratings:!0,[Ge]:jr}]);if(e.error)return e;let r=t.matchUpType&&[Ct,Rt].includes(t.matchUpType)?t.matchUpType:Ct,n=Object.keys(Ke),o=t.targetRatingType&&n.includes(t.targetRatingType)?t.targetRatingType:"ELO",i=t.ratings[r]?t.ratings[r].reduce((d,l)=>d.includes(l.scaleName)?d:d.concat(l.scaleName),[]):[];if(!i)return{error:fe};let s=t.ratings[r]?.find(d=>d.scaleName===o)??t.ratings[r]?.[0];if(i[0]===o)return s;let a=s?.scaleName,c=Ke[s?.scaleName]?.accessor,u=c&&s.scaleValue[c]||s?.scaleValue,p=Ap({sourceRatingType:a,sourceRating:u}),m=Jw({targetRatingType:o,sourceRating:p});return m?{convertedRating:m,sourceRating:u}:{error:O}}function ZL({participantResults:t,sides:e,score:r}){let n=e?.find(({sideNumber:a})=>a===1),o=e?.find(({sideNumber:a})=>a===2),i=n?.participant?.ratings,s=o?.participant?.ratings;if(i?.[Ct]&&s?.[Ct]){let a="ELO",{convertedRating:c}=Tb({ratings:i,targetRatingType:a}),{convertedRating:u}=Tb({ratings:s,targetRatingType:a}),{side1pressure:p,side2pressure:m}=rq({side1ConvertedRating:c,side2ConvertedRating:u,score:r});p&&t[n?.participantId].pressureScores.push(p),m&&t[o?.participantId].pressureScores.push(m);let d=Math.max(...Ke["ELO"].range),l=vg((u-c)/d),f=vg((c-u)/d);t[n?.participantId].ratingVariation.push(l),t[o?.participantId].ratingVariation.push(f)}}function rq({side1ConvertedRating:t,side2ConvertedRating:e,score:r}){let n=Math.max(t,e),o=Math.min(t,e),i=Math.abs(t-e),s=Ke["ELO"].range,a=Math.max(...s),c=(a-n)*0,p=(n+c)/a*i,m=r?.sets?.reduce((T,y)=>T+(y?.side1Score??0),0),d=r?.sets?.reduce((T,y)=>T+(y.side2Score??0),0),l=t>e?2:1,f=(m||0)*(o+(l===1?p:0)),g=(d||0)*(o+(l===2?p:0)),I=f+g,S=I?vg(f/I):0,h=I?vg(g/I):0;return{side1pressure:S,side2pressure:h}}function aS({winningSide:t,matchUpFormat:e=_n,matchUpStatus:r,tallyPolicy:n,score:o}){let i=[0,0],s=o?.sets,a=typeof t=="number"&&t-1,c=oe(e),u=yb(c?.bestOf??1);if(typeof a=="number"&&(r===xt&&n?.setsCreditForDefaults||r===Lt&&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===Ue&&(+i[1-a]===u&&(i[1-a]-=1),n?.setsCreditForRetirements&&(i[a]=u)),i}function IE({matchUpFormat:t=_n,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=oe(t),c=a?.bestOf??1,u=yb(c),p=a?.setFormat?.tiebreakAt||0,m=[[],[]];if(typeof s=="number"&&(r===xt&&n?.gamesCreditForDefaults||r===Lt&&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,S=a?.[g].tiebreakSet,{side1Score:h,side2Score:T}=d;t0(I)&&!S&&(m[0].push(st(h||0)),m[1].push(st(T||0))),S&&d.winningSide&&n?.gamesCreditForTiebreakSets!==!1&&m[d.winningSide-1].push(1)});if(r===Ue&&typeof s=="number"){let d=i.length>u&&a?.finalSetFormat?"finalSetFormat":"setFormat",l=a?.[d];if(t0(l.based)){let f=l?.setTo||0,g=h=>{if(!(!a||h===""))return+h===p-1||+h===p?st(p||0)+1:+h<p?f:p},I=aS({winningSide:e,score:{sets:i},matchUpStatus:r,matchUpFormat:t,tallyPolicy:n});if(m.map(h=>h[s]<=h[1-s]).reduce((h,T)=>h+(T?1:0),0)>I[1-s]){let h=m[s].length,T=g(m[1-s][h-1]);T&&(m[s][h-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 SE({matchUpFormat:t,score:e}){let r=t?oe(t):void 0,n=r?.bestOf??1,o=yb(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(e0(m)){let{side1Score:d,side2Score:l}=a;d&&(s[0]+=st(d||0)),l&&(s[1]+=st(l||0))}else a.side1TiebreakScore&&(s[0]+=st(a.side1TiebreakScore||0)),a.side2TiebreakScore&&(s[1]+=st(a.side2TiebreakScore||0)),(a.side1TiebreakScore||a.side2TiebreakScore)&&a.winningSide&&(i[a.winningSide-1]+=1)}),{pointsTally:s,tiebreaksTally:i}}function yb(t){return t&&Math.ceil(t/2)||1}function e0(t){return t==="P"}function t0(t){return!e0(t)}function r0({participantResults:t,groupingTotal:e,matchUpFormat:r,tallyPolicy:n,totalGames:o,perPlayer:i,totalSets:s}){let a=(r&&oe(r))??{},c=a.bestOf,u=c&&Math.ceil(c/2)||1,p=a.setFormat?.setTo,m=Math.pow(10,n?.precision||3);Object.keys(t).forEach(d=>{let l=t[d].setsWon,f=t[d].setsLost,g=n?.groupTotalSetsPlayed||e==="setsPct"?s:i*(u||0)||l+f,I=Math.round(l/g*m)/m;(I===1/0||Number.isNaN(I))&&(I=g);let S=t[d].tieMatchUpsWon,h=t[d].tieMatchUpsLost,T=S+h,y=Math.round(S/T*m)/m;(y===1/0||Number.isNaN(y))&&(y=S);let E=t[d].matchUpsWon,A=t[d].matchUpsLost,N=E+A,U=Math.round(E/N*m)/m;(U===1/0||Number.isNaN(U))&&(U=E);let R=t[d].gamesWon||0,D=t[d].gamesLost||0,b=(i||0)*(u||0)*(p||0),C=n?.groupTotalGamesPlayed||e==="gamesPct"?o:Math.max(b,R+D),_=Math.round(R/C*m)/m;(_===1/0||Number.isNaN(_))&&(_=0);let v=t[d].pointsWon+t[d].pointsLost,w=Math.round(t[d].pointsWon/v*m)/m;(w===1/0||Number.isNaN(w))&&(w=0),t[d].setsWon=l,t[d].setsLost=f,t[d].setsPct=I,t[d].tieMatchUpsWon=S,t[d].tieMatchUpsPct=y,t[d].matchUpsPct=U,t[d].gamesWon=R,t[d].gamesLost=D,t[d].gamesPct=_,t[d].pointsPct=w,t[d].result=`${t[d].matchUpsWon}/${t[d].matchUpsLost}`})}function Lp({participantIds:t,pressureRating:e,groupingTotal:r,matchUpFormat:n,tallyPolicy:o,perPlayer:i,matchUps:s}){let a={},c=o?.excludeMatchUpStatuses??[],u=nq({matchUps:s,excludeMatchUpStatuses:c,participantIds:t}),{totalSets:p,totalGames:m}=oq({filteredMatchUps:u,excludeMatchUpStatuses:c});for(let d of u??[]){let{matchUpStatus:l,tieMatchUps:f,tieFormat:g,score:I,winningSide:S,sides:h}=d,T=g&&d._disableAutoCalc&&g.collectionDefinitions.every(({scoreValue:A})=>A),y=S&&pq(d),E=S&&mq(d);!y&&!E?i=iq({participantResults:a,manualGamesOverride:T,matchUpStatus:l,tieMatchUps:f,perPlayer:i,score:I,sides:h}):(hu(a,y),hu(a,E),i=aq({winningParticipantId:y,losingParticipantId:E,manualGamesOverride:T,participantResults:a,pressureRating:e,matchUpFormat:n,matchUpStatus:l,tieMatchUps:f,tallyPolicy:o,winningSide:S,perPlayer:i,matchUp:d,score:I,sides:h})),T&&uq({participantResults:a,score:I,sides:h})}return r0({participantResults:a,groupingTotal:r,matchUpFormat:n,tallyPolicy:o,totalGames:m,perPlayer:i,totalSets:p}),{participantResults:a}}function nq({matchUps:t,excludeMatchUpStatuses:e,participantIds:r}){return t?.filter(n=>(n.tieMatchUps||!e.includes(n.matchUpStatus))&&(!r?.length||Yt(r,[Ql(n,0),Ql(n,1)]).length===2))}function oq({filteredMatchUps:t,excludeMatchUpStatuses:e}){let n=t?.flatMap(({score:a,tieMatchUps:c})=>c?c.filter(({matchUpStatus:u})=>!e.includes(u)).flatMap(({score:u})=>u?.sets?.length??0):a?.sets?.length??0)?.reduce((a,c)=>a+c,0),o=a=>a?.sets?.reduce((c,u)=>c+(u?.side1Score??0)+(u?.side2Score??0),0)??0,s=t?.flatMap(({score:a,tieMatchUps:c})=>c?c.filter(({matchUpStatus:u})=>!e.includes(u)).flatMap(({score:u})=>o(u)):o(a))?.reduce((a,c)=>a+c,0);return{totalSets:n,totalGames:s}}function iq({participantResults:t,manualGamesOverride:e,matchUpStatus:r,tieMatchUps:n,perPlayer:o,score:i,sides:s}){if(r&&Mt.includes(r)){let a=Ql({sides:s},0),c=Ql({sides:s},1);a&&(hu(t,a),t[a].matchUpsCancelled+=1),c&&(hu(t,c),t[c].matchUpsCancelled+=1)}else if(n?.length){o=0;for(let a of n)a.winningSide&&sq({participantResults:t,tieMatchUp:a,sides:s}),o0({score:a.score,manualGamesOverride:e,participantResults:t,sides:s})}else o0({manualGamesOverride:e,participantResults:t,score:i,sides:s});return o}function sq({participantResults:t,tieMatchUp:e,sides:r}){let n=r?.find(({sideNumber:i})=>i===e.winningSide)?.participantId,o=r?.find(({sideNumber:i})=>i===e.winningSide)?.participantId;n&&o&&(hu(t,n),hu(t,o),t[n].tieMatchUpsWon+=1,t[o].tieMatchUpsLost+=1,re(Ct)(e.matchUpType)?(t[n].tieSinglesWon+=1,t[o].tieSinglesLost+=1):re(Rt)(e.matchUpType)&&(t[n].tieDoublesWon+=1,t[o].tieDoublesLost+=1))}function aq({winningParticipantId:t,losingParticipantId:e,manualGamesOverride:r,participantResults:n,pressureRating:o,matchUpFormat:i,matchUpStatus:s,tieMatchUps:a,tallyPolicy:c,winningSide:u,perPlayer:p,matchUp:m,score:d,sides:l}){if(a?.length){p=0;for(let f of a)f.winningSide&&cq({winningParticipantId:t,losingParticipantId:e,participantResults:n,tieMatchUp:f,winningSide:u}),i0({matchUpFormat:f.matchUpFormat,matchUpStatus:f.matchUpStatus,matchUpType:f.matchUpType,score:f.score,sides:f.sides,winningParticipantId:t,losingParticipantId:e,manualGamesOverride:r,participantResults:n,isTieMatchUp:!0,pressureRating:o,tallyPolicy:c,winningSide:u});s0({winningParticipantId:t,losingParticipantId:e,participantResults:n,matchUpStatus:s})}else i0({matchUpFormat:m.matchUpFormat??i,matchUpType:m.matchUpType,isTieMatchUp:void 0,winningParticipantId:t,manualGamesOverride:r,losingParticipantId:e,participantResults:n,pressureRating:o,matchUpStatus:s,tallyPolicy:c,winningSide:u,score:d,sides:l});return p}function cq({winningParticipantId:t,losingParticipantId:e,participantResults:r,tieMatchUp:n,winningSide:o}){let{matchUpType:i}=n,s=re(Rt)(i),a=re(Ct)(i),c=n.winningSide===o,u=c?t:e,p=c?e:t;n0(r,u,"Won",a,s),n0(r,p,"Lost",a,s)}function n0(t,e,r,n,o){e&&(t[e][`tieMatchUps${r}`]+=1,n&&(t[e][`tieSingles${r}`]+=1),o&&(t[e][`tieDoubles${r}`]+=1))}function uq({participantResults:t,score:e,sides:r}){let n=e?.sets?.reduce((a,c)=>a+(c?.side1Score??0),0),o=e?.sets?.reduce((a,c)=>a+(c.side2Score??0),0),i=r?.find(({sideNumber:a})=>a===1)?.participantId,s=r?.find(({sideNumber:a})=>a===2)?.participantId;hu(t,i),hu(t,s),i&&(t[i].gamesWon+=n,t[i].gamesLost+=o),s&&(t[s].gamesWon+=o,t[s].gamesLost+=n)}function pq(t){let e=t.winningSide-1;return Ql(t,e)}function mq(t){let e=1-(t.winningSide-1);return Ql(t,e)}function Ql(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 hu(t,e){e&&!t[e]&&(t[e]={allDefaults:0,defaults:0,defeats:[],gamesLost:0,gamesWon:0,matchUpsCancelled:0,matchUpsLost:0,matchUpsWon:0,pointsLost:0,pointsWon:0,pressureScores:[],ratingVariation:[],retirements:0,setsLost:0,setsWon:0,tieSinglesWon:0,tieSinglesLost:0,tieDoublesWon:0,tieDoublesLost:0,tieMatchUpsLost:0,tieMatchUpsWon:0,victories:[],walkovers:0})}function o0({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(st(p||0)),i[1].push(st(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&&(hu(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 i0({winningParticipantId:t,manualGamesOverride:e,losingParticipantId:r,participantResults:n,pressureRating:o,matchUpFormat:i,matchUpStatus:s,isTieMatchUp:a,matchUpType:c,tallyPolicy:u,winningSide:p,score:m,sides:d}){let l=p&&p-1,f=1-l;o&&c===Ct&&ZL({participantResults:n,sides:d,score:m}),a||s0({winningParticipantId:t,losingParticipantId:r,participantResults:n,matchUpStatus:s});let g=aS({matchUpStatus:s,matchUpFormat:i,tallyPolicy:u,winningSide:p,score:m}),I=IE({matchUpStatus:s,matchUpFormat:i,tallyPolicy:u,winningSide:p,score:m}),{pointsTally:S}=SE({score:m,matchUpFormat:i});t&&(n[t].setsWon+=g[l],n[t].setsLost+=g[f],e||(n[t].gamesWon+=I[l],n[t].gamesLost+=I[f]),n[t].pointsWon+=S[l],n[t].pointsLost+=S[f]),r&&(n[r].setsWon+=g[f],n[r].setsLost+=g[l],e||(n[r].gamesWon+=I[f],n[r].gamesLost+=I[l]),n[r].pointsWon+=S[f],n[r].pointsLost+=S[l])}function s0({winningParticipantId:t,losingParticipantId:e,participantResults:r,matchUpStatus:n}){e&&(n===Lt&&(r[e].walkovers+=1),n===xt&&(r[e].defaults+=1),n===Ue&&(r[e].retirements+=1),Ye(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 dq(t,e,r,n){t.groups&&Object.keys(t.groups).sort(n).forEach(o=>{let i=t.groups[o].map(a=>e[a]).join(", "),s=`${o} ${t.attribute}: ${i}`;r.push(s)})}function lq(t,e,r,n){if(t.excludedDirectives?.length){let o=t.excludedDirectives.map(({attribute:a})=>a).join(", "),i=`${o.length} directives were excluded due to participants limit}`;n.push(i);let s=`Excluded: ${o}`;n.push(s)}else{let o=(u,p)=>Number.parseFloat(t.reversed?u:p)-Number.parseFloat(t.reversed?p:u),i=t.groups?Object.values(t.groups).flat(1/0).length:t.participantIds?.length??0,s=t.reversed?" in reverse order":"",a=t.groups?"grouped":"separated",c=`Step ${e+1}: ${i} particiants were ${a}${s} by ${t.attribute}`;if(n.push(c),t.idsFilter){let u=`${t.attribute} was calculated considering ONLY TIED PARTICIPANTS`;n.push(u)}dq(t,r,n,o)}n.push("----------------------")}function a0({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)=>{lq(i,s,n,o)}),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 Eb({participantResults:t,participantIds:e,attribute:r}){return Ab({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 Ab(t){return(t.participantIds||Object.keys(t.participantResults)).reduce((r,n,o)=>(r.push({participantId:n,i:o,results:t.participantResults[n]}),r),[])}var fq=[{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}],Pb={matchUpsPct:20,tieMatchUpsPct:16,pointsPct:4,gamesPct:8,setsPct:12};function Nb(t){let{requireCompletion:e=!0,participantResults:r,subOrderMap:n,tallyPolicy:o}=t,i=[];if(e&&!gq(t))return{};let s=["tieMatchUpsWon","tieSinglesWon","tieDoublesWon","matchUpsWon","pointsWon","gamesWon","setsWon","gamesPct","setsPct","pointsPct","matchUpsPct"].includes(o?.groupOrderKey)?o.groupOrderKey:"matchUpsWon",a=Eb({participantResults:r,attribute:s});i.push({attribute:s,groups:a});let p=Object.keys(a).map(h=>Number.parseFloat(h)).sort((h,T)=>T-h).map(h=>a[h]).map(h=>{let T=c0({participantIds:h,...t});return i.push(...T.report??[]),T.order}).flatMap((h,T)=>h.map(y=>y.resolved?y:{...y,subGroup:[T].concat(...y.subGroup??[])})),m,d=0,l=1,f;p.forEach((h,T)=>{T&&(h.resolved||f&&!h.resolved)&&(l+=1),f=h.resolved;let y=Number.parseInt(h.subGroup?.join("")||0);h.resolved?(h.position=T+1,l=h.position):(m&&y>m&&(l+=d,d=0),h.position=l,d+=1),m=y});let g=p.map(({position:h})=>h),I=mn(g);return p.forEach(h=>{let{participantId:T,position:y}=h??{},E=r[T];h.GEMscore=S(E);let A=I[y];h?.position!==void 0&&(A>1&&(h.ties=A,n&&(h.subOrder=n[T])),h.rankOrder=y,h.groupOrder=y+(h.subOrder||1)-1)}),{groupOrder:p,report:i.flat(1/0).filter(Boolean)};function S(h){return(Array.isArray(o?.GEMscore)?Object.keys(Pb).filter(E=>o.GEMscore.includes(E)):Object.keys(Pb)).map(E=>(h[E]||0)*Math.pow(10,Pb[E].toFixed(3))).reduce((E,A)=>E+A,0)}}function gq({participantResults:t,participantsCount:e}){let n=Ab({participantResults:t}).filter(o=>e-1===o.results.matchUpsWon+o.results.matchUpsLost+o.results.matchUpsCancelled);return e===n.length}function Iq({disableHeadToHead:t,participantIds:e,matchUpFormat:r,groupTotals:n,tallyPolicy:o,attribute:i,idsFilter:s,matchUps:a,reversed:c}){let{participantResults:u}=Lp({participantIds:s&&e,groupingTotal:n&&i,matchUpFormat:r,tallyPolicy:o,matchUps:a}),p=Eb({participantResults:u,participantIds:e,attribute:i}),m=[{attribute:i,reversed:c,groups:p,idsFilter:s,groupTotals:n}],d;return Object.keys(p).length>1&&e.length&&(d=Object.keys(p).map(g=>Number.parseFloat(g)).sort((g,I)=>c?g-I:I-g).map(g=>p[g]).map(g=>{let I=c0({participantResults:u,disableHeadToHead:t,participantIds:g,matchUpFormat:r,tallyPolicy:o,matchUps:a});return m.push(...I.report??[]),I.order}).flatMap((g,I)=>g.map(S=>S.resolved?S:{...S,subGroup:[I].concat(...S.subGroup??[])}))),{order:d,report:m}}function c0({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=Sq({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||fq).filter(m=>{let d=!(Le(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,groupTotals:f,disableHeadToHead:g})=>(c=Iq({disableHeadToHead:g,participantIds:r,matchUpFormat:n,groupTotals:f,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 Sq({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 Ks({policyDefinitions:t,generateReport:e,pressureRating:r,matchUpFormat:n,matchUps:o=[],subOrderMap:i,perPlayer:s}){if(!o?.length||!Nr(o))return{error:Vn};let a=pt(o.map(({structureId:y})=>y));if(a.length!==1)return M({result:{error:O,info:"Maximum one structureId"},stack:"tallyParticipantResults",context:{structureIds:a}});let c=o.filter(y=>y&&y.matchUpStatus!=="BYE"),u=c.length&&pt(c.flatMap(({drawPositions:y})=>y)).length,p=c.filter(y=>js({matchUp:y})).length===c.length;p||(s=0);let m=o.every(({matchUpType:y,tieMatchUps:E})=>y===Ot&&E?.every(A=>js({matchUp:A}))),d=t?.[bI],l=o.filter(y=>js({matchUp:y})??y.matchUpType===Ot),{participantResults:f}=Lp({matchUps:l,pressureRating:r,matchUpFormat:n,tallyPolicy:d,perPlayer:s}),g,I,{groupOrder:S,report:h}=Nb({matchUps:l,participantResults:f,participantsCount:u,matchUpFormat:n,subOrderMap:i,tallyPolicy:d});if(r&&hq({participantResults:f}),p&&S)g=h,I=S,S.forEach(y=>{let{participantId:E,groupOrder:A,rankOrder:N,subOrder:U,ties:R,GEMscore:D}=y,b=f[E];Object.assign(b,{groupOrder:A,rankOrder:N,GEMscore:D,subOrder:U,ties:R})});else{let{groupOrder:y,report:E}=Nb({requireCompletion:!1,participantResults:f,participantsCount:u,matchUpFormat:n,tallyPolicy:d,subOrderMap:i,matchUps:o});g=E,I=y,y&&y.forEach(A=>{let{participantId:N,groupOrder:U,subOrder:R,ties:D,GEMscore:b}=A,C=f[N];Object.assign(C,{provisionalOrder:U,GEMscore:b,subOrder:R,ties:D})})}let T={completedTieMatchUps:m,readableReport:"",participantResults:f,bracketComplete:p,order:[],report:g};if((p||m)&&(T.order=I),e||je({tally:!0})){let y=a0({matchUps:o,report:g,order:I});je({tally:!0})&&console.log(y),T.readableReport=y}return T}function hq({participantResults:t}){let e=o=>o.reduce((i,s)=>i+parseFloat(s),0),r=o=>parseFloat((e(o)/o.length).toFixed(2)),n=Object.keys(t).map(o=>{let i=t[o],{pressureScores:s}=i,a=s?.length?r(s):0;return{participantId:o,averagePressure:a}}).sort((o,i)=>(i.averagePressure||0)-(o.averagePressure||0)).map((o,i)=>({...o,order:i+1}));for(let o of n)t[o.participantId].pressureOrder=o.order}function u0({publishedSeeding:t,usePublishState:e,withSeeding:r,participant:n,event:o}){let i={},s=m=>[ri,ho,o.eventType,m].join("."),a=Object.assign({},...(n.timeItems??[]).filter(({itemType:m})=>m.split(".")[1]===ho).map(({itemType:m,itemValue:d})=>({[m]:d}))),c=(t?.stageSeedingScaleNames&&Object.values(t?.stageSeedingScaleNames)||Array.isArray(t?.seedingScaleNames)&&t.seedingScaleNames||[]).map(s),u=Yt(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:ho,scaleName:g},S=yo({scaleAttributes:I,participant:n});if(S.scaleItem){f=S.scaleItem;break}}if(f&&(!e||t?.published&&!t?.published?.drawIds?.length)){let I=f.scaleValue;i.seedValue=I}}return i}function Xl({positionAssignments:t}){let e=(t??[]).filter(Fr(sr)).map(i=>{let{extension:s}=ot({element:i,name:au}),a=st(s?.value),c=!isNaN(a)&&a;return c&&{participantId:i.participantId,subOrder:c}}).filter(Boolean),r=e.map(({subOrder:i})=>i),n=mn(r);return{subOrderMap:Object.assign({},...e.filter(({subOrder:i})=>n[i]===1).map(({participantId:i,subOrder:s})=>({[i]:s})))}}function p0({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({},...II(m??[])):{},l=Object.assign(d,{entryPosition:p,entryStatus:c,entryStage:u,ranking:s,eventId:i});r.events[i]=et(l,!1,!1,!0),n&&(e&&(r.events[i].seedAssignments=e),o&&(r.events[i].seedValue=o))}function yc(t){let e=X(t,[{[rt]:!0}]);if(e.error)return e;let{tournamentRecord:r,status:n=Ur}=t,o=`${Bo}.${Ho}`;return q(Ml({tournamentRecord:r,itemType:o})?.timeItem?.itemValue?.[n],!1,!0)}function m0(t){let{tournamentId:e}=t??{};return!!e}function Dr({event:t,status:e=Ur}){let r=`${Bo}.${Ho}`;return Mp({itemType:r,event:t})?.timeItem?.itemValue?.[e]}function Fp({drawDetails:t,drawId:e,ignoreEmbargo:r=!1}){let n=t?.[e]?.publishingDetail;return r?!!n?.published:eo(n)}function zs(t){let{tournamentRecord:e,drawDefinition:r,eventIds:n,eventId:o,drawIds:i,drawId:s,event:a}=t??{};if(e&&!m0(e))return{error:O};if(o&&!a)return{error:Gr};if(Array.isArray(n)&&n?.length){let d={};for(let l of n){if(!_t(l))return{error:O};let f=_e({tournamentRecord:e,eventId:l})?.event;if(!f)return{error:Gr};let g=Ub({event:f});d[l]=g}return{...P,publishState:d}}if(a)return Tq({event:a,drawId:s,drawIds:i,drawDefinition:r});let c={},{publishedEventIds:u,tournamentPublished:p}=yq({publishState:c,tournamentRecord:e}),m=[];return e&&Eq({tournamentPublished:p,publishedEventIds:u,tournamentRecord:e,publishState:c,embargoes:m}),Aq({tournamentRecord:e,embargoes:m}),m.length&&(c.embargoes=m),{...P,publishState:c}}function Tq({event:t,drawId:e,drawIds:r,drawDefinition:n}){let o=Ub({event:t}),i={};if(e)return n?{publishState:{status:{published:!!o.status.publishedDrawIds?.includes(e),drawDetail:o.status.drawDetails?.[e]},...P}}:{error:Rr};if(Array.isArray(r)&&r?.length){let s=t.drawDefinitions?.map(dc)??[];for(let a of r){if(!_t(a))return{error:O};if(!s.includes(a))return{error:Rr};i[a]={status:{published:!!o.status.publishedDrawIds.includes(a),drawDetail:o.status.drawDetails?.[a]}}}}else i=o;return{...P,publishState:i}}function yq({publishState:t,tournamentRecord:e}){let r=[],n=!1;for(let o of e?.events??[]){let i=Ub({event:o});t[o.eventId]=i,i.status.published&&(r.push(o.eventId),n=!0);for(let{drawId:s}of o.drawDefinitions??[]){let a=i.status?.publishedDrawIds?.includes(s);a&&(t[s]={status:{published:a}})}}return{publishedEventIds:r,tournamentPublished:n}}function Eq({publishState:t,tournamentRecord:e,tournamentPublished:r,publishedEventIds:n,embargoes:o}){let i=yc({tournamentRecord:e});return t.tournament=i??{},(i?.orderOfPlay?.published||i?.participants?.published)&&(r=!0),t.tournament.status={published:r,publishedEventIds:n},i?.orderOfPlay?.embargo&&o.push({type:"orderOfPlay",embargo:i.orderOfPlay.embargo,embargoActive:Po(i.orderOfPlay)}),i?.participants?.embargo&&o.push({type:"participants",embargo:i.participants.embargo,embargoActive:Po(i.participants)}),r}function Aq({tournamentRecord:t,embargoes:e}){for(let r of t?.events??[]){let o=Dr({event:r})?.drawDetails??{};for(let[i,s]of Object.entries(o))Pq({drawId:i,detail:s,embargoes:e})}}function Pq({drawId:t,detail:e,embargoes:r}){e?.publishingDetail?.embargo&&r.push({type:"draw",id:t,embargo:e.publishingDetail.embargo,embargoActive:Po(e.publishingDetail)});for(let[n,o]of Object.entries(e?.stageDetails??{}))o?.embargo&&r.push({type:"stage",id:`${t}:${n}`,embargo:o.embargo,embargoActive:Po(o)});for(let[n,o]of Object.entries(e?.structureDetails??{}))o?.embargo&&r.push({type:"structure",id:n,embargo:o.embargo,embargoActive:Po(o)}),Nq({structureId:n,structureDetail:o,embargoes:r})}function Nq({structureId:t,structureDetail:e,embargoes:r}){if(e?.scheduledRounds)for(let[n,o]of Object.entries(e.scheduledRounds))o?.embargo&&r.push({type:"scheduledRound",id:`${t}:round${n}`,embargo:o.embargo,embargoActive:Po(o)})}function Ub({event:t}){let e=Dr({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 a of t.drawDefinitions?.map(dc)??[])n[a]||(n[a]={publishingDetail:{published:!1}});let o=n&&Object.keys(n).length&&Object.keys(n).filter(a=>Fp({drawDetails:n,drawId:a,ignoreEmbargo:!0})),i=o?.length?o:e.drawIds??[];if(i?.length&&!o?.length)for(let a of i)n[a]={publishingDetail:{published:!0}};let s=i?.length>0;return{status:{publishedDrawIds:i,publishedSeeding:r,drawDetails:n,published:s}}}function hE(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==="BYE"||e[r].scheduleItems.push({...p,scheduledDate:mt(p?.scheduledDate),scheduledTime:$t(p?.scheduledTime),checkScoreHasValue:ue({score:d}),matchUpStatus:n,roundPosition:o,structureId:i,matchUpType:s,roundNumber:a,matchUpId:c,potential:u,drawId:m})}function d0({finishingPositionRange:t={winner:[],loser:[]},collectionPosition:e,participantMap:r,finishingRound:n,participantWon:o,collectionId:i,matchUpStatus:s,participantId:a,stageSequence:c,roundNumber:u,structureId:p,matchUpId:m,drawId:d,stage:l}){let f=r[a],g=y=>Math.abs(y[0]-y[1]);f.structureParticipation[p]||(f.structureParticipation[p]={rankingStage:l,walkoverWinCount:0,defaultWinCount:0,stageSequence:c,winCount:0,structureId:p,drawId:d});let I=f.structureParticipation[p],{winner:S,loser:h}=t,T=o?S:h;o&&(I.winCount+=1,s===Lt&&(I.walkoverWinCount+=1),s===xt&&(I.defaultWinCount+=1)),T&&(!I.finishingPositionRange||g(T)<g(I.finishingPositionRange))&&(I.finishingPositionRange=T),n&&((!I.finishingRound||n<I.finishingRound)&&(I.finishingMatchUpId=m,I.finishingRound=n,I.roundNumber=u),n===1&&(I.participantWon=o)),e&&(I.lineParticipation||(I.lineParticipation=[]),I.lineParticipation.push({collectionPosition:e,collectionId:i,won:o}))}function Db(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:S,collectionPosition:h,tieWinningSide:T,roundPosition:y,matchUpTieId:E,matchUpSides:A,collectionId:N,matchUpType:U,winningSide:R,matchUpId:D,schedule:b,eventId:C,drawId:_,sides:v}=t,w=i&&v?.length===2&&Object.assign({},...v.map(({sideNumber:L},F)=>{let x=v[1-F].participantId;return L&&{[L]:x}}).filter(Boolean));for(let L of v){let{participantId:F,sideNumber:x,bye:k}=L;if(k)continue;let G=R===x,V=W=>{let K=o[W]?.participant,Y=K?.participantType,J=[{participantId:W,participantType:Y}];if(Y!==ur)for(let ct of K?.individualParticipantIds??[]){let Et=o[ct]?.participant;J.push({participantType:Et?.participantType,participantId:ct})}return J},B=(W,K)=>{if(s){if(o[W].matchUps[D]={participantWon:G,matchUpType:U,structureId:f,sideNumber:x,matchUpId:D,eventId:C,drawId:_,stage:I},i){let Y=V(K);o[W].matchUps[D].opponentParticipantInfo=Y}N&&(o[W].matchUps[D].collectionId=N)}i&&K&&(o[W].opponents[K]={participantId:K,matchUpId:D,eventId:C,drawId:_}),S&&R&&d0({finishingPositionRange:u,collectionPosition:h,participantMap:o,participantWon:G,collectionId:N,finishingRound:p,matchUpStatus:m,participantId:W,stageSequence:d,roundNumber:l,structureId:f,matchUpId:D,drawId:_,stage:I}),(r||e)&&hE({participantMap:o,participantId:W,matchUpStatus:m,roundPosition:y,matchUpType:U,roundNumber:l,structureId:f,matchUpId:D,schedule:b,drawId:_,score:g})},z=({participant:W,partnerParticipantId:K})=>{let Y=(J,ct)=>{J&&(J.partnerParticipantIds??=[],J.partnerParticipantIds.includes(ct)||J.partnerParticipantIds.push(ct))};c&&Y(W?.draws?.[_],K),a&&Y(W?.events?.[C],K),s&&Y(W?.matchUps?.[D],K)};if(F&&o[F]){let W=w?.[x];B(F,W);let K=o[F]?.participant.participantType===lt,Y=o[F]?.participant.individualParticipantIds??[];E&&Uq({individualParticipantIds:Y,tieWinningSide:T,withTeamMatchUps:n,participantMap:o,matchUpSides:A,matchUpTieId:E,sideNumber:x,participantId:F,withDraws:c,eventId:C,drawId:_}),K&&Dq({individualParticipantIds:Y,opponentParticipantId:W,participantMap:o,matchUpSides:A,participantId:F,sideNumber:x,withEvents:a,addMatchUp:B,addPartner:z,eventId:C}),R&&Rq({individualParticipantIds:Y,participantMap:o,participantWon:G,matchUpStatus:m,participantId:F,matchUpType:U})}}}function Uq({individualParticipantIds:t,tieWinningSide:e,withTeamMatchUps:r,participantMap:n,matchUpSides:o,matchUpTieId:i,sideNumber:s,participantId:a,withDraws:c,eventId:u,drawId:p}){if(r){let m=d=>n[d].matchUps[i]={participantWon:e===s,matchUpId:i,matchUpType:Ot,sideNumber:s};m(a),t.forEach(m)}if(c&&!n[a].draws[p]){let m=o.find(f=>f.sideNumber===s)?.participant?.participantId,d=n[m]?.draws?.[p]?.entryStatus,l=f=>n[f].draws[p]={entryStatus:d,eventId:u,drawId:p};l(a),t.forEach(l)}}function Dq({individualParticipantIds:t,opponentParticipantId:e,participantMap:r,matchUpSides:n,participantId:o,sideNumber:i,withEvents:s,addMatchUp:a,addPartner:c,eventId:u}){if(t.forEach(p=>r[p]&&a(p,e)),t.forEach((p,m)=>{let d=t[1-m],l=r[p];l&&c({participant:l,partnerParticipantId:d})}),s&&n){let p=n.find(m=>m.sideNumber===i)?.participant?.participantId;if(p){let m=r[p]?.events[u];m?(r[o].events[u]={...m},t.forEach(d=>r[d].events[u]={...m})):console.log("Missing teamEntry",{eventId:u,teamParticipantId:p})}}}function Rq({individualParticipantIds:t,participantMap:e,participantWon:r,matchUpStatus:n,participantId:o,matchUpType:i}){let s=a=>{r?(e[a].counters[i].wins+=1,e[a].counters.wins+=1,n===Lt&&(e[a].counters[i].walkoverWins+=1,e[a].counters.walkoverWins+=1),n===xt&&(e[a].counters[i].defaultWins+=1,e[a].counters.defaultWins+=1)):(e[a].counters[i].losses+=1,e[a].counters.losses+=1,n===Lt&&(e[a].counters[i].walkovers+=1,e[a].counters.walkovers+=1),n===xt&&(e[a].counters[i].defaults+=1,e[a].counters.defaults+=1))};s(o),t.forEach(s)}function kp(t,e){return(t||"").localeCompare(e||"")}function f0(t){let{participantFilters:e,convertExtensions:r,policyDefinitions:n,tournamentRecord:o,usePublishState:i,contextFilters:s,matchUpFilters:a,participantMap:c,contextProfile:u,withPotentialMatchUps:p,withRankingProfile:m,withScheduleItems:d,scheduleAnalysis:l,withTeamMatchUps:f,withStatistics:g,withOpponents:I,withMatchUps:S,withSeeding:h,withEvents:T,withDraws:y}=t,E=e?.participantIds,A=x=>{let k=[x];return c[x]?.participant.individualParticipantIds?.forEach(G=>k.push(G)),k.some(G=>!E?.length||E.includes(G))?k:[]},N={withMatchUps:S||m,withEvents:T||m,withDraws:y||m,withPotentialMatchUps:p,withRankingProfile:m,withScheduleItems:d,scheduleAnalysis:l,withTeamMatchUps:f,withStatistics:g,participantMap:c,withOpponents:I,withSeeding:h},U=[],R={},D=[],b={},C={},_={},v={},w={},L=({eventType:x,scaleNames:k,participantId:G})=>c[G]?.participant?.rankings?.[x]?.find(V=>k.includes(V.scaleName))?.scaleValue;for(let x of o?.events??[])e?.eventIds&&!e.eventIds.includes(x.eventId)||bq({convertExtensions:r,eventsPublishStatuses:b,derivedEventInfo:C,derivedDrawInfo:_,participantMap:c,getRanking:L,withOpts:N,event:x,getRelevantParticipantIds:A,withPotentialMatchUps:p,withRankingProfile:m,withScheduleItems:d,scheduleAnalysis:l,withTeamMatchUps:f,policyDefinitions:n,tournamentRecord:o,withStatistics:g,rrContainerInfo:w,rrGroupMatchUps:v,mappedMatchUps:R,contextFilters:s,matchUpFilters:a,contextProfile:u,withOpponents:I,usePublishState:i,withMatchUps:S,withSeeding:h,withEvents:T,withDraws:y,matchUps:D});let F=wq(v,w,m);if(g||m||l){let x=Fq({rrFinishingPositions:F,withRankingProfile:m,scheduleAnalysis:l,withStatistics:g,derivedDrawInfo:_,participantMap:c});U.push(...x)}return{participantIdsWithConflicts:U,eventsPublishStatuses:b,derivedEventInfo:C,derivedDrawInfo:_,mappedMatchUps:R,participantMap:c,matchUps:D}}function bq({convertExtensions:t,eventsPublishStatuses:e,derivedEventInfo:r,derivedDrawInfo:n,participantMap:o,getRanking:i,withOpts:s,event:a,getRelevantParticipantIds:c,withPotentialMatchUps:u,withRankingProfile:p,withScheduleItems:m,scheduleAnalysis:d,withTeamMatchUps:l,policyDefinitions:f,tournamentRecord:g,withStatistics:I,rrContainerInfo:S,rrGroupMatchUps:h,mappedMatchUps:T,contextFilters:y,matchUpFilters:E,contextProfile:A,withOpponents:N,usePublishState:U,withMatchUps:R,withSeeding:D,withEvents:b,withDraws:C,matchUps:_}){let{drawDefinitions:v=[],extensions:w=[],wheelchairClass:L,eventType:F,eventName:x,category:k,entries:G,eventId:V,gender:B}=a,{flightProfile:z}=Bt({event:a}),W=z?.flights??[],K=zs({event:a}).publishState;K&&(e[V]=K);let Y=K?.status?.publishedSeeding;if(b||D||p){let ct=t?Object.assign({},...II(w??[])):{};r[V]={...ct,wheelchairClass:L,eventName:x,eventType:F,category:k,eventId:V,gender:B};let Et=[k?.categoryName,k?.ageCategoryCode].filter(Boolean);for(let Wt of G){let{participantId:Dt}=Wt;if(!Dt||!o[Dt])continue;let pe=i({eventType:F,scaleNames:Et,participantId:Dt}),ye,Jt;if(D){let Kr=o[Dt].participant;({seedAssignments:ye,seedValue:Jt}=u0({publishedSeeding:Y,usePublishState:U,withSeeding:D,participant:Kr,event:a}))}let pr=Kr=>{if(o[Kr]?.events?.[V])return;let io=o[Kr];p0({convertExtensions:t,seedAssignments:ye,participant:io,withSeeding:D,seedValue:Jt,eventId:V,ranking:pe,entry:Wt})};pr(Dt),(o[Dt].participant.individualParticipantIds??[]).forEach(pr)}}let J=e?.[V]?.publishedSeeding;if(C||p||D){let ct=pt([...v.map(dc),...W.map(dc)]);for(let Et of ct)Mq({drawDefinitions:v,participantMap:o,derivedDrawInfo:n,eventPublishedSeeding:J,usePublishState:U,withRankingProfile:p,withSeeding:D,withDraws:C,eventType:F,category:k,eventId:V,flights:W,drawId:Et,getRanking:i})}if(p||d||l||I||N||R||C){let ct=!!d||u,Et=Mn({afterRecoveryTimes:!!d,policyDefinitions:f,tournamentRecord:g,inContext:!0,participantMap:o,contextFilters:y,matchUpFilters:E,contextProfile:A,nextMatchUps:ct,event:a})?.matchUps??[];for(let Wt of Et)vq({getRelevantParticipantIds:c,withScheduleItems:m,tournamentRecord:g,drawDefinitions:v,scheduleAnalysis:d,withRankingProfile:p,rrContainerInfo:S,rrGroupMatchUps:h,mappedMatchUps:T,participantMap:o,nextMatchUps:ct,withOpts:s,matchUp:Wt});_.push(...Et)}}function l0(t){return t?Object.assign({},...t.map(({participantId:e,seedValue:r,seedNumber:n})=>({[e]:{seedValue:r,seedNumber:n}}))):void 0}function Cq({participantMap:t,id:e,participantId:r,eventId:n,eventType:o,drawId:i,mainSeedingMap:s,qualifyingSeedingMap:a,seedingPublished:c,withSeeding:u}){let p=u&&c,m=p?{}:void 0,d=p?s?.[r]?.seedValue||s?.[r]?.seedNumber:void 0,l=d?s?.[r]:void 0,f=p?a?.[r]?.seedValue||a?.[r]?.seedNumber:void 0,g=f?a?.[r]:void 0;m&&d&&(m[H]=l),m&&f&&(m[Z]=g);let I=d||f;return I&&(t[e].participant.seedings[o]||(t[e].participant.seedings[o]=[]),l&&t[e].participant.seedings[o].push({...l,scaleName:i}),g&&t[e].participant.seedings[o].push({...g,scaleName:i}),m&&(t[e].events[n].seedAssignments||(t[e].events[n].seedAssignments={}),Object.keys(m).forEach(S=>t[e].events[n].seedAssignments[S]=m[S]))),{seedAssignments:m,seedValue:I}}function Mq({drawDefinitions:t,participantMap:e,derivedDrawInfo:r,eventPublishedSeeding:n,usePublishState:o,withRankingProfile:i,withSeeding:s,withDraws:a,eventType:c,category:u,eventId:p,flights:m,drawId:d,getRanking:l}){let f=t.find(G=>G.drawId===d),g=[u?.categoryName,u?.ageCategoryCode].filter(Boolean),{structures:I=[],drawOrder:S,drawName:h,drawType:T}=f??{},y=m?.find(G=>G.drawId===d),E=f?.entries||y?.drawEntries,A=y?.flightNumber,N=(f?.structures??[]).sort((G,V)=>ki(G,V)).map(({structureId:G,structures:V})=>[G,...(V??[]).map(({structureId:B})=>B)]).flat(1/0),U,R,D,b,C=0,_=new Set(I.filter(({stage:G,stageSequence:V})=>G===H&&V===1||G===Z).flatMap(G=>{let{positionAssignments:V}=Pt({structure:G}),{seedAssignments:B,stageSequence:z,stage:W}=G;return W===H?(C=V?.length??0,D=V,b=B):z===1&&(U=V,R=B),V}).map(({participantId:G})=>G).filter(Boolean)),v=l0(b),w=l0(R),L=f?E.filter(({participantId:G})=>_.has(G)):E,F=!o||n?.published&&(n?.drawIds?.length===0||n?.drawIds?.includes(d));for(let G of L){if(!e[G.participantId])continue;let{entryStatus:V,entryStage:B,entryPosition:z,participantId:W}=G,K=l({participantId:W,scaleNames:g,eventType:c}),Y=J=>{if(!e[J]||e[J].draws?.[d])return;let{seedAssignments:ct,seedValue:Et}=Cq({participantMap:e,id:J,participantId:W,eventId:p,eventType:c,drawId:d,mainSeedingMap:v,qualifyingSeedingMap:w,seedingPublished:F,withSeeding:s});(a||i)&&(e[J].draws[d]=et({seedAssignments:ct,entryPosition:z,entryStatus:V,entryStage:B,seedValue:Et,eventId:p,ranking:K,drawId:d},!1,!1,!0))};[Lr,Bi].includes(V)||(Y(W),(e[W].participant.individualParticipantIds??[])?.forEach(Y))}let x=(f?.structures??[]).reduce((G,V)=>(G.includes(V.stage)||G.push(V.stage),G),[]),k=(f?.links??[]).length;r[d]={qualifyingPositionAssignments:U,qualifyingSeedAssignments:R,mainPositionAssignments:D,qualifyingSeedingMap:w,mainSeedAssignments:b,orderedStructureIds:N,mainSeedingMap:v,flightNumber:A,linksCount:k,drawOrder:S,drawName:h,drawType:T,drawSize:C,drawId:d,stages:x}}function vq({getRelevantParticipantIds:t,withScheduleItems:e,tournamentRecord:r,drawDefinitions:n,scheduleAnalysis:o,withRankingProfile:i,rrContainerInfo:s,rrGroupMatchUps:a,mappedMatchUps:c,participantMap:u,nextMatchUps:p,withOpts:m,matchUp:d}){let{finishingPositionRange:l,potentialParticipants:f,tieMatchUps:g=[],sides:I=[],winningSide:S,matchUpType:h,matchUpId:T,eventId:y,drawId:E,collectionId:A,containerStructureId:N,stageSequence:U,finishingRound:R,matchUpStatus:D,roundPosition:b,roundNumber:C,structureId:_,schedule:v,score:w,stage:L}=d;if(c[T]=d,i&&N&&_&&E&&(a[_]||(a[_]=[]),a[_].push(d),!s[N])){let x=n.find(k=>k.drawId===E);x&&(s[N]={drawDefinition:x,drawId:E})}let F={finishingPositionRange:l,containerStructureId:N,finishingRound:R,stageSequence:U,roundPosition:b,collectionId:A,roundNumber:C,structureId:_,schedule:v,eventId:y,drawId:E,score:w,stage:L};Db({tournamentRecord:r,drawDefinitions:n,...F,...m,matchUpStatus:D,winningSide:S,matchUpType:h,matchUpId:T,sides:I});for(let x of g){let{winningSide:k,sides:G=[],matchUpId:V,collectionPosition:B,collectionId:z,matchUpStatus:W,matchUpType:K}=x;Db({...F,...m,winningSide:k,tieWinningSide:S,matchUpTieId:T,matchUpId:V,sides:G,collectionId:z,collectionPosition:B,matchUpSides:I,matchUpStatus:W,matchUpType:K})}Array.isArray(f)&&(p||o||e)&&Oq({getRelevantParticipantIds:t,potentialParticipants:f,withScheduleItems:e,tournamentRecord:r,scheduleAnalysis:o,participantMap:u,matchUpStatus:D,roundPosition:b,structureId:_,matchUpType:h,roundNumber:C,matchUpId:T,schedule:v,eventId:y,drawId:E,score:w})}function Oq({getRelevantParticipantIds:t,potentialParticipants:e,withScheduleItems:r,tournamentRecord:n,scheduleAnalysis:o,participantMap:i,matchUpStatus:s,roundPosition:a,structureId:c,matchUpType:u,roundNumber:p,matchUpId:m,schedule:d,eventId:l,drawId:f,score:g}){e.flat().map(ft).filter(Boolean)?.forEach(S=>{t(S)?.forEach(T=>{i[T]&&(i[T].potentialMatchUps[m]=et({tournamentId:n?.tournamentId,matchUpId:m,eventId:l,drawId:f}))}),(o||r)&&hE({potential:!0,participantMap:i,participantId:S,matchUpStatus:s,roundPosition:a,structureId:c,matchUpType:u,roundNumber:p,matchUpId:m,schedule:d,drawId:f,score:g})})}function _q({drawPositionsCount:t,containerStructureId:e,bracketsCount:r,playoffStructure:n,drawDefinition:o,bracketSize:i,order:s}){if(t===i&&s)return[s,s];if(r>1&&s&&!n)return[1,r];if(r>1&&s&&n){let a=o.links?.find(c=>c.source.structureId===e)?.source?.finishingPositions;if(a){let c=a.length*r;if(a.includes(s))return[1,c];let u=(i-s)*r;return[c+1,t-u]}}}function xq({containedStructure:t,rrGroupMatchUps:e,drawPositionsCount:r,containerStructureId:n,bracketsCount:o,playoffStructure:i,drawDefinition:s,drawPositions:a}){let c=t.structureId,u=e[c];if(!u?.length)return;let p=t.positionAssignments?.length,{subOrderMap:m}=Xl({positionAssignments:t.positionAssignments}),d=Ks({matchUps:u,subOrderMap:m});if(d?.participantResults)for(let[l,f]of Object.entries(d.participantResults)){let g=f.groupOrder||f.provisionalOrder;if(!g)continue;let I=_q({drawPositionsCount:r,containerStructureId:n,bracketsCount:o,playoffStructure:i,drawDefinition:s,bracketSize:p,order:g});I&&(a[l]=I)}}function wq(t,e,r){let n={};if(!r)return n;for(let[o,i]of Object.entries(e)){let{drawDefinition:s,drawId:a}=i,c=s.structures?.find(l=>l.structureType===de&&l.stage===H&&l.stageSequence===1);if(!c?.structures)continue;let u=c.structures,p=u.length,m=u.reduce((l,f)=>l+(f.positionAssignments?.length||0),0),d=s.structures?.find(l=>l.stage===Vt);n[a]||(n[a]={});for(let l of u)xq({containedStructure:l,rrGroupMatchUps:t,drawPositionsCount:m,containerStructureId:o,bracketsCount:p,playoffStructure:d,drawDefinition:s,drawPositions:n[a]})}return n}function Lq({scheduleItems:t,potentialMatchUps:e,scheduleAnalysis:r}){let n=Tt(r)?r.scheduledMinutesDifference:0,o={},i=t.reduce((s,a)=>{let{scheduledDate:c,scheduledTime:u}=a;return s[c]||(s[c]=[]),u&&s[c].push(a),s},{});Object.values(i).forEach(s=>s.sort(JT));for(let s of t){let{typeChangeTimeAfterRecovery:a,timeAfterRecovery:c,scheduledDate:u,scheduledTime:p}=s,m=i[u],d=jt(p);for(let l of m){if(l.matchUpId===s.matchUpId||Ye(l.matchUpStatus)&&!l.checkScoreHasValue)continue;let I=s.matchUpType!==l.matchUpType&&a||c,S=s.drawId===l.drawId,h=e[s.matchUpId]&&e[l.matchUpId],T=jt(l.scheduledTime),y=Math.abs(T-d),E=T>=d;if((n&&!Number.isNaN(n)?y<=n:E&&jt(l.scheduledTime)<jt(I))&&!(h&&S)&&E){let N=[s.matchUpId,l.matchUpId].sort(kp).join("|");o[N]={priorScheduledMatchUpId:s.matchUpId,matchUpIdWithConflict:l.matchUpId}}}}return o}function Fq({rrFinishingPositions:t,withRankingProfile:e,scheduleAnalysis:r,withStatistics:n,derivedDrawInfo:o,participantMap:i}){let s=[],a=Object.values(i);for(let c of a){let{wins:u,losses:p,[Ct]:{wins:m,losses:d},[Rt]:{wins:l,losses:f}}=c.counters,g=(I,S,h)=>{let T=S+h,y=S,E=T&&y/T;c.statistics[I]={denominator:T,numerator:y,statValue:E,statCode:I}};n&&(g(Ol,u,p),g(`${Ol}.${Ct}`,m,d),g(`${Ol}.${Rt}`,l,f)),e&&kq({participantAggregator:c,derivedDrawInfo:o,rrFinishingPositions:t}),r&&Gq({participantAggregator:c,scheduleAnalysis:r,participantMap:i,participantIdsWithConflicts:s})}return s}function kq({participantAggregator:t,derivedDrawInfo:e,rrFinishingPositions:r}){let n=(o=[])=>Math.abs(o[0]-o[1]);for(let o of Object.keys(t.draws)){let{orderedStructureIds:i=[],flightNumber:s}=e[o]??{};if(!t.structureParticipation||!i.length)continue;let a,c=0,u=i.map(p=>{let m=t.structureParticipation[p];if(!m)return;a||(a=m?.finishingPositionRange),n(a)>n(m?.finishingPositionRange)&&(a=m?.finishingPositionRange);let d=m.stage!==Z;return d&&(c+=1),et({...m,participationOrder:d?c:void 0,flightNumber:s})}).filter(Boolean);if(t.draws[o]){let p=t.participant.participantId,m=r[o]?.[p];m&&(a=m),t.draws[o].finishingPositionRange=a,t.draws[o].structureParticipation=u}}}function Gq({participantAggregator:t,scheduleAnalysis:e,participantMap:r,participantIdsWithConflicts:n}){let o=t.scheduleItems??[],i=t.potentialMatchUps??{};t.scheduleConflicts=Lq({scheduleAnalysis:e,scheduleItems:o,potentialMatchUps:i});let s=t.participant.participantId;Object.keys(t.scheduleConflicts).length&&n.push(s),r[s].scheduleConflicts=t.scheduleConflicts}function Gp({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=_a(l)&&e?.events?.filter(y=>l?.includes(y.eventId))||e?.events||[],I=o&&Vq({drawEntryStatuses:o,tournamentEvents:g}),S=s&&Bq({eventEntryStatuses:s,tournamentEvents:g}),h=i!==void 0&&[!0,!1].includes(i)&&g.reduce((y,E)=>y.concat(...(E.drawDefinitions??[]).map(A=>Vy({drawDefinition:A}).allPositionedParticipantIds).filter(Boolean)),[]),T=y=>n?.reduce((E,A)=>{let{accessor:N,value:U}=A,{values:R}=Li({element:y,accessor:N});return E&&R?.includes(U)},!0);if(r=r?.filter(y=>{let E=Jr({element:y,itemType:uu})?.timeItem?.itemValue,{participantRoleResponsibilities:A,participantType:N,participantRole:U,participantId:R,person:D}=y,b=Array.isArray(f)&&f?.length&&D?.sex&&f.includes(D.sex);return d?f&&b||i&&h.includes(R)||i===!1&&!h.includes(R)||I?.includes(R)||S?.includes(R)||p?.includes(R)||m&&E===m||u&&N&&_a(u)&&u.includes(N)||a&&U&&_a(a)&&a.includes(U)||c&&_a(A)&&_a(c)&&c.find(C=>A?.includes(C))||n?.length&&_a(n)&&T(y):(!f||b)&&(i===void 0||i&&h.includes(R)||i===!1&&!h.includes(R))&&(!I||I.includes(R))&&(!S||S.includes(R))&&(!p||p.includes(R))&&(!m||E===m)&&(!u||N&&_a(u)&&u.includes(N))&&(!a||U&&_a(a)&&a.includes(U))&&(!c||_a(A)&&_a(c)&&c.find(C=>A?.includes(C)))&&(!n?.length||_a(n)&&T(y))}),g.length&&l){let y=new Set(g.filter(E=>l.includes(E.eventId)).flatMap(E=>{let A=(E.entries??[]).map(U=>U.participantId);if(re(Ut)(E.eventType))return A;let N=(e?.participants??[]).filter(U=>A.includes(U.participantId)).flatMap(U=>U.individualParticipantIds);return A.concat(...N)}));r=r?.filter(E=>y.has(E.participantId))}return r}function _a(t){return t&&Array.isArray(t)&&t.length}function Vq({drawEntryStatuses:t,tournamentEvents:e}){let r=({entryStatus:n})=>Array.isArray(t)?t.includes(n):!0;return pt(e.reduce((n,o)=>{let{flightProfile:i}=Bt({event:o}),s=i?.flights?.flatMap(({drawEntries:c})=>Array.isArray(c)?c.filter(r).map(ft):[])??[],a=o.drawDefinitions?.map(({entries:c})=>c?c.filter(r).map(ft):[])??[];return n.concat(...s,...a)},[]))}function Bq({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(ft);return r.concat(...o)},[]))}function bt(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,withStatistics:f,contextFilters:g,matchUpFilters:I,contextProfile:S,withOpponents:h,withMatchUps:T,internalUse:y,withSeeding:E,withEvents:A,withDraws:N,withISO2:U,withIOC:R}=t,D="getParticipants";if(!c)return M({stack:D,result:{error:j}});(T||o)&&tn({tournamentRecord:c});let b=zy({convertExtensions:i,tournamentRecord:c,withSignInStatus:p,withScaleValues:d,internalUse:y,withISO2:U,withIOC:R}),{participantMap:C}=b,_=f0({withMatchUps:T??o,withEvents:A??o,withDraws:N??o,withPotentialMatchUps:n,participantFilters:r,withRankingProfile:o,convertExtensions:i,withScheduleItems:a,policyDefinitions:s,tournamentRecord:c,scheduleAnalysis:u,withTeamMatchUps:m,usePublishState:l,withStatistics:f,contextFilters:g,matchUpFilters:I,participantMap:C,withOpponents:h,contextProfile:S,withSeeding:E}),{participantIdsWithConflicts:v,eventsPublishStatuses:w,derivedEventInfo:L,derivedDrawInfo:F,mappedMatchUps:x}=_,k=_.matchUps;C=_.participantMap;let G=u??n,V=({potentialMatchUps:ct,scheduleConflicts:Et,scheduleItems:Wt,participant:Dt,statistics:pe,opponents:ye,matchUps:Jt,events:pr,draws:$n})=>{let Kr=Object.values($n),io=Object.values(ye);return h&&Kr?.forEach(Ko=>{Ko.opponents=io.filter(zo=>zo.drawId===Ko.drawId)}),et({...Dt,scheduleConflicts:u?Object.values(Et):void 0,draws:N||o?Kr:void 0,events:A||o?Object.values(pr):void 0,matchUps:T||o?Object.values(Jt):void 0,opponents:h?io:void 0,potentialMatchUps:G?Object.values(ct):void 0,statistics:f?Object.values(pe):void 0,scheduleItems:a?Wt:void 0},!1,!1,!0)},B=new Map;for(let ct of Object.keys(C))B.set(ct,V(C[ct]));let z=[...B.values()],K=s?.[Da]?.participant,Y=Gp({participants:z,participantFilters:r,tournamentRecord:c});if(e){let ct=Tt(e)?e:void 0;for(let Et of Y)for(let Wt of Et.individualParticipantIds??[]){Et.individualParticipants??=[];let Dt=B.get(String(Wt)),pe=ct?fs({template:ct,source:Dt}):Dt;Et.individualParticipants.push(pe)}}let J=K?Y.map(ct=>fs({source:ct,template:K})):Y;return{participantMap:t.returnParticipantMap!==!1?C:void 0,mappedMatchUps:t.returnMatchUps!==!1?x:void 0,matchUps:t.returnMatchUps!==!1?k:void 0,missingParticipantIds:b.missingParticipantIds,participantIdsWithConflicts:v,eventsPublishStatuses:w,derivedEventInfo:L,derivedDrawInfo:F,participants:J,...P}}function Ki(t){let{tournamentRecord:e,scaleAttributes:r,participantId:n}=t,o=t.tournamentRecords||e&&{[e.tournamentId]:e}||{};if(!n)return{error:He};let{participant:i,tournamentId:s}=Ao({tournamentRecords:o,tournamentRecord:e,participantId:n});return i?{...yo({participant:i,scaleAttributes:r}),tournamentId:s}:{error:ee}}function S0(t,e){let r=t.startDate||e?.startDate,n=t.endDate||e?.endDate;return!r||!n?{error:ew}:!Me(r)||!Me(n)?{error:ae}:{startDate:r,endDate:n}}function g0(t,e){let r=new Date(mt(t)),n=new Date(mt(e)),o=n.getFullYear()-r.getFullYear(),i=n.getMonth()-r.getMonth();return(i<0||i===0&&n.getDate()<r.getDate())&&o--,o}function I0(t,e,r){return!(e!==void 0&&t<e||r!==void 0&&t>r)}function Hq(t){return/^C\d{1,2}-\d{1,2}$/.test(t.ageCategoryCode||"")}function Wq(t,e,r,n){if(Hq(e))return{valid:!0};let o=e.ageMin,i=e.ageMax;if(e.ageCategoryCode&&!o&&!i){let m=ps({consideredDate:r,category:e});m.error||(o=m.ageMin,i=m.ageMax)}if(!o&&!i)return{valid:!0};let s=t.person?.birthDate;if(!s)return{valid:!1,reason:"Missing birthDate",details:{requiredMin:o,requiredMax:i}};let a=g0(s,r),c=g0(s,n),u=I0(a,o,i),p=I0(c,o,i);if(!u){let m=[o===void 0?null:`min: ${o}`,i===void 0?null:`max: ${i}`].filter(Boolean).join(", ");return{valid:!1,reason:`Age ${a} at event start (${r}) outside range [${m}]`,details:{birthDate:s,ageAtStart:a,ageAtEnd:c,requiredMin:o,requiredMax:i}}}if(!p){let m=[o===void 0?null:`min: ${o}`,i===void 0?null:`max: ${i}`].filter(Boolean).join(", ");return{valid:!1,reason:`Age ${c} at event end (${n}) outside range [${m}]`,details:{birthDate:s,ageAtStart:a,ageAtEnd:c,requiredMin:o,requiredMax:i}}}return{valid:!0}}function Yq(t,e,r,n){if(!e.ratingMin&&!e.ratingMax)return{valid:!0};if(!e.ratingType)return{valid:!0};let o={scaleType:"RATING",scaleName:e.ratingType,eventType:r.eventType},{scaleItem:i}=Ki({tournamentRecord:n,participantId:t.participantId,scaleAttributes:o});if(!i?.scaleValue)return{valid:!1,reason:`Missing ${e.ratingType} rating`,details:{ratingType:e.ratingType,requiredMin:e.ratingMin,requiredMax:e.ratingMax}};let s;if(typeof i.scaleValue=="object"){let a=Li({element:i.scaleValue,accessor:i.scaleValue?.accessor});if(a===void 0)return{valid:!1,reason:`Cannot extract rating value from ${e.ratingType} scale item`,details:{ratingType:e.ratingType,requiredMin:e.ratingMin,requiredMax:e.ratingMax}};s=a}else s=i.scaleValue;return e.ratingMin!==void 0&&s<e.ratingMin?{valid:!1,reason:`${e.ratingType} rating ${s} below minimum ${e.ratingMin}`,details:{ratingType:e.ratingType,ratingValue:s,requiredMin:e.ratingMin,requiredMax:e.ratingMax}}:e.ratingMax!==void 0&&s>e.ratingMax?{valid:!1,reason:`${e.ratingType} rating ${s} above maximum ${e.ratingMax}`,details:{ratingType:e.ratingType,ratingValue:s,requiredMin:e.ratingMin,requiredMax:e.ratingMax}}:{valid:!0}}function Rb(t){let e=t.person;if(!e)return t.participantOtherName||t.participantName||"Unknown";let r=e.standardGivenName||e.passportGivenName,n=e.standardFamilyName||e.passportFamilyName;return[r,n].filter(Boolean).join(" ")||t.participantOtherName||t.participantName||"Unknown"}function bb(t,e,r,n,o,i){let s=Wq(t,e,n,o),a=Yq(t,e,r,i);if(!s.valid||!a.valid){let c={participantId:t.participantId,participantName:Rb(t),rejectionReasons:[]};return s.valid||c.rejectionReasons.push({type:"age",reason:s.reason,details:s.details??{}}),a.valid||c.rejectionReasons.push({type:"rating",reason:a.reason,details:a.details??{}}),c}return null}function Tu({participantId:t,drawDefinition:e,entryStatus:r,entryStage:n}){if(!e)return{error:$};let o=e.entries?.find(i=>i.participantId===t&&(!r||r===i.entryStatus)&&(!n||n===i.entryStage));return t&&o}function Cb({stage:t,drawDefinition:e}){return!!(t===Fe||fL({stage:t,drawDefinition:e}))}function jq({relevantLinks:t,drawDefinition:e,provisionalPositioning:r,roundQualifiersCounts:n}){let o=0;for(let i of t){let s=tt({structureId:i.source.structureId,drawDefinition:e})?.structure;if(s?.stage===Z){let a=i.source.roundNumber,c=i.target.roundNumber,u;if(s.structureType===de){let p=s.structures?.length??0,m=i.source.finishingPositions?.length??0;u=p*m}else a===0&&i.source.qualifyingPositions?u=i.source.qualifyingPositions:u=ht({matchUpFilters:{roundNumbers:[a]},structure:s,afterRecoveryTimes:!1,provisionalPositioning:r,inContext:!1}).matchUps?.length||0;n[c]||(n[c]=0),n[c]+=u,o+=u}}return o}function Vp(t){let{provisionalPositioning:e,drawDefinition:r,structureId:n}=t;if(!r)return{error:$};let o={};if(!n)return{qualifiersCount:0,roundQualifiersCounts:o};let{structure:i}=tt({drawDefinition:r,structureId:n}),s=r.links?.filter(c=>c?.target?.structureId===i?.structureId),a=0;return s?.length&&(a=jq({relevantLinks:s,drawDefinition:r,provisionalPositioning:e,roundQualifiersCounts:o})),{qualifiersCount:a,roundQualifiersCounts:o}}function Mb({stage:t,drawDefinition:e,stageSequence:r,tournamentRecord:n,event:o}){let i=e?.structures?.filter(s=>s.stage===t&&(!r||s.stageSequence===r));if(i?.length)return i.reduce((s,a)=>a.structureType===de?s+(a.structures?.reduce((c,u)=>c+(u.positionAssignments?.length??0),0)??0):s+(a.positionAssignments?.length??0),0);if(t===H&&n){let{constraints:s}=KI({tournamentRecord:n,event:o});if(s?.drawSize)return s.drawSize}return 0}function h0(t){let{provisionalPositioning:e,drawDefinition:r,stageSequence:n,stage:o,tournamentRecord:i,event:s}=t,a=Mb({stage:o,drawDefinition:r,stageSequence:n,tournamentRecord:i,event:s}),c=r?.structures?.find(p=>p.stage===o&&(!n||p.stageSequence===n)),{qualifiersCount:u}=Vp({structureId:c?.structureId,provisionalPositioning:e,drawDefinition:r,stageSequence:n,stage:o});return a&&a-(u??0)}function vb({entryStatus:t=wr,tournamentRecord:e,drawDefinition:r,stageSequence:n,event:o,stage:i}){let{constraints:s}=KI({tournamentRecord:e,event:o});if(t===Zr){if(!s)return{positionsAvailable:1/0,...P};if(s.maxAlternates===void 0)return{positionsAvailable:1/0,...P};let f=Xy({entryStatus:Zr,drawDefinition:r,stage:i});return f<s.maxAlternates?{positionsAvailable:s.maxAlternates-f,...P}:{error:sD}}if(!r?.structures?.some(f=>f.stage===i))return{positionsAvailable:1/0,...P};let c=h0({drawDefinition:r,stageSequence:n,stage:i}),u=Xy({entryStatus:Op,drawDefinition:r,stage:i}),p=Xy({entryStatus:wr,drawDefinition:r,stage:i}),m=u+p,d=c>0&&m>=c,l=c-m;if(i!==Fe&&d)return{error:Kg};if(t===Op){if(!s)return m<c?{...P}:{error:Kg};let f=s.maxWildcards??c;return u<f?{...P}:{error:Kg}}return{positionsAvailable:l,...P}}var qq=new Set([hi,lp]);function Tn(t){return!!t&&qq.has(t)}function Jl(t){let e=X(t,[{[Kt]:!0,[Py]:!0}]);if(e.error)return e;let{suppressDuplicateEntries:r=!0,entryStatus:n=wr,entryStageSequence:o,entryStage:i=H,ignoreStageSpace:s,drawDefinition:a,entryPosition:c,participant:u,roundTarget:p,extensions:m,extension:d,drawType:l,event:f}=t,g="addDrawEntry";if(!Tn(l)&&!Cb({stage:i,drawDefinition:a}))return M({result:{error:tc},stack:g});let I=vb({stageSequence:o,stage:i,drawDefinition:a,entryStatus:n});if(!s&&!I.success&&(!l||!Tn(l)))return{error:I.error};if(d&&!Wn({extension:d}))return M({result:{error:O},info:"Invalid extension",context:{extension:d},stack:g});let S=t.participantId||u?.participantId;if(!S)return M({result:{error:He},stack:g});let h=n===ks&&Tu({participantId:S,drawDefinition:a,entryStatus:n}),T=i===Fe&&Tu({participantId:S,drawDefinition:a,entryStage:i}),y=Tu({participantId:S,drawDefinition:a}),E=n!==ks&&i!==Fe&&y;if(E)return r?(at({payload:{drawId:a.drawId,eventId:f?.eventId,error:tl,participantId:S},topic:Hy}),{...P}):M({result:{error:tl},context:{participantId:S},stack:g});if(h||T)return M({context:{invalidEntry:E,invalidLuckyLoser:h,invalidVoluntaryConsolation:T},result:{error:bm},stack:g});let A=et({entryStageSequence:o,participantId:S,entryPosition:c,entryStatus:n,entryStage:i,extensions:m});return d&&ut({element:A,extension:d}),p&&ut({extension:{name:Rn,value:p},element:A}),a.entries??=[],a.entries.push(A),Ft({drawDefinition:a}),{...P}}function T0(t){let e="addDrawEntries",{suppressDuplicateEntries:r=!0,entryStatus:n=wr,autoEntryPositions:o=!0,ignoreStageSpace:i,participantIds:s,drawDefinition:a,stageSequence:c,stage:u=H,roundTarget:p,extension:m,event:d}=t,l=Tn(a.drawType);if(!u)return{error:Gg};if(!a)return{error:$};if(!Array.isArray(s))return{error:Mr};if(!l&&!Cb({stage:u,drawDefinition:a}))return{error:tc};if(m&&!Wn({extension:m}))return M({result:{error:O},info:"Invalid extension",context:{extension:m},stack:e});let f=vb({drawDefinition:a,stageSequence:c,entryStatus:n,stage:u});if(!i&&!f.success&&!l)return{error:f.error};let g=f.positionsAvailable??0;if(!i&&!l&&u!==Fe&&g<s.length)return{error:qg};let I=[],S=a.drawId,h=d?.eventId,T=s.reduce((y,E)=>{let A=n===ks&&Tu({participantId:E,drawDefinition:a,entryStatus:n}),N=u===Fe&&Tu({entryStage:u,drawDefinition:a,participantId:E}),U=Tu({participantId:E,drawDefinition:a});return n!==ks&&u!==Fe&&U&&(I.push(E),r&&at({payload:{error:tl,participantId:E,eventId:h,drawId:S},topic:Hy})),A||N?y.concat(E):y},[]);return I.length&&!r?M({context:{eventId:h,drawId:S,duplicateEntries:I},result:{error:tl},stack:e}):(s.filter(y=>y&&!T.includes(y)).forEach(y=>{let E={entryStageSequence:c,entryStage:u,participantId:y,entryStatus:n};m&&ut({element:E,extension:m}),p&&ut({extension:{name:Rn,value:p},element:E}),a.entries??=[],a.entries.push(E)}),o&&(a.entries=ro({entries:a.entries})),Ft({drawDefinition:a}),T?.length||I?.length?{info:"some participantIds could not be added",participantIdsNotAdded:T,duplicateEntries:I,...P}:{...P})}function cS({suppressDuplicateEntries:t=!0,autoEntryPositions:e=!0,entryStageSequence:r,ignoreStageSpace:n,participantIds:o,drawDefinition:i,entryStatus:s,roundTarget:a,entryStage:c,extension:u,drawId:p,event:m}){if(!o?.length)return{error:Ro};if(!m)return{error:Gr};if(!p)return{error:Pn};let d=(m.entries??[]).map(ft);if(o.filter(I=>!d.includes(I)).length)return{error:_U};if(i){let I=T0({stageSequence:r,suppressDuplicateEntries:t,autoEntryPositions:e,stage:c,ignoreStageSpace:n,participantIds:o,drawDefinition:i,entryStatus:s,roundTarget:a,extension:u});if(I.error)return I}let{flightProfile:f}=Bt({event:m}),g=f?.flights.find(I=>I.drawId===p);return g?.drawEntries&&(o.forEach(I=>{let S=s===ks&&Ob({participantId:I,entryStatus:s,flight:g}),h=c===Fe&&Ob({participantId:I,entryStage:c,flight:g});!(s!==ks&&c!==Fe&&Ob({flight:g,participantId:I}))&&!S&&!h&&g.drawEntries.push({participantId:I,entryStatus:s,entryStage:c})}),e&&(g.drawEntries=ro({entries:g.drawEntries}))),{...P}}function Ob({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 yu({autoEntryPositions:t=!0,participantIds:e=[],entryStatuses:r,stage:n,event:o}){let i="removeEventEntries";if(!o?.eventId)return{error:le};if(!Array.isArray(e)||e.some(m=>!_t(m)))return M({result:{error:Vr},stack:i});let s=(o.drawDefinitions??[]).flatMap(m=>$i({drawDefinition:m}).assignedParticipantIds??[]),a=(r?.length&&o.entries?.filter(m=>m.entryStatus&&r.includes(m.entryStatus))||[]).map(ft).filter(m=>!s.includes(m)),c=(n&&o.entries?.filter(m=>m.entryStage&&m.entryStage===n)||[]).map(ft).filter(m=>!s.includes(m));if(e.length?e=e.filter(m=>(!r?.length||a.includes(m))&&(!n||c.includes(m))):a.length&&c.length?e=Yt(a,c):a.length?e=a:c.length&&(e=c),e?.length&&s.some(m=>e.includes(m)))return M({result:{error:Ia},stack:i});if(!e?.length)return{...P,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=ro({entries:o.entries}));let{flightProfile:p}=Bt({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))}),{...P,participantIdsRemoved:u}}var _b={[We]:{policyName:"matchUpActionsDefault",enabledStructures:[{stages:[],stageSequences:[],enabledActions:[],disabledActions:[]}],participants:{enforceCategory:!0,enforceGender:!0},processCodes:{substitution:["RANKING.IGNORE","RATING.IGNORE"]},substituteAfterCompleted:!1,substituteWithoutScore:!1}},ys=_b;function $q(t,e,r,n){return e.gender&&r&&!(nn(e.gender)||Co(e.gender))&&yr(e.gender)!==yr(t.person?.sex)?(n.push({participantId:t.participantId,sex:t.person?.sex}),!1):!0}function Kq({participantIds:t,typedParticipantIds:e,checkTypedParticipants:r}){return t.filter(n=>!r||e.includes(n))}function zq({tournamentRecord:t,participantIds:e,event:r,entryStatus:n,genderEnforced:o,mismatchedGender:i}){function s(m,d,l){return re(Ct)(d.eventType)&&m.participantType===St&&!$s(l)}function a(m,d,l){return d.eventType===Rt&&m.participantType===lt&&!$s(l)}function c(m,d,l,f,g){return d.eventType===Rt&&m.participantType===St&&$s(l)?d.gender&&f&&!(nn(d.gender)||Co(d.gender))&&yr(d.gender)!==yr(m.person?.sex)?(g.push({participantId:m.participantId,sex:m.person?.sex}),!1):!0:!1}function u(m,d,l){return d.eventType===hI&&[St,lt].includes(m.participantType)&&!$s(l)}function p(m,d,l){return d.eventType===vt&&(m.participantType===vt||$s(l)&&m.participantType===St)}return t?.participants?.filter(m=>e.includes(m.participantId)?s(m,r,n)?$q(m,r,o,i):a(m,r,n)||c(m,r,n,o,i)||u(m,r,n)?!0:p(m,r,n):!1).map(m=>m.participantId)??[]}function Qq(t,e,r,n,o){let i=[];for(let s of t.individualParticipantIds??[]){let a=e.participants?.find(u=>u.participantId===s);if(!a)continue;let c=bb(a,r.category,r,n,o,e);c&&i.push(c)}return i.length?{participantId:t.participantId,participantName:Rb(t),rejectionReasons:i.flatMap(s=>s.rejectionReasons.map(a=>({...a,reason:`${s.participantName}: ${a.reason}`})))}:null}function Xq(t){return(t.participantType===lt||t.participantType===vt)&&!!t.individualParticipantIds?.length}function Jq({typedParticipantIds:t,categoryRejections:e,tournamentRecord:r,startDate:n,endDate:o,event:i}){let s=[];for(let a of t){let c=r.participants?.find(u=>u.participantId===a);if(c)if(i.category){let u=Xq(c)?Qq(c,r,i,n,o):bb(c,i.category,i,n,o,r);u?e.push(u):s.push(a)}else s.push(a)}return s}function Zq({enforceCategory:t,event:e,tournamentRecord:r,typedParticipantIds:n,categoryRejections:o}){if(t&&e.category&&r){let i=S0(e,r);if(!("error"in i)){let{startDate:s,endDate:a}=i;return Jq({typedParticipantIds:n,tournamentRecord:r,event:e,startDate:s,endDate:a,categoryRejections:o})}}return n}function t$({validParticipantIds:t,existingIds:e,entryStatus:r,entryStage:n,extensions:o,extension:i,roundTarget:s,entryStageSequence:a,addedParticipantIdEntries:c,event:u}){t.forEach(p=>{if(!e.has(p)){let m=et({participantId:p,entryStatus:r,entryStage:n,extensions:o});i&&ut({element:m,extension:i}),s&&ut({extension:{name:Rn,value:s},element:m}),a&&(m.entryStageSequence=a),c.push(m.participantId),u.entries?.push(m)}})}function e$({tournamentRecord:t,removedEntries:e,event:r}){if(r.eventType&&[ei,Ze].includes(r.eventType)){let n=new Set((r.entries??[]).map(c=>c.participantId)),o=(r.entries??[]).filter(c=>$s(c.entryStatus)).map(c=>c.participantId),i=t?.participants??[],s=new Set(i.filter(c=>n.has(c.participantId)&&c.participantType&&[lt,vt].includes(c.participantType)).map(c=>c.individualParticipantIds).flat(1/0)),a=o.filter(c=>s.has(c));a.length&&(e.push(...a),yu({participantIds:a,autoEntryPositions:!1,event:r}))}}function r$(t,e){if(!Array.isArray(t.participantIds))return M({result:{error:Mr},stack:e});let r=pt(t.participantIds??[]);return t.event?r?.length?t.event?.eventId?{participantIds:r}:{error:Gr}:M({result:{error:Ro},stack:e}):{error:le}}function n$({policyDefinitions:t,tournamentRecord:e,event:r,enforceGender:n}){let o=It({tournamentRecord:e,event:r}).appliedPolicies??{},i=t?.[We]??o?.[We]??ys[We],s=(n??i?.participants?.enforceGender)!==!1;return{matchUpActionsPolicy:i,genderEnforced:s}}function o$(t,e,r){return t&&(!Array.isArray(t)||!t.every(n=>Wn({extension:n})))||e&&!Wn({extension:e})?M({context:et({extension:e,extensions:t}),result:{error:O},info:"Invalid extension(s)",stack:r}):null}function Yn(t){let{suppressDuplicateEntries:e=!0,entryStatus:r=wr,autoEntryPositions:n=!0,enforceCategory:o=!1,enforceGender:i=!0,entryStageSequence:s,policyDefinitions:a,entryStage:c=H,tournamentRecord:u,ignoreStageSpace:p,drawDefinition:m,roundTarget:d,extensions:l,extension:f,drawId:g,event:I}=t,S="addEventEntries",h=r$(t,S);if("error"in h)return h;let T="participantIds"in h?h.participantIds:[],y=o$(l,f,S);if(y)return y;let{genderEnforced:E}=n$({policyDefinitions:a,tournamentRecord:u,event:I,enforceGender:i}),A=[],N=[],U=!!u,R=[],D,b=zq({tournamentRecord:u,participantIds:T,event:I,entryStatus:r,genderEnforced:E,mismatchedGender:R}),C=[];b=Zq({enforceCategory:o,event:I,tournamentRecord:u,typedParticipantIds:b,categoryRejections:C});let _=Kq({participantIds:T,typedParticipantIds:b,checkTypedParticipants:U});I.entries??=[];let v=new Set(I.entries.map(x=>x.participantId||x.participant?.participantId));if(t$({validParticipantIds:_,existingIds:v,entryStatus:r,entryStage:c,extensions:l,extension:f,roundTarget:d,entryStageSequence:s,addedParticipantIdEntries:A,event:I}),g&&!$s(c)){let x=cS({participantIds:_,suppressDuplicateEntries:e,autoEntryPositions:n,entryStageSequence:s,ignoreStageSpace:p,drawDefinition:m,entryStatus:r,roundTarget:d,entryStage:c,extension:f,drawId:g,event:I});x.error&&(D=x.error)}if(e$({event:I,tournamentRecord:u,removedEntries:N}),_.length!==T.length)return M({context:et({categoryRejections:C.length?C:void 0,mismatchedGender:R.length?R:void 0,gender:I.gender}),result:{error:Mr},stack:S});n&&(I.entries=ro({entries:I.entries??[]}));let L=A.length,F=N.length;return M({result:{...P,addedEntriesCount:L,removedEntriesCount:F,...C.length&&{context:et({categoryRejections:C})}},stack:S,info:D})}var xb="ADMINISTRATION",i$="CAPTAIN",s$="COACH",Ve="COMPETITOR",a$="DIRECTOR",c$="HOSPITALITY",wb="MEDIA",Lb="MEDICAL",uS="OFFICIAL",Fb="OTHER",kb="SECURITY",u$="STRINGER",p$="SUPERVISOR",m$="TRANSPORT",d$="VOLUNTEER",Zl={ADMINISTRATION:xb,CAPTAIN:i$,COACH:s$,COMPETITOR:Ve,DIRECTOR:a$,HOSPITALITY:c$,MEDIA:wb,MEDICAL:Lb,OFFICIAL:uS,OTHER:Fb,SECURITY:kb,STRINGER:u$,SUPERVISOR:p$,TRANSPORT:m$,VOLUNTEER:d$};function pS({addIndividualParticipantsToEvents:t,individualParticipantIds:e,groupingParticipantId:r,tournamentRecord:n,suppressErrors:o}){let i="removeIndividualParticipantIds";if(!n)return M({result:{error:j},stack:i});if(!r||!e)return M({result:{error:nt},stack:i});let a=(n.participants??[]).find(m=>m.participantId===r);if(!a)return M({result:{error:ee},stack:i});if(![vt,qr].includes(a.participantType))return M({result:{participantType:a.participantType,error:Nn},stack:i});let c=y0({individualParticipantIds:e,groupingParticipant:a,tournamentRecord:n,suppressErrors:o}),{removed:u,error:p}=c;if(p)return M({result:c,stack:i});if(t)for(let m of n.events??[]){let d=new Set((m.entries??[]).map(({participantId:l})=>l).filter(Boolean));if(d.has(r)){let l=u?.filter(f=>!d.has(f));Yn({participantIds:l,entryStatus:Lr,tournamentRecord:n,event:m})}}return u&&at({topic:tr,payload:{tournamentId:n.tournamentId,participants:[a]}}),{...P,...c}}function y0({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}=bt({withMatchUps:!0,tournamentRecord:r,withEvents:!0}));let p=i?.find(({participantId:f})=>f===e.participantId)?.events?.map(({eventId:f})=>f),m=new Set(t),d=(e.individualParticipantIds??[]).filter(f=>m.has(f)?l$({groupingParticipantEventIds:p,mappedMatchUps:o,participantId:f,participants:i})?(c.push(f),!0):(s.push(f),f$({groupingParticipantId:e.participantId,tournamentRecord:r,participantId:f}),!1):(a.push(f),!0));e.individualParticipantIds=d;let l={groupingParticipantId:e.participantId,cannotRemove:c,notRemoved:a,removed:s};return c.length&&!n&&{...l,cannotRemove:c,error:Rm}||l}function l$({groupingParticipantEventIds:t,mappedMatchUps:e,participantId:r,participants:n}){return n?.find(i=>i.participantId===r)?.matchUps.filter(({eventId:i})=>t.includes(i)).map(({matchUpId:i})=>e?.[i]).filter(({winningSide:i,score:s})=>i||ue({score:s}))?.length>0}function f$({groupingParticipantId:t,tournamentRecord:e,participantId:r}){for(let n of e.events??[])for(let o of n.drawDefinitions??[])g$({drawDefinition:o,groupingParticipantId:t,participantId:r}),I$({drawDefinition:o,tournamentRecord:e,participantId:r})}function g$({drawDefinition:t,groupingParticipantId:e,participantId:r}){let{extension:n}=ot({element:t,name:wo}),o=n?.value[e];n&&o&&(n.value[e]=o.filter(i=>i.participantId!==r),ut({element:t,extension:n}),lc({drawDefinition:t}))}function I$({drawDefinition:t,tournamentRecord:e,participantId:r}){let n=rr({drawDefinition:t,inContext:!1}).matchUps??[];for(let o of n)for(let i of o.sides??[]){let s=i.lineUp??[];s.find(c=>c.participantId===r)&&(i.lineUp=s.filter(c=>c.participantId!==r),gt({tournamentId:e?.tournamentId,drawDefinition:t,matchUp:o}))}}function od({participantRole:t=Ve,individualParticipantIds:e=[],groupingTypes:r=[ur,qr],tournamentRecord:n}){if(!n)return{error:j};let o=n.participants??[],{participants:i,mappedMatchUps:s}=bt({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}=y0({groupingParticipant:c,individualParticipantIds:e,tournamentRecord:n,mappedMatchUps:s,participants:i});u&&a++}),a?P:{error:rD}}function Es(t){let e=X(t,[{[rt]:!0},{participantIds:!0,[Ge]:ke,[Yr]:Ro}]);if(e.error)return e;let{addIndividualParticipantsToEvents:r,tournamentRecord:n,participantIds:o}=t,i=n.participants?.length||0;if(!i)return{...P};let s=(n.events??[])?.filter(({eventType:f})=>f===Oe).map(f=>f?.drawDefinitions?.map(({drawId:g})=>g)).flat(1/0),a=bt({participantFilters:{participantIds:o},tournamentRecord:n,withDraws:!0}).participants??[],c=f=>{let I=(qt({matchUpFilters:{drawIds:f,matchUpTypes:[Rt]},tournamentRecord:n}).matchUps??[]).flatMap(({sides:S})=>S?.map(({participantId:h})=>h??[])).filter(Boolean);return Yt(I,o)},u=s?.length?c(s):[],p=a.filter(f=>f.draws?.filter(g=>(!s?.length||!s?.includes(g.drawId))&&g.positionAssignments).length);if(u?.length||p.length)return{error:Ia};let m={},d={};for(let f of n.events??[]){let g=yu({participantIds:o,event:f});if(g.error)return g;m[f.eventId]=g.participantIdsRemoved}n.participants=(n.participants??[]).filter(f=>{let g=o.includes(f.participantId)||f.participantType===lt&&f.individualParticipantIds?.some(I=>o.includes(I));if(!g&&f.participantType===Oe&&f.individualParticipantIds?.some(I=>o.includes(I))&&(f.individualParticipantIds=f.individualParticipantIds.filter(I=>!o.includes(I))),g&&r&&f.participantType&&[lt,vt].includes(f.participantType))for(let I of f.individualParticipantIds??[])o.includes(I)||(d[f.participantId]||(d[f.participantId]=[]),d[f.participantId].push(I));return!g});let l=i-n.participants.length;if(od({individualParticipantIds:o,tournamentRecord:n}),r)for(let f of n.events??[]){let I=m[f.eventId].map(S=>d[S]??[]).flat();Yn({participantIds:I,entryStatus:Lr,tournamentRecord:n,event:f})}return l&&at({payload:{participantIds:o,tournamentId:n.tournamentId},topic:FI}),l?{...P,participantsRemovedCount:l}:{error:Rm}}function TE({selected:t=!0,drawDefinition:e,entryStatuses:r,drawId:n,event:o,stage:i}){let s=o.entries??[];if(n){let{flightProfile:c}=Bt({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&&hr.includes(c.entryStatus)));return{entries:s,stageEntries:a}}function Gb({removeGroupParticipant:t,tournamentRecord:e,drawDefinition:r,participantId:n,drawId:o,stage:i,event:s}){let a="destroyGroupEntry",c=dt({tournamentRecord:e,participantId:n,event:s},[rt,sr,ce]);if(c.error)return c;if(!s.eventType||![ei,Ze].includes(s.eventType))return M({result:{error:Kn},stack:a});let u=e.participants??[],p=u.find(T=>T.participantId===n);if(!p)return M({result:{error:ee},stack:a});if(!p.participantType||![lt,ur].includes(p.participantType)||p.participantType===ur&&s.eventType!==Ze||p.participantType===lt&&s.eventType!==ei)return{error:Nn};let d=(s.entries??[]).find(T=>T.participantId===n);if(!d)return{error:VT};let{stageEntries:l}=TE({selected:!1,drawDefinition:r,drawId:o,event:s,stage:i}),f=l.map(ft),g=u.filter(({participantId:T})=>f.includes(T)).map(({individualParticipantIds:T})=>T).flat().filter(Boolean),I=p.individualParticipantIds?.filter(T=>os(T,g).length===1),S=yu({participantIds:[n],event:s});if(S.error||I?.length&&(S=Yn({participantIds:I,entryStatus:Lr,entryStage:d.entryStage,tournamentRecord:e,drawDefinition:r,drawId:o,event:s}),S.error))return S;let h;return t&&Es({participantIds:[n],tournamentRecord:e}).success&&(h=!0),{...P,participantRemoved:h}}function mS({removeGroupParticipant:t,tournamentRecord:e,drawDefinition:r,participantId:n,drawId:o,event:i}){return Gb({removeGroupParticipant:t,tournamentRecord:e,drawDefinition:r,participantId:n,drawId:o,event:i})}function Vb(t){if(!t.tournamentRecord)return{error:j};let{participantIds:e,...r}=t,n=0,o=[];for(let i of e){let s=Gb({participantId:i,...r});s.success&&(n+=1),s.error&&o.push(s.error)}return n?{destroyedCount:n,...P}:{error:o}}function Bp(t){let{tournamentRecord:e,replaceWithBye:r,drawDefinition:n,destroyPair:o,entryStatus:i,matchUpsMap:s,drawId:a}=t,c="removeDrawPositionAssignment",u=Su(t);if(u.error)return M({result:u,stack:c});let{participantId:p}=u,{drawPosition:m,event:d,structureId:l}=t,f=It({tournamentRecord:e,drawDefinition:n,event:d}).appliedPolicies??{};if([Zr,Cn].includes(i)&&p){let{tournamentRecord:S}=t,{participant:h}=Ao({tournamentRecord:S,participantId:p}),{participantType:T,individualParticipantIds:y}=h??{};if(o&&T===lt){let E=mS({tournamentRecord:S,drawDefinition:n,participantId:p,event:d});if(E.error)return M({result:E,stack:c});y&&zl({participantIds:y,tournamentRecord:S,drawDefinition:n,entryStatus:i,drawId:a,event:d})}else zl({participantIds:[p],tournamentRecord:S,drawDefinition:n,entryStatus:i,drawId:a,event:d})}if(r){let S=Cr({tournamentRecord:e,drawDefinition:n,drawPosition:m,structureId:l,matchUpsMap:s,event:d});if(S.error)return M({result:S,stack:c})}let{structure:g}=tt({drawDefinition:n,structureId:l});return Cl({structure:g,drawPositions:[m]}),fc({appliedPolicies:f,drawDefinition:n,positionAction:{name:"removeDrawPositionAssignment",replaceWithBye:r,drawPosition:m,entryStatus:i,structureId:l}}),u}function Bb(t){return Object.assign(t,{entryStatus:Cn}),Bp(t)}var Wo=({finishingPosition:t=ls,hasExistingDrawDefinition:e,qualifyingRoundNumber:r,structureAbbreviation:n,seedAssignments:o=[],stageSequence:i=1,qualifyingOnly:s,structureOrder:a,seedingProfile:c,matchUpFormat:u,structureType:p,structureName:m,matchUps:d=[],matchUpType:l,structureId:f,roundOffset:g,roundLimit:I,stageOrder:S,structures:h,tieFormat:T,stage:y})=>{let E={structureId:f??it(),structureAbbreviation:n,finishingPosition:t,seedAssignments:o,matchUpFormat:u,stageSequence:i,structureName:m};(s||e&&T)&&(E.tieFormat=T),a&&(E.structureOrder=a),p&&(E.structureType=p),c&&(typeof c=="string"?E.seedingProfile=c:typeof c=="object"&&typeof c.positioning=="string"&&(E.seedingProfile=c.positioning)),l&&(E.matchUpType=l),g&&(E.roundOffset=g),S&&(E.stageOrder=S),I&&(E.roundLimit=I),y&&(E.stage=y),r&&(E.qualifyingRoundNumber=r);let A=d.flatMap(({drawPositions:N})=>N).filter(Boolean);return h?E.structures=h:(E.matchUps=d,E.positionAssignments=pt(A).sort((N,U)=>N-U).map(N=>({drawPosition:N}))),E},lr=Wo;function yE(t){return _t(t)?t.split(" ").map(e=>e.split("").map((r,n)=>n?r.toLowerCase():r.toUpperCase()).join("")).join(" "):t}function xe(t){return _t(t)?yE(t.replace(/_/g," ")):""}function dS({structureName:t=xe(Fe),structureAbbreviation:e,drawDefinition:r,matchUpType:n,structureId:o}){if(!r)return{error:$};let i=lr({stage:Fe,structureAbbreviation:e,structureName:t,matchUps:[],structureId:o,matchUpType:n});return r.structures??=[],r.structures.push(i),Ft({drawDefinition:r,structureIds:[i.structureId]}),{...P}}function S$({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(Zt),e.reverse(),e}function E0({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 A0({positioning:t,size:e}){let r=S$({size:e}),n=[],o=[],i=d=>d[0],s=d=>d[d.length-1],a=(d,l)=>(t&&[Zc,km,vi].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=Q(1,e+1);for(let d of r)if(d===1){let l=he(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=he(m,d).map(p).filter(Boolean);f.length&&n.push(f)}return{divisions:r,divisionGroupings:n}}function lS({drawPositions:t}){if(!t?.length)return{error:Gc};let e=o=>t.filter(i=>i!==o).map(i=>[o,i]),r=[].concat(...(t??[]).map(e)),n=pt(r.map(fS)).map(o=>o.split("|").map(i=>+i));return{groupMatchUps:r,uniqueMatchUpGroupings:n}}function fS(t=[]){return!Array.isArray(t)||!t.length?"":[...t].sort(Zt).join("|")}function Hb({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,S)=>{o[d].push([i[S],s[S]])});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 fS(l)}))}function h$({rounds:t,hash:e}){return t?.length?t?.reduce((r,n,o)=>n.includes(e)?o+1:r,void 0):{error:nt}}var P0={getRoundRobinGroupMatchUps:lS,determineRoundNumber:h$,drawPositionsHash:fS,groupRounds:Hb};function Ec(t){let{hasExistingDrawDefinition:e,groupNameBase:r="Group",playoffAttributes:n,stageSequence:o=1,structureOptions:i,appliedPolicies:s,qualifyingOnly:a,seedingProfile:c,stage:u=H,matchUpType:p,roundTarget:m,structureId:d,groupNames:l,tieFormat:f,drawSize:g,idPrefix:I,isMock:S,uuids:h}=t,T=t.structureName??n?.["0"]?.name??xe(H),{groupCount:y,groupSize:E}=T$({structureOptions:i,appliedPolicies:s,drawSize:g}),A=uo,N,U=Q(1,y+1).map(D=>{let b=y$({groupSize:E,structureOrder:D,matchUpType:p,drawSize:g,idPrefix:I,isMock:S});N=Array.isArray(b)?Math.max(...b.map(({roundNumber:_})=>_??0)):0;let C=l?.[D-1]??`${r} ${D}`;return Wo({structureId:h?.pop(),hasExistingDrawDefinition:e,structureType:tu,finishingPosition:A,qualifyingOnly:a,structureOrder:D,structureName:C,tieFormat:f,matchUps:b,stage:u})}),R=Wo({structureId:d??h?.pop(),hasExistingDrawDefinition:e,structureType:de,finishingPosition:A,seedingProfile:c,structureName:T,stageSequence:o,structures:U,tieFormat:f,stage:u});return m&&ut({extension:{name:Rn,value:m},element:R}),{structures:[R],maxRoundNumber:N,groupCount:y,links:[],groupSize:E,...P}}function T$({appliedPolicies:t,structureOptions:e,drawSize:r}){let n=e?.groupSize,o=e?.groupSizeLimit||8,{validGroupSizes:i}=id({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 id(t){let{groupSizeLimit:e=10,drawSize:r=0}=t??{},n=Q(3,e+1).filter(o=>{let i=Math.ceil(r/o),s=i*o-r,a=Math.ceil(r/i),c=Math.ceil(s/i);return(!s||s<o)&&a===o&&a>=3&&c<2});return{...P,validGroupSizes:n}}function y$({structureOrder:t,matchUpType:e,groupSize:r,drawSize:n,idPrefix:o,isMock:i,uuids:s}){let a=(t-1)*r,c=Q(1+a,r+1+a),u=lS({drawPositions:c}).uniqueMatchUpGroupings??[],p=Hb({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,S)=>I.includes(f)?S+1:g,void 0)}function l(f){let g=fS(f),I=d(g),S=[1,n],h=E$({structureOrder:t,drawPositions:f,roundNumber:I,idPrefix:o,uuids:s}),T={matchUpStatus:I?zt:"BYE",matchUpType:e,finishingPositionRange:{winner:S,loser:S},drawPositions:f,roundNumber:I,matchUpId:h};return i&&(T.isMock=!0),T}}function E$({structureOrder:t,drawPositions:e,roundNumber:r,idPrefix:n,uuids:o}){return n?`${n}-${t}-${r}-DP-${e.join("-")}`:o?.pop()||it()}function gS(t){let{roundRobinGroupsCount:e,participantsCount:r,cluster:n}=t;if(!yt(r))return{seedBlocks:void 0,...M({result:{error:O},context:{participantsCount:r},stack:"getSeedBlocks"})};let o=Si(r);if(e){let l=Math.min(e,o),f=[],g=1;for(Q(0,l).forEach(()=>{f.push([g]),g++});g<o;){let I=Q(g,g+l);g+=l,f.push(I)}return{...P,seedBlocks:f}}let i=Q(1,o+1),s=[],a=o/2;for(;a>1;){let l=he(i,a),f=l.length;l.forEach((g,I)=>{let S,h=I<f/2,T=I%2===0,y=g[0],E=g[g.length-1];n&&f>4?f===8?S=h?E:y:S=T?y:E:S=h?y:E,Re(g,s)||s.push(S)}),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=Q(0,20).map(l=>Math.pow(2,l));u.unshift(1);let p=u.indexOf(o),m=0,d=[];return Q(0,p).forEach(l=>{d.push(s.slice(m,m+u[l])),m+=u[l]}),{...P,seedBlocks:d}}function IS({roundRobinGroupsCount:t,drawSize:e}){let r="getSeedGroups";if(!yt(e))return{seedGroups:void 0,...M({result:{error:O},context:{drawSize:e},stack:r})};if(t){if(!yt(t))return{seedGroups:void 0,...M({context:{roundRobinGroupsCount:t},result:{error:O},stack:r})};let n=1,o=Math.floor(e/t);return{seedGroups:Q(0,o).map(()=>{let s=Q(n,n+t);return n+=t,s})}}else{let{seedBlocks:n}=gS({participantsCount:e,roundRobinGroupsCount:t}),o=0;return{seedGroups:(n??[]).map(s=>(s??[]).map(()=>(o+=1,o)))}}}function EE({roundRobinGroupsCount:t,participantsCount:e}){if(t){let{validGroupSizes:o}=id({drawSize:e});if(!o?.map(a=>Math.ceil(e/a))?.includes(t))return M({context:{roundRobinGroupsCount:t},result:{error:O}})}let{seedGroups:r}=IS({drawSize:e,roundRobinGroupsCount:t}),n=r?.map(o=>Math.min(...o))??[];return{...P,seedingThresholds:n}}function Eu(t){if(!t)return 1/0;if(yt(t))return st(t);let e=t.split("-")[0];return yt(e)?st(e):1/0}function di({provisionalPositioning:t,returnAllProxies:e,appliedPolicies:r,seedingProfile:n,drawDefinition:o,allPositions:i,structure:s,random:a}){let c=[];if(!s)return{error:bi};let{matchUps:u,roundMatchUps:p}=ht({matchUpFilters:{roundNumbers:[1]},provisionalPositioning:t,structure:s}),{seedAssignments:m}=Pr({provisionalPositioning:t,returnAllProxies:e,drawDefinition:o,structure:s}),{positionAssignments:d}=se({structure:s}),l=d?.length,f=m?.length??0,g=[],S=Object.keys(p).map(k=>Number.parseInt(k)).sort((k,G)=>k-G).map(k=>{let G=p[k].map(B=>B.drawPositions).flat(1/0).filter(Boolean),V=G.filter(B=>!g.includes(B));return g=g.concat(...G),V}).filter(k=>k.length).reverse(),h=S.pop()??[],T=h&&Math.min(...h)-1||0;n=n??r?.seeding?.seedingProfile;let y=h?.length||0,E=S.filter(k=>k.filter(G=>G<=f).length),{stage:A,structureType:N,roundLimit:U}=s,R=N===de,D=!R&&S?.length,b=!R&&A===Z&&U,C=E.flat(1/0),_=D?C?.length:0,v=i?l:f,w=Ic({drawDefinition:o,structure:s,matchUps:u}),L=w?0:!D&&v||v&&C.length<v&&v-C.length||0;if(b){let k=s?.matchUps?s.matchUps.filter(({roundNumber:V})=>V===s.roundLimit).length:0,G=h.length/k;if(!D){let V=ad(n),B=he(h,G),z=1,W=Q(0,B[0].length).map(()=>{let K=Q(z,z+B.length);return z+=B.length,K});({validSeedBlocks:c}=N0({drawPositionBlocks:B,nonRandom:n?.nonRandom,positioning:V,seedGroups:W,random:a}))}}else R?{validSeedBlocks:c}=A$({nonRandom:n?.nonRandom,seedingProfile:n,structure:s,random:a}):D?c=E.map(k=>({seedNumbers:k,drawPositions:k})):w&&he(h,2).map((G,V)=>({drawPositions:[G[0]],seedNumbers:[V+1]})).forEach(G=>c.push(G));if(!R&&!w&&!b){let{blocks:k}=P$({drawPositionOffset:T,seedNumberOffset:_,seedCountGoal:L,seedingProfile:n,baseDrawSize:y});k.forEach(G=>c.push(G))}let x=c.flatMap(k=>k.drawPositions).reduce((k,G)=>h?.includes(G)&&k,!0);return!w&&!D&&!R&&!x?{error:CU,validSeedBlocks:[],isContainer:R,isFeedIn:D}:{isLuckyStructure:w,validSeedBlocks:c,isContainer:R,isFeedIn:D}}function A$({seedingProfile:t,structure:e,nonRandom:r,random:n}){let o=e.structures??[],i=o.length,s=Pt({structure:e})?.positionAssignments,a=ad(t),c=s?.length??0,{seedGroups:u}=IS({roundRobinGroupsCount:i,drawSize:c}),p=o.map(m=>Pt({structure:m}).positionAssignments?.map(d=>d.drawPosition));return N0({drawPositionBlocks:p,positioning:a,seedGroups:u,nonRandom:r,random:n})}function N0({drawPositionBlocks:t,positioning:e,seedGroups:r,nonRandom:n,random:o}){let i=[],{divisionGroupings:s}=A0({size:r.length,positioning:e}),a=[];return r.forEach((c,u)=>{let p=E0({blockPattern:s,index:u});c.forEach((m,d)=>{let l=u%2?t.length-d-1:d,g=t[l].slice().filter((S,h)=>p.includes(h+1)&&S);e!==vi?g=n?g:ar(g,o):u%2&&g.reverse();let I=g.find(S=>!a.includes(S));I&&(a.push(I),i.push({drawPositions:[I],seedNumbers:[m]}))})}),{validSeedBlocks:i}}function P$(t){let{drawPositionOffset:e=0,roundRobinGroupsCount:r,seedNumberOffset:n=0,seedingProfile:o,seedCountGoal:i,baseDrawSize:s}=t,a,c=[],{seedBlocks:u}=gS({cluster:[Zc,km].includes(ad(o)),participantsCount:s,roundRobinGroupsCount:r});a=0;for(let p of u){if(a+1>i)break;let m=p.map(l=>l+e),d=N$(a+1,p.length).map(l=>+l+n);a+=p.length,c.push({drawPositions:m,seedNumbers:d})}return{blocks:c}}function N$(t,e){return Array.from(new Array(e),(r,n)=>n+t)}function sd({appliedPolicies:t,drawDefinition:e,seedBlockInfo:r,drawPosition:n,structureId:o,seedNumber:i}){let{structure:s}=tt({drawDefinition:e,structureId:o});t??=It({drawDefinition:e}).appliedPolicies;let a=r?.validSeedBlocks;return!a&&s&&(a=di({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):a.flatMap(u=>u.drawPositions).includes(n)}function AE(t){let{provisionalPositioning:e,drawDefinition:r,seedingProfile:n,seedBlockInfo:o,structureId:i,randomize:s,random:a}=t,{structure:c}=tt({drawDefinition:r,structureId:i}),{seedAssignments:u}=Pr({returnAllProxies:t.returnAllProxies,provisionalPositioning:e,drawDefinition:r,structure:c}),{positionAssignments:p}=se({structure:c}),d=p?.filter(k=>k.participantId??k.bye??k.qualifier)?.map(k=>k.drawPosition).filter(Boolean),{appliedPolicies:l}=It({drawDefinition:r}),g=((o?.validSeedBlocks||c&&di({returnAllProxies:t.returnAllProxies,provisionalPositioning:e,appliedPolicies:l,drawDefinition:r,seedingProfile:n,structure:c})?.validSeedBlocks)??[]).find(k=>k.drawPositions.filter(V=>!d?.includes(V)).length),I=u?.map(k=>k.participantId).filter(Boolean),S=p?.map(k=>k.participantId).filter(Boolean),h=I?.filter(k=>S?.includes(k)),T=I?.filter(k=>!S?.includes(k)),y=u?.filter(k=>T?.includes(k.participantId)),E=u?.filter(k=>!k.participantId),N=(y?.length&&y.length>0?y.length:E?.length??0)&&g?.drawPositions.filter(k=>!d?.includes(k))||[],U=s?ar(N,a):N,R=[],D=U.map(()=>{let G=x(y,R)?.participantId;return G&&R.push(G),G}).filter(Boolean),b=u?.filter(k=>h?.includes(k.participantId)).map(k=>k.seedNumber),_=(g?.seedNumbers??[]).filter(k=>!b?.includes(k)),v=u?.filter(k=>_.includes(k.seedNumber)).map(k=>k.participantId),w=l?.seeding?.duplicateSeedNumbers;return{nextSeedBlock:g,unplacedSeedParticipantIds:(typeof w=="boolean"?w:!0)?D:v,unplacedSeedNumbers:_,unfilledPositions:U,unplacedSeedAssignments:y};function x(k,G){let V=k.filter(K=>!G.includes(K.participantId)),B=Math.min(...V.map(K=>Eu(K.seedValue))),z=V.filter(K=>Eu(K.seedValue)===B);return ar(z,a).pop()}}function ad(t){if(typeof t=="string")return t;if(typeof t=="object")return t.positioning}function xa({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}=tt({drawDefinition:r,structureId:s}),{positionAssignments:l}=se({structure:d}),f=Pr({provisionalPositioning:t,drawDefinition:r,structure:d}).seedAssignments,g=f.map(A=>A.seedNumber),I=Tu({drawDefinition:r,participantId:o});if(o&&!I)return M({result:{error:Vr},context:{participantId:o},stack:m});let S=p?Bt({event:p}).flightProfile?.flights?.length:0,h=S&&S>1,y=l?.find(A=>A.participantId===o)?.drawPosition;if(y&&!sd({drawPosition:y,drawDefinition:r,seedBlockInfo:i,structureId:s,seedNumber:a}))return M({result:{error:xg},context:{assignedDrawPosition:y},info:"invalid seed position",stack:m});g.includes(a)||f.push({seedNumber:a,seedValue:c});let E;return f.forEach(A=>{A.participantId===o&&A.seedNumber!==a&&(A.participantId=void 0),A.seedNumber===a&&(A.participantId=o,!n?.groupSeedingThreshold&&!h&&(A.seedValue=c??a),E=!0)}),E?(bl({tournamentId:e?.tournamentId,drawDefinition:r,structure:d,eventId:u}),{...P}):M({result:{error:bU},stack:m})}function tf({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}=ot({element:o,name:wo}),p=u?.value??{},m=q(p[r],!1,!0);if(c)i?.sides?.forEach(d=>{d.sideNumber===a&&(d.lineUp=m)});else{i.sides=[1,2].map(l=>({...i.sides?.find(g=>g.sideNumber===l)??{},sideNumber:l}));let d=i.sides.find(l=>l.sideNumber===a);d&&(d.lineUp=m)}gt({tournamentId:n?.tournamentId,context:"updateSidLineUp",eventId:s?.eventId,drawDefinition:o,matchUp:i})}function PE(t){let{sourceMatchUp:e}=t,{targetMatchUp:r,structure:n,matchUpsMap:o,drawPosition:i}=t,s=r.roundNumber>1&&r.roundNumber-1,a=Vo({structureId:n.structureId,matchUpsMap:o});Pe({method:"getPairedPreviousMatchUpIsDoubleExit",color:"brightcyan",keyColors:{structureId:"brightyellow",sourceMatchUpId:"brightmagenta"},structureId:n.structureId?.slice(0,8),targetMatchUpId:r.matchUpId,targetRound:[r.roundNumber,r.roundPosition],previousRoundNumber:s,sourceMatchUpId:e?.matchUpId,sourceStructureId:e?.structureId?.slice(0,8),sourceRound:e?[e.roundNumber,e.roundPosition]:void 0,drawPosition:i,structureMatchUpCount:a?.length}),e&&e.structureId!==n.structureId&&i?(Pe({method:"getPairedPreviousMatchUpIsDoubleExit",color:"cyan",info:"cross_structure_sourceMatchUp_resolving_in_target",originalSourceId:e?.matchUpId,originalSourceStructure:e?.structureId?.slice(0,8),targetStructure:n.structureId?.slice(0,8)}),e=a.find(({drawPositions:f,roundNumber:g})=>g===s&&f?.includes(i)),Pe({method:"getPairedPreviousMatchUpIsDoubleExit",color:"cyan",info:"resolved_cross_structure_sourceMatchUp",resolvedMatchUpId:e?.matchUpId,resolvedRound:e?[e.roundNumber,e.roundPosition]:void 0,resolvedStatus:e?.matchUpStatus})):!e&&i&&(e=a.find(({drawPositions:f,roundNumber:g})=>g===s&&f?.includes(i)),Pe({method:"getPairedPreviousMatchUpIsDoubleExit",color:"cyan",info:"resolved_sourceMatchUp_from_drawPosition",resolvedMatchUpId:e?.matchUpId,resolvedRound:e?[e.roundNumber,e.roundPosition]:void 0,resolvedStatus:e?.matchUpStatus}));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=[Qt,ge].includes(d);return Pe({method:"getPairedPreviousMatchUpIsDoubleExit",color:l?"brightred":"brightgreen",keyColors:{pairedMatchUpId:"brightcyan",isDoubleExit:l?"brightred":"brightgreen"},sourceRoundPosition:c,offset:u,pairedRoundPosition:p,pairedMatchUpId:m?.matchUpId,pairedRound:m?[m.roundNumber,m.roundPosition]:void 0,pairedStatus:d,isDoubleExit:l}),{pairedPreviousMatchUp:m,pairedPreviousMatchUpIsDoubleExit:l}}function U0({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(Zt).filter(Boolean),positionAdded:r,positionAssigned:n}}function NE({structureId:t,matchUpsMap:e,matchUp:r}){let n=r?.roundPosition,o=n%2?1:-1,i=n+o;return{pairedPreviousMatchUp:Vo({matchUpsMap:e,structureId:t}).find(({roundNumber:c,roundPosition:u})=>c===r?.roundNumber&&u===i)}}function UE({inContextDrawMatchUps:t,sourceMatchUpStatus:e,sourceMatchUpId:r,matchUpsMap:n,matchUp:o}){let i=t.find(a=>a.matchUpId===r),{pairedPreviousMatchUp:s}=NE({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=_t(p)||!isNaN(p)?{code:p}:p;return m.sideNumber===u?{...m,previousMatchUpStatus:e}:m})}}function ef({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 Ac({inContextDrawMatchUps:t,sourceMatchUpStatus:e,tournamentRecord:r,sourceMatchUpId:n,drawDefinition:o,matchUpStatus:i,drawPosition:s,matchUpsMap:a,matchUpId:c,event:u}){let p="assignMatchUpDrawPosition";a??=Ie({drawDefinition:o});let m=t??te({inContext:!0,drawDefinition:o,matchUpsMap:a}).matchUps??[],d=m.find(F=>F.matchUpId===c),l=d?.structureId,f=o?.structures?.find(F=>F.structureId===l);if(!f)return{error:Nt};let g=a?.drawMatchUps?.find(F=>F.matchUpId===c),I=g?.drawPositions??[],{positionAdded:S,positionAssigned:h,updatedDrawPositions:T}=U0({drawPositions:I,drawPosition:s}),{positionAssignments:y}=Pt({drawDefinition:o,structure:f}),A=y?.filter(F=>T.includes(F.drawPosition))?.find(({bye:F})=>F),N=g?.matchUpStatus&&Ye(g.matchUpStatus)&&T.filter(Boolean).length<2;i=U$({isByeMatchUp:A,matchUpStatus:i,isDoubleExitExit:N,matchUp:g});let U=!!(Ye(g?.matchUpStatus)&&g?.winningSide);g&&S&&D$({updatedDrawPositions:T,sourceMatchUpStatus:e,isPropagatedExit:U,isDoubleExitExit:N,tournamentRecord:r,inContextMatchUp:d,sourceMatchUpId:n,drawDefinition:o,matchUpStatus:i,drawPosition:s,matchUpsMap:a,matchUpId:c,matchUp:g,stack:p});let R=er({inContextDrawMatchUps:m,inContextMatchUp:d,drawDefinition:o,matchUpId:c}),{targetMatchUps:{winnerMatchUp:D,loserMatchUp:b,loserTargetDrawPosition:C},targetLinks:{loserTargetLink:_}}=R,v=an(o?.drawType),w=R$({inContextDrawMatchUps:m,positionAssigned:h,isPropagatedExit:U,tournamentRecord:r,inContextMatchUp:d,drawDefinition:o,matchUpStatus:i,winnerMatchUp:D,drawPosition:s,isByeMatchUp:A,isLuckyDraw:v,matchUpsMap:a,matchUp:g,structure:f});if(w?.error)return w;g?.matchUpType===Ot&&b$({inContextDrawMatchUps:m,positionAssignments:y,tournamentRecord:r,drawDefinition:o,drawPosition:s,matchUp:g});let L=C$({updatedDrawPositions:T,loserTargetDrawPosition:C,tournamentRecord:r,loserTargetLink:_,drawDefinition:o,structureId:f.structureId,isByeMatchUp:A,loserMatchUp:b,matchUpsMap:a,event:u});return L?.error?L:h?{...P}:M({result:{error:kc},context:{drawPosition:s},stack:p})}function U$({isByeMatchUp:t,matchUpStatus:e,isDoubleExitExit:r,matchUp:n}){return t&&"BYE"||e||r&&n.matchUpStatus||n?.matchUpStatus&&[Qt,ge].includes(n.matchUpStatus)&&n.matchUpStatus||zt}function D$({updatedDrawPositions:t,sourceMatchUpStatus:e,isPropagatedExit:r,isDoubleExitExit:n,tournamentRecord:o,inContextMatchUp:i,sourceMatchUpId:s,drawDefinition:a,matchUpStatus:c,drawPosition:u,matchUpsMap:p,matchUpId:m,matchUp:d,stack:l}){let f=te({inContext:!0,drawDefinition:a,matchUpsMap:p}).matchUps??[],g=n&&ef({inContextDrawMatchUps:f,drawPosition:u,matchUpId:m})||r&&d.winningSide||void 0;d?.matchUpStatusCodes&&UE({inContextDrawMatchUps:f,sourceMatchUpStatus:e,sourceMatchUpId:s,matchUpsMap:p,matchUp:d}),Object.assign(d,{drawPositions:t,winningSide:g,matchUpStatus:r?d?.matchUpStatus:c}),gt({tournamentId:o?.tournamentId,eventId:i?.eventId,context:l,drawDefinition:a,matchUp:d})}function R$({inContextDrawMatchUps:t,positionAssigned:e,isPropagatedExit:r,tournamentRecord:n,inContextMatchUp:o,drawDefinition:i,matchUpStatus:s,winnerMatchUp:a,drawPosition:c,isByeMatchUp:u,isLuckyDraw:p,matchUpsMap:m,matchUp:d,structure:l}){if(e&&u&&!p){if(a)if(["BYE",Qt,ge].includes(s)){let f=Ac({matchUpId:a.matchUpId,inContextDrawMatchUps:t,tournamentRecord:n,drawDefinition:i,drawPosition:c,matchUpsMap:m});if(f.error)return f}else{let{structureId:f}=a;f!==l.structureId&&console.log("winnerMatchUp in different structure... participant is in different targetDrawPosition")}}else if(e&&r){if(a){let f=Ac({matchUpId:a.matchUpId,inContextDrawMatchUps:t,tournamentRecord:n,drawDefinition:i,drawPosition:c,matchUpsMap:m});if(f.error)return f}}else if(a&&o&&!o.feedRound){let{pairedPreviousMatchUpIsDoubleExit:f}=PE({targetMatchUp:d,drawPosition:c,matchUpsMap:m,structure:l});if(f){let g=Ac({matchUpId:a.matchUpId,inContextDrawMatchUps:t,tournamentRecord:n,drawDefinition:i,drawPosition:c,matchUpsMap:m});if(g.error)return g}}}function b$({inContextDrawMatchUps:t,positionAssignments:e,tournamentRecord:r,drawDefinition:n,drawPosition:o,matchUp:i}){let s=t?.find(({matchUpId:p})=>p===i.matchUpId),c=(s?.sides??[]).reduce((p,m,d)=>m.drawPosition===o?d:p,void 0),u=e?.find(p=>p.drawPosition===o)?.participantId;u&&c!==void 0&&tf({inContextTargetMatchUp:s,drawPositionSideIndex:c,teamParticipantId:u,tournamentRecord:r,drawDefinition:n,matchUp:i})}function C$({updatedDrawPositions:t,loserTargetDrawPosition:e,tournamentRecord:r,loserTargetLink:n,drawDefinition:o,structureId:i,isByeMatchUp:s,loserMatchUp:a,matchUpsMap:c,event:u}){if(n?.linkCondition!==Bn||t.filter(Boolean).length!==2||s)return;if(Vo({structureId:i,matchUpsMap:c}).filter(({drawPositions:l,roundNumber:f})=>f===1&&Re(l,t)).every(({matchUpStatus:l})=>[ie,Ue].includes(l))&&a){let{structureId:l}=a,f=Cr({drawPosition:e,tournamentRecord:r,drawDefinition:o,structureId:l,matchUpsMap:c,event:u});if(f.error)return f}}function DE({inContextDrawMatchUps:t,drawDefinition:e,assignments:r,matchUpsMap:n,structure:o}){let s=Vi({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)&&Yt(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 rf({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}=nd({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 Ai(t){return`${t} must be an array`}function nf({lineUp:t,tieFormat:e}){let r=[];if(!Array.isArray(t))return r.push(Ai("lineUp")),{valid:!1,errors:r,error:O};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(Ai("collectionAssignments")),!1):(r.push("Missing participantId"),!1)}),o=pt(t.map(ft)).length===t.length;return o||r.push("Duplicated participantId(s)"),{valid:n&&o,errors:r,error:r.length?O:void 0}}function As({drawDefinition:t,participantId:e,tieFormat:r,lineUp:n}){if(typeof t!="object")return{error:$};if(typeof e!="string")return{error:He};let o=nf({lineUp:n,tieFormat:r});if(!o.valid)return o;let{extension:i}=ot({element:t,name:wo}),s=i?.value??{};return s[e]=rf({lineUp:n}),ut({element:t,extension:{name:wo,value:s}}),lc({drawDefinition:t}),{...P}}function SS({inContextDrawMatchUps:t,inheritance:e=!0,tournamentRecord:r,drawDefinition:n,matchUpsMap:o,assignments:i,structure:s,event:a}){if(!n)return{error:$};let{drawPositions:c,matchUps:u,targetMatchUps:p}=DE({inContextDrawMatchUps:t,matchUpsMap:o,assignments:i,structure:s});for(let m of p)m.matchUpType===Ir&&(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&&As({drawDefinition:n,participantId:I,lineUp:[],tieFormat:g})}gt({tournamentId:r?.tournamentId,context:"resetLineUps",eventId:a?.eventId,drawDefinition:n,matchUp:f})}}});return{...P}}function vn({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 M({result:{error:He},stack:l});p=p??Ie({drawDefinition:i}),e||({matchUps:e}=te({inContext:!0,drawDefinition:i,matchUpsMap:p}));let f=tt({drawDefinition:i,structureId:m});if(f.error)return M({result:f,stack:l});let{structure:g}=f;if(!g)return{error:Nt};if(Ae({structure:g}))return M({result:{error:cr},stack:l});let{seedAssignments:I}=Pr({provisionalPositioning:t,drawDefinition:i,structure:g}),h=I?.find(C=>C.participantId===a)?.seedNumber,{appliedPolicies:T}=It({tournamentRecord:o,drawDefinition:i,structure:g,event:d});if(h&&!sd({seedNumber:h,appliedPolicies:T,drawDefinition:i,seedBlockInfo:c,drawPosition:u,structureId:m}))return M({result:{error:xg},context:{drawPosition:u},stack:l});let E=se({structure:g}).positionAssignments??[],A=E?.find(C=>C.drawPosition===u);if(!A)return M({result:{error:is},context:{drawPosition:u},stack:l});if(E?.map(ft).includes(a))return M({result:{error:Ia},context:{drawPosition:u},stack:l});let{containsParticipant:U,containsBye:R}=Kl(A);if(R){let C=Su({inContextDrawMatchUps:e,tournamentRecord:o,drawDefinition:i,drawPosition:u,structureId:m,matchUpsMap:p,event:d});if(C.error)return M({result:C,stack:l})}if(U&&A.participantId!==a){let{activeDrawPositions:C}=qi({drawDefinition:i,structureId:m});if(C.includes(u))return M({result:{error:Vc},stack:l});SS({assignments:[A],inContextDrawMatchUps:e,tournamentRecord:o,drawDefinition:i,matchUpsMap:p,structure:g})}A.participantId=a,r&&(A.qualifier=!0),M$({provisionalPositioning:t,tournamentRecord:o,drawDefinition:i,seedingProfile:s,participantId:a,structureId:m,structure:g,event:d}),g.structureType===de?v$({inContextDrawMatchUps:e,positionAssignments:E,positionAssignment:A,tournamentRecord:o,drawDefinition:i,participantId:a,matchUpsMap:p,structure:g}):O$({provisionalPositioning:t,inContextDrawMatchUps:e,sourceMatchUpStatus:n,tournamentRecord:o,drawDefinition:i,drawPosition:u,matchUpsMap:p,structure:g,event:d});let D=i.entries?.find(C=>C.participantId===a),b=d?.entries?.find(C=>C.participantId===a);return!D&&b&&Jl({entryStatus:b.entryStatus,entryStage:g.stage,ignoreStageSpace:!0,drawDefinition:i,participantId:a,event:d}),Sn({tournamentId:o?.tournamentId,drawDefinition:i,structure:g,event:d}),{positionAssignments:E,...P}}function M$({provisionalPositioning:t,tournamentRecord:e,drawDefinition:r,seedingProfile:n,participantId:o,structureId:i,structure:s,event:a}){if(!(s.stage===H&&(!s.stageSequence||s.stageSequence>1))&&!(s.stage&&[me,Vt].includes(s.stage)))return;let u=s.stage===Z?Z:H,d=(r.structures?.find(l=>l?.stage===u&&l?.stageSequence===1)?.seedAssignments??[]).find(l=>l.participantId===o);d?.participantId&&xa({eventId:a?.eventId,participantId:d.participantId,seedNumber:d.seedNumber,seedValue:d.seedValue,provisionalPositioning:t,tournamentRecord:e,drawDefinition:r,seedingProfile:n,structureId:i,event:a})}function v$({inContextDrawMatchUps:t,positionAssignments:e,positionAssignment:r,tournamentRecord:n,drawDefinition:o,participantId:i,matchUpsMap:s,structure:a}){gE({positionAssignments:e,tournamentRecord:n,drawDefinition:o,matchUpsMap:s,structure:a});let{drawPositions:c,matchUps:u,targetMatchUps:p}=DE({assignments:[r],inContextDrawMatchUps:t,drawDefinition:o,matchUpsMap:s,structure:a});if(c&&u?.length===1&&u[0].matchUpType===Ot){let d=(p?.[0].sides??[]).reduce((l,f,g)=>c?.includes(f.drawPosition)?g:l,void 0);tf({inContextTargetMatchUp:p[0],teamParticipantId:i,matchUp:u[0],drawPositionSideIndex:d,tournamentRecord:n,drawDefinition:o})}}function O$({provisionalPositioning:t,inContextDrawMatchUps:e,sourceMatchUpStatus:r,tournamentRecord:n,drawDefinition:o,drawPosition:i,matchUpsMap:s,structure:a,event:c}){let u={isCollectionMatchUp:!1},{matchUps:p}=ht({provisionalPositioning:t,matchUpFilters:u,drawDefinition:o,matchUpsMap:s,structure:a,event:c}),{roundMatchUps:m}=De({matchUps:p}),{initialRoundNumber:d}=qs({drawPosition:i,matchUps:p}),l=d&&m?.[d].find(f=>f.drawPositions?.includes(i));if(l){let f=Ac({matchUpId:l.matchUpId,inContextDrawMatchUps:e,sourceMatchUpStatus:r,tournamentRecord:n,drawDefinition:o,drawPosition:i,matchUpsMap:s});if(f.error)return M({stack:"assignDrawPositionToMatchUps",context:{drawPosition:i},result:f})}return{...P}}function of(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:$};let m=It({tournamentRecord:o,drawDefinition:i,event:u}).appliedPolicies??{},{inContextDrawMatchUps:d,matchUpsMap:l}=t;l||(l=Ie({drawDefinition:i}),Object.assign(t,{matchUpsMap:l})),d||({matchUps:d}=te({inContext:!0,drawDefinition:i,matchUpsMap:l}),Object.assign(t,{inContextDrawMatchUps:d}));let{positionAssignments:f}=Pt({drawDefinition:i,structureId:c}),g=f?.find(y=>y.drawPosition===a);if(g?.participantId){let y=g.participantId,E=vn({inContextDrawMatchUps:d,tournamentRecord:o,drawDefinition:i,participantId:s,drawPosition:a,structureId:c,matchUpsMap:l,event:u});return E.success?T({appliedPolicies:m,removedParticipantId:y}):M({result:E,stack:p})}let I=Su({inContextDrawMatchUps:d,tournamentRecord:o,drawDefinition:i,drawPosition:a,structureId:c,matchUpsMap:l,event:u});if(I.error)return M({result:I,stack:p});let S=I.participantId,h=vn({inContextDrawMatchUps:d,isQualifierPosition:r,tournamentRecord:o,drawDefinition:i,participantId:s,drawPosition:a,structureId:c,matchUpsMap:l,event:u});if(!h.success)return M({result:h,stack:p});return T({appliedPolicies:m,removedParticipantId:S});function T({appliedPolicies:y,removedParticipantId:E}){let{structure:A}=tt({drawDefinition:i,structureId:c});Cl({drawPositions:[a],structure:A});let N={[e]:s,name:n,drawPosition:a,structureId:c};return fc({appliedPolicies:y,drawDefinition:i,positionAction:N}),M({context:{removedParticipantId:E},result:{...P},stack:p})}}function D0({luckyLoserParticipantId:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,structureId:o}){return of({positionActionName:"luckyLoserDrawPositionAssignment",participantId:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,structureId:o})}function Wb(t){return D0(t)}function RE({params:t,modMap:e,structure:r}){let{tournamentRecord:n,drawDefinition:o,event:i}=t;for(let s of r.matchUps)e[s.matchUpId]&&(s.roundNumber=e[s.matchUpId],gt({tournamentId:n?.tournamentId,eventId:i?.eventId,drawDefinition:o,matchUp:s}))}function bE(t,e){let r=[{drawDefinition:!0,structureId:!0}];Array.isArray(e)&&r.push(...e);let n=X(t,r);if(n.error)return n;let o=tt(t);if(o.error)return o;let i=o.structure;if(!Ae({structure:i}))return M({result:{error:Do,message:"structure must be adHoc"}});let{roundMatchUps:a=[],roundNumbers:c}=De({matchUps:i?.matchUps});return c?.length?{valid:!0,structure:i,roundMatchUps:a,roundNumbers:c}:{error:Vn}}function Yb(t){let e=bE(t,[{targetRoundNumber:!0,roundNumber:!0,[Ge]:Yw}]);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 M({result:{error:O},info:"roundNumbers must be valid rounds"});let a=i>s,c=a?Q(s+1,i+1):Q(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),RE({params:t,modMap:u,structure:r}),{...P}}function jb({structurePositionAssignments:t,provisionalPositioning:e,tournamentRecord:r,drawDefinition:n,event:o}){if(!n)return{error:$};if(!Array.isArray(t))return{error:O};let i="setPositionAssignments";for(let a of t){let{structureId:c,positionAssignments:u}=a;if(!u)continue;let p=tt({drawDefinition:n,structureId:c});if(p.error)return p;let m=p.structure;if(!m)return{error:Nt};let d=Pt({structure:m}).positionAssignments?.map(({drawPosition:I})=>I),l=u?.map(({drawPosition:I})=>I);if(Yt(d,l).length!==d?.length)return M({result:{error:O},info:"drawPositions do not match",stack:i});let f=Ie({drawDefinition:n}),{matchUps:g}=te({inContext:!0,drawDefinition:n,matchUpsMap:f});for(let I of u??[]){let{drawPosition:S,participantId:h,bye:T,qualifier:y}=I;if(T){let E=Cr({tournamentRecord:r,drawDefinition:n,drawPosition:S,matchUpsMap:f,structureId:c,structure:m,event:o});if(E?.error)return E}else if(y)u.forEach(E=>{E.drawPosition===S&&(E.qualifier=!0,delete E.participantId,delete E.bye)});else if(h){let E=vn({provisionalPositioning:e,inContextDrawMatchUps:g,tournamentRecord:r,drawDefinition:n,participantId:h,drawPosition:S,matchUpsMap:f,structureId:c,event:o});if(E?.error)return E}}Sn({tournamentId:r?.tournamentId,drawDefinition:n,structure:m,event:o})}let s=t.map(({structureId:a})=>a);return Ft({tournamentId:r?.tournamentId,eventId:o?.eventId,drawDefinition:n,structureIds:s}),{...P}}function qb(t){let e=bE(t,[{roundNumbers:!0,[Ge]:ke,[$e]:s=>s.length===2&&s.every(Le)}]);if(e.error)return e;let{structure:r,roundMatchUps:n,roundNumbers:o}=e;if(!t.roundNumbers.every(s=>o?.includes(s)))return M({result:{error:O,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]})),RE({params:t,modMap:i,structure:r}),{...P}}function sf({roundPosition:t,roundNumber:e,idPrefix:r,uuids:n}){return r?`${r}-${e}-${t}`:n?.pop()||it()}function R0({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=Q(0,p).map(g=>m?m+g:void 0),l=[];for(let g=0;g<p;g++){let I=d.shift(),S={drawPosition:I,fed:u+1,feed:!0},h=c[g];h.roundNumber=r-1;let T=sf({roundPosition:h.roundPosition,roundNumber:r,idPrefix:o,uuids:a}),y={roundPosition:h.roundPosition,drawPositions:[I],matchUpStatus:zt,roundNumber:r,matchUpId:T};t&&(y.matchUpType=n),s&&(y.isMock=!0),i.push(y);let E={children:[h,S]};l.push(E)}let f=e?e-p:void 0;return{roundNodes:l,matchUps:i,drawPosition:f}}function cd({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=sf({roundPosition:p,roundNumber:r,idPrefix:o,uuids:s}),I={roundPosition:p,children:[l,f],matchUpId:g};u.push(I);let S={drawPositions:I.children.map(h=>h?.drawPosition).filter(Boolean),matchUpStatus:zt,matchUpId:I.matchUpId,roundPosition:p,roundNumber:r};t&&e&&(S.matchUpType=e),i&&(S.isMock=!0),n.push(S),p++,c+=2}return{roundNodes:u,matchUps:n}}function Pi(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=_$({drawSize:i}),S=I.length,h=0;if(r?.length)h=r.reduce((x,k)=>x+k,0);else if(e){let x=e-i;r=I.filter(k=>k<=x?(x-=k,!0):!1),h=r.reduce((k,G)=>k+G,0),n=r.length}else o>=S?n=0:u&&(n=S-u,o=0),r=I.filter((x,k)=>u&&!n||n&&k>=o+n||k<o?0:x),h=r.reduce((x,k)=>x+k,0),n=r.length;let T=[...I,...r].sort((x,k)=>k-x),y=T.length,A=[...(c??[]).map(x=>x-1),...(s??[]).map(x=>y-x)].map(x=>T[x]).reduce((x,k)=>x+k,0);h=h-A;let N=0,U=[],R,D=1,C=Q(0,i).map((x,k)=>({drawPosition:k+1+h})),_=h+1;for(let x of I){if({roundNodes:R,matchUps:U}=cd({matchUpType:m,roundNumber:D,idPrefix:d,matchUps:U,isMock:l,nodes:C,uuids:f}),D++,r.includes(x)){let k=mn(r)[x],G=Q(0,k),V=y+1-D,B=s?.includes(V)??c?.includes(D);G.forEach(()=>{({roundNodes:R,matchUps:U,drawPosition:_}=R0({drawPosition:!B&&_||void 0,nodes:R,matchUpType:m,roundNumber:D,idPrefix:d,matchUps:U,isMock:l,uuids:f,fed:N})),D++,N+=1})}C=R}y!==D-1&&console.log("ERROR");let v=i-h;U=hc({finishingPositionOffset:p?v:a,positionsFed:h,roundsCount:y,matchUps:U,fmlc:g});let L=R?.length?R[0]:R;return L&&(L.roundNumber=D-1,L.matchUps=U),{draw:L,matchUps:U,roundsCount:y};function F(x){let k=Zd(x);return k>x?k/2:k}}function _$({drawSize:t}){let e=Math.ceil(Math.log(t)/Math.log(2));return Q(0,e).reverse().map(n=>Math.pow(2,n))}function Tr({finishingPositionOffset:t,finishingPositionLimit:e,qualifyingRoundNumber:r,qualifyingPositions:n,matchUpType:o,roundLimit:i,idPrefix:s,drawSize:a,isMock:c,uuids:u}){if(isNaN(a)||a<2||n&&a<=n)return{matchUps:[],roundsCount:0};if(n&&(!en(a)||a%n)){let I=n;for(;I<a;)I=2*I;a=I}let p=n&&!(a%2)&&(!isNaN(n)||r&&!isNaN(r))&&(a/n===Math.round(a/n)||r&&a/r===Math.round(a/r));if(!en(a)&&!p)return{matchUps:[],roundsCount:0};let m=Q(1,a+1).map(I=>({drawPosition:I})),d,l=[],f=1;for({roundNodes:d,matchUps:l}=cd({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}=cd({nodes:d,matchUpType:o,roundNumber:f,idPrefix:s,matchUps:l,isMock:c,uuids:u}),f++;let g=f-1;return l=hc({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 Au(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,childStage:g,stage:I=H,drawSize:S,idPrefix:h,isMock:T,uuids:y}=t;if(!(!s||!u||s?.[c])||S<2||f&&a>f)return{};let A=[],N=[],U=[],R=t.matchUpType??d?.matchUpType,D=e+1,b=e+S,C=`${D}-${b}`,_=s?.[c],v=n&&`${n} `||"",w=s?.[C]??o?.[C],L=t.structureName||w?.name||_?.name&&(r?`${v}${_?.name}`:_.name)||`${v}${C}`,F=w?.abbreviation??_?.abbreviation,x=t.structureId??_?.structureId??y?.pop(),k={idPrefix:h&&`${h}-${L}-RP`,finishingPositionOffset:e,matchUpType:R,drawSize:S,isMock:T,uuids:y},{matchUps:G}=l?Pi(k):Tr(k),V=lr({structureAbbreviation:F,stageSequence:a,structureName:L,matchUpType:R,roundOffset:m,structureId:x,matchUps:G,stage:I});A.push(...G),N.push(V);let B=Math.ceil(Math.log(S)/Math.log(2)),z=p?Math.min(p-m,B):(!i||D<i)&&B||0;return S>2&&Q(1,z+1).forEach(K=>W(K)),{structureId:V.structureId,matchUps:A,structureName:L,structures:N,links:U,...P};function W(K){let Y=S/Math.pow(2,K);if(Y<2)return;let J=S/Math.pow(2,K)+e;if(i&&J+1>i)return;let{structures:ct,structureId:Et,matchUps:Wt,links:Dt}=Au({finishingPositionOffset:J,exitProfile:`${c}-${K}`,roundOffset:m+K,stageSequence:a+1,stage:g??I,drawSize:Y,addNameBaseToAttributeName:r,playoffStructureNameBase:n,finishingPositionNaming:o,finishingPositionLimit:i,playoffAttributes:s,exitProfileLimit:u,roundOffsetLimit:p,drawDefinition:d,sequenceLimit:f,childStage:g,matchUpType:R,idPrefix:h,uuids:y});if(V.structureId&&Et){let pe={linkType:ir,source:{roundNumber:K,structureId:V.structureId},target:{roundNumber:1,feedProfile:qe,structureId:Et}};Dt&&V&&Dt.push(pe),Dt?.length&&U.push(...Dt)}return ct?.length&&N.push(...ct),Wt?.length&&A.push(...Wt),{structureId:Et,childLinks:Dt,structures:N}}}function b0({q1Structure:t,eliminatorStructure:e,q2Structure:r,finalStructure:n}){return[{linkType:Er,source:{roundNumber:1,structureId:t.structureId},target:{feedProfile:qe,roundNumber:1,structureId:n.structureId}},{linkType:ir,source:{roundNumber:1,structureId:t.structureId},target:{feedProfile:qe,roundNumber:1,structureId:r.structureId}},{linkType:Er,source:{roundNumber:1,structureId:e.structureId},target:{feedProfile:qe,roundNumber:1,structureId:r.structureId}},{linkType:Er,source:{roundNumber:1,structureId:r.structureId},target:{feedProfile:qe,roundNumber:1,structureId:n.structureId}}]}function CE({finishingPositionOffset:t=0,stage:e=H,structureName:r,matchUpType:n,idPrefix:o,drawSize:i,isMock:s,uuids:a}){if(i!==4)return{error:Jo,info:"PAGE_PLAYOFF requires exactly 4 participants"};let c=[],{matchUps:u}=Tr({idPrefix:o&&`${o}-q1`,drawSize:2,matchUpType:n,isMock:s,uuids:a}),p=Wo({structureName:r?`${r} Qualifier 1`:"Qualifier 1",structureAbbreviation:"Q1",structureId:a?.pop(),matchUps:u,stageSequence:1,matchUpType:n,stage:e});c.push(p);let{matchUps:m}=Tr({finishingPositionOffset:t+2,idPrefix:o&&`${o}-el`,drawSize:2,matchUpType:n,isMock:s,uuids:a}),d=Wo({structureName:r?`${r} Eliminator`:"Eliminator",structureAbbreviation:"EL",structureId:a?.pop(),matchUps:m,stageSequence:2,matchUpType:n,stage:e});c.push(d);let{matchUps:l}=Tr({finishingPositionOffset:t+1,idPrefix:o&&`${o}-q2`,drawSize:2,matchUpType:n,isMock:s,uuids:a}),f=Wo({structureName:r?`${r} Qualifier 2`:"Qualifier 2",structureAbbreviation:"Q2",structureId:a?.pop(),stage:Vt,matchUps:l,stageSequence:3,matchUpType:n});c.push(f);let{matchUps:g}=Tr({finishingPositionOffset:t,idPrefix:o&&`${o}-fi`,drawSize:2,matchUpType:n,isMock:s,uuids:a}),I=Wo({structureName:r?`${r} Final`:"Final",structureAbbreviation:"F",structureId:a?.pop(),matchUps:g,stage:Vt,stageSequence:4,matchUpType:n});c.push(I);let S=b0({eliminatorStructure:d,q1Structure:p,q2Structure:f,finalStructure:I});return{structures:c,links:S,...P}}function af({drawDefinition:t,matchUpsMap:e,structureId:r}){let n=tt({drawDefinition:t,structureId:r});if(n.error)return M({result:n});let{matchUps:o}=ht({structure:n.structure,matchUpsMap:e});return{...De({matchUps:o}),matchUps:o,matchUpsMap:e}}function $b({finishingPositions:t,drawDefinition:e,structureId:r}){let{roundProfile:n}=af({drawDefinition:e,structureId:r});return(n&&Object.keys(n))?.reduce((i,s)=>(C0(n?.[s]).forEach(c=>{t.forEach(u=>{x$({position:u,rangeDefinition:c})&&(i[u]={roundNumber:s})})}),i),{})}function x$({position:t,rangeDefinition:e}){if(!Array.isArray(e)||e.reduce((i,s)=>i||isNaN(s),!1))return!1;let[r,n]=e;return Q(r,(n||r)+1).includes(t)}function C0(t){return[pt(t?.finishingPositionRange?.loser??[]),pt(t?.finishingPositionRange?.winner??[])]}function M0(t){return C0(t).map(e=>Q(e[0],e[1]&&e[1]+1||e[0]+1))}function Pu({drawDefinition:t,structureIds:e,matchUpsMap:r}){if(e&&!Array.isArray(e))return{error:O,context:{structureIds:e}};if(!t)return{error:$};e=e??(t.structures??[]).filter(a=>a.stage!==Z).map(({structureId:a})=>a);let n=e.map(a=>{let{roundProfile:c}=af({drawDefinition:t,matchUpsMap:r,structureId:a});return(c&&Object.values(c))?.map(M0).flat()}).flat(),o=n.filter(a=>a?.length===1).sort(Zt).flat();return{positionsNotPlayedOff:pt(n.flat()).filter(a=>!o.includes(a)),positionsPlayedOff:o}}function ME({excludeRoundNumbers:t=[],playoffPositions:e=[],drawDefinition:r,structureId:n}){let o=dt({drawDefinition:r,structureId:n},[Kt,po]);if(o.error)return o;if(!e)return{error:nt,info:"missing playoffPositions"};let i=Pu({drawDefinition:r});if(i.error)return i;let s=i.positionsPlayedOff,a=e.filter(T=>!s.includes(T)),c=$b({finishingPositions:a,drawDefinition:r,structureId:n}),p=Object.values(c).reduce((T,y)=>T.includes(y.roundNumber)?T:T.concat(y.roundNumber),[]).map(T=>st(T)).filter(T=>!t.includes(T)),m=$b({finishingPositions:s,drawDefinition:r,structureId:n}),d=m?Object.values(m):[],l=m?d.reduce((T,y)=>T.includes(y.roundNumber)?T:T.concat(y.roundNumber),[]).map(T=>st(T)):[],f=p.filter(T=>!l.includes(T)).sort(Zt),{roundProfile:g}=af({drawDefinition:r,structureId:n}),I=f.map(T=>{let y=g?.[T].finishingPositionRange.loser,[E,A]=y??[0,0];return Q(E,(A||E)+1)}).flat().sort(Zt),{playoffRoundsRanges:S}=w$({playoffSourceRounds:f,roundProfile:g}),h=[...f,...l];return{playoffPositionsReturned:I,playedOffSourceRounds:l,playoffRoundsRanges:S,playoffSourceRounds:f,sourceRounds:h,roundProfile:g}}function w$({playoffSourceRounds:t,roundProfile:e}){return{playoffRoundsRanges:t.map(n=>{let o=e[n].finishingPositionRange.loser,[i,s]=o,a=Q(i,(s||i)+1);return{finishingPositionRange:o.join("-"),finishingPositions:a,roundNumber:n}})}}function Hp({drawDefinition:t,structureId:e}){if(!t)return{error:$};let{matchUps:r,matchUpsMap:n}=rr({inContext:!0,drawDefinition:t}),{positionsNotPlayedOff:o,positionsPlayedOff:i}=Pu({drawDefinition:t,matchUpsMap:n}),{structures:s}=In({drawDefinition:t}),a=s.filter(u=>!e&&u.stage!==Fe||u.structureId===e),c={};for(let u of a){let p=u?.structureId,m=L$({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 L$({playoffPositions:t,drawDefinition:e,structure:r,matchUps:n}){let o=r?.structureId,{links:i}=Ma({drawDefinition:e,structureId:o});if(r.structureType===de||r.structures){let l=Pt({structure:r})?.positionAssignments?.length,f=r.structures.length,g=(l??0)/f,I=i.source?.flatMap(({source:D})=>D?.finishingPositions??[])??[],S=Q(1,g+1).filter(D=>!I.includes(D)),h=n.find(D=>D.containerStructureId===o&&D.finishingPositionRange)?.finishingPositionRange?.winner||[0,1],T=i?.source.map(({target:D})=>D.structureId),{positionsPlayedOff:y=[],positionsNotPlayedOff:E=[]}=Pu({structureIds:T,drawDefinition:e}),A=new Set([...y,...E]),N=Q(h[0],h[1]+1).filter(D=>!A.has(D)),U=he(N,N.length/S.length),R=S.map((D,b)=>{let C=U[b],_=[Math.min(...C??[]),Math.max(...C??[])].join("-");return{finishingPosition:D,finishingPositions:C,finishingPositionRange:_}});return{positionsNotPlayedOff:N,playoffFinishingPositionRanges:R,finishingPositionsAvailable:S,finishingPositionsPlayedOff:I,positionsPlayedOff:y,groupCount:f,groupSize:g}}let s=i?.source?.filter(l=>l.linkCondition!==Bn).map(l=>l.source?.roundNumber)??[],a=i?.source?.filter(l=>l.linkCondition===Bn).map(l=>l.source?.roundNumber)??[],c=ME({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,S=n.filter(({roundNumber:T,structureId:y})=>y===I&&T===g),h=S.filter(({sides:T})=>T.find(y=>y.participantFed&&!y.participantId)).length;if(u&&h===S.length){u.push(l);let T=m?.[l]?.finishingPositionRange?.loser;if(T){let y=Math.min(...T),E=y+h,A=Q(y,E),N={finishingPositionRange:[y,E-1].join("-"),finishingPositions:A,roundNumber:l};p.push(N)}}}return u&&u.sort(Zt),p.sort((l,f)=>l.roundNumber-f.roundNumber),{playoffRounds:u,playoffRoundsRanges:p,error:d}}function v0({playoffGroups:t,drawDefinition:e,structureId:r}){if(!e)return{error:$};if(!_t(r)||!Array.isArray(t))return{error:O};let n=t.map(({finishingPositions:a})=>a).flat();return{positionRangeMap:Hp({drawDefinition:e,structureId:r}).playoffFinishingPositionRanges?.filter(a=>n.includes(a.finishingPosition))?.reduce((a,c)=>(a[c.finishingPosition]=c,a),{})}}function cf({playoffGroups:t,groupCount:e,groupSize:r}){if(!Array.isArray(t)||!t.length)return{error:O,valid:!1,info:"playoffGroups must be a non-empty array"};if(!e||e<1)return{error:O,valid:!1,info:"groupCount must be >= 1"};if(!r||r<1)return{error:O,valid:!1,info:"groupSize must be >= 1"};let n={};for(let a=1;a<=r;a++)n[a]=0;let o=e*r,i=0,s=!1;for(let a of t){let{finishingPositions:c,bestOf:u,rankBy:p,remainder:m}=a;if(m){let l=F$({hasBestOf:s,totalAvailable:o,totalClaimed:i});if(l.error)return l;i+=o-i;continue}if(!Array.isArray(c)||!c.length)return{error:O,valid:!1,info:"Each playoffGroup must have non-empty finishingPositions"};for(let l of c)if(l<1||l>r)return{error:O,valid:!1,info:`finishingPosition ${l} out of range [1, ${r}]`};let d=e*c.length;if(u===void 0){let l=k$({finishingPositions:c,groupCount:e,consumptionMap:n});if(l?.error)return l;i+=d}else{let l=G$({finishingPositions:c,guaranteedCount:d,consumptionMap:n,totalAvailable:o,groupCount:e,groupSize:r,bestOf:u,rankBy:p});if(l?.error)return l;s=!0,i+=u}}return i>o?{info:`Total claimed participants (${i}) exceeds available (${o})`,error:Jo,valid:!1}:{valid:!0,consumptionMap:n}}function F$({hasBestOf:t,totalAvailable:e,totalClaimed:r}){if(!t)return{error:Jo,valid:!1,info:"A remainder group must appear after at least one bestOf group"};let n=e-r;return n<2?{error:Jo,valid:!1,info:`Remainder group would have insufficient participants (${n}), minimum 2 required`}:{}}function k$({finishingPositions:t,groupCount:e,consumptionMap:r}){for(let n of t){let o=e-r[n];if(o<2)return{error:Jo,valid:!1,info:`finishingPosition ${n} has insufficient remaining participants (${o}) for a standard playoff group (minimum 2 required)`};r[n]+=o}return{}}function G$({finishingPositions:t,guaranteedCount:e,consumptionMap:r,totalAvailable:n,groupCount:o,groupSize:i,bestOf:s,rankBy:a}){if(typeof s!="number"||s<1)return{error:O,valid:!1,info:"bestOf must be a positive number"};if(s<e)return{info:`bestOf (${s}) cannot be less than guaranteed count (${e}) for finishingPositions [${t}] with ${o} groups`,error:Jo,valid:!1};if(s>n)return{info:`bestOf (${s}) exceeds total available participants (${n})`,error:Jo,valid:!1};if(a!==void 0&&a!==du)return{info:`Unsupported rankBy value: '${a}'. Currently only '${du}' is supported.`,error:O,valid:!1};for(let u of t)r[u]+=o;let c=s-e;if(c>0){let u=V$({remainder:c,finishingPositions:t,groupCount:o,groupSize:i,consumptionMap:r,bestOf:s});if(u?.error)return u}return{}}function V$({remainder:t,finishingPositions:e,groupCount:r,groupSize:n,consumptionMap:o,bestOf:i}){let s=t,a=[...e].sort(Zt),c=Math.max(...a)+1;for(;s>0&&c<=n;){let u=r-o[c],p=Math.min(s,u);o[c]+=p,s-=p,c++}return s>0?{info:`bestOf (${i}) requires more participants than available from remaining finishing positions`,error:Jo,valid:!1}:{}}function vE(t){let{finishingPositionOffset:e=0,playoffAttributes:r,stageSequence:n=1,staggeredEntry:o,structureName:i,stage:s=H,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?Pi(l):Tr(l),g=lr({structureName:i||r?.["0"]?.name||xe(H),structureId:c||d?.pop(),stageSequence:n,matchUpType:a,matchUps:f,stage:s}),I=[g],S=[];if(p>2){let h=p/2,{matchUps:T}=Tr({finishingPositionOffset:e+h,idPrefix:u&&`${u}-c`,drawSize:h,matchUpType:a,isMock:m}),y=xe(me),E=r?.["0-1"]?.name??t.consolationStructureName??(i?`${i} ${y}`:y),A=lr({structureName:E,matchUps:T,structureId:d?.pop(),stage:me,stageSequence:1,matchUpType:a});I.push(A);let N={linkType:ir,source:{roundNumber:1,structureId:g.structureId},target:{roundNumber:1,feedProfile:qe,structureId:A.structureId}};S.push(N)}return{...P,structures:I,links:S}}function OE({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 Q(1+e,n+1+e).map(p=>{let m=u?.[p-1]?u[p-1]:p%2&&qe||Oi,d=p-e<=2?p-e:(p-e-2)*2+2,l={linkType:ir,source:{roundNumber:p,structureId:r.structureId},target:{feedProfile:m,roundNumber:d,structureId:t.structureId}},f=c[p-1];return f&&(l.target.groupedOrder=f),je()&&(l.source.structureName=r.structureName,l.target.structureName=t.structureName),p===2&&i&&(l.linkCondition=Bn,l.target.feedProfile=qe),a.includes(d)?l:void 0}).filter(Boolean)}function _E(t){let{playoffStructureNameBase:e,finishingPositionOffset:r,stageSequence:n=1,playoffAttributes:o,structureNameMap:i,staggeredEntry:s,stage:a=H,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?Pi(f):Tr(f),S=t.structureName??o?.["0"]?.name??xe(H),h=Wo({structureId:u||l?.pop(),structureName:S,stageSequence:n,matchUpType:c,matchUps:g,stage:a}),T=[h],y=[];if(p>2){let N=[0,2].slice(0,p/16).map((U,R)=>{let D=R+1,{consolationStructure:b}=B$({idPrefix:m&&`${m}-c${R}`,structureId:l?.pop(),playoffStructureNameBase:e,playoffAttributes:o,structureNameMap:i,stageSequence:D,roundOffset:U,matchUpType:c,drawSize:p,isMock:d,index:R,uuids:l});T.push(b);let C=OE({consolationStructure:b,roundsCount:2,mainStructure:h,roundOffset:U});return{consolationStructure:b,links:C}}).map(U=>U.links).flat();if(y.push(...N),p>=4&&p<=16||p>32){let{matchUps:U}=Tr({idPrefix:m&&`${m}-p3t4`,finishingPositionOffset:2,drawSize:2,matchUpType:c,isMock:d}),R=o?.["3-4"]?.name??xe(Vt),D=i?.[R]||R,b=e?`${e} ${D}`:D,C=Wo({structureId:l?.pop(),matchUps:U,stageSequence:2,stage:Vt,structureName:b,matchUpType:c}),_={linkType:ir,source:{roundNumber:I-1,structureId:h.structureId},target:{structureId:C.structureId,feedProfile:qe,roundNumber:1}};T.push(C),y.push(_)}}return{structures:T,links:y,...P}}function B$({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}=Pi({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||`${xe(me)} ${p+1}`,S=n?.[I]||I,h=t?`${t} ${S}`:S;return{consolationStructure:Wo({matchUps:l,stage:me,structureName:h,stageSequence:e,matchUpType:i,structureId:s}),consolationRoundsCount:f}}function Nu(t){let{finishingPositionOffset:e,stageSequence:r=1,playoffAttributes:n,feedsFromFinal:o,staggeredEntry:i,structureName:s,stage:a=H,structureId:c,matchUpType:u,skipRounds:p,feedRounds:m,idPrefix:d,drawSize:l,isMock:f,uuids:g,fmlc:I}=t,S=t.feedPolicy||t.policyDefinitions?.[ou]||t.appliedPolicies?.[ou],h={finishingPositionOffset:e,matchUpType:u,skipRounds:p,drawSize:l,idPrefix:d,isMock:f,uuids:g},{matchUps:T}=i?Pi(h):Tr(h),y=lr({structureName:s||n?.["0"]?.name||xe(H),structureId:c||g?.pop(),stageSequence:r,matchUpType:u,matchUps:T,stage:a}),E=[y],A=[],N=l/2,{matchUps:U,roundsCount:R}=Pi({finishingPositionOffset:N,idPrefix:d&&`${d}-c`,isConsolation:!0,feedsFromFinal:o,baseDrawSize:N,matchUpType:u,feedRounds:m,skipRounds:p,isMock:f,uuids:g,fmlc:I});if(l>2){let D=n?.["0-1"]?.name??xe(me),b=t.playoffStructureNameBase?`${t.playoffStructureNameBase} ${D}`:D,C=lr({matchUps:U,structureId:g?.pop(),stage:me,stageSequence:1,structureName:b,matchUpType:u});E.push(C);let _=OE({consolationStructure:C,mainStructure:y,roundsCount:R,feedPolicy:S,fmlc:I});A.push(..._)}return{...P,structures:E,links:A}}var H$=new Set([ds,Ls,ru,eu,Pa,Na]),W$=new Set([ms,mp,Hm]);function uf({requireSequential:t=!0,playoffMatchUpFormat:e,playoffAttributes:r,sourceStructureId:n,policyDefinitions:o,stageSequence:i,drawDefinition:s,playoffGroups:a,matchUpType:c,feedPolicy:u,groupCount:p,groupSize:m,idPrefix:d,isMock:l,uuids:f}={}){let g=u||o?.[ou],I="processPlayoffGroups",S=0,h=[],T=[],y=[];if(a?.some(b=>b.bestOf!==void 0||b.remainder)&&m){let b=cf({playoffGroups:a,groupCount:p,groupSize:m});if(!b.valid)return M({result:{error:b.error||Jo},context:{info:b.info},stack:I})}let A=a?.filter(b=>!b.remainder),{error:N,positionRangeMap:U}=v0({structureId:n,playoffGroups:A,drawDefinition:s});if(N)return M({result:{error:N},stack:I});if(!(!U||A?.every(b=>{let{finishingPositions:C=[]}=b;if(!C.length)return!1;let _=[...C].sort(Zt).map((v,w)=>(C[w+1]||v)-v).every(v=>v<2);return(!t||_)&&C.every(v=>U[v])})))return M({context:{validFinishingPositions:Object.values(U)},result:{error:O},stack:I});let D=0;for(let b of a){let{bestOf:C,rankBy:_,remainder:v}=b;if(v){let W=Y$({finishingPositionOffset:S,playoffMatchUpFormat:e,sourceStructureId:n,stageSequence:i,totalClaimed:D,playoffGroup:b,matchUpType:c,groupCount:p,groupSize:m,idPrefix:d,isMock:l,uuids:f});T.push(W.structure),y.push(W.link),h.push(W.target),S+=W.remainderCount,D+=W.remainderCount;continue}let w=b.finishingPositions??[],L=U&&w.flatMap(W=>U[W]?.finishingPositions??[]),F=C??p*w.length;D+=F;let x=Si(F),k=x===2&&zr||b.drawType||zr;L&&(S=Math.min(...L)-1);let G=J$({positionsPlayedOff:L,playoffGroup:b}),B={...{addNameBaseToAttributeName:b.addNameBaseToAttributeName,playoffStructureNameBase:b.playoffStructureNameBase,finishingPositionNaming:b.finishingPositionNaming,finishingPositionLimit:b.finishingPositionLimit,structureId:b.structureId??f?.pop(),playoffAttributes:b.playoffAttributes,structureNameMap:b.structureNameMap,sequenceLimit:b.sequenceLimit,structureName:G},idPrefix:d&&`${d}-po`,appliedPolicies:o,finishingPositionOffset:S,stage:Vt,stageSequence:i,matchUpType:c,drawSize:x,isMock:l,uuids:f},z=({playoffStructures:W,playoffLinks:K})=>{let[Y]=W,J=Uu({playoffStructureId:Y.structureId,finishingPositions:w,sourceStructureId:n,bestOf:C,rankBy:_});y.push(J,...K),T.push(...W),h.push({structureId:Y.structureId,finishingPositions:w}),S+=F};if(k===zr)j$({finishingPositionOffset:S,playoffMatchUpFormat:e,finishingPositions:w,sourceStructureId:n,participantsInDraw:F,stageSequence:i,playoffGroup:b,structureName:G,matchUpType:c,drawSize:x,idPrefix:d,bestOf:C,rankBy:_,isMock:l,uuids:f,finishingPositionTargets:h,structures:T,links:y}),S+=F;else if(W$.has(k)){let W=q$({finishingPositionOffset:S,finishingPositions:w,sourceStructureId:n,playoffAttributes:r,playoffDrawType:k,stageSequence:i,playoffGroup:b,drawSize:x,idPrefix:d,bestOf:C,rankBy:_,isMock:l,uuids:f,finishingPositionTargets:h,structures:T,links:y});if(W)return W;S+=F}else if(H$.has(k))$$({finishingPositionOffset:S,finishingPositions:w,sourceStructureId:n,playoffDrawType:k,playoffGroup:b,structureName:G,matchUpType:c,drawSize:x,idPrefix:d,bestOf:C,rankBy:_,isMock:l,uuids:f,feedPolicy:g,finishingPositionTargets:h,structures:T,links:y}),S+=F;else if(k===Hr){let{structures:W,links:K}=Ec({...B,structureOptions:b.structureOptions||{groupSize:4}});z({playoffStructures:W,playoffLinks:K})}else if(k===Vm){let{structures:W,links:K}=vE(B);z({playoffStructures:W,playoffLinks:K})}else if(k===yI){let{structures:W,links:K}=_E(B);z({playoffStructures:W,playoffLinks:K})}else if(k===Bm){let W=K$({finishingPositionTargets:h,participantsInDraw:F,sourceStructureId:n,finishingPositions:w,drawDefinition:s,playoffGroup:b,structures:T,params:B,links:y,stack:I});if(W)return W}else k===hi&&X$({finishingPositions:w,stageSequence:i,structureName:G,playoffGroup:b,groupSize:m,uuids:f,updateStructureAndLinks:z})}return{finishingPositionTargets:h,positionRangeMap:U,structures:T,links:y}}function Y$({finishingPositionOffset:t,playoffMatchUpFormat:e,sourceStructureId:r,stageSequence:n,totalClaimed:o,playoffGroup:i,matchUpType:s,groupCount:a,groupSize:c,idPrefix:u,isMock:p,uuids:m}){let l=a*c-o,f=Si(l),g=Array.from({length:c},(y,E)=>E+1),I=i.structureName||"Remainder Playoff",{matchUps:S}=Tr({finishingPositionLimit:t+l,idPrefix:u&&`${u}-po`,finishingPositionOffset:t,matchUpType:s,drawSize:f,isMock:p,uuids:m}),h=lr({structureId:i.structureId??m?.pop(),matchUpFormat:e,stage:Vt,structureName:I,stageSequence:n,matchUps:S}),T=Uu({playoffStructureId:h.structureId,finishingPositions:g,sourceStructureId:r,remainder:!0});return{structure:h,target:{structureId:h.structureId,finishingPositions:g},remainderCount:l,link:T}}function j$({finishingPositionOffset:t,playoffMatchUpFormat:e,finishingPositions:r,sourceStructureId:n,participantsInDraw:o,stageSequence:i,playoffGroup:s,structureName:a,matchUpType:c,drawSize:u,idPrefix:p,bestOf:m,rankBy:d,isMock:l,uuids:f,finishingPositionTargets:g,structures:I,links:S}){let{matchUps:h}=Tr({finishingPositionLimit:t+o,idPrefix:p&&`${p}-po`,finishingPositionOffset:t,matchUpType:c,drawSize:u,isMock:l,uuids:f}),T=lr({structureId:s.structureId??f?.pop(),matchUpFormat:e,stage:Vt,structureName:a,stageSequence:i,matchUps:h});I.push(T);let y=Uu({playoffStructureId:T.structureId,finishingPositions:r,sourceStructureId:n,bestOf:m,rankBy:d});S.push(y),g.push({structureId:T.structureId,finishingPositions:r})}function q$({finishingPositionOffset:t,finishingPositions:e,sourceStructureId:r,playoffAttributes:n,playoffDrawType:o,stageSequence:i,playoffGroup:s,drawSize:a,idPrefix:c,bestOf:u,rankBy:p,isMock:m,uuids:d,finishingPositionTargets:l,structures:f,links:g}){let I={playoffAttributes:s.playoffAttributes??n,playoffStructureNameBase:s.playoffStructureNameBase,structureId:s.structureId??d?.pop(),structureName:s.structureName,idPrefix:c&&`${c}-po`,addNameBaseToAttributeName:!0,finishingPositionOffset:t,stage:Vt,roundOffset:0,stageSequence:i,drawSize:a,isMock:m,uuids:d};o===ms?Object.assign(I,{playoffAttributes:s?.playoffAttributes??n??EI,roundOffsetLimit:3}):o===mp&&Object.assign(I,{playoffAttributes:s?.playoffAttributes??n??AI,roundOffsetLimit:2});let S=Au(I);if(S.error)return S;if(S.links?.length&&g.push(...S.links),S.structures?.length&&f.push(...S.structures),f.sort(ki),S.structureId){let h=Uu({playoffStructureId:S.structureId,finishingPositions:e,sourceStructureId:r,bestOf:u,rankBy:p});g.push(h),l.push({structureId:S.structureId,finishingPositions:e})}}function $$({finishingPositionOffset:t,finishingPositions:e,sourceStructureId:r,playoffDrawType:n,playoffGroup:o,structureName:i,matchUpType:s,feedPolicy:a,drawSize:c,idPrefix:u,bestOf:p,rankBy:m,isMock:d,uuids:l,finishingPositionTargets:f,structures:g,links:I}){let S=[l?.pop(),l?.pop()],h={playoffStructureNameBase:o.playoffStructureNameBase,structureId:o.structureId??l?.pop(),playoffAttributes:o.playoffAttributes,idPrefix:u&&`${u}-po`,finishingPositionOffset:t,uuids:S,stage:Vt,structureName:i,matchUpType:s,feedPolicy:a,drawSize:c,isMock:d},T={[ds]:{fmlc:!0,feedRounds:1},[Na]:{feedRounds:1},[ru]:{feedsFromFinal:3},[eu]:{feedsFromFinal:2},[Pa]:{feedsFromFinal:1}};Object.assign(h,T[n]??{});let{structures:y,links:E}=Nu(h),[A]=y,N=Uu({playoffStructureId:A.structureId,finishingPositions:e,sourceStructureId:r,bestOf:p,rankBy:m});I.push(N,...E),g.push(...y),f.push({structureId:A.structureId,finishingPositions:e})}function K$({finishingPositionTargets:t,participantsInDraw:e,sourceStructureId:r,finishingPositions:n,drawDefinition:o,playoffGroup:i,structures:s,params:a,links:c,stack:u}){if(e!==4)return M({result:{error:Jo},context:{info:"PAGE_PLAYOFF requires exactly 4 participants"},stack:u});let p=o?.structures?.find(d=>d.structureId===r);return p&&!p.structures&&!p.structureType?z$({finishingPositionTargets:t,sourceStructureId:r,drawDefinition:o,playoffGroup:i,structures:s,params:a,links:c}):Q$({finishingPositionTargets:t,sourceStructureId:r,finishingPositions:n,playoffGroup:i,structures:s,params:a,links:c,stack:u})}function z$({finishingPositionTargets:t,sourceStructureId:e,drawDefinition:r,playoffGroup:n,structures:o,params:i,links:s}){let a=n.structureName,{matchUpType:c,isMock:u,uuids:p,idPrefix:m,finishingPositionOffset:d=0}=i,l=Vt,{matchUps:f}=Tr({finishingPositionOffset:d+2,idPrefix:m&&`${m}-el`,drawSize:2,matchUpType:c,isMock:u,uuids:p}),g=lr({structureName:a?`${a} 3-4 Playoff`:"3-4 Playoff",structureAbbreviation:"EL",structureId:p?.pop(),matchUps:f,stageSequence:1,matchUpType:c,stage:l}),{matchUps:I}=Tr({finishingPositionOffset:d+1,idPrefix:m&&`${m}-q2`,drawSize:2,matchUpType:c,isMock:u,uuids:p}),S=lr({structureName:a?`${a} Playoff Qualifier`:"Playoff Qualifier",structureAbbreviation:"Q2",structureId:p?.pop(),matchUps:I,stageSequence:2,matchUpType:c,stage:l}),{matchUps:h}=Tr({finishingPositionOffset:d,idPrefix:m&&`${m}-fi`,drawSize:2,matchUpType:c,isMock:u,uuids:p}),T=lr({structureName:a?`${a} Final`:"Playoff Final",structureAbbreviation:"F",structureId:p?.pop(),matchUps:h,stageSequence:3,matchUpType:c,stage:l});o.push(g,S,T);let E=r?.structures?.find(U=>U.structureId===e)?.matchUps||[],A=E.length?Math.max(...E.map(U=>U.roundNumber)):1,N=A-1;s.push({linkType:ir,source:{structureId:e,roundNumber:N},target:{feedProfile:qe,roundNumber:1,structureId:g.structureId}},{linkType:Er,source:{structureId:e,roundNumber:A},target:{feedProfile:qe,roundNumber:1,structureId:T.structureId}},{linkType:ir,source:{structureId:e,roundNumber:A},target:{feedProfile:qe,roundNumber:1,structureId:S.structureId}},{linkType:Er,source:{structureId:g.structureId,roundNumber:1},target:{feedProfile:qe,roundNumber:1,structureId:S.structureId}},{linkType:Er,source:{structureId:S.structureId,roundNumber:1},target:{feedProfile:qe,roundNumber:1,structureId:T.structureId}}),t.push({structureId:g.structureId,finishingPositions:[3,4]})}function Q$({finishingPositionTargets:t,sourceStructureId:e,finishingPositions:r,playoffGroup:n,structures:o,params:i,links:s,stack:a}){let c=CE({...i,structureName:n.structureName});if(c.error)return M({result:c,stack:a});o.push(...c.structures),s.push(...c.links);let u=c.structures.find(m=>m.structureAbbreviation==="Q1"),p=c.structures.find(m=>m.structureAbbreviation==="EL");if(r.length>=2&&u&&p){let m=Math.ceil(r.length/2),d=r.slice(0,m),l=r.slice(m);s.push(Uu({playoffStructureId:u.structureId,finishingPositions:d,sourceStructureId:e}),Uu({playoffStructureId:p.structureId,finishingPositions:l,sourceStructureId:e})),t.push({structureId:u.structureId,finishingPositions:d},{structureId:p.structureId,finishingPositions:l})}else u&&p&&(s.push(Uu({playoffStructureId:u.structureId,finishingPositions:r,sourceStructureId:e}),Uu({playoffStructureId:p.structureId,finishingPositions:r,sourceStructureId:e})),t.push({structureId:u.structureId,finishingPositions:r},{structureId:p.structureId,finishingPositions:r}))}function X$({finishingPositions:t,stageSequence:e,structureName:r,playoffGroup:n,groupSize:o,uuids:i,updateStructureAndLinks:s}){!t.length&&o&&t.push(...Array.from({length:o},(c,u)=>u+1));let a=lr({structureId:n.structureId??i?.pop(),structureName:n.structureName||r||"Playoff",finishingPosition:Ol,stage:Vt,stageSequence:e,matchUps:[]});s({playoffStructures:[a],playoffLinks:[]})}function J$({positionsPlayedOff:t,playoffGroup:e}){let r=t&&`${Math.min(...t)}-${Math.max(...t)}`;return e.structureName||r&&e.playoffAttributes?.[r]?.name||e.playoffAttributes?.["0"]?.name}function Uu({playoffStructureId:t,finishingPositions:e,sourceStructureId:r,remainder:n,bestOf:o,rankBy:i}){let s={structureId:r,finishingPositions:e};return o!==void 0&&(s.bestOf=o,s.rankBy=i||du),n&&(s.remainder=!0),{linkType:fn,source:s,target:{structureId:t,feedProfile:ln,roundNumber:1}}}function O0(t){let{drawDefinition:e,structureOptions:r,requireSequential:n}=t,o={structureName:xe(H),...t,stage:H},{structures:i,groupCount:s,groupSize:a}=Ec(o);if(s<1)return{error:Jo};let c=r?.playoffGroups||[{finishingPositions:[1],structureName:xe(Vt)}],[u]=i,{structures:p,links:m}=uf({sourceStructureId:u.structureId,requireSequential:n,drawDefinition:e,playoffGroups:c,groupCount:s,groupSize:a,...t});return p&&i.push(...p),{...P,structures:i,links:m}}function _0({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?qe:Oi,f=1+m;return{linkType:ir,source:{roundNumber:f,structureId:t.structureId},target:{feedProfile:l,roundNumber:p,structureId:e.structureId}}}),c={linkType:Er,source:{roundNumber:s,structureId:e.structureId},target:{feedProfile:qe,roundNumber:i,structureId:t.structureId}},u=[{linkType:Er,source:{roundNumber:i,structureId:t.structureId},target:{feedProfile:qe,roundNumber:1,structureId:r.structureId}},{linkType:ir,source:{roundNumber:i,structureId:t.structureId},target:{feedProfile:qe,roundNumber:1,structureId:r.structureId}}];return[...a,c,...u]}function x0({structureName:t,matchUpType:e,idPrefix:r,drawSize:n,isMock:o,uuids:i}){let s=[],{matchUps:a}=Pi({linkFedFinishingRoundNumbers:[1],drawSize:n+1,matchUpType:e,idPrefix:r,isMock:o}),c=Wo({structureName:t||xe(H),structureId:i?.pop(),stageSequence:1,stage:H,matchUpType:e,matchUps:a});s.push(c);let u=n/2,{matchUps:p}=Pi({finishingPositionOffset:u,idPrefix:r&&`${r}-c`,drawSize:n-1,isConsolation:!0,matchUpType:e,isMock:o,uuids:i}),m=Wo({structureName:xe(fR),matchUps:p,structureId:i?.pop(),stage:me,stageSequence:2,matchUpType:e});s.push(m);let{matchUps:d}=Tr({idPrefix:r&&`${r}-p1t2`,drawSize:2,matchUpType:e,isMock:o}),l=Wo({structureName:xe(lR),matchUps:d,structureId:i?.pop(),stageSequence:3,stage:Vt,matchUpType:e});s.push(l);let f=_0({mainStructure:c,consolationStructure:m,deciderStructure:l});return{structures:s,links:f,...P}}function xE(t){let{qualifyingRoundNumber:e,finishingPositionOffset:r,qualifyingPositions:n,matchUpType:o,idPrefix:i,drawSize:s,isMock:a,uuids:c}=t;if(!yt(s)||s<2)return{matchUps:[],roundsCount:0};if(en(s))return Tr(t);let u=wE(s),p=u.shift(),m=Q(1,(p?.participantsCount||0)+1).map(I=>({drawPosition:I})),d=[],l=1;({matchUps:d}=cd({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 S=I.participantsCount/2,h=Q(1,S+1);n&&S===n&&(f=l-1);let T=h.map(y=>{let E=sf({roundPosition:y,roundNumber:l,idPrefix:i,uuids:c});return{roundPosition:y,roundNumber:l,matchUpId:E}});d.push(...T),l++}let g=l-1;return d=hc({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 wE(t){let e=st(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 Kb(t){let{finishingPositionOffset:e=0,playoffAttributes:r=PI,stageSequence:n=1,exitProfile:o="0",roundOffsetLimit:i=3,roundOffset:s=0,childStage:a=Vt,stage:c=H,matchUpType:u,structureId:p,drawSize:m,idPrefix:d,isMock:l,uuids:f}=t;if(!(!r||r[o])||m<2)return{};let I=[],S=[],h=r[o],T=t.structureName||h?.name||`${e+1}-${e+m}`,y=h?.abbreviation,E=p??h?.structureId??f?.pop(),{matchUps:A}=xE({finishingPositionOffset:e,matchUpType:u,drawSize:m,idPrefix:d&&`${d}-${T}-RP`,isMock:l,uuids:f}),N=lr({structureAbbreviation:y,structureName:T,stageSequence:n,matchUpType:u,roundOffset:s,structureId:E,matchUps:A,stage:c});I.push(N);let U=Z$(m),R=U.length,D=Math.min(i-s,R);for(let b=0;b<D;b++){let{roundNumber:C,childSize:_}=U[b];if(_<2)continue;let v=e+t3(m,C),w=`${o}-${C}`,L=Kb({finishingPositionOffset:v,exitProfile:w,roundOffset:s+C,stageSequence:n+1,drawSize:_,stage:a,playoffAttributes:r,roundOffsetLimit:i,childStage:a,matchUpType:u,idPrefix:d,isMock:l,uuids:f});if(L.structureId&&N.structureId){let F={linkType:ir,source:{roundNumber:C,structureId:N.structureId},target:{roundNumber:1,feedProfile:qe,structureId:L.structureId}};S.push(F)}L.structures?.length&&I.push(...L.structures),L.links?.length&&S.push(...L.links)}return{structureId:N.structureId,structures:I,links:S,...P}}function Z$(t){if(en(t)){let n=Math.ceil(Math.log(t)/Math.log(2)),o=[];for(let i=1;i<=n;i++){let s=t/Math.pow(2,i);s>=2&&o.push({roundNumber:i,childSize:s})}return o}let e=wE(t),r=[];for(let n=0;n<e.length-1;n++){let o=e[n],i=o.participantsCount/2,s=o.preFeedRound?i-1:i;s>=2&&r.push({roundNumber:n+1,childSize:s})}return r}function t3(t,e){if(en(t))return t/Math.pow(2,e);let r=wE(t);return e<r.length?Math.ceil(r[e].participantsCount/2):1}function pf(t){let{playoffAttributes:e,stageSequence:r=1,stage:n=H,tieFormat:o,matchUpType:i,drawSize:s,uuids:a}=t,c=()=>!t.isMock&&!t.idPrefix?void 0:`${t.drawDefinition.drawId}-s-0`,u=t.structureId||c()||a?.pop(),p=t.appliedPolicies??It(t),m=t.policyDefinitions?.[ou]||p?.[ou];t.skipRounds=t.skipRounds||s<=4&&(m?.feedFromMainFinal?0:1)||0;let d=t.structureName??e?.["0"]?.name??xe(H),l=()=>{let{matchUps:g}=Tr(t);return{structures:[lr({stageSequence:r,structureName:d,matchUpType:i,structureId:u,tieFormat:o,matchUps:g,stage:n})],links:[],...P}};return{generators:{[hi]:()=>({structures:[lr({finishingPosition:uo,stageSequence:r,structureName:d,matchUps:[],matchUpType:i,structureId:u,stage:n})],links:[],...P}),[lp]:()=>{let g=lr({finishingPosition:uo,stageSequence:r,structureName:d,matchUps:[],matchUpType:i,structureId:u,stage:n});return s&&(g.positionAssignments=Array.from({length:s},(I,S)=>({drawPosition:S+1}))),{structures:[g],links:[],...P}},[ws]:()=>{let{matchUps:g}=xE(t);return{structures:[lr({stageSequence:r,structureName:d,matchUpType:i,structureId:u,matchUps:g,stage:n})],links:[],...P}},[zr]:()=>l(),[dp]:()=>x0(t),[ms]:()=>Au({...t,childStage:Vt,roundOffsetLimit:3,playoffAttributes:e??EI}),[mp]:()=>Au({...t,childStage:Vt,roundOffsetLimit:2,playoffAttributes:e??AI}),[nc]:()=>Kb({...t,childStage:Vt,roundOffsetLimit:t.roundOffsetLimit??3,playoffAttributes:e??PI}),[Bm]:()=>CE(t),[Hm]:()=>Au({...t,childStage:Vt}),[rc]:()=>{let{matchUps:g}=Pi({drawSize:s,uuids:a,matchUpType:i});return{structures:[lr({stageSequence:r,structureName:d,matchUpType:i,structureId:u,stage:H,tieFormat:o,matchUps:g})],links:[],...P}},[Vm]:()=>vE(t),[ds]:()=>Nu({...t,feedRounds:1,fmlc:!0}),[dR]:()=>Nu({...t,feedRounds:1}),[hy]:()=>Nu({...t,feedsFromFinal:1}),[Ty]:()=>Nu({...t,feedsFromFinal:2}),[yy]:()=>Nu({...t,feedsFromFinal:3}),[Ls]:()=>Nu(t),[TI]:()=>_E(t),[Hr]:()=>Ec(t),[Wr]:()=>O0(t)}}}function LE({element:t}){if(!t)return{error:O};if(!t.timeItems)return{};if(!Array.isArray(t.timeItems))return{error:O};let e=(r,n)=>(o,i)=>(i[r]&&(o[i[r]]=i[n]),o);return t.timeItems.reduce(e("itemType","itemValue"),{})}function no(t){let{duplicateValues:e=!0,creationTime:r=!0,removePriorValues:n,timeItem:o}=t;if(!o)return{error:Jg};let i=qy(t);if(i.error)return i;if(!(Tt(o)&&_t(o.itemType)&&Object.keys(o).includes("itemValue")))return{error:Xg};if(o.itemDate&&typeof o.itemDate=="string"&&!Me(o.itemDate))return{error:ae};if(!i.timeItems)i.timeItems=[];else if(e3({element:i,duplicateValues:e,timeItem:o}))return{...P};if(o.itemSubTypes&&!o.itemSubTypes.length&&delete o.itemSubTypes,r){let c=new Date().toISOString();Object.assign(o,{createdAt:c})}return n&&(i.timeItems=i.timeItems.filter(({itemType:c})=>o.itemType!==c)),n&&!o.itemValue||i.timeItems.push(o),{...P}}function e3({element:t,duplicateValues:e,timeItem:r}){let{itemType:n,itemSubTypes:o,itemValue:i}=r,s=n&&Jr({itemSubTypes:o,itemType:n,element:t})?.timeItem;return s&&JSON.stringify(s?.itemValue)===JSON.stringify(i)&&!e}function hS({creationTime:t=!0,removePriorValues:e,tournamentRecord:r,duplicateValues:n,participantId:o,timeItem:i}){if(!r)return{error:j};if(!o)return{error:He};let s=Ao({tournamentRecord:r,participantId:o});return s.error?s:no({element:s.participant,removePriorValues:e,duplicateValues:n,creationTime:t,timeItem:i})}function Du(t){let{removePriorValues:e,tournamentRecord:r,duplicateValues:n,creationTime:o,timeItem:i}=t;if(!r)return{error:j};let s=no({element:r,removePriorValues:e,duplicateValues:n,creationTime:o,timeItem:i});if(s.error)return s;let a=LE({element:r});return at({payload:{parentOrganisation:r.parentOrganisation,tournamentId:r.tournamentId,timeItemValues:a},topic:ii}),s}function Ps(t){let{removePriorValues:e,duplicateValues:r,creationTime:n,timeItem:o,event:i}=t;return i?no({removePriorValues:e,duplicateValues:r,element:i,creationTime:n,timeItem:o}):{error:Gr}}function TS(t){return ES({...t,itemType:"attachConsolationStructures"})}function yS(t){return ES({...t,itemType:"attachPlayoffStructures"})}function ES({itemType:t="attachStructures",matchUpModifications:e,tournamentRecord:r,drawDefinition:n,structures:o,links:i=[],event:s}){let a="attachStructures";if(!n)return{error:$};if(!Array.isArray(o)||!Array.isArray(i))return M({result:{error:O},stack:a});let c=S=>[S.source.structureId,S.source.roundNumber||S.source.finishingPositions?.join("|"),S.target.roundNumber].join("|"),u=n.links?.map(c);if(i.some(S=>{let h=c(S);return u?.includes(h)}))return M({result:{error:oI},info:"playoff structure exists",stack:a});if(i.length){let S=new Set([...n.structures?.map(({structureId:T})=>T)??[],...o.map(({structureId:T})=>T)]),h=i.filter(T=>!S.has(T.source.structureId)||!S.has(T.target.structureId));if(h.length)return M({result:{error:Do},info:"links reference non-existent structures",context:{invalidLinks:h.map(T=>({source:T.source.structureId,target:T.target.structureId}))},stack:a})}i.length&&n.links?.push(...i);let m=new Set(o.map(({structureId:S})=>S)),d=n.structures?.map(({structureId:S})=>S);n.structures=(n.structures??[]).map(S=>m.has(S.structureId)?o.find(({structureId:h})=>h===S.structureId):S);let l=o?.filter(({structureId:S})=>!d?.includes(S));l.length&&n.structures.push(...l),Ts({drawDefinition:n});let f=o.map(S=>ht({structure:S})?.matchUps??[]).flat();ko({tournamentId:r?.tournamentId,eventId:s?.eventId,drawDefinition:n,matchUps:f});let g=o.map(({structureId:S})=>S);if(Ft({drawDefinition:n,structureIds:g}),e?.length){let S={};e.forEach(T=>{let y=T.matchUp?.matchUpId;y&&(S[y]=T)});let h=T=>{T.matchUps.forEach(y=>{if(S[y.matchUpId]){let{tieMatchUps:E,...A}=S[y.matchUpId].matchUp;if(Object.assign(y,A),E?.length){let N={};E.forEach(U=>S[U.matchUpId]=U),y.tieMatchUps.forEach(U=>Object.assign(U,N[U.matchUpId]))}S[y.matchUpId].matchUp=y,gt(S[y.matchUpId])}})};n.structures.forEach(T=>{if(d?.includes(T.structureId))if(T.structures)for(let y of T.structures)h(y);else h(T)})}let I=l.map(Fr("structureId"));if(r){let h={itemValue:{structureIds:g,drawId:n.drawId},itemType:t};no({element:r,timeItem:h})}return{...P,addedStructureIds:I}}function zb({structureName:t,structureType:e=hi,drawSize:r=2,matchUpFormat:n,matchUpType:o}){let i={stage:me,stageSequence:1,structureName:t||xe(me),drawSize:r,matchUpFormat:n,matchUpType:o},{generators:s,error:a}=pf(i);if(a)return{error:a};let c=s[e];if(!c)return{error:Qu};let u=c();return u.error?u:{...P,structures:u.structures}}function Qb({drawDefinition:t,structureId:e,structureName:r,structureType:n=hi,drawSize:o=2,matchUpFormat:i,matchUpType:s,links:a=[]}){if(!t)return{error:$};if(e||(e=t.structures?.find(d=>d.stage===H)?.structureId),!e)return{error:bi};let{structure:c}=tt({drawDefinition:t,structureId:e});if(!c)return{error:bi};let u=zb({structureName:r,structureType:n,drawSize:o,matchUpFormat:i,matchUpType:s||t.matchUpType});if(u.error)return u;let p=u.structures?.[0];if(!p)return{error:Qu};let m=a.map(d=>({linkType:ir,source:{roundNumber:d.sourceRoundNumber,structureId:e},target:{roundNumber:d.targetRoundNumber,feedProfile:qe,structureId:p.structureId}}));return TS({drawDefinition:t,structures:[p],links:m})}function Xb({drawDefinition:t,participantId:e,preferences:r}){if(!t)return{error:$};if(!e)return{error:Vr};if(!Array.isArray(r))return{error:O};let{extension:n}=ot({element:t,name:wi});if(!n?.value)return{error:fe,info:"No active draft found"};let o=n.value;if(o.status==="COMPLETE")return{error:O,info:"Draft is already complete"};if(!o.tiers?.find(u=>u.participantIds?.includes(e)))return{error:Vr,info:"Participant not in any draft tier"};let s=new Set(o.unassignedDrawPositions);for(let u of r)if(!s.has(u))return{error:is,info:`Draw position ${u} is not available`};let a=o.preferencesCount??3,c=r.slice(0,a);return o.preferences[e]=c,o.status==="SEEDS_PLACED"&&(o.status="COLLECTING_PREFERENCES"),ut({element:t,extension:{name:wi,value:o}}),{...P}}function Jb({alternateParticipantId:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,structureId:o,event:i}){return of({positionActionName:"alternateDrawPositionAssignment",participantIdAttributeName:"alternateParticipantid",participantId:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,structureId:o,event:i})}function AS({targetMatchUpIds:t,drawDefinition:e}){if(!e)return{error:$};if(!Array.isArray(t)||!t.length)return{error:O};let{exitProfiles:r}=Ll({drawDefinition:e}),n=e.structures??[],o={},i=0;for(let s of n){let a=r?.[s.structureId]??[];if(s.structures?.length)for(let c of s.structures)i+=w0({exitProfiles:a,structure:c,parentStructure:s,targetMatchUpIds:t,idMap:o});i+=w0({exitProfiles:a,targetMatchUpIds:t,structure:s,idMap:o})}if(Object.keys(o).length)for(let s of n){F0(s,o);for(let a of s.structures??[])F0(a,o)}return{...P,remappedCount:i}}function w0({parentStructure:t,targetMatchUpIds:e,exitProfiles:r,structure:n,idMap:o}){let i=0,s=t?.stage??n.stage,a=t?.stageSequence??n.stageSequence;for(let c of n.matchUps??[]){let u=L0({stageSequence:a,roundPosition:c.roundPosition,roundNumber:c.roundNumber,structureId:n.structureId,parentStructureId:t?.structureId,stage:s,targetMatchUpIds:e,exitProfiles:r});u&&u.matchUpId!==c.matchUpId&&(o[c.matchUpId]=u.matchUpId,c.matchUpId=u.matchUpId,i++);for(let p of c.tieMatchUps??[]){let m=L0({stageSequence:a,roundPosition:p.roundPosition,roundNumber:p.roundNumber,structureId:n.structureId,parentStructureId:t?.structureId,stage:s,targetMatchUpIds:e,exitProfiles:r});m&&m.matchUpId!==p.matchUpId&&(o[p.matchUpId]=m.matchUpId,p.matchUpId=m.matchUpId,i++)}}return i}function L0({parentStructureId:t,targetMatchUpIds:e,stageSequence:r,roundPosition:n,exitProfiles:o,structureId:i,roundNumber:s,stage:a}){return e.find(c=>c.roundNumber!==s||c.roundPosition!==n?!1:c.structureId?c.structureId===i||c.structureId===t:c.exitProfile?o.includes(c.exitProfile):!(c.stage&&c.stage!==a||c.stageSequence&&c.stageSequence!==r))}function F0(t,e){let r=n=>{n.winnerMatchUpId&&e[n.winnerMatchUpId]&&(n.winnerMatchUpId=e[n.winnerMatchUpId]),n.loserMatchUpId&&e[n.loserMatchUpId]&&(n.loserMatchUpId=e[n.loserMatchUpId]);for(let o of n.tieMatchUps??[])r(o)};for(let n of t.matchUps??[])r(n)}function Wp({targetRoundNumber:t,finishingPosition:e,drawDefinition:r,structureId:n,linkType:o}){let{links:i}=Ma({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}=tt({structureId:p,drawDefinition:r});if(!(e&&m?.finishingPosition!==e))return u}).filter(Boolean);return{sourceStructureIds:a.map(({source:u})=>u.structureId),relevantLinks:a}}function PS({qualifyingParticipantId:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,structureId:o}){return of({positionActionName:"qualifierDrawPositionAssignment",participantId:t,isQualifierPosition:!0,tournamentRecord:e,drawDefinition:r,drawPosition:n,structureId:o})}function FE({drawDefinition:t,structureId:e}){if(!t)return{error:$};let{structure:r}=tt({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 NS({withStageGrouping:t,stageSequences:e,stageSequence:r,roundTarget:n,stages:o,event:i,stage:s}){if(!i)return{error:le};let a={},c=[];for(let u of i.drawDefinitions??[]){let{structures:p,stageStructures:m}=In({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 kE({withStageGrouping:t,tournamentRecord:e,stageSequences:r,stageSequence:n,roundTarget:o,stages:i,stage:s}){if(!e)return{error:j};let a={},c=[];for(let u of e.events??[]){let{structures:p,stageStructures:m}=NS({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 No(t){if(!t?.drawDefinition)return!1;let e=wp(t),r=e?.includesTeamMatchUps,{completedMatchUps:n,pendingMatchUps:o,upcomingMatchUps:i}=e??{};return r&&(n=n?.filter(({matchUpType:a})=>a===Ot),o=o?.filter(({matchUpType:a})=>a===Ot),i=i?.filter(({matchUpType:a})=>a===Ot)),!!(n?.length&&!o?.length&&!i?.length)}function GE(t){let{drawDefinition:e,structureId:r}=t;if(!e)return{error:$};let{playoffStructures:n}=FE({drawDefinition:e,structureId:r});if(!n?.length)return!1;let o=e?.entries?.filter(c=>c?.entryStatus&&hr.includes(c.entryStatus))?.length??0,i=0;return(n??[]).reduce((c,u)=>!!((Pt({structure:u}).positionAssignments??[])?.filter(d=>(d.participantId&&i++,d?.bye??d?.participantId)).length&&c),!!n.length)||i===o}var k0=(t,e)=>{let r=[...new Set(e.slice(0,t.length))],n=[...r].sort((a,c)=>a-c),o=new Set,i=[];r.forEach(a=>{let c=t.indexOf(a);if(c!==-1&&!o.has(c))i.push(c),o.add(c);else{let u=n.indexOf(a),p=t.findIndex((m,d)=>!o.has(d));for(;o.has(p)&&p===-1&&o.size<t.length;)p=t.findIndex((m,d)=>!o.has(d)&&d>p);i.push(u),o.add(u)}});let s=t.filter((a,c)=>!o.has(c));return[...i,...s]};function Zb({targetRoundNumber:t=1,tournamentRecord:e,drawDefinition:r,event:n,randomList:o}){let i=X({drawDefinition:r,event:n,tournamentRecord:e},[{[Kt]:!0,[ce]:!0,[rt]:!0}]);if(i.error)return i;let s=[],a=[],c=r.structures?.find(h=>h.stage===H&&h.stageSequence===1);if(!c)return M({result:{error:Fg}});let m=(It({tournamentRecord:e,drawDefinition:r,structure:c,event:n}).appliedPolicies??{})[Jn]?.requireCompletedStructures,{qualifierPositions:d,positionAssignments:l}=se({structure:c});if(!d.length)return M({result:{error:zg}});let f=Q(0,d.length);o&&(f=k0(f,o));let g=l.map(h=>h.participantId).filter(Boolean),{relevantLinks:I}=Wp({structureId:c.structureId,targetRoundNumber:t,linkType:Er,drawDefinition:r})??{},{relevantLinks:S}=Wp({structureId:c.structureId,targetRoundNumber:t,linkType:fn,drawDefinition:r})??{};return r3({eliminationSourceLinks:I,requireCompletedStructures:m,assignedParticipantIds:g,qualifyingParticipantIds:a,drawDefinition:r}),n3({roundRobinSourceLinks:S,assignedParticipantIds:g,qualifyingParticipantIds:a,drawDefinition:r}),a.length?(f.forEach((h,T)=>{let y=a[T],E=d[h].drawPosition;y&&PS({qualifyingParticipantId:y,structureId:c.structureId,drawPosition:E,tournamentRecord:e,drawDefinition:r})?.success&&s.push({participantId:y,drawPosition:E})}),M({result:et({...P,assignedParticipants:s})})):M({result:{error:tD}})}function r3({eliminationSourceLinks:t,requireCompletedStructures:e,assignedParticipantIds:r,qualifyingParticipantIds:n,drawDefinition:o}){for(let i of t){let s=o.structures?.find(p=>p.structureId===i.source.structureId);if(s?.stage!==Z)continue;let a=No({structureId:i.source.structureId,drawDefinition:o});if(e&&!a)continue;let c=s.qualifyingRoundNumber,{matchUps:u}=ht({matchUpFilters:{...c&&{roundNumbers:[c]},isCollectionMatchUp:!1,hasWinningSide:!0},afterRecoveryTimes:!1,inContext:!0,structure:s});for(let p of u){let m=p.matchUpStatus==="BYE"&&p.sides?.find(({participantId:l})=>l),d=p.sides.find(l=>l?.sideNumber===p.winningSide);if(d||m){let{participantId:l}=d||(m??{});l&&!r.includes(l)&&n.push(l)}}}}function n3({roundRobinSourceLinks:t,assignedParticipantIds:e,qualifyingParticipantIds:r,drawDefinition:n}){for(let o of t){let i=n?.structures?.find(u=>u.structureId===o.source.structureId);if(i?.stage!==Z||!No({structureId:o.source.structureId,drawDefinition:n}))continue;let{positionAssignments:a}=Pt({structure:i}),c=a?.map(u=>{let p=u.participantId,m=ot({element:u,name:Lo}).extension?.value;return m?{participantId:p,groupOrder:m?.groupOrder}:{}}).filter(({groupOrder:u,participantId:p})=>u===1&&!e.includes(p)).map(({participantId:u})=>u)??[];c&&r.push(...c)}}function VE({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=VE({accessors:s,significantCharacters:t,value:c});n.push(...u)});else if(r=r[o],s.length){let a=VE({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 BE({targetParticipantIds:t,policyAttributes:e,idCollections:r,participants:n}){if(!Array.isArray(e))return{error:FT};if(!Array.isArray(n))return{error:Wc};let o={};return t.forEach(i=>{let s=n.find(c=>c.participantId===i),{values:a}=tC({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 tC({policyAttributes:t,idCollections:e,participants:r,participant:n}){if(!Array.isArray(t))return{error:FT};if(!n)return{error:ga};let o=[];return t.forEach(s=>{let{directive:a,groupings:c,key:u,significantCharacters:p}=s??{};if(u){let m=u.split(".");o.push(...VE({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 eC({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}=tC({participants:e,policyAttributes:r,idCollections:n,participant:s});return{...i,values:a}})}function V0({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 B0(t){let{unfilledPositions:e,chunkedDrawPositions:r}=t,n=V0(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=G0(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=G0(c);return!s.includes(u)}}}function H0(t){let{unfilledPositions:e,chunkedDrawPositions:r}=t,n=V0(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 G0(t){return Number(t%2?t+1:t-1)}function W0({allGroups:t,participantId:e}){return Object.keys(t).filter(r=>t[r].includes(e))}function Y0({selectedParticipantGroups:t,participantIdGroups:e,positionAssignments:r,drawPositionChunks:n,unfilledPositions:o,isRoundRobin:i}){let s=n.map(a=>i?H0({groupsToAvoid:t,chunkedDrawPositions:a,participantIdGroups:e,positionAssignments:r,unfilledPositions:o}):B0({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 HE({positionAssignments:t,participantIds:e}){let r=t.map(n=>n.participantId);return e.filter(n=>!r.includes(n))}function j0({useSpecifiedGroupKey:t=!1,targetParticipantIds:e,largestFirst:r=!0,allGroups:n,groupKey:o,random:i}){let s=Object.assign({},...Object.keys(n).map(m=>[m,n[m].filter(d=>e.includes(d))]).filter(m=>m[1].length).map(([m,d])=>({[m]:d}))),a=Object.keys(s).reduce((m,d)=>s[d].length>m?s[d].length:m,0),c=Object.keys(s).filter(m=>s[m].length===a),u=r?An(c,i):An(Object.keys(s),i);return o=t&&s[o]?.length?o:u,{participantId:o&&s[o]?An(s[o],i):An(e,i),groupKey:o}}function q0({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 $0({candidatePositionAssignments:t,unseededParticipantIds:e,participantIdGroups:r,drawPositionChunks:n,drawPositionGroups:o,pairedPriority:i,allGroups:s,groupKey:a,random:c}){let p=o.reduce((D,b)=>b.length>D?b.length:D,0)<=2,m=HE({positionAssignments:t,participantIds:e}),d=q0({positionAssignments:t,drawPositionGroups:o}),{participantId:l,groupKey:f}=j0({targetParticipantIds:m,useSpecifiedGroupKey:p,allGroups:s,groupKey:a,random:c}),g=W0({participantId:l,allGroups:s}),I=Y0({positionAssignments:t,isRoundRobin:p,selectedParticipantGroups:g,participantIdGroups:r,drawPositionChunks:n,unfilledPositions:d}),{unassigned:S,unpaired:h,pairedNoConflict:T}=I,y=T?.length&&T[0],E=h?.length&&h[0],A=i&&y?y:E,N=i?E:y,U=A?.length&&A||N?.length&&N,R;if(U?.length){let D=Sr(U,c);R=Sr(D,c)}else{let D=Sr(S[0],c);R=Sr(D,c)}return{newGroupKey:f,selectedParticipantId:l,targetDrawPosition:R}}function US({isRoundRobin:t,groupedParticipants:e}){let r=[];return t?e.forEach(n=>{let o=n.map(a=>a.drawPosition),i=lS({drawPositions:o}).uniqueMatchUpGroupings??[],s=Object.assign({},...n.map(a=>({[a.drawPosition]:a})));i.forEach(a=>{Re(s[a[0]].values??[],s[a[1]].values??[])&&(r.push(a),n.conflict=!0)})}):e.forEach(n=>{Re(n[0]?.values??[],n[1]?.values??[])&&(r.push(n),n.conflict=!0)}),r}function o3(t,e){let r=t.find(n=>n.includes(e));if(r)return r.find(n=>n!==e)}function K0(t,e){return t.find(r=>r.drawPosition===e)}function i3({moveableParticipant:t,possibleDrawPosition:e,positionedParticipants:r,drawPositionGroups:n,isRoundRobin:o,getAvoidanceConflicts:i}){let s=o3(n,e),a=K0(r,s),u=i({isRoundRobin:o,groupedParticipants:[[t,a]]}),m=[K0(r,e),a],d=i({isRoundRobin:o,groupedParticipants:[m]});return!u.length&&!d.length}function z0({positionedParticipants:t,potentialDrawPositions:e,drawPositionGroups:r,avoidanceConflicts:n,isRoundRobin:o}){return n.flatMap(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=>i3({moveableParticipant:c,possibleDrawPosition:m,positionedParticipants:t,drawPositionGroups:r,isRoundRobin:o,getAvoidanceConflicts:US}));if(p.length)return{drawPosition:c.drawPosition,possibleDrawPositions:p}}).filter(Boolean)})}function rC(t){let{initialPositionAssignments:e,participantsWithGroupings:r,opponentsToPlaceCount:n,unseededByePositions:o,drawPositionGroups:i,policyAttributes:s,idCollections:a,allGroups:c,random:u}=t,p=[],m,d=Math.min(...(i??[]).map(y=>y?.length).filter(Boolean)),l=d>2,f=q(e,!1,!0).filter(y=>!y.qualifier),g=e.filter(y=>!y.participantId&&!y.qualifier&&(!y.bye||o?.includes(y.drawPosition))).map(y=>y.drawPosition);Q(0,n).forEach(()=>{let{newGroupKey:y,selectedParticipantId:E,targetDrawPosition:A}=$0({...t,candidatePositionAssignments:f,allGroups:c,groupKey:m});m=y,f.forEach(N=>{N.drawPosition===A&&(N.participantId=E)})});let I=eC({candidatePositionAssignments:f,participantsWithGroupings:r,policyAttributes:s,idCollections:a}),S=he(I,d),h=US({groupedParticipants:S,isRoundRobin:l}),T=0;for(;T<20&&h.length;){let y=z0({positionedParticipants:I,potentialDrawPositions:g,avoidanceConflicts:h,drawPositionGroups:i,isRoundRobin:l});if(y.length){let E=s3({candidatePositionAssignments:f,swapOptions:y,random:u});E.error&&console.log({result:E}),I=eC({candidatePositionAssignments:f,participantsWithGroupings:r,policyAttributes:s,idCollections:a}),S=he(I,d),h=US({groupedParticipants:S,isRoundRobin:l}),T++}else T=20}return f.forEach(y=>{if(y.bye&&y.participantId){let E=xT;p.push(E)}if(y.qualifier&&y.participantId){let E=xT;p.push(E)}}),{positionAssignments:f,conflicts:h.length,groupedParticipants:S,errors:p}}function s3({candidatePositionAssignments:t,swapOptions:e,random:r}){let n=Sr(e,r);if(!n)return{error:{message:"No swap options"}};let o=n.drawPosition,i=Sr(n.possibleDrawPositions,r),s=t.find(p=>p.drawPosition===o),a=t.find(p=>p.drawPosition===i)??{},c={participantId:a?.participantId,qualifier:a?.qualifier,bye:a?.bye},u={participantId:s.participantId,qualifier:s.qualifier,bye:s.bye};return Object.assign(s,c),Object.assign(a,u),{...P}}function Q0({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,random:l}){if(!p)return{error:HU};let{candidatesCount:f=1,policyAttributes:g,targetDivisions:I}=p,{roundsToSeparate:S}=p,h="randomUnseededSeparation",{structure:T}=tt({drawDefinition:i,structureId:u}),{matchUps:y}=ht({provisionalPositioning:t,matchUpsMap:c,structure:T,event:d});if(I&&en(I)&&!S){let B=Yx(I)||0,z=y.reduce((W,K)=>Math.max(Number(K.roundNumber),W),0);S=z<B?1:z-B+1}let{positionAssignments:E}=se({structure:T}),A=Cp({participantsProfile:{convertExtensions:!0},deepCopy:!1,participants:a}).participantsWithGroupings,N=E?.filter(B=>!B.participantId),U=E?.map(B=>B.drawPosition),R=T?.structureType===de,D=R?{structure:T,matchUps:y,allDrawPositions:U,roundsToSeparate:S}:{matchUps:y,allDrawPositions:U,roundsToSeparate:S},{drawPositionGroups:b,drawPositionChunks:C}=R?a3(D):c3(D),_={groupParticipants:a.filter(B=>B.participantType===qr).map(B=>B.participantId),teamParticipants:a.filter(B=>B.participantType===vt).map(B=>B.participantId),pairParticipants:a.filter(B=>B.participantType===lt).map(B=>B.participantId)},v=BE({targetParticipantIds:e,policyAttributes:g,idCollections:_,participants:a});if(v.error)return M({result:v,stack:h});let w=Object.assign({},...e.map(B=>{let z=Object.keys(v).filter(W=>(v[W]??[]).includes(B));return{[B]:z}})),L=HE({participantIds:e,positionAssignments:E});if(L.length>(N?.length||0))return{error:Qg};let F,x=L.length,k=Q(0,f).map(()=>rC({initialPositionAssignments:E,participantsWithGroupings:A,unseededParticipantIds:e,opponentsToPlaceCount:x,pairedPriority:!1,unseededByePositions:n,participantIdGroups:w,drawPositionChunks:C,drawPositionGroups:b,policyAttributes:g,idCollections:_,allGroups:v,drawSize:m,random:l}));if(F=k.reduce((B,z)=>!B||(z.conflicts||0)<(B.conflicts||0)?z:B,void 0),!F||F.conflicts){let B=Q(0,f).map(()=>rC({initialPositionAssignments:E,participantsWithGroupings:A,unseededParticipantIds:e,opponentsToPlaceCount:x,pairedPriority:!0,unseededByePositions:n,participantIdGroups:w,drawPositionChunks:C,drawPositionGroups:b,policyAttributes:g,idCollections:_,allGroups:v,drawSize:m,random:l}));F=k.concat(...B).filter(W=>!W.errors?.length).reduce((W,K)=>!W||(K.conflicts||0)<(W.conflicts||0)?K:W,void 0)}if(!F)return{error:Cm};let G=new Set((Pt({structure:T})?.positionAssignments??[]).filter(B=>B.participantId).map(B=>B.participantId)),V=F.positionAssignments.filter(B=>!G.has(B.participantId));for(let B of V)if(B.bye){let z=Cr({tournamentRecord:o,drawDefinition:i,seedBlockInfo:s,structureId:u,matchUpsMap:c,event:d,...B});if(z.error)return M({result:z,stack:h})}else if(B.participantId){let z=vn({automaticPlacement:!0,inContextDrawMatchUps:r,tournamentRecord:o,drawDefinition:i,seedBlockInfo:s,structureId:u,matchUpsMap:c,event:d,...B});if(z.error)return M({result:z,stack:h,context:{assignment:B}})}return{...P}}function a3(t){let{structure:{structures:e}}=t,r=e.map(n=>n.positionAssignments.map(o=>o.drawPosition));return{drawPositionGroups:r,drawPositionChunks:[r]}}function c3({allDrawPositions:t,roundsToSeparate:e,matchUps:r}){let n=r.filter(d=>d.roundNumber===1).map(d=>d.drawPositions),o=n.flat().sort(Zt),i=Math.max(...o),s=t.filter(d=>d>i),a=o.length,u=Q(a===2?1:2,a).filter(d=>d===Zd(d)),m=u.slice(0,e||u.length).reverse().map(d=>he(o,d));return s.length&&console.log({fedDrawPositions:s}),{drawPositionGroups:n,drawPositionChunks:m}}function X0({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,random:l}){let f="positionUnseededParticipants";p||({structure:p}=tt({drawDefinition:i,structureId:u})),u||({structureId:u}=p);let{positionAssignments:g}=se({structure:p}),{seedAssignments:I}=Pr({provisionalPositioning:t,drawDefinition:i,structure:p}),S=I?.map(C=>C.participantId).filter(Boolean),{stage:h,stageSequence:T}=p,y=h===Z?ot({element:p,name:Rn})?.extension?.value:void 0,A=Wi({provisionalPositioning:t,drawDefinition:i,stageSequence:T,entryStatuses:Hi,structureId:u,roundTarget:y,stage:h}),U=A.filter(C=>!S?.includes(C.participantId)).map(C=>C.participantId),R=g?.filter(C=>!C.participantId&&!C.bye&&!C.qualifier).map(C=>C.drawPosition);if(!n&&U.length>(R?.length||0))return M({result:{error:Qg},context:{unseededParticipantsCount:U.length,unfilledDrawPositionsCount:R?.length},stack:f});let{appliedPolicies:D}=It({tournamentRecord:o,drawDefinition:i,event:d}),b=D?.[ac];if(p.stage===Vt){let C=A.reduce((_,v)=>(_[v.groupingValue]||(_[v.groupingValue]=[]),_[v.groupingValue].push(v.participantId),_),{});Object.keys(C).length&&(b??={policyName:"Playoff Avoidance"},b.policyAttributes??=[],b.policyAttributes.push({groupings:C}))}return b&&a?Q0({provisionalPositioning:t,unseededParticipantIds:U,inContextDrawMatchUps:e,unseededByePositions:r,tournamentRecord:o,drawDefinition:i,seedBlockInfo:s,participants:a,matchUpsMap:c,structureId:u,avoidance:b,drawSize:m,entries:A,random:l}):u3({provisionalPositioning:t,unseededParticipantIds:U,inContextDrawMatchUps:e,unfilledDrawPositions:R,multipleStructures:n,tournamentRecord:o,drawDefinition:i,seedBlockInfo:s,structureId:u,matchUpsMap:c,drawSize:m,event:d,random:l})}function u3({provisionalPositioning:t,unseededParticipantIds:e,inContextDrawMatchUps:r,unfilledDrawPositions:n,multipleStructures:o,tournamentRecord:i,drawDefinition:s,seedBlockInfo:a,matchUpsMap:c,structureId:u,drawSize:p,event:m,random:d}){let l=p>2?ar(n,d):n.reverse();for(let f of e){let g=l.pop();if(!o||g){let I=vn({provisionalPositioning:t,inContextDrawMatchUps:r,tournamentRecord:i,drawDefinition:s,seedBlockInfo:a,participantId:f,drawPosition:g,matchUpsMap:c,structureId:u,event:m});if(I?.error&&console.log("!!!!!",{result:I}),I?.error)return M({result:I,stack:"randomUnseededDistribution"})}}return{...P}}function J0(t){let{random:e}=t,r=t.structure??tt(t).structure,n="positionQualifiers",o=[];if(r.stage===me)return M({result:{error:tc},stack:n});let{unplacedRoundQualifierCounts:i,positionAssignments:s,roundDrawPositions:a}=p3(t);for(let c of Object.keys(i)){let u=s?.filter(p=>a[c].includes(p.drawPosition)&&!p.participantId&&!p.qualifier&&!p.bye).map(p=>p.drawPosition);if(i[c]>(u||0))return M({result:{error:zg},context:{unfilledDrawPositions:u},stack:n});Q(0,i[c]).forEach(()=>{let p=Sr(u,e);o.push(p),s?.forEach(m=>{m.drawPosition===p&&(m.qualifier=!0,delete m.participantId,delete m.bye)})})}return{...P,qualifierDrawPositions:o}}function p3({drawDefinition:t,structure:e,structureId:r,qualifiersCount:n}){e||({structure:e}=tt({drawDefinition:t,structureId:r})),r||({structureId:r}=e);let{positionAssignments:o}=se({structure:e}),{stage:i,stageSequence:s}=e,{qualifiersCount:a,roundQualifiersCounts:c}=Vp({drawDefinition:t,stageSequence:s,structureId:r,stage:i}),u=a||n||0,p=Object.keys(c??{}).length?c:u?{1:u}:{},d=(p?Object.keys(p):[]).map(y=>st(y)),{matchUps:l}=ht({structure:e}),{roundProfile:f}=De({matchUps:l}),g=Object.assign({},...d.filter(y=>f?.[y]).map(y=>({[y]:f?.[y]?.drawPositions?.filter(Boolean)??[]}))),I=o?.filter(y=>y.qualifier).map(y=>y.drawPosition),S=(u??0)-(I?.length??0),h=I?.length;return{unplacedRoundQualifierCounts:Object.assign({},...d.map(y=>{let E=o?.filter(A=>A.qualifier&&g[y]?.drawPositions?.includes(A.drawPosition)).map(A=>A.drawPosition);return{[y]:(p?.[y]??0)-(E?.length??0)}})),unplacedQualifiersCount:S,placedQualifiersCount:h,roundQualifiersCounts:p,positionAssignments:o,roundDrawPositions:g,qualifiersCount:u}}function nC({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,random:l,event:f}){let g=[],I=[],S=0;if(d||({structure:d}=tt({drawDefinition:i,structureId:p})),p||(p=d?.structureId),n??=It({drawDefinition:i}).appliedPolicies,!o){let h=d&&di({provisionalPositioning:t,appliedPolicies:n,drawDefinition:i,seedingProfile:s,structure:d,random:l});h?.error&&I.push(h.error),o=h?.validSeedBlocks}return u=u??o?.length??0,Q(0,u).forEach(()=>{if(S<(u||0)){let h=m3({provisionalPositioning:t,inContextDrawMatchUps:e,tournamentRecord:r,drawDefinition:i,seedingProfile:s,seedBlockInfo:a,participants:c,structureId:p,matchUpsMap:m,random:l,event:f});h?.success&&(S++,g.push(...h.seedPositions??[])),h.error&&I.push({seedPositionError:h.error})}}),I.length?{error:I}:{...P,seedPositions:g}}function m3({provisionalPositioning:t,inContextDrawMatchUps:e,tournamentRecord:r,drawDefinition:n,seedingProfile:o,seedBlockInfo:i,participants:s,structureId:a,matchUpsMap:c,random:u,event:p}){let{unplacedSeedParticipantIds:m,unfilledPositions:d}=AE({provisionalPositioning:t,randomize:!0,drawDefinition:n,seedingProfile:o,seedBlockInfo:i,structureId:a,random:u,event:p}),{appliedPolicies:l}=It({drawDefinition:n}),f=l?.[ac];f?.policyAttributes&&s&&m?.length>2&&d3({unplacedSeedParticipantIds:m,unfilledPositions:d,policyAttributes:f.policyAttributes,participants:s});let g=[];for(let I of m){let S=d.pop();if(!S)return{error:da};g.push(S);let h=vn({provisionalPositioning:t,inContextDrawMatchUps:e,tournamentRecord:r,drawDefinition:n,seedingProfile:o,participantId:I,seedBlockInfo:i,drawPosition:S,matchUpsMap:c,structureId:a,event:p});if(!h.success)return h}return{...P,seedPositions:g}}function d3({unplacedSeedParticipantIds:t,unfilledPositions:e,policyAttributes:r,participants:n}){let o=BE({targetParticipantIds:t,policyAttributes:r,participants:n});if("error"in o)return;let s=Object.values(o).filter(l=>l.length>1);if(!s.length)return;let a=e.length;if(a<2)return;let c=Math.max(...e),u=Math.min(a,Math.max(2,s.length)),p=Math.ceil(c/u),m=l=>Math.floor((l-1)/p),d=t.map((l,f)=>{let g=e[a-1-f];return g===void 0?f:m(g)});for(let l of s){if(l.length<2)continue;let f=l.map(y=>t.indexOf(y)).filter(y=>y>=0);if(f.length<2)continue;let g=f.map(y=>d[y]);if(!(g.length!==new Set(g).size))continue;let S=new Set(l),h=t.map((y,E)=>S.has(y)?-1:E).filter(y=>y>=0),T=new Set;for(let y of f){let E=d[y];if(!T.has(E)){T.add(E);continue}let A=h.find(N=>!T.has(d[N]));if(A!==void 0){let N=t[y];t[y]=t[A],t[A]=N;let U=d[y];d[y]=d[A],d[A]=U,T.add(d[y]);let R=h.indexOf(A);R>=0&&h.splice(R,1)}}}}function Z0({provisionalPositioning:t,drawDefinition:e,structure:r}){let{positionAssignments:n}=se({structure:r}),{seedAssignments:o}=Pr({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 tF({orderedSortedFirstRoundSeededDrawPositions:t,validSeedBlocks:e,byesToPlace:r,random:n}){let o=n??Math.random,i=[];e.forEach(a=>l3(a,r,i,t,o));let s=i.map(a=>Array.isArray(a)?ar(a,n):a).flat(1/0);return RT(r)&&e.map(c=>c.seedNumbers[0]).includes(r)?t:s}function l3(t,e,r,n,o){if(e-r.length>t.drawPositions.length)r.push(...t.drawPositions);else{let s=oC(he(t.drawPositions,2));f3(s,r,n,o)}}function f3(t,e,r,n){let o,i=r[e.length];for(;o=DS(t,i,n);)e.push(o),i=r[e.length]}function DS(t,e,r){return Array.isArray(t)&&t.length!==2?t.pop():Array.isArray(t[0])?I3(t,e,r):g3(t,e,r)}function g3(t,e,r){return t.includes(e)?t.indexOf(e)?t.pop():t.shift():Math.round(r())?t.pop():t.shift()}function I3(t,e,r){let n=t[0].flat(1/0).length,o=t[1].flat(1/0).length;if(n===o){let i=t[0].flat(1/0).includes(e)?t[0]:t[1];return DS(e?i:t[Math.round(r())],e,r)}return n<o?DS(t[1],e,r):DS(t[0],e,r)}function oC(t){let e=Math.floor(t.length/2);return t.length>2?[oC(t.slice(0,e)),oC(t.slice(e))]:t}function rF({provisionalPositioning:t,relevantMatchUps:e,appliedPolicies:r,drawDefinition:n,seedingProfile:o,seedBlockInfo:i,byesToPlace:s,structure:a}){i||(i=di({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=Z0({provisionalPositioning:t,drawDefinition:n,structure:a})??[],l=pt([].concat(...e.map(E=>E.drawPositions))),f=d.filter(E=>l.includes(E.drawPosition)),g=(E,A)=>Eu(E.seedValue)-Eu(A.seedValue),S=m.reduce((E,A)=>{let N=f.filter(U=>A.drawPositions?.includes(U.drawPosition)).sort(g);return E.concat(...N)},[]).map(E=>E.drawPosition),h=tF({orderedSortedFirstRoundSeededDrawPositions:S,validSeedBlocks:m,byesToPlace:s}),T=eF({orderedSeedDrawPositions:S,relevantMatchUps:e}).slice(0,s),y=eF({orderedSeedDrawPositions:h,relevantMatchUps:e}).slice(0,s);return{strictSeedOrderByePositions:T,blockSeedOrderByePositions:y,isLuckyStructure:u,positionedSeeds:d,isContainer:p,isFeedIn:c}}function eF({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 nF({provisionalPositioning:t,seedOrderByePositions:e,isLuckyStructure:r,appliedPolicies:n,drawDefinition:o,seedLimit:i,structure:s,isFeedIn:a,random:c}){let u=n?.seeding?.seedingProfile,p=s.stage===Z,{positionAssignments:m}=se({structure:s}),d=m?.filter(L=>L.participantId).map(L=>L.drawPosition),l={isCollectionMatchUp:!1},{matchUps:f,roundMatchUps:g}=ht({provisionalPositioning:t,matchUpFilters:l,structure:s}),I=g?.[1]??[],S=s.structureType===de?f:I,h=pt(S.flatMap(L=>L.drawPositions)),T=Math.min(...h)-1,y=d?.filter(L=>h.includes(L)),E=L=>{let F=Math.ceil(L.length/2),x=[L.slice(0,F),L.slice(F)],k=x.map(J=>J.flat(1/0).flat().length),G=Math.min(...k.flat(1/0)),V=Math.max(...k.flat(1/0)),B=k.indexOf(V),z=G!==V,W=ar(x,c),[K,Y]=!G||z?[x[B],x[1-B]]:[W[0],W[1]];return{greaterHalf:K,lesserHalf:Y}},A=L=>{let{greaterHalf:F,lesserHalf:x}=E(L),{greaterHalf:k,lesserHalf:G}=E(F),B=ar(k.flat(1/0),c).pop(),z=k.flat().filter(K=>K!==B);return{newlyFilteredChunks:[...x,...G,z],drawPosition:B}},N=L=>!e.includes(L),U=L=>!y?.includes(L),R=L=>{let x=he(L.sort(Zt),Math.ceil(L.length/4)).map(V=>V.filter(U)),k=x.flat(1/0).flat().length,G=[];for(let V=0;V<k;V++){let{newlyFilteredChunks:B,drawPosition:z}=A(x);G.push(z),x=B}return G},{validSeedBlocks:D}=di({provisionalPositioning:t,allPositions:!0,appliedPolicies:n,drawDefinition:o,structure:s}),b=D?.map(L=>L.drawPositions?.map(F=>F+T)),C;if(a){let L=h.length,{seedBlocks:F}=gS({cluster:[Zc,km].includes(ad(u)),participantsCount:L});C=F.map(k=>k.map(G=>G+T)).map(R).filter(k=>k.length)}else p?C=b?.map(L=>L.filter(U)):C=b?.map(R).filter(L=>L.length);let _=S.map(L=>L.drawPositions).map(L=>L?.sort((F,x)=>F-x)).filter(L=>L?.[0]+1===L?.[1]),v=L=>_.reduce((F,x)=>x.includes(L)?x.reduce((k,G)=>G===L?k:G,void 0):F,void 0),w=C.map(L=>L.map(v)).flat(1/0).filter(U).filter(N).filter(Boolean);if(p&&!s.structures){let L=i%4,F=w.slice(0,L),x=g[s.roundLimit]?.length,k=he(w.slice(L),x).flatMap(G=>ar(G,c));w=F.concat(k)}return{unseededByePositions:w}}function oF({provisionalPositioning:t,drawDefinition:e,matchUpsMap:r,structure:n,event:o}){let i={isCollectionMatchUp:!1},{matchUps:s,roundMatchUps:a}=ht({afterRecoveryTimes:!1,provisionalPositioning:t,drawDefinition:e,matchUpFilters:i,matchUpsMap:r,structure:n,event:o}),c=a?.[1]??[],u=n?.structureType===de,p=u?s:c,m=u?n?.structures?.length||0:s.length,{structureId:d,stage:l,stageSequence:f}=n,g=Wi({entryStatuses:hr,provisionalPositioning:t,drawDefinition:e,stageSequence:f,structureId:d,stage:l}),{qualifiersCount:I}=Vp({provisionalPositioning:t,drawDefinition:e,stageSequence:f,structureId:d,stage:l}),S=g.length+(I??0),{positionAssignments:h,unassignedPositions:T}=se({structure:n}),y=T?.map(D=>D.drawPosition),E=h?.filter(D=>D.bye).length,A=h?.filter(D=>D.bye).map(D=>D.drawPosition),N=p.map(D=>D.drawPositions).filter(D=>D?.reduce((b,C)=>!A?.includes(C)&&b,!0)).flat(1/0).filter(D=>y?.includes(D)),U=h?.length,R=U?U-S:0;return R>m&&n.stageSequence===1&&n.stage!==me&&(R=m),{placedByes:E,byesCount:R,relevantMatchUps:p,placedByePositions:A,roundMatchUps:a,positionsToAvoidDoubleBye:N}}function iC({provisionalPositioning:t,tournamentRecord:e,appliedPolicies:r,drawDefinition:n,seedBlockInfo:o,seedingProfile:i,matchUpsMap:s,structureId:a,structure:c,seedLimit:u,seedsOnly:p,event:m,random:d}){c||({structure:c}=tt({drawDefinition:n,structureId:a})),a||(a=c?.structureId);let l=!(c?.structures??c?.stage===Z),{byesCount:f,placedByes:g,relevantMatchUps:I}=oF({provisionalPositioning:t,drawDefinition:n,matchUpsMap:s,structure:c,event:m}),S=f-(g||0);if(S<=0)return{...P};if(an(n.drawType)){let _=(I??[]).flatMap(L=>L.drawPositions??[]).filter(Boolean),v=new Set(c?.positionAssignments?.filter(L=>L.participantId).map(L=>L.drawPosition)??[]),w=_.filter(L=>!v.has(L)).slice(0,S);for(let L of w){let F=Cr({provisionalPositioning:t,tournamentRecord:e,drawDefinition:n,drawPosition:L,matchUpsMap:s,structureId:a,structure:c,event:m});if(F?.error)return F}return{...P,byeDrawPositions:w}}let{strictSeedOrderByePositions:h,blockSeedOrderByePositions:T,isLuckyStructure:y,isFeedIn:E}=rF({provisionalPositioning:t,relevantMatchUps:I,appliedPolicies:r,drawDefinition:n,seedingProfile:i,seedBlockInfo:o,byesToPlace:S,structure:c}),A=c?.structureType&&[de,tu].includes(c.structureType)&&r?.seeding?.containerByesIgnoreSeeding,N=l&&T?.length?T:h,{unseededByePositions:U}=nF({provisionalPositioning:t,seedOrderByePositions:N,isLuckyStructure:y,appliedPolicies:r,drawDefinition:n,seedLimit:u,structure:c,isFeedIn:E,random:d}),R=_=>_%2,D=(_,v)=>(_??[]).every(w=>R(w)?v!==w+1:v!==w-1),b=N.flat();if(!p)for(;U.length;){let _=U.find(v=>D(b,v));_?(b.push(_),U=U.filter(v=>v!==_)):(b.push(...U),U=[])}A&&(b=ar(b,d),je({ignoreSeededByes:A})&&console.log({byePositions:b}));let C=b.slice(0,S);for(let _ of C){let v=Cr({provisionalPositioning:t,tournamentRecord:e,drawDefinition:n,drawPosition:_,matchUpsMap:s,structureId:a,structure:c,event:m});if(v?.error)return v}return{...P,unseededByePositions:U,byeDrawPositions:C}}function RS(t,e){return e||iI(),M({result:t,stack:"automatedPositioning"})}function S3(t,e){return e||iI(),t}function h3(t,e,r,n){let o=tt({drawDefinition:e,structureId:r});if(o.error)return{error:o.error};let i=o.structure;if(!i)return{error:Nt};let s=t.appliedPolicies||It({drawDefinition:e,structure:i,event:n})?.appliedPolicies,{qualifiersCount:a}=Vp({stageSequence:i.stageSequence,provisionalPositioning:t.provisionalPositioning,stage:i.stage,drawDefinition:e,structureId:r}),c=a||t.qualifiersCount||0,u=Hi,p=Wi({stageSequence:i.stageSequence,provisionalPositioning:t.provisionalPositioning,stage:i.stage,placementGroup:t.placementGroup,drawDefinition:e,entryStatuses:u,structureId:r});return{structure:i,appliedPolicies:s,qualifiersCount:c,entries:p}}function T3({placeByes:t,provisionalPositioning:e,tournamentRecord:r,appliedPolicies:n,drawDefinition:o,seedBlockInfo:i,matchUpsMap:s,structure:a,seedLimit:c,seedsOnly:u,event:p,structureSeedingProfile:m,seedingProfile:d,inContextDrawMatchUps:l,participants:f,positioningReport:g,random:I}){let S=t?iC({provisionalPositioning:e,tournamentRecord:r,appliedPolicies:n,drawDefinition:o,seedBlockInfo:i,matchUpsMap:s,structure:a,seedLimit:c,seedsOnly:u,random:I,event:p}):void 0;if(S?.error)return{error:S.error};let h=S?.unseededByePositions;return g.push({action:"positionByes",unseededByePositions:h}),S=nC({seedingProfile:m?{positioning:m}:d,provisionalPositioning:e,inContextDrawMatchUps:l,tournamentRecord:r,appliedPolicies:n,validSeedBlocks:i.validSeedBlocks,drawDefinition:o,seedBlockInfo:i,participants:f,matchUpsMap:s,structure:a,random:I,event:p}),S.error?{error:S.error}:(g.push({seedPositions:S.seedPositions,action:"positionSeedBlocks"}),{unseededByePositions:h})}function y3({drawType:t,structureSeedingProfile:e,seedingProfile:r,provisionalPositioning:n,inContextDrawMatchUps:o,tournamentRecord:i,appliedPolicies:s,validSeedBlocks:a,drawDefinition:c,seedBlockInfo:u,participants:p,matchUpsMap:m,structure:d,event:l,placeByes:f,seedLimit:g,seedsOnly:I,positioningReport:S,random:h}){let T;if(!an(t)){let A=nC({seedingProfile:e?{positioning:e}:r,provisionalPositioning:n,inContextDrawMatchUps:o,tournamentRecord:i,appliedPolicies:s,validSeedBlocks:a,drawDefinition:c,seedBlockInfo:u,participants:p,matchUpsMap:m,structure:d,random:h,event:l});if(A.error)return{error:A.error};S.push({action:"positionSeedBlocks",seedPositions:A.seedPositions})}let y=f?iC({provisionalPositioning:n,tournamentRecord:i,appliedPolicies:s,drawDefinition:c,seedBlockInfo:u,matchUpsMap:m,structure:d,seedLimit:g,seedsOnly:I,random:h,event:l}):void 0;return y?.error?{error:y.error}:(T=y?.unseededByePositions,S.push({action:"positionByes",byeDrawPositions:y?.byeDrawPositions,unseededByePositions:T}),{unseededByePositions:T})}function E3({seedsOnly:t,inContextDrawMatchUps:e,tournamentRecord:r,appliedPolicies:n,validSeedBlocks:o,drawDefinition:i,seedBlockInfo:s,participants:a,matchUpsMap:c,structure:u,positionQualifiers:p,positionUnseededParticipants:m,provisionalPositioning:d,unseededByePositions:l,multipleStructures:f,qualifiersCount:g,structureId:I,drawSize:S,event:h,positioningReport:T,conflicts:y,random:E}){if(t)return{};let A=p({inContextDrawMatchUps:e,tournamentRecord:r,appliedPolicies:n,validSeedBlocks:o,drawDefinition:i,qualifiersCount:g,seedBlockInfo:s,participants:a,matchUpsMap:c,structure:u,random:E});return A.error?{error:A.error}:(A.conflicts&&(y.qualifierConflicts=A.conflicts),T.push({action:"positionQualifiers",qualifierDrawPositions:A.qualifierDrawPositions}),A=m({provisionalPositioning:d,inContextDrawMatchUps:e,unseededByePositions:l,multipleStructures:f,tournamentRecord:r,drawDefinition:i,seedBlockInfo:s,participants:a,matchUpsMap:c,structureId:I,structure:u,drawSize:S,random:E,event:h}),A.error?{error:A.error}:(A.conflicts&&(y.unseededConflicts=A.conflicts),T.push({action:"positionUnseededParticipants"}),{}))}function Ru(t){let{drawDefinition:e}=t,{applyPositioning:r=!0,provisionalPositioning:n,multipleStructures:o,placeByes:i=!0,tournamentRecord:s,seedingProfile:a,structureId:c,seedLimit:u,seedsOnly:p,drawType:m,drawSize:d,random:l,event:f}=t,g=[];r||(LD(),e=q(e,!1,!0));let{structure:I,appliedPolicies:S,qualifiersCount:h,entries:T,error:y}=h3(t,e,c,f);if(y)return RS(y,r);if(!T?.length&&!h)return S3({...P},r);let E=t.matchUpsMap??Ie({drawDefinition:e}),A=t.inContextDrawMatchUps??te({inContext:!0,drawDefinition:e,matchUpsMap:E})?.matchUps,N=di({provisionalPositioning:n,appliedPolicies:S,drawDefinition:e,seedingProfile:a,structure:I,random:l});if(N.error)return RS(N,r);let{validSeedBlocks:U}=N;g.push({validSeedBlocks:U});let R=t.participants||(s?bt({withIndividualParticipants:!0,convertExtensions:!0,tournamentRecord:s})?.participants:[]),D;if(ad(I.seedingProfile||a)===vi){let v=T3({placeByes:i,provisionalPositioning:n,tournamentRecord:s,appliedPolicies:S,drawDefinition:e,seedBlockInfo:N,matchUpsMap:E,structure:I,seedLimit:u,seedsOnly:p,event:f,structureSeedingProfile:I.seedingProfile,seedingProfile:a,inContextDrawMatchUps:A,participants:R,positioningReport:g,random:l});if(v?.error)return RS(v.error,r);D=v.unseededByePositions}else{let v=y3({drawType:m,structureSeedingProfile:I.seedingProfile,seedingProfile:a,provisionalPositioning:n,inContextDrawMatchUps:A,tournamentRecord:s,appliedPolicies:S,validSeedBlocks:U,drawDefinition:e,seedBlockInfo:N,participants:R,matchUpsMap:E,structure:I,event:f,placeByes:i,seedLimit:u,seedsOnly:p,positioningReport:g,random:l});if(v?.error)return RS(v.error,r);D=v.unseededByePositions}let b={},C=E3({seedsOnly:p,inContextDrawMatchUps:A,tournamentRecord:s,appliedPolicies:S,validSeedBlocks:U,drawDefinition:e,seedBlockInfo:N,participants:R,matchUpsMap:E,structure:I,positionQualifiers:J0,positionUnseededParticipants:X0,provisionalPositioning:n,unseededByePositions:D,multipleStructures:o,qualifiersCount:h,structureId:c,drawSize:d,event:f,positioningReport:g,conflicts:b,random:l});if(C?.error)return RS(C.error,r);let{positionAssignments:_}=Pt({drawDefinition:e,structure:I});return Ft({drawDefinition:e,structureIds:[c]}),r||iI(),{positionAssignments:_,conflicts:b,...P,positioningReport:g}}function wa(t){let{applyPositioning:e=!0,provisionalPositioning:r,tournamentRecord:n,drawDefinition:o,seedingProfile:i,structureId:s,placeByes:a,seedsOnly:c,random:u}=t;if(!o)return{error:Rr};if(!No({drawDefinition:o,structureId:s})&&!r)return{error:_g};let m=FE({drawDefinition:o,structureId:s}).playoffStructures?.sort((f,g)=>xI(f)-xI(g)),d=[],l=[];if(m)for(let f of m){let{structureId:g}=f,I=Ru({structureId:g,provisionalPositioning:r,applyPositioning:e,tournamentRecord:n,drawDefinition:o,seedingProfile:i,placeByes:a,seedsOnly:c,random:u});if(I.error)return I;I.positionAssignments&&d.push({positionAssignments:I.positionAssignments,structureId:g}),I.positioningReport&&l.push(I.positioningReport)}return{...P,structurePositionAssignments:d,positioningReports:l}}function sC({validation:t=!0,tournamentRecord:e,drawDefinition:r,participantId:n,structureId:o,seedValue:i,event:s}){if(!r)return{error:$};if(!o)return{error:dn};let a=(e?.participants??[]).find(l=>l.participantId===n);if(e&&!a)return{error:Vr};let{structure:c}=tt({drawDefinition:r,structureId:o});if(!c)return{error:Nt};if(!(!t||Le(i)||i===void 0||i===""||typeof i=="string"&&i.split("-").every(l=>Le(l)&&st(l)>0)))return{error:O};let{seedAssignments:p}=Pr({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.push(f)}return bl({tournamentId:e?.tournamentId,eventId:s?.eventId,drawDefinition:r,structure:c}),{...P}}function aC({drawDefinition:t,orderMap:e}){return t?((typeof e!="object"||!Object.values(e).every(r=>yt(r)))&&M({result:{error:O},context:{orderMap:e}}),t.structures??=[],t.structures.forEach(r=>{let n=e[r.structureId];n&&(r.structureOrder=n)}),t.structures.sort((r,n)=>Lc(r.structureOrder)-Lc(n.structureOrder)),{...P}):{error:$}}function Yp({drawDefinition:t}){let e=t.structures??[],r=t.links??[],n=new Map,o=I=>{let S=n.get(I)||n.set(I,{drawSources:[],drawTargets:[],progeny:[],sources:[],targets:[]})&&n.get(I);if(S&&!S?.stage){let h=e.find(T=>T.structureId===I);S.stage=h?.stage}return S},i={},s={},a=A3({links:r,initStructureProfile:o,sourceStructureIds:i,hasDrawFeedProfile:s});P3(n);let c=D3(n),u=a.length;Q(0,Math.ceil(u/2)).forEach(()=>{a=Q(0,u).map(I=>{let S=a[I],h=a.reduce((T,y)=>Re(S,y)?T.concat(...y):T,[])??[];return pt(S.concat(...h))})});let p=a[0],m=(I,S)=>Yt(I,S).length===I.length,d=a.slice(1).reduce((I,S)=>I&&m(S,p),!0),l=[p].filter(Boolean),f=[p].filter(Boolean);R3({structures:e,structureGroups:l,linkCheck:f});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 A3({links:t,initStructureProfile:e,sourceStructureIds:r,hasDrawFeedProfile:n}){return t.map(o=>{let i=o.source.structureId,s=o.target.structureId,a=e(i),c=e(s);return[Oi,qe,Gm,vi].includes(o.target.feedProfile)?(a?.targets.push(s),c?.sources.push(i)):o.target.feedProfile===ln&&(c?.drawSources.push(i),a?.drawTargets.push(s)),n[s]=n[s]||o.target.feedProfile===ln,r[s]=pt([...r[s]??[],i]).filter(Boolean),[o.source.structureId,o.target.structureId]})}function P3(t){for(let e of t.keys()){let r=t.get(e);r&&(N3(r,t),U3(r,t))}}function N3(t,e){let r=t.targets??[];for(;r.length;){let n=r.pop(),o=n&&e[n];o?.targets?.length?r.push(...o.targets):o&&(t.rootStage=o.stage)}t.rootStage??=t.stage}function U3(t,e){if(t.targets?.length)return;let r=t.sources??[];for(;r.length;){let n=r.pop(),o=n&&e[n];if(o?.sources?.length){for(let i of o.sources)t.progeny?.includes(i)||t.progeny?.push(i);r.push(...o.sources)}}}function D3(t){let e=0;for(let r of t.keys()){let n=t.get(r);if(n?.rootStage!==Z)continue;let o=[n.drawTargets?.[0]],i=0;for(;o.length;){i+=1;let s=o.pop(),a=s?t.get(s):void 0;a?.drawTargets?.length&&o.push(a.drawTargets[0])}n.distanceFromMain=i,i>e&&(e=i)}return e}function R3({structures:t,structureGroups:e,linkCheck:r}){t.forEach(n=>{let{structureId:o,stage:i}=n;e.find(a=>a.includes(o))||(e.push([o]),i!==Fe&&r.push([o]))})}function WE({drawDefinition:t}){let{maxQualifyingDepth:e,structureProfiles:r}=Yp({drawDefinition:t});for(let n of t.structures){let o=r[n.structureId];o.distanceFromMain&&(n.stageSequence=e+1-o.distanceFromMain)}return{...P}}function bS(t){let e=X(t,[{[rt]:!0,[Kt]:!0}]);if(e.error)return e;let{tournamentRecord:r,drawDefinition:n,structure:o,link:i}=t;return b3({tournamentId:r.tournamentId,drawDefinition:n,structure:o,link:i})}function b3(t){let e=X(t,[{[Kt]:!0,[oc]:!0},{link:!0,[Ge]:jr,[gU]:wg}]);if(e.error)return e;let{drawDefinition:r,tournamentId:n,structure:o,eventId:i,link:s}=t,a=s.target.structureId,c=tt({drawDefinition:r,structureId:a});if(c.error)return M({stack:"attachQualifyingStructure",context:{targetStructureId:a},result:c});r.structures??=[],r.links??=[],r.structures.push(o),r.links.push(s),WE({drawDefinition:r});let u=ht({structure:o})?.matchUps??[];return ko({drawDefinition:r,tournamentId:n,matchUps:u,eventId:i}),Ft({drawDefinition:r,structureIds:[o.structureId]}),{...P}}function cC({drawDefinition:t,structureDetails:e}){if(!Array.isArray(e))return{error:O};if(!t)return{error:$};let r=Object.assign({},...e.map(n=>{if(!Tt(n))return;let{structureId:o,structureName:i}=n??{};if(!(!o||!i))return{[o]:i}}).filter(Boolean));if(!Object.values(r).length)return{error:nt};for(let n of t.structures??[]){let o=r[n.structureId];if(o&&(n.structureName=o),n.structures)for(let i of n.structures){let s=r[i.structureId];s&&(i.structureName=s)}}return{...P}}function CS({drawDefinition:t,timeItem:e}){if(!t)return{error:Rr};if(!e)return{error:Jg};let r=e&&Object.keys(e),n=["itemType","itemValue"];if(!(n.filter(s=>r.includes(s)).length===n.length))return{error:Xg};t.timeItems??=[];let i=new Date().toISOString();return Object.assign(e,{createdAt:i}),t.timeItems.push(e),lc({drawDefinition:t}),{...P}}function iF({positionAssignments:t,participantFactors:e,random:r}){if(!e||!t)return{error:nt};let n=q(e,!1,!0),o=t.map(({drawPosition:g})=>g),i=t.filter(g=>!g.participantId&&!g.bye&&!g.qualifier).map(nL),s,a=!0;for(;a;)({drawPositionResolutions:s,remainingPreferences:a,participantPreferences:n}=C3({participantPreferences:n,drawPositionResolutions:s,random:r}));let c=new Set(Object.keys(s).map(g=>st(g))),u=i.filter(g=>!c.has(g)),p=Object.keys(n),d=Q(1,((g,I)=>Math.log(I)/Math.log(g))(2,o?.length||0)+1).map(g=>Math.pow(2,g)),l={};for(let g of d){let I=he(o,g).filter(T=>Re(T,u)),S={};if(p.forEach(T=>{I.forEach(y=>{let E=y.join("|");Re(y,e[T].preferences)&&(S[E]||(S[E]=[]),S[E].push(T))})}),ar(Object.keys(S),r).forEach(T=>{let y=S[T].filter(E=>p.includes(E));for(;y.length;){let E=Sr(y,r),A=T.split("|").map(N=>st(N)).filter(N=>u.includes(st(N)));if(A.length){let N=Sr(A,r);u=u.filter(R=>R!==N),p=p.filter(R=>R!==E),s[N]=E;let U=T.split("|").length;l[U]||(l[U]=0),l[U]+=1}}}),!u.length)break}let f={chunkResolution:l};return p.length&&(p.forEach(g=>{let I=Sr(u,r);I&&(s[I]=g)}),f.randomAssignment=p.length),{drawPositionResolutions:s,report:f}}function C3({participantPreferences:t,drawPositionResolutions:e={},random:r}){let n=Object.keys(t).reduce((a,c)=>{let p=t[c].preferences[0];return p&&(a[p]||(a[p]=[]),a[p].push(c)),a},{}),o=Math.min(...Object.values(n).filter(a=>a.length).map(a=>a.length)),i=Object.keys(n).filter(a=>n[a].length&&o&&n[a].length===o);i.forEach(a=>{let c=n[a],u=Sr(c,r);e[a]=u,delete t[u]});let s;return Object.values(t).forEach(a=>{a.preferences=a.preferences.filter(c=>{let u=!i.includes(c.toString());return u&&(s=!0),u})}),{drawPositionResolutions:e,remainingPreferences:s,participantPreferences:t}}function uC({tournamentRecord:t,drawDefinition:e,applyResults:r=!0,tierIndex:n,random:o,event:i}){if(!e)return{error:$};let{extension:s}=ot({element:e,name:wi});if(!s?.value)return{error:fe,info:"No active draft found"};let a=s.value;if(a.status==="COMPLETE")return{error:O,info:"Draft is already complete"};let c=a.structureId,{structure:u}=tt({drawDefinition:e,structureId:c});if(!u)return{error:fe,info:"Structure not found"};let{positionAssignments:p}=Pt({drawDefinition:e,structureId:c});if(!p)return{error:fe,info:"No position assignments"};let m=M3({draftState:a,targetTierIndex:n});if(m?.error)return m;let d=p.map(I=>({...I})),l={},f=[];for(let I=0;I<a.tiers.length;I++){let S=a.tiers[I];S.resolved||n!==void 0&&I!==n||(v3({draftState:a,tier:S,tierIndex:I,workingAssignments:d,allResolutions:l,tierReports:f,random:o}),S.resolved=!0)}let g=x3(a,l);if(r){let I=O3({allResolutions:l,tournamentRecord:t,drawDefinition:e,structureId:c,draftState:a,transparencyReport:g,tierReports:f,event:i});if(I)return I}return{...P,drawPositionResolutions:l,tierReports:f,transparencyReport:g}}function M3({draftState:t,targetTierIndex:e}){if(e!==void 0){if(e<0||e>=t.tiers.length)return{error:O,info:"Invalid tier index"};if(t.tiers[e].resolved)return{error:O,info:"Tier already resolved"};for(let r=0;r<e;r++)if(!t.tiers[r].resolved)return{error:O,info:`Tier ${r+1} must be resolved first`}}}function v3({draftState:t,tier:e,tierIndex:r,workingAssignments:n,allResolutions:o,tierReports:i,random:s}){let a=new Set(n.filter(p=>!p.participantId&&!p.bye&&!p.qualifier).map(p=>p.drawPosition)),c={},u=[];for(let p of e.participantIds){let d=t.preferences[p]?.filter(l=>a.has(l));d?.length?c[p]={preferences:d}:u.push(p)}if(Object.keys(c).length){let{drawPositionResolutions:p,report:m}=iF({positionAssignments:n,participantFactors:c});if(p)for(let[d,l]of Object.entries(p)){o[Number(d)]=l;let f=n.find(g=>g.drawPosition===Number(d));f&&(f.participantId=l)}i.push({tierIndex:r,preferenceReport:m,participantsWithoutPreferences:u})}if(u.length){let p=n.filter(l=>!l.participantId&&!l.bye&&!l.qualifier).map(l=>l.drawPosition),m=s??Math.random,d=[...p].sort(()=>m()-.5);for(let l=0;l<u.length&&l<d.length;l++){let f=d[l],g=u[l];o[f]=g;let I=n.find(S=>S.drawPosition===f);I&&(I.participantId=g)}i.push({tierIndex:r,randomAssignment:u.length})}}function O3({allResolutions:t,tournamentRecord:e,drawDefinition:r,structureId:n,draftState:o,transparencyReport:i,tierReports:s,event:a}){let c=[];for(let[m,d]of Object.entries(t)){let l=vn({drawPosition:Number(m),participantId:d,tournamentRecord:e,drawDefinition:r,structureId:n,event:a});l.error&&c.push({drawPosition:Number(m),participantId:d,error:l.error})}let u=new Set(Object.keys(t).map(Number));if(o.unassignedDrawPositions=(o.unassignedDrawPositions??[]).filter(m=>!u.has(m)),_3({draftState:o,allResolutions:t}),o.tiers.every(m=>m.resolved)&&(o.status="COMPLETE",o.resolvedAt=new Date().toISOString(),o.transparencyReport=i),ut({element:r,extension:{name:wi,value:o}}),c.length)return{...P,errors:c,drawPositionResolutions:t,tierReports:s,transparencyReport:i}}function _3({draftState:t,allResolutions:e}){let r={};for(let[n,o]of Object.entries(e))r[o]=Number(n);for(let n of t.tiers){if(!n.resolved||n.resolutions)continue;let o={};for(let i of n.participantIds){let s=r[i];if(s===void 0)continue;let c=(t.preferences[i]??[]).indexOf(s);o[i]={assignedPosition:s,preferenceMatch:c>=0?c+1:null}}n.resolutions=o}}function x3(t,e){let r=[],n={};for(let[o,i]of Object.entries(e))n[i]=Number(o);for(let o of t.tiers)for(let i of o.participantIds){let s=t.preferences[i]??[],a=n[i],c=s.indexOf(a);r.push({participantId:i,preferences:s,assignedPosition:a,preferenceMatch:c>=0?c+1:null})}return r}function pC({tournamentRecord:t,drawDefinition:e,event:r,structureId:n}){if(!e)return{error:$};let o=e.structures?.find(a=>a.stage===Z&&a.structureId===n);if(!o)return{error:Nt};if(o.matchUps?.some(({matchUpStatus:a,score:c})=>ue({score:c})??Mt.includes(a)))return{error:$c};let s=o.matchUps?.map(({matchUpId:a})=>a)??[];return o.positionAssignments=[],o.seedAssignments=[],o.matchUps=[],xn({tournamentId:t?.tournamentId,action:"resetVoluntaryConsolationStructure",matchUpIds:s,drawDefinition:e}),Ft({tournamentId:t?.tournamentId,eventId:r?.eventId,drawDefinition:e,structureIds:[o.structureId]}),{...P}}function mC(t){let{tournamentRecord:e,drawDefinition:r,structureId:n,event:o}=t,i=X(t,[{drawDefinition:!0,structureId:!0}]);if(i.error)return i;let s=r.structures??[],a=s.find(S=>S.structureId===n);if(!a)return{error:Nt};let c=s.find(({stage:S,stageSequence:h})=>S===H&&h===1),u=n===c?.structureId,p=s.filter(({stage:S})=>S===Z).map(Fr("structureId"));if(u&&!p.length)return{error:IU};let m=p.includes(n),d=w3({isQualifyingStructure:m,structure:a,...t});if(d?.error)return d;let{structureIdsToRemove:l,relatedStructureIdsMap:f}=F3({qualifyingStructureIds:p,isQualifyingStructure:m,isMainStageSequence1:u,mainStageSequence1:c,drawDefinition:r,structureId:n}),{removedMatchUpIds:g,removedStructureIds:I}=k3({relatedStructureIdsMap:f,qualifyingStructureIds:p,isMainStageSequence1:u,mainStageSequence1:c,drawDefinition:r,structureIdsToRemove:l,structureId:n});if(L3({removedMatchUpIds:g,drawDefinition:r}),u){let S=(c.matchUps??[])?.map(Fr("matchUpId"));g.push(...S),c.positionAssignments=[],c.seedAssignments=[],c.matchUps=[],c.extensions&&(c.extensions=[])}return m&&WE({drawDefinition:r}),xn({tournamentId:e?.tournamentId,matchUpIds:g,action:"removeStructure",eventId:o?.eventId,drawDefinition:r}),Ft({drawDefinition:r,eventId:o?.eventId}),{...P,removedMatchUpIds:g,removedStructureIds:I}}function w3({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(te({matchUpFilters:{structureIds:a},drawDefinition:r}).matchUps?.some(({score:p})=>ue({score:p}))){let p=It({tournamentRecord:e,drawDefinition:r,structure:o,event:i})?.appliedPolicies;if(!(s??p?.[Qr]?.allowDeletionWithScoresPresent?.structures))return{error:$c}}return{...P}}function L3({removedMatchUpIds:t,drawDefinition:e}){let{matchUps:r}=te({drawDefinition:e});r?.forEach(n=>{n.winnerMatchUpId&&t.includes(n.winnerMatchUpId)&&delete n.winnerMatchUpId,n.loserMatchUpId&&t.includes(n.loserMatchUpId)&&delete n.loserMatchUpId})}function F3({qualifyingStructureIds:t,isQualifyingStructure:e,isMainStageSequence1:r,mainStageSequence1:n,drawDefinition:o,structureId:i}){let a=(o.structures??[]).map(Fr("structureId")),c=d=>o.links?.map(l=>l.source.structureId===d&&l.target.structureId!==n?.structureId&&l.target.structureId).filter(Boolean)??[],u=d=>o.links?.map(l=>t.includes(l.source.structureId)&&l.target.structureId===d&&l.source.structureId).filter(Boolean)??[],p=new Map;return a.forEach(d=>p.set(d,e?u(d):c(d))),{structureIdsToRemove:r?p.get(i):[i],relatedStructureIdsMap:p}}function k3({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(...B3({idBeingRemoved:u,drawDefinition:o}));let p=V3({qualifyingStructureIds:e,isMainStageSequence1:r,idBeingRemoved:u,drawDefinition:o,structureId:s});a.push(...p.removedStructureIds);let m=G3({relatedStructureIdsMap:t,mainStageSequence1:n,idBeingRemoved:u,structureId:s});m?.length&&i.push(...m)}return{removedMatchUpIds:c,removedStructureIds:a}}function G3({idBeingRemoved:t,relatedStructureIdsMap:e,mainStageSequence1:r,structureId:n}){return t&&e.get(t)?.filter(o=>o!==r?.structureId||n===r.structureId)}function V3({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 B3({idBeingRemoved:t,drawDefinition:e}){let{structure:r}=tt({structureId:t,drawDefinition:e}),n=ht({structure:r}).matchUps;return Ul(n)}var sF="qualifierDrawPositionAssignment",aF="withdrawParticipantAtDrawPosition",cF="alternateDrawPositionAssignment",uF="luckyLoserDrawPositionAssignment",dC="removeDrawPositionAssignment",YE="swapDrawPositionAssignments",pF="modifyPairAssignment",mF="adHocPositionSwap",dF="modifyParticipantOtherName",lC="assignDrawPosition",lF="removeSeededParticipant",fF="assignDrawPositionBye",gF="modifySeedAssignment",IF="seedWithdrawalCascade",jE="addPenalty",MS="MODIFY_PAIR",ud="QUALIFIER",vS="ALTERNATE",OS="WITHDRAW",Qs="ASSIGN",qE="REMOVE",_S="LUCKY",pd="REMOVE_SEED",md="SWAP",jp="NICKNAME",La="SEED_VALUE",Fa="PENALTY",fC="SEED_CASCADE";var SF={MODIFY_PAIR_ASSIGNMENT:MS,QUALIFYING_PARTICIPANT:ud,ALTERNATE_PARTICIPANT:vS,WITHDRAW_PARTICIPANT:OS,ASSIGN_PARTICIPANT:Qs,LUCKY_PARTICIPANT:_S,REMOVE_ASSIGNMENT:qE,SWAP_PARTICIPANTS:md,ADD_NICKNAME:jp,REMOVE_SEED:pd,ADD_PENALTY:Fa,ASSIGN_BYE:"BYE",SEED_CASCADE:fC,SEED_VALUE:La};function gC({tournamentRecord:t,drawDefinition:e,drawPositions:r,structureId:n,event:o}){if(!e)return{error:$};if(!n)return{error:dn};if(r?.length!==2)return{error:O,drawPositions:r};let i=Ie({drawDefinition:e}),{matchUps:s}=te({inContext:!0,drawDefinition:e,matchUpsMap:i}),{structure:a}=tt({drawDefinition:e,structureId:n});if(!a)return{error:Nt};let c=It({tournamentRecord:t,drawDefinition:e,event:o}).appliedPolicies??{},u;if(a.structureType===de?u=Y3({inContextDrawMatchUps:s,tournamentRecord:t,drawDefinition:e,drawPositions:r,matchUpsMap:i,structure:a,event:o}):u=H3({inContextDrawMatchUps:s,tournamentRecord:t,drawDefinition:e,drawPositions:r,matchUpsMap:i,structure:a,event:o}),u.error)return u;if(Cl({structure:a,drawPositions:r}),fc({appliedPolicies:c,drawDefinition:e,positionAction:{name:YE,drawPositions:r,structureId:n}}),Sn({tournamentId:t?.tournamentId,drawDefinition:e,structure:a,event:o}),o.eventType===Ze){let m=ht({matchUpFilters:{matchUpTypes:[Ir]},inContext:!0,structure:a}).matchUps.filter(l=>l.drawPositions?.some(f=>r.includes(f))),d=ht({matchUpFilters:{matchUpTypes:[Ir]},structure:a}).matchUps;m.forEach(l=>{(l.sides??[]).forEach(f=>{let g=f?.drawPosition;if(r.includes(g)){let I=f.participantId,S=d.find(({matchUpId:T})=>T===l.matchUpId),h=l?.sides?.reduce((T,y,E)=>y.drawPosition===g?E:T,void 0);tf({inContextTargetMatchUp:l,drawPositionSideIndex:h,teamParticipantId:I,tournamentRecord:t,drawDefinition:e,matchUp:S,event:o})}})})}return Ft({drawDefinition:e,structureIds:[n]}),{...P}}function H3({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:O,structure:i,info:"Missing positionAssignments"};if(a.filter(({bye:p})=>p).length===2)return{...P};if(a.filter(({qualifier:p})=>p).length===2)return{...P};let c=a.some(({qualifier:p})=>p);return a.some(({bye:p})=>p)&&!c?hF({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,assignments:a,matchUpsMap:o,structure:i,event:s}):W3({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,assignments:a,matchUpsMap:o,structure:i,event:s})}function hF({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=Bp({drawPosition:u,inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,structureId:d,matchUpsMap:o});return l.error||(l=Bp({drawPosition:m,inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,structureId:d,matchUpsMap:o}),l.error)||(Cr({drawPosition:m,tournamentRecord:e,drawDefinition:r,structureId:d,matchUpsMap:o,event:s}),l=vn({drawPosition:u,inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,structureId:d,participantId:p,matchUpsMap:o,event:s}),l.error)?l:{...P}}function W3({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),SS({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,matchUpsMap:o,assignments:n,structure:i,event:s}),{...P}}function Y3({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{...P};if(a.filter(({qualifier:p})=>p).length===2)return{...P};SS({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)hF({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,assignments:a,matchUpsMap:o,structure:i,event:s});else{let p=q(a,!1,!0);a.forEach((m,d)=>{let l=p[1-d].participantId;m.qualifier=p[1-d].qualifier,m.participantId=l})}return{...P}}function IC({tournamentRecord:t,drawDefinition:e,participantId:r,structureId:n}){let o="removeSeededParticipant";if(!t)return{error:j};if(!e)return{error:$};let i=(e.structures??[]).find(a=>a.structureId===n);return i?!i.stage||![H,Z].includes(i.stage)||i.stage===H&&i.stageSequence!==1?M({result:{error:Do},stack:o}):i.seedAssignments?.find(a=>a.participantId===r)?{...P}:M({info:"participant not seeded",result:{error:fe},context:{participantId:r}}):M({result:{error:Nt},stack:o})}function Xs({qualifyingPositions:t,targetEntryRound:e=1,finishingPositions:r,sourceRoundNumber:n,sourceStructureId:o,targetStructureId:i,linkType:s=Er}){return!o||!i?{error:dn}:{link:et({linkType:s,source:{roundNumber:n,structureId:o,qualifyingPositions:t,finishingPositions:r},target:{feedProfile:ln,roundNumber:e,structureId:i}})}}function zi({matchUp:t,tieFormat:e,isMock:r,uuids:n}){let{collectionDefinitions:o}=e??{};return{tieMatchUps:(o??[]).map(s=>qp({matchUp:t,collectionDefinition:s,uuids:n,isMock:r})).filter(Boolean).flat()}}function qp({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()??it();let l=e?.collectionId;return i?.pop()??`${n?.matchUpId}-${l}-TMU-${d+1}`};return Q(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 j3(t,e){return t.drawDefinition?t.drawSize&&!yt(t.drawSize)||t.participantsCount&&!yt(t.participantsCount)||t.qualifyingPositions&&!yt(t.qualifyingPositions)?M({result:{error:O},stack:e}):t.drawSize?t.qualifyingPositions&&t.qualifyingPositions>=t.drawSize?M({result:{error:O},context:{drawSize:t.drawSize,qualifyingPositions:t.qualifyingPositions},stack:e}):null:M({result:{error:Bc},context:{drawSize:t.drawSize},stack:e}):M({result:{error:$},stack:e})}function q3(t,e,r){let{structureProfiles:n}=Yp({drawDefinition:t}),o=n[e];return o||M({result:{error:Nt},context:{targetStructureId:e},stack:r})}function $3(t){let{maxRoundNumber:e,structures:r,groupCount:n}=Ec(t);return{qualifiersCount:n,roundLimit:e,structure:r[0],finishingPositions:[1]}}function K3(t){let{drawSize:e,matchUps:r,roundLimit:n,roundsCount:o}=Tr(t);n||(n=o);let i=lr({structureName:t.structureName,structureId:t.structureId,qualifyingRoundNumber:n,stage:Z,matchUpFormat:t.matchUpFormat,stageSequence:t.stageSequence,matchUpType:t.matchUpType,roundLimit:n,matchUps:r});t.roundTarget&&ut({extension:{name:Rn,value:t.roundTarget},element:i});let s=r?.filter(a=>a.roundNumber===n)?.length??0;return{drawSize:e,structure:i,matchUps:r,roundLimit:n,qualifiersCount:s}}function mf(t){let e="generateQualifyingStructure",r=j3(t,e);if(r)return r;let n=t.drawSize??Jd(t.participantsCount),{hasExistingDrawDefinition:o,qualifyingRoundNumber:i,qualifyingPositions:s,targetStructureId:a,structureOptions:c,appliedPolicies:u,qualifyingOnly:p,drawDefinition:m,matchUpFormat:d,structureName:l,structureId:f,roundTarget:g,tieFormat:I,drawType:S,idPrefix:h,isMock:T,uuids:y}=t,E=q3(m,a,e);if(E?.error)return E;let A=m.matchUpType,N=1,U=g?`${g}-`:"",R=typeof E=="object"&&"stage"in E&&E.stage===Z,D=u?.[Oo]?.namingConventions?.pre??hL[Oo]?.namingConventions?.pre,b=R&&D?`${D}-`:"",C=l??(U?`${b}${xe(Z)} ${U}`:`${b}${xe(Z)}`),_,v,w,L,F;if(S===Hr){let G=$3({structureName:l??C,structureId:f??y?.pop(),hasExistingDrawDefinition:o,stage:Z,structureOptions:c,appliedPolicies:u,qualifyingOnly:p,stageSequence:N,matchUpType:A,roundTarget:g,tieFormat:I,idPrefix:h,drawSize:n,isMock:T,uuids:y});L=G.qualifiersCount,w=G.roundLimit,_=G.structure,F=G.finishingPositions}else{let G=K3({qualifyingRoundNumber:i,qualifyingPositions:s,matchUpType:A,idPrefix:h,drawSize:n,isMock:T,uuids:y,structureName:l??C,structureId:f??y?.pop(),matchUpFormat:d,stageSequence:N,roundTarget:g});n=G.drawSize,_=G.structure,w=G.roundLimit,L=G.qualifiersCount}let x=S===Hr?fn:Er,k=_&&w&&Xs({sourceStructureId:_.structureId,sourceRoundNumber:w,targetStructureId:a,finishingPositions:F,linkType:x})?.link;return I&&(v=ht({structure:_})?.matchUps??[],v?.forEach(G=>{let{tieMatchUps:V}=zi({tieFormat:I,matchUp:G,isMock:T});Object.assign(G,{tieMatchUps:V,matchUpType:A})})),{qualifyingDrawPositionsCount:n,qualifiersCount:L,...P,structure:_,link:k}}function SC(t){if(!t.tournamentRecord)return{error:j};let r=z3(t);return r.error,r}function z3(t){if(!t.drawDefinition)return{error:$};if(!t.targetStructureId)return{error:dn};let e=mf(t);if(e.error)return e;let{structure:r,link:n}=e;return!r||!n?{error:O}:bS({tournamentRecord:t.tournamentRecord,drawDefinition:t.drawDefinition,structure:r,link:n})}function hC({tournamentRecord:t,drawDefinition:e,structureId:r,drawPosition:n,event:o}){if(!e)return{error:$};if(r=r||e.structures?.[0]?.structureId,!r)return{error:O};let{structure:i}=tt({drawDefinition:e,structureId:r});if(!i)return{error:O};if(i.stage!==H||i.stageSequence!==1)return{error:O};if(i.structureType===de)return{error:O};if(qi({drawDefinition:e,structureId:r}).activeDrawPositions?.length)return{error:O};let{positionAssignments:a}=se({structure:i});if(!a)return{error:O};let{seedAssignments:c}=Pr({drawDefinition:e,structure:i});if(!c?.length)return{error:O};let p=a.find(A=>A.drawPosition===n)?.participantId;if(!p)return{error:O};let m=c.find(A=>A.participantId===p);if(!m)return{error:O};let{validSeedBlocks:d}=di({drawDefinition:e,structure:i});if(!d?.length)return{error:O};let l=m.seedNumber,f=d.findIndex(A=>A.seedNumbers.includes(l));if(f<0)return{error:O};let g=[],I=n,S=l;for(let A=f+1;A<d.length;A++){let N=d[A],U=c.filter(C=>N.seedNumbers.includes(C.seedNumber)&&C.participantId).sort((C,_)=>C.seedNumber-_.seedNumber);if(!U.length)break;let R=U[0],D=R.participantId,b=a.find(C=>C.participantId===D);if(!b)break;g.push({replacementParticipantId:D,replacementSeedNumber:R.seedNumber,targetSeedNumber:S,sourceDrawPosition:b.drawPosition,targetDrawPosition:I}),I=b.drawPosition,S=R.seedNumber}for(let A of g){let N=a.find(R=>R.drawPosition===A.targetDrawPosition);N&&(N.participantId=A.replacementParticipantId);let U=c.find(R=>R.seedNumber===A.targetSeedNumber);U&&(U.participantId=A.replacementParticipantId)}let h=g.length?g.at(-1)?.sourceDrawPosition:n,T=a.find(A=>A.drawPosition===h);if(T&&(T.participantId=void 0),g.length===0)m.participantId=void 0;else{let A=g.at(-1),N=c.find(U=>U.seedNumber===A?.replacementSeedNumber);N&&(N.participantId=void 0)}let y=e.entries?.find(A=>A.participantId===p);y&&(y.entryStatus=Cn);let E=t?.tournamentId;return Sn({drawDefinition:e,tournamentId:E,structure:i,event:o}),bl({eventId:o?.eventId,drawDefinition:e,tournamentId:E,structure:i}),{...P,vacatedDrawPosition:h}}function TC(t){let e=X(t,[{[Kt]:!0,[po]:!0,[Or]:!0},{[Fw]:!0,[$e]:m=>Number.isInteger(m)&&m>0},{[$e]:m=>Array.isArray(m)&&m.length===2&&m.every(_t),[_r]:Mr,participantIds:!0}]);if(e.error)return e;let{drawDefinition:r,structureId:n,tournamentRecord:o,event:i}=t,{structure:s}=tt({drawDefinition:r,structureId:n});if(!s)return{error:Nt};if(!Ae({structure:s}))return{error:Do};let a=m=>m.sides?.map(d=>d.participantId).some(d=>t.participantIds.includes(d)),c=m=>m.roundNumber===t.roundNumber,u=m=>!ue(m),p=(s?.matchUps??[]).filter(c).filter(u).filter(a);if(p.length!==2)return{error:Mr};for(let m of p){let d=m?.sides?.find(l=>t.participantIds.includes(l?.participantId));if(d){let l=t.participantIds.find(f=>f!==d?.participantId);d.participantId=l,gt({tournamentId:o?.tournamentId,eventId:i?.eventId,drawDefinition:r,matchUp:m})}}return Ft({drawDefinition:r,structureIds:[n]}),{...P}}var Q3=new Set([Lt,xt,Qt,ge]);function dd({matchUp:t}){if(!t)return{error:Xe};let{winningSide:e,score:r,matchUpStatus:n}=t;if(!e||!r)return{error:O};if(n&&Q3.has(n))return{...P,margin:Number.NaN,setRatio:Number.NaN,gameRatio:Number.NaN,pointRatio:Number.NaN,setsWonByLoser:0,setsWonByWinner:0,gameDifferential:0};let o=r.sets??[],i=e===1?2:1,s=o.filter(A=>A.winningSide===e).length,a=o.filter(A=>A.winningSide===i).length,c=s+a,u=c>0?a/c:Number.NaN,p=!1,m=0,d=0;for(let A of o){let N=e===1?A.side1PointScore:A.side2PointScore,U=e===1?A.side2PointScore:A.side1PointScore;N!=null&&(m+=Number(N),p=!0),U!=null&&(d+=Number(U),p=!0)}let l=m+d,f=p&&l>0?d/l:Number.NaN,{games:g}=Fl({score:r}),I=g[e-1],S=g[i-1],h=I+S,T=h>0?S/h:Number.NaN,y=I-S,E;return Number.isFinite(f)?E=f:Number.isFinite(T)?E=T:E=u,{...P,margin:E,setRatio:u,gameRatio:T,pointRatio:f,setsWonByLoser:a,setsWonByWinner:s,gameDifferential:y}}function df({tournamentRecord:t,drawDefinition:e,structureId:r,cumulativeMargin:n}){if(!e)return{error:$};let o=an(e.drawType);if(r=r||e.structures?.[0]?.structureId,!r)return o?{error:O}:{...P,isLuckyDraw:!1,rounds:[]};let{structure:i}=tt({drawDefinition:e,structureId:r});if(!i)return{error:O};if(!(o||Ic({drawDefinition:e,structure:i})))return{...P,isLuckyDraw:!1,rounds:[]};let a=i.matchUps??[],{roundProfile:c,roundNumbers:u}=De({matchUps:a});if(!c||!u?.length)return{...P,isLuckyDraw:!0,rounds:[]};let p=i.positionAssignments??[],m={};for(let f of p)f.drawPosition&&f.participantId&&(m[f.drawPosition]=f.participantId);let d={};if(t?.participants)for(let f of t.participants)f.participantId&&f.participantName&&(d[f.participantId]=f.participantName);let l=u.map(f=>{let g=c[f],I=a.filter(x=>x.roundNumber===f),S=I.filter(x=>Mt.includes(x.matchUpStatus)||x.winningSide||x.matchUpStatus==="BYE").length,h=S===g.matchUpsCount,y=!(g.matchUpsCount===1)&&g.matchUpsCount%2!==0,E=f+1,N=a.filter(x=>x.roundNumber===E).some(x=>!x.drawPositions||x.drawPositions.filter(Boolean).length<2?!0:x.drawPositions.some(k=>{if(!k)return!0;let G=p.find(V=>V.drawPosition===k);return!G?.participantId&&!G?.bye})),U=y&&h&&N,D=(e.links??[]).filter(x=>x.linkType===ir&&x.source.structureId===r&&(x.source.roundNumber||1)===f).map(x=>{let k=x.target.structureId,G=x.target.roundNumber,{structure:V}=tt({drawDefinition:e,structureId:k}),B=V?.positionAssignments??[],z=(V?.matchUps??[]).filter(Y=>Y.roundNumber===G),W=new Set(z.flatMap(Y=>(Y.drawPositions??[]).filter(Boolean))),K=W.size>0&&[...W].some(Y=>B.some(J=>J.drawPosition===Y&&J.participantId));return{targetStructureId:k,targetRoundNumber:G,feedProfile:x.target.feedProfile,losersPlaced:K}}),b={roundNumber:f,matchUpsCount:g.matchUpsCount,completedCount:S,isComplete:h,isPreFeedRound:y,needsLuckySelection:U,nextRoundHasOpenPosition:N,...D.length&&{consolidationLinks:D}},C=(x,k)=>{let G=x.sides?.find(B=>B.sideNumber===k);if(G)return G.participantId||G.participant?.participantId;let V=x.drawPositions?.[k-1];return V?m[V]:void 0},_=(x,k,G)=>x.sides?.find(B=>B.sideNumber===k)?.participant?.participantName||d[G],v=(x,k)=>{let G=C(x,k);if(!G)return;let V=_(x,k,G),B=dd({matchUp:x});return{participantId:G,participantName:V,matchUpId:x.matchUpId,scoreString:x.score?.scoreStringSide1,margin:B.margin??0,gameRatio:Number.isFinite(B.gameRatio)?B.gameRatio:void 0,pointRatio:Number.isFinite(B.pointRatio)?B.pointRatio:void 0,setRatio:Number.isFinite(B.setRatio)?B.setRatio:void 0,gameDifferential:B.gameDifferential??0,setsWonByLoser:B.setsWonByLoser??0}},w=I.filter(x=>x.winningSide),L=[...I].sort((x,k)=>(x.roundPosition||0)-(k.roundPosition||0)),F=[];for(let x of L)if(x.winningSide){let k=v(x,x.winningSide);k&&F.push(k)}else if(x.matchUpStatus==="BYE"){let k=x.drawPositions??[];for(let G of k){if(!G)continue;let V=p.find(B=>B.drawPosition===G);if(V?.participantId&&!V.bye){F.push({participantId:V.participantId,participantName:d[V.participantId],matchUpId:x.matchUpId,margin:0,gameDifferential:0,setsWonByLoser:0});break}}}if(b.advancingWinners=F,y){let x=w.map(k=>{let G=k.winningSide===1?2:1,V=v(k,G);if(!V||!n)return V;let B=a.filter(K=>{if(!K.roundNumber||K.roundNumber>f||!K.winningSide)return!1;let Y=C(K,1),J=C(K,2);return Y===V.participantId||J===V.participantId}),z=0,W=0;for(let K of B){let Y=dd({matchUp:K});if(Number.isFinite(Y.margin)){let J=C(K,1),ct=J===V.participantId&&K.winningSide!==1||J!==V.participantId&&K.winningSide!==2;z+=ct?Y.margin??0:1-(Y.margin??0),W++}}return W>0&&(V.margin=z/W),V}).filter(k=>!!k).sort((k,G)=>(G.margin??0)!==(k.margin??0)?(G.margin??0)-(k.margin??0):(G.setsWonByLoser??0)-(k.setsWonByLoser??0));b.eligibleLosers=x}return b});return{...P,isLuckyDraw:!0,rounds:l}}var TF="luckyDrawAdvancement";function yC({tournamentRecord:t,drawDefinition:e,participantId:r,structureId:n,roundNumber:o,random:i,event:s}){if(!e)return{error:$};if(n=n||e.structures?.[0]?.structureId,!n)return{error:O};let{structure:a}=tt({drawDefinition:e,structureId:n});if(!a)return{error:O};if(!an(e.drawType)&&!Ic({drawDefinition:e,structure:a}))return M({result:{error:O},info:"Not a lucky draw"});let c=df({tournamentRecord:t,drawDefinition:e,structureId:n});if(c.error)return c;let u=c.rounds?.find(h=>h.roundNumber===o);if(!u?.isComplete)return M({result:{error:O},info:"Round is not complete"});if(u.isPreFeedRound&&u.needsLuckySelection){if(!r)return{error:He};if(!u.eligibleLosers?.find(T=>T.participantId===r))return M({result:{error:O},info:"Participant is not an eligible loser from this round"})}let p=o+1,m=(a.matchUps??[]).filter(h=>h.roundNumber===p).sort((h,T)=>(h.roundPosition||0)-(T.roundPosition||0)),d=u.advancingWinners??[],l=d.map(h=>h.participantId);if(u.isPreFeedRound&&r&&t5({advancingParticipantIds:l,nextRoundMatchUps:m,roundStatus:u,participantId:r,winners:d,random:i}),!m.length)return M({result:{error:O},info:"No matchUps found in next round"});let f=m.length*2;if(l.length!==f)return M({result:{error:O},info:`Expected ${f} advancing participants, got ${l.length}`});let g=a.positionAssignments??[];g=e5({positionAssignments:g,nextRoundMatchUps:m,structure:a,roundNumber:o}),a.positionAssignments=g;let I=Z3({nextRoundMatchUps:m,positionAssignments:g});if(I)return I;let S=t?.tournamentId;return r5({advancingParticipantIds:l,positionAssignments:g,nextRoundMatchUps:m,drawDefinition:e,roundNumber:o,roundStatus:u,participantId:r,tournamentId:S,structureId:n,structure:a}),Sn({drawDefinition:e,tournamentId:S,structure:a,event:s}),u.isPreFeedRound&&r&&J3({drawDefinition:e,tournamentRecord:t,roundStatus:u,participantId:r,structureId:n,roundNumber:o,event:s}),{...P}}function X3({drawDefinition:t,tournamentRecord:e,targetStructureId:r,targetRoundNumber:n,feedProfile:o,participantIds:i,event:s}){let{structure:a}=tt({drawDefinition:t,structureId:r});if(!a)return{error:O};if(Ae({structure:a})&&a.finishingPosition===uo)return{...P};let c=(a.matchUps??[]).filter(d=>d.roundNumber===n).sort((d,l)=>(d.roundPosition||0)-(l.roundPosition||0)),u=a.positionAssignments??[],p=[];a.matchUps??=[],c.length===0?(n5({targetStructure:a,targetStructureId:r,targetRoundNumber:n,participantIds:i,unfilledPositions:p}),c=a.matchUps.filter(d=>d.roundNumber===n).sort((d,l)=>(d.roundPosition||0)-(l.roundPosition||0))):o5({targetMatchUps:c,targetPositionAssignments:u,targetStructure:a,unfilledPositions:p}),o==="BOTTOM_UP"?p.sort((d,l)=>l-d):p.sort((d,l)=>d-l);let m=e?.tournamentId;for(let d=0;d<i.length&&d<p.length;d++){let l=p[d],f=i[d],g=u.find(S=>S.drawPosition===l&&!S.participantId);g?g.participantId=f:u.push({drawPosition:l,participantId:f});let I=c.find(S=>S.drawPositions?.includes(l));I&&gt({context:TF,drawDefinition:t,tournamentId:m,structureId:r,matchUp:I})}return a.positionAssignments=u,Sn({drawDefinition:t,tournamentId:m,structure:a,event:s}),{...P}}function J3({drawDefinition:t,tournamentRecord:e,roundStatus:r,participantId:n,structureId:o,roundNumber:i,event:s}){let a=(r.eligibleLosers??[]).filter(u=>u.participantId!==n).map(u=>u.participantId);if(!a.length)return;let c=(t.links??[]).filter(u=>u.linkType===ir&&u.source.structureId===o&&(u.source.roundNumber||1)===i);for(let u of c){let p=X3({drawDefinition:t,tournamentRecord:e,targetStructureId:u.target.structureId,targetRoundNumber:u.target.roundNumber,feedProfile:u.target.feedProfile,participantIds:a,event:s});p?.error&&je()&&console.warn("Failed to place discarded losers in consolidation structure:",p.error)}}function Z3({nextRoundMatchUps:t,positionAssignments:e}){for(let r of t){let n=r.drawPositions;if(!n?.length)continue;if(n.filter(i=>i?e.some(s=>s.drawPosition===i&&s.participantId):!1).length)return M({result:{error:O},info:"Next round already has participants assigned"});n.some(Boolean)&&(r.drawPositions=[]),r.matchUpStatus&&r.matchUpStatus!=="TO_BE_PLAYED"&&(r.matchUpStatus=void 0,r.winningSide=void 0,r.score=void 0)}}function t5({advancingParticipantIds:t,nextRoundMatchUps:e,roundStatus:r,participantId:n,winners:o,random:i}){let s=r.eligibleLosers?.find(d=>d.participantId===n),a=s?o.findIndex(d=>d.matchUpId===s.matchUpId):-1,c=e.length,u=Math.ceil(c/2);if(a<0||c<=1){t.push(n);return}let p=c*2,m=[];for(let d=0;d<p;d++){let l=Math.floor(d/2),f=a+(d<=a?1:0),g=Math.floor(f/2),I=l<u,S=g<u;I!==S&&m.push(d)}if(m.length){let d=Math.floor((i??Math.random)()*m.length);t.splice(m[d],0,n)}else t.push(n)}function e5({positionAssignments:t,nextRoundMatchUps:e,structure:r,roundNumber:n}){let o=new Set(e.flatMap(s=>(s.drawPositions??[]).filter(Boolean)));if(o.size){let s=[];for(let a of o){let c=t.filter(p=>p.drawPosition===a),u=c.some(p=>!p.participantId&&!p.bye);(c.length>1||u)&&s.push(a)}if(s.length){let a=new Set(s);t=t.filter(c=>!a.has(c.drawPosition))}}let i=new Set((r.matchUps??[]).filter(s=>s.roundNumber&&s.roundNumber<=n).flatMap(s=>s.drawPositions??[]).filter(Boolean));return t=t.filter(s=>s.participantId||s.bye?!0:i.has(s.drawPosition)),t}function r5({advancingParticipantIds:t,positionAssignments:e,nextRoundMatchUps:r,drawDefinition:n,roundNumber:o,roundStatus:i,participantId:s,tournamentId:a,structureId:c,structure:u}){let p=new Set(e.map(g=>g.drawPosition)),m=(u.matchUps??[]).flatMap(g=>g.drawPositions??[]).filter(Boolean),d=[...p,...m],f=(d.length?Math.max(...d):0)+1;for(let g=0;g<r.length;g++){let I=r[g],S=f++,h=f++,T=t[g*2],y=t[g*2+1];I.drawPositions=[S,h];let E={drawPosition:S,participantId:T},A={drawPosition:h,participantId:y};i.isPreFeedRound&&s&&(T===s?E.extensions=[{name:"luckyAdvancement",value:{fromRoundNumber:o}}]:y===s&&(A.extensions=[{name:"luckyAdvancement",value:{fromRoundNumber:o}}])),e.push(E,A),gt({context:TF,drawDefinition:n,tournamentId:a,structureId:c,matchUp:I})}u.positionAssignments=e}function n5({targetStructure:t,targetStructureId:e,targetRoundNumber:r,participantIds:n,unfilledPositions:o}){let i=Math.ceil(n.length/2),s=1;for(let a=0;a<i;a++){let c=s++,u=s++,p={matchUpId:`${e}-mu-${a+1}`,roundNumber:r,roundPosition:a+1,drawPositions:[c,u],matchUpStatus:"TO_BE_PLAYED"};t.matchUps.push(p),o.push(c,u)}}function o5({targetMatchUps:t,targetPositionAssignments:e,targetStructure:r,unfilledPositions:n}){for(let o of t)for(let i of o.drawPositions??[]){if(!i)continue;let s=e.find(a=>a.drawPosition===i);!s?.participantId&&!s?.bye&&n.push(i)}if(!n.length){let o=new Set(e.filter(c=>c.participantId).map(c=>c.drawPosition)),i=(r.matchUps??[]).flatMap(c=>c.drawPositions??[]).filter(c=>c&&o.has(c)),s=[...o,...i],a=s.length?Math.max(...s)+1:1;for(let c of t)if(!c.drawPositions?.length||!c.drawPositions.some(Boolean)){let u=a++,p=a++;c.drawPositions=[u,p],n.push(u,p)}}}function yF(t){let e="generateAndPopulateRRplayoffStructures";if(!t.playoffGroups)return M({result:{error:nt},info:"playoffGroups required",stack:e});let{sourceStructureId:r,requireSequential:n,tournamentRecord:o,drawDefinition:i,playoffGroups:s,groupCount:a,groupSize:c,event:u}=t,p=uf({requireSequential:n,sourceStructureId:r,playoffGroups:s,groupCount:a,groupSize:c,...t});if(p.error)return M({result:p,stack:e});let{structures:m=[],links:d=[],finishingPositionTargets:l,positionRangeMap:f}=p,g=l?.flatMap(({finishingPositions:U})=>U).flatMap(U=>f[U].finishingPositions);i.structures.push(...m),i.links.push(...d);let{matchUps:I,matchUpsMap:S}=te({inContext:!0,drawDefinition:i}),h=new Set(m.map(({structureId:U})=>U)),T=I?.filter(({structureId:U})=>h.has(U)).map(Te),y=S?.drawMatchUps?.filter(({matchUpId:U})=>T?.includes(U));if(y?.length){let U=ze({drawDefinition:i,event:u})?.tieFormat;U&&y.forEach(R=>{let{tieMatchUps:D}=zi({isMock:t.isMock,tieFormat:U,matchUp:R});Object.assign(R,{tieMatchUps:D,matchUpType:Ir})})}let{positionAssignments:E}=Pt({structureId:r,drawDefinition:i}),A={};E?.forEach(U=>{let b=ot({element:U,name:Lo})?.extension?.value?.groupOrder;b&&(A[b]||(A[b]=[]),A[b].push(U.participantId))});let N=wa({provisionalPositioning:t.provisionalPositioning,structureId:r,applyPositioning:!0,event:t.event,tournamentRecord:o,drawDefinition:i});return N.error&&N.error?.code!==_g.code?M({result:N,stack:e}):{structures:m,links:d,positionsPlayedOff:g,drawDefinition:i,...P}}function lf({positionAssignments:t,tournamentRecord:e,drawDefinition:r,matchUpFormat:n,matchUps:o,event:i}){if(!Nr(o))return{error:O};if(!t)return{error:O};let{policyDefinitions:s}=lo({policyTypes:[bI],tournamentRecord:e,drawDefinition:r,event:i}),{subOrderMap:a}=Xl({positionAssignments:t}),c=o.length?Ks({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:Lo};ut({element:l,extension:g}),u[f].ties||dr({element:l,name:au})}else dr({element:l,name:Lo}),dr({element:l,name:au})}),Ft({drawDefinition:r}),{...P,participantResults:u,bracketComplete:p,report:m}}function $E({matchUps:t,matchUpId:e}){return{matchUp:(t??[]).find(n=>n.matchUpId===e)}}function Ht(t){let e=X(t,[{[Kt]:!0,[Or]:!0}]);if(e.error)return e;let{tournamentParticipants:r,participantsProfile:n,afterRecoveryTimes:o,contextProfile:i,drawDefinition:s,matchUpsMap:a,matchUpId:c,inContext:u,context:p,event:m}=t,{structures:d=[]}=In({drawDefinition:s}),l=t.contextContent||i&&to({contextProfile:i,drawDefinition:s});for(let f of d){let{matchUps:g}=ht({tournamentParticipants:r,participantsProfile:n,afterRecoveryTimes:o,contextContent:l,drawDefinition:s,contextProfile:i,matchUpsMap:a,inContext:u,structure:f,context:p,event:m}),{matchUp:I}=$E({matchUps:g,matchUpId:c});if(I)return{matchUp:I,structure:f}}return{error:Be}}function ld(t){return!Tt(t)||!t.notes?{error:nt}:Tt(t.element)?!_t(t.notes)&&!t.notes?.testing?{error:O}:(Object.assign(t.element,{notes:t.notes}),{...P}):{error:O}}function xS(t){return Tt(t)?Tt(t.element)?(t.element.notes&&delete t.element.notes,{...P}):{error:O}:{error:nt}}var ka={matchUpStatus:zt,matchUpStatusCodes:[],score:{scoreStringSide1:"",scoreStringSide2:"",sets:void 0},matchUpFormat:void 0,winningSide:void 0};function Ln(t){let e="modifyMatchUpScore",r=t.matchUpFormat,n=t.matchUp,o,{matchUpStatusCodes:i,tournamentRecord:s,drawDefinition:a,matchUpStatus:c,removeScore:u,winningSide:p,matchUpId:m,event:d,notes:l,score:f}=t,g=i5({appliedPolicies:t.appliedPolicies,tournamentRecord:s,drawDefinition:a,structure:o,event:d}),I=n.matchUpType===Ot,S=s5({isDualMatchUp:I,drawDefinition:a,matchUpId:m,matchUp:n,event:d});if(S?.error)return S;S&&({matchUp:n,structure:o}=S);let h=c&&n?.matchUpStatus===xt&&c!==xt;a5({matchUpStatusCodes:i,removeWinningSide:t.removeWinningSide,matchUpStatus:c,matchUpFormat:r,removeScore:u,winningSide:p,matchUp:n,score:f}),!o&&a&&({structure:o}=Ht({drawDefinition:a,matchUpId:m,event:d})),c5({matchUpStatus:c,matchUp:n});let T;(h&&n?.processCodes?.length||c===xt)&&(T=g?.[Qr]?.processCodes?.incompleteAssignmentsOnDefault);let y=u5({isDualMatchUp:I,tournamentRecord:s,drawDefinition:a,matchUpFormat:r,matchUpId:m,structure:o,matchUp:n,event:d});if(y?.error)return M({result:y,stack:e});if(a&&n.winningSide){let{competitionPolicy:N}=To({tournamentRecord:s,drawDefinition:a,event:d});N?.processingGranularity==="PER_MATCHUP"&&Km({tournamentRecord:s,drawDefinition:a,matchUp:n,event:d})}if(l){let N=ld({element:n,notes:l});if(N.error)return M({result:N,stack:e})}let E=s?.tournamentId,A=p5({defaultedProcessCodes:T,tournamentRecord:s,drawDefinition:a,matchUpId:m});return A&&br().topics.includes(Up)&&sL({tournamentId:E,inContextMatchUp:A}),m5({defaultedProcessCodes:T,inContextMatchUp:A,matchUpStatus:c,matchUp:n}),gt({eventId:d?.eventId,context:e,drawDefinition:a,tournamentId:E,matchUp:n}),{...P}}function i5({appliedPolicies:t,tournamentRecord:e,drawDefinition:r,structure:n,event:o}){return t&&Object.keys(t).length?t:It({policyTypes:[Qr],tournamentRecord:e,drawDefinition:r,structure:n,event:o})?.appliedPolicies}function s5({isDualMatchUp:t,drawDefinition:e,matchUpId:r,matchUp:n,event:o}){if(t&&e){if(r&&n.matchUpId!==r){let i=Ht({drawDefinition:e,matchUpId:r,event:o});return i.matchUp?{matchUp:i.matchUp,structure:i.structure}:{error:Be}}return}n.matchUpId!==r&&console.log("!!!!!")}function a5({matchUpStatusCodes:t,removeWinningSide:e,matchUpStatus:r,matchUpFormat:n,removeScore:o,winningSide:i,matchUp:s,score:a}){r&&new Set([Lt,Qt]).has(r)||o?Object.assign(s,{...ka}):a&&(s.score=a),r&&(s.matchUpStatus=r),n&&(s.matchUpFormat=n),t&&(s.matchUpStatusCodes=t),i&&(s.winningSide=i),e&&(s.winningSide=void 0)}function c5({matchUpStatus:t,matchUp:e}){let r=new Set([cu,Fi,Xr]);t&&!e.winningSide&&ue(e)&&!Mt.includes(t)&&!r.has(t)&&(e.matchUpStatus=bn)}function u5({isDualMatchUp:t,tournamentRecord:e,drawDefinition:r,matchUpFormat:n,matchUpId:o,structure:i,matchUp:s,event:a}){if(s.collectionId)return;let c=i?.structureType===de,u=Ae({structure:i});if(!Ic({drawDefinition:r,structure:i})&&!u&&!c)return;let p=t?"SET1-S:T100":n??s.matchUpFormat??i?.matchUpFormat??r?.matchUpFormat??a?.matchUpFormat,m=t?{matchUpTypes:[Ot]}:void 0,d=c&&i.structures.find(g=>g?.matchUps.find(I=>I.matchUpId===o))||i,{matchUps:l}=ht({structure:d,afterRecoveryTimes:!1,tournamentRecord:e,inContext:!0,matchUpFilters:m,drawDefinition:r,event:a});u&&(d.positionAssignments=pt(l.flatMap(g=>(g.sides??[]).map(I=>I.participantId)).filter(Boolean)).map(g=>({participantId:g})));let f=lf({positionAssignments:d.positionAssignments,matchUpFormat:p,tournamentRecord:e,drawDefinition:r,matchUps:l,event:a});return f.error?f:{matchUpFormat:p}}function p5({defaultedProcessCodes:t,tournamentRecord:e,drawDefinition:r,matchUpId:n}){if(!br().topics.includes(Up)&&!t)return;let i=Ie({drawDefinition:r});if(i)return te({matchUpFilters:{matchUpIds:[n]},nextMatchUps:!0,tournamentRecord:e,inContext:!0,drawDefinition:r,matchUpsMap:i}).matchUps?.[0]}function m5({defaultedProcessCodes:t,inContextMatchUp:e,matchUpStatus:r,matchUp:n}){if(!(!Array.isArray(t)||!e)&&!e.sides?.every(({participantId:o})=>o))if(r===xt)n.processCodes=pt([...n.processCodes??[],...t]);else for(let o of t??[]){let i=o&&n?.processCodes?.lastIndexOf(o);n?.processCodes?.splice(i,1)}}function ff(t){let{propagateExitStatus:e,matchUpStatusCodes:r,autoCalcDisabled:n,inContextMatchUp:o,matchUpStatus:i,dualMatchUp:s,structure:a,matchUp:c}=t,u=Oa({matchUpStatus:i})||[Zn,xr].includes(i)&&s||n,p=c?.sides?.map(S=>S.participantId).filter(Boolean).length||o?.sides?.map(S=>S.participantId).filter(Boolean).length,m="attemptToModifyScore";if(!(Ae({structure:a})&&p===1||i===xt&&p||d5({structure:a,matchUp:c,inContextMatchUp:o})||t.appliedPolicies?.[Qr]?.requireParticipantsForScoring===!1||Ye(i)&&p===1&&e))return M({result:{error:kg},stack:m});let f=[Lt].includes(i),g=u?i:t.winningSide&&ie||Xr,I=Ln({...t,winningSide:t.winningSide,matchUpStatusCodes:(u&&r)??[],matchUpStatus:g,context:m,removeScore:f});return M({result:I,stack:m})}function d5({structure:t,matchUp:e,inContextMatchUp:r}){let{drawPositions:n}=e,{positionAssignments:o}=se({structure:t}),i=o?.filter(a=>n?.includes(a.drawPosition)&&a.participantId),s=r?.sides?.every(a=>a.participantId);return i?.length===2||s}function KE({collectionGroups:t=[]}){let e=Object.assign({},...t.filter(n=>yt(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=>st(n));return{groupValueGroups:e,groupValueNumbers:r}}function EF({collectionDefinition:t,groupValueNumbers:e,groupValueGroups:r,sideTieValues:n,tieMatchUps:o}){let i=o.filter(h=>h.collectionId===t.collectionId),s=[0,0],a=[0,0],c=i.every(h=>Mt.includes(h.matchUpStatus)),{collectionValueProfiles:u,collectionGroupNumber:p,collectionValue:m,matchUpValue:d,winCriteria:l,scoreValue:f,setValue:g}=t,I=p&&e.includes(p),S=[0,0];i.forEach(h=>{h.winningSide&&(S[h.winningSide-1]+=1)}),l5({collectionDefinition:t,collectionMatchUps:i,sideMatchUpValues:s,collectionValueProfiles:u,matchUpValue:d,scoreValue:f,setValue:g}),a=I5({allCollectionMatchUpsCompleted:c,collectionDefinition:t,sideCollectionValues:a,belongsToValueGroup:I,sideMatchUpValues:s,groupValueGroups:r,collectionGroupNumber:p,collectionValue:m,matchUpValue:d,winCriteria:l,scoreValue:f,setValue:g,sideWins:S}),I?(r[p].sideWins[0]+=S[0]||0,r[p].sideWins[1]+=S[1]||0,r[p].allGroupMatchUpsCompleted=r[p].allGroupMatchUpsCompleted&&c,r[p].matchUpsCount+=i.length):a.forEach((h,T)=>n[T]+=h||0)}function l5({collectionDefinition:t,collectionMatchUps:e,sideMatchUpValues:r,collectionValueProfiles:n,matchUpValue:o,scoreValue:i,setValue:s}){yt(o)?e.forEach(a=>{a.winningSide&&(r[a.winningSide-1]+=o)}):yt(s)?e.forEach(a=>{a.score?.sets?.forEach(c=>{c.winningSide&&(r[c.winningSide-1]+=s)})}):yt(i)?f5({collectionMatchUps:e,sideMatchUpValues:r}):Array.isArray(n)&&g5({collectionMatchUps:e,collectionDefinition:t,sideMatchUpValues:r})}function f5({collectionMatchUps:t,sideMatchUpValues:e}){t.forEach(r=>{r.score?.sets?.forEach(n=>{let{side1TiebreakScore:o=0,side2TiebreakScore:i=0,side1Score:s=0,side2Score:a=0}=n;(r.matchUpStatus===ie||r.winningSide||n.winningSide)&&(s||a?(e[0]+=s,e[1]+=a):(o||i)&&n.winningSide&&(e[n.winningSide-1]+=1))})})}function g5({collectionMatchUps:t,collectionDefinition:e,sideMatchUpValues:r}){t.forEach(n=>{if(n.winningSide){let o=n.collectionPosition,i=h5({collectionDefinition:e,collectionPosition:o});yt(i)&&(r[n.winningSide-1]+=i)}})}function I5({allCollectionMatchUpsCompleted:t,collectionDefinition:e,sideCollectionValues:r,belongsToValueGroup:n,sideMatchUpValues:o,groupValueGroups:i,collectionGroupNumber:s,collectionValue:a,matchUpValue:c,winCriteria:u,scoreValue:p,setValue:m,sideWins:d}){if(yt(a)){let l=S5({allCollectionMatchUpsCompleted:t,collectionDefinition:e,sideMatchUpValues:o,matchUpValue:c,winCriteria:u,scoreValue:p,setValue:m,sideWins:d});l&&(n?i[s].values[l-1]+=a:r[l-1]+=a)}else n?(i[s].values[0]+=o[0]||0,i[s].values[1]+=o[1]||0):r=o;return r}function S5({allCollectionMatchUpsCompleted:t,collectionDefinition:e,sideMatchUpValues:r,matchUpValue:n,winCriteria:o,scoreValue:i,setValue:s,sideWins:a}){if(o?.aggregateValue){if(t){if(yt(n||s||i)&&r[0]!==r[1])return r[0]>r[1]?1:2;if(a[0]!==a[1])return a[0]>a[1]?1:2}return}if(o?.valueGoal)return r.reduce((u,p,m)=>p>=o.valueGoal?m+1:u,0);let c=Math.floor(e.matchUpCount/2)+1;return a.reduce((u,p,m)=>p>=c?m+1:u,0)}function h5({collectionDefinition:t,collectionPosition:e}){return(t.collectionValueProfiles??[])?.find(o=>o.collectionPosition===e)?.matchUpValue}function bu(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||Number.isNaN(e.reduce((I,S)=>I+S)))return{error:O};if(!s)return{error:Xe};let c=ze({matchUp:s,drawDefinition:n,structure:i,event:a})?.tieFormat||t?.tieFormat;if(!c)return{error:la};let u=or({tieFormat:c});if(u.error)return u;let m=T5(c,s).map((I,S)=>(I||0)+e[S]),d={side1Score:m[0],side2Score:m[1],winningSide:void 0},l=m.join(r),f=m.slice().reverse().join(r),g=E5({drawDefinition:n,matchUpsMap:o,sideScores:m,tieFormat:c,matchUp:s});return g&&(d.winningSide=g),{scoreStringSide1:l,scoreStringSide2:f,winningSide:g,set:d}}function T5(t,e){let r=t?.collectionDefinitions??[],n=e?.tieMatchUps??[],o=[0,0],{groupValueGroups:i,groupValueNumbers:s}=KE(t);for(let a of r)EF({collectionDefinition:a,groupValueNumbers:s,groupValueGroups:i,sideTieValues:o,tieMatchUps:n});for(let a of s){let c=y5(i[a]);c&&(o[c-1]+=i[a].groupValue||0)}return o}function y5(t){let{allGroupMatchUpsCompleted:e,matchUpCount:r,winCriteria:n,sideWins:o,values:i}=t;if(n?.aggregateValue)return e&&i[0]!==i[1]?i[0]>i[1]?1:2:void 0;if(n?.valueGoal)return i.reduce((a,c,u)=>c>=n.valueGoal?u+1:a,void 0);let s=Math.floor(r/2)+1;return o.reduce((a,c,u)=>c>=s?u+1:a,void 0)}function E5({drawDefinition:t,matchUpsMap:e,sideScores:r,tieFormat:n,matchUp:o}){if(!n?.winCriteria)return;let{valueGoal:i,aggregateValue:s,tallyDirectives:a}=n.winCriteria,c=o?.tieMatchUps??[],u;return i?u=A5(r,i):s&&(u=P5(c,r)),!u&&a&&(u=N5({drawDefinition:t,matchUpsMap:e,matchUp:o})),u}function A5(t,e){return t.map((n,o)=>({sideNumber:o+1,points:n})).find(({points:n})=>n>=e)?.sideNumber}function P5(t,e){if(t.every(n=>n.matchUpStatus&&Mt.includes(n.matchUpStatus)||n.winningSide)&&e[0]!==e[1])return e[0]>e[1]?1:2}function N5({drawDefinition:t,matchUpsMap:e,matchUp:r}){let n=r.matchUpId,o=r.hasContext?r:e?.drawMatchUps?.[n]||t&&Ht({inContext:!0,drawDefinition:t,matchUpId:n})?.matchUp;if(!o)return;let{completedTieMatchUps:i,order:s}=Ks({matchUps:[o]});if(!i||!s?.length)return;let a=s[0].participantId;return o.sides.find(({participantId:c})=>c===a)?.sideNumber}function Pc({inContextDualMatchUp:t,drawDefinition:e,tournamentId:r,dualMatchUp:n,eventId:o}){if(n){t||(t=Ht({matchUpId:n.matchUpId,inContext:!0,drawDefinition:e})?.matchUp);let{extension:i}=ot({element:e,name:wo}),s=q(i?.value??{},!1,!0),a=({displaySideNumber:c,drawPosition:u,sideNumber:p})=>({drawPosition:u,sideNumber:p,displaySideNumber:c});n.sides=t?.sides?.map(c=>{let u=c.participantId,p=u&&s[u]||void 0,{lineUp:m,...d}=n.sides?.find(({sideNumber:f})=>f===c.sideNumber)??{},l=m?.length?m:p;return{...a(c),...d,lineUp:l}}),gt({context:"ensureSidLineUps",matchUp:n,drawDefinition:e,tournamentId:r,eventId:o})}}function nr(t){if(t)return q(t,!1,!0)}function wS(t){let e=X(t,[{[Ee]:!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 zE({tournamentRecords:t,eventId:e,drawId:r}){let{tournamentIdMap:n}=wS({tournamentRecords:t});return(n?Object.keys(n):[]).find(i=>e&&n?.[i].includes(e)||r&&n?.[i].includes(r))}function Io(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&&zE({tournamentRecords:c,...t});let p=u&&c[u];if(!p)return{error:j};let m=Ht({drawDefinition:r,event:a,matchUpId:s});if(m.error)return m;if(!m.matchUp)return{error:Be};let{matchUp:d,structure:l}=m;if(!d.tieMatchUps)return{error:cr};Pc({tournamentId:p?.tournamentId,eventId:a?.eventId,dualMatchUp:d,drawDefinition:r});let{extension:f}=ot({name:cc,element:d});if(f?.value)if(o)dr({element:d,name:cc});else return{...P,score:d.score};let g=ze({drawDefinition:r,structure:l,matchUp:d,event:a})?.tieFormat;d.tieFormat=nr(g);let I=bu({drawDefinition:r,matchUpsMap:i,structure:l,matchUp:d,event:a}),{winningSide:S,set:h,scoreStringSide1:T,scoreStringSide2:y}=I,E=h?.side1Score||h?.side2Score;if(e&&!d.score&&!E)return{...P};let A={scoreStringSide1:T,scoreStringSide2:y,sets:h?[h]:[]},N=S&&[1,2].includes(S),U=N&&ie||sS({matchUpStatus:n??d.matchUpStatus,tieMatchUps:d.tieMatchUps,winningSide:d.winningSide,score:A})&&bn||zt,R=!!(d.winningSide&&!N),D=d.tieMatchUps.find(({score:C,winningSide:_,matchUpStatus:v})=>C?.sets?.length&&(C.sets[0].side1Score||C.sets[0].side2Score)||v&&Mt.includes(v)||_),b;if(d.tieFormat&&!N&&!D){let C=ze({drawDefinition:r,structure:l,event:a})?.tieFormat;C&&JSON.stringify(g)===JSON.stringify(C)&&(d.tieFormatId=void 0,d.tieFormat=void 0,b=!0)}return Ln({appliedPolicies:t.appliedPolicies,matchUpStatus:U,score:A,removeWinningSide:R,tournamentRecord:p,drawDefinition:r,removeScore:o,winningSide:S,matchUpId:s,matchUp:d,event:a}),{...P,score:A,removeWinningSide:R,tieFormatRemoved:b,winningSide:S}}function AF({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=U5({winnerMatchUpDrawPositionIndex:t,inContextDrawMatchUps:e,sourceMatchUpStatus:n,winningDrawPosition:o,tournamentRecord:i,winnerTargetLink:s,sourceMatchUpId:a,drawDefinition:c,winnerMatchUp:u,matchUpsMap:m,event:d,stack:l});if(f?.error)return f}else{let f=Ac({matchUpId:u.matchUpId,drawPosition:o,inContextDrawMatchUps:e,sourceMatchUpStatus:n,tournamentRecord:i,sourceMatchUpId:a,drawDefinition:c,matchUpsMap:m});if(f.error)return f}return p&&r&&D5({projectedWinningSide:r,tournamentRecord:i,drawDefinition:c,winnerMatchUp:u,dualMatchUp:p,matchUpsMap:m,stack:l}),{...P}}function U5({winnerMatchUpDrawPositionIndex:t,inContextDrawMatchUps:e,sourceMatchUpStatus:r,winningDrawPosition:n,tournamentRecord:o,winnerTargetLink:i,sourceMatchUpId:s,drawDefinition:a,winnerMatchUp:c,matchUpsMap:u,event:p,stack:m}){let d=c.drawPositions??[],l=d[t],f=i.source.structureId,g=tt({structureId:f,drawDefinition:a});if(g.error)return g;let{structure:I}=g,{positionAssignments:S}=se({structureId:f,drawDefinition:a}),T=S?.find(D=>D.drawPosition===n)?.participantId,y=i.target.structureId,{positionAssignments:E}=se({structureId:y,drawDefinition:a}),N=E?.find(D=>D.participantId===T)?.drawPosition,U=E?.filter(D=>{let b=d.includes(D.drawPosition),C=!D.participantId&&!D.bye&&!D.qualifier;return b&&C}).map(D=>D.drawPosition),R=U?.includes(l);if(T&&i.target.roundNumber===1&&R)vn({drawPosition:l,participantId:T,structureId:y,inContextDrawMatchUps:e,sourceMatchUpStatus:r,tournamentRecord:o,drawDefinition:a,matchUpsMap:u,event:p});else if(T&&U?.length){let D=U.pop();D&&vn({participantId:T,structureId:y,inContextDrawMatchUps:e,sourceMatchUpStatus:r,tournamentRecord:o,drawDefinition:a,drawPosition:D,matchUpsMap:u,event:p})}else if(N){let D=Ac({drawPosition:N,matchUpId:c.matchUpId,inContextDrawMatchUps:e,sourceMatchUpStatus:r,tournamentRecord:o,sourceMatchUpId:s,drawDefinition:a,matchUpsMap:u});if(D.error)return M({result:D,stack:m})}else if(I?.stage!==Z){let D="winner target position unavaiallble";console.log(D),M({stack:m,result:{error:D}})}if(I?.seedAssignments&&I.structureId!==y){let D=I.seedAssignments.find(({participantId:C})=>C===T),b=D?.participantId;D&&b&&xa({eventId:c?.eventId,structureId:y,...D,tournamentRecord:o,drawDefinition:a,participantId:b})}}function D5({projectedWinningSide:t,tournamentRecord:e,drawDefinition:r,winnerMatchUp:n,dualMatchUp:o,matchUpsMap:i,stack:s}){let a=o.sides?.find(f=>f.sideNumber===t);if(!a?.lineUp)return;let c=o.roundPosition,u=n.roundPosition,p=c===u&&c!==1||Math.floor(c/2)===u?2:1,m=i?.drawMatchUps?.find(({matchUpId:f})=>f===n.matchUpId),d=[1,2].map(f=>({...m.sides?.find(I=>I.sideNumber===f)??{},sideNumber:f}));m.sides=d;let l=m.sides.find(f=>f.sideNumber===p);if(l){let f=a.lineUp?.filter(g=>g?.participantId);l.lineUp=rf({lineUp:f}),gt({tournamentId:e?.tournamentId,eventId:n?.eventId,matchUp:m,context:s,drawDefinition:r})}}function PF(t){let{loserMatchUpDrawPositionIndex:e,inContextDrawMatchUps:r,projectedWinningSide:n,propagateExitStatus:o,sourceMatchUpStatus:i,loserDrawPosition:s,tournamentRecord:a,loserTargetLink:c,drawDefinition:u,loserMatchUp:p,dualMatchUp:m,matchUpsMap:d,event:l}=t,f="directLoser",g=c.linkCondition,I=p.drawPositions??[],S=g===Bn&&p.roundNumber===2&&Math.min(...I.filter(Boolean)),h=S||I[e],T=S||I[1-e],y=c.source.structureId,{structure:E}=tt({structureId:y,drawDefinition:u}),{matchUps:A}=ht({afterRecoveryTimes:!1,inContext:!0,drawDefinition:u,structure:E,event:l}),U=A.filter(W=>W.drawPositions?.includes(s)).filter(W=>{let K=W.sides.find(J=>J.drawPosition===s),Y=W.matchUpStatus===Lt||W.matchUpStatus===xt&&!ue(W);return K?.sideNumber===W.winningSide&&!Y}),R=g===Bn&&U.length===0,{positionAssignments:D}=se({structureId:y,drawDefinition:u}),C=D?.find(W=>W.drawPosition===s)?.participantId,_={loserParticipantId:C},v=c.target.structureId,{positionAssignments:w}=se({structureId:v,drawDefinition:u}),L=w?.filter(({drawPosition:W})=>I.includes(W)),F=L?.some(W=>W.participantId&&C&&W.participantId===C),x=o&&[Ue,Lt,xt].includes(i||"");if(F)return{...P,stack:f};let k=L?.filter(W=>{let K=I.includes(W.drawPosition),Y=!W.participantId&&!W.bye&&!W.qualifier;return K&&Y}).map(W=>W.drawPosition),G=k?.includes(h),V=c.target.roundNumber>1&&k?.length,B=c.target.roundNumber===1&&G,z=R5({fedDrawPositionFMLC:S,isFirstRoundValidDrawPosition:B,loserParticipantId:C,isFeedRound:V,unfilledTargetMatchUpDrawPositions:k,targetDrawPositionIsUnfilled:G,validForConsolation:R,targetMatchUpDrawPosition:h,loserBackdrawPosition:T,targetStructureId:v,inContextDrawMatchUps:r,sourceMatchUpStatus:i,validExitToPropagate:x,propagateExitStatus:o,loserDrawPosition:s,loserTargetLink:c,tournamentRecord:a,drawDefinition:u,matchUpsMap:d,event:l});return z.context&&Object.assign(_,z.context),z.error?M({result:z,stack:f}):z.earlyReturn?z.earlyReturn:(b5({loserParticipantId:C,targetStructureId:v,tournamentRecord:a,drawDefinition:u,loserMatchUp:p,structure:E}),C5({projectedWinningSide:n,tournamentRecord:a,drawDefinition:u,loserMatchUp:p,dualMatchUp:m,matchUpsMap:d,stack:f}),M({result:{...P},stack:f,context:_}))}function R5({fedDrawPositionFMLC:t,isFirstRoundValidDrawPosition:e,loserParticipantId:r,isFeedRound:n,unfilledTargetMatchUpDrawPositions:o,targetDrawPositionIsUnfilled:i,validForConsolation:s,targetMatchUpDrawPosition:a,loserBackdrawPosition:c,targetStructureId:u,inContextDrawMatchUps:p,sourceMatchUpStatus:m,validExitToPropagate:d,propagateExitStatus:l,loserDrawPosition:f,loserTargetLink:g,tournamentRecord:I,drawDefinition:S,matchUpsMap:h,event:T}){let y=()=>{let A=r?vn({drawPosition:a,participantId:r,structureId:u,inContextDrawMatchUps:p,sourceMatchUpStatus:m,tournamentRecord:I,drawDefinition:S,matchUpsMap:h,event:T}):{error:He};return!A.error&&d&&l?{context:{progressExitStatus:!0}}:M({result:A,stack:"assignLoserDrawPosition"})};if(t){let A="loserLinkFedFMLC";if(s)return M({result:y(),stack:A});let N=Cr({drawPosition:c,structureId:u,tournamentRecord:I,drawDefinition:S,event:T});return M({result:M({result:N,stack:"assignLoserPositionBye"}),stack:A})}if(e)return y();if(r&&(n||o?.length)){o.sort(Zt);let A=o[0],N=vn({participantId:r,structureId:u,drawPosition:A,inContextDrawMatchUps:p,sourceMatchUpStatus:m,tournamentRecord:I,drawDefinition:S,matchUpsMap:h,event:T});return N.error?N:d&&l?{earlyReturn:{stack:"directLoser",context:{progressExitStatus:!0,loserParticipantId:r}}}:{...P}}return{context:{loserDrawPosition:f,loserTargetLink:g,targetDrawPositionIsUnfilled:i},error:i?is:Zx}}function b5({loserParticipantId:t,targetStructureId:e,tournamentRecord:r,drawDefinition:n,loserMatchUp:o,structure:i}){if(!i?.seedAssignments||i.structureId===e)return;let s=i.seedAssignments.find(({participantId:c})=>c===t),a=s?.participantId;s&&a&&xa({eventId:o?.eventId,structureId:e,...s,tournamentRecord:r,drawDefinition:n,participantId:a})}function C5({projectedWinningSide:t,tournamentRecord:e,drawDefinition:r,loserMatchUp:n,dualMatchUp:o,matchUpsMap:i,stack:s}){if(!o||!t)return;let a=o.sides?.find(g=>g.sideNumber===3-t);if(!a?.lineUp)return;let{roundNumber:c,eventId:u}=n,{roundPosition:p}=o,m=c===1?2-p%2:1,d=i?.drawMatchUps?.find(({matchUpId:g})=>g===n.matchUpId),l=[1,2].map(g=>({...d.sides?.find(S=>S.sideNumber===g)??{},sideNumber:g}));d.sides=l;let f=d.sides.find(g=>g.sideNumber===m);f&&(f.lineUp=rf({lineUp:a.lineUp}),gt({tournamentId:e?.tournamentId,matchUp:d,context:s,drawDefinition:r,eventId:u}))}function QE(t){let e="directParticipants",r=ff(t);if(r.error)return M({result:r,stack:e});let n=Oa({matchUpStatus:t.matchUpStatus}),{dualWinningSideChange:o,inContextDrawMatchUps:i,projectedWinningSide:s,propagateExitStatus:a,matchUpStatusCodes:c,tournamentRecord:u,drawDefinition:p,matchUpStatus:m,dualMatchUp:d,matchUpsMap:l,winningSide:f,targetData:g,matchUpId:I,structure:S,matchUp:h,event:T}=t,y=!!h.collectionId,E=Ae({structure:S}),A=h.drawPositions,N;if(y){let{matchUpTieId:U,matchUpsMap:R}=t,D=Io({appliedPolicies:t.appliedPolicies,matchUpId:U,tournamentRecord:u,drawDefinition:p,matchUpsMap:R,event:T});if(N=D&&{tieMatchUpResult:D},A=i.find(({matchUpId:C})=>C===U)?.drawPositions,!o)return M({result:{...P,...N},stack:e})}return E?M({result:{...P,...N},stack:e}):A?M5({matchUpStatusIsValid:n,inContextDrawMatchUps:i,projectedWinningSide:s,propagateExitStatus:a,matchUpStatusCodes:c,tournamentRecord:u,drawDefinition:p,drawPositions:A,matchUpStatus:m,dualMatchUp:d,matchUpsMap:l,winningSide:f,targetData:g,matchUpId:I,structure:S,annotate:N,matchUp:h,stack:e,event:T}):M({result:{error:Gc},stack:e})}function M5({matchUpStatusIsValid:t,inContextDrawMatchUps:e,projectedWinningSide:r,propagateExitStatus:n,matchUpStatusCodes:o,tournamentRecord:i,drawDefinition:s,drawPositions:a,matchUpStatus:c,dualMatchUp:u,matchUpsMap:p,winningSide:m,targetData:d,matchUpId:l,structure:f,annotate:g,matchUp:I,stack:S,event:h}){let T=r?r-1:m-1,y=1-T,E=a[T],A=a[y],N={},{targetLinks:{loserTargetLink:U,winnerTargetLink:R,byeTargetLink:D},targetMatchUps:{winnerMatchUpDrawPositionIndex:b,loserMatchUpDrawPositionIndex:C,winnerMatchUp:_,loserMatchUp:v,byeMatchUp:w}}=d,L=an(s?.drawType),F=v5(L,I,f),x=!L||!F,k=t&&c||ie;if(_&&x){let G=AF({sourceMatchUpStatus:k,winnerMatchUpDrawPositionIndex:b,sourceMatchUpId:l,inContextDrawMatchUps:e,projectedWinningSide:r,winningDrawPosition:E,tournamentRecord:i,winnerTargetLink:R,drawDefinition:s,winnerMatchUp:_,dualMatchUp:u,matchUpsMap:p,event:h});if(G.error)return M({result:G,stack:S})}if(v&&x){let G=PF({sourceMatchUpStatus:k,sourceMatchUpStatusCodes:o??[],sourceWinningSide:m,loserMatchUpDrawPositionIndex:C,sourceMatchUpId:l,inContextDrawMatchUps:e,projectedWinningSide:r,propagateExitStatus:n,loserDrawPosition:A,tournamentRecord:i,loserTargetLink:U,drawDefinition:s,loserMatchUp:v,winningSide:m,matchUpsMap:p,dualMatchUp:u,event:h});if(G.context?.progressExitStatus&&Object.assign(N,G.context,{sourceMatchUpStatus:k,sourceMatchUpStatusCodes:o??[],loserMatchUp:v,matchUpsMap:p}),G.error)return M({result:G,stack:S})}if(w){let G=w.drawPositions??[],V=Math.min(...G.filter(Boolean)),B=D.target.structureId,z=Cr({drawPosition:V,structureId:B,tournamentRecord:i,drawDefinition:s,event:h});if(z.error)return M({result:z,stack:S})}return M({result:{...P,...g},stack:S,context:N})}function v5(t,e,r){return!t||!e.roundNumber||!r?.matchUps?!1:r.matchUps.filter(o=>o.roundNumber===e.roundNumber).length%2!==0}function gf(t){let e="genPlayoffStructure",r=O5(t,e);if(r.error||r.earlyReturn)return r.earlyReturn??r;let{addNameBaseToAttributeName:n,playoffStructureNameBase:o,finishingPositionNaming:i,finishingPositionLimit:s,availabilityResult:a,sourceStructureId:c,playoffAttributes:u,playoffPositions:p,roundOffsetLimit:m,tournamentRecord:d,exitProfileLimit:l,drawDefinition:f,roundProfiles:g,roundNumbers:I,structure:S,idPrefix:h,isMock:T,event:y,uuids:E}=r,{playoffRoundsRanges:A,playoffRounds:N}=a,{playoffPositionsReturned:U,error:R,playoffSourceRounds:D,playoffRoundsRanges:b}=ME(t);if(R)return M({result:{error:R},stack:e});let C=g?.length&&Object.assign({},...g),_=I||typeof g=="object"&&g.flatMap(Y=>Object.keys(Y)),v=Array.isArray(_)&&_.map(Y=>!Number.isNaN(Number(Y))&&st(Y)).filter(Boolean);if(v){if(!Array.isArray(v))return M({result:{error:O},context:{validRoundNumbers:v},stack:e});v.forEach(Y=>{if(!N?.includes(Y))return M({result:{error:O},context:{roundNumber:Y},stack:e})})}p&&p.forEach(Y=>{if(!U?.includes(Y))return M({result:{error:O},context:{playoffPosition:Y},stack:e})});let w=v||D,L=v?A:b,F=[],x=[],k=an(f.drawType);for(let Y of w??[]){let J=L?.find(pr=>pr.roundNumber===Y);if(!J)return M({result:{error:O},context:{roundNumber:Y},stack:e});let ct=x5({finishingPositionsCount:J.finishingPositions.length,isLuckyDraw:k,roundNumber:Y,structure:S}),Et=Math.min(...J.finishingPositions)-1,Wt=2,Dt=Y&&C?.[Y]&&Wt+C[Y]-1,pe=Au({exitProfile:`0-${Y}`,addNameBaseToAttributeName:n,playoffStructureNameBase:o,finishingPositionOffset:Et,playoffAttributes:u,exitProfileLimit:l,stage:Vt,roundOffset:0,drawDefinition:f,sequenceLimit:Dt,stageSequence:Wt,drawSize:ct,idPrefix:h,isMock:T,uuids:E,finishingPositionNaming:i,finishingPositionLimit:s,roundOffsetLimit:m});if(pe.error)return M({result:pe,stack:e});let{structures:ye,links:Jt}=pe;if(ye?.length&&F.push(...ye),Jt?.length&&x.push(...Jt),pe.structureId&&Y){let pr={linkType:ir,source:{structureId:c,roundNumber:Y},target:{structureId:pe.structureId,feedProfile:qe,roundNumber:1}};x.push(pr)}}if(!F.length)return M({result:{error:O},info:"No structures generated",stack:e});f.structures.push(...F),f.links.push(...x);let{matchUps:G,matchUpsMap:V}=te({inContext:!0,drawDefinition:f}),B=new Set(F.map(({structureId:Y})=>Y)),z=G?.filter(({structureId:Y})=>B.has(Y)).map(Te),W=V?.drawMatchUps?.filter(({matchUpId:Y})=>z?.includes(Y));if(W?.length){let Y=ze({drawDefinition:f,event:y})?.tieFormat;Y&&W.forEach(J=>{let{tieMatchUps:ct}=zi({matchUp:J,tieFormat:Y,isMock:T});Object.assign(J,{tieMatchUps:ct,matchUpType:Ot})})}NF({inContextDrawMatchUps:G,sourceStructureId:c,tournamentRecord:d,drawDefinition:f,matchUpsMap:V,structure:S,event:y}),UF({inContextDrawMatchUps:G,sourceStructureId:c,tournamentRecord:d,drawDefinition:f,event:y});let K=w5({inContextDrawMatchUps:G,sourceStructureId:c,tournamentRecord:d,drawDefinition:f,matchUpsMap:V,params:t,stack:e});return{structures:F,matchUpModifications:K,links:x,drawDefinition:f,...P}}function O5(t,e){if(!t.drawDefinition)return{error:!0,earlyReturn:M({result:{error:$},stack:e})};let r=Hp(t);if(r.error)return{error:!0,earlyReturn:M({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,playoffGroups:l,roundProfiles:f,roundNumbers:g,idPrefix:I,isMock:S,event:h,uuids:T}=t,y=q(t.drawDefinition,!1,!0),{structure:E}=tt({structureId:n,drawDefinition:y});return E?E.structureType===de||E.structures?{error:!0,earlyReturn:yF({sourceStructureId:E.structureId,...t,...r,drawDefinition:y})}:l?.length?{error:!0,earlyReturn:_5({sourceStructureId:n,tournamentRecord:m,drawDefinition:y,playoffGroups:l,structure:E,idPrefix:I,isMock:S,event:h,uuids:T,stack:e})}:{addNameBaseToAttributeName:o,playoffStructureNameBase:i,finishingPositionNaming:s,finishingPositionLimit:a,availabilityResult:r,sourceStructureId:n,playoffAttributes:c,playoffPositions:u,roundOffsetLimit:p,tournamentRecord:m,exitProfileLimit:d,drawDefinition:y,roundProfiles:f,roundNumbers:g,structure:E,idPrefix:I,isMock:S,event:h,uuids:T}:{error:!0,earlyReturn:M({result:{error:Nt},stack:e})}}function _5({sourceStructureId:t,tournamentRecord:e,drawDefinition:r,playoffGroups:n,structure:o,idPrefix:i,isMock:s,event:a,uuids:c,stack:u}){let p=uf({requireSequential:!1,matchUpType:a?.eventType,sourceStructureId:t,drawDefinition:r,playoffGroups:n,groupCount:1,idPrefix:i,isMock:s,uuids:c});if(p.error)return M({result:p,stack:u});let{structures:m,links:d}=p;if(!m?.length)return M({result:{error:O},info:"No playoff structures generated",stack:u});r.structures.push(...m),d?.length&&r.links.push(...d);let{matchUps:l,matchUpsMap:f}=te({inContext:!0,drawDefinition:r});return NF({inContextDrawMatchUps:l,sourceStructureId:t,tournamentRecord:e,drawDefinition:r,matchUpsMap:f,structure:o,event:a}),UF({inContextDrawMatchUps:l,sourceStructureId:t,tournamentRecord:e,drawDefinition:r,event:a}),{structures:m,links:d,matchUpModifications:[],drawDefinition:r,...P}}function x5({finishingPositionsCount:t,isLuckyDraw:e,roundNumber:r,structure:n}){let o=t;if(e&&n){let s=(n.matchUps??[]).filter(c=>c.roundNumber===r).length;if(!(s===1)&&s%2!==0){let c=s-1,u=c%2===0?c:c+1,p=1;for(;p<u;)p*=2;o=p}else o=Si(o)}return o}function NF({inContextDrawMatchUps:t,sourceStructureId:e,tournamentRecord:r,drawDefinition:n,matchUpsMap:o,structure:i,event:s}){t?.filter(c=>js({matchUp:c})&&c.structureId===e)?.forEach(c=>{let{matchUpId:u,score:p,winningSide:m}=c,d=er({inContextDrawMatchUps:t,drawDefinition:n,matchUpId:u}),l=QE({inContextDrawMatchUps:t,tournamentRecord:r,drawDefinition:n,matchUpsMap:o,winningSide:m,targetData:d,matchUpId:u,structure:i,matchUp:c,score:p,event:s});l.error&&console.log(l.error)})}function UF({inContextDrawMatchUps:t,sourceStructureId:e,tournamentRecord:r,drawDefinition:n,event:o}){t?.filter(s=>s.matchUpStatus==="BYE"&&s.structureId===e)?.forEach(s=>{let{matchUpId:a}=s,c=er({inContextDrawMatchUps:t,drawDefinition:n,matchUpId:a}),{targetLinks:{loserTargetLink:u},targetMatchUps:{loserMatchUpDrawPositionIndex:p,loserMatchUp:m}}=c;if(u&&m){let d=u.target.structureId,l=m.drawPositions[p],f=Cr({drawPosition:l,structureId:d,tournamentRecord:r,drawDefinition:n,event:o});f.error&&console.log(f.error)}})}function w5({inContextDrawMatchUps:t,sourceStructureId:e,tournamentRecord:r,drawDefinition:n,matchUpsMap:o,params:i,stack:s}){let a=[],c=Ts({inContextDrawMatchUps:t,drawDefinition:n,matchUpsMap:o}).goesToMap,{structure:u}=tt({drawDefinition:i.drawDefinition,structureId:e}),{matchUps:p}=ht({structure:u});return p.forEach(m=>{let d=c?.loserMatchUpIds[m.matchUpId];if(d&&m.loserMatchUpId!==d){m.loserMatchUpId=d;let f={tournamentId:r?.tournamentId,eventId:i.event?.eventId,context:s,matchUp:m};a.push(f)}let l=c?.winnerMatchUpIds[m.matchUpId];if(l&&m.winnerMatchUpId!==l){m.winnerMatchUpId=l;let f={tournamentId:r?.tournamentId,eventId:i.event?.eventId,context:s,matchUp:m};a.push(f)}}),a}function LS(t){let{structures:e,links:r,matchUpModifications:n,error:o}=gf(t);if(o)return{error:o};let i=t.drawDefinition;return yS({tournamentId:t.tournamentRecord?.tournamentId,eventId:t.event?.eventId||t.eventId,matchUpModifications:n,drawDefinition:i,structures:e,links:r})}function Ns(t){let e=X(t,[{_anyOf:{[Ee]:!1,[rt]:!1,[Kt]:!1,[ce]:!1},[NI]:!0}]);if(e.error)return e;let r=[],n=t.drawDefinition??t.event??((t.tournamentId||!t.tournamentRecords)&&t.tournamentRecord);if(n){let o=DF(t,n);if(o.error)return o;r.push(...o?.applied??[]),t.drawDefinition&&Ft({drawDefinition:t.drawDefinition,tournamentId:t.tournamentId})}else if(t.tournamentRecords){let o=Object.keys(t.tournamentRecords);if(!o.length)return{error:j};for(let i of o){let s=t.tournamentRecords[i],a=DF(t,s);if(a.error)return a;r.push(...a?.applied??[])}}else return{error:j};return r.length?{...P,applied:r}:{error:kT}}function DF(t,e){let r=It(t).appliedPolicies??{};e.extensions??=[];let n=[],o=Object.keys(t.policyDefinitions);if(!o.length)return{error:fa};for(let i of o)if(!r[i]||t.allowReplacement){let s=t.policyDefinitions[i];if(!s)continue;if(!Tt(s))return{error:O};let{policyName:a,...c}=s;if(!c||!Object.keys(c).length||a&&!_t(a))return{error:O};r[i]=t.policyDefinitions[i],n.push(i)}return n?.length?{...ut({element:e,extension:{name:Tp,value:r}}),applied:n}:{applied:n,error:kT}}function FS({tournamentRecord:t,drawDefinition:e,flightProfile:r,drawName:n,drawId:o,event:i}){if(!n||typeof n!="string")return M({result:{error:O},context:{drawName:n}});r||(r=Bt({event:i}).flightProfile);let s=r?.flights?.find(a=>a.drawId===o);if(s){s.drawName=n;let a={name:on,value:{...r,flights:r.flights}};xo({event:i,extension:a})}return e&&(e.drawName=n,Ft({tournamentId:t?.tournamentId,drawDefinition:e})),!s&&!e?{error:$}:{...P,flight:s}}function EC({tournamentRecord:t,drawDefinition:e,drawUpdates:r,drawId:n,event:o}){if(!Tt(r))return{error:O};let i=Bt({event:o}).flightProfile,s=r.drawName&&FS({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:$};if(a){let c={name:on,value:{...i,flights:i.flights}};xo({event:o,extension:c})}return e&&(r.policyDefinitions&&Ns({policyDefinitions:r.policyDefinitions,drawDefinition:e}),Ft({tournamentId:t?.tournamentId,drawDefinition:e})),{...P}}function AC({tournamentRecord:t,removeScheduling:e,removeAssignments:r,drawDefinition:n}){if(!n)return{error:$};let o=an(n.drawType),i=Ie({drawDefinition:n}),s=c=>i?.drawMatchUps?.find(u=>u.matchUpId===c);for(let c of n.structures??[]){let{stage:u}=c;if(u===Fe){L5(c);continue}F5({structure:c,isLuckyDraw:o,removeAssignments:r}),G5({removeScheduling:e,tournamentRecord:t,drawDefinition:n,getRawMatchUp:s,isLuckyDraw:o,matchUpsMap:i,structure:c,removeAssignments:r})}n.entries?.length&&(n.entries=n.entries.filter(c=>c.entryStage!==Fe)),n.extensions=n.extensions.filter(c=>c.name!==su&&c.name!==wi);let a=(n.structures??[]).map(({structureId:c})=>c);return Ft({drawDefinition:n,structureIds:a}),{...P}}function L5(t){t.matchUps=[],t.positionAssignments&&(t.positionAssignments=t.positionAssignments.map(e=>(delete e.participantId,e))),t.seedAssignments=[]}function F5({structure:t,isLuckyDraw:e,removeAssignments:r}){let{positionAssignments:n,stage:o,stageSequence:i}=t,s=i===1&&[Z,H].includes(o);e&&n?k5({structure:t,positionAssignments:n,isMainOrQualifyingFirst:s,removeAssignments:r}):n&&(!s||r)&&(t.positionAssignments=n.map(a=>(delete a.participantId,a)),t.seedAssignments=[])}function k5({structure:t,positionAssignments:e,isMainOrQualifyingFirst:r,removeAssignments:n}){let o=new Set((t.matchUps??[]).filter(i=>i.roundNumber===1).flatMap(i=>i.drawPositions??[]).filter(Boolean));r?(t.positionAssignments=e.filter(i=>o.has(i.drawPosition)).map(i=>(n&&(delete i.bye,delete i.participantId),i)),n&&(t.seedAssignments=[])):(t.positionAssignments=[],t.seedAssignments=[])}function G5({removeScheduling:t,tournamentRecord:e,removeAssignments:r,drawDefinition:n,getRawMatchUp:o,isLuckyDraw:i,matchUpsMap:s,structure:a}){let{matchUps:c,isRoundRobin:u}=ht({afterRecoveryTimes:!1,inContext:!0,matchUpsMap:s,structure:a});for(let p of c){let{matchUpId:m,roundNumber:d}=p,l=p.sides??[],f=o(m);f&&(delete f.extensions,delete f.notes,V5({matchUp:f,isLuckyDraw:i,removeAssignments:r,roundNumber:d,sides:l,isRoundRobin:u}),B5({matchUp:f,removeScheduling:t}),gt({tournamentId:e?.tournamentId,context:"resetDrawDefinition",drawDefinition:n,matchUp:f}))}}function V5({matchUp:t,isLuckyDraw:e,removeAssignments:r,roundNumber:n,sides:o,isRoundRobin:i}){if(e)!r&&t.matchUpStatus==="BYE"||Object.assign(t,ka),n&&n>1&&(t.drawPositions=[]);else if(t.matchUpStatus!=="BYE"&&Object.assign(t,ka),n&&n>1&&t.drawPositions?.length&&!i){let s=o?.map(({drawPosition:c,participantFed:u})=>!u&&c).filter(Boolean),a=t.drawPositions.map(c=>s.includes(c)?void 0:c);t.drawPositions=a}}function B5({matchUp:t,removeScheduling:e}){e?delete t.timeItems:t.timeItems?.length&&(t.timeItems=t.timeItems.filter(r=>r.itemType&&![fo,ai,gs,rS,fu,Is,Ss,lu].includes(r.itemType)))}function $p({tournamentRecord:t}){if(!t)return{error:j};let e={positionsNoOutcomes:[],canBePruned:[],matchPlay:[],inactive:[],drawAnalysis:{}},r={};return(t.events?.flatMap(o=>{let i=o.eventId;return r[i]=o,(o?.drawDefinitions??[]).map(s=>({drawDefinition:s,eventId:i}))}).filter(Boolean)).forEach(({drawDefinition:o,eventId:i})=>{let s=0,a=0,c=0,{allStructuresLinked:u}=Yp({drawDefinition:o}),p=r[i],d=(o?.structures??[]).map(E=>{let{stage:A,stageSequence:N,structureId:U}=E,R=Aa[A],{inContextStructureMatchUps:D}=qi({drawDefinition:o,structureId:U,structure:E,event:p}),b=D?.filter(({winningSide:W})=>W),C=b.filter(Boolean).length||0;a+=C,c+=D.length-a;let _=Math.max(b.filter(({roundNumber:W})=>W===1).map(({roundPosition:W})=>W)),{positionAssignments:v}=Pt({structure:E}),w=v?.filter(({participantId:W})=>W);s+=w?.length??0;let L=(v?.length??0)-(w?.length??0),{roundMatchUps:F,roundProfile:x,roundNumbers:k,maxMatchUpsCount:G}=De({matchUps:D}),V=x&&Object.keys(x).filter(W=>!x[W].inactiveRound).map(W=>Number.parseInt(W)),B=x&&Object.keys(x).filter(W=>x[W].inactiveRound).map(W=>Number.parseInt(W)),z=x&&Object.values(x).every(W=>W.inactiveRound);return{positionsAssignedCount:w?.length??0,maxWinningSideFirstRoundPosition:_,unassignedPositionsCount:L,inactiveStructure:z,maxMatchUpsCount:G,inactiveRounds:B,roundMatchUps:F,activeRounds:V,roundNumbers:k,roundProfile:x,structureId:U,stageSequence:N,orderNumber:R,stage:A}}),l=d.find(E=>E.orderNumber===2&&E.stageSequence===1),f=d.filter(({inactiveStructure:E})=>!E).length,{links:g}=Ma({structureId:l.structureId,drawDefinition:o}),I=st(l.activeRounds[0])===1&&l.activeRounds.length===1&&f===1,S=d?.every(({inactiveStructure:E})=>E),h=!g.length&&l.activeRounds.length&&(l.roundProfile[1].inactiveCount||l.inactiveRounds.length),T=o.drawId;s&&!a&&e.positionsNoOutcomes.push(T),S&&e.inactive.push(T),I&&e.matchPlay.push(T),h&&e.canBePruned.push(T);let y={matchUpsWithWinningSideCount:a,matchUpsNoOutcomeCount:c,positionsAssignedCount:s,allStructuresLinked:u,structuresData:d,inactiveDraw:S,isMatchPlay:I,drawId:T};e.drawAnalysis[T]=y}),{...P,drawsAnalysis:e}}function PC({matchPlayDrawPositions:t=!0,tournamentRecord:e,drawDefinition:r,drawId:n}){if(!e)return{error:j};if(!r)return{error:$};let o=[],{drawsAnalysis:i}=$p({tournamentRecord:e});if(i.canBePruned.includes(n)){let s=i.matchPlay.includes(n),a=i.drawAnalysis[n],{structures:[c]}=In({stageSequence:1,drawDefinition:r,stage:H}),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(Te),d=p.map(Te).filter(l=>!m.includes(l));if(s){let l=o.filter(({roundNumber:T})=>!u.inactiveRounds.includes(T)).filter(({winningSide:T})=>T),f=l.map(Te),g=m.filter(T=>!f.includes(T));d.push(...g);let S=l.flatMap(T=>T.drawPositions??[]).filter(Boolean).flat(),h=Object.assign({},...S.map((T,y)=>({[T]:y+1})));if(l.forEach(T=>{t?T.drawPositions=T.drawPositions.map(y=>h[y]):delete T.drawPositions}),t){let T=c?.positionAssignments?.filter(y=>S.includes(y.drawPosition)).map(y=>(y.drawPosition=h[y.drawPosition],y));c.positionAssignments=T}else c.positionAssignments=[];c.matchUps=l,o=l}xn({tournamentId:e?.tournamentId,matchUpIds:d,drawDefinition:r}),Ft({drawDefinition:r})}return{...P,matchUps:o}}function RF({isPositionAction:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,loserMatchUp:o,matchUpsMap:i,structureId:s,structure:a,event:c}){if(!r)return{error:$};if(a||({structure:a}=tt({drawDefinition:r,structureId:s})),!a)return{error:Nt};s||({structureId:s}=a);let u="assignDrawPositionQualifier";Pe({method:u,color:"cyan",drawPosition:n}),i??=Ie({drawDefinition:r});let{positionAssignments:p}=Pt({structure:a}),{activeDrawPositions:m}=qi({drawDefinition:r,structureId:s});if(p?.find(T=>T.drawPosition===n)?.qualifier)return{...P};let l=!!(o&&i.drawMatchUps.some(T=>T.loserMatchUpId===o?.matchUpId&&Ye(T.matchUpStatus)));if(m?.includes(n)&&!l)return{error:Vc};let g=p?.find(T=>T.drawPosition===n);if(!g)return{error:is};let{containsQualifier:I,containsParticipant:S}=Kl(g);if(I)return{...P};let h=It({tournamentRecord:e,drawDefinition:r,event:c}).appliedPolicies??{};return p?.forEach(T=>{T.drawPosition===n&&(T.qualifier=!0,l&&(T.participantId=void 0,console.log("oddity: invalid participantId on qualifier position cleared")))}),Sn({tournamentId:e?.tournamentId,drawDefinition:r,structure:a,event:c}),H5({assignedParticipantId:S,isPositionAction:t,appliedPolicies:h,drawDefinition:r,drawPosition:n,structureId:s,stack:u})}function H5({assignedParticipantId:t,isPositionAction:e,appliedPolicies:r,drawDefinition:n,drawPosition:o,structureId:i,stack:s}){return e&&fc({appliedPolicies:r,drawDefinition:n,positionAction:{removedParticipantId:t,drawPosition:o,structureId:i,name:s}}),M({result:{...P},stack:s})}function NC({tournamentRecord:t,drawDefinition:e,participantId:r,drawPosition:n,structureId:o,qualifier:i,event:s,bye:a}){if(!e)return{error:$};if(!n)return{error:da};if(!o)return{error:dn};if(a){let c=Cr({tournamentRecord:t,drawDefinition:e,drawPosition:n,structureId:o,event:s});if(c.error)return c}else if(i){let c=RF({tournamentRecord:t,drawDefinition:e,drawPosition:n,structureId:o,event:s});if(c.error)return c}else{let c=vn({participantId:r,tournamentRecord:t,drawDefinition:e,drawPosition:n,structureId:o,event:s});if(c.error)return c}return{...P}}function UC({tournamentRecord:t,drawDefinition:e,scaleAttributes:r,preferencesCount:n=3,tierMethod:o,ascending:i,structureId:s,tierCount:a,event:c,force:u}){if(!e)return{error:$};if(a!==void 0&&a<1)return{error:O};if(n<1)return{error:O};if(!s){let b=e.structures?.filter(C=>C.stage===H);b?.length===1&&(s=b[0].structureId)}if(!s)return{error:dn};let{structure:p}=tt({drawDefinition:e,structureId:s});if(!p)return{error:dn};let{extension:m}=ot({element:e,name:wi});if(m?.value?.status&&m.value.status!=="COMPLETE"&&!u)return{error:dD};let{positionAssignments:d}=Pt({drawDefinition:e,structureId:s}),l=d?.filter(b=>!b.participantId&&!b.bye&&!b.qualifier).map(b=>b.drawPosition);if(!l?.length)return{error:jc};let f=p.seedAssignments??[],g=new Set(f.map(b=>b.participantId).filter(Boolean)),I=d?.filter(b=>b.participantId).map(b=>b.participantId)??[],h=e.entries?.filter(b=>!g.has(b.participantId)&&!I.includes(b.participantId))?.map(b=>b.participantId)??[],T=o??"ENTRY_ORDER",y=r??W5(T,c),E=i??T==="RANKING",A=Y5({participantIds:h,tierMethod:T,scaleAttributes:y,ascending:E,tournamentRecord:t}),N=a??q5(A.length,g.size),U=Math.min(N,A.length),R=$5(A,U),D={status:"SEEDS_PLACED",structureId:s,preferencesCount:n,tierMethod:T,scaleAttributes:y,ascending:E,tiers:R,preferences:{},unassignedDrawPositions:l};return ut({element:e,extension:{name:wi,value:D}}),{...P,draftState:D,unassignedDrawPositions:l,tiers:R}}function W5(t,e){if(t==="RANKING")return{scaleType:Xn};if(t==="RATING"){let r=e?.category?.ratingType;return r?{scaleType:vo,scaleName:r}:void 0}}function Y5({participantIds:t,tierMethod:e,scaleAttributes:r,ascending:n,tournamentRecord:o}){if(e==="ENTRY_ORDER"||!r||!o)return t;let i=[],s=[];for(let a of t){let{scaleItem:c}=Ki({tournamentRecord:o,scaleAttributes:r,participantId:a}),u=c?.scaleValue,p=j5(u);p===void 0?s.push(a):i.push({participantId:a,scaleValue:p})}return i.sort((a,c)=>n?a.scaleValue-c.scaleValue:c.scaleValue-a.scaleValue),[...i.map(a=>a.participantId),...s]}function j5(t){if(t!=null){if(typeof t=="number")return t;if(typeof t=="string"){let e=Number.parseFloat(t);return Number.isNaN(e)?void 0:e}if(typeof t=="object")for(let e of Object.values(t)){if(typeof e=="number")return e;if(typeof e=="string"){let r=Number.parseFloat(e);if(!Number.isNaN(r))return r}}}}function q5(t,e){return t<4?1:e>0&&t>=24?3:2}function $5(t,e){let r=[],n=Math.floor(t.length/e),o=t.length%e,i=0;for(let s=0;s<e;s++){let a=n+(s<o?1:0);r.push({participantIds:t.slice(i,i+a),resolved:!1}),i+=a}return r}function XE(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:Nt};let o=r.structures?.find(c=>c.structureId===n);if(!o)return{error:Nt};let i=o?.matchUps,s=i?.find(c=>!!c.roundPosition);if(o.structures||s||o.finishingPosition===ls)return{error:Do};let a=i.filter(({roundNumber:c})=>t.roundNumbers?.includes(c)).map(Te);return e=e.filter(c=>!a.includes(c)),t.roundNumbers&&!e.length&&(e=a),{existingMatchUps:i,matchUpIds:e,structureId:n,structure:o}}function DC(t){let e=X(t,[{[Kt]:!0},{[Ua]:{[nu]:!1,roundNumbers:!1},[_r]:O,[Ge]:ke}]);if(e.error)return e;let{removeIncomplete:r=!1,removeUnAssigned:n=!0,removeCompleted:o=!1,tournamentRecord:i,drawDefinition:s,event:a}=t,c=XE(t);if(c.error)return c;let{structure:u,structureId:p,existingMatchUps:m,matchUpIds:d}=c,l=[],f=m?.filter(({matchUpId:S,score:h,winningSide:T})=>{if(T&&!o)return!1;if(T||ue({score:h})){if(!T&&!r)return!1;l.push(S)}else if(!n)return!1;return d?.includes(S)})??[],g=f.map(Te),I=f.map(({tieMatchUps:S})=>S?.map(Te)).filter(Boolean).flat();if(g.length){u.matchUps=(u.matchUps??[]).filter(({matchUpId:T})=>!g.includes(T)),xn({tournamentId:i?.tournamentId,matchUpIds:[...I,...g],action:"deleteAdHocMatchUps",eventId:a?.eventId,drawDefinition:s});let S=pt(u.matchUps.map(Fr("roundNumber"))),h=Xx(S);if(h.length){h.reverse();for(let T of h)u.matchUps.forEach(y=>{y.roundNumber&&y.roundNumber>T&&(y.roundNumber-=1,gt({tournamentId:i?.tournamentId,context:["adHoc round deletion"],eventId:a?.eventId,drawDefinition:s,matchUp:y}))})}if(l.length){u.positionAssignments=pt(u.matchUps.flatMap(R=>(R.sides??[]).map(D=>D.participantId)).filter(Boolean)).map(R=>({participantId:R}));let T=u?.matchUpFormat??s?.matchUpFormat??a?.matchUpFormat,E=c.existingMatchUps.some(R=>R.matchUpType===Ir)?{matchUpTypes:[Ir]}:void 0,{matchUps:A}=ht({afterRecoveryTimes:!1,inContext:!0,matchUpFilters:E,structure:u,event:a});Ae({structure:u})&&(u.positionAssignments=pt(A.flatMap(R=>(R.sides??[]).map(D=>D.participantId)).filter(Boolean)).map(R=>({participantId:R})));let U=lf({positionAssignments:u.positionAssignments,tournamentRecord:i,drawDefinition:s,matchUpFormat:T,matchUps:A,event:a});U.error&&console.log(U)}Ft({structureIds:[p],eventId:a?.eventId,drawDefinition:s})}return!g.length&&d.length?{error:$c}:{...P,deletedMatchUpsCount:[...g,...I].length}}function RC({removeCompletedMatchUps:t,tournamentRecord:e,drawDefinition:r,structureId:n,roundNumber:o,event:i}){let s=dt({tournamentRecord:e,drawDefinition:r},[rt,Kt]);if(s.error)return s;if(!o)return M({result:{error:nt},info:"roundNumber required"});let a=tt({drawDefinition:r,structureId:n});if(a.error)return a;let c=a.structure;return c?.structures?{error:Do}:Ae({structure:c})?K5({tournamentId:e.tournamentId,removeCompletedMatchUps:t,eventId:i.eventId,drawDefinition:r,roundNumber:o,structure:c}):(console.log("not implemented"),{...P})}function K5({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(Zt).includes(n)){let m=s.filter(d=>{let l=d.roundNumber===n&&(!Mt.includes(d.matchUpStatus)||t);return l&&(c.push(d.matchUpId),d.tieMatchUps&&a.push(...d.tieMatchUps.map(Te))),!l});c.length&&(xn({matchUpIds:[...a,...c],drawDefinition:e,tournamentId:r,eventId:i}),m.some(l=>l.roundNumber===n)||(m.forEach(l=>{l.roundNumber>n&&(l.roundNumber-=1,gt({drawDefinition:e,tournamentId:r,eventId:i,matchUp:l}))}),u=!0),o.matchUps=m)}return{deletedMatchUpsCount:c.length,roundRemoved:u,...P}}function Kp(t){let{suppressNotifications:e,tournamentRecord:r,drawDefinition:n,matchUps:o,event:i}=t;if(typeof n!="object")return{error:$};let s=t?.structureId;if(!s&&n.structures?.length===1&&(s=n.structures?.[0]?.structureId),typeof s!="string")return{error:dn};if(!Nr(o))return{error:O,info:Ai("matchUps")};let a=n.structures?.find(l=>l.structureId===s);if(!a)return{error:Nt};let u=(a?.matchUps).find(l=>!!l.roundPosition);if(a.structures||u||a.finishingPosition===ls)return{error:Do};let p=qt({tournamentRecord:r,inContext:!1})?.matchUps?.map(Te)??[],m=o.map(Te);if(Re(p,m))return{error:bD,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||(ko({tournamentId:r?.tournamentId,matchUps:[...d,...o],eventId:i?.eventId,drawDefinition:n}),Ft({drawDefinition:n,structureIds:[s]})),{...P}}function bC({tournamentRecord:t,drawDefinition:e,drawPosition:r,structureId:n,subOrder:o,event:i}){if(!e)return{error:$};if(!n)return{error:dn};if(!r)return{error:da};let{structure:s}=tt({drawDefinition:e,structureId:n});if(!s)return{error:Nt};let a=s;s.structures&&s.structureType===de&&(a=s.structures?.find(g=>g.positionAssignments?.find(I=>I.drawPosition===r)));let c=a?.positionAssignments,u=c?.find(g=>g.drawPosition===r);u&&ut({element:u,extension:{name:au,value:o}});let d=(i?.eventType===Ot||e.matchUpType===Ot||(i?.tieFormat??e?.tieFormat??s?.tieFormat))&&{matchUpTypes:[Ot]},{matchUps:l}=ht({structure:a,afterRecoveryTimes:!1,inContext:!0,matchUpFilters:d,event:i}),f=s?.matchUpFormat??e.matchUpFormat;return lf({positionAssignments:c,tournamentRecord:t,drawDefinition:e,matchUpFormat:f,matchUps:l,event:i}),Ft({drawDefinition:e,structureIds:[n]}),{...P}}var WC={};Gt(WC,{addGoesTo:()=>Ts,allPlayoffPositionsFilled:()=>GE,checkValidEntries:()=>Ef,findDrawDefinition:()=>iA,getAssignedParticipantIds:()=>$i,getAvailableMatchUpsCount:()=>Sf,getAvailablePlayoffProfiles:()=>Hp,getDraftState:()=>yA,getDrawDefinitionTimeItem:()=>$y,getDrawParticipantRepresentativeIds:()=>eA,getDrawStructures:()=>In,getDrawTypeCoercion:()=>Qp,getEligibleVoluntaryConsolationParticipants:()=>JE,getLuckyDrawRoundStatus:()=>df,getMatchUpsMap:()=>Ie,getParticipantIdFinishingPositions:()=>Tf,getPositionAssignments:()=>Cu,getPositionsPlayedOff:()=>Pu,getRandomQualifierList:()=>hA,getSeedingThresholds:()=>EE,getSeedsCount:()=>Xp,getStructureSeedAssignments:()=>Pr,getSwissChart:()=>tA,getSwissStandings:()=>ZE,getTeamLineUp:()=>Ys,getValidGroupSizes:()=>id,hasLuckyRounds:()=>tS,isAdHoc:()=>Ae,isCompletedStructure:()=>No,isValidForQualifying:()=>TA,positionActions:()=>SA,validatePlayoffGroups:()=>cf});function JE({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:$};let f=[H,Vt];r&&f.push(Z);let g=Q5({includeEventParticipants:e,tournamentRecord:s,drawDefinition:a,stages:f,event:l}),I=Wi({stage:Fe,drawDefinition:a}),S=new Set(I.map(({participantId:b})=>b)),h=X5({excludedMatchUpStatuses:t,includeEventParticipants:e,finishingRoundLimit:n,policyDefinitions:o,roundNumberLimit:i,tournamentRecord:s,drawDefinition:a,matchUpsLimit:c,requirePlay:u,requireLoss:p,allEntries:m,winsLimit:d,event:l}),{participantMatchUps:T,losingParticipants:y,matchUpParticipants:E,participantWins:A}=J5({excludedMatchUpStatuses:h.excludedMatchUpStatuses,finishingRoundLimit:h.finishingRoundLimit,roundNumberLimit:h.roundNumberLimit,requirePlay:h.requirePlay,matchUps:g}),N=Object.keys(y),U=e4({includeEventParticipants:h.includeEventParticipants,requireLoss:h.requireLoss,requirePlay:h.requirePlay,allEntries:h.allEntries,matchUpParticipants:E,losingParticipants:y,tournamentRecord:s,drawDefinition:a,event:l}),R=new Set(N);return{eligibleParticipants:U.filter(b=>z5({voluntaryConsolationEntryIds:S,losingParticipantIdSet:R,participantMatchUps:T,participantWins:A,resolvedPolicy:h,participant:b})).map(b=>({...b,individualParticipants:b.individualParticipantIds?.map(C=>s?.participants?.find(_=>_.participantId===C))})),losingParticipantIds:N,...P}}function z5({voluntaryConsolationEntryIds:t,losingParticipantIdSet:e,participantMatchUps:r,participantWins:n,resolvedPolicy:o,participant:i}){let s=i.participantId,a=o.requireLoss?e.has(s):!0,c=o.requirePlay?(r[s]||0)>=0:!0,u=o.winsLimit?(n[s]||0)<=o.winsLimit:!0,p=o.matchUpsLimit?r[s]<=o.matchUpsLimit:!0,m=!t.has(s);return a&&c&&u&&p&&m}function Q5({includeEventParticipants:t,tournamentRecord:e,drawDefinition:r,stages:n,event:o}){let i=o?.eventType?{matchUpTypes:[o.eventType]}:void 0,s=r?.matchUpType?{matchUpTypes:[r.matchUpType]}:void 0;return t&&o?Mn({contextFilters:{stages:n},matchUpFilters:i,tournamentRecord:e,inContext:!0,event:o})?.matchUps??[]:rr({contextFilters:{stages:n},matchUpFilters:s,tournamentRecord:e,inContext:!0,drawDefinition:r})?.matchUps??[]}function X5({excludedMatchUpStatuses:t,includeEventParticipants:e,finishingRoundLimit:r,policyDefinitions:n,roundNumberLimit:o,tournamentRecord:i,drawDefinition:s,matchUpsLimit:a,requirePlay:c,requireLoss:u,allEntries:p,winsLimit:m,event:d}){let f=(n??lo({policyTypes:[Ry],tournamentRecord:i,drawDefinition:s,event:d}).policyDefinitions)?.[Ry],g=t.length&&t||(f?.excludedMatchUpStatuses??[]);return{includeEventParticipants:e??f?.includeEventParticipants,finishingRoundLimit:r??f?.finishingRoundLimit,excludedMatchUpStatuses:g,roundNumberLimit:o??f?.roundNumberLimit,matchUpsLimit:a??f?.matchUpsLimit,requirePlay:c??f?.requirePlay??!0,requireLoss:u??f?.requireLoss??!0,allEntries:p??f?.allEntries,winsLimit:m??f?.winsLimit}}function J5({excludedMatchUpStatuses:t,finishingRoundLimit:e,roundNumberLimit:r,requirePlay:n,matchUps:o}){let i={},s={},a={},c={},u=new Set(t);for(let p of o)Z5({matchUp:p,requirePlay:n,finishingRoundLimit:e,roundNumberLimit:r})&&t4({matchUp:p,requirePlay:n,excludedSet:u,participantMatchUps:i,losingParticipants:s,matchUpParticipants:a,participantWins:c});return{participantMatchUps:i,losingParticipants:s,matchUpParticipants:a,participantWins:c}}function Z5({matchUp:t,requirePlay:e,finishingRoundLimit:r,roundNumberLimit:n}){return!(e&&t.winningSide&&![1,2].includes(t.winningSide)&&t.matchUpStatus!==Qt||t.finishingRound&&r&&t.finishingRound>=r||t.finishingRound&&n&&t.finishingRound<=n)}function t4({matchUp:t,requirePlay:e,excludedSet:r,participantMatchUps:n,losingParticipants:o,matchUpParticipants:i,participantWins:s}){let a=t.sides?.find(({sideNumber:u})=>t.winningSide&&u===3-t.winningSide),c=t.sides?.find(({sideNumber:u})=>t.winningSide&&u===t.winningSide);if(t.sides?.forEach(u=>{let p=u?.participant?.participantId;p&&(i[p]=u.participant,t.matchUpStatus===Qt&&!e&&(o[p]=u.participant,n[p]||(n[p]=0),(!t.matchUpStatus||!r.has(t.matchUpStatus))&&(n[p]+=1)))}),a?.participant){let u=a.participant.participantId;o[u]=a.participant,n[u]||(n[u]=0),t.matchUpStatus&&!r.has(t.matchUpStatus)&&(n[u]+=1)}if(c?.participant){let u=c.participant.participantId;s[u]||(s[u]=0),s[u]+=1,n[u]||(n[u]=0),t.matchUpStatus&&!r.has(t.matchUpStatus)&&(n[u]+=1)}}function e4({includeEventParticipants:t,matchUpParticipants:e,losingParticipants:r,tournamentRecord:n,drawDefinition:o,requireLoss:i,requirePlay:s,allEntries:a,event:c}){let u=n?.participants&&!s&&!i&&a,p;t&&c?p=c.entries:p=o.entries;let m=new Set([Cn,Lr]),d=u?(p??[]).filter(l=>!m.has(l.entryStatus)).map(({participantId:l})=>l):[];if(u){let l=new Set(d);return(n?.participants??[]).filter(({participantId:f})=>l.has(f))}return Object.values(i?r:e)}function If({participantIds:t,matchUps:e,allowDraws:r=!1}){let n=new Map;for(let s of t)n.set(s,{participantId:s,wins:0,losses:0,draws:0,points:0,opponentIds:[],opponentOutcomes:new Map,roundPoints:[]});for(let s of e){if(s.matchUpStatus!==ie||!s.sides||s.sides.length<2)continue;let a=ft(s.sides[0]),c=ft(s.sides[1]);if(!a||!c)continue;let u=n.get(a),p=n.get(c);!u||!p||(u.opponentIds.includes(c)||u.opponentIds.push(c),p.opponentIds.includes(a)||p.opponentIds.push(a),s.winningSide===1?(u.wins+=1,u.points+=1,p.losses+=1,u.opponentOutcomes.set(c,"WIN"),p.opponentOutcomes.set(a,"LOSS"),u.roundPoints.push(1),p.roundPoints.push(0)):s.winningSide===2?(p.wins+=1,p.points+=1,u.losses+=1,p.opponentOutcomes.set(a,"WIN"),u.opponentOutcomes.set(c,"LOSS"),u.roundPoints.push(0),p.roundPoints.push(1)):r&&(u.draws+=1,p.draws+=1,u.points+=.5,p.points+=.5,u.opponentOutcomes.set(c,"DRAW"),p.opponentOutcomes.set(a,"DRAW"),u.roundPoints.push(.5),p.roundPoints.push(.5)))}let o=new Map;for(let[s,a]of n){let c=`${a.wins}-${a.losses}-${a.draws}`,u=o.get(c)??[];u.push(s),o.set(c,u)}let i=[];for(let[s,a]of o){let[c,u,p]=s.split("-").map(Number);i.push({wins:c,losses:u,draws:p,participantIds:a})}return i.sort((s,a)=>{let c=s.wins+s.draws*.5,u=a.wins+a.draws*.5;return u!==c?u-c:s.losses-a.losses}),{scoreGroups:i,records:n}}function CF({records:t,tiebreakMethods:e=["BUCHHOLZ","SONNEBORN_BERGER"]}){let r=[];for(let[n,o]of t){let i={participantId:n,wins:o.wins,losses:o.losses,draws:o.draws,points:o.points,opponentIds:o.opponentIds,rank:0};e.includes("BUCHHOLZ")&&(i.buchholz=MF(n,t)),e.includes("MEDIAN_BUCHHOLZ")&&(i.medianBuchholz=r4(n,t)),e.includes("SONNEBORN_BERGER")&&(i.sonnebornBerger=n4(n,t)),e.includes("PROGRESSIVE_SCORE")&&(i.progressiveScore=o4(o)),r.push(i)}i4(r,e);for(let n=0;n<r.length;n++)r[n].rank=n+1;return r}function MF(t,e){let r=e.get(t);return r?r.opponentIds.reduce((n,o)=>{let i=e.get(o);return n+(i?.points??0)},0):0}function r4(t,e){let r=e.get(t);return!r||r.opponentIds.length<3?MF(t,e):r.opponentIds.map(i=>e.get(i)?.points??0).sort((i,s)=>i-s).slice(1,-1).reduce((i,s)=>i+s,0)}function n4(t,e){let r=e.get(t);if(!r)return 0;let n=0;for(let o of r.opponentIds){let i=e.get(o);if(!i)continue;let s=r.opponentOutcomes.get(o);s==="WIN"?n+=i.points:s==="DRAW"&&(n+=i.points*.5)}return n}function o4(t){let e=0,r=0;for(let n of t.roundPoints)e+=n,r+=e;return r}function i4(t,e){t.sort((r,n)=>{if(n.points!==r.points)return n.points-r.points;for(let o of e){let i=bF(r,o),s=bF(n,o);if(s!==i)return s-i}return 0})}function bF(t,e){switch(e){case"BUCHHOLZ":return t.buchholz??0;case"MEDIAN_BUCHHOLZ":return t.medianBuchholz??0;case"SONNEBORN_BERGER":return t.sonnebornBerger??0;case"PROGRESSIVE_SCORE":return t.progressiveScore??0;default:return 0}}function ZE({tiebreakMethods:t=["BUCHHOLZ","SONNEBORN_BERGER"],drawDefinition:e,structureId:r}){if(!e)return{error:$};let n=r?tt({drawDefinition:e,structureId:r}).structure:e.structures?.find(d=>Ae({structure:d}));if(!n)return{error:Nt};let o=n.matchUps??[],i=(e.entries??[]).filter(d=>hr.includes(d.entryStatus??"")).map(ft).filter(Boolean);if(!i.length)return{standings:[],scoreGroups:[],roundsPlayed:0,...P};let{scoreGroups:s,records:a}=If({participantIds:i,matchUps:o}),c=CF({records:a,tiebreakMethods:t}),u=o.filter(d=>d.winningSide),m=[...new Set(u.map(d=>d.roundNumber).filter(Boolean))].length;return{standings:c,scoreGroups:s,roundsPlayed:m,...P}}function tA({drawDefinition:t,structureId:e}){if(!t)return{error:$};let r=e?tt({drawDefinition:t,structureId:e}).structure:t.structures?.find(a=>Ae({structure:a}));if(!r)return{error:Nt};let n=r.matchUps??[],o=(t.entries??[]).filter(a=>hr.includes(a.entryStatus??"")).map(ft).filter(Boolean);if(!o.length)return{rounds:[],totalRounds:0,...P};let i=[...new Set(n.map(a=>a.roundNumber).filter(Boolean))].sort((a,c)=>(a??0)-(c??0)),s=[];s.push({roundNumber:0,nodes:[{wins:0,losses:0,draws:0,participantIds:[...o]}]});for(let a of i){let c=n.filter(p=>p.matchUpStatus===ie&&(p.roundNumber??0)<=(a??0)),{scoreGroups:u}=If({matchUps:c,participantIds:o});s.push({roundNumber:a??0,nodes:u.map(p=>({wins:p.wins,losses:p.losses,draws:p.draws,participantIds:[...p.participantIds]}))})}return{rounds:s,totalRounds:i.length,...P}}function Sf(t){let e=X(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:dn};let i=r.structures?.find(g=>g.structureId===o);if(!i)return{error:Nt};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===ls)return{error:Do};let u=r?.entries?.filter(g=>{let I=g.entryStatus;return hr.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{...P,availableMatchUpsCount:f,lastRoundNumber:c,roundMatchUpsCount:p}}function eA({drawDefinition:t}){let e=ot({name:"participantRepresentatives",element:t});return e.error?e:{representativeParticipantIds:e.extension?.value??[]}}function vF({tournamentParticipants:t,drawDefinition:e,event:r}){if(!e)return{error:$};let n=te({tournamentParticipants:t,inContext:!0,drawDefinition:e,event:r}),o=q(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 Cu({tournamentRecord:t,drawDefinition:e,stage:r=H,structureId:n,structure:o}){if(!t)return{error:j};if(!o&&!e)return{error:$};if(!o&&!n&&e?.structures?.filter(a=>a.stage===r).length===1&&(o=e.structures.find(a=>a.stage===r)),!o&&!n)return{error:dn};let{error:i,positionAssignments:s}=Pt({drawDefinition:e,structureId:n,structure:o});return{positionAssignments:s??[],structureId:o?.structureId,error:i}}function MC({dates:t=[],extension:e}){if(!e)return!1;if(typeof e.value=="boolean"&&e.value)return!0;if(!t.length)return!1;let r=Tt(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 OF({inContextCourt:t,venue:e}){let{defaultStartTime:r,defaultEndTime:n,dateAvailability:o}=e;if(!(r||n||o?.length))return;let s=t.dateAvailability;if(!s?.length){o?.length?t.dateAvailability=o.map(a=>({...a})):r&&n&&(t.dateAvailability=[{startTime:r,endTime:n}]);return}t.dateAvailability=s.map(a=>{let c=s4({date:a.date,venueDateAvailability:o,defaultStartTime:r,defaultEndTime:n});if(!c)return a;let u=a4(a.startTime,c.startTime),p=c4(a.endTime,c.endTime),m=u4(a.bookings,c.bookings);return{...a,startTime:u,endTime:p,...m.length?{bookings:m}:{}}})}function s4({date:t,venueDateAvailability:e,defaultStartTime:r,defaultEndTime:n}){if(e?.length){if(t){let i=e.find(s=>s.date===t);if(i)return i}let o=e.find(i=>!i.date);if(o)return o}if(r||n)return{startTime:r,endTime:n}}function a4(t,e){return t?e?t>e?t:e:t:e}function c4(t,e){return t?e?t<e?t:e:t:e}function u4(t,e){let r=[];return t?.length&&r.push(...t),e?.length&&r.push(...e),r}function vC({convertExtensions:t,ignoreDisabled:e,venue:r,court:n}){let o={...q(n,t,!0),venueId:r.venueId},{extension:i}=ot({name:mo,element:n});if(e&&i){let s=Tt(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 OF({inContextCourt:o,venue:r}),{inContextCourt:o}}function p4(t,e,r){if(e.length&&!e.includes(t.venueId))return!1;if(r){let{extension:n}=ot({name:mo,element:t});if(n?.value)return!1}return!0}function m4({venue:t,convertExtensions:e,ignoreDisabled:r,dates:n,uniqueVenueIds:o,venues:i,uniqueCourtIds:s,courts:a}){o.includes(t.venueId)||(i.push(q(t,e,!0)),o.push(t.venueId));for(let c of t.courts??[])if(!s.includes(c.courtId)){if(r){let{extension:p}=ot({name:mo,element:c});if(MC({extension:p,dates:n}))continue}let{inContextCourt:u}=vC({convertExtensions:e,ignoreDisabled:r,venue:t,court:c});a.push(u),s.push(c.courtId)}}function Fn(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??[])p4(l,n,!!r)&&m4({venue:l,convertExtensions:e,ignoreDisabled:r,dates:o,uniqueVenueIds:s,venues:u,uniqueCourtIds:a,courts:c})}),{courts:c,venues:u,...P}}function d4({convertExtensions:t,tournamentRecord:e,ignoreDisabled:r,dates:n}){if(!e)return{error:kt};let o=q(e.venues??[],t).filter(s=>{if(!r)return s;let{extension:a}=ot({name:mo,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}=ot({name:mo,element:u});return MC({extension:p,dates:n})}).filter(Boolean).map(u=>{let{inContextCourt:p}=vC({convertExtensions:t,ignoreDisabled:r,venue:a,court:u});return p});return c.length?s.concat(c):s},[]);return{venues:o,courts:i}}function fd({tournamentRecords:t,requireCourts:e,dates:r}){return typeof t!="object"||!Object.keys(t).length?{error:kt}:Object.keys(t).reduce((o,i)=>{let s=t[i],{venues:a}=d4({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 rA({event:t}){let{surfaceCategory:e,onlineResources:r,matchUpFormat:n,discipline:o,eventLevel:i,eventName:s,eventType:a,startDate:c,category:u,ballType:p,eventId:m,endDate:d,gender:l,notes:f}=t,g=t.entries?.length??0;return{eventInfo:{drawDefinitionCount:t.drawDefinitions?.length,entriesCount:g,surfaceCategory:e,onlineResources:r,matchUpFormat:n,discipline:o,eventLevel:i,eventName:s,eventType:a,ballType:p,startDate:c,category:u,endDate:d,eventId:m,gender:l,notes:f}}}var l4="IN_PROGRESS",f4="ABANDONED",g4="CANCELLED",I4="COMPLETED",S4="ACTIVE",OC="tournamentImage",nA={TOURNAMENT_IMAGE_RESOURCE_NAME:OC,IN_PROGRESS:l4,ABANDONED:f4,CANCELLED:g4,COMPLETED:I4,ACTIVE:S4};var h4={[Da]:{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}}}},_F=h4;function Js(t){let{tournamentRecord:e,withMatchUpStats:r,withStructureDetails:n,withVenueData:o}=t??{};if(!e)return{error:j};let s=(({tournamentId:I,tournamentRank:S,tournamentStatus:h,formalName:T,tournamentName:y,promotionalName:E,onlineResources:A,localTimeZone:N,activeDates:U,startDate:R,endDate:D,hostCountryCode:b,venues:C,notes:_,updatedAt:v})=>({tournamentId:I,tournamentRank:S,tournamentStatus:h,formalName:T,tournamentName:y,promotionalName:E,onlineResources:A,localTimeZone:N,activeDates:U,startDate:R,endDate:D,hostCountryCode:b,venues:C,notes:_,updatedAt:v}))(e),a=e.venues?.find(I=>I.isPrimary);a?.addresses?.length&&(s.tournamentAddress=a.addresses[0]);let u=bt({participantFilters:{participantRoles:[xb,uS,wb,Lb,kb]},policyDefinitions:_F,tournamentRecord:e})?.participants??[];u&&(s.tournamentContacts=u);let p=e?.onlineResources?.find(I=>I.name===OC&&I.resourceType==="URL")?.identifier;p&&(s.imageUrl=p);let m=zs({tournamentRecord:e})?.publishState,d=m?.tournament?.status?.publishedEventIds??[],l=[];for(let I of e.events??[])if(!t?.usePublishState||d.includes(I.eventId)){let S=rA({event:I}).eventInfo;S&&l.push(S)}s.timeItemValues=LE({element:e}),s.publishState=m?.tournament,s.eventInfo=l;let f=[],g=[];if(r||n)for(let I of e.events??[])for(let S of I.drawDefinitions??[])for(let h of S.structures??[])g.push(...h.matchUps??[]),f.push(et({eventId:I.eventId,eventName:I.eventName,eventType:I.eventType,drawId:S.drawId,drawName:S.drawName,drawType:S.drawType,structureId:h.structureId,structureName:h.structureName,stage:h.stage,stageSequence:h.stageSequence,positionAssignments:h.positionAssignments,seedAssignments:h.seedAssignments,matchUpFormat:h.matchUpFormat}));if(n&&(s.structures=f),r){let I=e.participants?.filter(U=>U.participantType===St).length??0,S=e.participants?.filter(U=>U.participantType===vt).length??0,h=e.events?.length??0,T=g?.filter(U=>U.matchUpStatus!=="BYE"),y=T?.length,E=T?.filter(U=>Mt.includes(U.matchUpStatus)||U.winningSide)?.length,A=T?.filter(U=>Ws({matchUp:U})?.scheduledDate||Wl({matchUp:U})?.scheduledTime)?.length,N=y>0?Math.round(E/y*100):0;s.matchUpStats={total:y,completed:E,scheduled:A,percentComplete:N},s.individualParticipantCount=I,s.teamParticipantCount=S,s.eventCount=h}if(o){let{venues:I}=Fn({tournamentRecord:e});s.venues=I??[]}return{tournamentInfo:q(et(s),!1,!0),...P}}function oA({publishStatus:t,drawId:e}){return t?.drawDetails?eo(t.drawDetails?.[e]?.publishingDetail):t?.drawIds?t.drawIds.includes(e):!0}var _C="PUBLIC",T4="ADMIN",xF={PUBLIC_DISPLAY:_C,ADMIN_DISPLAY:T4};function hf(t){let{tournamentParticipants:e=[],includePositionAssignments:r,policyDefinitions:n,tournamentRecord:o,inContext:i=!0,usePublishState:s,status:a=Ur,pressureRating:c,refreshResults:u,contextProfile:p,drawDefinition:m,noDeepCopy:d,sortConfig:l,context:f,event:g}=t;if(!m)return{error:$};let{matchUpFormat:I,updatedAt:S,drawType:h,drawName:T,drawId:y}=m,E={matchUpFormat:I,updatedAt:S,drawName:T,drawType:h,drawId:y};E.display=ot({element:m,name:El}).extension?.value;let A={},N,U,{allStructuresLinked:R,sourceStructureIds:D,hasDrawFeedProfile:b,structureGroups:C}=Yp({drawDefinition:m});if(!R)return{error:vU};let _=t?.eventPublishState??zs({event:g}).publishState,v=t?.publishStatus??Dr({event:g,status:a}),w=_?.status?.drawDetails?.[m.drawId],L=!!_?.status?.published,F=w?.structureDetails,x=!1,k=!1,V=C.map(B=>{let z={},W=B.map(K=>{let{structure:Y}=tt({drawDefinition:m,structureId:K}),{seedAssignments:J}=Pr({drawDefinition:m,structure:Y});return Y?.stage===H&&Y.stageSequence===1&&(N=J),Y?.stage===Z&&(A[Y.stageSequence??0]=J),Y}).sort((K,Y)=>ki(K,Y,l)).map(K=>{if(!K)return;let Y=K?.structureId,J=[];K.stage&&[H,me,Vt].includes(K.stage)&&(J=N),K?.stage===Z&&(J=A[K.stageSequence??0]);let{matchUps:ct,roundMatchUps:Et,roundProfile:Wt}=ht({seedAssignments:K?.seedAssignments?.length?void 0:J,context:{drawId:E.drawId,...f},hydrateParticipants:t.hydrateParticipants,participantsProfile:t.participantsProfile,tournamentParticipants:e,policyDefinitions:n,tournamentRecord:o,usePublishState:s,publishStatus:v,contextProfile:p,drawDefinition:m,inContext:i,structure:K,event:g}),{positionAssignments:Dt}=Pt({structure:K}),pe=Dt?.filter(Fr(sr)).map($n=>{let Kr=ot({element:$n,name:Lo})?.extension?.value,{drawPosition:io,participantId:Ko}=$n;return k=!0,{participantResult:Kr,participantId:Ko,drawPosition:io}});if(ct.length&&(!pe?.length&&t.allParticipantResults||u&&!K.structures)){let{subOrderMap:$n}=Xl({positionAssignments:Dt}),io=ct.some(zo=>zo.matchUpType===Ir)?ct.filter(zo=>zo.matchUpType===Ir):ct,Ko=Ks({matchUpFormat:K.matchUpFormat,matchUps:io,policyDefinitions:n,pressureRating:c,subOrderMap:$n});U=Ko?.report,pe=Dt?.filter(Fr(sr)).map(zo=>{let{drawPosition:sa,participantId:aa}=zo;return k=!0,{participantResult:aa&&Ko?.participantResults?.[aa],participantId:aa,drawPosition:sa}})}let ye=K?{stageSequence:K.stageSequence,structureName:K.structureName,structureType:K.structureType,finishingPosition:K.finishingPosition,matchUpFormat:K.matchUpFormat,stage:K.stage}:{},Jt=ot({element:K,name:El}).extension?.value;ye.display=Jt?.[_C]??Jt,ye.sourceStructureIds=D[Y],ye.hasDrawFeedProfile=b[Y],ye.positionAssignments=Dt,ye.structureActive=ct.reduce(($n,Kr)=>{let io=[Qt,ge,bn,ie,Zn,xt,Ue,Lt].includes(Kr.matchUpStatus);return $n||io||!!Kr.winningSide||!!Kr.score?.scoreStringSide1},!1);let pr=ct.every($n=>[...Mt,"BYE"].includes($n.matchUpStatus));return ye.structureCompleted=pr,z[Y]=pr,ye.structureActive&&(x=!0),{...ye,participantResults:pe,seedAssignments:J,roundMatchUps:Et,roundProfile:Wt,structureId:Y,report:U}});return W.forEach(K=>{r||delete K.positionAssignments,K.sourceStructuresComplete=K.sourceStructureIds?.every(Y=>z[Y])}),W}).flat().filter(B=>!s||eo(F?.[B?.structureId])||!0);return E.drawActive=x,E.participantPlacements=k,E.drawGenerated=V?.reduce((B,z)=>B||!!z?.roundMatchUps,!1),E.drawCompleted=V?.reduce((B,z)=>B&&z.structureCompleted,!0),E.drawPublished=s?L&&oA({publishStatus:v,drawId:E.drawId}):void 0,{structures:!s||E.drawPublished?d&&V||q(V,!1,!0):void 0,drawInfo:d?E:q(E,!1,!0),...P}}function zp(t){let{includePositionAssignments:e,participantsProfile:r,policyDefinitions:n,usePublishState:o,status:i=Ur,contextProfile:s,sortConfig:a}=t,c=X(t,[{tournamentRecord:!0},{[Ip]:{event:!1,eventId:!1}}]);if(c.error)return c;let u=q(t.tournamentRecord,!1,!0),p=t.event==null?_e({tournamentRecord:u,eventId:t.eventId}).event:void 0,m=t.event?q(t.event,!1,!0):p&&q(p,!1,!0)||void 0;if(!m)return{error:Gr};let{eventId:d}=m,{tournamentId:l,endDate:f}=u,g=Dr({event:m,status:i}),I=zs({event:m}).publishState??{},S=!!I?.status?.published,{participants:h}=bt({participantFilters:t.participantFilters,withGroupings:!0,withEvents:!1,withDraws:!1,policyDefinitions:n,...r,tournamentRecord:u}),T=({stage:v,drawId:w})=>{if(!o)return!0;let L=g?.drawDetails?.[w]?.stageDetails;return!L||!Object.keys(L).length?!0:eo(L[v])},y=({structureId:v,drawId:w})=>{if(!o)return!0;let L=g?.drawDetails?.[w]?.structureDetails;return!L||!Object.keys(L).length?!0:eo(L[v])},E=({drawId:v})=>o?oA({publishStatus:g,drawId:v}):!0,A=({drawId:v,drawType:w,structure:L})=>{if(!o||!Tn(w))return L;let F=g?.drawDetails?.[v]?.structureDetails?.[L.structureId]?.roundLimit;if(yt(F)){let x=Q(1,F+1),k={},G={};for(let V of x)L.roundMatchUps[V]&&(k[V]=L.roundMatchUps[V],G[V]=L.roundProfile[V]);L.roundMatchUps=k,L.roundProfile=G}return L},N=m.drawDefinitions??[],U=!o||S?N.filter(E).map(v=>(({drawInfo:w,structures:L})=>({...w,structures:L}))(hf({allParticipantResults:t.allParticipantResults,hydrateParticipants:t.hydrateParticipants,context:{eventId:d,tournamentId:l,endDate:f},pressureRating:t.pressureRating,refreshResults:t.refreshResults,includePositionAssignments:e,tournamentParticipants:h,eventPublishState:I,noDeepCopy:!0,policyDefinitions:n,tournamentRecord:u,usePublishState:o,contextProfile:s,drawDefinition:v,publishStatus:g,sortConfig:a,event:m}))).map(({structures:v,...w})=>{let L=v?.filter(({stage:F,structureId:x})=>y({structureId:x,drawId:w.drawId})&&T({stage:F,drawId:w.drawId})).map(F=>A({drawId:w.drawId,drawType:w.drawType,structure:F}));return{...w,structures:L}}).filter(v=>v.structures?.length):void 0,D=(Array.isArray(u.venues)?u.venues:[]).map(v=>{let{venueData:w}=Iu({venueId:v.venueId,tournamentRecord:u});return{...w}}),b=(({eventId:v,eventName:w,eventType:L,eventLevel:F,surfaceCategory:x,matchUpFormat:k,category:G,gender:V,startDate:B,endDate:z,ballType:W,discipline:K})=>({eventId:v,eventName:w,eventType:L,eventLevel:F,surfaceCategory:x,matchUpFormat:k,category:G,gender:V,startDate:B,endDate:z,ballType:W,discipline:K}))(m);b.display=ot({element:m,name:El}).extension?.value;let{tournamentInfo:C}=Js({tournamentRecord:u}),_={tournamentInfo:C,venuesData:D,eventInfo:b,drawsData:U};return _.eventInfo.publishState=I,_.eventInfo.published=I?.status?.published,{...P,eventData:_,participants:h}}function Tf({byeAdvancements:t=!1,tournamentRecord:e,drawDefinition:r,event:n}){if(!r)return{error:$};let{participantIds:o,participantIdMatchUps:i}=vF({tournamentParticipants:e?.participants,drawDefinition:r}),s=Object.values(i).some(f=>f.some(g=>g.containerStructureId)),c=(s&&zp({tournamentRecord:e,event:n}))?.eventData?.drawsData?.find(f=>f.drawId===r.drawId)?.structures,u=r?.structures?.find(f=>f.stage===H&&f.stageSequence===1),p=u?.structureType===de&&u.structures,d=(s?Cu({tournamentRecord:e,drawDefinition:r,structureId:u?.structureId})?.positionAssignments:void 0)?.length||0,l=o?.map(f=>{let I=i[f].filter(y=>[ie,"BYE"].includes(y.matchUpStatus)||y.winningSide),S=I.map(y=>{let E=y.sides.find(R=>R.bye),A=y.sides.find(R=>R.participantId===f).sideNumber;if(y.containerStructureId){let R=y4({containedStructures:p,drawPositionsCount:d,drawDataStructures:c,drawDefinition:r,participantId:f,matchUp:y});if(R)return R}return(y.winningSide||t&&E&&A)===A?y.finishingPositionRange.winner:y.finishingPositionRange.loser}),h=y=>Math.abs(y[0]-y[1]),T=S.reduce((y,E)=>y&&h(y)<h(E)?y:E,void 0);return{[f]:{finishingPositionRanges:S,finishingPositionRange:T,relevantMatchUps:I}}})??[];return Object.assign({},...l)}function y4({containedStructures:t,drawPositionsCount:e,drawDataStructures:r,drawDefinition:n,participantId:o,matchUp:i}){let a=t?.find(f=>f.structureId===i.structureId)?.positionAssignments?.length,c=r.find(f=>f.structureId===i.containerStructureId)?.participantResults?.find(f=>f.participantId===o)?.participantResult,{ties:u,groupOrder:p,provisionalOrder:m}=c??{},d=t?.length,l=n.structure?.find(f=>f.stage===Vt);if(je()&&console.log({drawPositionsCount:e,provisionalOrder:m,bracketsCount:d,bracketSize:a,groupOrder:p,ties:u}),e===a&&p)return[p,p];if(d>1&&p&&!l)return[1,d];if(d>1&&p&&l){let f=n.links?.find(I=>I.source.structureId===i.containerStructureId)?.source?.finishingPositions,g=f.length*d;if(p in f)return[1,g];{let I=(a-p)*d;return[g+1,e-I]}}}function Yo({tournamentRecords:t,tournamentRecord:e,tournamentId:r,drawId:n}){if(!e&&!t)return{error:j};if(!n)return{error:Pn};if(!e&&t){if(typeof r!="string"&&(r=zE({tournamentRecords:t,drawId:n}),!r))return{error:Za};if(e=t[r],!e)return{error:j}}let o=e&&_e({tournamentRecord:e,drawId:n});return o?.drawDefinition?{drawDefinition:o.drawDefinition,event:o.event,tournamentRecord:e,...P}:M({result:{error:Rr},stack:"findDrawDefinition"})}function iA(t){let{drawDefinition:e,error:r}=Yo(t);return r?{error:r}:{drawDefinition:q(e)}}function wF({tournamentParticipants:t,returnParticipants:e,drawPosition:r,participant:n,drawId:o,event:i}){let s=i?.entries?.filter(({entryStatus:a})=>[Lr,Bi].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:et({payload:{participantId:n.participantId,replacementIndividualParticipantId:void 0,existingIndividualParticipantId:void 0,drawPosition:r,drawId:o},method:pF,availableIndividualParticipantIds:s,availableIndividualParticipants:c,existingIndividualParticipantIds:a,existingIndividualParticipants:u,type:MS},!1,!1,!0)}}return{}}function Qi(t){let{inContextDrawMatchUps:e,targetData:r,drawDefinition:n,relevantLink:o}=t;if(o?.linkCondition===Bn&&r?.matchUp?.matchUpStatus==="BYE")return!1;let{targetMatchUps:{loserMatchUp:s,winnerMatchUp:a},targetLinks:c}=r,u=s&&er({matchUpId:s.matchUpId,inContextDrawMatchUps:e,drawDefinition:n}),p=u?.targetMatchUps?.loserMatchUp,m=u?.targetMatchUps?.loserMatchUpDrawPositionIndex,d=p?.sides[m]?.participant,l=Ye(s?.matchUpStatus),f=l&&!d,g=s?.sides?.filter(E=>E?.participant).length??0,I=s?.winningSide&&l&&g===1,S=a?.drawPositions?.filter(Boolean).length||0;if(!I&&(s?.winningSide&&!f||a?.winningSide&&S===2&&(!a.feedRound||!Ye(a?.matchUpStatus))))return!0;let h=a&&er({matchUpId:a.matchUpId,inContextDrawMatchUps:e,drawDefinition:n}),T=u&&Qi({relevantLink:c?.loserTargetLink,targetData:u,inContextDrawMatchUps:e,drawDefinition:n});return!!(h&&Qi({targetData:h,inContextDrawMatchUps:e,drawDefinition:n})||T)}var sA={[Jn]:{policyName:"positionActionsDefault",enabledStructures:[{stages:[Z,H],stageSequences:[1],enabledActions:[],disabledActions:[]},{stages:[],stageSequences:[],enabledActions:[jp,Fa,ud,La],disabledActions:[]}],disbledStructures:[],otherFlightEntries:!1,activePositionOverrides:[]}};var kS="positionAction",aA="matchUpAction";function cA({actionType:t=kS,appliedPolicies:e,drawDefinition:r,structure:n}){let o=t===kS&&Jn||t===aA&&We,i=t===kS&&sA||t===aA&&_b,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(S=>c.includes(S)))&&(!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 LF({activePositionOverrides:t,activeDrawPositions:e,action:r}){return r&&t.includes(r)?!0:!e.length}function uA({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),S=!l?.length||Array.isArray(l)&&l.some(h=>a.includes(h));return g&&I&&S&&u&&f})}}function jn({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 xC="replaceTieMatchUpParticipantId",wC="assignTieMatchUpParticipantId",pA="removeTieMatchUpParticipantId",LC="assignMatchUpSideParticipant",FF="removeMatchUpSideParticipant",FC="substituteParticipant",mA="REMOVE_SUBSTITUTION",kC="REPLACE_PARTICIPANT",GS="REMOVE_PARTICIPANT",dA="setMatchUpStatus",lA="SUBSTITUTION",GC="SCHEDULE",E4="PENALTY",fA="REFEREE",VC="STATUS",gA="START",BC="SCORE";var kF={REPLACE_TEAM_POSITION_METHOD:xC,ASSIGN_TEAM_POSITION_METHOD:wC,REMOVE_TEAM_POSITION_METHOD:pA,REPLACE_PARTICIPANT:kC,SUBSTITUTION_METHOD:FC,REMOVE_SUBSTITUTION:mA,REMOVE_PARTICIPANT:GS,SCHEDULE_METHOD:dA,SUBSTITUTION:lA,SCHEDULE:GC,PENALTY:E4,REFEREE:fA,STATUS:VC,SCORE:BC,START:gA,END:"END"};function GF({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=nn(o.gender)&&o.sideNumber&&o.sides?.filter(F=>F.particiapntId).length===1&&f?.participant?.person?.sex,I=o.matchUpType,h=(s??n?.participants?.enforceGender)!==!1?o.gender:void 0,y=o.sides?.flatMap(F=>F.participant?.individualParticipants||F.participant).filter(Boolean)?.map(ft),E=o.sides?.filter(F=>!c||F.sideNumber===c).flatMap(F=>F.participant?.individualParticipants||F.participant).filter(Boolean),A=E?.map(ft),U=e?.find(F=>F.matchUpId===o.matchUpTieId)?.sides?.map(F=>F?.participant?.individualParticipants?.filter(({participantId:x,person:k})=>!A?.includes(x)&&(!h||Co(h)||k.sex===h||nn(h)&&!g||g&&k.sex!==g))),R=c?U?.[c-1]:U?.map((F,x)=>({participants:F,sideNumber:x+1})),D=c?U?.[c-1]?.map(ft):U?.map((F,x)=>({participants:F?.map(ft),sideNumber:x+1})),b=c&&(re(bs)(I)&&!A?.length||re(Qo)(I)&&(A?.length??0)<2)||!c&&(re(bs)(I)&&(A?.length??0)<2||re(Qo)(I)&&(A?.length??0)<4),C=D?.filter(F=>!y?.includes(F)),_=R?.filter(({participantId:F})=>C.includes(F));if(b&&C?.length&&l.push({availableParticipantIds:C,method:wC,availableParticipants:_,type:Qs,payload:{participantId:void 0,tieMatchUpId:u,sideNumber:c,drawId:m}}),A?.length&&(!ue(p)||d?.substitutions?.length)&&l.push({method:pA,type:GS,existingParticipantIds:A,payload:{participantId:void 0,tieMatchUpId:u,drawId:m}}),_?.length&&(!c&&A?.length||c&&d?.participant)&&l.push({availableParticipantIds:C,method:xC,availableParticipants:_,type:kC,existingParticipantIds:A,payload:{existingParticipantId:void 0,participantId:void 0,tieMatchUpId:u,drawId:m}}),jn({policyActions:i,action:mA})&&d?.substitutions?.length){let F=d.participant?.participantType===St&&[d.participantId]||d.participant?.participantType===lt&&d.participant.individualParticipantIds||[],x=d.substitutions.map(k=>k.participantId).filter(k=>F.includes(k));(!a||x.includes(a))&&l.push({method:pA,type:mA,substitutedParticipantIds:x,payload:{participantId:void 0,tieMatchUpId:u,drawId:m}})}let v=t?.[We],w=v?.substituteWithoutScore,L=v?.substituteAfterCompleted;if(jn({policyActions:i,action:lA})&&r.length===2&&(!c&&A?.length||c&&d?.participant)&&(w||ue(p))&&(L||p.matchUpStatus&&!Mt.includes(p.matchUpStatus))&&E?.length&&R.length){let F=E.map(ft);l.push({info:"list of team players available for substitution",method:FC,availableParticipantIds:D,existingParticipantIds:F,availableParticipants:R,existingParticipants:E,type:lA,payload:{substituteParticipantId:void 0,existingParticipantId:void 0,sideNumber:c,matchUpId:u,drawId:m}})}return l}function VF({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===Qs)?.availableParticipantIds,f=i?.[Jn]?.otherFlightEntries,g=i?.[Jn]?.restrictQualifyingAlternates,I=(s.entries??[]).filter(({entryStage:U})=>!g||(p.stage===Z?U===Z:U!==Z)).sort((U,R)=>(U.entryPosition??1/0)-(R.entryPosition??1/0)).map(({participantId:U})=>U).filter(Boolean),{allPositionedParticipantIds:S}=Vy({drawDefinition:s}),h=n.map(U=>U.participantId).filter(Boolean),T=I.filter(U=>p.stage&&[Z,H,Vt].includes(p.stage)?!S?.includes(U):!h.includes(U)),E=(d?.entries??[]).filter(U=>U.entryStatus===Zr&&HC({restrictQualifyingAlternates:g,structure:p,entry:U})&&(p.stage&&[Z,H,Vt].includes(p.stage)?!S?.includes(U.participantId):!h.includes(U.participantId))).sort((U,R)=>(U.entryPosition??1/0)-(R.entryPosition??1/0)).map(U=>U.participantId),A=pt(T.concat(E));if(f){let R=(d?Bt({event:d}).flightProfile:void 0)?.flights?.filter(D=>D.drawId!==m).map(D=>D.drawEntries.filter(b=>b.participantId&&![Cn,Lr,Bi].includes(b.entryStatus)&&!I.includes(b.participantId)).map(({participantId:b})=>b)).flat().filter(Boolean);R?.length&&A.push(...R)}l?.length&&(A=A.filter(U=>!l.includes(U)));let N=o?t?.filter(U=>A.includes(U.participantId)):void 0;return N?.forEach(U=>{let R=(s.entries??[]).find(D=>D.participantId===U.participantId);U.entryPosition=R?.entryPosition}),N?.sort((U,R)=>(U.entryPosition||1/0)-(R.entryPosition||1/0)),A.length?{validAlternatesAction:et({payload:{drawId:m,structureId:u,drawPosition:a},willDisableLinks:e,method:cF,availableAlternatesParticipantIds:A,type:vS,availableAlternates:N})}:{}}function HC({restrictQualifyingAlternates:t,structure:e,entry:r}){let{stage:n}=e;if(!r.entryStage||r.entryStage===n||n===Z&&!t||r.entryStage===H&&n===me)return!0}function BF({eventEntries:t,structure:e}){let r=o=>o.entryStatus===Zr&&HC({structure:e,entry:o}),n=(o,i)=>(o.entryPosition||1/0)-(i.entryPosition||1/0);return t.filter(r).sort(n).map(ft)}function HF({restrictAdHocRoundParticipants:t,tournamentParticipants:e,matchUpParticipantIds:r,otherFlightEntries:n,drawDefinition:o,structureId:i,sideNumber:s,matchUpId:a,structure:c,matchUp:u,drawId:p,event:m}){let d=[],l=c?.matchUps??[],g=u.sides?.find(R=>R.sideNumber===s)?.participantId,I=l.filter(({roundNumber:R})=>R===u.roundNumber),S=o?.entries?.filter(({entryStatus:R})=>R&&Hi.includes(R)).map(ft)??[],h=I.map(R=>(R.sides??[]).flatMap(ft)).flat().filter(Boolean),T=S.filter(R=>!r.includes(R)&&(!t||!h.includes(R))),y=e?.filter(R=>T?.includes(R.participantId)).map(R=>q(R,void 0,!0));y?.forEach(R=>{let D=(o.entries??[]).find(b=>b.participantId===R.participantId);R.entryPosition=D?.entryPosition}),T.length&&d.push({payload:{drawId:p,matchUpId:a,structureId:i,sideNumber:s},method:LC,type:Qs,availableParticipantIds:T,participantsAvailable:y});let E=m?.entries??[],A=BF({eventEntries:E,structure:c}),N=pt(S.concat(A));if(n){let D=(m?Bt({event:m}):void 0)?.flights?.filter(b=>b.drawId!==p).flatMap(b=>b.drawEntries.filter(C=>C.participantId&&![Cn,Lr,Bi].includes(C.entryStatus)).map(({participantId:C})=>C)).filter(Boolean);D?.length&&N.push(...D)}N=N.filter(R=>!r.includes(R)&&!T.includes(R)&&(!t||!h.includes(R)));let U=e?.filter(R=>N.includes(R.participantId)).map(R=>q(R,void 0,!0));if(U?.forEach(R=>{let D=(o.entries??[]).find(b=>b.participantId===R.participantId);R.entryPosition=D?.entryPosition}),U?.sort((R,D)=>(R.entryPosition||1/0)-(D.entryPosition||1/0)),N.length&&d.push({payload:{drawId:p,matchUpId:a,structureId:i,sideNumber:s},availableParticipantIds:N,participantsAvailable:U,method:LC,type:Zr}),!ue(u)&&s&&g){d.push({payload:{drawId:p,matchUpId:a,structureId:i,sideNumber:s},method:FF,type:GS});let R=x=>x.sides.map(ft),D=({matchUpId:x})=>x!==u.matchUpId,b=x=>!ue(x),C=u.sides?.find(x=>x.sideNumber!==s)?.participantId,v=l.filter(({roundNumber:x})=>x!==u.roundNumber).filter(D).map(R),w=[C,...v.filter(x=>x.includes(g)).flat()].filter(Boolean),L=x=>!w.flat().includes(x),F=I.filter(b).filter(D).map(R).flat().filter(L);if(F.length){let x=e?.filter(k=>F.includes(k.participantId)).map(k=>q(k,void 0,!0));d.push({payload:{participantIds:[g],roundNumber:u.roundNumber,structureId:i,sideNumber:s,matchUpId:a,drawId:p},swappableParticipantIds:F,method:mF,type:md,swappableParticipants:x})}}return d}function yf(t){if(!t)return{error:O};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&&_t(t.tournamentId)&&t.tournamentRecords?.[t.tournamentId]);if(!u)return{error:j};if(!c||!_t(c))return{error:mr};if(a&&![1,2].includes(a))return M({result:{error:O},context:{sideNumber:a}});if(!e){let w=A4({tournamentRecord:u,matchUpId:c});w.drawDefinition&&(e=w.drawDefinition),w.event&&(r=w.event)}if(!e)return{error:$};let p=bt({withIndividualParticipants:!0,tournamentRecord:u}).participants,{drawId:m}=e,{matchUp:d,structure:l}=Ht({drawDefinition:e,matchUpId:c,event:r});if(!d)return{error:Be};let{appliedPolicies:f,policyActions:g,matchUpActionsPolicy:I,otherFlightEntries:S}=P4({specifiedPolicyDefinitions:o,tournamentRecord:u,drawDefinition:e,structure:l,event:r}),h=t.matchUpsMap??Ie({drawDefinition:e}),T=t.inContextDrawMatchUps??te({tournamentParticipants:p,inContext:!0,drawDefinition:e,matchUpsMap:h,event:r}).matchUps,y=T?.find(w=>w.matchUpId===c),E=a&&y?.sides?.find(w=>w.sideNumber===a),A=y?.sides?.map(w=>w.participantId||w.participant?.participantid).filter(Boolean)??[],{assignedPositions:N,allPositionsAssigned:U}=se({structure:l}),{structureId:R}=l??{},D=[];if(!R)return{validActions:D};let b=!!d.collectionId;Ae({structure:l})&&!b&&D.push(...HF({restrictAdHocRoundParticipants:n,tournamentParticipants:p,matchUpParticipantIds:A,otherFlightEntries:S,drawDefinition:e,structureId:R,sideNumber:a,matchUpId:c,structure:l,matchUp:d,drawId:m,event:r}));let C=No({drawDefinition:e,structure:l}),_=N4({matchUp:d,isCollectionMatchUp:b,assignedPositions:N});if(_)return{validActions:D,isByeMatchUp:_};let v=d.matchUpStatus&&[Qt,ge].includes(d.matchUpStatus);return U4({validActions:D,policyActions:g,matchUpActionsPolicy:I,specifiedPolicyDefinitions:o,inContextDrawMatchUps:T,matchUpParticipantIds:A,allPositionsAssigned:U,inContextMatchUp:y,assignedPositions:N,appliedPolicies:f,isCollectionMatchUp:b,enforceGender:i,participantId:s,isDoubleExit:v,sideNumber:a,matchUpId:c,structure:l,matchUp:d,drawId:m,drawDefinition:e,side:E}),{structureIsComplete:C,validActions:D,isDoubleExit:v,...P}}function A4({tournamentRecord:t,matchUpId:e}){let n=(qt({tournamentRecord:t}).matchUps??[]).find(s=>s.matchUpId===e),o=(t?.events??[]).find(s=>s.eventId===n?.eventId);return{drawDefinition:(o?.drawDefinitions??[]).find(s=>s.drawId===n?.drawId),event:o}}function P4({specifiedPolicyDefinitions:t,tournamentRecord:e,drawDefinition:r,structure:n,event:o}){let i=It({tournamentRecord:e,drawDefinition:r,structure:n,event:o}).appliedPolicies??{};Object.assign(i,t??{});let s=i?.[Jn]?.otherFlightEntries,a=i?.[We]??ys[We],{enabledStructures:c}=cA({actionType:aA,appliedPolicies:i,drawDefinition:r,structure:n}),{policyActions:u}=uA({enabledStructures:c,drawDefinition:r,structure:n});return{appliedPolicies:i,policyActions:u,matchUpActionsPolicy:a,otherFlightEntries:s}}function N4({matchUp:t,isCollectionMatchUp:e,assignedPositions:r}){let n=r?.filter(o=>o.bye).map(o=>o.drawPosition);return t.matchUpStatus==="BYE"||!e&&t.drawPositions?.reduce((o,i)=>n?.includes(i)||o,!1)}function U4({validActions:t,policyActions:e,matchUpActionsPolicy:r,specifiedPolicyDefinitions:n,inContextDrawMatchUps:o,matchUpParticipantIds:i,allPositionsAssigned:s,inContextMatchUp:a,assignedPositions:c,appliedPolicies:u,isCollectionMatchUp:p,enforceGender:m,participantId:d,isDoubleExit:l,sideNumber:f,matchUpId:g,structure:I,matchUp:S,drawId:h,drawDefinition:T,side:y}){jn({policyActions:e,action:fA})&&t.push({type:fA,payload:{matchUpId:g}});let E=!Oa({matchUpStatus:S.matchUpStatus}),A=D4({appliedPolicies:u,allPositionsAssigned:s,structure:I}),N=S.sides?.filter(_=>_?.participantId).length===2,U=er({inContextDrawMatchUps:o,drawDefinition:T,matchUpId:g}),R=Qi({inContextDrawMatchUps:o,drawDefinition:T,targetData:U}),D=c?.filter(_=>_.participantId).map(_=>_.drawPosition),C=(a?.drawPositions?.length===2&&a.drawPositions.every(_=>D?.includes(_))&&a?.sides?.length===2&&a.sides.every(({participantId:_})=>_)||N)&&!(l&&R);E&&t.push({payload:{drawId:h,matchUpId:g,schedule:{}},method:dA,type:GC}),jn({policyActions:e,action:Fa})&&(y?.participant||!f&&i?.length)&&t.push({method:jE,type:Fa,payload:{drawId:h,matchUpId:g,penaltyCode:void 0,penaltyType:void 0,participantIds:[],notes:void 0}}),E&&C&&t.push({type:VC}),A&&C&&(t.push({info:"set outcome and winningSide",method:dA,type:BC,payload:{drawId:h,matchUpId:g,matchUpFormat:S.matchUpFormat,outcome:{scoreStringSide1:void 0,scoreStringSide2:void 0,sets:[]},winningSide:void 0}}),jn({policyActions:e,action:gA})&&t.push({type:gA}),jn({policyActions:e,action:"END"})&&t.push({type:"END"})),p&&a&&t.push(...GF({specifiedPolicyDefinitions:n,inContextDrawMatchUps:o,matchUpParticipantIds:i,matchUpActionsPolicy:r,inContextMatchUp:a,policyActions:e,enforceGender:m,participantId:d,sideNumber:f,matchUpId:g,matchUp:S,drawId:h,side:y}))}function D4({appliedPolicies:t,allPositionsAssigned:e,structure:r}){let n=t?.scoring?.structures,o=r?.stage&&n?.stage?.[r.stage],i=r?.stageSequence&&o?.stageSequence?.[r.stageSequence];return!(t?.scoring?.requireAllPositionsAssigned||o?.requireAllPositionsAssigned||i?.requireAllPositionsAssigned)||e}function YF({positionAssignments:t,activeDrawPositions:e,drawDefinition:r,isByePosition:n,structure:o,drawPosition:i,structureId:s,drawId:a}){if(o.stage!==H||o.stageSequence!==1)return{};if(o.structureType===de)return{};if(n)return{};if(e.length)return{};let c=t.find(f=>f.drawPosition===i);if(!c?.participantId)return{};let{seedAssignments:u}=Pr({drawDefinition:r,structure:o});if(!u?.length)return{};let p=u.find(f=>f.participantId===c.participantId);if(!p)return{};let{validSeedBlocks:m}=di({drawDefinition:r,structure:o});if(!m?.length)return{};let d=m.findIndex(f=>f.seedNumbers.includes(p.seedNumber));return d<0||d>=m.length-1?{}:m.slice(d+1).some(f=>u.some(g=>f.seedNumbers.includes(g.seedNumber)&&g.participantId))?{validSeedCascadeAction:{type:fC,method:IF,payload:{drawId:a,structureId:s,drawPosition:i}}}:{}}function jF({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((S,h)=>{let T=h.source?.structureId,y=h.target?.structureId;return S.sourceStructureIds.includes(T)||S.sourceStructureIds.push(T),S.targetStructureIds.includes(y)||S.targetStructureIds.push(y),S},{sourceStructureIds:[],targetStructureIds:[]})??{},f=[],g=s.links?.filter(S=>S.target?.structureId===u.structureId)??[];for(let S of g){let h=S?.source?.structureId,{structure:T}=tt({structureId:h,drawDefinition:s}),y=T?.finishingPosition===ls&&(d?.length!==1||l?.length!==1),E={};if(y){let{matchUps:R}=ht({drawDefinition:s,structure:u,event:m}),{initialRoundNumber:D}=qs({drawPosition:a,matchUps:R}),C=s.links?.find(_=>_.target?.structureId===u?.structureId&&_.target.roundNumber===D)?.source?.roundNumber;E.roundNumbers=[C]}let{completedMatchUps:A}=wp({structureId:h,inContext:!0,matchUpFilters:E,drawDefinition:s}),N=i.map(R=>R.participantId).filter(Boolean);A?.filter(({matchUpType:R,winningSide:D})=>D&&(m?.eventType!==Oe||R===Oe)).map(({winningSide:R,sides:D})=>R&&D?.[1-(R-1)]).map(ft).filter(R=>R&&!N.includes(R))?.forEach(R=>{f.includes(R)||f.push(R)})}let I=t?.filter(S=>f?.includes(S.participantId));return I?.forEach(S=>{let h=(s.entries??[]).find(T=>T.participantId===S.participantId);S.entryPosition=h?.entryPosition}),f?.length?{validLuckyLosersAction:{type:_S,method:uF,availableLuckyLosers:I,availableLuckyLoserParticipantIds:f,willDisableLinks:r,payload:{drawId:p,structureId:c,drawPosition:a}}}:{}}function qF({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=[],S,h,T=[],y=c?.[Hn]?.validSeedPositions?.ignore;if(y||({unplacedSeedParticipantIds:S,unplacedSeedAssignments:h,unfilledPositions:T}=AE({provisionalPositioning:n,returnAllProxies:!0,randomize:!0,drawDefinition:u,seedingProfile:p,structureId:l,event:f})),T?.length||(T=s.filter(E=>!E.participantId&&!E.bye&&!E.qualifier).map(E=>E.drawPosition)),m||I.push({payload:{drawId:g,structureId:l,drawPosition:d,isPositionAction:!0},willDisableLinks:r,method:fF,type:"BYE"}),i&&y){let E=s.map(D=>D.participantId).filter(Boolean),A={structureIds:t},{completedMatchUps:N}=va({inContext:!0,matchUpFilters:A,drawDefinition:u}),U=pt((N??[]).filter(({matchUpType:D})=>f?.eventType!==Oe||D===Oe)?.map(({sides:D})=>D?.map(ft)).flat().filter(D=>D&&!E.includes(D))),R=a?o?.filter(D=>U?.includes(D.participantId)).map(D=>q(D,void 0,!0)):void 0;return R?.forEach(D=>{let b=(u.entries??[]).find(C=>C.participantId===D.participantId);D.entryPosition=b?.entryPosition}),R?.length&&I.push(et({payload:{drawId:g,structureId:l,drawPosition:d},willDisableLinks:r,method:lC,type:Qs,availableParticipantIds:U,participantsAvailable:R})),{validAssignmentActions:I}}if(T.includes(d)||m){let E;if(h?.length){let N=h.filter(U=>S?.includes(U.participantId));N.sort(R4),E=N.map(U=>U.participantId)}else E=e;let A=a?o?.filter(N=>E.includes(N.participantId)).map(N=>q(N,void 0,!0)):void 0;A?.length&&I.push(et({payload:{drawId:g,structureId:l,drawPosition:d},willDisableLinks:r,method:lC,type:Qs,availableParticipantIds:E,participantsAvailable:A}))}return{validAssignmentActions:I}}function R4(t,e){return t.bye||Eu(t.seedValue)<Eu(e.seedValue)||t.seedValue&&!e.seedValue?-1:(t.seedNumber||0)-(e.seedNumber||0)}function $F({drawPositionInitialRounds:t,tournamentParticipants:e,positionAssignments:r,returnParticipants:n,appliedPolicies:o,drawDefinition:i,drawPosition:s,structureId:a,drawId:c}){let u=[],p=[],m=[],d=[],l=new Set(r.map(E=>E.participantId).filter(Boolean)),f=o?.[Jn],g=!f?.disableRoundRestrictions&&t[s],I=f?.requireCompletedStructures,{sourceStructureIds:S,relevantLinks:h}=Wp({targetRoundNumber:g,linkType:Er,drawDefinition:i,structureId:a})??{};S?.length&&d.push(...S);let{sourceStructureIds:T,relevantLinks:y}=Wp({targetRoundNumber:g,linkType:fn,drawDefinition:i,structureId:a})??{};return T?.length&&d.push(...T),b4({requireCompletedStructures:I,tournamentParticipants:e,assignedParticipantIds:l,eliminationSourceLinks:h,qualifyingParticipantIds:p,qualifyingParticipants:u,returnParticipants:n,drawDefinition:i}),C4({requireCompletedStructures:I,tournamentParticipants:e,assignedParticipantIds:l,qualifyingParticipantIds:p,qualifyingParticipants:u,roundRobinSourceLinks:y,returnParticipants:n,drawDefinition:i}),p.length&&m.push(et({qualifyingParticipants:n?u:void 0,method:sF,type:ud,qualifyingParticipantIds:p,payload:{qualifyingParticipantId:void 0,drawPosition:s,structureId:a,drawId:c}})),{validAssignmentActions:m,sourceStructureIds:d}}function b4({requireCompletedStructures:t,tournamentParticipants:e,assignedParticipantIds:r,eliminationSourceLinks:n,qualifyingParticipantIds:o,qualifyingParticipants:i,returnParticipants:s,drawDefinition:a}){for(let c of n){let u=a.structures?.find(l=>l.structureId===c.source.structureId);if(u?.stage!==Z)continue;let p=No({structureId:c.source.structureId,drawDefinition:a});if(t&&!p)continue;let m=u.qualifyingRoundNumber,{matchUps:d}=ht({matchUpFilters:{roundNumbers:[m],isCollectionMatchUp:!1,hasWinningSide:!0},afterRecoveryTimes:!1,tournamentParticipants:e,inContext:!0,structure:u});for(let l of d){let f=l.sides.find(I=>I?.sideNumber===l.winningSide),g=l.matchUpStatus==="BYE"&&l.sides?.find(({participantId:I})=>I);if(f||g){let{participantId:I,participant:S}=f||(g??{});I&&!r.has(I)&&(S&&s&&i.push(S),o.push(I))}}}}function C4({requireCompletedStructures:t,tournamentParticipants:e,assignedParticipantIds:r,qualifyingParticipantIds:n,qualifyingParticipants:o,roundRobinSourceLinks:i,returnParticipants:s,drawDefinition:a}){for(let c of i){let u=a.structures?.find(l=>l.structureId===c.source.structureId);if(u?.stage!==Z)continue;let p=No({structureId:c.source.structureId,drawDefinition:a});if(t&&!p)continue;let{positionAssignments:m}=Pt({structure:u}),d=m?.map(l=>{let f=l.participantId,g=ot({element:l,name:Lo}).extension?.value;return g?{participantId:f,groupOrder:g?.groupOrder}:{}}).filter(({groupOrder:l,participantId:f})=>l===1&&!r.has(f)).map(({participantId:l})=>l)??[];if(d&&n.push(...d),s){let l=new Set(d),f=e.filter(({participantId:g})=>l.has(g));o.push(...f)}}}function KF({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=D=>!t||D.participantId||D.qualifier||D.bye,I=n?.filter(D=>D!==p&&!(u&&a.includes(D))),S=i?.filter(D=>g(D)&&I?.includes(D.drawPosition))??[],h=S.map(({drawPosition:D})=>D),{matchUps:T}=ht({afterRecoveryTimes:!1,inContext:!0,drawDefinition:c,structure:d,event:f}),y=T.filter(({drawPositions:D})=>Re(D,h)),E=Object.assign({},...y.map(D=>D.sides?.filter(({sourceDrawPositionRange:b})=>b).map(({drawPosition:b,sourceDrawPositionRange:C})=>({[b]:C}))).flat()),A=S.map(D=>D.participantId).filter(Boolean),N=(r??[]).filter(D=>A.includes(D.participantId)),U=Object.assign({},...N.map(D=>({[D.participantId]:D}))),R=S.map(D=>{let b=U?.[D.participantId],C=E[D.drawPosition];return et({...D,participant:s?q(b,!1,!0):void 0,sourceDrawPositionRange:C})});return R.length?{validSwapAction:{payload:{drawId:l,structureId:m,drawPositions:[p]},willDisableLinks:e,method:YE,type:md,availableAssignments:R}}:{}}function M4(t,e){return t.filter(r=>!e.includes(r.participantId)).map(r=>r.participantId)}function v4({validActions:t,policyActions:e,isActiveDrawPosition:r,positionAssignments:n,disablePlacementActions:o,positionAssignment:i,isByePosition:s,getValidAssignmentActions:a,positionSourceStructureIds:c,unassignedParticipantIds:u,possiblyDisablingAction:p,isWinRatioFedStructure:m,tournamentParticipants:d,returnParticipants:l,appliedPolicies:f,drawDefinition:g,drawPosition:I,structureId:S,event:h}){if(jn({policyActions:e,action:Qs})&&!r&&n&&!o&&(!i||s)){let{validAssignmentActions:T}=a({positionSourceStructureIds:c,unassignedParticipantIds:u,possiblyDisablingAction:p,isWinRatioFedStructure:m,tournamentParticipants:d,positionAssignments:n,returnParticipants:l,appliedPolicies:f,drawDefinition:g,isByePosition:s,drawPosition:I,structureId:S,event:h});T?.forEach(y=>t.push(y))}}function O4({validActions:t,policyActions:e,isActiveDrawPosition:r,getValidQualifiersAction:n,drawPositionInitialRounds:o,tournamentParticipants:i,positionAssignments:s,returnParticipants:a,appliedPolicies:c,drawDefinition:u,drawPosition:p,structureId:m,drawId:d}){if(jn({policyActions:e,action:ud})&&!r){let{validAssignmentActions:l}=n({drawPositionInitialRounds:o,tournamentParticipants:i,positionAssignments:s,returnParticipants:a,appliedPolicies:c,drawDefinition:u,drawPosition:p,structureId:m,drawId:d});l?.forEach(f=>t.push(f))}}function _4({isLuckyDrawAdvancedPosition:t,validActions:e,policyActions:r,isActiveDrawPosition:n,drawId:o,structureId:i,drawPosition:s,possiblyDisablingAction:a,isByePosition:c}){jn({policyActions:r,action:qE})&&!n&&(e.push({type:qE,method:dC,payload:{drawId:o,structureId:i,drawPosition:s},willDisableLinks:a}),!c&&!t&&e.push({type:OS,method:aF,payload:{drawId:o,structureId:i,drawPosition:s},willDisableLinks:a}),jn({policyActions:r,action:"BYE"})&&!c&&!t&&e.push({type:"BYE",method:dC,payload:{drawId:o,structureId:i,drawPosition:s,replaceWithBye:!0},willDisableLinks:a}))}function x4({validActions:t,policyActions:e,activePositionsCheck:r,activePositionOverrides:n,activeDrawPositions:o,drawDefinition:i,structureId:s,drawPosition:a,structure:c,isByePosition:u,participantId:p,participant:m,drawId:d}){let l=c.stage===Z||c.stage===H&&c.stageSequence===1;if(!u&&r({activePositionOverrides:n,activeDrawPositions:o,action:La})&&jn({policyActions:e,action:La})&&sd({drawDefinition:i,structureId:s,drawPosition:a})&&l){let{seedAssignments:f}=Pr({returnAllProxies:!0,drawDefinition:i,structure:c}),{seedNumber:g,seedValue:I}=f?.find(S=>S.participantId===p)??{};t.push({type:La,method:gF,participant:m,seedNumber:g,payload:{drawId:d,structureId:s,participantId:p,seedValue:I}})}if(!u&&r({activePositionOverrides:n,activeDrawPositions:o,action:pd})&&jn({policyActions:e,action:pd})&&sd({drawDefinition:i,structureId:s,drawPosition:a})&&l){let{seedAssignments:f}=Pr({returnAllProxies:!0,drawDefinition:i,structure:c}),{seedNumber:g}=f?.find(I=>I.participantId===p)??{};t.push({method:lF,type:pd,participant:m,seedNumber:g,payload:{participantId:p,structureId:s,drawId:d}})}}function w4({validActions:t,policyActions:e,isByePosition:r,participantId:n,participant:o,drawId:i}){if(!r&&n){if(jn({policyActions:e,action:Fa})){let s={type:Fa,method:jE,participant:o,payload:{penaltyCode:void 0,penaltyType:void 0,participantIds:[],notes:void 0,drawId:i}};t.push(s)}if(jn({policyActions:e,action:jp})){let s={type:jp,method:dF,participant:o,payload:{participantId:n,otherName:void 0}};t.push(s)}}}function L4({validActions:t,policyActions:e,getValidSwapAction:r,possiblyDisablingAction:n,tournamentParticipants:o,inactiveDrawPositions:i,activeDrawPositions:s,positionAssignments:a,returnParticipants:c,byeDrawPositions:u,drawDefinition:p,isByePosition:m,drawPosition:d,structureId:l,structure:f,drawId:g}){if(jn({policyActions:e,action:md})){let{validSwapAction:I}=r({possiblyDisablingAction:n,tournamentParticipants:o,inactiveDrawPositions:i,activeDrawPositions:s,positionAssignments:a,returnParticipants:c,byeDrawPositions:u,drawDefinition:p,isByePosition:m,drawPosition:d,structureId:l,structure:f,drawId:g});I&&t.push(I)}}function F4({validActions:t,policyActions:e,getValidAlternatesAction:r,possiblyDisablingAction:n,tournamentParticipants:o,positionAssignments:i,activeDrawPositions:s,returnParticipants:a,appliedPolicies:c,drawDefinition:u,drawPosition:p,structureId:m,structure:d,drawId:l,event:f,disablePlacementActions:g}){if(jn({policyActions:e,action:vS})&&!g){let{validAlternatesAction:I}=r({possiblyDisablingAction:n,tournamentParticipants:o,positionAssignments:i,activeDrawPositions:s,returnParticipants:a,appliedPolicies:c,drawDefinition:u,drawPosition:p,validActions:t,structureId:m,structure:d,drawId:l,event:f});I&&t.push(I)}}function k4({validActions:t,policyActions:e,getValidLuckyLosersAction:r,sourceStructuresComplete:n,possiblyDisablingAction:o,isWinRatioFedStructure:i,tournamentParticipants:s,activeDrawPositions:a,positionAssignments:c,drawDefinition:u,drawPosition:p,structureId:m,structure:d,drawId:l,disablePlacementActions:f,isActiveDrawPosition:g}){if(jn({policyActions:e,action:_S})&&!f&&!g&&c){let{validLuckyLosersAction:I}=r({sourceStructuresComplete:n,possiblyDisablingAction:o,isWinRatioFedStructure:i,tournamentParticipants:s,activeDrawPositions:a,positionAssignments:c,drawDefinition:u,drawPosition:p,structureId:m,structure:d,drawId:l});I&&t.push(I)}}function G4({validActions:t,policyActions:e,getValidModifyAssignedPairAction:r,participant:n,tournamentParticipants:o,returnParticipants:i,drawPosition:s,drawId:a,event:c}){if(n?.participantType===lt&&jn({policyActions:e,action:MS})){let{validModifyAssignedPairAction:u}=r({tournamentParticipants:o,returnParticipants:i,drawPosition:s,participant:n,drawId:a,event:c});u&&t.push(u)}}function SA(t){return B4(t)}function V4(t){let e=X(t,[{event:!0,drawDefinition:!0,structureId:!0}]);if(e.error)return{earlyReturn:e};let{policyDefinitions:r,returnParticipants:n=!0,provisionalPositioning:o,tournamentRecord:i,drawDefinition:s,drawPosition:a,event:c}=t,u=t.tournamentParticipants??(i&&bt({withIndividualParticipants:!0,tournamentRecord:i}).participants)??[],p=tt({structureId:t.structureId,drawDefinition:s});if(p.error)return{earlyReturn:p};let m=p.containingStructure||p.structure;if(!m)return{earlyReturn:{error:Nt}};let d=m.structureId;if(p=qi({drawDefinition:s,structureId:d}),a===void 0&&!p.isAdHoc)return{earlyReturn:{error:da}};if(p.isAdHoc)return{earlyReturn:yf(t)};if(p.error)return{earlyReturn:p};let{drawPositionInitialRounds:l,inactiveDrawPositions:f,activeDrawPositions:g,byeDrawPositions:I}=p,S=It({tournamentRecord:i,drawDefinition:s,structure:m,event:c}).appliedPolicies??{};Object.assign(S,r??{});let{actionsPolicy:h,enabledStructures:T,actionsDisabled:y}=cA({actionType:kS,appliedPolicies:S,drawDefinition:s,structure:m}),E=h?.activePositionOverrides??[],{sourceStructureIds:A}=Wp({finishingPosition:uo,targetRoundNumber:1,linkType:fn,drawDefinition:s,structureId:d})??{},N;A?.length&&(N=A.every(J=>No({structureId:J,drawDefinition:s})));let U=A.length,R=A.length&&!N,{policyActions:D}=uA({enabledStructures:T,drawDefinition:s,structure:m}),b=![Z,H].includes(m.stage)||m.stageSequence!==1,{drawId:C}=s,{assignedPositions:_,positionAssignments:v}=se({structure:m}),w=_?.find(J=>J.drawPosition===a),L=!!w;if(!v?.map(J=>J.drawPosition)?.includes(a)&&!(m.matchUps?.flatMap(ct=>ct.drawPositions??[])??[]).includes(a))return{earlyReturn:{error:is}};let{stage:x,stageSequence:k}=m,G=[x];x===me&&G.push(H),x===H&&G.push(me);let V=Wi({entryStatuses:Hi,provisionalPositioning:o,drawDefinition:s,stageSequence:k,structureId:d,stages:G}),B=$i({drawDefinition:s,stages:G}).assignedParticipantIds??[],z=M4(V,B),W=I.includes(a),K=g.includes(a),Y=an(s.drawType)&&l?.[a]>1;return y?{earlyReturn:{info:"Actions Disabled for structure",isActiveDrawPosition:K,isDrawPosition:!0,hasPositionAssigned:L,validActions:[],isByePosition:W}}:{positionSourceStructureIds:A,isLuckyDrawAdvancedPosition:Y,drawPositionInitialRounds:l,unassignedParticipantIds:z,sourceStructuresComplete:N,activePositionOverrides:E,tournamentParticipants:u,disablePlacementActions:R,possiblyDisablingAction:b,isWinRatioFedStructure:U,inactiveDrawPositions:f,isActiveDrawPosition:K,positionAssignments:v,hasPositionAssigned:L,positionAssignment:w,activeDrawPositions:g,returnParticipants:n,byeDrawPositions:I,appliedPolicies:S,drawDefinition:s,policyActions:D,isByePosition:W,drawPosition:a,structureId:d,structure:m,drawId:C,event:c}}function B4(t){let e=V4(t);if("earlyReturn"in e)return e.earlyReturn;let{positionSourceStructureIds:r,isLuckyDrawAdvancedPosition:n,drawPositionInitialRounds:o,unassignedParticipantIds:i,sourceStructuresComplete:s,activePositionOverrides:a,tournamentParticipants:c,disablePlacementActions:u,possiblyDisablingAction:p,isWinRatioFedStructure:m,inactiveDrawPositions:d,isActiveDrawPosition:l,positionAssignments:f,hasPositionAssigned:g,positionAssignment:I,activeDrawPositions:S,returnParticipants:h,byeDrawPositions:T,appliedPolicies:y,drawDefinition:E,policyActions:A,isByePosition:N,drawPosition:U,structureId:R,structure:D,drawId:b,event:C}=e,_=[];v4({validActions:_,policyActions:A,isActiveDrawPosition:l,positionAssignments:f,disablePlacementActions:u,positionAssignment:I,isByePosition:N,getValidAssignmentActions:qF,positionSourceStructureIds:r,unassignedParticipantIds:i,possiblyDisablingAction:p,isWinRatioFedStructure:m,tournamentParticipants:c,returnParticipants:h,appliedPolicies:y,drawDefinition:E,drawPosition:U,structureId:R,event:C}),O4({validActions:_,policyActions:A,isActiveDrawPosition:l,getValidQualifiersAction:$F,drawPositionInitialRounds:o,tournamentParticipants:c,positionAssignments:f,returnParticipants:h,appliedPolicies:y,drawDefinition:E,drawPosition:U,structureId:R,drawId:b});let{participantId:v}=I??{},w=v&&c.find(L=>L.participantId===v);if(I){if(_4({isLuckyDrawAdvancedPosition:n,validActions:_,policyActions:A,isActiveDrawPosition:l,drawId:b,structureId:R,drawPosition:U,possiblyDisablingAction:p,isByePosition:N}),n||x4({validActions:_,policyActions:A,activePositionsCheck:LF,activePositionOverrides:a,activeDrawPositions:S,drawDefinition:E,structureId:R,drawPosition:U,structure:D,isByePosition:N,participantId:v,participant:w,drawId:b}),!n&&!N){let{validSeedCascadeAction:L}=YF({positionAssignments:f,activeDrawPositions:S,drawDefinition:E,isByePosition:N,structure:D,drawPosition:U,structureId:R,drawId:b});L&&_.push(L)}w4({validActions:_,policyActions:A,isByePosition:N,participantId:v,participant:w,drawId:b}),L4({validActions:_,policyActions:A,getValidSwapAction:KF,possiblyDisablingAction:p,tournamentParticipants:c,inactiveDrawPositions:d,activeDrawPositions:S,positionAssignments:f,returnParticipants:h,byeDrawPositions:T,drawDefinition:E,isByePosition:N,drawPosition:U,structureId:R,structure:D,drawId:b})}return F4({validActions:_,policyActions:A,getValidAlternatesAction:VF,possiblyDisablingAction:p,tournamentParticipants:c,positionAssignments:f,activeDrawPositions:S,returnParticipants:h,appliedPolicies:y,drawDefinition:E,drawPosition:U,structureId:R,structure:D,drawId:b,event:C,disablePlacementActions:u}),k4({validActions:_,policyActions:A,getValidLuckyLosersAction:jF,sourceStructuresComplete:s,possiblyDisablingAction:p,isWinRatioFedStructure:m,tournamentParticipants:c,activeDrawPositions:S,positionAssignments:f,drawDefinition:E,drawPosition:U,structureId:R,structure:D,drawId:b,disablePlacementActions:u,isActiveDrawPosition:l}),G4({validActions:_,policyActions:A,getValidModifyAssignedPairAction:wF,participant:w,tournamentParticipants:c,returnParticipants:h,drawPosition:U,drawId:b,event:C}),{isActiveDrawPosition:l,isDrawPosition:!0,hasPositionAssigned:g,isByePosition:N,validActions:_,...P}}function Qp({policyDefinitions:t,appliedPolicies:e,drawType:r}){let n=t?.[hl]?.drawTypeCoercion,o=e?.[hl]?.drawTypeCoercion;return(typeof n=="boolean"?n:void 0)??(r&&n?.[r])??(typeof o=="boolean"?o:void 0)??(r&&o?.[r])??!0}var hA=({drawDefinition:t,random:e})=>{let r=X({drawDefinition:t},[{[Kt]:!0}]);if(r.error)return r;let n=t.structures?.find(s=>s.stage===H&&s.stageSequence===1);if(!n)return M({result:{error:Fg}});let{qualifierPositions:o}=se({structure:n}),i=e??Math.random;return Q(0,o.length).sort(()=>i()-.5)};function TA({structureId:t,drawDefinition:e}){if(!e)return{error:$};if(!_t(t))return{error:O};let r=Ma({drawDefinition:e,structureId:t});if(r.error)return r;let n=r.links.target.flatMap(i=>i.target.feedProfile).filter(Boolean),o=!Yt([Oi,qe,Gm,vi],n).length;return{...P,valid:o}}function yA({drawDefinition:t}){if(!t)return{error:$};let{extension:e}=ot({element:t,name:wi});if(!e?.value)return{error:fe,info:"No draft found"};let r=e.value,n=r.tiers?.reduce((s,a)=>s+(a.participantIds?.length??0),0),o=Object.keys(r.preferences??{}).length,i=r.tiers?.filter(s=>s.resolved).length??0;return{draftState:r,summary:{status:r.status,totalParticipants:n,preferencesSubmitted:o,preferencesOutstanding:n-o,tiersTotal:r.tiers?.length??0,tiersResolved:i,unassignedDrawPositions:r.unassignedDrawPositions,preferencesCount:r.preferencesCount}}}function EA({participantsCount:t,participantCount:e}){if(t=t??e,!t)return{error:O};let r=Si(t);return r?{drawSize:r}:M({result:{error:O},stack:"getEliminationDrawSize",context:{participantsCount:t}})}function Xp(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=lo({tournamentRecord:i,drawDefinition:s,event:a});if(I.error)return M({result:I,stack:c});r=I.policyDefinitions}let p=yt(u);if(u&&!p)return M({result:{error:O},context:{participantsCount:u},stack:c});if(o&&!p)return M({result:{error:nD},stack:c});if(Number.isNaN(Number(n)))if(u)({drawSize:n}=EA({participantsCount:u}));else return M({result:{error:Bc},stack:c});let m=o&&u||n;if(m&&m>n)return{error:qg};let d=r?.[Hn];if(!d)return{error:WU};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,S)=>u&&u>=S.minimumParticipantCount?S.seedsCount:I,0)}):{error:UU}}function Ef({consideredEntries:t,policyDefinitions:e,tournamentRecord:r,appliedPolicies:n,participantMap:o,enforceGender:i,participants:s,event:a}){if((!s||!o)&&r&&({participants:s,participantMap:o}=bt({tournamentRecord:r})),!s)return{error:Wc};if(!Array.isArray(s))return{error:O};if(!a)return{error:le};let c=e?.[We]??n?.[We]??ys[We],u=(i??c?.participants?.enforceGender)!==!1,{eventType:p,gender:m}=a,d=p===ei,l=p===Ze&&vt||d&&lt||St,f=Object.assign({},...(t??a.entries??[]).map(h=>({[h.participantId]:h.entryStatus}))),g=Object.keys(f),S=s.filter(h=>g.includes(h.participantId)).filter(h=>{let T=H4({participant:h,participantType:l,eventType:p,entryStatusMap:f}),y=W4({genderEnforced:u,participantMap:o,eventGender:m,participant:h,isDoubles:d,mismatch:T});return T||!y});if(S.length){let h=S.map(T=>T.participantId);return{error:xU,invalidParticipantIds:h}}return{...P,valid:!0}}function H4({participant:t,participantType:e,eventType:r,entryStatusMap:n}){if(r===hI&&[St,lt].includes(t.participantType))return!1;let o=n[t.participantId],i=r&&[ei,Ze].includes(r)&&t.participantType===St&&($s(o)||o===Cn);return t.participantType!==e&&!i}function W4(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||Co(n)||Un(n)&&yr(a[0])===yr(n)||nn(n)&&(a.length===1&&e.individualParticipantIds?.length===1||a.length===2),u=e?.person?.sex,p=!e?.person||!n||nn(n)||Co(n)||Un(n)&&yr(u)===yr(n);return!s||c&&p}function AA({hasExistingDrawDefinition:t,qualifyingProfiles:e,appliedPolicies:r,qualifyingOnly:n,tieFormat:o,idPrefix:i,isMock:s,uuids:a}){let c="generateQualifyingSTructures",u=[],p=[],m=[],d=(h,T)=>h.stageSequence-T.stageSequence,l=(h,T)=>h.roundTarget-T.roundTarget,f=0,g=0,I,S=1;for(let h of e.sort(l)){let T=h.structureProfiles??[];S=h.roundTarget||S;let y=1,E=0,A,N,U;for(let R of(T??[]).sort(d)){let D=Y4({structureProfile:R,qualifyingProfiles:e,structureProfiles:T,hasExistingDrawDefinition:t,appliedPolicies:r,qualifyingOnly:n,stageSequence:y,roundTarget:S,tieFormat:o,idPrefix:i,isMock:s,uuids:a,stack:c,finalQualifyingStructureId:N,finalQualifyingRoundNumber:A,qualifyingDrawPositionsCount:f,targetRoundQualifiersCount:E,finishingPositions:I,linkType:U,links:m,structures:p});if(D.error)return D;({qualifyingDrawPositionsCount:f,targetRoundQualifiersCount:E,finalQualifyingStructureId:N,finalQualifyingRoundNumber:A,finishingPositions:I,linkType:U,stageSequence:y}=D)}g+=E,u.push({qualifiersCount:E,finalQualifyingRoundNumber:A,finalQualifyingStructureId:N,finishingPositions:I,roundTarget:S,linkType:U}),S+=1}return{qualifiersCount:g,qualifyingDrawPositionsCount:f,qualifyingDetails:u,structures:p,...P,links:m}}function Y4({structureProfile:t,qualifyingProfiles:e,structureProfiles:r,hasExistingDrawDefinition:n,appliedPolicies:o,qualifyingOnly:i,stageSequence:s,roundTarget:a,tieFormat:c,idPrefix:u,isMock:p,uuids:m,stack:d,finalQualifyingStructureId:l,finalQualifyingRoundNumber:f,qualifyingDrawPositionsCount:g,targetRoundQualifiersCount:I,finishingPositions:S,linkType:h,links:T,structures:y}){let E=Jd(t.drawSize||t.participantsCount),{qualifyingRoundNumber:A,structureOptions:N,matchUpFormat:U,structureName:R,structureId:D,drawType:b}=t,C=t.matchUpType,_=t.qualifyingPositions||j4({drawSize:E,qualifyingRoundNumber:A});if(!yt(E))return M({result:{error:Bc},stack:d});let v=e.length>1?`${a}-`:"",w=r.length>1||v?s:"",L=R||(v||w?`${xe(Z)} ${v}${w}`:xe(Z)),F,x,k;if(b===Hr){let G=Ec({structureName:t.structureName||L,structureId:D||m?.pop(),hasExistingDrawDefinition:n,stage:Z,structureOptions:N,appliedPolicies:o,qualifyingOnly:i,stageSequence:s,matchUpType:C,roundTarget:a,tieFormat:c,drawSize:E,idPrefix:u,isMock:p,uuids:m});I=G.groupCount,F=G.maxRoundNumber,x=G.structures[0],S=[1]}else({drawSize:E,matchUps:k,roundLimit:F}=Tr({qualifyingRoundNumber:A,qualifyingPositions:_,matchUpType:C,drawSize:E,idPrefix:u,isMock:p,uuids:m})),x=lr({structureName:t.structureName||L,structureId:D||m?.pop(),qualifyingRoundNumber:F,hasExistingDrawDefinition:n,stage:Z,qualifyingOnly:i,matchUpFormat:U,stageSequence:s,matchUpType:C,roundLimit:F,tieFormat:c,matchUps:k}),a&&ut({extension:{name:Rn,value:a},element:x}),I=k?.filter(G=>G.roundNumber===F)?.length||0;if(s>1){let{link:G}=Xs({sourceStructureId:l,sourceRoundNumber:f,targetStructureId:x.structureId,finishingPositions:h===fn?[1]:void 0,linkType:h});T.push(G),g+=(E||0)-I}else g+=E||0;return h=b===Hr?fn:Er,l=x.structureId,f=F,c&&(k=ht({structure:x})?.matchUps??[],k?.forEach(G=>{let{tieMatchUps:V}=zi({tieFormat:c,matchUp:G,isMock:p});Object.assign(G,{tieMatchUps:V,matchUpType:C})})),y.push(x),s+=1,{qualifyingDrawPositionsCount:g,targetRoundQualifiersCount:I,finalQualifyingStructureId:l,finalQualifyingRoundNumber:f,finishingPositions:S,stageSequence:s,linkType:h}}function j4({drawSize:t,qualifyingRoundNumber:e}){let r=t,n=0;for(;n<e;)r=Math.floor(r/2),n+=1;return r}function PA(t){let{drawTypeCoercion:e,enforceMinimumDrawSize:r}=t,n=st(t.drawSize),o=e&&!Tn(t.drawType)&&(typeof e=="boolean"||e<=2)&&n===2&&zr||t.drawType||zr,i=gR.includes(o);if(n&&i){if(e&&(typeof e=="boolean"&&n<4||n<=e))o=zr;else if(n<4&&r)return{...M({context:{enforceMinimumDrawSize:r,drawSize:n,drawType:o},result:{error:Dm},stack:"getCoercedDrawType"}),drawType:o}}return{drawType:o}}function Af(t){let{enforceMinimumDrawSize:e=!0,overwriteExisting:r,appliedPolicies:n,qualifyingOnly:o,staggeredEntry:i,drawDefinition:s,tieFormat:a,isMock:c,uuids:u}=t??{},p=st(t.drawSize),m=t.drawTypeCoercion??Qp({appliedPolicies:n,drawType:t.drawType}),d="generateDrawStructuresAndLinks",l=PA({drawType:t.drawType,enforceMinimumDrawSize:e,drawTypeCoercion:m,drawSize:p});if(l.error)return l;let f=l.drawType,g=[],I=[],S=t?.matchUpType??Ct,{existingQualifyingDrawPositionsCount:h,mainStructureIsPlaceholder:T,existingQualifyingLinks:y,existingMainStructure:E,existingQualifiersCount:A}=q4({drawDefinition:s,structures:g});if(s?.structures?.filter(({stage:V})=>V===Z)?.length&&!T)return{error:HT};let N=!s?.structures?.filter(({stage:V})=>V===Z)?.length&&t.qualifyingProfiles,U=N?.length&&AA({idPrefix:t.idPrefix,qualifyingProfiles:N,appliedPolicies:n,qualifyingOnly:o,tieFormat:a,isMock:c,uuids:u});if(U?.error)return U;let{qualifyingDrawPositionsCount:R,qualifyingDetails:D,qualifiersCount:b}=U||{qualifyingDrawPositionsCount:h,qualifiersCount:A},C=b||t.qualifiersCount||0;R&&(U?.structures&&g.push(...U.structures),U?.links&&I.push(...U.links)),Object.assign(t,et({drawSize:p,matchUpType:S,tieFormat:a}));let _=$4({drawType:f,drawSize:p,staggeredEntry:i});if(_&&!R)return M({context:{drawSize:p,invalidDrawSize:_},result:{error:Dm},stack:d});let{generators:v,error:w}=pf(t);if(w)return{error:w};let L=v[f];if(!L)return{error:Qu};let F=L?.();if(F.error)return F;let{structures:x,links:k}=F;if(x?.length){let V=K4({mainStructureIsPlaceholder:T,existingMainStructure:E,generatedStructures:x,overwriteExisting:r,generatedLinks:k,structures:g});if(V?.error)return V}g.sort(ki),k?.length&&I.push(...k);let G=F.structures.find(({stage:V,stageSequence:B})=>V===H&&B===1);for(let V of D??[]){let{finalQualifyingRoundNumber:B,finalQualifyingStructureId:z,roundTarget:W,finishingPositions:K,linkType:Y}=V,J=G&&Xs({targetStructureId:G.structureId,sourceStructureId:z,sourceRoundNumber:B,finishingPositions:K,targetEntryRound:W,linkType:Y})?.link;if(J?.error)return J;J&&I.push(J)}return y&&I.push(...y),{...P,qualifyingResult:{qualifyingDrawPositionsCount:R,qualifiersCount:C},structures:g,links:I}}function zF(t,e){if(t.linkType===fn&&e?.structures){let r=t.source.finishingPositions??[];return e.structures.length*r.length}else if(t.linkType===Er&&e?.matchUps?.length){let r=t.source.roundNumber;return e.matchUps.filter(({roundNumber:o})=>o===r).length}}function q4({drawDefinition:t,structures:e}){let r=t?.structures?.filter(({stage:u})=>u===Z);r&&e.push(...r);let n=r?.map(({structureId:u})=>u),o=t?.structures?.find(({stage:u,stageSequence:p})=>u===H&&p===1),i=t?.links?.filter(u=>u.target.structureId===o?.structureId&&n?.includes(u.source.structureId)),s=r?.map(u=>{let p=i?.find(g=>g.target.structureId===u.structureId),m=Pt({structure:u})?.positionAssignments?.length??0;if(!p)return m;let d=p?.source.structureId,l=t.structures?.find(g=>g.structureId===d),f=zF(p,l)||0;return m-f}).filter(Boolean).reduce((u,p)=>u+p,0),a=i?.map(u=>{let p=u.source.structureId,m=r?.find(d=>d.structureId===p);return zF(u,m)}).filter(Boolean).reduce((u,p)=>u+p,0),c=!!(o&&!o?.matchUps?.length);return{existingQualifyingDrawPositionsCount:s,mainStructureIsPlaceholder:c,existingQualifyingLinks:i,existingMainStructure:o,existingQualifiersCount:a}}function $4({drawType:t,drawSize:e,staggeredEntry:r}){return!!(!Tn(t)&&(!e||e<2||[ws,nc].includes(t)&&!en(e)&&e<5||!r&&![rc,ws,nc].includes(t)&&([Wr,Hr].includes(t)&&e<3||![Hr,Wr].includes(t)&&!en(e))))}function K4({mainStructureIsPlaceholder:t,existingMainStructure:e,generatedStructures:r,overwriteExisting:n,generatedLinks:o,structures:i}){let s=r.find(({stage:a,stageSequence:c})=>a===H&&c===1);if(e&&s){if(t)z4(s,e.structureId,o);else if(!n)return{error:HT}}i.push(...r)}function z4(t,e,r){let n=t.structureId;t.structureId=e;for(let o of r??[])o.source.structureId===n&&(o.source.structureId=e),o.target.structureId===n&&(o.target.structureId=e)}function Pf(t){let{modifyOriginal:e=!0,isMock:r}=t??{},n="generateDrawTypeAndModifyDrawDefinition";if(!t.drawDefinition)return M({result:{error:$},stack:n});let o=e?t.drawDefinition:q(t.drawDefinition,!1,!0),{tieFormat:i,matchUpType:s}=t;if(i){let I=or({tieFormat:i});if(I.error)return I}i=nr(i??ze({drawDefinition:o})?.tieFormat),s=s??(o.matchUpType||Ct),t.tieFormat=i,t.matchUpType=s;let a=Mb({drawDefinition:o,stage:H});t.drawSize=t.drawSize??a;let c=new Set(Ie({drawDefinition:o}).drawMatchUps.map(Te)),u=Af(t);if(u.error)return M({result:u,stack:n});let{structures:p,links:m}=u;o.structures=p,o.links=m;let d=t.drawSize??a;Object.assign(t,et({drawSize:d,matchUpType:s,tieFormat:i}));let{matchUps:l,matchUpsMap:f}=te({drawDefinition:o});i&&l?.forEach(I=>{if(!c.has(I.matchUpId)){let{tieMatchUps:S}=zi({tieFormat:i,matchUp:I,isMock:r});Object.assign(I,{tieMatchUps:S,matchUpType:s})}});let{inContextDrawMatchUps:g}=Ts({drawDefinition:o,matchUpsMap:f});return Ft({tournamentId:t.tournamentRecord?.tournamentId,drawDefinition:o}),{inContextDrawMatchUps:g,drawDefinition:o,matchUpsMap:f,...P,structures:p,matchUps:l,links:m}}function Ga(t){let{removePriorValues:e,tournamentRecord:r,participantId:n,scaleItem:o}=t,i,s;if(!QF({scaleItem:o}))return{error:Yc};if(n&&Array.isArray(r.participants)&&(s=r.participants.find(a=>a.participantId===n),s)){if(s.participantType===ur&&o?.eventType!==Ze)return{error:Yc};let a=XF({removePriorValues:e,participant:s,scaleItem:o});if(a.error)return a;i=!a.valueChanged;let{topics:c}=br();c.includes(tr)&&at({topic:tr,payload:{tournamentId:r.tournamentId,participants:[s]}})}return i&&{...P,info:eI,existingValue:o?.scaleValue}||s&&{...P,newValue:o?.scaleValue}||{error:ee}}function YC(t){let{scaleItemsWithParticipantIds:e=[],removePriorValues:r,tournamentRecord:n,auditData:o,context:i}=t,s=dt({tournamentRecord:n},[rt]);if(s.error)return s;if(!n.participants)return{error:Wc};let a=Q4(e);if(a.error)return a;let{modificationsApplied:c,modifiedParticipants:u,error:p}=X4({participants:n.participants,participantScaleItemsMap:a,removePriorValues:r});if(p)return p;let m=c?void 0:Sa,{topics:d}=br();return d.includes(tr)&&c&&at({topic:tr,payload:{tournamentId:n.tournamentId,participants:u}}),J4({context:i,tournamentRecord:n}),o&&d.includes(Gi)&&at({topic:Gi,payload:o}),et({...P,modificationsApplied:c,info:m})}function QF({scaleItem:t}){let e=t&&Object.keys(t),r=["scaleType","eventType","scaleName"];return!!(r.filter(o=>e?.includes(o)).length===r.length)}function XF({removePriorValues:t,participant:e,scaleItem:r}){if(!e)return{error:ga};let n=r&&Object.keys(r),o=["scaleType","eventType","scaleName"];if(!(o.filter(p=>n.includes(p)&&r[p]).length===o.length))return{error:Yc};let s=new Date().toISOString();e.timeItems??=[];let{scaleItem:a}=yo({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){if(r.scaleDate&&typeof r.scaleDate=="string"&&!Me(r.scaleDate))return{error:ae};let{scaleType:p,eventType:m,scaleName:d}=r,l=[ri,p,m,d].join("."),f=et({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{...P,valueChanged:u,newValue:r.scaleValue}}function Q4(t){let e={};for(let r of t){let n=r?.participantId;if(Array.isArray(r?.scaleItems))for(let o of r.scaleItems)if(QF({scaleItem:o}))Array.isArray(e[n])||(e[n]=[]),e[n].push(o);else return{error:Yc}}return e}function X4({participants:t,participantScaleItemsMap:e,removePriorValues:r}){let n=0,o=[];for(let i of t){let{participantId:s}=i??{};if(Array.isArray(e[s]))for(let a of e[s]){if(i.participantType===ur&&a?.eventType!==Ze)return{error:M({context:{participantId:s,scaleItem:a,participantType:i.participantType},info:"Invalid participantType for eventType",result:{error:Yc}}),modificationsApplied:n,modifiedParticipants:o};XF({participant:i,scaleItem:a,removePriorValues:r}),o.push(i),n++}}return{modificationsApplied:n,modifiedParticipants:o,error:void 0}}function J4({context:t,tournamentRecord:e}){if(!t)return;let{eventId:r,drawId:n,...o}=t,i=o.scaleAttributes?.scaleType&&[o.scaleAttributes.scaleType];if(!Object.keys(o).length)return;let s={itemType:LI,itemValue:o};if(i&&(s.itemSubTypes=i),n||r){let{drawDefinition:a,event:c}=_e({tournamentRecord:e,eventId:r,drawId:n});n&&CS({drawDefinition:a,timeItem:s}),r&&Ps({event:c,timeItem:s})}else Du({tournamentRecord:e,timeItem:s})}function VS(t){let{tournamentRecord:e,modifiedScaleValues:r,removePriorValues:n}=t,o=X(t,[{[rt]:!0},{modifiedScaleValues:!0,[Ge]:jr}]);if(o.error)return o;for(let i in r){let s=Ga({scaleItem:r[i],removePriorValues:n,tournamentRecord:e,participantId:i});if(s.error)return s}return{...P}}var Z4=(t=0)=>250/Math.pow(t+5,.4),t6=()=>1;function e6(t=3,e=2){let r=t/e;return Number.isNaN(r)?Nf.kDefault():r}var Nf={nSpread:400,diffThreshold:.125,kCalc:Z4,kMultiplier:e6,kDefault:t6};function NA(t){let{winnerRating:e,loserRating:r}=t,{ratings:n=Ke,winnerCountables:o=1,loserCountables:i=0,ratingType:s="ELO",maxCountables:a,countables:c}=t??{},u=n?.[s];if(!u)return{error:nt};let p=u.range||t.ratingRange;e=e||u.defaultInitialization,r=r||u.defaultInitialization;let m=p[0]>p[1],d=u.decimalsCount||0,l=m?p.slice().reverse():p,f=(L,F)=>Number.parseFloat(F)>=Math.min(...L)&&Number.parseFloat(F)<=Math.max(...L);(!f(p,e)||!f(p,r))&&(f(p,e)||(e=u.defaultInitialization),f(p,r)||(r=u.defaultInitialization));let g=Ep({targetRange:Ke["ELO"].range,sourceRange:l,value:m?p[0]-e:e}),I=Ep({targetRange:Ke["ELO"].range,sourceRange:l,value:m?p[0]-r:r}),S=(L,F)=>1/(1+Math.pow(10,(F-L)/Nf.nSpread)),h=S(g,I),T=S(I,g),y=Nf.kCalc(o),E=Nf.kCalc(i),A=Nf.kMultiplier(a,c),N=g+A*y*(1-h),U=I+A*E*(0-T),R=Ep({sourceRange:Ke["ELO"].range,value:N,targetRange:l}),D=Ep({sourceRange:Ke["ELO"].range,value:U,targetRange:l}),b=m?p[0]-R:R,C=Number.parseFloat(b.toFixed(d)),_=m?p[0]-D:D,v=Number.parseFloat(_.toFixed(d)),w=Math.max(...p)?Math.abs(e-r)/Math.max(...p):0;return(R>D&&w>Nf.diffThreshold||C<0||v<0)&&(C=e,v=r),{newWinnerRating:C,newLoserRating:v}}var JF=t=>t?.reduce((e,r)=>(r.winningSide&&(e[r.winningSide-1]+=1),e),[0,0])||[0,0];function UA(t){let e=X(t,[{[rt]:!0},{matchUpIds:!0,[Ge]:ke,[Yr]:Ms},{ratingType:!1,[$e]:N=>Ke[N]}]);if(e.error)return e;let{updateParticipantRatings:r,removePriorValues:n=!0,tournamentRecord:o,ratingType:i="ELO",convertToELO:s,refreshDynamic:a,considerGames:c,drawDefinition:u,matchUpIds:p,asDynamic:m}=t,d=Ke[i],l=s&&i!=="ELO",f=l?"ELO":i,g=Ke[f],I=d.accessor,S=g.accessor,h={},T=(t.matchUps||a&&rr({drawDefinition:u,tournamentRecord:o,inContext:!0,matchUpFilters:{matchUpStatuses:Mt}}).matchUps||qt({matchUpFilters:{matchUpIds:p,matchUpStatuses:Mt},tournamentRecord:o,inContext:!0}).matchUps)??[],y=`${f}.${Sp}`,E=m?y:f;T.sort(ji);for(let N of T){let{endDate:U,matchUpFormat:R,score:D,sides:b,winningSide:C}=N,_=N.matchUpType,v={eventType:_,scaleName:i,scaleType:vo},w={scaleName:y,eventType:_,scaleType:vo},L=l?{scaleName:`${i}.${Sp}`,eventType:_,scaleType:vo}:void 0,F=Object.assign({},...(b??[]).map(W=>{let{sideNumber:K,participant:Y}=W;return K&&{[K]:[Y?.participantId,...Y?.individualParticipantIds??[]].filter(Boolean).flat()}})),x=Object.assign({},...Object.values(F).flat().map(W=>r6({participantId:W,modifiedScaleValues:h,refreshDynamic:a,dynamicScaleAttributes:w,sourceDynamicScaleAttributes:L,scaleAttributes:v,tournamentRecord:o,sourceAccessor:I,outputScaleName:E,ratingType:i,isEloNative:l,accessor:S,matchUpType:_,endDate:U}))),k=R?oe(R):{},G=k?.bestOf||1,V=k?.setsTo||1,B=c?G&V:G,z=D?.sets&&JF(D.sets)||C===1&&[1,0]||[0,1];o6({sideParticipantIds:F,computeRatingType:f,outputScaleName:E,scaleItemMap:x,winningSide:C,countables:z,maxCountables:B,accessor:S}),Object.assign(h,x),r&&VS({tournamentRecord:o,modifiedScaleValues:h,removePriorValues:n})}let A=T.map(({matchUpId:N})=>N);return{...P,modifiedScaleValues:h,outputScaleName:E,processedMatchUpIds:A,...l&&{sourceRatingType:i}}}function r6({participantId:t,modifiedScaleValues:e,refreshDynamic:r,dynamicScaleAttributes:n,sourceDynamicScaleAttributes:o,scaleAttributes:i,tournamentRecord:s,sourceAccessor:a,outputScaleName:c,ratingType:u,isEloNative:p,accessor:m,matchUpType:d,endDate:l}){let f=e[t],g=!r||f,I=g?Ki({scaleAttributes:n,tournamentRecord:s,participantId:t}).scaleItem:void 0;!I&&o&&g&&(I=n6({sourceDynamicScaleAttributes:o,tournamentRecord:s,participantId:t,sourceAccessor:a,outputScaleName:c,ratingType:u}));let S=Ki({tournamentRecord:s,scaleAttributes:i,participantId:t}).scaleItem,h=I??S;if(!I&&S&&p){let y=S.scaleValue,E=a&&typeof y=="object"?y[a]:y;E!=null&&(h={...S,scaleName:c,scaleValue:Ap({sourceRatingType:u,sourceRating:E})})}let T=m?{[m]:void 0}:void 0;return t&&{[t]:h??{scaleName:c,eventType:d,scaleDate:l,scaleType:vo,scaleValue:T}}}function n6({sourceDynamicScaleAttributes:t,tournamentRecord:e,participantId:r,sourceAccessor:n,outputScaleName:o,ratingType:i}){let s=Ki({scaleAttributes:t,tournamentRecord:e,participantId:r}).scaleItem;if(!s)return;let a=s.scaleValue,c=n&&typeof a=="object"?a[n]:a;if(c!=null)return{...s,scaleName:o,scaleValue:Ap({sourceRatingType:i,sourceRating:c})}}function o6({sideParticipantIds:t,computeRatingType:e,outputScaleName:r,scaleItemMap:n,winningSide:o,countables:i,maxCountables:s,accessor:a}){let c=o?t[o]:[],u=o?t[3-o]:[];for(let p of c){let m=n[p]?.scaleValue,d=typeof m=="object"?m[a]:m;for(let l of u){let f=n[l]?.scaleValue,g=typeof f=="object"?f[a]:f,I=o?i[o]:[0,0],S=o?i[3-o]:[0,0],{newWinnerRating:h,newLoserRating:T}=NA({ratingType:e,winnerCountables:I,loserCountables:S,maxCountables:s,winnerRating:d,loserRating:g}),y=a?{...m,[a]:h}:h,E=a?{...f,[a]:T}:T;n[p].scaleValue=y,n[l].scaleValue=E,n[p].scaleName=r,n[l].scaleName=r}}}function Nc(t){let{matchUpIds:e=[],drawDefinition:r,roundNumber:n,newRound:o,isMock:i,event:s}=t;if(typeof r!="object")return{error:$};let{participantIdPairings:a,matchUpsCount:c}=t,u=Sf(t);if(u.error)return M({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 M({result:{error:O,info:"matchUpsCount error",context:{roundMatchUpsCount:d}}});if(a&&!Array.isArray(a)||c&&!yt(c)||e&&!Array.isArray(e)||!a&&!c)return{error:O,info:"matchUpsCount or pairings error"};if(c&&t.restrictMatchUpsCount!==!1&&c>32)return{error:O,info:"matchUpsCount must be less than 33"};if(n&&!t.ignoreLastRoundNumber&&n-1>(p||0))return{error:O,info:"roundNumber error"};let l=n??(o&&(p??0)+1||p||1);a=a??Q(0,c).map(()=>({participantIds:[void 0,void 0]}));let f=I=>{if(!t.idPrefix)return;let S=r.drawId,h=t.idPrefix??"ah";return`${S}-${h}-${l}-${I}`},g=a?.map((I,S)=>{let h=I?.participantIds??[void 0,void 0];h.push(void 0,void 0);let y=h.slice(0,2).map((A,N)=>et({sideNumber:N+1,participantId:A})),E=e[S]??f(S)??it();return{roundNumber:l,matchUpStatus:zt,matchUpId:E,sides:y}});if(g?.length){let I=ze({drawDefinition:r,event:s})?.tieFormat;I&&g.forEach(S=>{let{tieMatchUps:h}=zi({tieFormat:I,matchUp:S,isMock:i});Object.assign(S,{tieMatchUps:h,matchUpType:Ot})})}return{roundNumber:l,matchUpsCount:g?.length??0,matchUps:g,...P}}function tk({maxIterations:t=4e3,valueSortedPairings:e,pairingValues:r,valueObjects:n,deltaObjects:o,random:i}){let s=i??Math.random,a=Object.assign({},...e.map(y=>({[y.pairing]:y.value}))),c=Object.keys(r),u=[],p=ZF({actorsCount:c.length,valueSortedPairings:e,pairingValueMap:a,deltaObjects:o,valueObjects:n,random:i}),m=[jC(p)];u.push(p);let d=p.value,l=p,f=1,g=0,I=c.length,S;do I-=1,S=c.length*r[c[0]].length;while(S>t&&I>5);let h=[];c.forEach(y=>{r[y].slice(0,I).forEach(A=>{g+=1;let N=Zs(y,A.opponent);if(!h.includes(N)){let U=ZF({stipulated:[[y,A.opponent]],actorsCount:c.length,valueSortedPairings:e,pairingValueMap:a,deltaObjects:o,valueObjects:n,random:i});if(!m.includes(jC(U))){m.push(jC(U)),u.push(U);let{maxDelta:R,value:D}=U;R<l.maxDelta&&(l=U),(D<d||D===d&&Math.round(s()))&&(d=D),h.push(N),f+=1}}}),u=u.filter(A=>Math.abs(A.value-d)<5)}),u.sort((y,E)=>y.maxDiff-E.maxDiff);let T=Sr(u,i);return{candidatesCount:f,deltaCandidate:l,maxIterations:t,iterations:g,candidate:T}}function jC(t){return t.participantIdPairings.map(({participantIds:e})=>e.sort().join("|")).sort().join("/")}function ZF({valueSortedPairings:t,stipulated:e=[],pairingValueMap:r,deltaObjects:n,valueObjects:o,actorsCount:i,random:s}){let a=s??Math.random,c=e.flat(),u=[],p=0;e.filter(Boolean).forEach(f=>{let[g,I]=f,S=Zs(g,I),h=r[S];u.push({participantIds:f,value:h}),p+=r[S]}),he(t,i).flatMap(f=>ar(f,s).map(g=>({...g,value:g.value+a()*Math.round(a())}))).forEach(f=>{let g=f.pairing.split("|");if(!g.reduce((S,h)=>c.includes(h)||S,!1)){c.push(...g);let S=f.value;p+=S,u.push({participantIds:g,value:S})}}),u.sort((f,g)=>f.value-g.value);let d=u.reduce((f,g)=>{let[I,S]=g.participantIds,h=Zs(I,S),T=n[h];return Math.max(T,f)},0),l=u.reduce((f,g)=>{let[I,S]=g.participantIds,h=Zs(I,S),T=o[h];return Math.max(T,f)},0);return{value:p,participantIdPairings:u,maxDelta:d,maxDiff:l}}function Zs(t,e){return[t,e].sort(kp).join("|")}function qC({participantIds:t}){let e={},r=[];t.forEach(o=>{e[o]=t.filter(i=>i!==o),e[o].forEach(i=>{let s=Zs(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 DA({matchUps:t}){let e=[];for(let r of t){let n=r.sides.map(ft);if(n.length===2){let[o,i]=n,s=Zs(o,i);e.includes(s)||e.push(s)}}return{encounters:e}}function ek({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=Zs(o,i);return{opponent:i,value:e[s]}}return{pairingValues:r}}var i6=0;function rk({tournamentParticipants:t,adHocRatings:e,eventType:r,scaleName:n,pairing:o}){let i=Ke[n]?.defaultInitialization??i6;return o.split("|").map(s=>{if(r===wt){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 nk(t){let{tournamentParticipants:e,adHocRatings:r={},possiblePairings:n,uniquePairings:o,maxIterations:i,minimizeDelta:s,deltaObjects:a,valueObjects:c,eventType:u,scaleName:p,salted:m}=t;o.forEach(T=>{let y=rk({tournamentParticipants:e,adHocRatings:r,scaleName:p,eventType:u,pairing:T}),E=typeof m=="number"&&m||.5,A=t.random??Math.random,N=m&&(Math.round(A())?E:E*-1)||0,U=Math.abs(y[0]-y[1])+N,R=Math.abs(y[0]-y[1]);a[T]=R,c[T]||(c[T]=0),c[T]+=U?Math.pow(U,2):0});let d=o.map(T=>({pairing:T,value:c[T]})).sort((T,y)=>T.value-y.value),{pairingValues:l}=ek({possiblePairings:n,valueObjects:c}),{candidate:f,candidatesCount:g,deltaCandidate:I,iterations:S}=tk({random:t.random,valueSortedPairings:d,maxIterations:i,pairingValues:l,deltaObjects:a,valueObjects:c}),{participantIdPairings:h}=s?I:f;return{participantIdPairings:h,candidatesCount:g,deltaCandidate:I,iterations:S,candidate:f}}var s6=100,a6=100,c6=4e3;function Uf(t){let{encounterValue:e=s6,sameTeamValue:r=a6,maxIterations:n=c6,updateParticipantRatings:o,generateMatchUps:i=!0,ignoreLastRoundNumber:s,iterationMatchUps:a,tournamentRecord:c,dynamicRatings:u,convertToELO:p,refreshDynamic:m,participantIds:d,drawDefinition:l,roundNumber:f,structureId:g,matchUpIds:I,eventType:S,scaleName:h,idPrefix:T,isMock:y,salted:E,event:A}=t;if(!l)return{error:$};if(!t.structure&&!g)return{error:Nt};let N=t.structure||tt({drawDefinition:l,structureId:g}).structure;if(!Tt(N))return{error:bi};if(!d?.length)return{error:Ro};let U=[...a??[],...N?.matchUps??[]],{encounters:R}=DA({matchUps:U}),D=c?.participants??[],b={},C,{competitionPolicy:_}=To({tournamentRecord:c,drawDefinition:l,event:A}),{competitionState:v}=_?Fo({drawDefinition:l}):{competitionState:void 0};if(_&&v&&_.pairingPolicy.ratingSource==="DYNAMIC_FORM")for(let[Dt,pe]of Object.entries(v.participantStates))b[Dt]=pe.dynamicFormRating;else if(u){let Dt=pt(N?.matchUps?N.matchUps.map(({roundNumber:ye})=>ye):[]),pe=Math.max(...Dt,0);if(pe){let ye=N?.matchUps?.filter(({roundNumber:pr})=>pr===pe).map(({matchUpId:pr})=>pr),Jt=UA({ratingType:h??A?.category?.ratingType,updateParticipantRatings:o,tournamentRecord:c,asDynamic:!0,convertToELO:p,refreshDynamic:m,drawDefinition:l,matchUpIds:ye});if(Jt.error)return Jt;Jt.modifiedScaleValues&&(b=Jt.modifiedScaleValues),Jt.sourceRatingType&&(C=Jt.sourceRatingType)}}let{valueObjects:L}=u6({tournamentParticipants:D,encounterValue:e,sameTeamValue:r,encounters:R}),{uniquePairings:F,possiblePairings:x,deltaObjects:k}=qC({participantIds:d}),G=Object.values(b).length?b:t.adHocRatings,V={tournamentParticipants:D,possiblePairings:x,participantIds:d,uniquePairings:F,drawDefinition:l,maxIterations:n,adHocRatings:G,deltaObjects:k,valueObjects:L,random:t.random,eventType:S,scaleName:h,structure:N,salted:E},{candidatesCount:B,participantIdPairings:z,deltaCandidate:W,iterations:K,candidate:Y}=nk(V);if(!B)return{error:Cm};let J,ct;if(i){let Dt=Nc({structureId:N?.structureId,ignoreLastRoundNumber:s,participantIdPairings:z,newRound:!0,drawDefinition:l,roundNumber:f,matchUpIds:I,idPrefix:T,isMock:y,event:A});if(Dt.error)return Dt;J=Dt.roundNumber,ct=Dt.matchUps}let{maxDelta:Et,maxDiff:Wt}=Y;return{roundNumber:J,participantIdPairings:z,modifiedScaleValues:b,sourceRatingType:C,candidatesCount:B,deltaCandidate:W,...P,iterations:K,matchUps:ct,maxDelta:Et,maxDiff:Wt}}function u6({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===vt);if(i)for(let s of i){let a=s.individualParticipantIds??[],{uniquePairings:c}=qC({participantIds:a});for(let u of c)o[u]||(o[u]=0),o[u]+=n}return{valueObjects:o}}function RA(t){let{drawType:e=zr,applyPositioning:r=!0,tournamentRecord:n,staggeredEntry:o,automated:i,placeByes:s,isMock:a,event:c}=t,u=t?.drawDefinition;if(!u)return{error:$};let p=Fe,m=Wi({entryStatuses:Qm,stageSequence:1,drawDefinition:u,stage:p}),l=[Hr,dp,Wr,ws].includes(e)?m.length:Si(m.length);if(!o&&e===rc&&m.length<2||e===Hr&&m.length<3)return{error:Dm};let{tieFormat:f,matchUpType:g}=t;if(f){let v=or({tieFormat:f});if(v.error)return v}f=nr(f??ze({drawDefinition:u})?.tieFormat),g=g??u.matchUpType;let{structures:I}=In({stageSequence:1,drawDefinition:u,stage:p});if(I.length>1)return{error:wU};if(I?.[0]?.matchUps?.length)return{error:oI};let h=I?.[0]?.structureId;Object.assign(t,et({structureName:t.structureName??xe(Fe),structureId:h,matchUpType:g,tieFormat:f,drawSize:l,stage:p}));let T=pf(t);if(T.error)return T;let y=T.generators[e];if(!y)return{error:Qu};let E=y?.();if(E.error)return E;let{structures:A,links:N}=E,U=A.flatMap(v=>ht({structure:v}).matchUps);f&&U.forEach(v=>{let{tieMatchUps:w}=zi({matchUp:v,tieFormat:f,isMock:a});Object.assign(v,{tieMatchUps:w,matchUpType:g})});let R=q(u,!1,!0);R.links??=[],N.length&&R.links.push(...N);let D=new Set(A.map(({structureId:v})=>v));R.structures??=[];let b=new Set(R.structures.map(({structureId:v})=>v));R.structures=R.structures.map(v=>D.has(v.structureId)?A.find(({structureId:w})=>w===v.structureId):v);let C=A.filter(({structureId:v})=>!b.has(v));if(C.length&&R.structures.push(...C),i&&r){let v=A[0],w=(v?.structures?.length||0)>1;Ru({structureId:h||v?.structureId,seedingProfile:t.seedingProfile,drawDefinition:R,random:t.random,multipleStructures:w,applyPositioning:r,tournamentRecord:n,placeByes:s,event:c})}let _=R.structures.filter(({structureId:v})=>D.has(v));return{links:N,structures:_,...P}}var th={};Gt(th,{ScoringEngine:()=>zS,addPoint:()=>Us,analyzeScore:()=>XS,analyzeSequence:()=>DM,analyzeSet:()=>Zp,calculateMatchStatistics:()=>Df,calculatePointsTo:()=>Id,checkScoreHasValue:()=>ue,checkSetIsComplete:()=>Td,createMatchUp:()=>Ji,deduceMatchUpFormat:()=>Nd,enrichPointHistory:()=>zC,exportMatchUpJSON:()=>Gk,generate:()=>eM,generateScoreString:()=>Ni,generateTieMatchUpScore:()=>bu,getEpisodes:()=>HS,getQuickStats:()=>QC,getScore:()=>Zi,getScoreboard:()=>BS,getSetComplement:()=>ZS,getSetScoreString:()=>vk,getTiebreakComplement:()=>Ad,getWinner:()=>YS,groupByMatch:()=>jA,helpers:()=>TM,inferServeSide:()=>jS,isComplete:()=>WS,isValidMatchUpFormat:()=>vr,keyValueScore:()=>hM,mcpValidator:()=>kk,mutate:()=>rM,parseCSV:()=>YA,parseMCPPoint:()=>WA,parseMatchUpFormat:()=>oe,parseScoreString:()=>Pd,pbpValidator:()=>xk,pointParser:()=>RM,query:()=>AM,resolvePointValue:()=>qS,reverseScore:()=>$C,shotParser:()=>HA,shotSplitter:()=>UM,stringifyMatchUpFormat:()=>ip,toStatObjects:()=>Rf,validateMCPMatch:()=>bM,validateMatchUp:()=>PM,validateMatchUpScore:()=>yM,validateScore:()=>JS,validateSet:()=>Ok,validateSetScore:()=>VA,validateTieFormat:()=>or});var eM={};Gt(eM,{ScoringEngine:()=>zS,generateScoreString:()=>Ni,generateTieMatchUpScore:()=>bu,reverseScore:()=>$C});function Ni(t){let{winnerFirst:e=!0,setTBlast:r=!0,addOutcomeString:n,reversed:o=!1,matchUpStatus:i,matchUpFormat:s,autoComplete:a,winningSide:c,sets:u}=t;if(!u)return{error:nt,info:"missing sets"};let p=s&&oe(s),{bestOf:m,finalSetFormat:d,setFormat:l}=p??{},g=o||!(!e||!c||c===1),I=n?p6({matchUpStatus:i}):"",S=u?.sort(m6).map(h).filter(Boolean).join(" ")||"";if(!I)return S;if(c===2)return`${I} ${S}`;return`${S} ${I}`;function h(T){let E=m&&T.setNumber===m&&d?d:l,A=Y=>Le(Y?.side1Score)||Le(Y?.side2Score),U=(Y=>Le(Y?.side1TiebreakScore)||Le(Y?.side2TiebreakScore))(T),R=E?.tiebreakSet||!A(T)&&U,{side1Score:D,side2Score:b,side1TiebreakScore:C,side2TiebreakScore:_}=T,v=C||(Le(C)||U&&a?0:""),w=_||(Le(_)||U&&a?0:"");if(R){let Y=A(T)&&!U,J=Y?D:v,ct=Y?b:w;return`[${(g?[ct,J]:[J,ct]).join("-")}]`}let L=U?Math.min(v,w):"",F=L===v?1:2,x=Le(L)?`(${L})`:"",k=D||(Le(D)||a?0:""),G=b||(Le(b)||a?0:""),V=Y=>!r&&F===Y?x:"",B=`${k}${V(1)}`,z=`${G}${V(2)}`,W=r&&U?`(${L})`:"",K=g?`${[z,B].join("-")}${W}`:`${[B,z].join("-")}${W}`;return["-"," "].includes(K)&&(K=""),K}}function p6({matchUpStatus:t}){let e={[Ue]:"RET",[Lt]:"WO",[ge]:"DF/DF",[Qt]:"WO/WO",[Fi]:"SUS",[xr]:"ABN",[xt]:"DEF",[Pp]:"DR"};return t&&e[t]||""}function m6(t,e){return t.setNumber-e.setNumber}function $C(t){if(!t?.score)return{error:nt};let{sets:e}=t.score,r=e.map(s=>{let{side1TiebreakScore:a,side2TiebreakScore:c,side1PointScore:u,side2PointScore:p,winningSide:m,side1Score:d,side2Score:l,setNumber:f}=s;return et({winningSide:m?3-m:void 0,side1TiebreakScore:c,side2TiebreakScore:a,side1PointScore:p,side2PointScore:u,side1Score:l,side2Score:d,setNumber:f})}),n=t?.setTBlast,o=Ni({setTBlast:n,sets:r}),i=Ni({sets:r,reversed:!0,setTBlast:n});return{reversedScore:{sets:r,scoreStringSide1:o,scoreStringSide2:i},...P}}var d6={A:"Ace",D:"Double Fault",S:"Serve Winner",R:"Return Winner",W:"Winner",E:"Unforced Error",F:"Forced Error"},l6=new Set(["A","S"]),f6=new Set(["D","R","E","F"]);function ok(t,e){let r={...t};return r.server=e.server,r.index=e.index,r.set=e.set,r.game=e.game,r.code&&!r.winner&&(r.winner=g6(r.code,e.server)),r.code&&!r.result&&(r.result=d6[r.code]),r.first_serve?r.serve=2:r.serve||(r.serve=1),r}function g6(t,e){return l6.has(t)?e:f6.has(t)?1-e:e}function ik(t){let e=[],r=[],n=t.result?.toLowerCase()||"";return n.includes("ace")&&e.push("aces"),(n.includes("winner")||n.includes("ace"))&&e.push("winners"),n.includes("double fault")&&r.push("doubleFaults"),n.includes("unforced error")&&r.push("unforcedErrors"),n.includes("forced error")&&r.push("forcedErrors"),t.winner===t.server?(e.push("servesWon"),t.serve===1?e.push("serves1stWon"):t.serve===2&&e.push("serves2ndWon")):(e.push("returns"),t.serve===1?e.push("received1stWon"):t.serve===2&&e.push("received2ndWon")),e.push("pointsWon"),{winner:e,loser:r}}function KC(t,e){let r={players:{},teams:{}};for(let i=0;i<2;i++)r.players[i]={},r.teams[i]={};let n=t;e?.setFilter!==void 0&&(n=t.filter(i=>i.set===e.setFilter));let o;return n.forEach((i,s)=>{if(i.winner===void 0){je()&&console.warn("Point missing winner:",i);return}let{winner:a,loser:c}=ik(i),u=i.winner,p=1-u;sk(r,u,a,i),sk(r,p,c,i),I6(r,i),S6(r,i,u,s),h6(r,i,o),T6(r,i,u),o=i}),r}function Uc(t,e,r,n){t[e][r]||(t[e][r]=[]),t[e][r].push(n)}function sk(t,e,r,n){r.forEach(o=>{Uc(t.teams,e,o,n),Uc(t.players,e,o,n)})}function I6(t,e){if(e.server===void 0)return;let r=e.server;Uc(t.teams,r,"pointsServed",e),e.serve===1?Uc(t.teams,r,"serves1stIn",e):e.serve===2&&Uc(t.teams,r,"serves2ndIn",e)}function S6(t,e,r,n){e.hand&&Uc(t.teams,r,e.hand,{point:e,index:n})}function h6(t,e,r){if(!y6(e,r)||r?.winner===void 0)return;let n=r.winner;Uc(t.teams,n,"gamesWon",r),Uc(t.players,n,"gamesWon",r)}function T6(t,e,r){if(!e.breakpoint)return;let n=e.server;Uc(t.teams,n,"breakpointsFaced",e),r===n&&Uc(t.teams,n,"breakpointsSaved",e)}function y6(t,e){return e&&t.game!==void 0&&e.game!==void 0?t.game!==e.game:!1}function ak(t){let e={totalPoints:0,byTeam:[0,0],byCategory:{}};for(let n=0;n<2;n++)if(t.teams[n].pointsWon){let o=t.teams[n].pointsWon.length;e.byTeam[n]=o,e.totalPoints+=o}let r=new Set;for(let n=0;n<2;n++)Object.keys(t.teams[n]).forEach(o=>r.add(o));return r.forEach(n=>{e.byCategory[n]=0;for(let o=0;o<2;o++)t.teams[o][n]&&(e.byCategory[n]+=t.teams[o][n].length)}),e}function uk(t){if(!t?.teams)return[];let e=[];return Object.values({Aces:{category:"Aces",numerators:["aces"],calc:"number"},"Double Faults":{category:"Double Faults",numerators:["doubleFaults"],calc:"number"},Winners:{category:"Winners",numerators:["winners"],calc:"number"},"Unforced Errors":{category:"Unforced Errors",numerators:["unforcedErrors"],calc:"number"},"Forced Errors":{category:"Forced Errors",numerators:["forcedErrors"],calc:"number"},"Total Points Won":{category:"Total Points Won",numerators:["pointsWon"],calc:"number"},"Max Pts/Row":{category:"Max Pts/Row",numerators:["pointsWon"],calc:"maxConsecutive",attribute:"index"},"Max Games/Row":{category:"Max Games/Row",numerators:["gamesWon"],calc:"maxConsecutive",attribute:"game"},"First Serve %":{category:"First Serve %",numerators:["serves1stIn"],denominators:["pointsServed"],calc:"percentage"},"Points Won 1st":{category:"Points Won 1st",numerators:["serves1stWon"],denominators:["serves1stIn"],calc:"percentage"},"Points Won 2nd":{category:"Points Won 2nd",numerators:["serves2ndWon"],denominators:["serves2ndIn"],calc:"percentage"},"Points Won Receiving":{category:"Points Won Receiving",numerators:["received1stWon","received2ndWon"],denominators:["-pointsServed"],calc:"percentage"},"Breakpoints Saved":{category:"Breakpoints Saved",numerators:["breakpointsSaved"],denominators:["breakpointsFaced"],calc:"percentage"},"Breakpoints Converted":{category:"Breakpoints Converted",numerators:["-breakpointsSaved"],denominators:["-breakpointsFaced"],calc:"difference"},"Games Won":{category:"Games Won",numerators:["gamesWon"],calc:"number"},"Service Points Won":{category:"Service Points Won",numerators:["servesWon"],denominators:["pointsServed"],calc:"percentage"},"Aggressive Margin":{category:"Aggressive Margin",numerators:["*doubleFaults","*unforcedErrors"],denominators:["*aces","*winners","-*forcedErrors"],calc:"aggressiveMargin"}}).forEach(n=>{let o=[ck(n,t.teams,0),ck(n,t.teams,1)];(o[0].value!==0||o[1].value!==0)&&e.push({category:n.category,teams:o})}),e}function ck(t,e,r){switch(t.calc){case"number":return E6(t,e,r);case"percentage":return A6(t,e,r);case"maxConsecutive":return P6(t,e,r);case"difference":return N6(t,e,r);case"aggressiveMargin":return U6(t,e,r)}}function E6(t,e,r){let n=gd(t.numerators,e,r);return{value:n,display:String(n),numerators:t.numerators}}function A6(t,e,r){let n=gd(t.numerators,e,r),o=gd(t.denominators??[],e,r);if(!o)return{value:0,display:"0",numerators:t.numerators};let i=Math.round(n/o*100);return{value:i,display:`${i}% (${n}/${o})`,numerators:t.numerators}}function P6(t,e,r){let n=t.numerators[0],o=t.attribute||"index";if(!e[r][n])return{value:0,display:"0"};let i=e[r][n],s=0,a=i.length?1:0,c;return i.forEach(u=>{let p=u[o];c!==void 0&&p===c+1?a++:(a>s&&(s=a),a=1),c=p}),a>s&&(s=a),{value:s,display:String(s)}}function N6(t,e,r){let n=gd(t.numerators,e,r),o=gd(t.denominators??[],e,r);if(!o)return{value:0,display:"0",numerators:t.numerators};let i=Math.abs(o-n),s=Math.round(i/o*100);return{value:s,display:`${s}% (${i}/${o})`,numerators:t.numerators}}function U6(t,e,r){let n=gd(t.denominators??[],e,r),o=gd(t.numerators,e,r),i=n-o;return{value:i,display:String(i)}}function gd(t,e,r){return t?t.reduce((n,o)=>{let i=o.startsWith("-"),s=o.includes("*"),a=o.replace("-","").replace("*",""),c=i?1-r:r,u=e[c]?.[a];return u?n+u.length:n},0):0}function Df(t,e,r){let n=KC(e??[],r),o=uk(n),i=ak(n);return{counters:n,calculated:o,summary:i}}function zC(t){if(!t)return[];let e=[],r=0,n=0,o=0;return t.forEach((i,s)=>{let a=ok(i,{server:r,index:s,set:n,game:o});e.push(a)}),e}function QC(t,e){let r=KC(t??[],e);return{aces:[r.teams[0].aces?.length||0,r.teams[1].aces?.length||0],doubleFaults:[r.teams[0].doubleFaults?.length||0,r.teams[1].doubleFaults?.length||0],winners:[r.teams[0].winners?.length||0,r.teams[1].winners?.length||0],unforcedErrors:[r.teams[0].unforcedErrors?.length||0,r.teams[1].unforcedErrors?.length||0],totalPoints:[r.teams[0].pointsWon?.length||0,r.teams[1].pointsWon?.length||0]}}function Ne(t,e,r){return t.teams[e]?.[r]?.length??0}function Xi(t,e){return!e||!t?0:Number.parseFloat((t/e*100).toFixed(2))}function bA(t,e,r){return t.find(o=>o.category===e)?.teams[r]?.value??0}function Rf(t){if(!t?.counters?.teams)return[];let{counters:e,calculated:r}=t,n=[];n.push({name:"Aces",numerator:[Ne(e,0,"aces"),Ne(e,1,"aces")],default:"numerator"},{name:"Double Faults",numerator:[Ne(e,0,"doubleFaults"),Ne(e,1,"doubleFaults")],default:"numerator"});let o=[Ne(e,0,"serves1stWon"),Ne(e,1,"serves1stWon")],i=[Ne(e,0,"servesWon"),Ne(e,1,"servesWon")];if(o[0]+o[1]>0&&(i[0]!==o[0]||i[1]!==o[1])){let E=[Ne(e,0,"pointsServed"),Ne(e,1,"pointsServed")],A=[Ne(e,0,"serves1stIn"),Ne(e,1,"serves1stIn")],N=[Ne(e,0,"serves2ndWon"),Ne(e,1,"serves2ndWon")],U=[Ne(e,0,"serves2ndIn"),Ne(e,1,"serves2ndIn")];n.push({name:"1st Serve In",numerator:A,denominator:E,pct:[Xi(A[0],E[0]),Xi(A[1],E[1])]},{name:"1st Serve Points Won",numerator:o,denominator:A,pct:[Xi(o[0],A[0]),Xi(o[1],A[1])]},{name:"2nd Serve Points Won",numerator:N,denominator:U,pct:[Xi(N[0],U[0]),Xi(N[1],U[1])]})}n.push({name:"Total Points Won",numerator:[Ne(e,0,"pointsWon"),Ne(e,1,"pointsWon")],default:"numerator"});let a=Ne(e,0,"received1stWon")+Ne(e,0,"received2ndWon"),c=Ne(e,1,"received1stWon")+Ne(e,1,"received2ndWon"),u=Ne(e,1,"pointsServed"),p=Ne(e,0,"pointsServed");n.push({name:"Receiving Points Won",numerator:[a,c],denominator:[u,p],pct:[Xi(a,u),Xi(c,p)]});let m=Ne(e,1,"breakpointsFaced")-Ne(e,1,"breakpointsSaved"),d=Ne(e,0,"breakpointsFaced")-Ne(e,0,"breakpointsSaved"),l=Ne(e,1,"breakpointsFaced"),f=Ne(e,0,"breakpointsFaced");n.push({name:"Break Points Won",numerator:[m,d],denominator:[l,f],pct:[Xi(m,l),Xi(d,f)]});let g=Ne(e,0,"breakpointsSaved"),I=Ne(e,1,"breakpointsSaved"),S=Ne(e,0,"breakpointsFaced"),h=Ne(e,1,"breakpointsFaced");n.push({name:"Break Points Saved",numerator:[g,I],denominator:[S,h],pct:[Xi(g,S),Xi(I,h)]},{name:"Winners",numerator:[Ne(e,0,"winners"),Ne(e,1,"winners")],default:"numerator"},{name:"Unforced Errors",numerator:[Ne(e,0,"unforcedErrors"),Ne(e,1,"unforcedErrors")],default:"numerator"},{name:"Forced Errors",numerator:[Ne(e,0,"forcedErrors"),Ne(e,1,"forcedErrors")],default:"numerator"});let T=i,y=[Ne(e,0,"pointsServed"),Ne(e,1,"pointsServed")];return n.push({name:"Service Points Won",numerator:T,denominator:y,pct:[Xi(T[0],y[0]),Xi(T[1],y[1])]},{name:"Games Won",numerator:[Ne(e,0,"gamesWon"),Ne(e,1,"gamesWon")]},{name:"Most Consecutive Points Won",numerator:[bA(r,"Max Pts/Row",0),bA(r,"Max Pts/Row",1)]},{name:"Most Consecutive Games Won",numerator:[bA(r,"Max Games/Row",0),bA(r,"Max Games/Row",1)]}),n}function CA(t){return t?!!t.aggregate:!1}function Mu(t,e){let r=t.bestOf||t.exactly||3,n=Math.ceil(r/2);if(e[0]===n-1&&e[1]===n-1&&t.finalSetFormat){let s=t.finalSetFormat;return s.tiebreakSet?"matchTiebreak":s.timed?"timed":"standard"}let i=t.setFormat;return i?i.tiebreakSet?"tiebreakOnly":i.timed?"timed":"standard":"standard"}function Ji(t){let{matchUpId:e=it(),matchUpFormat:r,participants:n=[],isDoubles:o=!1,matchUpType:i}=t,s=i||(o?"DOUBLES":"SINGLES"),a=n.map((p,m)=>({sideNumber:m+1,participantId:p.participantId,participant:p}));return a.length===0&&a.push({sideNumber:1},{sideNumber:2}),{matchUpId:e,matchUpFormat:r,matchUpStatus:"TO_BE_PLAYED",matchUpType:s,sides:a,score:{sets:[]},createdAt:new Date().toISOString()}}function BS(t,e){let r=t.score.sets;if(r.length===0)return"0-0";let n=e?.perspective,o=r.map(s=>{let a=s.side1Score||0,c=s.side2Score||0;if(n===1&&([a,c]=[c,a]),s.side1TiebreakScore!==void 0||s.side2TiebreakScore!==void 0){let u=s.side1TiebreakScore||0,p=s.side2TiebreakScore||0;return n===1&&([u,p]=[p,u]),a>c?`${a}-${c}(${p})`:`${a}(${u})-${c}`}return`${a}-${c}`}),i=r.at(-1);if(t.matchUpStatus==="IN_PROGRESS"&&i&&!i.winningSide){let s=i.side1GameScores??[],a=s.length-1;if(a>=0&&s.length>0){let c=s[a]||0,u=(i.side2GameScores??[])[a]||0;if(c===0&&u===0)return o.join(", ");n===1&&([c,u]=[u,c]);let p=i.side1Score||0,m=i.side2Score||0,d=t.matchUpFormat?oe(t.matchUpFormat):void 0,l=d?.setFormat?.setTo||6,f=(typeof d?.setFormat?.tiebreakAt=="number"?d.setFormat.tiebreakAt:void 0)??l,g=p===f&&m===f,I=d?.gameFormat?.type==="CONSECUTIVE",S=o.at(-1),h=`${o.slice(0,-1).join(", ")}${o.length>1?", ":""}${S}`;if(g||I)return`${h} (${c}-${u})`;{let T=D6(c,u);return`${h} (${T})`}}}return o.join(", ")}function D6(t,e){let r=["0","15","30","40"];if(t<=3&&e<=3)return`${r[t]}-${r[e]}`;if(t>=3&&e>=3){let n=t-e;return n===0?"40-40":n===1?"A-40":n===-1?"40-A":n>=2?"G-40":"40-G"}return t>=3?"G-40":e>=3?"40-G":`${r[t]}-${r[e]}`}function HS(t){if(!t)return[];let e=t.history?.points;if(!e||e.length===0)return[];let r=[];for(let n=0;n<e.length;n++){let o=e[n],i=n<e.length-1?e[n+1]:void 0,s=n===e.length-1,a=t.matchUpStatus==="COMPLETED",c=o.set??0,u=o.game??0,p=o.number??0,{gameComplete:m,setComplete:d}=R6({nextPoint:i,isLastPoint:s,isCompleted:a,pointSet:c,pointGame:u}),l=m?o.winner:void 0,f=b6(d,t,c),g=C6(o),I=i?.server??o.server??0,S=M6(t,c,u);r.push({action:"addPoint",point:{index:n,number:p,winner:o.winner,server:o.server,score:o.score,result:o.result},game:{index:u,isTiebreak:S,complete:m,winner:l},set:{index:c,complete:d,winner:f},needed:g,nextService:I,result:o.result,complete:s&&a})}return r}function R6({nextPoint:t,isLastPoint:e,isCompleted:r,pointSet:n,pointGame:o}){let i=t?t.set??0:void 0,s=t?t.game??0:void 0;return{gameComplete:e?r||i===void 0&&s===void 0:i!==n||s!==o,setComplete:e?r||!1:t!==void 0&&i!==n}}function b6(t,e,r){if(!t)return;let n=e.score.sets[r];if(n?.winningSide!==void 0)return n.winningSide-1}function C6(t){let e={};return t.pointsToGame&&(e.pointsToGame=t.pointsToGame),t.pointsToSet&&(e.pointsToSet=t.pointsToSet),t.pointsToMatch&&(e.pointsToMatch=t.pointsToMatch),t.gamesToSet&&(e.gamesToSet=t.gamesToSet),t.isBreakpoint!==void 0&&(e.isBreakpoint=t.isBreakpoint),e}function M6(t,e,r){let n=t.score.sets[e];return!!(n?.isTiebreakOnly||r>0&&n?.side1Score!==void 0&&n?.side2Score!==void 0&&!n?.isTiebreakOnly)}function WS(t){return t.matchUpStatus==="COMPLETED"}function YS(t){if(t.matchUpStatus==="COMPLETED")return t.winningSide}function Id(t,e,r,n,o){if(r==="timed"||!n)return;let i=v6(t),s=O6(t),a=e.exactly||e.bestOf||3,c=Math.ceil(a/2),{side1Points:u,side2Points:p}=_6(i),m=x6(u,p,n,r,e,i),d=L6(i,n,r),l=F6(m,d,n,r),f=k6(l,s,c,e),g=V6(m,o);return{pointsToGame:m,pointsToSet:l,pointsToMatch:f,gamesToSet:d,isBreakpoint:g}}function v6(t){let e=t.score.sets;if(e.length===0)return;let r=e.at(-1);return r?.winningSide===void 0?r:void 0}function O6(t){let e=[0,0];return t.score.sets.forEach(r=>{r.winningSide===1&&e[0]++,r.winningSide===2&&e[1]++}),e}function _6(t){if(!t)return{side1Points:0,side2Points:0};let e=t.side1GameScores??[],r=t.side2GameScores??[];if(e.length===0&&r.length===0)return{side1Points:0,side2Points:0};let n=Math.max(e.length,r.length)-1;return{side1Points:e[n]??0,side2Points:r[n]??0}}function x6(t,e,r,n,o,i){if(n==="tiebreakOnly"){let s=r.tiebreakSet?.tiebreakTo||11,a=r.tiebreakSet?.NoAD||!1;return XC(t,e,s,a)}if(n==="matchTiebreak"){let s=o.finalSetFormat?.tiebreakSet?.tiebreakTo||10,a=o.finalSetFormat?.tiebreakSet?.NoAD||!1;return XC(t,e,s,a)}if(i){let s=i.side1Score||0,a=i.side2Score||0,c=r.setTo||6,u=(typeof r.tiebreakAt=="number"?r.tiebreakAt:void 0)??c;if(!(r.noTiebreak||!1)&&s===u&&a===u){let m=r.tiebreakFormat?.tiebreakTo||7,d=r.tiebreakFormat?.NoAD||!1;return XC(t,e,m,d)}}if(o.gameFormat?.type==="CONSECUTIVE"){let s=o.gameFormat.count||3;return[s,s]}return w6(t,e,r,o)}function w6(t,e,r,n){let o=r.gameFormat?.NoAD||r.NoAD||!1,i=n?.gameFormat?.deuceAfter,s=4;return[pk(t,e,s,o,i),pk(e,t,s,o,i)]}function pk(t,e,r,n,o){if(t>=r-1&&e>=r-1){if(n||o&&t>=2+o&&e>=2+o)return t>e?0:t===e?1:2;let i=t-e;return i>=2?0:i===1?1:2}return t>=r?0:r-t}function XC(t,e,r,n){return[mk(t,e,r,n),mk(e,t,r,n)]}function mk(t,e,r,n){if(t>=r&&(t-e>=2||n&&t>e))return 0;if(t>=r-1&&e>=r-1){if(n)return t>e?0:t===e?1:2;let o=t-e;return o>=2?0:o===1?1:2}return t>=r?0:r-t}function L6(t,e,r){if(r==="tiebreakOnly"||r==="matchTiebreak")return!t||t.winningSide!==void 0?[1,1]:[1,1];let n=t?.side1Score||0,o=t?.side2Score||0,i=e.setTo||6,s=(typeof e.tiebreakAt=="number"?e.tiebreakAt:void 0)??i,a=e.noTiebreak||!1,c=e.winBy||2;return[dk(n,o,i,s,a,c),dk(o,n,i,s,a,c)]}function dk(t,e,r,n,o,i){if(!o&&t===n&&e===n)return 1;if(t>=r){let a=t-e;return a>=i?0:i-a}let s=r-t;if(e>=r-1&&t>=r-1){if(!o)return Math.max(1,r-t);let a=t-e;return a>=i?0:i-a}return s}function F6(t,e,r,n){if(n==="tiebreakOnly"||n==="matchTiebreak")return[...t];let o=4;return[lk(t[0],e[0],o),lk(t[1],e[1],o)]}function lk(t,e,r){if(e<=0)return 0;let n=Math.max(0,e-1);return t+n*r}function k6(t,e,r,n){let o=n.setFormat,i=G6(o,n);return[fk(t[0],e[0],r,i),fk(t[1],e[1],r,i)]}function G6(t,e){if(!t)return 24;if(t.tiebreakSet)return t.tiebreakSet.tiebreakTo||11;if(t.timed)return 0;let r=t.setTo||6,o=e.gameFormat?.type==="CONSECUTIVE"?e.gameFormat?.count||3:4;return r*o}function fk(t,e,r,n){if(e>=r)return 0;let o=Math.max(0,r-e-1);return t+o*n}function V6(t,e){if(e===void 0)return!1;let r=1-e;return t[r]===1}function jS(t,e,r){if(r==="timed")return;let n=B6(t);return CA(e)?H6(t,n):r==="tiebreakOnly"||r==="matchTiebreak"?W6(n):Y6(t,e,n)}function B6(t){let e=t.score.sets;if(e.length===0)return;let r=e[e.length-1];return r.winningSide===void 0?r:void 0}function H6(t,e){let r=0;for(let n of t.score.sets)n.winningSide!==void 0&&(n.side1TiebreakScore!==void 0?r+=(n.side1TiebreakScore??0)+(n.side2TiebreakScore??0):r+=(n.side1Score??0)+(n.side2Score??0));if(e&&e.winningSide===void 0){let n=e.side1GameScores??[],o=e.side2GameScores??[];if(n.length>0||o.length>0){let i=Math.max(n.length,o.length)-1;r+=(n[i]??0)+(o[i]??0)}else r+=(e.side1Score??0)+(e.side2Score??0)}return r%2===0?"deuce":"ad"}function W6(t){if(!t)return"deuce";let e=t.side1GameScores??[],r=t.side2GameScores??[];return e.length===0&&r.length===0||((e[0]??0)+(r[0]??0))%2===0?"deuce":"ad"}function Y6(t,e,r){if(!r)return"deuce";let n=r.side1GameScores??[],o=r.side2GameScores??[];if(n.length===0&&o.length===0)return"deuce";let i=Math.max(n.length,o.length)-1;return((n[i]??0)+(o[i]??0))%2===0?"deuce":"ad"}function qS(t,e){if(!e.length)return 1;for(let{condition:r,value:n}of e)if(r.results&&t.result&&r.results.includes(t.result)||r.strokes&&t.stroke&&r.strokes.includes(t.stroke))return n;return 1}function Us(t,e,r){if(!Tt(e))return t;let n=e.winner,o=e.server,{timestamp:i}=e;if(n===void 0&&e.winningSide!==void 0&&(n=e.winningSide-1),o===void 0&&e.serverSideNumber!==void 0&&(o=e.serverSideNumber-1),n==null)return t;let s=t;s.history??={points:[]};let a=oe(t.matchUpFormat);if(!a)throw new Error(`Invalid matchUpFormat: ${t.matchUpFormat}`);let c=a.exactly||a.bestOf||3,u=Math.ceil(c/2),p=s.history.points.length+1,m=s.history.points.length,d=[0,0];s.score.sets.forEach(N=>{N.winningSide===1&&d[0]++,N.winningSide===2&&d[1]++});let l=Mu(a,d),f=d[0]===u-1&&d[1]===u-1,g=f&&a.finalSetFormat?a.finalSetFormat:a.setFormat,I=g?.tiebreakSet?.modifier==="RALLY"||g?.modifier==="RALLY";o===void 0&&!I&&(o=KS(s,a,l));let S=e.code;!S&&n!==void 0&&o!==void 0&&(S=n===o?"S":"R");let h={...e,pointNumber:p,winner:n,winningSide:n+1,server:o,serverSideNumber:o===void 0?void 0:o+1,serverParticipantId:e.serverParticipantId,timestamp:i||new Date().toISOString()};S&&(h.code=S),h.index=m;let T=Id(s,a,l,g,o);T&&(h.pointsToGame=T.pointsToGame,h.pointsToSet=T.pointsToSet,h.pointsToMatch=T.pointsToMatch,h.gamesToSet=T.gamesToSet,h.isBreakpoint=T.isBreakpoint);let y=jS(s,a,l);y!==void 0&&(h.serveSide=y);let E=r?.pointMultipliers??[],A=e.scoreValue??qS(h,E);switch(A!==1&&(h.scoreValue=A),s.history.points.push(h),s.matchUpStatus==="TO_BE_PLAYED"&&(s.matchUpStatus="IN_PROGRESS"),l){case"tiebreakOnly":$6(s,h,n,a,g,u,A);break;case"matchTiebreak":K6(s,h,n,a,u,A);break;case"timed":z6(s,h,n,g,A);break;default:j6(s,h,n,a,g,u,f);break}return s}function j6(t,e,r,n,o,i,s){let a=MA(t,!1,!1),c=t.score.sets.indexOf(a),u=a.side1Score||0,p=a.side2Score||0,m=a.side1GameScores??[],d=a.side2GameScores??[];m.length===0&&d.length===0&&(m.push(0),d.push(0));let l=Math.max(m.length,d.length)-1,f=l>=0?m[l]??0:0,g=l>=0?d[l]??0:0,I=Math.max(m.length,d.length)-1,S=u+p-I;e.set=c,e.game=S+l,e.number=f+g;let h=o.setTo||6,T=(typeof o.tiebreakAt=="number"?o.tiebreakAt:void 0)??h,y=s&&n.finalSetFormat?.noTiebreak;r===0?(f++,m[m.length-1]=f):(g++,d[d.length-1]=g),a.side1GameScores=m,a.side2GameScores=d;let E=n.gameFormat?.type==="CONSECUTIVE",A=n.gameFormat?.count||3;if(E){let D=a.currentStreak;D?.side===r?a.currentStreak={side:r,count:D.count+1}:a.currentStreak={side:r,count:1}}let N=!y&&u===T&&p===T,U;E&&!N?U=a.currentStreak.count>=A?a.currentStreak.side:void 0:U=Q6(f,g,o,N,n);let R=U===void 0?tM(f,g,N,E&&!N):"0-0";e.score=R,U!==void 0&&q6(a,U,u,p,f,g,N,E,t,n,o,s,i)}function q6(t,e,r,n,o,i,s,a,c,u,p,m,d){a&&(t.currentStreak=void 0),e===0?t.side1Score=r+1:t.side2Score=n+1,s&&(t.side1TiebreakScore=o,t.side2TiebreakScore=i);let l=ZC(t.side1Score||0,t.side2Score||0,p,m,u.finalSetFormat);typeof l=="number"?(t.winningSide=l+1,$S(c,u,d)):(t.side1GameScores.push(0),t.side2GameScores.push(0))}function $6(t,e,r,n,o,i,s=1){let a=MA(t,!0,!1),c=t.score.sets.indexOf(a),u=o.tiebreakSet.tiebreakTo||11,p=o.tiebreakSet.NoAD||!1,m=a.side1GameScores??[],d=a.side2GameScores??[];m.length===0&&d.length===0&&(m.push(0),d.push(0),a.side1GameScores=m,a.side2GameScores=d);let l=m[0]||0,f=d[0]||0;e.set=c,e.game=0,e.number=l+f,r===0?(l+=s,m[0]=l):(f+=s,d[0]=f),a.side1GameScores=m,a.side2GameScores=d;let g=JC(l,f,u,p);e.score=g===void 0?`${l}-${f}`:"0-0",g!==void 0&&(a.winningSide=g+1,a.side1TiebreakScore=l,a.side2TiebreakScore=f,a.side1Score=g===0?1:0,a.side2Score=g===0?0:1,$S(t,n,i))}function K6(t,e,r,n,o,i=1){let s=n.finalSetFormat?.tiebreakSet?.tiebreakTo||10,a=n.finalSetFormat?.tiebreakSet?.NoAD||!1,c=MA(t,!1,!1),u=t.score.sets.indexOf(c),p=c.side1GameScores??[],m=c.side2GameScores??[];p.length===0&&m.length===0&&(p.push(0),m.push(0),c.side1GameScores=p,c.side2GameScores=m);let d=p[0]||0,l=m[0]||0;e.set=u,e.game=0,e.number=d+l,r===0?(d+=i,p[0]=d):(l+=i,m[0]=l),c.side1GameScores=p,c.side2GameScores=m;let f=JC(d,l,s,a);e.score=f===void 0?`${d}-${l}`:"0-0",f!==void 0&&(c.side1TiebreakScore=d,c.side2TiebreakScore=l,c.side1Score=f===0?1:0,c.side2Score=f===0?0:1,c.winningSide=f+1,$S(t,n,o))}function z6(t,e,r,n,o=1){let i=MA(t,!1,!0),s=t.score.sets.indexOf(i);e.set=s,e.game=0,e.number=(i.side1Score||0)+(i.side2Score||0),r===0?i.side1Score=(i.side1Score||0)+o:i.side2Score=(i.side2Score||0)+o;let a=i.side1Score||0,c=i.side2Score||0;e.score=`${a}-${c}`}function MA(t,e,r){let n=t.score.sets.length-1,o=n>=0?t.score.sets[n]:void 0;if(o&&o.winningSide===void 0&&!o.segmentComplete)return o;let i={setNumber:t.score.sets.length+1,side1Score:0,side2Score:0,side1GameScores:[],side2GameScores:[]};return e&&(i.isTiebreakOnly=!0),r&&(i.isTimed=!0),t.score.sets.push(i),i}function $S(t,e,r){let n=[0,0];t.score.sets.forEach(c=>{c.winningSide===1&&n[0]++,c.winningSide===2&&n[1]++});let o=CA(e),i=e.exactly;if(o){let c=i||e.bestOf||3;if(t.score.sets.length<c)return;let p=t.score.sets.reduce((m,d)=>(d.side1TiebreakScore!==void 0&&d.side2TiebreakScore!==void 0?(m[0]+=d.side1TiebreakScore,m[1]+=d.side2TiebreakScore):(m[0]+=d.side1Score??0,m[1]+=d.side2Score??0),m),[0,0]);p[0]!==p[1]&&(t.matchUpStatus="COMPLETED",t.winningSide=p[0]>p[1]?1:2,t.endTime=new Date().toISOString());return}if(!(n[0]>=r||n[1]>=r)||i&&t.score.sets.filter(u=>u.winningSide!==void 0).length<i)return;let a=n[0]>=r?0:1;t.matchUpStatus="COMPLETED",t.winningSide=a+1,t.endTime=new Date().toISOString()}function JC(t,e,r,n=!1){let o=Math.abs(t-e),i=n?1:2;if((t>=r||e>=r)&&o>=i)return t>e?0:1}function Q6(t,e,r,n,o){let i=r.gameFormat?.NoAD||r.NoAD||!1;if(n){let u=r.tiebreakFormat?.tiebreakTo||7,p=r.tiebreakFormat?.NoAD||!1;return JC(t,e,u,p)}let s=4,a=Math.abs(t-e);if(i)return t>=s||e>=s?t>e?0:1:void 0;let c=o?.gameFormat?.deuceAfter;if(c&&t>=2+c&&e>=2+c)return t!==e?t>e?0:1:void 0;if((t>=s||e>=s)&&a>=2)return t>e?0:1}function ZC(t,e,r,n,o){let i=r.setTo||6,s=(typeof r.tiebreakAt=="number"?r.tiebreakAt:void 0)??i,a=n&&o?.noTiebreak;if(i===1)return t>=1||e>=1?t>e?0:1:void 0;let u=(n&&o?o:r).winBy||2;if(!a&&(t===s+1||e===s+1)||(t>=i||e>=i)&&Math.abs(t-e)>=u)return t>e?0:1}function KS(t,e,r){let n=vA(t,e,r);if(t.serverFlip!==void 0)return t.serverFlip?1-n:n;let o=t.history?.points?.[0];if(o?.server!==void 0){let i=o.set??0,s=o.game??0,a=0;for(let u=0;u<i;u++){let p=t.score.sets[u];a+=(p.side1Score||0)+(p.side2Score||0)}a+=s;let c=a%2;if(o.server!==c)return 1-n}return n}function vA(t,e,r){let n=t.score.sets.length-1,o=n>=0?t.score.sets[n]:void 0;if(r==="tiebreakOnly"||r==="matchTiebreak")return X6(t,o);if(r==="timed")return J6(o);let i=o?.side1Score||0,s=o?.side2Score||0,a=0;for(let l=0;l<t.score.sets.length-1;l++){let f=t.score.sets[l];a+=(f.side1Score||0)+(f.side2Score||0)}let c=e.setFormat?.setTo||6,u=(typeof e.setFormat?.tiebreakAt=="number"?e.setFormat.tiebreakAt:void 0)??c;if(!e.finalSetFormat?.noTiebreak&&i===u&&s===u){let l=o?.side1GameScores??[],f=o?.side2GameScores??[],g=(l.at(-1)||0)+(f.at(-1)||0),S=(a+i+s)%2,h=Math.floor(g/2)%2;return(S+h)%2}return(a+i+s)%2}function X6(t,e){let r=e?.side1GameScores??[],n=e?.side2GameScores??[],o=(r[0]||0)+(n[0]||0),i=0;for(let c=0;c<t.score.sets.length-1;c++){let u=t.score.sets[c];i+=(u.side1Score||0)+(u.side2Score||0)}let s=i%2,a=Math.floor(o/2)%2;return(s+a)%2}function J6(t){return((t?.side1Score||0)+(t?.side2Score||0))%2}function tM(t,e,r,n){if(r||n)return`${t}-${e}`;let o=["0","15","30","40"];if(t<4&&e<4)return`${o[t]}-${o[e]}`;if(t>=3&&e>=3&&t===e)return"40-40";if(t>=3&&e>=3){let i=t-e;if(i===1)return"A-40";if(i===-1)return"40-A";if(i>=2)return"G-40";if(i<=-2)return"40-G"}return t>=3?`40-${e<4?o[e]:"40"}`:e>=3?`${t<4?o[t]:"40"}-40`:`${t<4?o[t]:"0"}-${e<4?o[e]:"0"}`}function Zi(t,e){let r=t.score.sets,n=eK(t,e?.useBracketNotation),o=r.length>0?r.at(-1):null,i=o&&o.winningSide===void 0?[o.side1Score||0,o.side2Score||0]:[0,0],s=[0,0];if(o?.side1GameScores&&o.side2GameScores){let u=Math.max(o.side1GameScores.length,o.side2GameScores.length)-1;u>=0&&(s=[o.side1GameScores[u]||0,o.side2GameScores[u]||0])}let a=Z6(t,s),c=tK(t);return{sets:r,scoreString:n,games:i,points:s,pointDisplay:a,situation:c}}function Z6(t,e){if(t.matchUpStatus==="COMPLETED"||t.matchUpStatus==="TO_BE_PLAYED")return;let r=oe(t.matchUpFormat);if(!r)return;let n=t.score.sets.at(-1);if(!n||n.winningSide!==void 0)return;let o=[0,0];t.score.sets.forEach(m=>{m.winningSide===1&&o[0]++,m.winningSide===2&&o[1]++});let i=Mu(r,o),s=i==="tiebreakOnly"||i==="matchTiebreak",a=r.gameFormat?.type==="CONSECUTIVE",c=s;if(!c&&i==="standard"){let m=r.exactly||r.bestOf||3,d=Math.ceil(m/2),l=o[0]===d-1&&o[1]===d-1,f=l&&r.finalSetFormat?r.finalSetFormat:r.setFormat;if(f){let g=n.side1Score||0,I=n.side2Score||0,S=f.setTo||6,h=(typeof f.tiebreakAt=="number"?f.tiebreakAt:void 0)??S,T=f.noTiebreak||!1,y=l&&r.finalSetFormat?.noTiebreak;c=!T&&!y&&g===h&&I===h}}let p=tM(e[0],e[1],c,a&&!c).split("-");return p.length===2?[p[0],p[1]]:[String(e[0]),String(e[1])]}function tK(t){if(t.matchUpStatus==="COMPLETED"||t.matchUpStatus==="TO_BE_PLAYED")return;let e=oe(t.matchUpFormat);if(!e)return;let r=e.exactly||e.bestOf||3,n=Math.ceil(r/2),o=[0,0];t.score.sets.forEach(A=>{A.winningSide===1&&o[0]++,A.winningSide===2&&o[1]++});let i=Mu(e,o),s=o[0]===n-1&&o[1]===n-1,a=s&&e.finalSetFormat?e.finalSetFormat:e.setFormat,c=a?.tiebreakSet?.modifier==="RALLY"||a?.modifier==="RALLY",u;c||(u=KS(t,e,i));let p=Id(t,e,i,a,u);if(!p)return{isBreakPoint:!1,isGamePoint:!1,isSetPoint:!1,isMatchPoint:!1,isGoldenPoint:!1,isTiebreak:!1,server:u};let{pointsToGame:m,pointsToSet:d,pointsToMatch:l,isBreakpoint:f}=p,g=i==="tiebreakOnly"||i==="matchTiebreak";if(!g&&i==="standard"&&a){let A=t.score.sets.at(-1);if(A){let N=A.side1Score||0,U=A.side2Score||0,R=a.setTo||6,D=(typeof a.tiebreakAt=="number"?a.tiebreakAt:void 0)??R,b=a.noTiebreak||!1,C=s&&e.finalSetFormat?.noTiebreak;g=!b&&!C&&N===D&&U===D}}let I=!!(a?.NoAD||a?.gameFormat?.NoAD||g&&(a?.tiebreakFormat?.NoAD||a?.tiebreakSet?.NoAD||e.finalSetFormat?.tiebreakSet?.NoAD)),S=e.gameFormat?.deuceAfter,h=m[0]===1&&m[1]===1&&(I||!!S&&!g),T=u===void 0?!1:m[u]===1,y=Math.min(d[0],d[1])===1,E=Math.min(l[0],l[1])===1;return{isBreakPoint:f,isGamePoint:T,isSetPoint:y,isMatchPoint:E,isGoldenPoint:h,isTiebreak:g,server:u}}function eK(t,e=!1){let r=t.score.sets;return r.length===0?"0-0":r.map(o=>{let i=o.side1Score||0,s=o.side2Score||0;if(o.side1TiebreakScore!==void 0||o.side2TiebreakScore!==void 0){let a=o.side1TiebreakScore||0,c=o.side2TiebreakScore||0;return e&&(i===0&&s===1||i===1&&s===0)?`[${a}-${c}]`:i>s?`${i}-${s}(${c})`:`${i}(${a})-${s}`}return`${i}-${s}`}).join(", ")}var zS=class{constructor(e={}){this.pointMultipliers=[];this.redoStack=[];e.competitionFormat?(this.competitionFormat=e.competitionFormat,this.matchUpFormat=e.matchUpFormat||e.competitionFormat.matchUpFormat||"SET3-S:6/TB7",this.pointMultipliers=e.pointMultipliers||(e.competitionFormat.pointMultipliers??[])):(this.matchUpFormat=e.matchUpFormat||"SET3-S:6/TB7",this.pointMultipliers=e.pointMultipliers??[]),this.matchUpId=e.matchUpId,this.isDoubles=e.isDoubles||!1,this.eventHandlers=e.eventHandlers,this.state=Ji({matchUpFormat:this.matchUpFormat,matchUpId:this.matchUpId,isDoubles:this.isDoubles}),this.cacheFormatStructure()}setState(e){this.state=e,this.matchUpFormat=e.matchUpFormat,this.matchUpId=e.matchUpId,this.isDoubles=e.matchUpType==="DOUBLES",this.redoStack=[],this.initialScore=void 0,this.cacheFormatStructure()}getState(){return JSON.parse(JSON.stringify(this.state))}addPoint(e){let r=this.state.history?.points.length||0,n=this.state.score.sets.reduce((a,c)=>a+(c.side1Score||0)+(c.side2Score||0),0),o=this.state.score.sets.filter(a=>a.winningSide!==void 0).length,i=this.state.matchUpStatus==="COMPLETED",s=this.hasLineUp()?this.getActivePlayers():void 0;if(this.state=Us(this.state,e,{pointMultipliers:this.pointMultipliers}),s){let a=this.state.history.points[this.state.history.points.length-1];this.isDoubles?a.activePlayers=[s.side1,s.side2]:a.activePlayers=[s.side1[0]||"",s.side2[0]||""]}if(e.penaltyType){let a=this.state.history.points[this.state.history.points.length-1];a.penaltyType=e.penaltyType}if(this.ensureHistory(),this.state.history.entries.push({type:"point",data:{winner:e.winner,winningSide:e.winningSide,server:e.server,serverSideNumber:e.serverSideNumber,serverParticipantId:e.serverParticipantId,timestamp:e.timestamp,rallyLength:e.rallyLength,result:e.result,penaltyType:e.penaltyType},timestamp:e.timestamp||new Date().toISOString(),pointIndex:r}),this.redoStack=[],this.eventHandlers){let a=this.buildEventContext();if(this.eventHandlers.onPoint?.(a),this.state.score.sets.reduce((p,m)=>p+(m.side1Score||0)+(m.side2Score||0),0)>n&&this.eventHandlers.onGameComplete?.({...a,gameWinner:e.winner}),this.state.score.sets.filter(p=>p.winningSide!==void 0).length>o){let m=this.state.score.sets.findLast(d=>d.winningSide!==void 0)?.winningSide===1?0:1;this.eventHandlers.onSetComplete?.({...a,setWinner:m})}if(!i&&this.state.matchUpStatus==="COMPLETED"){let p=this.state.winningSide===1?0:1;this.eventHandlers.onMatchComplete?.({...a,matchWinner:p})}}}addSet(e){this.applyAddSet(e),this.ensureHistory();let r=this.state.score.sets.at(-1)?.winningSide;this.state.history.entries.push({type:"set",data:{...e,winningSide:r},timestamp:e.timestamp||new Date().toISOString()}),this.redoStack=[]}addGame(e){this.applyAddGame(e),this.ensureHistory(),this.state.history.entries.push({type:"game",data:e,timestamp:e.timestamp||new Date().toISOString()}),this.redoStack=[]}endSegment(e){this.applyEndSegment(e),this.ensureHistory();let r=(e?.setNumber??this.state.score.sets.length)-1;this.state.history.entries.push({type:"endSegment",data:{setNumber:r+1,...e},timestamp:e?.timestamp||new Date().toISOString()})}setInitialScore(e){this.initialScore=e,this.redoStack=[],this.applyInitialScore(this.state,e),this.ensureHistory(),this.state.history.entries.push({type:"setInitialScore",data:e,timestamp:new Date().toISOString()}),this.state.matchUpStatus==="TO_BE_PLAYED"&&(this.state.matchUpStatus="IN_PROGRESS")}undo(e=1){let r=this.state.history?.entries;if(r&&r.length>0){let i=Math.min(e,r.length);for(let s=0;s<i;s++){let a=r.pop();this.redoStack.push(a),a.type==="point"&&this.state.history.points.pop()}return this.rebuildFromEntries(),this.eventHandlers?.onUndo?.(this.buildEventContext()),!0}let n=this.state.history?.points??[];if(n.length===0)return!1;let o=Math.min(e,n.length);for(let i=0;i<o;i++){let s=n.pop();this.redoStack.push({type:"point",data:{winner:s.winner,server:s.server,timestamp:s.timestamp,rallyLength:s.rallyLength},timestamp:s.timestamp||""})}return this.rebuildState(),this.eventHandlers?.onUndo?.(this.buildEventContext()),!0}redo(e=1){if(this.redoStack.length===0)return!1;let r=Math.min(e,this.redoStack.length);for(let n=0;n<r;n++){let o=this.redoStack.pop();this.ensureHistory(),this.state.history.entries.push(o),o.type}return this.rebuildFromEntries(),this.eventHandlers?.onRedo?.(this.buildEventContext()),!0}canUndo(){let e=this.state.history?.entries;return e&&e.length>0?!0:(this.state.history?.points.length||0)>0}canRedo(){return this.redoStack.length>0}getUndoDepth(){let e=this.state.history?.entries;return e&&e.length>0?e.length:this.state.history?.points.length||0}getRedoDepth(){return this.redoStack.length}getScore(){return Zi(this.state)}getScoreboard(e){return BS(this.state,e)}getWinner(){return YS(this.state)}isComplete(){return WS(this.state)}getPointCount(){return this.state.history?.points.length||0}getFormat(){return this.state.matchUpFormat}getStatistics(e){let r=this.state.history?.points??[];return Df(this.state,r,e)}getStatObjects(e){return Rf(this.getStatistics(e))}getNextServer(){if(this.competitionFormat?.serverRule==="WINNER_SERVES"){let o=this.state.history?.points.at(-1);return o?o.winner:0}if(!this.cachedFormatStructure)return 0;let r=[0,0];this.state.score.sets.forEach(o=>{o.winningSide===1&&r[0]++,o.winningSide===2&&r[1]++});let n=Mu(this.cachedFormatStructure,r);return KS(this.state,this.cachedFormatStructure,n)}setServer(e,r){if(!this.cachedFormatStructure)return;let n=[0,0];this.state.score.sets.forEach(s=>{s.winningSide===1&&n[0]++,s.winningSide===2&&n[1]++});let o=Mu(this.cachedFormatStructure,n),i=vA(this.state,this.cachedFormatStructure,o);this.state.serverFlip=e!==i,r?.recordEntry!==!1&&(this.ensureHistory(),this.state.history.entries.push({type:"setServer",data:{side:e},timestamp:new Date().toISOString()}),this.redoStack=[])}getEpisodes(){return HS(this.state)}isNoAd(){return!!(this.cachedFormatStructure?.setFormat?.NoAD||this.cachedFormatStructure?.setFormat?.gameFormat?.NoAD)}getSetsToWin(){if(!this.cachedFormatStructure)return 2;let e=this.cachedFormatStructure.exactly||this.cachedFormatStructure.bestOf||3;return Math.ceil(e/2)}getTiebreakAt(){let e=this.cachedFormatStructure?.setFormat;if(!e||e.tiebreakSet||e.timed||e.noTiebreak)return null;let r=e.setTo||6;return(typeof e.tiebreakAt=="number"?e.tiebreakAt:void 0)??r}hasFinalSetTiebreak(){let e=this.cachedFormatStructure?.finalSetFormat;return e?e.tiebreakSet?!0:e.noTiebreak?!1:!!(e.tiebreakFormat||e.tiebreakAt!==void 0):this.getTiebreakAt()!==null}getFormatStructure(){return this.cachedFormatStructure}getInputMode(){let e=this.state.history?.entries??[];if(e.length===0)return(this.state.history?.points.length||0)>0?"points":"none";let r=new Set(e.filter(n=>n.type!=="setInitialScore"&&n.type!=="endSegment").map(n=>n.type));if(r.size===0)return"none";if(r.size===1){let n=r.values().next().value;if(n==="point")return"points";if(n==="game")return"games";if(n==="set")return"sets"}return"mixed"}setLineUp(e,r){let n=this.state.sides.find(o=>o.sideNumber===e);n&&(n.lineUp=r),this.initialLineUps??={},this.initialLineUps[e]=r.map(o=>({...o}))}substitute(e){let r=this.state.sides.find(i=>i.sideNumber===e.sideNumber);if(!r?.lineUp)return;let n=r.lineUp.findIndex(i=>i.participantId===e.outParticipantId);if(n===-1)return;this.ensureHistory(),this.state.history.substitutions??=[];let o={sideNumber:e.sideNumber,outParticipantId:e.outParticipantId,inParticipantId:e.inParticipantId,beforePointIndex:this.state.history.points.length,timestamp:e.timestamp};this.state.history.substitutions.push(o),r.lineUp[n]={...r.lineUp[n],participantId:e.inParticipantId},this.state.history.entries.push({type:"substitution",data:o,timestamp:e.timestamp||new Date().toISOString()}),this.redoStack=[]}getActivePlayers(){let e=this.state.sides.find(n=>n.sideNumber===1),r=this.state.sides.find(n=>n.sideNumber===2);return{side1:e?.lineUp?.map(n=>n.participantId)??[],side2:r?.lineUp?.map(n=>n.participantId)??[]}}hasLineUp(){return this.state.sides.some(e=>e.lineUp&&e.lineUp.length>0)}setPointMultipliers(e){this.pointMultipliers=e}getPointMultipliers(){return this.pointMultipliers}getSupplementaryState(){return{redoStack:[...this.redoStack],initialLineUps:this.initialLineUps?Object.fromEntries(Object.entries(this.initialLineUps).map(([e,r])=>[e,r.map(n=>({...n}))])):void 0}}loadSupplementaryState(e){e.redoStack&&(this.redoStack=[...e.redoStack]),e.initialLineUps&&(this.initialLineUps=Object.fromEntries(Object.entries(e.initialLineUps).map(([r,n])=>[r,n.map(o=>({...o}))])))}getPenaltyProfile(){return this.competitionFormat?.penaltyProfile}getPointProfile(){return this.competitionFormat?.pointProfile}getTimerProfile(){return this.competitionFormat?.timerProfile}getTimeoutRules(){return this.competitionFormat?.timeoutRules}getPenaltyBoxProfile(){return this.competitionFormat?.penaltyBoxProfile}getSubstitutionRules(){return this.competitionFormat?.substitutionRules}getPlayerRules(){return this.competitionFormat?.playerRules}setEventHandlers(e){this.eventHandlers=e}getEventHandlers(){return this.eventHandlers}decoratePoint(e,r){let n=this.state.history?.points[e];n&&Object.assign(n,r)}markHardBoundary(e){let r=this.state.score.sets[e.setIndex];r&&(r.hardBoundaries??=[],r.hardBoundaries.includes(e.gameIndex)||(r.hardBoundaries.push(e.gameIndex),r.hardBoundaries.sort((n,o)=>n-o)))}editPoint(e,r,n){let o=this.state.history?.points;if(!o||e<0||e>=o.length)return;let i=n?.recalculate!==!1,s=o[e];if(r.winner!==void 0&&(s.winner=r.winner),r.server!==void 0&&(s.server=r.server),r.timestamp!==void 0&&(s.timestamp=r.timestamp),r.rallyLength!==void 0&&(s.rallyLength=r.rallyLength),r.wrongSide!==void 0&&(s.wrongSide=r.wrongSide),r.wrongServer!==void 0&&(s.wrongServer=r.wrongServer),r.penaltyPoint!==void 0&&(s.penaltyPoint=r.penaltyPoint),!i)return;let a=this.state.history?.entries;if(a){let c=a.find(u=>u.type==="point"&&u.pointIndex===e);c&&(r.winner!==void 0&&(c.data.winner=r.winner),r.server!==void 0&&(c.data.server=r.server))}a&&a.length>0?this.rebuildFromEntries():this.rebuildState(),this.redoStack=[]}removePoint(e,r){let n=this.state.history?.points;if(!n||e<0||e>=n.length)return;let o=r?.recalculate!==!1;n.splice(e,1);let i=this.state.history?.entries;if(i){let s=i.findIndex(a=>a.type==="point"&&a.pointIndex===e);s!==-1&&i.splice(s,1);for(let a of i)a.type==="point"&&a.pointIndex>e&&(a.pointIndex-=1)}o&&(i&&i.length>0?this.rebuildFromEntries():this.rebuildState(),this.redoStack=[])}reset(){this.state=Ji({matchUpFormat:this.matchUpFormat,matchUpId:this.matchUpId,isDoubles:this.isDoubles}),this.redoStack=[],this.initialScore=void 0,this.initialLineUps=void 0,this.eventHandlers?.onReset?.(this.buildEventContext())}ensureHistory(){this.state.history??={points:[]},this.state.history.entries??=[]}buildEventContext(){return{state:this.state,score:Zi(this.state)}}cacheFormatStructure(){this.cachedFormatStructure=oe(this.matchUpFormat)}getInitialLineUps(){return this.initialLineUps}applyAddSet(e){let{side1Score:r,side2Score:n,side1TiebreakScore:o,side2TiebreakScore:i}=e,s=e.winningSide;s===void 0&&(r>n?s=1:n>r&&(s=2));let a={setNumber:this.state.score.sets.length+1,side1Score:r,side2Score:n,winningSide:s};o!==void 0&&(a.side1TiebreakScore=o),i!==void 0&&(a.side2TiebreakScore=i),this.state.score.sets.push(a),this.state.matchUpStatus==="TO_BE_PLAYED"&&(this.state.matchUpStatus="IN_PROGRESS"),s!==void 0&&this.checkMatchCompletion()}applyAddGame(e){let{winner:r,tiebreakScore:n}=e,o=this.state.score.sets.length>0?this.state.score.sets.at(-1):void 0;(!o||o.winningSide!==void 0)&&(o={setNumber:this.state.score.sets.length+1,side1Score:0,side2Score:0},this.state.score.sets.push(o)),r===0?o.side1Score=(o.side1Score||0)+1:o.side2Score=(o.side2Score||0)+1,(o.side1GameScores?.length||o.side2GameScores?.length)&&(o.side1GameScores=o.side1GameScores??[],o.side2GameScores=o.side2GameScores??[],o.side1GameScores.push(0),o.side2GameScores.push(0)),n&&(o.side1TiebreakScore=n[0],o.side2TiebreakScore=n[1]),this.state.matchUpStatus==="TO_BE_PLAYED"&&(this.state.matchUpStatus="IN_PROGRESS"),this.checkSetCompletion(o),o.winningSide!==void 0&&this.checkMatchCompletion()}applySubstitution(e){let r=this.state.sides.find(o=>o.sideNumber===e.sideNumber);if(!r?.lineUp)return;let n=r.lineUp.findIndex(o=>o.participantId===e.outParticipantId);n!==-1&&(r.lineUp[n]={...r.lineUp[n],participantId:e.inParticipantId},this.state.history??={points:[]},this.state.history.substitutions??=[],this.state.history.substitutions.push(e))}applyEndSegment(e){let r=(e?.setNumber??this.state.score.sets.length)-1,n=this.state.score.sets[r];if(!n||n.winningSide!==void 0)return;let o=n.side1Score||0,i=n.side2Score||0;o>i?n.winningSide=1:i>o&&(n.winningSide=2),n.segmentComplete=!0,this.checkMatchCompletion()}checkSetCompletion(e){let r=oe(this.state.matchUpFormat);if(!r)return;let n=r.exactly||r.bestOf||3,o=Math.ceil(n/2),i=[0,0];this.state.score.sets.forEach(p=>{p.winningSide===1&&i[0]++,p.winningSide===2&&i[1]++});let s=i[0]===o-1&&i[1]===o-1,a=s&&r.finalSetFormat?r.finalSetFormat:r.setFormat;if(!a)return;let c=e.side1Score||0,u=e.side2Score||0;if(a.tiebreakSet){let p=a.tiebreakSet.tiebreakTo||11,d=a.tiebreakSet.NoAD||!1?1:2;(c>=p||u>=p)&&Math.abs(c-u)>=d&&(e.winningSide=c>u?1:2)}else if(!a.timed){let p=ZC(c,u,a,s,r.finalSetFormat);typeof p=="number"&&(e.winningSide=p+1)}}checkMatchCompletion(){let e=oe(this.state.matchUpFormat);if(!e)return;let r=e.exactly||e.bestOf||3,n=Math.ceil(r/2);$S(this.state,e,n)}rebuildFromEntries(){let e=this.state.history?.entries??[],r=this.prepareRebuildState(e);this.state=r;for(let n of e)switch(n.type){case"point":this.state=Us(this.state,n.data,{pointMultipliers:this.pointMultipliers}),this.state.history.entries=r.history.entries;break;case"set":this.applyAddSet(n.data);break;case"game":this.applyAddGame(n.data);break;case"endSegment":this.applyEndSegment(n.data);break;case"substitution":this.applySubstitution(n.data);break;case"setInitialScore":break;case"setServer":this.replaySetServerEntry(n.data);break}}prepareRebuildState(e){let r=this.getInitialLineUps(),n=Ji({matchUpFormat:this.matchUpFormat,matchUpId:this.matchUpId,isDoubles:this.isDoubles});if(r)for(let o of n.sides)r[o.sideNumber]&&(o.lineUp=r[o.sideNumber].map(i=>({...i})));return this.initialScore&&(this.applyInitialScore(n,this.initialScore),n.matchUpStatus==="TO_BE_PLAYED"&&(n.matchUpStatus="IN_PROGRESS")),n.history={points:[],entries:[...e]},n}replaySetServerEntry(e){let r=[0,0];this.state.score.sets.forEach(i=>{i.winningSide===1&&r[0]++,i.winningSide===2&&r[1]++});let n=Mu(this.cachedFormatStructure,r),o=vA(this.state,this.cachedFormatStructure,n);this.state.serverFlip=e.side!==o}rebuildState(){let e=this.state.history?.points??[],r=Ji({matchUpFormat:this.matchUpFormat,matchUpId:this.matchUpId,isDoubles:this.isDoubles});this.initialScore&&(this.applyInitialScore(r,this.initialScore),r.matchUpStatus==="TO_BE_PLAYED"&&(r.matchUpStatus="IN_PROGRESS"));for(let n of e)r=Us(r,{winner:n.winner,server:n.server,timestamp:n.timestamp,rallyLength:n.rallyLength,result:n.result},{pointMultipliers:this.pointMultipliers});this.state=r}applyInitialScore(e,r){e.score.sets=[];for(let n=0;n<r.sets.length;n++){let o=r.sets[n],i={setNumber:n+1,side1Score:o.side1Score,side2Score:o.side2Score};if(o.side1TiebreakScore!==void 0&&(i.side1TiebreakScore=o.side1TiebreakScore),o.side2TiebreakScore!==void 0&&(i.side2TiebreakScore=o.side2TiebreakScore),o.winningSide===void 0){let s=this.cachedFormatStructure,c=(s?.finalSetFormat&&n===(s.bestOf??s.exactly??3)-1?s.finalSetFormat:s?.setFormat)?.setTo;c&&(o.side1Score>=c||o.side2Score>=c)&&(o.side1Score>o.side2Score?i.winningSide=1:o.side2Score>o.side1Score&&(i.winningSide=2))}else i.winningSide=o.winningSide;e.score.sets.push(i)}if(r.currentSetScore){let n={setNumber:e.score.sets.length+1,side1Score:r.currentSetScore.side1Score,side2Score:r.currentSetScore.side2Score,side1GameScores:[],side2GameScores:[]};r.currentGameScore?(n.side1GameScores=[r.currentGameScore.side1Points],n.side2GameScores=[r.currentGameScore.side2Points]):(n.side1GameScores=[0],n.side2GameScores=[0]),e.score.sets.push(n)}}};var rM={};Gt(rM,{addPoint:()=>Us,calculatePointsTo:()=>Id,createMatchUp:()=>Ji,inferServeSide:()=>jS,resolvePointValue:()=>qS});var TM={};Gt(TM,{keyValueScore:()=>hM,parseMatchUpFormat:()=>oe,stringifyMatchUpFormat:()=>ip});var gk="COMPLETED";var rK="WO/WO";var OA=["RET","DEF","WO",rK,"ABN","SUS","INT"];var _A="DEFAULTED";var nM="WALKOVER";var xA="ABANDONED",wA="SUSPENDED",oM="RETIRED",LA="INTERRUPTED";var Ik=[oM,_A,nM],nK="Enter Score",ta="()",ea="[]",iM=["up","left","shift+tab"],sM=["enter","down","tab","right"],bf="backspace",aM="r",cM="s",uM="a",pM="d",mM="w",dM="i",Cf=[aM,pM,mM,uM,cM,dM],Sd="space",FA=["[","("],Mf=[...iM,...sM,Sd,"]"],Sk="-",oK="/",Ba=Sk,Ui=Sk,lM=[oK],hk=0,iK=["=","+","num_1","num_2","shift+=","shift+-"],Va=["0","1","2","3","4","5","6","7","8","9"].concat(Cf),Tk=Va.map(t=>`shift+${t}`),fM=[Ba,bf].concat(Mf,lM),gM=[Va,Tk,fM].join(","),sK=[gM,iM,sM,iK].join(","),I9t=[].concat(...Va,...Va,...fM,...Va,...Va,...Va,...Va,...Va,...Va),yk={OUTCOMEKEYS:Cf,SIDE1KEYS:Va,SIDE2KEYS:Tk,MODIFIERS:fM,PROMPT:nK,MOVEUP:iM,MOVEDOWN:sM,HOTKEYS:sK};function hd({scoreString:t,lowSide:e,outcome:r}){if({scoreString:t}=Ek({scoreString:t}),e===2){let o=t?.[t.length-1]===" "?"":" ";return t+o+r}else return r+" "+t}function Ek({scoreString:t}){if(!t)return{scoreString:""};let e=!1;for(let r of OA){let n=t?.indexOf(r);n===0?t=t.slice(r.length+1).trim()+" ":n>0&&(t=t.slice(0,n)),n>=0&&(e=!0)}return t?.trim()||(t=""),{scoreString:t,removed:e}}function aK({newScore:t,scoreString:e,lastMatchTiebreakOpenBracketIndex:r,lastSet:n,lowSide:o,NoAD:i,tiebreakTo:s}){let c=t.slice(r+1).split(Ui),u=c?.length>0&&c[0]!==void 0&&!Number.isNaN(Number.parseInt(c[0]))&&Number.parseInt(c[0])||void 0,p=c?.length>1&&c[1]!==void 0&&!Number.isNaN(Number.parseInt(c[1]))&&Number.parseInt(c[1])||void 0,m=[u,p],d=!1;if(p){let l=o===1?1:0;m[l]=(m?.[1-l]||0)+(i?1:2),(m[l]||0)<s&&(m[l]=s),t=e.slice(0,r+1),t+=m.join(Ui)}else u===void 0?(t=e.slice(0,r),d=!0):(t=e.slice(0,r+1),t+=u);return n.side1TiebreakScore=m[0]||0,n.side2TiebreakScore=m[1]||0,{newScore:t,isIncompleteScore:d}}function cK({lastSet:t,sets:e,analysis:r}){let n=t.side1Score?.toString();if(n){let i=n?.slice(0,-1);t.side1Score=Number.parseInt(i)&&!Number.isNaN(Number.parseInt(i))||void 0,t.side1Score===void 0&&(t.side2Score=void 0)}let o;return r.isTimedSet?(o=t.side1Score?e:e?.slice(0,-1)??[],o[e.length-1]=t):o=e?.slice(0,-1)??[],o}function uK({lastSet:t,sets:e,analysis:r}){let n=t.side2Score?.toString(),o=t.side1Score?.toString();if(!r.isTiebreakEntry&&!r.isMatchTiebreak)if(t.side2Score){let s=n?.slice(0,-1);t.side2Score=!isNaN(s)&&parseInt(s)||void 0}else{let s=o?.slice(0,-1);t.side1Score=!isNaN(s)&&parseInt(s)||void 0}let i;return r.isTimedSet?t.side1Score?(i=e??[],i[e.length-1]=t):i=e?.slice(0,e.length-1)??[]:(i=e??[],i[e.length-1]=t),i[i.length-1]&&Object.assign(i[i.length-1],{winningSide:void 0}),i}function QS({analysis:t,scoreString:e,sets:r,lowSide:n}){let o,i;if(!e)return{scoreString:e,sets:r};let{scoreString:s,removed:a}=Ek({scoreString:e});if(e=s,a)return{scoreString:e,sets:r,outcomeRemoved:!0};let c=r.at(-1)??{},u=Object.values(c).filter(g=>g!==void 0).length;c.setNumber&&u===1&&(r=r.slice(0,-1),c=r.at(-1)??{});let{tiebreakSet:p}=t.setFormat,{tiebreakTo:m,NoAD:d}=p??{},{isTiebreakEntry:l}=Jp({brackets:ea,scoreString:e}),f=pK(e);if(f>=0){o=e.slice(0,f);let{isTiebreakEntry:g}=Jp({brackets:ta,scoreString:o}),{lastOpenBracketIndex:I,isTiebreakEntry:S}=Jp({brackets:ea,scoreString:o}),h=o?.length?o[o.length-1].trim():void 0,T=o&&!isNaN(h),y=t.isIncompleteSetScore;return l&&S&&({newScore:o,isIncompleteScore:y}=aK({newScore:o,scoreString:e,lastMatchTiebreakOpenBracketIndex:I,lastSet:c,lowSide:n,NoAD:d,tiebreakTo:m})),o.length||(o=void 0),y?i=cK({lastSet:c,sets:r,analysis:t}):T?i=uK({lastSet:c,sets:r,analysis:t}):g?(i=r??[],Object.assign(i[i.length-1]??{},{winningSide:void 0,side1TiebreakScore:void 0,side2TiebreakScore:void 0})):(l&&!S?i=r?.slice(0,-1)??[]:(i=r,i[r.length-1]=c),l||(i[i.length-1].side2Score=0,i[i.length-1].winningSide=void 0)),{scoreString:o,sets:i}}return{scoreString:e,sets:r}}function Jp({brackets:t=ta,scoreString:e}){if(!e)return{};let[r,n]=t.split(""),o=e.split(""),i=Math.max(...os(r,o)),s=Math.max(...os(n,o));return{isTiebreakEntry:i>s,lastOpenBracketIndex:i}}function Ak({scoreString:t}){if(!t)return!1;let e=t?.[t.length-1].trim(),r=t&&!isNaN(e),[n,o]=ea.split(""),i=t.split(""),s=Math.max(...os(n,i)),a=Math.max(...os(o,i)),c=Math.max(...os(Ui,i));return r&&s>a&&c>s}function pK(t){return t.split("").reduce((n,o,i)=>(o.match(/\d+/g)&&n.push(i),n),[]).pop()}function kA(t){let{lowValue:e=0,NoAD:r=!1,tiebreakTo:n}=t??{},o=r?1:2;return e+1>=n?e+o:parseInt(n)}function IM({matchUpFormat:t,matchUpStatus:e,winningSide:r,sets:n}){let o=oe(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 Ik.includes(e)&&r&&(c=r),{matchUpWinningSide:c}}function Td({ignoreTiebreak:t=!1,matchUpScoringFormat:e,matchUpFormat:r,isTiebreakSet:n,isDecidingSet:o,isTimedSet:i,set:s}){if(!s)return{error:nt,info:"missing set"};e=e||r&&oe(r);let a=o&&e.finalSetFormat||(e?.setFormat??{}),{side1Score:c,side2Score:u}=s,{setTo:p,tiebreakAt:m}=a,d=c||u,l=yd({set:s}),f=Math.abs(c-u),g=c>=p||u>=p,I=n||c>=p&&u>=p||m&&m<p&&(c===m||u===m),S=t||I&&(l===1&&s.side1TiebreakScore>s.side2TiebreakScore||l===2&&s.side2TiebreakScore>s.side1TiebreakScore),h=!I&&a.NoAD||I||n&&a.tiebreakFormat?.NoAD?1:2,T=f>=h;return!!((i&&d||g&&(T||I)||n)&&(!I||S))}function yd({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 vf({analysis:t,set:e}){let r=yd({set:e}),{isDecidingSet:n,isTiebreakSet:o,matchUpScoringFormat:i}=t;return Td({matchUpScoringFormat:i,isDecidingSet:n,isTiebreakSet:o,set:e})&&r}function Pk({analysis:t,scoreString:e,sets:r,value:n}){let o;if(!r?.length)return{sets:[]};let i=r[r.length-1];n=st(n);let{validSide2Score:s,requiresTiebreak:a}=mK({analysis:t,set:i,value:n});if(s){o=!0,e=(e||"")+n,i.side2Score=n;let c=vf({analysis:t,set:r[r.length-1]});if(i.winningSide=c||void 0,a){let u=ta.split("")[0];e+=u}else t.isDecidingSet||(e+=" ")}return{sets:r,scoreString:e,updated:o}}function mK({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 GA({lowSide:t,value:e,sets:r,scoreString:n,winningSide:o,matchUpStatus:i}){let s;return e===aM?n?(s=!0,n=hd({scoreString:n,lowSide:t,outcome:"RET"}),o=t===2?1:2,i=oM):(s=!0,n=hd({scoreString:n,lowSide:t,outcome:"DEF"}),o=t===2?1:2,i=_A):e===pM?(s=!0,n=hd({scoreString:n,lowSide:t,outcome:"DEF"}),o=t===2?1:2,i=_A):e===mM?(s=!0,r=[],n="WO",o=t===2?1:2,i=nM):e===cM&&n?(s=!0,n=hd({scoreString:n,lowSide:t,outcome:"SUS"}),i=wA,o=void 0):e===uM?(s=!0,n=hd({scoreString:n,lowSide:t,outcome:"ABN"}),i=xA,o=void 0):e===dM&&n&&(s=!0,n=hd({scoreString:n,lowSide:t,outcome:"INT"}),i=LA,o=void 0),{updated:s,sets:r,scoreString:n,matchUpStatus:i,winningSide:o}}function Uk(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!==bf&&(e=[{setNumber:1}]);let m=e.length-1;if(Cf.includes(c))({sets:e,info:r,scoreString:n,winningSide:o,matchUpStatus:i,updated:u}=IK({sets:e,info:r,scoreString:n,winningSide:o,matchUpStatus:i,analysis:s,lowSide:a,value:c}));else if(c===bf)({scoreString:n,sets:e,outcomeRemoved:p}=QS({analysis:s,scoreString:n,sets:e})),{sets:e,scoreString:n,winningSide:o,matchUpStatus:i,updated:u}=SK({sets:e,scoreString:n,outcomeRemoved:p});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"};c===Sd?{sets:e,scoreString:n,updated:u}=hK({sets:e,scoreString:n,winningSide:o,analysis:s}):c===Ba&&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):Number.isNaN(Number(c))||({sets:e,scoreString:n,updated:u}=TK({sets:e,setIndex:m,value:c,scoreString:n}))}return{sets:e,scoreString:n,winningSide:o,matchUpStatus:i,info:r,updated:u}}function IK({sets:t,info:e,scoreString:r,winningSide:n,matchUpStatus:o,analysis:i,lowSide:s,value:a}){let c,u=t.at(-1)??{},{side1Score:p,side2Score:m}=u;return p&&!m?e="missing side2Score":i.finalSetIsComplete||n?e="final set is already complete":i.isIncompleteSetScore?e="incomplete set scoreString":{sets:t,scoreString:r,winningSide:n,matchUpStatus:o,updated:c}=GA({lowSide:s,value:a,sets:t,scoreString:r,matchUpStatus:o,winningSide:n}),{sets:t,info:e,scoreString:r,winningSide:n,matchUpStatus:o,updated:c}}function SK({sets:t,scoreString:e,outcomeRemoved:r}){let n=e,o=t;if(n?.trim()===""&&(n=n.trim()),n||(o=[]),r){let i=o.at(-1)??{},{side1Score:s,side2Score:a}=i;if(s&&a){let c=s>a&&1||a>s&&2||void 0;c&&(i.winningSide=c,o.push({setNumber:o.length+1}))}}return{sets:o,scoreString:n,winningSide:void 0,matchUpStatus:void 0,updated:!0}}function hK({sets:t,scoreString:e,winningSide:r,analysis:n}){let o,i=e,s=t.at(-1)??{},{side1Score:a,side2Score:c}=s,u=a>c&&1||c>a&&2||void 0;return u&&!r&&!n.isIncompleteSetScore&&(t.at(-1).winningSide=u,t.push({setNumber:t.length+1}),i+=" ",o=!0),{sets:t,scoreString:i,updated:o}}function TK({sets:t,setIndex:e,value:r,scoreString:n}){let o,i,s=n;if(t[e].side2Score===void 0){let a=st((t[e].side1Score||0).toString()+r).toString().slice(0,2);t[e].side1Score=st(a),o=t[e].side1Score.toString(),i=!0}else{let a=st((t[e].side2Score||0).toString()+r).toString().slice(0,2);t[e].side2Score=st(a),o=[t[e].side1Score,t[e].side2Score].join("-"),i=!0}if(i){let a=(t.slice(0,e)??[]).filter(c=>c).map(c=>[c.side1Score,c.side2Score].join("-")).join(" ");s=a?a+" "+o:o}return{sets:t,scoreString:s,updated:i}}function Dk({analysis:t,auto:e,lowSide:r,scoreString:n="",sets:o,value:i}){let s,a,{tiebreakSet:{tiebreakTo:c,NoAD:u}}=t.setFormat,[p]=ea.split("");if(t.isMatchTiebreakEntry||(n+=p),o[t.setNumber-1]){let{lastOpenBracketIndex:d}=Jp({brackets:ea,scoreString:n}),f=(n.slice((d??0)+1)+(e?"":i)).split(Ui);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=>st(T)),S=r===1?1:0;I[S]=I[1-S]+(u?1:2),I[S]<c&&(I[S]=c);let h=o[o.length-1];h.side1TiebreakScore=I[0],h.side2TiebreakScore=I[1],n=n.slice(0,(d??0)+1),n+=I.join(Ui),s=!0}else{let I=[f[0]||0,f[1]||0].map(h=>st(h)),S=o[o.length-1];S.side1TiebreakScore=I[0],S.side2TiebreakScore=I[1],n+=i,s=!0}}else{let d=kA({lowValue:st(i||0),tiebreakTo:c,NoAD:u}),l=[st(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(Ui),s=!0}return{info:a,scoreString:n,sets:o,updated:s}}function Rk({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&&!a||n>o)return{scoreString:r};let c=g(),u=[n,c];e===2&&u.reverse();let m=ta.split("")[0],d=u.join(Ba)+(a?m:" ");r=(r||"")+d;let l={side1Score:u[0],side2Score:u[1]},f=vf({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 bk({matchUpFormat:t,scoreString:e,winningSide:r,value:n,sets:o}){let s=(o?.filter(z=>z?.winningSide)?.length||0)+(r?0:1),a=oe(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}=Jp({brackets:ta,scoreString:e}),{isTiebreakEntry:f}=Jp({brackets:ea,scoreString:e}),g=l||f,I=!!u.tiebreakSet,S=e?.[e.length-1]?.trim(),h=e&&!isNaN(S),T=!g&&S===Ba,y=l&&FA.includes(S),E=f&&FA.includes(S),A=f&&S===Ui,N=e?.split(""),[U]=ea.split(""),R=N&&Math.max(...os(U,N)),D=N&&Math.max(...os(Ui,N)),b=N&&D>R,C=o[o.length-1]?.winningSide,_=o?.length&&!C,v=OA.find(z=>e?.indexOf(z)>=0),w=!isNaN(n),L=n===Sd,F=Mf.includes(n),x=e?.split("").find(z=>FA.includes(z)),k=F&&f&&!E&&(A||!Ak({scoreString:e}));return{isTiebreakSetValue:I&&w,matchUpScoringFormat:a,setNumber:s,setFormat:u,matchTiebreakHasJoiner:b,isGameScoreEntry:_,isSpace:L,isCloser:F,isTiebreakCloser:F&&x&&g&&h,isDecidingSet:c,isTiebreakSet:I,isTimedSet:p,isNumericEnding:h,isNumericValue:w,hasOpener:x,hasOutcome:v,finalSet:m,finalSetIsComplete:d,lastSetIsComplete:C,isInvalidSetTiebreakValue:L&&g&&y,isInvalidMatchTiebreakValue:k,isTiebreakEntry:g,isSetTiebreakEntry:l,isMatchTiebreakEntry:f,isIncompleteSetScore:T,isIncompleteSetTiebreak:y,isIncompleteMatchTiebreak:E,isPartialMatchTiebreakValue:A}}function yK({analysis:t,lowSide:e,sets:r,scoreString:n,matchUpStatus:o,winningSide:i,value:s}){let a,c;return t.finalSetIsComplete||i?a="final set is already complete":!t.isTiebreakEntry&&!t.isIncompleteSetScore?{sets:r,scoreString:n,matchUpStatus:o,winningSide:i,updated:c}=GA({lowSide:e,sets:r,scoreString:n,matchUpStatus:o,winningSide:i,value:s}):t.isTiebreakEntry||t.isIncompleteSetScore?a="incomplete set scoreString or tiebreak entry":console.log("handle case",{value:s}),{info:a,sets:r,scoreString:n,matchUpStatus:o,winningSide:i,updated:c}}function EK({analysis:t,scoreString:e,sets:r,lowSide:n}){return{scoreString:e,sets:r}=QS({analysis:t,scoreString:e,sets:r,lowSide:n}),e||(r=[]),{scoreString:e,sets:r,updated:!0,matchUpStatus:void 0,winningSide:void 0}}function AK({analysis:t,scoreString:e,sets:r,lowSide:n}){let o,i;return(!t.isSetTiebreakEntry||t.isSetTiebreakEntry&&!t.isNumericEnding)&&(o=!0,{scoreString:e,sets:r}=QS({analysis:t,scoreString:e,sets:r,lowSide:n}),i=void 0),{scoreString:e,sets:r,updated:o,matchUpStatus:i}}function PK({analysis:t,scoreString:e}){let r,n;return t.matchTiebreakHasJoiner?r="existing joiner":t.isNumericEnding&&(n=!0,e+=Ui),{info:r,scoreString:e,updated:n}}function NK({analysis:t,scoreString:e,sets:r}){let n=t.isSetTiebreakEntry?ta:ea,o=n.split("").reverse()[0],i=n.split("")[0],s=r[r.length-1],{tiebreakFormat:a}=t.setFormat,{tiebreakTo:c,NoAD:u}=a??{},p=yd({set:s});if(!t.isTiebreakSet){let d=Number.parseInt(e.split(i).reverse()[0]),l=kA({lowValue:d,tiebreakTo:c,NoAD:u});p===1?(s.side1TiebreakScore=l,s.side2TiebreakScore=d):(s.side1TiebreakScore=d,s.side2TiebreakScore=l)}e=(e||"")+o,t.isDecidingSet||(e+=" ");let m=vf({analysis:t,set:s});return s.winningSide=m||void 0,{scoreString:e,sets:r,updated:!0}}function UK({analysis:t,scoreString:e,value:r}){let n,o,[i]=ta.split(""),s=Math.max(...os(i,e.split(""))),a=e.slice(s+1),c=a&&st(a)===hk,u=st(a?a+r:r),{tiebreakFormat:p}=t.setFormat,{tiebreakTo:m,NoAD:d}=p??{};return!c&&a.length<2?d&&u>m-1?n="invalid low value for NoAD tiebreak":(o=!0,e=(e||"")+r):n=c?"tiebreak begins with zero":"tiebreak digit limit",{info:n,scoreString:e,updated:o}}function DK({analysis:t,lowSide:e,scoreString:r,sets:n,value:o}){let{scoreString:i,set:s}=Rk({analysis:t,lowSide:e,scoreString:r,value:st(o)});return s&&(s.setNumber=n?.length+1||1),n=n?.concat(s).filter(Boolean)||[s],r=i||void 0,{scoreString:r,sets:n,updated:!0}}function RK({sets:t,winningSide:e,matchUpStatus:r,matchUpFormat:n,scoreString:o,info:i}){t=t?.filter(Boolean);let{matchUpWinningSide:s}=IM({sets:t,winningSide:e,matchUpStatus:r,matchUpFormat:n});return e=s,s&&(!r||[zt,Xr].includes(r))?(r=gk,t=t.filter(a=>{let{side1Score:c,side2Score:u,side1TiebreakScore:p,side2TiebreakScore:m}=a;return c||u||p||m})):o&&!e&&![wA,xA,LA].includes(r)&&(r=void 0),{updated:!0,scoreString:o,sets:t,winningSide:e,matchUpStatus:r,info:i}}function hM(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;if(!gM.includes(r))return{updated:!1,info:"invalid key"};c&&(e=3-e);let p=c&&e===2||!c&&e===1,{matchUpWinningSide:m}=IM({sets:o,winningSide:i,matchUpStatus:s,matchUpFormat:a});i=m;let d=bk({value:r,winningSide:i,scoreString:n,sets:o,matchUpFormat:a});({value:r,scoreString:n}=bK({analysis:d,value:r,scoreString:n,isShifted:p}));let l=CK({analysis:d,lowSide:e,sets:o,scoreString:n,matchUpStatus:s,winningSide:i,value:r,auto:u});if(l.earlyReturn)return{updated:l.updated,info:l.info};({sets:o,scoreString:n,matchUpStatus:s,winningSide:i}=l);let{updated:f,info:g}=l;return f?RK({sets:o,winningSide:i,matchUpStatus:s,matchUpFormat:a,scoreString:n,info:g}):{updated:f,scoreString:n,sets:o,winningSide:i,matchUpStatus:s,info:g}}function bK({analysis:t,value:e,scoreString:r,isShifted:n}){let o=e,i=r;if(lM.includes(o)&&(o=Ba),t.hasOpener&&t.isTiebreakEntry&&!t.isTiebreakSet&&n&&st(o)===0&&(t.isTiebreakCloser=!0),Mf.includes(o)&&t.hasOpener&&(o=""),Mf.includes(o)&&(o=Sd),t.lastSetIsComplete){let s=i?.length&&i.at(-1);i&&s!==" "&&(i+=" ")}return{value:o,scoreString:i}}function CK({analysis:t,lowSide:e,sets:r,scoreString:n,matchUpStatus:o,winningSide:i,value:s,auto:a}){let c,u,p=r,m=n,d=o,l=i;if(t.isTimedSet)({info:c,sets:p,scoreString:m,updated:u,matchUpStatus:d,winningSide:l}=Uk({analysis:t,lowSide:e,scoreString:n,sets:r,matchUpStatus:o,winningSide:i,value:s}));else if(Cf.includes(s))({info:c,sets:p,scoreString:m,matchUpStatus:d,winningSide:l,updated:u}=yK({analysis:t,lowSide:e,sets:r,scoreString:n,matchUpStatus:o,winningSide:i,value:s}));else if(s===bf)({scoreString:m,sets:p,updated:u,matchUpStatus:d,winningSide:l}=EK({analysis:t,scoreString:n,sets:r,lowSide:e}));else if(t.hasOutcome)c="has outcome";else if(s===Ba&&!t.isMatchTiebreakEntry)({scoreString:m,sets:p,updated:u,matchUpStatus:d}=AK({analysis:t,scoreString:n,sets:r,lowSide:e}));else if(s===Ui&&t.isMatchTiebreakEntry&&!t.isSetTiebreakEntry)({info:c,scoreString:m,updated:u}=PK({analysis:t,scoreString:n}));else if([Ba,Ui].includes(s))c="invalid location for joiner";else{if(i)return{earlyReturn:!0,updated:!1,info:"matchUp is complete"};({info:c,updated:u,sets:p,scoreString:m}=MK({analysis:t,auto:a,lowSide:e,scoreString:n,sets:r,value:s}))}return{info:c,updated:u,sets:p,scoreString:m,matchUpStatus:d,winningSide:l}}function MK({analysis:t,auto:e,lowSide:r,scoreString:n,sets:o,value:i}){let s,a,c=o,u=n;return t.isIncompleteSetScore?t.isNumericValue&&({sets:c,scoreString:u,updated:a}=Pk({analysis:t,scoreString:n,sets:o,value:i})):t.isInvalidMatchTiebreakValue?s="invalid matchUp tiebreak character":t.isInvalidSetTiebreakValue?s="invalid set tiebreak character":t.isTiebreakCloser?{scoreString:u,sets:c,updated:a}=NK({analysis:t,scoreString:n,sets:o}):t.isTiebreakSetValue?{info:s,scoreString:u,sets:c,updated:a}=Dk({analysis:t,auto:e,lowSide:r,scoreString:n,sets:o,value:i}):t.isSetTiebreakEntry?{info:s,scoreString:u,updated:a}=UK({analysis:t,scoreString:n,value:i}):t.isCloser?s=`invalid key: ${i}`:t.isGameScoreEntry?s="game scoreString entry":t.lastSetIsComplete||!o.length?{scoreString:u,sets:c,updated:a}=DK({analysis:t,lowSide:r,scoreString:n,sets:o,value:i}):console.log("error: unknown outcome"),{info:s,updated:a,sets:c,scoreString:u}}var AM={};Gt(AM,{analyzeScore:()=>XS,analyzeSet:()=>Zp,calculateMatchStatistics:()=>Df,checkScoreHasValue:()=>ue,checkSetIsComplete:()=>Td,deduceMatchUpFormat:()=>Nd,enrichPointHistory:()=>zC,getEpisodes:()=>HS,getQuickStats:()=>QC,getScore:()=>Zi,getScoreboard:()=>BS,getSetComplement:()=>ZS,getTiebreakComplement:()=>Ad,getWinner:()=>YS,isComplete:()=>WS,isValidMatchUpFormat:()=>vr,parseScoreString:()=>Pd,toStatObjects:()=>Rf,validateMatchUpScore:()=>yM,validateScore:()=>JS,validateSetScore:()=>VA,validateTieFormat:()=>or});function vK(t,e,r,n,o,i=!1){return o?{isValid:!0}:t===0&&e===0?{isValid:!1,error:"Tiebreak-only set requires both scores"}:t<n?{isValid:!1,error:`Tiebreak-only set winner must reach at least ${n}, got ${t}`}:r<(i?1:2)?{isValid:!1,error:i?`Tiebreak-only set (NoAD) must be won by at least 1 point, got ${t}-${e}`:`Tiebreak-only set must be won by at least 2 points, got ${t}-${e}`}:i?{isValid:!0}:t===n&&e>n-2?{isValid:!1,error:`Tiebreak-only set at ${n}-${e} requires playing past ${n}`}:t>n&&r!==2?{isValid:!1,error:`Tiebreak-only set past ${n} must be won by exactly 2 points, got ${t}-${e}`}:{isValid:!0}}function OK(t,e,r,n){let o=n===r?r+1:r,i=n;return t!==o?{isValid:!1,error:`Tiebreak set winner must have ${o} games, got ${t}`}:e!==i?{isValid:!1,error:`Tiebreak set loser must have ${i} games, got ${e}`}:{isValid:!0}}function _K(t,e,r){let n=Math.max(t||0,e||0),o=Math.min(t||0,e||0),i=n-o,s=r.tiebreakTo||7;return n<s?{isValid:!1,error:`Tiebreak winner must reach ${s} points, got ${n}`}:i<2?{isValid:!1,error:`Tiebreak must be won by 2 points, got ${n}-${o}`}:o>=s-1&&i>2?{isValid:!1,error:`Tiebreak score ${n}-${o} is invalid`}:{isValid:!0}}function xK(t,e,r,n){return n?t===r+1&&e<r-1?{isValid:!1,error:`With tiebreak format, if side 1 has ${r+1} games, side 2 must be at least ${r-1}, got ${e}`}:e===r+1&&t<r-1?{isValid:!1,error:`With tiebreak format, if side 2 has ${r+1} games, side 1 must be at least ${r-1}, got ${t}`}:{isValid:!0}:{isValid:!0}}function wK(t,e,r,n,o){if(t<n)return{isValid:!1,error:`Set winner must reach ${n} games, got ${t}`};let i=o&&t===n&&e===o&&r===1;if(r<2&&!i)return{isValid:!1,error:`Set must be won by at least 2 games, got ${t}-${e}`};if(o){if(e>=o&&!i)return{isValid:!1,error:`When tied at ${o}-${o}, must play tiebreak. Use format like ${o+1}-${o}(5)`};let s=o===n?n+1:n;if(t>s)return{isValid:!1,error:`With tiebreak format, set score cannot exceed ${s}-${o}. Got ${t}-${e}`}}else if(t>n+10)return{isValid:!1,error:`Set score ${t}-${e} exceeds reasonable limits`};return{isValid:!0}}function LK(t,e,r){let n=t.side1TiebreakScore,o=t.side2TiebreakScore,i=e&&r?n:t.side1Score||t.side1||0,s=e&&r?o:t.side2Score||t.side2||0;return{side1Score:i,side2Score:s,side1TiebreakScore:n,side2TiebreakScore:o}}function FK(t,e,r,n,o,i,s){if(r&&n){let c=OK(t,e,r,n);if(!c.isValid)return c}return(o!==void 0||i!==void 0)&&s?_K(o,i,s):{isValid:!0}}function kK(t,e,r){return r&&(t>r+10||e>r+10)?{isValid:!1,error:`Set score ${t}-${e} exceeds expected range for ${r}-game sets`}:{isValid:!0}}function GK(t,e,r){let{side1:n,side2:o,winner:i,loser:s,diff:a}=t,{setTo:c,tiebreakAt:u}=e;if(c&&u){let p=xK(n,o,c,u);if(!p.isValid)return p}return r?kK(i,s,c):c?wK(i,s,a,c,u):{isValid:!0}}function VA(t,e,r,n){if(!e)return{isValid:!0};let o=oe(e);if(!o)return{isValid:!0};let i=r&&o.finalSetFormat?o.finalSetFormat:o.setFormat;if(!i)return{isValid:!0};if(i.timed){if(!n){let N=t.side1Score??0,U=t.side2Score??0;if(N===0&&U===0)return{isValid:!1,error:"Timed set requires at least one side to have scored"};if(i.based==="P"&&N===U&&N>0&&i.tiebreakFormat&&!(t.side1TiebreakScore!==void 0||t.side2TiebreakScore!==void 0))return{isValid:!1,error:"Tied timed set requires tiebreak"}}return{isValid:!0}}let{setTo:s,tiebreakAt:a,tiebreakFormat:c,tiebreakSet:u}=i,p=u?.tiebreakTo,m=!!p&&!s,d=t.side1TiebreakScore!==void 0&&t.side2TiebreakScore!==void 0,{side1Score:l,side2Score:f,side1TiebreakScore:g,side2TiebreakScore:I}=LK(t,m,d),S=Math.max(l,f),h=Math.min(l,f),T=S-h;if(m){let N=t.NoAD??i.tiebreakSet?.NoAD??!1;return vK(S,h,T,p,n??!1,N)}let y=g!==void 0||I!==void 0,E=s&&S===s+1&&h===s;return y||E?FK(S,h,s,a,g,I,c):GK({side1:l,side2:f,winner:S,loser:h,diff:T},{setTo:s,tiebreakAt:a},n)}function yM(t,e,r){if(!t||t.length===0)return{isValid:!0};let n=e?.match(/SET(\d+)/)?.[1],o=n?Number.parseInt(n):3,i=[Ue,Lt,xt].includes(r||"");for(let s=0;s<t.length;s++){let a=t[s],c=s+1===o,u=a.winningSide!==void 0,d=VA(a,e,c,i||r===void 0&&!u);if(!d.isValid)return{isValid:!1,error:`Set ${s+1}: ${d.error}`}}return{isValid:!0}}function Ed(t){return!!t?.aggregate}function VK(t,e,r,n,o,i){let{tiebreakTo:s,NoAD:a}=t??{},c=Math.max(e??0,r??0);return!(a&&c>s||c<s&&n&&(o&&!i||!o))}function BK(t,e,r,n,o,i){let a=e+1===n,{side1Score:c,side2Score:u,side1TiebreakScore:p,side2TiebreakScore:m,winningSide:d}=t,l=Math.max(c??0,u??0),f=p??m,{finalSetFormat:g,setFormat:I}=r,S=a&&g||I;return f&&!VK(S?.tiebreakFormat,p,m,d,o,i)?!1:S.setTo?!(!S.noTiebreak&&l>S.setTo+1):!0}function HK(t){let e=t.reduce((r,n)=>((n.side1Score!==void 0||n.side2Score!==void 0)&&(r[0]+=n.side1Score??0,r[1]+=n.side2Score??0),r),[0,0]);return e[0]>e[1]?1:e[1]>e[0]?2:t.find(n=>n.side1TiebreakScore!==void 0||n.side2TiebreakScore!==void 0)?.winningSide}function WK(t,e,r,n,o){return(!o||t===e)&&r===1&&n.indexOf(t)+1||void 0}function XS({existingMatchUpStatus:t,matchUpFormat:e,matchUpStatus:r,winningSide:n,score:o}){let i=o?.sets??[],a=(i?.filter(D=>D?.winningSide)??[]).reduce((D,b)=>{let{winningSide:C}=b;if(!C)return D;let _=C-1;return D[_]++,D},[0,0]),c=n?n-1:void 0,u=c!==void 0&&[0,1].includes(c)?1-c:void 0,p=c!==void 0&&a[c],m=u!==void 0&&a[u],d=e?oe(e):void 0,l=Math.max(...a),f=mn(a)[l],g=d?.setFormat?.timed||d?.finalSetFormat?.timed,I=d?.bestOf||d?.exactly,S=I&&Math.ceil(I/2)||1,h=r??t,T=!!(h&&[xt,Ue,Lt].includes(h)),y=!d||!i.length||i.every((D,b)=>BK(D,b,d,I??0,b===i.length-1,T)),E=d?.exactly,A=!E||!h||h!==ie||T||i.length>=E,N=Ed(d),U=N&&i.length>0?HK(i):WK(l,S,f,a,e);return{valid:!!(y&&A&&(n&&N&&n===U||n&&!N&&p>m&&n===U||n&&T||!n&&!U&&(![ie,xt,Ue,Lt].includes(h)||g&&h===ie)))}}function JS({existingMatchUpStatus:t,matchUpFormat:e,matchUpStatus:r,winningSide:n,score:o}){if(typeof o!="object")return{error:O};let{sets:i,scoreStringSide1:s,scoreStringSide2:a}=o,c="scoreString must be a string!";if(s!==void 0&&typeof s!="string")return{error:O,info:c};if(a!==void 0&&typeof a!="string")return{error:O,info:c};if(i!==void 0&&!Array.isArray(i))return{error:O,info:Ai("sets")};if(i?.length){let u=i.map(m=>m?.setNumber).filter(Boolean);if(u.length!==pt(u).length)return{error:O,info:"setNumbers not unique"};for(let m of i){let{side1Score:d,side2Score:l,side1TiebreakScore:f,side2TiebreakScore:g,side1PointScore:I,side2PointScore:S,winningSide:h,setNumber:T}=m;if(![[d,l],[f,g]].filter(U=>U.some(R=>![void 0,null].includes(R))).every(U=>U.every(R=>yt(R))))return{error:O,info:"non-numeric values"};let E=[I,S];if(E.some(U=>U!=null)&&!E.every(U=>U!=null))return{error:O,info:"both sides must have point scores if one does"};if(![T,h].filter(U=>![void 0,null].includes(U)).every(U=>yt(U)))return{error:O,info:"non-numeric values"};if(h&&![1,2].includes(h))return{error:O,info:"winningSide must be 1 or 2"}}let{valid:p}=XS({existingMatchUpStatus:t,matchUpStatus:r,matchUpFormat:e,winningSide:n,score:o});if(!p)return{error:zU,info:"score is invalid for matchUpFormat or winningSide does not match calculated winningSide"}}return{valid:!0}}var ZS=t=>{let{isSide1:e,lowValue:r,setTo:n,tiebreakAt:o,NoAD:i}=t;if(r===void 0)return!1;let s=st(r);s?.toString().length>2&&(s=Number.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]},Ad=t=>{let{isSide1:e,lowValue:r,tiebreakTo:n,tiebreakNoAd:o}=t;if(r===void 0)return!1;let i=typeof r=="string"?Number.parseInt(r):r;i?.toString().length>2&&(i=Number.parseInt(i.toString().slice(0,2))),o&&i>n-1&&(i=n-1);let s=YK({lowValue:i,NoAD:o,tiebreakTo:n});return[e?i:s,e?s:i]};function YK(t){let{lowValue:e,NoAD:r,tiebreakTo:n}=t,o=r?1:2;return e+1>=n?e+o:n}function EM(t,e){return t>e&&1||t<e&&2||void 0}function jK(t,e){return e?{side1Score:t[0],side2Score:t[1],winningSide:EM(t[0],t[1])}:{side1TiebreakScore:t[0],side2TiebreakScore:t[1],winningSide:EM(t[0],t[1])}}function Pd({tiebreakTo:t=7,scoreString:e="",matchUpFormat:r}){let n,o=3;if(r)try{n=oe(r);let p=/SET(\d+)/.exec(r)?.[1];o=p?Number.parseInt(p):3}catch{}return e?.split(" ").filter(Boolean).map((p,m)=>u({set:p,setNumber:m+1}));function i(p,m){if(!n||!m)return!1;let l=p===o&&n.finalSetFormat?n.finalSetFormat:n.setFormat;if(!l)return!1;let f=l.tiebreakSet?.tiebreakTo,g=l.setTo;return!!f&&!g}function s(p){if(!n)return t;let d=p===o&&n.finalSetFormat?n.finalSetFormat:n.setFormat;return d?.tiebreakSet?.tiebreakTo??d?.tiebreakFormat?.tiebreakTo??t}function a(p,m,d){let l=p[1],f=s(d),g=Ad({lowValue:l,isSide1:m===2,tiebreakTo:f});return Array.isArray(g)?[g[0],g[1]]:[void 0,void 0]}function c(p,m,d,l){let g=(m&&p.replace(m[0],"")||d&&p.replace(d[0],"")||p).split("-").map(E=>Number.parseInt(E)),I=g[0],S=g[1],h=EM(I,S),T,y;if(m&&([T,y]=a(m,h,l)),d){let E=d[1].split("-").map(A=>Number.parseInt(A));T=E[0],y=E[1]}return{side1Score:I,side2Score:S,side1TiebreakScore:T,side2TiebreakScore:y,winningSide:h}}function u({set:p,setNumber:m}){let d=/\(([^)]+)\)/,l=/\[([^\]]+)\]/,f=d.exec(p),g=l.exec(p),I=p?.startsWith("[")&&g,S=i(m,!!I),h=s(m),T=S&&h===1,y;if(I){let E=g[1].split("-").map(A=>Number.parseInt(A));y=jK(E,S)}else y=c(p,f,g,m);return{side1Score:y.side1Score,side2Score:y.side2Score,side1TiebreakScore:y.side1TiebreakScore,side2TiebreakScore:y.side2TiebreakScore,winningSide:y.winningSide,setNumber:m,...T&&{NoAD:!0},...S&&{tiebreakSet:!0}}}}function Ck({matchUpScoringFormat:t,isDecidingSet:e,isTiebreakSet:r,isTimedSet:n,setObject:o}){if(!o)return;let i=yd({set:o});return Td({matchUpScoringFormat:t,set:o,isDecidingSet:e,isTiebreakSet:r,isTimedSet:n})&&i||void 0}function Zp(t){let{setObject:e,matchUpScoringFormat:r}=t;if(!e)return{error:Bg};let{setNumber:n}=e??{},{bestOf:o,exactly:i}=r??{},s=o||i,a=!!(n&&s&&n===s),c=a&&r?.finalSetFormat||r?.setFormat,u=!!c?.tiebreakSet,p=!!c?.timed,m=!u&&!p,d=!!(n&&s&&n<=s),l=qK(e),{sideGameScores:f,sidePointScores:g,sideTiebreakScores:I}=l,S=f.filter(k=>k!==void 0).length,h=g.filter(k=>k!==void 0).length,T=I.filter(k=>k!==void 0).length,y=f?.filter(k=>typeof k=="number"&&!Number.isNaN(k)).length,E=I?.filter(k=>typeof k=="number"&&!Number.isNaN(k)).length,{tiebreakAt:A}=c??{},N=A&&f.filter(k=>k>=A).length===2,U=$K(N,f),R=!!(E&&!y),D=!!e?.winningSide,{error:b,result:C}=QK({sideTiebreakScores:I,sideGameScores:f,setFormat:c,setObject:e}),{error:_,result:v}=JK({sideTiebreakScores:I,setObject:e,setFormat:c}),w=KK({isValidStandardSetOutcome:C,isValidTiebreakSetOutcome:v,expectStandardSet:m,expectTiebreakSet:u,expectTimedSet:p,isTiebreakSet:R}),L=d&&!(u&&!R)&&!(m&&R)&&(!D||w),F=Ck({isTimedSet:p,matchUpScoringFormat:r,isDecidingSet:a,isTiebreakSet:R,setObject:e}),x={expectTiebreakSet:u,expectTimedSet:p,hasTiebreakCondition:N,isCompletedSet:D,isDecidingSet:a,isTiebreakSet:R,isValidSet:L,isValidSetNumber:d,isValidSetOutcome:w,leadingSide:U,setFormat:c,sideGameScores:f,sideGameScoresCount:S,sidePointScores:g,sidePointScoresCount:h,sideTiebreakScores:I,sideTiebreakScoresCount:T,winningSide:F};return e?.winningSide!==void 0&&zK({isValidStandardSetOutcome:C,isValidTiebreakSetOutcome:v,standardSetError:b,tiebreakSetError:_,isTiebreakSet:R,analysis:x}),x}function qK(t){return{sideGameScores:[t?.side1Score,t?.side2Score],sidePointScores:[t?.side1PointScore,t?.side2PointScore],sideTiebreakScores:[t?.side1TiebreakScore,t?.side2TiebreakScore]}}function $K(t,e){if(t){if(e[0]>e[1])return 1;if(e[1]>e[0])return 2}}function KK({isValidStandardSetOutcome:t,isValidTiebreakSetOutcome:e,expectStandardSet:r,expectTiebreakSet:n,expectTimedSet:o,isTiebreakSet:i}){return r&&!i&&t||n&&i&&e||o}function zK({isValidStandardSetOutcome:t,isValidTiebreakSetOutcome:e,standardSetError:r,tiebreakSetError:n,isTiebreakSet:o,analysis:i}){o?(i.isValidTiebreakSetOutcome=e,e||(i.tiebreakSetError=n)):(i.isValidStandardSetOutcome=t,t||(i.standardSetError=r))}function QK({setObject:t,setFormat:e,sideGameScores:r,sideTiebreakScores:n}){if(!t)return{result:!1,error:Bg};let o=!!e?.tiebreakSet,i=!!e?.timed;if(!e||o||i)return{result:!1,error:O};if(!(r?.filter(R=>typeof R=="number"&&!Number.isNaN(R)).length===2))return{result:!1,error:GT};let{setTo:a,tiebreakAt:c,tiebreakFormat:u,NoAD:p}=e??{};if(!!!(a&&r?.find(R=>R>=a)))return{result:!1,error:GT};let l=new Set([1,2]).has(t?.winningSide);if(!t||!l)return{result:!1,error:nl};let f=t?.winningSide-1,g=1-f,I=r[f],S=r[g],h=I-S;if(!(I>S))return{result:!1,error:{message:"winningSide game scoreString is not high"}};let y=XK({winningSideGameScore:I,sideTiebreakScores:n,winningSideIndex:f,losingSideIndex:g,sideGameScores:r,gamesDifference:h,tiebreakFormat:u,tiebreakAt:c,setTo:a});if(y)return y;let E=c&&r.filter(R=>R>=c).length===2,A=p?1:2,N=S>=a-1;return h&&N&&!E&&h<A?{result:!1,error:{message:"invalid winning game scoreString (3)"}}:h>A&&I>a?{result:!1,error:{message:"invalid winning game scoreString (4)"}}:{result:!0}}function XK({winningSideGameScore:t,sideTiebreakScores:e,winningSideIndex:r,losingSideIndex:n,sideGameScores:o,gamesDifference:i,tiebreakFormat:s,tiebreakAt:a,setTo:c}){if(!(a&&s))return;let p=e?.filter(S=>typeof S=="number"&&!Number.isNaN(S)).length===2,m=e?.[r],d=e?.[n],l=a&&o.filter(S=>S>=a).length===2,{NoAD:f,tiebreakTo:g}=s;if(l){if(i>1)return{result:!1,error:{message:"invalid winning game scoreString (5)"}};if(!p)return{result:!1,error:{message:"invalid tiebreak scores (1)"}};if(typeof g!="number"||Number.isNaN(g))return{result:!1,error:{message:"tiebreakTo error"}};if(!!!(g&&e?.find(N=>N>=g)))return{result:!1,error:{message:"invalid tiebreak scores (2)"}};let h=a<c?c:c+1;if(t>h)return{result:!1,error:{message:"invalid winning game scoreString (1)"}};if(!m||!d||m<d)return{result:!1,error:{message:"winningSide tiebreak value is not high"}};let T=f?1:2,y=m-d,E=d>=g-1;if(y&&E&&y<T)return{result:!1,error:{message:"invalid tiebreak scores (3)"}}}if(t>c&&!l)return{result:!1,error:{message:"invalid winning game scoreString (2)"}}}function JK({setObject:t,setFormat:e,sideTiebreakScores:r}){if(!t)return{result:!1,error:Bg};let n=!!e?.tiebreakSet,o=!!e?.timed;if(!e||!n||o)return{result:!1,error:{message:"not tiebreak set"}};let s=new Set([1,2]).has(t?.winningSide);if(!t||!s)return{result:!1,error:nl};let{tiebreakSet:a}=e??{},{NoAD:c,tiebreakTo:u}=a??{};if(!(r?.filter(y=>typeof y=="number"&&!Number.isNaN(y)).length===2))return{result:!1,error:{message:"invalid tiebreak scores (1)"}};if(Number.isNaN(u))return{result:!1,error:{message:"tiebreakTo error"}};if(!!!r?.find(y=>y>=u))return{result:!1,error:{message:"invalid tiebreak scores (2)"}};let d=t?.winningSide-1,l=1-d,f=r[d],g=r[l];if(!f||!g||f<g)return{result:!1,error:{message:"winningSide tiebreak value is not high"}};let I=c?1:2,S=f-g,h=g>=u-1;return S&&h&&S<I?{result:!1,error:{message:"invalid tiebreak scores (3)"}}:{result:!0}}var Mk="SET3-S:6/TB7";function Nd(t){let e=t.split(/[\s,]+/).filter(s=>s.length>0);if(e.length===0)return Mk;let r=ZK(e.length),n=tz(e,r);if(n)return n;let o=ez(e);if(o===void 0)return Mk;let i=oz(e,o);return iz(r,o,i)}function ZK(t){return t===1?1:t===2?3:5}function BA(t){return t.replaceAll(/\([^)]*\)/g,"").match(/(\d+)/g)?.map(r=>Number.parseInt(r,10))??[]}function tz(t,e){for(let r of t){let n=BA(r);if(n.length===2){let o=Math.max(...n),i=Math.min(...n),s=o-i;if(o===10||o>10&&s<=2)return`SET${e}-S:TB10`}}}function ez(t){let e=t.find(r=>/\(/.test(r));return e?rz(e):nz(t)}function rz(t){let e=BA(t);if(e.length===0)return;let r=Math.max(...e),n=Math.min(...e);return r===n+1?n:r-1}function nz(t){let e=[];for(let n of t){let o=BA(n);o.length>0&&e.push(Math.max(...o))}if(e.length===0)return;let r=Math.max(...e);return r>=6?6:r}function oz(t,e){if(t.length<3)return!1;let r=t.at(-1),n=BA(r);if(n.length!==2)return!1;let o=Math.max(...n),i=Math.min(...n);return o>e+1&&o-i===2}function iz(t,e,r){let n;return e===6?n=`SET${t}-S:6/TB7`:e===4?n=`SET${t}-S:4/TB7`:n=`SET${t}-S:${e}/TB7`,r&&(n+=`-F:${e}`),n}function PM(t){let{matchUp:e,expectedScore:r}=t;if(!e)return{isValid:!1,errors:["No matchUp provided"],warnings:[],actual:{sets:[],scoreString:""},expected:{sets:r?.sets,scoreString:r?.scoreString},pointsProcessed:0,pointsRejected:0};let n=[],o=[],i=Ji({matchUpFormat:e?.matchUpFormat,matchUpId:e?.matchUpId,participants:e?.sides?.map(p=>p.participant).filter(p=>p!==void 0)}),s=e?.history?.points??[];s.length===0&&o.push("No points found to validate");let a=0,c=0;for(let p of s)try{i=Us(i,{winner:p.winner,server:p.server}),a++}catch(m){c++;let d=m instanceof Error?m.message:String(m);n.push(`Point ${p.pointNumber||a+1}: ${d}`)}let u=Zi(i);return r&&(r.sets&&(u.sets.length!==r.sets.length&&n.push(`Set count mismatch: expected ${r.sets.length}, got ${u.sets.length}`),r.sets.forEach((p,m)=>{let d=u.sets[m];if(!d){n.push(`Missing set ${m+1}`);return}p.side1Score!==void 0&&d.side1Score!==p.side1Score&&n.push(`Set ${m+1} side1Score: expected ${p.side1Score}, got ${d.side1Score}`),p.side2Score!==void 0&&d.side2Score!==p.side2Score&&n.push(`Set ${m+1} side2Score: expected ${p.side2Score}, got ${d.side2Score}`),p.side1TiebreakScore!==void 0&&d.side1TiebreakScore!==p.side1TiebreakScore&&n.push(`Set ${m+1} side1TiebreakScore: expected ${p.side1TiebreakScore}, got ${d.side1TiebreakScore}`),p.side2TiebreakScore!==void 0&&d.side2TiebreakScore!==p.side2TiebreakScore&&n.push(`Set ${m+1} side2TiebreakScore: expected ${p.side2TiebreakScore}, got ${d.side2TiebreakScore}`)})),r.scoreString&&u.scoreString!==r.scoreString&&n.push(`Score string mismatch: expected "${r.scoreString}", got "${u.scoreString}"`)),{isValid:n.length===0,errors:n,warnings:o,actual:{sets:u.sets,scoreString:u.scoreString},expected:{sets:r?.sets,scoreString:r?.scoreString},pointsProcessed:a,pointsRejected:c}}function vk(t){let e=t?.side1Score||0,r=t?.side2Score||0;if(t?.side1TiebreakScore!==void 0||t?.side2TiebreakScore!==void 0){let n=t?.side1TiebreakScore||0,o=t?.side2TiebreakScore||0;return e>r?`${e}-${r}(${o})`:`${e}(${n})-${r}`}return`${e}-${r}`}function Ok(t){let{points:e,matchUpFormat:r,expectedGames:n,expectedTiebreak:o}=t,i={matchUpId:"validation",matchUpFormat:r,matchUpStatus:"TO_BE_PLAYED",matchUpType:"SINGLES",sides:[{sideNumber:1},{sideNumber:2}],score:{sets:[]},history:{points:e?.map((s,a)=>({...s,pointNumber:a+1,timestamp:"",winner:s.winner,server:s.server}))}};return PM({matchUp:i,expectedScore:{sets:[{side1Score:n?.[0],side2Score:n?.[1],side1TiebreakScore:o?.[0],side2TiebreakScore:o?.[1]}]}})}function xk(t){let{points:e,expectedScore:r,matchUpFormat:n,allowExtraPoints:o=!1,debug:i=!1}=t,s=[],a=[],c=[],u,p=!1;n?u=n:r?(u=Nd(r),p=!0,i&&console.log(`Deduced format: ${u} from score: ${r}`)):(u="SET3-S:6/TB7",p=!0,a.push("No format provided, using default SET3-S:6/TB7"));let m=Ji({matchUpFormat:u}),d=e?.split("").map(h=>{let T=Number.parseInt(h,10);return Number.isNaN(T)||T!==0&&T!==1?null:T}).filter(h=>h!==null);if(d?.length===0)return s.push("No valid points found in point string"),{valid:!1,errors:s,warnings:a,pointsProcessed:0,pointsRejected:[],actualScore:"0-0",matchUpFormat:u,formatDeduced:p,sets:[]};let l=0;for(let h=0;h<d?.length;h++){let T=d[h];if(m.matchUpStatus==="COMPLETED"&&!o){c.push(T),i&&console.log(`Point ${h+1}: Rejected (match complete)`);continue}try{if(m=Us(m,{winner:T}),l++,i){let y=Zi(m);console.log(`Point ${h+1}: ${T} \u2192 ${y.scoreString}`)}}catch(y){c.push(T);let E=y instanceof Error?y.message:String(y);s.push(`Point ${h+1}: ${E}`),i&&console.log(`Point ${h+1}: Error - ${E}`)}}let f=Zi(m),g=f.scoreString,I=f.sets.map(h=>{let T=[h.side1Score||0,h.side2Score||0],y=h.side1TiebreakScore===void 0?void 0:[h.side1TiebreakScore,h.side2TiebreakScore||0],E=`${T[0]}-${T[1]}`;return y&&(E=T[0]>T[1]?`${T[0]}-${T[1]}(${y[1]})`:`${T[0]}(${y[0]})-${T[1]}`),{games:T,tiebreak:y,scoreString:E}}),S=!0;if(r){let h=_k(r),T=_k(g);h!==T&&(S=!1,s.push(`Score mismatch: expected "${r}", got "${g}"`))}return c.length>0&&a.push(`${c.length} excess points after match complete`),s.length>0&&(S=!1),{valid:S,errors:s,warnings:a,pointsProcessed:l,pointsRejected:c,expectedScore:r,actualScore:g,matchUpFormat:u,formatDeduced:p,sets:I}}function _k(t){return t.replace(/\s+/g,"").replace(/,/g,", ").toLowerCase()}var sz={4:"Wide",5:"Body",6:"T"},wk={f:"Forehand",r:"Forehand Slice",v:"Forehand Volley",o:"Overhead Smash",u:"Forehand Drop Shot",l:"Forehand Lob",h:"Forehand Half-volley",j:"Forehand Drive Volley"},Lk={b:"Backhand",s:"Backhand Slice",z:"Backhand Volley",p:"Backhand Overhead Smash",y:"Backhand Drop Shot",m:"Backhand Lob",i:"Backhand Half-volley",k:"Backhand Drive Volley"},az={t:"Trick Shot",q:"Unknown Shot"},cz={...wk,...Lk,...az},uz={7:"shallow",8:"deep",9:"very deep"},pz={1:1,2:2,3:3},mz={"+":"approach","-":"net","=":"baseline"},Ud={n:"Net",w:"Out Wide",d:"Out Long",x:"Out Wide and Long",g:"Foot Fault",e:"Unknown","!":"Shank"};function dz(t,e){return t.PtWinner===t.Svr?e:1-e}function UM(t){let e=[],r="",n="fbrsvzouymlhijkpqt";for(let i=0;i<t.length;i++){let s=t[i];s&&(n.includes(s)||"456".includes(s)?(r&&e.push(r),r=s):r+=s)}return r&&e.push(r),e}function lz(t){if(t.includes("*"))return"*";if(t.includes("#"))return"#";if(t.includes("@"))return"@"}function Ha(t){if(t){for(let e of Object.keys(Ud))if(t.includes(e))return e}}function fz(t){let e=[];for(let r of t){if(!r)continue;let n=r[0];if(n&&/[456]/.test(n))e.push(r);else break}return e}function DM(t){if(!_t(t))return{serves:[],rally:[]};let e,r,n,o=t.split("c").length-1;t=t.split("c").join("");let i=UM(t),s=i;for(let p=i.length-1;p>=0;p--){let m=i[p];if(m&&(r=lz(m),r)){s=i.slice(0,p+1),n=i.slice(p+1),e=m;break}}let a=fz(s),c=a.length?s.slice(a.length):s;if(!r&&!a.length&&c.length===1){let p=c[0];p&&["S","P","Q","R"].includes(p)&&(e=p,c.length=0)}let u={serves:a,rally:c};return o&&(u.lets=o),r&&(u.terminator=r),e&&(u.result=e),n?.length,u}function RM(t){let e=t.join("|"),r=HA(t[0],1);if(r.winner==="S"||!t[1])return r.serve=1,r.code=e,r;let n=HA(t[1],2);return n.serve=2,n.first_serve={serves:r.serves},r.lets&&(n.first_serve.lets=r.lets),r.error&&(n.first_serve.error=r.error),r.parse_notes&&(n.first_serve.parse_notes=r.parse_notes),n.code=e,n}function HA(t,e){let r=DM(t);if(["Q","S"].includes(r.result||""))return r.winner="S",r;if(["P","R"].includes(r.result||"")||!r.terminator&&!Ha(r.serves[0])&&r.serves.length>2)return r.winner="R",r;let n=(r.serves.length+r.rally.length)%2===0?"R":"S",o;return r.rally.length>0?o=r.rally[r.rally.length-1]:r.serves.length>0&&(o=r.serves[r.serves.length-1]),o?r.rally.length?Iz(r,n,o):gz(r,e):{...r,winner:void 0}}function gz(t,e){if(t.terminator==="*")t.result="Ace",t.winner="S";else if(t.terminator==="#")t.result="Serve Winner",t.winner="S";else{let r=Ha(t.serves[0]);r?(t.error=Ud[r],e===2&&(t.result="Double Fault",t.winner="R")):(t.parse_notes="treated as a fault",e===2&&(t.result="Double Fault",t.winner="R"))}return t}function Iz(t,e,r){if(t.rally.length===1&&r.includes("#")){t.result="Serve Winner",t.winner="S";let n=Ha(r);return n&&(t.error=Ud[n]),t}return r.includes("#")?(t.result="Forced Error",t.error=Ud[Ha(r)],t.winner=e==="R"?"S":"R"):r.includes("*")?(t.result="Winner",t.winner=e):r.includes("@")?(t.result="Unforced Error",t.error=Ud[Ha(r)],t.winner=e==="R"?"S":"R"):Ha(t.serves[0])?t.rally.length===1&&Ha(r)&&(t.error=Ud[Ha(r)],t.winner=e==="R"?"S":"R"):t.serves.length&&t.rally.length?(t.parse_notes="no terminator: receiver wins point",t.result="Unknown",t.winner="R"):t.rally.length===1&&Ha(r)&&(t.error=Ud[Ha(r)],t.winner=e==="R"?"S":"R"),t}function NM(t){if(t)for(let e of t){let r=cz[e];if(r)return r}}function Sz(t){if(t)for(let e of t){let r=sz[e];if(r)return r}}function hz(t,e,r){let n=[],o=1,i=r;if(t.length>0&&!Ha(t[t.length-1])){let s=t[t.length-1],a=NM(s)||"Forehand";n.push({shotNumber:o++,player:i,stroke:a,code:s}),i=1-i}for(let s of e){let a=NM(s);if(!a)continue;let c={shotNumber:o++,player:i,stroke:a,code:s};for(let u of s){let p=pz[u];p!==void 0&&(c.direction=p)}for(let u of s){let p=uz[u];p&&(c.depth=p)}for(let u of s){let p=mz[u];p&&(c.position=p)}n.push(c),i=1-i}return n}function WA(t,e){let r=dz(t,e),n=t["1st"]||"",o=t["2nd"]||"";if(!n&&!o)return{winner:r,server:e,result:"Unknown"};let i=RM([n,o]),s={winner:r,server:e};i.result&&(s.result=i.result),i.serve&&(s.serve=i.serve);let a=i.serve===1?n:o,c=Sz(a);c&&(s.serveLocation=c);let u=i.rally[i.rally.length-1];if(u){let m=NM(u);m&&(s.stroke=m,Object.values(wk).includes(m)?s.hand="Forehand":Object.values(Lk).includes(m)&&(s.hand="Backhand"))}let p=hz(i.serves,i.rally,e);return p.length>0&&(s.rally=p,s.rallyLength=p.length),i.code&&(s.code=i.code),s}function YA(t){if(!t||!_t(t))return[];let e=t.trim().split(`