tods-competition-factory 2.2.3 → 2.2.4
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 oL=Object.defineProperty;var Xt=(t,e)=>{for(var r in e)oL(t,r,{get:e[r],enumerable:!0})};function Va(){return"2.2.3"}var hA={};Xt(hA,{competitionGovernor:()=>DU,drawsGovernor:()=>MN,entriesGovernor:()=>xN,eventGovernor:()=>$N,generationGovernor:()=>ZN,matchUpFormatGovernor:()=>Oy,matchUpGovernor:()=>yM,mocksGovernor:()=>fI,participantGovernor:()=>QM,policyGovernor:()=>nN,publishingGovernor:()=>iR,queryGovernor:()=>DN,reportGovernor:()=>sR,scheduleGovernor:()=>SR,scoreGovernor:()=>Hg,tieFormatGovernor:()=>RR,tournamentGovernor:()=>VR,venueGovernor:()=>QR});var DU={};Xt(DU,{getLinkedTournamentIds:()=>iu,getTournamentIds:()=>hp,linkTournaments:()=>yU,mutate:()=>UU,query:()=>PU,unlinkTournament:()=>EU,unlinkTournaments:()=>AU});var UU={};Xt(UU,{linkTournaments:()=>yU,unlinkTournament:()=>EU,unlinkTournaments:()=>AU});var aa="SINGLES",Ft="SINGLES",vi="DOUBLES",_t="DOUBLES",xr="TEAM",jt="TEAM",sC={SINGLES_MATCHUP:aa,SINGLES:Ft,DOUBLES_MATCHUP:vi,DOUBLES:_t,TEAM_MATCHUP:xr,TEAM:jt};var EI={[Ft]:[Ft,"S"],[_t]:[_t,"D"],[jt]:[jt,"T"],S:[Ft,"S"],D:[_t,"D"],T:[jt,"T"]};function me(t,e){return(t??0)-(e??0)}function pt(t){return typeof t=="number"?parseInt(t.toString()):typeof t=="string"?parseInt(t):0}function vn(t){return isNaN(t)?!1:t&&(t&t-1)===0}function AA(t){if(!t.length)return;let e=[...t].sort(me),r=Math.floor(e.length/2);return e.length%2?e[r]:(e[r-1]+e[r])/2}function aC(t){if(!vn(t))return!1;let e=t,r=1;for(;e!==2;)r+=1,e=e/2;return r}function Sm(t){return isNaN(t)?0:t%2&&t+1||t}function Tm(t){return Math.pow(2,Math.round(Math.log(t)/Math.log(2)))}function Zt(t){return!isNaN(parseFloat(t))}function UI(t){let e=pt(t);if(!isNaN(e))return e===0?!1:(e&-e)===1}function es(t){if(isNaN(t))return!1;for(;!vn(t);)t++;return t}function po(t,e){return t=Math.ceil(t),e=Math.floor(e),Math.floor(Math.random()*(e-t+1))+t}function It(t){return Number.isSafeInteger(typeof t=="string"?+t:t)}function cC(t=1,e=3,r=!0){let n=0;for(let o=0;o<e;o++)n+=Math.random()*(t/e);return r&&t>1?Math.round(n):n}function iL(t,e){e||(e=1);let r=1/e;return Math.round(t*r)/r}function EA(t,e,r,n,o=2){let i=1-Math.random(),s=1-Math.random(),a=Math.sqrt(-2*Math.log(i))*Math.cos(2*Math.PI*s);return a=a/10+.5,a>1||a<0?a=EA(t,e,r):(a=Math.pow(a,r),a*=e-t,a+=t),n&&(a=iL(a,n)),parseFloat(a.toFixed(o))}function _l(t,e=2){return parseFloat(Number(Math.round(t*1e3)/1e3).toFixed(e))}function ut(t){return Array.isArray(t)?t?.filter((e,r,n)=>n.lastIndexOf(e)===r):[]}function uC(t){return Array.isArray(t)?t?.map(e=>e===null?void 0:e):t}function Ir(t){return Array.isArray(t)?t.map(e=>[Math.random(),e]).sort((e,r)=>e[0]-r[0]).map(e=>e[1]):[]}function Ba(t){return It(t)?t:1/0}function Sr(t){return Array.isArray(t)?t.reduce((e,r)=>(e[r]||(e[r]=0),e[r]++,e),{}):{}}function pC(t){return UA(Sr(t))}function UA(t){return Object.keys(t).reduce((e,r)=>{let n=t[r];return e[n]?e[n].push(r):e[n]=[r],e},{})}function sL(t,e,r){return r.indexOf(t)===e}function PI(t){return t.filter(sL)}function tn(t){return Array.isArray(t)&&t.length?t.splice(Math.floor(Math.random()*t.length),1)[0]:void 0}function yn(t){let e=Math.floor(Math.random()*t.length);return t[e]}function et(t,e){return Array.from({length:e-t},(r,n)=>n+t)}function mo(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 PA(t,e){return!Array.isArray(t)||!Array.isArray(e)?[]:t.filter(r=>!e.includes(r))}function Fe(t,e){return!Array.isArray(t)||!Array.isArray(e)?!1:t.some(r=>e.includes(r))}function mC(t,e){return Array.isArray(e)&&e.reduce((r,n)=>(r[n]=1+r[n]||1,r),{})[t]||0}function dC(t,e,r,n){return Array.isArray(t)?[].concat(...t.slice(0,e),...t.slice(e,e+r).sort(n),...t.slice(e+r,t.length)):[]}function Ae(t,e){return Array.isArray(t)?t.reduce((r,n,o)=>{let i=Math.floor(o/e);return r[i]=[].concat(r[i]||[],n),r},[]):[]}function DA(t,[e,...r]){return t.length?[t.slice(0,e),...DA(t.slice(e),[...r,e])]:[]}function lC(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 DI(t){return Array.isArray(t)?t.reduce((e,r)=>!isNaN(parseInt(r))&&e,!0):!1}function NI(t){return Array.isArray(t)?t.reduce((e,r)=>isNaN(parseInt(r))&&e,!0):!1}function xl(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 fC(t,e=1){if(!Array.isArray(t)||!t.every(It))return[];let r=Math.min(...t,e),n=Math.max(...t);return et(r,n+1).filter(o=>!t.includes(o))}function Wr(t){return typeof t=="function"}function Vt(t){return typeof t=="string"}function ht(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function gC(t,e){if(!ht(t)||!ht(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 RI(t,e){return Array.isArray(t)?Object.assign({},...(t??[]).filter(ht).map(r=>r[e]&&{[r[e]]:r}).filter(Boolean)):{}}var IC=t=>e=>Object.keys(t).every(r=>e[r]===t[r]);function MI(t,e){if(t===void 0)return null;if(!ht(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=>MI(i))}:{[o]:e?n(t[o]):MI(t[o])}))}function NA(t){return Array.isArray(t)?t.length+t.map(NA).reduce((e,r)=>e+r,0):ht(t)&&t!==null?Object.keys(t).length+Object.keys(t).map(e=>NA(t[e])).reduce((e,r)=>e+r,0):0}function hC(t){if(t===null||typeof t!="object")return;let e=JSON.stringify(t),r=NA(t),n=e.split("").reduce((o,i)=>o+i.charCodeAt(0),0);return[e.length,r,n].map(o=>o.toString(36)).join("")}function Lc(t,e){return!Array.isArray(t)||!Vt(e)?!1:Yt(t,EI[e]).length}var C={success:!0},MA="error",SC={SUCCESS:C,ERROR:MA};function CI({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!==ut(n).length?(r.push("collectionPositions are not unique"),{errors:r}):{...C}}var bC={};Xt(bC,{addNotice:()=>mt,callListener:()=>Dm,createInstanceState:()=>wE,cycleMutationStatus:()=>cf,deepCopyEnabled:()=>af,deleteNotice:()=>YI,deleteNotices:()=>Fi,disableNotifications:()=>LE,enableNotifications:()=>sf,getDevContext:()=>Pr,getMethods:()=>uf,getNotices:()=>jI,getProvider:()=>qI,getTopics:()=>Lr,getTournamentId:()=>ns,getTournamentRecord:()=>pf,getTournamentRecords:()=>Fo,globalLog:()=>GE,handleCaughtError:()=>ip,hasTopic:()=>np,removeTournamentRecord:()=>kE,setDeepCopy:()=>Hc,setDevContext:()=>Bc,setGlobalLog:()=>MC,setGlobalMethods:()=>RC,setGlobalSubscriptions:()=>LL,setMethods:()=>CC,setStateMethods:()=>VE,setStateProvider:()=>xL,setSubscriptions:()=>FL,setTournamentId:()=>op,setTournamentRecord:()=>FE,setTournamentRecords:()=>Nm,timeKeeper:()=>wL});var bI={message:"Chronological error; time violation.",code:"ANACHRONISM"},ym={message:"Duplicate entry",code:"DUPLICATE_ENTRY"},RA={message:"Cannot remove main structure",code:"ERR_CANNOT_REMOVE_MAIN_STRUCTURE"},vI={message:"records must be an object with tournamentId keys",code:"ERR_INVALID_TOURNAMENTS"},xt={message:"Missing tournamentRecords",code:"ERR_MISSING_TOURNAMENTS"},Y={message:"Missing tournamentRecord",code:"ERR_MISSING_TOURNAMENT"},Ha={message:"Invalid tournamentRecord",code:"ERR_INVALID_TOURNAMENT"},ca={message:"Missing tournamentId",code:"ERR_MISSING_TOURNAMENT_ID"},ua={message:"Invalid drawDefinition",code:"ERR_INVALID_DRAWDEF"},Z={message:"Missing drawDefinition",code:"ERR_MISSING_DRAWDEF"},CA={message:"Existing drawDefinition(s)",code:"ERR_EXISTING_DRAWDEFS"},Rr={message:"drawDefinition not found",code:"ERR_NOT_FOUND_DRAWDEF"},Xo={message:"Invalid structure",code:"ERR_INVALID_STRUCTURE"},wl={message:"Incomplete source structure",code:"ERR_INCOMPLETE_STRUCTURE"},Ll={message:"Invalid drawPosition for seedAssignment",code:"ERR_INVALID_SEEDING_POSITION"},Wa={message:"drawPosition already assigned",code:"ERR_EXISTING_POSITION_ASSIGNMENT"},bA={message:"Schedule not cleared",code:"ERR_UNCHANGED_SCHEDULE_NOT_CLEARED"},vA={message:"drawPosition not cleared",code:"ERR_FAILURE_POSITION_NOT_CLEARED"},aL={message:"drawPosition not found",code:"ERR_NOT_FOUND_DRAW_POSITION"},Fl={message:"Unrecognized drawType",code:"ERR_UNRECOGNIZED_DRAW_TYPE"},ja={message:"Missing drawPositions",code:"ERR_MISSING_DRAW_POSITIONS"},qu={message:"drawPosition is active",code:"ERR_ACTIVE_DRAW_POSITION"},TC={message:"drawPosition is occupied",code:"ERR_OCCUPIED_DRAW_POSITION"},Rs={message:"Invlid drawPosition",code:"ERR_INVALID_DRAW_POSITION"},Cs={message:"Missing drawPosition",code:"ERR_MISSING_DRAW_POSITION"},Am={message:"Invalid drawType",code:"ERR_INVALID_DRAW_TYPE"},$u={message:"Invalid drawSize",code:"ERR_INVALID_DRAW_SIZE"},OI={message:"Cannot set drawSize to be less than existing entries",code:"ERR_INVALID_DRAW_SIZE_MISMATCH"},Ya={message:"Missing drawSize",code:"ERR_MISSING_DRAW_SIZE"},an={message:"Missing drawId",code:"ERR_MISSING_DRAW_ID"},OA={message:"drawId exists",code:"ERR_EXISTING_DRAW_ID"},_A={message:"participantId cannot be assigned to multiple seedNumbers",code:"INVALID_PARTICIPANT_SEEDING"},xA={message:"seedsCount greater than drawSize",code:"ERR_INVALID_SEED_COUNT"},wA={message:"Missing seedCountThresholds",code:"ERR_MISSING_SEED_COUNT_THRESHOLD"},LA={message:"Invalid action",code:"ERR_INVALID_ACTION"},_I={message:"Invalid assignment",code:"ERR_INVALID_ASSIGNMENT"},FA={message:"Missing seedAssignments",code:"ERR_MISSING_SEED_ASSIGNMENTS"},kA={message:"Invalid seedNumber",code:"ERR_INVALID_SEED_NUMBER"},GA={message:"Invalid seedPosition",code:"ERR_INVALID_SEED_POSITION"},kl={message:"Missing targetLink",code:"ERR_MISSING_LINK_TARGET"},VA={message:"Existing round",code:"ERR_EXISTING_ROUND"},cL={message:"Missing roundNumber",code:"ERR_MISSING_ROUND_NUMBER"},Ur={message:"Missing structureId",code:"ERR_MISSING_STRUCTURE_ID"},kt={message:"structure not found",code:"ERR_NOT_FOUND_STRUCTURE"},Gl={message:"Missing structures",code:"ERR_MISSING_STRUCTURES"},mi={message:"Missing structure",code:"ERR_MISSING_STRUCTURE"},BA={message:"drawDefinition contains unlinked structures",code:"ERR_MISSING_STRUCTURE_LINKS"},Hn={message:"Invalid eventType",code:"ERR_INVALID_EVENT_TYPE"};var vt={message:"Missing event / eventId",code:"ERR_MISSING_EVENT_ID"},jr={message:"Event not found",code:"ERR_NOT_FOUND_EVENT"},HA={message:"Event exists",code:"ERR_EXISTING_EVENT"},WA={message:"Missing entries",code:"ERR_MISSING_ENTRIES"},jA={message:"Invalid entries",code:"ERR_INVALID_ENTRIES"},Vl={message:"Missing assignments",code:"ERR_MISSING_ASSIGNMENTS"},YA={message:"Missing stage",code:"ERR_MISSING_STAGE"},Oi={message:"Invalid stage",code:"ERR_INVALID_STAGE"},qA={message:"stageSequence limit",code:"ERR_LIMIT_STAGE_SEQUENCE"},$A={message:"Missing positionAssignments",code:"ERR_MISSING_POSITION_ASSIGNMENTS"},KA={message:"Cannot Assign BYE status if no assignment: { bye: true }",code:"ERR_UNCHANGED_CANNOT_ASSIGN_BYE"},xI={message:"Unrecognized matchUpStatus",code:"ERR_UNRECOGNIZED_MATCHUP_STATUS"},qa={message:"Unrecognized matchUpFormat",code:"ERR_UNRECOGNIZED_MATCHUP_FORMAT"},Bl={message:"Incompatible matchUpStatus",code:"ERR_INCOMPATIBLE_MATCHUP_STATUS"},pa={message:"Invalid matchUpStatus",code:"ERR_INVALID_MATCHUP_STATUS"},Lo={message:"Invalid tieFormat",code:"ERR_INVALID_TIE_FORMAT"},Hl={message:"Invalid matchUpFormat",code:"ERR_INVALID_MATCHUP_FORMAT"},Wl={message:"Missing matchUpFormat",code:"ERR_MISSING_MATCHUP_FORMAT"},zA={message:"Missing collectionDefinition",code:"ERR_MISSING_COLLECTION_DEFINITION"},bs={message:"Missing tieFormat",code:"ERR_MISSING_TIE_FORMAT"},sr={message:"Missing matchUpId",code:"ERR_MISSING_MATCHUP_ID"},rs={message:"Missing matchUpIds",code:"ERR_MISSING_MATCHUP_IDS"},Le={message:"matchUp not found",code:"ERR_NOT_FOUND_MATCHUP"},Jn={message:"Missing matchUps",code:"ERR_MISSING_MATCHUPS"},hr={message:"Missing matchUp",code:"ERR_MISSING_MATCHUP"},dr={message:"Invalid matchUp",code:"ERR_INVALID_MATCHUP"},wI={message:"Missing policyType",code:"ERR_MISSING_POLICY_TYPE"},Ku={message:"Missing policyDefinitions",code:"ERR_MISSING_POLICY_DEFINITIONS"},uL={message:"Missing seeding policy",code:"ERR_MISSING_POLICY_SEEDING"},QA={message:"Missing avoidance policy",code:"ERR_MISSING_POLICY_AVOIDANCE"},LI={message:"Missing policy attributes",code:"ERR_MISSING_POLICY_ATTRIBUTES"},XA={message:"Invalid policyDefinitions",code:"ERR_INVALID_POLICY_DEFINITIONS"},FI={message:"existing policyType",code:"ERR_EXISTING_POLICY_TYPE"},pL={message:"Policy not attached",code:"ERR_FAILURE_POLICY_NOT_ATTACHED"},Fc={message:"Policy not found",code:"ERR_NOT_FOUND_POLICY"},mL={message:"Missing scoring policy / matchUpFormats",code:"ERR_MISSING_POLICY_SCORING_MATCHUP_FORMATS"},jl={message:"Invalid sideNumber",code:"ERR_INVALID_SIDE_NUMBER"},dL={message:"Invalid setNumber",code:"ERR_INVALID_SET_NUMBER"},Yl={message:"Missing setObject",code:"ERR_MISSING_SET_ATTRIBUTE"},lL={message:"Missing setNumber",code:"ERR_MISSING_SET_NUMBER"},fL={message:"Missing sideNumber",code:"ERR_MISSING_SIDE_NUMBER"},_i={message:"Missing courtId",code:"ERR_MISSING_COURT_ID"},st={message:"Missing value",code:"ERR_MISSING_VALUE"},JA={message:"Missing birthdate",code:"ERR_MISSING_BIRTH_DATE"},ZA={message:"Missing date",code:"ERR_MISSING_DATE"},tE={message:"No valid dates",code:"ERR_NO_VALID_DATES"},Em={message:"Invalid bookings",code:"ERR_INVALID_BOOKINGS"},ql={message:"Invalid dateAvailability",code:"ERR_INVALID_DATE_AVAILABILITY"},eE={message:"Missing dateAvailability",code:"ERR_MISSING_DATE_AVAILABILITY"},je={message:"Invalid Date",code:"ERR_INVALID_DATE"},Eo={message:"Invalid time",code:"ERR_INVALID_TIME"},rE={message:"Invalid tournament dates",code:"ERR_INVALID_DATES_TOURNAMENT"};var kI={message:"Invalid game scores",code:"ERR_INVALID_SCORES_GAME"},nE={message:"Invalid score",code:"ERR_INVALID_SCORE"},Um={message:"Invalid winningSide",code:"ERR_INVALID_WINNING_SIDE"};var yC={message:"No participants generated",code:"ERR_NO_PARTICIPANTS_GENERATED"},$l={message:"Cannot modify tieFormat",code:"ERR_UNCHANGED_CANNOT_MODIFY_TIEFORMAT"},oE={message:"Cannot modify participantType",code:"ERR_UNCHANGED_CANNOT_MODIFY_PARTICIPANT_TYPE"},zu={message:"Cannot remove participants",code:"ERR_UNCHANGED_CANNOT_REMOVE_PARTICIPANTS"},GI={message:"Participant category mismatch",code:"ERR_CATEGORY_MISMATCH"},Pm={message:"Cannot change winningSide",code:"ERR_UNCHANGED_CANNOT_CHANGE_WINNING_SIDE"},xi={message:"Invalid participant",code:"ERR_INVALID_PARTICIPANT"},mn={message:"Invalid participantId",code:"ERR_INVALID_PARTICIPANT_ID"},wr={message:"Invalid participantIds",code:"ERR_INVALID_PARTICIPANT_IDS"},iE={message:"Invalid participantRole",code:"ERR_INVALID_PARTICIPANT_ROLE"},An={message:"Invalid participantType",code:"ERR_INVALID_PARTICIPANT_TYPE"},sE={message:"Missing participantRole",code:"ERR_MISSING_PARTICIPANT_ROLE"},wi={message:"Missing participant",code:"ERR_MISSING_PARTICIPANT"},$a={message:"Missing participants",code:"ERR_MISSING_PARTICIPANTS"},oe={message:"Missing participantId",code:"ERR_MISSING_PARTICIPANT_ID"},te={message:"Participant Not Found",code:"ERR_NOT_FOUND_PARTICIPANT"},aE={message:"participantId exists",code:"ERR_EXISTING_PARTICIPANT_ID"},gL={message:"participant pair exists",code:"ERR_EXISTING_PARTICIPANT_PAIR"},cE={message:"No participant removed",code:"ERR_UNCHANGED_NO_PARTICIPANT_REMOVED"},Uo={message:"Missing participantIds",code:"ERR_MISSING_PARTICIPANT_IDS"},uE={message:"Missing participantsCount",code:"ERR_MISSING_PARTICIPANT_COUNT"},pE={message:"Participant not checked in",code:"ERR_UNCHANGED_PARTICIPANT_NOT_CHECKED_IN"},mE={message:"Missing person details",code:"ERR_MISSING_PERSON_DETAILS"},vs={message:"Existing participant drawPosition assignment",code:"ERR_EXISTING_PARTICIPANT_DRAW_POSITION_ASSIGNMENT"},Qu={message:"Existing participant",code:"ERR_EXISTING_PARTICIPANT"},Kl={message:"participantsCount exceeds drawSize",code:"ERR_INVALID_PARTICIPANT_COUNT"},zl={message:"Invalid entry status",code:"ERR_INVALID_ENTRY_STATUS"},VI={message:"Participant Entry Not Found",code:"ERR_NOT_FOUND_PARTICIPANT_ENTRY"},AC={message:"Participant not entered in stage",code:"ERR_UNCHANGED_PARTICIPANT_NOT_ENTERED"},EC={message:"Participant not found in stageSequence",code:"ERR_NOT_FOUND_PARTICIPANT_IN_STAGE"},dE={message:"entryStatus not allowed in stage",code:"ERR_INVALID_ENTRY_STATUS_IN_STAGE"},lE={message:"entryStatus not allowed for event",code:"ERR_INVALID_ENTRY_STATUS_IN_EVENT"},BI={message:"No stage space available for entryStatus",code:"ERR_UNCHANGED_NO_AVAILABLE_STAGE_SPACE"},fE={message:"Insufficient drawPositions to accommodate qualifiers",code:"ERR_UNCHANGED_NO_DRAW_POSITIONS_FOR_QUALIFIERS"},Ql={message:"Insufficient drawPositions to accommodate entries",code:"ERR_INSUFFICIENT_DRAW_POSITIONS"},gE={message:"Missing penaltyType",code:"ERR_MISSING_PENALTY_TYPE"},Xl={message:"Missing penaltyId",code:"ERR_MISSING_PENALTY_ID"},kc={message:"Penalty not found",code:"ERR_NOT_FOUND_PENALTY"},IE={message:"Missing courtsCount/courtNames",code:"ERR_MISSING_COURTS_INFO"},Os={message:"Court not found",code:"ERR_NOT_FOUND_COURT"},hE={message:"Court exists",code:"ERR_EXISTING_COURT"},SE={message:"Venue exists",code:"ERR_EXISTING_VENUE"},Li={message:"Venue not found",code:"ERR_NOT_FOUND_VENUE"},Jo={message:"Missing venueId",code:"ERR_MISSING_VENUE_ID"},TE={message:"Invalid endTime",code:"ERR_INVALID_END_TIME"},HI={message:"Existing endTime",code:"ERR_EXISTING_END_TIME"},yE={message:"Invalid stopTime",code:"ERR_INVALID_STOP_TIME"},AE={message:"Invalid startTime",code:"ERR_INVALID_START_TIME"},UC={message:"Invalid resumeTime",code:"ERR_INVALID_RESUME_TIME"},Jl={message:"Invalid timeItem",code:"ERR_INVALID_TIME_ITEMS"},EE={message:"Missing async state provider",code:"ERR_MISSING_ASYNC_STATE_PROVIDER"},Zl={message:"Missing timeItem",code:"ERR_MISSING_TIME_ITEM"},tf={message:"Missing timeItems",code:"ERR_MISSING_TIME_ITEMS"},Gc={message:"Missing context",code:"ERR_MISSING_CONTEXT"},UE={message:"Missing schedule",code:"ERR_MISSING_SCHEDULE"},Ka={message:"Invalid scaleItem",code:"ERR_INVALID_SCALE_ITEM"},PE={message:"Modifications failed",code:"ERR_FAILURE_MODIFICATIONS"},_s={message:"No modifications applied",code:"ERR_UNCHANGED_NO_MODIFICATIONS_APPLIED"},DE={message:"Unable to assign court",code:"ERR_UNCHANGED_COURT_NOT_ASSIGNED"},Xu={message:"No Candidates",code:"ERR_UNCHANGED_NO_CANDIDATES"},NE={message:"Invalid configuration",code:"ERR_INVALID_CONFIG"},ME={message:"Invalid collectionDefinition",code:"ERR_INVALID_COLLECTION_DEFINITION"},lo={message:"Invalid object",code:"ERR_INVALID_OBJECT"},Ju={message:"Invalid gender",code:"ERR_INVALID_GENDER"},Vc={message:"Invalid category",code:"ERR_INVALID_CATEGORY"},G={message:"Invalid values",code:"ERR_INVALID_VALUES"},RE={message:"Duplicate value",code:"ERR_DUPLICATE_VALUE"},ef={message:"Team not found",code:"ERR_NOT_FOUND_TEAM"},CE={message:"No valid actions",code:"ERR_NO_VALID_ACTIONS"},Zu={message:"No valid attributes",code:"ERR_NO_VALID_ATTRIBUTES"},rf={message:"Value unchanged",code:"ABORT_UNCHANGED"},ve={message:"Not found",code:"ERR_NOT_FOUND"},tp={message:"Not implemented",code:"ERR_NOT_IMPLEMENTED"},bE={message:"Existing flight",code:"ERR_EXISTING_FLIGHT"},nf={message:"Existing flight profile",code:"ERR_EXISTING_FLIGHT_PROFILE"},vE={message:"Existing outcome",code:"ERR_EXISTING_OUTCOME"},OE={message:"Existing matchUpId",code:"ERR_EXISTING_MATCHUP_ID"},WI={message:"Existing stage",code:"ERR_EXISTING_STAGE"},of={message:"Existing structure",code:"ERR_EXISTING_STRUCTURE"},za={message:"Method not found",code:"ERR_NOT_FOUND_METHOD"},_E={message:"Scheduled matchUps",code:"ERR_SCHEDULED_MATCHUPS"},ep={message:"Scores present",code:"ERR_SCORES_PRESENT"},PC={ANACHRONISM:bI,CANNOT_CHANGE_WINNING_SIDE:Pm,CANNOT_MODIFY_TIEFORMAT:$l,CANNOT_MODIFY_PARTICIPANT_TYPE:oE,CANNOT_REMOVE_MAIN_STRUCTURE:RA,CANNOT_REMOVE_PARTICIPANTS:zu,CATEGORY_MISMATCH:GI,COURT_EXISTS:hE,COURT_NOT_FOUND:Os,DRAW_DEFINITION_NOT_FOUND:Rr,DRAW_ID_EXISTS:OA,DRAW_POSITION_ACTIVE:qu,DRAW_POSITION_ASSIGNED:Wa,DRAW_POSITION_NOT_CLEARED:vA,DRAW_POSITION_NOT_FOUND:aL,DRAW_SIZE_MISMATCH:OI,DUPLICATE_ENTRY:ym,DUPLICATE_VALUE:RE,ENTRY_STATUS_NOT_ALLOWED_FOR_EVENT:lE,ENTRY_STATUS_NOT_ALLOWED_IN_STAGE:dE,EVENT_EXISTS:HA,EVENT_NOT_FOUND:jr,EXISTING_DRAW_DEFINITIONS:CA,EXISTING_END_TIME:HI,EXISTING_FLIGHT:bE,EXISTING_MATCHUP_ID:OE,EXISTING_OUTCOME:vE,EXISTING_PARTICIPANT_DRAW_POSITION_ASSIGNMENT:vs,EXISTING_PARTICIPANT:Qu,EXISTING_POLICY_TYPE:FI,EXISTING_PROFILE:nf,EXISTING_ROUND:VA,EXISTING_STAGE:WI,EXISTING_STRUCTURE:of,INCOMPATIBLE_MATCHUP_STATUS:Bl,INCOMPLETE_SOURCE_STRUCTURE:wl,INSUFFICIENT_DRAW_POSITIONS:Ql,INVALID_ACTION:LA,INVALID_ASSIGNMENT:_I,INVALID_BOOKINGS:Em,INVALID_CATEGORY:Vc,INVALID_COLLECTION_DEFINITION:ME,INVALID_CONFIGURATION:NE,INVALID_DATE_AVAILABILITY:ql,INVALID_DATE:je,INVALID_DRAW_DEFINITION:ua,INVALID_DRAW_POSITION_FOR_SEEDING:Ll,INVALID_DRAW_POSITION:Rs,INVALID_DRAW_SIZE:$u,INVALID_END_TIME:TE,INVALID_ENTRIES:jA,INVALID_EVENT_TYPE:Hn,INVALID_GAME_SCORES:kI,INVALID_GENDER:Ju,INVALID_MATCHUP_FORMAT:Hl,INVALID_MATCHUP_STATUS:pa,INVALID_MATCHUP_STATUS_BYE:KA,INVALID_MATCHUP:dr,INVALID_OBJECT:lo,INVALID_PARTICIPANT_ID:mn,INVALID_PARTICIPANT_IDS:wr,INVALID_PARTICIPANT_ROLE:iE,INVALID_PARTICIPANT_SEEDING:_A,INVALID_PARTICIPANT_TYPE:An,INVALID_PARTICIPANT:xi,INVALID_POLICY_DEFINITION:XA,INVALID_RECORDS:vI,INVALID_SCALE_ITEM:Ka,INVALID_SEED_NUMBER:kA,INVALID_SEED_POSITION:GA,INVALID_SET_NUMBER:dL,INVALID_SIDE_NUMBER:jl,INVALID_SCORE:nE,INVALID_STAGE:Oi,INVALID_START_TIME:AE,INVALID_STRUCTURE:Xo,INVALID_STOP_TIME:yE,INVALID_TIE_FORMAT:Lo,INVALID_TIME:Eo,INVALID_TIME_ITEM:Jl,INVALID_TOURNAMENT_DATES:rE,INVALID_TOURNAMENT_RECORD:Ha,INVALID_VALUES:G,INVALID_WINNING_SIDE:Um,MATCHUP_NOT_FOUND:Le,METHOD_NOT_FOUND:za,MISSING_ASSIGNMENTS:Vl,MISSING_ASYNC_STATE_PROVIDER:EE,MISSING_AVOIDANCE_POLICY:QA,MISSING_BIRTH_DATE:JA,MISSING_COLLECTION_DEFINITION:zA,MISSING_COURT_ID:_i,MISSING_COURTS_INFO:IE,MISSING_DATE_AVAILABILITY:eE,MISSING_DATE:ZA,MISSING_DRAW_DEFINITION:Z,MISSING_DRAW_ID:an,MISSING_DRAW_POSITION:Cs,MISSING_DRAW_POSITIONS:ja,MISSING_DRAW_SIZE:Ya,MISSING_ENTRIES:WA,MISSING_EVENT:vt,MISSING_MATCHUP_FORMAT:Wl,MISSING_MATCHUP_ID:sr,MISSING_MATCHUP_IDS:rs,MISSING_MATCHUP:hr,MISSING_MATCHUPS:Jn,MISSING_PARTICIPANT_COUNT:uE,MISSING_PARTICIPANT_ID:oe,MISSING_PARTICIPANT_IDS:Uo,MISSING_PARTICIPANT_ROLE:sE,MISSING_PARTICIPANT:wi,MISSING_PARTICIPANTS:$a,MISSING_PENALTY_ID:Xl,MISSING_PENALTY_TYPE:gE,MISSING_PERSON_DETAILS:mE,MISSING_POLICY_ATTRIBUTES:LI,MISSING_POLICY_DEFINITION:Ku,MISSING_POLICY_TYPE:wI,MISSING_POSITION_ASSIGNMENTS:$A,MISSING_ROUND_NUMBER:cL,MISSING_SCHEDULE:UE,MISSING_SCORING_POLICY:mL,MISSING_SEED_ASSIGNMENTS:FA,MISSING_SEEDCOUNT_THRESHOLDS:wA,MISSING_SEEDING_POLICY:uL,MISSING_SET_NUMBER:lL,MISSING_SET_OBJECT:Yl,MISSING_SIDE_NUMBER:fL,MISSING_STAGE:YA,MISSING_STRUCTURE_ID:Ur,MISSING_STRUCTURE:mi,MISSING_STRUCTURES:Gl,MISSING_TARGET_LINK:kl,MISSING_TIE_FORMAT:bs,MISSING_TIME_ITEM:Zl,MISSING_TIME_ITEMS:tf,MISSING_TOURNAMENT_ID:ca,MISSING_TOURNAMENT_RECORD:Y,MISSING_TOURNAMENT_RECORDS:xt,MISSING_VALUE:st,MISSING_VENUE_ID:Jo,MODIFICATIONS_FAILED:PE,NO_CANDIDATES:Xu,NO_DRAW_POSITIONS_AVAILABLE_FOR_QUALIFIERS:fE,NO_MODIFICATIONS_APPLIED:_s,NO_STAGE_SPACE_AVAILABLE_FOR_ENTRY_STATUS:BI,NO_PARTICIPANT_REMOVED:cE,NO_VALID_ACTIONS:CE,NO_VALID_ATTRIBUTES:Zu,NO_VALID_DATES:tE,NOT_FOUND:ve,NOT_IMPLEMENTED:tp,PARTICIPANT_COUNT_EXCEEDS_DRAW_SIZE:Kl,PARTICIPANT_ID_EXISTS:aE,PARTICIPANT_NOT_CHECKED_IN:pE,PARTICIPANT_NOT_FOUND:te,PARTICIPANT_PAIR_EXISTS:gL,PENALTY_NOT_FOUND:kc,POLICY_NOT_ATTACHED:pL,POLICY_NOT_FOUND:Fc,SCHEDULE_NOT_CLEARED:bA,SCHEDULED_MATCHUPS:_E,SCORES_PRESENT:ep,SEEDSCOUNT_GREATER_THAN_DRAW_SIZE:xA,STAGE_SEQUENCE_LIMIT:qA,STRUCTURE_NOT_FOUND:kt,TEAM_NOT_FOUND:ef,UNABLE_TO_ASSIGN_COURT:DE,UNLINKED_STRUCTURES:BA,UNRECOGNIZED_DRAW_TYPE:Fl,UNRECOGNIZED_MATCHUP_FORMAT:qa,UNRECOGNIZED_MATCHUP_STATUS:xI,VALUE_UNCHANGED:rf,VENUE_EXISTS:SE};var Ze={disableNotifications:!1,tournamentId:void 0,tournamentRecords:{},subscriptions:{},modified:!1,methods:{},notices:[]},xE={addNotice:ML,callListener:OL,cycleMutationStatus:NL,deleteNotice:bL,deleteNotices:CL,disableNotifications:IL,enableNotifications:hL,getMethods:rp,getNotices:RL,getTopics:vL,getTournamentId:DC,getTournamentRecord:SL,getTournamentRecords:TL,removeTournamentRecord:UL,setMethods:DL,setSubscriptions:PL,setTournamentId:AL,setTournamentRecord:yL,setTournamentRecords:EL,handleCaughtError:_L};function IL(){Ze.disableNotifications=!0}function hL(){Ze.disableNotifications=!1}function DC(){return Ze.tournamentId}function SL(t){return Ze.tournamentRecords[t]}function TL(){return Ze.tournamentRecords}function yL(t){let e=t?.tournamentId;return e?(Ze.tournamentRecords[e]=t,{success:!0}):{error:Ha}}function AL(t){return t?Ze.tournamentRecords[t]?(Ze.tournamentId=t,{success:!0}):{error:Y}:(Ze.tournamentId=void 0,{success:!0})}function EL(t){Ze.tournamentRecords=t;let e=Object.keys(t);e.length===1?Ze.tournamentId=e[0]:e.length||(Ze.tournamentId=void 0)}function UL(t){if(typeof t!="string")return{error:G};if(!Ze.tournamentRecords[t])return{error:ve};delete Ze.tournamentRecords[t];let e=Object.keys(Ze.tournamentRecords);return e.length===1?Ze.tournamentId=e[0]:e.length||(Ze.tournamentId=void 0),{success:!0}}function PL(t){return typeof t.subscriptions!="object"?{error:G}:(Object.keys(t.subscriptions).forEach(e=>{typeof t.subscriptions[e]=="function"?Ze.subscriptions[e]=t.subscriptions[e]:delete Ze.subscriptions[e]}),{...C})}function DL(t){return typeof t!="object"?{error:G}:(Object.keys(t).forEach(e=>{typeof t[e]=="function"&&(Ze.methods[e]=t[e])}),{...C})}function NL(){let t=Ze.modified;return Ze.modified=!1,t}function ML({topic:t,payload:e,key:r},n){if(!(typeof t!="string"||typeof e!="object")&&(Ze.disableNotifications||(Ze.modified=!0),!(Ze.disableNotifications||!Ze.subscriptions[t]&&!n)))return r&&(Ze.notices=Ze.notices.filter(o=>!(o.topic===t&&o.key===r))),Ze.notices.push({topic:t,payload:e,key:r}),{...C}}function rp(){return Ze.methods??{}}function RL({topic:t}){return Ze.notices.filter(e=>e.topic===t).map(e=>e.payload)}function CL(){Ze.notices=[]}function bL({topic:t,key:e}){Ze.notices=Ze.notices.filter(r=>(!t||r.topic===t)&&r.key!==e)}function vL(){return{topics:Object.keys(Ze.subscriptions)}}function OL({topic:t,notices:e},r){let n=Ze.subscriptions[t];n&&typeof n=="function"&&n(e);let o=r?.[t];o&&typeof o=="function"&&o(e)}function _L({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:DC(),params:JSON.stringify(r),engine:t,methodName:e,error:o}),{error:o}}var Oe={timers:{default:{elapsedTime:0}},globalSubscriptions:{},deepCopyAttributes:{stringify:[],ignore:[],toJSON:[]},globalMethods:[],deepCopy:!0},cn=xE,NC=["addNotice","callListener","cycleMutationStatus","deleteNotice","deleteNotices","disableNotifications","enableNotifications","getMethods","getNotices","getTopics","getTournamentId","getTournamentRecord","getTournamentRecords","removeTournamentRecord","setSubscriptions","setTournamentId","setTournamentRecord","setTournamentRecords"];function xL(t){if(typeof t!="object")throw new Error("Global state provider can not be undefined or null");if(Yt(Object.keys(t),NC).length!==NC.length)throw new Error("Global state provider is missing required methods");return cn=t,{success:!0}}function wE(){if(cn.createInstanceState){try{cn.createInstanceState()}catch(t){return{error:t}}return{success:!0}}else return{error:EE}}function Pr(t){return!t||typeof t!="object"?Oe.devContext??!1:typeof Oe.devContext!="object"?!1:Object.keys(t).every(e=>Oe.devContext?.[e]===t[e])&&Oe.devContext}function wL(t="reset",e="default"){let r=Date.now();if(t==="report"){if(e==="allTimers")return Object.keys(Oe.timers).filter(o=>o!=="default"||Oe.timers[o].startTime).map(o=>{let i=Oe.timers[o],s=i.state==="stopped"?0:(r-(i?.startTime??0))/1e3,a=i.elapsedTime+s;return{state:Oe.timers[o].state,elapsedTime:a.toFixed(2),timer:o}});{let n=Oe.timers[e].state==="stopped"?0:(r-(Oe.timers[e]?.startTime??0))/1e3,o=Oe.timers[e].elapsedTime+n;return{state:Oe.timers[e].state,elapsedTime:o.toFixed(2),timer:e}}}if(!Oe.timers[e]||t==="reset"){if(e==="allTimers")return Oe.timers={default:{elapsedTime:0}},!0;Oe.timers[e]={startTime:r,state:"active",elapsedTime:0}}return Oe.timers[e].elapsedTime||(Oe.timers[e].elapsedTime=0),t==="stop"&&Oe.timers[e].state!=="stopped"&&(Oe.timers[e].state="stopped")&&(Oe.timers[e].elapsedTime+=(r-(Oe.timers[e]?.startTime??0))/1e3),t==="start"&&(Oe.timers[e].startTime=r)&&(Oe.timers[e].state="active"),Oe.timers[e]}function MC(t){Wr(t)?Oe.globalLog=t:delete Oe.globalLog}function Bc(t){Oe.devContext=t}function LE(){cn.disableNotifications()}function sf(){cn.enableNotifications()}function Hc(t,e){typeof t=="boolean"&&(Oe.deepCopy=t),typeof e=="object"&&(Array.isArray(e.ignore)&&(Oe.deepCopyAttributes.ignore=e.ignore),Array.isArray(e.toJSON)&&(Oe.deepCopyAttributes.toJSON=e.toJSON),Array.isArray(e.stringify)&&(Oe.deepCopyAttributes.stringify=e.stringify),e.threshold&&(Oe.deepCopyAttributes.threshold=e.threshold))}function af(){return{enabled:Oe.deepCopy,...Oe.deepCopyAttributes}}function LL(t){return t?.subscriptions?(Object.keys(t.subscriptions).forEach(e=>{Oe.globalSubscriptions[e]=t.subscriptions[e]}),{...C}):{error:st,info:"missing subscriptions"}}function FL(t){return t?.subscriptions?cn.setSubscriptions({subscriptions:t.subscriptions}):{error:st,info:"missing subscriptions"}}function RC(t){return t?typeof t!="object"?{error:G}:(Object.keys(t).forEach(e=>{Wr(t[e])&&(Oe.globalMethods[e]=t[e])}),{...C}):{error:st,info:"missing method declarations"}}function CC(t){return t?typeof t!="object"?{error:G}:cn.setMethods(t):{error:st,info:"missing method declarations"}}function cf(){return cn.cycleMutationStatus()}function mt(t){if(typeof t?.topic!="string")return;let e=Oe.globalSubscriptions[t.topic];return cn.addNotice(t,e)}function uf(){return{...Oe.globalMethods,...cn.getMethods()}}function jI(t){return cn.getNotices(t)}function YI({key:t,topic:e}){return cn.deleteNotice({key:t,topic:e})}function Fi(){return cn.deleteNotices()}function Lr(){return cn.getTopics()}function np(t){return Lr()?.topics?.includes(t)}async function Dm(t){return cn.callListener(t,Oe.globalSubscriptions)}function ns(){return cn.getTournamentId()}function pf(t){return cn.getTournamentRecord(t)}function Fo(){return cn.getTournamentRecords()}function FE(t){return cn.setTournamentRecord(t)}function Nm(t){return cn.setTournamentRecords(t)}function op(t){return cn.setTournamentId(t)}function kE(t){return cn.removeTournamentRecord(t)}function qI(){return cn}function ip({engineName:t,methodName:e,params:r,err:n}){let o=Wr(cn.handleCaughtError)&&cn.handleCaughtError||xE.handleCaughtError,{tournamentRecord:i,...s}=r;return o({params:s,engineName:t,methodName:e,err:n})}function GE(t,e){if(Oe.globalLog)try{Oe.globalLog({log:t,engine:e})}catch(r){console.log("globalLog error",r),console.log(e,t),MC()}else console.log(e,t)}function VE(t,e,r,n){if(!ht(t))return{error:G};Zt||(r=1);let o=Array.isArray(e)?e:[],i={},s=(a,c=0)=>{Object.keys(a).forEach(u=>{Wr(a[u])?i[u]=a[u]:ht(a[u])&&(e===!0||o?.includes(u))&&(r===void 0||c<r)&&s(a[u],c+1)})};return s(t),n?RC(i):CC(i),{methods:i}}function kL(t,e,r){return Object.keys(t).filter(n=>!e.includes(t[n])&&(!r||(Array.isArray(t[n])?t[n].length:!0)))}function ot(t,e,r,n){if(typeof t!="object"||t===null)return t;af()?.enabled||(n=!0);let i=["",void 0,null];e&&i.push(!1);let s=kL(t,i,r);return Object.assign({},...s.map(a=>Array.isArray(t[a])?{[a]:n?t[a]:t[a].map(c=>ot(c))}:{[a]:n?t[a]:ot(t[a])}))}function _({context:t,result:e,stack:r,info:n}){return e&&!Array.isArray(e?.stack)&&(e.stack=[]),e&&Array.isArray(e?.stack)&&typeof r=="string"&&e.stack.push(r),e&&n&&(e.info=n),e&&typeof t=="object"&&Object.keys(t).length&&Object.assign(e,ot(t)),e&&!e?.error&&!e?.success&&Object.assign(e,{...C}),e??{success:!0}}var Pn="ANY",$t="MALE",Tr="MIXED",os="OTHER",ne="FEMALE",Mm={ANY:Pn,MALE:$t,FEMALE:ne,MIXED:Tr,OTHER:os};var GL="MIXED events can not contain mixed singles or { gender: ANY } collections",VL="events with { gender: ANY } can not contain MIXED singles collections";function Rm(t){let e="tieFormatGenderValidityCheck",{referenceGender:r,matchUpType:n,gender:o}=t;return r&&o&&[$t,ne].includes(r)&&r!==o?_({result:{valid:!1,error:Ju},context:{gender:o},stack:e}):r===Tr&&(o===Pn||o===Tr&&n!==_t)?_({result:{error:Ju,valid:!1},info:GL,stack:e}):r===Pn&&o===Tr&&n!==_t?_({result:{error:Ju,valid:!1},info:VL,stack:e}):{valid:!0}}var BL="normal",BE="timed",HL="final",mf="NOAD",Cm="SET",vC={S:BL,F:HL};function sp(t,e){if(ht(t),(t?.bestOf||t?.exactly)&&t?.setFormat)return WL(t,e)}function df(t){return!isNaN(Number(t))&&Number(t)}function xC(t){let e=`T${t.minutes}`;return t.based&&(e+=t.based),t.modifier&&(e+=`@${t.modifier}`),e}function WL(t,e){let r=df(t.bestOf)||void 0,n=df(t.exactly)||void 0,o=r||n;if(t.setFormat?.timed&&t.simplified&&o===1)return xC(t.setFormat);let i=o&&`${Cm}${o}`||"",s=OC(t.setFormat,e),a=s&&`S:${s}`||"",c=OC(t.finalSetFormat,e),u=o&&o>1&&c&&s!==c&&`F:${c}`||"";if(i&&s)return[i,a,u].filter(m=>m).join("-")}function OC(t,e){if(typeof t=="object"&&Object.keys(t).length){if(t.timed)return xC(t);if(t.tiebreakSet)return _C(t.tiebreakSet);let r=df(t.setTo);if(r){let n=t.NoAD&&mf||"",o=_C(t.tiebreakFormat),i=o&&`/${o}`||"",s=df(t.tiebreakAt),a=s&&(s!==r||e)&&`@${s}`||"";if(o!==!1)return`${r}${n}${i}${a}`}}}function _C(t){if(t){if(typeof t=="object"&&!t.tiebreakTo)return"";if(typeof t=="object"&&df(t.tiebreakTo)){let e=`TB${t.tiebreakTo}${t.NoAD?mf:""}`;return t.modifier&&(e+=`@${t.modifier}`),e}else return!1}}function Ye(t){if(Vt(t)){let e=t.startsWith("T")&&BE||t.startsWith(Cm)&&Cm||"";if(e===BE){let r=kC(t),n={simplified:!0,setFormat:r,bestOf:1};if(r)return n}if(e===Cm)return jL(t)}}function jL(t){let e=t.split("-"),r=lf(e[0].slice(3)),n=r===1||r%2!==0?r:void 0,o=r!==1&&r%2===0?r:void 0,i=e&&wC(e[1]),s=e&&wC(e[2]),a=i&&i.timed||s&&s.timed,c=n&&n<6||a&&o,u=!e[2]||s,p=i,m=ot({setFormat:i,exactly:o,bestOf:n});if(s&&(m.finalSetFormat=s),c&&p&&u)return m}function wC(t){if(t?.[1]===":"){let e=t.split(":"),r=vC[e[0]],n=e[1];if(r&&n){if(n.startsWith("TB")){let I=LC(n);return I===!1?!1:typeof I=="object"?{tiebreakSet:I}:void 0}if(n.startsWith("T"))return kC(n);let s=t.match(/^[FS]:(\d+)([A-Za-z]*)/),a=s&&GC(s[2])||!1,c=!s?.[2]||a,u=s?lf(s[1]):void 0,p=FC(n),m=p!==!1,d=m&&p||u,l=LC(n.split("/")[1]),f=l!==!1,g={setTo:u};return a&&(g.NoAD=!0),l?(g.tiebreakFormat=l,g.tiebreakAt=d):g.noTiebreak=!0,u&&c&&f&&m&&g||!1}}}function FC(t,e=!0){let r=t?.indexOf("@")>0&&t.split("@");if(r)return(e?lf(r[1]):r[1])||!1}function LC(t){if(t)if(t.startsWith("TB")){let e=FC(t,!1),r=t.match(/^TB(\d+)([A-Za-z]*)/),n=r?.[1],o=r&&GC(r[2]),i=!r?.[2]||o,s=lf(n);if(s&&i){let a={tiebreakTo:s};return e&&typeof e=="string"&&!It(e)&&(a.modifier=e),o&&(a.NoAD=!0),a}else return!1}else return!1}function kC(t){let e=t.slice(1),r=e.match(/^(\d+)(@?[A-Za-z]*)/),n=lf(r?.[1]);if(!n)return;let o={timed:!0,minutes:n},i=r?.[2],s=[void 0,"P","G"].includes(i);if(i&&!s){let a=e.match(/^(\d+)(@)([A-Za-z]+)$/)?.[3];return a?(o.modifier=a,o):void 0}return i&&(o.based=r[2]),o}function GC(t){return t&&t.indexOf(mf)>=0}function lf(t){return isNaN(Number(t))?0:Number(t)}function Dr({matchUpFormat:t}){if(!Vt(t)||t==="")return!1;let e=Ye(t),r=t.match(/-S:([1-9])+\/TB([0-9]{1,2})@?([1-9]?)*/),n=r?.[1],o=r?.[2],i=r?.[3],s=t.match(/-F:([1-9])+\/TB([0-9]{1,2})@?([1-9]?)*/),a=s?.[1],c=s?.[2],u=s?.[3];return sp(e,!!(r&&o&&n===i||s&&c&&a===u))===t}var bm=/^[\d]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][\d]|3[0-1])$/,$I=/^((0[\d]|1[\d]|2[0-3]):[0-5][\d](:[0-5][\d])?)([.,][0-9]{3})?$/,Po=/^([\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?$/,xs=/^([\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 vm(t){let{scheduledDate:e}=t;if(!e&&t.scheduledTime&&(e=Et(t.scheduledTime)),!e)return;let r=Kt(t.scheduledTime),n=Et(e);return n&&r&&(n+=`T${r}`),n}function VC(t){return typeof t!="object"||Array.isArray(t)?!1:Object.prototype.toString.call(t)==="[object Date]"}function Wc(t){let e=typeof t=="string"?t?.split(" "):[];return t&&e?.length>1&&!["AM","PM"].includes(e[1].toUpperCase())?!1:!!(!t||xs.test(Xa(t,!0,!0)))}function Cr(t){return Qa(t)||bm.test(t)}function YL(t){let e=new Date(t),r=e.getSeconds()+60*e.getMinutes()+60*60*e.getHours();return qL(r,{displaySeconds:!1})}function qL(t,e){let r=parseInt(t,10),n=Math.floor(r/3600),o=Math.floor((r-n*3600)/60),i=r-n*3600-o*60;return(!e||e?.displaySeconds?n+":"+o+":"+i:n+":"+o).split(":").map(Zn).join(":")}var If=t=>{let e=ff(t)||Qa(t)?new Date(t):new Date,r=e.getUTCMonth()+1,n=r<10?`0${r}`:`${r}`;return`${e.getUTCFullYear()}-${Zn(n)}-${Zn(e.getUTCDate())}`};function $L(t){let e=ff(t)||Qa(t)?new Date(t):new Date;return Date.UTC(e.getFullYear(),e.getMonth(),e.getDate())}function Wn(t,e="-",r="YMD"){if(!t)return"";typeof t=="string"&&t.indexOf("T")<0&&(t=t+"T00:00");let n=new Date(t),o=""+(n.getMonth()+1),i=""+n.getDate(),s=n.getFullYear();return o.length<2&&(o="0"+o),i.length<2&&(i="0"+i),r==="DMY"?[i,o,s].join(e):r==="MDY"?[o,i,s].join(e):r==="YDM"?[s,i,o].join(e):r==="DYM"?[i,s,o].join(e):r==="MYD"?[o,s,i].join(e):[s,o,i].join(e)}function KI(t){let e=t?new Date(t):new Date,r=e.getTimezoneOffset();return new Date(e.getTime()-r*60*1e3)}function KL(t){return KI(t).getTime()}function ff(t){if(typeof t=="boolean")return!1;let e=t instanceof Date&&t||!isNaN(t)&&new Date(t)||!1;return e&&!isNaN(e.valueOf())}function ws(t,e){if(!Cr(t)||!Cr(e))return[];let r=Et(t)+"T00:00",n=Et(e)+"T00:00",o=new Date(r),i=new Date(n),s=ff(i)&&ff(o)&&u(o,i),a=[],c=0;if(s){let p=o,m=p.getTime();for(;m<=i.getTime()&&c<300;)c+=1,a.push(new Date(p)),m=p.setDate(p.getDate()+1)}return a.map(p=>Wn(p));function u(p,m){return p<=m}}var zL=/^([+-]?\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 Qa(t){return typeof t!="string"?!1:zL.test(t)}function QI(t){if(typeof t!="string")return!1;let r=t.split("Z")[0].split(":"),n=r.every(i=>!isNaN(parseInt(i)));return!(r.length<2||!n||parseInt(r[0])>23||parseInt(r[1])>60)}function qt(t){let e=Kt(t);if(!e)return 0;let[r,n]=e.split(":").map(o=>parseInt(o));return r*60+n}function BC(t){let e=Math.floor(t/60),r=t-e*60;return e>23&&(e=e%24),[Zn(e),Zn(r)].join(":")}function gf(t){return QI(t)?t.split(":").slice(0,2).map(Zn).join(":"):void 0}function Kt(t){return Qa(t)&&t.indexOf("T")>0?gf(t.split("T").reverse()[0]):gf(t)}function Et(t){return Qa(t)||Po.test(t)?t.split("T")[0]:void 0}function ap(t,e){let r=new Date(t);return r.setDate(r.getDate()+e),Et(r.toISOString())}function zI(t){t=typeof t!="string"?"00:00":t;let e={},r={};return{0:e.time,1:e.ampm}=t.split(" ")||[],{0:r.hours,1:r.minutes}=e.time.split(":")||[],r.ampm=e.ampm,isNaN(r.hours)||isNaN(r.minutes)||r.ampm&&!["AM","PM"].includes(r.ampm.toUpperCase())?{}:r}function QL(t){let e=zI(t);return e.ampm&&e.hours&&(e.ampm.toLowerCase()==="pm"&&parseInt(e.hours)<12&&(e.hours=(e.hours&&parseInt(e.hours)||0)+12),e.ampm.toLowerCase()==="am"&&e.hours==="12"&&(e.hours="00")),`${e.hours||"12"}:${e.minutes||"00"}`.split(":").map(Zn).join(":")}function XL(t){let e=zI(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 Xa(t,e,r){let n=Et(t),o=Kt(t),i=n?o:t;return t?e&&(n&&r&&t||QL(i))||XL(i):void 0}function XI(t,e){let r=zI(t),n=zI(e);if(parseInt(r.hours)<parseInt(n.hours))return-1;if(parseInt(r.hours)>parseInt(n.hours))return 1;if(r.hours===n.hours){if(parseInt(r.minutes)<parseInt(n.minutes))return-1;if(parseInt(r.minutes)>parseInt(n.minutes))return 1}return 0}function JI(t,e=7){let r=Et(t)+"T00:00",n=new Date(r),o=new Date(n.setDate(n.getDate()+e));return Wn(o)}function JL(t){return JI(t)}function ZL(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())),Wn(o,r)}function HC(t,e,r){let n=new Date(t,0);return Wn(new Date(n.setDate(e)),r)}function ke(t,e=void 0){let[r,n]=(t||"00:00").split(":").map(Zn),o=KI(e).setHours(r,n,0,0);return KI(o)}function ma(t,e,r=!0){let n=new Date(t),i=(new Date(e).getTime()-n.getTime())/1e3/60;return r?Math.abs(Math.round(i)):Math.round(i)}function Yr(t,e){let r=Kt(t);if(!r)return"00:00";let n=isNaN(e)?0:e;return Kt(hf(ke(r),n).toISOString())}function hf(t,e){let r=new Date(t);return new Date(r.getTime()+e*6e4)}function Zn(t){return t.toString()[1]?t:"0"+t}function jn(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 ZI={addDays:JI,addWeek:JL,addMinutesToTimeString:Yr,convertTime:Xa,getIsoDateString:vm,getUTCdateString:If,DateHHMM:YL,extractDate:Et,extractTime:Kt,formatDate:Wn,getDateByWeek:ZL,isISODateString:Qa,isDate:ff,isTimeString:QI,offsetDate:KI,offsetTime:KL,sameDay:jn,timeStringMinutes:qt,timeToDate:ke,timeUTC:$L,validTimeValue:Wc,validDateString:bm,timeValidation:xs,dateValidation:Po};var tF=(t,e)=>t.filter(Boolean).every(r=>typeof r===e),eF=t=>t.filter(Boolean).every(Zt);function Ls(t){let e=t.category;if(typeof e!="object")return{error:Vc};let{ageCategoryCode:r,ageMaxDate:n,ageMinDate:o,ageMax:i,ageMin:s}=e,a=e.categoryName,c;if(!tF([r,n,o,a],"string")||!eF([i,s]))return{error:Vc};let u=t.consideredDate??Et(new Date().toLocaleDateString("sv"));if(!Cr(u))return{error:je};let[p]=u.split("-").slice(0,3).map(w=>parseInt(w)),m=ap(u,-1),[d,l]=m.split("-").slice(1,3).map(w=>parseInt(w)),f=`${Zn(d)}-${Zn(l)}`,g=ap(u,1),[I,h]=g.split("-").slice(1,3).map(w=>parseInt(w)),S=`${Zn(I)}-${Zn(h)}`,T=s&&ap(u,-1*365*s),y=i&&ap(u,-1*365*i),P=[],U=w=>!P.includes(w)&&P.push(w);r=r??a;let A=/^([UO]?)(\d{1,2})([UO]?)$/,E=/^C(\d{1,2})-(\d{1,2})$/,N=r?.includes("-"),D=N&&r?.match(E),M=r?.match(A),R=(w,V)=>`${w}-${V}`,b=w=>{let V=p-w,k=R(V,S);e.ageMinDate&&e.ageMinDate!==k&&U(`Invalid submitted ageMinDate: ${o}`),o=k,r&&(e.ageMax&&e.ageMax!==w-1&&(U(`Invalid submitted ageMax: ${i}`),y=void 0),i=w-1)},v=w=>{let V=p-w-1,k=R(V,S);e.ageMin&&e.ageMin>w&&U(`Invalid submitted ageMin: ${s}`),e.ageMax&&e.ageMax>w&&U(`Invalid submitted ageMax: ${i}`),e.ageMinDate&&e.ageMinDate!==k&&U(`Invalid submitted ageMinDate: ${o}`),o=k,r&&(e.ageMax&&e.ageMax!==w&&(U(`Invalid submitted ageMax: ${i}`),T=void 0),i=w)},O=w=>{let V=p-w,k=R(V,f);e.ageMaxDate&&e.ageMaxDate!==k&&U(`Invalid submitted ageMaxDate: ${n}`),n=k,r&&(e.ageMin&&e.ageMin!==w+1&&(U(`Invalid submitted ageMin: ${s}`),T=void 0),s=w+1)},x=w=>{let V=p-w-1,k=R(V,f);e.ageMaxDate&&e.ageMaxDate!==k&&U(`Invalid submitted ageMaxDate: ${n}`),n=k,r&&(e.ageMin&&e.ageMin!==w&&(U(`Invalid submitted ageMin: ${s}`),T=void 0),s=w)},F=w=>{let[V,k,W]=(w.match(A)||[]).slice(1),H=parseInt(k);V==="U"?(e.ageMaxDate&&e.ageMaxDate!==n&&U(`Invalid submitted ageMaxDate: ${e.ageMaxDate}`),b(H)):V==="O"&&O(H),W==="U"?(e.ageMaxDate&&e.ageMaxDate!==n&&U(`Invalid submitted ageMaxDate: ${e.ageMaxDate}`),v(H)):W==="O"&&x(H),n=n??T,o=o??y};if(D){if(n=void 0,o=void 0,i=void 0,s=void 0,e.ageMin){let k=p-e.ageMin;n=R(k,f)}if(e.ageMax){let k=p-e.ageMax-1;o=R(k,S)}let[w,V]=(r?.match(E)??[]).slice(1).map(k=>parseInt(k));w<=V?(s=w,i=V,c=!0):U(`Invalid combined age range ${r}`)}else N?r?.split("-").forEach(F):M?F(r):(s&&O(s),i&&v(i));i&&e.ageMin&&e.ageMin>i&&(U(`Invalid submitted ageMin: ${e.ageMin}`),s=void 0);let L=ot({consideredDate:u,combinedAge:c,ageMaxDate:n,ageMinDate:o,ageMax:i,ageMin:s});return P.length&&(L.errors=P),L}function jc({category:t}){if(!ht(t))return{error:G};let e=Ls({category:t});if(e.error)return{error:e};let{ratingMax:r,ratingMin:n}=t;return r&&!Zt(r)?_({result:{error:G},context:{ratingMax:r}}):n&&!Zt(n)?_({result:{error:G},context:{ratingMin:n}}):{...e}}function Yc({childCategory:t,withDetails:e,category:r}){let n=jc({category:r}),o=jc({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=ot({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 qc({checkCategory:t=!0,collectionDefinition:e,checkCollectionIds:r,checkGender:n=!0,referenceCategory:o,referenceGender:i,event:s}){i=i??s?.gender;let a="validateCollectionDefinition",c=[];if(typeof e!="object")return c.push(`collectionDefinition must be an object: ${e}`),_({result:{errors:c,error:lo},stack:a});let{collectionValueProfiles:u,collectionGroupNumber:p,collectionValue:m,collectionId:d,matchUpCount:l,matchUpFormat:f,matchUpValue:g,matchUpType:I,scoreValue:h,setValue:S,category:T,gender:y}=e;if(r&&typeof d!="string"&&c.push(`collectionId is not type string: ${d}`),typeof l!="number"&&c.push(`matchUpCount is not type number: ${l}`),I&&!Lc([Ft,_t],I)&&c.push(`matchUpType must be SINGLES or DOUBLES: ${I}`),[!!u?.length].concat([g,m,h,S].map(It)).filter(Boolean).length!==1&&c.push("Missing value definition for matchUps: matchUpValue, collectionValue, or collectionValueProfiles"),g&&typeof g!="number"&&c.push(`matchUpValue is not type number: ${g}`),m&&typeof m!="number"&&c.push(`collectionValue is not type number: ${m}`),u&&l){let U=CI({collectionValueProfiles:u,matchUpCount:l});U.errors&&c.push(...U.errors)}if(p&&typeof p!="number"&&c.push(`collectionGroupNumber is not type number: ${m}`),f&&!Dr({matchUpFormat:f})&&c.push(`Invalid matchUpFormat: ${f}`),n){let U=Rm({referenceGender:i,matchUpType:I,gender:y});if(U.error)return _({context:{referenceGender:i,gender:y},result:U,stack:a})}if(t&&o&&T){let U=Yc({category:o,childCategory:T});if(!U.valid)return _({result:{error:Vc},context:U,stack:a})}return c.length?_({result:{errors:c,error:ME},stack:a}):{valid:!0}}function ar(t){let e=!!(t?.enforceCategory!==!1&&t?.category),r=!!(t?.enforceGender!==!1&&t?.gender),n=t?.checkCollectionIds,o=t?.tieFormat,i=t?.event,s="validateTieFormat",a=[],c=rF({...t,stack:s});if(c?.error)return c;let u,p=o.collectionDefinitions.every(I=>{let{setValue:h,scoreValue:S,collectionValue:T}=I;(h||S)&&!T&&(u=!0);let{valid:y,errors:P}=qc({referenceCategory:t.category,referenceGender:t.gender,collectionDefinition:I,checkCollectionIds:n,checkCategory:e,checkGender:r,event:i});return y?!0:(Array.isArray(P)&&a.push(...P),!1)}),m=typeof o.winCriteria?.valueGoal=="number"&&o.winCriteria?.valueGoal>0&&!u||o.winCriteria?.aggregateValue;if(!(m||o.winCriteria?.aggregateValue))return u?a.push("aggregateValue is required"):a.push("Either non-zero valueGoal, or { aggregateValue: true } must be specified in winCriteria"),_({context:{tieFormat:o,errors:a,aggregateValueImperative:u},result:{error:Lo},stack:s});let d=o.collectionDefinitions.map(({collectionId:I})=>I),l=!n||d.length===ut(d).length,f=p&&m&&l,g={valid:f,errors:a};return f?g:_({result:{error:Lo},context:{tieFormat:o,errors:a},stack:s})}function rF(t){let{tieFormat:e,stack:r}=t;return!t||!e||!ht(e)?_({result:{error:Lo},context:{tieFormat:e,message:"tieformat must be an object"},stack:r}):ht(e.winCriteria)?Array.isArray(e.collectionDefinitions)?{...C}:_({result:{error:Lo},context:{tieFormat:e,message:"collectionDefinitions must be an array"},stack:r}):_({result:{error:Lo},context:{tieFormat:e,message:"tieformat.winCritiera must be an object"},stack:r})}var Ja="resourceSubType",Za="resourceType",tc="identifier",WC={RESOURCE_SUB_TYPE:Ja,RESOURCE_TYPE:Za,IDENTIFIER:tc};function J(t,e,r,n,o=0){if(qI().makeDeepCopy)return qI().makeDeepCopy(t,e,r,n);let i=af(),{stringify:s,toJSON:a,ignore:c,modulate:u}=i||{};if(!i?.enabled&&!r||typeof t!="object"||Wr(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)||Wr(c)&&!c(l)),d=(l,f)=>{p[l]=Wr(f?.toString)?f.toString():JSON.stringify(f)};for(let l of m){let f=t[l],g=Wr(u)?u(f):void 0;if(g!==void 0)p[l]=g;else if(e&&l==="extensions"&&Array.isArray(f)){let I=Sf(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)&&Wr(f?.toJSON)?p[l]=f.toJSON():f===null?p[l]=void 0:VC(f)?p[l]=new Date(f).toISOString():p[l]=J(f,e,r,n,o+1)}return p}function Sf(t){return t?.map(e=>{let{name:r,value:n}=e;return r&&n&&{[`_${r}`]:n}}).filter(Boolean)}function th(t=1,e){return et(0,t).map(()=>Dt(e))}function Dt(t){let e=[];for(let a=0;a<256;a++)e[a]=(a<16?"0":"")+a.toString(16);let r=Math.random()*4294967295|0,n=Math.random()*4294967295|0,o=Math.random()*4294967295|0,i=Math.random()*4294967295|0,s=e[r&255]+e[r>>8&255]+e[r>>16&255]+e[r>>24&255]+"-"+e[n&255]+e[n>>8&255]+"-"+e[n>>16&15|64]+e[n>>24&255]+"-"+e[o&63|128]+e[o>>8&255]+"-"+e[o>>16&255]+e[o>>24&255]+e[i&255]+e[i>>8&255]+e[i>>16&255]+e[i>>24&255];return typeof t=="string"?`${t}_${s.replace(/-/g,"")}`:s}var eh={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 rh={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 nh={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 oh={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 ih={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 sh={collectionDefinitions:[{scoreValue:1,matchUpType:"SINGLES",collectionName:"Men's Singles",matchUpFormat:"SET1-S:T60",gender:"MALE",matchUpCount:1},{scoreValue:1,matchUpType:"SINGLES",collectionName:"Women's Singles",matchUpFormat:"SET1-S:T60",gender:"FEMALE",matchUpCount:1},{matchUpValue:1,matchUpType:"DOUBLES",collectionName:"Mixed Doubles",matchUpFormat:"SET1-S:T60",gender:"MIXED",matchUpCount:1}],tieFormatName:"Time Tennis Pro Circuit",winCriteria:{aggregateValue:!0}};var ah={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 ch={collectionDefinitions:[{scoreValue:1,matchUpType:"SINGLES",collectionName:"Men's Singles",matchUpFormat:"SET1-S:T60",gender:"MALE",matchUpCount:3},{scoreValue:1,matchUpType:"SINGLES",collectionName:"Women's Singles",matchUpFormat:"SET1-S:T60",gender:"FEMALE",matchUpCount:3},{scoreValue:1,matchUpType:"DOUBLES",collectionName:"Men's Doubles",matchUpFormat:"SET1-S:T60",gender:"MALE",matchUpCount:1},{matchUpValue:1,matchUpType:"DOUBLES",collectionName:"Women's Doubles",matchUpFormat:"SET1-S:T60",gender:"FEMALE",matchUpCount:1},{matchUpValue:1,matchUpType:"DOUBLES",collectionName:"Mixed Doubles",matchUpFormat:"SET1-S:T60",gender:"MIXED",matchUpCount:1}],tieFormatName:"Time Tennis Dual",winCriteria:{aggregateValue:!0}};var uh={collectionDefinitions:[{category:{ageCategoryCode:"14U"},collectionName:"14U Singles",matchUpCount:2,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{category:{ageCategoryCode:"16U"},collectionName:"16U Singles",matchUpCount:2,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{category:{ageCategoryCode:"18U"},collectionName:"18U Singles",matchUpCount:2,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{category:{ageCategoryCode:"14U"},collectionName:"14U Doubles",collectionGroupNumber:1,matchUpCount:1,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1},{category:{ageCategoryCode:"16U"},collectionName:"16U Doubles",collectionGroupNumber:1,matchUpCount:1,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1},{category:{ageCategoryCode:"18U"},collectionName:"18U Doubles",collectionGroupNumber:1,matchUpCount:1,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1}],collectionGroups:[{groupNumber:1,groupName:"Doubles",groupValue:1,winCriteria:{valueGoal:2}}],tieFormatName:"USTA_BREWER_CUP",winCriteria:{valueGoal:4}};var ph={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 Dn="SET3-S:6/TB7",lF="SET3-S:6NOAD",HE="SET3-S:6/TB7-F:TB10",fF="SET3-S:4/TB7",gF="SET3-S:4/TB5@3",IF="SET1-S:T20",hF="SET1-S:8/TB7",SF="SET1-S:8/TB7@7",jC={FORMAT_STANDARD:Dn,FORMAT_STANDARD_NOAD:lF,FORMAT_ATP_DOUBLES:HE,FORMAT_SHORT_SETS:fF,FORMAT_FAST4:gF,FORMAT_PRO_SET:hF,FORMAT_COLLEGE_PRO_SET:SF,TIMED20:IF};var mh={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 dh={collectionDefinitions:[{collectionName:"Doubles",matchUpCount:3,matchUpFormat:"SET1-S:8/TB7@7",matchUpType:"DOUBLES",collectionValue:1},{collectionName:"Singles",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1}],tieFormatName:"USTA_COLLEGE",winCriteria:{valueGoal:4}};var lh={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 fh={collectionDefinitions:[{collectionName:"Female Doubles",gender:"FEMALE",matchUpCount:1,matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Male Doubles",gender:"MALE",matchUpCount:1,matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Female Singles",gender:"FEMALE",matchUpCount:1,matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"SINGLES",scoreValue:1},{collectionName:"Male Singles",matchUpCount:1,gender:"MALE",matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"SINGLES",scoreValue:1},{collectionName:"Mixed Doubles",matchUpCount:1,gender:"MIXED",matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Mixed Doubles",matchUpCount:1,gender:"MIXED",matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Overtime",matchUpCount:1,gender:"MIXED",matchUpFormat:"SET1-S:T20",matchUpType:"DOUBLES",scoreValue:1}],tieFormatName:"USTA_WTT_ITT",winCriteria:{aggregateValue:!0}};var gh={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 Ih={collectionDefinitions:[{collectionGroupNumber:1,matchUpType:"DOUBLES",matchUpCount:1,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpValue:1},{collectionGroupNumber:1,matchUpType:"SINGLES",matchUpCount:3,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpValue:1},{collectionGroupNumber:2,matchUpType:"DOUBLES",matchUpCount:1,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpValue:2},{collectionGroupNumber:2,matchUpType:"SINGLES",matchUpCount:3,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpValue:2},{collectionGroupNumber:3,matchUpType:"DOUBLES",matchUpCount:1,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpValue:3},{collectionGroupNumber:3,matchUpType:"SINGLES",matchUpCount:3,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpValue:3}],collectionGroups:[{groupNumber:1,groupName:"Day 1"},{groupNumber:2,groupName:"Day 2"},{groupNumber:3,groupName:"Day 3"}],tieFormatName:"LAVER_CUP",winCriteria:{valueGoal:13}};var hh={collectionDefinitions:[{collectionName:"Female Doubles",gender:"FEMALE",matchUpCount:1,matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Male Doubles",gender:"MALE",matchUpCount:1,matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Female Singles",gender:"FEMALE",matchUpCount:1,matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"SINGLES",scoreValue:1},{collectionName:"Male Singles",matchUpCount:1,gender:"MALE",matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"SINGLES",scoreValue:1},{collectionName:"Mixed Doubles",matchUpCount:1,gender:"MIXED",matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Overtime",matchUpCount:1,gender:"MIXED",matchUpFormat:"SET1-S:T20",matchUpType:"DOUBLES",scoreValue:1}],tieFormatName:"USTA_TOC",winCriteria:{aggregateValue:!0}};var Om="COLLEGE_DEFAULT",Sh="COLLEGE_JUCO",Th="COLLEGE_D3",WE="DOMINANT_DUO",jE="DOMINANT_DUO_MIXED",YE="LAVER_CUP",qE="TEAM_DOUBLES_3_AGGREGATION",$E="TIME_TENNIS_DUAL",KE="TIME_TENNIS_PRO_CIRCUIT",zE="USTA_BREWER_CUP",QE="USTA_OZAKI_CUP",XE="USTA_COLLEGE",JE="USTA_GOLD_TEAM_CHALLENGE",ZE="USTA_LEVEL_1",tU="USTA_INTERSECTIONAL",eU="USTA_SECTION_BATTLE",rU="USTA_SOUTHERN_LEVEL_5",nU="USTA_TOC",oU="USTA_WTT_ITT",iU="USTA_ZONAL",YC={COLLEGE_D3:Th,COLLEGE_DEFAULT:Om,COLLEGE_JUCO:Sh,DOMINANT_DUO:WE,DOMINANT_DUO_MIXED:jE,LAVER_CUP:YE,TEAM_DOUBLES_3_AGGREGATION:qE,TIME_TENNIS_DUAL:$E,TIME_TENNIS_PRO_CIRCUIT:KE,USTA_BREWER_CUP:zE,USTA_OZAKI_CUP:QE,USTA_COLLEGE:XE,USTA_GOLD_TEAM_CHALLENGE:JE,USTA_INTERSECTIONAL:tU,USTA_LEVEL_1:ZE,USTA_SECTION_BATTLE:eU,USTA_SOUTHERN_LEVEL_5:rU,USTA_TOC:nU,USTA_WTT_ITT:oU,USTA_ZONAL:iU};var $C="STANDARD",qC={[$C]:{hydrate:!0,doubles:{matchUpCount:3,matchUpValue:1},singles:{matchUpCount:6,matchUpValue:1},valueGoal:5},[Th]:{hydrate:!0,doubles:{matchUpFormat:"SET1-S:8/TB7@7",matchUpCount:3,matchUpValue:1},singles:{matchUpFormat:Dn,matchUpCount:6,matchUpValue:1},tieFormatName:Th,valueGoal:5},[Om]:{hydrate:!0,doubles:{matchUpFormat:"SET1-S:6/TB7",collectionValue:1,matchUpCount:3},singles:{matchUpFormat:Dn,matchUpCount:6,matchUpValue:1},tieFormatName:Om,valueGoal:4},[Sh]:{hydrate:!0,doubles:{matchUpFormat:"SET1-S:8/TB7",matchUpCount:3,matchUpValue:1},singles:{matchUpFormat:Dn,matchUpCount:6,matchUpValue:1},tieFormatName:Sh,valueGoal:5},[YE]:Ih,[WE]:mh,[jE]:ah,[qE]:rh,[$E]:ch,[KE]:sh,[zE]:uh,[QE]:ph,[XE]:dh,[JE]:eh,[tU]:ih,[ZE]:lh,[eU]:oh,[rU]:nh,[oU]:fh,[nU]:hh,[iU]:gh},NF=t=>{let e=t?.namedFormat&&Object.keys(qC).includes(t.namedFormat)?t.namedFormat:$C,r=Array.isArray(t?.uuids)?t?.uuids:[],n,{category:o,gender:i}=t?.event??{},s=J(qC[e],!1,!0),a=c=>{if(!t?.isMock&&!t?.event?.isMock||!t.event)return r?.pop()??Dt();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:HE,collectionName:"Doubles",matchUpType:_t,...s.doubles},{collectionId:a(1),matchUpFormat:Dn,collectionName:"Singles",matchUpType:Ft,...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},to=NF;var Yn="SINGLES",Fs="SINGLES",qr="DOUBLES",ko="DOUBLES",_e="TEAM",br="TEAM",MF="AGE",RF="RATING",CF="BOTH",KC={AGE:MF,BOTH:CF,DOUBLES:qr,DOUBLES_EVENT:ko,RATING:RF,SINGLES:Yn,SINGLES_EVENT:Fs,TEAM_EVENT:br,TEAM:_e};var nt="MAIN",ct="QUALIFYING",qe="CONSOLATION",$e="VOLUNTARY_CONSOLATION",de="PLAY_OFF",$c=[nt,ct,qe,de,$e],ks={[ct]:1,[nt]:2,[de]:3,[qe]:3,[$e]:4},sU="finishingPositions",aU="aggregateEventStructures",cU={[nt]:1,[de]:2,[qe]:3,[ct]:4,[$e]:5},zC={[de]:1,[nt]:2,[qe]:3,[ct]:4,[$e]:5},Kc="CLUSTER",QC="SEPARATE",di="WATERFALL",cp="ITEM",Ge="CONTAINER",dn="DRAW",up="RANDOM",En="TOP_DOWN",li="BOTTOM_UP",eo="POSITION",fo="WINNER",ro="LOSER",On="FIRST_MATCHUP",$r="AD_HOC",bF="AD_HOC",da="FEED_IN",zc="COMPASS",Qc="OLYMPIC",vF="SINGLE_ELIMINATION";var go="SINGLE_ELIMINATION",Xc="DOUBLE_ELIMINATION",Jc="FIRST_MATCH_LOSER_CONSOLATION",pp="FIRST_ROUND_LOSER_CONSOLATION",ki="LUCKY_DRAW",Tf="CURTIS_CONSOLATION",XC="CURTIS_CONSOLATION",yh="FEED_IN_CHAMPIONSHIP_TO_SF",_m="FEED_IN_CHAMPIONSHIP_TO_SF",Ah="FEED_IN_CHAMPIONSHIP_TO_QF",xm="FEED_IN_CHAMPIONSHIP_TO_QF",Eh="FEED_IN_CHAMPIONSHIP_TO_R16",wm="FEED_IN_CHAMPIONSHIP_TO_R16",uU="MODIFIED_FEED_IN_CHAMPIONSHIP",Lm="MODIFIED_FEED_IN_CHAMPIONSHIP",mp="FEED_IN_CHAMPIONSHIP",JC="DOUBLE_ROUND_ROBIN",Nn="ROUND_ROBIN",Io="ROUND_ROBIN_WITH_PLAYOFF",pU="DECIDER",mU="BACKDRAW",yf={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"}},Af={0:{name:"East",abbreviation:"E"},"0-1":{name:"West",abbreviation:"W"},"0-2":{name:"North",abbreviation:"N"},"0-1-1":{name:"South",abbreviation:"S"}},fi="WIN_RATIO",Gi="ROUND_OUTCOME",dU=[zc,Tf,xm,wm,_m,mp,Ah,Eh,yh,Jc,pp,ki,Lm,Qc,de,Io],OF=[$r,zc,Tf,Xc,xm,wm,_m,mp,da,Jc,pp,ki,Lm,Qc,de,Nn,Io,go],lU={MAIN:nt,QUALIFYING:ct,CONSOLATION:qe,ITEM:cp,CONTAINER:Ge,FIRST_MATCHUP:On,WINNER:fo,LOSER:ro,AD_HOC:$r,FEED_IN:da,FLEX_ROUNDS:bF,COMPASS:zc,PLAY_OFF:de,OLYMPIC:Qc,KNOCKOUT:vF,SINGLE_ELIMINATION:go,DOUBLE_ELIMINATION:Xc,CURTIS:Tf,FICSF:yh,FICQF:Ah,FICR16:Eh,MFIC:uU,VOLUNTARY_CONSOLATION:$e,FIRST_MATCH_LOSER_CONSOLATION:Jc,FIRST_ROUND_LOSER_CONSOLATION:pp,MODIFIED_FEED_IN_CHAMPIONSHIP:Lm,FEED_IN_CHAMPIONSHIP_TO_R16:wm,FEED_IN_CHAMPIONSHIP_TO_QF:xm,FEED_IN_CHAMPIONSHIP_TO_SF:_m,FEED_IN_CHAMPIONSHIP:mp,LUCKY_DRAW:ki,ROUND_ROBIN_WITH_PLAYOFF:Io,ROUND_ROBIN:Nn,DECIDER:pU,BACKDRAW:mU,COMPASS_ATTRIBUTES:yf,OLYMPIC_ATTRIBUTES:Af,DRAW:dn,RANDOM:up,TOP_DOWN:En,BOTTOM_UP:li,WATERFALL:di,WIN_RATIO:fi,ROUND_OUTCOME:Gi,MULTI_STRUCTURE_DRAWS:dU,generatedDrawTypes:OF,stageOrder:ks,finishOrder:cU,AGGREGATE_EVENT_STRUCTURES:aU,FINISHING_POSITIONS:sU},ZC=lU;var Ce="tournamentRecords",Ef="policyDefinitions",ie="tournamentRecord",Uh="onlineResource",Ve="drawDefinition",Ph="tieFormatName",Fm="matchUpFormat",no="participantId",Dh="scheduleDates",tb="tournamentId",eb="scheduleDate",rb="roundNumber",Zc="structureId",Uf="participant",ec="matchUpIds",Nh="entryStage",nb="policyType",fU="structures",Pf="eventType",ln="matchUpId",km="tieFormat",tu="inContext",dp="structure",lp="courtIds",ob="personId",fp="venueIds",Df="matchUps",Mh="courtId",Rh="eventId",_n="matchUp",Ch="drawId",fn="error",Do="event",is="param",Nf="uuids",ib="averageMatchUpMinutes",sb="recoveryMinutes",ab="periodLength",cb="number";var Kr="object",Be="array";var tr="_validate",bh="_message",Fr="_invalid",He="_ofType",Gm="_anyOf",Gs="_oneOf";var ub={[Uh]:t=>Yt(Object.keys(t),[Ja,Za,tc]).length===3,[Ph]:t=>t&&to({namedFormat:t}),[Nf]:t=>!t||Array.isArray(t)&&t.every(Vt),[km]:t=>!ar({tieFormat:t}).error,[Pf]:t=>[Yn,qr,_e].includes(t),[Nh]:t=>$c.includes(t)},_F={[Ce]:xt,[ie]:Y,[Ef]:Ku,[Ve]:Z,[no]:oe,[Fm]:Wl,[tb]:ca,[Zc]:Ur,[ec]:rs,[Uf]:wi,[Uh]:lo,[Pf]:Hn,[fU]:Gl,[ln]:sr,[km]:Lo,[dp]:mi,[Mh]:_i,[Df]:Jn,[Rh]:jr,[_n]:hr,[lp]:st,[fp]:st,[Ch]:an,[Do]:vt},xF={[Ce]:Kr,[Ef]:Kr,[ie]:Kr,[Ve]:Kr,[Uh]:Kr,[Dh]:Be,[Uf]:Kr,[ec]:Be,[fU]:Be,[km]:Kr,[dp]:Kr,[lp]:Be,[fp]:Be,[Df]:Be,[_n]:Kr,[Do]:Kr,[Nf]:Be};function rt(t,e,r){if(!t&&!ht(t))return{error:G};if(!e?.length||t?._bypassParamCheck)return{valid:!0};if(!Array.isArray(e))return{error:G};let{paramError:n,errorParam:o}=FF(t,e);if(!n)return{valid:!0};let i=n[tr]&&(n[fn]||n[Fr])||t?.[o]===void 0&&(n[fn]||n[Fr]||_F[o]||G)||G,s=o??(n[Gs]&&Object.keys(n[Gs]).join(", "));return _({info:{param:s,message:n[bh]},result:{error:i},stack:r})}function pb(t,e){let r=Object.keys(t),n=Object.keys(e);return Yt(r,n)}function wF(t,e){if(!e)return;let r=pb(t,e);return r.length!==1?{error:G}:r.reduce((n,o)=>({...n,[o]:!0}),{})}function LF(t,e){if(!e)return;let r=pb(t,e).filter(n=>t[n]);return r.length<1?{error:G}:r.reduce((n,o)=>({...n,[o]:!0}),{})}function FF(t,e){let r,n;return{paramError:e.find(({_ofType:i,_oneOf:s,_anyOf:a,_validate:c,_info:u,...p})=>{let m=s&&wF(t,s);if(m?.error)return m.error;m&&Object.assign(p,m);let d=a&&LF(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&&!Wr(c),h=t[g]!==void 0&&!c&&kF(t,g,i),S=p[g]&&[void 0,null].includes(t[g]),y=I||h||S||c&&t[g]!==void 0&&!GF(t[g],c)||ub[g]&&!ub[g](t[g]);return y&&(r=g,n=u),y});return!l.length||f}),errorParam:r,paramInfo:n}}function kF(t,e,r){return r=r||xF[e]||"string",r==="array"?!Array.isArray(t[e]):typeof t[e]!==r}function GF(t,e){return Wr(e)?e(t):!0}var Vm="DYNAMIC",gi="RANKING",Ii="RATING",hi="SCALE",ho="SEEDING",mb={RANKING:gi,RATING:Ii,SCALE:hi,SEEDING:ho};function la(t){let e=rt(t,[{[Uf]:!0}]);if(e.error)return e;let r=t.participant.timeItems?.filter(({itemType:o})=>o?.startsWith(hi)&&[gi,Ii,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=ut(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===gi&&"rankings"||"ratings";n[l][u]||(n[l][u]=[]),n[l][u].push({scaleValue:a.itemValue,scaleDate:a.itemDate,scaleName:d})}}}return{...C,...n}}function Vi(t){if(t===null)return{};let{source:e,template:r}=t||{};if(!r)return e;let n={};return o(e,r,n),n;function o(i,s,a){if(!i||!s)return;let c=Object.keys(i),u=Object.keys(s),p=Object.assign({},...u.filter(l=>l.indexOf("||")).map(l=>l.split("||").map(f=>({[f]:l}))).flat()),m=u.concat(...Object.keys(p)),d=m.includes("*");for(let l of c)if(m.indexOf(l)>=0||d){let f=p[l]||l,g=s[f]||d,I=i[l];if(typeof g=="object"&&typeof I!="function"&&!Array.isArray(g))if(Array.isArray(I)){let h=I.map(S=>{let T={};return o(S,g,T)!==!1?T:void 0}).filter(Boolean);a[l]=h}else I&&(a[l]={},o(I,g,a[l]));else{let h=i[l];if(Array.isArray(g)&&!g.includes(h))return!1;(s[l]||d&&s[l]!==!1)&&(a[l]=h)}}}}var vh="voluntaryConsolation",Si="competitiveBands",Mf="roundRobinTally",So="positionActions",er="matchUpActions",Rf="rankingPoints",fa="roundNaming",Vs="participant",eu="progression",No="scheduling",ru="avoidance",VF="participant",BF="display",en="scoring",xn="seeding",rc="feedIn",HF="audit",Bm="draws",db={POLICY_TYPE_VOLUNTARY_CONSOLATION:vh,POLICY_TYPE_COMPETITIVE_BANDS:Si,POLICY_TYPE_ROUND_ROBIN_TALLY:Mf,POLICY_TYPE_POSITION_ACTIONS:So,POLICY_TYPE_MATCHUP_ACTIONS:er,POLICY_TYPE_RANKING_POINTS:Rf,POLICY_TYPE_ROUND_NAMING:fa,POLICY_TYPE_PARTICIPANT:Vs,POLICY_TYPE_PROGRESSION:eu,POLICY_TYPE_SCHEDULING:No,POLICY_TYPE_AVOIDANCE:ru,POLICY_TYPE_DISPLAY:BF,POLICY_TYPE_PRIVACY:VF,POLICY_TYPE_FEED_IN:rc,POLICY_TYPE_SCORING:en,POLICY_TYPE_SEEDING:xn,POLICY_TYPE_AUDIT:HF,POLICY_TYPE_DRAWS:Bm};function Go({tournamentParticipants:t=[],policyDefinitions:e={},contextProfile:r,participantId:n,internalUse:o,personId:i}){let s=t.find(c=>n&&c.participantId===n||i&&c.person&&c.person.personId===i),a=J(s,!1,o);if(a){let c=e?.[Vs];if(r?.withScaleValues){let{ratings:u,rankings:p}=la({participant:a});a.rankings=p,a.ratings=u}if(c?.participant)return Vi({template:c.participant,source:a})}return a}var lb="element required",fb="missing name";function gr(t){if(!t||typeof t!="object")return{error:st};if(t.element&&typeof t?.element!="object")return{error:G};if(!t?.name)return{error:st,info:fb};if(!t?.element){if(t.discover&&t.tournamentRecords){for(let e of Object.keys(t.tournamentRecords)){let r=t.tournamentRecords[e],n=gr({element:r,name:t.name});if(n.error)return _({result:n,stack:"removeExtension"})}return{...C}}return{error:st,info:lb}}return t?.element.extensions?(t.element.extensions=t.element.extensions.filter(e=>e?.name!==t.name),{...C}):{...C,info:ve}}function wn({requiredAttributes:t=["name","value"],extension:e}){if(!e||typeof e!="object"||typeof e.name!="string")return!1;let r=Object.keys(e);return t.filter(n=>r.includes(n)).length===t.length}function At(t){if(typeof t!="object")return{error:st};let e="addExtension";if(t?.element&&typeof t.element!="object")return _({result:{error:G},stack:e});if(!wn({extension:t.extension}))return _({result:{error:G,info:"invalid extension"},stack:e});if(!t.element)if(t.discover&&!t.tournamentId&&t.tournamentRecords){for(let o of Object.values(t.tournamentRecords)){let i=At({extension:t.extension,element:o});if(i.error)return _({result:i,stack:e})}return{...C}}else return _({result:{error:st},stack:e});if(t.element.extensions||(t.element.extensions=[]),t?.creationTime??!0){let o=new Date().toISOString();Object.assign(t.extension,{createdAt:o})}let n=t.element.extensions.find(({name:o})=>o===t.extension.name);return n?n.value=t.extension.value:t.extension.value&&t.element.extensions.push(t.extension),{...C}}function Cf(t){return!t||typeof t!="object"?{error:st}:t.tournamentRecord?At({creationTime:t.creationTime,element:t.tournamentRecord,extension:t.extension}):{error:Y}}function gp(t){return!t||typeof t!="object"?{error:st}:t.drawDefinition?At({creationTime:t.creationTime,element:t.drawDefinition,extension:t.extension}):{error:Rr}}function Mo(t){return!t||typeof t!="object"?{error:st}:t.event?At({creationTime:t.creationTime,extension:t.extension,element:t.event}):{error:jr}}function gU(t){if(!t||typeof t!="object")return{error:st};if(!t.participantId)return{error:oe};let e=t.tournamentRecord?.participants||[],r=Go({participantId:t.participantId,tournamentParticipants:e});return r?At({creationTime:t.creationTime,extension:t.extension,element:r}):{error:te}}function bf(t){return!t||typeof t!="object"?{error:st}:t.tournamentRecord?gr({element:t.tournamentRecord,name:t.name}):{error:Y}}function IU(t){return!t||typeof t!="object"?{error:st}:t.drawDefinition?gr({element:t.drawDefinition,name:t.name}):{error:Rr}}function Ip(t){return!t||typeof t!="object"?{error:st}:t?.event?gr({element:t.event,name:t.name}):{error:jr}}function hU(t){if(!t||typeof t!="object")return{error:st};if(!t.participantId)return{error:oe};let e=t.tournamentRecord?.participants||[],r=Go({participantId:t.participantId,tournamentParticipants:e});return r?gr({element:r,name:t.name}):{error:te}}function hp({tournamentRecords:t}){return{tournamentIds:ht(t)?Object.keys(t):[],...C}}var WF="extensionQueries";function dt({discover:t,element:e,name:r,...n}){if(!e||!r){if(t&&n){let s=Object.keys(n).filter(p=>typeof t=="boolean"||Array.isArray(t)&&t.includes(p)).find(p=>Array.isArray(n[p]?.extensions)?n[p].extensions.find(m=>m?.name===r):!1),a=s&&n[s];!a&&n.tournamentRecords&&(a=Object.values(n.tournamentRecords).find(p=>p.extensions?.length));let c=a?.extensions?.find(p=>p?.name===r);return{extension:c,info:c?void 0:ve}}return _({result:{error:st},stack:WF})}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:ve}}var jF="activeSuspension",nu="appliedPolicies",SU="context",Hm="delegatedOutcome",oo="disabled",ga="disableAutoCalc",Wm="disableLinks",jm="display",Ia="drawDeletions",YF="drawProfile",Ym="entryProfile",qF="eventProfile",$F="eventWithdrawalRequests",KF="factory",un="flightProfile",Oh="groupingAttribute",Ro="lineUps",Bs="linkedTournamentsIds",qm="matchUpHistory",_h="participantRepresentatives",ha="personRequests",nc="positionActions",zF="rankingPoints",QF="registration",Mn="roundTarget",ou="scheduleLimits",Vo="scheduleTiming",Sa="schedulingProfile",XF="statusDetail",oc="subOrder",Zo="tally",$m="tieFormatModification",xh={ACTIVE_SUSPENSION:jF,APPLIED_POLICIES:nu,CONTEXT:SU,DELEGATED_OUTCOME:Hm,DISABLED:oo,DISABLE_LINKS:Wm,DISABLE_AUTO_CALC:ga,DISPLAY:jm,DRAW_DELETIONS:Ia,DRAW_PROFILE:YF,ENTRY_PROFILE:Ym,EVENT_PROFILE:qF,EVENT_WITHDRAWAL_REQUESTS:$F,FLIGHT_PROFILE:un,GROUPING_ATTRIBUTE:Oh,LINEUPS:Ro,LINKED_TOURNAMENTS:Bs,MATCHUP_HISTORY:qm,PARTICIPANT_REPRESENTATIVES:_h,PERSON_REQUESTS:ha,POSITION_ACTIONS:nc,RANKING_POINTS:zF,REGISTRATION:QF,ROUND_TARGET:Mn,SCHEDULE_LIMITS:ou,SCHEDULE_TIMING:Vo,SCHEDULING_PROFILE:Sa,STATUS_DETAIL:XF,SUB_ORDER:oc,TALLY:Zo,TIE_FORMAT_MODIFICATIONS:$m,FACTORY:KF},TU=[Hm,oo,ga,Wm,un,Ro,Bs,qm,_h,ha,Mn,ou,Vo,Sa,oc,Zo,$m];function yU({tournamentRecords:t}){if(typeof t!="object"||!Object.keys(t).length)return{error:xt};let e=hp({tournamentRecords:t}),{tournamentIds:r}=e;return r?.length>1?At({tournamentRecords:t,discover:!0,extension:{name:Bs,value:{tournamentIds:r}}}):{...C}}function AU({tournamentRecords:t}){if(typeof t!="object"||!Object.keys(t).length)return{error:xt};let e=gr({name:Bs,tournamentRecords:t,discover:!0});return _({result:e,stack:"unlinkTournaments"})}function EU({tournamentRecords:t,tournamentId:e}){if(typeof t!="object")return{error:G};if(!e)return{error:ca};let r=hp({tournamentRecords:t}),{tournamentIds:n}=r;if(!n.includes(e))return{error:ca};let o;return n.every(i=>{let s=t[i],{extension:a}=dt({element:s,name:Bs});if(!a)return!0;let c=a?.value?.tournamentIds||[];if(!c?.length||c.length===1&&c.includes(e)||i===e){let m=bf({name:Bs,tournamentRecord:s});return m.error&&(o=m.error),m.success}let u=c.filter(m=>m!==e);a.value={tournamentIds:u};let p=Cf({tournamentRecord:s,extension:a});return p.error&&(o=p.error),p.success}),o?{error:o}:{...C}}var PU={};Xt(PU,{getLinkedTournamentIds:()=>iu,getTournamentIds:()=>hp});function iu({tournamentRecords:t}){return typeof t!="object"||!Object.keys(t).length?{error:xt}:{linkedTournamentIds:Object.assign({},...Object.keys(t).map(r=>{let n=t[r],o=n?.tournamentId,{extension:i}=dt({element:n,name:Bs}),s=(i?.value?.tournamentIds||[]).filter(a=>a!==o);return{[r]:s}}))}}var MN={};Xt(MN,{adHocPositionSwap:()=>wP,addAdHocMatchUps:()=>bd,addDrawDefinitionTimeItem:()=>Tg,addFinishingRounds:()=>Ea,addGoesTo:()=>qi,addPlayoffStructures:()=>Gp,addQualifyingStructure:()=>xP,addVoluntaryConsolationStage:()=>CP,addVoluntaryConsolationStructure:()=>pg,allPlayoffPositionsFilled:()=>OS,alternateDrawPositionAssignment:()=>SP,assignDrawPosition:()=>zP,assignDrawPositionBye:()=>Hr,attachConsolationStructures:()=>YP,attachPlayoffStructures:()=>Cg,attachQualifyingStructure:()=>Sg,attachStructures:()=>bg,autoSeeding:()=>X_,automatedPlayoffPositioning:()=>Ks,automatedPositioning:()=>Sc,checkValidEntries:()=>_d,deleteAdHocMatchUps:()=>QP,drawMatic:()=>qd,findDrawDefinition:()=>oT,generateAdHocMatchUps:()=>_u,generateAdHocRounds:()=>Yd,generateAndPopulatePlayoffStructures:()=>Cd,generateDrawDefinition:()=>xa,generateDrawMaticRound:()=>Fd,generateDrawStructuresAndLinks:()=>xd,generateDrawTypeAndModifyDrawDefinition:()=>wd,generateQualifyingStructure:()=>Pd,generateVoluntaryConsolation:()=>PT,getAssignedParticipantIds:()=>Ri,getAvailableMatchUpsCount:()=>vd,getAvailablePlayoffProfiles:()=>Du,getDrawDefinitionTimeItem:()=>zh,getDrawParticipantRepresentativeIds:()=>rT,getDrawStructures:()=>gn,getDrawTypeCoercion:()=>vu,getEligibleVoluntaryConsolationParticipants:()=>eT,getMatchUpsMap:()=>Me,getParticipantIdFinishingPositions:()=>nT,getPositionAssignments:()=>Vp,getPositionsPlayedOff:()=>yc,getSeedingThresholds:()=>ES,getSeedsCount:()=>Ou,getStructureSeedAssignments:()=>on,getTeamLineUp:()=>ms,getValidGroupSizes:()=>bp,isAdHoc:()=>cr,isCompletedStructure:()=>ai,isValidForQualifying:()=>hT,luckyLoserDrawPositionAssignment:()=>lP,modifyDrawDefinition:()=>qP,modifyDrawName:()=>vg,modifySeedAssignment:()=>TP,mutate:()=>ZP,positionActions:()=>IT,pruneDrawDefinition:()=>KP,qualifierDrawPositionAssignment:()=>hP,query:()=>pD,removeDrawPositionAssignment:()=>Eu,removeRoundMatchUps:()=>XP,removeSeededParticipant:()=>_P,removeStructure:()=>RP,renameStructures:()=>MP,resetDrawDefinition:()=>$P,resetVoluntaryConsolationStructure:()=>wU,setDrawParticipantRepresentativeIds:()=>MU,setPositionAssignments:()=>gP,setStructureOrder:()=>NP,setSubOrder:()=>JP,shiftAdHocRounds:()=>fP,swapAdHocRounds:()=>IP,swapDrawPositionAssignments:()=>OP,updateTeamLineUp:()=>Ki,withdrawParticipantAtDrawPosition:()=>mP});var ZP={};Xt(ZP,{adHocPositionSwap:()=>wP,addAdHocMatchUps:()=>bd,addDrawDefinitionTimeItem:()=>Tg,addPlayoffStructures:()=>Gp,addQualifyingStructure:()=>xP,addVoluntaryConsolationStage:()=>CP,addVoluntaryConsolationStructure:()=>pg,alternateDrawPositionAssignment:()=>SP,assignDrawPosition:()=>zP,assignDrawPositionBye:()=>Hr,attachConsolationStructures:()=>YP,attachPlayoffStructures:()=>Cg,attachQualifyingStructure:()=>Sg,attachStructures:()=>bg,automatedPlayoffPositioning:()=>Ks,automatedPositioning:()=>Sc,deleteAdHocMatchUps:()=>QP,luckyLoserDrawPositionAssignment:()=>lP,modifyDrawDefinition:()=>qP,modifyDrawName:()=>vg,modifySeedAssignment:()=>TP,pruneDrawDefinition:()=>KP,qualifierDrawPositionAssignment:()=>hP,removeDrawPositionAssignment:()=>Eu,removeRoundMatchUps:()=>XP,removeSeededParticipant:()=>_P,removeStructure:()=>RP,renameStructures:()=>MP,resetDrawDefinition:()=>$P,resetVoluntaryConsolationStructure:()=>wU,setDrawParticipantRepresentativeIds:()=>MU,setPositionAssignments:()=>gP,setStructureOrder:()=>NP,setSubOrder:()=>JP,shiftAdHocRounds:()=>fP,swapAdHocRounds:()=>IP,swapDrawPositionAssignments:()=>OP,updateTeamLineUp:()=>Ki,withdrawParticipantAtDrawPosition:()=>mP});var NU=t=>e=>t[e],Km=(t=[])=>t.map(Ee).filter(Boolean),vf=(t=[])=>t.map(St).filter(Boolean),St=(t={})=>NU(t)("participantId");var Ee=(t={})=>NU(t)("matchUpId"),su=(t={})=>NU(t)("drawId");function MU({representativeParticipantIds:t,drawDefinition:e}){if(!e)return{error:Rr};if(!Array.isArray(t))return{error:G};let r=vf(e?.entries||[]);return t.length&&Yt(t,r).length<t.length?{error:G}:gp({drawDefinition:e,extension:{name:_h,value:t}})}var vr="ABANDONED",ic="AWAITING_RESULT",Nt="BYE",io="CANCELLED",le="COMPLETED",au="DEAD_RUBBER",Mt="DEFAULTED",be="DOUBLE_DEFAULT",he="DOUBLE_WALKOVER",Ln="IN_PROGRESS",pn="INCOMPLETE",RU="NOT_PLAYED",rr="RETIRED",ss="SUSPENDED",Qt="TO_BE_PLAYED",Ct="WALKOVER",gb=[ic,le,Mt,Ln,pn,rr,ss],wh=[ic,le,Mt,he,be,Ln,pn,rr,ss,Ct],Lh=[vr,ic,Nt,io,le,au,Mt,he,be,Ln,pn,RU,rr,ss,Qt,Ct],Fh=[Nt,he,be,le,Mt,rr,Ct],kh=[vr,ic,io,au,Ln,pn,RU,ss,Qt,void 0],ce=[io,vr,le,au,Mt,he,be,rr,Ct],zm=[vr,le,Mt,he,be,Ln,rr,Ct],Gh=[Ln,pn,ss,Qt],Vh={ABANDONED:vr,AWAITING_RESULT:ic,BYE:Nt,CANCELLED:io,COMPLETED:le,DEAD_RUBBER:au,DEFAULTED:Mt,DOUBLE_WALKOVER:he,DOUBLE_DEFAULT:be,IN_PROGRESS:Ln,INCOMPLETE:pn,NOT_PLAYED:RU,RETIRED:rr,SUSPENDED:ss,TO_BE_PLAYED:Qt,WALKOVER:Ct};function Ti(t,e,r){let n=m=>dt({element:m,name:Mn})?.extension?.value,o=r?.deprioritizeCompleted,i=r?.mode===aU&&zC,s=r?.mode===sU&&cU,a=s||i||ks,c=m=>m?.stage===nt&&m?.stageSequence===1,u=m=>c(m)?-1:a[m?.stage],p=m=>m?.matchUps.every(({matchUpStatus:d})=>ce.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)||(Of(t)||0)-(Of(e)||0)}function Of(t){return(t?.matchUps||[]).reduce((e,r)=>{let n=(r.finishingPositionRange?.winner||[]).reduce((o,i)=>o+i,0);return!e||n<e?n:e},void 0)}function at(t){let e=rt(t,[{[Ve]:!0,[Zc]:!0}]);if(e.error)return e;let{drawDefinition:r,structureId:n}=t,{structures:o}=gn({drawDefinition:r}),i=o?.map(c=>c.structures?[...c.structures].concat(c):c).flat(),s=i?.find(c=>c.structureId===n);if(!s)return{error:kt};let a=s.structureType===cp?i?.find(c=>c.structures?.some(u=>u.structureId===n)):void 0;return{structure:s,containingStructure:a}}function gn({withStageGrouping:t,drawDefinition:e,stageSequences:r,stageSequence:n,roundTarget:o,sortConfig:i,stages:s,stage:a}){let c=!e&&Z||!e?.structures&&Gl||void 0;if(c)return{error:c,structures:[],stageStructures:{}};let u=f=>{let g=dt({element:f,name:Mn})?.extension?.value;return!o||o===g},p=e?.structures?.filter(d).filter(l).filter(u).sort((f,g)=>Ti(f,g,i))??[],m=t?Object.assign({},...$c.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 Bh({drawDefinition:t}){if(!t)return{error:Z};let e={};return{allPositionedParticipantIds:(t.structures||[]).map(n=>{let o=n.stage;e[o]||(e[o]=[]);let{positionAssignments:i}=bt({structure:n}),s=i?.map(St).filter(Boolean)??[];return e[o].push(...s),s}).flat(),stagePositionedParticipantIds:e}}function bt({drawDefinition:t,structureId:e,structure:r}){let n,o=[];if(!r){if(!t)return{positionAssignments:o,error:Z};if({structure:r,error:n}=at({drawDefinition:t,structureId:e}),n)return{positionAssignments:o,error:n}}return r.structures?o=[].concat(...r.structures.map(i=>bt({structure:i}).positionAssignments)):r.positionAssignments?o=r.positionAssignments:n=$A,{positionAssignments:o,error:n}}function Se({drawDefinition:t,structureId:e,structure:r}){let n=bt({drawDefinition:t,structureId:e,structure:r})?.positionAssignments||[],o=n?.filter(u=>u.participantId??u.bye??u.qualifier),i=n&&n?.length===o?.length,s=n?.filter(u=>!u.participantId&&!u.bye&&!u.qualifier),a=n?.filter(u=>!u.participantId&&u.bye),c=n?.filter(u=>!u.participantId&&u.qualifier);return{allPositionsAssigned:i,positionAssignments:n,unassignedPositions:s,assignedPositions:o,qualifierPositions:c,byePositions:a}}var _f="addDrawDefinition",Sp="addMatchUps",ti="addParticipants",xf="addScaleItems",CU="addEvent",Hh="addVenue",yi="audit",Wh="dataIssue",wf="deleteParticipants",Lf="deleteVenue",Ff="deletedDrawIds",kf="deletedMatchUpIds",Gf="modifyDrawDefinition",bU="modifyDrawEntries",vU="modifyEventEntries",Vf="modifyMatchUp",nr="modifyParticipants",Bf="modifyPositionAssignments",Hf="modifySeedAssignments",Bi="modifyTournamentDetail",Ai="modifyVenue",Qm="mutations",jh="publishEvent",OU="publishEventSeeding",_U="publishOrderOfPlay",xU="publishParticipants",Wf="unPublishEvent",jf="unPublishEventSeeding",Yf="unPublishOrderOfPlay",Ib="unPublishParticipants",Tp="updateInContextMatchUp",hb={ADD_DRAW_DEFINITION:_f,ADD_MATCHUPS:Sp,ADD_PARTICIPANTS:ti,ADD_SCALE_ITEMS:xf,ADD_EVENT:CU,ADD_VENUE:Hh,AUDIT:yi,DATA_ISSUE:Wh,DELETE_PARTICIPANTS:wf,DELETE_VENUE:Lf,DELETED_DRAW_IDS:Ff,DELETED_MATCHUP_IDS:kf,MODIFY_DRAW_DEFINITION:Gf,MODIFY_DRAW_ENTRIES:bU,MODIFY_EVENT_ENTRIES:vU,MODIFY_MATCHUP:Vf,MODIFY_PARTICIPANTS:nr,MODIFY_POSITION_ASSIGNMENTS:Bf,MODIFY_SEED_ASSIGNMENTS:Hf,MODIFY_TOURNAMENT_DETAIL:Bi,MODIFY_VENUE:Ai,MUTATIONS:Qm,PUBLISH_EVENT_SEEDING:OU,PUBLISH_EVENT:jh,PUBLISH_ORDER_OF_PLAY:_U,PUBLISH_PARTICIPANTS:xU,UNPUBLISH_EVENT_SEEDING:jf,UNPUBLISH_EVENT:Wf,UNPUBLISH_ORDER_OF_PLAY:Yf,UPDATE_INCONTEXT_MATCHUP:Tp};function Yh(t,e){if(!t)return{error:Z};let r=Date.now();t.updatedAt&&r===new Date(t.updatedAt).getTime()&&(r+=1);let n=new Date(r).toISOString(),o=e?.filter(Boolean);return t.updatedAt=n,t.structures?.filter(Boolean).forEach(i=>{(!o?.length||o?.includes(i.structureId))&&(i.updatedAt=n)}),{...C}}function Co({drawDefinition:t,tournamentId:e,matchUps:r,eventId:n}){return t&&Yh(t),mt({payload:{matchUps:r,tournamentId:e,eventId:n},topic:Sp}),{...C}}function qn({drawDefinition:t,tournamentId:e,matchUpIds:r,eventId:n,action:o}){t&&Yh(t),mt({topic:kf,payload:{tournamentId:e,matchUpIds:r,eventId:n,action:o}});for(let i of r)YI({key:i});return{...C}}function gt({drawDefinition:t,tournamentId:e,structureId:r,context:n,eventId:o,matchUp:i}){return i?(t&&Ot({drawDefinition:t,structureIds:r?[r]:void 0,tournamentId:e,eventId:o}),mt({topic:Vf,payload:{matchUp:i,tournamentId:e,context:n},key:i.matchUpId}),{...C}):(console.log(hr),{error:hr})}function Sb({tournamentId:t,inContextMatchUp:e}){return e?(mt({payload:{inContextMatchUp:e,tournamentId:t},topic:Tp,key:e.matchUpId}),{...C}):{error:hr}}function Ta({tournamentId:t,eventId:e,drawDefinition:r}){return r?(Yh(r),mt({payload:{drawDefinition:r,tournamentId:t,eventId:e},topic:_f,key:r.drawId}),{...C}):(console.log(Z),{error:Z})}function Tb({tournamentId:t,eventId:e,drawId:r}){return mt({payload:{drawId:r,tournamentId:t,eventId:e},topic:Ff,key:r}),YI({key:r}),{...C}}function Ot({drawDefinition:t,tournamentId:e,structureIds:r,eventId:n}){return t?(Yh(t,r),mt({payload:{tournamentId:e,eventId:n,drawDefinition:t},topic:Gf,key:t.drawId}),{...C}):{error:Z}}function qh({drawDefinition:t,tournamentId:e,structure:r,eventId:n}){if(!t)return{error:Z};if(!r)return{error:mi};let o=r.seedAssignments,i=r.structureId,s=t.drawId;return mt({payload:{tournamentId:e,eventId:n,drawId:s,structureId:i,seedAssignments:o},topic:Hf,key:t.drawId}),Ot({structureIds:[i],drawDefinition:t,tournamentId:e,eventId:n}),{...C}}function bo({drawDefinition:t,tournamentId:e,structure:r,event:n}){if(!t)return{error:Z};if(!r)return{error:mi};let o=bt({structure:r}),i=r.structureId,s=t.drawId,a=n?.eventId;return mt({topic:Bf,payload:{positionAssignments:o,tournamentId:e,structureId:i,eventId:a,drawId:s},key:i}),Ot({structureIds:[i],drawDefinition:t,tournamentId:e,eventId:a}),{...C}}function wU({tournamentRecord:t,drawDefinition:e,resetEntries:r,event:n}){if(!e)return{error:Z};let o=e.structures?.find(s=>s.stage===$e);if(!o)return{error:kt};let i=o.matchUps?.map(({matchUpId:s})=>s)||[];return o.positionAssignments=[],o.seedAssignments=[],o.matchUps=[],qn({tournamentId:t?.tournamentId,action:"resetVoluntaryConsolationStructure",matchUpIds:i,drawDefinition:e}),r&&(e.entries=e.entries.filter(s=>s.entryStage!==$e)),Ot({tournamentId:t?.tournamentId,eventId:n?.eventId,drawDefinition:e,structureIds:[o.structureId]}),{...C}}function Xm({drawPositions:t,structure:e}){if([ct,nt].includes(e.stage)&&e.stageSequence===1)return;let{positionAssignments:r}=bt({structure:e});r?.filter(({drawPosition:o})=>t?.includes(o))?.forEach(o=>{At({element:o,extension:{name:Wm,value:!0}})})}function cu(t){let{appliedPolicies:e,positionAction:r,drawDefinition:n}=t;if(e?.audit?.[nc]===!1)return;let{extension:o}=dt({name:nc,element:n}),i=Array.isArray(o?.value)?o?.value??[]:[];if(!i?.length){let a=n.structures.find(c=>c.stage===nt);if(a){let c=bt({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:nc};At({element:n,extension:s})}function as({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 uu(t){let{sides:e,matchUpType:r}=t||{},n=t.potentialParticipants?.length?t.potentialParticipants.flat().map(s=>r===_t?s?.individualParticipantIds||[]:s.participantId).flat():[],o=(e||[]).map(s=>r===_t&&(s?.participant?.individualParticipantIds||[])||s?.participantId&&[s.participantId]||[]).flat();return{individualParticipantIds:o.concat(n).flat(),enteredIndividualParticipantIds:o,potentialIndividualParticipantIds:n}}function Nr(t){return t?.tournamentRecords??(t?.tournamentRecord&&{[t.tournamentRecord.tournamentId]:t.tournamentRecord})??{}}var sc="SIGN_IN_STATUS",LU="SIGNED_OUT",pu="SIGNED_IN",yr="TEAM",Tt="INDIVIDUAL",zr="GROUP",ft="PAIR",wt="TEAM",mu={TEAM_PARTICIPANT:yr,INDIVIDUAL:Tt,GROUP:zr,TEAM:wt,PAIR:ft},yb={INDIVIDUAL:Tt,GROUP:zr,PAIR:ft,TEAM:wt,SIGN_IN_STATUS:sc,SIGNED_OUT:LU,SIGNED_IN:pu};function du({participantsProfile:t,participants:e=[],deepCopy:r}){let n=new Map,o=r!==!1?J(e,t?.convertExtensions,!0):e,i=o.filter(c=>c.participantType===wt),s=o.filter(c=>c.participantType===zr),a=o.filter(c=>c.participantType===ft);return o.forEach(c=>{if(c.participantType===Tt){let{participantId:u}=c;c.groupParticipantIds=[],c.teamParticipantIds=[],c.pairParticipantIds=[],c.groups=[],c.teams=[],i.forEach(p=>{(p?.individualParticipantIds||[]).forEach(m=>{m===u&&!c.teamParticipantIds?.includes(p.participantId)&&(c.teamParticipantIds.push(p.participantId),n.get(p.participantId)||n.set(p.participantId,{participantName:p.participantName,participantId:p.participantId}),c.teams.push({participantRoleResponsibilities:p.participantRoleResponsibilities,participantOtherName:p.participantOtherName,participantName:p.participantName,participantId:p.participantId,teamId:p.teamId}))})}),a.forEach(p=>{(p?.individualParticipantIds||[]).forEach(m=>{m===u&&!c.pairParticipantIds.includes(p.participantId)&&c.pairParticipantIds.push(p.participantId)})}),s.forEach(p=>{(p?.individualParticipantIds||[]).forEach(m=>{m===u&&!c.groupParticipantIds.includes(p.participantId)&&(c.groupParticipantIds.push(p.participantId),c.groups.push({participantRoleResponsibilities:p.participantRoleResponsibilities,participantOtherName:p.participantOtherName,participantName:p.participantName,participantId:p.participantId}))})})}}),{participantsWithGroupings:o,groupInfo:Object.fromEntries(n)}}function FU(t){return t&&typeof String.fromCodePoint<"u"?t.toUpperCase().replace(/./g,e=>String.fromCodePoint(e.charCodeAt(0)+127397)):t}function Ab(t){let e=Object.assign({},...ei.filter(r=>r.ioc).map(r=>({[r.ioc]:r.iso})));return FU(e[t])}var ei=[{ioc:"",iso2:"",iso:"",label:"NONE",phone:""},{ioc:"AND",iso2:"AD",iso:"AND",label:"Andorra",phone:"376"},{ioc:"UAE",iso2:"AE",iso:"ARE",label:"United Arab Emirates",phone:"971"},{ioc:"AFG",iso2:"AF",iso:"AFG",label:"Afghanistan",phone:"93"},{ioc:"ANT",iso2:"AG",iso:"ATG",label:"Antigua and Barbuda",phone:"1-268"},{ioc:"AIA",iso2:"AI",iso:"AIA",label:"Anguilla",phone:"1-264"},{ioc:"ALB",iso2:"AL",iso:"ALB",label:"Albania",phone:"355"},{ioc:"ARM",iso2:"AM",iso:"ARM",label:"Armenia",phone:"374"},{ioc:"ANG",iso2:"AO",iso:"AGO",label:"Angola",phone:"244"},{ioc:"",iso2:"AQ",iso:"ATA",label:"Antarctica",phone:"672"},{ioc:"ARG",iso2:"AR",iso:"ARG",label:"Argentina",phone:"54"},{ioc:"ASA",iso2:"AS",iso:"ASM",label:"American Samoa",phone:"1-684"},{ioc:"AUT",iso2:"AT",iso:"AUT",label:"Austria",phone:"43"},{ioc:"AUS",iso2:"AU",iso:"AUS",label:"Australia",phone:"61",suggested:!0},{ioc:"ARU",iso2:"AW",iso:"ABW",label:"Aruba",phone:"297"},{ioc:"AZE",iso2:"AZ",iso:"AZE",label:"Azerbaijan",phone:"994"},{ioc:"BIH",iso2:"BA",iso:"BIH",label:"Bosnia and Herzegovina",phone:"387"},{ioc:"BAR",iso2:"BB",iso:"BRB",label:"Barbados",phone:"1-246"},{ioc:"BAN",iso2:"BD",iso:"BGD",label:"Bangladesh",phone:"880"},{ioc:"BEL",iso2:"BE",iso:"BEL",label:"Belgium",phone:"32"},{ioc:"BUR",iso2:"BF",iso:"BFA",label:"Burkina Faso",phone:"226"},{ioc:"BUL",iso2:"BG",iso:"BGR",label:"Bulgaria",phone:"359"},{ioc:"BRN",iso2:"BH",iso:"BHR",label:"Bahrain",phone:"973"},{ioc:"BDI",iso2:"BI",iso:"BDI",label:"Burundi",phone:"257"},{ioc:"BEN",iso2:"BJ",iso:"BEN",label:"Benin",phone:"229"},{ioc:"",iso2:"BL",iso:"BLM",label:"Saint Barthelemy",phone:"590"},{ioc:"BER",iso2:"BM",iso:"BMU",label:"Bermuda",phone:"1-441"},{ioc:"BRU",iso2:"BN",iso:"BRN",label:"Brunei Darussalam",phone:"673"},{ioc:"BOL",iso2:"BO",iso:"BOL",label:"Bolivia",phone:"591"},{ioc:"BRA",iso2:"BR",iso:"BRA",label:"Brazil",phone:"55"},{ioc:"BAH",iso2:"BS",iso:"BHS",label:"Bahamas",phone:"1-242"},{ioc:"BHU",iso2:"BT",iso:"BTN",label:"Bhutan",phone:"975"},{ioc:"",iso2:"BV",iso:"BVT",label:"Bouvet Island",phone:"47"},{ioc:"BOT",iso2:"BW",iso:"BWA",label:"Botswana",phone:"267"},{ioc:"BLR",iso2:"BY",iso:"BLR",label:"Belarus",phone:"375"},{ioc:"BIZ",iso2:"BZ",iso:"BLZ",label:"Belize",phone:"501"},{ioc:"CAN",iso2:"CA",iso:"CAN",label:"Canada",phone:"1",suggested:!0},{ioc:"",iso2:"CC",iso:"CCK",label:"Cocos (Keeling) Islands",phone:"61"},{ioc:"CGO",iso2:"CD",iso:"COG",label:"Congo, Republic of the",phone:"242"},{ioc:"CAF",iso2:"CF",iso:"CAF",label:"Central African Republic",phone:"236"},{ioc:"COD",iso2:"CG",iso:"CGD",label:"Congo, Democratic Republic of the",phone:"243"},{ioc:"SUI",iso2:"CH",iso:"CHE",label:"Switzerland",phone:"41"},{ioc:"CIV",iso2:"CI",iso:"CIV",label:"Cote d'Ivoire",phone:"225"},{ioc:"COK",iso2:"CK",iso:"COK",label:"Cook Islands",phone:"682"},{ioc:"CHI",iso2:"CL",iso:"CHL",label:"Chile",phone:"56"},{ioc:"CMR",iso2:"CM",iso:"CMR",label:"Cameroon",phone:"237"},{ioc:"CHN",iso2:"CN",iso:"CHN",label:"China",phone:"86"},{ioc:"COL",iso2:"CO",iso:"COL",label:"Colombia",phone:"57"},{ioc:"CRC",iso2:"CR",iso:"CRI",label:"Costa Rica",phone:"506"},{ioc:"CUB",iso2:"CU",iso:"CUB",label:"Cuba",phone:"53"},{ioc:"CPV",iso2:"CV",iso:"CPV",label:"Cape Verde",phone:"238"},{ioc:"CUW",iso2:"CW",iso:"CUW",label:"Curacao",phone:"599"},{ioc:"CXR",iso2:"CX",iso:"CXR",label:"Christmas Island",phone:"61"},{ioc:"CYP",iso2:"CY",iso:"CYP",label:"Cyprus",phone:"357"},{ioc:"CZE",iso2:"CZ",iso:"CZE",label:"Czech Republic",phone:"420"},{ioc:"GER",iso2:"DE",iso:"DEU",label:"Germany",phone:"49",suggested:!0},{ioc:"DJI",iso2:"DJ",iso:"DJI",label:"Djibouti",phone:"253"},{ioc:"DEN",iso2:"DK",iso:"DNK",label:"Denmark",phone:"45"},{ioc:"DMA",iso2:"DM",iso:"DMA",label:"Dominica",phone:"1-767"},{ioc:"DOM",iso2:"DO",iso:"DOM",label:"Dominican Republic",phone:"1-809"},{ioc:"ALG",iso2:"DZ",iso:"DZA",label:"Algeria",phone:"213"},{ioc:"ECU",iso2:"EC",iso:"ECU",label:"Ecuador",phone:"593"},{ioc:"EST",iso2:"EE",iso:"ESE",label:"Estonia",phone:"372"},{ioc:"EGY",iso2:"EG",iso:"EGY",label:"Egypt",phone:"20"},{ioc:"",iso2:"EH",iso:"ESH",label:"Western Sahara",phone:"212"},{ioc:"ERI",iso2:"ER",iso:"ERI",label:"Eritrea",phone:"291"},{ioc:"ESP",iso2:"ES",iso:"ESP",label:"Spain",phone:"34"},{ioc:"ETH",iso2:"ET",iso:"ETH",label:"Ethiopia",phone:"251"},{ioc:"FIN",iso2:"FI",iso:"FIN",label:"Finland",phone:"358"},{ioc:"FIJ",iso2:"FJ",iso:"FJI",label:"Fiji",phone:"679"},{ioc:"FLK",iso2:"FK",iso:"FLK",label:"Falkland Islands (Malvinas)",phone:"500"},{ioc:"FSM",iso2:"FM",iso:"FSM",label:"Micronesia, Federated States of",phone:"691"},{ioc:"FAR",iso2:"FO",iso:"FRO",label:"Faroe Islands",phone:"298"},{ioc:"FRA",iso2:"FR",iso:"FRA",label:"France",phone:"33",suggested:!0},{ioc:"GAB",iso2:"GA",iso:"GAB",label:"Gabon",phone:"241"},{ioc:"GBR",iso2:"GB",iso:"GBR",label:"United Kingdom",phone:"44"},{ioc:"GRN",iso2:"GD",iso:"GRD",label:"Grenada",phone:"1-473"},{ioc:"GEO",iso2:"GE",iso:"GEO",label:"Georgia",phone:"995"},{ioc:"FGU",iso2:"GF",iso:"GUF",label:"French Guiana",phone:"594"},{ioc:"",iso2:"GG",iso:"GGY",label:"Guernsey",phone:"44"},{ioc:"",iso2:"GH",iso:"GHA",label:"Ghana",phone:"233"},{ioc:"GIB",iso2:"GI",iso:"GIB",label:"Gibraltar",phone:"350"},{ioc:"GRL",iso2:"GL",iso:"GRL",label:"Greenland",phone:"299"},{ioc:"GAM",iso2:"GM",iso:"GMB",label:"Gambia",phone:"220"},{ioc:"GUI",iso2:"GN",iso:"GIN",label:"Guinea",phone:"224"},{ioc:"GUD",iso2:"GP",iso:"GLP",label:"Guadeloupe",phone:"590"},{ioc:"GEQ",iso2:"GQ",iso:"GNQ",label:"Equatorial Guinea",phone:"240"},{ioc:"GRE",iso2:"GR",iso:"GRC",label:"Greece",phone:"30"},{ioc:"",iso2:"GS",iso:"SGS",label:"South Georgia and the South Sandwich Islands",phone:"500"},{ioc:"GUA",iso2:"GT",iso:"GTM",label:"Guatemala",phone:"502"},{ioc:"GUM",iso2:"GU",iso:"GUM",label:"Guam",phone:"1-671"},{ioc:"GBS",iso2:"GW",iso:"GNB",label:"Guinea-Bissau",phone:"245"},{ioc:"GUY",iso2:"GY",iso:"GUY",label:"Guyana",phone:"592"},{ioc:"HKG",iso2:"HK",iso:"HKG",label:"Hong Kong",phone:"852"},{ioc:"",iso2:"HM",iso:"HMD",label:"Heard Island and McDonald Islands",phone:"672"},{ioc:"HON",iso2:"HN",iso:"HND",label:"Honduras",phone:"504"},{ioc:"CRO",iso2:"HR",iso:"HRV",label:"Croatia",phone:"385"},{ioc:"HAI",iso2:"HT",iso:"HTI",label:"Haiti",phone:"509"},{ioc:"HUN",iso2:"HU",iso:"HUN",label:"Hungary",phone:"36"},{ioc:"INA",iso2:"ID",iso:"IDN",label:"Indonesia",phone:"62"},{ioc:"IRL",iso2:"IE",iso:"IRL",label:"Ireland",phone:"353"},{ioc:"ISR",iso2:"IL",iso:"ISR",label:"Israel",phone:"972"},{ioc:"",iso2:"IM",iso:"IMN",label:"Isle of Man",phone:"44"},{ioc:"IND",iso2:"IN",iso:"IND",label:"India",phone:"91"},{ioc:"",iso2:"IO",iso:"IOT",label:"British Indian Ocean Territory",phone:"246"},{ioc:"IRQ",iso2:"IQ",iso:"IRQ",label:"Iraq",phone:"964"},{ioc:"IRI",iso2:"IR",iso:"IRN",label:"Iran, Islamic Republic of",phone:"98"},{ioc:"ISL",iso2:"IS",iso:"ISL",label:"Iceland",phone:"354"},{ioc:"ITA",iso2:"IT",iso:"ITA",label:"Italy",phone:"39"},{ioc:"",iso2:"JE",iso:"JEY",label:"Jersey",phone:"44"},{ioc:"JAM",iso2:"JM",iso:"JAM",label:"Jamaica",phone:"1-876"},{ioc:"JOR",iso2:"JO",iso:"JOR",label:"Jordan",phone:"962"},{ioc:"JPN",iso2:"JP",iso:"JPN",label:"Japan",phone:"81",suggested:!0},{ioc:"KEN",iso2:"KE",iso:"KEN",label:"Kenya",phone:"254"},{ioc:"KGZ",iso2:"KG",iso:"KGZ",label:"Kyrgyzstan",phone:"996"},{ioc:"CAM",iso2:"KH",iso:"KHM",label:"Cambodia",phone:"855"},{ioc:"KIR",iso2:"KI",iso:"KIR",label:"Kiribati",phone:"686"},{ioc:"COM",iso2:"KM",iso:"COM",label:"Comoros",phone:"269"},{ioc:"SKN",iso2:"KN",iso:"KNA",label:"Saint Kitts and Nevis",phone:"1-869"},{ioc:"KOR",iso2:"KP",iso:"KOR",label:"Korea, Democratic People's Republic of",phone:"850"},{ioc:"PRK",iso2:"KR",iso:"PRK",label:"Korea, Republic of",phone:"82"},{ioc:"KUW",iso2:"KW",iso:"KWT",label:"Kuwait",phone:"965"},{ioc:"CAY",iso2:"KY",iso:"CYM",label:"Cayman Islands",phone:"1-345"},{ioc:"KAZ",iso2:"KZ",iso:"KAZ",label:"Kazakhstan",phone:"7"},{ioc:"LAO",iso2:"LA",iso:"LAO",label:"Lao People's Democratic Republic",phone:"856"},{ioc:"LIB",iso2:"LB",iso:"LBN",label:"Lebanon",phone:"961"},{ioc:"LCA",iso2:"LC",iso:"LCA",label:"Saint Lucia",phone:"1-758"},{ioc:"LIE",iso2:"LI",iso:"LIE",label:"Liechtenstein",phone:"423"},{ioc:"SRI",iso2:"LK",iso:"LKA",label:"Sri Lanka",phone:"94"},{ioc:"LBR",iso2:"LR",iso:"LBR",label:"Liberia",phone:"231"},{ioc:"LES",iso2:"LS",iso:"LSO",label:"Lesotho",phone:"266"},{ioc:"LTU",iso2:"LT",iso:"LTU",label:"Lithuania",phone:"370"},{ioc:"LUX",iso2:"LU",iso:"LUX",label:"Luxembourg",phone:"352"},{ioc:"LAT",iso2:"LV",iso:"LVA",label:"Latvia",phone:"371"},{ioc:"LBA",iso2:"LY",iso:"LBY",label:"Libya",phone:"218"},{ioc:"MAR",iso2:"MA",iso:"MAR",label:"Morocco",phone:"212"},{ioc:"MON",iso2:"MC",iso:"MCO",label:"Monaco",phone:"377"},{ioc:"MDA",iso2:"MD",iso:"MDA",label:"Moldova, Republic of",phone:"373"},{ioc:"MNE",iso2:"ME",iso:"MNE",label:"Montenegro",phone:"382"},{ioc:"",iso2:"MF",iso:"MAF",label:"Saint Martin (French part)",phone:"590"},{ioc:"MAD",iso2:"MG",iso:"MDG",label:"Madagascar",phone:"261"},{ioc:"MSH",iso2:"MH",iso:"MHL",label:"Marshall Islands",phone:"692"},{ioc:"MKD",iso2:"MK",iso:"MKD",label:"Macedonia, the Former Yugoslav Republic of",phone:"389"},{ioc:"MLI",iso2:"ML",iso:"MLI",label:"Mali",phone:"223"},{ioc:"MYA",iso2:"MM",iso:"MMR",label:"Myanmar",phone:"95"},{ioc:"MGL",iso2:"MN",iso:"MNG",label:"Mongolia",phone:"976"},{ioc:"MAC",iso2:"MO",iso:"MAC",label:"Macao",phone:"853"},{ioc:"NMA",iso2:"MP",iso:"NMP",label:"Northern Mariana Islands",phone:"1-670"},{ioc:"MRT",iso2:"MQ",iso:"MTQ",label:"Martinique",phone:"596"},{ioc:"MTN",iso2:"MR",iso:"MRT",label:"Mauritania",phone:"222"},{ioc:"MNT",iso2:"MS",iso:"MSR",label:"Montserrat",phone:"1-664"},{ioc:"MLT",iso2:"MT",iso:"MLT",label:"Malta",phone:"356"},{ioc:"MRI",iso2:"MU",iso:"MUS",label:"Mauritius",phone:"230"},{ioc:"MDV",iso2:"MV",iso:"MDV",label:"Maldives",phone:"960"},{ioc:"MAW",iso2:"MW",iso:"MWI",label:"Malawi",phone:"265"},{ioc:"MEX",iso2:"MX",iso:"MEX",label:"Mexico",phone:"52"},{ioc:"MAS",iso2:"MY",iso:"MYS",label:"Malaysia",phone:"60"},{ioc:"MOZ",iso2:"MZ",iso:"MOZ",label:"Mozambique",phone:"258"},{ioc:"NAM",iso2:"NA",iso:"NAM",label:"Namibia",phone:"264"},{ioc:"NCL",iso2:"NC",iso:"NCL",label:"New Caledonia",phone:"687"},{ioc:"NIG",iso2:"NE",iso:"NER",label:"Niger",phone:"227"},{ioc:"NFI",iso2:"NF",iso:"NFK",label:"Norfolk Island",phone:"672"},{ioc:"NGR",iso2:"NG",iso:"NGA",label:"Nigeria",phone:"234"},{ioc:"NCA",iso2:"NI",iso:"NIC",label:"Nicaragua",phone:"505"},{ioc:"NED",iso2:"NL",iso:"NLD",label:"Netherlands",phone:"31"},{ioc:"NOR",iso2:"NO",iso:"NOR",label:"Norway",phone:"47"},{ioc:"NEP",iso2:"NP",iso:"NPL",label:"Nepal",phone:"977"},{ioc:"NRU",iso2:"NR",iso:"NRU",label:"Nauru",phone:"674"},{ioc:"NIU",iso2:"NU",iso:"NIU",label:"Niue",phone:"683"},{ioc:"NZL",iso2:"NZ",iso:"NZL",label:"New Zealand",phone:"64"},{ioc:"OMA",iso2:"OM",iso:"OMN",label:"Oman",phone:"968"},{ioc:"PAN",iso2:"PA",iso:"PAN",label:"Panama",phone:"507"},{ioc:"PER",iso2:"PE",iso:"PER",label:"Peru",phone:"51"},{ioc:"FPO",iso2:"PF",iso:"PYF",label:"French Polynesia",phone:"689"},{ioc:"PNG",iso2:"PG",iso:"PNG",label:"Papua New Guinea",phone:"675"},{ioc:"PHI",iso2:"PH",iso:"PHL",label:"Philippines",phone:"63"},{ioc:"PAK",iso2:"PK",iso:"PAK",label:"Pakistan",phone:"92"},{ioc:"POL",iso2:"PL",iso:"POL",label:"Poland",phone:"48"},{ioc:"SPM",iso2:"PM",iso:"SPM",label:"Saint Pierre and Miquelon",phone:"508"},{ioc:"",iso2:"PN",iso:"PCN",label:"Pitcairn",phone:"870"},{ioc:"PUR",iso2:"PR",iso:"PRI",label:"Puerto Rico",phone:"1"},{ioc:"PLE",iso2:"PS",iso:"PSE",label:"Palestine, State of",phone:"970"},{ioc:"POR",iso2:"PT",iso:"PRT",label:"Portugal",phone:"351"},{ioc:"PLW",iso2:"PW",iso:"PLW",label:"Palau",phone:"680"},{ioc:"PAR",iso2:"PY",iso:"PRY",label:"Paraguay",phone:"595"},{ioc:"QAT",iso2:"QA",iso:"QAT",label:"Qatar",phone:"974"},{ioc:"REU",iso2:"RE",iso:"REU",label:"Reunion",phone:"262"},{ioc:"ROU",iso2:"RO",iso:"ROU",label:"Romania",phone:"40"},{ioc:"SRB",iso2:"RS",iso:"SRB",label:"Serbia",phone:"381"},{ioc:"RUS",iso2:"RU",iso:"RUS",label:"Russia",phone:"7"},{ioc:"RWA",iso2:"RW",iso:"RWA",label:"Rwanda",phone:"250"},{ioc:"KSA",iso2:"SA",iso:"SAU",label:"Saudi Arabia",phone:"966"},{ioc:"SOL",iso2:"SB",iso:"SLB",label:"Solomon Islands",phone:"677"},{ioc:"SEY",iso2:"SC",iso:"SYC",label:"Seychelles",phone:"248"},{ioc:"SUD",iso2:"SD",iso:"SDN",label:"Sudan",phone:"249"},{ioc:"SWE",iso2:"SE",iso:"SWE",label:"Sweden",phone:"46"},{ioc:"SIN",iso2:"SG",iso:"SGP",label:"Singapore",phone:"65"},{ioc:"HEL",iso2:"SH",iso:"SHN",label:"Saint Helena",phone:"290"},{ioc:"SLO",iso2:"SI",iso:"SVN",label:"Slovenia",phone:"386"},{ioc:"",iso2:"SJ",iso:"SJM",label:"Svalbard and Jan Mayen",phone:"47"},{ioc:"SVK",iso2:"SK",iso:"SVK",label:"Slovakia",phone:"421"},{ioc:"SLE",iso2:"SL",iso:"SLE",label:"Sierra Leone",phone:"232"},{ioc:"SMR",iso2:"SM",iso:"SMR",label:"San Marino",phone:"378"},{ioc:"SEN",iso2:"SN",iso:"SEN",label:"Senegal",phone:"221"},{ioc:"SOM",iso2:"SO",iso:"SOM",label:"Somalia",phone:"252"},{ioc:"SUR",iso2:"SR",iso:"SUR",label:"Suriname",phone:"597"},{ioc:"",iso2:"SS",iso:"SSD",label:"South Sudan",phone:"211"},{ioc:"STP",iso2:"ST",iso:"STP",label:"Sao Tome and Principe",phone:"239"},{ioc:"ESA",iso2:"SV",iso:"SLV",label:"El Salvador",phone:"503"},{ioc:"",iso2:"SX",iso:"SMX",label:"Sint Maarten",phone:"1-721"},{ioc:"SYR",iso2:"SY",iso:"SYR",label:"Syria",phone:"963"},{ioc:"",iso2:"SZ",iso:"SWZ",label:"Swaziland",phone:"268"},{ioc:"TKS",iso2:"TC",iso:"TCA",label:"Turks and Caicos Islands",phone:"1-649"},{ioc:"CHA",iso2:"TD",iso:"TCD",label:"Chad",phone:"235"},{ioc:"",iso2:"TF",iso:"ATF",label:"French Southern Territories",phone:"262"},{ioc:"TOG",iso2:"TG",iso:"TGO",label:"Togo",phone:"228"},{ioc:"THA",iso2:"TH",iso:"THA",label:"Thailand",phone:"66"},{ioc:"TJK",iso2:"TJ",iso:"TJK",label:"Tajikistan",phone:"992"},{ioc:"",iso2:"TK",iso:"TKL",label:"Tokelau",phone:"690"},{ioc:"TLS",iso2:"TL",iso:"TLS",label:"Timor-Leste",phone:"670"},{ioc:"TKM",iso2:"TM",iso:"TKM",label:"Turkmenistan",phone:"993"},{ioc:"TUN",iso2:"TN",iso:"TUN",label:"Tunisia",phone:"216"},{ioc:"TGA",iso2:"TO",iso:"TON",label:"Tonga",phone:"676"},{ioc:"TUR",iso2:"TR",iso:"TUR",label:"Turkey",phone:"90"},{ioc:"TTO",iso2:"TT",iso:"TTO",label:"Trinidad and Tobago",phone:"1-868"},{ioc:"TUV",iso2:"TV",iso:"TUV",label:"Tuvalu",phone:"688"},{ioc:"TPE",iso2:"TW",iso:"TWN",label:"Taiwan",phone:"886"},{ioc:"TAN",iso2:"TZ",iso:"TZA",label:"United Republic of Tanzania",phone:"255"},{ioc:"UKR",iso2:"UA",iso:"UKR",label:"Ukraine",phone:"380"},{ioc:"UGA",iso2:"UG",iso:"UGA",label:"Uganda",phone:"256"},{ioc:"USA",iso2:"US",label:"United States",phone:"1",suggested:!0,iso:"USA"},{ioc:"URU",iso2:"UY",iso:"URY",label:"Uruguay",phone:"598"},{ioc:"UZB",iso2:"UZ",iso:"UZB",label:"Uzbekistan",phone:"998"},{ioc:"",iso2:"VA",iso:"VAT",label:"Holy See (Vatican City State)",phone:"379"},{ioc:"VIN",iso2:"VC",iso:"VCT",label:"Saint Vincent and the Grenadines",phone:"1-784"},{ioc:"VEN",iso2:"VE",iso:"VEN",label:"Venezuela",phone:"58"},{ioc:"IVB",iso2:"VG",iso:"VGB",label:"British Virgin Islands",phone:"1-284"},{ioc:"ISV",iso2:"VI",iso:"VIR",label:"US Virgin Islands",phone:"1-340"},{ioc:"VIE",iso2:"VN",iso:"VNM",label:"Vietnam",phone:"84"},{ioc:"VAN",iso2:"VU",iso:"VUT",label:"Vanuatu",phone:"678"},{ioc:"WAF",iso2:"WF",iso:"WLF",label:"Wallis and Futuna",phone:"681"},{ioc:"SAM",iso2:"WS",iso:"WSM",label:"Samoa",phone:"685"},{ioc:"KOS",iso2:"XK",iso:"KOS",label:"Kosovo",phone:"383"},{ioc:"YEM",iso2:"YE",iso:"YEM",label:"Yemen",phone:"967"},{ioc:"MAY",iso2:"YT",iso:"MYT",label:"Mayotte",phone:"262"},{ioc:"RSA",iso2:"ZA",iso:"ZAF",label:"South Africa",phone:"27"},{ioc:"ZAM",iso2:"ZM",iso:"ZMB",label:"Zambia",phone:"260"},{ioc:"ZIM",iso2:"ZW",iso:"ZWE",label:"Zimbabwe",phone:"263"}];function $h({participant:t,withISO2:e,withIOC:r}){let{person:n,individualParticipants:o}=t,i=[n,o?.map(({person:a})=>a)].flat().filter(Boolean);function s(a){let{nationalityCode:c}=a||{};if(c){let u=ei.find(({iso:p})=>p===c);r&&u?.ioc&&!a.iocNationalityCode&&(a.iocNationalityCode=u.ioc),e&&u?.iso2&&!a.iso2NationalityCode&&(a.iso2NationalityCode=u.iso2),u?.label&&!a.countryName&&(a.countryName=u.label)}}i.forEach(s)}function Eb({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?Vi({template:e,source:s}):s)}}}}function To(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:te}}function Kh(t){let{tournamentRecord:e,participantId:r}=t;if(r){let o=To({tournamentRecord:e,participantId:r});return o.participant??o}let n=t.element||t.drawDefinition||t.event||t.tournamentRecord;return n||{error:st}}function rn(t){let{returnPreviousValues:e,itemSubTypes:r,itemType:n}=t,o=Kh(t);if(o.error)return o;if(r&&!Array.isArray(r))return{error:G,context:{itemSubTypes:r}};if(!Array.isArray(o.timeItems))return{error:tf};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=J(i.pop(),!1,!0);if(s){let a={timeItem:s,...C};return e&&Object.assign(a,{previousItems:i}),a}else return{info:ve}}function zh({returnPreviousValues:t,drawDefinition:e,itemSubTypes:r,itemType:n}){if(!e)return{error:an};if(!e.timeItems)return{info:ve};let{timeItem:o,previousItems:i,info:s}=rn({element:e,returnPreviousValues:t,itemSubTypes:r,itemType:n});return o&&{timeItem:o,previousItems:i}||{info:s}}function lu({returnPreviousValues:t,itemSubTypes:e,itemType:r,event:n}){if(!n)return{error:vt};if(!n.timeItems)return{info:ve};let{timeItem:o,previousItems:i,info:s}=rn({returnPreviousValues:t,element:n,itemSubTypes:e,itemType:r});return o&&{timeItem:o,previousItems:i}||{info:s}}function Jm({returnPreviousValues:t,tournamentRecord:e,itemSubTypes:r,itemType:n}){if(!e)return{error:Y};if(!e.timeItems)return{info:ve};let{timeItem:o,previousItems:i,info:s}=rn({element:e,returnPreviousValues:t,itemSubTypes:r,itemType:n});return o&&{timeItem:o,previousItems:i}||{info:s}}function Qh({returnPreviousValues:t,tournamentRecord:e,participantId:r,itemSubTypes:n,itemType:o}){if(!e)return{error:Y};if(!r)return{error:oe};let i=To({tournamentRecord:e,participantId:r});if(i.error)return i;let{participant:s}=i;if(!s?.timeItems)return{info:ve};let{timeItem:a,previousItems:c,info:u}=rn({element:i.participant,returnPreviousValues:t,itemSubTypes:n,itemType:o});return a&&{timeItem:a,previousItems:c}||{info:u}}var JF={[zr]:"groupParticipantIds",[ft]:"pairParticipantIds",[wt]:"teamParticipantIds"},ZF={[zr]:"groups",[wt]:"teams"};function Xh({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&&rk({participantMap:p,participantId:l})}for(let d of r.participants??[]){let l=J(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 h=ek({individualParticipantIds:g,participantCopy:l,participantMap:p,participantType:I,participantId:f});h.missingParticipantIds.length&&u.push(...h.missingParticipantIds)}if(n&&(p[f].participant.signedIn=tk(l)),o){let{ratings:h,rankings:S,seedings:T}=la({participant:l});p[f].participant.seedings=T,p[f].participant.rankings=S,p[f].participant.ratings=h}(c||a)&&$h({participant:p[f].participant,withISO2:a,withIOC:c})}if(t){let d=ht(t)?t:void 0;Eb({participantMap:p,template:d})}let m;return i&&(m=du({participants:Object.values(p).map(({participant:d})=>d),participantsProfile:{convertExtensions:e},deepCopy:!1}).groupInfo),{missingParticipantIds:u,participantMap:p,groupInfo:m}}function tk(t){let{timeItem:e}=rn({itemType:sc,element:t});return e?.itemValue===pu}function ek({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[JF[n]].push(o),[wt,zr].includes(n)){let{participantRoleResponsibilities:c,participantOtherName:u,participantName:p,participantId:m,teamId:d}=e,l=ZF[n];a[l].push({participantRoleResponsibilities:c,participantOtherName:u,participantName:p,participantId:m,teamId:d})}if(n===ft){let c=t.find(u=>u!==s);r[s].pairIdMap[o]=c,r[s].pairIdMap[c]=o}}return{missingParticipantIds:i}}function rk({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:{[Ft]:{...r},[_t]:{...r},[wt]:{...r},...r}}}function Bo({participantsProfile:t,useParticipantMap:e,tournamentRecord:r,contextProfile:n,inContext:o}){if(e)return Xh({...t,...n,tournamentRecord:r});let i=J(r.participants,!1,!0)||[];(t?.withIOC||t?.withISO2)&&i.forEach(a=>$h({participant:a,...t}));let s;if((o||t?.withGroupings)&&i?.length&&({participantsWithGroupings:i,groupInfo:s}=du({participantsProfile:t,deepCopy:!1,participants:i})),t?.withScaleValues&&i?.length)for(let a of i){let{ratings:c,rankings:u}=la({participant:a});a.rankings=u,a.ratings=c}return{participants:i,groupInfo:s}}function yt({onlySpecifiedPolicyTypes:t=!1,policyTypes:e=[],tournamentRecord:r,drawDefinition:n,structure:o,event:i}){if(!Array.isArray(e))return{error:wI};let s={};return r&&a(r),i&&a(i),n&&a(n),o&&a(o),{appliedPolicies:s,...C};function a(c){let p=c?.extensions?.find(m=>m.name===nu)?.value;if(p)for(let m of Object.keys(p))(t?e.includes(m):!e.length||e.includes(m))&&(s[m]=J(p[m],!1,!0))}}function vo({policyTypes:t=[],tournamentRecord:e,drawDefinition:r,structure:n,event:o}){if(!Array.isArray(t))return{error:wI};let{appliedPolicies:i}=yt({tournamentRecord:e,drawDefinition:r,structure:n,event:o}),s={};for(let a of t){let c=i?.[a];c&&(s[a]=c)}return Object.keys(s).length?{policyDefinitions:s}:{info:Fc.message}}var Jh="WALKOVER",kU="RETIRED",Zm="COMPETITIVE",ac="ROUTINE",cc="DECISIVE",td="winRatio";var nk={[Si]:{policyName:"Competitive Bands Default",profileBands:{[cc]:20,[ac]:50}}},ed=nk;function $n({policyDefinitions:t,tournamentRecord:e,contextProfile:r,drawDefinition:n,event:o}){let i={policies:{}};if(!r)return i;let s=vo({tournamentRecord:e,drawDefinition:n,event:o}).policyDefinitions;if(r.withCompetitiveness){let a=t?.[Si]??s?.[Si]??ed[Si];i.policies[Si]=a}return i}function ri({tournamentRecord:t,drawDefinition:e,policyType:r,structure:n,event:o}){if(!t)return{error:Y};let{appliedPolicies:i}=yt({tournamentRecord:t,drawDefinition:e,structure:n,event:o});return i?.[r]?{policy:i[r]}:{info:Fc?.message}}function ya({tournamentRecord:t,categoryName:e,categoryType:r,event:n}){e=e??n?.category?.categoryName??n?.category?.ageCategoryCode,r=r??n?.category?.categoryType??n?.category?.subType;let{policy:o}=ri({policyType:No,tournamentRecord:t,event:n}),s=(t?dt({element:t,name:Vo}).extension:void 0)?.value,c=(n&&dt({name:Vo,element:n}).extension)?.value;return{scheduleTiming:{tournamentScheduling:s,eventScheduling:c,categoryName:e,categoryType:r,policy:o}}}function qf({drawDefinition:t,attributes:e}){let{extension:r}=dt({element:t,name:Ym}),n=r?.value||{};return e.forEach(o=>{Object.keys(o).forEach(i=>{n[i]?Object.assign(n[i],o[i]):n[i]=o[i]})}),r={name:Ym,value:n},gp({drawDefinition:t,extension:r}),{entryProfile:n}}function fu({drawDefinition:t}){let{extension:e}=dt({element:t,name:Ym});return{entryProfile:e?.value||{}}}var nn="ALTERNATE",$f="CONFIRMED",kr="DIRECT_ACCEPTANCE",rd="FEED_IN",Kf="JUNIOR_EXEMPT",cs="LUCKY_LOSER",zf="ORGANISER_ACCEPTANCE",nd="QUALIFIER",ok="REGISTERED",Qf="SPECIAL_EXEMPT",Gr="UNGROUPED",Ei="UNPAIRED",gu="WILDCARD",so="WITHDRAWN",Xf=[$f,kr,Kf,zf,Qf],GU=[rd,cs,nd],ni=[$f,kr,rd,Kf,zf,Qf,gu],Qr=[$f,kr,Kf,cs,nd,zf,Qf,gu],VU=[nn,$f,kr,rd,Kf,cs,zf,nd,ok,Qf,Gr,Ei,gu,so],Ub={ALTERNATE:nn,CONFIRMED:$f,DIRECT_ACCEPTANCE:kr,DIRECT_ENTRY_STATUSES:ni,DRAW_SPECIFIC_STATUSES:GU,EQUIVALENT_ACCEPTANCE_STATUSES:Xf,FEED_IN:rd,JUNIOR_EXEMPT:Kf,LUCKY_LOSER:cs,ORGANISER_ACCEPTANCE:zf,QUALIFIER:nd,SPECIAL_EXEMPT:Qf,STRUCTURE_SELECTED_STATUSES:Qr,UNGROUPED:Gr,UNPAIRED:Ei,VALID_ENTRY_STATUSES:VU,WILDCARD:gu,WITHDRAWN:so};function Jf({stage:t,drawDefinition:e}){let{entryProfile:r}=fu({drawDefinition:e}),n=Object.keys(r).includes(t);if(!n&&$c.includes(t)){let o=[{[t]:{drawSize:void 0,alternates:!0}}];return qf({drawDefinition:e,attributes:o}),!0}return n}function Pb({stage:t,drawDefinition:e}){let{entryProfile:r}=fu({drawDefinition:e});return r[t]?.alternates||0}function Db({stage:t,drawDefinition:e}){let{entryProfile:r}=fu({drawDefinition:e});return r[t]?.wildcardsCount||0}function Zh({stage:t,drawDefinition:e,entryStatus:r}){return e.entries.reduce((n,o)=>o.entryStage===t&&o.entryStatus===r?n+1:n,0)}function Ui({provisionalPositioning:t,placementGroup:e,drawDefinition:r,stageSequence:n,entryStatuses:o,structureId:i,roundTarget:s,stages:a,stage:c}){let u=r.entries?.reduce((p,m)=>{let d=dt({name:Mn,element:m})?.extension?.value,l=c&&m.entryStage===c||a?.length&&m.entryStage&&a.includes(m.entryStage),f=!o||m.entryStatus&&o.includes(m.entryStatus),g=m.entryStageSequence??1;return l&&(!n||g===n)&&f&&(!s||!d||s===d)?p.concat(m):p},[])??[];if(i&&c===de){let{playoffEntries:p,error:m}=ik({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 ik({provisionalPositioning:t,drawDefinition:e,structureId:r}){let n=[],o=(e.links??[]).find(i=>i.linkType===eo&&i.target.structureId===r);if(o){let{finishingPositions:i,structureId:s}=o.source,{structure:a}=at({drawDefinition:e,structureId:s});a?.structureType===Ge&&(a.structures??[]).forEach(u=>{let p=u.positionAssignments??[],{structureId:m}=u,d=m,l=Object.assign({},...p.map(h=>{let{participantId:S}=h,T=dt({element:h,name:Zo}).extension?.value;return T&&S?{[S]:T}:void 0}).filter(Boolean)),g=Object.keys(l).reduce((h,S)=>{let T=l[S],y=T.groupOrder||t&&T.provisionalOrder;return h.includes(y)||h.push(y),h},[]).length===Object.keys(l).length,I=Object.keys(l).filter(h=>{let S=l[h],T=S.groupOrder||t&&S.provisionalOrder;return i?.includes(T)});(!t||g)&&I.forEach(h=>{let S=l[h],{groupOrder:T,provisionalOrder:y,GEMscore:P}=S,U=T||t&&y,A=[...i??[]].sort(me).indexOf(U)+1;n.push({entryStage:de,entryStatus:rd,placementGroup:A,groupingValue:d,participantId:h,GEMscore:P})})})}return{playoffEntries:n}}function Nb({stage:t,drawDefinition:e}){return ni.reduce((r,n)=>(Zh({drawDefinition:e,entryStatus:n,stage:t})||0)+r,0)}function on({provisionalPositioning:t,returnAllProxies:e,drawDefinition:r,structureId:n,structure:o}){let i,s=[];o||({structure:o,error:i}=at({drawDefinition:r,structureId:n}));let a=bt({structure:o}).positionAssignments;if(i||!o)return{seedAssignments:[],error:kt};n||(n=o.structureId);let{stage:c,stageSequence:u}=o,m=c===de&&r&&Ui({provisionalPositioning:t,drawDefinition:r,stageSequence:u,structureId:n,stage:c}),d=m?m.filter(g=>g.placementGroup===1).sort((g,I)=>g.GEMscore<I.GEMscore&&1||g.GEMscore>I.GEMscore&&-1||0).map((g,I)=>{let h=I+1;return{participantId:g.participantId,seedValue:h,seedProxy:!0,seedNumber:h}}):[],l=d?.slice(0,e?d.length:a.length/2);l.length?s=l:o.seedAssignments?s=o.seedAssignments:i=FA;let f=o.seedLimit??o?.positionAssignments?.length;return{seedAssignments:s,stageSequence:u,seedLimit:f,stage:c,error:i}}function oi(t){if(!t)return;let{tieFormatId:e,tieFormats:r}=t;if(t.tieFormat)return t.tieFormat;if(e&&Array.isArray(r))return r.find(n=>n.tieFormatId===e)}function yp({item:t,drawDefinition:e,structure:r,event:n}){if(t){if(t.tieFormat)return t.tieFormat;if(t.tieFormatId){if(e.tieFormat)return e.tieFormat;let o=e.tieFormats?.find(i=>t.tieFormatId===i.tieFormatId);return o||(n.tieFormat?n.tieFormat:n.tieFormats?.find(i=>t.tieFormatId===i.tieFormatId))}if(r.tieFormat)return r.tieFormat;if(r.tieFormatId){let o=e.tieFormats?.find(i=>r.tieFormatId===i.tieFormatId);if(o)return o}}}function We({drawDefinition:t,structure:e,matchUp:r,event:n}){return{tieFormat:yp({item:r,drawDefinition:t,structure:e,event:n})||yp({item:e,drawDefinition:t,structure:e,event:n})||oi(t)||oi(n)}}function Mb({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 Me({drawDefinition:t,structure:e}){let r={},n=[];return(t?.structures??[e]).filter(o=>o&&typeof o=="object").forEach(o=>{if(!o)return;let{structureId:i,matchUps:s,structures:a}=o,c=Array.isArray(a);if(c)c&&a.forEach(u=>{let{structureName:p}=u,m=u.matchUps;r[u.structureId]={matchUps:m,itemStructureIds:[],structureName:p},m&&(n.push(...m),m.forEach(d=>{d.tieMatchUps&&n.push(...d.tieMatchUps)})),r[i]||(r[i]={itemStructureIds:[],matchUps:[]}),r[i].itemStructureIds||(r[i].itemStructureIds=[]),r[i].itemStructureIds.push(u.structureId)});else{let u=s;r[i]={matchUps:u,itemStructureIds:[]},u?.forEach(p=>{n.push(p),p.tieMatchUps&&n.push(...p.tieMatchUps)})}}),{mappedMatchUps:r,drawMatchUps:n}}function ii({mappedMatchUps:t,matchUpsMap:e,structureId:r,inContext:n}){t=e?.mappedMatchUps??t;let o=t[r],i=(o?.itemStructureIds||[]).map(s=>{let{matchUps:a,structureName:c}=t[s];return n?a.map(u=>Object.assign(J(u,!0,!0),{containerStructureId:r,structureId:s,structureName:c})):a}).flat();return(o?.matchUps||[]).concat(...i)}function tS({groupedOrder:t,roundPositionsCount:e}){if(!t||t?.length<=e)return t;let n=Ae(t,t.length/e).map(i=>i.reduce((s,a)=>s+a)),o=n.slice().sort(me);return n.map(i=>o.indexOf(i)+1)}function Zf(t){if(!ht(t))return!1;let{matchUpId:e,drawPositions:r}=t,n=typeof e=="string",o=!r||Array.isArray(r)&&r.length<=2&&r.every(i=>It(i)||i===void 0||i===null);return n&&o}function Vr(t){return Array.isArray(t)?t.every(Zf):!1}function Ke({matchUps:t=[],interpolate:e}){if(!Vr(t))return{roundMatchUps:[],error:G};let r=t.reduce((d,l)=>{let f=typeof l.roundNumber=="string"?pt(l.roundNumber):l.roundNumber;return!l.roundNumber||d.includes(f)?d:d.concat(f)},[]).sort(me).map(d=>{let l=t.filter(h=>h.roundNumber===d),g=l.find(({matchUpType:h})=>h===jt)?l.filter(({matchUpType:h})=>h===jt):l,I=h=>h.sort((S,T)=>me(S.roundPosition,T.roundPosition));return{[d]:I(g)}}),n=t.reduce((d,l)=>{let f=typeof l.roundNumber=="string"?pt(l.roundNumber):l.roundNumber;return d[f]||(d[f]=ot({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=>pt(f)).filter(f=>!isNaN(f))),l=o[d]?.length;if(l>1&&vn(l)){let f=d+1,g=f+l/2;et(f,g).forEach((h,S)=>{o[h]=et(0,l/(2+S*2)).map(()=>({}))})}}let i=0,s=Object.assign({},...Object.keys(o).map(d=>{let l=o[d]?.length,f=o[d]?.filter(I=>!ce.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=>pt(d)).filter(d=>!isNaN(d));u.forEach(d=>{let l=o[d].sort((g,I)=>g.roundPosition-I.roundPosition),f=l.map(g=>g?.drawPositions||[]).flat();if(s[d].roundNumber=d,s[d].roundFactor=s[d].matchUpsCount?i/s[d].matchUpsCount:1,s[d].finishingRound=n[d]?.finishingRound,s[d].roundName=n[d]?.roundName,s[d].abbreviatedRoundName=n[d]?.abbreviatedRoundName,s[d].finishingPositionRange=o[d]?.[0]?.finishingPositionRange,d===1||!s[d-1]){let g=f.sort(me),I=Ae(g,2);s[d].drawPositions=g,s[d].pairedDrawPositions=I}else{let g=s[d-1],I=g.drawPositions,h=g.matchUpsCount/s[d].matchUpsCount,S=Ae(I,h),T=l.map(y=>{let{roundPosition:P}=y,U=[...y.drawPositions||[],void 0,void 0].slice(0,2);if(!P)return U;let A=U?.filter(Boolean)||[];if(!A?.length)return[void 0,void 0];if(d<3&&A?.length===2)return U?.slice().sort(me);let E=Yt(I,A).length!==A?.length;if(A?.length&&E)return A?.length===1?[A[0],void 0]:U?.slice().sort(me);let N=(P-1)*2;return S.slice(N,N+2).map(M=>A?.find(R=>M.includes(R)))});s[d].drawPositions=T?.flat(),s[d].pairedDrawPositions=T}s[d+1]&&s[d+1].matchUpsCount===s[d].matchUpsCount&&(s[d+1].feedRound=!0,s[d+1].feedRoundIndex=c,s[d].preFeedRound=!0,c+=1),s[d]&&!s[d].feedRound&&(s[d].roundIndex=a,a+=1)});let p=!!Object.values(s).find(({matchUpsCount:d})=>!vn(d));return{hasNoRoundPositions:t.some(d=>!d.roundPosition),roundsNotPowerOf2:p,maxMatchUpsCount:i,roundMatchUps:o,roundNumbers:u,roundProfile:s,...C}}function od(t){if(!Array.isArray(t))return"";let e=t.filter(Zt);return e.length?ut([Math.min(...e),Math.max(...e)]).join("-"):""}function Rb({drawDefinition:t,structureId:e,matchUpsMap:r}){if(!t)return{error:Z};if(!e)return{error:Ur};let{structure:n}=at({drawDefinition:t,structureId:e});if(n?.stage!==qe)return{error:Oi,info:"Structure is not CONSOLATION stage"};let{links:o}=t,i=o?.filter(m=>m.target.structureId===e)||[],s=i?.reduce((m,d)=>{let{structureId:l}=d.source;return m.includes(l)?m:m.concat(l)},[])||[],a=Object.assign({},...s.map(m=>{let d=ii({structureId:m,matchUpsMap:r}),f=Ke({matchUps:d}).roundProfile;return{[m]:f}})),c=ii({matchUpsMap:r,structureId:e}),{roundProfile:u}=Ke({matchUps:c}),p={};return i?.forEach(m=>{let{structureId:d,roundNumber:l}=m.source,{feedProfile:f,groupedOrder:g,positionInterleave:I,roundNumber:h}=m.target,S=a[d],T=S[1]?.drawPositions,P=S[l]?.matchUpsCount;if(!P)return;let U=P?T.length/P:0,A=T.length/U,E=T.slice(),N=tS({roundPositionsCount:A,groupedOrder:g}),D=N?.length||1;if(D<=A){let v=T.length/D,O=Ae(E,v);f===li&&O.forEach(x=>x.reverse()),E=N?.length&&N?.map(x=>O[x-1]).flat()||E}let M=Ae(E,U);if(I){let v=et(0,I.interleave).map(()=>{}),O=et(0,I.offset).map(()=>{});M=M.map(F=>[F,...v]),M.unshift(O),M=M.flat(1);let x=M.length-I.offset;M=M.slice(0,x)}p[h]||(p[h]={});let b=u?.[h]?.feedRound?2:1;M.forEach((v,O)=>{let x=1+O*b;p[h][x]||(p[h][x]=od(v))})}),{sourceDrawPositionRanges:p}}function eS({drawDefinition:t}){if(typeof t!="object")return{error:ua};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"&&[qe,de].includes(m)||s[c].push(a);let d=n.filter(l=>l.source.structureId===c&&l.source.roundNumber>=u);for(let l of d){let f=l.source.roundNumber,g=l.target.roundNumber,I=l.target.structureId,h=r.find(T=>T.structureId===I).stage,S=[h,I,g,f].join("|");if(p[S])return;p[S]=!0,i({exitProfile:`${a}-${f}`,structureId:I,exitProfiles:s,targetRound:g,aggregator:p,stage:h})}}}function Cb({drawDefinition:t,roundProfile:e,structureId:r,matchUpsMap:n}){if(!t)return{error:Z};if(!r)return{error:Ur};if(!e){let c=ii({matchUpsMap:n,structureId:r});if({roundProfile:e}=Ke({matchUps:c}),!e)return{error:st}}let i=(Math.min(...e?.[1]?.drawPositions??[])||1)-1,s=Object.keys(e);return{drawPositionsRanges:Object.assign({},...(s||[]).map(c=>{let u=e?.[c]?.matchUpsCount,p=e?.[1]?.drawPositions??[],m=Ae(p,p.length/u),d=m.map(od),l=m.map(S=>S.map(T=>T-i)).map(od),f=s.map(S=>{if(S>c)return;let T=e?.[S]?.drawPositions??[];return Ae(T,T.length/u)}).filter(Boolean),g=et(0,u).map(S=>f.map(T=>T[S]).flat().filter(Boolean).sort(me)).map(S=>ut(S)),I=g.map(S=>lC(S).map(od).join(", ")),h=Object.assign({},...et(0,u).map(S=>({[S+1]:{firstRoundDrawPositionsRange:d[S],firstRoundOffsetDrawPositionsRange:l[S],possibleDrawPositions:g[S],drawPositionsRange:I[S]}})));return{[c]:h}}))}}function id({roundsNotPowerOf2:t,drawDefinition:e,structure:r,matchUps:n}){if(!r)return!1;n=n??r.matchUps??[],t=t??Ke({matchUps:n}).roundsNotPowerOf2;let o=!!r.positionAssignments?.find(({drawPosition:i})=>i)||!!n?.find(({drawPositions:i})=>i?.length);return(!e?.drawType||e.drawType!==ki)&&!r?.structures&&t&&o}function cr({structure:t}){if(!t)return!1;let e=t.matchUps||t.roundMatchUps&&Object.values(t.roundMatchUps).flat(),r=!!e?.find(o=>o?.roundPosition),n=!!e?.find(o=>o?.drawPositions?.length);return!t?.structures&&t?.stage!==$e&&(!e.length||!r&&!n)}var tg={[fa]:{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:{[nt]:"",[de]:"P",[ct]:"Q",[qe]:"C"}}},bb=tg;function vb({roundNamingPolicy:t,drawDefinition:e,structure:r,matchUps:n}){let{roundProfile:o,roundMatchUps:i}=Ke({matchUps:n}),{structureAbbreviation:s,stage:a}=r,c=cr({structure:r}),u=id({structure:r}),p=r.structures,m={},d=tg[fa],l=r.stage===ct,f=l?Math.max(...(e?.structures??[]).filter(b=>b.stage===ct).map(({stageSequence:b})=>b??1),0):0,g=(r.stageSequence??1)<f?r.stageSequence??1:"",I=g&&(t?.affixes?.preQualifying||d.affixes.preQualifying)||"",h=t?.roundNamingMap||d.roundNamingMap||{},S=t?.abbreviatedRoundNamingMap||d.abbreviatedRoundNamingMap||{},T=t?.affixes?.preFeedRound||d.affixes.preFeedRound,y=t?.affixes?.roundNumber||d.affixes.roundNumber,U=(t?.namingConventions||d.namingConventions).round,A=a&&a!==nt?a[0]:"",E=t?.stageConstants||d.stageConstants,N=a&&E?.[a]||A,D=`${I}${N}${g}`,M=o?Object.keys(o):[],R=l&&E?.[ct]?`${E?.[ct]}-`:"";if(p||c||u)Object.assign(m,...M.map(b=>{let v=`${R}${U} ${b}`,O=`${y}${b}`;return{[b]:{roundName:v,abbreviatedRoundName:O}}}));else{let b=l&&(t?.qualifyingFinishMap||d?.qualifyingFinishMap||{});Object.assign(m,...M.map(v=>{if(!o?.[v])return;let{matchUpsCount:O,preFeedRound:x}=o[v],F=O*2,L=b?.[o?.[v].finishingRound]||b&&`${y}${F}`||h[O]||`${y}${F}`,w=x?`-${T}`:"",V=`${L}${w}`,k=[D,s,V].filter(Boolean).join("-"),H=`${S[O]||`${y}${F}`}${w}`,q=[D,s,H].filter(Boolean).join("-");return{[v]:{abbreviatedRoundName:q,roundName:k}}}))}return{roundNamingProfile:m,roundProfile:o,roundMatchUps:i}}var sk=(t,e)=>(t||0)+(e||0);function rS(t,e){let r=Array.isArray(t)?t[0]:t;return isNaN(r)&&Jh||r<=e[cc]&&cc||r<=e[ac]&&ac||Zm}function nS({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(sk)&&(r[n[0]>n[1]?0:1]+=1),{sets:e,games:r,score:t}}function ak(t){let e=Math.min(...t.games),r=Math.max(...t.games);return Math.round(e/r*100)}function oS(t){return t.map(ak).sort().map(e=>parseFloat(e.toFixed(2)))}function Iu({tournamentRecord:t,profileBands:e,matchUp:r}){if(!r)return{error:hr};let{score:n,winningSide:o}=r;if(!o)return{error:G};let i=!e&&t&&ri({policyType:Si,tournamentRecord:t}).policy,s=e||i?.profileBands||ed[Si].profileBands,a=nS({score:n}),c=oS([a]),u=rS(c,s),p=Array.isArray(c)?c[0]:c;return{...C,competitiveness:u,pctSpread:p}}function iS({matchUp:t}){if(!t)return{error:hr};if(t&&!t.sides)return{error:dr};if(t&&!t.hasContext)return{error:Gc};let e=(t.sides??[])?.map(a=>a?.participantId).filter(Boolean),r=t.sides?.filter(a=>a.participant?.participantType===Tt).map(a=>a.participantId).filter(Boolean)??[],o=((t.sides??[])?.map(a=>a.participant?.individualParticipants).filter(Boolean)??[]).map(a=>(a??[]).map(c=>c?.participantId).filter(Boolean)),i=[...r,...o.flat()].filter(Boolean)??[],s=ut(i.concat(e)).filter(Boolean)??[];return{nestedIndividualParticipantIds:o,allRelevantParticipantIds:s,individualParticipantIds:i,sideParticipantIds:e,...C}}var sd="CHECK_IN",ad="CHECK_OUT",ck="SCHEDULE",Hi="SCHEDULE.ASSIGNMENT.VENUE",ao="SCHEDULE.ALLOCATION.COURTS",Ho="SCHEDULE.ASSIGNMENT.COURT",Ap="SCHEDULE.COURT.ORDER",Wi="SCHEDULE.DATE",uk="COMPLETED.DATE",cd="HOME_PARTICIPANT_ID",eg="SCHEDULE.ASSIGN.OFFICIAL",ji="SCHEDULE.TIME.SCHEDULED",Oo="SCHEDULE.TIME.START",Yi="SCHEDULE.TIME.STOP",Pi="SCHEDULE.TIME.RESUME",Di="SCHEDULE.TIME.END",Ep="SCHEDULE.TIME.MODIFIERS",Ob="TO_BE_ANNOUNCED",_b="NEXT_AVAILABLE",xb="FOLLOWED_BY",wb="AFTER_REST",Lb="RAIN_DELAY",pk="NOT_BEFORE",sS=[Ob,_b,xb,wb,Lb],mk="ELIGIBILITY",dk="REGISTRATION",lk="SUSPENSION",fk="MEDICAL",gk="PENALTY",BU="SCALE",HU="RATING",WU="RANKING",rg="SEEDING",_o="PUBLISH",Mr="PUBLIC",xo="STATUS",Ik="MODIFICATION",hk="RETRIEVAL",Sk="other",Fb={MUTUALLY_EXCLUSIVE_TIME_MODIFIERS:sS,AFTER_REST:wb,ALLOCATE_COURTS:ao,ASSIGN_COURT:Ho,ASSIGN_OFFICIAL:eg,ASSIGN_VENUE:Hi,CHECK_IN:sd,CHECK_OUT:ad,COMPLETED_DATE:uk,COURT_ORDER:Ap,ELIGIBILITY:mk,END_TIME:Di,FOLLOWED_BY:xb,MEDICAL:fk,MODIFICATION:Ik,NEXT_AVAILABLE:_b,NOT_BEFORE:pk,OTHER:Sk,PENALTY:gk,PUBLIC:Mr,PUBLISH:_o,RANKING:WU,RATING:HU,RAIN_DELAY:Lb,REGISTRATION:dk,RESUME_TIME:Pi,RETRIEVAL:hk,SCALE:BU,SCHEDULE:ck,SCHEDULED_DATE:Wi,SCHEDULED_TIME:ji,SEEDING:rg,START_TIME:Oo,STATUS:xo,STOP_TIME:Yi,SUSPENSION:lk,TIME_MODIFIERS:Ep,TO_BE_ANNOUNCED:Ob};function us({matchUp:t}){if(!t)return{error:hr};if(!t.hasContext)return{error:Gc};if(!t.sides||t.sides.filter(Boolean).length!==2)return{error:dr};let{nestedIndividualParticipantIds:e,allRelevantParticipantIds:r,sideParticipantIds:n}=iS({matchUp:t}),i=(t.timeItems??[]).filter(u=>u?.itemType&&[sd,ad].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===sd);e?.forEach((u,p)=>{let m=n?.[p],d=u?.length&&u.every(l=>a.includes(l));m&&d&&!a.includes(m)&&a.push(m)}),n?.forEach((u,p)=>{a.includes(u)&&(e?.[p]??[]).forEach(m=>{m&&!a.includes(m)&&a.push(m)})});let c=n?.reduce((u,p)=>a.includes(p)&&u,!0);return{allRelevantParticipantIds:r,allParticipantsCheckedIn:c,checkedInParticipantIds:a,...C}}var ue=t=>e=>{let r=ht(e)&&e?.matchUpType||Vt(e)&&e;return r&&EI[t].includes(r)};function Up(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 Pp(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 aS({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 kb({tournamentScheduling:t,eventScheduling:e,averageMinutes:r,defaultTiming:n,matchUpFormat:o,categoryName:i,categoryType:s,policy:a}){let c=e?.matchUpRecoveryTimes&&Pp({...e,averageMinutes:r,matchUpFormat:o}),u=t?.matchUpRecoveryTimes&&Pp({...t,averageMinutes:r,matchUpFormat:o}),p=a?.matchUpRecoveryTimes&&Pp({...a,averageMinutes:r,matchUpFormat:o}),m=[c,u,p,a?.defaultTimes?.recoveryTimes,n?.recoveryTimes];return aS({categoryName:i,categoryType:s,timesBlockArray:m})}function Gb({matchUpFormat:t,categoryName:e,categoryType:r,defaultTiming:n,tournamentScheduling:o,eventScheduling:i,policy:s}){let a=i?.matchUpAverageTimes&&Up({...i,matchUpFormat:t}),c=o?.matchUpAverageTimes&&Up({...o,matchUpFormat:t}),u=s?.matchUpAverageTimes&&Up({...s,matchUpFormat:t}),p=[a,c,u,s?.defaultTimes?.averageTimes,n?.averageTimes];return aS({categoryName:e,categoryType:r,timesBlockArray:p})}var jU="DOUBLES_SINGLES",YU="SINGLES_DOUBLES",co="total",cS="participantConflict",Aa="matchUpConflict",qU="ISSUE_IDS",uc="CONFLICT",pc="WARNING",uS="ERROR",pS="ISSUE",ng="STATE",Vb={SINGLES_DOUBLES:YU,DOUBLES_SINGLES:jU,TOTAL:co,CONFLICT_MATCHUP_ORDER:Aa,CONFLICT_PARTICIPANTS:cS,SCHEDULE_ISSUE_IDS:qU,SCHEDULE_CONFLICT:uc,SCHEDULE_WARNING:pc,SCHEDULE_ERROR:uS,SCHEDULE_ISSUE:pS,SCHEDULE_STATE:ng};function hu({defaultAverageMinutes:t=90,defaultRecoveryMinutes:e=0,tournamentRecord:r,matchUpFormat:n,categoryName:o,categoryType:i,eventType:s,event:a}){if(!r)return{error:Y};s=s??a?.eventType??Fs;let c={averageTimes:[{minutes:{default:t}}],recoveryTimes:[{minutes:{default:e}}]},{scheduleTiming:u}=ya({tournamentRecord:r,categoryName:o,categoryType:i,event:a}),p={...u,matchUpFormat:n,categoryType:i,defaultTiming:c};return Dp({eventType:s,timingDetails:p})}function Dp({timingDetails:t,eventType:e}){let r=Gb(t),n=Object.keys(r?.minutes||{}),o=r?.minutes&&(n?.includes(e)&&r.minutes[e]||r.minutes.default),i=kb({...t,averageMinutes:o}),s=Object.keys(i?.minutes||{}),a=i?.minutes&&(s?.includes(e)&&i.minutes[e]||i.minutes.default),c=ue(Fs)(e)?YU:jU,u=i?.minutes&&(s?.includes(c)&&i.minutes[c]||a);return{averageMinutes:o,recoveryMinutes:a,typeChangeRecoveryMinutes:u}}function $U(t){return t.createdAt?new Date(t.createdAt).getTime():0}function Wo({timeItems:t,itemType:e}){let r=t.filter(o=>o&&o.itemType===e).sort((o,i)=>$U(o)-$U(i)).pop(),n=r&&$U(r);return{itemValue:r?.itemValue,timeStamp:n}}function mS({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Wo({timeItems:r?.timeItems||[],itemType:ji});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{scheduledTime:n}:e}function Hs({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Wo({timeItems:r?.timeItems||[],itemType:Wi});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{scheduledDate:n}:e}function Np(t){if($I.test(t)){let e=If();return new Date(`${e}T${t}`)}else return new Date(t)}function Bb({matchUp:t}){if(!t)return{error:hr};if(!t.timeItems)return{error:tf};let e=t.timeItems.filter(n=>[Oo,Yi,Pi,Di].includes(n?.itemType)).sort((n,o)=>Np(n.itemValue).getTime()-Np(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 Oo:i=0;break;case Di:if(n.lastValue&&[Oo,Pi].includes(n.lastType)){let u=Np(o.itemValue).getTime()-Np(n.lastValue).getTime();i=n.milliseconds+u}else i=n.milliseconds;break;case Yi:if([Oo,"SCHECULE.TIME.RESUME"].includes(n.lastType)){let u=Np(o.itemValue).getTime()-Np(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([Oo,Pi].includes(r.lastType)){let n=new Date().getTime()-Np(r.lastValue).getTime();r.milliseconds+=n}return{milliseconds:r.milliseconds,time:Tk(r.milliseconds),relevantTimeItems:e}}function Tk(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 Hb({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===Oo&&s;return a&&(!i||r(a)<r(i))?a:i},void 0)?.itemValue}}function mc(t){let{disableNotice:e,venue:r,context:n}=t;if(typeof r!="object")return{error:G};let o=Nr(t);r.venueId||(r.venueId=Dt());let i;for(let s of Object.values(o)){let a=yk({disableNotice:!0,tournamentRecord:s,context:n,venue:r});if(a?.error)return a;i=a.venue}return e||mt({topic:Hh,payload:{venue:r}}),ot({...C,venue:i})}function yk({tournamentRecord:t,disableNotice:e,context:r,venue:n}){return t?n?(t.venues||(t.venues=[]),n.venueId||(n.venueId=Dt()),t.venues.reduce((i,s)=>i||s.venueId===n.venueId,void 0)?{error:SE}:(r&&At({element:n,extension:{value:r,name:SU}}),t.venues.push(n),e||mt({payload:{venue:n,tournamentId:t.tournamentId},topic:Hh}),{...C,venue:J(n)})):{error:st,info:"missing venue"}:{error:Y}}function jo({tournamentRecords:t,tournamentRecord:e,venueId:r}){if(!e)return{error:Y};if(!r)return{error:Jo};let o=(e.venues??[]).reduce((i,s)=>s.venueId===r?s:i,void 0);if(!o&&t){let s=(iu({tournamentRecords:t}).linkedTournamentIds??[])[e.tournamentId];for(let a of s){let c=t[a],u=jo({tournamentRecord:c,venueId:r});if(u.success&&u.venue)return mc({tournamentRecord:e,venue:u.venue}),{...C,venue:o}}}return o?{...C,venue:o}:{error:Li}}function dS({convertExtensions:t,...e}){let{tournamentRecords:r,tournamentRecord:n,venueId:o}=e,i=jo({tournamentRecords:r,tournamentRecord:n,venueId:o});return J(i,t,!0)}function ps({tournamentRecords:t,tournamentRecord:e,courtId:r}){if(!e)return{error:Y};if(!r)return{error:_i};let n="findCourt",o,i;if((e.venues??[]).forEach(s=>{(s.courts??[]).forEach(a=>{a.courtId===r&&(o=a,i=s)})}),o)return{...C,court:o,venue:i};if(t){let a=(iu({tournamentRecords:t}).linkedTournamentIds??[])[e.tournamentId];for(let c of a){let u=t[c],p=ps({tournamentRecord:u,courtId:r});if(p.success)return p.venue&&mc({tournamentRecord:e,venue:p.venue}),{...C,court:o,venue:i}}}return _({result:{error:Os},stack:n})}function lS(t){return J(ps(t),!1,!0)}function ud({tournamentRecord:t,internalUse:e,courtId:r}){if(!t)return{error:Y};if(!r)return{error:_i};let n=ps({tournamentRecord:t,courtId:r});if(n.error)return n;let o=n.court&&(({altitude:i,courtId:s,courtName:a,courtDimensions:c,latitude:u,longitude:p,surfaceCategory:m,surfaceType:d,surfacedDate:l,pace:f,notes:g})=>({altitude:i,courtId:s,courtName:a,courtDimensions:c,latitude:u,longitude:p,surfaceCategory:m,surfaceType:d,surfacedDate:l,pace:f,notes:g}))(n.court);return{...C,courtInfo:J(o,!1,e)}}function dc(t){let e=rt(t,[{[ie]:!0},{venueId:!0,[fn]:Jo}]);if(e.error)return e;let{tournamentRecord:r,venueId:n}=t,o=jo({tournamentRecord:r,venueId:n});if(o.error)return o;let s=(o.venue?.courts??[]).map(u=>(({courtInfo:p})=>({...p}))(ud({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{...C,venueData:J(c,!1,!0)}}function Wb({matchUp:t}){let e=t?.timeItems||[],r=i=>i.createdAt?new Date(i.createdAt).getTime():0;return{endTime:e.reduce((i,s)=>{let a=s.itemType===Di&&s;return a&&(!i||r(a)>r(i))?a:i},void 0)?.itemValue}}function Ht({event:t,eventId:e}){if(!t)return{error:vt};let n=dt({name:un,element:t})?.extension,o=e?J(n?.value,!1,!0):n?.value;return e&&t.drawDefinitions?.forEach(i=>{o?.flights?.forEach(s=>{s.drawId===i.drawId&&Object.assign(s,{drawDefinition:i})})}),{flightProfile:o}}function ze(t){let{tournamentRecord:e,eventId:r,drawId:n}=t,o="findEvent",i={},s=t.tournamentRecords??(e&&{[e.tournamentId]:e})??{},a=Object.values(s).map(({events:u,tournamentId:p})=>(u&&u.forEach(m=>{i[m.eventId]={tournamentId:p}}),u??[])).flat(),c;if(n){let u,p=a.find(m=>{let l=(m?.drawDefinitions??[]).find(f=>f.drawId===n);if(l)u=l,c=i[m.eventId].tournamentId;else{let g=(m&&Ht({event:m})?.flightProfile)?.flights?.find(I=>I.drawId===n);if(g)return c=i[m.eventId].tournamentId,{entries:g.drawEntries,drawName:g.drawName,tournamentId:c,drawId:n}}return l});if(p)return{event:p,drawDefinition:u,tournamentId:c}}if(r){let u=a.find(p=>p?.eventId===r);if(u)c=i[u.eventId].tournamentId;else return{event:void 0,drawDefinition:void 0,..._({result:{error:jr},stack:o})};return{event:u,drawDefinition:void 0,tournamentId:c}}return{event:void 0,drawDefinition:void 0,..._({result:{error:Rr},context:{drawId:n,eventId:r},stack:o})}}function pd(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:hr};if(o&&!p.matchUpType&&!t.matchUpType&&(e||i)&&p.drawId){let U=t.drawDefinition||e?.drawDefinitions?.find(E=>E.drawId===p.drawId);!U&&i&&({drawDefinition:U,event:e}=ze({drawId:p.drawId,tournamentRecord:i}));let A=p.structureId&&U?.structures?.find(({structureId:E})=>E===p.structureId);r=t.matchUpType||A?.matchUpType||U?.matchUpType||e?.eventType!==_e&&e?.eventType}let{milliseconds:m,time:d}=Bb({matchUp:p}),{startTime:l}=Hb({matchUp:p}),{endTime:f}=Wb({matchUp:p}),g,{eventIds:I,drawIds:h}=n??{};if((!I||I.includes(p.eventId))&&(!h||h.includes(p.drawId))){let U=X=>X.createdAt?new Date(X.createdAt).getTime():0,A=new Map,E=p.timeItems?.toSorted((X,lt)=>U(X)-U(lt))??[];for(let X of E)A.set(X.itemType,X.itemValue);let N=A.get(cd),D=A.get(ao),M=A.get(ji),R=A.get(Ep),b=A.get(Wi),v=A.get(eg),O=A.get(Ap),x=A.get(Hi),F=A.get(Ho),L,w,V,k,W,H=p.matchUpType??r;if(a&&M&&o&&H){let X={matchUpFormat:p.matchUpFormat??c,...a};({averageMinutes:w=0,recoveryMinutes:V=0,typeChangeRecoveryMinutes:k=0}=Dp({timingDetails:X,eventType:H})),(w||V)&&(L=f?Yr(Kt(f),V):Yr(M,w+V)),k&&(W=f?Yr(Kt(f),k):Yr(M,w+k))}!b&&M&&(b=Et(M));let q=vm({scheduledDate:b,scheduledTime:M}),$={},B=(i&&x&&dc({tournamentRecord:i,venueId:x}))?.venueData||{};x&&($[x]=B);let{venueName:K,venueAbbreviation:Q,courtsInfo:j}=B,z=(F&&j?.find(X=>X.courtId===F))?.courtName;for(let X of D||[]){if(!i)break;X.venueId&&!$[X.venueid]&&($[X.venueId]=dc({venueId:X.venueId,tournamentRecord:i})?.venueData);let lt=$[X.venueId];X.venueName=lt?.venueName;let it=lt?.courtsInfo?.find(Rt=>Rt.courtId===X.courtId);X.courtName=it?.courtName}g=ot({typeChangeTimeAfterRecovery:W,timeAfterRecovery:L,scheduledDate:b,scheduledTime:M,isoDateString:q,homeParticipantId:N,venueAbbreviation:Q,allocatedCourts:D,timeModifiers:R,venueName:K,venueId:x,courtOrder:O,courtName:z,courtId:F,official:v,typeChangeRecoveryMinutes:k,recoveryMinutes:V,averageMinutes:w,milliseconds:m,startTime:l,endTime:f,time:d})}else g=ot({milliseconds:m,startTime:l,endTime:f,time:d});let{scheduledDate:S}=Hs({matchUp:p}),{scheduledTime:T}=mS({matchUp:p});if(s&&u?.displaySettings?.draws){let U=u.displaySettings.draws,A=(U?.[p.drawId]??U?.default)?.scheduleDetails;if(A){let E=(A.find(N=>S&&N.dates?.includes(S))??A.find(N=>!N.dates?.length))?.attributes;if(E){let N=Object.assign({},...Object.keys(g).map(D=>({[D]:!0})),E);g=Vi({source:g,template:N})}}}let P=p.matchUpStatus&&ce.includes(p.matchUpStatus)&&(Et(f)||Et(S)||Et(T))||void 0;return{schedule:g,endDate:P}}function jb({drawPositions:t,roundProfile:e,roundNumber:r}){let n=[void 0,void 0];if(NI(t))return{orderedDrawPositions:n,displayOrder:n};let o=e?.[r],s=o?.pairedDrawPositions?.find(c=>Fe(c||[],t.filter(Boolean)))??n,a=o?.feedRound;if(DI(t)){let c=[...t].sort(me);return{orderedDrawPositions:c.length===2?c:s,displayOrder:a?c:s}}if(a){let u=[t.find(p=>!isNaN(pt(p))),void 0];return{orderedDrawPositions:u,displayOrder:u}}return{orderedDrawPositions:s,displayOrder:s}}function Mp({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 In({tournamentParticipants:t,tournamentRecord:e,participantIds:r}){let n="getPairedParticipant";if(!t&&!e)return{error:Y};if(!Array.isArray(r)||r.length>2)return{error:wr};if(!r.length)return _({result:{error:Uo},stack:n});t=t??e?.participants??[];let o=t.filter(a=>a.participantType===ft&&Yt(r,a.individualParticipantIds).length===r.length&&a.individualParticipantIds.length===r.length),i=o[0];if(!i)return _({result:{error:te},stack:n});let s=J(o.slice(1),!1,!0);return{participant:J(i),duplicatedPairParticipants:s,...C}}function ms({drawDefinition:t,participantId:e}){if(typeof t!="object")return{error:Z};if(typeof e!="string")return{error:oe};let{extension:r}=dt({element:t,name:Ro});return{lineUp:(r?.value||{})[e]}}function Yb({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}=Mp({collectionPosition:r,collectionId:s,lineUp:d});if(c===_t){if(f?.length<=2){let I=o?.[f[0]]?.pairIdMap?.[f[1]],T=(I&&o[I]?.participant||In({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||ms({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||ms({participantId:d,drawDefinition:i})?.lineUp;return u({attribute:m,lineUp:g,teamParticipant:f})}).filter(Boolean)||{};return{drawPositionCollectionAssignment:Object.assign({},...p)}}function md(t){let e=rt(t,[{[_n]:!0}]);if(e.error)return e;let r=t?.matchUp,n=r?.matchUpType;if(!n&&r?.sides?.length){let s=r.sides.find(({participant:a})=>a)?.participant?.participantType;n=s===Tt&&Ft||s===ft&&_t||s===wt&&wt||void 0}return{matchUpType:n}}function qb({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?Ak({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 Ak({displaySideNumber:t,seedAssignments:e,participantId:r,assignment:n,sideNumber:o}){let i={drawPosition:n.drawPosition,displaySideNumber:t,sideNumber:o};if(r){let s=Ek({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 Ek({seedAssignments:t,participantId:e}){return t?.find(r=>!r.seedProxy&&r.participantId===e)}function KU({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:h,scheduleTiming:S,contextProfile:T,drawDefinition:y,publishStatus:P,scoringActive:U,matchUpTieId:A,isRoundRobin:E,roundProfile:N,sideLineUps:D,structure:M,context:R,matchUp:b,event:v}){c=c??{};let O=We({drawDefinition:y,structure:M,matchUp:b,event:v})?.tieFormat,{roundOffset:x,structureId:F,structureName:L,stage:w,stageSequence:V}=M,{drawId:k,drawName:W,drawType:H}=y??{},q=O?.collectionDefinitions,$=b.collectionId&&q?.find(Ne=>Ne.collectionId===b.collectionId),B=b.collectionId?$?.matchUpFormat:b.matchUpFormat??M?.matchUpFormat??y?.matchUpFormat??v?.matchUpFormat,K=b.matchUpType||$?.matchUpType||M?.matchUpType||y?.matchUpType||!ue(_e)(v?.eventType)&&v?.eventType,Q=l?Nt:b.matchUpStatus,{schedule:j,endDate:tt}=pd({scheduleVisibilityFilters:t,afterRecoveryTimes:s,tournamentRecord:p,usePublishState:g,scheduleTiming:S,drawDefinition:y,matchUpFormat:B,publishStatus:P,matchUpType:K,matchUp:b,event:v}),z=m??b.drawPositions??[],{collectionPosition:X,collectionId:lt,roundPosition:it}=b,Rt=b.roundNumber??c.roundNumber,Lt=lt?Yb({tournamentParticipants:r,positionAssignments:n,collectionPosition:X,participantMap:I,drawDefinition:y,drawPositions:z,collectionId:lt,sideLineUps:D,matchUpType:K}):void 0,De=u?.[Rt]?.roundName||c.roundName,fe=u?.[Rt]?.abbreviatedRoundName||c.abbreviatedRoundName,Re=N?.[Rt]?.feedRound,Or=N?.[Rt]?.preFeedRound,Zr=N?.[Rt]?.roundFactor,lr=o?.[Rt],Xe=it?lr?.[it]:void 0,ee=e?.[Rt],Pt=$?.category?{...R?.category||{},...$.category}:R?.category??v?.category,ae=b.processCodes?.length&&b.processCodes||$?.processCodes?.length&&$?.processCodes||M?.processCodes?.length&&M?.processCodes||y?.processCodes?.length&&y?.processCodes||v?.processCodes?.length&&v?.processCodes||p?.processCodes,re=T?.withCompetitiveness&&Iu({...h,matchUp:b}),pr=b.finishingPositionRange??c.finishingPositionRange,Jt=Ne=>ot(Ne,void 0,!0),Wt={...Jt(R),...Jt({matchUpFormat:b.matchUpType===_e?void 0:B,tieFormat:b.matchUpType!==_e?void 0:O,gender:$?.gender??v?.gender,roundOfPlay:w!==ct&&It(a)&&a+(Rt||0),endDate:b.endDate??tt,discipline:v?.discipline,category:Pt,finishingPositionRange:pr,abbreviatedRoundName:fe,drawPositionsRange:Xe,competitiveProfile:re,structureName:L,stageSequence:V,drawPositions:z,matchUpStatus:Q,processCodes:ae,isRoundRobin:E,matchUpTieId:A,preFeedRound:Or,matchUpType:K,roundFactor:Zr,roundOffset:x,structureId:F,roundNumber:Rt,feedRound:Re,roundName:De,drawName:W,drawType:H,schedule:j,drawId:k,stage:w}),...J(Jt(b),!0,!0)};if(B&&b.score?.scoreStringSide1){let Ne=Ye(B),{bestOf:_r,finalSetFormat:Je,setFormat:Ue}=Ne??{};(Je?.tiebreakSet||Ue?.tiebreakSet||Ue?.timed)&&(Wt.score.sets=Wt.score.sets.sort((Pe,ge)=>Pe.setNumber-ge.setNumber).map((Pe,ge)=>(ge+1===_r?(Je?.tiebreakSet||Je?.timed)&&(Pe.tiebreakSet=!0):(Ue?.tiebreakSet||Ue?.timed)&&(Pe.tiebreakSet=!0),Pe)))}if(Array.isArray(z)){let{orderedDrawPositions:Ne,displayOrder:_r}=jb({drawPositions:z,roundProfile:N,roundNumber:Rt}),Je=N?.[Rt]?.feedRound,Ue=_r[0]!==Ne[0],ge=Ne.concat(void 0,void 0).slice(0,2).map((Ar,fr)=>{let Bn=fr+1,ye=Ue?3-Bn:Bn,Er=qb({...Lt,positionAssignments:n,displaySideNumber:ye,seedAssignments:f,drawPosition:Ar,isFeedRound:Je,sideNumber:Bn}),Zi=b.sides?.find(Yu=>Yu.sideNumber===Bn),Tn=it?(it-1)*2+fr+1:void 0,ts=Tn?ee?.[Tn]:void 0;return Jt({sourceDrawPositionRange:ts,...Zi,...Er})});Object.assign(Wt,J({sides:ge},!0,!0))}if(r&&Wt.sides){let Ne=d?.[Vs],_r=Ue=>{let Pe=I?.[Ue]?.participant;return Pe&&Vi({template:Ne?.participant,source:Pe})};if(Wt.sides.filter(Boolean).forEach(Ue=>{if(Ue.participantId){let Pe=J(_r(Ue.participantId)||(r?Go({policyDefinitions:d,participantId:Ue.participantId,tournamentParticipants:r,internalUse:!0,contextProfile:T}):void 0),void 0,!0);if(Pe){let ge,Ar;if(y?.entries){let fr=y.entries.find(ye=>ye.participantId===Ue.participantId),Bn=v?.entries?.find(ye=>ye.participantId===Ue.participantId);ge=fr?.entryStatus||Bn?.entryStatus,Pe.entryStatus=ge,fr?.entryStage&&(Ar=fr.entryStage,Pe.entryStage=Ar)}i!==!1?Object.assign(Ue,{participant:Pe}):Object.assign(Ue,{participant:{entryStage:Ar,entryStatus:ge}})}}if(Ue?.participant?.individualParticipantIds?.length&&!Ue.participant.individualParticipants?.length){let Pe=Ue.participant.individualParticipantIds.map(ge=>_r(ge)||(r?Go({policyDefinitions:d,tournamentParticipants:r,internalUse:!0,contextProfile:T,participantId:ge}):void 0));i!==!1&&Object.assign(Ue.participant,{individualParticipants:Pe})}}),!Wt.matchUpType){let{matchUpType:Ue}=md({matchUp:Wt});Ue&&Object.assign(Wt,{matchUpType:Ue})}if(T?.inferGender&&(!Wt.gender||Wt.gender===Tr)&&Wt.sides?.length===2&&Wt.matchUpType!==_e){let Ue=Wt.sides.map(Pe=>{if(ue(Ft)(Wt.matchUpType))return Pe.participant?.person?.sex;if(Pe.participant?.individualParticipants?.length===2){let ge=ut(Pe.participant.individualParticipants.map(Ar=>Ar.person?.sex)).filter(Boolean);if(ge.length===1)return ge[0]}});if(Ue.filter(Boolean).length===2&&ut(Ue).length===1){let Pe=Ue[0];Wt.inferredGender=Pe}}}if(Wt.tieMatchUps){let Ne=Wt.matchUpStatus===Nt,_r=Wt.sides?.map(({participant:Je,drawPosition:Ue,sideNumber:Pe,lineUp:ge})=>{let Ar=Je?.participantType===_e&&Je;return{teamParticipant:Ar&&ot({participantRoleResponsibilities:Ar.participantRoleResponsibilities,participantOtherName:Ar.participanOthertName,participantName:Ar.participantName,participantId:Ar.participantId,teamId:Ar.teamId}),drawPosition:Ue,sideNumber:Pe,lineUp:ge}});Wt.tieMatchUps=Wt.tieMatchUps.map(Je=>{let Ue=Wt.matchUpId,ge={finishingPositionRange:Wt.finishingPositionRange,abbreviatedRoundName:fe,roundNumber:Rt,roundName:De};return KU({tieDrawPositions:z,scheduleVisibilityFilters:t,sourceDrawPositionRanges:e,sideLineUps:_r,drawPositionsRanges:o,initialRoundOfPlay:a,roundNamingProfile:u,additionalContext:ge,appliedPolicies:d,isCollectionBye:Ne,usePublishState:g,publishStatus:P,matchUpTieId:Ue,isRoundRobin:E,roundProfile:N,matchUp:Je,event:v,tournamentParticipants:r,positionAssignments:n,tournamentRecord:p,seedAssignments:f,participantMap:I,contextContent:h,scheduleTiming:S,contextProfile:T,drawDefinition:y,scoringActive:U,structure:M,context:R})})}let mr=Wt.sides&&Wt.sides.filter(Ne=>Ne?.participantId).length===2,zt=!Wt.winningSide;if(Object.assign(Wt,{readyToScore:U&&mr&&zt,hasContext:!0}),mr){let{allParticipantsCheckedIn:Ne,checkedInParticipantIds:_r}=us({matchUp:Wt});Object.assign(Wt,{allParticipantsCheckedIn:Ne,checkedInParticipantIds:_r})}return Array.isArray(T?.exclude)&&T?.exclude.forEach(Ne=>delete Wt[Ne]),Wt}function $b({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Wo({timeItems:r?.timeItems||[],itemType:ao});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{allocatedCourts:J(n,!1,!0)}:e}function Kb({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Wo({timeItems:r?.timeItems||[],itemType:Ho});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{courtId:n}:e}function zb({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Wo({timeItems:r?.timeItems||[],itemType:Hi});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{venueId:n}:e}function Ni(t){if(!Array.isArray(t.matchUps))return[];let{matchUps:e,excludeMatchUpStatuses:r,hasParticipantsCount:n,isCollectionMatchUp:o,matchUpStatuses:i,hasWinningSide:s,matchUpFormats:a,roundPositions:c,matchUpFormat:u,collectionIds:p,isMatchUpTie:m,roundNumbers:d,matchUpIds:l,roundNames:f,filterMatchUpTypes:g=!0,filterMatchUpIds:I=!0,stageSequences:h,scheduledDates:S,scheduledDate:T,participantIds:y,processContext:P,tournamentIds:U,matchUpTypes:A,structureIds:E,readyToScore:N,courtIds:D,eventIds:M,venueIds:R,drawIds:b,stages:v}=t,O=Array.isArray(y)?y.filter(Boolean):[],x=Array.isArray(i)?i.filter(Boolean):[],F=Array.isArray(r)?r.filter(Boolean):[],L=Array.isArray(v)?v.filter(Boolean):[],w=Array.isArray(h)?h.filter(Boolean):[],V=Array.isArray(p)?p.filter(Boolean):[],k=Array.isArray(f)?f.filter(Boolean):[],W=Array.isArray(d)?d.filter(Boolean):[],H=Array.isArray(c)?c.filter(Boolean):[],q=Array.isArray(l)&&I?l.filter(Boolean):[],$=Array.isArray(A)&&g?A.filter(Boolean):[],B=Array.isArray(D)?D.filter(Boolean):[],K=Array.isArray(R)?R.filter(Boolean):[],Q=Array.isArray(a)&&a.filter(Boolean)||typeof u=="string"&&[u]||[],j=Array.isArray(S)&&S.filter(Boolean)||typeof T=="string"&&T.length&&[T]||[],tt=Array.isArray(U)?U.filter(Boolean):[],z=Array.isArray(M)?M.filter(Boolean):[],X=Array.isArray(b)?b.filter(Boolean):[],lt=Array.isArray(E)?E.filter(Boolean):[];return e.filter(it=>{if(N&&!ue(xr)(it)&&!it.readyToScore||it.winningSide&&s&&![1,2].includes(it.winningSide)||m!==void 0&&(m&&!it.tieMatchUps||!m&&it.tieMatchUps)||o!==void 0&&(o&&!it.collectionId||!o&&it.collectionId)||L.length&&!L.includes(it.stage)||w.length&&!w.includes(it.stageSequence)||V.length&&(!it.collectionId||!V.includes(it.collectionId))||k.length&&(!it.roundName||!k.includes(it.roundName))||W.length&&(!it.roundNumber||!W.includes(it.roundNumber))||H.length&&(!it.roundPosition||!H.includes(it.roundPosition))||x.length&&(!it.matchUpStatus||!x.includes(it.matchUpStatus))||F.length&&it.matchUpStatus&&F.includes(it.matchUpStatus)||q.length&&!q.includes(it.matchUpId)||$.length&&(!it.matchUpType||!Lc($,it.matchUpType))||Q.length&&(!it.matchUpFormat||!Q.includes(it.matchUpFormat)))return!1;if(j?.length){let{scheduledTime:Rt}=mS({matchUp:it}),{scheduledDate:Lt}=Hs({matchUp:it}),fe=Et(Rt)||Lt;if(!j.find(Re=>jn(Re,fe)))return!1}if(B.length){let{courtId:Rt}=Kb({matchUp:it}),{allocatedCourts:Lt}=$b({matchUp:it}),De=Lt?.map(({courtId:fe})=>fe);if(!B.filter(Boolean).includes(Rt)||De?.includes(Rt))return!1}if(K.length){let{venueId:Rt}=zb({matchUp:it});if(!K.filter(Boolean).includes(Rt))return!1}if(P){if(tt.length&&!tt.includes(it.tournamentId)||z.length&&!z.includes(it.eventId)||X.length&&!X.includes(it.drawId)||lt.length&&!lt.includes(it.structureId))return!1;let Rt=it.sides?.map(({participantId:Lt})=>Lt).filter(Boolean)??[];if(n&&Rt.length<n||O.length&&!O.some(De=>Rt.includes(De)))return!1}return!0})}function Ut(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:mi,roundMatchUps:I,matchUps:[]};let h=Array.isArray(o?.eventIds)?o?.eventIds.filter(Boolean):[],S=Array.isArray(o?.structureIds)?o?.structureIds.filter(Boolean):[],T=Array.isArray(o?.drawIds)?o?.drawIds.filter(Boolean):[],y=!a?.eventId||!h?.length&&!n?.eventIds?.filter(Boolean).length||h?.includes(a.eventId)||n?.eventIds?.includes(a.eventId),P=!S?.length||S.includes(c.structureId),U=!s||!T?.length||T.includes(s.drawId);if(!y||!P||!U)return{collectionPositionMatchUps:g,roundMatchUps:I,matchUps:[]};i&&!d&&(d=$n({tournamentRecord:r,contextProfile:i,drawDefinition:s}));let{appliedPolicies:A}=yt({drawDefinition:s}),E={...t.tournamentAppliedPolicies,...A,...t.policyDefinitions},N=E?.scoring?.structures,D=c.stage&&N?.stage?.[c.stage],M=c.stageSequence&&D?.stageSequence?.[c.stageSequence],R=E?.scoring?.requireAllPositionsAssigned||D?.requireAllPositionsAssigned||M?.requireAllPositionsAssigned;f||(f=Me({drawDefinition:s,structure:c}));let{positionAssignments:b,allPositionsAssigned:v}=Se({structure:c}),O=!R||v,{seedAssignments:x}=on({provisionalPositioning:e,drawDefinition:s,structure:c});m=m??x;let{structureId:F}=c;l=l||s&&eS({drawDefinition:s}).exitProfiles;let L=l?.[F],w=L?.length&&(L[0].split("-").map(B=>parseInt(B)).reduce((B,K)=>B+K)||0),V=!!c.structures,k=ii({matchUpsMap:f,structureId:F,inContext:u}),W=E?.[fa],H=vb({roundNamingPolicy:W,drawDefinition:s,structure:c,matchUps:k}),{roundNamingProfile:q,roundProfile:$}=H;if(I=H?.roundMatchUps??[],o&&(k=Ni({matchUps:k,...o,filterMatchUpTypes:!1,filterMatchUpIds:!1})),u){let{sourceDrawPositionRanges:B}=Rb({drawDefinition:s,matchUpsMap:f,structureId:F}),K=s?Cb({drawDefinition:s,roundProfile:$,matchUpsMap:f,structureId:F}).drawPositionsRanges:void 0,Q=t.tournamentParticipants,j=t.participantMap;!Q?.length&&!j&&r&&({participants:Q=[],participantMap:j}=Bo({participantsProfile:t.participantsProfile,useParticipantMap:t.useParticipantMap,policyDefinitions:t.policyDefinitions,tournamentRecord:r,contextProfile:i,inContext:u})),k=k.map(z=>KU({scheduleVisibilityFilters:t.scheduleVisibilityFilters,hydrateParticipants:t.hydrateParticipants,afterRecoveryTimes:t.afterRecoveryTimes,usePublishState:t.usePublishState,scheduleTiming:t.scheduleTiming,publishStatus:t.publishStatus,sourceDrawPositionRanges:B,tournamentParticipants:Q,positionAssignments:b,drawPositionsRanges:K,initialRoundOfPlay:w,roundNamingProfile:q,tournamentRecord:r,appliedPolicies:E,seedAssignments:m,contextContent:d,participantMap:j,contextProfile:i,drawDefinition:s,scoringActive:O,isRoundRobin:V,roundProfile:$,structure:c,context:a,matchUp:z,event:p})),(k?.filter(z=>Array.isArray(z.tieMatchUps))).forEach(z=>{let X=z.tieMatchUps;k=k.concat(...X)}),n&&(k=Ni({processContext:!0,...n,matchUps:k}))}else(k?.filter(K=>Array.isArray(K.tieMatchUps))).forEach(K=>{let Q=K.tieMatchUps;k=k.concat(...Q)});return o&&(k=Ni({matchUps:k,...o,filterMatchUpTypes:!1,filterMatchUpIds:!1})),(o?.matchUpTypes||o?.matchUpIds)&&(k=Ni({matchUpTypes:o.matchUpTypes,matchUpIds:o.matchUpIds,matchUps:k})),(o?.matchUpTypes||o?.matchUpIds||u)&&(I=Ke({matchUps:k}).roundMatchUps??[]),We({drawDefinition:s,structure:c,event:p})?.tieFormat&&({collectionPositionMatchUps:g}=Mb({matchUps:k})),{collectionPositionMatchUps:g,roundMatchUps:I,isRoundRobin:V,roundProfile:$,matchUpsMap:f,matchUps:k}}function ds({matchUp:t}){return t?ce.includes(t?.matchUpStatus)||t?.winningSide:!1}function Su({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:h,matchUpsMap:S,structureId:T,inContext:y,structure:P,context:U,event:A}){!P&&T&&({structure:P}=at({drawDefinition:I,structureId:T}));let E=Ut({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:h,matchUpsMap:S,structure:P,inContext:y,context:U,event:A}),N=[],D=[],M=[],R=[],b=[];if(E.error)return E;let{matchUps:v}=E,{assignedPositions:O}=Se({structure:P}),x=O?.filter(L=>L.participantId).map(L=>L.drawPosition),F;return v.filter(L=>{let w=u?.matchUpTypes?.length===1&&u.matchUpTypes[0]===jt;return!(L.matchUpType!==jt&&w)}).forEach(L=>{if(L.matchUpStatus===vr){N.push(L);return}L.matchUpType===jt&&(F=!0);let w=L.collectionId,V=w&&L.sides?.every(K=>K.participantId),k=!w&&L.drawPositions?.filter(Boolean).length===2,W=!w&&L.drawPositions?.every(K=>x?.includes(K)),H=O?.filter(K=>K.bye).map(K=>K.drawPosition),q=!w&&L.drawPositions?.find(K=>H?.includes(K)),B=Gh.includes(L.matchUpStatus)&&(V||k&&(!t||W));return q?b.push(L):ds({matchUp:L})?D.push(L):B?M.push(L):R.push(L)}),{includesTeamMatchUps:F,abandonedMatchUps:N,completedMatchUps:D,upcomingMatchUps:M,pendingMatchUps:R,byeMatchUps:b,structure:P}}function Qb({drawDefinition:t,roundNumber:e,structureId:r}){if(!t)return{error:Z};if(!r)return{error:Ur};let{links:n}=Ws({drawDefinition:t,structureId:r}),o=n.source.reduce((s,a)=>!a.source.roundNumber||a.source.roundNumber===e?s.concat(a):s,[]),i=n.target.reduce((s,a)=>!a.target.roundNumber||a.target.roundNumber===e?s.concat(a):s,[]);return{links:{source:o,target:i}}}function fS({finishingPositions:t,linkCondition:e,linkType:r,source:n}){let o=n.find(i=>{let s=!i.source?.finishingPositions||!t||Fe(t,i.source?.finishingPositions);return e===i.linkCondition&&s&&i.linkType===r});return[fo,ro].includes(o?.linkType)&&!o?.source?.roundNumber?_({result:{error:G},stack:"getTargetLink",context:o}):o}function Ws({drawDefinition:t,structureId:e,roundNumber:r}){return t?e?{links:(t.links||[]).filter(Boolean).reduce((i,s)=>(s.source?.structureId===e&&(!r||s.source.roundNumber===r)&&(i.source=i.source.concat(s)),s.target?.structureId===e&&(!r||s.target.roundNumber===r)&&(i.target=i.target.concat(s)),i),{source:[],target:[]})}:{error:Ur}:{error:Z}}function Xb({structureMatchUps:t,matchUp:e}){let{roundNumber:r,roundPosition:n}=e,o=t.filter(s=>s.roundNumber===r&&!s.matchUpTieId),i=t.filter(s=>s.roundNumber===r+1&&!s.matchUpTieId);if(i.length){let s;return i.length===o.length?s=i.find(a=>a.roundPosition===n):i.length===o.length/2&&(s=i.find(a=>a.roundPosition===Math.ceil(n/2))),{matchUp:s}}return{message:"no progression found"}}function gS({sourceRoundMatchUpCount:t,inContextDrawMatchUps:e,sourceRoundPosition:r,drawDefinition:n,targetLink:o}){if(!o)return{error:kl};let{target:{structureId:i,feedProfile:s,groupedOrder:a,roundNumber:c,positionInterleave:u}}=o,{structure:p}=at({drawDefinition:n,structureId:i}),{positionAssignments:m}=bt({structure:p}),l=(e?.filter(D=>D.structureId===p?.structureId)).filter(D=>D.roundNumber===c&&!D.matchUpTieId),f=l.length,g=et(1,f+1),I=f/t,h=Math.ceil(I*r),S=1-r%2;if(u?.interleave&&I!==.5){let D=u.offset+(r-1)*u.interleave,M=r+D;h=Math.ceil(M/2),S=1-M%2}let T=g,y=g[h-1],P=tS({roundPositionsCount:g.length,groupedOrder:a}),U=P?.length||1;if(U<=g.length){let D=f/U,M=Ae(g,D);s===li&&M.forEach(R=>R.reverse()),T=P?.length&&P?.map(R=>M[R-1]).flat()||T}s===En?y=T[h-1]:s===li?((!P?.length||U>g.length)&&(h=l.length+1-h),y=T[h-1]):s===up&&Pr()&&console.log(tp,{feedProfile:s});let A=y&&l.reduce((D,M)=>M.roundPosition===y?M:D,void 0),E;A?.feedRound?(S=0,E=Math.min(...(A.drawPositions||[]).filter(Boolean))):E=A?.drawPositions?.length===2&&A?.drawPositions[S];let N=m?.find(({drawPosition:D})=>D===E);if(N){let{extension:D}=dt({element:N,name:Wm});if(D?.value)return{disabledDrawPosition:E}}return{matchUp:A,targetDrawPosition:E,matchUpDrawPositionIndex:S}}function ur({inContextDrawMatchUps:t=[],useTargetMatchUpIds:e,inContextMatchUp:r,drawDefinition:n,matchUpId:o}){let i=r;t.length&&!i&&(i=t.find(c=>c.matchUpId===o));let{structure:s}=at({structureId:i?.structureId,drawDefinition:n});return s?.finishingPosition===Gi?Uk({inContextDrawMatchUps:t,useTargetMatchUpIds:e,drawDefinition:n,structure:s,matchUp:i}):Pk({matchUp:i})}function Uk({inContextDrawMatchUps:t,useTargetMatchUpIds:e,drawDefinition:r,structure:n,matchUp:o}){let{winnerMatchUpId:i,loserMatchUpId:s}=o,{links:a}=Qb({roundNumber:o.roundNumber,structureId:n.structureId,drawDefinition:r}),c=a?.source,u=fS({source:c,linkType:fo}),p=fS({linkCondition:On,linkType:ro,source:c}),m=fS({source:c,linkType:ro}),d=p&&m;m||(m=p);let l=u?.target?.feedProfile,f=m?.target?.feedProfile,g=p?.target?.feedProfile,I,h,S,T,y,P,U,A,E,N;if(e&&(i||s)&&(U=i&&l!==dn&&t.find(({matchUpId:R})=>R===i),T=s&&f!==dn&&t.find(({matchUpId:R})=>R===s),U||T))return{matchUp:o,targetLinks:{loserTargetLink:m,winnerTargetLink:u},targetMatchUps:{loserMatchUp:T,winnerMatchUp:U}};let{roundPosition:D}=o;N=N||t.filter(R=>R.structureId===n.structureId);let M=N.reduce((R,b)=>b.roundNumber===o.roundNumber&&!b.matchUpTieId?R+1:R,0);return m&&!T&&f!==dn&&({matchUpDrawPositionIndex:P,targetDrawPosition:y,matchUp:T}=gS({targetLink:m,sourceRoundMatchUpCount:M,inContextDrawMatchUps:t,sourceRoundPosition:D,drawDefinition:r})),d&&g!==dn&&({matchUpDrawPositionIndex:S,targetDrawPosition:h,matchUp:I}=gS({targetLink:p,sourceRoundMatchUpCount:M,inContextDrawMatchUps:t,sourceRoundPosition:D,drawDefinition:r})),u&&!U&&l!==dn&&({matchUpDrawPositionIndex:E,targetDrawPosition:A,matchUp:U}=gS({targetLink:u,sourceRoundMatchUpCount:M,inContextDrawMatchUps:t,sourceRoundPosition:D,drawDefinition:r})),U||(N=N||t.filter(R=>R.structureId===n.structureId),{matchUp:U}=Xb({structureMatchUps:N,matchUp:o})),ot({matchUp:o,targetLinks:{loserTargetLink:m,winnerTargetLink:u,byeTargetLink:p},targetMatchUps:{winnerMatchUpDrawPositionIndex:E,loserMatchUpDrawPositionIndex:P,byeMatchUpDrawPositionIndex:S,winnerTargetDrawPosition:A,loserTargetDrawPosition:y,byeTargetDrawPosition:h,winnerMatchUp:U,loserMatchUp:T,byeMatchUp:I},targetMatchUpIds:!!(i||s)})}function Pk({matchUp:t}){return{targetLinks:{loserTargetLink:void 0,winnerTargetLink:void 0},targetMatchUps:{loserMatchUp:void 0,winnerMatchUp:void 0},matchUp:t}}function Jb({drawDefinition:t,inContextDrawMatchUps:e}){let r={};return e.forEach(n=>{let{matchUpId:o,structureId:i,drawPositions:s=[]}=n,{structure:a}=at({drawDefinition:t,structureId:i});if(a?.finishingPosition===fi){let{roundNumber:c}=n,u=c&&pt(c)+1,p=a.matchUps??[],{roundMatchUps:m}=Ke({matchUps:p});if(u&&m?.[u]){let d=[...s].sort(me).map((l,f)=>{let g=m[u].find(I=>I.drawPositions?.includes(l));return{matchUpId:g?.matchUpId,roundNumber:u,schedule:g?.schedule,sideNumber:f+1,structureName:a.structureName}});Object.assign(n,{sidesTo:d})}}else{let c=ur({useTargetMatchUpIds:!0,inContextDrawMatchUps:e,inContextMatchUp:n,drawDefinition:t,matchUpId:o}),{winnerMatchUp:u}=c.targetMatchUps,{loserMatchUp:p}=c.targetMatchUps;!n.winnerMatchUpId&&u&&(n.winnerMatchUpId=u.matchUpId),!n.loserMatchUpId&&p&&(n.loserMatchUpId=p.matchUpId);let m=zU({upcomingMatchUp:u}),d=zU({upcomingMatchUp:p});if(n.matchUpStatus!==Nt&&p?.matchUpStatus===Nt){let{matchUp:f}=Zb({matchUp:p,drawDefinition:t,inContextDrawMatchUps:e})||{};d=f&&zU({upcomingMatchUp:f})||d}let l=n.schedule?.timeAfterRecovery;if(l&&(m?.schedule?.scheduledTime&&qt(m.schedule.scheduledTime)<qt(l)&&(r[m.matchUpId]=n.matchUpId,m.schedule.scheduleConflict=n.matchUpId),d?.schedule?.scheduledTime&&qt(d.schedule.scheduledTime)<qt(l)&&(r[d.matchUpId]=n.matchUpId,d.schedule.scheduleConflict=n.matchUpId)),Object.assign(n,{winnerTo:m,loserTo:d}),n.drawPositions?.filter(Boolean).length){let g=c.targetLinks?.loserTargetLink?.linkCondition===On,I=Dk(n);if(I.length){let h=vf(u?.sides),S=vf(p?.sides),y=I.find(({participantId:A})=>h.includes(A))?[]:I,U=I.find(({participantId:A})=>S.includes(A))?[]:I;p&&g&&U.length<2&&U.push({bye:!0,tbd:!0}),y?.length&&u&&(!c.targetMatchUpIds&&u&&(u=e.find(({matchUpId:A})=>A===u.matchUpId)),u.potentialParticipants||(u.potentialParticipants=[]),u.potentialParticipants.push(y)),U?.length&&p&&(c.targetMatchUpIds||(u=e.find(({matchUpId:A})=>A===p.matchUpId)),p.potentialParticipants||(p.potentialParticipants=[]),p.potentialParticipants.push(U))}}}}),Object.keys(r).length&&e.forEach(n=>{Object.keys(r).includes(n.matchUpId)&&(n.schedule.scheduleConflict=r[n.matchUpId])}),{scheduleConflictMatchUpIds:r}}function Dk(t){return t?.sides?.map(({participant:e,participantId:r,qualifier:n})=>e||r&&{participantId:r}||n&&{qualifier:n}).filter(Boolean)||[]}function Zb({matchUp:t,drawDefinition:e,inContextDrawMatchUps:r}){let{matchUpId:n,matchUpStatus:o,structureId:i}=t||{};if(!t||!i||t?.matchUpStatus===Qt)return{matchUp:t};if(o===Nt){let s;return t.winnerMatchUpId?s=r.find(({matchUpId:a})=>a===t.winnerMatchUpId):{winnerMatchUp:s}=ur({inContextDrawMatchUps:r,drawDefinition:e,matchUpId:n})?.targetMatchUps||{},Zb({matchUp:s,drawDefinition:e,inContextDrawMatchUps:r})}return{matchUp:void 0}}function zU(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 se(t){let e="getAllDrawMatchUps";Object.assign(t,{requireParticipants:!1});let r=js(t);if(r.error)return _({result:r,stack:e});let{abandonedMatchUps:n,completedMatchUps:o,upcomingMatchUps:i,pendingMatchUps:s,byeMatchUps:a,matchUpsMap:c}=r;return{matchUps:(n??[]).concat(...o??[],...i??[],...s??[],...a??[]),matchUpsMap:c}}function js(t){if(!t?.drawDefinition)return{error:Z};let{tournamentParticipants:e,contextContent:r,matchUpsMap:n}=t,{scheduleVisibilityFilters:o,tournamentAppliedPolicies:i,requireParticipants:s,participantsProfile:a,afterRecoveryTimes:c,policyDefinitions:u,tournamentRecord:p,usePublishState:m,contextFilters:d,matchUpFilters:l,scheduleTiming:f,participantMap:g,publishStatus:I,contextProfile:h,drawDefinition:S,nextMatchUps:T,inContext:y,context:P,event:U}=t,A=[],E=[],N=[],D=[],M=[];h&&!r&&(r=$n({policyDefinitions:u,tournamentRecord:p,contextProfile:h,event:U}));let R;!e?.length&&p&&(e=p?.participants,(y||a?.withGroupings)&&e?.length&&({participantsWithGroupings:e,groupInfo:R}=du({participants:e,participantsProfile:a})));let{structures:b}=gn({drawDefinition:S});if(!b)return{error:kt};n||(n=Me({drawDefinition:S}));let v=S&&eS({drawDefinition:S}).exitProfiles;b.forEach(F=>{let{byeMatchUps:L=[],pendingMatchUps:w=[],upcomingMatchUps:V=[],completedMatchUps:k=[],abandonedMatchUps:W=[]}=Su({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:h,drawDefinition:S,exitProfiles:v,matchUpsMap:n,structure:F,context:P,event:U});A=A.concat(...W),E=E.concat(...k),N=N.concat(...V),D=D.concat(...w),M=M.concat(...L)});let O=F=>(!l&&!T&&!d||(l&&(F=Ni({matchUps:F,...l})),d&&(F=Ni({matchUps:F,...d,processContext:!0}))),F),x={abandonedMatchUps:O(A),completedMatchUps:O(E),upcomingMatchUps:O(N),pendingMatchUps:O(D),byeMatchUps:O(M),matchUpsMap:n,...C,groupInfo:R};if(T){let F=typeof T=="object"||{abandoned:!0,completed:!0,upcoming:!0,pending:!0,bye:!0},{abandoned:L,completed:w,upcoming:V,pending:k,bye:W}=F,H=[].concat(...L&&A||[],...w&&E||[],...V&&N||[],...k&&D||[],...W&&M||[]);Jb({inContextDrawMatchUps:H,drawDefinition:S})}return x}function Kn(t){let{participants:e=[],contextContent:r,participantMap:n}=t,{scheduleVisibilityFilters:o,tournamentAppliedPolicies:i,participantsProfile:s,afterRecoveryTimes:a,policyDefinitions:c,useParticipantMap:u,tournamentRecord:p,contextFilters:m,contextProfile:d,matchUpFilters:l,nextMatchUps:f,inContext:g,context:I,event:h}=t;if(!h)return{error:vt};let{eventId:S,eventName:T,endDate:y,eventType:P,category:U,gender:A,matchUpFormat:E}=h??{},N={...I,...ot({indoorOutDoor:h.indoorOutdoor??p?.indoorOutdoor,surfaceCategory:h.surfaceCategory??p?.surfaceCategory,endDate:h.endDate??p?.endDate,tournamentId:p?.tournamentId,matchUpFormat:E,eventName:T,eventType:P,category:U,eventId:S,gender:A})};y&&(N.endDate=y),d&&!r&&(r=$n({policyDefinitions:c,tournamentRecord:p,contextProfile:d,event:h}));let D;if(!e?.length&&!n&&p){let v=Bo({participantsProfile:s,useParticipantMap:u,policyDefinitions:c,tournamentRecord:p,contextProfile:d,inContext:g});n=v.participantMap,e=v.participants??[],D=v.groupInfo}let M=h.drawDefinitions??[],R=ya({tournamentRecord:p,event:h}).scheduleTiming;return{matchUps:M.flatMap(v=>{let{matchUps:O}=se({tournamentParticipants:e,tournamentAppliedPolicies:i,scheduleVisibilityFilters:o,context:N,participantsProfile:s,afterRecoveryTimes:a,policyDefinitions:c,tournamentRecord:p,contextFilters:m,contextProfile:d,drawDefinition:v,contextContent:r,matchUpFilters:l,participantMap:n,scheduleTiming:R,nextMatchUps:f,inContext:g,event:h});return O??[]}),groupInfo:D}}function Te(t){let e=rt(t,[{tournamentRecord:!0}]);if(e.error)return e;if(!t?.tournamentRecord)return{error:Y};let{participantMap:r,participants:n}=t,{scheduleVisibilityFilters:o,participantsProfile:i,afterRecoveryTimes:s,useParticipantMap:a,policyDefinitions:c,tournamentRecord:u,inContext:p=!0,contextProfile:m,matchUpFilters:d,contextFilters:l,nextMatchUps:f,context:g}=t,I=t.tournamentId??u.tournamentId,h=u?.events??[];n||({participants:n,participantMap:r}=Bo({participantsProfile:i,useParticipantMap:a,policyDefinitions:c,tournamentRecord:u,contextProfile:m,inContext:p}));let{appliedPolicies:S}=yt({tournamentRecord:u}),T={...g,tournamentId:I,indoorOutDoor:u.indoorOutdoor,surfaceCategory:u.surfaceCategory,endDate:u.endDate},y=$n({policyDefinitions:c,tournamentRecord:u,contextProfile:m});return{matchUps:h.flatMap(U=>(T.eventDrawsCount=U.drawDefinitions?.length??0,Kn({context:T,scheduleVisibilityFilters:o,tournamentAppliedPolicies:S,participantsProfile:i,afterRecoveryTimes:s,policyDefinitions:c,tournamentRecord:u,contextContent:y,contextFilters:l,contextProfile:m,matchUpFilters:d,participantMap:r,nextMatchUps:f,participants:n,inContext:p,event:U}).matchUps??[])).concat(...u.matchUps??[])}}function Un({scheduleVisibilityFilters:t,afterRecoveryTimes:e,participantsProfile:r,tournamentRecords:n,policyDefinitions:o,matchUpFilters:i,contextFilters:s,nextMatchUps:a,inContext:c}){if(typeof n!="object"||!Object.keys(n).length)return{error:xt};let p=Object.keys(n).map(m=>{let d=n[m];return Te({scheduleVisibilityFilters:t,afterRecoveryTimes:e,participantsProfile:r,policyDefinitions:o,tournamentRecord:d,matchUpFilters:i,contextFilters:s,nextMatchUps:a,inContext:c}).matchUps??[]}).flat();return{...C,matchUps:p}}function Mi(t,e){return Nk(t,e)||(t?.stageSequence||0)-(e?.stageSequence||0)||t?.roundNumber&&e.roundNumber&&t?.roundNumber-e?.roundNumber||(t?.roundPosition??0)-(e?.roundPosition??0)}function Nk(t,e){return(ks[t?.stage]||0)-(ks[e?.stage]||0)}function or(t){let{participants:e,participantMap:r,contextContent:n}=t,{scheduleVisibilityFilters:o,tournamentAppliedPolicies:i,participantsProfile:s,afterRecoveryTimes:a,policyDefinitions:c,useParticipantMap:u,tournamentRecord:p,matchUpFilters:m,contextFilters:d,contextProfile:l,drawDefinition:f,nextMatchUps:g,inContext:I,context:h,event:S}=t,{eventId:T,eventName:y,endDate:P,eventType:U,category:A,gender:E,matchUpFormat:N}=S??{},D={...h,surfaceCategory:S?.surfaceCategory??p?.surfaceCategory,indoorOutDoor:S?.indoorOutdoor??p?.indoorOutdoor,matchUpFormat:N,eventType:U,eventName:y,category:A,eventId:T,endDate:P,gender:E},M;return!e?.length&&!r&&p&&({participants:e=[],participantMap:r,groupInfo:M}=Bo({participantsProfile:s,useParticipantMap:u,policyDefinitions:c,tournamentRecord:p,contextProfile:l,inContext:I})),l&&!n&&(n=$n({policyDefinitions:c,tournamentRecord:p,contextProfile:l,drawDefinition:f,event:S})),{...se({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:S}),groupInfo:M}}function ls({element:t,accessor:e}){if(typeof e!="string")return{values:[]};let r=J(t),n=e.split("."),o=[],i;a({targetElement:r,attributes:n});let s={value:i};return o.length&&(s.values=o),s;function a({targetElement:c,attributes:u=[],significantCharacters:p}){for(let[d,l]of u.entries())if(c?.[l]){let f=u.slice(d+1);f.length?Array.isArray(c[l])?c[l].forEach(I=>a({targetElement:I,attributes:f})):(c=c[l],m({targetElement:c,index:d})):(i||(i=c[l]),o.includes(c[l])||o.push(c[l]))}function m({targetElement:d,index:l}){if(d&&l===u.length-1&&["string","number"].includes(typeof d)){let f=p?d.slice(0,p):d;i?o.includes(f)||o.push(f):(i=f,o.push(f))}}}}var QU=t=>e=>!t||typeof e!="object"?void 0:Array.isArray(t)&&t.map(r=>({[r]:ls({element:e,accessor:r})?.value}))||typeof t=="object"&&Object.keys(t).map(r=>({[r]:ls({element:e,accessor:r})?.value}))||(typeof t=="string"&&ls({element:e,accessor:t}))?.value,Br=QU;function Ea({finishingPositionOffset:t=0,finishingPositionLimit:e,positionsFed:r,roundsCount:n,roundLimit:o,matchUps:i,lucky:s,fmlc:a}){if(!Vr(i))return[];let{roundProfile:c,roundNumbers:u=[]}=Ke({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(Br("matchUpsCount")),l=(I,h)=>{let S=Math.min(...I);m&&h&&S===1&&(S=m);let T=Math.max(...I);return e&&T>e&&(T=e),[S,T]},f=c&&Object.assign({},...u.map(I=>{let h=(n??0)+1-I-p,S=c[I].matchUpsCount,T={finishingPositionRange:{},finishingRound:h},y=d?.slice(I-1).reduce((R,b)=>R+(b||0),0),P=a&&I!==1,U=1+t+(P?r??0:0),A=1,E=et(U,s?U+S*2:y+U+A),N=y+A-S,D=l(E.slice(N)),M=l(E.slice(0,N),!0);return T.finishingPositionRange={loser:D,winner:M},{[I]:T}})),g=Pr({finishingRound:!0});return i.filter(Boolean).forEach(I=>{let h=I.roundNumber&&f[I.roundNumber];g&&!h&&console.log({roundFinishingData:f,matchUp:I}),I.finishingRound=h?.finishingRound,I.finishingPositionRange=h?.finishingPositionRange}),i}function qi({inContextDrawMatchUps:t,drawDefinition:e,matchUpsMap:r}){if(!e)return{error:Z};let n={loserMatchUpIds:{},winnerMatchUpIds:{}};if(t||({matchUps:t,matchUpsMap:r}=se({inContext:!0,drawDefinition:e,matchUpsMap:r})),!r?.drawMatchUps.some(i=>i.finishingPositionRange)&&e?.structures?.length===1&&!e?.structures[0].structures){let i=r?.drawMatchUps??[];Ea({matchUps:i})}return(t??[]).filter(({collectionId:i})=>!i).forEach(i=>{let{matchUpId:s,structureId:a}=i,c=ur({inContextDrawMatchUps:t,drawDefinition:e,matchUpId:s}),{winnerMatchUp:u,loserMatchUp:p}=c.targetMatchUps,m=u?.matchUpId,d=p?.matchUpId,f=ii({matchUpsMap:r,structureId:a}).find(g=>g.matchUpId===s);if(f&&(m&&(n.winnerMatchUpIds[f.matchUpId]=m,Object.assign(f,{winnerMatchUpId:m}),Object.assign(i,{winnerMatchUpId:m})),d&&(n.loserMatchUpIds[f.matchUpId]=d,i.loserMatchUpId=d,f.loserMatchUpId=d,i.finishingPositionRange))){let g=p.finishingPositionRange&&[...i.finishingPositionRange.loser,...p.finishingPositionRange.loser],I=g&&[Math.min(...g),Math.max(...g)];i.finishingPositionRange.loser=I,f.finishingPositionRange.loser=I}}),{inContextDrawMatchUps:t,goesToMap:n}}function sn(t){let e=Nr(t),r=t.matchUps??[],n=t.drawIds??[],{includeParticipantDependencies:o,tournamentRecord:i,drawDefinition:s}=t;if(!Array.isArray(r))return{error:Jn};if(!Array.isArray(n))return{error:an};let a=t.matchUpIds?.length?t.matchUpIds:r.map(T=>T.matchUpId);if(!Array.isArray(a))return{error:rs};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(P=>(P.drawDefinitions||[]).map(U=>U.links||[])).flat(1/0),[]).filter(({linkType:T})=>T===eo),g=r;if(f.length){g=Un({nextMatchUps:!0,tournamentRecords:e}).matchUps;let T=f.reduce((y,P)=>{let U=P.source?.structureId,A=P.target?.structureId;return U&&A&&(p[A]=U),U&&!y.includes(U)&&y.push(U),y},[]);for(let y of T)c[y]=[];for(let y of g??[]){let P=y.containerStructureId||y.structureId;T.includes(P)&&c[P].push(y.matchUpId)}}let I=T=>{u[T]||(u[T]={dependentMatchUpIds:[],participantIds:[],matchUpIds:[],sources:[]},m[T]=[])},h=(T,y)=>{u[T].matchUpIds.forEach(U=>{u[y].matchUpIds.push(U)}),u[y].matchUpIds.push(T),u[T].dependentMatchUpIds.push(y),o&&u[T].participantIds.forEach(U=>u[y].participantIds.push(U))},S=T=>{let y=Object.keys(c).length;for(let P of T||[]){let{matchUpId:U,winnerMatchUpId:A,loserMatchUpId:E}=P;if(!a.length||a.includes(U)){if(I(U),o){let{individualParticipantIds:M}=uu(P);u[U].participantIds=M}A&&(I(A),h(U,A),m[A].push(U)),E&&(I(E),h(U,E),m[E].push(U)),u[U].sources.push(m[U]);let N=m[U].map(M=>u[M].sources[0]).flat(),D=m[U].map(M=>u[M].sources[1]).flat();if(u[U].sources.push(N,D),y){let M=P.containerStructureId||P.structureId,R=p[M];if(c[R])for(let b of c[R])I(b),h(b,U),m[b].push(U)}}}};if(s)qi({drawDefinition:s}),g?.length||(g=or({drawDefinition:s}).matchUps),S(g);else{if(g?.length||(g=Un({nextMatchUps:!0,tournamentRecords:e}).matchUps),!n.length){let T=d?.length?d.map(({events:y=[]})=>y.map(({drawDefinitions:P=[]})=>P.map(({drawId:U})=>U))).flat(1/0):[];T&&(n=T)}for(let T of n){let y=g?.filter(U=>U.drawId===T).sort(Mi);if(!y?.find(({roundPosition:U})=>!U)){let U=y?.find(({tournamentId:E})=>E),{drawDefinition:A}=ze({tournamentRecord:e[U?.tournamentId],drawId:T});A&&qi({drawDefinition:A})}S(y)}}return{positionDependencies:c,matchUpDependencies:u,sourceMatchUpIds:m,matchUps:g,...C}}function Ie(t){let e=t?.matchUp,r=t?.score||e?.score,n=r?.sets?.[0],{side1Score:o,side2Score:i,side1TiebreakScore:s,side2TiebreakScore:a,side1PointScore:c,side2PointScore:u}=n||{},p=o||i||s||a||c||u;return!!(r?.sets?.length>1||p)}function Ua({matchUpStatus:t}){return Fh.includes(t)}function tv({matchUpStatus:t}){return zm.includes(t)}function og({matchUpStatus:t}){return kh.includes(t)}function ig({matchUpStatus:t,winningSide:e,tieMatchUps:r,sides:n,score:o}){let i=n?.find(({participantId:c})=>c),s=r?.filter(ig)?.length;return Ie({score:o})||s||e&&i||t&&tv({matchUpStatus:t})&&![Mt,Ct,Ln].includes(t)}function Pa(t){let{drawDefinition:e,findContainer:r,structureId:n,event:o}=t,i=t.structure,s={isCollectionMatchUp:!1},{containedStructures:a}=as({drawDefinition:e}),c=n?a[n]||[]:[];if(!i){let A=at({drawDefinition:e,structureId:n});if(A.error)return A;i=r?A.containingStructure??A.structure:A.structure}if(cr({structure:i}))return{structure:i,isAdHoc:!0,error:Rs};let{matchUps:u}=se({inContext:!0,matchUpFilters:s,drawDefinition:e,event:o}),p=u?.filter(A=>A.structureId===n||c.includes(A.structureId)),{matchUpDependencies:m}=sn({drawIds:[e.drawId],matchUps:u,drawDefinition:e}),d=[],l=[],f={},g=[];for(let A of u??[]){if(A.structureId===n||c.includes(A.structureId)){l.push(...A.drawPositions??[]);let E=A.roundNumber;for(let N of(A.drawPositions??[]).filter(Boolean))(!f[N]||E&&f[N]>E)&&(f[N]=E)}ig(A)&&(g.push(A),d.push(A.matchUpId,...m?.[A?.matchUpId]?.matchUpIds||[]))}let I=ut(l.filter(Boolean)).sort(me),h=ut(d),S=ut(p?.map(({matchUpId:A,drawPositions:E})=>h.includes(A)?E:[]).flat().filter(Boolean)).sort(me),{positionAssignments:T}=bt({drawDefinition:e,structure:i}),y=T?.filter(A=>A.bye).map(A=>A.drawPosition),P=T?.filter(A=>A.qualifier).map(A=>A.drawPosition),U=I?.filter(A=>!S.includes(A))||[];return{allDrawPositions:I,inContextStructureMatchUps:p,drawPositionInitialRounds:f,activeDependentMatchUpIds:h,qualifyingDrawPositions:P,inactiveDrawPositions:U,positionAssignments:T,activeDrawPositions:S,byeDrawPositions:y,activeMatchUps:g,structure:i}}function fs({drawPosition:t,matchUps:e=[]}){return{initialRoundNumber:e.filter(({drawPositions:n})=>t&&n?.includes(t)).map(({roundNumber:n})=>n).sort(me)[0]}}var Da={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 IS=[];function Rn(t,e){Vt(t)&&(t={method:t}),(e||Pr())&&IS.push(t)}function Mk(t){let e=IS.slice();return t&&(IS.length=0),e}function ev(t){let r=Mk(t).map(n=>{let{color:o,keyColors:i,method:s,newline:a}=n,c=Object.keys(Da).includes(o)?Da[o]:Da.cyan,p=Object.keys(n).filter(d=>!["color","keyColors","method","newline"].includes(d)).map(d=>{let l=i&&Object.keys(i).includes(d)&&Da[i[d]]?Da[i[d]]:Da.brightwhite;return`${Da.white}${d}: ${l}${n[d]}`}).join(", "),m=s?.length<15?" ":" ";return[a?`
|
|
1
|
+
var oL=Object.defineProperty;var Xt=(t,e)=>{for(var r in e)oL(t,r,{get:e[r],enumerable:!0})};function Va(){return"2.2.4"}var hA={};Xt(hA,{competitionGovernor:()=>DU,drawsGovernor:()=>MN,entriesGovernor:()=>xN,eventGovernor:()=>$N,generationGovernor:()=>ZN,matchUpFormatGovernor:()=>Oy,matchUpGovernor:()=>yM,mocksGovernor:()=>fI,participantGovernor:()=>QM,policyGovernor:()=>nN,publishingGovernor:()=>iR,queryGovernor:()=>DN,reportGovernor:()=>sR,scheduleGovernor:()=>SR,scoreGovernor:()=>Hg,tieFormatGovernor:()=>RR,tournamentGovernor:()=>VR,venueGovernor:()=>QR});var DU={};Xt(DU,{getLinkedTournamentIds:()=>iu,getTournamentIds:()=>hp,linkTournaments:()=>yU,mutate:()=>UU,query:()=>PU,unlinkTournament:()=>EU,unlinkTournaments:()=>AU});var UU={};Xt(UU,{linkTournaments:()=>yU,unlinkTournament:()=>EU,unlinkTournaments:()=>AU});var aa="SINGLES",Ft="SINGLES",vi="DOUBLES",_t="DOUBLES",xr="TEAM",jt="TEAM",sC={SINGLES_MATCHUP:aa,SINGLES:Ft,DOUBLES_MATCHUP:vi,DOUBLES:_t,TEAM_MATCHUP:xr,TEAM:jt};var EI={[Ft]:[Ft,"S"],[_t]:[_t,"D"],[jt]:[jt,"T"],S:[Ft,"S"],D:[_t,"D"],T:[jt,"T"]};function me(t,e){return(t??0)-(e??0)}function pt(t){return typeof t=="number"?parseInt(t.toString()):typeof t=="string"?parseInt(t):0}function vn(t){return isNaN(t)?!1:t&&(t&t-1)===0}function AA(t){if(!t.length)return;let e=[...t].sort(me),r=Math.floor(e.length/2);return e.length%2?e[r]:(e[r-1]+e[r])/2}function aC(t){if(!vn(t))return!1;let e=t,r=1;for(;e!==2;)r+=1,e=e/2;return r}function Sm(t){return isNaN(t)?0:t%2&&t+1||t}function Tm(t){return Math.pow(2,Math.round(Math.log(t)/Math.log(2)))}function Zt(t){return!isNaN(parseFloat(t))}function UI(t){let e=pt(t);if(!isNaN(e))return e===0?!1:(e&-e)===1}function es(t){if(isNaN(t))return!1;for(;!vn(t);)t++;return t}function po(t,e){return t=Math.ceil(t),e=Math.floor(e),Math.floor(Math.random()*(e-t+1))+t}function It(t){return Number.isSafeInteger(typeof t=="string"?+t:t)}function cC(t=1,e=3,r=!0){let n=0;for(let o=0;o<e;o++)n+=Math.random()*(t/e);return r&&t>1?Math.round(n):n}function iL(t,e){e||(e=1);let r=1/e;return Math.round(t*r)/r}function EA(t,e,r,n,o=2){let i=1-Math.random(),s=1-Math.random(),a=Math.sqrt(-2*Math.log(i))*Math.cos(2*Math.PI*s);return a=a/10+.5,a>1||a<0?a=EA(t,e,r):(a=Math.pow(a,r),a*=e-t,a+=t),n&&(a=iL(a,n)),parseFloat(a.toFixed(o))}function _l(t,e=2){return parseFloat(Number(Math.round(t*1e3)/1e3).toFixed(e))}function ut(t){return Array.isArray(t)?t?.filter((e,r,n)=>n.lastIndexOf(e)===r):[]}function uC(t){return Array.isArray(t)?t?.map(e=>e===null?void 0:e):t}function Ir(t){return Array.isArray(t)?t.map(e=>[Math.random(),e]).sort((e,r)=>e[0]-r[0]).map(e=>e[1]):[]}function Ba(t){return It(t)?t:1/0}function Sr(t){return Array.isArray(t)?t.reduce((e,r)=>(e[r]||(e[r]=0),e[r]++,e),{}):{}}function pC(t){return UA(Sr(t))}function UA(t){return Object.keys(t).reduce((e,r)=>{let n=t[r];return e[n]?e[n].push(r):e[n]=[r],e},{})}function sL(t,e,r){return r.indexOf(t)===e}function PI(t){return t.filter(sL)}function tn(t){return Array.isArray(t)&&t.length?t.splice(Math.floor(Math.random()*t.length),1)[0]:void 0}function yn(t){let e=Math.floor(Math.random()*t.length);return t[e]}function et(t,e){return Array.from({length:e-t},(r,n)=>n+t)}function mo(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 PA(t,e){return!Array.isArray(t)||!Array.isArray(e)?[]:t.filter(r=>!e.includes(r))}function Fe(t,e){return!Array.isArray(t)||!Array.isArray(e)?!1:t.some(r=>e.includes(r))}function mC(t,e){return Array.isArray(e)&&e.reduce((r,n)=>(r[n]=1+r[n]||1,r),{})[t]||0}function dC(t,e,r,n){return Array.isArray(t)?[].concat(...t.slice(0,e),...t.slice(e,e+r).sort(n),...t.slice(e+r,t.length)):[]}function Ae(t,e){return Array.isArray(t)?t.reduce((r,n,o)=>{let i=Math.floor(o/e);return r[i]=[].concat(r[i]||[],n),r},[]):[]}function DA(t,[e,...r]){return t.length?[t.slice(0,e),...DA(t.slice(e),[...r,e])]:[]}function lC(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 DI(t){return Array.isArray(t)?t.reduce((e,r)=>!isNaN(parseInt(r))&&e,!0):!1}function NI(t){return Array.isArray(t)?t.reduce((e,r)=>isNaN(parseInt(r))&&e,!0):!1}function xl(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 fC(t,e=1){if(!Array.isArray(t)||!t.every(It))return[];let r=Math.min(...t,e),n=Math.max(...t);return et(r,n+1).filter(o=>!t.includes(o))}function Wr(t){return typeof t=="function"}function Vt(t){return typeof t=="string"}function ht(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function gC(t,e){if(!ht(t)||!ht(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 RI(t,e){return Array.isArray(t)?Object.assign({},...(t??[]).filter(ht).map(r=>r[e]&&{[r[e]]:r}).filter(Boolean)):{}}var IC=t=>e=>Object.keys(t).every(r=>e[r]===t[r]);function MI(t,e){if(t===void 0)return null;if(!ht(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=>MI(i))}:{[o]:e?n(t[o]):MI(t[o])}))}function NA(t){return Array.isArray(t)?t.length+t.map(NA).reduce((e,r)=>e+r,0):ht(t)&&t!==null?Object.keys(t).length+Object.keys(t).map(e=>NA(t[e])).reduce((e,r)=>e+r,0):0}function hC(t){if(t===null||typeof t!="object")return;let e=JSON.stringify(t),r=NA(t),n=e.split("").reduce((o,i)=>o+i.charCodeAt(0),0);return[e.length,r,n].map(o=>o.toString(36)).join("")}function Lc(t,e){return!Array.isArray(t)||!Vt(e)?!1:Yt(t,EI[e]).length}var C={success:!0},MA="error",SC={SUCCESS:C,ERROR:MA};function CI({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!==ut(n).length?(r.push("collectionPositions are not unique"),{errors:r}):{...C}}var bC={};Xt(bC,{addNotice:()=>mt,callListener:()=>Dm,createInstanceState:()=>wE,cycleMutationStatus:()=>cf,deepCopyEnabled:()=>af,deleteNotice:()=>YI,deleteNotices:()=>Fi,disableNotifications:()=>LE,enableNotifications:()=>sf,getDevContext:()=>Pr,getMethods:()=>uf,getNotices:()=>jI,getProvider:()=>qI,getTopics:()=>Lr,getTournamentId:()=>ns,getTournamentRecord:()=>pf,getTournamentRecords:()=>Fo,globalLog:()=>GE,handleCaughtError:()=>ip,hasTopic:()=>np,removeTournamentRecord:()=>kE,setDeepCopy:()=>Hc,setDevContext:()=>Bc,setGlobalLog:()=>MC,setGlobalMethods:()=>RC,setGlobalSubscriptions:()=>LL,setMethods:()=>CC,setStateMethods:()=>VE,setStateProvider:()=>xL,setSubscriptions:()=>FL,setTournamentId:()=>op,setTournamentRecord:()=>FE,setTournamentRecords:()=>Nm,timeKeeper:()=>wL});var bI={message:"Chronological error; time violation.",code:"ANACHRONISM"},ym={message:"Duplicate entry",code:"DUPLICATE_ENTRY"},RA={message:"Cannot remove main structure",code:"ERR_CANNOT_REMOVE_MAIN_STRUCTURE"},vI={message:"records must be an object with tournamentId keys",code:"ERR_INVALID_TOURNAMENTS"},xt={message:"Missing tournamentRecords",code:"ERR_MISSING_TOURNAMENTS"},Y={message:"Missing tournamentRecord",code:"ERR_MISSING_TOURNAMENT"},Ha={message:"Invalid tournamentRecord",code:"ERR_INVALID_TOURNAMENT"},ca={message:"Missing tournamentId",code:"ERR_MISSING_TOURNAMENT_ID"},ua={message:"Invalid drawDefinition",code:"ERR_INVALID_DRAWDEF"},Z={message:"Missing drawDefinition",code:"ERR_MISSING_DRAWDEF"},CA={message:"Existing drawDefinition(s)",code:"ERR_EXISTING_DRAWDEFS"},Rr={message:"drawDefinition not found",code:"ERR_NOT_FOUND_DRAWDEF"},Xo={message:"Invalid structure",code:"ERR_INVALID_STRUCTURE"},wl={message:"Incomplete source structure",code:"ERR_INCOMPLETE_STRUCTURE"},Ll={message:"Invalid drawPosition for seedAssignment",code:"ERR_INVALID_SEEDING_POSITION"},Wa={message:"drawPosition already assigned",code:"ERR_EXISTING_POSITION_ASSIGNMENT"},bA={message:"Schedule not cleared",code:"ERR_UNCHANGED_SCHEDULE_NOT_CLEARED"},vA={message:"drawPosition not cleared",code:"ERR_FAILURE_POSITION_NOT_CLEARED"},aL={message:"drawPosition not found",code:"ERR_NOT_FOUND_DRAW_POSITION"},Fl={message:"Unrecognized drawType",code:"ERR_UNRECOGNIZED_DRAW_TYPE"},ja={message:"Missing drawPositions",code:"ERR_MISSING_DRAW_POSITIONS"},qu={message:"drawPosition is active",code:"ERR_ACTIVE_DRAW_POSITION"},TC={message:"drawPosition is occupied",code:"ERR_OCCUPIED_DRAW_POSITION"},Rs={message:"Invlid drawPosition",code:"ERR_INVALID_DRAW_POSITION"},Cs={message:"Missing drawPosition",code:"ERR_MISSING_DRAW_POSITION"},Am={message:"Invalid drawType",code:"ERR_INVALID_DRAW_TYPE"},$u={message:"Invalid drawSize",code:"ERR_INVALID_DRAW_SIZE"},OI={message:"Cannot set drawSize to be less than existing entries",code:"ERR_INVALID_DRAW_SIZE_MISMATCH"},Ya={message:"Missing drawSize",code:"ERR_MISSING_DRAW_SIZE"},an={message:"Missing drawId",code:"ERR_MISSING_DRAW_ID"},OA={message:"drawId exists",code:"ERR_EXISTING_DRAW_ID"},_A={message:"participantId cannot be assigned to multiple seedNumbers",code:"INVALID_PARTICIPANT_SEEDING"},xA={message:"seedsCount greater than drawSize",code:"ERR_INVALID_SEED_COUNT"},wA={message:"Missing seedCountThresholds",code:"ERR_MISSING_SEED_COUNT_THRESHOLD"},LA={message:"Invalid action",code:"ERR_INVALID_ACTION"},_I={message:"Invalid assignment",code:"ERR_INVALID_ASSIGNMENT"},FA={message:"Missing seedAssignments",code:"ERR_MISSING_SEED_ASSIGNMENTS"},kA={message:"Invalid seedNumber",code:"ERR_INVALID_SEED_NUMBER"},GA={message:"Invalid seedPosition",code:"ERR_INVALID_SEED_POSITION"},kl={message:"Missing targetLink",code:"ERR_MISSING_LINK_TARGET"},VA={message:"Existing round",code:"ERR_EXISTING_ROUND"},cL={message:"Missing roundNumber",code:"ERR_MISSING_ROUND_NUMBER"},Ur={message:"Missing structureId",code:"ERR_MISSING_STRUCTURE_ID"},kt={message:"structure not found",code:"ERR_NOT_FOUND_STRUCTURE"},Gl={message:"Missing structures",code:"ERR_MISSING_STRUCTURES"},mi={message:"Missing structure",code:"ERR_MISSING_STRUCTURE"},BA={message:"drawDefinition contains unlinked structures",code:"ERR_MISSING_STRUCTURE_LINKS"},Hn={message:"Invalid eventType",code:"ERR_INVALID_EVENT_TYPE"};var vt={message:"Missing event / eventId",code:"ERR_MISSING_EVENT_ID"},jr={message:"Event not found",code:"ERR_NOT_FOUND_EVENT"},HA={message:"Event exists",code:"ERR_EXISTING_EVENT"},WA={message:"Missing entries",code:"ERR_MISSING_ENTRIES"},jA={message:"Invalid entries",code:"ERR_INVALID_ENTRIES"},Vl={message:"Missing assignments",code:"ERR_MISSING_ASSIGNMENTS"},YA={message:"Missing stage",code:"ERR_MISSING_STAGE"},Oi={message:"Invalid stage",code:"ERR_INVALID_STAGE"},qA={message:"stageSequence limit",code:"ERR_LIMIT_STAGE_SEQUENCE"},$A={message:"Missing positionAssignments",code:"ERR_MISSING_POSITION_ASSIGNMENTS"},KA={message:"Cannot Assign BYE status if no assignment: { bye: true }",code:"ERR_UNCHANGED_CANNOT_ASSIGN_BYE"},xI={message:"Unrecognized matchUpStatus",code:"ERR_UNRECOGNIZED_MATCHUP_STATUS"},qa={message:"Unrecognized matchUpFormat",code:"ERR_UNRECOGNIZED_MATCHUP_FORMAT"},Bl={message:"Incompatible matchUpStatus",code:"ERR_INCOMPATIBLE_MATCHUP_STATUS"},pa={message:"Invalid matchUpStatus",code:"ERR_INVALID_MATCHUP_STATUS"},Lo={message:"Invalid tieFormat",code:"ERR_INVALID_TIE_FORMAT"},Hl={message:"Invalid matchUpFormat",code:"ERR_INVALID_MATCHUP_FORMAT"},Wl={message:"Missing matchUpFormat",code:"ERR_MISSING_MATCHUP_FORMAT"},zA={message:"Missing collectionDefinition",code:"ERR_MISSING_COLLECTION_DEFINITION"},bs={message:"Missing tieFormat",code:"ERR_MISSING_TIE_FORMAT"},sr={message:"Missing matchUpId",code:"ERR_MISSING_MATCHUP_ID"},rs={message:"Missing matchUpIds",code:"ERR_MISSING_MATCHUP_IDS"},Le={message:"matchUp not found",code:"ERR_NOT_FOUND_MATCHUP"},Jn={message:"Missing matchUps",code:"ERR_MISSING_MATCHUPS"},hr={message:"Missing matchUp",code:"ERR_MISSING_MATCHUP"},dr={message:"Invalid matchUp",code:"ERR_INVALID_MATCHUP"},wI={message:"Missing policyType",code:"ERR_MISSING_POLICY_TYPE"},Ku={message:"Missing policyDefinitions",code:"ERR_MISSING_POLICY_DEFINITIONS"},uL={message:"Missing seeding policy",code:"ERR_MISSING_POLICY_SEEDING"},QA={message:"Missing avoidance policy",code:"ERR_MISSING_POLICY_AVOIDANCE"},LI={message:"Missing policy attributes",code:"ERR_MISSING_POLICY_ATTRIBUTES"},XA={message:"Invalid policyDefinitions",code:"ERR_INVALID_POLICY_DEFINITIONS"},FI={message:"existing policyType",code:"ERR_EXISTING_POLICY_TYPE"},pL={message:"Policy not attached",code:"ERR_FAILURE_POLICY_NOT_ATTACHED"},Fc={message:"Policy not found",code:"ERR_NOT_FOUND_POLICY"},mL={message:"Missing scoring policy / matchUpFormats",code:"ERR_MISSING_POLICY_SCORING_MATCHUP_FORMATS"},jl={message:"Invalid sideNumber",code:"ERR_INVALID_SIDE_NUMBER"},dL={message:"Invalid setNumber",code:"ERR_INVALID_SET_NUMBER"},Yl={message:"Missing setObject",code:"ERR_MISSING_SET_ATTRIBUTE"},lL={message:"Missing setNumber",code:"ERR_MISSING_SET_NUMBER"},fL={message:"Missing sideNumber",code:"ERR_MISSING_SIDE_NUMBER"},_i={message:"Missing courtId",code:"ERR_MISSING_COURT_ID"},st={message:"Missing value",code:"ERR_MISSING_VALUE"},JA={message:"Missing birthdate",code:"ERR_MISSING_BIRTH_DATE"},ZA={message:"Missing date",code:"ERR_MISSING_DATE"},tE={message:"No valid dates",code:"ERR_NO_VALID_DATES"},Em={message:"Invalid bookings",code:"ERR_INVALID_BOOKINGS"},ql={message:"Invalid dateAvailability",code:"ERR_INVALID_DATE_AVAILABILITY"},eE={message:"Missing dateAvailability",code:"ERR_MISSING_DATE_AVAILABILITY"},je={message:"Invalid Date",code:"ERR_INVALID_DATE"},Eo={message:"Invalid time",code:"ERR_INVALID_TIME"},rE={message:"Invalid tournament dates",code:"ERR_INVALID_DATES_TOURNAMENT"};var kI={message:"Invalid game scores",code:"ERR_INVALID_SCORES_GAME"},nE={message:"Invalid score",code:"ERR_INVALID_SCORE"},Um={message:"Invalid winningSide",code:"ERR_INVALID_WINNING_SIDE"};var yC={message:"No participants generated",code:"ERR_NO_PARTICIPANTS_GENERATED"},$l={message:"Cannot modify tieFormat",code:"ERR_UNCHANGED_CANNOT_MODIFY_TIEFORMAT"},oE={message:"Cannot modify participantType",code:"ERR_UNCHANGED_CANNOT_MODIFY_PARTICIPANT_TYPE"},zu={message:"Cannot remove participants",code:"ERR_UNCHANGED_CANNOT_REMOVE_PARTICIPANTS"},GI={message:"Participant category mismatch",code:"ERR_CATEGORY_MISMATCH"},Pm={message:"Cannot change winningSide",code:"ERR_UNCHANGED_CANNOT_CHANGE_WINNING_SIDE"},xi={message:"Invalid participant",code:"ERR_INVALID_PARTICIPANT"},mn={message:"Invalid participantId",code:"ERR_INVALID_PARTICIPANT_ID"},wr={message:"Invalid participantIds",code:"ERR_INVALID_PARTICIPANT_IDS"},iE={message:"Invalid participantRole",code:"ERR_INVALID_PARTICIPANT_ROLE"},An={message:"Invalid participantType",code:"ERR_INVALID_PARTICIPANT_TYPE"},sE={message:"Missing participantRole",code:"ERR_MISSING_PARTICIPANT_ROLE"},wi={message:"Missing participant",code:"ERR_MISSING_PARTICIPANT"},$a={message:"Missing participants",code:"ERR_MISSING_PARTICIPANTS"},oe={message:"Missing participantId",code:"ERR_MISSING_PARTICIPANT_ID"},te={message:"Participant Not Found",code:"ERR_NOT_FOUND_PARTICIPANT"},aE={message:"participantId exists",code:"ERR_EXISTING_PARTICIPANT_ID"},gL={message:"participant pair exists",code:"ERR_EXISTING_PARTICIPANT_PAIR"},cE={message:"No participant removed",code:"ERR_UNCHANGED_NO_PARTICIPANT_REMOVED"},Uo={message:"Missing participantIds",code:"ERR_MISSING_PARTICIPANT_IDS"},uE={message:"Missing participantsCount",code:"ERR_MISSING_PARTICIPANT_COUNT"},pE={message:"Participant not checked in",code:"ERR_UNCHANGED_PARTICIPANT_NOT_CHECKED_IN"},mE={message:"Missing person details",code:"ERR_MISSING_PERSON_DETAILS"},vs={message:"Existing participant drawPosition assignment",code:"ERR_EXISTING_PARTICIPANT_DRAW_POSITION_ASSIGNMENT"},Qu={message:"Existing participant",code:"ERR_EXISTING_PARTICIPANT"},Kl={message:"participantsCount exceeds drawSize",code:"ERR_INVALID_PARTICIPANT_COUNT"},zl={message:"Invalid entry status",code:"ERR_INVALID_ENTRY_STATUS"},VI={message:"Participant Entry Not Found",code:"ERR_NOT_FOUND_PARTICIPANT_ENTRY"},AC={message:"Participant not entered in stage",code:"ERR_UNCHANGED_PARTICIPANT_NOT_ENTERED"},EC={message:"Participant not found in stageSequence",code:"ERR_NOT_FOUND_PARTICIPANT_IN_STAGE"},dE={message:"entryStatus not allowed in stage",code:"ERR_INVALID_ENTRY_STATUS_IN_STAGE"},lE={message:"entryStatus not allowed for event",code:"ERR_INVALID_ENTRY_STATUS_IN_EVENT"},BI={message:"No stage space available for entryStatus",code:"ERR_UNCHANGED_NO_AVAILABLE_STAGE_SPACE"},fE={message:"Insufficient drawPositions to accommodate qualifiers",code:"ERR_UNCHANGED_NO_DRAW_POSITIONS_FOR_QUALIFIERS"},Ql={message:"Insufficient drawPositions to accommodate entries",code:"ERR_INSUFFICIENT_DRAW_POSITIONS"},gE={message:"Missing penaltyType",code:"ERR_MISSING_PENALTY_TYPE"},Xl={message:"Missing penaltyId",code:"ERR_MISSING_PENALTY_ID"},kc={message:"Penalty not found",code:"ERR_NOT_FOUND_PENALTY"},IE={message:"Missing courtsCount/courtNames",code:"ERR_MISSING_COURTS_INFO"},Os={message:"Court not found",code:"ERR_NOT_FOUND_COURT"},hE={message:"Court exists",code:"ERR_EXISTING_COURT"},SE={message:"Venue exists",code:"ERR_EXISTING_VENUE"},Li={message:"Venue not found",code:"ERR_NOT_FOUND_VENUE"},Jo={message:"Missing venueId",code:"ERR_MISSING_VENUE_ID"},TE={message:"Invalid endTime",code:"ERR_INVALID_END_TIME"},HI={message:"Existing endTime",code:"ERR_EXISTING_END_TIME"},yE={message:"Invalid stopTime",code:"ERR_INVALID_STOP_TIME"},AE={message:"Invalid startTime",code:"ERR_INVALID_START_TIME"},UC={message:"Invalid resumeTime",code:"ERR_INVALID_RESUME_TIME"},Jl={message:"Invalid timeItem",code:"ERR_INVALID_TIME_ITEMS"},EE={message:"Missing async state provider",code:"ERR_MISSING_ASYNC_STATE_PROVIDER"},Zl={message:"Missing timeItem",code:"ERR_MISSING_TIME_ITEM"},tf={message:"Missing timeItems",code:"ERR_MISSING_TIME_ITEMS"},Gc={message:"Missing context",code:"ERR_MISSING_CONTEXT"},UE={message:"Missing schedule",code:"ERR_MISSING_SCHEDULE"},Ka={message:"Invalid scaleItem",code:"ERR_INVALID_SCALE_ITEM"},PE={message:"Modifications failed",code:"ERR_FAILURE_MODIFICATIONS"},_s={message:"No modifications applied",code:"ERR_UNCHANGED_NO_MODIFICATIONS_APPLIED"},DE={message:"Unable to assign court",code:"ERR_UNCHANGED_COURT_NOT_ASSIGNED"},Xu={message:"No Candidates",code:"ERR_UNCHANGED_NO_CANDIDATES"},NE={message:"Invalid configuration",code:"ERR_INVALID_CONFIG"},ME={message:"Invalid collectionDefinition",code:"ERR_INVALID_COLLECTION_DEFINITION"},lo={message:"Invalid object",code:"ERR_INVALID_OBJECT"},Ju={message:"Invalid gender",code:"ERR_INVALID_GENDER"},Vc={message:"Invalid category",code:"ERR_INVALID_CATEGORY"},G={message:"Invalid values",code:"ERR_INVALID_VALUES"},RE={message:"Duplicate value",code:"ERR_DUPLICATE_VALUE"},ef={message:"Team not found",code:"ERR_NOT_FOUND_TEAM"},CE={message:"No valid actions",code:"ERR_NO_VALID_ACTIONS"},Zu={message:"No valid attributes",code:"ERR_NO_VALID_ATTRIBUTES"},rf={message:"Value unchanged",code:"ABORT_UNCHANGED"},ve={message:"Not found",code:"ERR_NOT_FOUND"},tp={message:"Not implemented",code:"ERR_NOT_IMPLEMENTED"},bE={message:"Existing flight",code:"ERR_EXISTING_FLIGHT"},nf={message:"Existing flight profile",code:"ERR_EXISTING_FLIGHT_PROFILE"},vE={message:"Existing outcome",code:"ERR_EXISTING_OUTCOME"},OE={message:"Existing matchUpId",code:"ERR_EXISTING_MATCHUP_ID"},WI={message:"Existing stage",code:"ERR_EXISTING_STAGE"},of={message:"Existing structure",code:"ERR_EXISTING_STRUCTURE"},za={message:"Method not found",code:"ERR_NOT_FOUND_METHOD"},_E={message:"Scheduled matchUps",code:"ERR_SCHEDULED_MATCHUPS"},ep={message:"Scores present",code:"ERR_SCORES_PRESENT"},PC={ANACHRONISM:bI,CANNOT_CHANGE_WINNING_SIDE:Pm,CANNOT_MODIFY_TIEFORMAT:$l,CANNOT_MODIFY_PARTICIPANT_TYPE:oE,CANNOT_REMOVE_MAIN_STRUCTURE:RA,CANNOT_REMOVE_PARTICIPANTS:zu,CATEGORY_MISMATCH:GI,COURT_EXISTS:hE,COURT_NOT_FOUND:Os,DRAW_DEFINITION_NOT_FOUND:Rr,DRAW_ID_EXISTS:OA,DRAW_POSITION_ACTIVE:qu,DRAW_POSITION_ASSIGNED:Wa,DRAW_POSITION_NOT_CLEARED:vA,DRAW_POSITION_NOT_FOUND:aL,DRAW_SIZE_MISMATCH:OI,DUPLICATE_ENTRY:ym,DUPLICATE_VALUE:RE,ENTRY_STATUS_NOT_ALLOWED_FOR_EVENT:lE,ENTRY_STATUS_NOT_ALLOWED_IN_STAGE:dE,EVENT_EXISTS:HA,EVENT_NOT_FOUND:jr,EXISTING_DRAW_DEFINITIONS:CA,EXISTING_END_TIME:HI,EXISTING_FLIGHT:bE,EXISTING_MATCHUP_ID:OE,EXISTING_OUTCOME:vE,EXISTING_PARTICIPANT_DRAW_POSITION_ASSIGNMENT:vs,EXISTING_PARTICIPANT:Qu,EXISTING_POLICY_TYPE:FI,EXISTING_PROFILE:nf,EXISTING_ROUND:VA,EXISTING_STAGE:WI,EXISTING_STRUCTURE:of,INCOMPATIBLE_MATCHUP_STATUS:Bl,INCOMPLETE_SOURCE_STRUCTURE:wl,INSUFFICIENT_DRAW_POSITIONS:Ql,INVALID_ACTION:LA,INVALID_ASSIGNMENT:_I,INVALID_BOOKINGS:Em,INVALID_CATEGORY:Vc,INVALID_COLLECTION_DEFINITION:ME,INVALID_CONFIGURATION:NE,INVALID_DATE_AVAILABILITY:ql,INVALID_DATE:je,INVALID_DRAW_DEFINITION:ua,INVALID_DRAW_POSITION_FOR_SEEDING:Ll,INVALID_DRAW_POSITION:Rs,INVALID_DRAW_SIZE:$u,INVALID_END_TIME:TE,INVALID_ENTRIES:jA,INVALID_EVENT_TYPE:Hn,INVALID_GAME_SCORES:kI,INVALID_GENDER:Ju,INVALID_MATCHUP_FORMAT:Hl,INVALID_MATCHUP_STATUS:pa,INVALID_MATCHUP_STATUS_BYE:KA,INVALID_MATCHUP:dr,INVALID_OBJECT:lo,INVALID_PARTICIPANT_ID:mn,INVALID_PARTICIPANT_IDS:wr,INVALID_PARTICIPANT_ROLE:iE,INVALID_PARTICIPANT_SEEDING:_A,INVALID_PARTICIPANT_TYPE:An,INVALID_PARTICIPANT:xi,INVALID_POLICY_DEFINITION:XA,INVALID_RECORDS:vI,INVALID_SCALE_ITEM:Ka,INVALID_SEED_NUMBER:kA,INVALID_SEED_POSITION:GA,INVALID_SET_NUMBER:dL,INVALID_SIDE_NUMBER:jl,INVALID_SCORE:nE,INVALID_STAGE:Oi,INVALID_START_TIME:AE,INVALID_STRUCTURE:Xo,INVALID_STOP_TIME:yE,INVALID_TIE_FORMAT:Lo,INVALID_TIME:Eo,INVALID_TIME_ITEM:Jl,INVALID_TOURNAMENT_DATES:rE,INVALID_TOURNAMENT_RECORD:Ha,INVALID_VALUES:G,INVALID_WINNING_SIDE:Um,MATCHUP_NOT_FOUND:Le,METHOD_NOT_FOUND:za,MISSING_ASSIGNMENTS:Vl,MISSING_ASYNC_STATE_PROVIDER:EE,MISSING_AVOIDANCE_POLICY:QA,MISSING_BIRTH_DATE:JA,MISSING_COLLECTION_DEFINITION:zA,MISSING_COURT_ID:_i,MISSING_COURTS_INFO:IE,MISSING_DATE_AVAILABILITY:eE,MISSING_DATE:ZA,MISSING_DRAW_DEFINITION:Z,MISSING_DRAW_ID:an,MISSING_DRAW_POSITION:Cs,MISSING_DRAW_POSITIONS:ja,MISSING_DRAW_SIZE:Ya,MISSING_ENTRIES:WA,MISSING_EVENT:vt,MISSING_MATCHUP_FORMAT:Wl,MISSING_MATCHUP_ID:sr,MISSING_MATCHUP_IDS:rs,MISSING_MATCHUP:hr,MISSING_MATCHUPS:Jn,MISSING_PARTICIPANT_COUNT:uE,MISSING_PARTICIPANT_ID:oe,MISSING_PARTICIPANT_IDS:Uo,MISSING_PARTICIPANT_ROLE:sE,MISSING_PARTICIPANT:wi,MISSING_PARTICIPANTS:$a,MISSING_PENALTY_ID:Xl,MISSING_PENALTY_TYPE:gE,MISSING_PERSON_DETAILS:mE,MISSING_POLICY_ATTRIBUTES:LI,MISSING_POLICY_DEFINITION:Ku,MISSING_POLICY_TYPE:wI,MISSING_POSITION_ASSIGNMENTS:$A,MISSING_ROUND_NUMBER:cL,MISSING_SCHEDULE:UE,MISSING_SCORING_POLICY:mL,MISSING_SEED_ASSIGNMENTS:FA,MISSING_SEEDCOUNT_THRESHOLDS:wA,MISSING_SEEDING_POLICY:uL,MISSING_SET_NUMBER:lL,MISSING_SET_OBJECT:Yl,MISSING_SIDE_NUMBER:fL,MISSING_STAGE:YA,MISSING_STRUCTURE_ID:Ur,MISSING_STRUCTURE:mi,MISSING_STRUCTURES:Gl,MISSING_TARGET_LINK:kl,MISSING_TIE_FORMAT:bs,MISSING_TIME_ITEM:Zl,MISSING_TIME_ITEMS:tf,MISSING_TOURNAMENT_ID:ca,MISSING_TOURNAMENT_RECORD:Y,MISSING_TOURNAMENT_RECORDS:xt,MISSING_VALUE:st,MISSING_VENUE_ID:Jo,MODIFICATIONS_FAILED:PE,NO_CANDIDATES:Xu,NO_DRAW_POSITIONS_AVAILABLE_FOR_QUALIFIERS:fE,NO_MODIFICATIONS_APPLIED:_s,NO_STAGE_SPACE_AVAILABLE_FOR_ENTRY_STATUS:BI,NO_PARTICIPANT_REMOVED:cE,NO_VALID_ACTIONS:CE,NO_VALID_ATTRIBUTES:Zu,NO_VALID_DATES:tE,NOT_FOUND:ve,NOT_IMPLEMENTED:tp,PARTICIPANT_COUNT_EXCEEDS_DRAW_SIZE:Kl,PARTICIPANT_ID_EXISTS:aE,PARTICIPANT_NOT_CHECKED_IN:pE,PARTICIPANT_NOT_FOUND:te,PARTICIPANT_PAIR_EXISTS:gL,PENALTY_NOT_FOUND:kc,POLICY_NOT_ATTACHED:pL,POLICY_NOT_FOUND:Fc,SCHEDULE_NOT_CLEARED:bA,SCHEDULED_MATCHUPS:_E,SCORES_PRESENT:ep,SEEDSCOUNT_GREATER_THAN_DRAW_SIZE:xA,STAGE_SEQUENCE_LIMIT:qA,STRUCTURE_NOT_FOUND:kt,TEAM_NOT_FOUND:ef,UNABLE_TO_ASSIGN_COURT:DE,UNLINKED_STRUCTURES:BA,UNRECOGNIZED_DRAW_TYPE:Fl,UNRECOGNIZED_MATCHUP_FORMAT:qa,UNRECOGNIZED_MATCHUP_STATUS:xI,VALUE_UNCHANGED:rf,VENUE_EXISTS:SE};var Ze={disableNotifications:!1,tournamentId:void 0,tournamentRecords:{},subscriptions:{},modified:!1,methods:{},notices:[]},xE={addNotice:ML,callListener:OL,cycleMutationStatus:NL,deleteNotice:bL,deleteNotices:CL,disableNotifications:IL,enableNotifications:hL,getMethods:rp,getNotices:RL,getTopics:vL,getTournamentId:DC,getTournamentRecord:SL,getTournamentRecords:TL,removeTournamentRecord:UL,setMethods:DL,setSubscriptions:PL,setTournamentId:AL,setTournamentRecord:yL,setTournamentRecords:EL,handleCaughtError:_L};function IL(){Ze.disableNotifications=!0}function hL(){Ze.disableNotifications=!1}function DC(){return Ze.tournamentId}function SL(t){return Ze.tournamentRecords[t]}function TL(){return Ze.tournamentRecords}function yL(t){let e=t?.tournamentId;return e?(Ze.tournamentRecords[e]=t,{success:!0}):{error:Ha}}function AL(t){return t?Ze.tournamentRecords[t]?(Ze.tournamentId=t,{success:!0}):{error:Y}:(Ze.tournamentId=void 0,{success:!0})}function EL(t){Ze.tournamentRecords=t;let e=Object.keys(t);e.length===1?Ze.tournamentId=e[0]:e.length||(Ze.tournamentId=void 0)}function UL(t){if(typeof t!="string")return{error:G};if(!Ze.tournamentRecords[t])return{error:ve};delete Ze.tournamentRecords[t];let e=Object.keys(Ze.tournamentRecords);return e.length===1?Ze.tournamentId=e[0]:e.length||(Ze.tournamentId=void 0),{success:!0}}function PL(t){return typeof t.subscriptions!="object"?{error:G}:(Object.keys(t.subscriptions).forEach(e=>{typeof t.subscriptions[e]=="function"?Ze.subscriptions[e]=t.subscriptions[e]:delete Ze.subscriptions[e]}),{...C})}function DL(t){return typeof t!="object"?{error:G}:(Object.keys(t).forEach(e=>{typeof t[e]=="function"&&(Ze.methods[e]=t[e])}),{...C})}function NL(){let t=Ze.modified;return Ze.modified=!1,t}function ML({topic:t,payload:e,key:r},n){if(!(typeof t!="string"||typeof e!="object")&&(Ze.disableNotifications||(Ze.modified=!0),!(Ze.disableNotifications||!Ze.subscriptions[t]&&!n)))return r&&(Ze.notices=Ze.notices.filter(o=>!(o.topic===t&&o.key===r))),Ze.notices.push({topic:t,payload:e,key:r}),{...C}}function rp(){return Ze.methods??{}}function RL({topic:t}){return Ze.notices.filter(e=>e.topic===t).map(e=>e.payload)}function CL(){Ze.notices=[]}function bL({topic:t,key:e}){Ze.notices=Ze.notices.filter(r=>(!t||r.topic===t)&&r.key!==e)}function vL(){return{topics:Object.keys(Ze.subscriptions)}}function OL({topic:t,notices:e},r){let n=Ze.subscriptions[t];n&&typeof n=="function"&&n(e);let o=r?.[t];o&&typeof o=="function"&&o(e)}function _L({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:DC(),params:JSON.stringify(r),engine:t,methodName:e,error:o}),{error:o}}var Oe={timers:{default:{elapsedTime:0}},globalSubscriptions:{},deepCopyAttributes:{stringify:[],ignore:[],toJSON:[]},globalMethods:[],deepCopy:!0},cn=xE,NC=["addNotice","callListener","cycleMutationStatus","deleteNotice","deleteNotices","disableNotifications","enableNotifications","getMethods","getNotices","getTopics","getTournamentId","getTournamentRecord","getTournamentRecords","removeTournamentRecord","setSubscriptions","setTournamentId","setTournamentRecord","setTournamentRecords"];function xL(t){if(typeof t!="object")throw new Error("Global state provider can not be undefined or null");if(Yt(Object.keys(t),NC).length!==NC.length)throw new Error("Global state provider is missing required methods");return cn=t,{success:!0}}function wE(){if(cn.createInstanceState){try{cn.createInstanceState()}catch(t){return{error:t}}return{success:!0}}else return{error:EE}}function Pr(t){return!t||typeof t!="object"?Oe.devContext??!1:typeof Oe.devContext!="object"?!1:Object.keys(t).every(e=>Oe.devContext?.[e]===t[e])&&Oe.devContext}function wL(t="reset",e="default"){let r=Date.now();if(t==="report"){if(e==="allTimers")return Object.keys(Oe.timers).filter(o=>o!=="default"||Oe.timers[o].startTime).map(o=>{let i=Oe.timers[o],s=i.state==="stopped"?0:(r-(i?.startTime??0))/1e3,a=i.elapsedTime+s;return{state:Oe.timers[o].state,elapsedTime:a.toFixed(2),timer:o}});{let n=Oe.timers[e].state==="stopped"?0:(r-(Oe.timers[e]?.startTime??0))/1e3,o=Oe.timers[e].elapsedTime+n;return{state:Oe.timers[e].state,elapsedTime:o.toFixed(2),timer:e}}}if(!Oe.timers[e]||t==="reset"){if(e==="allTimers")return Oe.timers={default:{elapsedTime:0}},!0;Oe.timers[e]={startTime:r,state:"active",elapsedTime:0}}return Oe.timers[e].elapsedTime||(Oe.timers[e].elapsedTime=0),t==="stop"&&Oe.timers[e].state!=="stopped"&&(Oe.timers[e].state="stopped")&&(Oe.timers[e].elapsedTime+=(r-(Oe.timers[e]?.startTime??0))/1e3),t==="start"&&(Oe.timers[e].startTime=r)&&(Oe.timers[e].state="active"),Oe.timers[e]}function MC(t){Wr(t)?Oe.globalLog=t:delete Oe.globalLog}function Bc(t){Oe.devContext=t}function LE(){cn.disableNotifications()}function sf(){cn.enableNotifications()}function Hc(t,e){typeof t=="boolean"&&(Oe.deepCopy=t),typeof e=="object"&&(Array.isArray(e.ignore)&&(Oe.deepCopyAttributes.ignore=e.ignore),Array.isArray(e.toJSON)&&(Oe.deepCopyAttributes.toJSON=e.toJSON),Array.isArray(e.stringify)&&(Oe.deepCopyAttributes.stringify=e.stringify),e.threshold&&(Oe.deepCopyAttributes.threshold=e.threshold))}function af(){return{enabled:Oe.deepCopy,...Oe.deepCopyAttributes}}function LL(t){return t?.subscriptions?(Object.keys(t.subscriptions).forEach(e=>{Oe.globalSubscriptions[e]=t.subscriptions[e]}),{...C}):{error:st,info:"missing subscriptions"}}function FL(t){return t?.subscriptions?cn.setSubscriptions({subscriptions:t.subscriptions}):{error:st,info:"missing subscriptions"}}function RC(t){return t?typeof t!="object"?{error:G}:(Object.keys(t).forEach(e=>{Wr(t[e])&&(Oe.globalMethods[e]=t[e])}),{...C}):{error:st,info:"missing method declarations"}}function CC(t){return t?typeof t!="object"?{error:G}:cn.setMethods(t):{error:st,info:"missing method declarations"}}function cf(){return cn.cycleMutationStatus()}function mt(t){if(typeof t?.topic!="string")return;let e=Oe.globalSubscriptions[t.topic];return cn.addNotice(t,e)}function uf(){return{...Oe.globalMethods,...cn.getMethods()}}function jI(t){return cn.getNotices(t)}function YI({key:t,topic:e}){return cn.deleteNotice({key:t,topic:e})}function Fi(){return cn.deleteNotices()}function Lr(){return cn.getTopics()}function np(t){return Lr()?.topics?.includes(t)}async function Dm(t){return cn.callListener(t,Oe.globalSubscriptions)}function ns(){return cn.getTournamentId()}function pf(t){return cn.getTournamentRecord(t)}function Fo(){return cn.getTournamentRecords()}function FE(t){return cn.setTournamentRecord(t)}function Nm(t){return cn.setTournamentRecords(t)}function op(t){return cn.setTournamentId(t)}function kE(t){return cn.removeTournamentRecord(t)}function qI(){return cn}function ip({engineName:t,methodName:e,params:r,err:n}){let o=Wr(cn.handleCaughtError)&&cn.handleCaughtError||xE.handleCaughtError,{tournamentRecord:i,...s}=r;return o({params:s,engineName:t,methodName:e,err:n})}function GE(t,e){if(Oe.globalLog)try{Oe.globalLog({log:t,engine:e})}catch(r){console.log("globalLog error",r),console.log(e,t),MC()}else console.log(e,t)}function VE(t,e,r,n){if(!ht(t))return{error:G};Zt||(r=1);let o=Array.isArray(e)?e:[],i={},s=(a,c=0)=>{Object.keys(a).forEach(u=>{Wr(a[u])?i[u]=a[u]:ht(a[u])&&(e===!0||o?.includes(u))&&(r===void 0||c<r)&&s(a[u],c+1)})};return s(t),n?RC(i):CC(i),{methods:i}}function kL(t,e,r){return Object.keys(t).filter(n=>!e.includes(t[n])&&(!r||(Array.isArray(t[n])?t[n].length:!0)))}function ot(t,e,r,n){if(typeof t!="object"||t===null)return t;af()?.enabled||(n=!0);let i=["",void 0,null];e&&i.push(!1);let s=kL(t,i,r);return Object.assign({},...s.map(a=>Array.isArray(t[a])?{[a]:n?t[a]:t[a].map(c=>ot(c))}:{[a]:n?t[a]:ot(t[a])}))}function _({context:t,result:e,stack:r,info:n}){return e&&!Array.isArray(e?.stack)&&(e.stack=[]),e&&Array.isArray(e?.stack)&&typeof r=="string"&&e.stack.push(r),e&&n&&(e.info=n),e&&typeof t=="object"&&Object.keys(t).length&&Object.assign(e,ot(t)),e&&!e?.error&&!e?.success&&Object.assign(e,{...C}),e??{success:!0}}var Pn="ANY",$t="MALE",Tr="MIXED",os="OTHER",ne="FEMALE",Mm={ANY:Pn,MALE:$t,FEMALE:ne,MIXED:Tr,OTHER:os};var GL="MIXED events can not contain mixed singles or { gender: ANY } collections",VL="events with { gender: ANY } can not contain MIXED singles collections";function Rm(t){let e="tieFormatGenderValidityCheck",{referenceGender:r,matchUpType:n,gender:o}=t;return r&&o&&[$t,ne].includes(r)&&r!==o?_({result:{valid:!1,error:Ju},context:{gender:o},stack:e}):r===Tr&&(o===Pn||o===Tr&&n!==_t)?_({result:{error:Ju,valid:!1},info:GL,stack:e}):r===Pn&&o===Tr&&n!==_t?_({result:{error:Ju,valid:!1},info:VL,stack:e}):{valid:!0}}var BL="normal",BE="timed",HL="final",mf="NOAD",Cm="SET",vC={S:BL,F:HL};function sp(t,e){if(ht(t),(t?.bestOf||t?.exactly)&&t?.setFormat)return WL(t,e)}function df(t){return!isNaN(Number(t))&&Number(t)}function xC(t){let e=`T${t.minutes}`;return t.based&&(e+=t.based),t.modifier&&(e+=`@${t.modifier}`),e}function WL(t,e){let r=df(t.bestOf)||void 0,n=df(t.exactly)||void 0,o=r||n;if(t.setFormat?.timed&&t.simplified&&o===1)return xC(t.setFormat);let i=o&&`${Cm}${o}`||"",s=OC(t.setFormat,e),a=s&&`S:${s}`||"",c=OC(t.finalSetFormat,e),u=o&&o>1&&c&&s!==c&&`F:${c}`||"";if(i&&s)return[i,a,u].filter(m=>m).join("-")}function OC(t,e){if(typeof t=="object"&&Object.keys(t).length){if(t.timed)return xC(t);if(t.tiebreakSet)return _C(t.tiebreakSet);let r=df(t.setTo);if(r){let n=t.NoAD&&mf||"",o=_C(t.tiebreakFormat),i=o&&`/${o}`||"",s=df(t.tiebreakAt),a=s&&(s!==r||e)&&`@${s}`||"";if(o!==!1)return`${r}${n}${i}${a}`}}}function _C(t){if(t){if(typeof t=="object"&&!t.tiebreakTo)return"";if(typeof t=="object"&&df(t.tiebreakTo)){let e=`TB${t.tiebreakTo}${t.NoAD?mf:""}`;return t.modifier&&(e+=`@${t.modifier}`),e}else return!1}}function Ye(t){if(Vt(t)){let e=t.startsWith("T")&&BE||t.startsWith(Cm)&&Cm||"";if(e===BE){let r=kC(t),n={simplified:!0,setFormat:r,bestOf:1};if(r)return n}if(e===Cm)return jL(t)}}function jL(t){let e=t.split("-"),r=lf(e[0].slice(3)),n=r===1||r%2!==0?r:void 0,o=r!==1&&r%2===0?r:void 0,i=e&&wC(e[1]),s=e&&wC(e[2]),a=i&&i.timed||s&&s.timed,c=n&&n<6||a&&o,u=!e[2]||s,p=i,m=ot({setFormat:i,exactly:o,bestOf:n});if(s&&(m.finalSetFormat=s),c&&p&&u)return m}function wC(t){if(t?.[1]===":"){let e=t.split(":"),r=vC[e[0]],n=e[1];if(r&&n){if(n.startsWith("TB")){let I=LC(n);return I===!1?!1:typeof I=="object"?{tiebreakSet:I}:void 0}if(n.startsWith("T"))return kC(n);let s=t.match(/^[FS]:(\d+)([A-Za-z]*)/),a=s&&GC(s[2])||!1,c=!s?.[2]||a,u=s?lf(s[1]):void 0,p=FC(n),m=p!==!1,d=m&&p||u,l=LC(n.split("/")[1]),f=l!==!1,g={setTo:u};return a&&(g.NoAD=!0),l?(g.tiebreakFormat=l,g.tiebreakAt=d):g.noTiebreak=!0,u&&c&&f&&m&&g||!1}}}function FC(t,e=!0){let r=t?.indexOf("@")>0&&t.split("@");if(r)return(e?lf(r[1]):r[1])||!1}function LC(t){if(t)if(t.startsWith("TB")){let e=FC(t,!1),r=t.match(/^TB(\d+)([A-Za-z]*)/),n=r?.[1],o=r&&GC(r[2]),i=!r?.[2]||o,s=lf(n);if(s&&i){let a={tiebreakTo:s};return e&&typeof e=="string"&&!It(e)&&(a.modifier=e),o&&(a.NoAD=!0),a}else return!1}else return!1}function kC(t){let e=t.slice(1),r=e.match(/^(\d+)(@?[A-Za-z]*)/),n=lf(r?.[1]);if(!n)return;let o={timed:!0,minutes:n},i=r?.[2],s=[void 0,"P","G"].includes(i);if(i&&!s){let a=e.match(/^(\d+)(@)([A-Za-z]+)$/)?.[3];return a?(o.modifier=a,o):void 0}return i&&(o.based=r[2]),o}function GC(t){return t&&t.indexOf(mf)>=0}function lf(t){return isNaN(Number(t))?0:Number(t)}function Dr({matchUpFormat:t}){if(!Vt(t)||t==="")return!1;let e=Ye(t),r=t.match(/-S:([1-9])+\/TB([0-9]{1,2})@?([1-9]?)*/),n=r?.[1],o=r?.[2],i=r?.[3],s=t.match(/-F:([1-9])+\/TB([0-9]{1,2})@?([1-9]?)*/),a=s?.[1],c=s?.[2],u=s?.[3];return sp(e,!!(r&&o&&n===i||s&&c&&a===u))===t}var bm=/^[\d]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][\d]|3[0-1])$/,$I=/^((0[\d]|1[\d]|2[0-3]):[0-5][\d](:[0-5][\d])?)([.,][0-9]{3})?$/,Po=/^([\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?$/,xs=/^([\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 vm(t){let{scheduledDate:e}=t;if(!e&&t.scheduledTime&&(e=Et(t.scheduledTime)),!e)return;let r=Kt(t.scheduledTime),n=Et(e);return n&&r&&(n+=`T${r}`),n}function VC(t){return typeof t!="object"||Array.isArray(t)?!1:Object.prototype.toString.call(t)==="[object Date]"}function Wc(t){let e=typeof t=="string"?t?.split(" "):[];return t&&e?.length>1&&!["AM","PM"].includes(e[1].toUpperCase())?!1:!!(!t||xs.test(Xa(t,!0,!0)))}function Cr(t){return Qa(t)||bm.test(t)}function YL(t){let e=new Date(t),r=e.getSeconds()+60*e.getMinutes()+60*60*e.getHours();return qL(r,{displaySeconds:!1})}function qL(t,e){let r=parseInt(t,10),n=Math.floor(r/3600),o=Math.floor((r-n*3600)/60),i=r-n*3600-o*60;return(!e||e?.displaySeconds?n+":"+o+":"+i:n+":"+o).split(":").map(Zn).join(":")}var If=t=>{let e=ff(t)||Qa(t)?new Date(t):new Date,r=e.getUTCMonth()+1,n=r<10?`0${r}`:`${r}`;return`${e.getUTCFullYear()}-${Zn(n)}-${Zn(e.getUTCDate())}`};function $L(t){let e=ff(t)||Qa(t)?new Date(t):new Date;return Date.UTC(e.getFullYear(),e.getMonth(),e.getDate())}function Wn(t,e="-",r="YMD"){if(!t)return"";typeof t=="string"&&t.indexOf("T")<0&&(t=t+"T00:00");let n=new Date(t),o=""+(n.getMonth()+1),i=""+n.getDate(),s=n.getFullYear();return o.length<2&&(o="0"+o),i.length<2&&(i="0"+i),r==="DMY"?[i,o,s].join(e):r==="MDY"?[o,i,s].join(e):r==="YDM"?[s,i,o].join(e):r==="DYM"?[i,s,o].join(e):r==="MYD"?[o,s,i].join(e):[s,o,i].join(e)}function KI(t){let e=t?new Date(t):new Date,r=e.getTimezoneOffset();return new Date(e.getTime()-r*60*1e3)}function KL(t){return KI(t).getTime()}function ff(t){if(typeof t=="boolean")return!1;let e=t instanceof Date&&t||!isNaN(t)&&new Date(t)||!1;return e&&!isNaN(e.valueOf())}function ws(t,e){if(!Cr(t)||!Cr(e))return[];let r=Et(t)+"T00:00",n=Et(e)+"T00:00",o=new Date(r),i=new Date(n),s=ff(i)&&ff(o)&&u(o,i),a=[],c=0;if(s){let p=o,m=p.getTime();for(;m<=i.getTime()&&c<300;)c+=1,a.push(new Date(p)),m=p.setDate(p.getDate()+1)}return a.map(p=>Wn(p));function u(p,m){return p<=m}}var zL=/^([+-]?\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 Qa(t){return typeof t!="string"?!1:zL.test(t)}function QI(t){if(typeof t!="string")return!1;let r=t.split("Z")[0].split(":"),n=r.every(i=>!isNaN(parseInt(i)));return!(r.length<2||!n||parseInt(r[0])>23||parseInt(r[1])>60)}function qt(t){let e=Kt(t);if(!e)return 0;let[r,n]=e.split(":").map(o=>parseInt(o));return r*60+n}function BC(t){let e=Math.floor(t/60),r=t-e*60;return e>23&&(e=e%24),[Zn(e),Zn(r)].join(":")}function gf(t){return QI(t)?t.split(":").slice(0,2).map(Zn).join(":"):void 0}function Kt(t){return Qa(t)&&t.indexOf("T")>0?gf(t.split("T").reverse()[0]):gf(t)}function Et(t){return Qa(t)||Po.test(t)?t.split("T")[0]:void 0}function ap(t,e){let r=new Date(t);return r.setDate(r.getDate()+e),Et(r.toISOString())}function zI(t){t=typeof t!="string"?"00:00":t;let e={},r={};return{0:e.time,1:e.ampm}=t.split(" ")||[],{0:r.hours,1:r.minutes}=e.time.split(":")||[],r.ampm=e.ampm,isNaN(r.hours)||isNaN(r.minutes)||r.ampm&&!["AM","PM"].includes(r.ampm.toUpperCase())?{}:r}function QL(t){let e=zI(t);return e.ampm&&e.hours&&(e.ampm.toLowerCase()==="pm"&&parseInt(e.hours)<12&&(e.hours=(e.hours&&parseInt(e.hours)||0)+12),e.ampm.toLowerCase()==="am"&&e.hours==="12"&&(e.hours="00")),`${e.hours||"12"}:${e.minutes||"00"}`.split(":").map(Zn).join(":")}function XL(t){let e=zI(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 Xa(t,e,r){let n=Et(t),o=Kt(t),i=n?o:t;return t?e&&(n&&r&&t||QL(i))||XL(i):void 0}function XI(t,e){let r=zI(t),n=zI(e);if(parseInt(r.hours)<parseInt(n.hours))return-1;if(parseInt(r.hours)>parseInt(n.hours))return 1;if(r.hours===n.hours){if(parseInt(r.minutes)<parseInt(n.minutes))return-1;if(parseInt(r.minutes)>parseInt(n.minutes))return 1}return 0}function JI(t,e=7){let r=Et(t)+"T00:00",n=new Date(r),o=new Date(n.setDate(n.getDate()+e));return Wn(o)}function JL(t){return JI(t)}function ZL(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())),Wn(o,r)}function HC(t,e,r){let n=new Date(t,0);return Wn(new Date(n.setDate(e)),r)}function ke(t,e=void 0){let[r,n]=(t||"00:00").split(":").map(Zn),o=KI(e).setHours(r,n,0,0);return KI(o)}function ma(t,e,r=!0){let n=new Date(t),i=(new Date(e).getTime()-n.getTime())/1e3/60;return r?Math.abs(Math.round(i)):Math.round(i)}function Yr(t,e){let r=Kt(t);if(!r)return"00:00";let n=isNaN(e)?0:e;return Kt(hf(ke(r),n).toISOString())}function hf(t,e){let r=new Date(t);return new Date(r.getTime()+e*6e4)}function Zn(t){return t.toString()[1]?t:"0"+t}function jn(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 ZI={addDays:JI,addWeek:JL,addMinutesToTimeString:Yr,convertTime:Xa,getIsoDateString:vm,getUTCdateString:If,DateHHMM:YL,extractDate:Et,extractTime:Kt,formatDate:Wn,getDateByWeek:ZL,isISODateString:Qa,isDate:ff,isTimeString:QI,offsetDate:KI,offsetTime:KL,sameDay:jn,timeStringMinutes:qt,timeToDate:ke,timeUTC:$L,validTimeValue:Wc,validDateString:bm,timeValidation:xs,dateValidation:Po};var tF=(t,e)=>t.filter(Boolean).every(r=>typeof r===e),eF=t=>t.filter(Boolean).every(Zt);function Ls(t){let e=t.category;if(typeof e!="object")return{error:Vc};let{ageCategoryCode:r,ageMaxDate:n,ageMinDate:o,ageMax:i,ageMin:s}=e,a=e.categoryName,c;if(!tF([r,n,o,a],"string")||!eF([i,s]))return{error:Vc};let u=t.consideredDate??Et(new Date().toLocaleDateString("sv"));if(!Cr(u))return{error:je};let[p]=u.split("-").slice(0,3).map(w=>parseInt(w)),m=ap(u,-1),[d,l]=m.split("-").slice(1,3).map(w=>parseInt(w)),f=`${Zn(d)}-${Zn(l)}`,g=ap(u,1),[I,h]=g.split("-").slice(1,3).map(w=>parseInt(w)),S=`${Zn(I)}-${Zn(h)}`,T=s&&ap(u,-1*365*s),y=i&&ap(u,-1*365*i),P=[],U=w=>!P.includes(w)&&P.push(w);r=r??a;let A=/^([UO]?)(\d{1,2})([UO]?)$/,E=/^C(\d{1,2})-(\d{1,2})$/,N=r?.includes("-"),D=N&&r?.match(E),M=r?.match(A),R=(w,V)=>`${w}-${V}`,b=w=>{let V=p-w,k=R(V,S);e.ageMinDate&&e.ageMinDate!==k&&U(`Invalid submitted ageMinDate: ${o}`),o=k,r&&(e.ageMax&&e.ageMax!==w-1&&(U(`Invalid submitted ageMax: ${i}`),y=void 0),i=w-1)},v=w=>{let V=p-w-1,k=R(V,S);e.ageMin&&e.ageMin>w&&U(`Invalid submitted ageMin: ${s}`),e.ageMax&&e.ageMax>w&&U(`Invalid submitted ageMax: ${i}`),e.ageMinDate&&e.ageMinDate!==k&&U(`Invalid submitted ageMinDate: ${o}`),o=k,r&&(e.ageMax&&e.ageMax!==w&&(U(`Invalid submitted ageMax: ${i}`),T=void 0),i=w)},O=w=>{let V=p-w,k=R(V,f);e.ageMaxDate&&e.ageMaxDate!==k&&U(`Invalid submitted ageMaxDate: ${n}`),n=k,r&&(e.ageMin&&e.ageMin!==w+1&&(U(`Invalid submitted ageMin: ${s}`),T=void 0),s=w+1)},x=w=>{let V=p-w-1,k=R(V,f);e.ageMaxDate&&e.ageMaxDate!==k&&U(`Invalid submitted ageMaxDate: ${n}`),n=k,r&&(e.ageMin&&e.ageMin!==w&&(U(`Invalid submitted ageMin: ${s}`),T=void 0),s=w)},F=w=>{let[V,k,W]=(w.match(A)||[]).slice(1),H=parseInt(k);V==="U"?(e.ageMaxDate&&e.ageMaxDate!==n&&U(`Invalid submitted ageMaxDate: ${e.ageMaxDate}`),b(H)):V==="O"&&O(H),W==="U"?(e.ageMaxDate&&e.ageMaxDate!==n&&U(`Invalid submitted ageMaxDate: ${e.ageMaxDate}`),v(H)):W==="O"&&x(H),n=n??T,o=o??y};if(D){if(n=void 0,o=void 0,i=void 0,s=void 0,e.ageMin){let k=p-e.ageMin;n=R(k,f)}if(e.ageMax){let k=p-e.ageMax-1;o=R(k,S)}let[w,V]=(r?.match(E)??[]).slice(1).map(k=>parseInt(k));w<=V?(s=w,i=V,c=!0):U(`Invalid combined age range ${r}`)}else N?r?.split("-").forEach(F):M?F(r):(s&&O(s),i&&v(i));i&&e.ageMin&&e.ageMin>i&&(U(`Invalid submitted ageMin: ${e.ageMin}`),s=void 0);let L=ot({consideredDate:u,combinedAge:c,ageMaxDate:n,ageMinDate:o,ageMax:i,ageMin:s});return P.length&&(L.errors=P),L}function jc({category:t}){if(!ht(t))return{error:G};let e=Ls({category:t});if(e.error)return{error:e};let{ratingMax:r,ratingMin:n}=t;return r&&!Zt(r)?_({result:{error:G},context:{ratingMax:r}}):n&&!Zt(n)?_({result:{error:G},context:{ratingMin:n}}):{...e}}function Yc({childCategory:t,withDetails:e,category:r}){let n=jc({category:r}),o=jc({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=ot({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 qc({checkCategory:t=!0,collectionDefinition:e,checkCollectionIds:r,checkGender:n=!0,referenceCategory:o,referenceGender:i,event:s}){i=i??s?.gender;let a="validateCollectionDefinition",c=[];if(typeof e!="object")return c.push(`collectionDefinition must be an object: ${e}`),_({result:{errors:c,error:lo},stack:a});let{collectionValueProfiles:u,collectionGroupNumber:p,collectionValue:m,collectionId:d,matchUpCount:l,matchUpFormat:f,matchUpValue:g,matchUpType:I,scoreValue:h,setValue:S,category:T,gender:y}=e;if(r&&typeof d!="string"&&c.push(`collectionId is not type string: ${d}`),typeof l!="number"&&c.push(`matchUpCount is not type number: ${l}`),I&&!Lc([Ft,_t],I)&&c.push(`matchUpType must be SINGLES or DOUBLES: ${I}`),[!!u?.length].concat([g,m,h,S].map(It)).filter(Boolean).length!==1&&c.push("Missing value definition for matchUps: matchUpValue, collectionValue, or collectionValueProfiles"),g&&typeof g!="number"&&c.push(`matchUpValue is not type number: ${g}`),m&&typeof m!="number"&&c.push(`collectionValue is not type number: ${m}`),u&&l){let U=CI({collectionValueProfiles:u,matchUpCount:l});U.errors&&c.push(...U.errors)}if(p&&typeof p!="number"&&c.push(`collectionGroupNumber is not type number: ${m}`),f&&!Dr({matchUpFormat:f})&&c.push(`Invalid matchUpFormat: ${f}`),n){let U=Rm({referenceGender:i,matchUpType:I,gender:y});if(U.error)return _({context:{referenceGender:i,gender:y},result:U,stack:a})}if(t&&o&&T){let U=Yc({category:o,childCategory:T});if(!U.valid)return _({result:{error:Vc},context:U,stack:a})}return c.length?_({result:{errors:c,error:ME},stack:a}):{valid:!0}}function ar(t){let e=!!(t?.enforceCategory!==!1&&t?.category),r=!!(t?.enforceGender!==!1&&t?.gender),n=t?.checkCollectionIds,o=t?.tieFormat,i=t?.event,s="validateTieFormat",a=[],c=rF({...t,stack:s});if(c?.error)return c;let u,p=o.collectionDefinitions.every(I=>{let{setValue:h,scoreValue:S,collectionValue:T}=I;(h||S)&&!T&&(u=!0);let{valid:y,errors:P}=qc({referenceCategory:t.category,referenceGender:t.gender,collectionDefinition:I,checkCollectionIds:n,checkCategory:e,checkGender:r,event:i});return y?!0:(Array.isArray(P)&&a.push(...P),!1)}),m=typeof o.winCriteria?.valueGoal=="number"&&o.winCriteria?.valueGoal>0&&!u||o.winCriteria?.aggregateValue;if(!(m||o.winCriteria?.aggregateValue))return u?a.push("aggregateValue is required"):a.push("Either non-zero valueGoal, or { aggregateValue: true } must be specified in winCriteria"),_({context:{tieFormat:o,errors:a,aggregateValueImperative:u},result:{error:Lo},stack:s});let d=o.collectionDefinitions.map(({collectionId:I})=>I),l=!n||d.length===ut(d).length,f=p&&m&&l,g={valid:f,errors:a};return f?g:_({result:{error:Lo},context:{tieFormat:o,errors:a},stack:s})}function rF(t){let{tieFormat:e,stack:r}=t;return!t||!e||!ht(e)?_({result:{error:Lo},context:{tieFormat:e,message:"tieformat must be an object"},stack:r}):ht(e.winCriteria)?Array.isArray(e.collectionDefinitions)?{...C}:_({result:{error:Lo},context:{tieFormat:e,message:"collectionDefinitions must be an array"},stack:r}):_({result:{error:Lo},context:{tieFormat:e,message:"tieformat.winCritiera must be an object"},stack:r})}var Ja="resourceSubType",Za="resourceType",tc="identifier",WC={RESOURCE_SUB_TYPE:Ja,RESOURCE_TYPE:Za,IDENTIFIER:tc};function J(t,e,r,n,o=0){if(qI().makeDeepCopy)return qI().makeDeepCopy(t,e,r,n);let i=af(),{stringify:s,toJSON:a,ignore:c,modulate:u}=i||{};if(!i?.enabled&&!r||typeof t!="object"||Wr(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)||Wr(c)&&!c(l)),d=(l,f)=>{p[l]=Wr(f?.toString)?f.toString():JSON.stringify(f)};for(let l of m){let f=t[l],g=Wr(u)?u(f):void 0;if(g!==void 0)p[l]=g;else if(e&&l==="extensions"&&Array.isArray(f)){let I=Sf(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)&&Wr(f?.toJSON)?p[l]=f.toJSON():f===null?p[l]=void 0:VC(f)?p[l]=new Date(f).toISOString():p[l]=J(f,e,r,n,o+1)}return p}function Sf(t){return t?.map(e=>{let{name:r,value:n}=e;return r&&n&&{[`_${r}`]:n}}).filter(Boolean)}function th(t=1,e){return et(0,t).map(()=>Dt(e))}function Dt(t){let e=[];for(let a=0;a<256;a++)e[a]=(a<16?"0":"")+a.toString(16);let r=Math.random()*4294967295|0,n=Math.random()*4294967295|0,o=Math.random()*4294967295|0,i=Math.random()*4294967295|0,s=e[r&255]+e[r>>8&255]+e[r>>16&255]+e[r>>24&255]+"-"+e[n&255]+e[n>>8&255]+"-"+e[n>>16&15|64]+e[n>>24&255]+"-"+e[o&63|128]+e[o>>8&255]+"-"+e[o>>16&255]+e[o>>24&255]+e[i&255]+e[i>>8&255]+e[i>>16&255]+e[i>>24&255];return typeof t=="string"?`${t}_${s.replace(/-/g,"")}`:s}var eh={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 rh={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 nh={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 oh={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 ih={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 sh={collectionDefinitions:[{scoreValue:1,matchUpType:"SINGLES",collectionName:"Men's Singles",matchUpFormat:"SET1-S:T60",gender:"MALE",matchUpCount:1},{scoreValue:1,matchUpType:"SINGLES",collectionName:"Women's Singles",matchUpFormat:"SET1-S:T60",gender:"FEMALE",matchUpCount:1},{matchUpValue:1,matchUpType:"DOUBLES",collectionName:"Mixed Doubles",matchUpFormat:"SET1-S:T60",gender:"MIXED",matchUpCount:1}],tieFormatName:"Time Tennis Pro Circuit",winCriteria:{aggregateValue:!0}};var ah={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 ch={collectionDefinitions:[{scoreValue:1,matchUpType:"SINGLES",collectionName:"Men's Singles",matchUpFormat:"SET1-S:T60",gender:"MALE",matchUpCount:3},{scoreValue:1,matchUpType:"SINGLES",collectionName:"Women's Singles",matchUpFormat:"SET1-S:T60",gender:"FEMALE",matchUpCount:3},{scoreValue:1,matchUpType:"DOUBLES",collectionName:"Men's Doubles",matchUpFormat:"SET1-S:T60",gender:"MALE",matchUpCount:1},{matchUpValue:1,matchUpType:"DOUBLES",collectionName:"Women's Doubles",matchUpFormat:"SET1-S:T60",gender:"FEMALE",matchUpCount:1},{matchUpValue:1,matchUpType:"DOUBLES",collectionName:"Mixed Doubles",matchUpFormat:"SET1-S:T60",gender:"MIXED",matchUpCount:1}],tieFormatName:"Time Tennis Dual",winCriteria:{aggregateValue:!0}};var uh={collectionDefinitions:[{category:{ageCategoryCode:"14U"},collectionName:"14U Singles",matchUpCount:2,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{category:{ageCategoryCode:"16U"},collectionName:"16U Singles",matchUpCount:2,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{category:{ageCategoryCode:"18U"},collectionName:"18U Singles",matchUpCount:2,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{category:{ageCategoryCode:"14U"},collectionName:"14U Doubles",collectionGroupNumber:1,matchUpCount:1,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1},{category:{ageCategoryCode:"16U"},collectionName:"16U Doubles",collectionGroupNumber:1,matchUpCount:1,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1},{category:{ageCategoryCode:"18U"},collectionName:"18U Doubles",collectionGroupNumber:1,matchUpCount:1,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1}],collectionGroups:[{groupNumber:1,groupName:"Doubles",groupValue:1,winCriteria:{valueGoal:2}}],tieFormatName:"USTA_BREWER_CUP",winCriteria:{valueGoal:4}};var ph={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 Dn="SET3-S:6/TB7",lF="SET3-S:6NOAD",HE="SET3-S:6/TB7-F:TB10",fF="SET3-S:4/TB7",gF="SET3-S:4/TB5@3",IF="SET1-S:T20",hF="SET1-S:8/TB7",SF="SET1-S:8/TB7@7",jC={FORMAT_STANDARD:Dn,FORMAT_STANDARD_NOAD:lF,FORMAT_ATP_DOUBLES:HE,FORMAT_SHORT_SETS:fF,FORMAT_FAST4:gF,FORMAT_PRO_SET:hF,FORMAT_COLLEGE_PRO_SET:SF,TIMED20:IF};var mh={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 dh={collectionDefinitions:[{collectionName:"Doubles",matchUpCount:3,matchUpFormat:"SET1-S:8/TB7@7",matchUpType:"DOUBLES",collectionValue:1},{collectionName:"Singles",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1}],tieFormatName:"USTA_COLLEGE",winCriteria:{valueGoal:4}};var lh={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 fh={collectionDefinitions:[{collectionName:"Female Doubles",gender:"FEMALE",matchUpCount:1,matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Male Doubles",gender:"MALE",matchUpCount:1,matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Female Singles",gender:"FEMALE",matchUpCount:1,matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"SINGLES",scoreValue:1},{collectionName:"Male Singles",matchUpCount:1,gender:"MALE",matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"SINGLES",scoreValue:1},{collectionName:"Mixed Doubles",matchUpCount:1,gender:"MIXED",matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Mixed Doubles",matchUpCount:1,gender:"MIXED",matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Overtime",matchUpCount:1,gender:"MIXED",matchUpFormat:"SET1-S:T20",matchUpType:"DOUBLES",scoreValue:1}],tieFormatName:"USTA_WTT_ITT",winCriteria:{aggregateValue:!0}};var gh={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 Ih={collectionDefinitions:[{collectionGroupNumber:1,matchUpType:"DOUBLES",matchUpCount:1,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpValue:1},{collectionGroupNumber:1,matchUpType:"SINGLES",matchUpCount:3,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpValue:1},{collectionGroupNumber:2,matchUpType:"DOUBLES",matchUpCount:1,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpValue:2},{collectionGroupNumber:2,matchUpType:"SINGLES",matchUpCount:3,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpValue:2},{collectionGroupNumber:3,matchUpType:"DOUBLES",matchUpCount:1,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpValue:3},{collectionGroupNumber:3,matchUpType:"SINGLES",matchUpCount:3,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpValue:3}],collectionGroups:[{groupNumber:1,groupName:"Day 1"},{groupNumber:2,groupName:"Day 2"},{groupNumber:3,groupName:"Day 3"}],tieFormatName:"LAVER_CUP",winCriteria:{valueGoal:13}};var hh={collectionDefinitions:[{collectionName:"Female Doubles",gender:"FEMALE",matchUpCount:1,matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Male Doubles",gender:"MALE",matchUpCount:1,matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Female Singles",gender:"FEMALE",matchUpCount:1,matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"SINGLES",scoreValue:1},{collectionName:"Male Singles",matchUpCount:1,gender:"MALE",matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"SINGLES",scoreValue:1},{collectionName:"Mixed Doubles",matchUpCount:1,gender:"MIXED",matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Overtime",matchUpCount:1,gender:"MIXED",matchUpFormat:"SET1-S:T20",matchUpType:"DOUBLES",scoreValue:1}],tieFormatName:"USTA_TOC",winCriteria:{aggregateValue:!0}};var Om="COLLEGE_DEFAULT",Sh="COLLEGE_JUCO",Th="COLLEGE_D3",WE="DOMINANT_DUO",jE="DOMINANT_DUO_MIXED",YE="LAVER_CUP",qE="TEAM_DOUBLES_3_AGGREGATION",$E="TIME_TENNIS_DUAL",KE="TIME_TENNIS_PRO_CIRCUIT",zE="USTA_BREWER_CUP",QE="USTA_OZAKI_CUP",XE="USTA_COLLEGE",JE="USTA_GOLD_TEAM_CHALLENGE",ZE="USTA_LEVEL_1",tU="USTA_INTERSECTIONAL",eU="USTA_SECTION_BATTLE",rU="USTA_SOUTHERN_LEVEL_5",nU="USTA_TOC",oU="USTA_WTT_ITT",iU="USTA_ZONAL",YC={COLLEGE_D3:Th,COLLEGE_DEFAULT:Om,COLLEGE_JUCO:Sh,DOMINANT_DUO:WE,DOMINANT_DUO_MIXED:jE,LAVER_CUP:YE,TEAM_DOUBLES_3_AGGREGATION:qE,TIME_TENNIS_DUAL:$E,TIME_TENNIS_PRO_CIRCUIT:KE,USTA_BREWER_CUP:zE,USTA_OZAKI_CUP:QE,USTA_COLLEGE:XE,USTA_GOLD_TEAM_CHALLENGE:JE,USTA_INTERSECTIONAL:tU,USTA_LEVEL_1:ZE,USTA_SECTION_BATTLE:eU,USTA_SOUTHERN_LEVEL_5:rU,USTA_TOC:nU,USTA_WTT_ITT:oU,USTA_ZONAL:iU};var $C="STANDARD",qC={[$C]:{hydrate:!0,doubles:{matchUpCount:3,matchUpValue:1},singles:{matchUpCount:6,matchUpValue:1},valueGoal:5},[Th]:{hydrate:!0,doubles:{matchUpFormat:"SET1-S:8/TB7@7",matchUpCount:3,matchUpValue:1},singles:{matchUpFormat:Dn,matchUpCount:6,matchUpValue:1},tieFormatName:Th,valueGoal:5},[Om]:{hydrate:!0,doubles:{matchUpFormat:"SET1-S:6/TB7",collectionValue:1,matchUpCount:3},singles:{matchUpFormat:Dn,matchUpCount:6,matchUpValue:1},tieFormatName:Om,valueGoal:4},[Sh]:{hydrate:!0,doubles:{matchUpFormat:"SET1-S:8/TB7",matchUpCount:3,matchUpValue:1},singles:{matchUpFormat:Dn,matchUpCount:6,matchUpValue:1},tieFormatName:Sh,valueGoal:5},[YE]:Ih,[WE]:mh,[jE]:ah,[qE]:rh,[$E]:ch,[KE]:sh,[zE]:uh,[QE]:ph,[XE]:dh,[JE]:eh,[tU]:ih,[ZE]:lh,[eU]:oh,[rU]:nh,[oU]:fh,[nU]:hh,[iU]:gh},NF=t=>{let e=t?.namedFormat&&Object.keys(qC).includes(t.namedFormat)?t.namedFormat:$C,r=Array.isArray(t?.uuids)?t?.uuids:[],n,{category:o,gender:i}=t?.event??{},s=J(qC[e],!1,!0),a=c=>{if(!t?.isMock&&!t?.event?.isMock||!t.event)return r?.pop()??Dt();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:HE,collectionName:"Doubles",matchUpType:_t,...s.doubles},{collectionId:a(1),matchUpFormat:Dn,collectionName:"Singles",matchUpType:Ft,...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},to=NF;var Yn="SINGLES",Fs="SINGLES",qr="DOUBLES",ko="DOUBLES",_e="TEAM",br="TEAM",MF="AGE",RF="RATING",CF="BOTH",KC={AGE:MF,BOTH:CF,DOUBLES:qr,DOUBLES_EVENT:ko,RATING:RF,SINGLES:Yn,SINGLES_EVENT:Fs,TEAM_EVENT:br,TEAM:_e};var nt="MAIN",ct="QUALIFYING",qe="CONSOLATION",$e="VOLUNTARY_CONSOLATION",de="PLAY_OFF",$c=[nt,ct,qe,de,$e],ks={[ct]:1,[nt]:2,[de]:3,[qe]:3,[$e]:4},sU="finishingPositions",aU="aggregateEventStructures",cU={[nt]:1,[de]:2,[qe]:3,[ct]:4,[$e]:5},zC={[de]:1,[nt]:2,[qe]:3,[ct]:4,[$e]:5},Kc="CLUSTER",QC="SEPARATE",di="WATERFALL",cp="ITEM",Ge="CONTAINER",dn="DRAW",up="RANDOM",En="TOP_DOWN",li="BOTTOM_UP",eo="POSITION",fo="WINNER",ro="LOSER",On="FIRST_MATCHUP",$r="AD_HOC",bF="AD_HOC",da="FEED_IN",zc="COMPASS",Qc="OLYMPIC",vF="SINGLE_ELIMINATION";var go="SINGLE_ELIMINATION",Xc="DOUBLE_ELIMINATION",Jc="FIRST_MATCH_LOSER_CONSOLATION",pp="FIRST_ROUND_LOSER_CONSOLATION",ki="LUCKY_DRAW",Tf="CURTIS_CONSOLATION",XC="CURTIS_CONSOLATION",yh="FEED_IN_CHAMPIONSHIP_TO_SF",_m="FEED_IN_CHAMPIONSHIP_TO_SF",Ah="FEED_IN_CHAMPIONSHIP_TO_QF",xm="FEED_IN_CHAMPIONSHIP_TO_QF",Eh="FEED_IN_CHAMPIONSHIP_TO_R16",wm="FEED_IN_CHAMPIONSHIP_TO_R16",uU="MODIFIED_FEED_IN_CHAMPIONSHIP",Lm="MODIFIED_FEED_IN_CHAMPIONSHIP",mp="FEED_IN_CHAMPIONSHIP",JC="DOUBLE_ROUND_ROBIN",Nn="ROUND_ROBIN",Io="ROUND_ROBIN_WITH_PLAYOFF",pU="DECIDER",mU="BACKDRAW",yf={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"}},Af={0:{name:"East",abbreviation:"E"},"0-1":{name:"West",abbreviation:"W"},"0-2":{name:"North",abbreviation:"N"},"0-1-1":{name:"South",abbreviation:"S"}},fi="WIN_RATIO",Gi="ROUND_OUTCOME",dU=[zc,Tf,xm,wm,_m,mp,Ah,Eh,yh,Jc,pp,ki,Lm,Qc,de,Io],OF=[$r,zc,Tf,Xc,xm,wm,_m,mp,da,Jc,pp,ki,Lm,Qc,de,Nn,Io,go],lU={MAIN:nt,QUALIFYING:ct,CONSOLATION:qe,ITEM:cp,CONTAINER:Ge,FIRST_MATCHUP:On,WINNER:fo,LOSER:ro,AD_HOC:$r,FEED_IN:da,FLEX_ROUNDS:bF,COMPASS:zc,PLAY_OFF:de,OLYMPIC:Qc,KNOCKOUT:vF,SINGLE_ELIMINATION:go,DOUBLE_ELIMINATION:Xc,CURTIS:Tf,FICSF:yh,FICQF:Ah,FICR16:Eh,MFIC:uU,VOLUNTARY_CONSOLATION:$e,FIRST_MATCH_LOSER_CONSOLATION:Jc,FIRST_ROUND_LOSER_CONSOLATION:pp,MODIFIED_FEED_IN_CHAMPIONSHIP:Lm,FEED_IN_CHAMPIONSHIP_TO_R16:wm,FEED_IN_CHAMPIONSHIP_TO_QF:xm,FEED_IN_CHAMPIONSHIP_TO_SF:_m,FEED_IN_CHAMPIONSHIP:mp,LUCKY_DRAW:ki,ROUND_ROBIN_WITH_PLAYOFF:Io,ROUND_ROBIN:Nn,DECIDER:pU,BACKDRAW:mU,COMPASS_ATTRIBUTES:yf,OLYMPIC_ATTRIBUTES:Af,DRAW:dn,RANDOM:up,TOP_DOWN:En,BOTTOM_UP:li,WATERFALL:di,WIN_RATIO:fi,ROUND_OUTCOME:Gi,MULTI_STRUCTURE_DRAWS:dU,generatedDrawTypes:OF,stageOrder:ks,finishOrder:cU,AGGREGATE_EVENT_STRUCTURES:aU,FINISHING_POSITIONS:sU},ZC=lU;var Ce="tournamentRecords",Ef="policyDefinitions",ie="tournamentRecord",Uh="onlineResource",Ve="drawDefinition",Ph="tieFormatName",Fm="matchUpFormat",no="participantId",Dh="scheduleDates",tb="tournamentId",eb="scheduleDate",rb="roundNumber",Zc="structureId",Uf="participant",ec="matchUpIds",Nh="entryStage",nb="policyType",fU="structures",Pf="eventType",ln="matchUpId",km="tieFormat",tu="inContext",dp="structure",lp="courtIds",ob="personId",fp="venueIds",Df="matchUps",Mh="courtId",Rh="eventId",_n="matchUp",Ch="drawId",fn="error",Do="event",is="param",Nf="uuids",ib="averageMatchUpMinutes",sb="recoveryMinutes",ab="periodLength",cb="number";var Kr="object",Be="array";var tr="_validate",bh="_message",Fr="_invalid",He="_ofType",Gm="_anyOf",Gs="_oneOf";var ub={[Uh]:t=>Yt(Object.keys(t),[Ja,Za,tc]).length===3,[Ph]:t=>t&&to({namedFormat:t}),[Nf]:t=>!t||Array.isArray(t)&&t.every(Vt),[km]:t=>!ar({tieFormat:t}).error,[Pf]:t=>[Yn,qr,_e].includes(t),[Nh]:t=>$c.includes(t)},_F={[Ce]:xt,[ie]:Y,[Ef]:Ku,[Ve]:Z,[no]:oe,[Fm]:Wl,[tb]:ca,[Zc]:Ur,[ec]:rs,[Uf]:wi,[Uh]:lo,[Pf]:Hn,[fU]:Gl,[ln]:sr,[km]:Lo,[dp]:mi,[Mh]:_i,[Df]:Jn,[Rh]:jr,[_n]:hr,[lp]:st,[fp]:st,[Ch]:an,[Do]:vt},xF={[Ce]:Kr,[Ef]:Kr,[ie]:Kr,[Ve]:Kr,[Uh]:Kr,[Dh]:Be,[Uf]:Kr,[ec]:Be,[fU]:Be,[km]:Kr,[dp]:Kr,[lp]:Be,[fp]:Be,[Df]:Be,[_n]:Kr,[Do]:Kr,[Nf]:Be};function rt(t,e,r){if(!t&&!ht(t))return{error:G};if(!e?.length||t?._bypassParamCheck)return{valid:!0};if(!Array.isArray(e))return{error:G};let{paramError:n,errorParam:o}=FF(t,e);if(!n)return{valid:!0};let i=n[tr]&&(n[fn]||n[Fr])||t?.[o]===void 0&&(n[fn]||n[Fr]||_F[o]||G)||G,s=o??(n[Gs]&&Object.keys(n[Gs]).join(", "));return _({info:{param:s,message:n[bh]},result:{error:i},stack:r})}function pb(t,e){let r=Object.keys(t),n=Object.keys(e);return Yt(r,n)}function wF(t,e){if(!e)return;let r=pb(t,e);return r.length!==1?{error:G}:r.reduce((n,o)=>({...n,[o]:!0}),{})}function LF(t,e){if(!e)return;let r=pb(t,e).filter(n=>t[n]);return r.length<1?{error:G}:r.reduce((n,o)=>({...n,[o]:!0}),{})}function FF(t,e){let r,n;return{paramError:e.find(({_ofType:i,_oneOf:s,_anyOf:a,_validate:c,_info:u,...p})=>{let m=s&&wF(t,s);if(m?.error)return m.error;m&&Object.assign(p,m);let d=a&&LF(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&&!Wr(c),h=t[g]!==void 0&&!c&&kF(t,g,i),S=p[g]&&[void 0,null].includes(t[g]),y=I||h||S||c&&t[g]!==void 0&&!GF(t[g],c)||ub[g]&&!ub[g](t[g]);return y&&(r=g,n=u),y});return!l.length||f}),errorParam:r,paramInfo:n}}function kF(t,e,r){return r=r||xF[e]||"string",r==="array"?!Array.isArray(t[e]):typeof t[e]!==r}function GF(t,e){return Wr(e)?e(t):!0}var Vm="DYNAMIC",gi="RANKING",Ii="RATING",hi="SCALE",ho="SEEDING",mb={RANKING:gi,RATING:Ii,SCALE:hi,SEEDING:ho};function la(t){let e=rt(t,[{[Uf]:!0}]);if(e.error)return e;let r=t.participant.timeItems?.filter(({itemType:o})=>o?.startsWith(hi)&&[gi,Ii,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=ut(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===gi&&"rankings"||"ratings";n[l][u]||(n[l][u]=[]),n[l][u].push({scaleValue:a.itemValue,scaleDate:a.itemDate,scaleName:d})}}}return{...C,...n}}function Vi(t){if(t===null)return{};let{source:e,template:r}=t||{};if(!r)return e;let n={};return o(e,r,n),n;function o(i,s,a){if(!i||!s)return;let c=Object.keys(i),u=Object.keys(s),p=Object.assign({},...u.filter(l=>l.indexOf("||")).map(l=>l.split("||").map(f=>({[f]:l}))).flat()),m=u.concat(...Object.keys(p)),d=m.includes("*");for(let l of c)if(m.indexOf(l)>=0||d){let f=p[l]||l,g=s[f]||d,I=i[l];if(typeof g=="object"&&typeof I!="function"&&!Array.isArray(g))if(Array.isArray(I)){let h=I.map(S=>{let T={};return o(S,g,T)!==!1?T:void 0}).filter(Boolean);a[l]=h}else I&&(a[l]={},o(I,g,a[l]));else{let h=i[l];if(Array.isArray(g)&&!g.includes(h))return!1;(s[l]||d&&s[l]!==!1)&&(a[l]=h)}}}}var vh="voluntaryConsolation",Si="competitiveBands",Mf="roundRobinTally",So="positionActions",er="matchUpActions",Rf="rankingPoints",fa="roundNaming",Vs="participant",eu="progression",No="scheduling",ru="avoidance",VF="participant",BF="display",en="scoring",xn="seeding",rc="feedIn",HF="audit",Bm="draws",db={POLICY_TYPE_VOLUNTARY_CONSOLATION:vh,POLICY_TYPE_COMPETITIVE_BANDS:Si,POLICY_TYPE_ROUND_ROBIN_TALLY:Mf,POLICY_TYPE_POSITION_ACTIONS:So,POLICY_TYPE_MATCHUP_ACTIONS:er,POLICY_TYPE_RANKING_POINTS:Rf,POLICY_TYPE_ROUND_NAMING:fa,POLICY_TYPE_PARTICIPANT:Vs,POLICY_TYPE_PROGRESSION:eu,POLICY_TYPE_SCHEDULING:No,POLICY_TYPE_AVOIDANCE:ru,POLICY_TYPE_DISPLAY:BF,POLICY_TYPE_PRIVACY:VF,POLICY_TYPE_FEED_IN:rc,POLICY_TYPE_SCORING:en,POLICY_TYPE_SEEDING:xn,POLICY_TYPE_AUDIT:HF,POLICY_TYPE_DRAWS:Bm};function Go({tournamentParticipants:t=[],policyDefinitions:e={},contextProfile:r,participantId:n,internalUse:o,personId:i}){let s=t.find(c=>n&&c.participantId===n||i&&c.person&&c.person.personId===i),a=J(s,!1,o);if(a){let c=e?.[Vs];if(r?.withScaleValues){let{ratings:u,rankings:p}=la({participant:a});a.rankings=p,a.ratings=u}if(c?.participant)return Vi({template:c.participant,source:a})}return a}var lb="element required",fb="missing name";function gr(t){if(!t||typeof t!="object")return{error:st};if(t.element&&typeof t?.element!="object")return{error:G};if(!t?.name)return{error:st,info:fb};if(!t?.element){if(t.discover&&t.tournamentRecords){for(let e of Object.keys(t.tournamentRecords)){let r=t.tournamentRecords[e],n=gr({element:r,name:t.name});if(n.error)return _({result:n,stack:"removeExtension"})}return{...C}}return{error:st,info:lb}}return t?.element.extensions?(t.element.extensions=t.element.extensions.filter(e=>e?.name!==t.name),{...C}):{...C,info:ve}}function wn({requiredAttributes:t=["name","value"],extension:e}){if(!e||typeof e!="object"||typeof e.name!="string")return!1;let r=Object.keys(e);return t.filter(n=>r.includes(n)).length===t.length}function At(t){if(typeof t!="object")return{error:st};let e="addExtension";if(t?.element&&typeof t.element!="object")return _({result:{error:G},stack:e});if(!wn({extension:t.extension}))return _({result:{error:G,info:"invalid extension"},stack:e});if(!t.element)if(t.discover&&!t.tournamentId&&t.tournamentRecords){for(let o of Object.values(t.tournamentRecords)){let i=At({extension:t.extension,element:o});if(i.error)return _({result:i,stack:e})}return{...C}}else return _({result:{error:st},stack:e});if(t.element.extensions||(t.element.extensions=[]),t?.creationTime??!0){let o=new Date().toISOString();Object.assign(t.extension,{createdAt:o})}let n=t.element.extensions.find(({name:o})=>o===t.extension.name);return n?n.value=t.extension.value:t.extension.value&&t.element.extensions.push(t.extension),{...C}}function Cf(t){return!t||typeof t!="object"?{error:st}:t.tournamentRecord?At({creationTime:t.creationTime,element:t.tournamentRecord,extension:t.extension}):{error:Y}}function gp(t){return!t||typeof t!="object"?{error:st}:t.drawDefinition?At({creationTime:t.creationTime,element:t.drawDefinition,extension:t.extension}):{error:Rr}}function Mo(t){return!t||typeof t!="object"?{error:st}:t.event?At({creationTime:t.creationTime,extension:t.extension,element:t.event}):{error:jr}}function gU(t){if(!t||typeof t!="object")return{error:st};if(!t.participantId)return{error:oe};let e=t.tournamentRecord?.participants||[],r=Go({participantId:t.participantId,tournamentParticipants:e});return r?At({creationTime:t.creationTime,extension:t.extension,element:r}):{error:te}}function bf(t){return!t||typeof t!="object"?{error:st}:t.tournamentRecord?gr({element:t.tournamentRecord,name:t.name}):{error:Y}}function IU(t){return!t||typeof t!="object"?{error:st}:t.drawDefinition?gr({element:t.drawDefinition,name:t.name}):{error:Rr}}function Ip(t){return!t||typeof t!="object"?{error:st}:t?.event?gr({element:t.event,name:t.name}):{error:jr}}function hU(t){if(!t||typeof t!="object")return{error:st};if(!t.participantId)return{error:oe};let e=t.tournamentRecord?.participants||[],r=Go({participantId:t.participantId,tournamentParticipants:e});return r?gr({element:r,name:t.name}):{error:te}}function hp({tournamentRecords:t}){return{tournamentIds:ht(t)?Object.keys(t):[],...C}}var WF="extensionQueries";function dt({discover:t,element:e,name:r,...n}){if(!e||!r){if(t&&n){let s=Object.keys(n).filter(p=>typeof t=="boolean"||Array.isArray(t)&&t.includes(p)).find(p=>Array.isArray(n[p]?.extensions)?n[p].extensions.find(m=>m?.name===r):!1),a=s&&n[s];!a&&n.tournamentRecords&&(a=Object.values(n.tournamentRecords).find(p=>p.extensions?.length));let c=a?.extensions?.find(p=>p?.name===r);return{extension:c,info:c?void 0:ve}}return _({result:{error:st},stack:WF})}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:ve}}var jF="activeSuspension",nu="appliedPolicies",SU="context",Hm="delegatedOutcome",oo="disabled",ga="disableAutoCalc",Wm="disableLinks",jm="display",Ia="drawDeletions",YF="drawProfile",Ym="entryProfile",qF="eventProfile",$F="eventWithdrawalRequests",KF="factory",un="flightProfile",Oh="groupingAttribute",Ro="lineUps",Bs="linkedTournamentsIds",qm="matchUpHistory",_h="participantRepresentatives",ha="personRequests",nc="positionActions",zF="rankingPoints",QF="registration",Mn="roundTarget",ou="scheduleLimits",Vo="scheduleTiming",Sa="schedulingProfile",XF="statusDetail",oc="subOrder",Zo="tally",$m="tieFormatModification",xh={ACTIVE_SUSPENSION:jF,APPLIED_POLICIES:nu,CONTEXT:SU,DELEGATED_OUTCOME:Hm,DISABLED:oo,DISABLE_LINKS:Wm,DISABLE_AUTO_CALC:ga,DISPLAY:jm,DRAW_DELETIONS:Ia,DRAW_PROFILE:YF,ENTRY_PROFILE:Ym,EVENT_PROFILE:qF,EVENT_WITHDRAWAL_REQUESTS:$F,FLIGHT_PROFILE:un,GROUPING_ATTRIBUTE:Oh,LINEUPS:Ro,LINKED_TOURNAMENTS:Bs,MATCHUP_HISTORY:qm,PARTICIPANT_REPRESENTATIVES:_h,PERSON_REQUESTS:ha,POSITION_ACTIONS:nc,RANKING_POINTS:zF,REGISTRATION:QF,ROUND_TARGET:Mn,SCHEDULE_LIMITS:ou,SCHEDULE_TIMING:Vo,SCHEDULING_PROFILE:Sa,STATUS_DETAIL:XF,SUB_ORDER:oc,TALLY:Zo,TIE_FORMAT_MODIFICATIONS:$m,FACTORY:KF},TU=[Hm,oo,ga,Wm,un,Ro,Bs,qm,_h,ha,Mn,ou,Vo,Sa,oc,Zo,$m];function yU({tournamentRecords:t}){if(typeof t!="object"||!Object.keys(t).length)return{error:xt};let e=hp({tournamentRecords:t}),{tournamentIds:r}=e;return r?.length>1?At({tournamentRecords:t,discover:!0,extension:{name:Bs,value:{tournamentIds:r}}}):{...C}}function AU({tournamentRecords:t}){if(typeof t!="object"||!Object.keys(t).length)return{error:xt};let e=gr({name:Bs,tournamentRecords:t,discover:!0});return _({result:e,stack:"unlinkTournaments"})}function EU({tournamentRecords:t,tournamentId:e}){if(typeof t!="object")return{error:G};if(!e)return{error:ca};let r=hp({tournamentRecords:t}),{tournamentIds:n}=r;if(!n.includes(e))return{error:ca};let o;return n.every(i=>{let s=t[i],{extension:a}=dt({element:s,name:Bs});if(!a)return!0;let c=a?.value?.tournamentIds||[];if(!c?.length||c.length===1&&c.includes(e)||i===e){let m=bf({name:Bs,tournamentRecord:s});return m.error&&(o=m.error),m.success}let u=c.filter(m=>m!==e);a.value={tournamentIds:u};let p=Cf({tournamentRecord:s,extension:a});return p.error&&(o=p.error),p.success}),o?{error:o}:{...C}}var PU={};Xt(PU,{getLinkedTournamentIds:()=>iu,getTournamentIds:()=>hp});function iu({tournamentRecords:t}){return typeof t!="object"||!Object.keys(t).length?{error:xt}:{linkedTournamentIds:Object.assign({},...Object.keys(t).map(r=>{let n=t[r],o=n?.tournamentId,{extension:i}=dt({element:n,name:Bs}),s=(i?.value?.tournamentIds||[]).filter(a=>a!==o);return{[r]:s}}))}}var MN={};Xt(MN,{adHocPositionSwap:()=>wP,addAdHocMatchUps:()=>bd,addDrawDefinitionTimeItem:()=>Tg,addFinishingRounds:()=>Ea,addGoesTo:()=>qi,addPlayoffStructures:()=>Gp,addQualifyingStructure:()=>xP,addVoluntaryConsolationStage:()=>CP,addVoluntaryConsolationStructure:()=>pg,allPlayoffPositionsFilled:()=>OS,alternateDrawPositionAssignment:()=>SP,assignDrawPosition:()=>zP,assignDrawPositionBye:()=>Hr,attachConsolationStructures:()=>YP,attachPlayoffStructures:()=>Cg,attachQualifyingStructure:()=>Sg,attachStructures:()=>bg,autoSeeding:()=>X_,automatedPlayoffPositioning:()=>Ks,automatedPositioning:()=>Sc,checkValidEntries:()=>_d,deleteAdHocMatchUps:()=>QP,drawMatic:()=>qd,findDrawDefinition:()=>oT,generateAdHocMatchUps:()=>_u,generateAdHocRounds:()=>Yd,generateAndPopulatePlayoffStructures:()=>Cd,generateDrawDefinition:()=>xa,generateDrawMaticRound:()=>Fd,generateDrawStructuresAndLinks:()=>xd,generateDrawTypeAndModifyDrawDefinition:()=>wd,generateQualifyingStructure:()=>Pd,generateVoluntaryConsolation:()=>PT,getAssignedParticipantIds:()=>Ri,getAvailableMatchUpsCount:()=>vd,getAvailablePlayoffProfiles:()=>Du,getDrawDefinitionTimeItem:()=>zh,getDrawParticipantRepresentativeIds:()=>rT,getDrawStructures:()=>gn,getDrawTypeCoercion:()=>vu,getEligibleVoluntaryConsolationParticipants:()=>eT,getMatchUpsMap:()=>Me,getParticipantIdFinishingPositions:()=>nT,getPositionAssignments:()=>Vp,getPositionsPlayedOff:()=>yc,getSeedingThresholds:()=>ES,getSeedsCount:()=>Ou,getStructureSeedAssignments:()=>on,getTeamLineUp:()=>ms,getValidGroupSizes:()=>bp,isAdHoc:()=>cr,isCompletedStructure:()=>ai,isValidForQualifying:()=>hT,luckyLoserDrawPositionAssignment:()=>lP,modifyDrawDefinition:()=>qP,modifyDrawName:()=>vg,modifySeedAssignment:()=>TP,mutate:()=>ZP,positionActions:()=>IT,pruneDrawDefinition:()=>KP,qualifierDrawPositionAssignment:()=>hP,query:()=>pD,removeDrawPositionAssignment:()=>Eu,removeRoundMatchUps:()=>XP,removeSeededParticipant:()=>_P,removeStructure:()=>RP,renameStructures:()=>MP,resetDrawDefinition:()=>$P,resetVoluntaryConsolationStructure:()=>wU,setDrawParticipantRepresentativeIds:()=>MU,setPositionAssignments:()=>gP,setStructureOrder:()=>NP,setSubOrder:()=>JP,shiftAdHocRounds:()=>fP,swapAdHocRounds:()=>IP,swapDrawPositionAssignments:()=>OP,updateTeamLineUp:()=>Ki,withdrawParticipantAtDrawPosition:()=>mP});var ZP={};Xt(ZP,{adHocPositionSwap:()=>wP,addAdHocMatchUps:()=>bd,addDrawDefinitionTimeItem:()=>Tg,addPlayoffStructures:()=>Gp,addQualifyingStructure:()=>xP,addVoluntaryConsolationStage:()=>CP,addVoluntaryConsolationStructure:()=>pg,alternateDrawPositionAssignment:()=>SP,assignDrawPosition:()=>zP,assignDrawPositionBye:()=>Hr,attachConsolationStructures:()=>YP,attachPlayoffStructures:()=>Cg,attachQualifyingStructure:()=>Sg,attachStructures:()=>bg,automatedPlayoffPositioning:()=>Ks,automatedPositioning:()=>Sc,deleteAdHocMatchUps:()=>QP,luckyLoserDrawPositionAssignment:()=>lP,modifyDrawDefinition:()=>qP,modifyDrawName:()=>vg,modifySeedAssignment:()=>TP,pruneDrawDefinition:()=>KP,qualifierDrawPositionAssignment:()=>hP,removeDrawPositionAssignment:()=>Eu,removeRoundMatchUps:()=>XP,removeSeededParticipant:()=>_P,removeStructure:()=>RP,renameStructures:()=>MP,resetDrawDefinition:()=>$P,resetVoluntaryConsolationStructure:()=>wU,setDrawParticipantRepresentativeIds:()=>MU,setPositionAssignments:()=>gP,setStructureOrder:()=>NP,setSubOrder:()=>JP,shiftAdHocRounds:()=>fP,swapAdHocRounds:()=>IP,swapDrawPositionAssignments:()=>OP,updateTeamLineUp:()=>Ki,withdrawParticipantAtDrawPosition:()=>mP});var NU=t=>e=>t[e],Km=(t=[])=>t.map(Ee).filter(Boolean),vf=(t=[])=>t.map(St).filter(Boolean),St=(t={})=>NU(t)("participantId");var Ee=(t={})=>NU(t)("matchUpId"),su=(t={})=>NU(t)("drawId");function MU({representativeParticipantIds:t,drawDefinition:e}){if(!e)return{error:Rr};if(!Array.isArray(t))return{error:G};let r=vf(e?.entries||[]);return t.length&&Yt(t,r).length<t.length?{error:G}:gp({drawDefinition:e,extension:{name:_h,value:t}})}var vr="ABANDONED",ic="AWAITING_RESULT",Nt="BYE",io="CANCELLED",le="COMPLETED",au="DEAD_RUBBER",Mt="DEFAULTED",be="DOUBLE_DEFAULT",he="DOUBLE_WALKOVER",Ln="IN_PROGRESS",pn="INCOMPLETE",RU="NOT_PLAYED",rr="RETIRED",ss="SUSPENDED",Qt="TO_BE_PLAYED",Ct="WALKOVER",gb=[ic,le,Mt,Ln,pn,rr,ss],wh=[ic,le,Mt,he,be,Ln,pn,rr,ss,Ct],Lh=[vr,ic,Nt,io,le,au,Mt,he,be,Ln,pn,RU,rr,ss,Qt,Ct],Fh=[Nt,he,be,le,Mt,rr,Ct],kh=[vr,ic,io,au,Ln,pn,RU,ss,Qt,void 0],ce=[io,vr,le,au,Mt,he,be,rr,Ct],zm=[vr,le,Mt,he,be,Ln,rr,Ct],Gh=[Ln,pn,ss,Qt],Vh={ABANDONED:vr,AWAITING_RESULT:ic,BYE:Nt,CANCELLED:io,COMPLETED:le,DEAD_RUBBER:au,DEFAULTED:Mt,DOUBLE_WALKOVER:he,DOUBLE_DEFAULT:be,IN_PROGRESS:Ln,INCOMPLETE:pn,NOT_PLAYED:RU,RETIRED:rr,SUSPENDED:ss,TO_BE_PLAYED:Qt,WALKOVER:Ct};function Ti(t,e,r){let n=m=>dt({element:m,name:Mn})?.extension?.value,o=r?.deprioritizeCompleted,i=r?.mode===aU&&zC,s=r?.mode===sU&&cU,a=s||i||ks,c=m=>m?.stage===nt&&m?.stageSequence===1,u=m=>c(m)?-1:a[m?.stage],p=m=>m?.matchUps.every(({matchUpStatus:d})=>ce.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)||(Of(t)||0)-(Of(e)||0)}function Of(t){return(t?.matchUps||[]).reduce((e,r)=>{let n=(r.finishingPositionRange?.winner||[]).reduce((o,i)=>o+i,0);return!e||n<e?n:e},void 0)}function at(t){let e=rt(t,[{[Ve]:!0,[Zc]:!0}]);if(e.error)return e;let{drawDefinition:r,structureId:n}=t,{structures:o}=gn({drawDefinition:r}),i=o?.map(c=>c.structures?[...c.structures].concat(c):c).flat(),s=i?.find(c=>c.structureId===n);if(!s)return{error:kt};let a=s.structureType===cp?i?.find(c=>c.structures?.some(u=>u.structureId===n)):void 0;return{structure:s,containingStructure:a}}function gn({withStageGrouping:t,drawDefinition:e,stageSequences:r,stageSequence:n,roundTarget:o,sortConfig:i,stages:s,stage:a}){let c=!e&&Z||!e?.structures&&Gl||void 0;if(c)return{error:c,structures:[],stageStructures:{}};let u=f=>{let g=dt({element:f,name:Mn})?.extension?.value;return!o||o===g},p=e?.structures?.filter(d).filter(l).filter(u).sort((f,g)=>Ti(f,g,i))??[],m=t?Object.assign({},...$c.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 Bh({drawDefinition:t}){if(!t)return{error:Z};let e={};return{allPositionedParticipantIds:(t.structures||[]).map(n=>{let o=n.stage;e[o]||(e[o]=[]);let{positionAssignments:i}=bt({structure:n}),s=i?.map(St).filter(Boolean)??[];return e[o].push(...s),s}).flat(),stagePositionedParticipantIds:e}}function bt({drawDefinition:t,structureId:e,structure:r}){let n,o=[];if(!r){if(!t)return{positionAssignments:o,error:Z};if({structure:r,error:n}=at({drawDefinition:t,structureId:e}),n)return{positionAssignments:o,error:n}}return r.structures?o=[].concat(...r.structures.map(i=>bt({structure:i}).positionAssignments)):r.positionAssignments?o=r.positionAssignments:n=$A,{positionAssignments:o,error:n}}function Se({drawDefinition:t,structureId:e,structure:r}){let n=bt({drawDefinition:t,structureId:e,structure:r})?.positionAssignments||[],o=n?.filter(u=>u.participantId??u.bye??u.qualifier),i=n&&n?.length===o?.length,s=n?.filter(u=>!u.participantId&&!u.bye&&!u.qualifier),a=n?.filter(u=>!u.participantId&&u.bye),c=n?.filter(u=>!u.participantId&&u.qualifier);return{allPositionsAssigned:i,positionAssignments:n,unassignedPositions:s,assignedPositions:o,qualifierPositions:c,byePositions:a}}var _f="addDrawDefinition",Sp="addMatchUps",ti="addParticipants",xf="addScaleItems",CU="addEvent",Hh="addVenue",yi="audit",Wh="dataIssue",wf="deleteParticipants",Lf="deleteVenue",Ff="deletedDrawIds",kf="deletedMatchUpIds",Gf="modifyDrawDefinition",bU="modifyDrawEntries",vU="modifyEventEntries",Vf="modifyMatchUp",nr="modifyParticipants",Bf="modifyPositionAssignments",Hf="modifySeedAssignments",Bi="modifyTournamentDetail",Ai="modifyVenue",Qm="mutations",jh="publishEvent",OU="publishEventSeeding",_U="publishOrderOfPlay",xU="publishParticipants",Wf="unPublishEvent",jf="unPublishEventSeeding",Yf="unPublishOrderOfPlay",Ib="unPublishParticipants",Tp="updateInContextMatchUp",hb={ADD_DRAW_DEFINITION:_f,ADD_MATCHUPS:Sp,ADD_PARTICIPANTS:ti,ADD_SCALE_ITEMS:xf,ADD_EVENT:CU,ADD_VENUE:Hh,AUDIT:yi,DATA_ISSUE:Wh,DELETE_PARTICIPANTS:wf,DELETE_VENUE:Lf,DELETED_DRAW_IDS:Ff,DELETED_MATCHUP_IDS:kf,MODIFY_DRAW_DEFINITION:Gf,MODIFY_DRAW_ENTRIES:bU,MODIFY_EVENT_ENTRIES:vU,MODIFY_MATCHUP:Vf,MODIFY_PARTICIPANTS:nr,MODIFY_POSITION_ASSIGNMENTS:Bf,MODIFY_SEED_ASSIGNMENTS:Hf,MODIFY_TOURNAMENT_DETAIL:Bi,MODIFY_VENUE:Ai,MUTATIONS:Qm,PUBLISH_EVENT_SEEDING:OU,PUBLISH_EVENT:jh,PUBLISH_ORDER_OF_PLAY:_U,PUBLISH_PARTICIPANTS:xU,UNPUBLISH_EVENT_SEEDING:jf,UNPUBLISH_EVENT:Wf,UNPUBLISH_ORDER_OF_PLAY:Yf,UPDATE_INCONTEXT_MATCHUP:Tp};function Yh(t,e){if(!t)return{error:Z};let r=Date.now();t.updatedAt&&r===new Date(t.updatedAt).getTime()&&(r+=1);let n=new Date(r).toISOString(),o=e?.filter(Boolean);return t.updatedAt=n,t.structures?.filter(Boolean).forEach(i=>{(!o?.length||o?.includes(i.structureId))&&(i.updatedAt=n)}),{...C}}function Co({drawDefinition:t,tournamentId:e,matchUps:r,eventId:n}){return t&&Yh(t),mt({payload:{matchUps:r,tournamentId:e,eventId:n},topic:Sp}),{...C}}function qn({drawDefinition:t,tournamentId:e,matchUpIds:r,eventId:n,action:o}){t&&Yh(t),mt({topic:kf,payload:{tournamentId:e,matchUpIds:r,eventId:n,action:o}});for(let i of r)YI({key:i});return{...C}}function gt({drawDefinition:t,tournamentId:e,structureId:r,context:n,eventId:o,matchUp:i}){return i?(t&&Ot({drawDefinition:t,structureIds:r?[r]:void 0,tournamentId:e,eventId:o}),mt({topic:Vf,payload:{matchUp:i,tournamentId:e,context:n},key:i.matchUpId}),{...C}):(console.log(hr),{error:hr})}function Sb({tournamentId:t,inContextMatchUp:e}){return e?(mt({payload:{inContextMatchUp:e,tournamentId:t},topic:Tp,key:e.matchUpId}),{...C}):{error:hr}}function Ta({tournamentId:t,eventId:e,drawDefinition:r}){return r?(Yh(r),mt({payload:{drawDefinition:r,tournamentId:t,eventId:e},topic:_f,key:r.drawId}),{...C}):(console.log(Z),{error:Z})}function Tb({tournamentId:t,eventId:e,drawId:r}){return mt({payload:{drawId:r,tournamentId:t,eventId:e},topic:Ff,key:r}),YI({key:r}),{...C}}function Ot({drawDefinition:t,tournamentId:e,structureIds:r,eventId:n}){return t?(Yh(t,r),mt({payload:{tournamentId:e,eventId:n,drawDefinition:t},topic:Gf,key:t.drawId}),{...C}):{error:Z}}function qh({drawDefinition:t,tournamentId:e,structure:r,eventId:n}){if(!t)return{error:Z};if(!r)return{error:mi};let o=r.seedAssignments,i=r.structureId,s=t.drawId;return mt({payload:{tournamentId:e,eventId:n,drawId:s,structureId:i,seedAssignments:o},topic:Hf,key:t.drawId}),Ot({structureIds:[i],drawDefinition:t,tournamentId:e,eventId:n}),{...C}}function bo({drawDefinition:t,tournamentId:e,structure:r,event:n}){if(!t)return{error:Z};if(!r)return{error:mi};let o=bt({structure:r}),i=r.structureId,s=t.drawId,a=n?.eventId;return mt({topic:Bf,payload:{positionAssignments:o,tournamentId:e,structureId:i,eventId:a,drawId:s},key:i}),Ot({structureIds:[i],drawDefinition:t,tournamentId:e,eventId:a}),{...C}}function wU({tournamentRecord:t,drawDefinition:e,resetEntries:r,event:n}){if(!e)return{error:Z};let o=e.structures?.find(s=>s.stage===$e);if(!o)return{error:kt};let i=o.matchUps?.map(({matchUpId:s})=>s)||[];return o.positionAssignments=[],o.seedAssignments=[],o.matchUps=[],qn({tournamentId:t?.tournamentId,action:"resetVoluntaryConsolationStructure",matchUpIds:i,drawDefinition:e}),r&&(e.entries=e.entries.filter(s=>s.entryStage!==$e)),Ot({tournamentId:t?.tournamentId,eventId:n?.eventId,drawDefinition:e,structureIds:[o.structureId]}),{...C}}function Xm({drawPositions:t,structure:e}){if([ct,nt].includes(e.stage)&&e.stageSequence===1)return;let{positionAssignments:r}=bt({structure:e});r?.filter(({drawPosition:o})=>t?.includes(o))?.forEach(o=>{At({element:o,extension:{name:Wm,value:!0}})})}function cu(t){let{appliedPolicies:e,positionAction:r,drawDefinition:n}=t;if(e?.audit?.[nc]===!1)return;let{extension:o}=dt({name:nc,element:n}),i=Array.isArray(o?.value)?o?.value??[]:[];if(!i?.length){let a=n.structures.find(c=>c.stage===nt);if(a){let c=bt({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:nc};At({element:n,extension:s})}function as({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 uu(t){let{sides:e,matchUpType:r}=t||{},n=t.potentialParticipants?.length?t.potentialParticipants.flat().map(s=>r===_t?s?.individualParticipantIds||[]:s.participantId).flat():[],o=(e||[]).map(s=>r===_t&&(s?.participant?.individualParticipantIds||[])||s?.participantId&&[s.participantId]||[]).flat();return{individualParticipantIds:o.concat(n).flat(),enteredIndividualParticipantIds:o,potentialIndividualParticipantIds:n}}function Nr(t){return t?.tournamentRecords??(t?.tournamentRecord&&{[t.tournamentRecord.tournamentId]:t.tournamentRecord})??{}}var sc="SIGN_IN_STATUS",LU="SIGNED_OUT",pu="SIGNED_IN",yr="TEAM",Tt="INDIVIDUAL",zr="GROUP",ft="PAIR",wt="TEAM",mu={TEAM_PARTICIPANT:yr,INDIVIDUAL:Tt,GROUP:zr,TEAM:wt,PAIR:ft},yb={INDIVIDUAL:Tt,GROUP:zr,PAIR:ft,TEAM:wt,SIGN_IN_STATUS:sc,SIGNED_OUT:LU,SIGNED_IN:pu};function du({participantsProfile:t,participants:e=[],deepCopy:r}){let n=new Map,o=r!==!1?J(e,t?.convertExtensions,!0):e,i=o.filter(c=>c.participantType===wt),s=o.filter(c=>c.participantType===zr),a=o.filter(c=>c.participantType===ft);return o.forEach(c=>{if(c.participantType===Tt){let{participantId:u}=c;c.groupParticipantIds=[],c.teamParticipantIds=[],c.pairParticipantIds=[],c.groups=[],c.teams=[],i.forEach(p=>{(p?.individualParticipantIds||[]).forEach(m=>{m===u&&!c.teamParticipantIds?.includes(p.participantId)&&(c.teamParticipantIds.push(p.participantId),n.get(p.participantId)||n.set(p.participantId,{participantName:p.participantName,participantId:p.participantId}),c.teams.push({participantRoleResponsibilities:p.participantRoleResponsibilities,participantOtherName:p.participantOtherName,participantName:p.participantName,participantId:p.participantId,teamId:p.teamId}))})}),a.forEach(p=>{(p?.individualParticipantIds||[]).forEach(m=>{m===u&&!c.pairParticipantIds.includes(p.participantId)&&c.pairParticipantIds.push(p.participantId)})}),s.forEach(p=>{(p?.individualParticipantIds||[]).forEach(m=>{m===u&&!c.groupParticipantIds.includes(p.participantId)&&(c.groupParticipantIds.push(p.participantId),c.groups.push({participantRoleResponsibilities:p.participantRoleResponsibilities,participantOtherName:p.participantOtherName,participantName:p.participantName,participantId:p.participantId}))})})}}),{participantsWithGroupings:o,groupInfo:Object.fromEntries(n)}}function FU(t){return t&&typeof String.fromCodePoint<"u"?t.toUpperCase().replace(/./g,e=>String.fromCodePoint(e.charCodeAt(0)+127397)):t}function Ab(t){let e=Object.assign({},...ei.filter(r=>r.ioc).map(r=>({[r.ioc]:r.iso})));return FU(e[t])}var ei=[{ioc:"",iso2:"",iso:"",label:"NONE",phone:""},{ioc:"AND",iso2:"AD",iso:"AND",label:"Andorra",phone:"376"},{ioc:"UAE",iso2:"AE",iso:"ARE",label:"United Arab Emirates",phone:"971"},{ioc:"AFG",iso2:"AF",iso:"AFG",label:"Afghanistan",phone:"93"},{ioc:"ANT",iso2:"AG",iso:"ATG",label:"Antigua and Barbuda",phone:"1-268"},{ioc:"AIA",iso2:"AI",iso:"AIA",label:"Anguilla",phone:"1-264"},{ioc:"ALB",iso2:"AL",iso:"ALB",label:"Albania",phone:"355"},{ioc:"ARM",iso2:"AM",iso:"ARM",label:"Armenia",phone:"374"},{ioc:"ANG",iso2:"AO",iso:"AGO",label:"Angola",phone:"244"},{ioc:"",iso2:"AQ",iso:"ATA",label:"Antarctica",phone:"672"},{ioc:"ARG",iso2:"AR",iso:"ARG",label:"Argentina",phone:"54"},{ioc:"ASA",iso2:"AS",iso:"ASM",label:"American Samoa",phone:"1-684"},{ioc:"AUT",iso2:"AT",iso:"AUT",label:"Austria",phone:"43"},{ioc:"AUS",iso2:"AU",iso:"AUS",label:"Australia",phone:"61",suggested:!0},{ioc:"ARU",iso2:"AW",iso:"ABW",label:"Aruba",phone:"297"},{ioc:"AZE",iso2:"AZ",iso:"AZE",label:"Azerbaijan",phone:"994"},{ioc:"BIH",iso2:"BA",iso:"BIH",label:"Bosnia and Herzegovina",phone:"387"},{ioc:"BAR",iso2:"BB",iso:"BRB",label:"Barbados",phone:"1-246"},{ioc:"BAN",iso2:"BD",iso:"BGD",label:"Bangladesh",phone:"880"},{ioc:"BEL",iso2:"BE",iso:"BEL",label:"Belgium",phone:"32"},{ioc:"BUR",iso2:"BF",iso:"BFA",label:"Burkina Faso",phone:"226"},{ioc:"BUL",iso2:"BG",iso:"BGR",label:"Bulgaria",phone:"359"},{ioc:"BRN",iso2:"BH",iso:"BHR",label:"Bahrain",phone:"973"},{ioc:"BDI",iso2:"BI",iso:"BDI",label:"Burundi",phone:"257"},{ioc:"BEN",iso2:"BJ",iso:"BEN",label:"Benin",phone:"229"},{ioc:"",iso2:"BL",iso:"BLM",label:"Saint Barthelemy",phone:"590"},{ioc:"BER",iso2:"BM",iso:"BMU",label:"Bermuda",phone:"1-441"},{ioc:"BRU",iso2:"BN",iso:"BRN",label:"Brunei Darussalam",phone:"673"},{ioc:"BOL",iso2:"BO",iso:"BOL",label:"Bolivia",phone:"591"},{ioc:"BRA",iso2:"BR",iso:"BRA",label:"Brazil",phone:"55"},{ioc:"BAH",iso2:"BS",iso:"BHS",label:"Bahamas",phone:"1-242"},{ioc:"BHU",iso2:"BT",iso:"BTN",label:"Bhutan",phone:"975"},{ioc:"",iso2:"BV",iso:"BVT",label:"Bouvet Island",phone:"47"},{ioc:"BOT",iso2:"BW",iso:"BWA",label:"Botswana",phone:"267"},{ioc:"BLR",iso2:"BY",iso:"BLR",label:"Belarus",phone:"375"},{ioc:"BIZ",iso2:"BZ",iso:"BLZ",label:"Belize",phone:"501"},{ioc:"CAN",iso2:"CA",iso:"CAN",label:"Canada",phone:"1",suggested:!0},{ioc:"",iso2:"CC",iso:"CCK",label:"Cocos (Keeling) Islands",phone:"61"},{ioc:"CGO",iso2:"CD",iso:"COG",label:"Congo, Republic of the",phone:"242"},{ioc:"CAF",iso2:"CF",iso:"CAF",label:"Central African Republic",phone:"236"},{ioc:"COD",iso2:"CG",iso:"CGD",label:"Congo, Democratic Republic of the",phone:"243"},{ioc:"SUI",iso2:"CH",iso:"CHE",label:"Switzerland",phone:"41"},{ioc:"CIV",iso2:"CI",iso:"CIV",label:"Cote d'Ivoire",phone:"225"},{ioc:"COK",iso2:"CK",iso:"COK",label:"Cook Islands",phone:"682"},{ioc:"CHI",iso2:"CL",iso:"CHL",label:"Chile",phone:"56"},{ioc:"CMR",iso2:"CM",iso:"CMR",label:"Cameroon",phone:"237"},{ioc:"CHN",iso2:"CN",iso:"CHN",label:"China",phone:"86"},{ioc:"COL",iso2:"CO",iso:"COL",label:"Colombia",phone:"57"},{ioc:"CRC",iso2:"CR",iso:"CRI",label:"Costa Rica",phone:"506"},{ioc:"CUB",iso2:"CU",iso:"CUB",label:"Cuba",phone:"53"},{ioc:"CPV",iso2:"CV",iso:"CPV",label:"Cape Verde",phone:"238"},{ioc:"CUW",iso2:"CW",iso:"CUW",label:"Curacao",phone:"599"},{ioc:"CXR",iso2:"CX",iso:"CXR",label:"Christmas Island",phone:"61"},{ioc:"CYP",iso2:"CY",iso:"CYP",label:"Cyprus",phone:"357"},{ioc:"CZE",iso2:"CZ",iso:"CZE",label:"Czech Republic",phone:"420"},{ioc:"GER",iso2:"DE",iso:"DEU",label:"Germany",phone:"49",suggested:!0},{ioc:"DJI",iso2:"DJ",iso:"DJI",label:"Djibouti",phone:"253"},{ioc:"DEN",iso2:"DK",iso:"DNK",label:"Denmark",phone:"45"},{ioc:"DMA",iso2:"DM",iso:"DMA",label:"Dominica",phone:"1-767"},{ioc:"DOM",iso2:"DO",iso:"DOM",label:"Dominican Republic",phone:"1-809"},{ioc:"ALG",iso2:"DZ",iso:"DZA",label:"Algeria",phone:"213"},{ioc:"ECU",iso2:"EC",iso:"ECU",label:"Ecuador",phone:"593"},{ioc:"EST",iso2:"EE",iso:"ESE",label:"Estonia",phone:"372"},{ioc:"EGY",iso2:"EG",iso:"EGY",label:"Egypt",phone:"20"},{ioc:"",iso2:"EH",iso:"ESH",label:"Western Sahara",phone:"212"},{ioc:"ERI",iso2:"ER",iso:"ERI",label:"Eritrea",phone:"291"},{ioc:"ESP",iso2:"ES",iso:"ESP",label:"Spain",phone:"34"},{ioc:"ETH",iso2:"ET",iso:"ETH",label:"Ethiopia",phone:"251"},{ioc:"FIN",iso2:"FI",iso:"FIN",label:"Finland",phone:"358"},{ioc:"FIJ",iso2:"FJ",iso:"FJI",label:"Fiji",phone:"679"},{ioc:"FLK",iso2:"FK",iso:"FLK",label:"Falkland Islands (Malvinas)",phone:"500"},{ioc:"FSM",iso2:"FM",iso:"FSM",label:"Micronesia, Federated States of",phone:"691"},{ioc:"FAR",iso2:"FO",iso:"FRO",label:"Faroe Islands",phone:"298"},{ioc:"FRA",iso2:"FR",iso:"FRA",label:"France",phone:"33",suggested:!0},{ioc:"GAB",iso2:"GA",iso:"GAB",label:"Gabon",phone:"241"},{ioc:"GBR",iso2:"GB",iso:"GBR",label:"United Kingdom",phone:"44"},{ioc:"GRN",iso2:"GD",iso:"GRD",label:"Grenada",phone:"1-473"},{ioc:"GEO",iso2:"GE",iso:"GEO",label:"Georgia",phone:"995"},{ioc:"FGU",iso2:"GF",iso:"GUF",label:"French Guiana",phone:"594"},{ioc:"",iso2:"GG",iso:"GGY",label:"Guernsey",phone:"44"},{ioc:"",iso2:"GH",iso:"GHA",label:"Ghana",phone:"233"},{ioc:"GIB",iso2:"GI",iso:"GIB",label:"Gibraltar",phone:"350"},{ioc:"GRL",iso2:"GL",iso:"GRL",label:"Greenland",phone:"299"},{ioc:"GAM",iso2:"GM",iso:"GMB",label:"Gambia",phone:"220"},{ioc:"GUI",iso2:"GN",iso:"GIN",label:"Guinea",phone:"224"},{ioc:"GUD",iso2:"GP",iso:"GLP",label:"Guadeloupe",phone:"590"},{ioc:"GEQ",iso2:"GQ",iso:"GNQ",label:"Equatorial Guinea",phone:"240"},{ioc:"GRE",iso2:"GR",iso:"GRC",label:"Greece",phone:"30"},{ioc:"",iso2:"GS",iso:"SGS",label:"South Georgia and the South Sandwich Islands",phone:"500"},{ioc:"GUA",iso2:"GT",iso:"GTM",label:"Guatemala",phone:"502"},{ioc:"GUM",iso2:"GU",iso:"GUM",label:"Guam",phone:"1-671"},{ioc:"GBS",iso2:"GW",iso:"GNB",label:"Guinea-Bissau",phone:"245"},{ioc:"GUY",iso2:"GY",iso:"GUY",label:"Guyana",phone:"592"},{ioc:"HKG",iso2:"HK",iso:"HKG",label:"Hong Kong",phone:"852"},{ioc:"",iso2:"HM",iso:"HMD",label:"Heard Island and McDonald Islands",phone:"672"},{ioc:"HON",iso2:"HN",iso:"HND",label:"Honduras",phone:"504"},{ioc:"CRO",iso2:"HR",iso:"HRV",label:"Croatia",phone:"385"},{ioc:"HAI",iso2:"HT",iso:"HTI",label:"Haiti",phone:"509"},{ioc:"HUN",iso2:"HU",iso:"HUN",label:"Hungary",phone:"36"},{ioc:"INA",iso2:"ID",iso:"IDN",label:"Indonesia",phone:"62"},{ioc:"IRL",iso2:"IE",iso:"IRL",label:"Ireland",phone:"353"},{ioc:"ISR",iso2:"IL",iso:"ISR",label:"Israel",phone:"972"},{ioc:"",iso2:"IM",iso:"IMN",label:"Isle of Man",phone:"44"},{ioc:"IND",iso2:"IN",iso:"IND",label:"India",phone:"91"},{ioc:"",iso2:"IO",iso:"IOT",label:"British Indian Ocean Territory",phone:"246"},{ioc:"IRQ",iso2:"IQ",iso:"IRQ",label:"Iraq",phone:"964"},{ioc:"IRI",iso2:"IR",iso:"IRN",label:"Iran, Islamic Republic of",phone:"98"},{ioc:"ISL",iso2:"IS",iso:"ISL",label:"Iceland",phone:"354"},{ioc:"ITA",iso2:"IT",iso:"ITA",label:"Italy",phone:"39"},{ioc:"",iso2:"JE",iso:"JEY",label:"Jersey",phone:"44"},{ioc:"JAM",iso2:"JM",iso:"JAM",label:"Jamaica",phone:"1-876"},{ioc:"JOR",iso2:"JO",iso:"JOR",label:"Jordan",phone:"962"},{ioc:"JPN",iso2:"JP",iso:"JPN",label:"Japan",phone:"81",suggested:!0},{ioc:"KEN",iso2:"KE",iso:"KEN",label:"Kenya",phone:"254"},{ioc:"KGZ",iso2:"KG",iso:"KGZ",label:"Kyrgyzstan",phone:"996"},{ioc:"CAM",iso2:"KH",iso:"KHM",label:"Cambodia",phone:"855"},{ioc:"KIR",iso2:"KI",iso:"KIR",label:"Kiribati",phone:"686"},{ioc:"COM",iso2:"KM",iso:"COM",label:"Comoros",phone:"269"},{ioc:"SKN",iso2:"KN",iso:"KNA",label:"Saint Kitts and Nevis",phone:"1-869"},{ioc:"KOR",iso2:"KP",iso:"KOR",label:"Korea, Democratic People's Republic of",phone:"850"},{ioc:"PRK",iso2:"KR",iso:"PRK",label:"Korea, Republic of",phone:"82"},{ioc:"KUW",iso2:"KW",iso:"KWT",label:"Kuwait",phone:"965"},{ioc:"CAY",iso2:"KY",iso:"CYM",label:"Cayman Islands",phone:"1-345"},{ioc:"KAZ",iso2:"KZ",iso:"KAZ",label:"Kazakhstan",phone:"7"},{ioc:"LAO",iso2:"LA",iso:"LAO",label:"Lao People's Democratic Republic",phone:"856"},{ioc:"LIB",iso2:"LB",iso:"LBN",label:"Lebanon",phone:"961"},{ioc:"LCA",iso2:"LC",iso:"LCA",label:"Saint Lucia",phone:"1-758"},{ioc:"LIE",iso2:"LI",iso:"LIE",label:"Liechtenstein",phone:"423"},{ioc:"SRI",iso2:"LK",iso:"LKA",label:"Sri Lanka",phone:"94"},{ioc:"LBR",iso2:"LR",iso:"LBR",label:"Liberia",phone:"231"},{ioc:"LES",iso2:"LS",iso:"LSO",label:"Lesotho",phone:"266"},{ioc:"LTU",iso2:"LT",iso:"LTU",label:"Lithuania",phone:"370"},{ioc:"LUX",iso2:"LU",iso:"LUX",label:"Luxembourg",phone:"352"},{ioc:"LAT",iso2:"LV",iso:"LVA",label:"Latvia",phone:"371"},{ioc:"LBA",iso2:"LY",iso:"LBY",label:"Libya",phone:"218"},{ioc:"MAR",iso2:"MA",iso:"MAR",label:"Morocco",phone:"212"},{ioc:"MON",iso2:"MC",iso:"MCO",label:"Monaco",phone:"377"},{ioc:"MDA",iso2:"MD",iso:"MDA",label:"Moldova, Republic of",phone:"373"},{ioc:"MNE",iso2:"ME",iso:"MNE",label:"Montenegro",phone:"382"},{ioc:"",iso2:"MF",iso:"MAF",label:"Saint Martin (French part)",phone:"590"},{ioc:"MAD",iso2:"MG",iso:"MDG",label:"Madagascar",phone:"261"},{ioc:"MSH",iso2:"MH",iso:"MHL",label:"Marshall Islands",phone:"692"},{ioc:"MKD",iso2:"MK",iso:"MKD",label:"Macedonia, the Former Yugoslav Republic of",phone:"389"},{ioc:"MLI",iso2:"ML",iso:"MLI",label:"Mali",phone:"223"},{ioc:"MYA",iso2:"MM",iso:"MMR",label:"Myanmar",phone:"95"},{ioc:"MGL",iso2:"MN",iso:"MNG",label:"Mongolia",phone:"976"},{ioc:"MAC",iso2:"MO",iso:"MAC",label:"Macao",phone:"853"},{ioc:"NMA",iso2:"MP",iso:"NMP",label:"Northern Mariana Islands",phone:"1-670"},{ioc:"MRT",iso2:"MQ",iso:"MTQ",label:"Martinique",phone:"596"},{ioc:"MTN",iso2:"MR",iso:"MRT",label:"Mauritania",phone:"222"},{ioc:"MNT",iso2:"MS",iso:"MSR",label:"Montserrat",phone:"1-664"},{ioc:"MLT",iso2:"MT",iso:"MLT",label:"Malta",phone:"356"},{ioc:"MRI",iso2:"MU",iso:"MUS",label:"Mauritius",phone:"230"},{ioc:"MDV",iso2:"MV",iso:"MDV",label:"Maldives",phone:"960"},{ioc:"MAW",iso2:"MW",iso:"MWI",label:"Malawi",phone:"265"},{ioc:"MEX",iso2:"MX",iso:"MEX",label:"Mexico",phone:"52"},{ioc:"MAS",iso2:"MY",iso:"MYS",label:"Malaysia",phone:"60"},{ioc:"MOZ",iso2:"MZ",iso:"MOZ",label:"Mozambique",phone:"258"},{ioc:"NAM",iso2:"NA",iso:"NAM",label:"Namibia",phone:"264"},{ioc:"NCL",iso2:"NC",iso:"NCL",label:"New Caledonia",phone:"687"},{ioc:"NIG",iso2:"NE",iso:"NER",label:"Niger",phone:"227"},{ioc:"NFI",iso2:"NF",iso:"NFK",label:"Norfolk Island",phone:"672"},{ioc:"NGR",iso2:"NG",iso:"NGA",label:"Nigeria",phone:"234"},{ioc:"NCA",iso2:"NI",iso:"NIC",label:"Nicaragua",phone:"505"},{ioc:"NED",iso2:"NL",iso:"NLD",label:"Netherlands",phone:"31"},{ioc:"NOR",iso2:"NO",iso:"NOR",label:"Norway",phone:"47"},{ioc:"NEP",iso2:"NP",iso:"NPL",label:"Nepal",phone:"977"},{ioc:"NRU",iso2:"NR",iso:"NRU",label:"Nauru",phone:"674"},{ioc:"NIU",iso2:"NU",iso:"NIU",label:"Niue",phone:"683"},{ioc:"NZL",iso2:"NZ",iso:"NZL",label:"New Zealand",phone:"64"},{ioc:"OMA",iso2:"OM",iso:"OMN",label:"Oman",phone:"968"},{ioc:"PAN",iso2:"PA",iso:"PAN",label:"Panama",phone:"507"},{ioc:"PER",iso2:"PE",iso:"PER",label:"Peru",phone:"51"},{ioc:"FPO",iso2:"PF",iso:"PYF",label:"French Polynesia",phone:"689"},{ioc:"PNG",iso2:"PG",iso:"PNG",label:"Papua New Guinea",phone:"675"},{ioc:"PHI",iso2:"PH",iso:"PHL",label:"Philippines",phone:"63"},{ioc:"PAK",iso2:"PK",iso:"PAK",label:"Pakistan",phone:"92"},{ioc:"POL",iso2:"PL",iso:"POL",label:"Poland",phone:"48"},{ioc:"SPM",iso2:"PM",iso:"SPM",label:"Saint Pierre and Miquelon",phone:"508"},{ioc:"",iso2:"PN",iso:"PCN",label:"Pitcairn",phone:"870"},{ioc:"PUR",iso2:"PR",iso:"PRI",label:"Puerto Rico",phone:"1"},{ioc:"PLE",iso2:"PS",iso:"PSE",label:"Palestine, State of",phone:"970"},{ioc:"POR",iso2:"PT",iso:"PRT",label:"Portugal",phone:"351"},{ioc:"PLW",iso2:"PW",iso:"PLW",label:"Palau",phone:"680"},{ioc:"PAR",iso2:"PY",iso:"PRY",label:"Paraguay",phone:"595"},{ioc:"QAT",iso2:"QA",iso:"QAT",label:"Qatar",phone:"974"},{ioc:"REU",iso2:"RE",iso:"REU",label:"Reunion",phone:"262"},{ioc:"ROU",iso2:"RO",iso:"ROU",label:"Romania",phone:"40"},{ioc:"SRB",iso2:"RS",iso:"SRB",label:"Serbia",phone:"381"},{ioc:"RUS",iso2:"RU",iso:"RUS",label:"Russia",phone:"7"},{ioc:"RWA",iso2:"RW",iso:"RWA",label:"Rwanda",phone:"250"},{ioc:"KSA",iso2:"SA",iso:"SAU",label:"Saudi Arabia",phone:"966"},{ioc:"SOL",iso2:"SB",iso:"SLB",label:"Solomon Islands",phone:"677"},{ioc:"SEY",iso2:"SC",iso:"SYC",label:"Seychelles",phone:"248"},{ioc:"SUD",iso2:"SD",iso:"SDN",label:"Sudan",phone:"249"},{ioc:"SWE",iso2:"SE",iso:"SWE",label:"Sweden",phone:"46"},{ioc:"SIN",iso2:"SG",iso:"SGP",label:"Singapore",phone:"65"},{ioc:"HEL",iso2:"SH",iso:"SHN",label:"Saint Helena",phone:"290"},{ioc:"SLO",iso2:"SI",iso:"SVN",label:"Slovenia",phone:"386"},{ioc:"",iso2:"SJ",iso:"SJM",label:"Svalbard and Jan Mayen",phone:"47"},{ioc:"SVK",iso2:"SK",iso:"SVK",label:"Slovakia",phone:"421"},{ioc:"SLE",iso2:"SL",iso:"SLE",label:"Sierra Leone",phone:"232"},{ioc:"SMR",iso2:"SM",iso:"SMR",label:"San Marino",phone:"378"},{ioc:"SEN",iso2:"SN",iso:"SEN",label:"Senegal",phone:"221"},{ioc:"SOM",iso2:"SO",iso:"SOM",label:"Somalia",phone:"252"},{ioc:"SUR",iso2:"SR",iso:"SUR",label:"Suriname",phone:"597"},{ioc:"",iso2:"SS",iso:"SSD",label:"South Sudan",phone:"211"},{ioc:"STP",iso2:"ST",iso:"STP",label:"Sao Tome and Principe",phone:"239"},{ioc:"ESA",iso2:"SV",iso:"SLV",label:"El Salvador",phone:"503"},{ioc:"",iso2:"SX",iso:"SMX",label:"Sint Maarten",phone:"1-721"},{ioc:"SYR",iso2:"SY",iso:"SYR",label:"Syria",phone:"963"},{ioc:"",iso2:"SZ",iso:"SWZ",label:"Swaziland",phone:"268"},{ioc:"TKS",iso2:"TC",iso:"TCA",label:"Turks and Caicos Islands",phone:"1-649"},{ioc:"CHA",iso2:"TD",iso:"TCD",label:"Chad",phone:"235"},{ioc:"",iso2:"TF",iso:"ATF",label:"French Southern Territories",phone:"262"},{ioc:"TOG",iso2:"TG",iso:"TGO",label:"Togo",phone:"228"},{ioc:"THA",iso2:"TH",iso:"THA",label:"Thailand",phone:"66"},{ioc:"TJK",iso2:"TJ",iso:"TJK",label:"Tajikistan",phone:"992"},{ioc:"",iso2:"TK",iso:"TKL",label:"Tokelau",phone:"690"},{ioc:"TLS",iso2:"TL",iso:"TLS",label:"Timor-Leste",phone:"670"},{ioc:"TKM",iso2:"TM",iso:"TKM",label:"Turkmenistan",phone:"993"},{ioc:"TUN",iso2:"TN",iso:"TUN",label:"Tunisia",phone:"216"},{ioc:"TGA",iso2:"TO",iso:"TON",label:"Tonga",phone:"676"},{ioc:"TUR",iso2:"TR",iso:"TUR",label:"Turkey",phone:"90"},{ioc:"TTO",iso2:"TT",iso:"TTO",label:"Trinidad and Tobago",phone:"1-868"},{ioc:"TUV",iso2:"TV",iso:"TUV",label:"Tuvalu",phone:"688"},{ioc:"TPE",iso2:"TW",iso:"TWN",label:"Taiwan",phone:"886"},{ioc:"TAN",iso2:"TZ",iso:"TZA",label:"United Republic of Tanzania",phone:"255"},{ioc:"UKR",iso2:"UA",iso:"UKR",label:"Ukraine",phone:"380"},{ioc:"UGA",iso2:"UG",iso:"UGA",label:"Uganda",phone:"256"},{ioc:"USA",iso2:"US",label:"United States",phone:"1",suggested:!0,iso:"USA"},{ioc:"URU",iso2:"UY",iso:"URY",label:"Uruguay",phone:"598"},{ioc:"UZB",iso2:"UZ",iso:"UZB",label:"Uzbekistan",phone:"998"},{ioc:"",iso2:"VA",iso:"VAT",label:"Holy See (Vatican City State)",phone:"379"},{ioc:"VIN",iso2:"VC",iso:"VCT",label:"Saint Vincent and the Grenadines",phone:"1-784"},{ioc:"VEN",iso2:"VE",iso:"VEN",label:"Venezuela",phone:"58"},{ioc:"IVB",iso2:"VG",iso:"VGB",label:"British Virgin Islands",phone:"1-284"},{ioc:"ISV",iso2:"VI",iso:"VIR",label:"US Virgin Islands",phone:"1-340"},{ioc:"VIE",iso2:"VN",iso:"VNM",label:"Vietnam",phone:"84"},{ioc:"VAN",iso2:"VU",iso:"VUT",label:"Vanuatu",phone:"678"},{ioc:"WAF",iso2:"WF",iso:"WLF",label:"Wallis and Futuna",phone:"681"},{ioc:"SAM",iso2:"WS",iso:"WSM",label:"Samoa",phone:"685"},{ioc:"KOS",iso2:"XK",iso:"KOS",label:"Kosovo",phone:"383"},{ioc:"YEM",iso2:"YE",iso:"YEM",label:"Yemen",phone:"967"},{ioc:"MAY",iso2:"YT",iso:"MYT",label:"Mayotte",phone:"262"},{ioc:"RSA",iso2:"ZA",iso:"ZAF",label:"South Africa",phone:"27"},{ioc:"ZAM",iso2:"ZM",iso:"ZMB",label:"Zambia",phone:"260"},{ioc:"ZIM",iso2:"ZW",iso:"ZWE",label:"Zimbabwe",phone:"263"}];function $h({participant:t,withISO2:e,withIOC:r}){let{person:n,individualParticipants:o}=t,i=[n,o?.map(({person:a})=>a)].flat().filter(Boolean);function s(a){let{nationalityCode:c}=a||{};if(c){let u=ei.find(({iso:p})=>p===c);r&&u?.ioc&&!a.iocNationalityCode&&(a.iocNationalityCode=u.ioc),e&&u?.iso2&&!a.iso2NationalityCode&&(a.iso2NationalityCode=u.iso2),u?.label&&!a.countryName&&(a.countryName=u.label)}}i.forEach(s)}function Eb({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?Vi({template:e,source:s}):s)}}}}function To(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:te}}function Kh(t){let{tournamentRecord:e,participantId:r}=t;if(r){let o=To({tournamentRecord:e,participantId:r});return o.participant??o}let n=t.element||t.drawDefinition||t.event||t.tournamentRecord;return n||{error:st}}function rn(t){let{returnPreviousValues:e,itemSubTypes:r,itemType:n}=t,o=Kh(t);if(o.error)return o;if(r&&!Array.isArray(r))return{error:G,context:{itemSubTypes:r}};if(!Array.isArray(o.timeItems))return{error:tf};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=J(i.pop(),!1,!0);if(s){let a={timeItem:s,...C};return e&&Object.assign(a,{previousItems:i}),a}else return{info:ve}}function zh({returnPreviousValues:t,drawDefinition:e,itemSubTypes:r,itemType:n}){if(!e)return{error:an};if(!e.timeItems)return{info:ve};let{timeItem:o,previousItems:i,info:s}=rn({element:e,returnPreviousValues:t,itemSubTypes:r,itemType:n});return o&&{timeItem:o,previousItems:i}||{info:s}}function lu({returnPreviousValues:t,itemSubTypes:e,itemType:r,event:n}){if(!n)return{error:vt};if(!n.timeItems)return{info:ve};let{timeItem:o,previousItems:i,info:s}=rn({returnPreviousValues:t,element:n,itemSubTypes:e,itemType:r});return o&&{timeItem:o,previousItems:i}||{info:s}}function Jm({returnPreviousValues:t,tournamentRecord:e,itemSubTypes:r,itemType:n}){if(!e)return{error:Y};if(!e.timeItems)return{info:ve};let{timeItem:o,previousItems:i,info:s}=rn({element:e,returnPreviousValues:t,itemSubTypes:r,itemType:n});return o&&{timeItem:o,previousItems:i}||{info:s}}function Qh({returnPreviousValues:t,tournamentRecord:e,participantId:r,itemSubTypes:n,itemType:o}){if(!e)return{error:Y};if(!r)return{error:oe};let i=To({tournamentRecord:e,participantId:r});if(i.error)return i;let{participant:s}=i;if(!s?.timeItems)return{info:ve};let{timeItem:a,previousItems:c,info:u}=rn({element:i.participant,returnPreviousValues:t,itemSubTypes:n,itemType:o});return a&&{timeItem:a,previousItems:c}||{info:u}}var JF={[zr]:"groupParticipantIds",[ft]:"pairParticipantIds",[wt]:"teamParticipantIds"},ZF={[zr]:"groups",[wt]:"teams"};function Xh({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&&rk({participantMap:p,participantId:l})}for(let d of r.participants??[]){let l=J(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 h=ek({individualParticipantIds:g,participantCopy:l,participantMap:p,participantType:I,participantId:f});h.missingParticipantIds.length&&u.push(...h.missingParticipantIds)}if(n&&(p[f].participant.signedIn=tk(l)),o){let{ratings:h,rankings:S,seedings:T}=la({participant:l});p[f].participant.seedings=T,p[f].participant.rankings=S,p[f].participant.ratings=h}(c||a)&&$h({participant:p[f].participant,withISO2:a,withIOC:c})}if(t){let d=ht(t)?t:void 0;Eb({participantMap:p,template:d})}let m;return i&&(m=du({participants:Object.values(p).map(({participant:d})=>d),participantsProfile:{convertExtensions:e},deepCopy:!1}).groupInfo),{missingParticipantIds:u,participantMap:p,groupInfo:m}}function tk(t){let{timeItem:e}=rn({itemType:sc,element:t});return e?.itemValue===pu}function ek({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[JF[n]].push(o),[wt,zr].includes(n)){let{participantRoleResponsibilities:c,participantOtherName:u,participantName:p,participantId:m,teamId:d}=e,l=ZF[n];a[l].push({participantRoleResponsibilities:c,participantOtherName:u,participantName:p,participantId:m,teamId:d})}if(n===ft){let c=t.find(u=>u!==s);r[s].pairIdMap[o]=c,r[s].pairIdMap[c]=o}}return{missingParticipantIds:i}}function rk({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:{[Ft]:{...r},[_t]:{...r},[wt]:{...r},...r}}}function Bo({participantsProfile:t,useParticipantMap:e,tournamentRecord:r,contextProfile:n,inContext:o}){if(e)return Xh({...t,...n,tournamentRecord:r});let i=J(r.participants,!1,!0)||[];(t?.withIOC||t?.withISO2)&&i.forEach(a=>$h({participant:a,...t}));let s;if((o||t?.withGroupings)&&i?.length&&({participantsWithGroupings:i,groupInfo:s}=du({participantsProfile:t,deepCopy:!1,participants:i})),t?.withScaleValues&&i?.length)for(let a of i){let{ratings:c,rankings:u}=la({participant:a});a.rankings=u,a.ratings=c}return{participants:i,groupInfo:s}}function yt({onlySpecifiedPolicyTypes:t=!1,policyTypes:e=[],tournamentRecord:r,drawDefinition:n,structure:o,event:i}){if(!Array.isArray(e))return{error:wI};let s={};return r&&a(r),i&&a(i),n&&a(n),o&&a(o),{appliedPolicies:s,...C};function a(c){let p=c?.extensions?.find(m=>m.name===nu)?.value;if(p)for(let m of Object.keys(p))(t?e.includes(m):!e.length||e.includes(m))&&(s[m]=J(p[m],!1,!0))}}function vo({policyTypes:t=[],tournamentRecord:e,drawDefinition:r,structure:n,event:o}){if(!Array.isArray(t))return{error:wI};let{appliedPolicies:i}=yt({tournamentRecord:e,drawDefinition:r,structure:n,event:o}),s={};for(let a of t){let c=i?.[a];c&&(s[a]=c)}return Object.keys(s).length?{policyDefinitions:s}:{info:Fc.message}}var Jh="WALKOVER",kU="RETIRED",Zm="COMPETITIVE",ac="ROUTINE",cc="DECISIVE",td="winRatio";var nk={[Si]:{policyName:"Competitive Bands Default",profileBands:{[cc]:20,[ac]:50}}},ed=nk;function $n({policyDefinitions:t,tournamentRecord:e,contextProfile:r,drawDefinition:n,event:o}){let i={policies:{}};if(!r)return i;let s=vo({tournamentRecord:e,drawDefinition:n,event:o}).policyDefinitions;if(r.withCompetitiveness){let a=t?.[Si]??s?.[Si]??ed[Si];i.policies[Si]=a}return i}function ri({tournamentRecord:t,drawDefinition:e,policyType:r,structure:n,event:o}){if(!t)return{error:Y};let{appliedPolicies:i}=yt({tournamentRecord:t,drawDefinition:e,structure:n,event:o});return i?.[r]?{policy:i[r]}:{info:Fc?.message}}function ya({tournamentRecord:t,categoryName:e,categoryType:r,event:n}){e=e??n?.category?.categoryName??n?.category?.ageCategoryCode,r=r??n?.category?.categoryType??n?.category?.subType;let{policy:o}=ri({policyType:No,tournamentRecord:t,event:n}),s=(t?dt({element:t,name:Vo}).extension:void 0)?.value,c=(n&&dt({name:Vo,element:n}).extension)?.value;return{scheduleTiming:{tournamentScheduling:s,eventScheduling:c,categoryName:e,categoryType:r,policy:o}}}function qf({drawDefinition:t,attributes:e}){let{extension:r}=dt({element:t,name:Ym}),n=r?.value||{};return e.forEach(o=>{Object.keys(o).forEach(i=>{n[i]?Object.assign(n[i],o[i]):n[i]=o[i]})}),r={name:Ym,value:n},gp({drawDefinition:t,extension:r}),{entryProfile:n}}function fu({drawDefinition:t}){let{extension:e}=dt({element:t,name:Ym});return{entryProfile:e?.value||{}}}var nn="ALTERNATE",$f="CONFIRMED",kr="DIRECT_ACCEPTANCE",rd="FEED_IN",Kf="JUNIOR_EXEMPT",cs="LUCKY_LOSER",zf="ORGANISER_ACCEPTANCE",nd="QUALIFIER",ok="REGISTERED",Qf="SPECIAL_EXEMPT",Gr="UNGROUPED",Ei="UNPAIRED",gu="WILDCARD",so="WITHDRAWN",Xf=[$f,kr,Kf,zf,Qf],GU=[rd,cs,nd],ni=[$f,kr,rd,Kf,zf,Qf,gu],Qr=[$f,kr,Kf,cs,nd,zf,Qf,gu],VU=[nn,$f,kr,rd,Kf,cs,zf,nd,ok,Qf,Gr,Ei,gu,so],Ub={ALTERNATE:nn,CONFIRMED:$f,DIRECT_ACCEPTANCE:kr,DIRECT_ENTRY_STATUSES:ni,DRAW_SPECIFIC_STATUSES:GU,EQUIVALENT_ACCEPTANCE_STATUSES:Xf,FEED_IN:rd,JUNIOR_EXEMPT:Kf,LUCKY_LOSER:cs,ORGANISER_ACCEPTANCE:zf,QUALIFIER:nd,SPECIAL_EXEMPT:Qf,STRUCTURE_SELECTED_STATUSES:Qr,UNGROUPED:Gr,UNPAIRED:Ei,VALID_ENTRY_STATUSES:VU,WILDCARD:gu,WITHDRAWN:so};function Jf({stage:t,drawDefinition:e}){let{entryProfile:r}=fu({drawDefinition:e}),n=Object.keys(r).includes(t);if(!n&&$c.includes(t)){let o=[{[t]:{drawSize:void 0,alternates:!0}}];return qf({drawDefinition:e,attributes:o}),!0}return n}function Pb({stage:t,drawDefinition:e}){let{entryProfile:r}=fu({drawDefinition:e});return r[t]?.alternates||0}function Db({stage:t,drawDefinition:e}){let{entryProfile:r}=fu({drawDefinition:e});return r[t]?.wildcardsCount||0}function Zh({stage:t,drawDefinition:e,entryStatus:r}){return e.entries.reduce((n,o)=>o.entryStage===t&&o.entryStatus===r?n+1:n,0)}function Ui({provisionalPositioning:t,placementGroup:e,drawDefinition:r,stageSequence:n,entryStatuses:o,structureId:i,roundTarget:s,stages:a,stage:c}){let u=r.entries?.reduce((p,m)=>{let d=dt({name:Mn,element:m})?.extension?.value,l=c&&m.entryStage===c||a?.length&&m.entryStage&&a.includes(m.entryStage),f=!o||m.entryStatus&&o.includes(m.entryStatus),g=m.entryStageSequence??1;return l&&(!n||g===n)&&f&&(!s||!d||s===d)?p.concat(m):p},[])??[];if(i&&c===de){let{playoffEntries:p,error:m}=ik({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 ik({provisionalPositioning:t,drawDefinition:e,structureId:r}){let n=[],o=(e.links??[]).find(i=>i.linkType===eo&&i.target.structureId===r);if(o){let{finishingPositions:i,structureId:s}=o.source,{structure:a}=at({drawDefinition:e,structureId:s});a?.structureType===Ge&&(a.structures??[]).forEach(u=>{let p=u.positionAssignments??[],{structureId:m}=u,d=m,l=Object.assign({},...p.map(h=>{let{participantId:S}=h,T=dt({element:h,name:Zo}).extension?.value;return T&&S?{[S]:T}:void 0}).filter(Boolean)),g=Object.keys(l).reduce((h,S)=>{let T=l[S],y=T.groupOrder||t&&T.provisionalOrder;return h.includes(y)||h.push(y),h},[]).length===Object.keys(l).length,I=Object.keys(l).filter(h=>{let S=l[h],T=S.groupOrder||t&&S.provisionalOrder;return i?.includes(T)});(!t||g)&&I.forEach(h=>{let S=l[h],{groupOrder:T,provisionalOrder:y,GEMscore:P}=S,U=T||t&&y,A=[...i??[]].sort(me).indexOf(U)+1;n.push({entryStage:de,entryStatus:rd,placementGroup:A,groupingValue:d,participantId:h,GEMscore:P})})})}return{playoffEntries:n}}function Nb({stage:t,drawDefinition:e}){return ni.reduce((r,n)=>(Zh({drawDefinition:e,entryStatus:n,stage:t})||0)+r,0)}function on({provisionalPositioning:t,returnAllProxies:e,drawDefinition:r,structureId:n,structure:o}){let i,s=[];o||({structure:o,error:i}=at({drawDefinition:r,structureId:n}));let a=bt({structure:o}).positionAssignments;if(i||!o)return{seedAssignments:[],error:kt};n||(n=o.structureId);let{stage:c,stageSequence:u}=o,m=c===de&&r&&Ui({provisionalPositioning:t,drawDefinition:r,stageSequence:u,structureId:n,stage:c}),d=m?m.filter(g=>g.placementGroup===1).sort((g,I)=>g.GEMscore<I.GEMscore&&1||g.GEMscore>I.GEMscore&&-1||0).map((g,I)=>{let h=I+1;return{participantId:g.participantId,seedValue:h,seedProxy:!0,seedNumber:h}}):[],l=d?.slice(0,e?d.length:a.length/2);l.length?s=l:o.seedAssignments?s=o.seedAssignments:i=FA;let f=o.seedLimit??o?.positionAssignments?.length;return{seedAssignments:s,stageSequence:u,seedLimit:f,stage:c,error:i}}function oi(t){if(!t)return;let{tieFormatId:e,tieFormats:r}=t;if(t.tieFormat)return t.tieFormat;if(e&&Array.isArray(r))return r.find(n=>n.tieFormatId===e)}function yp({item:t,drawDefinition:e,structure:r,event:n}){if(t){if(t.tieFormat)return t.tieFormat;if(t.tieFormatId){if(e.tieFormat)return e.tieFormat;let o=e.tieFormats?.find(i=>t.tieFormatId===i.tieFormatId);return o||(n.tieFormat?n.tieFormat:n.tieFormats?.find(i=>t.tieFormatId===i.tieFormatId))}if(r.tieFormat)return r.tieFormat;if(r.tieFormatId){let o=e.tieFormats?.find(i=>r.tieFormatId===i.tieFormatId);if(o)return o}}}function We({drawDefinition:t,structure:e,matchUp:r,event:n}){return{tieFormat:yp({item:r,drawDefinition:t,structure:e,event:n})||yp({item:e,drawDefinition:t,structure:e,event:n})||oi(t)||oi(n)}}function Mb({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 Me({drawDefinition:t,structure:e}){let r={},n=[];return(t?.structures??[e]).filter(o=>o&&typeof o=="object").forEach(o=>{if(!o)return;let{structureId:i,matchUps:s,structures:a}=o,c=Array.isArray(a);if(c)c&&a.forEach(u=>{let{structureName:p}=u,m=u.matchUps;r[u.structureId]={matchUps:m,itemStructureIds:[],structureName:p},m&&(n.push(...m),m.forEach(d=>{d.tieMatchUps&&n.push(...d.tieMatchUps)})),r[i]||(r[i]={itemStructureIds:[],matchUps:[]}),r[i].itemStructureIds||(r[i].itemStructureIds=[]),r[i].itemStructureIds.push(u.structureId)});else{let u=s;r[i]={matchUps:u,itemStructureIds:[]},u?.forEach(p=>{n.push(p),p.tieMatchUps&&n.push(...p.tieMatchUps)})}}),{mappedMatchUps:r,drawMatchUps:n}}function ii({mappedMatchUps:t,matchUpsMap:e,structureId:r,inContext:n}){t=e?.mappedMatchUps??t;let o=t[r],i=(o?.itemStructureIds||[]).map(s=>{let{matchUps:a,structureName:c}=t[s];return n?a.map(u=>Object.assign(J(u,!0,!0),{containerStructureId:r,structureId:s,structureName:c})):a}).flat();return(o?.matchUps||[]).concat(...i)}function tS({groupedOrder:t,roundPositionsCount:e}){if(!t||t?.length<=e)return t;let n=Ae(t,t.length/e).map(i=>i.reduce((s,a)=>s+a)),o=n.slice().sort(me);return n.map(i=>o.indexOf(i)+1)}function Zf(t){if(!ht(t))return!1;let{matchUpId:e,drawPositions:r}=t,n=typeof e=="string",o=!r||Array.isArray(r)&&r.length<=2&&r.every(i=>It(i)||i===void 0||i===null);return n&&o}function Vr(t){return Array.isArray(t)?t.every(Zf):!1}function Ke({matchUps:t=[],interpolate:e}){if(!Vr(t))return{roundMatchUps:[],error:G};let r=t.reduce((d,l)=>{let f=typeof l.roundNumber=="string"?pt(l.roundNumber):l.roundNumber;return!l.roundNumber||d.includes(f)?d:d.concat(f)},[]).sort(me).map(d=>{let l=t.filter(h=>h.roundNumber===d),g=l.find(({matchUpType:h})=>h===jt)?l.filter(({matchUpType:h})=>h===jt):l,I=h=>h.sort((S,T)=>me(S.roundPosition,T.roundPosition));return{[d]:I(g)}}),n=t.reduce((d,l)=>{let f=typeof l.roundNumber=="string"?pt(l.roundNumber):l.roundNumber;return d[f]||(d[f]=ot({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=>pt(f)).filter(f=>!isNaN(f))),l=o[d]?.length;if(l>1&&vn(l)){let f=d+1,g=f+l/2;et(f,g).forEach((h,S)=>{o[h]=et(0,l/(2+S*2)).map(()=>({}))})}}let i=0,s=Object.assign({},...Object.keys(o).map(d=>{let l=o[d]?.length,f=o[d]?.filter(I=>!ce.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=>pt(d)).filter(d=>!isNaN(d));u.forEach(d=>{let l=o[d].sort((g,I)=>g.roundPosition-I.roundPosition),f=l.map(g=>g?.drawPositions||[]).flat();if(s[d].roundNumber=d,s[d].roundFactor=s[d].matchUpsCount?i/s[d].matchUpsCount:1,s[d].finishingRound=n[d]?.finishingRound,s[d].roundName=n[d]?.roundName,s[d].abbreviatedRoundName=n[d]?.abbreviatedRoundName,s[d].finishingPositionRange=o[d]?.[0]?.finishingPositionRange,d===1||!s[d-1]){let g=f.sort(me),I=Ae(g,2);s[d].drawPositions=g,s[d].pairedDrawPositions=I}else{let g=s[d-1],I=g.drawPositions,h=g.matchUpsCount/s[d].matchUpsCount,S=Ae(I,h),T=l.map(y=>{let{roundPosition:P}=y,U=[...y.drawPositions||[],void 0,void 0].slice(0,2);if(!P)return U;let A=U?.filter(Boolean)||[];if(!A?.length)return[void 0,void 0];if(d<3&&A?.length===2)return U?.slice().sort(me);let E=Yt(I,A).length!==A?.length;if(A?.length&&E)return A?.length===1?[A[0],void 0]:U?.slice().sort(me);let N=(P-1)*2;return S.slice(N,N+2).map(M=>A?.find(R=>M.includes(R)))});s[d].drawPositions=T?.flat(),s[d].pairedDrawPositions=T}s[d+1]&&s[d+1].matchUpsCount===s[d].matchUpsCount&&(s[d+1].feedRound=!0,s[d+1].feedRoundIndex=c,s[d].preFeedRound=!0,c+=1),s[d]&&!s[d].feedRound&&(s[d].roundIndex=a,a+=1)});let p=!!Object.values(s).find(({matchUpsCount:d})=>!vn(d));return{hasNoRoundPositions:t.some(d=>!d.roundPosition),roundsNotPowerOf2:p,maxMatchUpsCount:i,roundMatchUps:o,roundNumbers:u,roundProfile:s,...C}}function od(t){if(!Array.isArray(t))return"";let e=t.filter(Zt);return e.length?ut([Math.min(...e),Math.max(...e)]).join("-"):""}function Rb({drawDefinition:t,structureId:e,matchUpsMap:r}){if(!t)return{error:Z};if(!e)return{error:Ur};let{structure:n}=at({drawDefinition:t,structureId:e});if(n?.stage!==qe)return{error:Oi,info:"Structure is not CONSOLATION stage"};let{links:o}=t,i=o?.filter(m=>m.target.structureId===e)||[],s=i?.reduce((m,d)=>{let{structureId:l}=d.source;return m.includes(l)?m:m.concat(l)},[])||[],a=Object.assign({},...s.map(m=>{let d=ii({structureId:m,matchUpsMap:r}),f=Ke({matchUps:d}).roundProfile;return{[m]:f}})),c=ii({matchUpsMap:r,structureId:e}),{roundProfile:u}=Ke({matchUps:c}),p={};return i?.forEach(m=>{let{structureId:d,roundNumber:l}=m.source,{feedProfile:f,groupedOrder:g,positionInterleave:I,roundNumber:h}=m.target,S=a[d],T=S[1]?.drawPositions,P=S[l]?.matchUpsCount;if(!P)return;let U=P?T.length/P:0,A=T.length/U,E=T.slice(),N=tS({roundPositionsCount:A,groupedOrder:g}),D=N?.length||1;if(D<=A){let v=T.length/D,O=Ae(E,v);f===li&&O.forEach(x=>x.reverse()),E=N?.length&&N?.map(x=>O[x-1]).flat()||E}let M=Ae(E,U);if(I){let v=et(0,I.interleave).map(()=>{}),O=et(0,I.offset).map(()=>{});M=M.map(F=>[F,...v]),M.unshift(O),M=M.flat(1);let x=M.length-I.offset;M=M.slice(0,x)}p[h]||(p[h]={});let b=u?.[h]?.feedRound?2:1;M.forEach((v,O)=>{let x=1+O*b;p[h][x]||(p[h][x]=od(v))})}),{sourceDrawPositionRanges:p}}function eS({drawDefinition:t}){if(typeof t!="object")return{error:ua};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"&&[qe,de].includes(m)||s[c].push(a);let d=n.filter(l=>l.source.structureId===c&&l.source.roundNumber>=u);for(let l of d){let f=l.source.roundNumber,g=l.target.roundNumber,I=l.target.structureId,h=r.find(T=>T.structureId===I).stage,S=[h,I,g,f].join("|");if(p[S])return;p[S]=!0,i({exitProfile:`${a}-${f}`,structureId:I,exitProfiles:s,targetRound:g,aggregator:p,stage:h})}}}function Cb({drawDefinition:t,roundProfile:e,structureId:r,matchUpsMap:n}){if(!t)return{error:Z};if(!r)return{error:Ur};if(!e){let c=ii({matchUpsMap:n,structureId:r});if({roundProfile:e}=Ke({matchUps:c}),!e)return{error:st}}let i=(Math.min(...e?.[1]?.drawPositions??[])||1)-1,s=Object.keys(e);return{drawPositionsRanges:Object.assign({},...(s||[]).map(c=>{let u=e?.[c]?.matchUpsCount,p=e?.[1]?.drawPositions??[],m=Ae(p,p.length/u),d=m.map(od),l=m.map(S=>S.map(T=>T-i)).map(od),f=s.map(S=>{if(S>c)return;let T=e?.[S]?.drawPositions??[];return Ae(T,T.length/u)}).filter(Boolean),g=et(0,u).map(S=>f.map(T=>T[S]).flat().filter(Boolean).sort(me)).map(S=>ut(S)),I=g.map(S=>lC(S).map(od).join(", ")),h=Object.assign({},...et(0,u).map(S=>({[S+1]:{firstRoundDrawPositionsRange:d[S],firstRoundOffsetDrawPositionsRange:l[S],possibleDrawPositions:g[S],drawPositionsRange:I[S]}})));return{[c]:h}}))}}function id({roundsNotPowerOf2:t,drawDefinition:e,structure:r,matchUps:n}){if(!r)return!1;n=n??r.matchUps??[],t=t??Ke({matchUps:n}).roundsNotPowerOf2;let o=!!r.positionAssignments?.find(({drawPosition:i})=>i)||!!n?.find(({drawPositions:i})=>i?.length);return(!e?.drawType||e.drawType!==ki)&&!r?.structures&&t&&o}function cr({structure:t}){if(!t)return!1;let e=t.matchUps||t.roundMatchUps&&Object.values(t.roundMatchUps).flat(),r=!!e?.find(o=>o?.roundPosition),n=!!e?.find(o=>o?.drawPositions?.length);return!t?.structures&&t?.stage!==$e&&(!e.length||!r&&!n)}var tg={[fa]:{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:{[nt]:"",[de]:"P",[ct]:"Q",[qe]:"C"}}},bb=tg;function vb({roundNamingPolicy:t,drawDefinition:e,structure:r,matchUps:n}){let{roundProfile:o,roundMatchUps:i}=Ke({matchUps:n}),{structureAbbreviation:s,stage:a}=r,c=cr({structure:r}),u=id({structure:r}),p=r.structures,m={},d=tg[fa],l=r.stage===ct,f=l?Math.max(...(e?.structures??[]).filter(b=>b.stage===ct).map(({stageSequence:b})=>b??1),0):0,g=(r.stageSequence??1)<f?r.stageSequence??1:"",I=g&&(t?.affixes?.preQualifying||d.affixes.preQualifying)||"",h=t?.roundNamingMap||d.roundNamingMap||{},S=t?.abbreviatedRoundNamingMap||d.abbreviatedRoundNamingMap||{},T=t?.affixes?.preFeedRound||d.affixes.preFeedRound,y=t?.affixes?.roundNumber||d.affixes.roundNumber,U=(t?.namingConventions||d.namingConventions).round,A=a&&a!==nt?a[0]:"",E=t?.stageConstants||d.stageConstants,N=a&&E?.[a]||A,D=`${I}${N}${g}`,M=o?Object.keys(o):[],R=l&&E?.[ct]?`${E?.[ct]}-`:"";if(p||c||u)Object.assign(m,...M.map(b=>{let v=`${R}${U} ${b}`,O=`${y}${b}`;return{[b]:{roundName:v,abbreviatedRoundName:O}}}));else{let b=l&&(t?.qualifyingFinishMap||d?.qualifyingFinishMap||{});Object.assign(m,...M.map(v=>{if(!o?.[v])return;let{matchUpsCount:O,preFeedRound:x}=o[v],F=O*2,L=b?.[o?.[v].finishingRound]||b&&`${y}${F}`||h[O]||`${y}${F}`,w=x?`-${T}`:"",V=`${L}${w}`,k=[D,s,V].filter(Boolean).join("-"),H=`${S[O]||`${y}${F}`}${w}`,q=[D,s,H].filter(Boolean).join("-");return{[v]:{abbreviatedRoundName:q,roundName:k}}}))}return{roundNamingProfile:m,roundProfile:o,roundMatchUps:i}}var sk=(t,e)=>(t||0)+(e||0);function rS(t,e){let r=Array.isArray(t)?t[0]:t;return isNaN(r)&&Jh||r<=e[cc]&&cc||r<=e[ac]&&ac||Zm}function nS({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(sk)&&(r[n[0]>n[1]?0:1]+=1),{sets:e,games:r,score:t}}function ak(t){let e=Math.min(...t.games),r=Math.max(...t.games);return Math.round(e/r*100)}function oS(t){return t.map(ak).sort().map(e=>parseFloat(e.toFixed(2)))}function Iu({tournamentRecord:t,profileBands:e,matchUp:r}){if(!r)return{error:hr};let{score:n,winningSide:o}=r;if(!o)return{error:G};let i=!e&&t&&ri({policyType:Si,tournamentRecord:t}).policy,s=e||i?.profileBands||ed[Si].profileBands,a=nS({score:n}),c=oS([a]),u=rS(c,s),p=Array.isArray(c)?c[0]:c;return{...C,competitiveness:u,pctSpread:p}}function iS({matchUp:t}){if(!t)return{error:hr};if(t&&!t.sides)return{error:dr};if(t&&!t.hasContext)return{error:Gc};let e=(t.sides??[])?.map(a=>a?.participantId).filter(Boolean),r=t.sides?.filter(a=>a.participant?.participantType===Tt).map(a=>a.participantId).filter(Boolean)??[],o=((t.sides??[])?.map(a=>a.participant?.individualParticipants).filter(Boolean)??[]).map(a=>(a??[]).map(c=>c?.participantId).filter(Boolean)),i=[...r,...o.flat()].filter(Boolean)??[],s=ut(i.concat(e)).filter(Boolean)??[];return{nestedIndividualParticipantIds:o,allRelevantParticipantIds:s,individualParticipantIds:i,sideParticipantIds:e,...C}}var sd="CHECK_IN",ad="CHECK_OUT",ck="SCHEDULE",Hi="SCHEDULE.ASSIGNMENT.VENUE",ao="SCHEDULE.ALLOCATION.COURTS",Ho="SCHEDULE.ASSIGNMENT.COURT",Ap="SCHEDULE.COURT.ORDER",Wi="SCHEDULE.DATE",uk="COMPLETED.DATE",cd="HOME_PARTICIPANT_ID",eg="SCHEDULE.ASSIGN.OFFICIAL",ji="SCHEDULE.TIME.SCHEDULED",Oo="SCHEDULE.TIME.START",Yi="SCHEDULE.TIME.STOP",Pi="SCHEDULE.TIME.RESUME",Di="SCHEDULE.TIME.END",Ep="SCHEDULE.TIME.MODIFIERS",Ob="TO_BE_ANNOUNCED",_b="NEXT_AVAILABLE",xb="FOLLOWED_BY",wb="AFTER_REST",Lb="RAIN_DELAY",pk="NOT_BEFORE",sS=[Ob,_b,xb,wb,Lb],mk="ELIGIBILITY",dk="REGISTRATION",lk="SUSPENSION",fk="MEDICAL",gk="PENALTY",BU="SCALE",HU="RATING",WU="RANKING",rg="SEEDING",_o="PUBLISH",Mr="PUBLIC",xo="STATUS",Ik="MODIFICATION",hk="RETRIEVAL",Sk="other",Fb={MUTUALLY_EXCLUSIVE_TIME_MODIFIERS:sS,AFTER_REST:wb,ALLOCATE_COURTS:ao,ASSIGN_COURT:Ho,ASSIGN_OFFICIAL:eg,ASSIGN_VENUE:Hi,CHECK_IN:sd,CHECK_OUT:ad,COMPLETED_DATE:uk,COURT_ORDER:Ap,ELIGIBILITY:mk,END_TIME:Di,FOLLOWED_BY:xb,MEDICAL:fk,MODIFICATION:Ik,NEXT_AVAILABLE:_b,NOT_BEFORE:pk,OTHER:Sk,PENALTY:gk,PUBLIC:Mr,PUBLISH:_o,RANKING:WU,RATING:HU,RAIN_DELAY:Lb,REGISTRATION:dk,RESUME_TIME:Pi,RETRIEVAL:hk,SCALE:BU,SCHEDULE:ck,SCHEDULED_DATE:Wi,SCHEDULED_TIME:ji,SEEDING:rg,START_TIME:Oo,STATUS:xo,STOP_TIME:Yi,SUSPENSION:lk,TIME_MODIFIERS:Ep,TO_BE_ANNOUNCED:Ob};function us({matchUp:t}){if(!t)return{error:hr};if(!t.hasContext)return{error:Gc};if(!t.sides||t.sides.filter(Boolean).length!==2)return{error:dr};let{nestedIndividualParticipantIds:e,allRelevantParticipantIds:r,sideParticipantIds:n}=iS({matchUp:t}),i=(t.timeItems??[]).filter(u=>u?.itemType&&[sd,ad].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===sd);e?.forEach((u,p)=>{let m=n?.[p],d=u?.length&&u.every(l=>a.includes(l));m&&d&&!a.includes(m)&&a.push(m)}),n?.forEach((u,p)=>{a.includes(u)&&(e?.[p]??[]).forEach(m=>{m&&!a.includes(m)&&a.push(m)})});let c=n?.reduce((u,p)=>a.includes(p)&&u,!0);return{allRelevantParticipantIds:r,allParticipantsCheckedIn:c,checkedInParticipantIds:a,...C}}var ue=t=>e=>{let r=ht(e)&&e?.matchUpType||Vt(e)&&e;return r&&EI[t].includes(r)};function Up(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 Pp(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 aS({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 kb({tournamentScheduling:t,eventScheduling:e,averageMinutes:r,defaultTiming:n,matchUpFormat:o,categoryName:i,categoryType:s,policy:a}){let c=e?.matchUpRecoveryTimes&&Pp({...e,averageMinutes:r,matchUpFormat:o}),u=t?.matchUpRecoveryTimes&&Pp({...t,averageMinutes:r,matchUpFormat:o}),p=a?.matchUpRecoveryTimes&&Pp({...a,averageMinutes:r,matchUpFormat:o}),m=[c,u,p,a?.defaultTimes?.recoveryTimes,n?.recoveryTimes];return aS({categoryName:i,categoryType:s,timesBlockArray:m})}function Gb({matchUpFormat:t,categoryName:e,categoryType:r,defaultTiming:n,tournamentScheduling:o,eventScheduling:i,policy:s}){let a=i?.matchUpAverageTimes&&Up({...i,matchUpFormat:t}),c=o?.matchUpAverageTimes&&Up({...o,matchUpFormat:t}),u=s?.matchUpAverageTimes&&Up({...s,matchUpFormat:t}),p=[a,c,u,s?.defaultTimes?.averageTimes,n?.averageTimes];return aS({categoryName:e,categoryType:r,timesBlockArray:p})}var jU="DOUBLES_SINGLES",YU="SINGLES_DOUBLES",co="total",cS="participantConflict",Aa="matchUpConflict",qU="ISSUE_IDS",uc="CONFLICT",pc="WARNING",uS="ERROR",pS="ISSUE",ng="STATE",Vb={SINGLES_DOUBLES:YU,DOUBLES_SINGLES:jU,TOTAL:co,CONFLICT_MATCHUP_ORDER:Aa,CONFLICT_PARTICIPANTS:cS,SCHEDULE_ISSUE_IDS:qU,SCHEDULE_CONFLICT:uc,SCHEDULE_WARNING:pc,SCHEDULE_ERROR:uS,SCHEDULE_ISSUE:pS,SCHEDULE_STATE:ng};function hu({defaultAverageMinutes:t=90,defaultRecoveryMinutes:e=0,tournamentRecord:r,matchUpFormat:n,categoryName:o,categoryType:i,eventType:s,event:a}){if(!r)return{error:Y};s=s??a?.eventType??Fs;let c={averageTimes:[{minutes:{default:t}}],recoveryTimes:[{minutes:{default:e}}]},{scheduleTiming:u}=ya({tournamentRecord:r,categoryName:o,categoryType:i,event:a}),p={...u,matchUpFormat:n,categoryType:i,defaultTiming:c};return Dp({eventType:s,timingDetails:p})}function Dp({timingDetails:t,eventType:e}){let r=Gb(t),n=Object.keys(r?.minutes||{}),o=r?.minutes&&(n?.includes(e)&&r.minutes[e]||r.minutes.default),i=kb({...t,averageMinutes:o}),s=Object.keys(i?.minutes||{}),a=i?.minutes&&(s?.includes(e)&&i.minutes[e]||i.minutes.default),c=ue(Fs)(e)?YU:jU,u=i?.minutes&&(s?.includes(c)&&i.minutes[c]||a);return{averageMinutes:o,recoveryMinutes:a,typeChangeRecoveryMinutes:u}}function $U(t){return t.createdAt?new Date(t.createdAt).getTime():0}function Wo({timeItems:t,itemType:e}){let r=t.filter(o=>o&&o.itemType===e).sort((o,i)=>$U(o)-$U(i)).pop(),n=r&&$U(r);return{itemValue:r?.itemValue,timeStamp:n}}function mS({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Wo({timeItems:r?.timeItems||[],itemType:ji});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{scheduledTime:n}:e}function Hs({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Wo({timeItems:r?.timeItems||[],itemType:Wi});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{scheduledDate:n}:e}function Np(t){if($I.test(t)){let e=If();return new Date(`${e}T${t}`)}else return new Date(t)}function Bb({matchUp:t}){if(!t)return{error:hr};if(!t.timeItems)return{error:tf};let e=t.timeItems.filter(n=>[Oo,Yi,Pi,Di].includes(n?.itemType)).sort((n,o)=>Np(n.itemValue).getTime()-Np(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 Oo:i=0;break;case Di:if(n.lastValue&&[Oo,Pi].includes(n.lastType)){let u=Np(o.itemValue).getTime()-Np(n.lastValue).getTime();i=n.milliseconds+u}else i=n.milliseconds;break;case Yi:if([Oo,"SCHECULE.TIME.RESUME"].includes(n.lastType)){let u=Np(o.itemValue).getTime()-Np(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([Oo,Pi].includes(r.lastType)){let n=new Date().getTime()-Np(r.lastValue).getTime();r.milliseconds+=n}return{milliseconds:r.milliseconds,time:Tk(r.milliseconds),relevantTimeItems:e}}function Tk(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 Hb({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===Oo&&s;return a&&(!i||r(a)<r(i))?a:i},void 0)?.itemValue}}function mc(t){let{disableNotice:e,venue:r,context:n}=t;if(typeof r!="object")return{error:G};let o=Nr(t);r.venueId||(r.venueId=Dt());let i;for(let s of Object.values(o)){let a=yk({disableNotice:!0,tournamentRecord:s,context:n,venue:r});if(a?.error)return a;i=a.venue}return e||mt({topic:Hh,payload:{venue:r}}),ot({...C,venue:i})}function yk({tournamentRecord:t,disableNotice:e,context:r,venue:n}){return t?n?(t.venues||(t.venues=[]),n.venueId||(n.venueId=Dt()),t.venues.reduce((i,s)=>i||s.venueId===n.venueId,void 0)?{error:SE}:(r&&At({element:n,extension:{value:r,name:SU}}),t.venues.push(n),e||mt({payload:{venue:n,tournamentId:t.tournamentId},topic:Hh}),{...C,venue:J(n)})):{error:st,info:"missing venue"}:{error:Y}}function jo({tournamentRecords:t,tournamentRecord:e,venueId:r}){if(!e)return{error:Y};if(!r)return{error:Jo};let o=(e.venues??[]).reduce((i,s)=>s.venueId===r?s:i,void 0);if(!o&&t){let s=(iu({tournamentRecords:t}).linkedTournamentIds??[])[e.tournamentId];for(let a of s){let c=t[a],u=jo({tournamentRecord:c,venueId:r});if(u.success&&u.venue)return mc({tournamentRecord:e,venue:u.venue}),{...C,venue:o}}}return o?{...C,venue:o}:{error:Li}}function dS({convertExtensions:t,...e}){let{tournamentRecords:r,tournamentRecord:n,venueId:o}=e,i=jo({tournamentRecords:r,tournamentRecord:n,venueId:o});return J(i,t,!0)}function ps({tournamentRecords:t,tournamentRecord:e,courtId:r}){if(!e)return{error:Y};if(!r)return{error:_i};let n="findCourt",o,i;if((e.venues??[]).forEach(s=>{(s.courts??[]).forEach(a=>{a.courtId===r&&(o=a,i=s)})}),o)return{...C,court:o,venue:i};if(t){let a=(iu({tournamentRecords:t}).linkedTournamentIds??[])[e.tournamentId];for(let c of a){let u=t[c],p=ps({tournamentRecord:u,courtId:r});if(p.success)return p.venue&&mc({tournamentRecord:e,venue:p.venue}),{...C,court:o,venue:i}}}return _({result:{error:Os},stack:n})}function lS(t){return J(ps(t),!1,!0)}function ud({tournamentRecord:t,internalUse:e,courtId:r}){if(!t)return{error:Y};if(!r)return{error:_i};let n=ps({tournamentRecord:t,courtId:r});if(n.error)return n;let o=n.court&&(({altitude:i,courtId:s,courtName:a,courtDimensions:c,latitude:u,longitude:p,surfaceCategory:m,surfaceType:d,surfacedDate:l,pace:f,notes:g})=>({altitude:i,courtId:s,courtName:a,courtDimensions:c,latitude:u,longitude:p,surfaceCategory:m,surfaceType:d,surfacedDate:l,pace:f,notes:g}))(n.court);return{...C,courtInfo:J(o,!1,e)}}function dc(t){let e=rt(t,[{[ie]:!0},{venueId:!0,[fn]:Jo}]);if(e.error)return e;let{tournamentRecord:r,venueId:n}=t,o=jo({tournamentRecord:r,venueId:n});if(o.error)return o;let s=(o.venue?.courts??[]).map(u=>(({courtInfo:p})=>({...p}))(ud({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{...C,venueData:J(c,!1,!0)}}function Wb({matchUp:t}){let e=t?.timeItems||[],r=i=>i.createdAt?new Date(i.createdAt).getTime():0;return{endTime:e.reduce((i,s)=>{let a=s.itemType===Di&&s;return a&&(!i||r(a)>r(i))?a:i},void 0)?.itemValue}}function Ht({event:t,eventId:e}){if(!t)return{error:vt};let n=dt({name:un,element:t})?.extension,o=e?J(n?.value,!1,!0):n?.value;return e&&t.drawDefinitions?.forEach(i=>{o?.flights?.forEach(s=>{s.drawId===i.drawId&&Object.assign(s,{drawDefinition:i})})}),{flightProfile:o}}function ze(t){let{tournamentRecord:e,eventId:r,drawId:n}=t,o="findEvent",i={},s=t.tournamentRecords??(e&&{[e.tournamentId]:e})??{},a=Object.values(s).map(({events:u,tournamentId:p})=>(u&&u.forEach(m=>{i[m.eventId]={tournamentId:p}}),u??[])).flat(),c;if(n){let u,p=a.find(m=>{let l=(m?.drawDefinitions??[]).find(f=>f.drawId===n);if(l)u=l,c=i[m.eventId].tournamentId;else{let g=(m&&Ht({event:m})?.flightProfile)?.flights?.find(I=>I.drawId===n);if(g)return c=i[m.eventId].tournamentId,{entries:g.drawEntries,drawName:g.drawName,tournamentId:c,drawId:n}}return l});if(p)return{event:p,drawDefinition:u,tournamentId:c}}if(r){let u=a.find(p=>p?.eventId===r);if(u)c=i[u.eventId].tournamentId;else return{event:void 0,drawDefinition:void 0,..._({result:{error:jr},stack:o})};return{event:u,drawDefinition:void 0,tournamentId:c}}return{event:void 0,drawDefinition:void 0,..._({result:{error:Rr},context:{drawId:n,eventId:r},stack:o})}}function pd(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:hr};if(o&&!p.matchUpType&&!t.matchUpType&&(e||i)&&p.drawId){let U=t.drawDefinition||e?.drawDefinitions?.find(E=>E.drawId===p.drawId);!U&&i&&({drawDefinition:U,event:e}=ze({drawId:p.drawId,tournamentRecord:i}));let A=p.structureId&&U?.structures?.find(({structureId:E})=>E===p.structureId);r=t.matchUpType||A?.matchUpType||U?.matchUpType||e?.eventType!==_e&&e?.eventType}let{milliseconds:m,time:d}=Bb({matchUp:p}),{startTime:l}=Hb({matchUp:p}),{endTime:f}=Wb({matchUp:p}),g,{eventIds:I,drawIds:h}=n??{};if((!I||I.includes(p.eventId))&&(!h||h.includes(p.drawId))){let U=X=>X.createdAt?new Date(X.createdAt).getTime():0,A=new Map,E=p.timeItems?.toSorted((X,lt)=>U(X)-U(lt))??[];for(let X of E)A.set(X.itemType,X.itemValue);let N=A.get(cd),D=A.get(ao),M=A.get(ji),R=A.get(Ep),b=A.get(Wi),v=A.get(eg),O=A.get(Ap),x=A.get(Hi),F=A.get(Ho),L,w,V,k,W,H=p.matchUpType??r;if(a&&M&&o&&H){let X={matchUpFormat:p.matchUpFormat??c,...a};({averageMinutes:w=0,recoveryMinutes:V=0,typeChangeRecoveryMinutes:k=0}=Dp({timingDetails:X,eventType:H})),(w||V)&&(L=f?Yr(Kt(f),V):Yr(M,w+V)),k&&(W=f?Yr(Kt(f),k):Yr(M,w+k))}!b&&M&&(b=Et(M));let q=vm({scheduledDate:b,scheduledTime:M}),$={},B=(i&&x&&dc({tournamentRecord:i,venueId:x}))?.venueData||{};x&&($[x]=B);let{venueName:K,venueAbbreviation:Q,courtsInfo:j}=B,z=(F&&j?.find(X=>X.courtId===F))?.courtName;for(let X of D||[]){if(!i)break;X.venueId&&!$[X.venueid]&&($[X.venueId]=dc({venueId:X.venueId,tournamentRecord:i})?.venueData);let lt=$[X.venueId];X.venueName=lt?.venueName;let it=lt?.courtsInfo?.find(Rt=>Rt.courtId===X.courtId);X.courtName=it?.courtName}g=ot({typeChangeTimeAfterRecovery:W,timeAfterRecovery:L,scheduledDate:b,scheduledTime:M,isoDateString:q,homeParticipantId:N,venueAbbreviation:Q,allocatedCourts:D,timeModifiers:R,venueName:K,venueId:x,courtOrder:O,courtName:z,courtId:F,official:v,typeChangeRecoveryMinutes:k,recoveryMinutes:V,averageMinutes:w,milliseconds:m,startTime:l,endTime:f,time:d})}else g=ot({milliseconds:m,startTime:l,endTime:f,time:d});let{scheduledDate:S}=Hs({matchUp:p}),{scheduledTime:T}=mS({matchUp:p});if(s&&u?.displaySettings?.draws){let U=u.displaySettings.draws,A=(U?.[p.drawId]??U?.default)?.scheduleDetails;if(A){let E=(A.find(N=>S&&N.dates?.includes(S))??A.find(N=>!N.dates?.length))?.attributes;if(E){let N=Object.assign({},...Object.keys(g).map(D=>({[D]:!0})),E);g=Vi({source:g,template:N})}}}let P=p.matchUpStatus&&ce.includes(p.matchUpStatus)&&(Et(f)||Et(S)||Et(T))||void 0;return{schedule:g,endDate:P}}function jb({drawPositions:t,roundProfile:e,roundNumber:r}){let n=[void 0,void 0];if(NI(t))return{orderedDrawPositions:n,displayOrder:n};let o=e?.[r],s=o?.pairedDrawPositions?.find(c=>Fe(c||[],t.filter(Boolean)))??n,a=o?.feedRound;if(DI(t)){let c=[...t].sort(me);return{orderedDrawPositions:c.length===2?c:s,displayOrder:a?c:s}}if(a){let u=[t.find(p=>!isNaN(pt(p))),void 0];return{orderedDrawPositions:u,displayOrder:u}}return{orderedDrawPositions:s,displayOrder:s}}function Mp({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 In({tournamentParticipants:t,tournamentRecord:e,participantIds:r}){let n="getPairedParticipant";if(!t&&!e)return{error:Y};if(!Array.isArray(r)||r.length>2)return{error:wr};if(!r.length)return _({result:{error:Uo},stack:n});t=t??e?.participants??[];let o=t.filter(a=>a.participantType===ft&&Yt(r,a.individualParticipantIds).length===r.length&&a.individualParticipantIds.length===r.length),i=o[0];if(!i)return _({result:{error:te},stack:n});let s=J(o.slice(1),!1,!0);return{participant:J(i),duplicatedPairParticipants:s,...C}}function ms({drawDefinition:t,participantId:e}){if(typeof t!="object")return{error:Z};if(typeof e!="string")return{error:oe};let{extension:r}=dt({element:t,name:Ro});return{lineUp:(r?.value||{})[e]}}function Yb({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}=Mp({collectionPosition:r,collectionId:s,lineUp:d});if(c===_t){if(f?.length<=2){let I=o?.[f[0]]?.pairIdMap?.[f[1]],T=(I&&o[I]?.participant||In({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||ms({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||ms({participantId:d,drawDefinition:i})?.lineUp;return u({attribute:m,lineUp:g,teamParticipant:f})}).filter(Boolean)||{};return{drawPositionCollectionAssignment:Object.assign({},...p)}}function md(t){let e=rt(t,[{[_n]:!0}]);if(e.error)return e;let r=t?.matchUp,n=r?.matchUpType;if(!n&&r?.sides?.length){let s=r.sides.find(({participant:a})=>a)?.participant?.participantType;n=s===Tt&&Ft||s===ft&&_t||s===wt&&wt||void 0}return{matchUpType:n}}function qb({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?Ak({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 Ak({displaySideNumber:t,seedAssignments:e,participantId:r,assignment:n,sideNumber:o}){let i={drawPosition:n.drawPosition,displaySideNumber:t,sideNumber:o};if(r){let s=Ek({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 Ek({seedAssignments:t,participantId:e}){return t?.find(r=>!r.seedProxy&&r.participantId===e)}function KU({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:h,scheduleTiming:S,contextProfile:T,drawDefinition:y,publishStatus:P,scoringActive:U,matchUpTieId:A,isRoundRobin:E,roundProfile:N,sideLineUps:D,structure:M,context:R,matchUp:b,event:v}){c=c??{};let O=We({drawDefinition:y,structure:M,matchUp:b,event:v})?.tieFormat,{roundOffset:x,structureId:F,structureName:L,stage:w,stageSequence:V}=M,{drawId:k,drawName:W,drawType:H}=y??{},q=O?.collectionDefinitions,$=b.collectionId&&q?.find(Ne=>Ne.collectionId===b.collectionId),B=b.collectionId?$?.matchUpFormat:b.matchUpFormat??M?.matchUpFormat??y?.matchUpFormat??v?.matchUpFormat,K=b.matchUpType||$?.matchUpType||M?.matchUpType||y?.matchUpType||!ue(_e)(v?.eventType)&&v?.eventType,Q=l?Nt:b.matchUpStatus,{schedule:j,endDate:tt}=pd({scheduleVisibilityFilters:t,afterRecoveryTimes:s,tournamentRecord:p,usePublishState:g,scheduleTiming:S,drawDefinition:y,matchUpFormat:B,publishStatus:P,matchUpType:K,matchUp:b,event:v}),z=m??b.drawPositions??[],{collectionPosition:X,collectionId:lt,roundPosition:it}=b,Rt=b.roundNumber??c.roundNumber,Lt=lt?Yb({tournamentParticipants:r,positionAssignments:n,collectionPosition:X,participantMap:I,drawDefinition:y,drawPositions:z,collectionId:lt,sideLineUps:D,matchUpType:K}):void 0,De=u?.[Rt]?.roundName||c.roundName,fe=u?.[Rt]?.abbreviatedRoundName||c.abbreviatedRoundName,Re=N?.[Rt]?.feedRound,Or=N?.[Rt]?.preFeedRound,Zr=N?.[Rt]?.roundFactor,lr=o?.[Rt],Xe=it?lr?.[it]:void 0,ee=e?.[Rt],Pt=$?.category?{...R?.category||{},...$.category}:R?.category??v?.category,ae=b.processCodes?.length&&b.processCodes||$?.processCodes?.length&&$?.processCodes||M?.processCodes?.length&&M?.processCodes||y?.processCodes?.length&&y?.processCodes||v?.processCodes?.length&&v?.processCodes||p?.processCodes,re=T?.withCompetitiveness&&Iu({...h,matchUp:b}),pr=b.finishingPositionRange??c.finishingPositionRange,Jt=Ne=>ot(Ne,void 0,!0),Wt={...Jt(R),...Jt({matchUpFormat:b.matchUpType===_e?void 0:B,tieFormat:b.matchUpType!==_e?void 0:O,gender:$?.gender??v?.gender,roundOfPlay:w!==ct&&It(a)&&a+(Rt||0),endDate:b.endDate??tt,discipline:v?.discipline,category:Pt,finishingPositionRange:pr,abbreviatedRoundName:fe,drawPositionsRange:Xe,competitiveProfile:re,structureName:L,stageSequence:V,drawPositions:z,matchUpStatus:Q,processCodes:ae,isRoundRobin:E,matchUpTieId:A,preFeedRound:Or,matchUpType:K,roundFactor:Zr,roundOffset:x,structureId:F,roundNumber:Rt,feedRound:Re,roundName:De,drawName:W,drawType:H,schedule:j,drawId:k,stage:w}),...J(Jt(b),!0,!0)};if(B&&b.score?.scoreStringSide1){let Ne=Ye(B),{bestOf:_r,finalSetFormat:Je,setFormat:Ue}=Ne??{};(Je?.tiebreakSet||Ue?.tiebreakSet||Ue?.timed)&&(Wt.score.sets=Wt.score.sets.sort((Pe,ge)=>Pe.setNumber-ge.setNumber).map((Pe,ge)=>(ge+1===_r?(Je?.tiebreakSet||Je?.timed)&&(Pe.tiebreakSet=!0):(Ue?.tiebreakSet||Ue?.timed)&&(Pe.tiebreakSet=!0),Pe)))}if(Array.isArray(z)){let{orderedDrawPositions:Ne,displayOrder:_r}=jb({drawPositions:z,roundProfile:N,roundNumber:Rt}),Je=N?.[Rt]?.feedRound,Ue=_r[0]!==Ne[0],ge=Ne.concat(void 0,void 0).slice(0,2).map((Ar,fr)=>{let Bn=fr+1,ye=Ue?3-Bn:Bn,Er=qb({...Lt,positionAssignments:n,displaySideNumber:ye,seedAssignments:f,drawPosition:Ar,isFeedRound:Je,sideNumber:Bn}),Zi=b.sides?.find(Yu=>Yu.sideNumber===Bn),Tn=it?(it-1)*2+fr+1:void 0,ts=Tn?ee?.[Tn]:void 0;return Jt({sourceDrawPositionRange:ts,...Zi,...Er})});Object.assign(Wt,J({sides:ge},!0,!0))}if(r&&Wt.sides){let Ne=d?.[Vs],_r=Ue=>{let Pe=I?.[Ue]?.participant;return Pe&&Vi({template:Ne?.participant,source:Pe})};if(Wt.sides.filter(Boolean).forEach(Ue=>{if(Ue.participantId){let Pe=J(_r(Ue.participantId)||(r?Go({policyDefinitions:d,participantId:Ue.participantId,tournamentParticipants:r,internalUse:!0,contextProfile:T}):void 0),void 0,!0);if(Pe){let ge,Ar;if(y?.entries){let fr=y.entries.find(ye=>ye.participantId===Ue.participantId),Bn=v?.entries?.find(ye=>ye.participantId===Ue.participantId);ge=fr?.entryStatus||Bn?.entryStatus,Pe.entryStatus=ge,fr?.entryStage&&(Ar=fr.entryStage,Pe.entryStage=Ar)}i!==!1?Object.assign(Ue,{participant:Pe}):Object.assign(Ue,{participant:{entryStage:Ar,entryStatus:ge}})}}if(Ue?.participant?.individualParticipantIds?.length&&!Ue.participant.individualParticipants?.length){let Pe=Ue.participant.individualParticipantIds.map(ge=>_r(ge)||(r?Go({policyDefinitions:d,tournamentParticipants:r,internalUse:!0,contextProfile:T,participantId:ge}):void 0));i!==!1&&Object.assign(Ue.participant,{individualParticipants:Pe})}}),!Wt.matchUpType){let{matchUpType:Ue}=md({matchUp:Wt});Ue&&Object.assign(Wt,{matchUpType:Ue})}if(T?.inferGender&&(!Wt.gender||Wt.gender===Tr)&&Wt.sides?.length===2&&Wt.matchUpType!==_e){let Ue=Wt.sides.map(Pe=>{if(ue(Ft)(Wt.matchUpType))return Pe.participant?.person?.sex;if(Pe.participant?.individualParticipants?.length===2){let ge=ut(Pe.participant.individualParticipants.map(Ar=>Ar.person?.sex)).filter(Boolean);if(ge.length===1)return ge[0]}});if(Ue.filter(Boolean).length===2&&ut(Ue).length===1){let Pe=Ue[0];Wt.inferredGender=Pe}}}if(Wt.tieMatchUps){let Ne=Wt.matchUpStatus===Nt,_r=Wt.sides?.map(({participant:Je,drawPosition:Ue,sideNumber:Pe,lineUp:ge})=>{let Ar=Je?.participantType===_e&&Je;return{teamParticipant:Ar&&ot({participantRoleResponsibilities:Ar.participantRoleResponsibilities,participantOtherName:Ar.participanOthertName,participantName:Ar.participantName,participantId:Ar.participantId,teamId:Ar.teamId}),drawPosition:Ue,sideNumber:Pe,lineUp:ge}});Wt.tieMatchUps=Wt.tieMatchUps.map(Je=>{let Ue=Wt.matchUpId,ge={finishingPositionRange:Wt.finishingPositionRange,abbreviatedRoundName:fe,roundNumber:Rt,roundName:De};return KU({tieDrawPositions:z,scheduleVisibilityFilters:t,sourceDrawPositionRanges:e,sideLineUps:_r,drawPositionsRanges:o,initialRoundOfPlay:a,roundNamingProfile:u,additionalContext:ge,appliedPolicies:d,isCollectionBye:Ne,usePublishState:g,publishStatus:P,matchUpTieId:Ue,isRoundRobin:E,roundProfile:N,matchUp:Je,event:v,tournamentParticipants:r,positionAssignments:n,tournamentRecord:p,seedAssignments:f,participantMap:I,contextContent:h,scheduleTiming:S,contextProfile:T,drawDefinition:y,scoringActive:U,structure:M,context:R})})}let mr=Wt.sides&&Wt.sides.filter(Ne=>Ne?.participantId).length===2,zt=!Wt.winningSide;if(Object.assign(Wt,{readyToScore:U&&mr&&zt,hasContext:!0}),mr){let{allParticipantsCheckedIn:Ne,checkedInParticipantIds:_r}=us({matchUp:Wt});Object.assign(Wt,{allParticipantsCheckedIn:Ne,checkedInParticipantIds:_r})}return Array.isArray(T?.exclude)&&T?.exclude.forEach(Ne=>delete Wt[Ne]),Wt}function $b({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Wo({timeItems:r?.timeItems||[],itemType:ao});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{allocatedCourts:J(n,!1,!0)}:e}function Kb({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Wo({timeItems:r?.timeItems||[],itemType:Ho});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{courtId:n}:e}function zb({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Wo({timeItems:r?.timeItems||[],itemType:Hi});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{venueId:n}:e}function Ni(t){if(!Array.isArray(t.matchUps))return[];let{matchUps:e,excludeMatchUpStatuses:r,hasParticipantsCount:n,isCollectionMatchUp:o,matchUpStatuses:i,hasWinningSide:s,matchUpFormats:a,roundPositions:c,matchUpFormat:u,collectionIds:p,isMatchUpTie:m,roundNumbers:d,matchUpIds:l,roundNames:f,filterMatchUpTypes:g=!0,filterMatchUpIds:I=!0,stageSequences:h,scheduledDates:S,scheduledDate:T,participantIds:y,processContext:P,tournamentIds:U,matchUpTypes:A,structureIds:E,readyToScore:N,courtIds:D,eventIds:M,venueIds:R,drawIds:b,stages:v}=t,O=Array.isArray(y)?y.filter(Boolean):[],x=Array.isArray(i)?i.filter(Boolean):[],F=Array.isArray(r)?r.filter(Boolean):[],L=Array.isArray(v)?v.filter(Boolean):[],w=Array.isArray(h)?h.filter(Boolean):[],V=Array.isArray(p)?p.filter(Boolean):[],k=Array.isArray(f)?f.filter(Boolean):[],W=Array.isArray(d)?d.filter(Boolean):[],H=Array.isArray(c)?c.filter(Boolean):[],q=Array.isArray(l)&&I?l.filter(Boolean):[],$=Array.isArray(A)&&g?A.filter(Boolean):[],B=Array.isArray(D)?D.filter(Boolean):[],K=Array.isArray(R)?R.filter(Boolean):[],Q=Array.isArray(a)&&a.filter(Boolean)||typeof u=="string"&&[u]||[],j=Array.isArray(S)&&S.filter(Boolean)||typeof T=="string"&&T.length&&[T]||[],tt=Array.isArray(U)?U.filter(Boolean):[],z=Array.isArray(M)?M.filter(Boolean):[],X=Array.isArray(b)?b.filter(Boolean):[],lt=Array.isArray(E)?E.filter(Boolean):[];return e.filter(it=>{if(N&&!ue(xr)(it)&&!it.readyToScore||it.winningSide&&s&&![1,2].includes(it.winningSide)||m!==void 0&&(m&&!it.tieMatchUps||!m&&it.tieMatchUps)||o!==void 0&&(o&&!it.collectionId||!o&&it.collectionId)||L.length&&!L.includes(it.stage)||w.length&&!w.includes(it.stageSequence)||V.length&&(!it.collectionId||!V.includes(it.collectionId))||k.length&&(!it.roundName||!k.includes(it.roundName))||W.length&&(!it.roundNumber||!W.includes(it.roundNumber))||H.length&&(!it.roundPosition||!H.includes(it.roundPosition))||x.length&&(!it.matchUpStatus||!x.includes(it.matchUpStatus))||F.length&&it.matchUpStatus&&F.includes(it.matchUpStatus)||q.length&&!q.includes(it.matchUpId)||$.length&&(!it.matchUpType||!Lc($,it.matchUpType))||Q.length&&(!it.matchUpFormat||!Q.includes(it.matchUpFormat)))return!1;if(j?.length){let{scheduledTime:Rt}=mS({matchUp:it}),{scheduledDate:Lt}=Hs({matchUp:it}),fe=Et(Rt)||Lt;if(!j.find(Re=>jn(Re,fe)))return!1}if(B.length){let{courtId:Rt}=Kb({matchUp:it}),{allocatedCourts:Lt}=$b({matchUp:it}),De=Lt?.map(({courtId:fe})=>fe);if(!B.filter(Boolean).includes(Rt)||De?.includes(Rt))return!1}if(K.length){let{venueId:Rt}=zb({matchUp:it});if(!K.filter(Boolean).includes(Rt))return!1}if(P){if(tt.length&&!tt.includes(it.tournamentId)||z.length&&!z.includes(it.eventId)||X.length&&!X.includes(it.drawId)||lt.length&&!lt.includes(it.structureId))return!1;let Rt=it.sides?.map(({participantId:Lt})=>Lt).filter(Boolean)??[];if(n&&Rt.length<n||O.length&&!O.some(De=>Rt.includes(De)))return!1}return!0})}function Ut(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:mi,roundMatchUps:I,matchUps:[]};let h=Array.isArray(o?.eventIds)?o?.eventIds.filter(Boolean):[],S=Array.isArray(o?.structureIds)?o?.structureIds.filter(Boolean):[],T=Array.isArray(o?.drawIds)?o?.drawIds.filter(Boolean):[],y=!a?.eventId||!h?.length&&!n?.eventIds?.filter(Boolean).length||h?.includes(a.eventId)||n?.eventIds?.includes(a.eventId),P=!S?.length||S.includes(c.structureId),U=!s||!T?.length||T.includes(s.drawId);if(!y||!P||!U)return{collectionPositionMatchUps:g,roundMatchUps:I,matchUps:[]};i&&!d&&(d=$n({tournamentRecord:r,contextProfile:i,drawDefinition:s}));let{appliedPolicies:A}=yt({drawDefinition:s}),E={...t.tournamentAppliedPolicies,...A,...t.policyDefinitions},N=E?.scoring?.structures,D=c.stage&&N?.stage?.[c.stage],M=c.stageSequence&&D?.stageSequence?.[c.stageSequence],R=E?.scoring?.requireAllPositionsAssigned||D?.requireAllPositionsAssigned||M?.requireAllPositionsAssigned;f||(f=Me({drawDefinition:s,structure:c}));let{positionAssignments:b,allPositionsAssigned:v}=Se({structure:c}),O=!R||v,{seedAssignments:x}=on({provisionalPositioning:e,drawDefinition:s,structure:c});m=m??x;let{structureId:F}=c;l=l||s&&eS({drawDefinition:s}).exitProfiles;let L=l?.[F],w=L?.length&&(L[0].split("-").map(B=>parseInt(B)).reduce((B,K)=>B+K)||0),V=!!c.structures,k=ii({matchUpsMap:f,structureId:F,inContext:u}),W=E?.[fa],H=vb({roundNamingPolicy:W,drawDefinition:s,structure:c,matchUps:k}),{roundNamingProfile:q,roundProfile:$}=H;if(I=H?.roundMatchUps??[],o&&(k=Ni({matchUps:k,...o,filterMatchUpTypes:!1,filterMatchUpIds:!1})),u){let{sourceDrawPositionRanges:B}=Rb({drawDefinition:s,matchUpsMap:f,structureId:F}),K=s?Cb({drawDefinition:s,roundProfile:$,matchUpsMap:f,structureId:F}).drawPositionsRanges:void 0,Q=t.tournamentParticipants,j=t.participantMap;!Q?.length&&!j&&r&&({participants:Q=[],participantMap:j}=Bo({participantsProfile:t.participantsProfile,useParticipantMap:t.useParticipantMap,policyDefinitions:t.policyDefinitions,tournamentRecord:r,contextProfile:i,inContext:u})),k=k.map(z=>KU({scheduleVisibilityFilters:t.scheduleVisibilityFilters,hydrateParticipants:t.hydrateParticipants,afterRecoveryTimes:t.afterRecoveryTimes,usePublishState:t.usePublishState,scheduleTiming:t.scheduleTiming,publishStatus:t.publishStatus,sourceDrawPositionRanges:B,tournamentParticipants:Q,positionAssignments:b,drawPositionsRanges:K,initialRoundOfPlay:w,roundNamingProfile:q,tournamentRecord:r,appliedPolicies:E,seedAssignments:m,contextContent:d,participantMap:j,contextProfile:i,drawDefinition:s,scoringActive:O,isRoundRobin:V,roundProfile:$,structure:c,context:a,matchUp:z,event:p})),(k?.filter(z=>Array.isArray(z.tieMatchUps))).forEach(z=>{let X=z.tieMatchUps;k=k.concat(...X)}),n&&(k=Ni({processContext:!0,...n,matchUps:k}))}else(k?.filter(K=>Array.isArray(K.tieMatchUps))).forEach(K=>{let Q=K.tieMatchUps;k=k.concat(...Q)});return o&&(k=Ni({matchUps:k,...o,filterMatchUpTypes:!1,filterMatchUpIds:!1})),(o?.matchUpTypes||o?.matchUpIds)&&(k=Ni({matchUpTypes:o.matchUpTypes,matchUpIds:o.matchUpIds,matchUps:k})),(o?.matchUpTypes||o?.matchUpIds||u)&&(I=Ke({matchUps:k}).roundMatchUps??[]),We({drawDefinition:s,structure:c,event:p})?.tieFormat&&({collectionPositionMatchUps:g}=Mb({matchUps:k})),{collectionPositionMatchUps:g,roundMatchUps:I,isRoundRobin:V,roundProfile:$,matchUpsMap:f,matchUps:k}}function ds({matchUp:t}){return t?ce.includes(t?.matchUpStatus)||t?.winningSide:!1}function Su({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:h,matchUpsMap:S,structureId:T,inContext:y,structure:P,context:U,event:A}){!P&&T&&({structure:P}=at({drawDefinition:I,structureId:T}));let E=Ut({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:h,matchUpsMap:S,structure:P,inContext:y,context:U,event:A}),N=[],D=[],M=[],R=[],b=[];if(E.error)return E;let{matchUps:v}=E,{assignedPositions:O}=Se({structure:P}),x=O?.filter(L=>L.participantId).map(L=>L.drawPosition),F;return v.filter(L=>{let w=u?.matchUpTypes?.length===1&&u.matchUpTypes[0]===jt;return!(L.matchUpType!==jt&&w)}).forEach(L=>{if(L.matchUpStatus===vr){N.push(L);return}L.matchUpType===jt&&(F=!0);let w=L.collectionId,V=w&&L.sides?.every(K=>K.participantId),k=!w&&L.drawPositions?.filter(Boolean).length===2,W=!w&&L.drawPositions?.every(K=>x?.includes(K)),H=O?.filter(K=>K.bye).map(K=>K.drawPosition),q=!w&&L.drawPositions?.find(K=>H?.includes(K)),B=Gh.includes(L.matchUpStatus)&&(V||k&&(!t||W));return q?b.push(L):ds({matchUp:L})?D.push(L):B?M.push(L):R.push(L)}),{includesTeamMatchUps:F,abandonedMatchUps:N,completedMatchUps:D,upcomingMatchUps:M,pendingMatchUps:R,byeMatchUps:b,structure:P}}function Qb({drawDefinition:t,roundNumber:e,structureId:r}){if(!t)return{error:Z};if(!r)return{error:Ur};let{links:n}=Ws({drawDefinition:t,structureId:r}),o=n.source.reduce((s,a)=>!a.source.roundNumber||a.source.roundNumber===e?s.concat(a):s,[]),i=n.target.reduce((s,a)=>!a.target.roundNumber||a.target.roundNumber===e?s.concat(a):s,[]);return{links:{source:o,target:i}}}function fS({finishingPositions:t,linkCondition:e,linkType:r,source:n}){let o=n.find(i=>{let s=!i.source?.finishingPositions||!t||Fe(t,i.source?.finishingPositions);return e===i.linkCondition&&s&&i.linkType===r});return[fo,ro].includes(o?.linkType)&&!o?.source?.roundNumber?_({result:{error:G},stack:"getTargetLink",context:o}):o}function Ws({drawDefinition:t,structureId:e,roundNumber:r}){return t?e?{links:(t.links||[]).filter(Boolean).reduce((i,s)=>(s.source?.structureId===e&&(!r||s.source.roundNumber===r)&&(i.source=i.source.concat(s)),s.target?.structureId===e&&(!r||s.target.roundNumber===r)&&(i.target=i.target.concat(s)),i),{source:[],target:[]})}:{error:Ur}:{error:Z}}function Xb({structureMatchUps:t,matchUp:e}){let{roundNumber:r,roundPosition:n}=e,o=t.filter(s=>s.roundNumber===r&&!s.matchUpTieId),i=t.filter(s=>s.roundNumber===r+1&&!s.matchUpTieId);if(i.length){let s;return i.length===o.length?s=i.find(a=>a.roundPosition===n):i.length===o.length/2&&(s=i.find(a=>a.roundPosition===Math.ceil(n/2))),{matchUp:s}}return{message:"no progression found"}}function gS({sourceRoundMatchUpCount:t,inContextDrawMatchUps:e,sourceRoundPosition:r,drawDefinition:n,targetLink:o}){if(!o)return{error:kl};let{target:{structureId:i,feedProfile:s,groupedOrder:a,roundNumber:c,positionInterleave:u}}=o,{structure:p}=at({drawDefinition:n,structureId:i}),{positionAssignments:m}=bt({structure:p}),l=(e?.filter(D=>D.structureId===p?.structureId)).filter(D=>D.roundNumber===c&&!D.matchUpTieId),f=l.length,g=et(1,f+1),I=f/t,h=Math.ceil(I*r),S=1-r%2;if(u?.interleave&&I!==.5){let D=u.offset+(r-1)*u.interleave,M=r+D;h=Math.ceil(M/2),S=1-M%2}let T=g,y=g[h-1],P=tS({roundPositionsCount:g.length,groupedOrder:a}),U=P?.length||1;if(U<=g.length){let D=f/U,M=Ae(g,D);s===li&&M.forEach(R=>R.reverse()),T=P?.length&&P?.map(R=>M[R-1]).flat()||T}s===En?y=T[h-1]:s===li?((!P?.length||U>g.length)&&(h=l.length+1-h),y=T[h-1]):s===up&&Pr()&&console.log(tp,{feedProfile:s});let A=y&&l.reduce((D,M)=>M.roundPosition===y?M:D,void 0),E;A?.feedRound?(S=0,E=Math.min(...(A.drawPositions||[]).filter(Boolean))):E=A?.drawPositions?.length===2&&A?.drawPositions[S];let N=m?.find(({drawPosition:D})=>D===E);if(N){let{extension:D}=dt({element:N,name:Wm});if(D?.value)return{disabledDrawPosition:E}}return{matchUp:A,targetDrawPosition:E,matchUpDrawPositionIndex:S}}function ur({inContextDrawMatchUps:t=[],useTargetMatchUpIds:e,inContextMatchUp:r,drawDefinition:n,matchUpId:o}){let i=r;t.length&&!i&&(i=t.find(c=>c.matchUpId===o));let{structure:s}=at({structureId:i?.structureId,drawDefinition:n});return s?.finishingPosition===Gi?Uk({inContextDrawMatchUps:t,useTargetMatchUpIds:e,drawDefinition:n,structure:s,matchUp:i}):Pk({matchUp:i})}function Uk({inContextDrawMatchUps:t,useTargetMatchUpIds:e,drawDefinition:r,structure:n,matchUp:o}){let{winnerMatchUpId:i,loserMatchUpId:s}=o,{links:a}=Qb({roundNumber:o.roundNumber,structureId:n.structureId,drawDefinition:r}),c=a?.source,u=fS({source:c,linkType:fo}),p=fS({linkCondition:On,linkType:ro,source:c}),m=fS({source:c,linkType:ro}),d=p&&m;m||(m=p);let l=u?.target?.feedProfile,f=m?.target?.feedProfile,g=p?.target?.feedProfile,I,h,S,T,y,P,U,A,E,N;if(e&&(i||s)&&(U=i&&l!==dn&&t.find(({matchUpId:R})=>R===i),T=s&&f!==dn&&t.find(({matchUpId:R})=>R===s),U||T))return{matchUp:o,targetLinks:{loserTargetLink:m,winnerTargetLink:u},targetMatchUps:{loserMatchUp:T,winnerMatchUp:U}};let{roundPosition:D}=o;N=N||t.filter(R=>R.structureId===n.structureId);let M=N.reduce((R,b)=>b.roundNumber===o.roundNumber&&!b.matchUpTieId?R+1:R,0);return m&&!T&&f!==dn&&({matchUpDrawPositionIndex:P,targetDrawPosition:y,matchUp:T}=gS({targetLink:m,sourceRoundMatchUpCount:M,inContextDrawMatchUps:t,sourceRoundPosition:D,drawDefinition:r})),d&&g!==dn&&({matchUpDrawPositionIndex:S,targetDrawPosition:h,matchUp:I}=gS({targetLink:p,sourceRoundMatchUpCount:M,inContextDrawMatchUps:t,sourceRoundPosition:D,drawDefinition:r})),u&&!U&&l!==dn&&({matchUpDrawPositionIndex:E,targetDrawPosition:A,matchUp:U}=gS({targetLink:u,sourceRoundMatchUpCount:M,inContextDrawMatchUps:t,sourceRoundPosition:D,drawDefinition:r})),U||(N=N||t.filter(R=>R.structureId===n.structureId),{matchUp:U}=Xb({structureMatchUps:N,matchUp:o})),ot({matchUp:o,targetLinks:{loserTargetLink:m,winnerTargetLink:u,byeTargetLink:p},targetMatchUps:{winnerMatchUpDrawPositionIndex:E,loserMatchUpDrawPositionIndex:P,byeMatchUpDrawPositionIndex:S,winnerTargetDrawPosition:A,loserTargetDrawPosition:y,byeTargetDrawPosition:h,winnerMatchUp:U,loserMatchUp:T,byeMatchUp:I},targetMatchUpIds:!!(i||s)})}function Pk({matchUp:t}){return{targetLinks:{loserTargetLink:void 0,winnerTargetLink:void 0},targetMatchUps:{loserMatchUp:void 0,winnerMatchUp:void 0},matchUp:t}}function Jb({drawDefinition:t,inContextDrawMatchUps:e}){let r={};return e.forEach(n=>{let{matchUpId:o,structureId:i,drawPositions:s=[]}=n,{structure:a}=at({drawDefinition:t,structureId:i});if(a?.finishingPosition===fi){let{roundNumber:c}=n,u=c&&pt(c)+1,p=a.matchUps??[],{roundMatchUps:m}=Ke({matchUps:p});if(u&&m?.[u]){let d=[...s].sort(me).map((l,f)=>{let g=m[u].find(I=>I.drawPositions?.includes(l));return{matchUpId:g?.matchUpId,roundNumber:u,schedule:g?.schedule,sideNumber:f+1,structureName:a.structureName}});Object.assign(n,{sidesTo:d})}}else{let c=ur({useTargetMatchUpIds:!0,inContextDrawMatchUps:e,inContextMatchUp:n,drawDefinition:t,matchUpId:o}),{winnerMatchUp:u}=c.targetMatchUps,{loserMatchUp:p}=c.targetMatchUps;!n.winnerMatchUpId&&u&&(n.winnerMatchUpId=u.matchUpId),!n.loserMatchUpId&&p&&(n.loserMatchUpId=p.matchUpId);let m=zU({upcomingMatchUp:u}),d=zU({upcomingMatchUp:p});if(n.matchUpStatus!==Nt&&p?.matchUpStatus===Nt){let{matchUp:f}=Zb({matchUp:p,drawDefinition:t,inContextDrawMatchUps:e})||{};d=f&&zU({upcomingMatchUp:f})||d}let l=n.schedule?.timeAfterRecovery;if(l&&(m?.schedule?.scheduledTime&&qt(m.schedule.scheduledTime)<qt(l)&&(r[m.matchUpId]=n.matchUpId,m.schedule.scheduleConflict=n.matchUpId),d?.schedule?.scheduledTime&&qt(d.schedule.scheduledTime)<qt(l)&&(r[d.matchUpId]=n.matchUpId,d.schedule.scheduleConflict=n.matchUpId)),Object.assign(n,{winnerTo:m,loserTo:d}),n.drawPositions?.filter(Boolean).length){let g=c.targetLinks?.loserTargetLink?.linkCondition===On,I=Dk(n);if(I.length){let h=vf(u?.sides),S=vf(p?.sides),y=I.find(({participantId:A})=>h.includes(A))?[]:I,U=I.find(({participantId:A})=>S.includes(A))?[]:I;p&&g&&U.length<2&&U.push({bye:!0,tbd:!0}),y?.length&&u&&(!c.targetMatchUpIds&&u&&(u=e.find(({matchUpId:A})=>A===u.matchUpId)),u.potentialParticipants||(u.potentialParticipants=[]),u.potentialParticipants.push(y)),U?.length&&p&&(c.targetMatchUpIds||(u=e.find(({matchUpId:A})=>A===p.matchUpId)),p.potentialParticipants||(p.potentialParticipants=[]),p.potentialParticipants.push(U))}}}}),Object.keys(r).length&&e.forEach(n=>{Object.keys(r).includes(n.matchUpId)&&(n.schedule.scheduleConflict=r[n.matchUpId])}),{scheduleConflictMatchUpIds:r}}function Dk(t){return t?.sides?.map(({participant:e,participantId:r,qualifier:n})=>e||r&&{participantId:r}||n&&{qualifier:n}).filter(Boolean)||[]}function Zb({matchUp:t,drawDefinition:e,inContextDrawMatchUps:r}){let{matchUpId:n,matchUpStatus:o,structureId:i}=t||{};if(!t||!i||t?.matchUpStatus===Qt)return{matchUp:t};if(o===Nt){let s;return t.winnerMatchUpId?s=r.find(({matchUpId:a})=>a===t.winnerMatchUpId):{winnerMatchUp:s}=ur({inContextDrawMatchUps:r,drawDefinition:e,matchUpId:n})?.targetMatchUps||{},Zb({matchUp:s,drawDefinition:e,inContextDrawMatchUps:r})}return{matchUp:void 0}}function zU(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 se(t){let e="getAllDrawMatchUps";Object.assign(t,{requireParticipants:!1});let r=js(t);if(r.error)return _({result:r,stack:e});let{abandonedMatchUps:n,completedMatchUps:o,upcomingMatchUps:i,pendingMatchUps:s,byeMatchUps:a,matchUpsMap:c}=r;return{matchUps:(n??[]).concat(...o??[],...i??[],...s??[],...a??[]),matchUpsMap:c}}function js(t){if(!t?.drawDefinition)return{error:Z};let{tournamentParticipants:e,contextContent:r,matchUpsMap:n}=t,{scheduleVisibilityFilters:o,tournamentAppliedPolicies:i,requireParticipants:s,participantsProfile:a,afterRecoveryTimes:c,policyDefinitions:u,tournamentRecord:p,usePublishState:m,contextFilters:d,matchUpFilters:l,scheduleTiming:f,participantMap:g,publishStatus:I,contextProfile:h,drawDefinition:S,nextMatchUps:T,inContext:y,context:P,event:U}=t,A=[],E=[],N=[],D=[],M=[];h&&!r&&(r=$n({policyDefinitions:u,tournamentRecord:p,contextProfile:h,event:U}));let R;!e?.length&&p&&(e=p?.participants,(y||a?.withGroupings)&&e?.length&&({participantsWithGroupings:e,groupInfo:R}=du({participants:e,participantsProfile:a})));let{structures:b}=gn({drawDefinition:S});if(!b)return{error:kt};n||(n=Me({drawDefinition:S}));let v=S&&eS({drawDefinition:S}).exitProfiles;b.forEach(F=>{let{byeMatchUps:L=[],pendingMatchUps:w=[],upcomingMatchUps:V=[],completedMatchUps:k=[],abandonedMatchUps:W=[]}=Su({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:h,drawDefinition:S,exitProfiles:v,matchUpsMap:n,structure:F,context:P,event:U});A=A.concat(...W),E=E.concat(...k),N=N.concat(...V),D=D.concat(...w),M=M.concat(...L)});let O=F=>(!l&&!T&&!d||(l&&(F=Ni({matchUps:F,...l})),d&&(F=Ni({matchUps:F,...d,processContext:!0}))),F),x={abandonedMatchUps:O(A),completedMatchUps:O(E),upcomingMatchUps:O(N),pendingMatchUps:O(D),byeMatchUps:O(M),matchUpsMap:n,...C,groupInfo:R};if(T){let F=typeof T=="object"||{abandoned:!0,completed:!0,upcoming:!0,pending:!0,bye:!0},{abandoned:L,completed:w,upcoming:V,pending:k,bye:W}=F,H=[].concat(...L&&A||[],...w&&E||[],...V&&N||[],...k&&D||[],...W&&M||[]);Jb({inContextDrawMatchUps:H,drawDefinition:S})}return x}function Kn(t){let{participants:e=[],contextContent:r,participantMap:n}=t,{scheduleVisibilityFilters:o,tournamentAppliedPolicies:i,participantsProfile:s,afterRecoveryTimes:a,policyDefinitions:c,useParticipantMap:u,tournamentRecord:p,contextFilters:m,contextProfile:d,matchUpFilters:l,nextMatchUps:f,inContext:g,context:I,event:h}=t;if(!h)return{error:vt};let{eventId:S,eventName:T,endDate:y,eventType:P,category:U,gender:A,matchUpFormat:E}=h??{},N={...I,...ot({indoorOutDoor:h.indoorOutdoor??p?.indoorOutdoor,surfaceCategory:h.surfaceCategory??p?.surfaceCategory,endDate:h.endDate??p?.endDate,tournamentId:p?.tournamentId,matchUpFormat:E,eventName:T,eventType:P,category:U,eventId:S,gender:A})};y&&(N.endDate=y),d&&!r&&(r=$n({policyDefinitions:c,tournamentRecord:p,contextProfile:d,event:h}));let D;if(!e?.length&&!n&&p){let v=Bo({participantsProfile:s,useParticipantMap:u,policyDefinitions:c,tournamentRecord:p,contextProfile:d,inContext:g});n=v.participantMap,e=v.participants??[],D=v.groupInfo}let M=h.drawDefinitions??[],R=ya({tournamentRecord:p,event:h}).scheduleTiming;return{matchUps:M.flatMap(v=>{let{matchUps:O}=se({tournamentParticipants:e,tournamentAppliedPolicies:i,scheduleVisibilityFilters:o,context:N,participantsProfile:s,afterRecoveryTimes:a,policyDefinitions:c,tournamentRecord:p,contextFilters:m,contextProfile:d,drawDefinition:v,contextContent:r,matchUpFilters:l,participantMap:n,scheduleTiming:R,nextMatchUps:f,inContext:g,event:h});return O??[]}),groupInfo:D}}function Te(t){let e=rt(t,[{tournamentRecord:!0}]);if(e.error)return e;if(!t?.tournamentRecord)return{error:Y};let{participantMap:r,participants:n}=t,{scheduleVisibilityFilters:o,participantsProfile:i,afterRecoveryTimes:s,useParticipantMap:a,policyDefinitions:c,tournamentRecord:u,inContext:p=!0,contextProfile:m,matchUpFilters:d,contextFilters:l,nextMatchUps:f,context:g}=t,I=t.tournamentId??u.tournamentId,h=u?.events??[];n||({participants:n,participantMap:r}=Bo({participantsProfile:i,useParticipantMap:a,policyDefinitions:c,tournamentRecord:u,contextProfile:m,inContext:p}));let{appliedPolicies:S}=yt({tournamentRecord:u}),T={...g,tournamentId:I,indoorOutDoor:u.indoorOutdoor,surfaceCategory:u.surfaceCategory,endDate:u.endDate},y=$n({policyDefinitions:c,tournamentRecord:u,contextProfile:m});return{matchUps:h.flatMap(U=>(T.eventDrawsCount=U.drawDefinitions?.length??0,Kn({context:T,scheduleVisibilityFilters:o,tournamentAppliedPolicies:S,participantsProfile:i,afterRecoveryTimes:s,policyDefinitions:c,tournamentRecord:u,contextContent:y,contextFilters:l,contextProfile:m,matchUpFilters:d,participantMap:r,nextMatchUps:f,participants:n,inContext:p,event:U}).matchUps??[])).concat(...u.matchUps??[])}}function Un({scheduleVisibilityFilters:t,afterRecoveryTimes:e,participantsProfile:r,tournamentRecords:n,policyDefinitions:o,matchUpFilters:i,contextFilters:s,nextMatchUps:a,inContext:c}){if(typeof n!="object"||!Object.keys(n).length)return{error:xt};let p=Object.keys(n).map(m=>{let d=n[m];return Te({scheduleVisibilityFilters:t,afterRecoveryTimes:e,participantsProfile:r,policyDefinitions:o,tournamentRecord:d,matchUpFilters:i,contextFilters:s,nextMatchUps:a,inContext:c}).matchUps??[]}).flat();return{...C,matchUps:p}}function Mi(t,e){return Nk(t,e)||(t?.stageSequence||0)-(e?.stageSequence||0)||t?.roundNumber&&e.roundNumber&&t?.roundNumber-e?.roundNumber||(t?.roundPosition??0)-(e?.roundPosition??0)}function Nk(t,e){return(ks[t?.stage]||0)-(ks[e?.stage]||0)}function or(t){let{participants:e,participantMap:r,contextContent:n}=t,{scheduleVisibilityFilters:o,tournamentAppliedPolicies:i,participantsProfile:s,afterRecoveryTimes:a,policyDefinitions:c,useParticipantMap:u,tournamentRecord:p,matchUpFilters:m,contextFilters:d,contextProfile:l,drawDefinition:f,nextMatchUps:g,inContext:I,context:h,event:S}=t,{eventId:T,eventName:y,endDate:P,eventType:U,category:A,gender:E,matchUpFormat:N}=S??{},D={...h,surfaceCategory:S?.surfaceCategory??p?.surfaceCategory,indoorOutDoor:S?.indoorOutdoor??p?.indoorOutdoor,matchUpFormat:N,eventType:U,eventName:y,category:A,eventId:T,endDate:P,gender:E},M;return!e?.length&&!r&&p&&({participants:e=[],participantMap:r,groupInfo:M}=Bo({participantsProfile:s,useParticipantMap:u,policyDefinitions:c,tournamentRecord:p,contextProfile:l,inContext:I})),l&&!n&&(n=$n({policyDefinitions:c,tournamentRecord:p,contextProfile:l,drawDefinition:f,event:S})),{...se({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:S}),groupInfo:M}}function ls({element:t,accessor:e}){if(typeof e!="string")return{values:[]};let r=J(t),n=e.split("."),o=[],i;a({targetElement:r,attributes:n});let s={value:i};return o.length&&(s.values=o),s;function a({targetElement:c,attributes:u=[],significantCharacters:p}){for(let[d,l]of u.entries())if(c?.[l]){let f=u.slice(d+1);f.length?Array.isArray(c[l])?c[l].forEach(I=>a({targetElement:I,attributes:f})):(c=c[l],m({targetElement:c,index:d})):(i||(i=c[l]),o.includes(c[l])||o.push(c[l]))}function m({targetElement:d,index:l}){if(d&&l===u.length-1&&["string","number"].includes(typeof d)){let f=p?d.slice(0,p):d;i?o.includes(f)||o.push(f):(i=f,o.push(f))}}}}var QU=t=>e=>!t||typeof e!="object"?void 0:Array.isArray(t)&&t.map(r=>({[r]:ls({element:e,accessor:r})?.value}))||typeof t=="object"&&Object.keys(t).map(r=>({[r]:ls({element:e,accessor:r})?.value}))||(typeof t=="string"&&ls({element:e,accessor:t}))?.value,Br=QU;function Ea({finishingPositionOffset:t=0,finishingPositionLimit:e,positionsFed:r,roundsCount:n,roundLimit:o,matchUps:i,lucky:s,fmlc:a}){if(!Vr(i))return[];let{roundProfile:c,roundNumbers:u=[]}=Ke({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(Br("matchUpsCount")),l=(I,h)=>{let S=Math.min(...I);m&&h&&S===1&&(S=m);let T=Math.max(...I);return e&&T>e&&(T=e),[S,T]},f=c&&Object.assign({},...u.map(I=>{let h=(n??0)+1-I-p,S=c[I].matchUpsCount,T={finishingPositionRange:{},finishingRound:h},y=d?.slice(I-1).reduce((R,b)=>R+(b||0),0),P=a&&I!==1,U=1+t+(P?r??0:0),A=1,E=et(U,s?U+S*2:y+U+A),N=y+A-S,D=l(E.slice(N)),M=l(E.slice(0,N),!0);return T.finishingPositionRange={loser:D,winner:M},{[I]:T}})),g=Pr({finishingRound:!0});return i.filter(Boolean).forEach(I=>{let h=I.roundNumber&&f[I.roundNumber];g&&!h&&console.log({roundFinishingData:f,matchUp:I}),I.finishingRound=h?.finishingRound,I.finishingPositionRange=h?.finishingPositionRange}),i}function qi({inContextDrawMatchUps:t,drawDefinition:e,matchUpsMap:r}){if(!e)return{error:Z};let n={loserMatchUpIds:{},winnerMatchUpIds:{}};if(t||({matchUps:t,matchUpsMap:r}=se({inContext:!0,drawDefinition:e,matchUpsMap:r})),!r?.drawMatchUps.some(i=>i.finishingPositionRange)&&e?.structures?.length===1&&!e?.structures[0].structures){let i=r?.drawMatchUps??[];Ea({matchUps:i})}return(t??[]).filter(({collectionId:i})=>!i).forEach(i=>{let{matchUpId:s,structureId:a}=i,c=ur({inContextDrawMatchUps:t,drawDefinition:e,matchUpId:s}),{winnerMatchUp:u,loserMatchUp:p}=c.targetMatchUps,m=u?.matchUpId,d=p?.matchUpId,f=ii({matchUpsMap:r,structureId:a}).find(g=>g.matchUpId===s);if(f&&(m&&(n.winnerMatchUpIds[f.matchUpId]=m,Object.assign(f,{winnerMatchUpId:m}),Object.assign(i,{winnerMatchUpId:m})),d&&(n.loserMatchUpIds[f.matchUpId]=d,i.loserMatchUpId=d,f.loserMatchUpId=d,i.finishingPositionRange))){let g=p.finishingPositionRange&&[...i.finishingPositionRange.loser,...p.finishingPositionRange.loser],I=g&&[Math.min(...g),Math.max(...g)];i.finishingPositionRange.loser=I,f.finishingPositionRange.loser=I}}),{inContextDrawMatchUps:t,goesToMap:n}}function sn(t){let e=Nr(t),r=t.matchUps??[],n=t.drawIds??[],{includeParticipantDependencies:o,tournamentRecord:i,drawDefinition:s}=t;if(!Array.isArray(r))return{error:Jn};if(!Array.isArray(n))return{error:an};let a=t.matchUpIds?.length?t.matchUpIds:r.map(T=>T.matchUpId);if(!Array.isArray(a))return{error:rs};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(P=>(P.drawDefinitions||[]).map(U=>U.links||[])).flat(1/0),[]).filter(({linkType:T})=>T===eo),g=r;if(f.length){g=Un({nextMatchUps:!0,tournamentRecords:e}).matchUps;let T=f.reduce((y,P)=>{let U=P.source?.structureId,A=P.target?.structureId;return U&&A&&(p[A]=U),U&&!y.includes(U)&&y.push(U),y},[]);for(let y of T)c[y]=[];for(let y of g??[]){let P=y.containerStructureId||y.structureId;T.includes(P)&&c[P].push(y.matchUpId)}}let I=T=>{u[T]||(u[T]={dependentMatchUpIds:[],participantIds:[],matchUpIds:[],sources:[]},m[T]=[])},h=(T,y)=>{u[T].matchUpIds.forEach(U=>{u[y].matchUpIds.push(U)}),u[y].matchUpIds.push(T),u[T].dependentMatchUpIds.push(y),o&&u[T].participantIds.forEach(U=>u[y].participantIds.push(U))},S=T=>{let y=Object.keys(c).length;for(let P of T||[]){let{matchUpId:U,winnerMatchUpId:A,loserMatchUpId:E}=P;if(!a.length||a.includes(U)){if(I(U),o){let{individualParticipantIds:M}=uu(P);u[U].participantIds=M}A&&(I(A),h(U,A),m[A].push(U)),E&&(I(E),h(U,E),m[E].push(U)),u[U].sources.push(m[U]);let N=m[U].map(M=>u[M].sources[0]).flat(),D=m[U].map(M=>u[M].sources[1]).flat();if(u[U].sources.push(N,D),y){let M=P.containerStructureId||P.structureId,R=p[M];if(c[R])for(let b of c[R])I(b),h(b,U),m[b].push(U)}}}};if(s)qi({drawDefinition:s}),g?.length||(g=or({drawDefinition:s}).matchUps),S(g);else{if(g?.length||(g=Un({nextMatchUps:!0,tournamentRecords:e}).matchUps),!n.length){let T=d?.length?d.map(({events:y=[]})=>y.map(({drawDefinitions:P=[]})=>P.map(({drawId:U})=>U))).flat(1/0):[];T&&(n=T)}for(let T of n){let y=g?.filter(U=>U.drawId===T).sort(Mi);if(!y?.find(({roundPosition:U})=>!U)){let U=y?.find(({tournamentId:E})=>E),{drawDefinition:A}=ze({tournamentRecord:e[U?.tournamentId],drawId:T});A&&qi({drawDefinition:A})}S(y)}}return{positionDependencies:c,matchUpDependencies:u,sourceMatchUpIds:m,matchUps:g,...C}}function Ie(t){let e=t?.matchUp,r=t?.score||e?.score,n=r?.sets?.[0],{side1Score:o,side2Score:i,side1TiebreakScore:s,side2TiebreakScore:a,side1PointScore:c,side2PointScore:u}=n||{},p=o||i||s||a||c||u;return!!(r?.sets?.length>1||p)}function Ua({matchUpStatus:t}){return Fh.includes(t)}function tv({matchUpStatus:t}){return zm.includes(t)}function og({matchUpStatus:t}){return kh.includes(t)}function ig({matchUpStatus:t,winningSide:e,tieMatchUps:r,sides:n,score:o}){let i=n?.find(({participantId:c})=>c),s=r?.filter(ig)?.length;return Ie({score:o})||s||e&&i||t&&tv({matchUpStatus:t})&&![Mt,Ct,Ln].includes(t)}function Pa(t){let{drawDefinition:e,findContainer:r,structureId:n,event:o}=t,i=t.structure,s={isCollectionMatchUp:!1},{containedStructures:a}=as({drawDefinition:e}),c=n?a[n]||[]:[];if(!i){let A=at({drawDefinition:e,structureId:n});if(A.error)return A;i=r?A.containingStructure??A.structure:A.structure}if(cr({structure:i}))return{structure:i,isAdHoc:!0,error:Rs};let{matchUps:u}=se({inContext:!0,matchUpFilters:s,drawDefinition:e,event:o}),p=u?.filter(A=>A.structureId===n||c.includes(A.structureId)),{matchUpDependencies:m}=sn({drawIds:[e.drawId],matchUps:u,drawDefinition:e}),d=[],l=[],f={},g=[];for(let A of u??[]){if(A.structureId===n||c.includes(A.structureId)){l.push(...A.drawPositions??[]);let E=A.roundNumber;for(let N of(A.drawPositions??[]).filter(Boolean))(!f[N]||E&&f[N]>E)&&(f[N]=E)}ig(A)&&(g.push(A),d.push(A.matchUpId,...m?.[A?.matchUpId]?.matchUpIds||[]))}let I=ut(l.filter(Boolean)).sort(me),h=ut(d),S=ut(p?.map(({matchUpId:A,drawPositions:E})=>h.includes(A)?E:[]).flat().filter(Boolean)).sort(me),{positionAssignments:T}=bt({drawDefinition:e,structure:i}),y=T?.filter(A=>A.bye).map(A=>A.drawPosition),P=T?.filter(A=>A.qualifier).map(A=>A.drawPosition),U=I?.filter(A=>!S.includes(A))||[];return{allDrawPositions:I,inContextStructureMatchUps:p,drawPositionInitialRounds:f,activeDependentMatchUpIds:h,qualifyingDrawPositions:P,inactiveDrawPositions:U,positionAssignments:T,activeDrawPositions:S,byeDrawPositions:y,activeMatchUps:g,structure:i}}function fs({drawPosition:t,matchUps:e=[]}){return{initialRoundNumber:e.filter(({drawPositions:n})=>t&&n?.includes(t)).map(({roundNumber:n})=>n).sort(me)[0]}}var Da={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 IS=[];function Rn(t,e){Vt(t)&&(t={method:t}),(e||Pr())&&IS.push(t)}function Mk(t){let e=IS.slice();return t&&(IS.length=0),e}function ev(t){let r=Mk(t).map(n=>{let{color:o,keyColors:i,method:s,newline:a}=n,c=Object.keys(Da).includes(o)?Da[o]:Da.cyan,p=Object.keys(n).filter(d=>!["color","keyColors","method","newline"].includes(d)).map(d=>{let l=i&&Object.keys(i).includes(d)&&Da[i[d]]?Da[i[d]]:Da.brightwhite;return`${Da.white}${d}: ${l}${n[d]}`}).join(", "),m=s?.length<15?" ":" ";return[a?`
|
|
2
2
|
`:"",c,s,m,Da.white,p,Da.reset,`
|
|
3
3
|
`].join("")});r?.length&&console.log(...r)}function rv(){IS.length=0}function Hr({provisionalPositioning:t,isPositionAction:e,tournamentRecord:r,drawDefinition:n,drawPosition:o,matchUpsMap:i,structureId:s,structure:a,event:c}){if(!n)return{error:Z};if(a||({structure:a}=at({drawDefinition:n,structureId:s})),!a)return{error:kt};s||({structureId:s}=a);let u="assignDrawPositionBye";Rn({method:u,color:"cyan",drawPosition:o}),i||(i=Me({drawDefinition:n}));let{positionAssignments:p}=bt({structure:a}),{activeDrawPositions:m}=Pa({drawDefinition:n,structureId:s});if(p?.find(R=>R.drawPosition===o)?.bye)return{...C};if(m?.includes(o))return{error:qu};let f=p?.find(R=>R.drawPosition===o);if(!f)return{error:Rs};let{filled:g,containsBye:I,assignedParticipantId:h}=Rk(f);if(I)return{...C};if(g&&!I)return _({result:{error:Wa},stack:u});let S=yt({tournamentRecord:r,drawDefinition:n,event:c}).appliedPolicies??{},T=se({inContext:!0,drawDefinition:n,matchUpsMap:i}).matchUps??[],y={isCollectionMatchUp:!1},{matchUps:P}=Ut({provisionalPositioning:t,drawDefinition:n,matchUpFilters:y,matchUpsMap:i,structure:a});if(p?.forEach(R=>{R.drawPosition===o&&(R.bye=!0)}),a.structureType===Ge)return Ck({tournamentRecord:r,drawDefinition:n,drawPosition:o,matchUps:P}),bo({tournamentId:r?.tournamentId,drawDefinition:n,structure:a,event:c}),nv({assignedParticipantId:h,isPositionAction:e,appliedPolicies:S,drawDefinition:n,drawPosition:o,structureId:s,stack:u});let{roundProfile:U,roundMatchUps:A}=Ke({matchUps:P}),N=(U&&Object.keys(U).map(R=>parseInt(R)).reverse())?.find(R=>U?.[R].drawPositions?.includes(o)),D=N?A?.[N].find(({drawPositions:R})=>R?.includes(o)):void 0;D&&ov({tournamentRecord:r,drawDefinition:n,matchUp:D,event:c});let M=D?.drawPositions?.find(R=>R!==o);if(D&&M){let R=hS({sourceDrawPositions:D.drawPositions,matchUpId:D.matchUpId,inContextDrawMatchUps:T,drawPositionToAdvance:M,tournamentRecord:r,drawDefinition:n,matchUpsMap:i});if(R.error)return R}return bo({tournamentId:r?.tournamentId,drawDefinition:n,structure:a,event:c}),nv({assignedParticipantId:h,isPositionAction:e,appliedPolicies:S,drawDefinition:n,drawPosition:o,structureId:s,stack:u})}function nv({assignedParticipantId:t,isPositionAction:e,appliedPolicies:r,drawDefinition:n,drawPosition:o,structureId:i,stack:s}){return e&&cu({appliedPolicies:r,drawDefinition:n,positionAction:{removedParticipantId:t,drawPosition:o,structureId:i,name:s}}),_({result:{...C},stack:s})}function Rk(t){let e=t.bye,r=t.qualifier,n=t.participantId;return{containsBye:e,containsQualifier:r,assignedParticipantId:n,filled:e||r||n}}function ov({tournamentRecord:t,drawDefinition:e,eventId:r,matchUp:n,event:o}){Object.assign(n,{matchUpStatus:Nt,score:void 0,winningSide:void 0}),gt({tournamentId:t?.tournamentId,eventId:r??o?.eventId,context:"setMatchUpStatusBye",drawDefinition:e,matchUp:n})}function Ck({tournamentRecord:t,drawDefinition:e,drawPosition:r,matchUps:n,event:o}){n.forEach(i=>{i.drawPositions?.includes(r)&&ov({eventId:o?.eventId,tournamentRecord:t,drawDefinition:e,matchUp:i})})}function hS({drawPositionToAdvance:t,inContextDrawMatchUps:e,sourceDrawPositions:r,tournamentRecord:n,drawDefinition:o,matchUpsMap:i,matchUpId:s,event:a}){Rn({method:"advanceDrawPosition",color:"cyan",drawPositionToAdvance:t});let u=i.drawMatchUps.find(P=>P.matchUpId===s),m=e.find(P=>P.matchUpId===s)?.structureId,{structure:d}=at({drawDefinition:o,structureId:m}),{positionAssignments:l}=bt({structure:d}),f=l?.filter(P=>P.bye).map(P=>P.drawPosition),g=u?.drawPositions?.find(P=>P!==t),I=g&&f?.includes(g),{targetLinks:{loserTargetLink:h},targetMatchUps:{loserMatchUp:S,winnerMatchUp:T,loserTargetDrawPosition:y}}=ur({inContextDrawMatchUps:e,drawDefinition:o,matchUpId:s});if(T&&T.structureId===d?.structureId&&bk({drawPositionToAdvance:t,inContextDrawMatchUps:e,sourceDrawPositions:r,tournamentRecord:n,drawDefinition:o,winnerMatchUp:T,matchUpsMap:i,event:a}),S&&I&&S.structureId!==d?.structureId){let{roundNumber:P}=S;if(P===1){let U=Hr({structureId:h.target.structureId,drawPosition:y,tournamentRecord:n,drawDefinition:o,event:a});if(U.error)return U}else iv({loserTargetDrawPosition:y,tournamentRecord:n,loserTargetLink:h,drawDefinition:o,loserMatchUp:S,matchUpsMap:i,event:a})}return{...C}}function bk({drawPositionToAdvance:t,inContextDrawMatchUps:e,sourceDrawPositions:r,tournamentRecord:n,drawDefinition:o,winnerMatchUp:i,matchUpsMap:s,event:a}){let c="advanceWinner",u=s.drawMatchUps.find(L=>L.matchUpId===i.matchUpId),m=e.find(L=>L.matchUpId===i.matchUpId)?.structureId,{structure:d}=at({drawDefinition:o,structureId:m}),{positionAssignments:l}=bt({structure:d}),g=l?.find(({drawPosition:L})=>L===t)?.bye,I=u.drawPositions?.filter(Boolean),h=l?.filter(L=>I?.includes(L.drawPosition)),S=l?.find(({drawPosition:L})=>L===t),T=r?.find(L=>L!==t),P=(T&&h?.find(({drawPosition:L})=>L===T))?.bye,U=g&&P;if(U&&console.log({isByeAdvancedBye:U}),I?.length>1&&g&&!P)return _({result:{error:Wa},stack:c});let A=I?.find(L=>L!==t),E=U,N=[...(u.drawPositions||[]).filter(Boolean),void 0,void 0].slice(0,2),D=N.map(L=>!L&&!E||L===t?(E=!0,t):L).sort(me);if(!E)return console.log("@@@@@@@",{advancingAssignmentIsBye:S,drawPositionToAdvance:t,existingAssignments:h}),_({result:{error:Wa},stack:c});let M=l?.find(({drawPosition:L})=>L===A)?.bye,R=l?.find(({drawPosition:L})=>L===t)?.bye;Object.assign(u,{matchUpStatus:R||M?Nt:Qt,score:void 0,winningSide:void 0,drawPositions:D});let v=u.drawPositions.find(L=>!N.includes(L));Rn({method:c,color:"brightyellow",changedDrawPosition:v,pairedDrawPositionIsBye:M,drawPositionIsBye:R}),gt({tournamentId:n?.tournamentId,matchUp:u,eventId:a?.eventId,context:c,drawDefinition:o});let{targetLinks:{loserTargetLink:O},targetMatchUps:{loserMatchUp:x,loserTargetDrawPosition:F}}=ur({matchUpId:i.matchUpId,inContextDrawMatchUps:e,drawDefinition:o});if(M||R){let L=M?t:A;if(L)hS({drawPositionToAdvance:L,matchUpId:i.matchUpId,inContextDrawMatchUps:e,tournamentRecord:n,drawDefinition:o,matchUpsMap:s});else if(R&&O&&x)if(x.feedRound)iv({loserTargetDrawPosition:F,tournamentRecord:n,loserTargetLink:O,drawDefinition:o,loserMatchUp:x,matchUpsMap:s});else{let V=1-i.roundPosition%2,k=x.drawPositions[V],W=Hr({structureId:O.target.structureId,drawPosition:k,tournamentRecord:n,drawDefinition:o,event:a});if(W.error)return W}}}function iv({loserTargetDrawPosition:t,tournamentRecord:e,loserTargetLink:r,drawDefinition:n,loserMatchUp:o,matchUpsMap:i,event:s}){let{roundNumber:a}=o;Rn({method:"assignFedDrawPositionBye",color:"cyan",loserTargetDrawPosition:t});let p=(i?.mappedMatchUps||{})[o.structureId].matchUps,{initialRoundNumber:m}=fs({drawPosition:t,matchUps:p});if(m===a){let d=Hr({structureId:r.target.structureId,drawPosition:t,tournamentRecord:e,drawDefinition:n,event:s});if(d.error)return d}}function SS({positionAssignments:t,tournamentRecord:e,drawDefinition:r,matchUpsMap:n,structure:o,event:i}){let{matchUps:s}=Ut({drawDefinition:r,matchUpsMap:n,structure:o,event:i});s.forEach(a=>{let u=t.filter(({drawPosition:p})=>a.drawPositions?.includes(p)).filter(p=>p.bye).length;a.winningSide||(Object.assign(a,{matchUpStatus:u?Nt:Qt}),gt({tournamentId:e?.tournamentId,context:"modifyRoundRobinMatchUpsStatus",eventId:i?.eventId,drawDefinition:r,matchUp:a}))})}function lc(t){let{inContextDrawMatchUps:e,participantId:r,drawPosition:n}=t,{tournamentRecord:o,drawDefinition:i,structureId:s,matchUpsMap:a,event:c}=t,{structure:u}=at({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:Cs};r||(r=m?.participantId);let{activeDrawPositions:d}=Pa({drawDefinition:i,structureId:s});return d.includes(n)?{error:qu}:(e||({matchUps:e}=se({inContext:!0,drawDefinition:i,matchUpsMap:a})),XU({inContextDrawMatchUps:e,tournamentRecord:o,drawDefinition:i,structureId:s,drawPosition:n,matchUpsMap:a,event:c}).drawPositionCleared?(bo({tournamentId:o?.tournamentId,drawDefinition:i,structure:u,event:c}),{...C,participantId:r}):{error:vA})}function XU({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,matchUpsMap:o,structureId:i,event:s}){let{structure:a}=at({drawDefinition:r,structureId:i});if(!a)return{error:kt};let c=Se({drawDefinition:r,structure:a}).positionAssignments||[],u=c.some(T=>{if(T.drawPosition===n)return delete T.participantId,delete T.qualifier,delete T.bye,!0});if(a.structureType===Ge)return SS({positionAssignments:c,tournamentRecord:e,drawDefinition:r,matchUpsMap:o,structure:a}),{drawPositionCleared:u,...C};let p={isCollectionMatchUp:!1},{matchUps:m}=Ut({drawDefinition:r,matchUpFilters:p,matchUpsMap:o,structure:a,event:s}),{roundProfile:d,roundMatchUps:l}=Ke({matchUps:m}),g=(d&&Object.keys(d))?.map(T=>pt(T)),I=n,S=g?.map(T=>{let P=d?.[T]?.pairedDrawPositions?.find(v=>v.includes(I)),U=P?.find(v=>v!==I),A=c.find(v=>v.drawPosition===U),E=d?.[T+1],N=A?.bye,D=E?.pairedDrawPositions?.find(v=>v.includes(U)),M=N&&D&&E&&E.drawPositions?.includes(U),b=P&&{pairedDrawPositionByeAdvancedPair:!M&&D,pairedDrawPosition:U,targetDrawPosition:I,relevantPair:P,roundNumber:T};return M&&(I=U),b}).filter(T=>T?.targetDrawPosition)?.reduce((T,y)=>{let{roundNumber:P,relevantPair:U,targetDrawPosition:A,pairedDrawPosition:E,pairedDrawPositionByeAdvancedPair:N}=y,D={roundNumber:P,targetDrawPosition:A,relevantPair:U},M=N&&{roundNumber:P+1,targetDrawPosition:E,relevantPair:N,subsequentRoundRemoval:!0},R=[D,M].filter(Boolean);return T.concat(...R)},[]);return S?.forEach(({roundNumber:T,targetDrawPosition:y,relevantPair:P})=>{let U=l?.[T].find(A=>Fe(A.drawPositions?.filter(Boolean),P.filter(Boolean)));U&&(vk({inContextDrawMatchUps:t,targetDrawPosition:y,tournamentRecord:e,drawDefinition:r,structureId:i,roundNumber:T,matchUpsMap:o}),sv({inContextDrawMatchUps:t,positionAssignments:c,tournamentRecord:e,drawDefinition:r,targetMatchUp:U,drawPosition:n,matchUpsMap:o,structure:a,event:s}))}),{tasks:S,drawPositionCleared:u,positionAssignments:c}}function vk({inContextDrawMatchUps:t,targetDrawPosition:e,tournamentRecord:r,drawDefinition:n,matchUpsMap:o,roundNumber:i,structureId:s}){let{structure:a}=at({drawDefinition:n,structureId:s});if(!a)return{error:kt};if(a.structureType===Ge)return;o=o||Me({drawDefinition:n});let u=(o?.mappedMatchUps||{})[s].matchUps,{initialRoundNumber:p}=fs({drawPosition:e,matchUps:u}),m=u?.filter(l=>l.roundNumber>=i&&l.roundNumber!==p&&l.drawPositions?.includes(e)),d=bt({drawDefinition:n,structureId:s}).positionAssignments??[];return m?.forEach(l=>sv({drawPosition:e,targetMatchUp:l,inContextDrawMatchUps:t,positionAssignments:d,tournamentRecord:r,drawDefinition:n,matchUpsMap:o,structure:a})),{...C}}function sv({inContextDrawMatchUps:t,positionAssignments:e,tournamentRecord:r,drawDefinition:n,targetMatchUp:o,drawPosition:i,matchUpsMap:s,structure:a,event:c}){let u="removeDrawPosition",p=o.drawPositions?.slice(),m=o.matchUpStatus,d=o.winningSide;s=s??Me({drawDefinition:n});let f=s.mappedMatchUps[a.structureId].matchUps,{initialRoundNumber:g}=fs({drawPosition:i,matchUps:f});if(o.roundNumber&&g&&o.roundNumber>g){let D=(o.drawPositions??[]).map(M=>M===i?void 0:M);o.drawPositions=D}if(o.matchUpType===jt){let R=(t?.find(b=>b.matchUpId===o.matchUpId)?.sides??[]).reduce((b,v,O)=>v.drawPosition===i?O:b,void 0);R!==void 0&&o.sides?.[R]?.lineUp&&(delete o.sides?.[R].lineUp,gt({tournamentId:r?.tournamentId,context:`${u}-TEAM`,eventId:c?.eventId,matchUp:o,drawDefinition:n}))}let I=ur({matchUpId:o.matchUpId,inContextDrawMatchUps:t,drawDefinition:n}),{targetLinks:{winnerTargetLink:h},targetMatchUps:{loserMatchUp:S,winnerMatchUp:T,loserMatchUpDrawPositionIndex:y}}=I,U=e.filter(({drawPosition:D})=>o.drawPositions?.includes(D)).filter(D=>D.bye).length,A=U&&Nt||o.matchUpStatus&&[Mt,Ct].includes(o.matchUpStatus)&&o.matcHUpStatus||Qt;o.matchUpStatus=A,o.matchUpStatus&&[Ct,Mt].includes(o.matchUpStatus)&&(o.winningSide=void 0);let E=p?.find(D=>!o.drawPositions?.includes(D));if(p?.includes(i)&&m===o.matchUpStatus&&d===o.winningSide||(E&&Rn({method:u,color:"brightyellow",removedDrawPosition:E}),gt({tournamentId:r?.tournamentId,context:`${u}-${i}`,eventId:c?.eventId,matchUp:o,drawDefinition:n})),S&&S.structureId!==I.matchUp.structureId&&!U){let{drawPositions:D,roundNumber:M}=S;if(M===1){let R=D[y];XU({structureId:S.structureId,drawPosition:R,inContextDrawMatchUps:t,tournamentRecord:r,drawDefinition:n,matchUpsMap:s})}else{let R=Math.min(...D.filter(Boolean)),b=Ok({loserMatchUpDrawPosition:R,inContextDrawMatchUps:t,tournamentRecord:r,drawDefinition:n,loserMatchUp:S,matchUpsMap:s,event:c});if(b.error)return _({result:b,stack:u});let O=(s?.mappedMatchUps||{})[S.structureId].matchUps,{initialRoundNumber:x}=fs({drawPosition:R,matchUps:O});x===1&&(Rn({method:u,color:"brightyellow",loserMatchUpDrawPosition:R}),XU({structureId:S.structureId,drawPosition:R,inContextDrawMatchUps:t,tournamentRecord:r,drawDefinition:n,matchUpsMap:s}))}}return T&&T.structureId!==I.matchUp.structureId&&(h.target.feedProfile,dn),{...C}}function Ok({loserMatchUpDrawPosition:t,inContextDrawMatchUps:e,tournamentRecord:r,drawDefinition:n,loserMatchUp:o,matchUpsMap:i,event:s}){let{structure:a}=at({structureId:o.structureId,drawDefinition:n}),{positionAssignments:c}=bt({structure:a});if(c?.find(p=>p.drawPosition===t)?.bye){let p=lc({drawPosition:t,structureId:o.structureId,inContextDrawMatchUps:e,tournamentRecord:r,drawDefinition:n,matchUpsMap:i,event:s});if(p.error)return p}return{...C}}function Ri({drawDefinition:t,stages:e}){if(!t)return{error:Z};let r=(t?.structures??[]).filter(o=>!e?.length||o.stage&&e.includes(o.stage)),n=ut(r.map(o=>{let{positionAssignments:i}=bt({structure:o});return i?i.map(St):[]}).flat().filter(Boolean));return{...C,assignedParticipantIds:n}}function zn(t){let e=(t?.entries??[]).filter(Boolean).reduce((n,o)=>{let{entryStage:i,entryStatus:s}=o,a=`_${i||nt}${s||""}`;return n[a]||(n[a]=[]),n[a].push(o),n},{}),r=n=>isNaN(n)?1/0:n;return Object.keys(e).map(n=>e[n].sort((o,i)=>r(o.entryPosition)-r(i.entryPosition)).map((o,i)=>{let s=i+1;return{...o,entryPosition:s}})).flat()}function Ys(t){return[Ei,Gr].includes(t)}function dd({autoEntryPositions:t=!0,ignoreAssignment:e,tournamentRecord:r,drawDefinition:n,participantIds:o,entryStatus:i,entryStage:s,extension:a,eventSync:c,drawId:u,stage:p,event:m}){if(!o||!Array.isArray(o))return{error:mn,method:"modifyEntriesStatus",participantIds:o};if(!n&&!m)return{error:vt};if(i&&!VU.includes(i))return{error:zl};if(s&&!$c.includes(s))return{error:Oi};let d="modifyEntriesStatus",l=[];if(!i&&!a)return _({result:{error:st},info:"Missing entryStatus",stack:d});if(a&&!wn({extension:a,requiredAttributes:["name"]}))return _({result:{error:G},info:"Invalid extension",context:{extension:a},stack:d});let f=[];m?.drawDefinitions?.forEach(D=>{let M=Ri({stages:p&&[p],drawDefinition:D}).assignedParticipantIds??[];f.push(...M)});let g=r?.participants??[];if(!o.every(D=>{let M=Go({tournamentParticipants:g,participantId:D})?.participantType;return!(M&&[ft,yr].includes(M)&&Ys(i))&&!(i&&m?.eventType&&M===Tt&&[qr,br].includes(m.eventType)&&[nn,...Xf].includes(i))}))return{error:zl};let h=m&&Ht({event:m}).flightProfile,S=h?.flights?.find(D=>D.drawId===u),T=D=>{let M=(D||[]).filter(v=>!p||!v.entryStage||p===v.entryStage).filter(({participantId:v})=>o.includes(v)),R=v=>i&&f.includes(v.participantId)&&!(Xf.includes(v.entryStatus)&&Xf.includes(i));return M.every(v=>R(v)&&!e?!1:(i&&(v.entryStatus=i,delete v.entryPosition),s&&(v.entryStage=s,delete v.entryPosition),a&&(a.value?At({element:v,extension:a}):gr({element:v,name:a.name})),!0))?{...C}:{error:vs}},y=({flight:D,drawDefinition:M})=>{m&&(m.entries=zn({entries:m.entries??[]})),D&&(D.drawEntries=zn({entries:D.drawEntries})),M&&(M.entries=zn({entries:M.entries}))},P=D=>{let{flight:M,drawDefinition:R}=D,b="updateDrawEntries";if(M){let v=T(M.drawEntries);if(v.error)return _({result:v,stack:b})}if(R){let v=T(R.entries);if(v.error)return _({result:v,stack:b});l.includes(R.drawId)||l.push(R.drawId)}return{...C}},U=m?.entries?.find(({entryPosition:D})=>D)??(S?.drawEntries?.find(({entryPosition:D})=>D)||n?.entries?.find(({entryPosition:D})=>D));if(t&&!U&&y({flight:S,drawDefinition:n}),S||n){let D=P({flight:S,drawDefinition:n});if(D.error)return _({result:D,stack:d})}let A=m?.drawDefinitions?.map(({drawId:D})=>D)??[],E=h?.flights?.filter(D=>!A.includes(D.drawId))||[];for(let D of E){let M=D&&P({flight:D});if(M?.error)return _({result:M,stack:d})}let N=h?.flights?.length===1&&(m?.drawDefinitions?.length??0)<=h?.flights?.length;if(!S&&!n&&i&&GU.includes(i))return{error:lE};if(!S&&!n||i===so||c&&N){let D=T(m?.entries);if(D?.error)return _({result:D,stack:d});let M;if(i===so&&(h?.flights?.every(R=>{let b=T(R.drawEntries);return b.error?(M=b.error,!1):(R.drawEntries=R.drawEntries.filter(({participantId:v})=>!o.includes(v)),!0)}),m?.drawDefinitions?.every(R=>{let b=T(R.entries);return b.error?(M=b.error,!1):(R.entries=R.entries?.filter(({participantId:v})=>!o.includes(v)),!0)})),M)return _({result:{error:M},stack:d})}t&&y({flight:S,drawDefinition:n});for(let D of m?.drawDefinitions??[])l.length&&!l.includes(D.drawId)||Ot({tournamentId:r.tournamentId,eventId:m?.eventId,drawDefinition:D});return{...C}}function yo({requireTimeStamp:t,scaleAttributes:e,participant:r}){if(!r)return{error:wi};if(!ht(e))return{error:G};if(r.timeItems||(r.timeItems=[]),Array.isArray(r.timeItems)){let{accessor:n,scaleType:o,eventType:i,scaleName:s}=e,a=[hi,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!==hi)return{error:Ka};let g=(n&&ls({element:u.itemValue,accessor:n}))?.value||u.itemValue,I={eventType:d,scaleDate:u.itemDate,scaleValue:g,scaleName:l,scaleType:m};return{...C,scaleItem:I}}}return{...C,scaleItem:void 0}}function av({publishedSeeding:t,usePublishState:e,withSeeding:r,participant:n,event:o}){let i={},s=m=>[hi,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},h=yo({scaleAttributes:I,participant:n});if(h.scaleItem){f=h.scaleItem;break}}if(f&&(!e||t?.published&&!t?.published?.drawIds?.length)){let I=f.scaleValue;i.seedValue=I}}return i}function cv({convertExtensions:t,seedAssignments:e,participant:r,withSeeding:n,seedValue:o,eventId:i,ranking:s,entry:a}){let{entryStatus:c,entryStage:u,entryPosition:p,extensions:m}=a,d=m?.length&&t?Object.assign({},...Sf(m??[])):{},l=Object.assign(d,{entryPosition:p,entryStatus:c,entryStage:u,ranking:s,eventId:i});r.events[i]=ot(l,!1,!1,!0),n&&(e&&(r.events[i].seedAssignments=e),o&&(r.events[i].seedValue=o))}function TS(t){let{participantMap:e,participantId:r,matchUpStatus:n,roundPosition:o,structureId:i,matchUpType:s,roundNumber:a,matchUpId:c,potential:u,schedule:p,drawId:m,score:d}=t;if(!p||!Object.keys(p).length)return;n===Nt||e[r].scheduleItems.push({...p,scheduledDate:Et(p?.scheduledDate),scheduledTime:Kt(p?.scheduledTime),checkScoreHasValue:Ie({score:d}),matchUpStatus:n,roundPosition:o,structureId:i,matchUpType:s,roundNumber:a,matchUpId:c,potential:u,drawId:m})}function Tu(t){let e=rt(t,[{[ie]:!0}]);if(e.error)return e;let{tournamentRecord:r,status:n=Mr}=t,o=`${_o}.${xo}`;return J(Jm({tournamentRecord:r,itemType:o})?.timeItem?.itemValue?.[n],!1,!0)}function uv(t){let{tournamentId:e}=t??{};return!!e}function Xr({event:t,status:e=Mr}){let r=`${_o}.${xo}`;return lu({itemType:r,event:t})?.timeItem?.itemValue?.[e]}function ld({drawDetails:t,drawId:e}){return t?.[e]?.publishingDetail?.published}function gs(t){let{tournamentRecord:e,drawDefinition:r,eventIds:n,eventId:o,drawIds:i,drawId:s,event:a}=t??{};if(e&&!uv(e))return{error:G};if(o&&!a)return{error:jr};if(Array.isArray(n)&&n?.length){let m={};for(let d of n){if(!Vt(d))return{error:G};let l=ze({tournamentRecord:e,eventId:d})?.event;if(!l)return{error:jr};let f=JU({event:l});m[d]=f}return{...C,publishState:m}}if(a){let m=JU({event:a}),d={};if(s)return r?{publishState:{status:{published:!!m.status.publishedDrawIds?.includes(s),drawDetail:m.status.drawDetails?.[s]},...C}}:{error:Rr};if(Array.isArray(i)&&i?.length){let l=a.drawDefinitions?.map(su)??[];for(let f of i){if(!Vt(f))return{error:G};if(!l.includes(f))return{error:Rr};d[f]={status:{published:!!m.status.publishedDrawIds.includes(f),drawDetail:m.status.drawDetails?.[f]}}}}else d=m;return{...C,publishState:d}}let c=[],u=!1,p={};for(let m of e?.events??[]){let d=JU({event:m});p[m.eventId]=d,d.status.published&&(c.push(m.eventId),u=!0);for(let{drawId:l}of m.drawDefinitions??[]){let f=d.status?.publishedDrawIds?.includes(l);f&&(p[l]={status:{published:f}})}}if(e){let m=Tu({tournamentRecord:e});p.tournament=m??{},(m?.orderOfPlay?.published||m?.participants?.published)&&(u=!0),p.tournament.status={published:u,publishedEventIds:c}}return{...C,publishState:p}}function JU({event:t}){let e=Xr({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(su)||[])n[a]||(n[a]={publishingDetail:{published:!1}});let o=n&&Object.keys(n).length&&Object.keys(n).filter(a=>ld({drawDetails:n,drawId:a})),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 yu(t,e){return(t||"").localeCompare(e||"")}function pv({finishingPositionRange:t={},participantMap:e,finishingRound:r,participantWon:n,matchUpStatus:o,participantId:i,stageSequence:s,roundNumber:a,structureId:c,matchUpId:u,drawId:p,stage:m}){let d=e[i],l=S=>Math.abs(S[0]-S[1]);d.structureParticipation[c]||(d.structureParticipation[c]={rankingStage:m,walkoverWinCount:0,defaultWinCount:0,stageSequence:s,winCount:0,structureId:c,drawId:p});let f=d.structureParticipation[c],{winner:g,loser:I}=t,h=n?g:I;n&&(f.winCount+=1,o===Ct&&(f.walkoverWinCount+=1),o===Mt&&(f.defaultWinCount+=1)),h&&(!f.finishingPositionRange||l(h)<l(f.finishingPositionRange))&&(f.finishingPositionRange=h),r&&((!f.finishingRound||r<f.finishingRound)&&(f.finishingMatchUpId=u,f.finishingRound=r,f.roundNumber=a),r===1&&(f.participantWon=n))}function ZU(t){let{withScheduleItems:e,scheduleAnalysis:r,withTeamMatchUps:n,participantMap:o,withOpponents:i,withMatchUps:s,withEvents:a,withDraws:c,finishingPositionRange:u,finishingRound:p,matchUpStatus:m,stageSequence:d,roundNumber:l,structureId:f,score:g,stage:I,withRankingProfile:h,tieWinningSide:S,roundPosition:T,matchUpTieId:y,matchUpSides:P,collectionId:U,matchUpType:A,winningSide:E,matchUpId:N,schedule:D,eventId:M,drawId:R,sides:b}=t,v=i&&b?.length===2&&Object.assign({},...b.map(({sideNumber:O},x)=>{let F=b[1-x].participantId;return O&&{[O]:F}}).filter(Boolean));for(let O of b){let{participantId:x,sideNumber:F,bye:L}=O;if(L)continue;let w=E===F,V=H=>{let q=o[H]?.participant,$=q?.participantType,B=[{participantId:H,participantType:$}];if($!==yr)for(let K of q?.individualParticipantIds||[]){let Q=o[K]?.participant;B.push({participantType:Q?.participantType,participantId:K})}return B},k=(H,q)=>{if(s){if(o[H].matchUps[N]={participantWon:w,matchUpType:A,structureId:f,sideNumber:F,matchUpId:N,eventId:M,drawId:R,stage:I},i){let $=V(q);o[H].matchUps[N].opponentParticipantInfo=$}U&&(o[H].matchUps[N].collectionId=U)}i&&q&&(o[H].opponents[q]={participantId:q,matchUpId:N,eventId:M,drawId:R}),h&&pv({finishingPositionRange:u,participantMap:o,participantWon:w,finishingRound:p,matchUpStatus:m,participantId:H,stageSequence:d,roundNumber:l,structureId:f,matchUpId:N,drawId:R,stage:I}),(r||e)&&TS({participantMap:o,participantId:H,matchUpStatus:m,roundPosition:T,matchUpType:A,roundNumber:l,structureId:f,matchUpId:N,schedule:D,drawId:R,score:g})},W=({participant:H,partnerParticipantId:q})=>{let $=(B,K)=>{B&&(B.partnerParticipantIds||(B.partnerParticipantIds=[]),B.partnerParticipantIds.includes(K)||B.partnerParticipantIds.push(K))};c&&$(H?.draws?.[R],q),a&&$(H?.events?.[M],q),s&&$(H?.matchUps?.[N],q)};if(x&&o[x]){let H=v?.[F];k(x,H);let q=o[x]?.participant.participantType===ft,$=o[x]?.participant.individualParticipantIds||[];if(y){if(n){let B=K=>o[K].matchUps[y]={participantWon:S===F,matchUpId:y,matchUpType:jt,sideNumber:F};B(x),$.forEach(B)}if(c&&!o[x].draws[R]){let B=P.find(j=>j.sideNumber===F)?.participant?.participantId,K=o[B]?.draws?.[R]?.entryStatus,Q=j=>o[j].draws[R]={entryStatus:K,eventId:M,drawId:R};Q(x),$.forEach(Q)}}if(q&&($.forEach(B=>o[B]&&k(B,H)),$.forEach((B,K)=>{let Q=$[1-K],j=o[B];j&&W({participant:j,partnerParticipantId:Q})}),a&&P)){let B=P.find(K=>K.sideNumber===F)?.participant?.participantId;if(B){let K=o[B]?.events[M];K?(o[x].events[M]={...K},$.forEach(Q=>o[Q].events[M]={...K})):console.log("Missing teamEntry",{eventId:M,teamParticipantId:B})}}if(E){let B=K=>{w?(o[K].counters[A].wins+=1,o[K].counters.wins+=1,m===Ct&&(o[K].counters[A].walkoverWins+=1,o[K].counters.walkoverWins+=1),m===Mt&&(o[K].counters[A].defaultWins+=1,o[K].counters.defaultWins+=1)):(o[K].counters[A].losses+=1,o[K].counters.losses+=1,m===Ct&&(o[K].counters[A].walkovers+=1,o[K].counters.walkovers+=1),m===Mt&&(o[K].counters[A].defaults+=1,o[K].counters.defaults+=1))};B(x),$.forEach(B)}}}}function mv(t){let{participantFilters:e,convertExtensions:r,policyDefinitions:n,tournamentRecord:o,usePublishState:i,participantMap:s,contextProfile:a,withPotentialMatchUps:c,withRankingProfile:u,withScheduleItems:p,scheduleAnalysis:m,withTeamMatchUps:d,withStatistics:l,withOpponents:f,withMatchUps:g,withSeeding:I,withEvents:h,withDraws:S}=t,T=e?.participantIds,y=b=>{let v=[b];return s[b]?.participant.individualParticipantIds?.forEach(O=>v.push(O)),v.some(O=>!T?.length||T.includes(O))?v:[]},P={withMatchUps:g||u,withEvents:h||u,withDraws:S||u,withPotentialMatchUps:c,withRankingProfile:u,withScheduleItems:p,scheduleAnalysis:m,withTeamMatchUps:d,withStatistics:l,participantMap:s,withOpponents:f,withSeeding:I},U=[],A={},E=[],N={},D={},M={},R=({eventType:b,scaleNames:v,participantId:O})=>s[O]?.participant?.rankings?.[b]?.find(x=>v.includes(x.scaleName))?.scaleValue;for(let b of o?.events||[]){if(e?.eventIds&&!e.eventIds.includes(b.eventId))continue;let{drawDefinitions:v=[],extensions:O=[],eventType:x,eventName:F,category:L,entries:w,eventId:V,gender:k}=b,{flightProfile:W}=Ht({event:b}),H=W?.flights??[],q=gs({event:b}).publishState;q&&(N[V]=q);let $=q?.status?.publishedSeeding;if(h||I||u){let K=r?Object.assign({},...Sf(O??[])):{};D[V]={...K,eventName:F,eventType:x,category:L,eventId:V,gender:k};let Q=[L?.categoryName,L?.ageCategoryCode].filter(Boolean);for(let j of w){let{participantId:tt}=j;if(!tt||!s[tt])continue;let z=R({eventType:x,scaleNames:Q,participantId:tt}),X,lt;if(I){let Lt=s[tt].participant;({seedAssignments:X,seedValue:lt}=av({publishedSeeding:$,usePublishState:i,withSeeding:I,participant:Lt,event:b}))}let it=Lt=>{if(s[Lt]?.events?.[V])return;let De=s[Lt];cv({convertExtensions:r,seedAssignments:X,participant:De,withSeeding:I,seedValue:lt,eventId:V,ranking:z,entry:j})};it(tt),(s[tt].participant.individualParticipantIds||[]).forEach(it)}}let B=N?.[V]?.publishedSeeding;if(S||u||I){let K=j=>j?Object.assign({},...j.map(({participantId:tt,seedValue:z,seedNumber:X})=>({[tt]:{seedValue:z,seedNumber:X}}))):void 0,Q=ut([...v.map(su),...H.map(su)]);for(let j of Q){let tt=v.find(zt=>zt.drawId===j),z=[L?.categoryName,L?.ageCategoryCode].filter(Boolean),{structures:X=[],drawOrder:lt,drawName:it,drawType:Rt}=tt??{},Lt=H?.find(zt=>zt.drawId===j),De=tt?.entries||Lt?.drawEntries,fe=Lt?.flightNumber,Re=(tt?.structures||[]).sort((zt,pe)=>Ti(zt,pe)).map(({structureId:zt,structures:pe})=>[zt,...(pe||[]).map(({structureId:Ne})=>Ne)]).flat(1/0),Or,Zr,lr,Xe,ee=0,Pt=X.filter(({stage:zt,stageSequence:pe})=>zt===nt&&pe===1||zt===ct).flatMap(zt=>{let{positionAssignments:pe}=bt({structure:zt}),{seedAssignments:Ne,stageSequence:_r,stage:Je}=zt;return Je===nt?(ee=pe?.length??0,lr=pe,Xe=Ne):_r===1&&(Or=pe,Zr=Ne),pe}).map(({participantId:zt})=>zt).filter(Boolean),ae=K(Xe),re=K(Zr),pr=tt?De.filter(({participantId:zt})=>Pt.includes(zt)):De,Jt=!i||B?.published&&(B?.drawIds?.length===0||B?.drawIds?.includes(j));for(let zt of pr){if(!s[zt.participantId])continue;let{entryStatus:pe,entryStage:Ne,entryPosition:_r,participantId:Je}=zt,Ue=R({participantId:Je,scaleNames:z,eventType:x}),Pe=ge=>{if(!s[ge]||s[ge].draws?.[j])return;let Ar=I&&Jt,fr=Ar?{}:void 0,Bn=Ar?ae?.[Je]?.seedValue||ae?.[Je]?.seedNumber:void 0,ye=Bn?ae?.[Je]:void 0,Er=Ar?re?.[Je]?.seedValue||re?.[Je]?.seedNumber:void 0,Zi=Er?re?.[Je]:void 0;fr&&Bn&&(fr[nt]=ye),fr&&Er&&(fr[ct]=Zi);let Tn=Bn||Er;Tn&&(s[ge].participant.seedings[x]||(s[ge].participant.seedings[x]=[]),ye&&s[ge].participant.seedings[x].push({...ye,scaleName:j}),Zi&&s[ge].participant.seedings[x].push({...Zi,scaleName:j}),fr&&(s[ge].events[V].seedAssignments||(s[ge].events[V].seedAssignments={}),Object.keys(fr).forEach(ts=>s[ge].events[V].seedAssignments[ts]=fr[ts]))),(S||u)&&(s[ge].draws[j]=ot({seedAssignments:fr,entryPosition:_r,entryStatus:pe,entryStage:Ne,seedValue:Tn,eventId:V,ranking:Ue,drawId:j},!1,!1,!0))};[Gr,Ei].includes(pe)||(Pe(Je),(s[Je].participant.individualParticipantIds||[])?.forEach(Pe))}let Wt=(tt?.structures??[]).reduce((zt,pe)=>(zt.includes(pe.stage)||zt.push(pe.stage),zt),[]),mr=(tt?.links??[]).length;M[j]={qualifyingPositionAssignments:Or,qualifyingSeedAssignments:Zr,mainPositionAssignments:lr,qualifyingSeedingMap:re,mainSeedAssignments:Xe,orderedStructureIds:Re,mainSeedingMap:ae,flightNumber:fe,linksCount:mr,drawOrder:lt,drawName:it,drawType:Rt,drawSize:ee,drawId:j,stages:Wt}}}if(u||m||d||l||f||g||S){let K=!!m||c,Q=Kn({afterRecoveryTimes:!!m,policyDefinitions:n,tournamentRecord:o,inContext:!0,contextProfile:a,participantMap:s,nextMatchUps:K,event:b})?.matchUps??[];for(let j of Q){let{finishingPositionRange:tt,potentialParticipants:z,tieMatchUps:X=[],sides:lt=[],winningSide:it,matchUpType:Rt,matchUpId:Lt,eventId:De,drawId:fe,collectionId:Re,stageSequence:Or,finishingRound:Zr,matchUpStatus:lr,roundPosition:Xe,roundNumber:ee,structureId:Pt,schedule:ae,score:re,stage:pr}=j;A[Lt]=j;let Jt={finishingPositionRange:tt,finishingRound:Zr,stageSequence:Or,roundPosition:Xe,collectionId:Re,roundNumber:ee,structureId:Pt,schedule:ae,eventId:De,drawId:fe,score:re,stage:pr};ZU({...Jt,...P,matchUpStatus:lr,winningSide:it,matchUpType:Rt,matchUpId:Lt,sides:lt});for(let Wt of X){let{winningSide:mr,sides:zt=[],matchUpId:pe,matchUpStatus:Ne,matchUpType:_r}=Wt;ZU({...Jt,...P,winningSide:mr,tieWinningSide:it,matchUpTieId:Lt,matchUpId:pe,sides:zt,matchUpSides:lt,matchUpStatus:Ne,matchUpType:_r})}Array.isArray(z)&&(K||m||p)&&z.flat().map(St).filter(Boolean)?.forEach(mr=>{y(mr)?.forEach(pe=>{s[pe]&&(s[pe].potentialMatchUps[Lt]=ot({tournamentId:o?.tournamentId,matchUpId:Lt,eventId:De,drawId:fe}))}),(m||p)&&TS({potential:!0,participantMap:s,participantId:mr,matchUpStatus:lr,roundPosition:Xe,structureId:Pt,matchUpType:Rt,roundNumber:ee,matchUpId:Lt,schedule:ae,drawId:fe,score:re})})}E.push(...Q)}}if(l||u||m){let b=Object.values(s);for(let v of b){let{wins:O,losses:x,[Ft]:{wins:F,losses:L},[_t]:{wins:w,losses:V}}=v.counters,k=(W,H,q)=>{let $=H+q,B=H,K=$&&B/$;v.statistics[W]={denominator:$,numerator:B,statValue:K,statCode:W}};if(l&&(k(td,O,x),k(`${td}.${Ft}`,F,L),k(`${td}.${_t}`,w,V)),u){let W=(H=[])=>Math.abs(H[0]-H[1]);for(let H of Object.keys(v.draws)){let{orderedStructureIds:q=[],flightNumber:$}=M[H]||{};if(v.structureParticipation&&q.length){let B,K=0,Q=q.map(j=>{let tt=v.structureParticipation[j];if(!tt)return;B||(B=tt?.finishingPositionRange),W(B)>W(tt?.finishingPositionRange)&&(B=tt?.finishingPositionRange);let z=tt.stage!==ct;return z&&(K+=1),ot({...tt,participationOrder:z?K:void 0,flightNumber:$})}).filter(Boolean);v.draws[H]&&(v.draws[H].finishingPositionRange=B,v.draws[H].structureParticipation=Q)}}}if(m){let W=ht(m)?m.scheduledMinutesDifference:0,H=v.scheduleItems||[],q=v.potentialMatchUps||{},$=H.reduce((K,Q)=>{let{scheduledDate:j,scheduledTime:tt}=Q;return K[j]||(K[j]=[]),tt&&K[j].push(Q),K},{});Object.values($).forEach(K=>K.sort(XI));for(let K of H){let{typeChangeTimeAfterRecovery:Q,timeAfterRecovery:j,scheduledDate:tt,scheduledTime:z}=K,X=$[tt],lt=qt(z);for(let it of X){if(it.matchUpId===K.matchUpId||[Ct,Mt].includes(it.matchUpStatus)&&!it.checkScoreHasValue)continue;let De=K.matchUpType!==it.matchUpType&&Q||j,fe=K.drawId===it.drawId,Re=q[K.matchUpId]&&q[it.matchUpId],Or=qt(it.scheduledTime),Zr=Math.abs(Or-lt),lr=Or>=lt;if((W&&!isNaN(W)?Zr<=W:lr&&qt(it.scheduledTime)<qt(De))&&!(Re&&fe)&&lr){let ee=[K.matchUpId,it.matchUpId].sort(yu).join("|");v.scheduleConflicts[ee]={priorScheduledMatchUpId:K.matchUpId,matchUpIdWithConflict:it.matchUpId}}}}let B=v.participant.participantId;Object.keys(v.scheduleConflicts).length&&U.push(B),s[B].scheduleConflicts=v.scheduleConflicts}}}return{participantIdsWithConflicts:U,eventsPublishStatuses:N,derivedEventInfo:D,derivedDrawInfo:M,mappedMatchUps:A,participantMap:s,matchUps:E}}function Au({participantFilters:t={},tournamentRecord:e,participants:r=[]}){if(!Object.keys(t).length)return r;let{accessorValues:n,drawEntryStatuses:o,positionedParticipants:i,eventEntryStatuses:s,participantRoles:a,participantRoleResponsibilities:c,participantTypes:u,participantIds:p,signInStatus:m,enableOrFiltering:d,eventIds:l,genders:f}=t,g=qs(l)&&e?.events?.filter(y=>l?.includes(y.eventId))||e?.events||[],I=o&&_k({drawEntryStatuses:o,tournamentEvents:g}),h=s&&xk({eventEntryStatuses:s,tournamentEvents:g}),S=i!==void 0&&[!0,!1].includes(i)&&g.reduce((y,P)=>y.concat(...(P.drawDefinitions||[]).map(U=>Bh({drawDefinition:U}).allPositionedParticipantIds).filter(Boolean)),[]),T=y=>n?.reduce((P,U)=>{let{accessor:A,value:E}=U,{values:N}=ls({element:y,accessor:A});return P&&N?.includes(E)},!0);if(r=r?.filter(y=>{let P=rn({element:y,itemType:sc})?.timeItem?.itemValue,{participantRoleResponsibilities:U,participantType:A,participantRole:E,participantId:N,person:D}=y,M=Array.isArray(f)&&f?.length&&D?.sex&&f.includes(D.sex);return d?f&&M||i&&S.includes(N)||i===!1&&!S.includes(N)||I?.includes(N)||h?.includes(N)||p?.includes(N)||m&&P===m||u&&A&&qs(u)&&u.includes(A)||a&&E&&qs(a)&&a.includes(E)||c&&qs(U)&&qs(c)&&c.find(R=>U?.includes(R))||n?.length&&qs(n)&&T(y):(!f||M)&&(i===void 0||i&&S.includes(N)||i===!1&&!S.includes(N))&&(!I||I.includes(N))&&(!h||h.includes(N))&&(!p||p.includes(N))&&(!m||P===m)&&(!u||A&&qs(u)&&u.includes(A))&&(!a||E&&qs(a)&&a.includes(E))&&(!c||qs(U)&&qs(c)&&c.find(R=>U?.includes(R)))&&(!n?.length||qs(n)&&T(y))}),g.length&&l){let y=g.filter(P=>l.includes(P.eventId)).map(P=>{let U=(P.entries||[]).map(E=>E.participantId);if(ue(Yn)(P.eventType))return U;let A=(e?.participants??[]).filter(E=>U.includes(E.participantId)).map(E=>E.individualParticipantIds).flat(1);return U.concat(...A)}).flat(1);r=r?.filter(P=>y.includes(P.participantId))}return r}function qs(t){return t&&Array.isArray(t)&&t.length}function _k({drawEntryStatuses:t,tournamentEvents:e}){let r=({entryStatus:n})=>Array.isArray(t)?t.includes(n):!0;return ut(e.reduce((n,o)=>{let{flightProfile:i}=Ht({event:o}),s=i?.flights?.map(({drawEntries:c})=>Array.isArray(c)?c.filter(r).map(St):[]).flat()||[],a=o.drawDefinitions?.map(({entries:c})=>c?c.filter(r).map(St):[])||[];return n.concat(...s,...a)},[]))}function xk({eventEntryStatuses:t,tournamentEvents:e}){return ut(e.reduce((r,n)=>{let o=(n.entries||[]).filter(({entryStatus:i})=>Array.isArray(t)?t.includes(i):!0).map(St);return r.concat(...o)},[]))}function Gt(t){let{withIndividualParticipants:e,participantFilters:r={},withPotentialMatchUps:n,withRankingProfile:o,convertExtensions:i,policyDefinitions:s,withScheduleItems:a,tournamentRecord:c,scheduleAnalysis:u,withSignInStatus:p,withTeamMatchUps:m,withScaleValues:d,usePublishState:l,contextProfile:f,withStatistics:g,withOpponents:I,withMatchUps:h,internalUse:S,withSeeding:T,withEvents:y,withDraws:P,withISO2:U,withIOC:A}=t;if(!c)return{error:Y};(h||o)&&sn({tournamentRecord:c});let E=Xh({convertExtensions:i,tournamentRecord:c,withSignInStatus:p,withScaleValues:d,internalUse:S,withISO2:U,withIOC:A}),{participantMap:N}=E,D=mv({withMatchUps:h??o,withEvents:y??o,withDraws:P??o,withPotentialMatchUps:n,participantFilters:r,withRankingProfile:o,convertExtensions:i,withScheduleItems:a,policyDefinitions:s,tournamentRecord:c,scheduleAnalysis:u,withTeamMatchUps:m,usePublishState:l,withStatistics:g,participantMap:N,withOpponents:I,contextProfile:f,withSeeding:T}),{participantIdsWithConflicts:M,eventsPublishStatuses:R,derivedEventInfo:b,derivedDrawInfo:v,mappedMatchUps:O}=D,x=D.matchUps;N=D.participantMap;let F=u??n,L=({potentialMatchUps:$,scheduleConflicts:B,scheduleItems:K,participant:Q,statistics:j,opponents:tt,matchUps:z,events:X,draws:lt})=>{let it=Object.values(lt),Rt=Object.values(tt);return I&&it?.forEach(Lt=>{Lt.opponents=Rt.filter(De=>De.drawId===Lt.drawId)}),ot({...Q,scheduleConflicts:u?Object.values(B):void 0,draws:P||o?it:void 0,events:y||o?Object.values(X):void 0,matchUps:h||o?Object.values(z):void 0,opponents:I?Rt:void 0,potentialMatchUps:F?Object.values($):void 0,statistics:g?Object.values(j):void 0,scheduleItems:a?K:void 0},!1,!1,!0)},w=new Map;for(let $ of Object.keys(N))w.set($,L(N[$]));let V=[...w.values()],W=s?.[Vs]?.participant,H=Au({participants:V,participantFilters:r,tournamentRecord:c});if(e){let $=ht(e)?e:void 0;for(let B of H)for(let K of B.individualParticipantIds??[]){B.individualParticipants||(B.individualParticipants=[]);let Q=w.get(K),j=$?Vi({template:$,source:Q}):Q;B.individualParticipants.push(j)}}let q=W?H.map($=>Vi({source:$,template:W})):H;return{participantMap:t.returnParticipantMap!==!1?N:void 0,mappedMatchUps:t.returnMatchUps!==!1?O:void 0,matchUps:t.returnMatchUps!==!1?x:void 0,missingParticipantIds:E.missingParticipantIds,participantIdsWithConflicts:M,eventsPublishStatuses:R,derivedEventInfo:b,derivedDrawInfo:v,participants:q,...C}}function fc({participantId:t,drawDefinition:e,entryStatus:r,entryStage:n}){if(!e)return{error:Z};let o=e.entries?.find(i=>i.participantId===t&&(!r||r===i.entryStatus)&&(!n||n===i.entryStage));return t&&o}function Is(t){let{provisionalPositioning:e,drawDefinition:r,stageSequence:n,structureId:o,stage:i}=t;if(!r)return{error:Z};let{entryProfile:s}=fu({drawDefinition:r}),a=i&&n&&s?.[i]?.stageSequence?.[n]?.qualifiersCount||i&&s?.[i]?.qualifiersCount||0,c={};if(!o)return{qualifiersCount:a,roundQualifiersCounts:c};let{structure:u}=at({drawDefinition:r,structureId:o}),p=r.links?.filter(l=>l?.target?.structureId===u?.structureId),m=0;if(p?.length)for(let l of p){let f=at({structureId:l.source.structureId,drawDefinition:r})?.structure;if(f?.stage===ct){let g=l.source.roundNumber,I=l.target.roundNumber,h=0;if(f.structureType===Ge){let S=f.structures?.length??0,T=l.source.finishingPositions?.length??0;h=S*T}else h=Ut({matchUpFilters:{roundNumbers:[g]},structure:f,afterRecoveryTimes:!1,provisionalPositioning:e,inContext:!1}).matchUps?.length||0;c[I]||(c[I]=0),c[I]+=h,m+=h}}let d=Object.keys(c);if(d.length<=1){let l=d[0]||1;c[l]=Math.max(c[l]||0,a)}return m=Math.max(m,a),{qualifiersCount:m,roundQualifiersCounts:c}}function Rp({stage:t,drawDefinition:e}){let{entryProfile:r}=fu({drawDefinition:e});return r?.[t]?.drawSize||0}function dv(t){let{provisionalPositioning:e,drawDefinition:r,stageSequence:n,stage:o}=t,i=Rp({stage:o,drawDefinition:r}),{qualifiersCount:s}=Is({provisionalPositioning:e,drawDefinition:r,stageSequence:n,stage:o});return i&&i-s}function tP({stage:t,drawDefinition:e}){return!!(t===$e||Jf({stage:t,drawDefinition:e})&&Rp({stage:t,drawDefinition:e}))}function eP({entryStatus:t=kr,drawDefinition:e,stageSequence:r,stage:n}){if(t===nn)return Pb({stage:n,drawDefinition:e})?{positionsAvailable:1/0,...C}:{error:dE};let o=dv({drawDefinition:e,stageSequence:r,stage:n}),i=Db({drawDefinition:e,stage:n}),s=Zh({entryStatus:gu,drawDefinition:e,stage:n}),a=Zh({entryStatus:kr,drawDefinition:e,stage:n}),c=s+a,u=c>=o,p=o-c;return n!==$e&&u?{error:BI}:t===gu?s<i?{...C}:{error:BI}:{positionsAvailable:p,...C}}function fd(t){let e=rt(t,[{[Ve]:!0,[Nh]:!0}]);if(e.error)return e;let{suppressDuplicateEntries:r=!0,entryStatus:n=kr,entryStageSequence:o,entryStage:i=nt,ignoreStageSpace:s,drawDefinition:a,entryPosition:c,participant:u,roundTarget:p,extensions:m,extension:d,drawType:l,event:f}=t,g="addDrawEntry";if(l!==$r&&!tP({stage:i,drawDefinition:a}))return _({result:{error:Oi},stack:g});let I=eP({stageSequence:o,stage:i,drawDefinition:a,entryStatus:n});if(!s&&!I.success&&(!l||l!==$r))return{error:I.error};if(d&&!wn({extension:d}))return _({result:{error:G},info:"Invalid extension",context:{extension:d},stack:g});let h=t.participantId||u?.participantId;if(!h)return _({result:{error:oe},stack:g});let S=n===cs&&fc({participantId:h,drawDefinition:a,entryStatus:n}),T=i===$e&&fc({participantId:h,drawDefinition:a,entryStage:i}),y=fc({participantId:h,drawDefinition:a}),P=n!==cs&&i!==$e&&y;if(P)return r?(mt({payload:{drawId:a.drawId,eventId:f?.eventId,error:ym,participantId:h},topic:Wh}),{...C}):_({result:{error:ym},context:{participantId:h},stack:g});if(S||T)return _({context:{invalidEntry:P,invalidLuckyLoser:S,invalidVoluntaryConsolation:T},result:{error:Qu},stack:g});let U=ot({entryStageSequence:o,participantId:h,entryPosition:c,entryStatus:n,entryStage:i,extensions:m});return d&&At({element:U,extension:d}),p&&At({extension:{name:"roundEntry",value:p},element:U}),a.entries||(a.entries=[]),a.entries.push(U),Ot({drawDefinition:a}),{...C}}function lv(t){let e="addDrawEntries",{suppressDuplicateEntries:r=!0,entryStatus:n=kr,autoEntryPositions:o=!0,ignoreStageSpace:i,participantIds:s,drawDefinition:a,stageSequence:c,stage:u=nt,roundTarget:p,extension:m,event:d}=t;if(!u)return{error:YA};if(!a)return{error:Z};if(!Array.isArray(s))return{error:wr};if(!tP({stage:u,drawDefinition:a}))return{error:Oi};if(m&&!wn({extension:m}))return _({result:{error:G},info:"Invalid extension",context:{extension:m},stack:e});let l=eP({drawDefinition:a,stageSequence:c,entryStatus:n,stage:u});if(!i&&!l.success)return{error:l.error};let f=l.positionsAvailable??0;if(!i&&u!==$e&&f<s.length)return{error:Kl};let g=[],I=a.drawId,h=d?.eventId,S=s.reduce((T,y)=>{let P=n===cs&&fc({participantId:y,drawDefinition:a,entryStatus:n}),U=u===$e&&fc({entryStage:u,drawDefinition:a,participantId:y}),A=fc({participantId:y,drawDefinition:a});return n!==cs&&u!==$e&&A&&(g.push(y),r&&mt({payload:{error:ym,participantId:y,eventId:h,drawId:I},topic:Wh})),P||U?T.concat(y):T},[]);return g.length&&!r?_({context:{eventId:h,drawId:I,duplicateEntries:g},result:{error:ym},stack:e}):(s.filter(T=>T&&!S.includes(T)).forEach(T=>{let y={entryStageSequence:c,entryStage:u,participantId:T,entryStatus:n};m&&At({element:y,extension:m}),p&&At({extension:{name:Mn,value:p},element:y}),a.entries||(a.entries=[]),a.entries.push(y)}),o&&(a.entries=zn({entries:a.entries})),Ot({drawDefinition:a}),S?.length||g?.length?{info:"some participantIds could not be added",participantIdsNotAdded:S,duplicateEntries:g,...C}:{...C})}function sg({suppressDuplicateEntries:t=!0,autoEntryPositions:e=!0,entryStageSequence:r,ignoreStageSpace:n,participantIds:o,drawDefinition:i,entryStatus:s,roundTarget:a,entryStage:c,extension:u,drawId:p,event:m}){if(!o?.length)return{error:Uo};if(!m)return{error:jr};if(!p)return{error:an};let d=(m.entries||[]).map(St);if(o.filter(I=>!d.includes(I)).length)return{error:WA};if(i){let I=lv({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}=Ht({event:m}),g=f?.flights.find(I=>I.drawId===p);return g?.drawEntries&&(o.forEach(I=>{let h=s===cs&&rP({participantId:I,entryStatus:s,flight:g}),S=c===$e&&rP({participantId:I,entryStage:c,flight:g});!(s!==cs&&c!==$e&&rP({flight:g,participantId:I}))&&!h&&!S&&g.drawEntries.push({participantId:I,entryStatus:s,entryStage:c})}),e&&(g.drawEntries=zn({entries:g.drawEntries}))),{...C}}function rP({participantId:t,entryStatus:e,entryStage:r,flight:n}){let o=n.drawEntries?.find(i=>i.participantId===t&&(!e||e===i.entryStatus)&&(!r||r===i.entryStage));return t&&o}function gc({autoEntryPositions:t=!0,participantIds:e=[],entryStatuses:r,stage:n,event:o}){let i="removeEventEntries";if(!o?.eventId)return{error:vt};if(!Array.isArray(e)||e.some(m=>!Vt(m)))return _({result:{error:mn},stack:i});let s=(o.drawDefinitions??[]).flatMap(m=>Ri({drawDefinition:m}).assignedParticipantIds??[]),a=(r?.length&&o.entries?.filter(m=>m.entryStatus&&r.includes(m.entryStatus))||[]).map(St).filter(m=>!s.includes(m)),c=(n&&o.entries?.filter(m=>m.entryStage&&m.entryStage===n)||[]).map(St).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 _({result:{error:vs},stack:i});if(!e?.length)return{...C,participantIdsRemoved:[]};let u=[];o.entries=(o.entries??[]).filter(m=>{let d=!e.includes(m?.participantId);return d||u.push(m.participantId),d}),t&&(o.entries=zn({entries:o.entries}));let{flightProfile:p}=Ht({event:o});return p?.flights?.forEach(m=>{m.drawEntries=(m.drawEntries||[]).filter(d=>!e.includes(d.participantId))}),o.drawDefinitions?.forEach(m=>{m.entries=(m.entries??[]).filter(d=>!e.includes(d.participantId))}),{...C,participantIdsRemoved:u}}var nP={[er]:{policyName:"matchUpActionsDefault",enabledStructures:[{stages:[],stageSequences:[],enabledActions:[],disabledActions:[]}],participants:{enforceCategory:!0,enforceGender:!0},processCodes:{substitution:["RANKING.IGNORE","RATING.IGNORE"]},substituteAfterCompleted:!1,substituteWithoutScore:!1}},hs=nP;function Fn(t){let{suppressDuplicateEntries:e=!0,entryStatus:r=kr,autoEntryPositions:n=!0,enforceGender:o=!0,entryStageSequence:i,policyDefinitions:s,entryStage:a=nt,tournamentRecord:c,ignoreStageSpace:u,drawDefinition:p,roundTarget:m,extensions:d,extension:l,drawId:f,event:g}=t,I="addEventEntries";if(!Array.isArray(t.participantIds))return _({result:{error:wr},stack:I});let h=ut(t.participantIds??[]);if(!g)return{error:vt};if(!h?.length)return _({result:{error:Uo},stack:I});if(!g?.eventId)return{error:jr};let S=yt({tournamentRecord:c,event:g}).appliedPolicies??{},T=s?.[er]??S?.[er]??hs[er],y=(o??T?.participants?.enforceGender)!==!1,P=[],U=[];if(d&&(!Array.isArray(d)||!d.every(x=>wn({extension:x})))||l&&!wn({extension:l}))return _({context:ot({extension:l,extensions:d}),result:{error:G},info:"Invalid extension(s)",stack:I});let A=!!c,E=[],N,D=c?.participants?.filter(x=>{if(!h.includes(x.participantId))return!1;let F=ue(Ft)(g.eventType)&&x.participantType===Tt&&!Ys(r),L=g.eventType===_t&&x.participantType===ft;return F&&(!g.gender||!y||[Tr,Pn].includes(g.gender)||g.gender===x.person?.sex)||L&&!Ys(r)||g.eventType===_t&&x.participantType===Tt&&Ys(r)?!0:F&&g.gender&&y&&![Tr,Pn].includes(g.gender)&&g.gender!==x.person?.sex?(E.push({participantId:x.participantId,sex:x.person?.sex}),!1):g.eventType===wt&&(x.participantType===wt||Ys(r)&&x.participantType===Tt)}).map(x=>x.participantId)??[],M=h.filter(x=>!A||D.includes(x));g.entries||(g.entries=[]);let R=g.entries.map(x=>x.participantId||x.participant?.participantId);if(M.forEach(x=>{if(!R.includes(x)){let F=ot({participantId:x,entryStatus:r,entryStage:a,extensions:d});l&&At({element:F,extension:l}),m&&At({extension:{name:Mn,value:m},element:F}),i&&(F.entryStageSequence=i),P.push(F.participantId),g.entries?.push(F)}}),f&&!Ys(a)){let x=sg({participantIds:M,suppressDuplicateEntries:e,autoEntryPositions:n,entryStageSequence:i,ignoreStageSpace:u,drawDefinition:p,entryStatus:r,roundTarget:m,entryStage:a,extension:l,drawId:f,event:g});x.error&&(N=x.error)}if(g.eventType&&[ko,br].includes(g.eventType)){let x=(g.entries||[]).map(k=>k.participantId),F=(g.entries||[]).filter(k=>Ys(k.entryStatus)).map(k=>k.participantId),w=(c?.participants??[]).filter(k=>x.includes(k.participantId)&&k.participantType&&[ft,wt].includes(k.participantType)).map(k=>k.individualParticipantIds).flat(1/0),V=F.filter(k=>w.includes(k));V.length&&(U.push(...V),gc({participantIds:V,autoEntryPositions:!1,event:g}))}if(M.length!==h.length)return _({context:{mismatchedGender:E,gender:g.gender},result:{error:wr},stack:I});n&&(g.entries=zn({entries:g.entries||[]}));let v=P.length,O=U.length;return _({result:{...C,addedEntriesCount:v,removedEntriesCount:O},stack:I,info:N})}var oP="ADMINISTRATION",wk="CAPTAIN",Lk="COACH",xe="COMPETITOR",iP="MEDIA",sP="MEDICAL",ag="OFFICIAL",aP="OTHER",cP="SECURITY",gd={ADMINISTRATION:oP,CAPTAIN:wk,COACH:Lk,COMPETITOR:xe,MEDIA:iP,MEDICAL:sP,OFFICIAL:ag,OTHER:aP,SECURITY:cP};function cg({addIndividualParticipantsToEvents:t,individualParticipantIds:e,groupingParticipantId:r,tournamentRecord:n,suppressErrors:o}){let i="removeIndividualParticipantIds";if(!n)return _({result:{error:Y},stack:i});if(!r||!e)return _({result:{error:st},stack:i});let a=(n.participants??[]).find(m=>m.participantId===r);if(!a)return _({result:{error:te},stack:i});if(![wt,zr].includes(a.participantType))return _({result:{participantType:a.participantType,error:An},stack:i});let c=fv({individualParticipantIds:e,groupingParticipant:a,tournamentRecord:n,suppressErrors:o}),{removed:u,error:p}=c;if(p)return _({result:c,stack:i});if(t)for(let m of n.events??[]){let d=(m.entries??[]).map(({participantId:l})=>l).filter(Boolean);if(d.includes(r)){let l=u?.filter(f=>!d.includes(f));Fn({participantIds:l,entryStatus:Gr,tournamentRecord:n,event:m})}}return u&&mt({topic:nr,payload:{tournamentId:n.tournamentId,participants:[a]}}),{...C,...c}}function fv({individualParticipantIds:t=[],groupingParticipant:e,tournamentRecord:r,suppressErrors:n,mappedMatchUps:o,participants:i}){let s=[];if(!e)return{removed:s};let a=[],c=[];i||({participants:i,mappedMatchUps:o}=Gt({withMatchUps:!0,tournamentRecord:r,withEvents:!0}));let p=i?.find(({participantId:l})=>l===e.participantId)?.events?.map(({eventId:l})=>l),m=(e.individualParticipantIds??[]).filter(l=>{let f=t?.includes(l),g=f&&i?.find(h=>h.participantId===l)?.matchUps.filter(({eventId:h})=>p.includes(h)).map(({matchUpId:h})=>o?.[h]).filter(({winningSide:h,score:S})=>h||Ie({score:S})),I=f&&!g?.length;if(f&&!I&&c.push(l),I){s.push(l);for(let h of r.events??[])for(let S of h.drawDefinitions??[]){let{extension:T}=dt({element:S,name:Ro}),y=T?.value[e.participantId];T&&y&&(T.value[e.participantId]=y.filter(U=>U.participantId!==l),At({element:S,extension:T}),Ta({drawDefinition:S}));let P=or({drawDefinition:S,inContext:!1}).matchUps??[];for(let U of P){let A=U.sides??[];for(let E of A){let N=E.lineUp??[];N.find(M=>M.participantId===l)&&(E.lineUp=N.filter(M=>M.participantId!==l),gt({tournamentId:r?.tournamentId,drawDefinition:S,matchUp:U}))}}}}else a.push(l);return!I});e.individualParticipantIds=m;let d={groupingParticipantId:e.participantId,cannotRemove:c,notRemoved:a,removed:s};return c.length&&!n&&{...d,cannotRemove:c,error:zu}||d}function Cp({participantRole:t=xe,individualParticipantIds:e=[],groupingTypes:r=[yr,zr],tournamentRecord:n}){if(!n)return{error:Y};let o=n.participants??[],{participants:i,mappedMatchUps:s}=Gt({withMatchUps:!0,tournamentRecord:n,withEvents:!0}),a=0;return o.filter(c=>(c.participantRole===t||!c.participantRole)&&c.participantType&&r.includes(c.participantType)).forEach(c=>{let{removed:u}=fv({groupingParticipant:c,individualParticipantIds:e,tournamentRecord:n,mappedMatchUps:s,participants:i});u&&a++}),a?C:{error:cE}}function $i(t){let e=rt(t,[{[ie]:!0},{participantIds:!0,[He]:Be,[fn]:Uo}]);if(e.error)return e;let{addIndividualParticipantsToEvents:r,tournamentRecord:n,participantIds:o}=t,i=n.participants?.length||0;if(!i)return{...C};let s=(n.events||[])?.filter(({eventType:f})=>f===_e).map(f=>f?.drawDefinitions?.map(({drawId:g})=>g)).flat(1/0),a=Gt({participantFilters:{participantIds:o},tournamentRecord:n,withDraws:!0}).participants??[],c=f=>{let I=(Te({matchUpFilters:{drawIds:f,matchUpTypes:[_t]},tournamentRecord:n}).matchUps??[]).flatMap(({sides:h})=>h?.map(({participantId:S})=>S||[])).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:vs};let m={},d={};for(let f of n.events||[]){let g=gc({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===ft&&f.individualParticipantIds?.some(I=>o.includes(I));if(!g&&f.participantType===_e&&f.individualParticipantIds?.some(I=>o.includes(I))&&(f.individualParticipantIds=f.individualParticipantIds.filter(I=>!o.includes(I))),g&&r&&f.participantType&&[ft,wt].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(Cp({individualParticipantIds:o,tournamentRecord:n}),r)for(let f of n.events||[]){let I=m[f.eventId].map(h=>d[h]||[]).flat();Fn({participantIds:I,entryStatus:Gr,tournamentRecord:n,event:f})}return l&&mt({payload:{participantIds:o,tournamentId:n.tournamentId},topic:wf}),l?{...C,participantsRemovedCount:l}:{error:zu}}function yS({selected:t=!0,drawDefinition:e,entryStatuses:r,drawId:n,event:o,stage:i}){let s=o.entries??[];if(n){let{flightProfile:c}=Ht({event:o}),u=c?.flights?.find(p=>p.drawId===n);u?s=u.drawEntries:e.entries&&(s=e?.entries)}let a=s.filter(c=>(!r?.length||!c.entryStatus||r.includes(c.entryStatus))&&(!i||!c.entryStage||c.entryStage===i)&&(!t||c.entryStatus&&Qr.includes(c.entryStatus)));return{entries:s,stageEntries:a}}function uP({removeGroupParticipant:t,tournamentRecord:e,drawDefinition:r,participantId:n,drawId:o,stage:i,event:s}){let a="destroyGroupEntry";if(!e)return{error:Y};if(!n)return _({result:{error:oe},stack:a});if(!s)return{error:vt};if(!s.eventType||![ko,br].includes(s.eventType))return _({result:{error:Hn},stack:a});let c=e.participants??[],u=c.find(S=>S.participantId===n);if(!u)return _({result:{error:te},stack:a});if(!u.participantType||![ft,yr].includes(u.participantType)||u.participantType===yr&&s.eventType!==br||u.participantType===ft&&s.eventType!==ko)return{error:An};let m=(s.entries??[]).find(S=>S.participantId===n);if(!m)return{error:VI};let{stageEntries:d}=yS({selected:!1,drawDefinition:r,drawId:o,event:s,stage:i}),l=d.map(St),f=c.filter(({participantId:S})=>l.includes(S)).map(({individualParticipantIds:S})=>S).flat().filter(Boolean),g=u.individualParticipantIds?.filter(S=>mo(S,f).length===1),I=gc({participantIds:[n],event:s});if(I.error||g?.length&&(I=Fn({participantIds:g,entryStatus:Gr,entryStage:m.entryStage,tournamentRecord:e,drawDefinition:r,drawId:o,event:s}),I.error))return I;let h;return t&&$i({participantIds:[n],tournamentRecord:e}).success&&(h=!0),{...C,participantRemoved:h}}function ug({removeGroupParticipant:t,tournamentRecord:e,drawDefinition:r,participantId:n,drawId:o,event:i}){return uP({removeGroupParticipant:t,tournamentRecord:e,drawDefinition:r,participantId:n,drawId:o,event:i})}function pP(t){if(!t.tournamentRecord)return{error:Y};let{participantIds:e,...r}=t,n=0,o=[];for(let i of e){let s=uP({participantId:i,...r});s.success&&(n+=1),s.error&&o.push(s.error)}return n?{destroyedCount:n,...C}:{error:o}}function Eu(t){let{tournamentRecord:e,replaceWithBye:r,drawDefinition:n,destroyPair:o,entryStatus:i,matchUpsMap:s,drawId:a}=t,c="removeDrawPositionAssignment",u=lc(t);if(u.error)return _({result:u,stack:c});let{participantId:p}=u,{drawPosition:m,event:d,structureId:l}=t,f=yt({tournamentRecord:e,drawDefinition:n,event:d}).appliedPolicies??{};if([nn,so].includes(i)&&p){let{tournamentRecord:h}=t,{participant:S}=To({tournamentRecord:h,participantId:p}),{participantType:T,individualParticipantIds:y}=S??{};if(o&&T===ft){let P=ug({tournamentRecord:h,drawDefinition:n,participantId:p,event:d});if(P.error)return _({result:P,stack:c});y&&dd({participantIds:y,tournamentRecord:h,drawDefinition:n,entryStatus:i,drawId:a,event:d})}else dd({participantIds:[p],tournamentRecord:h,drawDefinition:n,entryStatus:i,drawId:a,event:d})}if(r){let h=Hr({tournamentRecord:e,drawDefinition:n,drawPosition:m,structureId:l,matchUpsMap:s,event:d});if(h.error)return _({result:h,stack:c})}let{structure:g}=at({drawDefinition:n,structureId:l});return Xm({structure:g,drawPositions:[m]}),cu({appliedPolicies:f,drawDefinition:n,positionAction:{name:"removeDrawPositionAssignment",replaceWithBye:r,drawPosition:m,entryStatus:i,structureId:l}}),u}function mP(t){return Object.assign(t,{entryStatus:so}),Eu(t)}function AS(t){return Vt(t)?t.split(" ").map(e=>e.split("").map((r,n)=>n?r.toLowerCase():r.toUpperCase()).join("")).join(" "):t}function Qe(t){return Vt(t)?AS(t.replace(/_/g," ")):""}var Ss=({finishingPosition:t=Gi,qualifyingRoundNumber:e,structureAbbreviation:r,seedAssignments:n=[],stageSequence:o=1,structureOrder:i,seedingProfile:s,matchUpFormat:a,structureType:c,structureName:u,matchUpType:p,matchUps:m=[],structureId:d,roundOffset:l,roundLimit:f,stageOrder:g,structures:I,stage:h})=>{let S={structureId:d??Dt(),structureAbbreviation:r,finishingPosition:t,seedAssignments:n,matchUpFormat:a,stageSequence:o,structureName:u};i&&(S.structureOrder=i),c&&(S.structureType=c),s&&(typeof s=="string"?S.seedingProfile=s:typeof s=="object"&&typeof s.positioning=="string"&&(S.seedingProfile=s.positioning)),p&&(S.matchUpType=p),l&&(S.roundOffset=l),g&&(S.stageOrder=g),f&&(S.roundLimit=f),h&&(S.stage=h),e&&(S.qualifyingRoundNumber=e);let T=m.flatMap(({drawPositions:y})=>y).filter(Boolean);return I?S.structures=I:(S.matchUps=m,S.positionAssignments=ut(T).sort((y,P)=>y-P).map(y=>({drawPosition:y}))),S},hn=Ss;function pg({structureName:t=Qe($e),structureAbbreviation:e,drawDefinition:r,matchUpType:n,structureId:o}){if(!r)return{error:Z};let i=hn({stage:$e,structureAbbreviation:e,structureName:t,matchUps:[],structureId:o,matchUpType:n});return r.structures||(r.structures=[]),r.structures.push(i),Ot({drawDefinition:r,structureIds:[i.structureId]}),{...C}}function mg({drawPositions:t}){if(!t?.length)return{error:ja};let e=o=>t.filter(i=>i!==o).map(i=>[o,i]),r=[].concat(...(t??[]).map(e)),n=ut(r.map(dg)).map(o=>o.split("|").map(i=>+i));return{groupMatchUps:r,uniqueMatchUpGroupings:n}}function dg(t=[]){return!Array.isArray(t)||!t.length?"":[...t].sort(me).join("|")}function dP({groupSize:t,drawPositionOffset:e}){if(!t)return[];let r=m=>[...Array(m)].map((d,l)=>l),n=r(2*Math.round(t/2)+1).slice(1),o=r(n.length-1).map(()=>[]),i=n.slice(0,n.length/2),s=n.slice(n.length/2);n.slice(1).forEach((m,d)=>{i.forEach((I,h)=>{o[d].push([i[h],s[h]])});let l=i.shift(),f=i.pop(),g=s.shift();i=[l,g,...i].filter(Boolean),s=[...s,f].filter(Boolean)});let a=i.shift(),c=i.pop(),u=s.shift();i=[a,u,...i].filter(Boolean),s=[...s,c].filter(Boolean);let p=m=>m[0].reduce((d,l)=>d+l);return[...o].reverse().sort((m,d)=>p(m)-p(d)).map(m=>m.filter(d=>d.every(l=>l<=t)).map(d=>{let l=d.map(f=>f+e);return dg(l)}))}function Fk({rounds:t,hash:e}){return t?.length?t?.reduce((r,n,o)=>n.includes(e)?o+1:r,void 0):{error:st}}var gv={getRoundRobinGroupMatchUps:mg,determineRoundNumber:Fk,drawPositionsHash:dg,groupRounds:dP};function Na(t){let{groupNameBase:e="Group",playoffAttributes:r,stageSequence:n=1,structureOptions:o,appliedPolicies:i,seedingProfile:s,stage:a=nt,matchUpType:c,roundTarget:u,structureId:p,groupNames:m,drawSize:d,idPrefix:l,isMock:f,uuids:g}=t,I=t.structureName??r?.["0"]?.name??Qe(nt),{groupCount:h,groupSize:S}=kk({structureOptions:o,appliedPolicies:i,drawSize:d}),T=fi,y,P=et(1,h+1).map(A=>{let E=Gk({groupSize:S,structureOrder:A,matchUpType:c,drawSize:d,idPrefix:l,isMock:f});y=Array.isArray(E)?Math.max(...E.map(({roundNumber:D})=>D??0)):0;let N=m?.[A-1]??`${e} ${A}`;return Ss({structureId:g?.pop(),structureType:cp,finishingPosition:T,structureOrder:A,structureName:N,matchUps:E})}),U=Ss({structureId:p??g?.pop(),structureType:Ge,finishingPosition:T,seedingProfile:s,structureName:I,stageSequence:n,structures:P,stage:a});return u&&At({extension:{name:Mn,value:u},element:U}),{structures:[U],maxRoundNumber:y,groupCount:h,links:[],groupSize:S,...C}}function kk({appliedPolicies:t,structureOptions:e,drawSize:r}){let n=e?.groupSize,o=e?.groupSizeLimit||8,{validGroupSizes:i}=bp({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 bp(t){let{groupSizeLimit:e=10,drawSize:r=0}=t??{},n=et(3,e+1).filter(o=>{let i=Math.ceil(r/o),s=i*o-r,a=Math.ceil(r/i),c=Math.ceil(s/i);return(!s||s<o)&&a===o&&a>=3&&c<2});return{...C,validGroupSizes:n}}function Gk({structureOrder:t,matchUpType:e,groupSize:r,drawSize:n,idPrefix:o,isMock:i,uuids:s}){let a=(t-1)*r,c=et(1+a,r+1+a),u=mg({drawPositions:c}).uniqueMatchUpGroupings??[],p=dP({groupSize:r,drawPositionOffset:a});return u.map(l).sort((f,g)=>(f.roundNumber??1/0)-(g.roundNumber??1/0));function d(f){return p.reduce((g,I,h)=>I.includes(f)?h+1:g,void 0)}function l(f){let g=dg(f),I=d(g),h=[1,n],S=Vk({structureOrder:t,drawPositions:f,roundNumber:I,idPrefix:o,uuids:s}),T={matchUpStatus:I?Qt:Nt,matchUpType:e,finishingPositionRange:{winner:h,loser:h},drawPositions:f,roundNumber:I,matchUpId:S};return i&&(T.isMock=!0),T}}function Vk({structureOrder:t,drawPositions:e,roundNumber:r,idPrefix:n,uuids:o}){return n?`${n}-${t}-${r}-DP-${e.join("-")}`:o?.pop()||Dt()}function lg(t){let{roundRobinGroupsCount:e,participantsCount:r,cluster:n}=t;if(!It(r))return{seedBlocks:void 0,..._({result:{error:G},context:{participantsCount:r},stack:"getSeedBlocks"})};let o=es(r);if(e){let l=Math.min(e,o),f=[],g=1;for(et(0,l).forEach(()=>{f.push([g]),g++});g<o;){let I=et(g,g+l);g+=l,f.push(I)}return{...C,seedBlocks:f}}let i=et(1,o+1),s=[],a=o/2;for(;a>1;){let l=Ae(i,a),f=l.length;l.forEach((g,I)=>{let h,S=I<f/2,T=I%2===0,y=g[0],P=g[g.length-1];n&&f>4?f===8?h=S?P:y:h=T?y:P:h=S?y:P,Fe(g,s)||s.push(h)}),a=a/2}let c=i.filter(l=>!s.includes(l));for(;c.length;)c.length%2===0?s.push(c.pop()):s.push(c.shift());let u=et(0,20).map(l=>Math.pow(2,l));u.unshift(1);let p=u.indexOf(o),m=0,d=[];return et(0,p).forEach(l=>{d.push(s.slice(m,m+u[l])),m+=u[l]}),{...C,seedBlocks:d}}function fg({roundRobinGroupsCount:t,drawSize:e}){let r="getSeedGroups";if(!It(e))return{seedGroups:void 0,..._({result:{error:G},context:{drawSize:e},stack:r})};if(t){if(!It(t))return{seedGroups:void 0,..._({context:{roundRobinGroupsCount:t},result:{error:G},stack:r})};let n=1,o=Math.floor(e/t);return{seedGroups:et(0,o).map(()=>{let s=et(n,n+t);return n+=t,s})}}else{let{seedBlocks:n}=lg({participantsCount:e,roundRobinGroupsCount:t}),o=0;return{seedGroups:(n||[]).map(s=>(s||[]).map(()=>(o+=1,o)))}}}function ES({roundRobinGroupsCount:t,participantsCount:e}){if(t){let{validGroupSizes:o}=bp({drawSize:e});if(!o?.map(a=>Math.ceil(e/a))?.includes(t))return _({context:{roundRobinGroupsCount:t},result:{error:G}})}let{seedGroups:r}=fg({drawSize:e,roundRobinGroupsCount:t}),n=r?.map(o=>Math.min(...o))||[];return{...C,seedingThresholds:n}}function Ic(t){if(!t)return 1/0;if(It(t))return pt(t);let e=t.split("-")[0];return It(e)?pt(e):1/0}function Bk({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(me),e.reverse(),e}function Iv({blockPattern:t,index:e}){let r=0;for(let n of t){if(r===e)return n;let o=0;for(;o<n.length;){if(r===e)return n;r+=1,o++}}}function hv({positioning:t,size:e}){let r=Bk({size:e}),n=[],o=[],i=d=>d[0],s=d=>d[d.length-1],a=(d,l)=>(t&&[Kc,di].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=et(1,e+1);for(let d of r)if(d===1){let l=Ae(m,2),f=l.map(c).filter(Boolean);f.length&&n.push(f);let g=l.flatMap(u).filter(Boolean);g.length&&n.push(g)}else{let f=Ae(m,d).map(p).filter(Boolean);f.length&&n.push(f)}return{divisions:r,divisionGroupings:n}}function Ts({provisionalPositioning:t,returnAllProxies:e,appliedPolicies:r,seedingProfile:n,drawDefinition:o,allPositions:i,structure:s}){let a=[];if(!s)return{error:mi};let{matchUps:c,roundMatchUps:u}=Ut({matchUpFilters:{roundNumbers:[1]},provisionalPositioning:t,structure:s}),{seedAssignments:p}=on({provisionalPositioning:t,returnAllProxies:e,drawDefinition:o,structure:s}),{positionAssignments:m}=Se({structure:s}),d=m?.length,l=p?.length??0,f=[],I=Object.keys(u).map(L=>parseInt(L)).sort((L,w)=>L-w).map(L=>{let w=u[L].map(k=>k.drawPositions).flat(1/0).filter(Boolean),V=w.filter(k=>!f.includes(k));return f=f.concat(...w),V}).filter(L=>L.length).reverse(),h=I.pop()??[],S=h&&Math.min(...h)-1||0;n=n??r?.seeding?.seedingProfile;let T=h?.length||0,y=I.filter(L=>L.filter(w=>w<=l).length),{stage:P,structureType:U,roundLimit:A}=s,E=U===Ge,N=!E&&I?.length,D=!E&&P===ct&&A,M=y.flat(1/0),R=N?M?.length:0,b=i?d:l,v=id({drawDefinition:o,structure:s,matchUps:c}),O=v?0:!N&&b||b&&M.length<b&&b-M.length||0;if(D){let L=s?.matchUps?s.matchUps.filter(({roundNumber:V})=>V===s.roundLimit).length:0,w=h.length/L;if(!N){let V=Op(n),k=Ae(h,w),W=1,H=et(0,k[0].length).map(()=>{let q=et(W,W+k.length);return W+=k.length,q});({validSeedBlocks:a}=Sv({drawPositionBlocks:k,nonRandom:n?.nonRandom,positioning:V,seedGroups:H}))}}else E?{validSeedBlocks:a}=Hk({nonRandom:n?.nonRandom,seedingProfile:n,structure:s}):N?a=y.map(L=>({seedNumbers:L,drawPositions:L})):v&&Ae(h,2).map((w,V)=>({drawPositions:[w[0]],seedNumbers:[V+1]})).forEach(w=>a.push(w));if(!E&&!v&&!D){let{blocks:L}=Wk({drawPositionOffset:S,seedNumberOffset:R,seedCountGoal:O,seedingProfile:n,baseDrawSize:T});L.forEach(w=>a.push(w))}let F=a.flatMap(L=>L.drawPositions).reduce((L,w)=>h?.includes(w)&&L,!0);return!v&&!N&&!E&&!F?{error:GA,validSeedBlocks:[],isContainer:E,isFeedIn:N}:{isLuckyStructure:v,validSeedBlocks:a,isContainer:E,isFeedIn:N}}function Hk({seedingProfile:t,structure:e,nonRandom:r}){let n=e.structures||[],o=n.length,i=bt({structure:e})?.positionAssignments,s=Op(t),a=i?.length??0,{seedGroups:c}=fg({roundRobinGroupsCount:o,drawSize:a}),u=n.map(p=>bt({structure:p}).positionAssignments?.map(m=>m.drawPosition));return Sv({drawPositionBlocks:u,positioning:s,seedGroups:c,nonRandom:r})}function Sv({drawPositionBlocks:t,positioning:e,seedGroups:r,nonRandom:n}){let o=[],{divisionGroupings:i}=hv({size:r.length,positioning:e}),s=[];return r.forEach((a,c)=>{let u=Iv({blockPattern:i,index:c});a.forEach((p,m)=>{let d=c%2?t.length-m-1:m,f=t[d].slice().filter((I,h)=>u.includes(h+1)&&I);e!==di?f=n?f:Ir(f):c%2&&f.reverse();let g=f.find(I=>!s.includes(I));g&&(s.push(g),o.push({drawPositions:[g],seedNumbers:[p]}))})}),{validSeedBlocks:o}}function Wk(t){let{drawPositionOffset:e=0,roundRobinGroupsCount:r,seedNumberOffset:n=0,seedingProfile:o,seedCountGoal:i,baseDrawSize:s}=t,a=1,c=[],{seedBlocks:u}=lg({cluster:Op(o)===Kc,participantsCount:s,roundRobinGroupsCount:r});a=0;for(let m of u){if(a+1>i)break;let d=m.map(f=>f+e),l=p(a+1,m.length).map(f=>+f+n);a+=m.length,c.push({drawPositions:d,seedNumbers:l})}return{blocks:c};function p(m,d){return Array.from(new Array(d),(l,f)=>f+m)}}function vp({appliedPolicies:t,drawDefinition:e,seedBlockInfo:r,drawPosition:n,structureId:o,seedNumber:i}){let{structure:s}=at({drawDefinition:e,structureId:o});t||(t=yt({drawDefinition:e}).appliedPolicies);let a=r?.validSeedBlocks;return!a&&s&&(a=Ts({appliedPolicies:t,drawDefinition:e,structure:s})?.validSeedBlocks),t?.seeding?.validSeedPositions?.ignore?!0:t?.seeding?.validSeedPositions?.strict?(a.find(m=>m.seedNumbers.includes(i))?.drawPositions||[]).includes(n):[].concat(...a.map(u=>u.drawPositions)).includes(n)}function US(t){let{provisionalPositioning:e,drawDefinition:r,seedingProfile:n,seedBlockInfo:o,structureId:i,randomize:s}=t,{structure:a}=at({drawDefinition:r,structureId:i}),{seedAssignments:c}=on({returnAllProxies:t.returnAllProxies,provisionalPositioning:e,drawDefinition:r,structure:a}),{positionAssignments:u}=Se({structure:a}),m=u?.filter(w=>w.participantId??w.bye??w.qualifier)?.map(w=>w.drawPosition).filter(Boolean),{appliedPolicies:d}=yt({drawDefinition:r}),g=(o?.validSeedBlocks||a&&Ts({returnAllProxies:t.returnAllProxies,provisionalPositioning:e,appliedPolicies:d,drawDefinition:r,seedingProfile:n,structure:a})?.validSeedBlocks||[]).filter(w=>w.drawPositions.filter(k=>!m?.includes(k)).length)[0],I=c?.map(w=>w.participantId).filter(Boolean),h=u?.map(w=>w.participantId).filter(Boolean),S=I?.filter(w=>h?.includes(w)),T=I?.filter(w=>!h?.includes(w)),y=c?.filter(w=>T?.includes(w.participantId)),P=c?.filter(w=>!w.participantId),A=(y?.length&&y.length>0?y.length:P?.length??0)&&g?.drawPositions.filter(w=>!m?.includes(w))||[],E=s?Ir(A):A,N=[],D=E.map(()=>{let V=L(y,N)?.participantId;return V&&N.push(V),V}).filter(Boolean),M=c?.filter(w=>S?.includes(w.participantId)).map(w=>w.seedNumber),b=(g?.seedNumbers||[]).filter(w=>!M?.includes(w)),v=c?.filter(w=>b.includes(w.seedNumber)).map(w=>w.participantId),O=d?.seeding?.duplicateSeedNumbers;return{nextSeedBlock:g,unplacedSeedParticipantIds:(O!==void 0?O:!0)?D:v,unplacedSeedNumbers:b,unfilledPositions:E,unplacedSeedAssignments:y};function L(w,V){let k=w.filter($=>!V.includes($.participantId)),W=Math.min(...k.map($=>Ic($.seedValue))),H=k.filter($=>Ic($.seedValue)===W);return Ir(H).pop()}}function Op(t){if(typeof t=="string")return t;if(typeof t=="object")return t.positioning}function $s({provisionalPositioning:t,tournamentRecord:e,drawDefinition:r,seedingProfile:n,participantId:o,seedBlockInfo:i,structureId:s,seedNumber:a,seedValue:c,eventId:u,event:p}){let m="assignSeed",{structure:d}=at({drawDefinition:r,structureId:s}),{positionAssignments:l}=Se({structure:d}),f=on({provisionalPositioning:t,drawDefinition:r,structure:d}).seedAssignments,g=f.map(U=>U.seedNumber),I=fc({drawDefinition:r,participantId:o});if(o&&!I)return _({result:{error:mn},context:{participantId:o},stack:m});let h=p?Ht({event:p}).flightProfile?.flights?.length:0,S=h&&h>1,y=l?.find(U=>U.participantId===o)?.drawPosition;if(y&&!vp({drawPosition:y,drawDefinition:r,seedBlockInfo:i,structureId:s,seedNumber:a}))return _({result:{error:Ll},context:{assignedDrawPosition:y},info:"invalid seed position",stack:m});g.includes(a)||f.push({seedNumber:a,seedValue:c});let P;return f.forEach(U=>{U.participantId===o&&U.seedNumber!==a&&(U.participantId=void 0),U.seedNumber===a&&(U.participantId=o,!n?.groupSeedingThreshold&&!S&&(U.seedValue=c??a),P=!0)}),P?(qh({tournamentId:e?.tournamentId,drawDefinition:r,structure:d,eventId:u}),{...C}):_({result:{error:kA},stack:m})}function Id({inContextTargetMatchUp:t,drawPositionSideIndex:e,teamParticipantId:r,tournamentRecord:n,drawDefinition:o,matchUp:i,event:s}){let a=t?.sides?.[e]?.sideNumber,c=a&&i.sides?.find(d=>d.sideNumber===a),{extension:u}=dt({element:o,name:Ro}),p=u?.value||{},m=J(p[r],!1,!0);if(c)i?.sides?.forEach(d=>{d.sideNumber===a&&(d.lineUp=m)});else{i.sides=[1,2].map(l=>({...i.sides?.find(g=>g.sideNumber===l)??{},sideNumber:l}));let d=i.sides.find(l=>l.sideNumber===a);d&&(d.lineUp=m)}gt({tournamentId:n?.tournamentId,context:"updateSidLineUp",eventId:s?.eventId,drawDefinition:o,matchUp:i})}function PS(t){let{sourceMatchUp:e}=t,{targetMatchUp:r,structure:n,matchUpsMap:o,drawPosition:i}=t,s=r.roundNumber>1&&r.roundNumber-1,a=ii({structureId:n.structureId,matchUpsMap:o});!e&&i&&(e=a.find(({drawPositions:f,roundNumber:g})=>g===s&&f?.includes(i)));let c=e?.roundPosition,u=c%2?1:-1,p=c+u,m=s&&a.find(({roundNumber:f,roundPosition:g})=>f===s&&g===p),d=m?.matchUpStatus,l=[he,be].includes(d);return{pairedPreviousMatchUp:m,pairedPreviousMatchUpIsDoubleExit:l}}function Tv({drawPosition:t,drawPositions:e}){let r=!1,n=!!e?.includes(t);return{updatedDrawPositions:n?e||[]:[...e,void 0,void 0].slice(0,2).map(s=>!s&&!n?(n=!0,r=!0,t):s).sort(me).filter(Boolean),positionAdded:r,positionAssigned:n}}function DS({structureId:t,matchUpsMap:e,matchUp:r}){let n=r?.roundPosition,o=n%2?1:-1,i=n+o;return{pairedPreviousMatchUp:ii({matchUpsMap:e,structureId:t}).find(({roundNumber:c,roundPosition:u})=>c===r?.roundNumber&&u===i)}}function NS({inContextDrawMatchUps:t,sourceMatchUpStatus:e,sourceMatchUpId:r,matchUpsMap:n,matchUp:o}){let i=t.find(a=>a.matchUpId===r),{pairedPreviousMatchUp:s}=DS({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=Vt(p)||!isNaN(p)?{code:p}:p;return m.sideNumber===u?{...m,previousMatchUpStatus:e}:m})}}function hd({inContextDrawMatchUps:t,drawPosition:e,matchUpId:r}){let n=t.filter(({winnerMatchUpId:s,loserMatchUpId:a})=>a===r||s===r).sort((s,a)=>s.roundPosition-a.roundPosition);return t.find(s=>s.matchUpId===r).feedRound?1:n.reduce((s,a,c)=>a.drawPositions?.includes(e)?c+1:s,void 0)}function hc({inContextDrawMatchUps:t,sourceMatchUpStatus:e,tournamentRecord:r,sourceMatchUpId:n,drawDefinition:o,matchUpStatus:i,drawPosition:s,matchUpsMap:a,matchUpId:c,event:u}){let p="assignMatchUpDrawPosition";a||(a=Me({drawDefinition:o})),t||(t=se({inContext:!0,drawDefinition:o,matchUpsMap:a}).matchUps??[]);let m=t.find(b=>b.matchUpId===c),d=m?.structureId,l=o?.structures?.find(b=>b.structureId===d);if(!l)return{error:kt};let f=a?.drawMatchUps?.find(b=>b.matchUpId===c),g=f?.drawPositions??[],{positionAdded:I,positionAssigned:h,updatedDrawPositions:S}=Tv({drawPositions:g,drawPosition:s}),{positionAssignments:T}=bt({drawDefinition:o,structure:l}),P=T?.filter(b=>S.includes(b.drawPosition))?.find(({bye:b})=>b),U=f?.matchUpStatus&&[Ct,Mt].includes(f.matchUpStatus)&&S.filter(Boolean).length<2;if(i=P&&Nt||i||U&&f.matchUpStatus||f?.matchUpStatus&&[he,be].includes(f.matchUpStatus)&&f.matchUpStatus||Qt,f&&I){t=se({inContext:!0,drawDefinition:o,matchUpsMap:a}).matchUps??[];let b=U&&hd({inContextDrawMatchUps:t,drawPosition:s,matchUpId:c})||void 0;f?.matchUpStatusCodes&&NS({inContextDrawMatchUps:t,sourceMatchUpStatus:e,sourceMatchUpId:n,matchUpsMap:a,matchUp:f}),Object.assign(f,{drawPositions:S,winningSide:b,matchUpStatus:i}),gt({tournamentId:r?.tournamentId,eventId:m?.eventId,context:p,drawDefinition:o,matchUp:f})}let A=ur({inContextDrawMatchUps:t,inContextMatchUp:m,drawDefinition:o,matchUpId:c}),{targetMatchUps:{winnerMatchUp:E,loserMatchUp:N,loserTargetDrawPosition:D},targetLinks:{loserTargetLink:M}}=A,R=ii({structureId:l.structureId,matchUpsMap:a});if(h&&P){if(E)if([Nt,he,be].includes(i)){let b=hc({matchUpId:E.matchUpId,inContextDrawMatchUps:t,tournamentRecord:r,drawDefinition:o,drawPosition:s,matchUpsMap:a});if(b.error)return b}else{let{structureId:b}=E;b!==l.structureId&&console.log("winnerMatchUp in different structure... participant is in different targetDrawPosition")}}else if(E&&m&&!m.feedRound){let{pairedPreviousMatchUpIsDoubleExit:b}=PS({targetMatchUp:f,drawPosition:s,matchUpsMap:a,structure:l});if(b){let v=hc({matchUpId:E.matchUpId,inContextDrawMatchUps:t,tournamentRecord:r,drawDefinition:o,drawPosition:s,matchUpsMap:a});if(v.error)return v}}if(f?.matchUpType===jt){let b=t?.find(({matchUpId:F})=>F===f.matchUpId),O=(b?.sides??[]).reduce((F,L,w)=>L.drawPosition===s?w:F,void 0),x=T?.find(F=>F.drawPosition===s)?.participantId;x&&O!==void 0&&Id({inContextTargetMatchUp:b,drawPositionSideIndex:O,teamParticipantId:x,tournamentRecord:r,drawDefinition:o,matchUp:f})}if(M?.linkCondition===On&&S.filter(Boolean).length===2&&!P&&R.filter(({drawPositions:O,roundNumber:x})=>x===1&&Fe(O,S)).every(({matchUpStatus:O})=>[le,rr].includes(O))&&N){let{structureId:O}=N,x=Hr({drawPosition:D,tournamentRecord:r,drawDefinition:o,structureId:O,matchUpsMap:a,event:u});if(x.error)return x}return h?{...C}:_({result:{error:Wa},context:{drawPosition:s},stack:p})}function MS({inContextDrawMatchUps:t,drawDefinition:e,assignments:r,matchUpsMap:n,structure:o}){let s=as({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 Sd({lineUp:t}){if(!Array.isArray(t))return;let e={};return ut(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}=Mp({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 si(t){return`${t} must be an array`}function Td({lineUp:t,tieFormat:e}){let r=[];if(!Array.isArray(t))return r.push(si("lineUp")),{valid:!1,errors:r,error:G};let n=t.every(s=>{if(typeof s!="object")return r.push("lineUp entries must be objects"),!1;let{participantId:a,collectionAssignments:c}=s;return a?typeof a!="string"?(r.push("participantIds must be strings"),!1):Array.isArray(c)?c.every(u=>{if(typeof u!="object")return r.push("collectionAssignments must be objects"),!1;let{collectionPosition:p}=u;return typeof p!="number"?(r.push("collectionPosition must be a number"),!1):!0}):(r.push(si("collectionAssignments")),!1):(r.push("Missing participantId"),!1)}),o=ut(t.map(St)).length===t.length;return o||r.push("Duplicated participantId(s)"),{valid:n&&o,errors:r,error:r.length?G:void 0}}function Ki({drawDefinition:t,participantId:e,tieFormat:r,lineUp:n}){if(typeof t!="object")return{error:Z};if(typeof e!="string")return{error:oe};let o=Td({lineUp:n,tieFormat:r});if(!o.valid)return o;let{extension:i}=dt({element:t,name:Ro}),s=i?.value||{};return s[e]=Sd({lineUp:n}),At({element:t,extension:{name:Ro,value:s}}),Ta({drawDefinition:t}),{...C}}function gg({inContextDrawMatchUps:t,inheritance:e=!0,tournamentRecord:r,drawDefinition:n,matchUpsMap:o,assignments:i,structure:s,event:a}){if(!n)return{error:Z};let{drawPositions:c,matchUps:u,targetMatchUps:p}=MS({inContextDrawMatchUps:t,matchUpsMap:o,assignments:i,structure:s});for(let m of p)m.matchUpType===xr&&(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&&Ki({drawDefinition:n,participantId:I,lineUp:[],tieFormat:g})}gt({tournamentId:r?.tournamentId,context:"resetLineUps",eventId:a?.eventId,drawDefinition:n,matchUp:f})}}});return{...C}}function kn({provisionalPositioning:t,inContextDrawMatchUps:e,isQualifierPosition:r,sourceMatchUpStatus:n,tournamentRecord:o,drawDefinition:i,seedingProfile:s,participantId:a,seedBlockInfo:c,drawPosition:u,matchUpsMap:p,structureId:m,event:d}){let l="assignDrawPosition";if(!a&&!r)return _({result:{error:oe},stack:l});p=p??Me({drawDefinition:i}),e||({matchUps:e}=se({inContext:!0,drawDefinition:i,matchUpsMap:p}));let f=at({drawDefinition:i,structureId:m});if(f.error)return _({result:f,stack:l});let{structure:g}=f;if(!g)return{error:kt};if(cr({structure:g}))return _({result:{error:dr},stack:l});let{seedAssignments:I}=on({provisionalPositioning:t,drawDefinition:i,structure:g}),S=I?.find(v=>v.participantId===a)?.seedNumber,{appliedPolicies:T}=yt({tournamentRecord:o,drawDefinition:i,structure:g,event:d});if(S&&!vp({seedNumber:S,appliedPolicies:T,drawDefinition:i,seedBlockInfo:c,drawPosition:u,structureId:m}))return _({result:{error:Ll},context:{drawPosition:u},stack:l});let P=Se({structure:g}).positionAssignments||[],U=P?.find(v=>v.drawPosition===u);if(!U)return _({result:{error:Rs},context:{drawPosition:u},stack:l});if(P?.map(St).includes(a))return _({result:{error:vs},context:{drawPosition:u},stack:l});let{containsParticipant:E,containsBye:N}=b(U);if(N){let v=lc({inContextDrawMatchUps:e,tournamentRecord:o,drawDefinition:i,drawPosition:u,structureId:m,matchUpsMap:p,event:d});if(v.error)return _({result:v,stack:l})}if(E&&U.participantId!==a){let{activeDrawPositions:v}=Pa({drawDefinition:i,structureId:m});if(v.includes(u))return _({result:{error:qu},stack:l});gg({assignments:[U],inContextDrawMatchUps:e,tournamentRecord:o,drawDefinition:i,matchUpsMap:p,structure:g})}if(U.participantId=a,r&&(U.qualifier=!0),g.stage===nt&&(!g.stageSequence||g.stageSequence>1)||g.stage&&[qe,de].includes(g.stage)){let v=g.stage===ct?ct:nt,F=(i.structures?.find(L=>L?.stage===v&&L?.stageSequence===1)?.seedAssignments??[]).find(L=>L.participantId===a);if(F?.participantId){let{participantId:L,seedNumber:w,seedValue:V}=F;$s({eventId:d?.eventId,provisionalPositioning:t,tournamentRecord:o,drawDefinition:i,seedingProfile:s,participantId:L,seedNumber:w,seedValue:V,structureId:m,event:d})}}if(g.structureType!==Ge)jk({provisionalPositioning:t,inContextDrawMatchUps:e,sourceMatchUpStatus:n,tournamentRecord:o,drawDefinition:i,drawPosition:u,matchUpsMap:p,structure:g,event:d});else{SS({positionAssignments:P,tournamentRecord:o,drawDefinition:i,matchUpsMap:p,structure:g});let{drawPositions:v,matchUps:O,targetMatchUps:x}=MS({assignments:[U],inContextDrawMatchUps:e,drawDefinition:i,matchUpsMap:p,structure:g});if(v&&O?.length===1&&O[0].matchUpType===jt){let L=(x?.[0].sides??[]).reduce((w,V,k)=>v?.includes(V.drawPosition)?k:w,void 0);Id({inContextTargetMatchUp:x[0],teamParticipantId:a,matchUp:O[0],drawPositionSideIndex:L,tournamentRecord:o,drawDefinition:i})}}let M=i.entries?.find(v=>v.participantId===a),R=d?.entries?.find(v=>v.participantId===a);return!M&&R&&fd({entryStatus:R.entryStatus,entryStage:g.stage,ignoreStageSpace:!0,drawDefinition:i,participantId:a,event:d}),bo({tournamentId:o?.tournamentId,drawDefinition:i,structure:g,event:d}),{positionAssignments:P,...C};function b(v){let O=v.bye,x=v.qualifier,F=v.participantId;return{containsBye:O,containsQualifier:x,containsParticipant:F,filled:O||x||F}}}function jk({provisionalPositioning:t,inContextDrawMatchUps:e,sourceMatchUpStatus:r,tournamentRecord:n,drawDefinition:o,drawPosition:i,matchUpsMap:s,structure:a,event:c}){let u={isCollectionMatchUp:!1},{matchUps:p}=Ut({provisionalPositioning:t,matchUpFilters:u,drawDefinition:o,matchUpsMap:s,structure:a,event:c}),{roundMatchUps:m}=Ke({matchUps:p}),{initialRoundNumber:d}=fs({drawPosition:i,matchUps:p}),l=d&&m?.[d].find(f=>f.drawPositions?.includes(i));if(l){let f=hc({matchUpId:l.matchUpId,inContextDrawMatchUps:e,sourceMatchUpStatus:r,tournamentRecord:n,drawDefinition:o,drawPosition:i,matchUpsMap:s});if(f.error)return _({stack:"assignDrawPositionToMatchUps",context:{drawPosition:i},result:f})}return{...C}}function yd(t){let{participantIdAttributeName:e="participantId",isQualifierPosition:r,positionActionName:n,tournamentRecord:o,drawDefinition:i,participantId:s,drawPosition:a,structureId:c,event:u}=t,p="positionParticipantAction";if(!i)return{error:Z};let m=yt({tournamentRecord:o,drawDefinition:i,event:u}).appliedPolicies??{},{inContextDrawMatchUps:d,matchUpsMap:l}=t;l||(l=Me({drawDefinition:i}),Object.assign(t,{matchUpsMap:l})),d||({matchUps:d}=se({inContext:!0,drawDefinition:i,matchUpsMap:l}),Object.assign(t,{inContextDrawMatchUps:d}));let{positionAssignments:f}=bt({drawDefinition:i,structureId:c}),g=f?.find(y=>y.drawPosition===a);if(g?.participantId){let y=g.participantId,P=kn({inContextDrawMatchUps:d,tournamentRecord:o,drawDefinition:i,participantId:s,drawPosition:a,structureId:c,matchUpsMap:l,event:u});return P.success?T({appliedPolicies:m,removedParticipantId:y}):_({result:P,stack:p})}let I=lc({inContextDrawMatchUps:d,tournamentRecord:o,drawDefinition:i,drawPosition:a,structureId:c,matchUpsMap:l,event:u});if(I.error)return _({result:I,stack:p});let h=I.participantId,S=kn({inContextDrawMatchUps:d,isQualifierPosition:r,tournamentRecord:o,drawDefinition:i,participantId:s,drawPosition:a,structureId:c,matchUpsMap:l,event:u});if(!S.success)return _({result:S,stack:p});return T({appliedPolicies:m,removedParticipantId:h});function T({appliedPolicies:y,removedParticipantId:P}){let{structure:U}=at({drawDefinition:i,structureId:c});Xm({drawPositions:[a],structure:U});let A={[e]:s,name:n,drawPosition:a,structureId:c};return cu({appliedPolicies:y,drawDefinition:i,positionAction:A}),_({context:{removedParticipantId:P},result:{...C},stack:p})}}function yv({luckyLoserParticipantId:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,structureId:o}){return yd({positionActionName:"luckyLoserDrawPositionAssignment",participantId:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,structureId:o})}function lP(t){return yv(t)}function RS({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 CS(t,e){let r=[{drawDefinition:!0,structureId:!0}];Array.isArray(e)&&r.push(...e);let n=rt(t,r);if(n.error)return n;let o=at(t);if(o.error)return o;let i=o.structure;if(!cr({structure:i}))return _({result:{error:Xo,message:"structure must be adHoc"}});let{roundMatchUps:a=[],roundNumbers:c}=Ke({matchUps:i?.matchUps});return c?.length?{valid:!0,structure:i,roundMatchUps:a,roundNumbers:c}:{error:Jn}}function fP(t){let e=CS(t,[{targetRoundNumber:!0,roundNumber:!0,[He]:cb}]);if(e.error)return e;let{structure:r,roundMatchUps:n,roundNumbers:o}=e,{targetRoundNumber:i,roundNumber:s}=t;if(!o?.includes(s)||!o?.includes(i))return _({result:{error:G},info:"roundNumbers must be valid rounds"});let a=i>s,c=a?et(s+1,i+1):et(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),RS({params:t,modMap:u,structure:r}),{...C}}function gP({structurePositionAssignments:t,provisionalPositioning:e,tournamentRecord:r,drawDefinition:n,event:o}){if(!n)return{error:Z};if(!Array.isArray(t))return{error:G};let i="setPositionAssignments";for(let a of t){let{structureId:c,positionAssignments:u}=a;if(!u)continue;let p=at({drawDefinition:n,structureId:c});if(p.error)return p;let m=p.structure;if(!m)return{error:kt};let d=bt({structure:m}).positionAssignments?.map(({drawPosition:I})=>I),l=u?.map(({drawPosition:I})=>I);if(Yt(d,l).length!==d?.length)return _({result:{error:G},info:"drawPositions do not match",stack:i});let f=Me({drawDefinition:n}),{matchUps:g}=se({inContext:!0,drawDefinition:n,matchUpsMap:f});for(let I of u||[]){let{drawPosition:h,participantId:S,bye:T,qualifier:y}=I;if(T){let P=Hr({tournamentRecord:r,drawDefinition:n,drawPosition:h,matchUpsMap:f,structureId:c,structure:m,event:o});if(P?.error)return P}else if(y)u.forEach(P=>{P.drawPosition===h&&(P.qualifier=!0,delete P.participantId,delete P.bye)});else if(S){let P=kn({provisionalPositioning:e,inContextDrawMatchUps:g,tournamentRecord:r,drawDefinition:n,participantId:S,drawPosition:h,matchUpsMap:f,structureId:c,event:o});if(P?.error)return P}}bo({tournamentId:r?.tournamentId,drawDefinition:n,structure:m,event:o})}let s=t.map(({structureId:a})=>a);return Ot({tournamentId:r?.tournamentId,eventId:o?.eventId,drawDefinition:n,structureIds:s}),{...C}}function IP(t){let e=CS(t,[{roundNumbers:!0,[He]:Be,[tr]:s=>s.length===2&&s.every(Zt)}]);if(e.error)return e;let{structure:r,roundMatchUps:n,roundNumbers:o}=e;if(!t.roundNumbers.every(s=>o?.includes(s)))return _({result:{error:G,message:"roundNumbers must be valid rounds"}});let i={};return t.roundNumbers.forEach((s,a)=>(n?.[s]??[]).forEach(({matchUpId:c})=>{i[c]=t.roundNumbers[1-a]})),RS({params:t,modMap:i,structure:r}),{...C}}function Av({qualifyingParticipantId:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,structureId:o}){return yd({positionActionName:"qualifierDrawPositionAssignment",participantId:t,isQualifierPosition:!0,tournamentRecord:e,drawDefinition:r,drawPosition:n,structureId:o})}function hP(t){return Av(t)}function SP({alternateParticipantId:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,structureId:o,event:i}){return yd({positionActionName:"alternateDrawPositionAssignment",participantIdAttributeName:"alternateParticipantid",participantId:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,structureId:o,event:i})}function TP({validation:t=!0,tournamentRecord:e,drawDefinition:r,participantId:n,structureId:o,seedValue:i,event:s}){if(!r)return{error:Z};if(!o)return{error:Ur};let a=(e?.participants??[]).find(l=>l.participantId===n);if(e&&!a)return{error:mn};let{structure:c}=at({drawDefinition:r,structureId:o});if(!c)return{error:kt};if(!(!t||Zt(i)||i===void 0||i===""||typeof i=="string"&&i.split("-").every(l=>Zt(l)&&pt(l)>0)))return{error:G};let{seedAssignments:p}=on({drawDefinition:r,structure:c}),m=p?.map(l=>l.seedNumber),d=p?.find(l=>l.participantId===n);if(d){let l=typeof i=="string"?i.includes("-")&&i.split("-").map(f=>parseInt(f)).join("-")||parseInt(i)>0&&parseInt(i)||"":i&&i>0&&i||"";d.seedValue=l}else{let f={seedNumber:Math.max(0,...m||[])+1,participantId:n};i&&(f.seedValue=i),c.seedAssignments||(c.seedAssignments=[]),c.seedAssignments.push(f)}return qh({tournamentId:e?.tournamentId,eventId:s?.eventId,drawDefinition:r,structure:c}),{...C}}function bS({drawDefinition:t,structureId:e}){if(!t)return{error:Z};let{structure:r}=at({drawDefinition:t,structureId:e}),n=(t?.links||[]).filter(i=>i.source?.structureId===e).map(i=>i.target?.structureId);return{playoffStructures:(t?.structures||[]).filter(i=>n.includes(i.structureId)),structure:r}}function Ig({withStageGrouping:t,stageSequences:e,stageSequence:r,roundTarget:n,stages:o,event:i,stage:s}){if(!i)return{error:vt};let a={},c=[];for(let u of i.drawDefinitions||[]){let{structures:p,stageStructures:m}=gn({withStageGrouping:t,stageSequences:e,drawDefinition:u,stageSequence:r,roundTarget:n,stages:o,stage:s});if(c.push(...p),m)for(let d of Object.keys(m))a[d]||(a[d]=[]),a[d].push(...m[d])}return{structures:c,stageStructures:a}}function vS({withStageGrouping:t,tournamentRecord:e,stageSequences:r,stageSequence:n,roundTarget:o,stages:i,stage:s}){if(!e)return{error:Y};let a={},c=[];for(let u of e.events||[]){let{structures:p,stageStructures:m}=Ig({withStageGrouping:t,stageSequences:r,stageSequence:n,roundTarget:o,stages:i,event:u,stage:s});if(p&&c.push(...p),m)for(let d of Object.keys(m))a[d]||(a[d]=[]),a[d].push(...m[d])}return{structures:c,stageStructures:a}}function ai(t){if(!t?.drawDefinition)return!1;let e=Su(t),r=e?.includesTeamMatchUps,{completedMatchUps:n,pendingMatchUps:o,upcomingMatchUps:i}=e||{};return r&&(n=n?.filter(({matchUpType:a})=>a===jt),o=o?.filter(({matchUpType:a})=>a===jt),i=i?.filter(({matchUpType:a})=>a===jt)),!!(n?.length&&!o?.length&&!i?.length)}function OS(t){let{drawDefinition:e,structureId:r}=t;if(!e)return{error:Z};let{playoffStructures:n}=bS({drawDefinition:e,structureId:r});if(!n?.length)return!1;let o=e?.entries?.filter(c=>c?.entryStatus&&Qr.includes(c.entryStatus))?.length??0,i=0;return(n||[]).reduce((c,u)=>!!((bt({structure:u}).positionAssignments??[])?.filter(d=>(d.participantId&&i++,d?.bye??d?.participantId)).length&&c),!!n.length)||i===o}function _S({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=_S({accessors:s,significantCharacters:t,value:c});n.push(...u)});else if(r=r[o],s.length){let a=_S({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 Ev({targetParticipantIds:t,policyAttributes:e,idCollections:r,participants:n}){if(!Array.isArray(e))return{error:LI};if(!Array.isArray(n))return{error:$a};let o={};return t.forEach(i=>{let s=n.find(c=>c.participantId===i),{values:a}=yP({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 yP({policyAttributes:t,idCollections:e,participants:r,participant:n}){if(!Array.isArray(t))return{error:LI};if(!n)return{error:wi};let o=[];return t.forEach(s=>{let{directive:a,groupings:c,key:u,significantCharacters:p}=s||{};if(u){let m=u.split(".");o.push(..._S({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:ut(o)}}function AP({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}=yP({participants:e,policyAttributes:r,idCollections:n,participant:s});return{...i,values:a}})}function Pv({participantIdGroups:t,positionAssignments:e,groupsToAvoid:r}){return Object.assign({},...e.filter(n=>n?.participantId).map(n=>{let{drawPosition:o,participantId:i}=n,s=t?t[i]||[]:[],a=!!r.some(c=>s.includes(c));return{[o]:{participantGroups:s,includesGroupsToAvoid:a}}}))}function Dv(t){let{unfilledPositions:e,chunkedDrawPositions:r}=t,n=Pv(t);return r.map(s=>{let a=e.filter(m=>s.includes(m)),c=i(a),p=a.filter(m=>!c.includes(m)).filter(m=>{let d=Uv(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=Uv(c);return!s.includes(u)}}}function Nv(t){let{unfilledPositions:e,chunkedDrawPositions:r}=t,n=Pv(t);return r.map(o=>{let i=e.filter(u=>o.includes(u)),s=i.length===o.length?i:[],a=o.filter(u=>n[u]?.includesGroupsToAvoid).length;return{unassigned:i,unpaired:s,pairedNoConflict:a?[]:i,conflictsCount:a}})}function Uv(t){return Number(t%2?t+1:t-1)}function Mv({allGroups:t,participantId:e}){return Object.keys(t).filter(r=>t[r].includes(e))}function Rv({selectedParticipantGroups:t,participantIdGroups:e,positionAssignments:r,drawPositionChunks:n,unfilledPositions:o,isRoundRobin:i}){let s=n.map(a=>i?Nv({groupsToAvoid:t,chunkedDrawPositions:a,participantIdGroups:e,positionAssignments:r,unfilledPositions:o}):Dv({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 xS({positionAssignments:t,participantIds:e}){let r=t.map(n=>n.participantId);return e.filter(n=>!r.includes(n))}function Cv({useSpecifiedGroupKey:t=!1,targetParticipantIds:e,largestFirst:r=!0,allGroups:n,groupKey:o}){let i=Object.assign({},...Object.keys(n).map(p=>[p,n[p].filter(m=>e.includes(m))]).filter(p=>p[1].length).map(([p,m])=>({[p]:m}))),s=Object.keys(i).reduce((p,m)=>i[m].length>p?i[m].length:p,0),a=Object.keys(i).filter(p=>i[p].length===s),c=r?yn(a):yn(Object.keys(i));return o=t&&i[o]?.length?o:c,{participantId:o&&i[o]?yn(i[o]):yn(e),groupKey:o}}function bv({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 vv({candidatePositionAssignments:t,unseededParticipantIds:e,participantIdGroups:r,drawPositionChunks:n,drawPositionGroups:o,pairedPriority:i,allGroups:s,groupKey:a}){let u=o.reduce((N,D)=>D.length>N?D.length:N,0)<=2,p=xS({positionAssignments:t,participantIds:e}),m=bv({positionAssignments:t,drawPositionGroups:o}),{participantId:d,groupKey:l}=Cv({targetParticipantIds:p,useSpecifiedGroupKey:u,allGroups:s,groupKey:a}),f=Mv({participantId:d,allGroups:s}),g=Rv({positionAssignments:t,isRoundRobin:u,selectedParticipantGroups:f,participantIdGroups:r,drawPositionChunks:n,unfilledPositions:m}),{unassigned:I,unpaired:h,pairedNoConflict:S}=g,T=S?.length&&S[0],y=h?.length&&h[0],P=i&&T?T:y,U=i?y:T,A=P?.length&&P||U?.length&&U,E;if(A?.length){let N=tn(A);E=tn(N)}else{let N=tn(I[0]);E=tn(N)}return{newGroupKey:l,selectedParticipantId:d,targetDrawPosition:E}}function Ad({isRoundRobin:t,groupedParticipants:e}){let r=[];return t?e.forEach(n=>{let o=n.map(a=>a.drawPosition),i=mg({drawPositions:o}).uniqueMatchUpGroupings??[],s=Object.assign({},...n.map(a=>({[a.drawPosition]:a})));i.forEach(a=>{Fe(s[a[0]].values||[],s[a[1]].values||[])&&(r.push(a),n.conflict=!0)})}):e.forEach(n=>{Fe(n[0]?.values||[],n[1]?.values||[])&&(r.push(n),n.conflict=!0)}),r}function Ov({positionedParticipants:t,potentialDrawPositions:e,drawPositionGroups:r,avoidanceConflicts:n,isRoundRobin:o}){return n.map(i=>{let s=i.map(c=>c.drawPosition);return i.filter(c=>e.includes(c.drawPosition)).map(c=>{let p=e.filter(m=>!s?.includes(m)).filter(m=>{let d=r.find(T=>T.includes(m)).find(T=>T!==m),l=t.find(T=>T.drawPosition===d),g=Ad({isRoundRobin:o,groupedParticipants:[[c,l]]}),h=[t.find(T=>T.drawPosition===m),l],S=Ad({isRoundRobin:o,groupedParticipants:[h]});return!g.length&&!S.length});if(p.length)return{drawPosition:c.drawPosition,possibleDrawPositions:p}}).filter(Boolean)}).flat(1)}function EP(t){let{initialPositionAssignments:e,participantsWithGroupings:r,opponentsToPlaceCount:n,unseededByePositions:o,drawPositionGroups:i,policyAttributes:s,idCollections:a,allGroups:c}=t,u=[],p,m=Math.min(...(i||[]).map(T=>T?.length).filter(Boolean)),d=m>2,l=J(e,!1,!0).filter(T=>!T.qualifier),f=e.filter(T=>!T.participantId&&(!T.bye||o?.includes(T.drawPosition))).map(T=>T.drawPosition);et(0,n).forEach(()=>{let{newGroupKey:T,selectedParticipantId:y,targetDrawPosition:P}=vv({...t,candidatePositionAssignments:l,allGroups:c,groupKey:p});p=T,l.forEach(U=>{U.drawPosition===P&&(U.participantId=y)})});let g=AP({candidatePositionAssignments:l,participantsWithGroupings:r,policyAttributes:s,idCollections:a}),I=Ae(g,m),h=Ad({groupedParticipants:I,isRoundRobin:d}),S=0;for(;S<20&&h.length;){let T=Ov({positionedParticipants:g,potentialDrawPositions:f,avoidanceConflicts:h,drawPositionGroups:i,isRoundRobin:d});if(T.length){let y=Yk({candidatePositionAssignments:l,swapOptions:T});y.error&&console.log({result:y}),g=AP({candidatePositionAssignments:l,participantsWithGroupings:r,policyAttributes:s,idCollections:a}),I=Ae(g,m),h=Ad({groupedParticipants:I,isRoundRobin:d}),S++}else S=20}return l.forEach(T=>{if(T.bye&&T.participantId){let y=_I;u.push(y)}if(T.qualifier&&T.participantId){let y=_I;u.push(y)}}),{positionAssignments:l,conflicts:h.length,groupedParticipants:I,errors:u}}function Yk({candidatePositionAssignments:t,swapOptions:e}){let r=tn(e);if(!r)return{error:{message:"No swap options"}};let n=r.drawPosition,o=tn(r.possibleDrawPositions),i=t.find(u=>u.drawPosition===n),s=t.find(u=>u.drawPosition===o)??{},a={participantId:s?.participantId,qualifier:s?.qualifier,bye:s?.bye},c={participantId:i.participantId,qualifier:i.qualifier,bye:i.bye};return Object.assign(i,a),Object.assign(s,c),{...C}}function _v({provisionalPositioning:t,unseededParticipantIds:e,inContextDrawMatchUps:r,unseededByePositions:n,tournamentRecord:o,drawDefinition:i,seedBlockInfo:s,participants:a,matchUpsMap:c,structureId:u,avoidance:p,drawSize:m,event:d}){if(!p)return{error:QA};let{candidatesCount:l=1,policyAttributes:f,targetDivisions:g}=p,{roundsToSeparate:I}=p,h="randomUnseededSeparation",{structure:S}=at({drawDefinition:i,structureId:u}),{matchUps:T}=Ut({provisionalPositioning:t,matchUpsMap:c,structure:S,event:d});if(g&&vn(g)&&!I){let k=aC(g)||0,W=T.reduce((H,q)=>q.roundNumber>H?q.roundNumber:H,0);I=W<k?1:W-k+1}let{positionAssignments:y}=Se({structure:S}),P=du({participantsProfile:{convertExtensions:!0},deepCopy:!1,participants:a}).participantsWithGroupings,U=y?.filter(k=>!k.participantId),A=y?.map(k=>k.drawPosition),E=S?.structureType===Ge,N=E?{structure:S,matchUps:T,allDrawPositions:A,roundsToSeparate:I}:{matchUps:T,allDrawPositions:A,roundsToSeparate:I},{drawPositionGroups:D,drawPositionChunks:M}=E?qk(N):$k(N),R={groupParticipants:a.filter(k=>k.participantType===zr).map(k=>k.participantId),teamParticipants:a.filter(k=>k.participantType===wt).map(k=>k.participantId),pairParticipants:a.filter(k=>k.participantType===ft).map(k=>k.participantId)},b=Ev({targetParticipantIds:e,policyAttributes:f,idCollections:R,participants:a});if(b.error)return _({result:b,stack:h});let v=Object.assign({},...e.map(k=>{let W=Object.keys(b).filter(H=>(b[H]??[]).includes(k));return{[k]:W}})),O=xS({participantIds:e,positionAssignments:y});if(O.length>(U?.length||0))return{error:Ql};let x,F=O.length,L=et(0,l).map(()=>EP({initialPositionAssignments:y,participantsWithGroupings:P,unseededParticipantIds:e,opponentsToPlaceCount:F,pairedPriority:!1,unseededByePositions:n,participantIdGroups:v,drawPositionChunks:M,drawPositionGroups:D,policyAttributes:f,idCollections:R,allGroups:b,drawSize:m}));if(x=L.reduce((k,W)=>!k||(W.conflicts||0)<(k.conflicts||0)?W:k,void 0),!x||x.conflicts){let k=et(0,l).map(()=>EP({initialPositionAssignments:y,participantsWithGroupings:P,unseededParticipantIds:e,opponentsToPlaceCount:F,pairedPriority:!0,unseededByePositions:n,participantIdGroups:v,drawPositionChunks:M,drawPositionGroups:D,policyAttributes:f,idCollections:R,allGroups:b,drawSize:m}));x=L.concat(...k).filter(H=>!H.errors?.length).reduce((H,q)=>!H||(q.conflicts||0)<(H.conflicts||0)?q:H,void 0)}if(!x)return{error:Xu};let w=(bt({structure:S})?.positionAssignments??[]).filter(k=>k.participantId).map(k=>k.participantId),V=x.positionAssignments.filter(k=>!w.includes(k.participantId));for(let k of V)if(k.bye){let W=Hr({tournamentRecord:o,drawDefinition:i,seedBlockInfo:s,structureId:u,matchUpsMap:c,event:d,...k});if(W.error)return _({result:W,stack:h})}else if(k.participantId){let W=kn({automaticPlacement:!0,inContextDrawMatchUps:r,tournamentRecord:o,drawDefinition:i,seedBlockInfo:s,structureId:u,matchUpsMap:c,event:d,...k});if(W.error)return _({result:W,stack:h,context:{assignment:k}})}return{...C}}function qk(t){let{structure:{structures:e}}=t,r=e.map(n=>n.positionAssignments.map(o=>o.drawPosition));return{drawPositionGroups:r,drawPositionChunks:[r]}}function $k({allDrawPositions:t,roundsToSeparate:e,matchUps:r}){let n=r.filter(d=>d.roundNumber===1).map(d=>d.drawPositions),o=n.flat().sort(me),i=Math.max(...o),s=t.filter(d=>d>i),a=o.length,u=et(a===2?1:2,a).filter(d=>d===Tm(d)),m=u.slice(0,e||u.length).reverse().map(d=>Ae(o,d));return s.length&&console.log({fedDrawPositions:s}),{drawPositionGroups:n,drawPositionChunks:m}}function xv({provisionalPositioning:t,inContextDrawMatchUps:e,unseededByePositions:r,multipleStructures:n,tournamentRecord:o,drawDefinition:i,seedBlockInfo:s,participants:a,matchUpsMap:c,structureId:u,structure:p,drawSize:m,event:d}){let l="positionUnseededParticipants";p||({structure:p}=at({drawDefinition:i,structureId:u})),u||({structureId:u}=p);let{positionAssignments:f}=Se({structure:p}),{seedAssignments:g}=on({provisionalPositioning:t,drawDefinition:i,structure:p}),I=g?.map(M=>M.participantId).filter(Boolean),{stage:h,stageSequence:S}=p,T=h===ct?dt({element:p,name:Mn})?.extension?.value:void 0,P=Ui({provisionalPositioning:t,drawDefinition:i,stageSequence:S,entryStatuses:ni,structureId:u,roundTarget:T,stage:h}),A=P.filter(M=>!I?.includes(M.participantId)).map(M=>M.participantId),E=f?.filter(M=>!M.participantId&&!M.bye&&!M.qualifier).map(M=>M.drawPosition);if(!n&&A.length>(E?.length||0))return _({result:{error:Ql},context:{unseededParticipantsCount:A.length,unfilledDrawPositionsCount:E?.length},stack:l});let{appliedPolicies:N}=yt({tournamentRecord:o,drawDefinition:i,event:d}),D=N?.[ru];if(p.stage===de){let M=P.reduce((R,b)=>(R[b.groupingValue]||(R[b.groupingValue]=[]),R[b.groupingValue].push(b.participantId),R),{});Object.keys(M).length&&(D||(D={policyName:"Playoff Avoidance"}),D.policyAttributes||(D.policyAttributes=[]),D.policyAttributes.push({groupings:M}))}return D&&a?_v({provisionalPositioning:t,unseededParticipantIds:A,inContextDrawMatchUps:e,unseededByePositions:r,tournamentRecord:o,drawDefinition:i,seedBlockInfo:s,participants:a,matchUpsMap:c,structureId:u,avoidance:D,drawSize:m,entries:P}):Kk({provisionalPositioning:t,unseededParticipantIds:A,inContextDrawMatchUps:e,unfilledDrawPositions:E,multipleStructures:n,tournamentRecord:o,drawDefinition:i,seedBlockInfo:s,structureId:u,matchUpsMap:c,drawSize:m,event:d})}function Kk({provisionalPositioning:t,unseededParticipantIds:e,inContextDrawMatchUps:r,unfilledDrawPositions:n,multipleStructures:o,tournamentRecord:i,drawDefinition:s,seedBlockInfo:a,matchUpsMap:c,structureId:u,drawSize:p,event:m}){let d=p>2?Ir(n):n.reverse();for(let l of e){let f=d.pop();if(!o||f){let g=kn({provisionalPositioning:t,inContextDrawMatchUps:r,tournamentRecord:i,drawDefinition:s,seedBlockInfo:a,participantId:l,drawPosition:f,matchUpsMap:c,structureId:u,event:m});if(g?.error&&console.log("!!!!!",{result:g}),g?.error)return _({result:g,stack:"randomUnseededDistribution"})}}return{...C}}function wv(t){let e=t.structure??at(t).structure,r="positionQualifiers",n=[];if(e.stage===qe)return _({result:{error:Oi},stack:r});let{unplacedRoundQualifierCounts:o,positionAssignments:i,roundDrawPositions:s}=zk(t);for(let a of Object.keys(o)){let c=i?.filter(u=>s[a].includes(u.drawPosition)&&!u.participantId&&!u.qualifier&&!u.bye).map(u=>u.drawPosition);if(o[a]>(c||0))return _({result:{error:fE},context:{unfilledDrawPositions:c},stack:r});et(0,o[a]).forEach(()=>{let u=tn(c);n.push(u),i?.forEach(p=>{p.drawPosition===u&&(p.qualifier=!0,delete p.participantId,delete p.bye)})})}return{...C,qualifierDrawPositions:n}}function zk({drawDefinition:t,structure:e,structureId:r}){e||({structure:e}=at({drawDefinition:t,structureId:r})),r||({structureId:r}=e);let{positionAssignments:n}=Se({structure:e}),{stage:o,stageSequence:i}=e,{qualifiersCount:s,roundQualifiersCounts:a}=Is({drawDefinition:t,stageSequence:i,structureId:r,stage:o}),u=(a?Object.keys(a):[]).map(h=>pt(h)),{matchUps:p}=Ut({structure:e}),{roundProfile:m}=Ke({matchUps:p}),d=Object.assign({},...u.filter(h=>m?.[h]).map(h=>({[h]:m?.[h]?.drawPositions?.filter(Boolean)??[]}))),l=n?.filter(h=>h.qualifier).map(h=>h.drawPosition),f=s-(l?.length??0),g=l?.length;return{unplacedRoundQualifierCounts:Object.assign({},...u.map(h=>{let S=n?.filter(T=>T.qualifier&&d[h]?.drawPositions?.includes(T.drawPosition)).map(T=>T.drawPosition);return{[h]:(a?.[h]??0)-(S?.length??0)}})),unplacedQualifiersCount:f,placedQualifiersCount:g,roundQualifiersCounts:a,positionAssignments:n,roundDrawPositions:d,qualifiersCount:s}}function UP({provisionalPositioning:t,inContextDrawMatchUps:e,tournamentRecord:r,appliedPolicies:n,validSeedBlocks:o,drawDefinition:i,seedingProfile:s,seedBlockInfo:a,participants:c,groupsCount:u,structureId:p,matchUpsMap:m,structure:d,event:l}){let f=[],g=[],I=0;if(d||({structure:d}=at({drawDefinition:i,structureId:p})),p||(p=d?.structureId),n||(n=yt({drawDefinition:i}).appliedPolicies),!o){let h=d&&Ts({provisionalPositioning:t,appliedPolicies:n,drawDefinition:i,seedingProfile:s,structure:d});h?.error&&g.push(h.error),o=h?.validSeedBlocks}return u=u??o?.length??0,et(0,u).forEach(()=>{if(I<(u||0)){let h=Qk({provisionalPositioning:t,inContextDrawMatchUps:e,tournamentRecord:r,drawDefinition:i,seedingProfile:s,seedBlockInfo:a,participants:c,structureId:p,matchUpsMap:m,event:l});h?.success&&(I++,f.push(...h.seedPositions??[])),h.error&&g.push({seedPositionError:h.error})}}),g.length?{error:g}:{...C,seedPositions:f}}function Qk({provisionalPositioning:t,inContextDrawMatchUps:e,tournamentRecord:r,drawDefinition:n,seedingProfile:o,seedBlockInfo:i,participants:s,structureId:a,matchUpsMap:c,event:u}){let{unplacedSeedParticipantIds:p,unfilledPositions:m}=US({provisionalPositioning:t,randomize:!0,drawDefinition:n,seedingProfile:o,seedBlockInfo:i,structureId:a,event:u}),{appliedPolicies:d}=yt({drawDefinition:n}),{avoidance:l}=d??{};l&&s&&p?.length>2;let f=[];for(let g of p){let I=m.pop();if(!I)return{error:Cs};f.push(I);let h=kn({provisionalPositioning:t,inContextDrawMatchUps:e,tournamentRecord:r,drawDefinition:n,seedingProfile:o,participantId:g,seedBlockInfo:i,drawPosition:I,matchUpsMap:c,structureId:a,event:u});if(!h.success)return h}return{...C,seedPositions:f}}function Lv({provisionalPositioning:t,drawDefinition:e,structure:r}){let{positionAssignments:n}=Se({structure:r}),{seedAssignments:o}=on({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 Fv({orderedSortedFirstRoundSeededDrawPositions:t,validSeedBlocks:e,byesToPlace:r}){let n=[];e.forEach(i=>{if(r-n.length>i.drawPositions.length)n.push(...i.drawPositions);else{let a=PP(Ae(i.drawPositions,2)),c,u=t[n.length];for(;c=hg(a,u);)n.push(c),u=t[n.length]}});let o=n.map(i=>Array.isArray(i)?Ir(i):i).flat(1/0);return UI(r)&&e.map(s=>s.seedNumbers[0]).includes(r)?t:o}function hg(t,e){if(Array.isArray(t)&&t.length!==2)return t.pop();if(!Array.isArray(t[0]))return t.includes(e)?t.indexOf(e)?t.pop():t.shift():Math.round(Math.random())?t.pop():t.shift();let r=t[0].flat(1/0).length,n=t[1].flat(1/0).length;if(r===n){let o=t[0].flat(1/0).includes(e)?t[0]:t[1];return hg(e?o:t[Math.round(Math.random())],e)}return r<n?hg(t[1],e):hg(t[0],e)}function PP(t){let e=Math.floor(t.length/2);return t.length>2?[PP(t.slice(0,e)),PP(t.slice(e))]:t}function Gv({provisionalPositioning:t,relevantMatchUps:e,appliedPolicies:r,drawDefinition:n,seedingProfile:o,seedBlockInfo:i,byesToPlace:s,structure:a}){i||(i=Ts({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=Lv({provisionalPositioning:t,drawDefinition:n,structure:a})??[],l=ut([].concat(...e.map(P=>P.drawPositions))),f=d.filter(P=>l.includes(P.drawPosition)),g=(P,U)=>Ic(P.seedValue)-Ic(U.seedValue),h=m.reduce((P,U)=>{let A=f.filter(E=>U.drawPositions?.includes(E.drawPosition)).sort(g);return P.concat(...A)},[]).map(P=>P.drawPosition),S=Fv({orderedSortedFirstRoundSeededDrawPositions:h,validSeedBlocks:m,byesToPlace:s}),T=kv({orderedSeedDrawPositions:h,relevantMatchUps:e}).slice(0,s),y=kv({orderedSeedDrawPositions:S,relevantMatchUps:e}).slice(0,s);return{strictSeedOrderByePositions:T,blockSeedOrderByePositions:y,isLuckyStructure:u,positionedSeeds:d,isContainer:p,isFeedIn:c}}function kv({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 Vv({provisionalPositioning:t,seedOrderByePositions:e,isLuckyStructure:r,appliedPolicies:n,drawDefinition:o,seedLimit:i,structure:s,isFeedIn:a}){let c=n?.seeding?.seedingProfile,u=s.stage===ct,{positionAssignments:p}=Se({structure:s}),m=p?.filter(O=>O.participantId).map(O=>O.drawPosition),d={isCollectionMatchUp:!1},{matchUps:l,roundMatchUps:f}=Ut({provisionalPositioning:t,matchUpFilters:d,structure:s}),g=f?.[1]||[],I=s.structureType===Ge?l:g,h=ut([].concat(...I.map(O=>O.drawPositions))),S=Math.min(...h)-1,T=m?.filter(O=>h.includes(O)),y=O=>{let x=Math.ceil(O.length/2),F=[O.slice(0,x),O.slice(x)],L=F.map(B=>[].concat(...B.flat(1/0)).length),w=Math.min(...L.flat(1/0)),V=Math.max(...L.flat(1/0)),k=L.indexOf(V),W=w!==V,H=Ir(F),[q,$]=!w||W?[F[k],F[1-k]]:[H[0],H[1]];return{greaterHalf:q,lesserHalf:$}},P=O=>{let{greaterHalf:x,lesserHalf:F}=y(O),{greaterHalf:L,lesserHalf:w}=y(x),k=Ir(L.flat(1/0)).pop(),W=L.flat().filter(q=>q!==k);return{newlyFilteredChunks:[...F,...w,W],drawPosition:k}},U=O=>!e.includes(O),A=O=>!T?.includes(O),E=O=>{let F=Ae(O.sort(me),Math.ceil(O.length/4)).map(V=>V.filter(A)),L=[].concat(...F.flat(1/0)).length,w=[];for(let V=0;V<L;V++){let{newlyFilteredChunks:k,drawPosition:W}=P(F);w.push(W),F=k}return w},{validSeedBlocks:N}=Ts({provisionalPositioning:t,allPositions:!0,appliedPolicies:n,drawDefinition:o,structure:s}),D=N?.map(O=>O.drawPositions?.map(x=>x+S)),M;if(a){let O=h.length,{seedBlocks:x}=lg({cluster:Op(c)===Kc,participantsCount:O});M=x.map(L=>L.map(w=>w+S)).map(E).filter(L=>L.length)}else u?M=D?.map(O=>O.filter(A)):M=D?.map(E).filter(O=>O.length);let R=I.map(O=>O.drawPositions).map(O=>O?.sort((x,F)=>x-F)).filter(O=>O?.[0]+1===O?.[1]),b=O=>R.reduce((x,F)=>F.includes(O)?F.reduce((L,w)=>w!==O?w:L,void 0):x,void 0),v=M.map(O=>O.map(b)).flat(1/0).filter(A).filter(U).filter(Boolean);if(u&&!s.structures){let O=i%4,x=v.slice(0,O),F=f[s.roundLimit]?.length,L=Ae(v.slice(O),F).map(Ir).flat();v=x.concat(L)}return{unseededByePositions:v}}function Bv({provisionalPositioning:t,drawDefinition:e,matchUpsMap:r,structure:n,event:o}){let i={isCollectionMatchUp:!1},{matchUps:s,roundMatchUps:a}=Ut({afterRecoveryTimes:!1,provisionalPositioning:t,drawDefinition:e,matchUpFilters:i,matchUpsMap:r,structure:n,event:o}),c=a?.[1]||[],u=n?.structureType===Ge,p=u?s:c,m=u?n?.structures?.length||0:s.length,{structureId:d,stage:l,stageSequence:f}=n,g=Ui({entryStatuses:Qr,provisionalPositioning:t,drawDefinition:e,stageSequence:f,structureId:d,stage:l}),{qualifiersCount:I}=Is({provisionalPositioning:t,drawDefinition:e,stageSequence:f,structureId:d,stage:l}),h=g.length+I,{positionAssignments:S,unassignedPositions:T}=Se({structure:n}),y=T?.map(D=>D.drawPosition),P=S?.filter(D=>D.bye).length,U=S?.filter(D=>D.bye).map(D=>D.drawPosition),A=p.map(D=>D.drawPositions).filter(D=>D?.reduce((M,R)=>!U?.includes(R)&&M,!0)).flat(1/0).filter(D=>y?.includes(D)),E=S?.length,N=E?E-h:0;return N>m&&n.stageSequence===1&&n.stage!==qe&&(N=m),{placedByes:P,byesCount:N,relevantMatchUps:p,placedByePositions:U,roundMatchUps:a,positionsToAvoidDoubleBye:A}}function DP({provisionalPositioning:t,tournamentRecord:e,appliedPolicies:r,drawDefinition:n,seedBlockInfo:o,seedingProfile:i,matchUpsMap:s,structureId:a,structure:c,seedLimit:u,seedsOnly:p,event:m}){c||({structure:c}=at({drawDefinition:n,structureId:a})),a||(a=c?.structureId);let d=!(c?.structures??c?.stage===ct),{byesCount:l,placedByes:f,relevantMatchUps:g}=Bv({provisionalPositioning:t,drawDefinition:n,matchUpsMap:s,structure:c,event:m}),I=l-(f||0);if(I<=0)return{...C};let{strictSeedOrderByePositions:h,blockSeedOrderByePositions:S,isLuckyStructure:T,isFeedIn:y}=Gv({provisionalPositioning:t,relevantMatchUps:g,appliedPolicies:r,drawDefinition:n,seedingProfile:i,seedBlockInfo:o,byesToPlace:I,structure:c}),P=c?.structureType&&[Ge,cp].includes(c.structureType)&&r?.seeding?.containerByesIgnoreSeeding,U=d&&S?.length?S:h,{unseededByePositions:A}=Vv({provisionalPositioning:t,seedOrderByePositions:U,isLuckyStructure:T,appliedPolicies:r,drawDefinition:n,seedLimit:u,structure:c,isFeedIn:y}),E=R=>R%2,N=(R,b)=>(R||[]).every(v=>E(v)?b!==v+1:b!==v-1),D=[].concat(...U);if(!p)for(;A.length;){let R=A.find(b=>N(D,b));R?(D.push(R),A=A.filter(b=>b!==R)):(D.push(...A),A=[])}P&&(D=Ir(D),Pr({ignoreSeededByes:P})&&console.log({byePositions:D}));let M=D.slice(0,I);for(let R of M){let b=Hr({provisionalPositioning:t,tournamentRecord:e,drawDefinition:n,drawPosition:R,matchUpsMap:s,structureId:a,structure:c,event:m});if(b?.error)return b}return{...C,unseededByePositions:A,byeDrawPositions:M}}function Sc(t){let{drawDefinition:e}=t,{applyPositioning:r=!0,provisionalPositioning:n,multipleStructures:o,placeByes:i=!0,tournamentRecord:s,placementGroup:a,seedingProfile:c,structureId:u,seedLimit:p,seedsOnly:m,drawType:d,drawSize:l,event:f}=t,g=[];r||(LE(),e=J(e,!1,!0));let I=x=>(r||sf(),_({result:x,stack:"automatedPositioning"})),h=x=>(r||sf(),x),S=at({drawDefinition:e,structureId:u});if(S.error)return I(S);let T=S.structure;if(!T)return{error:kt};let y=t.appliedPolicies||yt({drawDefinition:e,structure:T,event:f})?.appliedPolicies,{qualifiersCount:P}=Is({stageSequence:T.stageSequence,provisionalPositioning:n,stage:T.stage,drawDefinition:e,structureId:u}),U=ni;if(!Ui({stageSequence:T.stageSequence,provisionalPositioning:n,stage:T.stage,placementGroup:a,drawDefinition:e,entryStatuses:U,structureId:u})?.length&&!P)return h({...C});let E=t.matchUpsMap??Me({drawDefinition:e}),N=t.inContextDrawMatchUps??se({inContext:!0,drawDefinition:e,matchUpsMap:E})?.matchUps,D=[],M=Ts({provisionalPositioning:n,appliedPolicies:y,drawDefinition:e,seedingProfile:c,structure:T});if(M.error)return M;let{validSeedBlocks:R}=M;g.push({validSeedBlocks:R});let b=t.participants||(s?Gt({withIndividualParticipants:!0,convertExtensions:!0,tournamentRecord:s})?.participants:[]);if(Op(T.seedingProfile||c)===di){let x=i?DP({provisionalPositioning:n,tournamentRecord:s,appliedPolicies:y,drawDefinition:e,seedBlockInfo:M,matchUpsMap:E,structure:T,seedLimit:p,seedsOnly:m,event:f}):void 0;if(x?.error)return I(x);D=x.unseededByePositions,g.push({action:"positionByes",unseededByePositions:D});let F=T.seedingProfile?{positioning:T.seedingProfile}:c;if(x=UP({seedingProfile:F,provisionalPositioning:n,inContextDrawMatchUps:N,tournamentRecord:s,appliedPolicies:y,validSeedBlocks:R,drawDefinition:e,seedBlockInfo:M,participants:b,matchUpsMap:E,structure:T,event:f}),x.error)return I(x);g.push({seedPositions:x.seedPositions,action:"positionSeedBlocks"})}else{if(d!==ki){let F=T.seedingProfile?{positioning:T.seedingProfile}:c,L=UP({seedingProfile:F,provisionalPositioning:n,inContextDrawMatchUps:N,tournamentRecord:s,appliedPolicies:y,validSeedBlocks:R,drawDefinition:e,seedBlockInfo:M,participants:b,matchUpsMap:E,structure:T,event:f});if(L.error)return I(L);g.push({action:"positionSeedBlocks",seedPositions:L.seedPositions})}let x=i?DP({provisionalPositioning:n,tournamentRecord:s,appliedPolicies:y,drawDefinition:e,seedBlockInfo:M,matchUpsMap:E,structure:T,seedLimit:p,seedsOnly:m,event:f}):void 0;if(x?.error)return I(x);D=x?.unseededByePositions,g.push({action:"positionByes",byeDrawPositions:x?.byeDrawPositions,unseededByePositions:D})}let v={};if(!m){let x=wv({inContextDrawMatchUps:N,tournamentRecord:s,appliedPolicies:y,validSeedBlocks:R,drawDefinition:e,seedBlockInfo:M,participants:b,matchUpsMap:E,structure:T});if(x.error||(x.conflicts&&(v.qualifierConflicts=x.conflicts),g.push({action:"positionQualifiers",qualifierDrawPositions:x.qualifierDrawPositions}),x=xv({provisionalPositioning:n,inContextDrawMatchUps:N,unseededByePositions:D,multipleStructures:o,tournamentRecord:s,drawDefinition:e,seedBlockInfo:M,participants:b,matchUpsMap:E,structureId:u,structure:T,drawSize:l,event:f}),x.error))return I(x);x.conflicts&&(v.unseededConflicts=x.conflicts),g.push({action:"positionUnseededParticipants"})}let{positionAssignments:O}=bt({drawDefinition:e,structure:T});return Ot({drawDefinition:e,structureIds:[u]}),r||sf(),{positionAssignments:O,conflicts:v,...C,positioningReport:g}}function Ks(t){let{applyPositioning:e=!0,provisionalPositioning:r,tournamentRecord:n,drawDefinition:o,seedingProfile:i,structureId:s,placeByes:a,seedsOnly:c}=t;if(!o)return{error:Rr};if(!ai({drawDefinition:o,structureId:s})&&!r)return{error:wl};let p=bS({drawDefinition:o,structureId:s}).playoffStructures?.sort((l,f)=>Of(l)-Of(f)),m=[],d=[];if(p)for(let l of p){let{structureId:f}=l,g=Sc({structureId:f,provisionalPositioning:r,applyPositioning:e,tournamentRecord:n,drawDefinition:o,seedingProfile:i,placeByes:a,seedsOnly:c});if(g.error)return g;g.positionAssignments&&m.push({positionAssignments:g.positionAssignments,structureId:f}),g.positioningReport&&d.push(g.positioningReport)}return{...C,structurePositionAssignments:m,positioningReports:d}}function NP({drawDefinition:t,orderMap:e}){return t?((typeof e!="object"||!Object.values(e).every(r=>It(r)))&&_({result:{error:G},context:{orderMap:e}}),t.structures||(t.structures=[]),t.structures.forEach(r=>{let n=e[r.structureId];n&&(r.structureOrder=n)}),t.structures.sort((r,n)=>Ba(r.structureOrder)-Ba(n.structureOrder)),{...C}):{error:Z}}function Uu({drawDefinition:t}){let e=t.structures??[],r=t.links??[],n=new Map,o=I=>{let h=n.get(I)||n.set(I,{drawSources:[],drawTargets:[],progeny:[],sources:[],targets:[]})&&n.get(I);if(h&&!h?.stage){let S=e.find(T=>T.structureId===I);h.stage=S?.stage}return h},i={},s={},a=r.map(I=>{let h=I.source.structureId,S=I.target.structureId,T=o(h),y=o(S);return[li,En,up,di].includes(I.target.feedProfile)?(T?.targets.push(S),y?.sources.push(h)):I.target.feedProfile===dn&&(y?.drawSources.push(h),T?.drawTargets.push(S)),s[S]=s[S]||I.target.feedProfile===dn,i[S]=ut([...i[S]||[],h]).filter(Boolean),[I.source.structureId,I.target.structureId]});for(let I of n.keys()){let h=n.get(I);if(h){let S=h.targets??[];for(;S.length;){let T=S.pop(),y=T&&n[T];y?.targets?.length?S.push(...y.targets):y&&(h.rootStage=y.stage)}if(h.rootStage||(h.rootStage=h.stage),!h.targets?.length){let T=h.sources??[];for(;T.length;){let y=T.pop(),P=y&&n[y];if(P?.sources?.length){for(let U of P.sources)h.progeny?.includes(U)||h.progeny?.push(U);T.push(...P.sources)}}}}}let c=0;for(let I of n.keys()){let h=n.get(I);if(h&&h.rootStage===ct){let S=[h.drawTargets?.[0]],T=0;for(;S.length;){T+=1;let y=S.pop(),P=y?n.get(y):void 0;P?.drawTargets?.length&&S.push(P.drawTargets[0])}h.distanceFromMain=T,T>c&&(c=T)}}let u=a.length;et(0,Math.ceil(u/2)).forEach(()=>{a=et(0,u).map(I=>{let h=a[I],S=a.reduce((T,y)=>Fe(h,y)?T.concat(...y):T,[])||[];return ut(h.concat(...S))})});let p=a[0],m=(I,h)=>Yt(I,h).length===I.length,d=a.slice(1).reduce((I,h)=>I&&m(h,p),!0),l=[p].filter(Boolean),f=[p].filter(Boolean);e.forEach(I=>{let{structureId:h,stage:S}=I;l.find(y=>y.includes(h))||(l.push([h]),S!==$e&&f.push([h]))});let g=d&&f.length===1;return!r?.length&&e.length===1&&o(e[0].structureId),{structureProfiles:Object.fromEntries(n),allStructuresLinked:g,maxQualifyingDepth:c,sourceStructureIds:i,hasDrawFeedProfile:s,structureGroups:l}}function wS({drawDefinition:t}){let{maxQualifyingDepth:e,structureProfiles:r}=Uu({drawDefinition:t});for(let n of t.structures){let o=r[n.structureId];o.distanceFromMain&&(n.stageSequence=e+1-o.distanceFromMain)}return{...C}}function Sg(t){let e=rt(t,[{[ie]:!0,[Ve]:!0}]);if(e.error)return e;let{tournamentRecord:r,drawDefinition:n,structure:o,link:i}=t;return Xk({tournamentId:r.tournamentId,drawDefinition:n,structure:o,link:i})}function Xk(t){let e=rt(t,[{[Ve]:!0,[dp]:!0},{link:!0,[He]:Kr,[MA]:kl}]);if(e.error)return e;let{drawDefinition:r,tournamentId:n,structure:o,eventId:i,link:s}=t,a=s.target.structureId,c=at({drawDefinition:r,structureId:a});if(c.error)return _({stack:"attachQualifyingStructure",context:{targetStructureId:a},result:c});r.structures||(r.structures=[]),r.links||(r.links=[]),r.structures.push(o),r.links.push(s),wS({drawDefinition:r});let u=Ut({structure:o})?.matchUps||[];return Co({drawDefinition:r,tournamentId:n,matchUps:u,eventId:i}),Ot({drawDefinition:r,structureIds:[o.structureId]}),{...C}}function MP({drawDefinition:t,structureDetails:e}){if(!Array.isArray(e))return{error:G};if(!t)return{error:Z};let r=Object.assign({},...e.map(n=>{if(!ht(n))return;let{structureId:o,structureName:i}=n||{};if(!(!o||!i))return{[o]:i}}).filter(Boolean));if(!Object.values(r).length)return{error:st};for(let n of t.structures||[]){let o=r[n.structureId];if(o&&(n.structureName=o),n.structures)for(let i of n.structures){let s=r[i.structureId];s&&(i.structureName=s)}}return{...C}}function Tg({drawDefinition:t,timeItem:e}){if(!t)return{error:Rr};if(!e)return{error:Zl};let r=e&&Object.keys(e),n=["itemType","itemValue"];if(!(n.filter(s=>r.includes(s)).length===n.length))return{error:Jl};t.timeItems||(t.timeItems=[]);let i=new Date().toISOString();return Object.assign(e,{createdAt:i}),t.timeItems.push(e),Ta({drawDefinition:t}),{...C}}function RP(t){let{tournamentRecord:e,drawDefinition:r,structureId:n,event:o}=t,i=rt(t,[{drawDefinition:!0,structureId:!0}]);if(i.error)return i;let s=r.structures??[],a=s.find(h=>h.structureId===n);if(!a)return{error:kt};let c=s.find(({stage:h,stageSequence:S})=>h===nt&&S===1),u=n===c?.structureId,p=s.filter(({stage:h})=>h===ct).map(Br("structureId"));if(u&&!p.length)return{error:RA};let m=p.includes(n),d=Jk({isQualifyingStructure:m,structure:a,...t});if(d?.error)return d;let{structureIdsToRemove:l,relatedStructureIdsMap:f}=tG({qualifyingStructureIds:p,isQualifyingStructure:m,isMainStageSequence1:u,mainStageSequence1:c,drawDefinition:r,structureId:n}),{removedMatchUpIds:g,removedStructureIds:I}=eG({relatedStructureIdsMap:f,qualifyingStructureIds:p,isMainStageSequence1:u,mainStageSequence1:c,drawDefinition:r,structureIdsToRemove:l,structureId:n});if(Zk({removedMatchUpIds:g,drawDefinition:r}),u){let h=(c.matchUps??[])?.map(Br("matchUpId"));g.push(...h),c.positionAssignments=[],c.seedAssignments=[],c.matchUps=[],c.extensions&&(c.extensions=[])}return m&&wS({drawDefinition:r}),qn({tournamentId:e?.tournamentId,matchUpIds:g,action:"removeStructure",eventId:o?.eventId,drawDefinition:r}),Ot({drawDefinition:r,eventId:o?.eventId}),{...C,removedMatchUpIds:g,removedStructureIds:I}}function Jk({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(se({matchUpFilters:{structureIds:a},drawDefinition:r}).matchUps?.some(({score:p})=>Ie({score:p}))){let p=yt({tournamentRecord:e,drawDefinition:r,structure:o,event:i})?.appliedPolicies;if(!(s??p?.[en]?.allowDeletionWithScoresPresent?.structures))return{error:ep}}return{...C}}function Zk({removedMatchUpIds:t,drawDefinition:e}){let{matchUps:r}=se({drawDefinition:e});r?.forEach(n=>{n.winnerMatchUpId&&t.includes(n.winnerMatchUpId)&&delete n.winnerMatchUpId,n.loserMatchUpId&&t.includes(n.loserMatchUpId)&&delete n.loserMatchUpId})}function tG({qualifyingStructureIds:t,isQualifyingStructure:e,isMainStageSequence1:r,mainStageSequence1:n,drawDefinition:o,structureId:i}){let a=(o.structures??[]).map(Br("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 eG({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(...oG({idBeingRemoved:u,drawDefinition:o}));let p=nG({qualifyingStructureIds:e,isMainStageSequence1:r,idBeingRemoved:u,drawDefinition:o,structureId:s});a.push(...p.removedStructureIds);let m=rG({relatedStructureIdsMap:t,mainStageSequence1:n,idBeingRemoved:u,structureId:s});m?.length&&i.push(...m)}return{removedMatchUpIds:c,removedStructureIds:a}}function rG({idBeingRemoved:t,relatedStructureIdsMap:e,mainStageSequence1:r,structureId:n}){return t&&e.get(t)?.filter(o=>o!==r?.structureId||n===r.structureId)}function nG({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 oG({idBeingRemoved:t,drawDefinition:e}){let{structure:r}=at({structureId:t,drawDefinition:e}),n=Ut({structure:r}).matchUps;return Km(n)}function _p({stageSequence:t=1,drawDefinition:e,drawSize:r,stage:n}){if(!e)return{error:Z};if(!Jf({drawDefinition:e,stage:n}))return{error:Oi};let o=Nb({drawDefinition:e,stage:n}),{qualifiersCount:i}=Is({drawDefinition:e,stageSequence:t,stage:n}),s=o+i;if(r<s)return{error:OI};let{entryProfile:a}=qf({attributes:[{[n]:{drawSize:r}}],drawDefinition:e});return Ot({drawDefinition:e}),{...C,entryProfile:a}}function LS({qualifiersCount:t=0,drawDefinition:e,stage:r}){return e?Jf({drawDefinition:e,stage:r})?r!==nt?{error:OI,info:"qualifiersCount can only be set for main stage"}:(qf({attributes:[{[r]:{qualifiersCount:t}}],drawDefinition:e}),Ot({drawDefinition:e}),{...C}):{error:Oi}:{error:Z}}function Hv({drawDefinition:t,drawSize:e}){if(!t)return{error:Z};let r=_p({stage:$e,stageSequence:1,drawDefinition:t,drawSize:e});return r.error?r:(Ot({drawDefinition:t}),{...C})}function CP(t){return Hv(t)}var Wv="qualifierDrawPositionAssignment",jv="withdrawParticipantAtDrawPosition",Yv="alternateDrawPositionAssignment",qv="luckyLoserDrawPositionAssignment",bP="removeDrawPositionAssignment",FS="swapDrawPositionAssignments",$v="modifyPairAssignment",Kv="adHocPositionSwap",zv="modifyParticipantOtherName",vP="assignDrawPosition",Qv="removeSeededParticipant",Xv="assignDrawPositionBye",Jv="modifySeedAssignment",kS="addPenalty",yg="MODIFY_PAIR",xp="QUALIFIER",Ag="ALTERNATE",Eg="WITHDRAW",ys="ASSIGN",GS="REMOVE",Ug="LUCKY",wp="REMOVE_SEED",Lp="SWAP",Pu="NICKNAME",zs="SEED_VALUE",Qs="PENALTY",Ed="BYE",Zv={MODIFY_PAIR_ASSIGNMENT:yg,QUALIFYING_PARTICIPANT:xp,ALTERNATE_PARTICIPANT:Ag,WITHDRAW_PARTICIPANT:Eg,ASSIGN_PARTICIPANT:ys,LUCKY_PARTICIPANT:Ug,REMOVE_ASSIGNMENT:GS,SWAP_PARTICIPANTS:Lp,ADD_NICKNAME:Pu,REMOVE_SEED:wp,ADD_PENALTY:Qs,ASSIGN_BYE:Ed,SEED_VALUE:zs};function OP({tournamentRecord:t,drawDefinition:e,drawPositions:r,structureId:n,event:o}){if(!e)return{error:Z};if(!n)return{error:Ur};if(r?.length!==2)return{error:G,drawPositions:r};let i=Me({drawDefinition:e}),{matchUps:s}=se({inContext:!0,drawDefinition:e,matchUpsMap:i}),{structure:a}=at({drawDefinition:e,structureId:n});if(!a)return{error:kt};let c=yt({tournamentRecord:t,drawDefinition:e,event:o}).appliedPolicies??{},u;if(a.structureType===Ge?u=aG({inContextDrawMatchUps:s,tournamentRecord:t,drawDefinition:e,drawPositions:r,matchUpsMap:i,structure:a,event:o}):u=iG({inContextDrawMatchUps:s,tournamentRecord:t,drawDefinition:e,drawPositions:r,matchUpsMap:i,structure:a,event:o}),u.error)return u;if(Xm({structure:a,drawPositions:r}),cu({appliedPolicies:c,drawDefinition:e,positionAction:{name:FS,drawPositions:r,structureId:n}}),bo({tournamentId:t?.tournamentId,drawDefinition:e,structure:a,event:o}),o.eventType===br){let m=Ut({matchUpFilters:{matchUpTypes:[xr]},inContext:!0,structure:a}).matchUps.filter(l=>l.drawPositions?.some(f=>r.includes(f))),d=Ut({matchUpFilters:{matchUpTypes:[xr]},structure:a}).matchUps;m.forEach(l=>{(l.sides||[]).forEach(f=>{let g=f?.drawPosition;if(r.includes(g)){let I=f.participantId,h=d.find(({matchUpId:T})=>T===l.matchUpId),S=l?.sides?.reduce((T,y,P)=>y.drawPosition===g?P:T,void 0);Id({inContextTargetMatchUp:l,drawPositionSideIndex:S,teamParticipantId:I,tournamentRecord:t,drawDefinition:e,matchUp:h,event:o})}})})}return Ot({drawDefinition:e,structureIds:[n]}),{...C}}function iG({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,drawPositions:n,matchUpsMap:o,structure:i,event:s}){let a=i?.positionAssignments.filter(p=>n?.includes(p.drawPosition));if(!a)return{error:G,structure:i,info:"Missing positionAssignments"};if(a.filter(({bye:p})=>p).length===2)return{...C};if(a.filter(({qualifier:p})=>p).length===2)return{...C};let c=a.some(({qualifier:p})=>p);return a.some(({bye:p})=>p)&&!c?tO({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,assignments:a,matchUpsMap:o,structure:i,event:s}):sG({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,assignments:a,matchUpsMap:o,structure:i,event:s})}function tO({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=Eu({drawPosition:u,inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,structureId:d,matchUpsMap:o});return l.error||(l=Eu({drawPosition:m,inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,structureId:d,matchUpsMap:o}),l.error)||(Hr({drawPosition:m,tournamentRecord:e,drawDefinition:r,structureId:d,matchUpsMap:o,event:s}),l=kn({drawPosition:u,inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,structureId:d,participantId:p,matchUpsMap:o,event:s}),l.error)?l:{...C}}function sG({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,assignments:n,matchUpsMap:o,structure:i,event:s}){let a=Object.assign({},...n.map((c,u)=>{let{drawPosition:p}=c,m={...n[1-u],drawPosition:p};return{[p]:m}}));return i.positionAssignments=i.positionAssignments.map(c=>a[c.drawPosition]||c),gg({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,matchUpsMap:o,assignments:n,structure:i,event:s}),{...C}}function aG({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,drawPositions:n,matchUpsMap:o,structure:i,event:s}){let a=i.structures?.reduce((p,m)=>{let d=m?.positionAssignments.filter(l=>n?.includes(l.drawPosition));return d&&p.push(...d),p},[]);if(a.filter(({bye:p})=>p).length===2)return{...C};if(a.filter(({qualifier:p})=>p).length===2)return{...C};gg({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,matchUpsMap:o,assignments:a,structure:i,event:s});let c=a.some(({qualifier:p})=>p);if(a.some(({bye:p})=>p)&&!c)tO({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,assignments:a,matchUpsMap:o,structure:i,event:s});else{let p=J(a,!1,!0);a.forEach((m,d)=>{let l=p[1-d].participantId;m.qualifier=p[1-d].qualifier,m.participantId=l})}return{...C}}function _P({tournamentRecord:t,drawDefinition:e,participantId:r,structureId:n}){let o="removeSeededParticipant";if(!t)return{error:Y};if(!e)return{error:Z};let i=(e.structures??[]).find(a=>a.structureId===n);return i?!i.stage||![nt,ct].includes(i.stage)||i.stage===nt&&i.stageSequence!==1?_({result:{error:Xo},stack:o}):i.seedAssignments?.find(a=>a.participantId===r)?{...C}:_({info:"participant not seeded",result:{error:ve},context:{participantId:r}}):_({result:{error:kt},stack:o})}function Ma({targetEntryRound:t=1,finishingPositions:e,sourceRoundNumber:r,sourceStructureId:n,targetStructureId:o,linkType:i=fo}){return!n||!o?{error:Ur}:{link:ot({linkType:i,source:{roundNumber:r,structureId:n,finishingPositions:e},target:{feedProfile:dn,roundNumber:t,structureId:o}})}}function Ud({roundPosition:t,roundNumber:e,idPrefix:r,uuids:n}){return r?`${r}-${e}-${t}`:n?.pop()||Dt()}function Fp({includeMatchUpType:t,matchUpType:e,roundNumber:r,matchUps:n,idPrefix:o,isMock:i,uuids:s,nodes:a}){let c=0,u=[],p=1,m=r-1,d=a?.length;for(;c<(d||0);){let l=a?.[c],f=a?.[c+1];m&&(l.roundNumber=m),f&&m&&(f.roundNumber=m);let g=Ud({roundPosition:p,roundNumber:r,idPrefix:o,uuids:s}),I={roundPosition:p,children:[l,f],matchUpId:g};u.push(I);let h={drawPositions:I.children.map(S=>S?.drawPosition).filter(Boolean),matchUpStatus:Qt,matchUpId:I.matchUpId,roundPosition:p,roundNumber:r};t&&e&&(h.matchUpType=e),i&&(h.isMock=!0),n.push(h),p++,c+=2}return{roundNodes:u,matchUps:n}}function Cn({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&&(!vn(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(!vn(a)&&!p)return{matchUps:[],roundsCount:0};let m=et(1,a+1).map(I=>({drawPosition:I})),d,l=[],f=1;for({roundNodes:d,matchUps:l}=Fp({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}=Fp({nodes:d,matchUpType:o,roundNumber:f,idPrefix:s,matchUps:l,isMock:c,uuids:u}),f++;let g=f-1;return l=Ea({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 Pd(t){let e="generateQualifyingStructure";if(!t.drawDefinition)return _({result:{error:Z},stack:e});if(t.drawSize&&!It(t.drawSize)||t.participantsCount&&!It(t.participantsCount)||t.qualifyingPositions&&!It(t.qualifyingPositions))return _({result:{error:G},stack:e});let r=t.drawSize??Sm(t.participantsCount),{qualifyingRoundNumber:n,qualifyingPositions:o,targetStructureId:i,structureOptions:s,appliedPolicies:a,drawDefinition:c,matchUpFormat:u,structureName:p,structureId:m,roundTarget:d,drawType:l,idPrefix:f,isMock:g,uuids:I}=t;if(!t.drawSize)return _({result:{error:Ya},context:{drawSize:r},stack:e});if(o&&o>=t.drawSize)return _({result:{error:G},context:{drawSize:r,qualifyingPositions:o},stack:e});let h,S,T,y,P=0,U,A=1,{structureProfiles:E}=Uu({drawDefinition:c}),N=E[i];if(!N)return _({result:{error:kt},context:{targetStructureId:i},stack:e});let D=c.matchUpType,M=d?`${d}-`:"",R=N.stage===ct,b=a?.[fa]?.namingConventions?.pre??bb[fa]?.namingConventions?.pre,v=R&&b?`${b}-`:"",O=p??(M?`${v}${Qe(ct)} ${M}`:`${v}${Qe(ct)}`);if(l===Nn){let{maxRoundNumber:L,structures:w,groupCount:V}=Na({structureName:p??O,structureId:m??I?.pop(),stage:ct,structureOptions:s,appliedPolicies:a,stageSequence:A,matchUpType:D,roundTarget:d,idPrefix:f,drawSize:r,isMock:g,uuids:I});P=V,h=L,T=w[0],U=[1]}else({drawSize:r,matchUps:y,roundLimit:h,roundsCount:S}=Cn({qualifyingRoundNumber:n,qualifyingPositions:o,matchUpType:D,idPrefix:f,drawSize:r,isMock:g,uuids:I})),h||(h=S),T=hn({structureName:p??O,structureId:m??I?.pop(),qualifyingRoundNumber:h,stage:ct,matchUpFormat:u,stageSequence:A,matchUpType:D,roundLimit:h,matchUps:y}),d&&At({extension:{name:Mn,value:d},element:T}),P=y?.filter(L=>L.roundNumber===h)?.length;let x=l===Nn?eo:fo,F=T&&h&&Ma({sourceStructureId:T.structureId,sourceRoundNumber:h,targetStructureId:i,finishingPositions:U,linkType:x})?.link;return{qualifyingDrawPositionsCount:r,qualifiersCount:P,...C,structure:T,link:F}}function xP(t){if(!t.tournamentRecord)return{error:Y};let r=cG(t);return r.error,r}function cG(t){if(!t.drawDefinition)return{error:Z};if(!t.targetStructureId)return{error:Ur};let e=Pd(t);if(e.error)return e;let{structure:r,link:n}=e;return!r||!n?{error:G}:Sg({tournamentRecord:t.tournamentRecord,drawDefinition:t.drawDefinition,structure:r,link:n})}function wP(t){let e=rt(t,[{[Ve]:!0,[Zc]:!0,[ln]:!0},{[rb]:!0,[tr]:m=>Number.isInteger(m)&&m>0},{[tr]:m=>Array.isArray(m)&&m.length===2&&m.every(Vt),[Fr]:wr,participantIds:!0}]);if(e.error)return e;let{drawDefinition:r,structureId:n,tournamentRecord:o,event:i}=t,{structure:s}=at({drawDefinition:r,structureId:n});if(!s)return{error:kt};if(!cr({structure:s}))return{error:Xo};let a=m=>m.sides?.map(d=>d.participantId).some(d=>t.participantIds.includes(d)),c=m=>m.roundNumber===t.roundNumber,u=m=>!Ie(m),p=(s?.matchUps??[]).filter(c).filter(u).filter(a);if(p.length!==2)return{error:wr};for(let m of p){let d=m?.sides?.find(l=>t.participantIds.includes(l?.participantId));if(d){let l=t.participantIds.find(f=>f!==d?.participantId);d.participantId=l,gt({tournamentId:o?.tournamentId,eventId:i?.eventId,drawDefinition:r,matchUp:m})}}return Ot({drawDefinition:r,structureIds:[n]}),{...C}}function eO({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=et(0,p).map(g=>m?m+g:void 0),l=[];for(let g=0;g<p;g++){let I=d.shift(),h={drawPosition:I,fed:u+1,feed:!0},S=c[g];S.roundNumber=r-1;let T=Ud({roundPosition:S.roundPosition,roundNumber:r,idPrefix:o,uuids:a}),y={roundPosition:S.roundPosition,drawPositions:[I],matchUpStatus:Qt,roundNumber:r,matchUpId:T};t&&(y.matchUpType=n),s&&(y.isMock=!0),i.push(y);let P={children:[S,h]};l.push(P)}let f=e?e-p:void 0;return{roundNodes:l,matchUps:i,drawPosition:f}}function ci(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=uG({drawSize:i}),h=I.length,S=0;if(r?.length)S=r.reduce((L,w)=>L+w,0);else if(e){let L=e-i;r=I.filter(w=>w<=L?(L-=w,!0):!1),S=r.reduce((w,V)=>w+V,0),n=r.length}else o>=h?n=0:u&&(n=h-u,o=0),r=I.filter((L,w)=>u&&!n||n&&w>=o+n||w<o?0:L),S=r.reduce((L,w)=>L+w,0),n=r.length;let T=[...I,...r].sort((L,w)=>w-L),y=T.length,U=[...(c??[]).map(L=>L-1),...(s??[]).map(L=>y-L)].map(L=>T[L]).reduce((L,w)=>L+w,0);S=S-U;let A=0,E=[],N,D=1,R=et(0,i).map((L,w)=>({drawPosition:w+1+S})),b=S+1;for(let L of I){if({roundNodes:N,matchUps:E}=Fp({matchUpType:m,roundNumber:D,idPrefix:d,matchUps:E,isMock:l,nodes:R,uuids:f}),D++,r.includes(L)){let w=Sr(r)[L],V=et(0,w),k=y+1-D,W=s?.includes(k)??c?.includes(D);V.forEach(()=>{({roundNodes:N,matchUps:E,drawPosition:b}=eO({drawPosition:!W&&b||void 0,nodes:N,matchUpType:m,roundNumber:D,idPrefix:d,matchUps:E,isMock:l,uuids:f,fed:A})),D++,A+=1})}R=N}y!==D-1&&console.log("ERROR");let v=i-S;E=Ea({finishingPositionOffset:p?v:a,positionsFed:S,roundsCount:y,matchUps:E,fmlc:g});let x=N?.length?N[0]:N;return x&&(x.roundNumber=D-1,x.matchUps=E),{draw:x,matchUps:E,roundsCount:y};function F(L){let w=Tm(L);return w>L?w/2:w}}function uG({drawSize:t}){let e=Math.ceil(Math.log(t)/Math.log(2));return et(0,e).reverse().map(n=>Math.pow(2,n))}function Tc(t){let{finishingPositionOffset:e=0,addNameBaseToAttributeName:r,playoffStructureNameBase:n,finishingPositionNaming:o,finishingPositionLimit:i,playoffAttributes:s,stageSequence:a=1,exitProfile:c="0",exitProfileLimit:u,roundOffsetLimit:p,roundOffset:m=0,drawDefinition:d,staggeredEntry:l,sequenceLimit:f,stage:g=nt,drawSize:I,idPrefix:h,isMock:S,uuids:T}=t;if(!(!s||!u||s?.[c])||I<2||f&&a>f)return{};let P=[],U=[],A=[],E=t.matchUpType??d?.matchUpType,N=e+1,D=e+I,M=`${N}-${D}`,R=s?.[c],b=n&&`${n} `||"",v=s?.[M]??o?.[M],O=t.structureName||v?.name||R?.name&&(r?`${b}${R?.name}`:R.name)||`${b}${M}`,x=v?.abbreviation??R?.abbreviation,F=t.structureId??R?.structureId??T?.pop(),L={idPrefix:h&&`${h}-${O}-RP`,finishingPositionOffset:e,matchUpType:E,drawSize:I,isMock:S,uuids:T},{matchUps:w}=l?ci(L):Cn(L),V=hn({structureAbbreviation:x,stageSequence:a,structureName:O,matchUpType:E,roundOffset:m,structureId:F,matchUps:w,stage:g});P.push(...w),U.push(V);let k=Math.ceil(Math.log(I)/Math.log(2)),W=p?Math.min(p-m,k):(!i||N<i)&&k||0;return I>2&&et(1,W+1).forEach(q=>H(q)),{structureId:V.structureId,matchUps:P,structureName:O,structures:U,links:A,...C};function H(q){let $=I/Math.pow(2,q);if($<2)return;let B=I/Math.pow(2,q)+e;if(i&&B+1>i)return;let{structures:K,structureId:Q,matchUps:j,links:tt}=Tc({finishingPositionOffset:B,exitProfile:`${c}-${q}`,roundOffset:m+q,stageSequence:a+1,drawSize:$,addNameBaseToAttributeName:r,playoffStructureNameBase:n,finishingPositionNaming:o,finishingPositionLimit:i,playoffAttributes:s,exitProfileLimit:u,roundOffsetLimit:p,drawDefinition:d,sequenceLimit:f,matchUpType:E,idPrefix:h,uuids:T,stage:g});if(V.structureId&&Q){let z={linkType:ro,source:{roundNumber:q,structureId:V.structureId},target:{roundNumber:1,feedProfile:En,structureId:Q}};tt&&V&&tt.push(z),tt?.length&&A.push(...tt)}return K?.length&&U.push(...K),j?.length&&P.push(...j),{structureId:Q,childLinks:tt,structures:U}}}function Dd({drawDefinition:t,matchUpsMap:e,structureId:r}){let n=at({drawDefinition:t,structureId:r});if(n.error)return _({result:n});let{matchUps:o}=Ut({structure:n.structure,matchUpsMap:e});return{...Ke({matchUps:o}),matchUps:o,matchUpsMap:e}}function LP({finishingPositions:t,drawDefinition:e,structureId:r}){let{roundProfile:n}=Dd({drawDefinition:e,structureId:r});return(n&&Object.keys(n))?.reduce((i,s)=>(rO(n?.[s]).forEach(c=>{t.forEach(u=>{pG({position:u,rangeDefinition:c})&&(i[u]={roundNumber:s})})}),i),{})}function pG({position:t,rangeDefinition:e}){if(!Array.isArray(e)||e.reduce((i,s)=>i||isNaN(s),!1))return!1;let[r,n]=e;return et(r,(n||r)+1).includes(t)}function rO(t){return[ut(t?.finishingPositionRange?.loser||[]),ut(t?.finishingPositionRange?.winner||[])]}function nO(t){return rO(t).map(e=>et(e[0],e[1]&&e[1]+1||e[0]+1))}function yc({drawDefinition:t,structureIds:e,matchUpsMap:r}){if(e&&!Array.isArray(e))return{error:G,context:{structureIds:e}};if(!t)return{error:Z};e=e??(t.structures??[]).filter(a=>a.stage!==ct).map(({structureId:a})=>a);let n=e.map(a=>{let{roundProfile:c}=Dd({drawDefinition:t,matchUpsMap:r,structureId:a});return(c&&Object.values(c))?.map(nO).flat()}).flat(),o=n.filter(a=>a?.length===1).sort(me).flat();return{positionsNotPlayedOff:ut(n.flat()).filter(a=>!o.includes(a)),positionsPlayedOff:o}}function VS({excludeRoundNumbers:t=[],playoffPositions:e=[],drawDefinition:r,structureId:n}){if(!r)return{error:Z};if(!n)return{error:Ur};if(!e)return{error:st,info:"missing playoffPositions"};let o=yc({drawDefinition:r});if(o.error)return o;let i=o.positionsPlayedOff,s=e.filter(S=>!i.includes(S)),a=LP({finishingPositions:s,drawDefinition:r,structureId:n}),u=Object.values(a).reduce((S,T)=>S.includes(T.roundNumber)?S:S.concat(T.roundNumber),[]).map(S=>pt(S)).filter(S=>!t.includes(S)),p=LP({finishingPositions:i,drawDefinition:r,structureId:n}),m=p?Object.values(p):[],d=p?m.reduce((S,T)=>S.includes(T.roundNumber)?S:S.concat(T.roundNumber),[]).map(S=>pt(S)):[],l=u.filter(S=>!d.includes(S)).sort(me),{roundProfile:f}=Dd({drawDefinition:r,structureId:n}),g=l.map(S=>{let T=f?.[S].finishingPositionRange.loser,[y,P]=T??[0,0];return et(y,(P||y)+1)}).flat().sort(me),{playoffRoundsRanges:I}=mG({playoffSourceRounds:l,roundProfile:f}),h=[...l,...d];return{playoffPositionsReturned:g,playedOffSourceRounds:d,playoffRoundsRanges:I,playoffSourceRounds:l,sourceRounds:h,roundProfile:f}}function mG({playoffSourceRounds:t,roundProfile:e}){return{playoffRoundsRanges:t.map(n=>{let o=e[n].finishingPositionRange.loser,[i,s]=o,a=et(i,(s||i)+1);return{finishingPositionRange:o.join("-"),finishingPositions:a,roundNumber:n}})}}function Du({drawDefinition:t,structureId:e}){if(!t)return{error:Z};let{matchUps:r,matchUpsMap:n}=or({inContext:!0,drawDefinition:t}),{positionsNotPlayedOff:o,positionsPlayedOff:i}=yc({drawDefinition:t,matchUpsMap:n}),{structures:s}=gn({drawDefinition:t}),a=s.filter(u=>!e&&u.stage!==$e||u.structureId===e),c={};for(let u of a){let p=u?.structureId,m=dG({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 dG({playoffPositions:t,drawDefinition:e,structure:r,matchUps:n}){let o=r?.structureId,{links:i}=Ws({drawDefinition:e,structureId:o});if(r.structureType===Ge||r.structures){let l=bt({structure:r})?.positionAssignments?.length,f=r.structures.length,g=(l??0)/f,I=i.source?.flatMap(({source:D})=>D?.finishingPositions||[])||[],h=et(1,g+1).filter(D=>!I.includes(D)),S=n.find(D=>D.containerStructureId===o&&D.finishingPositionRange)?.finishingPositionRange?.winner||[0,1],T=i?.source.map(({target:D})=>D.structureId),{positionsPlayedOff:y=[],positionsNotPlayedOff:P=[]}=yc({structureIds:T,drawDefinition:e}),U=[...y,...P],A=et(S[0],S[1]+1).filter(D=>!U.includes(D)),E=Ae(A,A.length/h.length),N=h.map((D,M)=>{let R=E[M],b=[Math.min(...R||[]),Math.max(...R||[])].join("-");return{finishingPosition:D,finishingPositions:R,finishingPositionRange:b}});return{positionsNotPlayedOff:A,playoffFinishingPositionRanges:N,finishingPositionsAvailable:h,finishingPositionsPlayedOff:I,positionsPlayedOff:y,groupCount:f,groupSize:g}}let s=i?.source?.filter(l=>l.linkCondition!==On).map(l=>l.source?.roundNumber)||[],a=i?.source?.filter(l=>l.linkCondition===On).map(l=>l.source?.roundNumber)||[],c=VS({excludeRoundNumbers:s,playoffPositions:t,drawDefinition:e,structureId:o}),u=c?.playoffSourceRounds?[...c?.playoffSourceRounds||[]]:void 0,p=[...c?.playoffRoundsRanges||[]],{roundProfile:m,error:d}=c;for(let l of a){let f=i?.source.find(T=>T.source.roundNumber===l),g=f?.target.roundNumber,I=f?.target.structureId,h=n.filter(({roundNumber:T,structureId:y})=>y===I&&T===g),S=h.filter(({sides:T})=>T.find(y=>y.participantFed&&!y.participantId)).length;if(u&&S===h.length){u.push(l);let T=m?.[l]?.finishingPositionRange?.loser;if(T){let y=Math.min(...T),P=y+S,U=et(y,P),A={finishingPositionRange:[y,P-1].join("-"),finishingPositions:U,roundNumber:l};p.push(A)}}}return u&&u.sort(me),p.sort((l,f)=>l.roundNumber-f.roundNumber),{playoffRounds:u,playoffRoundsRanges:p,error:d}}function oO({playoffGroups:t,drawDefinition:e,structureId:r}){if(!e)return{error:Z};if(!Vt(r)||!Array.isArray(t))return{error:G};let n=t.map(({finishingPositions:a})=>a).flat();return{positionRangeMap:Du({drawDefinition:e,structureId:r}).playoffFinishingPositionRanges?.filter(a=>n.includes(a.finishingPosition))?.reduce((a,c)=>(a[c.finishingPosition]=c,a),{})}}function BS(t){let{finishingPositionOffset:e=0,playoffAttributes:r,stageSequence:n=1,staggeredEntry:o,structureName:i,stage:s=nt,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?ci(l):Cn(l),g=hn({structureName:i||r?.["0"]?.name||Qe(nt),structureId:c||d?.pop(),stageSequence:n,matchUpType:a,matchUps:f,stage:s}),I=[g],h=[];if(p>2){let S=p/2,{matchUps:T}=Cn({finishingPositionOffset:e+S,idPrefix:u&&`${u}-c`,drawSize:S,matchUpType:a,isMock:m}),y=Qe(qe),P=r?.["0-1"]?.name??t.consolationStructureName??(i?`${i} ${y}`:y),U=hn({structureName:P,matchUps:T,structureId:d?.pop(),stage:qe,stageSequence:1,matchUpType:a});I.push(U);let A={linkType:ro,source:{roundNumber:1,structureId:g.structureId},target:{roundNumber:1,feedProfile:En,structureId:U.structureId}};h.push(A)}return{...C,structures:I,links:h}}function HS({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 et(1+e,n+1+e).map(p=>{let m=u?.[p-1]?u[p-1]:p%2&&En||li,d=p-e<=2?p-e:(p-e-2)*2+2,l={linkType:ro,source:{roundNumber:p,structureId:r.structureId},target:{feedProfile:m,roundNumber:d,structureId:t.structureId}},f=c[p-1];return f&&(l.target.groupedOrder=f),Pr()&&(l.source.structureName=r.structureName,l.target.structureName=t.structureName),p===2&&i&&(l.linkCondition=On,l.target.feedProfile=En),a.includes(d)?l:void 0}).filter(Boolean)}function WS(t){let{playoffStructureNameBase:e,finishingPositionOffset:r,stageSequence:n=1,playoffAttributes:o,structureNameMap:i,staggeredEntry:s,stage:a=nt,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?ci(f):Cn(f),h=t.structureName??o?.["0"]?.name??Qe(nt),S=Ss({structureId:u||l?.pop(),structureName:h,stageSequence:n,matchUpType:c,matchUps:g,stage:a}),T=[S],y=[];if(p>2){let A=[0,2].slice(0,p/16).map((E,N)=>{let D=N+1,{consolationStructure:M}=lG({idPrefix:m&&`${m}-c${N}`,structureId:l?.pop(),playoffStructureNameBase:e,playoffAttributes:o,structureNameMap:i,stageSequence:D,roundOffset:E,matchUpType:c,drawSize:p,isMock:d,index:N,uuids:l});T.push(M);let R=HS({consolationStructure:M,roundsCount:2,mainStructure:S,roundOffset:E});return{consolationStructure:M,links:R}}).map(E=>E.links).flat();if(y.push(...A),p>=4&&p<=16||p>32){let{matchUps:E}=Cn({idPrefix:m&&`${m}-p3t4`,finishingPositionOffset:2,drawSize:2,matchUpType:c,isMock:d}),N=o?.["3-4"]?.name??Qe(de),D=i?.[N]||N,M=e?`${e} ${D}`:D,R=Ss({structureId:l?.pop(),matchUps:E,stageSequence:2,stage:de,structureName:M,matchUpType:c}),b={linkType:ro,source:{roundNumber:I-1,structureId:S.structureId},target:{structureId:R.structureId,feedProfile:En,roundNumber:1}};T.push(R),y.push(b)}}return{structures:T,links:y,...C}}function lG({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}=ci({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||`${Qe(qe)} ${p+1}`,h=n?.[I]||I,S=t?`${t} ${h}`:h;return{consolationStructure:Ss({matchUps:l,stage:qe,structureName:S,stageSequence:e,matchUpType:i,structureId:s}),consolationRoundsCount:f}}function Ac(t){let{finishingPositionOffset:e,stageSequence:r=1,playoffAttributes:n,feedsFromFinal:o,staggeredEntry:i,structureName:s,stage:a=nt,structureId:c,matchUpType:u,skipRounds:p,feedRounds:m,idPrefix:d,drawSize:l,isMock:f,uuids:g,fmlc:I}=t,h=t.feedPolicy||t.policyDefinitions?.[rc]||t.appliedPolicies?.[rc],S={finishingPositionOffset:e,matchUpType:u,skipRounds:p,drawSize:l,idPrefix:d,isMock:f,uuids:g},{matchUps:T}=i?ci(S):Cn(S),y=hn({structureName:s||n?.["0"]?.name||Qe(nt),structureId:c||g?.pop(),stageSequence:r,matchUpType:u,matchUps:T,stage:a}),P=[y],U=[],A=l/2,{matchUps:E,roundsCount:N}=ci({finishingPositionOffset:A,idPrefix:d&&`${d}-c`,isConsolation:!0,feedsFromFinal:o,baseDrawSize:A,matchUpType:u,feedRounds:m,skipRounds:p,isMock:f,uuids:g,fmlc:I});if(l>2){let D=n?.["0-1"]?.name??Qe(qe),M=t.playoffStructureNameBase?`${t.playoffStructureNameBase} ${D}`:D,R=hn({matchUps:E,structureId:g?.pop(),stage:qe,stageSequence:1,structureName:M,matchUpType:u});P.push(R);let b=HS({consolationStructure:R,mainStructure:y,roundsCount:N,feedPolicy:h,fmlc:I});U.push(...b)}return{...C,structures:P,links:U}}function YS({requireSequential:t=!0,playoffMatchUpFormat:e,playoffAttributes:r,sourceStructureId:n,policyDefinitions:o,stageSequence:i,drawDefinition:s,playoffGroups:a,matchUpType:c,feedPolicy:u,groupCount:p,idPrefix:m,isMock:d,uuids:l}){u=u||o?.[rc];let f="processPlayoffGroups",g=0,I=[],h=[],S=[],{error:T,positionRangeMap:y}=oO({structureId:n,drawDefinition:s,playoffGroups:a});if(T)return _({result:{error:T},stack:f});if(!(!y||a?.every(U=>{let{finishingPositions:A=[]}=U;if(!A.length)return!1;let E=[...A].sort(me).map((N,D)=>(A[D+1]||N)-N).every(N=>N<2);return(!t||E)&&A.every(N=>y[N])})))return _({context:{validFinishingPositions:Object.values(y)},result:{error:G},stack:f});for(let U of a){let A=U.finishingPositions,E=y&&A.map(F=>y[F]?.finishingPositions).flat(),N=p*A.length,D=es(N),M=D===2&&go||U.drawType||go;E&&(g=Math.min(...E)-1);let R=E&&`${Math.min(...E)}-${Math.max(...E)}`,b=U.structureName||R&&U.playoffAttributes?.[R]?.name||U.playoffAttributes?.["0"]?.name,O={...{addNameBaseToAttributeName:U.addNameBaseToAttributeName,playoffStructureNameBase:U.playoffStructureNameBase,finishingPositionNaming:U.finishingPositionNaming,finishingPositionLimit:U.finishingPositionLimit,structureId:U.structureId??l?.pop(),playoffAttributes:U.playoffAttributes,structureNameMap:U.structureNameMap,sequenceLimit:U.sequenceLimit,structureName:b},idPrefix:m&&`${m}-po`,appliedPolicies:o,finishingPositionOffset:g,stage:de,stageSequence:i,matchUpType:c,drawSize:D,isMock:d,uuids:l},x=({playoffStructures:F,playoffLinks:L})=>{let[w]=F,V=jS({playoffStructureId:w.structureId,finishingPositions:A,sourceStructureId:n});S.push(V),S.push(...L),h.push(...F),I.push({structureId:w.structureId,finishingPositions:A}),g+=N};if(M===go){let{matchUps:F}=Cn({finishingPositionLimit:g+N,idPrefix:m&&`${m}-po`,finishingPositionOffset:g,matchUpType:c,drawSize:D,isMock:d,uuids:l}),L=hn({structureId:U.structureId??l?.pop(),matchUpFormat:e,stage:de,structureName:b,stageSequence:i,matchUps:F});h.push(L);let w=jS({playoffStructureId:L.structureId,finishingPositions:A,sourceStructureId:n});S.push(w),g+=N,I.push({structureId:L.structureId,finishingPositions:A})}else if([zc,Qc,de].includes(M)){let F={playoffAttributes:U.playoffAttributes??r,playoffStructureNameBase:U.playoffStructureNameBase,structureId:U.structureId??l?.pop(),structureName:U.structureName,idPrefix:m&&`${m}-po`,addNameBaseToAttributeName:!0,finishingPositionOffset:g,stage:de,roundOffset:0,stageSequence:i,drawSize:D,isMock:d,uuids:l};M===zc?Object.assign(F,{playoffAttributes:U?.playoffAttributes??r??yf,roundOffsetLimit:3}):M===Qc&&Object.assign(F,{playoffAttributes:U?.playoffAttributes??r??Af,roundOffsetLimit:2});let L=Tc(F);if(L.error)return L;if(L.links?.length&&S.push(...L.links),L.structures?.length&&h.push(...L.structures),h.sort(Ti),L.structureId){let w=jS({playoffStructureId:L.structureId,finishingPositions:A,sourceStructureId:n});S.push(w),I.push({structureId:L.structureId,finishingPositions:A})}g+=N}else if([Jc,mp,wm,xm,_m,Lm].includes(M)){let F=[l?.pop(),l?.pop()],L={playoffStructureNameBase:U.playoffStructureNameBase,structureId:U.structureId??l?.pop(),playoffAttributes:U.playoffAttributes,idPrefix:m&&`${m}-po`,finishingPositionOffset:g,uuids:F,stage:de,structureName:b,matchUpType:c,feedPolicy:u,drawSize:D,isMock:d},w={[Jc]:{fmlc:!0,feedRounds:1},[Lm]:{feedRounds:1},[wm]:{feedsFromFinal:3},[xm]:{feedsFromFinal:2},[_m]:{feedsFromFinal:1}};Object.assign(L,w[M]||{});let{structures:V,links:k}=Ac(L),[W]=V,H=jS({playoffStructureId:W.structureId,finishingPositions:A,sourceStructureId:n});S.push(H),S.push(...k),h.push(...V),I.push({structureId:W.structureId,finishingPositions:A}),g+=N}else if([Nn].includes(M)){let{structures:F,links:L}=Na({...O,structureOptions:U.structureOptions||{groupSize:4}});x({playoffStructures:F,playoffLinks:L})}else if([pp].includes(M)){let{structures:F,links:L}=BS(O);x({playoffStructures:F,playoffLinks:L})}else if([XC].includes(M)){let{structures:F,links:L}=WS(O);x({playoffStructures:F,playoffLinks:L})}else if([$r].includes(M)){let F=hn({structureId:U.structureId??l?.pop(),structureName:U.structureName,finishingPosition:td,stage:de,stageSequence:i,matchUps:[]});x({playoffStructures:[F],playoffLinks:[]})}}return{finishingPositionTargets:I,positionRangeMap:y,structures:h,links:S}}function jS({playoffStructureId:t,finishingPositions:e,sourceStructureId:r}){return{linkType:eo,source:{structureId:r,finishingPositions:e},target:{structureId:t,feedProfile:dn,roundNumber:1}}}function Ra({matchUp:t,tieFormat:e,isMock:r,uuids:n}){let{collectionDefinitions:o}=e??{};return{tieMatchUps:(o??[]).map(s=>Nu({matchUp:t,collectionDefinition:s,uuids:n,isMock:r})).filter(Boolean).flat()}}function Nu({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()??Dt();let l=e?.collectionId;return i?.pop()??`${n?.matchUpId}-${l}-TMU-${d+1}`};return et(0,p).map(d=>{let l=t+d+1;return{sides:[{sideNumber:1},{sideNumber:2}],matchUpId:m(d),matchUpStatus:Qt,collectionPosition:l,collectionId:c,processCodes:u,matchUpType:a,isMock:o}})}function iO(t){let e="generateAndPopulateRRplayoffStructures";if(!t.playoffGroups)return _({result:{error:st},info:"playoffGroups required",stack:e});let{sourceStructureId:r,requireSequential:n,tournamentRecord:o,drawDefinition:i,playoffGroups:s,groupCount:a,groupSize:c,event:u}=t,p=YS({requireSequential:n,sourceStructureId:r,playoffGroups:s,groupCount:a,groupSize:c,...t});if(p.error)return _({result:p,stack:e});let{structures:m=[],links:d=[],finishingPositionTargets:l,positionRangeMap:f}=p,g=l?.map(({finishingPositions:E})=>E).flat().map(E=>f[E].finishingPositions).flat();i.structures.push(...m),i.links.push(...d);let{matchUps:I,matchUpsMap:h}=se({inContext:!0,drawDefinition:i}),S=m.map(({structureId:E})=>E),T=I?.filter(({structureId:E})=>S.includes(E)).map(Ee),y=h?.drawMatchUps?.filter(({matchUpId:E})=>T?.includes(E));if(y?.length){let E=We({drawDefinition:i,event:u})?.tieFormat;E&&y.forEach(N=>{let{tieMatchUps:D}=Ra({isMock:t.isMock,tieFormat:E,matchUp:N});Object.assign(N,{tieMatchUps:D,matchUpType:xr})})}let{positionAssignments:P}=bt({structureId:r,drawDefinition:i}),U={};P?.forEach(E=>{let M=dt({element:E,name:Zo})?.extension?.value?.groupOrder;M&&(U[M]||(U[M]=[]),U[M].push(E.participantId))});let A=Ks({provisionalPositioning:t.provisionalPositioning,structureId:r,applyPositioning:!0,event:t.event,tournamentRecord:o,drawDefinition:i});return A.error&&A.error?.code!==wl.code?_({result:A,stack:e}):{structures:m,links:d,positionsPlayedOff:g,drawDefinition:i,...C}}function Mu({value:t,sourceRange:e,targetRange:r}){let n=Math.min(...e),o=Math.max(...e),i=Math.min(...r),s=Math.max(...r);return(t-n)*(s-i)/(o-n)+i}var Qn="ELO",FP="NTRP",fG="TRN",kP="UTR",Pg="WTN",sO={ELO:Qn,NTRP:FP,TRN:fG,UTR:kP,WTN:Pg};var gG={[Qn]:{defaultInitialization:1500,decimalsCount:0,range:[0,3e3],ascending:!0},[FP]:{accessors:["ntrpRating","dntrpRatingHundredths"],attributes:{ustaRatingType:""},accessor:"dntrpRatingHundredths",defaultInitialization:3,decimalsCount:1,ascending:!0,range:[1,7]},[kP]:{defaultInitialization:6,accessors:["utrRating"],accessor:"utrRating",decimalsCount:2,ascending:!0,range:[1,16]},[Pg]:{attributes:{confidence:{generator:!0,range:[60,100]}},accessors:["wtnRating","confidence"],defaultInitialization:23,accessor:"wtnRating",ascending:!1,decimalsCount:2,range:[40,1]}},we=gG;function aO({sourceRatingType:t,sourceRating:e}){let r=we[t].range,n=r[0]>r[1],o=we[Qn].range;return Mu({value:n?r[0]-e:e,sourceRange:r,targetRange:o})}function cO({targetRatingType:t,sourceRating:e}){let r=we[t].decimalsCount||0,n=we[t].range,o=n[0]>n[1],i=Math.max(...n),s=we[Qn].range,a=Mu({targetRange:n,sourceRange:s,value:e}),c=parseFloat(a.toFixed(r));return o?i-c:c}function GP(t){let e=rt(t,[{ratings:!0,[He]:Kr}]);if(e.error)return e;let r=t.matchUpType&&[Ft,_t].includes(t.matchUpType)?t.matchUpType:Ft,n=Object.keys(we),o=t.targetRatingType&&n.includes(t.targetRatingType)?t.targetRatingType:Qn,i=t.ratings[r]?t.ratings[r].reduce((d,l)=>d.includes(l.scaleName)?d:d.concat(l.scaleName),[]):[];if(!i)return{error:ve};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=we[s.scaleName].accessor,u=c?s.scaleValue[c]:s.scaleValue,p=aO({sourceRatingType:a,sourceRating:u});return{convertedRating:cO({targetRatingType:o,sourceRating:p}),sourceRating:u}}function uO({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?.[Ft]&&s?.[Ft]){let a=Qn,{convertedRating:c}=GP({ratings:i,targetRatingType:a}),{convertedRating:u}=GP({ratings:s,targetRatingType:a}),{side1pressure:p,side2pressure:m}=IG({side1ConvertedRating:c,side2ConvertedRating:u,score:r});p&&t[n?.participantId].pressureScores.push(p),m&&t[o?.participantId].pressureScores.push(m);let d=Math.max(...we[Qn].range),l=_l((u-c)/d),f=_l((c-u)/d);t[n?.participantId].ratingVariation.push(l),t[o?.participantId].ratingVariation.push(f)}}function IG({side1ConvertedRating:t,side2ConvertedRating:e,score:r}){let n=t>e?t:e,o=t>e?e:t,i=Math.abs(t-e),s=we[Qn].range,a=Math.max(...s),c=(a-n)*0,p=(n+c)/a*i,m=r?.sets?.reduce((T,y)=>T+(y?.side1Score??0),0),d=r?.sets?.reduce((T,y)=>T+(y.side2Score??0),0),l=t>e?2:1,f=(m||0)*(o+(l===1?p:0)),g=(d||0)*(o+(l===2?p:0)),I=f+g,h=I?_l(f/I):0,S=I?_l(g/I):0;return{side1pressure:h,side2pressure:S}}function Dg({winningSide:t,matchUpFormat:e=Dn,matchUpStatus:r,tallyPolicy:n,score:o}){let i=[0,0],s=o?.sets,a=typeof t=="number"&&t-1,c=Ye(e),u=VP(c?.bestOf??1);if(typeof a=="number"&&(r===Mt&&n?.setsCreditForDefaults||r===Ct&&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===rr&&(+i[1-a]===u&&(i[1-a]-=1),n?.setsCreditForRetirements&&(i[a]=u)),i}function qS({matchUpFormat:t=Dn,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=Ye(t),c=a?.bestOf??1,u=VP(c),p=a?.setFormat?.tiebreakAt||0,m=[[],[]];if(typeof s=="number"&&(r===Mt&&n?.gamesCreditForDefaults||r===Ct&&n?.gamesCreditForWalkovers)){let d=a?.setFormat?.setTo||0,l=u*d;m[s].push(l)}else i.forEach((d,l)=>{let g=(d.setNumber||l+1)>u&&a?.finalSetFormat?"finalSetFormat":"setFormat",I=a?.[g]?.based,h=a?.[g].tiebreakSet,{side1Score:S,side2Score:T}=d;pO(I)&&(m[0].push(pt(S||0)),m[1].push(pt(T||0))),h&&d.winningSide&&n?.gamesCreditForTiebreakSets!==!1&&m[d.winningSide-1].push(1)});if(r===rr&&typeof s=="number"){let d=i.length>u&&a?.finalSetFormat?"finalSetFormat":"setFormat",l=a?.[d];if(pO(l.based)){let f=l?.setTo||0,g=S=>{if(!(!a||S===""))return+S===p-1||+S===p?pt(p||0)+1:+S<p?f:p},I=Dg({winningSide:e,score:{sets:i},matchUpStatus:r,matchUpFormat:t,tallyPolicy:n});if(m.map(S=>S[s]<=S[1-s]).reduce((S,T)=>S+(T?1:0),0)>I[1-s]){let S=m[s].length,T=g(m[1-s][S-1]);T&&(m[s][S-1]=T)}u>m[s].length&&n?.gamesCreditForRetirements&&m[s].push(f)}}return[m[0].reduce((d,l)=>d+l,0),m[1].reduce((d,l)=>d+l,0)]}function $S({matchUpFormat:t,score:e}){let r=t?Ye(t):void 0,n=r?.bestOf??1,o=VP(n),i=[0,0],s=[0,0];return e?.sets?.forEach((a,c)=>{let p=(a.setNumber||c+1)>o&&r?.finalSetFormat?"finalSetFormat":"setFormat",m=r?.[p]?.based;if(mO(m)){let{side1Score:d,side2Score:l}=a;d&&(s[0]+=pt(d||0)),l&&(s[1]+=pt(l||0))}else a.side1TiebreakScore&&(s[0]+=pt(a.side1TiebreakScore||0)),a.side2TiebreakScore&&(s[1]+=pt(a.side2TiebreakScore||0)),(a.side1TiebreakScore||a.side2TiebreakScore)&&a.winningSide&&(i[a.winningSide-1]+=1)}),{pointsTally:s,tiebreaksTally:i}}function VP(t){return t&&Math.ceil(t/2)||1}function mO(t){return t==="P"}function pO(t){return!mO(t)}function dO({participantResults:t,matchUpFormat:e,tallyPolicy:r,perPlayer:n,totalSets:o}){let i=e&&Ye(e)||{},s=i.bestOf,a=s&&Math.ceil(s/2)||1,c=i.setFormat?.setTo;Object.keys(t).forEach(u=>{let p=t[u].setsWon,m=t[u].setsLost,d=r?.groupTotalSetsPlayed?o:n*(a||0)||p+m,l=Math.round(p/d*1e3)/1e3;(l===1/0||isNaN(l))&&(l=d);let f=t[u].tieMatchUpsWon,g=t[u].tieMatchUpsLost,I=f+g,h=Math.round(f/I*1e3)/1e3;(h===1/0||isNaN(h))&&(h=f);let S=t[u].matchUpsWon,T=t[u].matchUpsLost,y=S+T,P=Math.round(S/y*1e3)/1e3;(P===1/0||isNaN(P))&&(P=S);let U=t[u].gamesWon||0,A=t[u].gamesLost||0,E=(n||0)*(a||0)*(c||0),N=Math.max(E,U+A),D=Math.round(U/N*1e3)/1e3;(D===1/0||isNaN(D))&&(D=0);let M=t[u].pointsWon+t[u].pointsLost,R=Math.round(t[u].pointsWon/M*1e3)/1e3;(R===1/0||isNaN(R))&&(R=0),t[u].setsWon=p,t[u].setsLost=m,t[u].setsPct=l,t[u].tieMatchUpsWon=f,t[u].tieMatchUpsPct=h,t[u].matchUpsPct=P,t[u].gamesWon=U,t[u].gamesLost=A,t[u].gamesPct=D,t[u].pointsPct=R,t[u].result=`${t[u].matchUpsWon}/${t[u].matchUpsLost}`})}function Ru({participantIds:t,pressureRating:e,matchUpFormat:r,tallyPolicy:n,perPlayer:o,matchUps:i}){let s={},a=n?.excludeMatchUpStatuses||[],c=i?.filter(m=>(m.tieMatchUps||!a.includes(m.matchUpStatus))&&(!t?.length||Yt(t,[Nd(m,0),Nd(m,1)]).length===2)),p=c?.flatMap(({score:m,tieMatchUps:d})=>d?d.filter(({matchUpStatus:l})=>!a.includes(l)).flatMap(({score:l})=>l?.sets?.length??0):m?.sets?.length??0)?.reduce((m,d)=>m+d,0);for(let m of c??[]){let{matchUpStatus:d,tieMatchUps:l,tieFormat:f,score:g,winningSide:I,sides:h}=m,S=f&&m._disableAutoCalc&&f.collectionDefinitions.every(({scoreValue:A})=>A),T=I&&hG(m),y=I&&SG(m);if(!T&&!y)if(d&&ce.includes(d)){let A=Nd(m,0),E=Nd(m,1);A&&(Ec(s,A),s[A].matchUpsCancelled+=1),E&&(Ec(s,E),s[E].matchUpsCancelled+=1)}else if(l?.length){o=0;for(let A of l){if(A.winningSide){let E=h?.find(({sideNumber:D})=>D===A.winningSide)?.participantId,N=h?.find(({sideNumber:D})=>D===A.winningSide)?.participantId;E&&N&&(Ec(s,E),Ec(s,N),s[E].tieMatchUpsWon+=1,s[N].tieMatchUpsLost+=1,ue(Ft)(A.matchUpType)?(s[E].tieSinglesWon+=1,s[N].tieSinglesLost+=1):ue(_t)(A.matchUpType)&&(s[E].tieDoublesWon+=1,s[N].tieDoublesLost+=1))}lO({score:A.score,manualGamesOverride:S,participantResults:s,sides:h})}}else lO({manualGamesOverride:S,participantResults:s,score:g,sides:h});else if(Ec(s,T),Ec(s,y),l?.length){o=0;for(let A of l){let{matchUpType:E}=A,N=ue(_t)(E),D=ue(Ft)(E);A.winningSide&&(A.winningSide===I?(T&&(s[T].tieMatchUpsWon+=1,D&&(s[T].tieSinglesWon+=1),N&&(s[T].tieDoublesWon+=1)),y&&(s[y].tieMatchUpsLost+=1,D&&(s[y].tieSinglesLost+=1),N&&(s[y].tieDoublesLost+=1))):A.winningSide!==I&&(y&&(s[y].tieMatchUpsWon+=1,D&&(s[y].tieSinglesWon+=1),N&&(s[y].tieDoublesWon+=1)),T&&(s[T].tieMatchUpsLost+=1,D&&(s[T].tieSinglesLost+=1),N&&(s[T].tieDoublesLost+=1)))),fO({matchUpFormat:A.matchUpFormat,matchUpStatus:A.matchUpStatus,matchUpType:A.matchUpType,score:A.score,sides:A.sides,winningParticipantId:T,losingParticipantId:y,manualGamesOverride:S,participantResults:s,isTieMatchUp:!0,pressureRating:e,tallyPolicy:n,winningSide:I})}gO({winningParticipantId:T,losingParticipantId:y,participantResults:s,matchUpStatus:d})}else fO({matchUpFormat:m.matchUpFormat??r,matchUpType:m.matchUpType,isTieMatchUp:void 0,winningParticipantId:T,manualGamesOverride:S,losingParticipantId:y,participantResults:s,pressureRating:e,matchUpStatus:d,tallyPolicy:n,winningSide:I,score:g,sides:h});let P=g?.sets?.reduce((A,E)=>A+(E?.side1Score??0),0),U=g?.sets?.reduce((A,E)=>A+(E.side2Score??0),0);if(S){let A=h?.find(({sideNumber:N})=>N===1)?.participantId,E=h?.find(({sideNumber:N})=>N===2)?.participantId;Ec(s,A),Ec(s,E),A&&(s[A].gamesWon+=P,s[A].gamesLost+=U),E&&(s[E].gamesWon+=U,s[E].gamesLost+=P)}}return dO({participantResults:s,matchUpFormat:r,tallyPolicy:n,perPlayer:o,totalSets:p}),{participantResults:s}}function hG(t){let e=t.winningSide-1;return Nd(t,e)}function SG(t){let e=1-(t.winningSide-1);return Nd(t,e)}function Nd(t,e){if(!t?.sides)return console.log("no sides:",{matchUp:t}),"foo";let r=t.sides[e];return r?r.participantId:(console.log("No Side",{matchUp:t,index:e}),"foo")}function Ec(t,e){e&&!t[e]&&(t[e]={allDefaults:0,defaults:0,defeats:[],gamesLost:0,gamesWon:0,matchUpsCancelled:0,matchUpsLost:0,matchUpsWon:0,pointsLost:0,pointsWon:0,pressureScores:[],ratingVariation:[],retirements:0,setsLost:0,setsWon:0,tieSinglesWon:0,tieSinglesLost:0,tieDoublesWon:0,tieDoublesLost:0,tieMatchUpsLost:0,tieMatchUpsWon:0,victories:[],walkovers:0})}function lO({manualGamesOverride:t,participantResults:e,score:r,sides:n}){let{sets:o}=r||{},i=[[],[]],s=[0,0];for(let c of o||[]){let{winningSide:u,side1Score:p,side2Score:m}=c;u&&(s[u-1]+=1),i[0].push(pt(p||0)),i[1].push(pt(m||0))}let a=[i[0].reduce((c,u)=>c+u,0),i[1].reduce((c,u)=>c+u,0)];n.forEach((c,u)=>{let{participantId:p}=c;p&&(Ec(e,p),e[p].setsWon+=s[u],e[p].setsLost+=s[1-u],t||(e[p].gamesWon+=a[u],e[p].gamesLost+=a[1-u]))})}function fO({winningParticipantId:t,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===Ft&&uO({participantResults:n,sides:d,score:m}),a||gO({winningParticipantId:t,losingParticipantId:r,participantResults:n,matchUpStatus:s});let g=Dg({matchUpStatus:s,matchUpFormat:i,tallyPolicy:u,winningSide:p,score:m}),I=qS({matchUpStatus:s,matchUpFormat:i,tallyPolicy:u,winningSide:p,score:m}),{pointsTally:h}=$S({score:m,matchUpFormat:i});t&&(n[t].setsWon+=g[l],n[t].setsLost+=g[f],e||(n[t].gamesWon+=I[l],n[t].gamesLost+=I[f]),n[t].pointsWon+=h[l],n[t].pointsLost+=h[f]),r&&(n[r].setsWon+=g[f],n[r].setsLost+=g[l],e||(n[r].gamesWon+=I[f],n[r].gamesLost+=I[l]),n[r].pointsWon+=h[f],n[r].pointsLost+=h[l])}function gO({winningParticipantId:t,losingParticipantId:e,participantResults:r,matchUpStatus:n}){e&&(n===Ct&&(r[e].walkovers+=1),n===Mt&&(r[e].defaults+=1),n===rr&&(r[e].retirements+=1),[Mt,rr,Ct].includes(n)&&(r[e].allDefaults+=1),r[e].matchUpsLost+=1),t&&(r[t].matchUpsWon+=1),e&&t&&(r[e].defeats.push(t),r[t].victories.push(e))}function IO({matchUps:t,order:e,report:r}){let n={};t.forEach(({sides:i})=>{i.forEach(s=>{s.participantId&&s.participant&&(n[s.participantId]=s.participant.participantName)})});let o=[];return Array.isArray(r)&&r.forEach((i,s)=>{if(i.excludedDirectives?.length){let a=i.excludedDirectives.map(({attribute:p})=>p).join(", "),c=`${a.length} directives were excluded due to participants limit}`;o.push(c);let u=`Excluded: ${a}`;o.push(u)}else{let a=(l,f)=>parseFloat(i.reversed?l:f)-parseFloat(i.reversed?f:l),c=i.groups?Object.values(i.groups).flat(1/0).length:i.participantIds?.length??0,u=l=>{l.groups&&Object.keys(l.groups).sort(a).forEach(f=>{let g=l.groups[f].map(h=>n[h]).join(", "),I=`${f} ${l.attribute}: ${g}`;o.push(I)})},p=i.reversed?" in reverse order":"",m=i.groups?"grouped":"separated",d=`Step ${s+1}: ${c} particiants were ${m}${p} by ${i.attribute}`;if(o.push(d),i.idsFilter){let l=`${i.attribute} was calculated considering ONLY TIED PARTICIPANTS`;o.push(l)}u(i)}o.push("----------------------")}),o.push("Final Order:"),e.forEach(i=>{let{participantId:s,resolved:a}=i,c=i.groupOrder||i.provisionalOrder;o.push(`${c}: ${n[s]} => resolved: ${!!a}`)}),o.join(`\r
|
|
4
4
|
`)}function BP({participantResults:t,participantIds:e,attribute:r}){return HP({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 HP(t){return(t.participantIds||Object.keys(t.participantResults)).reduce((r,n,o)=>(r.push({participantId:n,i:o,results:t.participantResults[n]}),r),[])}var TG=[{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}],WP={matchUpsPct:20,tieMatchUpsPct:16,pointsPct:4,gamesPct:8,setsPct:12};function jP(t){let{requireCompletion:e=!0,participantResults:r,subOrderMap:n,tallyPolicy:o}=t,i=[];if(e&&!yG(t))return{};let s=["tieMatchUpsWon","tieSinglesWon","tieDoublesWon","matchUpsWon","pointsWon","gamesWon","setsWon","gamesPct","setsPct","pointsPct","matchUpsPct"].includes(o?.groupOrderKey)?o.groupOrderKey:"matchUpsWon",a=BP({participantResults:r,attribute:s});i.push({attribute:s,groups:a});let p=Object.keys(a).map(S=>parseFloat(S)).sort((S,T)=>T-S).map(S=>a[S]).map(S=>{let T=hO({participantIds:S,...t});return i.push(...T.report??[]),T.order}).map((S,T)=>S.map(y=>y.resolved?y:{...y,subGroup:[T].concat(...y.subGroup??[])})).flat(),m,d=0,l=1,f;p.forEach((S,T)=>{T&&(S.resolved||f&&!S.resolved)&&(l+=1),f=S.resolved;let y=parseInt(S.subGroup?.join("")||0);S.resolved?(S.position=T+1,l=S.position):(m&&y>m&&(l+=d,d=0),S.position=l,d+=1),m=y});let g=p.map(({position:S})=>S),I=Sr(g);return p.forEach(S=>{let{participantId:T,position:y}=S||{},P=r[T];S.GEMscore=h(P);let U=I[y];S?.position!==void 0&&(U>1&&(S.ties=U,n&&(S.subOrder=n[T])),S.rankOrder=y,S.groupOrder=y+(S.subOrder||1)-1)}),{groupOrder:p,report:i.flat(1/0).filter(Boolean)};function h(S){return(Array.isArray(o?.GEMscore)?Object.keys(WP).filter(P=>o.GEMscore.includes(P)):Object.keys(WP)).map(P=>(S[P]||0)*Math.pow(10,WP[P].toFixed(3))).reduce((P,U)=>P+U,0)}}function yG({participantResults:t,participantsCount:e}){let n=HP({participantResults:t}).filter(o=>e-1===o.results.matchUpsWon+o.results.matchUpsLost+o.results.matchUpsCancelled);return e===n.length}function AG({disableHeadToHead:t,participantIds:e,matchUpFormat:r,tallyPolicy:n,attribute:o,idsFilter:i,matchUps:s,reversed:a}){let{participantResults:c}=Ru({participantIds:i&&e,matchUpFormat:r,tallyPolicy:n,matchUps:s}),u=BP({participantResults:c,participantIds:e,attribute:o}),p=[{attribute:o,reversed:a,groups:u,idsFilter:i}],m;return Object.keys(u).length>1&&e.length&&(m=Object.keys(u).map(f=>parseFloat(f)).sort((f,g)=>a?f-g:g-f).map(f=>u[f]).map(f=>{let g=hO({participantResults:c,disableHeadToHead:t,participantIds:f,matchUpFormat:r,tallyPolicy:n,matchUps:s});return p.push(...g.report??[]),g.order}).map((f,g)=>f.map(I=>I.resolved?I:{...I,subGroup:[g].concat(...I.subGroup??[])})).flat()),{order:m,report:p}}function hO({participantResults:t,disableHeadToHead:e,participantIds:r,matchUpFormat:n,tallyPolicy:o,matchUps:i}){let s=[],a=[],c;if(r?.length===1)return{order:[{resolved:!0,participantId:r[0]}]};if(r?.length===2&&(!o?.headToHead||!o.headToHead.disabled&&!e)){let m=EG({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||TG).filter(m=>{let d=!(Zt(m.maxParticipants)&&r?.length>m.maxParticipants);return d||s.push(m),d});return s.length&&a.push({excludedDirectives:s,participantIds:r}),p.every(({attribute:m,reversed:d,idsFilter:l,disableHeadToHead:f})=>(c=AG({disableHeadToHead:f,participantIds:r,matchUpFormat:n,tallyPolicy:o,attribute:m,idsFilter:l,matchUps:i,reversed:d}),a.push(c.report),!c.order)),c.order?{order:c.order,report:a}:{order:r?.map(m=>({participantId:m})),report:a}}function EG({participantIds:t,participantResults:e}){if(t){if(e[t[0]].victories.includes(t[1]))return t.map(r=>({resolved:!0,participantId:r}));if(e[t[1]].victories.includes(t[0]))return t.reverse().map(r=>({resolved:!0,participantId:r}))}}function Ca({policyDefinitions:t,generateReport:e,pressureRating:r,matchUpFormat:n,matchUps:o=[],subOrderMap:i,perPlayer:s}){if(!o?.length||!Vr(o))return{error:Jn};let a=ut(o.map(({structureId:y})=>y));if(a.length!==1)return _({result:{error:G,info:"Maximum one structureId"},stack:"tallyParticipantResults",context:{structureIds:a}});let c=o.filter(y=>y&&y.matchUpStatus!==Nt),u=c.length&&ut(c.map(({drawPositions:y})=>y).flat()).length,p=c.filter(y=>ds({matchUp:y})).length===c.length;p||(s=0);let m=o.every(({matchUpType:y,tieMatchUps:P})=>y===jt&&P?.every(U=>ds({matchUp:U}))),d=t?.[Mf],l=o.filter(y=>ds({matchUp:y})||y.matchUpType===jt),{participantResults:f}=Ru({matchUps:l,pressureRating:r,matchUpFormat:n,tallyPolicy:d,perPlayer:s}),g,I,{groupOrder:h,report:S}=jP({matchUps:l,participantResults:f,participantsCount:u,matchUpFormat:n,tallyPolicy:d,subOrderMap:i});if(r&&UG({participantResults:f}),p&&h)g=S,I=h,h.forEach(y=>{let{participantId:P,groupOrder:U,rankOrder:A,subOrder:E,ties:N,GEMscore:D}=y,M=f[P];Object.assign(M,{groupOrder:U,rankOrder:A,GEMscore:D,subOrder:E,ties:N})});else{let{groupOrder:y,report:P}=jP({requireCompletion:!1,participantResults:f,participantsCount:u,matchUpFormat:n,tallyPolicy:d,subOrderMap:i,matchUps:o});g=P,I=y,y&&y.forEach(U=>{let{participantId:A,groupOrder:E,GEMscore:N}=U,D=f[A];Object.assign(D,{provisionalOrder:E,GEMscore:N})})}let T={completedTieMatchUps:m,readableReport:"",participantResults:f,bracketComplete:p,order:[],report:g};if((p||m)&&(T.order=I),e||Pr({tally:!0})){let y=IO({matchUps:o,report:g,order:I});Pr({tally:!0})&&console.log(y),T.readableReport=y}return T}function UG({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 KS({positionAssignments:t}){let e=(t||[]).filter(Br(no)).map(i=>{let{extension:s}=dt({element:i,name:oc}),a=pt(s?.value),c=!isNaN(a)&&a;return c&&{participantId:i.participantId,subOrder:c}}).filter(Boolean),r=e.map(({subOrder:i})=>i),n=Sr(r);return{subOrderMap:Object.assign({},...e.filter(({subOrder:i})=>n[i]===1).map(({participantId:i,subOrder:s})=>({[i]:s})))}}function Md({positionAssignments:t,tournamentRecord:e,drawDefinition:r,matchUpFormat:n,matchUps:o,event:i}){if(!Vr(o))return{error:G};if(!t)return{error:G};let{policyDefinitions:s}=vo({policyTypes:[Mf],tournamentRecord:e,drawDefinition:r,event:i}),{subOrderMap:a}=KS({positionAssignments:t}),c=o.length?Ca({policyDefinitions:s,matchUpFormat:n,subOrderMap:a,matchUps:o}):void 0;if(c?.error)return c;let{participantResults:u={},bracketComplete:p,report:m}=c??{},d=Object.keys(u);return t.forEach(l=>{let{participantId:f}=l;if(d.includes(f)){let g={value:u[f],name:Zo};At({element:l,extension:g}),u[f].ties||gr({element:l,name:oc})}else gr({element:l,name:Zo}),gr({element:l,name:oc})}),Ot({drawDefinition:r}),{...C,participantResults:u,bracketComplete:p,report:m}}function zS({matchUps:t,matchUpId:e}){return{matchUp:(t||[]).find(n=>n.matchUpId===e)}}function Bt(t){let e=rt(t,[{[Ve]:!0,[ln]:!0}]);if(e.error)return e;let{tournamentParticipants:r,afterRecoveryTimes:n,contextProfile:o,drawDefinition:i,matchUpsMap:s,matchUpId:a,inContext:c,context:u,event:p}=t,{structures:m=[]}=gn({drawDefinition:i}),d=t.contextContent||o&&$n({contextProfile:o,drawDefinition:i});for(let l of m){let{matchUps:f}=Ut({tournamentParticipants:r,afterRecoveryTimes:n,contextContent:d,drawDefinition:i,contextProfile:o,matchUpsMap:s,inContext:c,structure:l,context:u,event:p}),{matchUp:g}=zS({matchUps:f,matchUpId:a});if(g)return{matchUp:g,structure:l}}return{error:Le}}function kp(t){return!ht(t)||!t.notes?{error:st}:ht(t.element)?!Vt(t.notes)&&!t.notes?.testing?{error:G}:(Object.assign(t.element,{notes:t.notes}),{...C}):{error:G}}function Ng(t){return ht(t)?ht(t.element)?(t.element.notes&&delete t.element.notes,{...C}):{error:G}:{error:st}}var Cu={matchUpStatus:Qt,matchUpStatusCodes:[],score:{scoreStringSide1:"",scoreStringSide2:"",sets:void 0},matchUpFormat:void 0,winningSide:void 0};function Gn(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,I=t.appliedPolicies&&Object.keys(t.appliedPolicies).length?t.appliedPolicies:yt({policyTypes:[en],tournamentRecord:s,drawDefinition:a,structure:o,event:d})?.appliedPolicies,h=n.matchUpType===jt;if(h&&a){if(m&&n.matchUpId!==m){let E=Bt({drawDefinition:a,matchUpId:m,event:d});if(!E.matchUp)return{error:Le};({matchUp:n,structure:o}=E)}}else n.matchUpId!==m&&console.log("!!!!!");c&&[Ct,he].includes(c)||u?Object.assign(n,{...Cu}):f&&(n.score=f);let S=c&&n?.matchUpStatus===Mt&&c!==Mt;c&&(n.matchUpStatus=c),r&&(n.matchUpFormat=r),i&&(n.matchUpStatusCodes=i),p&&(n.winningSide=p),t.removeWinningSide&&(n.winningSide=void 0),!o&&a&&({structure:o}=Bt({drawDefinition:a,matchUpId:m,event:d})),c&&!n.winningSide&&Ie(n)&&!ce.includes(c)&&![ic,ss,pn].includes(c)&&(n.matchUpStatus=Ln);let T;if((S&&n?.processCodes?.length||c===Mt)&&(T=I?.[en]?.processCodes?.incompleteAssignmentsOnDefault),!n.collectionId){let E=o?.structureType===Ge,N=cr({structure:o});if(id({drawDefinition:a,structure:o})||N||E){let D=b=>{r=h?"SET1-S:T100":r??n.matchUpFormat??b?.matchUpFormat??a?.matchUpFormat??d?.matchUpFormat;let v=h?{matchUpTypes:[jt]}:void 0,{matchUps:O}=Ut({afterRecoveryTimes:!1,tournamentRecord:s,inContext:!0,matchUpFilters:v,drawDefinition:a,structure:b,event:d});return N&&(b.positionAssignments=ut(O.flatMap(x=>(x.sides??[]).map(F=>F.participantId)).filter(Boolean)).map(x=>({participantId:x}))),Md({positionAssignments:b.positionAssignments,tournamentRecord:s,drawDefinition:a,matchUpFormat:r,matchUps:O,event:d})},M=E&&o.structures.find(b=>b?.matchUps.find(v=>v.matchUpId===m)),R=D(M||o);if(R.error)return _({result:R,stack:e})}}if(l){let E=kp({element:n,notes:l});if(E.error)return _({result:E,stack:e})}let y=s?.tournamentId,P=Lr().topics.includes(Tp),U=(P||T)&&Me({drawDefinition:a}),A=U&&se({matchUpFilters:{matchUpIds:[m]},nextMatchUps:!0,tournamentRecord:s,inContext:!0,drawDefinition:a,matchUpsMap:U}).matchUps?.[0];if(P&&A&&Sb({tournamentId:y,inContextMatchUp:A}),Array.isArray(T)&&A&&!A.sides?.every(({participantId:E})=>E))if(c===Mt)n.processCodes=ut([...n.processCodes??[],...T]);else for(let E of T||[]){let N=E&&n?.processCodes?.lastIndexOf(E);n?.processCodes?.splice(N,1)}return gt({eventId:d?.eventId,context:e,drawDefinition:a,tournamentId:y,matchUp:n}),{...C}}function Rd(t){let{matchUpStatusCodes:e,matchUpStatus:r,structure:n,matchUp:o,dualMatchUp:i,inContextMatchUp:s,autoCalcDisabled:a}=t,c=Ua({matchUpStatus:r})||[io,vr].includes(r)&&i||a,u=o?.sides?.map(I=>I.participantId).filter(Boolean).length||s?.sides?.map(I=>I.participantId).filter(Boolean).length,p="attemptToModifyScore";if(!(cr({structure:n})&&u===1||r===Mt&&u||PG({structure:n,matchUp:o,inContextMatchUp:s})||t.appliedPolicies?.[en]?.requireParticipantsForScoring===!1))return _({result:{error:Vl},stack:p});let l=[Ct].includes(r),f=c?r:t.winningSide&&le||pn,g=Gn({...t,matchUpStatusCodes:c&&e||[],matchUpStatus:f,context:p,removeScore:l});return _({result:g,stack:p})}function PG({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 QS({collectionGroups:t=[]}){let e=Object.assign({},...t.filter(n=>It(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=>pt(n));return{groupValueGroups:e,groupValueNumbers:r}}function SO({collectionDefinition:t,groupValueNumbers:e,groupValueGroups:r,sideTieValues:n,tieMatchUps:o}){let i=o.filter(S=>S.collectionId===t.collectionId),s=[0,0],a=[0,0],c=i.every(S=>ce.includes(S.matchUpStatus)),{collectionValueProfiles:u,collectionGroupNumber:p,collectionValue:m,matchUpValue:d,winCriteria:l,scoreValue:f,setValue:g}=t,I=p&&e.includes(p),h=[0,0];if(i.forEach(S=>{S.winningSide&&(h[S.winningSide-1]+=1)}),It(d)?i.forEach(S=>{S.winningSide&&(s[S.winningSide-1]+=d)}):It(g)?i.forEach(S=>{S.score?.sets?.forEach(T=>{T.winningSide&&(s[T.winningSide-1]+=g)})}):It(f)?i.forEach(S=>{S.score?.sets?.forEach(T=>{let{side1TiebreakScore:y=0,side2TiebreakScore:P=0,side1Score:U=0,side2Score:A=0}=T;(S.matchUpStatus===le||S.winningSide||T.winningSide)&&(U||A?(s[0]+=U,s[1]+=A):(y||P)&&T.winningSide&&(s[T.winningSide-1]+=1))})}):Array.isArray(u)&&i.forEach(S=>{if(S.winningSide){let T=S.collectionPosition,y=DG({collectionDefinition:t,collectionPosition:T});It(y)&&(s[S.winningSide-1]+=y)}}),It(m)){let S;if(l?.aggregateValue)c&&(It(d||g||f)&&s[0]!==s[1]?S=s[0]>s[1]?1:2:h[0]!==h[1]&&(S=h[0]>h[1]?1:2));else if(l?.valueGoal)S=s.reduce((T,y,P)=>y>=l.valueGoal?P+1:T,0);else{let T=Math.floor(t.matchUpCount/2)+1;S=h.reduce((y,P,U)=>P>=T?U+1:y,0)}S&&(I?r[p].values[S-1]+=m:a[S-1]+=m)}else I?(r[p].values[0]+=s[0]||0,r[p].values[1]+=s[1]||0):a=s;I?(r[p].sideWins[0]+=h[0]||0,r[p].sideWins[1]+=h[1]||0,r[p].allGroupMatchUpsCompleted=r[p].allGroupMatchUpsCompleted&&c,r[p].matchUpsCount+=i.length):a.forEach((S,T)=>n[T]+=S||0)}function DG({collectionDefinition:t,collectionPosition:e}){return(t.collectionValueProfiles||[])?.find(o=>o.collectionPosition===e)?.matchUpValue}function Uc(t){let{sideAdjustments:e=[0,0],separator:r="-",drawDefinition:n,matchUpsMap:o,structure:i,matchUp:s,event:a}=t;if(!Array.isArray(e)||e.length!==2||isNaN(e.reduce((y,P)=>y+P)))return{error:G};if(!s)return{error:hr};let c=We({matchUp:s,drawDefinition:n,structure:i,event:a})?.tieFormat||t?.tieFormat;if(!c)return{error:bs};let u=ar({tieFormat:c});if(u.error)return u;let p=c?.collectionDefinitions||[],m=s?.tieMatchUps??[],d=[0,0],{groupValueGroups:l,groupValueNumbers:f}=QS(c);for(let y of p)SO({collectionDefinition:y,groupValueNumbers:f,groupValueGroups:l,sideTieValues:d,tieMatchUps:m});for(let y of f){let P=l[y],{allGroupMatchUpsCompleted:U,matchUpCount:A,winCriteria:E,groupValue:N,sideWins:D,values:M}=P,R;if(E?.aggregateValue)U&&M[0]!==M[1]&&(R=M[0]>M[1]?1:2);else if(E?.valueGoal)R=M.reduce((b,v,O)=>v>=E.valueGoal?O+1:b,void 0);else{let b=Math.floor(A/2)+1;R=D.reduce((v,O,x)=>O>=b?x+1:v,void 0)}R&&(d[R-1]+=N||0)}let g=d.map((y,P)=>(y||0)+e[P]),I={side1Score:g[0],side2Score:g[1],winningSide:void 0},h=g.join(r),S=g.slice().reverse().join(r),T;if(c?.winCriteria){let{valueGoal:y,aggregateValue:P,tallyDirectives:U}=c.winCriteria;if(y?T=g.map((E,N)=>({sideNumber:N+1,points:E})).find(({points:E})=>E>=y)?.sideNumber:P&&m.every(E=>E.matchUpStatus&&ce.includes(E.matchUpStatus)||E.winningSide)&&g[0]!==g[1]&&(T=g[0]>g[1]?1:2),!T&&U){let A=s.matchUpId,E=s.hasContext?s:o?.drawMatchUps?.[A]||n&&Bt({inContext:!0,drawDefinition:n,matchUpId:A})?.matchUp;if(E){let{completedTieMatchUps:N,order:D}=Ca({matchUps:[E]});if(N&&D?.length){let M=D[0].participantId;T=E.sides.find(({participantId:R})=>R===M)?.sideNumber}}}}return T&&(I.winningSide=T),{scoreStringSide1:h,scoreStringSide2:S,winningSide:T,set:I}}function ba({inContextDualMatchUp:t,drawDefinition:e,tournamentId:r,dualMatchUp:n,eventId:o}){if(n){t||(t=Bt({matchUpId:n.matchUpId,inContext:!0,drawDefinition:e})?.matchUp);let{extension:i}=dt({element:e,name:Ro}),s=J(i?.value||{},!1,!0),a=({displaySideNumber:c,drawPosition:u,sideNumber:p})=>({drawPosition:u,sideNumber:p,displaySideNumber:c});n.sides=t?.sides?.map(c=>{let u=c.participantId,p=u&&s[u]||void 0,{lineUp:m,...d}=n.sides?.find(({sideNumber:f})=>f===c.sideNumber)??{},l=m?.length?m:p;return{...a(c),...d,lineUp:l}}),gt({context:"ensureSidLineUps",matchUp:n,drawDefinition:e,tournamentId:r,eventId:o})}}function ir(t){if(t)return J(t,!1,!0)}function Mg(t){let e=rt(t,[{[Ce]:!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 XS({tournamentRecords:t,eventId:e,drawId:r}){let{tournamentIdMap:n}=Mg({tournamentRecords:t});return(n?Object.keys(n):[]).find(i=>e&&n?.[i].includes(e)||r&&n?.[i].includes(r))}function uo(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&&XS({tournamentRecords:c,...t});let p=u&&c[u];if(!p)return{error:Y};let m=Bt({drawDefinition:r,event:a,matchUpId:s});if(m.error)return m;if(!m.matchUp)return{error:Le};let{matchUp:d,structure:l}=m;if(!d.tieMatchUps)return{error:dr};ba({tournamentId:p?.tournamentId,eventId:a?.eventId,dualMatchUp:d,drawDefinition:r});let{extension:f}=dt({name:ga,element:d});if(f?.value)if(o)gr({element:d,name:ga});else return{...C,score:d.score};let g=We({drawDefinition:r,structure:l,matchUp:d,event:a})?.tieFormat;d.tieFormat=ir(g);let I=Uc({drawDefinition:r,matchUpsMap:i,structure:l,matchUp:d,event:a}),{winningSide:h,set:S,scoreStringSide1:T,scoreStringSide2:y}=I,P=S?.side1Score||S?.side2Score;if(e&&!d.score&&!P)return{...C};let U={scoreStringSide1:T,scoreStringSide2:y,sets:S?[S]:[]},A=h&&[1,2].includes(h),E=A&&le||ig({matchUpStatus:n??d.matchUpStatus,tieMatchUps:d.tieMatchUps,winningSide:d.winningSide,score:U})&&Ln||Qt,N=!!(d.winningSide&&!A),D=d.tieMatchUps.find(({score:R,winningSide:b,matchUpStatus:v})=>R?.sets?.length&&(R.sets[0].side1Score||R.sets[0].side2Score)||v&&ce.includes(v)||b),M;if(d.tieFormat&&!A&&!D){let R=We({drawDefinition:r,structure:l,event:a})?.tieFormat;R&&JSON.stringify(g)===JSON.stringify(R)&&(d.tieFormatId=void 0,d.tieFormat=void 0,M=!0)}return Gn({appliedPolicies:t.appliedPolicies,matchUpStatus:E,score:U,removeWinningSide:N,tournamentRecord:p,drawDefinition:r,removeScore:o,winningSide:h,matchUpId:s,matchUp:d,event:a}),{...C,score:U,removeWinningSide:N,tieFormatRemoved:M,winningSide:h}}function TO({winnerMatchUpDrawPositionIndex:t,inContextDrawMatchUps:e,projectedWinningSide:r,sourceMatchUpStatus:n,winningDrawPosition:o,tournamentRecord:i,winnerTargetLink:s,sourceMatchUpId:a,drawDefinition:c,winnerMatchUp:u,dualMatchUp:p,matchUpsMap:m,event:d}){let l="directWinner";if(s){let f=u.drawPositions||[],g=f[t],I=s.source.structureId,h=at({structureId:I,drawDefinition:c});if(h.error)return h;let{structure:S}=h,{positionAssignments:T}=Se({structureId:I,drawDefinition:c}),P=T?.find(R=>R.drawPosition===o)?.participantId,U=s.target.structureId,{positionAssignments:A}=Se({structureId:U,drawDefinition:c}),N=A?.find(R=>R.participantId===P)?.drawPosition,D=A?.filter(R=>{let b=f.includes(R.drawPosition),v=!R.participantId&&!R.bye&&!R.qualifier;return b&&v}).map(R=>R.drawPosition),M=D?.includes(g);if(P&&s.target.roundNumber===1&&M)kn({drawPosition:g,participantId:P,structureId:U,inContextDrawMatchUps:e,sourceMatchUpStatus:n,tournamentRecord:i,drawDefinition:c,matchUpsMap:m,event:d});else if(P&&D?.length){let R=D.pop();R&&kn({participantId:P,structureId:U,inContextDrawMatchUps:e,sourceMatchUpStatus:n,tournamentRecord:i,drawDefinition:c,drawPosition:R,matchUpsMap:m,event:d})}else if(N){let R=hc({drawPosition:N,matchUpId:u.matchUpId,inContextDrawMatchUps:e,sourceMatchUpStatus:n,tournamentRecord:i,sourceMatchUpId:a,drawDefinition:c,matchUpsMap:m});if(R.error)return _({result:R,stack:l})}else if(S?.stage!==ct){let R="winner target position unavaiallble";return console.log(R),{error:R}}if(S?.seedAssignments&&S.structureId!==U){let R=S.seedAssignments.find(({participantId:v})=>v===P),b=R?.participantId;R&&b&&$s({eventId:u?.eventId,structureId:U,...R,tournamentRecord:i,drawDefinition:c,participantId:b})}}else{let f=hc({matchUpId:u.matchUpId,drawPosition:o,inContextDrawMatchUps:e,sourceMatchUpStatus:n,tournamentRecord:i,sourceMatchUpId:a,drawDefinition:c,matchUpsMap:m});if(f.error)return f}if(p&&r){let f=p.sides?.find(g=>g.sideNumber===r);if(f?.lineUp){let g=p.roundPosition,I=u.roundPosition,h=g===I&&g!==1||Math.floor(g/2)===I?2:1,S=m?.drawMatchUps?.find(({matchUpId:P})=>P===u.matchUpId),T=[1,2].map(P=>({...S.sides?.find(A=>A.sideNumber===P)||{},sideNumber:P}));S.sides=T;let y=S.sides.find(P=>P.sideNumber===h);if(y){let P=f.lineUp?.filter(U=>U?.participantId);y.lineUp=Sd({lineUp:P}),gt({tournamentId:i?.tournamentId,eventId:u?.eventId,matchUp:S,context:l,drawDefinition:c})}}}return{...C}}function yO(t){let{loserMatchUpDrawPositionIndex:e,inContextDrawMatchUps:r,projectedWinningSide:n,sourceMatchUpStatus:o,loserDrawPosition:i,tournamentRecord:s,loserTargetLink:a,drawDefinition:c,loserMatchUp:u,dualMatchUp:p,matchUpsMap:m,event:d}=t,l="directLoser",f=a.linkCondition,g=u.drawPositions||[],I=f===On&&u.roundNumber===2&&Math.min(...g.filter(Boolean)),h=I||g[e],S=I||g[1-e],T=a.source.structureId,{structure:y}=at({structureId:T,drawDefinition:c}),{matchUps:P}=Ut({afterRecoveryTimes:!1,inContext:!0,drawDefinition:c,structure:y,event:d}),A=P.filter(H=>H.drawPositions?.includes(i)).filter(H=>{let q=H.sides.find(B=>B.drawPosition===i),$=H.matchUpStatus===Ct||H.matchUpStatus===Mt&&!Ie(H);return q?.sideNumber===H.winningSide&&!$}),E=f===On&&A.length===0,{positionAssignments:N}=Se({structureId:T,drawDefinition:c}),M=N?.find(H=>H.drawPosition===i)?.participantId,R=a.target.structureId,{positionAssignments:b}=Se({structureId:R,drawDefinition:c}),v=b?.filter(({drawPosition:H})=>g.includes(H));if(v?.some(H=>H.participantId===M))return{...C};let x=v?.filter(H=>{let q=g.includes(H.drawPosition),$=!H.participantId&&!H.bye&&!H.qualifier;return q&&$}).map(H=>H.drawPosition),F=x?.includes(h),L=a.target.roundNumber>1&&x?.length,w=a.target.roundNumber===1&&F;if(I){let H=V();if(H.error)return _({result:H,stack:l})}else if(w){let H=W();if(H.error)return _({result:H,stack:l})}else if(M&&L){x.sort(me);let H=x[0],q=kn({participantId:M,structureId:R,drawPosition:H,inContextDrawMatchUps:r,sourceMatchUpStatus:o,tournamentRecord:s,drawDefinition:c,matchUpsMap:m,event:d});if(q.error)return _({result:q,stack:l})}else return _({context:{loserDrawPosition:i,loserTargetLink:a,targetDrawPositionIsUnfilled:F},result:{error:F?Rs:TC},stack:l});if(y?.seedAssignments&&y.structureId!==R){let H=y.seedAssignments.find(({participantId:$})=>$===M),q=H?.participantId;H&&q&&$s({eventId:u?.eventId,structureId:R,...H,tournamentRecord:s,drawDefinition:c,participantId:q})}if(p&&n){let H=p.sides?.find(q=>q.sideNumber===3-n);if(H?.lineUp){let{roundNumber:q,eventId:$}=u,{roundPosition:B}=p,K=q===1?2-B%2:1,Q=m?.drawMatchUps?.find(({matchUpId:z})=>z===u.matchUpId),j=[1,2].map(z=>({...Q.sides?.find(lt=>lt.sideNumber===z)||{},sideNumber:z}));Q.sides=j;let tt=Q.sides.find(z=>z.sideNumber===K);tt&&(tt.lineUp=Sd({lineUp:H.lineUp}),gt({tournamentId:s?.tournamentId,matchUp:Q,context:l,drawDefinition:c,eventId:$}))}}return{...C};function V(){let H="loserLinkFedFMLC";return E?_({result:W(),stack:H}):_({result:k(),stack:H})}function k(){let H=Hr({drawPosition:S,structureId:R,tournamentRecord:s,drawDefinition:c,event:d});return _({result:H,stack:"assignLoserPositionBye"})}function W(){let H=M?kn({drawPosition:h,participantId:M,structureId:R,inContextDrawMatchUps:r,sourceMatchUpStatus:o,tournamentRecord:s,drawDefinition:c,matchUpsMap:m,event:d}):{error:oe};return _({result:H,stack:"assignLoserDrawPosition"})}}function JS(t){let e="directParticipants",r=Rd(t);if(r.error)return _({result:r,stack:e});let n=Ua({matchUpStatus:t.matchUpStatus}),{dualWinningSideChange:o,projectedWinningSide:i,inContextDrawMatchUps:s,tournamentRecord:a,drawDefinition:c,matchUpStatus:u,dualMatchUp:p,matchUpsMap:m,winningSide:d,targetData:l,matchUpId:f,structure:g,matchUp:I,event:h}=t,S=!!I.collectionId,T=cr({structure:g}),y=I.drawPositions,P;if(S){let{matchUpTieId:U,matchUpsMap:A}=t,E=uo({appliedPolicies:t.appliedPolicies,matchUpId:U,tournamentRecord:a,drawDefinition:c,matchUpsMap:A,event:h});if(P=E&&{tieMatchUpResult:E},y=s.find(({matchUpId:D})=>D===U)?.drawPositions,!o)return _({result:{...C,...P},stack:e})}if(T)return _({result:{...C,...P},stack:e});if(y){let U=i?i-1:d-1,A=1-U,E=y[U],N=y[A],{targetLinks:{loserTargetLink:D,winnerTargetLink:M,byeTargetLink:R},targetMatchUps:{winnerMatchUpDrawPositionIndex:b,loserMatchUpDrawPositionIndex:v,winnerMatchUp:O,loserMatchUp:x,byeMatchUp:F}}=l;if(O){let L=TO({sourceMatchUpStatus:n&&u||le,winnerMatchUpDrawPositionIndex:b,sourceMatchUpId:f,inContextDrawMatchUps:s,projectedWinningSide:i,winningDrawPosition:E,tournamentRecord:a,winnerTargetLink:M,drawDefinition:c,winnerMatchUp:O,dualMatchUp:p,matchUpsMap:m,event:h});if(L.error)return _({result:L,stack:e})}if(x){let L=yO({sourceMatchUpStatus:n&&u||le,loserMatchUpDrawPositionIndex:v,sourceMatchUpId:f,inContextDrawMatchUps:s,projectedWinningSide:i,loserDrawPosition:N,tournamentRecord:a,loserTargetLink:D,drawDefinition:c,loserMatchUp:x,winningSide:d,matchUpsMap:m,dualMatchUp:p,event:h});if(L.error)return _({result:L,stack:e})}if(F){let L=F.drawPositions||[],w=Math.min(...L.filter(Boolean)),V=R.target.structureId,k=Hr({drawPosition:w,structureId:V,tournamentRecord:a,drawDefinition:c,event:h});if(k.error)return _({result:k,stack:e})}}else return _({result:{error:ja},stack:e});return _({result:{...C,...P},stack:e})}function Cd(t){let e="genPlayoffStructure";if(!t.drawDefinition)return _({result:{error:Z},stack:e});let r=Du(t);if(r.error)return _({result:r,stack:e});let{structureId:n,addNameBaseToAttributeName:o,playoffStructureNameBase:i,finishingPositionNaming:s,finishingPositionLimit:a,playoffAttributes:c,playoffPositions:u,roundOffsetLimit:p,tournamentRecord:m,exitProfileLimit:d,roundProfiles:l,roundNumbers:f,idPrefix:g,isMock:I,event:h,uuids:S}=t,T=J(t.drawDefinition,!1,!0),{structure:y}=at({structureId:n,drawDefinition:T});if(!y)return _({result:{error:kt},stack:e});if(y.structureType===Ge||y.structures)return iO({sourceStructureId:y.structureId,...t,...r,drawDefinition:T});let{playoffRoundsRanges:P,playoffRounds:U}=r,{playoffPositionsReturned:A,error:E,playoffSourceRounds:N,playoffRoundsRanges:D}=VS(t);if(E)return _({result:{error:E},stack:e});let M=l?.length&&Object.assign({},...l),R=f||typeof l=="object"&&l.map(j=>Object.keys(j)).flat(),b=Array.isArray(R)&&R.map(j=>!isNaN(j)&&pt(j)).filter(Boolean);if(b){if(!Array.isArray(b))return _({result:{error:G},context:{validRoundNumbers:b},stack:e});b.forEach(j=>{if(!U?.includes(j))return _({result:{error:G},context:{roundNumber:j},stack:e})})}u&&u.forEach(j=>{if(!A?.includes(j))return _({result:{error:G},context:{playoffPosition:j},stack:e})});let v=b||N,O=b?P:D,x=[],F=[];for(let j of v??[]){let tt=O?.find(fe=>fe.roundNumber===j);if(!tt)return _({result:{error:G},context:{roundNumber:j},stack:e});let z=tt.finishingPositions.length,X=Math.min(...tt.finishingPositions)-1,lt=2,it=j&&M?.[j]&<+M[j]-1,Rt=Tc({exitProfile:`0-${j}`,addNameBaseToAttributeName:o,playoffStructureNameBase:i,finishingPositionOffset:X,playoffAttributes:c,exitProfileLimit:d,stage:de,roundOffset:0,drawDefinition:T,sequenceLimit:it,stageSequence:lt,drawSize:z,idPrefix:g,isMock:I,uuids:S,finishingPositionNaming:s,finishingPositionLimit:a,roundOffsetLimit:p});if(Rt.error)return _({result:Rt,stack:e});let{structures:Lt,links:De}=Rt;if(Lt?.length&&x.push(...Lt),De?.length&&F.push(...De),Rt.structureId&&j){let fe={linkType:ro,source:{structureId:n,roundNumber:j},target:{structureId:Rt.structureId,feedProfile:En,roundNumber:1}};F.push(fe)}}if(!x.length)return _({result:{error:G},info:"No structures generated",stack:e});T.structures.push(...x),T.links.push(...F);let{matchUps:L,matchUpsMap:w}=se({inContext:!0,drawDefinition:T}),V=x.map(({structureId:j})=>j),k=L?.filter(({structureId:j})=>V.includes(j)).map(Ee),W=w?.drawMatchUps?.filter(({matchUpId:j})=>k?.includes(j));if(W?.length){let j=We({drawDefinition:T,event:h})?.tieFormat;j&&W.forEach(tt=>{let{tieMatchUps:z}=Ra({matchUp:tt,tieFormat:j,isMock:I});Object.assign(tt,{tieMatchUps:z,matchUpType:jt})})}L?.filter(j=>ds({matchUp:j})&&j.structureId===n)?.forEach(j=>{let{matchUpId:tt,score:z,winningSide:X}=j,lt=ur({inContextDrawMatchUps:L,drawDefinition:T,matchUpId:tt}),it=JS({inContextDrawMatchUps:L,tournamentRecord:m,drawDefinition:T,matchUpsMap:w,winningSide:X,targetData:lt,matchUpId:tt,structure:y,matchUp:j,score:z,event:h});it.error&&console.log(it.error)}),L?.filter(j=>j.matchUpStatus===Nt&&j.structureId===n)?.forEach(j=>{let{matchUpId:tt}=j,z=ur({inContextDrawMatchUps:L,drawDefinition:T,matchUpId:tt}),{targetLinks:{loserTargetLink:X},targetMatchUps:{loserMatchUpDrawPositionIndex:lt,loserMatchUp:it}}=z;if(X&&it){let Rt=X.target.structureId,Lt=it.drawPositions[lt],De=Hr({drawPosition:Lt,structureId:Rt,tournamentRecord:m,drawDefinition:T,event:h});De.error&&console.log(De.error)}});let $=[],B=qi({inContextDrawMatchUps:L,drawDefinition:T,matchUpsMap:w}).goesToMap,{structure:K}=at({drawDefinition:t.drawDefinition,structureId:n}),{matchUps:Q}=Ut({structure:K});return Q.forEach(j=>{let tt=B?.loserMatchUpIds[j.matchUpId];if(tt&&j.loserMatchUpId!==tt){j.loserMatchUpId=tt;let X={tournamentId:m?.tournamentId,eventId:t.event?.eventId,context:e,matchUp:j};$.push(X)}let z=B?.winnerMatchUpIds[j.matchUpId];if(z&&j.winnerMatchUpId!==z){j.winnerMatchUpId=z;let X={tournamentId:m?.tournamentId,eventId:t.event?.eventId,context:e,matchUp:j};$.push(X)}}),{structures:x,matchUpModifications:$,links:F,drawDefinition:T,...C}}function ZS({element:t}){if(!t)return{error:G};if(!t.timeItems)return{};if(!Array.isArray(t.timeItems))return{error:G};let e=(r,n)=>(o,i)=>(i[r]&&(o[i[r]]=i[n]),o);return t.timeItems.reduce(e("itemType","itemValue"),{})}function Xn(t){let{duplicateValues:e=!0,creationTime:r=!0,removePriorValues:n,timeItem:o}=t;if(!o)return{error:Zl};let i=Kh(t);if(i.error)return i;if(!(ht(o)&&Vt(o.itemType)&&Object.keys(o).includes("itemValue")))return{error:Jl};if(!i.timeItems)i.timeItems=[];else if(NG({element:i,duplicateValues:e,timeItem:o}))return{...C};if(o.itemSubTypes&&!o.itemSubTypes.length&&delete o.itemSubTypes,r){let c=new Date().toISOString();Object.assign(o,{createdAt:c})}return n&&(i.timeItems=i.timeItems.filter(({itemType:c})=>o.itemType!==c)),n&&!o.itemValue||i.timeItems.push(o),{...C}}function NG({element:t,duplicateValues:e,timeItem:r}){let{itemType:n,itemSubTypes:o,itemValue:i}=r,s=n&&rn({itemSubTypes:o,itemType:n,element:t})?.timeItem;return s&&JSON.stringify(s?.itemValue)===JSON.stringify(i)&&!e}function Rg({creationTime:t=!0,removePriorValues:e,tournamentRecord:r,duplicateValues:n,participantId:o,timeItem:i}){if(!r)return{error:Y};if(!o)return{error:oe};let s=To({tournamentRecord:r,participantId:o});return s.error?s:Xn({element:s.participant,removePriorValues:e,duplicateValues:n,creationTime:t,timeItem:i})}function Pc(t){let{removePriorValues:e,tournamentRecord:r,duplicateValues:n,creationTime:o,timeItem:i}=t;if(!r)return{error:Y};let s=Xn({element:r,removePriorValues:e,duplicateValues:n,creationTime:o,timeItem:i});if(s.error)return s;let a=ZS({element:r});return mt({payload:{parentOrganisation:r.parentOrganisation,tournamentId:r.tournamentId,timeItemValues:a},topic:Bi}),s}function zi(t){let{removePriorValues:e,duplicateValues:r,creationTime:n,timeItem:o,event:i}=t;return i?Xn({removePriorValues:e,duplicateValues:r,element:i,creationTime:n,timeItem:o}):{error:jr}}function YP(t){return bg({...t,itemType:"attachConsolationStructures"})}function Cg(t){return bg({...t,itemType:"attachPlayoffStructures"})}function bg({itemType:t="attachStructures",matchUpModifications:e,tournamentRecord:r,drawDefinition:n,structures:o,links:i=[],event:s}){let a="attachStructures";if(!n)return{error:Z};if(!Array.isArray(o)||!Array.isArray(i))return _({result:{error:G},stack:a});let c=h=>[h.source.structureId,h.source.roundNumber||h.source.finishingPositions?.join("|"),h.target.roundNumber].join("|"),u=n.links?.map(c);if(i.some(h=>{let S=c(h);return u?.includes(S)}))return _({result:{error:of},info:"playoff structure exists",stack:a});i.length&&n.links?.push(...i);let m=o.map(({structureId:h})=>h),d=n.structures?.map(({structureId:h})=>h);n.structures=(n.structures??[]).map(h=>m.includes(h.structureId)?o.find(({structureId:S})=>S===h.structureId):h);let l=o?.filter(({structureId:h})=>!d?.includes(h));l.length&&n.structures.push(...l),qi({drawDefinition:n});let f=o.map(h=>Ut({structure:h})?.matchUps||[]).flat();Co({tournamentId:r?.tournamentId,eventId:s?.eventId,drawDefinition:n,matchUps:f});let g=o.map(({structureId:h})=>h);if(Ot({drawDefinition:n,structureIds:g}),e?.length){let h={};e.forEach(T=>{let y=T.matchUp?.matchUpId;y&&(h[y]=T)});let S=T=>{T.matchUps.forEach(y=>{if(h[y.matchUpId]){let{tieMatchUps:P,...U}=h[y.matchUpId].matchUp;if(Object.assign(y,U),P?.length){let A={};P.forEach(E=>h[E.matchUpId]=E),y.tieMatchUps.forEach(E=>Object.assign(E,A[E.matchUpId]))}h[y.matchUpId].matchUp=y,gt(h[y.matchUpId])}})};n.structures.forEach(T=>{if(d?.includes(T.structureId))if(T.structures)for(let y of T.structures)S(y);else S(T)})}let I=l.map(Br("structureId"));if(r){let S={itemValue:{structureIds:g,drawId:n.drawId},itemType:t};Xn({element:r,timeItem:S})}return{...C,addedStructureIds:I}}function Gp(t){let{structures:e,links:r,matchUpModifications:n,error:o}=Cd(t);if(o)return{error:o};let i=t.drawDefinition;return Cg({tournamentId:t.tournamentRecord?.tournamentId,eventId:t.event?.eventId||t.eventId,matchUpModifications:n,drawDefinition:i,structures:e,links:r})}function Qi(t){let e=rt(t,[{_anyOf:{[Ce]:!1,[ie]:!1,[Ve]:!1,[Do]:!1},[Ef]:!0}]);if(e.error)return e;let r=[],n=t.drawDefinition??t.event??((t.tournamentId||!t.tournamentRecords)&&t.tournamentRecord);if(n){let o=AO(t,n);if(o.error)return o;r.push(...o?.applied??[]),t.drawDefinition&&Ot({drawDefinition:t.drawDefinition,tournamentId:t.tournamentId})}else if(t.tournamentRecords){let o=Object.keys(t.tournamentRecords);if(!o.length)return{error:Y};for(let i of o){let s=t.tournamentRecords[i],a=AO(t,s);if(a.error)return a;r.push(...a?.applied??[])}}else return{error:Y};return r.length?{...C,applied:r}:{error:FI}}function AO(t,e){let r=yt(t).appliedPolicies??{};e.extensions||(e.extensions=[]);let n=[],o=Object.keys(t.policyDefinitions);if(!o.length)return{error:Ku};for(let i of o)if(!r[i]||t.allowReplacement){let s=t.policyDefinitions[i];if(!s)continue;if(!ht(s))return{error:G};let{policyName:a,...c}=s;if(!c||!Object.keys(c).length||a&&!Vt(a))return{error:G};r[i]=t.policyDefinitions[i],n.push(i)}return n?.length?{...At({element:e,extension:{name:nu,value:r}}),applied:n}:{applied:n,error:FI}}function vg({tournamentRecord:t,drawDefinition:e,flightProfile:r,drawName:n,drawId:o,event:i}){if(!n||typeof n!="string")return _({result:{error:G},context:{drawName:n}});r||(r=Ht({event:i}).flightProfile);let s=r?.flights?.find(a=>a.drawId===o);if(s){s.drawName=n;let a={name:un,value:{...r,flights:r.flights}};Mo({event:i,extension:a})}return e&&(e.drawName=n,Ot({tournamentId:t?.tournamentId,drawDefinition:e})),!s&&!e?{error:Z}:{...C,flight:s}}function qP({tournamentRecord:t,drawDefinition:e,drawUpdates:r,drawId:n,event:o}){if(!ht(r))return{error:G};let i=Ht({event:o}).flightProfile,s=r.drawName&&vg({drawName:r.drawName,tournamentRecord:t,drawDefinition:e,flightProfile:i,drawId:n,event:o});if(s?.error)return s?.error;let a=s?.flight||i?.flights?.find(c=>c.drawId===n);if(!a&&!e)return{error:Z};if(a){let c={name:un,value:{...i,flights:i.flights}};Mo({event:o,extension:c})}return e&&(r.policyDefinitions&&Qi({policyDefinitions:r.policyDefinitions,drawDefinition:e}),Ot({tournamentId:t?.tournamentId,drawDefinition:e})),{...C}}function $P({tournamentRecord:t,removeScheduling:e,drawDefinition:r}){if(!r)return{error:Z};let n=Me({drawDefinition:r}),o=s=>n?.drawMatchUps?.find(a=>a.matchUpId===s);for(let s of r.structures||[]){let{positionAssignments:a,stage:c,stageSequence:u}=s;a&&(u!==1||![ct,nt].includes(c))&&(s.positionAssignments=a.map(d=>(delete d.participantId,d)),s.seedAssignments=[]);let{matchUps:p,isRoundRobin:m}=Ut({afterRecoveryTimes:!1,inContext:!0,matchUpsMap:n,structure:s});for(let d of p){let{matchUpId:l,roundNumber:f}=d,g=d.sides||[],I=o(l);if(I){if(delete I.extensions,delete I.notes,I.matchUpStatus!==Nt&&Object.assign(I,Cu),f&&f>1&&I.drawPositions?.length&&!m){let h=g?.map(({drawPosition:T,participantFed:y})=>!y&&T).filter(Boolean),S=I.drawPositions.map(T=>h.includes(T)?void 0:T);I.drawPositions=S}e?delete I.timeItems:I.timeItems?.length&&(I.timeItems=I.timeItems.filter(h=>h.itemType&&![ao,Ho,Hi,eg,Wi,ji].includes(h.itemType))),gt({tournamentId:t?.tournamentId,context:"resetDrawDefiniton",drawDefinition:r,matchUp:I})}}}r.extensions=r.extensions.filter(s=>s.name!==nc);let i=(r.structures||[]).map(({structureId:s})=>s);return Ot({drawDefinition:r,structureIds:i}),{...C}}function bu({tournamentRecord:t}){if(!t)return{error:Y};let e={positionsNoOutcomes:[],canBePruned:[],matchPlay:[],inactive:[],drawAnalysis:{}},r={};return(t.events?.map(o=>{let i=o.eventId;return r[i]=o,(o?.drawDefinitions||[]).map(s=>({drawDefinition:s,eventId:i}))}).flat().filter(Boolean)).forEach(({drawDefinition:o,eventId:i})=>{let s=0,a=0,c=0,{allStructuresLinked:u}=Uu({drawDefinition:o}),p=r[i],d=(o?.structures||[]).map(P=>{let{stage:U,stageSequence:A,structureId:E}=P,N=ks[U],{inContextStructureMatchUps:D}=Pa({drawDefinition:o,structure:P,event:p}),M=D?.filter(({winningSide:q})=>q),R=M.filter(Boolean).length||0;a+=R,c+=D.length-a;let b=Math.max(M.filter(({roundNumber:q})=>q===1).map(({roundPosition:q})=>q)),{positionAssignments:v}=bt({structure:P}),O=v?.filter(({participantId:q})=>q);s+=O?.length??0;let x=(v?.length??0)-(O?.length??0),{roundMatchUps:F,roundProfile:L,roundNumbers:w,maxMatchUpsCount:V}=Ke({matchUps:D}),k=L&&Object.keys(L).filter(q=>!L[q].inactiveRound).map(q=>parseInt(q)),W=L&&Object.keys(L).filter(q=>L[q].inactiveRound).map(q=>parseInt(q)),H=L&&Object.values(L).every(q=>q.inactiveRound);return{positionsAssignedCount:O?.length??0,maxWinningSideFirstRoundPosition:b,unassignedPositionsCount:x,inactiveStructure:H,maxMatchUpsCount:V,inactiveRounds:W,roundMatchUps:F,activeRounds:k,roundNumbers:w,roundProfile:L,structureId:E,stageSequence:A,orderNumber:N,stage:U}}),l=d.find(P=>P.orderNumber===2&&P.stageSequence===1),f=d.filter(({inactiveStructure:P})=>!P).length,{links:g}=Ws({structureId:l.structureId,drawDefinition:o}),I=pt(l.activeRounds[0])===1&&l.activeRounds.length===1&&f===1,h=d?.every(({inactiveStructure:P})=>P),S=!g.length&&l.activeRounds.length&&(l.roundProfile[1].inactiveCount||l.inactiveRounds.length),T=o.drawId;s&&!a&&e.positionsNoOutcomes.push(T),h&&e.inactive.push(T),I&&e.matchPlay.push(T),S&&e.canBePruned.push(T);let y={matchUpsWithWinningSideCount:a,matchUpsNoOutcomeCount:c,positionsAssignedCount:s,allStructuresLinked:u,structuresData:d,inactiveDraw:h,isMatchPlay:I,drawId:T};e.drawAnalysis[T]=y}),{...C,drawsAnalysis:e}}function KP({matchPlayDrawPositions:t=!0,tournamentRecord:e,drawDefinition:r,drawId:n}){if(!e)return{error:Y};if(!r)return{error:Z};let o=[],{drawsAnalysis:i}=bu({tournamentRecord:e});if(i.canBePruned.includes(n)){let s=i.matchPlay.includes(n),a=i.drawAnalysis[n],{structures:[c]}=gn({stageSequence:1,drawDefinition:r,stage:nt}),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(Ee),d=p.map(Ee).filter(l=>!m.includes(l));if(s){let l=o.filter(({roundNumber:T})=>!u.inactiveRounds.includes(T)).filter(({winningSide:T})=>T),f=l.map(Ee),g=m.filter(T=>!f.includes(T));d.push(...g);let h=l.flatMap(T=>T.drawPositions??[]).filter(Boolean).flat(),S=Object.assign({},...h.map((T,y)=>({[T]:y+1})));if(l.forEach(T=>{t?T.drawPositions=T.drawPositions.map(y=>S[y]):delete T.drawPositions}),t){let T=c?.positionAssignments?.filter(y=>h.includes(y.drawPosition)).map(y=>(y.drawPosition=S[y.drawPosition],y));c.positionAssignments=T}else c.positionAssignments=[];c.matchUps=l,o=l}qn({tournamentId:e?.tournamentId,matchUpIds:d,drawDefinition:r}),Ot({drawDefinition:r})}return{...C,matchUps:o}}function zP({tournamentRecord:t,drawDefinition:e,participantId:r,drawPosition:n,structureId:o,qualifier:i,event:s,bye:a}){if(!e)return{error:Z};if(!n)return{error:Cs};if(!o)return{error:Ur};if(a){let c=Hr({tournamentRecord:t,drawDefinition:e,drawPosition:n,structureId:o,event:s});if(c.error)return c}else{if(i)return{error:tp};{let c=kn({tournamentRecord:t,drawDefinition:e,participantId:r,drawPosition:n,structureId:o,event:s});if(c.error)return c}}return{...C}}function tT(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:kt};let o=r.structures?.find(c=>c.structureId===n);if(!o)return{error:kt};let i=o?.matchUps,s=i?.find(c=>!!c.roundPosition);if(o.structures||s||o.finishingPosition===Gi)return{error:Xo};let a=i.filter(({roundNumber:c})=>t.roundNumbers?.includes(c)).map(Ee);return e=e.filter(c=>!a.includes(c)),t.roundNumbers&&!e.length&&(e=a),{existingMatchUps:i,matchUpIds:e,structureId:n,structure:o}}function QP(t){let e=rt(t,[{[Ve]:!0},{[Gs]:{[ec]:!1,roundNumbers:!1},[Fr]:G,[He]:Be}]);if(e.error)return e;let{removeIncomplete:r=!1,removeUnAssigned:n=!0,removeCompleted:o=!1,tournamentRecord:i,drawDefinition:s,event:a}=t,c=tT(t);if(c.error)return c;let{structure:u,structureId:p,existingMatchUps:m,matchUpIds:d}=c,l=[],f=m?.filter(({matchUpId:h,score:S,winningSide:T})=>{if(T&&!o)return!1;if(T||Ie({score:S})){if(!T&&!r)return!1;l.push(h)}else if(!n)return!1;return d?.includes(h)})??[],g=f.map(Ee),I=f.map(({tieMatchUps:h})=>h?.map(Ee)).filter(Boolean).flat();if(g.length){u.matchUps=(u.matchUps??[]).filter(({matchUpId:T})=>!g.includes(T)),qn({tournamentId:i?.tournamentId,matchUpIds:[...I,...g],action:"deleteAdHocMatchUps",eventId:a?.eventId,drawDefinition:s});let h=ut(u.matchUps.map(Br("roundNumber"))),S=fC(h);if(S.length){S.reverse();for(let T of S)u.matchUps.forEach(y=>{y.roundNumber&&y.roundNumber>T&&(y.roundNumber-=1,gt({tournamentId:i?.tournamentId,context:["adHoc round deletion"],eventId:a?.eventId,drawDefinition:s,matchUp:y}))})}if(l.length){u.positionAssignments=ut(u.matchUps.flatMap(N=>(N.sides??[]).map(D=>D.participantId)).filter(Boolean)).map(N=>({participantId:N}));let T=u?.matchUpFormat??s?.matchUpFormat??a?.matchUpFormat,P=c.existingMatchUps.some(N=>N.matchUpType===xr)?{matchUpTypes:[xr]}:void 0,{matchUps:U}=Ut({afterRecoveryTimes:!1,inContext:!0,matchUpFilters:P,structure:u,event:a});cr({structure:u})&&(u.positionAssignments=ut(U.flatMap(N=>(N.sides??[]).map(D=>D.participantId)).filter(Boolean)).map(N=>({participantId:N})));let E=Md({positionAssignments:u.positionAssignments,tournamentRecord:i,drawDefinition:s,matchUpFormat:T,matchUps:U,event:a});E.error&&console.log(E)}Ot({structureIds:[p],eventId:a?.eventId,drawDefinition:s})}return!g.length&&d.length?{error:ep}:{...C,deletedMatchUpsCount:[...g,...I].length}}function XP({removeCompletedMatchUps:t,tournamentRecord:e,drawDefinition:r,structureId:n,roundNumber:o,event:i}){if(!e)return{error:Y};if(!r)return{error:Z};if(!o)return _({result:{error:st},info:"roundNumber required"});let s=at({drawDefinition:r,structureId:n});if(s.error)return s;let a=s.structure;return a?.structures?{error:Xo}:cr({structure:a})?MG({tournamentId:e.tournamentId,removeCompletedMatchUps:t,eventId:i.eventId,drawDefinition:r,roundNumber:o,structure:a}):(console.log("not implemented"),{...C})}function MG({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(me).includes(n)){let m=s.filter(d=>{let l=d.roundNumber===n&&(!ce.includes(d.matchUpStatus)||t);return l&&(c.push(d.matchUpId),d.tieMatchUps&&a.push(...d.tieMatchUps.map(Ee))),!l});c.length&&(qn({matchUpIds:[...a,...c],drawDefinition:e,tournamentId:r,eventId:i}),m.some(l=>l.roundNumber===n)||(m.forEach(l=>{l.roundNumber>n&&(l.roundNumber-=1,gt({drawDefinition:e,tournamentId:r,eventId:i,matchUp:l}))}),u=!0),o.matchUps=m)}return{deletedMatchUpsCount:c.length,roundRemoved:u,...C}}function bd(t){let{suppressNotifications:e,tournamentRecord:r,drawDefinition:n,matchUps:o,event:i}=t;if(typeof n!="object")return{error:Z};let s=t?.structureId;if(!s&&n.structures?.length===1&&(s=n.structures?.[0]?.structureId),typeof s!="string")return{error:Ur};if(!Vr(o))return{error:G,info:si("matchUps")};let a=n.structures?.find(l=>l.structureId===s);if(!a)return{error:kt};let u=(a?.matchUps).find(l=>!!l.roundPosition);if(a.structures||u||a.finishingPosition===Gi)return{error:Xo};let p=Te({tournamentRecord:r,inContext:!1})?.matchUps?.map(Ee)??[],m=o.map(Ee);if(Fe(p,m))return{error:OE,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||(Co({tournamentId:r?.tournamentId,matchUps:[...d,...o],eventId:i?.eventId,drawDefinition:n}),Ot({drawDefinition:n,structureIds:[s]})),{...C}}function JP({tournamentRecord:t,drawDefinition:e,drawPosition:r,structureId:n,subOrder:o,event:i}){if(!e)return{error:Z};if(!n)return{error:Ur};if(!r)return{error:Cs};let{structure:s}=at({drawDefinition:e,structureId:n});if(!s)return{error:kt};let a=s;s.structures&&s.structureType===Ge&&(a=s.structures?.find(g=>g.positionAssignments?.find(I=>I.drawPosition===r)));let c=a?.positionAssignments,u=c?.find(g=>g.drawPosition===r);u&&At({element:u,extension:{name:oc,value:o}});let d=(i?.eventType===jt||e.matchUpType===jt||(i?.tieFormat??e?.tieFormat??s?.tieFormat))&&{matchUpTypes:[jt]},{matchUps:l}=Ut({structure:a,afterRecoveryTimes:!1,inContext:!0,matchUpFilters:d,event:i}),f=s?.matchUpFormat??e.matchUpFormat;return Md({positionAssignments:c,tournamentRecord:t,drawDefinition:e,matchUpFormat:f,matchUps:l,event:i}),Ot({drawDefinition:e,structureIds:[n]}),{...C}}var pD={};Xt(pD,{addGoesTo:()=>qi,allPlayoffPositionsFilled:()=>OS,checkValidEntries:()=>_d,findDrawDefinition:()=>oT,getAssignedParticipantIds:()=>Ri,getAvailableMatchUpsCount:()=>vd,getAvailablePlayoffProfiles:()=>Du,getDrawDefinitionTimeItem:()=>zh,getDrawParticipantRepresentativeIds:()=>rT,getDrawStructures:()=>gn,getDrawTypeCoercion:()=>vu,getEligibleVoluntaryConsolationParticipants:()=>eT,getMatchUpsMap:()=>Me,getParticipantIdFinishingPositions:()=>nT,getPositionAssignments:()=>Vp,getPositionsPlayedOff:()=>yc,getSeedingThresholds:()=>ES,getSeedsCount:()=>Ou,getStructureSeedAssignments:()=>on,getTeamLineUp:()=>ms,getValidGroupSizes:()=>bp,isAdHoc:()=>cr,isCompletedStructure:()=>ai,isValidForQualifying:()=>hT,positionActions:()=>IT});function eT({excludedMatchUpStatuses:t=[],includeEventParticipants:e,includeQualifyingStage:r,finishingRoundLimit:n,policyDefinitions:o,roundNumberLimit:i,tournamentRecord:s,drawDefinition:a,matchUpsLimit:c,requirePlay:u,requireLoss:p,allEntries:m,winsLimit:d,event:l}){if(!a)return{error:Z};let f=[nt,de];r&&f.push(ct);let g=l?.eventType?{matchUpTypes:[l.eventType]}:void 0,I=a?.matchUpType?{matchUpTypes:[a.matchUpType]}:void 0,h=e&&l?Kn({contextFilters:{stages:f},matchUpFilters:g,tournamentRecord:s,inContext:!0,event:l})?.matchUps??[]:or({contextFilters:{stages:f},matchUpFilters:I,tournamentRecord:s,inContext:!0,drawDefinition:a})?.matchUps??[],T=Ui({stage:$e,drawDefinition:a}).map(({participantId:w})=>w),y={},P={},U={},A={};o||(o=vo({policyTypes:[vh],tournamentRecord:s,drawDefinition:a,event:l}).policyDefinitions);let E=o?.[vh];t=t.length&&t||E?.excludedMatchUpStatuses||[],e=e??E?.includeEventParticipants,m=m??E?.allEntries,n=n??E?.finishingRoundLimit,i=i??E?.roundNumberLimit,c=c??E?.matchUpsLimit,u===void 0&&(u=E?.requirePlay!==void 0?E.requirePlay:!0),p===void 0&&(p=E?.requireLoss!==void 0?E.requireLoss:!0),d=d??E?.winsLimit;for(let w of h){if(u&&w.winningSide&&![1,2].includes(w.winningSide)&&w.matchUpStatus!==he||w.finishingRound&&n&&w.finishingRound>=n||w.finishingRound&&i&&w.finishingRound<=i)continue;let V=w.sides?.find(({sideNumber:W})=>w.winningSide&&W===3-w.winningSide),k=w.sides?.find(({sideNumber:W})=>w.winningSide&&W===w.winningSide);if(w.sides?.forEach(W=>{let H=W?.participant?.participantId;H&&(U[H]=W.participant,w.matchUpStatus===he&&!u&&(P[H]=W.participant,y[H]||(y[H]=0),(!w.matchUpStatus||!t.includes(w.matchUpStatus))&&(y[H]+=1)))}),V?.participant){let W=V.participant.participantId;P[W]=V.participant,y[W]||(y[W]=0),w.matchUpStatus&&!t.includes(w.matchUpStatus)&&(y[W]+=1)}if(k?.participant){let W=k.participant.participantId;A[W]||(A[W]=0),A[W]+=1,y[W]||(y[W]=0),w.matchUpStatus&&!t.includes(w.matchUpStatus)&&(y[W]+=1)}}let N=s?.participants&&!u&&!p&&m,D=N?((e&&l?l.entries:a.entries)??[]).filter(w=>![so,Gr].includes(w.entryStatus)).map(({participantId:w})=>w):[],M=Object.keys(P),R=N?(s?.participants??[]).filter(({participantId:w})=>D.includes(w)):p&&Object.values(P)||Object.values(U),b=w=>!p||M.includes(w),v=w=>!u||(y[w]||0)>=0,O=w=>!d||(A[w]||0)<=d,x=w=>!c||y[w]<=c,F=w=>!T.includes(w);return{eligibleParticipants:R.filter(w=>b(w.participantId)&&v(w.participantId)&&O(w.participantId)&&x(w.participantId)&&F(w.participantId)).map(w=>({...w,individualParticipants:w.individualParticipantIds?.map(V=>s?.participants?.find(k=>k.participantId===V))})),losingParticipantIds:M,...C}}function vd(t){let e=rt(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:Ur};let i=r.structures?.find(g=>g.structureId===o);if(!i)return{error:kt};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===Gi)return{error:Xo};let u=r?.entries?.filter(g=>{let I=g.entryStatus;return Qr.includes(I)})??[],p=Math.floor(u?.length/2)||1,m=n??c??1,d=i.matchUps?.filter(g=>g.roundNumber===m)?.length??0,l=p-d,f=l>0?l:0;return{...C,availableMatchUpsCount:f,lastRoundNumber:c,roundMatchUpsCount:p}}function rT({drawDefinition:t}){let e=dt({name:"participantRepresentatives",element:t});return e.error?e:{representativeParticipantIds:e.extension?.value||[]}}function EO({tournamentParticipants:t,drawDefinition:e,event:r}){if(!e)return{error:Z};let n=se({tournamentParticipants:t,inContext:!0,drawDefinition:e,event:r}),o=J(n.matchUps,!1,!0),i=ut(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 nT({byeAdvancements:t=!1,tournamentRecord:e,drawDefinition:r}){if(!r)return{error:Z};let{participantIds:n,participantIdMatchUps:o}=EO({tournamentParticipants:e?.participants,drawDefinition:r}),i=n?.map(s=>{let c=o[s].filter(d=>[le,Nt].includes(d.matchUpStatus)||d.winningSide),u=c.map(d=>{let l=d.sides.find(I=>I.bye),f=d.sides.find(I=>I.participantId===s).sideNumber;return(d.winningSide||t&&l&&f)===f?d.finishingPositionRange.winner:d.finishingPositionRange.loser}),p=d=>Math.abs(d[0]-d[1]),m=u.reduce((d,l)=>d&&p(d)<p(l)?d:l,void 0);return{[s]:{relevantMatchUps:c,finishingPositionRanges:u,finishingPositionRange:m}}})||[];return Object.assign({},...i)}function wo({tournamentRecords:t,tournamentRecord:e,tournamentId:r,drawId:n}){if(!e&&!t)return{error:Y};if(!n)return{error:an};if(!e&&t){if(typeof r!="string"&&(r=XS({tournamentRecords:t,drawId:n}),!r))return{error:ca};if(e=t[r],!e)return{error:Y}}let o=e&&ze({tournamentRecord:e,drawId:n});return o?.drawDefinition?{drawDefinition:o.drawDefinition,event:o.event,tournamentRecord:e,...C}:_({result:{error:Rr},stack:"findDrawDefinition"})}function oT(t){let{drawDefinition:e,error:r}=wo(t);return r?{error:r}:{drawDefinition:J(e)}}function Og({targetRoundNumber:t,finishingPosition:e,drawDefinition:r,structureId:n,linkType:o}){let{links:i}=Ws({drawDefinition:r,structureId:n})||{},a=(i?.target||[]).filter(({linkType:u})=>u===o).filter(({target:u})=>!t||t===u.roundNumber).map(u=>{let p=u.source.structureId,{structure:m}=at({structureId:p,drawDefinition:r});if(!(e&&m?.finishingPosition!==e))return u}).filter(Boolean);return{sourceStructureIds:a.map(({source:u})=>u.structureId),relevantLinks:a}}function UO({tournamentParticipants:t,returnParticipants:e,drawPosition:r,participant:n,drawId:o,event:i}){let s=i?.entries?.filter(({entryStatus:a})=>[Gr,Ei].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:ot({payload:{participantId:n.participantId,replacementIndividualParticipantId:void 0,existingIndividualParticipantId:void 0,drawPosition:r,drawId:o},method:$v,availableIndividualParticipantIds:s,availableIndividualParticipants:c,existingIndividualParticipantIds:a,existingIndividualParticipants:u,type:yg},!1,!1,!0)}}return{}}function Ci(t){let{inContextDrawMatchUps:e,targetData:r,drawDefinition:n,relevantLink:o}=t;if(o?.linkCondition===On&&r?.matchUp?.matchUpStatus===Nt)return!1;let{targetMatchUps:{loserMatchUp:s,winnerMatchUp:a},targetLinks:c}=r,u=s&&ur({matchUpId:s.matchUpId,inContextDrawMatchUps:e,drawDefinition:n}),p=u?.targetMatchUps?.loserMatchUp,m=u?.targetMatchUps?.loserMatchUpDrawPositionIndex,d=p?.sides[m]?.participant,l=[Mt,Ct].includes(s?.matchUpStatus)&&!d,f=a?.drawPositions?.filter(Boolean).length||0;if(s?.winningSide&&!l||a?.winningSide&&f===2&&(!a.feedRound||![Ct,Mt].includes(a?.matchUpStatus)))return!0;let g=a&&ur({matchUpId:a.matchUpId,inContextDrawMatchUps:e,drawDefinition:n}),I=u&&Ci({relevantLink:c?.loserTargetLink,targetData:u,inContextDrawMatchUps:e,drawDefinition:n});return!!(g&&Ci({targetData:g,inContextDrawMatchUps:e,drawDefinition:n})||I)}var iT={[So]:{policyName:"positionActionsDefault",enabledStructures:[{stages:[ct,nt],stageSequences:[1],enabledActions:[],disabledActions:[]},{stages:[],stageSequences:[],enabledActions:[Pu,Qs,xp,zs],disabledActions:[]}],disbledStructures:[],otherFlightEntries:!1,activePositionOverrides:[]}};var _g="positionAction",sT="matchUpAction";function aT({actionType:t=_g,appliedPolicies:e,drawDefinition:r,structure:n}){let o=t===_g&&So||t===sT&&er,i=t===_g&&iT||t===sT&&nP,s=o&&(e?.[o]||i?.[o]),c=r.links?.filter(d=>d?.target?.structureId===n?.structureId)?.map(({target:d})=>d.feedProfile)??[],{enabledStructures:u,disabledStructures:p}=s||{},m=p?.find(d=>{let{stages:l,stageSequences:f,structureTypes:g,feedProfiles:I}=d;return(!I?.length||Array.isArray(I)&&I.some(h=>c.includes(h)))&&(!l?.length||Array.isArray(l)&&l?.includes(n?.stage))&&(!g?.length||Array.isArray(g)&&g?.includes(n?.structureType))&&(!f?.length||Array.isArray(f)&&f.includes(n?.stageSequence))});return{enabledStructures:u,actionsDisabled:m,actionsPolicy:s}}function tD({activePositionOverrides:t,activeDrawPositions:e,action:r}){return r&&t.includes(r)?!0:!e.length}function cT({enabledStructures:t,drawDefinition:e,structure:r}){if(t===!1)return{};if(!t?.length)return{policyActions:{enabledActions:[],disabledActions:[]}};let{stage:n,stageSequence:o,structureType:i}=r||{},a=e.links?.filter(u=>u?.target?.structureId===r?.structureId)?.map(({target:u})=>u.feedProfile)||[];return{policyActions:t.find(u=>{let{stages:p,stageSequences:m,structureTypes:d,feedProfiles:l}=u||{},f=!p?.length||Array.isArray(p)&&p.includes(n),g=!m?.length||Array.isArray(m)&&m.includes(o),I=!d?.length||Array.isArray(d)&&d.includes(i),h=!l?.length||Array.isArray(l)&&l.some(S=>a.includes(S));return g&&I&&h&&u&&f})}}function Vn({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 eD="replaceTieMatchUpParticipantId",rD="assignTieMatchUpParticipantId",uT="removeTieMatchUpParticipantId",nD="assignMatchUpSideParticipant",PO="removeMatchUpSideParticipant",oD="substituteParticipant",pT="REMOVE_SUBSTITUTION",iD="REPLACE_PARTICIPANT",xg="REMOVE_PARTICIPANT",mT="setMatchUpStatus",dT="SUBSTITUTION",sD="SCHEDULE",RG="PENALTY",lT="REFEREE",aD="STATUS",fT="START",cD="SCORE",gT="END",DO={REPLACE_TEAM_POSITION_METHOD:eD,ASSIGN_TEAM_POSITION_METHOD:rD,REMOVE_TEAM_POSITION_METHOD:uT,REPLACE_PARTICIPANT:iD,SUBSTITUTION_METHOD:oD,REMOVE_SUBSTITUTION:pT,REMOVE_PARTICIPANT:xg,SCHEDULE_METHOD:mT,SUBSTITUTION:dT,SCHEDULE:sD,PENALTY:RG,REFEREE:lT,STATUS:aD,SCORE:cD,START:fT,END:gT};function NO({specifiedPolicyDefinitions:t,inContextDrawMatchUps:e,matchUpParticipantIds:r,matchUpActionsPolicy:n,inContextMatchUp:o,policyActions:i,enforceGender:s,participantId:a,sideNumber:c,matchUpId:u,matchUp:p,drawId:m,side:d}){let l=[],f=o.sides?.find(F=>F.participant),g=o.gender===Tr&&o.sideNumber&&o.sides?.filter(F=>F.particiapntId).length===1&&f?.participant?.person?.sex,I=o.matchUpType,S=(s??n?.participants?.enforceGender)!==!1?o.gender:void 0,y=o.sides?.flatMap(F=>F.participant?.individualParticipants||F.participant).filter(Boolean)?.map(St),P=o.sides?.filter(F=>!c||F.sideNumber===c).flatMap(F=>F.participant?.individualParticipants||F.participant).filter(Boolean),U=P?.map(St),E=e?.find(F=>F.matchUpId===o.matchUpTieId)?.sides?.map(F=>F?.participant?.individualParticipants?.filter(({participantId:L,person:w})=>!U?.includes(L)&&(!S||S===Pn||w.sex===S||S===Tr&&!g||g&&w.sex!==g))),N=c?E?.[c-1]:E?.map((F,L)=>({participants:F,sideNumber:L+1})),D=c?E?.[c-1]?.map(St):E?.map((F,L)=>({participants:F?.map(St),sideNumber:L+1})),M=c&&(ue(aa)(I)&&!U?.length||ue(vi)(I)&&(U?.length??0)<2)||!c&&(ue(aa)(I)&&(U?.length??0)<2||ue(vi)(I)&&(U?.length??0)<4),R=D?.filter(F=>!y?.includes(F)),b=N?.filter(({participantId:F})=>R.includes(F));if(M&&R?.length&&l.push({availableParticipantIds:R,method:rD,availableParticipants:b,type:ys,payload:{participantId:void 0,tieMatchUpId:u,sideNumber:c,drawId:m}}),U?.length&&(!Ie(p)||d?.substitutions?.length)&&l.push({method:uT,type:xg,existingParticipantIds:U,payload:{participantId:void 0,tieMatchUpId:u,drawId:m}}),b?.length&&(!c&&U?.length||c&&d?.participant)&&l.push({availableParticipantIds:R,method:eD,availableParticipants:b,type:iD,existingParticipantIds:U,payload:{existingParticipantId:void 0,participantId:void 0,tieMatchUpId:u,drawId:m}}),Vn({policyActions:i,action:pT})&&d?.substitutions?.length){let F=d.participant?.participantType===Tt&&[d.participantId]||d.participant?.participantType===ft&&d.participant.individualParticipantIds||[],L=d.substitutions.map(w=>w.participantId).filter(w=>F.includes(w));(!a||L.includes(a))&&l.push({method:uT,type:pT,substitutedParticipantIds:L,payload:{participantId:void 0,tieMatchUpId:u,drawId:m}})}let v=t?.[er],O=v?.substituteWithoutScore,x=v?.substituteAfterCompleted;if(Vn({policyActions:i,action:dT})&&r.length===2&&(!c&&U?.length||c&&d?.participant)&&(O||Ie(p))&&(x||p.matchUpStatus&&!ce.includes(p.matchUpStatus))&&P?.length&&N.length){let F=P.map(St);l.push({info:"list of team players available for substitution",method:oD,availableParticipantIds:D,existingParticipantIds:F,availableParticipants:N,existingParticipants:P,type:dT,payload:{substituteParticipantId:void 0,existingParticipantId:void 0,sideNumber:c,matchUpId:u,drawId:m}})}return l}function MO({tournamentParticipants:t=[],possiblyDisablingAction:e,activeDrawPositions:r,positionAssignments:n,returnParticipants:o,appliedPolicies:i,drawDefinition:s,drawPosition:a,validActions:c,structureId:u,structure:p,drawId:m,event:d}){if(r.includes(a))return{};let l=c.find(E=>E.type===ys)?.availableParticipantIds,f=i?.[So]?.otherFlightEntries,g=i?.[So]?.restrictQualifyingAlternates,I=(s.entries??[]).filter(({entryStage:E})=>!g||(p.stage===ct?E===ct:E!==ct)).sort((E,N)=>(E.entryPosition??1/0)-(N.entryPosition??1/0)).map(({participantId:E})=>E).filter(Boolean),{allPositionedParticipantIds:h}=Bh({drawDefinition:s}),S=n.map(E=>E.participantId).filter(Boolean),T=I.filter(E=>p.stage&&[ct,nt,de].includes(p.stage)?!h?.includes(E):!S.includes(E)),P=(d?.entries??[]).filter(E=>E.entryStatus===nn&&uD({restrictQualifyingAlternates:g,structure:p,entry:E})&&(p.stage&&[ct,nt,de].includes(p.stage)?!h?.includes(E.participantId):!S.includes(E.participantId))).sort((E,N)=>(E.entryPosition??1/0)-(N.entryPosition??1/0)).map(E=>E.participantId),U=ut(T.concat(P));if(f){let N=(d?Ht({event:d}).flightProfile:void 0)?.flights?.filter(D=>D.drawId!==m).map(D=>D.drawEntries.filter(M=>M.participantId&&![so,Gr,Ei].includes(M.entryStatus)&&!I.includes(M.participantId)).map(({participantId:M})=>M)).flat().filter(Boolean);N?.length&&U.push(...N)}l?.length&&(U=U.filter(E=>!l.includes(E)));let A=o?t?.filter(E=>U.includes(E.participantId)):void 0;return A?.forEach(E=>{let N=(s.entries??[]).find(D=>D.participantId===E.participantId);E.entryPosition=N?.entryPosition}),A?.sort((E,N)=>(E.entryPosition||1/0)-(N.entryPosition||1/0)),U.length?{validAlternatesAction:ot({payload:{drawId:m,structureId:u,drawPosition:a},willDisableLinks:e,method:Yv,availableAlternatesParticipantIds:U,type:Ag,availableAlternates:A})}:{}}function uD({restrictQualifyingAlternates:t,structure:e,entry:r}){let{stage:n}=e;if(!r.entryStage||r.entryStage===n||n===ct&&!t||r.entryStage===nt&&n===qe)return!0}function RO({eventEntries:t,structure:e}){let r=o=>o.entryStatus===nn&&uD({structure:e,entry:o}),n=(o,i)=>(o.entryPosition||1/0)-(i.entryPosition||1/0);return t.filter(r).sort(n).map(St)}function CO({restrictAdHocRoundParticipants:t,tournamentParticipants:e,matchUpParticipantIds:r,otherFlightEntries:n,drawDefinition:o,structureId:i,sideNumber:s,matchUpId:a,structure:c,matchUp:u,drawId:p,event:m}){let d=[],l=c?.matchUps??[],g=u.sides?.find(N=>N.sideNumber===s)?.participantId,I=l.filter(({roundNumber:N})=>N===u.roundNumber),h=o?.entries?.filter(({entryStatus:N})=>N&&ni.includes(N)).map(St)??[],S=I.map(N=>(N.sides??[]).flatMap(St)).flat().filter(Boolean),T=h.filter(N=>!r.includes(N)&&(!t||!S.includes(N))),y=e?.filter(N=>T?.includes(N.participantId)).map(N=>J(N,void 0,!0));y?.forEach(N=>{let D=(o.entries??[]).find(M=>M.participantId===N.participantId);N.entryPosition=D?.entryPosition}),T.length&&d.push({payload:{drawId:p,matchUpId:a,structureId:i,sideNumber:s},method:nD,type:ys,availableParticipantIds:T,participantsAvailable:y});let P=m?.entries??[],U=RO({eventEntries:P,structure:c}),A=ut(h.concat(U));if(n){let D=(m?Ht({event:m}):void 0)?.flights?.filter(M=>M.drawId!==p).flatMap(M=>M.drawEntries.filter(R=>R.participantId&&![so,Gr,Ei].includes(R.entryStatus)).map(({participantId:R})=>R)).filter(Boolean);D?.length&&A.push(...D)}A=A.filter(N=>!r.includes(N)&&!T.includes(N)&&(!t||!S.includes(N)));let E=e?.filter(N=>A.includes(N.participantId)).map(N=>J(N,void 0,!0));if(E?.forEach(N=>{let D=(o.entries??[]).find(M=>M.participantId===N.participantId);N.entryPosition=D?.entryPosition}),E?.sort((N,D)=>(N.entryPosition||1/0)-(D.entryPosition||1/0)),A.length&&d.push({payload:{drawId:p,matchUpId:a,structureId:i,sideNumber:s},availableParticipantIds:A,participantsAvailable:E,method:nD,type:nn}),!Ie(u)&&s&&g){d.push({payload:{drawId:p,matchUpId:a,structureId:i,sideNumber:s},method:PO,type:xg});let N=L=>L.sides.map(St),D=({matchUpId:L})=>L!==u.matchUpId,M=L=>!Ie(L),R=u.sides?.find(L=>L.sideNumber!==s)?.participantId,v=l.filter(({roundNumber:L})=>L!==u.roundNumber).filter(D).map(N),O=[R,...v.filter(L=>L.includes(g)).flat()].filter(Boolean),x=L=>!O.flat().includes(L),F=I.filter(M).filter(D).map(N).flat().filter(x);if(F.length){let L=e?.filter(w=>F.includes(w.participantId)).map(w=>J(w,void 0,!0));d.push({payload:{participantIds:[g],roundNumber:u.roundNumber,structureId:i,sideNumber:s,matchUpId:a,drawId:p},swappableParticipantIds:F,method:Kv,type:Lp,swappableParticipants:L})}}return d}function Od(t){if(!t)return{error:G};let{drawDefinition:e,event:r}=t,{restrictAdHocRoundParticipants:n=!0,policyDefinitions:o,enforceGender:i,participantId:s,sideNumber:a,matchUpId:c}=t,u=t.tournamentRecord??(t.tournamentId&&Vt(t.tournamentId)&&t.tournamentRecords?.[t.tournamentId]);if(!u)return{error:Y};if(!c||!Vt(c))return{error:sr};if(a&&![1,2].includes(a))return _({result:{error:G},context:{sideNumber:a}});if(!e){let X=(Te({tournamentRecord:u}).matchUps??[]).find(it=>it.matchUpId===c);r=(u?.events??[]).find(it=>it.eventId===X?.eventId);let lt=(r?.drawDefinitions??[]).find(it=>it.drawId===X?.drawId);lt&&(e=lt)}if(!e)return{error:Z};let p=Gt({withIndividualParticipants:!0,tournamentRecord:u}).participants,{drawId:m}=e,{matchUp:d,structure:l}=Bt({drawDefinition:e,matchUpId:c,event:r});if(!d)return{error:Le};let f=yt({tournamentRecord:u,drawDefinition:e,structure:l,event:r}).appliedPolicies??{};Object.assign(f,o??{});let g=f?.[So]?.otherFlightEntries,I=f?.[er]??hs[er],{enabledStructures:h}=aT({actionType:sT,appliedPolicies:f,drawDefinition:e,structure:l}),{policyActions:S}=cT({enabledStructures:h,drawDefinition:e,structure:l}),T=t.matchUpsMap??Me({drawDefinition:e}),y=t.inContextDrawMatchUps??se({tournamentParticipants:p,inContext:!0,drawDefinition:e,matchUpsMap:T,event:r}).matchUps,P=y?.find(z=>z.matchUpId===c),U=a&&P?.sides?.find(z=>z.sideNumber===a),A=P?.sides?.map(z=>z.participantId||z.participant?.participantid).filter(Boolean)??[],{assignedPositions:E,allPositionsAssigned:N}=Se({structure:l}),{structureId:D}=l??{},M=[];if(!D)return{validActions:M};let R=cr({structure:l}),b=d.collectionId;if(R&&!b){let z=CO({restrictAdHocRoundParticipants:n,tournamentParticipants:p,matchUpParticipantIds:A,otherFlightEntries:g,drawDefinition:e,structureId:D,sideNumber:a,matchUpId:c,structure:l,matchUp:d,drawId:m,event:r});M.push(...z)}let v=ai({drawDefinition:e,structure:l}),O=E?.filter(z=>z.participantId).map(z=>z.drawPosition),x=E?.filter(z=>z.bye).map(z=>z.drawPosition),F=d.matchUpStatus===Nt||!b&&d.drawPositions?.reduce((z,X)=>x?.includes(X)||z,!1);if(F)return{validActions:M,isByeMatchUp:F};Vn({policyActions:S,action:lT})&&M.push({type:lT,payload:{matchUpId:c}});let L=!Ua({matchUpStatus:d.matchUpStatus}),w=f?.scoring?.structures,V=l?.stage&&w?.stage&&w?.stage[l.stage],k=l?.stageSequence&&V?.stageSequence&&V.stageSequence[l.stageSequence],H=!(f?.scoring?.requireAllPositionsAssigned||V?.requireAllPositionsAssigned||k?.requireAllPositionsAssigned)||N,q=d.sides&&d.sides.filter(z=>z?.participantId).length===2,$=d.matchUpStatus&&[he,be].includes(d.matchUpStatus),B=ur({inContextDrawMatchUps:y,drawDefinition:e,matchUpId:c}),K=Ci({inContextDrawMatchUps:y,drawDefinition:e,targetData:B}),j=(P?.drawPositions?.length===2&&P.drawPositions.every(z=>O?.includes(z))&&P?.sides?.length===2&&P.sides.every(({participantId:z})=>z)||q)&&!($&&K),tt={method:kS,type:Qs,payload:{drawId:m,matchUpId:c,penaltyCode:void 0,penaltyType:void 0,participantIds:[],notes:void 0}};if(L&&M.push({payload:{drawId:m,matchUpId:c,schedule:{}},method:mT,type:sD}),Vn({policyActions:S,action:Qs})&&(U?.participant||!a&&A?.length)&&M.push(tt),L&&j&&M.push({type:aD}),H&&j){let{matchUpId:z,matchUpFormat:X}=d,lt={drawId:m,matchUpId:z,matchUpFormat:X,outcome:{scoreStringSide1:void 0,scoreStringSide2:void 0,sets:[]},winningSide:void 0};M.push({info:"set outcome and winningSide",method:mT,type:cD,payload:lt}),Vn({policyActions:S,action:fT})&&M.push({type:fT}),Vn({policyActions:S,action:gT})&&M.push({type:gT})}if(b&&P){let z=NO({specifiedPolicyDefinitions:o,inContextDrawMatchUps:y,matchUpParticipantIds:A,matchUpActionsPolicy:I,inContextMatchUp:P,policyActions:S,enforceGender:i,participantId:s,sideNumber:a,matchUpId:c,matchUp:d,drawId:m,side:U});M.push(...z)}return{structureIsComplete:v,validActions:M,isDoubleExit:$,...C}}function bO({tournamentParticipants:t=[],sourceStructuresComplete:e,possiblyDisablingAction:r,isWinRatioFedStructure:n,activeDrawPositions:o,positionAssignments:i,drawDefinition:s,drawPosition:a,structureId:c,structure:u,drawId:p,event:m}){if(o.includes(a)||n&&!e)return{};let{sourceStructureIds:d,targetStructureIds:l}=s.links?.reduce((h,S)=>{let T=S.source?.structureId,y=S.target?.structureId;return h.sourceStructureIds.includes(T)||h.sourceStructureIds.push(T),h.targetStructureIds.includes(y)||h.targetStructureIds.push(y),h},{sourceStructureIds:[],targetStructureIds:[]})||{},f=[],g=s.links?.filter(h=>h.target?.structureId===u.structureId)??[];for(let h of g){let S=h?.source?.structureId,{structure:T}=at({structureId:S,drawDefinition:s}),y=T?.finishingPosition===Gi&&(d?.length!==1||l?.length!==1),P={};if(y){let{matchUps:N}=Ut({drawDefinition:s,structure:u,event:m}),{initialRoundNumber:D}=fs({drawPosition:a,matchUps:N}),R=s.links?.find(b=>b.target?.structureId===u?.structureId&&b.target.roundNumber===D)?.source?.roundNumber;P.roundNumbers=[R]}let{completedMatchUps:U}=Su({structureId:S,inContext:!0,matchUpFilters:P,drawDefinition:s}),A=i.map(N=>N.participantId).filter(Boolean);U?.filter(({matchUpType:N,winningSide:D})=>D&&(m?.eventType!==_e||N===_e)).map(({winningSide:N,sides:D})=>N&&D?.[1-(N-1)]).map(St).filter(N=>N&&!A.includes(N))?.forEach(N=>{f.includes(N)||f.push(N)})}let I=t?.filter(h=>f?.includes(h.participantId));return I?.forEach(h=>{let S=(s.entries??[]).find(T=>T.participantId===h.participantId);h.entryPosition=S?.entryPosition}),f?.length?{validLuckyLosersAction:{type:Ug,method:qv,availableLuckyLosers:I,availableLuckyLoserParticipantIds:f,willDisableLinks:r,payload:{drawId:p,structureId:c,drawPosition:a}}}:{}}function vO({positionSourceStructureIds:t,unassignedParticipantIds:e,possiblyDisablingAction:r,provisionalPositioning:n,tournamentParticipants:o,isWinRatioFedStructure:i,positionAssignments:s,returnParticipants:a,appliedPolicies:c,drawDefinition:u,seedingProfile:p,isByePosition:m,drawPosition:d,structureId:l,event:f}){let{drawId:g}=u,I=[],h,S,T=[],y=c?.[xn]?.validSeedPositions?.ignore;if(y||({unplacedSeedParticipantIds:h,unplacedSeedAssignments:S,unfilledPositions:T}=US({provisionalPositioning:n,returnAllProxies:!0,randomize:!0,drawDefinition:u,seedingProfile:p,structureId:l,event:f})),T?.length||(T=s.filter(P=>!P.participantId&&!P.bye&&!P.qualifier).map(P=>P.drawPosition)),m||I.push({payload:{drawId:g,structureId:l,drawPosition:d,isPositionAction:!0},willDisableLinks:r,method:Xv,type:Ed}),i&&y){let P=s.map(D=>D.participantId).filter(Boolean),U={structureIds:t},{completedMatchUps:A}=js({inContext:!0,matchUpFilters:U,drawDefinition:u}),E=ut((A??[]).filter(({matchUpType:D})=>f?.eventType!==_e||D===_e)?.map(({sides:D})=>D?.map(St)).flat().filter(D=>D&&!P.includes(D))),N=a?o?.filter(D=>E?.includes(D.participantId)).map(D=>J(D,void 0,!0)):void 0;return N?.forEach(D=>{let M=(u.entries??[]).find(R=>R.participantId===D.participantId);D.entryPosition=M?.entryPosition}),N?.length&&I.push(ot({payload:{drawId:g,structureId:l,drawPosition:d},willDisableLinks:r,method:vP,type:ys,availableParticipantIds:E,participantsAvailable:N})),{validAssignmentActions:I}}if(T.includes(d)||m){let P;if(S?.length){let A=S.filter(E=>h?.includes(E.participantId));A.sort(CG),P=A.map(E=>E.participantId)}else P=e;let U=a?o?.filter(A=>P.includes(A.participantId)).map(A=>J(A,void 0,!0)):void 0;U?.length&&I.push(ot({payload:{drawId:g,structureId:l,drawPosition:d},willDisableLinks:r,method:vP,type:ys,availableParticipantIds:P,participantsAvailable:U}))}return{validAssignmentActions:I}}function CG(t,e){return t.bye||Ic(t.seedValue)<Ic(e.seedValue)||t.seedValue&&!e.seedValue?-1:(t.seedNumber||0)-(e.seedNumber||0)}function OO({drawPositionInitialRounds:t,tournamentParticipants:e,positionAssignments:r,returnParticipants:n,appliedPolicies:o,drawDefinition:i,drawPosition:s,structureId:a,drawId:c}){let u=[],p=[],m=[],d=[],l=r.map(P=>P.participantId).filter(Boolean),f=o?.[So],g=!f?.disableRoundRestrictions&&t[s],I=f?.requireCompletedStructures,{sourceStructureIds:h,relevantLinks:S}=Og({targetRoundNumber:g,linkType:fo,drawDefinition:i,structureId:a})||{};h?.length&&d.push(...h);let{sourceStructureIds:T,relevantLinks:y}=Og({targetRoundNumber:g,linkType:eo,drawDefinition:i,structureId:a})||{};T?.length&&d.push(...T);for(let P of S){let U=i.structures?.find(E=>E.structureId===P.source.structureId);if(U?.stage!==ct)continue;let A=ai({structureId:P.source.structureId,drawDefinition:i});if(!I||A){let E=U.qualifyingRoundNumber,{matchUps:N}=Ut({matchUpFilters:{roundNumbers:[E],hasWinningSide:!0},afterRecoveryTimes:!1,tournamentParticipants:e,inContext:!0,structure:U});for(let D of N){let M=D.sides.find(b=>b?.sideNumber===D.winningSide),R=D.matchUpStatus===Nt&&D.sides?.find(({participantId:b})=>b);if(M||R){let{participantId:b,participant:v}=M||R||{};b&&!l.includes(b)&&(v&&n&&u.push(v),p.push(b))}}}}for(let P of y){let U=i.structures?.find(E=>E.structureId===P.source.structureId);if(U?.stage!==ct)continue;let A=ai({structureId:P.source.structureId,drawDefinition:i});if(!I||A){let{positionAssignments:E}=bt({structure:U}),N=E?.map(D=>{let M=D.participantId,R=dt({element:D,name:Zo}).extension?.value;return R?{participantId:M,groupOrder:R?.groupOrder}:{}}).filter(({groupOrder:D,participantId:M})=>D===1&&!l.includes(M)).map(({participantId:D})=>D)??[];if(N&&p.push(...N),n){let D=e.filter(({participantId:M})=>N.includes(M));u.push(...D)}}}return p.length&&m.push(ot({qualifyingParticipants:n?u:void 0,method:Wv,type:xp,qualifyingParticipantIds:p,payload:{qualifyingParticipantId:void 0,drawPosition:s,structureId:a,drawId:c}})),{validAssignmentActions:m,sourceStructureIds:d}}function _O({onlyAssignedPositions:t=!0,possiblyDisablingAction:e,tournamentParticipants:r,inactiveDrawPositions:n,activeDrawPositions:o,positionAssignments:i,returnParticipants:s,byeDrawPositions:a,drawDefinition:c,isByePosition:u,drawPosition:p,structureId:m,structure:d,drawId:l,event:f}){if(o.includes(p))return{};let g=D=>!t||D.participantId||D.qualifier||D.bye,I=n?.filter(D=>D!==p&&!(u&&a.includes(D))),h=i?.filter(D=>g(D)&&I?.includes(D.drawPosition))??[],S=h.map(({drawPosition:D})=>D),{matchUps:T}=Ut({afterRecoveryTimes:!1,inContext:!0,drawDefinition:c,structure:d,event:f}),y=T.filter(({drawPositions:D})=>Fe(D,S)),P=Object.assign({},...y.map(D=>D.sides?.filter(({sourceDrawPositionRange:M})=>M).map(({drawPosition:M,sourceDrawPositionRange:R})=>({[M]:R}))).flat()),U=h.map(D=>D.participantId).filter(Boolean),A=(r??[]).filter(D=>U.includes(D.participantId)),E=Object.assign({},...A.map(D=>({[D.participantId]:D}))),N=h.map(D=>{let M=E?.[D.participantId],R=P[D.drawPosition];return ot({...D,participant:s?J(M,!1,!0):void 0,sourceDrawPositionRange:R})});return N.length?{validSwapAction:{payload:{drawId:l,structureId:m,drawPositions:[p]},willDisableLinks:e,method:FS,type:Lp,availableAssignments:N}}:{}}function IT(t){let e=rt(t,[{event:!0,drawDefinition:!0,structureId:!0}]);if(e.error)return e;let{policyDefinitions:r,returnParticipants:n=!0,provisionalPositioning:o,tournamentRecord:i,drawDefinition:s,drawPosition:a,event:c}=t,u=t.tournamentParticipants??(i&&Gt({withIndividualParticipants:!0,tournamentRecord:i}).participants)??[],p=at({structureId:t.structureId,drawDefinition:s});if(p.error)return p;let m=p.containingStructure||p.structure;if(!m)return{error:kt};let d=m.structureId;if(p=Pa({drawDefinition:s,structureId:d}),a===void 0&&!p.isAdHoc)return{error:Cs};if(p.isAdHoc)return Od(t);if(p.error)return p;let{drawPositionInitialRounds:l,inactiveDrawPositions:f,activeDrawPositions:g,byeDrawPositions:I}=p,h=yt({tournamentRecord:i,drawDefinition:s,structure:m,event:c}).appliedPolicies??{};Object.assign(h,r??{});let{actionsPolicy:S,enabledStructures:T,actionsDisabled:y}=aT({actionType:_g,appliedPolicies:h,drawDefinition:s,structure:m}),P=S?.activePositionOverrides||[],{sourceStructureIds:U}=Og({finishingPosition:fi,targetRoundNumber:1,linkType:eo,drawDefinition:s,structureId:d})||{},A;U?.length&&(A=U.every(j=>ai({structureId:j,drawDefinition:s})));let E=U.length,N=U.length&&!A,{policyActions:D}=cT({enabledStructures:T,drawDefinition:s,structure:m}),M=![ct,nt].includes(m.stage)||m.stageSequence!==1,{drawId:R}=s,b=[],{assignedPositions:v,positionAssignments:O}=Se({structure:m}),x=v?.find(j=>j.drawPosition===a),F=!!x;if(!O?.map(j=>j.drawPosition)?.includes(a))return{error:Rs};let{stage:w,stageSequence:V}=m,k=[w];w===qe&&k.push(nt),w===nt&&k.push(qe);let W=Ui({entryStatuses:ni,provisionalPositioning:o,drawDefinition:s,stageSequence:V,structureId:d,stages:k}),H=Ri({drawDefinition:s,stages:k}).assignedParticipantIds??[],q=W.filter(j=>!H.includes(j.participantId)).map(j=>j.participantId),$=I.includes(a),B=g.includes(a);if(y)return{info:"Actions Disabled for structure",isActiveDrawPosition:B,isDrawPosition:!0,hasPositionAssigned:F,validActions:[],isByePosition:$};if(Vn({policyActions:D,action:ys})&&!B&&O&&!N&&(!x||$)){let{validAssignmentActions:j}=vO({positionSourceStructureIds:U,unassignedParticipantIds:q,possiblyDisablingAction:M,isWinRatioFedStructure:E,tournamentParticipants:u,positionAssignments:O,returnParticipants:n,appliedPolicies:h,drawDefinition:s,isByePosition:$,drawPosition:a,structureId:d,event:c});j?.forEach(tt=>b.push(tt))}if(Vn({policyActions:D,action:xp})&&!B){let{validAssignmentActions:j}=OO({drawPositionInitialRounds:l,tournamentParticipants:u,positionAssignments:O,returnParticipants:n,appliedPolicies:h,drawDefinition:s,drawPosition:a,structureId:d,drawId:R});j?.forEach(tt=>b.push(tt))}let{participantId:K}=x||{},Q=K&&u.find(j=>j.participantId===K);if(x){Vn({policyActions:D,action:GS})&&!B&&(b.push({type:GS,method:bP,payload:{drawId:R,structureId:d,drawPosition:a},willDisableLinks:M}),$||b.push({type:Eg,method:jv,payload:{drawId:R,structureId:d,drawPosition:a},willDisableLinks:M}),Vn({policyActions:D,action:Ed})&&!$&&b.push({type:Ed,method:bP,payload:{drawId:R,structureId:d,drawPosition:a,replaceWithBye:!0},willDisableLinks:M}));let j=m.stage===ct||m.stage===nt&&m.stageSequence===1;if(!$&&tD({activePositionOverrides:P,activeDrawPositions:g,action:zs})&&Vn({policyActions:D,action:zs})&&vp({drawDefinition:s,structureId:d,drawPosition:a})&&j){let{seedAssignments:tt}=on({returnAllProxies:!0,drawDefinition:s,structure:m}),{seedNumber:z,seedValue:X}=tt?.find(lt=>lt.participantId===K)??{};b.push({type:zs,method:Jv,participant:Q,seedNumber:z,payload:{drawId:R,structureId:d,participantId:K,seedValue:X}})}if(!$&&tD({activePositionOverrides:P,activeDrawPositions:g,action:wp})&&Vn({policyActions:D,action:wp})&&vp({drawDefinition:s,structureId:d,drawPosition:a})&&j){let{seedAssignments:tt}=on({returnAllProxies:!0,drawDefinition:s,structure:m}),{seedNumber:z}=tt?.find(X=>X.participantId===K)??{};b.push({method:Qv,type:wp,participant:Q,seedNumber:z,payload:{participantId:K,structureId:d,drawId:R}})}if(!$&&K){if(Vn({policyActions:D,action:Qs})){let tt={type:Qs,method:kS,participant:Q,payload:{penaltyCode:void 0,penaltyType:void 0,participantIds:[],notes:void 0,drawId:R}};b.push(tt)}if(Vn({policyActions:D,action:Pu})){let tt={type:Pu,method:zv,participant:Q,payload:{participantId:K,otherName:void 0}};b.push(tt)}}if(Vn({policyActions:D,action:Lp})){let{validSwapAction:tt}=_O({possiblyDisablingAction:M,tournamentParticipants:u,inactiveDrawPositions:f,activeDrawPositions:g,positionAssignments:O,returnParticipants:n,byeDrawPositions:I,drawDefinition:s,isByePosition:$,drawPosition:a,structureId:d,structure:m,drawId:R});tt&&b.push(tt)}}if(Vn({policyActions:D,action:Ag})&&!N){let{validAlternatesAction:j}=MO({possiblyDisablingAction:M,tournamentParticipants:u,positionAssignments:O,activeDrawPositions:g,returnParticipants:n,appliedPolicies:h,drawDefinition:s,drawPosition:a,validActions:b,structureId:d,structure:m,drawId:R,event:c});j&&b.push(j)}if(Vn({policyActions:D,action:Ug})&&!N&&!B&&O){let{validLuckyLosersAction:j}=bO({sourceStructuresComplete:A,possiblyDisablingAction:M,isWinRatioFedStructure:E,tournamentParticipants:u,activeDrawPositions:g,positionAssignments:O,drawDefinition:s,drawPosition:a,structureId:d,structure:m,drawId:R});j&&b.push(j)}if(Q?.participantType===ft&&Vn({policyActions:D,action:yg})){let{validModifyAssignedPairAction:j}=UO({tournamentParticipants:u,returnParticipants:n,drawPosition:a,participant:Q,drawId:R,event:c});j&&b.push(j)}return{isActiveDrawPosition:B,isDrawPosition:!0,hasPositionAssigned:F,isByePosition:$,validActions:b,...C}}function vu({policyDefinitions:t,appliedPolicies:e,drawType:r}){let n=t?.[Bm]?.drawTypeCoercion,o=e?.[Bm]?.drawTypeCoercion;return(typeof n=="boolean"?n:void 0)??(r&&n?.[r])??(typeof o=="boolean"?o:void 0)??(r&&o?.[r])??!0}function Vp({tournamentRecord:t,drawDefinition:e,stage:r=nt,structureId:n,structure:o}){if(!t)return{error:Y};if(!o&&!e)return{error:Z};if(!o&&!n&&e?.structures?.filter(a=>a.stage===r).length===1&&(o=e.structures.find(a=>a.stage===r)),!o&&!n)return{error:Ur};let{error:i,positionAssignments:s}=bt({drawDefinition:e,structureId:n,structure:o});return{positionAssignments:s??[],structureId:o?.structureId,error:i}}function hT({structureId:t,drawDefinition:e}){if(!e)return{error:Z};if(!Vt(t))return{error:G};let r=Ws({drawDefinition:e,structureId:t});if(r.error)return r;let n=r.links.target.flatMap(i=>i.target.feedProfile).filter(Boolean),o=!Yt([li,En,up,di],n).length;return{...C,valid:o}}function ST({participantsCount:t,participantCount:e}){if(t=t??e,!t)return{error:G};let r=es(t);return r?{drawSize:r}:_({result:{error:G},stack:"getEliminationDrawSize",context:{participantsCount:t}})}function Ou(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=vo({tournamentRecord:i,drawDefinition:s,event:a});if(I.error)return _({result:I,stack:c});r=I.policyDefinitions}let p=It(u);if(u&&!p)return _({result:{error:G},context:{participantsCount:u},stack:c});if(o&&!p)return _({result:{error:uE},stack:c});if(isNaN(n))if(u)({drawSize:n}=ST({participantsCount:u}));else return _({result:{error:Ya},stack:c});let m=o&&u||n;if(m&&m>n)return{error:Kl};let d=r?.[xn];if(!d)return{error:XA};let l=d.seedsCountThresholds;return l?(d.drawSizeProgression!==void 0&&(e=d.drawSizeProgression),{seedsCount:l.filter(I=>e?I.drawSize<=n:n===I.drawSize).reduce((I,h)=>u&&u>=h.minimumParticipantCount?h.seedsCount:I,0)}):{error:wA}}function _d({consideredEntries:t,policyDefinitions:e,tournamentRecord:r,appliedPolicies:n,participantMap:o,enforceGender:i,participants:s,event:a}){if((!s||!o)&&r&&({participants:s,participantMap:o}=Gt({tournamentRecord:r})),!s)return{error:$a};if(!Array.isArray(s))return{error:G};if(!a)return{error:vt};let c=e?.[er]??n?.[er]??hs[er],u=(i??c?.participants?.enforceGender)!==!1,{eventType:p,gender:m}=a,d=p===ko,l=p===br&&wt||d&&ft||Tt,f=Object.assign({},...(t??a.entries??[]).map(S=>({[S.participantId]:S.entryStatus}))),g=Object.keys(f),h=s.filter(S=>g.includes(S.participantId)).filter(S=>{let T=bG({participant:S,participantType:l,eventType:p,entryStatusMap:f}),y=vG({genderEnforced:u,participantMap:o,eventGender:m,participant:S,isDoubles:d,mismatch:T});return T||!y});if(h.length){let S=h.map(T=>T.participantId);return{error:jA,invalidParticipantIds:S}}return{...C,valid:!0}}function bG({participant:t,participantType:e,eventType:r,entryStatusMap:n}){let o=n[t.participantId],i=r&&[ko,br].includes(r)&&t.participantType===Tt&&(Ys(o)||o===so);return t.participantType!==e&&!i}function vG(t){let{participant:e,participantMap:r,eventGender:n,mismatch:o,isDoubles:i,genderEnforced:s}=t,a=!o&&i&&ut(e?.individualParticipantIds?.map(m=>r?.[m]?.participant?.person?.sex).filter(Boolean)??[])||[],c=!n||!a?.length||Pn===n||[$t,ne].includes(n)&&a[0]===n||Tr===n&&(a.length===1&&e.individualParticipantIds?.length===1||a.length===2),u=e?.person?.sex,p=!e?.person||!n||[Pn,Tr].includes(n)||[$t,ne].includes(n)&&u===n;return!s||c&&p}function TT({qualifyingProfiles:t,appliedPolicies:e,idPrefix:r,isMock:n,uuids:o}){let i="generateQualifyingSTructures",s=[],a=[],c=[],u=(g,I)=>g.stageSequence-I.stageSequence,p=(g,I)=>g.roundTarget-I.roundTarget,m=0,d=0,l,f=1;for(let g of t.sort(p)){let I=g.structureProfiles||[];f=g.roundTarget||f;let h=1,S=0,T,y,P;for(let U of(I||[]).sort(u)){let A=Sm(U.drawSize||U.participantsCount),{qualifyingRoundNumber:E,structureOptions:N,matchUpFormat:D,structureName:M,structureId:R,drawType:b}=U,v=U.matchUpType,O=U.qualifyingPositions||OG({drawSize:A,qualifyingRoundNumber:E}),x,F,L;if(!It(A))return _({result:{error:Ya},stack:i});let w=t.length>1?`${f}-`:"",V=I.length>1||w?h:"",k=M||(w||V?`${Qe(ct)} ${w}${V}`:Qe(ct));if(b===Nn){let{structures:W,groupCount:H,maxRoundNumber:q}=Na({structureName:U.structureName||k,structureId:R||o?.pop(),stage:ct,structureOptions:N,appliedPolicies:e,stageSequence:h,matchUpType:v,roundTarget:f,drawSize:A,idPrefix:r,isMock:n,uuids:o});S=H,x=q,F=W[0],l=[1]}else({drawSize:A,matchUps:L,roundLimit:x}=Cn({qualifyingRoundNumber:E,qualifyingPositions:O,matchUpType:v,drawSize:A,idPrefix:r,isMock:n,uuids:o})),F=hn({structureName:U.structureName||k,structureId:R||o?.pop(),qualifyingRoundNumber:x,stage:ct,matchUpFormat:D,stageSequence:h,matchUpType:v,roundLimit:x,matchUps:L}),f&&At({extension:{name:Mn,value:f},element:F}),S=L?.filter(W=>W.roundNumber===x)?.length||0;if(h>1){let{link:W}=Ma({sourceStructureId:y,sourceRoundNumber:T,targetStructureId:F.structureId,finishingPositions:P===eo?[1]:void 0,linkType:P});c.push(W),m+=(A||0)-S}else m+=A||0;P=b===Nn?eo:fo,y=F.structureId,T=x,a.push(F),h+=1}d+=S,s.push({qualifiersCount:S,finalQualifyingRoundNumber:T,finalQualifyingStructureId:y,finishingPositions:l,roundTarget:f,linkType:P}),f+=1}return{qualifiersCount:d,qualifyingDrawPositionsCount:m,qualifyingDetails:s,structures:a,...C,links:c}}function OG({drawSize:t,qualifyingRoundNumber:e}){let r=t,n=0;for(;n<e;)r=Math.floor(r/2),n+=1;return r}function yT(t){let{drawTypeCoercion:e,enforceMinimumDrawSize:r}=t,n=pt(t.drawSize),o=e&&t.drawType!==$r&&(typeof e=="boolean"||e<=2)&&n===2&&go||t.drawType||go,i=dU.includes(o);if(n&&i){if(e&&(typeof e=="boolean"&&n<4||n<=e))o=go;else if(n<4&&r)return{..._({context:{enforceMinimumDrawSize:r,drawSize:n,drawType:o},result:{error:$u},stack:"getCoercedDrawType"}),drawType:o}}return{drawType:o}}function xO(t){let{drawDefinition:e,structureOptions:r,requireSequential:n}=t,o={structureName:Qe(nt),...t,stage:nt},{structures:i,groupCount:s,groupSize:a}=Na(o);if(s<1)return{error:NE};let c=r?.playoffGroups||[{finishingPositions:[1],structureName:Qe(de)}],[u]=i,{structures:p,links:m}=YS({sourceStructureId:u.structureId,requireSequential:n,drawDefinition:e,playoffGroups:c,groupCount:s,groupSize:a,...t});return p&&i.push(...p),{...C,structures:i,links:m}}function wO({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?En:li,f=1+m;return{linkType:ro,source:{roundNumber:f,structureId:t.structureId},target:{feedProfile:l,roundNumber:p,structureId:e.structureId}}}),c={linkType:fo,source:{roundNumber:s,structureId:e.structureId},target:{feedProfile:En,roundNumber:i,structureId:t.structureId}},u=[{linkType:fo,source:{roundNumber:i,structureId:t.structureId},target:{feedProfile:En,roundNumber:1,structureId:r.structureId}},{linkType:ro,source:{roundNumber:i,structureId:t.structureId},target:{feedProfile:En,roundNumber:1,structureId:r.structureId}}];return[...a,c,...u]}function LO({structureName:t,matchUpType:e,idPrefix:r,drawSize:n,isMock:o,uuids:i}){let s=[],{matchUps:a}=ci({linkFedFinishingRoundNumbers:[1],drawSize:n+1,matchUpType:e,idPrefix:r,isMock:o}),c=Ss({structureName:t||Qe(nt),structureId:i?.pop(),stageSequence:1,stage:nt,matchUpType:e,matchUps:a});s.push(c);let u=n/2,{matchUps:p}=ci({finishingPositionOffset:u,idPrefix:r&&`${r}-c`,drawSize:n-1,isConsolation:!0,matchUpType:e,isMock:o,uuids:i}),m=Ss({structureName:Qe(mU),matchUps:p,structureId:i?.pop(),stage:qe,stageSequence:2,matchUpType:e});s.push(m);let{matchUps:d}=Cn({idPrefix:r&&`${r}-p1t2`,drawSize:2,matchUpType:e,isMock:o}),l=Ss({structureName:Qe(pU),matchUps:d,structureId:i?.pop(),stageSequence:3,stage:de,matchUpType:e});s.push(l);let f=wO({mainStructure:c,consolationStructure:m,deciderStructure:l});return{structures:s,links:f,...C}}function FO(t){let{qualifyingRoundNumber:e,finishingPositionOffset:r,qualifyingPositions:n,matchUpType:o,idPrefix:i,drawSize:s,isMock:a,uuids:c}=t;if(!It(s)||s<2)return{matchUps:[],roundsCount:0};if(vn(s))return Cn(t);let u=_G(s),p=u.shift(),m=et(1,(p?.participantsCount||0)+1).map(I=>({drawPosition:I})),d=[],l=1;({matchUps:d}=Fp({roundNumber:l,matchUpType:o,idPrefix:i,matchUps:d,isMock:a,nodes:m,uuids:c})),l++;let f=t.roundLimit||e;for(let I of u){let h=I.participantsCount/2,S=et(1,h+1);n&&h===n&&(f=l-1);let T=S.map(y=>{let P=Ud({roundPosition:y,roundNumber:l,idPrefix:i,uuids:c});return{roundPosition:y,roundNumber:l,matchUpId:P}});d.push(...T),l++}let g=l-1;return d=Ea({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 _G(t){let e=pt(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 AT(t){let{playoffAttributes:e,stageSequence:r=1,stage:n=nt,matchUpType:o,drawSize:i,uuids:s}=t,a=()=>!t.isMock&&!t.idPrefix?void 0:`${t.drawDefinition.drawId}-s-0`,c=t.structureId||a()||s?.pop(),u=t.appliedPolicies??yt(t),p=t.policyDefinitions?.[rc]||u?.[rc];t.skipRounds=t.skipRounds||i<=4&&(p?.feedFromMainFinal?0:1)||0;let m=t.structureName??e?.["0"]?.name??Qe(nt),d=()=>{let{matchUps:f}=Cn(t);return{structures:[hn({stageSequence:r,structureName:m,matchUpType:o,structureId:c,matchUps:f,stage:n})],links:[],...C}};return{generators:{[$r]:()=>({structures:[hn({finishingPosition:fi,stageSequence:r,structureName:m,matchUps:[],matchUpType:o,structureId:c,stage:n})],links:[],...C}),[ki]:()=>{let{matchUps:f}=FO(t);return{structures:[hn({stageSequence:r,structureName:m,matchUpType:o,structureId:c,matchUps:f,stage:n})],links:[],...C}},[go]:()=>d(),[Xc]:()=>LO(t),[zc]:()=>Tc({...t,roundOffsetLimit:3,playoffAttributes:e??yf}),[Qc]:()=>Tc({...t,roundOffsetLimit:2,playoffAttributes:e??Af}),[de]:()=>Tc(t),[da]:()=>{let{matchUps:f}=ci({drawSize:i,uuids:s,matchUpType:o});return{structures:[hn({stageSequence:r,structureName:m,matchUpType:o,structureId:c,stage:nt,matchUps:f})],links:[],...C}},[pp]:()=>BS(t),[Jc]:()=>Ac({...t,feedRounds:1,fmlc:!0}),[uU]:()=>Ac({...t,feedRounds:1}),[yh]:()=>Ac({...t,feedsFromFinal:1}),[Ah]:()=>Ac({...t,feedsFromFinal:2}),[Eh]:()=>Ac({...t,feedsFromFinal:3}),[mp]:()=>Ac(t),[Tf]:()=>WS(t),[Nn]:()=>Na(t),[Io]:()=>xO(t)}}}function xd(t){let{enforceMinimumDrawSize:e=!0,overwriteExisting:r,appliedPolicies:n,staggeredEntry:o,drawDefinition:i,tieFormat:s,isMock:a,uuids:c}=t||{},u=pt(t.drawSize),p=t.drawTypeCoercion??vu({appliedPolicies:n,drawType:t.drawType}),m="generateDrawStructuresAndLinks",d=yT({drawType:t.drawType,enforceMinimumDrawSize:e,drawTypeCoercion:p,drawSize:u});if(d.error)return d;let l=d.drawType,f=[],g=[],I=t?.matchUpType??Ft,h=i?.structures?.filter(({stage:W})=>W===ct);h&&f.push(...h);let S=h?.map(({structureId:W})=>W),T=i?.structures?.find(({stage:W,stageSequence:H})=>W===nt&&H===1),y=i?.links?.filter(W=>W.target.structureId===T?.structureId&&S?.includes(W.source.structureId)),P=(W,H)=>{if(W.linkType===eo&&H?.structures){let q=W.source.finishingPositions||[];return H.structures.length*q.length}else if(W.linkType===fo&&H?.matchUps?.length){let q=W.source.roundNumber;return H.matchUps.filter(({roundNumber:B})=>B===q).length}},U=h?.map(W=>{let H=y?.find(Q=>Q.target.structureId===W.structureId),q=bt({structure:W})?.positionAssignments?.length??0;if(!H)return q;let $=H?.source.structureId,B=i.structures?.find(Q=>Q.structureId===$),K=P(H,B)||0;return q-K}).filter(Boolean).reduce((W,H)=>W+H,0),A=y?.map(W=>{let H=W.source.structureId,q=h?.find($=>$.structureId===H);return P(W,q)}).filter(Boolean).reduce((W,H)=>W+H,0),E=!!(T&&!T?.matchUps?.length);if(h?.length&&!E)return{error:WI};let N=!h?.length&&t.qualifyingProfiles,D=N?.length&&TT({idPrefix:t.idPrefix,qualifyingProfiles:N,appliedPolicies:n,isMock:a,uuids:c});if(D?.error)return D;let{qualifyingDrawPositionsCount:M,qualifyingDetails:R,qualifiersCount:b}=D||{qualifyingDrawPositionsCount:U,qualifiersCount:A};M&&(D?.structures&&f.push(...D.structures),D?.links&&g.push(...D.links)),Object.assign(t,ot({drawSize:u,matchUpType:I,tieFormat:s}));let v=l!==$r&&(!u||u<2||!o&&![da,ki].includes(l)&&([Io,Nn].includes(l)&&u<3||![Nn,Io].includes(l)&&!vn(u)));if(v&&!M)return _({context:{drawSize:u,invalidDrawSize:v},result:{error:$u},stack:m});let{generators:O,error:x}=AT(t);if(x)return{error:x};let F=O[l];if(!F)return{error:Fl};let L=F?.();if(L.error)return L;let{structures:w,links:V}=L;if(w?.length){let W=w.find(({stage:H,stageSequence:q})=>H===nt&&q===1);if(T&&W){if(E){let H=W.structureId;if(W.structureId=T.structureId,V?.length)for(let q of V)q.source.structureId===H&&(q.source.structureId=T.structureId),q.target.structureId===H&&(q.target.structureId=T.structureId)}else if(!r)return{error:WI}}f.push(...w)}f.sort(Ti),V?.length&&g.push(...V);let k=L.structures.find(({stage:W,stageSequence:H})=>W===nt&&H===1);for(let W of R||[]){let{finalQualifyingRoundNumber:H,finalQualifyingStructureId:q,roundTarget:$,finishingPositions:B,linkType:K}=W,Q=k&&Ma({targetStructureId:k.structureId,sourceStructureId:q,sourceRoundNumber:H,finishingPositions:B,targetEntryRound:$,linkType:K})?.link;if(Q?.error)return Q;Q&&g.push(Q)}return y&&g.push(...y),{...C,qualifyingResult:{qualifyingDrawPositionsCount:M,qualifiersCount:b},structures:f,links:g}}function wd(t){let{modifyOriginal:e=!0,stageSequence:r=1,isMock:n}=t||{},o="generateDrawTypeAndModifyDrawDefinition";if(!t.drawDefinition)return _({result:{error:Z},stack:o});let i=e?t.drawDefinition:J(t.drawDefinition,!1,!0),{tieFormat:s,matchUpType:a}=t;if(s){let T=ar({tieFormat:s});if(T.error)return T}s=ir(s??We({drawDefinition:i})?.tieFormat),a=a??(i.matchUpType||Ft),t.tieFormat=s,t.matchUpType=a;let c=Rp({drawDefinition:i,stage:nt});t.drawSize=t.drawSize??c,!c&&t.drawSize&&_p({drawSize:t.drawSize,drawDefinition:i,stageSequence:r,stage:nt});let u=Me({drawDefinition:i}).drawMatchUps.map(Ee),p=xd(t);if(p.error)return _({result:p,stack:o});let{structures:m,links:d,qualifyingResult:l}=p;i.structures=m,i.links=d;let f=Math.max(t.qualifiersCount??0,l?.qualifiersCount||0);if(l?.qualifyingDrawPositionsCount&&!Rp({stage:ct,drawDefinition:i})){let y=_p({drawSize:l.qualifyingDrawPositionsCount,stage:ct,drawDefinition:i});if(y.error)return y}if(f){let T=LS({qualifiersCount:f,drawDefinition:i,stage:nt});if(T.error)return T}let g=t.drawSize??c;Object.assign(t,ot({drawSize:g,matchUpType:a,tieFormat:s}));let{matchUps:I,matchUpsMap:h}=se({drawDefinition:i});s&&I?.forEach(T=>{if(!u.includes(T.matchUpId)){let{tieMatchUps:y}=Ra({tieFormat:s,matchUp:T,isMock:n});Object.assign(T,{tieMatchUps:y,matchUpType:a})}});let{inContextDrawMatchUps:S}=qi({drawDefinition:i,matchUpsMap:h});return Ot({tournamentId:t.tournamentRecord?.tournamentId,drawDefinition:i}),{inContextDrawMatchUps:S,drawDefinition:i,matchUpsMap:h,...C,structures:m,matchUps:I,links:d}}function Dc(t){let{removePriorValues:e,tournamentRecord:r,participantId:n,scaleItem:o}=t,i,s;if(!kO({scaleItem:o}))return{error:Ka};if(n&&Array.isArray(r.participants)&&(s=r.participants.find(a=>a.participantId===n),s)){if(s.participantType===yr&&o?.eventType!==br)return{error:Ka};let a=GO({removePriorValues:e,participant:s,scaleItem:o});if(a.error)return a;i=!a.valueChanged;let{topics:c}=Lr();c.includes(nr)&&mt({topic:nr,payload:{tournamentId:r.tournamentId,participants:[s]}})}return i&&{...C,info:rf,existingValue:o?.scaleValue}||s&&{...C,newValue:o?.scaleValue}||{error:te}}function mD(t){let{scaleItemsWithParticipantIds:e=[],removePriorValues:r,tournamentRecord:n,auditData:o,context:i}=t;if(!n)return{error:Y};if(!n.participants)return{error:$a};let s=0,a={},c=[];for(let m of e){let d=m?.participantId;if(Array.isArray(m?.scaleItems))for(let l of m.scaleItems)if(kO({scaleItem:l}))Array.isArray(a[d])||(a[d]=[]),a[d].push(l);else return{error:Ka}}for(let m of n.participants){let{participantId:d}=m||{};if(Array.isArray(a[d]))for(let l of a[d]){if(m.participantType===yr&&l?.eventType!==br)return _({context:{participantId:d,scaleItem:l,participantType:m.participantType},info:"Invalid participantType for eventType",result:{error:Ka}});GO({participant:m,scaleItem:l,removePriorValues:r}),c.push(m),s++}}let u=s?void 0:_s,{topics:p}=Lr();if(p.includes(nr)&&s&&mt({topic:nr,payload:{tournamentId:n.tournamentId,participants:c}}),i){let{eventId:m,drawId:d,...l}=i,f=l.scaleAttributes?.scaleType&&[l.scaleAttributes.scaleType];if(Object.keys(l).length){let g={itemType:xf,itemValue:l};if(f&&(g.itemSubTypes=f),d||m){let{drawDefinition:I,event:h}=ze({tournamentRecord:n,eventId:m,drawId:d});d&&Tg({drawDefinition:I,timeItem:g}),m&&zi({event:h,timeItem:g})}else Pc({tournamentRecord:n,timeItem:g})}}return o&&p.includes(yi)&&mt({topic:yi,payload:o}),ot({...C,modificationsApplied:s,info:u})}function kO({scaleItem:t}){let e=t&&Object.keys(t),r=["scaleType","eventType","scaleName"];return!!(r.filter(o=>e?.includes(o)).length===r.length)}function GO({removePriorValues:t,participant:e,scaleItem:r}){if(!e)return{error:wi};let n=r&&Object.keys(r),o=["scaleType","eventType","scaleName"];if(!(o.filter(p=>n.includes(p)&&r[p]).length===o.length))return{error:Ka};let s=new Date().toISOString();e.timeItems||(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){let{scaleType:p,eventType:m,scaleName:d}=r,l=[hi,p,m,d].join("."),f=ot({itemValue:r.scaleValue,itemDate:r.scaleDate,createdAt:s,itemType:l});r.scaleId&&(f.itemSubTypes=[r.scaleId]),t&&(e.timeItems=e.timeItems.filter(g=>g.itemType!==l)),e.timeItems.push(f)}return{...C,valueChanged:u,newValue:r.scaleValue}}function wg(t){let{tournamentRecord:e,modifiedScaleValues:r,removePriorValues:n}=t,o=rt(t,[{[ie]:!0},{modifiedScaleValues:!0,[He]:Kr}]);if(o.error)return o;for(let i in r){let s=Dc({scaleItem:r[i],removePriorValues:n,tournamentRecord:e,participantId:i});if(s.error)return s}return{...C}}function Nc(t){let{tournamentRecord:e,scaleAttributes:r,participantId:n}=t,o=t.tournamentRecords||e&&{[e.tournamentId]:e}||{};if(!n)return{error:oe};let{participant:i,tournamentId:s}=To({tournamentRecords:o,tournamentRecord:e,participantId:n});return i?{...yo({participant:i,scaleAttributes:r}),tournamentId:s}:{error:te}}var xG=(t=0)=>250/Math.pow(t+5,.4),wG=()=>1;function LG(t=3,e=2){let r=t/e;return isNaN(r)?Ld.kDefault():r}var Ld={nSpread:400,diffThreshold:.125,kCalc:xG,kMultiplier:LG,kDefault:wG};function ET(t){let{winnerRating:e,loserRating:r}=t,{ratings:n=we,winnerCountables:o=1,loserCountables:i=0,ratingType:s=Qn,maxCountables:a,countables:c}=t||{},u=n?.[s];if(!u)return{error:st};let p=u.range||t.ratingRange;e=e||u.defaultInitialization,r=r||u.defaultInitialization;let m=p[0]>p[1],d=u.decimalsCount||0,l=m?p.slice().reverse():p,f=(x,F)=>parseFloat(F)>=Math.min(...x)&&parseFloat(F)<=Math.max(...x);(!f(p,e)||!f(p,r))&&(f(p,e)||(e=u.defaultInitialization),f(p,r)||(r=u.defaultInitialization));let g=Mu({targetRange:we[Qn].range,sourceRange:l,value:m?p[0]-e:e}),I=Mu({targetRange:we[Qn].range,sourceRange:l,value:m?p[0]-r:r}),h=(x,F)=>1/(1+Math.pow(10,(F-x)/Ld.nSpread)),S=h(g,I),T=h(I,g),y=Ld.kCalc(o),P=Ld.kCalc(i),U=Ld.kMultiplier(a,c),A=g+U*y*(1-S),E=I+U*P*(0-T),N=Mu({sourceRange:we[Qn].range,value:A,targetRange:l}),D=Mu({sourceRange:we[Qn].range,value:E,targetRange:l}),M=m?p[0]-N:N,R=parseFloat(M.toFixed(d)),b=m?p[0]-D:D,v=parseFloat(b.toFixed(d)),O=Math.max(...p)?Math.abs(e-r)/Math.max(...p):0;return(N>D&&O>Ld.diffThreshold||R<0||v<0)&&(R=e,v=r),{newWinnerRating:R,newLoserRating:v}}var VO=t=>t?.reduce((e,r)=>(r.winningSide&&(e[r.winningSide-1]+=1),e),[0,0])||[0,0];function UT(t){let e=rt(t,[{[ie]:!0},{matchUpIds:!0,[He]:Be,[fn]:rs},{ratingType:!1,[tr]:S=>we[S]}]);if(e.error)return e;let{updateParticipantRatings:r,removePriorValues:n=!0,tournamentRecord:o,ratingType:i=Qn,refreshDynamic:s,considerGames:a,drawDefinition:c,matchUpIds:u,asDynamic:p}=t,m=we[i],{accessor:d}=m,l={},f=(t.matchUps||s&&or({drawDefinition:c,tournamentRecord:o,inContext:!0,matchUpFilters:{matchUpStatuses:ce}}).matchUps||Te({matchUpFilters:{matchUpIds:u,matchUpStatuses:ce},tournamentRecord:o,inContext:!0}).matchUps)??[],g=`${i}.${Vm}`,I=p?g:i;f.sort(Mi);for(let S of f){let{endDate:T,matchUpFormat:y,score:P,sides:U,winningSide:A}=S,E=S.matchUpType,N={eventType:E,scaleName:i,scaleType:Ii},D={scaleName:g,eventType:E,scaleType:Ii},M=Object.assign({},...(U??[]).map(V=>{let{sideNumber:k,participant:W}=V;return k&&{[k]:[W?.participantId,...W?.individualParticipantIds??[]].filter(Boolean).flat()}})),R=Object.assign({},...Object.values(M).flat().map(V=>{let k=l[V],H=!s||k?Nc({scaleAttributes:D,tournamentRecord:o,participantId:V}).scaleItem:void 0,q=Nc({tournamentRecord:o,scaleAttributes:N,participantId:V}).scaleItem,$=d?{[d]:void 0}:void 0;return V&&{[V]:H??q??{scaleName:I,eventType:E,scaleDate:T,scaleType:Ii,scaleValue:$}}})),b=y?Ye(y):{},v=b?.bestOf||1,O=b?.setsTo||1,x=a?v&O:v,F=P?.sets&&VO(P.sets)||A===1&&[1,0]||[0,1],L=A?M[A]:[],w=A?M[3-A]:[];for(let V of L){let k=R[V]?.scaleValue,W=typeof k=="object"?k[d]:k;for(let H of w){let q=R[H]?.scaleValue,$=typeof q=="object"?q[d]:q,B=A?F[A]:[0,0],K=A?F[3-A]:[0,0],{newWinnerRating:Q,newLoserRating:j}=ET({winnerCountables:B,loserCountables:K,maxCountables:x,winnerRating:W,loserRating:$,ratingType:i}),tt=d?{...k,[d]:Q}:Q,z=d?{...q,[d]:j}:j;R[V].scaleValue=tt,R[H].scaleValue=z,R[V].scaleName=I,R[H].scaleName=I}}Object.assign(l,R),r&&wg({tournamentRecord:o,modifiedScaleValues:l,removePriorValues:n})}let h=f.map(({matchUpId:S})=>S);return{...C,modifiedScaleValues:l,outputScaleName:I,processedMatchUpIds:h}}function _u(t){let{matchUpIds:e=[],drawDefinition:r,roundNumber:n,newRound:o,isMock:i,event:s}=t;if(typeof r!="object")return{error:Z};let{participantIdPairings:a,matchUpsCount:c}=t,u=vd(t);if(u.error)return _({result:u});let{lastRoundNumber:p,availableMatchUpsCount:m=0,roundMatchUpsCount:d=0}=u;if(!c)o?c=d:m>0&&(c=m);else if(c>d&&t.restrictMatchUpsCount!==!1)return _({result:{error:G,info:"matchUpsCount error",context:{roundMatchUpsCount:d}}});if(a&&!Array.isArray(a)||c&&!It(c)||e&&!Array.isArray(e)||!a&&!c)return{error:G,info:"matchUpsCount or pairings error"};if(c&&t.restrictMatchUpsCount!==!1&&c>32)return{error:G,info:"matchUpsCount must be less than 33"};if(n&&!t.ignoreLastRoundNumber&&n-1>(p||0))return{error:G,info:"roundNumber error"};let l=n??(o&&(p??0)+1||p||1);a=a??et(0,c).map(()=>({participantIds:[void 0,void 0]}));let f=I=>{if(!t.idPrefix)return;let h=r.drawId,S=t.idPrefix??"ah";return`${h}-${S}-${l}-${I}`},g=a?.map((I,h)=>{let S=I?.participantIds??[void 0,void 0];S.push(void 0,void 0);let y=S.slice(0,2).map((U,A)=>ot({sideNumber:A+1,participantId:U})),P=e[h]??f(h)??Dt();return{roundNumber:l,matchUpStatus:Qt,matchUpId:P,sides:y}});if(g?.length){let I=We({drawDefinition:r,event:s})?.tieFormat;I&&g.forEach(h=>{let{tieMatchUps:S}=Ra({tieFormat:I,matchUp:h,isMock:i});Object.assign(h,{tieMatchUps:S,matchUpType:jt})})}return{roundNumber:l,matchUpsCount:g?.length??0,matchUps:g,...C}}function HO({maxIterations:t=4e3,valueSortedPairings:e,pairingValues:r,valueObjects:n,deltaObjects:o}){let i=Object.assign({},...e.map(S=>({[S.pairing]:S.value}))),s=Object.keys(r),a=[],c=BO({actorsCount:s.length,valueSortedPairings:e,pairingValueMap:i,deltaObjects:o,valueObjects:n}),u=[dD(c)];a.push(c);let p=c.value,m=c,d=1,l=0,f=s.length,g;do f-=1,g=s.length*r[s[0]].length;while(g>t&&f>5);let I=[];s.forEach(S=>{r[S].slice(0,f).forEach(y=>{l+=1;let P=va(S,y.opponent);if(!I.includes(P)){let U=BO({stipulated:[[S,y.opponent]],actorsCount:s.length,valueSortedPairings:e,pairingValueMap:i,deltaObjects:o,valueObjects:n});if(!u.includes(dD(U))){u.push(dD(U)),a.push(U);let{maxDelta:A,value:E}=U;A<m.maxDelta&&(m=U),(E<p||E===p&&Math.round(Math.random()))&&(p=E),I.push(P),d+=1}}}),a=a.filter(y=>Math.abs(y.value-p)<5)}),a.sort((S,T)=>S.maxDiff-T.maxDiff);let h=tn(a);return{candidatesCount:d,deltaCandidate:m,maxIterations:t,iterations:l,candidate:h}}function dD(t){return t.participantIdPairings.map(({participantIds:e})=>e.sort().join("|")).sort().join("/")}function BO({valueSortedPairings:t,stipulated:e=[],pairingValueMap:r,deltaObjects:n,valueObjects:o,actorsCount:i}){let s=[].concat(...e),a=[],c=0;e.filter(Boolean).forEach(d=>{let[l,f]=d,g=va(l,f),I=r[g];a.push({participantIds:d,value:I}),c+=r[g]}),Ae(t,i).map(d=>Ir(d).map(l=>({...l,value:l.value+Math.random()*Math.round(Math.random())}))).flat().forEach(d=>{let l=d.pairing.split("|");if(!l.reduce((g,I)=>s.includes(I)||g,!1)){s.push(...l);let g=d.value;c+=g,a.push({participantIds:l,value:g})}}),a.sort((d,l)=>d.value-l.value);let p=a.reduce((d,l)=>{let[f,g]=l.participantIds,I=va(f,g),h=n[I];return h>d?h:d},0),m=a.reduce((d,l)=>{let[f,g]=l.participantIds,I=va(f,g),h=o[I];return h>d?h:d},0);return{value:c,participantIdPairings:a,maxDelta:p,maxDiff:m}}function va(t,e){return[t,e].sort(yu).join("|")}function lD({participantIds:t}){let e={},r=[];t.forEach(o=>{e[o]=t.filter(i=>i!==o),e[o].forEach(i=>{let s=va(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 WO({matchUps:t}){let e=[];for(let r of t){let n=r.sides.map(St);if(n.length===2){let[o,i]=n,s=va(o,i);e.includes(s)||e.push(s)}}return{encounters:e}}function jO({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=va(o,i);return{opponent:i,value:e[s]}}return{pairingValues:r}}var FG=0;function YO({tournamentParticipants:t,adHocRatings:e,eventType:r,scaleName:n,pairing:o}){let i=we[n]?.defaultInitialization??FG;return o.split("|").map(s=>{if(r===qr){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 qO(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=YO({tournamentParticipants:e,adHocRatings:r,scaleName:p,eventType:u,pairing:T}),P=typeof m=="number"&&m||.5,U=m&&(Math.round(Math.random())?P:P*-1)||0,A=Math.abs(y[0]-y[1])+U,E=Math.abs(y[0]-y[1]);a[T]=E,c[T]||(c[T]=0),c[T]+=A?Math.pow(A,2):0});let d=o.map(T=>({pairing:T,value:c[T]})).sort((T,y)=>T.value-y.value),{pairingValues:l}=jO({possiblePairings:n,valueObjects:c}),{candidate:f,candidatesCount:g,deltaCandidate:I,iterations:h}=HO({valueSortedPairings:d,maxIterations:i,pairingValues:l,deltaObjects:a,valueObjects:c}),{participantIdPairings:S}=s?I:f;return{participantIdPairings:S,candidatesCount:g,deltaCandidate:I,iterations:h,candidate:f}}var kG=100,GG=100,VG=4e3;function Fd(t){let{encounterValue:e=kG,sameTeamValue:r=GG,maxIterations:n=VG,updateParticipantRatings:o,generateMatchUps:i=!0,ignoreLastRoundNumber:s,iterationMatchUps:a,tournamentRecord:c,dynamicRatings:u,refreshDynamic:p,participantIds:m,drawDefinition:d,roundNumber:l,structureId:f,matchUpIds:g,eventType:I,scaleName:h,idPrefix:S,isMock:T,salted:y,event:P}=t;if(!d)return{error:Z};if(!t.structure&&!f)return{error:kt};let U=t.structure||at({drawDefinition:d,structureId:f}).structure;if(!ht(U))return{error:mi};if(!m?.length)return{error:Uo};let A=[...a??[],...U?.matchUps??[]],{encounters:E}=WO({matchUps:A}),N=c?.participants??[],D={};if(u){let B=ut(U?.matchUps?U.matchUps.map(({roundNumber:Q})=>Q):[]),K=Math.max(...B,0);if(K){let Q=U?.matchUps?.filter(({roundNumber:tt})=>tt===K).map(({matchUpId:tt})=>tt),j=UT({ratingType:h??P?.category?.ratingType,updateParticipantRatings:o,tournamentRecord:c,asDynamic:!0,refreshDynamic:p,drawDefinition:d,matchUpIds:Q});if(j.error)return j;j.modifiedScaleValues&&(D=j.modifiedScaleValues)}}let{valueObjects:M}=BG({tournamentParticipants:N,encounterValue:e,sameTeamValue:r,encounters:E}),{uniquePairings:R,possiblePairings:b,deltaObjects:v}=lD({participantIds:m}),O=Object.values(D).length?D:t.adHocRatings,x={tournamentParticipants:N,possiblePairings:b,participantIds:m,uniquePairings:R,drawDefinition:d,maxIterations:n,adHocRatings:O,deltaObjects:v,valueObjects:M,eventType:I,scaleName:h,structure:U,salted:y},{candidatesCount:F,participantIdPairings:L,deltaCandidate:w,iterations:V,candidate:k}=qO(x);if(!F)return{error:Xu};let W,H;if(i){let B=_u({structureId:U?.structureId,ignoreLastRoundNumber:s,participantIdPairings:L,newRound:!0,drawDefinition:d,roundNumber:l,matchUpIds:g,idPrefix:S,isMock:T,event:P});if(B.error)return B;W=B.roundNumber,H=B.matchUps}let{maxDelta:q,maxDiff:$}=k;return{roundNumber:W,participantIdPairings:L,modifiedScaleValues:D,candidatesCount:F,deltaCandidate:w,...C,iterations:V,matchUps:H,maxDelta:q,maxDiff:$}}function BG({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===wt);if(i)for(let s of i){let a=s.individualParticipantIds??[],{uniquePairings:c}=lD({participantIds:a});for(let u of c)o[u]||(o[u]=0),o[u]+=n}return{valueObjects:o}}function PT(t){let{drawType:e=go,attachConsolation:r=!0,applyPositioning:n=!0,tournamentRecord:o,staggeredEntry:i,automated:s,placeByes:a,isMock:c,event:u}=t,p=t?.drawDefinition;if(!p)return{error:Z};let m=$e,d=Ui({stageSequence:1,drawDefinition:p,stage:m}),l=[Nn,Xc,Io].includes(e)?d.length:es(d.length);if(!i&&e===da&&d.length<2||e===Nn&&d.length<3)return{error:$u};let{tieFormat:f,matchUpType:g}=t;if(f){let R=ar({tieFormat:f});if(R.error)return R}f=ir(f??We({drawDefinition:p})?.tieFormat),g=g??p.matchUpType;let{structures:I}=gn({stageSequence:1,drawDefinition:p,stage:m});if(I.length>1)return{error:qA};if(I?.[0]?.matchUps?.length)return{error:of};let S=I?.[0]?.structureId;Object.assign(t,ot({structureName:t.structureName??Qe($e),structureId:S,matchUpType:g,tieFormat:f,drawSize:l,stage:m}));let T=AT(t);if(T.error)return T;let y=T.generators[e];if(!y)return{error:Fl};let P=y?.();if(P.error)return P;let{structures:U,links:A}=P,E=U.map(R=>Ut({structure:R}).matchUps).flat();f&&E.forEach(R=>{let{tieMatchUps:b}=Ra({matchUp:R,tieFormat:f,isMock:c});Object.assign(R,{tieMatchUps:b,matchUpType:g})}),(!n||!r)&&(p=J(p,!1,!0)),p.links||(p.links=[]),A.length&&p.links.push(...A);let N=U.map(({structureId:R})=>R);p.structures||(p.structures=[]);let D=p.structures.map(({structureId:R})=>R);p.structures=p.structures.map(R=>N.includes(R.structureId)?U.find(({structureId:b})=>b===R.structureId):R);let M=U.filter(({structureId:R})=>!D.includes(R));return M.length&&p.structures.push(...M),s&&Sc({seedingProfile:t.seedingProfile,applyPositioning:n,tournamentRecord:o,drawDefinition:p,structureId:S,placeByes:a,drawSize:l,event:u}),r&&Ot({drawDefinition:p}),{links:A,structures:U,...C}}var Hg={};Xt(Hg,{addGame:()=>yD,addPoint:()=>TD,addSet:()=>ED,addShot:()=>AD,analyzeScore:()=>Gg,analyzeSet:()=>Lu,calculateHistoryScore:()=>ID,checkScoreHasValue:()=>Ie,checkSetIsComplete:()=>Wp,clearHistory:()=>SD,generate:()=>gD,generateScoreString:()=>Yo,generateTieMatchUpScore:()=>Uc,getSetComplement:()=>Bg,getTiebreakComplement:()=>$p,helpers:()=>JD,isValidMatchUpFormat:()=>Dr,keyValueScore:()=>qD,mutate:()=>ND,parseMatchUpFormat:()=>Ye,parseScoreString:()=>jd,query:()=>ZD,redo:()=>UD,reverseScore:()=>fD,setServingSide:()=>hD,stringifyMatchUpFormat:()=>sp,tidyScore:()=>XD,umo:()=>DD,undo:()=>PD,validateScore:()=>Vg,validateTieFormat:()=>ar});var gD={};Xt(gD,{generateScoreString:()=>Yo,generateTieMatchUpScore:()=>Uc,reverseScore:()=>fD});function Yo(t){let{winnerFirst:e=!0,addOutcomeString:r,reversed:n=!1,matchUpStatus:o,matchUpFormat:i,autoComplete:s,winningSide:a,sets:c}=t;if(!c)return{error:st,info:"missing sets"};let u=i&&Ye(i),{bestOf:p,finalSetFormat:m,setFormat:d}=u??{},f=n||!(!e||!a||a===1),g=r?HG({matchUpStatus:o}):"",I=c?.sort(WG).map(h).filter(Boolean).join(" ")||"";if(!g)return I;if(a===2)return`${g} ${I}`;return`${I} ${g}`;function h(S){let y=p&&S.setNumber===p&&m?m:d,P=H=>Zt(H?.side1Score)||Zt(H?.side2Score),U=H=>Zt(H?.side1TiebreakScore)||Zt(H?.side2TiebreakScore),A=y?.tiebreakSet||!P(S)&&U(S),{side1Score:E,side2Score:N,side1TiebreakScore:D,side2TiebreakScore:M}=S,R=D||(Zt(D)||s?0:""),b=M||(Zt(M)||s?0:"");if(A)return`[${(f?[b,R]:[R,b]).join("-")}]`;let v=Math.min(R,b),O=v===R?1:2,x=v?`(${v})`:"",F=E||(Zt(E)||s?0:""),L=N||(Zt(N)||s?0:""),w=H=>O===H?x:"",V=`${F}${w(1)}`,k=`${L}${w(2)}`,W=f?`${[k,V].join("-")}`:`${[V,k].join("-")}`;return["-"," "].includes(W)&&(W=""),W}}function HG({matchUpStatus:t}){let e={[rr]:"RET",[Ct]:"WO",[be]:"DF/DF",[he]:"WO/WO",[ss]:"SUS",[vr]:"ABN",[Mt]:"DEF",[au]:"DR"};return t&&e[t]||""}function WG(t,e){return t.setNumber-e.setNumber}function fD(t){if(!t?.score)return{error:st};let{sets:e}=t.score,r=e.map(i=>{let{side1TiebreakScore:s,side2TiebreakScore:a,winningSide:c,side1Score:u,side2Score:p,setNumber:m}=i;return ot({winningSide:c?3-c:void 0,side1TiebreakScore:a,side2TiebreakScore:s,side1Score:p,side2Score:u,setNumber:m})}),n=Yo({sets:r}),o=Yo({sets:r,reversed:!0});return{reversedScore:{sets:r,scoreStringSide1:n,scoreStringSide2:o},...C}}var ND={};Xt(ND,{addGame:()=>yD,addPoint:()=>TD,addSet:()=>ED,addShot:()=>AD,calculateHistoryScore:()=>ID,clearHistory:()=>SD,redo:()=>UD,setServingSide:()=>hD,umo:()=>DD,undo:()=>PD});function qo({matchUp:t}){let{extension:e}=dt({name:qm,element:t});if(!e)return{error:ve};let{history:r=[],undoHistory:n=[]}=e.value;return{history:r,undoHistory:n,...C}}function ID(t){if(!t)return{error:st};let{matchUp:e,updateScore:r}=t;if(!e)return{error:hr};let n=qo({matchUp:e})?.history||[];if(!Array.isArray(n))return{error:G,info:"history is not an array"};let{matchUpFormat:o}=e;if(!o)return{error:Wl};if(!Dr({matchUpFormat:o}))return{error:Hl};let i=Ye(o),{bestOf:s,finalSetFormat:a,setFormat:c}=i,u=["0","15","30","40","A","G"],p={sets:[]},m=[],d,l=[0,0],f=1,g=0,I,h=0,S=D=>[1,2].includes(D),T=()=>(g+=1,{winningSide:void 0,side1Score:0,side2Score:0,setNumber:g,games:[]}),y=()=>({winningSide:void 0,points:[]}),P=()=>({winningSide:void 0,side1Score:"",side2Score:"",shots:[]}),U=P(),A=y(),E=T(),N=0;for(let D of n){N+=1,I=p.sets.length+1===s;let M=I&&a?a:c,{tiebreakAt:R,setTo:b,NoAD:v,tiebbreakFormat:O}=M,x=E.side1Score===R&&E.side1Score===E.side2Score,F=!!M.tiebreakSet,L=F?M.tiebreakSet:O,{tiebreakTo:w,NoAD:V}=L||{},k=()=>{d=void 0,l=[0,0],f=3-f,E.side1TiebreakScore=0,E.side2TiebreakScore=0,E.side1PointScore="",E.side2PointScore="",h=0},W=$=>{E.winningSide=$;let{s:B,...K}=E;p.sets.push(K),U=P(),A=y(),E=T(),k()},H=$=>{A.winningSide=$;let{g:B,...K}=A;E.games.push(K),U=P(),A=y(),k();let Q=`side${$}Score`;E[Q]+=1},q=$=>{U.winningSide=$;let{p:B,...K}=U;A.points.push(K),U=P(),h=0;let Q=()=>l.reduce((X,lt)=>X+lt)%4/4>.5?f:3-f,j=$-1;if(x||F){l[j]+=1,d=Q(),E[`side${$}TiebreakScore`]=l[j],E[`side${3-$}TiebreakScore`]=l[1-j];let tt=V?1:2;if(l[j]>=w&&l[j]>=l[1-j]+tt)return H($),{gameCompleted:!0}}else if(l[1-j]===4&&l[j]===3?l[1-j]-=1:l[j]+=1,E.side1PointScore=u[l[0]],E.side2PointScore=u[l[1]],l[j]===5||l[j]===4&&l[1-j]<3||v&&l[j]===4)return H($),{gameCompleted:!0}};if(S(D.srv)&&(f=D.srv),["p","s","g","o"].includes(D.u)&&m.push(D.u),D.shotOutcome&&(U.shots.push(D),D.shotType==="SERVE"&&["OUT","NET"].includes(D.shotOutcome)&&(h+=1),h===2)){let B=3-f;q(B)}if(S(D.p)||It(D.pointNumber)){let $=D.winningSide||D.p;if(q($)?.gameCompleted)continue}if(S(D.g)||It(D.gameNumber)){let $=D.winningSide||D.g;A.winningSide=$;let B=`side${$}Score`,K=`side${3-$}Score`;if(m.length&&(m.includes("p"),m=[]),H($),E[B]===b&&E[B]-E[K]>=(v?1:2)&&(W($),I))break}if(S(D.s)||It(D.setNumber)){let $=D.winningSide||D.s;if(W($),m.length&&(m.includes("p"),m.includes("g"),m=[]),I)break}}return N!==n.length&&console.log({error:"Match completed with excess history"}),(E.side1Score||E.side2Score||E.games.length||E.side1TiebreakScore||E.side2TiebreakScore)&&p.sets.push(E),p.scoreStringSide1=Yo({...p,matchUpFormat:o}),p.scoreStringSide2=Yo({...p,matchUpFormat:o,reversed:!0}),f=d||f,r&&(e.score=p),{...C,servingSide:f,score:p}}function $o({undoHistory:t,history:e,matchUp:r}){return At({element:r,extension:{value:{history:e,undoHistory:t},name:qm}})}function hD({matchUp:t,sideNumber:e}){if(![1,2].includes(e))return{error:jl};let{history:r=[]}=qo({matchUp:t});return r.push({srv:e}),$o({matchUp:t,history:r})}function SD({matchUp:t}){return $o({matchUp:t})}function TD({matchUp:t,point:e}){if(!e||!t)return{error:st};if(typeof e!="object")return{error:G,context:{point:e}};let{history:r=[]}=qo({matchUp:t});return r.push(e),$o({matchUp:t,history:r})}function yD({matchUp:t,game:e}){if(typeof e!="object")return{error:G,context:{game:e}};let{history:r=[]}=qo({matchUp:t});return r.push(e),$o({matchUp:t,history:r})}function AD({matchUp:t,shot:e}){if(typeof e!="object")return{error:st};let{history:r=[]}=qo({matchUp:t});return r.push(e),$o({matchUp:t,history:r})}function ED({matchUp:t,set:e}){if(typeof e!="object")return{error:st};let{history:r=[]}=qo({matchUp:t});return r.push(e),$o({matchUp:t,history:r})}function UD({matchUp:t}){let{history:e=[],undoHistory:r=[]}=qo({matchUp:t});return r.length&&e.push(r.pop()),$o({matchUp:t,history:e,undoHistory:r})}function PD({matchUp:t}){let{history:e=[],undoHistory:r=[]}=qo({matchUp:t});return r.push(e.pop()),$o({matchUp:t,history:e,undoHistory:r})}var DD={};var JD={};Xt(JD,{keyValueScore:()=>qD,parseMatchUpFormat:()=>Ye,stringifyMatchUpFormat:()=>sp,tidyScore:()=>XD});var Js=" ",DT="DEF",$O="COMPLETED",MD="WO",jG="WO/WO",RD="ABN",CD="SUS",bD="RET",vD="INT",NT=[bD,DT,MD,jG,RD,CD,vD];var MT="DEFAULTED";var OD="WALKOVER";var RT="ABANDONED",CT="SUSPENDED",_D="RETIRED",bT="INTERRUPTED";var KO=[_D,MT,OD],YG="Enter Score",As="()",Es="[]",xD=["up","left","shift+tab"],wD=["enter","down","tab","right"],kd="backspace",LD="r",FD="s",kD="a",GD="d",VD="w",BD="i",Gd=[LD,GD,VD,kD,FD,BD],Bp="space",vT=["[","("],Vd=[...xD,...wD,Bp,"]"],zO="-",qG="/",Zs=zO,ui=zO,HD=[qG],QO=0,$G=["=","+","num_1","num_2","shift+=","shift+-"],Xs=["0","1","2","3","4","5","6","7","8","9"].concat(Gd),XO=Xs.map(t=>`shift+${t}`),WD=[Zs,kd].concat(Vd,HD),jD=[Xs,XO,WD].join(","),KG=[jD,xD,wD,$G].join(","),ARt=[].concat(...Xs,...Xs,...WD,...Xs,...Xs,...Xs,...Xs,...Xs,...Xs),JO={OUTCOMEKEYS:Gd,SIDE1KEYS:Xs,SIDE2KEYS:XO,MODIFIERS:WD,PROMPT:YG,MOVEUP:xD,MOVEDOWN:wD,HOTKEYS:KG};function Hp({scoreString:t,lowSide:e,outcome:r}){if({scoreString:t}=ZO({scoreString:t}),e===2){let o=(t&&t[t.length-1])!==Js?Js:"";return t+o+r}else return r+Js+t}function ZO({scoreString:t}){if(!t)return{scoreString:""};let e=!1;for(let r of NT){let n=t?.indexOf(r);n===0?t=t.slice(r.length+1).trim()+Js:n>0&&(t=t.slice(0,n)),n>=0&&(e=!0)}return t?.trim()||(t=""),{scoreString:t,removed:e}}function Lg({analysis:t,scoreString:e,sets:r,lowSide:n}){let o,i;if(!e)return{scoreString:e,sets:r};let{scoreString:s,removed:a}=ZO({scoreString:e});if(e=s,a)return{scoreString:e,sets:r,outcomeRemoved:!0};let c=r[r.length-1]||{},u=Object.values(c).filter(g=>g!==void 0).length;c.setNumber&&u===1&&(r=r.slice(0,r.length-1),c=r[r.length-1]||{});let{tiebreakSet:p}=t.setFormat,{tiebreakTo:m,NoAD:d}=p||{},{isTiebreakEntry:l}=xu({brackets:Es,scoreString:e}),f=zG(e);if(f>=0){o=e.slice(0,f);let{isTiebreakEntry:g}=xu({brackets:As,scoreString:o}),{lastOpenBracketIndex:I,isTiebreakEntry:h}=xu({brackets:Es,scoreString:o}),S=o&&o[o.length-1].trim(),T=o&&!isNaN(S),y=t.isIncompleteSetScore;if(l&&h){let U=o.slice(I+1).split(ui),A=U?.length>0&&U[0]!==void 0&&!isNaN(parseInt(U[0]))&&parseInt(U[0])||void 0,E=U?.length>1&&U[1]!==void 0&&parseInt(U[1])||void 0,N=[A,E];if(E){let D=n===1?1:0;N[D]=(N?.[1-D]||0)+(d?1:2),(N[D]||0)<m&&(N[D]=m),o=e.slice(0,I+1),o+=N.join(ui)}else A!==void 0?(o=e.slice(0,I+1),o+=A):(o=e.slice(0,I),y=!0);c.side1TiebreakScore=N[0]||0,c.side2TiebreakScore=N[1]||0}if(o.length||(o=void 0),y){let P=c.side1Score?.toString();if(P){let U=P?.slice(0,P.length-1);c.side1Score=!isNaN(U)&&parseInt(U)||void 0,c.side1Score===void 0&&(c.side2Score=void 0)}t.isTimedSet?(i=c.side1Score?r:r?.slice(0,r.length-1)||[],i[r.length-1]=c):i=r?.slice(0,r.length-1)||[]}else if(T){let P=c.side2Score?.toString(),U=c.side1Score?.toString();if(!t.isTiebreakEntry&&!t.isMatchTiebreak)if(c.side2Score){let A=P?.slice(0,P.length-1);c.side2Score=!isNaN(A)&&parseInt(A)||void 0}else{let A=U?.slice(0,U.length-1);c.side1Score=!isNaN(A)&&parseInt(A)||void 0}t.isTimedSet?c.side1Score?(i=r||[],i[r.length-1]=c):i=r?.slice(0,r.length-1)||[]:(i=r||[],i[r.length-1]=c),i[i.length-1]&&Object.assign(i[i.length-1],{winningSide:void 0})}else g?(i=r||[],Object.assign(i[i.length-1]||{},{winningSide:void 0,side1TiebreakScore:void 0,side2TiebreakScore:void 0})):(l&&!h?i=r?.slice(0,r.length-1)||[]:(i=r,i[r.length-1]=c),l||(i[i.length-1].side2Score=0,i[i.length-1].winningSide=void 0));return{scoreString:o,sets:i}}return{scoreString:e,sets:r}}function xu({brackets:t=As,scoreString:e}){if(!e)return{};let[r,n]=t.split(""),o=e.split(""),i=Math.max(...mo(r,o)),s=Math.max(...mo(n,o));return{isTiebreakEntry:i>s,lastOpenBracketIndex:i}}function t_({scoreString:t}){if(!t)return!1;let e=t&&t[t.length-1].trim(),r=t&&!isNaN(e),[n,o]=Es.split(""),i=t.split(""),s=Math.max(...mo(n,i)),a=Math.max(...mo(o,i)),c=Math.max(...mo(ui,i));return r&&s>a&&c>s}function zG(t){return t.split("").reduce((n,o,i)=>(o.match(/\d+/g)&&n.push(i),n),[]).pop()}function OT(t){let{lowValue:e=0,NoAD:r=!1,tiebreakTo:n}=t||{},o=r?1:2;return e+1>=n?e+o:parseInt(n)}function YD({matchUpFormat:t,matchUpStatus:e,winningSide:r,sets:n}){let o=Ye(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 KO.includes(e)&&r&&(c=r),{matchUpWinningSide:c}}function Wp({ignoreTiebreak:t=!1,matchUpScoringFormat:e,matchUpFormat:r,isTiebreakSet:n,isDecidingSet:o,isTimedSet:i,set:s}){if(!s)return{error:st,info:"missing set"};e=e||r&&Ye(r);let a=o&&e.finalSetFormat||e?.setFormat||{},{side1Score:c,side2Score:u}=s,{setTo:p,tiebreakAt:m}=a,d=c||u,l=jp({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),h=t||I&&(l===1&&s.side1TiebreakScore>s.side2TiebreakScore||l===2&&s.side2TiebreakScore>s.side1TiebreakScore),S=!I&&a.NoAD||I||n&&a.tiebreakFormat?.NoAD?1:2,T=f>=S;return!!((i&&d||g&&(T||I)||n)&&(!I||h))}function jp({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 Bd({analysis:t,set:e}){let r=jp({set:e}),{isDecidingSet:n,isTiebreakSet:o,matchUpScoringFormat:i}=t;return Wp({matchUpScoringFormat:i,isDecidingSet:n,isTiebreakSet:o,set:e})&&r}function e_({analysis:t,scoreString:e,sets:r,value:n}){let o;if(!r?.length)return{sets:[]};let i=r[r.length-1];n=pt(n);let{validSide2Score:s,requiresTiebreak:a}=QG({analysis:t,set:i,value:n});if(s){o=!0,e=(e||"")+n,i.side2Score=n;let c=Bd({analysis:t,set:r[r.length-1]});if(i.winningSide=c||void 0,a){let u=As.split("")[0];e+=u}else t.isDecidingSet||(e+=Js)}return{sets:r,scoreString:e,updated:o}}function QG({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 _T({lowSide:t,value:e,sets:r,scoreString:n,winningSide:o,matchUpStatus:i}){let s;return e===LD?n?(s=!0,n=Hp({scoreString:n,lowSide:t,outcome:bD}),o=t===2?1:2,i=_D):(s=!0,n=Hp({scoreString:n,lowSide:t,outcome:DT}),o=t===2?1:2,i=MT):e===GD?(s=!0,n=Hp({scoreString:n,lowSide:t,outcome:DT}),o=t===2?1:2,i=MT):e===VD?(s=!0,r=[],n=MD,o=t===2?1:2,i=OD):e===FD&&n?(s=!0,n=Hp({scoreString:n,lowSide:t,outcome:CD}),i=CT,o=void 0):e===kD?(s=!0,n=Hp({scoreString:n,lowSide:t,outcome:RD}),i=RT,o=void 0):e===BD&&n&&(s=!0,n=Hp({scoreString:n,lowSide:t,outcome:vD}),i=bT,o=void 0),{updated:s,sets:r,scoreString:n,matchUpStatus:i,winningSide:o}}function r_(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!==kd&&(e=[{setNumber:1}]);let m=e.length-1;if(Gd.includes(c)){let d=e[e.length-1]||{},{side1Score:l,side2Score:f}=d;l&&!f?r="missing side2Score":s.finalSetIsComplete||o?r="final set is already complete":s.isIncompleteSetScore?r="incomplete set scoreString":s.isIncompleteSetScore||({sets:e,scoreString:n,winningSide:o,matchUpStatus:i,updated:u}=_T({lowSide:a,value:c,sets:e,scoreString:n,matchUpStatus:i,winningSide:o}))}else if(c===kd){if({scoreString:n,sets:e,outcomeRemoved:p}=Lg({analysis:s,scoreString:n,sets:e}),n?.trim()===""&&(n=n.trim()),n||(e=[]),p){let d=e[e.length-1]||{},{side1Score:l,side2Score:f}=d;if(l&&f){let g=l>f&&1||f>l&&2||void 0;g&&(d.winningSide=g,e.push({setNumber:e.length+1}))}}i=void 0,o=void 0,u=!0}else if(s.hasOutcome)r="has outcome";else{if(o)return{sets:e,scoreString:n,winningSide:o,matchUpStatus:i,updated:!1,info:"matchUp is complete"};if(c===Bp){let d=e[e.length-1]||{},{side1Score:l,side2Score:f}=d,g=l>f&&1||f>l&&2||void 0;g&&!o&&!s.isIncompleteSetScore&&(e[e.length-1].winningSide=g,e.push({setNumber:e.length+1}),n+=" ",u=!0)}else if(c===Zs&&e[m].side1Score!==void 0&&e[m].side2Score===void 0&&n&&s.isNumericEnding)n+="-",e[m].side2Score=0,i=void 0,o=void 0,u=!0;else if(!isNaN(c)){let d;if(e[m].side2Score===void 0){let l=pt((e[m].side1Score||0).toString()+c).toString().slice(0,2);e[m].side1Score=pt(l),d=e[m].side1Score.toString(),u=!0}else{let l=pt((e[m].side2Score||0).toString()+c).toString().slice(0,2);e[m].side2Score=pt(l),d=[e[m].side1Score,e[m].side2Score].join("-"),u=!0}if(u){let l=(e.slice(0,m)||[]).filter(f=>f).map(f=>{let{side1Score:g,side2Score:I}=f;return[g,I].join("-")}).join(" ");l?n=l+" "+d:n=d}}}return{sets:e,scoreString:n,winningSide:o,matchUpStatus:i,info:r,updated:u}}function n_({analysis:t,auto:e,lowSide:r,scoreString:n="",sets:o,value:i}){let s,a,{tiebreakSet:{tiebreakTo:c,NoAD:u}}=t.setFormat,[p]=Es.split("");if(t.isMatchTiebreakEntry||(n+=p),o[t.setNumber-1]){let{lastOpenBracketIndex:d}=xu({brackets:Es,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=>pt(T)),h=r===1?1:0;I[h]=I[1-h]+(u?1:2),I[h]<c&&(I[h]=c);let S=o[o.length-1];S.side1TiebreakScore=I[0],S.side2TiebreakScore=I[1],n=n.slice(0,(d??0)+1),n+=I.join(ui),s=!0}else{let I=[f[0]||0,f[1]||0].map(S=>pt(S)),h=o[o.length-1];h.side1TiebreakScore=I[0],h.side2TiebreakScore=I[1],n+=i,s=!0}}else{let d=OT({lowValue:pt(i||0),tiebreakTo:c,NoAD:u}),l=[pt(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 o_({analysis:t,lowSide:e,scoreString:r,value:n}){let{setTo:o,tiebreakAt:i,NoAD:s}=t?.setFormat||{},a=n===parseInt(i||o);if(i&&i<o&&n>i)return{scoreString:r};if(s&&n===o||n>o)return{scoreString:r};let c=g(),u=[n,c];e===2&&u.reverse();let m=As.split("")[0],d=u.join(Zs)+(a?m:Js);r=(r||"")+d;let l={side1Score:u[0],side2Score:u[1]},f=Bd({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 i_({matchUpFormat:t,scoreString:e,winningSide:r,value:n,sets:o}){let s=(o?.filter(H=>H?.winningSide)?.length||0)+(r?0:1),a=Ye(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}=xu({brackets:As,scoreString:e}),{isTiebreakEntry:f}=xu({brackets:Es,scoreString:e}),g=l||f,I=!!u.tiebreakSet,h=e?.[e.length-1]?.trim(),S=e&&!isNaN(h),T=!g&&h===Zs,y=l&&vT.includes(h),P=f&&vT.includes(h),U=f&&h===ui,A=e?.split(""),[E]=Es.split(""),N=A&&Math.max(...mo(E,A)),D=A&&Math.max(...mo(ui,A)),M=A&&D>N,R=o[o.length-1]?.winningSide,b=o?.length&&!R,v=NT.find(H=>e?.indexOf(H)>=0),O=!isNaN(n),x=n===Bp,F=Vd.includes(n),L=e?.split("").find(H=>vT.includes(H)),w=F&&f&&!P&&(U||!t_({scoreString:e}));return{isTiebreakSetValue:I&&O,matchUpScoringFormat:a,setNumber:s,setFormat:u,matchTiebreakHasJoiner:M,isGameScoreEntry:b,isSpace:x,isCloser:F,isTiebreakCloser:F&&L&&g&&S,isDecidingSet:c,isTiebreakSet:I,isTimedSet:p,isNumericEnding:S,isNumericValue:O,hasOpener:L,hasOutcome:v,finalSet:m,finalSetIsComplete:d,lastSetIsComplete:R,isInvalidSetTiebreakValue:x&&g&&y,isInvalidMatchTiebreakValue:w,isTiebreakEntry:g,isSetTiebreakEntry:l,isMatchTiebreakEntry:f,isIncompleteSetScore:T,isIncompleteSetTiebreak:y,isIncompleteMatchTiebreak:P,isPartialMatchTiebreakValue:U}}function qD(t){let{lowSide:e=1,value:r}=t,{scoreString:n,sets:o,winningSide:i,matchUpStatus:s}=t,{matchUpFormat:a,shiftFirst:c,auto:u=!0}=t,p,m,d=c&&e===2||!c&&e===1;if(!jD.includes(r))return{updated:!1,info:"invalid key"};c&&(e=3-e);let{matchUpWinningSide:l}=YD({sets:o,winningSide:i,matchUpStatus:s,matchUpFormat:a});i=l;let f=i_({value:r,winningSide:i,scoreString:n,sets:o,matchUpFormat:a});if(HD.includes(r)&&(r=Zs),f.hasOpener&&f.isTiebreakEntry&&!f.isTiebreakSet&&d&&pt(r)===0&&(f.isTiebreakCloser=!0),Vd.includes(r)&&f.hasOpener&&(r=""),Vd.includes(r)&&(r=Bp),f.lastSetIsComplete){let g=n?.length&&n[n.length-1];n&&g!==" "&&(n+=" ")}if(f.isTimedSet)({info:m,sets:o,scoreString:n,updated:p,matchUpStatus:s,winningSide:i}=r_({analysis:f,lowSide:e,scoreString:n,sets:o,matchUpStatus:s,winningSide:i,value:r}));else if(Gd.includes(r))f.finalSetIsComplete||i?m="final set is already complete":!f.isTiebreakEntry&&!f.isIncompleteSetScore?{sets:o,scoreString:n,matchUpStatus:s,winningSide:i,updated:p}=_T({lowSide:e,sets:o,scoreString:n,matchUpStatus:s,winningSide:i,value:r}):f.isTiebreakEntry||f.isIncompleteSetScore?m="incomplete set scoreString or tiebreak entry":console.log("handle case",{value:r});else if(r===kd)p=!0,{scoreString:n,sets:o}=Lg({analysis:f,scoreString:n,sets:o,lowSide:e}),n||(o=[]),s=void 0,i=void 0;else if(f.hasOutcome)m="has outcome";else if(r===Zs&&!f.isMatchTiebreakEntry)(!f.isSetTiebreakEntry||f.isSetTiebreakEntry&&!f.isNumericEnding)&&(p=!0,{scoreString:n,sets:o}=Lg({analysis:f,scoreString:n,sets:o,lowSide:e}),s=void 0);else if(r===ui&&f.isMatchTiebreakEntry&&!f.isSetTiebreakEntry)f.matchTiebreakHasJoiner?m="existing joiner":f.isNumericEnding&&(p=!0,n+=ui);else if([Zs,ui].includes(r))m="invalid location for joiner";else{if(i)return{updated:!1,info:"matchUp is complete"};if(f.isIncompleteSetScore)f.isNumericValue&&({sets:o,scoreString:n,updated:p}=e_({analysis:f,scoreString:n,sets:o,value:r}));else if(f.isInvalidMatchTiebreakValue)m="invalid matchUp tiebreak character";else if(f.isInvalidSetTiebreakValue)m="invalid set tiebreak character";else if(f.isTiebreakCloser){let g=f.isSetTiebreakEntry?As:Es,I=g.split("").reverse()[0],h=g.split("")[0],S=o[o.length-1],{tiebreakFormat:T}=f.setFormat,{tiebreakTo:y,NoAD:P}=T||{},U=jp({set:S});if(!f.isTiebreakSet){let E=parseInt(n.split(h).reverse()[0]),N=OT({lowValue:E,tiebreakTo:y,NoAD:P});U===1?(S.side1TiebreakScore=N,S.side2TiebreakScore=E):(S.side1TiebreakScore=E,S.side2TiebreakScore=N)}n=(n||"")+I,f.isDecidingSet||(n+=Js);let A=Bd({analysis:f,set:S});S.winningSide=A||void 0,p=!0}else if(f.isTiebreakSetValue)({info:m,scoreString:n,sets:o,updated:p}=n_({analysis:f,auto:u,lowSide:e,scoreString:n,sets:o,value:r}));else if(f.isSetTiebreakEntry){let[g]=As.split(""),I=Math.max(...mo(g,n.split(""))),h=n.slice(I+1),S=h&&pt(h)===QO,T=pt(h?h+r:r),{tiebreakFormat:y}=f.setFormat,{tiebreakTo:P,NoAD:U}=y||{};!S&&h.length<2?U&&T>P-1?m="invalid low value for NoAD tiebreak":(p=!0,n=(n||"")+r):m=S?"tiebreak begins with zero":"tiebreak digit limit"}else if(f.isCloser)m=`invalid key: ${r}`;else if(f.isGameScoreEntry)m="game scoreString entry";else if(f.lastSetIsComplete||!o.length){p=!0;let{scoreString:g,set:I}=o_({analysis:f,lowSide:e,scoreString:n,value:pt(r)});I&&(I.setNumber=o?.length+1||1),o=o?.concat(I).filter(Boolean)||[I],n=g||void 0}else console.log("error: unknown outcome")}if(p){o=o?.filter(Boolean);let{matchUpWinningSide:g}=YD({sets:o,winningSide:i,matchUpStatus:s,matchUpFormat:a});return i=g,g&&(!s||[Qt,pn].includes(s))?(s=$O,o=o.filter(I=>{let{side1Score:h,side2Score:S,side1TiebreakScore:T,side2TiebreakScore:y}=I;return h||S||T||y})):n&&!i&&![CT,RT,bT].includes(s)&&(s=void 0),{updated:p,scoreString:n,sets:o,winningSide:i,matchUpStatus:s,info:m}}return{updated:p,scoreString:n,sets:o,winningSide:i,matchUpStatus:s,info:m}}var Hd="\\d+-\\d+",Yp="\\d+-\\d+\\(\\d+\\)",Fg="\\[\\d+-\\d+\\]",XG="\\d+-\\d+\\(\\d+-\\d+\\)",s_=new RegExp(`(${Hd}),`,"g"),a_=new RegExp(`(${Yp}),`,"g"),JG=[Hd,Yp,Fg,XG],ZG=["0","1","2","00","01","10","11","002","012","102","112","000","001","010","100","011","101","110","111","002","012","102","112","0002","0012","0102","1002","0112","1012","1102","1112","3","03","13","013","103"],tV=ZG.map(t=>{let r=t.split("").map(n=>JG[n]).join(" ");return new RegExp(`^${r}$`)});function $D(t){return!t||tV.some(e=>e.test(t))}function c_(t){let e="[];",r="()",n=e+r,o=[e[0],r[0]],i=Object.assign({},...n.split("").map(c=>({[c]:0}))),s="",a=t.split("").map(c=>{let u=n.includes(c)&&c,p=o.includes(u);if(p&&u)return i[u]+=1,s=u,c;if(!p&&u&&s&&u!==s){i[s]-=1;let m=e.includes(s)&&e||r.includes(s)&&r||"",d=m.split("").find(l=>l!==s);if(m.includes(u))i[s]||(s="");else return i[u]||(s=""),d}return c}).join("");return t!==a?a:t}function Wd(t){return/^\(\d+\)$/.test(t)||/^\(\d+$/.test(t)}function u_(t){return/^\(\d+-\d+\)$/.test(t)||/^\[\d+-\d+\]$/.test(t)}function Oa(t){let r=(n=>n?.split("-").join("").split("/").join(""))(t);if(/^\d+$/.test(r)&&r.length===2){let n=r.split("");return Math.abs(n.reduce((i,s)=>+i-+s))===1}return!1}function qp(t,e){let r=[t.slice(e,e+2),e?t.slice(0,1):t.slice(2)].map(i=>parseInt(i.join("")));e&&r.reverse();let n=r;if(Math.abs(n.reduce((i,s)=>+i-+s))>=2)return n.join("-")}function KD(t){return t.length===2?t.split("").join("-"):([", ",",","/"," "].forEach(e=>t=t.split(e).join("-")),t=t.replace(/-{2,}/,"-"),t)}function p_(t){return t.startsWith("(")&&t.endsWith(")")}function m_({score:t,applied:e}){t=c_(t);let r=/\)(\d+)/g;if(r.test(t))for(let U of t.match(r)){let A=U.replace(")",") ");t=t.replace(U,A)}t=t.replace(/\)\//g,") / "),t=t.replace(/\/\)/g,")");let n=/\(([\d- ]+)\)/g,o=/\(([\d- ]+)\)/,i=t.match(n);for(let U of i||[]){let[A]=U.match(o).slice(1),E=A.replace(/ /g,"");t=t.replace(U,`(${E})`)}let s=/\(\(\d-\d\)\)/g;if(s.test(t)){let U=t.match(s);U.length&&U.forEach(A=>{let E=A.match(/\((\(\d-\d\))\)/).slice(1)[0];t=t.replace(A,E)})}if(s=/\(\((\d)\)\)/g,s.test(t)){let U=t.match(s);U.length&&U.forEach(A=>{let E=A.match(/\((\(\d\))\)/).slice(1)[0];t=t.replace(A,E)})}/(^|\s)6-,/.test(t)&&(t=t.replace(/(^|\s)6-,/g,"6-0,"));let a=new RegExp(/[-,]{2,}/g);t=t.replace(a,"-"),["- "," -"].forEach(U=>{let A=new RegExp(`(\\d+)${U}(\\d+)`,"g"),E=t.match(A);E&&E.forEach(N=>t=t.replace(N,N.split(U).join("-")))}),/^[(-/,]+$/.test(t)&&(t=""),/\)[-/,]+$/.test(t)&&(t=t.slice(0,t.length-1)),/\d \/\d/.test(t)&&(t=t.replace(/ \//g,"/")),t.includes(" /")&&(t=t.replace(/ \//g," "));let c=/\(\d+, \)/g;c.test(t)&&t.match(c).forEach(A=>{let[E]=A.match(/\((\d+), \)/).slice(1);E.length===2?t=t.replace(A,`(${E})`):E.length===1&&E==="6"&&(t=t.replace(A,"(6-0)"))});let u=/\((\d+)\/\)/g;u.test(t)&&t.match(u).forEach(A=>{let[E]=A.match(/\((\d+)\/\)/).slice(1);E.length===2?t=t.replace(A,`(${E})`):E.length===1&&E==="6"?t=t.replace(A,"(6-0)"):t=t.replace(A,`(${E})`)});let p=/\d\/\d\/,/g;p.test(t)&&t.match(p).forEach(A=>{let[E]=A.match(/(\d\/\d)\/,/).slice(1);t=t.replace(A,`${E},`),e.push("slashComma")});let m=/\(\/(\d+)\)/g;m.test(t)&&t.match(m).forEach(A=>{let[E]=A.match(/\(\/(\d+)\)/).slice(1);E.length===2?t=t.replace(A,`(${E})`):E.length===1&&parseInt(E)<6?t=t.replace(A,`(6-${E})`):t=t.replace(A,`(${E})`)});let d,l,f,g,I,h=()=>{I=Sr(t.split("")),l=I["("]===(I[")"]||0)+1,d=(I["("]||0)+1===I[")"],f=I["["]===I["]"]+1,g=l&&!f};h();let S=/(\d+-\d+\(\d+)0,/;if(S.test(t)){let[U]=t.match(S).slice(1);t=t.replace(S,U+")")}if(I["("]===I[")"]&&I["("]>1){let U=t.split(")(").join(") (").split(" ");U.every(p_)?t=U.map(A=>{let E=A.slice(1,A.length-1);return E.length>2?E:A}).join(" "):t=U.join(" ")}h();let T=/[A-Za-z]+/.test(t),y=/\d+/.test(t);if(!T&&!y)return{score:""};if(/^\[.+\]$/.test(t)&&"()/,- ".split("").some(U=>I[U])&&(t=t.slice(1,t.length-1)),/^\(.+\)$/.test(t)&&I["("]===1&&I[")"]===1&&"[]/,".split("").some(U=>I[U]>1)&&(t=t.slice(1,t.length-1)),t.startsWith("(")&&t.endsWith("))")&&(t=t.slice(1,t.length-1)),I["("]>(I[")"]||0)&&t[t.length-1]==="("&&(t=t.slice(0,t.length-1)+")",h()),I["("]===1&&!I[")"]&&t[0]==="("&&(t=t+")",h()),I["("]>(I[")"]||0)&&t.slice(0,2)==="(("&&(t=t.slice(1)),d){if(/^9\d/.test(t))t="("+t.slice(1);else if(t[0]!=="(")t="("+t;else{let U=[],A=0;for(let E of t.split("").reverse())E===")"&&(A?U.push("("):A+=1),E==="("&&(A-=1),U.push(E);U.reverse(),t=U.join("")}h()}if(I[")"]>(I["("]||0)&&t[0]===")"&&(t="("+t.slice(1),h()),g&&(t.endsWith(9)||/\d+0$/.test(t))&&(t=t.slice(0,t.length-1)+")",h()),g&&(!t.endsWith(")")||t.startsWith("(("))&&(t=t+")",h()),g){let U="",A=0;for(let E of t.split(""))E==="("&&(A?U+=")":A+=1),E===")"&&(A-=1),U+=E;t=U}h(),f&&!l&&(t=t+"]"),t.includes("([")&&t.includes("])")&&(t=t.split("([").join("[").split("])").join("]"),h()),/\(\d+0$/.test(t)&&(t=t.slice(0,t.length-1)+")"),h(),I[")"]===1&&!I["("]&&t.endsWith(")")&&(t=t.slice(0,t.length-1)),t.startsWith("(")&&t.endsWith(")")&&I["("]===1&&I[")"]===1&&(t=t.slice(1,t.length-1),h());let P=U=>{let A=U.indexOf("("),E=U.indexOf(")");return A>=0&&E>=0&&A<E};if(/^\([\d ]+.*[\d ]+\)$/.test(t)&&I["("]===I[")"]){let U=t.slice(1,t.length-1);P(U)&&(t=U,h())}return{score:t,applied:e}}function wu(t){if(!/^[\d-]+(\(\d\))*$/.test(t))return t;let e=mo("-",t.split(""));if(!e.length)return t;let r=t.split("-"),n=!(r.length%2),o=!!(e.length%2);return n&&o&&e.length>r.length/2&&e.filter((s,a)=>a%2).forEach(s=>{t=t.substring(0,s)+" "+t.substring(s+1)}),t}function d_({score:t,applied:e}){return t.includes("( ")&&(e.push("removeParenSpacingAfterOpen"),t=t.split("( ").map(r=>r.trim()).join("(")),t.includes(" )")&&(e.push("removeParenSpacingBeforeClose"),t=t.split(" )").map(r=>r.trim()).join(")")),[s_,a_].forEach(r=>{let n=t.match(r);n?.length&&(n.forEach(o=>{t=t.replace(o,o.slice(0,o.length-1)+" ")}),e.push("setsEndComma"))}),t=t.split(" ").filter(Boolean).map(wu).join(" "),{score:t,applied:e}}function l_({score:t}){if(typeof t!="string")return{score:t};let e=d=>d?.split("-").join("").split("/").join(""),r=d=>d.split("[").join("(").split("]").join(")");t=t.split(", ").join(" ");let n=t.split(" ");t=n.map(d=>{let l=/^-(\d+)$/;if(l.test(d)){let[f]=d.match(l).slice(1);if(f.length===2)return f.split("").join("-")}return d}).join(" "),n=t.split(" ");let o=n.filter(Wd),i=0,s="";for(let d of o){let l=mo(d,n).filter(h=>!i||h>i)[0],f=n.slice(i,l-1),g=n[l-1],I=e(g);if(/^\d+$/.test(I)&&I.length===2){let h=I.split(""),S=Math.abs(h.reduce((T,y)=>+T-+y));if(S===1){let T=[f.join(" "),[g,d].join("")].join(" ");s+=T,i=l+1}else if(S===0){let T=Math.max(...h);if([4,5,6,7,8,9].includes(T)){let y=[6,4].includes(T)?T+1:T-1,P=[T,y].sort().reverse().join("-"),U=[f.join(" "),[P,d].join("")].join(" ");s+=U,i=l+1}}}}if(o.length&&s.length){let d=n.slice(i).join(" ");return s=[s,d].join(" "),{score:s.trim()}}if(n.length===2&&["(","["].some(d=>n[1].includes(d))){let l=e(n[0]).split("");if(Math.abs(l.reduce((g,I)=>+g-+I,0))===1)return n[1]=r(n[1]),{score:n.join("")}}let a=n.map(d=>u_(d)&&"bracket"||Oa(d)&&"set");if(a.includes("set")&&a.includes("bracket")){let d,l="";return n.forEach((f,g)=>{a[g]==="bracket"&&d==="set"?(f=r(f),l+=f):l+=` ${f}`,d=a[g]}),{score:l.trim()}}n=t.split(" ");let c,u=n.map(d=>{let l=new RegExp(/^(\d+)-(\d+)$/);if(l.test(d)){let[f,g]=d.match(l).slice(1),I=Math.abs([f,g].reduce((S,T)=>+S-+T)),h=Math.max(f,g);if(I===1)return c="tiebreakSet",c;if(I>=2&&h>=7&&c==="tiebreakSet")return c="tiebreak",c}}),p=mo("tiebreak",u);if(p.length){let d="";n.forEach((l,f)=>{p.includes(f)?d+=`(${l}) `:p.includes(f+1)?d+=`${l}`:d+=`${l} `}),t=d.trim()}let m=/(\d+-\d+)\((\d+)-(\d+)\)$/;if(m.test(t)){let[d,l,f]=t.match(m).slice(1),I=Math.max(l,f)>=10;!Oa(d)&&I&&(t=t.replace(m,`${d} [${l}-${f}]`))}return u=[],t=t.split(" ").map(d=>{let l=/^\((.*)\)$/,f=l.test(d),g=new RegExp(Fg).test(d)&&"super"||new RegExp(Yp).test(d)&&"tiebreak"||new RegExp(Hd).test(d)&&"standard"||"unknown";return u.push(g),g==="standard"&&f?d.match(l)[1]:d}).join(" "),{score:t}}function f_({score:t,applied:e}){for(let D of[".",","," ","/"]){let M=new RegExp(`^(\\d+)\\${D}(\\d+)$`);if(M.test(t)){let R=t.match(M).slice(1).map(v=>parseInt(v)),b=Math.abs(R[0]-R[1]);b<=10&&b>=2&&(t=t.split(D).join("-"),e.push("variedJoinerPattern"))}}t.includes(";")&&(t=t.split(";").join(" "),e.push("semicolon set separation"));let r=/(^|\s)(\d)\/(\d)(\d)\/(\d)(\(|$)/;if(r.test(t)){let[D,M,R,b,v,O]=t.match(r).slice(1);t=t.replace(r,`${D}${M}-${R} ${b}-${v}${O}`),e.push("smashSlashPattern")}/.*\s6[/-]+$/.test(t)&&(t+="0",e.push("incompleteFinalSetPattern"));let o=/\(6,\)/g;o.test(t)&&(t=t.replace(o,"(6, 0)"),e.push("missingZeroPattern1"));let i=/^\d{3,}\(/,s=/\(\d+\)\d+/;[i,s].forEach(()=>{t=t.split(" ").map(M=>(i.test(M)&&(M=M.replace("("," (")),s.test(M)&&(M=M.replace(")",") ")),M)).join(" "),e.push("spaceConsiderationPatterns")});let c=wu(t);c!==t&&(t=c,e.push("deDashMash"));let u=/^(\d)[-/,]+(\d{2})[-/,]+(\d)$/;if(u.test(t)){let[D,M,R]=t.match(u).slice(1),[b,v]=M.split("");t=`${D}-${b} ${v}-${R}`,e.push("smashSetPattern")}let p=/^(\d+)[ -](\d+)$/,m=/^([\d -]+)\/([\d -]+)$/;if(m.test(t)){let[D,M]=t.match(m).slice(1),R=D.trim(),b=M.trim();if(p.test(R)&&p.test(b)){let v=R.match(p).slice(1,3).join("-"),O=b.match(p).slice(1,3).join("-");t=`${v} ${O}`,e.push("slashSeparationPattern")}}let d=/^([\d -]+),([\d -]+)$/;if(d.test(t)){let[D,M]=t.match(d).slice(1),R=D.trim(),b=M.trim();if(p.test(R)&&p.test(b)){let v=R.match(p).slice(1,3).join("-"),O=b.match(p).slice(1,3).join("-");t=`${v} ${O}`,e.push("commaSeparationPattern")}}let l=/^\d \d,/;if(l.test(t)){let D=t.match(l)[0],M=D.slice(0,D.length-1).split(" ").join("-");t=t.replace(D,M),e.push("singleSetCommaSeparationPattern")}let f=0,g=/(\d+)-(\d{2})-(\d+)/;for(;g.test(t)&&f<3;){let[D,M,R]=t.match(g).slice(1),b=M.split(""),v=`${D}-${b[0]} ${b[1]}-${R}`;t=t.replace(g,v),e.push("noSetSeparationPattern"),f+=1}let I=/(^|\s)7-6\s(\d+)\s/g,h=t.match(I);if(h?.length){let D=/(^|\s)7-6\s(\d+)\s/;h.forEach(M=>{let R=M.match(D).slice(2)[0];t=t.replace(M,`7-6(${R}) `),e.push("floatingTiebreakPattern1")})}let S=t.match(/\d \d /);S?.forEach(D=>{let M=D.slice(0,D.length-1).split(" ").join("-");t=t.replace(D,M),e.push("spaceSeparatedSetPattern1")}),S=t.match(/ \d \d$/),S?.forEach(D=>{let M=" "+D.slice(1).split(" ").join("-");t=t.replace(D,M),e.push("spaceSeparatedSetPattern2")});let T=/^\d, *\d\/\d, *\d/;if(T.test(t)){let D=t.match(T)[0],M=D.split("/").map(R=>`(${R})`).join(" ")+" ";t=t.replace(D,M),e.push("slashCommaSetPattern")}let y=/\(6-\)/g;y.test(t)&&(t=t.replace(y,"(6-0)"),e.push("missingZeroPattern2"));let P=/(?<!-)(\d+)\/(\d+)(?!-)/g;if(P.test(t)){let D=t.match(P),M=/(?<!-)(\d+)\/(\d+)(?!-)/,R=t;D.forEach(b=>{let[v,O]=b.match(M).slice(1),x=`${v}-${O}`;R=R.replace(b,x)}),t=R,e.push("slashSetPattern")}let U=/(.*)\s(1\d)\s(\d+)$/;if(U.test(t)){let[D,M,R]=t.match(U).slice(1);D.replace(/\D/g,"").length>=4&&(t=D+` ${M}${R}`,e.push("spaceSeparatedSuperPattern"))}let A=/(^|\s)(\d+-\d+)\s(\d+)(\s|$)/g;for(let D of t.match(A)||[]){let[M,R,b,v]=D.match(/(^|\s)(\d+-\d+)\s(\d+)(\s|$)/).slice(1),[O,x]=R.split("-").map(L=>parseInt(L));Math.abs(O-x)===1&&(t=t.replace(D,`${M}${R}(${b})${v}`),e.push("spaceSeparatedSetPattern"))}let E=/\d-\d \(\d{1,2}\)(\s|$|,)/g;for(let D of t.match(E)||[]){let M=/(\d-\d) \((\d{1,2})\)(\s|$|,)/,[R,b,v]=D.match(M).slice(1),[O,x]=R.split("-").map(L=>parseInt(L));Math.abs(O-x)===1&&(t=t.replace(D,`${R}(${b})${v}`),e.push("floatingTiebreakPattern2"))}let N=/(^|\s)(\d \d)\(/g;for(let D of t.match(N)||[]){let M=/(^|\s)(\d \d)\(/,[R,b]=D.match(M).slice(1);t=t.replace(D,`${R}${b.split(" ").join("-")}(`),e.push("spacedTiebreakPattern")}return{score:t,applied:e}}function g_({score:t,matchUpStatus:e}){let r=t?.split(" ");t=r.map(a=>{if(a.endsWith("]")){let c=a.split("[");if(Oa(c[0]))return c[0]+`(${c[1].slice(0,c[1].length-1)})`}return a}).join(" ");let n=new RegExp(/(\([\d ]+\))/g);if(n.test(t))for(let a of t.match(n)){let u=a.replace(" ","-").match(/\((.*)\)/)?.[1];if(Zt(u)&&u?.[0]>2){if([2,4].includes(u.length))u=u.split("").join("-");else if(u.length===3){let p=u.indexOf("1");u=qp(u.split(""),p)}}t=t.replace(a,`(${u})`)}r=t?.split(" ");let o=new RegExp(/^(\d[-/]+\d)\((\d+)[-/]+(\d+)\)$/),i=r.length-1;t=r.map((a,c)=>{let u=[void 0,"","COMPLETED"].includes(e)||c!==i;if(o.test(a)&&u){let[p,m,d]=Array.from(a.match(o)).slice(1),l=Math.min(m,d);return`${p}(${l})`}return a}).join(" "),r=t?.split(" "),o=new RegExp(/^(\d{2})\((\d+)\)$/),t=r.map(a=>{if(o.test(a)){let[c,u]=Array.from(a.match(o)).slice(1),p=c.split("");return`${p[0]}-${p[1]}(${u})`}return a}).join(" "),r=t?.split(" "),o=new RegExp(/^\((\d[-/]+\d)\)(\d+)$/),t=r.map(a=>{if(o.test(a)){let[c,u]=Array.from(a.match(o)).slice(1);return Oa(c)?`${c}(${u})`:c}return a}).join(" "),r=t?.split(" "),o=new RegExp(/^1-0\((\d+)\)$/),t=r.map(a=>{if(o.test(a)){let[c]=a.match(o).slice(1);return`[${c<9?10:parseInt(c)+2}-${c}]`}return a}).join(" ");let s=/\((\d)+0 /;if(s.test(t)){let a=t.match(s)[1];t=t.replace(s,`(${a}) `)}return{score:t}}function I_({score:t,attributes:e,identifier:r}){if(typeof t!="string")return{score:t,identifier:r};let n=new RegExp(/\([\d,/ ]+\)/g),o=t.match(n);for(let m of o||[]){let l=m.match(/^\((.*)\)$/)?.slice(1)?.[0],g=t.split(m)[0].split(")").reverse()[0].replace(/\D/g,"");if(l?.length===2&&g?.length>=2){let S=g.slice(g.length-2).split("").map(y=>parseInt(y));if(Math.abs(S[0]-S[1])===1)continue}let I=KD(l),h=wu(I);t=t.replace(m,`(${h})`).trim()}let i=new RegExp(/\[[\d,/ ]+\]/g);t.match(i)?.forEach(m=>{let d=KD(m.match(/^\[(.*)\]$/)[1]);t=t.replace(m,`(${d}) `).trim()});let a=[")","]"],c=[")(","), (",") (",")[",") [","](","] ("];if(t.startsWith("(")&&a.some(m=>t.endsWith(m))&&c.some(m=>t.includes(m))){let m="",d=t.split(/[)\]]/).filter(Boolean).map(h=>(h.startsWith(",")&&(h=h.slice(1)),h.trim())),l=d.every(h=>h.includes(",")||Wd(h)),f=d.every(h=>h.includes("/")||Wd(h)),g=d.every(h=>h.includes("-")||Wd(h)),I=l&&","||g&&"-"||f&&"/";if(I){let h;d.forEach(S=>{if(S.startsWith("("))if(h==="set"&&(m+=" "),S.includes(I))m+=S.slice(1).split(I).map(T=>T.trim()).join("-"),h="set";else{let T=S.slice(1);m+=`(${T}) `,h="tiebreak"}else if(S.startsWith("[")){let T=S.slice(1).split(I).map(P=>parseInt(P.trim())),y=Math.min(...T);h==="set"?m+=`(${y}) `:m+=`[${T.join("-")}] `,h="tiebreak"}}),t=m.trim()}}let u=Sr(t.split(""));u["("]===1&&u[")"]===1&&t.startsWith("(")&&t.endsWith(")")&&(t=t.slice(1,t.length-1),u["-"]===1&&Oa(t)&&Zt(e?.removed)&&(t=t+`(${e.removed})`,e.removed=void 0));let p=/\(\)/g;return p.test(t)&&(t=t.replace(p,"").trim()),{score:t}}function xT({score:t}){let e=t.split(""),r=[],n,o=()=>n=[void 0,void 0,void 0],i=()=>{let a=`${n[0]}-${n[1]}`;return n[2]&&(a+=` (${n[2]})`),o(),n.push(n),a};o();let s=()=>n[0]!==void 0&&n[1]!==void 0&&Math.abs(parseInt(n[0])-parseInt(n[1]));for(;e.length;){let a=e.shift(),c=Zt(a)&&parseInt(a),u=n[0]!==void 0&&n[1]!==void 0;if(Zt(c)){if(n[0]===void 0){n[0]=c;continue}if(n[1]===void 0&&(n[1]=c,s())){r.push(i()),n=[void 0,void 0];continue}if(u&&e.length===1&&Zt(e[0])){let p=e.pop();n[0]=n[0].toString()+n[1].toString(),n[1]=p,r.push(i()),n=[void 0,void 0]}u&&s()}}return{sets:r}}function kg(t){let e=t.indexOf("1"),r=t.split(""),n=r.every(o=>!isNaN(o));if(n&&t.length===3&&e===0){let o=qp(r,e);if(o)return o}if(n&&t.length===7&&e>3){let o=r.slice(4),i=qp(o,e-4);if(i)return`${r[0]}-${r[1]} ${r[2]}-${r[3]} ${i}`}}function zD(t){let{score:e}=t,{applied:r,matchUpStatus:n}=t,o=e?.toString().split(""),i=o?.every(a=>Zt(a)),s=a=>Math.abs(a[0]-a[1]);if(typeof e=="number"||i){e=e.toString().toLowerCase(),i&&(e=o.join(""));let a=i?o.map(u=>parseInt(u)):e.split("").map(u=>parseInt(u)),{sets:c}=xT({score:e});if(a.length,e.length===3&&s(a.slice(0,2))===1){let[u,p,m]=a;e=`${u}-${p}(${m})`,r.push("numericTiebreakPattern1")}else if(e.length===3&&a[0]===1){let[u,p,m]=a;e=`[${u}${p}-${m}]`,r.push("numericTiebreakPattern2")}else if(e.length===4&&s(a.slice(0,2))===1&&"987654".split("").includes(a[0].toString())){let[u,p,m,d]=a,l=Math.min(m,d);e=`${u}-${p}(${l})`,r.push("numericTiebreakPattern3")}else if(e.length===4&&a[0]===1&&a[2]===1){let[u,p,m,d]=a;e=`[${u}${p}-${m}${d}]`,r.push("bigSuper")}else if(e.length===4){let[u,p,m,d]=a;e=`${u}${p} ${m}${d}`,r.push("split4")}else if(e.length===5&&s(a.slice(0,2))===1){let[u,p,m,d,l]=a;e=`${u}-${p}(${m}) ${d}-${l}`,r.push("numericTiebreakPattern4")}else if(e.length===5&&s(a.slice(3))===1){let[u,p,m,d,l]=a;e=`${u}-${p} ${m}-${d}(${l})`,r.push("numericTiebreakPattern5")}else if(a.length===7)if(s(a.slice(0,2))>1&&s(a.slice(2,4))>1&&a[4]===1){let[u,p,m,d,l,f,g]=a;e=`${u}-${p} ${m}-${d} [${l}${f}-${g}]`,r.push("numericTiebreakPattern6")}else if(s(a.slice(0,2))===1&&s(a.slice(3,5))>1&&s(a.slice(5,7))>1){let[u,p,m,d,l,f,g]=a;e=`${u}-${p}(${m}) ${d}-${l} ${f}-${g}`,r.push("numericTiebreakPattern7")}else if(s(a.slice(0,2))>1&&s(a.slice(2,4))===1&&s(a.slice(5,7))>1){let[u,p,m,d,l,f,g]=a;e=`${u}-${p} ${m}-${d}(${l}) ${f}-${g}`,r.push("numericTiebreakPattern8")}else if(s(a.slice(0,2))>1&&s(a.slice(2,4))>1&&s(a.slice(4,6))===1){let[u,p,m,d,l,f,g]=a;e=`${u}-${p} ${m}-${d} ${l}-${f}(${g})`,r.push("numericTiebreakPattern9")}else e=e.slice(0,2)+" "+e.slice(2,4)+" "+e.slice(4),r.push("numericMatchTiebreakPattern");else if(e.length%2){let u=kg(e);u&&e!==u&&r.push("parsedSuperPattern"),e=u??e}else{let u=Ae(e.split(""),2).map(h=>h.join("")),p=u.map(h=>{let[S,T]=h.split("").map(U=>parseInt(U)),y=Math.abs(S-T),P=S>T?1:2;return y>1&&P||P*-1}),m=p.reduce((h,S)=>h>0&&S>0,1),d=Sr(p),l=p.map(h=>Math.abs(h)),f=Sr(l),g=p[0]<0,I=!g&&p[1]<0;if(p[0]>0&&p[1]>0&&p[0]!==p[1])e=[u.slice(0,2).join(" "),u.slice(2).join("-")].join(" "),r.push("numeric3rdSetTiebreakPattern");else if(m)e=u.join(" "),r.push("chunkSplit");else if(a.length===6){if(d[1]===2||d[2]===2)if(!Object.values(f).includes(3))e=u.join(" "),r.push("chunkSplit");else{let[h,S,T,y,P,U]=a,A=p.reduce((E,N,D)=>N<0?D:E,void 0);if(A===0){let E=Math.min(T,y);e=`${h}-${S}(${E}) ${P}-${U}`,r.push("chunkSplitTiebreak1")}else if(A===1){let E=Math.min(P,U);e=`${h}-${S} ${T}-${y}(${E})`,r.push("chunkSplitTiebreak2")}else e=`${h}-${S} ${T}-${y}`,r.push("chunkSplitTrimExtraneous")}}else if(a.length===8){let[h,S,T,y,P,U,A,E]=a;g||I?a[5]===1&&(g?e=`${h}-${S}(${T}) ${y}-${P} [${U}${A}-${E}]`:e=`${h}-${S} ${T}-${y}(${P}) [${U}${A}-${E}]`):(p[0],p[1])}}}return{score:e,applied:r,matchUpStatus:n}}function wT(t){let e=[0,0],r=[],n=t.split(" "),o=/(\d+)-(\d+)/;n.forEach(c=>{if(o.test(c)){let u=c.match(o).slice(1).map(m=>parseInt(m)),p=u[0]>u[1]&&1||u[1]>u[0]&&2;p&&(e[p-1]+=1,r.push(p))}});let i=e[0]>e[1]&&1||e[1]>e[0]&&2,s=e[0]>0&&e[0]===e[1],a=e.reduce((c,u)=>c+u,0);return{setsWon:e,setsTied:s,setWinners:r,totalSets:a,winningSide:i}}function h_({score:t,matchUpStatus:e,attributes:r}){let n=[],o,i=t.split(" "),s=i.length;t=i.map((p,m)=>{if(new RegExp(Yp).test(p)){let l=p.slice(3),f=p.slice(0,3),g=f.split("-");if(!Oa(f)&&!e){let I=Math.max(...g),h=f.indexOf(I),S=[I,I-1];return h&&S.reverse(),S.join("-")+l}}else if(p.length===2&&Zt(p))return p.split("").join("-");p=wu(p);let d=new RegExp(`^${Fg}$`).test(p)&&"super"||new RegExp(`^${Yp}$`).test(p)&&"tiebreak"||new RegExp(`^${Hd}$`).test(p)&&"standard"||"unknown";if(n.push(d),s>1&&d==="standard"&&m<2){let[l,f]=p.split("-"),g=Math.abs(parseInt(l)-parseInt(f)),I=Math.max(l,f),h=Math.min(l,f),S=[parseInt(l),parseInt(f)].indexOf(h);if(I>9&&g>2){let T=I.toString().split(""),y=T.find(P=>parseInt(P)>h||m&&parseInt(P)<=o)??T[0];y&&(p=S?[y,h].join("-"):[h,y].join("-"))}I>(o||0)&&(o=I)}if(d==="standard"){let[l,f]=p.split("-");if(!Math.abs(parseInt(l)-parseInt(f))&&e!=="RETIRED")return""}return p}).filter(Boolean).join(" ");let{setsWon:a,setWinners:c,totalSets:u}=wT(t);if(u===1&&r?.removed==="6"&&(t+=" 6-0"),t.split(" ").length>2&&Math.max(...a)>=2&&c[0]===c[1]&&(t=t.split(" ").slice(0,2).join(" ")),Math.max(...a)>2){let p=[0,0];t=t.split(" ").map((m,d)=>(p[c[d]]+=1,Math.max(...p)>2?void 0:m)).filter(Boolean).join(" ")}return{score:t,profile:n}}function S_({score:t}){let{setsTied:e,winningSide:r}=wT(t),n=/\s\((\d+)\)$/;if(!r&&e&&n.test(t)){let a=t.match(n).slice(1)[0],c=a<=8?10:a+2;t=t.replace(n,` [${c}-${a}]`)}let o=t.split(" "),i=o[o.length-1];if(!i.includes("-")||i.indexOf("(")>0)return{score:t};let s=i.split("(").join("").split(")").join("").split("-");if(!s.every(a=>Zt(a)))return{score:t};if(s[0]==="76"){let a=s[1].length===2?Math.min(...s[1].split("").map(c=>parseInt(c))):s[1];t=[...o.slice(0,o.length-1),`7-6(${a})`].join(" ")}else{s=s.map(u=>parseInt(u));let a=Math.max(...s),c=Math.abs(s[0]-s[1]);if(a>=10){if(c>2&&s.every(u=>+u>=10)){let u=s.map(p=>p===a?p-10:10).sort();c=Math.abs(u[0]-u[1]),c>2&&(s=u)}t=[...o.slice(0,o.length-1),`[${s.join("-")}]`].join(" ")}else o.length===3&&a>=7&&c>2&&(t=[...o.slice(0,o.length-1),`[${s.join("-")}]`].join(" "))}return{score:t}}function eV({score:t}){return t=t?.toString().toLowerCase()||"",{score:t}}function rV({score:t,applied:e}){return typeof t!="string"?{score:t}:(t.toLowerCase().includes("o")&&(t=t.toLowerCase().split(" ").map(r=>r.split("o").join("0")).join(" "),e.push("replaceOh")),{score:t,applied:e})}function nV({score:t,applied:e}){return typeof t!="string"?{score:t}:(t=t.toLowerCase().split(" ").map(r=>{if(/^\d+$/.test(r)&&r.length>2){let n=r.indexOf("1");if(r.length%2){if(r.length===3&&n===0){let o=qp(r.split(""),n);return e.push("getSuper"),o}}else{let{score:o,applied:i}=zD({score:r,applied:[]});o!==r&&(r=o,e.push(...i))}}return r}).join(" "),{score:t,applied:e})}function oV({score:t,applied:e}){return typeof t!="string"?{score:t}:[3,4].includes(t.length)&&kg(t)?{score:kg(t)}:(t=t.toLowerCase().split(" ").map(r=>{if(/^\d+$/.test(r)&&r.length===1){e.push("removeErroneous1");return}return r}).filter(Boolean).join(" "),{score:t,applied:e})}function iV({score:t,applied:e}){return["walkover","wo","w/o","w-o"].includes(t?.toString().toLowerCase())?(e.push("handleWalkover"),{matchUpStatus:"walkover",score:"",applied:e}):{score:t}}function sV({score:t,profile:e,applied:r}){t=t?.toString().toLowerCase();let n=/^(.*\d+.*)(ret|con)+[A-Za-z ]*$/;if(n.test(t)){let[a]=t.match(n).slice(1);return r.push("handleRetired"),{score:a.trim(),matchUpStatus:"retired",applied:r}}let o=e?.matchUpStatuses?.retired,s=["rtd",...Array.isArray(o)?o:[o].filter(Boolean)].find(a=>t?.endsWith(a));return s?(r.push("handleRetired"),{matchUpStatus:"retired",score:t?.replace(s,"").trim(),applied:r}):{score:t}}function aV({score:t,attributes:e}){(t.endsWith(" am")||t.endsWith(" pm"))&&(t=""),t=t.replace(/[A-Za-z]+/g,"").trim(),[".",","].some(o=>t.endsWith(o))&&(t=t.slice(0,t.length-1));let r="()/-".split("").some(o=>t.includes(o));/ \d$/.test(t)&&r&&(e={removed:t.slice(t.length-2).trim()},t=t.slice(0,t.length-2));let n=/(.*)[A-Za-z]+$/;return n.test(t)&&(t=t.match(n).slice(1)[0].trim()),{score:t,attributes:e}}function cV({score:t}){return new RegExp(/-\d+\/\d+-/).test(t)&&(t=t.split("/").join(" ")),{score:t}}function uV({score:t}){let e=new RegExp(/^\d+\/\d+/),r=t.split(" ");r.some(o=>e.test(o))&&(t=r.map(o=>e.test(o)?o.replace("/","-"):o).join(" "));let n=/^(\d+), *(\d+)$/;if(n.test(t)){let[o,i]=t.match(n).slice(1);t=[o,i].join("-")}return{score:t}}function pV({score:t}){let e=new RegExp(/\(\d+\/\d+\)/g),r=t.match(e);for(let n of r||[]){let o=n.replace("/","-");t=t.replace(n,o)}return{score:t}}function mV({score:t}){if(t.includes(",")){let e=t.split(",").map(o=>o.trim()),r=o=>/\d \d/.test(o);e.every(r)&&(t=e.map(o=>{let i=/\d+ \d+/g;for(let s of o.match(i)){let[a,c]=s.match(/(\d+) (\d+)/).slice(1);o=o.replace(s,`${a}-${c}`)}return o}).join(" "))}if(t.includes(" ")){let e=t.replace(/[ ,]/g,"");e.split("").every(n=>Zt(n))&&e.length===4&&(t=e)}return{score:t}}function dV({score:t}){let e=new RegExp(/^\[\d+\](.*)$/);e.test(t)&&(t=t.match(e).slice(1)[0].trim());let r=/\(,/g;return r.test(t)&&(t=t.replace(r,"(")),{score:t}}var T_={handleTiebreakSlashSeparation:pV,handleSetSlashSeparation:cV,punctuationAdjustments:m_,handleGameSeparation:uV,joinFloatingTiebreak:l_,handleBracketSpacing:d_,handleSpaceSeparator:mV,separateScoreBlocks:nV,matchKnownPatterns:f_,removeDanglingBits:aV,removeErroneous:oV,handleWalkover:iV,properTiebreak:g_,handleNumeric:zD,handleRetired:sV,containedSets:I_,sensibleSets:h_,stringScore:eV,superSquare:S_,setBuilder:xT,excisions:dV,replaceOh:rV};var QD={},lV=[],fV=["handleNumeric","handleWalkover","handleRetired","replaceOh","stringScore","punctuationAdjustments","excisions","handleSpaceSeparator","matchKnownPatterns","removeDanglingBits","handleBracketSpacing","matchKnownPatterns","containedSets","separateScoreBlocks","handleGameSeparation","removeErroneous","joinFloatingTiebreak","handleSetSlashSeparation","handleTiebreakSlashSeparation","properTiebreak","sensibleSets","superSquare"],gV=["handleNumeric","separateScoreBlocks","sensibleSets","superSquare"];function XD(t){if(!t.score)return{error:G};let{score:e,sheetName:r,identifier:n,fileName:o,stepLog:i,fullLog:s,profile:a}=t,c=[],u,p=[],m,d,l=e,f=I=>{I.forEach(h=>{d=T_[h]({profile:a,identifier:n,matchUpStatus:u,attributes:m,applied:p,score:l});let S=d.score!==l;S&&c.push({method:h,score:d.score}),i&&(s||S||d.matchUpStatus!==u)&&console.log(u?{score:d.score,matchUpStatus:u}:{score:d.score},h),d.matchUpStatus&&(u=d.matchUpStatus),d.attributes&&(m=d.attributes),d.applied&&(p=d.applied),l=d.score})};f(fV);let g=$D(l);return g||(l=e.toString().replace(/\D/g,""),m?.removed&&(m.removed=void 0),f(gV),g=$D(l),g||(lV.push({score:l,fileName:o,sheetName:r}),l="")),p.forEach(I=>{QD[I]||(QD[I]=0),QD[I]+=1}),{matchUpStatus:u?.toUpperCase(),modifications:c,attributes:m,isValid:g,score:l}}var ZD={};Xt(ZD,{analyzeScore:()=>Gg,analyzeSet:()=>Lu,checkScoreHasValue:()=>Ie,checkSetIsComplete:()=>Wp,getSetComplement:()=>Bg,getTiebreakComplement:()=>$p,isValidMatchUpFormat:()=>Dr,parseScoreString:()=>jd,validateScore:()=>Vg,validateTieFormat:()=>ar});function Gg({existingMatchUpStatus:t,matchUpFormat:e,matchUpStatus:r,winningSide:n,score:o}){let i=o?.sets??[],a=(i?.filter(A=>A?.winningSide)||[]).reduce((A,E)=>{let{winningSide:N}=E;if(!N)return A;let D=N-1;return A[D]++,A},[0,0]),c=n?n-1:void 0,u=c!==void 0?1-c:void 0,p=c!==void 0&&a[c],m=u!==void 0&&a[u],d=e?Ye(e):void 0,l=Math.max(...a),f=Sr(a)[l],g=d?.setFormat?.timed||d?.finalSetFormat?.timed,I=d?.bestOf,h=I&&Math.ceil(I/2)||1,S=r??t,T=S&&[Mt,rr,Ct].includes(S),y=!d||!i.length||i.every((A,E)=>{let N=E+1,D=N===I,M=N===i.length,{side1Score:R,side2Score:b,side1TiebreakScore:v,side2TiebreakScore:O,winningSide:x}=A,F=Math.max(R??0,b??0),L=v??O,{finalSetFormat:w,setFormat:V}=d,k=D&&w||V;if(L){let{tiebreakTo:H,NoAD:q}=k?.tiebreakFormat||{},$=Math.max(v??0,O??0);if(q&&$>H||$<H&&x&&(M&&!T||!M))return!1}return k.setTo?!(!k.noTiebreak&&F>k.setTo+1):!0}),P=(!e||l===h)&&f===1&&a.indexOf(l)+1||void 0;return{valid:!!(y&&(n&&p>m&&n===P||n&&T||!n&&!P&&(![le,Mt,rr,Ct].includes(S)||g&&S===le)))}}function Vg({existingMatchUpStatus:t,matchUpFormat:e,matchUpStatus:r,winningSide:n,score:o}){if(typeof o!="object")return{error:G};let{sets:i,scoreStringSide1:s,scoreStringSide2:a}=o,c="scoreString must be a string!";if(s!==void 0&&typeof s!="string")return{error:G,info:c};if(a!==void 0&&typeof a!="string")return{error:G,info:c};if(i!==void 0&&!Array.isArray(i))return{error:G,info:si("sets")};if(i?.length){let u=i.map(m=>m?.setNumber).filter(Boolean);if(u.length!==ut(u).length)return{error:G,info:"setNumbers not unique"};for(let m of i){let{side1Score:d,side2Score:l,side1TiebreakScore:f,side2TiebreakScore:g,side1PointScore:I,side2PointScore:h,winningSide:S,setNumber:T}=m;if(![[d,l],[f,g],[I,h]].filter(U=>U.some(A=>![void 0,null].includes(A))).every(U=>U.every(A=>It(A))))return{error:G,info:"non-numeric values"};if(![T,S].filter(U=>![void 0,null].includes(U)).every(U=>It(U)))return{error:G,info:"non-numeric values"};if(S&&![1,2].includes(S))return{error:G,info:"winningSide must be 1 or 2"}}let{valid:p}=Gg({existingMatchUpStatus:t,matchUpStatus:r,matchUpFormat:e,winningSide:n,score:o});if(!p)return{error:nE,info:"score is invalid for matchUpFormat or winningSide does not match calculated winningSide"}}return{valid:!0}}var Bg=t=>{let{isSide1:e,lowValue:r,setTo:n,tiebreakAt:o,NoAD:i}=t;if(r===void 0)return!1;let s=pt(r);s?.toString().length>2&&(s=parseInt(s.toString().slice(0,2))),o&&o<n&&s>o&&(s=o);let a;return i&&!o?(s>n&&(a=n),a=s<n?n:n-1):a=s+1<n&&n||o&&o<n&&s===o&&n||!o&&s+2||n+1,[e?s:a,e?a:s]},$p=t=>{let{isSide1:e,lowValue:r,tiebreakTo:n,tiebreakNoAd:o}=t;if(r===void 0)return!1;let i=typeof r=="string"?parseInt(r):r;i?.toString().length>2&&(i=parseInt(i.toString().slice(0,2))),o&&i>n-1&&(i=n-1);let s=IV({lowValue:i,NoAD:o,tiebreakTo:n});return[e?i:s,e?s:i]};function IV(t){let{lowValue:e,NoAD:r,tiebreakTo:n}=t,o=r?1:2;return e+1>=n?e+o:n}function jd({tiebreakTo:t=7,scoreString:e=""}){return e?.split(" ").filter(Boolean).map((n,o)=>r({set:n,setNumber:o+1}));function r({set:n,setNumber:o}){let i=/\(([^)]+)\)/,s=/\[([^)]+)\]/,a=i.exec(n),c=s.exec(n),u=n?.startsWith("[")&&c&&c[1].split("-").map(y=>parseInt(y)),p=a&&n.replace(a[0],"")||c&&n.replace(c[0],"")||n,m=!u&&p.split("-").map(y=>parseInt(y)),d=u?u[0]>u[1]&&1||u[0]<u[1]&&2||void 0:m[0]>m[1]&&1||m[0]<m[1]&&2||void 0,l=a?a[1]:void 0,g=(l&&$p({lowValue:l,isSide1:d===2,tiebreakTo:t}))??[],[I,h]=m||[],[S,T]=u||g||[];return{side1Score:I,side2Score:h,side1TiebreakScore:S,side2TiebreakScore:T,winningSide:d,setNumber:o}}}function y_({matchUpScoringFormat:t,isDecidingSet:e,isTiebreakSet:r,isTimedSet:n,setObject:o}){if(!o)return;let i=jp({set:o});return Wp({matchUpScoringFormat:t,set:o,isDecidingSet:e,isTiebreakSet:r,isTimedSet:n})&&i||void 0}function Lu(t){let{setObject:e,matchUpScoringFormat:r}=t;if(!e)return{error:Yl};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=[e?.side1Score,e?.side2Score],f=[e?.side1PointScore,e?.side2PointScore],g=[e?.side1TiebreakScore,e?.side2TiebreakScore],I=l.filter(L=>L!==void 0).length,h=f.filter(L=>L!==void 0).length,S=g.filter(L=>L!==void 0).length,T=l?.filter(L=>!isNaN(L)).length,y=g?.filter(L=>!isNaN(L)).length,{tiebreakAt:P}=c||{},U=P&&l.filter(L=>L>=P).length===2,A=U&&(l[0]>l[1]&&1||l[1]>l[0]&&2||void 0),E=!!(y&&!T),N=!!e?.winningSide,{error:D,result:M}=hV({sideTiebreakScores:g,sideGameScores:l,setFormat:c,setObject:e}),{error:R,result:b}=SV({sideTiebreakScores:g,setObject:e,setFormat:c}),v=m&&!E&&M||u&&E&&b||p,O=d&&!(u&&!E)&&!(m&&E)&&(!N||v),x=y_({isTimedSet:p,matchUpScoringFormat:r,isDecidingSet:a,isTiebreakSet:E,setObject:e}),F={expectTiebreakSet:u,expectTimedSet:p,hasTiebreakCondition:U,isCompletedSet:N,isDecidingSet:a,isTiebreakSet:E,isValidSet:O,isValidSetNumber:d,isValidSetOutcome:v,leadingSide:A,setFormat:c,sideGameScores:l,sideGameScoresCount:I,sidePointScores:f,sidePointScoresCount:h,sideTiebreakScores:g,sideTiebreakScoresCount:S,winningSide:x};return e?.winningSide!==void 0&&(E?(F.isValidTiebreakSetOutcome=b,b||(F.tiebreakSetError=R)):(F.isValidStandardSetOutcome=M,M||(F.standardSetError=D))),F}function hV({setObject:t,setFormat:e,sideGameScores:r,sideTiebreakScores:n}){if(!t)return{result:!1,error:Yl};let o=!!e?.tiebreakSet,i=!!e?.timed;if(!e||o||i)return{result:!1,error:G};if(!(r?.filter(M=>!isNaN(M)).length===2))return{result:!1,error:kI};let{setTo:a,tiebreakAt:c,tiebreakFormat:u,NoAD:p}=e||{};if(!!!(a&&r?.find(M=>M>=a)))return{result:!1,error:kI};let d=[1,2].includes(t?.winningSide);if(!t||!d)return{result:!1,error:Um};let l=t?.winningSide-1,f=1-l,g=r[l],I=r[f],h=g-I;if(!(g>I))return{result:!1,error:{message:"winningSide game scoreString is not high"}};let T=c&&u,y=n?.filter(M=>!isNaN(M)).length===2,P=n?.[l],U=n?.[f],A=c&&r.filter(M=>M>=c).length===2;if(T){let{NoAD:M,tiebreakTo:R}=u;if(A){if(h>1)return{result:!1,error:{message:"invalid winning game scoreString (5)"}};if(!y)return{result:!1,error:{message:"invalid tiebreak scores (1)"}};if(isNaN(R))return{result:!1,error:{message:"tiebreakTo error"}};if(!!!(R&&n?.find(V=>V>=R)))return{result:!1,error:{message:"invalid tiebreak scores (2)"}};let O=c<a?a:a+1;if(g>O)return{result:!1,error:{message:"invalid winning game scoreString (1)"}};if(!P||!U||P<U)return{result:!1,error:{message:"winningSide tiebreak value is not high"}};let x=M?1:2,F=P-U,L=U>=R-1;if(F&&L&&F<x)return{result:!1,error:{message:"invalid tiebreak scores (3)"}}}if(g>a&&!A)return{result:!1,error:{message:"invalid winning game scoreString (2)"}}}let E=p?1:2,N=I>=a-1;return h&&N&&!A&&h<E?{result:!1,error:{message:"invalid winning game scoreString (3)"}}:h>E&&g>a?{result:!1,error:{message:"invalid winning game scoreString (4)"}}:{result:!0}}function SV({setObject:t,setFormat:e,sideTiebreakScores:r}){if(!t)return{result:!1,error:Yl};let n=!!e?.tiebreakSet,o=!!e?.timed;if(!e||!n||o)return{result:!1,error:{message:"not tiebreak set"}};let i=[1,2].includes(t?.winningSide);if(!t||!i)return{result:!1,error:Um};let{tiebreakSet:s}=e||{},{NoAD:a,tiebreakTo:c}=s||{};if(!(r?.filter(T=>!isNaN(T)).length===2))return{result:!1,error:{message:"invalid tiebreak scores (1)"}};if(isNaN(c))return{result:!1,error:{message:"tiebreakTo error"}};if(!!!r?.find(T=>T>=c))return{result:!1,error:{message:"invalid tiebreak scores (2)"}};let m=t?.winningSide-1,d=1-m,l=r[m],f=r[d];if(!l||!f||l<f)return{result:!1,error:{message:"winningSide tiebreak value is not high"}};let g=a?1:2,I=l-f,h=f>=c-1;return I&&h&&I<g?{result:!1,error:{message:"invalid tiebreak scores (3)"}}:{result:!0}}function A_(t){let{existingDrawDefinition:e,hydrateCollections:r,enforceGender:n,tieFormatName:o,matchUpType:i,eventType:s,isMock:a,event:c}=t,{tieFormat:u,matchUpFormat:p}=t;if(i===_e&&s===_e){let m=e?.structures?.find(({stage:d})=>d===nt)?.tieFormat;u=u||m||o&&c?.tieFormat?.tieFormatName===o&&c.tieFormat||o&&to({namedFormat:o,hydrateCollections:r,isMock:a,event:c})||c?.tieFormat||to({event:c,isMock:a,hydrateCollections:r}),p=void 0}else p||(u=void 0,c?.matchUpFormat||(p=Dn));if(u){let m=ar({gender:c?.gender,enforceGender:n,tieFormat:u});if(m.error)return m}return{tieFormat:u,matchUpFormat:p}}function E_(t){let e=t.drawDefinition,{existingQualifyingPlaceholderStructureId:r,appliedPolicies:n,drawEntries:o,structureId:i,idPrefix:s,isMock:a,event:c}=t,u=t.qualifyingProfiles,p=u?.length?TT({uuids:t.uuids,qualifyingProfiles:u,appliedPolicies:n,idPrefix:s,isMock:a}):void 0;if(p?.error)return p;e.structures=e.structures?.filter(({structureId:T})=>T!==r),e.links=e.links?.filter(({source:T})=>T.structureId!==r);let{qualifiersCount:m,qualifyingDrawPositionsCount:d,qualifyingDetails:l}=p??{};d&&(p?.structures&&e.structures?.push(...p.structures),p?.links&&e.links?.push(...p.links));let f=e.structures?.find(({stage:T,stageSequence:y})=>T===nt&&y===1),{qualifiersCount:g}=Is({stageSequence:1,drawDefinition:e,structureId:i,stage:nt}),I=Math.max(m??0,g??0),h=LS({qualifiersCount:I,drawDefinition:e,stage:nt});if(h.error||(h=_p({drawSize:d,stage:ct,drawDefinition:e}),h.error))return h;TV({drawDefinition:e,drawEntries:o,event:c});let S=yV({mainStructure:f,qualifyingDetails:l,drawDefinition:e});return S.error?S:{drawDefinition:e,structureId:i}}function TV({drawDefinition:t,drawEntries:e,event:r}){for(let n of(e??[]).filter(({entryStage:o})=>o===ct)){let o={...n,entryStage:n.entryStage??nt,drawDefinition:t,event:r};fd(o)}}function yV({mainStructure:t,qualifyingDetails:e,drawDefinition:r}){for(let n of e||[]){let{finalQualifyingRoundNumber:o,finalQualifyingStructureId:i,roundTarget:s,finishingPositions:a,linkType:c}=n,u=t&&Ma({targetStructureId:t.structureId,sourceStructureId:i,sourceRoundNumber:o,finishingPositions:a,targetEntryRound:s,linkType:c})?.link;if(u?.error)return u;u&&(r.links||(r.links=[]),r.links.push(u))}return{error:void 0}}function LT(t){let{participantIds:e}=t,r=t.drawDefinition?.entries?.filter(n=>{let o=n.entryStatus;return!t.restrictEntryStatus||Qr.includes(o)}).map(St)??[];if(e){let n=e.filter(o=>!r?.includes(o));if(n?.length)return _({result:{error:mn},info:{invalidParticipantIds:n}})}else e=r;return t.roundsCount&&t.restrictRoundsCount!==!1&&t.roundsCount>e.length-1&&(!t.enableDoubleRobin||t.roundsCount>(e.length-1)*2)?{error:G,info:"Not enough participants for roundsCount"}:t.roundsCount&&t.restrictRoundsCount!==!1&&t.roundsCount>31?{error:G,info:"roundsCount must be less than 32"}:{participantIds:e}}function Yd(t){let e=[],{roundsCount:r=1,drawDefinition:n,matchUpsCount:o,structureId:i,idPrefix:s,isMock:a,event:c}=t,u,p=LT(t);if(p.error)return p;for(let m of et(1,r+1)){let d=_u({restrictMatchUpsCount:t.restrictMatchUpsCount,ignoreLastRoundNumber:!!u,newRound:!u,drawDefinition:n,matchUpsCount:o,structureId:i,roundNumber:u,idPrefix:s,isMock:a,event:c});if(d.error)return _({result:d,info:{iteration:m}});d.matchUps?.length&&e.push(...d.matchUps),u=(d?.roundNumber??1)+1}return{matchUps:e}}function P_(t){let{tournamentRecord:e,participantIds:r,scaleName:n,eventType:o,adHocRatings:i={}}=t,s=t.scaleAccessor??we[n]?.accessor,a=e.participants??[];for(let c of r??[]){let u=a?.find(m=>m.participantId===c),p=U_({scaleName:`${n}.${Vm}`,participant:u,eventType:o});!p&&n&&(p=U_({scaleAccessor:s,participant:u,scaleName:n,eventType:o})),p&&!i[c]&&(i[c]=p)}return i}function U_({scaleType:t=Ii,scaleAccessor:e,participant:r,scaleName:n,eventType:o}){let a=(r&&yo({scaleAttributes:{eventType:o??Fs,scaleType:t,scaleName:n},participant:r}))?.scaleItem?.scaleValue;return e&&ht(a)?a[e]:a}function qd(t){let e=EV(t);if(e?.error)return e;let r=LT(t);if(r.error)return r;let n=AV(t);if(n.error)return n;let o=P_(t),i=t.tournamentRecord?.isMock??t.isMock,s=t.eventType??t.event?.eventType,a=[],c=[],u;for(let p of et(1,(t.roundsCount??1)+1)){let m=Fd({...t,participantIds:r.participantIds,structure:n.structure,ignoreLastRoundNumber:!0,iterationMatchUps:a,adHocRatings:o,roundNumber:u,eventType:s,isMock:i});if(m.error)return m;let{matchUps:d,...l}=m;l.modifiedScaleValues&&(o=l.modifiedScaleValues),c.push({...l,iteration:p,matchUpsCount:d?.length}),u=(l?.roundNumber??1)+1,d?.length&&a.push(...d)}return{...C,matchUps:a,roundResults:c}}function AV(t){if(t.structureId)return t.structureId;let e=t.drawDefinition,r=e?.structures?.filter(i=>i.stageSequence===1)?.reduce((i,s)=>{let a=s.stage&&ks[s.stage];return cr({structure:s})&&a>(ks[i?.stage]||1)?s:i},void 0),n=e?.structures?.find(i=>i.structureId===r?.structureId);return n?cr({structure:n})?{structure:n}:{error:ua}:{error:kt}}function EV(t){return t.roundsCount&&typeof t.roundsCount!="number"?{error:G,info:"roundsCount must be a number"}:typeof t.drawDefinition!="object"||t.drawDefinition.drawType&&t.drawDefinition.drawType!==$r?{error:ua}:!Array.isArray(t.drawDefinition?.entries)&&t.participantIds&&!Array.isArray(t.participantIds)?{error:G,info:"Missing Entries"}:{error:void 0}}function D_(t){let{tournamentRecord:e,drawDefinition:r,structureId:n,idPrefix:o,isMock:i,event:s}=t,a=s?.entries?.filter(({entryStage:p,entryStatus:m})=>(!p||p===nt)&&m&&Qr.includes(m)),c=a?.map(St),u=a?Math.floor(a.length/2):0;if(t.automated)return UV({...t,participantIds:c});{let p=Yd({roundsCount:t.roundsCount,drawDefinition:r,matchUpsCount:u,idPrefix:o,isMock:i,event:s});if(p.error)return p;p.matchUps?.length&&bd({matchUps:p.matchUps,suppressNotifications:!0,tournamentRecord:e,drawDefinition:r,structureId:n,event:s})}return{...C}}function UV(t){let{restrictEntryStatus:e,generateMatchUps:r,structureId:n,matchUpIds:o,scaleName:i,scaleAccessor:s}=t.drawMatic??{},a=qd({...t,eventType:t.drawMatic?.eventType??t.matchUpType,generateMatchUps:r??!0,scaleAccessor:s??t.scaleAccessor,scaleName:i??t.scaleName,participantIds:t.participantIds,roundsCount:t.roundsCount,restrictEntryStatus:e,structureId:n,matchUpIds:o});return a.error?a:(a?.matchUps?.length&&bd({tournamentRecord:t.tournamentRecord,drawDefinition:t.drawDefinition,suppressNotifications:!0,matchUps:a.matchUps,event:t.event,structureId:n}),{...C})}function N_({requireParticipantCount:t=!0,enforcePolicyLimits:e=!0,drawSizeProgression:r,participantsCount:n,participantCount:o,appliedPolicies:i,drawDefinition:s,seedingProfile:a,structureId:c,seedsCount:u}){n=n??o;let p=at({drawDefinition:s,structureId:c});if(p.error)return p;let m=p.structure;if(!m)return{error:kt};let{positionAssignments:d}=Se({structure:m}),l=d?.length||0;if(u>l)return{error:xA};let f=m.structures?.length,g=It(a?.groupSeedingThreshold)&&a?.groupSeedingThreshold,I=fg({roundRobinGroupsCount:f,drawSize:l})?.seedGroups,{seedsCount:h}=Ou({policyDefinitions:i,requireParticipantCount:t,drawSizeProgression:r,participantsCount:n,drawSize:l});return h&&i?.[xn]&&u>h&&e&&(u=h),m.seedLimit=u,m.seedAssignments=et(1,u+1).map(S=>{let T=I?.find(U=>U.includes(S)),y=T&&Math.min(...T),P=g&&S>=g?y:S;return{participantId:void 0,seedNumber:S,seedValue:P}}),Ot({drawDefinition:s,structureIds:[c]}),{...C,seedLimit:u}}function ta({sortDescending:t=!1,tournamentRecord:e,scaleAttributes:r,scaleSortMethod:n,stageSequence:o,entries:i,event:s,stage:a}){if(!e)return{error:Y};return i=i??s?.entries??[],{scaledEntries:i.filter(d=>(!a||!d.entryStage||d.entryStage===a)&&(!o||!d.entryStageSequence||d.entryStageSequence===o)&&Qr.includes(d.entryStatus)).map(d=>{let{participantId:l}=d,{scaleItem:f}=Nc({tournamentRecord:e,scaleAttributes:r,participantId:l});return{...d,...f}}).filter(d=>{let l=d.scaleValue;return!n&&(isNaN(l)||!parseFloat(l))?!1:l}).sort(n||p)};function p(d,l){return t?m(l)-m(d):m(d)-m(l)}function m(d){return parseFloat(d.scaleValue||(t?-1:1e5))}}function FT(t){let e="prepareStage",{drawDefinition:r}=t,{structures:n}=gn({stageSequence:t.stageSequence||1,roundTarget:t.roundTarget,stage:t.stage,drawDefinition:r}),o=t.preparedStructureIds||[],i=n?.find(({structureId:l})=>!o.includes(l));if(!i)return _({result:{error:kt},stack:e});let s=i?.structureId,{seedsCount:a,stageEntries:c,seedLimit:u}=vV({...t,structureId:s});(t.seededParticipants||t.event||t.seedingScaleName)&&NV({...t,seedsCount:a,structure:i,structureId:s});let p=t.automated!==!1&&t.drawType!==$r&&!(t.qualifyingOnly&&t.stage!==ct),m=(n?.length||0)>1,d=p?DV({...t,multipleStructures:m,seedLimit:u,structureId:s}):{};return d?.error?_({result:d,stack:e}):{...d,stageEntries:c,structureId:s,seedsCount:a}}function PV({entries:t,stage:e,stageSequence:r,roundTarget:n}){return t.filter(o=>{let i=dt({name:Mn,element:o})?.extension?.value;return(!o.entryStage||o.entryStage===e)&&(!r||!o.entryStageSequence||o.entryStageSequence===r)&&(!n||!i||i===n)&&ni.includes(o.entryStatus)})}function DV(t){let e=typeof t.automated=="object"&&t.automated.seedsOnly,r=Sc({...t,seedsOnly:e});if(r.error)return r;let n=r?.positionAssignments,o=r?.positioningReport;return{conflicts:r.conflicts,positionAssignments:n,positioningReport:o}}function NV(t){let{seededParticipants:e,seedingScaleName:r,entries:n,event:o}=t,i=n.map(St);e?MV({...t,enteredParticipantIds:i}):(o||r)&&RV({...t,enteredParticipantIds:i})}function MV(t){let{provisionalPositioning:e,enteredParticipantIds:r,seededParticipants:n,tournamentRecord:o,appliedPolicies:i,drawDefinition:s,seedingProfile:a,structureId:c,structure:u,event:p}=t,m=u?Ts({provisionalPositioning:e,appliedPolicies:i,drawDefinition:s,seedingProfile:a,structure:u}):void 0;n.filter(({participantId:d})=>r.includes(d)).filter(d=>!d.seedNumber||d.seedNumber<=n.length).sort((d,l)=>d.seedNumber<l.seedNumber?-1:d.seedNumber<l.seedNumber?1:0).forEach(d=>{let{participantId:l,seedNumber:f,seedValue:g}=d;$s({provisionalPositioning:e,tournamentRecord:o,drawDefinition:s,seedingProfile:a,participantId:l,seedBlockInfo:m,structureId:c,seedNumber:f,seedValue:g,event:p})})}function RV(t){let e=t.seedsCount,{provisionalPositioning:r,enteredParticipantIds:n,seedAssignmentProfile:o,assignSeedsCount:i,tournamentRecord:s,drawDefinition:a,seedByRanking:c,seedingProfile:u,structureId:p,event:m}=t,{categoryName:d,ageCategoryCode:l}=m?.category||{},f=m?.eventType,g=CV({...t,ageCategoryCode:l,categoryName:d,eventType:f})||c&&bV({...t,ageCategoryCode:l,categoryName:d,eventType:f}),I=g?.length??0;I<e&&(e=I),g?.filter(({participantId:h})=>n.includes(h)).slice(0,i||e).forEach((h,S)=>{let T=S+1,{participantId:y,scaleValue:P}=h,U=o?.[T]||P||T;$s({provisionalPositioning:r,tournamentRecord:s,drawDefinition:a,seedingProfile:u,participantId:y,structureId:p,seedNumber:T,seedValue:U,event:m})})}function CV(t){let{tournamentRecord:e,seedingScaleName:r,stageSequence:n,entries:o,stage:i,event:s}=t,{categoryName:a,ageCategoryCode:c}=s?.category||{},u=s?.eventType,p={scaleName:r||a||c||s.eventId,scaleType:ho,eventType:u};return ta({scaleAttributes:p,tournamentRecord:e,stageSequence:n,entries:o,stage:i}).scaledEntries}function bV(t){let{tournamentRecord:e,stageSequence:r,event:n,entries:o,stage:i}=t,{categoryName:s,ageCategoryCode:a}=n?.category||{},c=n?.eventType;return ta({scaleAttributes:{scaleName:s||a,scaleType:gi,eventType:c},tournamentRecord:e,stageSequence:r,entries:o,stage:i}).scaledEntries}function vV(t){let{seedsCount:e}=t;t.seededParticipants&&(e=t.seededParticipants.length),e>t.drawSize&&(e=t.drawSize);let r=PV(t);e>r.length&&(e=r.length);let{seedLimit:n}=N_({enforcePolicyLimits:t.enforcePolicyLimits??!0,appliedPolicies:t.appliedPolicies,participantsCount:r.length,seedingProfile:t.seedingProfile,drawDefinition:t.drawDefinition,structureId:t.structureId,seedsCount:e});return n&&n<e&&(e=n),{seedsCount:e,stageEntries:r,seedLimit:n}}function M_(t){let e=wd({...t,modifyOriginal:!1});if(e.error)return e;let r=e.drawDefinition,{suppressDuplicateEntries:n=!0,ignoreStageSpace:o,appliedPolicies:i,qualifyingOnly:s,seedingProfile:a,participants:c,drawEntries:u,placeByes:p,drawSize:m,drawType:d,entries:l}=t,f=[],g=[],I=OV({suppressDuplicateEntries:n,ignoreStageSpace:o,drawDefinition:r,drawEntries:u,drawType:d,entries:l});if(I.error)return I;let h=d===ki?0:pt(t.seedsCount??0),S=FT({...t,qualifyingOnly:!m||s,appliedPolicies:i,drawDefinition:r,seedingProfile:a,participants:c,stage:nt,seedsCount:h,placeByes:p,drawSize:m,entries:l});if(S.error&&!S.conflicts)return S;S.positioningReport?.length&&f.push({[nt]:S.positioningReport});let T=S.structureId;return S.conflicts&&(g=S.conflicts),d===$r&&t.roundsCount&&D_({...t,drawDefinition:r,structureId:T}),{drawDefinition:r,positioningReports:f,conflicts:g,structureId:T}}function OV(t){let{ignoreStageSpace:e,drawDefinition:r,drawEntries:n,drawType:o,entries:i}=t;for(let s of i){if(n&&s.entryStage&&s.entryStage!==nt)continue;let a={...s,ignoreStageSpace:e??o===$r,entryStage:s.entryStage??nt,event:t.event,drawDefinition:r,drawType:o},c=fd(a);if(n&&c.error)return c}return{error:void 0}}var _V=()=>({matchUpType:void 0,drawName:void 0,drawId:void 0,structures:[],entries:[],links:[]});var R_=_V;function C_(t){let{drawId:e=Dt(),processCodes:r,matchUpType:n,drawType:o}=t??{},i=R_();return Object.assign(i,{processCodes:r,matchUpType:n,drawType:o,drawId:e})}function $d(t){let e=t.structureIds,{tournamentRecord:r,drawDefinition:n,matchUpFormat:o,structureId:i,matchUpId:s,event:a}=t,c=rt(t,[{[Ve]:!0,[Fm]:!0}]);if(c.error)return c;if(!Dr({matchUpFormat:o}))return{error:qa};let u="setMatchUpFormat";if(s){let p=Bt({drawDefinition:n,matchUpId:s,event:a});if(p.error)return p;let m=p.matchUp;if(m?.matchUpType===_e)return{info:"Cannot set matchUpFormat when { matchUpType: TEAM }",error:dr};m&&(m.matchUpFormat=o,gt({tournamentId:r?.tournamentId,eventId:a?.eventId,context:u,drawDefinition:n,matchUp:m}))}else if(Array.isArray(e)){if(a?.eventType===_e)return{error:Hn};for(let p of e){let m=at({drawDefinition:n,structureId:p});if(m.error)return m;m.structure&&(m.structure.matchUpFormat=o)}}else if(i){if(a?.eventType===_e)return{error:Hn};let p=at({drawDefinition:n,structureId:i});if(p.error)return p;p.structure&&(p.structure.matchUpFormat=o)}else n&&(n.matchUpFormat=o);return e=e??(i?[i]:void 0),Ot({drawDefinition:n,structureIds:e}),{...C}}function b_({tieFormat:t}){let e=ar({checkCollectionIds:!1,tieFormat:t});if(e.error)return e;for(let r of t.collectionDefinitions)r.collectionId||(r.collectionId=Dt());return{tieFormat:t}}function v_({tournamentRecord:t,drawDefinition:e,matchUpFormat:r,matchUpType:n,tieFormat:o,event:i}){if((r||o)&&!(r&&i?.matchUpFormat===r||i?.tieFormat&&o&&JSON.stringify(i.tieFormat)===JSON.stringify(o))){if(o){let a=b_({tieFormat:o});if(a.error)return a;e.tieFormat=a.tieFormat??o}else if(r){let a=$d({tournamentRecord:t,drawDefinition:e,matchUpFormat:r,event:i});if(a.error)return{info:"matchUpFormat or tieFormat error",error:a.error}}n&&(e.matchUpType=n)}return{error:void 0}}var nN={};Xt(nN,{attachPolicies:()=>Qi,findPolicy:()=>ri,getAppliedPolicies:()=>yt,getPolicyDefinitions:()=>vo,mutate:()=>eN,query:()=>rN,removePolicy:()=>tN});var eN={};Xt(eN,{attachPolicies:()=>Qi,removePolicy:()=>tN});function tN(t){let e=rt(t,[{[nb]:!0,_anyOf:{[Ce]:!1,[ie]:!1,[Ve]:!1,[Do]:!1}}]);if(e.error)return e;let r,n=t.drawDefinition??t.event??((t.tournamentId||!t.tournamentRecords)&&t.tournamentRecord);if(n)return O_(t,n);if(t.tournamentRecords){let o=Object.keys(t.tournamentRecords);if(!o.length)return{error:Y};for(let i of o){let s=t.tournamentRecords[i],a=O_(t,s);if(a.error)return a;r=!0}}else return{error:Y};return r?{...C}:{error:Fc}}function O_(t,e){let r=yt(t).appliedPolicies??{};return r[t.policyType]?(delete r[t.policyType],Object.keys(r).length?At({element:e,extension:{name:nu,value:r}}):gr({element:e,name:nu}),{...C}):{error:Fc}}var rN={};Xt(rN,{findPolicy:()=>ri,getAppliedPolicies:()=>yt,getPolicyDefinitions:()=>vo});var oN={[xn]:{validSeedPositions:{ignore:!0},duplicateSeedNumbers:!0,drawSizeProgression:!0,seedingProfile:{drawTypes:{[Io]:{positioning:di},[Nn]:{positioning:di}},positioning:QC},policyName:"USTA SEEDING",seedsCountThresholds:[{drawSize:4,minimumParticipantCount:3,seedsCount:2},{drawSize:16,minimumParticipantCount:12,seedsCount:4},{drawSize:32,minimumParticipantCount:24,seedsCount:8},{drawSize:64,minimumParticipantCount:48,seedsCount:16},{drawSize:128,minimumParticipantCount:96,seedsCount:32},{drawSize:256,minimumParticipantCount:192,seedsCount:64}]}},Wg=oN;function __({appliedPolicies:t,policyDefinitions:e,drawDefinition:r,stack:n}){if(e&&typeof e!="object")return _({info:"policyDefinitions must be an object",result:{error:G},stack:n});let o={[ru]:t?.[ru]};return e?xV({policyDefinitions:e,appliedPolicies:t,policiesToAttach:o,drawDefinition:r}):o.avoidance&&Qi({drawDefinition:r,policyDefinitions:o}),!t?.[xn]&&!e?.[xn]&&(Qi({policyDefinitions:Wg,drawDefinition:r}),t&&Object.assign(t,Wg)),{error:void 0}}function xV({policyDefinitions:t,appliedPolicies:e,policiesToAttach:r,drawDefinition:n}){for(let o of Object.keys(t))JSON.stringify(e?.[o])!==JSON.stringify(t[o])&&(r[o]=t[o]);Object.keys(r).length&&(Qi({policyDefinitions:r,drawDefinition:n}),e&&Object.assign(e,r))}function x_(t){let{tournamentRecord:e,matchUpFormat:r,appliedPolicies:n,policyDefinitions:o,matchUpType:i,tieFormat:s,drawType:a,stack:c,event:u}=t,p=t.drawId?u?.drawDefinitions?.find(h=>h.drawId===t.drawId):void 0;p&&a!==p.drawType&&(p.drawType=a);let m=p??C_({processCodes:t.processCodes,drawId:t.drawId,drawType:a}),d=v_({tournamentRecord:e,drawDefinition:m,matchUpFormat:r,matchUpType:i,tieFormat:s,event:u});if(d.error)return _({result:d,stack:c});let l=__({appliedPolicies:n,policyDefinitions:o,drawDefinition:m,stack:c});if(l.error)return l;let f=p?.structures?.find(h=>h.stage===nt&&h.stageSequence===1)?.structureId,g=p?p.structures?.filter(h=>h.stage===ct):[],I=g?.length===1&&!g[0].matchUps?.length&&g[0].structureId;return{drawDefinition:m,structureId:f,existingDrawDefinition:p,existingQualifyingPlaceholderStructureId:I}}function w_(t){let e="generateOrGetExisting",r=[],n=[],o=x_(t);if(o.error)return _({result:o,stack:e});let i=o.existingDrawDefinition,s=o.drawDefinition??{},a=o.structureId,c=t.drawEntries??t.eventEntries??[],u=o.existingQualifyingPlaceholderStructureId&&E_({...t,...o})||M_({...t,...o,entries:c});return u.error?_({result:u,stack:e}):(u.positioningReports?.length&&r.push(...u.positioningReports??[]),u.conflicts?.length&&n.push(...u.conflicts??[]),s=u.drawDefinition,a=u.structureId,{existingDrawDefinition:i,positioningReports:r,drawDefinition:s,structureId:a,conflicts:n,entries:c})}function L_(t){let{qualifyingPlaceholder:e,qualifyingProfiles:r,existingDrawDefinition:n,positioningReports:o,appliedPolicies:i,qualifyingOnly:s,drawDefinition:a,seedingProfile:c,participants:u,structureId:p,entries:m,stack:d}=t,l=e&&!r?.length&&!n,f=[];if(r){let g=(T,y)=>T.stageSequence-y.stageSequence,I=(T,y)=>T.roundTarget-y.roundTarget,h=[],S=1;r.sort(I);for(let T of r){if(!Array.isArray(T.structureProfiles))return _({info:si("structureProfiles"),result:{error:st},stack:d});S=T.roundTarget||S;let y=T.structureProfiles?.sort(g)||[],P=1;for(let U of y){let{qualifyingRoundNumber:A,qualifyingPositions:E,seededParticipants:N,seedingScaleName:D,seedsCount:M=0,seedByRanking:R,placeByes:b,drawSize:v}=U,O=FT({...t,seedingProfile:U.seedingProfile??c,stageSequence:P,qualifyingRoundNumber:A,preparedStructureIds:h,qualifyingPositions:E,seededParticipants:N,stage:ct,seedingScaleName:D,appliedPolicies:i,drawDefinition:a,qualifyingOnly:s,seedByRanking:R,participants:u,roundTarget:S,seedsCount:M,placeByes:b,drawSize:v,entries:m});if(O.error)return O;O.structureId&&h.push(O.structureId),P+=1,O.conflicts?.length&&f.push(...O.conflicts),O.positioningReport?.length&&o.push({[ct]:O.positioningReport})}S+=1}}else if(p&&l){let g=hn({structureName:Qe(ct),stage:ct}),{link:I}=Ma({sourceStructureId:g.structureId,targetStructureId:p,sourceRoundNumber:0,linkType:eo});a.structures||(a.structures=[]),a.structures.push(g),a.links||(a.links=[]),a.links.push(I)}return{qualifyingConflicts:f,error:void 0}}var DN={};Xt(DN,{addGoesTo:()=>qi,allCompetitionMatchUps:()=>Un,allDrawMatchUps:()=>or,allEventMatchUps:()=>Kn,allPlayoffPositionsFilled:()=>OS,allTournamentMatchUps:()=>Te,analyzeDraws:()=>bu,analyzeMatchUp:()=>Jp,analyzeTournament:()=>KT,bulkUpdatePublishedEventIds:()=>XT,calculateWinCriteria:()=>Ps,categoryCanContain:()=>Yc,checkMatchUpIsComplete:()=>ds,checkValidEntries:()=>_d,compareTieFormats:()=>Ko,competitionScheduleMatchUps:()=>ku,courtGridRows:()=>nl,credits:()=>F_,drawMatchUps:()=>fy,eventMatchUps:()=>al,filterMatchUps:()=>Ni,filterParticipants:()=>Au,findDrawDefinition:()=>oT,findExtension:()=>dt,findVenue:()=>jo,getAggregateTeamResults:()=>$T,getAllDrawMatchUps:()=>se,getAllEventData:()=>JT,getAllStructureMatchUps:()=>Ut,getAllowedDrawTypes:()=>Kd,getAllowedMatchUpFormats:()=>WT,getAppliedPolicies:()=>yt,getAssignedParticipantIds:()=>Ri,getAvailableMatchUpsCount:()=>vd,getAvailablePlayoffProfiles:()=>Du,getCategoryAgeDetails:()=>Ls,getCheckedInParticipantIds:()=>us,getCompetitionDateRange:()=>Qd,getCompetitionMatchUps:()=>Xp,getCompetitionParticipants:()=>kT,getCompetitionPenalties:()=>jT,getCompetitionVenues:()=>Kp,getCourtInfo:()=>ud,getCourts:()=>gy,getDrawData:()=>Zd,getDrawDefinitionTimeItem:()=>zh,getDrawParticipantRepresentativeIds:()=>rT,getDrawStructures:()=>gn,getDrawTypeCoercion:()=>vu,getEligibleVoluntaryConsolationParticipants:()=>eT,getEntriesAndSeedsCount:()=>ol,getEvent:()=>Sy,getEventData:()=>tl,getEventMatchUpFormatTiming:()=>iy,getEventProperties:()=>Iy,getEventPublishStatus:()=>Xr,getEventStructures:()=>Ig,getEventTimeItem:()=>lu,getEvents:()=>hy,getFlightProfile:()=>Ht,getHomeParticipantId:()=>uy,getLinkedTournamentIds:()=>iu,getMatchUpCompetitiveProfile:()=>Iu,getMatchUpContextIds:()=>py,getMatchUpDailyLimits:()=>ul,getMatchUpDailyLimitsUpdate:()=>sy,getMatchUpDependencies:()=>sn,getMatchUpFormat:()=>my,getMatchUpFormatTiming:()=>hu,getMatchUpFormatTimingUpdate:()=>ny,getMatchUpScheduleDetails:()=>pd,getMatchUpType:()=>md,getMatchUpsMap:()=>Me,getMatchUpsStats:()=>dy,getMatchUpsToSchedule:()=>el,getMaxEntryPosition:()=>ey,getModifiedMatchUpFormatTiming:()=>il,getPairedParticipant:()=>In,getParticipantEventDetails:()=>GT,getParticipantIdFinishingPositions:()=>nT,getParticipantMembership:()=>VT,getParticipantResults:()=>Ru,getParticipantScaleItem:()=>Nc,getParticipantSchedules:()=>BT,getParticipantSignInStatus:()=>HT,getParticipantTimeItem:()=>Qh,getParticipants:()=>Gt,getPersonRequests:()=>bi,getPolicyDefinitions:()=>vo,getPositionAssignments:()=>Vp,getPositionsPlayedOff:()=>yc,getPredictiveAccuracy:()=>cy,getProfileRounds:()=>rl,getPublishState:()=>gs,getRoundMatchUps:()=>Ke,getRounds:()=>ly,getScaleValues:()=>la,getScaledEntries:()=>ta,getScheduledRoundsDetails:()=>Fu,getSchedulingProfile:()=>zo,getSchedulingProfileIssues:()=>ty,getSeedingThresholds:()=>ES,getSeedsCount:()=>Ou,getStructureSeedAssignments:()=>on,getTeamLineUp:()=>ms,getTieFormat:()=>QT,getTimeItem:()=>rn,getTournamentIds:()=>hp,getTournamentInfo:()=>Us,getTournamentPenalties:()=>zd,getTournamentPersons:()=>qT,getTournamentPoints:()=>Xd,getTournamentPublishStatus:()=>Tu,getTournamentStructures:()=>vS,getTournamentTimeItem:()=>Jm,getValidGroupSizes:()=>bp,getVenueData:()=>dc,getVenuesAndCourts:()=>Ao,isAdHoc:()=>cr,isCompletedStructure:()=>ai,isValidForQualifying:()=>hT,isValidMatchUpFormat:()=>Dr,matchUpActions:()=>Od,participantScaleItem:()=>yo,participantScheduledMatchUps:()=>ay,positionActions:()=>IT,publicFindCourt:()=>lS,publicFindVenue:()=>dS,tallyParticipantResults:()=>Ca,tieFormatGenderValidityCheck:()=>Rm,tournamentMatchUps:()=>cl,validMatchUp:()=>Zf,validMatchUps:()=>Vr,validateCollectionDefinition:()=>qc,validateLineUp:()=>Td});function F_(){return`
|