tods-competition-factory 2.2.26 → 2.2.28

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,11 +1,11 @@
1
- var pL=Object.defineProperty;var Jt=(t,e)=>{for(var r in e)pL(t,r,{get:e[r],enumerable:!0})};function Ba(){return"2.2.26"}var EA={};Jt(EA,{competitionGovernor:()=>bU,drawsGovernor:()=>_N,entriesGovernor:()=>VN,eventGovernor:()=>ZN,generationGovernor:()=>iM,matchUpFormatGovernor:()=>Fy,matchUpGovernor:()=>NM,mocksGovernor:()=>TI,participantGovernor:()=>rR,policyGovernor:()=>uN,publishingGovernor:()=>mR,queryGovernor:()=>vN,reportGovernor:()=>dR,scheduleGovernor:()=>PR,scoreGovernor:()=>$g,tieFormatGovernor:()=>xR,tournamentGovernor:()=>qR,venueGovernor:()=>rC});var bU={};Jt(bU,{getLinkedTournamentIds:()=>au,getTournamentIds:()=>Tp,linkTournaments:()=>DU,mutate:()=>RU,query:()=>CU,unlinkTournament:()=>MU,unlinkTournaments:()=>NU});var RU={};Jt(RU,{linkTournaments:()=>DU,unlinkTournament:()=>MU,unlinkTournaments:()=>NU});var ua="SINGLES",kt="SINGLES",_i="DOUBLES",xt="DOUBLES",xr="TEAM",Wt="TEAM",mC={SINGLES_MATCHUP:ua,SINGLES:kt,DOUBLES_MATCHUP:_i,DOUBLES:xt,TEAM_MATCHUP:xr,TEAM:Wt};var MI={[kt]:[kt,"S"],[xt]:[xt,"D"],[Wt]:[Wt,"T"],S:[kt,"S"],D:[xt,"D"],T:[Wt,"T"]};function le(t,e){return(t??0)-(e??0)}function dt(t){return typeof t=="number"?parseInt(t.toString()):typeof t=="string"?parseInt(t):0}function _n(t){return isNaN(t)?!1:t&&(t&t-1)===0}function NA(t){if(!t.length)return;let e=[...t].sort(le),r=Math.floor(e.length/2);return e.length%2?e[r]:(e[r-1]+e[r])/2}function dC(t){if(!_n(t))return!1;let e=t,r=1;for(;e!==2;)r+=1,e=e/2;return r}function ym(t){return isNaN(t)?0:t%2&&t+1||t}function Am(t){return Math.pow(2,Math.round(Math.log(t)/Math.log(2)))}function Zt(t){return!isNaN(parseFloat(t))}function RI(t){let e=dt(t);if(!isNaN(e))return e===0?!1:(e&-e)===1}function rs(t){if(isNaN(t))return!1;for(;!_n(t);)t++;return t}function fo(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 lC(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 mL(t,e){e||(e=1);let r=1/e;return Math.round(t*r)/r}function MA(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=MA(t,e,r):(a=Math.pow(a,r),a*=e-t,a+=t),n&&(a=mL(a,n)),parseFloat(a.toFixed(o))}function Ll(t,e=2){return parseFloat(Number(Math.round(t*1e3)/1e3).toFixed(e))}function pt(t){return Array.isArray(t)?t?.filter((e,r,n)=>n.lastIndexOf(e)===r):[]}function fC(t){return Array.isArray(t)?t?.map(e=>e===null?void 0:e):t}function Sr(t){return Array.isArray(t)?t.map(e=>[Math.random(),e]).sort((e,r)=>e[0]-r[0]).map(e=>e[1]):[]}function Ha(t){return It(t)?t:1/0}function yr(t){return Array.isArray(t)?t.reduce((e,r)=>(e[r]||(e[r]=0),e[r]++,e),{}):{}}function gC(t){return RA(yr(t))}function RA(t){return Object.keys(t).reduce((e,r)=>{let n=t[r];return e[n]?e[n].push(r):e[n]=[r],e},{})}function dL(t,e,r){return r.indexOf(t)===e}function CI(t){return t.filter(dL)}function Zr(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 tt(t,e){return Array.from({length:e-t},(r,n)=>n+t)}function go(t,e){return e.reduce((r,n,o)=>(n===t&&r.push(o),r),[])}function jt(t,e){return!Array.isArray(t)||!Array.isArray(e)?[]:t.filter(r=>e.indexOf(r)!==-1).filter((r,n,o)=>o.indexOf(r)===n)}function CA(t,e){return!Array.isArray(t)||!Array.isArray(e)?[]:t.filter(r=>!e.includes(r))}function ke(t,e){return!Array.isArray(t)||!Array.isArray(e)?!1:t.some(r=>e.includes(r))}function IC(t,e){return Array.isArray(e)&&e.reduce((r,n)=>(r[n]=1+r[n]||1,r),{})[t]||0}function hC(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 Ee(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 bA(t,[e,...r]){return t.length?[t.slice(0,e),...bA(t.slice(e),[...r,e])]:[]}function SC(t){return t.reduce((e,r)=>{let n=e[e.length-1];return(!n||n[n.length-1]!==r-1)&&e.push([]),e[e.length-1].push(r),e},[])}function bI(t){return Array.isArray(t)?t.reduce((e,r)=>!isNaN(parseInt(r))&&e,!0):!1}function vI(t){return Array.isArray(t)?t.reduce((e,r)=>isNaN(parseInt(r))&&e,!0):!1}function Fl(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 TC(t,e=1){if(!Array.isArray(t)||!t.every(It))return[];let r=Math.min(...t,e),n=Math.max(...t);return tt(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 yC(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 _I(t,e){return Array.isArray(t)?Object.assign({},...(t??[]).filter(ht).map(r=>r[e]&&{[r[e]]:r}).filter(Boolean)):{}}var AC=t=>e=>Object.keys(t).every(r=>e[r]===t[r]);function OI(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=>OI(i))}:{[o]:e?n(t[o]):OI(t[o])}))}function vA(t){return Array.isArray(t)?t.length+t.map(vA).reduce((e,r)=>e+r,0):ht(t)&&t!==null?Object.keys(t).length+Object.keys(t).map(e=>vA(t[e])).reduce((e,r)=>e+r,0):0}function EC(t){if(t===null||typeof t!="object")return;let e=JSON.stringify(t),r=vA(t),n=e.split("").reduce((o,i)=>o+i.charCodeAt(0),0);return[e.length,r,n].map(o=>o.toString(36)).join("")}function kc(t,e){return!Array.isArray(t)||!Vt(e)?!1:jt(t,MI[e]).length}var C={success:!0},OA="error",UC={SUCCESS:C,ERROR:OA};function xI({collectionValueProfiles:t,matchUpCount:e}){let r=[];if(!Array.isArray(t))return r.push(`collectionValueProfiles is not an array: ${t}`),{errors:r};if(t.length&&t.length!==e)return r.push("collectionValueProfiles do not align with matchUpsCount"),{errors:r};for(let o of t){if(typeof o!="object")return r.push(`valueProfile is not type object: ${o}`),{errors:r};let{matchUpValue:i,collectionPosition:s}=o;if(typeof i!="number"||typeof s!="number"||s>e||s<1)return r.push("Invalid value profile: value and collectionPosition must be numeric. collectionPosition cannot be greater than matchUpCount"),{errors:r}}let n=t.map(o=>o.collectionPosition);return n.length!==pt(n).length?(r.push("collectionPositions are not unique"),{errors:r}):{...C}}var wC={};Jt(wC,{addNotice:()=>lt,callListener:()=>Mm,createInstanceState:()=>VE,cycleMutationStatus:()=>lf,deepCopyEnabled:()=>df,deleteNotice:()=>QI,deleteNotices:()=>Gi,disableNotifications:()=>BE,enableNotifications:()=>mf,getDevContext:()=>Pr,getMethods:()=>ff,getNotices:()=>zI,getProvider:()=>XI,getTopics:()=>Lr,getTournamentId:()=>os,getTournamentRecord:()=>gf,getTournamentRecords:()=>Go,globalLog:()=>jE,handleCaughtError:()=>ap,hasTopic:()=>ip,removeTournamentRecord:()=>WE,setDeepCopy:()=>jc,setDevContext:()=>Wc,setGlobalLog:()=>OC,setGlobalMethods:()=>_C,setGlobalSubscriptions:()=>HL,setMethods:()=>xC,setStateMethods:()=>YE,setStateProvider:()=>VL,setSubscriptions:()=>WL,setTournamentId:()=>sp,setTournamentRecord:()=>HE,setTournamentRecords:()=>Rm,timeKeeper:()=>BL});var wI={message:"Chronological error; time violation.",code:"ANACHRONISM"},Em={message:"Duplicate entry",code:"DUPLICATE_ENTRY"},_A={message:"Cannot remove main structure",code:"ERR_CANNOT_REMOVE_MAIN_STRUCTURE"},LI={message:"records must be an object with tournamentId keys",code:"ERR_INVALID_TOURNAMENTS"},Lt={message:"Missing tournamentRecords",code:"ERR_MISSING_TOURNAMENTS"},$={message:"Missing tournamentRecord",code:"ERR_MISSING_TOURNAMENT"},Wa={message:"Invalid tournamentRecord",code:"ERR_INVALID_TOURNAMENT"},pa={message:"Missing tournamentId",code:"ERR_MISSING_TOURNAMENT_ID"},ma={message:"Invalid drawDefinition",code:"ERR_INVALID_DRAWDEF"},Z={message:"Missing drawDefinition",code:"ERR_MISSING_DRAWDEF"},xA={message:"Existing drawDefinition(s)",code:"ERR_EXISTING_DRAWDEFS"},Cr={message:"drawDefinition not found",code:"ERR_NOT_FOUND_DRAWDEF"},Zo={message:"Invalid structure",code:"ERR_INVALID_STRUCTURE"},kl={message:"Incomplete source structure",code:"ERR_INCOMPLETE_STRUCTURE"},Gl={message:"Invalid drawPosition for seedAssignment",code:"ERR_INVALID_SEEDING_POSITION"},ja={message:"drawPosition already assigned",code:"ERR_EXISTING_POSITION_ASSIGNMENT"},wA={message:"Schedule not cleared",code:"ERR_UNCHANGED_SCHEDULE_NOT_CLEARED"},LA={message:"drawPosition not cleared",code:"ERR_FAILURE_POSITION_NOT_CLEARED"},lL={message:"drawPosition not found",code:"ERR_NOT_FOUND_DRAW_POSITION"},Vl={message:"Unrecognized drawType",code:"ERR_UNRECOGNIZED_DRAW_TYPE"},Ya={message:"Missing drawPositions",code:"ERR_MISSING_DRAW_POSITIONS"},zu={message:"drawPosition is active",code:"ERR_ACTIVE_DRAW_POSITION"},PC={message:"drawPosition is occupied",code:"ERR_OCCUPIED_DRAW_POSITION"},Cs={message:"Invlid drawPosition",code:"ERR_INVALID_DRAW_POSITION"},bs={message:"Missing drawPosition",code:"ERR_MISSING_DRAW_POSITION"},Um={message:"Invalid drawType",code:"ERR_INVALID_DRAW_TYPE"},Qu={message:"Invalid drawSize",code:"ERR_INVALID_DRAW_SIZE"},FI={message:"Cannot set drawSize to be less than existing entries",code:"ERR_INVALID_DRAW_SIZE_MISMATCH"},qa={message:"Missing drawSize",code:"ERR_MISSING_DRAW_SIZE"},sn={message:"Missing drawId",code:"ERR_MISSING_DRAW_ID"},FA={message:"drawId exists",code:"ERR_EXISTING_DRAW_ID"},kA={message:"participantId cannot be assigned to multiple seedNumbers",code:"INVALID_PARTICIPANT_SEEDING"},GA={message:"seedsCount greater than drawSize",code:"ERR_INVALID_SEED_COUNT"},VA={message:"Missing seedCountThresholds",code:"ERR_MISSING_SEED_COUNT_THRESHOLD"},BA={message:"Invalid action",code:"ERR_INVALID_ACTION"},kI={message:"Invalid assignment",code:"ERR_INVALID_ASSIGNMENT"},HA={message:"Missing seedAssignments",code:"ERR_MISSING_SEED_ASSIGNMENTS"},WA={message:"Invalid seedNumber",code:"ERR_INVALID_SEED_NUMBER"},jA={message:"Invalid seedPosition",code:"ERR_INVALID_SEED_POSITION"},Bl={message:"Missing targetLink",code:"ERR_MISSING_LINK_TARGET"},YA={message:"Existing round",code:"ERR_EXISTING_ROUND"},fL={message:"Missing roundNumber",code:"ERR_MISSING_ROUND_NUMBER"},Ur={message:"Missing structureId",code:"ERR_MISSING_STRUCTURE_ID"},wt={message:"structure not found",code:"ERR_NOT_FOUND_STRUCTURE"},Hl={message:"Missing structures",code:"ERR_MISSING_STRUCTURES"},di={message:"Missing structure",code:"ERR_MISSING_STRUCTURE"},Wl={message:"Missing MAIN structure",code:"ERR_MISSING_MAIN_STRUCTURE"},qA={message:"drawDefinition contains unlinked structures",code:"ERR_MISSING_STRUCTURE_LINKS"},jn={message:"Invalid eventType",code:"ERR_INVALID_EVENT_TYPE"};var Ot={message:"Missing event / eventId",code:"ERR_MISSING_EVENT_ID"},jr={message:"Event not found",code:"ERR_NOT_FOUND_EVENT"},$A={message:"Event exists",code:"ERR_EXISTING_EVENT"},KA={message:"Missing entries",code:"ERR_MISSING_ENTRIES"},zA={message:"Invalid entries",code:"ERR_INVALID_ENTRIES"},jl={message:"Missing assignments",code:"ERR_MISSING_ASSIGNMENTS"},QA={message:"Missing stage",code:"ERR_MISSING_STAGE"},xi={message:"Invalid stage",code:"ERR_INVALID_STAGE"},XA={message:"stageSequence limit",code:"ERR_LIMIT_STAGE_SEQUENCE"},JA={message:"Missing positionAssignments",code:"ERR_MISSING_POSITION_ASSIGNMENTS"},ZA={message:"Cannot Assign BYE status if no assignment: { bye: true }",code:"ERR_UNCHANGED_CANNOT_ASSIGN_BYE"},GI={message:"Unrecognized matchUpStatus",code:"ERR_UNRECOGNIZED_MATCHUP_STATUS"},$a={message:"Unrecognized matchUpFormat",code:"ERR_UNRECOGNIZED_MATCHUP_FORMAT"},Yl={message:"Incompatible matchUpStatus",code:"ERR_INCOMPATIBLE_MATCHUP_STATUS"},da={message:"Invalid matchUpStatus",code:"ERR_INVALID_MATCHUP_STATUS"},ko={message:"Invalid tieFormat",code:"ERR_INVALID_TIE_FORMAT"},ql={message:"Invalid matchUpFormat",code:"ERR_INVALID_MATCHUP_FORMAT"},$l={message:"Missing matchUpFormat",code:"ERR_MISSING_MATCHUP_FORMAT"},tE={message:"Missing collectionDefinition",code:"ERR_MISSING_COLLECTION_DEFINITION"},vs={message:"Missing tieFormat",code:"ERR_MISSING_TIE_FORMAT"},cr={message:"Missing matchUpId",code:"ERR_MISSING_MATCHUP_ID"},ns={message:"Missing matchUpIds",code:"ERR_MISSING_MATCHUP_IDS"},Le={message:"matchUp not found",code:"ERR_NOT_FOUND_MATCHUP"},eo={message:"Missing matchUps",code:"ERR_MISSING_MATCHUPS"},Tr={message:"Missing matchUp",code:"ERR_MISSING_MATCHUP"},lr={message:"Invalid matchUp",code:"ERR_INVALID_MATCHUP"},VI={message:"Missing policyType",code:"ERR_MISSING_POLICY_TYPE"},Xu={message:"Missing policyDefinitions",code:"ERR_MISSING_POLICY_DEFINITIONS"},gL={message:"Missing seeding policy",code:"ERR_MISSING_POLICY_SEEDING"},eE={message:"Missing avoidance policy",code:"ERR_MISSING_POLICY_AVOIDANCE"},BI={message:"Missing policy attributes",code:"ERR_MISSING_POLICY_ATTRIBUTES"},rE={message:"Invalid policyDefinitions",code:"ERR_INVALID_POLICY_DEFINITIONS"},HI={message:"existing policyType",code:"ERR_EXISTING_POLICY_TYPE"},IL={message:"Policy not attached",code:"ERR_FAILURE_POLICY_NOT_ATTACHED"},Gc={message:"Policy not found",code:"ERR_NOT_FOUND_POLICY"},hL={message:"Missing scoring policy / matchUpFormats",code:"ERR_MISSING_POLICY_SCORING_MATCHUP_FORMATS"},Kl={message:"Invalid sideNumber",code:"ERR_INVALID_SIDE_NUMBER"},SL={message:"Invalid setNumber",code:"ERR_INVALID_SET_NUMBER"},zl={message:"Missing setObject",code:"ERR_MISSING_SET_ATTRIBUTE"},TL={message:"Missing setNumber",code:"ERR_MISSING_SET_NUMBER"},yL={message:"Missing sideNumber",code:"ERR_MISSING_SIDE_NUMBER"},wi={message:"Missing courtId",code:"ERR_MISSING_COURT_ID"},st={message:"Missing value",code:"ERR_MISSING_VALUE"},nE={message:"Missing birthdate",code:"ERR_MISSING_BIRTH_DATE"},oE={message:"Missing date",code:"ERR_MISSING_DATE"},iE={message:"No valid dates",code:"ERR_NO_VALID_DATES"},Pm={message:"Invalid bookings",code:"ERR_INVALID_BOOKINGS"},Ql={message:"Invalid dateAvailability",code:"ERR_INVALID_DATE_AVAILABILITY"},sE={message:"Missing dateAvailability",code:"ERR_MISSING_DATE_AVAILABILITY"},je={message:"Invalid Date",code:"ERR_INVALID_DATE"},Po={message:"Invalid time",code:"ERR_INVALID_TIME"},aE={message:"Invalid tournament dates",code:"ERR_INVALID_DATES_TOURNAMENT"};var WI={message:"Invalid game scores",code:"ERR_INVALID_SCORES_GAME"},cE={message:"Invalid score",code:"ERR_INVALID_SCORE"},Dm={message:"Invalid winningSide",code:"ERR_INVALID_WINNING_SIDE"};var DC={message:"No participants generated",code:"ERR_NO_PARTICIPANTS_GENERATED"},Xl={message:"Cannot modify tieFormat",code:"ERR_UNCHANGED_CANNOT_MODIFY_TIEFORMAT"},uE={message:"Cannot modify participantType",code:"ERR_UNCHANGED_CANNOT_MODIFY_PARTICIPANT_TYPE"},Ju={message:"Cannot remove participants",code:"ERR_UNCHANGED_CANNOT_REMOVE_PARTICIPANTS"},jI={message:"Participant category mismatch",code:"ERR_CATEGORY_MISMATCH"},Nm={message:"Cannot change winningSide",code:"ERR_UNCHANGED_CANNOT_CHANGE_WINNING_SIDE"},Li={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"},pE={message:"Invalid participantRole",code:"ERR_INVALID_PARTICIPANT_ROLE"},An={message:"Invalid participantType",code:"ERR_INVALID_PARTICIPANT_TYPE"},mE={message:"Missing participantRole",code:"ERR_MISSING_PARTICIPANT_ROLE"},Fi={message:"Missing participant",code:"ERR_MISSING_PARTICIPANT"},Ka={message:"Missing participants",code:"ERR_MISSING_PARTICIPANTS"},ie={message:"Missing participantId",code:"ERR_MISSING_PARTICIPANT_ID"},dE={message:"Missing qualified participants",code:"ERR_MISSING_QUALIFIED_PARTICIPANTS"},re={message:"Participant Not Found",code:"ERR_NOT_FOUND_PARTICIPANT"},lE={message:"participantId exists",code:"ERR_EXISTING_PARTICIPANT_ID"},AL={message:"participant pair exists",code:"ERR_EXISTING_PARTICIPANT_PAIR"},fE={message:"No participant removed",code:"ERR_UNCHANGED_NO_PARTICIPANT_REMOVED"},Do={message:"Missing participantIds",code:"ERR_MISSING_PARTICIPANT_IDS"},gE={message:"Missing participantsCount",code:"ERR_MISSING_PARTICIPANT_COUNT"},IE={message:"Participant not checked in",code:"ERR_UNCHANGED_PARTICIPANT_NOT_CHECKED_IN"},hE={message:"Missing person details",code:"ERR_MISSING_PERSON_DETAILS"},Os={message:"Existing participant drawPosition assignment",code:"ERR_EXISTING_PARTICIPANT_DRAW_POSITION_ASSIGNMENT"},Zu={message:"Existing participant",code:"ERR_EXISTING_PARTICIPANT"},Jl={message:"participantsCount exceeds drawSize",code:"ERR_INVALID_PARTICIPANT_COUNT"},Zl={message:"Invalid entry status",code:"ERR_INVALID_ENTRY_STATUS"},YI={message:"Participant Entry Not Found",code:"ERR_NOT_FOUND_PARTICIPANT_ENTRY"},NC={message:"Participant not entered in stage",code:"ERR_UNCHANGED_PARTICIPANT_NOT_ENTERED"},MC={message:"Participant not found in stageSequence",code:"ERR_NOT_FOUND_PARTICIPANT_IN_STAGE"},SE={message:"entryStatus not allowed in stage",code:"ERR_INVALID_ENTRY_STATUS_IN_STAGE"},TE={message:"entryStatus not allowed for event",code:"ERR_INVALID_ENTRY_STATUS_IN_EVENT"},qI={message:"No stage space available for entryStatus",code:"ERR_UNCHANGED_NO_AVAILABLE_STAGE_SPACE"},tf={message:"Insufficient drawPositions to accommodate qualifiers",code:"ERR_UNCHANGED_NO_DRAW_POSITIONS_FOR_QUALIFIERS"},ef={message:"Insufficient drawPositions to accommodate entries",code:"ERR_INSUFFICIENT_DRAW_POSITIONS"},yE={message:"Missing penaltyType",code:"ERR_MISSING_PENALTY_TYPE"},rf={message:"Missing penaltyId",code:"ERR_MISSING_PENALTY_ID"},Vc={message:"Penalty not found",code:"ERR_NOT_FOUND_PENALTY"},AE={message:"Missing courtsCount/courtNames",code:"ERR_MISSING_COURTS_INFO"},_s={message:"Court not found",code:"ERR_NOT_FOUND_COURT"},EE={message:"Court exists",code:"ERR_EXISTING_COURT"},UE={message:"Venue exists",code:"ERR_EXISTING_VENUE"},ki={message:"Venue not found",code:"ERR_NOT_FOUND_VENUE"},ti={message:"Missing venueId",code:"ERR_MISSING_VENUE_ID"},PE={message:"Invalid endTime",code:"ERR_INVALID_END_TIME"},$I={message:"Existing endTime",code:"ERR_EXISTING_END_TIME"},DE={message:"Invalid stopTime",code:"ERR_INVALID_STOP_TIME"},NE={message:"Invalid startTime",code:"ERR_INVALID_START_TIME"},RC={message:"Invalid resumeTime",code:"ERR_INVALID_RESUME_TIME"},nf={message:"Invalid timeItem",code:"ERR_INVALID_TIME_ITEMS"},ME={message:"Missing async state provider",code:"ERR_MISSING_ASYNC_STATE_PROVIDER"},of={message:"Missing timeItem",code:"ERR_MISSING_TIME_ITEM"},sf={message:"Missing timeItems",code:"ERR_MISSING_TIME_ITEMS"},Bc={message:"Missing context",code:"ERR_MISSING_CONTEXT"},RE={message:"Missing schedule",code:"ERR_MISSING_SCHEDULE"},za={message:"Invalid scaleItem",code:"ERR_INVALID_SCALE_ITEM"},CE={message:"Modifications failed",code:"ERR_FAILURE_MODIFICATIONS"},xs={message:"No modifications applied",code:"ERR_UNCHANGED_NO_MODIFICATIONS_APPLIED"},bE={message:"Unable to assign court",code:"ERR_UNCHANGED_COURT_NOT_ASSIGNED"},tp={message:"No Candidates",code:"ERR_UNCHANGED_NO_CANDIDATES"},vE={message:"Invalid configuration",code:"ERR_INVALID_CONFIG"},OE={message:"Invalid collectionDefinition",code:"ERR_INVALID_COLLECTION_DEFINITION"},Io={message:"Invalid object",code:"ERR_INVALID_OBJECT"},ep={message:"Invalid gender",code:"ERR_INVALID_GENDER"},Hc={message:"Invalid category",code:"ERR_INVALID_CATEGORY"},V={message:"Invalid values",code:"ERR_INVALID_VALUES"},_E={message:"Duplicate value",code:"ERR_DUPLICATE_VALUE"},af={message:"Team not found",code:"ERR_NOT_FOUND_TEAM"},xE={message:"No valid actions",code:"ERR_NO_VALID_ACTIONS"},rp={message:"No valid attributes",code:"ERR_NO_VALID_ATTRIBUTES"},cf={message:"Value unchanged",code:"ABORT_UNCHANGED"},ve={message:"Not found",code:"ERR_NOT_FOUND"},np={message:"Not implemented",code:"ERR_NOT_IMPLEMENTED"},wE={message:"Existing flight",code:"ERR_EXISTING_FLIGHT"},uf={message:"Existing flight profile",code:"ERR_EXISTING_FLIGHT_PROFILE"},LE={message:"Existing outcome",code:"ERR_EXISTING_OUTCOME"},FE={message:"Existing matchUpId",code:"ERR_EXISTING_MATCHUP_ID"},KI={message:"Existing stage",code:"ERR_EXISTING_STAGE"},pf={message:"Existing structure",code:"ERR_EXISTING_STRUCTURE"},Qa={message:"Method not found",code:"ERR_NOT_FOUND_METHOD"},kE={message:"Scheduled matchUps",code:"ERR_SCHEDULED_MATCHUPS"},Xa={message:"Scores present",code:"ERR_SCORES_PRESENT"},CC={ANACHRONISM:wI,CANNOT_CHANGE_WINNING_SIDE:Nm,CANNOT_MODIFY_TIEFORMAT:Xl,CANNOT_MODIFY_PARTICIPANT_TYPE:uE,CANNOT_REMOVE_MAIN_STRUCTURE:_A,CANNOT_REMOVE_PARTICIPANTS:Ju,CATEGORY_MISMATCH:jI,COURT_EXISTS:EE,COURT_NOT_FOUND:_s,DRAW_DEFINITION_NOT_FOUND:Cr,DRAW_ID_EXISTS:FA,DRAW_POSITION_ACTIVE:zu,DRAW_POSITION_ASSIGNED:ja,DRAW_POSITION_NOT_CLEARED:LA,DRAW_POSITION_NOT_FOUND:lL,DRAW_SIZE_MISMATCH:FI,DUPLICATE_ENTRY:Em,DUPLICATE_VALUE:_E,ENTRY_STATUS_NOT_ALLOWED_FOR_EVENT:TE,ENTRY_STATUS_NOT_ALLOWED_IN_STAGE:SE,EVENT_EXISTS:$A,EVENT_NOT_FOUND:jr,EXISTING_DRAW_DEFINITIONS:xA,EXISTING_END_TIME:$I,EXISTING_FLIGHT:wE,EXISTING_MATCHUP_ID:FE,EXISTING_OUTCOME:LE,EXISTING_PARTICIPANT_DRAW_POSITION_ASSIGNMENT:Os,EXISTING_PARTICIPANT:Zu,EXISTING_POLICY_TYPE:HI,EXISTING_PROFILE:uf,EXISTING_ROUND:YA,EXISTING_STAGE:KI,EXISTING_STRUCTURE:pf,INCOMPATIBLE_MATCHUP_STATUS:Yl,INCOMPLETE_SOURCE_STRUCTURE:kl,INSUFFICIENT_DRAW_POSITIONS:ef,INVALID_ACTION:BA,INVALID_ASSIGNMENT:kI,INVALID_BOOKINGS:Pm,INVALID_CATEGORY:Hc,INVALID_COLLECTION_DEFINITION:OE,INVALID_CONFIGURATION:vE,INVALID_DATE_AVAILABILITY:Ql,INVALID_DATE:je,INVALID_DRAW_DEFINITION:ma,INVALID_DRAW_POSITION_FOR_SEEDING:Gl,INVALID_DRAW_POSITION:Cs,INVALID_DRAW_SIZE:Qu,INVALID_END_TIME:PE,INVALID_ENTRIES:zA,INVALID_EVENT_TYPE:jn,INVALID_GAME_SCORES:WI,INVALID_GENDER:ep,INVALID_MATCHUP_FORMAT:ql,INVALID_MATCHUP_STATUS:da,INVALID_MATCHUP_STATUS_BYE:ZA,INVALID_MATCHUP:lr,INVALID_OBJECT:Io,INVALID_PARTICIPANT_ID:mn,INVALID_PARTICIPANT_IDS:wr,INVALID_PARTICIPANT_ROLE:pE,INVALID_PARTICIPANT_SEEDING:kA,INVALID_PARTICIPANT_TYPE:An,INVALID_PARTICIPANT:Li,INVALID_POLICY_DEFINITION:rE,INVALID_RECORDS:LI,INVALID_SCALE_ITEM:za,INVALID_SEED_NUMBER:WA,INVALID_SEED_POSITION:jA,INVALID_SET_NUMBER:SL,INVALID_SIDE_NUMBER:Kl,INVALID_SCORE:cE,INVALID_STAGE:xi,INVALID_START_TIME:NE,INVALID_STRUCTURE:Zo,INVALID_STOP_TIME:DE,INVALID_TIE_FORMAT:ko,INVALID_TIME:Po,INVALID_TIME_ITEM:nf,INVALID_TOURNAMENT_DATES:aE,INVALID_TOURNAMENT_RECORD:Wa,INVALID_VALUES:V,INVALID_WINNING_SIDE:Dm,MATCHUP_NOT_FOUND:Le,METHOD_NOT_FOUND:Qa,MISSING_ASSIGNMENTS:jl,MISSING_ASYNC_STATE_PROVIDER:ME,MISSING_AVOIDANCE_POLICY:eE,MISSING_BIRTH_DATE:nE,MISSING_COLLECTION_DEFINITION:tE,MISSING_COURT_ID:wi,MISSING_COURTS_INFO:AE,MISSING_DATE_AVAILABILITY:sE,MISSING_DATE:oE,MISSING_DRAW_DEFINITION:Z,MISSING_DRAW_ID:sn,MISSING_DRAW_POSITION:bs,MISSING_DRAW_POSITIONS:Ya,MISSING_DRAW_SIZE:qa,MISSING_ENTRIES:KA,MISSING_EVENT:Ot,MISSING_QUALIFIED_PARTICIPANTS:dE,MISSING_MATCHUP_FORMAT:$l,MISSING_MATCHUP_ID:cr,MISSING_MATCHUP_IDS:ns,MISSING_MATCHUP:Tr,MISSING_MATCHUPS:eo,MISSING_PARTICIPANT_COUNT:gE,MISSING_PARTICIPANT_ID:ie,MISSING_PARTICIPANT_IDS:Do,MISSING_PARTICIPANT_ROLE:mE,MISSING_PARTICIPANT:Fi,MISSING_PARTICIPANTS:Ka,MISSING_PENALTY_ID:rf,MISSING_PENALTY_TYPE:yE,MISSING_PERSON_DETAILS:hE,MISSING_POLICY_ATTRIBUTES:BI,MISSING_POLICY_DEFINITION:Xu,MISSING_POLICY_TYPE:VI,MISSING_POSITION_ASSIGNMENTS:JA,MISSING_ROUND_NUMBER:fL,MISSING_SCHEDULE:RE,MISSING_SCORING_POLICY:hL,MISSING_SEED_ASSIGNMENTS:HA,MISSING_SEEDCOUNT_THRESHOLDS:VA,MISSING_SEEDING_POLICY:gL,MISSING_SET_NUMBER:TL,MISSING_SET_OBJECT:zl,MISSING_SIDE_NUMBER:yL,MISSING_STAGE:QA,MISSING_STRUCTURE_ID:Ur,MISSING_STRUCTURE:di,MISSING_MAIN_STRUCTURE:Wl,MISSING_STRUCTURES:Hl,MISSING_TARGET_LINK:Bl,MISSING_TIE_FORMAT:vs,MISSING_TIME_ITEM:of,MISSING_TIME_ITEMS:sf,MISSING_TOURNAMENT_ID:pa,MISSING_TOURNAMENT_RECORD:$,MISSING_TOURNAMENT_RECORDS:Lt,MISSING_VALUE:st,MISSING_VENUE_ID:ti,MODIFICATIONS_FAILED:CE,NO_CANDIDATES:tp,NO_DRAW_POSITIONS_AVAILABLE_FOR_QUALIFIERS:tf,NO_MODIFICATIONS_APPLIED:xs,NO_STAGE_SPACE_AVAILABLE_FOR_ENTRY_STATUS:qI,NO_PARTICIPANT_REMOVED:fE,NO_VALID_ACTIONS:xE,NO_VALID_ATTRIBUTES:rp,NO_VALID_DATES:iE,NOT_FOUND:ve,NOT_IMPLEMENTED:np,PARTICIPANT_COUNT_EXCEEDS_DRAW_SIZE:Jl,PARTICIPANT_ID_EXISTS:lE,PARTICIPANT_NOT_CHECKED_IN:IE,PARTICIPANT_NOT_FOUND:re,PARTICIPANT_PAIR_EXISTS:AL,PENALTY_NOT_FOUND:Vc,POLICY_NOT_ATTACHED:IL,POLICY_NOT_FOUND:Gc,SCHEDULE_NOT_CLEARED:wA,SCHEDULED_MATCHUPS:kE,SCORES_PRESENT:Xa,SEEDSCOUNT_GREATER_THAN_DRAW_SIZE:GA,STAGE_SEQUENCE_LIMIT:XA,STRUCTURE_NOT_FOUND:wt,TEAM_NOT_FOUND:af,UNABLE_TO_ASSIGN_COURT:bE,UNLINKED_STRUCTURES:qA,UNRECOGNIZED_DRAW_TYPE:Vl,UNRECOGNIZED_MATCHUP_FORMAT:$a,UNRECOGNIZED_MATCHUP_STATUS:GI,VALUE_UNCHANGED:cf,VENUE_EXISTS:UE};var tr={disableNotifications:!1,tournamentId:void 0,tournamentRecords:{},subscriptions:{},modified:!1,methods:{},notices:[]},GE={addNotice:_L,callListener:kL,cycleMutationStatus:OL,deleteNotice:LL,deleteNotices:wL,disableNotifications:EL,enableNotifications:UL,getMethods:op,getNotices:xL,getTopics:FL,getTournamentId:bC,getTournamentRecord:PL,getTournamentRecords:DL,removeTournamentRecord:CL,setMethods:vL,setSubscriptions:bL,setTournamentId:ML,setTournamentRecord:NL,setTournamentRecords:RL,handleCaughtError:GL};function EL(){tr.disableNotifications=!0}function UL(){tr.disableNotifications=!1}function bC(){return tr.tournamentId}function PL(t){return tr.tournamentRecords[t]}function DL(){return tr.tournamentRecords}function NL(t){let e=t?.tournamentId;return e?(tr.tournamentRecords[e]=t,{success:!0}):{error:Wa}}function ML(t){return t?tr.tournamentRecords[t]?(tr.tournamentId=t,{success:!0}):{error:$}:(tr.tournamentId=void 0,{success:!0})}function RL(t){tr.tournamentRecords=t;let e=Object.keys(t);e.length===1?tr.tournamentId=e[0]:e.length||(tr.tournamentId=void 0)}function CL(t){if(typeof t!="string")return{error:V};if(!tr.tournamentRecords[t])return{error:ve};delete tr.tournamentRecords[t];let e=Object.keys(tr.tournamentRecords);return e.length===1?tr.tournamentId=e[0]:e.length||(tr.tournamentId=void 0),{success:!0}}function bL(t){return typeof t.subscriptions!="object"?{error:V}:(Object.keys(t.subscriptions).forEach(e=>{typeof t.subscriptions[e]=="function"?tr.subscriptions[e]=t.subscriptions[e]:delete tr.subscriptions[e]}),{...C})}function vL(t){return typeof t!="object"?{error:V}:(Object.keys(t).forEach(e=>{typeof t[e]=="function"&&(tr.methods[e]=t[e])}),{...C})}function OL(){let t=tr.modified;return tr.modified=!1,t}function _L({topic:t,payload:e,key:r},n){if(!(typeof t!="string"||typeof e!="object")&&(tr.disableNotifications||(tr.modified=!0),!(tr.disableNotifications||!tr.subscriptions[t]&&!n)))return r&&(tr.notices=tr.notices.filter(o=>!(o.topic===t&&o.key===r))),tr.notices.push({topic:t,payload:e,key:r}),{...C}}function op(){return tr.methods??{}}function xL({topic:t}){return tr.notices.filter(e=>e.topic===t).map(e=>e.payload)}function wL(){tr.notices=[]}function LL({topic:t,key:e}){tr.notices=tr.notices.filter(r=>(!t||r.topic===t)&&r.key!==e)}function FL(){return{topics:Object.keys(tr.subscriptions)}}function kL({topic:t,notices:e},r){let n=tr.subscriptions[t];n&&typeof n=="function"&&n(e);let o=r?.[t];o&&typeof o=="function"&&o(e)}function GL({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:bC(),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},an=GE,vC=["addNotice","callListener","cycleMutationStatus","deleteNotice","deleteNotices","disableNotifications","enableNotifications","getMethods","getNotices","getTopics","getTournamentId","getTournamentRecord","getTournamentRecords","removeTournamentRecord","setSubscriptions","setTournamentId","setTournamentRecord","setTournamentRecords"];function VL(t){if(typeof t!="object")throw new Error("Global state provider can not be undefined or null");if(jt(Object.keys(t),vC).length!==vC.length)throw new Error("Global state provider is missing required methods");return an=t,{success:!0}}function VE(){if(an.createInstanceState){try{an.createInstanceState()}catch(t){return{error:t}}return{success:!0}}else return{error:ME}}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 BL(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 OC(t){Wr(t)?Oe.globalLog=t:delete Oe.globalLog}function Wc(t){Oe.devContext=t}function BE(){an.disableNotifications()}function mf(){an.enableNotifications()}function jc(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 df(){return{enabled:Oe.deepCopy,...Oe.deepCopyAttributes}}function HL(t){return t?.subscriptions?(Object.keys(t.subscriptions).forEach(e=>{Oe.globalSubscriptions[e]=t.subscriptions[e]}),{...C}):{error:st,info:"missing subscriptions"}}function WL(t){return t?.subscriptions?an.setSubscriptions({subscriptions:t.subscriptions}):{error:st,info:"missing subscriptions"}}function _C(t){return t?typeof t!="object"?{error:V}:(Object.keys(t).forEach(e=>{Wr(t[e])&&(Oe.globalMethods[e]=t[e])}),{...C}):{error:st,info:"missing method declarations"}}function xC(t){return t?typeof t!="object"?{error:V}:an.setMethods(t):{error:st,info:"missing method declarations"}}function lf(){return an.cycleMutationStatus()}function lt(t){if(typeof t?.topic!="string")return;let e=Oe.globalSubscriptions[t.topic];return an.addNotice(t,e)}function ff(){return{...Oe.globalMethods,...an.getMethods()}}function zI(t){return an.getNotices(t)}function QI({key:t,topic:e}){return an.deleteNotice({key:t,topic:e})}function Gi(){return an.deleteNotices()}function Lr(){return an.getTopics()}function ip(t){return Lr()?.topics?.includes(t)}async function Mm(t){return an.callListener(t,Oe.globalSubscriptions)}function os(){return an.getTournamentId()}function gf(t){return an.getTournamentRecord(t)}function Go(){return an.getTournamentRecords()}function HE(t){return an.setTournamentRecord(t)}function Rm(t){return an.setTournamentRecords(t)}function sp(t){return an.setTournamentId(t)}function WE(t){return an.removeTournamentRecord(t)}function XI(){return an}function ap({engineName:t,methodName:e,params:r,err:n}){let o=Wr(an.handleCaughtError)&&an.handleCaughtError||GE.handleCaughtError,{tournamentRecord:i,...s}=r;return o({params:s,engineName:t,methodName:e,err:n})}function jE(t,e){if(Oe.globalLog)try{Oe.globalLog({log:t,engine:e})}catch(r){console.log("globalLog error",r),console.log(e,t),OC()}else console.log(e,t)}function YE(t,e,r,n){if(!ht(t))return{error:V};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?_C(i):xC(i),{methods:i}}function jL(t,e,r){return Object.keys(t).filter(n=>!e.includes(t[n])&&(!r||(Array.isArray(t[n])?t[n].length:!0)))}function nt(t,e,r,n){if(typeof t!="object"||t===null)return t;df()?.enabled||(n=!0);let i=["",void 0,null];e&&i.push(!1);let s=jL(t,i,r);return Object.assign({},...s.map(a=>Array.isArray(t[a])?{[a]:n?t[a]:t[a].map(c=>nt(c))}:{[a]:n?t[a]:nt(t[a])}))}function _({context:t,result:e,stack:r,info:n}){return e&&!Array.isArray(e?.stack)&&(e.stack=[]),e&&Array.isArray(e?.stack)&&typeof r=="string"&&e.stack.push(r),e&&n&&(e.info=n),e&&typeof t=="object"&&Object.keys(t).length&&Object.assign(e,nt(t)),e&&!e?.error&&!e?.success&&Object.assign(e,{...C}),e??{success:!0}}var Pn="ANY",zt="MALE",Ar="MIXED",is="OTHER",oe="FEMALE",Cm={ANY:Pn,MALE:zt,FEMALE:oe,MIXED:Ar,OTHER:is};var YL="MIXED events can not contain mixed singles or { gender: ANY } collections",qL="events with { gender: ANY } can not contain MIXED singles collections";function bm(t){let e="tieFormatGenderValidityCheck",{referenceGender:r,matchUpType:n,gender:o}=t;return r&&o&&[zt,oe].includes(r)&&r!==o?_({result:{valid:!1,error:ep},context:{gender:o},stack:e}):r===Ar&&(o===Pn||o===Ar&&n!==xt)?_({result:{error:ep,valid:!1},info:YL,stack:e}):r===Pn&&o===Ar&&n!==xt?_({result:{error:ep,valid:!1},info:qL,stack:e}):{valid:!0}}var $L="normal",qE="timed",KL="final",If="NOAD",vm="SET",LC={S:$L,F:KL};function cp(t,e){if(ht(t),(t?.bestOf||t?.exactly)&&t?.setFormat)return zL(t,e)}function hf(t){return!isNaN(Number(t))&&Number(t)}function GC(t){let e=`T${t.minutes}`;return t.based&&(e+=t.based),t.modifier&&(e+=`@${t.modifier}`),e}function zL(t,e){let r=hf(t.bestOf)||void 0,n=hf(t.exactly)||void 0,o=r||n;if(t.setFormat?.timed&&t.simplified&&o===1)return GC(t.setFormat);let i=o&&`${vm}${o}`||"",s=FC(t.setFormat,e),a=s&&`S:${s}`||"",c=FC(t.finalSetFormat,e),u=o&&o>1&&c&&s!==c&&`F:${c}`||"";if(i&&s)return[i,a,u].filter(m=>m).join("-")}function FC(t,e){if(typeof t=="object"&&Object.keys(t).length){if(t.timed)return GC(t);if(t.tiebreakSet)return kC(t.tiebreakSet);let r=hf(t.setTo);if(r){let n=t.NoAD&&If||"",o=kC(t.tiebreakFormat),i=o&&`/${o}`||"",s=hf(t.tiebreakAt),a=s&&(s!==r||e)&&`@${s}`||"";if(o!==!1)return`${r}${n}${i}${a}`}}}function kC(t){if(t){if(typeof t=="object"&&!t.tiebreakTo)return"";if(typeof t=="object"&&hf(t.tiebreakTo)){let e=`TB${t.tiebreakTo}${t.NoAD?If:""}`;return t.modifier&&(e+=`@${t.modifier}`),e}else return!1}}function Ye(t){if(Vt(t)){let e=t.startsWith("T")&&qE||t.startsWith(vm)&&vm||"";if(e===qE){let r=WC(t),n={simplified:!0,setFormat:r,bestOf:1};if(r)return n}if(e===vm)return QL(t)}}function QL(t){let e=t.split("-"),r=Sf(e[0].slice(3)),n=r===1||r%2!==0?r:void 0,o=r!==1&&r%2===0?r:void 0,i=e&&VC(e[1]),s=e&&VC(e[2]),a=i&&i.timed||s&&s.timed,c=n&&n<6||a&&o,u=!e[2]||s,p=i,m=nt({setFormat:i,exactly:o,bestOf:n});if(s&&(m.finalSetFormat=s),c&&p&&u)return m}function VC(t){if(t?.[1]===":"){let e=t.split(":"),r=LC[e[0]],n=e[1];if(r&&n){if(n.startsWith("TB")){let I=BC(n);return I===!1?!1:typeof I=="object"?{tiebreakSet:I}:void 0}if(n.startsWith("T"))return WC(n);let s=t.match(/^[FS]:(\d+)([A-Za-z]*)/),a=s&&jC(s[2])||!1,c=!s?.[2]||a,u=s?Sf(s[1]):void 0,p=HC(n),m=p!==!1,d=m&&p||u,l=BC(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 HC(t,e=!0){let r=t?.indexOf("@")>0&&t.split("@");if(r)return(e?Sf(r[1]):r[1])||!1}function BC(t){if(t)if(t.startsWith("TB")){let e=HC(t,!1),r=t.match(/^TB(\d+)([A-Za-z]*)/),n=r?.[1],o=r&&jC(r[2]),i=!r?.[2]||o,s=Sf(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 WC(t){let e=t.slice(1),r=e.match(/^(\d+)(@?[A-Za-z]*)/),n=Sf(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 jC(t){return t&&t.indexOf(If)>=0}function Sf(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(\d{1,2})@?([1-9]?)*/),n=r?.[1],o=r?.[2],i=r?.[3],s=t.match(/-F:([1-9])+\/TB(\d{1,2})@?([1-9]?)*/),a=s?.[1],c=s?.[2],u=s?.[3];return cp(e,!!(r&&o&&n===i||s&&c&&a===u))===t}var Om=/^[\d]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][\d]|3[0-1])$/,JI=/^((0[\d]|1[\d]|2[0-3]):[0-5][\d](:[0-5][\d])?)([.,][0-9]{3})?$/,No=/^([\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?$/,ws=/^([\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 _m(t){let{scheduledDate:e}=t;if(!e&&t.scheduledTime&&(e=Pt(t.scheduledTime)),!e)return;let r=Qt(t.scheduledTime),n=Pt(e);return n&&r&&(n+=`T${r}`),n}function YC(t){return typeof t!="object"||Array.isArray(t)?!1:Object.prototype.toString.call(t)==="[object Date]"}function Yc(t){let e=typeof t=="string"?t?.split(" "):[];return t&&e?.length>1&&!["AM","PM"].includes(e[1].toUpperCase())?!1:!!(!t||ws.test(Za(t,!0,!0)))}function Nr(t){return Ja(t)||Om.test(t)}function XL(t){let e=new Date(t),r=e.getSeconds()+60*e.getMinutes()+60*60*e.getHours();return JL(r,{displaySeconds:!1})}function JL(t,e){let r=parseInt(t,10),n=Math.floor(r/3600),o=Math.floor((r-n*3600)/60),i=r-n*3600-o*60;return(!e||e?.displaySeconds?n+":"+o+":"+i:n+":"+o).split(":").map(ro).join(":")}var Af=t=>{let e=Tf(t)||Ja(t)?new Date(t):new Date,r=e.getUTCMonth()+1,n=r<10?`0${r}`:`${r}`;return`${e.getUTCFullYear()}-${ro(n)}-${ro(e.getUTCDate())}`};function ZL(t){let e=Tf(t)||Ja(t)?new Date(t):new Date;return Date.UTC(e.getFullYear(),e.getMonth(),e.getDate())}function Yn(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 ZI(t){let e=t?new Date(t):new Date,r=e.getTimezoneOffset();return new Date(e.getTime()-r*60*1e3)}function tF(t){return ZI(t).getTime()}function Tf(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 Ls(t,e){if(!Nr(t)||!Nr(e))return[];let r=Pt(t)+"T00:00",n=Pt(e)+"T00:00",o=new Date(r),i=new Date(n),s=Tf(i)&&Tf(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=>Yn(p));function u(p,m){return p<=m}}var eF=/^([+-]?\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 Ja(t){return typeof t!="string"?!1:eF.test(t)}function eh(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 Yt(t){let e=Qt(t);if(!e)return 0;let[r,n]=e.split(":").map(o=>parseInt(o));return r*60+n}function qC(t){let e=Math.floor(t/60),r=t-e*60;return e>23&&(e=e%24),[ro(e),ro(r)].join(":")}function yf(t){return eh(t)?t.split(":").slice(0,2).map(ro).join(":"):void 0}function Qt(t){return Ja(t)&&t.indexOf("T")>0?yf(t.split("T").reverse()[0]):yf(t)}function Pt(t){return Ja(t)||No.test(t)?t.split("T")[0]:void 0}function up(t,e){let r=new Date(t);return r.setDate(r.getDate()+e),Pt(r.toISOString())}function th(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 rF(t){let e=th(t);return e.ampm&&e.hours&&(e.ampm.toLowerCase()==="pm"&&parseInt(e.hours)<12&&(e.hours=(e.hours&&parseInt(e.hours)||0)+12),e.ampm.toLowerCase()==="am"&&e.hours==="12"&&(e.hours="00")),`${e.hours||"12"}:${e.minutes||"00"}`.split(":").map(ro).join(":")}function nF(t){let e=th(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 Za(t,e,r){let n=Pt(t),o=Qt(t),i=n?o:t;return t?e&&(n&&r&&t||rF(i))||nF(i):void 0}function rh(t,e){let r=th(t),n=th(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 nh(t,e=7){let r=Pt(t)+"T00:00",n=new Date(r),o=new Date(n.setDate(n.getDate()+e));return Yn(o)}function oF(t){return nh(t)}function iF(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())),Yn(o,r)}function $C(t,e,r){let n=new Date(t,0);return Yn(new Date(n.setDate(e)),r)}function Ge(t,e=void 0){let[r,n]=(t||"00:00").split(":").map(ro),o=ZI(e).setHours(r,n,0,0);return ZI(o)}function la(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=Qt(t);if(!r)return"00:00";let n=isNaN(e)?0:e;return Qt(Ef(Ge(r),n).toISOString())}function Ef(t,e){let r=new Date(t);return new Date(r.getTime()+e*6e4)}function ro(t){return t.toString()[1]?t:"0"+t}function qn(t,e){let r=new Date(t),n=new Date(e);return r.getFullYear()===n.getFullYear()&&r.getMonth()===n.getMonth()&&r.getDate()===n.getDate()}var oh={addDays:nh,addWeek:oF,addMinutesToTimeString:Yr,convertTime:Za,getIsoDateString:_m,getUTCdateString:Af,DateHHMM:XL,extractDate:Pt,extractTime:Qt,formatDate:Yn,getDateByWeek:iF,isISODateString:Ja,isDate:Tf,isTimeString:eh,offsetDate:ZI,offsetTime:tF,sameDay:qn,timeStringMinutes:Yt,timeToDate:Ge,timeUTC:ZL,validTimeValue:Yc,validDateString:Om,timeValidation:ws,dateValidation:No};var sF=(t,e)=>t.filter(Boolean).every(r=>typeof r===e),aF=t=>t.filter(Boolean).every(Zt);function Fs(t){let e=t.category;if(typeof e!="object")return{error:Hc};let{ageCategoryCode:r,ageMaxDate:n,ageMinDate:o,ageMax:i,ageMin:s}=e,a=e.categoryName,c;if(!(sF([r,n,o,a],"string")&&aF([i,s])&&[n,o].filter(Boolean).every(Nr)))return{error:Hc};let p=t.consideredDate??Pt(new Date().toLocaleDateString("sv"));if(!Nr(p))return{error:je};let[m]=p.split("-").slice(0,3).map(G=>parseInt(G)),d=up(p,-1),[l,f]=d.split("-").slice(1,3).map(G=>parseInt(G)),g=`${ro(l)}-${ro(f)}`,I=up(p,1),[h,S]=I.split("-").slice(1,3).map(G=>parseInt(G)),T=`${ro(h)}-${ro(S)}`,y=s&&up(p,-1*365*s),E=i&&up(p,-1*365*i),P=[],A=G=>!P.includes(G)&&P.push(G);r=r??a;let U=/^([UO]?)(\d{1,2})([UO]?)$/,N=/^C(\d{1,2})-(\d{1,2})$/,D=r?.includes("-"),M=D&&r?.match(N),R=r?.match(U),b=(G,k)=>`${G}-${k}`,v=G=>{let k=m-G,H=b(k,T);e.ageMinDate&&e.ageMinDate!==H&&A(`Invalid submitted ageMinDate: ${o}`),o=H,r&&(e.ageMax&&e.ageMax!==G-1&&(A(`Invalid submitted ageMax: ${i}`),E=void 0),i=G-1)},O=G=>{let k=m-G-1,H=b(k,T);e.ageMin&&e.ageMin>G&&A(`Invalid submitted ageMin: ${s}`),e.ageMax&&e.ageMax>G&&A(`Invalid submitted ageMax: ${i}`),e.ageMinDate&&e.ageMinDate!==H&&A(`Invalid submitted ageMinDate: ${o}`),o=H,r&&(e.ageMax&&e.ageMax!==G&&(A(`Invalid submitted ageMax: ${i}`),y=void 0),i=G)},x=G=>{let k=m-G,H=b(k,g);e.ageMaxDate&&e.ageMaxDate!==H&&A(`Invalid submitted ageMaxDate: ${n}`),n=H,r&&(e.ageMin&&e.ageMin!==G+1&&(A(`Invalid submitted ageMin: ${s}`),y=void 0),s=G+1)},F=G=>{let k=m-G-1,H=b(k,g);e.ageMaxDate&&e.ageMaxDate!==H&&A(`Invalid submitted ageMaxDate: ${n}`),n=H,r&&(e.ageMin&&e.ageMin!==G&&(A(`Invalid submitted ageMin: ${s}`),y=void 0),s=G)},w=G=>{let[k,H,W]=(G.match(U)||[]).slice(1),q=parseInt(H);k==="U"?(e.ageMaxDate&&e.ageMaxDate!==n&&A(`Invalid submitted ageMaxDate: ${e.ageMaxDate}`),v(q)):k==="O"&&x(q),W==="U"?(e.ageMaxDate&&e.ageMaxDate!==n&&A(`Invalid submitted ageMaxDate: ${e.ageMaxDate}`),O(q)):W==="O"&&F(q),n=n??y,o=o??E};if(M){if(n=void 0,o=void 0,i=void 0,s=void 0,e.ageMin){let H=m-e.ageMin;n=b(H,g)}if(e.ageMax){let H=m-e.ageMax-1;o=b(H,T)}let[G,k]=(r?.match(N)??[]).slice(1).map(H=>parseInt(H));G<=k?(s=G,i=k,c=!0):A(`Invalid combined age range ${r}`)}else D?r?.split("-").forEach(w):R?w(r):(s&&x(s),i&&O(i));i&&e.ageMin&&e.ageMin>i&&(A(`Invalid submitted ageMin: ${e.ageMin}`),s=void 0);let L=nt({consideredDate:p,combinedAge:c,ageMaxDate:n,ageMinDate:o,ageMax:i,ageMin:s});return P.length&&(L.errors=P),L}function qc({category:t}){if(!ht(t))return{error:V};let e=Fs({category:t});if(e.error)return{error:e};let{ratingMax:r,ratingMin:n}=t;return r&&!Zt(r)?_({result:{error:V},context:{ratingMax:r}}):n&&!Zt(n)?_({result:{error:V},context:{ratingMin:n}}):{...e}}function $c({childCategory:t,withDetails:e,category:r}){let n=qc({category:r}),o=qc({category:t}),i=o.ageMin&&(n.ageMin&&o.ageMin<n.ageMin||n.ageMax&&o.ageMin>n.ageMax),s=o.ageMax&&(n.ageMax&&o.ageMax>n.ageMax||n.ageMin&&o.ageMax<n.ageMin),a=o.ageMinDate&&n.ageMaxDate&&new Date(o.ageMinDate)>new Date(n.ageMaxDate),c=o.ageMaxDate&&n.ageMinDate&&new Date(o.ageMaxDate)<new Date(n.ageMinDate),p=r?.ratingType&&t?.ratingType&&r.ratingType===t.ratingType&&(r.ratingMin&&t.ratingMin&&t.ratingMin<r.ratingMin||r.ratingMax&&t.ratingMax&&t.ratingMax>r.ratingMax||r.ratingMin&&t.ratingMax&&t.ratingMax<r.ratingMin||r.ratingMax&&t.ratingMin&&t.ratingMin>r.ratingMax),m=r?.ballType&&t?.ballType&&r.ballType!==t.ballType,f=nt({invalidRatingRange:p,invalidAgeMinDate:a,invalidAgeMaxDate:c,invalidBallType:m,invalidAgeMax:s,invalidAgeMin:i,valid:!p&&!a&&!c&&!m&&!s&&!i},!0);return e&&Object.assign(f,{categoryDetails:n,childCategoryDetails:o}),f}function Kc({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:Io},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&&!kc([kt,xt],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 P=xI({collectionValueProfiles:u,matchUpCount:l});P.errors&&c.push(...P.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 P=bm({referenceGender:i,matchUpType:I,gender:y});if(P.error)return _({context:{referenceGender:i,gender:y},result:P,stack:a})}if(t&&o&&T){let P=$c({category:o,childCategory:T});if(!P.valid)return _({result:{error:Hc},context:P,stack:a})}return c.length?_({result:{errors:c,error:OE},stack:a}):{valid:!0}}function ur(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=cF({...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:E}=Kc({referenceCategory:t.category,referenceGender:t.gender,collectionDefinition:I,checkCollectionIds:n,checkCategory:e,checkGender:r,event:i});return y?!0:(Array.isArray(E)&&a.push(...E),!1)}),m=typeof o.winCriteria?.valueGoal=="number"&&o.winCriteria?.valueGoal>0&&!u||o.winCriteria?.aggregateValue;if(!(m||o.winCriteria?.aggregateValue))return u?a.push("aggregateValue is required"):a.push("Either non-zero valueGoal, or { aggregateValue: true } must be specified in winCriteria"),_({context:{tieFormat:o,errors:a,aggregateValueImperative:u},result:{error:ko},stack:s});let d=o.collectionDefinitions.map(({collectionId:I})=>I),l=!n||d.length===pt(d).length,f=p&&m&&l,g={valid:f,errors:a};return f?g:_({result:{error:ko},context:{tieFormat:o,errors:a},stack:s})}function cF(t){let{tieFormat:e,stack:r}=t;return!t||!e||!ht(e)?_({result:{error:ko},context:{tieFormat:e,message:"tieformat must be an object"},stack:r}):ht(e.winCriteria)?Array.isArray(e.collectionDefinitions)?{...C}:_({result:{error:ko},context:{tieFormat:e,message:"collectionDefinitions must be an array"},stack:r}):_({result:{error:ko},context:{tieFormat:e,message:"tieformat.winCritiera must be an object"},stack:r})}var tc="resourceSubType",ec="resourceType",rc="identifier",KC={RESOURCE_SUB_TYPE:tc,RESOURCE_TYPE:ec,IDENTIFIER:rc};function J(t,e,r,n,o=0){if(XI().makeDeepCopy)return XI().makeDeepCopy(t,e,r,n);let i=df(),{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=Uf(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:YC(f)?p[l]=new Date(f).toISOString():p[l]=J(f,e,r,n,o+1)}return p}function Uf(t){return t?.map(e=>{let{name:r,value:n}=e;return r&&n&&{[`_${r}`]:n}}).filter(Boolean)}function ih(t=1,e){return tt(0,t).map(()=>Mt(e))}function Mt(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 sh={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 ah={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 ch={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 uh={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 ph={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 mh={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 dh={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 lh={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 fh={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 gh={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",TF="SET3-S:6NOAD",$E="SET3-S:6/TB7-F:TB10",yF="SET3-S:4/TB7",AF="SET3-S:4/TB5@3",EF="SET1-S:T20",UF="SET1-S:8/TB7",PF="SET1-S:8/TB7@7",zC={FORMAT_STANDARD:Dn,FORMAT_STANDARD_NOAD:TF,FORMAT_ATP_DOUBLES:$E,FORMAT_SHORT_SETS:yF,FORMAT_FAST4:AF,FORMAT_PRO_SET:UF,FORMAT_COLLEGE_PRO_SET:PF,TIMED20:EF};var Ih={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 hh={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 Sh={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 Th={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 yh={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 Ah={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 Eh={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 xm="COLLEGE_DEFAULT",Uh="COLLEGE_JUCO",Ph="COLLEGE_D3",KE="DOMINANT_DUO",zE="DOMINANT_DUO_MIXED",QE="LAVER_CUP",XE="TEAM_DOUBLES_3_AGGREGATION",JE="TIME_TENNIS_DUAL",ZE="TIME_TENNIS_PRO_CIRCUIT",tU="USTA_BREWER_CUP",eU="USTA_OZAKI_CUP",rU="USTA_COLLEGE",nU="USTA_GOLD_TEAM_CHALLENGE",oU="USTA_LEVEL_1",iU="USTA_INTERSECTIONAL",sU="USTA_SECTION_BATTLE",aU="USTA_SOUTHERN_LEVEL_5",cU="USTA_TOC",uU="USTA_WTT_ITT",pU="USTA_ZONAL",QC={COLLEGE_D3:Ph,COLLEGE_DEFAULT:xm,COLLEGE_JUCO:Uh,DOMINANT_DUO:KE,DOMINANT_DUO_MIXED:zE,LAVER_CUP:QE,TEAM_DOUBLES_3_AGGREGATION:XE,TIME_TENNIS_DUAL:JE,TIME_TENNIS_PRO_CIRCUIT:ZE,USTA_BREWER_CUP:tU,USTA_OZAKI_CUP:eU,USTA_COLLEGE:rU,USTA_GOLD_TEAM_CHALLENGE:nU,USTA_INTERSECTIONAL:iU,USTA_LEVEL_1:oU,USTA_SECTION_BATTLE:sU,USTA_SOUTHERN_LEVEL_5:aU,USTA_TOC:cU,USTA_WTT_ITT:uU,USTA_ZONAL:pU};var JC="STANDARD",XC={[JC]:{hydrate:!0,doubles:{matchUpCount:3,matchUpValue:1},singles:{matchUpCount:6,matchUpValue:1},valueGoal:5},[Ph]:{hydrate:!0,doubles:{matchUpFormat:"SET1-S:8/TB7@7",matchUpCount:3,matchUpValue:1},singles:{matchUpFormat:Dn,matchUpCount:6,matchUpValue:1},tieFormatName:Ph,valueGoal:5},[xm]:{hydrate:!0,doubles:{matchUpFormat:"SET1-S:6/TB7",collectionValue:1,matchUpCount:3},singles:{matchUpFormat:Dn,matchUpCount:6,matchUpValue:1},tieFormatName:xm,valueGoal:4},[Uh]:{hydrate:!0,doubles:{matchUpFormat:"SET1-S:8/TB7",matchUpCount:3,matchUpValue:1},singles:{matchUpFormat:Dn,matchUpCount:6,matchUpValue:1},tieFormatName:Uh,valueGoal:5},[QE]:Ah,[KE]:Ih,[zE]:dh,[XE]:ah,[JE]:lh,[ZE]:mh,[tU]:fh,[eU]:gh,[rU]:hh,[nU]:sh,[iU]:ph,[oU]:Sh,[sU]:uh,[aU]:ch,[uU]:Th,[cU]:Eh,[pU]:yh},OF=t=>{let e=t?.namedFormat&&Object.keys(XC).includes(t.namedFormat)?t.namedFormat:JC,r=Array.isArray(t?.uuids)?t?.uuids:[],n,{category:o,gender:i}=t?.event??{},s=J(XC[e],!1,!0),a=c=>{if(!t?.isMock&&!t?.event?.isMock||!t.event)return r?.pop()??Mt();let u=t?.event?.eventId;return r.pop()??`${u}-COL-${c+1}`};return s.hydrate?(n={winCriteria:{valueGoal:s.valueGoal},collectionDefinitions:[{collectionId:a(0),matchUpFormat:$E,collectionName:"Doubles",matchUpType:xt,...s.doubles},{collectionId:a(1),matchUpFormat:Dn,collectionName:"Singles",matchUpType:kt,...s.singles}]},s.tieFormatName&&(n.tieFormatName=s.tieFormatName)):(s.collectionDefinitions.forEach((c,u)=>c.collectionId=a(u)),n=s),t?.hydrateCollections&&n.collectionDefinitions.forEach(c=>{o&&!c.category&&(c.category=o),i&&!c.gender&&(c.gender=i)}),n},no=OF;var $n="SINGLES",ks="SINGLES",qr="DOUBLES",Vo="DOUBLES",_e="TEAM",br="TEAM",_F="AGE",xF="RATING",wF="BOTH",ZC={AGE:_F,BOTH:wF,DOUBLES:qr,DOUBLES_EVENT:Vo,RATING:xF,SINGLES:$n,SINGLES_EVENT:ks,TEAM_EVENT:br,TEAM:_e};var rt="MAIN",ct="QUALIFYING",qe="CONSOLATION",$e="VOLUNTARY_CONSOLATION",fe="PLAY_OFF",zc=[rt,ct,qe,fe,$e],Gs={[ct]:1,[rt]:2,[fe]:3,[qe]:3,[$e]:4},mU="finishingPositions",dU="aggregateEventStructures",lU={[rt]:1,[fe]:2,[qe]:3,[ct]:4,[$e]:5},tb={[fe]:1,[rt]:2,[qe]:3,[ct]:4,[$e]:5},Qc="CLUSTER",eb="SEPARATE",li="WATERFALL",pp="ITEM",Ve="CONTAINER",dn="DRAW",mp="RANDOM",En="TOP_DOWN",fi="BOTTOM_UP",xn="POSITION",Kn="WINNER",oo="LOSER",wn="FIRST_MATCHUP",$r="AD_HOC",LF="AD_HOC",fa="FEED_IN",Xc="COMPASS",Jc="OLYMPIC",FF="SINGLE_ELIMINATION";var ho="SINGLE_ELIMINATION",Zc="DOUBLE_ELIMINATION",tu="FIRST_MATCH_LOSER_CONSOLATION",dp="FIRST_ROUND_LOSER_CONSOLATION",Vi="LUCKY_DRAW",Pf="CURTIS_CONSOLATION",rb="CURTIS_CONSOLATION",Dh="FEED_IN_CHAMPIONSHIP_TO_SF",wm="FEED_IN_CHAMPIONSHIP_TO_SF",Nh="FEED_IN_CHAMPIONSHIP_TO_QF",Lm="FEED_IN_CHAMPIONSHIP_TO_QF",Mh="FEED_IN_CHAMPIONSHIP_TO_R16",Fm="FEED_IN_CHAMPIONSHIP_TO_R16",fU="MODIFIED_FEED_IN_CHAMPIONSHIP",km="MODIFIED_FEED_IN_CHAMPIONSHIP",lp="FEED_IN_CHAMPIONSHIP",nb="DOUBLE_ROUND_ROBIN",Nn="ROUND_ROBIN",So="ROUND_ROBIN_WITH_PLAYOFF",gU="DECIDER",IU="BACKDRAW",Df={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"}},Nf={0:{name:"East",abbreviation:"E"},"0-1":{name:"West",abbreviation:"W"},"0-2":{name:"North",abbreviation:"N"},"0-1-1":{name:"South",abbreviation:"S"}},gi="WIN_RATIO",Bi="ROUND_OUTCOME",hU=[Xc,Pf,Lm,Fm,wm,lp,Nh,Mh,Dh,tu,dp,Vi,km,Jc,fe,So],kF=[$r,Xc,Pf,Zc,Lm,Fm,wm,lp,fa,tu,dp,Vi,km,Jc,fe,Nn,So,ho],SU={MAIN:rt,QUALIFYING:ct,CONSOLATION:qe,ITEM:pp,CONTAINER:Ve,FIRST_MATCHUP:wn,WINNER:Kn,LOSER:oo,AD_HOC:$r,FEED_IN:fa,FLEX_ROUNDS:LF,COMPASS:Xc,PLAY_OFF:fe,OLYMPIC:Jc,KNOCKOUT:FF,SINGLE_ELIMINATION:ho,DOUBLE_ELIMINATION:Zc,CURTIS:Pf,FICSF:Dh,FICQF:Nh,FICR16:Mh,MFIC:fU,VOLUNTARY_CONSOLATION:$e,FIRST_MATCH_LOSER_CONSOLATION:tu,FIRST_ROUND_LOSER_CONSOLATION:dp,MODIFIED_FEED_IN_CHAMPIONSHIP:km,FEED_IN_CHAMPIONSHIP_TO_R16:Fm,FEED_IN_CHAMPIONSHIP_TO_QF:Lm,FEED_IN_CHAMPIONSHIP_TO_SF:wm,FEED_IN_CHAMPIONSHIP:lp,LUCKY_DRAW:Vi,ROUND_ROBIN_WITH_PLAYOFF:So,ROUND_ROBIN:Nn,DECIDER:gU,BACKDRAW:IU,COMPASS_ATTRIBUTES:Df,OLYMPIC_ATTRIBUTES:Nf,DRAW:dn,RANDOM:mp,TOP_DOWN:En,BOTTOM_UP:fi,WATERFALL:li,WIN_RATIO:gi,ROUND_OUTCOME:Bi,MULTI_STRUCTURE_DRAWS:hU,generatedDrawTypes:kF,stageOrder:Gs,finishOrder:lU,AGGREGATE_EVENT_STRUCTURES:dU,FINISHING_POSITIONS:mU},ob=SU;var Re="tournamentRecords",Mf="policyDefinitions",ne="tournamentRecord",Rh="onlineResource",Ce="drawDefinition",Ch="tieFormatName",Gm="matchUpFormat",io="participantId",bh="scheduleDates",ib="tournamentId",sb="scheduleDate",ab="roundNumber",eu="structureId",Rf="participant",nc="matchUpIds",vh="entryStage",cb="policyType",TU="structures",Cf="eventType",ln="matchUpId",Vm="tieFormat",ru="inContext",fp="structure",gp="courtIds",ub="personId",Ip="venueIds",bf="matchUps",Oh="courtId",_h="eventId",Ln="matchUp",xh="drawId",fn="error",so="event",ss="param",vf="uuids",pb="averageMatchUpMinutes",mb="recoveryMinutes",db="periodLength",lb="number";var Kr="object",Be="array";var er="_validate",wh="_message",Fr="_invalid",He="_ofType",Bm="_anyOf",Vs="_oneOf";var fb={[Rh]:t=>jt(Object.keys(t),[tc,ec,rc]).length===3,[Ch]:t=>t&&no({namedFormat:t}),[vf]:t=>!t||Array.isArray(t)&&t.every(Vt),[Vm]:t=>!ur({tieFormat:t}).error,[Cf]:t=>[$n,qr,_e].includes(t),[vh]:t=>zc.includes(t)},GF={[Re]:Lt,[ne]:$,[Mf]:Xu,[Ce]:Z,[io]:ie,[Gm]:$l,[ib]:pa,[eu]:Ur,[nc]:ns,[Rf]:Fi,[Rh]:Io,[Cf]:jn,[TU]:Hl,[ln]:cr,[Vm]:ko,[fp]:di,[Oh]:wi,[bf]:eo,[_h]:jr,[Ln]:Tr,[gp]:st,[Ip]:st,[xh]:sn,[so]:Ot},VF={[Re]:Kr,[Mf]:Kr,[ne]:Kr,[Ce]:Kr,[Rh]:Kr,[bh]:Be,[Rf]:Kr,[nc]:Be,[TU]:Be,[Vm]:Kr,[fp]:Kr,[gp]:Be,[Ip]:Be,[bf]:Be,[Ln]:Kr,[so]:Kr,[vf]:Be};function et(t,e,r){if(!t&&!ht(t))return{error:V};if(!e?.length||t?._bypassParamCheck)return{valid:!0};if(!Array.isArray(e))return{error:V};let{paramError:n,errorParam:o}=WF(t,e);if(!n)return{valid:!0};let i=n[er]&&(n[fn]||n[Fr])||t?.[o]===void 0&&(n[fn]||n[Fr]||GF[o]||V)||V,s=o??(n[Vs]&&Object.keys(n[Vs]).join(", "));return _({info:{param:s,message:n[wh]},result:{error:i},stack:r})}function gb(t,e){let r=Object.keys(t),n=Object.keys(e);return jt(r,n)}function BF(t,e){if(!e)return;let r=gb(t,e);return r.length!==1?{error:V}:r.reduce((n,o)=>({...n,[o]:!0}),{})}function HF(t,e){if(!e)return;let r=gb(t,e).filter(n=>t[n]);return r.length<1?{error:V}:r.reduce((n,o)=>({...n,[o]:!0}),{})}function WF(t,e){let r,n;return{paramError:e.find(({_ofType:i,_oneOf:s,_anyOf:a,_validate:c,_info:u,...p})=>{let m=s&&BF(t,s);if(m?.error)return m.error;m&&Object.assign(p,m);let d=a&&HF(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&&jF(t,g,i),S=p[g]&&[void 0,null].includes(t[g]),y=I||h||S||c&&t[g]!==void 0&&!YF(t[g],c)||fb[g]&&!fb[g](t[g]);return y&&(r=g,n=u),y});return!l.length||f}),errorParam:r,paramInfo:n}}function jF(t,e,r){return r=r||VF[e]||"string",r==="array"?!Array.isArray(t[e]):typeof t[e]!==r}function YF(t,e){return Wr(e)?e(t):!0}var Hm="DYNAMIC",Ii="RANKING",hi="RATING",Si="SCALE",To="SEEDING",Ib={RANKING:Ii,RATING:hi,SCALE:Si,SEEDING:To};function ga(t){let e=et(t,[{[Rf]:!0}]);if(e.error)return e;let r=t.participant.timeItems?.filter(({itemType:o})=>o?.startsWith(Si)&&[Ii,hi,To].includes(o.split(".")[1])),n={ratings:{},rankings:{},seedings:{}};if(r?.length){let o=s=>r.filter(a=>a?.itemType===s).sort((a,c)=>new Date(a.createdAt||void 0).getTime()-new Date(c.createdAt||void 0).getTime()).pop(),i=pt(r.map(({itemType:s})=>s));for(let s of i){let a=o(s);if(a){let[,c,u,p,m]=a.itemType.split("."),d=m?`${p}.${m}`:p,l=c===To&&"seedings"||c===Ii&&"rankings"||"ratings";n[l][u]||(n[l][u]=[]),n[l][u].push({scaleValue:a.itemValue,scaleDate:a.itemDate,scaleName:d})}}}return{...C,...n}}function Hi(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 Lh="voluntaryConsolation",Ti="competitiveBands",Of="roundRobinTally",zn="positionActions",rr="matchUpActions",_f="rankingPoints",Ia="roundNaming",Bs="participant",nu="progression",Mo="scheduling",ou="avoidance",qF="participant",$F="display",tn="scoring",Fn="seeding",oc="feedIn",KF="audit",Wm="draws",hb={POLICY_TYPE_VOLUNTARY_CONSOLATION:Lh,POLICY_TYPE_COMPETITIVE_BANDS:Ti,POLICY_TYPE_ROUND_ROBIN_TALLY:Of,POLICY_TYPE_POSITION_ACTIONS:zn,POLICY_TYPE_MATCHUP_ACTIONS:rr,POLICY_TYPE_RANKING_POINTS:_f,POLICY_TYPE_ROUND_NAMING:Ia,POLICY_TYPE_PARTICIPANT:Bs,POLICY_TYPE_PROGRESSION:nu,POLICY_TYPE_SCHEDULING:Mo,POLICY_TYPE_AVOIDANCE:ou,POLICY_TYPE_DISPLAY:$F,POLICY_TYPE_PRIVACY:qF,POLICY_TYPE_FEED_IN:oc,POLICY_TYPE_SCORING:tn,POLICY_TYPE_SEEDING:Fn,POLICY_TYPE_AUDIT:KF,POLICY_TYPE_DRAWS:Wm};function Bo({tournamentParticipants:t=[],policyDefinitions:e={},contextProfile:r,participantId:n,internalUse:o,personId:i}){let s=t.find(c=>n&&c.participantId===n||i&&c.person&&c.person.personId===i),a=J(s,!1,o);if(a){let c=e?.[Bs];if(r?.withScaleValues){let{ratings:u,rankings:p}=ga({participant:a});a.rankings=p,a.ratings=u}if(c?.participant)return Hi({template:c.participant,source:a})}return a}var Sb="element required",Tb="missing name";function gr(t){if(!t||typeof t!="object")return{error:st};if(t.element&&typeof t?.element!="object")return{error:V};if(!t?.name)return{error:st,info:Tb};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:Sb}}return t?.element.extensions?(t.element.extensions=t.element.extensions.filter(e=>e?.name!==t.name),{...C}):{...C,info:ve}}function kn({requiredAttributes:t=["name","value"],extension:e}){if(!e||typeof e!="object"||typeof e.name!="string")return!1;let r=Object.keys(e);return t.filter(n=>r.includes(n)).length===t.length}function Ut(t){if(typeof t!="object")return{error:st};let e="addExtension";if(t?.element&&typeof t.element!="object")return _({result:{error:V},stack:e});if(!kn({extension:t.extension}))return _({result:{error:V,info:"invalid extension"},stack:e});if(!t.element)if(t.discover&&!t.tournamentId&&t.tournamentRecords){for(let o of Object.values(t.tournamentRecords)){let i=Ut({extension:t.extension,element:o});if(i.error)return _({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 xf(t){return!t||typeof t!="object"?{error:st}:t.tournamentRecord?Ut({creationTime:t.creationTime,element:t.tournamentRecord,extension:t.extension}):{error:$}}function hp(t){return!t||typeof t!="object"?{error:st}:t.drawDefinition?Ut({creationTime:t.creationTime,element:t.drawDefinition,extension:t.extension}):{error:Cr}}function Ro(t){return!t||typeof t!="object"?{error:st}:t.event?Ut({creationTime:t.creationTime,extension:t.extension,element:t.event}):{error:jr}}function yU(t){if(!t||typeof t!="object")return{error:st};if(!t.participantId)return{error:ie};let e=t.tournamentRecord?.participants||[],r=Bo({participantId:t.participantId,tournamentParticipants:e});return r?Ut({creationTime:t.creationTime,extension:t.extension,element:r}):{error:re}}function wf(t){return!t||typeof t!="object"?{error:st}:t.tournamentRecord?gr({element:t.tournamentRecord,name:t.name}):{error:$}}function AU(t){return!t||typeof t!="object"?{error:st}:t.drawDefinition?gr({element:t.drawDefinition,name:t.name}):{error:Cr}}function Sp(t){return!t||typeof t!="object"?{error:st}:t?.event?gr({element:t.event,name:t.name}):{error:jr}}function EU(t){if(!t||typeof t!="object")return{error:st};if(!t.participantId)return{error:ie};let e=t.tournamentRecord?.participants||[],r=Bo({participantId:t.participantId,tournamentParticipants:e});return r?gr({element:r,name:t.name}):{error:re}}function Tp({tournamentRecords:t}){return{tournamentIds:ht(t)?Object.keys(t):[],...C}}var zF="extensionQueries";function mt({discover:t,element:e,name:r,...n}){if(!e||!r){if(t&&n){let s=Object.keys(n).filter(p=>typeof t=="boolean"||Array.isArray(t)&&t.includes(p)).find(p=>Array.isArray(n[p]?.extensions)?n[p].extensions.find(m=>m?.name===r):!1),a=s&&n[s];!a&&n.tournamentRecords&&(a=Object.values(n.tournamentRecords).find(p=>p.extensions?.length));let c=a?.extensions?.find(p=>p?.name===r);return{extension:c,info:c?void 0:ve}}return _({result:{error:st},stack:zF})}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 QF="activeSuspension",iu="appliedPolicies",UU="context",jm="delegatedOutcome",ao="disabled",ha="disableAutoCalc",Ym="disableLinks",qm="display",Sa="drawDeletions",XF="drawProfile",$m="entryProfile",JF="eventProfile",ZF="eventWithdrawalRequests",tk="factory",cn="flightProfile",Fh="groupingAttribute",Co="lineUps",Hs="linkedTournamentsIds",Km="matchUpHistory",kh="participantRepresentatives",Ta="personRequests",ic="positionActions",ek="rankingPoints",rk="registration",Mn="roundTarget",su="scheduleLimits",Ho="scheduleTiming",ya="schedulingProfile",nk="statusDetail",sc="subOrder",bo="tally",zm="tieFormatModification",Gh={ACTIVE_SUSPENSION:QF,APPLIED_POLICIES:iu,CONTEXT:UU,DELEGATED_OUTCOME:jm,DISABLED:ao,DISABLE_LINKS:Ym,DISABLE_AUTO_CALC:ha,DISPLAY:qm,DRAW_DELETIONS:Sa,DRAW_PROFILE:XF,ENTRY_PROFILE:$m,EVENT_PROFILE:JF,EVENT_WITHDRAWAL_REQUESTS:ZF,FLIGHT_PROFILE:cn,GROUPING_ATTRIBUTE:Fh,LINEUPS:Co,LINKED_TOURNAMENTS:Hs,MATCHUP_HISTORY:Km,PARTICIPANT_REPRESENTATIVES:kh,PERSON_REQUESTS:Ta,POSITION_ACTIONS:ic,RANKING_POINTS:ek,REGISTRATION:rk,ROUND_TARGET:Mn,SCHEDULE_LIMITS:su,SCHEDULE_TIMING:Ho,SCHEDULING_PROFILE:ya,STATUS_DETAIL:nk,SUB_ORDER:sc,TALLY:bo,TIE_FORMAT_MODIFICATIONS:zm,FACTORY:tk},PU=[jm,ao,ha,Ym,cn,Co,Hs,Km,kh,Ta,Mn,su,Ho,ya,sc,bo,zm];function DU({tournamentRecords:t}){if(typeof t!="object"||!Object.keys(t).length)return{error:Lt};let e=Tp({tournamentRecords:t}),{tournamentIds:r}=e;return r?.length>1?Ut({tournamentRecords:t,discover:!0,extension:{name:Hs,value:{tournamentIds:r}}}):{...C}}function NU({tournamentRecords:t}){if(typeof t!="object"||!Object.keys(t).length)return{error:Lt};let e=gr({name:Hs,tournamentRecords:t,discover:!0});return _({result:e,stack:"unlinkTournaments"})}function MU({tournamentRecords:t,tournamentId:e}){if(typeof t!="object")return{error:V};if(!e)return{error:pa};let r=Tp({tournamentRecords:t}),{tournamentIds:n}=r;if(!n.includes(e))return{error:pa};let o;return n.every(i=>{let s=t[i],{extension:a}=mt({element:s,name:Hs});if(!a)return!0;let c=a?.value?.tournamentIds||[];if(!c?.length||c.length===1&&c.includes(e)||i===e){let m=wf({name:Hs,tournamentRecord:s});return m.error&&(o=m.error),m.success}let u=c.filter(m=>m!==e);a.value={tournamentIds:u};let p=xf({tournamentRecord:s,extension:a});return p.error&&(o=p.error),p.success}),o?{error:o}:{...C}}var CU={};Jt(CU,{getLinkedTournamentIds:()=>au,getTournamentIds:()=>Tp});function au({tournamentRecords:t}){return typeof t!="object"||!Object.keys(t).length?{error:Lt}:{linkedTournamentIds:Object.assign({},...Object.keys(t).map(r=>{let n=t[r],o=n?.tournamentId,{extension:i}=mt({element:n,name:Hs}),s=(i?.value?.tournamentIds||[]).filter(a=>a!==o);return{[r]:s}}))}}var _N={};Jt(_N,{adHocPositionSwap:()=>BP,addAdHocMatchUps:()=>Od,addDrawDefinitionTimeItem:()=>Dg,addFinishingRounds:()=>Pa,addGoesTo:()=>Ki,addPlayoffStructures:()=>Bp,addQualifyingStructure:()=>VP,addVoluntaryConsolationStage:()=>xP,addVoluntaryConsolationStructure:()=>gg,allPlayoffPositionsFilled:()=>FS,alternateDrawPositionAssignment:()=>EP,assignDrawPosition:()=>eD,assignDrawPositionBye:()=>Hr,attachConsolationStructures:()=>XP,attachPlayoffStructures:()=>wg,attachQualifyingStructure:()=>Pg,attachStructures:()=>Lg,autoSeeding:()=>rx,automatedPlayoffPositioning:()=>zs,automatedPositioning:()=>yc,checkValidEntries:()=>wd,deleteAdHocMatchUps:()=>rD,drawMatic:()=>Kd,findDrawDefinition:()=>uT,generateAdHocMatchUps:()=>Lu,generateAdHocRounds:()=>$d,generateAndPopulatePlayoffStructures:()=>vd,generateDrawDefinition:()=>wa,generateDrawMaticRound:()=>Gd,generateDrawStructuresAndLinks:()=>Ld,generateDrawTypeAndModifyDrawDefinition:()=>Fd,generateQualifyingStructure:()=>Nd,generateVoluntaryConsolation:()=>bT,getAssignedParticipantIds:()=>Ci,getAvailableMatchUpsCount:()=>_d,getAvailablePlayoffProfiles:()=>Cu,getDrawDefinitionTimeItem:()=>tS,getDrawParticipantRepresentativeIds:()=>aT,getDrawStructures:()=>gn,getDrawTypeCoercion:()=>xu,getEligibleVoluntaryConsolationParticipants:()=>sT,getMatchUpsMap:()=>Me,getParticipantIdFinishingPositions:()=>cT,getPositionAssignments:()=>Hp,getPositionsPlayedOff:()=>Ec,getRandomQualifierList:()=>ET,getSeedingThresholds:()=>MS,getSeedsCount:()=>wu,getStructureSeedAssignments:()=>nn,getTeamLineUp:()=>ds,getValidGroupSizes:()=>Op,isAdHoc:()=>pr,isCompletedStructure:()=>Eo,isValidForQualifying:()=>UT,luckyLoserDrawPositionAssignment:()=>SP,modifyDrawDefinition:()=>JP,modifyDrawName:()=>Fg,modifySeedAssignment:()=>CP,mutate:()=>iD,positionActions:()=>AT,pruneDrawDefinition:()=>tD,qualifierDrawPositionAssignment:()=>Ug,qualifierProgression:()=>bP,query:()=>ID,removeDrawPositionAssignment:()=>Pu,removeRoundMatchUps:()=>nD,removeSeededParticipant:()=>GP,removeStructure:()=>_P,renameStructures:()=>OP,resetDrawDefinition:()=>ZP,resetQualifyingStructure:()=>wP,resetVoluntaryConsolationStructure:()=>VU,setDrawParticipantRepresentativeIds:()=>OU,setPositionAssignments:()=>yP,setStructureOrder:()=>vP,setSubOrder:()=>oD,shiftAdHocRounds:()=>TP,swapAdHocRounds:()=>AP,swapDrawPositionAssignments:()=>kP,updateTeamLineUp:()=>Qi,withdrawParticipantAtDrawPosition:()=>IP});var iD={};Jt(iD,{adHocPositionSwap:()=>BP,addAdHocMatchUps:()=>Od,addDrawDefinitionTimeItem:()=>Dg,addPlayoffStructures:()=>Bp,addQualifyingStructure:()=>VP,addVoluntaryConsolationStage:()=>xP,addVoluntaryConsolationStructure:()=>gg,alternateDrawPositionAssignment:()=>EP,assignDrawPosition:()=>eD,assignDrawPositionBye:()=>Hr,attachConsolationStructures:()=>XP,attachPlayoffStructures:()=>wg,attachQualifyingStructure:()=>Pg,attachStructures:()=>Lg,automatedPlayoffPositioning:()=>zs,automatedPositioning:()=>yc,deleteAdHocMatchUps:()=>rD,luckyLoserDrawPositionAssignment:()=>SP,modifyDrawDefinition:()=>JP,modifyDrawName:()=>Fg,modifySeedAssignment:()=>CP,pruneDrawDefinition:()=>tD,qualifierDrawPositionAssignment:()=>Ug,qualifierProgression:()=>bP,removeDrawPositionAssignment:()=>Pu,removeRoundMatchUps:()=>nD,removeSeededParticipant:()=>GP,removeStructure:()=>_P,renameStructures:()=>OP,resetDrawDefinition:()=>ZP,resetQualifyingStructure:()=>wP,resetVoluntaryConsolationStructure:()=>VU,setDrawParticipantRepresentativeIds:()=>OU,setPositionAssignments:()=>yP,setStructureOrder:()=>vP,setSubOrder:()=>oD,shiftAdHocRounds:()=>TP,swapAdHocRounds:()=>AP,swapDrawPositionAssignments:()=>kP,updateTeamLineUp:()=>Qi,withdrawParticipantAtDrawPosition:()=>IP});var vU=t=>e=>t[e],Qm=(t=[])=>t.map(Ue).filter(Boolean),Lf=(t=[])=>t.map(St).filter(Boolean),St=(t={})=>vU(t)("participantId");var Ue=(t={})=>vU(t)("matchUpId"),cu=(t={})=>vU(t)("drawId");function OU({representativeParticipantIds:t,drawDefinition:e}){if(!e)return{error:Cr};if(!Array.isArray(t))return{error:V};let r=Lf(e?.entries||[]);return t.length&&jt(t,r).length<t.length?{error:V}:hp({drawDefinition:e,extension:{name:kh,value:t}})}var vr="ABANDONED",ac="AWAITING_RESULT",Nt="BYE",co="CANCELLED",he="COMPLETED",uu="DEAD_RUBBER",Rt="DEFAULTED",be="DOUBLE_DEFAULT",Te="DOUBLE_WALKOVER",Gn="IN_PROGRESS",un="INCOMPLETE",_U="NOT_PLAYED",nr="RETIRED",as="SUSPENDED",Xt="TO_BE_PLAYED",bt="WALKOVER",yb=[ac,he,Rt,Gn,un,nr,as],Vh=[ac,he,Rt,Te,be,Gn,un,nr,as,bt],Bh=[vr,ac,Nt,co,he,uu,Rt,Te,be,Gn,un,_U,nr,as,Xt,bt],Hh=[Nt,Te,be,he,Rt,nr,bt],Wh=[vr,ac,co,uu,Gn,un,_U,as,Xt,void 0],se=[co,vr,he,uu,Rt,Te,be,nr,bt],Xm=[vr,he,Rt,Te,be,Gn,nr,bt],jh=[Gn,un,as,Xt],Yh={ABANDONED:vr,AWAITING_RESULT:ac,BYE:Nt,CANCELLED:co,COMPLETED:he,DEAD_RUBBER:uu,DEFAULTED:Rt,DOUBLE_WALKOVER:Te,DOUBLE_DEFAULT:be,IN_PROGRESS:Gn,INCOMPLETE:un,NOT_PLAYED:_U,RETIRED:nr,SUSPENDED:as,TO_BE_PLAYED:Xt,WALKOVER:bt};function yi(t,e,r){let n=m=>mt({element:m,name:Mn})?.extension?.value,o=r?.deprioritizeCompleted,i=r?.mode===dU&&tb,s=r?.mode===mU&&lU,a=s||i||Gs,c=m=>m?.stage===rt&&m?.stageSequence===1,u=m=>c(m)?-1:a[m?.stage],p=m=>m?.matchUps.every(({matchUpStatus:d})=>se.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)||(Ff(t)||0)-(Ff(e)||0)}function Ff(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=et(t,[{[Ce]:!0,[eu]:!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:wt};let a=s.structureType===pp?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&&Hl||void 0;if(c)return{error:c,structures:[],stageStructures:{}};let u=f=>{let g=mt({element:f,name:Mn})?.extension?.value;return!o||o===g},p=e?.structures?.filter(d).filter(l).filter(u).sort((f,g)=>yi(f,g,i))??[],m=t?Object.assign({},...zc.map(f=>{let g=p?.filter(I=>I.stage===f);return g?.length&&{[f]:g}}).filter(Boolean)):{};return{structures:p,stageStructures:m};function d(f){return!a&&!Array.isArray(s)||a&&f.stage===a||Array.isArray(s)&&s.includes(f.stage)}function l(f){return!n&&!Array.isArray(r)||n&&f.stageSequence===n||Array.isArray(r)&&r.includes(f.stageSequence)}}function qh({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}=Ct({structure:n}),s=i?.map(St).filter(Boolean)??[];return e[o].push(...s),s}).flat(),stagePositionedParticipantIds:e}}function Ct({drawDefinition:t,structureId:e,structure:r}){let n,o=[];if(!r){if(!t)return{positionAssignments:o,error: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=>Ct({structure:i}).positionAssignments)):r.positionAssignments?o=r.positionAssignments:n=JA,{positionAssignments:o,error:n}}function ge({drawDefinition:t,structureId:e,structure:r}){let n=Ct({drawDefinition:t,structureId:e,structure:r})?.positionAssignments||[],o=n?.filter(u=>u.participantId??u.bye??u.qualifier),i=n&&n?.length===o?.length,s=n?.filter(u=>!u.participantId&&!u.bye&&!u.qualifier),a=n?.filter(u=>!u.participantId&&u.bye),c=n?.filter(u=>!u.participantId&&u.qualifier);return{allPositionsAssigned:i,positionAssignments:n,unassignedPositions:s,assignedPositions:o,qualifierPositions:c,byePositions:a}}var kf="addDrawDefinition",yp="addMatchUps",ei="addParticipants",Gf="addScaleItems",xU="addEvent",$h="addVenue",Ai="audit",Kh="dataIssue",Vf="deleteParticipants",Bf="deleteVenue",Hf="deletedDrawIds",Wf="deletedMatchUpIds",jf="modifyDrawDefinition",wU="modifyDrawEntries",LU="modifyEventEntries",Yf="modifyMatchUp",or="modifyParticipants",qf="modifyPositionAssignments",$f="modifySeedAssignments",Wi="modifyTournamentDetail",Ei="modifyVenue",Jm="mutations",zh="publishEvent",FU="publishEventSeeding",kU="publishOrderOfPlay",GU="publishParticipants",Kf="unPublishEvent",zf="unPublishEventSeeding",Qf="unPublishOrderOfPlay",Ab="unPublishParticipants",Ap="updateInContextMatchUp",Eb={ADD_DRAW_DEFINITION:kf,ADD_MATCHUPS:yp,ADD_PARTICIPANTS:ei,ADD_SCALE_ITEMS:Gf,ADD_EVENT:xU,ADD_VENUE:$h,AUDIT:Ai,DATA_ISSUE:Kh,DELETE_PARTICIPANTS:Vf,DELETE_VENUE:Bf,DELETED_DRAW_IDS:Hf,DELETED_MATCHUP_IDS:Wf,MODIFY_DRAW_DEFINITION:jf,MODIFY_DRAW_ENTRIES:wU,MODIFY_EVENT_ENTRIES:LU,MODIFY_MATCHUP:Yf,MODIFY_PARTICIPANTS:or,MODIFY_POSITION_ASSIGNMENTS:qf,MODIFY_SEED_ASSIGNMENTS:$f,MODIFY_TOURNAMENT_DETAIL:Wi,MODIFY_VENUE:Ei,MUTATIONS:Jm,PUBLISH_EVENT_SEEDING:FU,PUBLISH_EVENT:zh,PUBLISH_ORDER_OF_PLAY:kU,PUBLISH_PARTICIPANTS:GU,UNPUBLISH_EVENT_SEEDING:zf,UNPUBLISH_EVENT:Kf,UNPUBLISH_ORDER_OF_PLAY:Qf,UPDATE_INCONTEXT_MATCHUP:Ap};function Qh(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 vo({drawDefinition:t,tournamentId:e,matchUps:r,eventId:n}){return t&&Qh(t),lt({payload:{matchUps:r,tournamentId:e,eventId:n},topic:yp}),{...C}}function Rn({drawDefinition:t,tournamentId:e,matchUpIds:r,eventId:n,action:o}){t&&Qh(t),lt({topic:Wf,payload:{tournamentId:e,matchUpIds:r,eventId:n,action:o}});for(let i of r)QI({key:i});return{...C}}function gt({drawDefinition:t,tournamentId:e,structureId:r,context:n,eventId:o,matchUp:i}){return i?(t&&vt({drawDefinition:t,structureIds:r?[r]:void 0,tournamentId:e,eventId:o}),lt({topic:Yf,payload:{matchUp:i,tournamentId:e,context:n},key:i.matchUpId}),{...C}):(console.log(Tr),{error:Tr})}function Ub({tournamentId:t,inContextMatchUp:e}){return e?(lt({payload:{inContextMatchUp:e,tournamentId:t},topic:Ap,key:e.matchUpId}),{...C}):{error:Tr}}function Aa({tournamentId:t,eventId:e,drawDefinition:r}){return r?(Qh(r),lt({payload:{drawDefinition:r,tournamentId:t,eventId:e},topic:kf,key:r.drawId}),{...C}):(console.log(Z),{error:Z})}function Pb({tournamentId:t,eventId:e,drawId:r}){return lt({payload:{drawId:r,tournamentId:t,eventId:e},topic:Hf,key:r}),QI({key:r}),{...C}}function vt({drawDefinition:t,tournamentId:e,structureIds:r,eventId:n}){return t?(Qh(t,r),lt({payload:{tournamentId:e,eventId:n,drawDefinition:t},topic:jf,key:t.drawId}),{...C}):{error:Z}}function Xh({drawDefinition:t,tournamentId:e,structure:r,eventId:n}){if(!t)return{error:Z};if(!r)return{error:di};let o=r.seedAssignments,i=r.structureId,s=t.drawId;return lt({payload:{tournamentId:e,eventId:n,drawId:s,structureId:i,seedAssignments:o},topic:$f,key:t.drawId}),vt({structureIds:[i],drawDefinition:t,tournamentId:e,eventId:n}),{...C}}function Oo({drawDefinition:t,tournamentId:e,structure:r,event:n}){if(!t)return{error:Z};if(!r)return{error:di};let o=Ct({structure:r}),i=r.structureId,s=t.drawId,a=n?.eventId;return lt({topic:qf,payload:{positionAssignments:o,tournamentId:e,structureId:i,eventId:a,drawId:s},key:i}),vt({structureIds:[i],drawDefinition:t,tournamentId:e,eventId:a}),{...C}}function VU({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:wt};let i=o.matchUps?.map(({matchUpId:s})=>s)||[];return o.positionAssignments=[],o.seedAssignments=[],o.matchUps=[],Rn({tournamentId:t?.tournamentId,action:"resetVoluntaryConsolationStructure",matchUpIds:i,drawDefinition:e}),r&&(e.entries=e.entries.filter(s=>s.entryStage!==$e)),vt({tournamentId:t?.tournamentId,eventId:n?.eventId,drawDefinition:e,structureIds:[o.structureId]}),{...C}}function Zm({drawPositions:t,structure:e}){if([ct,rt].includes(e.stage)&&e.stageSequence===1)return;let{positionAssignments:r}=Ct({structure:e});r?.filter(({drawPosition:o})=>t?.includes(o))?.forEach(o=>{Ut({element:o,extension:{name:Ym,value:!0}})})}function pu(t){let{appliedPolicies:e,positionAction:r,drawDefinition:n}=t;if(e?.audit?.[ic]===!1)return;let{extension:o}=mt({name:ic,element:n}),i=Array.isArray(o?.value)?o?.value??[]:[];if(!i?.length){let a=n.structures.find(c=>c.stage===rt);if(a){let c=Ct({structure:a}).positionAssignments?.map(({drawPosition:u,participantId:p,bye:m,qualifier:d})=>({drawPosition:u,participantId:p,qualifier:d,bye:m}));i.push({name:"initialMainAssignments",initialAssignments:c})}}let s={value:i.concat(r),name:ic};Ut({element:n,extension:s})}function cs({tournamentRecord:t,drawDefinition:e,event:r}){let o=(t?.events||r&&[r])?.map(c=>c?.drawDefinitions).flat().filter(Boolean)||e&&[e]||[],i={},s={},a=o.map(c=>c?.structures?.filter(u=>u?.structures)).flat().filter(Boolean);for(let c of a){let{structures:u,structureId:p}=c??{};u&&p&&(i[p]=u?.map(m=>m.structureId))&&u.forEach(m=>s[m.structureId]=c?.structureId)}return{containedStructures:i,containerStructures:s}}function mu(t){let{sides:e,matchUpType:r}=t||{},n=t.potentialParticipants?.length?t.potentialParticipants.flat().map(s=>r===xt?s?.individualParticipantIds||[]:s.participantId).flat():[],o=(e||[]).map(s=>r===xt&&(s?.participant?.individualParticipantIds||[])||s?.participantId&&[s.participantId]||[]).flat();return{individualParticipantIds:o.concat(n).flat(),enteredIndividualParticipantIds:o,potentialIndividualParticipantIds:n}}function Mr(t){return t?.tournamentRecords??(t?.tournamentRecord&&{[t.tournamentRecord.tournamentId]:t.tournamentRecord})??{}}var cc="SIGN_IN_STATUS",BU="SIGNED_OUT",du="SIGNED_IN",Er="TEAM",At="INDIVIDUAL",zr="GROUP",ft="PAIR",Ft="TEAM",lu={TEAM_PARTICIPANT:Er,INDIVIDUAL:At,GROUP:zr,TEAM:Ft,PAIR:ft},Db={INDIVIDUAL:At,GROUP:zr,PAIR:ft,TEAM:Ft,SIGN_IN_STATUS:cc,SIGNED_OUT:BU,SIGNED_IN:du};function fu({participantsProfile:t,participants:e=[],deepCopy:r}){let n=new Map,o=r!==!1?J(e,t?.convertExtensions,!0):e,i=o.filter(c=>c.participantType===Ft),s=o.filter(c=>c.participantType===zr),a=o.filter(c=>c.participantType===ft);return o.forEach(c=>{if(c.participantType===At){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 HU(t){return t&&typeof String.fromCodePoint<"u"?t.toUpperCase().replace(/./g,e=>String.fromCodePoint(e.charCodeAt(0)+127397)):t}function Nb(t){let e=Object.assign({},...ri.filter(r=>r.ioc).map(r=>({[r.ioc]:r.iso})));return HU(e[t])}var ri=[{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 Jh({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=ri.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 Mb({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?Hi({template:e,source:s}):s)}}}}function yo(t){let{tournamentRecord:e,participantId:r}=t,n=t.tournamentRecords||e&&{[e.tournamentId]:e}||{};for(let o of Object.values(n)){let i=o.participants?.find(s=>s.participantId===r);if(i)return{participant:i,tournamentId:o.tournamentId}}return{error:re}}function Zh(t){let{tournamentRecord:e,participantId:r}=t;if(r){let o=yo({tournamentRecord:e,participantId:r});return o.participant??o}let n=t.element||t.drawDefinition||t.event||t.tournamentRecord;return n||{error:st}}function en(t){let{returnPreviousValues:e,itemSubTypes:r,itemType:n}=t,o=Zh(t);if(o.error)return o;if(r&&!Array.isArray(r))return{error:V,context:{itemSubTypes:r}};if(!Array.isArray(o.timeItems))return{error:sf};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 tS({returnPreviousValues:t,drawDefinition:e,itemSubTypes:r,itemType:n}){if(!e)return{error:sn};if(!e.timeItems)return{info:ve};let{timeItem:o,previousItems:i,info:s}=en({element:e,returnPreviousValues:t,itemSubTypes:r,itemType:n});return o&&{timeItem:o,previousItems:i}||{info:s}}function gu({returnPreviousValues:t,itemSubTypes:e,itemType:r,event:n}){if(!n)return{error:Ot};if(!n.timeItems)return{info:ve};let{timeItem:o,previousItems:i,info:s}=en({returnPreviousValues:t,element:n,itemSubTypes:e,itemType:r});return o&&{timeItem:o,previousItems:i}||{info:s}}function td({returnPreviousValues:t,tournamentRecord:e,itemSubTypes:r,itemType:n}){if(!e)return{error:$};if(!e.timeItems)return{info:ve};let{timeItem:o,previousItems:i,info:s}=en({element:e,returnPreviousValues:t,itemSubTypes:r,itemType:n});return o&&{timeItem:o,previousItems:i}||{info:s}}function eS({returnPreviousValues:t,tournamentRecord:e,participantId:r,itemSubTypes:n,itemType:o}){if(!e)return{error:$};if(!r)return{error:ie};let i=yo({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}=en({element:i.participant,returnPreviousValues:t,itemSubTypes:n,itemType:o});return a&&{timeItem:a,previousItems:c}||{info:u}}var ok={[zr]:"groupParticipantIds",[ft]:"pairParticipantIds",[Ft]:"teamParticipantIds"},ik={[zr]:"groups",[Ft]:"teams"};function rS({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&&ck({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=ak({individualParticipantIds:g,participantCopy:l,participantMap:p,participantType:I,participantId:f});h.missingParticipantIds.length&&u.push(...h.missingParticipantIds)}if(n&&(p[f].participant.signedIn=sk(l)),o){let{ratings:h,rankings:S,seedings:T}=ga({participant:l});p[f].participant.seedings=T,p[f].participant.rankings=S,p[f].participant.ratings=h}(c||a)&&Jh({participant:p[f].participant,withISO2:a,withIOC:c})}if(t){let d=ht(t)?t:void 0;Mb({participantMap:p,template:d})}let m;return i&&(m=fu({participants:Object.values(p).map(({participant:d})=>d),participantsProfile:{convertExtensions:e},deepCopy:!1}).groupInfo),{missingParticipantIds:u,participantMap:p,groupInfo:m}}function sk(t){let{timeItem:e}=en({itemType:cc,element:t});return e?.itemValue===du}function ak({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[ok[n]].push(o),[Ft,zr].includes(n)){let{participantRoleResponsibilities:c,participantOtherName:u,participantName:p,participantId:m,teamId:d}=e,l=ik[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 ck({participantMap:t,participantId:e}){if(t[e])return;let r={walkoverWins:0,defaultWins:0,walkovers:0,defaults:0,losses:0,wins:0};t[e]={structureParticipation:{},potentialMatchUps:{},scheduleConflicts:{},scheduleItems:[],participant:{groupParticipantIds:[],pairParticipantIds:[],teamParticipantIds:[],seedings:{},rankings:{},ratings:{},groups:[],teams:[]},statistics:{},opponents:{},pairIdMap:{},matchUps:{},events:{},draws:{},counters:{[kt]:{...r},[xt]:{...r},[Ft]:{...r},...r}}}function Wo({participantsProfile:t,useParticipantMap:e,tournamentRecord:r,contextProfile:n,inContext:o}){if(e)return rS({...t,...n,tournamentRecord:r});let i=J(r.participants,!1,!0)||[];(t?.withIOC||t?.withISO2)&&i.forEach(a=>Jh({participant:a,...t}));let s;if((o||t?.withGroupings)&&i?.length&&({participantsWithGroupings:i,groupInfo:s}=fu({participantsProfile:t,deepCopy:!1,participants:i})),t?.withScaleValues&&i?.length)for(let a of i){let{ratings:c,rankings:u}=ga({participant:a});a.rankings=u,a.ratings=c}return{participants:i,groupInfo:s}}function Tt({onlySpecifiedPolicyTypes:t=!1,policyTypes:e=[],tournamentRecord:r,drawDefinition:n,structure:o,event:i}){if(!Array.isArray(e))return{error:VI};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===iu)?.value;if(p)for(let m of Object.keys(p))(t?e.includes(m):!e.length||e.includes(m))&&(s[m]=J(p[m],!1,!0))}}function _o({policyTypes:t=[],tournamentRecord:e,drawDefinition:r,structure:n,event:o}){if(!Array.isArray(t))return{error:VI};let{appliedPolicies:i}=Tt({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:Gc.message}}var nS="WALKOVER",WU="RETIRED",ed="COMPETITIVE",uc="ROUTINE",pc="DECISIVE",rd="winRatio";var uk={[Ti]:{policyName:"Competitive Bands Default",profileBands:{[pc]:20,[uc]:50}}},nd=uk;function Qn({policyDefinitions:t,tournamentRecord:e,contextProfile:r,drawDefinition:n,event:o}){let i={policies:{}};if(!r)return i;let s=_o({tournamentRecord:e,drawDefinition:n,event:o}).policyDefinitions;if(r.withCompetitiveness){let a=t?.[Ti]??s?.[Ti]??nd[Ti];i.policies[Ti]=a}return i}function ni({tournamentRecord:t,drawDefinition:e,policyType:r,structure:n,event:o}){if(!t)return{error:$};let{appliedPolicies:i}=Tt({tournamentRecord:t,drawDefinition:e,structure:n,event:o});return i?.[r]?{policy:i[r]}:{info:Gc?.message}}function Ea({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}=ni({policyType:Mo,tournamentRecord:t,event:n}),s=(t?mt({element:t,name:Ho}).extension:void 0)?.value,c=(n&&mt({name:Ho,element:n}).extension)?.value;return{scheduleTiming:{tournamentScheduling:s,eventScheduling:c,categoryName:e,categoryType:r,policy:o}}}function Xf({drawDefinition:t,attributes:e}){let{extension:r}=mt({element:t,name:$m}),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:$m,value:n},hp({drawDefinition:t,extension:r}),{entryProfile:n}}function Iu({drawDefinition:t}){let{extension:e}=mt({element:t,name:$m});return{entryProfile:e?.value||{}}}var rn="ALTERNATE",Jf="CONFIRMED",kr="DIRECT_ACCEPTANCE",od="FEED_IN",Zf="JUNIOR_EXEMPT",us="LUCKY_LOSER",tg="ORGANISER_ACCEPTANCE",id="QUALIFIER",pk="REGISTERED",eg="SPECIAL_EXEMPT",Gr="UNGROUPED",Ui="UNPAIRED",hu="WILDCARD",uo="WITHDRAWN",rg=[Jf,kr,Zf,tg,eg],jU=[od,us,id],oi=[Jf,kr,od,Zf,tg,eg,hu],Qr=[Jf,kr,Zf,us,id,tg,eg,hu],YU=[rn,Jf,kr,od,Zf,us,tg,id,pk,eg,Gr,Ui,hu,uo],Rb={ALTERNATE:rn,CONFIRMED:Jf,DIRECT_ACCEPTANCE:kr,DIRECT_ENTRY_STATUSES:oi,DRAW_SPECIFIC_STATUSES:jU,EQUIVALENT_ACCEPTANCE_STATUSES:rg,FEED_IN:od,JUNIOR_EXEMPT:Zf,LUCKY_LOSER:us,ORGANISER_ACCEPTANCE:tg,QUALIFIER:id,SPECIAL_EXEMPT:eg,STRUCTURE_SELECTED_STATUSES:Qr,UNGROUPED:Gr,UNPAIRED:Ui,VALID_ENTRY_STATUSES:YU,WILDCARD:hu,WITHDRAWN:uo};function ng({stage:t,drawDefinition:e}){let{entryProfile:r}=Iu({drawDefinition:e}),n=Object.keys(r).includes(t);if(!n&&zc.includes(t)){let o=[{[t]:{drawSize:void 0,alternates:!0}}];return Xf({drawDefinition:e,attributes:o}),!0}return n}function Cb({stage:t,drawDefinition:e}){let{entryProfile:r}=Iu({drawDefinition:e});return r[t]?.alternates||0}function bb({stage:t,drawDefinition:e}){let{entryProfile:r}=Iu({drawDefinition:e});return r[t]?.wildcardsCount||0}function oS({stage:t,drawDefinition:e,entryStatus:r}){return e.entries.reduce((n,o)=>o.entryStage===t&&o.entryStatus===r?n+1:n,0)}function Pi({provisionalPositioning:t,placementGroup:e,drawDefinition:r,stageSequence:n,entryStatuses:o,structureId:i,roundTarget:s,stages:a,stage:c}){let u=r.entries?.reduce((p,m)=>{let d=mt({name:Mn,element:m})?.extension?.value,l=c&&m.entryStage===c||a?.length&&m.entryStage&&a.includes(m.entryStage),f=!o||m.entryStatus&&o.includes(m.entryStatus),g=m.entryStageSequence??1;return l&&(!n||g===n)&&f&&(!s||!d||s===d)?p.concat(m):p},[])??[];if(i&&c===fe){let{playoffEntries:p,error:m}=mk({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 mk({provisionalPositioning:t,drawDefinition:e,structureId:r}){let n=[],o=(e.links??[]).find(i=>i.linkType===xn&&i.target.structureId===r);if(o){let{finishingPositions:i,structureId:s}=o.source,{structure:a}=at({drawDefinition:e,structureId:s});a?.structureType===Ve&&(a.structures??[]).forEach(u=>{let p=u.positionAssignments??[],{structureId:m}=u,d=m,l=Object.assign({},...p.map(h=>{let{participantId:S}=h,T=mt({element:h,name:bo}).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:E}=S,P=T||t&&y,A=[...i??[]].sort(le).indexOf(P)+1;n.push({entryStage:fe,entryStatus:od,placementGroup:A,groupingValue:d,participantId:h,GEMscore:E})})})}return{playoffEntries:n}}function vb({stage:t,drawDefinition:e}){return oi.reduce((r,n)=>(oS({drawDefinition:e,entryStatus:n,stage:t})||0)+r,0)}function nn({provisionalPositioning:t,returnAllProxies:e,drawDefinition:r,structureId:n,structure:o}){let i,s=[];o||({structure:o,error:i}=at({drawDefinition:r,structureId:n}));let a=Ct({structure:o}).positionAssignments;if(i||!o)return{seedAssignments:[],error:wt};n||(n=o.structureId);let{stage:c,stageSequence:u}=o,m=c===fe&&r&&Pi({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=HA;let f=o.seedLimit??o?.positionAssignments?.length;return{seedAssignments:s,stageSequence:u,seedLimit:f,stage:c,error:i}}function ii(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 Ep({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:Ep({item:r,drawDefinition:t,structure:e,event:n})||Ep({item:e,drawDefinition:t,structure:e,event:n})||ii(t)||ii(n)}}function Ob({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 si({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 iS({groupedOrder:t,roundPositionsCount:e}){if(!t||t?.length<=e)return t;let n=Ee(t,t.length/e).map(i=>i.reduce((s,a)=>s+a)),o=n.slice().sort(le);return n.map(i=>o.indexOf(i)+1)}function og(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(og):!1}function Ke({matchUps:t=[],interpolate:e}){if(!Vr(t))return{roundMatchUps:[],error:V};let r=t.reduce((d,l)=>{let f=typeof l.roundNumber=="string"?dt(l.roundNumber):l.roundNumber;return!l.roundNumber||d.includes(f)?d:d.concat(f)},[]).sort(le).map(d=>{let l=t.filter(h=>h.roundNumber===d),g=l.find(({matchUpType:h})=>h===Wt)?l.filter(({matchUpType:h})=>h===Wt):l,I=h=>h.sort((S,T)=>le(S.roundPosition,T.roundPosition));return{[d]:I(g)}}),n=t.reduce((d,l)=>{let f=typeof l.roundNumber=="string"?dt(l.roundNumber):l.roundNumber;return d[f]||(d[f]=nt({abbreviatedRoundName:l.abbreviatedRoundName,finishingRound:l.finishingRound,roundName:l.roundName})),d},{}),o=Object.assign({},...r);if(e){let d=Math.max(...Object.keys(o).map(f=>dt(f)).filter(f=>!isNaN(f))),l=o[d]?.length;if(l>1&&_n(l)){let f=d+1,g=f+l/2;tt(f,g).forEach((h,S)=>{o[h]=tt(0,l/(2+S*2)).map(()=>({}))})}}let i=0,s=Object.assign({},...Object.keys(o).map(d=>{let l=o[d]?.length,f=o[d]?.filter(I=>!se.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=>dt(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(le),I=Ee(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=Ee(I,h),T=l.map(y=>{let{roundPosition:E}=y,P=[...y.drawPositions||[],void 0,void 0].slice(0,2);if(!E)return P;let A=P?.filter(Boolean)||[];if(!A?.length)return[void 0,void 0];if(d<3&&A?.length===2)return P?.slice().sort(le);let U=jt(I,A).length!==A?.length;if(A?.length&&U)return A?.length===1?[A[0],void 0]:P?.slice().sort(le);let N=(E-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})=>!_n(d));return{hasNoRoundPositions:t.some(d=>!d.roundPosition),roundsNotPowerOf2:p,maxMatchUpsCount:i,roundMatchUps:o,roundNumbers:u,roundProfile:s,...C}}function sd(t){if(!Array.isArray(t))return"";let e=t.filter(Zt);return e.length?pt([Math.min(...e),Math.max(...e)]).join("-"):""}function _b({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:xi,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=si({structureId:m,matchUpsMap:r}),f=Ke({matchUps:d}).roundProfile;return{[m]:f}})),c=si({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,E=S[l]?.matchUpsCount;if(!E)return;let P=E?T.length/E:0,A=T.length/P,U=T.slice(),N=iS({roundPositionsCount:A,groupedOrder:g}),D=N?.length||1;if(D<=A){let v=T.length/D,O=Ee(U,v);f===fi&&O.forEach(x=>x.reverse()),U=N?.length&&N?.map(x=>O[x-1]).flat()||U}let M=Ee(U,P);if(I){let v=tt(0,I.interleave).map(()=>{}),O=tt(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]=sd(v))})}),{sourceDrawPositionRanges:p}}function sS({drawDefinition:t}){if(typeof t!="object")return{error:ma};let e={},{structures:r=[],links:n=[]}=t||{},o=r.reduce((s,a)=>{let{stage:c}=a;return s[c]?s[c].push(a):s[c]=[a],s},{});for(let s of Object.keys(o)){let a=o[s].find(({stageSequence:p})=>p===1);if(!a)continue;let{structureId:c}=a;i({aggregator:{},targetRound:0,exitProfiles:e,exitProfile:"0",structureId:c,stage:s})}return{exitProfiles:e};function i({exitProfiles:s,exitProfile:a,structureId:c,targetRound:u,aggregator:p,stage:m}){s[c]||(s[c]=[]),a==="0"&&[qe,fe].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 xb({drawDefinition:t,roundProfile:e,structureId:r,matchUpsMap:n}){if(!t)return{error:Z};if(!r)return{error:Ur};if(!e){let c=si({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=Ee(p,p.length/u),d=m.map(sd),l=m.map(S=>S.map(T=>T-i)).map(sd),f=s.map(S=>{if(S>c)return;let T=e?.[S]?.drawPositions??[];return Ee(T,T.length/u)}).filter(Boolean),g=tt(0,u).map(S=>f.map(T=>T[S]).flat().filter(Boolean).sort(le)).map(S=>pt(S)),I=g.map(S=>SC(S).map(sd).join(", ")),h=Object.assign({},...tt(0,u).map(S=>({[S+1]:{firstRoundDrawPositionsRange:d[S],firstRoundOffsetDrawPositionsRange:l[S],possibleDrawPositions:g[S],drawPositionsRange:I[S]}})));return{[c]:h}}))}}function ad({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!==Vi)&&!r?.structures&&t&&o}function pr({structure:t}){if(!t)return!1;let e=t.matchUps||t.roundMatchUps&&Object.values(t.roundMatchUps).flat(),r=!!e?.find(o=>o?.roundPosition),n=!!e?.find(o=>o?.drawPositions?.length);return!t?.structures&&t?.stage!==$e&&(!e.length||!r&&!n)}var ig={[Ia]:{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:{[rt]:"",[fe]:"P",[ct]:"Q",[qe]:"C"}}},wb=ig;function Lb({roundNamingPolicy:t,drawDefinition:e,structure:r,matchUps:n}){let{roundProfile:o,roundMatchUps:i}=Ke({matchUps:n}),{structureAbbreviation:s,stage:a}=r,c=pr({structure:r}),u=ad({structure:r}),p=r.structures,m={},d=ig[Ia],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,P=(t?.namingConventions||d.namingConventions).round,A=a&&a!==rt?a[0]:"",U=t?.stageConstants||d.stageConstants,N=a&&U?.[a]||A,D=`${I}${N}${g}`,M=o?Object.keys(o):[],R=l&&U?.[ct]?`${U?.[ct]}-`:"";if(p||c||u)Object.assign(m,...M.map(b=>{let v=`${R}${P} ${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,w=b?.[o?.[v].finishingRound]||b&&`${y}${F}`||h[O]||`${y}${F}`,L=x?`-${T}`:"",G=`${w}${L}`,k=[D,s,G].filter(Boolean).join("-"),W=`${S[O]||`${y}${F}`}${L}`,q=[D,s,W].filter(Boolean).join("-");return{[v]:{abbreviatedRoundName:q,roundName:k}}}))}return{roundNamingProfile:m,roundProfile:o,roundMatchUps:i}}var dk=(t,e)=>(t||0)+(e||0);function aS(t,e){let r=Array.isArray(t)?t[0]:t;return isNaN(r)&&nS||r<=e[pc]&&pc||r<=e[uc]&&uc||ed}function cS({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(dk)&&(r[n[0]>n[1]?0:1]+=1),{sets:e,games:r,score:t}}function lk(t){let e=Math.min(...t.games),r=Math.max(...t.games);return Math.round(e/r*100)}function uS(t){return t.map(lk).sort().map(e=>parseFloat(e.toFixed(2)))}function Su({tournamentRecord:t,profileBands:e,matchUp:r}){if(!r)return{error:Tr};let{score:n,winningSide:o}=r;if(!o)return{error:V};let i=!e&&t&&ni({policyType:Ti,tournamentRecord:t}).policy,s=e||i?.profileBands||nd[Ti].profileBands,a=cS({score:n}),c=uS([a]),u=aS(c,s),p=Array.isArray(c)?c[0]:c;return{...C,competitiveness:u,pctSpread:p}}function pS({matchUp:t}){if(!t)return{error:Tr};if(t&&!t.sides)return{error:lr};if(t&&!t.hasContext)return{error:Bc};let e=(t.sides??[])?.map(a=>a?.participantId).filter(Boolean),r=t.sides?.filter(a=>a.participant?.participantType===At).map(a=>a.participantId).filter(Boolean)??[],o=((t.sides??[])?.map(a=>a.participant?.individualParticipants).filter(Boolean)??[]).map(a=>(a??[]).map(c=>c?.participantId).filter(Boolean)),i=[...r,...o.flat()].filter(Boolean)??[],s=pt(i.concat(e)).filter(Boolean)??[];return{nestedIndividualParticipantIds:o,allRelevantParticipantIds:s,individualParticipantIds:i,sideParticipantIds:e,...C}}var cd="CHECK_IN",ud="CHECK_OUT",fk="SCHEDULE",ji="SCHEDULE.ASSIGNMENT.VENUE",po="SCHEDULE.ALLOCATION.COURTS",jo="SCHEDULE.ASSIGNMENT.COURT",Up="SCHEDULE.COURT.ORDER",Yi="SCHEDULE.DATE",gk="COMPLETED.DATE",pd="HOME_PARTICIPANT_ID",sg="SCHEDULE.ASSIGN.OFFICIAL",qi="SCHEDULE.TIME.SCHEDULED",xo="SCHEDULE.TIME.START",$i="SCHEDULE.TIME.STOP",Di="SCHEDULE.TIME.RESUME",Ni="SCHEDULE.TIME.END",Pp="SCHEDULE.TIME.MODIFIERS",Fb="TO_BE_ANNOUNCED",kb="NEXT_AVAILABLE",Gb="FOLLOWED_BY",Vb="AFTER_REST",Bb="RAIN_DELAY",Ik="NOT_BEFORE",mS=[Fb,kb,Gb,Vb,Bb],hk="ELIGIBILITY",Sk="REGISTRATION",Tk="SUSPENSION",yk="MEDICAL",Ak="PENALTY",qU="SCALE",$U="RATING",KU="RANKING",ag="SEEDING",wo="PUBLISH",Rr="PUBLIC",Lo="STATUS",Ek="MODIFICATION",Uk="RETRIEVAL",Pk="other",Hb={MUTUALLY_EXCLUSIVE_TIME_MODIFIERS:mS,AFTER_REST:Vb,ALLOCATE_COURTS:po,ASSIGN_COURT:jo,ASSIGN_OFFICIAL:sg,ASSIGN_VENUE:ji,CHECK_IN:cd,CHECK_OUT:ud,COMPLETED_DATE:gk,COURT_ORDER:Up,ELIGIBILITY:hk,END_TIME:Ni,FOLLOWED_BY:Gb,MEDICAL:yk,MODIFICATION:Ek,NEXT_AVAILABLE:kb,NOT_BEFORE:Ik,OTHER:Pk,PENALTY:Ak,PUBLIC:Rr,PUBLISH:wo,RANKING:KU,RATING:$U,RAIN_DELAY:Bb,REGISTRATION:Sk,RESUME_TIME:Di,RETRIEVAL:Uk,SCALE:qU,SCHEDULE:fk,SCHEDULED_DATE:Yi,SCHEDULED_TIME:qi,SEEDING:ag,START_TIME:xo,STATUS:Lo,STOP_TIME:$i,SUSPENSION:Tk,TIME_MODIFIERS:Pp,TO_BE_ANNOUNCED:Fb};function ps({matchUp:t}){if(!t)return{error:Tr};if(!t.hasContext)return{error:Bc};if(!t.sides||t.sides.filter(Boolean).length!==2)return{error:lr};let{nestedIndividualParticipantIds:e,allRelevantParticipantIds:r,sideParticipantIds:n}=pS({matchUp:t}),i=(t.timeItems??[]).filter(u=>u?.itemType&&[cd,ud].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===cd);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 de=t=>e=>{let r=ht(e)&&e?.matchUpType||Vt(e)&&e;return r&&MI[t].includes(r)};function Dp(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 Np(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 dS({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 Wb({tournamentScheduling:t,eventScheduling:e,averageMinutes:r,defaultTiming:n,matchUpFormat:o,categoryName:i,categoryType:s,policy:a}){let c=e?.matchUpRecoveryTimes&&Np({...e,averageMinutes:r,matchUpFormat:o}),u=t?.matchUpRecoveryTimes&&Np({...t,averageMinutes:r,matchUpFormat:o}),p=a?.matchUpRecoveryTimes&&Np({...a,averageMinutes:r,matchUpFormat:o}),m=[c,u,p,a?.defaultTimes?.recoveryTimes,n?.recoveryTimes];return dS({categoryName:i,categoryType:s,timesBlockArray:m})}function jb({matchUpFormat:t,categoryName:e,categoryType:r,defaultTiming:n,tournamentScheduling:o,eventScheduling:i,policy:s}){let a=i?.matchUpAverageTimes&&Dp({...i,matchUpFormat:t}),c=o?.matchUpAverageTimes&&Dp({...o,matchUpFormat:t}),u=s?.matchUpAverageTimes&&Dp({...s,matchUpFormat:t}),p=[a,c,u,s?.defaultTimes?.averageTimes,n?.averageTimes];return dS({categoryName:e,categoryType:r,timesBlockArray:p})}var zU="DOUBLES_SINGLES",QU="SINGLES_DOUBLES",mo="total",lS="participantConflict",Ua="matchUpConflict",XU="ISSUE_IDS",mc="CONFLICT",dc="WARNING",fS="ERROR",gS="ISSUE",cg="STATE",Yb={SINGLES_DOUBLES:QU,DOUBLES_SINGLES:zU,TOTAL:mo,CONFLICT_MATCHUP_ORDER:Ua,CONFLICT_PARTICIPANTS:lS,SCHEDULE_ISSUE_IDS:XU,SCHEDULE_CONFLICT:mc,SCHEDULE_WARNING:dc,SCHEDULE_ERROR:fS,SCHEDULE_ISSUE:gS,SCHEDULE_STATE:cg};function Tu({defaultAverageMinutes:t=90,defaultRecoveryMinutes:e=0,tournamentRecord:r,matchUpFormat:n,categoryName:o,categoryType:i,eventType:s,event:a}){if(!r)return{error:$};s=s??a?.eventType??ks;let c={averageTimes:[{minutes:{default:t}}],recoveryTimes:[{minutes:{default:e}}]},{scheduleTiming:u}=Ea({tournamentRecord:r,categoryName:o,categoryType:i,event:a}),p={...u,matchUpFormat:n,categoryType:i,defaultTiming:c};return Mp({eventType:s,timingDetails:p})}function Mp({timingDetails:t,eventType:e}){let r=jb(t),n=Object.keys(r?.minutes||{}),o=r?.minutes&&(n?.includes(e)&&r.minutes[e]||r.minutes.default),i=Wb({...t,averageMinutes:o}),s=Object.keys(i?.minutes||{}),a=i?.minutes&&(s?.includes(e)&&i.minutes[e]||i.minutes.default),c=de(ks)(e)?QU:zU,u=i?.minutes&&(s?.includes(c)&&i.minutes[c]||a);return{averageMinutes:o,recoveryMinutes:a,typeChangeRecoveryMinutes:u}}function JU(t){return t.createdAt?new Date(t.createdAt).getTime():0}function Yo({timeItems:t,itemType:e}){let r=t.filter(o=>o&&o.itemType===e).sort((o,i)=>JU(o)-JU(i)).pop(),n=r&&JU(r);return{itemValue:r?.itemValue,timeStamp:n}}function IS({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Yo({timeItems:r?.timeItems||[],itemType:qi});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{scheduledTime:n}:e}function Ws({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Yo({timeItems:r?.timeItems||[],itemType:Yi});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{scheduledDate:n}:e}function Rp(t){if(JI.test(t)){let e=Af();return new Date(`${e}T${t}`)}else return new Date(t)}function qb({matchUp:t}){if(!t)return{error:Tr};if(!t.timeItems)return{error:sf};let e=t.timeItems.filter(n=>[xo,$i,Di,Ni].includes(n?.itemType)).sort((n,o)=>Rp(n.itemValue).getTime()-Rp(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 xo:i=0;break;case Ni:if(n.lastValue&&[xo,Di].includes(n.lastType)){let u=Rp(o.itemValue).getTime()-Rp(n.lastValue).getTime();i=n.milliseconds+u}else i=n.milliseconds;break;case $i:if([xo,"SCHECULE.TIME.RESUME"].includes(n.lastType)){let u=Rp(o.itemValue).getTime()-Rp(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([xo,Di].includes(r.lastType)){let n=new Date().getTime()-Rp(r.lastValue).getTime();r.milliseconds+=n}return{milliseconds:r.milliseconds,time:Dk(r.milliseconds),relevantTimeItems:e}}function Dk(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 $b({matchUp:t}){let e=t?.timeItems||[],r=i=>i.createdAt?new Date(i.createdAt).getTime():0;return{startTime:e.reduce((i,s)=>{let a=s.itemType===xo&&s;return a&&(!i||r(a)<r(i))?a:i},void 0)?.itemValue}}function lc(t){let{disableNotice:e,venue:r,context:n}=t;if(typeof r!="object")return{error:V};let o=Mr(t);r.venueId||(r.venueId=Mt());let i;for(let s of Object.values(o)){let a=Nk({disableNotice:!0,tournamentRecord:s,context:n,venue:r});if(a?.error)return a;i=a.venue}return e||lt({topic:$h,payload:{venue:r}}),nt({...C,venue:i})}function Nk({tournamentRecord:t,disableNotice:e,context:r,venue:n}){return t?n?(t.venues||(t.venues=[]),n.venueId||(n.venueId=Mt()),t.venues.reduce((i,s)=>i||s.venueId===n.venueId,void 0)?{error:UE}:(r&&Ut({element:n,extension:{value:r,name:UU}}),t.venues.push(n),e||lt({payload:{venue:n,tournamentId:t.tournamentId},topic:$h}),{...C,venue:J(n)})):{error:st,info:"missing venue"}:{error:$}}function qo({tournamentRecords:t,tournamentRecord:e,venueId:r}){if(!e)return{error:$};if(!r)return{error:ti};let o=(e.venues??[]).reduce((i,s)=>s.venueId===r?s:i,void 0);if(!o&&t){let s=(au({tournamentRecords:t}).linkedTournamentIds??[])[e.tournamentId];for(let a of s){let c=t[a],u=qo({tournamentRecord:c,venueId:r});if(u.success&&u.venue)return lc({tournamentRecord:e,venue:u.venue}),{...C,venue:o}}}return o?{...C,venue:o}:{error:ki}}function hS({convertExtensions:t,...e}){let{tournamentRecords:r,tournamentRecord:n,venueId:o}=e,i=qo({tournamentRecords:r,tournamentRecord:n,venueId:o});return J(i,t,!0)}function ms({tournamentRecords:t,tournamentRecord:e,courtId:r}){if(!e)return{error:$};if(!r)return{error:wi};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=(au({tournamentRecords:t}).linkedTournamentIds??[])[e.tournamentId];for(let c of a){let u=t[c],p=ms({tournamentRecord:u,courtId:r});if(p.success)return p.venue&&lc({tournamentRecord:e,venue:p.venue}),{...C,court:o,venue:i}}}return _({result:{error:_s},stack:n})}function SS(t){return J(ms(t),!1,!0)}function md({tournamentRecord:t,internalUse:e,courtId:r}){if(!t)return{error:$};if(!r)return{error:wi};let n=ms({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 fc(t){let e=et(t,[{[ne]:!0},{venueId:!0,[fn]:ti}]);if(e.error)return e;let{tournamentRecord:r,venueId:n}=t,o=qo({tournamentRecord:r,venueId:n});if(o.error)return o;let s=(o.venue?.courts??[]).map(u=>(({courtInfo:p})=>({...p}))(md({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 Kb({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===Ni&&s;return a&&(!i||r(a)>r(i))?a:i},void 0)?.itemValue}}function Ht({event:t,eventId:e}){if(!t)return{error:Ot};let n=mt({name:cn,element:t})?.extension,o=e?J(n?.value,!1,!0):n?.value;return e&&t.drawDefinitions?.forEach(i=>{o?.flights?.forEach(s=>{s.drawId===i.drawId&&Object.assign(s,{drawDefinition:i})})}),{flightProfile:o}}function 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:Cr},context:{drawId:n,eventId:r},stack:o})}}function dd(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:Tr};if(o&&!p.matchUpType&&!t.matchUpType&&(e||i)&&p.drawId){let P=t.drawDefinition||e?.drawDefinitions?.find(U=>U.drawId===p.drawId);!P&&i&&({drawDefinition:P,event:e}=ze({drawId:p.drawId,tournamentRecord:i}));let A=p.structureId&&P?.structures?.find(({structureId:U})=>U===p.structureId);r=t.matchUpType||A?.matchUpType||P?.matchUpType||e?.eventType!==_e&&e?.eventType}let{milliseconds:m,time:d}=qb({matchUp:p}),{startTime:l}=$b({matchUp:p}),{endTime:f}=Kb({matchUp:p}),g,{eventIds:I,drawIds:h}=n??{};if((!I||I.includes(p.eventId))&&(!h||h.includes(p.drawId))){let P=Q=>Q.createdAt?new Date(Q.createdAt).getTime():0,A=new Map,U=p.timeItems?.toSorted((Q,ut)=>P(Q)-P(ut))??[];for(let Q of U)A.set(Q.itemType,Q.itemValue);let N=A.get(pd),D=A.get(po),M=A.get(qi),R=A.get(Pp),b=A.get(Yi),v=A.get(sg),O=A.get(Up),x=A.get(ji),F=A.get(jo),w,L,G,k,H,W=p.matchUpType??r;if(a&&M&&o&&W){let Q={matchUpFormat:p.matchUpFormat??c,...a};({averageMinutes:L=0,recoveryMinutes:G=0,typeChangeRecoveryMinutes:k=0}=Mp({timingDetails:Q,eventType:W})),(L||G)&&(w=f?Yr(Qt(f),G):Yr(M,L+G)),k&&(H=f?Yr(Qt(f),k):Yr(M,L+k))}!b&&M&&(b=Pt(M));let q=_m({scheduledDate:b,scheduledTime:M}),Y={},B=(i&&x&&fc({tournamentRecord:i,venueId:x}))?.venueData||{};x&&(Y[x]=B);let{venueName:K,venueAbbreviation:X,courtsInfo:j}=B,z=(F&&j?.find(Q=>Q.courtId===F))?.courtName;for(let Q of D||[]){if(!i)break;Q.venueId&&!Y[Q.venueid]&&(Y[Q.venueId]=fc({venueId:Q.venueId,tournamentRecord:i})?.venueData);let ut=Y[Q.venueId];Q.venueName=ut?.venueName;let it=ut?.courtsInfo?.find(Et=>Et.courtId===Q.courtId);Q.courtName=it?.courtName}g=nt({typeChangeTimeAfterRecovery:H,timeAfterRecovery:w,scheduledDate:b,scheduledTime:M,isoDateString:q,homeParticipantId:N,venueAbbreviation:X,allocatedCourts:D,timeModifiers:R,venueName:K,venueId:x,courtOrder:O,courtName:z,courtId:F,official:v,typeChangeRecoveryMinutes:k,recoveryMinutes:G,averageMinutes:L,milliseconds:m,startTime:l,endTime:f,time:d})}else g=nt({milliseconds:m,startTime:l,endTime:f,time:d});let{scheduledDate:S}=Ws({matchUp:p}),{scheduledTime:T}=IS({matchUp:p});if(s&&u?.displaySettings?.draws){let P=u.displaySettings.draws,A=(P?.[p.drawId]??P?.default)?.scheduleDetails;if(A){let U=(A.find(N=>S&&N.dates?.includes(S))??A.find(N=>!N.dates?.length))?.attributes;if(U){let N=Object.assign({},...Object.keys(g).map(D=>({[D]:!0})),U);g=Hi({source:g,template:N})}}}let E=p.matchUpStatus&&se.includes(p.matchUpStatus)&&(Pt(f)||Pt(S)||Pt(T))||void 0;return{schedule:g,endDate:E}}function zb({drawPositions:t,roundProfile:e,roundNumber:r}){let n=[void 0,void 0];if(vI(t))return{orderedDrawPositions:n,displayOrder:n};let o=e?.[r],s=o?.pairedDrawPositions?.find(c=>ke(c||[],t.filter(Boolean)))??n,a=o?.feedRound;if(bI(t)){let c=[...t].sort(le);return{orderedDrawPositions:c.length===2?c:s,displayOrder:a?c:s}}if(a){let u=[t.find(p=>!isNaN(dt(p))),void 0];return{orderedDrawPositions:u,displayOrder:u}}return{orderedDrawPositions:s,displayOrder:s}}function Cp({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:$};if(!Array.isArray(r)||r.length>2)return{error:wr};if(!r.length)return _({result:{error:Do},stack:n});t=t??e?.participants??[];let o=t.filter(a=>a.participantType===ft&&jt(r,a.individualParticipantIds).length===r.length&&a.individualParticipantIds.length===r.length),i=o[0];if(!i)return _({result:{error:re},stack:n});let s=J(o.slice(1),!1,!0);return{participant:J(i),duplicatedPairParticipants:s,...C}}function ds({drawDefinition:t,participantId:e}){if(typeof t!="object")return{error:Z};if(typeof e!="string")return{error:ie};let{extension:r}=mt({element:t,name:Co});return{lineUp:(r?.value||{})[e]}}function Qb({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}=Cp({collectionPosition:r,collectionId:s,lineUp:d});if(c===xt){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||ds({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||ds({participantId:d,drawDefinition:i})?.lineUp;return u({attribute:m,lineUp:g,teamParticipant:f})}).filter(Boolean)||{};return{drawPositionCollectionAssignment:Object.assign({},...p)}}function ld(t){let e=et(t,[{[Ln]:!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===At&&kt||s===ft&&xt||s===Ft&&Ft||void 0}return{matchUpType:n}}function Xb({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?Mk({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 Mk({displaySideNumber:t,seedAssignments:e,participantId:r,assignment:n,sideNumber:o}){let i={drawPosition:n.drawPosition,displaySideNumber:t,sideNumber:o};if(r){let s=Rk({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 Rk({seedAssignments:t,participantId:e}){return t?.find(r=>!r.seedProxy&&r.participantId===e)}function ZU({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:E,scoringActive:P,matchUpTieId:A,isRoundRobin:U,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:w,stage:L,stageSequence:G}=M,{drawId:k,drawName:H,drawType:W}=y??{},q=O?.collectionDefinitions,Y=b.collectionId&&q?.find(ae=>ae.collectionId===b.collectionId),B=b.collectionId?Y?.matchUpFormat:b.matchUpFormat??M?.matchUpFormat??y?.matchUpFormat??v?.matchUpFormat,K=b.matchUpType||Y?.matchUpType||M?.matchUpType||y?.matchUpType||!de(_e)(v?.eventType)&&v?.eventType,X=l?Nt:b.matchUpStatus,{schedule:j,endDate:ot}=dd({scheduleVisibilityFilters:t,afterRecoveryTimes:s,tournamentRecord:p,usePublishState:g,scheduleTiming:S,drawDefinition:y,matchUpFormat:B,publishStatus:E,matchUpType:K,matchUp:b,event:v}),z=m??b.drawPositions??[],{collectionPosition:Q,collectionId:ut,roundPosition:it}=b,Et=b.roundNumber??c.roundNumber,_t=ut?Qb({tournamentParticipants:r,positionAssignments:n,collectionPosition:Q,participantMap:I,drawDefinition:y,drawPositions:z,collectionId:ut,sideLineUps:D,matchUpType:K}):void 0,Ae=u?.[Et]?.roundName||c.roundName,$t=u?.[Et]?.abbreviatedRoundName||c.abbreviatedRoundName,Se=N?.[Et]?.feedRound,Or=N?.[Et]?.preFeedRound,pn=N?.[Et]?.roundFactor,Ir=o?.[Et],Xe=it?Ir?.[it]:void 0,te=e?.[Et],Dt=Y?.category?{...R?.category||{},...Y.category}:R?.category??v?.category,ue=b.processCodes?.length&&b.processCodes||Y?.processCodes?.length&&Y?.processCodes||M?.processCodes?.length&&M?.processCodes||y?.processCodes?.length&&y?.processCodes||v?.processCodes?.length&&v?.processCodes||p?.processCodes,pe=T?.withCompetitiveness&&Su({...h,matchUp:b}),Fe=b.finishingPositionRange??c.finishingPositionRange,ee=L!==ct&&It(a)&&a+(Et||0),Je=ae=>nt(ae,void 0,!0),qt={...Je(R),...Je({matchUpFormat:K===_e?void 0:B,tieFormat:K!==_e?void 0:O,gender:Y?.gender??v?.gender,endDate:b.endDate??ot,discipline:v?.discipline,category:Dt,finishingPositionRange:Fe,abbreviatedRoundName:$t,drawPositionsRange:Xe,competitiveProfile:pe,structureName:w,stageSequence:G,drawPositions:z,matchUpStatus:X,processCodes:ue,isRoundRobin:U,matchUpTieId:A,preFeedRound:Or,matchUpType:K,roundFactor:pn,roundOffset:x,structureId:F,roundNumber:Et,roundOfPlay:ee,feedRound:Se,roundName:Ae,drawName:H,drawType:W,schedule:j,drawId:k,stage:L}),...J(Je(b),!0,!0)};if(B&&b.score?.scoreStringSide1){let ae=Ye(B),{bestOf:hr,finalSetFormat:_r,setFormat:Kt}=ae??{};(_r?.tiebreakSet||Kt?.tiebreakSet||Kt?.timed)&&(qt.score.sets=qt.score.sets.sort((De,fr)=>De.setNumber-fr.setNumber).map((De,fr)=>(fr+1===hr?(_r?.tiebreakSet||_r?.timed)&&(De.tiebreakSet=!0):(Kt?.tiebreakSet||Kt?.timed)&&(De.tiebreakSet=!0),De)))}if(Array.isArray(z)){let{orderedDrawPositions:ae,displayOrder:hr}=zb({drawPositions:z,roundProfile:N,roundNumber:Et}),_r=N?.[Et]?.feedRound,Kt=hr[0]!==ae[0],fr=ae.concat(void 0,void 0).slice(0,2).map((Ne,On)=>{let me=On+1,dr=Kt?3-me:me,es=Xb({..._t,positionAssignments:n,displaySideNumber:dr,seedAssignments:f,drawPosition:Ne,isFeedRound:_r,sideNumber:me}),Tn=b.sides?.find(Ku=>Ku.sideNumber===me),mi=it?(it-1)*2+On+1:void 0,ca=mi?te?.[mi]:void 0;return Je({sourceDrawPositionRange:ca,...Tn,...es})});Object.assign(qt,J({sides:fr},!0,!0))}if(r&&qt.sides){let ae=d?.[Bs],hr=Kt=>{let De=I?.[Kt]?.participant;return De&&Hi({template:ae?.participant,source:De})};if(qt.sides.filter(Boolean).forEach(Kt=>{if(Kt.participantId){let De=J(hr(Kt.participantId)||(r?Bo({policyDefinitions:d,participantId:Kt.participantId,tournamentParticipants:r,internalUse:!0,contextProfile:T}):void 0),void 0,!0);if(De){let fr,Ne;if(y?.entries){let On=y.entries.find(dr=>dr.participantId===Kt.participantId),me=v?.entries?.find(dr=>dr.participantId===Kt.participantId);fr=On?.entryStatus||me?.entryStatus,De.entryStatus=fr,On?.entryStage&&(Ne=On.entryStage,De.entryStage=Ne)}i!==!1?Object.assign(Kt,{participant:De}):Object.assign(Kt,{participant:{entryStage:Ne,entryStatus:fr}})}}if(Kt?.participant?.individualParticipantIds?.length&&!Kt.participant.individualParticipants?.length){let De=Kt.participant.individualParticipantIds.map(fr=>hr(fr)||(r?Bo({policyDefinitions:d,tournamentParticipants:r,internalUse:!0,contextProfile:T,participantId:fr}):void 0));i!==!1&&Object.assign(Kt.participant,{individualParticipants:De})}}),!qt.matchUpType){let{matchUpType:Kt}=ld({matchUp:qt});Kt&&Object.assign(qt,{matchUpType:Kt})}if(T?.inferGender&&(!qt.gender||qt.gender===Ar)&&qt.sides?.length===2&&qt.matchUpType!==_e){let Kt=qt.sides.map(De=>{if(de(kt)(qt.matchUpType))return De.participant?.person?.sex;if(De.participant?.individualParticipants?.length===2){let fr=pt(De.participant.individualParticipants.map(Ne=>Ne.person?.sex)).filter(Boolean);if(fr.length===1)return fr[0]}});if(Kt.filter(Boolean).length===2&&pt(Kt).length===1){let De=Kt[0];qt.inferredGender=De}}}if(qt.tieMatchUps){let ae=qt.matchUpStatus===Nt,hr=qt.sides?.map(({participant:_r,drawPosition:Kt,sideNumber:De,lineUp:fr})=>{let Ne=_r?.participantType===_e&&_r;return{teamParticipant:Ne&&nt({participantRoleResponsibilities:Ne.participantRoleResponsibilities,participantOtherName:Ne.participanOthertName,participantName:Ne.participantName,participantId:Ne.participantId,teamId:Ne.teamId}),drawPosition:Kt,sideNumber:De,lineUp:fr}});qt.tieMatchUps=qt.tieMatchUps.map(_r=>{let Kt=qt.matchUpId,fr={finishingPositionRange:qt.finishingPositionRange,abbreviatedRoundName:$t,roundNumber:Et,roundName:Ae};return ZU({tieDrawPositions:z,scheduleVisibilityFilters:t,sourceDrawPositionRanges:e,sideLineUps:hr,drawPositionsRanges:o,initialRoundOfPlay:a,roundNamingProfile:u,additionalContext:fr,appliedPolicies:d,isCollectionBye:ae,usePublishState:g,publishStatus:E,matchUpTieId:Kt,isRoundRobin:U,roundProfile:N,matchUp:_r,event:v,tournamentParticipants:r,positionAssignments:n,tournamentRecord:p,seedAssignments:f,participantMap:I,contextContent:h,scheduleTiming:S,contextProfile:T,drawDefinition:y,scoringActive:P,structure:M,context:R})})}let ar=qt.sides&&qt.sides.filter(ae=>ae?.participantId).length===2,Ze=!qt.winningSide;if(Object.assign(qt,{readyToScore:P&&ar&&Ze,hasContext:!0}),ar){let{allParticipantsCheckedIn:ae,checkedInParticipantIds:hr}=ps({matchUp:qt});Object.assign(qt,{allParticipantsCheckedIn:ae,checkedInParticipantIds:hr})}return Array.isArray(T?.exclude)&&T?.exclude.forEach(ae=>delete qt[ae]),qt}function Jb({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Yo({timeItems:r?.timeItems||[],itemType:po});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{allocatedCourts:J(n,!1,!0)}:e}function Zb({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Yo({timeItems:r?.timeItems||[],itemType:jo});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{courtId:n}:e}function tv({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Yo({timeItems:r?.timeItems||[],itemType:ji});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{venueId:n}:e}function Mi(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:E,tournamentIds:P,matchUpTypes:A,structureIds:U,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):[],w=Array.isArray(v)?v.filter(Boolean):[],L=Array.isArray(h)?h.filter(Boolean):[],G=Array.isArray(p)?p.filter(Boolean):[],k=Array.isArray(f)?f.filter(Boolean):[],H=Array.isArray(d)?d.filter(Boolean):[],W=Array.isArray(c)?c.filter(Boolean):[],q=Array.isArray(l)&&I?l.filter(Boolean):[],Y=Array.isArray(A)&&g?A.filter(Boolean):[],B=Array.isArray(D)?D.filter(Boolean):[],K=Array.isArray(R)?R.filter(Boolean):[],X=Array.isArray(a)&&a.filter(Boolean)||typeof u=="string"&&[u]||[],j=Array.isArray(S)&&S.filter(Boolean)||typeof T=="string"&&T.length&&[T]||[],ot=Array.isArray(P)?P.filter(Boolean):[],z=Array.isArray(M)?M.filter(Boolean):[],Q=Array.isArray(b)?b.filter(Boolean):[],ut=Array.isArray(U)?U.filter(Boolean):[];return e.filter(it=>{if(N&&!de(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)||w.length&&!w.includes(it.stage)||L.length&&!L.includes(it.stageSequence)||G.length&&(!it.collectionId||!G.includes(it.collectionId))||k.length&&(!it.roundName||!k.includes(it.roundName))||H.length&&(!it.roundNumber||!H.includes(it.roundNumber))||W.length&&(!it.roundPosition||!W.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)||Y.length&&(!it.matchUpType||!kc(Y,it.matchUpType))||X.length&&(!it.matchUpFormat||!X.includes(it.matchUpFormat)))return!1;if(j?.length){let{scheduledTime:Et}=IS({matchUp:it}),{scheduledDate:_t}=Ws({matchUp:it}),$t=Pt(Et)||_t;if(!j.find(Se=>qn(Se,$t)))return!1}if(B.length){let{courtId:Et}=Zb({matchUp:it}),{allocatedCourts:_t}=Jb({matchUp:it}),Ae=_t?.map(({courtId:$t})=>$t);if(!B.filter(Boolean).includes(Et)||Ae?.includes(Et))return!1}if(K.length){let{venueId:Et}=tv({matchUp:it});if(!K.filter(Boolean).includes(Et))return!1}if(E){if(ot.length&&!ot.includes(it.tournamentId)||z.length&&!z.includes(it.eventId)||Q.length&&!Q.includes(it.drawId)||ut.length&&!ut.includes(it.structureId))return!1;let Et=it.sides?.map(({participantId:_t})=>_t).filter(Boolean)??[];if(n&&Et.length<n||O.length&&!O.some(Ae=>Et.includes(Ae)))return!1}return!0})}function yt(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:di,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),E=!S?.length||S.includes(c.structureId),P=!s||!T?.length||T.includes(s.drawId);if(!y||!E||!P)return{collectionPositionMatchUps:g,roundMatchUps:I,matchUps:[]};i&&!d&&(d=Qn({tournamentRecord:r,contextProfile:i,drawDefinition:s}));let{appliedPolicies:A}=Tt({drawDefinition:s}),U={...t.tournamentAppliedPolicies,...A,...t.policyDefinitions},N=U?.scoring?.structures,D=c.stage&&N?.stage?.[c.stage],M=c.stageSequence&&D?.stageSequence?.[c.stageSequence],R=U?.scoring?.requireAllPositionsAssigned||D?.requireAllPositionsAssigned||M?.requireAllPositionsAssigned;f||(f=Me({drawDefinition:s,structure:c}));let{positionAssignments:b,allPositionsAssigned:v}=ge({structure:c}),O=!R||v,{seedAssignments:x}=nn({provisionalPositioning:e,drawDefinition:s,structure:c});m=m??x;let{structureId:F}=c;l=l||s&&sS({drawDefinition:s}).exitProfiles;let w=l?.[F],L=w?.length&&(w[0].split("-").map(B=>parseInt(B)).reduce((B,K)=>B+K)||0),G=!!c.structures,k=si({matchUpsMap:f,structureId:F,inContext:u}),H=U?.[Ia],W=Lb({roundNamingPolicy:H,drawDefinition:s,structure:c,matchUps:k}),{roundNamingProfile:q,roundProfile:Y}=W;if(I=W?.roundMatchUps??[],o&&(k=Mi({matchUps:k,...o,filterMatchUpTypes:!1,filterMatchUpIds:!1})),u){let{sourceDrawPositionRanges:B}=_b({drawDefinition:s,matchUpsMap:f,structureId:F}),K=s?xb({drawDefinition:s,roundProfile:Y,matchUpsMap:f,structureId:F}).drawPositionsRanges:void 0,X=t.tournamentParticipants,j=t.participantMap;!X?.length&&!j&&r&&({participants:X=[],participantMap:j}=Wo({participantsProfile:t.participantsProfile,useParticipantMap:t.useParticipantMap,policyDefinitions:t.policyDefinitions,tournamentRecord:r,contextProfile:i,inContext:u})),k=k.map(z=>ZU({scheduleVisibilityFilters:t.scheduleVisibilityFilters,hydrateParticipants:t.hydrateParticipants,afterRecoveryTimes:t.afterRecoveryTimes,usePublishState:t.usePublishState,scheduleTiming:t.scheduleTiming,publishStatus:t.publishStatus,sourceDrawPositionRanges:B,tournamentParticipants:X,positionAssignments:b,drawPositionsRanges:K,initialRoundOfPlay:L,roundNamingProfile:q,tournamentRecord:r,appliedPolicies:U,seedAssignments:m,contextContent:d,participantMap:j,contextProfile:i,drawDefinition:s,scoringActive:O,isRoundRobin:G,roundProfile:Y,structure:c,context:a,matchUp:z,event:p})),(k?.filter(z=>Array.isArray(z.tieMatchUps))).forEach(z=>{let Q=z.tieMatchUps;k=k.concat(...Q)}),n&&(k=Mi({processContext:!0,...n,matchUps:k}))}else(k?.filter(K=>Array.isArray(K.tieMatchUps))).forEach(K=>{let X=K.tieMatchUps;k=k.concat(...X)});return o&&(k=Mi({matchUps:k,...o,filterMatchUpTypes:!1,filterMatchUpIds:!1})),(o?.matchUpTypes||o?.matchUpIds)&&(k=Mi({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}=Ob({matchUps:k})),{collectionPositionMatchUps:g,roundMatchUps:I,isRoundRobin:G,roundProfile:Y,matchUpsMap:f,matchUps:k}}function ls({matchUp:t}){return t?se.includes(t?.matchUpStatus)||t?.winningSide:!1}function yu({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:E,context:P,event:A}){!E&&T&&({structure:E}=at({drawDefinition:I,structureId:T}));let U=yt({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:E,inContext:y,context:P,event:A}),N=[],D=[],M=[],R=[],b=[];if(U.error)return U;let{matchUps:v}=U,{assignedPositions:O}=ge({structure:E}),x=O?.filter(w=>w.participantId).map(w=>w.drawPosition),F;return v.filter(w=>{let L=u?.matchUpTypes?.length===1&&u.matchUpTypes[0]===Wt;return!(w.matchUpType!==Wt&&L)}).forEach(w=>{if(w.matchUpStatus===vr){N.push(w);return}w.matchUpType===Wt&&(F=!0);let L=!!w.collectionId,G=L&&w.sides?.every(K=>K.participantId),k=!L&&w.drawPositions?.filter(Boolean).length===2,H=!L&&w.drawPositions?.every(K=>x?.includes(K)),W=O?.filter(K=>K.bye).map(K=>K.drawPosition),q=!L&&w.drawPositions?.find(K=>W?.includes(K)),B=jh.includes(w.matchUpStatus)&&(G||k&&(!t||H));return q?b.push(w):ls({matchUp:w})?D.push(w):B?M.push(w):R.push(w)}),{includesTeamMatchUps:F,abandonedMatchUps:N,completedMatchUps:D,upcomingMatchUps:M,pendingMatchUps:R,byeMatchUps:b,structure:E}}function ev({drawDefinition:t,roundNumber:e,structureId:r}){if(!t)return{error:Z};if(!r)return{error:Ur};let{links:n}=js({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 TS({finishingPositions:t,linkCondition:e,linkType:r,source:n}){let o=n.find(i=>{let s=!i.source?.finishingPositions||!t||ke(t,i.source?.finishingPositions);return e===i.linkCondition&&s&&i.linkType===r});return[Kn,oo].includes(o?.linkType)&&!o?.source?.roundNumber?_({result:{error:V},stack:"getTargetLink",context:o}):o}function js({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 rv({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 yS({sourceRoundMatchUpCount:t,inContextDrawMatchUps:e,sourceRoundPosition:r,drawDefinition:n,targetLink:o}){if(!o)return{error:Bl};let{target:{structureId:i,feedProfile:s,groupedOrder:a,roundNumber:c,positionInterleave:u}}=o,{structure:p}=at({drawDefinition:n,structureId:i}),{positionAssignments:m}=Ct({structure:p}),l=(e?.filter(D=>D.structureId===p?.structureId)).filter(D=>D.roundNumber===c&&!D.matchUpTieId),f=l.length,g=tt(1,f+1),I=f/t,h=Math.ceil(I*r),S=1-r%2;if(u?.interleave&&I!==.5){let 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],E=iS({roundPositionsCount:g.length,groupedOrder:a}),P=E?.length||1;if(P<=g.length){let D=f/P,M=Ee(g,D);s===fi&&M.forEach(R=>R.reverse()),T=E?.length&&E?.map(R=>M[R-1]).flat()||T}s===En?y=T[h-1]:s===fi?((!E?.length||P>g.length)&&(h=l.length+1-h),y=T[h-1]):s===mp&&Pr()&&console.log(np,{feedProfile:s});let A=y&&l.reduce((D,M)=>M.roundPosition===y?M:D,void 0),U;A?.feedRound?(S=0,U=Math.min(...(A.drawPositions||[]).filter(Boolean))):U=A?.drawPositions?.length===2&&A?.drawPositions[S];let N=m?.find(({drawPosition:D})=>D===U);if(N){let{extension:D}=mt({element:N,name:Ym});if(D?.value)return{disabledDrawPosition:U}}return{matchUp:A,targetDrawPosition:U,matchUpDrawPositionIndex:S}}function mr({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===Bi?Ck({inContextDrawMatchUps:t,useTargetMatchUpIds:e,drawDefinition:n,structure:s,matchUp:i}):bk({matchUp:i})}function Ck({inContextDrawMatchUps:t,useTargetMatchUpIds:e,drawDefinition:r,structure:n,matchUp:o}){let{winnerMatchUpId:i,loserMatchUpId:s}=o,{links:a}=ev({roundNumber:o.roundNumber,structureId:n.structureId,drawDefinition:r}),c=a?.source,u=TS({source:c,linkType:Kn}),p=TS({linkCondition:wn,linkType:oo,source:c}),m=TS({source:c,linkType:oo}),d=p&&m;m||(m=p);let l=u?.target?.feedProfile,f=m?.target?.feedProfile,g=p?.target?.feedProfile,I,h,S,T,y,E,P,A,U,N;if(e&&(i||s)&&(P=i&&l!==dn&&t.find(({matchUpId:R})=>R===i),T=s&&f!==dn&&t.find(({matchUpId:R})=>R===s),P||T))return{matchUp:o,targetLinks:{loserTargetLink:m,winnerTargetLink:u},targetMatchUps:{loserMatchUp:T,winnerMatchUp:P}};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:E,targetDrawPosition:y,matchUp:T}=yS({targetLink:m,sourceRoundMatchUpCount:M,inContextDrawMatchUps:t,sourceRoundPosition:D,drawDefinition:r})),d&&g!==dn&&({matchUpDrawPositionIndex:S,targetDrawPosition:h,matchUp:I}=yS({targetLink:p,sourceRoundMatchUpCount:M,inContextDrawMatchUps:t,sourceRoundPosition:D,drawDefinition:r})),u&&!P&&l!==dn&&({matchUpDrawPositionIndex:U,targetDrawPosition:A,matchUp:P}=yS({targetLink:u,sourceRoundMatchUpCount:M,inContextDrawMatchUps:t,sourceRoundPosition:D,drawDefinition:r})),P||(N=N||t.filter(R=>R.structureId===n.structureId),{matchUp:P}=rv({structureMatchUps:N,matchUp:o})),nt({matchUp:o,targetLinks:{loserTargetLink:m,winnerTargetLink:u,byeTargetLink:p},targetMatchUps:{winnerMatchUpDrawPositionIndex:U,loserMatchUpDrawPositionIndex:E,byeMatchUpDrawPositionIndex:S,winnerTargetDrawPosition:A,loserTargetDrawPosition:y,byeTargetDrawPosition:h,winnerMatchUp:P,loserMatchUp:T,byeMatchUp:I},targetMatchUpIds:!!(i||s)})}function bk({matchUp:t}){return{targetLinks:{loserTargetLink:void 0,winnerTargetLink:void 0},targetMatchUps:{loserMatchUp:void 0,winnerMatchUp:void 0},matchUp:t}}function nv({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===gi){let{roundNumber:c}=n,u=c&&dt(c)+1,p=a.matchUps??[],{roundMatchUps:m}=Ke({matchUps:p});if(u&&m?.[u]){let d=[...s].sort(le).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=mr({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=tP({upcomingMatchUp:u}),d=tP({upcomingMatchUp:p});if(n.matchUpStatus!==Nt&&p?.matchUpStatus===Nt){let{matchUp:f}=ov({matchUp:p,drawDefinition:t,inContextDrawMatchUps:e})||{};d=f&&tP({upcomingMatchUp:f})||d}let l=n.schedule?.timeAfterRecovery;if(l&&(m?.schedule?.scheduledTime&&Yt(m.schedule.scheduledTime)<Yt(l)&&(r[m.matchUpId]=n.matchUpId,m.schedule.scheduleConflict=n.matchUpId),d?.schedule?.scheduledTime&&Yt(d.schedule.scheduledTime)<Yt(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===wn,I=vk(n);if(I.length){let h=Lf(u?.sides),S=Lf(p?.sides),y=I.find(({participantId:A})=>h.includes(A))?[]:I,P=I.find(({participantId:A})=>S.includes(A))?[]:I;p&&g&&P.length<2&&P.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)),P?.length&&p&&(c.targetMatchUpIds||(u=e.find(({matchUpId:A})=>A===p.matchUpId)),p.potentialParticipants||(p.potentialParticipants=[]),p.potentialParticipants.push(P))}}}}),Object.keys(r).length&&e.forEach(n=>{Object.keys(r).includes(n.matchUpId)&&(n.schedule.scheduleConflict=r[n.matchUpId])}),{scheduleConflictMatchUpIds:r}}function vk(t){return t?.sides?.map(({participant:e,participantId:r,qualifier:n})=>e||r&&{participantId:r}||n&&{qualifier:n}).filter(Boolean)||[]}function ov({matchUp:t,drawDefinition:e,inContextDrawMatchUps:r}){let{matchUpId:n,matchUpStatus:o,structureId:i}=t||{};if(!t||!i||t?.matchUpStatus===Xt)return{matchUp:t};if(o===Nt){let s;return t.winnerMatchUpId?s=r.find(({matchUpId:a})=>a===t.winnerMatchUpId):{winnerMatchUp:s}=mr({inContextDrawMatchUps:r,drawDefinition:e,matchUpId:n})?.targetMatchUps||{},ov({matchUp:s,drawDefinition:e,inContextDrawMatchUps:r})}return{matchUp:void 0}}function tP(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 ce(t){let e="getAllDrawMatchUps";Object.assign(t,{requireParticipants:!1});let r=Ys(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 Ys(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:E,event:P}=t,A=[],U=[],N=[],D=[],M=[];h&&!r&&(r=Qn({policyDefinitions:u,tournamentRecord:p,contextProfile:h,event:P}));let R;!e?.length&&p&&(e=p?.participants,(y||a?.withGroupings)&&e?.length&&({participantsWithGroupings:e,groupInfo:R}=fu({participants:e,participantsProfile:a})));let{structures:b}=gn({drawDefinition:S});if(!b)return{error:wt};n||(n=Me({drawDefinition:S}));let v=S&&sS({drawDefinition:S}).exitProfiles;b.forEach(F=>{let{byeMatchUps:w=[],pendingMatchUps:L=[],upcomingMatchUps:G=[],completedMatchUps:k=[],abandonedMatchUps:H=[]}=yu({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:E,event:P});A=A.concat(...H),U=U.concat(...k),N=N.concat(...G),D=D.concat(...L),M=M.concat(...w)});let O=F=>(!l&&!T&&!d||(l&&(F=Mi({matchUps:F,...l})),d&&(F=Mi({matchUps:F,...d,processContext:!0}))),F),x={abandonedMatchUps:O(A),completedMatchUps:O(U),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:w,completed:L,upcoming:G,pending:k,bye:H}=F,W=[].concat(...w&&A||[],...L&&U||[],...G&&N||[],...k&&D||[],...H&&M||[]);nv({inContextDrawMatchUps:W,drawDefinition:S})}return x}function Xn(t){let{participants:e=[],contextContent:r,participantMap:n}=t,{scheduleVisibilityFilters:o,tournamentAppliedPolicies:i,participantsProfile:s,afterRecoveryTimes:a,policyDefinitions:c,useParticipantMap:u,tournamentRecord:p,usePublishState:m,contextFilters:d,matchUpFilters:l,contextProfile:f,nextMatchUps:g,inContext:I,context:h,event:S}=t;if(!S)return{error:Ot};let{eventId:T,eventName:y,endDate:E,eventType:P,category:A,gender:U,matchUpFormat:N}=S??{},D={...h,...nt({indoorOutDoor:S.indoorOutdoor??p?.indoorOutdoor,surfaceCategory:S.surfaceCategory??p?.surfaceCategory,endDate:S.endDate??p?.endDate,tournamentId:p?.tournamentId,matchUpFormat:N,eventName:y,eventType:P,category:A,eventId:T,gender:U})};E&&(D.endDate=E),f&&!r&&(r=Qn({policyDefinitions:c,tournamentRecord:p,contextProfile:f,event:S}));let M;if(!e?.length&&!n&&p){let O=Wo({participantsProfile:s,useParticipantMap:u,policyDefinitions:c,tournamentRecord:p,contextProfile:f,inContext:I});n=O.participantMap,e=O.participants??[],M=O.groupInfo}let R=S.drawDefinitions??[],b=Ea({tournamentRecord:p,event:S}).scheduleTiming;return{matchUps:R.flatMap(O=>{let{matchUps:x}=ce({tournamentParticipants:e,tournamentAppliedPolicies:i,scheduleVisibilityFilters:o,context:D,participantsProfile:s,afterRecoveryTimes:a,policyDefinitions:c,tournamentRecord:p,usePublishState:m,contextFilters:d,contextProfile:f,drawDefinition:O,contextContent:r,matchUpFilters:l,participantMap:n,scheduleTiming:b,nextMatchUps:g,inContext:I,event:S});return x??[]}),groupInfo:M}}function ye(t){let e=et(t,[{tournamentRecord:!0}]);if(e.error)return e;if(!t?.tournamentRecord)return{error:$};let{participantMap:r,participants:n}=t,{scheduleVisibilityFilters:o,participantsProfile:i,afterRecoveryTimes:s,useParticipantMap:a,policyDefinitions:c,tournamentRecord:u,inContext:p=!0,usePublishState:m,contextProfile:d,matchUpFilters:l,contextFilters:f,nextMatchUps:g,context:I}=t,h=t.tournamentId??u.tournamentId,S=u?.events??[];n||({participants:n,participantMap:r}=Wo({participantsProfile:i,useParticipantMap:a,policyDefinitions:c,tournamentRecord:u,contextProfile:d,inContext:p}));let{appliedPolicies:T}=Tt({tournamentRecord:u}),y={...I,tournamentId:h,indoorOutDoor:u.indoorOutdoor,surfaceCategory:u.surfaceCategory,endDate:u.endDate},E=Qn({policyDefinitions:c,tournamentRecord:u,contextProfile:d});return{matchUps:S.flatMap(A=>(y.eventDrawsCount=A.drawDefinitions?.length??0,Xn({context:y,scheduleVisibilityFilters:o,tournamentAppliedPolicies:T,participantsProfile:i,afterRecoveryTimes:s,policyDefinitions:c,tournamentRecord:u,usePublishState:m,contextContent:E,contextFilters:f,contextProfile:d,matchUpFilters:l,participantMap:r,nextMatchUps:g,participants:n,inContext:p,event:A}).matchUps??[])).concat(...u.matchUps??[])}}function Un({scheduleVisibilityFilters:t,afterRecoveryTimes:e,participantsProfile:r,tournamentRecords:n,policyDefinitions:o,usePublishState:i,matchUpFilters:s,contextFilters:a,nextMatchUps:c,inContext:u}){if(typeof n!="object"||!Object.keys(n).length)return{error:Lt};let m=Object.keys(n).map(d=>{let l=n[d];return ye({scheduleVisibilityFilters:t,afterRecoveryTimes:e,participantsProfile:r,policyDefinitions:o,tournamentRecord:l,usePublishState:i,matchUpFilters:s,contextFilters:a,nextMatchUps:c,inContext:u}).matchUps??[]}).flat();return{...C,matchUps:m}}function Ri(t,e){return Ok(t,e)||(t?.stageSequence||0)-(e?.stageSequence||0)||t?.roundNumber&&e.roundNumber&&t?.roundNumber-e?.roundNumber||(t?.roundPosition??0)-(e?.roundPosition??0)}function Ok(t,e){return(Gs[t?.stage]||0)-(Gs[e?.stage]||0)}function ir(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:E,eventType:P,category:A,gender:U,matchUpFormat:N}=S??{},D={...h,surfaceCategory:S?.surfaceCategory??p?.surfaceCategory,indoorOutDoor:S?.indoorOutdoor??p?.indoorOutdoor,matchUpFormat:N,eventType:P,eventName:y,category:A,eventId:T,endDate:E,gender:U},M;return!e?.length&&!r&&p&&({participants:e=[],participantMap:r,groupInfo:M}=Wo({participantsProfile:s,useParticipantMap:u,policyDefinitions:c,tournamentRecord:p,contextProfile:l,inContext:I})),l&&!n&&(n=Qn({policyDefinitions:c,tournamentRecord:p,contextProfile:l,drawDefinition:f,event:S})),{...ce({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 fs({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 eP=t=>e=>!t||typeof e!="object"?void 0:Array.isArray(t)&&t.map(r=>({[r]:fs({element:e,accessor:r})?.value}))||typeof t=="object"&&Object.keys(t).map(r=>({[r]:fs({element:e,accessor:r})?.value}))||(typeof t=="string"&&fs({element:e,accessor:t}))?.value,Br=eP;function Pa({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),E=a&&I!==1,P=1+t+(E?r??0:0),A=1,U=tt(P,s?P+S*2:y+P+A),N=y+A-S,D=l(U.slice(N)),M=l(U.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 Ki({inContextDrawMatchUps:t,drawDefinition:e,matchUpsMap:r}){if(!e)return{error:Z};let n={loserMatchUpIds:{},winnerMatchUpIds:{}};if(t||({matchUps:t,matchUpsMap:r}=ce({inContext:!0,drawDefinition:e,matchUpsMap:r})),!r?.drawMatchUps.some(i=>i.finishingPositionRange)&&e?.structures?.length===1&&!e?.structures[0].structures){let i=r?.drawMatchUps??[];Pa({matchUps:i})}return(t??[]).filter(({collectionId:i})=>!i).forEach(i=>{let{matchUpId:s,structureId:a}=i,c=mr({inContextDrawMatchUps:t,drawDefinition:e,matchUpId:s}),{winnerMatchUp:u,loserMatchUp:p}=c.targetMatchUps,m=u?.matchUpId,d=p?.matchUpId,f=si({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 on(t){let e=Mr(t),r=t.matchUps??[],n=t.drawIds??[],{includeParticipantDependencies:o,tournamentRecord:i,drawDefinition:s}=t;if(!Array.isArray(r))return{error:eo};if(!Array.isArray(n))return{error:sn};let a=t.matchUpIds?.length?t.matchUpIds:r.map(T=>T.matchUpId);if(!Array.isArray(a))return{error:ns};let c={},u={},p={},m={};i&&!Object.keys(e).length&&(e={[i.tournamentId]:i});let d=Object.values(e),f=d.reduce((T,y)=>T.concat(y.events??[]).map(E=>(E.drawDefinitions||[]).map(P=>P.links||[])).flat(1/0),[]).filter(({linkType:T})=>T===xn),g=r;if(f.length){g=Un({nextMatchUps:!0,tournamentRecords:e}).matchUps;let T=f.reduce((y,E)=>{let P=E.source?.structureId,A=E.target?.structureId;return P&&A&&(p[A]=P),P&&!y.includes(P)&&y.push(P),y},[]);for(let y of T)c[y]=[];for(let y of g??[]){let E=y.containerStructureId||y.structureId;T.includes(E)&&c[E].push(y.matchUpId)}}let I=T=>{u[T]||(u[T]={dependentMatchUpIds:[],participantIds:[],matchUpIds:[],sources:[]},m[T]=[])},h=(T,y)=>{u[T].matchUpIds.forEach(P=>{u[y].matchUpIds.push(P)}),u[y].matchUpIds.push(T),u[T].dependentMatchUpIds.push(y),o&&u[T].participantIds.forEach(P=>u[y].participantIds.push(P))},S=T=>{let y=Object.keys(c).length;for(let E of T||[]){let{matchUpId:P,winnerMatchUpId:A,loserMatchUpId:U}=E;if(!a.length||a.includes(P)){if(I(P),o){let{individualParticipantIds:M}=mu(E);u[P].participantIds=M}A&&(I(A),h(P,A),m[A].push(P)),U&&(I(U),h(P,U),m[U].push(P)),u[P].sources.push(m[P]);let N=m[P].map(M=>u[M].sources[0]).flat(),D=m[P].map(M=>u[M].sources[1]).flat();if(u[P].sources.push(N,D),y){let M=E.containerStructureId||E.structureId,R=p[M];if(c[R])for(let b of c[R])I(b),h(b,P),m[b].push(P)}}}};if(s)Ki({drawDefinition:s}),g?.length||(g=ir({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:E=[]})=>E.map(({drawId:P})=>P))).flat(1/0):[];T&&(n=T)}for(let T of n){let y=g?.filter(P=>P.drawId===T).sort(Ri);if(!y?.find(({roundPosition:P})=>!P)){let P=y?.find(({tournamentId:U})=>U),{drawDefinition:A}=ze({tournamentRecord:e[P?.tournamentId],drawId:T});A&&Ki({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 Da({matchUpStatus:t}){return Hh.includes(t)}function iv({matchUpStatus:t}){return Xm.includes(t)}function ug({matchUpStatus:t}){return Wh.includes(t)}function pg({matchUpStatus:t,winningSide:e,tieMatchUps:r,sides:n,score:o}){let i=n?.find(({participantId:c})=>c),s=r?.filter(pg)?.length;return Ie({score:o})||s||e&&i||t&&iv({matchUpStatus:t})&&![Rt,bt,Gn].includes(t)}function Na(t){let{drawDefinition:e,findContainer:r,structureId:n,event:o}=t,i=t.structure,{containedStructures:s}=cs({drawDefinition:e}),a=n?s[n]||[]:[],c={isCollectionMatchUp:!1};if(!i){let A=at({drawDefinition:e,structureId:n});if(A.error)return A;i=r?A.containingStructure??A.structure:A.structure}if(pr({structure:i}))return{structure:i,isAdHoc:!0,error:Cs};let{matchUps:u}=ce({inContext:!0,matchUpFilters:c,drawDefinition:e,event:o}),p=u?.filter(A=>A.structureId===n||a.includes(A.structureId)),{matchUpDependencies:m}=on({drawIds:[e.drawId],matchUps:u,drawDefinition:e}),d=[],l=[],f={},g=[];for(let A of u??[]){if(A.structureId===n||a.includes(A.structureId)){l.push(...A.drawPositions??[]);let U=A.roundNumber;for(let N of(A.drawPositions??[]).filter(Boolean))(!f[N]||U&&f[N]>U)&&(f[N]=U)}pg(A)&&(g.push(A),d.push(A.matchUpId,...m?.[A?.matchUpId]?.matchUpIds||[]))}let I=pt(l.filter(Boolean)).sort(le),h=pt(d),S=pt(p?.map(({matchUpId:A,drawPositions:U})=>h.includes(A)?U:[]).flat().filter(Boolean)).sort(le),{positionAssignments:T}=Ct({drawDefinition:e,structure:i}),y=T?.filter(A=>A.bye).map(A=>A.drawPosition),E=T?.filter(A=>A.qualifier).map(A=>A.drawPosition),P=I?.filter(A=>!S.includes(A))||[];return{allDrawPositions:I,inContextStructureMatchUps:p,drawPositionInitialRounds:f,activeDependentMatchUpIds:h,qualifyingDrawPositions:E,inactiveDrawPositions:P,positionAssignments:T,activeDrawPositions:S,byeDrawPositions:y,activeMatchUps:g,structure:i}}function gs({drawPosition:t,matchUps:e=[]}){return{initialRoundNumber:e.filter(({drawPositions:n})=>t&&n?.includes(t)).map(({roundNumber:n})=>n).sort(le)[0]}}var Ma={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 AS=[];function Cn(t,e){Vt(t)&&(t={method:t}),(e||Pr())&&AS.push(t)}function _k(t){let e=AS.slice();return t&&(AS.length=0),e}function sv(t){let r=_k(t).map(n=>{let{color:o,keyColors:i,method:s,newline:a}=n,c=Object.keys(Ma).includes(o)?Ma[o]:Ma.cyan,p=Object.keys(n).filter(d=>!["color","keyColors","method","newline"].includes(d)).map(d=>{let l=i&&Object.keys(i).includes(d)&&Ma[i[d]]?Ma[i[d]]:Ma.brightwhite;return`${Ma.white}${d}: ${l}${n[d]}`}).join(", "),m=s?.length<15?" ":" ";return[a?`
1
+ var pL=Object.defineProperty;var Jt=(t,e)=>{for(var r in e)pL(t,r,{get:e[r],enumerable:!0})};function Ba(){return"2.2.28"}var EA={};Jt(EA,{competitionGovernor:()=>bU,drawsGovernor:()=>_N,entriesGovernor:()=>VN,eventGovernor:()=>ZN,generationGovernor:()=>iM,matchUpFormatGovernor:()=>Fy,matchUpGovernor:()=>NM,mocksGovernor:()=>TI,participantGovernor:()=>rR,policyGovernor:()=>uN,publishingGovernor:()=>mR,queryGovernor:()=>vN,reportGovernor:()=>dR,scheduleGovernor:()=>PR,scoreGovernor:()=>$g,tieFormatGovernor:()=>xR,tournamentGovernor:()=>qR,venueGovernor:()=>rC});var bU={};Jt(bU,{getLinkedTournamentIds:()=>au,getTournamentIds:()=>Tp,linkTournaments:()=>DU,mutate:()=>RU,query:()=>CU,unlinkTournament:()=>MU,unlinkTournaments:()=>NU});var RU={};Jt(RU,{linkTournaments:()=>DU,unlinkTournament:()=>MU,unlinkTournaments:()=>NU});var ua="SINGLES",kt="SINGLES",_i="DOUBLES",xt="DOUBLES",xr="TEAM",Wt="TEAM",mC={SINGLES_MATCHUP:ua,SINGLES:kt,DOUBLES_MATCHUP:_i,DOUBLES:xt,TEAM_MATCHUP:xr,TEAM:Wt};var MI={[kt]:[kt,"S"],[xt]:[xt,"D"],[Wt]:[Wt,"T"],S:[kt,"S"],D:[xt,"D"],T:[Wt,"T"]};function le(t,e){return(t??0)-(e??0)}function dt(t){return typeof t=="number"?parseInt(t.toString()):typeof t=="string"?parseInt(t):0}function _n(t){return isNaN(t)?!1:t&&(t&t-1)===0}function NA(t){if(!t.length)return;let e=[...t].sort(le),r=Math.floor(e.length/2);return e.length%2?e[r]:(e[r-1]+e[r])/2}function dC(t){if(!_n(t))return!1;let e=t,r=1;for(;e!==2;)r+=1,e=e/2;return r}function ym(t){return isNaN(t)?0:t%2&&t+1||t}function Am(t){return Math.pow(2,Math.round(Math.log(t)/Math.log(2)))}function Zt(t){return!isNaN(parseFloat(t))}function RI(t){let e=dt(t);if(!isNaN(e))return e===0?!1:(e&-e)===1}function rs(t){if(isNaN(t))return!1;for(;!_n(t);)t++;return t}function fo(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 lC(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 mL(t,e){e||(e=1);let r=1/e;return Math.round(t*r)/r}function MA(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=MA(t,e,r):(a=Math.pow(a,r),a*=e-t,a+=t),n&&(a=mL(a,n)),parseFloat(a.toFixed(o))}function Ll(t,e=2){return parseFloat(Number(Math.round(t*1e3)/1e3).toFixed(e))}function pt(t){return Array.isArray(t)?t?.filter((e,r,n)=>n.lastIndexOf(e)===r):[]}function fC(t){return Array.isArray(t)?t?.map(e=>e===null?void 0:e):t}function Sr(t){return Array.isArray(t)?t.map(e=>[Math.random(),e]).sort((e,r)=>e[0]-r[0]).map(e=>e[1]):[]}function Ha(t){return It(t)?t:1/0}function yr(t){return Array.isArray(t)?t.reduce((e,r)=>(e[r]||(e[r]=0),e[r]++,e),{}):{}}function gC(t){return RA(yr(t))}function RA(t){return Object.keys(t).reduce((e,r)=>{let n=t[r];return e[n]?e[n].push(r):e[n]=[r],e},{})}function dL(t,e,r){return r.indexOf(t)===e}function CI(t){return t.filter(dL)}function Zr(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 tt(t,e){return Array.from({length:e-t},(r,n)=>n+t)}function go(t,e){return e.reduce((r,n,o)=>(n===t&&r.push(o),r),[])}function jt(t,e){return!Array.isArray(t)||!Array.isArray(e)?[]:t.filter(r=>e.indexOf(r)!==-1).filter((r,n,o)=>o.indexOf(r)===n)}function CA(t,e){return!Array.isArray(t)||!Array.isArray(e)?[]:t.filter(r=>!e.includes(r))}function ke(t,e){return!Array.isArray(t)||!Array.isArray(e)?!1:t.some(r=>e.includes(r))}function IC(t,e){return Array.isArray(e)&&e.reduce((r,n)=>(r[n]=1+r[n]||1,r),{})[t]||0}function hC(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 Ee(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 bA(t,[e,...r]){return t.length?[t.slice(0,e),...bA(t.slice(e),[...r,e])]:[]}function SC(t){return t.reduce((e,r)=>{let n=e[e.length-1];return(!n||n[n.length-1]!==r-1)&&e.push([]),e[e.length-1].push(r),e},[])}function bI(t){return Array.isArray(t)?t.reduce((e,r)=>!isNaN(parseInt(r))&&e,!0):!1}function vI(t){return Array.isArray(t)?t.reduce((e,r)=>isNaN(parseInt(r))&&e,!0):!1}function Fl(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 TC(t,e=1){if(!Array.isArray(t)||!t.every(It))return[];let r=Math.min(...t,e),n=Math.max(...t);return tt(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 yC(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 _I(t,e){return Array.isArray(t)?Object.assign({},...(t??[]).filter(ht).map(r=>r[e]&&{[r[e]]:r}).filter(Boolean)):{}}var AC=t=>e=>Object.keys(t).every(r=>e[r]===t[r]);function OI(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=>OI(i))}:{[o]:e?n(t[o]):OI(t[o])}))}function vA(t){return Array.isArray(t)?t.length+t.map(vA).reduce((e,r)=>e+r,0):ht(t)&&t!==null?Object.keys(t).length+Object.keys(t).map(e=>vA(t[e])).reduce((e,r)=>e+r,0):0}function EC(t){if(t===null||typeof t!="object")return;let e=JSON.stringify(t),r=vA(t),n=e.split("").reduce((o,i)=>o+i.charCodeAt(0),0);return[e.length,r,n].map(o=>o.toString(36)).join("")}function kc(t,e){return!Array.isArray(t)||!Vt(e)?!1:jt(t,MI[e]).length}var C={success:!0},OA="error",UC={SUCCESS:C,ERROR:OA};function xI({collectionValueProfiles:t,matchUpCount:e}){let r=[];if(!Array.isArray(t))return r.push(`collectionValueProfiles is not an array: ${t}`),{errors:r};if(t.length&&t.length!==e)return r.push("collectionValueProfiles do not align with matchUpsCount"),{errors:r};for(let o of t){if(typeof o!="object")return r.push(`valueProfile is not type object: ${o}`),{errors:r};let{matchUpValue:i,collectionPosition:s}=o;if(typeof i!="number"||typeof s!="number"||s>e||s<1)return r.push("Invalid value profile: value and collectionPosition must be numeric. collectionPosition cannot be greater than matchUpCount"),{errors:r}}let n=t.map(o=>o.collectionPosition);return n.length!==pt(n).length?(r.push("collectionPositions are not unique"),{errors:r}):{...C}}var wC={};Jt(wC,{addNotice:()=>lt,callListener:()=>Mm,createInstanceState:()=>VE,cycleMutationStatus:()=>lf,deepCopyEnabled:()=>df,deleteNotice:()=>QI,deleteNotices:()=>Gi,disableNotifications:()=>BE,enableNotifications:()=>mf,getDevContext:()=>Pr,getMethods:()=>ff,getNotices:()=>zI,getProvider:()=>XI,getTopics:()=>Lr,getTournamentId:()=>os,getTournamentRecord:()=>gf,getTournamentRecords:()=>Go,globalLog:()=>jE,handleCaughtError:()=>ap,hasTopic:()=>ip,removeTournamentRecord:()=>WE,setDeepCopy:()=>jc,setDevContext:()=>Wc,setGlobalLog:()=>OC,setGlobalMethods:()=>_C,setGlobalSubscriptions:()=>HL,setMethods:()=>xC,setStateMethods:()=>YE,setStateProvider:()=>VL,setSubscriptions:()=>WL,setTournamentId:()=>sp,setTournamentRecord:()=>HE,setTournamentRecords:()=>Rm,timeKeeper:()=>BL});var wI={message:"Chronological error; time violation.",code:"ANACHRONISM"},Em={message:"Duplicate entry",code:"DUPLICATE_ENTRY"},_A={message:"Cannot remove main structure",code:"ERR_CANNOT_REMOVE_MAIN_STRUCTURE"},LI={message:"records must be an object with tournamentId keys",code:"ERR_INVALID_TOURNAMENTS"},Lt={message:"Missing tournamentRecords",code:"ERR_MISSING_TOURNAMENTS"},$={message:"Missing tournamentRecord",code:"ERR_MISSING_TOURNAMENT"},Wa={message:"Invalid tournamentRecord",code:"ERR_INVALID_TOURNAMENT"},pa={message:"Missing tournamentId",code:"ERR_MISSING_TOURNAMENT_ID"},ma={message:"Invalid drawDefinition",code:"ERR_INVALID_DRAWDEF"},Z={message:"Missing drawDefinition",code:"ERR_MISSING_DRAWDEF"},xA={message:"Existing drawDefinition(s)",code:"ERR_EXISTING_DRAWDEFS"},Cr={message:"drawDefinition not found",code:"ERR_NOT_FOUND_DRAWDEF"},Zo={message:"Invalid structure",code:"ERR_INVALID_STRUCTURE"},kl={message:"Incomplete source structure",code:"ERR_INCOMPLETE_STRUCTURE"},Gl={message:"Invalid drawPosition for seedAssignment",code:"ERR_INVALID_SEEDING_POSITION"},ja={message:"drawPosition already assigned",code:"ERR_EXISTING_POSITION_ASSIGNMENT"},wA={message:"Schedule not cleared",code:"ERR_UNCHANGED_SCHEDULE_NOT_CLEARED"},LA={message:"drawPosition not cleared",code:"ERR_FAILURE_POSITION_NOT_CLEARED"},lL={message:"drawPosition not found",code:"ERR_NOT_FOUND_DRAW_POSITION"},Vl={message:"Unrecognized drawType",code:"ERR_UNRECOGNIZED_DRAW_TYPE"},Ya={message:"Missing drawPositions",code:"ERR_MISSING_DRAW_POSITIONS"},zu={message:"drawPosition is active",code:"ERR_ACTIVE_DRAW_POSITION"},PC={message:"drawPosition is occupied",code:"ERR_OCCUPIED_DRAW_POSITION"},Cs={message:"Invlid drawPosition",code:"ERR_INVALID_DRAW_POSITION"},bs={message:"Missing drawPosition",code:"ERR_MISSING_DRAW_POSITION"},Um={message:"Invalid drawType",code:"ERR_INVALID_DRAW_TYPE"},Qu={message:"Invalid drawSize",code:"ERR_INVALID_DRAW_SIZE"},FI={message:"Cannot set drawSize to be less than existing entries",code:"ERR_INVALID_DRAW_SIZE_MISMATCH"},qa={message:"Missing drawSize",code:"ERR_MISSING_DRAW_SIZE"},sn={message:"Missing drawId",code:"ERR_MISSING_DRAW_ID"},FA={message:"drawId exists",code:"ERR_EXISTING_DRAW_ID"},kA={message:"participantId cannot be assigned to multiple seedNumbers",code:"INVALID_PARTICIPANT_SEEDING"},GA={message:"seedsCount greater than drawSize",code:"ERR_INVALID_SEED_COUNT"},VA={message:"Missing seedCountThresholds",code:"ERR_MISSING_SEED_COUNT_THRESHOLD"},BA={message:"Invalid action",code:"ERR_INVALID_ACTION"},kI={message:"Invalid assignment",code:"ERR_INVALID_ASSIGNMENT"},HA={message:"Missing seedAssignments",code:"ERR_MISSING_SEED_ASSIGNMENTS"},WA={message:"Invalid seedNumber",code:"ERR_INVALID_SEED_NUMBER"},jA={message:"Invalid seedPosition",code:"ERR_INVALID_SEED_POSITION"},Bl={message:"Missing targetLink",code:"ERR_MISSING_LINK_TARGET"},YA={message:"Existing round",code:"ERR_EXISTING_ROUND"},fL={message:"Missing roundNumber",code:"ERR_MISSING_ROUND_NUMBER"},Ur={message:"Missing structureId",code:"ERR_MISSING_STRUCTURE_ID"},wt={message:"structure not found",code:"ERR_NOT_FOUND_STRUCTURE"},Hl={message:"Missing structures",code:"ERR_MISSING_STRUCTURES"},di={message:"Missing structure",code:"ERR_MISSING_STRUCTURE"},Wl={message:"Missing MAIN structure",code:"ERR_MISSING_MAIN_STRUCTURE"},qA={message:"drawDefinition contains unlinked structures",code:"ERR_MISSING_STRUCTURE_LINKS"},jn={message:"Invalid eventType",code:"ERR_INVALID_EVENT_TYPE"};var Ot={message:"Missing event / eventId",code:"ERR_MISSING_EVENT_ID"},jr={message:"Event not found",code:"ERR_NOT_FOUND_EVENT"},$A={message:"Event exists",code:"ERR_EXISTING_EVENT"},KA={message:"Missing entries",code:"ERR_MISSING_ENTRIES"},zA={message:"Invalid entries",code:"ERR_INVALID_ENTRIES"},jl={message:"Missing assignments",code:"ERR_MISSING_ASSIGNMENTS"},QA={message:"Missing stage",code:"ERR_MISSING_STAGE"},xi={message:"Invalid stage",code:"ERR_INVALID_STAGE"},XA={message:"stageSequence limit",code:"ERR_LIMIT_STAGE_SEQUENCE"},JA={message:"Missing positionAssignments",code:"ERR_MISSING_POSITION_ASSIGNMENTS"},ZA={message:"Cannot Assign BYE status if no assignment: { bye: true }",code:"ERR_UNCHANGED_CANNOT_ASSIGN_BYE"},GI={message:"Unrecognized matchUpStatus",code:"ERR_UNRECOGNIZED_MATCHUP_STATUS"},$a={message:"Unrecognized matchUpFormat",code:"ERR_UNRECOGNIZED_MATCHUP_FORMAT"},Yl={message:"Incompatible matchUpStatus",code:"ERR_INCOMPATIBLE_MATCHUP_STATUS"},da={message:"Invalid matchUpStatus",code:"ERR_INVALID_MATCHUP_STATUS"},ko={message:"Invalid tieFormat",code:"ERR_INVALID_TIE_FORMAT"},ql={message:"Invalid matchUpFormat",code:"ERR_INVALID_MATCHUP_FORMAT"},$l={message:"Missing matchUpFormat",code:"ERR_MISSING_MATCHUP_FORMAT"},tE={message:"Missing collectionDefinition",code:"ERR_MISSING_COLLECTION_DEFINITION"},vs={message:"Missing tieFormat",code:"ERR_MISSING_TIE_FORMAT"},cr={message:"Missing matchUpId",code:"ERR_MISSING_MATCHUP_ID"},ns={message:"Missing matchUpIds",code:"ERR_MISSING_MATCHUP_IDS"},Le={message:"matchUp not found",code:"ERR_NOT_FOUND_MATCHUP"},eo={message:"Missing matchUps",code:"ERR_MISSING_MATCHUPS"},Tr={message:"Missing matchUp",code:"ERR_MISSING_MATCHUP"},lr={message:"Invalid matchUp",code:"ERR_INVALID_MATCHUP"},VI={message:"Missing policyType",code:"ERR_MISSING_POLICY_TYPE"},Xu={message:"Missing policyDefinitions",code:"ERR_MISSING_POLICY_DEFINITIONS"},gL={message:"Missing seeding policy",code:"ERR_MISSING_POLICY_SEEDING"},eE={message:"Missing avoidance policy",code:"ERR_MISSING_POLICY_AVOIDANCE"},BI={message:"Missing policy attributes",code:"ERR_MISSING_POLICY_ATTRIBUTES"},rE={message:"Invalid policyDefinitions",code:"ERR_INVALID_POLICY_DEFINITIONS"},HI={message:"existing policyType",code:"ERR_EXISTING_POLICY_TYPE"},IL={message:"Policy not attached",code:"ERR_FAILURE_POLICY_NOT_ATTACHED"},Gc={message:"Policy not found",code:"ERR_NOT_FOUND_POLICY"},hL={message:"Missing scoring policy / matchUpFormats",code:"ERR_MISSING_POLICY_SCORING_MATCHUP_FORMATS"},Kl={message:"Invalid sideNumber",code:"ERR_INVALID_SIDE_NUMBER"},SL={message:"Invalid setNumber",code:"ERR_INVALID_SET_NUMBER"},zl={message:"Missing setObject",code:"ERR_MISSING_SET_ATTRIBUTE"},TL={message:"Missing setNumber",code:"ERR_MISSING_SET_NUMBER"},yL={message:"Missing sideNumber",code:"ERR_MISSING_SIDE_NUMBER"},wi={message:"Missing courtId",code:"ERR_MISSING_COURT_ID"},st={message:"Missing value",code:"ERR_MISSING_VALUE"},nE={message:"Missing birthdate",code:"ERR_MISSING_BIRTH_DATE"},oE={message:"Missing date",code:"ERR_MISSING_DATE"},iE={message:"No valid dates",code:"ERR_NO_VALID_DATES"},Pm={message:"Invalid bookings",code:"ERR_INVALID_BOOKINGS"},Ql={message:"Invalid dateAvailability",code:"ERR_INVALID_DATE_AVAILABILITY"},sE={message:"Missing dateAvailability",code:"ERR_MISSING_DATE_AVAILABILITY"},je={message:"Invalid Date",code:"ERR_INVALID_DATE"},Po={message:"Invalid time",code:"ERR_INVALID_TIME"},aE={message:"Invalid tournament dates",code:"ERR_INVALID_DATES_TOURNAMENT"};var WI={message:"Invalid game scores",code:"ERR_INVALID_SCORES_GAME"},cE={message:"Invalid score",code:"ERR_INVALID_SCORE"},Dm={message:"Invalid winningSide",code:"ERR_INVALID_WINNING_SIDE"};var DC={message:"No participants generated",code:"ERR_NO_PARTICIPANTS_GENERATED"},Xl={message:"Cannot modify tieFormat",code:"ERR_UNCHANGED_CANNOT_MODIFY_TIEFORMAT"},uE={message:"Cannot modify participantType",code:"ERR_UNCHANGED_CANNOT_MODIFY_PARTICIPANT_TYPE"},Ju={message:"Cannot remove participants",code:"ERR_UNCHANGED_CANNOT_REMOVE_PARTICIPANTS"},jI={message:"Participant category mismatch",code:"ERR_CATEGORY_MISMATCH"},Nm={message:"Cannot change winningSide",code:"ERR_UNCHANGED_CANNOT_CHANGE_WINNING_SIDE"},Li={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"},pE={message:"Invalid participantRole",code:"ERR_INVALID_PARTICIPANT_ROLE"},An={message:"Invalid participantType",code:"ERR_INVALID_PARTICIPANT_TYPE"},mE={message:"Missing participantRole",code:"ERR_MISSING_PARTICIPANT_ROLE"},Fi={message:"Missing participant",code:"ERR_MISSING_PARTICIPANT"},Ka={message:"Missing participants",code:"ERR_MISSING_PARTICIPANTS"},ie={message:"Missing participantId",code:"ERR_MISSING_PARTICIPANT_ID"},dE={message:"Missing qualified participants",code:"ERR_MISSING_QUALIFIED_PARTICIPANTS"},re={message:"Participant Not Found",code:"ERR_NOT_FOUND_PARTICIPANT"},lE={message:"participantId exists",code:"ERR_EXISTING_PARTICIPANT_ID"},AL={message:"participant pair exists",code:"ERR_EXISTING_PARTICIPANT_PAIR"},fE={message:"No participant removed",code:"ERR_UNCHANGED_NO_PARTICIPANT_REMOVED"},Do={message:"Missing participantIds",code:"ERR_MISSING_PARTICIPANT_IDS"},gE={message:"Missing participantsCount",code:"ERR_MISSING_PARTICIPANT_COUNT"},IE={message:"Participant not checked in",code:"ERR_UNCHANGED_PARTICIPANT_NOT_CHECKED_IN"},hE={message:"Missing person details",code:"ERR_MISSING_PERSON_DETAILS"},Os={message:"Existing participant drawPosition assignment",code:"ERR_EXISTING_PARTICIPANT_DRAW_POSITION_ASSIGNMENT"},Zu={message:"Existing participant",code:"ERR_EXISTING_PARTICIPANT"},Jl={message:"participantsCount exceeds drawSize",code:"ERR_INVALID_PARTICIPANT_COUNT"},Zl={message:"Invalid entry status",code:"ERR_INVALID_ENTRY_STATUS"},YI={message:"Participant Entry Not Found",code:"ERR_NOT_FOUND_PARTICIPANT_ENTRY"},NC={message:"Participant not entered in stage",code:"ERR_UNCHANGED_PARTICIPANT_NOT_ENTERED"},MC={message:"Participant not found in stageSequence",code:"ERR_NOT_FOUND_PARTICIPANT_IN_STAGE"},SE={message:"entryStatus not allowed in stage",code:"ERR_INVALID_ENTRY_STATUS_IN_STAGE"},TE={message:"entryStatus not allowed for event",code:"ERR_INVALID_ENTRY_STATUS_IN_EVENT"},qI={message:"No stage space available for entryStatus",code:"ERR_UNCHANGED_NO_AVAILABLE_STAGE_SPACE"},tf={message:"Insufficient drawPositions to accommodate qualifiers",code:"ERR_UNCHANGED_NO_DRAW_POSITIONS_FOR_QUALIFIERS"},ef={message:"Insufficient drawPositions to accommodate entries",code:"ERR_INSUFFICIENT_DRAW_POSITIONS"},yE={message:"Missing penaltyType",code:"ERR_MISSING_PENALTY_TYPE"},rf={message:"Missing penaltyId",code:"ERR_MISSING_PENALTY_ID"},Vc={message:"Penalty not found",code:"ERR_NOT_FOUND_PENALTY"},AE={message:"Missing courtsCount/courtNames",code:"ERR_MISSING_COURTS_INFO"},_s={message:"Court not found",code:"ERR_NOT_FOUND_COURT"},EE={message:"Court exists",code:"ERR_EXISTING_COURT"},UE={message:"Venue exists",code:"ERR_EXISTING_VENUE"},ki={message:"Venue not found",code:"ERR_NOT_FOUND_VENUE"},ti={message:"Missing venueId",code:"ERR_MISSING_VENUE_ID"},PE={message:"Invalid endTime",code:"ERR_INVALID_END_TIME"},$I={message:"Existing endTime",code:"ERR_EXISTING_END_TIME"},DE={message:"Invalid stopTime",code:"ERR_INVALID_STOP_TIME"},NE={message:"Invalid startTime",code:"ERR_INVALID_START_TIME"},RC={message:"Invalid resumeTime",code:"ERR_INVALID_RESUME_TIME"},nf={message:"Invalid timeItem",code:"ERR_INVALID_TIME_ITEMS"},ME={message:"Missing async state provider",code:"ERR_MISSING_ASYNC_STATE_PROVIDER"},of={message:"Missing timeItem",code:"ERR_MISSING_TIME_ITEM"},sf={message:"Missing timeItems",code:"ERR_MISSING_TIME_ITEMS"},Bc={message:"Missing context",code:"ERR_MISSING_CONTEXT"},RE={message:"Missing schedule",code:"ERR_MISSING_SCHEDULE"},za={message:"Invalid scaleItem",code:"ERR_INVALID_SCALE_ITEM"},CE={message:"Modifications failed",code:"ERR_FAILURE_MODIFICATIONS"},xs={message:"No modifications applied",code:"ERR_UNCHANGED_NO_MODIFICATIONS_APPLIED"},bE={message:"Unable to assign court",code:"ERR_UNCHANGED_COURT_NOT_ASSIGNED"},tp={message:"No Candidates",code:"ERR_UNCHANGED_NO_CANDIDATES"},vE={message:"Invalid configuration",code:"ERR_INVALID_CONFIG"},OE={message:"Invalid collectionDefinition",code:"ERR_INVALID_COLLECTION_DEFINITION"},Io={message:"Invalid object",code:"ERR_INVALID_OBJECT"},ep={message:"Invalid gender",code:"ERR_INVALID_GENDER"},Hc={message:"Invalid category",code:"ERR_INVALID_CATEGORY"},V={message:"Invalid values",code:"ERR_INVALID_VALUES"},_E={message:"Duplicate value",code:"ERR_DUPLICATE_VALUE"},af={message:"Team not found",code:"ERR_NOT_FOUND_TEAM"},xE={message:"No valid actions",code:"ERR_NO_VALID_ACTIONS"},rp={message:"No valid attributes",code:"ERR_NO_VALID_ATTRIBUTES"},cf={message:"Value unchanged",code:"ABORT_UNCHANGED"},ve={message:"Not found",code:"ERR_NOT_FOUND"},np={message:"Not implemented",code:"ERR_NOT_IMPLEMENTED"},wE={message:"Existing flight",code:"ERR_EXISTING_FLIGHT"},uf={message:"Existing flight profile",code:"ERR_EXISTING_FLIGHT_PROFILE"},LE={message:"Existing outcome",code:"ERR_EXISTING_OUTCOME"},FE={message:"Existing matchUpId",code:"ERR_EXISTING_MATCHUP_ID"},KI={message:"Existing stage",code:"ERR_EXISTING_STAGE"},pf={message:"Existing structure",code:"ERR_EXISTING_STRUCTURE"},Qa={message:"Method not found",code:"ERR_NOT_FOUND_METHOD"},kE={message:"Scheduled matchUps",code:"ERR_SCHEDULED_MATCHUPS"},Xa={message:"Scores present",code:"ERR_SCORES_PRESENT"},CC={ANACHRONISM:wI,CANNOT_CHANGE_WINNING_SIDE:Nm,CANNOT_MODIFY_TIEFORMAT:Xl,CANNOT_MODIFY_PARTICIPANT_TYPE:uE,CANNOT_REMOVE_MAIN_STRUCTURE:_A,CANNOT_REMOVE_PARTICIPANTS:Ju,CATEGORY_MISMATCH:jI,COURT_EXISTS:EE,COURT_NOT_FOUND:_s,DRAW_DEFINITION_NOT_FOUND:Cr,DRAW_ID_EXISTS:FA,DRAW_POSITION_ACTIVE:zu,DRAW_POSITION_ASSIGNED:ja,DRAW_POSITION_NOT_CLEARED:LA,DRAW_POSITION_NOT_FOUND:lL,DRAW_SIZE_MISMATCH:FI,DUPLICATE_ENTRY:Em,DUPLICATE_VALUE:_E,ENTRY_STATUS_NOT_ALLOWED_FOR_EVENT:TE,ENTRY_STATUS_NOT_ALLOWED_IN_STAGE:SE,EVENT_EXISTS:$A,EVENT_NOT_FOUND:jr,EXISTING_DRAW_DEFINITIONS:xA,EXISTING_END_TIME:$I,EXISTING_FLIGHT:wE,EXISTING_MATCHUP_ID:FE,EXISTING_OUTCOME:LE,EXISTING_PARTICIPANT_DRAW_POSITION_ASSIGNMENT:Os,EXISTING_PARTICIPANT:Zu,EXISTING_POLICY_TYPE:HI,EXISTING_PROFILE:uf,EXISTING_ROUND:YA,EXISTING_STAGE:KI,EXISTING_STRUCTURE:pf,INCOMPATIBLE_MATCHUP_STATUS:Yl,INCOMPLETE_SOURCE_STRUCTURE:kl,INSUFFICIENT_DRAW_POSITIONS:ef,INVALID_ACTION:BA,INVALID_ASSIGNMENT:kI,INVALID_BOOKINGS:Pm,INVALID_CATEGORY:Hc,INVALID_COLLECTION_DEFINITION:OE,INVALID_CONFIGURATION:vE,INVALID_DATE_AVAILABILITY:Ql,INVALID_DATE:je,INVALID_DRAW_DEFINITION:ma,INVALID_DRAW_POSITION_FOR_SEEDING:Gl,INVALID_DRAW_POSITION:Cs,INVALID_DRAW_SIZE:Qu,INVALID_END_TIME:PE,INVALID_ENTRIES:zA,INVALID_EVENT_TYPE:jn,INVALID_GAME_SCORES:WI,INVALID_GENDER:ep,INVALID_MATCHUP_FORMAT:ql,INVALID_MATCHUP_STATUS:da,INVALID_MATCHUP_STATUS_BYE:ZA,INVALID_MATCHUP:lr,INVALID_OBJECT:Io,INVALID_PARTICIPANT_ID:mn,INVALID_PARTICIPANT_IDS:wr,INVALID_PARTICIPANT_ROLE:pE,INVALID_PARTICIPANT_SEEDING:kA,INVALID_PARTICIPANT_TYPE:An,INVALID_PARTICIPANT:Li,INVALID_POLICY_DEFINITION:rE,INVALID_RECORDS:LI,INVALID_SCALE_ITEM:za,INVALID_SEED_NUMBER:WA,INVALID_SEED_POSITION:jA,INVALID_SET_NUMBER:SL,INVALID_SIDE_NUMBER:Kl,INVALID_SCORE:cE,INVALID_STAGE:xi,INVALID_START_TIME:NE,INVALID_STRUCTURE:Zo,INVALID_STOP_TIME:DE,INVALID_TIE_FORMAT:ko,INVALID_TIME:Po,INVALID_TIME_ITEM:nf,INVALID_TOURNAMENT_DATES:aE,INVALID_TOURNAMENT_RECORD:Wa,INVALID_VALUES:V,INVALID_WINNING_SIDE:Dm,MATCHUP_NOT_FOUND:Le,METHOD_NOT_FOUND:Qa,MISSING_ASSIGNMENTS:jl,MISSING_ASYNC_STATE_PROVIDER:ME,MISSING_AVOIDANCE_POLICY:eE,MISSING_BIRTH_DATE:nE,MISSING_COLLECTION_DEFINITION:tE,MISSING_COURT_ID:wi,MISSING_COURTS_INFO:AE,MISSING_DATE_AVAILABILITY:sE,MISSING_DATE:oE,MISSING_DRAW_DEFINITION:Z,MISSING_DRAW_ID:sn,MISSING_DRAW_POSITION:bs,MISSING_DRAW_POSITIONS:Ya,MISSING_DRAW_SIZE:qa,MISSING_ENTRIES:KA,MISSING_EVENT:Ot,MISSING_QUALIFIED_PARTICIPANTS:dE,MISSING_MATCHUP_FORMAT:$l,MISSING_MATCHUP_ID:cr,MISSING_MATCHUP_IDS:ns,MISSING_MATCHUP:Tr,MISSING_MATCHUPS:eo,MISSING_PARTICIPANT_COUNT:gE,MISSING_PARTICIPANT_ID:ie,MISSING_PARTICIPANT_IDS:Do,MISSING_PARTICIPANT_ROLE:mE,MISSING_PARTICIPANT:Fi,MISSING_PARTICIPANTS:Ka,MISSING_PENALTY_ID:rf,MISSING_PENALTY_TYPE:yE,MISSING_PERSON_DETAILS:hE,MISSING_POLICY_ATTRIBUTES:BI,MISSING_POLICY_DEFINITION:Xu,MISSING_POLICY_TYPE:VI,MISSING_POSITION_ASSIGNMENTS:JA,MISSING_ROUND_NUMBER:fL,MISSING_SCHEDULE:RE,MISSING_SCORING_POLICY:hL,MISSING_SEED_ASSIGNMENTS:HA,MISSING_SEEDCOUNT_THRESHOLDS:VA,MISSING_SEEDING_POLICY:gL,MISSING_SET_NUMBER:TL,MISSING_SET_OBJECT:zl,MISSING_SIDE_NUMBER:yL,MISSING_STAGE:QA,MISSING_STRUCTURE_ID:Ur,MISSING_STRUCTURE:di,MISSING_MAIN_STRUCTURE:Wl,MISSING_STRUCTURES:Hl,MISSING_TARGET_LINK:Bl,MISSING_TIE_FORMAT:vs,MISSING_TIME_ITEM:of,MISSING_TIME_ITEMS:sf,MISSING_TOURNAMENT_ID:pa,MISSING_TOURNAMENT_RECORD:$,MISSING_TOURNAMENT_RECORDS:Lt,MISSING_VALUE:st,MISSING_VENUE_ID:ti,MODIFICATIONS_FAILED:CE,NO_CANDIDATES:tp,NO_DRAW_POSITIONS_AVAILABLE_FOR_QUALIFIERS:tf,NO_MODIFICATIONS_APPLIED:xs,NO_STAGE_SPACE_AVAILABLE_FOR_ENTRY_STATUS:qI,NO_PARTICIPANT_REMOVED:fE,NO_VALID_ACTIONS:xE,NO_VALID_ATTRIBUTES:rp,NO_VALID_DATES:iE,NOT_FOUND:ve,NOT_IMPLEMENTED:np,PARTICIPANT_COUNT_EXCEEDS_DRAW_SIZE:Jl,PARTICIPANT_ID_EXISTS:lE,PARTICIPANT_NOT_CHECKED_IN:IE,PARTICIPANT_NOT_FOUND:re,PARTICIPANT_PAIR_EXISTS:AL,PENALTY_NOT_FOUND:Vc,POLICY_NOT_ATTACHED:IL,POLICY_NOT_FOUND:Gc,SCHEDULE_NOT_CLEARED:wA,SCHEDULED_MATCHUPS:kE,SCORES_PRESENT:Xa,SEEDSCOUNT_GREATER_THAN_DRAW_SIZE:GA,STAGE_SEQUENCE_LIMIT:XA,STRUCTURE_NOT_FOUND:wt,TEAM_NOT_FOUND:af,UNABLE_TO_ASSIGN_COURT:bE,UNLINKED_STRUCTURES:qA,UNRECOGNIZED_DRAW_TYPE:Vl,UNRECOGNIZED_MATCHUP_FORMAT:$a,UNRECOGNIZED_MATCHUP_STATUS:GI,VALUE_UNCHANGED:cf,VENUE_EXISTS:UE};var tr={disableNotifications:!1,tournamentId:void 0,tournamentRecords:{},subscriptions:{},modified:!1,methods:{},notices:[]},GE={addNotice:_L,callListener:kL,cycleMutationStatus:OL,deleteNotice:LL,deleteNotices:wL,disableNotifications:EL,enableNotifications:UL,getMethods:op,getNotices:xL,getTopics:FL,getTournamentId:bC,getTournamentRecord:PL,getTournamentRecords:DL,removeTournamentRecord:CL,setMethods:vL,setSubscriptions:bL,setTournamentId:ML,setTournamentRecord:NL,setTournamentRecords:RL,handleCaughtError:GL};function EL(){tr.disableNotifications=!0}function UL(){tr.disableNotifications=!1}function bC(){return tr.tournamentId}function PL(t){return tr.tournamentRecords[t]}function DL(){return tr.tournamentRecords}function NL(t){let e=t?.tournamentId;return e?(tr.tournamentRecords[e]=t,{success:!0}):{error:Wa}}function ML(t){return t?tr.tournamentRecords[t]?(tr.tournamentId=t,{success:!0}):{error:$}:(tr.tournamentId=void 0,{success:!0})}function RL(t){tr.tournamentRecords=t;let e=Object.keys(t);e.length===1?tr.tournamentId=e[0]:e.length||(tr.tournamentId=void 0)}function CL(t){if(typeof t!="string")return{error:V};if(!tr.tournamentRecords[t])return{error:ve};delete tr.tournamentRecords[t];let e=Object.keys(tr.tournamentRecords);return e.length===1?tr.tournamentId=e[0]:e.length||(tr.tournamentId=void 0),{success:!0}}function bL(t){return typeof t.subscriptions!="object"?{error:V}:(Object.keys(t.subscriptions).forEach(e=>{typeof t.subscriptions[e]=="function"?tr.subscriptions[e]=t.subscriptions[e]:delete tr.subscriptions[e]}),{...C})}function vL(t){return typeof t!="object"?{error:V}:(Object.keys(t).forEach(e=>{typeof t[e]=="function"&&(tr.methods[e]=t[e])}),{...C})}function OL(){let t=tr.modified;return tr.modified=!1,t}function _L({topic:t,payload:e,key:r},n){if(!(typeof t!="string"||typeof e!="object")&&(tr.disableNotifications||(tr.modified=!0),!(tr.disableNotifications||!tr.subscriptions[t]&&!n)))return r&&(tr.notices=tr.notices.filter(o=>!(o.topic===t&&o.key===r))),tr.notices.push({topic:t,payload:e,key:r}),{...C}}function op(){return tr.methods??{}}function xL({topic:t}){return tr.notices.filter(e=>e.topic===t).map(e=>e.payload)}function wL(){tr.notices=[]}function LL({topic:t,key:e}){tr.notices=tr.notices.filter(r=>(!t||r.topic===t)&&r.key!==e)}function FL(){return{topics:Object.keys(tr.subscriptions)}}function kL({topic:t,notices:e},r){let n=tr.subscriptions[t];n&&typeof n=="function"&&n(e);let o=r?.[t];o&&typeof o=="function"&&o(e)}function GL({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:bC(),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},an=GE,vC=["addNotice","callListener","cycleMutationStatus","deleteNotice","deleteNotices","disableNotifications","enableNotifications","getMethods","getNotices","getTopics","getTournamentId","getTournamentRecord","getTournamentRecords","removeTournamentRecord","setSubscriptions","setTournamentId","setTournamentRecord","setTournamentRecords"];function VL(t){if(typeof t!="object")throw new Error("Global state provider can not be undefined or null");if(jt(Object.keys(t),vC).length!==vC.length)throw new Error("Global state provider is missing required methods");return an=t,{success:!0}}function VE(){if(an.createInstanceState){try{an.createInstanceState()}catch(t){return{error:t}}return{success:!0}}else return{error:ME}}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 BL(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 OC(t){Wr(t)?Oe.globalLog=t:delete Oe.globalLog}function Wc(t){Oe.devContext=t}function BE(){an.disableNotifications()}function mf(){an.enableNotifications()}function jc(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 df(){return{enabled:Oe.deepCopy,...Oe.deepCopyAttributes}}function HL(t){return t?.subscriptions?(Object.keys(t.subscriptions).forEach(e=>{Oe.globalSubscriptions[e]=t.subscriptions[e]}),{...C}):{error:st,info:"missing subscriptions"}}function WL(t){return t?.subscriptions?an.setSubscriptions({subscriptions:t.subscriptions}):{error:st,info:"missing subscriptions"}}function _C(t){return t?typeof t!="object"?{error:V}:(Object.keys(t).forEach(e=>{Wr(t[e])&&(Oe.globalMethods[e]=t[e])}),{...C}):{error:st,info:"missing method declarations"}}function xC(t){return t?typeof t!="object"?{error:V}:an.setMethods(t):{error:st,info:"missing method declarations"}}function lf(){return an.cycleMutationStatus()}function lt(t){if(typeof t?.topic!="string")return;let e=Oe.globalSubscriptions[t.topic];return an.addNotice(t,e)}function ff(){return{...Oe.globalMethods,...an.getMethods()}}function zI(t){return an.getNotices(t)}function QI({key:t,topic:e}){return an.deleteNotice({key:t,topic:e})}function Gi(){return an.deleteNotices()}function Lr(){return an.getTopics()}function ip(t){return Lr()?.topics?.includes(t)}async function Mm(t){return an.callListener(t,Oe.globalSubscriptions)}function os(){return an.getTournamentId()}function gf(t){return an.getTournamentRecord(t)}function Go(){return an.getTournamentRecords()}function HE(t){return an.setTournamentRecord(t)}function Rm(t){return an.setTournamentRecords(t)}function sp(t){return an.setTournamentId(t)}function WE(t){return an.removeTournamentRecord(t)}function XI(){return an}function ap({engineName:t,methodName:e,params:r,err:n}){let o=Wr(an.handleCaughtError)&&an.handleCaughtError||GE.handleCaughtError,{tournamentRecord:i,...s}=r;return o({params:s,engineName:t,methodName:e,err:n})}function jE(t,e){if(Oe.globalLog)try{Oe.globalLog({log:t,engine:e})}catch(r){console.log("globalLog error",r),console.log(e,t),OC()}else console.log(e,t)}function YE(t,e,r,n){if(!ht(t))return{error:V};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?_C(i):xC(i),{methods:i}}function jL(t,e,r){return Object.keys(t).filter(n=>!e.includes(t[n])&&(!r||(Array.isArray(t[n])?t[n].length:!0)))}function nt(t,e,r,n){if(typeof t!="object"||t===null)return t;df()?.enabled||(n=!0);let i=["",void 0,null];e&&i.push(!1);let s=jL(t,i,r);return Object.assign({},...s.map(a=>Array.isArray(t[a])?{[a]:n?t[a]:t[a].map(c=>nt(c))}:{[a]:n?t[a]:nt(t[a])}))}function _({context:t,result:e,stack:r,info:n}){return e&&!Array.isArray(e?.stack)&&(e.stack=[]),e&&Array.isArray(e?.stack)&&typeof r=="string"&&e.stack.push(r),e&&n&&(e.info=n),e&&typeof t=="object"&&Object.keys(t).length&&Object.assign(e,nt(t)),e&&!e?.error&&!e?.success&&Object.assign(e,{...C}),e??{success:!0}}var Pn="ANY",zt="MALE",Ar="MIXED",is="OTHER",oe="FEMALE",Cm={ANY:Pn,MALE:zt,FEMALE:oe,MIXED:Ar,OTHER:is};var YL="MIXED events can not contain mixed singles or { gender: ANY } collections",qL="events with { gender: ANY } can not contain MIXED singles collections";function bm(t){let e="tieFormatGenderValidityCheck",{referenceGender:r,matchUpType:n,gender:o}=t;return r&&o&&[zt,oe].includes(r)&&r!==o?_({result:{valid:!1,error:ep},context:{gender:o},stack:e}):r===Ar&&(o===Pn||o===Ar&&n!==xt)?_({result:{error:ep,valid:!1},info:YL,stack:e}):r===Pn&&o===Ar&&n!==xt?_({result:{error:ep,valid:!1},info:qL,stack:e}):{valid:!0}}var $L="normal",qE="timed",KL="final",If="NOAD",vm="SET",LC={S:$L,F:KL};function cp(t,e){if(ht(t),(t?.bestOf||t?.exactly)&&t?.setFormat)return zL(t,e)}function hf(t){return!isNaN(Number(t))&&Number(t)}function GC(t){let e=`T${t.minutes}`;return t.based&&(e+=t.based),t.modifier&&(e+=`@${t.modifier}`),e}function zL(t,e){let r=hf(t.bestOf)||void 0,n=hf(t.exactly)||void 0,o=r||n;if(t.setFormat?.timed&&t.simplified&&o===1)return GC(t.setFormat);let i=o&&`${vm}${o}`||"",s=FC(t.setFormat,e),a=s&&`S:${s}`||"",c=FC(t.finalSetFormat,e),u=o&&o>1&&c&&s!==c&&`F:${c}`||"";if(i&&s)return[i,a,u].filter(m=>m).join("-")}function FC(t,e){if(typeof t=="object"&&Object.keys(t).length){if(t.timed)return GC(t);if(t.tiebreakSet)return kC(t.tiebreakSet);let r=hf(t.setTo);if(r){let n=t.NoAD&&If||"",o=kC(t.tiebreakFormat),i=o&&`/${o}`||"",s=hf(t.tiebreakAt),a=s&&(s!==r||e)&&`@${s}`||"";if(o!==!1)return`${r}${n}${i}${a}`}}}function kC(t){if(t){if(typeof t=="object"&&!t.tiebreakTo)return"";if(typeof t=="object"&&hf(t.tiebreakTo)){let e=`TB${t.tiebreakTo}${t.NoAD?If:""}`;return t.modifier&&(e+=`@${t.modifier}`),e}else return!1}}function Ye(t){if(Vt(t)){let e=t.startsWith("T")&&qE||t.startsWith(vm)&&vm||"";if(e===qE){let r=WC(t),n={simplified:!0,setFormat:r,bestOf:1};if(r)return n}if(e===vm)return QL(t)}}function QL(t){let e=t.split("-"),r=Sf(e[0].slice(3)),n=r===1||r%2!==0?r:void 0,o=r!==1&&r%2===0?r:void 0,i=e&&VC(e[1]),s=e&&VC(e[2]),a=i&&i.timed||s&&s.timed,c=n&&n<6||a&&o,u=!e[2]||s,p=i,m=nt({setFormat:i,exactly:o,bestOf:n});if(s&&(m.finalSetFormat=s),c&&p&&u)return m}function VC(t){if(t?.[1]===":"){let e=t.split(":"),r=LC[e[0]],n=e[1];if(r&&n){if(n.startsWith("TB")){let I=BC(n);return I===!1?!1:typeof I=="object"?{tiebreakSet:I}:void 0}if(n.startsWith("T"))return WC(n);let s=t.match(/^[FS]:(\d+)([A-Za-z]*)/),a=s&&jC(s[2])||!1,c=!s?.[2]||a,u=s?Sf(s[1]):void 0,p=HC(n),m=p!==!1,d=m&&p||u,l=BC(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 HC(t,e=!0){let r=t?.indexOf("@")>0&&t.split("@");if(r)return(e?Sf(r[1]):r[1])||!1}function BC(t){if(t)if(t.startsWith("TB")){let e=HC(t,!1),r=t.match(/^TB(\d+)([A-Za-z]*)/),n=r?.[1],o=r&&jC(r[2]),i=!r?.[2]||o,s=Sf(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 WC(t){let e=t.slice(1),r=e.match(/^(\d+)(@?[A-Za-z]*)/),n=Sf(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 jC(t){return t&&t.indexOf(If)>=0}function Sf(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(\d{1,2})@?([1-9]?)*/),n=r?.[1],o=r?.[2],i=r?.[3],s=t.match(/-F:([1-9])+\/TB(\d{1,2})@?([1-9]?)*/),a=s?.[1],c=s?.[2],u=s?.[3];return cp(e,!!(r&&o&&n===i||s&&c&&a===u))===t}var Om=/^[\d]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][\d]|3[0-1])$/,JI=/^((0[\d]|1[\d]|2[0-3]):[0-5][\d](:[0-5][\d])?)([.,][0-9]{3})?$/,No=/^([\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?$/,ws=/^([\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 _m(t){let{scheduledDate:e}=t;if(!e&&t.scheduledTime&&(e=Pt(t.scheduledTime)),!e)return;let r=Qt(t.scheduledTime),n=Pt(e);return n&&r&&(n+=`T${r}`),n}function YC(t){return typeof t!="object"||Array.isArray(t)?!1:Object.prototype.toString.call(t)==="[object Date]"}function Yc(t){let e=typeof t=="string"?t?.split(" "):[];return t&&e?.length>1&&!["AM","PM"].includes(e[1].toUpperCase())?!1:!!(!t||ws.test(Za(t,!0,!0)))}function Nr(t){return Ja(t)||Om.test(t)}function XL(t){let e=new Date(t),r=e.getSeconds()+60*e.getMinutes()+60*60*e.getHours();return JL(r,{displaySeconds:!1})}function JL(t,e){let r=parseInt(t,10),n=Math.floor(r/3600),o=Math.floor((r-n*3600)/60),i=r-n*3600-o*60;return(!e||e?.displaySeconds?n+":"+o+":"+i:n+":"+o).split(":").map(ro).join(":")}var Af=t=>{let e=Tf(t)||Ja(t)?new Date(t):new Date,r=e.getUTCMonth()+1,n=r<10?`0${r}`:`${r}`;return`${e.getUTCFullYear()}-${ro(n)}-${ro(e.getUTCDate())}`};function ZL(t){let e=Tf(t)||Ja(t)?new Date(t):new Date;return Date.UTC(e.getFullYear(),e.getMonth(),e.getDate())}function Yn(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 ZI(t){let e=t?new Date(t):new Date,r=e.getTimezoneOffset();return new Date(e.getTime()-r*60*1e3)}function tF(t){return ZI(t).getTime()}function Tf(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 Ls(t,e){if(!Nr(t)||!Nr(e))return[];let r=Pt(t)+"T00:00",n=Pt(e)+"T00:00",o=new Date(r),i=new Date(n),s=Tf(i)&&Tf(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=>Yn(p));function u(p,m){return p<=m}}var eF=/^([+-]?\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 Ja(t){return typeof t!="string"?!1:eF.test(t)}function eh(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 Yt(t){let e=Qt(t);if(!e)return 0;let[r,n]=e.split(":").map(o=>parseInt(o));return r*60+n}function qC(t){let e=Math.floor(t/60),r=t-e*60;return e>23&&(e=e%24),[ro(e),ro(r)].join(":")}function yf(t){return eh(t)?t.split(":").slice(0,2).map(ro).join(":"):void 0}function Qt(t){return Ja(t)&&t.indexOf("T")>0?yf(t.split("T").reverse()[0]):yf(t)}function Pt(t){return Ja(t)||No.test(t)?t.split("T")[0]:void 0}function up(t,e){let r=new Date(t);return r.setDate(r.getDate()+e),Pt(r.toISOString())}function th(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 rF(t){let e=th(t);return e.ampm&&e.hours&&(e.ampm.toLowerCase()==="pm"&&parseInt(e.hours)<12&&(e.hours=(e.hours&&parseInt(e.hours)||0)+12),e.ampm.toLowerCase()==="am"&&e.hours==="12"&&(e.hours="00")),`${e.hours||"12"}:${e.minutes||"00"}`.split(":").map(ro).join(":")}function nF(t){let e=th(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 Za(t,e,r){let n=Pt(t),o=Qt(t),i=n?o:t;return t?e&&(n&&r&&t||rF(i))||nF(i):void 0}function rh(t,e){let r=th(t),n=th(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 nh(t,e=7){let r=Pt(t)+"T00:00",n=new Date(r),o=new Date(n.setDate(n.getDate()+e));return Yn(o)}function oF(t){return nh(t)}function iF(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())),Yn(o,r)}function $C(t,e,r){let n=new Date(t,0);return Yn(new Date(n.setDate(e)),r)}function Ge(t,e=void 0){let[r,n]=(t||"00:00").split(":").map(ro),o=ZI(e).setHours(r,n,0,0);return ZI(o)}function la(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=Qt(t);if(!r)return"00:00";let n=isNaN(e)?0:e;return Qt(Ef(Ge(r),n).toISOString())}function Ef(t,e){let r=new Date(t);return new Date(r.getTime()+e*6e4)}function ro(t){return t.toString()[1]?t:"0"+t}function qn(t,e){let r=new Date(t),n=new Date(e);return r.getFullYear()===n.getFullYear()&&r.getMonth()===n.getMonth()&&r.getDate()===n.getDate()}var oh={addDays:nh,addWeek:oF,addMinutesToTimeString:Yr,convertTime:Za,getIsoDateString:_m,getUTCdateString:Af,DateHHMM:XL,extractDate:Pt,extractTime:Qt,formatDate:Yn,getDateByWeek:iF,isISODateString:Ja,isDate:Tf,isTimeString:eh,offsetDate:ZI,offsetTime:tF,sameDay:qn,timeStringMinutes:Yt,timeToDate:Ge,timeUTC:ZL,validTimeValue:Yc,validDateString:Om,timeValidation:ws,dateValidation:No};var sF=(t,e)=>t.filter(Boolean).every(r=>typeof r===e),aF=t=>t.filter(Boolean).every(Zt);function Fs(t){let e=t.category;if(typeof e!="object")return{error:Hc};let{ageCategoryCode:r,ageMaxDate:n,ageMinDate:o,ageMax:i,ageMin:s}=e,a=e.categoryName,c;if(!(sF([r,n,o,a],"string")&&aF([i,s])&&[n,o].filter(Boolean).every(Nr)))return{error:Hc};let p=t.consideredDate??Pt(new Date().toLocaleDateString("sv"));if(!Nr(p))return{error:je};let[m]=p.split("-").slice(0,3).map(G=>parseInt(G)),d=up(p,-1),[l,f]=d.split("-").slice(1,3).map(G=>parseInt(G)),g=`${ro(l)}-${ro(f)}`,I=up(p,1),[h,S]=I.split("-").slice(1,3).map(G=>parseInt(G)),T=`${ro(h)}-${ro(S)}`,y=s&&up(p,-1*365*s),E=i&&up(p,-1*365*i),P=[],A=G=>!P.includes(G)&&P.push(G);r=r??a;let U=/^([UO]?)(\d{1,2})([UO]?)$/,N=/^C(\d{1,2})-(\d{1,2})$/,D=r?.includes("-"),M=D&&r?.match(N),R=r?.match(U),b=(G,k)=>`${G}-${k}`,v=G=>{let k=m-G,H=b(k,T);e.ageMinDate&&e.ageMinDate!==H&&A(`Invalid submitted ageMinDate: ${o}`),o=H,r&&(e.ageMax&&e.ageMax!==G-1&&(A(`Invalid submitted ageMax: ${i}`),E=void 0),i=G-1)},O=G=>{let k=m-G-1,H=b(k,T);e.ageMin&&e.ageMin>G&&A(`Invalid submitted ageMin: ${s}`),e.ageMax&&e.ageMax>G&&A(`Invalid submitted ageMax: ${i}`),e.ageMinDate&&e.ageMinDate!==H&&A(`Invalid submitted ageMinDate: ${o}`),o=H,r&&(e.ageMax&&e.ageMax!==G&&(A(`Invalid submitted ageMax: ${i}`),y=void 0),i=G)},x=G=>{let k=m-G,H=b(k,g);e.ageMaxDate&&e.ageMaxDate!==H&&A(`Invalid submitted ageMaxDate: ${n}`),n=H,r&&(e.ageMin&&e.ageMin!==G+1&&(A(`Invalid submitted ageMin: ${s}`),y=void 0),s=G+1)},F=G=>{let k=m-G-1,H=b(k,g);e.ageMaxDate&&e.ageMaxDate!==H&&A(`Invalid submitted ageMaxDate: ${n}`),n=H,r&&(e.ageMin&&e.ageMin!==G&&(A(`Invalid submitted ageMin: ${s}`),y=void 0),s=G)},w=G=>{let[k,H,W]=(G.match(U)||[]).slice(1),q=parseInt(H);k==="U"?(e.ageMaxDate&&e.ageMaxDate!==n&&A(`Invalid submitted ageMaxDate: ${e.ageMaxDate}`),v(q)):k==="O"&&x(q),W==="U"?(e.ageMaxDate&&e.ageMaxDate!==n&&A(`Invalid submitted ageMaxDate: ${e.ageMaxDate}`),O(q)):W==="O"&&F(q),n=n??y,o=o??E};if(M){if(n=void 0,o=void 0,i=void 0,s=void 0,e.ageMin){let H=m-e.ageMin;n=b(H,g)}if(e.ageMax){let H=m-e.ageMax-1;o=b(H,T)}let[G,k]=(r?.match(N)??[]).slice(1).map(H=>parseInt(H));G<=k?(s=G,i=k,c=!0):A(`Invalid combined age range ${r}`)}else D?r?.split("-").forEach(w):R?w(r):(s&&x(s),i&&O(i));i&&e.ageMin&&e.ageMin>i&&(A(`Invalid submitted ageMin: ${e.ageMin}`),s=void 0);let L=nt({consideredDate:p,combinedAge:c,ageMaxDate:n,ageMinDate:o,ageMax:i,ageMin:s});return P.length&&(L.errors=P),L}function qc({category:t}){if(!ht(t))return{error:V};let e=Fs({category:t});if(e.error)return{error:e};let{ratingMax:r,ratingMin:n}=t;return r&&!Zt(r)?_({result:{error:V},context:{ratingMax:r}}):n&&!Zt(n)?_({result:{error:V},context:{ratingMin:n}}):{...e}}function $c({childCategory:t,withDetails:e,category:r}){let n=qc({category:r}),o=qc({category:t}),i=o.ageMin&&(n.ageMin&&o.ageMin<n.ageMin||n.ageMax&&o.ageMin>n.ageMax),s=o.ageMax&&(n.ageMax&&o.ageMax>n.ageMax||n.ageMin&&o.ageMax<n.ageMin),a=o.ageMinDate&&n.ageMaxDate&&new Date(o.ageMinDate)>new Date(n.ageMaxDate),c=o.ageMaxDate&&n.ageMinDate&&new Date(o.ageMaxDate)<new Date(n.ageMinDate),p=r?.ratingType&&t?.ratingType&&r.ratingType===t.ratingType&&(r.ratingMin&&t.ratingMin&&t.ratingMin<r.ratingMin||r.ratingMax&&t.ratingMax&&t.ratingMax>r.ratingMax||r.ratingMin&&t.ratingMax&&t.ratingMax<r.ratingMin||r.ratingMax&&t.ratingMin&&t.ratingMin>r.ratingMax),m=r?.ballType&&t?.ballType&&r.ballType!==t.ballType,f=nt({invalidRatingRange:p,invalidAgeMinDate:a,invalidAgeMaxDate:c,invalidBallType:m,invalidAgeMax:s,invalidAgeMin:i,valid:!p&&!a&&!c&&!m&&!s&&!i},!0);return e&&Object.assign(f,{categoryDetails:n,childCategoryDetails:o}),f}function Kc({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:Io},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&&!kc([kt,xt],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 P=xI({collectionValueProfiles:u,matchUpCount:l});P.errors&&c.push(...P.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 P=bm({referenceGender:i,matchUpType:I,gender:y});if(P.error)return _({context:{referenceGender:i,gender:y},result:P,stack:a})}if(t&&o&&T){let P=$c({category:o,childCategory:T});if(!P.valid)return _({result:{error:Hc},context:P,stack:a})}return c.length?_({result:{errors:c,error:OE},stack:a}):{valid:!0}}function ur(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=cF({...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:E}=Kc({referenceCategory:t.category,referenceGender:t.gender,collectionDefinition:I,checkCollectionIds:n,checkCategory:e,checkGender:r,event:i});return y?!0:(Array.isArray(E)&&a.push(...E),!1)}),m=typeof o.winCriteria?.valueGoal=="number"&&o.winCriteria?.valueGoal>0&&!u||o.winCriteria?.aggregateValue;if(!(m||o.winCriteria?.aggregateValue))return u?a.push("aggregateValue is required"):a.push("Either non-zero valueGoal, or { aggregateValue: true } must be specified in winCriteria"),_({context:{tieFormat:o,errors:a,aggregateValueImperative:u},result:{error:ko},stack:s});let d=o.collectionDefinitions.map(({collectionId:I})=>I),l=!n||d.length===pt(d).length,f=p&&m&&l,g={valid:f,errors:a};return f?g:_({result:{error:ko},context:{tieFormat:o,errors:a},stack:s})}function cF(t){let{tieFormat:e,stack:r}=t;return!t||!e||!ht(e)?_({result:{error:ko},context:{tieFormat:e,message:"tieformat must be an object"},stack:r}):ht(e.winCriteria)?Array.isArray(e.collectionDefinitions)?{...C}:_({result:{error:ko},context:{tieFormat:e,message:"collectionDefinitions must be an array"},stack:r}):_({result:{error:ko},context:{tieFormat:e,message:"tieformat.winCritiera must be an object"},stack:r})}var tc="resourceSubType",ec="resourceType",rc="identifier",KC={RESOURCE_SUB_TYPE:tc,RESOURCE_TYPE:ec,IDENTIFIER:rc};function J(t,e,r,n,o=0){if(XI().makeDeepCopy)return XI().makeDeepCopy(t,e,r,n);let i=df(),{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=Uf(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:YC(f)?p[l]=new Date(f).toISOString():p[l]=J(f,e,r,n,o+1)}return p}function Uf(t){return t?.map(e=>{let{name:r,value:n}=e;return r&&n&&{[`_${r}`]:n}}).filter(Boolean)}function ih(t=1,e){return tt(0,t).map(()=>Mt(e))}function Mt(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 sh={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 ah={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 ch={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 uh={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 ph={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 mh={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 dh={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 lh={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 fh={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 gh={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",TF="SET3-S:6NOAD",$E="SET3-S:6/TB7-F:TB10",yF="SET3-S:4/TB7",AF="SET3-S:4/TB5@3",EF="SET1-S:T20",UF="SET1-S:8/TB7",PF="SET1-S:8/TB7@7",zC={FORMAT_STANDARD:Dn,FORMAT_STANDARD_NOAD:TF,FORMAT_ATP_DOUBLES:$E,FORMAT_SHORT_SETS:yF,FORMAT_FAST4:AF,FORMAT_PRO_SET:UF,FORMAT_COLLEGE_PRO_SET:PF,TIMED20:EF};var Ih={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 hh={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 Sh={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 Th={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 yh={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 Ah={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 Eh={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 xm="COLLEGE_DEFAULT",Uh="COLLEGE_JUCO",Ph="COLLEGE_D3",KE="DOMINANT_DUO",zE="DOMINANT_DUO_MIXED",QE="LAVER_CUP",XE="TEAM_DOUBLES_3_AGGREGATION",JE="TIME_TENNIS_DUAL",ZE="TIME_TENNIS_PRO_CIRCUIT",tU="USTA_BREWER_CUP",eU="USTA_OZAKI_CUP",rU="USTA_COLLEGE",nU="USTA_GOLD_TEAM_CHALLENGE",oU="USTA_LEVEL_1",iU="USTA_INTERSECTIONAL",sU="USTA_SECTION_BATTLE",aU="USTA_SOUTHERN_LEVEL_5",cU="USTA_TOC",uU="USTA_WTT_ITT",pU="USTA_ZONAL",QC={COLLEGE_D3:Ph,COLLEGE_DEFAULT:xm,COLLEGE_JUCO:Uh,DOMINANT_DUO:KE,DOMINANT_DUO_MIXED:zE,LAVER_CUP:QE,TEAM_DOUBLES_3_AGGREGATION:XE,TIME_TENNIS_DUAL:JE,TIME_TENNIS_PRO_CIRCUIT:ZE,USTA_BREWER_CUP:tU,USTA_OZAKI_CUP:eU,USTA_COLLEGE:rU,USTA_GOLD_TEAM_CHALLENGE:nU,USTA_INTERSECTIONAL:iU,USTA_LEVEL_1:oU,USTA_SECTION_BATTLE:sU,USTA_SOUTHERN_LEVEL_5:aU,USTA_TOC:cU,USTA_WTT_ITT:uU,USTA_ZONAL:pU};var JC="STANDARD",XC={[JC]:{hydrate:!0,doubles:{matchUpCount:3,matchUpValue:1},singles:{matchUpCount:6,matchUpValue:1},valueGoal:5},[Ph]:{hydrate:!0,doubles:{matchUpFormat:"SET1-S:8/TB7@7",matchUpCount:3,matchUpValue:1},singles:{matchUpFormat:Dn,matchUpCount:6,matchUpValue:1},tieFormatName:Ph,valueGoal:5},[xm]:{hydrate:!0,doubles:{matchUpFormat:"SET1-S:6/TB7",collectionValue:1,matchUpCount:3},singles:{matchUpFormat:Dn,matchUpCount:6,matchUpValue:1},tieFormatName:xm,valueGoal:4},[Uh]:{hydrate:!0,doubles:{matchUpFormat:"SET1-S:8/TB7",matchUpCount:3,matchUpValue:1},singles:{matchUpFormat:Dn,matchUpCount:6,matchUpValue:1},tieFormatName:Uh,valueGoal:5},[QE]:Ah,[KE]:Ih,[zE]:dh,[XE]:ah,[JE]:lh,[ZE]:mh,[tU]:fh,[eU]:gh,[rU]:hh,[nU]:sh,[iU]:ph,[oU]:Sh,[sU]:uh,[aU]:ch,[uU]:Th,[cU]:Eh,[pU]:yh},OF=t=>{let e=t?.namedFormat&&Object.keys(XC).includes(t.namedFormat)?t.namedFormat:JC,r=Array.isArray(t?.uuids)?t?.uuids:[],n,{category:o,gender:i}=t?.event??{},s=J(XC[e],!1,!0),a=c=>{if(!t?.isMock&&!t?.event?.isMock||!t.event)return r?.pop()??Mt();let u=t?.event?.eventId;return r.pop()??`${u}-COL-${c+1}`};return s.hydrate?(n={winCriteria:{valueGoal:s.valueGoal},collectionDefinitions:[{collectionId:a(0),matchUpFormat:$E,collectionName:"Doubles",matchUpType:xt,...s.doubles},{collectionId:a(1),matchUpFormat:Dn,collectionName:"Singles",matchUpType:kt,...s.singles}]},s.tieFormatName&&(n.tieFormatName=s.tieFormatName)):(s.collectionDefinitions.forEach((c,u)=>c.collectionId=a(u)),n=s),t?.hydrateCollections&&n.collectionDefinitions.forEach(c=>{o&&!c.category&&(c.category=o),i&&!c.gender&&(c.gender=i)}),n},no=OF;var $n="SINGLES",ks="SINGLES",qr="DOUBLES",Vo="DOUBLES",_e="TEAM",br="TEAM",_F="AGE",xF="RATING",wF="BOTH",ZC={AGE:_F,BOTH:wF,DOUBLES:qr,DOUBLES_EVENT:Vo,RATING:xF,SINGLES:$n,SINGLES_EVENT:ks,TEAM_EVENT:br,TEAM:_e};var rt="MAIN",ct="QUALIFYING",qe="CONSOLATION",$e="VOLUNTARY_CONSOLATION",fe="PLAY_OFF",zc=[rt,ct,qe,fe,$e],Gs={[ct]:1,[rt]:2,[fe]:3,[qe]:3,[$e]:4},mU="finishingPositions",dU="aggregateEventStructures",lU={[rt]:1,[fe]:2,[qe]:3,[ct]:4,[$e]:5},tb={[fe]:1,[rt]:2,[qe]:3,[ct]:4,[$e]:5},Qc="CLUSTER",eb="SEPARATE",li="WATERFALL",pp="ITEM",Ve="CONTAINER",dn="DRAW",mp="RANDOM",En="TOP_DOWN",fi="BOTTOM_UP",xn="POSITION",Kn="WINNER",oo="LOSER",wn="FIRST_MATCHUP",$r="AD_HOC",LF="AD_HOC",fa="FEED_IN",Xc="COMPASS",Jc="OLYMPIC",FF="SINGLE_ELIMINATION";var ho="SINGLE_ELIMINATION",Zc="DOUBLE_ELIMINATION",tu="FIRST_MATCH_LOSER_CONSOLATION",dp="FIRST_ROUND_LOSER_CONSOLATION",Vi="LUCKY_DRAW",Pf="CURTIS_CONSOLATION",rb="CURTIS_CONSOLATION",Dh="FEED_IN_CHAMPIONSHIP_TO_SF",wm="FEED_IN_CHAMPIONSHIP_TO_SF",Nh="FEED_IN_CHAMPIONSHIP_TO_QF",Lm="FEED_IN_CHAMPIONSHIP_TO_QF",Mh="FEED_IN_CHAMPIONSHIP_TO_R16",Fm="FEED_IN_CHAMPIONSHIP_TO_R16",fU="MODIFIED_FEED_IN_CHAMPIONSHIP",km="MODIFIED_FEED_IN_CHAMPIONSHIP",lp="FEED_IN_CHAMPIONSHIP",nb="DOUBLE_ROUND_ROBIN",Nn="ROUND_ROBIN",So="ROUND_ROBIN_WITH_PLAYOFF",gU="DECIDER",IU="BACKDRAW",Df={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"}},Nf={0:{name:"East",abbreviation:"E"},"0-1":{name:"West",abbreviation:"W"},"0-2":{name:"North",abbreviation:"N"},"0-1-1":{name:"South",abbreviation:"S"}},gi="WIN_RATIO",Bi="ROUND_OUTCOME",hU=[Xc,Pf,Lm,Fm,wm,lp,Nh,Mh,Dh,tu,dp,Vi,km,Jc,fe,So],kF=[$r,Xc,Pf,Zc,Lm,Fm,wm,lp,fa,tu,dp,Vi,km,Jc,fe,Nn,So,ho],SU={MAIN:rt,QUALIFYING:ct,CONSOLATION:qe,ITEM:pp,CONTAINER:Ve,FIRST_MATCHUP:wn,WINNER:Kn,LOSER:oo,AD_HOC:$r,FEED_IN:fa,FLEX_ROUNDS:LF,COMPASS:Xc,PLAY_OFF:fe,OLYMPIC:Jc,KNOCKOUT:FF,SINGLE_ELIMINATION:ho,DOUBLE_ELIMINATION:Zc,CURTIS:Pf,FICSF:Dh,FICQF:Nh,FICR16:Mh,MFIC:fU,VOLUNTARY_CONSOLATION:$e,FIRST_MATCH_LOSER_CONSOLATION:tu,FIRST_ROUND_LOSER_CONSOLATION:dp,MODIFIED_FEED_IN_CHAMPIONSHIP:km,FEED_IN_CHAMPIONSHIP_TO_R16:Fm,FEED_IN_CHAMPIONSHIP_TO_QF:Lm,FEED_IN_CHAMPIONSHIP_TO_SF:wm,FEED_IN_CHAMPIONSHIP:lp,LUCKY_DRAW:Vi,ROUND_ROBIN_WITH_PLAYOFF:So,ROUND_ROBIN:Nn,DECIDER:gU,BACKDRAW:IU,COMPASS_ATTRIBUTES:Df,OLYMPIC_ATTRIBUTES:Nf,DRAW:dn,RANDOM:mp,TOP_DOWN:En,BOTTOM_UP:fi,WATERFALL:li,WIN_RATIO:gi,ROUND_OUTCOME:Bi,MULTI_STRUCTURE_DRAWS:hU,generatedDrawTypes:kF,stageOrder:Gs,finishOrder:lU,AGGREGATE_EVENT_STRUCTURES:dU,FINISHING_POSITIONS:mU},ob=SU;var Re="tournamentRecords",Mf="policyDefinitions",ne="tournamentRecord",Rh="onlineResource",Ce="drawDefinition",Ch="tieFormatName",Gm="matchUpFormat",io="participantId",bh="scheduleDates",ib="tournamentId",sb="scheduleDate",ab="roundNumber",eu="structureId",Rf="participant",nc="matchUpIds",vh="entryStage",cb="policyType",TU="structures",Cf="eventType",ln="matchUpId",Vm="tieFormat",ru="inContext",fp="structure",gp="courtIds",ub="personId",Ip="venueIds",bf="matchUps",Oh="courtId",_h="eventId",Ln="matchUp",xh="drawId",fn="error",so="event",ss="param",vf="uuids",pb="averageMatchUpMinutes",mb="recoveryMinutes",db="periodLength",lb="number";var Kr="object",Be="array";var er="_validate",wh="_message",Fr="_invalid",He="_ofType",Bm="_anyOf",Vs="_oneOf";var fb={[Rh]:t=>jt(Object.keys(t),[tc,ec,rc]).length===3,[Ch]:t=>t&&no({namedFormat:t}),[vf]:t=>!t||Array.isArray(t)&&t.every(Vt),[Vm]:t=>!ur({tieFormat:t}).error,[Cf]:t=>[$n,qr,_e].includes(t),[vh]:t=>zc.includes(t)},GF={[Re]:Lt,[ne]:$,[Mf]:Xu,[Ce]:Z,[io]:ie,[Gm]:$l,[ib]:pa,[eu]:Ur,[nc]:ns,[Rf]:Fi,[Rh]:Io,[Cf]:jn,[TU]:Hl,[ln]:cr,[Vm]:ko,[fp]:di,[Oh]:wi,[bf]:eo,[_h]:jr,[Ln]:Tr,[gp]:st,[Ip]:st,[xh]:sn,[so]:Ot},VF={[Re]:Kr,[Mf]:Kr,[ne]:Kr,[Ce]:Kr,[Rh]:Kr,[bh]:Be,[Rf]:Kr,[nc]:Be,[TU]:Be,[Vm]:Kr,[fp]:Kr,[gp]:Be,[Ip]:Be,[bf]:Be,[Ln]:Kr,[so]:Kr,[vf]:Be};function et(t,e,r){if(!t&&!ht(t))return{error:V};if(!e?.length||t?._bypassParamCheck)return{valid:!0};if(!Array.isArray(e))return{error:V};let{paramError:n,errorParam:o}=WF(t,e);if(!n)return{valid:!0};let i=n[er]&&(n[fn]||n[Fr])||t?.[o]===void 0&&(n[fn]||n[Fr]||GF[o]||V)||V,s=o??(n[Vs]&&Object.keys(n[Vs]).join(", "));return _({info:{param:s,message:n[wh]},result:{error:i},stack:r})}function gb(t,e){let r=Object.keys(t),n=Object.keys(e);return jt(r,n)}function BF(t,e){if(!e)return;let r=gb(t,e);return r.length!==1?{error:V}:r.reduce((n,o)=>({...n,[o]:!0}),{})}function HF(t,e){if(!e)return;let r=gb(t,e).filter(n=>t[n]);return r.length<1?{error:V}:r.reduce((n,o)=>({...n,[o]:!0}),{})}function WF(t,e){let r,n;return{paramError:e.find(({_ofType:i,_oneOf:s,_anyOf:a,_validate:c,_info:u,...p})=>{let m=s&&BF(t,s);if(m?.error)return m.error;m&&Object.assign(p,m);let d=a&&HF(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&&jF(t,g,i),S=p[g]&&[void 0,null].includes(t[g]),y=I||h||S||c&&t[g]!==void 0&&!YF(t[g],c)||fb[g]&&!fb[g](t[g]);return y&&(r=g,n=u),y});return!l.length||f}),errorParam:r,paramInfo:n}}function jF(t,e,r){return r=r||VF[e]||"string",r==="array"?!Array.isArray(t[e]):typeof t[e]!==r}function YF(t,e){return Wr(e)?e(t):!0}var Hm="DYNAMIC",Ii="RANKING",hi="RATING",Si="SCALE",To="SEEDING",Ib={RANKING:Ii,RATING:hi,SCALE:Si,SEEDING:To};function ga(t){let e=et(t,[{[Rf]:!0}]);if(e.error)return e;let r=t.participant.timeItems?.filter(({itemType:o})=>o?.startsWith(Si)&&[Ii,hi,To].includes(o.split(".")[1])),n={ratings:{},rankings:{},seedings:{}};if(r?.length){let o=s=>r.filter(a=>a?.itemType===s).sort((a,c)=>new Date(a.createdAt||void 0).getTime()-new Date(c.createdAt||void 0).getTime()).pop(),i=pt(r.map(({itemType:s})=>s));for(let s of i){let a=o(s);if(a){let[,c,u,p,m]=a.itemType.split("."),d=m?`${p}.${m}`:p,l=c===To&&"seedings"||c===Ii&&"rankings"||"ratings";n[l][u]||(n[l][u]=[]),n[l][u].push({scaleValue:a.itemValue,scaleDate:a.itemDate,scaleName:d})}}}return{...C,...n}}function Hi(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 Lh="voluntaryConsolation",Ti="competitiveBands",Of="roundRobinTally",zn="positionActions",rr="matchUpActions",_f="rankingPoints",Ia="roundNaming",Bs="participant",nu="progression",Mo="scheduling",ou="avoidance",qF="participant",$F="display",tn="scoring",Fn="seeding",oc="feedIn",KF="audit",Wm="draws",hb={POLICY_TYPE_VOLUNTARY_CONSOLATION:Lh,POLICY_TYPE_COMPETITIVE_BANDS:Ti,POLICY_TYPE_ROUND_ROBIN_TALLY:Of,POLICY_TYPE_POSITION_ACTIONS:zn,POLICY_TYPE_MATCHUP_ACTIONS:rr,POLICY_TYPE_RANKING_POINTS:_f,POLICY_TYPE_ROUND_NAMING:Ia,POLICY_TYPE_PARTICIPANT:Bs,POLICY_TYPE_PROGRESSION:nu,POLICY_TYPE_SCHEDULING:Mo,POLICY_TYPE_AVOIDANCE:ou,POLICY_TYPE_DISPLAY:$F,POLICY_TYPE_PRIVACY:qF,POLICY_TYPE_FEED_IN:oc,POLICY_TYPE_SCORING:tn,POLICY_TYPE_SEEDING:Fn,POLICY_TYPE_AUDIT:KF,POLICY_TYPE_DRAWS:Wm};function Bo({tournamentParticipants:t=[],policyDefinitions:e={},contextProfile:r,participantId:n,internalUse:o,personId:i}){let s=t.find(c=>n&&c.participantId===n||i&&c.person&&c.person.personId===i),a=J(s,!1,o);if(a){let c=e?.[Bs];if(r?.withScaleValues){let{ratings:u,rankings:p}=ga({participant:a});a.rankings=p,a.ratings=u}if(c?.participant)return Hi({template:c.participant,source:a})}return a}var Sb="element required",Tb="missing name";function gr(t){if(!t||typeof t!="object")return{error:st};if(t.element&&typeof t?.element!="object")return{error:V};if(!t?.name)return{error:st,info:Tb};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:Sb}}return t?.element.extensions?(t.element.extensions=t.element.extensions.filter(e=>e?.name!==t.name),{...C}):{...C,info:ve}}function kn({requiredAttributes:t=["name","value"],extension:e}){if(!e||typeof e!="object"||typeof e.name!="string")return!1;let r=Object.keys(e);return t.filter(n=>r.includes(n)).length===t.length}function Ut(t){if(typeof t!="object")return{error:st};let e="addExtension";if(t?.element&&typeof t.element!="object")return _({result:{error:V},stack:e});if(!kn({extension:t.extension}))return _({result:{error:V,info:"invalid extension"},stack:e});if(!t.element)if(t.discover&&!t.tournamentId&&t.tournamentRecords){for(let o of Object.values(t.tournamentRecords)){let i=Ut({extension:t.extension,element:o});if(i.error)return _({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 xf(t){return!t||typeof t!="object"?{error:st}:t.tournamentRecord?Ut({creationTime:t.creationTime,element:t.tournamentRecord,extension:t.extension}):{error:$}}function hp(t){return!t||typeof t!="object"?{error:st}:t.drawDefinition?Ut({creationTime:t.creationTime,element:t.drawDefinition,extension:t.extension}):{error:Cr}}function Ro(t){return!t||typeof t!="object"?{error:st}:t.event?Ut({creationTime:t.creationTime,extension:t.extension,element:t.event}):{error:jr}}function yU(t){if(!t||typeof t!="object")return{error:st};if(!t.participantId)return{error:ie};let e=t.tournamentRecord?.participants||[],r=Bo({participantId:t.participantId,tournamentParticipants:e});return r?Ut({creationTime:t.creationTime,extension:t.extension,element:r}):{error:re}}function wf(t){return!t||typeof t!="object"?{error:st}:t.tournamentRecord?gr({element:t.tournamentRecord,name:t.name}):{error:$}}function AU(t){return!t||typeof t!="object"?{error:st}:t.drawDefinition?gr({element:t.drawDefinition,name:t.name}):{error:Cr}}function Sp(t){return!t||typeof t!="object"?{error:st}:t?.event?gr({element:t.event,name:t.name}):{error:jr}}function EU(t){if(!t||typeof t!="object")return{error:st};if(!t.participantId)return{error:ie};let e=t.tournamentRecord?.participants||[],r=Bo({participantId:t.participantId,tournamentParticipants:e});return r?gr({element:r,name:t.name}):{error:re}}function Tp({tournamentRecords:t}){return{tournamentIds:ht(t)?Object.keys(t):[],...C}}var zF="extensionQueries";function mt({discover:t,element:e,name:r,...n}){if(!e||!r){if(t&&n){let s=Object.keys(n).filter(p=>typeof t=="boolean"||Array.isArray(t)&&t.includes(p)).find(p=>Array.isArray(n[p]?.extensions)?n[p].extensions.find(m=>m?.name===r):!1),a=s&&n[s];!a&&n.tournamentRecords&&(a=Object.values(n.tournamentRecords).find(p=>p.extensions?.length));let c=a?.extensions?.find(p=>p?.name===r);return{extension:c,info:c?void 0:ve}}return _({result:{error:st},stack:zF})}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 QF="activeSuspension",iu="appliedPolicies",UU="context",jm="delegatedOutcome",ao="disabled",ha="disableAutoCalc",Ym="disableLinks",qm="display",Sa="drawDeletions",XF="drawProfile",$m="entryProfile",JF="eventProfile",ZF="eventWithdrawalRequests",tk="factory",cn="flightProfile",Fh="groupingAttribute",Co="lineUps",Hs="linkedTournamentsIds",Km="matchUpHistory",kh="participantRepresentatives",Ta="personRequests",ic="positionActions",ek="rankingPoints",rk="registration",Mn="roundTarget",su="scheduleLimits",Ho="scheduleTiming",ya="schedulingProfile",nk="statusDetail",sc="subOrder",bo="tally",zm="tieFormatModification",Gh={ACTIVE_SUSPENSION:QF,APPLIED_POLICIES:iu,CONTEXT:UU,DELEGATED_OUTCOME:jm,DISABLED:ao,DISABLE_LINKS:Ym,DISABLE_AUTO_CALC:ha,DISPLAY:qm,DRAW_DELETIONS:Sa,DRAW_PROFILE:XF,ENTRY_PROFILE:$m,EVENT_PROFILE:JF,EVENT_WITHDRAWAL_REQUESTS:ZF,FLIGHT_PROFILE:cn,GROUPING_ATTRIBUTE:Fh,LINEUPS:Co,LINKED_TOURNAMENTS:Hs,MATCHUP_HISTORY:Km,PARTICIPANT_REPRESENTATIVES:kh,PERSON_REQUESTS:Ta,POSITION_ACTIONS:ic,RANKING_POINTS:ek,REGISTRATION:rk,ROUND_TARGET:Mn,SCHEDULE_LIMITS:su,SCHEDULE_TIMING:Ho,SCHEDULING_PROFILE:ya,STATUS_DETAIL:nk,SUB_ORDER:sc,TALLY:bo,TIE_FORMAT_MODIFICATIONS:zm,FACTORY:tk},PU=[jm,ao,ha,Ym,cn,Co,Hs,Km,kh,Ta,Mn,su,Ho,ya,sc,bo,zm];function DU({tournamentRecords:t}){if(typeof t!="object"||!Object.keys(t).length)return{error:Lt};let e=Tp({tournamentRecords:t}),{tournamentIds:r}=e;return r?.length>1?Ut({tournamentRecords:t,discover:!0,extension:{name:Hs,value:{tournamentIds:r}}}):{...C}}function NU({tournamentRecords:t}){if(typeof t!="object"||!Object.keys(t).length)return{error:Lt};let e=gr({name:Hs,tournamentRecords:t,discover:!0});return _({result:e,stack:"unlinkTournaments"})}function MU({tournamentRecords:t,tournamentId:e}){if(typeof t!="object")return{error:V};if(!e)return{error:pa};let r=Tp({tournamentRecords:t}),{tournamentIds:n}=r;if(!n.includes(e))return{error:pa};let o;return n.every(i=>{let s=t[i],{extension:a}=mt({element:s,name:Hs});if(!a)return!0;let c=a?.value?.tournamentIds||[];if(!c?.length||c.length===1&&c.includes(e)||i===e){let m=wf({name:Hs,tournamentRecord:s});return m.error&&(o=m.error),m.success}let u=c.filter(m=>m!==e);a.value={tournamentIds:u};let p=xf({tournamentRecord:s,extension:a});return p.error&&(o=p.error),p.success}),o?{error:o}:{...C}}var CU={};Jt(CU,{getLinkedTournamentIds:()=>au,getTournamentIds:()=>Tp});function au({tournamentRecords:t}){return typeof t!="object"||!Object.keys(t).length?{error:Lt}:{linkedTournamentIds:Object.assign({},...Object.keys(t).map(r=>{let n=t[r],o=n?.tournamentId,{extension:i}=mt({element:n,name:Hs}),s=(i?.value?.tournamentIds||[]).filter(a=>a!==o);return{[r]:s}}))}}var _N={};Jt(_N,{adHocPositionSwap:()=>BP,addAdHocMatchUps:()=>Od,addDrawDefinitionTimeItem:()=>Dg,addFinishingRounds:()=>Pa,addGoesTo:()=>Ki,addPlayoffStructures:()=>Bp,addQualifyingStructure:()=>VP,addVoluntaryConsolationStage:()=>xP,addVoluntaryConsolationStructure:()=>gg,allPlayoffPositionsFilled:()=>FS,alternateDrawPositionAssignment:()=>EP,assignDrawPosition:()=>eD,assignDrawPositionBye:()=>Hr,attachConsolationStructures:()=>XP,attachPlayoffStructures:()=>wg,attachQualifyingStructure:()=>Pg,attachStructures:()=>Lg,autoSeeding:()=>rx,automatedPlayoffPositioning:()=>zs,automatedPositioning:()=>yc,checkValidEntries:()=>wd,deleteAdHocMatchUps:()=>rD,drawMatic:()=>Kd,findDrawDefinition:()=>uT,generateAdHocMatchUps:()=>Lu,generateAdHocRounds:()=>$d,generateAndPopulatePlayoffStructures:()=>vd,generateDrawDefinition:()=>wa,generateDrawMaticRound:()=>Gd,generateDrawStructuresAndLinks:()=>Ld,generateDrawTypeAndModifyDrawDefinition:()=>Fd,generateQualifyingStructure:()=>Nd,generateVoluntaryConsolation:()=>bT,getAssignedParticipantIds:()=>Ci,getAvailableMatchUpsCount:()=>_d,getAvailablePlayoffProfiles:()=>Cu,getDrawDefinitionTimeItem:()=>tS,getDrawParticipantRepresentativeIds:()=>aT,getDrawStructures:()=>gn,getDrawTypeCoercion:()=>xu,getEligibleVoluntaryConsolationParticipants:()=>sT,getMatchUpsMap:()=>Me,getParticipantIdFinishingPositions:()=>cT,getPositionAssignments:()=>Hp,getPositionsPlayedOff:()=>Ec,getRandomQualifierList:()=>ET,getSeedingThresholds:()=>MS,getSeedsCount:()=>wu,getStructureSeedAssignments:()=>nn,getTeamLineUp:()=>ds,getValidGroupSizes:()=>Op,isAdHoc:()=>pr,isCompletedStructure:()=>Eo,isValidForQualifying:()=>UT,luckyLoserDrawPositionAssignment:()=>SP,modifyDrawDefinition:()=>JP,modifyDrawName:()=>Fg,modifySeedAssignment:()=>CP,mutate:()=>iD,positionActions:()=>AT,pruneDrawDefinition:()=>tD,qualifierDrawPositionAssignment:()=>Ug,qualifierProgression:()=>bP,query:()=>ID,removeDrawPositionAssignment:()=>Pu,removeRoundMatchUps:()=>nD,removeSeededParticipant:()=>GP,removeStructure:()=>_P,renameStructures:()=>OP,resetDrawDefinition:()=>ZP,resetQualifyingStructure:()=>wP,resetVoluntaryConsolationStructure:()=>VU,setDrawParticipantRepresentativeIds:()=>OU,setPositionAssignments:()=>yP,setStructureOrder:()=>vP,setSubOrder:()=>oD,shiftAdHocRounds:()=>TP,swapAdHocRounds:()=>AP,swapDrawPositionAssignments:()=>kP,updateTeamLineUp:()=>Qi,withdrawParticipantAtDrawPosition:()=>IP});var iD={};Jt(iD,{adHocPositionSwap:()=>BP,addAdHocMatchUps:()=>Od,addDrawDefinitionTimeItem:()=>Dg,addPlayoffStructures:()=>Bp,addQualifyingStructure:()=>VP,addVoluntaryConsolationStage:()=>xP,addVoluntaryConsolationStructure:()=>gg,alternateDrawPositionAssignment:()=>EP,assignDrawPosition:()=>eD,assignDrawPositionBye:()=>Hr,attachConsolationStructures:()=>XP,attachPlayoffStructures:()=>wg,attachQualifyingStructure:()=>Pg,attachStructures:()=>Lg,automatedPlayoffPositioning:()=>zs,automatedPositioning:()=>yc,deleteAdHocMatchUps:()=>rD,luckyLoserDrawPositionAssignment:()=>SP,modifyDrawDefinition:()=>JP,modifyDrawName:()=>Fg,modifySeedAssignment:()=>CP,pruneDrawDefinition:()=>tD,qualifierDrawPositionAssignment:()=>Ug,qualifierProgression:()=>bP,removeDrawPositionAssignment:()=>Pu,removeRoundMatchUps:()=>nD,removeSeededParticipant:()=>GP,removeStructure:()=>_P,renameStructures:()=>OP,resetDrawDefinition:()=>ZP,resetQualifyingStructure:()=>wP,resetVoluntaryConsolationStructure:()=>VU,setDrawParticipantRepresentativeIds:()=>OU,setPositionAssignments:()=>yP,setStructureOrder:()=>vP,setSubOrder:()=>oD,shiftAdHocRounds:()=>TP,swapAdHocRounds:()=>AP,swapDrawPositionAssignments:()=>kP,updateTeamLineUp:()=>Qi,withdrawParticipantAtDrawPosition:()=>IP});var vU=t=>e=>t[e],Qm=(t=[])=>t.map(Ue).filter(Boolean),Lf=(t=[])=>t.map(St).filter(Boolean),St=(t={})=>vU(t)("participantId");var Ue=(t={})=>vU(t)("matchUpId"),cu=(t={})=>vU(t)("drawId");function OU({representativeParticipantIds:t,drawDefinition:e}){if(!e)return{error:Cr};if(!Array.isArray(t))return{error:V};let r=Lf(e?.entries||[]);return t.length&&jt(t,r).length<t.length?{error:V}:hp({drawDefinition:e,extension:{name:kh,value:t}})}var vr="ABANDONED",ac="AWAITING_RESULT",Nt="BYE",co="CANCELLED",he="COMPLETED",uu="DEAD_RUBBER",Rt="DEFAULTED",be="DOUBLE_DEFAULT",Te="DOUBLE_WALKOVER",Gn="IN_PROGRESS",un="INCOMPLETE",_U="NOT_PLAYED",nr="RETIRED",as="SUSPENDED",Xt="TO_BE_PLAYED",bt="WALKOVER",yb=[ac,he,Rt,Gn,un,nr,as],Vh=[ac,he,Rt,Te,be,Gn,un,nr,as,bt],Bh=[vr,ac,Nt,co,he,uu,Rt,Te,be,Gn,un,_U,nr,as,Xt,bt],Hh=[Nt,Te,be,he,Rt,nr,bt],Wh=[vr,ac,co,uu,Gn,un,_U,as,Xt,void 0],se=[co,vr,he,uu,Rt,Te,be,nr,bt],Xm=[vr,he,Rt,Te,be,Gn,nr,bt],jh=[Gn,un,as,Xt],Yh={ABANDONED:vr,AWAITING_RESULT:ac,BYE:Nt,CANCELLED:co,COMPLETED:he,DEAD_RUBBER:uu,DEFAULTED:Rt,DOUBLE_WALKOVER:Te,DOUBLE_DEFAULT:be,IN_PROGRESS:Gn,INCOMPLETE:un,NOT_PLAYED:_U,RETIRED:nr,SUSPENDED:as,TO_BE_PLAYED:Xt,WALKOVER:bt};function yi(t,e,r){let n=m=>mt({element:m,name:Mn})?.extension?.value,o=r?.deprioritizeCompleted,i=r?.mode===dU&&tb,s=r?.mode===mU&&lU,a=s||i||Gs,c=m=>m?.stage===rt&&m?.stageSequence===1,u=m=>c(m)?-1:a[m?.stage],p=m=>m?.matchUps.every(({matchUpStatus:d})=>se.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)||(Ff(t)||0)-(Ff(e)||0)}function Ff(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=et(t,[{[Ce]:!0,[eu]:!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:wt};let a=s.structureType===pp?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&&Hl||void 0;if(c)return{error:c,structures:[],stageStructures:{}};let u=f=>{let g=mt({element:f,name:Mn})?.extension?.value;return!o||o===g},p=e?.structures?.filter(d).filter(l).filter(u).sort((f,g)=>yi(f,g,i))??[],m=t?Object.assign({},...zc.map(f=>{let g=p?.filter(I=>I.stage===f);return g?.length&&{[f]:g}}).filter(Boolean)):{};return{structures:p,stageStructures:m};function d(f){return!a&&!Array.isArray(s)||a&&f.stage===a||Array.isArray(s)&&s.includes(f.stage)}function l(f){return!n&&!Array.isArray(r)||n&&f.stageSequence===n||Array.isArray(r)&&r.includes(f.stageSequence)}}function qh({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}=Ct({structure:n}),s=i?.map(St).filter(Boolean)??[];return e[o].push(...s),s}).flat(),stagePositionedParticipantIds:e}}function Ct({drawDefinition:t,structureId:e,structure:r}){let n,o=[];if(!r){if(!t)return{positionAssignments:o,error: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=>Ct({structure:i}).positionAssignments)):r.positionAssignments?o=r.positionAssignments:n=JA,{positionAssignments:o,error:n}}function ge({drawDefinition:t,structureId:e,structure:r}){let n=Ct({drawDefinition:t,structureId:e,structure:r})?.positionAssignments||[],o=n?.filter(u=>u.participantId??u.bye??u.qualifier),i=n&&n?.length===o?.length,s=n?.filter(u=>!u.participantId&&!u.bye&&!u.qualifier),a=n?.filter(u=>!u.participantId&&u.bye),c=n?.filter(u=>!u.participantId&&u.qualifier);return{allPositionsAssigned:i,positionAssignments:n,unassignedPositions:s,assignedPositions:o,qualifierPositions:c,byePositions:a}}var kf="addDrawDefinition",yp="addMatchUps",ei="addParticipants",Gf="addScaleItems",xU="addEvent",$h="addVenue",Ai="audit",Kh="dataIssue",Vf="deleteParticipants",Bf="deleteVenue",Hf="deletedDrawIds",Wf="deletedMatchUpIds",jf="modifyDrawDefinition",wU="modifyDrawEntries",LU="modifyEventEntries",Yf="modifyMatchUp",or="modifyParticipants",qf="modifyPositionAssignments",$f="modifySeedAssignments",Wi="modifyTournamentDetail",Ei="modifyVenue",Jm="mutations",zh="publishEvent",FU="publishEventSeeding",kU="publishOrderOfPlay",GU="publishParticipants",Kf="unPublishEvent",zf="unPublishEventSeeding",Qf="unPublishOrderOfPlay",Ab="unPublishParticipants",Ap="updateInContextMatchUp",Eb={ADD_DRAW_DEFINITION:kf,ADD_MATCHUPS:yp,ADD_PARTICIPANTS:ei,ADD_SCALE_ITEMS:Gf,ADD_EVENT:xU,ADD_VENUE:$h,AUDIT:Ai,DATA_ISSUE:Kh,DELETE_PARTICIPANTS:Vf,DELETE_VENUE:Bf,DELETED_DRAW_IDS:Hf,DELETED_MATCHUP_IDS:Wf,MODIFY_DRAW_DEFINITION:jf,MODIFY_DRAW_ENTRIES:wU,MODIFY_EVENT_ENTRIES:LU,MODIFY_MATCHUP:Yf,MODIFY_PARTICIPANTS:or,MODIFY_POSITION_ASSIGNMENTS:qf,MODIFY_SEED_ASSIGNMENTS:$f,MODIFY_TOURNAMENT_DETAIL:Wi,MODIFY_VENUE:Ei,MUTATIONS:Jm,PUBLISH_EVENT_SEEDING:FU,PUBLISH_EVENT:zh,PUBLISH_ORDER_OF_PLAY:kU,PUBLISH_PARTICIPANTS:GU,UNPUBLISH_EVENT_SEEDING:zf,UNPUBLISH_EVENT:Kf,UNPUBLISH_ORDER_OF_PLAY:Qf,UPDATE_INCONTEXT_MATCHUP:Ap};function Qh(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 vo({drawDefinition:t,tournamentId:e,matchUps:r,eventId:n}){return t&&Qh(t),lt({payload:{matchUps:r,tournamentId:e,eventId:n},topic:yp}),{...C}}function Rn({drawDefinition:t,tournamentId:e,matchUpIds:r,eventId:n,action:o}){t&&Qh(t),lt({topic:Wf,payload:{tournamentId:e,matchUpIds:r,eventId:n,action:o}});for(let i of r)QI({key:i});return{...C}}function gt({drawDefinition:t,tournamentId:e,structureId:r,context:n,eventId:o,matchUp:i}){return i?(t&&vt({drawDefinition:t,structureIds:r?[r]:void 0,tournamentId:e,eventId:o}),lt({topic:Yf,payload:{matchUp:i,tournamentId:e,context:n},key:i.matchUpId}),{...C}):(console.log(Tr),{error:Tr})}function Ub({tournamentId:t,inContextMatchUp:e}){return e?(lt({payload:{inContextMatchUp:e,tournamentId:t},topic:Ap,key:e.matchUpId}),{...C}):{error:Tr}}function Aa({tournamentId:t,eventId:e,drawDefinition:r}){return r?(Qh(r),lt({payload:{drawDefinition:r,tournamentId:t,eventId:e},topic:kf,key:r.drawId}),{...C}):(console.log(Z),{error:Z})}function Pb({tournamentId:t,eventId:e,drawId:r}){return lt({payload:{drawId:r,tournamentId:t,eventId:e},topic:Hf,key:r}),QI({key:r}),{...C}}function vt({drawDefinition:t,tournamentId:e,structureIds:r,eventId:n}){return t?(Qh(t,r),lt({payload:{tournamentId:e,eventId:n,drawDefinition:t},topic:jf,key:t.drawId}),{...C}):{error:Z}}function Xh({drawDefinition:t,tournamentId:e,structure:r,eventId:n}){if(!t)return{error:Z};if(!r)return{error:di};let o=r.seedAssignments,i=r.structureId,s=t.drawId;return lt({payload:{tournamentId:e,eventId:n,drawId:s,structureId:i,seedAssignments:o},topic:$f,key:t.drawId}),vt({structureIds:[i],drawDefinition:t,tournamentId:e,eventId:n}),{...C}}function Oo({drawDefinition:t,tournamentId:e,structure:r,event:n}){if(!t)return{error:Z};if(!r)return{error:di};let o=Ct({structure:r}),i=r.structureId,s=t.drawId,a=n?.eventId;return lt({topic:qf,payload:{positionAssignments:o,tournamentId:e,structureId:i,eventId:a,drawId:s},key:i}),vt({structureIds:[i],drawDefinition:t,tournamentId:e,eventId:a}),{...C}}function VU({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:wt};let i=o.matchUps?.map(({matchUpId:s})=>s)||[];return o.positionAssignments=[],o.seedAssignments=[],o.matchUps=[],Rn({tournamentId:t?.tournamentId,action:"resetVoluntaryConsolationStructure",matchUpIds:i,drawDefinition:e}),r&&(e.entries=e.entries.filter(s=>s.entryStage!==$e)),vt({tournamentId:t?.tournamentId,eventId:n?.eventId,drawDefinition:e,structureIds:[o.structureId]}),{...C}}function Zm({drawPositions:t,structure:e}){if([ct,rt].includes(e.stage)&&e.stageSequence===1)return;let{positionAssignments:r}=Ct({structure:e});r?.filter(({drawPosition:o})=>t?.includes(o))?.forEach(o=>{Ut({element:o,extension:{name:Ym,value:!0}})})}function pu(t){let{appliedPolicies:e,positionAction:r,drawDefinition:n}=t;if(e?.audit?.[ic]===!1)return;let{extension:o}=mt({name:ic,element:n}),i=Array.isArray(o?.value)?o?.value??[]:[];if(!i?.length){let a=n.structures.find(c=>c.stage===rt);if(a){let c=Ct({structure:a}).positionAssignments?.map(({drawPosition:u,participantId:p,bye:m,qualifier:d})=>({drawPosition:u,participantId:p,qualifier:d,bye:m}));i.push({name:"initialMainAssignments",initialAssignments:c})}}let s={value:i.concat(r),name:ic};Ut({element:n,extension:s})}function cs({tournamentRecord:t,drawDefinition:e,event:r}){let o=(t?.events||r&&[r])?.map(c=>c?.drawDefinitions).flat().filter(Boolean)||e&&[e]||[],i={},s={},a=o.map(c=>c?.structures?.filter(u=>u?.structures)).flat().filter(Boolean);for(let c of a){let{structures:u,structureId:p}=c??{};u&&p&&(i[p]=u?.map(m=>m.structureId))&&u.forEach(m=>s[m.structureId]=c?.structureId)}return{containedStructures:i,containerStructures:s}}function mu(t){let{sides:e,matchUpType:r}=t||{},n=t.potentialParticipants?.length?t.potentialParticipants.flat().map(s=>r===xt?s?.individualParticipantIds||[]:s.participantId).flat():[],o=(e||[]).map(s=>r===xt&&(s?.participant?.individualParticipantIds||[])||s?.participantId&&[s.participantId]||[]).flat();return{individualParticipantIds:o.concat(n).flat(),enteredIndividualParticipantIds:o,potentialIndividualParticipantIds:n}}function Mr(t){return t?.tournamentRecords??(t?.tournamentRecord&&{[t.tournamentRecord.tournamentId]:t.tournamentRecord})??{}}var cc="SIGN_IN_STATUS",BU="SIGNED_OUT",du="SIGNED_IN",Er="TEAM",At="INDIVIDUAL",zr="GROUP",ft="PAIR",Ft="TEAM",lu={TEAM_PARTICIPANT:Er,INDIVIDUAL:At,GROUP:zr,TEAM:Ft,PAIR:ft},Db={INDIVIDUAL:At,GROUP:zr,PAIR:ft,TEAM:Ft,SIGN_IN_STATUS:cc,SIGNED_OUT:BU,SIGNED_IN:du};function fu({participantsProfile:t,participants:e=[],deepCopy:r}){let n=new Map,o=r!==!1?J(e,t?.convertExtensions,!0):e,i=o.filter(c=>c.participantType===Ft),s=o.filter(c=>c.participantType===zr),a=o.filter(c=>c.participantType===ft);return o.forEach(c=>{if(c.participantType===At){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 HU(t){return t&&typeof String.fromCodePoint<"u"?t.toUpperCase().replace(/./g,e=>String.fromCodePoint(e.charCodeAt(0)+127397)):t}function Nb(t){let e=Object.assign({},...ri.filter(r=>r.ioc).map(r=>({[r.ioc]:r.iso})));return HU(e[t])}var ri=[{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 Jh({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=ri.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 Mb({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?Hi({template:e,source:s}):s)}}}}function yo(t){let{tournamentRecord:e,participantId:r}=t,n=t.tournamentRecords||e&&{[e.tournamentId]:e}||{};for(let o of Object.values(n)){let i=o.participants?.find(s=>s.participantId===r);if(i)return{participant:i,tournamentId:o.tournamentId}}return{error:re}}function Zh(t){let{tournamentRecord:e,participantId:r}=t;if(r){let o=yo({tournamentRecord:e,participantId:r});return o.participant??o}let n=t.element||t.drawDefinition||t.event||t.tournamentRecord;return n||{error:st}}function en(t){let{returnPreviousValues:e,itemSubTypes:r,itemType:n}=t,o=Zh(t);if(o.error)return o;if(r&&!Array.isArray(r))return{error:V,context:{itemSubTypes:r}};if(!Array.isArray(o.timeItems))return{error:sf};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 tS({returnPreviousValues:t,drawDefinition:e,itemSubTypes:r,itemType:n}){if(!e)return{error:sn};if(!e.timeItems)return{info:ve};let{timeItem:o,previousItems:i,info:s}=en({element:e,returnPreviousValues:t,itemSubTypes:r,itemType:n});return o&&{timeItem:o,previousItems:i}||{info:s}}function gu({returnPreviousValues:t,itemSubTypes:e,itemType:r,event:n}){if(!n)return{error:Ot};if(!n.timeItems)return{info:ve};let{timeItem:o,previousItems:i,info:s}=en({returnPreviousValues:t,element:n,itemSubTypes:e,itemType:r});return o&&{timeItem:o,previousItems:i}||{info:s}}function td({returnPreviousValues:t,tournamentRecord:e,itemSubTypes:r,itemType:n}){if(!e)return{error:$};if(!e.timeItems)return{info:ve};let{timeItem:o,previousItems:i,info:s}=en({element:e,returnPreviousValues:t,itemSubTypes:r,itemType:n});return o&&{timeItem:o,previousItems:i}||{info:s}}function eS({returnPreviousValues:t,tournamentRecord:e,participantId:r,itemSubTypes:n,itemType:o}){if(!e)return{error:$};if(!r)return{error:ie};let i=yo({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}=en({element:i.participant,returnPreviousValues:t,itemSubTypes:n,itemType:o});return a&&{timeItem:a,previousItems:c}||{info:u}}var ok={[zr]:"groupParticipantIds",[ft]:"pairParticipantIds",[Ft]:"teamParticipantIds"},ik={[zr]:"groups",[Ft]:"teams"};function rS({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&&ck({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=ak({individualParticipantIds:g,participantCopy:l,participantMap:p,participantType:I,participantId:f});h.missingParticipantIds.length&&u.push(...h.missingParticipantIds)}if(n&&(p[f].participant.signedIn=sk(l)),o){let{ratings:h,rankings:S,seedings:T}=ga({participant:l});p[f].participant.seedings=T,p[f].participant.rankings=S,p[f].participant.ratings=h}(c||a)&&Jh({participant:p[f].participant,withISO2:a,withIOC:c})}if(t){let d=ht(t)?t:void 0;Mb({participantMap:p,template:d})}let m;return i&&(m=fu({participants:Object.values(p).map(({participant:d})=>d),participantsProfile:{convertExtensions:e},deepCopy:!1}).groupInfo),{missingParticipantIds:u,participantMap:p,groupInfo:m}}function sk(t){let{timeItem:e}=en({itemType:cc,element:t});return e?.itemValue===du}function ak({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[ok[n]].push(o),[Ft,zr].includes(n)){let{participantRoleResponsibilities:c,participantOtherName:u,participantName:p,participantId:m,teamId:d}=e,l=ik[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 ck({participantMap:t,participantId:e}){if(t[e])return;let r={walkoverWins:0,defaultWins:0,walkovers:0,defaults:0,losses:0,wins:0};t[e]={structureParticipation:{},potentialMatchUps:{},scheduleConflicts:{},scheduleItems:[],participant:{groupParticipantIds:[],pairParticipantIds:[],teamParticipantIds:[],seedings:{},rankings:{},ratings:{},groups:[],teams:[]},statistics:{},opponents:{},pairIdMap:{},matchUps:{},events:{},draws:{},counters:{[kt]:{...r},[xt]:{...r},[Ft]:{...r},...r}}}function Wo({participantsProfile:t,useParticipantMap:e,tournamentRecord:r,contextProfile:n,inContext:o}){if(e)return rS({...t,...n,tournamentRecord:r});let i=J(r.participants,!1,!0)||[];(t?.withIOC||t?.withISO2)&&i.forEach(a=>Jh({participant:a,...t}));let s;if((o||t?.withGroupings)&&i?.length&&({participantsWithGroupings:i,groupInfo:s}=fu({participantsProfile:t,deepCopy:!1,participants:i})),t?.withScaleValues&&i?.length)for(let a of i){let{ratings:c,rankings:u}=ga({participant:a});a.rankings=u,a.ratings=c}return{participants:i,groupInfo:s}}function Tt({onlySpecifiedPolicyTypes:t=!1,policyTypes:e=[],tournamentRecord:r,drawDefinition:n,structure:o,event:i}){if(!Array.isArray(e))return{error:VI};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===iu)?.value;if(p)for(let m of Object.keys(p))(t?e.includes(m):!e.length||e.includes(m))&&(s[m]=J(p[m],!1,!0))}}function _o({policyTypes:t=[],tournamentRecord:e,drawDefinition:r,structure:n,event:o}){if(!Array.isArray(t))return{error:VI};let{appliedPolicies:i}=Tt({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:Gc.message}}var nS="WALKOVER",WU="RETIRED",ed="COMPETITIVE",uc="ROUTINE",pc="DECISIVE",rd="winRatio";var uk={[Ti]:{policyName:"Competitive Bands Default",profileBands:{[pc]:20,[uc]:50}}},nd=uk;function Qn({policyDefinitions:t,tournamentRecord:e,contextProfile:r,drawDefinition:n,event:o}){let i={policies:{}};if(!r)return i;let s=_o({tournamentRecord:e,drawDefinition:n,event:o}).policyDefinitions;if(r.withCompetitiveness){let a=t?.[Ti]??s?.[Ti]??nd[Ti];i.policies[Ti]=a}return i}function ni({tournamentRecord:t,drawDefinition:e,policyType:r,structure:n,event:o}){if(!t)return{error:$};let{appliedPolicies:i}=Tt({tournamentRecord:t,drawDefinition:e,structure:n,event:o});return i?.[r]?{policy:i[r]}:{info:Gc?.message}}function Ea({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}=ni({policyType:Mo,tournamentRecord:t,event:n}),s=(t?mt({element:t,name:Ho}).extension:void 0)?.value,c=(n&&mt({name:Ho,element:n}).extension)?.value;return{scheduleTiming:{tournamentScheduling:s,eventScheduling:c,categoryName:e,categoryType:r,policy:o}}}function Xf({drawDefinition:t,attributes:e}){let{extension:r}=mt({element:t,name:$m}),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:$m,value:n},hp({drawDefinition:t,extension:r}),{entryProfile:n}}function Iu({drawDefinition:t}){let{extension:e}=mt({element:t,name:$m});return{entryProfile:e?.value||{}}}var rn="ALTERNATE",Jf="CONFIRMED",kr="DIRECT_ACCEPTANCE",od="FEED_IN",Zf="JUNIOR_EXEMPT",us="LUCKY_LOSER",tg="ORGANISER_ACCEPTANCE",id="QUALIFIER",pk="REGISTERED",eg="SPECIAL_EXEMPT",Gr="UNGROUPED",Ui="UNPAIRED",hu="WILDCARD",uo="WITHDRAWN",rg=[Jf,kr,Zf,tg,eg],jU=[od,us,id],oi=[Jf,kr,od,Zf,tg,eg,hu],Qr=[Jf,kr,Zf,us,id,tg,eg,hu],YU=[rn,Jf,kr,od,Zf,us,tg,id,pk,eg,Gr,Ui,hu,uo],Rb={ALTERNATE:rn,CONFIRMED:Jf,DIRECT_ACCEPTANCE:kr,DIRECT_ENTRY_STATUSES:oi,DRAW_SPECIFIC_STATUSES:jU,EQUIVALENT_ACCEPTANCE_STATUSES:rg,FEED_IN:od,JUNIOR_EXEMPT:Zf,LUCKY_LOSER:us,ORGANISER_ACCEPTANCE:tg,QUALIFIER:id,SPECIAL_EXEMPT:eg,STRUCTURE_SELECTED_STATUSES:Qr,UNGROUPED:Gr,UNPAIRED:Ui,VALID_ENTRY_STATUSES:YU,WILDCARD:hu,WITHDRAWN:uo};function ng({stage:t,drawDefinition:e}){let{entryProfile:r}=Iu({drawDefinition:e}),n=Object.keys(r).includes(t);if(!n&&zc.includes(t)){let o=[{[t]:{drawSize:void 0,alternates:!0}}];return Xf({drawDefinition:e,attributes:o}),!0}return n}function Cb({stage:t,drawDefinition:e}){let{entryProfile:r}=Iu({drawDefinition:e});return r[t]?.alternates||0}function bb({stage:t,drawDefinition:e}){let{entryProfile:r}=Iu({drawDefinition:e});return r[t]?.wildcardsCount||0}function oS({stage:t,drawDefinition:e,entryStatus:r}){return e.entries.reduce((n,o)=>o.entryStage===t&&o.entryStatus===r?n+1:n,0)}function Pi({provisionalPositioning:t,placementGroup:e,drawDefinition:r,stageSequence:n,entryStatuses:o,structureId:i,roundTarget:s,stages:a,stage:c}){let u=r.entries?.reduce((p,m)=>{let d=mt({name:Mn,element:m})?.extension?.value,l=c&&m.entryStage===c||a?.length&&m.entryStage&&a.includes(m.entryStage),f=!o||m.entryStatus&&o.includes(m.entryStatus),g=m.entryStageSequence??1;return l&&(!n||g===n)&&f&&(!s||!d||s===d)?p.concat(m):p},[])??[];if(i&&c===fe){let{playoffEntries:p,error:m}=mk({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 mk({provisionalPositioning:t,drawDefinition:e,structureId:r}){let n=[],o=(e.links??[]).find(i=>i.linkType===xn&&i.target.structureId===r);if(o){let{finishingPositions:i,structureId:s}=o.source,{structure:a}=at({drawDefinition:e,structureId:s});a?.structureType===Ve&&(a.structures??[]).forEach(u=>{let p=u.positionAssignments??[],{structureId:m}=u,d=m,l=Object.assign({},...p.map(h=>{let{participantId:S}=h,T=mt({element:h,name:bo}).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:E}=S,P=T||t&&y,A=[...i??[]].sort(le).indexOf(P)+1;n.push({entryStage:fe,entryStatus:od,placementGroup:A,groupingValue:d,participantId:h,GEMscore:E})})})}return{playoffEntries:n}}function vb({stage:t,drawDefinition:e}){return oi.reduce((r,n)=>(oS({drawDefinition:e,entryStatus:n,stage:t})||0)+r,0)}function nn({provisionalPositioning:t,returnAllProxies:e,drawDefinition:r,structureId:n,structure:o}){let i,s=[];o||({structure:o,error:i}=at({drawDefinition:r,structureId:n}));let a=Ct({structure:o}).positionAssignments;if(i||!o)return{seedAssignments:[],error:wt};n||(n=o.structureId);let{stage:c,stageSequence:u}=o,m=c===fe&&r&&Pi({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=HA;let f=o.seedLimit??o?.positionAssignments?.length;return{seedAssignments:s,stageSequence:u,seedLimit:f,stage:c,error:i}}function ii(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 Ep({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:Ep({item:r,drawDefinition:t,structure:e,event:n})||Ep({item:e,drawDefinition:t,structure:e,event:n})||ii(t)||ii(n)}}function Ob({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 si({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 iS({groupedOrder:t,roundPositionsCount:e}){if(!t||t?.length<=e)return t;let n=Ee(t,t.length/e).map(i=>i.reduce((s,a)=>s+a)),o=n.slice().sort(le);return n.map(i=>o.indexOf(i)+1)}function og(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(og):!1}function Ke({matchUps:t=[],interpolate:e}){if(!Vr(t))return{roundMatchUps:[],error:V};let r=t.reduce((d,l)=>{let f=typeof l.roundNumber=="string"?dt(l.roundNumber):l.roundNumber;return!l.roundNumber||d.includes(f)?d:d.concat(f)},[]).sort(le).map(d=>{let l=t.filter(h=>h.roundNumber===d),g=l.find(({matchUpType:h})=>h===Wt)?l.filter(({matchUpType:h})=>h===Wt):l,I=h=>h.sort((S,T)=>le(S.roundPosition,T.roundPosition));return{[d]:I(g)}}),n=t.reduce((d,l)=>{let f=typeof l.roundNumber=="string"?dt(l.roundNumber):l.roundNumber;return d[f]||(d[f]=nt({abbreviatedRoundName:l.abbreviatedRoundName,finishingRound:l.finishingRound,roundName:l.roundName})),d},{}),o=Object.assign({},...r);if(e){let d=Math.max(...Object.keys(o).map(f=>dt(f)).filter(f=>!isNaN(f))),l=o[d]?.length;if(l>1&&_n(l)){let f=d+1,g=f+l/2;tt(f,g).forEach((h,S)=>{o[h]=tt(0,l/(2+S*2)).map(()=>({}))})}}let i=0,s=Object.assign({},...Object.keys(o).map(d=>{let l=o[d]?.length,f=o[d]?.filter(I=>!se.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=>dt(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(le),I=Ee(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=Ee(I,h),T=l.map(y=>{let{roundPosition:E}=y,P=[...y.drawPositions||[],void 0,void 0].slice(0,2);if(!E)return P;let A=P?.filter(Boolean)||[];if(!A?.length)return[void 0,void 0];if(d<3&&A?.length===2)return P?.slice().sort(le);let U=jt(I,A).length!==A?.length;if(A?.length&&U)return A?.length===1?[A[0],void 0]:P?.slice().sort(le);let N=(E-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})=>!_n(d));return{hasNoRoundPositions:t.some(d=>!d.roundPosition),roundsNotPowerOf2:p,maxMatchUpsCount:i,roundMatchUps:o,roundNumbers:u,roundProfile:s,...C}}function sd(t){if(!Array.isArray(t))return"";let e=t.filter(Zt);return e.length?pt([Math.min(...e),Math.max(...e)]).join("-"):""}function _b({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:xi,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=si({structureId:m,matchUpsMap:r}),f=Ke({matchUps:d}).roundProfile;return{[m]:f}})),c=si({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,E=S[l]?.matchUpsCount;if(!E)return;let P=E?T.length/E:0,A=T.length/P,U=T.slice(),N=iS({roundPositionsCount:A,groupedOrder:g}),D=N?.length||1;if(D<=A){let v=T.length/D,O=Ee(U,v);f===fi&&O.forEach(x=>x.reverse()),U=N?.length&&N?.map(x=>O[x-1]).flat()||O.flat()}let M=Ee(U,P);if(I){let v=tt(0,I.interleave).map(()=>{}),O=tt(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]=sd(v))})}),{sourceDrawPositionRanges:p}}function sS({drawDefinition:t}){if(typeof t!="object")return{error:ma};let e={},{structures:r=[],links:n=[]}=t||{},o=r.reduce((s,a)=>{let{stage:c}=a;return s[c]?s[c].push(a):s[c]=[a],s},{});for(let s of Object.keys(o)){let a=o[s].find(({stageSequence:p})=>p===1);if(!a)continue;let{structureId:c}=a;i({aggregator:{},targetRound:0,exitProfiles:e,exitProfile:"0",structureId:c,stage:s})}return{exitProfiles:e};function i({exitProfiles:s,exitProfile:a,structureId:c,targetRound:u,aggregator:p,stage:m}){s[c]||(s[c]=[]),a==="0"&&[qe,fe].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 xb({drawDefinition:t,roundProfile:e,structureId:r,matchUpsMap:n}){if(!t)return{error:Z};if(!r)return{error:Ur};if(!e){let c=si({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=Ee(p,p.length/u),d=m.map(sd),l=m.map(S=>S.map(T=>T-i)).map(sd),f=s.map(S=>{if(S>c)return;let T=e?.[S]?.drawPositions??[];return Ee(T,T.length/u)}).filter(Boolean),g=tt(0,u).map(S=>f.map(T=>T[S]).flat().filter(Boolean).sort(le)).map(S=>pt(S)),I=g.map(S=>SC(S).map(sd).join(", ")),h=Object.assign({},...tt(0,u).map(S=>({[S+1]:{firstRoundDrawPositionsRange:d[S],firstRoundOffsetDrawPositionsRange:l[S],possibleDrawPositions:g[S],drawPositionsRange:I[S]}})));return{[c]:h}}))}}function ad({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!==Vi)&&!r?.structures&&t&&o}function pr({structure:t}){if(!t)return!1;let e=t.matchUps||t.roundMatchUps&&Object.values(t.roundMatchUps).flat(),r=!!e?.find(o=>o?.roundPosition),n=!!e?.find(o=>o?.drawPositions?.length);return!t?.structures&&t?.stage!==$e&&(!e.length||!r&&!n)}var ig={[Ia]:{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:{[rt]:"",[fe]:"P",[ct]:"Q",[qe]:"C"}}},wb=ig;function Lb({roundNamingPolicy:t,drawDefinition:e,structure:r,matchUps:n}){let{roundProfile:o,roundMatchUps:i}=Ke({matchUps:n}),{structureAbbreviation:s,stage:a}=r,c=pr({structure:r}),u=ad({structure:r}),p=r.structures,m={},d=ig[Ia],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,P=(t?.namingConventions||d.namingConventions).round,A=a&&a!==rt?a[0]:"",U=t?.stageConstants||d.stageConstants,N=a&&U?.[a]||A,D=`${I}${N}${g}`,M=o?Object.keys(o):[],R=l&&U?.[ct]?`${U?.[ct]}-`:"";if(p||c||u)Object.assign(m,...M.map(b=>{let v=`${R}${P} ${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,w=b?.[o?.[v].finishingRound]||b&&`${y}${F}`||h[O]||`${y}${F}`,L=x?`-${T}`:"",G=`${w}${L}`,k=[D,s,G].filter(Boolean).join("-"),W=`${S[O]||`${y}${F}`}${L}`,q=[D,s,W].filter(Boolean).join("-");return{[v]:{abbreviatedRoundName:q,roundName:k}}}))}return{roundNamingProfile:m,roundProfile:o,roundMatchUps:i}}var dk=(t,e)=>(t||0)+(e||0);function aS(t,e){let r=Array.isArray(t)?t[0]:t;return isNaN(r)&&nS||r<=e[pc]&&pc||r<=e[uc]&&uc||ed}function cS({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(dk)&&(r[n[0]>n[1]?0:1]+=1),{sets:e,games:r,score:t}}function lk(t){let e=Math.min(...t.games),r=Math.max(...t.games);return Math.round(e/r*100)}function uS(t){return t.map(lk).sort().map(e=>parseFloat(e.toFixed(2)))}function Su({tournamentRecord:t,profileBands:e,matchUp:r}){if(!r)return{error:Tr};let{score:n,winningSide:o}=r;if(!o)return{error:V};let i=!e&&t&&ni({policyType:Ti,tournamentRecord:t}).policy,s=e||i?.profileBands||nd[Ti].profileBands,a=cS({score:n}),c=uS([a]),u=aS(c,s),p=Array.isArray(c)?c[0]:c;return{...C,competitiveness:u,pctSpread:p}}function pS({matchUp:t}){if(!t)return{error:Tr};if(t&&!t.sides)return{error:lr};if(t&&!t.hasContext)return{error:Bc};let e=(t.sides??[])?.map(a=>a?.participantId).filter(Boolean),r=t.sides?.filter(a=>a.participant?.participantType===At).map(a=>a.participantId).filter(Boolean)??[],o=((t.sides??[])?.map(a=>a.participant?.individualParticipants).filter(Boolean)??[]).map(a=>(a??[]).map(c=>c?.participantId).filter(Boolean)),i=[...r,...o.flat()].filter(Boolean)??[],s=pt(i.concat(e)).filter(Boolean)??[];return{nestedIndividualParticipantIds:o,allRelevantParticipantIds:s,individualParticipantIds:i,sideParticipantIds:e,...C}}var cd="CHECK_IN",ud="CHECK_OUT",fk="SCHEDULE",ji="SCHEDULE.ASSIGNMENT.VENUE",po="SCHEDULE.ALLOCATION.COURTS",jo="SCHEDULE.ASSIGNMENT.COURT",Up="SCHEDULE.COURT.ORDER",Yi="SCHEDULE.DATE",gk="COMPLETED.DATE",pd="HOME_PARTICIPANT_ID",sg="SCHEDULE.ASSIGN.OFFICIAL",qi="SCHEDULE.TIME.SCHEDULED",xo="SCHEDULE.TIME.START",$i="SCHEDULE.TIME.STOP",Di="SCHEDULE.TIME.RESUME",Ni="SCHEDULE.TIME.END",Pp="SCHEDULE.TIME.MODIFIERS",Fb="TO_BE_ANNOUNCED",kb="NEXT_AVAILABLE",Gb="FOLLOWED_BY",Vb="AFTER_REST",Bb="RAIN_DELAY",Ik="NOT_BEFORE",mS=[Fb,kb,Gb,Vb,Bb],hk="ELIGIBILITY",Sk="REGISTRATION",Tk="SUSPENSION",yk="MEDICAL",Ak="PENALTY",qU="SCALE",$U="RATING",KU="RANKING",ag="SEEDING",wo="PUBLISH",Rr="PUBLIC",Lo="STATUS",Ek="MODIFICATION",Uk="RETRIEVAL",Pk="other",Hb={MUTUALLY_EXCLUSIVE_TIME_MODIFIERS:mS,AFTER_REST:Vb,ALLOCATE_COURTS:po,ASSIGN_COURT:jo,ASSIGN_OFFICIAL:sg,ASSIGN_VENUE:ji,CHECK_IN:cd,CHECK_OUT:ud,COMPLETED_DATE:gk,COURT_ORDER:Up,ELIGIBILITY:hk,END_TIME:Ni,FOLLOWED_BY:Gb,MEDICAL:yk,MODIFICATION:Ek,NEXT_AVAILABLE:kb,NOT_BEFORE:Ik,OTHER:Pk,PENALTY:Ak,PUBLIC:Rr,PUBLISH:wo,RANKING:KU,RATING:$U,RAIN_DELAY:Bb,REGISTRATION:Sk,RESUME_TIME:Di,RETRIEVAL:Uk,SCALE:qU,SCHEDULE:fk,SCHEDULED_DATE:Yi,SCHEDULED_TIME:qi,SEEDING:ag,START_TIME:xo,STATUS:Lo,STOP_TIME:$i,SUSPENSION:Tk,TIME_MODIFIERS:Pp,TO_BE_ANNOUNCED:Fb};function ps({matchUp:t}){if(!t)return{error:Tr};if(!t.hasContext)return{error:Bc};if(!t.sides||t.sides.filter(Boolean).length!==2)return{error:lr};let{nestedIndividualParticipantIds:e,allRelevantParticipantIds:r,sideParticipantIds:n}=pS({matchUp:t}),i=(t.timeItems??[]).filter(u=>u?.itemType&&[cd,ud].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===cd);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 de=t=>e=>{let r=ht(e)&&e?.matchUpType||Vt(e)&&e;return r&&MI[t].includes(r)};function Dp(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 Np(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 dS({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 Wb({tournamentScheduling:t,eventScheduling:e,averageMinutes:r,defaultTiming:n,matchUpFormat:o,categoryName:i,categoryType:s,policy:a}){let c=e?.matchUpRecoveryTimes&&Np({...e,averageMinutes:r,matchUpFormat:o}),u=t?.matchUpRecoveryTimes&&Np({...t,averageMinutes:r,matchUpFormat:o}),p=a?.matchUpRecoveryTimes&&Np({...a,averageMinutes:r,matchUpFormat:o}),m=[c,u,p,a?.defaultTimes?.recoveryTimes,n?.recoveryTimes];return dS({categoryName:i,categoryType:s,timesBlockArray:m})}function jb({matchUpFormat:t,categoryName:e,categoryType:r,defaultTiming:n,tournamentScheduling:o,eventScheduling:i,policy:s}){let a=i?.matchUpAverageTimes&&Dp({...i,matchUpFormat:t}),c=o?.matchUpAverageTimes&&Dp({...o,matchUpFormat:t}),u=s?.matchUpAverageTimes&&Dp({...s,matchUpFormat:t}),p=[a,c,u,s?.defaultTimes?.averageTimes,n?.averageTimes];return dS({categoryName:e,categoryType:r,timesBlockArray:p})}var zU="DOUBLES_SINGLES",QU="SINGLES_DOUBLES",mo="total",lS="participantConflict",Ua="matchUpConflict",XU="ISSUE_IDS",mc="CONFLICT",dc="WARNING",fS="ERROR",gS="ISSUE",cg="STATE",Yb={SINGLES_DOUBLES:QU,DOUBLES_SINGLES:zU,TOTAL:mo,CONFLICT_MATCHUP_ORDER:Ua,CONFLICT_PARTICIPANTS:lS,SCHEDULE_ISSUE_IDS:XU,SCHEDULE_CONFLICT:mc,SCHEDULE_WARNING:dc,SCHEDULE_ERROR:fS,SCHEDULE_ISSUE:gS,SCHEDULE_STATE:cg};function Tu({defaultAverageMinutes:t=90,defaultRecoveryMinutes:e=0,tournamentRecord:r,matchUpFormat:n,categoryName:o,categoryType:i,eventType:s,event:a}){if(!r)return{error:$};s=s??a?.eventType??ks;let c={averageTimes:[{minutes:{default:t}}],recoveryTimes:[{minutes:{default:e}}]},{scheduleTiming:u}=Ea({tournamentRecord:r,categoryName:o,categoryType:i,event:a}),p={...u,matchUpFormat:n,categoryType:i,defaultTiming:c};return Mp({eventType:s,timingDetails:p})}function Mp({timingDetails:t,eventType:e}){let r=jb(t),n=Object.keys(r?.minutes||{}),o=r?.minutes&&(n?.includes(e)&&r.minutes[e]||r.minutes.default),i=Wb({...t,averageMinutes:o}),s=Object.keys(i?.minutes||{}),a=i?.minutes&&(s?.includes(e)&&i.minutes[e]||i.minutes.default),c=de(ks)(e)?QU:zU,u=i?.minutes&&(s?.includes(c)&&i.minutes[c]||a);return{averageMinutes:o,recoveryMinutes:a,typeChangeRecoveryMinutes:u}}function JU(t){return t.createdAt?new Date(t.createdAt).getTime():0}function Yo({timeItems:t,itemType:e}){let r=t.filter(o=>o&&o.itemType===e).sort((o,i)=>JU(o)-JU(i)).pop(),n=r&&JU(r);return{itemValue:r?.itemValue,timeStamp:n}}function IS({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Yo({timeItems:r?.timeItems||[],itemType:qi});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{scheduledTime:n}:e}function Ws({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Yo({timeItems:r?.timeItems||[],itemType:Yi});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{scheduledDate:n}:e}function Rp(t){if(JI.test(t)){let e=Af();return new Date(`${e}T${t}`)}else return new Date(t)}function qb({matchUp:t}){if(!t)return{error:Tr};if(!t.timeItems)return{error:sf};let e=t.timeItems.filter(n=>[xo,$i,Di,Ni].includes(n?.itemType)).sort((n,o)=>Rp(n.itemValue).getTime()-Rp(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 xo:i=0;break;case Ni:if(n.lastValue&&[xo,Di].includes(n.lastType)){let u=Rp(o.itemValue).getTime()-Rp(n.lastValue).getTime();i=n.milliseconds+u}else i=n.milliseconds;break;case $i:if([xo,"SCHECULE.TIME.RESUME"].includes(n.lastType)){let u=Rp(o.itemValue).getTime()-Rp(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([xo,Di].includes(r.lastType)){let n=new Date().getTime()-Rp(r.lastValue).getTime();r.milliseconds+=n}return{milliseconds:r.milliseconds,time:Dk(r.milliseconds),relevantTimeItems:e}}function Dk(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 $b({matchUp:t}){let e=t?.timeItems||[],r=i=>i.createdAt?new Date(i.createdAt).getTime():0;return{startTime:e.reduce((i,s)=>{let a=s.itemType===xo&&s;return a&&(!i||r(a)<r(i))?a:i},void 0)?.itemValue}}function lc(t){let{disableNotice:e,venue:r,context:n}=t;if(typeof r!="object")return{error:V};let o=Mr(t);r.venueId||(r.venueId=Mt());let i;for(let s of Object.values(o)){let a=Nk({disableNotice:!0,tournamentRecord:s,context:n,venue:r});if(a?.error)return a;i=a.venue}return e||lt({topic:$h,payload:{venue:r}}),nt({...C,venue:i})}function Nk({tournamentRecord:t,disableNotice:e,context:r,venue:n}){return t?n?(t.venues||(t.venues=[]),n.venueId||(n.venueId=Mt()),t.venues.reduce((i,s)=>i||s.venueId===n.venueId,void 0)?{error:UE}:(r&&Ut({element:n,extension:{value:r,name:UU}}),t.venues.push(n),e||lt({payload:{venue:n,tournamentId:t.tournamentId},topic:$h}),{...C,venue:J(n)})):{error:st,info:"missing venue"}:{error:$}}function qo({tournamentRecords:t,tournamentRecord:e,venueId:r}){if(!e)return{error:$};if(!r)return{error:ti};let o=(e.venues??[]).reduce((i,s)=>s.venueId===r?s:i,void 0);if(!o&&t){let s=(au({tournamentRecords:t}).linkedTournamentIds??[])[e.tournamentId];for(let a of s){let c=t[a],u=qo({tournamentRecord:c,venueId:r});if(u.success&&u.venue)return lc({tournamentRecord:e,venue:u.venue}),{...C,venue:o}}}return o?{...C,venue:o}:{error:ki}}function hS({convertExtensions:t,...e}){let{tournamentRecords:r,tournamentRecord:n,venueId:o}=e,i=qo({tournamentRecords:r,tournamentRecord:n,venueId:o});return J(i,t,!0)}function ms({tournamentRecords:t,tournamentRecord:e,courtId:r}){if(!e)return{error:$};if(!r)return{error:wi};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=(au({tournamentRecords:t}).linkedTournamentIds??[])[e.tournamentId];for(let c of a){let u=t[c],p=ms({tournamentRecord:u,courtId:r});if(p.success)return p.venue&&lc({tournamentRecord:e,venue:p.venue}),{...C,court:o,venue:i}}}return _({result:{error:_s},stack:n})}function SS(t){return J(ms(t),!1,!0)}function md({tournamentRecord:t,internalUse:e,courtId:r}){if(!t)return{error:$};if(!r)return{error:wi};let n=ms({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 fc(t){let e=et(t,[{[ne]:!0},{venueId:!0,[fn]:ti}]);if(e.error)return e;let{tournamentRecord:r,venueId:n}=t,o=qo({tournamentRecord:r,venueId:n});if(o.error)return o;let s=(o.venue?.courts??[]).map(u=>(({courtInfo:p})=>({...p}))(md({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 Kb({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===Ni&&s;return a&&(!i||r(a)>r(i))?a:i},void 0)?.itemValue}}function Ht({event:t,eventId:e}){if(!t)return{error:Ot};let n=mt({name:cn,element:t})?.extension,o=e?J(n?.value,!1,!0):n?.value;return e&&t.drawDefinitions?.forEach(i=>{o?.flights?.forEach(s=>{s.drawId===i.drawId&&Object.assign(s,{drawDefinition:i})})}),{flightProfile:o}}function 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:Cr},context:{drawId:n,eventId:r},stack:o})}}function dd(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:Tr};if(o&&!p.matchUpType&&!t.matchUpType&&(e||i)&&p.drawId){let P=t.drawDefinition||e?.drawDefinitions?.find(U=>U.drawId===p.drawId);!P&&i&&({drawDefinition:P,event:e}=ze({drawId:p.drawId,tournamentRecord:i}));let A=p.structureId&&P?.structures?.find(({structureId:U})=>U===p.structureId);r=t.matchUpType||A?.matchUpType||P?.matchUpType||e?.eventType!==_e&&e?.eventType}let{milliseconds:m,time:d}=qb({matchUp:p}),{startTime:l}=$b({matchUp:p}),{endTime:f}=Kb({matchUp:p}),g,{eventIds:I,drawIds:h}=n??{};if((!I||I.includes(p.eventId))&&(!h||h.includes(p.drawId))){let P=Q=>Q.createdAt?new Date(Q.createdAt).getTime():0,A=new Map,U=p.timeItems?.toSorted((Q,ut)=>P(Q)-P(ut))??[];for(let Q of U)A.set(Q.itemType,Q.itemValue);let N=A.get(pd),D=A.get(po),M=A.get(qi),R=A.get(Pp),b=A.get(Yi),v=A.get(sg),O=A.get(Up),x=A.get(ji),F=A.get(jo),w,L,G,k,H,W=p.matchUpType??r;if(a&&M&&o&&W){let Q={matchUpFormat:p.matchUpFormat??c,...a};({averageMinutes:L=0,recoveryMinutes:G=0,typeChangeRecoveryMinutes:k=0}=Mp({timingDetails:Q,eventType:W})),(L||G)&&(w=f?Yr(Qt(f),G):Yr(M,L+G)),k&&(H=f?Yr(Qt(f),k):Yr(M,L+k))}!b&&M&&(b=Pt(M));let q=_m({scheduledDate:b,scheduledTime:M}),Y={},B=(i&&x&&fc({tournamentRecord:i,venueId:x}))?.venueData||{};x&&(Y[x]=B);let{venueName:K,venueAbbreviation:X,courtsInfo:j}=B,z=(F&&j?.find(Q=>Q.courtId===F))?.courtName;for(let Q of D||[]){if(!i)break;Q.venueId&&!Y[Q.venueid]&&(Y[Q.venueId]=fc({venueId:Q.venueId,tournamentRecord:i})?.venueData);let ut=Y[Q.venueId];Q.venueName=ut?.venueName;let it=ut?.courtsInfo?.find(Et=>Et.courtId===Q.courtId);Q.courtName=it?.courtName}g=nt({typeChangeTimeAfterRecovery:H,timeAfterRecovery:w,scheduledDate:b,scheduledTime:M,isoDateString:q,homeParticipantId:N,venueAbbreviation:X,allocatedCourts:D,timeModifiers:R,venueName:K,venueId:x,courtOrder:O,courtName:z,courtId:F,official:v,typeChangeRecoveryMinutes:k,recoveryMinutes:G,averageMinutes:L,milliseconds:m,startTime:l,endTime:f,time:d})}else g=nt({milliseconds:m,startTime:l,endTime:f,time:d});let{scheduledDate:S}=Ws({matchUp:p}),{scheduledTime:T}=IS({matchUp:p});if(s&&u?.displaySettings?.draws){let P=u.displaySettings.draws,A=(P?.[p.drawId]??P?.default)?.scheduleDetails;if(A){let U=(A.find(N=>S&&N.dates?.includes(S))??A.find(N=>!N.dates?.length))?.attributes;if(U){let N=Object.assign({},...Object.keys(g).map(D=>({[D]:!0})),U);g=Hi({source:g,template:N})}}}let E=p.matchUpStatus&&se.includes(p.matchUpStatus)&&(Pt(f)||Pt(S)||Pt(T))||void 0;return{schedule:g,endDate:E}}function zb({drawPositions:t,roundProfile:e,roundNumber:r}){let n=[void 0,void 0];if(vI(t))return{orderedDrawPositions:n,displayOrder:n};let o=e?.[r],s=o?.pairedDrawPositions?.find(c=>ke(c||[],t.filter(Boolean)))??n,a=o?.feedRound;if(bI(t)){let c=[...t].sort(le);return{orderedDrawPositions:c.length===2?c:s,displayOrder:a?c:s}}if(a){let u=[t.find(p=>!isNaN(dt(p))),void 0];return{orderedDrawPositions:u,displayOrder:u}}return{orderedDrawPositions:s,displayOrder:s}}function Cp({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:$};if(!Array.isArray(r)||r.length>2)return{error:wr};if(!r.length)return _({result:{error:Do},stack:n});t=t??e?.participants??[];let o=t.filter(a=>a.participantType===ft&&jt(r,a.individualParticipantIds).length===r.length&&a.individualParticipantIds.length===r.length),i=o[0];if(!i)return _({result:{error:re},stack:n});let s=J(o.slice(1),!1,!0);return{participant:J(i),duplicatedPairParticipants:s,...C}}function ds({drawDefinition:t,participantId:e}){if(typeof t!="object")return{error:Z};if(typeof e!="string")return{error:ie};let{extension:r}=mt({element:t,name:Co});return{lineUp:(r?.value||{})[e]}}function Qb({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}=Cp({collectionPosition:r,collectionId:s,lineUp:d});if(c===xt){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||ds({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||ds({participantId:d,drawDefinition:i})?.lineUp;return u({attribute:m,lineUp:g,teamParticipant:f})}).filter(Boolean)||{};return{drawPositionCollectionAssignment:Object.assign({},...p)}}function ld(t){let e=et(t,[{[Ln]:!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===At&&kt||s===ft&&xt||s===Ft&&Ft||void 0}return{matchUpType:n}}function Xb({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?Mk({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 Mk({displaySideNumber:t,seedAssignments:e,participantId:r,assignment:n,sideNumber:o}){let i={drawPosition:n.drawPosition,displaySideNumber:t,sideNumber:o};if(r){let s=Rk({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 Rk({seedAssignments:t,participantId:e}){return t?.find(r=>!r.seedProxy&&r.participantId===e)}function ZU({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:E,scoringActive:P,matchUpTieId:A,isRoundRobin:U,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:w,stage:L,stageSequence:G}=M,{drawId:k,drawName:H,drawType:W}=y??{},q=O?.collectionDefinitions,Y=b.collectionId&&q?.find(ae=>ae.collectionId===b.collectionId),B=b.collectionId?Y?.matchUpFormat:b.matchUpFormat??M?.matchUpFormat??y?.matchUpFormat??v?.matchUpFormat,K=b.matchUpType||Y?.matchUpType||M?.matchUpType||y?.matchUpType||!de(_e)(v?.eventType)&&v?.eventType,X=l?Nt:b.matchUpStatus,{schedule:j,endDate:ot}=dd({scheduleVisibilityFilters:t,afterRecoveryTimes:s,tournamentRecord:p,usePublishState:g,scheduleTiming:S,drawDefinition:y,matchUpFormat:B,publishStatus:E,matchUpType:K,matchUp:b,event:v}),z=m??b.drawPositions??[],{collectionPosition:Q,collectionId:ut,roundPosition:it}=b,Et=b.roundNumber??c.roundNumber,_t=ut?Qb({tournamentParticipants:r,positionAssignments:n,collectionPosition:Q,participantMap:I,drawDefinition:y,drawPositions:z,collectionId:ut,sideLineUps:D,matchUpType:K}):void 0,Ae=u?.[Et]?.roundName||c.roundName,$t=u?.[Et]?.abbreviatedRoundName||c.abbreviatedRoundName,Se=N?.[Et]?.feedRound,Or=N?.[Et]?.preFeedRound,pn=N?.[Et]?.roundFactor,Ir=o?.[Et],Xe=it?Ir?.[it]:void 0,te=e?.[Et],Dt=Y?.category?{...R?.category||{},...Y.category}:R?.category??v?.category,ue=b.processCodes?.length&&b.processCodes||Y?.processCodes?.length&&Y?.processCodes||M?.processCodes?.length&&M?.processCodes||y?.processCodes?.length&&y?.processCodes||v?.processCodes?.length&&v?.processCodes||p?.processCodes,pe=T?.withCompetitiveness&&Su({...h,matchUp:b}),Fe=b.finishingPositionRange??c.finishingPositionRange,ee=L!==ct&&It(a)&&a+(Et||0),Je=ae=>nt(ae,void 0,!0),qt={...Je(R),...Je({matchUpFormat:K===_e?void 0:B,tieFormat:K!==_e?void 0:O,gender:Y?.gender??v?.gender,endDate:b.endDate??ot,discipline:v?.discipline,category:Dt,finishingPositionRange:Fe,abbreviatedRoundName:$t,drawPositionsRange:Xe,competitiveProfile:pe,structureName:w,stageSequence:G,drawPositions:z,matchUpStatus:X,processCodes:ue,isRoundRobin:U,matchUpTieId:A,preFeedRound:Or,matchUpType:K,roundFactor:pn,roundOffset:x,structureId:F,roundNumber:Et,roundOfPlay:ee,feedRound:Se,roundName:Ae,drawName:H,drawType:W,schedule:j,drawId:k,stage:L}),...J(Je(b),!0,!0)};if(B&&b.score?.scoreStringSide1){let ae=Ye(B),{bestOf:hr,finalSetFormat:_r,setFormat:Kt}=ae??{};(_r?.tiebreakSet||Kt?.tiebreakSet||Kt?.timed)&&(qt.score.sets=qt.score.sets.sort((De,fr)=>De.setNumber-fr.setNumber).map((De,fr)=>(fr+1===hr?(_r?.tiebreakSet||_r?.timed)&&(De.tiebreakSet=!0):(Kt?.tiebreakSet||Kt?.timed)&&(De.tiebreakSet=!0),De)))}if(Array.isArray(z)){let{orderedDrawPositions:ae,displayOrder:hr}=zb({drawPositions:z,roundProfile:N,roundNumber:Et}),_r=N?.[Et]?.feedRound,Kt=hr[0]!==ae[0],fr=ae.concat(void 0,void 0).slice(0,2).map((Ne,On)=>{let me=On+1,dr=Kt?3-me:me,es=Xb({..._t,positionAssignments:n,displaySideNumber:dr,seedAssignments:f,drawPosition:Ne,isFeedRound:_r,sideNumber:me}),Tn=b.sides?.find(Ku=>Ku.sideNumber===me),mi=it?(it-1)*2+On+1:void 0,ca=mi?te?.[mi]:void 0;return Je({sourceDrawPositionRange:ca,...Tn,...es})});Object.assign(qt,J({sides:fr},!0,!0))}if(r&&qt.sides){let ae=d?.[Bs],hr=Kt=>{let De=I?.[Kt]?.participant;return De&&Hi({template:ae?.participant,source:De})};if(qt.sides.filter(Boolean).forEach(Kt=>{if(Kt.participantId){let De=J(hr(Kt.participantId)||(r?Bo({policyDefinitions:d,participantId:Kt.participantId,tournamentParticipants:r,internalUse:!0,contextProfile:T}):void 0),void 0,!0);if(De){let fr,Ne;if(y?.entries){let On=y.entries.find(dr=>dr.participantId===Kt.participantId),me=v?.entries?.find(dr=>dr.participantId===Kt.participantId);fr=On?.entryStatus||me?.entryStatus,De.entryStatus=fr,On?.entryStage&&(Ne=On.entryStage,De.entryStage=Ne)}i!==!1?Object.assign(Kt,{participant:De}):Object.assign(Kt,{participant:{entryStage:Ne,entryStatus:fr}})}}if(Kt?.participant?.individualParticipantIds?.length&&!Kt.participant.individualParticipants?.length){let De=Kt.participant.individualParticipantIds.map(fr=>hr(fr)||(r?Bo({policyDefinitions:d,tournamentParticipants:r,internalUse:!0,contextProfile:T,participantId:fr}):void 0));i!==!1&&Object.assign(Kt.participant,{individualParticipants:De})}}),!qt.matchUpType){let{matchUpType:Kt}=ld({matchUp:qt});Kt&&Object.assign(qt,{matchUpType:Kt})}if(T?.inferGender&&(!qt.gender||qt.gender===Ar)&&qt.sides?.length===2&&qt.matchUpType!==_e){let Kt=qt.sides.map(De=>{if(de(kt)(qt.matchUpType))return De.participant?.person?.sex;if(De.participant?.individualParticipants?.length===2){let fr=pt(De.participant.individualParticipants.map(Ne=>Ne.person?.sex)).filter(Boolean);if(fr.length===1)return fr[0]}});if(Kt.filter(Boolean).length===2&&pt(Kt).length===1){let De=Kt[0];qt.inferredGender=De}}}if(qt.tieMatchUps){let ae=qt.matchUpStatus===Nt,hr=qt.sides?.map(({participant:_r,drawPosition:Kt,sideNumber:De,lineUp:fr})=>{let Ne=_r?.participantType===_e&&_r;return{teamParticipant:Ne&&nt({participantRoleResponsibilities:Ne.participantRoleResponsibilities,participantOtherName:Ne.participanOthertName,participantName:Ne.participantName,participantId:Ne.participantId,teamId:Ne.teamId}),drawPosition:Kt,sideNumber:De,lineUp:fr}});qt.tieMatchUps=qt.tieMatchUps.map(_r=>{let Kt=qt.matchUpId,fr={finishingPositionRange:qt.finishingPositionRange,abbreviatedRoundName:$t,roundNumber:Et,roundName:Ae};return ZU({tieDrawPositions:z,scheduleVisibilityFilters:t,sourceDrawPositionRanges:e,sideLineUps:hr,drawPositionsRanges:o,initialRoundOfPlay:a,roundNamingProfile:u,additionalContext:fr,appliedPolicies:d,isCollectionBye:ae,usePublishState:g,publishStatus:E,matchUpTieId:Kt,isRoundRobin:U,roundProfile:N,matchUp:_r,event:v,tournamentParticipants:r,positionAssignments:n,tournamentRecord:p,seedAssignments:f,participantMap:I,contextContent:h,scheduleTiming:S,contextProfile:T,drawDefinition:y,scoringActive:P,structure:M,context:R})})}let ar=qt.sides&&qt.sides.filter(ae=>ae?.participantId).length===2,Ze=!qt.winningSide;if(Object.assign(qt,{readyToScore:P&&ar&&Ze,hasContext:!0}),ar){let{allParticipantsCheckedIn:ae,checkedInParticipantIds:hr}=ps({matchUp:qt});Object.assign(qt,{allParticipantsCheckedIn:ae,checkedInParticipantIds:hr})}return Array.isArray(T?.exclude)&&T?.exclude.forEach(ae=>delete qt[ae]),qt}function Jb({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Yo({timeItems:r?.timeItems||[],itemType:po});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{allocatedCourts:J(n,!1,!0)}:e}function Zb({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Yo({timeItems:r?.timeItems||[],itemType:jo});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{courtId:n}:e}function tv({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Yo({timeItems:r?.timeItems||[],itemType:ji});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{venueId:n}:e}function Mi(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:E,tournamentIds:P,matchUpTypes:A,structureIds:U,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):[],w=Array.isArray(v)?v.filter(Boolean):[],L=Array.isArray(h)?h.filter(Boolean):[],G=Array.isArray(p)?p.filter(Boolean):[],k=Array.isArray(f)?f.filter(Boolean):[],H=Array.isArray(d)?d.filter(Boolean):[],W=Array.isArray(c)?c.filter(Boolean):[],q=Array.isArray(l)&&I?l.filter(Boolean):[],Y=Array.isArray(A)&&g?A.filter(Boolean):[],B=Array.isArray(D)?D.filter(Boolean):[],K=Array.isArray(R)?R.filter(Boolean):[],X=Array.isArray(a)&&a.filter(Boolean)||typeof u=="string"&&[u]||[],j=Array.isArray(S)&&S.filter(Boolean)||typeof T=="string"&&T.length&&[T]||[],ot=Array.isArray(P)?P.filter(Boolean):[],z=Array.isArray(M)?M.filter(Boolean):[],Q=Array.isArray(b)?b.filter(Boolean):[],ut=Array.isArray(U)?U.filter(Boolean):[];return e.filter(it=>{if(N&&!de(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)||w.length&&!w.includes(it.stage)||L.length&&!L.includes(it.stageSequence)||G.length&&(!it.collectionId||!G.includes(it.collectionId))||k.length&&(!it.roundName||!k.includes(it.roundName))||H.length&&(!it.roundNumber||!H.includes(it.roundNumber))||W.length&&(!it.roundPosition||!W.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)||Y.length&&(!it.matchUpType||!kc(Y,it.matchUpType))||X.length&&(!it.matchUpFormat||!X.includes(it.matchUpFormat)))return!1;if(j?.length){let{scheduledTime:Et}=IS({matchUp:it}),{scheduledDate:_t}=Ws({matchUp:it}),$t=Pt(Et)||_t;if(!j.find(Se=>qn(Se,$t)))return!1}if(B.length){let{courtId:Et}=Zb({matchUp:it}),{allocatedCourts:_t}=Jb({matchUp:it}),Ae=_t?.map(({courtId:$t})=>$t);if(!B.filter(Boolean).includes(Et)||Ae?.includes(Et))return!1}if(K.length){let{venueId:Et}=tv({matchUp:it});if(!K.filter(Boolean).includes(Et))return!1}if(E){if(ot.length&&!ot.includes(it.tournamentId)||z.length&&!z.includes(it.eventId)||Q.length&&!Q.includes(it.drawId)||ut.length&&!ut.includes(it.structureId))return!1;let Et=it.sides?.map(({participantId:_t})=>_t).filter(Boolean)??[];if(n&&Et.length<n||O.length&&!O.some(Ae=>Et.includes(Ae)))return!1}return!0})}function yt(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:di,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),E=!S?.length||S.includes(c.structureId),P=!s||!T?.length||T.includes(s.drawId);if(!y||!E||!P)return{collectionPositionMatchUps:g,roundMatchUps:I,matchUps:[]};i&&!d&&(d=Qn({tournamentRecord:r,contextProfile:i,drawDefinition:s}));let{appliedPolicies:A}=Tt({drawDefinition:s}),U={...t.tournamentAppliedPolicies,...A,...t.policyDefinitions},N=U?.scoring?.structures,D=c.stage&&N?.stage?.[c.stage],M=c.stageSequence&&D?.stageSequence?.[c.stageSequence],R=U?.scoring?.requireAllPositionsAssigned||D?.requireAllPositionsAssigned||M?.requireAllPositionsAssigned;f||(f=Me({drawDefinition:s,structure:c}));let{positionAssignments:b,allPositionsAssigned:v}=ge({structure:c}),O=!R||v,{seedAssignments:x}=nn({provisionalPositioning:e,drawDefinition:s,structure:c});m=m??x;let{structureId:F}=c;l=l||s&&sS({drawDefinition:s}).exitProfiles;let w=l?.[F],L=w?.length&&(w[0].split("-").map(B=>parseInt(B)).reduce((B,K)=>B+K)||0),G=!!c.structures,k=si({matchUpsMap:f,structureId:F,inContext:u}),H=U?.[Ia],W=Lb({roundNamingPolicy:H,drawDefinition:s,structure:c,matchUps:k}),{roundNamingProfile:q,roundProfile:Y}=W;if(I=W?.roundMatchUps??[],o&&(k=Mi({matchUps:k,...o,filterMatchUpTypes:!1,filterMatchUpIds:!1})),u){let{sourceDrawPositionRanges:B}=_b({drawDefinition:s,matchUpsMap:f,structureId:F}),K=s?xb({drawDefinition:s,roundProfile:Y,matchUpsMap:f,structureId:F}).drawPositionsRanges:void 0,X=t.tournamentParticipants,j=t.participantMap;!X?.length&&!j&&r&&({participants:X=[],participantMap:j}=Wo({participantsProfile:t.participantsProfile,useParticipantMap:t.useParticipantMap,policyDefinitions:t.policyDefinitions,tournamentRecord:r,contextProfile:i,inContext:u})),k=k.map(z=>ZU({scheduleVisibilityFilters:t.scheduleVisibilityFilters,hydrateParticipants:t.hydrateParticipants,afterRecoveryTimes:t.afterRecoveryTimes,usePublishState:t.usePublishState,scheduleTiming:t.scheduleTiming,publishStatus:t.publishStatus,sourceDrawPositionRanges:B,tournamentParticipants:X,positionAssignments:b,drawPositionsRanges:K,initialRoundOfPlay:L,roundNamingProfile:q,tournamentRecord:r,appliedPolicies:U,seedAssignments:m,contextContent:d,participantMap:j,contextProfile:i,drawDefinition:s,scoringActive:O,isRoundRobin:G,roundProfile:Y,structure:c,context:a,matchUp:z,event:p})),(k?.filter(z=>Array.isArray(z.tieMatchUps))).forEach(z=>{let Q=z.tieMatchUps;k=k.concat(...Q)}),n&&(k=Mi({processContext:!0,...n,matchUps:k}))}else(k?.filter(K=>Array.isArray(K.tieMatchUps))).forEach(K=>{let X=K.tieMatchUps;k=k.concat(...X)});return o&&(k=Mi({matchUps:k,...o,filterMatchUpTypes:!1,filterMatchUpIds:!1})),(o?.matchUpTypes||o?.matchUpIds)&&(k=Mi({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}=Ob({matchUps:k})),{collectionPositionMatchUps:g,roundMatchUps:I,isRoundRobin:G,roundProfile:Y,matchUpsMap:f,matchUps:k}}function ls({matchUp:t}){return t?se.includes(t?.matchUpStatus)||t?.winningSide:!1}function yu({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:E,context:P,event:A}){!E&&T&&({structure:E}=at({drawDefinition:I,structureId:T}));let U=yt({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:E,inContext:y,context:P,event:A}),N=[],D=[],M=[],R=[],b=[];if(U.error)return U;let{matchUps:v}=U,{assignedPositions:O}=ge({structure:E}),x=O?.filter(w=>w.participantId).map(w=>w.drawPosition),F;return v.filter(w=>{let L=u?.matchUpTypes?.length===1&&u.matchUpTypes[0]===Wt;return!(w.matchUpType!==Wt&&L)}).forEach(w=>{if(w.matchUpStatus===vr){N.push(w);return}w.matchUpType===Wt&&(F=!0);let L=!!w.collectionId,G=L&&w.sides?.every(K=>K.participantId),k=!L&&w.drawPositions?.filter(Boolean).length===2,H=!L&&w.drawPositions?.every(K=>x?.includes(K)),W=O?.filter(K=>K.bye).map(K=>K.drawPosition),q=!L&&w.drawPositions?.find(K=>W?.includes(K)),B=jh.includes(w.matchUpStatus)&&(G||k&&(!t||H));return q?b.push(w):ls({matchUp:w})?D.push(w):B?M.push(w):R.push(w)}),{includesTeamMatchUps:F,abandonedMatchUps:N,completedMatchUps:D,upcomingMatchUps:M,pendingMatchUps:R,byeMatchUps:b,structure:E}}function ev({drawDefinition:t,roundNumber:e,structureId:r}){if(!t)return{error:Z};if(!r)return{error:Ur};let{links:n}=js({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 TS({finishingPositions:t,linkCondition:e,linkType:r,source:n}){let o=n.find(i=>{let s=!i.source?.finishingPositions||!t||ke(t,i.source?.finishingPositions);return e===i.linkCondition&&s&&i.linkType===r});return[Kn,oo].includes(o?.linkType)&&!o?.source?.roundNumber?_({result:{error:V},stack:"getTargetLink",context:o}):o}function js({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 rv({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 yS({sourceRoundMatchUpCount:t,inContextDrawMatchUps:e,sourceRoundPosition:r,drawDefinition:n,targetLink:o}){if(!o)return{error:Bl};let{target:{structureId:i,feedProfile:s,groupedOrder:a,roundNumber:c,positionInterleave:u}}=o,{structure:p}=at({drawDefinition:n,structureId:i}),{positionAssignments:m}=Ct({structure:p}),l=(e?.filter(D=>D.structureId===p?.structureId)).filter(D=>D.roundNumber===c&&!D.matchUpTieId),f=l.length,g=tt(1,f+1),I=f/t,h=Math.ceil(I*r),S=1-r%2;if(u?.interleave&&I!==.5){let 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],E=iS({roundPositionsCount:g.length,groupedOrder:a}),P=E?.length||1;if(P<=g.length){let D=f/P,M=Ee(g,D);s===fi&&M.forEach(R=>R.reverse()),T=E?.length&&E?.map(R=>M[R-1]).flat()||T}s===En?y=T[h-1]:s===fi?((!E?.length||P>g.length)&&(h=l.length+1-h),y=T[h-1]):s===mp&&Pr()&&console.log(np,{feedProfile:s});let A=y&&l.reduce((D,M)=>M.roundPosition===y?M:D,void 0),U;A?.feedRound?(S=0,U=Math.min(...(A.drawPositions||[]).filter(Boolean))):U=A?.drawPositions?.length===2&&A?.drawPositions[S];let N=m?.find(({drawPosition:D})=>D===U);if(N){let{extension:D}=mt({element:N,name:Ym});if(D?.value)return{disabledDrawPosition:U}}return{matchUp:A,targetDrawPosition:U,matchUpDrawPositionIndex:S}}function mr({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===Bi?Ck({inContextDrawMatchUps:t,useTargetMatchUpIds:e,drawDefinition:n,structure:s,matchUp:i}):bk({matchUp:i})}function Ck({inContextDrawMatchUps:t,useTargetMatchUpIds:e,drawDefinition:r,structure:n,matchUp:o}){let{winnerMatchUpId:i,loserMatchUpId:s}=o,{links:a}=ev({roundNumber:o.roundNumber,structureId:n.structureId,drawDefinition:r}),c=a?.source,u=TS({source:c,linkType:Kn}),p=TS({linkCondition:wn,linkType:oo,source:c}),m=TS({source:c,linkType:oo}),d=p&&m;m||(m=p);let l=u?.target?.feedProfile,f=m?.target?.feedProfile,g=p?.target?.feedProfile,I,h,S,T,y,E,P,A,U,N;if(e&&(i||s)&&(P=i&&l!==dn&&t.find(({matchUpId:R})=>R===i),T=s&&f!==dn&&t.find(({matchUpId:R})=>R===s),P||T))return{matchUp:o,targetLinks:{loserTargetLink:m,winnerTargetLink:u},targetMatchUps:{loserMatchUp:T,winnerMatchUp:P}};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:E,targetDrawPosition:y,matchUp:T}=yS({targetLink:m,sourceRoundMatchUpCount:M,inContextDrawMatchUps:t,sourceRoundPosition:D,drawDefinition:r})),d&&g!==dn&&({matchUpDrawPositionIndex:S,targetDrawPosition:h,matchUp:I}=yS({targetLink:p,sourceRoundMatchUpCount:M,inContextDrawMatchUps:t,sourceRoundPosition:D,drawDefinition:r})),u&&!P&&l!==dn&&({matchUpDrawPositionIndex:U,targetDrawPosition:A,matchUp:P}=yS({targetLink:u,sourceRoundMatchUpCount:M,inContextDrawMatchUps:t,sourceRoundPosition:D,drawDefinition:r})),P||(N=N||t.filter(R=>R.structureId===n.structureId),{matchUp:P}=rv({structureMatchUps:N,matchUp:o})),nt({matchUp:o,targetLinks:{loserTargetLink:m,winnerTargetLink:u,byeTargetLink:p},targetMatchUps:{winnerMatchUpDrawPositionIndex:U,loserMatchUpDrawPositionIndex:E,byeMatchUpDrawPositionIndex:S,winnerTargetDrawPosition:A,loserTargetDrawPosition:y,byeTargetDrawPosition:h,winnerMatchUp:P,loserMatchUp:T,byeMatchUp:I},targetMatchUpIds:!!(i||s)})}function bk({matchUp:t}){return{targetLinks:{loserTargetLink:void 0,winnerTargetLink:void 0},targetMatchUps:{loserMatchUp:void 0,winnerMatchUp:void 0},matchUp:t}}function nv({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===gi){let{roundNumber:c}=n,u=c&&dt(c)+1,p=a.matchUps??[],{roundMatchUps:m}=Ke({matchUps:p});if(u&&m?.[u]){let d=[...s].sort(le).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=mr({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=tP({upcomingMatchUp:u}),d=tP({upcomingMatchUp:p});if(n.matchUpStatus!==Nt&&p?.matchUpStatus===Nt){let{matchUp:f}=ov({matchUp:p,drawDefinition:t,inContextDrawMatchUps:e})||{};d=f&&tP({upcomingMatchUp:f})||d}let l=n.schedule?.timeAfterRecovery;if(l&&(m?.schedule?.scheduledTime&&Yt(m.schedule.scheduledTime)<Yt(l)&&(r[m.matchUpId]=n.matchUpId,m.schedule.scheduleConflict=n.matchUpId),d?.schedule?.scheduledTime&&Yt(d.schedule.scheduledTime)<Yt(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===wn,I=vk(n);if(I.length){let h=Lf(u?.sides),S=Lf(p?.sides),y=I.find(({participantId:A})=>h.includes(A))?[]:I,P=I.find(({participantId:A})=>S.includes(A))?[]:I;p&&g&&P.length<2&&P.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)),P?.length&&p&&(c.targetMatchUpIds||(u=e.find(({matchUpId:A})=>A===p.matchUpId)),p.potentialParticipants||(p.potentialParticipants=[]),p.potentialParticipants.push(P))}}}}),Object.keys(r).length&&e.forEach(n=>{Object.keys(r).includes(n.matchUpId)&&(n.schedule.scheduleConflict=r[n.matchUpId])}),{scheduleConflictMatchUpIds:r}}function vk(t){return t?.sides?.map(({participant:e,participantId:r,qualifier:n})=>e||r&&{participantId:r}||n&&{qualifier:n}).filter(Boolean)||[]}function ov({matchUp:t,drawDefinition:e,inContextDrawMatchUps:r}){let{matchUpId:n,matchUpStatus:o,structureId:i}=t||{};if(!t||!i||t?.matchUpStatus===Xt)return{matchUp:t};if(o===Nt){let s;return t.winnerMatchUpId?s=r.find(({matchUpId:a})=>a===t.winnerMatchUpId):{winnerMatchUp:s}=mr({inContextDrawMatchUps:r,drawDefinition:e,matchUpId:n})?.targetMatchUps||{},ov({matchUp:s,drawDefinition:e,inContextDrawMatchUps:r})}return{matchUp:void 0}}function tP(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 ce(t){let e="getAllDrawMatchUps";Object.assign(t,{requireParticipants:!1});let r=Ys(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 Ys(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:E,event:P}=t,A=[],U=[],N=[],D=[],M=[];h&&!r&&(r=Qn({policyDefinitions:u,tournamentRecord:p,contextProfile:h,event:P}));let R;!e?.length&&p&&(e=p?.participants,(y||a?.withGroupings)&&e?.length&&({participantsWithGroupings:e,groupInfo:R}=fu({participants:e,participantsProfile:a})));let{structures:b}=gn({drawDefinition:S});if(!b)return{error:wt};n||(n=Me({drawDefinition:S}));let v=S&&sS({drawDefinition:S}).exitProfiles;b.forEach(F=>{let{byeMatchUps:w=[],pendingMatchUps:L=[],upcomingMatchUps:G=[],completedMatchUps:k=[],abandonedMatchUps:H=[]}=yu({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:E,event:P});A=A.concat(...H),U=U.concat(...k),N=N.concat(...G),D=D.concat(...L),M=M.concat(...w)});let O=F=>(!l&&!T&&!d||(l&&(F=Mi({matchUps:F,...l})),d&&(F=Mi({matchUps:F,...d,processContext:!0}))),F),x={abandonedMatchUps:O(A),completedMatchUps:O(U),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:w,completed:L,upcoming:G,pending:k,bye:H}=F,W=[].concat(...w&&A||[],...L&&U||[],...G&&N||[],...k&&D||[],...H&&M||[]);nv({inContextDrawMatchUps:W,drawDefinition:S})}return x}function Xn(t){let{participants:e=[],contextContent:r,participantMap:n}=t,{scheduleVisibilityFilters:o,tournamentAppliedPolicies:i,participantsProfile:s,afterRecoveryTimes:a,policyDefinitions:c,useParticipantMap:u,tournamentRecord:p,usePublishState:m,contextFilters:d,matchUpFilters:l,contextProfile:f,nextMatchUps:g,inContext:I,context:h,event:S}=t;if(!S)return{error:Ot};let{eventId:T,eventName:y,endDate:E,eventType:P,category:A,gender:U,matchUpFormat:N}=S??{},D={...h,...nt({indoorOutDoor:S.indoorOutdoor??p?.indoorOutdoor,surfaceCategory:S.surfaceCategory??p?.surfaceCategory,endDate:S.endDate??p?.endDate,tournamentId:p?.tournamentId,matchUpFormat:N,eventName:y,eventType:P,category:A,eventId:T,gender:U})};E&&(D.endDate=E),f&&!r&&(r=Qn({policyDefinitions:c,tournamentRecord:p,contextProfile:f,event:S}));let M;if(!e?.length&&!n&&p){let O=Wo({participantsProfile:s,useParticipantMap:u,policyDefinitions:c,tournamentRecord:p,contextProfile:f,inContext:I});n=O.participantMap,e=O.participants??[],M=O.groupInfo}let R=S.drawDefinitions??[],b=Ea({tournamentRecord:p,event:S}).scheduleTiming;return{matchUps:R.flatMap(O=>{let{matchUps:x}=ce({tournamentParticipants:e,tournamentAppliedPolicies:i,scheduleVisibilityFilters:o,context:D,participantsProfile:s,afterRecoveryTimes:a,policyDefinitions:c,tournamentRecord:p,usePublishState:m,contextFilters:d,contextProfile:f,drawDefinition:O,contextContent:r,matchUpFilters:l,participantMap:n,scheduleTiming:b,nextMatchUps:g,inContext:I,event:S});return x??[]}),groupInfo:M}}function ye(t){let e=et(t,[{tournamentRecord:!0}]);if(e.error)return e;if(!t?.tournamentRecord)return{error:$};let{participantMap:r,participants:n}=t,{scheduleVisibilityFilters:o,participantsProfile:i,afterRecoveryTimes:s,useParticipantMap:a,policyDefinitions:c,tournamentRecord:u,inContext:p=!0,usePublishState:m,contextProfile:d,matchUpFilters:l,contextFilters:f,nextMatchUps:g,context:I}=t,h=t.tournamentId??u.tournamentId,S=u?.events??[];n||({participants:n,participantMap:r}=Wo({participantsProfile:i,useParticipantMap:a,policyDefinitions:c,tournamentRecord:u,contextProfile:d,inContext:p}));let{appliedPolicies:T}=Tt({tournamentRecord:u}),y={...I,tournamentId:h,indoorOutDoor:u.indoorOutdoor,surfaceCategory:u.surfaceCategory,endDate:u.endDate},E=Qn({policyDefinitions:c,tournamentRecord:u,contextProfile:d});return{matchUps:S.flatMap(A=>(y.eventDrawsCount=A.drawDefinitions?.length??0,Xn({context:y,scheduleVisibilityFilters:o,tournamentAppliedPolicies:T,participantsProfile:i,afterRecoveryTimes:s,policyDefinitions:c,tournamentRecord:u,usePublishState:m,contextContent:E,contextFilters:f,contextProfile:d,matchUpFilters:l,participantMap:r,nextMatchUps:g,participants:n,inContext:p,event:A}).matchUps??[])).concat(...u.matchUps??[])}}function Un({scheduleVisibilityFilters:t,afterRecoveryTimes:e,participantsProfile:r,tournamentRecords:n,policyDefinitions:o,usePublishState:i,matchUpFilters:s,contextFilters:a,nextMatchUps:c,inContext:u}){if(typeof n!="object"||!Object.keys(n).length)return{error:Lt};let m=Object.keys(n).map(d=>{let l=n[d];return ye({scheduleVisibilityFilters:t,afterRecoveryTimes:e,participantsProfile:r,policyDefinitions:o,tournamentRecord:l,usePublishState:i,matchUpFilters:s,contextFilters:a,nextMatchUps:c,inContext:u}).matchUps??[]}).flat();return{...C,matchUps:m}}function Ri(t,e){return Ok(t,e)||(t?.stageSequence||0)-(e?.stageSequence||0)||t?.roundNumber&&e.roundNumber&&t?.roundNumber-e?.roundNumber||(t?.roundPosition??0)-(e?.roundPosition??0)}function Ok(t,e){return(Gs[t?.stage]||0)-(Gs[e?.stage]||0)}function ir(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:E,eventType:P,category:A,gender:U,matchUpFormat:N}=S??{},D={...h,surfaceCategory:S?.surfaceCategory??p?.surfaceCategory,indoorOutDoor:S?.indoorOutdoor??p?.indoorOutdoor,matchUpFormat:N,eventType:P,eventName:y,category:A,eventId:T,endDate:E,gender:U},M;return!e?.length&&!r&&p&&({participants:e=[],participantMap:r,groupInfo:M}=Wo({participantsProfile:s,useParticipantMap:u,policyDefinitions:c,tournamentRecord:p,contextProfile:l,inContext:I})),l&&!n&&(n=Qn({policyDefinitions:c,tournamentRecord:p,contextProfile:l,drawDefinition:f,event:S})),{...ce({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 fs({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 eP=t=>e=>!t||typeof e!="object"?void 0:Array.isArray(t)&&t.map(r=>({[r]:fs({element:e,accessor:r})?.value}))||typeof t=="object"&&Object.keys(t).map(r=>({[r]:fs({element:e,accessor:r})?.value}))||(typeof t=="string"&&fs({element:e,accessor:t}))?.value,Br=eP;function Pa({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),E=a&&I!==1,P=1+t+(E?r??0:0),A=1,U=tt(P,s?P+S*2:y+P+A),N=y+A-S,D=l(U.slice(N)),M=l(U.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 Ki({inContextDrawMatchUps:t,drawDefinition:e,matchUpsMap:r}){if(!e)return{error:Z};let n={loserMatchUpIds:{},winnerMatchUpIds:{}};if(t||({matchUps:t,matchUpsMap:r}=ce({inContext:!0,drawDefinition:e,matchUpsMap:r})),!r?.drawMatchUps.some(i=>i.finishingPositionRange)&&e?.structures?.length===1&&!e?.structures[0].structures){let i=r?.drawMatchUps??[];Pa({matchUps:i})}return(t??[]).filter(({collectionId:i})=>!i).forEach(i=>{let{matchUpId:s,structureId:a}=i,c=mr({inContextDrawMatchUps:t,drawDefinition:e,matchUpId:s}),{winnerMatchUp:u,loserMatchUp:p}=c.targetMatchUps,m=u?.matchUpId,d=p?.matchUpId,f=si({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 on(t){let e=Mr(t),r=t.matchUps??[],n=t.drawIds??[],{includeParticipantDependencies:o,tournamentRecord:i,drawDefinition:s}=t;if(!Array.isArray(r))return{error:eo};if(!Array.isArray(n))return{error:sn};let a=t.matchUpIds?.length?t.matchUpIds:r.map(T=>T.matchUpId);if(!Array.isArray(a))return{error:ns};let c={},u={},p={},m={};i&&!Object.keys(e).length&&(e={[i.tournamentId]:i});let d=Object.values(e),f=d.reduce((T,y)=>T.concat(y.events??[]).map(E=>(E.drawDefinitions||[]).map(P=>P.links||[])).flat(1/0),[]).filter(({linkType:T})=>T===xn),g=r;if(f.length){g=Un({nextMatchUps:!0,tournamentRecords:e}).matchUps;let T=f.reduce((y,E)=>{let P=E.source?.structureId,A=E.target?.structureId;return P&&A&&(p[A]=P),P&&!y.includes(P)&&y.push(P),y},[]);for(let y of T)c[y]=[];for(let y of g??[]){let E=y.containerStructureId||y.structureId;T.includes(E)&&c[E].push(y.matchUpId)}}let I=T=>{u[T]||(u[T]={dependentMatchUpIds:[],participantIds:[],matchUpIds:[],sources:[]},m[T]=[])},h=(T,y)=>{u[T].matchUpIds.forEach(P=>{u[y].matchUpIds.push(P)}),u[y].matchUpIds.push(T),u[T].dependentMatchUpIds.push(y),o&&u[T].participantIds.forEach(P=>u[y].participantIds.push(P))},S=T=>{let y=Object.keys(c).length;for(let E of T||[]){let{matchUpId:P,winnerMatchUpId:A,loserMatchUpId:U}=E;if(!a.length||a.includes(P)){if(I(P),o){let{individualParticipantIds:M}=mu(E);u[P].participantIds=M}A&&(I(A),h(P,A),m[A].push(P)),U&&(I(U),h(P,U),m[U].push(P)),u[P].sources.push(m[P]);let N=m[P].map(M=>u[M].sources[0]).flat(),D=m[P].map(M=>u[M].sources[1]).flat();if(u[P].sources.push(N,D),y){let M=E.containerStructureId||E.structureId,R=p[M];if(c[R])for(let b of c[R])I(b),h(b,P),m[b].push(P)}}}};if(s)Ki({drawDefinition:s}),g?.length||(g=ir({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:E=[]})=>E.map(({drawId:P})=>P))).flat(1/0):[];T&&(n=T)}for(let T of n){let y=g?.filter(P=>P.drawId===T).sort(Ri);if(!y?.find(({roundPosition:P})=>!P)){let P=y?.find(({tournamentId:U})=>U),{drawDefinition:A}=ze({tournamentRecord:e[P?.tournamentId],drawId:T});A&&Ki({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 Da({matchUpStatus:t}){return Hh.includes(t)}function iv({matchUpStatus:t}){return Xm.includes(t)}function ug({matchUpStatus:t}){return Wh.includes(t)}function pg({matchUpStatus:t,winningSide:e,tieMatchUps:r,sides:n,score:o}){let i=n?.find(({participantId:c})=>c),s=r?.filter(pg)?.length;return Ie({score:o})||s||e&&i||t&&iv({matchUpStatus:t})&&![Rt,bt,Gn].includes(t)}function Na(t){let{drawDefinition:e,findContainer:r,structureId:n,event:o}=t,i=t.structure,{containedStructures:s}=cs({drawDefinition:e}),a=n?s[n]||[]:[],c={isCollectionMatchUp:!1};if(!i){let A=at({drawDefinition:e,structureId:n});if(A.error)return A;i=r?A.containingStructure??A.structure:A.structure}if(pr({structure:i}))return{structure:i,isAdHoc:!0,error:Cs};let{matchUps:u}=ce({inContext:!0,matchUpFilters:c,drawDefinition:e,event:o}),p=u?.filter(A=>A.structureId===n||a.includes(A.structureId)),{matchUpDependencies:m}=on({drawIds:[e.drawId],matchUps:u,drawDefinition:e}),d=[],l=[],f={},g=[];for(let A of u??[]){if(A.structureId===n||a.includes(A.structureId)){l.push(...A.drawPositions??[]);let U=A.roundNumber;for(let N of(A.drawPositions??[]).filter(Boolean))(!f[N]||U&&f[N]>U)&&(f[N]=U)}pg(A)&&(g.push(A),d.push(A.matchUpId,...m?.[A?.matchUpId]?.matchUpIds||[]))}let I=pt(l.filter(Boolean)).sort(le),h=pt(d),S=pt(p?.map(({matchUpId:A,drawPositions:U})=>h.includes(A)?U:[]).flat().filter(Boolean)).sort(le),{positionAssignments:T}=Ct({drawDefinition:e,structure:i}),y=T?.filter(A=>A.bye).map(A=>A.drawPosition),E=T?.filter(A=>A.qualifier).map(A=>A.drawPosition),P=I?.filter(A=>!S.includes(A))||[];return{allDrawPositions:I,inContextStructureMatchUps:p,drawPositionInitialRounds:f,activeDependentMatchUpIds:h,qualifyingDrawPositions:E,inactiveDrawPositions:P,positionAssignments:T,activeDrawPositions:S,byeDrawPositions:y,activeMatchUps:g,structure:i}}function gs({drawPosition:t,matchUps:e=[]}){return{initialRoundNumber:e.filter(({drawPositions:n})=>t&&n?.includes(t)).map(({roundNumber:n})=>n).sort(le)[0]}}var Ma={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 AS=[];function Cn(t,e){Vt(t)&&(t={method:t}),(e||Pr())&&AS.push(t)}function _k(t){let e=AS.slice();return t&&(AS.length=0),e}function sv(t){let r=_k(t).map(n=>{let{color:o,keyColors:i,method:s,newline:a}=n,c=Object.keys(Ma).includes(o)?Ma[o]:Ma.cyan,p=Object.keys(n).filter(d=>!["color","keyColors","method","newline"].includes(d)).map(d=>{let l=i&&Object.keys(i).includes(d)&&Ma[i[d]]?Ma[i[d]]:Ma.brightwhite;return`${Ma.white}${d}: ${l}${n[d]}`}).join(", "),m=s?.length<15?" ":" ";return[a?`
2
2
  `:"",c,s,m,Ma.white,p,Ma.reset,`
3
3
  `].join("")});r?.length&&console.log(...r)}function av(){AS.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:wt};s||({structureId:s}=a);let u="assignDrawPositionBye";Cn({method:u,color:"cyan",drawPosition:o}),i||(i=Me({drawDefinition:n}));let{positionAssignments:p}=Ct({structure:a}),{activeDrawPositions:m}=Na({drawDefinition:n,structureId:s});if(p?.find(R=>R.drawPosition===o)?.bye)return{...C};if(m?.includes(o))return{error:zu};let f=p?.find(R=>R.drawPosition===o);if(!f)return{error:Cs};let{filled:g,containsBye:I,assignedParticipantId:h}=xk(f);if(I)return{...C};if(g&&!I)return _({result:{error:ja},stack:u});let S=Tt({tournamentRecord:r,drawDefinition:n,event:c}).appliedPolicies??{},T=ce({inContext:!0,drawDefinition:n,matchUpsMap:i}).matchUps??[],y={isCollectionMatchUp:!1},{matchUps:E}=yt({provisionalPositioning:t,drawDefinition:n,matchUpFilters:y,matchUpsMap:i,structure:a});if(p?.forEach(R=>{R.drawPosition===o&&(R.bye=!0)}),a.structureType===Ve)return wk({tournamentRecord:r,drawDefinition:n,drawPosition:o,matchUps:E}),Oo({tournamentId:r?.tournamentId,drawDefinition:n,structure:a,event:c}),cv({assignedParticipantId:h,isPositionAction:e,appliedPolicies:S,drawDefinition:n,drawPosition:o,structureId:s,stack:u});let{roundProfile:P,roundMatchUps:A}=Ke({matchUps:E}),N=(P&&Object.keys(P).map(R=>parseInt(R)).reverse())?.find(R=>P?.[R].drawPositions?.includes(o)),D=N?A?.[N].find(({drawPositions:R})=>R?.includes(o)):void 0;D&&uv({tournamentRecord:r,drawDefinition:n,matchUp:D,event:c});let M=D?.drawPositions?.find(R=>R!==o);if(D&&M){let R=ES({sourceDrawPositions:D.drawPositions,matchUpId:D.matchUpId,inContextDrawMatchUps:T,drawPositionToAdvance:M,tournamentRecord:r,drawDefinition:n,matchUpsMap:i});if(R.error)return R}return Oo({tournamentId:r?.tournamentId,drawDefinition:n,structure:a,event:c}),cv({assignedParticipantId:h,isPositionAction:e,appliedPolicies:S,drawDefinition:n,drawPosition:o,structureId:s,stack:u})}function cv({assignedParticipantId:t,isPositionAction:e,appliedPolicies:r,drawDefinition:n,drawPosition:o,structureId:i,stack:s}){return e&&pu({appliedPolicies:r,drawDefinition:n,positionAction:{removedParticipantId:t,drawPosition:o,structureId:i,name:s}}),_({result:{...C},stack:s})}function xk(t){let e=t.bye,r=t.qualifier,n=t.participantId;return{containsBye:e,containsQualifier:r,assignedParticipantId:n,filled:e||r||n}}function uv({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 wk({tournamentRecord:t,drawDefinition:e,drawPosition:r,matchUps:n,event:o}){n.forEach(i=>{i.drawPositions?.includes(r)&&uv({eventId:o?.eventId,tournamentRecord:t,drawDefinition:e,matchUp:i})})}function ES({drawPositionToAdvance:t,inContextDrawMatchUps:e,sourceDrawPositions:r,tournamentRecord:n,drawDefinition:o,matchUpsMap:i,matchUpId:s,event:a}){Cn({method:"advanceDrawPosition",color:"cyan",drawPositionToAdvance:t});let u=i.drawMatchUps.find(E=>E.matchUpId===s),m=e.find(E=>E.matchUpId===s)?.structureId,{structure:d}=at({drawDefinition:o,structureId:m}),{positionAssignments:l}=Ct({structure:d}),f=l?.filter(E=>E.bye).map(E=>E.drawPosition),g=u?.drawPositions?.find(E=>E!==t),I=g&&f?.includes(g),{targetLinks:{loserTargetLink:h},targetMatchUps:{loserMatchUp:S,winnerMatchUp:T,loserTargetDrawPosition:y}}=mr({inContextDrawMatchUps:e,drawDefinition:o,matchUpId:s});if(T&&T.structureId===d?.structureId&&Lk({drawPositionToAdvance:t,inContextDrawMatchUps:e,sourceDrawPositions:r,tournamentRecord:n,drawDefinition:o,winnerMatchUp:T,matchUpsMap:i,event:a}),S&&I&&S.structureId!==d?.structureId){let{roundNumber:E}=S;if(E===1){let P=Hr({structureId:h.target.structureId,drawPosition:y,tournamentRecord:n,drawDefinition:o,event:a});if(P.error)return P}else pv({loserTargetDrawPosition:y,tournamentRecord:n,loserTargetLink:h,drawDefinition:o,loserMatchUp:S,matchUpsMap:i,event:a})}return{...C}}function Lk({drawPositionToAdvance:t,inContextDrawMatchUps:e,sourceDrawPositions:r,tournamentRecord:n,drawDefinition:o,winnerMatchUp:i,matchUpsMap:s,event:a}){let c="advanceWinner",u=s.drawMatchUps.find(w=>w.matchUpId===i.matchUpId),m=e.find(w=>w.matchUpId===i.matchUpId)?.structureId,{structure:d}=at({drawDefinition:o,structureId:m}),{positionAssignments:l}=Ct({structure:d}),g=l?.find(({drawPosition:w})=>w===t)?.bye,I=u.drawPositions?.filter(Boolean),h=l?.filter(w=>I?.includes(w.drawPosition)),S=l?.find(({drawPosition:w})=>w===t),T=r?.find(w=>w!==t),E=(T&&h?.find(({drawPosition:w})=>w===T))?.bye,P=g&&E;if(P&&console.log({isByeAdvancedBye:P}),I?.length>1&&g&&!E)return _({result:{error:ja},stack:c});let A=I?.find(w=>w!==t),U=P,N=[...(u.drawPositions||[]).filter(Boolean),void 0,void 0].slice(0,2),D=N.map(w=>!w&&!U||w===t?(U=!0,t):w).sort(le);if(!U)return console.log("@@@@@@@",{advancingAssignmentIsBye:S,drawPositionToAdvance:t,existingAssignments:h}),_({result:{error:ja},stack:c});let M=l?.find(({drawPosition:w})=>w===A)?.bye,R=l?.find(({drawPosition:w})=>w===t)?.bye;Object.assign(u,{matchUpStatus:R||M?Nt:Xt,score:void 0,winningSide:void 0,drawPositions:D});let v=u.drawPositions.find(w=>!N.includes(w));Cn({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}}=mr({matchUpId:i.matchUpId,inContextDrawMatchUps:e,drawDefinition:o});if(M||R){let w=M?t:A;if(w)ES({drawPositionToAdvance:w,matchUpId:i.matchUpId,inContextDrawMatchUps:e,tournamentRecord:n,drawDefinition:o,matchUpsMap:s});else if(R&&O&&x)if(x.feedRound)pv({loserTargetDrawPosition:F,tournamentRecord:n,loserTargetLink:O,drawDefinition:o,loserMatchUp:x,matchUpsMap:s});else{let G=1-i.roundPosition%2,k=x.drawPositions[G],H=Hr({structureId:O.target.structureId,drawPosition:k,tournamentRecord:n,drawDefinition:o,event:a});if(H.error)return H}}}function pv({loserTargetDrawPosition:t,tournamentRecord:e,loserTargetLink:r,drawDefinition:n,loserMatchUp:o,matchUpsMap:i,event:s}){let{roundNumber:a}=o;Cn({method:"assignFedDrawPositionBye",color:"cyan",loserTargetDrawPosition:t});let p=(i?.mappedMatchUps||{})[o.structureId].matchUps,{initialRoundNumber:m}=gs({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 US({positionAssignments:t,tournamentRecord:e,drawDefinition:r,matchUpsMap:n,structure:o,event:i}){let{matchUps:s}=yt({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:Xt}),gt({tournamentId:e?.tournamentId,context:"modifyRoundRobinMatchUpsStatus",eventId:i?.eventId,drawDefinition:r,matchUp:a}))})}function gc(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=(ge({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:bs};r||(r=m?.participantId);let{activeDrawPositions:d}=Na({drawDefinition:i,structureId:s});return d.includes(n)?{error:zu}:(e||({matchUps:e}=ce({inContext:!0,drawDefinition:i,matchUpsMap:a})),rP({inContextDrawMatchUps:e,tournamentRecord:o,drawDefinition:i,structureId:s,drawPosition:n,matchUpsMap:a,event:c}).drawPositionCleared?(Oo({tournamentId:o?.tournamentId,drawDefinition:i,structure:u,event:c}),{...C,participantId:r}):{error:LA})}function rP({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:wt};let c=ge({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===Ve)return US({positionAssignments:c,tournamentRecord:e,drawDefinition:r,matchUpsMap:o,structure:a}),{drawPositionCleared:u,...C};let p={isCollectionMatchUp:!1},{matchUps:m}=yt({drawDefinition:r,matchUpFilters:p,matchUpsMap:o,structure:a,event:s}),{roundProfile:d,roundMatchUps:l}=Ke({matchUps:m}),g=(d&&Object.keys(d))?.map(T=>dt(T)),I=n,S=g?.map(T=>{let E=d?.[T]?.pairedDrawPositions?.find(v=>v.includes(I)),P=E?.find(v=>v!==I),A=c.find(v=>v.drawPosition===P),U=d?.[T+1],N=A?.bye,D=U?.pairedDrawPositions?.find(v=>v.includes(P)),M=N&&D&&U&&U.drawPositions?.includes(P),b=E&&{pairedDrawPositionByeAdvancedPair:!M&&D,pairedDrawPosition:P,targetDrawPosition:I,relevantPair:E,roundNumber:T};return M&&(I=P),b}).filter(T=>T?.targetDrawPosition)?.reduce((T,y)=>{let{roundNumber:E,relevantPair:P,targetDrawPosition:A,pairedDrawPosition:U,pairedDrawPositionByeAdvancedPair:N}=y,D={roundNumber:E,targetDrawPosition:A,relevantPair:P},M=N&&{roundNumber:E+1,targetDrawPosition:U,relevantPair:N,subsequentRoundRemoval:!0},R=[D,M].filter(Boolean);return T.concat(...R)},[]);return S?.forEach(({roundNumber:T,targetDrawPosition:y,relevantPair:E})=>{let P=l?.[T].find(A=>ke(A.drawPositions?.filter(Boolean),E.filter(Boolean)));P&&(Fk({inContextDrawMatchUps:t,targetDrawPosition:y,tournamentRecord:e,drawDefinition:r,structureId:i,roundNumber:T,matchUpsMap:o}),mv({inContextDrawMatchUps:t,positionAssignments:c,tournamentRecord:e,drawDefinition:r,targetMatchUp:P,drawPosition:n,matchUpsMap:o,structure:a,event:s}))}),{tasks:S,drawPositionCleared:u,positionAssignments:c}}function Fk({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:wt};if(a.structureType===Ve)return;o=o||Me({drawDefinition:n});let u=(o?.mappedMatchUps||{})[s].matchUps,{initialRoundNumber:p}=gs({drawPosition:e,matchUps:u}),m=u?.filter(l=>l.roundNumber>=i&&l.roundNumber!==p&&l.drawPositions?.includes(e)),d=Ct({drawDefinition:n,structureId:s}).positionAssignments??[];return m?.forEach(l=>mv({drawPosition:e,targetMatchUp:l,inContextDrawMatchUps:t,positionAssignments:d,tournamentRecord:r,drawDefinition:n,matchUpsMap:o,structure:a})),{...C}}function mv({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}=gs({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===Wt){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=mr({matchUpId:o.matchUpId,inContextDrawMatchUps:t,drawDefinition:n}),{targetLinks:{winnerTargetLink:h},targetMatchUps:{loserMatchUp:S,winnerMatchUp:T,loserMatchUpDrawPositionIndex:y}}=I,P=e.filter(({drawPosition:D})=>o.drawPositions?.includes(D)).filter(D=>D.bye).length,A=P&&Nt||o.matchUpStatus&&[Rt,bt].includes(o.matchUpStatus)&&o.matcHUpStatus||Xt;o.matchUpStatus=A,o.matchUpStatus&&[bt,Rt].includes(o.matchUpStatus)&&(o.winningSide=void 0);let U=p?.find(D=>!o.drawPositions?.includes(D));if(p?.includes(i)&&m===o.matchUpStatus&&d===o.winningSide||(U&&Cn({method:u,color:"brightyellow",removedDrawPosition:U}),gt({tournamentId:r?.tournamentId,context:`${u}-${i}`,eventId:c?.eventId,matchUp:o,drawDefinition:n})),S&&S.structureId!==I.matchUp.structureId&&!P){let{drawPositions:D,roundNumber:M}=S;if(M===1){let R=D[y];rP({structureId:S.structureId,drawPosition:R,inContextDrawMatchUps:t,tournamentRecord:r,drawDefinition:n,matchUpsMap:s})}else{let R=Math.min(...D.filter(Boolean)),b=kk({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}=gs({drawPosition:R,matchUps:O});x===1&&(Cn({method:u,color:"brightyellow",loserMatchUpDrawPosition:R}),rP({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 kk({loserMatchUpDrawPosition:t,inContextDrawMatchUps:e,tournamentRecord:r,drawDefinition:n,loserMatchUp:o,matchUpsMap:i,event:s}){let{structure:a}=at({structureId:o.structureId,drawDefinition:n}),{positionAssignments:c}=Ct({structure:a});if(c?.find(p=>p.drawPosition===t)?.bye){let p=gc({drawPosition:t,structureId:o.structureId,inContextDrawMatchUps:e,tournamentRecord:r,drawDefinition:n,matchUpsMap:i,event:s});if(p.error)return p}return{...C}}function Ci({drawDefinition:t,stages:e}){if(!t)return{error:Z};let r=(t?.structures??[]).filter(o=>!e?.length||o.stage&&e.includes(o.stage)),n=pt(r.map(o=>{let{positionAssignments:i}=Ct({structure:o});return i?i.map(St):[]}).flat().filter(Boolean));return{...C,assignedParticipantIds:n}}function Jn(t){let e=(t?.entries??[]).filter(Boolean).reduce((n,o)=>{let{entryStage:i,entryStatus:s}=o,a=`_${i||rt}${s||""}`;return n[a]||(n[a]=[]),n[a].push(o),n},{}),r=n=>isNaN(n)?1/0:n;return Object.keys(e).map(n=>e[n].sort((o,i)=>r(o.entryPosition)-r(i.entryPosition)).map((o,i)=>{let s=i+1;return{...o,entryPosition:s}})).flat()}function qs(t){return[Ui,Gr].includes(t)}function fd({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:Ot};if(i&&!YU.includes(i))return{error:Zl};if(s&&!zc.includes(s))return{error:xi};let d="modifyEntriesStatus",l=[];if(!i&&!a)return _({result:{error:st},info:"Missing entryStatus",stack:d});if(a&&!kn({extension:a,requiredAttributes:["name"]}))return _({result:{error:V},info:"Invalid extension",context:{extension:a},stack:d});let f=[];m?.drawDefinitions?.forEach(D=>{let M=Ci({stages:p&&[p],drawDefinition:D}).assignedParticipantIds??[];f.push(...M)});let g=r?.participants??[];if(!o.every(D=>{let M=Bo({tournamentParticipants:g,participantId:D})?.participantType;return!(M&&[ft,Er].includes(M)&&qs(i))&&!(i&&m?.eventType&&M===At&&[qr,br].includes(m.eventType)&&[rn,...rg].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)&&!(rg.includes(v.entryStatus)&&rg.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?Ut({element:v,extension:a}):gr({element:v,name:a.name})),!0))?{...C}:{error:Os}},y=({flight:D,drawDefinition:M})=>{m&&(m.entries=Jn({entries:m.entries??[]})),D&&(D.drawEntries=Jn({entries:D.drawEntries})),M&&(M.entries=Jn({entries:M.entries}))},E=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}},P=m?.entries?.find(({entryPosition:D})=>D)??(S?.drawEntries?.find(({entryPosition:D})=>D)||n?.entries?.find(({entryPosition:D})=>D));if(t&&!P&&y({flight:S,drawDefinition:n}),S||n){let D=E({flight:S,drawDefinition:n});if(D.error)return _({result:D,stack:d})}let A=m?.drawDefinitions?.map(({drawId:D})=>D)??[],U=h?.flights?.filter(D=>!A.includes(D.drawId))||[];for(let D of U){let M=D&&E({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&&jU.includes(i))return{error:TE};if(!S&&!n||i===uo||c&&N){let D=T(m?.entries);if(D?.error)return _({result:D,stack:d});let M;if(i===uo&&(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)||vt({tournamentId:r.tournamentId,eventId:m?.eventId,drawDefinition:D});return{...C}}function Ao({requireTimeStamp:t,scaleAttributes:e,participant:r}){if(!r)return{error:Fi};if(!ht(e))return{error:V};if(r.timeItems||(r.timeItems=[]),Array.isArray(r.timeItems)){let{accessor:n,scaleType:o,eventType:i,scaleName:s}=e,a=[Si,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!==Si)return{error:za};let g=(n&&fs({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 dv({publishedSeeding:t,usePublishState:e,withSeeding:r,participant:n,event:o}){let i={},s=m=>[Si,To,o.eventType,m].join("."),a=Object.assign({},...(n.timeItems||[]).filter(({itemType:m})=>m.split(".")[1]===To).map(({itemType:m,itemValue:d})=>({[m]:d}))),c=(t?.stageSeedingScaleNames&&Object.values(t?.stageSeedingScaleNames)||Array.isArray(t?.seedingScaleNames)&&t.seedingScaleNames||[]).map(s),u=jt(Object.keys(a),c);if(!!(!e||!Object.keys(a).length&&!t?.drawIds?.length||u.length)&&u.length){if(t?.stageSeedingScaleNames){let m=Object.keys(t.stageSeedingScaleNames).map(l=>{let f=s(t.stageSeedingScaleNames[l]),g=a[f];return[l,g]}).filter(l=>l[1]).map(l=>({[l[0]]:{seedValue:l[1]}})),d=Object.assign({},...m);i.seedAssignments=d}else if(u){let m=u.map(d=>a[d]);i.seedValue=m.pop()}}else if(!e&&typeof r=="object"){let m=Object.keys(r).map(l=>{let f=s(r[l]),g=a[f];return[l,g]}).filter(l=>l[1]).map(l=>({[l[0]]:{seedValue:l[1]}})),d=Object.assign({},...m);i.seedAssignments=d}else{let{categoryName:m,ageCategoryCode:d}=o.category||{},l=[d,o.eventId,m].filter(Boolean),f;for(let g of l){let I={eventType:o.eventType,scaleType:To,scaleName:g},h=Ao({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 lv({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({},...Uf(m??[])):{},l=Object.assign(d,{entryPosition:p,entryStatus:c,entryStage:u,ranking:s,eventId:i});r.events[i]=nt(l,!1,!1,!0),n&&(e&&(r.events[i].seedAssignments=e),o&&(r.events[i].seedValue=o))}function Au(t){let e=et(t,[{[ne]:!0}]);if(e.error)return e;let{tournamentRecord:r,status:n=Rr}=t,o=`${wo}.${Lo}`;return J(td({tournamentRecord:r,itemType:o})?.timeItem?.itemValue?.[n],!1,!0)}function fv(t){let{tournamentId:e}=t??{};return!!e}function Xr({event:t,status:e=Rr}){let r=`${wo}.${Lo}`;return gu({itemType:r,event:t})?.timeItem?.itemValue?.[e]}function gd({drawDetails:t,drawId:e}){return t?.[e]?.publishingDetail?.published}function Is(t){let{tournamentRecord:e,drawDefinition:r,eventIds:n,eventId:o,drawIds:i,drawId:s,event:a}=t??{};if(e&&!fv(e))return{error:V};if(o&&!a)return{error:jr};if(Array.isArray(n)&&n?.length){let m={};for(let d of n){if(!Vt(d))return{error:V};let l=ze({tournamentRecord:e,eventId:d})?.event;if(!l)return{error:jr};let f=nP({event:l});m[d]=f}return{...C,publishState:m}}if(a){let m=nP({event:a}),d={};if(s)return r?{publishState:{status:{published:!!m.status.publishedDrawIds?.includes(s),drawDetail:m.status.drawDetails?.[s]},...C}}:{error:Cr};if(Array.isArray(i)&&i?.length){let l=a.drawDefinitions?.map(cu)??[];for(let f of i){if(!Vt(f))return{error:V};if(!l.includes(f))return{error:Cr};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=nP({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=Au({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 nP({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(cu)||[])n[a]||(n[a]={publishingDetail:{published:!1}});let o=n&&Object.keys(n).length&&Object.keys(n).filter(a=>gd({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 PS(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:Pt(p?.scheduledDate),scheduledTime:Qt(p?.scheduledTime),checkScoreHasValue:Ie({score:d}),matchUpStatus:n,roundPosition:o,structureId:i,matchUpType:s,roundNumber:a,matchUpId:c,potential:u,drawId:m})}function gv({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===bt&&(f.walkoverWinCount+=1),o===Rt&&(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 oP(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:E,collectionId:P,matchUpType:A,winningSide:U,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:w}=O;if(w)continue;let L=U===F,G=W=>{let q=o[W]?.participant,Y=q?.participantType,B=[{participantId:W,participantType:Y}];if(Y!==Er)for(let K of q?.individualParticipantIds||[]){let X=o[K]?.participant;B.push({participantType:X?.participantType,participantId:K})}return B},k=(W,q)=>{if(s){if(o[W].matchUps[N]={participantWon:L,matchUpType:A,structureId:f,sideNumber:F,matchUpId:N,eventId:M,drawId:R,stage:I},i){let Y=G(q);o[W].matchUps[N].opponentParticipantInfo=Y}P&&(o[W].matchUps[N].collectionId=P)}i&&q&&(o[W].opponents[q]={participantId:q,matchUpId:N,eventId:M,drawId:R}),h&&gv({finishingPositionRange:u,participantMap:o,participantWon:L,finishingRound:p,matchUpStatus:m,participantId:W,stageSequence:d,roundNumber:l,structureId:f,matchUpId:N,drawId:R,stage:I}),(r||e)&&PS({participantMap:o,participantId:W,matchUpStatus:m,roundPosition:T,matchUpType:A,roundNumber:l,structureId:f,matchUpId:N,schedule:D,drawId:R,score:g})},H=({participant:W,partnerParticipantId:q})=>{let Y=(B,K)=>{B&&(B.partnerParticipantIds||(B.partnerParticipantIds=[]),B.partnerParticipantIds.includes(K)||B.partnerParticipantIds.push(K))};c&&Y(W?.draws?.[R],q),a&&Y(W?.events?.[M],q),s&&Y(W?.matchUps?.[N],q)};if(x&&o[x]){let W=v?.[F];k(x,W);let q=o[x]?.participant.participantType===ft,Y=o[x]?.participant.individualParticipantIds||[];if(y){if(n){let B=K=>o[K].matchUps[y]={participantWon:S===F,matchUpId:y,matchUpType:Wt,sideNumber:F};B(x),Y.forEach(B)}if(c&&!o[x].draws[R]){let B=E.find(j=>j.sideNumber===F)?.participant?.participantId,K=o[B]?.draws?.[R]?.entryStatus,X=j=>o[j].draws[R]={entryStatus:K,eventId:M,drawId:R};X(x),Y.forEach(X)}}if(q&&(Y.forEach(B=>o[B]&&k(B,W)),Y.forEach((B,K)=>{let X=Y[1-K],j=o[B];j&&H({participant:j,partnerParticipantId:X})}),a&&E)){let B=E.find(K=>K.sideNumber===F)?.participant?.participantId;if(B){let K=o[B]?.events[M];K?(o[x].events[M]={...K},Y.forEach(X=>o[X].events[M]={...K})):console.log("Missing teamEntry",{eventId:M,teamParticipantId:B})}}if(U){let B=K=>{L?(o[K].counters[A].wins+=1,o[K].counters.wins+=1,m===bt&&(o[K].counters[A].walkoverWins+=1,o[K].counters.walkoverWins+=1),m===Rt&&(o[K].counters[A].defaultWins+=1,o[K].counters.defaultWins+=1)):(o[K].counters[A].losses+=1,o[K].counters.losses+=1,m===bt&&(o[K].counters[A].walkovers+=1,o[K].counters.walkovers+=1),m===Rt&&(o[K].counters[A].defaults+=1,o[K].counters.defaults+=1))};B(x),Y.forEach(B)}}}}function Eu(t,e){return(t||"").localeCompare(e||"")}function Iv(t){let{participantFilters:e,convertExtensions:r,policyDefinitions:n,tournamentRecord:o,usePublishState:i,contextFilters:s,matchUpFilters:a,participantMap:c,contextProfile:u,withPotentialMatchUps:p,withRankingProfile:m,withScheduleItems:d,scheduleAnalysis:l,withTeamMatchUps:f,withStatistics:g,withOpponents:I,withMatchUps:h,withSeeding:S,withEvents:T,withDraws:y}=t,E=e?.participantIds,P=O=>{let x=[O];return c[O]?.participant.individualParticipantIds?.forEach(F=>x.push(F)),x.some(F=>!E?.length||E.includes(F))?x:[]},A={withMatchUps:h||m,withEvents:T||m,withDraws:y||m,withPotentialMatchUps:p,withRankingProfile:m,withScheduleItems:d,scheduleAnalysis:l,withTeamMatchUps:f,withStatistics:g,participantMap:c,withOpponents:I,withSeeding:S},U=[],N={},D=[],M={},R={},b={},v=({eventType:O,scaleNames:x,participantId:F})=>c[F]?.participant?.rankings?.[O]?.find(w=>x.includes(w.scaleName))?.scaleValue;for(let O of o?.events||[]){if(e?.eventIds&&!e.eventIds.includes(O.eventId))continue;let{drawDefinitions:x=[],extensions:F=[],eventType:w,eventName:L,category:G,entries:k,eventId:H,gender:W}=O,{flightProfile:q}=Ht({event:O}),Y=q?.flights??[],B=Is({event:O}).publishState;B&&(M[H]=B);let K=B?.status?.publishedSeeding;if(T||S||m){let j=r?Object.assign({},...Uf(F??[])):{};R[H]={...j,eventName:L,eventType:w,category:G,eventId:H,gender:W};let ot=[G?.categoryName,G?.ageCategoryCode].filter(Boolean);for(let z of k){let{participantId:Q}=z;if(!Q||!c[Q])continue;let ut=v({eventType:w,scaleNames:ot,participantId:Q}),it,Et;if(S){let $t=c[Q].participant;({seedAssignments:it,seedValue:Et}=dv({publishedSeeding:K,usePublishState:i,withSeeding:S,participant:$t,event:O}))}let _t=$t=>{if(c[$t]?.events?.[H])return;let Se=c[$t];lv({convertExtensions:r,seedAssignments:it,participant:Se,withSeeding:S,seedValue:Et,eventId:H,ranking:ut,entry:z})};_t(Q),(c[Q].participant.individualParticipantIds||[]).forEach(_t)}}let X=M?.[H]?.publishedSeeding;if(y||m||S){let j=z=>z?Object.assign({},...z.map(({participantId:Q,seedValue:ut,seedNumber:it})=>({[Q]:{seedValue:ut,seedNumber:it}}))):void 0,ot=pt([...x.map(cu),...Y.map(cu)]);for(let z of ot){let Q=x.find(Pe=>Pe.drawId===z),ut=[G?.categoryName,G?.ageCategoryCode].filter(Boolean),{structures:it=[],drawOrder:Et,drawName:_t,drawType:Ae}=Q??{},$t=Y?.find(Pe=>Pe.drawId===z),Se=Q?.entries||$t?.drawEntries,Or=$t?.flightNumber,pn=(Q?.structures||[]).sort((Pe,ae)=>yi(Pe,ae)).map(({structureId:Pe,structures:ae})=>[Pe,...(ae||[]).map(({structureId:hr})=>hr)]).flat(1/0),Ir,Xe,te,Dt,ue=0,pe=it.filter(({stage:Pe,stageSequence:ae})=>Pe===rt&&ae===1||Pe===ct).flatMap(Pe=>{let{positionAssignments:ae}=Ct({structure:Pe}),{seedAssignments:hr,stageSequence:_r,stage:Kt}=Pe;return Kt===rt?(ue=ae?.length??0,te=ae,Dt=hr):_r===1&&(Ir=ae,Xe=hr),ae}).map(({participantId:Pe})=>Pe).filter(Boolean),Fe=j(Dt),ee=j(Xe),Je=Q?Se.filter(({participantId:Pe})=>pe.includes(Pe)):Se,qt=!i||X?.published&&(X?.drawIds?.length===0||X?.drawIds?.includes(z));for(let Pe of Je){if(!c[Pe.participantId])continue;let{entryStatus:ae,entryStage:hr,entryPosition:_r,participantId:Kt}=Pe,De=v({participantId:Kt,scaleNames:ut,eventType:w}),fr=Ne=>{if(!c[Ne]||c[Ne].draws?.[z])return;let On=S&&qt,me=On?{}:void 0,dr=On?Fe?.[Kt]?.seedValue||Fe?.[Kt]?.seedNumber:void 0,es=dr?Fe?.[Kt]:void 0,Tn=On?ee?.[Kt]?.seedValue||ee?.[Kt]?.seedNumber:void 0,mi=Tn?ee?.[Kt]:void 0;me&&dr&&(me[rt]=es),me&&Tn&&(me[ct]=mi);let ca=dr||Tn;ca&&(c[Ne].participant.seedings[w]||(c[Ne].participant.seedings[w]=[]),es&&c[Ne].participant.seedings[w].push({...es,scaleName:z}),mi&&c[Ne].participant.seedings[w].push({...mi,scaleName:z}),me&&(c[Ne].events[H].seedAssignments||(c[Ne].events[H].seedAssignments={}),Object.keys(me).forEach(Ku=>c[Ne].events[H].seedAssignments[Ku]=me[Ku]))),(y||m)&&(c[Ne].draws[z]=nt({seedAssignments:me,entryPosition:_r,entryStatus:ae,entryStage:hr,seedValue:ca,eventId:H,ranking:De,drawId:z},!1,!1,!0))};[Gr,Ui].includes(ae)||(fr(Kt),(c[Kt].participant.individualParticipantIds||[])?.forEach(fr))}let ar=(Q?.structures??[]).reduce((Pe,ae)=>(Pe.includes(ae.stage)||Pe.push(ae.stage),Pe),[]),Ze=(Q?.links??[]).length;b[z]={qualifyingPositionAssignments:Ir,qualifyingSeedAssignments:Xe,mainPositionAssignments:te,qualifyingSeedingMap:ee,mainSeedAssignments:Dt,orderedStructureIds:pn,mainSeedingMap:Fe,flightNumber:Or,linksCount:Ze,drawOrder:Et,drawName:_t,drawType:Ae,drawSize:ue,drawId:z,stages:ar}}}if(m||l||f||g||I||h||y){let j=!!l||p,ot=Xn({afterRecoveryTimes:!!l,policyDefinitions:n,tournamentRecord:o,inContext:!0,participantMap:c,contextFilters:s,matchUpFilters:a,contextProfile:u,nextMatchUps:j,event:O})?.matchUps??[];for(let z of ot){let{finishingPositionRange:Q,potentialParticipants:ut,tieMatchUps:it=[],sides:Et=[],winningSide:_t,matchUpType:Ae,matchUpId:$t,eventId:Se,drawId:Or,collectionId:pn,stageSequence:Ir,finishingRound:Xe,matchUpStatus:te,roundPosition:Dt,roundNumber:ue,structureId:pe,schedule:Fe,score:ee,stage:Je}=z;N[$t]=z;let qt={finishingPositionRange:Q,finishingRound:Xe,stageSequence:Ir,roundPosition:Dt,collectionId:pn,roundNumber:ue,structureId:pe,schedule:Fe,eventId:Se,drawId:Or,score:ee,stage:Je};oP({...qt,...A,matchUpStatus:te,winningSide:_t,matchUpType:Ae,matchUpId:$t,sides:Et});for(let ar of it){let{winningSide:Ze,sides:Pe=[],matchUpId:ae,matchUpStatus:hr,matchUpType:_r}=ar;oP({...qt,...A,winningSide:Ze,tieWinningSide:_t,matchUpTieId:$t,matchUpId:ae,sides:Pe,matchUpSides:Et,matchUpStatus:hr,matchUpType:_r})}Array.isArray(ut)&&(j||l||d)&&ut.flat().map(St).filter(Boolean)?.forEach(Ze=>{P(Ze)?.forEach(ae=>{c[ae]&&(c[ae].potentialMatchUps[$t]=nt({tournamentId:o?.tournamentId,matchUpId:$t,eventId:Se,drawId:Or}))}),(l||d)&&PS({potential:!0,participantMap:c,participantId:Ze,matchUpStatus:te,roundPosition:Dt,structureId:pe,matchUpType:Ae,roundNumber:ue,matchUpId:$t,schedule:Fe,drawId:Or,score:ee})})}D.push(...ot)}}if(g||m||l){let O=Object.values(c);for(let x of O){let{wins:F,losses:w,[kt]:{wins:L,losses:G},[xt]:{wins:k,losses:H}}=x.counters,W=(q,Y,B)=>{let K=Y+B,X=Y,j=K&&X/K;x.statistics[q]={denominator:K,numerator:X,statValue:j,statCode:q}};if(g&&(W(rd,F,w),W(`${rd}.${kt}`,L,G),W(`${rd}.${xt}`,k,H)),m){let q=(Y=[])=>Math.abs(Y[0]-Y[1]);for(let Y of Object.keys(x.draws)){let{orderedStructureIds:B=[],flightNumber:K}=b[Y]||{};if(x.structureParticipation&&B.length){let X,j=0,ot=B.map(z=>{let Q=x.structureParticipation[z];if(!Q)return;X||(X=Q?.finishingPositionRange),q(X)>q(Q?.finishingPositionRange)&&(X=Q?.finishingPositionRange);let ut=Q.stage!==ct;return ut&&(j+=1),nt({...Q,participationOrder:ut?j:void 0,flightNumber:K})}).filter(Boolean);x.draws[Y]&&(x.draws[Y].finishingPositionRange=X,x.draws[Y].structureParticipation=ot)}}}if(l){let q=ht(l)?l.scheduledMinutesDifference:0,Y=x.scheduleItems||[],B=x.potentialMatchUps||{},K=Y.reduce((j,ot)=>{let{scheduledDate:z,scheduledTime:Q}=ot;return j[z]||(j[z]=[]),Q&&j[z].push(ot),j},{});Object.values(K).forEach(j=>j.sort(rh));for(let j of Y){let{typeChangeTimeAfterRecovery:ot,timeAfterRecovery:z,scheduledDate:Q,scheduledTime:ut}=j,it=K[Q],Et=Yt(ut);for(let _t of it){if(_t.matchUpId===j.matchUpId||[bt,Rt].includes(_t.matchUpStatus)&&!_t.checkScoreHasValue)continue;let Se=j.matchUpType!==_t.matchUpType&&ot||z,Or=j.drawId===_t.drawId,pn=B[j.matchUpId]&&B[_t.matchUpId],Ir=Yt(_t.scheduledTime),Xe=Math.abs(Ir-Et),te=Ir>=Et;if((q&&!isNaN(q)?Xe<=q:te&&Yt(_t.scheduledTime)<Yt(Se))&&!(pn&&Or)&&te){let ue=[j.matchUpId,_t.matchUpId].sort(Eu).join("|");x.scheduleConflicts[ue]={priorScheduledMatchUpId:j.matchUpId,matchUpIdWithConflict:_t.matchUpId}}}}let X=x.participant.participantId;Object.keys(x.scheduleConflicts).length&&U.push(X),c[X].scheduleConflicts=x.scheduleConflicts}}}return{participantIdsWithConflicts:U,eventsPublishStatuses:M,derivedEventInfo:R,derivedDrawInfo:b,mappedMatchUps:N,participantMap:c,matchUps:D}}function Uu({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=$s(l)&&e?.events?.filter(y=>l?.includes(y.eventId))||e?.events||[],I=o&&Gk({drawEntryStatuses:o,tournamentEvents:g}),h=s&&Vk({eventEntryStatuses:s,tournamentEvents:g}),S=i!==void 0&&[!0,!1].includes(i)&&g.reduce((y,E)=>y.concat(...(E.drawDefinitions||[]).map(P=>qh({drawDefinition:P}).allPositionedParticipantIds).filter(Boolean)),[]),T=y=>n?.reduce((E,P)=>{let{accessor:A,value:U}=P,{values:N}=fs({element:y,accessor:A});return E&&N?.includes(U)},!0);if(r=r?.filter(y=>{let E=en({element:y,itemType:cc})?.timeItem?.itemValue,{participantRoleResponsibilities:P,participantType:A,participantRole:U,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&&E===m||u&&A&&$s(u)&&u.includes(A)||a&&U&&$s(a)&&a.includes(U)||c&&$s(P)&&$s(c)&&c.find(R=>P?.includes(R))||n?.length&&$s(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||E===m)&&(!u||A&&$s(u)&&u.includes(A))&&(!a||U&&$s(a)&&a.includes(U))&&(!c||$s(P)&&$s(c)&&c.find(R=>P?.includes(R)))&&(!n?.length||$s(n)&&T(y))}),g.length&&l){let y=g.filter(E=>l.includes(E.eventId)).map(E=>{let P=(E.entries||[]).map(U=>U.participantId);if(de($n)(E.eventType))return P;let A=(e?.participants??[]).filter(U=>P.includes(U.participantId)).map(U=>U.individualParticipantIds).flat(1);return P.concat(...A)}).flat(1);r=r?.filter(E=>y.includes(E.participantId))}return r}function $s(t){return t&&Array.isArray(t)&&t.length}function Gk({drawEntryStatuses:t,tournamentEvents:e}){let r=({entryStatus:n})=>Array.isArray(t)?t.includes(n):!0;return pt(e.reduce((n,o)=>{let{flightProfile:i}=Ht({event:o}),s=i?.flights?.map(({drawEntries:c})=>Array.isArray(c)?c.filter(r).map(St):[]).flat()||[],a=o.drawDefinitions?.map(({entries:c})=>c?c.filter(r).map(St):[])||[];return n.concat(...s,...a)},[]))}function Vk({eventEntryStatuses:t,tournamentEvents:e}){return pt(e.reduce((r,n)=>{let o=(n.entries||[]).filter(({entryStatus:i})=>Array.isArray(t)?t.includes(i):!0).map(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,withStatistics:f,contextFilters:g,matchUpFilters:I,contextProfile:h,withOpponents:S,withMatchUps:T,internalUse:y,withSeeding:E,withEvents:P,withDraws:A,withISO2:U,withIOC:N}=t;if(!c)return{error:$};(T||o)&&on({tournamentRecord:c});let D=rS({convertExtensions:i,tournamentRecord:c,withSignInStatus:p,withScaleValues:d,internalUse:y,withISO2:U,withIOC:N}),{participantMap:M}=D,R=Iv({withMatchUps:T??o,withEvents:P??o,withDraws:A??o,withPotentialMatchUps:n,participantFilters:r,withRankingProfile:o,convertExtensions:i,withScheduleItems:a,policyDefinitions:s,tournamentRecord:c,scheduleAnalysis:u,withTeamMatchUps:m,usePublishState:l,withStatistics:f,contextFilters:g,matchUpFilters:I,participantMap:M,withOpponents:S,contextProfile:h,withSeeding:E}),{participantIdsWithConflicts:b,eventsPublishStatuses:v,derivedEventInfo:O,derivedDrawInfo:x,mappedMatchUps:F}=R,w=R.matchUps;M=R.participantMap;let L=u??n,G=({potentialMatchUps:K,scheduleConflicts:X,scheduleItems:j,participant:ot,statistics:z,opponents:Q,matchUps:ut,events:it,draws:Et})=>{let _t=Object.values(Et),Ae=Object.values(Q);return S&&_t?.forEach($t=>{$t.opponents=Ae.filter(Se=>Se.drawId===$t.drawId)}),nt({...ot,scheduleConflicts:u?Object.values(X):void 0,draws:A||o?_t:void 0,events:P||o?Object.values(it):void 0,matchUps:T||o?Object.values(ut):void 0,opponents:S?Ae:void 0,potentialMatchUps:L?Object.values(K):void 0,statistics:f?Object.values(z):void 0,scheduleItems:a?j:void 0},!1,!1,!0)},k=new Map;for(let K of Object.keys(M))k.set(K,G(M[K]));let H=[...k.values()],q=s?.[Bs]?.participant,Y=Uu({participants:H,participantFilters:r,tournamentRecord:c});if(e){let K=ht(e)?e:void 0;for(let X of Y)for(let j of X.individualParticipantIds??[]){X.individualParticipants||(X.individualParticipants=[]);let ot=k.get(j),z=K?Hi({template:K,source:ot}):ot;X.individualParticipants.push(z)}}let B=q?Y.map(K=>Hi({source:K,template:q})):Y;return{participantMap:t.returnParticipantMap!==!1?M:void 0,mappedMatchUps:t.returnMatchUps!==!1?F:void 0,matchUps:t.returnMatchUps!==!1?w:void 0,missingParticipantIds:D.missingParticipantIds,participantIdsWithConflicts:b,eventsPublishStatuses:v,derivedEventInfo:O,derivedDrawInfo:x,participants:B,...C}}function Ic({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 hs(t){let{provisionalPositioning:e,drawDefinition:r,stageSequence:n,structureId:o,stage:i}=t;if(!r)return{error:Z};let{entryProfile:s}=Iu({drawDefinition:r}),a=i&&n&&s?.[i]?.stageSequence?.[n]?.qualifiersCount||i&&s?.[i]?.qualifiersCount||0,c={};if(!o)return{qualifiersCount:a,roundQualifiersCounts:c};let{structure:u}=at({drawDefinition:r,structureId:o}),p=r.links?.filter(l=>l?.target?.structureId===u?.structureId),m=0;if(p?.length)for(let l of p){let f=at({structureId:l.source.structureId,drawDefinition:r})?.structure;if(f?.stage===ct){let g=l.source.roundNumber,I=l.target.roundNumber,h=0;if(f.structureType===Ve){let S=f.structures?.length??0,T=l.source.finishingPositions?.length??0;h=S*T}else h=yt({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 bp({stage:t,drawDefinition:e}){let{entryProfile:r}=Iu({drawDefinition:e});return r?.[t]?.drawSize||0}function hv(t){let{provisionalPositioning:e,drawDefinition:r,stageSequence:n,stage:o}=t,i=bp({stage:o,drawDefinition:r}),{qualifiersCount:s}=hs({provisionalPositioning:e,drawDefinition:r,stageSequence:n,stage:o});return i&&i-s}function iP({stage:t,drawDefinition:e}){return!!(t===$e||ng({stage:t,drawDefinition:e})&&bp({stage:t,drawDefinition:e}))}function sP({entryStatus:t=kr,drawDefinition:e,stageSequence:r,stage:n}){if(t===rn)return Cb({stage:n,drawDefinition:e})?{positionsAvailable:1/0,...C}:{error:SE};let o=hv({drawDefinition:e,stageSequence:r,stage:n}),i=bb({drawDefinition:e,stage:n}),s=oS({entryStatus:hu,drawDefinition:e,stage:n}),a=oS({entryStatus:kr,drawDefinition:e,stage:n}),c=s+a,u=c>=o,p=o-c;return n!==$e&&u?{error:qI}:t===hu?s<i?{...C}:{error:qI}:{positionsAvailable:p,...C}}function Id(t){let e=et(t,[{[Ce]:!0,[vh]:!0}]);if(e.error)return e;let{suppressDuplicateEntries:r=!0,entryStatus:n=kr,entryStageSequence:o,entryStage:i=rt,ignoreStageSpace:s,drawDefinition:a,entryPosition:c,participant:u,roundTarget:p,extensions:m,extension:d,drawType:l,event:f}=t,g="addDrawEntry";if(l!==$r&&!iP({stage:i,drawDefinition:a}))return _({result:{error:xi},stack:g});let I=sP({stageSequence:o,stage:i,drawDefinition:a,entryStatus:n});if(!s&&!I.success&&(!l||l!==$r))return{error:I.error};if(d&&!kn({extension:d}))return _({result:{error:V},info:"Invalid extension",context:{extension:d},stack:g});let h=t.participantId||u?.participantId;if(!h)return _({result:{error:ie},stack:g});let S=n===us&&Ic({participantId:h,drawDefinition:a,entryStatus:n}),T=i===$e&&Ic({participantId:h,drawDefinition:a,entryStage:i}),y=Ic({participantId:h,drawDefinition:a}),E=n!==us&&i!==$e&&y;if(E)return r?(lt({payload:{drawId:a.drawId,eventId:f?.eventId,error:Em,participantId:h},topic:Kh}),{...C}):_({result:{error:Em},context:{participantId:h},stack:g});if(S||T)return _({context:{invalidEntry:E,invalidLuckyLoser:S,invalidVoluntaryConsolation:T},result:{error:Zu},stack:g});let P=nt({entryStageSequence:o,participantId:h,entryPosition:c,entryStatus:n,entryStage:i,extensions:m});return d&&Ut({element:P,extension:d}),p&&Ut({extension:{name:"roundEntry",value:p},element:P}),a.entries||(a.entries=[]),a.entries.push(P),vt({drawDefinition:a}),{...C}}function Sv(t){let e="addDrawEntries",{suppressDuplicateEntries:r=!0,entryStatus:n=kr,autoEntryPositions:o=!0,ignoreStageSpace:i,participantIds:s,drawDefinition:a,stageSequence:c,stage:u=rt,roundTarget:p,extension:m,event:d}=t;if(!u)return{error:QA};if(!a)return{error:Z};if(!Array.isArray(s))return{error:wr};if(!iP({stage:u,drawDefinition:a}))return{error:xi};if(m&&!kn({extension:m}))return _({result:{error:V},info:"Invalid extension",context:{extension:m},stack:e});let l=sP({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:Jl};let g=[],I=a.drawId,h=d?.eventId,S=s.reduce((T,y)=>{let E=n===us&&Ic({participantId:y,drawDefinition:a,entryStatus:n}),P=u===$e&&Ic({entryStage:u,drawDefinition:a,participantId:y}),A=Ic({participantId:y,drawDefinition:a});return n!==us&&u!==$e&&A&&(g.push(y),r&&lt({payload:{error:Em,participantId:y,eventId:h,drawId:I},topic:Kh})),E||P?T.concat(y):T},[]);return g.length&&!r?_({context:{eventId:h,drawId:I,duplicateEntries:g},result:{error:Em},stack:e}):(s.filter(T=>T&&!S.includes(T)).forEach(T=>{let y={entryStageSequence:c,entryStage:u,participantId:T,entryStatus:n};m&&Ut({element:y,extension:m}),p&&Ut({extension:{name:Mn,value:p},element:y}),a.entries||(a.entries=[]),a.entries.push(y)}),o&&(a.entries=Jn({entries:a.entries})),vt({drawDefinition:a}),S?.length||g?.length?{info:"some participantIds could not be added",participantIdsNotAdded:S,duplicateEntries:g,...C}:{...C})}function mg({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:Do};if(!m)return{error:jr};if(!p)return{error:sn};let d=(m.entries||[]).map(St);if(o.filter(I=>!d.includes(I)).length)return{error:KA};if(i){let I=Sv({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===us&&aP({participantId:I,entryStatus:s,flight:g}),S=c===$e&&aP({participantId:I,entryStage:c,flight:g});!(s!==us&&c!==$e&&aP({flight:g,participantId:I}))&&!h&&!S&&g.drawEntries.push({participantId:I,entryStatus:s,entryStage:c})}),e&&(g.drawEntries=Jn({entries:g.drawEntries}))),{...C}}function aP({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 hc({autoEntryPositions:t=!0,participantIds:e=[],entryStatuses:r,stage:n,event:o}){let i="removeEventEntries";if(!o?.eventId)return{error:Ot};if(!Array.isArray(e)||e.some(m=>!Vt(m)))return _({result:{error:mn},stack:i});let s=(o.drawDefinitions??[]).flatMap(m=>Ci({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=jt(a,c):a.length?e=a:c.length&&(e=c),e?.length&&s.some(m=>e.includes(m)))return _({result:{error:Os},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=Jn({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 cP={[rr]:{policyName:"matchUpActionsDefault",enabledStructures:[{stages:[],stageSequences:[],enabledActions:[],disabledActions:[]}],participants:{enforceCategory:!0,enforceGender:!0},processCodes:{substitution:["RANKING.IGNORE","RATING.IGNORE"]},substituteAfterCompleted:!1,substituteWithoutScore:!1}},Ss=cP;function Vn(t){let{suppressDuplicateEntries:e=!0,entryStatus:r=kr,autoEntryPositions:n=!0,enforceGender:o=!0,entryStageSequence:i,policyDefinitions:s,entryStage:a=rt,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=pt(t.participantIds??[]);if(!g)return{error:Ot};if(!h?.length)return _({result:{error:Do},stack:I});if(!g?.eventId)return{error:jr};let S=Tt({tournamentRecord:c,event:g}).appliedPolicies??{},T=s?.[rr]??S?.[rr]??Ss[rr],y=(o??T?.participants?.enforceGender)!==!1,E=[],P=[];if(d&&(!Array.isArray(d)||!d.every(x=>kn({extension:x})))||l&&!kn({extension:l}))return _({context:nt({extension:l,extensions:d}),result:{error:V},info:"Invalid extension(s)",stack:I});let A=!!c,U=[],N,D=c?.participants?.filter(x=>{if(!h.includes(x.participantId))return!1;let F=de(kt)(g.eventType)&&x.participantType===At&&!qs(r),w=g.eventType===xt&&x.participantType===ft;return F&&(!g.gender||!y||[Ar,Pn].includes(g.gender)||g.gender===x.person?.sex)||w&&!qs(r)||g.eventType===xt&&x.participantType===At&&qs(r)?!0:F&&g.gender&&y&&![Ar,Pn].includes(g.gender)&&g.gender!==x.person?.sex?(U.push({participantId:x.participantId,sex:x.person?.sex}),!1):g.eventType===Ft&&(x.participantType===Ft||qs(r)&&x.participantType===At)}).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=nt({participantId:x,entryStatus:r,entryStage:a,extensions:d});l&&Ut({element:F,extension:l}),m&&Ut({extension:{name:Mn,value:m},element:F}),i&&(F.entryStageSequence=i),E.push(F.participantId),g.entries?.push(F)}}),f&&!qs(a)){let x=mg({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&&[Vo,br].includes(g.eventType)){let x=(g.entries||[]).map(k=>k.participantId),F=(g.entries||[]).filter(k=>qs(k.entryStatus)).map(k=>k.participantId),L=(c?.participants??[]).filter(k=>x.includes(k.participantId)&&k.participantType&&[ft,Ft].includes(k.participantType)).map(k=>k.individualParticipantIds).flat(1/0),G=F.filter(k=>L.includes(k));G.length&&(P.push(...G),hc({participantIds:G,autoEntryPositions:!1,event:g}))}if(M.length!==h.length)return _({context:{mismatchedGender:U,gender:g.gender},result:{error:wr},stack:I});n&&(g.entries=Jn({entries:g.entries||[]}));let v=E.length,O=P.length;return _({result:{...C,addedEntriesCount:v,removedEntriesCount:O},stack:I,info:N})}var uP="ADMINISTRATION",Bk="CAPTAIN",Hk="COACH",xe="COMPETITOR",pP="MEDIA",mP="MEDICAL",dg="OFFICIAL",dP="OTHER",lP="SECURITY",hd={ADMINISTRATION:uP,CAPTAIN:Bk,COACH:Hk,COMPETITOR:xe,MEDIA:pP,MEDICAL:mP,OFFICIAL:dg,OTHER:dP,SECURITY:lP};function lg({addIndividualParticipantsToEvents:t,individualParticipantIds:e,groupingParticipantId:r,tournamentRecord:n,suppressErrors:o}){let i="removeIndividualParticipantIds";if(!n)return _({result:{error:$},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:re},stack:i});if(![Ft,zr].includes(a.participantType))return _({result:{participantType:a.participantType,error:An},stack:i});let c=Tv({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));Vn({participantIds:l,entryStatus:Gr,tournamentRecord:n,event:m})}}return u&&lt({topic:or,payload:{tournamentId:n.tournamentId,participants:[a]}}),{...C,...c}}function Tv({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}=mt({element:S,name:Co}),y=T?.value[e.participantId];T&&y&&(T.value[e.participantId]=y.filter(P=>P.participantId!==l),Ut({element:S,extension:T}),Aa({drawDefinition:S}));let E=ir({drawDefinition:S,inContext:!1}).matchUps??[];for(let P of E){let A=P.sides??[];for(let U of A){let N=U.lineUp??[];N.find(M=>M.participantId===l)&&(U.lineUp=N.filter(M=>M.participantId!==l),gt({tournamentId:r?.tournamentId,drawDefinition:S,matchUp:P}))}}}}else a.push(l);return!I});e.individualParticipantIds=m;let d={groupingParticipantId:e.participantId,cannotRemove:c,notRemoved:a,removed:s};return c.length&&!n&&{...d,cannotRemove:c,error:Ju}||d}function vp({participantRole:t=xe,individualParticipantIds:e=[],groupingTypes:r=[Er,zr],tournamentRecord:n}){if(!n)return{error:$};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}=Tv({groupingParticipant:c,individualParticipantIds:e,tournamentRecord:n,mappedMatchUps:s,participants:i});u&&a++}),a?C:{error:fE}}function zi(t){let e=et(t,[{[ne]:!0},{participantIds:!0,[He]:Be,[fn]:Do}]);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=(ye({matchUpFilters:{drawIds:f,matchUpTypes:[xt]},tournamentRecord:n}).matchUps??[]).flatMap(({sides:h})=>h?.map(({participantId:S})=>S||[])).filter(Boolean);return jt(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:Os};let m={},d={};for(let f of n.events||[]){let g=hc({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,Ft].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(vp({individualParticipantIds:o,tournamentRecord:n}),r)for(let f of n.events||[]){let I=m[f.eventId].map(h=>d[h]||[]).flat();Vn({participantIds:I,entryStatus:Gr,tournamentRecord:n,event:f})}return l&&lt({payload:{participantIds:o,tournamentId:n.tournamentId},topic:Vf}),l?{...C,participantsRemovedCount:l}:{error:Ju}}function DS({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 fP({removeGroupParticipant:t,tournamentRecord:e,drawDefinition:r,participantId:n,drawId:o,stage:i,event:s}){let a="destroyGroupEntry";if(!e)return{error:$};if(!n)return _({result:{error:ie},stack:a});if(!s)return{error:Ot};if(!s.eventType||![Vo,br].includes(s.eventType))return _({result:{error:jn},stack:a});let c=e.participants??[],u=c.find(S=>S.participantId===n);if(!u)return _({result:{error:re},stack:a});if(!u.participantType||![ft,Er].includes(u.participantType)||u.participantType===Er&&s.eventType!==br||u.participantType===ft&&s.eventType!==Vo)return{error:An};let m=(s.entries??[]).find(S=>S.participantId===n);if(!m)return{error:YI};let{stageEntries:d}=DS({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=>go(S,f).length===1),I=hc({participantIds:[n],event:s});if(I.error||g?.length&&(I=Vn({participantIds:g,entryStatus:Gr,entryStage:m.entryStage,tournamentRecord:e,drawDefinition:r,drawId:o,event:s}),I.error))return I;let h;return t&&zi({participantIds:[n],tournamentRecord:e}).success&&(h=!0),{...C,participantRemoved:h}}function fg({removeGroupParticipant:t,tournamentRecord:e,drawDefinition:r,participantId:n,drawId:o,event:i}){return fP({removeGroupParticipant:t,tournamentRecord:e,drawDefinition:r,participantId:n,drawId:o,event:i})}function gP(t){if(!t.tournamentRecord)return{error:$};let{participantIds:e,...r}=t,n=0,o=[];for(let i of e){let s=fP({participantId:i,...r});s.success&&(n+=1),s.error&&o.push(s.error)}return n?{destroyedCount:n,...C}:{error:o}}function Pu(t){let{tournamentRecord:e,replaceWithBye:r,drawDefinition:n,destroyPair:o,entryStatus:i,matchUpsMap:s,drawId:a}=t,c="removeDrawPositionAssignment",u=gc(t);if(u.error)return _({result:u,stack:c});let{participantId:p}=u,{drawPosition:m,event:d,structureId:l}=t,f=Tt({tournamentRecord:e,drawDefinition:n,event:d}).appliedPolicies??{};if([rn,uo].includes(i)&&p){let{tournamentRecord:h}=t,{participant:S}=yo({tournamentRecord:h,participantId:p}),{participantType:T,individualParticipantIds:y}=S??{};if(o&&T===ft){let E=fg({tournamentRecord:h,drawDefinition:n,participantId:p,event:d});if(E.error)return _({result:E,stack:c});y&&fd({participantIds:y,tournamentRecord:h,drawDefinition:n,entryStatus:i,drawId:a,event:d})}else fd({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 Zm({structure:g,drawPositions:[m]}),pu({appliedPolicies:f,drawDefinition:n,positionAction:{name:"removeDrawPositionAssignment",replaceWithBye:r,drawPosition:m,entryStatus:i,structureId:l}}),u}function IP(t){return Object.assign(t,{entryStatus:uo}),Pu(t)}var Ts=({finishingPosition:t=Bi,hasExistingDrawDefinition:e,qualifyingRoundNumber:r,structureAbbreviation:n,seedAssignments:o=[],stageSequence:i=1,qualifyingOnly:s,structureOrder:a,seedingProfile:c,matchUpFormat:u,structureType:p,structureName:m,matchUps:d=[],matchUpType:l,structureId:f,roundOffset:g,roundLimit:I,stageOrder:h,structures:S,tieFormat:T,stage:y})=>{let E={structureId:f??Mt(),structureAbbreviation:n,finishingPosition:t,seedAssignments:o,matchUpFormat:u,stageSequence:i,structureName:m};(s||e&&T)&&(E.tieFormat=T),a&&(E.structureOrder=a),p&&(E.structureType=p),c&&(typeof c=="string"?E.seedingProfile=c:typeof c=="object"&&typeof c.positioning=="string"&&(E.seedingProfile=c.positioning)),l&&(E.matchUpType=l),g&&(E.roundOffset=g),h&&(E.stageOrder=h),I&&(E.roundLimit=I),y&&(E.stage=y),r&&(E.qualifyingRoundNumber=r);let P=d.flatMap(({drawPositions:A})=>A).filter(Boolean);return S?E.structures=S:(E.matchUps=d,E.positionAssignments=pt(P).sort((A,U)=>A-U).map(A=>({drawPosition:A}))),E},hn=Ts;function NS(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)?NS(t.replace(/_/g," ")):""}function gg({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),vt({drawDefinition:r,structureIds:[i.structureId]}),{...C}}function Ig({drawPositions:t}){if(!t?.length)return{error:Ya};let e=o=>t.filter(i=>i!==o).map(i=>[o,i]),r=[].concat(...(t??[]).map(e)),n=pt(r.map(hg)).map(o=>o.split("|").map(i=>+i));return{groupMatchUps:r,uniqueMatchUpGroupings:n}}function hg(t=[]){return!Array.isArray(t)||!t.length?"":[...t].sort(le).join("|")}function hP({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 hg(l)}))}function Wk({rounds:t,hash:e}){return t?.length?t?.reduce((r,n,o)=>n.includes(e)?o+1:r,void 0):{error:st}}var yv={getRoundRobinGroupMatchUps:Ig,determineRoundNumber:Wk,drawPositionsHash:hg,groupRounds:hP};function Ra(t){let{hasExistingDrawDefinition:e,groupNameBase:r="Group",playoffAttributes:n,stageSequence:o=1,structureOptions:i,appliedPolicies:s,qualifyingOnly:a,seedingProfile:c,stage:u=rt,matchUpType:p,roundTarget:m,structureId:d,groupNames:l,tieFormat:f,drawSize:g,idPrefix:I,isMock:h,uuids:S}=t,T=t.structureName??n?.["0"]?.name??Qe(rt),{groupCount:y,groupSize:E}=jk({structureOptions:i,appliedPolicies:s,drawSize:g}),P=gi,A,U=tt(1,y+1).map(D=>{let M=Yk({groupSize:E,structureOrder:D,matchUpType:p,drawSize:g,idPrefix:I,isMock:h});A=Array.isArray(M)?Math.max(...M.map(({roundNumber:b})=>b??0)):0;let R=l?.[D-1]??`${r} ${D}`;return Ts({structureId:S?.pop(),hasExistingDrawDefinition:e,structureType:pp,finishingPosition:P,qualifyingOnly:a,structureOrder:D,structureName:R,tieFormat:f,matchUps:M})}),N=Ts({structureId:d??S?.pop(),hasExistingDrawDefinition:e,structureType:Ve,finishingPosition:P,seedingProfile:c,structureName:T,stageSequence:o,structures:U,tieFormat:f,stage:u});return m&&Ut({extension:{name:Mn,value:m},element:N}),{structures:[N],maxRoundNumber:A,groupCount:y,links:[],groupSize:E,...C}}function jk({appliedPolicies:t,structureOptions:e,drawSize:r}){let n=e?.groupSize,o=e?.groupSizeLimit||8,{validGroupSizes:i}=Op({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 Op(t){let{groupSizeLimit:e=10,drawSize:r=0}=t??{},n=tt(3,e+1).filter(o=>{let i=Math.ceil(r/o),s=i*o-r,a=Math.ceil(r/i),c=Math.ceil(s/i);return(!s||s<o)&&a===o&&a>=3&&c<2});return{...C,validGroupSizes:n}}function Yk({structureOrder:t,matchUpType:e,groupSize:r,drawSize:n,idPrefix:o,isMock:i,uuids:s}){let a=(t-1)*r,c=tt(1+a,r+1+a),u=Ig({drawPositions:c}).uniqueMatchUpGroupings??[],p=hP({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=hg(f),I=d(g),h=[1,n],S=qk({structureOrder:t,drawPositions:f,roundNumber:I,idPrefix:o,uuids:s}),T={matchUpStatus:I?Xt:Nt,matchUpType:e,finishingPositionRange:{winner:h,loser:h},drawPositions:f,roundNumber:I,matchUpId:S};return i&&(T.isMock=!0),T}}function qk({structureOrder:t,drawPositions:e,roundNumber:r,idPrefix:n,uuids:o}){return n?`${n}-${t}-${r}-DP-${e.join("-")}`:o?.pop()||Mt()}function Sg(t){let{roundRobinGroupsCount:e,participantsCount:r,cluster:n}=t;if(!It(r))return{seedBlocks:void 0,..._({result:{error:V},context:{participantsCount:r},stack:"getSeedBlocks"})};let o=rs(r);if(e){let l=Math.min(e,o),f=[],g=1;for(tt(0,l).forEach(()=>{f.push([g]),g++});g<o;){let I=tt(g,g+l);g+=l,f.push(I)}return{...C,seedBlocks:f}}let i=tt(1,o+1),s=[],a=o/2;for(;a>1;){let l=Ee(i,a),f=l.length;l.forEach((g,I)=>{let h,S=I<f/2,T=I%2===0,y=g[0],E=g[g.length-1];n&&f>4?f===8?h=S?E:y:h=T?y:E:h=S?y:E,ke(g,s)||s.push(h)}),a=a/2}let c=i.filter(l=>!s.includes(l));for(;c.length;)c.length%2===0?s.push(c.pop()):s.push(c.shift());let u=tt(0,20).map(l=>Math.pow(2,l));u.unshift(1);let p=u.indexOf(o),m=0,d=[];return tt(0,p).forEach(l=>{d.push(s.slice(m,m+u[l])),m+=u[l]}),{...C,seedBlocks:d}}function Tg({roundRobinGroupsCount:t,drawSize:e}){let r="getSeedGroups";if(!It(e))return{seedGroups:void 0,..._({result:{error:V},context:{drawSize:e},stack:r})};if(t){if(!It(t))return{seedGroups:void 0,..._({context:{roundRobinGroupsCount:t},result:{error:V},stack:r})};let n=1,o=Math.floor(e/t);return{seedGroups:tt(0,o).map(()=>{let s=tt(n,n+t);return n+=t,s})}}else{let{seedBlocks:n}=Sg({participantsCount:e,roundRobinGroupsCount:t}),o=0;return{seedGroups:(n||[]).map(s=>(s||[]).map(()=>(o+=1,o)))}}}function MS({roundRobinGroupsCount:t,participantsCount:e}){if(t){let{validGroupSizes:o}=Op({drawSize:e});if(!o?.map(a=>Math.ceil(e/a))?.includes(t))return _({context:{roundRobinGroupsCount:t},result:{error:V}})}let{seedGroups:r}=Tg({drawSize:e,roundRobinGroupsCount:t}),n=r?.map(o=>Math.min(...o))||[];return{...C,seedingThresholds:n}}function Sc(t){if(!t)return 1/0;if(It(t))return dt(t);let e=t.split("-")[0];return It(e)?dt(e):1/0}function $k({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(le),e.reverse(),e}function Av({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 Ev({positioning:t,size:e}){let r=$k({size:e}),n=[],o=[],i=d=>d[0],s=d=>d[d.length-1],a=(d,l)=>(t&&[Qc,li].includes(t)&&l%2?s(d):i(d))||i(d),c=(d,l)=>{if(d.every(f=>!o.includes(f))){let f=a(d,l);return o.push(f),f}},u=d=>{let l=d.filter(f=>!o.includes(f));if(l.length)return o.push(...l),l},p=(d,l)=>{let f=a(d,l);if(!o.includes(f))return o.push(f),f},m=tt(1,e+1);for(let d of r)if(d===1){let l=Ee(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=Ee(m,d).map(p).filter(Boolean);f.length&&n.push(f)}return{divisions:r,divisionGroupings:n}}function ys({provisionalPositioning:t,returnAllProxies:e,appliedPolicies:r,seedingProfile:n,drawDefinition:o,allPositions:i,structure:s}){let a=[];if(!s)return{error:di};let{matchUps:c,roundMatchUps:u}=yt({matchUpFilters:{roundNumbers:[1]},provisionalPositioning:t,structure:s}),{seedAssignments:p}=nn({provisionalPositioning:t,returnAllProxies:e,drawDefinition:o,structure:s}),{positionAssignments:m}=ge({structure:s}),d=m?.length,l=p?.length??0,f=[],I=Object.keys(u).map(w=>parseInt(w)).sort((w,L)=>w-L).map(w=>{let L=u[w].map(k=>k.drawPositions).flat(1/0).filter(Boolean),G=L.filter(k=>!f.includes(k));return f=f.concat(...L),G}).filter(w=>w.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(w=>w.filter(L=>L<=l).length),{stage:E,structureType:P,roundLimit:A}=s,U=P===Ve,N=!U&&I?.length,D=!U&&E===ct&&A,M=y.flat(1/0),R=N?M?.length:0,b=i?d:l,v=ad({drawDefinition:o,structure:s,matchUps:c}),O=v?0:!N&&b||b&&M.length<b&&b-M.length||0;if(D){let w=s?.matchUps?s.matchUps.filter(({roundNumber:G})=>G===s.roundLimit).length:0,L=h.length/w;if(!N){let G=xp(n),k=Ee(h,L),H=1,W=tt(0,k[0].length).map(()=>{let q=tt(H,H+k.length);return H+=k.length,q});({validSeedBlocks:a}=Uv({drawPositionBlocks:k,nonRandom:n?.nonRandom,positioning:G,seedGroups:W}))}}else U?{validSeedBlocks:a}=Kk({nonRandom:n?.nonRandom,seedingProfile:n,structure:s}):N?a=y.map(w=>({seedNumbers:w,drawPositions:w})):v&&Ee(h,2).map((L,G)=>({drawPositions:[L[0]],seedNumbers:[G+1]})).forEach(L=>a.push(L));if(!U&&!v&&!D){let{blocks:w}=zk({drawPositionOffset:S,seedNumberOffset:R,seedCountGoal:O,seedingProfile:n,baseDrawSize:T});w.forEach(L=>a.push(L))}let F=a.flatMap(w=>w.drawPositions).reduce((w,L)=>h?.includes(L)&&w,!0);return!v&&!N&&!U&&!F?{error:jA,validSeedBlocks:[],isContainer:U,isFeedIn:N}:{isLuckyStructure:v,validSeedBlocks:a,isContainer:U,isFeedIn:N}}function Kk({seedingProfile:t,structure:e,nonRandom:r}){let n=e.structures||[],o=n.length,i=Ct({structure:e})?.positionAssignments,s=xp(t),a=i?.length??0,{seedGroups:c}=Tg({roundRobinGroupsCount:o,drawSize:a}),u=n.map(p=>Ct({structure:p}).positionAssignments?.map(m=>m.drawPosition));return Uv({drawPositionBlocks:u,positioning:s,seedGroups:c,nonRandom:r})}function Uv({drawPositionBlocks:t,positioning:e,seedGroups:r,nonRandom:n}){let o=[],{divisionGroupings:i}=Ev({size:r.length,positioning:e}),s=[];return r.forEach((a,c)=>{let u=Av({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!==li?f=n?f:Sr(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 zk(t){let{drawPositionOffset:e=0,roundRobinGroupsCount:r,seedNumberOffset:n=0,seedingProfile:o,seedCountGoal:i,baseDrawSize:s}=t,a=1,c=[],{seedBlocks:u}=Sg({cluster:xp(o)===Qc,participantsCount:s,roundRobinGroupsCount:r});a=0;for(let m of u){if(a+1>i)break;let d=m.map(f=>f+e),l=p(a+1,m.length).map(f=>+f+n);a+=m.length,c.push({drawPositions:d,seedNumbers:l})}return{blocks:c};function p(m,d){return Array.from(new Array(d),(l,f)=>f+m)}}function _p({appliedPolicies:t,drawDefinition:e,seedBlockInfo:r,drawPosition:n,structureId:o,seedNumber:i}){let{structure:s}=at({drawDefinition:e,structureId:o});t||(t=Tt({drawDefinition:e}).appliedPolicies);let a=r?.validSeedBlocks;return!a&&s&&(a=ys({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 RS(t){let{provisionalPositioning:e,drawDefinition:r,seedingProfile:n,seedBlockInfo:o,structureId:i,randomize:s}=t,{structure:a}=at({drawDefinition:r,structureId:i}),{seedAssignments:c}=nn({returnAllProxies:t.returnAllProxies,provisionalPositioning:e,drawDefinition:r,structure:a}),{positionAssignments:u}=ge({structure:a}),m=u?.filter(L=>L.participantId??L.bye??L.qualifier)?.map(L=>L.drawPosition).filter(Boolean),{appliedPolicies:d}=Tt({drawDefinition:r}),g=(o?.validSeedBlocks||a&&ys({returnAllProxies:t.returnAllProxies,provisionalPositioning:e,appliedPolicies:d,drawDefinition:r,seedingProfile:n,structure:a})?.validSeedBlocks||[]).filter(L=>L.drawPositions.filter(k=>!m?.includes(k)).length)[0],I=c?.map(L=>L.participantId).filter(Boolean),h=u?.map(L=>L.participantId).filter(Boolean),S=I?.filter(L=>h?.includes(L)),T=I?.filter(L=>!h?.includes(L)),y=c?.filter(L=>T?.includes(L.participantId)),E=c?.filter(L=>!L.participantId),A=(y?.length&&y.length>0?y.length:E?.length??0)&&g?.drawPositions.filter(L=>!m?.includes(L))||[],U=s?Sr(A):A,N=[],D=U.map(()=>{let G=w(y,N)?.participantId;return G&&N.push(G),G}).filter(Boolean),M=c?.filter(L=>S?.includes(L.participantId)).map(L=>L.seedNumber),b=(g?.seedNumbers||[]).filter(L=>!M?.includes(L)),v=c?.filter(L=>b.includes(L.seedNumber)).map(L=>L.participantId),O=d?.seeding?.duplicateSeedNumbers;return{nextSeedBlock:g,unplacedSeedParticipantIds:(O!==void 0?O:!0)?D:v,unplacedSeedNumbers:b,unfilledPositions:U,unplacedSeedAssignments:y};function w(L,G){let k=L.filter(Y=>!G.includes(Y.participantId)),H=Math.min(...k.map(Y=>Sc(Y.seedValue))),W=k.filter(Y=>Sc(Y.seedValue)===H);return Sr(W).pop()}}function xp(t){if(typeof t=="string")return t;if(typeof t=="object")return t.positioning}function Ks({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}=ge({structure:d}),f=nn({provisionalPositioning:t,drawDefinition:r,structure:d}).seedAssignments,g=f.map(P=>P.seedNumber),I=Ic({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(P=>P.participantId===o)?.drawPosition;if(y&&!_p({drawPosition:y,drawDefinition:r,seedBlockInfo:i,structureId:s,seedNumber:a}))return _({result:{error:Gl},context:{assignedDrawPosition:y},info:"invalid seed position",stack:m});g.includes(a)||f.push({seedNumber:a,seedValue:c});let E;return f.forEach(P=>{P.participantId===o&&P.seedNumber!==a&&(P.participantId=void 0),P.seedNumber===a&&(P.participantId=o,!n?.groupSeedingThreshold&&!S&&(P.seedValue=c??a),E=!0)}),E?(Xh({tournamentId:e?.tournamentId,drawDefinition:r,structure:d,eventId:u}),{...C}):_({result:{error:WA},stack:m})}function Sd({inContextTargetMatchUp:t,drawPositionSideIndex:e,teamParticipantId:r,tournamentRecord:n,drawDefinition:o,matchUp:i,event:s}){let a=t?.sides?.[e]?.sideNumber,c=a&&i.sides?.find(d=>d.sideNumber===a),{extension:u}=mt({element:o,name:Co}),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 CS(t){let{sourceMatchUp:e}=t,{targetMatchUp:r,structure:n,matchUpsMap:o,drawPosition:i}=t,s=r.roundNumber>1&&r.roundNumber-1,a=si({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=[Te,be].includes(d);return{pairedPreviousMatchUp:m,pairedPreviousMatchUpIsDoubleExit:l}}function Pv({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(le).filter(Boolean),positionAdded:r,positionAssigned:n}}function bS({structureId:t,matchUpsMap:e,matchUp:r}){let n=r?.roundPosition,o=n%2?1:-1,i=n+o;return{pairedPreviousMatchUp:si({matchUpsMap:e,structureId:t}).find(({roundNumber:c,roundPosition:u})=>c===r?.roundNumber&&u===i)}}function vS({inContextDrawMatchUps:t,sourceMatchUpStatus:e,sourceMatchUpId:r,matchUpsMap:n,matchUp:o}){let i=t.find(a=>a.matchUpId===r),{pairedPreviousMatchUp:s}=bS({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 Td({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 Tc({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=ce({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:wt};let f=a?.drawMatchUps?.find(b=>b.matchUpId===c),g=f?.drawPositions??[],{positionAdded:I,positionAssigned:h,updatedDrawPositions:S}=Pv({drawPositions:g,drawPosition:s}),{positionAssignments:T}=Ct({drawDefinition:o,structure:l}),E=T?.filter(b=>S.includes(b.drawPosition))?.find(({bye:b})=>b),P=f?.matchUpStatus&&[bt,Rt].includes(f.matchUpStatus)&&S.filter(Boolean).length<2;if(i=E&&Nt||i||P&&f.matchUpStatus||f?.matchUpStatus&&[Te,be].includes(f.matchUpStatus)&&f.matchUpStatus||Xt,f&&I){t=ce({inContext:!0,drawDefinition:o,matchUpsMap:a}).matchUps??[];let b=P&&Td({inContextDrawMatchUps:t,drawPosition:s,matchUpId:c})||void 0;f?.matchUpStatusCodes&&vS({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=mr({inContextDrawMatchUps:t,inContextMatchUp:m,drawDefinition:o,matchUpId:c}),{targetMatchUps:{winnerMatchUp:U,loserMatchUp:N,loserTargetDrawPosition:D},targetLinks:{loserTargetLink:M}}=A,R=si({structureId:l.structureId,matchUpsMap:a});if(h&&E){if(U)if([Nt,Te,be].includes(i)){let b=Tc({matchUpId:U.matchUpId,inContextDrawMatchUps:t,tournamentRecord:r,drawDefinition:o,drawPosition:s,matchUpsMap:a});if(b.error)return b}else{let{structureId:b}=U;b!==l.structureId&&console.log("winnerMatchUp in different structure... participant is in different targetDrawPosition")}}else if(U&&m&&!m.feedRound){let{pairedPreviousMatchUpIsDoubleExit:b}=CS({targetMatchUp:f,drawPosition:s,matchUpsMap:a,structure:l});if(b){let v=Tc({matchUpId:U.matchUpId,inContextDrawMatchUps:t,tournamentRecord:r,drawDefinition:o,drawPosition:s,matchUpsMap:a});if(v.error)return v}}if(f?.matchUpType===Wt){let b=t?.find(({matchUpId:F})=>F===f.matchUpId),O=(b?.sides??[]).reduce((F,w,L)=>w.drawPosition===s?L:F,void 0),x=T?.find(F=>F.drawPosition===s)?.participantId;x&&O!==void 0&&Sd({inContextTargetMatchUp:b,drawPositionSideIndex:O,teamParticipantId:x,tournamentRecord:r,drawDefinition:o,matchUp:f})}if(M?.linkCondition===wn&&S.filter(Boolean).length===2&&!E&&R.filter(({drawPositions:O,roundNumber:x})=>x===1&&ke(O,S)).every(({matchUpStatus:O})=>[he,nr].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:ja},context:{drawPosition:s},stack:p})}function OS({inContextDrawMatchUps:t,drawDefinition:e,assignments:r,matchUpsMap:n,structure:o}){let s=cs({drawDefinition:e})?.containedStructures?.[o.structureId]?.map(({structureId:m})=>m)||[];s.push(o?.structureId);let a=r?.map(({drawPosition:m})=>m)||[],c=t?.filter(m=>s.includes(m.structureId)&&jt(m.drawPositions??[],a).length)??[],u=c.map(({matchUpId:m})=>m),p=n?.drawMatchUps?.filter(m=>u.includes(m.matchUpId))??[];return{drawPositions:a,matchUps:p,targetMatchUps:c}}function yd({lineUp:t}){if(!Array.isArray(t))return;let e={};return pt(t.flatMap(({collectionAssignments:n})=>n?.map(({collectionId:o,collectionPosition:i})=>[o,i].join("|"))).filter(Boolean)).forEach(n=>{let[o,i]=n.split("|"),s=parseInt(i),{assignedParticipantIds:a}=Cp({collectionPosition:s,collectionId:o,lineUp:t});a.forEach(c=>{e[c]||(e[c]=[]),e[c].push({collectionId:o,collectionPosition:s})})}),Object.keys(e).map(n=>({participantId:n,collectionAssignments:e[n]}))}function ai(t){return`${t} must be an array`}function Ad({lineUp:t,tieFormat:e}){let r=[];if(!Array.isArray(t))return r.push(ai("lineUp")),{valid:!1,errors:r,error:V};let n=t.every(s=>{if(typeof s!="object")return r.push("lineUp entries must be objects"),!1;let{participantId:a,collectionAssignments:c}=s;return a?typeof a!="string"?(r.push("participantIds must be strings"),!1):Array.isArray(c)?c.every(u=>{if(typeof u!="object")return r.push("collectionAssignments must be objects"),!1;let{collectionPosition:p}=u;return typeof p!="number"?(r.push("collectionPosition must be a number"),!1):!0}):(r.push(ai("collectionAssignments")),!1):(r.push("Missing participantId"),!1)}),o=pt(t.map(St)).length===t.length;return o||r.push("Duplicated participantId(s)"),{valid:n&&o,errors:r,error:r.length?V:void 0}}function Qi({drawDefinition:t,participantId:e,tieFormat:r,lineUp:n}){if(typeof t!="object")return{error:Z};if(typeof e!="string")return{error:ie};let o=Ad({lineUp:n,tieFormat:r});if(!o.valid)return o;let{extension:i}=mt({element:t,name:Co}),s=i?.value||{};return s[e]=yd({lineUp:n}),Ut({element:t,extension:{name:Co,value:s}}),Aa({drawDefinition:t}),{...C}}function yg({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}=OS({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&&Qi({drawDefinition:n,participantId:I,lineUp:[],tieFormat:g})}gt({tournamentId:r?.tournamentId,context:"resetLineUps",eventId:a?.eventId,drawDefinition:n,matchUp:f})}}});return{...C}}function Bn({provisionalPositioning:t,inContextDrawMatchUps:e,isQualifierPosition:r,sourceMatchUpStatus:n,tournamentRecord:o,drawDefinition:i,seedingProfile:s,participantId:a,seedBlockInfo:c,drawPosition:u,matchUpsMap:p,structureId:m,event:d}){let l="assignDrawPosition";if(!a&&!r)return _({result:{error:ie},stack:l});p=p??Me({drawDefinition:i}),e||({matchUps:e}=ce({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:wt};if(pr({structure:g}))return _({result:{error:lr},stack:l});let{seedAssignments:I}=nn({provisionalPositioning:t,drawDefinition:i,structure:g}),S=I?.find(v=>v.participantId===a)?.seedNumber,{appliedPolicies:T}=Tt({tournamentRecord:o,drawDefinition:i,structure:g,event:d});if(S&&!_p({seedNumber:S,appliedPolicies:T,drawDefinition:i,seedBlockInfo:c,drawPosition:u,structureId:m}))return _({result:{error:Gl},context:{drawPosition:u},stack:l});let E=ge({structure:g}).positionAssignments||[],P=E?.find(v=>v.drawPosition===u);if(!P)return _({result:{error:Cs},context:{drawPosition:u},stack:l});if(E?.map(St).includes(a))return _({result:{error:Os},context:{drawPosition:u},stack:l});let{containsParticipant:U,containsBye:N}=b(P);if(N){let v=gc({inContextDrawMatchUps:e,tournamentRecord:o,drawDefinition:i,drawPosition:u,structureId:m,matchUpsMap:p,event:d});if(v.error)return _({result:v,stack:l})}if(U&&P.participantId!==a){let{activeDrawPositions:v}=Na({drawDefinition:i,structureId:m});if(v.includes(u))return _({result:{error:zu},stack:l});yg({assignments:[P],inContextDrawMatchUps:e,tournamentRecord:o,drawDefinition:i,matchUpsMap:p,structure:g})}if(P.participantId=a,r&&(P.qualifier=!0),g.stage===rt&&(!g.stageSequence||g.stageSequence>1)||g.stage&&[qe,fe].includes(g.stage)){let v=g.stage===ct?ct:rt,F=(i.structures?.find(w=>w?.stage===v&&w?.stageSequence===1)?.seedAssignments??[]).find(w=>w.participantId===a);if(F?.participantId){let{participantId:w,seedNumber:L,seedValue:G}=F;Ks({eventId:d?.eventId,provisionalPositioning:t,tournamentRecord:o,drawDefinition:i,seedingProfile:s,participantId:w,seedNumber:L,seedValue:G,structureId:m,event:d})}}if(g.structureType!==Ve)Qk({provisionalPositioning:t,inContextDrawMatchUps:e,sourceMatchUpStatus:n,tournamentRecord:o,drawDefinition:i,drawPosition:u,matchUpsMap:p,structure:g,event:d});else{US({positionAssignments:E,tournamentRecord:o,drawDefinition:i,matchUpsMap:p,structure:g});let{drawPositions:v,matchUps:O,targetMatchUps:x}=OS({assignments:[P],inContextDrawMatchUps:e,drawDefinition:i,matchUpsMap:p,structure:g});if(v&&O?.length===1&&O[0].matchUpType===Wt){let w=(x?.[0].sides??[]).reduce((L,G,k)=>v?.includes(G.drawPosition)?k:L,void 0);Sd({inContextTargetMatchUp:x[0],teamParticipantId:a,matchUp:O[0],drawPositionSideIndex:w,tournamentRecord:o,drawDefinition:i})}}let M=i.entries?.find(v=>v.participantId===a),R=d?.entries?.find(v=>v.participantId===a);return!M&&R&&Id({entryStatus:R.entryStatus,entryStage:g.stage,ignoreStageSpace:!0,drawDefinition:i,participantId:a,event:d}),Oo({tournamentId:o?.tournamentId,drawDefinition:i,structure:g,event:d}),{positionAssignments:E,...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 Qk({provisionalPositioning:t,inContextDrawMatchUps:e,sourceMatchUpStatus:r,tournamentRecord:n,drawDefinition:o,drawPosition:i,matchUpsMap:s,structure:a,event:c}){let u={isCollectionMatchUp:!1},{matchUps:p}=yt({provisionalPositioning:t,matchUpFilters:u,drawDefinition:o,matchUpsMap:s,structure:a,event:c}),{roundMatchUps:m}=Ke({matchUps:p}),{initialRoundNumber:d}=gs({drawPosition:i,matchUps:p}),l=d&&m?.[d].find(f=>f.drawPositions?.includes(i));if(l){let f=Tc({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 Ed(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=Tt({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}=ce({inContext:!0,drawDefinition:i,matchUpsMap:l}),Object.assign(t,{inContextDrawMatchUps:d}));let{positionAssignments:f}=Ct({drawDefinition:i,structureId:c}),g=f?.find(y=>y.drawPosition===a);if(g?.participantId){let y=g.participantId,E=Bn({inContextDrawMatchUps:d,tournamentRecord:o,drawDefinition:i,participantId:s,drawPosition:a,structureId:c,matchUpsMap:l,event:u});return E.success?T({appliedPolicies:m,removedParticipantId:y}):_({result:E,stack:p})}let I=gc({inContextDrawMatchUps:d,tournamentRecord:o,drawDefinition:i,drawPosition:a,structureId:c,matchUpsMap:l,event:u});if(I.error)return _({result:I,stack:p});let h=I.participantId,S=Bn({inContextDrawMatchUps:d,isQualifierPosition:r,tournamentRecord:o,drawDefinition:i,participantId:s,drawPosition:a,structureId:c,matchUpsMap:l,event:u});if(!S.success)return _({result:S,stack:p});return T({appliedPolicies:m,removedParticipantId:h});function T({appliedPolicies:y,removedParticipantId:E}){let{structure:P}=at({drawDefinition:i,structureId:c});Zm({drawPositions:[a],structure:P});let A={[e]:s,name:n,drawPosition:a,structureId:c};return pu({appliedPolicies:y,drawDefinition:i,positionAction:A}),_({context:{removedParticipantId:E},result:{...C},stack:p})}}function Dv({luckyLoserParticipantId:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,structureId:o}){return Ed({positionActionName:"luckyLoserDrawPositionAssignment",participantId:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,structureId:o})}function SP(t){return Dv(t)}function _S({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 xS(t,e){let r=[{drawDefinition:!0,structureId:!0}];Array.isArray(e)&&r.push(...e);let n=et(t,r);if(n.error)return n;let o=at(t);if(o.error)return o;let i=o.structure;if(!pr({structure:i}))return _({result:{error:Zo,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:eo}}function TP(t){let e=xS(t,[{targetRoundNumber:!0,roundNumber:!0,[He]:lb}]);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:V},info:"roundNumbers must be valid rounds"});let a=i>s,c=a?tt(s+1,i+1):tt(i,s),u={};return c.forEach(p=>(n?.[p]??[]).forEach(({matchUpId:m})=>{u[m]=p-(a?1:-1)})),n?.[s]?.forEach(({matchUpId:p})=>u[p]=i),_S({params:t,modMap:u,structure:r}),{...C}}function yP({structurePositionAssignments:t,provisionalPositioning:e,tournamentRecord:r,drawDefinition:n,event:o}){if(!n)return{error:Z};if(!Array.isArray(t))return{error:V};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:wt};let d=Ct({structure:m}).positionAssignments?.map(({drawPosition:I})=>I),l=u?.map(({drawPosition:I})=>I);if(jt(d,l).length!==d?.length)return _({result:{error:V},info:"drawPositions do not match",stack:i});let f=Me({drawDefinition:n}),{matchUps:g}=ce({inContext:!0,drawDefinition:n,matchUpsMap:f});for(let I of u||[]){let{drawPosition:h,participantId:S,bye:T,qualifier:y}=I;if(T){let E=Hr({tournamentRecord:r,drawDefinition:n,drawPosition:h,matchUpsMap:f,structureId:c,structure:m,event:o});if(E?.error)return E}else if(y)u.forEach(E=>{E.drawPosition===h&&(E.qualifier=!0,delete E.participantId,delete E.bye)});else if(S){let E=Bn({provisionalPositioning:e,inContextDrawMatchUps:g,tournamentRecord:r,drawDefinition:n,participantId:S,drawPosition:h,matchUpsMap:f,structureId:c,event:o});if(E?.error)return E}}Oo({tournamentId:r?.tournamentId,drawDefinition:n,structure:m,event:o})}let s=t.map(({structureId:a})=>a);return vt({tournamentId:r?.tournamentId,eventId:o?.eventId,drawDefinition:n,structureIds:s}),{...C}}function AP(t){let e=xS(t,[{roundNumbers:!0,[He]:Be,[er]: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:V,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]})),_S({params:t,modMap:i,structure:r}),{...C}}function EP({alternateParticipantId:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,structureId:o,event:i}){return Ed({positionActionName:"alternateDrawPositionAssignment",participantIdAttributeName:"alternateParticipantid",participantId:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,structureId:o,event:i})}function wS({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 Ag({withStageGrouping:t,stageSequences:e,stageSequence:r,roundTarget:n,stages:o,event:i,stage:s}){if(!i)return{error:Ot};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 LS({withStageGrouping:t,tournamentRecord:e,stageSequences:r,stageSequence:n,roundTarget:o,stages:i,stage:s}){if(!e)return{error:$};let a={},c=[];for(let u of e.events||[]){let{structures:p,stageStructures:m}=Ag({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 Eo(t){if(!t?.drawDefinition)return!1;let e=yu(t),r=e?.includesTeamMatchUps,{completedMatchUps:n,pendingMatchUps:o,upcomingMatchUps:i}=e||{};return r&&(n=n?.filter(({matchUpType:a})=>a===Wt),o=o?.filter(({matchUpType:a})=>a===Wt),i=i?.filter(({matchUpType:a})=>a===Wt)),!!(n?.length&&!o?.length&&!i?.length)}function FS(t){let{drawDefinition:e,structureId:r}=t;if(!e)return{error:Z};let{playoffStructures:n}=wS({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)=>!!((Ct({structure:u}).positionAssignments??[])?.filter(d=>(d.participantId&&i++,d?.bye??d?.participantId)).length&&c),!!n.length)||i===o}function kS({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=kS({accessors:s,significantCharacters:t,value:c});n.push(...u)});else if(r=r[o],s.length){let a=kS({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 Nv({targetParticipantIds:t,policyAttributes:e,idCollections:r,participants:n}){if(!Array.isArray(e))return{error:BI};if(!Array.isArray(n))return{error:Ka};let o={};return t.forEach(i=>{let s=n.find(c=>c.participantId===i),{values:a}=UP({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 UP({policyAttributes:t,idCollections:e,participants:r,participant:n}){if(!Array.isArray(t))return{error:BI};if(!n)return{error:Fi};let o=[];return t.forEach(s=>{let{directive:a,groupings:c,key:u,significantCharacters:p}=s||{};if(u){let m=u.split(".");o.push(...kS({significantCharacters:p,value:n,accessors:m}))}else if(a){let m=s?.includeIds,d=(e?.[a]||[]).filter(l=>!m||m.includes(l));d?.length&&r?.length&&d.forEach(l=>{let f=r.find(g=>g.participantId===l);if(f?.individualParticipantIds?.includes(n.participantId)){let g=f?.participantId;o.push(g)}})}else c&&Object.keys(c).forEach(m=>{c[m].includes(n.participantId)&&o.push(m)})}),{values:pt(o)}}function PP({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}=UP({participants:e,policyAttributes:r,idCollections:n,participant:s});return{...i,values:a}})}function Rv({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 Cv(t){let{unfilledPositions:e,chunkedDrawPositions:r}=t,n=Rv(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=Mv(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=Mv(c);return!s.includes(u)}}}function bv(t){let{unfilledPositions:e,chunkedDrawPositions:r}=t,n=Rv(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 Mv(t){return Number(t%2?t+1:t-1)}function vv({allGroups:t,participantId:e}){return Object.keys(t).filter(r=>t[r].includes(e))}function Ov({selectedParticipantGroups:t,participantIdGroups:e,positionAssignments:r,drawPositionChunks:n,unfilledPositions:o,isRoundRobin:i}){let s=n.map(a=>i?bv({groupsToAvoid:t,chunkedDrawPositions:a,participantIdGroups:e,positionAssignments:r,unfilledPositions:o}):Cv({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 GS({positionAssignments:t,participantIds:e}){let r=t.map(n=>n.participantId);return e.filter(n=>!r.includes(n))}function _v({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 xv({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 wv({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=GS({positionAssignments:t,participantIds:e}),m=xv({positionAssignments:t,drawPositionGroups:o}),{participantId:d,groupKey:l}=_v({targetParticipantIds:p,useSpecifiedGroupKey:u,allGroups:s,groupKey:a}),f=vv({participantId:d,allGroups:s}),g=Ov({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],E=i&&T?T:y,P=i?y:T,A=E?.length&&E||P?.length&&P,U;if(A?.length){let N=Zr(A);U=Zr(N)}else{let N=Zr(I[0]);U=Zr(N)}return{newGroupKey:l,selectedParticipantId:d,targetDrawPosition:U}}function Ud({isRoundRobin:t,groupedParticipants:e}){let r=[];return t?e.forEach(n=>{let o=n.map(a=>a.drawPosition),i=Ig({drawPositions:o}).uniqueMatchUpGroupings??[],s=Object.assign({},...n.map(a=>({[a.drawPosition]:a})));i.forEach(a=>{ke(s[a[0]].values||[],s[a[1]].values||[])&&(r.push(a),n.conflict=!0)})}):e.forEach(n=>{ke(n[0]?.values||[],n[1]?.values||[])&&(r.push(n),n.conflict=!0)}),r}function Lv({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=Ud({isRoundRobin:o,groupedParticipants:[[c,l]]}),h=[t.find(T=>T.drawPosition===m),l],S=Ud({isRoundRobin:o,groupedParticipants:[h]});return!g.length&&!S.length});if(p.length)return{drawPosition:c.drawPosition,possibleDrawPositions:p}}).filter(Boolean)}).flat(1)}function DP(t){let{initialPositionAssignments:e,participantsWithGroupings:r,opponentsToPlaceCount:n,unseededByePositions:o,drawPositionGroups:i,policyAttributes:s,idCollections:a,allGroups:c}=t,u=[],p,m=Math.min(...(i||[]).map(T=>T?.length).filter(Boolean)),d=m>2,l=J(e,!1,!0).filter(T=>!T.qualifier),f=e.filter(T=>!T.participantId&&(!T.bye||o?.includes(T.drawPosition))).map(T=>T.drawPosition);tt(0,n).forEach(()=>{let{newGroupKey:T,selectedParticipantId:y,targetDrawPosition:E}=wv({...t,candidatePositionAssignments:l,allGroups:c,groupKey:p});p=T,l.forEach(P=>{P.drawPosition===E&&(P.participantId=y)})});let g=PP({candidatePositionAssignments:l,participantsWithGroupings:r,policyAttributes:s,idCollections:a}),I=Ee(g,m),h=Ud({groupedParticipants:I,isRoundRobin:d}),S=0;for(;S<20&&h.length;){let T=Lv({positionedParticipants:g,potentialDrawPositions:f,avoidanceConflicts:h,drawPositionGroups:i,isRoundRobin:d});if(T.length){let y=Xk({candidatePositionAssignments:l,swapOptions:T});y.error&&console.log({result:y}),g=PP({candidatePositionAssignments:l,participantsWithGroupings:r,policyAttributes:s,idCollections:a}),I=Ee(g,m),h=Ud({groupedParticipants:I,isRoundRobin:d}),S++}else S=20}return l.forEach(T=>{if(T.bye&&T.participantId){let y=kI;u.push(y)}if(T.qualifier&&T.participantId){let y=kI;u.push(y)}}),{positionAssignments:l,conflicts:h.length,groupedParticipants:I,errors:u}}function Xk({candidatePositionAssignments:t,swapOptions:e}){let r=Zr(e);if(!r)return{error:{message:"No swap options"}};let n=r.drawPosition,o=Zr(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 Fv({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:eE};let{candidatesCount:l=1,policyAttributes:f,targetDivisions:g}=p,{roundsToSeparate:I}=p,h="randomUnseededSeparation",{structure:S}=at({drawDefinition:i,structureId:u}),{matchUps:T}=yt({provisionalPositioning:t,matchUpsMap:c,structure:S,event:d});if(g&&_n(g)&&!I){let k=dC(g)||0,H=T.reduce((W,q)=>q.roundNumber>W?q.roundNumber:W,0);I=H<k?1:H-k+1}let{positionAssignments:y}=ge({structure:S}),E=fu({participantsProfile:{convertExtensions:!0},deepCopy:!1,participants:a}).participantsWithGroupings,P=y?.filter(k=>!k.participantId),A=y?.map(k=>k.drawPosition),U=S?.structureType===Ve,N=U?{structure:S,matchUps:T,allDrawPositions:A,roundsToSeparate:I}:{matchUps:T,allDrawPositions:A,roundsToSeparate:I},{drawPositionGroups:D,drawPositionChunks:M}=U?Jk(N):Zk(N),R={groupParticipants:a.filter(k=>k.participantType===zr).map(k=>k.participantId),teamParticipants:a.filter(k=>k.participantType===Ft).map(k=>k.participantId),pairParticipants:a.filter(k=>k.participantType===ft).map(k=>k.participantId)},b=Nv({targetParticipantIds:e,policyAttributes:f,idCollections:R,participants:a});if(b.error)return _({result:b,stack:h});let v=Object.assign({},...e.map(k=>{let H=Object.keys(b).filter(W=>(b[W]??[]).includes(k));return{[k]:H}})),O=GS({participantIds:e,positionAssignments:y});if(O.length>(P?.length||0))return{error:ef};let x,F=O.length,w=tt(0,l).map(()=>DP({initialPositionAssignments:y,participantsWithGroupings:E,unseededParticipantIds:e,opponentsToPlaceCount:F,pairedPriority:!1,unseededByePositions:n,participantIdGroups:v,drawPositionChunks:M,drawPositionGroups:D,policyAttributes:f,idCollections:R,allGroups:b,drawSize:m}));if(x=w.reduce((k,H)=>!k||(H.conflicts||0)<(k.conflicts||0)?H:k,void 0),!x||x.conflicts){let k=tt(0,l).map(()=>DP({initialPositionAssignments:y,participantsWithGroupings:E,unseededParticipantIds:e,opponentsToPlaceCount:F,pairedPriority:!0,unseededByePositions:n,participantIdGroups:v,drawPositionChunks:M,drawPositionGroups:D,policyAttributes:f,idCollections:R,allGroups:b,drawSize:m}));x=w.concat(...k).filter(W=>!W.errors?.length).reduce((W,q)=>!W||(q.conflicts||0)<(W.conflicts||0)?q:W,void 0)}if(!x)return{error:tp};let L=(Ct({structure:S})?.positionAssignments??[]).filter(k=>k.participantId).map(k=>k.participantId),G=x.positionAssignments.filter(k=>!L.includes(k.participantId));for(let k of G)if(k.bye){let H=Hr({tournamentRecord:o,drawDefinition:i,seedBlockInfo:s,structureId:u,matchUpsMap:c,event:d,...k});if(H.error)return _({result:H,stack:h})}else if(k.participantId){let H=Bn({automaticPlacement:!0,inContextDrawMatchUps:r,tournamentRecord:o,drawDefinition:i,seedBlockInfo:s,structureId:u,matchUpsMap:c,event:d,...k});if(H.error)return _({result:H,stack:h,context:{assignment:k}})}return{...C}}function Jk(t){let{structure:{structures:e}}=t,r=e.map(n=>n.positionAssignments.map(o=>o.drawPosition));return{drawPositionGroups:r,drawPositionChunks:[r]}}function Zk({allDrawPositions:t,roundsToSeparate:e,matchUps:r}){let n=r.filter(d=>d.roundNumber===1).map(d=>d.drawPositions),o=n.flat().sort(le),i=Math.max(...o),s=t.filter(d=>d>i),a=o.length,u=tt(a===2?1:2,a).filter(d=>d===Am(d)),m=u.slice(0,e||u.length).reverse().map(d=>Ee(o,d));return s.length&&console.log({fedDrawPositions:s}),{drawPositionGroups:n,drawPositionChunks:m}}function kv({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}=ge({structure:p}),{seedAssignments:g}=nn({provisionalPositioning:t,drawDefinition:i,structure:p}),I=g?.map(M=>M.participantId).filter(Boolean),{stage:h,stageSequence:S}=p,T=h===ct?mt({element:p,name:Mn})?.extension?.value:void 0,E=Pi({provisionalPositioning:t,drawDefinition:i,stageSequence:S,entryStatuses:oi,structureId:u,roundTarget:T,stage:h}),A=E.filter(M=>!I?.includes(M.participantId)).map(M=>M.participantId),U=f?.filter(M=>!M.participantId&&!M.bye&&!M.qualifier).map(M=>M.drawPosition);if(!n&&A.length>(U?.length||0))return _({result:{error:ef},context:{unseededParticipantsCount:A.length,unfilledDrawPositionsCount:U?.length},stack:l});let{appliedPolicies:N}=Tt({tournamentRecord:o,drawDefinition:i,event:d}),D=N?.[ou];if(p.stage===fe){let M=E.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?Fv({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:E}):tG({provisionalPositioning:t,unseededParticipantIds:A,inContextDrawMatchUps:e,unfilledDrawPositions:U,multipleStructures:n,tournamentRecord:o,drawDefinition:i,seedBlockInfo:s,structureId:u,matchUpsMap:c,drawSize:m,event:d})}function tG({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?Sr(n):n.reverse();for(let l of e){let f=d.pop();if(!o||f){let g=Bn({provisionalPositioning:t,inContextDrawMatchUps:r,tournamentRecord:i,drawDefinition:s,seedBlockInfo:a,participantId:l,drawPosition:f,matchUpsMap:c,structureId:u,event:m});if(g?.error&&console.log("!!!!!",{result:g}),g?.error)return _({result:g,stack:"randomUnseededDistribution"})}}return{...C}}function Gv(t){let e=t.structure??at(t).structure,r="positionQualifiers",n=[];if(e.stage===qe)return _({result:{error:xi},stack:r});let{unplacedRoundQualifierCounts:o,positionAssignments:i,roundDrawPositions:s}=eG(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:tf},context:{unfilledDrawPositions:c},stack:r});tt(0,o[a]).forEach(()=>{let u=Zr(c);n.push(u),i?.forEach(p=>{p.drawPosition===u&&(p.qualifier=!0,delete p.participantId,delete p.bye)})})}return{...C,qualifierDrawPositions:n}}function eG({drawDefinition:t,structure:e,structureId:r}){e||({structure:e}=at({drawDefinition:t,structureId:r})),r||({structureId:r}=e);let{positionAssignments:n}=ge({structure:e}),{stage:o,stageSequence:i}=e,{qualifiersCount:s,roundQualifiersCounts:a}=hs({drawDefinition:t,stageSequence:i,structureId:r,stage:o}),u=(a?Object.keys(a):[]).map(h=>dt(h)),{matchUps:p}=yt({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 NP({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=Tt({drawDefinition:i}).appliedPolicies),!o){let h=d&&ys({provisionalPositioning:t,appliedPolicies:n,drawDefinition:i,seedingProfile:s,structure:d});h?.error&&g.push(h.error),o=h?.validSeedBlocks}return u=u??o?.length??0,tt(0,u).forEach(()=>{if(I<(u||0)){let h=rG({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 rG({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}=RS({provisionalPositioning:t,randomize:!0,drawDefinition:n,seedingProfile:o,seedBlockInfo:i,structureId:a,event:u}),{appliedPolicies:d}=Tt({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:bs};f.push(I);let h=Bn({provisionalPositioning:t,inContextDrawMatchUps:e,tournamentRecord:r,drawDefinition:n,seedingProfile:o,participantId:g,seedBlockInfo:i,drawPosition:I,matchUpsMap:c,structureId:a,event:u});if(!h.success)return h}return{...C,seedPositions:f}}function Vv({provisionalPositioning:t,drawDefinition:e,structure:r}){let{positionAssignments:n}=ge({structure:r}),{seedAssignments:o}=nn({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 Bv({orderedSortedFirstRoundSeededDrawPositions:t,validSeedBlocks:e,byesToPlace:r}){let n=[];e.forEach(i=>nG(i,r,n,t));let o=n.map(i=>Array.isArray(i)?Sr(i):i).flat(1/0);return RI(r)&&e.map(s=>s.seedNumbers[0]).includes(r)?t:o}function nG(t,e,r,n){if(e-r.length>t.drawPositions.length)r.push(...t.drawPositions);else{let i=MP(Ee(t.drawPositions,2));oG(i,r,n)}}function oG(t,e,r){let n,o=r[e.length];for(;n=Eg(t,o);)e.push(n),o=r[e.length]}function Eg(t,e){return Array.isArray(t)&&t.length!==2?t.pop():Array.isArray(t[0])?sG(t,e):iG(t,e)}function iG(t,e){return t.includes(e)?t.indexOf(e)?t.pop():t.shift():Math.round(Math.random())?t.pop():t.shift()}function sG(t,e){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 Eg(e?o:t[Math.round(Math.random())],e)}return r<n?Eg(t[1],e):Eg(t[0],e)}function MP(t){let e=Math.floor(t.length/2);return t.length>2?[MP(t.slice(0,e)),MP(t.slice(e))]:t}function Wv({provisionalPositioning:t,relevantMatchUps:e,appliedPolicies:r,drawDefinition:n,seedingProfile:o,seedBlockInfo:i,byesToPlace:s,structure:a}){i||(i=ys({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=Vv({provisionalPositioning:t,drawDefinition:n,structure:a})??[],l=pt([].concat(...e.map(E=>E.drawPositions))),f=d.filter(E=>l.includes(E.drawPosition)),g=(E,P)=>Sc(E.seedValue)-Sc(P.seedValue),h=m.reduce((E,P)=>{let A=f.filter(U=>P.drawPositions?.includes(U.drawPosition)).sort(g);return E.concat(...A)},[]).map(E=>E.drawPosition),S=Bv({orderedSortedFirstRoundSeededDrawPositions:h,validSeedBlocks:m,byesToPlace:s}),T=Hv({orderedSeedDrawPositions:h,relevantMatchUps:e}).slice(0,s),y=Hv({orderedSeedDrawPositions:S,relevantMatchUps:e}).slice(0,s);return{strictSeedOrderByePositions:T,blockSeedOrderByePositions:y,isLuckyStructure:u,positionedSeeds:d,isContainer:p,isFeedIn:c}}function Hv({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 jv({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}=ge({structure:s}),m=p?.filter(O=>O.participantId).map(O=>O.drawPosition),d={isCollectionMatchUp:!1},{matchUps:l,roundMatchUps:f}=yt({provisionalPositioning:t,matchUpFilters:d,structure:s}),g=f?.[1]||[],I=s.structureType===Ve?l:g,h=pt([].concat(...I.map(O=>O.drawPositions))),S=Math.min(...h)-1,T=m?.filter(O=>h.includes(O)),y=O=>{let x=Math.ceil(O.length/2),F=[O.slice(0,x),O.slice(x)],w=F.map(B=>[].concat(...B.flat(1/0)).length),L=Math.min(...w.flat(1/0)),G=Math.max(...w.flat(1/0)),k=w.indexOf(G),H=L!==G,W=Sr(F),[q,Y]=!L||H?[F[k],F[1-k]]:[W[0],W[1]];return{greaterHalf:q,lesserHalf:Y}},E=O=>{let{greaterHalf:x,lesserHalf:F}=y(O),{greaterHalf:w,lesserHalf:L}=y(x),k=Sr(w.flat(1/0)).pop(),H=w.flat().filter(q=>q!==k);return{newlyFilteredChunks:[...F,...L,H],drawPosition:k}},P=O=>!e.includes(O),A=O=>!T?.includes(O),U=O=>{let F=Ee(O.sort(le),Math.ceil(O.length/4)).map(G=>G.filter(A)),w=[].concat(...F.flat(1/0)).length,L=[];for(let G=0;G<w;G++){let{newlyFilteredChunks:k,drawPosition:H}=E(F);L.push(H),F=k}return L},{validSeedBlocks:N}=ys({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}=Sg({cluster:xp(c)===Qc,participantsCount:O});M=x.map(w=>w.map(L=>L+S)).map(U).filter(w=>w.length)}else u?M=D?.map(O=>O.filter(A)):M=D?.map(U).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((w,L)=>L!==O?L:w,void 0):x,void 0),v=M.map(O=>O.map(b)).flat(1/0).filter(A).filter(P).filter(Boolean);if(u&&!s.structures){let O=i%4,x=v.slice(0,O),F=f[s.roundLimit]?.length,w=Ee(v.slice(O),F).map(Sr).flat();v=x.concat(w)}return{unseededByePositions:v}}function Yv({provisionalPositioning:t,drawDefinition:e,matchUpsMap:r,structure:n,event:o}){let i={isCollectionMatchUp:!1},{matchUps:s,roundMatchUps:a}=yt({afterRecoveryTimes:!1,provisionalPositioning:t,drawDefinition:e,matchUpFilters:i,matchUpsMap:r,structure:n,event:o}),c=a?.[1]||[],u=n?.structureType===Ve,p=u?s:c,m=u?n?.structures?.length||0:s.length,{structureId:d,stage:l,stageSequence:f}=n,g=Pi({entryStatuses:Qr,provisionalPositioning:t,drawDefinition:e,stageSequence:f,structureId:d,stage:l}),{qualifiersCount:I}=hs({provisionalPositioning:t,drawDefinition:e,stageSequence:f,structureId:d,stage:l}),h=g.length+I,{positionAssignments:S,unassignedPositions:T}=ge({structure:n}),y=T?.map(D=>D.drawPosition),E=S?.filter(D=>D.bye).length,P=S?.filter(D=>D.bye).map(D=>D.drawPosition),A=p.map(D=>D.drawPositions).filter(D=>D?.reduce((M,R)=>!P?.includes(R)&&M,!0)).flat(1/0).filter(D=>y?.includes(D)),U=S?.length,N=U?U-h:0;return N>m&&n.stageSequence===1&&n.stage!==qe&&(N=m),{placedByes:E,byesCount:N,relevantMatchUps:p,placedByePositions:P,roundMatchUps:a,positionsToAvoidDoubleBye:A}}function RP({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}=Yv({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}=Wv({provisionalPositioning:t,relevantMatchUps:g,appliedPolicies:r,drawDefinition:n,seedingProfile:i,seedBlockInfo:o,byesToPlace:I,structure:c}),E=c?.structureType&&[Ve,pp].includes(c.structureType)&&r?.seeding?.containerByesIgnoreSeeding,P=d&&S?.length?S:h,{unseededByePositions:A}=jv({provisionalPositioning:t,seedOrderByePositions:P,isLuckyStructure:T,appliedPolicies:r,drawDefinition:n,seedLimit:u,structure:c,isFeedIn:y}),U=R=>R%2,N=(R,b)=>(R||[]).every(v=>U(v)?b!==v+1:b!==v-1),D=[].concat(...P);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=[])}E&&(D=Sr(D),Pr({ignoreSeededByes:E})&&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 yc(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||(BE(),e=J(e,!1,!0));let I=x=>(r||mf(),_({result:x,stack:"automatedPositioning"})),h=x=>(r||mf(),x),S=at({drawDefinition:e,structureId:u});if(S.error)return I(S);let T=S.structure;if(!T)return{error:wt};let y=t.appliedPolicies||Tt({drawDefinition:e,structure:T,event:f})?.appliedPolicies,{qualifiersCount:E}=hs({stageSequence:T.stageSequence,provisionalPositioning:n,stage:T.stage,drawDefinition:e,structureId:u}),P=oi;if(!Pi({stageSequence:T.stageSequence,provisionalPositioning:n,stage:T.stage,placementGroup:a,drawDefinition:e,entryStatuses:P,structureId:u})?.length&&!E)return h({...C});let U=t.matchUpsMap??Me({drawDefinition:e}),N=t.inContextDrawMatchUps??ce({inContext:!0,drawDefinition:e,matchUpsMap:U})?.matchUps,D=[],M=ys({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(xp(T.seedingProfile||c)===li){let x=i?RP({provisionalPositioning:n,tournamentRecord:s,appliedPolicies:y,drawDefinition:e,seedBlockInfo:M,matchUpsMap:U,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=NP({seedingProfile:F,provisionalPositioning:n,inContextDrawMatchUps:N,tournamentRecord:s,appliedPolicies:y,validSeedBlocks:R,drawDefinition:e,seedBlockInfo:M,participants:b,matchUpsMap:U,structure:T,event:f}),x.error)return I(x);g.push({seedPositions:x.seedPositions,action:"positionSeedBlocks"})}else{if(d!==Vi){let F=T.seedingProfile?{positioning:T.seedingProfile}:c,w=NP({seedingProfile:F,provisionalPositioning:n,inContextDrawMatchUps:N,tournamentRecord:s,appliedPolicies:y,validSeedBlocks:R,drawDefinition:e,seedBlockInfo:M,participants:b,matchUpsMap:U,structure:T,event:f});if(w.error)return I(w);g.push({action:"positionSeedBlocks",seedPositions:w.seedPositions})}let x=i?RP({provisionalPositioning:n,tournamentRecord:s,appliedPolicies:y,drawDefinition:e,seedBlockInfo:M,matchUpsMap:U,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=Gv({inContextDrawMatchUps:N,tournamentRecord:s,appliedPolicies:y,validSeedBlocks:R,drawDefinition:e,seedBlockInfo:M,participants:b,matchUpsMap:U,structure:T});if(x.error||(x.conflicts&&(v.qualifierConflicts=x.conflicts),g.push({action:"positionQualifiers",qualifierDrawPositions:x.qualifierDrawPositions}),x=kv({provisionalPositioning:n,inContextDrawMatchUps:N,unseededByePositions:D,multipleStructures:o,tournamentRecord:s,drawDefinition:e,seedBlockInfo:M,participants:b,matchUpsMap:U,structureId:u,structure:T,drawSize:l,event:f}),x.error))return I(x);x.conflicts&&(v.unseededConflicts=x.conflicts),g.push({action:"positionUnseededParticipants"})}let{positionAssignments:O}=Ct({drawDefinition:e,structure:T});return vt({drawDefinition:e,structureIds:[u]}),r||mf(),{positionAssignments:O,conflicts:v,...C,positioningReport:g}}function zs(t){let{applyPositioning:e=!0,provisionalPositioning:r,tournamentRecord:n,drawDefinition:o,seedingProfile:i,structureId:s,placeByes:a,seedsOnly:c}=t;if(!o)return{error:Cr};if(!Eo({drawDefinition:o,structureId:s})&&!r)return{error:kl};let p=wS({drawDefinition:o,structureId:s}).playoffStructures?.sort((l,f)=>Ff(l)-Ff(f)),m=[],d=[];if(p)for(let l of p){let{structureId:f}=l,g=yc({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 CP({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:wt};if(!(!t||Zt(i)||i===void 0||i===""||typeof i=="string"&&i.split("-").every(l=>Zt(l)&&dt(l)>0)))return{error:V};let{seedAssignments:p}=nn({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 Xh({tournamentId:e?.tournamentId,eventId:s?.eventId,drawDefinition:r,structure:c}),{...C}}function Ug({qualifyingParticipantId:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,structureId:o}){return Ed({positionActionName:"qualifierDrawPositionAssignment",participantId:t,isQualifierPosition:!0,tournamentRecord:e,drawDefinition:r,drawPosition:n,structureId:o})}function Du({targetRoundNumber:t,finishingPosition:e,drawDefinition:r,structureId:n,linkType:o}){let{links:i}=js({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}}var qv=(t,e)=>{let r=[...new Set(e.slice(0,t.length))],n=[...r].sort((a,c)=>a-c),o=new Set,i=[];r.forEach(a=>{let c=t.indexOf(a);if(c!==-1&&!o.has(c))i.push(c),o.add(c);else{let u=n.indexOf(a),p=t.findIndex((m,d)=>!o.has(d));for(;o.has(p)&&p===-1&&o.size<t.length;)p=t.findIndex((m,d)=>!o.has(d)&&d>p);i.push(u),o.add(u)}});let s=t.filter((a,c)=>!o.has(c));return[...i,...s]};function bP({targetRoundNumber:t=1,tournamentRecord:e,drawDefinition:r,event:n,randomList:o}){let i=et({drawDefinition:r,event:n,tournamentRecord:e},[{[Ce]:!0,[so]:!0,[ne]:!0}]);if(i.error)return i;let s=[],a=[],c=r.structures?.find(S=>S.stage===rt&&S.stageSequence===1);if(!c)return _({result:{error:Wl}});let m=(Tt({tournamentRecord:e,drawDefinition:r,structure:c,event:n}).appliedPolicies??{})[zn]?.requireCompletedStructures,{qualifierPositions:d,positionAssignments:l}=ge({structure:c});if(!d.length)return _({result:{error:tf}});let f=tt(0,d.length);o&&(f=qv(f,o));let g=l.map(S=>S.participantId).filter(Boolean),{relevantLinks:I}=Du({structureId:c.structureId,targetRoundNumber:t,linkType:Kn,drawDefinition:r})||{},{relevantLinks:h}=Du({structureId:c.structureId,targetRoundNumber:t,linkType:xn,drawDefinition:r})||{};for(let S of I){let T=r.structures?.find(E=>E.structureId===S.source.structureId);if(T?.stage!==ct)continue;let y=Eo({structureId:S.source.structureId,drawDefinition:r});if(!m||y){let E=T.qualifyingRoundNumber,{matchUps:P}=yt({matchUpFilters:{...E&&{roundNumbers:[E]},isCollectionMatchUp:!1,hasWinningSide:!0},afterRecoveryTimes:!1,inContext:!0,structure:T});for(let A of P){let U=A.matchUpStatus===Nt&&A.sides?.find(({participantId:D})=>D),N=A.sides.find(D=>D?.sideNumber===A.winningSide);if(N||U){let{participantId:D}=N||U||{};D&&!g.includes(D)&&a.push(D)}}}}for(let S of h){let T=r?.structures?.find(E=>E.structureId===S.source.structureId);if(T?.stage!==ct)continue;if(Eo({structureId:S.source.structureId,drawDefinition:r})){let{positionAssignments:E}=Ct({structure:T}),P=E?.map(A=>{let U=A.participantId,N=mt({element:A,name:bo}).extension?.value;return N?{participantId:U,groupOrder:N?.groupOrder}:{}}).filter(({groupOrder:A,participantId:U})=>A===1&&!g.includes(U)).map(({participantId:A})=>A)??[];P&&a.push(...P)}}return a.length?(f.forEach((S,T)=>{let y=a[T],E=d[S].drawPosition;y&&Ug({qualifyingParticipantId:y,structureId:c.structureId,drawPosition:E,tournamentRecord:e,drawDefinition:r})?.success&&s.push({participantId:y,drawPosition:E})}),_({result:nt({...C,assignedParticipants:s})})):_({result:{error:dE}})}function vP({drawDefinition:t,orderMap:e}){return t?((typeof e!="object"||!Object.values(e).every(r=>It(r)))&&_({result:{error:V},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)=>Ha(r.structureOrder)-Ha(n.structureOrder)),{...C}):{error:Z}}function Nu({drawDefinition:t}){let e=t.structures??[],r=t.links??[],n=new Map,o=I=>{let h=n.get(I)||n.set(I,{drawSources:[],drawTargets:[],progeny:[],sources:[],targets:[]})&&n.get(I);if(h&&!h?.stage){let S=e.find(T=>T.structureId===I);h.stage=S?.stage}return h},i={},s={},a=r.map(I=>{let h=I.source.structureId,S=I.target.structureId,T=o(h),y=o(S);return[fi,En,mp,li].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]=pt([...i[S]||[],h]).filter(Boolean),[I.source.structureId,I.target.structureId]});for(let I of n.keys()){let h=n.get(I);if(h){let S=h.targets??[];for(;S.length;){let T=S.pop(),y=T&&n[T];y?.targets?.length?S.push(...y.targets):y&&(h.rootStage=y.stage)}if(h.rootStage||(h.rootStage=h.stage),!h.targets?.length){let T=h.sources??[];for(;T.length;){let y=T.pop(),E=y&&n[y];if(E?.sources?.length){for(let P of E.sources)h.progeny?.includes(P)||h.progeny?.push(P);T.push(...E.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(),E=y?n.get(y):void 0;E?.drawTargets?.length&&S.push(E.drawTargets[0])}h.distanceFromMain=T,T>c&&(c=T)}}let u=a.length;tt(0,Math.ceil(u/2)).forEach(()=>{a=tt(0,u).map(I=>{let h=a[I],S=a.reduce((T,y)=>ke(h,y)?T.concat(...y):T,[])||[];return pt(h.concat(...S))})});let p=a[0],m=(I,h)=>jt(I,h).length===I.length,d=a.slice(1).reduce((I,h)=>I&&m(h,p),!0),l=[p].filter(Boolean),f=[p].filter(Boolean);e.forEach(I=>{let{structureId:h,stage:S}=I;l.find(y=>y.includes(h))||(l.push([h]),S!==$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 VS({drawDefinition:t}){let{maxQualifyingDepth:e,structureProfiles:r}=Nu({drawDefinition:t});for(let n of t.structures){let o=r[n.structureId];o.distanceFromMain&&(n.stageSequence=e+1-o.distanceFromMain)}return{...C}}function Pg(t){let e=et(t,[{[ne]:!0,[Ce]:!0}]);if(e.error)return e;let{tournamentRecord:r,drawDefinition:n,structure:o,link:i}=t;return aG({tournamentId:r.tournamentId,drawDefinition:n,structure:o,link:i})}function aG(t){let e=et(t,[{[Ce]:!0,[fp]:!0},{link:!0,[He]:Kr,[OA]:Bl}]);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),VS({drawDefinition:r});let u=yt({structure:o})?.matchUps||[];return vo({drawDefinition:r,tournamentId:n,matchUps:u,eventId:i}),vt({drawDefinition:r,structureIds:[o.structureId]}),{...C}}function OP({drawDefinition:t,structureDetails:e}){if(!Array.isArray(e))return{error:V};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 Dg({drawDefinition:t,timeItem:e}){if(!t)return{error:Cr};if(!e)return{error:of};let r=e&&Object.keys(e),n=["itemType","itemValue"];if(!(n.filter(s=>r.includes(s)).length===n.length))return{error:nf};t.timeItems||(t.timeItems=[]);let i=new Date().toISOString();return Object.assign(e,{createdAt:i}),t.timeItems.push(e),Aa({drawDefinition:t}),{...C}}function _P(t){let{tournamentRecord:e,drawDefinition:r,structureId:n,event:o}=t,i=et(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:wt};let c=s.find(({stage:h,stageSequence:S})=>h===rt&&S===1),u=n===c?.structureId,p=s.filter(({stage:h})=>h===ct).map(Br("structureId"));if(u&&!p.length)return{error:_A};let m=p.includes(n),d=cG({isQualifyingStructure:m,structure:a,...t});if(d?.error)return d;let{structureIdsToRemove:l,relatedStructureIdsMap:f}=pG({qualifyingStructureIds:p,isQualifyingStructure:m,isMainStageSequence1:u,mainStageSequence1:c,drawDefinition:r,structureId:n}),{removedMatchUpIds:g,removedStructureIds:I}=mG({relatedStructureIdsMap:f,qualifyingStructureIds:p,isMainStageSequence1:u,mainStageSequence1:c,drawDefinition:r,structureIdsToRemove:l,structureId:n});if(uG({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&&VS({drawDefinition:r}),Rn({tournamentId:e?.tournamentId,matchUpIds:g,action:"removeStructure",eventId:o?.eventId,drawDefinition:r}),vt({drawDefinition:r,eventId:o?.eventId}),{...C,removedMatchUpIds:g,removedStructureIds:I}}function cG({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(ce({matchUpFilters:{structureIds:a},drawDefinition:r}).matchUps?.some(({score:p})=>Ie({score:p}))){let p=Tt({tournamentRecord:e,drawDefinition:r,structure:o,event:i})?.appliedPolicies;if(!(s??p?.[tn]?.allowDeletionWithScoresPresent?.structures))return{error:Xa}}return{...C}}function uG({removedMatchUpIds:t,drawDefinition:e}){let{matchUps:r}=ce({drawDefinition:e});r?.forEach(n=>{n.winnerMatchUpId&&t.includes(n.winnerMatchUpId)&&delete n.winnerMatchUpId,n.loserMatchUpId&&t.includes(n.loserMatchUpId)&&delete n.loserMatchUpId})}function pG({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 mG({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(...fG({idBeingRemoved:u,drawDefinition:o}));let p=lG({qualifyingStructureIds:e,isMainStageSequence1:r,idBeingRemoved:u,drawDefinition:o,structureId:s});a.push(...p.removedStructureIds);let m=dG({relatedStructureIdsMap:t,mainStageSequence1:n,idBeingRemoved:u,structureId:s});m?.length&&i.push(...m)}return{removedMatchUpIds:c,removedStructureIds:a}}function dG({idBeingRemoved:t,relatedStructureIdsMap:e,mainStageSequence1:r,structureId:n}){return t&&e.get(t)?.filter(o=>o!==r?.structureId||n===r.structureId)}function lG({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 fG({idBeingRemoved:t,drawDefinition:e}){let{structure:r}=at({structureId:t,drawDefinition:e}),n=yt({structure:r}).matchUps;return Qm(n)}function wp({stageSequence:t=1,drawDefinition:e,drawSize:r,stage:n}){if(!e)return{error:Z};if(!ng({drawDefinition:e,stage:n}))return{error:xi};let o=vb({drawDefinition:e,stage:n}),{qualifiersCount:i}=hs({drawDefinition:e,stageSequence:t,stage:n}),s=o+i;if(r<s)return{error:FI};let{entryProfile:a}=Xf({attributes:[{[n]:{drawSize:r}}],drawDefinition:e});return vt({drawDefinition:e}),{...C,entryProfile:a}}function BS({qualifiersCount:t=0,drawDefinition:e,stage:r}){return e?ng({drawDefinition:e,stage:r})?r!==rt?{error:FI,info:"qualifiersCount can only be set for main stage"}:(Xf({attributes:[{[r]:{qualifiersCount:t}}],drawDefinition:e}),vt({drawDefinition:e}),{...C}):{error:xi}:{error:Z}}function $v({drawDefinition:t,drawSize:e}){if(!t)return{error:Z};let r=wp({stage:$e,stageSequence:1,drawDefinition:t,drawSize:e});return r.error?r:(vt({drawDefinition:t}),{...C})}function xP(t){return $v(t)}function wP({tournamentRecord:t,drawDefinition:e,event:r,structureId:n}){if(!e)return{error:Z};let o=e.structures?.find(a=>a.stage===ct&&a.structureId===n);if(!o)return{error:wt};if(o.matchUps?.some(({matchUpStatus:a,score:c})=>Ie({score:c})??se.includes(a)))return{error:Xa};let s=o.matchUps?.map(({matchUpId:a})=>a)||[];return o.positionAssignments=[],o.seedAssignments=[],o.matchUps=[],Rn({tournamentId:t?.tournamentId,action:"resetVoluntaryConsolationStructure",matchUpIds:s,drawDefinition:e}),vt({tournamentId:t?.tournamentId,eventId:r?.eventId,drawDefinition:e,structureIds:[o.structureId]}),{...C}}var Kv="qualifierDrawPositionAssignment",zv="withdrawParticipantAtDrawPosition",Qv="alternateDrawPositionAssignment",Xv="luckyLoserDrawPositionAssignment",LP="removeDrawPositionAssignment",HS="swapDrawPositionAssignments",Jv="modifyPairAssignment",Zv="adHocPositionSwap",tO="modifyParticipantOtherName",FP="assignDrawPosition",eO="removeSeededParticipant",rO="assignDrawPositionBye",nO="modifySeedAssignment",WS="addPenalty",Ng="MODIFY_PAIR",Lp="QUALIFIER",Mg="ALTERNATE",Rg="WITHDRAW",As="ASSIGN",jS="REMOVE",Cg="LUCKY",Fp="REMOVE_SEED",kp="SWAP",Mu="NICKNAME",Qs="SEED_VALUE",Xs="PENALTY",Pd="BYE",oO={MODIFY_PAIR_ASSIGNMENT:Ng,QUALIFYING_PARTICIPANT:Lp,ALTERNATE_PARTICIPANT:Mg,WITHDRAW_PARTICIPANT:Rg,ASSIGN_PARTICIPANT:As,LUCKY_PARTICIPANT:Cg,REMOVE_ASSIGNMENT:jS,SWAP_PARTICIPANTS:kp,ADD_NICKNAME:Mu,REMOVE_SEED:Fp,ADD_PENALTY:Xs,ASSIGN_BYE:Pd,SEED_VALUE:Qs};function kP({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:V,drawPositions:r};let i=Me({drawDefinition:e}),{matchUps:s}=ce({inContext:!0,drawDefinition:e,matchUpsMap:i}),{structure:a}=at({drawDefinition:e,structureId:n});if(!a)return{error:wt};let c=Tt({tournamentRecord:t,drawDefinition:e,event:o}).appliedPolicies??{},u;if(a.structureType===Ve?u=hG({inContextDrawMatchUps:s,tournamentRecord:t,drawDefinition:e,drawPositions:r,matchUpsMap:i,structure:a,event:o}):u=gG({inContextDrawMatchUps:s,tournamentRecord:t,drawDefinition:e,drawPositions:r,matchUpsMap:i,structure:a,event:o}),u.error)return u;if(Zm({structure:a,drawPositions:r}),pu({appliedPolicies:c,drawDefinition:e,positionAction:{name:HS,drawPositions:r,structureId:n}}),Oo({tournamentId:t?.tournamentId,drawDefinition:e,structure:a,event:o}),o.eventType===br){let m=yt({matchUpFilters:{matchUpTypes:[xr]},inContext:!0,structure:a}).matchUps.filter(l=>l.drawPositions?.some(f=>r.includes(f))),d=yt({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,E)=>y.drawPosition===g?E:T,void 0);Sd({inContextTargetMatchUp:l,drawPositionSideIndex:S,teamParticipantId:I,tournamentRecord:t,drawDefinition:e,matchUp:h,event:o})}})})}return vt({drawDefinition:e,structureIds:[n]}),{...C}}function gG({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:V,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?iO({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,assignments:a,matchUpsMap:o,structure:i,event:s}):IG({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,assignments:a,matchUpsMap:o,structure:i,event:s})}function iO({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,assignments:n,matchUpsMap:o,structure:i,event:s}){let a=n.find(({bye:f})=>f),c=n.find(({participantId:f})=>f),u=a.drawPosition,{participantId:p,drawPosition:m}=c,{structureId:d}=i,l=Pu({drawPosition:u,inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,structureId:d,matchUpsMap:o});return l.error||(l=Pu({drawPosition:m,inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,structureId:d,matchUpsMap:o}),l.error)||(Hr({drawPosition:m,tournamentRecord:e,drawDefinition:r,structureId:d,matchUpsMap:o,event:s}),l=Bn({drawPosition:u,inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,structureId:d,participantId:p,matchUpsMap:o,event:s}),l.error)?l:{...C}}function IG({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),yg({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,matchUpsMap:o,assignments:n,structure:i,event:s}),{...C}}function hG({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};yg({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)iO({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 GP({tournamentRecord:t,drawDefinition:e,participantId:r,structureId:n}){let o="removeSeededParticipant";if(!t)return{error:$};if(!e)return{error:Z};let i=(e.structures??[]).find(a=>a.structureId===n);return i?!i.stage||![rt,ct].includes(i.stage)||i.stage===rt&&i.stageSequence!==1?_({result:{error:Zo},stack:o}):i.seedAssignments?.find(a=>a.participantId===r)?{...C}:_({info:"participant not seeded",result:{error:ve},context:{participantId:r}}):_({result:{error:wt},stack:o})}function Ca({targetEntryRound:t=1,finishingPositions:e,sourceRoundNumber:r,sourceStructureId:n,targetStructureId:o,linkType:i=Kn}){return!n||!o?{error:Ur}:{link:nt({linkType:i,source:{roundNumber:r,structureId:n,finishingPositions:e},target:{feedProfile:dn,roundNumber:t,structureId:o}})}}function bi({matchUp:t,tieFormat:e,isMock:r,uuids:n}){let{collectionDefinitions:o}=e??{};return{tieMatchUps:(o??[]).map(s=>Ru({matchUp:t,collectionDefinition:s,uuids:n,isMock:r})).filter(Boolean).flat()}}function Ru({collectionPositionOffset:t=0,collectionDefinition:e,matchUpsLimit:r,matchUp:n,isMock:o,uuids:i}){let{matchUpCount:s,matchUpType:a,collectionId:c,processCodes:u}=e||{},p=r??s??0,m=d=>{if(!o&&!n?.isMock)return i?.pop()??Mt();let l=e?.collectionId;return i?.pop()??`${n?.matchUpId}-${l}-TMU-${d+1}`};return tt(0,p).map(d=>{let l=t+d+1;return{sides:[{sideNumber:1},{sideNumber:2}],matchUpId:m(d),matchUpStatus:Xt,collectionPosition:l,collectionId:c,processCodes:u,matchUpType:a,isMock:o}})}function Dd({roundPosition:t,roundNumber:e,idPrefix:r,uuids:n}){return r?`${r}-${e}-${t}`:n?.pop()||Mt()}function Gp({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=Dd({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:Xt,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 bn({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&&(!_n(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(!_n(a)&&!p)return{matchUps:[],roundsCount:0};let m=tt(1,a+1).map(I=>({drawPosition:I})),d,l=[],f=1;for({roundNodes:d,matchUps:l}=Gp({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}=Gp({nodes:d,matchUpType:o,roundNumber:f,idPrefix:s,matchUps:l,isMock:c,uuids:u}),f++;let g=f-1;return l=Pa({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 Nd(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:V},stack:e});let r=t.drawSize??ym(t.participantsCount),{hasExistingDrawDefinition:n,qualifyingRoundNumber:o,qualifyingPositions:i,targetStructureId:s,structureOptions:a,appliedPolicies:c,qualifyingOnly:u,drawDefinition:p,matchUpFormat:m,structureName:d,structureId:l,roundTarget:f,tieFormat:g,drawType:I,idPrefix:h,isMock:S,uuids:T}=t;if(!t.drawSize)return _({result:{error:qa},context:{drawSize:r},stack:e});if(i&&i>=t.drawSize)return _({result:{error:V},context:{drawSize:r,qualifyingPositions:i},stack:e});let y,E,P,A,U=0,N,D=1,{structureProfiles:M}=Nu({drawDefinition:p}),R=M[s];if(!R)return _({result:{error:wt},context:{targetStructureId:s},stack:e});let b=p.matchUpType,v=f?`${f}-`:"",O=R.stage===ct,x=c?.[Ia]?.namingConventions?.pre??wb[Ia]?.namingConventions?.pre,F=O&&x?`${x}-`:"",w=d??(v?`${F}${Qe(ct)} ${v}`:`${F}${Qe(ct)}`);if(I===Nn){let{maxRoundNumber:k,structures:H,groupCount:W}=Ra({structureName:d??w,structureId:l??T?.pop(),hasExistingDrawDefinition:n,stage:ct,structureOptions:a,appliedPolicies:c,qualifyingOnly:u,stageSequence:D,matchUpType:b,roundTarget:f,tieFormat:g,idPrefix:h,drawSize:r,isMock:S,uuids:T});U=W,y=k,P=H[0],N=[1]}else({drawSize:r,matchUps:A,roundLimit:y,roundsCount:E}=bn({qualifyingRoundNumber:o,qualifyingPositions:i,matchUpType:b,idPrefix:h,drawSize:r,isMock:S,uuids:T})),y||(y=E),P=hn({structureName:d??w,structureId:l??T?.pop(),qualifyingRoundNumber:y,stage:ct,matchUpFormat:m,stageSequence:D,matchUpType:b,roundLimit:y,matchUps:A}),f&&Ut({extension:{name:Mn,value:f},element:P}),U=A?.filter(k=>k.roundNumber===y)?.length;let L=I===Nn?xn:Kn,G=P&&y&&Ca({sourceStructureId:P.structureId,sourceRoundNumber:y,targetStructureId:s,finishingPositions:N,linkType:L})?.link;return g&&(A=yt({structure:P})?.matchUps||[],A?.forEach(k=>{let{tieMatchUps:H}=bi({tieFormat:g,matchUp:k,isMock:S});Object.assign(k,{tieMatchUps:H,matchUpType:b})})),{qualifyingDrawPositionsCount:r,qualifiersCount:U,...C,structure:P,link:G}}function VP(t){if(!t.tournamentRecord)return{error:$};let r=SG(t);return r.error,r}function SG(t){if(!t.drawDefinition)return{error:Z};if(!t.targetStructureId)return{error:Ur};let e=Nd(t);if(e.error)return e;let{structure:r,link:n}=e;return!r||!n?{error:V}:Pg({tournamentRecord:t.tournamentRecord,drawDefinition:t.drawDefinition,structure:r,link:n})}function BP(t){let e=et(t,[{[Ce]:!0,[eu]:!0,[ln]:!0},{[ab]:!0,[er]:m=>Number.isInteger(m)&&m>0},{[er]: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:wt};if(!pr({structure:s}))return{error:Zo};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 vt({drawDefinition:r,structureIds:[n]}),{...C}}function sO({includeMatchUpType:t,drawPosition:e,roundNumber:r,matchUpType:n,idPrefix:o,matchUps:i,isMock:s,uuids:a,nodes:c,fed:u}){let p=c.length,m=e?e-p:void 0,d=tt(0,p).map(g=>m?m+g:void 0),l=[];for(let g=0;g<p;g++){let I=d.shift(),h={drawPosition:I,fed:u+1,feed:!0},S=c[g];S.roundNumber=r-1;let T=Dd({roundPosition:S.roundPosition,roundNumber:r,idPrefix:o,uuids:a}),y={roundPosition:S.roundPosition,drawPositions:[I],matchUpStatus:Xt,roundNumber:r,matchUpId:T};t&&(y.matchUpType=n),s&&(y.isMock=!0),i.push(y);let E={children:[S,h]};l.push(E)}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=TG({drawSize:i}),h=I.length,S=0;if(r?.length)S=r.reduce((w,L)=>w+L,0);else if(e){let w=e-i;r=I.filter(L=>L<=w?(w-=L,!0):!1),S=r.reduce((L,G)=>L+G,0),n=r.length}else o>=h?n=0:u&&(n=h-u,o=0),r=I.filter((w,L)=>u&&!n||n&&L>=o+n||L<o?0:w),S=r.reduce((w,L)=>w+L,0),n=r.length;let T=[...I,...r].sort((w,L)=>L-w),y=T.length,P=[...(c??[]).map(w=>w-1),...(s??[]).map(w=>y-w)].map(w=>T[w]).reduce((w,L)=>w+L,0);S=S-P;let A=0,U=[],N,D=1,R=tt(0,i).map((w,L)=>({drawPosition:L+1+S})),b=S+1;for(let w of I){if({roundNodes:N,matchUps:U}=Gp({matchUpType:m,roundNumber:D,idPrefix:d,matchUps:U,isMock:l,nodes:R,uuids:f}),D++,r.includes(w)){let L=yr(r)[w],G=tt(0,L),k=y+1-D,H=s?.includes(k)??c?.includes(D);G.forEach(()=>{({roundNodes:N,matchUps:U,drawPosition:b}=sO({drawPosition:!H&&b||void 0,nodes:N,matchUpType:m,roundNumber:D,idPrefix:d,matchUps:U,isMock:l,uuids:f,fed:A})),D++,A+=1})}R=N}y!==D-1&&console.log("ERROR");let v=i-S;U=Pa({finishingPositionOffset:p?v:a,positionsFed:S,roundsCount:y,matchUps:U,fmlc:g});let x=N?.length?N[0]:N;return x&&(x.roundNumber=D-1,x.matchUps=U),{draw:x,matchUps:U,roundsCount:y};function F(w){let L=Am(w);return L>w?L/2:L}}function TG({drawSize:t}){let e=Math.ceil(Math.log(t)/Math.log(2));return tt(0,e).reverse().map(n=>Math.pow(2,n))}function Ac(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=rt,drawSize:I,idPrefix:h,isMock:S,uuids:T}=t;if(!(!s||!u||s?.[c])||I<2||f&&a>f)return{};let E=[],P=[],A=[],U=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(),w={idPrefix:h&&`${h}-${O}-RP`,finishingPositionOffset:e,matchUpType:U,drawSize:I,isMock:S,uuids:T},{matchUps:L}=l?ci(w):bn(w),G=hn({structureAbbreviation:x,stageSequence:a,structureName:O,matchUpType:U,roundOffset:m,structureId:F,matchUps:L,stage:g});E.push(...L),P.push(G);let k=Math.ceil(Math.log(I)/Math.log(2)),H=p?Math.min(p-m,k):(!i||N<i)&&k||0;return I>2&&tt(1,H+1).forEach(q=>W(q)),{structureId:G.structureId,matchUps:E,structureName:O,structures:P,links:A,...C};function W(q){let Y=I/Math.pow(2,q);if(Y<2)return;let B=I/Math.pow(2,q)+e;if(i&&B+1>i)return;let{structures:K,structureId:X,matchUps:j,links:ot}=Ac({finishingPositionOffset:B,exitProfile:`${c}-${q}`,roundOffset:m+q,stageSequence:a+1,drawSize:Y,addNameBaseToAttributeName:r,playoffStructureNameBase:n,finishingPositionNaming:o,finishingPositionLimit:i,playoffAttributes:s,exitProfileLimit:u,roundOffsetLimit:p,drawDefinition:d,sequenceLimit:f,matchUpType:U,idPrefix:h,uuids:T,stage:g});if(G.structureId&&X){let z={linkType:oo,source:{roundNumber:q,structureId:G.structureId},target:{roundNumber:1,feedProfile:En,structureId:X}};ot&&G&&ot.push(z),ot?.length&&A.push(...ot)}return K?.length&&P.push(...K),j?.length&&E.push(...j),{structureId:X,childLinks:ot,structures:P}}}function Md({drawDefinition:t,matchUpsMap:e,structureId:r}){let n=at({drawDefinition:t,structureId:r});if(n.error)return _({result:n});let{matchUps:o}=yt({structure:n.structure,matchUpsMap:e});return{...Ke({matchUps:o}),matchUps:o,matchUpsMap:e}}function HP({finishingPositions:t,drawDefinition:e,structureId:r}){let{roundProfile:n}=Md({drawDefinition:e,structureId:r});return(n&&Object.keys(n))?.reduce((i,s)=>(aO(n?.[s]).forEach(c=>{t.forEach(u=>{yG({position:u,rangeDefinition:c})&&(i[u]={roundNumber:s})})}),i),{})}function yG({position:t,rangeDefinition:e}){if(!Array.isArray(e)||e.reduce((i,s)=>i||isNaN(s),!1))return!1;let[r,n]=e;return tt(r,(n||r)+1).includes(t)}function aO(t){return[pt(t?.finishingPositionRange?.loser||[]),pt(t?.finishingPositionRange?.winner||[])]}function cO(t){return aO(t).map(e=>tt(e[0],e[1]&&e[1]+1||e[0]+1))}function Ec({drawDefinition:t,structureIds:e,matchUpsMap:r}){if(e&&!Array.isArray(e))return{error:V,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}=Md({drawDefinition:t,matchUpsMap:r,structureId:a});return(c&&Object.values(c))?.map(cO).flat()}).flat(),o=n.filter(a=>a?.length===1).sort(le).flat();return{positionsNotPlayedOff:pt(n.flat()).filter(a=>!o.includes(a)),positionsPlayedOff:o}}function YS({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=Ec({drawDefinition:r});if(o.error)return o;let i=o.positionsPlayedOff,s=e.filter(S=>!i.includes(S)),a=HP({finishingPositions:s,drawDefinition:r,structureId:n}),u=Object.values(a).reduce((S,T)=>S.includes(T.roundNumber)?S:S.concat(T.roundNumber),[]).map(S=>dt(S)).filter(S=>!t.includes(S)),p=HP({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=>dt(S)):[],l=u.filter(S=>!d.includes(S)).sort(le),{roundProfile:f}=Md({drawDefinition:r,structureId:n}),g=l.map(S=>{let T=f?.[S].finishingPositionRange.loser,[y,E]=T??[0,0];return tt(y,(E||y)+1)}).flat().sort(le),{playoffRoundsRanges:I}=AG({playoffSourceRounds:l,roundProfile:f}),h=[...l,...d];return{playoffPositionsReturned:g,playedOffSourceRounds:d,playoffRoundsRanges:I,playoffSourceRounds:l,sourceRounds:h,roundProfile:f}}function AG({playoffSourceRounds:t,roundProfile:e}){return{playoffRoundsRanges:t.map(n=>{let o=e[n].finishingPositionRange.loser,[i,s]=o,a=tt(i,(s||i)+1);return{finishingPositionRange:o.join("-"),finishingPositions:a,roundNumber:n}})}}function Cu({drawDefinition:t,structureId:e}){if(!t)return{error:Z};let{matchUps:r,matchUpsMap:n}=ir({inContext:!0,drawDefinition:t}),{positionsNotPlayedOff:o,positionsPlayedOff:i}=Ec({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=EG({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 EG({playoffPositions:t,drawDefinition:e,structure:r,matchUps:n}){let o=r?.structureId,{links:i}=js({drawDefinition:e,structureId:o});if(r.structureType===Ve||r.structures){let l=Ct({structure:r})?.positionAssignments?.length,f=r.structures.length,g=(l??0)/f,I=i.source?.flatMap(({source:D})=>D?.finishingPositions||[])||[],h=tt(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:E=[]}=Ec({structureIds:T,drawDefinition:e}),P=[...y,...E],A=tt(S[0],S[1]+1).filter(D=>!P.includes(D)),U=Ee(A,A.length/h.length),N=h.map((D,M)=>{let R=U[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!==wn).map(l=>l.source?.roundNumber)||[],a=i?.source?.filter(l=>l.linkCondition===wn).map(l=>l.source?.roundNumber)||[],c=YS({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),E=y+S,P=tt(y,E),A={finishingPositionRange:[y,E-1].join("-"),finishingPositions:P,roundNumber:l};p.push(A)}}}return u&&u.sort(le),p.sort((l,f)=>l.roundNumber-f.roundNumber),{playoffRounds:u,playoffRoundsRanges:p,error:d}}function uO({playoffGroups:t,drawDefinition:e,structureId:r}){if(!e)return{error:Z};if(!Vt(r)||!Array.isArray(t))return{error:V};let n=t.map(({finishingPositions:a})=>a).flat();return{positionRangeMap:Cu({drawDefinition:e,structureId:r}).playoffFinishingPositionRanges?.filter(a=>n.includes(a.finishingPosition))?.reduce((a,c)=>(a[c.finishingPosition]=c,a),{})}}function qS(t){let{finishingPositionOffset:e=0,playoffAttributes:r,stageSequence:n=1,staggeredEntry:o,structureName:i,stage:s=rt,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):bn(l),g=hn({structureName:i||r?.["0"]?.name||Qe(rt),structureId:c||d?.pop(),stageSequence:n,matchUpType:a,matchUps:f,stage:s}),I=[g],h=[];if(p>2){let S=p/2,{matchUps:T}=bn({finishingPositionOffset:e+S,idPrefix:u&&`${u}-c`,drawSize:S,matchUpType:a,isMock:m}),y=Qe(qe),E=r?.["0-1"]?.name??t.consolationStructureName??(i?`${i} ${y}`:y),P=hn({structureName:E,matchUps:T,structureId:d?.pop(),stage:qe,stageSequence:1,matchUpType:a});I.push(P);let A={linkType:oo,source:{roundNumber:1,structureId:g.structureId},target:{roundNumber:1,feedProfile:En,structureId:P.structureId}};h.push(A)}return{...C,structures:I,links:h}}function $S({consolationStructure:t,roundOffset:e=0,mainStructure:r,roundsCount:n,feedPolicy:o,fmlc:i}){let a=t.matchUps.reduce((p,m)=>(m.drawPositions||[]).filter(Boolean).length&&!p.includes(m.roundNumber)?p.concat(m.roundNumber):p,[]),c=o?.roundGroupedOrder||[],u=o?.roundFeedProfiles;return tt(1+e,n+1+e).map(p=>{let m=u?.[p-1]?u[p-1]:p%2&&En||fi,d=p-e<=2?p-e:(p-e-2)*2+2,l={linkType:oo,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=wn,l.target.feedProfile=En),a.includes(d)?l:void 0}).filter(Boolean)}function KS(t){let{playoffStructureNameBase:e,finishingPositionOffset:r,stageSequence:n=1,playoffAttributes:o,structureNameMap:i,staggeredEntry:s,stage:a=rt,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):bn(f),h=t.structureName??o?.["0"]?.name??Qe(rt),S=Ts({structureId:u||l?.pop(),structureName:h,stageSequence:n,matchUpType:c,matchUps:g,stage:a}),T=[S],y=[];if(p>2){let A=[0,2].slice(0,p/16).map((U,N)=>{let D=N+1,{consolationStructure:M}=UG({idPrefix:m&&`${m}-c${N}`,structureId:l?.pop(),playoffStructureNameBase:e,playoffAttributes:o,structureNameMap:i,stageSequence:D,roundOffset:U,matchUpType:c,drawSize:p,isMock:d,index:N,uuids:l});T.push(M);let R=$S({consolationStructure:M,roundsCount:2,mainStructure:S,roundOffset:U});return{consolationStructure:M,links:R}}).map(U=>U.links).flat();if(y.push(...A),p>=4&&p<=16||p>32){let{matchUps:U}=bn({idPrefix:m&&`${m}-p3t4`,finishingPositionOffset:2,drawSize:2,matchUpType:c,isMock:d}),N=o?.["3-4"]?.name??Qe(fe),D=i?.[N]||N,M=e?`${e} ${D}`:D,R=Ts({structureId:l?.pop(),matchUps:U,stageSequence:2,stage:fe,structureName:M,matchUpType:c}),b={linkType:oo,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 UG({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:Ts({matchUps:l,stage:qe,structureName:S,stageSequence:e,matchUpType:i,structureId:s}),consolationRoundsCount:f}}function Uc(t){let{finishingPositionOffset:e,stageSequence:r=1,playoffAttributes:n,feedsFromFinal:o,staggeredEntry:i,structureName:s,stage:a=rt,structureId:c,matchUpType:u,skipRounds:p,feedRounds:m,idPrefix:d,drawSize:l,isMock:f,uuids:g,fmlc:I}=t,h=t.feedPolicy||t.policyDefinitions?.[oc]||t.appliedPolicies?.[oc],S={finishingPositionOffset:e,matchUpType:u,skipRounds:p,drawSize:l,idPrefix:d,isMock:f,uuids:g},{matchUps:T}=i?ci(S):bn(S),y=hn({structureName:s||n?.["0"]?.name||Qe(rt),structureId:c||g?.pop(),stageSequence:r,matchUpType:u,matchUps:T,stage:a}),E=[y],P=[],A=l/2,{matchUps:U,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:U,structureId:g?.pop(),stage:qe,stageSequence:1,structureName:M,matchUpType:u});E.push(R);let b=$S({consolationStructure:R,mainStructure:y,roundsCount:N,feedPolicy:h,fmlc:I});P.push(...b)}return{...C,structures:E,links:P}}function QS({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?.[oc];let f="processPlayoffGroups",g=0,I=[],h=[],S=[],{error:T,positionRangeMap:y}=uO({structureId:n,drawDefinition:s,playoffGroups:a});if(T)return _({result:{error:T},stack:f});if(!(!y||a?.every(P=>{let{finishingPositions:A=[]}=P;if(!A.length)return!1;let U=[...A].sort(le).map((N,D)=>(A[D+1]||N)-N).every(N=>N<2);return(!t||U)&&A.every(N=>y[N])})))return _({context:{validFinishingPositions:Object.values(y)},result:{error:V},stack:f});for(let P of a){let A=P.finishingPositions,U=y&&A.map(F=>y[F]?.finishingPositions).flat(),N=p*A.length,D=rs(N),M=D===2&&ho||P.drawType||ho;U&&(g=Math.min(...U)-1);let R=U&&`${Math.min(...U)}-${Math.max(...U)}`,b=P.structureName||R&&P.playoffAttributes?.[R]?.name||P.playoffAttributes?.["0"]?.name,O={...{addNameBaseToAttributeName:P.addNameBaseToAttributeName,playoffStructureNameBase:P.playoffStructureNameBase,finishingPositionNaming:P.finishingPositionNaming,finishingPositionLimit:P.finishingPositionLimit,structureId:P.structureId??l?.pop(),playoffAttributes:P.playoffAttributes,structureNameMap:P.structureNameMap,sequenceLimit:P.sequenceLimit,structureName:b},idPrefix:m&&`${m}-po`,appliedPolicies:o,finishingPositionOffset:g,stage:fe,stageSequence:i,matchUpType:c,drawSize:D,isMock:d,uuids:l},x=({playoffStructures:F,playoffLinks:w})=>{let[L]=F,G=zS({playoffStructureId:L.structureId,finishingPositions:A,sourceStructureId:n});S.push(G),S.push(...w),h.push(...F),I.push({structureId:L.structureId,finishingPositions:A}),g+=N};if(M===ho){let{matchUps:F}=bn({finishingPositionLimit:g+N,idPrefix:m&&`${m}-po`,finishingPositionOffset:g,matchUpType:c,drawSize:D,isMock:d,uuids:l}),w=hn({structureId:P.structureId??l?.pop(),matchUpFormat:e,stage:fe,structureName:b,stageSequence:i,matchUps:F});h.push(w);let L=zS({playoffStructureId:w.structureId,finishingPositions:A,sourceStructureId:n});S.push(L),g+=N,I.push({structureId:w.structureId,finishingPositions:A})}else if([Xc,Jc,fe].includes(M)){let F={playoffAttributes:P.playoffAttributes??r,playoffStructureNameBase:P.playoffStructureNameBase,structureId:P.structureId??l?.pop(),structureName:P.structureName,idPrefix:m&&`${m}-po`,addNameBaseToAttributeName:!0,finishingPositionOffset:g,stage:fe,roundOffset:0,stageSequence:i,drawSize:D,isMock:d,uuids:l};M===Xc?Object.assign(F,{playoffAttributes:P?.playoffAttributes??r??Df,roundOffsetLimit:3}):M===Jc&&Object.assign(F,{playoffAttributes:P?.playoffAttributes??r??Nf,roundOffsetLimit:2});let w=Ac(F);if(w.error)return w;if(w.links?.length&&S.push(...w.links),w.structures?.length&&h.push(...w.structures),h.sort(yi),w.structureId){let L=zS({playoffStructureId:w.structureId,finishingPositions:A,sourceStructureId:n});S.push(L),I.push({structureId:w.structureId,finishingPositions:A})}g+=N}else if([tu,lp,Fm,Lm,wm,km].includes(M)){let F=[l?.pop(),l?.pop()],w={playoffStructureNameBase:P.playoffStructureNameBase,structureId:P.structureId??l?.pop(),playoffAttributes:P.playoffAttributes,idPrefix:m&&`${m}-po`,finishingPositionOffset:g,uuids:F,stage:fe,structureName:b,matchUpType:c,feedPolicy:u,drawSize:D,isMock:d},L={[tu]:{fmlc:!0,feedRounds:1},[km]:{feedRounds:1},[Fm]:{feedsFromFinal:3},[Lm]:{feedsFromFinal:2},[wm]:{feedsFromFinal:1}};Object.assign(w,L[M]||{});let{structures:G,links:k}=Uc(w),[H]=G,W=zS({playoffStructureId:H.structureId,finishingPositions:A,sourceStructureId:n});S.push(W),S.push(...k),h.push(...G),I.push({structureId:H.structureId,finishingPositions:A}),g+=N}else if([Nn].includes(M)){let{structures:F,links:w}=Ra({...O,structureOptions:P.structureOptions||{groupSize:4}});x({playoffStructures:F,playoffLinks:w})}else if([dp].includes(M)){let{structures:F,links:w}=qS(O);x({playoffStructures:F,playoffLinks:w})}else if([rb].includes(M)){let{structures:F,links:w}=KS(O);x({playoffStructures:F,playoffLinks:w})}else if([$r].includes(M)){let F=hn({structureId:P.structureId??l?.pop(),structureName:P.structureName,finishingPosition:rd,stage:fe,stageSequence:i,matchUps:[]});x({playoffStructures:[F],playoffLinks:[]})}}return{finishingPositionTargets:I,positionRangeMap:y,structures:h,links:S}}function zS({playoffStructureId:t,finishingPositions:e,sourceStructureId:r}){return{linkType:xn,source:{structureId:r,finishingPositions:e},target:{structureId:t,feedProfile:dn,roundNumber:1}}}function pO(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=QS({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:U})=>U).flat().map(U=>f[U].finishingPositions).flat();i.structures.push(...m),i.links.push(...d);let{matchUps:I,matchUpsMap:h}=ce({inContext:!0,drawDefinition:i}),S=m.map(({structureId:U})=>U),T=I?.filter(({structureId:U})=>S.includes(U)).map(Ue),y=h?.drawMatchUps?.filter(({matchUpId:U})=>T?.includes(U));if(y?.length){let U=We({drawDefinition:i,event:u})?.tieFormat;U&&y.forEach(N=>{let{tieMatchUps:D}=bi({isMock:t.isMock,tieFormat:U,matchUp:N});Object.assign(N,{tieMatchUps:D,matchUpType:xr})})}let{positionAssignments:E}=Ct({structureId:r,drawDefinition:i}),P={};E?.forEach(U=>{let M=mt({element:U,name:bo})?.extension?.value?.groupOrder;M&&(P[M]||(P[M]=[]),P[M].push(U.participantId))});let A=zs({provisionalPositioning:t.provisionalPositioning,structureId:r,applyPositioning:!0,event:t.event,tournamentRecord:o,drawDefinition:i});return A.error&&A.error?.code!==kl.code?_({result:A,stack:e}):{structures:m,links:d,positionsPlayedOff:g,drawDefinition:i,...C}}function bu({value:t,sourceRange:e,targetRange:r}){let n=Math.min(...e),o=Math.max(...e),i=Math.min(...r),s=Math.max(...r);return(t-n)*(s-i)/(o-n)+i}var Zn="ELO",WP="NTRP",PG="TRN",jP="UTR",bg="WTN",mO={ELO:Zn,NTRP:WP,TRN:PG,UTR:jP,WTN:bg};var DG={[Zn]:{defaultInitialization:1500,decimalsCount:0,range:[0,3e3],ascending:!0},[WP]:{accessors:["ntrpRating","dntrpRatingHundredths"],attributes:{ustaRatingType:""},accessor:"dntrpRatingHundredths",defaultInitialization:3,decimalsCount:1,ascending:!0,range:[1,7]},[jP]:{defaultInitialization:6,accessors:["utrRating"],accessor:"utrRating",decimalsCount:2,ascending:!0,range:[1,16]},[bg]:{attributes:{confidence:{generator:!0,range:[60,100]}},accessors:["wtnRating","confidence"],defaultInitialization:23,accessor:"wtnRating",ascending:!1,decimalsCount:2,range:[40,1]}},we=DG;function dO({sourceRatingType:t,sourceRating:e}){let r=we[t].range,n=r[0]>r[1],o=we[Zn].range;return bu({value:n?r[0]-e:e,sourceRange:r,targetRange:o})}function lO({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[Zn].range,a=bu({targetRange:n,sourceRange:s,value:e}),c=parseFloat(a.toFixed(r));return o?i-c:c}function YP(t){let e=et(t,[{ratings:!0,[He]:Kr}]);if(e.error)return e;let r=t.matchUpType&&[kt,xt].includes(t.matchUpType)?t.matchUpType:kt,n=Object.keys(we),o=t.targetRatingType&&n.includes(t.targetRatingType)?t.targetRatingType:Zn,i=t.ratings[r]?t.ratings[r].reduce((d,l)=>d.includes(l.scaleName)?d:d.concat(l.scaleName),[]):[];if(!i)return{error: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=dO({sourceRatingType:a,sourceRating:u});return{convertedRating:lO({targetRatingType:o,sourceRating:p}),sourceRating:u}}function fO({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?.[kt]&&s?.[kt]){let a=Zn,{convertedRating:c}=YP({ratings:i,targetRatingType:a}),{convertedRating:u}=YP({ratings:s,targetRatingType:a}),{side1pressure:p,side2pressure:m}=NG({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[Zn].range),l=Ll((u-c)/d),f=Ll((c-u)/d);t[n?.participantId].ratingVariation.push(l),t[o?.participantId].ratingVariation.push(f)}}function NG({side1ConvertedRating:t,side2ConvertedRating:e,score:r}){let n=t>e?t:e,o=t>e?e:t,i=Math.abs(t-e),s=we[Zn].range,a=Math.max(...s),c=(a-n)*0,p=(n+c)/a*i,m=r?.sets?.reduce((T,y)=>T+(y?.side1Score??0),0),d=r?.sets?.reduce((T,y)=>T+(y.side2Score??0),0),l=t>e?2:1,f=(m||0)*(o+(l===1?p:0)),g=(d||0)*(o+(l===2?p:0)),I=f+g,h=I?Ll(f/I):0,S=I?Ll(g/I):0;return{side1pressure:h,side2pressure:S}}function vg({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=qP(c?.bestOf??1);if(typeof a=="number"&&(r===Rt&&n?.setsCreditForDefaults||r===bt&&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===nr&&(+i[1-a]===u&&(i[1-a]-=1),n?.setsCreditForRetirements&&(i[a]=u)),i}function XS({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=qP(c),p=a?.setFormat?.tiebreakAt||0,m=[[],[]];if(typeof s=="number"&&(r===Rt&&n?.gamesCreditForDefaults||r===bt&&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;gO(I)&&(m[0].push(dt(S||0)),m[1].push(dt(T||0))),h&&d.winningSide&&n?.gamesCreditForTiebreakSets!==!1&&m[d.winningSide-1].push(1)});if(r===nr&&typeof s=="number"){let d=i.length>u&&a?.finalSetFormat?"finalSetFormat":"setFormat",l=a?.[d];if(gO(l.based)){let f=l?.setTo||0,g=S=>{if(!(!a||S===""))return+S===p-1||+S===p?dt(p||0)+1:+S<p?f:p},I=vg({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 JS({matchUpFormat:t,score:e}){let r=t?Ye(t):void 0,n=r?.bestOf??1,o=qP(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(IO(m)){let{side1Score:d,side2Score:l}=a;d&&(s[0]+=dt(d||0)),l&&(s[1]+=dt(l||0))}else a.side1TiebreakScore&&(s[0]+=dt(a.side1TiebreakScore||0)),a.side2TiebreakScore&&(s[1]+=dt(a.side2TiebreakScore||0)),(a.side1TiebreakScore||a.side2TiebreakScore)&&a.winningSide&&(i[a.winningSide-1]+=1)}),{pointsTally:s,tiebreaksTally:i}}function qP(t){return t&&Math.ceil(t/2)||1}function IO(t){return t==="P"}function gO(t){return!IO(t)}function hO({participantResults:t,groupingTotal:e,matchUpFormat:r,tallyPolicy:n,totalGames:o,perPlayer:i,totalSets:s}){let a=r&&Ye(r)||{},c=a.bestOf,u=c&&Math.ceil(c/2)||1,p=a.setFormat?.setTo,m=Math.pow(10,n?.precision||3);Object.keys(t).forEach(d=>{let l=t[d].setsWon,f=t[d].setsLost,g=n?.groupTotalSetsPlayed||e==="setsPct"?s:i*(u||0)||l+f,I=Math.round(l/g*m)/m;(I===1/0||isNaN(I))&&(I=g);let h=t[d].tieMatchUpsWon,S=t[d].tieMatchUpsLost,T=h+S,y=Math.round(h/T*m)/m;(y===1/0||isNaN(y))&&(y=h);let E=t[d].matchUpsWon,P=t[d].matchUpsLost,A=E+P,U=Math.round(E/A*m)/m;(U===1/0||isNaN(U))&&(U=E);let N=t[d].gamesWon||0,D=t[d].gamesLost||0,M=(i||0)*(u||0)*(p||0),R=n?.groupTotalGamesPlayed||e==="gamesPct"?o:Math.max(M,N+D),b=Math.round(N/R*m)/m;(b===1/0||isNaN(b))&&(b=0);let v=t[d].pointsWon+t[d].pointsLost,O=Math.round(t[d].pointsWon/v*m)/m;(O===1/0||isNaN(O))&&(O=0),t[d].setsWon=l,t[d].setsLost=f,t[d].setsPct=I,t[d].tieMatchUpsWon=h,t[d].tieMatchUpsPct=y,t[d].matchUpsPct=U,t[d].gamesWon=N,t[d].gamesLost=D,t[d].gamesPct=b,t[d].pointsPct=O,t[d].result=`${t[d].matchUpsWon}/${t[d].matchUpsLost}`})}function vu({participantIds:t,pressureRating:e,groupingTotal:r,matchUpFormat:n,tallyPolicy:o,perPlayer:i,matchUps:s}){let a={},c=o?.excludeMatchUpStatuses||[],u=s?.filter(g=>(g.tieMatchUps||!c.includes(g.matchUpStatus))&&(!t?.length||jt(t,[Rd(g,0),Rd(g,1)]).length===2)),m=u?.flatMap(({score:g,tieMatchUps:I})=>I?I.filter(({matchUpStatus:h})=>!c.includes(h)).flatMap(({score:h})=>h?.sets?.length??0):g?.sets?.length??0)?.reduce((g,I)=>g+I,0),d=g=>g?.sets?.reduce((I,h)=>I+(h?.side1Score??0)+(h?.side2Score??0),0)??0,f=u?.flatMap(({score:g,tieMatchUps:I})=>I?I.filter(({matchUpStatus:h})=>!c.includes(h)).flatMap(({score:h})=>d(h)):d(g))?.reduce((g,I)=>g+I,0);for(let g of u??[]){let{matchUpStatus:I,tieMatchUps:h,tieFormat:S,score:T,winningSide:y,sides:E}=g,P=S&&g._disableAutoCalc&&S.collectionDefinitions.every(({scoreValue:N})=>N),A=y&&MG(g),U=y&&RG(g);if(!A&&!U)if(I&&se.includes(I)){let N=Rd(g,0),D=Rd(g,1);N&&(Pc(a,N),a[N].matchUpsCancelled+=1),D&&(Pc(a,D),a[D].matchUpsCancelled+=1)}else if(h?.length){i=0;for(let N of h){if(N.winningSide){let D=E?.find(({sideNumber:R})=>R===N.winningSide)?.participantId,M=E?.find(({sideNumber:R})=>R===N.winningSide)?.participantId;D&&M&&(Pc(a,D),Pc(a,M),a[D].tieMatchUpsWon+=1,a[M].tieMatchUpsLost+=1,de(kt)(N.matchUpType)?(a[D].tieSinglesWon+=1,a[M].tieSinglesLost+=1):de(xt)(N.matchUpType)&&(a[D].tieDoublesWon+=1,a[M].tieDoublesLost+=1))}SO({score:N.score,manualGamesOverride:P,participantResults:a,sides:E})}}else SO({manualGamesOverride:P,participantResults:a,score:T,sides:E});else if(Pc(a,A),Pc(a,U),h?.length){i=0;for(let N of h){let{matchUpType:D}=N,M=de(xt)(D),R=de(kt)(D);N.winningSide&&(N.winningSide===y?(A&&(a[A].tieMatchUpsWon+=1,R&&(a[A].tieSinglesWon+=1),M&&(a[A].tieDoublesWon+=1)),U&&(a[U].tieMatchUpsLost+=1,R&&(a[U].tieSinglesLost+=1),M&&(a[U].tieDoublesLost+=1))):N.winningSide!==y&&(U&&(a[U].tieMatchUpsWon+=1,R&&(a[U].tieSinglesWon+=1),M&&(a[U].tieDoublesWon+=1)),A&&(a[A].tieMatchUpsLost+=1,R&&(a[A].tieSinglesLost+=1),M&&(a[A].tieDoublesLost+=1)))),TO({matchUpFormat:N.matchUpFormat,matchUpStatus:N.matchUpStatus,matchUpType:N.matchUpType,score:N.score,sides:N.sides,winningParticipantId:A,losingParticipantId:U,manualGamesOverride:P,participantResults:a,isTieMatchUp:!0,pressureRating:e,tallyPolicy:o,winningSide:y})}yO({winningParticipantId:A,losingParticipantId:U,participantResults:a,matchUpStatus:I})}else TO({matchUpFormat:g.matchUpFormat??n,matchUpType:g.matchUpType,isTieMatchUp:void 0,winningParticipantId:A,manualGamesOverride:P,losingParticipantId:U,participantResults:a,pressureRating:e,matchUpStatus:I,tallyPolicy:o,winningSide:y,score:T,sides:E});if(P){let N=T?.sets?.reduce((b,v)=>b+(v?.side1Score??0),0),D=T?.sets?.reduce((b,v)=>b+(v.side2Score??0),0),M=E?.find(({sideNumber:b})=>b===1)?.participantId,R=E?.find(({sideNumber:b})=>b===2)?.participantId;Pc(a,M),Pc(a,R),M&&(a[M].gamesWon+=N,a[M].gamesLost+=D),R&&(a[R].gamesWon+=D,a[R].gamesLost+=N)}}return hO({participantResults:a,groupingTotal:r,matchUpFormat:n,tallyPolicy:o,totalGames:f,perPlayer:i,totalSets:m}),{participantResults:a}}function MG(t){let e=t.winningSide-1;return Rd(t,e)}function RG(t){let e=1-(t.winningSide-1);return Rd(t,e)}function Rd(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 Pc(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 SO({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(dt(p||0)),i[1].push(dt(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&&(Pc(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 TO({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===kt&&fO({participantResults:n,sides:d,score:m}),a||yO({winningParticipantId:t,losingParticipantId:r,participantResults:n,matchUpStatus:s});let g=vg({matchUpStatus:s,matchUpFormat:i,tallyPolicy:u,winningSide:p,score:m}),I=XS({matchUpStatus:s,matchUpFormat:i,tallyPolicy:u,winningSide:p,score:m}),{pointsTally:h}=JS({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 yO({winningParticipantId:t,losingParticipantId:e,participantResults:r,matchUpStatus:n}){e&&(n===bt&&(r[e].walkovers+=1),n===Rt&&(r[e].defaults+=1),n===nr&&(r[e].retirements+=1),[Rt,nr,bt].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 AO({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 $P({participantResults:t,participantIds:e,attribute:r}){return KP({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 KP(t){return(t.participantIds||Object.keys(t.participantResults)).reduce((r,n,o)=>(r.push({participantId:n,i:o,results:t.participantResults[n]}),r),[])}var CG=[{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}],zP={matchUpsPct:20,tieMatchUpsPct:16,pointsPct:4,gamesPct:8,setsPct:12};function QP(t){let{requireCompletion:e=!0,participantResults:r,subOrderMap:n,tallyPolicy:o}=t,i=[];if(e&&!bG(t))return{};let s=["tieMatchUpsWon","tieSinglesWon","tieDoublesWon","matchUpsWon","pointsWon","gamesWon","setsWon","gamesPct","setsPct","pointsPct","matchUpsPct"].includes(o?.groupOrderKey)?o.groupOrderKey:"matchUpsWon",a=$P({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=EO({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=yr(g);return p.forEach(S=>{let{participantId:T,position:y}=S||{},E=r[T];S.GEMscore=h(E);let P=I[y];S?.position!==void 0&&(P>1&&(S.ties=P,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(zP).filter(E=>o.GEMscore.includes(E)):Object.keys(zP)).map(E=>(S[E]||0)*Math.pow(10,zP[E].toFixed(3))).reduce((E,P)=>E+P,0)}}function bG({participantResults:t,participantsCount:e}){let n=KP({participantResults:t}).filter(o=>e-1===o.results.matchUpsWon+o.results.matchUpsLost+o.results.matchUpsCancelled);return e===n.length}function vG({disableHeadToHead:t,participantIds:e,matchUpFormat:r,groupTotals:n,tallyPolicy:o,attribute:i,idsFilter:s,matchUps:a,reversed:c}){let{participantResults:u}=vu({participantIds:s&&e,groupingTotal:n&&i,matchUpFormat:r,tallyPolicy:o,matchUps:a}),p=$P({participantResults:u,participantIds:e,attribute:i}),m=[{attribute:i,reversed:c,groups:p,idsFilter:s,groupTotals:n}],d;return Object.keys(p).length>1&&e.length&&(d=Object.keys(p).map(g=>parseFloat(g)).sort((g,I)=>c?g-I:I-g).map(g=>p[g]).map(g=>{let I=EO({participantResults:u,disableHeadToHead:t,participantIds:g,matchUpFormat:r,tallyPolicy:o,matchUps:a});return m.push(...I.report??[]),I.order}).map((g,I)=>g.map(h=>h.resolved?h:{...h,subGroup:[I].concat(...h.subGroup??[])})).flat()),{order:d,report:m}}function EO({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=OG({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||CG).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,groupTotals:f,disableHeadToHead:g})=>(c=vG({disableHeadToHead:g,participantIds:r,matchUpFormat:n,groupTotals:f,tallyPolicy:o,attribute:m,idsFilter:l,matchUps:i,reversed:d}),a.push(c.report),!c.order)),c.order?{order:c.order,report:a}:{order:r?.map(m=>({participantId:m})),report:a}}function OG({participantIds:t,participantResults:e}){if(t){if(e[t[0]].victories.includes(t[1]))return t.map(r=>({resolved:!0,participantId:r}));if(e[t[1]].victories.includes(t[0]))return t.reverse().map(r=>({resolved:!0,participantId:r}))}}function ba({policyDefinitions:t,generateReport:e,pressureRating:r,matchUpFormat:n,matchUps:o=[],subOrderMap:i,perPlayer:s}){if(!o?.length||!Vr(o))return{error:eo};let a=pt(o.map(({structureId:y})=>y));if(a.length!==1)return _({result:{error:V,info:"Maximum one structureId"},stack:"tallyParticipantResults",context:{structureIds:a}});let c=o.filter(y=>y&&y.matchUpStatus!==Nt),u=c.length&&pt(c.map(({drawPositions:y})=>y).flat()).length,p=c.filter(y=>ls({matchUp:y})).length===c.length;p||(s=0);let m=o.every(({matchUpType:y,tieMatchUps:E})=>y===Wt&&E?.every(P=>ls({matchUp:P}))),d=t?.[Of],l=o.filter(y=>ls({matchUp:y})||y.matchUpType===Wt),{participantResults:f}=vu({matchUps:l,pressureRating:r,matchUpFormat:n,tallyPolicy:d,perPlayer:s}),g,I,{groupOrder:h,report:S}=QP({matchUps:l,participantResults:f,participantsCount:u,matchUpFormat:n,subOrderMap:i,tallyPolicy:d});if(r&&_G({participantResults:f}),p&&h)g=S,I=h,h.forEach(y=>{let{participantId:E,groupOrder:P,rankOrder:A,subOrder:U,ties:N,GEMscore:D}=y,M=f[E];Object.assign(M,{groupOrder:P,rankOrder:A,GEMscore:D,subOrder:U,ties:N})});else{let{groupOrder:y,report:E}=QP({requireCompletion:!1,participantResults:f,participantsCount:u,matchUpFormat:n,tallyPolicy:d,subOrderMap:i,matchUps:o});g=E,I=y,y&&y.forEach(P=>{let{participantId:A,groupOrder:U,GEMscore:N}=P,D=f[A];Object.assign(D,{provisionalOrder:U,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=AO({matchUps:o,report:g,order:I});Pr({tally:!0})&&console.log(y),T.readableReport=y}return T}function _G({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 ZS({positionAssignments:t}){let e=(t||[]).filter(Br(io)).map(i=>{let{extension:s}=mt({element:i,name:sc}),a=dt(s?.value),c=!isNaN(a)&&a;return c&&{participantId:i.participantId,subOrder:c}}).filter(Boolean),r=e.map(({subOrder:i})=>i),n=yr(r);return{subOrderMap:Object.assign({},...e.filter(({subOrder:i})=>n[i]===1).map(({participantId:i,subOrder:s})=>({[i]:s})))}}function Cd({positionAssignments:t,tournamentRecord:e,drawDefinition:r,matchUpFormat:n,matchUps:o,event:i}){if(!Vr(o))return{error:V};if(!t)return{error:V};let{policyDefinitions:s}=_o({policyTypes:[Of],tournamentRecord:e,drawDefinition:r,event:i}),{subOrderMap:a}=ZS({positionAssignments:t}),c=o.length?ba({policyDefinitions:s,matchUpFormat:n,subOrderMap:a,matchUps:o}):void 0;if(c?.error)return c;let{participantResults:u={},bracketComplete:p,report:m}=c??{},d=Object.keys(u);return t.forEach(l=>{let{participantId:f}=l;if(d.includes(f)){let g={value:u[f],name:bo};Ut({element:l,extension:g}),u[f].ties||gr({element:l,name:sc})}else gr({element:l,name:bo}),gr({element:l,name:sc})}),vt({drawDefinition:r}),{...C,participantResults:u,bracketComplete:p,report:m}}function tT({matchUps:t,matchUpId:e}){return{matchUp:(t||[]).find(n=>n.matchUpId===e)}}function Bt(t){let e=et(t,[{[Ce]:!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&&Qn({contextProfile:o,drawDefinition:i});for(let l of m){let{matchUps:f}=yt({tournamentParticipants:r,afterRecoveryTimes:n,contextContent:d,drawDefinition:i,contextProfile:o,matchUpsMap:s,inContext:c,structure:l,context:u,event:p}),{matchUp:g}=tT({matchUps:f,matchUpId:a});if(g)return{matchUp:g,structure:l}}return{error:Le}}function Vp(t){return!ht(t)||!t.notes?{error:st}:ht(t.element)?!Vt(t.notes)&&!t.notes?.testing?{error:V}:(Object.assign(t.element,{notes:t.notes}),{...C}):{error:V}}function Og(t){return ht(t)?ht(t.element)?(t.element.notes&&delete t.element.notes,{...C}):{error:V}:{error:st}}var Ou={matchUpStatus:Xt,matchUpStatusCodes:[],score:{scoreStringSide1:"",scoreStringSide2:"",sets:void 0},matchUpFormat:void 0,winningSide:void 0};function Hn(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:Tt({policyTypes:[tn],tournamentRecord:s,drawDefinition:a,structure:o,event:d})?.appliedPolicies,h=n.matchUpType===Wt;if(h&&a){if(m&&n.matchUpId!==m){let U=Bt({drawDefinition:a,matchUpId:m,event:d});if(!U.matchUp)return{error:Le};({matchUp:n,structure:o}=U)}}else n.matchUpId!==m&&console.log("!!!!!");c&&[bt,Te].includes(c)||u?Object.assign(n,{...Ou}):f&&(n.score=f);let S=c&&n?.matchUpStatus===Rt&&c!==Rt;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)&&!se.includes(c)&&![ac,as,un].includes(c)&&(n.matchUpStatus=Gn);let T;if((S&&n?.processCodes?.length||c===Rt)&&(T=I?.[tn]?.processCodes?.incompleteAssignmentsOnDefault),!n.collectionId){let U=o?.structureType===Ve,N=pr({structure:o});if(ad({drawDefinition:a,structure:o})||N||U){let D=b=>{r=h?"SET1-S:T100":r??n.matchUpFormat??b?.matchUpFormat??a?.matchUpFormat??d?.matchUpFormat;let v=h?{matchUpTypes:[Wt]}:void 0,{matchUps:O}=yt({afterRecoveryTimes:!1,tournamentRecord:s,inContext:!0,matchUpFilters:v,drawDefinition:a,structure:b,event:d});return N&&(b.positionAssignments=pt(O.flatMap(x=>(x.sides??[]).map(F=>F.participantId)).filter(Boolean)).map(x=>({participantId:x}))),Cd({positionAssignments:b.positionAssignments,tournamentRecord:s,drawDefinition:a,matchUpFormat:r,matchUps:O,event:d})},M=U&&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 U=Vp({element:n,notes:l});if(U.error)return _({result:U,stack:e})}let y=s?.tournamentId,E=Lr().topics.includes(Ap),P=(E||T)&&Me({drawDefinition:a}),A=P&&ce({matchUpFilters:{matchUpIds:[m]},nextMatchUps:!0,tournamentRecord:s,inContext:!0,drawDefinition:a,matchUpsMap:P}).matchUps?.[0];if(E&&A&&Ub({tournamentId:y,inContextMatchUp:A}),Array.isArray(T)&&A&&!A.sides?.every(({participantId:U})=>U))if(c===Rt)n.processCodes=pt([...n.processCodes??[],...T]);else for(let U of T||[]){let N=U&&n?.processCodes?.lastIndexOf(U);n?.processCodes?.splice(N,1)}return gt({eventId:d?.eventId,context:e,drawDefinition:a,tournamentId:y,matchUp:n}),{...C}}function bd(t){let{matchUpStatusCodes:e,matchUpStatus:r,structure:n,matchUp:o,dualMatchUp:i,inContextMatchUp:s,autoCalcDisabled:a}=t,c=Da({matchUpStatus:r})||[co,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(!(pr({structure:n})&&u===1||r===Rt&&u||xG({structure:n,matchUp:o,inContextMatchUp:s})||t.appliedPolicies?.[tn]?.requireParticipantsForScoring===!1))return _({result:{error:jl},stack:p});let l=[bt].includes(r),f=c?r:t.winningSide&&he||un,g=Hn({...t,matchUpStatusCodes:c&&e||[],matchUpStatus:f,context:p,removeScore:l});return _({result:g,stack:p})}function xG({structure:t,matchUp:e,inContextMatchUp:r}){let{drawPositions:n}=e,{positionAssignments:o}=ge({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 eT({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=>dt(n));return{groupValueGroups:e,groupValueNumbers:r}}function UO({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=>se.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:E=0,side1Score:P=0,side2Score:A=0}=T;(S.matchUpStatus===he||S.winningSide||T.winningSide)&&(P||A?(s[0]+=P,s[1]+=A):(y||E)&&T.winningSide&&(s[T.winningSide-1]+=1))})}):Array.isArray(u)&&i.forEach(S=>{if(S.winningSide){let T=S.collectionPosition,y=wG({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,E)=>y>=l.valueGoal?E+1:T,0);else{let T=Math.floor(t.matchUpCount/2)+1;S=h.reduce((y,E,P)=>E>=T?P+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 wG({collectionDefinition:t,collectionPosition:e}){return(t.collectionValueProfiles||[])?.find(o=>o.collectionPosition===e)?.matchUpValue}function Dc(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,E)=>y+E)))return{error:V};if(!s)return{error:Tr};let c=We({matchUp:s,drawDefinition:n,structure:i,event:a})?.tieFormat||t?.tieFormat;if(!c)return{error:vs};let u=ur({tieFormat:c});if(u.error)return u;let p=c?.collectionDefinitions||[],m=s?.tieMatchUps??[],d=[0,0],{groupValueGroups:l,groupValueNumbers:f}=eT(c);for(let y of p)UO({collectionDefinition:y,groupValueNumbers:f,groupValueGroups:l,sideTieValues:d,tieMatchUps:m});for(let y of f){let E=l[y],{allGroupMatchUpsCompleted:P,matchUpCount:A,winCriteria:U,groupValue:N,sideWins:D,values:M}=E,R;if(U?.aggregateValue)P&&M[0]!==M[1]&&(R=M[0]>M[1]?1:2);else if(U?.valueGoal)R=M.reduce((b,v,O)=>v>=U.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,E)=>(y||0)+e[E]),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:E,tallyDirectives:P}=c.winCriteria;if(y?T=g.map((U,N)=>({sideNumber:N+1,points:U})).find(({points:U})=>U>=y)?.sideNumber:E&&m.every(U=>U.matchUpStatus&&se.includes(U.matchUpStatus)||U.winningSide)&&g[0]!==g[1]&&(T=g[0]>g[1]?1:2),!T&&P){let A=s.matchUpId,U=s.hasContext?s:o?.drawMatchUps?.[A]||n&&Bt({inContext:!0,drawDefinition:n,matchUpId:A})?.matchUp;if(U){let{completedTieMatchUps:N,order:D}=ba({matchUps:[U]});if(N&&D?.length){let M=D[0].participantId;T=U.sides.find(({participantId:R})=>R===M)?.sideNumber}}}}return T&&(I.winningSide=T),{scoreStringSide1:h,scoreStringSide2:S,winningSide:T,set:I}}function va({inContextDualMatchUp:t,drawDefinition:e,tournamentId:r,dualMatchUp:n,eventId:o}){if(n){t||(t=Bt({matchUpId:n.matchUpId,inContext:!0,drawDefinition:e})?.matchUp);let{extension:i}=mt({element:e,name:Co}),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 sr(t){if(t)return J(t,!1,!0)}function _g(t){let e=et(t,[{[Re]:!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 rT({tournamentRecords:t,eventId:e,drawId:r}){let{tournamentIdMap:n}=_g({tournamentRecords:t});return(n?Object.keys(n):[]).find(i=>e&&n?.[i].includes(e)||r&&n?.[i].includes(r))}function lo(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&&rT({tournamentRecords:c,...t});let p=u&&c[u];if(!p)return{error:$};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:lr};va({tournamentId:p?.tournamentId,eventId:a?.eventId,dualMatchUp:d,drawDefinition:r});let{extension:f}=mt({name:ha,element:d});if(f?.value)if(o)gr({element:d,name:ha});else return{...C,score:d.score};let g=We({drawDefinition:r,structure:l,matchUp:d,event:a})?.tieFormat;d.tieFormat=sr(g);let I=Dc({drawDefinition:r,matchUpsMap:i,structure:l,matchUp:d,event:a}),{winningSide:h,set:S,scoreStringSide1:T,scoreStringSide2:y}=I,E=S?.side1Score||S?.side2Score;if(e&&!d.score&&!E)return{...C};let P={scoreStringSide1:T,scoreStringSide2:y,sets:S?[S]:[]},A=h&&[1,2].includes(h),U=A&&he||pg({matchUpStatus:n??d.matchUpStatus,tieMatchUps:d.tieMatchUps,winningSide:d.winningSide,score:P})&&Gn||Xt,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&&se.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 Hn({appliedPolicies:t.appliedPolicies,matchUpStatus:U,score:P,removeWinningSide:N,tournamentRecord:p,drawDefinition:r,removeScore:o,winningSide:h,matchUpId:s,matchUp:d,event:a}),{...C,score:P,removeWinningSide:N,tieFormatRemoved:M,winningSide:h}}function PO({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}=ge({structureId:I,drawDefinition:c}),E=T?.find(R=>R.drawPosition===o)?.participantId,P=s.target.structureId,{positionAssignments:A}=ge({structureId:P,drawDefinition:c}),N=A?.find(R=>R.participantId===E)?.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(E&&s.target.roundNumber===1&&M)Bn({drawPosition:g,participantId:E,structureId:P,inContextDrawMatchUps:e,sourceMatchUpStatus:n,tournamentRecord:i,drawDefinition:c,matchUpsMap:m,event:d});else if(E&&D?.length){let R=D.pop();R&&Bn({participantId:E,structureId:P,inContextDrawMatchUps:e,sourceMatchUpStatus:n,tournamentRecord:i,drawDefinition:c,drawPosition:R,matchUpsMap:m,event:d})}else if(N){let R=Tc({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!==P){let R=S.seedAssignments.find(({participantId:v})=>v===E),b=R?.participantId;R&&b&&Ks({eventId:u?.eventId,structureId:P,...R,tournamentRecord:i,drawDefinition:c,participantId:b})}}else{let f=Tc({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:E})=>E===u.matchUpId),T=[1,2].map(E=>({...S.sides?.find(A=>A.sideNumber===E)||{},sideNumber:E}));S.sides=T;let y=S.sides.find(E=>E.sideNumber===h);if(y){let E=f.lineUp?.filter(P=>P?.participantId);y.lineUp=yd({lineUp:E}),gt({tournamentId:i?.tournamentId,eventId:u?.eventId,matchUp:S,context:l,drawDefinition:c})}}}return{...C}}function DO(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===wn&&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:E}=yt({afterRecoveryTimes:!1,inContext:!0,drawDefinition:c,structure:y,event:d}),A=E.filter(W=>W.drawPositions?.includes(i)).filter(W=>{let q=W.sides.find(B=>B.drawPosition===i),Y=W.matchUpStatus===bt||W.matchUpStatus===Rt&&!Ie(W);return q?.sideNumber===W.winningSide&&!Y}),U=f===wn&&A.length===0,{positionAssignments:N}=ge({structureId:T,drawDefinition:c}),M=N?.find(W=>W.drawPosition===i)?.participantId,R=a.target.structureId,{positionAssignments:b}=ge({structureId:R,drawDefinition:c}),v=b?.filter(({drawPosition:W})=>g.includes(W));if(v?.some(W=>W.participantId===M))return{...C};let x=v?.filter(W=>{let q=g.includes(W.drawPosition),Y=!W.participantId&&!W.bye&&!W.qualifier;return q&&Y}).map(W=>W.drawPosition),F=x?.includes(h),w=a.target.roundNumber>1&&x?.length,L=a.target.roundNumber===1&&F;if(I){let W=G();if(W.error)return _({result:W,stack:l})}else if(L){let W=H();if(W.error)return _({result:W,stack:l})}else if(M&&w){x.sort(le);let W=x[0],q=Bn({participantId:M,structureId:R,drawPosition:W,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?Cs:PC},stack:l});if(y?.seedAssignments&&y.structureId!==R){let W=y.seedAssignments.find(({participantId:Y})=>Y===M),q=W?.participantId;W&&q&&Ks({eventId:u?.eventId,structureId:R,...W,tournamentRecord:s,drawDefinition:c,participantId:q})}if(p&&n){let W=p.sides?.find(q=>q.sideNumber===3-n);if(W?.lineUp){let{roundNumber:q,eventId:Y}=u,{roundPosition:B}=p,K=q===1?2-B%2:1,X=m?.drawMatchUps?.find(({matchUpId:z})=>z===u.matchUpId),j=[1,2].map(z=>({...X.sides?.find(ut=>ut.sideNumber===z)||{},sideNumber:z}));X.sides=j;let ot=X.sides.find(z=>z.sideNumber===K);ot&&(ot.lineUp=yd({lineUp:W.lineUp}),gt({tournamentId:s?.tournamentId,matchUp:X,context:l,drawDefinition:c,eventId:Y}))}}return{...C};function G(){let W="loserLinkFedFMLC";return U?_({result:H(),stack:W}):_({result:k(),stack:W})}function k(){let W=Hr({drawPosition:S,structureId:R,tournamentRecord:s,drawDefinition:c,event:d});return _({result:W,stack:"assignLoserPositionBye"})}function H(){let W=M?Bn({drawPosition:h,participantId:M,structureId:R,inContextDrawMatchUps:r,sourceMatchUpStatus:o,tournamentRecord:s,drawDefinition:c,matchUpsMap:m,event:d}):{error:ie};return _({result:W,stack:"assignLoserDrawPosition"})}}function nT(t){let e="directParticipants",r=bd(t);if(r.error)return _({result:r,stack:e});let n=Da({matchUpStatus:t.matchUpStatus}),{dualWinningSideChange:o,projectedWinningSide:i,inContextDrawMatchUps:s,tournamentRecord:a,drawDefinition:c,matchUpStatus:u,dualMatchUp:p,matchUpsMap:m,winningSide:d,targetData:l,matchUpId:f,structure:g,matchUp:I,event:h}=t,S=!!I.collectionId,T=pr({structure:g}),y=I.drawPositions,E;if(S){let{matchUpTieId:P,matchUpsMap:A}=t,U=lo({appliedPolicies:t.appliedPolicies,matchUpId:P,tournamentRecord:a,drawDefinition:c,matchUpsMap:A,event:h});if(E=U&&{tieMatchUpResult:U},y=s.find(({matchUpId:D})=>D===P)?.drawPositions,!o)return _({result:{...C,...E},stack:e})}if(T)return _({result:{...C,...E},stack:e});if(y){let P=i?i-1:d-1,A=1-P,U=y[P],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 w=PO({sourceMatchUpStatus:n&&u||he,winnerMatchUpDrawPositionIndex:b,sourceMatchUpId:f,inContextDrawMatchUps:s,projectedWinningSide:i,winningDrawPosition:U,tournamentRecord:a,winnerTargetLink:M,drawDefinition:c,winnerMatchUp:O,dualMatchUp:p,matchUpsMap:m,event:h});if(w.error)return _({result:w,stack:e})}if(x){let w=DO({sourceMatchUpStatus:n&&u||he,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(w.error)return _({result:w,stack:e})}if(F){let w=F.drawPositions||[],L=Math.min(...w.filter(Boolean)),G=R.target.structureId,k=Hr({drawPosition:L,structureId:G,tournamentRecord:a,drawDefinition:c,event:h});if(k.error)return _({result:k,stack:e})}}else return _({result:{error:Ya},stack:e});return _({result:{...C,...E},stack:e})}function vd(t){let e="genPlayoffStructure";if(!t.drawDefinition)return _({result:{error:Z},stack:e});let r=Cu(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:wt},stack:e});if(y.structureType===Ve||y.structures)return pO({sourceStructureId:y.structureId,...t,...r,drawDefinition:T});let{playoffRoundsRanges:E,playoffRounds:P}=r,{playoffPositionsReturned:A,error:U,playoffSourceRounds:N,playoffRoundsRanges:D}=YS(t);if(U)return _({result:{error:U},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)&&dt(j)).filter(Boolean);if(b){if(!Array.isArray(b))return _({result:{error:V},context:{validRoundNumbers:b},stack:e});b.forEach(j=>{if(!P?.includes(j))return _({result:{error:V},context:{roundNumber:j},stack:e})})}u&&u.forEach(j=>{if(!A?.includes(j))return _({result:{error:V},context:{playoffPosition:j},stack:e})});let v=b||N,O=b?E:D,x=[],F=[];for(let j of v??[]){let ot=O?.find($t=>$t.roundNumber===j);if(!ot)return _({result:{error:V},context:{roundNumber:j},stack:e});let z=ot.finishingPositions.length,Q=Math.min(...ot.finishingPositions)-1,ut=2,it=j&&M?.[j]&&ut+M[j]-1,Et=Ac({exitProfile:`0-${j}`,addNameBaseToAttributeName:o,playoffStructureNameBase:i,finishingPositionOffset:Q,playoffAttributes:c,exitProfileLimit:d,stage:fe,roundOffset:0,drawDefinition:T,sequenceLimit:it,stageSequence:ut,drawSize:z,idPrefix:g,isMock:I,uuids:S,finishingPositionNaming:s,finishingPositionLimit:a,roundOffsetLimit:p});if(Et.error)return _({result:Et,stack:e});let{structures:_t,links:Ae}=Et;if(_t?.length&&x.push(..._t),Ae?.length&&F.push(...Ae),Et.structureId&&j){let $t={linkType:oo,source:{structureId:n,roundNumber:j},target:{structureId:Et.structureId,feedProfile:En,roundNumber:1}};F.push($t)}}if(!x.length)return _({result:{error:V},info:"No structures generated",stack:e});T.structures.push(...x),T.links.push(...F);let{matchUps:w,matchUpsMap:L}=ce({inContext:!0,drawDefinition:T}),G=x.map(({structureId:j})=>j),k=w?.filter(({structureId:j})=>G.includes(j)).map(Ue),H=L?.drawMatchUps?.filter(({matchUpId:j})=>k?.includes(j));if(H?.length){let j=We({drawDefinition:T,event:h})?.tieFormat;j&&H.forEach(ot=>{let{tieMatchUps:z}=bi({matchUp:ot,tieFormat:j,isMock:I});Object.assign(ot,{tieMatchUps:z,matchUpType:Wt})})}w?.filter(j=>ls({matchUp:j})&&j.structureId===n)?.forEach(j=>{let{matchUpId:ot,score:z,winningSide:Q}=j,ut=mr({inContextDrawMatchUps:w,drawDefinition:T,matchUpId:ot}),it=nT({inContextDrawMatchUps:w,tournamentRecord:m,drawDefinition:T,matchUpsMap:L,winningSide:Q,targetData:ut,matchUpId:ot,structure:y,matchUp:j,score:z,event:h});it.error&&console.log(it.error)}),w?.filter(j=>j.matchUpStatus===Nt&&j.structureId===n)?.forEach(j=>{let{matchUpId:ot}=j,z=mr({inContextDrawMatchUps:w,drawDefinition:T,matchUpId:ot}),{targetLinks:{loserTargetLink:Q},targetMatchUps:{loserMatchUpDrawPositionIndex:ut,loserMatchUp:it}}=z;if(Q&&it){let Et=Q.target.structureId,_t=it.drawPositions[ut],Ae=Hr({drawPosition:_t,structureId:Et,tournamentRecord:m,drawDefinition:T,event:h});Ae.error&&console.log(Ae.error)}});let Y=[],B=Ki({inContextDrawMatchUps:w,drawDefinition:T,matchUpsMap:L}).goesToMap,{structure:K}=at({drawDefinition:t.drawDefinition,structureId:n}),{matchUps:X}=yt({structure:K});return X.forEach(j=>{let ot=B?.loserMatchUpIds[j.matchUpId];if(ot&&j.loserMatchUpId!==ot){j.loserMatchUpId=ot;let Q={tournamentId:m?.tournamentId,eventId:t.event?.eventId,context:e,matchUp:j};Y.push(Q)}let z=B?.winnerMatchUpIds[j.matchUpId];if(z&&j.winnerMatchUpId!==z){j.winnerMatchUpId=z;let Q={tournamentId:m?.tournamentId,eventId:t.event?.eventId,context:e,matchUp:j};Y.push(Q)}}),{structures:x,matchUpModifications:Y,links:F,drawDefinition:T,...C}}function oT({element:t}){if(!t)return{error:V};if(!t.timeItems)return{};if(!Array.isArray(t.timeItems))return{error:V};let e=(r,n)=>(o,i)=>(i[r]&&(o[i[r]]=i[n]),o);return t.timeItems.reduce(e("itemType","itemValue"),{})}function to(t){let{duplicateValues:e=!0,creationTime:r=!0,removePriorValues:n,timeItem:o}=t;if(!o)return{error:of};let i=Zh(t);if(i.error)return i;if(!(ht(o)&&Vt(o.itemType)&&Object.keys(o).includes("itemValue")))return{error:nf};if(!i.timeItems)i.timeItems=[];else if(LG({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 LG({element:t,duplicateValues:e,timeItem:r}){let{itemType:n,itemSubTypes:o,itemValue:i}=r,s=n&&en({itemSubTypes:o,itemType:n,element:t})?.timeItem;return s&&JSON.stringify(s?.itemValue)===JSON.stringify(i)&&!e}function xg({creationTime:t=!0,removePriorValues:e,tournamentRecord:r,duplicateValues:n,participantId:o,timeItem:i}){if(!r)return{error:$};if(!o)return{error:ie};let s=yo({tournamentRecord:r,participantId:o});return s.error?s:to({element:s.participant,removePriorValues:e,duplicateValues:n,creationTime:t,timeItem:i})}function Nc(t){let{removePriorValues:e,tournamentRecord:r,duplicateValues:n,creationTime:o,timeItem:i}=t;if(!r)return{error:$};let s=to({element:r,removePriorValues:e,duplicateValues:n,creationTime:o,timeItem:i});if(s.error)return s;let a=oT({element:r});return lt({payload:{parentOrganisation:r.parentOrganisation,tournamentId:r.tournamentId,timeItemValues:a},topic:Wi}),s}function Xi(t){let{removePriorValues:e,duplicateValues:r,creationTime:n,timeItem:o,event:i}=t;return i?to({removePriorValues:e,duplicateValues:r,element:i,creationTime:n,timeItem:o}):{error:jr}}function XP(t){return Lg({...t,itemType:"attachConsolationStructures"})}function wg(t){return Lg({...t,itemType:"attachPlayoffStructures"})}function Lg({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:V},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:pf},info:"playoff structure exists",stack:a});i.length&&n.links?.push(...i);let m=o.map(({structureId:h})=>h),d=n.structures?.map(({structureId:h})=>h);n.structures=(n.structures??[]).map(h=>m.includes(h.structureId)?o.find(({structureId:S})=>S===h.structureId):h);let l=o?.filter(({structureId:h})=>!d?.includes(h));l.length&&n.structures.push(...l),Ki({drawDefinition:n});let f=o.map(h=>yt({structure:h})?.matchUps||[]).flat();vo({tournamentId:r?.tournamentId,eventId:s?.eventId,drawDefinition:n,matchUps:f});let g=o.map(({structureId:h})=>h);if(vt({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:E,...P}=h[y.matchUpId].matchUp;if(Object.assign(y,P),E?.length){let A={};E.forEach(U=>h[U.matchUpId]=U),y.tieMatchUps.forEach(U=>Object.assign(U,A[U.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};to({element:r,timeItem:S})}return{...C,addedStructureIds:I}}function Bp(t){let{structures:e,links:r,matchUpModifications:n,error:o}=vd(t);if(o)return{error:o};let i=t.drawDefinition;return wg({tournamentId:t.tournamentRecord?.tournamentId,eventId:t.event?.eventId||t.eventId,matchUpModifications:n,drawDefinition:i,structures:e,links:r})}function Ji(t){let e=et(t,[{_anyOf:{[Re]:!1,[ne]:!1,[Ce]:!1,[so]:!1},[Mf]:!0}]);if(e.error)return e;let r=[],n=t.drawDefinition??t.event??((t.tournamentId||!t.tournamentRecords)&&t.tournamentRecord);if(n){let o=NO(t,n);if(o.error)return o;r.push(...o?.applied??[]),t.drawDefinition&&vt({drawDefinition:t.drawDefinition,tournamentId:t.tournamentId})}else if(t.tournamentRecords){let o=Object.keys(t.tournamentRecords);if(!o.length)return{error:$};for(let i of o){let s=t.tournamentRecords[i],a=NO(t,s);if(a.error)return a;r.push(...a?.applied??[])}}else return{error:$};return r.length?{...C,applied:r}:{error:HI}}function NO(t,e){let r=Tt(t).appliedPolicies??{};e.extensions||(e.extensions=[]);let n=[],o=Object.keys(t.policyDefinitions);if(!o.length)return{error:Xu};for(let i of o)if(!r[i]||t.allowReplacement){let s=t.policyDefinitions[i];if(!s)continue;if(!ht(s))return{error:V};let{policyName:a,...c}=s;if(!c||!Object.keys(c).length||a&&!Vt(a))return{error:V};r[i]=t.policyDefinitions[i],n.push(i)}return n?.length?{...Ut({element:e,extension:{name:iu,value:r}}),applied:n}:{applied:n,error:HI}}function Fg({tournamentRecord:t,drawDefinition:e,flightProfile:r,drawName:n,drawId:o,event:i}){if(!n||typeof n!="string")return _({result:{error:V},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:cn,value:{...r,flights:r.flights}};Ro({event:i,extension:a})}return e&&(e.drawName=n,vt({tournamentId:t?.tournamentId,drawDefinition:e})),!s&&!e?{error:Z}:{...C,flight:s}}function JP({tournamentRecord:t,drawDefinition:e,drawUpdates:r,drawId:n,event:o}){if(!ht(r))return{error:V};let i=Ht({event:o}).flightProfile,s=r.drawName&&Fg({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:cn,value:{...i,flights:i.flights}};Ro({event:o,extension:c})}return e&&(r.policyDefinitions&&Ji({policyDefinitions:r.policyDefinitions,drawDefinition:e}),vt({tournamentId:t?.tournamentId,drawDefinition:e})),{...C}}function ZP({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,rt].includes(c))&&(s.positionAssignments=a.map(d=>(delete d.participantId,d)),s.seedAssignments=[]);let{matchUps:p,isRoundRobin:m}=yt({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,Ou),f&&f>1&&I.drawPositions?.length&&!m){let h=g?.map(({drawPosition:T,participantFed:y})=>!y&&T).filter(Boolean),S=I.drawPositions.map(T=>h.includes(T)?void 0:T);I.drawPositions=S}e?delete I.timeItems:I.timeItems?.length&&(I.timeItems=I.timeItems.filter(h=>h.itemType&&![po,jo,ji,sg,Yi,qi].includes(h.itemType))),gt({tournamentId:t?.tournamentId,context:"resetDrawDefiniton",drawDefinition:r,matchUp:I})}}}r.extensions=r.extensions.filter(s=>s.name!==ic);let i=(r.structures||[]).map(({structureId:s})=>s);return vt({drawDefinition:r,structureIds:i}),{...C}}function _u({tournamentRecord:t}){if(!t)return{error:$};let e={positionsNoOutcomes:[],canBePruned:[],matchPlay:[],inactive:[],drawAnalysis:{}},r={};return(t.events?.map(o=>{let i=o.eventId;return r[i]=o,(o?.drawDefinitions||[]).map(s=>({drawDefinition:s,eventId:i}))}).flat().filter(Boolean)).forEach(({drawDefinition:o,eventId:i})=>{let s=0,a=0,c=0,{allStructuresLinked:u}=Nu({drawDefinition:o}),p=r[i],d=(o?.structures||[]).map(E=>{let{stage:P,stageSequence:A,structureId:U}=E,N=Gs[P],{inContextStructureMatchUps:D}=Na({drawDefinition:o,structure:E,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}=Ct({structure:E}),O=v?.filter(({participantId:q})=>q);s+=O?.length??0;let x=(v?.length??0)-(O?.length??0),{roundMatchUps:F,roundProfile:w,roundNumbers:L,maxMatchUpsCount:G}=Ke({matchUps:D}),k=w&&Object.keys(w).filter(q=>!w[q].inactiveRound).map(q=>parseInt(q)),H=w&&Object.keys(w).filter(q=>w[q].inactiveRound).map(q=>parseInt(q)),W=w&&Object.values(w).every(q=>q.inactiveRound);return{positionsAssignedCount:O?.length??0,maxWinningSideFirstRoundPosition:b,unassignedPositionsCount:x,inactiveStructure:W,maxMatchUpsCount:G,inactiveRounds:H,roundMatchUps:F,activeRounds:k,roundNumbers:L,roundProfile:w,structureId:U,stageSequence:A,orderNumber:N,stage:P}}),l=d.find(E=>E.orderNumber===2&&E.stageSequence===1),f=d.filter(({inactiveStructure:E})=>!E).length,{links:g}=js({structureId:l.structureId,drawDefinition:o}),I=dt(l.activeRounds[0])===1&&l.activeRounds.length===1&&f===1,h=d?.every(({inactiveStructure:E})=>E),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 tD({matchPlayDrawPositions:t=!0,tournamentRecord:e,drawDefinition:r,drawId:n}){if(!e)return{error:$};if(!r)return{error:Z};let o=[],{drawsAnalysis:i}=_u({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:rt}),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(Ue),d=p.map(Ue).filter(l=>!m.includes(l));if(s){let l=o.filter(({roundNumber:T})=>!u.inactiveRounds.includes(T)).filter(({winningSide:T})=>T),f=l.map(Ue),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}Rn({tournamentId:e?.tournamentId,matchUpIds:d,drawDefinition:r}),vt({drawDefinition:r})}return{...C,matchUps:o}}function eD({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:bs};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:np};{let c=Bn({tournamentRecord:t,drawDefinition:e,participantId:r,drawPosition:n,structureId:o,event:s});if(c.error)return c}}return{...C}}function iT(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:wt};let o=r.structures?.find(c=>c.structureId===n);if(!o)return{error:wt};let i=o?.matchUps,s=i?.find(c=>!!c.roundPosition);if(o.structures||s||o.finishingPosition===Bi)return{error:Zo};let a=i.filter(({roundNumber:c})=>t.roundNumbers?.includes(c)).map(Ue);return e=e.filter(c=>!a.includes(c)),t.roundNumbers&&!e.length&&(e=a),{existingMatchUps:i,matchUpIds:e,structureId:n,structure:o}}function rD(t){let e=et(t,[{[Ce]:!0},{[Vs]:{[nc]:!1,roundNumbers:!1},[Fr]:V,[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=iT(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(Ue),I=f.map(({tieMatchUps:h})=>h?.map(Ue)).filter(Boolean).flat();if(g.length){u.matchUps=(u.matchUps??[]).filter(({matchUpId:T})=>!g.includes(T)),Rn({tournamentId:i?.tournamentId,matchUpIds:[...I,...g],action:"deleteAdHocMatchUps",eventId:a?.eventId,drawDefinition:s});let h=pt(u.matchUps.map(Br("roundNumber"))),S=TC(h);if(S.length){S.reverse();for(let T of S)u.matchUps.forEach(y=>{y.roundNumber&&y.roundNumber>T&&(y.roundNumber-=1,gt({tournamentId:i?.tournamentId,context:["adHoc round deletion"],eventId:a?.eventId,drawDefinition:s,matchUp:y}))})}if(l.length){u.positionAssignments=pt(u.matchUps.flatMap(N=>(N.sides??[]).map(D=>D.participantId)).filter(Boolean)).map(N=>({participantId:N}));let T=u?.matchUpFormat??s?.matchUpFormat??a?.matchUpFormat,E=c.existingMatchUps.some(N=>N.matchUpType===xr)?{matchUpTypes:[xr]}:void 0,{matchUps:P}=yt({afterRecoveryTimes:!1,inContext:!0,matchUpFilters:E,structure:u,event:a});pr({structure:u})&&(u.positionAssignments=pt(P.flatMap(N=>(N.sides??[]).map(D=>D.participantId)).filter(Boolean)).map(N=>({participantId:N})));let U=Cd({positionAssignments:u.positionAssignments,tournamentRecord:i,drawDefinition:s,matchUpFormat:T,matchUps:P,event:a});U.error&&console.log(U)}vt({structureIds:[p],eventId:a?.eventId,drawDefinition:s})}return!g.length&&d.length?{error:Xa}:{...C,deletedMatchUpsCount:[...g,...I].length}}function nD({removeCompletedMatchUps:t,tournamentRecord:e,drawDefinition:r,structureId:n,roundNumber:o,event:i}){if(!e)return{error:$};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:Zo}:pr({structure:a})?FG({tournamentId:e.tournamentId,removeCompletedMatchUps:t,eventId:i.eventId,drawDefinition:r,roundNumber:o,structure:a}):(console.log("not implemented"),{...C})}function FG({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(le).includes(n)){let m=s.filter(d=>{let l=d.roundNumber===n&&(!se.includes(d.matchUpStatus)||t);return l&&(c.push(d.matchUpId),d.tieMatchUps&&a.push(...d.tieMatchUps.map(Ue))),!l});c.length&&(Rn({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 Od(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:V,info:ai("matchUps")};let a=n.structures?.find(l=>l.structureId===s);if(!a)return{error:wt};let u=(a?.matchUps).find(l=>!!l.roundPosition);if(a.structures||u||a.finishingPosition===Bi)return{error:Zo};let p=ye({tournamentRecord:r,inContext:!1})?.matchUps?.map(Ue)??[],m=o.map(Ue);if(ke(p,m))return{error:FE,info:"One or more matchUpIds already present in tournamentRecord"};a.matchUps.push(...o);let d=o.map(({tieMatchUps:l})=>l).filter(Boolean).flat();return e||(vo({tournamentId:r?.tournamentId,matchUps:[...d,...o],eventId:i?.eventId,drawDefinition:n}),vt({drawDefinition:n,structureIds:[s]})),{...C}}function oD({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:bs};let{structure:s}=at({drawDefinition:e,structureId:n});if(!s)return{error:wt};let a=s;s.structures&&s.structureType===Ve&&(a=s.structures?.find(g=>g.positionAssignments?.find(I=>I.drawPosition===r)));let c=a?.positionAssignments,u=c?.find(g=>g.drawPosition===r);u&&Ut({element:u,extension:{name:sc,value:o}});let d=(i?.eventType===Wt||e.matchUpType===Wt||(i?.tieFormat??e?.tieFormat??s?.tieFormat))&&{matchUpTypes:[Wt]},{matchUps:l}=yt({structure:a,afterRecoveryTimes:!1,inContext:!0,matchUpFilters:d,event:i}),f=s?.matchUpFormat??e.matchUpFormat;return Cd({positionAssignments:c,tournamentRecord:t,drawDefinition:e,matchUpFormat:f,matchUps:l,event:i}),vt({drawDefinition:e,structureIds:[n]}),{...C}}var ID={};Jt(ID,{addGoesTo:()=>Ki,allPlayoffPositionsFilled:()=>FS,checkValidEntries:()=>wd,findDrawDefinition:()=>uT,getAssignedParticipantIds:()=>Ci,getAvailableMatchUpsCount:()=>_d,getAvailablePlayoffProfiles:()=>Cu,getDrawDefinitionTimeItem:()=>tS,getDrawParticipantRepresentativeIds:()=>aT,getDrawStructures:()=>gn,getDrawTypeCoercion:()=>xu,getEligibleVoluntaryConsolationParticipants:()=>sT,getMatchUpsMap:()=>Me,getParticipantIdFinishingPositions:()=>cT,getPositionAssignments:()=>Hp,getPositionsPlayedOff:()=>Ec,getRandomQualifierList:()=>ET,getSeedingThresholds:()=>MS,getSeedsCount:()=>wu,getStructureSeedAssignments:()=>nn,getTeamLineUp:()=>ds,getValidGroupSizes:()=>Op,isAdHoc:()=>pr,isCompletedStructure:()=>Eo,isValidForQualifying:()=>UT,positionActions:()=>AT});function sT({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=[rt,fe];r&&f.push(ct);let g=l?.eventType?{matchUpTypes:[l.eventType]}:void 0,I=a?.matchUpType?{matchUpTypes:[a.matchUpType]}:void 0,h=e&&l?Xn({contextFilters:{stages:f},matchUpFilters:g,tournamentRecord:s,inContext:!0,event:l})?.matchUps??[]:ir({contextFilters:{stages:f},matchUpFilters:I,tournamentRecord:s,inContext:!0,drawDefinition:a})?.matchUps??[],T=Pi({stage:$e,drawDefinition:a}).map(({participantId:L})=>L),y={},E={},P={},A={};o||(o=_o({policyTypes:[Lh],tournamentRecord:s,drawDefinition:a,event:l}).policyDefinitions);let U=o?.[Lh];t=t.length&&t||U?.excludedMatchUpStatuses||[],e=e??U?.includeEventParticipants,m=m??U?.allEntries,n=n??U?.finishingRoundLimit,i=i??U?.roundNumberLimit,c=c??U?.matchUpsLimit,u===void 0&&(u=U?.requirePlay!==void 0?U.requirePlay:!0),p===void 0&&(p=U?.requireLoss!==void 0?U.requireLoss:!0),d=d??U?.winsLimit;for(let L of h){if(u&&L.winningSide&&![1,2].includes(L.winningSide)&&L.matchUpStatus!==Te||L.finishingRound&&n&&L.finishingRound>=n||L.finishingRound&&i&&L.finishingRound<=i)continue;let G=L.sides?.find(({sideNumber:H})=>L.winningSide&&H===3-L.winningSide),k=L.sides?.find(({sideNumber:H})=>L.winningSide&&H===L.winningSide);if(L.sides?.forEach(H=>{let W=H?.participant?.participantId;W&&(P[W]=H.participant,L.matchUpStatus===Te&&!u&&(E[W]=H.participant,y[W]||(y[W]=0),(!L.matchUpStatus||!t.includes(L.matchUpStatus))&&(y[W]+=1)))}),G?.participant){let H=G.participant.participantId;E[H]=G.participant,y[H]||(y[H]=0),L.matchUpStatus&&!t.includes(L.matchUpStatus)&&(y[H]+=1)}if(k?.participant){let H=k.participant.participantId;A[H]||(A[H]=0),A[H]+=1,y[H]||(y[H]=0),L.matchUpStatus&&!t.includes(L.matchUpStatus)&&(y[H]+=1)}}let N=s?.participants&&!u&&!p&&m,D=N?((e&&l?l.entries:a.entries)??[]).filter(L=>![uo,Gr].includes(L.entryStatus)).map(({participantId:L})=>L):[],M=Object.keys(E),R=N?(s?.participants??[]).filter(({participantId:L})=>D.includes(L)):p&&Object.values(E)||Object.values(P),b=L=>!p||M.includes(L),v=L=>!u||(y[L]||0)>=0,O=L=>!d||(A[L]||0)<=d,x=L=>!c||y[L]<=c,F=L=>!T.includes(L);return{eligibleParticipants:R.filter(L=>b(L.participantId)&&v(L.participantId)&&O(L.participantId)&&x(L.participantId)&&F(L.participantId)).map(L=>({...L,individualParticipants:L.individualParticipantIds?.map(G=>s?.participants?.find(k=>k.participantId===G))})),losingParticipantIds:M,...C}}function _d(t){let e=et(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:wt};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===Bi)return{error:Zo};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 aT({drawDefinition:t}){let e=mt({name:"participantRepresentatives",element:t});return e.error?e:{representativeParticipantIds:e.extension?.value||[]}}function MO({tournamentParticipants:t,drawDefinition:e,event:r}){if(!e)return{error:Z};let n=ce({tournamentParticipants:t,inContext:!0,drawDefinition:e,event:r}),o=J(n.matchUps,!1,!0),i=pt(o.reduce((a,c)=>a.concat(...c.sides.map(u=>u.participantId).filter(Boolean)),[])),s=Object.assign({},...i.map(a=>{let c=o.filter(u=>u.sides.map(m=>m.participantId).filter(Boolean).includes(a));return{[a]:c}}));return{participantIds:i,participantIdMatchUps:s}}function cT({byeAdvancements:t=!1,tournamentRecord:e,drawDefinition:r}){if(!r)return{error:Z};let{participantIds:n,participantIdMatchUps:o}=MO({tournamentParticipants:e?.participants,drawDefinition:r}),i=n?.map(s=>{let c=o[s].filter(d=>[he,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 Fo({tournamentRecords:t,tournamentRecord:e,tournamentId:r,drawId:n}){if(!e&&!t)return{error:$};if(!n)return{error:sn};if(!e&&t){if(typeof r!="string"&&(r=rT({tournamentRecords:t,drawId:n}),!r))return{error:pa};if(e=t[r],!e)return{error:$}}let o=e&&ze({tournamentRecord:e,drawId:n});return o?.drawDefinition?{drawDefinition:o.drawDefinition,event:o.event,tournamentRecord:e,...C}:_({result:{error:Cr},stack:"findDrawDefinition"})}function uT(t){let{drawDefinition:e,error:r}=Fo(t);return r?{error:r}:{drawDefinition:J(e)}}function RO({tournamentParticipants:t,returnParticipants:e,drawPosition:r,participant:n,drawId:o,event:i}){let s=i?.entries?.filter(({entryStatus:a})=>[Gr,Ui].includes(a)).map(({participantId:a})=>a)||[];if(s.length){let a=n.individualParticipantIds,c=e?t.filter(({participantId:m})=>s.includes(m)):void 0,u=e?t.filter(({participantId:m})=>a.includes(m)):void 0;return{validModifyAssignedPairAction:nt({payload:{participantId:n.participantId,replacementIndividualParticipantId:void 0,existingIndividualParticipantId:void 0,drawPosition:r,drawId:o},method:Jv,availableIndividualParticipantIds:s,availableIndividualParticipants:c,existingIndividualParticipantIds:a,existingIndividualParticipants:u,type:Ng},!1,!1,!0)}}return{}}function vi(t){let{inContextDrawMatchUps:e,targetData:r,drawDefinition:n,relevantLink:o}=t;if(o?.linkCondition===wn&&r?.matchUp?.matchUpStatus===Nt)return!1;let{targetMatchUps:{loserMatchUp:s,winnerMatchUp:a},targetLinks:c}=r,u=s&&mr({matchUpId:s.matchUpId,inContextDrawMatchUps:e,drawDefinition:n}),p=u?.targetMatchUps?.loserMatchUp,m=u?.targetMatchUps?.loserMatchUpDrawPositionIndex,d=p?.sides[m]?.participant,l=[Rt,bt].includes(s?.matchUpStatus)&&!d,f=a?.drawPositions?.filter(Boolean).length||0;if(s?.winningSide&&!l||a?.winningSide&&f===2&&(!a.feedRound||![bt,Rt].includes(a?.matchUpStatus)))return!0;let g=a&&mr({matchUpId:a.matchUpId,inContextDrawMatchUps:e,drawDefinition:n}),I=u&&vi({relevantLink:c?.loserTargetLink,targetData:u,inContextDrawMatchUps:e,drawDefinition:n});return!!(g&&vi({targetData:g,inContextDrawMatchUps:e,drawDefinition:n})||I)}var pT={[zn]:{policyName:"positionActionsDefault",enabledStructures:[{stages:[ct,rt],stageSequences:[1],enabledActions:[],disabledActions:[]},{stages:[],stageSequences:[],enabledActions:[Mu,Xs,Lp,Qs],disabledActions:[]}],disbledStructures:[],otherFlightEntries:!1,activePositionOverrides:[]}};var kg="positionAction",mT="matchUpAction";function dT({actionType:t=kg,appliedPolicies:e,drawDefinition:r,structure:n}){let o=t===kg&&zn||t===mT&&rr,i=t===kg&&pT||t===mT&&cP,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 sD({activePositionOverrides:t,activeDrawPositions:e,action:r}){return r&&t.includes(r)?!0:!e.length}function lT({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 Wn({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 aD="replaceTieMatchUpParticipantId",cD="assignTieMatchUpParticipantId",fT="removeTieMatchUpParticipantId",uD="assignMatchUpSideParticipant",CO="removeMatchUpSideParticipant",pD="substituteParticipant",gT="REMOVE_SUBSTITUTION",mD="REPLACE_PARTICIPANT",Gg="REMOVE_PARTICIPANT",IT="setMatchUpStatus",hT="SUBSTITUTION",dD="SCHEDULE",kG="PENALTY",ST="REFEREE",lD="STATUS",TT="START",fD="SCORE",yT="END",bO={REPLACE_TEAM_POSITION_METHOD:aD,ASSIGN_TEAM_POSITION_METHOD:cD,REMOVE_TEAM_POSITION_METHOD:fT,REPLACE_PARTICIPANT:mD,SUBSTITUTION_METHOD:pD,REMOVE_SUBSTITUTION:gT,REMOVE_PARTICIPANT:Gg,SCHEDULE_METHOD:IT,SUBSTITUTION:hT,SCHEDULE:dD,PENALTY:kG,REFEREE:ST,STATUS:lD,SCORE:fD,START:TT,END:yT};function vO({specifiedPolicyDefinitions:t,inContextDrawMatchUps:e,matchUpParticipantIds:r,matchUpActionsPolicy:n,inContextMatchUp:o,policyActions:i,enforceGender:s,participantId:a,sideNumber:c,matchUpId:u,matchUp:p,drawId:m,side:d}){let l=[],f=o.sides?.find(F=>F.participant),g=o.gender===Ar&&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),E=o.sides?.filter(F=>!c||F.sideNumber===c).flatMap(F=>F.participant?.individualParticipants||F.participant).filter(Boolean),P=E?.map(St),U=e?.find(F=>F.matchUpId===o.matchUpTieId)?.sides?.map(F=>F?.participant?.individualParticipants?.filter(({participantId:w,person:L})=>!P?.includes(w)&&(!S||S===Pn||L.sex===S||S===Ar&&!g||g&&L.sex!==g))),N=c?U?.[c-1]:U?.map((F,w)=>({participants:F,sideNumber:w+1})),D=c?U?.[c-1]?.map(St):U?.map((F,w)=>({participants:F?.map(St),sideNumber:w+1})),M=c&&(de(ua)(I)&&!P?.length||de(_i)(I)&&(P?.length??0)<2)||!c&&(de(ua)(I)&&(P?.length??0)<2||de(_i)(I)&&(P?.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:cD,availableParticipants:b,type:As,payload:{participantId:void 0,tieMatchUpId:u,sideNumber:c,drawId:m}}),P?.length&&(!Ie(p)||d?.substitutions?.length)&&l.push({method:fT,type:Gg,existingParticipantIds:P,payload:{participantId:void 0,tieMatchUpId:u,drawId:m}}),b?.length&&(!c&&P?.length||c&&d?.participant)&&l.push({availableParticipantIds:R,method:aD,availableParticipants:b,type:mD,existingParticipantIds:P,payload:{existingParticipantId:void 0,participantId:void 0,tieMatchUpId:u,drawId:m}}),Wn({policyActions:i,action:gT})&&d?.substitutions?.length){let F=d.participant?.participantType===At&&[d.participantId]||d.participant?.participantType===ft&&d.participant.individualParticipantIds||[],w=d.substitutions.map(L=>L.participantId).filter(L=>F.includes(L));(!a||w.includes(a))&&l.push({method:fT,type:gT,substitutedParticipantIds:w,payload:{participantId:void 0,tieMatchUpId:u,drawId:m}})}let v=t?.[rr],O=v?.substituteWithoutScore,x=v?.substituteAfterCompleted;if(Wn({policyActions:i,action:hT})&&r.length===2&&(!c&&P?.length||c&&d?.participant)&&(O||Ie(p))&&(x||p.matchUpStatus&&!se.includes(p.matchUpStatus))&&E?.length&&N.length){let F=E.map(St);l.push({info:"list of team players available for substitution",method:pD,availableParticipantIds:D,existingParticipantIds:F,availableParticipants:N,existingParticipants:E,type:hT,payload:{substituteParticipantId:void 0,existingParticipantId:void 0,sideNumber:c,matchUpId:u,drawId:m}})}return l}function OO({tournamentParticipants:t=[],possiblyDisablingAction:e,activeDrawPositions:r,positionAssignments:n,returnParticipants:o,appliedPolicies:i,drawDefinition:s,drawPosition:a,validActions:c,structureId:u,structure:p,drawId:m,event:d}){if(r.includes(a))return{};let l=c.find(U=>U.type===As)?.availableParticipantIds,f=i?.[zn]?.otherFlightEntries,g=i?.[zn]?.restrictQualifyingAlternates,I=(s.entries??[]).filter(({entryStage:U})=>!g||(p.stage===ct?U===ct:U!==ct)).sort((U,N)=>(U.entryPosition??1/0)-(N.entryPosition??1/0)).map(({participantId:U})=>U).filter(Boolean),{allPositionedParticipantIds:h}=qh({drawDefinition:s}),S=n.map(U=>U.participantId).filter(Boolean),T=I.filter(U=>p.stage&&[ct,rt,fe].includes(p.stage)?!h?.includes(U):!S.includes(U)),E=(d?.entries??[]).filter(U=>U.entryStatus===rn&&gD({restrictQualifyingAlternates:g,structure:p,entry:U})&&(p.stage&&[ct,rt,fe].includes(p.stage)?!h?.includes(U.participantId):!S.includes(U.participantId))).sort((U,N)=>(U.entryPosition??1/0)-(N.entryPosition??1/0)).map(U=>U.participantId),P=pt(T.concat(E));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&&![uo,Gr,Ui].includes(M.entryStatus)&&!I.includes(M.participantId)).map(({participantId:M})=>M)).flat().filter(Boolean);N?.length&&P.push(...N)}l?.length&&(P=P.filter(U=>!l.includes(U)));let A=o?t?.filter(U=>P.includes(U.participantId)):void 0;return A?.forEach(U=>{let N=(s.entries??[]).find(D=>D.participantId===U.participantId);U.entryPosition=N?.entryPosition}),A?.sort((U,N)=>(U.entryPosition||1/0)-(N.entryPosition||1/0)),P.length?{validAlternatesAction:nt({payload:{drawId:m,structureId:u,drawPosition:a},willDisableLinks:e,method:Qv,availableAlternatesParticipantIds:P,type:Mg,availableAlternates:A})}:{}}function gD({restrictQualifyingAlternates:t,structure:e,entry:r}){let{stage:n}=e;if(!r.entryStage||r.entryStage===n||n===ct&&!t||r.entryStage===rt&&n===qe)return!0}function _O({eventEntries:t,structure:e}){let r=o=>o.entryStatus===rn&&gD({structure:e,entry:o}),n=(o,i)=>(o.entryPosition||1/0)-(i.entryPosition||1/0);return t.filter(r).sort(n).map(St)}function xO({restrictAdHocRoundParticipants:t,tournamentParticipants:e,matchUpParticipantIds:r,otherFlightEntries:n,drawDefinition:o,structureId:i,sideNumber:s,matchUpId:a,structure:c,matchUp:u,drawId:p,event:m}){let d=[],l=c?.matchUps??[],g=u.sides?.find(N=>N.sideNumber===s)?.participantId,I=l.filter(({roundNumber:N})=>N===u.roundNumber),h=o?.entries?.filter(({entryStatus:N})=>N&&oi.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:uD,type:As,availableParticipantIds:T,participantsAvailable:y});let E=m?.entries??[],P=_O({eventEntries:E,structure:c}),A=pt(h.concat(P));if(n){let D=(m?Ht({event:m}):void 0)?.flights?.filter(M=>M.drawId!==p).flatMap(M=>M.drawEntries.filter(R=>R.participantId&&![uo,Gr,Ui].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 U=e?.filter(N=>A.includes(N.participantId)).map(N=>J(N,void 0,!0));if(U?.forEach(N=>{let D=(o.entries??[]).find(M=>M.participantId===N.participantId);N.entryPosition=D?.entryPosition}),U?.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:U,method:uD,type:rn}),!Ie(u)&&s&&g){d.push({payload:{drawId:p,matchUpId:a,structureId:i,sideNumber:s},method:CO,type:Gg});let N=w=>w.sides.map(St),D=({matchUpId:w})=>w!==u.matchUpId,M=w=>!Ie(w),R=u.sides?.find(w=>w.sideNumber!==s)?.participantId,v=l.filter(({roundNumber:w})=>w!==u.roundNumber).filter(D).map(N),O=[R,...v.filter(w=>w.includes(g)).flat()].filter(Boolean),x=w=>!O.flat().includes(w),F=I.filter(M).filter(D).map(N).flat().filter(x);if(F.length){let w=e?.filter(L=>F.includes(L.participantId)).map(L=>J(L,void 0,!0));d.push({payload:{participantIds:[g],roundNumber:u.roundNumber,structureId:i,sideNumber:s,matchUpId:a,drawId:p},swappableParticipantIds:F,method:Zv,type:kp,swappableParticipants:w})}}return d}function xd(t){if(!t)return{error:V};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:$};if(!c||!Vt(c))return{error:cr};if(a&&![1,2].includes(a))return _({result:{error:V},context:{sideNumber:a}});if(!e){let Q=(ye({tournamentRecord:u}).matchUps??[]).find(it=>it.matchUpId===c);r=(u?.events??[]).find(it=>it.eventId===Q?.eventId);let ut=(r?.drawDefinitions??[]).find(it=>it.drawId===Q?.drawId);ut&&(e=ut)}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=Tt({tournamentRecord:u,drawDefinition:e,structure:l,event:r}).appliedPolicies??{};Object.assign(f,o??{});let g=f?.[zn]?.otherFlightEntries,I=f?.[rr]??Ss[rr],{enabledStructures:h}=dT({actionType:mT,appliedPolicies:f,drawDefinition:e,structure:l}),{policyActions:S}=lT({enabledStructures:h,drawDefinition:e,structure:l}),T=t.matchUpsMap??Me({drawDefinition:e}),y=t.inContextDrawMatchUps??ce({tournamentParticipants:p,inContext:!0,drawDefinition:e,matchUpsMap:T,event:r}).matchUps,E=y?.find(z=>z.matchUpId===c),P=a&&E?.sides?.find(z=>z.sideNumber===a),A=E?.sides?.map(z=>z.participantId||z.participant?.participantid).filter(Boolean)??[],{assignedPositions:U,allPositionsAssigned:N}=ge({structure:l}),{structureId:D}=l??{},M=[];if(!D)return{validActions:M};let R=pr({structure:l}),b=!!d.collectionId;if(R&&!b){let z=xO({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=Eo({drawDefinition:e,structure:l}),O=U?.filter(z=>z.participantId).map(z=>z.drawPosition),x=U?.filter(z=>z.bye).map(z=>z.drawPosition),F=d.matchUpStatus===Nt||!b&&d.drawPositions?.reduce((z,Q)=>x?.includes(Q)||z,!1);if(F)return{validActions:M,isByeMatchUp:F};Wn({policyActions:S,action:ST})&&M.push({type:ST,payload:{matchUpId:c}});let w=!Da({matchUpStatus:d.matchUpStatus}),L=f?.scoring?.structures,G=l?.stage&&L?.stage&&L?.stage[l.stage],k=l?.stageSequence&&G?.stageSequence&&G.stageSequence[l.stageSequence],W=!(f?.scoring?.requireAllPositionsAssigned||G?.requireAllPositionsAssigned||k?.requireAllPositionsAssigned)||N,q=d.sides&&d.sides.filter(z=>z?.participantId).length===2,Y=d.matchUpStatus&&[Te,be].includes(d.matchUpStatus),B=mr({inContextDrawMatchUps:y,drawDefinition:e,matchUpId:c}),K=vi({inContextDrawMatchUps:y,drawDefinition:e,targetData:B}),j=(E?.drawPositions?.length===2&&E.drawPositions.every(z=>O?.includes(z))&&E?.sides?.length===2&&E.sides.every(({participantId:z})=>z)||q)&&!(Y&&K),ot={method:WS,type:Xs,payload:{drawId:m,matchUpId:c,penaltyCode:void 0,penaltyType:void 0,participantIds:[],notes:void 0}};if(w&&M.push({payload:{drawId:m,matchUpId:c,schedule:{}},method:IT,type:dD}),Wn({policyActions:S,action:Xs})&&(P?.participant||!a&&A?.length)&&M.push(ot),w&&j&&M.push({type:lD}),W&&j){let{matchUpId:z,matchUpFormat:Q}=d,ut={drawId:m,matchUpId:z,matchUpFormat:Q,outcome:{scoreStringSide1:void 0,scoreStringSide2:void 0,sets:[]},winningSide:void 0};M.push({info:"set outcome and winningSide",method:IT,type:fD,payload:ut}),Wn({policyActions:S,action:TT})&&M.push({type:TT}),Wn({policyActions:S,action:yT})&&M.push({type:yT})}if(b&&E){let z=vO({specifiedPolicyDefinitions:o,inContextDrawMatchUps:y,matchUpParticipantIds:A,matchUpActionsPolicy:I,inContextMatchUp:E,policyActions:S,enforceGender:i,participantId:s,sideNumber:a,matchUpId:c,matchUp:d,drawId:m,side:P});M.push(...z)}return{structureIsComplete:v,validActions:M,isDoubleExit:Y,...C}}function wO({tournamentParticipants:t=[],sourceStructuresComplete:e,possiblyDisablingAction:r,isWinRatioFedStructure:n,activeDrawPositions:o,positionAssignments:i,drawDefinition:s,drawPosition:a,structureId:c,structure:u,drawId:p,event:m}){if(o.includes(a)||n&&!e)return{};let{sourceStructureIds:d,targetStructureIds:l}=s.links?.reduce((h,S)=>{let T=S.source?.structureId,y=S.target?.structureId;return h.sourceStructureIds.includes(T)||h.sourceStructureIds.push(T),h.targetStructureIds.includes(y)||h.targetStructureIds.push(y),h},{sourceStructureIds:[],targetStructureIds:[]})||{},f=[],g=s.links?.filter(h=>h.target?.structureId===u.structureId)??[];for(let h of g){let S=h?.source?.structureId,{structure:T}=at({structureId:S,drawDefinition:s}),y=T?.finishingPosition===Bi&&(d?.length!==1||l?.length!==1),E={};if(y){let{matchUps:N}=yt({drawDefinition:s,structure:u,event:m}),{initialRoundNumber:D}=gs({drawPosition:a,matchUps:N}),R=s.links?.find(b=>b.target?.structureId===u?.structureId&&b.target.roundNumber===D)?.source?.roundNumber;E.roundNumbers=[R]}let{completedMatchUps:P}=yu({structureId:S,inContext:!0,matchUpFilters:E,drawDefinition:s}),A=i.map(N=>N.participantId).filter(Boolean);P?.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:Cg,method:Xv,availableLuckyLosers:I,availableLuckyLoserParticipantIds:f,willDisableLinks:r,payload:{drawId:p,structureId:c,drawPosition:a}}}:{}}function LO({positionSourceStructureIds:t,unassignedParticipantIds:e,possiblyDisablingAction:r,provisionalPositioning:n,tournamentParticipants:o,isWinRatioFedStructure:i,positionAssignments:s,returnParticipants:a,appliedPolicies:c,drawDefinition:u,seedingProfile:p,isByePosition:m,drawPosition:d,structureId:l,event:f}){let{drawId:g}=u,I=[],h,S,T=[],y=c?.[Fn]?.validSeedPositions?.ignore;if(y||({unplacedSeedParticipantIds:h,unplacedSeedAssignments:S,unfilledPositions:T}=RS({provisionalPositioning:n,returnAllProxies:!0,randomize:!0,drawDefinition:u,seedingProfile:p,structureId:l,event:f})),T?.length||(T=s.filter(E=>!E.participantId&&!E.bye&&!E.qualifier).map(E=>E.drawPosition)),m||I.push({payload:{drawId:g,structureId:l,drawPosition:d,isPositionAction:!0},willDisableLinks:r,method:rO,type:Pd}),i&&y){let E=s.map(D=>D.participantId).filter(Boolean),P={structureIds:t},{completedMatchUps:A}=Ys({inContext:!0,matchUpFilters:P,drawDefinition:u}),U=pt((A??[]).filter(({matchUpType:D})=>f?.eventType!==_e||D===_e)?.map(({sides:D})=>D?.map(St)).flat().filter(D=>D&&!E.includes(D))),N=a?o?.filter(D=>U?.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(nt({payload:{drawId:g,structureId:l,drawPosition:d},willDisableLinks:r,method:FP,type:As,availableParticipantIds:U,participantsAvailable:N})),{validAssignmentActions:I}}if(T.includes(d)||m){let E;if(S?.length){let A=S.filter(U=>h?.includes(U.participantId));A.sort(GG),E=A.map(U=>U.participantId)}else E=e;let P=a?o?.filter(A=>E.includes(A.participantId)).map(A=>J(A,void 0,!0)):void 0;P?.length&&I.push(nt({payload:{drawId:g,structureId:l,drawPosition:d},willDisableLinks:r,method:FP,type:As,availableParticipantIds:E,participantsAvailable:P}))}return{validAssignmentActions:I}}function GG(t,e){return t.bye||Sc(t.seedValue)<Sc(e.seedValue)||t.seedValue&&!e.seedValue?-1:(t.seedNumber||0)-(e.seedNumber||0)}function FO({drawPositionInitialRounds:t,tournamentParticipants:e,positionAssignments:r,returnParticipants:n,appliedPolicies:o,drawDefinition:i,drawPosition:s,structureId:a,drawId:c}){let u=[],p=[],m=[],d=[],l=r.map(E=>E.participantId).filter(Boolean),f=o?.[zn],g=!f?.disableRoundRestrictions&&t[s],I=f?.requireCompletedStructures,{sourceStructureIds:h,relevantLinks:S}=Du({targetRoundNumber:g,linkType:Kn,drawDefinition:i,structureId:a})||{};h?.length&&d.push(...h);let{sourceStructureIds:T,relevantLinks:y}=Du({targetRoundNumber:g,linkType:xn,drawDefinition:i,structureId:a})||{};T?.length&&d.push(...T);for(let E of S){let P=i.structures?.find(U=>U.structureId===E.source.structureId);if(P?.stage!==ct)continue;let A=Eo({structureId:E.source.structureId,drawDefinition:i});if(!I||A){let U=P.qualifyingRoundNumber,{matchUps:N}=yt({matchUpFilters:{roundNumbers:[U],isCollectionMatchUp:!1,hasWinningSide:!0},afterRecoveryTimes:!1,tournamentParticipants:e,inContext:!0,structure:P});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 E of y){let P=i.structures?.find(U=>U.structureId===E.source.structureId);if(P?.stage!==ct)continue;let A=Eo({structureId:E.source.structureId,drawDefinition:i});if(!I||A){let{positionAssignments:U}=Ct({structure:P}),N=U?.map(D=>{let M=D.participantId,R=mt({element:D,name:bo}).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(nt({qualifyingParticipants:n?u:void 0,method:Kv,type:Lp,qualifyingParticipantIds:p,payload:{qualifyingParticipantId:void 0,drawPosition:s,structureId:a,drawId:c}})),{validAssignmentActions:m,sourceStructureIds:d}}function kO({onlyAssignedPositions:t=!0,possiblyDisablingAction:e,tournamentParticipants:r,inactiveDrawPositions:n,activeDrawPositions:o,positionAssignments:i,returnParticipants:s,byeDrawPositions:a,drawDefinition:c,isByePosition:u,drawPosition:p,structureId:m,structure:d,drawId:l,event:f}){if(o.includes(p))return{};let g=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}=yt({afterRecoveryTimes:!1,inContext:!0,drawDefinition:c,structure:d,event:f}),y=T.filter(({drawPositions:D})=>ke(D,S)),E=Object.assign({},...y.map(D=>D.sides?.filter(({sourceDrawPositionRange:M})=>M).map(({drawPosition:M,sourceDrawPositionRange:R})=>({[M]:R}))).flat()),P=h.map(D=>D.participantId).filter(Boolean),A=(r??[]).filter(D=>P.includes(D.participantId)),U=Object.assign({},...A.map(D=>({[D.participantId]:D}))),N=h.map(D=>{let M=U?.[D.participantId],R=E[D.drawPosition];return nt({...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:HS,type:kp,availableAssignments:N}}:{}}function AT(t){let e=et(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:wt};let d=m.structureId;if(p=Na({drawDefinition:s,structureId:d}),a===void 0&&!p.isAdHoc)return{error:bs};if(p.isAdHoc)return xd(t);if(p.error)return p;let{drawPositionInitialRounds:l,inactiveDrawPositions:f,activeDrawPositions:g,byeDrawPositions:I}=p,h=Tt({tournamentRecord:i,drawDefinition:s,structure:m,event:c}).appliedPolicies??{};Object.assign(h,r??{});let{actionsPolicy:S,enabledStructures:T,actionsDisabled:y}=dT({actionType:kg,appliedPolicies:h,drawDefinition:s,structure:m}),E=S?.activePositionOverrides||[],{sourceStructureIds:P}=Du({finishingPosition:gi,targetRoundNumber:1,linkType:xn,drawDefinition:s,structureId:d})||{},A;P?.length&&(A=P.every(j=>Eo({structureId:j,drawDefinition:s})));let U=P.length,N=P.length&&!A,{policyActions:D}=lT({enabledStructures:T,drawDefinition:s,structure:m}),M=![ct,rt].includes(m.stage)||m.stageSequence!==1,{drawId:R}=s,b=[],{assignedPositions:v,positionAssignments:O}=ge({structure:m}),x=v?.find(j=>j.drawPosition===a),F=!!x;if(!O?.map(j=>j.drawPosition)?.includes(a))return{error:Cs};let{stage:L,stageSequence:G}=m,k=[L];L===qe&&k.push(rt),L===rt&&k.push(qe);let H=Pi({entryStatuses:oi,provisionalPositioning:o,drawDefinition:s,stageSequence:G,structureId:d,stages:k}),W=Ci({drawDefinition:s,stages:k}).assignedParticipantIds??[],q=H.filter(j=>!W.includes(j.participantId)).map(j=>j.participantId),Y=I.includes(a),B=g.includes(a);if(y)return{info:"Actions Disabled for structure",isActiveDrawPosition:B,isDrawPosition:!0,hasPositionAssigned:F,validActions:[],isByePosition:Y};if(Wn({policyActions:D,action:As})&&!B&&O&&!N&&(!x||Y)){let{validAssignmentActions:j}=LO({positionSourceStructureIds:P,unassignedParticipantIds:q,possiblyDisablingAction:M,isWinRatioFedStructure:U,tournamentParticipants:u,positionAssignments:O,returnParticipants:n,appliedPolicies:h,drawDefinition:s,isByePosition:Y,drawPosition:a,structureId:d,event:c});j?.forEach(ot=>b.push(ot))}if(Wn({policyActions:D,action:Lp})&&!B){let{validAssignmentActions:j}=FO({drawPositionInitialRounds:l,tournamentParticipants:u,positionAssignments:O,returnParticipants:n,appliedPolicies:h,drawDefinition:s,drawPosition:a,structureId:d,drawId:R});j?.forEach(ot=>b.push(ot))}let{participantId:K}=x||{},X=K&&u.find(j=>j.participantId===K);if(x){Wn({policyActions:D,action:jS})&&!B&&(b.push({type:jS,method:LP,payload:{drawId:R,structureId:d,drawPosition:a},willDisableLinks:M}),Y||b.push({type:Rg,method:zv,payload:{drawId:R,structureId:d,drawPosition:a},willDisableLinks:M}),Wn({policyActions:D,action:Pd})&&!Y&&b.push({type:Pd,method:LP,payload:{drawId:R,structureId:d,drawPosition:a,replaceWithBye:!0},willDisableLinks:M}));let j=m.stage===ct||m.stage===rt&&m.stageSequence===1;if(!Y&&sD({activePositionOverrides:E,activeDrawPositions:g,action:Qs})&&Wn({policyActions:D,action:Qs})&&_p({drawDefinition:s,structureId:d,drawPosition:a})&&j){let{seedAssignments:ot}=nn({returnAllProxies:!0,drawDefinition:s,structure:m}),{seedNumber:z,seedValue:Q}=ot?.find(ut=>ut.participantId===K)??{};b.push({type:Qs,method:nO,participant:X,seedNumber:z,payload:{drawId:R,structureId:d,participantId:K,seedValue:Q}})}if(!Y&&sD({activePositionOverrides:E,activeDrawPositions:g,action:Fp})&&Wn({policyActions:D,action:Fp})&&_p({drawDefinition:s,structureId:d,drawPosition:a})&&j){let{seedAssignments:ot}=nn({returnAllProxies:!0,drawDefinition:s,structure:m}),{seedNumber:z}=ot?.find(Q=>Q.participantId===K)??{};b.push({method:eO,type:Fp,participant:X,seedNumber:z,payload:{participantId:K,structureId:d,drawId:R}})}if(!Y&&K){if(Wn({policyActions:D,action:Xs})){let ot={type:Xs,method:WS,participant:X,payload:{penaltyCode:void 0,penaltyType:void 0,participantIds:[],notes:void 0,drawId:R}};b.push(ot)}if(Wn({policyActions:D,action:Mu})){let ot={type:Mu,method:tO,participant:X,payload:{participantId:K,otherName:void 0}};b.push(ot)}}if(Wn({policyActions:D,action:kp})){let{validSwapAction:ot}=kO({possiblyDisablingAction:M,tournamentParticipants:u,inactiveDrawPositions:f,activeDrawPositions:g,positionAssignments:O,returnParticipants:n,byeDrawPositions:I,drawDefinition:s,isByePosition:Y,drawPosition:a,structureId:d,structure:m,drawId:R});ot&&b.push(ot)}}if(Wn({policyActions:D,action:Mg})&&!N){let{validAlternatesAction:j}=OO({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(Wn({policyActions:D,action:Cg})&&!N&&!B&&O){let{validLuckyLosersAction:j}=wO({sourceStructuresComplete:A,possiblyDisablingAction:M,isWinRatioFedStructure:U,tournamentParticipants:u,activeDrawPositions:g,positionAssignments:O,drawDefinition:s,drawPosition:a,structureId:d,structure:m,drawId:R});j&&b.push(j)}if(X?.participantType===ft&&Wn({policyActions:D,action:Ng})){let{validModifyAssignedPairAction:j}=RO({tournamentParticipants:u,returnParticipants:n,drawPosition:a,participant:X,drawId:R,event:c});j&&b.push(j)}return{isActiveDrawPosition:B,isDrawPosition:!0,hasPositionAssigned:F,isByePosition:Y,validActions:b,...C}}function xu({policyDefinitions:t,appliedPolicies:e,drawType:r}){let n=t?.[Wm]?.drawTypeCoercion,o=e?.[Wm]?.drawTypeCoercion;return(typeof n=="boolean"?n:void 0)??(r&&n?.[r])??(typeof o=="boolean"?o:void 0)??(r&&o?.[r])??!0}var ET=({drawDefinition:t})=>{let e=et({drawDefinition:t},[{[Ce]:!0}]);if(e.error)return e;let r=t.structures?.find(o=>o.stage===rt&&o.stageSequence===1);if(!r)return _({result:{error:Wl}});let{qualifierPositions:n}=ge({structure:r});return tt(0,n.length).sort(()=>Math.random()-.5)};function UT({structureId:t,drawDefinition:e}){if(!e)return{error:Z};if(!Vt(t))return{error:V};let r=js({drawDefinition:e,structureId:t});if(r.error)return r;let n=r.links.target.flatMap(i=>i.target.feedProfile).filter(Boolean),o=!jt([fi,En,mp,li],n).length;return{...C,valid:o}}function Hp({tournamentRecord:t,drawDefinition:e,stage:r=rt,structureId:n,structure:o}){if(!t)return{error:$};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}=Ct({drawDefinition:e,structureId:n,structure:o});return{positionAssignments:s??[],structureId:o?.structureId,error:i}}function PT({participantsCount:t,participantCount:e}){if(t=t??e,!t)return{error:V};let r=rs(t);return r?{drawSize:r}:_({result:{error:V},stack:"getEliminationDrawSize",context:{participantsCount:t}})}function wu(t){let{drawSizeProgression:e=!1,policyDefinitions:r,drawSize:n}=t||{},{requireParticipantCount:o=!0,tournamentRecord:i,drawDefinition:s,event:a}=t||{},c="getSeedsCount",u=t?.participantsCount??t?.participantCount;if(!r){let I=_o({tournamentRecord:i,drawDefinition:s,event:a});if(I.error)return _({result:I,stack:c});r=I.policyDefinitions}let p=It(u);if(u&&!p)return _({result:{error:V},context:{participantsCount:u},stack:c});if(o&&!p)return _({result:{error:gE},stack:c});if(isNaN(n))if(u)({drawSize:n}=PT({participantsCount:u}));else return _({result:{error:qa},stack:c});let m=o&&u||n;if(m&&m>n)return{error:Jl};let d=r?.[Fn];if(!d)return{error:rE};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:VA}}function wd({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:Ka};if(!Array.isArray(s))return{error:V};if(!a)return{error:Ot};let c=e?.[rr]??n?.[rr]??Ss[rr],u=(i??c?.participants?.enforceGender)!==!1,{eventType:p,gender:m}=a,d=p===Vo,l=p===br&&Ft||d&&ft||At,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=VG({participant:S,participantType:l,eventType:p,entryStatusMap:f}),y=BG({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:zA,invalidParticipantIds:S}}return{...C,valid:!0}}function VG({participant:t,participantType:e,eventType:r,entryStatusMap:n}){let o=n[t.participantId],i=r&&[Vo,br].includes(r)&&t.participantType===At&&(qs(o)||o===uo);return t.participantType!==e&&!i}function BG(t){let{participant:e,participantMap:r,eventGender:n,mismatch:o,isDoubles:i,genderEnforced:s}=t,a=!o&&i&&pt(e?.individualParticipantIds?.map(m=>r?.[m]?.participant?.person?.sex).filter(Boolean)??[])||[],c=!n||!a?.length||Pn===n||[zt,oe].includes(n)&&a[0]===n||Ar===n&&(a.length===1&&e.individualParticipantIds?.length===1||a.length===2),u=e?.person?.sex,p=!e?.person||!n||[Pn,Ar].includes(n)||[zt,oe].includes(n)&&u===n;return!s||c&&p}function DT({hasExistingDrawDefinition:t,qualifyingProfiles:e,appliedPolicies:r,qualifyingOnly:n,tieFormat:o,idPrefix:i,isMock:s,uuids:a}){let c="generateQualifyingSTructures",u=[],p=[],m=[],d=(S,T)=>S.stageSequence-T.stageSequence,l=(S,T)=>S.roundTarget-T.roundTarget,f=0,g=0,I,h=1;for(let S of e.sort(l)){let T=S.structureProfiles||[];h=S.roundTarget||h;let y=1,E=0,P,A,U;for(let N of(T||[]).sort(d)){let D=ym(N.drawSize||N.participantsCount),{qualifyingRoundNumber:M,structureOptions:R,matchUpFormat:b,structureName:v,structureId:O,drawType:x}=N,F=N.matchUpType,w=N.qualifyingPositions||HG({drawSize:D,qualifyingRoundNumber:M}),L,G,k;if(!It(D))return _({result:{error:qa},stack:c});let H=e.length>1?`${h}-`:"",W=T.length>1||H?y:"",q=v||(H||W?`${Qe(ct)} ${H}${W}`:Qe(ct));if(x===Nn){let{structures:Y,groupCount:B,maxRoundNumber:K}=Ra({structureName:N.structureName||q,structureId:O||a?.pop(),hasExistingDrawDefinition:t,stage:ct,structureOptions:R,appliedPolicies:r,qualifyingOnly:n,stageSequence:y,matchUpType:F,roundTarget:h,tieFormat:o,drawSize:D,idPrefix:i,isMock:s,uuids:a});E=B,L=K,G=Y[0],I=[1]}else({drawSize:D,matchUps:k,roundLimit:L}=bn({qualifyingRoundNumber:M,qualifyingPositions:w,matchUpType:F,drawSize:D,idPrefix:i,isMock:s,uuids:a})),G=hn({structureName:N.structureName||q,structureId:O||a?.pop(),qualifyingRoundNumber:L,hasExistingDrawDefinition:t,stage:ct,qualifyingOnly:n,matchUpFormat:b,stageSequence:y,matchUpType:F,roundLimit:L,tieFormat:o,matchUps:k}),h&&Ut({extension:{name:Mn,value:h},element:G}),E=k?.filter(Y=>Y.roundNumber===L)?.length||0;if(y>1){let{link:Y}=Ca({sourceStructureId:A,sourceRoundNumber:P,targetStructureId:G.structureId,finishingPositions:U===xn?[1]:void 0,linkType:U});m.push(Y),f+=(D||0)-E}else f+=D||0;U=x===Nn?xn:Kn,A=G.structureId,P=L,o&&(k=yt({structure:G})?.matchUps||[],k?.forEach(Y=>{let{tieMatchUps:B}=bi({tieFormat:o,matchUp:Y,isMock:s});Object.assign(Y,{tieMatchUps:B,matchUpType:F})})),p.push(G),y+=1}g+=E,u.push({qualifiersCount:E,finalQualifyingRoundNumber:P,finalQualifyingStructureId:A,finishingPositions:I,roundTarget:h,linkType:U}),h+=1}return{qualifiersCount:g,qualifyingDrawPositionsCount:f,qualifyingDetails:u,structures:p,...C,links:m}}function HG({drawSize:t,qualifyingRoundNumber:e}){let r=t,n=0;for(;n<e;)r=Math.floor(r/2),n+=1;return r}function NT(t){let{drawTypeCoercion:e,enforceMinimumDrawSize:r}=t,n=dt(t.drawSize),o=e&&t.drawType!==$r&&(typeof e=="boolean"||e<=2)&&n===2&&ho||t.drawType||ho,i=hU.includes(o);if(n&&i){if(e&&(typeof e=="boolean"&&n<4||n<=e))o=ho;else if(n<4&&r)return{..._({context:{enforceMinimumDrawSize:r,drawSize:n,drawType:o},result:{error:Qu},stack:"getCoercedDrawType"}),drawType:o}}return{drawType:o}}function GO(t){let{drawDefinition:e,structureOptions:r,requireSequential:n}=t,o={structureName:Qe(rt),...t,stage:rt},{structures:i,groupCount:s,groupSize:a}=Ra(o);if(s<1)return{error:vE};let c=r?.playoffGroups||[{finishingPositions:[1],structureName:Qe(fe)}],[u]=i,{structures:p,links:m}=QS({sourceStructureId:u.structureId,requireSequential:n,drawDefinition:e,playoffGroups:c,groupCount:s,groupSize:a,...t});return p&&i.push(...p),{...C,structures:i,links:m}}function VO({mainStructure:t,consolationStructure:e,deciderStructure:r}){let o=e.matchUps.reduce((p,m)=>(m.drawPositions||[]).filter(Boolean).length&&!p.includes(m.roundNumber)?p.concat(m.roundNumber):p,[]),i=t.matchUps.reduce((p,m)=>!p||m.roundNumber>p?m.roundNumber:p,void 0),s=e.matchUps.reduce((p,m)=>!p||m.roundNumber>p?m.roundNumber:p,void 0),a=o.map((p,m)=>{let l=o.indexOf(p)%2?En:fi,f=1+m;return{linkType:oo,source:{roundNumber:f,structureId:t.structureId},target:{feedProfile:l,roundNumber:p,structureId:e.structureId}}}),c={linkType:Kn,source:{roundNumber:s,structureId:e.structureId},target:{feedProfile:En,roundNumber:i,structureId:t.structureId}},u=[{linkType:Kn,source:{roundNumber:i,structureId:t.structureId},target:{feedProfile:En,roundNumber:1,structureId:r.structureId}},{linkType:oo,source:{roundNumber:i,structureId:t.structureId},target:{feedProfile:En,roundNumber:1,structureId:r.structureId}}];return[...a,c,...u]}function BO({structureName:t,matchUpType:e,idPrefix:r,drawSize:n,isMock:o,uuids:i}){let s=[],{matchUps:a}=ci({linkFedFinishingRoundNumbers:[1],drawSize:n+1,matchUpType:e,idPrefix:r,isMock:o}),c=Ts({structureName:t||Qe(rt),structureId:i?.pop(),stageSequence:1,stage:rt,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=Ts({structureName:Qe(IU),matchUps:p,structureId:i?.pop(),stage:qe,stageSequence:2,matchUpType:e});s.push(m);let{matchUps:d}=bn({idPrefix:r&&`${r}-p1t2`,drawSize:2,matchUpType:e,isMock:o}),l=Ts({structureName:Qe(gU),matchUps:d,structureId:i?.pop(),stageSequence:3,stage:fe,matchUpType:e});s.push(l);let f=VO({mainStructure:c,consolationStructure:m,deciderStructure:l});return{structures:s,links:f,...C}}function HO(t){let{qualifyingRoundNumber:e,finishingPositionOffset:r,qualifyingPositions:n,matchUpType:o,idPrefix:i,drawSize:s,isMock:a,uuids:c}=t;if(!It(s)||s<2)return{matchUps:[],roundsCount:0};if(_n(s))return bn(t);let u=WG(s),p=u.shift(),m=tt(1,(p?.participantsCount||0)+1).map(I=>({drawPosition:I})),d=[],l=1;({matchUps:d}=Gp({roundNumber:l,matchUpType:o,idPrefix:i,matchUps:d,isMock:a,nodes:m,uuids:c})),l++;let f=t.roundLimit||e;for(let I of u){let h=I.participantsCount/2,S=tt(1,h+1);n&&h===n&&(f=l-1);let T=S.map(y=>{let E=Dd({roundPosition:y,roundNumber:l,idPrefix:i,uuids:c});return{roundPosition:y,roundNumber:l,matchUpId:E}});d.push(...T),l++}let g=l-1;return d=Pa({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 WG(t){let e=dt(t),r=e%2?e+1:e,n=!!(Math.ceil(r/2)%2),o=[{participantsCount:r,preFeedRound:n}];for(;r>2;){let i=Math.ceil(r/2),s=i===1,a=!!(!s&&i%2);r=!s&&a?i+1:i;let c=!!(r!==2&&Math.ceil(r/2)%2);o.push({participantsCount:r,preFeedRound:c,feedRound:a})}return o}function MT(t){let{playoffAttributes:e,stageSequence:r=1,stage:n=rt,tieFormat:o,matchUpType:i,drawSize:s,uuids:a}=t,c=()=>!t.isMock&&!t.idPrefix?void 0:`${t.drawDefinition.drawId}-s-0`,u=t.structureId||c()||a?.pop(),p=t.appliedPolicies??Tt(t),m=t.policyDefinitions?.[oc]||p?.[oc];t.skipRounds=t.skipRounds||s<=4&&(m?.feedFromMainFinal?0:1)||0;let d=t.structureName??e?.["0"]?.name??Qe(rt),l=()=>{let{matchUps:g}=bn(t);return{structures:[hn({stageSequence:r,structureName:d,matchUpType:i,structureId:u,tieFormat:o,matchUps:g,stage:n})],links:[],...C}};return{generators:{[$r]:()=>({structures:[hn({finishingPosition:gi,stageSequence:r,structureName:d,matchUps:[],matchUpType:i,structureId:u,stage:n})],links:[],...C}),[Vi]:()=>{let{matchUps:g}=HO(t);return{structures:[hn({stageSequence:r,structureName:d,matchUpType:i,structureId:u,matchUps:g,stage:n})],links:[],...C}},[ho]:()=>l(),[Zc]:()=>BO(t),[Xc]:()=>Ac({...t,roundOffsetLimit:3,playoffAttributes:e??Df}),[Jc]:()=>Ac({...t,roundOffsetLimit:2,playoffAttributes:e??Nf}),[fe]:()=>Ac(t),[fa]:()=>{let{matchUps:g}=ci({drawSize:s,uuids:a,matchUpType:i});return{structures:[hn({stageSequence:r,structureName:d,matchUpType:i,structureId:u,stage:rt,tieFormat:o,matchUps:g})],links:[],...C}},[dp]:()=>qS(t),[tu]:()=>Uc({...t,feedRounds:1,fmlc:!0}),[fU]:()=>Uc({...t,feedRounds:1}),[Dh]:()=>Uc({...t,feedsFromFinal:1}),[Nh]:()=>Uc({...t,feedsFromFinal:2}),[Mh]:()=>Uc({...t,feedsFromFinal:3}),[lp]:()=>Uc(t),[Pf]:()=>KS(t),[Nn]:()=>Ra(t),[So]:()=>GO(t)}}}function Ld(t){let{enforceMinimumDrawSize:e=!0,overwriteExisting:r,appliedPolicies:n,qualifyingOnly:o,staggeredEntry:i,drawDefinition:s,tieFormat:a,isMock:c,uuids:u}=t||{},p=dt(t.drawSize),m=t.drawTypeCoercion??xu({appliedPolicies:n,drawType:t.drawType}),d="generateDrawStructuresAndLinks",l=NT({drawType:t.drawType,enforceMinimumDrawSize:e,drawTypeCoercion:m,drawSize:p});if(l.error)return l;let f=l.drawType,g=[],I=[],h=t?.matchUpType??kt,S=s?.structures?.filter(({stage:W})=>W===ct);S&&g.push(...S);let T=S?.map(({structureId:W})=>W),y=s?.structures?.find(({stage:W,stageSequence:q})=>W===rt&&q===1),E=s?.links?.filter(W=>W.target.structureId===y?.structureId&&T?.includes(W.source.structureId)),P=(W,q)=>{if(W.linkType===xn&&q?.structures){let Y=W.source.finishingPositions||[];return q.structures.length*Y.length}else if(W.linkType===Kn&&q?.matchUps?.length){let Y=W.source.roundNumber;return q.matchUps.filter(({roundNumber:K})=>K===Y).length}},A=S?.map(W=>{let q=E?.find(j=>j.target.structureId===W.structureId),Y=Ct({structure:W})?.positionAssignments?.length??0;if(!q)return Y;let B=q?.source.structureId,K=s.structures?.find(j=>j.structureId===B),X=P(q,K)||0;return Y-X}).filter(Boolean).reduce((W,q)=>W+q,0),U=E?.map(W=>{let q=W.source.structureId,Y=S?.find(B=>B.structureId===q);return P(W,Y)}).filter(Boolean).reduce((W,q)=>W+q,0),N=!!(y&&!y?.matchUps?.length);if(S?.length&&!N)return{error:KI};let D=!S?.length&&t.qualifyingProfiles,M=D?.length&&DT({idPrefix:t.idPrefix,qualifyingProfiles:D,appliedPolicies:n,qualifyingOnly:o,tieFormat:a,isMock:c,uuids:u});if(M?.error)return M;let{qualifyingDrawPositionsCount:R,qualifyingDetails:b,qualifiersCount:v}=M||{qualifyingDrawPositionsCount:A,qualifiersCount:U};R&&(M?.structures&&g.push(...M.structures),M?.links&&I.push(...M.links)),Object.assign(t,nt({drawSize:p,matchUpType:h,tieFormat:a}));let O=f!==$r&&(!p||p<2||!i&&![fa,Vi].includes(f)&&([So,Nn].includes(f)&&p<3||![Nn,So].includes(f)&&!_n(p)));if(O&&!R)return _({context:{drawSize:p,invalidDrawSize:O},result:{error:Qu},stack:d});let{generators:x,error:F}=MT(t);if(F)return{error:F};let w=x[f];if(!w)return{error:Vl};let L=w?.();if(L.error)return L;let{structures:G,links:k}=L;if(G?.length){let W=G.find(({stage:q,stageSequence:Y})=>q===rt&&Y===1);if(y&&W){if(N){let q=W.structureId;if(W.structureId=y.structureId,k?.length)for(let Y of k)Y.source.structureId===q&&(Y.source.structureId=y.structureId),Y.target.structureId===q&&(Y.target.structureId=y.structureId)}else if(!r)return{error:KI}}g.push(...G)}g.sort(yi),k?.length&&I.push(...k);let H=L.structures.find(({stage:W,stageSequence:q})=>W===rt&&q===1);for(let W of b||[]){let{finalQualifyingRoundNumber:q,finalQualifyingStructureId:Y,roundTarget:B,finishingPositions:K,linkType:X}=W,j=H&&Ca({targetStructureId:H.structureId,sourceStructureId:Y,sourceRoundNumber:q,finishingPositions:K,targetEntryRound:B,linkType:X})?.link;if(j?.error)return j;j&&I.push(j)}return E&&I.push(...E),{...C,qualifyingResult:{qualifyingDrawPositionsCount:R,qualifiersCount:v},structures:g,links:I}}function Fd(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=ur({tieFormat:s});if(T.error)return T}s=sr(s??We({drawDefinition:i})?.tieFormat),a=a??(i.matchUpType||kt),t.tieFormat=s,t.matchUpType=a;let c=bp({drawDefinition:i,stage:rt});t.drawSize=t.drawSize??c,!c&&t.drawSize&&wp({drawSize:t.drawSize,drawDefinition:i,stageSequence:r,stage:rt});let u=Me({drawDefinition:i}).drawMatchUps.map(Ue),p=Ld(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&&!bp({stage:ct,drawDefinition:i})){let y=wp({drawSize:l.qualifyingDrawPositionsCount,stage:ct,drawDefinition:i});if(y.error)return y}if(f){let T=BS({qualifiersCount:f,drawDefinition:i,stage:rt});if(T.error)return T}let g=t.drawSize??c;Object.assign(t,nt({drawSize:g,matchUpType:a,tieFormat:s}));let{matchUps:I,matchUpsMap:h}=ce({drawDefinition:i});s&&I?.forEach(T=>{if(!u.includes(T.matchUpId)){let{tieMatchUps:y}=bi({tieFormat:s,matchUp:T,isMock:n});Object.assign(T,{tieMatchUps:y,matchUpType:a})}});let{inContextDrawMatchUps:S}=Ki({drawDefinition:i,matchUpsMap:h});return vt({tournamentId:t.tournamentRecord?.tournamentId,drawDefinition:i}),{inContextDrawMatchUps:S,drawDefinition:i,matchUpsMap:h,...C,structures:m,matchUps:I,links:d}}function Mc(t){let{removePriorValues:e,tournamentRecord:r,participantId:n,scaleItem:o}=t,i,s;if(!WO({scaleItem:o}))return{error:za};if(n&&Array.isArray(r.participants)&&(s=r.participants.find(a=>a.participantId===n),s)){if(s.participantType===Er&&o?.eventType!==br)return{error:za};let a=jO({removePriorValues:e,participant:s,scaleItem:o});if(a.error)return a;i=!a.valueChanged;let{topics:c}=Lr();c.includes(or)&&lt({topic:or,payload:{tournamentId:r.tournamentId,participants:[s]}})}return i&&{...C,info:cf,existingValue:o?.scaleValue}||s&&{...C,newValue:o?.scaleValue}||{error:re}}function hD(t){let{scaleItemsWithParticipantIds:e=[],removePriorValues:r,tournamentRecord:n,auditData:o,context:i}=t;if(!n)return{error:$};if(!n.participants)return{error:Ka};let s=0,a={},c=[];for(let m of e){let d=m?.participantId;if(Array.isArray(m?.scaleItems))for(let l of m.scaleItems)if(WO({scaleItem:l}))Array.isArray(a[d])||(a[d]=[]),a[d].push(l);else return{error:za}}for(let m of n.participants){let{participantId:d}=m||{};if(Array.isArray(a[d]))for(let l of a[d]){if(m.participantType===Er&&l?.eventType!==br)return _({context:{participantId:d,scaleItem:l,participantType:m.participantType},info:"Invalid participantType for eventType",result:{error:za}});jO({participant:m,scaleItem:l,removePriorValues:r}),c.push(m),s++}}let u=s?void 0:xs,{topics:p}=Lr();if(p.includes(or)&&s&&lt({topic:or,payload:{tournamentId:n.tournamentId,participants:c}}),i){let{eventId:m,drawId:d,...l}=i,f=l.scaleAttributes?.scaleType&&[l.scaleAttributes.scaleType];if(Object.keys(l).length){let g={itemType:Gf,itemValue:l};if(f&&(g.itemSubTypes=f),d||m){let{drawDefinition:I,event:h}=ze({tournamentRecord:n,eventId:m,drawId:d});d&&Dg({drawDefinition:I,timeItem:g}),m&&Xi({event:h,timeItem:g})}else Nc({tournamentRecord:n,timeItem:g})}}return o&&p.includes(Ai)&&lt({topic:Ai,payload:o}),nt({...C,modificationsApplied:s,info:u})}function WO({scaleItem:t}){let e=t&&Object.keys(t),r=["scaleType","eventType","scaleName"];return!!(r.filter(o=>e?.includes(o)).length===r.length)}function jO({removePriorValues:t,participant:e,scaleItem:r}){if(!e)return{error:Fi};let n=r&&Object.keys(r),o=["scaleType","eventType","scaleName"];if(!(o.filter(p=>n.includes(p)&&r[p]).length===o.length))return{error:za};let s=new Date().toISOString();e.timeItems||(e.timeItems=[]);let{scaleItem:a}=Ao({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=[Si,p,m,d].join("."),f=nt({itemValue:r.scaleValue,itemDate:r.scaleDate,createdAt:s,itemType:l});r.scaleId&&(f.itemSubTypes=[r.scaleId]),t&&(e.timeItems=e.timeItems.filter(g=>g.itemType!==l)),e.timeItems.push(f)}return{...C,valueChanged:u,newValue:r.scaleValue}}function Vg(t){let{tournamentRecord:e,modifiedScaleValues:r,removePriorValues:n}=t,o=et(t,[{[ne]:!0},{modifiedScaleValues:!0,[He]:Kr}]);if(o.error)return o;for(let i in r){let s=Mc({scaleItem:r[i],removePriorValues:n,tournamentRecord:e,participantId:i});if(s.error)return s}return{...C}}function Rc(t){let{tournamentRecord:e,scaleAttributes:r,participantId:n}=t,o=t.tournamentRecords||e&&{[e.tournamentId]:e}||{};if(!n)return{error:ie};let{participant:i,tournamentId:s}=yo({tournamentRecords:o,tournamentRecord:e,participantId:n});return i?{...Ao({participant:i,scaleAttributes:r}),tournamentId:s}:{error:re}}var jG=(t=0)=>250/Math.pow(t+5,.4),YG=()=>1;function qG(t=3,e=2){let r=t/e;return isNaN(r)?kd.kDefault():r}var kd={nSpread:400,diffThreshold:.125,kCalc:jG,kMultiplier:qG,kDefault:YG};function RT(t){let{winnerRating:e,loserRating:r}=t,{ratings:n=we,winnerCountables:o=1,loserCountables:i=0,ratingType:s=Zn,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=bu({targetRange:we[Zn].range,sourceRange:l,value:m?p[0]-e:e}),I=bu({targetRange:we[Zn].range,sourceRange:l,value:m?p[0]-r:r}),h=(x,F)=>1/(1+Math.pow(10,(F-x)/kd.nSpread)),S=h(g,I),T=h(I,g),y=kd.kCalc(o),E=kd.kCalc(i),P=kd.kMultiplier(a,c),A=g+P*y*(1-S),U=I+P*E*(0-T),N=bu({sourceRange:we[Zn].range,value:A,targetRange:l}),D=bu({sourceRange:we[Zn].range,value:U,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>kd.diffThreshold||R<0||v<0)&&(R=e,v=r),{newWinnerRating:R,newLoserRating:v}}var YO=t=>t?.reduce((e,r)=>(r.winningSide&&(e[r.winningSide-1]+=1),e),[0,0])||[0,0];function CT(t){let e=et(t,[{[ne]:!0},{matchUpIds:!0,[He]:Be,[fn]:ns},{ratingType:!1,[er]:S=>we[S]}]);if(e.error)return e;let{updateParticipantRatings:r,removePriorValues:n=!0,tournamentRecord:o,ratingType:i=Zn,refreshDynamic:s,considerGames:a,drawDefinition:c,matchUpIds:u,asDynamic:p}=t,m=we[i],{accessor:d}=m,l={},f=(t.matchUps||s&&ir({drawDefinition:c,tournamentRecord:o,inContext:!0,matchUpFilters:{matchUpStatuses:se}}).matchUps||ye({matchUpFilters:{matchUpIds:u,matchUpStatuses:se},tournamentRecord:o,inContext:!0}).matchUps)??[],g=`${i}.${Hm}`,I=p?g:i;f.sort(Ri);for(let S of f){let{endDate:T,matchUpFormat:y,score:E,sides:P,winningSide:A}=S,U=S.matchUpType,N={eventType:U,scaleName:i,scaleType:hi},D={scaleName:g,eventType:U,scaleType:hi},M=Object.assign({},...(P??[]).map(G=>{let{sideNumber:k,participant:H}=G;return k&&{[k]:[H?.participantId,...H?.individualParticipantIds??[]].filter(Boolean).flat()}})),R=Object.assign({},...Object.values(M).flat().map(G=>{let k=l[G],W=!s||k?Rc({scaleAttributes:D,tournamentRecord:o,participantId:G}).scaleItem:void 0,q=Rc({tournamentRecord:o,scaleAttributes:N,participantId:G}).scaleItem,Y=d?{[d]:void 0}:void 0;return G&&{[G]:W??q??{scaleName:I,eventType:U,scaleDate:T,scaleType:hi,scaleValue:Y}}})),b=y?Ye(y):{},v=b?.bestOf||1,O=b?.setsTo||1,x=a?v&O:v,F=E?.sets&&YO(E.sets)||A===1&&[1,0]||[0,1],w=A?M[A]:[],L=A?M[3-A]:[];for(let G of w){let k=R[G]?.scaleValue,H=typeof k=="object"?k[d]:k;for(let W of L){let q=R[W]?.scaleValue,Y=typeof q=="object"?q[d]:q,B=A?F[A]:[0,0],K=A?F[3-A]:[0,0],{newWinnerRating:X,newLoserRating:j}=RT({winnerCountables:B,loserCountables:K,maxCountables:x,winnerRating:H,loserRating:Y,ratingType:i}),ot=d?{...k,[d]:X}:X,z=d?{...q,[d]:j}:j;R[G].scaleValue=ot,R[W].scaleValue=z,R[G].scaleName=I,R[W].scaleName=I}}Object.assign(l,R),r&&Vg({tournamentRecord:o,modifiedScaleValues:l,removePriorValues:n})}let h=f.map(({matchUpId:S})=>S);return{...C,modifiedScaleValues:l,outputScaleName:I,processedMatchUpIds:h}}function Lu(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=_d(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:V,info:"matchUpsCount error",context:{roundMatchUpsCount:d}}});if(a&&!Array.isArray(a)||c&&!It(c)||e&&!Array.isArray(e)||!a&&!c)return{error:V,info:"matchUpsCount or pairings error"};if(c&&t.restrictMatchUpsCount!==!1&&c>32)return{error:V,info:"matchUpsCount must be less than 33"};if(n&&!t.ignoreLastRoundNumber&&n-1>(p||0))return{error:V,info:"roundNumber error"};let l=n??(o&&(p??0)+1||p||1);a=a??tt(0,c).map(()=>({participantIds:[void 0,void 0]}));let f=I=>{if(!t.idPrefix)return;let h=r.drawId,S=t.idPrefix??"ah";return`${h}-${S}-${l}-${I}`},g=a?.map((I,h)=>{let S=I?.participantIds??[void 0,void 0];S.push(void 0,void 0);let y=S.slice(0,2).map((P,A)=>nt({sideNumber:A+1,participantId:P})),E=e[h]??f(h)??Mt();return{roundNumber:l,matchUpStatus:Xt,matchUpId:E,sides:y}});if(g?.length){let I=We({drawDefinition:r,event:s})?.tieFormat;I&&g.forEach(h=>{let{tieMatchUps:S}=bi({tieFormat:I,matchUp:h,isMock:i});Object.assign(h,{tieMatchUps:S,matchUpType:Wt})})}return{roundNumber:l,matchUpsCount:g?.length??0,matchUps:g,...C}}function $O({maxIterations:t=4e3,valueSortedPairings:e,pairingValues:r,valueObjects:n,deltaObjects:o}){let i=Object.assign({},...e.map(S=>({[S.pairing]:S.value}))),s=Object.keys(r),a=[],c=qO({actorsCount:s.length,valueSortedPairings:e,pairingValueMap:i,deltaObjects:o,valueObjects:n}),u=[SD(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 E=Oa(S,y.opponent);if(!I.includes(E)){let P=qO({stipulated:[[S,y.opponent]],actorsCount:s.length,valueSortedPairings:e,pairingValueMap:i,deltaObjects:o,valueObjects:n});if(!u.includes(SD(P))){u.push(SD(P)),a.push(P);let{maxDelta:A,value:U}=P;A<m.maxDelta&&(m=P),(U<p||U===p&&Math.round(Math.random()))&&(p=U),I.push(E),d+=1}}}),a=a.filter(y=>Math.abs(y.value-p)<5)}),a.sort((S,T)=>S.maxDiff-T.maxDiff);let h=Zr(a);return{candidatesCount:d,deltaCandidate:m,maxIterations:t,iterations:l,candidate:h}}function SD(t){return t.participantIdPairings.map(({participantIds:e})=>e.sort().join("|")).sort().join("/")}function qO({valueSortedPairings:t,stipulated:e=[],pairingValueMap:r,deltaObjects:n,valueObjects:o,actorsCount:i}){let s=[].concat(...e),a=[],c=0;e.filter(Boolean).forEach(d=>{let[l,f]=d,g=Oa(l,f),I=r[g];a.push({participantIds:d,value:I}),c+=r[g]}),Ee(t,i).map(d=>Sr(d).map(l=>({...l,value:l.value+Math.random()*Math.round(Math.random())}))).flat().forEach(d=>{let l=d.pairing.split("|");if(!l.reduce((g,I)=>s.includes(I)||g,!1)){s.push(...l);let g=d.value;c+=g,a.push({participantIds:l,value:g})}}),a.sort((d,l)=>d.value-l.value);let p=a.reduce((d,l)=>{let[f,g]=l.participantIds,I=Oa(f,g),h=n[I];return h>d?h:d},0),m=a.reduce((d,l)=>{let[f,g]=l.participantIds,I=Oa(f,g),h=o[I];return h>d?h:d},0);return{value:c,participantIdPairings:a,maxDelta:p,maxDiff:m}}function Oa(t,e){return[t,e].sort(Eu).join("|")}function TD({participantIds:t}){let e={},r=[];t.forEach(o=>{e[o]=t.filter(i=>i!==o),e[o].forEach(i=>{let s=Oa(i,o);r.includes(s)||r.push(s)})});let n=Object.assign({},...r.map(o=>({[o]:0})));return{uniquePairings:r,possiblePairings:e,deltaObjects:n}}function KO({matchUps:t}){let e=[];for(let r of t){let n=r.sides.map(St);if(n.length===2){let[o,i]=n,s=Oa(o,i);e.includes(s)||e.push(s)}}return{encounters:e}}function zO({possiblePairings:t,valueObjects:e}){let r={};for(let o of Object.keys(t)){let i=t[o].map(s=>n(o,s));r[o]=i.sort((s,a)=>s.value-a.value)}function n(o,i){let s=Oa(o,i);return{opponent:i,value:e[s]}}return{pairingValues:r}}var $G=0;function QO({tournamentParticipants:t,adHocRatings:e,eventType:r,scaleName:n,pairing:o}){let i=we[n]?.defaultInitialization??$G;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 XO(t){let{tournamentParticipants:e,adHocRatings:r={},possiblePairings:n,uniquePairings:o,maxIterations:i,minimizeDelta:s,deltaObjects:a,valueObjects:c,eventType:u,scaleName:p,salted:m}=t;o.forEach(T=>{let y=QO({tournamentParticipants:e,adHocRatings:r,scaleName:p,eventType:u,pairing:T}),E=typeof m=="number"&&m||.5,P=m&&(Math.round(Math.random())?E:E*-1)||0,A=Math.abs(y[0]-y[1])+P,U=Math.abs(y[0]-y[1]);a[T]=U,c[T]||(c[T]=0),c[T]+=A?Math.pow(A,2):0});let d=o.map(T=>({pairing:T,value:c[T]})).sort((T,y)=>T.value-y.value),{pairingValues:l}=zO({possiblePairings:n,valueObjects:c}),{candidate:f,candidatesCount:g,deltaCandidate:I,iterations:h}=$O({valueSortedPairings:d,maxIterations:i,pairingValues:l,deltaObjects:a,valueObjects:c}),{participantIdPairings:S}=s?I:f;return{participantIdPairings:S,candidatesCount:g,deltaCandidate:I,iterations:h,candidate:f}}var KG=100,zG=100,QG=4e3;function Gd(t){let{encounterValue:e=KG,sameTeamValue:r=zG,maxIterations:n=QG,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:E}=t;if(!d)return{error:Z};if(!t.structure&&!f)return{error:wt};let P=t.structure||at({drawDefinition:d,structureId:f}).structure;if(!ht(P))return{error:di};if(!m?.length)return{error:Do};let A=[...a??[],...P?.matchUps??[]],{encounters:U}=KO({matchUps:A}),N=c?.participants??[],D={};if(u){let B=pt(P?.matchUps?P.matchUps.map(({roundNumber:X})=>X):[]),K=Math.max(...B,0);if(K){let X=P?.matchUps?.filter(({roundNumber:ot})=>ot===K).map(({matchUpId:ot})=>ot),j=CT({ratingType:h??E?.category?.ratingType,updateParticipantRatings:o,tournamentRecord:c,asDynamic:!0,refreshDynamic:p,drawDefinition:d,matchUpIds:X});if(j.error)return j;j.modifiedScaleValues&&(D=j.modifiedScaleValues)}}let{valueObjects:M}=XG({tournamentParticipants:N,encounterValue:e,sameTeamValue:r,encounters:U}),{uniquePairings:R,possiblePairings:b,deltaObjects:v}=TD({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:P,salted:y},{candidatesCount:F,participantIdPairings:w,deltaCandidate:L,iterations:G,candidate:k}=XO(x);if(!F)return{error:tp};let H,W;if(i){let B=Lu({structureId:P?.structureId,ignoreLastRoundNumber:s,participantIdPairings:w,newRound:!0,drawDefinition:d,roundNumber:l,matchUpIds:g,idPrefix:S,isMock:T,event:E});if(B.error)return B;H=B.roundNumber,W=B.matchUps}let{maxDelta:q,maxDiff:Y}=k;return{roundNumber:H,participantIdPairings:w,modifiedScaleValues:D,candidatesCount:F,deltaCandidate:L,...C,iterations:G,matchUps:W,maxDelta:q,maxDiff:Y}}function XG({encounters:t,tournamentParticipants:e,encounterValue:r,sameTeamValue:n}){let o={};for(let s of t)o[s]||(o[s]=0),o[s]+=r;let i=e?.filter(({participantType:s})=>s===Ft);if(i)for(let s of i){let a=s.individualParticipantIds??[],{uniquePairings:c}=TD({participantIds:a});for(let u of c)o[u]||(o[u]=0),o[u]+=n}return{valueObjects:o}}function bT(t){let{drawType:e=ho,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=Pi({stageSequence:1,drawDefinition:p,stage:m}),l=[Nn,Zc,So].includes(e)?d.length:rs(d.length);if(!i&&e===fa&&d.length<2||e===Nn&&d.length<3)return{error:Qu};let{tieFormat:f,matchUpType:g}=t;if(f){let R=ur({tieFormat:f});if(R.error)return R}f=sr(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:XA};if(I?.[0]?.matchUps?.length)return{error:pf};let S=I?.[0]?.structureId;Object.assign(t,nt({structureName:t.structureName??Qe($e),structureId:S,matchUpType:g,tieFormat:f,drawSize:l,stage:m}));let T=MT(t);if(T.error)return T;let y=T.generators[e];if(!y)return{error:Vl};let E=y?.();if(E.error)return E;let{structures:P,links:A}=E,U=P.map(R=>yt({structure:R}).matchUps).flat();f&&U.forEach(R=>{let{tieMatchUps:b}=bi({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=P.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)?P.find(({structureId:b})=>b===R.structureId):R);let M=P.filter(({structureId:R})=>!D.includes(R));return M.length&&p.structures.push(...M),s&&yc({seedingProfile:t.seedingProfile,applyPositioning:n,tournamentRecord:o,drawDefinition:p,structureId:S,placeByes:a,drawSize:l,event:u}),r&&vt({drawDefinition:p}),{links:A,structures:P,...C}}var $g={};Jt($g,{addGame:()=>ND,addPoint:()=>DD,addSet:()=>RD,addShot:()=>MD,analyzeScore:()=>jg,analyzeSet:()=>Gu,calculateHistoryScore:()=>ED,checkScoreHasValue:()=>Ie,checkSetIsComplete:()=>Yp,clearHistory:()=>PD,generate:()=>AD,generateScoreString:()=>$o,generateTieMatchUpScore:()=>Dc,getSetComplement:()=>qg,getTiebreakComplement:()=>zp,helpers:()=>oN,isValidMatchUpFormat:()=>Dr,keyValueScore:()=>JD,mutate:()=>OD,parseMatchUpFormat:()=>Ye,parseScoreString:()=>qd,query:()=>iN,redo:()=>CD,reverseScore:()=>yD,setServingSide:()=>UD,stringifyMatchUpFormat:()=>cp,tidyScore:()=>nN,umo:()=>vD,undo:()=>bD,validateScore:()=>Yg,validateTieFormat:()=>ur});var AD={};Jt(AD,{generateScoreString:()=>$o,generateTieMatchUpScore:()=>Dc,reverseScore:()=>yD});function $o(t){let{winnerFirst:e=!0,setTBlast:r=!0,addOutcomeString:n,reversed:o=!1,matchUpStatus:i,matchUpFormat:s,autoComplete:a,winningSide:c,sets:u}=t;if(!u)return{error:st,info:"missing sets"};let p=s&&Ye(s),{bestOf:m,finalSetFormat:d,setFormat:l}=p??{},g=o||!(!e||!c||c===1),I=n?JG({matchUpStatus:i}):"",h=u?.sort(ZG).map(S).filter(Boolean).join(" ")||"";if(!I)return h;if(c===2)return`${I} ${h}`;return`${h} ${I}`;function S(T){let E=m&&T.setNumber===m&&d?d:l,P=B=>Zt(B?.side1Score)||Zt(B?.side2Score),U=(B=>Zt(B?.side1TiebreakScore)||Zt(B?.side2TiebreakScore))(T),N=E?.tiebreakSet||!P(T)&&U,{side1Score:D,side2Score:M,side1TiebreakScore:R,side2TiebreakScore:b}=T,v=R||(Zt(R)||U&&a?0:""),O=b||(Zt(b)||U&&a?0:"");if(N)return`[${(g?[O,v]:[v,O]).join("-")}]`;let x=U?Math.min(v,O):"",F=x===v?1:2,w=Zt(x)?`(${x})`:"",L=D||(Zt(D)||a?0:""),G=M||(Zt(M)||a?0:""),k=B=>!r&&F===B?w:"",H=`${L}${k(1)}`,W=`${G}${k(2)}`,q=r&&U?`(${x})`:"",Y=g?`${[W,H].join("-")}${q}`:`${[H,W].join("-")}${q}`;return["-"," "].includes(Y)&&(Y=""),Y}}function JG({matchUpStatus:t}){let e={[nr]:"RET",[bt]:"WO",[be]:"DF/DF",[Te]:"WO/WO",[as]:"SUS",[vr]:"ABN",[Rt]:"DEF",[uu]:"DR"};return t&&e[t]||""}function ZG(t,e){return t.setNumber-e.setNumber}function yD(t){if(!t?.score)return{error:st};let{sets:e}=t.score,r=e.map(s=>{let{side1TiebreakScore:a,side2TiebreakScore:c,winningSide:u,side1Score:p,side2Score:m,setNumber:d}=s;return nt({winningSide:u?3-u:void 0,side1TiebreakScore:c,side2TiebreakScore:a,side1Score:m,side2Score:p,setNumber:d})}),n=t?.setTBlast,o=$o({setTBlast:n,sets:r}),i=$o({sets:r,reversed:!0,setTBlast:n});return{reversedScore:{sets:r,scoreStringSide1:o,scoreStringSide2:i},...C}}var OD={};Jt(OD,{addGame:()=>ND,addPoint:()=>DD,addSet:()=>RD,addShot:()=>MD,calculateHistoryScore:()=>ED,clearHistory:()=>PD,redo:()=>CD,setServingSide:()=>UD,umo:()=>vD,undo:()=>bD});function Ko({matchUp:t}){let{extension:e}=mt({name:Km,element:t});if(!e)return{error:ve};let{history:r=[],undoHistory:n=[]}=e.value;return{history:r,undoHistory:n,...C}}function ED(t){if(!t)return{error:st};let{matchUp:e,updateScore:r}=t;if(!e)return{error:Tr};let n=Ko({matchUp:e})?.history||[];if(!Array.isArray(n))return{error:V,info:"history is not an array"};let{matchUpFormat:o}=e;if(!o)return{error:$l};if(!Dr({matchUpFormat:o}))return{error:ql};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:[]}),E=()=>({winningSide:void 0,side1Score:"",side2Score:"",shots:[]}),P=E(),A=y(),U=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=U.side1Score===R&&U.side1Score===U.side2Score,F=!!M.tiebreakSet,w=F?M.tiebreakSet:O,{tiebreakTo:L,NoAD:G}=w||{},k=()=>{d=void 0,l=[0,0],f=3-f,U.side1TiebreakScore="",U.side2TiebreakScore="",U.side1PointScore="",U.side2PointScore="",h=0},H=Y=>{U.winningSide=Y;let{s:B,...K}=U;p.sets.push(K),P=E(),A=y(),U=T(),k()},W=Y=>{A.winningSide=Y;let{g:B,...K}=A;U.games.push(K),P=E(),A=y(),k();let X=`side${Y}Score`;U[X]+=1},q=Y=>{P.winningSide=Y;let{p:B,...K}=P;A.points.push(K),P=E(),h=0;let X=()=>l.reduce((Q,ut)=>Q+ut)%4/4>.5?f:3-f,j=Y-1;if(x||F){l[j]+=1,d=X(),U[`side${Y}TiebreakScore`]=l[j],U[`side${3-Y}TiebreakScore`]=l[1-j];let ot=G?1:2;if(l[j]>=L&&l[j]>=l[1-j]+ot)return W(Y),{gameCompleted:!0}}else if(l[1-j]===4&&l[j]===3?l[1-j]-=1:l[j]+=1,U.side1PointScore=u[l[0]],U.side2PointScore=u[l[1]],l[j]===5||l[j]===4&&l[1-j]<3||v&&l[j]===4)return W(Y),{gameCompleted:!0}};if(S(D.srv)&&(f=D.srv),["p","s","g","o"].includes(D.u)&&m.push(D.u),D.shotOutcome&&(P.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 Y=D.winningSide||D.p;if(q(Y)?.gameCompleted)continue}if(S(D.g)||It(D.gameNumber)){let Y=D.winningSide||D.g;A.winningSide=Y;let B=`side${Y}Score`,K=`side${3-Y}Score`;if(m.length&&(m.includes("p"),m=[]),W(Y),U[B]===b&&U[B]-U[K]>=(v?1:2)&&(H(Y),I))break}if(S(D.s)||It(D.setNumber)){let Y=D.winningSide||D.s;if(H(Y),m.length&&(m.includes("p"),m.includes("g"),m=[]),I)break}}return N!==n.length&&console.log({error:"Match completed with excess history"}),(U.side1Score||U.side2Score||U.games.length||U.side1TiebreakScore||U.side2TiebreakScore)&&p.sets.push(U),p.scoreStringSide1=$o({...p,matchUpFormat:o}),p.scoreStringSide2=$o({...p,matchUpFormat:o,reversed:!0}),f=d||f,r&&(e.score=p),{...C,servingSide:f,score:p}}function zo({undoHistory:t,history:e,matchUp:r}){return Ut({element:r,extension:{value:{history:e,undoHistory:t},name:Km}})}function UD({matchUp:t,sideNumber:e}){if(![1,2].includes(e))return{error:Kl};let{history:r=[]}=Ko({matchUp:t});return r.push({srv:e}),zo({matchUp:t,history:r})}function PD({matchUp:t}){return zo({matchUp:t})}function DD({matchUp:t,point:e}){if(!e||!t)return{error:st};if(typeof e!="object")return{error:V,context:{point:e}};let{history:r=[]}=Ko({matchUp:t});return r.push(e),zo({matchUp:t,history:r})}function ND({matchUp:t,game:e}){if(typeof e!="object")return{error:V,context:{game:e}};let{history:r=[]}=Ko({matchUp:t});return r.push(e),zo({matchUp:t,history:r})}function MD({matchUp:t,shot:e}){if(typeof e!="object")return{error:st};let{history:r=[]}=Ko({matchUp:t});return r.push(e),zo({matchUp:t,history:r})}function RD({matchUp:t,set:e}){if(typeof e!="object")return{error:st};let{history:r=[]}=Ko({matchUp:t});return r.push(e),zo({matchUp:t,history:r})}function CD({matchUp:t}){let{history:e=[],undoHistory:r=[]}=Ko({matchUp:t});return r.length&&e.push(r.pop()),zo({matchUp:t,history:e,undoHistory:r})}function bD({matchUp:t}){let{history:e=[],undoHistory:r=[]}=Ko({matchUp:t});return r.push(e.pop()),zo({matchUp:t,history:e,undoHistory:r})}var vD={};var oN={};Jt(oN,{keyValueScore:()=>JD,parseMatchUpFormat:()=>Ye,stringifyMatchUpFormat:()=>cp,tidyScore:()=>nN});var Zs=" ",vT="DEF",JO="COMPLETED",_D="WO",tV="WO/WO",xD="ABN",wD="SUS",LD="RET",FD="INT",OT=[LD,vT,_D,tV,xD,wD,FD];var _T="DEFAULTED";var kD="WALKOVER";var xT="ABANDONED",wT="SUSPENDED",GD="RETIRED",LT="INTERRUPTED";var ZO=[GD,_T,kD],eV="Enter Score",Es="()",Us="[]",VD=["up","left","shift+tab"],BD=["enter","down","tab","right"],Vd="backspace",HD="r",WD="s",jD="a",YD="d",qD="w",$D="i",Bd=[HD,YD,qD,jD,WD,$D],Wp="space",FT=["[","("],Hd=[...VD,...BD,Wp,"]"],t_="-",rV="/",ta=t_,ui=t_,KD=[rV],e_=0,nV=["=","+","num_1","num_2","shift+=","shift+-"],Js=["0","1","2","3","4","5","6","7","8","9"].concat(Bd),r_=Js.map(t=>`shift+${t}`),zD=[ta,Vd].concat(Hd,KD),QD=[Js,r_,zD].join(","),oV=[QD,VD,BD,nV].join(","),yCt=[].concat(...Js,...Js,...zD,...Js,...Js,...Js,...Js,...Js,...Js),n_={OUTCOMEKEYS:Bd,SIDE1KEYS:Js,SIDE2KEYS:r_,MODIFIERS:zD,PROMPT:eV,MOVEUP:VD,MOVEDOWN:BD,HOTKEYS:oV};function jp({scoreString:t,lowSide:e,outcome:r}){if({scoreString:t}=o_({scoreString:t}),e===2){let o=(t&&t[t.length-1])!==Zs?Zs:"";return t+o+r}else return r+Zs+t}function o_({scoreString:t}){if(!t)return{scoreString:""};let e=!1;for(let r of OT){let n=t?.indexOf(r);n===0?t=t.slice(r.length+1).trim()+Zs:n>0&&(t=t.slice(0,n)),n>=0&&(e=!0)}return t?.trim()||(t=""),{scoreString:t,removed:e}}function Bg({analysis:t,scoreString:e,sets:r,lowSide:n}){let o,i;if(!e)return{scoreString:e,sets:r};let{scoreString:s,removed:a}=o_({scoreString:e});if(e=s,a)return{scoreString:e,sets:r,outcomeRemoved:!0};let c=r[r.length-1]||{},u=Object.values(c).filter(g=>g!==void 0).length;c.setNumber&&u===1&&(r=r.slice(0,r.length-1),c=r[r.length-1]||{});let{tiebreakSet:p}=t.setFormat,{tiebreakTo:m,NoAD:d}=p||{},{isTiebreakEntry:l}=Fu({brackets:Us,scoreString:e}),f=iV(e);if(f>=0){o=e.slice(0,f);let{isTiebreakEntry:g}=Fu({brackets:Es,scoreString:o}),{lastOpenBracketIndex:I,isTiebreakEntry:h}=Fu({brackets:Us,scoreString:o}),S=o&&o[o.length-1].trim(),T=o&&!isNaN(S),y=t.isIncompleteSetScore;if(l&&h){let P=o.slice(I+1).split(ui),A=P?.length>0&&P[0]!==void 0&&!isNaN(parseInt(P[0]))&&parseInt(P[0])||void 0,U=P?.length>1&&P[1]!==void 0&&parseInt(P[1])||void 0,N=[A,U];if(U){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 E=c.side1Score?.toString();if(E){let P=E?.slice(0,E.length-1);c.side1Score=!isNaN(P)&&parseInt(P)||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 E=c.side2Score?.toString(),P=c.side1Score?.toString();if(!t.isTiebreakEntry&&!t.isMatchTiebreak)if(c.side2Score){let A=E?.slice(0,E.length-1);c.side2Score=!isNaN(A)&&parseInt(A)||void 0}else{let A=P?.slice(0,P.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 Fu({brackets:t=Es,scoreString:e}){if(!e)return{};let[r,n]=t.split(""),o=e.split(""),i=Math.max(...go(r,o)),s=Math.max(...go(n,o));return{isTiebreakEntry:i>s,lastOpenBracketIndex:i}}function i_({scoreString:t}){if(!t)return!1;let e=t&&t[t.length-1].trim(),r=t&&!isNaN(e),[n,o]=Us.split(""),i=t.split(""),s=Math.max(...go(n,i)),a=Math.max(...go(o,i)),c=Math.max(...go(ui,i));return r&&s>a&&c>s}function iV(t){return t.split("").reduce((n,o,i)=>(o.match(/\d+/g)&&n.push(i),n),[]).pop()}function kT(t){let{lowValue:e=0,NoAD:r=!1,tiebreakTo:n}=t||{},o=r?1:2;return e+1>=n?e+o:parseInt(n)}function XD({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 ZO.includes(e)&&r&&(c=r),{matchUpWinningSide:c}}function Yp({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=qp({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 qp({set:t}){if(t.side1Score||t.side2Score){if(t.side1Score>t.side2Score)return 1;if(t.side2Score>t.side1Score)return 2}else if(t.side1TiebreakScore||t.side2TiebreakScore){if(t.side1TiebreakScore>t.side2TiebreakScore)return 1;if(t.side2TiebreakScore>t.side1TiebreakScore)return 2}}function Wd({analysis:t,set:e}){let r=qp({set:e}),{isDecidingSet:n,isTiebreakSet:o,matchUpScoringFormat:i}=t;return Yp({matchUpScoringFormat:i,isDecidingSet:n,isTiebreakSet:o,set:e})&&r}function s_({analysis:t,scoreString:e,sets:r,value:n}){let o;if(!r?.length)return{sets:[]};let i=r[r.length-1];n=dt(n);let{validSide2Score:s,requiresTiebreak:a}=sV({analysis:t,set:i,value:n});if(s){o=!0,e=(e||"")+n,i.side2Score=n;let c=Wd({analysis:t,set:r[r.length-1]});if(i.winningSide=c||void 0,a){let u=Es.split("")[0];e+=u}else t.isDecidingSet||(e+=Zs)}return{sets:r,scoreString:e,updated:o}}function sV({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 GT({lowSide:t,value:e,sets:r,scoreString:n,winningSide:o,matchUpStatus:i}){let s;return e===HD?n?(s=!0,n=jp({scoreString:n,lowSide:t,outcome:LD}),o=t===2?1:2,i=GD):(s=!0,n=jp({scoreString:n,lowSide:t,outcome:vT}),o=t===2?1:2,i=_T):e===YD?(s=!0,n=jp({scoreString:n,lowSide:t,outcome:vT}),o=t===2?1:2,i=_T):e===qD?(s=!0,r=[],n=_D,o=t===2?1:2,i=kD):e===WD&&n?(s=!0,n=jp({scoreString:n,lowSide:t,outcome:wD}),i=wT,o=void 0):e===jD?(s=!0,n=jp({scoreString:n,lowSide:t,outcome:xD}),i=xT,o=void 0):e===$D&&n&&(s=!0,n=jp({scoreString:n,lowSide:t,outcome:FD}),i=LT,o=void 0),{updated:s,sets:r,scoreString:n,matchUpStatus:i,winningSide:o}}function a_(t){let{sets:e,info:r,scoreString:n,winningSide:o,matchUpStatus:i}=t,{analysis:s,lowSide:a,value:c}=t,u,p;!e?.length&&c!==Vd&&(e=[{setNumber:1}]);let m=e.length-1;if(Bd.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}=GT({lowSide:a,value:c,sets:e,scoreString:n,matchUpStatus:i,winningSide:o}))}else if(c===Vd){if({scoreString:n,sets:e,outcomeRemoved:p}=Bg({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===Wp){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===ta&&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=dt((e[m].side1Score||0).toString()+c).toString().slice(0,2);e[m].side1Score=dt(l),d=e[m].side1Score.toString(),u=!0}else{let l=dt((e[m].side2Score||0).toString()+c).toString().slice(0,2);e[m].side2Score=dt(l),d=[e[m].side1Score,e[m].side2Score].join("-"),u=!0}if(u){let l=(e.slice(0,m)||[]).filter(f=>f).map(f=>{let{side1Score:g,side2Score:I}=f;return[g,I].join("-")}).join(" ");l?n=l+" "+d:n=d}}}return{sets:e,scoreString:n,winningSide:o,matchUpStatus:i,info:r,updated:u}}function c_({analysis:t,auto:e,lowSide:r,scoreString:n="",sets:o,value:i}){let s,a,{tiebreakSet:{tiebreakTo:c,NoAD:u}}=t.setFormat,[p]=Us.split("");if(t.isMatchTiebreakEntry||(n+=p),o[t.setNumber-1]){let{lastOpenBracketIndex:d}=Fu({brackets:Us,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=>dt(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=>dt(S)),h=o[o.length-1];h.side1TiebreakScore=I[0],h.side2TiebreakScore=I[1],n+=i,s=!0}}else{let d=kT({lowValue:dt(i||0),tiebreakTo:c,NoAD:u}),l=[dt(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 u_({analysis:t,lowSide:e,scoreString:r,value:n}){let{setTo:o,tiebreakAt:i,NoAD:s}=t?.setFormat||{},a=n===parseInt(i||o);if(i&&i<o&&n>i)return{scoreString:r};if(s&&n===o||n>o)return{scoreString:r};let c=g(),u=[n,c];e===2&&u.reverse();let m=Es.split("")[0],d=u.join(ta)+(a?m:Zs);r=(r||"")+d;let l={side1Score:u[0],side2Score:u[1]},f=Wd({analysis:t,set:l});return l.winningSide=f||void 0,{scoreString:r,set:l};function g(){return a?n+1:n+1===o?n+(s?1:2):o}}function p_({matchUpFormat:t,scoreString:e,winningSide:r,value:n,sets:o}){let s=(o?.filter(W=>W?.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}=Fu({brackets:Es,scoreString:e}),{isTiebreakEntry:f}=Fu({brackets:Us,scoreString:e}),g=l||f,I=!!u.tiebreakSet,h=e?.[e.length-1]?.trim(),S=e&&!isNaN(h),T=!g&&h===ta,y=l&&FT.includes(h),E=f&&FT.includes(h),P=f&&h===ui,A=e?.split(""),[U]=Us.split(""),N=A&&Math.max(...go(U,A)),D=A&&Math.max(...go(ui,A)),M=A&&D>N,R=o[o.length-1]?.winningSide,b=o?.length&&!R,v=OT.find(W=>e?.indexOf(W)>=0),O=!isNaN(n),x=n===Wp,F=Hd.includes(n),w=e?.split("").find(W=>FT.includes(W)),L=F&&f&&!E&&(P||!i_({scoreString:e}));return{isTiebreakSetValue:I&&O,matchUpScoringFormat:a,setNumber:s,setFormat:u,matchTiebreakHasJoiner:M,isGameScoreEntry:b,isSpace:x,isCloser:F,isTiebreakCloser:F&&w&&g&&S,isDecidingSet:c,isTiebreakSet:I,isTimedSet:p,isNumericEnding:S,isNumericValue:O,hasOpener:w,hasOutcome:v,finalSet:m,finalSetIsComplete:d,lastSetIsComplete:R,isInvalidSetTiebreakValue:x&&g&&y,isInvalidMatchTiebreakValue:L,isTiebreakEntry:g,isSetTiebreakEntry:l,isMatchTiebreakEntry:f,isIncompleteSetScore:T,isIncompleteSetTiebreak:y,isIncompleteMatchTiebreak:E,isPartialMatchTiebreakValue:P}}function JD(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(!QD.includes(r))return{updated:!1,info:"invalid key"};c&&(e=3-e);let{matchUpWinningSide:l}=XD({sets:o,winningSide:i,matchUpStatus:s,matchUpFormat:a});i=l;let f=p_({value:r,winningSide:i,scoreString:n,sets:o,matchUpFormat:a});if(KD.includes(r)&&(r=ta),f.hasOpener&&f.isTiebreakEntry&&!f.isTiebreakSet&&d&&dt(r)===0&&(f.isTiebreakCloser=!0),Hd.includes(r)&&f.hasOpener&&(r=""),Hd.includes(r)&&(r=Wp),f.lastSetIsComplete){let g=n?.length&&n[n.length-1];n&&g!==" "&&(n+=" ")}if(f.isTimedSet)({info:m,sets:o,scoreString:n,updated:p,matchUpStatus:s,winningSide:i}=a_({analysis:f,lowSide:e,scoreString:n,sets:o,matchUpStatus:s,winningSide:i,value:r}));else if(Bd.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}=GT({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===Vd)p=!0,{scoreString:n,sets:o}=Bg({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===ta&&!f.isMatchTiebreakEntry)(!f.isSetTiebreakEntry||f.isSetTiebreakEntry&&!f.isNumericEnding)&&(p=!0,{scoreString:n,sets:o}=Bg({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([ta,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}=s_({analysis:f,scoreString:n,sets:o,value:r}));else if(f.isInvalidMatchTiebreakValue)m="invalid matchUp tiebreak character";else if(f.isInvalidSetTiebreakValue)m="invalid set tiebreak character";else if(f.isTiebreakCloser){let g=f.isSetTiebreakEntry?Es:Us,I=g.split("").reverse()[0],h=g.split("")[0],S=o[o.length-1],{tiebreakFormat:T}=f.setFormat,{tiebreakTo:y,NoAD:E}=T||{},P=qp({set:S});if(!f.isTiebreakSet){let U=parseInt(n.split(h).reverse()[0]),N=kT({lowValue:U,tiebreakTo:y,NoAD:E});P===1?(S.side1TiebreakScore=N,S.side2TiebreakScore=U):(S.side1TiebreakScore=U,S.side2TiebreakScore=N)}n=(n||"")+I,f.isDecidingSet||(n+=Zs);let A=Wd({analysis:f,set:S});S.winningSide=A||void 0,p=!0}else if(f.isTiebreakSetValue)({info:m,scoreString:n,sets:o,updated:p}=c_({analysis:f,auto:u,lowSide:e,scoreString:n,sets:o,value:r}));else if(f.isSetTiebreakEntry){let[g]=Es.split(""),I=Math.max(...go(g,n.split(""))),h=n.slice(I+1),S=h&&dt(h)===e_,T=dt(h?h+r:r),{tiebreakFormat:y}=f.setFormat,{tiebreakTo:E,NoAD:P}=y||{};!S&&h.length<2?P&&T>E-1?m="invalid low value for NoAD tiebreak":(p=!0,n=(n||"")+r):m=S?"tiebreak begins with zero":"tiebreak digit limit"}else if(f.isCloser)m=`invalid key: ${r}`;else if(f.isGameScoreEntry)m="game scoreString entry";else if(f.lastSetIsComplete||!o.length){p=!0;let{scoreString:g,set:I}=u_({analysis:f,lowSide:e,scoreString:n,value:dt(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}=XD({sets:o,winningSide:i,matchUpStatus:s,matchUpFormat:a});return i=g,g&&(!s||[Xt,un].includes(s))?(s=JO,o=o.filter(I=>{let{side1Score:h,side2Score:S,side1TiebreakScore:T,side2TiebreakScore:y}=I;return h||S||T||y})):n&&!i&&![wT,xT,LT].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 jd="\\d+-\\d+",$p="\\d+-\\d+\\(\\d+\\)",Hg="\\[\\d+-\\d+\\]",aV="\\d+-\\d+\\(\\d+-\\d+\\)",m_=new RegExp(`(${jd}),`,"g"),d_=new RegExp(`(${$p}),`,"g"),cV=[jd,$p,Hg,aV],uV=["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"],pV=uV.map(t=>{let r=t.split("").map(n=>cV[n]).join(" ");return new RegExp(`^${r}$`)});function ZD(t){return!t||pV.some(e=>e.test(t))}function l_(t){let e="[];",r="()",n=e+r,o=[e[0],r[0]],i=Object.assign({},...n.split("").map(c=>({[c]:0}))),s="",a=t.split("").map(c=>{let u=n.includes(c)&&c,p=o.includes(u);if(p&&u)return i[u]+=1,s=u,c;if(!p&&u&&s&&u!==s){i[s]-=1;let m=e.includes(s)&&e||r.includes(s)&&r||"",d=m.split("").find(l=>l!==s);if(m.includes(u))i[s]||(s="");else return i[u]||(s=""),d}return c}).join("");return t!==a?a:t}function Yd(t){return/^\(\d+\)$/.test(t)||/^\(\d+$/.test(t)}function f_(t){return/^\(\d+-\d+\)$/.test(t)||/^\[\d+-\d+\]$/.test(t)}function _a(t){let r=(n=>n?.split("-").join("").split("/").join(""))(t);if(/^\d+$/.test(r)&&r.length===2){let n=r.split("");return Math.abs(n.reduce((i,s)=>+i-+s))===1}return!1}function Kp(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 tN(t){return t.length===2?t.split("").join("-"):([", ",",","/"," "].forEach(e=>t=t.split(e).join("-")),t=t.replace(/-{2,}/,"-"),t)}function g_(t){return t.startsWith("(")&&t.endsWith(")")}function I_({score:t,applied:e}){t=l_(t);let r=/\)(\d+)/g;if(r.test(t))for(let P of t.match(r)){let A=P.replace(")",") ");t=t.replace(P,A)}t=t.replace(/\)\//g,") / "),t=t.replace(/\/\)/g,")");let n=/\(([\d- ]+)\)/g,o=/\(([\d- ]+)\)/,i=t.match(n);for(let P of i||[]){let[A]=P.match(o).slice(1),U=A.replace(/ /g,"");t=t.replace(P,`(${U})`)}let s=/\(\(\d-\d\)\)/g;if(s.test(t)){let P=t.match(s);P.length&&P.forEach(A=>{let U=A.match(/\((\(\d-\d\))\)/).slice(1)[0];t=t.replace(A,U)})}if(s=/\(\((\d)\)\)/g,s.test(t)){let P=t.match(s);P.length&&P.forEach(A=>{let U=A.match(/\((\(\d\))\)/).slice(1)[0];t=t.replace(A,U)})}/(^|\s)6-,/.test(t)&&(t=t.replace(/(^|\s)6-,/g,"6-0,"));let a=new RegExp(/[-,]{2,}/g);t=t.replace(a,"-"),["- "," -"].forEach(P=>{let A=new RegExp(`(\\d+)${P}(\\d+)`,"g"),U=t.match(A);U&&U.forEach(N=>t=t.replace(N,N.split(P).join("-")))}),/^[(-/,]+$/.test(t)&&(t=""),/\)[-/,]+$/.test(t)&&(t=t.slice(0,t.length-1)),/\d \/\d/.test(t)&&(t=t.replace(/ \//g,"/")),t.includes(" /")&&(t=t.replace(/ \//g," "));let c=/\(\d+, \)/g;c.test(t)&&t.match(c).forEach(A=>{let[U]=A.match(/\((\d+), \)/).slice(1);U.length===2?t=t.replace(A,`(${U})`):U.length===1&&U==="6"&&(t=t.replace(A,"(6-0)"))});let u=/\((\d+)\/\)/g;u.test(t)&&t.match(u).forEach(A=>{let[U]=A.match(/\((\d+)\/\)/).slice(1);U.length===2?t=t.replace(A,`(${U})`):U.length===1&&U==="6"?t=t.replace(A,"(6-0)"):t=t.replace(A,`(${U})`)});let p=/\d\/\d\/,/g;p.test(t)&&t.match(p).forEach(A=>{let[U]=A.match(/(\d\/\d)\/,/).slice(1);t=t.replace(A,`${U},`),e.push("slashComma")});let m=/\(\/(\d+)\)/g;m.test(t)&&t.match(m).forEach(A=>{let[U]=A.match(/\(\/(\d+)\)/).slice(1);U.length===2?t=t.replace(A,`(${U})`):U.length===1&&parseInt(U)<6?t=t.replace(A,`(6-${U})`):t=t.replace(A,`(${U})`)});let d,l,f,g,I,h=()=>{I=yr(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[P]=t.match(S).slice(1);t=t.replace(S,P+")")}if(I["("]===I[")"]&&I["("]>1){let P=t.split(")(").join(") (").split(" ");P.every(g_)?t=P.map(A=>{let U=A.slice(1,A.length-1);return U.length>2?U:A}).join(" "):t=P.join(" ")}h();let T=/[A-Za-z]+/.test(t),y=/\d+/.test(t);if(!T&&!y)return{score:""};if(/^\[.+\]$/.test(t)&&"()/,- ".split("").some(P=>I[P])&&(t=t.slice(1,t.length-1)),/^\(.+\)$/.test(t)&&I["("]===1&&I[")"]===1&&"[]/,".split("").some(P=>I[P]>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 P=[],A=0;for(let U of t.split("").reverse())U===")"&&(A?P.push("("):A+=1),U==="("&&(A-=1),P.push(U);P.reverse(),t=P.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 P="",A=0;for(let U of t.split(""))U==="("&&(A?P+=")":A+=1),U===")"&&(A-=1),P+=U;t=P}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 E=P=>{let A=P.indexOf("("),U=P.indexOf(")");return A>=0&&U>=0&&A<U};if(/^\([\d ]+.*[\d ]+\)$/.test(t)&&I["("]===I[")"]){let P=t.slice(1,t.length-1);E(P)&&(t=P,h())}return{score:t,applied:e}}function ku(t){if(!/^[\d-]+(\(\d\))*$/.test(t))return t;let e=go("-",t.split(""));if(!e.length)return t;let r=t.split("-"),n=!(r.length%2),o=!!(e.length%2);return n&&o&&e.length>r.length/2&&e.filter((s,a)=>a%2).forEach(s=>{t=t.substring(0,s)+" "+t.substring(s+1)}),t}function h_({score:t,applied:e}){return t.includes("( ")&&(e.push("removeParenSpacingAfterOpen"),t=t.split("( ").map(r=>r.trim()).join("(")),t.includes(" )")&&(e.push("removeParenSpacingBeforeClose"),t=t.split(" )").map(r=>r.trim()).join(")")),[m_,d_].forEach(r=>{let n=t.match(r);n?.length&&(n.forEach(o=>{t=t.replace(o,o.slice(0,o.length-1)+" ")}),e.push("setsEndComma"))}),t=t.split(" ").filter(Boolean).map(ku).join(" "),{score:t,applied:e}}function S_({score:t}){if(typeof t!="string")return{score:t};let e=d=>d?.split("-").join("").split("/").join(""),r=d=>d.split("[").join("(").split("]").join(")");t=t.split(", ").join(" ");let n=t.split(" ");t=n.map(d=>{let l=/^-(\d+)$/;if(l.test(d)){let[f]=d.match(l).slice(1);if(f.length===2)return f.split("").join("-")}return d}).join(" "),n=t.split(" ");let o=n.filter(Yd),i=0,s="";for(let d of o){let l=go(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,E=[T,y].sort().reverse().join("-"),P=[f.join(" "),[E,d].join("")].join(" ");s+=P,i=l+1}}}}if(o.length&&s.length){let d=n.slice(i).join(" ");return s=[s,d].join(" "),{score:s.trim()}}if(n.length===2&&["(","["].some(d=>n[1].includes(d))){let l=e(n[0]).split("");if(Math.abs(l.reduce((g,I)=>+g-+I,0))===1)return n[1]=r(n[1]),{score:n.join("")}}let a=n.map(d=>f_(d)&&"bracket"||_a(d)&&"set");if(a.includes("set")&&a.includes("bracket")){let d,l="";return n.forEach((f,g)=>{a[g]==="bracket"&&d==="set"?(f=r(f),l+=f):l+=` ${f}`,d=a[g]}),{score:l.trim()}}n=t.split(" ");let c,u=n.map(d=>{let l=new RegExp(/^(\d+)-(\d+)$/);if(l.test(d)){let[f,g]=d.match(l).slice(1),I=Math.abs([f,g].reduce((S,T)=>+S-+T)),h=Math.max(f,g);if(I===1)return c="tiebreakSet",c;if(I>=2&&h>=7&&c==="tiebreakSet")return c="tiebreak",c}}),p=go("tiebreak",u);if(p.length){let d="";n.forEach((l,f)=>{p.includes(f)?d+=`(${l}) `:p.includes(f+1)?d+=`${l}`:d+=`${l} `}),t=d.trim()}let m=/(\d+-\d+)\((\d+)-(\d+)\)$/;if(m.test(t)){let[d,l,f]=t.match(m).slice(1),I=Math.max(l,f)>=10;!_a(d)&&I&&(t=t.replace(m,`${d} [${l}-${f}]`))}return u=[],t=t.split(" ").map(d=>{let l=/^\((.*)\)$/,f=l.test(d),g=new RegExp(Hg).test(d)&&"super"||new RegExp($p).test(d)&&"tiebreak"||new RegExp(jd).test(d)&&"standard"||"unknown";return u.push(g),g==="standard"&&f?d.match(l)[1]:d}).join(" "),{score:t}}function T_({score:t,applied:e}){for(let 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=ku(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 E=/(?<!-)(\d+)\/(\d+)(?!-)/g;if(E.test(t)){let D=t.match(E),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 P=/(.*)\s(1\d)\s(\d+)$/;if(P.test(t)){let[D,M,R]=t.match(P).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(w=>parseInt(w));Math.abs(O-x)===1&&(t=t.replace(D,`${M}${R}(${b})${v}`),e.push("spaceSeparatedSetPattern"))}let U=/\d-\d \(\d{1,2}\)(\s|$|,)/g;for(let D of t.match(U)||[]){let M=/(\d-\d) \((\d{1,2})\)(\s|$|,)/,[R,b,v]=D.match(M).slice(1),[O,x]=R.split("-").map(w=>parseInt(w));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 y_({score:t,matchUpStatus:e}){let r=t?.split(" ");t=r.map(a=>{if(a.endsWith("]")){let c=a.split("[");if(_a(c[0]))return c[0]+`(${c[1].slice(0,c[1].length-1)})`}return a}).join(" ");let n=new RegExp(/(\([\d ]+\))/g);if(n.test(t))for(let a of t.match(n)){let u=a.replace(" ","-").match(/\((.*)\)/)?.[1];if(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=Kp(u.split(""),p)}}t=t.replace(a,`(${u})`)}r=t?.split(" ");let o=new RegExp(/^(\d[-/]+\d)\((\d+)[-/]+(\d+)\)$/),i=r.length-1;t=r.map((a,c)=>{let u=[void 0,"","COMPLETED"].includes(e)||c!==i;if(o.test(a)&&u){let[p,m,d]=Array.from(a.match(o)).slice(1),l=Math.min(m,d);return`${p}(${l})`}return a}).join(" "),r=t?.split(" "),o=new RegExp(/^(\d{2})\((\d+)\)$/),t=r.map(a=>{if(o.test(a)){let[c,u]=Array.from(a.match(o)).slice(1),p=c.split("");return`${p[0]}-${p[1]}(${u})`}return a}).join(" "),r=t?.split(" "),o=new RegExp(/^\((\d[-/]+\d)\)(\d+)$/),t=r.map(a=>{if(o.test(a)){let[c,u]=Array.from(a.match(o)).slice(1);return _a(c)?`${c}(${u})`:c}return a}).join(" "),r=t?.split(" "),o=new RegExp(/^1-0\((\d+)\)$/),t=r.map(a=>{if(o.test(a)){let[c]=a.match(o).slice(1);return`[${c<9?10:parseInt(c)+2}-${c}]`}return a}).join(" ");let s=/\((\d)+0 /;if(s.test(t)){let a=t.match(s)[1];t=t.replace(s,`(${a}) `)}return{score:t}}function A_({score:t,attributes:e,identifier:r}){if(typeof t!="string")return{score:t,identifier:r};let n=new RegExp(/\([\d,/ ]+\)/g),o=t.match(n);for(let m of o||[]){let l=m.match(/^\((.*)\)$/)?.slice(1)?.[0],g=t.split(m)[0].split(")").reverse()[0].replace(/\D/g,"");if(l?.length===2&&g?.length>=2){let S=g.slice(g.length-2).split("").map(y=>parseInt(y));if(Math.abs(S[0]-S[1])===1)continue}let I=tN(l),h=ku(I);t=t.replace(m,`(${h})`).trim()}let i=new RegExp(/\[[\d,/ ]+\]/g);t.match(i)?.forEach(m=>{let d=tN(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(",")||Yd(h)),f=d.every(h=>h.includes("/")||Yd(h)),g=d.every(h=>h.includes("-")||Yd(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(E=>parseInt(E.trim())),y=Math.min(...T);h==="set"?m+=`(${y}) `:m+=`[${T.join("-")}] `,h="tiebreak"}}),t=m.trim()}}let u=yr(t.split(""));u["("]===1&&u[")"]===1&&t.startsWith("(")&&t.endsWith(")")&&(t=t.slice(1,t.length-1),u["-"]===1&&_a(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 VT({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 Wg(t){let e=t.indexOf("1"),r=t.split(""),n=r.every(o=>!isNaN(o));if(n&&t.length===3&&e===0){let o=Kp(r,e);if(o)return o}if(n&&t.length===7&&e>3){let o=r.slice(4),i=Kp(o,e-4);if(i)return`${r[0]}-${r[1]} ${r[2]}-${r[3]} ${i}`}}function eN(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}=VT({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=Wg(e);u&&e!==u&&r.push("parsedSuperPattern"),e=u??e}else{let u=Ee(e.split(""),2).map(h=>h.join("")),p=u.map(h=>{let[S,T]=h.split("").map(P=>parseInt(P)),y=Math.abs(S-T),E=S>T?1:2;return y>1&&E||E*-1}),m=p.reduce((h,S)=>h>0&&S>0,1),d=yr(p),l=p.map(h=>Math.abs(h)),f=yr(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,E,P]=a,A=p.reduce((U,N,D)=>N<0?D:U,void 0);if(A===0){let U=Math.min(T,y);e=`${h}-${S}(${U}) ${E}-${P}`,r.push("chunkSplitTiebreak1")}else if(A===1){let U=Math.min(E,P);e=`${h}-${S} ${T}-${y}(${U})`,r.push("chunkSplitTiebreak2")}else e=`${h}-${S} ${T}-${y}`,r.push("chunkSplitTrimExtraneous")}}else if(a.length===8){let[h,S,T,y,E,P,A,U]=a;g||I?a[5]===1&&(g?e=`${h}-${S}(${T}) ${y}-${E} [${P}${A}-${U}]`:e=`${h}-${S} ${T}-${y}(${E}) [${P}${A}-${U}]`):(p[0],p[1])}}}return{score:e,applied:r,matchUpStatus:n}}function BT(t){let e=[0,0],r=[],n=t.split(" "),o=/(\d+)-(\d+)/;n.forEach(c=>{if(o.test(c)){let u=c.match(o).slice(1).map(m=>parseInt(m)),p=u[0]>u[1]&&1||u[1]>u[0]&&2;p&&(e[p-1]+=1,r.push(p))}});let i=e[0]>e[1]&&1||e[1]>e[0]&&2,s=e[0]>0&&e[0]===e[1],a=e.reduce((c,u)=>c+u,0);return{setsWon:e,setsTied:s,setWinners:r,totalSets:a,winningSide:i}}function E_({score:t,matchUpStatus:e,attributes:r}){let n=[],o,i=t.split(" "),s=i.length;t=i.map((p,m)=>{if(new RegExp($p).test(p)){let l=p.slice(3),f=p.slice(0,3),g=f.split("-");if(!_a(f)&&!e){let I=Math.max(...g),h=f.indexOf(I),S=[I,I-1];return h&&S.reverse(),S.join("-")+l}}else if(p.length===2&&Zt(p))return p.split("").join("-");p=ku(p);let d=new RegExp(`^${Hg}$`).test(p)&&"super"||new RegExp(`^${$p}$`).test(p)&&"tiebreak"||new RegExp(`^${jd}$`).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(E=>parseInt(E)>h||m&&parseInt(E)<=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}=BT(t);if(u===1&&r?.removed==="6"&&(t+=" 6-0"),t.split(" ").length>2&&Math.max(...a)>=2&&c[0]===c[1]&&(t=t.split(" ").slice(0,2).join(" ")),Math.max(...a)>2){let p=[0,0];t=t.split(" ").map((m,d)=>(p[c[d]]+=1,Math.max(...p)>2?void 0:m)).filter(Boolean).join(" ")}return{score:t,profile:n}}function U_({score:t}){let{setsTied:e,winningSide:r}=BT(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 mV({score:t}){return t=t?.toString().toLowerCase()||"",{score:t}}function dV({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 lV({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=Kp(r.split(""),n);return e.push("getSuper"),o}}else{let{score:o,applied:i}=eN({score:r,applied:[]});o!==r&&(r=o,e.push(...i))}}return r}).join(" "),{score:t,applied:e})}function fV({score:t,applied:e}){return typeof t!="string"?{score:t}:[3,4].includes(t.length)&&Wg(t)?{score:Wg(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 gV({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 IV({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 hV({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 SV({score:t}){return new RegExp(/-\d+\/\d+-/).test(t)&&(t=t.split("/").join(" ")),{score:t}}function TV({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 yV({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 AV({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 EV({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 P_={handleTiebreakSlashSeparation:yV,handleSetSlashSeparation:SV,punctuationAdjustments:I_,handleGameSeparation:TV,joinFloatingTiebreak:S_,handleBracketSpacing:h_,handleSpaceSeparator:AV,separateScoreBlocks:lV,matchKnownPatterns:T_,removeDanglingBits:hV,removeErroneous:fV,handleWalkover:gV,properTiebreak:y_,handleNumeric:eN,handleRetired:IV,containedSets:A_,sensibleSets:E_,stringScore:mV,superSquare:U_,setBuilder:VT,excisions:EV,replaceOh:dV};var rN={},UV=[],PV=["handleNumeric","handleWalkover","handleRetired","replaceOh","stringScore","punctuationAdjustments","excisions","handleSpaceSeparator","matchKnownPatterns","removeDanglingBits","handleBracketSpacing","matchKnownPatterns","containedSets","separateScoreBlocks","handleGameSeparation","removeErroneous","joinFloatingTiebreak","handleSetSlashSeparation","handleTiebreakSlashSeparation","properTiebreak","sensibleSets","superSquare"],DV=["handleNumeric","separateScoreBlocks","sensibleSets","superSquare"];function nN(t){if(!t.score)return{error:V};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=P_[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(PV);let g=ZD(l);return g||(l=e.toString().replace(/\D/g,""),m?.removed&&(m.removed=void 0),f(DV),g=ZD(l),g||(UV.push({score:l,fileName:o,sheetName:r}),l="")),p.forEach(I=>{rN[I]||(rN[I]=0),rN[I]+=1}),{matchUpStatus:u?.toUpperCase(),modifications:c,attributes:m,isValid:g,score:l}}var iN={};Jt(iN,{analyzeScore:()=>jg,analyzeSet:()=>Gu,checkScoreHasValue:()=>Ie,checkSetIsComplete:()=>Yp,getSetComplement:()=>qg,getTiebreakComplement:()=>zp,isValidMatchUpFormat:()=>Dr,parseScoreString:()=>qd,validateScore:()=>Yg,validateTieFormat:()=>ur});function jg({existingMatchUpStatus:t,matchUpFormat:e,matchUpStatus:r,winningSide:n,score:o}){let i=o?.sets??[],a=(i?.filter(A=>A?.winningSide)||[]).reduce((A,U)=>{let{winningSide:N}=U;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=yr(a)[l],g=d?.setFormat?.timed||d?.finalSetFormat?.timed,I=d?.bestOf,h=I&&Math.ceil(I/2)||1,S=r??t,T=S&&[Rt,nr,bt].includes(S),y=!d||!i.length||i.every((A,U)=>{let N=U+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),w=v??O,{finalSetFormat:L,setFormat:G}=d,k=D&&L||G;if(w){let{tiebreakTo:W,NoAD:q}=k?.tiebreakFormat||{},Y=Math.max(v??0,O??0);if(q&&Y>W||Y<W&&x&&(M&&!T||!M))return!1}return k.setTo?!(!k.noTiebreak&&F>k.setTo+1):!0}),E=(!e||l===h)&&f===1&&a.indexOf(l)+1||void 0;return{valid:!!(y&&(n&&p>m&&n===E||n&&T||!n&&!E&&(![he,Rt,nr,bt].includes(S)||g&&S===he)))}}function Yg({existingMatchUpStatus:t,matchUpFormat:e,matchUpStatus:r,winningSide:n,score:o}){if(typeof o!="object")return{error:V};let{sets:i,scoreStringSide1:s,scoreStringSide2:a}=o,c="scoreString must be a string!";if(s!==void 0&&typeof s!="string")return{error:V,info:c};if(a!==void 0&&typeof a!="string")return{error:V,info:c};if(i!==void 0&&!Array.isArray(i))return{error:V,info:ai("sets")};if(i?.length){let u=i.map(m=>m?.setNumber).filter(Boolean);if(u.length!==pt(u).length)return{error:V,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(P=>P.some(A=>![void 0,null].includes(A))).every(P=>P.every(A=>It(A))))return{error:V,info:"non-numeric values"};if(![T,S].filter(P=>![void 0,null].includes(P)).every(P=>It(P)))return{error:V,info:"non-numeric values"};if(S&&![1,2].includes(S))return{error:V,info:"winningSide must be 1 or 2"}}let{valid:p}=jg({existingMatchUpStatus:t,matchUpStatus:r,matchUpFormat:e,winningSide:n,score:o});if(!p)return{error:cE,info:"score is invalid for matchUpFormat or winningSide does not match calculated winningSide"}}return{valid:!0}}var qg=t=>{let{isSide1:e,lowValue:r,setTo:n,tiebreakAt:o,NoAD:i}=t;if(r===void 0)return!1;let s=dt(r);s?.toString().length>2&&(s=parseInt(s.toString().slice(0,2))),o&&o<n&&s>o&&(s=o);let a;return i&&!o?(s>n&&(a=n),a=s<n?n:n-1):a=s+1<n&&n||o&&o<n&&s===o&&n||!o&&s+2||n+1,[e?s:a,e?a:s]},zp=t=>{let{isSide1:e,lowValue:r,tiebreakTo:n,tiebreakNoAd:o}=t;if(r===void 0)return!1;let i=typeof r=="string"?parseInt(r):r;i?.toString().length>2&&(i=parseInt(i.toString().slice(0,2))),o&&i>n-1&&(i=n-1);let s=NV({lowValue:i,NoAD:o,tiebreakTo:n});return[e?i:s,e?s:i]};function NV(t){let{lowValue:e,NoAD:r,tiebreakTo:n}=t,o=r?1:2;return e+1>=n?e+o:n}function qd({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&&zp({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 D_({matchUpScoringFormat:t,isDecidingSet:e,isTiebreakSet:r,isTimedSet:n,setObject:o}){if(!o)return;let i=qp({set:o});return Yp({matchUpScoringFormat:t,set:o,isDecidingSet:e,isTiebreakSet:r,isTimedSet:n})&&i||void 0}function Gu(t){let{setObject:e,matchUpScoringFormat:r}=t;if(!e)return{error:zl};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(w=>w!==void 0).length,h=f.filter(w=>w!==void 0).length,S=g.filter(w=>w!==void 0).length,T=l?.filter(w=>!isNaN(w)).length,y=g?.filter(w=>!isNaN(w)).length,{tiebreakAt:E}=c||{},P=E&&l.filter(w=>w>=E).length===2,A=P&&(l[0]>l[1]&&1||l[1]>l[0]&&2||void 0),U=!!(y&&!T),N=!!e?.winningSide,{error:D,result:M}=MV({sideTiebreakScores:g,sideGameScores:l,setFormat:c,setObject:e}),{error:R,result:b}=RV({sideTiebreakScores:g,setObject:e,setFormat:c}),v=m&&!U&&M||u&&U&&b||p,O=d&&!(u&&!U)&&!(m&&U)&&(!N||v),x=D_({isTimedSet:p,matchUpScoringFormat:r,isDecidingSet:a,isTiebreakSet:U,setObject:e}),F={expectTiebreakSet:u,expectTimedSet:p,hasTiebreakCondition:P,isCompletedSet:N,isDecidingSet:a,isTiebreakSet:U,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&&(U?(F.isValidTiebreakSetOutcome=b,b||(F.tiebreakSetError=R)):(F.isValidStandardSetOutcome=M,M||(F.standardSetError=D))),F}function MV({setObject:t,setFormat:e,sideGameScores:r,sideTiebreakScores:n}){if(!t)return{result:!1,error:zl};let o=!!e?.tiebreakSet,i=!!e?.timed;if(!e||o||i)return{result:!1,error:V};if(!(r?.filter(M=>!isNaN(M)).length===2))return{result:!1,error:WI};let{setTo:a,tiebreakAt:c,tiebreakFormat:u,NoAD:p}=e||{};if(!!!(a&&r?.find(M=>M>=a)))return{result:!1,error:WI};let d=[1,2].includes(t?.winningSide);if(!t||!d)return{result:!1,error:Dm};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,E=n?.[l],P=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(G=>G>=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(!E||!P||E<P)return{result:!1,error:{message:"winningSide tiebreak value is not high"}};let x=M?1:2,F=E-P,w=P>=R-1;if(F&&w&&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 U=p?1:2,N=I>=a-1;return h&&N&&!A&&h<U?{result:!1,error:{message:"invalid winning game scoreString (3)"}}:h>U&&g>a?{result:!1,error:{message:"invalid winning game scoreString (4)"}}:{result:!0}}function RV({setObject:t,setFormat:e,sideTiebreakScores:r}){if(!t)return{result:!1,error:zl};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:Dm};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 N_(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===rt)?.tieFormat;u=u||m||o&&c?.tieFormat?.tieFormatName===o&&c.tieFormat||o&&no({namedFormat:o,hydrateCollections:r,isMock:a,event:c})||c?.tieFormat||no({event:c,isMock:a,hydrateCollections:r}),p=void 0}else p||(u=void 0,c?.matchUpFormat||(p=Dn));if(u){let m=ur({gender:c?.gender,enforceGender:n,tieFormat:u});if(m.error)return m}return{tieFormat:u,matchUpFormat:p}}function M_(t){let e=t.drawDefinition,{existingQualifyingPlaceholderStructureId:r,appliedPolicies:n,qualifyingOnly:o,drawEntries:i,structureId:s,tieFormat:a,idPrefix:c,isMock:u,event:p}=t,m=t.qualifyingProfiles,d=m?.length?DT({hasExistingDrawDefinition:!0,uuids:t.uuids,qualifyingProfiles:m,appliedPolicies:n,qualifyingOnly:o,tieFormat:a,idPrefix:c,isMock:u}):void 0;if(d?.error)return d;e.structures=e.structures?.filter(({structureId:E})=>E!==r),e.links=e.links?.filter(({source:E})=>E.structureId!==r);let{qualifiersCount:l,qualifyingDrawPositionsCount:f,qualifyingDetails:g}=d??{};f&&(d?.structures&&e.structures?.push(...d.structures),d?.links&&e.links?.push(...d.links));let I=e.structures?.find(({stage:E,stageSequence:P})=>E===rt&&P===1),{qualifiersCount:h}=hs({stageSequence:1,drawDefinition:e,structureId:s,stage:rt}),S=Math.max(l??0,h??0),T=BS({qualifiersCount:S,drawDefinition:e,stage:rt});if(T.error||(T=wp({drawSize:f,stage:ct,drawDefinition:e}),T.error))return T;CV({drawDefinition:e,drawEntries:i,event:p});let y=bV({mainStructure:I,qualifyingDetails:g,drawDefinition:e});return y.error?y:{drawDefinition:e,structureId:s}}function CV({drawDefinition:t,drawEntries:e,event:r}){for(let n of(e??[]).filter(({entryStage:o})=>o===ct)){let o={...n,entryStage:n.entryStage??rt,drawDefinition:t,event:r};Id(o)}}function bV({mainStructure:t,qualifyingDetails:e,drawDefinition:r}){for(let n of e||[]){let{finalQualifyingRoundNumber:o,finalQualifyingStructureId:i,roundTarget:s,finishingPositions:a,linkType:c}=n,u=t&&Ca({targetStructureId:t.structureId,sourceStructureId:i,sourceRoundNumber:o,finishingPositions:a,targetEntryRound:s,linkType:c})?.link;if(u?.error)return u;u&&(r.links||(r.links=[]),r.links.push(u))}return{error:void 0}}function HT(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:V,info:"Not enough participants for roundsCount"}:t.roundsCount&&t.restrictRoundsCount!==!1&&t.roundsCount>31?{error:V,info:"roundsCount must be less than 32"}:{participantIds:e}}function $d(t){let e=[],{roundsCount:r=1,drawDefinition:n,matchUpsCount:o,structureId:i,idPrefix:s,isMock:a,event:c}=t,u,p=HT(t);if(p.error)return p;for(let m of tt(1,r+1)){let d=Lu({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 C_(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=R_({scaleName:`${n}.${Hm}`,participant:u,eventType:o});!p&&n&&(p=R_({scaleAccessor:s,participant:u,scaleName:n,eventType:o})),p&&!i[c]&&(i[c]=p)}return i}function R_({scaleType:t=hi,scaleAccessor:e,participant:r,scaleName:n,eventType:o}){let a=(r&&Ao({scaleAttributes:{eventType:o??ks,scaleType:t,scaleName:n},participant:r}))?.scaleItem?.scaleValue;return e&&ht(a)?a[e]:a}function Kd(t){let e=OV(t);if(e?.error)return e;let r=HT(t);if(r.error)return r;let n=vV(t);if(n.error)return n;let o=C_(t),i=t.tournamentRecord?.isMock??t.isMock,s=t.eventType??t.event?.eventType,a=[],c=[],u;for(let p of tt(1,(t.roundsCount??1)+1)){let m=Gd({...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 vV(t){if(t.structureId)return t.structureId;let e=t.drawDefinition,r=e?.structures?.filter(i=>i.stageSequence===1)?.reduce((i,s)=>{let a=s.stage&&Gs[s.stage];return pr({structure:s})&&a>(Gs[i?.stage]||1)?s:i},void 0),n=e?.structures?.find(i=>i.structureId===r?.structureId);return n?pr({structure:n})?{structure:n}:{error:ma}:{error:wt}}function OV(t){return t.roundsCount&&typeof t.roundsCount!="number"?{error:V,info:"roundsCount must be a number"}:typeof t.drawDefinition!="object"||t.drawDefinition.drawType&&t.drawDefinition.drawType!==$r?{error:ma}:!Array.isArray(t.drawDefinition?.entries)&&t.participantIds&&!Array.isArray(t.participantIds)?{error:V,info:"Missing Entries"}:{error:void 0}}function b_(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===rt)&&m&&Qr.includes(m)),c=a?.map(St),u=a?Math.floor(a.length/2):0;if(t.automated)return _V({...t,participantIds:c});{let p=$d({roundsCount:t.roundsCount,drawDefinition:r,matchUpsCount:u,idPrefix:o,isMock:i,event:s});if(p.error)return p;p.matchUps?.length&&Od({matchUps:p.matchUps,suppressNotifications:!0,tournamentRecord:e,drawDefinition:r,structureId:n,event:s})}return{...C}}function _V(t){let{restrictEntryStatus:e,generateMatchUps:r,structureId:n,matchUpIds:o,scaleName:i,scaleAccessor:s}=t.drawMatic??{},a=Kd({...t,eventType:t.drawMatic?.eventType??t.matchUpType,generateMatchUps:r??!0,scaleAccessor:s??t.scaleAccessor,scaleName:i??t.scaleName,participantIds:t.participantIds,roundsCount:t.roundsCount,restrictEntryStatus:e,structureId:n,matchUpIds:o});return a.error?a:(a?.matchUps?.length&&Od({tournamentRecord:t.tournamentRecord,drawDefinition:t.drawDefinition,suppressNotifications:!0,matchUps:a.matchUps,event:t.event,structureId:n}),{...C})}function v_({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:wt};let{positionAssignments:d}=ge({structure:m}),l=d?.length||0;if(u>l)return{error:GA};let f=m.structures?.length,g=It(a?.groupSeedingThreshold)&&a?.groupSeedingThreshold,I=Tg({roundRobinGroupsCount:f,drawSize:l})?.seedGroups,{seedsCount:h}=wu({policyDefinitions:i,requireParticipantCount:t,drawSizeProgression:r,participantsCount:n,drawSize:l});return h&&i?.[Fn]&&u>h&&e&&(u=h),m.seedLimit=u,m.seedAssignments=tt(1,u+1).map(S=>{let T=I?.find(P=>P.includes(S)),y=T&&Math.min(...T),E=g&&S>=g?y:S;return{participantId:void 0,seedNumber:S,seedValue:E}}),vt({drawDefinition:s,structureIds:[c]}),{...C,seedLimit:u}}function ea({sortDescending:t=!1,tournamentRecord:e,scaleAttributes:r,scaleSortMethod:n,stageSequence:o,entries:i,event:s,stage:a}){if(!e)return{error:$};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}=Rc({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 WT(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:wt},stack:e});let s=i?.structureId,{seedsCount:a,stageEntries:c,seedLimit:u}=BV({...t,structureId:s});(t.seededParticipants||t.event||t.seedingScaleName)&&LV({...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?wV({...t,multipleStructures:m,seedLimit:u,structureId:s}):{};return d?.error?_({result:d,stack:e}):{...d,stageEntries:c,structureId:s,seedsCount:a}}function xV({entries:t,stage:e,stageSequence:r,roundTarget:n}){return t.filter(o=>{let i=mt({name:Mn,element:o})?.extension?.value;return(!o.entryStage||o.entryStage===e)&&(!r||!o.entryStageSequence||o.entryStageSequence===r)&&(!n||!i||i===n)&&oi.includes(o.entryStatus)})}function wV(t){let e=typeof t.automated=="object"&&t.automated.seedsOnly,r=yc({...t,seedsOnly:e});if(r.error)return r;let n=r?.positionAssignments,o=r?.positioningReport;return{conflicts:r.conflicts,positionAssignments:n,positioningReport:o}}function LV(t){let{seededParticipants:e,seedingScaleName:r,entries:n,event:o}=t,i=n.map(St);e?FV({...t,enteredParticipantIds:i}):(o||r)&&kV({...t,enteredParticipantIds:i})}function FV(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?ys({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;Ks({provisionalPositioning:e,tournamentRecord:o,drawDefinition:s,seedingProfile:a,participantId:l,seedBlockInfo:m,structureId:c,seedNumber:f,seedValue:g,event:p})})}function kV(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=GV({...t,ageCategoryCode:l,categoryName:d,eventType:f})||c&&VV({...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:E}=h,P=o?.[T]||E||T;Ks({provisionalPositioning:r,tournamentRecord:s,drawDefinition:a,seedingProfile:u,participantId:y,structureId:p,seedNumber:T,seedValue:P,event:m})})}function GV(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:To,eventType:u};return ea({scaleAttributes:p,tournamentRecord:e,stageSequence:n,entries:o,stage:i}).scaledEntries}function VV(t){let{tournamentRecord:e,stageSequence:r,event:n,entries:o,stage:i}=t,{categoryName:s,ageCategoryCode:a}=n?.category||{},c=n?.eventType;return ea({scaleAttributes:{scaleName:s||a,scaleType:Ii,eventType:c},tournamentRecord:e,stageSequence:r,entries:o,stage:i}).scaledEntries}function BV(t){let{seedsCount:e}=t;t.seededParticipants&&(e=t.seededParticipants.length),e>t.drawSize&&(e=t.drawSize);let r=xV(t);e>r.length&&(e=r.length);let{seedLimit:n}=v_({enforcePolicyLimits:t.enforcePolicyLimits??!0,appliedPolicies:t.appliedPolicies,participantsCount:r.length,seedingProfile:t.seedingProfile,drawDefinition:t.drawDefinition,structureId:t.structureId,seedsCount:e});return n&&n<e&&(e=n),{seedsCount:e,stageEntries:r,seedLimit:n}}function O_(t){let e=Fd({...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=HV({suppressDuplicateEntries:n,ignoreStageSpace:o,drawDefinition:r,drawEntries:u,drawType:d,entries:l});if(I.error)return I;let h=d===Vi?0:dt(t.seedsCount??0),S=WT({...t,qualifyingOnly:!m||s,appliedPolicies:i,drawDefinition:r,seedingProfile:a,participants:c,stage:rt,seedsCount:h,placeByes:p,drawSize:m,entries:l});if(S.error&&!S.conflicts)return S;S.positioningReport?.length&&f.push({[rt]:S.positioningReport});let T=S.structureId;return S.conflicts&&(g=S.conflicts),d===$r&&t.roundsCount&&b_({...t,drawDefinition:r,structureId:T}),{drawDefinition:r,positioningReports:f,conflicts:g,structureId:T}}function HV(t){let{ignoreStageSpace:e,drawDefinition:r,drawEntries:n,drawType:o,entries:i}=t;for(let s of i){if(n&&s.entryStage&&s.entryStage!==rt)continue;let a={...s,ignoreStageSpace:e??o===$r,entryStage:s.entryStage??rt,event:t.event,drawDefinition:r,drawType:o},c=Id(a);if(n&&c.error)return c}return{error:void 0}}var WV=()=>({matchUpType:void 0,drawName:void 0,drawId:void 0,structures:[],entries:[],links:[]});var __=WV;function x_(t){let{drawId:e=Mt(),processCodes:r,matchUpType:n,drawType:o}=t??{},i=__();return Object.assign(i,{processCodes:r,matchUpType:n,drawType:o,drawId:e})}function zd(t){let e=t.structureIds,{tournamentRecord:r,drawDefinition:n,matchUpFormat:o,structureId:i,matchUpId:s,event:a}=t,c=et(t,[{[Ce]:!0,[Gm]:!0}]);if(c.error)return c;if(!Dr({matchUpFormat:o}))return{error:$a};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:lr};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:jn};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:jn};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),vt({drawDefinition:n,structureIds:e}),{...C}}function w_({tieFormat:t}){let e=ur({checkCollectionIds:!1,tieFormat:t});if(e.error)return e;for(let r of t.collectionDefinitions)r.collectionId||(r.collectionId=Mt());return{tieFormat:t}}function L_({existingQualifyingStructures:t,tournamentRecord:e,drawDefinition:r,matchUpFormat:n,matchUpType:o,tieFormat:i,event:s}){if((n||i)&&!(n&&s?.matchUpFormat===n||s?.tieFormat&&i&&JSON.stringify(s.tieFormat)===JSON.stringify(i))){if(i){let c=w_({tieFormat:i});if(c.error)return c;let u=t?.every(p=>p.tieFormat);(!t?.length||u)&&(r.tieFormat=c.tieFormat??i)}else if(n){let c=zd({tournamentRecord:e,drawDefinition:r,matchUpFormat:n,event:s});if(c.error)return{info:"matchUpFormat or tieFormat error",error:c.error}}o&&(r.matchUpType=o)}return{error:void 0}}var uN={};Jt(uN,{attachPolicies:()=>Ji,findPolicy:()=>ni,getAppliedPolicies:()=>Tt,getPolicyDefinitions:()=>_o,mutate:()=>aN,query:()=>cN,removePolicy:()=>sN});var aN={};Jt(aN,{attachPolicies:()=>Ji,removePolicy:()=>sN});function sN(t){let e=et(t,[{[cb]:!0,_anyOf:{[Re]:!1,[ne]:!1,[Ce]:!1,[so]:!1}}]);if(e.error)return e;let r,n=t.drawDefinition??t.event??((t.tournamentId||!t.tournamentRecords)&&t.tournamentRecord);if(n)return F_(t,n);if(t.tournamentRecords){let o=Object.keys(t.tournamentRecords);if(!o.length)return{error:$};for(let i of o){let s=t.tournamentRecords[i],a=F_(t,s);if(a.error)return a;r=!0}}else return{error:$};return r?{...C}:{error:Gc}}function F_(t,e){let r=Tt(t).appliedPolicies??{};return r[t.policyType]?(delete r[t.policyType],Object.keys(r).length?Ut({element:e,extension:{name:iu,value:r}}):gr({element:e,name:iu}),{...C}):{error:Gc}}var cN={};Jt(cN,{findPolicy:()=>ni,getAppliedPolicies:()=>Tt,getPolicyDefinitions:()=>_o});var pN={[Fn]:{validSeedPositions:{ignore:!0},duplicateSeedNumbers:!0,drawSizeProgression:!0,seedingProfile:{drawTypes:{[So]:{positioning:li},[Nn]:{positioning:li}},positioning:eb},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}]}},Kg=pN;function k_({appliedPolicies:t,policyDefinitions:e,drawDefinition:r,stack:n}){if(e&&typeof e!="object")return _({info:"policyDefinitions must be an object",result:{error:V},stack:n});let o={[ou]:t?.[ou]};return e?jV({policyDefinitions:e,appliedPolicies:t,policiesToAttach:o,drawDefinition:r}):o.avoidance&&Ji({drawDefinition:r,policyDefinitions:o}),!t?.[Fn]&&!e?.[Fn]&&(Ji({policyDefinitions:Kg,drawDefinition:r}),t&&Object.assign(t,Kg)),{error:void 0}}function jV({policyDefinitions:t,appliedPolicies:e,policiesToAttach:r,drawDefinition:n}){for(let o of Object.keys(t))JSON.stringify(e?.[o])!==JSON.stringify(t[o])&&(r[o]=t[o]);Object.keys(r).length&&(Ji({policyDefinitions:r,drawDefinition:n}),e&&Object.assign(e,r))}function G_(t){let{tournamentRecord:e,policyDefinitions:r,appliedPolicies:n,matchUpFormat: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,m=p?.structures?.find(h=>h.stage===rt&&h.stageSequence===1)?.structureId,d=p?p.structures?.filter(h=>h.stage===ct):[],l=d?.length===1&&!d[0].matchUps?.length&&d[0].structureId;p&&a!==p.drawType&&(p.drawType=a);let f=p??x_({processCodes:t.processCodes,drawId:t.drawId,drawType:a}),g=L_({existingQualifyingStructures:d,tournamentRecord:e,drawDefinition:f,matchUpFormat:o,matchUpType:i,tieFormat:s,event:u});if(g.error)return _({result:g,stack:c});let I=k_({appliedPolicies:n,policyDefinitions:r,drawDefinition:f,stack:c});return I.error?I:{drawDefinition:f,structureId:m,existingDrawDefinition:p,existingQualifyingPlaceholderStructureId:l}}function V_(t){let e="generateOrGetExisting",r=[],n=[],o=G_(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&&M_({...t,...o})||O_({...t,...o,entries:c});return u.error?_({result:u,stack:e}):(u.positioningReports?.length&&r.push(...u.positioningReports??[]),u.conflicts?.length&&n.push(...u.conflicts??[]),s=u.drawDefinition,a=u.structureId,{existingDrawDefinition:i,positioningReports:r,drawDefinition:s,structureId:a,conflicts:n,entries:c})}function B_(t){let{qualifyingPlaceholder:e,existingDrawDefinition:r,positioningReports:n,qualifyingProfiles:o,appliedPolicies:i,qualifyingOnly:s,drawDefinition:a,seedingProfile:c,participants:u,structureId:p,tieFormat:m,entries:d,stack:l}=t,f=e&&!o?.length&&!r,g=[];if(o){let I=(y,E)=>y.stageSequence-E.stageSequence,h=(y,E)=>y.roundTarget-E.roundTarget,S=[],T=1;o.sort(h);for(let y of o){if(!Array.isArray(y.structureProfiles))return _({info:ai("structureProfiles"),result:{error:st},stack:l});T=y.roundTarget||T;let E=y.structureProfiles?.sort(I)||[],P=1;for(let A of E){let{qualifyingRoundNumber:U,qualifyingPositions:N,seededParticipants:D,seedingScaleName:M,seedsCount:R=0,seedByRanking:b,placeByes:v,drawSize:O}=A,x=WT({...t,seedingProfile:A.seedingProfile??c,stageSequence:P,qualifyingRoundNumber:U,preparedStructureIds:S,qualifyingPositions:N,seededParticipants:D,stage:ct,seedingScaleName:M,appliedPolicies:i,drawDefinition:a,qualifyingOnly:s,seedByRanking:b,participants:u,roundTarget:T,seedsCount:R,placeByes:v,drawSize:O,entries:d});if(x.error)return x;x.structureId&&S.push(x.structureId),P+=1,x.conflicts?.length&&g.push(...x.conflicts),x.positioningReport?.length&&n.push({[ct]:x.positioningReport})}T+=1}}else if(p&&f){let I=hn({structureName:Qe(ct),stage:ct,qualifyingOnly:s,tieFormat:m}),{link:h}=Ca({sourceStructureId:I.structureId,targetStructureId:p,sourceRoundNumber:0,linkType:xn});a.structures||(a.structures=[]),a.structures.push(I),a.links||(a.links=[]),a.links.push(h)}return{qualifyingConflicts:g,error:void 0}}var vN={};Jt(vN,{addGoesTo:()=>Ki,allCompetitionMatchUps:()=>Un,allDrawMatchUps:()=>ir,allEventMatchUps:()=>Xn,allPlayoffPositionsFilled:()=>FS,allTournamentMatchUps:()=>ye,analyzeDraws:()=>_u,analyzeMatchUp:()=>tm,analyzeTournament:()=>ty,bulkUpdatePublishedEventIds:()=>ry,calculateWinCriteria:()=>Ds,categoryCanContain:()=>$c,checkMatchUpIsComplete:()=>ls,checkValidEntries:()=>wd,compareTieFormats:()=>Qo,competitionScheduleMatchUps:()=>Bu,courtGridRows:()=>sl,credits:()=>H_,drawMatchUps:()=>Ty,eventMatchUps:()=>pl,filterMatchUps:()=>Mi,filterParticipants:()=>Uu,findDrawDefinition:()=>uT,findExtension:()=>mt,findVenue:()=>qo,getAggregateTeamResults:()=>ZT,getAllDrawMatchUps:()=>ce,getAllEventData:()=>ny,getAllStructureMatchUps:()=>yt,getAllowedDrawTypes:()=>Qd,getAllowedMatchUpFormats:()=>zT,getAppliedPolicies:()=>Tt,getAssignedParticipantIds:()=>Ci,getAvailableMatchUpsCount:()=>_d,getAvailablePlayoffProfiles:()=>Cu,getCategoryAgeDetails:()=>Fs,getCheckedInParticipantIds:()=>ps,getCompetitionDateRange:()=>Jd,getCompetitionMatchUps:()=>Zp,getCompetitionParticipants:()=>jT,getCompetitionPenalties:()=>QT,getCompetitionVenues:()=>Qp,getCourtInfo:()=>md,getCourts:()=>yy,getDrawData:()=>rl,getDrawDefinitionTimeItem:()=>tS,getDrawParticipantRepresentativeIds:()=>aT,getDrawStructures:()=>gn,getDrawTypeCoercion:()=>xu,getEligibleVoluntaryConsolationParticipants:()=>sT,getEntriesAndSeedsCount:()=>al,getEvent:()=>Uy,getEventData:()=>nl,getEventMatchUpFormatTiming:()=>py,getEventProperties:()=>Ay,getEventPublishStatus:()=>Xr,getEventStructures:()=>Ag,getEventTimeItem:()=>gu,getEvents:()=>Ey,getFlightProfile:()=>Ht,getHomeParticipantId:()=>fy,getLinkedTournamentIds:()=>au,getMatchUpCompetitiveProfile:()=>Su,getMatchUpContextIds:()=>gy,getMatchUpDailyLimits:()=>dl,getMatchUpDailyLimitsUpdate:()=>my,getMatchUpDependencies:()=>on,getMatchUpFormat:()=>Iy,getMatchUpFormatTiming:()=>Tu,getMatchUpFormatTimingUpdate:()=>cy,getMatchUpScheduleDetails:()=>dd,getMatchUpType:()=>ld,getMatchUpsMap:()=>Me,getMatchUpsStats:()=>hy,getMatchUpsToSchedule:()=>ol,getMaxEntryPosition:()=>sy,getModifiedMatchUpFormatTiming:()=>cl,getPairedParticipant:()=>In,getParticipantEventDetails:()=>YT,getParticipantIdFinishingPositions:()=>cT,getParticipantMembership:()=>qT,getParticipantResults:()=>vu,getParticipantScaleItem:()=>Rc,getParticipantSchedules:()=>$T,getParticipantSignInStatus:()=>KT,getParticipantTimeItem:()=>eS,getParticipants:()=>Gt,getPersonRequests:()=>Oi,getPolicyDefinitions:()=>_o,getPositionAssignments:()=>Hp,getPositionsPlayedOff:()=>Ec,getPredictiveAccuracy:()=>ly,getProfileRounds:()=>il,getPublishState:()=>Is,getRandomQualifierList:()=>ET,getRoundMatchUps:()=>Ke,getRounds:()=>Sy,getScaleValues:()=>ga,getScaledEntries:()=>ea,getScheduledRoundsDetails:()=>Vu,getSchedulingProfile:()=>Xo,getSchedulingProfileIssues:()=>iy,getSeedingThresholds:()=>MS,getSeedsCount:()=>wu,getStructureSeedAssignments:()=>nn,getTeamLineUp:()=>ds,getTieFormat:()=>el,getTimeItem:()=>en,getTournamentIds:()=>Tp,getTournamentInfo:()=>Ps,getTournamentPenalties:()=>Xd,getTournamentPersons:()=>JT,getTournamentPoints:()=>Zd,getTournamentPublishStatus:()=>Au,getTournamentStructures:()=>LS,getTournamentTimeItem:()=>td,getValidGroupSizes:()=>Op,getVenueData:()=>fc,getVenuesAndCourts:()=>Uo,isAdHoc:()=>pr,isCompletedStructure:()=>Eo,isValidForQualifying:()=>UT,isValidMatchUpFormat:()=>Dr,matchUpActions:()=>xd,participantScaleItem:()=>Ao,participantScheduledMatchUps:()=>dy,positionActions:()=>AT,publicFindCourt:()=>SS,publicFindVenue:()=>hS,tallyParticipantResults:()=>ba,tieFormatGenderValidityCheck:()=>bm,tournamentMatchUps:()=>ml,validMatchUp:()=>og,validMatchUps:()=>Vr,validateCollectionDefinition:()=>Kc,validateLineUp:()=>Ad});function H_(){return`
5
5
  This project would not have been possible without the generous input and patience
6
6
  of tournament organizers and directors who worked with early versions of CourtHive/TMX.
7
7
 
8
- Thanks to Pavel, Ivan, Mladen, Zdenko, Antonia, Jakov, Kreso, Barry, Jeff, Bobby... to name just a few.
8
+ Thanks to Miro, Pavel, Ivan, Mladen, Zdenko, Antonia, Jakov, Kreso, Barry, Jeff, Bobby... to name just a few.
9
9
 
10
10
  The project would not have even begun without the support of Miro, or the introduction by Sretchko.
11
11
  The project would not have succeeded without the enthusiasm of Randy and Bruce.
@@ -23,5 +23,5 @@ var pL=Object.defineProperty;var Jt=(t,e)=>{for(var r in e)pL(t,r,{get:e[r],enum
23
23
  `}var mN={};Jt(mN,{filterParticipants:()=>Uu,getCompetitionParticipants:()=>jT,getPairedParticipant:()=>In,getParticipantEventDetails:()=>YT,getParticipantMembership:()=>qT,getParticipantScaleItem:()=>Rc,getParticipantSchedules:()=>$T,getParticipantSignInStatus:()=>KT,getParticipantTimeItem:()=>eS,getParticipants:()=>Gt,getScaleValues:()=>ga,participantScaleItem:()=>Ao,validateLineUp:()=>Ad});function jT(t){let{tournamentRecords:e}=t||{};if(typeof e!="object"||!Object.keys(e).length)return{error:Lt};let r=[],n={},o={},i={},s=[],a={},c=[];for(let u of Object.values(e)){let{participantIdsWithConflicts:p,mappedMatchUps:m,participantMap:d,participants:l,matchUps:f,derivedEventInfo:g,derivedDrawInfo:I}=Gt({...t,tournamentRecord:u});Object.assign(a,m),Object.assign(n,d),Object.assign(o,g),Object.assign(i,I),r.push(...l??[]),s.push(...f??[]),p?.forEach(h=>{c.includes(h)||c.push(h)})}return{participantIdsWithConflicts:c,derivedEventInfo:o,derivedDrawInfo:i,participantMap:n,mappedMatchUps:a,participants:r,...C,matchUps:s}}function YT({tournamentRecord:t,participantId:e}){if(!t)return{error:$};if(!e)return{error:ie};let r=[e].concat((t.participants??[]).filter(o=>o?.participantType&&[Ft,ft].includes(o.participantType)&&o.individualParticipantIds?.includes(e)).map(o=>o.participantId));return{eventDetails:(t.events??[]).filter(o=>{let i=(o?.entries??[]).map(s=>s.participantId);return ke(i,r)}).map(o=>({eventName:o.eventName,eventId:o.eventId}))}}function qT({tournamentRecord:t,participantId:e}){if(!t)return{error:$};if(!e)return{error:ie};let{participants:r}=Gt({participantFilters:{participantTypes:[Ft,ft,zr]},tournamentRecord:t});return(r??[]).filter(o=>o.individualParticipantIds?.includes(e)).reduce((o,i)=>{let s=i.participantType;return s&&(o[s]||(o[s]=[]),o[s].push(i)),o},{})}function $T({participantFilters:t={},tournamentRecord:e}){if(!e)return{error:$};if(typeof t!="object")return{error:Io,context:{participantFilters:t}};let r={eventIds:t.eventIds},n=ye({tournamentRecord:e,contextFilters:r}).matchUps??[],o=Object.assign({},...n.map(p=>({[p.matchUpId]:p}))),i=n.filter(({schedule:p})=>p&&Object.keys(p).length),s=on({tournamentRecord:e,matchUps:n}).sourceMatchUpIds??[],a={};for(let p of i){let{sides:m}=p,d,l=m?.map(g=>{if(g.participant)return[g.participant].concat(...g.participant.individualParticipants||[]);s[p.matchUpId]&&!d&&(d=(s[p.matchUpId]||[]).map(I=>o[I]).filter(({winningSide:I,bye:h})=>!I&&!h))}).filter(Boolean).flat()??[];for(let g of l){let{participantId:I}=g;a[I]||(a[I]={potentialMatchUps:[],participant:g,matchUps:[]}),a[I].matchUps.push(p)}let f=d?.map(({sides:g})=>g).flat().map(({participant:g})=>g&&[g].concat(...g.individualParticipants||[])).filter(Boolean).flat()||[];for(let g of f){let{participantId:I}=g;a[I]||(a[I]={potentialMatchUps:[],participant:g,matchUps:[]}),a[I].potentialMatchUps.push(p)}}return{participantSchedules:Object.values(a).filter(({participant:p})=>!(t.participantIds&&!t.participantIds.includes(p.participantId)||t.participantTypes&&!t.participantTypes.includes(p.participantType))),...C}}function KT({tournamentRecord:t,participantId:e}){if(!t)return{error:$};if(!e)return{error:ie};let{participant:r}=yo({tournamentRecord:t,participantId:e});if(!r)return{error:re};let{timeItem:n}=en({itemType:cc,element:r});return n&&n.itemValue===du&&du}var lN={};Jt(lN,{analyzeDraws:()=>_u,analyzeTournament:()=>ty,getAggregateTeamResults:()=>ZT,getAllowedDrawTypes:()=>Qd,getAllowedMatchUpFormats:()=>zT,getAppliedPolicies:()=>Tt,getCompetitionDateRange:()=>Jd,getCompetitionPenalties:()=>QT,getPolicyDefinitions:()=>_o,getTournamentInfo:()=>Ps,getTournamentPenalties:()=>Xd,getTournamentPersons:()=>JT,getTournamentPoints:()=>Zd,getTournamentStructures:()=>LS,getTournamentTimeItem:()=>td});function zT({tournamentRecord:t,categoryName:e,categoryType:r}){if(!t)return{error:$};let{appliedPolicies:n}=Tt({tournamentRecord:t});return(n?.[tn]?.matchUpFormats||[]).filter(({categoryNames:s,categoryTypes:a})=>!e&&!a||e&&s?.includes(e)||r&&a?.includes(r))}function Qd({tournamentRecord:t,categoryName:e,categoryType:r}){if(!t)return{error:$};let{appliedPolicies:n}=Tt({tournamentRecord:t});return(n?.[Wm]?.allowedDrawTypes||[]).filter(({categoryNames:s,categoryTypes:a})=>!e&&!a||e&&s?.includes(e)||r&&a?.includes(r))}function Xd({tournamentRecord:t}){if(!t)return{error:$};let r=(t?.participants??[]).reduce((n,o)=>{let{participantId:i}=o;return(o.penalties??[]).forEach(s=>{let{penaltyId:a}=s||{};n[a]?n[a].participants.push(i):n[a]={...s,participantIds:[i]}}),n},{});return{penalties:Object.values(r)}}function QT({tournamentRecords:t}){if(typeof t!="object"||!Object.keys(t).length)return{error:Lt};let e=[];for(let r of Object.values(t)){let{penalties:n}=Xd({tournamentRecord:r});e.push(...n??[])}return{penalties:e}}function XT({event:t}){return{eventInfo:(({eventId:r,eventName:n,eventType:o,eventLevel:i,surfaceCategory:s,matchUpFormat:a,category:c,gender:u,startDate:p,endDate:m,ballType:d,discipline:l,onlineResources:f,notes:g})=>({eventId:r,eventName:n,eventType:o,eventLevel:i,surfaceCategory:s,matchUpFormat:a,category:c,gender:u,startDate:p,endDate:m,ballType:d,discipline:l,onlineResources:f,notes:g}))(t)}}var YV={[Bs]:{policyName:"Staff Privacy Policy",participant:{contacts:!1,individualParticipants:!1,individualParticipantIds:!1,onlineResources:!1,participantName:!0,participantOtherName:!0,participantId:!0,participantRole:!0,participantRoleResponsibilities:!0,participantStatus:!0,penalties:!1,representing:!0,participantType:!0,person:{addresses:!1,biographicalInformation:!1,birthDate:!1,contacts:!1,nationalityCode:!0,nativeFamilyName:!1,nativeGivenName:!1,onlineResources:!1,otherNames:!0,parentOrganisationId:!1,passportFamilyName:!1,passportGivenName:!1,personId:!1,personOtherIds:!1,previousNames:!1,sex:!1,standardFamilyName:!0,standardGivenName:!0,status:!1,tennisId:!1,wheelchair:!0}}}},W_=YV;function Ps(t){let{tournamentRecord:e}=t??{};if(!e)return{error:$};let r=(({tournamentId:c,tournamentRank:u,tournamentStatus:p,formalName:m,tournamentName:d,promotionalName:l,onlineResources:f,localTimeZone:g,activeDates:I,startDate:h,endDate:S,hostCountryCode:T,venues:y,notes:E,updatedAt:P})=>({tournamentId:c,tournamentRank:u,tournamentStatus:p,formalName:m,tournamentName:d,promotionalName:l,onlineResources:f,localTimeZone:g,activeDates:I,startDate:h,endDate:S,hostCountryCode:T,venues:y,notes:E,updatedAt:P}))(e),o=Gt({participantFilters:{participantRoles:[uP,dg,pP,mP,lP]},policyDefinitions:W_,tournamentRecord:e})?.participants??[];o&&(r.tournamentContacts=o);let i=Is({tournamentRecord:e})?.publishState,s=i?.tournament?.status?.publishedEventIds||[],a=[];for(let c of e.events??[])if(!t?.usePublishState||s.includes(c.eventId)){let u=XT({event:c}).eventInfo;u&&a.push(u)}return r.timeItemValues=oT({element:e}),r.publishState=i?.tournament,r.eventInfo=a,{tournamentInfo:J(nt(r),!1,!0),...C}}function Jd({tournamentRecords:t}){if(!ht(t))return{error:Lt};let r=Object.keys(t??{}).reduce((i,s)=>{let a=t[s],{tournamentInfo:{startDate:c,endDate:u}}=Ps({tournamentRecord:a}),p=c&&new Date(Pt(c));(!i.startDate||p&&p<i.startDate)&&(i.startDate=p);let m=u&&new Date(Pt(u));return(!i.endDate||m&&m>i.endDate)&&(i.endDate=m),i},{startDate:void 0,endDate:void 0}),n=r.startDate&&Pt(r.startDate.toISOString()),o=r.endDate&&Pt(r.endDate.toISOString());return!n||!o?{error:oE}:{startDate:n,endDate:o}}function JT({tournamentRecord:t,participantFilters:e}){if(!t)return{error:$};let r=t.participants||[];e&&(r=Uu({participants:r,participantFilters:e,tournamentRecord:t}));let n={},o=i=>{if(i.person){let{personId:s}=i.person;n[s]?n[s].participantIds.push(i.participantId):n[s]={...i.person,participantIds:[i.participantId]}}};return r.forEach(i=>{i.person&&o(i)}),{tournamentPersons:Object.values(n)}}function ZT(t){let e=et(t,[{[ne]:!0}]);if(e.error)return e;let r=t.finishingPositionRangeBounsPoints||{},n={},o=m=>{let d=m?.individualParticipants?.map(l=>l.teams?.length===1&&l.teams[0]);return m?.teams?.length===1&&m?.teams?.[0]||d?.[0].participantId===d?.[1].participantId&&d?.[0]},{matchUps:i,participants:s}=Gt({participantFilters:{participantTypes:[At]},withRankingProfile:!0,withStatistics:!0,...t});for(let m of s??[]){if(m.participantType===Er)continue;m.draws?.[0]?.drawId==="draw-0-3"&&console.log(m.participantType,m.draws[0].finishingPositionRange);let d=o(m);if(d)for(let l of m?.draws??[]){let f=l?.finishingPositionRange?.join("-");if(f&&r?.[f]){let g=d?.participantId,I=l?.drawId,h=`${g}|${I}|${f}`;n[h]=r[f]}}}let a=m=>({teamName:m,standingPoints:0,pointsPlayed:0,pointsPct:0,points:0,bonus:0,diff:0,loss:0,win:0}),c=(m,d,l)=>{m[d]===void 0&&(m[d]=0),m[d]+=l},u={},p={};for(let m of i??[]){let{sides:d,matchUpFormat:l}=m,f=l&&Ye(l);if(d?.length===2&&f.setFormat?.timed&&(!f.finalSetFormat||f.finalSetFormat?.timed))for(let g of d){let I=o(g.participant),h=I?.participantId,S=g.participant?.participantId,T=I?.participantName,y=g.sideNumber,E=g.participant?.individualParticipantIds||S&&[S]||[];if(E.forEach(P=>{P&&!u[P]&&(u[P]=a(T))}),h&&y){p[h]||(p[h]=a(T));let P=[...E.map(U=>u[U]),p[h]];m.winningSide&&(y===m.winningSide?P.forEach(U=>c(U,"win",1)):P.forEach(U=>c(U,"loss",1)));let A=m.score?.sets||[];for(let U of A){let N=U?.[`side${3-y}Score`]||0,D=U?.[`side${y}Score`]||0,M=D-N;P.forEach(R=>c(R,"pointsPlayed",D+N)),P.forEach(R=>c(R,"points",D)),P.forEach(R=>c(R,"diff",M))}}}}for(let m of Object.keys(n)){let[d]=m.split("|");p[d]&&(p[d].bonus+=n[m],p[d].pointsPct=parseFloat((p[d].points/p[d].pointsPlayed).toFixed(2)),p[d].standingPoints=p[d].win+p[d].bonus)}for(let m of Object.keys(u))u[m].pointsPct=parseFloat((u[m].points/u[m].pointsPlayed).toFixed(2));return{...C,individualResults:u,teamResults:p}}function j_(t){let r=t.participants?.filter(({participantType:a})=>a===Ft)?.length===2,n=t.events?.length===1&&t.events[0],o=n?.drawDefinitions?.length===1&&n.drawDefinitions[0],s=(o?.structures?.length===1&&o.structures[0])?.positionAssignments?.length===2;return!!(n.tieFormat&&r&&s)}function ty({tournamentRecord:t}){if(!t)return{error:$};let{drawsAnalysis:e}=_u({tournamentRecord:t}),r={isDual:j_(t),drawsAnalysis:e},n=Gt({tournamentRecord:t});return n.missingParticipantIds?.length&&(r.missingParticipantIds=n.missingParticipantIds),{...C,analysis:r}}function ey(t,e){return t&&e&&Array.isArray(e)&&e[t-1]||typeof e=="object"&&e[t]}function Y_(t){let{participation:e={},awardProfiles:r,startDate:n,eventType:o,drawSize:i,drawType:s,category:a,endDate:c,level:u}=t,{participationOrder:p,flightNumber:m,rankingStage:d}=e,l=g=>!n&&!c||!g.dateRanges?!0:g.dateRanges.some(I=>{let h=!n||!I.startDate||new Date(n)>new Date(I.startDate),S=!c||!I.endDate||new Date(c)<=new Date(I.endDate);return h&&S});return{awardProfile:r.find(g=>l(g)&&(!g.maxFlightNumber||m<=g.maxFlightNumber)&&(!g.drawTypes?.length||g.drawTypes?.includes(s))&&(!g.drawSizes?.length||g.drawSizes.includes(i))&&(!g.stages?.length||g.stages.includes(d))&&(!g.levels?.length||g.levels.includes(u))&&(!g.maxDrawSize||i<=g.maxDrawSize)&&(!g.drawSize||g.drawSize===i)&&(!g.maxLevel||u<=g.maxLevel)&&(!m||!g.flights?.flightNumbers?.length||g.flights.flightNumbers.includes(m))&&(!g.participationOrder||g.participationOrder===p)&&(!g.category?.ageCategoryCodes||g.category.ageCategoryCodes.includes(a?.ageCategoryCode))&&(!g.eventTypes?.length||g.eventTypes?.includes(o)))}}function dN({participantWon:t,flightNumber:e,valueObj:r,drawSize:n,flights:o,level:i}){let s=(f,g)=>{if(f){if(Array.isArray(g)){let I=g.find(h=>h.flight===f||h.f===f);return I.value||I.v}if(typeof g=="object"){let I=g.flights||g.f;if(Array.isArray(I))return I[f-1]}}},a=(f,g)=>{let I=f?.value||f?.v||(It(f)?f:0),h=ey(i,f?.level);return{value:s(g,h)||It(h)&&h||I}},c=0,u,p,m,d,l=t&&"won"||t===!1&&"lost"||void 0;if(Array.isArray(r)){let f=r.find(h=>h.drawSize===n||h.drawSizes?.includes(n)),g=r.find(h=>h.drawSize&&h.threshold&&n>h.drawSize),I=r.find(h=>!h.drawSize&&!h.drawSizes?.length);l!==void 0&&(f=f?.[l],g=g?.[l],I=I?.[l]),p=a(f,e).value,m=a(g,e).value,d=a(I,e).value,c=p||m||d,u=p&&f.requireWin||m&&g.requireWin||I?.requireWin}else if(typeof r=="object"){let f=r?.drawSizes?.[n],g=r;l!==void 0&&(f=f?.[l],g=g?.[l]),p=a(f,e).value,d=a(g,e).value,c=p||d,u=p?f.requireWin:g?.requireWin}else It(r)&&l===void 0&&(c=r);return e&&o?.pct?.[e]&&(c=Math.round(c*o.pct[e])),{awardPoints:c,requireWin:u}}function Zd({participantFilters:t,policyDefinitions:e,tournamentRecord:r,level:n}){if(!r)return{error:$};let{policyDefinitions:o}=_o({policyTypes:[_f],tournamentRecord:r}),i=e?.[_f]??o?.[_f];if(!i)return{error:Xu};let s=i.awardProfiles,a=i.requireWinFirstRound,c=i.requireWinForPoints,{participants:u,derivedEventInfo:p,derivedDrawInfo:m,mappedMatchUps:d}=Gt({withRankingProfile:!0,participantFilters:t,tournamentRecord:r}),l=u?.filter(h=>h.draws?.length),f={},g={},I={};for(let h of l??[]){let{participantType:S,participantId:T,person:y,draws:E}=h;for(let P of E){let{drawId:A,structureParticipation:U,eventId:N}=P,D=p[N],M=m[A],R=M?.drawType,{category:b,eventType:v}=D||{},O=P.startDate||D.startDate||r.startDate,x=P.endDate||D.endDate||r.endDate;if(v===br&&T!==Er)continue;let F;if(s){let w=c,L=0,G=0,k=0,H;for(let W of U){let{finishingPositionRange:q,participationOrder:Y,participantWon:B,flightNumber:K,rankingStage:X,winCount:j}=W;L+=j||0;let ot=M?.drawSize,{awardProfile:z}=Y_({awardProfiles:s,participation:W,eventType:v,startDate:O,category:b,drawSize:ot,drawType:R,endDate:x,level:n});if(z){if(!ot)continue;let Q=Array.isArray(q)&&Math.max(...q),ut=pt(q||[]).join("-"),it=Q&&X!==ct&&q?.includes(ot);z.requireWinForPoints!==void 0&&(w=z.requireWinForPoints),z.requireWinFirstRound!==void 0&&(a=z.requireWinFirstRound);let{finishingPositionPoints:Et={},finishingPositionRanges:_t,finishingRound:Ae,pointsPerWin:$t,flights:Se}=z,Or=Array.isArray(z.perWinPoints)?z.perWinPoints?.find(Dt=>Dt.participationOrders?.includes(Y)):z.perWinPoints,pn=Et.participationOrders,Ir=0,Xe;if((!pn||pn.includes(Y))&&_t&&Q){let Dt=_t[Q];Dt&&({awardPoints:Ir,requireWin:Xe}=dN({flightNumber:K,valueObj:Dt,drawSize:ot,flights:Se,level:n}))}if(!Ir&&Ae&&Y===1&&Q){let Dt=Ae[Q];Dt&&({awardPoints:Ir,requireWin:Xe}=dN({participantWon:B,flightNumber:K,valueObj:Dt,drawSize:ot,flights:Se,level:n}))}if(it&&a!==void 0&&(w=a),Xe!==void 0&&(w=Xe),Ir>G&&(!w||j)&&(G=Ir,H=Q),!Ir&&$t&&j&&(k+=j*$t,H=ut),!Ir&&j&&Or){let Dt=ey(n,Or?.level);Dt?k+=j*Dt:Or.value&&(k+=j*Or.value)}}if(F=G+k,S===Er){let Q=(h.matchUps||[]).filter(({structureId:ut})=>ut===W.structureId);for(let{matchUpId:ut}of Q){let it=d[ut],Et=it.sides.find(_t=>_t.participantId===T).sideNumber;if(it.winningSice===Et)for(let _t of it.tieMatchUps)_t.winningSide}}}if(k||G){let W={winCount:L,positionPoints:G,rangeAccessor:H,perWinPoints:k,eventType:v,drawId:A,points:F},q=y?.personId;q?(f[q]||(f[q]=[]),f[q].push(W)):S===ft?(I[T]||(I[T]=[]),I[T].push(W)):S===Er&&(g[T]||(g[T]=[]),g[T].push(W))}}}}return{participantsWithOutcomes:l,personPoints:f,pairPoints:I,teamPoints:g,...C}}var gN={};Jt(gN,{compareTieFormats:()=>Qo,getTieFormat:()=>el,tieFormatGenderValidityCheck:()=>bm,validateCollectionDefinition:()=>Kc});function tl(t){if(!t)return{};let e=[],r=t.tieFormatName,n=t.collectionDefinitions?.map(o=>{let{matchUpType:i,matchUpFormat:s,matchUpCount:a,category:c,gender:u}=o;e.includes(s)||e.push(s);let p=c?.ageCategoryCode;return[a,i===_i?"D":"S",p,s,u].join(";")}).join("|");return{tieFormatName:t&&r||"UNNAMED",matchUpFormats:e,tieFormatDesc:n}}function Qo({considerations:t={},descendant:e,ancestor:r}){let n={},o={},{matchUpFormats:i,tieFormatDesc:s}=tl(e),{matchUpFormats:a,tieFormatDesc:c}=tl(r),u=pt((i??[]).filter(E=>!(a??[]).includes(E)).concat((a??[]).filter(E=>!(i??[]).includes(E)))),p=!!(t?.collectionName&&e.collectionDefinitions.map(({collectionName:E})=>E).join("|")!==r.collectionDefinitions.map(({collectionName:E})=>E).join("|")),m=!!(t?.collectionOrder&&e.collectionDefinitions.map(({collectionOrder:E})=>E).join("|")!==r.collectionDefinitions.map(({collectionOrder:E})=>E).join("|")),d=Object.assign({},...(e?.collectionDefinitions||[]).map(E=>({[E.collectionId]:E}))),l=Object.assign({},...(r?.collectionDefinitions||[]).map(E=>({[E.collectionId]:E})));n.collectionIds=CA(Object.keys(d),Object.keys(l)),o.collectionIds=CA(Object.keys(l),Object.keys(d)),n.collectionsValue=q_(d),o.collectionsValue=q_(l),n.groupsCount=r?.collectionGroups?.length??(0-(e?.collectionGroups?.length??0)||0),o.groupsCount=n.groupsCount?-1*n.groupsCount:0;let f=n.collectionsValue.totalValue-o.collectionsValue.totalValue,g=n.collectionsValue.totalMatchUps-o.collectionsValue.totalMatchUps,I=o.collectionsValue.assignmentValues.length!==n.collectionsValue.assignmentValues.length,h=o.collectionsValue.assignmentValues.some((E,P)=>{let A=n.collectionsValue.assignmentValues[P];return!A||E.valueKey!==A.valueKey||E.value!==A.value?!0:Array.isArray(E.value)?E.value.every((U,N)=>A.value[N]===U):!1}),S=p||m||c!==s||I||h||f!==0,T=[...o.collectionsValue.invalidValues,...n.collectionsValue.invalidValues],y=T.length&&T;return{matchUpFormatDifferences:u,matchUpCountDifference:g,descendantDifferences:n,ancestorDifferences:o,orderDifference:m,valueDifference:f,nameDifference:p,descendantDesc:s,ancestorDesc:c,...C,different:S,invalid:y}}function q_(t){let e=[],r=[],n=0;return{totalValue:Object.keys(t).sort(Eu).reduce((s,a)=>{let c=t[a],{collectionValueProfiles:u,collectionValue:p,matchUpCount:m,matchUpValue:d,scoreValue:l,setValue:f}=c,g={collectionValueProfiles:u,collectionValue:p,matchUpValue:d,scoreValue:l,setValue:f},I=Object.keys(g).filter(S=>![void 0,null].includes(g[S])&&(!Array.isArray(g[S])||g[S].length>0));I.length!==1&&e.push({collectionId:a});let h=I[0];if(h){let S=h==="collectionValueProfiles"?Object.values(u):g[h];r.push({valueKey:h,value:S})}return n+=m,u?.length?s+u.reduce((S,T)=>S+T.value,0):m?It(d)?s+d*m:It(l)?s+l*m:It(f)?s+f*m:s+p:s},0),totalMatchUps:n,invalidValues:e,assignmentValues:r}}function zg(t){Object.assign(t,{inContext:!0});let{matchUp:e,error:r}=fN(t);return{matchUp:J(e,!0,!0),error:r}}function fN({participantsProfile:t,afterRecoveryTimes:e,tournamentRecord:r,contextContent:n,contextProfile:o,drawDefinition:i,nextMatchUps:s,matchUpId:a,inContext:c,eventId:u,drawId:p,event:m}){if(!r)return{error:$};if(typeof a!="string")return{error:cr};if(!i||!m){let g=(ye({tournamentRecord:r,nextMatchUps:s}).matchUps??[]).find(I=>I.matchUpId===a);if(!g)return{error:Le};({eventId:u,drawId:p}=g),{event:m,drawDefinition:i}=ze({tournamentRecord:r,eventId:u,drawId:p})}if(!i)return{error:Cr};o&&!n&&(n=Qn({tournamentRecord:r,contextProfile:o}));let d={surfaceCategory:m?.surfaceCategory??r.surfaceCategory,indoorOutDoor:m?.indoorOutdoor??r.indoorOutdoor,endDate:m?.endDate??r.endDate,tournamentId:r.tournamentId,eventId:u??m?.eventId,drawId:p},{participants:l=[]}=Wo({participantsProfile:t,tournamentRecord:r,contextProfile:o,inContext:c});if(s){let g=(ir({context:c?d:void 0,participants:l,afterRecoveryTimes:e,contextContent:n,contextProfile:o,drawDefinition:i,nextMatchUps:s,inContext:c,event:m}).matchUps??[]).find(h=>h.matchUpId===a);if(!g)return{error:Le};let I=i?.structures?.find(h=>h.structureId===g.structureId);return{drawDefinition:i,structure:I,matchUp:g}}else{let{matchUp:f,structure:g}=Bt({context:c?d:void 0,tournamentParticipants:l,afterRecoveryTimes:e,contextContent:n,drawDefinition:i,contextProfile:o,matchUpId:a,inContext:c,event:m});return{matchUp:f,structure:g,drawDefinition:i}}}function el({tournamentRecord:t,drawDefinition:e,structureId:r,matchUpId:n,structure:o,eventId:i,drawId:s,event:a}){if(!t)return{error:$};if(!s&&!a&&!r&&!n)return _({result:{error:st},stack:"getTieFormat"});i&&!a&&(a=t.events?.find(l=>l.eventId===i));let c=zg({tournamentRecord:t,drawDefinition:e,matchUpId:n,drawId:s,event:a});if(n&&c?.error)return c;if(!e&&c?.drawDefinition&&(e=c?.drawDefinition),o=o??c?.structure,!o&&r&&!n){if(!e)return{error:sn};let l=at({drawDefinition:e,structureId:r});if(l.error)return l;o=l.structure}let u=(o?.tieFormat||o?.tieFormatId)&&We({structure:o,drawDefinition:e,event:a})?.tieFormat,p=(e?.tieFormat||e?.tieFormatId)&&We({drawDefinition:e,event:a})?.tieFormat,m=We({event:a})?.tieFormat,d=We({matchUp:c?.matchUp,drawDefinition:e,structure:o,event:a})?.tieFormat;return{...C,matchUp:c?.matchUp,structureDefaultTieFormat:sr(u),eventDefaultTieFormat:sr(m),drawDefaultTieFormat:sr(p),tieFormat:sr(d),structure:o}}var TN={};Jt(TN,{bulkUpdatePublishedEventIds:()=>ry,getAllEventData:()=>ny,getCourtInfo:()=>md,getDrawData:()=>rl,getEventData:()=>nl,getEventPublishStatus:()=>Xr,getPublishState:()=>Is,getTournamentPublishStatus:()=>Au,getVenueData:()=>fc});function ry({tournamentRecord:t,outcomes:e}){if(!t)return{error:$};if(!e?.length)return{error:st,info:"Missing outcomes"};let r=e.reduce((s,a)=>{let{drawId:c,eventId:u}=a;return u&&c&&(s[u]?s[u].includes(c)||s[u].push(c):s[u]=[c]),s},{}),n=Object.keys(r);return{publishedEventIds:(t.events?.filter(s=>n.includes(s.eventId))).filter(s=>{let a=Xr({event:s}),{drawDetails:c,drawIds:u}=a??{},{eventId:p}=s;return r[p].filter(d=>{let l=c?Object.keys(a.drawDetails).filter(f=>gd({drawId:f,drawDetails:c})):[];return u?.includes(d)||l.includes(d)}).length}).map(s=>s.eventId),eventIdPublishedDrawIdsMap:r}}function IN({dates:t=[],extension:e}){if(!e)return!1;if(typeof e.value=="boolean"&&e.value)return!0;if(!t.length)return!1;let r=ht(e.value)?e.value?.dates:void 0;if(Array.isArray(r))return r?.length?!!r.filter(o=>!t.length||t.includes(o)).length:!1}function hN({convertExtensions:t,ignoreDisabled:e,venue:r,court:n}){let o={...J(n,t,!0),venueId:r.venueId},{extension:i}=mt({name:ao,element:n});if(e&&i){let s=ht(i.value)?i.value?.dates:void 0,a=i?.value===!0?[]:o.dateAvailability.map(c=>{let u=c.date;if(!(!u||s.includes(u)))return c}).filter(Boolean);o.dateAvailability=a}return{inContextCourt:o}}function Uo(t){let{convertExtensions:e,ignoreDisabled:r,venueIds:n=[],dates:o}=t,i=t.tournamentRecords||t.tournamentRecord&&{[t.tournamentRecord.tournamentId]:t.tournamentRecord}||{},s=[],a=[],c=[],u=[];return Object.keys(i).filter(m=>!t.tournamentId||m===t.tournamentId).forEach(m=>{let d=i[m];for(let l of d.venues??[])if(!(n.length&&!n.includes(l.venueId))){if(r){let{extension:f}=mt({name:ao,element:l});if(f?.value)continue}s.includes(l.venueId)||(u.push(J(l,e,!0)),s.push(l.venueId));for(let f of l.courts??[])if(!a.includes(f.courtId)){if(r){let{extension:I}=mt({name:ao,element:f});if(IN({extension:I,dates:o}))continue}let{inContextCourt:g}=hN({convertExtensions:e,ignoreDisabled:r,venue:l,court:f});c.push(g),a.push(f.courtId)}}}),{courts:c,venues:u,...C}}function qV({convertExtensions:t,tournamentRecord:e,ignoreDisabled:r,dates:n}){if(!e)return{error:Lt};let o=J(e.venues??[],t).filter(s=>{if(!r)return s;let{extension:a}=mt({name:ao,element:s});return!a?.value&&s}).filter(Boolean),i=o.reduce((s,a)=>{let c=(a?.courts||[]).filter(u=>{if(!r&&!n?.length)return u;let{extension:p}=mt({name:ao,element:u});return IN({extension:p,dates:n})}).filter(Boolean).map(u=>{let{inContextCourt:p}=hN({convertExtensions:t,ignoreDisabled:r,venue:a,court:u});return p});return c.length?s.concat(c):s},[]);return{venues:o,courts:i}}function Qp({tournamentRecords:t,requireCourts:e,dates:r}){return typeof t!="object"||!Object.keys(t).length?{error:Lt}:Object.keys(t).reduce((o,i)=>{let s=t[i],{venues:a}=qV({tournamentRecord:s,dates:r});return a?.forEach(c=>{let{venueId:u,courts:p}=c;(!e||p?.length)&&!o.venueIds.includes(u)&&(o.venues.push(c),o.venueIds.push(u))}),o},{venues:[],venueIds:[]})}function ny({tournamentRecord:t,policyDefinitions:e}){if(!t)return{error:$};let r=t.events||[],n=t?.participants||[],{tournamentInfo:o}=Ps({tournamentRecord:t}),{venues:i}=Uo({tournamentRecord:t}),s=r.map(c=>{let{eventId:u}=c,p=XT({event:c}).eventInfo,m=Ea({tournamentRecord:t,event:c}).scheduleTiming,d=(c.drawDefinitions||[]).map(f=>{let g=(({drawId:y,drawName:E,matchUpFormat:P,updatedAt:A})=>({matchUpFormat:P,updatedAt:A,drawName:E,drawId:y}))(f),{abandonedMatchUps:I,completedMatchUps:h,upcomingMatchUps:S,pendingMatchUps:T}=Ys({requireParticipants:!0,tournamentParticipants:n,context:{eventId:u},policyDefinitions:e,tournamentRecord:t,inContext:!0,scheduleTiming:m,drawDefinition:f,event:c});return{drawInfo:g,matchUps:{abandonedMatchUps:I,completedMatchUps:h,upcomingMatchUps:S,pendingMatchUps:T}}}),l=Xr({event:c});return Object.assign(p,{drawsData:d,publish:l}),p});return{allEventData:{tournamentInfo:o,venuesData:i,eventsData:s}}}function oy({publishStatus:t,drawId:e}){return t?.drawDetails?t.drawDetails?.[e]?.publishingDetail?.published:t?.drawIds?t.drawIds.includes(e):!0}var SN="PUBLIC",$V="ADMIN",$_={PUBLIC_DISPLAY:SN,ADMIN_DISPLAY:$V};function rl(t){let{tournamentParticipants:e=[],includePositionAssignments:r,policyDefinitions:n,tournamentRecord:o,inContext:i=!0,usePublishState:s,status:a=Rr,pressureRating:c,refreshResults:u,contextProfile:p,drawDefinition:m,noDeepCopy:d,sortConfig:l,context:f,event:g}=t;if(!m)return{error:Z};let I=(({matchUpFormat:F,updatedAt:w,drawType:L,drawName:G,drawId:k})=>({matchUpFormat:F,updatedAt:w,drawName:G,drawType:L,drawId:k}))(m);I.display=mt({element:m,name:qm}).extension?.value;let h={},S,T,{allStructuresLinked:y,sourceStructureIds:E,hasDrawFeedProfile:P,structureGroups:A}=Nu({drawDefinition:m});if(!y)return{error:qA};let U=t?.eventPublishState??Is({event:g}).publishState,N=t?.publishStatus??Xr({event:g,status:a}),D=U?.status?.drawDetails?.[m.drawId],M=!!U?.status?.published,R=D?.structureDetails,b=!1,v=!1,x=A.map(F=>{let w={},L=F.map(G=>{let{structure:k}=at({drawDefinition:m,structureId:G}),{seedAssignments:H}=nn({drawDefinition:m,structure:k});return k?.stage===rt&&k.stageSequence===1&&(S=H),k?.stage===ct&&(h[k.stageSequence??0]=H),k}).sort((G,k)=>yi(G,k,l)).map(G=>{if(!G)return;let k=G?.structureId,H=[];G.stage&&[rt,qe,fe].includes(G.stage)&&(H=S),G?.stage===ct&&(H=h[G.stageSequence??0]);let{matchUps:W,roundMatchUps:q,roundProfile:Y}=yt({seedAssignments:G?.seedAssignments?.length?void 0:H,context:{drawId:I.drawId,...f},hydrateParticipants:t.hydrateParticipants,participantsProfile:t.participantsProfile,tournamentParticipants:e,policyDefinitions:n,tournamentRecord:o,usePublishState:s,publishStatus:N,contextProfile:p,drawDefinition:m,inContext:i,structure:G,event:g}),{positionAssignments:B}=Ct({structure:G}),K=B?.filter(Br(io)).map(z=>{let Q=mt({element:z,name:bo})?.extension?.value,{drawPosition:ut,participantId:it}=z;return v=!0,{participantResult:Q,participantId:it,drawPosition:ut}});if(W.length&&(!K?.length&&t.allParticipantResults||u&&!G.structures)){let{subOrderMap:z}=ZS({positionAssignments:B}),ut=W.some(Et=>Et.matchUpType===xr)?W.filter(Et=>Et.matchUpType===xr):W,it=ba({matchUpFormat:G.matchUpFormat,matchUps:ut,policyDefinitions:n,pressureRating:c,subOrderMap:z});T=it?.report,K=B?.filter(Br(io)).map(Et=>{let{drawPosition:_t,participantId:Ae}=Et;return v=!0,{participantResult:Ae&&it?.participantResults?.[Ae],participantId:Ae,drawPosition:_t}})}let X=G?(({stageSequence:z,structureName:Q,structureType:ut,matchUpFormat:it,stage:Et})=>({stageSequence:z,structureName:Q,structureType:ut,matchUpFormat:it,stage:Et}))(G):{},j=mt({element:G,name:qm}).extension?.value;X.display=j?.[SN]??j,X.sourceStructureIds=E[k],X.hasDrawFeedProfile=P[k],X.positionAssignments=B,X.structureActive=W.reduce((z,Q)=>{let ut=[Te,be,Gn,he,co,Rt,nr,bt].includes(Q.matchUpStatus);return z||ut||!!Q.winningSide||!!Q.score?.scoreStringSide1},!1);let ot=W.reduce((z,Q)=>z&&[Nt,he,nr,bt,Rt,vr].includes(Q.matchUpStatus),!!W.length);return X.structureCompleted=ot,w[k]=ot,X.structureActive&&(b=!0),{...X,participantResults:K,seedAssignments:H,roundMatchUps:q,roundProfile:Y,structureId:k,report:T}});return L.forEach(G=>{r||delete G.positionAssignments,G.sourceStructuresComplete=G.sourceStructureIds?.every(k=>w[k])}),L}).flat().filter(F=>!s||R?.[F?.structureId]?.published||!0);return I.drawActive=b,I.participantPlacements=v,I.drawGenerated=x?.reduce((F,w)=>F||!!w?.roundMatchUps,!1),I.drawCompleted=x?.reduce((F,w)=>F&&w.structureCompleted,!0),I.drawPublished=s?M&&oy({publishStatus:N,drawId:I.drawId}):void 0,{structures:!s||I.drawPublished?d&&x||J(x,!1,!0):void 0,drawInfo:d?I:J(I,!1,!0),...C}}function nl(t){let{includePositionAssignments:e,participantsProfile:r,policyDefinitions:n,usePublishState:o,status:i=Rr,contextProfile:s,sortConfig:a}=t,c=et(t,[{tournamentRecord:!0},{[Bm]:{event:!1,eventId:!1}}]);if(c.error)return c;let u=J(t.tournamentRecord,!1,!0),p=t.event?void 0:ze({tournamentRecord:u,eventId:t.eventId}).event,m=t.event?J(t.event,!1,!0):p&&J(p,!1,!0)||void 0;if(!m)return{error:jr};let{eventId:d}=m,{tournamentId:l,endDate:f}=u,g=Xr({event:m,status:i}),I=Is({event:m}).publishState??{},h=!!I?.status?.published,{participants:S}=Gt({withGroupings:!0,withEvents:!1,withDraws:!1,policyDefinitions:n,...r,tournamentRecord:u}),T=({stage:v,drawId:O})=>{if(!o)return!0;let x=g?.drawDetails?.[O]?.stageDetails;return!x||!Object.keys(x).length?!0:x[v]?.published},y=({structureId:v,drawId:O})=>{if(!o)return!0;let x=g?.drawDetails?.[O]?.structureDetails;return!x||!Object.keys(x).length?!0:x[v]?.published},E=({drawId:v})=>o?oy({publishStatus:g,drawId:v}):!0,P=({drawId:v,structure:O})=>{if(!o)return O;let x=g?.drawDetails?.[v]?.structureDetails?.[O.structureId]?.roundLimit;if(It(x)){let F=tt(1,x+1),w={},L={};for(let G of F)O.roundMatchUps[G]&&(w[G]=O.roundMatchUps[G],L[G]=O.roundProfile[G]);O.roundMatchUps=w,O.roundProfile=L}return O},A=m.drawDefinitions||[],U=!o||h?A.filter(E).map(v=>(({drawInfo:O,structures:x})=>({...O,structures:x}))(rl({allParticipantResults:t.allParticipantResults,hydrateParticipants:t.hydrateParticipants,context:{eventId:d,tournamentId:l,endDate:f},pressureRating:t.pressureRating,refreshResults:t.refreshResults,includePositionAssignments:e,tournamentParticipants:S,eventPublishState:I,noDeepCopy:!0,policyDefinitions:n,tournamentRecord:u,usePublishState:o,contextProfile:s,drawDefinition:v,publishStatus:g,sortConfig:a,event:m}))).map(({structures:v,...O})=>{let x=v?.filter(({stage:F,structureId:w})=>y({structureId:w,drawId:O.drawId})&&T({stage:F,drawId:O.drawId})).map(F=>P({drawId:O.drawId,structure:F}));return{...O,structures:x}}).filter(v=>v.structures?.length):void 0,D=(Array.isArray(u.venues)?u.venues:[]).map(v=>(({venueData:O})=>({...O}))(fc({venueId:v.venueId,tournamentRecord:u}))),M=(({eventId:v,eventName:O,eventType:x,eventLevel:F,surfaceCategory:w,matchUpFormat:L,category:G,gender:k,startDate:H,endDate:W,ballType:q,discipline:Y})=>({eventId:v,eventName:O,eventType:x,eventLevel:F,surfaceCategory:w,matchUpFormat:L,category:G,gender:k,startDate:H,endDate:W,ballType:q,discipline:Y}))(m);M.display=mt({element:m,name:qm}).extension?.value;let{tournamentInfo:R}=Ps({tournamentRecord:u}),b={tournamentInfo:R,venuesData:D,eventInfo:M,drawsData:U};return b.eventInfo.publishState=I,b.eventInfo.published=I?.status?.published,{...C,eventData:b,participants:S}}var UN={};Jt(UN,{courtGridRows:()=>sl,findVenue:()=>qo,getMatchUpsToSchedule:()=>ol,getPersonRequests:()=>Oi,getProfileRounds:()=>il,getScheduledRoundsDetails:()=>Vu,getSchedulingProfile:()=>Xo,getSchedulingProfileIssues:()=>iy,publicFindCourt:()=>SS});function ra({matchUpPotentialParticipantIds:t,matchUpNotBeforeTimes:e,timeAfterRecovery:r,matchUp:n}){let{individualParticipantIds:o}=mu(n);r=r??n.schedule?.timeAfterRecovery;let i=u=>{t[u]||(t[u]=[]),t[u]=pt(t[u].concat(...o))},s=u=>{r&&(!e[u]||r>e[u])&&(e[u]=r)},a=n.winnerTo?.matchUpId||n.winnerMatchUpId;a&&(r&&s(a),i(a));let c=n.loserTo?.matchUpId||n.loserMatchUpId;c&&(r&&s(c),i(c)),n.sidesTo?.length&&n.sidesTo.forEach(({matchUpId:u})=>{u&&(r&&s(u),i(u))})}function ol(t){let e=et(t,[{[bf]:!0}]);if(e.error)return e;let{matchUpPotentialParticipantIds:r,dateScheduledMatchUpIds:n=[],scheduleCompletedMatchUps:o,matchUpNotBeforeTimes:i,matchUpScheduleTimes:s,orderedMatchUpIds:a,clearDate:c,matchUps:u}=t,p=s?Object.keys(s):[],m=(a??[]).map(l=>u.find(f=>f.matchUpId===l)).filter(Boolean).filter(l=>{let f=!c&&(n.includes(l.matchUpId)||p.includes(l.matchUpId)),g=[Nt,Rt,he,vr,nr,bt,Te,be].includes(l?.matchUpStatus);return o||!f&&!l.winningSide&&!g}),d=r&&i?m.reduce((l,f)=>{let{drawId:g,tournamentId:I}=f;return l.matchUpMap[I]||(l.matchUpMap[I]={}),l.matchUpMap[I][g]?l.matchUpMap[I][g].push(f):l.matchUpMap[I][g]=[f],ra({matchUpPotentialParticipantIds:r,matchUpNotBeforeTimes:i,matchUp:f}),l},{matchUpMap:{}}).matchUpMap:{};return{matchUpsToSchedule:m,matchUpMap:d}}function Xp({defaultRecoveryMinutes:t=0,defaultAverageMinutes:e,tournamentRecords:r,matchUpFormat:n,categoryName:o,categoryType:i,tournamentId:s,eventType:a,eventId:c}){if(!Dr({matchUpFormat:n}))return{error:$a};let u=Object.keys(r).filter(m=>!s||m===s),p;return u.forEach(m=>{if(p)return;let d=r[m],l=c?ze({tournamentRecord:d,eventId:c})?.event:void 0;return p=Tu({tournamentRecord:d,matchUpFormat:n,categoryName:o,categoryType:i,eventType:a,event:l}),p?.averageMinutes||p?.recoveryMinutes}),{recoveryMinutes:p?.recoveryMinutes||t,averageMinutes:p?.averageMinutes||e,typeChangeRecoveryMinutes:p?.typeChangeRecoveryMinutes||p?.recoveryMinutes||t}}function Vu(t){let e=et(t,[{[Bm]:{tournamentRecords:!1,tournamentRecord:!1}},{rounds:!0,[He]:Be}]);if(e.error)return e;let{scheduleCompletedMatchUps:r,periodLength:n=30}=t,o=t.tournamentRecords||t.tournamentRecord&&{[t.tournamentRecord.tournamentId]:t.tournamentRecord}||{};if(typeof o!="object")return{error:Lt};let i={},s=[],a=[],c=t.rounds.toSorted((I,h)=>(I.sortOrder??0)-(h.sortOrder??0)),u=t.containedStructureIds??Object.assign({},...Object.values(o).map(I=>cs({tournamentRecord:I}).containedStructures)),p=t.matchUps??Un({nextMatchUps:!0,tournamentRecords:o}).matchUps,m=0,d={},l={},f={};return{scheduledRoundsDetails:c.flatMap(I=>{let h=I.periodLength||n,S=[];u?.[I.structureId]?S.push(...u[I.structureId]):S.push(I.structureId);let T=p?Mi({tournamentIds:[I.tournamentId],roundNumbers:[I.roundNumber],matchUpIds:I.matchUpIds,eventIds:[I.eventId],drawIds:[I.drawId],processContext:!0,structureIds:S,matchUps:p}).sort(Ri):[],{segmentNumber:y,segmentsCount:E}=I.roundSegment||{};if(It(y)&&_n(T?.length)&&_n(E)&&y>0&&y<=E&&E<T?.length&&!I.matchUpIds?.length){let N=T.length/E,D=N*(y-1);T=T.slice(D,D+N)}let P=o[I.tournamentId],A=ze({drawId:I.drawId,tournamentRecord:P}).event,U=[];for(let N of T){let D=N.matchUpFormat;D&&(i[D]||(i[D]=[],i[D].push(N)),U.push(D))}for(let N of U){let{eventType:D,category:M}=A??{},{categoryName:R,ageCategoryCode:b}=M??{},{typeChangeRecoveryMinutes:v,recoveryMinutes:O,averageMinutes:x,error:F}=Xp({categoryName:R??b,categoryType:M?.categoryType,tournamentId:I.tournamentId,eventId:I.eventId,tournamentRecords:o,matchUpFormat:N,eventType:D});if(F)return{error:F,round:I};let w=T.filter(G=>(r||!se.includes(G.matchUpStatus))&&G.matchUpStatus!==Nt).map(Ue);w.forEach(G=>{f[G]={typeChangeRecoveryMinutes:v,recoveryMinutes:O,averageMinutes:x},d[G]=O,l[G]=x}),a.push(...w),m=Math.max(x||0,m);let L=`${x}|${h}`;return s.includes(L)||s.push(L),{roundPeriodLength:h,recoveryMinutes:O,averageMinutes:x,matchUpIds:w,hash:L}}}),greatestAverageMinutes:m,matchUpFormatCohorts:i,recoveryMinutesMap:d,averageMinutesMap:l,orderedMatchUpIds:a,minutesMap:f,...C}}function yN({schedulingProfile:t,venueIds:e,eventIds:r,drawIds:n}){let o=[],i=t?.map(a=>{let c=Pt(a?.scheduleDate);if(!c){o.push(`Invalid date: ${a?.scheduledDate}`);return}let u=(a?.venues||[]).map(p=>{let{rounds:m,venueId:d}=p;if(!e?.includes(d)){o.push(`Missing venueId: ${d}`);return}let f=m.filter(g=>{let I=r.includes(g.eventId)&&n.includes(g.drawId);return I||o.push(`Invalid eventId: ${g.eventId} or drawId: ${g.drawId}`),I});if(f.length)return{venueId:d,rounds:f}}).filter(Boolean);return u.length&&c&&{...a,venues:u}}).filter(Boolean),s=o.length;return{updatedSchedulingProfile:i,modifications:s,issues:o}}function Jp({tournamentRecords:t,schedulingProfile:e}){if(!e)return{valid:!0};if(!Array.isArray(e))return{valid:!1,error:V};let{venueIds:r,tournamentsMap:n}=zV({tournamentRecords:t}),o,i,s=e.every(a=>{let{scheduleDate:c,venues:u}=a;return Nr(c)?u.every(p=>{let{venueId:m,rounds:d}=p;return typeof m!="string"?(i="venueId should be a string",!1):Array.isArray(d)?r.includes(m)?!!d.every(f=>{if(!f)return i="empty round",!1;let{roundSegment:g,tournamentId:I,structureId:h,roundNumber:S,eventId:T,drawId:y}=f,P=n?.[I]?.[T]?.[y]?.[h]?.includes(S);P||(i="Invalid rounds");let{segmentNumber:A,segmentsCount:U}=g||{},N=!g||It(A)&&_n(U)&&A<=U;return N||(i="Invalid segment"),P&&N}):(o=ki,!1):(i="rounds should be an array",!1)}):!1});return!s&&!o&&(o=V),{valid:!!s,error:o,info:i}}function KV(t){let{tournamentRecord:e={},tournamentMap:r={},requireCourts:n}=t,o=[],i=[],s=[],a=[],c=(e?.venues||[]).map(({venueId:p,courts:m})=>(!n||m?.length)&&p),u=e?.tournamentId;if(u){o.push(u),r[u]={};let p=e?.events||[];for(let m of p){let d=m.eventId;s.push(d),r[u][d]={};let l=f=>parseInt(f);for(let f of m.drawDefinitions||[]){let g=f.drawId;a.push(g),r[u][d][g]={};let{structures:I}=gn({drawDefinition:f});for(let h of I||[]){let S=h.structureId,{matchUps:T}=yt({structure:h}),{roundMatchUps:y}=Ke({matchUps:T}),E=y&&Object.keys(y).map(l);if(r[u][d][g][S]=E,i.push(S),h.structures?.length)for(let P of h.structures)i.push(P.structureId),r[u][d][g][P.structureId]=E}}}}return{tournamentMap:r,tournamentIds:o,structureIds:i,venueIds:c,eventIds:s,drawIds:a}}function zV(t){let e=t?.tournamentRecords&&Object.values(t?.tournamentRecords)||[],r={},{venueIds:n,eventIds:o,drawIds:i,structureIds:s,tournamentIds:a}=e.reduce((c,u)=>{let{tournamentIds:p,tournamentMap:m,structureIds:d,venueIds:l,eventIds:f,drawIds:g}=KV({tournamentRecord:u});return l.forEach(I=>{c.venueIds.includes(I)||c.venueIds.push(I)}),c.tournamentIds.push(...p),c.structureIds.push(...d),c.eventIds.push(...f),c.drawIds.push(...g),Object.assign(r,m),c},{tournamentIds:[],structureIds:[],venueIds:[],eventIds:[],drawIds:[]});return{tournamentsMap:r,tournamentIds:a,structureIds:s,venueIds:n,eventIds:o,drawIds:i}}function Xo({tournamentRecords:t,tournamentRecord:e}){if(typeof t!="object"||!Object.keys(t).length)return{error:Lt};let{extension:r}=mt({element:e,name:ya,tournamentRecords:t,discover:!0}),n=r?.value||[];if(n.length){let{venueIds:o}=Qp({requireCourts:!0,tournamentRecords:t}),{eventIds:i,drawIds:s}=_g({tournamentRecords:t}),{updatedSchedulingProfile:a,modifications:c,issues:u}=yN({schedulingProfile:n,venueIds:o,eventIds:i,drawIds:s});if(c){n=a;let p=Cc({tournamentRecords:t,tournamentRecord:e,schedulingProfile:n});return p.error?p:{schedulingProfile:n,modifications:c,issues:u}}}return{schedulingProfile:n,modifications:0}}function Cc({tournamentRecords:t,tournamentRecord:e,schedulingProfile:r}){let n=Jp({tournamentRecords:t,schedulingProfile:r});return n.error?n:r?Ut({tournamentRecords:t,discover:!0,extension:{name:ya,value:r}}):gr({element:e,name:ya,tournamentRecords:t,discover:!0})}function bc(t){let{tournamentRecord:e}=t,r=t.tournamentRecords||e&&{[e.tournamentId]:e}||{};if(!t.schedulingProfile){let{modifications:u,issues:p}=Xo({tournamentRecords:r,tournamentRecord:e});return{success:!u,modifications:u,issues:p}}let{venueIds:n}=Qp({tournamentRecords:r}),{eventIds:o,drawIds:i}=_g({tournamentRecords:r}),{updatedSchedulingProfile:s,modifications:a,issues:c}=yN({schedulingProfile:t.schedulingProfile,venueIds:n,eventIds:o,drawIds:i});return a?{...Cc({schedulingProfile:s,tournamentRecords:r}),modifications:a,issues:c}:{...C,modifications:a,issues:c}}function iy(t){let{scheduleDates:e=[],tournamentRecords:r,periodLength:n=30}=t??{};if(typeof r!="object")return{error:Wa};if(!Array.isArray(e))return{error:V};if(!e.every(Nr))return{error:je};let i=[],s=0,a={},{schedulingProfile:c}=Xo({tournamentRecords:r});if(!c)return{issues:i,...C};let{matchUps:u}=Un({nextMatchUps:!0,tournamentRecords:r});for(let m of c){let{scheduleDate:d,venues:l=[]}=m;if(!e?.length||e.includes(d)){for(let f of l||[])if(f){let{rounds:g}=f,I=[],{orderedMatchUpIds:h,scheduledRoundsDetails:S}=Vu({tournamentRecords:r,periodLength:n,matchUps:u,rounds:g}),{matchUpDependencies:T}=on({tournamentRecords:r,matchUps:u}),y=E=>{let P;return S?.find((A,U)=>{let N=A.matchUpIds.includes(E);return N&&(P=U),N}),P};if(h?.forEach((E,P)=>{let A=h.slice(P+1),U=jt(A,T?.[E]?.matchUpIds||[]);U.length&&I.push({matchUpId:E,shouldBeAfter:U})}),I.length){s+=I.length;let E=I.map(({matchUpId:P,shouldBeAfter:A})=>{let U=y(P),N=pt(A.map(y));return a[d]||(a[d]={}),a[d][U]||(a[d][U]=[]),N.forEach(D=>{a[d][U].includes(D)||a[d][U].push(D)}),{matchUpId:P,matchUpRoundIndex:U,earlierRoundIndices:N,shouldBeAfter:A}});i.push(...E)}}}}let p={matchUpIdShouldBeAfter:Object.assign({},...i.map(m=>{let{matchUpId:d,shouldBeAfter:l,earlierRoundIndices:f}=m;return{[d]:{earlierRoundIndices:f,shouldBeAfter:l}}}))};return{issuesCount:s,profileIssues:p,roundIndexShouldBeAfter:a,...C}}function Oi(t){let{tournamentRecords:e,requestType:r}=t,n=et(t,[{[Re]:!0}]);if(n.error)return n;let o={};for(let i of Object.values(e)){let{extension:s}=mt({element:i,name:Ta}),a=s?.value||[];for(let c of a){let{personId:u,requests:p}=c||{};o[u]||(o[u]=[]);for(let m of p)r&&m.requestType!==r||o[u].push(m)}}return{personRequests:o,...C}}function Qg(t){let{containerStructureId:e,roundSegment:r,isRoundRobin:n,tournamentId:o,roundNumber:i,structureId:s,eventId:a,drawId:c}=t,u=n?e:s,p=[o,a,c,u,i].join("|");return nt({structureId:u,roundSegment:r,tournamentId:o,roundNumber:i,eventId:a,drawId:c,id:p})}function AN({round:t,matchUps:e,events:r,tournamentRecords:n}){let o=r.find(d=>d.eventId===t.eventId),{eventType:i,category:s,categoryType:a}=o||{},{categoryName:c,ageCategoryCode:u}=s||{},p=yr(e.map(({matchUpFormat:d})=>d)),m=0;return Object.keys(p).forEach(d=>{let l=p[d],f=Xp({categoryName:c||u,tournamentId:t.tournamentId,eventId:t.eventId,tournamentRecords:n,matchUpFormat:d,categoryType:a,eventType:i});if(f.error)return f;let g=f.averageMinutes*l;isNaN(m)||(m+=g)}),{roundMinutes:m}}function K_(t){return(t||[]).reduce((e,r)=>{let n=(r.finishingPositionRange?.winner||[]).reduce((i,s)=>i+s,0),o=(r.finishingPositionRange?.winner||[]).join("-")||"";return!e.minFinishingSum||n<e.minFinishingSum?{minFinishingSum:n,winnerFinishingPositionRange:o}:e},{minFinishingSum:0,winnerFinishingPositionRange:""})}function EN(t){let e=t.length,r=t.filter(({sides:p})=>p?.some(({bye:m})=>m)).length||0,n=t.filter(({winningSide:p,matchUpStatus:m})=>p||se.includes(m)).length||0,o=t.filter(({schedule:p,matchUpStatus:m})=>p?.scheduledDate&&p?.scheduledTime&&m!==Nt).length||0,i=e-r,s=i===n,a=i-o,c=i-o;return{unscheduledCount:a,incompleteCount:c,scheduledCount:o,completedCount:n,matchUpsCount:e,isScheduled:i===o,isComplete:s,byeCount:r}}function il({tournamentRecords:t,schedulingProfile:e,tournamentRecord:r,withRoundId:n}){if(r&&!t){if(typeof r!="object")return{error:Wa};t={[r.tournamentId]:r}}if(e){let s=Jp({tournamentRecords:t,schedulingProfile:e});if(s.error)return s}if(!e&&t){let s=Xo({tournamentRecords:t});if(s.error)return s;e=s.schedulingProfile}if(!e)return{error:ve};let o={};return{profileRounds:e.map(({venues:s,scheduleDate:a})=>s.map(({rounds:c})=>c.map(u=>{let p=Qg(u);return p.roundSegment?.segmentsCount&&(o[p.id]=p.roundSegment.segmentsCount),nt({id:n?p.id:void 0,scheduleDate:a,...p})}))).flat(1/0),segmentedRounds:o}}function sl({courtPrefix:t="C|",minRowsCount:e,courtsData:r}){if(!Array.isArray(r))return{error:V};let n=r?.reduce((s,a)=>{let c=a.matchUps||[],u=Math.max(0,...c.map(p=>p.schedule.courtOrder||0));return u>s?u:s},1),o=e?Math.max(e,n):n,i=tt(0,o).map(s=>({matchUps:tt(0,r.length).map(a=>{let c=r[a],{courtId:u,venueId:p}=c;return{schedule:{courtOrder:s+1,venueId:p,courtId:u}}})}));return r.forEach((s,a)=>{for(let c of s.matchUps){let u=c.schedule?.courtOrder;u&&(i[u-1].matchUps[a]=c)}}),{courtPrefix:t,rows:i.map((s,a)=>Object.assign({rowId:`rowId-${a+1}`},...s.matchUps.map((c,u)=>({[`${t}${u}`]:c}))))}}var PN={};Jt(PN,{getEntriesAndSeedsCount:()=>al,getMaxEntryPosition:()=>sy});function al({policyDefinitions:t,drawDefinition:e,drawSize:r,drawId:n,event:o,stage:i}){if(!o)return{error:Ot};let{entries:s,stageEntries:a}=DS({drawDefinition:e,drawId:n,stage:i,event:o}),c=a.length,{drawSize:u}=PT({participantsCount:c}),p=wu({drawSize:r??u,participantsCount:c,policyDefinitions:t});if(p.error)return _({result:p,stack:"getEntriesAndSeedsCount"});let{seedsCount:m}=p;return{entries:s,seedsCount:m,stageEntries:a}}function sy(t){let{entries:e=[],entryStatus:r,stage:n}=t;return Math.max(...e.filter(o=>(!n||n===o.entryStage)&&(!r||o.entryStatus===r)&&!isNaN(o.entryPosition)).map(({entryPosition:o})=>dt(o||0)),0)}var RN={};Jt(RN,{allCompetitionMatchUps:()=>Un,allDrawMatchUps:()=>ir,allEventMatchUps:()=>Xn,allTournamentMatchUps:()=>ye,analyzeMatchUp:()=>tm,calculateWinCriteria:()=>Ds,checkMatchUpIsComplete:()=>ls,competitionScheduleMatchUps:()=>Bu,drawMatchUps:()=>Ty,eventMatchUps:()=>pl,filterMatchUps:()=>Mi,getAllDrawMatchUps:()=>ce,getAllStructureMatchUps:()=>yt,getCheckedInParticipantIds:()=>ps,getCompetitionMatchUps:()=>Zp,getEventMatchUpFormatTiming:()=>py,getHomeParticipantId:()=>fy,getMatchUpCompetitiveProfile:()=>Su,getMatchUpContextIds:()=>gy,getMatchUpDailyLimits:()=>dl,getMatchUpDailyLimitsUpdate:()=>my,getMatchUpDependencies:()=>on,getMatchUpFormat:()=>Iy,getMatchUpFormatTiming:()=>Tu,getMatchUpFormatTimingUpdate:()=>cy,getMatchUpScheduleDetails:()=>dd,getMatchUpType:()=>ld,getMatchUpsStats:()=>hy,getModifiedMatchUpFormatTiming:()=>cl,getParticipantResults:()=>vu,getPredictiveAccuracy:()=>ly,getRoundMatchUps:()=>Ke,getRounds:()=>Sy,isValidMatchUpFormat:()=>Dr,matchUpActions:()=>xd,participantScheduledMatchUps:()=>dy,tallyParticipantResults:()=>ba,tournamentMatchUps:()=>ml,validMatchUp:()=>og,validMatchUps:()=>Vr});function ay({tournamentRecords:t,extensionName:e}){if(typeof t!="object"||!Object.keys(t).length)return{error:Lt};let r=[],n;for(let o of Object.values(t)){let{extension:i}=mt({element:o,name:e});i&&!n&&(r.push({params:{extension:i,discover:!0},method:"addExtension"}),n=!0);let s=o.events??[];for(let a of s){let{eventId:c}=a,{extension:u}=mt({name:e,element:a});u&&r.push({params:{eventId:c,extension:u},method:"addEventExtension"})}}return{methods:r}}function cy({tournamentRecords:t}){return ay({extensionName:Ho,tournamentRecords:t})}var DN="ADULT",NN="JUNIOR",uy="WHEELCHAIR",MN={[Mo]:{allowModificationWhenMatchUpsScheduled:{courts:!1,venues:!1},defaultTimes:{averageTimes:[{categoryNames:[],minutes:{default:90}}],recoveryTimes:[{minutes:{[xt]:30,default:60}}]},defaultDailyLimits:{[kt]:2,[xt]:2,total:3},matchUpAverageTimes:[{matchUpFormatCodes:[Dn],averageTimes:[{categoryNames:[],minutes:{default:90}},{categoryTypes:[uy],minutes:{default:120}}]},{matchUpFormatCodes:["SET3-S:6/TB7-F:TB10"],averageTimes:[{categoryNames:[],minutes:{default:85}}]},{matchUpFormatCodes:["SET3-S:6/TB7-F:TB7"],averageTimes:[{categoryNames:[],minutes:{default:70}}]},{matchUpFormatCodes:["SET3-S:4NOAD-F:TB7"],averageTimes:[{categoryNames:[],minutes:{default:55}}]},{matchUpFormatCodes:["SET3-S:4/TB7"],averageTimes:[{categoryNames:[],minutes:{default:60}}]},{matchUpFormatCodes:["SET3-S:4/TB7-F:TB7"],averageTimes:[{categoryNames:[],minutes:{default:50}}]},{matchUpFormatCodes:["SET3-S:4/TB7-F:TB10"],averageTimes:[{categoryNames:[],minutes:{default:55}}]},{matchUpFormatCodes:["SET3-S:4/TB5@3"],averageTimes:[{categoryNames:[],minutes:{default:45}}]},{matchUpFormatCodes:["SET1-S:8/TB7","SET1-S:8/TB7@7"],averageTimes:[{categoryNames:[],minutes:{default:40}}]},{matchUpFormatCodes:["SET1-S:5/TB9@4"],averageTimes:[{categoryNames:[],minutes:{default:30}}]},{matchUpFormatCodes:["SET1-S:6/TB7"],averageTimes:[{categoryNames:[],minutes:{default:30}}]},{matchUpFormatCodes:["SET1-S:6NOAD"],averageTimes:[{categoryNames:[],minutes:{default:30}}]},{matchUpFormatCodes:["SET1-S:4/TB7","SET1-S:4/TB5@3","SET3-S:TB10","SET1-S:T20"],averageTimes:[{categoryNames:[],minutes:{default:20}}]},{matchUpFormatCodes:["SET1-S:4NOAD"],averageTimes:[{categoryNames:[],minutes:{default:20}}]},{matchUpFormatCodes:["SET1-S:TB10"],averageTimes:[{categoryNames:[],minutes:{default:10}}]}],matchUpRecoveryTimes:[{matchUpFormatCodes:["SET3-S:6/TB7","SET3-S:6/TB7-F:TB10","SET3-S:6/TB7-F:TB7"],recoveryTimes:[{categoryTypes:[DN,uy],minutes:{default:60,[xt]:30}},{categoryTypes:[NN],minutes:{default:60,[xt]:60}}]},{matchUpFormatCodes:["SET3-S:4/TB7-F:TB7","SET3-S:4/TB7-F:TB10","SET3-S:4NOAD-F:TB7","SET3-S:4/TB7","SET3-S:4/TB5@3"],recoveryTimes:[{categoryTypes:[DN,uy],minutes:{default:30}},{categoryTypes:[NN],minutes:{default:60}}]},{matchUpFormatCodes:["SET1-S:8/TB7","SET1-S:8/TB7@7","SET1-S:5/TB9@4","SET1-S:6/TB7","SET1-S:6NOAD","SET1-S:4/TB7","SET1-S:4NOAD","SET3-S:TB10","SET1-S:T20"],recoveryTimes:[{categoryNames:[],minutes:{default:30}}]},{matchUpFormatCodes:["SET1-S:4/TB5@3"],recoveryTimes:[{categoryTypes:[DN,NN],minutes:{default:30}},{categoryTypes:[uy],minutes:{default:15}}]},{matchUpFormatCodes:["SET1-S:TB10"],recoveryTimes:[{categoryNames:[],minutes:{default:15}}]}],matchUpDailyLimits:[]}},z_=MN;function py({tournamentRecord:t,matchUpFormats:e,categoryType:r,event:n}){if(!n)return{error:Ot};let o=[],i;if(e?.length){let m=[];o=e.map(d=>{let l=typeof d=="string"?{matchUpFormat:d}:d;if(!m.includes(l?.matchUpFormat)&&Dr({matchUpFormat:l?.matchUpFormat}))return m.push(l.matchUpFormat),l}).filter(Boolean)}else{let{policy:m}=ni({policyType:tn,tournamentRecord:t,event:n});if(m?.matchUpFormats)o=m?.matchUpFormats;else{let{extension:d}=mt({name:Ho,element:n}),l,f;d?.value?{matchUpAverageTimes:l,matchUpRecoveryTimes:f}=d.value:{matchUpAverageTimes:l,matchUpRecoveryTimes:f}=z_[Mo],o=pt([...(l||[]).map(g=>g.matchUpFormatCodes),...(f||[]).map(g=>g.matchUpFormatCodes)].flat()).map(g=>({matchUpFormat:g})),i="default scheduling policy in use"}}let{eventType:s,eventId:a,category:c}=n,u=c?.categoryName??c?.ageCategoryCode??a;if(!a)return{error:Ot};let p=o.map(({matchUpFormat:m,description:d})=>{let l=Tu({tournamentRecord:t,matchUpFormat:m,categoryName:u,categoryType:r,eventType:s,event:n});return{matchUpFormat:m,description:d,...l}});return nt({eventMatchUpFormatTiming:p,info:i})}function cl(t){let e=et(t,[{[ne]:!0},{[er]:g=>Dr({matchUpFormat:g}),[Fr]:$a,[Gm]:!0}]);if(e.error)return e;let{tournamentRecord:r,matchUpFormat:n,event:o}=t,{extension:i}=mt({name:Ho,element:o}),s=i?.value,{extension:a}=mt({element:r,name:Ho}),c=a?.value,u=s?.matchUpAverageTimes&&Dp({...s,matchUpFormat:n}),p=c?.matchUpAverageTimes&&Dp({...c,matchUpFormat:n}),m=[u,p].find(g=>g),d=s?.matchUpRecoveryTimes&&Np({...s,matchUpFormat:n}),l=c?.matchUpRecoveryTimes&&Np({...c,matchUpFormat:n}),f=[d,l].find(g=>g);return{matchUpFormat:n,recoveryTimes:f,averageTimes:m}}function my({tournamentRecords:t}){return ay({extensionName:su,tournamentRecords:t})}var xa=({scheduleAttributes:t=["scheduledDate","scheduledTime"],schedule:e={}})=>!!Object.keys(e).filter(n=>t.includes(n)).filter(n=>e[n]).length;function dy({scheduleAttributes:t=["scheduledDate","scheduledTime"],matchUps:e=[]}){if(!Vr(e))return{error:eo};if(!Array.isArray(t))return{error:V};let r=e.filter(Boolean).filter(({schedule:o})=>xa({schedule:o,scheduleAttributes:t})).reduce((o,i)=>{let{schedule:s}=i,a=Pt(s?.scheduledDate),c=Qt(s?.scheduledTime);return a&&c&&(o[a]?o[a].push(i):o[a]=[i]),o},{});return Object.keys(r).forEach(o=>{r[o].sort((i,s)=>rh(Qt(i.schedule?.scheduledTime),Qt(s.schedule?.scheduledTime)))}),{...C,scheduledMatchUps:r}}function Q_({tournamentRecords:t}){let e={},r=[];for(let n of Object.values(t))for(let o of n.events??[]){let i=Xr({event:o}),s=i?.drawDetails;ht(s)?(Object.assign(e,s),r.push(...Object.keys(s).filter(a=>gd({drawId:a,drawDetails:s})))):i?.drawIds?.length&&r.push(...i.drawIds)}return{drawIds:r,detailsMap:e}}function ul({schedulingProfile:t,matchUps:e=[]}){let r={},n=({eventId:a,drawId:c,structureId:u,roundNumber:p})=>`${a}|${c}|${u}${p}`;t?.length&&t.map(({venues:c})=>c.map(({rounds:u})=>u)).flat().forEach(c=>{c.sort((p,m)=>(p.sortOrder||0)-(m.sortOrder||0)).forEach(({eventId:p,drawId:m,structureId:d,roundNumber:l},f)=>{let g=n({eventId:p,drawId:m,structureId:d,roundNumber:l});r[g]=f})});let o=[],i={noScheduledDate:[]};for(let a of e){let c=a.schedule||{},u=c.scheduledDate&&Pt(c.scheduledDate)||c.scheduledTime&&Pt(c.scheduledTime)||"noScheduledDate";i[u]||(i[u]=[]),i[u].push(a)}let s=Object.keys(i).sort();for(let a of s){let c=i[a],u={noScheduledTime:[]};for(let m of c){let d=m.schedule||{},l=d.scheduledTime&&Qt(d.scheduledTime)||"noScheduledTime";u[l]||(u[l]=[]),u[l].push(m)}for(let m of Object.keys(u)){let l=u[m].sort((f,g)=>(f.roundNumber||0)-(g.roundNumber||0));u[m]=l}let p=Object.keys(u).sort();for(let m of p){let d=u[m];d.sort((l,f)=>{let g=r[n(l)]||0,I=r[n(f)]||0;return g-I}),o.push(...d)}}return o}function pl(t){let{participants:e,contextContent:r,participantMap:n}=t,{tournamentAppliedPolicies:o,scheduleVisibilityFilters:i,participantsProfile:s,afterRecoveryTimes:a,policyDefinitions:c,useParticipantMap:u,tournamentRecord:p,usePublishState:m,contextFilters:d,matchUpFilters:l,contextProfile:f,nextMatchUps:g,tournamentId:I,inContext:h,context:S,event:T}=t;if(!T)return{error:Ot};let{eventId:y,eventName:E,endDate:P,eventType:A,category:U,gender:N}=T??{},D={...S,...nt({surfaceCategory:T.surfaceCategory??p?.surfaceCategory,indoorOutDoor:T.indoorOutdoor??p?.indoorOutdoor,tournamentId:I??p?.tournamentId,endDate:P??p?.endDate,eventName:E,eventType:A,category:U,eventId:y,gender:N})},M;!e&&p&&({participants:e,participantMap:n,groupInfo:M}=Wo({participantsProfile:s,policyDefinitions:c,useParticipantMap:u,tournamentRecord:p,contextProfile:f,inContext:h})),f&&!r&&(r=Qn({policyDefinitions:c,tournamentRecord:p,contextProfile:f,event:T}));let R=Xr({event:T});return{...(T.drawDefinitions??[]).reduce((O,x)=>{let F=Ys({hydrateParticipants:t.hydrateParticipants,context:D,tournamentAppliedPolicies:o,scheduleVisibilityFilters:i,tournamentParticipants:e,participantsProfile:s,afterRecoveryTimes:a,policyDefinitions:c,tournamentRecord:p,usePublishState:m,contextContent:r,contextFilters:d,matchUpFilters:l,participantMap:n,publishStatus:R,contextProfile:f,drawDefinition:x,nextMatchUps:g,inContext:h,event:T});return Object.keys(F)?.forEach(L=>{Array.isArray(F[L])&&(O[L]||(O[L]=[]),O[L]=O[L].concat(F[L]))}),O},{}),...C,groupInfo:M}}function ml(t){if(!t?.tournamentRecord)return{error:$};let e=t.contextContent,{scheduleVisibilityFilters:r,participantsProfile:n,afterRecoveryTimes:o,policyDefinitions:i,tournamentRecord:s,inContext:a=!0,usePublishState:c,contextFilters:u,matchUpFilters:p,contextProfile:m,nextMatchUps:d,context:l}=t,f=t.tournamentId??s.tournamentId,g=s?.events??[],{participants:I,participantMap:h,groupInfo:S}=Wo({participantsProfile:n,policyDefinitions:i,tournamentRecord:s,contextProfile:m,inContext:a});m&&!e&&(e=Qn({policyDefinitions:i,tournamentRecord:s,contextProfile:m}));let{appliedPolicies:T}=Tt({tournamentRecord:s}),y=u?.eventIds??[];return{...g.filter(A=>!y.includes(A.eventId)).map(A=>{let N={eventDrawsCount:Ht({event:A}).flightProfile?.flights?.length||A.drawDefinitions?.length||0,...l};return pl({hydrateParticipants:t.hydrateParticipants,context:N,tournamentAppliedPolicies:T,scheduleVisibilityFilters:r,participantsProfile:n,afterRecoveryTimes:o,policyDefinitions:i,tournamentRecord:s,usePublishState:c,contextFilters:u,contextProfile:m,contextContent:e,matchUpFilters:p,participantMap:h,participants:I,tournamentId:f,nextMatchUps:d,inContext:a,event:A})}).reduce((A,U)=>((U&&Object.keys(U).filter(D=>!["success","matchUpsMap"].includes(D)))?.forEach(D=>{Array.isArray(U[D])&&(A[D]||(A[D]=[]),A[D]=A[D].concat(U[D]),A.matchUpsCount!==void 0?A.matchUpsCount+=U[D].length:A.matchUpsCount=U[D].length)}),A),{matchUpsCount:0}),groupInfo:S,participants:I}}function Zp({scheduleVisibilityFilters:t,hydrateParticipants:e,participantsProfile:r,tournamentRecords:n,useParticipantMap:o,policyDefinitions:i,usePublishState:s,matchUpFilters:a,contextFilters:c,nextMatchUps:u,inContext:p}){if(typeof n!="object"||!Object.keys(n).length)return{error:Lt};let d=Object.keys(n).map(I=>{let h=n[I];return ml({scheduleVisibilityFilters:t,hydrateParticipants:e,participantsProfile:r,useParticipantMap:o,policyDefinitions:i,tournamentRecord:h,usePublishState:s,matchUpFilters:a,contextFilters:c,nextMatchUps:u,inContext:p})}),l={},f={};return{...d.reduce((I,h)=>(Object.keys(h).forEach(T=>{if(T==="groupInfo")Object.assign(f,h[T]);else if(T==="participants")for(let y of h[T]??[])l[y.participantId]=y;else Array.isArray(h[T])&&(I[T]||(I[T]=[]),I[T]=I[T].concat(h[T]))}),I),{}),groupInfo:f,mappedParticipants:l}}function Bu(t){if(typeof t?.tournamentRecords!="object"||!Object.keys(t?.tournamentRecords).length)return{error:Lt};let{courts:e,venues:r}=Uo(t),o=Xo(t).schedulingProfile,{sortDateMatchUps:i=!0,courtCompletedMatchUps:s,alwaysReturnCompleted:a,activeTournamentId:c,tournamentRecords:u,withCourtGridRows:p,minCourtGridRows:m,usePublishState:d,status:l=Rr,sortCourtsData:f}=t,g=c??os()??Object.keys(u)[0],I=d?Au({tournamentRecord:u[g],status:l}):void 0,h=a?Zp({...t,matchUpFilters:{...t.matchUpFilters,matchUpStatuses:[he]},contextFilters:t.contextFilters}).completedMatchUps:[];if(d&&!I?.orderOfPlay?.published)return{completedMatchUps:h,dateMatchUps:[],courtsData:[],venues:r};let S,T;d&&({drawIds:S,detailsMap:T}=Q_({tournamentRecords:u})),S?.length&&(t.contextFilters||(t.contextFilters={}),t.contextFilters?.drawIds?t.contextFilters.drawIds=t.contextFilters.drawIds.filter(v=>S.includes(v)):t.contextFilters.drawIds=S),I?.eventIds?.length&&(t.matchUpFilters||(t.matchUpFilters={}),t.matchUpFilters?.eventIds&&t.matchUpFilters.eventIds.length?t.matchUpFilters.eventIds=t.matchUpFilters.eventIds.filter(v=>I.eventIds.includes(v)):t.matchUpFilters.eventIds=I.eventIds),I?.scheduledDates?.length&&(t.matchUpFilters||(t.matchUpFilters={}),t.matchUpFilters.scheduledDates&&t.matchUpFilters.scheduledDates.length?t.matchUpFilters.scheduledDates=t.matchUpFilters.scheduledDates.filter(v=>I.scheduledDates.includes(v)):t.matchUpFilters.scheduledDates=I.scheduledDates),a&&(t.matchUpFilters||(t.matchUpFilters={}),t.matchUpFilters?.excludeMatchUpStatuses?.length?t.matchUpFilters.excludeMatchUpStatuses.includes(he)||t.matchUpFilters.excludeMatchUpStatuses.push(he):t.matchUpFilters.excludeMatchUpStatuses=[he]);let{completedMatchUps:y,upcomingMatchUps:E,pendingMatchUps:P,groupInfo:A,mappedParticipants:U}=Zp({...t,matchUpFilters:t.matchUpFilters,contextFilters:t.contextFilters}),N=[...E??[],...P??[]];T&&(!S?.length||Object.keys(T).length)&&(N=N.filter(v=>{let{drawId:O,structureId:x,stage:F}=v;if(!T?.[O]?.publishingDetail?.published)return!1;let w=Object.keys(T[O].stageDetails??{});if(w.length){let G=w.filter(H=>!T[O].stageDetails[H].published),k=w.filter(H=>T[O].stageDetails[H].published);return G.length&&G.includes(F)?!1:k.length&&k.includes(F)?!0:G.length&&!G.includes(F)&&!k.length}let L=Object.keys(T[O].structureDetails??{});if(L.length){let G=L.filter(H=>!T[O].structureDetails[H].published),k=L.filter(H=>T[O].structureDetails[H].published);return G.length&&G.includes(x)?!1:k.length&&k.includes(x)?!0:G.length&&!G.includes(x)&&!k.length}return!0}));let D=i?ul({matchUps:N,schedulingProfile:o}):N,M=e?.map(v=>{let O=b(v);return{surfaceCategory:v?.surfaceCategory??"",matchUps:O,...v}}),R={completedMatchUps:a?h:y,mappedParticipants:t.hydrateParticipants?void 0:U,dateMatchUps:D,courtsData:M,groupInfo:A,venues:r};if(p){let{rows:v,courtPrefix:O}=sl({minRowsCount:m,courtsData:M});R.courtPrefix=O,R.rows=v}return{...R,...C};function b({courtId:v}){let x=(s?D.concat(y??[]):D).filter(F=>F.schedule?.courtId===v||F.schedule?.allocatedCourts?.map(({courtId:w})=>w).includes(v));return f?ul({matchUps:x,schedulingProfile:o}):x}}function dl({tournamentRecords:t,tournamentId:e}){if(typeof t!="object"||!Object.keys(t).length)return{error:Lt};let r=Object.keys(t).filter(o=>!e||o===e),n;return r.forEach(o=>{let i=t[o],{matchUpDailyLimits:s}=QV({tournamentRecord:i});n=s}),{matchUpDailyLimits:n}}function QV(t){let e=et(t,[{[ne]:!0}]);if(e.error)return e;let{tournamentRecord:r}=t,{policy:n}=ni({policyType:Mo,tournamentRecord:r}),{extension:o}=mt({element:r,name:su}),i=o?.value?.dailyLimits,s=n?.defaultDailyLimits;return{matchUpDailyLimits:i||s}}function ly(t){let{matchUps:e}=t,{singlesForDoubles:r,tournamentRecord:n,drawDefinition:o,excludeMargin:i,exclusionRule:s,zoneDoubling:a,matchUpType:c,scaleName:u,eventId:p,zonePct:m,drawId:d,event:l}=t;if(!n&&!e)return{error:$};if(c&&![kt,xt].includes(c))return{error:V,info:{matchUpType:c}};if(e&&!Vr(e))return{error:V,context:{matchUps:e}};let f=we[u],g=f?.ascending??t.ascending??!1,I=f?.accessor??t.valueAccessor,h=Array.isArray(f?.range)?Math.abs(f.range[0]-f.range[1]):0,S=It(m)&&h?(m??0/100)*h:t.zoneMargin??h,T={withScaleValues:!0,withCompetitiveness:!0},y={matchUpTypes:c?[c]:[kt,xt]},E=n?.participants;e?.[0]?.hasContext?d?e=e.filter(v=>v.drawId===d):p&&(e=e.filter(v=>v.eventId===p)):e===void 0&&(e=d&&!o&&[]||!d&&p&&!l&&[]||d&&ir({inContext:!0,drawDefinition:o,contextFilters:y,contextProfile:T,participants:E})?.matchUps||!d&&p&&Xn({inContext:!0,contextFilters:y,contextProfile:T,participants:E,event:l})?.matchUps||ye({tournamentRecord:n,contextFilters:y,contextProfile:T})?.matchUps||[]),c&&(e=e.filter(v=>v.matchUpType===c));let P=e.filter(({winningSide:v,score:O,sides:x,matchUpStatus:F})=>![nr,Rt,bt,uu,vr].includes(F??"")&&Ie({score:O})&&x?.length===2&&v),A=JV({matchUps:P,excludeMargin:i,exclusionRule:s,valueAccessor:I,ascending:g,scaleName:u}),U=!a||de(kt)(c)?S:(S||0)*2,N=S?P.map(({competitiveProfile:v,matchUpType:O,score:x,sides:F})=>{let w=J_({singlesForDoubles:r,valueAccessor:I,matchUpType:O,scaleName:u,sides:F}),L=Math.abs(w[0].value-w[1].value);return{competitiveness:v?.competitiveness,valuesGap:L,score:x}}).filter(({valuesGap:v})=>v<=U):[],D=XV({zoneData:N}),M=D&&[].concat(Object.values(D)).flat().length,R=M&&Object.assign({},...Object.keys(D).map(v=>({[v]:Math.round(1e4*D[v].length/M)/100}))),b=P.length-(N?.length||0);return{...C,relevantMatchUps:P,zoneDistribution:R,zoneData:N,accuracy:A,nonZone:b}}function XV({zoneData:t}){let e={[ed]:[],[uc]:[],[pc]:[]};for(let r of t){let{competitiveness:n,score:o,valuesGap:i}=r;e[n]&&e[n].push({score:o,valuesGap:i})}return e}function J_({singlesForDoubles:t,exclusionRule:e,valueAccessor:r,matchUpType:n,scaleName:o,sides:i}){let s=e?.range.sort(),a=c=>{let u=c?.[e?.valueAccessor];return{exclude:e&&u>=s[0]&&u<=s[1],exclusionValue:u}};return i.sort((c,u)=>c.sideNumber-u.sideNumber).map(({participant:c})=>{let u=[],p=c?.individualParticipants;if(p?.length){let m=[],d=0;for(let l of p){let{scaleValue:f,value:g}=X_({singlesForDoubles:t,valueAccessor:r,participant:l,matchUpType:n,scaleName:o}),{exclude:I,exclusionValue:h}=a(f);I&&u.push(h),m.push(f),g&&!isNaN(d)?d+=g:d=void 0}return{participantName:c.participantName,exclusionValues:u,scaleValues:m,value:d}}else if(c){let{scaleValue:m,value:d}=X_({singlesForDoubles:t,valueAccessor:r,matchUpType:n,participant:c,scaleName:o}),{exclude:l,exclusionValue:f}=a(m);return l&&u.push(f),{participantName:c.participantName,exclusionValues:u,scaleValue:m,value:d}}else return{}})}function X_({singlesForDoubles:t,valueAccessor:e,matchUpType:r,participant:n,scaleName:o}){let i=t?kt:r,s=n?.rankings?.[i]?.find(p=>p.scaleName===o),c=(n?.ratings?.[i]?.find(p=>p.scaleName===o)||s)?.scaleValue,u=e?c?.[e]:c;return{scaleValue:c,value:u}}function JV({excludeMargin:t,exclusionRule:e,valueAccessor:r,ascending:n,scaleName:o,matchUps:i}){let s={affirmative:[],negative:[],excluded:[]};for(let u of i){let{matchUpType:p,sides:m,score:d,winningSide:l}=u;if(!l)continue;if(e&&(!e.valueAccessor||!e.range))return{info:"exclusionRule requires valueAccessor and range",error:st};let f=l-1,g=J_({exclusionRule:e,valueAccessor:r,matchUpType:p,scaleName:o,sides:m});if(e){let E=g.map(({exclusionValues:P})=>P).flat();if(E.length){s.excluded.push({scoreString:d?.scoreStringSide1,exclusionValues:E,winningSide:l,sideValues:g});continue}}if(g.filter(E=>![void 0,"",null].includes(E.value)).length<2){s.excluded.push({scoreString:d?.scoreStringSide1,missingValues:!0,winningSide:l,sideValues:g});continue}let I=g[f].value-g[1-f].value,h=parseFloat(t||0),S=h&&Math.abs(I)<h;if(S){s.excluded.push({scoreString:d?.scoreStringSide1,excludeMargin:t,winningSide:l,excludeGap:S,sideValues:g,valuesGap:I});continue}let T=n?I:I*-1,y=l===1?d?.scoreStringSide1:d?.scoreStringSide2;T>0?s.affirmative.push({winningScoreString:y,winningSide:l,sideValues:g,valuesGap:I,score:d}):s.negative.push({winningScoreString:y,winningSide:l,sideValues:g,valuesGap:I,score:d})}let a=s.affirmative.length+s.negative.length,c=a&&s.affirmative.length/a*100;return s.percent=c?Math.round(100*c)/100:0,s}function Ds({collectionDefinitions:t=[],collectionGroups:e=[]}){let r=0,{groupValueNumbers:n}=eT({collectionGroups:e}),o;for(let s of t||[]){let{collectionValueProfiles:a,collectionGroupNumber:c,collectionValue:u,matchUpCount:p,matchUpValue:m,scoreValue:d,setValue:l}=s,f=c&&n.includes(c);if(It(l||d))o=!0;else{if(f)continue;if(typeof u=="number"&&It(u))r+=u;else if(Array.isArray(a)&&a?.length)for(let g of a)r+=g.matchUpValue;else typeof m=="number"&&It(m)&&(r+=(p??0)*m)}}for(let s of e)r+=s.groupValue??0;return o||!r?{aggregateValue:!0,...C}:{valueGoal:Math.floor(r/2)+1,...C}}function fy(t){let{timeStamp:e,schedule:r,matchUp:n}=t,o=et(t,[{[Ln]:!0}]);if(o.error)return o;let{itemValue:i,timeStamp:s}=Yo({timeItems:n?.timeItems||[],itemType:pd});return!r||s&&e&&new Date(s).getTime()>new Date(e).getTime()?{homeParticipantId:i}:r}function gy({matchUps:t,matchUpId:e}){if(!Vr(t))return{error:V};let r=t.find(a=>a.matchUpId===e),{drawId:n,eventId:o,structureId:i,tournamentId:s}=r||{};return{matchUpId:e,drawId:n,eventId:o,structureId:i,tournamentId:s}}function Ns(t,e){if(!ht(t))return{error:V};if(!Array.isArray(e))return{error:V};let r={};for(let{param:n,error:o,attr:i}of e){let s=ZV({params:t,param:n,attr:i,error:o});if(s?.error)return s;r[n]=s}return r}function ZV({params:t,param:e,attr:r,error:n}){if(e===fp&&ht(t.drawDefinition)&&Vt(t.structureId)){let o=(t.drawDefinition.structures??[]).find(({structureId:i})=>i===t.structureId);return!o.length&&n?{error:n}:{structure:o}}if(e===Ln){let o=fN({...t,...r});return o.error&&n?{...o,error:n}:o}return{error:ve,info:{param:e}}}function Iy(t){let{structureId:e,matchUpId:r,event:n}=t,o=t.drawDefinition,i=et(t,[{[ne]:!0},{[Bm]:{[eu]:!1,[ln]:!1,[xh]:!1,[so]:!1}}]);if(i[fn])return i;let a=Ns(t,[{[ss]:Ln,[fn]:st}])?.matchUp;if(r&&a?.error)return a;!o&&a?.drawDefinition&&(o=a?.drawDefinition);let c=a?.structure;if(!c&&e&&!r){if(!o)return{error:sn};let l=at({drawDefinition:o,structureId:e});if(l.error)return l;c=l.structure}let u=c?.matchUpFormat,p=o?.matchUpFormat,m=n?.matchUpFormat,d=a?.matchUp?.matchUpFormat||u||p||m;return{structureDefaultMatchUpFormat:u,eventDefaultMatchUpFormat:m,drawDefaultMatchUpFormat:p,matchUpFormat:d}}function hy({profileBands:t,tournamentRecord:e,matchUps:r}){if(!Vr(r))return{error:eo};let n=!t&&ni({policyType:Ti,tournamentRecord:e}).policy,o=t||n?.profileBands||nd[Ti].profileBands,i=r.filter(({winningSide:d})=>d),s=i.map(cS),a=(d,l)=>{let f=aS(l,o);return d[f]+=1,d},c=uS(s).reduce((d,l)=>a(d,l),{[ed]:0,[uc]:0,[pc]:0,[nS]:0}),u=Object.keys(c).reduce((d,l)=>(c[l]||0)+d,0),p=Object.keys(c).map(d=>{let l=parseFloat((c[d]/u).toFixed(4));return{[d]:l*100}}),m=i.filter(({matchUpStatus:d})=>d===WU).length;return p.push({[WU]:parseFloat((m/u).toFixed(4))*100}),{competitiveBands:Object.assign({},...p),...C}}var{stageOrder:Z_}=ob;function tx(t,e){return t.eventName.localeCompare(e.eventName)||t.eventId.localeCompare(e.eventId)||(Z_[t?.stage]||0)-(Z_[e?.stage]||0)||e.matchUpsCount-t.matchUpsCount||`${t.stageSequence}-${t.roundNumber}-${t.minFinishingSum}`.localeCompare(`${e.stageSequence}-${e.roundNumber}-${e.minFinishingSum}`)}function Sy({excludeScheduleDateProfileRounds:t,excludeScheduledRounds:e,excludeCompletedRounds:r,inContextMatchUps:n,tournamentRecords:o,schedulingProfile:i,tournamentRecord:s,withSplitRounds:a,matchUpFilters:c,scheduleDate:u,withRoundId:p,venueId:m,context:d}){if(n&&!Array.isArray(n||typeof n[0]!="object"))return{error:V,inContextMatchUps:n};if(s&&!o){if(typeof s!="object")return{error:Wa};o={[s.tournamentId]:s}}let l=typeof o!="object"||!Object.keys(o).length;if((m||u||!n||!i&&(t||r||i||a))&&l)return{error:Lt};let g=Object.assign({},...Object.values(o??{}).map(({venues:A=[],tournamentId:U})=>({[U]:A?.map(({venueId:N})=>N)}))),I=Object.values(o??{}).map(({events:A=[],tournamentId:U,startDate:N,endDate:D})=>A.map(M=>({...M,validVenueIds:g[U],startDate:M.startDate??N,endDate:M.endDate??D}))).flat(),{segmentedRounds:h,profileRounds:S}=o&&(t||r||i||a)&&il({tournamentRecords:o,schedulingProfile:i})||{},T=t&&Object.assign({},...S.map(A=>({[A.id]:A}))),y=n||o&&Un({tournamentRecords:o,matchUpFilters:c})?.matchUps||[],E=[],P=y&&Object.values(y.reduce((A,U)=>{let N=Qg(U).id,D=h?.[N],M=[...A[N]?.matchUps??[],U],{containerStructureId:R,stageSequence:b,structureName:v,tournamentId:O,isRoundRobin:x,matchUpType:F,roundNumber:w,roundOffset:L,structureId:G,eventName:k,roundName:H,drawName:W,eventId:q,drawId:Y}=U,B=x?R:G;return{...A,[N]:{id:p?N:void 0,structureId:B,stageSequence:b,segmentsCount:D,structureName:v,tournamentId:O,matchUpType:F,roundNumber:w,roundOffset:L,eventName:k,roundName:H,drawName:W,matchUps:M,eventId:q,drawId:Y}}},{})).map(A=>{let{minFinishingSum:U,winnerFinishingPositionRange:N}=K_(A.matchUps),D=A.segmentsCount;if(D){let w=A.matchUps.length/D;return Ee(A.matchUps.sort((G,k)=>G.roundPosition-k.roundPosition),w).map((G,k)=>{let{unscheduledCount:H,incompleteCount:W,matchUpsCount:q,isScheduled:Y,isComplete:B,byeCount:K}=EN(G),X=AN({matchUps:A.matchUps,tournamentRecords:o,events:I,round:A});return nt({...A,...d,roundSegment:{segmentsCount:D,segmentNumber:k+1},winnerFinishingPositionRange:N,unscheduledCount:H,incompleteCount:W,minFinishingSum:U,matchUpsCount:q,isScheduled:Y,roundTiming:X,isComplete:B,byeCount:K,matchUps:G})})}let{unscheduledCount:M,incompleteCount:R,matchUpsCount:b,isScheduled:v,isComplete:O,byeCount:x}=EN(A.matchUps),F=AN({matchUps:A.matchUps,tournamentRecords:o,events:I,round:A});return nt({...A,...d,winnerFinishingPositionRange:N,unscheduledCount:M,incompleteCount:R,minFinishingSum:U,matchUpsCount:b,isScheduled:v,roundTiming:F,isComplete:O,byeCount:x})}).flat().filter(A=>{if(t){let G=Pt(t),k=p?A.id:Qg(A).id;if(G&&T[k]&&Pt(T[k].scheduleDate)===G)return!1}let{isComplete:U,isScheduled:N}=A,D=!r||!U,M=!e||!N,R=m||u?I?.find(({eventId:G})=>G===A.eventId):void 0,b=R?.startDate??s?.startDate,v=R?.endDate??s?.endDate,O=!u||!b||new Date(u)>=new Date(b),x=!u||!v||new Date(u)<=new Date(v),F=O&&x,w=!m||R?.validVenueIds.includes(m),L=D&&M&&w&&F;return L||E.push(A),L}).sort(tx)||[];return{...C,rounds:P,excludedRounds:E}}function tm(t){let{matchUp:e,sideNumber:r,setNumber:n,isTiebreakValue:o,isPointValue:i}=t||{},{matchUpFormat:s}=t||{};if(!e)return{error:Tr};s=s||e?.matchUpFormat;let a=Ye(s),c=!!e?.winningSide,u=e.score?.sets,p=u?.length,m=n&&n-1,d=!!u?.find((B,K)=>B.setNumber===n&&K===m),l=u?.filter(B=>B?.winningSide)||[],f=l?.length||0,g=n&&u?.slice(n)||[],I=!!(p&&n&&g?.reduce((B,K)=>(!K||!K.side1Score&&!K.side2Score&&!K.side1TiebreakScore&&!K.side2TiebreakScore&&!K.side1PointScore&&!K.side2PointScore)&&B,!0)),h=n<=p&&u.find(B=>B.setNumber===n),S=h&&Gu({setObject:h,matchUpScoringFormat:a}),{isCompletedSet:T,sideGameScores:y,sideTiebreakScores:E}=S||{},P=!!(h&&!T&&I||n&&n===p+1&&!c),A=[1,2].includes(r),U=A?r-1:0,N=h&&A&&(!o&&!i&&y[U]!==void 0&&y[U]||o&&E[U]!==void 0&&E[U]),D=!!N,M=l?.map(B=>Gu({setObject:B,matchUpScoringFormat:a}).isValidSetOutcome).reduce((B,K)=>B&&K,!0),R=l.reduce((B,K)=>{let{winningSide:X}=K,j=X-1;return B[j]++,B},[0,0]),b=e?.winningSide,v=b&&b-1,O=1-v,x=R[v],F=R[O],w=Math.max(...R),L=yr(R)[w],{bestOf:G,exactly:k}=a??{},H=G&&Math.ceil(G/2)||k||1,W=w===H&&L===1&&R.indexOf(w)+1||void 0,q=x>F&&b===W;return{completedSetsHaveValidOutcomes:M,validMatchUpWinningSide:q,calculatedWinningSide:W,matchUpScoringFormat:a,validMatchUpOutcome:W&&M&&q,isLastSetWithValues:I,completedSetsCount:f,isCompletedMatchUp:c,isValidSideNumber:A,hasExistingValue:D,existingValue:N,isExistingSet:d,isActiveSet:P,...S}}function Ty({participants:t,tournamentAppliedPolicies:e,scheduleVisibilityFilters:r,participantsProfile:n,afterRecoveryTimes:o,policyDefinitions:i,useParticipantMap:s,tournamentRecord:a,usePublishState:c,contextFilters:u,contextContent:p,matchUpFilters:m,participantMap:d,publishStatus:l,contextProfile:f,drawDefinition:g,nextMatchUps:I,tournamentId:h,inContext:S,context:T,event:y}){let{eventId:E,eventName:P,endDate:A,eventType:U,category:N,gender:D}=y??{},M={...T,...nt({surfaceCategory:y?.surfaceCategory??a?.surfaceCategory,indoorOutDoor:y?.indoorOutdoor??a?.indoorOutdoor,endDate:A??y?.endDate??a?.endDate,tournamentId:h??a?.tournamentId,eventName:P,eventType:U,category:N,eventId:E,gender:D})},R;return!t?.length&&a&&({participants:t,participantMap:d,groupInfo:R}=Wo({participantsProfile:n,policyDefinitions:i,useParticipantMap:s,tournamentRecord:a,contextProfile:f,inContext:S})),y&&f&&!p&&(p=Qn({policyDefinitions:i,tournamentRecord:a,contextProfile:f,drawDefinition:g,event:y})),{...Ys({context:M,tournamentAppliedPolicies:e,scheduleVisibilityFilters:r,tournamentParticipants:t,participantsProfile:n,afterRecoveryTimes:o,policyDefinitions:i,tournamentRecord:a,usePublishState:c,participantMap:d,contextContent:p,contextFilters:u,matchUpFilters:m,publishStatus:l,contextProfile:f,drawDefinition:g,nextMatchUps:I,inContext:S,event:y}),groupInfo:R}}var CN={};Jt(CN,{getCompetitionVenues:()=>Qp,getCourts:()=>yy,getVenuesAndCourts:()=>Uo,publicFindVenue:()=>hS});function yy({tournamentRecord:t,venueId:e,venueIds:r}){return t?{courts:(t.venues||[]).filter(o=>e?o.venueId===e:r?r.includes(o.venueId):!0).map(o=>{let{venueId:i}=o,s=J(o.courts||[]);return s.forEach(a=>Object.assign(a,{venueId:i})),s}).flat()}:{error:$}}var bN={};Jt(bN,{categoryCanContain:()=>$c,getCategoryAgeDetails:()=>Fs,getEvent:()=>Uy,getEventProperties:()=>Ay,getEventStructures:()=>Ag,getEventTimeItem:()=>gu,getEvents:()=>Ey,getFlightProfile:()=>Ht,getScaledEntries:()=>ea});function Ay({tournamentRecord:t,event:e}){if(!t)return{error:$};if(!e)return{error:Ot};let r=e.entries||[],n=t.participants||[],o=e.category?.categoryName||e.category?.ageCategoryCode,{eventType:i}=e,s=r.map(d=>d.participantId),a=n.filter(d=>s.includes(d.participantId)),c,u,p;return{entryScaleAttributes:a.map(d=>{let{participantId:l,participantName:f,name:g}=d,I={scaleType:ag,eventType:i,scaleName:o},h=Ao({participant:d,scaleAttributes:I})?.scaleItem?.scaleValue;I={scaleType:KU,eventType:i,scaleName:o};let S=Ao({participant:d,scaleAttributes:I})?.scaleItem?.scaleValue;I={scaleType:$U,eventType:i,scaleName:o};let T=Ao({participant:d,scaleAttributes:I})?.scaleItem?.scaleValue;return c=!!(c||h),u=!!(u||S),p=!!(p||T),{participantId:l,participantName:f||g,seed:h,ranking:S,rating:T}}),hasSeededParticipants:c,hasRankedParticipants:u,hasRatedParticipants:p}}function Ey({tournamentRecord:t,withScaleValues:e,scaleEventType:r,inContext:n,eventIds:o,drawIds:i,context:s}){if(!t)return{error:$};let{tournamentId:a}=t,c=(t.events??[]).filter(({eventId:p})=>!o||Array.isArray(o)&&o.includes(p)).map(p=>{let m=p.drawDefinitions?.map(cu);if(i?.length&&!jt(i,m).length)return;let d=J(p);return n&&Object.assign(d,{tournamentId:a}),s&&Object.assign(d,s),d}).filter(Boolean),u={};if(e){let p=Gt({withScaleValues:!0,tournamentRecord:t}).participantMap,m=d=>d.reduce((l,f)=>l+parseFloat(f),0);for(let d of c){let l=r??d.eventType,f=d.eventId;u[f]||(u[f]={ratingsStats:{},ratings:{},ranking:{},draws:{}});let I=(d.entries??[]).filter(({entryStatus:A})=>Qr.includes(A)).map(St),h=A=>{if(A?.ratings?.[l])for(let U of A?.ratings?.[l]??[]){let N=U.scaleName;u[f].ratings[N]||(u[f].ratings[N]=[]);let D=we[N]?.accessor;if(D){let M=parseFloat(U.scaleValue?.[D]);M&&u[f].ratings[N].push(M)}}if(A?.rankings?.[l])for(let U of A?.rankings?.[l]??[]){let N=U.scaleName;u[f].ranking[N]||(u[f].ranking[N]=[]),U.scaleValue&&u[f].ranking[N].push(U.scaleValue)}};for(let A of I){let U=p?.[A]?.participant;if(U?.participantType!==At)for(let N of U?.individualParticipantIds??[]){let D=p?.[N]?.participant;h(D)}else h(U)}let S=u[f].ratings;for(let A of Object.keys(S)){let U=S[A];if(!U.length)continue;let N=NA(U)?.toFixed(2);u[f].ratingsStats[A]={avg:parseFloat((m(U)/U.length).toFixed(2)),median:N?parseFloat(N):void 0,max:Math.max(...U),min:Math.min(...U)}}let T=(A,U)=>{let N=D=>{if(u[f].draws?.[A]&&D?.ratings?.[l])for(let M of D?.ratings?.[l]??[]){let R=M.scaleName;u[f].draws[A]?.ratings[R]||(u[f].draws[A].ratings[R]=[]);let b=we[R]?.accessor;if(b){let v=parseFloat(M.scaleValue?.[b]);v&&u[f].draws[A].ratings[R].push(v)}}if(u[f].draws?.[A]&&D?.rankings?.[l])for(let M of D?.rankings?.[l]??[]){let R=M.scaleName;u[f].draws[A]?.ranking[R]||(u[f].draws[A].ranking[R]=[]);let b=M.scaleValue;b&&u[f].draws[A].ranking[R].push(b)}};for(let D of U.filter(Boolean)){let M=p?.[D]?.participant;if(M?.participantType!==At)for(let R of M?.individualParticipantIds??[]){let b=p?.[R]?.participant;N(b)}else N(M)}},y=[],E=A=>i?.length&&i.includes(A)||y.includes(A);for(let A of d.drawDefinitions??[]){let U=A.drawId;if(E(U))continue;let N=Ci({drawDefinition:A}).assignedParticipantIds??[];u[f].draws[U]||(u[f].draws[U]={ratingsStats:{},ratings:{},ranking:{}}),y.push(U),T(U,N)}let P=Ht({event:d}).flightProfile;for(let A of P?.flights??[]){let U=A.drawId;if(E(U))continue;let N=A.drawEntries.map(St);T(U,N)}for(let A of y){let U=u[f].draws[A].ratings;for(let N of Object.keys(U)){let D=U[N];if(!D.length)continue;let M=NA(D)?.toFixed(2);u[f].draws[A].ratingsStats[N]={avg:parseFloat((m(D)/D.length).toFixed(2)),median:M?parseFloat(M):void 0,max:Math.max(...D),min:Math.min(...D)}}}}}return nt({eventScaleValues:u,events:c,...C})}function Uy({tournamentRecord:t,drawDefinition:e,context:r,event:n}){if(!t)return{error:$};if(!n)return{error:Ot};let o=J(n);r&&Object.assign(o,r);let i=e&&o.drawDefinitions?.find(({drawId:s})=>e.drawId===s);return nt({drawDefinition:i,event:o})}function ex(t){let e="validateAndDeriveDrawValues",{appliedPolicies:r,policyDefinitions:n}=r1(t),o=n1({...t,policyDefinitions:n,appliedPolicies:r}),i=e1(t),s=o1({...t,consideredEntries:i,appliedPolicies:r});if(s?.error)return _({result:s,stack:e});let a=i1({...t,consideredEntries:i}),c=t1({...t,appliedPolicies:r,policyDefinitions:n,drawSize:a});if(c.error)return _({result:c,stack:e});let u=c.drawType;if(isNaN(a)&&u!==$r)return _({result:{error:qa},stack:e});let p=n?.[Fn]??r?.[Fn],m=t.seedingProfile??p?.seedingProfile?.drawTypes?.[u??""]??p?.seedingProfile;t.seedingProfile&&(n[Fn]||(n[Fn]={...Kg[Fn]}),n[Fn].seedingProfile=m);let d=s1({...t,drawType:u});return d?.error?_({result:d,stack:e}):{drawSize:a,drawType:u,enforceGender:o,seedingProfile:m,appliedPolicies:r,policyDefinitions:n}}function t1(t){let{policyDefinitions:e,appliedPolicies:r,enforceMinimumDrawSize:n=!0,drawSize:o}=t,i=t.drawTypeCoercion??xu({drawType:t.drawType,policyDefinitions:e,appliedPolicies:r}),s=NT({drawType:t.drawType,enforceMinimumDrawSize:n,drawTypeCoercion:i,drawSize:o});return s.error?s:{drawType:s.drawType}}function ON(t){return t?.filter(e=>e.entryStatus&&[...Qr,id].includes(e.entryStatus))}function e1({considerEventEntries:t=!0,drawEntries:e,eventEntries:r,qualifyingOnly:n}){return(n&&[]||ON(e)||(t?r:[])).filter(({entryStage:o})=>!o||o===rt)}function r1(t){let{tournamentRecord:e,event:r}=t,n=Tt({tournamentRecord:e,event:r}).appliedPolicies??{},o=J(t.policyDefinitions??{},!1,!0);return{appliedPolicies:n,policyDefinitions:o}}function n1({enforceGender:t,policyDefinitions:e,appliedPolicies:r}){return t??e?.[rr]?.participants?.enforceGender??r?.[rr]?.participants?.enforceGender}function o1(t){let{consideredEntries:e,appliedPolicies:r,policyDefinitions:n,enforceGender:o,participantMap:i,participants:s,event:a}=t;return a&&s&&wd({consideredEntries:e,policyDefinitions:n,appliedPolicies:r,participantMap:i,enforceGender:o,participants:s,event:a})}function i1(t){return!t.drawSize&&t.consideredEntries.length&&![$r,Zc,fa,Nn,So].includes(t.drawType??"")&&rs(t.consideredEntries.length)||t.drawSize&&dt(t.drawSize)||!1}function s1(t){let{tournamentRecord:e,event:r,ignoreAllowedDrawTypes:n,drawType:o}=t,i=!n&&e&&Qd({tournamentRecord:e,categoryType:r?.category?.categoryType,categoryName:r?.category?.categoryName});return i?.length&&!i.includes(o)?{error:Um}:{...C}}function wa(t){let{voluntaryConsolation:e,tournamentRecord:r,event:n}=t,o="generateDrawDefinition",{participants:i,participantMap:s}=Gt({withIndividualParticipants:!0,convertExtensions:!0,internalUse:!0,tournamentRecord:r}),a=ON(n?.entries)??[],c=ex({...t,participantMap:s,participants:i,eventEntries:a});if(c.error)return _({result:c,stack:o});let{appliedPolicies:u,policyDefinitions:p,drawSize:m,drawType:d,enforceGender:l,seedingProfile:f}=c,g=n?.eventType,I=t.matchUpType??g,h=N_({...t,enforceGender:l,eventType:g,matchUpType:I});if(h.error)return _({result:h,stack:o});let{matchUpFormat:S,tieFormat:T}=h;if(t.drawId&&typeof t.drawId!="string")return _({result:{error:V},stack:o});let E=V_({...t,policyDefinitions:p,tournamentRecord:r,appliedPolicies:u,matchUpFormat:S,seedingProfile:f,participants:i,eventEntries:a,matchUpType:I,tieFormat:T,drawSize:m,drawType:d,event:n});if(E.error)return _({result:E,stack:o});let{existingDrawDefinition:P,positioningReports:A,drawDefinition:U,structureId:N,conflicts:D,entries:M}=E;if(!U)return _({result:{error:V},stack:o});let R=B_({...t,existingDrawDefinition:P,positioningReports:A,appliedPolicies:u,drawDefinition:U,seedingProfile:f,participants:i,structureId:N,entries:M,params:t,stack:o});if(R.error)return R;let{qualifyingConflicts:b}=R;return U.drawName=t.drawName??(d&&Qe(d)),m&&typeof e=="object"&&m>=4&&gg({...e,drawDefinition:U,matchUpType:I}),{existingDrawDefinition:!!P,qualifyingConflicts:b,positioningReports:A,drawDefinition:U,structureId:N,...C,conflicts:D}}function Py({scaleAttributes:t,scaledEntries:e,stageEntries:r,seedsCount:n,scaleName:o}){if(!t)return{error:st,info:"missing scaleAttributes"};let i=Object.assign({},...(e||[]).slice(0,n).map(({participantId:c},u)=>({[c]:u+1})));o=o||t.scaleName;let s=new Date().toISOString();return{scaleItemsWithParticipantIds:r.map(({participantId:c})=>({scaleItems:[{scaleValue:i[c],eventType:t.eventType,scaleType:To,scaleName:o,scaleDate:s}],participantId:c}))}}function rx({tournamentRecord:t,drawDefinition:e,policyDefinitions:r,scaleAttributes:n,scaleName:o,drawSize:i,drawId:s,event:a,stage:c,sortDescending:u,scaleSortMethod:p}){let m=al({policyDefinitions:r,drawDefinition:e,drawSize:i,drawId:s,event:a,stage:c});if(m.error)return m;let{entries:d,seedsCount:l,stageEntries:f}=m;if(!f||!l)return{error:V};let g=ea({tournamentRecord:t,scaleAttributes:n,scaleSortMethod:p,sortDescending:u,entries:d,stage:c}).scaledEntries??[],{scaleItemsWithParticipantIds:I}=Py({scaleAttributes:n,scaledEntries:g,stageEntries:f,seedsCount:l,scaleName:o});return{scaleItemsWithParticipantIds:I}}var VN={};Jt(VN,{addDrawEntries:()=>mg,addEventEntries:()=>Vn,addEventEntryPairs:()=>FN,destroyPairEntries:()=>gP,destroyPairEntry:()=>fg,getEntriesAndSeedsCount:()=>al,getMaxEntryPosition:()=>sy,modifyEntriesStatus:()=>fd,modifyEventEntries:()=>kN,mutate:()=>GN,promoteAlternate:()=>wN,promoteAlternates:()=>Ny,query:()=>PN,removeDrawEntries:()=>LN,removeEventEntries:()=>hc,setEntryPosition:()=>Dy,setEntryPositions:()=>xN});var GN={};Jt(GN,{addDrawEntries:()=>mg,addEventEntries:()=>Vn,addEventEntryPairs:()=>FN,destroyPairEntries:()=>gP,destroyPairEntry:()=>fg,modifyEntriesStatus:()=>fd,modifyEventEntries:()=>kN,promoteAlternate:()=>wN,promoteAlternates:()=>Ny,removeDrawEntries:()=>LN,removeEventEntries:()=>hc,setEntryPosition:()=>Dy,setEntryPositions:()=>xN});function Dy({tournamentRecord:t,drawDefinition:e,participantId:r,entryPosition:n,skipRefresh:o,event:i}){let s="setEntryPositions";if(!t)return{error:$};if(!r)return _({result:{error:ie},stack:s});if(n!==void 0&&!Number.isSafeInteger(n))return{error:V,entryPosition:n};(i?.entries||[]).forEach(c=>{c.participantId===r&&(c.entryPosition=n)}),(e?.entries||[]).forEach(c=>{c.participantId===r&&(c.entryPosition=n)});let a=c=>{c.entries.forEach(u=>{u.entryPosition===n&&u.participantId!==r&&(u.entryPosition+=.1)})};return o||(i?.entries&&(a(i),i.entries=Jn({entries:i.entries})),e?.entries&&(a(e),e.entries=Jn({entries:e.entries}))),{...C}}function xN({tournamentRecord:t,entryPositions:e,drawDefinition:r,event:n}){if(!t)return{error:$};if(!Array.isArray(e))return{error:V};for(let o of e){let{participantId:i,entryPosition:s}=o,a=Dy({skipRefresh:!0,tournamentRecord:t,drawDefinition:r,participantId:i,entryPosition:s,event:n});if(a.error)return a}return n?.entries&&(n.entries=Jn({entries:n.entries})),r?.entries&&(r.entries=Jn({entries:r.entries})),{...C}}function wN(t){let{participantId:e}=t;return e&&typeof e!="string"?{error:V,participantId:e}:Ny({...t,participantIds:[e].filter(Boolean)})}function Ny({tournamentRecord:t,drawDefinition:e,participantIds:r,stageSequence:n,stage:o=rt,eventId:i,event:s}){if(!t)return{error:$};if(!Array.isArray(r))return{error:V,participantIds:r};if(!s)return{error:Ot};let a="promoteAlternates";if(s){let c=nx({element:s,participantIds:r,stageSequence:n,stage:o});if(c.error)return c}if(e){let c=nx({element:e,participantIds:r,stageSequence:n,stage:o});if(c.error)return i?_({context:{drawPromotionError:c.error,drawId:e.drawId},result:{...C},stack:a}):c}return{...C}}function nx({participantIds:t,stageSequence:e,element:r,stage:n}){let o=(r.entries||[]).filter(m=>m.entryStatus===rn),i=(r.entries||[]).filter(m=>t.includes(m.participantId)),s=o.reduce((m,d)=>{let{entryPosition:l}=d;return isNaN(l)&&m||(!m||l<m.entryPosition)&&d||m},void 0),a=i.length?i:[s].filter(Boolean);if(!a?.length)return{error:YI};let c=a.filter(({entryStatus:m})=>m!==rn);if(c.length)return{error:Zl,invalidEntryStatus:c};let u=a.filter(({entryStage:m})=>m&&m!==n);if(u.length)return{error:NC,invalidStage:u};let p=e&&a.filter(m=>m.stageSequence!==e);if(p?.length)return{error:MC,invalidStageSequence:p};for(let m of a){m.entryStatus=kr;let d=m?.entryPosition;isNaN(d)||r.entries.forEach(f=>{f.entryStatus===rn&&f.entryPosition>d&&(f.entryPosition=f.entryPosition-1)});let l=Math.max(...r.entries.filter(f=>f.entryStatus===kr&&!isNaN(f.entryPosition)).map(({entryPosition:f})=>dt(f||0)),0);m.entryPosition=l||0}return{...C}}function LN({autoEntryPositions:t=!0,participantIds:e,drawDefinition:r,drawId:n,stages:o,event:i}){if(!i)return{error:Ot};if(!n)return{error:sn};if(!e?.length)return{error:Do};let s=Ci({drawDefinition:r,stages:o}).assignedParticipantIds??[];if(ke(s,e))return{error:Os};let c=m=>{let d=m.participantId;return!e.includes(d)},{flightProfile:u}=Ht({event:i}),p=u?.flights?.find(m=>m.drawId===n);return p?.drawEntries&&(p.drawEntries=p.drawEntries.filter(c),t&&(p.drawEntries=Jn({entries:p.drawEntries}))),r?.entries&&(r.entries=r.entries.filter(c),t&&(r.entries=Jn({entries:r.entries}))),{...C}}function vn(t){let e="addParticipant",{allowDuplicateParticipantIdPairs:r,returnParticipant:n,disableNotice:o,pairOverride:i,participant:s}=t,a=t.tournamentId?t.tournamentRecords?.[t.tournamentId]:t.tournamentRecord??(t.activeTournamentId&&t.tournamentRecords?.[t.activeTournamentId]);if(!a)return{error:$};if(!s)return _({result:{error:Fi},stack:e});s.participantId||(s.participantId=Mt()),a.participants||(a.participants=[]);let{participantId:c,individualParticipantIds:u}=s;if(a.participants.reduce((I,h)=>h.participantId===c||I,!1))return{error:lE};let{participantType:m,participantRole:d}=s;if(!m||!Object.keys(lu).includes(m))return{error:An,participantType:m};if(!d)return{error:mE};let l=a.participants||[],f=l.filter(I=>I.participantType===At).map(I=>I.participantId);if(m!==At&&s.person)return{error:V,person:s.person};if(u&&!Array.isArray(u))return{error:V,individualParticipantIds:u};if(m===ft){if(s.person)return{error:V,person:s.person};if(s.individualParticipantIds){if(s.individualParticipantIds.length!==2&&!i)return _({info:"PAIR must be 2 individualParticipantIds",result:{error:wr},stack:e});{let S=l.filter(y=>y.participantType===At).map(y=>y.participantId);if(!Array.isArray(s.individualParticipantIds))return _({result:{error:wr},stack:e});if(!s.individualParticipantIds.reduce((y,E)=>S.includes(E)&&y,!0))return _({result:{error:wr},stack:e})}}else return _({result:{error:Do},stack:e});let I=l.filter(S=>S.participantType===ft).map(S=>({individualParticipantIds:S.individualParticipantIds,participant:S})),h=s.participantType===ft&&I.find(S=>jt(S.individualParticipantIds,s.individualParticipantIds).length===2);if(h&&!r)return{...C,existingParticipant:!0,participant:n&&J(h.participant)};if(!s.participantName){let S=l.filter(y=>s.individualParticipantIds?.includes(y.participantId)),T=S.map(y=>y.person?.standardFamilyName).filter(Boolean).join("/");S.length===1&&(T+="/Unknown"),s.participantName=T}}else if(m===At){if(!s.person?.standardFamilyName||!s.person?.standardGivenName)return{error:hE};if(!s.participantName){let I=`${s.person.standardFamilyName.toUpperCase()}, ${s.person.standardGivenName}`;s.participantName=I}}else if(m&&[Ft,zr].includes(m)){if(u||(s.individualParticipantIds=[]),s.individualParticipantIds?.length)for(let I of s.individualParticipantIds){if(typeof I!="string")return _({result:{participantId:I,error:V},stack:e});if(!f.includes(I))return _({result:{participantId:I,error:re},stack:e})}}else return{error:An};a.participants.push(s),o||lt({payload:{tournamentId:a.tournamentId,participants:[s]},topic:ei});let g={participant:n&&J(s),...C};return nt(g)}function Sn({allowDuplicateParticipantIdPairs:t,returnParticipants:e,tournamentRecord:r,participants:n=[]}){if(!r)return{error:$};r.participants||(r.participants=[]);let i=r.participants.map(d=>d.participantId)||[];n.forEach(d=>{d.participantId||(d.participantId=Mt())});let s=n.filter(d=>!i.includes(d.participantId)),a=n.filter(d=>i.includes(d.participantId)),c=s.filter(d=>d.participantType===At),u=s.filter(d=>d.participantType!==At),p=c.concat(...u),m=[];if(p.length){for(let l of p){let f=vn({allowDuplicateParticipantIdPairs:t,returnParticipant:!0,disableNotice:!0,tournamentRecord:r,participant:l});if(f.error)return f;f.success&&!f.existingParticipant&&m.push(f.participant)}m.length&&lt({topic:ei,payload:{tournamentId:r.tournamentId,participants:m}});let d={participants:e&&J(m),addedCount:m.length,...C};return a.length&&Object.assign(d,{notAdded:a,info:Zu}),nt(d)}else return{info:"No new participants to add",addedCount:0,...C}}function FN(t){let e=et(t,[{[ne]:!0,[so]:!0}]);if(e.error)return e;let{allowDuplicateParticipantIdPairs:r,entryStatus:n=rn,participantIdPairs:o=[],entryStage:i=rt,tournamentRecord:s,drawDefinition:a,event:c,uuids:u}=t;if(c.eventType!==xt)return{error:jn};let p=[],m=new Map;for(let y of s.participants??[]){let{participantType:E,participantId:P,person:A,individualParticipantIds:U}=y;E===At&&A?.sex?m.set(P,A.sex):E===ft&&U&&p.push(U)}let d=o.filter(y=>{if(y.length!==2)return!0;if(!c.gender||c.gender===Pn)return!1;if(!m.has(y[0])||!m.has(y[1]))return!0;let E=y.map(A=>m.get(A)),P=c.gender===zt&&(E[0]!==zt||E[1]!==zt)||c.gender===oe&&(E[0]!==oe||E[1]!==oe);return c.gender===Ar&&(E.sort(Eu),(E[0]!==oe||E[1]!==zt)&&(P=!0)),P});if(d.length)return{error:wr,invalidParticipantIdPairs:d};let l=o.map(y=>({participantId:u?.pop()??Mt(),participantRole:xe,individualParticipantIds:y,participantType:ft})),f=r?l:l.filter(y=>!p.find(E=>jt(E,y.individualParticipantIds).length===2)),g,I=[];if(f){let y=Sn({allowDuplicateParticipantIdPairs:r,participants:f,returnParticipants:!0,tournamentRecord:s});if(y.error)return y;I=y.participants||[],g=y.info}let h=o.map(y=>{let E=I.find(A=>jt(A.individualParticipantIds,y).length===2);if(E)return E;let{participant:P}=In({tournamentRecord:s,participantIds:y});return P}).map(y=>y.participantId),S=Vn({participantIds:h,tournamentRecord:s,drawDefinition:a,entryStatus:n,entryStage:i,event:c});f.length&&lt({payload:{participants:f},topic:ei});let T=f.map(St);return{...S,info:g,newParticipantIds:T}}function kN({entryStatus:t=kr,unpairedParticipantIds:e=[],participantIdPairs:r=[],entryStage:n=rt,tournamentRecord:o,event:i}){if(!o)return{error:$};if(!i)return{error:Ot};let s=o.participants??[],a=s.filter(h=>h.participantType===At).map(h=>h.participantId),u=e.concat(...r).flat(1/0).filter(h=>!a.includes(h));if(u.length)return{error:wr,invalidParticipantIds:u};let p=r.filter(h=>h.length!==2);if(p.length)return{error:wr,invalidParticipantIdPairs:p};let m=s.filter(h=>h.participantType===ft).map(h=>h.individualParticipantIds),l=r.filter(h=>!m.find(S=>jt(S,h).length===2)).map(h=>({participantType:ft,participantRole:xe,individualParticipantIds:h})),f=Sn({participants:l,tournamentRecord:o});if(f.error)return f;let g=r.map(h=>{let{participant:S}=In({tournamentRecord:o,participantIds:h});return S}).map(h=>({participantId:h,entryStatus:t,entryStage:n})),I=e.map(h=>({entryStatus:Gr,participantId:h,entryStage:n}));return i.entries=(i.entries??[]).filter(h=>h.entryStage===n),i.entries=i.entries.concat(...g,...I),{...C}}var ZN={};Jt(ZN,{addDrawDefinition:()=>vc,addEvent:()=>na,addFlight:()=>rm,assignSeedPositions:()=>KN,attachFlightProfile:()=>rI,categoryCanContain:()=>$c,deleteDrawDefinitions:()=>em,deleteEvents:()=>QN,deleteFlightAndFlightDraw:()=>qN,deleteFlightProfileAndFlightDraws:()=>jN,generate:()=>HN,generateEventsFromTieFormat:()=>BN,getCategoryAgeDetails:()=>Fs,getEvent:()=>Uy,getEventProperties:()=>Ay,getEventStructures:()=>Ag,getEventTimeItem:()=>gu,getEvents:()=>Ey,getFlightProfile:()=>Ht,getScaledEntries:()=>ea,modifyEvent:()=>XN,modifyEventMatchUpFormatTiming:()=>YN,modifyPairAssignment:()=>$N,mutate:()=>JN,query:()=>bN,refreshEventDrawOrder:()=>eI,removeEventMatchUpFormatTiming:()=>ll,removeScaleValues:()=>nI,removeSeeding:()=>zN,setEventDates:()=>Zg,setEventDisplay:()=>fl,setEventEndDate:()=>Oy,setEventStartDate:()=>vy,updateDrawIdsOrder:()=>tI,validateCategory:()=>qc});var HN={};Jt(HN,{generateEventsFromTieFormat:()=>BN});function ox({tournamentId:t,event:e}){return e?(lt({payload:{tournamentId:t,event:e},key:e.eventId,topic:xU}),{...C}):{error:Ot}}var ix={collectionDefinitions:[{collectionName:"Doubles",matchUpCount:3,matchUpFormat:"SET1-S:8/TB7@7",matchUpType:"DOUBLES",matchUpValue:1},{collectionName:"Singles",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7",matchUpType:"SINGLES",matchUpValue:1}],tieFormatName:"COLLEGE_D3",winCriteria:{valueGoal:5}};var sx={collectionDefinitions:[{collectionName:"Doubles",collectionValue:1,matchUpCount:3,matchUpFormat:"SET1-S:6/TB7",matchUpType:"DOUBLES"},{collectionName:"Singles",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7",matchUpType:"SINGLES",matchUpValue:1}],tieFormatName:"COLLEGE_DEFAULT",winCriteria:{valueGoal:5}};var ax={collectionDefinitions:[{collectionName:"Doubles",matchUpCount:3,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1},{collectionName:"Singles",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7",matchUpType:"SINGLES",matchUpValue:1}],tieFormatName:"COLLEGE_JUCO",winCriteria:{valueGoal:5}};var My={COLLEGE_D3:ix,COLLEGE_DEFAULT:sx,COLLEGE_JUCO:ax,DOMINANT_DUO:Ih,DOMINANT_DUO_MIXED:dh,LAVER_CUP:Ah,TEAM_DOUBLES_3_AGGREGATION:ah,TIME_TENNIS_DUAL:lh,TIME_TENNIS_PRO_CIRCUIT:mh,USTA_BREWER_CUP:fh,USTA_OZAKI_CUP:gh,USTA_COLLEGE:hh,USTA_GOLD_TEAM_CHALLENGE:sh,USTA_INTERSECTIONAL:ph,USTA_LEVEL_1:Sh,USTA_SECTION_BATTLE:uh,USTA_SOUTHERN_LEVEL_5:ch,USTA_TOC:Eh,USTA_WTT_ITT:Th,USTA_ZONAL:yh};function na({suppressNotifications:t,tournamentRecord:e,internalUse:r,event:n}){if(!e)return{error:$};if(e.events||(e.events=[]),!n)return{error:Ot};let{startDate:o,endDate:i}=e;if(!r&&(n.entries?.length||n.drawDefinitions?.length)){let c=nt({drawDefinitions:!!n.drawDefinitions?.length,entries:!!n.entries?.length});return{info:"entries/drawDefinitions cannot exist",error:V,context:c}}let s={eventType:ks,drawDefinitions:[],entries:[],startDate:o,endDate:i,...n};if(n.eventType===br){if(n.tieFormat){let c=ur({tieFormat:n.tieFormat});if(c.error)return c}else if(n.tieFormatName){if(!My[n.tieFormatName])return{context:{tieFormatName:n.tieFormatName},error:V};let c=no({isMock:e?.isMock,namedFormat:n.tieFormatName,event:n});s.tieFormat=c}}if(s.eventId||(s.eventId=Mt()),e.events.reduce((c,u)=>c||u.eventId===s.eventId,void 0))return{error:$A};{let c=s;if(e.events.push(c),!t){let{topics:u}=Lr();if(u.includes(yp)){let d=Xn({event:n}).matchUps??[];vo({tournamentId:e?.tournamentId,eventId:n.eventId,matchUps:d})}let{drawDefinitions:p,...m}=n;for(let d of p||[])Aa({drawDefinition:d});ox({tournamentId:e?.tournamentId,event:m})}return{...C,event:s}}}function BN(t){let e=et(t,[{[Vs]:{[Vm]:!0,[Ch]:!0}},{[ne]:!0}]);if(e.error)return e;let r=t.tieFormat||no({namedFormat:t.tieFormatName}),n=t.uuids||[ih(r.collectionDefinitions.length)],o={[zt]:[],[oe]:[]};if(t.addEntriesFromTeams){let a=t.tournamentRecord.participants?.filter(c=>c.participantType===Er)?.flatMap(c=>c.individualParticipantIds??[]);for(let c of t.tournamentRecord.participants??[])if(a?.includes(c.participantId)){let u=c.person?.sex;u&&[zt,oe].includes(u)&&o[u].push(c.participantId)}}let i=[];for(let s of r.collectionDefinitions??[]){let a=n?.pop()?.toString()||Mt(),c=s.matchUpType,u=s.gender,p={matchUpFormat:s.matchUpFormat,eventName:s.collectionName,category:s.category,gender:u,eventType:c,eventId:a};if(t.addEntriesFromTeams){let m=c===Vo?Gr:t.entryStatus||kr,d=u===Ar?[...o[zt],...o[oe]]:o[u]??[];if(d.length){let l=Vn({participantIds:d,entryStatus:m,event:p});if(l.error)return l}}if(i.push(p),t.addEvents!==!1){let m=na({internalUse:!0,tournamentRecord:t.tournamentRecord,event:p});if(m.error)return m}}return{...C,events:i}}var JN={};Jt(JN,{addDrawDefinition:()=>vc,addEvent:()=>na,addFlight:()=>rm,assignSeedPositions:()=>KN,attachFlightProfile:()=>rI,deleteDrawDefinitions:()=>em,deleteEvents:()=>QN,deleteFlightAndFlightDraw:()=>qN,deleteFlightProfileAndFlightDraws:()=>jN,modifyEvent:()=>XN,modifyEventMatchUpFormatTiming:()=>YN,modifyPairAssignment:()=>$N,refreshEventDrawOrder:()=>eI,removeEventMatchUpFormatTiming:()=>ll,removeScaleValues:()=>nI,removeSeeding:()=>zN,setEventDates:()=>Zg,setEventDisplay:()=>fl,setEventEndDate:()=>Oy,setEventStartDate:()=>vy,updateDrawIdsOrder:()=>tI,validateCategory:()=>qc});function oa({removePriorValues:t=!0,status:e=Rr,statusObject:r,event:n}){if(!ht(r))return{error:V};let o=Xr({event:n,status:e}),i=`${wo}.${Lo}`,s={itemValue:{[e]:{...o,...r}},itemType:i};return Xi({timeItem:s,removePriorValues:t,event:n})}function ia(t){let e=et(t,[{[ne]:!0,[so]:!0},{eventDataParams:!1,[He]:Kr}]);if(e.error)return e;let{includePositionAssignments:r,removePriorValues:n,tournamentRecord:o,status:i=Rr,event:s,drawIdsToRemove:a,drawIdsToAdd:c}=t,{appliedPolicies:u}=Tt({tournamentRecord:o,event:s}),p={...u,...t.policyDefinitions},m=s?.drawDefinitions?.map(({drawId:E})=>E)??[],d=t.drawDetails?Object.keys(t.drawDetails):[],l=d.length?[]:t.drawIds,f=(c??[]).concat(...a??[],...l??[],...d),g=f.filter(E=>!m.includes(E));if(g.length)return _({result:{error:Cr},context:{invalidDrawIds:g}});let I=Xr({event:s,status:i}),h=Object.keys(I?.drawDetails||{}).filter(E=>m.includes(E)).reduce((E,P)=>(E[P]=I.drawDetails[P],E),{});for(let E of m)if((!f.length||f.includes(E))&&(a?.includes(E)||l?.length&&!l.includes(E)?h[E]={...h[E],publishingDetail:{published:!1}}:(c?.includes(E)||l?.includes(E)||!l?.length)&&(h[E]={...h[E],publishingDetail:{published:!0}})),t.drawDetails?.[E]){let P=t.drawDetails[E],A=P.structureDetails??h[E].structureDetails,U=P.stageDetails??h[E].stageDetails??{},{structureIdsToRemove:N=[],structureIdsToAdd:D=[],publishingDetail:M={},stagesToRemove:R=[],stagesToAdd:b=[]}=P;if((D||b)&&(M.published=!0),h[E]={publishingDetail:M,structureDetails:A,stageDetails:U},D.length||N.length){let O=(s?.drawDefinitions?.find(w=>w.drawId===E)?.structures??[]).map(({structureId:w})=>w),F=(D??[]).concat(N??[]).filter(w=>!O.includes(w));if(F.length)return _({result:{error:wt},context:{invalidStructureIds:F}});A=A??{};for(let w of O)N.includes(w)?A[w]={published:!1}:A[w]={published:!0};h[E].structureDetails=A}let v=(s?.drawDefinitions?.find(O=>O.drawId===E)?.structures??[]).map(({stage:O})=>O);if(b.length){for(let O of b)U[O]={published:!0};for(let O of v)U[O]||(U[O]={published:!1})}if(b.length||R.length){for(let O of R)U[O]={published:!1};for(let O of v)U[O]||(U[O]={published:!0})}(b.length||R.length)&&(h[E].stageDetails=U)}oa({statusObject:{drawDetails:h},removePriorValues:n,status:i,event:s});let{topics:S}=Lr(),T=S.includes(zh),y=T||t.returnEventData?nl({includePositionAssignments:r,...t.eventDataParams,usePublishState:!0,tournamentRecord:o,policyDefinitions:p,event:s})?.eventData:void 0;return T&&lt({payload:{eventData:y,tournamentId:o.tournamentId},topic:zh}),{...C,eventData:y}}var WN="deleteDrawDefinitions",Ry="autoSchedulingAudit",Xg="deleteEvents",cx={AUTO_SCHEDULING_AUDIT:Ry,DELETE_EVENTS:Xg,DELETE_DRAW_DEFINITIONS:WN};function em(t){if(!t.tournamentRecord)return{error:$};let e="deleteDrawDefinitions",r=t.drawIds??[],n=t.event,{autoPublish:o=!0,tournamentRecord:i,auditData:s,eventId:a,force:c}=t,{appliedPolicies:u}=Tt({tournamentRecord:i,event:n}),p={...u,...t.policyDefinitions},m=Array.isArray(r)?r[0]:void 0;if(!n){let U=ze({tournamentRecord:i,eventId:a,drawId:m});if(U.error)return U;n=U.event}let d=[],l=[],f=[];if(!n?.drawDefinitions)return _({info:"event has no drawDefinition",result:{...C},stack:e});let g=n.drawDefinitions.map(({drawId:U})=>U);if(r.length||(r=g),r=r.filter(U=>g.includes(U)),!r.length)return _({info:"nothing to do; no matching drawIds in event.",result:{...C},stack:e});let I=J(Ht({event:n}).flightProfile,!1,!0),h=({participantId:U,drawPosition:N,qualifier:D,bye:M})=>({bye:M,qualifier:D,drawPosition:N,participantId:U}),S=c??u?.[tn]?.allowDeletionWithScoresPresent?.drawDefinitions,T=Xr({event:n})??{},y=T.drawIds??(T.drawDetails&&Object.keys(T.drawDetails))??[],E,P=[],A=n.drawDefinitions.filter(U=>{if(r.includes(U.drawId)){let N=ir({event:n,drawDefinition:U})?.matchUps??[];if(N.some(({score:k})=>Ie({score:k}))&&!S)return P.push(U.drawId),!0;let{drawId:M,drawType:R,drawName:b}=U,v=I?.flights?.find(k=>k.drawId===U.drawId);v&&(v.drawEntries=v.drawEntries?.filter(k=>Qr.includes(k.entryStatus))),y.includes(M)&&(y=y.filter(k=>k!==M),E=!0);let O=gn({stageSequence:1,drawDefinition:U,stage:rt})?.structures?.[0],F=(O?Hp({structureId:O.structureId,tournamentRecord:i,drawDefinition:U}):void 0)?.positionAssignments?.map(h),w=gn({stage:ct,drawDefinition:U})?.structures,L=w?.length?w.map(k=>{let H=k.stageSequence;return{positionAssignments:Hp({structureId:k.structureId,tournamentRecord:i,drawDefinition:U})?.positionAssignments.map(h),stageSequence:H}}):void 0,G={action:WN,payload:{drawDefinitions:[U],eventId:a??n?.eventId,auditData:s}};f.push(G),d.push(nt({tournamentId:i.tournamentId,eventId:a??n?.eventId,qualifyingPositionAssignments:L,positionAssignments:F,auditData:s,drawType:R,drawName:b,drawId:M})),N?.forEach(({matchUpId:k})=>l.push(k))}return!r.includes(U.drawId)});if(P.length&&!c)return _({context:{drawIdsWithScoresPresent:P},result:{error:Xa},stack:e});if(n.drawDefinitions=A,I&&Ro({event:n,extension:{name:cn,value:I}}),bc({tournamentRecord:i}),E){let U={};for(let D of y)U[D]=T.drawDetails?.[D]??{published:!0};let N=oa({statusObject:{drawDetails:U},event:n});if(N.error)return{error:N.error}}if(f.length)if(ip(Ai)){let U=i.tournamentId;lt({topic:Ai,payload:{tournamentId:U,detail:f}});let D=(en({element:n,itemType:Sa})?.timeItem?.itemValue||0)+1;to({element:n,timeItem:{itemType:Sa,itemValue:D},removePriorValues:!0})}else p1({appliedPolicies:u,event:n,deletedDrawsDetail:d,auditData:s});if(l.length&&Rn({tournamentId:i?.tournamentId,matchUpIds:l}),r.forEach(U=>Pb({drawId:U})),o&&E){let U=ia({...t.eventDataParams,drawIdsToRemove:r,policyDefinitions:p,tournamentRecord:i,event:n});if(U.error)return{...C,info:U.error}}return{...C}}function p1({appliedPolicies:t,event:e,deletedDrawsDetail:r,auditData:n}){if(t?.audit?.[Sa]===!1)return;let{extension:o}=mt({name:Sa,element:e}),i={...n,deletedDrawsDetail:r},s={value:Array.isArray(o?.value)?o?.value.concat(i):[i],name:Sa};Ut({element:e,extension:s})}function jN({autoPublish:t=!0,tournamentRecord:e,auditData:r,event:n,force:o}){if(!e)return{error:$};if(!n)return{error:Ot};let{flightProfile:i}=Ht({event:n});if(i){let s=i.flights?.map(({drawId:c})=>c).filter(Boolean),a=em({eventId:n.eventId,tournamentRecord:e,autoPublish:t,auditData:r,drawIds:s,event:n,force:o});return a.error?a:Sp({event:n,name:cn})}return{...C}}function Jg(t){let{matchUpFormat:e,recoveryTimes:r,averageTimes:n,tournamentId:o,eventId:i}=t,s=t?.tournamentRecords??(t?.tournamentRecord&&{[t.tournamentRecord.tournamentId]:t.tournamentRecord})??{};if(!Object.keys(s).length)return{error:Lt};let a=Object.keys(s).filter(u=>!o||o===u);if(o&&!a.includes(o))return{error:V};let c;for(let u of a){let p=s[u],{event:m}=ze({tournamentRecord:p,eventId:i});i&&m&&(c=!0);let d=m1({tournamentRecord:p,event:m,matchUpFormat:e,averageTimes:n,recoveryTimes:r});if(d.error)return d}return!i||c?{...C}:{error:jr}}function m1({tournamentRecord:t,recoveryTimes:e,matchUpFormat:r,averageTimes:n,event:o}){if(!t)return{error:$};if(n&&!Array.isArray(n))return{error:V};if(e&&!Array.isArray(e))return{error:V};let i=Ho;if(o){let{extension:s}=mt({element:o,name:i}),a=s?.value||{},c=ux({...a,matchUpFormat:r,averageTimes:n,recoveryTimes:e});Ut({element:o,extension:{name:i,value:c}})}else{let{extension:s}=mt({element:t,name:i}),a=s?.value||{},c=ux({...a,matchUpFormat:r,averageTimes:n,recoveryTimes:e});Ut({extension:{name:i,value:c},element:t})}return{...C}}function ux(t){let{matchUpRecoveryTimes:e=[],matchUpAverageTimes:r=[],matchUpFormat:n}=t,{averageTimes:o,recoveryTimes:i}=t;o=(o||[]).filter(c=>c?.categoryNames?.length||c?.categoryTypes?.length);let s=o?.length&&r.map(c=>c?.matchUpFormatCodes.includes(n)?{...c,matchUpFormatCodes:c.matchUpFormatCodes?.filter(u=>u!==n)}:c).filter(({matchUpFormatCodes:c})=>c?.length).concat({matchUpFormatCodes:[n],averageTimes:o});i=(i||[]).filter(c=>c?.categoryNames?.length||c?.categoryTypes?.length);let a=i?.length&&e.map(c=>c?.matchUpFormatCodes.includes(n)?{...c,matchUpFormatCodes:c.matchUpFormatCodes?.filter(u=>u!==n)}:c).filter(({matchUpFormatCodes:c,averageTimes:u})=>c?.length||u).concat({matchUpFormatCodes:[n],recoveryTimes:i});return{matchUpAverageTimes:s?.length&&s||r,matchUpRecoveryTimes:a?.length&&a||e}}function YN(t){let{tournamentRecord:e,recoveryMinutes:r,averageMinutes:n,matchUpFormat:o,categoryType:i,eventId:s,event:a}=t;if(!e)return{error:$};if(!Dr({matchUpFormat:o}))return{error:V};if(!a)return{error:Ot};let{averageTimes:c=[],recoveryTimes:u=[]}=cl({tournamentRecord:e,matchUpFormat:o,event:a}),p=a.category,m=p?.categoryName||p?.ageCategoryCode||a?.eventId,d={categoryNames:[m],minutes:{}},l={categoryNames:[m],minutes:{}},f=T=>{if(T.categoryTypes?.includes(i)&&console.log("encountered:",{categoryType:i}),!(T.categoryNames?.includes(m)&&(T.categoryNames=T.categoryNames.filter(y=>y!==m),d={minutes:T.minutes,categoryNames:[m]},!T.categoryNames.length)))return T},g=n&&!isNaN(dt(n)),I=r&&!isNaN(dt(r)),h=c.map(f).filter(T=>T?.categoryNames?.length),S=u.map(f).filter(T=>T?.categoryNames?.length);return g&&(Object.assign(d.minutes,{[a?.eventType||kt]:n}),h.push(d)),I&&(Object.assign(l.minutes,{[a?.eventType||kt]:r}),S.push(l)),!g&&!I?{error:V}:Jg({averageTimes:g&&h,recoveryTimes:I&&S,tournamentRecord:e,matchUpFormat:o,eventId:s,event:a})}function ll(t){if(t.event)return px({event:t.event});{t.tournamentRecord&&!t.tournamentRecords&&(t.tournamentRecords={[t.tournamentRecord.tournamentId]:t.tournamentRecord});let e=et(t,[{[Re]:!0,[_h]:!0}]);if(e.error)return e;let{tournamentRecords:r,eventId:n}=t;for(let o of Object.values(r??{})){let{event:i}=ze({tournamentRecord:o,eventId:n});if(i)return px({event:i})}}return{error:jr}}function px({event:t}){return Sp({event:t,name:Ho})}var d1="MON",l1="TUE",f1="WED",g1="THU",I1="FRI",h1="SAT",S1="SUN",Cy={MON:d1,TUE:l1,WED:f1,THU:g1,FRI:I1,SAT:h1,SUN:S1};function by(t){return!Array.isArray(t)||pt(t).length!==t.length?!1:t.every(e=>Object.keys(Cy).includes(e))}function vy({tournamentRecord:t,event:e,startDate:r}){if(!t)return{error:$};if(!e)return{error:Ot};if(!No.test(r))return{error:je};let n=mx(t);if(n.error)return n;let{tournamentStartDate:o,tournamentEndDate:i}=n,s=new Date(Pt(r)).getTime();if(!o||!i||s<o||s>i)return{error:je};let a=e.endDate&&new Date(Pt(e.endDate)).getTime();return a&&s>a&&(e.endDate=r),e.startDate=r,{...C}}function Oy(t){let{tournamentRecord:e,event:r,endDate:n}=t;if(!e)return{error:$};if(!r)return{error:Ot};if(!No.test(n))return{error:je};let o=mx(e);if(o.error)return o;let{tournamentStartDate:i,tournamentEndDate:s}=o,a=new Date(Pt(n)).getTime();if(!i||!s||a<i||a>s)return{error:je};let c=r.startDate&&new Date(Pt(r.startDate)).getTime();return c&&a<c&&(r.startDate=n),r.endDate=n,{...C}}function Zg(t){let e=et(t,[{tournamentRecord:!0,event:!0},{[er]:c=>No.test(c),[Fr]:je,startDate:!1,endDate:!1},{[er]:c=>c.filter(Boolean).every(u=>No.test(u)),[Fr]:je,activeDates:!1},{[er]:by,weekdays:!1}]);if(e.error)return e;let{tournamentRecord:r,weekdays:n,event:o,startDate:i,endDate:s}=t,a=t.activeDates?.filter(Boolean);if(i&&s){let c=new Date(Pt(i)).getTime(),u=new Date(Pt(s)).getTime();if(c>u)return{error:V}}if(a){let c=i||r.startDate,u=s||r.endDate,p=!c||a.every(d=>new Date(d)>=new Date(c)),m=!u||a.every(d=>new Date(d)<=new Date(u));if(!p||!m)return{error:je}}if(i){let c=vy({tournamentRecord:r,event:o,startDate:i});if(c.error)return c}if(s){let c=Oy({tournamentRecord:r,event:o,endDate:s});if(c.error)return c}return a&&(o.activeDates=a),n&&(o.weekdays=n),{...C}}function mx(t){let{startDate:e,endDate:r}=t;return!No.test(e)||!No.test(r)?_({result:{error:aE},context:{startDate:e,endDate:r}}):{tournamentStartDate:new Date(Pt(e)).getTime(),tournamentEndDate:new Date(Pt(r)).getTime()}}function tI({event:t,orderedDrawIdsMap:e}){if(typeof t!="object")return{error:Ot};if(!e)return{error:st,info:"Missing drawIdsOrderMap"};if(typeof e!="object")return{error:V,info:"orderedDrawIdsMap must be an object"};let r=Object.values(e);if(!r.every(i=>!isNaN(i)))return{error:V,info:"drawOrder must be numeric"};if(pt(r).length!==r.length)return{error:V,info:"drawOrder values must be unique"};if(t.drawDefinitions?.length){let i=(t.drawDefinitions||[]).map(({drawId:a})=>a),s=Object.keys(e);if(s?.length&&jt(i,s).length!==i.length)return{error:V,info:"Missing drawIds"};t.drawDefinitions.forEach(a=>{a.drawOrder=e[a.drawId]})}let{flightProfile:o}=Ht({event:t});return o?.flights?.forEach(i=>{i.flightNumber=e[i.drawId]}),{...C}}function eI({tournamentRecord:t,event:e}){if(!t)return{error:$};if(!e)return{error:Ot};let{flightProfile:r}=Ht({event:e}),n=r?.flights&&Object.assign({},...r.flights.sort((o,i)=>o.flightNumber-i.flightNumber).map((o,i)=>({[o.drawId]:i+1})))||e.drawDefinitions?.length&&Object.assign({},...e.drawDefinitions.sort((o,i)=>o.drawOrder-i.drawOrder).map((o,i)=>({[o.drawId]:i+1})))||void 0;return n?tI({event:e,orderedDrawIdsMap:n}):{...C}}function qN({autoPublish:t=!0,tournamentRecord:e,auditData:r,drawId:n,event:o,force:i}){if(!e)return{error:$};if(!n)return{error:sn};if(!o)return{error:Ot};let{flightProfile:s}=Ht({event:o});if(s&&s.flights?.find(u=>u.drawId===n)){let u=s.flights.filter(m=>m.drawId!==n),p={name:cn,value:{...s,flights:u}};Ro({event:o,extension:p})}if(o.drawDefinitions?.find(c=>c.drawId===n)){let c=em({drawIds:[n],eventId:o.eventId,tournamentRecord:e,autoPublish:t,auditData:r,event:o,force:i});if(c.error)return c}return eI({tournamentRecord:e,event:o})}function $N(t){let e=et(t,[{[so]:!0,[ne]:!0,[vf]:!1},{replacementIndividualParticipantId:!0,[er]:h=>Vt(h),existingIndividualParticipantId:!0,[fn]:ie,participantId:!0}]),{replacementIndividualParticipantId:r,existingIndividualParticipantId:n,tournamentRecord:o,drawDefinition:i,participantId:s,event:a,uuids:c}=t;if(e.error)return e;if(a?.eventType!==qr)return{error:jn};if(!(a?.entries?.filter(({entryStatus:h})=>[Gr,Ui].includes(h)).map(({participantId:h})=>h)||[]).includes(r))return{error:mn};let p=(o.participants||[]).find(h=>h.participantId===s);if(p?.participantType!==ft)return{error:Li,participant:p};let m=p.individualParticipantIds,d=[r,...m.filter(h=>h!==n)],{participant:l}=In({participantIds:d,tournamentRecord:o}),f;if(l)f=l.participantId;else{let h={participantId:c?.pop(),participantRole:xe,individualParticipantIds:d,participantType:ft},S=vn({participant:h,returnParticipant:!0,tournamentRecord:o});if(S.error)return S;f=S.participant.participantId}let{flightProfile:g}=Ht({event:a});if(i){let h=g?.flights?.find(({drawId:S})=>S===i.drawId);h&&(h.drawEntries=h.drawEntries.map(S=>S.participantId===s?{...S,participantId:f}:S)),i.entries=i.entries.map(S=>S.participantId===s?{...S,participantId:f}:S);for(let S of i.structures||[])if(S.structures){S.positionAssignments=void 0;for(let T of S.structures)T.positionAssignments=T.positionAssignments.map(y=>y.participantId===s?{...y,participantId:f}:y)}else S.positionAssignments&&(S.positionAssignments=S.positionAssignments.map(T=>T.participantId===s?{...T,participantId:f}:T))}a.entries=a.entries.map(h=>h.participantId===s&&{...h,participantId:f}||h.participantId===r&&{...h,participantId:n}||h);let I=o.events.some(({entries:h,eventId:S,drawDefinitions:T})=>a.eventId===S?T.some(({drawId:y,entries:E})=>y===i?.drawId?!1:E?.find(P=>P.participantId===s)):h?.find(y=>y.participantId===s));if(!I){let h=zi({addIndividualParticipantsToEvents:!1,participantIds:[s],tournamentRecord:o});if(h.error)return h}return{...C,participantOtherEntries:I,newPairParticipantId:f}}function vc(t){let{flight:e,suppressNotifications:r,modifyEventEntries:n,existingDrawCount:o,allowReplacement:i,checkEntryStatus:s,tournamentRecord:a,drawDefinition:c,event:u}=t;if(!c)return{error:Z};if(!u)return{error:Ot};u.drawDefinitions||(u.drawDefinitions=[]);let{drawId:p,drawName:m,entries:d}=c,{entries:l}=u,f=0;if(o!==void 0&&o!==u.drawDefinitions.length)return{error:V,info:"drawDefintions count mismatch"};let{flightProfile:g}=Ht({event:u}),I=e&&g?.flights?.find(v=>v.flightNumber===e.flightNumber),h=g?.links?.find(v=>v?.target?.drawId===p)?.source?.drawId;if(h&&!u.drawDefinitions.find(v=>v.drawId===h))return _({result:{error:Z},info:{sourceDrawId:h}});if(I&&I.drawId!==c.drawId)return _({result:{error:ma},info:{relevantFlight:I}});let y=d?.every(({participantId:v,entryStatus:O})=>{let x=I?.drawEntries.find(F=>F.participantId===v);return!O||x?.entryStatus===O}),E=!s||l&&d?.every(({participantId:v,entryStatus:O,entryStage:x})=>l.find(w=>w.participantId===v&&(!w.entryStage||w.entryStage===x))?.entryStatus===O);if(I&&!y)return _({result:{error:ma},context:{drawEntriesPresentInFlight:y,matchingEventEntries:E,relevantFlight:I},info:"Draw entries are not present in flight or do not match entryStatuses"});if(n&&d?.filter(Boolean).forEach(v=>{if(v?.entryStatus&&Qr.includes(v?.entryStatus)){let O=l?.filter(Boolean).find(x=>x.participantId===v.participantId);O&&v.entryStatus&&O?.entryStatus!==v.entryStatus&&(O.entryStatus=v.entryStatus,f+=1)}}),l&&!E)return _({result:{info:"Draw entries do not match event entryStatuses",context:{matchingEventEntries:E,eventEntries:l},error:ma}});let P=g?.flights?.map(({flightNumber:v})=>!isNaN(v)&&dt(v))?.filter(Boolean)||[],A=u.drawDefinitions.map(({drawOrder:v})=>v&&dt(v))?.filter(Boolean)||[],U=Math.max(0,...A,...P)+1,N=g?.flights?.find(v=>v.drawId===p),D;if(N){N.drawName=c.drawName,D={name:cn,value:{...g,flights:g.flights}};let v=N.flightNumber;v&&!A.includes(v)?U=v:N.flightNumber=U}else{let v=g?.flights||[];v.push({manuallyAdded:!0,flightNumber:U,drawEntries:d,drawName:m,drawId:p}),D={name:cn,value:{...g||{},flights:v}}}Ro({event:u,extension:D}),Object.assign(c,{drawOrder:U});let M=u.drawDefinitions.find(v=>v.drawId===p),R=a?.tournamentId,b=u.eventId;if(M){if(!i)return{error:FA};let O=ir({drawDefinition:M})?.matchUps?.map(Ue)??[],x=ir({drawDefinition:c})?.matchUps;if(!r){O?.length&&Rn({matchUpIds:O,action:"modifyDrawDefinition",tournamentId:R,eventId:b}),x?.length&&vo({matchUps:x,tournamentId:R,eventId:b}),u.drawDefinitions=u.drawDefinitions.map(w=>w.drawId===p?c:w);let F=c.structures?.map(({structureId:w})=>w);vt({drawDefinition:c,tournamentId:R,structureIds:F,eventId:b})}}else if(u.drawDefinitions.push(c),!r){let{matchUps:v}=ir({drawDefinition:c,event:u});v&&vo({tournamentId:a?.tournamentId,matchUps:v}),Aa({drawDefinition:c,tournamentId:R,eventId:b})}return{...C,modifiedEventEntryStatusCount:f}}function KN(t){let{provisionalPositioning:e,useExistingSeedLimit:r,tournamentRecord:n,drawDefinition:o,seedingProfile:i,structureId:s,assignments:a,drawId:c,event:u}=t,p=0;if(!a?.length)return{error:jl};if(!n)return{error:$};if(!c)return{error:sn};let m=nn({provisionalPositioning:e,drawDefinition:o,structureId:s});if(m.error)return m;let{seedAssignments:d,seedLimit:l}=m,f=Object.assign({},...(d??[]).filter(h=>h.seedNumber).map(h=>({[h.seedNumber]:h})));a.forEach(h=>{let{seedNumber:S}=h;l&&S<=l&&(!r||f[S])&&(f[S]=h)});let g=Object.values(f),I=g.map(h=>h?.participantId).filter(Boolean);if(I.length!==CI(I).length)return{error:kA};for(let h of g){let S=Ks({...h,provisionalPositioning:e,tournamentRecord:n,drawDefinition:o,seedingProfile:i,structureId:s,event:u});if(S?.error)return S;S?.success&&p++}return p?{...C,modifications:p}:{error:xs}}function rI({deleteExisting:t,event:e,flightProfile:r}){let n="attachFlightProfile";if(!r)return _({result:{error:st},stack:n});if(!e)return _({result:{error:Ot},stack:n});let{flightProfile:o}=Ht({event:e});return o&&!t?_({result:{error:uf},stack:n}):e.drawDefinitions?.length?_({result:{error:xA},stack:n}):(Ro({event:e,extension:{name:cn,value:r}}),{flightProfile:J(r,!1,!0),...C})}function dx({tournamentRecord:t,scaleAttributes:e,participantIds:r}){if(!t)return{error:$};if(!r)return{error:Do};if(!e)return{error:st,info:"scaleAttributes required"};let{scaleType:n,eventType:o,scaleName:i}=e,s=[qU,n,o,i].join(".");return t.participants?.forEach(a=>{r.includes(a.participantId)&&a.timeItems&&(a.timeItems=a.timeItems.filter(c=>c&&c?.itemType!==s))}),{...C}}function nI({tournamentRecord:t,scaleAttributes:e,drawDefinition:r,entryStatuses:n,drawId:o,event:i,stage:s}){if(!i)return{error:Ot};if(n&&!Array.isArray(n))return _({result:{error:V},info:ai("entryStatus"),stack:"removeScaleValues"});let a=i.entries;if(o){let{flightProfile:p}=Ht({event:i}),m=p?.flights?.find(d=>d.drawId===o);m?a=m.drawEntries:a=r?.entries}let u=(a||[]).filter(p=>(!s||!p.entryStage||p.entryStage===s)&&(!n||n.includes(p.entryStatus))).map(St);return dx({tournamentRecord:t,scaleAttributes:e,participantIds:u})}function fl({removePriorValues:t,tournamentRecord:e,displaySettings:r,status:n=Rr,event:o}){if(!e)return _({result:{error:$}});if(!o)return _({result:{error:Ot}});if(!ht(r))return _({result:{error:st}});if(ht(r.draws))for(let s of Object.keys(r.draws)){let a=r.draws[s].scheduleDetails??[];if(a.length){let c=[];for(let u of a){let p=c.find(m=>yC(m.attributes,u.attributes));p?.dates&&u.dates?p.dates.push(...u.dates):c.push(u)}r.draws[s].scheduleDetails=c}}let i=oa({statusObject:{displaySettings:r},removePriorValues:t,status:n,event:o});return i.error?i:{...C}}function zN({tournamentRecord:t,drawDefinition:e,entryStatuses:r,scaleName:n,drawId:o,event:i,stage:s}){if(!t)return{error:$};if(!i)return{error:Ot};n=n||i.category?.categoryName||i.category?.ageCategoryCode;let a={eventType:i.eventType,scaleType:To,scaleName:n};return nI({tournamentRecord:t,scaleAttributes:a,drawDefinition:e,entryStatuses:r,drawId:o,event:i,stage:s})}function QN(t){let e=et(t,[{[ne]:!0},{eventIds:!0,[He]:Be}]);if(e.error)return e;let{removePairParticipants:r,tournamentRecord:n,eventIds:o}=t,i=[],s=[],a=[],c=[];if(n.events=(n.events||[]).filter(u=>{if(o.includes(u.eventId)){let d={action:Xg,payload:{events:[u]}};i.push(d),s.push({tournamentId:n.tournamentId,eventName:u.eventName,eventType:u.eventType,category:u.category,eventId:u.eventId,gender:u.gender})}let p=u.eventType===qr?(u.entries||[]).map(({entryStatus:d,participantId:l})=>d!==Gr&&l).filter(Boolean):[],m=o.includes(u.eventId);return m?c.push(...p):a.push(...p),!m}),r){let u=c.filter(p=>!a.includes(p));n.participants=n.participants.filter(({participantId:p})=>!u.includes(p))}if(bc({tournamentRecord:n}),i.length)if(ip(Ai)){let u=n.tournamentId;lt({topic:Ai,payload:{type:Xg,tournamentId:u,detail:i}})}else Nc({tournamentRecord:n,timeItem:{itemValue:s,itemType:Xg}});return{...C}}function XN(t){let e=et(t,[{tournamentRecord:!0,eventId:!0,event:!0},{eventUpdates:!0,_ofType:Kr}]);if(e.error)return e;let{eventUpdates:r,event:n}=t,o="modifyEvent",i=A1(t),s=E1({enteredParticipants:i}),{enteredParticipantGenders:a,enteredParticipantTypes:c}=s,u=Ht({event:n})?.flightProfile?.flights,p=!n.drawDefinitions?.length&&!u?.length,m=U1({noFlightsNoDraws:p,enteredParticipantGenders:a,eventUpdates:r,stack:o});if(m.error)return m;let d=P1({enteredParticipantTypes:c,eventUpdates:r,stack:o});if(d.error)return d;let l=T1({...t,...s,enteredParticipants:i,stack:o});if(l.error)return l;let f=y1({...t,stack:o});return f.error?f:(r.eventType&&(n.eventType=r.eventType),r.eventName&&(n.eventName=r.eventName),r.gender&&(n.gender=r.gender),{...C})}function T1(t){let e=t.eventUpdates?.category;if(!e)return{...C};let r=qc({category:e});if(r.error)return r;if(t.event.eventType===_e){let n=t.event?.drawDefinitions?.map(u=>ii(u))??[],o=ii(t.event),s=(Xn(t)?.matchUps??[]).map(u=>ii(u))??[];if(![o,...n,...s].filter(Boolean).every(u=>u.collectionDefinitions.every(p=>!p.category||$c({category:t.eventUpdates.category,childCategory:p.category}))))return _({result:{error:Hc},stack:t.stack})}if(t.enteredParticipants?.length){let n=t.eventUpdates.startDate||t.event.startDate||t.tournamentRecord.startDate,o=t.eventUpdates.endDate||t.event.endDate||t.tournamentRecord.endDate,i=t.enteredParticipants.map(c=>c.participantType===At?c:c.individualParticpants??[]).flat(),s=Fs({category:e,consideredDate:n}),a=Fs({category:e,consideredDate:o});if(s?.ageMinDate||s?.ageMaxDate||a?.ageMinDate||a?.ageMaxDate)for(let c of i){let u=c.person?.birthDate;if(!u)return _({result:{error:nE},stack:t.stack});let p=new Date(u).getTime();if(s.ageMinDate||s.ageMaxDate){let m=new Date(s.ageMinDate).getTime(),d=new Date(s.ageMaxDate).getTime();if(p<m||p>d)return _({result:{error:jI},stack:t.stack})}if(a.ageMin||a.ageMax){let m=new Date(a.ageMinDate).getTime(),d=new Date(a.ageMaxDate).getTime();if(p<m||p>d)return _({result:{error:jI},stack:t.stack})}}}return{...C}}function y1(t){let{tournamentRecord:e,eventUpdates:r,event:n,stack:o}=t;if(r.startDate||r.endDate){let i=Zg({startDate:r.startDate,endDate:r.endDate,tournamentRecord:e,event:n});if(i.error)return _({result:i,stack:o})}return{...C}}function A1(t){let{tournamentRecord:e,event:r}=t,n=r?.entries?.filter(({entryStatus:o})=>{let i=o;return[...Qr,rn].includes(i)}).map(({participantId:o})=>o)??[];return n?Gt({participantFilters:{participantIds:n},withIndividualParticipants:!0,tournamentRecord:e}).participants??[]:[]}function E1({enteredParticipants:t}){let e=[],r=t.reduce((o,i)=>{let s=i.person?.sex?[i.person.sex]:i.individualParticpants?.map(a=>a.person?.sex)||[];return e.push(...s),o.includes(i.participantType)?o:o.concat(i.participantType)},[]),n=pt(e);return{enteredParticipantTypes:r,enteredParticipantGenders:n}}function U1({noFlightsNoDraws:t,enteredParticipantGenders:e,eventUpdates:r,stack:n}){let o=!e.length||!r.gender||r.gender===Pn||e.length===1&&e[0]===r.gender||t&&r.gender===Ar;return r.gender&&!o?_({context:{gender:r.gender,validGender:o},result:{error:ep},stack:n}):{...C}}function P1({enteredParticipantTypes:t,eventUpdates:e,stack:r}){let o=(t.includes(_e)&&[_e]||t.includes(At)&&[$n]||t.includes(ft)&&[qr]||[qr,$n,_e]).includes(e.eventType??"");return e.eventType&&!o?_({context:{participantType:e.eventType,validEventType:o},result:{error:jn},stack:r}):{...C}}function rm({qualifyingPositions:t,drawEntries:e=[],drawName:r,drawId:n,event:o,stage:i}){let s="addFlight";if(!o)return _({result:{error:Ot},stack:s});if(!r)return _({result:{error:st},stack:s});if(e?.length){let g=(o.entries??[]).map(St),I=e.map(St);if(jt(I,g).length!==I.length)return _({result:{error:V},stack:s})}let a=Ht({event:o})?.flightProfile,c=a?.flights?.map(({flightNumber:g})=>!isNaN(g)&&dt(g))?.filter(Boolean)||[],u=Math.max(0,...c)+1,m={drawId:n||Mt(),flightNumber:u,drawEntries:e,drawName:r};if(i&&(m.stage=i),t&&(m.qualifyingPositions=t),(a?.flights||[]).find(({drawId:g})=>g===m.drawId))return _({result:{error:wE},stack:s});let l=(a?.flights||[]).concat(m),f={name:cn,value:{...a||{},flights:l}};return Ro({event:o,extension:f})}var iM={};Jt(iM,{drawMatic:()=>Kd,garman:()=>oM,generateAdHocMatchUps:()=>Lu,generateAdHocRounds:()=>$d,generateAndPopulatePlayoffStructures:()=>vd,generateCourts:()=>oI,generateDrawDefinition:()=>wa,generateDrawMaticRound:()=>Gd,generateDrawStructuresAndLinks:()=>Ld,generateDrawTypeAndModifyDrawDefinition:()=>Fd,generateFlightProfile:()=>fx,generateLineUps:()=>xy,generateQualifyingStructure:()=>Nd,generateSeedingScaleItems:()=>Py,generateStatCrew:()=>Sx,generateVoluntaryConsolation:()=>bT,roundRobinGroups:()=>yv});var D1="splitLevelBased",tM="splitWaterfall",eM="splitShuttle",lx={SPLIT_LEVEL_BASED:D1,SPLIT_WATERFALL:tM,SPLIT_SHUTTLE:eM};function fx(t){let{drawNameRoot:e="Flight",attachFlightProfile:r,tournamentRecord:n,scaleAttributes:o,scaleSortMethod:i,deleteExisting:s,sortDescending:a,drawNames:c=[],flightsCount:u,splitMethod:p,uuids:m=[],event:d,stage:l}=t;if(!d)return{error:Ot};let f=d.entries??[],{flightProfile:g}=Ht({event:d});if(g&&r&&!s)return{error:uf};let I=t.scaledEntries??ea({tournamentRecord:n,scaleAttributes:o,scaleSortMethod:i,sortDescending:a,event:d,stage:l}).scaledEntries,h=I.map(St),S=Sr(f.filter(({participantId:D})=>!h.includes(D)).filter(D=>(!l||!D.entryStage||D.entryStage===l)&&(!D.entryStatus||oi.includes(D.entryStatus)))),T=I.concat(...S),y=T.length,E=Math.ceil(y/u),P=Ee(T,E);p===tM?P=Fl(T,u):p===eM&&(P=Fl(T,u,!0));function A(D){return(D||[]).map(({participantId:M,scaleValue:R})=>{let b=f.find(v=>v.participantId===M);return b?.scaleValue&&R&&(b.scaleValue=R),b}).sort((M,R)=>M.scaleValue-R.scaleValue).map((M,R)=>(M.scaleValue&&(M.seedNumber=R+1),M))}let U=tt(0,u).map(D=>{let M=D+1;return{flightNumber:M,drawId:m?.pop()??Mt(),drawEntries:A(P[D]),drawName:c?.length&&c[D]||`${e} ${M}`}}),N={scaleAttributes:o,splitMethod:p,flights:U};if(r){let D=rI({flightProfile:N,deleteExisting:s,event:d});return{splitEntries:Pr()&&P||void 0,...D}}else return{flightProfile:N,...C}}function rM({json:t,tagName:e}){let r=Object.keys(t).filter(i=>Array.isArray(t[i])).map(i=>({key:i,value:t[i].filter(s=>typeof s=="object"&&Object.keys(s).length===1)})),n=Object.keys(t).filter(i=>typeof t[i]=="object"&&!Array.isArray(t[i])).map(i=>({key:i,value:t[i]})),o=Object.keys(t).filter(i=>["string","number"].includes(typeof t[i])).map(i=>({key:i,value:t[i]}));return gx({tagName:e,attributes:o,childArrays:r,childObjects:n})}function gx(t){let{tagName:e,attributes:r=[],childArrays:n=[],childObjects:o}=t,i=`\r
24
24
  `,s=l=>{let f=Object.keys(l)[0],g=l[f];return{key:f,value:g}},a=n?.map(({key:l,value:f})=>gx({tagName:l,childObjects:f.map(s)})).join(`\r
25
25
  `),c=o?.map(({key:l,value:f})=>rM({tagName:l,json:f??[]})).join(`\r
26
- `),u=r?.map(({key:l,value:f})=>`${l}="${f}"`).join(" "),p=u?` ${u}`:"";if(e==="childArray")return c;let m=c?.length?`${i}${c}${i}`:"",d=a?.length?`${i}${a}${i}`:"";return`<${e}${p}>${m}${d}</${e}>`}function Sx(t){let e=et(t,[{[ne]:!0}]);if(e.error)return e;let{tournamentRecord:r}=t,{startDate:n,tournamentId:o,tournamentName:i}=r,{participantMap:s,matchUps:a,mappedMatchUps:c}=Gt({withMatchUps:!0,withEvents:!0,tournamentRecord:r}),u=r.participants.filter(y=>y.participantType===Ft),p=a?.filter(y=>y.matchUpType===Ft)??[],m=p?.reduce((y,E)=>{let P=E?.tieMatchUps??[];return P&&[...y,...P]},[])??[],d=a?.filter(y=>y.matchUpType===kt)??[],l=a?.filter(y=>y.matchUpType===xt)??[],f=m.length===d.length+l.length,g=p.length===1&&f,h={mappedMatchUps:c,participantMap:s,tournamentName:i,tournamentId:o,tournament:f?"N":"Y",startDate:n},S=[],T=[];if(g){let y=p[0],{json:E,xml:P}=Ix({teamParticipants:u,teamMatchUp:y,...h,doubles:l,singles:d});T.push(E),S.push(P)}else for(let y of p){let E=y?.sides?.map(({participant:N})=>N?.participantId).filter(Boolean);if(E?.length!==2)continue;let P=E.map(N=>N&&s?.[N]?.participant),{xml:A,json:U}=Ix({doubles:y.tieMatchUps?.filter(N=>N.matchUpType===xt),singles:y.tieMatchUps?.filter(N=>N.matchUpType===kt),teamParticipants:P,teamMatchUp:y,...h});T.push(U),S.push(A)}return{json:T,xml:S,...C}}function Ix({teamParticipants:t,mappedMatchUps:e,participantMap:r,tournamentName:n,tournamentId:o,teamMatchUp:i,tournament:s,startDate:a,doubles:c,singles:u}){let p=t?.find(y=>y.participantRoleResponsibilities?.includes("Home")),m=t?.filter(y=>y.participantId!==p?.participantId),d=Yn(a,"/","MDY"),l=p?.participantName||m?.[1]?.participantName,f=p?.participantId||m?.[1]?.participantId,g=m?.[0]?.participantName,I=m?.[0]?.participantId,h={},S=t.map(y=>({team:{...R1({teamParticipant:y,teamMatchUp:i,uniValues:h,participantMap:r,mappedMatchUps:e,homeid:f})}})),T=nt({venue:{tournamentname:s?n:void 0,neutralgame:p?"N":"Y",gameid:o,officials:{},tournament:s,rules:{},homename:l,visname:g,homeid:f,visid:I,date:d},childArray:S,singles_matches:u?.map(y=>hx({matchUp:y,homeid:f,uniValues:h})),doubles_matches:c?.map(y=>hx({matchUp:y,homeid:f,uniValues:h}))});return{json:T,xml:rM({json:T,tagName:"tngame"})}}function N1({homeid:t,uniValues:e,participant:r}){if(!r)return{};let n=r.individualParticipants?.length===2,o=n?pt(r.individualParticipants?.map(g=>g.teams?.[0]?.participantId)):[],i=n?pt(r.individualParticipants?.map(g=>g.teams?.[0]?.teamId)):[],s=!n&&r.teams?.[0]?.participantId||o?.length===1&&o[0]||void 0,a=!n&&r.teams?.[0]?.teamId||i?.length===1&&i[0]||s,c=n?void 0:r.participantName,u=r.individualParticipants?.[0]?.participantName,p=r.individualParticipants?.[1]?.participantName,m=t&&(s===t?"H":"V")||"",d=n?void 0:e[s][r.participantId],l=e[s][r.individualParticipants?.[0]?.participantId],f=e[s][r.individualParticipants?.[1]?.participantId];return nt({vh:m,uni:d,uni_1:l,uni_2:f,team:a,name:c,name_1:u,name_2:p})}function M1({sets:t,sideNumber:e}){return Object.assign({},...t?.map(r=>{let{setNumber:n,side1Score:o,side2Score:i,side1TiebreakScore:s,side2TiebreakScore:a}=r,c=`set_${n}`,u=`tie_${n}`,p=e===1?o:i,m=e===1?s:a;return{[c]:p,[u]:m}})??[])}function R1({teamParticipant:t,teamMatchUp:e,participantMap:r,mappedMatchUps:n,homeid:o,uniValues:i}){let{participantId:s,participantName:a}=t,c=o&&(s===o?"H":"V")||"",u=r?.[s]?.matchUps,p=u&&Object.keys(u),m=e?.sides?.find(({participant:E})=>E.participantId===s)?.sideNumber,d=e?.score?.sets?.[0]?.[`side${m}Score`]??0;i[s]={};let l={SINGLES:{w:0,l:0},DOUBLES:{w:0,l:0}},f=[],g=[],I=0;for(let E of p??[]){let P=n?.[E],A=P.sides.find(({participant:N})=>N.participantId===s)?.sideNumber,U=P.score?.sets?.[0]?.[`side${A}Score`]??0;I+=U;for(let N of P.tieMatchUps??[]){let{matchUpType:D,winningSide:M}=N,R=M&&(M===A?"w":"l")||"";R&&(l[D][R]+=1);let b=R==="w"?"1":"0",v=R==="l"?"1":"0";if(D===kt){let O=g.length+1;g.push({singles_pair:{pair:O,won:b,lost:v,tied:"0"}})}else if(D===xt){let O=f.length+1;f.push({doubles_pair:{pair:O,won:b,lost:v,tied:"0"}})}}}let h=[{singles:{childArray:g,won:l.SINGLES.w,lost:l.SINGLES.l}},{doubles:{childArray:f,won:l.DOUBLES.w,lost:l.DOUBLES.l}}],S=[],T=1;for(let E of t.individualParticipantIds){let P=r?.[E];if(P){let{participant:A,counters:U}=P,N={won:U?.DOUBLES?.wins||0,lost:U?.DOUBLES?.losses||0},D={won:U?.SINGLES?.wins||0,lost:U?.SINGLES?.losses||0},{participantName:M,participantId:R}=A;i[s][R]=T,S.push({player:{name:M,uni:T,singles:D,doubles:N}})}T+=1}return{vh:c,id:s,name:a,score:d||I,totals:h,childArray:S}}function hx({matchUp:t,homeid:e,uniValues:r}){let{collectionPosition:n,orderOfFinish:o,matchUpType:i,sides:s}=t??{},a=s?.map(u=>{let{sideNumber:p,participant:m}=u,d=M1({sets:t.score?.sets,sideNumber:p});return{[i===kt?"singles_score":"doubles_score"]:{...N1({homeid:e,uniValues:r,participant:m}),...d}}});return{[i===kt?"singles_match":"doubles_match"]:{match:n,order:o,childArray:a}}}var C1="ASC",nM="ASC",b1="DESC",_y="DESC",Tx={ASC:C1,ASCENDING:nM,DESC:b1,DESCENDING:_y};function xy(t){let{tieFormat:e}=t,{useDefaultEventRanking:r,tournamentRecord:n,drawDefinition:o,scaleAccessor:i,singlesOnly:s,attach:a,event:c}=t;if(c?.eventType!==br)return{error:jn};if(!n)return{error:$};if(!e&&!o)return{error:Cr};if(e=e??We({drawDefinition:o,event:c})?.tieFormat,ur({tieFormat:e}).error)return{error:ko};if(typeof i!="object"&&!r)return{error:V,context:{scaleAccessor:i}};let u={},m=(o?.entries??c?.entries??[]).filter(R=>R?.entryStatus===kr).map(St),{participants:d=[]}=Gt({withIndividualParticipants:!0,withScaleValues:!0,tournamentRecord:n}),l=d.filter(({participantId:R})=>m.includes(R)),f=R=>R===Ii?"rankings":"ratings",g=c?.category?.categoryName??c?.category?.ageCategoryCode,{scaleName:I=g,scaleType:h=Ii,sortOrder:S,accessor:T}=i||{},y=f(h),E=(R,b)=>{let v=R[y]?.[b];if(!v&&r&&(v=R[y]?.[ua]),Array.isArray(v)){let O=v.find(x=>x.scaleName===I)?.scaleValue;if(Zt(O))return O;if(T&&typeof O=="object")return O[T]}return 0},P=(R,b,v)=>{let O=S===_y?b:R,x=S===_y?R:b;return E(O,v)-E(x,v)},A=(R,b)=>P(R,b,ua),U=(R,b)=>P(R,b,_i),N=[],D=e?.collectionDefinitions??[];for(let R of l){let b=R.individualParticipants?.sort(A)??[],v=s?b:R.individualParticipants?.sort(U)??[],O={};for(let F of D){let w=[],{collectionId:L,matchUpCount:G,matchUpType:k,gender:H}=F,W=de(ua)(k);tt(0,G).forEach(q=>{let Y=W?b:v??[],B=q+1,K=[];tt(0,W?1:2).forEach(X=>{let j=Y?.find(ot=>{let z=H&&([zt,oe].includes(H)&&H||H===Ar&&[zt,oe][X]);return(!z||z===ot.person?.sex)&&!w.includes(ot.participantId)})?.participantId;j&&(K.push(j),w.push(j),O[j]||(O[j]=[]),O[j].push({collectionPosition:B,collectionId:L}))}),W||N.push(K)})}let x=Object.keys(O).map(F=>({collectionAssignments:O[F],participantId:F}));u[R.participantId]=x}let M=[];for(let R of N){let{participant:b}=In({tournamentParticipants:d,participantIds:R});if(!b){let v={individualParticipantIds:R,participantRole:xe,participantType:ft};M.push(v)}}if(a){for(;M.length;)vn({participant:M.pop(),tournamentRecord:n});Ut({element:o,extension:{name:Co,value:u}})}return{...C,lineUps:u,participantsToAdd:M}}function oI(t){if(!t)return{error:st};let e=et(t,[{dates:!1,[er]:s=>Array.isArray(s)&&s.every(Nr)},{uuids:!1,[er]:s=>Array.isArray(s)&&s.every(Vt)},{startTime:!1,endTime:!1,[er]:eh},{idPrefix:!1,namePrefix:!1,[er]:Vt},{count:!0,[er]:Zt}]);if(e.error)return e;let{startDate:r,endDate:n}=t.tournamentRecord??{},o=t.dates||r&&n&&Ls(r,n)||[],i=tt(1,t.count+1).map(s=>nt({courtId:t.uuids?.pop()??(t.idPrefix&&`${t.idPrefix}-${s}`)??Mt(),courtName:t.courtNames?.pop()??(t.namePrefix&&`${t.namePrefix} ${s}`),dateAvailability:o.map(a=>({startTime:t.startTime??"08:00",endTime:t.endTime??"20:00",date:a}))}));return{...C,courts:i}}var oM={};Jt(oM,{default:()=>v1,garman:()=>Ex});function La({court:t,date:e}){let r=e&&t.dateAvailability.find(o=>qn(o.date,e)),n=t.dateAvailability.find(o=>!o.date);return r||n}function Ms(t){let e=et(t,[{courtDate:!0,_ofType:Kr}]);if(e.error)return e;let{includeBookingTypes:r=[],courtDate:n}=t,o=[],i=Ge(n.startTime);(n.bookings||[]).filter(a=>!a.bookingType||!r.includes(a.bookingType)).sort((a,c)=>yf(a.startTime).localeCompare(yf(c.startTime))).forEach(a=>{let c={startTime:Qt(i.toISOString()),endTime:a.startTime};Ge(a.startTime)>i&&o.push(c),Ge(a.endTime)>i&&(i=Ge(a.endTime))});let s={startTime:Qt(i.toISOString()),endTime:n.endTime};return Ge(n.endTime)>i&&o.push(s),{timeSlots:o}}function yx({averageMatchUpMinutes:t,includeBookingTypes:e,periodStartTime:r,periodEndTime:n}){let o=s=>{let{timeSlots:a}=Ms({includeBookingTypes:e,courtDate:s});return!!a?.filter(i)?.length};function i(s){let a=Ge(s.startTime),c=Ge(s.endTime);return a>r||c<n?!1:la(r,c)>=t}return{enoughTime:o}}function wy(t){let e=et(t,[{periodStart:!0,date:!0},{courts:!0,_ofType:Be}]);if(e.error)return e;let{averageMatchUpMinutes:r,includeBookingTypes:n,periodStart:o,date:i}=t,s=t.courts,a=Ge(o),c=Ef(a,r),{enoughTime:u}=yx({averageMatchUpMinutes:r,includeBookingTypes:n,periodStartTime:a,periodEndTime:c});return{availableToScheduleCount:(s?.filter(m=>{if(!Array.isArray(m.dateAvailability))return!1;let d=La({date:i,court:m});return!!(d&&u(d))})||[]).length,...C}}function nm(t){let{remainingScheduleTimes:e=[],clearScheduleDates:r,periodLength:n=30,scheduleDate:o,courts:i=[]}=t,{bookings:s=[]}=t;if(!Array.isArray(i)||!i.length)return{error:V,courts:i};if(!Array.isArray(s))return{error:Pm};if(!Nr(o))return{error:je};r&&(Array.isArray(r)?r.includes(o)&&(s=[]):s=[]);let{courtBookings:a,unassignedBookings:c}=s.reduce((l,f)=>{let{courtId:g}=f;return g?l.courtBookings[g]?l.courtBookings[g].push(f):l.courtBookings[g]=[f]:l.unassignedBookings.push(f),l},{courtBookings:{},unassignedBookings:[]}),u=i.map((l,f)=>{let{courtId:g,courtName:I}=l,h=a[g]||[],S=La({date:o,court:l})||{},{bookings:T=[],startTime:y,endTime:E,date:P}=S,U=[e[f]&&{startTime:y,endTime:e[f]},...J(T,!1,!0),...h].filter(Boolean);return{courtId:g,courtName:I,dateAvailability:{bookings:U,startTime:y,endTime:E,date:P}}});c.sort((l,f)=>Yt(l.startTime)-Yt(f.startTime));let p=()=>u.map(l=>{let f=l.dateAvailability,{timeSlots:g=[]}=Ms({courtDate:f});return{courtName:l.courtName,courtId:l.courtId,timeSlots:g}}).flat(),m=[];for(let l of c){let{startTime:f,endTime:g,averageMinutes:I,recoveryMinutes:h,matchUpId:S}=l,T=Yt(f),y=Yt(g),P=p().reduce((A,{courtId:U,courtName:N,timeSlots:D})=>{let M;return D.find(({startTime:b,endTime:v})=>{M=Yt(b)-T;let O=T>=Yt(b);return y<=Yt(v)&&A.startDifference!==0&&((M===0||M+n>=0)&&(A.startDifference===void 0||M<A.startDifference)||O)})?{courtName:N,courtId:U,startDifference:M}:A},{});if(P.courtId){let A={averageMinutes:I,recoveryMinutes:h,matchUpId:S,startTime:f,endTime:g};m.push(A),u.find(({courtId:N})=>N===P.courtId)?.dateAvailability.bookings.push(A)}else console.log({unassignedBooking:l})}return{virtualCourts:u.map(({courtId:l,courtName:f,dateAvailability:g})=>({dateAvailability:[g],courtName:f,courtId:l})),assignedBookings:m}}function Hu({averageMatchUpMinutes:t,periodLength:e=30,recoveryMinutes:r}){let n=(t||90)+(r||0);return e>n?n:e||30}function Ly(t){let{startTime:e="8:00",endTime:r="20:30",count:n=10,date:o}=t??{};return tt(0,n).map(()=>({dateAvailability:[{date:o,startTime:e,endTime:r}]}))}function Oc({scheduleDate:t,startTime:e,endTime:r,courts:n}){let o=e&&"startTime"||r&&"endTime"||void 0;return n.reduce((i,s)=>{let a=La({date:t,court:s}),c=o&&(a?.[o]||s[o]);return c&&(!i||e&&Yt(c)<Yt(i)||r&&Yt(c)>Yt(i))?c:i},void 0)}function Ax({averageMinutes:t,startTime:e,endTime:r,courts:n,date:o}){e=e||Oc({courts:n,scheduleDate:o,startTime:!0}),r=r||Oc({courts:n,scheduleDate:o,endTime:!0});let i;if(e&&r){let s=Ge(e),a=Ge(r);for(let c of n||[]){if(!Array.isArray(c.dateAvailability))continue;let u=La({court:c,date:o}),{timeSlots:p}=Ms({courtDate:u});p?.forEach(m=>{let d=Ge(m.startTime),l=Ge(m.endTime);if(d>a||d<s||l<s)return!1;if(la(d,l)>=t){let I=Qt(d.toISOString());(!i||I<i)&&(i=I)}})}}return{firstTimeSlotStartTime:i}}function gl(t){let e=et(t,[{courts:!0,_ofType:Be}]);if(e.error)return e;let{date:r=Af(),startTime:n="08:00",endTime:o="19:00",periodLength:i,courts:s}=t,{calculateStartTimeFromCourts:a=!0,remainingScheduleTimes:c,averageMatchUpMinutes:u,clearScheduleDates:p,courtsCount:m,bookings:d}=t;i=i||Hu({averageMatchUpMinutes:u}),r=Pt(r),n=Qt(n),o=Qt(o);let l=0,f=0,g=0,I=0,h=0;!s&&m&&(s=Ly({startTime:n,endTime:o,count:m,date:r}));let{virtualCourts:S}=nm({remainingScheduleTimes:c,clearScheduleDates:p,scheduleDate:r,periodLength:i,bookings:d,courts:s}),{firstTimeSlotStartTime:T}=Ax({averageMinutes:u,courts:S,startTime:n,endTime:o,date:r});a&&T&&(n=T??n);let y=Yt(n),P=Yt(o)-y,A=Math.floor(P/i),N=tt(0,A+1).map(M=>{let R=y+M*i,b=qC(R),v=wy({courts:S??[],averageMatchUpMinutes:u,periodStart:b,date:r});if(v.error)return{error:v.error};let{availableToScheduleCount:O=0}=v,x=O>f?O-f:0;h+=M?O:0;let F=M?h/M:O,L=i*F/u,G=M?L*(M-1)+F:F,k=O?f&&G-l||x:0;l=G,f=O,g+=k;let H=dt(g)-I;return I+=H,{periodStart:b,add:H,availableToScheduleCount:O,newCourts:x,totalMatchUps:I}});return{scheduleTimes:N.reduce((M,R)=>{let v=tt(0,R.add).map(()=>({scheduleTime:R.periodStart}));return M.concat(...v)},[]).flat(),timingProfile:N,totalMatchUps:I}}var Ex={getCourtsAvailableAtPeriodStart:wy,generateTimeSlots:Ms,getScheduleTimes:gl,courtGenerator:Ly},v1=Ex;var Fy={};Jt(Fy,{isValid:()=>Dr,isValidMatchUpFormat:()=>Dr,parse:()=>Ye,stringify:()=>cp});var NM={};Jt(NM,{allCompetitionMatchUps:()=>Un,allDrawMatchUps:()=>ir,allEventMatchUps:()=>Xn,allTournamentMatchUps:()=>ye,analyzeMatchUp:()=>tm,applyLineUps:()=>PM,assignMatchUpSideParticipant:()=>sM,assignTieMatchUpParticipantId:()=>Sl,bulkMatchUpStatusUpdate:()=>yM,calculateWinCriteria:()=>Ds,checkInParticipant:()=>sI,checkMatchUpIsComplete:()=>ls,checkOutParticipant:()=>iI,competitionScheduleMatchUps:()=>Bu,disableTieAutoCalc:()=>SM,drawMatchUps:()=>Ty,enableTieAutoCalc:()=>gM,eventMatchUps:()=>pl,filterMatchUps:()=>Mi,findMatchUp:()=>zg,getAllDrawMatchUps:()=>ce,getAllStructureMatchUps:()=>yt,getCheckedInParticipantIds:()=>ps,getCompetitionMatchUps:()=>Zp,getEventMatchUpFormatTiming:()=>py,getHomeParticipantId:()=>fy,getMatchUpCompetitiveProfile:()=>Su,getMatchUpContextIds:()=>gy,getMatchUpDailyLimits:()=>dl,getMatchUpDailyLimitsUpdate:()=>my,getMatchUpDependencies:()=>on,getMatchUpFormat:()=>Iy,getMatchUpFormatTiming:()=>Tu,getMatchUpFormatTimingUpdate:()=>cy,getMatchUpScheduleDetails:()=>dd,getMatchUpType:()=>ld,getMatchUpsStats:()=>hy,getModifiedMatchUpFormatTiming:()=>cl,getParticipantResults:()=>vu,getPredictiveAccuracy:()=>ly,getRoundMatchUps:()=>Ke,getRounds:()=>Sy,isValidMatchUpFormat:()=>Dr,matchUpActions:()=>xd,mutate:()=>DM,participantScheduledMatchUps:()=>dy,query:()=>RN,removeDelegatedOutcome:()=>IM,removeMatchUpSideParticipant:()=>cI,removeTieMatchUpParticipantId:()=>cM,replaceTieMatchUpParticipantId:()=>aI,resetAdHocMatchUps:()=>EM,resetMatchUpLineUps:()=>pI,resetScorecard:()=>dI,resetTieFormat:()=>mI,setDelegatedOutcome:()=>AM,setMatchUpFormat:()=>TM,setMatchUpStatus:()=>Wu,setOrderOfFinish:()=>UM,substituteParticipant:()=>hM,tallyParticipantResults:()=>ba,toggleParticipantCheckInState:()=>Il,tournamentMatchUps:()=>ml,updateTieMatchUpScore:()=>lo,validMatchUp:()=>og,validMatchUps:()=>Vr});var DM={};Jt(DM,{applyLineUps:()=>PM,assignMatchUpSideParticipant:()=>sM,assignTieMatchUpParticipantId:()=>Sl,bulkMatchUpStatusUpdate:()=>yM,checkInParticipant:()=>sI,checkOutParticipant:()=>iI,disableTieAutoCalc:()=>SM,enableTieAutoCalc:()=>gM,findMatchUp:()=>zg,removeDelegatedOutcome:()=>IM,removeMatchUpSideParticipant:()=>cI,removeTieMatchUpParticipantId:()=>cM,replaceTieMatchUpParticipantId:()=>aI,resetAdHocMatchUps:()=>EM,resetMatchUpLineUps:()=>pI,resetScorecard:()=>dI,resetTieFormat:()=>mI,setDelegatedOutcome:()=>AM,setMatchUpFormat:()=>TM,setMatchUpStatus:()=>Wu,setOrderOfFinish:()=>UM,substituteParticipant:()=>hM,toggleParticipantCheckInState:()=>Il,updateTieMatchUpScore:()=>lo});function sM({tournamentRecord:t,drawDefinition:e,participantId:r,sideNumber:n,matchUpId:o,event:i}){if(r&&typeof r!="string")return{error:mn};if(!e)return{error:Z};if(!o)return{error:cr};let s=n===void 0;if(s&&(n=1),![1,2].includes(n))return _({result:{error:V,context:{sideNumber:n}}});let{matchUp:a,structure:c}=Bt({drawDefinition:e,matchUpId:o,event:i});if(!a)return{error:Le};if(!(!c?.structures&&!(e.drawType&&e.drawType!==$r)&&!c?.matchUps?.find(({roundPosition:p})=>!!p)))return{error:Um};if(!r&&(a?.score?.scoreStringSide1||se.includes(a?.matchUpstatus)||a?.matchUpStatus&&[Te,be].includes(a.matchUpStatus)))return{error:Ju,info:"matchUp has completed status or score"};if(a){if(a.sides=[1,2].map(p=>{let m=a.sides?.find(d=>d.sideNumber===p)??{sideNumber:p};return n===p?{...m,participantId:r}:m}),s)for(let p of a.sides)p.sideNumber&&(p.sideNumber=3-p.sideNumber);gt({tournamentId:t?.tournamentId,context:"assignSideParticipant",drawDefinition:e,matchUp:a})}return{...C,sidesSwapped:s}}function Jr({removePriorValues:t,tournamentRecord:e,duplicateValues:r,drawDefinition:n,disableNotice:o,matchUpId:i,timeItem:s,event:a}){let{matchUp:c}=Bt({drawDefinition:n,event:a,matchUpId:i});if(!c)return{error:Le};let u=to({removePriorValues:t,element:c,duplicateValues:r,timeItem:s});return o||gt({tournamentId:e?.tournamentId,eventId:a?.eventId,context:"addTimeItem",drawDefinition:n,matchUp:c}),u}function iI(t){let e=[{[ne]:!0},{[Ce]:!0},{[io]:!0},{[ln]:!0}],r=et(t,e);if(r.error)return r;let n=Ns(t,[{[ss]:Ln,attr:{[ru]:!0}}]);if(n.error)return n;let{tournamentRecord:o,drawDefinition:i,participantId:s,matchUpId:a}=t,c=n?.matchUp?.matchUp,{matchUpStatus:u,score:p}=c??{};if(u&&Xm.includes(u)||u&&se.includes(u)||Ie({score:p}))return{error:BA};let m=ps({matchUp:c});if(m?.error)return m;let{checkedInParticipantIds:d,allRelevantParticipantIds:l}=m??{};if(!l?.includes(s))return{error:mn};if(!d?.includes(s))return{error:IE};let f=pS({matchUp:c});if(f?.error)return f;let{sideParticipantIds:g,nestedIndividualParticipantIds:I}=f??{},h=g?.indexOf(s);return h!==void 0&&[0,1].includes(h)&&(I?.[h]??[]).forEach(T=>{Jr({drawDefinition:i,matchUpId:a,timeItem:{itemType:ud,itemValue:T}})}),Jr({tournamentRecord:o,drawDefinition:i,matchUpId:a,timeItem:{itemValue:s,itemType:ud}}),{...C,checkedOut:!0}}function sI(t){let e=[{[ne]:!0},{[Ce]:!0},{[io]:!0},{[ln]:!0}],r=et(t,e);if(r[fn])return r;let n=Ns(t,[{[ss]:Ln,attr:{[ru]:!0}}]);if(n[fn])return n;let{tournamentRecord:o,drawDefinition:i,participantId:s,matchUpId:a}=t,c=ps({matchUp:n?.matchUp?.matchUp});if(c?.error)return c;let{checkedInParticipantIds:u,allRelevantParticipantIds:p}=c??{};if(!p?.includes(s))return{[fn]:mn};let m={...C,checkedIn:!0};return u?.includes(s)||Jr({tournamentRecord:o,drawDefinition:i,matchUpId:a,timeItem:{itemValue:s,itemType:cd}}),m}function Il(t){let e=et(t,[{[io]:!0,[Ce]:!0,[ln]:!0}]);if(e.error)return e;let r=t.tournamentId??t.activeTournamentId,n=t.tournamentRecord??(r&&t.tournamentRecords?.[r]);if(!n)return{error:$};let i=Ns(t,[{[ss]:Ln,attr:{[ru]:!0},[fn]:Le}]).matchUp?.matchUp;if(!i)return{error:Le};let{checkedInParticipantIds:s=[]}=ps({matchUp:i}),{participantId:a,matchUpId:c,drawDefinition:u}=t;return a&&s.includes(a)?iI({tournamentRecord:n,drawDefinition:u,participantId:a,matchUpId:c,matchUp:i}):sI({tournamentRecord:n,drawDefinition:u,participantId:a,matchUpId:c,matchUp:i})}function hl({tournamentRecord:t,drawDefinition:e,tieMatchUpId:r,event:n}){if(!t)return{error:$};if(!e)return{error:sn};if(!n)return{error:jr};let o=Me({drawDefinition:e}),{matchUp:i}=Bt({matchUpId:r,drawDefinition:e,matchUpsMap:o});if(!i)return{error:Le};let{matchUp:s,structure:a}=Bt({tournamentParticipants:t.participants,matchUpId:r,inContext:!0,drawDefinition:e,matchUpsMap:o,event:n});if(!s)return{error:Le};let{collectionPosition:c,drawPositions:u,collectionId:p,matchUpTieId:m,matchUpType:d}=s;if(d&&!kc([kt,xt],d))return{error:lr};let{positionAssignments:l}=Ct({structure:a}),f=l?.filter(P=>u?.includes(P.drawPosition)),{matchUp:g}=Bt({matchUpId:m,drawDefinition:e,matchUpsMap:o}),I=g?.sides?.map(St)??[],h=f?.map(St)??[],S=[...I,...h],{participants:T}=Gt({tournamentRecord:t,participantFilters:{participantTypes:[Ft],participantIds:S}}),{matchUp:y}=Bt({matchUpId:m,inContext:!0,drawDefinition:e,matchUpsMap:o}),E=We({matchUp:g,drawDefinition:e,structure:a,event:n})?.tieFormat;return{inContextDualMatchUp:y,inContextTieMatchUp:s,relevantAssignments:f,collectionPosition:c,teamParticipants:T,collectionId:p,matchUpType:d,dualMatchUp:g,tieMatchUp:i,tieFormat:E,structure:a,...C}}function aI(t){let e=hl(t);if(e.error)return e;let r="replaceTieMatchUpParticipantid",{existingParticipantId:n,tournamentRecord:o,newParticipantId:i,drawDefinition:s,substitution:a,event:c}=t;if(!n||!i)return _({result:{error:ie},stack:r});if(n===i)return{...C};let{inContextDualMatchUp:u,inContextTieMatchUp:p,collectionPosition:m,collectionId:d,dualMatchUp:l,tieMatchUp:f,tieFormat:g}=e,I=p?.matchUpType,h=p?.sides?.find(G=>G.participant?.participantId===n||G.participant?.individualParticipantIds?.includes(n));if(!h)return{error:re};let S=Gt({tournamentRecord:o,participantFilters:{participantIds:[n,i]}})?.participants??[];if(S.length!==2)return _({result:{error:ie},stack:r});if(S[0].participantType!==S[1].participantType)return _({result:{error:An},stack:r});let{appliedPolicies:T}=Tt({tournamentRecord:o,drawDefinition:s,event:c}),y=t.policyDefinitions?.[rr]??T?.[rr]??Ss[rr],E=S.find(({participantId:G})=>G===i);if((t.enforceGender??y?.participants?.enforceGender)!==!1&&[zt,oe].includes(p?.gender)&&p?.gender!==E?.person?.sex)return{error:Li,info:"Gender mismatch"};let A=y?.processCodes?.substitution;va({tournamentId:o.tournamentId,eventId:c.eventId,inContextDualMatchUp:u,drawDefinition:s,dualMatchUp:l});let U=l?.sides?.find(({sideNumber:G})=>G===h.sideNumber);if(!U)return _({result:{sideNumber:h.sideNumber,existingParticipantId:n,error:ve},stack:r});if(p?.sides?.flatMap(G=>G.participant?.individualParticipantIds||G.participant?.participantId||[])?.includes(i))return _({result:{error:Zu},stack:r});let D=u?.sides?.find(({sideNumber:G})=>G===h.sideNumber)?.participantId,M=U.lineUp,R=M?.find(({participantId:G})=>i===G),b=M?.reduce((G,k)=>k.substitutionOrder>G?k.substitutionOrder:G,0),v=M?.map(G=>{let k=J(G,!1,!0);if(![n,i].includes(k.participantId))return k;if(!a&&[n,i].includes(k.participantId)&&(k.collectionAssignments=k.collectionAssignments?.filter(H=>!(H.collectionPosition===m&&H.collectionId===d))),a&&n===k.participantId&&(k.collectionAssignments=k.collectionAssignments.map(H=>H.collectionPosition===m&&H.collectionId===d&&H.substitutionOrder===void 0?{...H,substitutionOrder:b}:H)),k.participantId===i){k.collectionAssignments||(k.collectionAssignments=[]);let H={collectionId:d,collectionPosition:m};a&&(H.previousParticipantId=n,H.substitutionOrder=(b??0)+1),k.collectionAssignments.push(H)}return k})??[];if(!R){let G={collectionId:d,collectionPosition:m};a&&(G.substitutionOrder=(b??0)+1,G.previousParticipantId=n);let k={collectionAssignments:[G],participantId:i};v.push(k)}let O=I===xt,{assignedParticipantIds:x}=Cp({lineUp:M,collectionPosition:m,collectionId:d}),{assignedParticipantIds:F}=Cp({lineUp:v,collectionPosition:m,collectionId:d});if(U.lineUp=v,D&&g){let G=Qi({participantId:D,lineUp:v,drawDefinition:s,tieFormat:g});if(G.error)return _({result:G,stack:r})}else console.log("team participantId not found");let w,L;if(O){let{tournamentRecord:G}=t,k=In({participantIds:F,tournamentRecord:G});if(!k.participant){let q=vn({returnParticipant:!0,pairOverride:!0,tournamentRecord:G,participant:{participantRole:xe,individualParticipantIds:F,participantType:ft}});if(q.error)return _({result:q,stack:r});w=q.participant?.participantId}k=In({participantIds:x,tournamentRecord:G});let H=k.participant?.participantId;H&&zi({participantIds:[H],tournamentRecord:G}).success&&(L=H)}if(a||h.substitutions?.length===1){if(a)A&&f&&(f.processCodes=pt([...f?.processCodes??[],...A]));else for(let G of A||[]){let k=f?.processCodes?.lastIndexOf(G);k!==void 0&&f?.processCodes?.splice(k,1)}f&&gt({tournamentId:o?.tournamentId,matchUp:f,context:r,drawDefinition:s})}return l&&gt({tournamentId:o?.tournamentId,matchUp:l,context:r,drawDefinition:s}),{...C,modifiedLineUp:v,participantRemoved:L,participantAdded:w}}function ky({collectionPosition:t,teamParticipantId:e,dualMatchUpSide:r,drawDefinition:n,participantIds:o,collectionId:i}){if(!i||!t||!Array.isArray(o))return{modifiedLineUp:r?.lineUp||[],error:V};let s=r?.lineUp||ds({participantId:e,drawDefinition:n})?.lineUp,a=[],c=[];return{modifiedLineUp:s?.map(p=>{if(!o.includes(p.participantId))return p;let m=p.collectionAssignments?.filter(d=>{let l=d.collectionId===i&&d.collectionPosition===t;return l&&(d.previousParticipantId&&a.push(d.previousParticipantId),c.push({participantId:p.participantId,...d})),!l});return{participantId:p.participantId,collectionAssignments:m}}).filter(Boolean)||[],assignmentsRemoved:c,previousParticipantIds:a}}function Ux({individualParticipantIds:t,groupingParticipantId:e,tournamentRecord:r}){let n=(r.events||[]).filter(i=>i?.eventType===_e&&i?.entries?.some(s=>s.participantId===e)),o=i=>!t.includes(i.participantId);for(let i of n){i.entries=(i.entries||[]).filter(o);let{flightProfile:s}=Ht({event:i});s?.flights?.forEach(a=>{a.drawEntries=(a.drawEntries||[]).filter(o)}),i?.drawDefinitions?.forEach(a=>{a.entries=(a.entries||[]).filter(o)})}return{...C}}function om({individualParticipantIds:t,groupingParticipantId:e,removeFromOtherTeams:r,tournamentRecord:n}){let o="addIndividualParticipantIds";if(!n)return _({result:{error:$},stack:o});if(!e||!t)return _({result:{error:st},stack:o});let i=n.participants??[],s=i.find(m=>m.participantId===e);if(!s)return _({result:{error:re},stack:o});if(s?.participantType&&![Ft,zr].includes(s.participantType))return _({context:{participantType:s.participantType},result:{error:An},stack:o});let a=t.filter(m=>i.find(l=>l.participantId===m)?.participantType!==At);if(a.length)return _({result:{error:wr,invalidParticipantIds:a},stack:o});s.individualParticipantIds||(s.individualParticipantIds=[]);let c=s.individualParticipantIds,u=t.filter(m=>!c.includes(m));u.length&&(r&&vp({individualParticipantIds:u,tournamentRecord:n}),s.individualParticipantIds=s.individualParticipantIds.concat(...u));let{topics:p}=Lr();if(p.includes(or)){let m=i.find(({participantId:d})=>d===e);lt({topic:or,payload:{participants:[m]}})}return Ux({individualParticipantIds:t,groupingParticipantId:e,tournamentRecord:n}),{groupingParticipant:J(s,!1,!0),added:u.length,...C}}function im(t){let{updateParticipantName:e=!0,groupingParticipantId:r,removeFromOtherTeams:n,tournamentRecord:o,pairOverride:i,participant:s}=t;if(!o)return{error:$};if(!s)return{error:Fi};if(!s.participantId)return vn({tournamentRecord:o,participant:s});let{participant:a}=yo({participantId:s.participantId,tournamentRecord:o});if(!a)return vn({tournamentRecord:o,participant:s});let{participantRoleResponsibilties:c,individualParticipantIds:u,participantOtherName:p,participantName:m,participantRole:d,participantType:l,onlineResources:f,contacts:g,person:I}=s;if(l&&a.participantType!==l)return{error:uE};let h={};if(g&&(h.contacts=g),f&&(h.onlineResources=f),p&&Vt(p)&&(h.participantOtherName=p),m&&Vt(m)&&(h.participantName=m),Array.isArray(u)){let{participants:S}=Gt({participantFilters:{participantTypes:[At]},tournamentRecord:o}),T=S?.map(St);if(T){let y=u.filter(E=>Vt(E)&&T.includes(E));([zr,Wt].includes(l||a.participantType)||l===ft&&(y.length===2||i))&&(h.individualParticipantIds=y),a.participantType===lu.PAIR&&e&&(h.participantName=O1({individualParticipants:S,newValues:h}))}}return Object.keys(hd).includes(d)&&(h.participantRole=d),Object.keys(lu).includes(l)&&(h.participantType=l),Array.isArray(c)&&(h.participantRoleResponsibilties=c),a.participantType===lu.INDIVIDUAL&&I&&_1({updateParticipantName:e,existingParticipant:a,newValues:h,person:I}),Object.assign(a,nt(h)),r&&om({individualParticipantIds:[a.participantId],groupingParticipantId:r,removeFromOtherTeams:n,tournamentRecord:o}),lt({topic:or,payload:{tournamentId:o.tournamentId,participants:[a]}}),{participant:J(a),...C}}function O1({individualParticipants:t,newValues:e}){let r=e.individualParticipantIds,n=t.filter(({participantId:o})=>r.includes(o)).map(({person:o})=>o?.standardFamilyName).filter(Boolean).sort().join("/");return r.length===1&&(n+="/Unknown"),n}function _1({updateParticipantName:t,existingParticipant:e,newValues:r,person:n}){let o={},{standardFamilyName:i,standardGivenName:s,nationalityCode:a,personId:c,birthdate:u,tennisId:p,sex:m}=n;m&&Object.keys(Cm).includes(m)&&(o.sex=m);let d;if(Vt(c)&&(o.personId=c),a&&Vt(a)&&(x1(a)||a==="")&&(o.nationalityCode=a),i&&typeof Vt(i)&&i.length>1&&(o.standardFamilyName=i,d=!0),s&&typeof Vt(s)&&s.length>1&&(o.standardGivenName=s,d=!0),d&&t){let l=`${o.standardGivenName} ${o.standardFamilyName}`;r.participantName=l}u&&Nr(u)&&(o.birthdate=u),p&&Vt(p)&&(o.tennisId=p),Object.assign(e.person,o)}function x1(t){return ri.flatMap(({iso:e,ioc:r})=>[e,r]).filter(Boolean).includes(t)}function Sl(t){let e=hl(t);if(e.error)return e;let r="assignTieMatchUpParticipantId",n=t.teamParticipantId,{tournamentRecord:o,drawDefinition:i,participantId:s,event:a}=t;if(!s)return _({result:{error:ie},stack:r});if(t.sideNumber&&![1,2].includes(t.sideNumber))return _({result:{error:Kl},stack:r});let{inContextDualMatchUp:c,inContextTieMatchUp:u,relevantAssignments:p,collectionPosition:m,teamParticipants:d,collectionId:l,matchUpType:f,dualMatchUp:g,tieFormat:I}=e;if(u?.sides?.flatMap(B=>B.participant?.individualParticipantIds||B.participant?.participantId||[])?.includes(s))return _({result:{...C},stack:r});n=n??(t.sideNumber?c?.sides?.find(B=>B.sideNumber===t.sideNumber)?.participantId:void 0);let S=Gt({participantFilters:{participantIds:[s]},tournamentRecord:o})?.participants?.[0];if(!S)return _({result:{error:re},stack:r});let{appliedPolicies:T}=Tt({tournamentRecord:o,drawDefinition:i,event:a}),y=t.policyDefinitions?.[rr]??T?.[rr]??Ss[rr];if((t.enforceGender??y?.participants?.enforceGender)!==!1&&[zt,oe].includes(u?.gender)&&u?.gender!==S.person?.sex)return{error:Li,info:"Gender mismatch"};let{individualParticipantIds:P,participantType:A}=S;if(de(kt)(f)&&A!==At)return{error:An};let U=A===At?[s]:P,N=n&&d?.find(({participantId:B})=>B===n)||d?.find(({individualParticipantIds:B})=>ke(U,B));if(!N)return{error:af};if(n||(n=N.participantId),!n)return{error:re};let M=p?.find(B=>B.participantId===N?.participantId)?.drawPosition,R=g?.sides?.find(B=>B.participantId===n)?.sideNumber,b=u?.sides?.find(B=>M&&B.drawPosition===M)?.sideNumber,v=R??b??t.sideNumber;if(!I)return{error:vs};if(!I.collectionDefinitions?.find(B=>B.collectionId===l))return{error:tE};va({tournamentId:o.tournamentId,eventId:a.eventId,inContextDualMatchUp:c,drawDefinition:i,dualMatchUp:g});let x=g?.sides?.find(B=>B.sideNumber===v),F=u?.sides?.find(B=>B.sideNumber===v),G=(x?.lineUp??ds({participantId:n,drawDefinition:i})?.lineUp)?.filter(B=>B.collectionAssignments?.find(K=>K.collectionPosition===m&&K.collectionId===l&&!K.previousParticipantId))?.map(B=>B?.participantId),k=G?.length>1&&G||(A===ft?S.individualParticipantIds:[s]),H=ky({collectionPosition:m,teamParticipantId:n,dualMatchUpSide:x,drawDefinition:i,participantIds:k,collectionId:l});if(H.error)return _({result:H,stack:r});let{modifiedLineUp:W}=H,q;if(f===xt){if(A!==ft){let B=aM({collectionPosition:m,teamParticipantId:n,drawDefinition:i,modifiedLineUp:W,participantId:s,collectionId:l,tieFormat:I});if(B?.error)return _({result:B,stack:r});if(B=Y({side:F}),B.error)return B;q=B.deletedParticipantId,x&&(x.lineUp=W),g&&gt({tournamentId:o?.tournamentId,matchUp:g,context:r,drawDefinition:i})}else if(A===ft)for(let B of k)aM({collectionPosition:m,teamParticipantId:n,drawDefinition:i,modifiedLineUp:W,participantId:B,collectionId:l,tieFormat:I})}else{let B=aM({collectionPosition:m,teamParticipantId:n,drawDefinition:i,modifiedLineUp:W,participantId:s,collectionId:l,tieFormat:I});if(B?.error)return B}if(x&&(x.lineUp=W),g&&gt({tournamentId:o?.tournamentId,matchUp:g,context:r,drawDefinition:i}),q){let{error:B}=zi({participantIds:[q],tournamentRecord:o});B&&console.log("cleanup")}return{...C,modifiedLineUp:W};function Y({side:B}){let K;if(B.participant){let X=B.participant.individualParticipantIds||[];if(X.filter(Boolean).length===1){let{participant:ot}=In({participantIds:X,tournamentRecord:o});X.push(s);let{participant:z}=In({participantIds:X,tournamentRecord:o});if(!z&&ot){ot.individualParticipantIds=X;let Q=im({pairOverride:!0,tournamentRecord:o,participant:ot});if(Q.error)return Q}else K=ot?.participantId}}else{let j=vn({participant:{individualParticipantIds:[s],participantRole:xe,participantType:ft},pairOverride:!0,tournamentRecord:o});if(j.error)return j}return{...C,deletedParticipantId:K}}}function aM({collectionPosition:t,teamParticipantId:e,drawDefinition:r,modifiedLineUp:n,participantId:o,collectionId:i,tieFormat:s}){let a=ds({participantId:e,drawDefinition:r})?.lineUp,c=(n||a)?.find(p=>p?.participantId===o),u={collectionId:i,collectionPosition:t};if(c)c.collectionAssignments.push(u);else{let p={collectionAssignments:[u],participantId:o};n.push(p)}return Qi({participantId:e,lineUp:n,drawDefinition:r,tieFormat:s})}function cM(t){let{tournamentRecord:e,drawDefinition:r,participantId:n,event:o}=t,i="removeTieMatchUpParticiapantId";if(!n)return _({result:{error:ie},stack:i});let s=hl(t);if(s.error)return s;let{appliedPolicies:a}=Tt({tournamentRecord:e,drawDefinition:r,event:o}),u=(t.policyDefinitions?.[rr]??a?.[rr]??Ss[rr])?.processCodes?.substitution,{inContextDualMatchUp:p,inContextTieMatchUp:m,relevantAssignments:d,collectionPosition:l,teamParticipants:f,collectionId:g,matchUpType:I,dualMatchUp:h,tieMatchUp:S,tieFormat:T}=s;if(!h)return _({result:{error:Tr},stack:i});let y=m?.sides?.find(R=>R.participant?.participantId===n||R.participant?.individualParticipantIds?.includes(n));if(!y)return _({result:{error:re},stack:i});let E=t.policyDefinitions?.[tn]??a?.[tn];if(!y.substitutions?.length&&(Ie({score:m?.score})||m?.winningSide)&&E?.requireParticipantsForScoring!==!1)return _({result:{error:LE},stack:i});let P=p?.sides?.find(({sideNumber:R})=>R===y.sideNumber)?.participantId;if(!P)return _({result:{error:re},stack:i});let A=Gt({participantFilters:{participantIds:[n]},tournamentRecord:e})?.participants?.[0];if(!A)return _({result:{error:re},stack:i});if(I===kt&&A.participantType===ft)return _({result:{error:Li},stack:i});let U=A.participantType===At?[n]:A.individualParticipantIds;va({tournamentId:e.tournamentId,eventId:o.eventId,inContextDualMatchUp:p,drawDefinition:r,dualMatchUp:h});let N=h.sides?.find(({sideNumber:R})=>R===y.sideNumber);if(!N&&(h.sides?.filter(({lineUp:R})=>!R).length||0)<2){let R=f?.map(({participantId:b})=>({drawPosition:d?.find(v=>v.participantId===b)?.drawPosition,teamParticipantId:b}));N=h.sides?.find(b=>R?.find(({drawPosition:v})=>v===b.drawPosition)?.teamParticipantId===P)}if(!N)return _({result:{error:re,context:{participantId:n}}});let{modifiedLineUp:D,previousParticipantIds:M}=ky({collectionPosition:l,teamParticipantId:P,dualMatchUpSide:N,participantIds:U,drawDefinition:r,collectionId:g});if(N.lineUp=D,P&&T&&Qi({participantId:P,lineUp:D,drawDefinition:r,tieFormat:T}),I===xt&&A.participantType===At){let R=m?.sides?.find(O=>O.sideNumber===N?.sideNumber),{participantId:b}=R??{},v=b&&Gt({participantFilters:{participantIds:[b]},tournamentRecord:e,withDraws:!0})?.participants?.[0];if(v){let O=v?.individualParticipantIds?.filter(x=>x!==n)??[];if(M&&O.push(...M),O.length>2)return _({result:{error:wr},stack:i});if(v.draws?.length){if(O.length===1){let{participant:x}=In({participantIds:O,tournamentRecord:e});if(!x){let w=vn({participant:{participantRole:xe,individualParticipantIds:O,participantType:ft},pairOverride:!0,tournamentRecord:e});if(w.error)return _({result:w,stack:i})}}}else if(O.length){v.individualParticipantIds=O;let x=im({participant:v,pairOverride:!0,tournamentRecord:e});if(x.error)return _({result:x,stack:i})}else{let x=zi({participantIds:[b],tournamentRecord:e});x.error&&console.log("cleanup",{result:x})}}else return _({result:{error:re},stack:i})}if(y.substitutions?.length===1&&!m?.sides?.find(b=>b.sideNumber!==y.sideNumber)?.substitutions?.length&&S?.processCodes?.length){for(let b of u||[]){let v=S.processCodes.lastIndexOf(b);S.processCodes.splice(v,1)}gt({tournamentId:e?.tournamentId,matchUp:S,context:i,drawDefinition:r})}return gt({tournamentId:e?.tournamentId,matchUp:h,context:i,drawDefinition:r}),{...C,modifiedLineUp:D}}function cI(t){let e=et(t,[{[ne]:!0,[Ce]:!0,[ln]:!0}]);if(e.error)return e;let{drawDefinition:r,sideNumber:n,matchUpId:o,event:i}=t;if(n&&![1,2].includes(n))return{error:V,sideNumber:n};let{matchUp:s,structure:a}=Bt({drawDefinition:r,matchUpId:o,event:i});return s?pr({structure:a})?(s.sides?.forEach(c=>{(!n||c.sideNumber===n)&&delete c.participantId}),gt({tournamentId:t.tournamentRecord?.tournamentId,context:"assignSideParticipant",drawDefinition:r,matchUp:s}),{...C}):{error:Um}:{error:Le}}function Px({matchUpStatuses:t=[Nt,bt,Rt],drawPositionMatchUps:e,loserDrawPosition:r,sourceMatchUps:n}){let o=e?.reduce((p,m)=>!p||m.roundNumber>p.roundNumber?m:p,void 0),i=o?.drawPositions?.find(p=>p!==r),s=n.filter(p=>p?.drawPositions?.includes(i)).map(p=>p.matchUpStatus),a=n.filter(p=>p?.drawPositions?.includes(r)).map(p=>p.matchUpStatus),c=ke(s||[],t),u=ke(a||[],t);return{sourceMatchUp:o,winnerHadMatchUpStatus:c,winnerMatchUpStatuses:s,loserHadMatchUpStatus:u,loserMatchUpStatuses:a}}function Dx({inContextDrawMatchUps:t,sourceMatchUpStatus:e,targetDrawPosition:r,tournamentRecord:n,sourceMatchUpId:o,drawDefinition:i,structureId:s,dualMatchUp:a,roundNumber:c,matchUpsMap:u,event:p}){let{structure:m}=at({drawDefinition:i,structureId:s});if(m?.structureType===Ve)return{...C};u=u??Me({drawDefinition:i});let l=(u?.mappedMatchUps||{})[s].matchUps,{initialRoundNumber:f}=gs({drawPosition:r,matchUps:l}),g=l?.filter(h=>h.roundNumber>=c&&h.roundNumber!==f&&h.drawPositions?.includes(r)),{positionAssignments:I}=Ct({drawDefinition:i,structureId:s});for(let h of g??[])w1({inContextDrawMatchUps:t,sourceMatchUpStatus:e,positionAssignments:I,targetDrawPosition:r,tournamentRecord:n,sourceMatchUpId:o,drawDefinition:i,dualMatchUp:a,matchUpsMap:u,matchUp:h,event:p});return{...C}}function w1({inContextDrawMatchUps:t,positionAssignments:e,sourceMatchUpStatus:r,targetDrawPosition:n,tournamentRecord:o,sourceMatchUpId:i,drawDefinition:s,dualMatchUp:a,matchUpsMap:c,matchUp:u,event:p}){let m="removeSubsequentDrawPosition";if(a){let g=t.find(({matchUpId:h})=>u.matchUpId===h).sides?.find(h=>h.drawPosition===n)?.sideNumber,I=u.sides?.find(h=>h.sideNumber===g);I&&delete I.lineUp}u.drawPositions=(u.drawPositions||[]).map(f=>f===n?void 0:f).filter(Boolean);let l=e.filter(({drawPosition:f})=>u.drawPositions?.includes(f)).filter(f=>f.bye).length;return u.matchUpStatus=l&&Nt||[Rt,bt].includes(u.matchUpStatus)&&u.matchUpStatus||Xt,[bt,Rt].includes(u.matchUpStatus)&&(u.winningSide=void 0),u.matchUpStatusCodes&&vS({inContextDrawMatchUps:t,sourceMatchUpStatus:r,sourceMatchUpId:i,matchUpsMap:c,matchUp:u}),gt({tournamentId:o?.tournamentId,eventId:p?.eventId,context:`${m}-${n}`,drawDefinition:s,matchUp:u}),{...C}}function _c(t){let{dualWinningSideChange:e,inContextDrawMatchUps:r,tournamentRecord:n,drawDefinition:o,matchUpStatus:i,matchUpsMap:s,dualMatchUp:a,targetData:c,matchUpId:u,structure:p,event:m}=t,d=!!t.matchUp.collectionId,l=pr({structure:p}),{drawPositions:f,winningSide:g}=c.matchUp||{};if(!l&&!f)return{error:Ya};let{targetLinks:{loserTargetLink:I,winnerTargetLink:h,byeTargetLink:S},targetMatchUps:{loserMatchUp:T,winnerMatchUp:y,byeMatchUp:E}}=c,P=Hn({...t,matchUpStatus:i||Xt,removeWinningSide:!0});if(P.error)return P;let A;if(d){let{matchUpTieId:w,matchUpsMap:L}=t;if(A=lo({appliedPolicies:t.appliedPolicies,matchUpId:w,tournamentRecord:n,drawDefinition:o,matchUpsMap:L,event:m}),!e&&!A.removeWinningSide)return{...C}}if(l)return{...C};let{matchUps:U}=yt({afterRecoveryTimes:!1,inContext:!0,drawDefinition:o,matchUpsMap:s,structure:p}),{positionAssignments:N}=ge({structure:p}),D=g-1,M=1-D,R=f[D],b=f[M],{winnerParticipantId:v,loserParticipantId:O}=N?.reduce((w,L)=>(L.drawPosition===b&&(w.loserParticipantId=L.participantId),L.drawPosition===R&&(w.winnerParticipantId=L.participantId),w),{winnerParticipantId:void 0,loserParticipantId:void 0})||{},x=U.filter(w=>w.drawPositions?.includes(b));if(y&&uM({sourceMatchUpStatus:i,sourceMatchUpId:u,inContextDrawMatchUps:r,winningDrawPosition:R,winnerParticipantId:v,tournamentRecord:n,winnerTargetLink:h,drawDefinition:o,winnerMatchUp:y,dualMatchUp:a,matchUpsMap:s}),T){let{winnerHadMatchUpStatus:w}=Px({drawPositionMatchUps:x,loserDrawPosition:b,sourceMatchUps:U}),G=I.linkCondition===wn;if(w&&G){let H=Math.min(...T.drawPositions);Gy({targetLink:I,inContextDrawMatchUps:r,drawDefinition:o,drawPosition:H,matchUpsMap:s,event:m})}let k=L1({sourceMatchUpStatus:i,sourceMatchUpId:u,loserParticipantId:O,tournamentRecord:n,loserTargetLink:I,drawDefinition:o,loserMatchUp:T,dualMatchUp:a,matchUpsMap:s,event:m});if(k.error)return k}if(E){let w=Math.min(...E.drawPositions);Gy({sourceMatchUpId:u,targetLink:S,inContextDrawMatchUps:r,drawDefinition:o,drawPosition:w,matchUpsMap:s,event:m})}return{...C,...A&&{tieMatchUpResult:A}}}function uM({inContextDrawMatchUps:t,winningDrawPosition:e,sourceMatchUpStatus:r,winnerParticipantId:n,tournamentRecord:o,winnerTargetLink:i,sourceMatchUpId:s,drawDefinition:a,winnerMatchUp:c,matchUpsMap:u,dualMatchUp:p,event:m}){let{structureId:d,roundNumber:l}=c,f="removeDirectedWinner";if(i){let g=i.target.structureId,{structure:I}=at({drawDefinition:a,structureId:g});if(!I)return{error:wt};let{positionAssignments:h}=ge({structure:I});I.seedAssignments=(I.seedAssignments??[]).filter(N=>N.participantId!==n);let T=h?.find(N=>N.participantId===n)?.drawPosition,{matchUps:y}=yt({drawDefinition:a,structure:I,event:m}),E=y.map(N=>N.drawPositions).flat(1/0).filter(Boolean),P=yr(E);if((T?P[T]:void 0)===1)h?.forEach(N=>{N.participantId===n&&delete N.participantId});else{let N=y.filter(({drawPositions:D})=>D.includes(T));console.log("not removing from position assignments since instances > 1",{drawPositionMatchUps:N,winnerTargetLink:i})}let U=u?.drawMatchUps?.find(({matchUpId:N})=>N===c.matchUpId);U&&gt({tournamentId:o?.tournamentId,eventId:m?.eventId,matchUp:U,context:f,drawDefinition:a})}return l&&Dx({targetDrawPosition:e,inContextDrawMatchUps:t,sourceMatchUpStatus:r,tournamentRecord:o,sourceMatchUpId:s,drawDefinition:a,dualMatchUp:p,matchUpsMap:u,roundNumber:l,structureId:d}),{...C}}function L1({sourceMatchUpStatus:t,loserParticipantId:e,tournamentRecord:r,loserTargetLink:n,sourceMatchUpId:o,drawDefinition:i,loserMatchUp:s,matchUpsMap:a,dualMatchUp:c,event:u}){let p="removeDirectedLoser",m=n.target.structureId,{structure:d}=at({drawDefinition:i,structureId:m});if(!d)return{error:wt};let{positionAssignments:l}=ge({structure:d}),f=l?.find(g=>g.participantId===e)?.drawPosition;if(l?.forEach(g=>{g.participantId===e&&delete g.participantId}),d.seedAssignments=(d.seedAssignments??[]).filter(g=>g.participantId!==e),c){let g=s?.sides.reduce((S,T,y)=>T.drawPosition===f?y:S,void 0),I=a?.drawMatchUps?.find(({matchUpId:S})=>S===s.matchUpId),h=I?.sides?.[g];h&&(delete h.lineUp,gt({tournamentId:r?.tournamentId,eventId:u?.eventId,matchUp:I,context:p,drawDefinition:i}))}return{...C}}function Gy({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,matchUpsMap:o,targetLink:i,event:s}){let a=i.target.structureId,c="removeDirectedBye";Cn({color:"brightyellow",method:c,drawPosition:n});let u=gc({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,matchUpsMap:o,structureId:a,event:s});return _({result:u,stack:c})}function Nx(t){let{matchUpFormat:e,score:r}=t,n=r?.sets?.length,o=e&&Ye(e),{setFormat:i,finalSetFormat:s,bestOf:a}=o??{};return(a&&n===a&&s||i)?.timed||!1}function Mx({tournamentRecord:t,drawDefinition:e,structure:r,matchUp:n}){let o="attemptToSetMatchUpStatusBYE";if(n?.winningSide)return _({result:{error:da},context:{matchUpStatus:Nt},stack:o});let{positionAssignments:i}=ge({structure:r}),s=i?.filter(c=>c.bye).map(c=>c.drawPosition);return n.drawPositions?.some(c=>s?.includes(c))?(n.matchUpStatus=Nt,n.matchUpStatusCodes=[],gt({tournamentId:t?.tournamentId,context:o,drawDefinition:e,matchUp:n}),{...C}):_({result:{error:ZA},info:"matchUp does not include BYE",stack:o})}function Tl(t){let{tournamentRecord:e,appliedPolicies:r,drawDefinition:n,matchUpsMap:o,targetData:i,structure:s,event:a}=t,c="doubleExitAdvancement";if(s.structureType===Ve)return _({result:{...C},stack:c});let{matchUp:u,targetMatchUps:p,targetLinks:m}=i,{loserMatchUp:d,winnerMatchUp:l,loserTargetDrawPosition:f}=p,g=[bt,Rt].includes(d?.matchUpStatus)&&!d.sides?.map(I=>I.participantId??I.participant).filter(Boolean).length;if(d&&d.matchUpStatus!==Nt){let{loserTargetLink:I}=m;if(r?.progression?.doubleExitPropagateBye){let h=Cx({loserTargetDrawPosition:f,tournamentRecord:e,loserTargetLink:I,drawDefinition:n,loserMatchUp:d,matchUpsMap:o,event:a});if(h.error)return _({result:h,stack:c})}else if(!g){let{feedRound:h,drawPositions:S,matchUpId:T}=d,y=h?2:2-S.indexOf(f),E=Rx({...t,targetMatchUp:d,walkoverWinningSide:y,tournamentRecord:e,sourceMatchUp:u,matchUpId:T});if(E.error)return _({result:E,stack:c})}}if(l){let I=Rx({...t,matchUpId:l.matchUpId,targetMatchUp:l,tournamentRecord:e,sourceMatchUp:u});if(I.error)return _({result:I,stack:c})}return _({result:{...C},stack:c})}function Rx(t){let{inContextDrawMatchUps:e,tournamentRecord:r,drawDefinition:n,sourceMatchUp:o,targetMatchUp:i,matchUpsMap:s}=t,a=n.structures.find(({structureId:Y})=>Y===i.structureId),c=t.matchUpStatus===be?be:Te,u=t.matchUpStatus===be?Rt:bt,p="conditionallyAdvanceDrawPosition",m=s.drawMatchUps.find(Y=>Y.matchUpId===i.matchUpId);if(!m)return{error:Tr};let d=o?.drawPositions||[],l=m.drawPositions?.filter(Boolean),f=o?.structureId===i.structureId;if(f&&ke(d,l)&&(l=l.filter(Y=>!d.includes(Y))),f&&l.length>1)return _({result:{error:ja},stack:p});let{pairedPreviousMatchUpIsDoubleExit:g,pairedPreviousMatchUp:I}=CS(t),h=mr({matchUpId:i.matchUpId,inContextDrawMatchUps:e,drawDefinition:n}),{targetMatchUps:S,targetLinks:T}=h,{loserTargetDrawPosition:y,winnerMatchUp:E,loserMatchUp:P}=S;if(P){let{loserTargetLink:Y}=T,B=Cx({loserTargetDrawPosition:y,loserMatchUp:P,tournamentRecord:r,loserTargetLink:Y,drawDefinition:n,matchUpsMap:s});if(B.error)return _({result:B,stack:p})}let A=m.drawPositions?.filter(Boolean)||[],U=A.length===1,N=t.walkoverWinningSide||U&&Td({drawPosition:A[0],matchUpId:i.matchUpId,inContextDrawMatchUps:e})||void 0,D=[bt,Rt].includes(m.matchUpStatus)&&!A.length,M=m.finishingRound===1,R=D&&!M?c:u,b=e.find(Y=>Y.matchUpId===I.matchUpId),v=[],O;o&&(o?.structureId===b?.structureId?o.roundPosition<I?.roundPosition?O=1:O=2:i.feedRound?o.structureId===i.structureId?O=2:O=1:N&&(O=3-N));let x=t.matchUpStatus,F=I?.matchUpStatus;O===1?v=[{matchUpStatus:Vy(x),previousMatchUpStatus:x,sideNumber:1},{matchUpStatus:Vy(F),previousMatchUpStatus:F,sideNumber:2}]:O===2&&(v=[{matchUpStatus:Vy(F),previousMatchUpStatus:F,sideNumber:1},{matchUpStatus:Vy(x),previousMatchUpStatus:x,sideNumber:2}]),v.length&&(v=v.map(Y=>nt(Y)));let w=Hn({...t,winningSide:N,matchUp:m,matchUpStatusCodes:v,context:p,matchUpStatus:R});if(w.error)return _({result:w,stack:p});if(D)return Tl({...t,matchUpStatus:R,targetData:h});if(!E)return _({result:{...C},stack:p});let L=l.length===2?l[N-1]:l[0],{positionAssignments:G}=Ct({structure:a}),k=G?.find(Y=>Y.drawPosition===L),H=s.drawMatchUps.find(Y=>Y.matchUpId===E.matchUpId),W=H?.drawPositions?.filter(Boolean),q=W.length===1;if(L){if(k?.bye){let Y=mr({matchUpId:H.matchUpId,inContextDrawMatchUps:e,drawDefinition:n});if(q){let B=W.filter(Boolean)[0],K=Td({drawPosition:B,matchUpId:H.matchUpId,inContextDrawMatchUps:e}),X=Hn({appliedPolicies:t.appliedPolicies,matchUpId:H.matchUpId,matchUp:H,matchUpStatus:u,matchUpStatusCodes:[],removeScore:!0,context:p,drawDefinition:n,winningSide:K});return X.error?_({result:X,stack:p}):ES({drawPositionToAdvance:B,matchUpId:H.matchUpId,inContextDrawMatchUps:e,drawDefinition:n,matchUpsMap:s})}else if([bt,Rt].includes(E.matchUpStatus)){let B=Tl({...t,matchUpId:H.matchUpId,matchUpStatus:R,targetData:Y});if(B.error)return _({result:B,stack:p})}return _({result:{...C},stack:p})}return Tc({matchUpId:E.matchUpId,drawPosition:L,inContextDrawMatchUps:e,drawDefinition:n})}else if(g){if(!H)return{error:Tr};if(q){let K=W[0],X=Td({matchUpId:i.matchUpId,inContextDrawMatchUps:e,drawPosition:K});console.log("existing drawPosition is winningSide",{walkoverWinningSide:X})}let Y=[bt,Rt].includes(H.matchUpStatus)?u:c,B=Hn({matchUpId:H.matchUpId,appliedPolicies:t.appliedPolicies,matchUp:H,matchUpStatusCodes:[],removeScore:!0,context:p,drawDefinition:n,matchUpStatus:Y});if(B.error)return _({result:B,stack:p});if(Y===c){let K=Tl({...t,matchUpId:i.matchUpId,matchUpStatus:Y,targetData:h});if(K.error)return K}}return _({result:{...C},stack:p})}function Cx(t){let{loserTargetDrawPosition:e,tournamentRecord:r,loserTargetLink:n,drawDefinition:o,matchUpsMap:i,event:s}=t,a=n?.target?.structureId,{structure:c}=at({drawDefinition:o,structureId:a});return c?Hr({drawPosition:e,tournamentRecord:r,drawDefinition:o,structureId:a,matchUpsMap:i,event:s}):{error:di}}function Vy(t){return t===Te?bt:t===be?Rt:t}function bx(t){let{tournamentRecord:e,drawDefinition:r,matchUpStatus:n,structure:o,matchUp:i}=t,s=!!(i.tieMatchUps&&!i.rondPosition&&t.inContextDrawMatchUps.find(h=>h.matchUpId===i.matchUpId).containerStructureId),a="attemptToSetMatchUpStatus",c=n===Nt,u=i.winningSide,p=[Te,be].includes(n),m=Da({matchUpStatus:n}),d=ug({matchUpStatus:n}),l=!m&&!d,f=t.matchUpTieId||u&&m&&!p,g=u&&p,I=()=>Hn({...t,removeScore:[co,bt].includes(n),matchUpStatus:n||Xt});return l&&{error:GI}||f&&pM(t)||g&&F1(t)||u&&_c(t)||d&&I()||c&&Mx({tournamentRecord:e,drawDefinition:r,structure:o,matchUp:i})||!m&&{error:GI}||p&&k1(t)||s&&pM(t)||_({result:{error:da},stack:a})}function F1(t){let e=_c(t);return e.error?e:Tl(t)}function k1(t){let e=pM({...t,removeScore:!0});return e.error?e:Tl(t)}function pM(t){let e="scoreModification";if(t.isCollectionMatchUp&&t.dualMatchUp?.winningSide&&!t.projectedWinningSide){let i=_c(t);if(i.error)return _({result:i,stack:e})}let n=!!t.matchUp.collectionId,o=Hn({...t,context:e});if(n){let{matchUpTieId:i,drawDefinition:s,matchUpsMap:a}=t,c=lo({tournamentRecord:t.tournamentRecord,appliedPolicies:t.appliedPolicies,matchUpId:i,event:t.event,drawDefinition:s,matchUpsMap:a});if(c.error)return _({result:c,stack:e});Object.assign(o,{tieMatchUpResult:c})}return _({result:o,stack:e})}function vx({drawDefinition:t,structure:e,matchUp:r}){let{drawPositions:n}=r,{positionAssignments:o}=Ct({drawDefinition:t,structure:e}),s=o?.filter(({drawPosition:m})=>n?.includes(m))?.map(m=>{let{extension:d}=mt({element:m,name:bo});return d?.value?.groupOrder}),{containerStructures:a}=cs({drawDefinition:t}),c=a[e.structureId];return{structureIds:js({drawDefinition:t,structureId:c})?.links?.source?.filter(m=>ke(s,m.source?.finishingPositions||[])).map(m=>m.source.structureId)}}function By({drawDefinition:t,structure:e,matchUp:r}){let n=[];if(e.finishingPosition===gi&&Eo({drawDefinition:t,structure:e})){let{structureIds:i}=vx({drawDefinition:t,structure:e,matchUp:r});i?.length&&n.push(...i)}return{connectedStructureIds:n}}function Ox(t){let e,{inContextDrawMatchUps:r,inContextMatchUp:n,drawDefinition:o,winningSide:i}=t,s=t.targetData.targetLinks?.winnerTargetLink;if(s.target.feedProfile===dn){let a=n.sides.find(({sideNumber:u})=>u!==i).participantId,c=r.find(u=>u.structureId===s.target.structureId&&u.roundNumber===s.target.roundNumber&&u.sides.some(({participantId:p})=>p===a));if(c?.matchUpStatus===Xt){let u=mr({matchUpId:c.matchUpId,inContextDrawMatchUps:r,drawDefinition:o});if(!vi({inContextDrawMatchUps:r,drawDefinition:o,targetData:u})){let{structure:m}=at({structureId:c.structureId,drawDefinition:o}),d=Ct({structure:m}).positionAssignments;for(let l of d||[])if(l.participantId===a){let f=n.sides.find(({sideNumber:g})=>g===i).participantId;if(l.participantId=f,m?.positionAssignments)m.positionAssignments=d;else if(m?.structures){let g=Object.assign({},...(d||[]).map(I=>({[I.drawPosition]:I.participantId})));for(let I of m.structures)I.positionAssignments?.forEach(h=>h.participantId=g[h.drawPosition])}Oo({tournamentId:t.tournamentRecord?.tournamentId,event:t.event,drawDefinition:o,structure:m}),e=!0}}}}return{...C,qualifierReplaced:e}}function _x(t){let e,{inContextDrawMatchUps:r,inContextMatchUp:n,drawDefinition:o,winningSide:i}=t,s=t.targetData.targetLinks?.winnerTargetLink;if(s.target.feedProfile===dn){let a=n.sides.find(({sideNumber:p})=>p===i)?.participantId,c=r.filter(p=>p.structureId===s.target.structureId&&p.roundNumber===s.target.roundNumber&&p.sides.some(({participantId:m,qualifier:d})=>d&&!m)),u=yn(c);if(u?.matchUpStatus===Xt){let p=mr({matchUpId:u.matchUpId,inContextDrawMatchUps:r,drawDefinition:o});if(!vi({inContextDrawMatchUps:r,drawDefinition:o,targetData:p})){let d=u.sides.find(g=>g.qualifier&&!g.participantId)?.drawPosition,{structure:l}=at({structureId:u.structureId,drawDefinition:o});if(!l)return{error:wt};let f=Ct({structure:l}).positionAssignments;for(let g of f||[])if(g.drawPosition===d&&!g.participantId){if(g.participantId=a,l.positionAssignments)l.positionAssignments=f;else if(l.structures){let I=Object.assign({},...(f||[]).map(h=>({[h.drawPosition]:h.participantId})));for(let h of l.structures)h.positionAssignments?.forEach(S=>S.participantId=I[S.drawPosition])}Oo({tournamentId:t.tournamentRecord?.tournamentId,event:t.event,drawDefinition:o,structure:l}),e=!0}}}}return{...C,qualifierPlaced:e}}function xx(t){let e="attemptToSetWinningSide",r,{appliedPolicies:n,disableAutoCalc:o,drawDefinition:i,dualMatchUp:s,winningSide:a,structure:c,matchUp:u}=t;if(s?._disableAutoCalc&&o!==!1)return bd(t);if(u.winningSide&&u.winningSide!==a){let{connectedStructureIds:l}=By({drawDefinition:i,structure:c,matchUp:u});l.length&&(console.log({connectedStructureIds:l}),r=!0);let f=_c(t);if(f.error)return f}let p=nT(t);if(p.error)return _({result:p,stack:e});let m,d;return t.qualifierChanging&&n?.[nu]?.autoReplaceQualifiers&&(m=Ox(t).qualifierReplaced),t.qualifierAdvancing&&n?.[nu]?.autoPlaceQualifiers&&(d=_x(t).qualifierPlaced),_({result:nt({...C,...p,connectedStructures:r,qualifierReplaced:m,qualifierPlaced:d}),stack:e})}var Hy={drawPositionToRemove:"green",iteration:"brightred",winner:"green",loser:"brightred"};function mM(t){let{inContextDrawMatchUps:e,appliedPolicies:r,drawDefinition:n,matchUpsMap:o,targetData:i,matchUp:s}=t,{matchUpId:a}=s,{iteration:c=0}=t;c+=1;let u="removeDoubleExit";Cn({color:"brightyellow",method:u,matchUpId:a,iteration:c,keyColors:Hy});let{targetMatchUps:{loserMatchUp:p,winnerMatchUp:m,loserTargetDrawPosition:d},targetLinks:{loserTargetLink:l}}=i;if(m&&m.matchUpStatus!==Nt){let{stage:I,roundNumber:h,roundPosition:S,structureName:T}=m;Cn({winner:"winner",roundPosition:S,structureName:T,roundNumber:h,keyColors:Hy,stage:I}),wx({...t,targetMatchUp:m,sourceMatchUp:s,iteration:c})}let f=p?.matchUpStatus===Nt&&(p?.feedRound||p?.roundNumber===1),g=i?.targetLinks?.loserTargetLink?.linkCondition===wn;if(f&&g){let I=e.filter(({roundNumber:E,structureId:P})=>P===s.structureId&&E===1),h=I.map(({roundPosition:E})=>E),S=Ee(h.sort(),2).find(E=>E.includes(s.roundPosition));if((I.filter(({roundPosition:E})=>S.includes(E))?.map(({matchUpStatus:E})=>E)).every(E=>[be,Te].includes(E)))return _({result:{...C},stack:u})}if(p&&(p.matchUpStatus!==Nt||f)){let I=e.find(({matchUpId:A})=>A===p.matchUpId),{structure:h}=at({drawDefinition:n,structureId:I.structureId}),{stage:S,roundNumber:T,roundPosition:y,feedRound:E,structureName:P}=p;if(Cn({loser:"loser",roundPosition:y,structureName:P,roundNumber:T,keyColors:Hy,feedRound:E,stage:S}),r?.progression?.doubleExitPropagateBye||f)Gy({drawPosition:d,targetLink:l,inContextDrawMatchUps:e,drawDefinition:n,matchUpsMap:o});else{let A=wx({...t,targetMatchUp:p,structure:h,iteration:c});if(A.error)return _({result:A,stack:u})}}return _({result:{...C},stack:u})}function wx(t){let{inContextDrawMatchUps:e,appliedPolicies:r,drawDefinition:n,sourceMatchUp:o,targetMatchUp:i,matchUpsMap:s,structure:a,iteration:c}=t,u="conditionallyRemoveDrawPosition";Cn({method:u,structureName:a?.structureName,iteration:c});let p=mr({matchUpId:i.matchUpId,inContextDrawMatchUps:e,drawDefinition:n}),{targetMatchUps:{winnerMatchUp:m}}=p,d=s?.drawMatchUps.find(y=>y.matchUpId===i.matchUpId),l=[],f,g,I;if(i.feedRound)I=m?.drawPositions?.filter(Boolean)?.find(E=>i.drawPositions.includes(E));else if(!o)I=jt(i?.drawPositions||[],m?.drawPositions||[])?.[0];else if(g=bS({structureId:a.structureId,matchUp:o,matchUpsMap:s})?.pairedPreviousMatchUp,f=[Te,be].includes(g?.matchUpStatus),l=g?.drawPositions?.filter(Boolean)||[],[...se,Nt].includes(g?.matchUpStatus)||g?.winningSide){let E=o.drawPositions||[],P=i.drawPositions?.filter(Boolean);ke(E,P)&&(P=P?.filter(U=>!E.includes(U))),I=E.concat(l).find(U=>P?.includes(U))}if(m&&I){let{stage:y,roundNumber:E,roundPosition:P,structureName:A}=m;Cn({method:"removeDirectedWinner",drawPositionToRemove:I,color:"brightgreen",roundPosition:P,structureName:A,roundNumber:E,keyColors:Hy,stage:y}),uM({winningDrawPosition:I,winnerMatchUp:m,inContextDrawMatchUps:e,drawDefinition:n,matchUpsMap:s})}let h=mM({targetData:p,matchUp:i,inContextDrawMatchUps:e,appliedPolicies:r,drawDefinition:n,matchUpsMap:s,structure:a,iteration:c});if(h.error)return _({result:h,stack:u});let S=G1({pairedPreviousDoubleExit:f,noContextTargetMatchUp:d}),T=!f;return h=Hn({...t,matchUpId:i.matchUpId,matchUp:d,removeWinningSide:!0,matchUpStatusCodes:[],context:u,matchUpStatus:S,removeScore:T,score:{scoreStringSide1:"",scoreStringSide2:"",sets:void 0}}),h.error?_({result:h,stack:u}):{...C}}function G1({pairedPreviousDoubleExit:t,noContextTargetMatchUp:e}){return e.matchUpStatus===Nt?Nt:t?[be,Rt].includes(e?.matchUpStatus)?Rt:bt:Xt}function Lx(t){let e,{inContextDrawMatchUps:r,inContextMatchUp:n,drawDefinition:o}=t,i=t.targetData.targetLinks?.winnerTargetLink;if(i.target.feedProfile===dn){let s=n.sides?.find(({sideNumber:c})=>c===n.winningSide)?.participantId,a=r.find(c=>c.structureId===i.target.structureId&&c.roundNumber===i.target.roundNumber&&c.sides?.some(({participantId:u})=>u===s));if(a&&a.matchUpStatus===Xt){let c=mr({matchUpId:a.matchUpId,inContextDrawMatchUps:r,drawDefinition:o});if(!vi({inContextDrawMatchUps:r,drawDefinition:o,targetData:c})){let{structure:p}=at({structureId:a.structureId,drawDefinition:o}),m=Ct({structure:p}).positionAssignments;for(let d of m||[])if(d.participantId===s){if(d.participantId=void 0,p?.positionAssignments)p.positionAssignments=m;else if(p?.structures){let l=Object.assign({},...(m||[]).map(f=>({[f.drawPosition]:f.participantId})));for(let f of p?.structures||[])f.positionAssignments?.forEach(g=>g.participantId=l[g.drawPosition])}Oo({tournamentId:t.tournamentRecord?.tournamentId,event:t.event,drawDefinition:o,structure:p}),e=!0}}}}return{qualifierRemoved:e}}function kx(t){let{matchUp:e,matchUpStatus:r,score:n,winningSide:o}=t,i="noDownStreamDependencies";if([Te,be].includes(e?.matchUpStatus)&&![Te,be].includes(r)){let I=mM(t);if(I.error)return _({result:I,stack:i})}let a=r===Te,c=Ie({score:n})&&!a&&(t.isCollectionMatchUp&&!t.projectedWinningSide||!o),u=t?.inContextMatchUp?.collectionId&&Nx(t.inContextMatchUp),p=t.removeScore||!u&&![un,vr].includes(r||un),m=t.isCollectionMatchUp&&t.dualMatchUp.winningSide&&!t.projectedWinningSide||e.winningSide&&!o&&!Ie({score:n}),d=r&&r!==Xt,l=I=>{let h,{structure:S,drawDefinition:T,dualMatchUp:y,disableAutoCalc:E}=t;if(y?._disableAutoCalc&&E!==!1)return bd({...t,removeWinningSide:m});let{connectedStructureIds:P}=By({drawDefinition:T,structure:S,matchUp:e});P.length&&(console.log({connectedStructureIds:P}),h=!0),Object.assign(t,{removeScore:I});let A=_c(t);if(A.error)return A;if(t.removingQualifier&&t.appliedPolicies?.[nu]?.autoRemoveQualifiers){let U=Lx(t);return{...C,connectedStructures:h,...U}}return{...C,connectedStructures:h}};if(m&&o&&t.isCollectionMatchUp)return Fx(t);let f=[co,vr].includes(r)&&t.dualWinningSideChange,g=(o||f)&&xx(t)||c&&l(p)||d&&bx(t)||m&&l(p)||e&&Fx({...t,removeScore:!0})||{...C};return _({result:g,stack:i})}function Fx(t){let e="ndd:scoreModification";if(t.isCollectionMatchUp&&t.dualMatchUp?.winningSide&&!t.projectedWinningSide&&!t.autoCalcDisabled){let o=_c(t);if(o.error)return o}let n=Hn({...t,context:e});if(t.isCollectionMatchUp){let{matchUpTieId:o,drawDefinition:i,event:s,matchUpsMap:a}=t,{removeWinningSide:c}=lo({tournamentRecord:t.tournamentRecord,appliedPolicies:t.appliedPolicies,matchUpId:o,drawDefinition:i,matchUpsMap:a,event:s});c&&console.log("REMOVE WINNING SIDE")}return _({result:n,stack:e})}function uI(t){let e=et(t,[{[ne]:!0,[Ce]:!0,[ln]:!0},{homeParticipantId:!0,[fn]:ie}]);if(e.error)return e;let r=Ns(t,[{[ss]:Ln,attr:{[ru]:!0}}]);if(r.error)return r;let n=r?.matchUp?.matchUp?.sides?.map(m=>m?.participantId);if(t.homeParticipantId&&!n?.includes(t.homeParticipantId))return{error:mn};let{disableNotice:o,homeParticipantId:i,removePriorValues:s,tournamentRecord:a,drawDefinition:c,matchUpId:u}=t;return Jr({duplicateValues:!1,removePriorValues:s,tournamentRecord:a,drawDefinition:c,disableNotice:o,matchUpId:u,timeItem:{itemType:pd,itemValue:i}})}function dM({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Yo({timeItems:r?.timeItems||[],itemType:Pp});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{timeModifiers:n}:e}function Jo(t){let e="addMatchUpScheduledTime",r=t.matchUp,{removePriorValues:n,tournamentRecord:o,drawDefinition:i,disableNotice:s,scheduledTime:a,matchUpId:c}=t;if(!c)return _({result:{error:cr},stack:e});if(!Yc(a))return _({result:{error:Po},stack:e});if(!r){let I=Bt({drawDefinition:i,matchUpId:c});if(I.error)return _({result:I,stack:e});r=I.matchUp}let u=Pt(a),p=Ws({matchUp:r}).scheduledDate,m=u&&!p;if((dM({matchUp:r}).timeModifiers||[])?.length){let I=lM({disableNotice:!0,removePriorValues:n,tournamentRecord:o,timeModifiers:[],drawDefinition:i,matchUpId:c,matchUp:r});if(I?.error)return _({result:I,stack:e})}let f=Za(a,!0,m);return Jr({duplicateValues:!1,removePriorValues:n,tournamentRecord:o,drawDefinition:i,disableNotice:s,matchUpId:c,timeItem:{itemType:qi,itemValue:f}})}function lM({removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,timeModifiers:o,matchUpId:i,matchUp:s}){let a="addMatchUpTimeModifiers";if(!i)return _({result:{error:cr},stack:a});if(o!==void 0&&!Array.isArray(o))return _({info:ai("timeModifiers"),result:{error:V},stack:a});if(!s){let l=Bt({drawDefinition:r,matchUpId:i});if(l.error)return _({result:l,stack:a});s=l.matchUp}let c=dM({matchUp:s}).timeModifiers||[],u=o.filter(l=>!c.includes(l));if(o.length&&!u.length)return{...C};if(u.some(l=>mS.includes(l))){c=c.filter(f=>!mS.includes(f));let l=Jo({disableNotice:!0,removePriorValues:t,scheduledTime:"",tournamentRecord:e,drawDefinition:r,matchUpId:i});if(l.error)return _({result:l,stack:a})}let m=o?.length?[...u,...c]:void 0;return Jr({duplicateValues:!1,removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,matchUpId:i,timeItem:{itemType:Pp,itemValue:m}})}function sm({scheduledDate:t,removePriorValues:e,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:i}){if(!i)return{error:cr};let s=t&&No.test(t);if(t&&!s)return{error:je};let c={itemValue:Pt(t),itemType:Yi};return Jr({duplicateValues:!1,removePriorValues:e,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:i,timeItem:c})}function am({removePriorValues:t,tournamentRecords:e,tournamentRecord:r,drawDefinition:n,disableNotice:o,courtDayDate:i,matchUpId:s,courtIds:a}){if(!r&&!e)return{error:$};if(!s)return{error:cr};let c=Bt({drawDefinition:n,matchUpId:s});if(c.error)return c;if(c?.matchUp?.matchUpType!==xr)return{error:lr};if(!(a===void 0||Array.isArray(a)&&a.length&&a.every(d=>typeof d=="string")))return{error:V,context:{courtIds:a}};let p;if(a){let d=e||r&&{[r.tournamentId]:r},l=Uo({tournamentRecords:d});if(l.error)return l;let f=l.courts?.filter(g=>a.includes(g.courtId));if(f?.length!==a.length)return{error:V,context:{courtIds:a}};p=f?.map(g=>({venueId:g.venueId,courtId:g.courtId}))}return Jr({duplicateValues:!1,removePriorValues:t,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:s,timeItem:{itemType:po,itemDate:i,itemValue:p}})}function sa({removePriorValues:t,tournamentRecords:e,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:i,venueId:s}){if(!r)return{error:$};if(!i)return{error:cr};if(s){let c=qo({tournamentRecords:e,tournamentRecord:r,venueId:s});if(c.error)return c}return Jr({duplicateValues:!1,removePriorValues:t,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:i,timeItem:{itemType:ji,itemValue:s}})}function Zi({removePriorValues:t,tournamentRecords:e,tournamentRecord:r,drawDefinition:n,disableNotice:o,courtDayDate:i,matchUpId:s,courtId:a}){if(!r&&!e)return{error:$};if(!s)return{error:cr};if(a){let u=ms({tournamentRecords:e,tournamentRecord:r,courtId:a});if(u.error)return u;let p=u.venue?.venueId;sa({tournamentRecords:e,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:s,venueId:p})}return Jr({duplicateValues:!1,removePriorValues:t,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:s,timeItem:{itemType:jo,itemDate:i,itemValue:a}})}function Rs(t,e){let r=JI.test(t)?t:Qt(t),n=Pt(t)||Pt(e)||Yn(new Date);return new Date(`${n}T${r}`).getTime()}function cm(t){let e="addMatchUpScheduleItems",r=et(t,[{drawDefinition:!0,matchUpId:!0},{schedule:!0,[He]:Kr}],e);if(r.error)return r;let{matchUpDependencies:n,inContextMatchUps:o}=t,{errorOnAnachronism:i=!1,checkChronology:s=!0,removePriorValues:a,tournamentRecords:c,tournamentRecord:u,drawDefinition:p,disableNotice:m,drawMatchUps:d,matchUpId:l,schedule:f,event:g}=t,I,h;if(d)I=d.find(O=>O.matchUpId===l);else{let O=Bt({drawDefinition:p,event:g,matchUpId:l});if(O.error)return O;I=O.matchUp}let{endTime:S,courtId:T,courtIds:y,courtOrder:E,resumeTime:P,homeParticipantId:A,scheduledDate:U,scheduledTime:N,startTime:D,stopTime:M,timeModifiers:R,venueId:b}=f;s&&(!n||!o)&&({matchUpDependencies:n,matchUps:o}=on({drawDefinition:p}));let v=n?.[l]?.matchUpIds;if(f.scheduledDate&&s&&v){let O=o?.filter(x=>(x.schedule?.scheduledDate||Pt(x.schedule?.scheduledTime))&&v.includes(x.matchUpId)).map(({schedule:x})=>{let F=_m(x);return new Date(F).getTime()});if(O?.length){let x=_m(f),F=new Date(x).getTime();if(Math.max(...O)>=F){if(i)return _({result:{error:wI},stack:e});h=wI}}}if(U!==void 0){let O=sm({disableNotice:!0,removePriorValues:a,tournamentRecord:u,drawDefinition:p,scheduledDate:U,matchUpId:l});if(O?.error)return _({result:O,stack:e,context:{scheduledDate:U}})}if(N!==void 0){let O=Jo({disableNotice:!0,removePriorValues:a,tournamentRecord:u,drawDefinition:p,scheduledTime:N,matchUpId:l,matchUp:I});if(O?.error)return _({result:O,stack:e,context:{scheduledTime:N}})}if(D!==void 0){let O=jy({disableNotice:!0,removePriorValues:a,tournamentRecord:u,drawDefinition:p,matchUpId:l,startTime:D,event:g});if(O?.error)return _({result:O,stack:e,context:{startTime:D}})}if(M!==void 0){let O=qy({disableNotice:!0,removePriorValues:a,tournamentRecord:u,drawDefinition:p,matchUpId:l,stopTime:M,event:g});if(O?.error)return _({result:O,stack:e,context:{stopTime:M}})}if(P!==void 0){let O=$y({disableNotice:!0,removePriorValues:a,tournamentRecord:u,drawDefinition:p,resumeTime:P,matchUpId:l,event:g});if(O?.error)return _({result:O,stack:e,context:{resumeTime:P}})}if(S!==void 0){let O=Yy({disableNotice:!0,removePriorValues:a,tournamentRecord:u,drawDefinition:p,matchUpId:l,endTime:S,event:g});if(O?.error)return _({result:O,stack:e,context:{endTime:S}})}if(y!==void 0){let O=am({disableNotice:!0,removePriorValues:a,tournamentRecord:u,drawDefinition:p,matchUpId:l,courtIds:y});if(O?.error)return _({result:O,stack:e,context:{courtIds:y}})}if(T!==void 0&&U!==void 0){let O=Zi({courtDayDate:U,disableNotice:!0,removePriorValues:a,tournamentRecords:c,tournamentRecord:u,drawDefinition:p,matchUpId:l,courtId:T});if(O?.error)return _({result:O,stack:e,context:{courtId:T}})}if(b!==void 0){let O=sa({disableNotice:!0,removePriorValues:a,tournamentRecords:c,tournamentRecord:u,drawDefinition:p,matchUpId:l,venueId:b});if(O?.error)return _({result:O,stack:e,context:{venueId:b}})}if(E!==void 0&&It(E)){let O=Wy({disableNotice:!0,removePriorValues:a,tournamentRecord:u,drawDefinition:p,courtOrder:E,matchUpId:l});if(O?.error)return _({result:O,stack:e,context:{courtOrder:E}})}if(R!==void 0){let O=lM({disableNotice:!0,removePriorValues:a,tournamentRecord:u,drawDefinition:p,timeModifiers:R,matchUpId:l,matchUp:I});if(O?.error)return _({result:O,stack:e,context:{timeModifiers:R}})}return Vt(A)&&uI({disableNotice:!0,homeParticipantId:A,removePriorValues:a,tournamentRecord:u,drawDefinition:p,matchUpId:l}),m||gt({tournamentId:u?.tournamentId,eventId:g?.eventId,context:e,drawDefinition:p,matchUp:I}),h?{...C,warnings:[h]}:{...C}}function Wy({removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,courtOrder:o,matchUpId:i}){if(!i)return{error:cr};if(o&&!It(o))return{error:V,info:"courtOrder must be numeric"};let s=o&&dt(o);return Jr({duplicateValues:!1,removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,matchUpId:i,timeItem:{itemType:Up,itemValue:s}})}function fM({removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,participantId:o,officialType:i,matchUpId:s}){if(!s)return{error:cr};if(!o)return{error:ie};if(e){let c=Gt({tournamentRecord:e,participantFilters:{participantTypes:[At],participantRoles:[dg]}}).participants??[];if(!Bo({tournamentParticipants:c,participantId:o}))return{error:re}}let a={itemType:"SCHEDULE.ASSIGNMENT.OFFICIAL",itemValue:o};return i&&(a.itemSubTypes=[i]),Jr({duplicateValues:!1,removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,matchUpId:s,timeItem:a})}function jy({removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,matchUpId:o,startTime:i,event:s}){if(!o)return{error:cr};if(!Yc(i))return{error:Po};let{matchUp:a}=Bt({drawDefinition:r,event:s,matchUpId:o}),{scheduledDate:c}=Ws({matchUp:a}),p=(a?.timeItems??[]).filter(m=>[$i,Di,Ni].includes(m?.itemType)).map(m=>Rs(m.itemValue,c)).reduce((m,d)=>!m||d<m?d:m,void 0);if(!p||Rs(i,c)<p){a?.timeItems&&(a.timeItems=a.timeItems.filter(l=>l.itemType!==xo));let m=Za(i,!0,!0);return Jr({duplicateValues:!1,removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,matchUpId:o,timeItem:{itemType:xo,itemValue:m}})}else return{error:NE}}function Yy({validateTimeSeries:t=!0,removePriorValues:e,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:i,endTime:s,event:a}){if(!i)return{error:cr};if(!Yc(s))return{error:Po};let{matchUp:c}=Bt({drawDefinition:n,event:a,matchUpId:i}),{scheduledDate:u}=Ws({matchUp:c}),m=(c?.timeItems??[]).filter(d=>[xo,Di,$i].includes(d?.itemType)).map(d=>Rs(d.itemValue,u)).reduce((d,l)=>!d||l>d?l:d,void 0);if(!t||!m||Rs(s,u)>m){c?.timeItems&&(c.timeItems=c.timeItems.filter(f=>f.itemType!==Ni));let d=Za(s,!0,!0);return Jr({duplicateValues:!1,removePriorValues:e,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:i,timeItem:{itemType:Ni,itemValue:d}})}else return{error:PE}}function qy({removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,matchUpId:o,stopTime:i,event:s}){if(!o)return{error:cr};if(!Yc(i))return{error:Po};let{matchUp:a}=Bt({drawDefinition:r,event:s,matchUpId:o}),{scheduledDate:c}=Ws({matchUp:a}),u=a?.timeItems??[];if(u.reduce((g,I)=>I.itemType===Ni||g,void 0))return{error:$I};let m=u.filter(g=>[xo,Di,$i].includes(g?.itemType)).sort((g,I)=>Rs(g.itemValue,c)-Rs(I.itemValue,c)),d=m[m.length-1],l=d&&d.itemType===$i,f=m.filter(g=>!l||g.createdAt!==d.createdAt).map(g=>Rs(g.itemValue,c)).reduce((g,I)=>!g||I>g?I:g,void 0);if(Rs(i,c)>f){if(a?.timeItems&&l){let h=d.createdAt;a.timeItems=a.timeItems.filter(S=>S.createdAt!==h)}let I={itemValue:Za(i,!0,!0),itemType:$i};return Jr({duplicateValues:!0,removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,matchUpId:o,timeItem:I})}else return{error:DE}}function $y({removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,resumeTime:o,matchUpId:i,event:s}){if(!i)return{error:cr};if(!Yc(o))return{error:Po};let{matchUp:a}=Bt({drawDefinition:r,event:s,matchUpId:i}),{scheduledDate:c}=Ws({matchUp:a}),u=a?.timeItems??[];if(u.reduce((g,I)=>I.itemType===Ni||g,void 0))return{error:$I};let m=u.filter(g=>[xo,Di,$i].includes(g?.itemType)).sort((g,I)=>Rs(g.itemValue,c)-Rs(I.itemValue,c)),d=m[m.length-1],l=d&&d.itemType===Di,f=m.filter(g=>!l||g.createdAt!==d.createdAt).map(g=>Rs(g.itemValue,c)).reduce((g,I)=>!g||I>g?I:g,void 0);if(Rs(o,c)>f){if(a?.timeItems&&l){let h=d.createdAt;a.timeItems=a.timeItems.filter(S=>S.createdAt!==h)}let I={itemValue:Za(o,!0,!0),itemType:Di};return Jr({duplicateValues:!0,removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,matchUpId:i,timeItem:I})}else return{error:RC}}function Gx({drawDefinition:t,matchUpStatus:e,matchUpsMap:r,winningSide:n,dualMatchUp:o,tieFormat:i,structure:s,matchUp:a,event:c,score:u}){let p=J(o,void 0,!0);for(let d of p?.tieMatchUps||[])d.matchUpId===a.matchUpId&&(d.winningSide=n,d.score=u,!Ie({score:u})&&!e?Object.assign(d,{...Ou}):e&&(d.matchUpStatus=e));i=i??We({matchUp:a,structure:s,drawDefinition:t,event:c})?.tieFormat;let{winningSide:m}=Dc({matchUp:p,drawDefinition:t,matchUpsMap:r,structure:s,tieFormat:i,event:c});return{projectedWinningSide:m}}function Vx(t){let{tournamentRecord:e,inContextMatchUp:r,structure:n,drawDefinition:o}=t,i=r.roundNumber,s=r.sides.find(P=>P.sideNumber===r.winningSide),a=r.sides.find(P=>P.sideNumber!==r.winningSide),{drawPosition:c,participantId:u}=s,{drawPosition:p,participantId:m}=a,d="swapWinnerLoser",{matchUps:l}=yt(t),f=l.filter(({drawPositions:P,roundNumber:A})=>P?.includes(c)&&A>i);Pr({changeWinner:!0})&&console.log({existingWinnerSubsequentMatchUps:f}),f.forEach(P=>{P.drawPositions=P.drawPositions?.map(A=>A===c?p:A)||[],gt({tournamentId:e?.tournamentId,eventId:t.event?.eventId,context:d,drawDefinition:o,matchUp:P})});let{stage:g,stageSequence:I}=n,h=o.structures.filter(({stage:P,stageSequence:A})=>P===g&&A>I).map(({structureId:P})=>P),{targetLinks:{loserTargetLink:S,winnerTargetLink:T}}=t.targetData,y=[S?.target.structureId,T?.target?.structureId].filter(Boolean);return o.structures.filter(({stage:P,structureId:A})=>P!==g&&y.includes(A)).forEach(({stage:P,stageSequence:A,structureId:U})=>{h.includes(U)||h.push(U),o.structures.filter(({stage:N,stageSequence:D})=>N===P&&D>A).forEach(({structureId:N})=>{h.includes(N)||h.push(N)})}),o.structures.filter(({structureId:P})=>h.includes(P)).forEach(P=>{let{positionAssignments:A}=Ct({structure:P}),U=A?.find(({participantId:D})=>D===u),N=A?.find(({participantId:D})=>D===m);U&&(U.participantId=m),N&&(N.participantId=u)}),Hn({...t,context:d})}function Fa(t){let e="setMatchUpStatus";t.matchUpStatus&&[bt,Te].includes(t.matchUpStatus)&&(t.score=void 0);let{allowChangePropagation:r,disableScoreValidation:n,tournamentRecords:o,tournamentRecord:i,disableAutoCalc:s,enableAutoCalc:a,drawDefinition:c,matchUpStatus:u,winningSide:p,matchUpId:m,event:d,score:l}=t;if(!c)return{error:Z};if(u&&[co,un,vr,Xt].includes(u)&&p)return{error:V,winningSide:p,matchUpStatus:u};if(![void 0,...Bh].includes(u))return _({result:{error:da},info:"matchUpStatus does not exist",stack:"setMatchUpStatus"});let f=Me({drawDefinition:c}),{matchUps:g}=ce({nextMatchUps:!0,tournamentRecord:i,inContext:!0,drawDefinition:c,matchUpsMap:f,event:d}),I=f.drawMatchUps.find(k=>k.matchUpId===m),h=g?.find(k=>k.matchUpId===m);if(!I||!g)return{error:Le};if((I.winningSide||p)&&u===Nt)return{context:"Cannot have Bye with winningSide",error:Yl,matchUpStatus:u};let S=h?.structureId,{structure:T}=at({drawDefinition:c,structureId:S}),y=de(Wt)(I.matchUpType),E=h?.drawPositions?.filter(Boolean),P=h?.matchUpTieId,A=mr({matchUpId:P||m,inContextDrawMatchUps:g,drawDefinition:c});Object.assign(t,{inContextDrawMatchUps:g,inContextMatchUp:h,matchUpTieId:P,matchUpsMap:f,targetData:A,structure:T,matchUp:I});let U=vi(t),N;if(y){if(s)Ut({extension:{name:ha,value:!0},element:I});else if(a){let k=I.winningSide,{winningSide:H,scoreStringSide1:W,scoreStringSide2:q,set:Y}=Dc({drawDefinition:c,matchUpsMap:f,structure:T,matchUp:I,event:d}),B={scoreStringSide1:W,scoreStringSide2:q,sets:Y?[Y]:[]};if(N=H!==k,U&&N)return _({stack:"winningSideWithDownstreamDependencies",result:{error:Nm},context:{winningSide:p,matchUp:I}});gr({name:ha,element:I}),Object.assign(t,{winningSide:H,dualWinningSideChange:N,projectedWinningSide:H,score:B})}va({tournamentId:i?.tournamentId,inContextDualMatchUp:h,eventId:d?.eventId,dualMatchUp:I,drawDefinition:c})}if(y&&u&&[ac].includes(u))return{info:"Not supported for matchUpType: TEAM",error:V};if(l&&!y&&!n){let k=I.matchUpFormat??T?.matchUpFormat??c?.matchUpFormat??d?.matchUpFormat,H=Yg({existingMatchUpStatus:I.matchUpStatus,matchUpFormat:k,matchUpStatus:u,winningSide:p,score:l});if(H.error)return H}let D=Tt({policyTypes:[nu,tn],tournamentRecord:i,drawDefinition:c,event:d})?.appliedPolicies??{};ht(t.policyDefinitions)&&Object.assign(D,t.policyDefinitions);let M=B1({assignedDrawPositions:E,inContextMatchUp:h,appliedPolicies:D,drawDefinition:c,matchUpStatus:u,structure:T,matchUp:I});if(M?.error)return M;let R=h?.stage===ct&&h.finishingRound===1,b=R&&p,v=R&&I.winningSide&&!p&&(!t.matchUpStatus||t.matchUpStatus&&ug({matchUpStatus:t.matchUpStatus}))&&(!t.outcome||!Ie({outcome:t.outcome})),O=b&&p!==I.winningSide&&I.winningSide;if(Object.assign(t,{qualifierAdvancing:b,qualifierChanging:O,removingQualifier:v,appliedPolicies:D}),P){let{matchUp:k}=Bt({matchUpId:P,inContext:!0,drawDefinition:c,matchUpsMap:f,event:d});if(k){let H=We({matchUp:k,drawDefinition:c,structure:T,event:d})?.tieFormat,{projectedWinningSide:W}=Gx({drawDefinition:c,matchUpStatus:u,dualMatchUp:k,matchUpsMap:f,winningSide:p,tieFormat:H,structure:T,matchUp:I,event:d,score:l}),q=k.winningSide;N=W!==q;let Y=k._disableAutoCalc;Object.assign(t,{isCollectionMatchUp:!0,dualWinningSideChange:N,projectedWinningSide:W,autoCalcDisabled:Y,matchUpTieId:P,dualMatchUp:k,tieFormat:H})}}let x=Da({matchUpStatus:u});if(!P){if(U&&!p&&(u&&ug({matchUpStatus:u})||u&&[Te,be].includes(u)))return{error:Yl,activeDownstream:U,winningSide:p};if(p&&p===I.winningSide&&u&&!x)return{context:"winningSide must include directing matchUpStatus",error:Yl,directingMatchUpStatus:x,matchUpStatus:u}}let{schedule:F}=t;if(F){let k=cm({disableNotice:!0,tournamentRecords:o,tournamentRecord:i,drawDefinition:c,matchUpId:m,schedule:F});if(k.error)return k}let w=!y&&!N&&p&&I.winningSide&&I.winningSide!==p;if(r&&w&&I.roundPosition)return Vx(t);let L=p&&!P||t.projectedWinningSide;Cn({activeDownstream:U,matchUpWinner:L,method:e,winningSide:p});let G=!U&&kx(t)||L&&V1(t)||(x||t.autoCalcDisabled)&&Bx(t)||{error:xE};return _({result:G,stack:e})}function V1(t){let{matchUp:e,winningSide:r,matchUpTieId:n,dualWinningSideChange:o}=t;return r===e.winningSide||n&&!o?Bx(t):_({stack:"winningSideWithDownstreamDependencies",result:{error:Nm},context:{winningSide:r,matchUp:e}})}function Bx(t){let{tournamentRecord:e,matchUp:r,event:n}=t,o=t.isCollectionMatchUp&&r.winningSide&&!t.winningSide&&!Ie({score:t.score}),i=t.isCollectionMatchUp?t.matchUpStatus||o&&Xt||t.winningSide&&he||un:t.matchUpStatus||he,s=t.removeScore||[co,bt].includes(i)&&![un,vr].includes(i),a=Hn({...t,matchUpStatus:i,removeWinningSide:o,context:"sms",removeScore:s});if(a.error)return a;if(t.isCollectionMatchUp){let{matchUpTieId:c,drawDefinition:u,matchUpsMap:p}=t,m=lo({appliedPolicies:t.appliedPolicies,matchUpId:c,tournamentRecord:e,drawDefinition:u,matchUpsMap:p,event:n});if(m.error)return m;Object.assign(a,{tieMatchUpResult:m})}return a}function B1({assignedDrawPositions:t,inContextMatchUp:e,appliedPolicies:r,drawDefinition:n,matchUpStatus:o,structure:i,matchUp:s}){if(r?.[tn]?.requireParticipantsForScoring===!1)return{...C};let a=e?.sides?.map(p=>p.participantId).filter(Boolean).length,c=s?.sides?[]:Ct({structureId:i?.structureId,drawDefinition:n}).positionAssignments,u=a&&a===2||s.collectionId&&pr({structure:i})&&a&&a>=1||t?.length===2&&c?.filter(p=>t.includes(p.drawPosition)).every(p=>p.participantId);return o&&Vh.includes(o)&&!u?_({info:"matchUpStatus requires assigned participants",context:{matchUpStatus:o,requiredParticipants:u},result:{error:da}}):{...C}}function gM({tournamentRecord:t,drawDefinition:e,matchUpId:r,event:n}){if(!e)return{error:Z};let{matchUp:o}=Bt({drawDefinition:e,matchUpId:r,event:n});return o?.matchUpType!==xr?{error:lr}:Fa({enableAutoCalc:!0,tournamentRecord:t,drawDefinition:e,matchUpId:r,event:n})}function IM({drawDefinition:t,event:e,matchUpId:r}){if(!t)return{error:Z};if(!r)return{error:cr};let{matchUp:n}=Bt({drawDefinition:t,event:e,matchUpId:r});return n?gr({name:jm,element:n}):{error:Le}}function Hx({substituteParticipantId:t,existingParticipantId:e,tournamentRecord:r,drawDefinition:n,sideNumber:o,matchUpId:i,event:s}){let a="substituteParticipant";if(!n)return{error:Z};if(!i)return{error:cr};if(!e||!t)return _({result:{error:ie},stack:a});let{matchUp:c}=Bt({drawDefinition:n,matchUpId:i,event:s});if(!c)return{error:Le};if(!c.collectionId)return _({result:{error:lr},stack:a});let u=Me({drawDefinition:n}),{matchUps:p}=ce({tournamentParticipants:r?.participants,inContext:!0,drawDefinition:n,matchUpsMap:u}),m=p?.find(g=>g.matchUpId===i),l=p?.find(g=>g.matchUpId===m?.matchUpTieId)?.sides?.find(g=>g.participant.individualParticipants.some(({participantId:I})=>I===e));return!l||o&&l.sideNumber!==o?{error:mn}:l.participant?.individualParticipants?.map(St).filter(g=>g!==e)?.includes(t)?aI({newParticipantId:t,tieMatchUpId:i,existingParticipantId:e,substitution:!0,tournamentRecord:r,drawDefinition:n,event:s}):_({result:{error:mn},stack:a})}function hM(t){return Hx(t)}function SM({drawDefinition:t,matchUpId:e,event:r}){if(!t)return{error:Z};let{matchUp:n}=Bt({drawDefinition:t,matchUpId:e,event:r});return Ut({extension:{name:ha,value:!0},element:n})}function TM(t){let e="setMatchUpFormat",r=et(t,[{tournamentRecord:!0},{[er]:E=>Dr({matchUpFormat:E}),[Fr]:$a,matchUpFormat:!0}]);if(r.error)return _({result:r,stack:e});let{tournamentRecord:n,drawDefinition:o,scheduledDates:i,stageSequences:s,matchUpFormat:a,structureId:c,eventType:u,matchUpId:p,eventId:m,stages:d,drawId:l,event:f,force:g}=t;if(i&&!Array.isArray(i))return _({result:{error:V,scheduledDates:i},stack:e});if(u&&!kc([$n,qr],u))return _({result:{error:jn},stack:e});let I=0,h=t.structureIds||c&&[c].filter(Boolean)||[],S=t.eventIds||m&&[m].filter(Boolean)||[],T=t.drawIds||l&&[l].filter(Boolean)||[];if((c||h?.length)&&!o)return _({result:{error:Z},stack:e});if(l&&p&&o){let E=zd({tournamentRecord:n,drawDefinition:o,matchUpFormat:a,structureIds:h,structureId:c,matchUpId:p});if(E.error)return E;I+=1}let y=E=>{let P=[];for(let A of E.structures||[]){if(Array.isArray(d)&&!d.includes(A.stage)||Array.isArray(s)&&!s.includes(A.stageSequence)||h?.length&&!h.includes(A.structureId))continue;h?.length&&A.matchUpFormat!==a&&(A.matchUpFormat=a,P.push(A.structureId),I+=1);let U=((g||i)&&yt({matchUpFilters:{matchUpStatuses:[Xt]},structure:A}).matchUps)??[],N=(i&&yt({matchUpFilters:{matchUpStatuses:[Xt]},contextFilters:{scheduledDates:i},afterRecoveryTimes:!1,inContext:!0,structure:A}).matchUps)??[];if(U?.length){let D=N?N.map(Ue):U.map(Ue);for(let M of U)D.includes(M.matchUpId)&&(M.matchUpFormat=i?.length?a:void 0,gt({tournamentId:n?.tournamentId,eventId:f?.eventId,context:e,drawDefinition:E,matchUp:M}))}}return!P.length&&E.matchUpFormat!==a&&(E.matchUpFormat=a,I+=1),P};for(let E of n?.events||[])if(!(S?.length&&!S.includes(E.eventId)||u&&u!==E.eventType||u===_e))if(Array.isArray(s)||Array.isArray(d)||h?.length||T?.length)for(let P of E.drawDefinitions||[]){if(Array.isArray(T)&&!T.includes(P.drawId))continue;let A=y(P);vt({structureIds:A,drawDefinition:P})}else E.matchUpFormat!==a&&(E.matchUpFormat=a,I+=1);return I?{...C,modificationsCount:I}:{...C,info:xs}}function pI({inheritance:t=!0,tournamentRecord:e,drawDefinition:r,matchUpId:n,event:o}){if(!r)return{error:Z};let i=Bt({drawDefinition:r,matchUpId:n})?.matchUp;if(!i?.tieMatchUps)return{error:lr};let s=Bt({inContext:!0,drawDefinition:r,matchUpId:n,event:o})?.matchUp,a=0;return(i?.sides||[]).forEach(c=>{c.lineUp&&delete c.lineUp}),(s?.sides||[]).forEach(c=>{if(a+=1,t===!1){let u=s?.tieFormat,p=c.participantId;u&&p&&Qi({drawDefinition:r,participantId:p,lineUp:[],tieFormat:u})}gt({tournamentId:e?.tournamentId,context:"resetMatchUpLineUps",eventId:o?.eventId,drawDefinition:r,matchUp:i})}),{...C,modificationsCount:a}}function Ky(t){let{matchUpFormat:e,matchUpStatus:r,winningSide:n,score:o,setTBlast:i}=t;if(!o)return{sets:[]};let s=o.sets||[],a=$o({winnerFirst:!1,matchUpFormat:e,matchUpStatus:r,setTBlast:i,sets:s}),c=$o({winnerFirst:!1,reversed:!0,matchUpFormat:e,matchUpStatus:r,setTBlast:i,sets:s}),u=$o({matchUpFormat:e,matchUpStatus:r,winningSide:n,setTBlast:i,sets:s}),p=a===u?c:a;return n&&(a=n===1?u:p,c=n===2?u:p),{score:{sets:s,scoreStringSide1:a,scoreStringSide2:c}}}function Wu(t){let e=et(t,[{[ln]:!0,[Ce]:!0}]);if(e.error)return e;let r=Mr(t);if(!t.drawDefinition){let S=t.tournamentRecord??(t.tournamentId&&r[t.tournamentId]);t.tournamentRecord||(t.tournamentRecord=S);let T=ze({eventId:t.eventId,drawId:t.drawId,tournamentRecord:S});if(T.error)return T;T.drawDefinition&&(t.drawDefinition=T.drawDefinition),t.event=T.event}let{disableScoreValidation:n,policyDefinitions:o,tournamentRecord:i,disableAutoCalc:s,enableAutoCalc:a,drawDefinition:c,matchUpId:u,schedule:p,event:m,notes:d}=t,l=t.matchUpFormat||t.outcome?.matchUpFormat,{policy:f}=ni({policyType:tn,tournamentRecord:i,event:m}),g=t.allowChangePropagation!==void 0&&t.allowChangePropagation||f?.allowChangePropagation!==void 0&&f.allowChangePropagation||void 0,{outcome:I,setTBlast:h}=t;if(I?.winningSide&&![1,2].includes(I.winningSide))return{error:Dm};if(l){let S=zd({tournamentRecord:i,drawDefinition:c,matchUpFormat:l,matchUpId:u,event:m});if(S.error)return S}if(I?.score?.sets&&!I.score.scoreStringSide1){let{score:S}=Ky({...I,setTBlast:h});I.score=S,I.score.sets=I.score.sets.filter(T=>T.side1Score||T.side2Score||T.side1TiebreakScore||T.side2TiebreakScore)}return Fa({matchUpStatusCodes:I?.matchUpStatusCodes,matchUpStatus:I?.matchUpStatus,winningSide:I?.winningSide,allowChangePropagation:g,disableScoreValidation:n,score:I?.score,tournamentRecords:r,policyDefinitions:o,tournamentRecord:i,disableAutoCalc:s,enableAutoCalc:a,drawDefinition:c,matchUpFormat:l,matchUpId:u,schedule:p,event:m,notes:d})}function yM(t){if(!t?.outcomes)return{error:st};if(!Array.isArray(t.outcomes))return{error:st,info:{outcomes:t.outcomes}};let e=t.tournamentRecords||t.tournamentRecord&&{[t.tournamentRecord.tournamentId]:t.tournamentRecord}||{},r=t.outcomes??[],n=r.reduce((o,i)=>o.includes(i.tournamentId)?o:o.concat(i.tournamentId),[]);for(let o of n){let i=e[o];if(!i)return{error:$};let s=r.filter(a=>a.tournamentId===o);if(s.length){let a=H1({outcomes:s,tournamentRecord:i});if(a.error)return a}}return{...C}}function H1(t){let{tournamentRecords:e,tournamentRecord:r,outcomes:n,policyDefinitions:o}=t,i={};n.forEach(s=>{let{eventId:a}=s;i[a]||(i[a]=[]),i[a].push(s)});for(let s of Object.keys(i)){let{event:a}=ze({tournamentRecord:r,eventId:s});for(let c of i[s]){let{drawId:u}=c,p=a?.drawDefinitions?.find(m=>m.drawId===u);if(p&&u){let{matchUpFormat:m,matchUpId:d}=c,l=Wu({schedule:c?.schedule,tournamentRecords:e,policyDefinitions:o,tournamentRecord:r,drawDefinition:p,matchUpFormat:m,matchUpId:d,outcome:c,drawId:u,event:a});if(l.error)return l}}}return{...C}}function Wx({drawDefinition:t,matchUpId:e,outcome:r,matchUp:n}){if(!n&&!t)return{error:Z};if(!r)return{error:st,info:"missing outcome"};if(!n&&!e)return{error:Tr};if(!n){let i=Bt({drawDefinition:t,matchUpId:e});if(i.error)return i;n=i.matchUp}return typeof r!="object"||!r.score?.scoreStringSide1||!r.score?.scoreStringSide2?{error:V}:Ut({element:n,extension:{name:jm,value:r}})}function AM(t){return Wx(t)}function mI(t){let e="resetTieFormat",{drawDefinition:r,event:n,uuids:o}=t,i=et(t,[{[ne]:!0,[ln]:!0}],e);if(i.error)return i;let s=Ns(t,[{[ss]:Ln}]);if(s[fn])return s;let a=t.tournamentRecord?.tournamentId,{matchUp:c,structure:u}=s?.matchUp??{};if(!c?.tieMatchUps)return _({result:{error:lr},info:"Must be a TEAM matchUp",stack:e});if(!c.tieFormat)return{...C};let p=We({structure:u,drawDefinition:r,event:n})?.tieFormat;if(!p)return _({result:{error:ve},info:"No inherited tieFormat",stack:e});let m=[],d=[],l=[],f=[];for(let g of p.collectionDefinitions){let{matchUpCount:I,collectionId:h}=g;d.push(h);let S=(c.tieMatchUps||[]).filter(T=>T.collectionId===h);if(S.length>I)S.sort((T,y)=>(T.matchUpStatus===Xt?1:0)-(y.matchUpStatus===Xt?1:0)),l.push(...S.slice(0,I)),m.push(...S.slice(3).map(Ue));else if(l.push(...S),S.length<I){let T=I-S.length,y=Ru({collectionDefinition:g,matchUpsLimit:T,matchUp:c,uuids:o});f.push(...y)}}for(let g of c?.tieMatchUps||[])g.collectionId&&!d.includes(g.collectionId)&&m.push(g.matchUpId);return f.length&&(l.push(...f),vo({eventId:n?.eventId,matchUps:f,drawDefinition:r,tournamentId:a})),m.length&&Rn({matchUpIds:m,eventId:n?.eventId,drawDefinition:r,tournamentId:a}),c&&(c.tieMatchUps=l,c.tieFormatId=void 0,c.tieFormat=void 0,gt({structureId:u?.structureId,eventId:n?.eventId,context:e,drawDefinition:r,tournamentId:a,matchUp:c})),{...C,newMatchUps:f,deletedMatchUpIds:m}}function dI(t){let{tournamentRecord:e,drawDefinition:r,matchUpId:n,event:o}=t,i="resetScorecard";if(!r)return _({result:{error:Z},stack:i});if(!n)return _({result:{error:cr},stack:i});if(!Vt(n))return _({result:{error:V,matchUpId:n},stack:i});let s=Me({drawDefinition:r}),{matchUps:a}=ce({nextMatchUps:!0,inContext:!0,drawDefinition:r,matchUpsMap:s}),c=s.drawMatchUps.find(I=>I.matchUpId===n),u=a?.find(I=>I.matchUpId===n);if(!c||!a)return{error:Le};if(c.matchUpType!==br)return{error:lr};let p=mr({inContextDrawMatchUps:a,drawDefinition:r,matchUpId:n}),m=u?.structureId,{structure:d}=at({drawDefinition:r,structureId:m});if(Object.assign(t,{inContextDrawMatchUps:a,inContextMatchUp:u,matchUpsMap:s,targetData:p,structure:d,matchUp:c}),vi(t))return{error:Nm};if(c.tieMatchUps?.length)for(let I of c.tieMatchUps){let h=Fa({matchUpId:I.matchUpId,matchUpTieId:n,winningSide:void 0,removeScore:!0,tournamentRecord:e,drawDefinition:r,event:o});if(h.error)return _({result:h,stack:i})}let f=Tt({tournamentRecord:e,drawDefinition:r,event:o})?.appliedPolicies,g=lo({event:t.event,removeScore:!0,tournamentRecord:e,appliedPolicies:f,drawDefinition:r,matchUpsMap:s,matchUpId:n});if(g.error)return _({result:g,stack:i});if(t.tiebreakReset&&!g.tieFormatRemoved){let I=We({drawDefinition:r,structure:d,event:o})?.tieFormat;if(c.tieFormat&&I){let{matchUpCountDifference:h,descendantDifferences:S,ancestorDifferences:T,valueDifference:y}=Qo({descendant:c.tieFormat,ancestor:I});if(S.collectionIds.length===1&&!T.collectionIds.length&&!T.groupsCount&&h===1&&y===1){let E=mI({tournamentRecord:e,drawDefinition:r,matchUpId:n,event:o});if(E.error)return E}}}return{...C}}function EM(t){let e=et(t,[{[Ce]:!0,[so]:!0},{[Vs]:{[nc]:!1,roundNumbers:!1},[wh]:"At least one must be provided",[He]:Be}]);if(e.error)return e;let r=iT(t);if(r.error)return r;let{matchUpIds:n}=r,o=de(br)(t.event.eventType),{tournamentRecord:i,drawDefinition:s,event:a}=t;for(let c of n){if(o){let p=dI({tiebreakReset:!0,tournamentRecord:i,drawDefinition:s,matchUpId:c,event:a});if(p.error||t.removeAssignments&&pI({inheritance:!1,drawDefinition:s,matchUpId:c}).error)return p}let u=Fa({winningSide:void 0,removeScore:!0,tournamentRecord:i,drawDefinition:s,matchUpId:c,event:a});if(u.error)return u;if(t.removeAssignments){let p=cI({...t,matchUpId:c});if(p.error)return p}}return{...C}}function jx({tournamentRecord:t,drawDefinition:e,finishingOrder:r}){if(!e)return{error:Z};let n="setOrderOfFinish";if(!Array.isArray(r))return _({info:ai("finishingOrder"),result:{error:V},stack:n});let{completedMatchUps:o,matchUpsMap:i}=Ys({inContext:!0,drawDefinition:e}),s=o?.map(Ue)??[],a=r.map(Ue),{matchUpTypes:c,roundNumbers:u,structureIds:p,matchUpTieIds:m}=(o??[]).filter(({matchUpId:T})=>a.includes(T)).reduce((T,y)=>{let{matchUpTieId:E,matchUpType:P,roundNumber:A,structureId:U}=y;return T.matchUpTypes.includes(P)||T.matchUpTypes.push(P),T.roundNumbers.includes(A)||T.roundNumbers.push(A),T.structureIds.includes(U)||T.structureIds.push(U),T.matchUpTieIds.includes(E)||T.matchUpTieIds.push(E),T},{matchUpTypes:[],roundNumbers:[],structureIds:[],matchUpTieIds:[]});if(c.length>1||m.length>1||u.length>1||p.length>1)return _({info:"matchUpType, structureId and roundNumber must be equivalent",result:{error:V},stack:n});let d,l,f={},g=[],I=[];if(!r.every(({orderOfFinish:T,matchUpId:y})=>(g.push(y),T&&I.push(T),f[y]=T,d=s.includes(y),l=T===void 0||It(T)&&Math.floor(T)>0,d&&l)))return _({result:{error:d?V:da},info:!d&&"matchUps must be completed"||!l&&"orderOfFinish must be integer > 0 or undefined"||void 0,stack:n});let S=o?.filter(T=>T.structureId===p[0]&&T.roundNumber===u[0]&&T.matchUpType===c[0]&&T.matchUpTieId===m[0]&&!g.includes(T.matchUpId));for(let T of S??[]){let{orderOfFinish:y}=T||{};if(y){if(!It(y))return _({context:{orderOfFinish:y,matchUp:T},result:{error:V},stack:n});I.push(y)}}if(CI(I).length!==I.length||Math.max(...I)>I.length)return _({info:"Values not unique or greater than expected number of values",result:{error:V},stack:n});if(p.length){let T=yu({matchUpFilters:{matchUpIds:a},structureId:p[0],drawDefinition:e,matchUpsMap:i});if(T.error)return _({result:T,stack:n});T.completedMatchUps?.forEach(y=>{y.orderOfFinish=f[y.matchUpId],gt({tournamentId:t.tournamentId,context:"setOrderOfFinish",drawDefinition:e,matchUp:y})})}return{...C}}function UM(t){return jx(t)}function PM(t){let{tournamentRecord:e,drawDefinition:r,matchUpId:n,lineUps:o,event:i}=t,s="applyLineUps",a=et(t,[{[ne]:!0,[Ce]:!0,[ln]:!0},{lineUps:!0,[He]:Be}],s);if(a.error)return a;let c=e.participants||[],u=Bt({tournamentParticipants:c,inContext:!0,drawDefinition:r,matchUpId:n});if(u.error)return u;if(!u.matchUp)return{error:Le};let{matchUp:p,structure:m}=u,{drawPositions:d,matchUpType:l}=p;if(l!==Wt)return{error:lr};if(!d?.length)return{error:Ya};let f=We({matchUp:p,drawDefinition:r,structure:m,event:i})?.tieFormat,g={};for(let h of o){if(!Array.isArray(h))return{error:V,lineUp:h};let S={},T=[];for(let U of h){if(typeof U!="object")return{error:V,lineUpAssignment:U};let{participantId:N,collectionAssignments:D=[]}=U;if(!Array.isArray(D))return{error:V,collectionAssignments:D};let M=c.find(b=>b.participantId===N);if(!M)return{error:re};if(M.participantType!==At)return{error:An};let R=p.sides?.find(b=>b.participant?.individualParticipantIds?.includes(N))?.sideNumber;R&&T.push(R);for(let b of D){if(typeof b!="object")return{error:V,collectionAssignment:b};let{collectionId:v,collectionPosition:O}=b,x=f?.collectionDefinitions?.find(L=>L.collectionId===v);if(!x)return{error:V,collectionId:v};let F=`${v}-${O}`;S[F]||(S[F]=[]);let w=S[F].length;if(de(kt)(x.matchUpType)&&w||x.matchUpType===xt&&w>1)return{info:"Excessive collectionPosition assignments",error:V};S[F].push(N)}}let y=Object.values(S);for(let U of y)if(U.length===2){let{participant:N}=In({tournamentParticipants:c,participantIds:U});if(!N){let M=vn({participant:{participantType:ft,participantRole:xe,individualParticipantIds:U},pairOverride:!0,tournamentRecord:e});if(M.error)return M}}let E=yr(T),P=(E[1]||0)>(E[2]||0)&&1||(E[2]||0)>(E[1]||0)&&2||void 0,A=Object.keys(g).map(U=>parseInt(U));P&&!A.includes(P)&&(g[P]=h)}if(!Object.keys(g).length)return{error:cf};if(u=Bt({drawDefinition:r,matchUpId:n}),u.error)return u;if(!u.matchUp)return{error:Le};let{matchUp:I}=u;I.sides||(I.sides=[]);for(let h of[1,2]){let S=I.sides.find(y=>y.sideNumber===h),T=g[h];if(T)S?S.lineUp=T:I.sides.push({lineUp:T,sideNumber:h});else continue}return gt({tournamentId:e?.tournamentId,context:s,drawDefinition:r,matchUp:I}),{...C}}var TI={};Jt(TI,{anonymizeTournamentRecord:()=>_M,generate:()=>OM,generateEventWithDraw:()=>gm,generateOutcome:()=>II,generateOutcomeFromScoreString:()=>lI,generateParticipants:()=>aa,generateTournamentRecord:()=>vM,modifyTournamentRecord:()=>xM,mutate:()=>wM});var OM={};Jt(OM,{generateEventWithDraw:()=>gm,generateOutcome:()=>II,generateOutcomeFromScoreString:()=>lI,generateParticipants:()=>aa,generateTournamentRecord:()=>vM});function lI(t){let{matchUpFormat:e,matchUpStatus:r,winningSide:n,scoreString:o,setTBlast:i}=t;if(!o)return{outcome:{...Ou,winningSide:n,matchUpStatus:r}};if(n&&![1,2,void 0].includes(n))return{error:V,winningSide:n};let s=o&&qd({scoreString:o}),a={},c=$o({sets:s,matchUpFormat:e,setTBlast:i}),u=$o({sets:s,reversed:!0,matchUpFormat:e,setTBlast:i});return n===2?(a.scoreStringSide1=u,a.scoreStringSide2=c):(a.scoreStringSide1=c,a.scoreStringSide2=u),a.sets=qd({scoreString:a.scoreStringSide1}),nt({outcome:{matchUpStatus:r,winningSide:n,score:a}})}function yl({matchUpScheduleTimes:t,matchUpDependencies:e,allDateMatchUpIds:r,matchUp:n}){let i=(e?.[n.matchUpId]?.matchUpIds||[]).filter(a=>r.includes(a)).filter(a=>!t[a]);return{dependenciesScheduled:!i?.length,remainingDependencies:i}}function ka({individualParticipantProfiles:t,participantId:e}){t[e]||(t[e]={typeChangeTimeAfterRecovery:void 0,timeAfterRecovery:void 0,priorMatchUpType:void 0,potentialRecovery:{},potentialCounted:{},potentialBookings:{},bookings:[],counters:{}})}function Yx({individualParticipantProfiles:t,recoveryValue:e,participantId:r,scheduleTime:n,drawId:o}){t[r].potentialRecovery[o]||(t[r].potentialRecovery[o]=[]),t[r].potentialRecovery[o].push(e),t[r].potentialBookings[o]||(t[r].potentialBookings[o]=[]),t[r].potentialBookings[o].push({timeAfterRecovery:e,scheduleTime:n})}function xc({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,typeChangeRecoveryMinutes:r,averageMatchUpMinutes:n=0,matchUpNotBeforeTimes:o,matchUpDependencies:i,recoveryMinutes:s=0,scheduleTime:a,matchUp:c}){let u=Qt(c?.schedule?.endTime),p=u?Yr(u,dt(s)):Yr(a,dt(n)+dt(s)),m=r&&(u?Yr(Qt(u),r):Yr(a,dt(n)+dt(r))),d=i?.[c.matchUpId]?.participantIds||[],l=(c.roundPosition&&t[c.matchUpId]||[]).flat();d.forEach(f=>{ka({individualParticipantProfiles:e,participantId:f});let I=e[f].priorMatchUpType!==c.matchUpType&&m||p;l.includes(f)?Yx({individualParticipantProfiles:e,drawId:c.drawId,recoveryValue:I,participantId:f,scheduleTime:a}):(e[f].timeAfterRecovery=I,e[f].bookings.push({scheduleTime:a,timeAfterRecovery:I}))}),ra({matchUpPotentialParticipantIds:t,matchUpNotBeforeTimes:o,timeAfterRecovery:p,matchUp:c})}function zy({matchUpScheduleTimes:t,matchUpDependencies:e,scheduleTime:r,matchUpId:n,details:o}){let i,s=o.minutesMap?.[n]?.recoveryMinutes,c=(o.minutesMap?.[n]?.averageMinutes||0)+(s||0),u=Yr(r,c),p=e?.[n]?.dependentMatchUpIds||[];if(p.length){let m=p.reduce((d,l)=>{let f=t[l];if(!f)return d;let g={scheduleTime:f,matchUpId:l};return f&&!d.matchUpId||Yt(f)<Yt(d.scheduleTime)?g:d},{});m.scheduleTime&&Yt(u)>Yt(m.scheduleTime)&&(i=m)}return{scheduledDependent:i}}function qx(t){let{sides:e,matchUpType:r}=t||{};return(e||[]).map(n=>r===xt&&(n?.participant?.individualParticipants||[])||n?.participant&&[n.participant]||[]).flat()}var wc="DO_NOT_SCHEDULE",$x={DO_NOT_SCHEDULE:wc};function Al({averageMatchUpMinutes:t=90,requestConflicts:e={},potentials:r=!0,personRequests:n,scheduleTime:o,scheduleDate:i,matchUp:s}){let a=qx(s).map(({person:l})=>l?.personId);if(r){let l=(s?.potentialParticipants||[]).flat().map(({person:f})=>f?.personId);a.push(...l)}let c=a.map(l=>n[l]?.map(f=>({...f,personId:l}))).filter(Boolean).flat().filter(l=>l.requestType===wc&&qn(i,l.date)),u=[],p=s?.matchUpId,m=Ge(Qt(o),Pt(i)),d=Qt(Ef(m,t).toISOString());for(let l of c){let{requestId:f,startTime:g,endTime:I}=l;(o>g&&o<I||d>g&&d<I)&&(u.push({matchUpId:p,request:l,scheduleTime:o}),e[f]?(e[f].scheduleTimes.includes(o)||e[f].scheduleTimes.push(o),e[f].matchUpIds.includes(p)||e[f].matchUpIds.push(p)):e[f]={request:l,scheduleTimes:[o],matchUpIds:[p]})}return{conflicts:u}}function fI({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,matchUp:r,value:n}){let{matchUpType:o}=r,{individualParticipantIds:i}=mu(r),a=(t[r.matchUpId]||[]).filter(u=>!ke(u,i)).flat();[...i,...a].forEach(u=>{if(ka({individualParticipantProfiles:e,participantId:u}),!e[u].potentialCounted[r.drawId]){let p=e[u].counters;p[o]?p[o]+=n:n>0&&(p[o]=n),p[mo]?p[mo]+=n:n>0&&(p[mo]=n),a.includes(u)&&(e[u].potentialCounted[r.drawId]=!0)}})}function Kx({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,dateScheduledMatchUpIds:r,greatestAverageMinutes:n,dateScheduledMatchUps:o,matchUpNotBeforeTimes:i,matchUpScheduleTimes:s,matchUpDependencies:a,clearScheduleDates:c,scheduleDate:u,minutesMap:p,matchUps:m}){let d=[];r||(o=m?.filter(g=>{let I=g.schedule||{},h=g.matchUpStatus===Nt;return h&&d.push({tournamentId:g.tournamentId,matchUpId:g.matchUpId}),!h&&xa({schedule:I})&&(!u||g.schedule.scheduledDate===u)}),r=o.map(Ue));let l=Array.isArray(c)?c.includes(u):c,f=l?[]:m.filter(({matchUpId:g})=>r.includes(g));for(let g of f){fI({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,value:1,matchUp:g});let I=g.schedule?.scheduledTime;if(I){s[g.matchUpId]=I;let h=p?.[g.matchUpId]?.recoveryMinutes;xc({individualParticipantProfiles:e,matchUpPotentialParticipantIds:t,matchUpNotBeforeTimes:i,matchUpDependencies:a,averageMatchUpMinutes:n,recoveryMinutes:h,scheduleTime:I,matchUp:g})}}return{dateScheduledMatchUpIds:r,byeScheduledMatchUpDetails:d,dateScheduledMatchUps:o,clearDate:l}}function um({defaultRecoveryMinutes:t=0,averageMatchUpMinutes:e=90,dateScheduledMatchUps:r,tournamentRecords:n,venueIds:o=[],periodLength:i,scheduleDate:s,matchUps:a}){if(typeof n!="object")return{error:Lt};if(!Vr(a)&&!Array.isArray(r))return{error:eo};i=i??Hu({recoveryMinutes:t,averageMatchUpMinutes:e});let c=Object.assign({},...Object.values(n).map(d=>(d.events??[]).map(l=>{let{scheduleTiming:f}=Ea({tournamentRecord:d,event:l});return{[l.eventId]:{event:l,scheduleTiming:f}}})).flat()),u={averageTimes:[{minutes:{default:e}}],recoveryTimes:[{minutes:{default:t}}]};r||(r=a?.filter(d=>{let l=d.schedule;return xa({schedule:l})&&(!s||d.schedule.scheduledDate===s)}));let p=r?.filter(d=>(!o.length||o.includes(d.schedule.venueId))&&d.matchUpStatus!==Nt);return{bookings:p?.map(({eventId:d,schedule:l,matchUpFormat:f})=>{let{event:g,scheduleTiming:I}=c[d],h=g?.eventType,S={...I,defaultTiming:u,matchUpFormat:f},{averageMinutes:T,recoveryMinutes:y}=Mp({timingDetails:S,eventType:h}),{courtId:E,venueId:P}=l,A=Qt(l.scheduledTime),U=Yr(A,T);return{recoveryMinutes:y,averageMinutes:T,periodLength:i,startTime:A,courtId:E,endTime:U,venueId:P}}).filter(Boolean),relevantMatchUps:p,dateScheduledMatchUps:r}}function zx({calculateStartTimeFromCourts:t=!0,remainingScheduleTimes:e,defaultRecoveryMinutes:r,averageMatchUpMinutes:n,clearScheduleDates:o,tournamentRecords:i,tournamentRecord:s,periodLength:a,scheduleDate:c,startTime:u,venueIds:p,matchUps:m,endTime:d}){if(s&&!i&&(i={[s.tournamentId]:s}),typeof i!="object"||!Object.keys(i).length)return{error:Lt};a=a??Hu({recoveryMinutes:r,averageMatchUpMinutes:n});let{courts:l,venues:f}=Uo({dates:[c],ignoreDisabled:!0,tournamentRecords:i}),g=l?.filter(P=>!p||p.includes(P.venueId))??[];u=u??Oc({courts:g,scheduleDate:c,startTime:!0}),d=d??Oc({courts:g,scheduleDate:c,endTime:!0});let{bookings:I,dateScheduledMatchUps:h}=um({defaultRecoveryMinutes:r,averageMatchUpMinutes:n,tournamentRecords:i,scheduleDate:c,periodLength:a,venueIds:p,matchUps:m}),S={calculateStartTimeFromCourts:t,remainingScheduleTimes:e,averageMatchUpMinutes:n,clearScheduleDates:o,date:c,periodLength:a,startTime:u,bookings:I,endTime:d,courts:g},{scheduleTimes:T}=gl(S),y=p?.length===1&&p[0]||f?.length===1&&f[0].venueId||void 0;return{dateScheduledMatchUpIds:h?.map(Br("matchUpId")),dateScheduledMatchUps:h,scheduleTimes:T,venueId:y}}function Qx({scheduledRoundsDetails:t,greatestAverageMinutes:e,garmanSinglePass:r}){let n=[],o=[],i,s,a,c;for(let u of t.filter(Boolean))c||(c=u.hash),(u.hash===c||r)&&(o=o.concat(u.matchUpIds)),u.hash!==c&&!r&&(c=u.hash,n.push({averageMinutes:a,recoveryMinutes:s,roundPeriodLength:i,matchUpIds:o}),o=u.matchUpIds),a=r?e:u.averageMinutes,s=u.recoveryMinutes,i=u.roundPeriodLength;return o.length&&n.push({matchUpIds:o,roundPeriodLength:i,recoveryMinutes:s,averageMinutes:a}),{groupedRounds:n}}function Qy({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,scheduleCompletedMatchUps:r,containedStructureIds:n,matchUpNotBeforeTimes:o,matchUpScheduleTimes:i,matchUpDependencies:s,clearScheduleDates:a,tournamentRecords:c,periodLength:u,scheduleDate:p,useGarman:m,matchUps:d,courts:l,venues:f}){let g={},I=[],h=[],S=[];for(let T of f){let{rounds:y=[],venueId:E}=T,{scheduledRoundsDetails:P,greatestAverageMinutes:A,orderedMatchUpIds:U,minutesMap:N}=Vu({scheduleCompletedMatchUps:r,containedStructureIds:n,tournamentRecords:c,periodLength:u,matchUps:d,rounds:y});S.push(...U??[]);let{groupedRounds:D}=Qx({scheduledRoundsDetails:P,greatestAverageMinutes:A,garmanSinglePass:!0}),M,R=[];m&&({scheduleTimes:R,dateScheduledMatchUpIds:M}=zx({averageMatchUpMinutes:D[0]?.averageMinutes,scheduleDate:Pt(p),venueIds:[T.venueId],clearScheduleDates:a,tournamentRecords:c,periodLength:u,matchUps:d}));let b=Kx({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,dateScheduledMatchUpIds:M,greatestAverageMinutes:A,matchUpNotBeforeTimes:o,matchUpScheduleTimes:i,matchUpDependencies:s,clearScheduleDates:a,scheduleDate:p,minutesMap:N,matchUps:d});({dateScheduledMatchUpIds:M}=b);let v=b,{byeScheduledMatchUpDetails:O,clearDate:x}=b;O?.length&&h.push(...O);let{matchUpsToSchedule:F,matchUpMap:w}=ol({matchUpPotentialParticipantIds:t,scheduleCompletedMatchUps:r,dateScheduledMatchUpIds:M,matchUpNotBeforeTimes:o,matchUpScheduleTimes:i,orderedMatchUpIds:U,clearDate:x,matchUps:d}),L=l.filter(G=>G.venueId===E);g[E]={previousRemainingScheduleTimes:[],courtsCount:L.length,greatestAverageMinutes:A,scheduledRoundsDetails:P,dateScheduledMatchUps:v,matchUpsToSchedule:F,scheduleTimes:R,groupedRounds:D,venueCourts:L,minutesMap:N,matchUpMap:w},a||I.push(...M)}return{allDateScheduledByeMatchUpDetails:h,allDateScheduledMatchUpIds:I,venueScheduledRoundDetails:g,allDateMatchUpIds:S}}function Xx(t,e){let r=Yt(t.scheduleTime),n=Yt(t.timeAfterRecovery),o=Yt(e.scheduleTime),i=Yt(e.timeAfterRecovery),s=r===o||n===i,a=r>o&&r<i,c=o>r&&o<n,u=n>o&&n<i,p=i>r&&i<n;return nt({hasOverlap:s||a||u||c||p,startAisContained:a,endAisContained:u,startBisContained:c,endBisContained:p},!0)}function El({individualParticipantProfiles:t,matchUpNotBeforeTimes:e,matchUpDependencies:r,scheduleTime:n,matchUp:o,details:i}){let s=(r?.[o.matchUpId]?.participantIds||[]).flat(),a=i?.minutesMap?.[o.matchUpId]?.averageMinutes||0,c=i?.minutesMap?.[o.matchUpId]?.recoveryMinutes||0,u=s.every(f=>{ka({individualParticipantProfiles:t,participantId:f});let g=t[f];if(!g.timeAfterRecovery)return!0;let I=Qt(o?.schedule?.endTime),h=I?Yr(I,dt(c)):Yr(n,dt(a)+dt(c));return!!![...Object.keys(g.potentialBookings).filter(E=>E!==o.drawId).map(E=>g.potentialBookings[E]).flat(),...g.bookings].find(E=>Xx({scheduleTime:n,timeAfterRecovery:h},E).hasOverlap)}),p=e[o.matchUpId],d=(p?la(Ge(p),Ge(n),!1):0)>=0;return{enoughTime:u&&d}}function Xy({autoSchedulingAudit:t,tournamentRecords:e}){lt({topic:Ai,payload:t});let r=s=>s?Object.values(s).reduce((c,u)=>c+u.length||0,0):0,n=(t?.schedulingProfile||[]).reduce((s,a)=>s+a.venues.reduce((c,u)=>c+u.rounds.length,0),0),o={scheduledDatesCount:t.scheduledDates?.length,noTimeMatchUpIdsCount:r(t?.noTimeMatchUpIds),scheduledMatchUpIdsCount:r(t?.scheduledMatchUpIds),overLimitMatchUpIdsCount:r(t?.overLimitMatchUpIds),requestConflictsCount:r(t?.requestConflicts),profileRoundsCount:n},i={itemType:Ry,itemValue:o};for(let s of Object.values(e)){let a=s.tournamentId;ip(Ai)?lt({payload:{type:Ry,tournamentId:a,detail:o},topic:Ai}):Nc({tournamentRecord:s,timeItem:i})}}function Ul({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,matchUpDailyLimits:r={},matchUp:n}){let{enteredIndividualParticipantIds:o}=mu(n),{matchUpId:i,matchUpType:s}=n,a=(n.roundPosition&&t[i]||[]).flat(),c=pt(o.concat(...a));return c.forEach(p=>{ka({individualParticipantProfiles:e,participantId:p})}),{participantIdsAtLimit:c.filter(p=>{let m=e[p];if(m)return[s,mo].find(d=>{let l=m.counters?.[d]||0,f=r[d]||0;return l&&f&&l>=f})}),relevantParticipantIds:c}}function ju({scheduleCompletedMatchUps:t=!1,scheduleByeMatchUps:e=!1,errorOnAnachronism:r=!1,checkChronology:n=!0,matchUpDependencies:o,removePriorValues:i,tournamentRecords:s,tournamentRecord:a,matchUpDetails:c,matchUpIds:u,schedule:p}){if(!a)return{error:$};if(!c&&(!u||!Array.isArray(u)))return{error:ns};if(!c&&(!p||typeof p!="object"))return{error:RE};let m,d=[],l=0;if(n&&!o){let I=on({tournamentRecords:s,tournamentRecord:a});o=I.matchUpDependencies,m=I.matchUps}m||(m=ye({tournamentRecord:a})?.matchUps??[]);let f=m.reduce((I,h)=>{let{matchUpId:S,drawId:T,matchUpStatus:y}=h;return(e||y!==Nt)&&(t||!se.includes(y))&&(I[T]?I[T].push(S):I[T]=[S]),I},{}),g=c?.map(I=>I.matchUpId);for(let I of Object.keys(f)){let{drawDefinition:h}=Fo({tournamentRecord:a,drawId:I});if(!h)continue;let S=f[I].filter(y=>u?.includes(y)??g?.includes(y)),T=ir({inContext:!1,drawDefinition:h}).matchUps;for(let y of S){let E=c?.find(A=>A.matchUpId===y)?.schedule||p,P=cm({schedule:E,matchUpDependencies:o,errorOnAnachronism:r,removePriorValues:i,inContextMatchUps:m,tournamentRecords:s,tournamentRecord:a,checkChronology:n,drawDefinition:h,drawMatchUps:T,matchUpId:y});if(P?.warnings?.length&&d.push(...P.warnings),P?.success&&(l+=1),P.error)return P}}return d.length?{...C,scheduled:l,warnings:d}:{...C,scheduled:l}}function Lc(t){let{scheduleCompletedMatchUps:e=!1,scheduleByeMatchUps:r=!1,errorOnAnachronism:n,matchUpContextIds:o,removePriorValues:i,tournamentRecords:s,checkChronology:a,matchUpDetails:c,schedule:u}=t;if(t.matchUpIds&&!o)return ju(t);let p=et(t,[{[Re]:!0},{[Vs]:{matchUpContextIds:!1,matchUpDetails:!1},[Fr]:V,[He]:Be}]);if(p.error)return p;if((!c||o)&&!u)return{error:st,info:"schedule is required"};let m=[],d=0,{matchUpDependencies:l}=on({tournamentRecords:s});for(let f of Object.values(s)){let{tournamentId:g}=f,I=o?.filter(S=>S.tournamentId===g).map(Ue),h=c?.filter(S=>S?.tournamentId===g);if(I?.length||h?.length){let S=ju({matchUpDetails:h,scheduleCompletedMatchUps:e,scheduleByeMatchUps:r,matchUpDependencies:l,errorOnAnachronism:n,removePriorValues:i,tournamentRecords:s,tournamentRecord:f,checkChronology:a,matchUpIds:I,schedule:u});if(S.warnings?.length&&m.push(...S.warnings),S.scheduled&&(d+=S.scheduled),S.error)return S}}return m.length?{...C,scheduled:d,warnings:m}:{...C,scheduled:d}}function Jx({schedulingProfileModifications:t,checkPotentialRequestConflicts:e,scheduleCompletedMatchUps:r,schedulingProfileIssues:n,dateSchedulingProfiles:o,containedStructureIds:i,matchUpDependencies:s,matchUpDailyLimits:a,clearScheduleDates:c,tournamentRecords:u,schedulingProfile:p,personRequests:m,periodLength:d,matchUps:l,courts:f,dryRun:g}){let I={},h={},S={},T={},y={},E={},P={},A={},U={},N={};for(let R of o){let b=Pt(R?.scheduleDate),v=R?.venues||[],O={},x={},F=(B,K)=>{B.forEach(X=>{let j=x[X].counters;j[K]?j[K]+=1:j[K]=1,j[mo]?j[mo]+=1:j[mo]=1})};S[b]={},T[b]={},I[b]={},h[b]={},P[b]=[],A[b]=[],U[b]=[],N[b]=[];let w={};l.forEach(B=>{B.schedule?.scheduledDate&&qn(b,Pt(B.schedule.scheduledDate))&&ra({matchUpPotentialParticipantIds:O,matchUpNotBeforeTimes:w,matchUp:B})});let{allDateScheduledByeMatchUpDetails:L,venueScheduledRoundDetails:G,allDateMatchUpIds:k}=Qy({matchUpPotentialParticipantIds:O,individualParticipantProfiles:x,scheduleCompletedMatchUps:r,containedStructureIds:i,matchUpNotBeforeTimes:w,matchUpScheduleTimes:E,matchUpDependencies:s,clearScheduleDates:c,tournamentRecords:u,useGarman:!0,periodLength:d,scheduleDate:b,matchUps:l,courts:f,venues:v}),H=10,W=0,q,Y=10;for(;!q;){for(let{venueId:B}of v){let K=0,X=G[B];for(;X.courtsCount&&X.scheduleTimes?.length&&X.matchUpsToSchedule?.length&&K<=X.courtsCount;){let{scheduleTime:j,attempts:ot=0}=X.scheduleTimes.shift(),z=X.matchUpsToSchedule.find(Q=>{let{matchUpId:ut,matchUpType:it}=Q,{participantIdsAtLimit:Et,relevantParticipantIds:_t}=Ul({matchUpPotentialParticipantIds:O,individualParticipantProfiles:x,matchUpDailyLimits:a,matchUp:Q});if(Et.length)return A[b].includes(ut)||A[b].push(ut),!1;let{scheduledDependent:Ae}=zy({matchUpScheduleTimes:E,matchUpDependencies:s,scheduleTime:j,matchUpId:ut,details:X});if(Ae)return!1;let{dependenciesScheduled:$t,remainingDependencies:Se}=yl({matchUpScheduleTimes:E,matchUpDependencies:s,allDateMatchUpIds:k,matchUp:Q});if(!$t)return T[b][ut]||(T[b][ut]=[]),T[b][ut].push({scheduleTime:j,remainingDependencies:Se}),!1;let{enoughTime:Or}=El({individualParticipantProfiles:x,matchUpNotBeforeTimes:w,matchUpDependencies:s,scheduleTime:j,details:X,matchUp:Q});if(!Or)return S[b][ut]||(S[b][ut]=[]),S[b][ut].push({scheduleTime:j}),!1;let pn=X.greatestAverageMinutes,{conflicts:Ir}=Al({potentials:e,averageMatchUpMinutes:pn,requestConflicts:N,personRequests:m,scheduleTime:j,scheduleDate:b,matchUp:Q});if(Ir?.length)return y[b]||(y[b]=[]),y[b].push(...Ir),!1;F(_t,it);let Xe=X.minutesMap?.[ut]?.recoveryMinutes;return xc({matchUpPotentialParticipantIds:O,individualParticipantProfiles:x,matchUpNotBeforeTimes:w,averageMatchUpMinutes:pn,matchUpDependencies:s,recoveryMinutes:Xe,scheduleTime:j,matchUp:Q}),E[ut]=j,!0});X.matchUpsToSchedule=X.matchUpsToSchedule.filter(({matchUpId:Q})=>Q!==z?.matchUpId),z?K+=1:(h[b][B]||(h[b][B]=[]),h[b][B].push({scheduleTime:j,attempts:ot+1}))}X.matchUpsToSchedule?.length&&(h[b][B]=h[b][B]?.filter(j=>{let ot=j.attempts<H;return ot&&X.scheduleTimes.push(j),!ot})),(!X.scheduleTimes?.length||!X.matchUpsToSchedule?.length)&&(X.complete=!0)}W+=1,q=v.every(({venueId:B})=>G[B].complete)||W===Y}for(let{venueId:B}of v){let K=G[B].matchUpMap;Object.keys(K).forEach(X=>{let j=u[X];j&&Object.keys(K[X]).forEach(ot=>{let{drawDefinition:z}=Fo({tournamentRecord:j,drawId:ot});z&&K[X][ot].forEach(({matchUpId:ut})=>{let it=E[ut];if(it){let Et=it.split(":").map(ro).join(":"),_t=`${Pt(b)}T${Et}`;g?P[b].push(ut):(Jo({drawDefinition:z,scheduledTime:_t,matchUpId:ut}).success&&P[b].push(ut),B&&sa({tournamentRecord:j,drawDefinition:z,matchUpId:ut,venueId:B}))}})})}),U[b]=G[B].matchUpsToSchedule.map(Ue),I[b][B]=G[B].scheduleTimes.sort((X,j)=>Yt(X.scheduleTime)-Yt(j.scheduleTime))}!g&&L?.length&&Lc({matchUpDetails:L,scheduleByeMatchUps:!0,removePriorValues:!0,tournamentRecords:u,schedule:{scheduledDate:"",scheduledTime:"",courtOrder:"",courtId:"",venueId:""}});for(let B of R.venues)for(let K of B.rounds){let j=(K.matchUps?.map(({matchUpId:z})=>z)||[]).filter(z=>P[b].includes(z));K.canScheduledMatchUpIds=j;let ot=Math.round(j.length/K.matchUpsCount*1e4)/100;(ot===1/0||isNaN(ot))&&(ot=0),K.possibleToSchedulePct=ot,K.matchUpsCount===j.length&&(K.possibleToSchedule=!0)}}let D=o.map(({scheduleDate:R})=>R),M={timeStamp:Date.now(),overLimitMatchUpIds:A,scheduledMatchUpIds:P,schedulingProfile:p,noTimeMatchUpIds:U,requestConflicts:N,scheduledDates:D};return Xy({tournamentRecords:u,autoSchedulingAudit:M}),{...C,schedulingProfileModifications:t,schedulingProfileIssues:n,scheduleTimesRemaining:I,dateSchedulingProfiles:o,skippedScheduleTimes:h,recoveryTimeDeferredMatchUpIds:S,dependencyDeferredMatchUpIds:T,matchUpScheduleTimes:E,overLimitMatchUpIds:A,scheduledMatchUpIds:P,noTimeMatchUpIds:U,requestConflicts:N,scheduledDates:D}}function MM({averageMinutes:t,startTime:e,endTime:r,court:n,date:o}){if(!Array.isArray(n.dateAvailability))return{error:st,stack:"getEarliestCourtTime"};let i=Oc({scheduleDate:o,courts:[n],startTime:!0}),s=Oc({scheduleDate:o,courts:[n],endTime:!0});e=e||i,r=r||s;let a=La({court:n,date:o}),{timeSlots:c}=Ms({courtDate:a}),u=Ge(e),p=Ge(r);return{earliestCourtTime:c?.reduce((d,l)=>{let f=Ge(l.startTime),g=Ge(l.endTime);if(f>p||g<u)return d;let I=u>f?u:f;if(la(I,g)>=t){let T=Qt(I.toISOString());(!d||T<d)&&(d=T)}return d},void 0),courtStartTime:i,courtEndTime:s}}function Zx({schedulingProfileModifications:t,checkPotentialRequestConflicts:e,scheduleCompletedMatchUps:r,schedulingProfileIssues:n,dateSchedulingProfiles:o,containedStructureIds:i,matchUpDependencies:s,matchUpDailyLimits:a,clearScheduleDates:c,tournamentRecords:u,periodLength:p=30,schedulingProfile:m,personRequests:d,matchUps:l=[],courts:f,dryRun:g}){let I={},h={},S={},T={},y={},E={},P={},A={},U={};for(let M of o??[]){let R=Pt(M?.scheduleDate),b=M?.venues||[],v={},O={},x=(z,Q)=>{z.forEach(ut=>{let it=O[ut].counters;it[Q]?it[Q]+=1:it[Q]=1,it[mo]?it[mo]+=1:it[mo]=1})};I[R]={},h[R]={},E[R]=[],P[R]=[],A[R]=[],U[R]=[];let F={};l?.forEach(z=>{z.schedule?.scheduledDate&&qn(R,Pt(z.schedule.scheduledDate))&&ra({matchUpPotentialParticipantIds:v,matchUpNotBeforeTimes:F,matchUp:z})});let{allDateScheduledByeMatchUpDetails:w,allDateScheduledMatchUpIds:L,venueScheduledRoundDetails:G,allDateMatchUpIds:k}=Qy({matchUpPotentialParticipantIds:v,individualParticipantProfiles:O,scheduleCompletedMatchUps:r,containedStructureIds:i,matchUpNotBeforeTimes:F,matchUpScheduleTimes:y,matchUpDependencies:s,clearScheduleDates:c,tournamentRecords:u,periodLength:p,scheduleDate:R,matchUps:l,courts:f,venues:b}),H=l?.filter(({matchUpId:z})=>L.includes(z)),{bookings:W}=um({dateScheduledMatchUps:H,tournamentRecords:u,scheduleDate:R,periodLength:p}),{virtualCourts:q}=nm({scheduleDate:R,periodLength:p,bookings:W,courts:f}),Y=q?.reduce((z,Q)=>{let{earliestCourtTime:ut,courtEndTime:it}=MM({date:R,averageMinutes:0,court:Q});return(!z.startTime||Ge(ut)<Ge(z.startTime))&&(z.startTime=ut),(!z.endTime||Ge(it)>Ge(z.endTime))&&(z.endTime=it),z},{}),B=Y.startTime,K=({courtId:z,booking:Q})=>q?.find(ut=>ut.courtId===z)?.dateAvailability[0].bookings.push(Q),X=10,j=0,ot;for(;!ot;){for(let{venueId:z}of b){let Q=G[z],ut=Q.matchUpsToSchedule.length,it=[],Et=[],_t,Ae=0;for(;!_t;){for(let $t of Q.matchUpsToSchedule){if(Et.length===Q.courtsCount||it.length===Q.courtsCount){_t=!0;break}let{matchUpId:Se,matchUpType:Or}=$t,{participantIdsAtLimit:pn,relevantParticipantIds:Ir}=Ul({matchUpPotentialParticipantIds:v,individualParticipantProfiles:O,matchUpDailyLimits:a,matchUp:$t});if(pn.length){P[R].includes(Se)||P[R].push(Se);continue}let{dependenciesScheduled:Xe,remainingDependencies:te}=yl({matchUpScheduleTimes:y,matchUpDependencies:s,allDateMatchUpIds:k,matchUp:$t});if(!Xe){h[R][Se]||(h[R][Se]=[]),h[R][Se].push({remainingDependencies:te});continue}let Dt=[],ue=q?.reduce((pe,Fe)=>{if(Et.includes(Fe.courtId))return pe;let{earliestCourtTime:ee}=MM({averageMinutes:Q.greatestAverageMinutes,startTime:B,date:R,court:Fe});if(pe.scheduleTime&&Yt(ee)>=Yt(pe.scheduleTime))return pe;let{scheduledDependent:Je}=zy({matchUpScheduleTimes:y,matchUpDependencies:s,scheduleTime:ee,matchUpId:Se,details:Q});if(Je)return pe;let{enoughTime:qt}=El({individualParticipantProfiles:O,matchUpNotBeforeTimes:F,matchUpDependencies:s,scheduleTime:ee,details:Q,matchUp:$t});if(!qt)return I[R][Se]||(I[R][Se]=[]),I[R][Se].includes(ee)||I[R][Se].push(ee),pe;let ar=Q.minutesMap?.[Se]?.averageMinutes||Q.greatestAverageMinutes,{conflicts:Ze}=Al({potentials:e,averageMatchUpMinutes:ar,requestConflicts:U,personRequests:d,scheduleTime:ee,scheduleDate:R,matchUp:$t});if(Ze?.length)return Dt.push(...Ze),!1;x(Ir,Or);let Pe=Q.minutesMap?.[Se]?.recoveryMinutes;return xc({matchUpPotentialParticipantIds:v,individualParticipantProfiles:O,matchUpNotBeforeTimes:F,averageMatchUpMinutes:ar,matchUpDependencies:s,recoveryMinutes:Pe,scheduleTime:ee,matchUp:$t}),(!pe.scheduleTime||Yt(ee)<Yt(pe.scheduleTime))&&(pe.averageMatchUpMinutes=ar,pe.recoveryMinutes=Pe,pe.scheduleTime=ee,pe.courtName=Fe.courtName,pe.courtId=Fe.courtId),pe},{});if(ue.scheduleTime){let{averageMatchUpMinutes:pe,recoveryMinutes:Fe,scheduleTime:ee,courtId:Je}=ue;y[Se]=ee,T[Se]=Je,it.push(Se),Et.push(Je);let qt=ee,ar=Yr(qt,pe);K({courtId:Je,booking:{averageMatchUpMinutes:pe,recoveryMinutes:Fe,periodLength:p,matchUpId:Se,startTime:qt,courtId:Je,endTime:ar,venueId:z}}),Q.matchUpsToSchedule=Q.matchUpsToSchedule.filter(Pe=>Pe.matchUpId!==Se)}else Dt?.length&&(S[R]||(S[R]=[]),S[R].push(...Dt))}(Et.length===Q.courtsCount||it.length===Q.courtsCount||!Q.matchUpsToSchedule.length)&&(_t=!0),Q.matchUpsToSchedule.length&&it<Q.courtsCount&&(Ge(B)<Ge(Y.endTime)?B=Yr(B,p):(_t=!0,Q.complete=!0)),Ae+=1,!_t&&Ae>=ut&&(_t=!0)}Q.matchUpsToSchedule?.length||(Q.complete=!0)}j+=1,ot=b.every(({venueId:z})=>G[z].complete)||j===X}for(let{venueId:z}of b){let Q=G[z].matchUpMap;Object.keys(Q).forEach(ut=>{let it=u[ut];it&&Object.keys(Q[ut]).forEach(Et=>{let{drawDefinition:_t}=Fo({tournamentRecord:it,drawId:Et});_t&&Q[ut][Et].forEach(({matchUpId:$t})=>{let Se=y[$t],Or=T[$t];if(Se){let pn=Se.split(":").map(ro).join(":"),Ir=`${Pt(R)}T${pn}`;g||(Jo({drawDefinition:_t,scheduledTime:Ir,matchUpId:$t}),Zi({courtDayDate:R,tournamentRecords:u,tournamentRecord:it,drawDefinition:_t,matchUpId:$t,courtId:Or})),E[R].push($t)}})})}),A[R]=G[z].matchUpsToSchedule.map(Ue)}!g&&w?.length&&Lc({matchUpDetails:w,scheduleByeMatchUps:!0,removePriorValues:!0,tournamentRecords:u,schedule:{scheduledDate:"",scheduledTime:"",courtOrder:"",courtId:"",venueId:""}});for(let z of M.venues)for(let Q of z.rounds){let it=(Q.matchUps??[]).map(({matchUpId:_t})=>_t)?.filter(_t=>E[R].includes(_t));Q.canScheduledMatchUpIds=it;let Et=Math.round((it?.length||0)/Q.matchUpsCount*1e4)/100;(Et===1/0||isNaN(Et))&&(Et=void 0),Q.possibleToSchedulePct=Et,Q.matchUpsCount===it?.length&&(Q.possibleToSchedule=!0)}}let N=(o??[]).map(({scheduleDate:M})=>M),D={timeStamp:Date.now(),overLimitMatchUpIds:P,scheduledMatchUpIds:E,schedulingProfile:m,noTimeMatchUpIds:A,requestConflicts:U,scheduledDates:N};return Xy({tournamentRecords:u,autoSchedulingAudit:D}),{...C,schedulingProfileModifications:t,schedulingProfileIssues:n,dateSchedulingProfiles:o,recoveryTimeDeferredMatchUpIds:I,dependencyDeferredMatchUpIds:h,matchUpScheduleTimes:y,overLimitMatchUpIds:P,scheduledMatchUpIds:E,noTimeMatchUpIds:A,requestConflicts:U,scheduledDates:N}}function pm(t){let{scheduleAttributes:e=["scheduledDate","scheduledTime","courtOrder"],ignoreMatchUpStatuses:r=se,scheduledDates:n,venueIds:o}=t,i=Mr(t),s=ht(i)?Object.values(i).map(({tournamentId:c})=>c).filter(Boolean):[];if(!s?.length)return{error:Lt};let a=0;for(let c of s){let u=i[c],p=W1({ignoreMatchUpStatuses:r,scheduleAttributes:e,tournamentRecord:u,scheduledDates:n,venueIds:o});if(p.error)return p;a+=p.clearedScheduleCount??0}return{...C,clearedScheduleCount:a}}function W1({scheduleAttributes:t=["scheduledDate","scheduledTime","courtOrder"],ignoreMatchUpStatuses:e=se,tournamentRecord:r,scheduledDates:n,venueIds:o=[]}){if(typeof r!="object")return{error:$};if(!Array.isArray(e)||!Array.isArray(o))return{error:V};o.length&&t.push("venueId");let i=ye({matchUpFilters:{scheduledDates:n},tournamentRecord:r}).matchUps??[],s={};i.forEach(({matchUpStatus:u,schedule:p,drawId:m,matchUpId:d})=>{(!u||!e.includes(u))&&xa({schedule:p,scheduleAttributes:t})&&(!o?.length||o.includes(p.venueId))&&(s[m]||(s[m]=[]),s[m].push(d))});let a=r.tournamentId,c=0;for(let u in s){let{event:p,drawDefinition:m}=ze({tournamentRecord:r,drawId:u}),d=ir({drawDefinition:m,matchUpFilters:{matchUpIds:s[u]}}).matchUps??[];for(let l of d){let f=!1;l.timeItems=(l.timeItems??[]).filter(g=>{let I=g?.itemType&&![po,jo,ji,Up,Yi,qi].includes(g?.itemType);return I||(f=!0),I}),f&&(gt({context:"clear schedules",eventId:p?.eventId,drawDefinition:m,tournamentId:a,matchUp:l}),c+=1)}}return{...C,clearedScheduleCount:c}}function mm(t){let{checkPotentialRequestConflicts:e=!0,scheduleCompletedMatchUps:r,clearScheduleDates:n,scheduleDates:o=[],tournamentRecords:i,periodLength:s,useGarman:a,dryRun:c,pro:u}=t,p=et(t,[{[Re]:!0},{[er]:N=>!N||Array.isArray(N)&&N.every(Nr),[bh]:!1,[He]:Be}]);if(p.error)return p;let m=Xo({tournamentRecords:i});if(m.error)return m;if(!m.schedulingProfile.length)return{...C};let{modifications:d,issues:l=[],schedulingProfile:f=[]}=m,g=Object.assign({},...Object.values(i).map(N=>cs({tournamentRecord:N}).containedStructures)),I=o.map(N=>{if(Nr(N))return Pt(N)}).filter(Boolean),h=f.map(N=>N.scheduleDate).map(N=>Nr(N)&&Pt(N)).filter(N=>N&&(!o.length||I.includes(N)));if(!h.length)return{error:iE};if(n&&!c){let N=Array.isArray(n)?n:[];pm({tournamentRecords:i,scheduledDates:N})}let S=Uo({ignoreDisabled:!1,tournamentRecords:i}).courts,{matchUps:T}=Un({matchUpFilters:{matchUpTypes:[kt,xt]},afterRecoveryTimes:!0,nextMatchUps:!0,tournamentRecords:i}),{matchUpDependencies:y}=on({includeParticipantDependencies:!0,tournamentRecords:i,matchUps:T}),{matchUpDailyLimits:E}=dl({tournamentRecords:i}),{personRequests:P}=Oi({requestType:wc,tournamentRecords:i}),A=f.filter(N=>{let D=Pt(N?.scheduleDate);return h.includes(D)}).sort((N,D)=>new Date(N.scheduleDate).getTime()-new Date(D.scheduleDate).getTime()),U={schedulingProfileModifications:d,checkPotentialRequestConflicts:e,scheduleCompletedMatchUps:r,schedulingProfileIssues:l,dateSchedulingProfiles:A,containedStructureIds:g,matchUpDependencies:y,matchUpDailyLimits:E,clearScheduleDates:n,tournamentRecords:i,schedulingProfile:f,personRequests:P,periodLength:s,useGarman:a,matchUps:T,dryRun:c,courts:S};return u?Zx(U):Jx(U)}function dm(t){let{tournamentRecord:e,tournamentRecords:r,activeTournamentId:n,...o}=t||{};return o.tournamentId||(o.tournamentId=Mt()),o.startDate&&!Ja(o.startDate)&&!Om.test(o.startDate)?{error:je}:o.endDate&&!Ja(o.endDate)&&!Om.test(o.endDate)?{error:je}:(o.extensions&&(o.extensions=o.extensions.filter(kn)),{...o})}function gI({addParticipants:t=!0,participantAttribute:e,tournamentRecord:r,personAttribute:n,teamNames:o,accessor:i,uuids:s}){if(!r)return{error:$};let a={},c=(r.participants??[]).filter(({participantType:f,participantRole:g})=>f===At&&g===xe),u=0;for(let f of c){let I=i&&fs({element:f,accessor:i})?.value||n&&f.person?.[n]||e&&f[e];if(I){if(!Object.keys(a).includes(I)){a[I]={participantName:o?.[u]??I,participantId:s?.pop()??Mt(),individualParticipantIds:[],participantRole:xe,participantType:Ft};let h={value:n??e,name:Fh};Ut({element:a[I],extension:h}),u+=1}a[I].individualParticipantIds.push(f.participantId)}}let p=Object.keys(a),m=(r.participants??[]).map(f=>{if(f.participantType!==Ft||f.participantRole!==xe)return;let{extension:g}=mt({name:Fh,element:f}),I=g?.value;if(p.includes(I))return f.participantId}).filter(Boolean),d=0,l=[];return Object.keys(a).forEach(f=>{let g=a[f],{participantId:I}=g;m.includes(I)||(r.participants||(r.participants=[]),t&&r.participants.push(g),l.push(g),d++)}),t&&d?(lt({payload:{tournamentId:r.tournamentId,participants:l},topic:ei}),{...C,participantsAdded:d}):l.length?{...C,newParticipants:l}:{error:DC}}var tw=[{AA:"Annexia"},{BA:"Bacteria"},{BO:"Borduria"},{BM:"Bensalem"},{BS:"Basenji"},{BI:"Balnibarbi"},{BV:"Bartovia"},{BZ:"Berzerkistan"},{CA:"Caldonia"},{CC:"Concordia"},{CH:"Chula"},{DA:"Deltora"},{DW:"Discworld"},{EA:"Eastasia"},{EP:"Ecotopia"},{ER:"Erewhon"},{FA:"Freedonia"},{FN:"Florin"},{FG:"Fogg"},{FK:"Fourecks"},{GA:"Genovia"},{GL:"Gilead"},{GD:"Gilead"},{GL:"Gondal"},{GO:"Gondor"},{GR:"Gruzinia"},{GT:"Goritania"},{GU:"Guilder"},{HA:"Heldscalla"},{HO:"Hidalgo"},{IL:"Illyria"},{KA:"Kinakuta"},{KG:"Kangan"},{KN:"Kreplachistan"},{KS:"Kallipolis"},{LH:"Lugash"},{LI:"Listenbourg"},{LT:"Lilliput"},{LU:"Luggnagg"},{LV:"Lichtenslava"},{MR:"Moher"},{NA:"Narnia"},{NV:"Novaria"},{OA:"Oceania"},{OS:"Orsinia"},{OV:"Octavia"},{PA:"Palombia"},{PG:"Penguina"},{QA:"Qasha"},{PM:"Panem"},{SA:"Solymbria"},{SD:"Syldavia"},{SG:"San Glucose"},{SL:"San Lorenzo"},{SR:"Sontar"},{SY:"Sylvania"},{TF:"Tralfamadore"},{TH:"Themyscira"},{UA:"Utopia"},{VA:"Vespugia"},{WA:"Wakanda"},{WX:"Wessex"},{ZA:"Zamunda"},{ZK:"Zubrowka"}];var ew=["Amber","Ansul","Atlantis","Braavos","Busytown","Castle Rock","Centralia","Coober Pedy","Chefchaouen","Chronopolis","Damanhur","Diaspar","Dictionopolis","Diomira","El Dorado","Elista","Ephesus","Gotham","Hadleyburg","Hallstatt","Hierusalem","Ilium","Inverness","Kowloon","Laputa","Longyearbyen","Lys","Matmata","Maycomb","Metropolis","Miyake-jima","Monowi","Nagoro","Navarre","New New York","Nimbin","Pemberley","Pseudopolis","Rivendell","Roswell","Shangri-La","Springfield","Supilinn","Thneedville","Trantor","Wobegon","Yonwood","Xanadu","Xylar","Zion"];function Jy({count:t=1,participantsCount:e=32}={}){let r=Sr(ew),n=r.slice(0,t);return{cities:tt(0,e).map(i=>i<Math.min(t,r.length)?n[i]:yn(n))}}function Zy({count:t=1,participantsCount:e=32}={}){let r=Sr(tw),n=r.slice(0,t).map(i=>Object.keys(i)).flat();return{states:tt(0,e).map(i=>i<Math.min(t,r.length)?n[i]:yn(n))}}function tA({count:t=1,participantsCount:e=32}={}){let r=tt(0,t).map(()=>tt(0,5).map(()=>fo(0,9)).join(""));return{postalCodes:tt(0,e).map(o=>o<t?r[o]:yn(r))}}function lm({idPrefix:t,participantType:e,index:r,uuids:n}){let o=Vt(e)?e[0]:"X";return t?`${t}-${o}-${r}`:n?.pop()||Mt()}function eA(t){let{cities:e,states:r,postalCodes:n,nationalityCode:o,participantIndex:i}=t;return{postalCode:n?.[i],state:r?.[i],city:e?.[i],countryCode:o}}var rw={lastNames:["Abbey","Ahern","Ampleforth","Ananiadis","Andelic","Assange","Atreides","Austen","Bach","Banks","Barrington","Batty","Bauers","Beals","Beer","Bennett","Berry","Bonaparte","Brewer","Brockovich","Bukowski","Cassidy","Catton","Calvino","Carlin","Carson","Chip","Constant","Crane","Crowne","Cummings","Curie","Dallas","Diamond","Deckard","Drazic","Dunbar","Earhart","Eisenstein","Eldritch","Elliot","Ellul","Escher","Eyre","Faulkner","Fulcher","Fukuoka","Godel","Goldstein","Greer","Hedges","Herbert","Holmgren","Humperdinck","Huxley","Illich","Jeffers","Jensen","Jevons","Johnson","Johnstone","Jovovich","Kingsnorth","Langer","Fernwright","Fuller","Le Guin","Lem","Lovelace","Mander","McLuhan","Midgely","Mond","Montoya","Moore","Murry","Nagle","Nearing","Ogden","Ophuls","Parks","Paz","Peet","Perfect","Pendejo","Pevensie","Postman","Ripley","Rodda","Rumfoord","Runciter","Rugen","Sale","Schumacher","Shaftoe","Shelley","Shepard","Smith","Stratton","Stewart","Swift","Tillich","Turing","Tyrell","Twain","Yeats","Veblen","Yates","Vonnegut","Waterhouse","Watson","Wolin","Wirt","Waschuk","Wormwood"],firstFemale:["Ada","Amelia","Amelie","America","Anne","Antonia","Aravis","Astrid","Beatrice","Brienne","Buttercup","Caitlin","Cimorene","Cordelia","Desdemona","Ellen","Elizabeth","Emily","Emmie","Erin","Eva","Evelyn","Heather","Helen","Hermia","Hypatia","Imogen","Jane","Jasmine","Juliana","Juliet","Katniss","Leeloo","Lenina","Lilith","Linda","Lizzie","Louise","Lucy","Marie","Mary","Martha","Matilda","Milla","Miranda","Meg","Melba","Nicole","Ola","Portia","Pris","Rachael","Rachel","Rebecca","River","Rosa","Rosalind","Scout","Sharn","Susanne","Titania","Uhura","Ursula","Valentina","Viola","Virginia","Xena","Zoe"],firstMale:["Alan","Aldous","August","Axel","Barda","Barry","Bill","Bruce","Charles","Chris","Constantine","Darwin","David","Derrick","Edward","Emmanuel","Ernst","Estlin","Fezzik","Filby","Frank","Frito","George","Glen","Helmholtz","Inigo","Italo","Ivan","Jacques","James","Jared","Jerry","Joe","Johann","Julian","John Michael","Jonathan","Korben","Kirkpatrick","Kurt","Lief","Malachi","Mark","Marhsall","Masanobu","Maurits","Michael","Mustapha","Neil","Nikola","Octavio","Palmer","Paul","Pierre","Robinson","Rick","Rincewind","Roy","Shannon","Sheldon","Stafford","Stanislaw","Stanley","Syme","Thorstein","Thomas","Tyrone","Vizzini","Walton","Walker","Warren","Wendell","Westley","William","Winston","Zoran"]};function rA(t){let{count:e=100,sex:r}=t||{};if(!e||r&&![zt,oe].includes(r))return{personData:[],error:V};let n=Math.ceil(e*1.3),{lastNames:o,firstFemale:i,firstMale:s}=rw,a=ri.map(({iso:I})=>I).filter(Boolean),c=Math.ceil(n/o.length),u=Math.ceil(n/i.length),p=Math.ceil(n/s.length),m=tt(0,c).flatMap(()=>{let I=J(o,!1,!0);return tt(0,o.length).map(()=>Zr(I))}),d=tt(0,u).flatMap(()=>{let I=J(i,!1,!0);return tt(0,i.length).map(()=>Zr(I))}),l=tt(0,p).flatMap(()=>{let I=J(s,!1,!0);return tt(0,s.length).map(()=>Zr(I))}),f={};for(let I=0;I<n;I++){let h=m.pop(),S=r||yn([zt,oe]),T=S===zt?l.pop():d.pop(),y=yn(a);f[`${T}${h}`]={nationalityCode:y,sex:S,firstName:T,lastName:h}}return{personData:Object.values(f).slice(0,e)}}function nA(t){let e=t?.count||1,{personExtensions:r,consideredDate:n,isMock:o=!0,gendersCount:i,personData:s,category:a,sex:c}=t||{};if(isNaN(e))return{error:V};let u=i?.[zt]||c===zt&&e||0,p=i?.[oe]||c===oe&&e||0;e=Math.max(e,u+p);let m=e-(u+p),d=u&&rA({count:u,sex:zt}).personData||[],l=p&&rA({count:p,sex:oe}).personData||[],f=[...d,...l,...m&&rA({count:m}).personData||[]],g=f.filter(U=>!c||u&&p||U.sex===c),I=[];if(Array.isArray(s)){let U=s.filter(N=>typeof N.firstName!="string"||typeof N.lastName!="string"||N.sex&&![zt,oe].includes(N.sex)||N.nationalityCode&&(typeof N.nationalityCode!="string"||N.nationalityCode.length>3||!ri.find(({iso:D,ioc:M})=>[D,M].includes(N.nationalityCode)))?!1:(N.nationalityCode&&I.push(N.nationalityCode),!0));if(U.length)g=U;else return{error:V}}let h=s?g:Sr(g);if(h.length<e){let{maleFirstNames:U,maleLastNames:N,femaleFirstNames:D,femaleLastNames:M,nationalityCodes:R}=f.reduce((b,v)=>{let{firstName:O,lastName:x,nationalityCode:F}=v;return v.sex===zt?(b.maleFirstNames.includes(O)||b.maleFirstNames.push(O),b.maleLastNames.includes(x)||b.maleLastNames.push(x)):(b.femaleFirstNames.includes(O)||b.femaleFirstNames.push(O),b.femaleLastNames.includes(x)||b.femaleLastNames.push(x)),b.nationalityCodes.includes(F)||b.nationalityCodes.push(F),b},{maleFirstNames:[],maleLastNames:[],femaleFirstNames:[],femaleLastNames:[],nationalityCodes:[]});tt(0,e-h.length).forEach(()=>{let b=c||yn([zt,oe]),v=yn(R),O=b===zt?yn(U):yn(D),x=b===zt?yn(N):yn(M),F={firstName:O,lastName:x,sex:b,nationalityCode:v};h.push(F)})}let{ageMinDate:S,ageMaxDate:T}=Fs({consideredDate:n,category:a}),y=dt(S?.slice(0,4)||0)||dt(T?.slice(0,4)||0)-3,E=dt(T?.slice(0,4)||0)||dt(S?.slice(0,4)||0)+3,P=(S||T)&&[y,E],A=h.slice(0,e).map((U,N)=>{let[D,M]=P||[],R=P&&Zr(tt(D,M)),b=Zr(tt(0,365)),v=R&&$C(R,b);return Object.assign(nt({extensions:r||[{name:"regionCode",value:N+1}],birthDate:v,isMock:o}),U)});return{persons:A.length&&A||h[0],nationalityCodes:I}}var nw=["Ace Academy","Avengers","Ball Bouncers","Baseliners","Captivators","Civil Disobedients","Continentals","Court Royal","Court Sharks","Diamond Dogs","Danger Zone","Doubles Dominators","Double Faults","Tricksters","Eliminators","Court Crusaders","Fuzz Busters","Game Changers","Goal Gurus","Good Volley","Green Machine","Hawk Eyes","Inside Outers","Killer Instinct","Line Toers","Masters of Mayhem","Matter Catchers","Cheap Shot","Mean Machines","Mindspace Invaders","Net Centric","Net Positive","Smash Mullet","Over Your Head","Spin Meisters","Aggressors","Racket Machine","Slice Happy","Refs Nightmare","Sandeaters","Sun Seekers","Slicer Dicers","Stacked Deck","Cross Stringers","The Emergence","Total Demolition","Touch and Go","Unreturnables","Upside Downers","Vertically Challenged","Visual Spectacle"];function fm({nameRoot:t="TEAM",count:e=1}={}){let n=Sr(nw).slice(0,e);return n.length<e&&tt(0,e-n.length).forEach(o=>n.push(`${t} ${o+1}`)),{names:n}}function aa(t){let{scaledParticipantsCount:e,rankingRange:r}=t,{ratingsParameters:n=we,valuesInstanceLimit:o,ratingsValues:i=[],consideredDate:s,categories:a,category:c,nationalityCodesCount:u,nationalityCodeType:p,nationalityCodes:m,participantsCount:d=32,participantType:l,teamSize:f=8,personIds:g,idPrefix:I,uuids:h,personExtensions:S,addressProps:T,gendersCount:y,matchUpType:E,personData:P,sex:A,inContext:U,withISO2:N,withIOC:D,scaleAllParticipants:M}=t,R=l===ft||E===_i,b=l===Ft||E===Ft;r&&(!Array.isArray(r)||!r.every(te=>Zt(te))||r.length!==2)&&(r=void 0),e=M?d:e;let v=1e3,O=e&&e>v?e:v;r=r||[1,O],r[1]+=1;let x=d*(R&&2||b&&(f??8)||1),F=nA({count:x,personExtensions:S,consideredDate:s,gendersCount:y,personData:P,category:c,sex:A});if(F.error)return F;let{nationalityCodes:w,persons:L}=F,G={},k={},H={},W={},q=te=>{Object.assign(G,te.doublesRankings),Object.assign(k,te.singlesRankings),Object.assign(W,te.doublesRatings),Object.assign(H,te.singlesRatings)};if(ht(c)){let te=ow({scaledParticipantsCount:e,ratingsParameters:n,participantType:l,ratingsValues:i,rankingRange:r,category:c});q(te)}Array.isArray(a)&&a.forEach(te=>{let Dt=ow({scaledParticipantsCount:e,ratingsParameters:n,participantType:l,ratingsValues:i,rankingRange:r,category:te});q(Dt)});let Y=ri.filter(te=>p==="IOC"&&te.ioc||te.iso);function B(te){let Dt=Math.ceil(x/te);return o&&Dt>o?Math.ceil(x/o):te}let{postalCodesProfile:K,postalCodesCount:X,statesProfile:j,citiesProfile:ot,citiesCount:z,statesCount:Q}=T||{},ut=te=>Object.keys(te).map(Dt=>tt(0,j[Dt]).map(()=>Dt)).flat(),it=ot&&ut(ot)||T?.cities||Jy({count:z||x,participantsCount:x}).cities,Et=j&&ut(j)||T?.states||Zy({count:Q||x,participantsCount:x}).states,_t=K&&ut(K)||T?.postalCodes||tA({count:X||x,participantsCount:x}).postalCodes,Ae={cities:it,states:Et,postalCodes:_t},$t=B(u),Se=$t?Sr(Y).slice(0,u):m&&Y.filter(te=>m.includes(te.iso))||Y,Or=Sr(tt(0,Math.ceil(x/($t||1))).map(()=>Se).flat(1/0)),pn=fm({count:d}).names;return{participants:tt(0,d).map(te=>{let Dt=R&&2||b&&(f??8)||1,ue=tt(0,Dt).map(qt=>{let ar=te*Dt+qt;return Xe(ar)}),pe=ue.map(qt=>qt.participantId),Fe=ue.map(qt=>qt.person.standardFamilyName).join("/"),ee=R?ft:Ft,Je={participantId:lm({participantType:ee,index:te,idPrefix:I,uuids:h}),participantName:R?Fe:pn[te],participantRole:xe,individualParticipantIds:pe,participantType:ee};return U&&(Je.individualParticipants=ue),R||b?[Je,...ue]:ue}).flat(),...C};function Xe(te){let Dt=L[te],{nationalityCode:ue,participantExtensions:pe,participantTimeItems:Fe,extensions:ee,firstName:Je,birthDate:qt,lastName:ar,personId:Ze,sex:Pe}=Dt||{},ae=Je||"GivenName",hr=ar||"FamilyName",_r=`${ae} ${hr}`,Kt=Or[te],De=w?.length&&ue||Kt&&(p==="IOC"?Kt.ioc||Kt.iso:Kt.iso||Kt.ioc)||ue;Or?.length&&!De&&!ue&&console.log("%c Invalid Nationality Code",{participantIndex:te,country:Kt});let fr=eA({...Ae,participantIndex:te,nationalityCode:De}),Ne=nt({participantId:lm({participantType:At,index:te,idPrefix:I,uuids:h}),extensions:pe,timeItems:Fe,participantRole:xe,participantType:At,participantName:_r,person:{personId:Ze||g?.length&&g[te]||Mt(),birthDate:Nr(qt)?qt:void 0,addresses:[fr],standardFamilyName:hr,standardGivenName:ae,nationalityCode:De,extensions:ee,sex:Pe}});if(D&&De){let me=ri.find(({iso:dr})=>dr===De);me?.ioc&&(Ne.person.iocNationalityCode=me.ioc),me?.label&&(Ne.person.countryName=me.label)}if(N&&De){let me=ri.find(({iso:dr})=>dr===De);me?.iso2&&(Ne.person.iso2NationalityCode=me.iso2),me?.label&&(Ne.person.countryName=me.label)}let On=me=>{let dr=me.categoryName||me.ratingType||me.ageCategoryCode,es=k[dr]?.[te],Tn=G[dr]?.[te];oA({scaleValue:es,eventType:ks,scaleType:Ii,participant:Ne,category:me}),oA({scaleValue:Tn,eventType:Vo,scaleType:Ii,participant:Ne,category:me});let mi=H[dr]?.[te],ca=W[dr]?.[te];oA({scaleValue:mi,eventType:ks,scaleType:hi,participant:Ne,category:me}),oA({scaleValue:ca,eventType:Vo,scaleType:hi,participant:Ne,category:me})};return Array.isArray(a)?a.forEach(me=>On(me)):c&&On(c),Ne}}function oA({scaleValue:t,participant:e,eventType:r,scaleType:n,category:o}){let i=o.categoryName||o.ratingType||o.ageCategoryCode,s=[Si,n,r,i].join("."),a={itemValue:t,itemType:s};i&&t&&(e.timeItems||(e.timeItems=[]),e.timeItems.push(a))}function ow(t){let{category:e,scaledParticipantsCount:r,ratingsParameters:n,participantType:o,ratingsValues:i=[]}=t,s=e.rankingRange||t.rankingRange||[1,1e3],a={},c={},u={},p={},{categoryName:m,ageCategoryCode:d,ratingType:l}=e,f=e.categoryName||e.ratingType||e.ageCategoryCode;if((m||d)&&!l){let[g,I]=s||[];if(c[f]=Sr(tt(g,I)).slice(0,r||fo(20,30)),[ft,Ft].includes(o)){let[h,S]=s||[];a[f]=Sr(tt(h,S)).slice(0,r||fo(20,30))}}if(l&&n[l]){let{ratingMax:g,ratingMin:I,ratingAttributes:h}=e,S={...n[l],...h||{}},{attributes:T={},decimalsCount:y,accessors:E,range:P,step:A}=S,U=O=>{let x={},F=Object.keys(O||{});for(let w of F){let L=O[w];if(typeof L=="object"&&L.generator){let{range:G}=L,[k,H]=G.slice().sort();x[w]=fo(k,H)}else x[w]=L}return x},D=P[0]>P[1]?2:.7,[M,R]=P.slice().sort(),v=tt(0,2e3).map(()=>MA(M,R,D,A,y)).filter(x=>(!g||x<=g)&&(!I||x>=I)).slice(0,r||fo(20,30)).map(x=>E?Object.assign({},...E.map(F=>({[F]:x})),U(T)):x);u[f]=[...i,...v],[ft,Ft].includes(o)&&(p[f]=[...i,...v])}return{singlesRankings:c,doublesRankings:a,singlesRatings:u,doublesRatings:p}}function Pl(t){let{alternatesCount:e=0,tieFormatName:r,drawSize:n}=t,o=0,i=0,s=0,a=0,c={},u={[zt]:0,[oe]:0,[Ar]:0,[is]:0,[Pn]:0};(ht(t.tieFormat)?t.tieFormat:no({namedFormat:r}))?.collectionDefinitions?.filter(Boolean).forEach(f=>{let{category:g,collectionId:I,matchUpType:h,matchUpCount:S,gender:T}=f;if([zt,oe].includes(T)){let y=S*(h===xt?2:1);u[T]<y&&(u[T]=y)}else T===Ar&&(u[zt]<S&&(u[zt]=S),u[oe]<S&&(u[oe]=S));if(g){let y=JSON.stringify(g);c[y]=g}if(I||(f.collectionId=Mt()),de(xt)(h)){let y=S;a+=S,o=Math.max(o,y)}if(de(kt)(h)){let y=S;s+=S,i=Math.max(i,y)}});let m=Object.keys(c).length?Math.max(s,a*2):Math.max(i,o*2),d=o*(n+e),l=i*(n+e);return{maxDoublesDraw:d,maxSinglesDraw:l,teamSize:m,genders:u}}function iw({participantsProfile:t,eventProfiles:e,drawProfiles:r}){let{participantsCount:n,participantType:o=At}=t||{},i=n||0,s={[oe]:0,[Ar]:0,[is]:0,[zt]:0,[Pn]:0},a=0,c=0,u=0,p=0,m=0,d=({alternatesCount:f=0,uniqueParticipants:g,tieFormatName:I,drawSize:h=0,eventType:S,tieFormat:T,category:y,gender:E,stage:P})=>{let A=S===qr,U=S===_e,N=!!(g||P===ct||y||E);if(U){p=Math.max(p,h+f),T=typeof T=="object"?T:no({namedFormat:I});let{teamSize:D,maxDoublesDraw:M,maxSinglesDraw:R,genders:b}=Pl({alternatesCount:f,tieFormatName:I,tieFormat:T,drawSize:h});u=Math.max(u,D),c=Math.max(c,R),N||(a=Math.max(a,M)),Object.keys(b).forEach(v=>s[v]+=b[v])}else if(A)if(N){let D=(h+f)*2;m+=D,E&&(s[E]+=D)}else h+f&&h+f>a&&(a=h+f);else if(N){let D=h+f;E&&(s[E]+=D),m+=D}else h&&h>c&&(c=h+f)};if(e?.forEach(f=>{let{tieFormatName:g,tieFormat:I,drawProfiles:h,eventType:S,category:T,gender:y}=f;if(h)for(let E of h){let{tieFormatName:P,tieFormat:A}=E;d({...E,tieFormatName:P||g,tieFormat:A||I,eventType:S,category:T,gender:y})}}),Array.isArray(r))for(let f of r)d(f);let l=Math.max(p*u,a*2,c);return a&&(o=ft),(n||i)<l&&(n=l),n&&a&&[ft,_e].includes(o)&&(c&&Math.floor(c/2)>a?n=Math.floor(c/2):(!c||a*2>=c)&&(n=Math.ceil(n/2))),n===void 0&&(n=!e?.length&&!r?.length?32:0),n<i&&(n=i),{uniqueParticipantsCount:m,participantsCount:n,largestTeamDraw:p,largestTeamSize:u,participantType:o,gendersCount:s}}function iA({participantsProfile:t,tournamentRecord:e,eventProfiles:r,drawProfiles:n,startDate:o,uuids:i}){if(t?.participantsCount===0)return{addedCount:0,...C};let{participantsCount:s,participantType:a,largestTeamDraw:c,largestTeamSize:u,gendersCount:p}=iw({participantsProfile:t,eventProfiles:r,drawProfiles:n}),m=t?.teamKey,d=aa({consideredDate:o,...t,participantsCount:s,participantType:a,gendersCount:p,uuids:i}).participants,l=0,f=Sn({tournamentRecord:e,participants:d});if(f.error)return f;if(l+=f.addedCount,m){let S=gI({tournamentRecord:e,...m});if(S.error)return S}let g=d.filter(({participantType:S})=>S===At).map(St),I=t?.idPrefix?`${Ft}-${t.idPrefix}`:void 0,h=tt(0,c).map(S=>{let T=g.slice(S*u,(S+1)*u),y=lm({index:S,participantType:a,idPrefix:I,uuids:i});return{participantName:`Team ${S+1}`,participantRole:xe,individualParticipantIds:T,participantType:Ft,participantId:y}});return f=Sn({participants:h,tournamentRecord:e}),f.error?f:(l+=f.addedCount,{addedCount:l,...C})}function sA({drawProfiles:t,category:e,gender:r}){let n={},o=t?.reduce((s,a)=>{let{qualifyingPositions:c=0,participantsCount:u=0,uniqueParticipants:p,stage:m=rt,drawSize:d=0}=a||{};Object.keys(s).includes(m)||(s[m]=0);let l=(u||d)-c;return p||r||e||m===ct?(Object.keys(n).includes(m)||(n[m]=0),n[m]+=l):s[m]=Math.max(s[m],l),s},{}),i=Object.keys(n);return i.forEach(s=>o[s]+=n[s]),{stageParticipantsCount:o,uniqueParticipantsCount:n,uniqueParticipantStages:i}}function aA({allUniqueParticipantIds:t,stageParticipantsCount:e,eventParticipantType:r,targetParticipants:n}){let o=e[rt]||0,i=e[ct]||0;return{stageParticipants:{QUALIFYING:n?.filter(({participantType:a})=>a===r).filter(({participantId:a})=>!t.includes(a)).slice(0,i),MAIN:n?.filter(({participantType:a})=>a===r).filter(({participantId:a})=>!t.includes(a)).slice(i,i+o)}}}var K1={[bt]:2,[Te]:1,[be]:1,[nr]:1,[Rt]:4};function II(t){let{defaultWithScorePercent:e=2,winningSide:r}=t,{matchUpStatusProfile:n=K1,matchUpFormat:o=Dn,pointsPerMinute:i=1,sideWeight:s=4}=t;if(!Dr({matchUpFormat:o}))return{error:ql};if(typeof n!="object")return{error:V};if(e>100&&(e=100),isNaN(e)||isNaN(i)||isNaN(s))return{error:V};let a=Object.keys(n).filter(b=>Object.keys(Yh).includes(b)&&b!==he);if(Object.keys(a).reduce((b,v)=>b+n[v],0)>100)return{error:V,matchUpStatusProfile:n};let u=a.reduce((b,v)=>(b.pointer=b.pointer+n[v],b.valueMap.push([b.pointer,v]),b),{pointer:0,valueMap:[]}),p=fo(1,100),m=(u.valueMap.find(b=>p<=b[0])??[100,he])[1],d={sets:[],scoreStringSide1:"",side2ScoreString:""};if([bt,Rt].includes(m)){r=r||fo(1,2);let b={score:d,matchUpStatus:m,winningSide:r};if(!(m===Rt&&fo(1,100)>100-e))return{outcome:b}}else if([Te,be].includes(m))return{outcome:{score:d,matchUpStatus:m}};let l=Ye(o),{bestOf:f=1,exactly:g,setFormat:I,finalSetFormat:h}=l??{},S=[],T=fo(0,1),y=r?[r-1]:[...tt(0,s).map(()=>T),1-T],P=[nr,Rt,un,as].includes(m)&&(Zr(tt(1,g||f))||1),A,U=tt(1,(g??f)+1);for(let b of U){let v=b===(g??f),{set:O,incomplete:x,winningSideNumber:F}=z1({setFormat:v&&h||I,incomplete:P===b,pointsPerMinute:i,matchUpStatus:m,weightedRange:y,setNumber:b});if(S.push(O),x){A=F;break}if(tm({matchUp:{score:{sets:S},matchUpFormat:o}}).calculatedWinningSide)break}let N=tm({matchUp:{score:{sets:S},matchUpFormat:o,winningSide:r}}),D=A?r||A:N.calculatedWinningSide,{score:M}=Ky({winningSide:D,score:{sets:S},matchUpStatus:m});return{outcome:{winningSide:D,matchUpStatus:m,score:M}}}function z1({weightedRange:t=[0,1],pointsPerMinute:e,matchUpStatus:r,incomplete:n,setFormat:o,setNumber:i}){let s={setNumber:i},{setTo:a,tiebreakFormat:c,tiebreakAt:u,tiebreakSet:p,timed:m,minutes:d}=o,l=fo(0,t.length-1),f=t[l],g;if(m){let I=d*e,h=Math.round(I*.2),S=I+Zr([1,-1])*h,T=lC(S,2),y=[T,S-T];f&&y.reverse(),g=t[l]+1;let E=y[0]>y[1]&&1||y[1]>y[0]&&2||0;if(n){let[U,N]=y;return Object.assign(s,{side1Score:U,side2Score:N}),se.includes(r)?{set:s,incomplete:n,winningSideNumber:g}:{set:s,incomplete:n}}E||(y[fo(0,1)]+=1),E=y[0]>y[1]?1:2,E!==g&&y.reverse();let[P,A]=y;return Object.assign(s,{side1Score:P,side2Score:A,winningSide:g}),{set:s}}else{if(n)return s.side1Score=fo(0,u),s.side2Score=fo(0,u),se.includes(r)&&(g=t[l]+1),{set:s,incomplete:n,winningSideNumber:g};{let I=tt(1,a+1).map(A=>tt(0,a+2-A).map(()=>A)).flat(),h=I[fo(0,I.length-1)],S=a&&qg({isSide1:!0,tiebreakAt:u,lowValue:h,setTo:a}),T=!S,y=t.length===1&&t[l]+1;if(!T){y?(S[0]>S[1]?1:2)!==y&&S.reverse():f&&S.reverse();let[A,U]=S;Object.assign(s,{side1Score:A,side2Score:U})}let E=Gu({matchUpScoringFormat:{setFormat:o},setObject:s}),P;if(E.hasTiebreakCondition||T){let{NoAD:A,tiebreakTo:U}=c||p||{},N=tt(1,U+1).map(R=>tt(0,U+2-R).map(()=>R)).flat(),D=N[fo(0,N.length-1)],M=zp({isSide1:!0,tiebreakNoAd:A,tiebreakTo:U,lowValue:D});if(M)if(T){let R=M[0]>M[1]?1:2;y?R!==y&&M.reverse():f&&M.reverse(),[s.side1TiebreakScore,s.side2TiebreakScore]=M,P=M[0]>M[1]&&1||M[1]>M[0]&&2||void 0}else E.leadingSide===2?[s.side1TiebreakScore,s.side2TiebreakScore]=M:[s.side2TiebreakScore,s.side1TiebreakScore]=M}s.winningSide=E.winningSide||E.leadingSide||y||P}}return{set:s}}function Dl(t){let{matchUpStatusProfile:e,completeAllMatchUps:r,randomWinningSide:n,tournamentRecord:o,completionGoal:i,drawDefinition:s,event:a}=t;if(!s)return{error:Z};let c=t.matchUpFormat||s.matchUpFormat||a?.matchUpFormat,u=s.structures.slice().sort(yi),p=0,{matchUps:m,matchUpsMap:d}=ce({matchUpFilters:{matchUpTypes:[Wt],roundNumbers:[1]},contextFilters:{stages:[rt,ct]},inContext:!0,drawDefinition:s});if(m?.length){let h=a?.category?.ageCategoryCode||a?.category?.categoryName;if(h){let T=xy({singlesOnly:!0,tournamentRecord:o,drawDefinition:s,scaleAccessor:{scaleName:h,sortOrder:nM,scaleType:Ii},event:a});if(T.error)return T;let{lineUps:y,participantsToAdd:E}=T;Sn({tournamentRecord:o,participants:E}),Ut({element:s,extension:{name:Co,value:y}})}else{let S=m[0]?.structureId,{positionAssignments:T}=Ct({drawDefinition:s,structureId:S});if(T?.length){let{participants:y}=Gt({participantFilters:{participantTypes:[Wt]},tournamentRecord:o}),E=P=>{let A=P.tieMatchUps.filter(de(kt)),U=P.tieMatchUps.filter(de(xt));A.forEach((N,D)=>{let M=N.matchUpId;N.sides.forEach(R=>{let{drawPosition:b}=R,v=y?.find(O=>{let{participantId:x}=O;return T.find(w=>w.participantId===x)?.drawPosition===b});if(v){let O=v.individualParticipantIds?.[D];O&&Sl({teamParticipantId:v.participantId,participantId:O,tournamentRecord:o,drawDefinition:s,tieMatchUpId:M,event:a})}})}),U.forEach((N,D)=>{let M=N.matchUpId;N.sides.forEach(R=>{let{drawPosition:b}=R,v=y?.find(O=>{let{participantId:x}=O;return T.find(w=>w.participantId===x)?.drawPosition===b});v&&v.individualParticipantIds?.slice(D*2,D*2+2)?.forEach(x=>{Sl({teamParticipantId:v.participantId,participantId:x,tournamentRecord:o,drawDefinition:s,tieMatchUpId:M,event:a})})})})};m.forEach(E)}}}let l=typeof r=="string"&&r,f=l&&he,g=u.length===2&&u[0].finishingPosition===gi&&jt(u.map(({stage:h})=>h),[rt,fe]).length===2,I=u.map(({structureId:h})=>h);for(let h of I){if(p>=i)break;let S=s.structures.find(E=>E.structureId===h),T=yt({contextFilters:{matchUpTypes:[xt,kt]},afterRecoveryTimes:!1,tournamentRecord:o,inContext:!0,drawDefinition:s,matchUpsMap:d,structure:S,event:a}).matchUps;T.length;let y=T.filter(({winningSide:E})=>!E).sort(Ri).map(Ue);for(let E of y){if(!isNaN(i)&&p>=i)break;let{matchUps:P}=yt({matchUpFilters:{matchUpTypes:[xt,kt]},afterRecoveryTimes:!1,tournamentRecord:o,inContext:!0,drawDefinition:s,matchUpsMap:d,structure:S,event:a}),A=P.find(N=>N.matchUpId===E),U=[Te,be].includes(A.matchUpStatus);if(A?.readyToScore&&!U){let D=Q1({matchUpStatusProfile:e,tournamentRecord:o,drawDefinition:s,targetMatchUp:A,matchUpFormat:c,matchUpStatus:f,scoreString:l,winningSide:!n&&1,event:a});if(D?.error)return D;p+=1}}g&&S.finishingPosition===gi&&t.completeRoundRobinPlayoffs&&zs({structureId:S.structureId,applyPositioning:!0,drawDefinition:s})}return{...C,completedCount:p}}function RM(t){let{matchUpStatusCodes:e,policyDefinitions:r,tournamentRecord:n,drawDefinition:o,targetMatchUp:i,matchUpStatus:s,matchUpFormat:a,scoreString:c,winningSide:u,event:p}=t;if(!i||i.matchUpStatus===Nt)return;let{matchUpId:m}=i||{},{outcome:d}=lI({matchUpFormat:a,matchUpStatus:s,scoreString:c,winningSide:u});return e&&(d.matchUpStatusCodes=e),Wu({tournamentRecord:n,policyDefinitions:r,drawDefinition:o,matchUpFormat:a,matchUpId:m,outcome:d,event:p})}function Q1(t){let{matchUpStatusProfile:e={},tournamentRecord:r,policyDefinitions:n,drawDefinition:o,matchUpStatus:i,matchUpFormat:s,targetMatchUp:a,scoreString:c,winningSide:u,event:p}=t;if(c||i)return RM(t);let{matchUpId:m}=a||{},{outcome:d}=II({matchUpStatusProfile:e,matchUpFormat:s,winningSide:u});return Wu({policyDefinitions:n,tournamentRecord:r,drawDefinition:o,matchUpFormat:s,matchUpId:m,outcome:d,event:p})}function cA({matchUpStatusProfile:t,completeAllMatchUps:e,randomWinningSide:r,tournamentRecord:n,drawProfiles:o,isMock:i,event:s}){let a=Ht({event:s}).flightProfile,{eventName:c,eventType:u,category:p}=s,{startDate:m}=n,d=[],l=p?.categoryName||p?.ageCategoryCode||p?.ratingType,f=s.drawDefinitions?.map(({drawId:g})=>g);if(Array.isArray(a?.flights))for(let[g,I]of a.flights.entries()){let{drawId:h,stage:S,drawName:T,drawEntries:y}=I;d.push(I.drawId);let E=o[g],{seedsCount:P,generate:A=!0}=E||{};if(A){let U=y.filter(Br(io)).map(Br(io)),N=l||c;if(n&&P&&P<=U.length&&tt(1,P+1).forEach((x,F)=>{let w={scaleValue:x,scaleName:N,scaleType:To,eventType:u,scaleDate:m},L=U[F];Mc({tournamentRecord:n,participantId:L,scaleItem:w})}),f?.includes(h))break;let D=wa({...E,matchUpType:u,seedingScaleName:N,tournamentRecord:n,drawEntries:y,drawName:T,drawId:h,isMock:i,event:s,stage:S});if(D.error)return{error:D.error,drawIds:[]};let{drawDefinition:M}=D;if(!M)return{error:Cr};let R=o[g]?.drawExtensions;if(Array.isArray(R)&&R.filter(kn).forEach(O=>Ut({element:M,extension:O})),D=vc({suppressNotifications:!0,tournamentRecord:n,drawDefinition:M,event:s}),D.error)return{error:D.error,drawIds:[]};if(E?.withPlayoffs){let O=M.structures?.[0].structureId,x=Bp({idPrefix:E.idPrefix,...E.withPlayoffs,tournamentRecord:n,drawDefinition:M,structureId:O,isMock:i,event:s});if(x?.error)return x}let b=E?.completionGoal;if(!(E?.automated===!1)&&(e||b)){let O=E?.matchUpFormat,x=Dl({completeAllMatchUps:!b&&e,matchUpStatusProfile:t,randomWinningSide:r,tournamentRecord:n,completionGoal:b,drawDefinition:M,matchUpFormat:O,event:s});if(x.error)return{error:x.error,drawIds:[]};let F=x.completedCount;if(E?.drawType===So){let w=M.structures?.find(k=>k.stage===rt);if(!w)return{error:wt};let L=zs({structureId:w.structureId,tournamentRecord:n,drawDefinition:M,event:s});if(L.error)return{error:L.error,drawIds:[]};let G=b?b-(F??0):void 0;if(L=Dl({completeAllMatchUps:!b&&e,completionGoal:b?G:void 0,matchUpStatusProfile:t,randomWinningSide:r,tournamentRecord:n,drawDefinition:M,matchUpFormat:O,event:s}),L.error)return{error:L.error,drawIds:[]}}}}}return{...C,drawIds:d}}function uA(t){let{participantsProfile:e={},uniqueParticipantsCount:r,ratingsParameters:n,tournamentRecord:o,eventProfile:i,eventIndex:s,event:a,uuids:c}=t,{category:u,gender:p,eventType:m}=a,d=de($n)(m)&&At||de(qr)(m)&&ft||m,l=r[rt]||0,f=r[ct]||0,g=i.drawProfiles?.length?l+f:i.participantsProfile?.participantsCount??0,I=[zt,oe].includes(p)?p:void 0,h=e?.idPrefix?`E-${s}-${e?.idPrefix}`:void 0,{participants:S}=aa({uuids:i.uuids||c,...e,scaledParticipantsCount:i.scaledParticipantsCount,consideredDate:o?.startDate,rankingRange:i.rankingRange,participantType:d,participantsCount:g,ratingsParameters:n,category:u,idPrefix:h,sex:I}),y=Sn({tournamentRecord:o,participants:S});if(y.error)return y;let E=S?.filter(({participantType:A})=>A===d),P=S?.map(St);return{uniqueDrawParticipants:E,uniqueParticipantIds:P}}function sw({autoEntryPositions:t,tournamentRecord:e,drawParticipants:r,drawProfile:n,event:o}){let{drawType:i=ho,qualifyingPositions:s=0,stage:a=rt,drawSize:c=0,drawName:u,drawId:p}=n,m=c-s,d=r.slice(0,m).map(St);if(d.length){let g=Vn({participantIds:d,autoEntryPositions:t,entryStage:a,tournamentRecord:e,event:o});if(g.error)return g}let l=d.map(g=>({entryStatus:kr,entryStage:a,participantId:g})),f=rm({drawName:u||i,qualifyingPositions:s,drawEntries:l,drawId:p,event:o,stage:a});return f.error?f:{...C}}function pA({uniqueDrawParticipants:t,autoEntryPositions:e,stageParticipants:r,tournamentRecord:n,drawProfiles:o,category:i,gender:s,event:a}){let c=0;for(let u of o){let{qualifyingPositions:p=0,uniqueParticipants:m,stage:d=rt,drawSize:l=0}=u,f=l-p,g=m||s||i||d===ct,I=g?t.slice(c,c+f):r[d||rt]||[];g&&(c+=f);let h=sw({autoEntryPositions:e,drawParticipants:I,tournamentRecord:n,drawProfile:u,event:a});if(h.error)return h}return{...C}}function mA(t){let{allUniqueParticipantIds:e,matchUpStatusProfile:r,participantsProfile:n,completeAllMatchUps:o,autoEntryPositions:i,hydrateCollections:s,randomWinningSide:a,ratingsParameters:c,tournamentRecord:u,eventProfile:p,eventIndex:m,publish:d,isMock:l,uuids:f}=t,g=p.gender,I=p.eventName,{eventType:h=$n,policyDefinitions:S,drawProfiles:T=[],eventExtensions:y,surfaceCategory:E,tieFormatName:P,processCodes:A,discipline:U,eventLevel:N,timeItems:D,ballType:M,category:R}=p,b=p.eventId||Mt(),v=p.tieFormat||(h===_e?no({namedFormat:P,event:{eventId:b,category:R,gender:g},hydrateCollections:s,isMock:l}):void 0),O=u.participants;for(let j of T)!g&&j.gender&&(g=j?.gender);let{stageParticipantsCount:x,uniqueParticipantsCount:F,uniqueParticipantStages:w}=sA({drawProfiles:T,category:R,gender:g}),L=de($n)(h)&&At||de(qr)(h)&&ft||h,{uniqueDrawParticipants:G=[],uniqueParticipantIds:k=[]}=w?uA({event:{eventType:h,category:R,gender:g},uniqueParticipantsCount:F,participantsProfile:n,ratingsParameters:c,tournamentRecord:u,eventProfile:p,eventIndex:m,uuids:f}):{},{eventAttributes:H}=p;typeof H!="object"&&(H={});let W=R?.categoryName||R?.ageCategoryCode||R?.ratingType;I=I||W||"Generated Event";let q={...H,surfaceCategory:E,processCodes:A,discipline:U,eventLevel:N,eventName:I,eventType:h,tieFormat:v,ballType:M,category:R,eventId:b,gender:g};if(y?.length&&Array.isArray(y)){let j=y.filter(kn);j?.length&&Object.assign(q,{extensions:j})}if(Array.isArray(D)&&D.forEach(j=>Xi({event:K,timeItem:j})),typeof S=="object")for(let j of Object.keys(S))Ji({policyDefinitions:{[j]:S[j]},event:q});q.category&&(q.category.categoryName=W);let Y,B=na({suppressNotifications:!1,internalUse:!0,tournamentRecord:u,event:q});if(B.error)return B;let K=B?.event,{stageParticipants:X}=aA({allUniqueParticipantIds:e,stageParticipantsCount:x,eventParticipantType:L,targetParticipants:O});if(T?.length){let j=pA({uniqueDrawParticipants:G,autoEntryPositions:i,stageParticipants:X,tournamentRecord:u,drawProfiles:T,category:R,gender:g,event:K});if(j.error)return j;let ot=cA({matchUpStatusProfile:r,completeAllMatchUps:o,randomWinningSide:a,tournamentRecord:u,drawProfiles:T,isMock:l,event:K});if(ot.error)return ot;Y=ot.drawIds}else if(p?.participantsProfile?.participantsCount){let j=G.map(St);if(j.length){let ot=Vn({participantIds:j,autoEntryPositions:i,tournamentRecord:u,entryStage:rt,event:K});if(ot.error)return ot}}return d&&ia({tournamentRecord:u,event:K}),{drawIds:Y,eventId:b,uniqueParticipantIds:k}}function hI({tournamentRecords:t,scheduleDate:e,venueId:r,round:n}){if(!Nr(e))return{error:je};let o="addSchedulingProfileRound",{extension:i}=mt({name:ya,tournamentRecords:t,discover:!0}),s=i?.value||[],a=s.find(l=>qn(e,l.scheduleDate));if(!a){let{startDate:l,endDate:f}=Jd({tournamentRecords:t}),g=new Date(e);if(l&&g<new Date(l)||f&&g>new Date(f))return{error:je};a={scheduleDate:e,venues:[]},s.push(a)}let c=a.venues.find(l=>l.venueId===r);c||(c={venueId:r,rounds:[]},a.venues.push(c));let u=["notBeforeTime"],p=l=>Object.keys(l).filter(f=>!u.includes(f)).sort().map(f=>ht(l[f])?p(l[f]):l[f]).flat().join("|");if(c.rounds.find(l=>p(l)===p(n)))return _({result:{error:YA},stack:o});c.rounds.push(n);let d=Cc({tournamentRecords:t,schedulingProfile:s});return d.error?d:{...C}}function aw({schedulingProfile:t,tournamentRecord:e}){if(typeof t!="object")return{error:V};let r=cs({tournamentRecord:e}).containedStructures,n=ye({tournamentRecord:e}).matchUps??[],{tournamentId:o}=e,i=[];for(let s of t){let{scheduleDate:a,venues:c=[]}=s;for(let u of c){let{rounds:p,venueId:m}=u;for(let d of p){let{drawId:l,winnerFinishingPositionRange:f,roundSegment:g}=d,h=n.filter(S=>{let T=f?.indexOf("-")>0&&f.split("-").map(E=>+E),y=S.finishingPositionRange?.winner;return S.drawId===l&&(!d.roundNumber||S.roundNumber===d.roundNumber)&&(!y||!T||jt(y,T).length===2||pt(y).length===pt(T).length&&jt(y,T).length===pt(y).length)})[0];if(h){let{eventId:S,roundNumber:T,drawName:y,structureName:E,roundName:P}=h,A=h.structureId;T&&!f&&(A=Object.keys(r).find(D=>r[D].includes(A))??A);let U={tournamentId:o,structureId:A,roundNumber:T,roundSegment:g,eventId:S,drawId:l},N=hI({tournamentRecords:{[o]:e},round:U,scheduleDate:a,venueId:m});if(N.error)return N;i.push({structureName:E,roundName:P,drawName:y,...U})}}}}return{scheduledRounds:i}}function gm(t){let e=et(t,[{drawProfile:!0,_ofType:Kr}]);if(e.error)return e;let{allUniqueParticipantIds:r=[],participantsProfile:n={},matchUpStatusProfile:o,completeAllMatchUps:i,autoEntryPositions:s,hydrateCollections:a,randomWinningSide:c,ratingsParameters:u,tournamentRecord:p,isMock:m=!0,drawProfile:d,startDate:l,drawIndex:f,uuids:g}=t,I=J(d,!1,!0),{excessParticipantAlternates:h=!0,matchUpFormat:S=Dn,drawType:T=ho,tournamentAlternates:y=0,alternatesCount:E=0,qualifyingPositions:P,qualifyingProfiles:A,generate:U=!0,eventExtensions:N,drawExtensions:D,completionGoal:M,tieFormatName:R,buildTeams:b,seedsCount:v,timeItems:O,drawName:x,category:F,idPrefix:w,publish:L,gender:G,stage:k}=I,H=I.drawSize||(I.ignoreDefaults?void 0:32),W=I.eventId||Mt(),q=d.eventType||d.matchUpType||$n,Y=q===qr?ft:At,B=ht(d.tieFormat)&&d.tieFormat||q===Ft&&no({event:{eventId:W,category:F,gender:G},namedFormat:R,hydrateCollections:a,isMock:m})||void 0,K=F?.categoryName||F?.ageCategoryCode||F?.ratingType,X=d.eventName||K||`Generated ${q}`,j=p?.participants||[],ot=(A?.map(Dt=>Dt.structureProfiles||[]).flat().reduce((Dt,ue)=>{let pe=!ue.participantsCount||ue.participantsCount>ue.drawSize?ue.drawSize:ue.participantsCount||0;return Dt+pe},0)||0)*(Y===ft?2:1),z=(!d.participantsCount||d.participantsCount>H?H:d.participantsCount)||0,Q={eventName:X,eventType:q,tieFormat:B,category:F,eventId:W,gender:G};Array.isArray(O)&&O.forEach(Dt=>Xi({event:Q,timeItem:Dt}));let{eventAttributes:ut}=d;if(typeof ut!="object"&&(ut={}),Object.assign(Q,ut),N?.length&&Array.isArray(N)){let Dt=N.filter(kn);Dt?.length&&Object.assign(Q,{extensions:Dt})}let it=[];if(n?.participantsCount===0||d.uniqueParticipants||ot||!p||G||F){let Dt=(z||0)+E+ot,ue=Dt,pe={[zt]:0,[oe]:0},Fe,ee;q===Ft&&({teamSize:Fe,genders:ee}=Pl({alternatesCount:E,tieFormatName:R,tieFormat:B,drawSize:H}),Object.keys(ee).forEach(Ze=>{[zt,oe].includes(Ze)&&ee[Ze]&&(pe[Ze]=H*ee[Ze])}),ue=Fe*((H||0)+ot));let Je=n?.idPrefix?`D-${f}-${n?.idPrefix}`:void 0,ar=aa({...n,scaledParticipantsCount:d.scaledParticipantsCount||n.scaledParticipantsCount,participantsCount:ue,consideredDate:p?.startDate,sex:G||n?.sex,rankingRange:d.rankingRange,uuids:d.uuids||g,ratingsParameters:u,participantType:Y,gendersCount:pe,idPrefix:Je,category:F}).participants;if(Q.category&&(Q.category.categoryName=K),p){let Ze=Sn({participants:ar,tournamentRecord:p});if(Ze.error)return Ze}if(ar.forEach(({participantId:Ze})=>it.push(Ze)),j=ar,q===Ft){let Ze=ee[zt]?ar.filter(({participantType:me,person:dr})=>me===At&&dr?.sex===zt).map(St):[],Pe=ee[oe]?ar.filter(({participantType:me,person:dr})=>me===At&&dr?.sex===oe).map(St):[],ae=ar.filter(({participantType:me})=>me===At).map(St).filter(me=>!Ze.includes(me)&&!Pe.includes(me)),hr=[...I.teamNames??[],...fm({count:Dt}).names],_r=Fe-(ee[zt]+ee[oe]),Kt=0,De=0,fr=0,Ne=tt(0,Dt).map(me=>{let dr=Pe.slice(Kt,Kt+ee[oe]),es=Ze.slice(De,De+ee[zt]),Tn=ae.slice(fr,fr+_r);Kt+=ee[oe],De+=ee[zt],fr+=_r;let mi=b!==!1?[...dr,...es,...Tn]:[];return{participantName:hr[me]||`Team ${me+1}`,participantOtherName:`TM${me+1}`,participantRole:xe,individualParticipantIds:mi,participantType:Ft,participantId:Mt()}}),On=Sn({participants:Ne,tournamentRecord:p});if(!On.success)return On;j=Ne}}let Et=Dt=>{let{participantType:ue}=Dt;return de($n)(q)&&ue===At||de(qr)(q)&&ue===ft?!0:q===Ft&&ue===Ft},_t=Dt=>!d.gender||Dt.person?.sex===d.gender?!0:Dt.individualParticipantIds?.some(ue=>{let pe=j.find(Fe=>Fe.participantId===ue);return pe&&_t(pe)}),Ae=j.filter(Et).filter(_t).filter(({participantId:Dt})=>!r.includes(Dt)),$t=Ae.slice(0,z).map(Dt=>Dt.participantId);if(m&&$t?.length){let Dt=Vn({autoEntryPositions:s,entryStage:k,tournamentRecord:p,participantIds:$t,event:Q});if(Dt.error)return Dt}let Se=ot?Ae.slice(z,z+ot).map(Dt=>Dt.participantId):0;if(m&&Se?.length){let Dt=0,ue=1,pe=(ee,Je)=>ee.stageSequence-Je.stageSequence,Fe=(ee,Je)=>ee.roundTarget-Je.roundTarget;for(let ee of A.sort(Fe)){ue=ee.roundTarget||ue;let Je=1,qt;for(let ar of ee.structureProfiles.sort(pe)){let Pe=(ar.drawSize||ym(ar.participantsCount))-(qt||0),ae=Se.slice(Dt,Dt+Pe),hr=Vn({entryStage:ct,entryStageSequence:Je,autoEntryPositions:s,tournamentRecord:p,participantIds:ae,roundTarget:ue,event:Q});if(hr.error)return hr;qt=ar.qualifyingPositions,Dt+=Pe,Je+=1}ue+=1}}let Or=h&&p?.participants?.filter(({participantId:Dt})=>!$t.includes(Dt)).filter(Et).filter(_t).slice(0,E||H-z||y).map(Dt=>Dt.participantId);if(m&&Or?.length){let Dt=Vn({participantIds:Or,autoEntryPositions:!1,entryStatus:rn,tournamentRecord:p,event:Q});if(Dt.error)return Dt.error}let pn=K||X;p&&v&&v<=$t.length&&tt(1,v+1).forEach((ue,pe)=>{let Fe={scaleName:pn,scaleDate:l,scaleType:ag,scaleValue:ue,eventType:q},ee=$t[pe];Mc({tournamentRecord:p,participantId:ee,scaleItem:Fe})});let Ir=wa({...J(d,!1,!0),tournamentRecord:p,seedingScaleName:pn,matchUpFormat:S,eventId:W,isMock:m,event:Q});if(Ir.error)return Ir;if(!Ir.drawDefinition)return{error:Cr};let{drawDefinition:Xe}=Ir,te=Xe.drawId;if(Array.isArray(D)&&D.filter(kn).forEach(Dt=>Ut({element:Xe,extension:Dt})),U){if(vc({drawDefinition:Xe,event:Q,suppressNotifications:!0}),d.withPlayoffs){let ue=Xe.structures?.[0].structureId,pe=Bp({...d.withPlayoffs,tournamentRecord:p,drawDefinition:Xe,structureId:ue,idPrefix:w,isMock:m,event:Q});if(pe?.error)return pe}let Dt=d.automated===!1;if(m&&!Dt){let ue=pe=>{let Fe=Dl({completeAllMatchUps:pe.completeAllMatchUps,completionGoal:pe.completionGoal,matchUpStatusProfile:o,randomWinningSide:c,tournamentRecord:p,drawDefinition:Xe,matchUpFormat:S,event:Q});if(Fe.error)return Fe;let ee=Fe.completedCount;if(T===So){let Je=Xe.structures?.find(Ze=>Ze.stage===rt);if(!Je)return{error:wt};zs({structureId:Je.structureId,tournamentRecord:p,drawDefinition:Xe,event:Q});let qt=M?M-(ee??0):void 0,ar=Dl({completionGoal:M?qt:void 0,matchUpStatusProfile:o,completeAllMatchUps:i,randomWinningSide:c,tournamentRecord:p,drawDefinition:Xe,matchUpFormat:S,event:Q});if(ar.error)return ar}};if(M&&ue({completionGoal:M}),d.outcomes){let{matchUps:pe}=ir({inContext:!0,drawDefinition:Xe,event:Q});for(let Fe of d.outcomes){let{matchUpStatus:ee=he,matchUpStatusCodes:Je,stageSequence:qt=1,matchUpIndex:ar=0,structureOrder:Ze,matchUpFormat:Pe,drawPositions:ae,roundPosition:hr,stage:_r=rt,roundNumber:Kt,winningSide:De,scoreString:fr}=Fe,Ne=pe?.reduce((Tn,mi)=>{let{structureId:ca,matchUpId:Ku}=mi;return Tn[ca]?Tn[ca].push(Ku):Tn[ca]=[Ku],Tn},{})??[],On=Object.assign({},...Object.keys(Ne).map((Tn,mi)=>({[Tn]:mi+1}))),dr=pe?.filter(Tn=>(!_r||Tn.stage===_r)&&(!qt||Tn.stageSequence===qt)&&(!Kt||Tn.roundNumber===Kt)&&(!hr||Tn.roundPosition===hr)&&(!Ze||On[Tn.structureId]===Ze)&&(!ae||jt(ae,Tn.drawPositions).length===2))?.[ar],es=RM({matchUpStatusCodes:Je,tournamentRecord:p,drawDefinition:Xe,targetMatchUp:dr,matchUpFormat:Pe,matchUpStatus:ee,scoreString:fr,winningSide:De});if(es?.error)return es}}i&&ue({completeAllMatchUps:i})}L&&ia({tournamentRecord:p,event:Q})}else{let Dt=rm({drawEntries:Xe.entries,drawName:x||T,qualifyingPositions:P,drawId:te,event:Q,stage:k});if(Dt.error)return Dt}return{...C,event:nt(Q),uniqueParticipantIds:it,targetParticipants:j,drawDefinition:Xe,eventId:W,drawId:te}}var CM=()=>({altitude:void 0,courtId:void 0,courtName:"",courtDimensions:void 0,latitude:void 0,longitude:void 0,surfaceCategory:void 0,surfaceType:void 0,surfacedDate:void 0,dateAvailability:[],onlineResources:[],pace:void 0,notes:void 0}),cw=CM;function dA(t){return parseInt(t)}function bM({startTime:t="",endTime:e=""}={}){if(!t||!e||!ws.test(t)||!ws.test(e))return!1;let[r,n]=t.split(":").map(dA),[o,i]=e.split(":").map(dA);return o<r?!1:!(r===o&&i<n)}function uw(t,e){let[r,n]=t.startTime.split(":").map(dA),[o,i]=e.startTime.split(":").map(dA);return r<o?-1:r>o?1:n<i?-1:n>i?1:0}function lA({dateAvailability:t}){if(!t)return{error:sE};if(!Array.isArray(t))return{error:Ql};let e="Dates must be formated => YYYY-MM-DD",r="Times must be 24 hour => 00:00";for(let n of t){if(typeof n!="object")return{error:Ql};let{date:o,startTime:i,endTime:s,bookings:a=[]}=n;if(!i||!s)return{error:Ql};if(o&&!No.test(o))return{error:je,dateAvailability:{date:o},info:e};if(!ws.test(i))return{error:Po,dateAvailability:{startTime:i},info:r};if(!ws.test(s))return{error:Po,dateAvailability:{endTime:s},info:r};if(i===s)return{error:Po,dateAvailability:{startTime:i,endTime:s},info:"startTime and endTime are equivalent"};if(!bM({startTime:i,endTime:s}))return{error:Po,dateAvailability:{startTime:i,endTime:s},info:"endTime must be after startTime"};if(a){if(!Array.isArray(a))return{error:Pm};for(let c of a){if(typeof c!="object")return{error:Pm};let{startTime:u,endTime:p}=c;if(!ws.test(u))return{error:Po,booking:{startTime:u},info:r};if(!ws.test(p))return{error:Po,booking:{endTime:p},info:r};if(u===p)return{error:Po,dateAvailability:{startTime:u,endTime:p},info:"startTime and endTime are equivalent"};if(!bM({startTime:u,endTime:p}))return{error:Po,dateAvailability:{startTime:u,endTime:p},info:"endTime must be after startTime"}}}}return{valid:!0}}function Nl({tournamentRecord:t,disableNotice:e,venueId:r,courtId:n,court:o}){let{venue:i}=qo({tournamentRecord:t,venueId:r});if(!i)return{error:ki};i.courts||(i.courts=[]);let s={...CM(),venueId:r,courtId:n};if(s.courtId||(s.courtId=Mt()),i.courts.some(c=>c.courtId===s.courtId))return{error:EE};{let c=(o?.dateAvailability||[]).map(m=>({...m,date:Pt(m.date),startTime:Qt(m.startTime),endTime:Qt(m.endTime),bookings:m.bookings?.map(({startTime:d,endTime:l,bookingType:f})=>({startTime:Qt(d),endTime:Qt(l),bookingType:f}))})),u=Object.keys(s);for(let m of u)if(o?.[m])if(m==="dateAvailability"){let d=lA({dateAvailability:c});if(!d.valid&&d.error)return d;s.dateAvailability=c}else s[m]=o[m];let p=s;return i.courts.push(p),e||lt({payload:{venue:i,tournamentId:t.tournamentId},topic:Ei,key:i.venueId}),{...C,court:J(s),venueId:r}}}function SI(t){let{tournamentRecord:e,venueId:r}=t;if(typeof r!="string"||!r)return{error:ti};let n=t.tournamentRecords??(e&&{[e.tournamentId]:e})??{},o=[],i;for(let s of Object.values(n)){let{venue:a}=qo({tournamentRecord:s,venueId:r});if(a){let c=X1({...t,tournamentRecord:s});for(let u of c?.courts??[])o.push(u?.courtId);if(c.error)return c;i=!0}}return i?{...C,courtIds:o}:{error:ki}}function X1({courtNameRoot:t="Court",dateAvailability:e=[],venueAbbreviationRoot:r,tournamentRecord:n,courtNames:o=[],courtTimings:i,courtsCount:s,startTime:a,courtIds:c,endTime:u,idPrefix:p,venueId:m,dates:d}){if(!m)return{error:ti};let l=qo({tournamentRecord:n,venueId:m});if(l.error)return l;let{venue:f}=l;if(!Zt(s)||!o)return{error:AE};s=s??o.length;let h=tt(0,s).map(S=>{let T=i?.[S],y=T?d.map(E=>({date:Yn(E),startTime:a,endTime:u,...T})):e;return T&&a&&u&&y.push({startTime:a,endTime:u}),{courtName:o[S]||r&&f?.venueAbbreviation&&`${f?.venueAbbreviation} ${S+1}`||`${t} ${S+1}`,dateAvailability:y}}).map((S,T)=>{let y=c?.pop()||p&&`${p}-${T+1}`;return Nl({disableNotice:!0,tournamentRecord:n,courtId:y,venueId:m,court:S})}).map(S=>S.court).filter(Boolean);return h.length!==s?_({info:"not all courts could be generated",result:{error:V}}):(f&&lt({payload:{venue:f,tournamentId:n.tournamentId},topic:Ei,key:f.venueId}),{...C,courts:J(h)})}function Ml({tournamentRecord:t,ignoreExistingVenues:e,venueProfiles:r,uuids:n}){let{startDate:o,endDate:i}=t,s=[];for(let[a,c]of r.entries()){let{venueAbbreviation:u,venueId:p=n?.pop()??Mt(),dateAvailability:m,startTime:d="07:00",endTime:l="19:00",courtTimings:f,courtsCount:g,courtNames:I,venueName:h,idPrefix:S,courtIds:T}=c,y={venueName:h||`Venue ${a+1}`,venueAbbreviation:u,venueId:p},E=lc({tournamentRecord:t,venue:y});if(E.error){if(e)continue;return E}s.push(p);let P=Ls(o,i),A=!Array.isArray(m)&&[{startTime:d,endTime:l}].concat(P.map(U=>({date:Yn(U),startTime:d,endTime:l})));if(g||I){let U=SI({dateAvailability:m||A,tournamentRecord:t,courtTimings:f,courtsCount:g,courtNames:I,startTime:d,idPrefix:S,courtIds:T,endTime:l,venueId:p,dates:P});if(U.error)return U}}return s}function pw(t){let{tournamentRecord:e,leagueProfiles:r,eventIds:n,venueIds:o,drawIds:i,allUniqueParticipantIds:s,uuids:a}=t,c=0;for(let p of r){let m=[],{tieFormatName:d=xm,teamProfiles:l=[],teamsCount:f=0,category:g,idPrefix:I,gender:h}=p,S=p.leagueName??p.eventName??`League ${c+1}`,T=p.leagueId??p.eventId??a?.pop()??Mt();n.push(T);let y=ht(p.tieFormat)&&p.tieFormat||no({event:{eventId:T,category:g,gender:h},namedFormat:d,isMock:t.isMock})||void 0;if(!y)return{error:vs};let E=Math.max(f,l.length),P=tt(0,E),{genders:A,teamSize:U}=Pl({tieFormat:y,drawSize:E}),N={[oe]:0,[Ar]:0,[is]:0,[zt]:0,[Pn]:0};Object.keys(A).forEach(R=>N[R]+=A[R]);for(let R of P){let b=l?.[R]?.teamName??`Team ${R+1}`,v=l?.[R]?.teamId||a?.pop()||Mt(),O=p.startDate??t.startDate,x=aa({...p?.participantsProfile,participantsCount:U,consideredDate:O,gendersCount:N,category:g,gender:h,uuids:a}).participants,F=x.map(W=>W.participantId),w=Ft,L=v??lm({participantType:w,idPrefix:I,index:R,uuids:a});m.push({participantId:L,entryStatus:kr,entryStage:rt});let G=l?.[R]?.venueIds??[],k={participantId:L,participantRole:xe,participantName:b,individualParticipantIds:F,participantType:w,homeVenueIds:G};G.forEach(W=>!o.includes(W)&&o.push(W)),s.push(...F),s.push(L);let H=Sn({participants:[k,...x],tournamentRecord:e});if(H.error)return H}let M={eventName:S,entries:m,eventType:Ft,tieFormat:y,category:g,eventId:T,gender:h};if(e.events||(e.events=[]),e.events.push(M),m.length){let R=(Zt(p.roundsCount)&&p.roundsCount)??p.roundsCount===nb?(E-1)*2:E-1,b=wa({automated:p.automated,tournamentRecord:e,drawType:$r,roundsCount:R,drawSize:E,event:M});if(b.error)return b;let{drawDefinition:v}=b;if(v){let O=v?.drawId;vc({drawDefinition:v,event:M,suppressNotifications:!0}),i.push(O)}}c++}let u=o.map(p=>({venueId:p}));Ml({tournamentRecord:e,ignoreExistingVenues:!0,venueProfiles:u,uuids:a})}var J1=["Generated Tournament","CourtHive Challenge","Replication Crisis","Open Competition","Factory Follies","Mock Tournament","Atomic Culture","Racket Rally","Stats Fail"];function vM(t){let{startDate:e,endDate:r}=t??{},{tournamentName:n=Zr(J1),ratingsParameters:o=we,tournamentExtensions:i,policyDefinitions:s,schedulingProfile:a,venueProfiles:c,uuids:u}=t??{},p=t?.isMock===!1?void 0:!0;if(e&&!Nr(e)||r&&!Nr(r))return{error:je};if(t.leagueProfiles&&!Array.isArray(t.leagueProfiles)||t.eventProfiles&&!Array.isArray(t.eventProfiles)||t.drawProfiles&&!Array.isArray(t.drawProfiles))return{error:V};if(!e){let S=new Date;e=Yn(r??S),r=Yn(S.setDate(S.getDate()+7))}if(!r){let S=new Date(e);r=Yn(S.setDate(S.getDate()+7))}let m=dm({...t.tournamentAttributes??{},tournamentName:n,startDate:e,endDate:r,isMock:p}),d=c?.length?Ml({tournamentRecord:m,venueProfiles:c,uuids:u}):[];if(i?.length&&Array.isArray(i)){let S=i.filter(T=>kn({extension:T}));S?.length&&Object.assign(m,{extensions:S,isMock:p})}if(typeof s=="object")for(let S of Object.keys(s))Ji({policyDefinitions:{[S]:s[S]},tournamentRecord:m});if(!t?.leagueProfiles?.length||t.eventProfiles?.length||t.drawProfiles?.length||t.participantsProfile){let S=iA({tournamentRecord:m,...t});if(!S.success)return S}let l=[],f=[],g=[];if(t.leagueProfiles){let S=pw({allUniqueParticipantIds:l,tournamentRecord:m,...t,eventIds:f,venueIds:d,drawIds:g});if(S?.error)return S}if(t.drawProfiles){let S=Z1({allUniqueParticipantIds:l,ratingsParameters:o,tournamentRecord:m,...t,eventIds:f,drawIds:g});if(S?.error)return S}if(t.eventProfiles){let S=t0({allUniqueParticipantIds:l,ratingsParameters:o,tournamentRecord:m,...t,eventIds:f,drawIds:g});if(S?.error)return S}let{scheduledRounds:I=void 0,schedulerResult:h={}}=a?e0({...t,tournamentRecord:m}):{};return lf(),nt({...C,tournamentRecord:m,scheduledRounds:I,schedulerResult:h,eventIds:f,venueIds:d,drawIds:g})}function Z1(t){let{tournamentRecord:e,drawProfiles:r,allUniqueParticipantIds:n,eventIds:o,drawIds:i}=t,s=0;for(let a of r){let c=gm({allUniqueParticipantIds:n,tournamentRecord:e,drawProfile:a,drawIndex:s,...t});if(c.error)return c;let{drawId:u,eventId:p,event:m,uniqueParticipantIds:d}=c;if(a?.addEvent!==!1){if(c=na({suppressNotifications:!1,internalUse:!0,tournamentRecord:e,event:m}),c.error)return c;u&&i.push(u),o.push(p)}d?.length&&n.push(...d),s+=1}}function t0(t){let{eventProfiles:e,allUniqueParticipantIds:r,eventIds:n,drawIds:o}=t,i=0;for(let s of e){let a=mA({...t,eventIndex:i,eventProfile:s});if(a.error)return a;let{eventId:c,drawIds:u,uniqueParticipantIds:p}=a;u&&o.push(...u),n.push(c),p?.length&&r.push(...p),i+=1}}function e0(t){let{schedulingProfile:e,tournamentRecord:r,autoSchedule:n,periodLength:o,scheduleCompletedMatchUps:i}=t,s=aw({schedulingProfile:e,tournamentRecord:r});if(s.error)return s;let a=s.scheduledRounds;if(n){let{tournamentId:c}=r,u={[c]:r};return{schedulerResult:mm({scheduleCompletedMatchUps:i,tournamentRecords:u,periodLength:o}),scheduledRounds:a}}return{scheduledRounds:a}}var wM={};Jt(wM,{anonymizeTournamentRecord:()=>_M,modifyTournamentRecord:()=>xM});function _M({keepExtensions:t=[],anonymizeParticipantNames:e=!0,tournamentRecord:r,tournamentName:n,personIds:o=[],tournamentId:i}){if(!r)return{error:$};let s=Array.isArray(t)?PU.concat(...t):PU,a=L=>Array.isArray(t)?L?.extensions?.filter(G=>s.includes(G.name)):L?.extensions,c={};r.extensions=a(r);let u=i||Mt();c[r.tournamentId]=u,r.tournamentId=u,r.createdAt=new Date().toISOString(),r.tournamentName=n||`Anonymized: ${Yn(new Date)}`,r.isMock=!0,delete r.parentOrganisation;for(let L of r.participants||[]){L.extensions=a(L),L.onlineResources=[];let G=Mt();c[L.participantId]=G,L.participantId=G}for(let L of r.participants||[])Array.isArray(L.individualParticipantIds)&&(L.individualParticipantIds=L.individualParticipantIds.map(G=>c[G]));let p=0;for(let L of r.venues||[]){L.venueAbbreviation=`V${p}`,L.extensions=a(L),L.venueName=`Venue #${p}`,L.onlineResources=[],L.addresses=[];let G=Mt();c[L.venueId]=G,L.isMock=!0,p+=1;let k=0;for(let H of L.courts||[])H.courtName=`V${p}C${k}`,H.extensions=a(H),H.onlineResources=[],H.isMock=!0,k+=1}let m=1;for(let L of r.events||[]){L.extensions=a(L),L.onlineResources=[],L.isMock=!0;let G=Mt();c[L.eventId]=G,L.eventId=G;let k=L.category?.categoryName||L.category?.ageCategoryCode||L.category?.ratingType||L.gender;if(L.eventName=`Event ${m} ${k}`,Array.isArray(L.entries))for(let W of L.entries)W.participantId=c[W.participantId];for(let W of L.drawDefinitions||[]){W.extensions=a(W);let q=Mt();if(c[W.drawId]=q,W.drawId=q,W.isMock=!0,Array.isArray(W.entries))for(let B of W.entries)B.participantId=c[B.participantId];let Y=B=>{B.extensions=a(B);let K=Mt();c[B.structureId]=K,B.structureId=K;for(let X of B.positionAssignments||[])X.participantId&&(X.participantId=c[X.participantId]);for(let X of B.seedAssignments||[])X.participantId&&(X.participantId=c[X.participantId]);for(let X of B.matchUps||[]){X.isMock=!0;for(let j of X.sides||[])j.lineUp&&(j.lineUp=j.lineUp.map(({participantId:ot,collectionAssignments:z})=>({participantId:c[ot],collectionAssignments:z})))}};for(let B of W.structures||[])if(Y(B),Array.isArray(B.structures))for(let K of B.structures)Y(K);for(let B of W.links||[])B.source.structureId=c[B.source.structureId],B.target.structureId=c[B.target.structureId]}let{extension:H}=mt({name:cn,element:L});Array.isArray(H?.value?.flights)&&H?.value.flights?.forEach(W=>{if(W.drawId=c[W.drawId],Array.isArray(W.drawEntries))for(let q of W.drawEntries)q.participantId=c[q.participantId]}),m+=1}let d=r.startDate||Yn(new Date),l=(r.participants||[]).filter(({participantType:L})=>L===At),f=l.reduce((L,G)=>{let k=G.person?.sex;return[zt,oe].includes(k)?L[k]+=1:L[is]+=1,L},{[zt]:0,[oe]:0,[is]:0}),g=Object.assign({},...Object.keys(f).map(L=>({[L]:nA({category:{ageCategoryCode:"O18"},count:f[L],addressProps:{citiesCount:10},personExtensions:[],consideredDate:d,sex:L})?.persons||[]}))),I={[zt]:0,[oe]:0,[is]:0},h=l.length,S=l.reduce((L,G)=>{let k=G.person?.addresses?.[0]||{},{city:H,state:W,postalCode:q}=k;return L.cities.includes(H)||L.cities.push(H),L.states.includes(W)||L.states.push(W),L.postalCodes.includes(q)||L.postalCodes.push(q),L},{cities:[],postalCodes:[],states:[]}),T=S.postalCodes.length,y=S.cities.length,E=S.states.length,{cities:P}=Jy({count:y||h,participantsCount:h}),{states:A}=Zy({count:E||h,participantsCount:h}),{postalCodes:U}=tA({count:T||h,participantsCount:h}),N={cities:P,states:A,postalCodes:U};l.forEach((L,G)=>{let k=L?.person,H=k?.sex||is,W=Pt(k?.birthDate)?.split("-")[0],q=I[H],Y=g[H][q];if(I[H]+=1,W){let[,B,K]=Y?.birthDate?.split("-")||[],X=[W,B,K].join("-");Y.birthDate=X}if(k?.addresses){let B=eA({...N,participantIndex:G,nationalityCode:Y.nationalityCode});Y.addresses=[B]}Y.personId=o?.[G]||Mt(),e?(Y.standardFamilyName=Y.lastName,Y.standardGivenName=Y.firstName,L.participantName=`${Y.standardGivenName} ${Y.standardFamilyName}`):(Y.standardFamilyName=k?.standardFamilyName,Y.standardGivenName=k?.standardGivenName),delete Y.firstName,delete Y.lastName,Y.extensions=a(k),L.person=Y,c[k?.personId]=Y.personId}),(r.participants||[]).filter(({participantType:L})=>L===ft).forEach(L=>{let{individualParticipantIds:G}=L;L.participantName=r0({individualParticipantIds:G,individualParticipants:l})});let M=(r.participants||[]).filter(({participantType:L})=>L===Ft),R=M.length,b=fm({count:R}).names;M.forEach((L,G)=>{L.participantName=b[G]});let v=(r.participants||[]).filter(({participantType:L})=>L===zr),O=v.length,x=fm({count:O,nameRoot:"Group"}).names;v.forEach((L,G)=>{L.participantName=x[G]});let{extension:F}=mt({element:r,name:ya});Array.isArray(F?.value)&&F?.value.forEach(L=>{L.tournamentId=c[L.tournamentId],L.structureId=c[L.structureId],L.eventId=c[L.eventId],L.drawId=c[L.drawId]});let{extension:w}=mt({element:r,name:Ta});return Array.isArray(w?.value)&&w?.value.forEach(L=>{L.personId=c[L.personId]}),{...C}}function r0({individualParticipantIds:t,individualParticipants:e}){let r=e.filter(({participantId:n})=>t.includes(n)).map(({person:n})=>n?.standardFamilyName).filter(Boolean).sort().join("/");return t.length===1&&(r+="/Unknown"),r}function xM(t){let{ratingsParameters:e=we,participantsProfile:r={},matchUpStatusProfile:n,completeAllMatchUps:o,autoEntryPositions:i,hydrateCollections:s,randomWinningSide:a,schedulingProfile:c,tournamentRecord:u,autoSchedule:p,eventProfiles:m,periodLength:d,venueProfiles:l,drawProfiles:f,isMock:g,uuids:I}=t;if(!u)return{error:$};let h=[],S=[],T=[];m?.forEach(D=>{let M=u.events?.find((R,b)=>D.eventIndex!==void 0&&b===D.eventIndex||D.eventName&&R.eventName===D.eventName||D.eventId&&R.eventId===D.eventId);M?.gender&&(D.gender=M.gender)});let y=u.participants?.length||void 0;y&&r?.idPrefix&&(r.idPrefix=`${r.idPrefix}-${y}`);let E=iA({startDate:u.startDate,participantsProfile:r,tournamentRecord:u,eventProfiles:m,drawProfiles:f,uuids:I});if(!E.success)return E;if(m){let D=u.events?.length||0;for(let M of m){let{ratingsParameters:R}=M,b=u.events?.find((v,O)=>M.eventIndex!==void 0&&O===M.eventIndex||M.eventName&&v.eventName===M.eventName||M.eventId&&v.eventId===M.eventId);if(b){let{gender:v,category:O,eventType:x}=b,{drawProfiles:F,publish:w}=M,L=de($n)(x)&&At||de(qr)(x)&&ft||x;if(F){let{stageParticipantsCount:G,uniqueParticipantsCount:k,uniqueParticipantStages:H}=sA({drawProfiles:F,category:O,gender:v}),{uniqueDrawParticipants:W=[],uniqueParticipantIds:q=[]}=H?uA({event:{eventType:x,category:O,gender:v},uniqueParticipantsCount:k,participantsProfile:r,ratingsParameters:R,tournamentRecord:u,eventProfile:M,uuids:I}):{};h.push(...q);let{stageParticipants:Y}=aA({targetParticipants:u.participants||[],allUniqueParticipantIds:h,stageParticipantsCount:G,eventParticipantType:L}),B=pA({uniqueDrawParticipants:W,autoEntryPositions:i,stageParticipants:Y,tournamentRecord:u,drawProfiles:F,category:O,gender:v,event:b});if(B.error||(B=cA({matchUpStatusProfile:n,completeAllMatchUps:o,randomWinningSide:a,tournamentRecord:u,drawProfiles:F,isMock:g,event:b}),B.error))return B;T.push(...B.drawIds)}w&&ia({tournamentRecord:u,event:b})}else{let v=mA({startDate:u.startDate,allUniqueParticipantIds:h,matchUpStatusProfile:n,participantsProfile:r,completeAllMatchUps:o,autoEntryPositions:i,randomWinningSide:a,ratingsParameters:R,tournamentRecord:u,eventProfile:M,eventIndex:D,uuids:I});if(v.error)return v;let{eventId:O,drawIds:x,uniqueParticipantIds:F}=v;x&&T.push(...x),S.push(O),F?.length&&h.push(...F),D+=1}}}if(f){let D=(u.events||[]).map(M=>M.drawDefinitions?.map(()=>1)||[]).flat().reduce((M,R)=>M+R,0);for(let M of f){let R=gm({startDate:u.startDate,allUniqueParticipantIds:h,matchUpStatusProfile:n,participantsProfile:r,completeAllMatchUps:o,autoEntryPositions:i,hydrateCollections:s,randomWinningSide:a,ratingsParameters:e,tournamentRecord:u,drawProfile:M,drawIndex:D,uuids:I});if(R.error)return R;let{drawId:b,eventId:v,event:O,uniqueParticipantIds:x}=R;if(R=na({tournamentRecord:u,event:O,internalUse:!0}),R.error)return R;b&&T.push(b),S.push(v),x?.length&&h.push(...x),D+=1}}let P=l?.length?Ml({tournamentRecord:u,venueProfiles:l}):[],A,U={};if(c?.length){let D={[u.tournamentId]:u},M=Cc({tournamentRecords:D,schedulingProfile:c});if(M.error)return M;if(p){let{tournamentId:R}=u,b={[R]:u};U=mm({tournamentRecords:b,periodLength:d})}}return{totalParticipantsCount:u.participants.length,scheduledRounds:A,schedulerResult:U,...C,eventIds:S,venueIds:P,drawIds:T}}var rR={};Jt(rR,{addDynamicRatings:()=>Vg,addIndividualParticipantIds:()=>om,addParticipant:()=>vn,addParticipants:()=>Sn,addPenalty:()=>ZM,addPersonRequests:()=>kM,addPersons:()=>tR,createGroupParticipant:()=>YM,createTeamsFromParticipantAttributes:()=>gI,deleteParticipants:()=>zi,filterParticipants:()=>Uu,findParticipant:()=>jM,getCompetitionParticipants:()=>jT,getPairedParticipant:()=>In,getParticipantEventDetails:()=>YT,getParticipantMembership:()=>qT,getParticipantScaleItem:()=>Rc,getParticipantSchedules:()=>$T,getParticipantSignInStatus:()=>KT,getParticipantTimeItem:()=>eS,getParticipants:()=>Gt,getScaleValues:()=>ga,mergeParticipants:()=>JM,modifyIndividualParticipantIds:()=>GM,modifyParticipant:()=>im,modifyParticipantName:()=>qM,modifyParticipantOtherName:()=>BM,modifyParticipantsSignInStatus:()=>VM,modifyPenalty:()=>QM,modifyPersonRequests:()=>LM,mutate:()=>eR,participantScaleItem:()=>Ao,query:()=>mN,regenerateParticipantNames:()=>WM,removeIndividualParticipantIds:()=>lg,removeParticipantIdsFromAllTeams:()=>vp,removePenalty:()=>zM,removePersonRequests:()=>FM,removeRatings:()=>KM,scaledTeamAssignment:()=>$M,setParticipantScaleItem:()=>Mc,setParticipantScaleItems:()=>hD,validateLineUp:()=>Ad});var eR={};Jt(eR,{addDynamicRatings:()=>Vg,addIndividualParticipantIds:()=>om,addParticipant:()=>vn,addParticipants:()=>Sn,addPenalty:()=>ZM,addPersonRequests:()=>kM,addPersons:()=>tR,createGroupParticipant:()=>YM,createTeamsFromParticipantAttributes:()=>gI,deleteParticipants:()=>zi,findParticipant:()=>jM,mergeParticipants:()=>JM,modifyIndividualParticipantIds:()=>GM,modifyParticipant:()=>im,modifyParticipantName:()=>qM,modifyParticipantOtherName:()=>BM,modifyParticipantsSignInStatus:()=>VM,modifyPenalty:()=>QM,modifyPersonRequests:()=>LM,regenerateParticipantNames:()=>WM,removeIndividualParticipantIds:()=>lg,removeParticipantIdsFromAllTeams:()=>vp,removePenalty:()=>zM,removePersonRequests:()=>FM,removeRatings:()=>KM,scaledTeamAssignment:()=>$M,setParticipantScaleItem:()=>Mc,setParticipantScaleItems:()=>hD});function fA(t=0){(typeof t!="number"||isNaN(t))&&(t=0);let e=new Date;return e.setHours(e.getHours()+t),e.getTime().toString(36).slice(-6).toUpperCase()}function gA({personRequests:t,personId:e,requests:r}){t[e]||(t[e]=[]);let n=r.filter(({requestType:o})=>o).map(o=>{let{date:i,startTime:s,endTime:a}=o;return o.requestType===wc&&(i=Pt(i),s=Qt(s),a=Qt(a),i&&s&&a)?{date:i,startTime:s,endTime:a,requestType:o.requestType}:o}).filter(Boolean);for(let o of n)o.requestId=fA(),t[e].push(o);return{mergeCount:n.length}}function Rl(t){let{tournamentRecords:e,personRequests:r}=t,n=et(t,[{[Re]:!0}]);if(n.error)return n;if(!r)return{...C};let o=Object.values(e);for(let i of o){let s=i.participants??[],a=[];for(let c of Object.keys(r))if(Bo({tournamentParticipants:s,personId:c})){let u=r[c];u.length&&a.push({personId:c,requests:u})}Object.keys(a).length&&Ut({element:i,extension:{value:a,name:Ta}})}return{...C}}function LM(t){let{tournamentRecords:e,requests:r,personId:n}=t,o=et(t,[{[Re]:!0},{requests:!0,[He]:Be,[Fr]:V}]);if(o.error)return o;let i=r.map(({requestId:u})=>u).filter(Boolean),{personRequests:s}=Oi({tournamentRecords:e}),a=u=>{s&&(s[u]=s[u].map(p=>{if(!i.includes(p.requestId))return p;let m=r.find(d=>d.requestId===p.requestId);if(m.requestType)return Object.assign(p,m)}).filter(Boolean))};if(n&&s?.[n])a(n);else if(s)for(let u of Object.keys(s))a(u);let c=r.filter(u=>!u.requestId);return c.length&&gA({personRequests:s,personId:n,requests:c}),Rl({tournamentRecords:e,personRequests:s})}function FM(t){let{tournamentRecords:e,requestType:r,requestId:n,personId:o,date:i}=t,s=et(t,[{[Re]:!0}]);if(s.error)return s;let{personRequests:a}=Oi({tournamentRecords:e}),c=p=>{a&&(a[p]=a[p].filter(m=>(!r||m.requestType!==r)&&(!n||m.requestId!==n)&&(!i||m.date!==i)),a?.[p]?.length||delete a[p])},u=!r&&!n&&!o&&!i;if(!u){if(o&&a?.[o])c(o);else if(a)for(let p of Object.keys(a))c(p)}return u||!a||!Object.keys(a).length?gr({name:Ta,tournamentRecords:e,discover:!0}):Rl({tournamentRecords:e,personRequests:a})}function kM(t){let{tournamentRecords:e,personId:r,requests:n}=t,o=et(t,[{[Re]:!0,[ub]:!0},{requests:!0,[He]:Be,[Fr]:V}]);if(o.error)return o;let{personRequests:i}=Oi({tournamentRecords:e}),{mergeCount:s}=gA({personRequests:i,personId:r,requests:n});return s&&i?Rl({tournamentRecords:e,personRequests:i}):{error:V}}function GM({individualParticipantIds:t,groupingParticipantId:e,tournamentRecord:r}){let n="modifyIndividualParticipantIds";if(!r)return _({result:{error:$},stack:n});if(!e||!t)return _({result:{error:st},stack:n});let o=r.participants||[],i=o.find(l=>l.participantId===e);if(!i)return _({result:{error:re},stack:n});if(![Ft,zr].includes(i.participantType))return _({result:{error:An},context:{participantType:i.participantType},stack:n});let s=t.filter(l=>o.find(g=>g.participantId===l)?.participantType!==At);if(s.length)return _({result:{error:wr,invalidParticipantIds:s},stack:n});let a=i.individualParticipantIds||[],c=t.filter(l=>!a.includes(l)),u=a.filter(l=>!t.includes(l)),p=om({individualParticipantIds:c,groupingParticipantId:e,tournamentRecord:r});if(p.error)return _({result:p,stack:n});let m=lg({individualParticipantIds:u,groupingParticipantId:e,tournamentRecord:r});if(m.error)return _({result:m,stack:n});let{topics:d}=Lr();if(d.includes(or)){let l=o.find(({participantId:f})=>f===e);lt({topic:or,payload:{tournamentId:r.tournamentId,participants:[l]}})}return{...p,...m}}function VM({tournamentRecord:t,participantIds:e,signInState:r}){if(!t)return{error:$};if(!Array.isArray(e))return{error:st};if(![du,BU].includes(r))return{error:V,signInState:r};let o=t.participants||[];if(!o.length)return{error:Ka};let i=o.map(St),s=e.filter(p=>!i.includes(p));if(s.length)return{error:V,context:{invalidParticipantIds:s}};let a=[],c=new Date().toISOString();for(let p of o){let{participantId:m}=p;if(e.includes(m)){let l=xg({duplicateValues:!1,tournamentRecord:t,participantId:m,timeItem:{itemType:cc,itemValue:r,createdAt:c}});if(l.error)return l;a.push(p)}}let{topics:u}=Lr();return a.length&&u.includes(or)&&lt({topic:or,payload:{tournamentId:t.tournamentId,participants:a}}),{...C}}function BM({tournamentRecord:t,participantId:e,participantOtherName:r}){if(!t)return{error:$};if(!e)return{error:ie};let{participant:n}=yo({tournamentRecord:t,participantId:e});if(!n)return{error:re};n.participantOtherName=r;let{topics:o}=Lr();return o.includes(or)&&lt({topic:or,payload:{tournamentId:t.tournamentId,participants:[n]}}),{...C}}function HM({personFormat:t,person:e}){let r=g=>g.replace(/\W/g,""),n=g=>/^[a-z]*$/.test(r(g)),o=g=>/^[A-Z]*$/.test(r(g)),i=g=>/^[LAST]{4}/.test(r(g)),s=g=>g.toLowerCase().indexOf("l")<g.toLowerCase().indexOf("f"),a=g=>g.indexOf(",")>=0,c=g=>g.toLowerCase().indexOf("f.")>=0,u=g=>g.toLowerCase().indexOf("f")<0,p=g=>g.indexOf(" ")>0;if(!e)return;let m=p(t)?" ":"",d=NS(e?.standardGivenName??""),l=NS(e?.standardFamilyName??"");if(!t)return`${d}${m}${l}`;c(t)&&!a(t)&&!s(t)&&(d=`${d[0]}.`),n(t)?(d=d.toLowerCase(),l=l.toLowerCase()):o(t)?(d=d.toUpperCase(),l=l.toUpperCase()):i(t)&&(l=l.toUpperCase());let f=`${d}${m}${l}`;return u(t)?f=l:s(t)&&(a(t)?f=`${l},${m}${d}`:f=`${l}${m}${d}`),f}function mw({participantMap:t,participant:e,formats:r}){let{participantType:n,individualParticipantIds:o,person:i}=e,s=n&&r[n];if(n!==Er&&s){let{personFormat:a,doublesJoiner:c}=s;n===At&&(e.participantName=HM({person:i,personFormat:a})),n===ft&&(e.participantName=o?.map(u=>{let p=t[u]?.person;return HM({person:p,personFormat:a})}).filter(Boolean).join(c??"/"))}}function WM({tournamentRecord:t,formats:e}){if(!t)return{error:$};if(!ht(e))return{error:st};let r=t.participants??[],n=_I(r,"participantId");for(let o of r)mw({participant:o,participantMap:n,formats:e});return{...C}}function jM(t){let{tournamentRecord:e,policyDefinitions:r,contextProfile:n,participantId:o,personId:i}=t,s=t.tournamentRecords||e&&{[e.tournamentId]:e}||{};if(typeof o!="string"&&typeof i!="string")return{error:st,stack:"publicFindParticipant"};let a,c;for(let u of Object.values(s)){c=u.tournamentId;let p=u.participants||[];if(a=Bo({tournamentParticipants:p,internalUse:!0,policyDefinitions:r,contextProfile:n,participantId:o,personId:i}),a)break}return{participant:a,tournamentId:c,...C}}function YM({individualParticipantIds:t=[],participantRoleResponsibilities:e,participantRole:r=dP,tournamentRecord:n,participantId:o,groupName:i}){if(!n)return{error:$};if(!i)return{error:st,info:"Missing groupName"};if(!Array.isArray(t))return{info:"Invalid individualParticipantIds",error:V};let a=(Gt({participantFilters:{participantTypes:[At]},tournamentRecord:n}).participants??[]).map(m=>m.participantId);for(let m of t)if(!a.includes(m))return{error:An,participantId:m};let c=nt({participantId:o||Mt(),participantRoleResponsibilities:e,participantName:i,individualParticipantIds:t,participantType:zr,participantRole:r}),u=vn({participant:c,tournamentRecord:n});if(u.error)return u;let{topics:p}=Lr();return p.includes(ei)&&lt({topic:ei,payload:{tournamentId:n.tournamentId,participants:[c]}}),{...C,participant:J(c)}}function qM({tournamentRecord:t,participantName:e,participantId:r}){if(!t)return{error:$};if(!r)return{error:ie};if(!e)return{error:st,info:"Missing participantName"};let{participant:n}=yo({tournamentRecord:t,participantId:r});if(!n)return{error:re};n.participantName=e;let{topics:o}=Lr();return o.includes(or)&&lt({topic:or,payload:{tournamentId:t.tournamentId,participants:[n]}}),{...C}}function $M({clearExistingAssignments:t=!0,individualParticipantIds:e,reverseAssignmentOrder:r,initialTeamIndex:n=0,scaledParticipants:o=[],teamParticipantIds:i,tournamentRecord:s,scaleAttributes:a,teamNameBase:c,teamsCount:u,eventId:p,event:m}){if(!s)return{error:$};if(!Array.isArray(i)&&!It(u)&&!p||!It(n)||o&&!Array.isArray(o)||a&&(typeof a!="object"||!Object.keys(a).length))return{error:V};if(!a&&!o.length||!o&&!(e&&a))return{error:st,info:"Missing scaling details"};if(p&&!i){if(m?.eventType!==br)return{error:jn};i=m?.entries?.filter(({entryStatus:h})=>h===kr).map(St)}if(!i?.length&&!u)return{info:"Missing teamParticipantIds or teamsCount",error:st};let d=e??o.map(({participantId:h})=>h);r&&(i?.reverse(),n+=1),n>(i?.length||0)-1&&(n=0);let l=i?.slice(n).concat(...i.slice(0,n))??[],f=[];for(let h of s.participants??[]){let{participantId:S,participantType:T}=h;if(l.includes(S)){if(T!==Er)return{error:An,participant:h};f.push(h)}}if(u&&f.length<u){let h=u-(f?.length||0),S=c??"Team",T=tt(0,h).map(A=>({participantName:`${S} ${A+1}`,participantType:Er,participantRole:xe})),{participants:y=[]}=Sn({participants:T,returnParticipants:!0,tournamentRecord:s}),E=y.map(St),P=s.participants?.filter(({participantId:A})=>E.includes(A))??[];f.push(...P)}if(!f.length)return{error:af};if(t)for(let h of f)h.individualParticipantIds=[];else{let h=f.map(S=>S).flat();e?.length?d=d.filter(S=>!h.includes(S)):o=o?.filter(({participantId:S})=>!h.includes(S))}if(!e?.length&&!o?.length)return{error:tp,info:"Nothing to be done"};if(!o.length){for(let h of s.participants??[]){let{participantId:S,participantType:T}=h;if(!d.includes(S))continue;if(T!==At)return{error:An,participant:h};let y=Ao({scaleAttributes:a,participant:h})?.scaleItem,E=a?.accessor?y?.scaleValue?.[a?.accessor]:y?.scaleValue,P={participantId:S,scaleValue:E};o.push(P)}if(!o.length)return{error:re}}o.sort((h,S)=>a?.sortOrder?(S?.scaleValue||0)-(h?.scaleValue||0):(h?.scaleValue||1/0)-(S?.scaleValue||1/0));for(let h of o)if(!h.participantId)return{error:V,scaledParticipant:h};let g=0;for(;g<o.length;){for(let h of f){if(g+1>o.length)break;let S=o[g];h.individualParticipantIds.push(S.participantId),g++}f.reverse()}let I=f.map(St);for(let h of s.events??[]){if(h.eventType!==br)continue;let S=(h.entries??[]).filter(T=>I.includes(T.participantId));for(let T of S){let y=T.participantId,P=f.find(U=>U.participantId===y)?.individualParticipantIds;h.entries=(h.entries??[]).filter(U=>!P.includes(U.participantId)),(h.drawDefinitions??[]).forEach(U=>{U.entries=(U.entries??[]).filter(N=>!P.includes(N.participantId))});let{flightProfile:A}=Ht({event:h});(A?.flights||[]).forEach(U=>{U.drawEntries=(U.drawEntries||[]).filter(N=>!P.includes(N.participantId))})}}return{...C,scaledParticipants:o}}function KM(t){let e=et(t,[{[ne]:!0,[Cf]:!0},{ratingType:!1,[er]:s=>we[s]}]);if(e.error)return e;let r=`${t.ratingType}.${Hm}`,n=t.asDynamic?r:t.ratingType,o=[Si,hi,t.eventType,n].join("."),i=t.tournamentRecord.participants??[];for(let s of i)s.timeItems&&(s.timeItems=s.timeItems.filter(a=>a.itemType!==o));return{...C}}function zM(t){let{tournamentRecords:e}=t;if(typeof e!="object"||!Object.keys(e).length)return{error:Lt};for(let r of Object.values(e)){let n=n0({...t,tournamentRecord:r});if(n.error&&n.error!==Vc)return n}return{...C}}function n0({tournamentRecord:t,penaltyId:e}){if(!t)return{error:$};if(!e)return{error:rf};let r=t?.participants??[],n=[],o=!1,i;return r.forEach(s=>{let a=!1;s.penalties=(s.penalties??[]).filter(c=>(c.penaltyId===e&&(a=!0,o||(i=c,o=!0)),a&&n.push(s),c.penaltyId!==e))}),i&&lt({topic:or,payload:{tournamentId:t.tournamentId,participants:n}}),i?{...C,penalty:i}:{error:Vc}}var o0=({penaltyId:t=Mt()}={})=>({refereeParticipantId:void 0,penaltyCode:void 0,penaltyType:void 0,extensions:void 0,matchUpId:void 0,createdAt:void 0,issuedAt:void 0,notes:void 0,penaltyId:t}),IA=o0;function QM(t){let{tournamentRecords:e}=t;if(typeof e!="object"||!Object.keys(e).length)return{error:Lt};for(let r of Object.values(e)){let n=i0({...t,tournamentRecord:r});if(n.error&&n.error!==Vc||n.success)return n}return{error:Vc}}function i0({tournamentRecord:t,modifications:e,penaltyId:r}){if(!t)return{error:$};if(!e)return{error:V,modifications:e};if(!r)return{error:rf};let n=t?.participants??[],o=Object.keys(IA()).filter(c=>c!=="penaltyId"),i=Object.keys(e).filter(c=>o.includes(c));if(!i.length)return{error:rp};let s,a=[];return n.forEach(c=>{let u=!1;c.penalties=(c.penalties??[]).map(p=>(p.penaltyId===r&&(u=!0,i.forEach(m=>Object.assign(p,{[m]:e[m]})),s||(s=p)),p)),u&&a.push(c)}),s&&lt({topic:or,payload:{tournamentId:t.tournamentId,participants:a}}),s?{...C,penalty:s}:{error:Vc}}function XM(t,e,r){return!t&&e?e:t&&!e||typeof t!="object"||typeof e!="object"?t:pt(Object.keys(t).concat(Object.keys(e))).reduce((o,i)=>{if(!e[i])o[i]=t[i];else if(!t[i])o[i]=e[i];else if(typeof t[i]!=typeof e[i])o[i]=e[i];else if(Array.isArray(t[i]))if(r===!0||Array.isArray(r)&&r.includes(i)){let s=pt(t[i].map(a=>JSON.stringify(a)).concat(e[i].map(a=>JSON.stringify(a)))).map(a=>JSON.parse(a));o[i]=s}else o[i]=e[i];else typeof t[i]=="object"?o[i]=XM(t[i],e[i],r):o[i]=e[i];return o},{})}function JM({participants:t=[],tournamentRecord:e,arraysToMerge:r}){if(!e)return{error:$};e.participants||(e.participants=[]);let n=t.filter(Br(io)).map(u=>({[u.participantId]:u})),o=Object.assign({},...n),i=[];e.participants=e.participants.map(u=>{if(o[u.participantId]){let p=XM(u,o[u.participantId],r);return i.push(p),p}return u});let s=e.participants.map(Br(io))||[],a=t.filter(({participantId:u})=>!s.includes(u)),{topics:c}=Lr();return a.length&&(e.participants=e.participants.concat(...a),c.includes(ei)&&lt({topic:ei,payload:{participants:a}})),i.length&&c.includes(or)&&lt({topic:or,payload:{tournamentId:e.tournamentId,participants:i}}),{modifiedParticipantsCount:i.length,newParticipantsCount:a.length,...C}}function ZM(t){let{tournamentRecord:e,participantIds:r}=t,n=t.tournamentRecords??(e&&{[e.tournamentId]:e})??{},o;for(let i of Object.values(n)){let a=(Gt({tournamentRecord:i}).participants??[])?.map(St).filter(c=>r.includes(c));a.length&&(o=s0({...t,penaltyId:t.penaltyId??o,tournamentRecord:i,participantIds:a}).penaltyId)}return o?{...C,penaltyId:o}:{error:re}}function s0({refereeParticipantId:t,tournamentRecord:e,participantIds:r,penaltyCode:n,penaltyType:o,extensions:i,penaltyId:s,matchUpId:a,issuedAt:c,notes:u}){if(!e)return{error:$};if(!r)return{error:ie};if(!o)return{error:yE};let m=(e?.participants??[]).filter(f=>r.includes(f.participantId));if(!m.length)return{error:re};let d=new Date().toISOString(),l=Object.assign(IA({penaltyId:s}),{refereeParticipantId:t,penaltyCode:n,penaltyType:o,matchUpId:a,createdAt:d,issuedAt:c,notes:u});return Array.isArray(i)&&i.forEach(f=>Ut({element:l,extension:f})),m.forEach(f=>{f.penalties||(f.penalties=[]),f.penalties.push(l)}),lt({topic:or,payload:{tournamentId:e.tournamentId,participants:m}}),{...C,penaltyId:l.penaltyId}}function tR({participantRole:t=xe,tournamentRecord:e,persons:r}){if(!e)return{error:$};if(!Array.isArray(r))return{error:V};if(!Object.keys(hd).includes(t))return{error:pE};let n=(e.participants||[]).map(({person:f})=>f?.personId).filter(Boolean),o=[],i=r.filter(f=>f&&(!f.personId||!n.includes(f.personId))).map(f=>(f.personId||(f.personId=Mt()),o.push(f.personId),f)),s=(f,g)=>Object.assign({},...Object.keys(f).filter(I=>!g.includes(I)).map(I=>({[I]:f[I]}))),a=i.map(f=>nt({extensions:f.participantExtensions,timeItems:f.participantTimeItems,participantType:At,participantRole:t,person:s(f,["participantExtensions","participantTimeItems","pairedPersons"])})),c=0,u=0,p=Sn({participants:a,tournamentRecord:e});if(p.error)return p;u=p.addedCount||0;let m=[],d=Gt({participantFilters:{participantTypes:[At]},tournamentRecord:e})?.participants??[];if(t===xe&&r.filter(({pairedPersons:f})=>f).forEach(({personId:f,pairedPersons:g})=>{Array.isArray(g)&&g.forEach(I=>{let h=[f,I.personId].map(S=>Bo({tournamentParticipants:d,personId:S})).filter(Boolean);if(h.length===2){let S=h.map(St);m.push(nt({extensions:I.participantExtensions,timeItems:I.timeItems,participantRole:xe,individualParticipantIds:S,participantType:ft}))}})}),m.length){if(p=Sn({participants:m,tournamentRecord:e}),p.error)return p;c=p.addedCount||0}let l=u+c;return{...C,addedCount:l,newPersonIds:o}}var mR={};Jt(mR,{bulkUpdatePublishedEventIds:()=>ry,getAllEventData:()=>ny,getCourtInfo:()=>md,getDrawData:()=>rl,getEventData:()=>nl,getEventPublishStatus:()=>Xr,getPublishState:()=>Is,getTournamentPublishStatus:()=>Au,getVenueData:()=>fc,mutate:()=>pR,publishEvent:()=>ia,publishEventSeeding:()=>nR,publishOrderOfPlay:()=>cR,publishParticipants:()=>aR,query:()=>TN,setEventDisplay:()=>fl,unPublishEvent:()=>uR,unPublishEventSeeding:()=>oR,unPublishOrderOfPlay:()=>sR,unPublishParticipants:()=>iR});var pR={};Jt(pR,{publishEvent:()=>ia,publishEventSeeding:()=>nR,publishOrderOfPlay:()=>cR,publishParticipants:()=>aR,setEventDisplay:()=>fl,unPublishEvent:()=>uR,unPublishEventSeeding:()=>oR,unPublishOrderOfPlay:()=>sR,unPublishParticipants:()=>iR});function nR({removePriorValues:t=!0,stageSeedingScaleNames:e,seedingScaleNames:r,tournamentRecord:n,status:o=Rr,drawIds:i=[],event:s}){if(!n)return{error:$};if(!s)return{error:Ot};let a=Xr({event:s,status:o}),c=(a?.seeding?.seedingScaleNames||r)&&{...a?.seeding?.seedingScaleNames,...r},u=(a?.seeding?.stageSeedingScaleNames||e)&&{...a?.seeding?.stageSeedingScaleNames,...e},p=nt({stageSeedingScaleNames:u,seedingScaleNames:c,published:!0,drawIds:i});return oa({statusObject:{seeding:p},removePriorValues:t,status:o,event:s}),lt({topic:FU,payload:{tournamentId:n.tournamentId,eventId:s.eventId,drawIds:i}}),{...C}}function oR({removePriorValues:t=!0,seedingScaleNames:e,tournamentRecord:r,status:n=Rr,drawIds:o,stages:i,event:s}){if(!r)return{error:$};if(!s)return{error:Ot};let a=Xr({event:s});if(a){let c=a.seeding;if(Array.isArray(i)&&c.stageSeedingScaleNames)for(let u of i)c.stageSeedingScaleNames[u]&&delete c.stageSeedingScaleNames[u];Array.isArray(e)&&c?.seedingScaleNames&&(c.seedingScaleNames=c.seedingScaleNames.filter(u=>!e.includes(u))),Array.isArray(o)&&c?.drawIds&&(c.drawIds=c.drawIds.filter(u=>!o.includes(u))),(!Object.values(c.stageSeedingScaleNames??{}).length&&!c.seedingScaleNames?.length&&!c.drawIds?.length||!i&&!e&&!o?.length)&&(delete c.stageSeedingScaleNames,delete c.seedingScaleNames,delete c.drawIds,c.published=!1),oa({statusObject:{seeding:c},removePriorValues:t,status:n,event:s})}return lt({topic:zf,payload:{tournamentId:r.tournamentId,eventId:s.eventId}}),{...C}}function iR(t){let e=Mr(t);if(!Object.keys(e).length)return{error:Lt};for(let r of Object.values(e)){let n=a0({tournamentRecord:r,...t});if(n.error)return n}return{...C}}function a0({removePriorValues:t=!0,tournamentRecord:e,status:r=Rr}){if(!e)return{error:$};let n=`${wo}.${Lo}`,{timeItem:o}=en({element:e,itemType:n}),i=o?.itemValue||{[r]:{}};return i[r]&&delete i[r].participants,to({timeItem:{itemValue:i,itemType:n},element:e,removePriorValues:t}),lt({payload:{tournamentId:e.tournamentId},topic:Ab}),{...C}}function sR(t){let e=Mr(t);if(!Object.keys(e).length)return{error:Lt};for(let r of Object.values(e)){let n=c0({tournamentRecord:r,...t});if(n.error)return n}return{...C}}function c0({removePriorValues:t=!0,tournamentRecord:e,status:r=Rr}){if(!e)return{error:$};let n=`${wo}.${Lo}`,{timeItem:o}=en({element:e,itemType:n}),i=o?.itemValue||{[r]:{}};return i[r]&&delete i[r].orderOfPlay,to({timeItem:{itemValue:i,itemType:n},element:e,removePriorValues:t}),lt({topic:Qf,payload:{tournamentId:e.tournamentId}}),{...C}}function aR(t){let e=Mr(t);if(!Object.keys(e).length)return{error:Lt};for(let r of Object.values(e)){let n=u0({tournamentRecord:r,...t});if(n.error)return n}return{...C}}function u0({removePriorValues:t,tournamentRecord:e,status:r=Rr}){if(!e)return{error:$};let n=`${wo}.${Lo}`,{timeItem:o}=en({element:e,itemType:n}),i=o?.itemValue||{[r]:{}};return i[r].participants={published:!0},to({timeItem:{itemValue:i,itemType:n},element:e,removePriorValues:t}),lt({payload:{tournamentId:e.tournamentId},topic:GU}),{...C}}function cR(t){let e=Mr(t);if(!Object.keys(e).length)return{error:Lt};for(let r of Object.values(e)){let n=p0({tournamentRecord:r,...t});if(n.error)return n}return{...C}}function p0({scheduledDates:t=[],removePriorValues:e,tournamentRecord:r,status:n=Rr,eventIds:o=[]}){if(!r)return{error:$};let i=`${wo}.${Lo}`,{timeItem:s}=en({element:r,itemType:i}),a=s?.itemValue||{[n]:{}};return a[n].orderOfPlay={published:!0,scheduledDates:t,eventIds:o},to({timeItem:{itemValue:a,itemType:i},element:r,removePriorValues:e}),lt({topic:kU,payload:{tournamentId:r.tournamentId,scheduledDates:t,eventIds:o}}),{...C}}function uR({removePriorValues:t=!0,tournamentRecord:e,status:r=Rr,event:n}){if(!e)return{error:$};if(!n)return{error:Ot};let o=`${wo}.${Lo}`,{timeItem:i}=gu({itemType:o,event:n}),s=i?.itemValue||{[r]:{}};return delete s[r].structureIds,delete s[r].drawDetails,delete s[r].drawIds,Xi({event:n,timeItem:{itemValue:s,itemType:o},removePriorValues:t}),oa({statusObject:{structureIds:void 0,drawIds:void 0,seeding:void 0},removePriorValues:t,status:r,event:n}),lt({topic:Kf,payload:{tournamentId:e.tournamentId,eventId:n.eventId}}),{eventId:n.eventId,...C}}var dR={};Jt(dR,{getEntryStatusReports:()=>lw,getParticipantStats:()=>dw,getStructureReports:()=>gw,getVenuesReport:()=>Iw});function dw({withCompetitiveProfiles:t,opponentParticipantId:e,withIndividualStats:r,teamParticipantId:n,tournamentRecord:o,withScaleValues:i,tallyPolicy:s,matchUps:a}){if(!o)return{error:$};if(a&&!Array.isArray(a))return{error:lr};if(a=a??ye({tournamentRecord:o,participantsProfile:i?{withScaleValues:i}:void 0}).matchUps,!a?.length)return{error:eo};let u=[];e&&u.push(e),n&&u.push(n);let p=u.length?{participantIds:u}:{participantTypes:[Er]},m=Gt({participantFilters:p,tournamentRecord:o}).participants??[];if(!m.every(({participantType:U})=>U===Er))return{error:wr};u.length||u.push(...m.map(St));let d=new Map,l=new Map,f=new Map,g=new Map,I=(U,N="")=>l.get(U)||l.set(U,{participantName:N,participantId:U,competitorIds:[],competitiveness:{},matchUpStatuses:{},tiebreaks:[0,0],matchUps:[0,0],points:[0,0],games:[0,0],sets:[0,0]})&&l.get(U);for(let U of m){let{participantId:N,individualParticipantIds:D}=U;g.set(N,D??[]),I(N,U.participantName)}if(n&&!g.get(n))return _({result:{error:re},context:{teamParticipantId:n}});if(e&&!g.get(e))return _({result:{error:re},context:{opponentParticipantId:e}});let h=[],S=U=>{let N=[[],[]];for(let M of U){let R=M.participant;if(R?.participantName){d.set(R.participantId,{participantName:R.participantName,ratings:R.ratings});let b=l.get(R.participantId);b&&(b.participantName=R.participantName)}}let D=({side:M,individualParticipantIds:R})=>M.participantId&&(!R?.length||R.includes(M.participantId))&&[M.participantId]||M.participant?.individualParticipantIds?.length&&(!R?.length||jt(R,M.participant?.individualParticipantIds).length===M.participant?.individualParticipantIds?.length)&&M.participant.individualParticipantIds;if(g.size){let M=(R,b)=>{for(let v of U){if(!v.participant)continue;let O=D({individualParticipantIds:b,side:v});if(O?.length){let x=v.sideNumber;if(!x)continue;let F=[R];r&&F.push(...O),N[x-1]=F;let w=l.get(R);for(let L of O.filter(Boolean))w&&!w.competitorIds.includes(L)&&w.competitorIds.push(L)}}};if(n)(!e||U.every(b=>b.participant&&(D({individualParticipantIds:g.get(n),side:b})||D({individualParticipantIds:g.get(e),side:b}))))&&M(n,g.get(n));else for(let[R,b]of g)M(R,b)}else if(r)for(let M of U){if(!M.participant)continue;let R=D({individualParticipantIds:[],side:M}),b=M.sideNumber;b&&(N[b-1]=R)}return N};for(let U of a){if(!ht(U))return{error:lr};let{matchUpStatus:N,matchUpFormat:D,matchUpType:M,winningSide:R,score:b,sides:v}=U;if(!v||!b||M===xr||N===Nt)continue;let O=S(v);if(!O.filter(Boolean).length)continue;let x=t&&R&&Su({matchUp:U})?.competitiveness;h.push(U);let F=vg({matchUpStatus:N,matchUpFormat:D,tallyPolicy:s,winningSide:R,score:b}),w=XS({matchUpStatus:N,matchUpFormat:D,tallyPolicy:s,winningSide:R,score:b}),{pointsTally:L,tiebreaksTally:G}=JS({matchUpFormat:D,score:b});O.forEach((k,H)=>{for(let W of k){let q=d.get(W)?.participantName,Y=I(W,q);if(Y){let B=(z,Q)=>Q.forEach((ut,it)=>Y[z][it]+=ut),K=H?[...G].reverse():G,X=H?[...L].reverse():L,j=H?[...w].reverse():w,ot=H?[...F].reverse():F;if(B("tiebreaks",K),B("points",X),B("games",j),B("sets",ot),R){let z=R-1===H?0:1;Y.matchUps[z]+=1}if(x){let z=x.toLowerCase();Y.competitiveness[z]||(Y.competitiveness[z]=[0,0]),Y.competitiveness[z][H]+=1}if(N){let z=N.toLowerCase();Y.matchUpStatuses[z]||(Y.matchUpStatuses[z]=0),Y.matchUpStatuses[z]+=1}}}})}let T=["tiebreaks","matchUps","points","games","sets"],y=["competitive","routine","decisive"],E=new Map,P=(U,N)=>(U??0)+(N??0);for(let[U,N]of l.entries()){for(let D of T){let M=N[D].reduce(P);if(M){let R=N[D][0]/M,b=`${D}Ratio`,v=parseFloat(R.toFixed(2));N[b]=v,f.set(U,!0),E.has(b)||E.set(b,[]),E.get(b)?.push(v)}}for(let D of y){let M=N.competitiveness?.[D]?.reduce(P);if(M){let R=N.competitiveness[D][0]/M,b=`${D}Ratio`,v=parseFloat(R.toFixed(2));N[b]=v}}}if(!n){let U=(N,D)=>D-N;for(let N of l.values())for(let D of T){let M=`${D}Ratio`;if(typeof N[M]=="number"){let R=E.get(M)?.sort(U).indexOf(N[M]);if(typeof R=="number"&&R>=0){let b=`${D}Rank`;N[b]=R+1}}}}let A={relevantMatchUps:h,...C};return n?(A.teamStats=l.get(n),e&&(A.opponentStats=l.get(e))):A.participatingTeamsCount=f.size,A.allParticipantStats=[...l.values()],A}function Im({participant:t,eventType:e}){let r=t?.person?.personId,n=t?.person?.personOtherIds?.[0],o=t?.person?.tennisId,i=t?.ratings?.[e]?.find(({scaleName:u})=>u===bg),s=i?.scaleValue,{wtnRating:a,confidence:c}=s||{};return{timeStamp:i?.scaleDate,personOtherId:n,confidence:c,wtnRating:a,personId:r,tennisId:o}}function lw({tournamentRecord:t}){if(!t)return{error:$};let e=t.tournamentId,{participantMap:r}=Gt({withScaleValues:!0,withEvents:!0,withSeeding:!0,tournamentRecord:t,withDraws:!0}),o=(ye({matchUpFilters:{matchUpTypes:[ua,_i]},tournamentRecord:t}).matchUps??[]).flatMap(({sides:f,matchUpType:g})=>f?.flatMap(I=>g===_i?I?.participant?.individualParticipantIds:I?.participant?.participantId||I.participantId).filter(Boolean)).filter(Boolean),i=[],s={},a={},c={},u=0,p=({id:f,entry:g,eventId:I,eventType:h})=>{let{qualifyingSeeding:S,mainSeeding:T,entryStatus:y,entryStage:E,drawId:P}=g;s[f]||(s[f]=[]);let{participant:A,events:U}=r?.[f]??{},N=Im({participant:A,eventType:h}),D=U?.[I]?.ranking;y===Rg&&i.push(f),s[f].push({participantType:A?.participantType,participantId:f,tournamentId:e,eventType:h,eventId:I,drawId:P,entryStatus:y,entryStage:E,...N,ranking:D,mainSeeding:T,qualifyingSeeding:S})};for(let f of t.events??[]){let g={},I=N=>{g[N]||(g[N]={count:0}),g[N].count+=1},{drawDefinitions:h=[],eventType:S,eventId:T}=f,y=h.flatMap(N=>{let{drawId:D,entries:M}=N;u+=1;let R=({stage:F,stageSequence:w})=>F===rt&&w===1||F===ct,v=(N.structures??[]).filter(R).flatMap(({positionAssignments:F})=>F).filter(Boolean).map(({participantId:F})=>F),O=({participantId:F})=>v.includes(F),x=F=>{let{participantId:w,entryStatus:L,entryStage:G}=F;I(L);let k=r?.[w]?.draws?.[D]?.seedAssignments?.[rt];return{qualifyingSeeding:r?.[w]?.draws?.[D]?.seedAssignments?.[ct],participantId:w,mainSeeding:k,entryStatus:L,entryStage:G,drawId:D}};return M?.filter(O).map(x)}),E=N=>{let D=N.participantId,M=r?.[D].participant.individualParticipantIds?.filter(R=>o.includes(R));return D&&{[D]:{individualParticipantIds:M}}};S===Vo?(()=>{let N=Object.assign({},...y.map(E).filter(Boolean)),D=M=>{N[M.participantId].individualParticipantIds.forEach(R=>{p({id:R,eventType:S,eventId:T,entry:M})})};y.forEach(D)})():y.forEach(N=>{p({id:N?.participantId,eventType:S,eventId:T,entry:N})});let A=Object.values(g).reduce((N,D)=>N+D.count,0);Object.keys(g).forEach(N=>{g[N].pct=g[N].count/A*100}),c[T]={tournamentId:e,eventId:T,entries:y,entryStatuses:g};let U=Object.assign({},...Qr.flatMap(N=>[{[N+"_count"]:g[N]?.count},{[N+"_pct"]:g[N]?.pct}]));a[T]={tournamentId:e,eventId:T,...U}}let m=Object.values(r??{}).filter(({participant:{participantType:f,participantRole:g}})=>f===At&&g===xe),d=m.filter(({participant:f})=>!o.includes(f.participantId)).map(({participant:f})=>f.participantId),l={nonParticipatingEntriesCount:d.length,individualParticipantsCount:m.length,eventsCount:Object.values(c).length,nonParticipatingParticipantIds:d,drawDefinitionsCount:u,tournamentId:e};return{entryStatusReports:Object.values(a).flat(),participantEntryReports:Object.values(s).flat(),eventReports:Object.values(c).flat(),withDrawnParticipantIds:i,tournamentEntryReport:l}}function fw({eventType:t,matchUps:e,eventId:r,drawId:n}){let o={},i=g=>{let I=g?.matchUpFormat;I&&(o[I]||(o[I]=0),o[I]+=1)},s=e.filter(g=>r?g.eventId===r:g.drawId===n).reduce((g,I)=>(i(I),(I.sides??[]).flatMap(h=>(h?.participant?.individualParticipants||[h?.participant]).filter(Boolean)).forEach(h=>g[h.participantId]=h),g),{}),a=Object.values(s),c=a.map(g=>Im({participant:g,eventType:t})).filter(({wtnRating:g})=>g),u=(a.length-c.length)/a.length*100,p=c.reduce((g,I)=>{let{wtnRating:h,confidence:S}=I;return g.totalWTN+=h,g.totalConfidence+=S,g},{totalWTN:0,totalConfidence:0}),m=c?.length?p.totalWTN/c.length:0,d=c?.length?p.totalConfidence/c.length:0,f=Object.values(o).reduce((g,I)=>g+(I||0),0);return{matchUpFormatCounts:o,matchUpsCount:f,avgConfidence:d,pctNoRating:u,avgWTN:m}}function gw(t){let{tournamentRecord:e,extensionProfiles:r,firstFlightOnly:n}=t;if(!e)return{error:pa};let o=[],i={},s={},a=[],c=Object.assign({},...(r??[]).map(({name:g,label:I,accessor:h})=>{let S=mt({element:e,name:g})?.extension?.value,T=h?fs({element:S,accessor:h})?.value:S;return{[I||g]:T}})),u=e?.tournamentId,m=ye({participantsProfile:{withScaleValues:!0},tournamentRecord:e}).matchUps??[],d=g=>en({itemType:Gf,itemSubTypes:[To],element:{timeItems:g}})?.timeItem?.itemValue?.scaleBasis,l=({positionManipulations:g})=>{g?.forEach(I=>{let{structureId:h,name:S}=I,T=I.drawPositions||[I.drawPosition];i[h]||(i[h]=[]),i[h].push(`${S}: ${T.join("/")}`)})},f=e?.events?.flatMap(({timeItems:g,drawDefinitions:I=[],extensions:h,eventType:S,eventName:T,eventId:y,category:E})=>{let A=h?.find(O=>O.name===cn)?.value?.flights?.map(O=>({[O.drawId]:O.flightNumber})),U=A&&Object.assign({},...A),N=h?.find(O=>O.name===Sa),D=g?.find(O=>O.itemType===Sa),M=N?.value?.length||D?.itemValue||0,R=Object.values(U??{}),b=U&&Math.min(...R),v=d(g);return s[y]={seedingBasis:v?JSON.stringify(v):void 0,totalPositionManipulations:0,maxPositionManipulations:0,generatedDrawsCount:0,drawDeletionsCount:M,tournamentId:u,eventId:y},I.filter(O=>!n||!A||U[O.drawId]===b).flatMap(O=>{let{matchUpFormat:x,tieFormat:F,timeItems:w,extensions:L,structures:G,drawName:k,drawType:H,drawId:W}=O,{matchUpFormatCounts:q,matchUpsCount:Y,avgConfidence:B,pctNoRating:K,avgWTN:X}=fw({eventType:S,matchUps:m,drawId:W}),j=d(w)||v,ot=m0({extensions:L}),z=ot?.length||0;return l({positionManipulations:ot}),s[y].totalPositionManipulations+=z,s[y].generatedDrawsCount+=1,z>s[y].maxPositionManipulations&&(s[y].maxPositionManipulations=z),G?.filter(Q=>Q.stageSequence===1&&[ct,rt,qe,fe].includes(Q.stage)).map(Q=>{let ut=[rt,fe].includes(Q.stage)?m.find(dr=>dr.structureId===Q.structureId&&dr.finishingRound===1&&dr.winningSide):void 0;Q.stage===rt&&o.push({eventName:T,drawName:k,structureId:Q.structureId});let Et=ut?.sides?.find(dr=>dr.sideNumber===ut.winningSide)?.participant,_t=Et?.participantType===Er&&Et.participantId,Ae=Et?.participantType===ft?Et.individualParticipants:[],$t=Im({participant:Ae?.[0]||Et,eventType:S}),{personId:Se,personOtherId:Or,tennisId:pn,confidence:Ir,wtnRating:Xe}=$t||{},te=Im({participant:Ae?.[1],eventType:S}),{personId:Dt,personOtherId:ue,tennisId:pe,confidence:Fe,wtnRating:ee}=te||{},{ageCategoryCode:Je,categoryName:qt,subType:ar}=E??{},Ze=Q.matchUpFormat||x,ae=(q[Ze]||0)/Y*100,{tieFormatName:hr,tieFormatDesc:_r}=tl(F),{tieFormatName:Kt,tieFormatDesc:De}=tl(Q.tieFormat),fr=_r===De,Ne=!fr&&Kt,On=Q.tieFormat&&!fr&&De,me=ot?.filter(dr=>dr.structureId===Q.structureId)?.length||0;return{...c,tournamentId:u,eventId:y,structureId:Q.structureId,drawId:W,eventType:S,category:ar,categoryName:qt,ageCategoryCode:Je,flightNumber:U?.[W],drawType:H,stage:Q.stage,seedingBasis:j?JSON.stringify(j):void 0,winningPersonId:Se,winningPersonOtherId:Or,winningPersonTennisId:pn,winningPersonWTNrating:Xe,winningPersonWTNconfidence:Ir,winningPerson2Id:Dt,winningPerson2OtherId:ue,winningPerson2TennisId:pe,winningPerson2WTNrating:ee,winningPerson2WTNconfidence:Fe,winningTeamId:_t,positionManipulations:me,pctNoRating:K,matchUpFormat:Ze,pctInitialMatchUpFormat:ae,matchUpsCount:Y,drawTieFormatName:hr,drawTieFormatDesc:_r,tieFormatName:Ne,tieFormatDesc:On,avgConfidence:B,avgWTN:X}})})});return o.forEach(({eventName:g,drawName:I,structureId:h})=>{i[h]?.length&&a.push({eventName:g,drawName:I,actions:i[h]})}),{eventStructureReports:Object.values(s),structureReports:f,flightReports:a}}function m0({extensions:t}){return t?.find(({name:e})=>e===ic)?.value?.slice(1)}function Iw({ignoreDisabled:t=!0,tournamentRecords:e,tournamentId:r,venueIds:n=[],dates:o=[]}){if(!Array.isArray(o))return{error:V,dates:o};if(!Array.isArray(n))return{error:V,venueIds:n};if(!(e&&Object.keys(e).filter(l=>!r||l===r)||[]).length)return{error:Lt};if(!o.every(Nr))return{error:je};let a=Uo({tournamentRecords:e,ignoreDisabled:t,dates:o});if(a.error)return a;let c=a?.venues?.filter(({venueId:l})=>!n?.length||n.includes(l)),u=a.courts?.reduce((l,f)=>(f.dateAvailability?.forEach(g=>{let I=g.date;l.includes(I)||l.push(I)}),l),[]).filter(l=>!o.length||o.includes(l)),p={venueIds:c?.map(({venueId:l})=>l)},{matchUps:m}=Un({afterRecoveryTimes:!0,tournamentRecords:e,matchUpFilters:p});return{venuesReport:c?.map(l=>d0(u,l,m))}}function d0(t,e,r){let{venueId:n,courts:o,venueName:i}=e,s={};return t.forEach(a=>{let c=0,u=0,p=0;for(let l of o){let f=l.dateAvailability.find(h=>h.date===a),I=(f&&Ms({courtDate:f}).timeSlots)?.reduce((h,S)=>{let{startTime:T,endTime:y}=S,E=Yt(y)-Yt(T);return h+E},0);I&&(p+=1),c+=I}let m=r.filter(({schedule:l})=>l.venueId===n&&qn(a,l.scheduledDate));m.forEach(({schedule:l})=>{let f=Qt(l.scheduledTime),g=Yr(f,l.averageMinutes),I=Yt(g)-Yt(f);u+=I});let d=c?(u/c*100).toFixed(2):"100";s[a]={scheduledMatchUpsCount:m.length,availableCourts:p,availableMinutes:c,scheduledMinutes:u,percentUtilization:d}}),{venueId:n,venueName:i,venueReport:s}}var PR={};Jt(PR,{addMatchUpCourtOrder:()=>Wy,addMatchUpEndTime:()=>Yy,addMatchUpOfficial:()=>fM,addMatchUpResumeTime:()=>$y,addMatchUpScheduleItems:()=>cm,addMatchUpScheduledDate:()=>sm,addMatchUpScheduledTime:()=>Jo,addMatchUpStartTime:()=>jy,addMatchUpStopTime:()=>qy,addSchedulingProfileRound:()=>hI,allocateTeamMatchUpCourts:()=>am,assignMatchUpCourt:()=>Zi,assignMatchUpVenue:()=>sa,bulkRescheduleMatchUps:()=>TR,bulkScheduleMatchUps:()=>Lc,bulkScheduleTournamentMatchUps:()=>ju,bulkUpdateCourtAssignments:()=>gR,calculateScheduleTimes:()=>yI,clearMatchUpSchedule:()=>AR,clearScheduledMatchUps:()=>pm,courtGridRows:()=>sl,findMatchUpFormatTiming:()=>Xp,findVenue:()=>qo,generateBookings:()=>um,generateVirtualCourts:()=>nm,getMatchUpsToSchedule:()=>ol,getPersonRequests:()=>Oi,getProfileRounds:()=>il,getScheduledRoundsDetails:()=>Vu,getSchedulingProfile:()=>Xo,getSchedulingProfileIssues:()=>iy,matchUpScheduleChange:()=>yR,modifyMatchUpFormatTiming:()=>Jg,mutate:()=>UR,proAutoSchedule:()=>fR,proConflicts:()=>hR,publicFindCourt:()=>SS,query:()=>UN,removeEventMatchUpFormatTiming:()=>ll,removeMatchUpCourtAssignment:()=>lR,reorderUpcomingMatchUps:()=>SR,scheduleMatchUps:()=>IR,scheduleProfileRounds:()=>mm,setMatchUpDailyLimits:()=>ER,setMatchUpHomeParticipantId:()=>uI,setSchedulingProfile:()=>Cc,toggleParticipantCheckInState:()=>Il,validateSchedulingProfile:()=>Jp});var UR={};Jt(UR,{addMatchUpCourtOrder:()=>Wy,addMatchUpEndTime:()=>Yy,addMatchUpOfficial:()=>fM,addMatchUpResumeTime:()=>$y,addMatchUpScheduleItems:()=>cm,addMatchUpScheduledDate:()=>sm,addMatchUpScheduledTime:()=>Jo,addMatchUpStartTime:()=>jy,addMatchUpStopTime:()=>qy,addSchedulingProfileRound:()=>hI,allocateTeamMatchUpCourts:()=>am,assignMatchUpCourt:()=>Zi,assignMatchUpVenue:()=>sa,bulkRescheduleMatchUps:()=>TR,bulkScheduleMatchUps:()=>Lc,bulkScheduleTournamentMatchUps:()=>ju,bulkUpdateCourtAssignments:()=>gR,calculateScheduleTimes:()=>yI,clearMatchUpSchedule:()=>AR,clearScheduledMatchUps:()=>pm,findMatchUpFormatTiming:()=>Xp,generateBookings:()=>um,generateVirtualCourts:()=>nm,matchUpScheduleChange:()=>yR,modifyMatchUpFormatTiming:()=>Jg,proAutoSchedule:()=>fR,proConflicts:()=>hR,removeEventMatchUpFormatTiming:()=>ll,removeMatchUpCourtAssignment:()=>lR,reorderUpcomingMatchUps:()=>SR,scheduleMatchUps:()=>IR,scheduleProfileRounds:()=>mm,setMatchUpDailyLimits:()=>ER,setMatchUpHomeParticipantId:()=>uI,setSchedulingProfile:()=>Cc,toggleParticipantCheckInState:()=>Il,validateSchedulingProfile:()=>Jp});function yI({calculateStartTimeFromCourts:t=!0,defaultRecoveryMinutes:e=0,averageMatchUpMinutes:r=90,remainingScheduleTimes:n,clearScheduleDates:o,tournamentRecords:i,periodLength:s,scheduleDate:a,startTime:c,venueIds:u,endTime:p}){if(typeof i!="object"||!Object.keys(i).length)return{error:Lt};s=s??Hu({recoveryMinutes:e,averageMatchUpMinutes:r});let{courts:m,venues:d}=Uo({dates:[a],ignoreDisabled:!0,tournamentRecords:i}),l=m?.filter(M=>!u||u.includes(M.venueId));c||(c=l?.reduce((M,R)=>{let v=R.dateAvailability?.find(O=>!O.date||qn(a,O.date))?.startTime??R.startTime;return v&&(!M||Yt(v)<Yt(M))?v:M},void 0)),p||(p=l?.reduce((M,R)=>{let v=R.dateAvailability?.find(O=>!O.date||qn(a,O.date))?.endTime??R.endTime;return v&&(!M||Yt(v)>Yt(M))?v:M},void 0));let f=Object.values(i),g=Object.assign({},...f.map(M=>(M.events??[]).map(R=>{let{scheduleTiming:b}=Ea({tournamentRecord:M,event:R});return{[R.eventId]:{event:R,scheduleTiming:b}}})).flat()),h=Bu({sortDateMatchUps:!1,tournamentRecords:i,matchUpFilters:{scheduledDate:a,venueIds:u}}),S=h?.dateMatchUps??[],T=h?.completedMatchUps??[],y=[];y.push(...S),y.push(...T);let E={averageTimes:[{minutes:{default:r}}],recoveryTimes:[{minutes:{default:e}}]},P=y?.map(({eventId:M,schedule:R,matchUpFormat:b})=>{let{event:v,scheduleTiming:O}=g[M],x=v?.eventType,F={...O,defaultTiming:E,matchUpFormat:b},{averageMinutes:w,recoveryMinutes:L}=Mp({eventType:x,timingDetails:F}),{courtId:G,venueId:k}=R,H=Qt(R.scheduledTime),W=Yr(H,w);return{recoveryMinutes:L,averageMinutes:w,periodLength:s,startTime:H,endTime:W,courtId:G,venueId:k}}),A={calculateStartTimeFromCourts:t,remainingScheduleTimes:n,averageMatchUpMinutes:r,date:a,clearScheduleDates:o,periodLength:s,startTime:c,endTime:p,bookings:P,courts:l},{scheduleTimes:U}=gl(A),N=u?.length===1&&u[0]||d?.length===1&&d[0].venueId||void 0,D=y.map(Ue);return{venueId:N,scheduleTimes:U,dateScheduledMatchUpIds:D}}function lR(t){let e=et(t,[{[Re]:!0}]);if(e.error)return e;let{removePriorValues:r,tournamentRecords:n,tournamentId:o,courtDayDate:i,matchUpId:s,courtId:a,drawId:c}=t,u=n[o];if(!u)return{error:$};let{drawDefinition:p,event:m}=Fo({tournamentRecord:u,drawId:c});if(!p)return{error:Z};let d=Bt({drawDefinition:p,event:m,matchUpId:s});if(d.error)return d;if(d?.matchUp?.matchUpType===xr){let{itemValue:l}=Yo({timeItems:d.matchUp.timeItems??[],itemType:po}),f=a&&l.filter(I=>I.courtId!==a);return Jr({duplicateValues:!1,removePriorValues:r,tournamentRecord:u,drawDefinition:p,matchUpId:s,timeItem:{itemType:po,itemValue:f}})}else return Zi({tournamentRecord:u,drawDefinition:p,courtDayDate:i,courtId:"",matchUpId:s})}function fR({scheduleCompletedMatchUps:t,tournamentRecords:e,scheduledDate:r,matchUps:n}){if(!Vr(n))return{error:V};if(n.some(({hasContext:g})=>!g))return{info:"matchUps must have { inContext: true, nextMatchUps: true }",error:Bc};let i=Bu({courtCompletedMatchUps:!0,withCourtGridRows:!0,minCourtGridRows:10,tournamentRecords:e,matchUpFilters:{localPerspective:!0,scheduledDate:r}});if(i.error)return i;let{rows:s}=i,a=[],c=g=>[(g.sides||[]).map(I=>[I.participantId,I.participant?.individualParticipantIds]),(g.potentialParticipants||[]).flat().map(I=>[I.participantId,I.individualParticipantIds])].flat(1/0).filter(Boolean),u=s?.reduce((g,I)=>{let h=[],S=[];Object.values(I).forEach(y=>{if(ht(y)&&(y.matchUpId&&(h.push(y.matchUpId),a.push(y)),y.sides)){let E=c(y);S.push(...E)}});let T=Object.values(I).filter(y=>ht(y)&&!y.matchUpId);return g.concat({matchUpIds:h,availableCourts:T,rowId:I.rowId,participantIds:S})},[]);n.filter(({matchUpStatus:g})=>g&&g!==Nt&&(t||!se.includes(g))).sort(Ri);let p=on({matchUps:n.concat(a),includeParticipantDependencies:!0,tournamentRecords:e}).matchUpDependencies,m=[],d=[];for(;n.length&&u.length;){let g=u.shift(),I=[];for(;n.length&&g.availableCourts.length;){let h=n.concat(I).map(D=>D.matchUpId),S=n.shift(),T=S?.matchUpId,y=T&&p[T].matchUpIds.concat(p[T].dependentMatchUpIds),E=T&&h.some(D=>p[T].matchUpIds.includes(D)),P=T&&d.some(D=>p[T].dependentMatchUpIds.includes(D)),A=g.matchUpIds.some(D=>y.includes(D)),U=c(S),N=g.participantIds.some(D=>U.includes(D));if(S&&!A&&!E&&!N&&!P){let D=g.availableCourts.shift();Object.assign(S.schedule,D.schedule),Object.assign(D,S),m.push(S),g.participantIds.push(...U),g.matchUpIds.push(T)}else S&&I.push(S)}n.push(...I),d.push(...g.matchUpIds)}let l=m.map(({matchUpId:g,tournamentId:I,schedule:h,drawId:S})=>({tournamentId:I,matchUpId:g,drawId:S,schedule:{...h,scheduledDate:r}}));return i=Lc({tournamentRecords:e,matchUpDetails:l}),{...i,scheduled:m,notScheduled:n}}function gR(t){let{courtDayDate:e}=t,r=et(t,[{courtAssignments:!0,[He]:Be,[Fr]:st},{[Re]:!0}]);if(r.error)return r;let n=t.courtAssignments.reduce((s,a)=>{let{tournamentId:c}=a;return s[c]||(s[c]=[]),s[c].push(a),s},{}),o;return Object.keys(n).every(s=>{let a=t[Re][s];if(!a)return o={error:$},!1;let c=n[s].reduce((p,m)=>{let{drawId:d}=m;return p[d]||(p[d]=[]),p[d].push(m),p},{});Object.keys(c).every(p=>{let{drawDefinition:m}=ze({tournamentRecord:a,drawId:p});return m?(c[p].every(d=>{let{matchUpId:l,courtId:f}=d,g=Zi({tournamentRecord:a,drawDefinition:m,courtDayDate:e,matchUpId:l,courtId:f});if(g.success)return g?.success;o={error:bE}}),!0):(o={error:Z},!1)})}),o||C}function IR(t){let{tournamentRecords:e,allDateMatchUpIds:r=[],averageMatchUpMinutes:n=90,recoveryMinutes:o=0,recoveryMinutesMap:i,matchUpPotentialParticipantIds:s={},individualParticipantProfiles:a={},matchUpNotBeforeTimes:c={},matchUpDailyLimits:u={},checkPotentialRequestConflicts:p=!0,remainingScheduleTimes:m,clearScheduleDates:d,periodLength:l=30,scheduleDate:f,matchUpIds:g,venueIds:I,startTime:h,endTime:S,dryRun:T}=t,y=et(t,[{[Re]:!0,[nc]:!0},{[er]:Nr,[Fr]:je,[sb]:!0},{[er]:B=>!B||!isNaN(B),[pb]:!1,[Fr]:V,[mb]:!1,[db]:!1}]);if(y.error)return y;let E=t.competitionMatchUps??Un({nextMatchUps:!0,tournamentRecords:e}).matchUps??[],P=t.matchUpDependencies??on({includeParticipantDependencies:!0,matchUps:E,tournamentRecords:e}).matchUpDependencies;E.forEach(B=>{B.schedule?.scheduledDate&&qn(f,Pt(B.schedule.scheduledDate))&&ra({matchUpPotentialParticipantIds:s,matchUpNotBeforeTimes:c,matchUp:B})});let A=g.map(B=>E.find(K=>K.matchUpId===B)).filter(Boolean),{venueId:U,scheduleTimes:N,dateScheduledMatchUpIds:D}=yI({tournamentRecords:e,remainingScheduleTimes:m,startTime:Qt(h),endTime:Qt(S),scheduleDate:Pt(f),averageMatchUpMinutes:n,clearScheduleDates:d,periodLength:l,venueIds:I}),M={},R=[],b={},v={},O={};E.filter(({matchUpId:B})=>D?.includes(B)).forEach(B=>{fI({matchUpPotentialParticipantIds:s,individualParticipantProfiles:a,matchUp:B,value:1});let K=B.schedule?.scheduledTime;if(K){b[B.matchUpId]=K;let X=i?.[B.matchUpId];xc({recoveryMinutes:X||o,matchUpPotentialParticipantIds:s,individualParticipantProfiles:a,matchUpNotBeforeTimes:c,averageMatchUpMinutes:n,matchUpDependencies:P,scheduleTime:K,matchUp:B})}});let F=A.filter(B=>{let K=D?.includes(B.matchUpId),X=[Nt,Rt,he,vr,nr,bt].includes(B?.matchUpStatus);return!K&&!B.winningSide&&!X}),{matchUpMap:w,overLimitMatchUpIds:L,participantIdsAtLimit:G}=F.reduce((B,K)=>{let{drawId:X,tournamentId:j,matchUpType:ot}=K,{participantIdsAtLimit:z,relevantParticipantIds:Q}=Ul({individualParticipantProfiles:a,matchUpPotentialParticipantIds:s,matchUpDailyLimits:u,matchUp:K});return z?.length?(B.overLimitMatchUpIds.push(K.matchUpId),B.participantIdsAtLimit.push(...z),B):(Q.forEach(ut=>{ka({individualParticipantProfiles:a,participantId:ut});let it=a[ut].counters;it[ot]?it[ot]+=1:it[ot]=1,it[mo]?it[mo]+=1:it[mo]=1}),B.matchUpMap[j]||(B.matchUpMap[j]={}),B.matchUpMap[j][X]?B.matchUpMap[j][X].push(K):B.matchUpMap[j][X]=[K],ra({matchUpPotentialParticipantIds:s,matchUpNotBeforeTimes:c,matchUp:K}),B)},{matchUpMap:{},overLimitMatchUpIds:[],participantIdsAtLimit:[]});F=F.filter(({matchUpId:B})=>!L.includes(B));let k=0,H=N?.length??0,{personRequests:W}=Oi({tournamentRecords:e,requestType:wc});for(;N?.length&&F.length&&k<=H;){k++;let{scheduleTime:B}=N.shift(),K=F.find(X=>{let{matchUpId:j}=X,{dependenciesScheduled:ot,remainingDependencies:z}=yl({matchUpScheduleTimes:b,matchUpDependencies:P,allDateMatchUpIds:r,matchUp:X});if(!ot)return O[j]||(O[j]=[]),O[j].push({scheduleTime:B,remainingDependencies:z}),!1;let{enoughTime:Q}=El({individualParticipantProfiles:a,matchUpNotBeforeTimes:c,matchUpDependencies:P,scheduleTime:B,matchUp:X});if(!Q)return v[j]||(v[j]=[]),v[j].push({scheduleTime:B}),!1;let{conflicts:ut}=Al({potentials:p,averageMatchUpMinutes:n,requestConflicts:M,personRequests:W,scheduleTime:B,scheduleDate:f,matchUp:X});if(ut?.length)return!1;let it=i?.[X.matchUpId];return xc({recoveryMinutes:it||o,matchUpPotentialParticipantIds:s,individualParticipantProfiles:a,matchUpNotBeforeTimes:c,averageMatchUpMinutes:n,matchUpDependencies:P,scheduleTime:B,matchUp:X}),b[X.matchUpId]=B,!0});F=F.filter(({matchUpId:X})=>X!==K?.matchUpId),K||R.push(B)}F.forEach(B=>{fI({individualParticipantProfiles:a,matchUpPotentialParticipantIds:s,value:-1,matchUp:B})});let q=[];Object.keys(w).forEach(B=>{let K=e[B];K&&Object.keys(w[B]).forEach(X=>{let{drawDefinition:j}=Fo({tournamentRecord:K,drawId:X});j&&w[B][X].forEach(({matchUpId:z})=>{let Q=b[z];if(Q){let ut=Q.split(":").map(ro).join(":"),it=`${Pt(f)}T${ut}`;T?q.push(z):(Jo({drawDefinition:j,matchUpId:z,scheduledTime:it}).success&&q.push(z),U&&sa({tournamentRecords:e,tournamentRecord:K,drawDefinition:j,matchUpId:z,venueId:U}))}})})});let Y=Qm(F);return{...C,requestConflicts:Object.values(M),remainingScheduleTimes:N?.map(({scheduleTime:B})=>B),individualParticipantProfiles:a,matchUpNotBeforeTimes:c,participantIdsAtLimit:G,skippedScheduleTimes:R,overLimitMatchUpIds:L,scheduledMatchUpIds:q,noTimeMatchUpIds:Y,recoveryTimeDeferred:v,dependencyDeferred:O}}function hR({tournamentRecords:t,matchUps:e}){if(!Vr(e))return{error:eo};if(e.some(({matchUpId:f,hasContext:g})=>f&&!g))return{info:"matchUps must have { inContext: true, nextMatchUps: true }",error:Bc};let r=Math.max(...e.map(({schedule:f})=>f?.courtOrder||1).map(f=>dt(f))),n=tt(1,r+1).map(f=>e.filter(g=>dt(g.schedule?.courtOrder)===f)),o={},i={},s={};n.flat().filter(Boolean).sort(Ri).forEach(({schedule:f})=>delete f[cg]);let c=pt(e.map(({drawId:f})=>f)),u=on({includeParticipantDependencies:!0,tournamentRecords:t,drawIds:c}).matchUpDependencies,p=n.map((f,g)=>f.reduce((I,h)=>{if(!h.matchUpId)return I;let{matchUpId:S,winnerMatchUpId:T,loserMatchUpId:y,schedule:E,sides:P,potentialParticipants:A}=h,U=E?.courtId;o[S]=g,i[U]=[],I.matchUpIds.push(S),s[S]=h;let N=u[S].matchUpIds;N.length&&I.sourceMatchUpIds.push(...N);let D=P?.map(R=>[R.participant?.individualParticipantIds,R.participantId]).flat().filter(Boolean)??[],M=A?.flat().map(({individualParticipantIds:R,participantId:b})=>[R,b]).flat().filter(Boolean)||[];return I.participantIds.push(...M,...D),T&&I.targetMatchUpIds.push(T),y&&I.targetMatchUpIds.push(y),I},{sourceMatchUpIds:[],targetMatchUpIds:[],participantIds:[],matchUpIds:[]})),m=(f,g)=>u[f].sources.reduce((I,h,S)=>h.includes(g)&&S+1||I,0),d=p.map(()=>[]),l=(f,g,I,h)=>{if(!s[f].schedule[cg]){s[f].schedule[cg]=g,s[f].schedule[XU]=h,d[o[f]].push({matchUpId:f,issueType:I,issueIds:h,issue:g});let S=s[f].schedule.courtId;i[S]||(i[S]=[]),i[S].push({matchUpId:f,issue:g,issueType:I,issueIds:h})}};return p.forEach((f,g)=>{let I=g?p[g-1]:void 0,h=p.slice(g+1),S={},T=yr(f.participantIds),y=Object.keys(T).filter(A=>T[A]>1),E=f.matchUpIds.filter(A=>u[A].participantIds.some(U=>y.includes(U)));E.forEach(A=>{S[A]||(S[A]={}),S[A][mc]||(S[A][mc]=E.filter(U=>U!==A))});let P=I&&f.participantIds.filter(A=>I.participantIds.includes(A));P&&P.forEach(A=>{let U=f.matchUpIds.concat(I.matchUpIds).filter(N=>u[N].participantIds.includes(A));U.forEach(N=>{S[N]||(S[N]={}),S[N][dc]||(S[N][dc]=U.filter(D=>D!==N))})}),f.matchUpIds.forEach(A=>{let U=u[A].matchUpIds;for(let D of h){let M=D.matchUpIds.filter(R=>U.includes(R));M?.length&&(M.forEach(R=>l(R,fS,Ua,[A])),l(A,fS,Ua,M))}if(S[A]?.[mc]&&l(A,mc,lS,S[A][mc]),f.sourceMatchUpIds.includes(A)){let D=f.matchUpIds.filter(M=>u[M].matchUpIds.includes(A));l(A,mc,Ua,D),f.matchUpIds.filter(M=>u[M].matchUpIds.includes(A)).forEach(M=>l(M,mc,Ua,[A]))}let N=I?.matchUpIds?.filter(D=>m(A,D)>1);if(N?.length&&(l(A,gS,Ua,N),N.forEach(D=>l(D,gS,Ua,[A]))),S[A]?.[dc]&&l(A,dc,lS,S[A][dc]),I?.targetMatchUpIds?.includes(A)){let D=s[A].schedule.courtId,M=U.filter(b=>I.matchUpIds.includes(b));M.some(b=>s[b].schedule.courtId===D)||(M.forEach(b=>l(b,dc,Ua,[A])),l(A,dc,Ua,M))}})}),{courtIssues:i,rowIssues:d}}function SR(t){let e="reorderUpcomingMatchUps",{tournamentRecords:r}=t;if(typeof r!="object"||!Object.keys(r).length)return _({result:{error:Lt},stack:e});let{matchUpsContextIds:n,firstToLast:o}=t;if(!n)return _({result:{error:st},stack:e});let i=n?.length;if(!i)return{...C};let s=0;return n.forEach((c,u)=>{let{tournamentId:p,drawId:m,matchUpId:d}=c,l=u+(o?-1:1);l<0&&(l=i-1),l===i&&(l=0);let f=n[l].schedule.scheduledTime,g=a({tournamentId:p,scheduledTime:f,matchUpId:d,drawId:m});if(g.success)s++;else return g}),s===i?C:_({result:{error:CE},stack:e});function a({tournamentId:c,scheduledTime:u,matchUpId:p,drawId:m}){let d=r[c],{drawDefinition:l}=Fo({tournamentRecord:d,drawId:m});return l?Jo({drawDefinition:l,scheduledTime:u,matchUpId:p}):{error:Cr}}}function TR(t){let{scheduleChange:e,matchUpIds:r,dryRun:n}=t;if(!r||!Array.isArray(r))return{error:ns};if(typeof e!="object")return{error:V};let o=Mr(t),i=[],s=[];for(let c of Object.values(o)){let u=l0({tournamentRecord:c,scheduleChange:e,matchUpIds:r,dryRun:n});if(u.error)return u;Array.isArray(u.notRescheduled)&&s.push(...u.notRescheduled);let p=Qm(u.notRescheduled),m=[];u.rescheduled?.forEach(d=>{let{matchUpId:l}=d;p.includes(l)&&m.push(l),i.push(d)}),m.length&&(s=u?.notRescheduled?.filter(({matchUpId:d})=>!m.includes(d))||[])}let a=!!(i.length&&!s.length);return{...C,rescheduled:i,notRescheduled:s,allRescheduled:a}}function l0({tournamentRecord:t,scheduleChange:e,matchUpIds:r,dryRun:n}){if(!t)return{error:$};if(!r||!Array.isArray(r))return{error:ns};if(typeof e!="object")return{error:V};let o=[],i=[],{minutesChange:s,daysChange:a}=e;if(!s&&!a)return{...C};if(s&&isNaN(s))return{error:V};if(a&&isNaN(a))return{error:V};let{matchUps:c}=ye({matchUpFilters:{matchUpIds:r},tournamentRecord:t}),u=({matchUpStatus:y})=>!se.includes(y),p=c?.filter(y=>xa({schedule:y.schedule})).filter(y=>u({matchUpStatus:y.matchUpStatus}));if(!p?.length)return{...C};let{tournamentInfo:m}=Ps({tournamentRecord:t}),{startDate:d,endDate:l}=m,f=p?.reduce((y,E)=>{let{matchUpId:P,drawId:A}=E;return y[A]?y[A].push(P):y[A]=[P],y},{}),g=1440;for(let y of Object.keys(f)){let E=Fo({tournamentRecord:t,drawId:y});if(E.error)return E;let P=E.drawDefinition,A=f[y].filter(U=>r.includes(U));for(let U of A)if(U&&P){let D=p.find(x=>x.matchUpId===U)?.schedule,{scheduledTime:M,scheduledDate:R}=D,b,v,O;if(!b&&a&&R){let x=Pt(R);O=up(x,a),b=new Date(O)<new Date(d)||new Date(O)>new Date(l)}if(s&&M){let x=Pt(M),w=Yt(Qt(M))+s;if(b=w<0||w>g,!b){let L=Yr(M,s),G=x&&O||R===x&&x;v=G?`${G}T${L}`:L}}if(b)i.push(U);else{if(!n){if(v){let x=Jo({scheduledTime:v,drawDefinition:P,matchUpId:U});if(x.error)return x}if(O){let x=sm({scheduledDate:O,drawDefinition:P,matchUpId:U});if(x.error)return x}}(v||O)&&o.push(U)}}}let I=ye({matchUpFilters:{matchUpIds:r},tournamentRecord:t}).matchUps??[],h=I.filter(({matchUpId:y})=>o.includes(y)),S=I.filter(({matchUpId:y})=>i.includes(y)),T=h.length&&!S.length;return{...C,rescheduled:h,notRescheduled:S,allRescheduled:T}}function yR(t){let e="matchUpScheduleChange",{tournamentRecords:r}=t;if(typeof r!="object"||!Object.keys(r).length)return{error:Lt};let{sourceMatchUpContextIds:n,targetMatchUpContextIds:o,sourceCourtId:i,targetCourtId:s,courtDayDate:a}=t||{},{drawId:c,matchUpId:u,tournamentId:p}=n||{},{drawId:m,matchUpId:d,tournamentId:l}=o||{};if(!u&&!d)return _({result:{error:st},stack:e});let{matchUps:f}=Un({matchUpFilters:{matchUpIds:[u,d].filter(Boolean),drawIds:[c,m].filter(Boolean)},tournamentRecords:t.tournamentRecords}),g=f?.find(({matchUpId:y})=>y===u),I=f?.find(({matchUpId:y})=>y===d),h=0;if(s&&u&&!d){let y=S({tournamentId:p,matchUpId:u,courtId:s,matchUp:g,drawId:c,tournamentRecords:r,sourceCourtId:i,courtDayDate:a});if(y?.success&&h++,y.error)return _({result:y,stack:e})}else if(i&&s&&u&&d){let y=S({tournamentId:p,matchUpId:u,courtId:s,matchUp:g,drawId:c,tournamentRecords:r,sourceCourtId:i,courtDayDate:a});if(y.success&&h++,y.error)return _({result:y,stack:e,info:"source"});let E=S({tournamentId:l,sourceCourtId:s,matchUpId:d,matchUp:I,courtId:i,drawId:m,tournamentRecords:r,courtDayDate:a});if(E.success&&h++,E.error)return _({result:E,stack:e,info:"target"})}else return{error:st};return h?C:_({result:{error:xs},stack:e});function S(y){let{tournamentRecords:E,tournamentId:P,matchUp:A,drawId:U}=y,N=E[P],{drawDefinition:D}=Fo({tournamentRecord:N,drawId:U});return A.matchUpType===Wt?T({...y,tournamentRecord:N,drawDefinition:D}):Zi({...y,tournamentRecord:N,drawDefinition:D})}function T({removePriorValues:y,tournamentRecords:E,tournamentRecord:P,drawDefinition:A,sourceCourtId:U,courtDayDate:N,matchUpId:D,matchUp:M,courtId:R}){let b=[R].concat(M.schedule.allocatedCourts.map(({courtId:v})=>v).filter(v=>v!==U));return am({removePriorValues:y,tournamentRecords:E,tournamentRecord:P,drawDefinition:A,courtDayDate:N,matchUpId:D,courtIds:b})}}function AR({scheduleAttributes:t=[po,jo,ji,Yi,qi,xo,Ni,Di,$i],tournamentRecord:e,drawDefinition:r,matchUpId:n}){let o="clearMatchUpSchedule",i=r?ir({matchUpFilters:{matchUpIds:[n]},inContext:!1,drawDefinition:r}).matchUps?.[0]:ye({matchUpFilters:{matchUpIds:[n]},tournamentRecord:e,inContext:!1}).matchUps?.[0];if(!i)return{error:Le};let s=(i.timeItems??[]).filter(a=>a?.itemType&&!t.includes(a?.itemType));return i.timeItems=s,gt({tournamentId:e.tournamentId,context:o,drawDefinition:r,matchUp:i}),{...C}}function ER(t){let{tournamentRecord:e,tournamentId:r,dailyLimits:n}=t,o=t.tournamentRecords||e&&{[e.tournamentId]:e}||{};if(typeof o!="object"||!Object.keys(o).length)return{error:Lt};if(typeof n!="object")return{error:Io};let i=Object.keys(o).filter(s=>!r||r===s);if(r&&!i.includes(r))return{error:V};for(let s of i){let a=o[s],c=Ut({extension:{name:su,value:{dailyLimits:n}},element:a});if(c.error)return c}return{...C}}var xR={};Jt(xR,{addCollectionDefinition:()=>UI,addCollectionGroup:()=>CR,aggregateTieFormats:()=>OR,compareTieFormats:()=>Qo,getTieFormat:()=>el,modifyCollectionDefinition:()=>AI,modifyTieFormat:()=>vR,mutate:()=>_R,orderCollectionDefinitions:()=>RR,query:()=>gN,removeCollectionDefinition:()=>EI,removeCollectionGroup:()=>NR,tieFormatGenderValidityCheck:()=>bm,validateCollectionDefinition:()=>Kc});var _R={};Jt(_R,{addCollectionDefinition:()=>UI,addCollectionGroup:()=>CR,aggregateTieFormats:()=>OR,modifyCollectionDefinition:()=>AI,modifyTieFormat:()=>vR,orderCollectionDefinitions:()=>RR,removeCollectionDefinition:()=>EI,removeCollectionGroup:()=>NR});function pi({drawDefinition:t,structureId:e,matchUpId:r,structure:n,matchUp:o,eventId:i,event:s}){let a="getTieFormat",c;if(e=n?.structureId??e,r=o?.matchUpId??r,(r||e)&&!t)return{error:Z};if(i&&s)c=ii(s);else if(r){if(t&&(!o||!n)){let u=Bt({drawDefinition:t,matchUpId:r});if(u.error)return u;if(u.matchUp?.matchUpType!==xr)return _({result:{error:lr},stack:a});n||(n=u.structure),o||(o=u.matchUp)}c=Ep({item:o,drawDefinition:t,structure:n,event:s})||Ep({item:n,drawDefinition:t,structure:n,event:s})||ii(t)||ii(s)}else if(t&&e){if(!n){let u=at({drawDefinition:t,structureId:e});if(u.error)return u;n=u?.structure}c=Ep({item:n,drawDefinition:t,structure:n,event:s})||ii(t)||ii(s)}else c=ii(t)||ii(s);return c?{...C,structure:n,tieFormat:c,matchUp:o}:_({result:{error:vs},stack:a})}function Cl({matchUp:t,updateInProgressMatchUps:e}){return!t.winningSide&&![se].includes(t.matchUpStatus)&&(e||t.matchUpStatus!==Gn&&!Ie(t))}function DR({from:t,to:e}){let r=Object.keys(t),n=jt(r,Object.keys(e)).length===r.length,i=r.filter(c=>t[c]!==e[c]).map(c=>({countChange:e[c]-t[c],collectionId:c})),s=r.every(c=>t[c]===e[c]);return{equivalent:n&&s,matchUpsCountChanges:i}}function Sw({updateInProgressMatchUps:t,tournamentRecord:e,drawDefinition:r,structure:n,tieFormat:o,eventId:i,matchUp:s,event:a,uuids:c}){let u="updateTieFormat",p=e?.tournamentId,m=0,d=0,l=0,f=0,g=o?.collectionDefinitions.reduce((P,A)=>(P[A.collectionId]=(P[A.collectionId]||0)+A.matchUpCount,P),{}),I=({tieFormat:P})=>{let A=P?.collectionDefinitions.reduce((U,N)=>(U[N.collectionId]=(U[N.collectionId]||0)+N.matchUpCount,U),{});return DR({from:A,to:g}).equivalent},h=pi({drawDefinition:r})?.tieFormat,S=pi({event:a})?.tieFormat;if(a&&i){for(let P of a.drawDefinitions??[])T({drawDefinition:P});a.tieFormat=sr(o),f+=1}else if(s){if(!s.tieMatchUps)return _({result:{error:lr},stack:u});let P=yr(s.tieMatchUps?.map(({collectionId:M})=>M)),A=DR({to:g,from:P}),{changes:U,changesArePossible:N,cannotChangeReaon:D}=hw({matchUp:s,check:A});if(A.equivalent)if(Cl({matchUp:s,updateInProgressMatchUps:t}))s.tieFormat=sr(o),f+=1;else return _({result:{error:Xl},info:"matchUp is IN_PROGRESS or COMPLETE",stack:u});else if(N)E({tieFormat:o,matchUp:s,changes:U,uuids:c});else return _({context:{collectionMap:g,matchUpMap:P},result:{error:ko},info:D||"specified changes not possible",stack:u});d+=1,gt({eventId:a?.eventId,context:u,drawDefinition:r,tournamentId:p,matchUp:s})}else if(n){let A=y({inheritedTieFormat:h??S,structure:n})?.modifiedMatchUpsCount;A&&(d+=A,m+=1,f+=1);let U=!n.tieFormat||Qo({ancestor:n.tieFormat,descendant:o}).different;U&&(n.tieFormat=sr(o),m+=1,f+=1),(A||U)&&r&&vt({structureIds:[n.structureId],eventId:a?.eventId,drawDefinition:r})}else if(r)T({drawDefinition:r}),r.tieFormat=sr(o),f+=1;else return{error:Z};return{modifiedStructuresCount:m,modifiedMatchUpsCount:d,addedMatchUpsCount:l,modifiedCount:f,...C,tieFormat:o};function T({drawDefinition:P}){let A=P.structures||[],U=[];for(let N of A){if(N.tieFormat)continue;let M=y({inheritedTieFormat:S,structure:N})?.modifiedMatchUpsCount;if(M){m+=1,d+=M;let R=N.structureId;U.push(R)}}return vt({structureIds:U,eventId:a?.eventId,drawDefinition:P}),U.length}function y({inheritedTieFormat:P,structure:A}){let U=0,N=yt({matchUpFilters:{matchUpTypes:[Wt]},structure:A})?.matchUps||[];for(let D of N){let M=Cl({matchUp:D,updateInProgressMatchUps:t}),R=!1,b=yr(D.tieMatchUps?.map(({collectionId:O})=>O)),v=DR({from:b,to:g});if(v.equivalent)D.tieFormat&&I(D)&&M&&(D.tieFormat=sr(o),R=!0);else{let{changes:O,changesArePossible:x}=hw({matchUp:D,check:v});if(x&&!D.tieFormat)E({changes:O,matchUp:D,tieFormat:o,uuids:c});else if(P)(!D.tieFormat||Qo({ancestor:P,descendant:D.tieFormat}).different)&&(D.tieFormat=P,R=!0);else return _({result:{error:vs},stack:u})}R&&(U+=1,gt({tournamentId:e?.tournamentId,drawDefinition:r,context:u,eventId:i,matchUp:D}))}return{modifiedMatchUpsCount:U}}function E({uuids:P,matchUp:A,tieFormat:U,changes:N}){A.tieFormat=sr(U);let D=[],M=[];return N.forEach(R=>{if(R.countChange>0){let b=Math.max(0,...A.tieMatchUps.filter(x=>x.collectionId===R.collectionId).map(Br("collectionPosition"))),v=U.collectionDefinitions.find(x=>x.collectionId===R.collectionId),O=Ru({matchUpsLimit:R.countChange,collectionPositionOffset:b,collectionDefinition:v,matchUp:A,uuids:P});M.push(...J(O,!1,!0)),l+=M.length,A.tieMatchUps.push(...O)}else{let b=R.toBePlayedTieMatchUpIds.slice(0,Math.abs(R.countChange));console.log("remove",b.length),D.push(...b),A.tieMatchUps=A.tieMatchUps.filter(({matchUpId:v})=>!b.includes(v))}}),M.length&&vo({matchUps:M,drawDefinition:r,tournamentId:p,eventId:i}),D.length&&Rn({matchUpIds:D,action:"updateTieFormat",drawDefinition:r,tournamentId:p,eventId:i}),{matchUpIdsRemoved:D,matchUpsAdded:M}}}function hw({check:t,matchUp:e}){let r="",n=[];return{changesArePossible:t.matchUpsCountChanges.every(({collectionId:i,countChange:s})=>{let a=e.tieMatchUps.filter(u=>u.collectionId===i&&u.matchUpStatus===Xt).map(Br("matchUpId")),c=a.length+s>=0||s>0;return!c&&s<0&&(r="Insufficient TO_BE_PLAYED matchUps"),n.push({toBePlayedTieMatchUpIds:a,collectionId:i,countChange:s}),c}),changes:n,cannotChangeReaon:r}}function Yu({appliedPolicies:t,drawDefinition:e,auditData:r}){if(!t?.audit?.[zm])return;let{extension:n}=mt({name:zm,element:e}),o={value:Array.isArray(n?.value)?n?.value.concat(r):[r],name:zm};Ut({element:e,extension:o})}function AI({updateInProgressMatchUps:t=!1,tournamentRecord:e,collectionOrder:r,collectionName:n,tieFormatName:o,drawDefinition:i,matchUpFormat:s,matchUpCount:a,collectionId:c,matchUpType:u,structureId:p,matchUpId:m,category:d,eventId:l,gender:f,event:g,collectionValueProfiles:I,collectionValue:h,matchUpValue:S,scoreValue:T,setValue:y}){let E="modifyCollectionDefinition";if(s&&!Dr({matchUpFormat:s}))return _({result:{error:V},context:{matchUpFormat:s},stack:E});if(n&&typeof n!="string")return _({result:{error:V},context:{collectionName:n},stack:E});if(f&&!Object.values(Cm).includes(f))return _({result:{error:V},context:{gender:f},stack:E});if(d&&typeof d!="object")return _({result:{error:V},context:{category:d},stack:E});let P={collectionValueProfiles:I,collectionValue:h,matchUpValue:S,scoreValue:T,setValue:y};if(!Object.values(P).filter(Boolean).length&&!r&&!n&&!s&&!a&&!u)return _({result:{error:st},stack:E});if(Object.values(P).filter(Boolean).length>1)return _({info:"Only one value assignment allowed per collectionDefinition",result:{error:V},stack:E});let A=pi({drawDefinition:i,structureId:p,matchUpId:m,eventId:l,event:g});if(A.error)return _({result:A,stack:E});let{matchUp:U,structure:N,tieFormat:D}=A,M=sr(D),R=D?.collectionDefinitions.find(q=>q.collectionId===c),b=M?.collectionDefinitions.find(q=>q.collectionId===c);if(!R)return _({info:"source collectionDefinition",result:{error:ve},context:{collectionId:c},stack:E});let v=h??S??T??y;if(I?.length){let q=xI({matchUpCount:a??R?.matchUpCount??0,collectionValueProfiles:I});if(q.errors)return _({result:{error:V},info:q.errors,stack:E})}else if(v&&!It(v))return _({result:{error:V},info:"value is not an integer",context:{value:v},stack:E});let O=(q,Y)=>jt(Object.keys(q),Object.keys(Y)).length===Object.keys(q).length&&jt(Object.values(q),Object.values(Y)).length===Object.values(q).length,x=I&&(!R.collectionValueProfiles||!O(R.collectionValueProfiles,I)),F=It(h)&&R.collectionValue!==h||It(S)&&R.matchUpValue!==S||It(T)&&R.scoreValue!==T||It(y)&&R.setValue!==y||x,w=[];if(F&&(b.collectionValueProfiles=void 0,b.collectionValue=void 0,b.matchUpValue=void 0,b.scoreValue=void 0,b.setValue=void 0,Object.assign(b,P),w.push({collectionId:c,...nt(P)})),(It(T)||It(y))&&b.collectionGroupNumber){let q=b.collectionGroupNumber;M.collectionDefinitions=M.collectionDefinitions.map(Y=>{let{collectionGroupNumber:B,...K}=Y;return B===q?K:Y}),M.collectionGroups=M.collectionGroups.filter(({groupNumber:Y})=>Y!==q),w.push({collectionId:c,change:"collectionGroupNumber removed"})}let{aggregateValue:L,valueGoal:G}=Ds(M),k=nt({aggregateValue:L,valueGoal:G});if((k.aggregateValue!==D?.winCriteria.aggregateValue||k.valueGoal!==D?.winCriteria.valueGoal)&&(M.winCriteria=k,w.push({collectionId:c,winCriteria:k})),It(r)&&R.collectionOrder!==r&&(b.collectionOrder=r,w.push({collectionId:c,collectionOrder:r})),n&&R.collectionName!==n&&(b.collectionName=n,w.push({collectionId:c,collectionName:n})),s&&R.matchUpFormat!==s&&(b.matchUpFormat=s,w.push({collectionId:c,matchUpFormat:s})),It(a)&&R.matchUpCount!==a&&(b.matchUpCount=a,w.push({collectionId:c,matchUpCount:a})),u&&R.matchUpType!==u)return _({result:{error:np},context:{matchUpType:u},stack:E});d&&R.category!==d&&(b.category=d,w.push({collectionId:c,category:d})),f&&R.gender!==f&&(b.gender=f,w.push({collectionId:c,gender:f}));let H=nt(M);if(A=ur({tieFormat:H}),A.error)return _({result:A,stack:E});if(!w.length)return _({result:{...C,modifications:w}});if(D?.tieFormatName!==o?(H.tieFormatName=o,w.push({tieFormatName:o})):w.length&&(delete H.tieFormatName,w.push("tieFormatName removed: modifications without new tieFormatName")),A=Sw({tieFormat:H,updateInProgressMatchUps:t,tournamentRecord:e,drawDefinition:i,structure:N,eventId:l,matchUp:U,event:g}),!A.error){let{appliedPolicies:q}=Tt({tournamentRecord:e}),Y=nt({collectionDefinition:b,drawId:i?.drawId,action:E,structureId:p,matchUpId:m,eventId:l});Yu({appliedPolicies:q,drawDefinition:i,auditData:Y})}return _({result:{...A,modifications:w},stack:E})}function Tw({updateInProgressMatchUps:t,drawDefinition:e,structureId:r,structure:n,matchUpId:o,matchUp:i}){let s=[];return o&&i?s=[i]:r&&n?s=yt({matchUpFilters:{matchUpTypes:[Wt]},structure:n})?.matchUps??[]:e&&(s=ir({matchUpFilters:{matchUpTypes:[Wt]},drawDefinition:e})?.matchUps??[]),{targetMatchUps:s.filter(c=>!c.winningSide&&c.matchUpStatus!==he&&(t||c.matchUpStatus!==Gn&&!Ie(c)))}}function yw({updateInProgressMatchUps:t,tournamentRecord:e,drawDefinition:r,targetMatchUps:n,tieFormat:o,event:i}){for(let s of n){let a=!!s.tieFormat;a&&(s.tieFormat=sr(o));let c;if(t){let u=Tt({tournamentRecord:e,drawDefinition:r,event:i}).appliedPolicies,p=lo({matchUpId:s.matchUpId,exitWhenNoValues:!0,tournamentRecord:e,appliedPolicies:u,drawDefinition:r,event:i});if(p.error)return p;c=p.score}a&&!c&&gt({tournamentId:e?.tournamentId,context:"updateTargetTeamMatchUps",eventId:i?.eventId,matchUp:s,drawDefinition:r})}return{...C}}function hA({updateInProgressMatchUps:t,originalValueGoal:e,tournamentRecord:r,wasAggregateValue:n,tieFormatName:o,drawDefinition:i,structureId:s,structure:a,tieFormat:c,matchUpId:u,matchUp:p,eventId:m,event:d}){let{aggregateValue:l,valueGoal:f}=Ds(c);c.winCriteria=nt({aggregateValue:l,valueGoal:f}),(e&&e!==f||l&&!n)&&(o?c.tieFormatName=o:delete c.tieFormatName);let{targetMatchUps:g}=Tw({updateInProgressMatchUps:t,drawDefinition:i,structureId:s,structure:a,matchUpId:u,matchUp:p});yw({updateInProgressMatchUps:t,tournamentRecord:r,targetMatchUps:g,drawDefinition:i,tieFormat:c,event:d});let I=nt(c),h=ur({tieFormat:I});if(h.error)return h;if(m&&d)d.tieFormat=I;else if(u&&p)p.tieFormat=c;else if(a)a.tieFormat=I;else if(i)i.tieFormat=I;else if(!p||!i)return{error:Z};return vt({drawDefinition:i,eventId:d?.eventId}),{...C}}function NR({updateInProgressMatchUps:t=!0,collectionGroupNumber:e,tournamentRecord:r,drawDefinition:n,tieFormatName:o,structureId:i,matchUpId:s,matchUp:a,eventId:c,event:u}){if(!e)return{error:st};if(isNaN(e))return{error:V};let p="removeCollectionGroup",m=a?void 0:pi({drawDefinition:n,structureId:i,matchUpId:s,eventId:c,event:u});if(m?.error)return _({result:m,stack:p});let d=m?.structure;a=a??m?.matchUp;let l=m?.tieFormat,f=l?.winCriteria.valueGoal,g=l?.winCriteria.aggregateValue,I=sr(l);if(m=ur({tieFormat:I}),m.error)return _({result:m,stack:p});let h=[];if(I.collectionDefinitions=I.collectionDefinitions.map(S=>{let{collectionGroupNumber:T,...y}=S;return T!==e?S:(h.push(S.collectionId),y)}),I.collectionGroups=I.collectionGroups.filter(({groupNumber:S})=>S!==e),m=hA({updateInProgressMatchUps:t,originalValueGoal:f,wasAggregateValue:g,tournamentRecord:r,drawDefinition:n,tieFormatName:o,structureId:i,structure:d,tieFormat:I,matchUpId:s,matchUp:a,eventId:c,event:u}),!m.error){let{appliedPolicies:S}=Tt({tournamentRecord:r}),T=nt({drawId:n?.drawId,collectionGroupNumber:e,action:p,structureId:i,matchUpId:s,eventId:c});Yu({appliedPolicies:S,drawDefinition:n,auditData:T})}return _({result:{...m,modifiedCollectionIds:h},stack:p})}function bl({tieFormat:t,orderMap:e}){let r=sr(t);return r.collectionDefinitions?.forEach(n=>{let o=e[n.collectionId];o&&(n.collectionOrder=o)}),r.collectionDefinitions?.sort((n,o)=>Ha(n.collectionOrder)-Ha(o.collectionOrder)),r}function RR({tournamentRecord:t,drawDefinition:e,structureId:r,matchUpId:n,orderMap:o,eventId:i,matchUp:s,event:a}){if(typeof o!="object"||!Object.values(o).every(p=>It(p)))return _({result:{error:V},context:{orderMap:o}});let c=r?at({drawDefinition:e,structureId:r}):void 0;if(c?.error)return c;let u=c?.structure;if(i&&a?.tieFormat)Aw({tournamentRecord:t,event:a,orderMap:o});else if(n){let p=e&&Bt({drawDefinition:e,matchUpId:n});if(p?.error)return p;if(s=p.matchUp,!s)return{error:Tr};let m=el({tournamentRecord:t,matchUpId:n,structure:u,drawDefinition:e,event:a})?.tieFormat;s.tieFormat=bl({tieFormat:m,orderMap:o}),gt({tournamentId:t?.tournamentId,eventId:a?.eventId,drawDefinition:e,matchUp:s})}else if(r)if(u?.tieFormat)u.tieFormat=bl({tieFormat:u.tieFormat,orderMap:o}),Ew({eventId:a?.eventId,tournamentRecord:t,drawDefinition:e,structure:u,orderMap:o}),vt({drawDefinition:e,structureIds:[u.structureId]});else if(e.tieFormat)MR({structureIds:[r],tournamentRecord:t,drawDefinition:e,orderMap:o,event:a});else if(a?.tieFormat)Aw({structureIds:[r],tournamentRecord:t,orderMap:o,event:a});else return{error:ve};else if(e?.tieFormat)MR({tournamentRecord:t,drawDefinition:e,orderMap:o,event:a});else return{error:ve};return{...C}}function Aw({tournamentRecord:t,structureIds:e,orderMap:r,event:n}){let o=bl({tieFormat:n.tieFormat,orderMap:r});e?.length||(n.tieFormat=o);for(let i of n.drawDefinitions??[])MR({tournamentRecord:t,drawDefinition:i,structureIds:e,orderMap:r,event:n})}function MR({tournamentRecord:t,drawDefinition:e,structureIds:r,orderMap:n,event:o}){let i=e.tieFormat??o?.tieFormat,s=bl({tieFormat:i,orderMap:n});r?.length||(e.tieFormat=s);let a=[];for(let c of e.structures??[])r?.length&&!r.includes(c.structureId)||((c.tieFormat||r?.includes(c.structureId))&&(c.tieFormat=bl({tieFormat:c.tieFormat??e.tieFormat??o?.tieFormat,orderMap:n})),Ew({eventId:o?.eventId,tournamentRecord:t,drawDefinition:e,structure:c,orderMap:n}),a.push(c.structureId));vt({drawDefinition:e,structureIds:a})}function Ew({tournamentRecord:t,drawDefinition:e,structure:r,orderMap:n,eventId:o}){let i=yt({matchUpFilters:{matchUpTypes:[Wt]},structure:r})?.matchUps;for(let s of i)s.tieFormat&&(s.tieFormat=bl({tieFormat:s.tieFormat,orderMap:n}),gt({tournamentId:t?.tournamentId,drawDefinition:e,eventId:o,matchUp:s}))}function EI({updateInProgressMatchUps:t=!0,tieFormatComparison:e,tournamentRecord:r,drawDefinition:n,tieFormatName:o,collectionId:i,structureId:s,matchUpId:a,eventId:c,matchUp:u,event:p}){let m="removeCollectionDefinition",d=u?void 0:pi({drawDefinition:n,structureId:s,matchUpId:a,eventId:c,event:p});if(d?.error)return _({result:d,stack:m});let l=d?.structure;u=u??d?.matchUp;let f=d?.tieFormat,g=sr(f);if(d=ur({tieFormat:g}),d.error)return _({result:d,stack:m});let I=g?.collectionDefinitions?.find(M=>M.collectionId===i);if(!I)return _({result:{error:ve,collectionId:i}});g.collectionDefinitions=g.collectionDefinitions.filter(M=>M.collectionId!==i),I.collectionGroupNumber&&(g.collectionDefinitions=g.collectionDefinitions.map(M=>{let{collectionGroupNumber:R,...b}=M;return b}),g.collectionGroups=g.collectionGroups.filter(({groupNumber:M})=>M!==I.collectionGroupNumber));let{aggregateValue:h,valueGoal:S}=Ds(g);g.winCriteria=nt({aggregateValue:h,valueGoal:S});let T=f?.winCriteria.valueGoal,y=f?.winCriteria.aggregateValue;(T&&T!==S||h&&!y)&&(o?g.tieFormatName=o:delete g.tieFormatName);let E=[];a&&u?E=[u]:s&&l?E=yt({matchUpFilters:{matchUpTypes:[Wt]},structure:l})?.matchUps??[]:n?E=ir({matchUpFilters:{matchUpTypes:[Wt]},drawDefinition:n})?.matchUps??[]:p&&(E=Xn({matchUpFilters:{matchUpTypes:[Wt]},drawDefinition:n})?.matchUps??[]);let P=(E||[]).filter(M=>{let b=M.tieMatchUps?.filter(O=>O.collectionId===i)?.some(Ie),v=e&&M.tieFormat?Qo({descendant:M.tieFormat,ancestor:g})?.different:!1;return t&&!b||!M.winningSide&&M.matchUpStatus!==he&&(t||M.matchUpStatus!==Gn&&!Ie(M)&&!v)});if(!P.length)return{error:xs};let{appliedPolicies:A}=Tt({tournamentRecord:r});if(a&&u&&t){let M=u.tieMatchUps?.filter(R=>R.collectionId===i);for(let R of M??[]){let b=Fa({matchUpId:R.matchUpId,tieMatchUpId:u?.matchUpId,winningSide:void 0,removeScore:!0,tournamentRecord:r,appliedPolicies:A,drawDefinition:n,event:p});if(b.error||(b=Bt({drawDefinition:n,matchUpId:a}),b.error))return b;u=b?.matchUp}}let U=[];for(let M of P){for(let R of M?.sides??[])R.lineUp=(R.lineUp??[]).map(b=>({participantId:b.participantId,collectionAssignments:(b?.collectionAssignments??[]).filter(v=>v.collectionId!==i)}));if(M.tieMatchUps=(M.tieMatchUps??[]).filter(R=>{let b=R.collectionId===i;return b&&U.push(R.matchUpId),!b}),M.tieFormat&&(M.tieFormat=sr(g)),t){let R=lo({matchUpId:M.matchUpId,exitWhenNoValues:!0,tournamentRecord:r,appliedPolicies:A,drawDefinition:n,event:p});if(R.error)return R}gt({tournamentId:r?.tournamentId,eventId:p?.eventId,drawDefinition:n,context:m,matchUp:M})}U.length&&Rn({tournamentId:r?.tournamentId,matchUpIds:U,eventId:p?.eventId,drawDefinition:n});let N=nt(g);if(d=ur({tieFormat:N}),d.error)return _({result:d,stack:m});if(c&&p)p.tieFormat=N;else if(a&&u)u.tieFormat=N;else if(l)l.tieFormat=N;else if(n)n.tieFormat=N;else if(!u||!n)return{error:Z};vt({drawDefinition:n,eventId:p?.eventId});let D=nt({drawId:n?.drawId,action:m,collectionId:i,structureId:s,matchUpId:a,eventId:c});return Yu({appliedPolicies:A,drawDefinition:n,auditData:D}),{tieFormat:N,deletedMatchUpIds:U,targetMatchUps:P,...C}}function CR({updateInProgressMatchUps:t=!0,tournamentRecord:e,groupDefinition:r,drawDefinition:n,collectionIds:o,tieFormatName:i,structureId:s,matchUpId:a,matchUp:c,eventId:u,event:p}){let m="addCollectionGroup";if(!Array.isArray(o))return _({result:{error:st},stack:m});let d=c?void 0:pi({drawDefinition:n,structureId:s,matchUpId:a,eventId:u,event:p});if(d?.error)return _({result:d,stack:m});let l=d?.structure;c=c||d?.matchUp;let f=d?.tieFormat,g=f?.winCriteria.valueGoal,I=sr(f);if(d=ur({tieFormat:I}),d.error)return _({result:d,stack:m});for(let T of I.collectionDefinitions){let{collectionId:y,collectionGroupNumber:E}=T;if(E&&o.includes(y))return _({info:"collectionIds cannot be part of other collectionGroups",result:{error:V},stack:m})}let S=(I.collectionGroups||[]).reduce((T,y)=>y.groupNumber>T?y.groupNumber:T,0)+1;return r.groupNumber=S,I.collectionDefinitions=I.collectionDefinitions.map(T=>o.includes(T.collectionId)?{...T,collectionGroupNumber:S}:T),I.collectionGroups=[...I.collecitonGroups||[],r],hA({updateInProgressMatchUps:t,originalValueGoal:g,tournamentRecord:e,drawDefinition:n,tieFormatName:i,structureId:s,structure:l,tieFormat:I,matchUpId:a,matchUp:c,eventId:u,event:p})}function UI({updateInProgressMatchUps:t=!0,collectionDefinition:e,referenceCategory:r,tournamentRecord:n,policyDefinitions:o,enforceCategory:i,referenceGender:s,drawDefinition:a,tieFormatName:c,enforceGender:u,structureId:p,matchUpId:m,matchUp:d,eventId:l,uuids:f,event:g}){let I="addCollectionDefinition",h=Tt({tournamentRecord:n,drawDefinition:a,event:g}).appliedPolicies??{},S=o?.[rr]??h?.[rr];i=i??S?.participants?.enforceCategory;let T=(u??S?.participants?.enforceGender)!==!1,y=!!((r??g?.category)&&i!==!1),E=!!((s??g?.gender)&&T),P=Kc({referenceCategory:r??g?.category,collectionDefinition:e,referenceGender:s,checkCategory:y,checkGender:E,event:g});if(P.error)return _({result:P,stack:I});let A=d?.tieFormat?void 0:pi({drawDefinition:a,structureId:p,matchUpId:m,eventId:l,event:g});if(A?.error)return _({result:{error:A.error},stack:I});let U=A?.structure;d=d??A?.matchUp;let N=d?.tieFormat??A?.tieFormat,D=sr(N);if(A=ur({tieFormat:D}),A?.error)return _({result:{error:A.error},stack:I});if(!e.collectionId)e.collectionId=Mt();else if(D.collectionDefinitions.map(({collectionId:k})=>k).includes(e.collectionId))return _({context:{collectionId:e.collectionId},result:{error:_E}});D.collectionDefinitions.push(e),D.collectionDefinitions.sort((G,k)=>(G.collectionOrder||0)-(k.collectionOrder||0)).forEach((G,k)=>G.collectionOrder=k+1);let{aggregateValue:M,valueGoal:R}=Ds(D);D.winCriteria=nt({aggregateValue:M,valueGoal:R});let b=N?.winCriteria.valueGoal,v=N?.winCriteria.aggregateValue;(b&&b!==R||M&&!v)&&(c?D.tieFormatName=c:delete D.tieFormatName);let O=[],x=[],F=[],w=nt(D);if(A=ur({tieFormat:w}),A?.error)return _({result:{error:A.error},stack:I});if(l&&g){g.tieFormat=w;for(let G of g.drawDefinitions??[])if(!G.tieFormat)for(let k of G.structures??[]){if(k.tieFormat)continue;let H=bR({updateInProgressMatchUps:t,collectionDefinition:e,structure:k,uuids:f});x.push(...H.newMatchUps),F.push(...H.targetMatchUps),O.push(k.structureId)}SA({modifiedMatchUps:F,eventId:g?.eventId,modifiedStructureIds:O,tournamentRecord:n,drawDefinition:a,addedMatchUps:x,stack:I})}else if(p&&U){U.tieFormat=w;let G=bR({updateInProgressMatchUps:t,collectionDefinition:e,structure:U,uuids:f});x.push(...G.newMatchUps),F=G.targetMatchUps,SA({modifiedMatchUps:F,eventId:g?.eventId,modifiedStructureIds:O,tournamentRecord:n,drawDefinition:a,addedMatchUps:x,stack:I})}else if(m&&d){if(!Cl({matchUp:d,updateInProgressMatchUps:t}))return _({result:{error:Xl},stack:I});d.tieFormat=w;let G=Ru({collectionDefinition:e,matchUp:d,uuids:f});Array.isArray(d.tieMatchUps)||(d.tieMatchUps=[]),d.tieMatchUps.push(...G),x.push(...G),SA({modifiedMatchUps:[d],eventId:g?.eventId,modifiedStructureIds:O,tournamentRecord:n,drawDefinition:a,addedMatchUps:x,stack:I})}else if(a){a.tieFormat=w;for(let G of a.structures??[]){let k=bR({updateInProgressMatchUps:t,collectionDefinition:e,structure:G,uuids:f});O.push(G.structureId),x.push(...k.newMatchUps),F.push(...k.targetMatchUps)}SA({modifiedMatchUps:F,eventId:g?.eventId,tournamentRecord:n,drawDefinition:a,addedMatchUps:x,stack:I})}else return{error:Z};let L=nt({drawId:a?.drawId,collectionDefinition:e,action:I,structureId:p,matchUpId:m,eventId:l});return Yu({appliedPolicies:h,drawDefinition:a,auditData:L}),{tieFormat:w,targetMatchUps:F,addedMatchUps:x,...C}}function bR({updateInProgressMatchUps:t,collectionDefinition:e,structure:r,uuids:n}){let o=[],s=(yt({matchUpFilters:{matchUpTypes:[Wt]},structure:r})?.matchUps).filter(a=>Cl({matchUp:a,updateInProgressMatchUps:t})&&!a.tieFormat);for(let a of s){let c=Ru({collectionDefinition:e,matchUp:a,uuids:n});Array.isArray(a.tieMatchUps)||(a.tieMatchUps=[]),a.tieMatchUps.push(...c),o.push(...c)}return{newMatchUps:o,targetMatchUps:s}}function SA({modifiedStructureIds:t,tournamentRecord:e,modifiedMatchUps:r,drawDefinition:n,addedMatchUps:o,eventId:i,stack:s}){vo({tournamentId:e?.tournamentId,matchUps:o,drawDefinition:n,eventId:i}),r?.forEach(a=>{gt({tournamentId:e?.tournamentId,drawDefinition:n,context:s,matchUp:a,eventId:i})}),vt({structureIds:t,drawDefinition:n,eventId:i})}function vR({updateInProgressMatchUps:t=!1,tieFormatComparison:e,modifiedTieFormat:r,tournamentRecord:n,considerations:o,drawDefinition:i,structureId:s,matchUpId:a,eventId:c,uuids:u,event:p}){let m="modifyTieFormat";if(!ur({tieFormat:r}).valid)return _({result:{error:ko},info:"falied validation",stack:m});let d=pi({drawDefinition:i,structureId:s,matchUpId:a,eventId:c,event:p});if(d.error)return _({result:d,stack:m});let{matchUp:l,tieFormat:f}=d,g=sr(f),I=Qo({descendant:r,ancestor:g,considerations:o});if(I.invalid)return _({context:{invalid:I.invalid},result:{error:ko},stack:m});if(!I?.different)return _({result:{...C},info:"Nothing to do",stack:m});let h=g.collectionDefinitions.map(({collectionId:D})=>D),S=r.collectionDefinitions.map(({collectionId:D})=>D),T=h.filter(D=>!S.includes(D)),y=r.collectionDefinitions.filter(({collectionId:D})=>!h.includes(D)),E=y.map(Br("collectionId")),P=[],A,U=r.tieFormatName;for(let D of r.collectionDefinitions){if(E.includes(D.collectionId))continue;let M=AI({updateInProgressMatchUps:t,...D,tournamentRecord:n,tieFormatName:U,drawDefinition:i,structureId:s,matchUpId:a,eventId:c,event:p});if(M.modifications&&P.push(...M.modifications),M.error)return _({result:M,stack:m});M.tieFormat&&(A=M.tieFormat)}for(let D of y){let M=UI({updateInProgressMatchUps:t,collectionDefinition:D,tournamentRecord:n,drawDefinition:i,tieFormatName:U,structureId:s,matchUpId:a,matchUp:l,eventId:c,uuids:u,event:p});if(M.error)return _({result:M,stack:m});M.tieFormat&&(A=M.tieFormat)}for(let D of T){let M=EI({updateInProgressMatchUps:t,tieFormatComparison:e,tournamentRecord:n,drawDefinition:i,tieFormatName:U,collectionId:D,structureId:s,matchUpId:a,eventId:c,matchUp:l,event:p});if(M.error)return _({result:M,stack:m});M.tieFormat&&(A=M.tieFormat)}return f?.tieFormatName!==U?(A.tieFormatName=U,P.push({tieFormatName:U})):(P.length||E.length||T.length)&&(delete A.tieFormatName,P.push("tieFormatName removed: modifications without new tieFormatName")),A.collectionDefinitions=A.collectionDefinitions.sort((D,M)=>Ha(D.collectionOrder)-Ha(M.collectionOrder)).map((D,M)=>({...D,collectionOrder:M+1})),{processedTieFormat:sr(A),modifications:P,...C}}function OR({tournamentRecord:t}){if(!t)return{error:$};let e=0;for(let r of t.events??[]){let n=r.tieFormats??[],o=p=>{if(!p.tieFormat)return;let m;for(let d of n)Qo({descendant:p.tieFormat,ancestor:d}).different||(m=d.tieFormatId);if(m)p.tieFormatId=m,delete p.tieFormat;else{let d=J(p.tieFormat,void 0,!0);d.tieFormatId||(d.tieFormatId=Mt()),p.tieFormatId=d.tieFormatId,delete p.tieFormat,n.push(d),e+=1}},i=r.eventType;o({tieFormat:r.tieFormat,eventType:i});for(let p of r.drawDefinitions??[]){o({tieFormat:p.tieFormat,eventType:i});for(let m of p.structures??[])o({tieFormat:m.tieFormat,eventType:i})}let s=(p,m)=>{let d=c.matchUps?.find(l=>l.matchUpId===p);d&&(d.tieFormatId=m,delete d.tieFormat,gt({tournamentId:t?.tournamentId,eventId:r.eventId,matchUp:d}))},a=p=>{let m=J(p.tieFormat,void 0,!0);m.tieFormatId||(m.tieFormatId=Mt()),n.push(m),e+=1,s(p.matchUpId,m.tieFormatId)},c=Xn({matchUpFilters:{matchUpTypes:[xr]},event:r}),u=c.matchUps??[];for(let p of u){let m;for(let d of n)p.tieFormat&&Qo({descendant:p.tieFormat,ancestor:d}).different||(m=d.tieFormatId);m?s(p.matchUpId,m):a(p)}n.length&&(r.tieFormats=n)}return{...C,addedCount:e}}var qR={};Jt(qR,{addDrawDefinitionExtension:()=>hp,addEventExtension:()=>Ro,addEventTimeItem:()=>Xi,addExtension:()=>Ut,addNotes:()=>Vp,addOnlineResource:()=>GR,addParticipantExtension:()=>yU,addParticipantTimeItem:()=>xg,addTimeItem:()=>to,addTournamentExtension:()=>xf,addTournamentTimeItem:()=>Nc,analyzeDraws:()=>_u,analyzeTournament:()=>ty,copyTournamentRecord:()=>wR,createTournamentRecord:()=>dm,generate:()=>LR,getAggregateTeamResults:()=>ZT,getAllowedDrawTypes:()=>Qd,getAllowedMatchUpFormats:()=>zT,getAppliedPolicies:()=>Tt,getCompetitionDateRange:()=>Jd,getCompetitionPenalties:()=>QT,getPolicyDefinitions:()=>_o,getTournamentInfo:()=>Ps,getTournamentPenalties:()=>Xd,getTournamentPersons:()=>JT,getTournamentPoints:()=>Zd,getTournamentStructures:()=>LS,getTournamentTimeItem:()=>td,mutate:()=>YR,query:()=>lN,removeDrawDefinitionExtension:()=>AU,removeEventExtension:()=>Sp,removeExtension:()=>gr,removeNotes:()=>Og,removeOnlineResource:()=>kR,removeParticipantExtension:()=>EU,removeTournamentExtension:()=>wf,setTournamentCategories:()=>HR,setTournamentDates:()=>PI,setTournamentEndDate:()=>jR,setTournamentName:()=>VR,setTournamentNotes:()=>BR,setTournamentStartDate:()=>WR,setTournamentStatus:()=>FR});var LR={};Jt(LR,{copyTournamentRecord:()=>wR,createTournamentRecord:()=>dm});function wR(t){let e=et(t,[{tournamentRecord:!0,startDate:!0,endDate:!1,tournamentName:!0}]);if(e.error)return e;let{startDate:r,endDate:n}=t.tournamentRecord,o=24*60*60*1e3,s=(r&&n?new Date(Pt(n)).getTime()-new Date(Pt(r)).getTime():0)/o,a=t.endDate||nh(t.startDate,s),c=l=>l?.filter(({itemType:f})=>t.itemTypeList?.includes(f)),u=l=>l?.filter(({name:f})=>t.extensionList?.includes(f)),p=l=>{let{timeItems:f,extensions:g,...I}=l;return J({...I,timeItems:c(f),extensions:u(g)},!1,!0)},m=l=>{let{drawDefinitions:f,timeItems:g,extensions:I,startDate:h,endDate:S,...T}=l;return J({extensions:u(I),timeItems:c(g),startDate:t.startDate,endDate:a,...T},!1,!0)},d={participants:t.copyParticipants?t.tournamentRecord.participants?.map(p)??[]:[],parentOrganisation:J({...t.tournamentRecord.parentOrganisation},!1,!0),venues:J(t.tournamentRecord.venues??[],!1,!0),extensions:u(t.tournamentRecord.extensions),timeItems:c(t.tournamentRecord.timeItems),events:t.tournamentRecord.events?.map(m)??[],weekdays:[...t.tournamentRecord.weekdays??[]],tournamentName:t.tournamentName,startDate:t.startDate,tournamentId:Mt(),endDate:a};return{...C,tournamentRecord:d}}var YR={};Jt(YR,{addDrawDefinitionExtension:()=>hp,addEventExtension:()=>Ro,addEventTimeItem:()=>Xi,addExtension:()=>Ut,addNotes:()=>Vp,addOnlineResource:()=>GR,addParticipantExtension:()=>yU,addParticipantTimeItem:()=>xg,addTimeItem:()=>to,addTournamentExtension:()=>xf,addTournamentTimeItem:()=>Nc,removeDrawDefinitionExtension:()=>AU,removeEventExtension:()=>Sp,removeExtension:()=>gr,removeNotes:()=>Og,removeOnlineResource:()=>kR,removeParticipantExtension:()=>EU,removeTournamentExtension:()=>wf,setTournamentCategories:()=>HR,setTournamentDates:()=>PI,setTournamentEndDate:()=>jR,setTournamentName:()=>VR,setTournamentNotes:()=>BR,setTournamentStartDate:()=>WR,setTournamentStatus:()=>FR});var f0="ABANDONED",g0="ACTIVE",I0="CANCELLED",h0="COMPLETED",S0="IN_PROGRESS",TA={ABANDONED:f0,ACTIVE:g0,CANCELLED:I0,COMPLETED:h0,IN_PROGRESS:S0};function FR({tournamentRecord:t,status:e}){return t?e&&!Object.keys(TA).includes(e)?{error:V,info:"Unknown status"}:(t.tournamentStatus=e,{...C}):{error:$}}function kR(t){let e=et(t,[{tournamentRecord:!0,onlineResource:!0}]);if(e.error)return e;let{tournamentRecord:r,onlineResource:n,organisationId:o,participantId:i,personId:s,courtId:a,venueId:c}=t;if(o){if(r.parentOrganisation?.parentOrganisationId!==o)return _({result:{error:ve}});vl({element:r.parentOrganisation,onlineResource:n})}else if(i||s){let u=(r.participants??[]).find(p=>s&&p.person?.personId===s||p.participantId===i);if(!u)return s?_({result:{error:ve}}):_({result:{error:re}});if(s){if(u.person?.personId!==s)return _({result:{error:Li}});vl({element:u.person,onlineResource:n})}else vl({element:u,onlineResource:n})}else if(a){let u=(r.venues??[]).filter(p=>!c||p.venueId===c).flatMap(p=>(p.courts??[]).filter(m=>m.courtId===a))?.[0];if(!u)return _({result:{error:_s}});vl({element:u,onlineResource:n})}else if(c){let u=(r.venues??[]).find(p=>p.venueId===c);if(!u)return _({result:{error:ki}});vl({element:u,onlineResource:n})}else vl({element:r,onlineResource:n}),lt({payload:{parentOrganisation:r.parentOrganisation,onlineResources:r.onlineResources,tournamentId:r.tournamentId},topic:Wi});return{...C}}function vl({element:t,onlineResource:e}){let r=(t.onlineResources??[]).filter(n=>!(n?.[tc]===e[tc]&&n?.[ec]===e[ec]&&n?.[rc]===e[rc]));t.onlineResources=r}function GR(t){let e=et(t,[{tournamentRecord:!0,onlineResource:!0}]);if(e.error)return e;let{tournamentRecord:r,onlineResource:n,organisationId:o,participantId:i,personId:s,courtId:a,venueId:c}=t;if(o){if(r.parentOrganisation?.parentOrganisationId!==o)return _({result:{error:ve}});Ol({element:r.parentOrganisation,onlineResource:n})}else if(i||s){let u=(r.participants??[]).find(p=>s&&p.person?.personId===s||p.participantId===i);if(!u)return s?_({result:{error:ve}}):_({result:{error:re}});if(s){if(u.person?.personId!==s)return _({result:{error:Li}});Ol({element:u.person,onlineResource:n})}else Ol({element:u,onlineResource:n})}else if(a){let u=(r.venues??[]).filter(p=>!c||p.venueId===c).flatMap(p=>(p.courts??[]).filter(m=>m.courtId===a))?.[0];if(!u)return _({result:{error:_s}});Ol({element:u,onlineResource:n})}else if(c){let u=(r.venues??[]).find(p=>p.venueId===c);if(!u)return _({result:{error:ki}});Ol({element:u,onlineResource:n})}else Ol({element:r,onlineResource:n}),lt({payload:{parentOrganisation:r.parentOrganisation,onlineResources:r.onlineResources,tournamentId:r.tournamentId},topic:Wi});return{...C}}function Ol({element:t,onlineResource:e}){let r=(t.onlineResources??[]).filter(n=>n?.[tc]!==e[tc]&&n?.[ec]!==e[ec]&&n?.[rc]!==e[rc]);return r.push(e),t.onlineResources=r,{...C}}function VR({tournamentRecord:t,promotionalName:e,tournamentName:r,formalName:n}){if(!t)return{error:$};let o=t.tournamentId,i={tournamentId:o};return r&&r!==t.tournamentName&&(t.tournamentName=r,i.tournamentName=r),e&&e!==t.promotionalName&&(t.promotionalName=e,i.promotionalName=e),n&&n!==t.formalName&&(t.formalName=n,i.formalName=n),t.promotionalName===t.tournamentName&&(delete t.promotionalName,i.promotionalName=""),t.formalName===t.tournamentName&&(delete t.formalName,i.formalName=""),Object.keys(i).length>1&&lt({topic:Wi,payload:{parentOrganisation:t.parentOrganisation,tournamentId:o,...i}}),{...C}}function BR({tournamentRecord:t,notes:e}){if(!t)return{error:$};let r=e?Vp({element:t,notes:e}):Og({element:t});return r.error?r:(lt({topic:Wi,payload:{parentOrganisation:t.parentOrganisation,tournamentId:t.tournamentId,notes:e??""}}),{...C})}function HR({tournamentRecord:t,categories:e}){return t?(e=(e||[]).filter(r=>r.categoryName&&r.type),t.tournamentCategories=e,lt({topic:Wi,payload:{parentOrganisation:t.parentOrganisation,tournamentId:t.tournamentId,categories:e}}),{...C}):{error:$}}function Uw({tournamentRecord:t}){if(!t)return{error:$};let{startDate:e,endDate:r}=t,n=Ls(e,r),o=[];for(let i of t.venues||[])i?.courts?.length&&o.push(...i.courts);for(let i of o){let{startTime:s,endTime:a}=(i.dateAvailability??[]).reduce((p,m)=>{let d=Yt(p.startTime),l=Yt(p.endTime);return m.startTime&&Yt(m.startTime)<d&&(p.startTime=m.startTime),m.endTime&&Yt(m.endTime)>l&&(p.endTime=m.endTime),p},{startTime:"08:00",endTime:"18:00"}),c=n.map(p=>i.dateAvailability?.find(d=>d.date===p)??{date:p,startTime:s,endTime:a}),u=i.dateAvailability?.find(p=>!p.date);u&&c.unshift(u),i.dateAvailability=c}return{...C}}function PI(t){let{tournamentRecord:e,startDate:r,endDate:n,weekdays:o}=t,i=t.activeDates?.filter(Boolean),s=et(t,[{tournamentRecord:!0},{[er]:l=>No.test(l),[Fr]:je,startDate:!1,endDate:!1},{[er]:l=>l.filter(Boolean).every(f=>No.test(f)),[Fr]:je,activeDates:!1},{[er]:by,weekdays:!1}]);if(s.error)return s;if(n&&r&&new Date(n)<new Date(r))return{error:V};if(n&&r&&new Date(r)>new Date(n))return{error:V};if(i?.length){let l=r||e.startDate,f=n||e.endDate,g=!l||i.every(h=>new Date(h)>=new Date(l)),I=!f||i.every(h=>new Date(h)<=new Date(f));if(!g||!I)return{error:je}}let a;(r&&e.startDate&&new Date(r)>new Date(e.startDate)||n&&e.endDate&&new Date(n)<new Date(e.endDate))&&(a=!0);let c=Ls(e.startDate,e.endDate);r&&(e.startDate=r),n&&(e.endDate=n);let u=Ls(e.startDate,e.endDate),p=c.filter(l=>!u.includes(l)),m=u.filter(l=>!c.includes(l));for(let l of e.events??[])r&&l.startDate&&new Date(l.startDate)<new Date(r)&&(l.startDate=r),n&&l.startDate&&new Date(l.startDate)>new Date(n)&&(l.startDate=r??n),n&&l.endDate&&new Date(l.endDate)>new Date(n)&&(l.endDate=n),r&&l.endDate&&new Date(l.endDate)<new Date(r)&&(l.endDate=n??r);r&&e.endDate&&new Date(r)>new Date(e.endDate)&&(e.endDate=r),n&&e.startDate&&new Date(n)<new Date(e.startDate)&&(e.startDate=n),i&&(e.activeDates=i),o&&(e.weekdays=o);let d=a&&T0({tournamentRecord:e})?.unscheduledMatchUpIds;return Uw({tournamentRecord:e}),lt({payload:nt({parentOrganisation:e.parentOrganisation,tournamentId:e.tournamentId,activeDates:i,startDate:r,weekdays:o,endDate:n}),topic:Wi}),{...C,unscheduledMatchUpIds:d,datesAdded:m,datesRemoved:p}}function WR({tournamentRecord:t,startDate:e}){return e?PI({tournamentRecord:t,startDate:e}):{error:je}}function jR({tournamentRecord:t,endDate:e}){return e?PI({tournamentRecord:t,endDate:e}):{error:je}}function T0({tournamentRecord:t}){let e=ye({tournamentRecord:t}).matchUps??[],r=t.startDate&&new Date(t.startDate),n=t.endDate&&new Date(t.endDate),o=[],i=[];for(let s of e){let{schedule:a,matchUpId:c}=s;if(a&&a.scheduledDate){let u=new Date(a.scheduledDate);(r&&u<r||n&&u>n)&&(i.push(c),o.includes(a.scheduledDate)||o.push(a.scheduledDate))}}return o.length&&!pm({scheduledDates:o,tournamentRecord:t}).clearedScheduleCount?{error:wA}:{unscheduledMatchUpIds:i}}var rC={};Jt(rC,{addCourt:()=>Nl,addCourts:()=>SI,addVenue:()=>lc,deleteCourt:()=>ZR,deleteVenue:()=>AA,deleteVenues:()=>KR,disableCourts:()=>zR,disableVenues:()=>QR,enableCourts:()=>XR,enableVenues:()=>JR,generate:()=>$R,generateCourts:()=>oI,getCompetitionVenues:()=>Qp,getCourts:()=>yy,getVenuesAndCourts:()=>Uo,modifyCourt:()=>NI,modifyCourtAvailability:()=>DI,modifyVenue:()=>tC,mutate:()=>eC,publicFindVenue:()=>hS,query:()=>CN});var $R={};Jt($R,{generateCourts:()=>oI});var eC={};Jt(eC,{addCourt:()=>Nl,addCourts:()=>SI,addVenue:()=>lc,deleteCourt:()=>ZR,deleteVenue:()=>AA,deleteVenues:()=>KR,disableCourts:()=>zR,disableVenues:()=>QR,enableCourts:()=>XR,enableVenues:()=>JR,modifyCourt:()=>NI,modifyCourtAvailability:()=>DI,modifyVenue:()=>tC});function _l(t){if(!t?.tournamentRecord&&!Array.isArray(t?.venueMatchUps))return{error:$};if(!t?.courtId)return{error:wi};let{scheduleVisibilityFilters:e,tournamentRecord:r,matchUpFilters:n,venueMatchUps:o,courtId:i}=t,{schedulingProfile:s}=Xo({tournamentRecord:r});if(Array.isArray(o))return{matchUps:u({matchUps:o,courtId:i})};let{matchUps:a}=ye({scheduleVisibilityFilters:e,tournamentRecord:r,matchUpFilters:n});return{matchUps:u({matchUps:a,courtId:i})};function u({matchUps:p,courtId:m}){let d=p.filter(l=>{let f=l.schedule?.allocatedCourts?.map(({courtId:g})=>g);return l.schedule?.courtId===m||f?.includes(m)});return ul({matchUps:d,schedulingProfile:s})}}function Pw({scheduleVisibilityFilters:t,tournamentRecord:e,matchUpFilters:r,venueId:n}){if(!e)return{error:$};if(!n)return{error:ti};let{schedulingProfile:o}=Xo({tournamentRecord:e}),{matchUps:i}=ye({scheduleVisibilityFilters:t,tournamentRecord:e,matchUpFilters:r});return{matchUps:a({matchUps:i,venueId:n})};function a({matchUps:c,venueId:u}){let p=c.filter(m=>{let d=m.schedule?.allocatedCourts?.map(({venueId:l})=>l);return m.schedule?.venueId===u||d?.includes(u)});return ul({matchUps:p,schedulingProfile:o})}}function DI({tournamentRecord:t,dateAvailability:e,disableNotice:r,venueMatchUps:n,courtId:o,force:i}){if(!t)return{error:$};if(!o)return{error:wi};let s=lA({dateAvailability:e});if(s.error)return s;let{updatedDateAvailability:a,totalMergeCount:c}=y0(e);e=a;let u=ms({tournamentRecord:t,courtId:o});if(u.error)return u;let{court:p,venue:m}=u,{matchUps:d}=_l({tournamentRecord:t,venueMatchUps:n,courtId:o});if(d?.length){let l=Tt({tournamentRecord:t})?.appliedPolicies,f=i??l?.[Mo]?.allowDeletionWithScoresPresent?.courts,g=[];g.length&&(f||console.log("throw error: scheduled court matchUps",g.length))}return p&&(p.dateAvailability=e,!r&&m&&lt({payload:{venue:m,tournamentId:t.tournamentId},topic:Ei,key:m.venueId})),{...C,totalMergeCount:c}}function y0(t){let e=0,r=t.reduce((o,i)=>{let{date:s,startTime:a,endTime:c,bookings:u}=i;return o[s]||(o[s]=[]),o[s].push({startTime:a,endTime:c,bookings:u}),o},{}),n=[];return Object.keys(r).forEach(o=>{r[o].sort(uw);let{mergedAvailability:i,mergeCount:s}=A0(r[o]);n.push(...i.map(a=>({date:o,...a}))),e+=s}),{updatedDateAvailability:n,totalMergeCount:e}}function A0(t){let e,r,n,o=t.length,i=0,s=[];for(;t.length&&o;){let c=t.shift(),{startTime:u,endTime:p,bookings:m}=c;if(o-=1,!e)e=u,n=m,r=p;else if(la(Ge(r),Ge(u),!1)>0){let l={startTime:e,endTime:r};n?.length&&(l.bookings=n),s.push(l),e=u,n=m,r=p}else m&&(n?n.push(m):n=m),r=p,i+=1}let a={startTime:e,endTime:r};return n?.length&&(a.bookings=n),s.push(a),{mergedAvailability:s,mergeCount:i}}function xl({matchUpsCount:t=0}){let r=`Schedule would be deleted from ${t} ${t===1?"matchUp":"matchUps"}; use { force: true }`;return{error:kE,info:r}}function yA({tournamentRecord:t,drawDefinition:e,matchUpId:r,drawId:n}){let o="removeCourtAssignment";if(!r)return{error:cr};if(!e&&!n)return{error:sn};let i;if(!e){if(!t)return{error:$};({drawDefinition:e}=ze({tournamentRecord:t,drawId:n}))}if(e)({matchUp:i}=Bt({drawDefinition:e,matchUpId:r}));else{if(!t)return{error:$};let s=ye({tournamentRecord:t,inContext:!1}).matchUps??[];({matchUp:i}=tT({matchUps:s,matchUpId:r}))}return i?(i.timeItems&&i.timeItems.find(a=>[jo,po].includes(a.itemType))&&(i.timeItems=i.timeItems.filter(({itemType:a})=>![jo,po].includes(a)),gt({tournamentId:t?.tournamentId,context:o,drawDefinition:e,matchUp:i})),{...C}):{error:Le}}function AA(t){if(typeof t?.venueId!="string")return{error:ti};let{tournamentRecord:e,venueId:r,force:n}=t,o=t.tournamentRecords||e&&{[e.tournamentId]:e}||{};if(!Object.keys(o).length)return{error:$};let s=Un({tournamentRecords:o,contextFilters:{venueIds:[r]}}).matchUps??[],a=Tt({tournamentRecord:e})?.appliedPolicies,c=n??a?.[Mo]?.allowDeletionWithScoresPresent?.venues;if(!s.length||c)for(let u of Object.values(o)){for(let m of s){let d=yA({matchUpId:m.matchUpId,drawId:m.drawId,tournamentRecord:u});if(d.error)return d}let p;u.venues=(u.venues??[]).filter(m=>m?.venueId!==r?!0:(p=!0,!1)),p&&lt({payload:{venueId:r,tournamentId:u.tournamentId},topic:Bf,key:r})}else return xl({matchUpsCount:s.length});return bc({tournamentRecords:o}),{...C}}function KR({tournamentRecord:t,venueIds:e,force:r}){if(!t)return{error:$};if(!Array.isArray(e))return{error:V};for(let n of t.venues||[]){let{venueId:o}=n;if(e.includes(o)){let{venueId:i}=n,s=AA({tournamentRecord:t,venueId:i,force:r});if(s.error)return s}}return{...C}}function zR(t){let{courtIds:e,dates:r}=t,n=Mr(t),o=[{[Re]:!0,[gp]:!0}],i=et(t,o);if(i.error)return i;for(let s of Object.values(n))E0({tournamentRecord:s,courtIds:e,dates:r});return{...C}}function E0({tournamentRecord:t,courtIds:e,dates:r}){let n=Array.isArray(r)&&r.length?{dates:r}:!0,o=i=>Ut({extension:{value:n,name:ao},creationTime:!1,element:i});for(let i of t.venues||[])for(let s of i.courts||[])if(e?.includes(s.courtId)){let a=o(s);if(a.error)return a}return{...C}}function QR(t){let{tournamentRecords:e,tournamentId:r,venueIds:n}=t,o=[{[Re]:!0,[Ip]:!0}],i=et(t,o);if(i.error)return i;let s=Object.keys(e).filter(a=>!r||a===r);for(let a of s){let c=e[a];U0({tournamentRecord:c,venueIds:n})}return{...C}}function U0({tournamentRecord:t,venueIds:e}){for(let r of t.venues||[])if(e?.includes(r.venueId)){let n=Ut({creationTime:!1,element:r,extension:{name:ao,value:!0}});if(n.error)return n}return{...C}}function XR(t){let e=Mr(t),r=[{[Re]:!0}];!t.enableAll&&r.push({[gp]:!0});let n=et(t,r);if(n.error)return n;let{enableAll:o,courtIds:i,dates:s}=t;for(let a of Object.values(e))P0({tournamentRecord:a,courtIds:i,enableAll:o,dates:s});return{...C}}function P0({tournamentRecord:t,courtIds:e,enableAll:r,dates:n}){for(let o of t.venues||[])for(let i of o.courts||[])if(r||e?.includes(i.courtId))if(Array.isArray(n)){let{extension:s}=mt({element:i,name:ao});if(s){let a=s.value;Array.isArray(a.dates)&&(a.dates=a.dates.filter(c=>!n.includes(c))),Ut({extension:{name:ao,value:a},creationTime:!1,element:i})}}else gr({element:i,name:ao});return{...C}}function JR(t){let e=Mr(t),r=[{[Re]:!0}];!t.enableAll&&r.push({[Ip]:!0});let n=et(t,r);if(n.error)return n;let{venueIds:o,enableAll:i}=t;for(let s of Object.values(e))for(let a of s.venues||[])(i||o?.includes(a.venueId))&&gr({element:a,name:ao});return{...C}}function ZR(t){let{courtId:e,disableNotice:r,force:n}=t,o=Mr(t),i=et(t,[{[Re]:!0,[Oh]:!0}]);if(i.error)return i;let s,a;for(let c of Object.values(o)){if(a=D0({tournamentRecord:c,disableNotice:r,courtId:e,force:n}),a.error&&a.error!==_s)return a;a.success&&(s=!0)}return s?{...C}:a}function D0({tournamentRecord:t,disableNotice:e,courtId:r,force:n}){let o=ms({tournamentRecord:t,courtId:r});if(o.error)return o;let i=o.venue,{matchUps:s}=_l({tournamentRecord:t,courtId:r}),a=Tt({tournamentRecord:t})?.appliedPolicies,c=n??a?.[Mo]?.allowDeletionWithScoresPresent?.courts;if(!s?.length||c){for(let u of s??[]){let p=yA({matchUpId:u.matchUpId,drawId:u.drawId,tournamentRecord:t});if(p.error)return p}i&&(i.courts=(i.courts??[]).filter(u=>u.courtId!==r),e||lt({payload:{venue:i,tournamentId:t.tournamentId},topic:Ei,key:i.venueId}))}else return xl({matchUpsCount:s.length});return{...C}}function NI(t){let{disableNotice:e,modifications:r,courtId:n,force:o,venueMatchUps:i}=t,s=Mr(t);if(!Object.keys(s).length)return{error:Lt};let a,c;for(let u of Object.values(s)){let p=N0({tournamentRecord:u,disableNotice:e,venueMatchUps:i,modifications:r,courtId:n,force:o});if(p?.error)return p;a=!0}return a?{...C}:c}function N0({tournamentRecord:t,disableNotice:e,venueMatchUps:r,modifications:n,courtId:o,force:i}){if(!t)return{error:$};if(!o)return{error:wi};if(!n||typeof n!="object")return{error:Io};let s=ms({tournamentRecord:t,courtId:o});if(s.error)return s;let{venue:a,court:c}=s,u=Object.keys(cw()).filter(l=>l!=="courtId");if(!Object.keys(n).filter(l=>u.includes(l)).length)return{error:rp};let m=u.filter(l=>!["dateAvailability"].includes(l)),d=Object.keys(n).filter(l=>m.includes(l));if(c&&d.forEach(l=>Object.assign(c,{[l]:n[l]})),n.dateAvailability){let l=DI({dateAvailability:n.dateAvailability,tournamentRecord:t,venueMatchUps:r,disableNotice:e,courtId:o,force:i});if(l.error)return l}return e||lt({payload:{venue:a,tournamentId:t.tournamentId},topic:Ei,key:a?.venueId}),{...C,court:J(c)}}var M0=()=>({venueId:void 0,venueName:"",venueAbbreviation:"",onlineResources:[],venueType:void 0,addresses:[],contacts:[],courts:[],roles:[]}),Dw=M0;function tC(t){let{modifications:e,venueId:r,force:n}=t,o=Mr(t);if(!Object.keys(o).length)return{error:Lt};if(typeof r!="string")return{error:ti};let i,s;for(let a of Object.values(o)){let c=R0({tournamentRecord:a,modifications:e,venueId:r,force:n});if(c.success&&(s=!0),c.error&&(i=c.error),c.error&&c.error!==ki)return c}return bc({tournamentRecords:o}),s?{...C}:{error:i}}function R0({tournamentRecord:t,modifications:e,venueId:r,force:n}){if(!t)return{error:$};if(!e||typeof e!="object")return{error:Io};if(!r)return{error:ti};let o=Tt({tournamentRecord:t})?.appliedPolicies,i=n??o?.[Mo]?.allowDeletionWithScoresPresent?.venues,{matchUps:s}=Pw({tournamentRecord:t,venueId:r}),a=qo({tournamentRecord:t,venueId:r});if(a.error)return a;let c=a.venue,u=Object.keys(Dw()).filter(h=>h!=="venueId");if(!Object.keys(e).filter(h=>u.includes(h)).length)return{error:rp};let m=u.filter(h=>!["courts","onlineResources"].includes(h)),d=Object.keys(e).filter(h=>m.includes(h));c&&d.forEach(h=>Object.assign(c,{[h]:e[h]}));let l=c?.courts?.map(h=>h.courtId)??[],f=e.courts?.map(h=>h.courtId)||[],g=f.length?l.filter(h=>!f.includes(h)):e?.courts&&l,I=[];if(g?.length){let S=c?.courts?.filter(T=>g.includes(T.courtId))?.map(T=>{let y=_l({courtId:T.courtId,tournamentRecord:t,venueMatchUps:s});for(let E of y.matchUps??[])I.push({matchUpId:E.matchUpId,drawId:E.drawId});return y.matchUps?.length??0}).reduce((T,y)=>T+y);if(c&&(!S||i))c.courts=c.courts?.filter(T=>f.includes(T.courtId)),ju({schedule:{courtId:"",scheduledDate:""},matchUpDetails:I,removePriorValues:!0,tournamentRecord:t});else return xl({matchUpsCount:S})}if(e.courts)for(let h of e.courts){let{courtId:S}=h||{},T=NI({modifications:h,disableNotice:!0,tournamentRecord:t,venueMatchUps:s,courtId:S,force:n});if(T.error===_s&&(T=Nl({disableNotice:!0,tournamentRecord:t,venueId:r,court:h})),T.error)return T}return bc({tournamentRecord:t}),c&&lt({payload:{venue:c,tournamentId:t.tournamentId},topic:Ei,key:c?.venueId}),{...C,venue:J(c)}}var nC={};Jt(nC,{JSON2CSV:()=>vw,UUID:()=>Mt,UUIDS:()=>ih,allNumeric:()=>bI,attributeFilter:()=>Hi,chunkArray:()=>Ee,chunkByNth:()=>Fl,chunkSizeProfile:()=>bA,constantToString:()=>Qe,countValues:()=>gC,createMap:()=>_I,dateTime:()=>oh,definedAttributes:()=>nt,dehydrateMatchUps:()=>bw,extractAttributes:()=>eP,flattenJSON:()=>UA,generateDateRange:()=>Ls,generateHashCode:()=>EC,generateRange:()=>tt,generateTimeCode:()=>fA,groupValues:()=>RA,hasAttributeValues:()=>AC,instanceCount:()=>yr,intersection:()=>jt,isConvertableInteger:()=>It,isNumeric:()=>Zt,isOdd:()=>RI,isPowerOf2:()=>_n,makeDeepCopy:()=>J,matchUpScheduleSort:()=>Cw,matchUpSort:()=>Ri,nearestPowerOf2:()=>Am,nextPowerOf2:()=>rs,noNulls:()=>fC,noNumeric:()=>vI,numericSort:()=>le,occurrences:()=>IC,overlap:()=>ke,randomMember:()=>yn,randomPop:()=>Zr,shuffleArray:()=>Sr,structureSort:()=>yi,subSort:()=>hC,undefinedToNull:()=>OI,unique:()=>pt,visualizeScheduledMatchUps:()=>Nw});function Nw({scheduledMatchUps:t,showGlobalLog:e}){av();let r=t?.reduce((o,{structureId:i})=>o.includes(i)?o:o.concat(i),[]),n=Array.isArray(r)&&{...r.map(o=>{let{structureName:i,matchUpType:s}=t.find(a=>a.structureId===o);return{[o]:`${i} ${s}`}})};r?.forEach(o=>{Cn({color:"blue",method:"draw",structure:n[o],keyColors:{structure:"magenta"}},!0);let i=t.filter(a=>a.structureId===o),s=Ke({matchUps:i})?.roundMatchUps||[];Object.keys(s).forEach(a=>{Cn({roundNumber:a,keyColors:{roundNumber:"brightcyan"}},!0),s[a].forEach(({matchUpId:c,schedule:u})=>{let p=Qt(u.scheduledTime);Cn({matchUpId:c,time:p,date:u.scheduledDate,venue:u.venueId,keyColors:{time:"brightcyan",date:"brightcyan",matchUpId:"yellow",venue:"magenta"}},!0)})})}),e&&sv()}var{extractTime:Mw,timeStringMinutes:Rw}=oh;function Cw(t,e){let r=t.schedule??{},n=e.schedule??{};if(r.scheduledDate&&!n.scheduledDate)return 1;if(n.scheduledDate&&!r.scheduledDate)return-1;if(r.scheduledDate&&n.scheduledDate){if(r.scheduledDate===n.scheduledDate){if(r.scheduledTime&&!n.scheduledTime)return 1;if(n.scheduledTime&&!r.scheduledTime)return-1;if(r.scheduledTime&&n.scheduledTime){let o=Rw(Mw(r.scheduledTime)),i=Rw(Mw(n.scheduledTime));return o-i}}return new Date(r.scheduledDate).getTime()-new Date(n.scheduledDate).getTime()}return 0}function bw({tournamentRecord:t}){if(!t)return{error:$};if(typeof t!="object"||!t.tournamentId)return{error:V};let{matchUps:e}=ye({tournamentRecord:t,inContext:!1});if(e?.length){let r=C0({tournamentRecord:t});v0(e,r)}return{...C}}function C0({tournamentRecord:t}){let e={};for(let r of t.events||[]){r.matchUpFormat&&(e[r.eventId]=r.matchUpFormat);for(let n of r.drawDefinitions||[]){n.matchUpFormat&&(e[n.drawId]=n.matchUpFormat);for(let o of n.structures||[]){o.matchUpFormat&&(e[o.structureId]=o.matchUpFormat);for(let i of o.structures||[])i.matchUpFormat&&(e[i.structureId]=i.matchUpFormat)}}}return e}var b0=["collectionId","collectionPosition","drawPositions","extensions","finishingPositionRange","finishingRound","isMock","matchUpId","matchUpStatus","matchUpStatusCodes","orderOfFinish","processCodes","roundNumber","tieFormat","tieMatchUps","roundPosition","score","sides","winnerMatchUpId","loserMatchUpId","matchUpDuration","winningSide"];function v0(t,e={}){for(let r of t){let{structureId:n,drawId:o,eventId:i}=r,s=e[n]||e[o]||e[i],a=r.matchUpFormat===s?void 0:r.matchUpFormat;for(let c of Object.keys(r))b0.includes(c)||delete r[c];r.sides&&r.drawPositions&&!r.tieMatchUps&&delete r.sides,a&&(r.matchUpFormat=a)}}function vw(t,e){if(e&&typeof e!="object")return{error:V};let{columnTransform:r={}}=e||{},{includeTransformAccessors:n,includeHeaderRow:o=!0,returnTransformedJSON:i,removeEmptyColumns:s,onlyHeaderRow:a,columnAccessors:c=[],functionMap:u={},columnMap:p={},valuesMap:m={},context:d={},delimiter:l='"',columnJoiner:f=",",rowJoiner:g=`\r
26
+ `),u=r?.map(({key:l,value:f})=>`${l}="${f}"`).join(" "),p=u?` ${u}`:"";if(e==="childArray")return c;let m=c?.length?`${i}${c}${i}`:"",d=a?.length?`${i}${a}${i}`:"";return`<${e}${p}>${m}${d}</${e}>`}function Sx(t){let e=et(t,[{[ne]:!0}]);if(e.error)return e;let{tournamentRecord:r}=t,{startDate:n,tournamentId:o,tournamentName:i}=r,{participantMap:s,matchUps:a,mappedMatchUps:c}=Gt({withMatchUps:!0,withEvents:!0,tournamentRecord:r}),u=r.participants.filter(y=>y.participantType===Ft),p=a?.filter(y=>y.matchUpType===Ft)??[],m=p?.reduce((y,E)=>{let P=E?.tieMatchUps??[];return P&&[...y,...P]},[])??[],d=a?.filter(y=>y.matchUpType===kt)??[],l=a?.filter(y=>y.matchUpType===xt)??[],f=m.length===d.length+l.length,g=p.length===1&&f,h={mappedMatchUps:c,participantMap:s,tournamentName:i,tournamentId:o,tournament:f?"N":"Y",startDate:n},S=[],T=[];if(g){let y=p[0],{json:E,xml:P}=Ix({teamParticipants:u,teamMatchUp:y,...h,doubles:l,singles:d});T.push(E),S.push(P)}else for(let y of p){let E=y?.sides?.map(({participant:N})=>N?.participantId).filter(Boolean);if(E?.length!==2)continue;let P=E.map(N=>N&&s?.[N]?.participant),{xml:A,json:U}=Ix({doubles:y.tieMatchUps?.filter(N=>N.matchUpType===xt),singles:y.tieMatchUps?.filter(N=>N.matchUpType===kt),teamParticipants:P,teamMatchUp:y,...h});T.push(U),S.push(A)}return{json:T,xml:S,...C}}function Ix({teamParticipants:t,mappedMatchUps:e,participantMap:r,tournamentName:n,tournamentId:o,teamMatchUp:i,tournament:s,startDate:a,doubles:c,singles:u}){let p=t?.find(y=>y.participantRoleResponsibilities?.includes("Home")),m=t?.filter(y=>y.participantId!==p?.participantId),d=Yn(a,"/","MDY"),l=p?.participantName||m?.[1]?.participantName,f=p?.participantId||m?.[1]?.participantId,g=m?.[0]?.participantName,I=m?.[0]?.participantId,h={},S=t.map(y=>({team:{...R1({teamParticipant:y,teamMatchUp:i,uniValues:h,participantMap:r,mappedMatchUps:e,homeid:f})}})),T=nt({venue:{tournamentname:s?n:void 0,neutralgame:p?"N":"Y",gameid:o,officials:{},tournament:s,rules:{},homename:l,visname:g,homeid:f,visid:I,date:d},childArray:S,singles_matches:u?.map(y=>hx({matchUp:y,homeid:f,uniValues:h})),doubles_matches:c?.map(y=>hx({matchUp:y,homeid:f,uniValues:h}))});return{json:T,xml:rM({json:T,tagName:"tngame"})}}function N1({homeid:t,uniValues:e,participant:r}){if(!r)return{};let n=r.individualParticipants?.length===2,o=n?pt(r.individualParticipants?.map(g=>g.teams?.[0]?.participantId)):[],i=n?pt(r.individualParticipants?.map(g=>g.teams?.[0]?.teamId)):[],s=!n&&r.teams?.[0]?.participantId||o?.length===1&&o[0]||void 0,a=!n&&r.teams?.[0]?.teamId||i?.length===1&&i[0]||s,c=n?void 0:r.participantName,u=r.individualParticipants?.[0]?.participantName,p=r.individualParticipants?.[1]?.participantName,m=t&&(s===t?"H":"V")||"",d=n?void 0:e[s][r.participantId],l=e[s][r.individualParticipants?.[0]?.participantId],f=e[s][r.individualParticipants?.[1]?.participantId];return nt({vh:m,uni:d,uni_1:l,uni_2:f,team:a,name:c,name_1:u,name_2:p})}function M1({sets:t,sideNumber:e}){return Object.assign({},...t?.map(r=>{let{setNumber:n,side1Score:o,side2Score:i,side1TiebreakScore:s,side2TiebreakScore:a}=r,c=`set_${n}`,u=`tie_${n}`,p=e===1?o:i,m=e===1?s:a;return{[c]:p,[u]:m}})??[])}function R1({teamParticipant:t,teamMatchUp:e,participantMap:r,mappedMatchUps:n,homeid:o,uniValues:i}){let{participantId:s,participantName:a}=t,c=o&&(s===o?"H":"V")||"",u=r?.[s]?.matchUps,p=u&&Object.keys(u),m=e?.sides?.find(({participant:E})=>E.participantId===s)?.sideNumber,d=e?.score?.sets?.[0]?.[`side${m}Score`]??0;i[s]={};let l={SINGLES:{w:0,l:0},DOUBLES:{w:0,l:0}},f=[],g=[],I=0;for(let E of p??[]){let P=n?.[E],A=P.sides.find(({participant:N})=>N.participantId===s)?.sideNumber,U=P.score?.sets?.[0]?.[`side${A}Score`]??0;I+=U;for(let N of P.tieMatchUps??[]){let{matchUpType:D,winningSide:M}=N,R=M&&(M===A?"w":"l")||"";R&&(l[D][R]+=1);let b=R==="w"?"1":"0",v=R==="l"?"1":"0";if(D===kt){let O=g.length+1;g.push({singles_pair:{pair:O,won:b,lost:v,tied:"0"}})}else if(D===xt){let O=f.length+1;f.push({doubles_pair:{pair:O,won:b,lost:v,tied:"0"}})}}}let h=[{singles:{childArray:g,won:l.SINGLES.w,lost:l.SINGLES.l}},{doubles:{childArray:f,won:l.DOUBLES.w,lost:l.DOUBLES.l}}],S=[],T=1;for(let E of t.individualParticipantIds){let P=r?.[E];if(P){let{participant:A,counters:U}=P,N={won:U?.DOUBLES?.wins||0,lost:U?.DOUBLES?.losses||0},D={won:U?.SINGLES?.wins||0,lost:U?.SINGLES?.losses||0},{participantName:M,participantId:R}=A;i[s][R]=T,S.push({player:{name:M,uni:T,singles:D,doubles:N}})}T+=1}return{vh:c,id:s,name:a,score:d||I,totals:h,childArray:S}}function hx({matchUp:t,homeid:e,uniValues:r}){let{collectionPosition:n,orderOfFinish:o,matchUpType:i,sides:s}=t??{},a=s?.map(u=>{let{sideNumber:p,participant:m}=u,d=M1({sets:t.score?.sets,sideNumber:p});return{[i===kt?"singles_score":"doubles_score"]:{...N1({homeid:e,uniValues:r,participant:m}),...d}}});return{[i===kt?"singles_match":"doubles_match"]:{match:n,order:o,childArray:a}}}var C1="ASC",nM="ASC",b1="DESC",_y="DESC",Tx={ASC:C1,ASCENDING:nM,DESC:b1,DESCENDING:_y};function xy(t){let{tieFormat:e}=t,{useDefaultEventRanking:r,tournamentRecord:n,drawDefinition:o,scaleAccessor:i,singlesOnly:s,attach:a,event:c}=t;if(c?.eventType!==br)return{error:jn};if(!n)return{error:$};if(!e&&!o)return{error:Cr};if(e=e??We({drawDefinition:o,event:c})?.tieFormat,ur({tieFormat:e}).error)return{error:ko};if(typeof i!="object"&&!r)return{error:V,context:{scaleAccessor:i}};let u={},m=(o?.entries??c?.entries??[]).filter(R=>R?.entryStatus===kr).map(St),{participants:d=[]}=Gt({withIndividualParticipants:!0,withScaleValues:!0,tournamentRecord:n}),l=d.filter(({participantId:R})=>m.includes(R)),f=R=>R===Ii?"rankings":"ratings",g=c?.category?.categoryName??c?.category?.ageCategoryCode,{scaleName:I=g,scaleType:h=Ii,sortOrder:S,accessor:T}=i||{},y=f(h),E=(R,b)=>{let v=R[y]?.[b];if(!v&&r&&(v=R[y]?.[ua]),Array.isArray(v)){let O=v.find(x=>x.scaleName===I)?.scaleValue;if(Zt(O))return O;if(T&&typeof O=="object")return O[T]}return 0},P=(R,b,v)=>{let O=S===_y?b:R,x=S===_y?R:b;return E(O,v)-E(x,v)},A=(R,b)=>P(R,b,ua),U=(R,b)=>P(R,b,_i),N=[],D=e?.collectionDefinitions??[];for(let R of l){let b=R.individualParticipants?.sort(A)??[],v=s?b:R.individualParticipants?.sort(U)??[],O={};for(let F of D){let w=[],{collectionId:L,matchUpCount:G,matchUpType:k,gender:H}=F,W=de(ua)(k);tt(0,G).forEach(q=>{let Y=W?b:v??[],B=q+1,K=[];tt(0,W?1:2).forEach(X=>{let j=Y?.find(ot=>{let z=H&&([zt,oe].includes(H)&&H||H===Ar&&[zt,oe][X]);return(!z||z===ot.person?.sex)&&!w.includes(ot.participantId)})?.participantId;j&&(K.push(j),w.push(j),O[j]||(O[j]=[]),O[j].push({collectionPosition:B,collectionId:L}))}),W||N.push(K)})}let x=Object.keys(O).map(F=>({collectionAssignments:O[F],participantId:F}));u[R.participantId]=x}let M=[];for(let R of N){let{participant:b}=In({tournamentParticipants:d,participantIds:R});if(!b){let v={individualParticipantIds:R,participantRole:xe,participantType:ft};M.push(v)}}if(a){for(;M.length;)vn({participant:M.pop(),tournamentRecord:n});Ut({element:o,extension:{name:Co,value:u}})}return{...C,lineUps:u,participantsToAdd:M}}function oI(t){if(!t)return{error:st};let e=et(t,[{dates:!1,[er]:s=>Array.isArray(s)&&s.every(Nr)},{uuids:!1,[er]:s=>Array.isArray(s)&&s.every(Vt)},{startTime:!1,endTime:!1,[er]:eh},{idPrefix:!1,namePrefix:!1,[er]:Vt},{count:!0,[er]:Zt}]);if(e.error)return e;let{startDate:r,endDate:n}=t.tournamentRecord??{},o=t.dates||r&&n&&Ls(r,n)||[],i=tt(1,t.count+1).map(s=>nt({courtId:t.uuids?.pop()??(t.idPrefix&&`${t.idPrefix}-${s}`)??Mt(),courtName:t.courtNames?.pop()??(t.namePrefix&&`${t.namePrefix} ${s}`),dateAvailability:o.map(a=>({startTime:t.startTime??"08:00",endTime:t.endTime??"20:00",date:a}))}));return{...C,courts:i}}var oM={};Jt(oM,{default:()=>v1,garman:()=>Ex});function La({court:t,date:e}){let r=e&&t.dateAvailability.find(o=>qn(o.date,e)),n=t.dateAvailability.find(o=>!o.date);return r||n}function Ms(t){let e=et(t,[{courtDate:!0,_ofType:Kr}]);if(e.error)return e;let{includeBookingTypes:r=[],courtDate:n}=t,o=[],i=Ge(n.startTime);(n.bookings||[]).filter(a=>!a.bookingType||!r.includes(a.bookingType)).sort((a,c)=>yf(a.startTime).localeCompare(yf(c.startTime))).forEach(a=>{let c={startTime:Qt(i.toISOString()),endTime:a.startTime};Ge(a.startTime)>i&&o.push(c),Ge(a.endTime)>i&&(i=Ge(a.endTime))});let s={startTime:Qt(i.toISOString()),endTime:n.endTime};return Ge(n.endTime)>i&&o.push(s),{timeSlots:o}}function yx({averageMatchUpMinutes:t,includeBookingTypes:e,periodStartTime:r,periodEndTime:n}){let o=s=>{let{timeSlots:a}=Ms({includeBookingTypes:e,courtDate:s});return!!a?.filter(i)?.length};function i(s){let a=Ge(s.startTime),c=Ge(s.endTime);return a>r||c<n?!1:la(r,c)>=t}return{enoughTime:o}}function wy(t){let e=et(t,[{periodStart:!0,date:!0},{courts:!0,_ofType:Be}]);if(e.error)return e;let{averageMatchUpMinutes:r,includeBookingTypes:n,periodStart:o,date:i}=t,s=t.courts,a=Ge(o),c=Ef(a,r),{enoughTime:u}=yx({averageMatchUpMinutes:r,includeBookingTypes:n,periodStartTime:a,periodEndTime:c});return{availableToScheduleCount:(s?.filter(m=>{if(!Array.isArray(m.dateAvailability))return!1;let d=La({date:i,court:m});return!!(d&&u(d))})||[]).length,...C}}function nm(t){let{remainingScheduleTimes:e=[],clearScheduleDates:r,periodLength:n=30,scheduleDate:o,courts:i=[]}=t,{bookings:s=[]}=t;if(!Array.isArray(i)||!i.length)return{error:V,courts:i};if(!Array.isArray(s))return{error:Pm};if(!Nr(o))return{error:je};r&&(Array.isArray(r)?r.includes(o)&&(s=[]):s=[]);let{courtBookings:a,unassignedBookings:c}=s.reduce((l,f)=>{let{courtId:g}=f;return g?l.courtBookings[g]?l.courtBookings[g].push(f):l.courtBookings[g]=[f]:l.unassignedBookings.push(f),l},{courtBookings:{},unassignedBookings:[]}),u=i.map((l,f)=>{let{courtId:g,courtName:I}=l,h=a[g]||[],S=La({date:o,court:l})||{},{bookings:T=[],startTime:y,endTime:E,date:P}=S,U=[e[f]&&{startTime:y,endTime:e[f]},...J(T,!1,!0),...h].filter(Boolean);return{courtId:g,courtName:I,dateAvailability:{bookings:U,startTime:y,endTime:E,date:P}}});c.sort((l,f)=>Yt(l.startTime)-Yt(f.startTime));let p=()=>u.map(l=>{let f=l.dateAvailability,{timeSlots:g=[]}=Ms({courtDate:f});return{courtName:l.courtName,courtId:l.courtId,timeSlots:g}}).flat(),m=[];for(let l of c){let{startTime:f,endTime:g,averageMinutes:I,recoveryMinutes:h,matchUpId:S}=l,T=Yt(f),y=Yt(g),P=p().reduce((A,{courtId:U,courtName:N,timeSlots:D})=>{let M;return D.find(({startTime:b,endTime:v})=>{M=Yt(b)-T;let O=T>=Yt(b);return y<=Yt(v)&&A.startDifference!==0&&((M===0||M+n>=0)&&(A.startDifference===void 0||M<A.startDifference)||O)})?{courtName:N,courtId:U,startDifference:M}:A},{});if(P.courtId){let A={averageMinutes:I,recoveryMinutes:h,matchUpId:S,startTime:f,endTime:g};m.push(A),u.find(({courtId:N})=>N===P.courtId)?.dateAvailability.bookings.push(A)}else console.log({unassignedBooking:l})}return{virtualCourts:u.map(({courtId:l,courtName:f,dateAvailability:g})=>({dateAvailability:[g],courtName:f,courtId:l})),assignedBookings:m}}function Hu({averageMatchUpMinutes:t,periodLength:e=30,recoveryMinutes:r}){let n=(t||90)+(r||0);return e>n?n:e||30}function Ly(t){let{startTime:e="8:00",endTime:r="20:30",count:n=10,date:o}=t??{};return tt(0,n).map(()=>({dateAvailability:[{date:o,startTime:e,endTime:r}]}))}function Oc({scheduleDate:t,startTime:e,endTime:r,courts:n}){let o=e&&"startTime"||r&&"endTime"||void 0;return n.reduce((i,s)=>{let a=La({date:t,court:s}),c=o&&(a?.[o]||s[o]);return c&&(!i||e&&Yt(c)<Yt(i)||r&&Yt(c)>Yt(i))?c:i},void 0)}function Ax({averageMinutes:t,startTime:e,endTime:r,courts:n,date:o}){e=e||Oc({courts:n,scheduleDate:o,startTime:!0}),r=r||Oc({courts:n,scheduleDate:o,endTime:!0});let i;if(e&&r){let s=Ge(e),a=Ge(r);for(let c of n||[]){if(!Array.isArray(c.dateAvailability))continue;let u=La({court:c,date:o}),{timeSlots:p}=Ms({courtDate:u});p?.forEach(m=>{let d=Ge(m.startTime),l=Ge(m.endTime);if(d>a||d<s||l<s)return!1;if(la(d,l)>=t){let I=Qt(d.toISOString());(!i||I<i)&&(i=I)}})}}return{firstTimeSlotStartTime:i}}function gl(t){let e=et(t,[{courts:!0,_ofType:Be}]);if(e.error)return e;let{date:r=Af(),startTime:n="08:00",endTime:o="19:00",periodLength:i,courts:s}=t,{calculateStartTimeFromCourts:a=!0,remainingScheduleTimes:c,averageMatchUpMinutes:u,clearScheduleDates:p,courtsCount:m,bookings:d}=t;i=i||Hu({averageMatchUpMinutes:u}),r=Pt(r),n=Qt(n),o=Qt(o);let l=0,f=0,g=0,I=0,h=0;!s&&m&&(s=Ly({startTime:n,endTime:o,count:m,date:r}));let{virtualCourts:S}=nm({remainingScheduleTimes:c,clearScheduleDates:p,scheduleDate:r,periodLength:i,bookings:d,courts:s}),{firstTimeSlotStartTime:T}=Ax({averageMinutes:u,courts:S,startTime:n,endTime:o,date:r});a&&T&&(n=T??n);let y=Yt(n),P=Yt(o)-y,A=Math.floor(P/i),N=tt(0,A+1).map(M=>{let R=y+M*i,b=qC(R),v=wy({courts:S??[],averageMatchUpMinutes:u,periodStart:b,date:r});if(v.error)return{error:v.error};let{availableToScheduleCount:O=0}=v,x=O>f?O-f:0;h+=M?O:0;let F=M?h/M:O,L=i*F/u,G=M?L*(M-1)+F:F,k=O?f&&G-l||x:0;l=G,f=O,g+=k;let H=dt(g)-I;return I+=H,{periodStart:b,add:H,availableToScheduleCount:O,newCourts:x,totalMatchUps:I}});return{scheduleTimes:N.reduce((M,R)=>{let v=tt(0,R.add).map(()=>({scheduleTime:R.periodStart}));return M.concat(...v)},[]).flat(),timingProfile:N,totalMatchUps:I}}var Ex={getCourtsAvailableAtPeriodStart:wy,generateTimeSlots:Ms,getScheduleTimes:gl,courtGenerator:Ly},v1=Ex;var Fy={};Jt(Fy,{isValid:()=>Dr,isValidMatchUpFormat:()=>Dr,parse:()=>Ye,stringify:()=>cp});var NM={};Jt(NM,{allCompetitionMatchUps:()=>Un,allDrawMatchUps:()=>ir,allEventMatchUps:()=>Xn,allTournamentMatchUps:()=>ye,analyzeMatchUp:()=>tm,applyLineUps:()=>PM,assignMatchUpSideParticipant:()=>sM,assignTieMatchUpParticipantId:()=>Sl,bulkMatchUpStatusUpdate:()=>yM,calculateWinCriteria:()=>Ds,checkInParticipant:()=>sI,checkMatchUpIsComplete:()=>ls,checkOutParticipant:()=>iI,competitionScheduleMatchUps:()=>Bu,disableTieAutoCalc:()=>SM,drawMatchUps:()=>Ty,enableTieAutoCalc:()=>gM,eventMatchUps:()=>pl,filterMatchUps:()=>Mi,findMatchUp:()=>zg,getAllDrawMatchUps:()=>ce,getAllStructureMatchUps:()=>yt,getCheckedInParticipantIds:()=>ps,getCompetitionMatchUps:()=>Zp,getEventMatchUpFormatTiming:()=>py,getHomeParticipantId:()=>fy,getMatchUpCompetitiveProfile:()=>Su,getMatchUpContextIds:()=>gy,getMatchUpDailyLimits:()=>dl,getMatchUpDailyLimitsUpdate:()=>my,getMatchUpDependencies:()=>on,getMatchUpFormat:()=>Iy,getMatchUpFormatTiming:()=>Tu,getMatchUpFormatTimingUpdate:()=>cy,getMatchUpScheduleDetails:()=>dd,getMatchUpType:()=>ld,getMatchUpsStats:()=>hy,getModifiedMatchUpFormatTiming:()=>cl,getParticipantResults:()=>vu,getPredictiveAccuracy:()=>ly,getRoundMatchUps:()=>Ke,getRounds:()=>Sy,isValidMatchUpFormat:()=>Dr,matchUpActions:()=>xd,mutate:()=>DM,participantScheduledMatchUps:()=>dy,query:()=>RN,removeDelegatedOutcome:()=>IM,removeMatchUpSideParticipant:()=>cI,removeTieMatchUpParticipantId:()=>cM,replaceTieMatchUpParticipantId:()=>aI,resetAdHocMatchUps:()=>EM,resetMatchUpLineUps:()=>pI,resetScorecard:()=>dI,resetTieFormat:()=>mI,setDelegatedOutcome:()=>AM,setMatchUpFormat:()=>TM,setMatchUpStatus:()=>Wu,setOrderOfFinish:()=>UM,substituteParticipant:()=>hM,tallyParticipantResults:()=>ba,toggleParticipantCheckInState:()=>Il,tournamentMatchUps:()=>ml,updateTieMatchUpScore:()=>lo,validMatchUp:()=>og,validMatchUps:()=>Vr});var DM={};Jt(DM,{applyLineUps:()=>PM,assignMatchUpSideParticipant:()=>sM,assignTieMatchUpParticipantId:()=>Sl,bulkMatchUpStatusUpdate:()=>yM,checkInParticipant:()=>sI,checkOutParticipant:()=>iI,disableTieAutoCalc:()=>SM,enableTieAutoCalc:()=>gM,findMatchUp:()=>zg,removeDelegatedOutcome:()=>IM,removeMatchUpSideParticipant:()=>cI,removeTieMatchUpParticipantId:()=>cM,replaceTieMatchUpParticipantId:()=>aI,resetAdHocMatchUps:()=>EM,resetMatchUpLineUps:()=>pI,resetScorecard:()=>dI,resetTieFormat:()=>mI,setDelegatedOutcome:()=>AM,setMatchUpFormat:()=>TM,setMatchUpStatus:()=>Wu,setOrderOfFinish:()=>UM,substituteParticipant:()=>hM,toggleParticipantCheckInState:()=>Il,updateTieMatchUpScore:()=>lo});function sM({tournamentRecord:t,drawDefinition:e,participantId:r,sideNumber:n,matchUpId:o,event:i}){if(r&&typeof r!="string")return{error:mn};if(!e)return{error:Z};if(!o)return{error:cr};let s=n===void 0;if(s&&(n=1),![1,2].includes(n))return _({result:{error:V,context:{sideNumber:n}}});let{matchUp:a,structure:c}=Bt({drawDefinition:e,matchUpId:o,event:i});if(!a)return{error:Le};if(!(!c?.structures&&!(e.drawType&&e.drawType!==$r)&&!c?.matchUps?.find(({roundPosition:p})=>!!p)))return{error:Um};if(!r&&(a?.score?.scoreStringSide1||se.includes(a?.matchUpstatus)||a?.matchUpStatus&&[Te,be].includes(a.matchUpStatus)))return{error:Ju,info:"matchUp has completed status or score"};if(a){if(a.sides=[1,2].map(p=>{let m=a.sides?.find(d=>d.sideNumber===p)??{sideNumber:p};return n===p?{...m,participantId:r}:m}),s)for(let p of a.sides)p.sideNumber&&(p.sideNumber=3-p.sideNumber);gt({tournamentId:t?.tournamentId,context:"assignSideParticipant",drawDefinition:e,matchUp:a})}return{...C,sidesSwapped:s}}function Jr({removePriorValues:t,tournamentRecord:e,duplicateValues:r,drawDefinition:n,disableNotice:o,matchUpId:i,timeItem:s,event:a}){let{matchUp:c}=Bt({drawDefinition:n,event:a,matchUpId:i});if(!c)return{error:Le};let u=to({removePriorValues:t,element:c,duplicateValues:r,timeItem:s});return o||gt({tournamentId:e?.tournamentId,eventId:a?.eventId,context:"addTimeItem",drawDefinition:n,matchUp:c}),u}function iI(t){let e=[{[ne]:!0},{[Ce]:!0},{[io]:!0},{[ln]:!0}],r=et(t,e);if(r.error)return r;let n=Ns(t,[{[ss]:Ln,attr:{[ru]:!0}}]);if(n.error)return n;let{tournamentRecord:o,drawDefinition:i,participantId:s,matchUpId:a}=t,c=n?.matchUp?.matchUp,{matchUpStatus:u,score:p}=c??{};if(u&&Xm.includes(u)||u&&se.includes(u)||Ie({score:p}))return{error:BA};let m=ps({matchUp:c});if(m?.error)return m;let{checkedInParticipantIds:d,allRelevantParticipantIds:l}=m??{};if(!l?.includes(s))return{error:mn};if(!d?.includes(s))return{error:IE};let f=pS({matchUp:c});if(f?.error)return f;let{sideParticipantIds:g,nestedIndividualParticipantIds:I}=f??{},h=g?.indexOf(s);return h!==void 0&&[0,1].includes(h)&&(I?.[h]??[]).forEach(T=>{Jr({drawDefinition:i,matchUpId:a,timeItem:{itemType:ud,itemValue:T}})}),Jr({tournamentRecord:o,drawDefinition:i,matchUpId:a,timeItem:{itemValue:s,itemType:ud}}),{...C,checkedOut:!0}}function sI(t){let e=[{[ne]:!0},{[Ce]:!0},{[io]:!0},{[ln]:!0}],r=et(t,e);if(r[fn])return r;let n=Ns(t,[{[ss]:Ln,attr:{[ru]:!0}}]);if(n[fn])return n;let{tournamentRecord:o,drawDefinition:i,participantId:s,matchUpId:a}=t,c=ps({matchUp:n?.matchUp?.matchUp});if(c?.error)return c;let{checkedInParticipantIds:u,allRelevantParticipantIds:p}=c??{};if(!p?.includes(s))return{[fn]:mn};let m={...C,checkedIn:!0};return u?.includes(s)||Jr({tournamentRecord:o,drawDefinition:i,matchUpId:a,timeItem:{itemValue:s,itemType:cd}}),m}function Il(t){let e=et(t,[{[io]:!0,[Ce]:!0,[ln]:!0}]);if(e.error)return e;let r=t.tournamentId??t.activeTournamentId,n=t.tournamentRecord??(r&&t.tournamentRecords?.[r]);if(!n)return{error:$};let i=Ns(t,[{[ss]:Ln,attr:{[ru]:!0},[fn]:Le}]).matchUp?.matchUp;if(!i)return{error:Le};let{checkedInParticipantIds:s=[]}=ps({matchUp:i}),{participantId:a,matchUpId:c,drawDefinition:u}=t;return a&&s.includes(a)?iI({tournamentRecord:n,drawDefinition:u,participantId:a,matchUpId:c,matchUp:i}):sI({tournamentRecord:n,drawDefinition:u,participantId:a,matchUpId:c,matchUp:i})}function hl({tournamentRecord:t,drawDefinition:e,tieMatchUpId:r,event:n}){if(!t)return{error:$};if(!e)return{error:sn};if(!n)return{error:jr};let o=Me({drawDefinition:e}),{matchUp:i}=Bt({matchUpId:r,drawDefinition:e,matchUpsMap:o});if(!i)return{error:Le};let{matchUp:s,structure:a}=Bt({tournamentParticipants:t.participants,matchUpId:r,inContext:!0,drawDefinition:e,matchUpsMap:o,event:n});if(!s)return{error:Le};let{collectionPosition:c,drawPositions:u,collectionId:p,matchUpTieId:m,matchUpType:d}=s;if(d&&!kc([kt,xt],d))return{error:lr};let{positionAssignments:l}=Ct({structure:a}),f=l?.filter(P=>u?.includes(P.drawPosition)),{matchUp:g}=Bt({matchUpId:m,drawDefinition:e,matchUpsMap:o}),I=g?.sides?.map(St)??[],h=f?.map(St)??[],S=[...I,...h],{participants:T}=Gt({tournamentRecord:t,participantFilters:{participantTypes:[Ft],participantIds:S}}),{matchUp:y}=Bt({matchUpId:m,inContext:!0,drawDefinition:e,matchUpsMap:o}),E=We({matchUp:g,drawDefinition:e,structure:a,event:n})?.tieFormat;return{inContextDualMatchUp:y,inContextTieMatchUp:s,relevantAssignments:f,collectionPosition:c,teamParticipants:T,collectionId:p,matchUpType:d,dualMatchUp:g,tieMatchUp:i,tieFormat:E,structure:a,...C}}function aI(t){let e=hl(t);if(e.error)return e;let r="replaceTieMatchUpParticipantid",{existingParticipantId:n,tournamentRecord:o,newParticipantId:i,drawDefinition:s,substitution:a,event:c}=t;if(!n||!i)return _({result:{error:ie},stack:r});if(n===i)return{...C};let{inContextDualMatchUp:u,inContextTieMatchUp:p,collectionPosition:m,collectionId:d,dualMatchUp:l,tieMatchUp:f,tieFormat:g}=e,I=p?.matchUpType,h=p?.sides?.find(G=>G.participant?.participantId===n||G.participant?.individualParticipantIds?.includes(n));if(!h)return{error:re};let S=Gt({tournamentRecord:o,participantFilters:{participantIds:[n,i]}})?.participants??[];if(S.length!==2)return _({result:{error:ie},stack:r});if(S[0].participantType!==S[1].participantType)return _({result:{error:An},stack:r});let{appliedPolicies:T}=Tt({tournamentRecord:o,drawDefinition:s,event:c}),y=t.policyDefinitions?.[rr]??T?.[rr]??Ss[rr],E=S.find(({participantId:G})=>G===i);if((t.enforceGender??y?.participants?.enforceGender)!==!1&&[zt,oe].includes(p?.gender)&&p?.gender!==E?.person?.sex)return{error:Li,info:"Gender mismatch"};let A=y?.processCodes?.substitution;va({tournamentId:o.tournamentId,eventId:c.eventId,inContextDualMatchUp:u,drawDefinition:s,dualMatchUp:l});let U=l?.sides?.find(({sideNumber:G})=>G===h.sideNumber);if(!U)return _({result:{sideNumber:h.sideNumber,existingParticipantId:n,error:ve},stack:r});if(p?.sides?.flatMap(G=>G.participant?.individualParticipantIds||G.participant?.participantId||[])?.includes(i))return _({result:{error:Zu},stack:r});let D=u?.sides?.find(({sideNumber:G})=>G===h.sideNumber)?.participantId,M=U.lineUp,R=M?.find(({participantId:G})=>i===G),b=M?.reduce((G,k)=>k.substitutionOrder>G?k.substitutionOrder:G,0),v=M?.map(G=>{let k=J(G,!1,!0);if(![n,i].includes(k.participantId))return k;if(!a&&[n,i].includes(k.participantId)&&(k.collectionAssignments=k.collectionAssignments?.filter(H=>!(H.collectionPosition===m&&H.collectionId===d))),a&&n===k.participantId&&(k.collectionAssignments=k.collectionAssignments.map(H=>H.collectionPosition===m&&H.collectionId===d&&H.substitutionOrder===void 0?{...H,substitutionOrder:b}:H)),k.participantId===i){k.collectionAssignments||(k.collectionAssignments=[]);let H={collectionId:d,collectionPosition:m};a&&(H.previousParticipantId=n,H.substitutionOrder=(b??0)+1),k.collectionAssignments.push(H)}return k})??[];if(!R){let G={collectionId:d,collectionPosition:m};a&&(G.substitutionOrder=(b??0)+1,G.previousParticipantId=n);let k={collectionAssignments:[G],participantId:i};v.push(k)}let O=I===xt,{assignedParticipantIds:x}=Cp({lineUp:M,collectionPosition:m,collectionId:d}),{assignedParticipantIds:F}=Cp({lineUp:v,collectionPosition:m,collectionId:d});if(U.lineUp=v,D&&g){let G=Qi({participantId:D,lineUp:v,drawDefinition:s,tieFormat:g});if(G.error)return _({result:G,stack:r})}else console.log("team participantId not found");let w,L;if(O){let{tournamentRecord:G}=t,k=In({participantIds:F,tournamentRecord:G});if(!k.participant){let q=vn({returnParticipant:!0,pairOverride:!0,tournamentRecord:G,participant:{participantRole:xe,individualParticipantIds:F,participantType:ft}});if(q.error)return _({result:q,stack:r});w=q.participant?.participantId}k=In({participantIds:x,tournamentRecord:G});let H=k.participant?.participantId;H&&zi({participantIds:[H],tournamentRecord:G}).success&&(L=H)}if(a||h.substitutions?.length===1){if(a)A&&f&&(f.processCodes=pt([...f?.processCodes??[],...A]));else for(let G of A||[]){let k=f?.processCodes?.lastIndexOf(G);k!==void 0&&f?.processCodes?.splice(k,1)}f&&gt({tournamentId:o?.tournamentId,matchUp:f,context:r,drawDefinition:s})}return l&&gt({tournamentId:o?.tournamentId,matchUp:l,context:r,drawDefinition:s}),{...C,modifiedLineUp:v,participantRemoved:L,participantAdded:w}}function ky({collectionPosition:t,teamParticipantId:e,dualMatchUpSide:r,drawDefinition:n,participantIds:o,collectionId:i}){if(!i||!t||!Array.isArray(o))return{modifiedLineUp:r?.lineUp||[],error:V};let s=r?.lineUp||ds({participantId:e,drawDefinition:n})?.lineUp,a=[],c=[];return{modifiedLineUp:s?.map(p=>{if(!o.includes(p.participantId))return p;let m=p.collectionAssignments?.filter(d=>{let l=d.collectionId===i&&d.collectionPosition===t;return l&&(d.previousParticipantId&&a.push(d.previousParticipantId),c.push({participantId:p.participantId,...d})),!l});return{participantId:p.participantId,collectionAssignments:m}}).filter(Boolean)||[],assignmentsRemoved:c,previousParticipantIds:a}}function Ux({individualParticipantIds:t,groupingParticipantId:e,tournamentRecord:r}){let n=(r.events||[]).filter(i=>i?.eventType===_e&&i?.entries?.some(s=>s.participantId===e)),o=i=>!t.includes(i.participantId);for(let i of n){i.entries=(i.entries||[]).filter(o);let{flightProfile:s}=Ht({event:i});s?.flights?.forEach(a=>{a.drawEntries=(a.drawEntries||[]).filter(o)}),i?.drawDefinitions?.forEach(a=>{a.entries=(a.entries||[]).filter(o)})}return{...C}}function om({individualParticipantIds:t,groupingParticipantId:e,removeFromOtherTeams:r,tournamentRecord:n}){let o="addIndividualParticipantIds";if(!n)return _({result:{error:$},stack:o});if(!e||!t)return _({result:{error:st},stack:o});let i=n.participants??[],s=i.find(m=>m.participantId===e);if(!s)return _({result:{error:re},stack:o});if(s?.participantType&&![Ft,zr].includes(s.participantType))return _({context:{participantType:s.participantType},result:{error:An},stack:o});let a=t.filter(m=>i.find(l=>l.participantId===m)?.participantType!==At);if(a.length)return _({result:{error:wr,invalidParticipantIds:a},stack:o});s.individualParticipantIds||(s.individualParticipantIds=[]);let c=s.individualParticipantIds,u=t.filter(m=>!c.includes(m));u.length&&(r&&vp({individualParticipantIds:u,tournamentRecord:n}),s.individualParticipantIds=s.individualParticipantIds.concat(...u));let{topics:p}=Lr();if(p.includes(or)){let m=i.find(({participantId:d})=>d===e);lt({topic:or,payload:{participants:[m]}})}return Ux({individualParticipantIds:t,groupingParticipantId:e,tournamentRecord:n}),{groupingParticipant:J(s,!1,!0),added:u.length,...C}}function im(t){let{updateParticipantName:e=!0,groupingParticipantId:r,removeFromOtherTeams:n,tournamentRecord:o,pairOverride:i,participant:s}=t;if(!o)return{error:$};if(!s)return{error:Fi};if(!s.participantId)return vn({tournamentRecord:o,participant:s});let{participant:a}=yo({participantId:s.participantId,tournamentRecord:o});if(!a)return vn({tournamentRecord:o,participant:s});let{participantRoleResponsibilties:c,individualParticipantIds:u,participantOtherName:p,participantName:m,participantRole:d,participantType:l,onlineResources:f,contacts:g,person:I}=s;if(l&&a.participantType!==l)return{error:uE};let h={};if(g&&(h.contacts=g),f&&(h.onlineResources=f),p&&Vt(p)&&(h.participantOtherName=p),m&&Vt(m)&&(h.participantName=m),Array.isArray(u)){let{participants:S}=Gt({participantFilters:{participantTypes:[At]},tournamentRecord:o}),T=S?.map(St);if(T){let y=u.filter(E=>Vt(E)&&T.includes(E));([zr,Wt].includes(l||a.participantType)||l===ft&&(y.length===2||i))&&(h.individualParticipantIds=y),a.participantType===lu.PAIR&&e&&(h.participantName=O1({individualParticipants:S,newValues:h}))}}return Object.keys(hd).includes(d)&&(h.participantRole=d),Object.keys(lu).includes(l)&&(h.participantType=l),Array.isArray(c)&&(h.participantRoleResponsibilties=c),a.participantType===lu.INDIVIDUAL&&I&&_1({updateParticipantName:e,existingParticipant:a,newValues:h,person:I}),Object.assign(a,nt(h)),r&&om({individualParticipantIds:[a.participantId],groupingParticipantId:r,removeFromOtherTeams:n,tournamentRecord:o}),lt({topic:or,payload:{tournamentId:o.tournamentId,participants:[a]}}),{participant:J(a),...C}}function O1({individualParticipants:t,newValues:e}){let r=e.individualParticipantIds,n=t.filter(({participantId:o})=>r.includes(o)).map(({person:o})=>o?.standardFamilyName).filter(Boolean).sort().join("/");return r.length===1&&(n+="/Unknown"),n}function _1({updateParticipantName:t,existingParticipant:e,newValues:r,person:n}){let o={},{standardFamilyName:i,standardGivenName:s,nationalityCode:a,personId:c,birthdate:u,tennisId:p,sex:m}=n;m&&Object.keys(Cm).includes(m)&&(o.sex=m);let d;if(Vt(c)&&(o.personId=c),a&&Vt(a)&&(x1(a)||a==="")&&(o.nationalityCode=a),i&&typeof Vt(i)&&i.length>1&&(o.standardFamilyName=i,d=!0),s&&typeof Vt(s)&&s.length>1&&(o.standardGivenName=s,d=!0),d&&t){let l=`${o.standardGivenName} ${o.standardFamilyName}`;r.participantName=l}u&&Nr(u)&&(o.birthdate=u),p&&Vt(p)&&(o.tennisId=p),Object.assign(e.person,o)}function x1(t){return ri.flatMap(({iso:e,ioc:r})=>[e,r]).filter(Boolean).includes(t)}function Sl(t){let e=hl(t);if(e.error)return e;let r="assignTieMatchUpParticipantId",n=t.teamParticipantId,{tournamentRecord:o,drawDefinition:i,participantId:s,event:a}=t;if(!s)return _({result:{error:ie},stack:r});if(t.sideNumber&&![1,2].includes(t.sideNumber))return _({result:{error:Kl},stack:r});let{inContextDualMatchUp:c,inContextTieMatchUp:u,relevantAssignments:p,collectionPosition:m,teamParticipants:d,collectionId:l,matchUpType:f,dualMatchUp:g,tieFormat:I}=e;if(u?.sides?.flatMap(B=>B.participant?.individualParticipantIds||B.participant?.participantId||[])?.includes(s))return _({result:{...C},stack:r});n=n??(t.sideNumber?c?.sides?.find(B=>B.sideNumber===t.sideNumber)?.participantId:void 0);let S=Gt({participantFilters:{participantIds:[s]},tournamentRecord:o})?.participants?.[0];if(!S)return _({result:{error:re},stack:r});let{appliedPolicies:T}=Tt({tournamentRecord:o,drawDefinition:i,event:a}),y=t.policyDefinitions?.[rr]??T?.[rr]??Ss[rr];if((t.enforceGender??y?.participants?.enforceGender)!==!1&&[zt,oe].includes(u?.gender)&&u?.gender!==S.person?.sex)return{error:Li,info:"Gender mismatch"};let{individualParticipantIds:P,participantType:A}=S;if(de(kt)(f)&&A!==At)return{error:An};let U=A===At?[s]:P,N=n&&d?.find(({participantId:B})=>B===n)||d?.find(({individualParticipantIds:B})=>ke(U,B));if(!N)return{error:af};if(n||(n=N.participantId),!n)return{error:re};let M=p?.find(B=>B.participantId===N?.participantId)?.drawPosition,R=g?.sides?.find(B=>B.participantId===n)?.sideNumber,b=u?.sides?.find(B=>M&&B.drawPosition===M)?.sideNumber,v=R??b??t.sideNumber;if(!I)return{error:vs};if(!I.collectionDefinitions?.find(B=>B.collectionId===l))return{error:tE};va({tournamentId:o.tournamentId,eventId:a.eventId,inContextDualMatchUp:c,drawDefinition:i,dualMatchUp:g});let x=g?.sides?.find(B=>B.sideNumber===v),F=u?.sides?.find(B=>B.sideNumber===v),G=(x?.lineUp??ds({participantId:n,drawDefinition:i})?.lineUp)?.filter(B=>B.collectionAssignments?.find(K=>K.collectionPosition===m&&K.collectionId===l&&!K.previousParticipantId))?.map(B=>B?.participantId),k=G?.length>1&&G||(A===ft?S.individualParticipantIds:[s]),H=ky({collectionPosition:m,teamParticipantId:n,dualMatchUpSide:x,drawDefinition:i,participantIds:k,collectionId:l});if(H.error)return _({result:H,stack:r});let{modifiedLineUp:W}=H,q;if(f===xt){if(A!==ft){let B=aM({collectionPosition:m,teamParticipantId:n,drawDefinition:i,modifiedLineUp:W,participantId:s,collectionId:l,tieFormat:I});if(B?.error)return _({result:B,stack:r});if(B=Y({side:F}),B.error)return B;q=B.deletedParticipantId,x&&(x.lineUp=W),g&&gt({tournamentId:o?.tournamentId,matchUp:g,context:r,drawDefinition:i})}else if(A===ft)for(let B of k)aM({collectionPosition:m,teamParticipantId:n,drawDefinition:i,modifiedLineUp:W,participantId:B,collectionId:l,tieFormat:I})}else{let B=aM({collectionPosition:m,teamParticipantId:n,drawDefinition:i,modifiedLineUp:W,participantId:s,collectionId:l,tieFormat:I});if(B?.error)return B}if(x&&(x.lineUp=W),g&&gt({tournamentId:o?.tournamentId,matchUp:g,context:r,drawDefinition:i}),q){let{error:B}=zi({participantIds:[q],tournamentRecord:o});B&&console.log("cleanup")}return{...C,modifiedLineUp:W};function Y({side:B}){let K;if(B.participant){let X=B.participant.individualParticipantIds||[];if(X.filter(Boolean).length===1){let{participant:ot}=In({participantIds:X,tournamentRecord:o});X.push(s);let{participant:z}=In({participantIds:X,tournamentRecord:o});if(!z&&ot){ot.individualParticipantIds=X;let Q=im({pairOverride:!0,tournamentRecord:o,participant:ot});if(Q.error)return Q}else K=ot?.participantId}}else{let j=vn({participant:{individualParticipantIds:[s],participantRole:xe,participantType:ft},pairOverride:!0,tournamentRecord:o});if(j.error)return j}return{...C,deletedParticipantId:K}}}function aM({collectionPosition:t,teamParticipantId:e,drawDefinition:r,modifiedLineUp:n,participantId:o,collectionId:i,tieFormat:s}){let a=ds({participantId:e,drawDefinition:r})?.lineUp,c=(n||a)?.find(p=>p?.participantId===o),u={collectionId:i,collectionPosition:t};if(c)c.collectionAssignments.push(u);else{let p={collectionAssignments:[u],participantId:o};n.push(p)}return Qi({participantId:e,lineUp:n,drawDefinition:r,tieFormat:s})}function cM(t){let{tournamentRecord:e,drawDefinition:r,participantId:n,event:o}=t,i="removeTieMatchUpParticiapantId";if(!n)return _({result:{error:ie},stack:i});let s=hl(t);if(s.error)return s;let{appliedPolicies:a}=Tt({tournamentRecord:e,drawDefinition:r,event:o}),u=(t.policyDefinitions?.[rr]??a?.[rr]??Ss[rr])?.processCodes?.substitution,{inContextDualMatchUp:p,inContextTieMatchUp:m,relevantAssignments:d,collectionPosition:l,teamParticipants:f,collectionId:g,matchUpType:I,dualMatchUp:h,tieMatchUp:S,tieFormat:T}=s;if(!h)return _({result:{error:Tr},stack:i});let y=m?.sides?.find(R=>R.participant?.participantId===n||R.participant?.individualParticipantIds?.includes(n));if(!y)return _({result:{error:re},stack:i});let E=t.policyDefinitions?.[tn]??a?.[tn];if(!y.substitutions?.length&&(Ie({score:m?.score})||m?.winningSide)&&E?.requireParticipantsForScoring!==!1)return _({result:{error:LE},stack:i});let P=p?.sides?.find(({sideNumber:R})=>R===y.sideNumber)?.participantId;if(!P)return _({result:{error:re},stack:i});let A=Gt({participantFilters:{participantIds:[n]},tournamentRecord:e})?.participants?.[0];if(!A)return _({result:{error:re},stack:i});if(I===kt&&A.participantType===ft)return _({result:{error:Li},stack:i});let U=A.participantType===At?[n]:A.individualParticipantIds;va({tournamentId:e.tournamentId,eventId:o.eventId,inContextDualMatchUp:p,drawDefinition:r,dualMatchUp:h});let N=h.sides?.find(({sideNumber:R})=>R===y.sideNumber);if(!N&&(h.sides?.filter(({lineUp:R})=>!R).length||0)<2){let R=f?.map(({participantId:b})=>({drawPosition:d?.find(v=>v.participantId===b)?.drawPosition,teamParticipantId:b}));N=h.sides?.find(b=>R?.find(({drawPosition:v})=>v===b.drawPosition)?.teamParticipantId===P)}if(!N)return _({result:{error:re,context:{participantId:n}}});let{modifiedLineUp:D,previousParticipantIds:M}=ky({collectionPosition:l,teamParticipantId:P,dualMatchUpSide:N,participantIds:U,drawDefinition:r,collectionId:g});if(N.lineUp=D,P&&T&&Qi({participantId:P,lineUp:D,drawDefinition:r,tieFormat:T}),I===xt&&A.participantType===At){let R=m?.sides?.find(O=>O.sideNumber===N?.sideNumber),{participantId:b}=R??{},v=b&&Gt({participantFilters:{participantIds:[b]},tournamentRecord:e,withDraws:!0})?.participants?.[0];if(v){let O=v?.individualParticipantIds?.filter(x=>x!==n)??[];if(M&&O.push(...M),O.length>2)return _({result:{error:wr},stack:i});if(v.draws?.length){if(O.length===1){let{participant:x}=In({participantIds:O,tournamentRecord:e});if(!x){let w=vn({participant:{participantRole:xe,individualParticipantIds:O,participantType:ft},pairOverride:!0,tournamentRecord:e});if(w.error)return _({result:w,stack:i})}}}else if(O.length){v.individualParticipantIds=O;let x=im({participant:v,pairOverride:!0,tournamentRecord:e});if(x.error)return _({result:x,stack:i})}else{let x=zi({participantIds:[b],tournamentRecord:e});x.error&&console.log("cleanup",{result:x})}}else return _({result:{error:re},stack:i})}if(y.substitutions?.length===1&&!m?.sides?.find(b=>b.sideNumber!==y.sideNumber)?.substitutions?.length&&S?.processCodes?.length){for(let b of u||[]){let v=S.processCodes.lastIndexOf(b);S.processCodes.splice(v,1)}gt({tournamentId:e?.tournamentId,matchUp:S,context:i,drawDefinition:r})}return gt({tournamentId:e?.tournamentId,matchUp:h,context:i,drawDefinition:r}),{...C,modifiedLineUp:D}}function cI(t){let e=et(t,[{[ne]:!0,[Ce]:!0,[ln]:!0}]);if(e.error)return e;let{drawDefinition:r,sideNumber:n,matchUpId:o,event:i}=t;if(n&&![1,2].includes(n))return{error:V,sideNumber:n};let{matchUp:s,structure:a}=Bt({drawDefinition:r,matchUpId:o,event:i});return s?pr({structure:a})?(s.sides?.forEach(c=>{(!n||c.sideNumber===n)&&delete c.participantId}),gt({tournamentId:t.tournamentRecord?.tournamentId,context:"assignSideParticipant",drawDefinition:r,matchUp:s}),{...C}):{error:Um}:{error:Le}}function Px({matchUpStatuses:t=[Nt,bt,Rt],drawPositionMatchUps:e,loserDrawPosition:r,sourceMatchUps:n}){let o=e?.reduce((p,m)=>!p||m.roundNumber>p.roundNumber?m:p,void 0),i=o?.drawPositions?.find(p=>p!==r),s=n.filter(p=>p?.drawPositions?.includes(i)).map(p=>p.matchUpStatus),a=n.filter(p=>p?.drawPositions?.includes(r)).map(p=>p.matchUpStatus),c=ke(s||[],t),u=ke(a||[],t);return{sourceMatchUp:o,winnerHadMatchUpStatus:c,winnerMatchUpStatuses:s,loserHadMatchUpStatus:u,loserMatchUpStatuses:a}}function Dx({inContextDrawMatchUps:t,sourceMatchUpStatus:e,targetDrawPosition:r,tournamentRecord:n,sourceMatchUpId:o,drawDefinition:i,structureId:s,dualMatchUp:a,roundNumber:c,matchUpsMap:u,event:p}){let{structure:m}=at({drawDefinition:i,structureId:s});if(m?.structureType===Ve)return{...C};u=u??Me({drawDefinition:i});let l=(u?.mappedMatchUps||{})[s].matchUps,{initialRoundNumber:f}=gs({drawPosition:r,matchUps:l}),g=l?.filter(h=>h.roundNumber>=c&&h.roundNumber!==f&&h.drawPositions?.includes(r)),{positionAssignments:I}=Ct({drawDefinition:i,structureId:s});for(let h of g??[])w1({inContextDrawMatchUps:t,sourceMatchUpStatus:e,positionAssignments:I,targetDrawPosition:r,tournamentRecord:n,sourceMatchUpId:o,drawDefinition:i,dualMatchUp:a,matchUpsMap:u,matchUp:h,event:p});return{...C}}function w1({inContextDrawMatchUps:t,positionAssignments:e,sourceMatchUpStatus:r,targetDrawPosition:n,tournamentRecord:o,sourceMatchUpId:i,drawDefinition:s,dualMatchUp:a,matchUpsMap:c,matchUp:u,event:p}){let m="removeSubsequentDrawPosition";if(a){let g=t.find(({matchUpId:h})=>u.matchUpId===h).sides?.find(h=>h.drawPosition===n)?.sideNumber,I=u.sides?.find(h=>h.sideNumber===g);I&&delete I.lineUp}u.drawPositions=(u.drawPositions||[]).map(f=>f===n?void 0:f).filter(Boolean);let l=e.filter(({drawPosition:f})=>u.drawPositions?.includes(f)).filter(f=>f.bye).length;return u.matchUpStatus=l&&Nt||[Rt,bt].includes(u.matchUpStatus)&&u.matchUpStatus||Xt,[bt,Rt].includes(u.matchUpStatus)&&(u.winningSide=void 0),u.matchUpStatusCodes&&vS({inContextDrawMatchUps:t,sourceMatchUpStatus:r,sourceMatchUpId:i,matchUpsMap:c,matchUp:u}),gt({tournamentId:o?.tournamentId,eventId:p?.eventId,context:`${m}-${n}`,drawDefinition:s,matchUp:u}),{...C}}function _c(t){let{dualWinningSideChange:e,inContextDrawMatchUps:r,tournamentRecord:n,drawDefinition:o,matchUpStatus:i,matchUpsMap:s,dualMatchUp:a,targetData:c,matchUpId:u,structure:p,event:m}=t,d=!!t.matchUp.collectionId,l=pr({structure:p}),{drawPositions:f,winningSide:g}=c.matchUp||{};if(!l&&!f)return{error:Ya};let{targetLinks:{loserTargetLink:I,winnerTargetLink:h,byeTargetLink:S},targetMatchUps:{loserMatchUp:T,winnerMatchUp:y,byeMatchUp:E}}=c,P=Hn({...t,matchUpStatus:i||Xt,removeWinningSide:!0});if(P.error)return P;let A;if(d){let{matchUpTieId:w,matchUpsMap:L}=t;if(A=lo({appliedPolicies:t.appliedPolicies,matchUpId:w,tournamentRecord:n,drawDefinition:o,matchUpsMap:L,event:m}),!e&&!A.removeWinningSide)return{...C}}if(l)return{...C};let{matchUps:U}=yt({afterRecoveryTimes:!1,inContext:!0,drawDefinition:o,matchUpsMap:s,structure:p}),{positionAssignments:N}=ge({structure:p}),D=g-1,M=1-D,R=f[D],b=f[M],{winnerParticipantId:v,loserParticipantId:O}=N?.reduce((w,L)=>(L.drawPosition===b&&(w.loserParticipantId=L.participantId),L.drawPosition===R&&(w.winnerParticipantId=L.participantId),w),{winnerParticipantId:void 0,loserParticipantId:void 0})||{},x=U.filter(w=>w.drawPositions?.includes(b));if(y&&uM({sourceMatchUpStatus:i,sourceMatchUpId:u,inContextDrawMatchUps:r,winningDrawPosition:R,winnerParticipantId:v,tournamentRecord:n,winnerTargetLink:h,drawDefinition:o,winnerMatchUp:y,dualMatchUp:a,matchUpsMap:s}),T){let{winnerHadMatchUpStatus:w}=Px({drawPositionMatchUps:x,loserDrawPosition:b,sourceMatchUps:U}),G=I.linkCondition===wn;if(w&&G){let H=Math.min(...T.drawPositions);Gy({targetLink:I,inContextDrawMatchUps:r,drawDefinition:o,drawPosition:H,matchUpsMap:s,event:m})}let k=L1({sourceMatchUpStatus:i,sourceMatchUpId:u,loserParticipantId:O,tournamentRecord:n,loserTargetLink:I,drawDefinition:o,loserMatchUp:T,dualMatchUp:a,matchUpsMap:s,event:m});if(k.error)return k}if(E){let w=Math.min(...E.drawPositions);Gy({sourceMatchUpId:u,targetLink:S,inContextDrawMatchUps:r,drawDefinition:o,drawPosition:w,matchUpsMap:s,event:m})}return{...C,...A&&{tieMatchUpResult:A}}}function uM({inContextDrawMatchUps:t,winningDrawPosition:e,sourceMatchUpStatus:r,winnerParticipantId:n,tournamentRecord:o,winnerTargetLink:i,sourceMatchUpId:s,drawDefinition:a,winnerMatchUp:c,matchUpsMap:u,dualMatchUp:p,event:m}){let{structureId:d,roundNumber:l}=c,f="removeDirectedWinner";if(i){let g=i.target.structureId,{structure:I}=at({drawDefinition:a,structureId:g});if(!I)return{error:wt};let{positionAssignments:h}=ge({structure:I});I.seedAssignments=(I.seedAssignments??[]).filter(N=>N.participantId!==n);let T=h?.find(N=>N.participantId===n)?.drawPosition,{matchUps:y}=yt({drawDefinition:a,structure:I,event:m}),E=y.map(N=>N.drawPositions).flat(1/0).filter(Boolean),P=yr(E);if((T?P[T]:void 0)===1)h?.forEach(N=>{N.participantId===n&&delete N.participantId});else{let N=y.filter(({drawPositions:D})=>D.includes(T));console.log("not removing from position assignments since instances > 1",{drawPositionMatchUps:N,winnerTargetLink:i})}let U=u?.drawMatchUps?.find(({matchUpId:N})=>N===c.matchUpId);U&&gt({tournamentId:o?.tournamentId,eventId:m?.eventId,matchUp:U,context:f,drawDefinition:a})}return l&&Dx({targetDrawPosition:e,inContextDrawMatchUps:t,sourceMatchUpStatus:r,tournamentRecord:o,sourceMatchUpId:s,drawDefinition:a,dualMatchUp:p,matchUpsMap:u,roundNumber:l,structureId:d}),{...C}}function L1({sourceMatchUpStatus:t,loserParticipantId:e,tournamentRecord:r,loserTargetLink:n,sourceMatchUpId:o,drawDefinition:i,loserMatchUp:s,matchUpsMap:a,dualMatchUp:c,event:u}){let p="removeDirectedLoser",m=n.target.structureId,{structure:d}=at({drawDefinition:i,structureId:m});if(!d)return{error:wt};let{positionAssignments:l}=ge({structure:d}),f=l?.find(g=>g.participantId===e)?.drawPosition;if(l?.forEach(g=>{g.participantId===e&&delete g.participantId}),d.seedAssignments=(d.seedAssignments??[]).filter(g=>g.participantId!==e),c){let g=s?.sides.reduce((S,T,y)=>T.drawPosition===f?y:S,void 0),I=a?.drawMatchUps?.find(({matchUpId:S})=>S===s.matchUpId),h=I?.sides?.[g];h&&(delete h.lineUp,gt({tournamentId:r?.tournamentId,eventId:u?.eventId,matchUp:I,context:p,drawDefinition:i}))}return{...C}}function Gy({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,matchUpsMap:o,targetLink:i,event:s}){let a=i.target.structureId,c="removeDirectedBye";Cn({color:"brightyellow",method:c,drawPosition:n});let u=gc({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,matchUpsMap:o,structureId:a,event:s});return _({result:u,stack:c})}function Nx(t){let{matchUpFormat:e,score:r}=t,n=r?.sets?.length,o=e&&Ye(e),{setFormat:i,finalSetFormat:s,bestOf:a}=o??{};return(a&&n===a&&s||i)?.timed||!1}function Mx({tournamentRecord:t,drawDefinition:e,structure:r,matchUp:n}){let o="attemptToSetMatchUpStatusBYE";if(n?.winningSide)return _({result:{error:da},context:{matchUpStatus:Nt},stack:o});let{positionAssignments:i}=ge({structure:r}),s=i?.filter(c=>c.bye).map(c=>c.drawPosition);return n.drawPositions?.some(c=>s?.includes(c))?(n.matchUpStatus=Nt,n.matchUpStatusCodes=[],gt({tournamentId:t?.tournamentId,context:o,drawDefinition:e,matchUp:n}),{...C}):_({result:{error:ZA},info:"matchUp does not include BYE",stack:o})}function Tl(t){let{tournamentRecord:e,appliedPolicies:r,drawDefinition:n,matchUpsMap:o,targetData:i,structure:s,event:a}=t,c="doubleExitAdvancement";if(s.structureType===Ve)return _({result:{...C},stack:c});let{matchUp:u,targetMatchUps:p,targetLinks:m}=i,{loserMatchUp:d,winnerMatchUp:l,loserTargetDrawPosition:f}=p,g=[bt,Rt].includes(d?.matchUpStatus)&&!d.sides?.map(I=>I.participantId??I.participant).filter(Boolean).length;if(d&&d.matchUpStatus!==Nt){let{loserTargetLink:I}=m;if(r?.progression?.doubleExitPropagateBye){let h=Cx({loserTargetDrawPosition:f,tournamentRecord:e,loserTargetLink:I,drawDefinition:n,loserMatchUp:d,matchUpsMap:o,event:a});if(h.error)return _({result:h,stack:c})}else if(!g){let{feedRound:h,drawPositions:S,matchUpId:T}=d,y=h?2:2-S.indexOf(f),E=Rx({...t,targetMatchUp:d,walkoverWinningSide:y,tournamentRecord:e,sourceMatchUp:u,matchUpId:T});if(E.error)return _({result:E,stack:c})}}if(l){let I=Rx({...t,matchUpId:l.matchUpId,targetMatchUp:l,tournamentRecord:e,sourceMatchUp:u});if(I.error)return _({result:I,stack:c})}return _({result:{...C},stack:c})}function Rx(t){let{inContextDrawMatchUps:e,tournamentRecord:r,drawDefinition:n,sourceMatchUp:o,targetMatchUp:i,matchUpsMap:s}=t,a=n.structures.find(({structureId:Y})=>Y===i.structureId),c=t.matchUpStatus===be?be:Te,u=t.matchUpStatus===be?Rt:bt,p="conditionallyAdvanceDrawPosition",m=s.drawMatchUps.find(Y=>Y.matchUpId===i.matchUpId);if(!m)return{error:Tr};let d=o?.drawPositions||[],l=m.drawPositions?.filter(Boolean),f=o?.structureId===i.structureId;if(f&&ke(d,l)&&(l=l.filter(Y=>!d.includes(Y))),f&&l.length>1)return _({result:{error:ja},stack:p});let{pairedPreviousMatchUpIsDoubleExit:g,pairedPreviousMatchUp:I}=CS(t),h=mr({matchUpId:i.matchUpId,inContextDrawMatchUps:e,drawDefinition:n}),{targetMatchUps:S,targetLinks:T}=h,{loserTargetDrawPosition:y,winnerMatchUp:E,loserMatchUp:P}=S;if(P){let{loserTargetLink:Y}=T,B=Cx({loserTargetDrawPosition:y,loserMatchUp:P,tournamentRecord:r,loserTargetLink:Y,drawDefinition:n,matchUpsMap:s});if(B.error)return _({result:B,stack:p})}let A=m.drawPositions?.filter(Boolean)||[],U=A.length===1,N=t.walkoverWinningSide||U&&Td({drawPosition:A[0],matchUpId:i.matchUpId,inContextDrawMatchUps:e})||void 0,D=[bt,Rt].includes(m.matchUpStatus)&&!A.length,M=m.finishingRound===1,R=D&&!M?c:u,b=e.find(Y=>Y.matchUpId===I.matchUpId),v=[],O;o&&(o?.structureId===b?.structureId?o.roundPosition<I?.roundPosition?O=1:O=2:i.feedRound?o.structureId===i.structureId?O=2:O=1:N&&(O=3-N));let x=t.matchUpStatus,F=I?.matchUpStatus;O===1?v=[{matchUpStatus:Vy(x),previousMatchUpStatus:x,sideNumber:1},{matchUpStatus:Vy(F),previousMatchUpStatus:F,sideNumber:2}]:O===2&&(v=[{matchUpStatus:Vy(F),previousMatchUpStatus:F,sideNumber:1},{matchUpStatus:Vy(x),previousMatchUpStatus:x,sideNumber:2}]),v.length&&(v=v.map(Y=>nt(Y)));let w=Hn({...t,winningSide:N,matchUp:m,matchUpStatusCodes:v,context:p,matchUpStatus:R});if(w.error)return _({result:w,stack:p});if(D)return Tl({...t,matchUpStatus:R,targetData:h});if(!E)return _({result:{...C},stack:p});let L=l.length===2?l[N-1]:l[0],{positionAssignments:G}=Ct({structure:a}),k=G?.find(Y=>Y.drawPosition===L),H=s.drawMatchUps.find(Y=>Y.matchUpId===E.matchUpId),W=H?.drawPositions?.filter(Boolean),q=W.length===1;if(L){if(k?.bye){let Y=mr({matchUpId:H.matchUpId,inContextDrawMatchUps:e,drawDefinition:n});if(q){let B=W.filter(Boolean)[0],K=Td({drawPosition:B,matchUpId:H.matchUpId,inContextDrawMatchUps:e}),X=Hn({appliedPolicies:t.appliedPolicies,matchUpId:H.matchUpId,matchUp:H,matchUpStatus:u,matchUpStatusCodes:[],removeScore:!0,context:p,drawDefinition:n,winningSide:K});return X.error?_({result:X,stack:p}):ES({drawPositionToAdvance:B,matchUpId:H.matchUpId,inContextDrawMatchUps:e,drawDefinition:n,matchUpsMap:s})}else if([bt,Rt].includes(E.matchUpStatus)){let B=Tl({...t,matchUpId:H.matchUpId,matchUpStatus:R,targetData:Y});if(B.error)return _({result:B,stack:p})}return _({result:{...C},stack:p})}return Tc({matchUpId:E.matchUpId,drawPosition:L,inContextDrawMatchUps:e,drawDefinition:n})}else if(g){if(!H)return{error:Tr};if(q){let K=W[0],X=Td({matchUpId:i.matchUpId,inContextDrawMatchUps:e,drawPosition:K});console.log("existing drawPosition is winningSide",{walkoverWinningSide:X})}let Y=[bt,Rt].includes(H.matchUpStatus)?u:c,B=Hn({matchUpId:H.matchUpId,appliedPolicies:t.appliedPolicies,matchUp:H,matchUpStatusCodes:[],removeScore:!0,context:p,drawDefinition:n,matchUpStatus:Y});if(B.error)return _({result:B,stack:p});if(Y===c){let K=Tl({...t,matchUpId:i.matchUpId,matchUpStatus:Y,targetData:h});if(K.error)return K}}return _({result:{...C},stack:p})}function Cx(t){let{loserTargetDrawPosition:e,tournamentRecord:r,loserTargetLink:n,drawDefinition:o,matchUpsMap:i,event:s}=t,a=n?.target?.structureId,{structure:c}=at({drawDefinition:o,structureId:a});return c?Hr({drawPosition:e,tournamentRecord:r,drawDefinition:o,structureId:a,matchUpsMap:i,event:s}):{error:di}}function Vy(t){return t===Te?bt:t===be?Rt:t}function bx(t){let{tournamentRecord:e,drawDefinition:r,matchUpStatus:n,structure:o,matchUp:i}=t,s=!!(i.tieMatchUps&&!i.rondPosition&&t.inContextDrawMatchUps.find(h=>h.matchUpId===i.matchUpId).containerStructureId),a="attemptToSetMatchUpStatus",c=n===Nt,u=i.winningSide,p=[Te,be].includes(n),m=Da({matchUpStatus:n}),d=ug({matchUpStatus:n}),l=!m&&!d,f=t.matchUpTieId||u&&m&&!p,g=u&&p,I=()=>Hn({...t,removeScore:[co,bt].includes(n),matchUpStatus:n||Xt});return l&&{error:GI}||f&&pM(t)||g&&F1(t)||u&&_c(t)||d&&I()||c&&Mx({tournamentRecord:e,drawDefinition:r,structure:o,matchUp:i})||!m&&{error:GI}||p&&k1(t)||s&&pM(t)||_({result:{error:da},stack:a})}function F1(t){let e=_c(t);return e.error?e:Tl(t)}function k1(t){let e=pM({...t,removeScore:!0});return e.error?e:Tl(t)}function pM(t){let e="scoreModification";if(t.isCollectionMatchUp&&t.dualMatchUp?.winningSide&&!t.projectedWinningSide){let i=_c(t);if(i.error)return _({result:i,stack:e})}let n=!!t.matchUp.collectionId,o=Hn({...t,context:e});if(n){let{matchUpTieId:i,drawDefinition:s,matchUpsMap:a}=t,c=lo({tournamentRecord:t.tournamentRecord,appliedPolicies:t.appliedPolicies,matchUpId:i,event:t.event,drawDefinition:s,matchUpsMap:a});if(c.error)return _({result:c,stack:e});Object.assign(o,{tieMatchUpResult:c})}return _({result:o,stack:e})}function vx({drawDefinition:t,structure:e,matchUp:r}){let{drawPositions:n}=r,{positionAssignments:o}=Ct({drawDefinition:t,structure:e}),s=o?.filter(({drawPosition:m})=>n?.includes(m))?.map(m=>{let{extension:d}=mt({element:m,name:bo});return d?.value?.groupOrder}),{containerStructures:a}=cs({drawDefinition:t}),c=a[e.structureId];return{structureIds:js({drawDefinition:t,structureId:c})?.links?.source?.filter(m=>ke(s,m.source?.finishingPositions||[])).map(m=>m.source.structureId)}}function By({drawDefinition:t,structure:e,matchUp:r}){let n=[];if(e.finishingPosition===gi&&Eo({drawDefinition:t,structure:e})){let{structureIds:i}=vx({drawDefinition:t,structure:e,matchUp:r});i?.length&&n.push(...i)}return{connectedStructureIds:n}}function Ox(t){let e,{inContextDrawMatchUps:r,inContextMatchUp:n,drawDefinition:o,winningSide:i}=t,s=t.targetData.targetLinks?.winnerTargetLink;if(s.target.feedProfile===dn){let a=n.sides.find(({sideNumber:u})=>u!==i).participantId,c=r.find(u=>u.structureId===s.target.structureId&&u.roundNumber===s.target.roundNumber&&u.sides.some(({participantId:p})=>p===a));if(c?.matchUpStatus===Xt){let u=mr({matchUpId:c.matchUpId,inContextDrawMatchUps:r,drawDefinition:o});if(!vi({inContextDrawMatchUps:r,drawDefinition:o,targetData:u})){let{structure:m}=at({structureId:c.structureId,drawDefinition:o}),d=Ct({structure:m}).positionAssignments;for(let l of d||[])if(l.participantId===a){let f=n.sides.find(({sideNumber:g})=>g===i).participantId;if(l.participantId=f,m?.positionAssignments)m.positionAssignments=d;else if(m?.structures){let g=Object.assign({},...(d||[]).map(I=>({[I.drawPosition]:I.participantId})));for(let I of m.structures)I.positionAssignments?.forEach(h=>h.participantId=g[h.drawPosition])}Oo({tournamentId:t.tournamentRecord?.tournamentId,event:t.event,drawDefinition:o,structure:m}),e=!0}}}}return{...C,qualifierReplaced:e}}function _x(t){let e,{inContextDrawMatchUps:r,inContextMatchUp:n,drawDefinition:o,winningSide:i}=t,s=t.targetData.targetLinks?.winnerTargetLink;if(s.target.feedProfile===dn){let a=n.sides.find(({sideNumber:p})=>p===i)?.participantId,c=r.filter(p=>p.structureId===s.target.structureId&&p.roundNumber===s.target.roundNumber&&p.sides.some(({participantId:m,qualifier:d})=>d&&!m)),u=yn(c);if(u?.matchUpStatus===Xt){let p=mr({matchUpId:u.matchUpId,inContextDrawMatchUps:r,drawDefinition:o});if(!vi({inContextDrawMatchUps:r,drawDefinition:o,targetData:p})){let d=u.sides.find(g=>g.qualifier&&!g.participantId)?.drawPosition,{structure:l}=at({structureId:u.structureId,drawDefinition:o});if(!l)return{error:wt};let f=Ct({structure:l}).positionAssignments;for(let g of f||[])if(g.drawPosition===d&&!g.participantId){if(g.participantId=a,l.positionAssignments)l.positionAssignments=f;else if(l.structures){let I=Object.assign({},...(f||[]).map(h=>({[h.drawPosition]:h.participantId})));for(let h of l.structures)h.positionAssignments?.forEach(S=>S.participantId=I[S.drawPosition])}Oo({tournamentId:t.tournamentRecord?.tournamentId,event:t.event,drawDefinition:o,structure:l}),e=!0}}}}return{...C,qualifierPlaced:e}}function xx(t){let e="attemptToSetWinningSide",r,{appliedPolicies:n,disableAutoCalc:o,drawDefinition:i,dualMatchUp:s,winningSide:a,structure:c,matchUp:u}=t;if(s?._disableAutoCalc&&o!==!1)return bd(t);if(u.winningSide&&u.winningSide!==a){let{connectedStructureIds:l}=By({drawDefinition:i,structure:c,matchUp:u});l.length&&(console.log({connectedStructureIds:l}),r=!0);let f=_c(t);if(f.error)return f}let p=nT(t);if(p.error)return _({result:p,stack:e});let m,d;return t.qualifierChanging&&n?.[nu]?.autoReplaceQualifiers&&(m=Ox(t).qualifierReplaced),t.qualifierAdvancing&&n?.[nu]?.autoPlaceQualifiers&&(d=_x(t).qualifierPlaced),_({result:nt({...C,...p,connectedStructures:r,qualifierReplaced:m,qualifierPlaced:d}),stack:e})}var Hy={drawPositionToRemove:"green",iteration:"brightred",winner:"green",loser:"brightred"};function mM(t){let{inContextDrawMatchUps:e,appliedPolicies:r,drawDefinition:n,matchUpsMap:o,targetData:i,matchUp:s}=t,{matchUpId:a}=s,{iteration:c=0}=t;c+=1;let u="removeDoubleExit";Cn({color:"brightyellow",method:u,matchUpId:a,iteration:c,keyColors:Hy});let{targetMatchUps:{loserMatchUp:p,winnerMatchUp:m,loserTargetDrawPosition:d},targetLinks:{loserTargetLink:l}}=i;if(m&&m.matchUpStatus!==Nt){let{stage:I,roundNumber:h,roundPosition:S,structureName:T}=m;Cn({winner:"winner",roundPosition:S,structureName:T,roundNumber:h,keyColors:Hy,stage:I}),wx({...t,targetMatchUp:m,sourceMatchUp:s,iteration:c})}let f=p?.matchUpStatus===Nt&&(p?.feedRound||p?.roundNumber===1),g=i?.targetLinks?.loserTargetLink?.linkCondition===wn;if(f&&g){let I=e.filter(({roundNumber:E,structureId:P})=>P===s.structureId&&E===1),h=I.map(({roundPosition:E})=>E),S=Ee(h.sort(),2).find(E=>E.includes(s.roundPosition));if((I.filter(({roundPosition:E})=>S.includes(E))?.map(({matchUpStatus:E})=>E)).every(E=>[be,Te].includes(E)))return _({result:{...C},stack:u})}if(p&&(p.matchUpStatus!==Nt||f)){let I=e.find(({matchUpId:A})=>A===p.matchUpId),{structure:h}=at({drawDefinition:n,structureId:I.structureId}),{stage:S,roundNumber:T,roundPosition:y,feedRound:E,structureName:P}=p;if(Cn({loser:"loser",roundPosition:y,structureName:P,roundNumber:T,keyColors:Hy,feedRound:E,stage:S}),r?.progression?.doubleExitPropagateBye||f)Gy({drawPosition:d,targetLink:l,inContextDrawMatchUps:e,drawDefinition:n,matchUpsMap:o});else{let A=wx({...t,targetMatchUp:p,structure:h,iteration:c});if(A.error)return _({result:A,stack:u})}}return _({result:{...C},stack:u})}function wx(t){let{inContextDrawMatchUps:e,appliedPolicies:r,drawDefinition:n,sourceMatchUp:o,targetMatchUp:i,matchUpsMap:s,structure:a,iteration:c}=t,u="conditionallyRemoveDrawPosition";Cn({method:u,structureName:a?.structureName,iteration:c});let p=mr({matchUpId:i.matchUpId,inContextDrawMatchUps:e,drawDefinition:n}),{targetMatchUps:{winnerMatchUp:m}}=p,d=s?.drawMatchUps.find(y=>y.matchUpId===i.matchUpId),l=[],f,g,I;if(i.feedRound)I=m?.drawPositions?.filter(Boolean)?.find(E=>i.drawPositions.includes(E));else if(!o)I=jt(i?.drawPositions||[],m?.drawPositions||[])?.[0];else if(g=bS({structureId:a.structureId,matchUp:o,matchUpsMap:s})?.pairedPreviousMatchUp,f=[Te,be].includes(g?.matchUpStatus),l=g?.drawPositions?.filter(Boolean)||[],[...se,Nt].includes(g?.matchUpStatus)||g?.winningSide){let E=o.drawPositions||[],P=i.drawPositions?.filter(Boolean);ke(E,P)&&(P=P?.filter(U=>!E.includes(U))),I=E.concat(l).find(U=>P?.includes(U))}if(m&&I){let{stage:y,roundNumber:E,roundPosition:P,structureName:A}=m;Cn({method:"removeDirectedWinner",drawPositionToRemove:I,color:"brightgreen",roundPosition:P,structureName:A,roundNumber:E,keyColors:Hy,stage:y}),uM({winningDrawPosition:I,winnerMatchUp:m,inContextDrawMatchUps:e,drawDefinition:n,matchUpsMap:s})}let h=mM({targetData:p,matchUp:i,inContextDrawMatchUps:e,appliedPolicies:r,drawDefinition:n,matchUpsMap:s,structure:a,iteration:c});if(h.error)return _({result:h,stack:u});let S=G1({pairedPreviousDoubleExit:f,noContextTargetMatchUp:d}),T=!f;return h=Hn({...t,matchUpId:i.matchUpId,matchUp:d,removeWinningSide:!0,matchUpStatusCodes:[],context:u,matchUpStatus:S,removeScore:T,score:{scoreStringSide1:"",scoreStringSide2:"",sets:void 0}}),h.error?_({result:h,stack:u}):{...C}}function G1({pairedPreviousDoubleExit:t,noContextTargetMatchUp:e}){return e.matchUpStatus===Nt?Nt:t?[be,Rt].includes(e?.matchUpStatus)?Rt:bt:Xt}function Lx(t){let e,{inContextDrawMatchUps:r,inContextMatchUp:n,drawDefinition:o}=t,i=t.targetData.targetLinks?.winnerTargetLink;if(i.target.feedProfile===dn){let s=n.sides?.find(({sideNumber:c})=>c===n.winningSide)?.participantId,a=r.find(c=>c.structureId===i.target.structureId&&c.roundNumber===i.target.roundNumber&&c.sides?.some(({participantId:u})=>u===s));if(a&&a.matchUpStatus===Xt){let c=mr({matchUpId:a.matchUpId,inContextDrawMatchUps:r,drawDefinition:o});if(!vi({inContextDrawMatchUps:r,drawDefinition:o,targetData:c})){let{structure:p}=at({structureId:a.structureId,drawDefinition:o}),m=Ct({structure:p}).positionAssignments;for(let d of m||[])if(d.participantId===s){if(d.participantId=void 0,p?.positionAssignments)p.positionAssignments=m;else if(p?.structures){let l=Object.assign({},...(m||[]).map(f=>({[f.drawPosition]:f.participantId})));for(let f of p?.structures||[])f.positionAssignments?.forEach(g=>g.participantId=l[g.drawPosition])}Oo({tournamentId:t.tournamentRecord?.tournamentId,event:t.event,drawDefinition:o,structure:p}),e=!0}}}}return{qualifierRemoved:e}}function kx(t){let{matchUp:e,matchUpStatus:r,score:n,winningSide:o}=t,i="noDownStreamDependencies";if([Te,be].includes(e?.matchUpStatus)&&![Te,be].includes(r)){let I=mM(t);if(I.error)return _({result:I,stack:i})}let a=r===Te,c=Ie({score:n})&&!a&&(t.isCollectionMatchUp&&!t.projectedWinningSide||!o),u=t?.inContextMatchUp?.collectionId&&Nx(t.inContextMatchUp),p=t.removeScore||!u&&![un,vr].includes(r||un),m=t.isCollectionMatchUp&&t.dualMatchUp.winningSide&&!t.projectedWinningSide||e.winningSide&&!o&&!Ie({score:n}),d=r&&r!==Xt,l=I=>{let h,{structure:S,drawDefinition:T,dualMatchUp:y,disableAutoCalc:E}=t;if(y?._disableAutoCalc&&E!==!1)return bd({...t,removeWinningSide:m});let{connectedStructureIds:P}=By({drawDefinition:T,structure:S,matchUp:e});P.length&&(console.log({connectedStructureIds:P}),h=!0),Object.assign(t,{removeScore:I});let A=_c(t);if(A.error)return A;if(t.removingQualifier&&t.appliedPolicies?.[nu]?.autoRemoveQualifiers){let U=Lx(t);return{...C,connectedStructures:h,...U}}return{...C,connectedStructures:h}};if(m&&o&&t.isCollectionMatchUp)return Fx(t);let f=[co,vr].includes(r)&&t.dualWinningSideChange,g=(o||f)&&xx(t)||c&&l(p)||d&&bx(t)||m&&l(p)||e&&Fx({...t,removeScore:!0})||{...C};return _({result:g,stack:i})}function Fx(t){let e="ndd:scoreModification";if(t.isCollectionMatchUp&&t.dualMatchUp?.winningSide&&!t.projectedWinningSide&&!t.autoCalcDisabled){let o=_c(t);if(o.error)return o}let n=Hn({...t,context:e});if(t.isCollectionMatchUp){let{matchUpTieId:o,drawDefinition:i,event:s,matchUpsMap:a}=t,{removeWinningSide:c}=lo({tournamentRecord:t.tournamentRecord,appliedPolicies:t.appliedPolicies,matchUpId:o,drawDefinition:i,matchUpsMap:a,event:s});c&&console.log("REMOVE WINNING SIDE")}return _({result:n,stack:e})}function uI(t){let e=et(t,[{[ne]:!0,[Ce]:!0,[ln]:!0},{homeParticipantId:!0,[fn]:ie}]);if(e.error)return e;let r=Ns(t,[{[ss]:Ln,attr:{[ru]:!0}}]);if(r.error)return r;let n=r?.matchUp?.matchUp?.sides?.map(m=>m?.participantId);if(t.homeParticipantId&&!n?.includes(t.homeParticipantId))return{error:mn};let{disableNotice:o,homeParticipantId:i,removePriorValues:s,tournamentRecord:a,drawDefinition:c,matchUpId:u}=t;return Jr({duplicateValues:!1,removePriorValues:s,tournamentRecord:a,drawDefinition:c,disableNotice:o,matchUpId:u,timeItem:{itemType:pd,itemValue:i}})}function dM({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Yo({timeItems:r?.timeItems||[],itemType:Pp});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{timeModifiers:n}:e}function Jo(t){let e="addMatchUpScheduledTime",r=t.matchUp,{removePriorValues:n,tournamentRecord:o,drawDefinition:i,disableNotice:s,scheduledTime:a,matchUpId:c}=t;if(!c)return _({result:{error:cr},stack:e});if(!Yc(a))return _({result:{error:Po},stack:e});if(!r){let I=Bt({drawDefinition:i,matchUpId:c});if(I.error)return _({result:I,stack:e});r=I.matchUp}let u=Pt(a),p=Ws({matchUp:r}).scheduledDate,m=u&&!p;if((dM({matchUp:r}).timeModifiers||[])?.length){let I=lM({disableNotice:!0,removePriorValues:n,tournamentRecord:o,timeModifiers:[],drawDefinition:i,matchUpId:c,matchUp:r});if(I?.error)return _({result:I,stack:e})}let f=Za(a,!0,m);return Jr({duplicateValues:!1,removePriorValues:n,tournamentRecord:o,drawDefinition:i,disableNotice:s,matchUpId:c,timeItem:{itemType:qi,itemValue:f}})}function lM({removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,timeModifiers:o,matchUpId:i,matchUp:s}){let a="addMatchUpTimeModifiers";if(!i)return _({result:{error:cr},stack:a});if(o!==void 0&&!Array.isArray(o))return _({info:ai("timeModifiers"),result:{error:V},stack:a});if(!s){let l=Bt({drawDefinition:r,matchUpId:i});if(l.error)return _({result:l,stack:a});s=l.matchUp}let c=dM({matchUp:s}).timeModifiers||[],u=o.filter(l=>!c.includes(l));if(o.length&&!u.length)return{...C};if(u.some(l=>mS.includes(l))){c=c.filter(f=>!mS.includes(f));let l=Jo({disableNotice:!0,removePriorValues:t,scheduledTime:"",tournamentRecord:e,drawDefinition:r,matchUpId:i});if(l.error)return _({result:l,stack:a})}let m=o?.length?[...u,...c]:void 0;return Jr({duplicateValues:!1,removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,matchUpId:i,timeItem:{itemType:Pp,itemValue:m}})}function sm({scheduledDate:t,removePriorValues:e,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:i}){if(!i)return{error:cr};let s=t&&No.test(t);if(t&&!s)return{error:je};let c={itemValue:Pt(t),itemType:Yi};return Jr({duplicateValues:!1,removePriorValues:e,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:i,timeItem:c})}function am({removePriorValues:t,tournamentRecords:e,tournamentRecord:r,drawDefinition:n,disableNotice:o,courtDayDate:i,matchUpId:s,courtIds:a}){if(!r&&!e)return{error:$};if(!s)return{error:cr};let c=Bt({drawDefinition:n,matchUpId:s});if(c.error)return c;if(c?.matchUp?.matchUpType!==xr)return{error:lr};if(!(a===void 0||Array.isArray(a)&&a.length&&a.every(d=>typeof d=="string")))return{error:V,context:{courtIds:a}};let p;if(a){let d=e||r&&{[r.tournamentId]:r},l=Uo({tournamentRecords:d});if(l.error)return l;let f=l.courts?.filter(g=>a.includes(g.courtId));if(f?.length!==a.length)return{error:V,context:{courtIds:a}};p=f?.map(g=>({venueId:g.venueId,courtId:g.courtId}))}return Jr({duplicateValues:!1,removePriorValues:t,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:s,timeItem:{itemType:po,itemDate:i,itemValue:p}})}function sa({removePriorValues:t,tournamentRecords:e,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:i,venueId:s}){if(!r)return{error:$};if(!i)return{error:cr};if(s){let c=qo({tournamentRecords:e,tournamentRecord:r,venueId:s});if(c.error)return c}return Jr({duplicateValues:!1,removePriorValues:t,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:i,timeItem:{itemType:ji,itemValue:s}})}function Zi({removePriorValues:t,tournamentRecords:e,tournamentRecord:r,drawDefinition:n,disableNotice:o,courtDayDate:i,matchUpId:s,courtId:a}){if(!r&&!e)return{error:$};if(!s)return{error:cr};if(a){let u=ms({tournamentRecords:e,tournamentRecord:r,courtId:a});if(u.error)return u;let p=u.venue?.venueId;sa({tournamentRecords:e,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:s,venueId:p})}return Jr({duplicateValues:!1,removePriorValues:t,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:s,timeItem:{itemType:jo,itemDate:i,itemValue:a}})}function Rs(t,e){let r=JI.test(t)?t:Qt(t),n=Pt(t)||Pt(e)||Yn(new Date);return new Date(`${n}T${r}`).getTime()}function cm(t){let e="addMatchUpScheduleItems",r=et(t,[{drawDefinition:!0,matchUpId:!0},{schedule:!0,[He]:Kr}],e);if(r.error)return r;let{matchUpDependencies:n,inContextMatchUps:o}=t,{errorOnAnachronism:i=!1,checkChronology:s=!0,removePriorValues:a,tournamentRecords:c,tournamentRecord:u,drawDefinition:p,disableNotice:m,drawMatchUps:d,matchUpId:l,schedule:f,event:g}=t,I,h;if(d)I=d.find(O=>O.matchUpId===l);else{let O=Bt({drawDefinition:p,event:g,matchUpId:l});if(O.error)return O;I=O.matchUp}let{endTime:S,courtId:T,courtIds:y,courtOrder:E,resumeTime:P,homeParticipantId:A,scheduledDate:U,scheduledTime:N,startTime:D,stopTime:M,timeModifiers:R,venueId:b}=f;s&&(!n||!o)&&({matchUpDependencies:n,matchUps:o}=on({drawDefinition:p}));let v=n?.[l]?.matchUpIds;if(f.scheduledDate&&s&&v){let O=o?.filter(x=>(x.schedule?.scheduledDate||Pt(x.schedule?.scheduledTime))&&v.includes(x.matchUpId)).map(({schedule:x})=>{let F=_m(x);return new Date(F).getTime()});if(O?.length){let x=_m(f),F=new Date(x).getTime();if(Math.max(...O)>=F){if(i)return _({result:{error:wI},stack:e});h=wI}}}if(U!==void 0){let O=sm({disableNotice:!0,removePriorValues:a,tournamentRecord:u,drawDefinition:p,scheduledDate:U,matchUpId:l});if(O?.error)return _({result:O,stack:e,context:{scheduledDate:U}})}if(N!==void 0){let O=Jo({disableNotice:!0,removePriorValues:a,tournamentRecord:u,drawDefinition:p,scheduledTime:N,matchUpId:l,matchUp:I});if(O?.error)return _({result:O,stack:e,context:{scheduledTime:N}})}if(D!==void 0){let O=jy({disableNotice:!0,removePriorValues:a,tournamentRecord:u,drawDefinition:p,matchUpId:l,startTime:D,event:g});if(O?.error)return _({result:O,stack:e,context:{startTime:D}})}if(M!==void 0){let O=qy({disableNotice:!0,removePriorValues:a,tournamentRecord:u,drawDefinition:p,matchUpId:l,stopTime:M,event:g});if(O?.error)return _({result:O,stack:e,context:{stopTime:M}})}if(P!==void 0){let O=$y({disableNotice:!0,removePriorValues:a,tournamentRecord:u,drawDefinition:p,resumeTime:P,matchUpId:l,event:g});if(O?.error)return _({result:O,stack:e,context:{resumeTime:P}})}if(S!==void 0){let O=Yy({disableNotice:!0,removePriorValues:a,tournamentRecord:u,drawDefinition:p,matchUpId:l,endTime:S,event:g});if(O?.error)return _({result:O,stack:e,context:{endTime:S}})}if(y!==void 0){let O=am({disableNotice:!0,removePriorValues:a,tournamentRecord:u,drawDefinition:p,matchUpId:l,courtIds:y});if(O?.error)return _({result:O,stack:e,context:{courtIds:y}})}if(T!==void 0&&U!==void 0){let O=Zi({courtDayDate:U,disableNotice:!0,removePriorValues:a,tournamentRecords:c,tournamentRecord:u,drawDefinition:p,matchUpId:l,courtId:T});if(O?.error)return _({result:O,stack:e,context:{courtId:T}})}if(b!==void 0){let O=sa({disableNotice:!0,removePriorValues:a,tournamentRecords:c,tournamentRecord:u,drawDefinition:p,matchUpId:l,venueId:b});if(O?.error)return _({result:O,stack:e,context:{venueId:b}})}if(E!==void 0&&It(E)){let O=Wy({disableNotice:!0,removePriorValues:a,tournamentRecord:u,drawDefinition:p,courtOrder:E,matchUpId:l});if(O?.error)return _({result:O,stack:e,context:{courtOrder:E}})}if(R!==void 0){let O=lM({disableNotice:!0,removePriorValues:a,tournamentRecord:u,drawDefinition:p,timeModifiers:R,matchUpId:l,matchUp:I});if(O?.error)return _({result:O,stack:e,context:{timeModifiers:R}})}return Vt(A)&&uI({disableNotice:!0,homeParticipantId:A,removePriorValues:a,tournamentRecord:u,drawDefinition:p,matchUpId:l}),m||gt({tournamentId:u?.tournamentId,eventId:g?.eventId,context:e,drawDefinition:p,matchUp:I}),h?{...C,warnings:[h]}:{...C}}function Wy({removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,courtOrder:o,matchUpId:i}){if(!i)return{error:cr};if(o&&!It(o))return{error:V,info:"courtOrder must be numeric"};let s=o&&dt(o);return Jr({duplicateValues:!1,removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,matchUpId:i,timeItem:{itemType:Up,itemValue:s}})}function fM({removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,participantId:o,officialType:i,matchUpId:s}){if(!s)return{error:cr};if(!o)return{error:ie};if(e){let c=Gt({tournamentRecord:e,participantFilters:{participantTypes:[At],participantRoles:[dg]}}).participants??[];if(!Bo({tournamentParticipants:c,participantId:o}))return{error:re}}let a={itemType:"SCHEDULE.ASSIGNMENT.OFFICIAL",itemValue:o};return i&&(a.itemSubTypes=[i]),Jr({duplicateValues:!1,removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,matchUpId:s,timeItem:a})}function jy({removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,matchUpId:o,startTime:i,event:s}){if(!o)return{error:cr};if(!Yc(i))return{error:Po};let{matchUp:a}=Bt({drawDefinition:r,event:s,matchUpId:o}),{scheduledDate:c}=Ws({matchUp:a}),p=(a?.timeItems??[]).filter(m=>[$i,Di,Ni].includes(m?.itemType)).map(m=>Rs(m.itemValue,c)).reduce((m,d)=>!m||d<m?d:m,void 0);if(!p||Rs(i,c)<p){a?.timeItems&&(a.timeItems=a.timeItems.filter(l=>l.itemType!==xo));let m=Za(i,!0,!0);return Jr({duplicateValues:!1,removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,matchUpId:o,timeItem:{itemType:xo,itemValue:m}})}else return{error:NE}}function Yy({validateTimeSeries:t=!0,removePriorValues:e,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:i,endTime:s,event:a}){if(!i)return{error:cr};if(!Yc(s))return{error:Po};let{matchUp:c}=Bt({drawDefinition:n,event:a,matchUpId:i}),{scheduledDate:u}=Ws({matchUp:c}),m=(c?.timeItems??[]).filter(d=>[xo,Di,$i].includes(d?.itemType)).map(d=>Rs(d.itemValue,u)).reduce((d,l)=>!d||l>d?l:d,void 0);if(!t||!m||Rs(s,u)>m){c?.timeItems&&(c.timeItems=c.timeItems.filter(f=>f.itemType!==Ni));let d=Za(s,!0,!0);return Jr({duplicateValues:!1,removePriorValues:e,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:i,timeItem:{itemType:Ni,itemValue:d}})}else return{error:PE}}function qy({removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,matchUpId:o,stopTime:i,event:s}){if(!o)return{error:cr};if(!Yc(i))return{error:Po};let{matchUp:a}=Bt({drawDefinition:r,event:s,matchUpId:o}),{scheduledDate:c}=Ws({matchUp:a}),u=a?.timeItems??[];if(u.reduce((g,I)=>I.itemType===Ni||g,void 0))return{error:$I};let m=u.filter(g=>[xo,Di,$i].includes(g?.itemType)).sort((g,I)=>Rs(g.itemValue,c)-Rs(I.itemValue,c)),d=m[m.length-1],l=d&&d.itemType===$i,f=m.filter(g=>!l||g.createdAt!==d.createdAt).map(g=>Rs(g.itemValue,c)).reduce((g,I)=>!g||I>g?I:g,void 0);if(Rs(i,c)>f){if(a?.timeItems&&l){let h=d.createdAt;a.timeItems=a.timeItems.filter(S=>S.createdAt!==h)}let I={itemValue:Za(i,!0,!0),itemType:$i};return Jr({duplicateValues:!0,removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,matchUpId:o,timeItem:I})}else return{error:DE}}function $y({removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,resumeTime:o,matchUpId:i,event:s}){if(!i)return{error:cr};if(!Yc(o))return{error:Po};let{matchUp:a}=Bt({drawDefinition:r,event:s,matchUpId:i}),{scheduledDate:c}=Ws({matchUp:a}),u=a?.timeItems??[];if(u.reduce((g,I)=>I.itemType===Ni||g,void 0))return{error:$I};let m=u.filter(g=>[xo,Di,$i].includes(g?.itemType)).sort((g,I)=>Rs(g.itemValue,c)-Rs(I.itemValue,c)),d=m[m.length-1],l=d&&d.itemType===Di,f=m.filter(g=>!l||g.createdAt!==d.createdAt).map(g=>Rs(g.itemValue,c)).reduce((g,I)=>!g||I>g?I:g,void 0);if(Rs(o,c)>f){if(a?.timeItems&&l){let h=d.createdAt;a.timeItems=a.timeItems.filter(S=>S.createdAt!==h)}let I={itemValue:Za(o,!0,!0),itemType:Di};return Jr({duplicateValues:!0,removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,matchUpId:i,timeItem:I})}else return{error:RC}}function Gx({drawDefinition:t,matchUpStatus:e,matchUpsMap:r,winningSide:n,dualMatchUp:o,tieFormat:i,structure:s,matchUp:a,event:c,score:u}){let p=J(o,void 0,!0);for(let d of p?.tieMatchUps||[])d.matchUpId===a.matchUpId&&(d.winningSide=n,d.score=u,!Ie({score:u})&&!e?Object.assign(d,{...Ou}):e&&(d.matchUpStatus=e));i=i??We({matchUp:a,structure:s,drawDefinition:t,event:c})?.tieFormat;let{winningSide:m}=Dc({matchUp:p,drawDefinition:t,matchUpsMap:r,structure:s,tieFormat:i,event:c});return{projectedWinningSide:m}}function Vx(t){let{tournamentRecord:e,inContextMatchUp:r,structure:n,drawDefinition:o}=t,i=r.roundNumber,s=r.sides.find(P=>P.sideNumber===r.winningSide),a=r.sides.find(P=>P.sideNumber!==r.winningSide),{drawPosition:c,participantId:u}=s,{drawPosition:p,participantId:m}=a,d="swapWinnerLoser",{matchUps:l}=yt(t),f=l.filter(({drawPositions:P,roundNumber:A})=>P?.includes(c)&&A>i);Pr({changeWinner:!0})&&console.log({existingWinnerSubsequentMatchUps:f}),f.forEach(P=>{P.drawPositions=P.drawPositions?.map(A=>A===c?p:A)||[],gt({tournamentId:e?.tournamentId,eventId:t.event?.eventId,context:d,drawDefinition:o,matchUp:P})});let{stage:g,stageSequence:I}=n,h=o.structures.filter(({stage:P,stageSequence:A})=>P===g&&A>I).map(({structureId:P})=>P),{targetLinks:{loserTargetLink:S,winnerTargetLink:T}}=t.targetData,y=[S?.target.structureId,T?.target?.structureId].filter(Boolean);return o.structures.filter(({stage:P,structureId:A})=>P!==g&&y.includes(A)).forEach(({stage:P,stageSequence:A,structureId:U})=>{h.includes(U)||h.push(U),o.structures.filter(({stage:N,stageSequence:D})=>N===P&&D>A).forEach(({structureId:N})=>{h.includes(N)||h.push(N)})}),o.structures.filter(({structureId:P})=>h.includes(P)).forEach(P=>{let{positionAssignments:A}=Ct({structure:P}),U=A?.find(({participantId:D})=>D===u),N=A?.find(({participantId:D})=>D===m);U&&(U.participantId=m),N&&(N.participantId=u)}),Hn({...t,context:d})}function Fa(t){let e="setMatchUpStatus";t.matchUpStatus&&[bt,Te].includes(t.matchUpStatus)&&(t.score=void 0);let{allowChangePropagation:r,disableScoreValidation:n,tournamentRecords:o,tournamentRecord:i,disableAutoCalc:s,enableAutoCalc:a,drawDefinition:c,matchUpStatus:u,winningSide:p,matchUpId:m,event:d,score:l}=t;if(!c)return{error:Z};if(u&&[co,un,vr,Xt].includes(u)&&p)return{error:V,winningSide:p,matchUpStatus:u};if(![void 0,...Bh].includes(u))return _({result:{error:da},info:"matchUpStatus does not exist",stack:"setMatchUpStatus"});let f=Me({drawDefinition:c}),{matchUps:g}=ce({nextMatchUps:!0,tournamentRecord:i,inContext:!0,drawDefinition:c,matchUpsMap:f,event:d}),I=f.drawMatchUps.find(k=>k.matchUpId===m),h=g?.find(k=>k.matchUpId===m);if(!I||!g)return{error:Le};if((I.winningSide||p)&&u===Nt)return{context:"Cannot have Bye with winningSide",error:Yl,matchUpStatus:u};let S=h?.structureId,{structure:T}=at({drawDefinition:c,structureId:S}),y=de(Wt)(I.matchUpType),E=h?.drawPositions?.filter(Boolean),P=h?.matchUpTieId,A=mr({matchUpId:P||m,inContextDrawMatchUps:g,drawDefinition:c});Object.assign(t,{inContextDrawMatchUps:g,inContextMatchUp:h,matchUpTieId:P,matchUpsMap:f,targetData:A,structure:T,matchUp:I});let U=vi(t),N;if(y){if(s)Ut({extension:{name:ha,value:!0},element:I});else if(a){let k=I.winningSide,{winningSide:H,scoreStringSide1:W,scoreStringSide2:q,set:Y}=Dc({drawDefinition:c,matchUpsMap:f,structure:T,matchUp:I,event:d}),B={scoreStringSide1:W,scoreStringSide2:q,sets:Y?[Y]:[]};if(N=H!==k,U&&N)return _({stack:"winningSideWithDownstreamDependencies",result:{error:Nm},context:{winningSide:p,matchUp:I}});gr({name:ha,element:I}),Object.assign(t,{winningSide:H,dualWinningSideChange:N,projectedWinningSide:H,score:B})}va({tournamentId:i?.tournamentId,inContextDualMatchUp:h,eventId:d?.eventId,dualMatchUp:I,drawDefinition:c})}if(y&&u&&[ac].includes(u))return{info:"Not supported for matchUpType: TEAM",error:V};if(l&&!y&&!n){let k=I.matchUpFormat??T?.matchUpFormat??c?.matchUpFormat??d?.matchUpFormat,H=Yg({existingMatchUpStatus:I.matchUpStatus,matchUpFormat:k,matchUpStatus:u,winningSide:p,score:l});if(H.error)return H}let D=Tt({policyTypes:[nu,tn],tournamentRecord:i,drawDefinition:c,event:d})?.appliedPolicies??{};ht(t.policyDefinitions)&&Object.assign(D,t.policyDefinitions);let M=B1({assignedDrawPositions:E,inContextMatchUp:h,appliedPolicies:D,drawDefinition:c,matchUpStatus:u,structure:T,matchUp:I});if(M?.error)return M;let R=h?.stage===ct&&h.finishingRound===1,b=R&&p,v=R&&I.winningSide&&!p&&(!t.matchUpStatus||t.matchUpStatus&&ug({matchUpStatus:t.matchUpStatus}))&&(!t.outcome||!Ie({outcome:t.outcome})),O=b&&p!==I.winningSide&&I.winningSide;if(Object.assign(t,{qualifierAdvancing:b,qualifierChanging:O,removingQualifier:v,appliedPolicies:D}),P){let{matchUp:k}=Bt({matchUpId:P,inContext:!0,drawDefinition:c,matchUpsMap:f,event:d});if(k){let H=We({matchUp:k,drawDefinition:c,structure:T,event:d})?.tieFormat,{projectedWinningSide:W}=Gx({drawDefinition:c,matchUpStatus:u,dualMatchUp:k,matchUpsMap:f,winningSide:p,tieFormat:H,structure:T,matchUp:I,event:d,score:l}),q=k.winningSide;N=W!==q;let Y=k._disableAutoCalc;Object.assign(t,{isCollectionMatchUp:!0,dualWinningSideChange:N,projectedWinningSide:W,autoCalcDisabled:Y,matchUpTieId:P,dualMatchUp:k,tieFormat:H})}}let x=Da({matchUpStatus:u});if(!P){if(U&&!p&&(u&&ug({matchUpStatus:u})||u&&[Te,be].includes(u)))return{error:Yl,activeDownstream:U,winningSide:p};if(p&&p===I.winningSide&&u&&!x)return{context:"winningSide must include directing matchUpStatus",error:Yl,directingMatchUpStatus:x,matchUpStatus:u}}let{schedule:F}=t;if(F){let k=cm({disableNotice:!0,tournamentRecords:o,tournamentRecord:i,drawDefinition:c,matchUpId:m,schedule:F});if(k.error)return k}let w=!y&&!N&&p&&I.winningSide&&I.winningSide!==p;if(r&&w&&I.roundPosition)return Vx(t);let L=p&&!P||t.projectedWinningSide;Cn({activeDownstream:U,matchUpWinner:L,method:e,winningSide:p});let G=!U&&kx(t)||L&&V1(t)||(x||t.autoCalcDisabled)&&Bx(t)||{error:xE};return _({result:G,stack:e})}function V1(t){let{matchUp:e,winningSide:r,matchUpTieId:n,dualWinningSideChange:o}=t;return r===e.winningSide||n&&!o?Bx(t):_({stack:"winningSideWithDownstreamDependencies",result:{error:Nm},context:{winningSide:r,matchUp:e}})}function Bx(t){let{tournamentRecord:e,matchUp:r,event:n}=t,o=t.isCollectionMatchUp&&r.winningSide&&!t.winningSide&&!Ie({score:t.score}),i=t.isCollectionMatchUp?t.matchUpStatus||o&&Xt||t.winningSide&&he||un:t.matchUpStatus||he,s=t.removeScore||[co,bt].includes(i)&&![un,vr].includes(i),a=Hn({...t,matchUpStatus:i,removeWinningSide:o,context:"sms",removeScore:s});if(a.error)return a;if(t.isCollectionMatchUp){let{matchUpTieId:c,drawDefinition:u,matchUpsMap:p}=t,m=lo({appliedPolicies:t.appliedPolicies,matchUpId:c,tournamentRecord:e,drawDefinition:u,matchUpsMap:p,event:n});if(m.error)return m;Object.assign(a,{tieMatchUpResult:m})}return a}function B1({assignedDrawPositions:t,inContextMatchUp:e,appliedPolicies:r,drawDefinition:n,matchUpStatus:o,structure:i,matchUp:s}){if(r?.[tn]?.requireParticipantsForScoring===!1)return{...C};let a=e?.sides?.map(p=>p.participantId).filter(Boolean).length,c=s?.sides?[]:Ct({structureId:i?.structureId,drawDefinition:n}).positionAssignments,u=a&&a===2||s.collectionId&&pr({structure:i})&&a&&a>=1||t?.length===2&&c?.filter(p=>t.includes(p.drawPosition)).every(p=>p.participantId);return o&&Vh.includes(o)&&!u?_({info:"matchUpStatus requires assigned participants",context:{matchUpStatus:o,requiredParticipants:u},result:{error:da}}):{...C}}function gM({tournamentRecord:t,drawDefinition:e,matchUpId:r,event:n}){if(!e)return{error:Z};let{matchUp:o}=Bt({drawDefinition:e,matchUpId:r,event:n});return o?.matchUpType!==xr?{error:lr}:Fa({enableAutoCalc:!0,tournamentRecord:t,drawDefinition:e,matchUpId:r,event:n})}function IM({drawDefinition:t,event:e,matchUpId:r}){if(!t)return{error:Z};if(!r)return{error:cr};let{matchUp:n}=Bt({drawDefinition:t,event:e,matchUpId:r});return n?gr({name:jm,element:n}):{error:Le}}function Hx({substituteParticipantId:t,existingParticipantId:e,tournamentRecord:r,drawDefinition:n,sideNumber:o,matchUpId:i,event:s}){let a="substituteParticipant";if(!n)return{error:Z};if(!i)return{error:cr};if(!e||!t)return _({result:{error:ie},stack:a});let{matchUp:c}=Bt({drawDefinition:n,matchUpId:i,event:s});if(!c)return{error:Le};if(!c.collectionId)return _({result:{error:lr},stack:a});let u=Me({drawDefinition:n}),{matchUps:p}=ce({tournamentParticipants:r?.participants,inContext:!0,drawDefinition:n,matchUpsMap:u}),m=p?.find(g=>g.matchUpId===i),l=p?.find(g=>g.matchUpId===m?.matchUpTieId)?.sides?.find(g=>g.participant.individualParticipants.some(({participantId:I})=>I===e));return!l||o&&l.sideNumber!==o?{error:mn}:l.participant?.individualParticipants?.map(St).filter(g=>g!==e)?.includes(t)?aI({newParticipantId:t,tieMatchUpId:i,existingParticipantId:e,substitution:!0,tournamentRecord:r,drawDefinition:n,event:s}):_({result:{error:mn},stack:a})}function hM(t){return Hx(t)}function SM({drawDefinition:t,matchUpId:e,event:r}){if(!t)return{error:Z};let{matchUp:n}=Bt({drawDefinition:t,matchUpId:e,event:r});return Ut({extension:{name:ha,value:!0},element:n})}function TM(t){let e="setMatchUpFormat",r=et(t,[{tournamentRecord:!0},{[er]:E=>Dr({matchUpFormat:E}),[Fr]:$a,matchUpFormat:!0}]);if(r.error)return _({result:r,stack:e});let{tournamentRecord:n,drawDefinition:o,scheduledDates:i,stageSequences:s,matchUpFormat:a,structureId:c,eventType:u,matchUpId:p,eventId:m,stages:d,drawId:l,event:f,force:g}=t;if(i&&!Array.isArray(i))return _({result:{error:V,scheduledDates:i},stack:e});if(u&&!kc([$n,qr],u))return _({result:{error:jn},stack:e});let I=0,h=t.structureIds||c&&[c].filter(Boolean)||[],S=t.eventIds||m&&[m].filter(Boolean)||[],T=t.drawIds||l&&[l].filter(Boolean)||[];if((c||h?.length)&&!o)return _({result:{error:Z},stack:e});if(l&&p&&o){let E=zd({tournamentRecord:n,drawDefinition:o,matchUpFormat:a,structureIds:h,structureId:c,matchUpId:p});if(E.error)return E;I+=1}let y=E=>{let P=[];for(let A of E.structures||[]){if(Array.isArray(d)&&!d.includes(A.stage)||Array.isArray(s)&&!s.includes(A.stageSequence)||h?.length&&!h.includes(A.structureId))continue;h?.length&&A.matchUpFormat!==a&&(A.matchUpFormat=a,P.push(A.structureId),I+=1);let U=((g||i)&&yt({matchUpFilters:{matchUpStatuses:[Xt]},structure:A}).matchUps)??[],N=(i&&yt({matchUpFilters:{matchUpStatuses:[Xt]},contextFilters:{scheduledDates:i},afterRecoveryTimes:!1,inContext:!0,structure:A}).matchUps)??[];if(U?.length){let D=N?N.map(Ue):U.map(Ue);for(let M of U)D.includes(M.matchUpId)&&(M.matchUpFormat=i?.length?a:void 0,gt({tournamentId:n?.tournamentId,eventId:f?.eventId,context:e,drawDefinition:E,matchUp:M}))}}return!P.length&&E.matchUpFormat!==a&&(E.matchUpFormat=a,I+=1),P};for(let E of n?.events||[])if(!(S?.length&&!S.includes(E.eventId)||u&&u!==E.eventType||u===_e))if(Array.isArray(s)||Array.isArray(d)||h?.length||T?.length)for(let P of E.drawDefinitions||[]){if(Array.isArray(T)&&!T.includes(P.drawId))continue;let A=y(P);vt({structureIds:A,drawDefinition:P})}else E.matchUpFormat!==a&&(E.matchUpFormat=a,I+=1);return I?{...C,modificationsCount:I}:{...C,info:xs}}function pI({inheritance:t=!0,tournamentRecord:e,drawDefinition:r,matchUpId:n,event:o}){if(!r)return{error:Z};let i=Bt({drawDefinition:r,matchUpId:n})?.matchUp;if(!i?.tieMatchUps)return{error:lr};let s=Bt({inContext:!0,drawDefinition:r,matchUpId:n,event:o})?.matchUp,a=0;return(i?.sides||[]).forEach(c=>{c.lineUp&&delete c.lineUp}),(s?.sides||[]).forEach(c=>{if(a+=1,t===!1){let u=s?.tieFormat,p=c.participantId;u&&p&&Qi({drawDefinition:r,participantId:p,lineUp:[],tieFormat:u})}gt({tournamentId:e?.tournamentId,context:"resetMatchUpLineUps",eventId:o?.eventId,drawDefinition:r,matchUp:i})}),{...C,modificationsCount:a}}function Ky(t){let{matchUpFormat:e,matchUpStatus:r,winningSide:n,score:o,setTBlast:i}=t;if(!o)return{sets:[]};let s=o.sets||[],a=$o({winnerFirst:!1,matchUpFormat:e,matchUpStatus:r,setTBlast:i,sets:s}),c=$o({winnerFirst:!1,reversed:!0,matchUpFormat:e,matchUpStatus:r,setTBlast:i,sets:s}),u=$o({matchUpFormat:e,matchUpStatus:r,winningSide:n,setTBlast:i,sets:s}),p=a===u?c:a;return n&&(a=n===1?u:p,c=n===2?u:p),{score:{sets:s,scoreStringSide1:a,scoreStringSide2:c}}}function Wu(t){let e=et(t,[{[ln]:!0,[Ce]:!0}]);if(e.error)return e;let r=Mr(t);if(!t.drawDefinition){let S=t.tournamentRecord??(t.tournamentId&&r[t.tournamentId]);t.tournamentRecord||(t.tournamentRecord=S);let T=ze({eventId:t.eventId,drawId:t.drawId,tournamentRecord:S});if(T.error)return T;T.drawDefinition&&(t.drawDefinition=T.drawDefinition),t.event=T.event}let{disableScoreValidation:n,policyDefinitions:o,tournamentRecord:i,disableAutoCalc:s,enableAutoCalc:a,drawDefinition:c,matchUpId:u,schedule:p,event:m,notes:d}=t,l=t.matchUpFormat||t.outcome?.matchUpFormat,{policy:f}=ni({policyType:tn,tournamentRecord:i,event:m}),g=t.allowChangePropagation!==void 0&&t.allowChangePropagation||f?.allowChangePropagation!==void 0&&f.allowChangePropagation||void 0,{outcome:I,setTBlast:h}=t;if(I?.winningSide&&![1,2].includes(I.winningSide))return{error:Dm};if(l){let S=zd({tournamentRecord:i,drawDefinition:c,matchUpFormat:l,matchUpId:u,event:m});if(S.error)return S}if(I?.score?.sets&&!I.score.scoreStringSide1){let{score:S}=Ky({...I,setTBlast:h});I.score=S,I.score.sets=I.score.sets.filter(T=>T.side1Score||T.side2Score||T.side1TiebreakScore||T.side2TiebreakScore)}return Fa({matchUpStatusCodes:I?.matchUpStatusCodes,matchUpStatus:I?.matchUpStatus,winningSide:I?.winningSide,allowChangePropagation:g,disableScoreValidation:n,score:I?.score,tournamentRecords:r,policyDefinitions:o,tournamentRecord:i,disableAutoCalc:s,enableAutoCalc:a,drawDefinition:c,matchUpFormat:l,matchUpId:u,schedule:p,event:m,notes:d})}function yM(t){if(!t?.outcomes)return{error:st};if(!Array.isArray(t.outcomes))return{error:st,info:{outcomes:t.outcomes}};let e=t.tournamentRecords||t.tournamentRecord&&{[t.tournamentRecord.tournamentId]:t.tournamentRecord}||{},r=t.outcomes??[],n=r.reduce((o,i)=>o.includes(i.tournamentId)?o:o.concat(i.tournamentId),[]);for(let o of n){let i=e[o];if(!i)return{error:$};let s=r.filter(a=>a.tournamentId===o);if(s.length){let a=H1({outcomes:s,tournamentRecord:i});if(a.error)return a}}return{...C}}function H1(t){let{tournamentRecords:e,tournamentRecord:r,outcomes:n,policyDefinitions:o}=t,i={};n.forEach(s=>{let{eventId:a}=s;i[a]||(i[a]=[]),i[a].push(s)});for(let s of Object.keys(i)){let{event:a}=ze({tournamentRecord:r,eventId:s});for(let c of i[s]){let{drawId:u}=c,p=a?.drawDefinitions?.find(m=>m.drawId===u);if(p&&u){let{matchUpFormat:m,matchUpId:d}=c,l=Wu({schedule:c?.schedule,tournamentRecords:e,policyDefinitions:o,tournamentRecord:r,drawDefinition:p,matchUpFormat:m,matchUpId:d,outcome:c,drawId:u,event:a});if(l.error)return l}}}return{...C}}function Wx({drawDefinition:t,matchUpId:e,outcome:r,matchUp:n}){if(!n&&!t)return{error:Z};if(!r)return{error:st,info:"missing outcome"};if(!n&&!e)return{error:Tr};if(!n){let i=Bt({drawDefinition:t,matchUpId:e});if(i.error)return i;n=i.matchUp}return typeof r!="object"||!r.score?.scoreStringSide1||!r.score?.scoreStringSide2?{error:V}:Ut({element:n,extension:{name:jm,value:r}})}function AM(t){return Wx(t)}function mI(t){let e="resetTieFormat",{drawDefinition:r,event:n,uuids:o}=t,i=et(t,[{[ne]:!0,[ln]:!0}],e);if(i.error)return i;let s=Ns(t,[{[ss]:Ln}]);if(s[fn])return s;let a=t.tournamentRecord?.tournamentId,{matchUp:c,structure:u}=s?.matchUp??{};if(!c?.tieMatchUps)return _({result:{error:lr},info:"Must be a TEAM matchUp",stack:e});if(!c.tieFormat)return{...C};let p=We({structure:u,drawDefinition:r,event:n})?.tieFormat;if(!p)return _({result:{error:ve},info:"No inherited tieFormat",stack:e});let m=[],d=[],l=[],f=[];for(let g of p.collectionDefinitions){let{matchUpCount:I,collectionId:h}=g;d.push(h);let S=(c.tieMatchUps||[]).filter(T=>T.collectionId===h);if(S.length>I)S.sort((T,y)=>(T.matchUpStatus===Xt?1:0)-(y.matchUpStatus===Xt?1:0)),l.push(...S.slice(0,I)),m.push(...S.slice(3).map(Ue));else if(l.push(...S),S.length<I){let T=I-S.length,y=Ru({collectionDefinition:g,matchUpsLimit:T,matchUp:c,uuids:o});f.push(...y)}}for(let g of c?.tieMatchUps||[])g.collectionId&&!d.includes(g.collectionId)&&m.push(g.matchUpId);return f.length&&(l.push(...f),vo({eventId:n?.eventId,matchUps:f,drawDefinition:r,tournamentId:a})),m.length&&Rn({matchUpIds:m,eventId:n?.eventId,drawDefinition:r,tournamentId:a}),c&&(c.tieMatchUps=l,c.tieFormatId=void 0,c.tieFormat=void 0,gt({structureId:u?.structureId,eventId:n?.eventId,context:e,drawDefinition:r,tournamentId:a,matchUp:c})),{...C,newMatchUps:f,deletedMatchUpIds:m}}function dI(t){let{tournamentRecord:e,drawDefinition:r,matchUpId:n,event:o}=t,i="resetScorecard";if(!r)return _({result:{error:Z},stack:i});if(!n)return _({result:{error:cr},stack:i});if(!Vt(n))return _({result:{error:V,matchUpId:n},stack:i});let s=Me({drawDefinition:r}),{matchUps:a}=ce({nextMatchUps:!0,inContext:!0,drawDefinition:r,matchUpsMap:s}),c=s.drawMatchUps.find(I=>I.matchUpId===n),u=a?.find(I=>I.matchUpId===n);if(!c||!a)return{error:Le};if(c.matchUpType!==br)return{error:lr};let p=mr({inContextDrawMatchUps:a,drawDefinition:r,matchUpId:n}),m=u?.structureId,{structure:d}=at({drawDefinition:r,structureId:m});if(Object.assign(t,{inContextDrawMatchUps:a,inContextMatchUp:u,matchUpsMap:s,targetData:p,structure:d,matchUp:c}),vi(t))return{error:Nm};if(c.tieMatchUps?.length)for(let I of c.tieMatchUps){let h=Fa({matchUpId:I.matchUpId,matchUpTieId:n,winningSide:void 0,removeScore:!0,tournamentRecord:e,drawDefinition:r,event:o});if(h.error)return _({result:h,stack:i})}let f=Tt({tournamentRecord:e,drawDefinition:r,event:o})?.appliedPolicies,g=lo({event:t.event,removeScore:!0,tournamentRecord:e,appliedPolicies:f,drawDefinition:r,matchUpsMap:s,matchUpId:n});if(g.error)return _({result:g,stack:i});if(t.tiebreakReset&&!g.tieFormatRemoved){let I=We({drawDefinition:r,structure:d,event:o})?.tieFormat;if(c.tieFormat&&I){let{matchUpCountDifference:h,descendantDifferences:S,ancestorDifferences:T,valueDifference:y}=Qo({descendant:c.tieFormat,ancestor:I});if(S.collectionIds.length===1&&!T.collectionIds.length&&!T.groupsCount&&h===1&&y===1){let E=mI({tournamentRecord:e,drawDefinition:r,matchUpId:n,event:o});if(E.error)return E}}}return{...C}}function EM(t){let e=et(t,[{[Ce]:!0,[so]:!0},{[Vs]:{[nc]:!1,roundNumbers:!1},[wh]:"At least one must be provided",[He]:Be}]);if(e.error)return e;let r=iT(t);if(r.error)return r;let{matchUpIds:n}=r,o=de(br)(t.event.eventType),{tournamentRecord:i,drawDefinition:s,event:a}=t;for(let c of n){if(o){let p=dI({tiebreakReset:!0,tournamentRecord:i,drawDefinition:s,matchUpId:c,event:a});if(p.error||t.removeAssignments&&pI({inheritance:!1,drawDefinition:s,matchUpId:c}).error)return p}let u=Fa({winningSide:void 0,removeScore:!0,tournamentRecord:i,drawDefinition:s,matchUpId:c,event:a});if(u.error)return u;if(t.removeAssignments){let p=cI({...t,matchUpId:c});if(p.error)return p}}return{...C}}function jx({tournamentRecord:t,drawDefinition:e,finishingOrder:r}){if(!e)return{error:Z};let n="setOrderOfFinish";if(!Array.isArray(r))return _({info:ai("finishingOrder"),result:{error:V},stack:n});let{completedMatchUps:o,matchUpsMap:i}=Ys({inContext:!0,drawDefinition:e}),s=o?.map(Ue)??[],a=r.map(Ue),{matchUpTypes:c,roundNumbers:u,structureIds:p,matchUpTieIds:m}=(o??[]).filter(({matchUpId:T})=>a.includes(T)).reduce((T,y)=>{let{matchUpTieId:E,matchUpType:P,roundNumber:A,structureId:U}=y;return T.matchUpTypes.includes(P)||T.matchUpTypes.push(P),T.roundNumbers.includes(A)||T.roundNumbers.push(A),T.structureIds.includes(U)||T.structureIds.push(U),T.matchUpTieIds.includes(E)||T.matchUpTieIds.push(E),T},{matchUpTypes:[],roundNumbers:[],structureIds:[],matchUpTieIds:[]});if(c.length>1||m.length>1||u.length>1||p.length>1)return _({info:"matchUpType, structureId and roundNumber must be equivalent",result:{error:V},stack:n});let d,l,f={},g=[],I=[];if(!r.every(({orderOfFinish:T,matchUpId:y})=>(g.push(y),T&&I.push(T),f[y]=T,d=s.includes(y),l=T===void 0||It(T)&&Math.floor(T)>0,d&&l)))return _({result:{error:d?V:da},info:!d&&"matchUps must be completed"||!l&&"orderOfFinish must be integer > 0 or undefined"||void 0,stack:n});let S=o?.filter(T=>T.structureId===p[0]&&T.roundNumber===u[0]&&T.matchUpType===c[0]&&T.matchUpTieId===m[0]&&!g.includes(T.matchUpId));for(let T of S??[]){let{orderOfFinish:y}=T||{};if(y){if(!It(y))return _({context:{orderOfFinish:y,matchUp:T},result:{error:V},stack:n});I.push(y)}}if(CI(I).length!==I.length||Math.max(...I)>I.length)return _({info:"Values not unique or greater than expected number of values",result:{error:V},stack:n});if(p.length){let T=yu({matchUpFilters:{matchUpIds:a},structureId:p[0],drawDefinition:e,matchUpsMap:i});if(T.error)return _({result:T,stack:n});T.completedMatchUps?.forEach(y=>{y.orderOfFinish=f[y.matchUpId],gt({tournamentId:t.tournamentId,context:"setOrderOfFinish",drawDefinition:e,matchUp:y})})}return{...C}}function UM(t){return jx(t)}function PM(t){let{tournamentRecord:e,drawDefinition:r,matchUpId:n,lineUps:o,event:i}=t,s="applyLineUps",a=et(t,[{[ne]:!0,[Ce]:!0,[ln]:!0},{lineUps:!0,[He]:Be}],s);if(a.error)return a;let c=e.participants||[],u=Bt({tournamentParticipants:c,inContext:!0,drawDefinition:r,matchUpId:n});if(u.error)return u;if(!u.matchUp)return{error:Le};let{matchUp:p,structure:m}=u,{drawPositions:d,matchUpType:l}=p;if(l!==Wt)return{error:lr};if(!d?.length)return{error:Ya};let f=We({matchUp:p,drawDefinition:r,structure:m,event:i})?.tieFormat,g={};for(let h of o){if(!Array.isArray(h))return{error:V,lineUp:h};let S={},T=[];for(let U of h){if(typeof U!="object")return{error:V,lineUpAssignment:U};let{participantId:N,collectionAssignments:D=[]}=U;if(!Array.isArray(D))return{error:V,collectionAssignments:D};let M=c.find(b=>b.participantId===N);if(!M)return{error:re};if(M.participantType!==At)return{error:An};let R=p.sides?.find(b=>b.participant?.individualParticipantIds?.includes(N))?.sideNumber;R&&T.push(R);for(let b of D){if(typeof b!="object")return{error:V,collectionAssignment:b};let{collectionId:v,collectionPosition:O}=b,x=f?.collectionDefinitions?.find(L=>L.collectionId===v);if(!x)return{error:V,collectionId:v};let F=`${v}-${O}`;S[F]||(S[F]=[]);let w=S[F].length;if(de(kt)(x.matchUpType)&&w||x.matchUpType===xt&&w>1)return{info:"Excessive collectionPosition assignments",error:V};S[F].push(N)}}let y=Object.values(S);for(let U of y)if(U.length===2){let{participant:N}=In({tournamentParticipants:c,participantIds:U});if(!N){let M=vn({participant:{participantType:ft,participantRole:xe,individualParticipantIds:U},pairOverride:!0,tournamentRecord:e});if(M.error)return M}}let E=yr(T),P=(E[1]||0)>(E[2]||0)&&1||(E[2]||0)>(E[1]||0)&&2||void 0,A=Object.keys(g).map(U=>parseInt(U));P&&!A.includes(P)&&(g[P]=h)}if(!Object.keys(g).length)return{error:cf};if(u=Bt({drawDefinition:r,matchUpId:n}),u.error)return u;if(!u.matchUp)return{error:Le};let{matchUp:I}=u;I.sides||(I.sides=[]);for(let h of[1,2]){let S=I.sides.find(y=>y.sideNumber===h),T=g[h];if(T)S?S.lineUp=T:I.sides.push({lineUp:T,sideNumber:h});else continue}return gt({tournamentId:e?.tournamentId,context:s,drawDefinition:r,matchUp:I}),{...C}}var TI={};Jt(TI,{anonymizeTournamentRecord:()=>_M,generate:()=>OM,generateEventWithDraw:()=>gm,generateOutcome:()=>II,generateOutcomeFromScoreString:()=>lI,generateParticipants:()=>aa,generateTournamentRecord:()=>vM,modifyTournamentRecord:()=>xM,mutate:()=>wM});var OM={};Jt(OM,{generateEventWithDraw:()=>gm,generateOutcome:()=>II,generateOutcomeFromScoreString:()=>lI,generateParticipants:()=>aa,generateTournamentRecord:()=>vM});function lI(t){let{matchUpFormat:e,matchUpStatus:r,winningSide:n,scoreString:o,setTBlast:i}=t;if(!o)return{outcome:{...Ou,winningSide:n,matchUpStatus:r}};if(n&&![1,2,void 0].includes(n))return{error:V,winningSide:n};let s=o&&qd({scoreString:o}),a={},c=$o({sets:s,matchUpFormat:e,setTBlast:i}),u=$o({sets:s,reversed:!0,matchUpFormat:e,setTBlast:i});return n===2?(a.scoreStringSide1=u,a.scoreStringSide2=c):(a.scoreStringSide1=c,a.scoreStringSide2=u),a.sets=qd({scoreString:a.scoreStringSide1}),nt({outcome:{matchUpStatus:r,winningSide:n,score:a}})}function yl({matchUpScheduleTimes:t,matchUpDependencies:e,allDateMatchUpIds:r,matchUp:n}){let i=(e?.[n.matchUpId]?.matchUpIds||[]).filter(a=>r.includes(a)).filter(a=>!t[a]);return{dependenciesScheduled:!i?.length,remainingDependencies:i}}function ka({individualParticipantProfiles:t,participantId:e}){t[e]||(t[e]={typeChangeTimeAfterRecovery:void 0,timeAfterRecovery:void 0,priorMatchUpType:void 0,potentialRecovery:{},potentialCounted:{},potentialBookings:{},bookings:[],counters:{}})}function Yx({individualParticipantProfiles:t,recoveryValue:e,participantId:r,scheduleTime:n,drawId:o}){t[r].potentialRecovery[o]||(t[r].potentialRecovery[o]=[]),t[r].potentialRecovery[o].push(e),t[r].potentialBookings[o]||(t[r].potentialBookings[o]=[]),t[r].potentialBookings[o].push({timeAfterRecovery:e,scheduleTime:n})}function xc({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,typeChangeRecoveryMinutes:r,averageMatchUpMinutes:n=0,matchUpNotBeforeTimes:o,matchUpDependencies:i,recoveryMinutes:s=0,scheduleTime:a,matchUp:c}){let u=Qt(c?.schedule?.endTime),p=u?Yr(u,dt(s)):Yr(a,dt(n)+dt(s)),m=r&&(u?Yr(Qt(u),r):Yr(a,dt(n)+dt(r))),d=i?.[c.matchUpId]?.participantIds||[],l=(c.roundPosition&&t[c.matchUpId]||[]).flat();d.forEach(f=>{ka({individualParticipantProfiles:e,participantId:f});let I=e[f].priorMatchUpType!==c.matchUpType&&m||p;l.includes(f)?Yx({individualParticipantProfiles:e,drawId:c.drawId,recoveryValue:I,participantId:f,scheduleTime:a}):(e[f].timeAfterRecovery=I,e[f].bookings.push({scheduleTime:a,timeAfterRecovery:I}))}),ra({matchUpPotentialParticipantIds:t,matchUpNotBeforeTimes:o,timeAfterRecovery:p,matchUp:c})}function zy({matchUpScheduleTimes:t,matchUpDependencies:e,scheduleTime:r,matchUpId:n,details:o}){let i,s=o.minutesMap?.[n]?.recoveryMinutes,c=(o.minutesMap?.[n]?.averageMinutes||0)+(s||0),u=Yr(r,c),p=e?.[n]?.dependentMatchUpIds||[];if(p.length){let m=p.reduce((d,l)=>{let f=t[l];if(!f)return d;let g={scheduleTime:f,matchUpId:l};return f&&!d.matchUpId||Yt(f)<Yt(d.scheduleTime)?g:d},{});m.scheduleTime&&Yt(u)>Yt(m.scheduleTime)&&(i=m)}return{scheduledDependent:i}}function qx(t){let{sides:e,matchUpType:r}=t||{};return(e||[]).map(n=>r===xt&&(n?.participant?.individualParticipants||[])||n?.participant&&[n.participant]||[]).flat()}var wc="DO_NOT_SCHEDULE",$x={DO_NOT_SCHEDULE:wc};function Al({averageMatchUpMinutes:t=90,requestConflicts:e={},potentials:r=!0,personRequests:n,scheduleTime:o,scheduleDate:i,matchUp:s}){let a=qx(s).map(({person:l})=>l?.personId);if(r){let l=(s?.potentialParticipants||[]).flat().map(({person:f})=>f?.personId);a.push(...l)}let c=a.map(l=>n[l]?.map(f=>({...f,personId:l}))).filter(Boolean).flat().filter(l=>l.requestType===wc&&qn(i,l.date)),u=[],p=s?.matchUpId,m=Ge(Qt(o),Pt(i)),d=Qt(Ef(m,t).toISOString());for(let l of c){let{requestId:f,startTime:g,endTime:I}=l;(o>g&&o<I||d>g&&d<I)&&(u.push({matchUpId:p,request:l,scheduleTime:o}),e[f]?(e[f].scheduleTimes.includes(o)||e[f].scheduleTimes.push(o),e[f].matchUpIds.includes(p)||e[f].matchUpIds.push(p)):e[f]={request:l,scheduleTimes:[o],matchUpIds:[p]})}return{conflicts:u}}function fI({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,matchUp:r,value:n}){let{matchUpType:o}=r,{individualParticipantIds:i}=mu(r),a=(t[r.matchUpId]||[]).filter(u=>!ke(u,i)).flat();[...i,...a].forEach(u=>{if(ka({individualParticipantProfiles:e,participantId:u}),!e[u].potentialCounted[r.drawId]){let p=e[u].counters;p[o]?p[o]+=n:n>0&&(p[o]=n),p[mo]?p[mo]+=n:n>0&&(p[mo]=n),a.includes(u)&&(e[u].potentialCounted[r.drawId]=!0)}})}function Kx({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,dateScheduledMatchUpIds:r,greatestAverageMinutes:n,dateScheduledMatchUps:o,matchUpNotBeforeTimes:i,matchUpScheduleTimes:s,matchUpDependencies:a,clearScheduleDates:c,scheduleDate:u,minutesMap:p,matchUps:m}){let d=[];r||(o=m?.filter(g=>{let I=g.schedule||{},h=g.matchUpStatus===Nt;return h&&d.push({tournamentId:g.tournamentId,matchUpId:g.matchUpId}),!h&&xa({schedule:I})&&(!u||g.schedule.scheduledDate===u)}),r=o.map(Ue));let l=Array.isArray(c)?c.includes(u):c,f=l?[]:m.filter(({matchUpId:g})=>r.includes(g));for(let g of f){fI({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,value:1,matchUp:g});let I=g.schedule?.scheduledTime;if(I){s[g.matchUpId]=I;let h=p?.[g.matchUpId]?.recoveryMinutes;xc({individualParticipantProfiles:e,matchUpPotentialParticipantIds:t,matchUpNotBeforeTimes:i,matchUpDependencies:a,averageMatchUpMinutes:n,recoveryMinutes:h,scheduleTime:I,matchUp:g})}}return{dateScheduledMatchUpIds:r,byeScheduledMatchUpDetails:d,dateScheduledMatchUps:o,clearDate:l}}function um({defaultRecoveryMinutes:t=0,averageMatchUpMinutes:e=90,dateScheduledMatchUps:r,tournamentRecords:n,venueIds:o=[],periodLength:i,scheduleDate:s,matchUps:a}){if(typeof n!="object")return{error:Lt};if(!Vr(a)&&!Array.isArray(r))return{error:eo};i=i??Hu({recoveryMinutes:t,averageMatchUpMinutes:e});let c=Object.assign({},...Object.values(n).map(d=>(d.events??[]).map(l=>{let{scheduleTiming:f}=Ea({tournamentRecord:d,event:l});return{[l.eventId]:{event:l,scheduleTiming:f}}})).flat()),u={averageTimes:[{minutes:{default:e}}],recoveryTimes:[{minutes:{default:t}}]};r||(r=a?.filter(d=>{let l=d.schedule;return xa({schedule:l})&&(!s||d.schedule.scheduledDate===s)}));let p=r?.filter(d=>(!o.length||o.includes(d.schedule.venueId))&&d.matchUpStatus!==Nt);return{bookings:p?.map(({eventId:d,schedule:l,matchUpFormat:f})=>{let{event:g,scheduleTiming:I}=c[d],h=g?.eventType,S={...I,defaultTiming:u,matchUpFormat:f},{averageMinutes:T,recoveryMinutes:y}=Mp({timingDetails:S,eventType:h}),{courtId:E,venueId:P}=l,A=Qt(l.scheduledTime),U=Yr(A,T);return{recoveryMinutes:y,averageMinutes:T,periodLength:i,startTime:A,courtId:E,endTime:U,venueId:P}}).filter(Boolean),relevantMatchUps:p,dateScheduledMatchUps:r}}function zx({calculateStartTimeFromCourts:t=!0,remainingScheduleTimes:e,defaultRecoveryMinutes:r,averageMatchUpMinutes:n,clearScheduleDates:o,tournamentRecords:i,tournamentRecord:s,periodLength:a,scheduleDate:c,startTime:u,venueIds:p,matchUps:m,endTime:d}){if(s&&!i&&(i={[s.tournamentId]:s}),typeof i!="object"||!Object.keys(i).length)return{error:Lt};a=a??Hu({recoveryMinutes:r,averageMatchUpMinutes:n});let{courts:l,venues:f}=Uo({dates:[c],ignoreDisabled:!0,tournamentRecords:i}),g=l?.filter(P=>!p||p.includes(P.venueId))??[];u=u??Oc({courts:g,scheduleDate:c,startTime:!0}),d=d??Oc({courts:g,scheduleDate:c,endTime:!0});let{bookings:I,dateScheduledMatchUps:h}=um({defaultRecoveryMinutes:r,averageMatchUpMinutes:n,tournamentRecords:i,scheduleDate:c,periodLength:a,venueIds:p,matchUps:m}),S={calculateStartTimeFromCourts:t,remainingScheduleTimes:e,averageMatchUpMinutes:n,clearScheduleDates:o,date:c,periodLength:a,startTime:u,bookings:I,endTime:d,courts:g},{scheduleTimes:T}=gl(S),y=p?.length===1&&p[0]||f?.length===1&&f[0].venueId||void 0;return{dateScheduledMatchUpIds:h?.map(Br("matchUpId")),dateScheduledMatchUps:h,scheduleTimes:T,venueId:y}}function Qx({scheduledRoundsDetails:t,greatestAverageMinutes:e,garmanSinglePass:r}){let n=[],o=[],i,s,a,c;for(let u of t.filter(Boolean))c||(c=u.hash),(u.hash===c||r)&&(o=o.concat(u.matchUpIds)),u.hash!==c&&!r&&(c=u.hash,n.push({averageMinutes:a,recoveryMinutes:s,roundPeriodLength:i,matchUpIds:o}),o=u.matchUpIds),a=r?e:u.averageMinutes,s=u.recoveryMinutes,i=u.roundPeriodLength;return o.length&&n.push({matchUpIds:o,roundPeriodLength:i,recoveryMinutes:s,averageMinutes:a}),{groupedRounds:n}}function Qy({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,scheduleCompletedMatchUps:r,containedStructureIds:n,matchUpNotBeforeTimes:o,matchUpScheduleTimes:i,matchUpDependencies:s,clearScheduleDates:a,tournamentRecords:c,periodLength:u,scheduleDate:p,useGarman:m,matchUps:d,courts:l,venues:f}){let g={},I=[],h=[],S=[];for(let T of f){let{rounds:y=[],venueId:E}=T,{scheduledRoundsDetails:P,greatestAverageMinutes:A,orderedMatchUpIds:U,minutesMap:N}=Vu({scheduleCompletedMatchUps:r,containedStructureIds:n,tournamentRecords:c,periodLength:u,matchUps:d,rounds:y});S.push(...U??[]);let{groupedRounds:D}=Qx({scheduledRoundsDetails:P,greatestAverageMinutes:A,garmanSinglePass:!0}),M,R=[];m&&({scheduleTimes:R,dateScheduledMatchUpIds:M}=zx({averageMatchUpMinutes:D[0]?.averageMinutes,scheduleDate:Pt(p),venueIds:[T.venueId],clearScheduleDates:a,tournamentRecords:c,periodLength:u,matchUps:d}));let b=Kx({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,dateScheduledMatchUpIds:M,greatestAverageMinutes:A,matchUpNotBeforeTimes:o,matchUpScheduleTimes:i,matchUpDependencies:s,clearScheduleDates:a,scheduleDate:p,minutesMap:N,matchUps:d});({dateScheduledMatchUpIds:M}=b);let v=b,{byeScheduledMatchUpDetails:O,clearDate:x}=b;O?.length&&h.push(...O);let{matchUpsToSchedule:F,matchUpMap:w}=ol({matchUpPotentialParticipantIds:t,scheduleCompletedMatchUps:r,dateScheduledMatchUpIds:M,matchUpNotBeforeTimes:o,matchUpScheduleTimes:i,orderedMatchUpIds:U,clearDate:x,matchUps:d}),L=l.filter(G=>G.venueId===E);g[E]={previousRemainingScheduleTimes:[],courtsCount:L.length,greatestAverageMinutes:A,scheduledRoundsDetails:P,dateScheduledMatchUps:v,matchUpsToSchedule:F,scheduleTimes:R,groupedRounds:D,venueCourts:L,minutesMap:N,matchUpMap:w},a||I.push(...M)}return{allDateScheduledByeMatchUpDetails:h,allDateScheduledMatchUpIds:I,venueScheduledRoundDetails:g,allDateMatchUpIds:S}}function Xx(t,e){let r=Yt(t.scheduleTime),n=Yt(t.timeAfterRecovery),o=Yt(e.scheduleTime),i=Yt(e.timeAfterRecovery),s=r===o||n===i,a=r>o&&r<i,c=o>r&&o<n,u=n>o&&n<i,p=i>r&&i<n;return nt({hasOverlap:s||a||u||c||p,startAisContained:a,endAisContained:u,startBisContained:c,endBisContained:p},!0)}function El({individualParticipantProfiles:t,matchUpNotBeforeTimes:e,matchUpDependencies:r,scheduleTime:n,matchUp:o,details:i}){let s=(r?.[o.matchUpId]?.participantIds||[]).flat(),a=i?.minutesMap?.[o.matchUpId]?.averageMinutes||0,c=i?.minutesMap?.[o.matchUpId]?.recoveryMinutes||0,u=s.every(f=>{ka({individualParticipantProfiles:t,participantId:f});let g=t[f];if(!g.timeAfterRecovery)return!0;let I=Qt(o?.schedule?.endTime),h=I?Yr(I,dt(c)):Yr(n,dt(a)+dt(c));return!!![...Object.keys(g.potentialBookings).filter(E=>E!==o.drawId).map(E=>g.potentialBookings[E]).flat(),...g.bookings].find(E=>Xx({scheduleTime:n,timeAfterRecovery:h},E).hasOverlap)}),p=e[o.matchUpId],d=(p?la(Ge(p),Ge(n),!1):0)>=0;return{enoughTime:u&&d}}function Xy({autoSchedulingAudit:t,tournamentRecords:e}){lt({topic:Ai,payload:t});let r=s=>s?Object.values(s).reduce((c,u)=>c+u.length||0,0):0,n=(t?.schedulingProfile||[]).reduce((s,a)=>s+a.venues.reduce((c,u)=>c+u.rounds.length,0),0),o={scheduledDatesCount:t.scheduledDates?.length,noTimeMatchUpIdsCount:r(t?.noTimeMatchUpIds),scheduledMatchUpIdsCount:r(t?.scheduledMatchUpIds),overLimitMatchUpIdsCount:r(t?.overLimitMatchUpIds),requestConflictsCount:r(t?.requestConflicts),profileRoundsCount:n},i={itemType:Ry,itemValue:o};for(let s of Object.values(e)){let a=s.tournamentId;ip(Ai)?lt({payload:{type:Ry,tournamentId:a,detail:o},topic:Ai}):Nc({tournamentRecord:s,timeItem:i})}}function Ul({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,matchUpDailyLimits:r={},matchUp:n}){let{enteredIndividualParticipantIds:o}=mu(n),{matchUpId:i,matchUpType:s}=n,a=(n.roundPosition&&t[i]||[]).flat(),c=pt(o.concat(...a));return c.forEach(p=>{ka({individualParticipantProfiles:e,participantId:p})}),{participantIdsAtLimit:c.filter(p=>{let m=e[p];if(m)return[s,mo].find(d=>{let l=m.counters?.[d]||0,f=r[d]||0;return l&&f&&l>=f})}),relevantParticipantIds:c}}function ju({scheduleCompletedMatchUps:t=!1,scheduleByeMatchUps:e=!1,errorOnAnachronism:r=!1,checkChronology:n=!0,matchUpDependencies:o,removePriorValues:i,tournamentRecords:s,tournamentRecord:a,matchUpDetails:c,matchUpIds:u,schedule:p}){if(!a)return{error:$};if(!c&&(!u||!Array.isArray(u)))return{error:ns};if(!c&&(!p||typeof p!="object"))return{error:RE};let m,d=[],l=0;if(n&&!o){let I=on({tournamentRecords:s,tournamentRecord:a});o=I.matchUpDependencies,m=I.matchUps}m||(m=ye({tournamentRecord:a})?.matchUps??[]);let f=m.reduce((I,h)=>{let{matchUpId:S,drawId:T,matchUpStatus:y}=h;return(e||y!==Nt)&&(t||!se.includes(y))&&(I[T]?I[T].push(S):I[T]=[S]),I},{}),g=c?.map(I=>I.matchUpId);for(let I of Object.keys(f)){let{drawDefinition:h}=Fo({tournamentRecord:a,drawId:I});if(!h)continue;let S=f[I].filter(y=>u?.includes(y)??g?.includes(y)),T=ir({inContext:!1,drawDefinition:h}).matchUps;for(let y of S){let E=c?.find(A=>A.matchUpId===y)?.schedule||p,P=cm({schedule:E,matchUpDependencies:o,errorOnAnachronism:r,removePriorValues:i,inContextMatchUps:m,tournamentRecords:s,tournamentRecord:a,checkChronology:n,drawDefinition:h,drawMatchUps:T,matchUpId:y});if(P?.warnings?.length&&d.push(...P.warnings),P?.success&&(l+=1),P.error)return P}}return d.length?{...C,scheduled:l,warnings:d}:{...C,scheduled:l}}function Lc(t){let{scheduleCompletedMatchUps:e=!1,scheduleByeMatchUps:r=!1,errorOnAnachronism:n,matchUpContextIds:o,removePriorValues:i,tournamentRecords:s,checkChronology:a,matchUpDetails:c,schedule:u}=t;if(t.matchUpIds&&!o)return ju(t);let p=et(t,[{[Re]:!0},{[Vs]:{matchUpContextIds:!1,matchUpDetails:!1},[Fr]:V,[He]:Be}]);if(p.error)return p;if((!c||o)&&!u)return{error:st,info:"schedule is required"};let m=[],d=0,{matchUpDependencies:l}=on({tournamentRecords:s});for(let f of Object.values(s)){let{tournamentId:g}=f,I=o?.filter(S=>S.tournamentId===g).map(Ue),h=c?.filter(S=>S?.tournamentId===g);if(I?.length||h?.length){let S=ju({matchUpDetails:h,scheduleCompletedMatchUps:e,scheduleByeMatchUps:r,matchUpDependencies:l,errorOnAnachronism:n,removePriorValues:i,tournamentRecords:s,tournamentRecord:f,checkChronology:a,matchUpIds:I,schedule:u});if(S.warnings?.length&&m.push(...S.warnings),S.scheduled&&(d+=S.scheduled),S.error)return S}}return m.length?{...C,scheduled:d,warnings:m}:{...C,scheduled:d}}function Jx({schedulingProfileModifications:t,checkPotentialRequestConflicts:e,scheduleCompletedMatchUps:r,schedulingProfileIssues:n,dateSchedulingProfiles:o,containedStructureIds:i,matchUpDependencies:s,matchUpDailyLimits:a,clearScheduleDates:c,tournamentRecords:u,schedulingProfile:p,personRequests:m,periodLength:d,matchUps:l,courts:f,dryRun:g}){let I={},h={},S={},T={},y={},E={},P={},A={},U={},N={};for(let R of o){let b=Pt(R?.scheduleDate),v=R?.venues||[],O={},x={},F=(B,K)=>{B.forEach(X=>{let j=x[X].counters;j[K]?j[K]+=1:j[K]=1,j[mo]?j[mo]+=1:j[mo]=1})};S[b]={},T[b]={},I[b]={},h[b]={},P[b]=[],A[b]=[],U[b]=[],N[b]=[];let w={};l.forEach(B=>{B.schedule?.scheduledDate&&qn(b,Pt(B.schedule.scheduledDate))&&ra({matchUpPotentialParticipantIds:O,matchUpNotBeforeTimes:w,matchUp:B})});let{allDateScheduledByeMatchUpDetails:L,venueScheduledRoundDetails:G,allDateMatchUpIds:k}=Qy({matchUpPotentialParticipantIds:O,individualParticipantProfiles:x,scheduleCompletedMatchUps:r,containedStructureIds:i,matchUpNotBeforeTimes:w,matchUpScheduleTimes:E,matchUpDependencies:s,clearScheduleDates:c,tournamentRecords:u,useGarman:!0,periodLength:d,scheduleDate:b,matchUps:l,courts:f,venues:v}),H=10,W=0,q,Y=10;for(;!q;){for(let{venueId:B}of v){let K=0,X=G[B];for(;X.courtsCount&&X.scheduleTimes?.length&&X.matchUpsToSchedule?.length&&K<=X.courtsCount;){let{scheduleTime:j,attempts:ot=0}=X.scheduleTimes.shift(),z=X.matchUpsToSchedule.find(Q=>{let{matchUpId:ut,matchUpType:it}=Q,{participantIdsAtLimit:Et,relevantParticipantIds:_t}=Ul({matchUpPotentialParticipantIds:O,individualParticipantProfiles:x,matchUpDailyLimits:a,matchUp:Q});if(Et.length)return A[b].includes(ut)||A[b].push(ut),!1;let{scheduledDependent:Ae}=zy({matchUpScheduleTimes:E,matchUpDependencies:s,scheduleTime:j,matchUpId:ut,details:X});if(Ae)return!1;let{dependenciesScheduled:$t,remainingDependencies:Se}=yl({matchUpScheduleTimes:E,matchUpDependencies:s,allDateMatchUpIds:k,matchUp:Q});if(!$t)return T[b][ut]||(T[b][ut]=[]),T[b][ut].push({scheduleTime:j,remainingDependencies:Se}),!1;let{enoughTime:Or}=El({individualParticipantProfiles:x,matchUpNotBeforeTimes:w,matchUpDependencies:s,scheduleTime:j,details:X,matchUp:Q});if(!Or)return S[b][ut]||(S[b][ut]=[]),S[b][ut].push({scheduleTime:j}),!1;let pn=X.greatestAverageMinutes,{conflicts:Ir}=Al({potentials:e,averageMatchUpMinutes:pn,requestConflicts:N,personRequests:m,scheduleTime:j,scheduleDate:b,matchUp:Q});if(Ir?.length)return y[b]||(y[b]=[]),y[b].push(...Ir),!1;F(_t,it);let Xe=X.minutesMap?.[ut]?.recoveryMinutes;return xc({matchUpPotentialParticipantIds:O,individualParticipantProfiles:x,matchUpNotBeforeTimes:w,averageMatchUpMinutes:pn,matchUpDependencies:s,recoveryMinutes:Xe,scheduleTime:j,matchUp:Q}),E[ut]=j,!0});X.matchUpsToSchedule=X.matchUpsToSchedule.filter(({matchUpId:Q})=>Q!==z?.matchUpId),z?K+=1:(h[b][B]||(h[b][B]=[]),h[b][B].push({scheduleTime:j,attempts:ot+1}))}X.matchUpsToSchedule?.length&&(h[b][B]=h[b][B]?.filter(j=>{let ot=j.attempts<H;return ot&&X.scheduleTimes.push(j),!ot})),(!X.scheduleTimes?.length||!X.matchUpsToSchedule?.length)&&(X.complete=!0)}W+=1,q=v.every(({venueId:B})=>G[B].complete)||W===Y}for(let{venueId:B}of v){let K=G[B].matchUpMap;Object.keys(K).forEach(X=>{let j=u[X];j&&Object.keys(K[X]).forEach(ot=>{let{drawDefinition:z}=Fo({tournamentRecord:j,drawId:ot});z&&K[X][ot].forEach(({matchUpId:ut})=>{let it=E[ut];if(it){let Et=it.split(":").map(ro).join(":"),_t=`${Pt(b)}T${Et}`;g?P[b].push(ut):(Jo({drawDefinition:z,scheduledTime:_t,matchUpId:ut}).success&&P[b].push(ut),B&&sa({tournamentRecord:j,drawDefinition:z,matchUpId:ut,venueId:B}))}})})}),U[b]=G[B].matchUpsToSchedule.map(Ue),I[b][B]=G[B].scheduleTimes.sort((X,j)=>Yt(X.scheduleTime)-Yt(j.scheduleTime))}!g&&L?.length&&Lc({matchUpDetails:L,scheduleByeMatchUps:!0,removePriorValues:!0,tournamentRecords:u,schedule:{scheduledDate:"",scheduledTime:"",courtOrder:"",courtId:"",venueId:""}});for(let B of R.venues)for(let K of B.rounds){let j=(K.matchUps?.map(({matchUpId:z})=>z)||[]).filter(z=>P[b].includes(z));K.canScheduledMatchUpIds=j;let ot=Math.round(j.length/K.matchUpsCount*1e4)/100;(ot===1/0||isNaN(ot))&&(ot=0),K.possibleToSchedulePct=ot,K.matchUpsCount===j.length&&(K.possibleToSchedule=!0)}}let D=o.map(({scheduleDate:R})=>R),M={timeStamp:Date.now(),overLimitMatchUpIds:A,scheduledMatchUpIds:P,schedulingProfile:p,noTimeMatchUpIds:U,requestConflicts:N,scheduledDates:D};return Xy({tournamentRecords:u,autoSchedulingAudit:M}),{...C,schedulingProfileModifications:t,schedulingProfileIssues:n,scheduleTimesRemaining:I,dateSchedulingProfiles:o,skippedScheduleTimes:h,recoveryTimeDeferredMatchUpIds:S,dependencyDeferredMatchUpIds:T,matchUpScheduleTimes:E,overLimitMatchUpIds:A,scheduledMatchUpIds:P,noTimeMatchUpIds:U,requestConflicts:N,scheduledDates:D}}function MM({averageMinutes:t,startTime:e,endTime:r,court:n,date:o}){if(!Array.isArray(n.dateAvailability))return{error:st,stack:"getEarliestCourtTime"};let i=Oc({scheduleDate:o,courts:[n],startTime:!0}),s=Oc({scheduleDate:o,courts:[n],endTime:!0});e=e||i,r=r||s;let a=La({court:n,date:o}),{timeSlots:c}=Ms({courtDate:a}),u=Ge(e),p=Ge(r);return{earliestCourtTime:c?.reduce((d,l)=>{let f=Ge(l.startTime),g=Ge(l.endTime);if(f>p||g<u)return d;let I=u>f?u:f;if(la(I,g)>=t){let T=Qt(I.toISOString());(!d||T<d)&&(d=T)}return d},void 0),courtStartTime:i,courtEndTime:s}}function Zx({schedulingProfileModifications:t,checkPotentialRequestConflicts:e,scheduleCompletedMatchUps:r,schedulingProfileIssues:n,dateSchedulingProfiles:o,containedStructureIds:i,matchUpDependencies:s,matchUpDailyLimits:a,clearScheduleDates:c,tournamentRecords:u,periodLength:p=30,schedulingProfile:m,personRequests:d,matchUps:l=[],courts:f,dryRun:g}){let I={},h={},S={},T={},y={},E={},P={},A={},U={};for(let M of o??[]){let R=Pt(M?.scheduleDate),b=M?.venues||[],v={},O={},x=(z,Q)=>{z.forEach(ut=>{let it=O[ut].counters;it[Q]?it[Q]+=1:it[Q]=1,it[mo]?it[mo]+=1:it[mo]=1})};I[R]={},h[R]={},E[R]=[],P[R]=[],A[R]=[],U[R]=[];let F={};l?.forEach(z=>{z.schedule?.scheduledDate&&qn(R,Pt(z.schedule.scheduledDate))&&ra({matchUpPotentialParticipantIds:v,matchUpNotBeforeTimes:F,matchUp:z})});let{allDateScheduledByeMatchUpDetails:w,allDateScheduledMatchUpIds:L,venueScheduledRoundDetails:G,allDateMatchUpIds:k}=Qy({matchUpPotentialParticipantIds:v,individualParticipantProfiles:O,scheduleCompletedMatchUps:r,containedStructureIds:i,matchUpNotBeforeTimes:F,matchUpScheduleTimes:y,matchUpDependencies:s,clearScheduleDates:c,tournamentRecords:u,periodLength:p,scheduleDate:R,matchUps:l,courts:f,venues:b}),H=l?.filter(({matchUpId:z})=>L.includes(z)),{bookings:W}=um({dateScheduledMatchUps:H,tournamentRecords:u,scheduleDate:R,periodLength:p}),{virtualCourts:q}=nm({scheduleDate:R,periodLength:p,bookings:W,courts:f}),Y=q?.reduce((z,Q)=>{let{earliestCourtTime:ut,courtEndTime:it}=MM({date:R,averageMinutes:0,court:Q});return(!z.startTime||Ge(ut)<Ge(z.startTime))&&(z.startTime=ut),(!z.endTime||Ge(it)>Ge(z.endTime))&&(z.endTime=it),z},{}),B=Y.startTime,K=({courtId:z,booking:Q})=>q?.find(ut=>ut.courtId===z)?.dateAvailability[0].bookings.push(Q),X=10,j=0,ot;for(;!ot;){for(let{venueId:z}of b){let Q=G[z],ut=Q.matchUpsToSchedule.length,it=[],Et=[],_t,Ae=0;for(;!_t;){for(let $t of Q.matchUpsToSchedule){if(Et.length===Q.courtsCount||it.length===Q.courtsCount){_t=!0;break}let{matchUpId:Se,matchUpType:Or}=$t,{participantIdsAtLimit:pn,relevantParticipantIds:Ir}=Ul({matchUpPotentialParticipantIds:v,individualParticipantProfiles:O,matchUpDailyLimits:a,matchUp:$t});if(pn.length){P[R].includes(Se)||P[R].push(Se);continue}let{dependenciesScheduled:Xe,remainingDependencies:te}=yl({matchUpScheduleTimes:y,matchUpDependencies:s,allDateMatchUpIds:k,matchUp:$t});if(!Xe){h[R][Se]||(h[R][Se]=[]),h[R][Se].push({remainingDependencies:te});continue}let Dt=[],ue=q?.reduce((pe,Fe)=>{if(Et.includes(Fe.courtId))return pe;let{earliestCourtTime:ee}=MM({averageMinutes:Q.greatestAverageMinutes,startTime:B,date:R,court:Fe});if(pe.scheduleTime&&Yt(ee)>=Yt(pe.scheduleTime))return pe;let{scheduledDependent:Je}=zy({matchUpScheduleTimes:y,matchUpDependencies:s,scheduleTime:ee,matchUpId:Se,details:Q});if(Je)return pe;let{enoughTime:qt}=El({individualParticipantProfiles:O,matchUpNotBeforeTimes:F,matchUpDependencies:s,scheduleTime:ee,details:Q,matchUp:$t});if(!qt)return I[R][Se]||(I[R][Se]=[]),I[R][Se].includes(ee)||I[R][Se].push(ee),pe;let ar=Q.minutesMap?.[Se]?.averageMinutes||Q.greatestAverageMinutes,{conflicts:Ze}=Al({potentials:e,averageMatchUpMinutes:ar,requestConflicts:U,personRequests:d,scheduleTime:ee,scheduleDate:R,matchUp:$t});if(Ze?.length)return Dt.push(...Ze),!1;x(Ir,Or);let Pe=Q.minutesMap?.[Se]?.recoveryMinutes;return xc({matchUpPotentialParticipantIds:v,individualParticipantProfiles:O,matchUpNotBeforeTimes:F,averageMatchUpMinutes:ar,matchUpDependencies:s,recoveryMinutes:Pe,scheduleTime:ee,matchUp:$t}),(!pe.scheduleTime||Yt(ee)<Yt(pe.scheduleTime))&&(pe.averageMatchUpMinutes=ar,pe.recoveryMinutes=Pe,pe.scheduleTime=ee,pe.courtName=Fe.courtName,pe.courtId=Fe.courtId),pe},{});if(ue.scheduleTime){let{averageMatchUpMinutes:pe,recoveryMinutes:Fe,scheduleTime:ee,courtId:Je}=ue;y[Se]=ee,T[Se]=Je,it.push(Se),Et.push(Je);let qt=ee,ar=Yr(qt,pe);K({courtId:Je,booking:{averageMatchUpMinutes:pe,recoveryMinutes:Fe,periodLength:p,matchUpId:Se,startTime:qt,courtId:Je,endTime:ar,venueId:z}}),Q.matchUpsToSchedule=Q.matchUpsToSchedule.filter(Pe=>Pe.matchUpId!==Se)}else Dt?.length&&(S[R]||(S[R]=[]),S[R].push(...Dt))}(Et.length===Q.courtsCount||it.length===Q.courtsCount||!Q.matchUpsToSchedule.length)&&(_t=!0),Q.matchUpsToSchedule.length&&it<Q.courtsCount&&(Ge(B)<Ge(Y.endTime)?B=Yr(B,p):(_t=!0,Q.complete=!0)),Ae+=1,!_t&&Ae>=ut&&(_t=!0)}Q.matchUpsToSchedule?.length||(Q.complete=!0)}j+=1,ot=b.every(({venueId:z})=>G[z].complete)||j===X}for(let{venueId:z}of b){let Q=G[z].matchUpMap;Object.keys(Q).forEach(ut=>{let it=u[ut];it&&Object.keys(Q[ut]).forEach(Et=>{let{drawDefinition:_t}=Fo({tournamentRecord:it,drawId:Et});_t&&Q[ut][Et].forEach(({matchUpId:$t})=>{let Se=y[$t],Or=T[$t];if(Se){let pn=Se.split(":").map(ro).join(":"),Ir=`${Pt(R)}T${pn}`;g||(Jo({drawDefinition:_t,scheduledTime:Ir,matchUpId:$t}),Zi({courtDayDate:R,tournamentRecords:u,tournamentRecord:it,drawDefinition:_t,matchUpId:$t,courtId:Or})),E[R].push($t)}})})}),A[R]=G[z].matchUpsToSchedule.map(Ue)}!g&&w?.length&&Lc({matchUpDetails:w,scheduleByeMatchUps:!0,removePriorValues:!0,tournamentRecords:u,schedule:{scheduledDate:"",scheduledTime:"",courtOrder:"",courtId:"",venueId:""}});for(let z of M.venues)for(let Q of z.rounds){let it=(Q.matchUps??[]).map(({matchUpId:_t})=>_t)?.filter(_t=>E[R].includes(_t));Q.canScheduledMatchUpIds=it;let Et=Math.round((it?.length||0)/Q.matchUpsCount*1e4)/100;(Et===1/0||isNaN(Et))&&(Et=void 0),Q.possibleToSchedulePct=Et,Q.matchUpsCount===it?.length&&(Q.possibleToSchedule=!0)}}let N=(o??[]).map(({scheduleDate:M})=>M),D={timeStamp:Date.now(),overLimitMatchUpIds:P,scheduledMatchUpIds:E,schedulingProfile:m,noTimeMatchUpIds:A,requestConflicts:U,scheduledDates:N};return Xy({tournamentRecords:u,autoSchedulingAudit:D}),{...C,schedulingProfileModifications:t,schedulingProfileIssues:n,dateSchedulingProfiles:o,recoveryTimeDeferredMatchUpIds:I,dependencyDeferredMatchUpIds:h,matchUpScheduleTimes:y,overLimitMatchUpIds:P,scheduledMatchUpIds:E,noTimeMatchUpIds:A,requestConflicts:U,scheduledDates:N}}function pm(t){let{scheduleAttributes:e=["scheduledDate","scheduledTime","courtOrder"],ignoreMatchUpStatuses:r=se,scheduledDates:n,venueIds:o}=t,i=Mr(t),s=ht(i)?Object.values(i).map(({tournamentId:c})=>c).filter(Boolean):[];if(!s?.length)return{error:Lt};let a=0;for(let c of s){let u=i[c],p=W1({ignoreMatchUpStatuses:r,scheduleAttributes:e,tournamentRecord:u,scheduledDates:n,venueIds:o});if(p.error)return p;a+=p.clearedScheduleCount??0}return{...C,clearedScheduleCount:a}}function W1({scheduleAttributes:t=["scheduledDate","scheduledTime","courtOrder"],ignoreMatchUpStatuses:e=se,tournamentRecord:r,scheduledDates:n,venueIds:o=[]}){if(typeof r!="object")return{error:$};if(!Array.isArray(e)||!Array.isArray(o))return{error:V};o.length&&t.push("venueId");let i=ye({matchUpFilters:{scheduledDates:n},tournamentRecord:r}).matchUps??[],s={};i.forEach(({matchUpStatus:u,schedule:p,drawId:m,matchUpId:d})=>{(!u||!e.includes(u))&&xa({schedule:p,scheduleAttributes:t})&&(!o?.length||o.includes(p.venueId))&&(s[m]||(s[m]=[]),s[m].push(d))});let a=r.tournamentId,c=0;for(let u in s){let{event:p,drawDefinition:m}=ze({tournamentRecord:r,drawId:u}),d=ir({drawDefinition:m,matchUpFilters:{matchUpIds:s[u]}}).matchUps??[];for(let l of d){let f=!1;l.timeItems=(l.timeItems??[]).filter(g=>{let I=g?.itemType&&![po,jo,ji,Up,Yi,qi].includes(g?.itemType);return I||(f=!0),I}),f&&(gt({context:"clear schedules",eventId:p?.eventId,drawDefinition:m,tournamentId:a,matchUp:l}),c+=1)}}return{...C,clearedScheduleCount:c}}function mm(t){let{checkPotentialRequestConflicts:e=!0,scheduleCompletedMatchUps:r,clearScheduleDates:n,scheduleDates:o=[],tournamentRecords:i,periodLength:s,useGarman:a,dryRun:c,pro:u}=t,p=et(t,[{[Re]:!0},{[er]:N=>!N||Array.isArray(N)&&N.every(Nr),[bh]:!1,[He]:Be}]);if(p.error)return p;let m=Xo({tournamentRecords:i});if(m.error)return m;if(!m.schedulingProfile.length)return{...C};let{modifications:d,issues:l=[],schedulingProfile:f=[]}=m,g=Object.assign({},...Object.values(i).map(N=>cs({tournamentRecord:N}).containedStructures)),I=o.map(N=>{if(Nr(N))return Pt(N)}).filter(Boolean),h=f.map(N=>N.scheduleDate).map(N=>Nr(N)&&Pt(N)).filter(N=>N&&(!o.length||I.includes(N)));if(!h.length)return{error:iE};if(n&&!c){let N=Array.isArray(n)?n:[];pm({tournamentRecords:i,scheduledDates:N})}let S=Uo({ignoreDisabled:!1,tournamentRecords:i}).courts,{matchUps:T}=Un({matchUpFilters:{matchUpTypes:[kt,xt]},afterRecoveryTimes:!0,nextMatchUps:!0,tournamentRecords:i}),{matchUpDependencies:y}=on({includeParticipantDependencies:!0,tournamentRecords:i,matchUps:T}),{matchUpDailyLimits:E}=dl({tournamentRecords:i}),{personRequests:P}=Oi({requestType:wc,tournamentRecords:i}),A=f.filter(N=>{let D=Pt(N?.scheduleDate);return h.includes(D)}).sort((N,D)=>new Date(N.scheduleDate).getTime()-new Date(D.scheduleDate).getTime()),U={schedulingProfileModifications:d,checkPotentialRequestConflicts:e,scheduleCompletedMatchUps:r,schedulingProfileIssues:l,dateSchedulingProfiles:A,containedStructureIds:g,matchUpDependencies:y,matchUpDailyLimits:E,clearScheduleDates:n,tournamentRecords:i,schedulingProfile:f,personRequests:P,periodLength:s,useGarman:a,matchUps:T,dryRun:c,courts:S};return u?Zx(U):Jx(U)}function dm(t){let{tournamentRecord:e,tournamentRecords:r,activeTournamentId:n,...o}=t||{};return o.tournamentId||(o.tournamentId=Mt()),o.startDate&&!Ja(o.startDate)&&!Om.test(o.startDate)?{error:je}:o.endDate&&!Ja(o.endDate)&&!Om.test(o.endDate)?{error:je}:(o.extensions&&(o.extensions=o.extensions.filter(kn)),{...o})}function gI({addParticipants:t=!0,participantAttribute:e,tournamentRecord:r,personAttribute:n,teamNames:o,accessor:i,uuids:s}){if(!r)return{error:$};let a={},c=(r.participants??[]).filter(({participantType:f,participantRole:g})=>f===At&&g===xe),u=0;for(let f of c){let I=i&&fs({element:f,accessor:i})?.value||n&&f.person?.[n]||e&&f[e];if(I){if(!Object.keys(a).includes(I)){a[I]={participantName:o?.[u]??I,participantId:s?.pop()??Mt(),individualParticipantIds:[],participantRole:xe,participantType:Ft};let h={value:n??e,name:Fh};Ut({element:a[I],extension:h}),u+=1}a[I].individualParticipantIds.push(f.participantId)}}let p=Object.keys(a),m=(r.participants??[]).map(f=>{if(f.participantType!==Ft||f.participantRole!==xe)return;let{extension:g}=mt({name:Fh,element:f}),I=g?.value;if(p.includes(I))return f.participantId}).filter(Boolean),d=0,l=[];return Object.keys(a).forEach(f=>{let g=a[f],{participantId:I}=g;m.includes(I)||(r.participants||(r.participants=[]),t&&r.participants.push(g),l.push(g),d++)}),t&&d?(lt({payload:{tournamentId:r.tournamentId,participants:l},topic:ei}),{...C,participantsAdded:d}):l.length?{...C,newParticipants:l}:{error:DC}}var tw=[{AA:"Annexia"},{BA:"Bacteria"},{BO:"Borduria"},{BM:"Bensalem"},{BS:"Basenji"},{BI:"Balnibarbi"},{BV:"Bartovia"},{BZ:"Berzerkistan"},{CA:"Caldonia"},{CC:"Concordia"},{CH:"Chula"},{DA:"Deltora"},{DW:"Discworld"},{EA:"Eastasia"},{EP:"Ecotopia"},{ER:"Erewhon"},{FA:"Freedonia"},{FN:"Florin"},{FG:"Fogg"},{FK:"Fourecks"},{GA:"Genovia"},{GL:"Gilead"},{GD:"Gilead"},{GL:"Gondal"},{GO:"Gondor"},{GR:"Gruzinia"},{GT:"Goritania"},{GU:"Guilder"},{HA:"Heldscalla"},{HO:"Hidalgo"},{IL:"Illyria"},{KA:"Kinakuta"},{KG:"Kangan"},{KN:"Kreplachistan"},{KS:"Kallipolis"},{LH:"Lugash"},{LI:"Listenbourg"},{LT:"Lilliput"},{LU:"Luggnagg"},{LV:"Lichtenslava"},{MR:"Moher"},{NA:"Narnia"},{NV:"Novaria"},{OA:"Oceania"},{OS:"Orsinia"},{OV:"Octavia"},{PA:"Palombia"},{PG:"Penguina"},{QA:"Qasha"},{PM:"Panem"},{SA:"Solymbria"},{SD:"Syldavia"},{SG:"San Glucose"},{SL:"San Lorenzo"},{SR:"Sontar"},{SY:"Sylvania"},{TF:"Tralfamadore"},{TH:"Themyscira"},{UA:"Utopia"},{VA:"Vespugia"},{WA:"Wakanda"},{WX:"Wessex"},{ZA:"Zamunda"},{ZK:"Zubrowka"}];var ew=["Amber","Ansul","Atlantis","Braavos","Busytown","Castle Rock","Centralia","Coober Pedy","Chefchaouen","Chronopolis","Damanhur","Diaspar","Dictionopolis","Diomira","El Dorado","Elista","Ephesus","Gotham","Hadleyburg","Hallstatt","Hierusalem","Ilium","Inverness","Kowloon","Laputa","Longyearbyen","Lys","Matmata","Maycomb","Metropolis","Miyake-jima","Monowi","Nagoro","Navarre","New New York","Nimbin","Pemberley","Pseudopolis","Rivendell","Roswell","Shangri-La","Springfield","Supilinn","Thneedville","Trantor","Wobegon","Yonwood","Xanadu","Xylar","Zion"];function Jy({count:t=1,participantsCount:e=32}={}){let r=Sr(ew),n=r.slice(0,t);return{cities:tt(0,e).map(i=>i<Math.min(t,r.length)?n[i]:yn(n))}}function Zy({count:t=1,participantsCount:e=32}={}){let r=Sr(tw),n=r.slice(0,t).map(i=>Object.keys(i)).flat();return{states:tt(0,e).map(i=>i<Math.min(t,r.length)?n[i]:yn(n))}}function tA({count:t=1,participantsCount:e=32}={}){let r=tt(0,t).map(()=>tt(0,5).map(()=>fo(0,9)).join(""));return{postalCodes:tt(0,e).map(o=>o<t?r[o]:yn(r))}}function lm({idPrefix:t,participantType:e,index:r,uuids:n}){let o=Vt(e)?e[0]:"X";return t?`${t}-${o}-${r}`:n?.pop()||Mt()}function eA(t){let{cities:e,states:r,postalCodes:n,nationalityCode:o,participantIndex:i}=t;return{postalCode:n?.[i],state:r?.[i],city:e?.[i],countryCode:o}}var rw={lastNames:["Abbey","Ahern","Ampleforth","Ananiadis","Andelic","Assange","Atreides","Austen","Bach","Banks","Barrington","Batty","Bauers","Beals","Beer","Bennett","Berry","Bonaparte","Brewer","Brockovich","Bukowski","Cassidy","Catton","Calvino","Carlin","Carson","Chip","Constant","Crane","Crowne","Cummings","Curie","Dallas","Diamond","Deckard","Drazic","Dunbar","Earhart","Eisenstein","Eldritch","Elliot","Ellul","Escher","Eyre","Faulkner","Fulcher","Fukuoka","Godel","Goldstein","Greer","Hedges","Herbert","Holmgren","Humperdinck","Huxley","Illich","Jeffers","Jensen","Jevons","Johnson","Johnstone","Jovovich","Kingsnorth","Langer","Fernwright","Fuller","Le Guin","Lem","Lovelace","Mander","McLuhan","Midgely","Mond","Montoya","Moore","Murry","Nagle","Nearing","Ogden","Ophuls","Parks","Paz","Peet","Perfect","Pendejo","Pevensie","Postman","Ripley","Rodda","Rumfoord","Runciter","Rugen","Sale","Schumacher","Shaftoe","Shelley","Shepard","Smith","Stratton","Stewart","Swift","Tillich","Turing","Tyrell","Twain","Yeats","Veblen","Yates","Vonnegut","Waterhouse","Watson","Wolin","Wirt","Waschuk","Wormwood","Zecic"],firstFemale:["Ada","Amelia","Amelie","America","Anne","Antonia","Aravis","Astrid","Beatrice","Brienne","Buttercup","Caitlin","Cimorene","Cordelia","Desdemona","Ellen","Elizabeth","Emily","Emmie","Erin","Eva","Evelyn","Heather","Helen","Hermia","Hypatia","Imogen","Jane","Jasmine","Juliana","Juliet","Katniss","Leeloo","Lenina","Lilith","Linda","Lizzie","Louise","Lucy","Marie","Mary","Martha","Matilda","Milla","Miranda","Meg","Melba","Nicole","Ola","Portia","Pris","Rachael","Rachel","Rebecca","River","Rosa","Rosalind","Scout","Sharn","Susanne","Titania","Uhura","Ursula","Valentina","Viola","Virginia","Xena","Zoe"],firstMale:["Alan","Aldous","August","Axel","Barda","Barry","Bill","Bruce","Charles","Chris","Constantine","Darwin","David","Derrick","Edward","Emmanuel","Ernst","Estlin","Fezzik","Filby","Frank","Frito","George","Glen","Helmholtz","Inigo","Italo","Ivan","Jacques","James","Jared","Jerry","Joe","Johann","Julian","John Michael","Jonathan","Korben","Kirkpatrick","Kurt","Lief","Malachi","Mark","Marhsall","Masanobu","Maurits","Michael","Miro","Mustapha","Neil","Nikola","Octavio","Palmer","Paul","Pierre","Robinson","Rick","Rincewind","Roy","Shannon","Sheldon","Stafford","Stanislaw","Stanley","Syme","Thorstein","Thomas","Tyrone","Vizzini","Walton","Walker","Warren","Wendell","Westley","William","Winston","Zoran"]};function rA(t){let{count:e=100,sex:r}=t||{};if(!e||r&&![zt,oe].includes(r))return{personData:[],error:V};let n=Math.ceil(e*1.3),{lastNames:o,firstFemale:i,firstMale:s}=rw,a=ri.map(({iso:I})=>I).filter(Boolean),c=Math.ceil(n/o.length),u=Math.ceil(n/i.length),p=Math.ceil(n/s.length),m=tt(0,c).flatMap(()=>{let I=J(o,!1,!0);return tt(0,o.length).map(()=>Zr(I))}),d=tt(0,u).flatMap(()=>{let I=J(i,!1,!0);return tt(0,i.length).map(()=>Zr(I))}),l=tt(0,p).flatMap(()=>{let I=J(s,!1,!0);return tt(0,s.length).map(()=>Zr(I))}),f={};for(let I=0;I<n;I++){let h=m.pop(),S=r||yn([zt,oe]),T=S===zt?l.pop():d.pop(),y=yn(a);f[`${T}${h}`]={nationalityCode:y,sex:S,firstName:T,lastName:h}}return{personData:Object.values(f).slice(0,e)}}function nA(t){let e=t?.count||1,{personExtensions:r,consideredDate:n,isMock:o=!0,gendersCount:i,personData:s,category:a,sex:c}=t||{};if(isNaN(e))return{error:V};let u=i?.[zt]||c===zt&&e||0,p=i?.[oe]||c===oe&&e||0;e=Math.max(e,u+p);let m=e-(u+p),d=u&&rA({count:u,sex:zt}).personData||[],l=p&&rA({count:p,sex:oe}).personData||[],f=[...d,...l,...m&&rA({count:m}).personData||[]],g=f.filter(U=>!c||u&&p||U.sex===c),I=[];if(Array.isArray(s)){let U=s.filter(N=>typeof N.firstName!="string"||typeof N.lastName!="string"||N.sex&&![zt,oe].includes(N.sex)||N.nationalityCode&&(typeof N.nationalityCode!="string"||N.nationalityCode.length>3||!ri.find(({iso:D,ioc:M})=>[D,M].includes(N.nationalityCode)))?!1:(N.nationalityCode&&I.push(N.nationalityCode),!0));if(U.length)g=U;else return{error:V}}let h=s?g:Sr(g);if(h.length<e){let{maleFirstNames:U,maleLastNames:N,femaleFirstNames:D,femaleLastNames:M,nationalityCodes:R}=f.reduce((b,v)=>{let{firstName:O,lastName:x,nationalityCode:F}=v;return v.sex===zt?(b.maleFirstNames.includes(O)||b.maleFirstNames.push(O),b.maleLastNames.includes(x)||b.maleLastNames.push(x)):(b.femaleFirstNames.includes(O)||b.femaleFirstNames.push(O),b.femaleLastNames.includes(x)||b.femaleLastNames.push(x)),b.nationalityCodes.includes(F)||b.nationalityCodes.push(F),b},{maleFirstNames:[],maleLastNames:[],femaleFirstNames:[],femaleLastNames:[],nationalityCodes:[]});tt(0,e-h.length).forEach(()=>{let b=c||yn([zt,oe]),v=yn(R),O=b===zt?yn(U):yn(D),x=b===zt?yn(N):yn(M),F={firstName:O,lastName:x,sex:b,nationalityCode:v};h.push(F)})}let{ageMinDate:S,ageMaxDate:T}=Fs({consideredDate:n,category:a}),y=dt(S?.slice(0,4)||0)||dt(T?.slice(0,4)||0)-3,E=dt(T?.slice(0,4)||0)||dt(S?.slice(0,4)||0)+3,P=(S||T)&&[y,E],A=h.slice(0,e).map((U,N)=>{let[D,M]=P||[],R=P&&Zr(tt(D,M)),b=Zr(tt(0,365)),v=R&&$C(R,b);return Object.assign(nt({extensions:r||[{name:"regionCode",value:N+1}],birthDate:v,isMock:o}),U)});return{persons:A.length&&A||h[0],nationalityCodes:I}}var nw=["Ace Academy","Avengers","Ball Bouncers","Baseliners","Captivators","Civil Disobedients","Continentals","Court Royal","Court Sharks","Diamond Dogs","Danger Zone","Doubles Dominators","Double Faults","Tricksters","Eliminators","Court Crusaders","Fuzz Busters","Game Changers","Goal Gurus","Good Volley","Green Machine","Hawk Eyes","Inside Outers","Killer Instinct","Line Toers","Masters of Mayhem","Matter Catchers","Cheap Shot","Mean Machines","Mindspace Invaders","Net Centric","Net Positive","Smash Mullet","Over Your Head","Spin Meisters","Aggressors","Racket Machine","Slice Happy","Refs Nightmare","Sandeaters","Sun Seekers","Slicer Dicers","Stacked Deck","Cross Stringers","The Emergence","Total Demolition","Touch and Go","Unreturnables","Upside Downers","Vertically Challenged","Visual Spectacle"];function fm({nameRoot:t="TEAM",count:e=1}={}){let n=Sr(nw).slice(0,e);return n.length<e&&tt(0,e-n.length).forEach(o=>n.push(`${t} ${o+1}`)),{names:n}}function aa(t){let{scaledParticipantsCount:e,rankingRange:r}=t,{ratingsParameters:n=we,valuesInstanceLimit:o,ratingsValues:i=[],consideredDate:s,categories:a,category:c,nationalityCodesCount:u,nationalityCodeType:p,nationalityCodes:m,participantsCount:d=32,participantType:l,teamSize:f=8,personIds:g,idPrefix:I,uuids:h,personExtensions:S,addressProps:T,gendersCount:y,matchUpType:E,personData:P,sex:A,inContext:U,withISO2:N,withIOC:D,scaleAllParticipants:M}=t,R=l===ft||E===_i,b=l===Ft||E===Ft;r&&(!Array.isArray(r)||!r.every(te=>Zt(te))||r.length!==2)&&(r=void 0),e=M?d:e;let v=1e3,O=e&&e>v?e:v;r=r||[1,O],r[1]+=1;let x=d*(R&&2||b&&(f??8)||1),F=nA({count:x,personExtensions:S,consideredDate:s,gendersCount:y,personData:P,category:c,sex:A});if(F.error)return F;let{nationalityCodes:w,persons:L}=F,G={},k={},H={},W={},q=te=>{Object.assign(G,te.doublesRankings),Object.assign(k,te.singlesRankings),Object.assign(W,te.doublesRatings),Object.assign(H,te.singlesRatings)};if(ht(c)){let te=ow({scaledParticipantsCount:e,ratingsParameters:n,participantType:l,ratingsValues:i,rankingRange:r,category:c});q(te)}Array.isArray(a)&&a.forEach(te=>{let Dt=ow({scaledParticipantsCount:e,ratingsParameters:n,participantType:l,ratingsValues:i,rankingRange:r,category:te});q(Dt)});let Y=ri.filter(te=>p==="IOC"&&te.ioc||te.iso);function B(te){let Dt=Math.ceil(x/te);return o&&Dt>o?Math.ceil(x/o):te}let{postalCodesProfile:K,postalCodesCount:X,statesProfile:j,citiesProfile:ot,citiesCount:z,statesCount:Q}=T||{},ut=te=>Object.keys(te).map(Dt=>tt(0,j[Dt]).map(()=>Dt)).flat(),it=ot&&ut(ot)||T?.cities||Jy({count:z||x,participantsCount:x}).cities,Et=j&&ut(j)||T?.states||Zy({count:Q||x,participantsCount:x}).states,_t=K&&ut(K)||T?.postalCodes||tA({count:X||x,participantsCount:x}).postalCodes,Ae={cities:it,states:Et,postalCodes:_t},$t=B(u),Se=$t?Sr(Y).slice(0,u):m&&Y.filter(te=>m.includes(te.iso))||Y,Or=Sr(tt(0,Math.ceil(x/($t||1))).map(()=>Se).flat(1/0)),pn=fm({count:d}).names;return{participants:tt(0,d).map(te=>{let Dt=R&&2||b&&(f??8)||1,ue=tt(0,Dt).map(qt=>{let ar=te*Dt+qt;return Xe(ar)}),pe=ue.map(qt=>qt.participantId),Fe=ue.map(qt=>qt.person.standardFamilyName).join("/"),ee=R?ft:Ft,Je={participantId:lm({participantType:ee,index:te,idPrefix:I,uuids:h}),participantName:R?Fe:pn[te],participantRole:xe,individualParticipantIds:pe,participantType:ee};return U&&(Je.individualParticipants=ue),R||b?[Je,...ue]:ue}).flat(),...C};function Xe(te){let Dt=L[te],{nationalityCode:ue,participantExtensions:pe,participantTimeItems:Fe,extensions:ee,firstName:Je,birthDate:qt,lastName:ar,personId:Ze,sex:Pe}=Dt||{},ae=Je||"GivenName",hr=ar||"FamilyName",_r=`${ae} ${hr}`,Kt=Or[te],De=w?.length&&ue||Kt&&(p==="IOC"?Kt.ioc||Kt.iso:Kt.iso||Kt.ioc)||ue;Or?.length&&!De&&!ue&&console.log("%c Invalid Nationality Code",{participantIndex:te,country:Kt});let fr=eA({...Ae,participantIndex:te,nationalityCode:De}),Ne=nt({participantId:lm({participantType:At,index:te,idPrefix:I,uuids:h}),extensions:pe,timeItems:Fe,participantRole:xe,participantType:At,participantName:_r,person:{personId:Ze||g?.length&&g[te]||Mt(),birthDate:Nr(qt)?qt:void 0,addresses:[fr],standardFamilyName:hr,standardGivenName:ae,nationalityCode:De,extensions:ee,sex:Pe}});if(D&&De){let me=ri.find(({iso:dr})=>dr===De);me?.ioc&&(Ne.person.iocNationalityCode=me.ioc),me?.label&&(Ne.person.countryName=me.label)}if(N&&De){let me=ri.find(({iso:dr})=>dr===De);me?.iso2&&(Ne.person.iso2NationalityCode=me.iso2),me?.label&&(Ne.person.countryName=me.label)}let On=me=>{let dr=me.categoryName||me.ratingType||me.ageCategoryCode,es=k[dr]?.[te],Tn=G[dr]?.[te];oA({scaleValue:es,eventType:ks,scaleType:Ii,participant:Ne,category:me}),oA({scaleValue:Tn,eventType:Vo,scaleType:Ii,participant:Ne,category:me});let mi=H[dr]?.[te],ca=W[dr]?.[te];oA({scaleValue:mi,eventType:ks,scaleType:hi,participant:Ne,category:me}),oA({scaleValue:ca,eventType:Vo,scaleType:hi,participant:Ne,category:me})};return Array.isArray(a)?a.forEach(me=>On(me)):c&&On(c),Ne}}function oA({scaleValue:t,participant:e,eventType:r,scaleType:n,category:o}){let i=o.categoryName||o.ratingType||o.ageCategoryCode,s=[Si,n,r,i].join("."),a={itemValue:t,itemType:s};i&&t&&(e.timeItems||(e.timeItems=[]),e.timeItems.push(a))}function ow(t){let{category:e,scaledParticipantsCount:r,ratingsParameters:n,participantType:o,ratingsValues:i=[]}=t,s=e.rankingRange||t.rankingRange||[1,1e3],a={},c={},u={},p={},{categoryName:m,ageCategoryCode:d,ratingType:l}=e,f=e.categoryName||e.ratingType||e.ageCategoryCode;if((m||d)&&!l){let[g,I]=s||[];if(c[f]=Sr(tt(g,I)).slice(0,r||fo(20,30)),[ft,Ft].includes(o)){let[h,S]=s||[];a[f]=Sr(tt(h,S)).slice(0,r||fo(20,30))}}if(l&&n[l]){let{ratingMax:g,ratingMin:I,ratingAttributes:h}=e,S={...n[l],...h||{}},{attributes:T={},decimalsCount:y,accessors:E,range:P,step:A}=S,U=O=>{let x={},F=Object.keys(O||{});for(let w of F){let L=O[w];if(typeof L=="object"&&L.generator){let{range:G}=L,[k,H]=G.slice().sort();x[w]=fo(k,H)}else x[w]=L}return x},D=P[0]>P[1]?2:.7,[M,R]=P.slice().sort(),v=tt(0,2e3).map(()=>MA(M,R,D,A,y)).filter(x=>(!g||x<=g)&&(!I||x>=I)).slice(0,r||fo(20,30)).map(x=>E?Object.assign({},...E.map(F=>({[F]:x})),U(T)):x);u[f]=[...i,...v],[ft,Ft].includes(o)&&(p[f]=[...i,...v])}return{singlesRankings:c,doublesRankings:a,singlesRatings:u,doublesRatings:p}}function Pl(t){let{alternatesCount:e=0,tieFormatName:r,drawSize:n}=t,o=0,i=0,s=0,a=0,c={},u={[zt]:0,[oe]:0,[Ar]:0,[is]:0,[Pn]:0};(ht(t.tieFormat)?t.tieFormat:no({namedFormat:r}))?.collectionDefinitions?.filter(Boolean).forEach(f=>{let{category:g,collectionId:I,matchUpType:h,matchUpCount:S,gender:T}=f;if([zt,oe].includes(T)){let y=S*(h===xt?2:1);u[T]<y&&(u[T]=y)}else T===Ar&&(u[zt]<S&&(u[zt]=S),u[oe]<S&&(u[oe]=S));if(g){let y=JSON.stringify(g);c[y]=g}if(I||(f.collectionId=Mt()),de(xt)(h)){let y=S;a+=S,o=Math.max(o,y)}if(de(kt)(h)){let y=S;s+=S,i=Math.max(i,y)}});let m=Object.keys(c).length?Math.max(s,a*2):Math.max(i,o*2),d=o*(n+e),l=i*(n+e);return{maxDoublesDraw:d,maxSinglesDraw:l,teamSize:m,genders:u}}function iw({participantsProfile:t,eventProfiles:e,drawProfiles:r}){let{participantsCount:n,participantType:o=At}=t||{},i=n||0,s={[oe]:0,[Ar]:0,[is]:0,[zt]:0,[Pn]:0},a=0,c=0,u=0,p=0,m=0,d=({alternatesCount:f=0,uniqueParticipants:g,tieFormatName:I,drawSize:h=0,eventType:S,tieFormat:T,category:y,gender:E,stage:P})=>{let A=S===qr,U=S===_e,N=!!(g||P===ct||y||E);if(U){p=Math.max(p,h+f),T=typeof T=="object"?T:no({namedFormat:I});let{teamSize:D,maxDoublesDraw:M,maxSinglesDraw:R,genders:b}=Pl({alternatesCount:f,tieFormatName:I,tieFormat:T,drawSize:h});u=Math.max(u,D),c=Math.max(c,R),N||(a=Math.max(a,M)),Object.keys(b).forEach(v=>s[v]+=b[v])}else if(A)if(N){let D=(h+f)*2;m+=D,E&&(s[E]+=D)}else h+f&&h+f>a&&(a=h+f);else if(N){let D=h+f;E&&(s[E]+=D),m+=D}else h&&h>c&&(c=h+f)};if(e?.forEach(f=>{let{tieFormatName:g,tieFormat:I,drawProfiles:h,eventType:S,category:T,gender:y}=f;if(h)for(let E of h){let{tieFormatName:P,tieFormat:A}=E;d({...E,tieFormatName:P||g,tieFormat:A||I,eventType:S,category:T,gender:y})}}),Array.isArray(r))for(let f of r)d(f);let l=Math.max(p*u,a*2,c);return a&&(o=ft),(n||i)<l&&(n=l),n&&a&&[ft,_e].includes(o)&&(c&&Math.floor(c/2)>a?n=Math.floor(c/2):(!c||a*2>=c)&&(n=Math.ceil(n/2))),n===void 0&&(n=!e?.length&&!r?.length?32:0),n<i&&(n=i),{uniqueParticipantsCount:m,participantsCount:n,largestTeamDraw:p,largestTeamSize:u,participantType:o,gendersCount:s}}function iA({participantsProfile:t,tournamentRecord:e,eventProfiles:r,drawProfiles:n,startDate:o,uuids:i}){if(t?.participantsCount===0)return{addedCount:0,...C};let{participantsCount:s,participantType:a,largestTeamDraw:c,largestTeamSize:u,gendersCount:p}=iw({participantsProfile:t,eventProfiles:r,drawProfiles:n}),m=t?.teamKey,d=aa({consideredDate:o,...t,participantsCount:s,participantType:a,gendersCount:p,uuids:i}).participants,l=0,f=Sn({tournamentRecord:e,participants:d});if(f.error)return f;if(l+=f.addedCount,m){let S=gI({tournamentRecord:e,...m});if(S.error)return S}let g=d.filter(({participantType:S})=>S===At).map(St),I=t?.idPrefix?`${Ft}-${t.idPrefix}`:void 0,h=tt(0,c).map(S=>{let T=g.slice(S*u,(S+1)*u),y=lm({index:S,participantType:a,idPrefix:I,uuids:i});return{participantName:`Team ${S+1}`,participantRole:xe,individualParticipantIds:T,participantType:Ft,participantId:y}});return f=Sn({participants:h,tournamentRecord:e}),f.error?f:(l+=f.addedCount,{addedCount:l,...C})}function sA({drawProfiles:t,category:e,gender:r}){let n={},o=t?.reduce((s,a)=>{let{qualifyingPositions:c=0,participantsCount:u=0,uniqueParticipants:p,stage:m=rt,drawSize:d=0}=a||{};Object.keys(s).includes(m)||(s[m]=0);let l=(u||d)-c;return p||r||e||m===ct?(Object.keys(n).includes(m)||(n[m]=0),n[m]+=l):s[m]=Math.max(s[m],l),s},{}),i=Object.keys(n);return i.forEach(s=>o[s]+=n[s]),{stageParticipantsCount:o,uniqueParticipantsCount:n,uniqueParticipantStages:i}}function aA({allUniqueParticipantIds:t,stageParticipantsCount:e,eventParticipantType:r,targetParticipants:n}){let o=e[rt]||0,i=e[ct]||0;return{stageParticipants:{QUALIFYING:n?.filter(({participantType:a})=>a===r).filter(({participantId:a})=>!t.includes(a)).slice(0,i),MAIN:n?.filter(({participantType:a})=>a===r).filter(({participantId:a})=>!t.includes(a)).slice(i,i+o)}}}var K1={[bt]:2,[Te]:1,[be]:1,[nr]:1,[Rt]:4};function II(t){let{defaultWithScorePercent:e=2,winningSide:r}=t,{matchUpStatusProfile:n=K1,matchUpFormat:o=Dn,pointsPerMinute:i=1,sideWeight:s=4}=t;if(!Dr({matchUpFormat:o}))return{error:ql};if(typeof n!="object")return{error:V};if(e>100&&(e=100),isNaN(e)||isNaN(i)||isNaN(s))return{error:V};let a=Object.keys(n).filter(b=>Object.keys(Yh).includes(b)&&b!==he);if(Object.keys(a).reduce((b,v)=>b+n[v],0)>100)return{error:V,matchUpStatusProfile:n};let u=a.reduce((b,v)=>(b.pointer=b.pointer+n[v],b.valueMap.push([b.pointer,v]),b),{pointer:0,valueMap:[]}),p=fo(1,100),m=(u.valueMap.find(b=>p<=b[0])??[100,he])[1],d={sets:[],scoreStringSide1:"",side2ScoreString:""};if([bt,Rt].includes(m)){r=r||fo(1,2);let b={score:d,matchUpStatus:m,winningSide:r};if(!(m===Rt&&fo(1,100)>100-e))return{outcome:b}}else if([Te,be].includes(m))return{outcome:{score:d,matchUpStatus:m}};let l=Ye(o),{bestOf:f=1,exactly:g,setFormat:I,finalSetFormat:h}=l??{},S=[],T=fo(0,1),y=r?[r-1]:[...tt(0,s).map(()=>T),1-T],P=[nr,Rt,un,as].includes(m)&&(Zr(tt(1,g||f))||1),A,U=tt(1,(g??f)+1);for(let b of U){let v=b===(g??f),{set:O,incomplete:x,winningSideNumber:F}=z1({setFormat:v&&h||I,incomplete:P===b,pointsPerMinute:i,matchUpStatus:m,weightedRange:y,setNumber:b});if(S.push(O),x){A=F;break}if(tm({matchUp:{score:{sets:S},matchUpFormat:o}}).calculatedWinningSide)break}let N=tm({matchUp:{score:{sets:S},matchUpFormat:o,winningSide:r}}),D=A?r||A:N.calculatedWinningSide,{score:M}=Ky({winningSide:D,score:{sets:S},matchUpStatus:m});return{outcome:{winningSide:D,matchUpStatus:m,score:M}}}function z1({weightedRange:t=[0,1],pointsPerMinute:e,matchUpStatus:r,incomplete:n,setFormat:o,setNumber:i}){let s={setNumber:i},{setTo:a,tiebreakFormat:c,tiebreakAt:u,tiebreakSet:p,timed:m,minutes:d}=o,l=fo(0,t.length-1),f=t[l],g;if(m){let I=d*e,h=Math.round(I*.2),S=I+Zr([1,-1])*h,T=lC(S,2),y=[T,S-T];f&&y.reverse(),g=t[l]+1;let E=y[0]>y[1]&&1||y[1]>y[0]&&2||0;if(n){let[U,N]=y;return Object.assign(s,{side1Score:U,side2Score:N}),se.includes(r)?{set:s,incomplete:n,winningSideNumber:g}:{set:s,incomplete:n}}E||(y[fo(0,1)]+=1),E=y[0]>y[1]?1:2,E!==g&&y.reverse();let[P,A]=y;return Object.assign(s,{side1Score:P,side2Score:A,winningSide:g}),{set:s}}else{if(n)return s.side1Score=fo(0,u),s.side2Score=fo(0,u),se.includes(r)&&(g=t[l]+1),{set:s,incomplete:n,winningSideNumber:g};{let I=tt(1,a+1).map(A=>tt(0,a+2-A).map(()=>A)).flat(),h=I[fo(0,I.length-1)],S=a&&qg({isSide1:!0,tiebreakAt:u,lowValue:h,setTo:a}),T=!S,y=t.length===1&&t[l]+1;if(!T){y?(S[0]>S[1]?1:2)!==y&&S.reverse():f&&S.reverse();let[A,U]=S;Object.assign(s,{side1Score:A,side2Score:U})}let E=Gu({matchUpScoringFormat:{setFormat:o},setObject:s}),P;if(E.hasTiebreakCondition||T){let{NoAD:A,tiebreakTo:U}=c||p||{},N=tt(1,U+1).map(R=>tt(0,U+2-R).map(()=>R)).flat(),D=N[fo(0,N.length-1)],M=zp({isSide1:!0,tiebreakNoAd:A,tiebreakTo:U,lowValue:D});if(M)if(T){let R=M[0]>M[1]?1:2;y?R!==y&&M.reverse():f&&M.reverse(),[s.side1TiebreakScore,s.side2TiebreakScore]=M,P=M[0]>M[1]&&1||M[1]>M[0]&&2||void 0}else E.leadingSide===2?[s.side1TiebreakScore,s.side2TiebreakScore]=M:[s.side2TiebreakScore,s.side1TiebreakScore]=M}s.winningSide=E.winningSide||E.leadingSide||y||P}}return{set:s}}function Dl(t){let{matchUpStatusProfile:e,completeAllMatchUps:r,randomWinningSide:n,tournamentRecord:o,completionGoal:i,drawDefinition:s,event:a}=t;if(!s)return{error:Z};let c=t.matchUpFormat||s.matchUpFormat||a?.matchUpFormat,u=s.structures.slice().sort(yi),p=0,{matchUps:m,matchUpsMap:d}=ce({matchUpFilters:{matchUpTypes:[Wt],roundNumbers:[1]},contextFilters:{stages:[rt,ct]},inContext:!0,drawDefinition:s});if(m?.length){let h=a?.category?.ageCategoryCode||a?.category?.categoryName;if(h){let T=xy({singlesOnly:!0,tournamentRecord:o,drawDefinition:s,scaleAccessor:{scaleName:h,sortOrder:nM,scaleType:Ii},event:a});if(T.error)return T;let{lineUps:y,participantsToAdd:E}=T;Sn({tournamentRecord:o,participants:E}),Ut({element:s,extension:{name:Co,value:y}})}else{let S=m[0]?.structureId,{positionAssignments:T}=Ct({drawDefinition:s,structureId:S});if(T?.length){let{participants:y}=Gt({participantFilters:{participantTypes:[Wt]},tournamentRecord:o}),E=P=>{let A=P.tieMatchUps.filter(de(kt)),U=P.tieMatchUps.filter(de(xt));A.forEach((N,D)=>{let M=N.matchUpId;N.sides.forEach(R=>{let{drawPosition:b}=R,v=y?.find(O=>{let{participantId:x}=O;return T.find(w=>w.participantId===x)?.drawPosition===b});if(v){let O=v.individualParticipantIds?.[D];O&&Sl({teamParticipantId:v.participantId,participantId:O,tournamentRecord:o,drawDefinition:s,tieMatchUpId:M,event:a})}})}),U.forEach((N,D)=>{let M=N.matchUpId;N.sides.forEach(R=>{let{drawPosition:b}=R,v=y?.find(O=>{let{participantId:x}=O;return T.find(w=>w.participantId===x)?.drawPosition===b});v&&v.individualParticipantIds?.slice(D*2,D*2+2)?.forEach(x=>{Sl({teamParticipantId:v.participantId,participantId:x,tournamentRecord:o,drawDefinition:s,tieMatchUpId:M,event:a})})})})};m.forEach(E)}}}let l=typeof r=="string"&&r,f=l&&he,g=u.length===2&&u[0].finishingPosition===gi&&jt(u.map(({stage:h})=>h),[rt,fe]).length===2,I=u.map(({structureId:h})=>h);for(let h of I){if(p>=i)break;let S=s.structures.find(E=>E.structureId===h),T=yt({contextFilters:{matchUpTypes:[xt,kt]},afterRecoveryTimes:!1,tournamentRecord:o,inContext:!0,drawDefinition:s,matchUpsMap:d,structure:S,event:a}).matchUps;T.length;let y=T.filter(({winningSide:E})=>!E).sort(Ri).map(Ue);for(let E of y){if(!isNaN(i)&&p>=i)break;let{matchUps:P}=yt({matchUpFilters:{matchUpTypes:[xt,kt]},afterRecoveryTimes:!1,tournamentRecord:o,inContext:!0,drawDefinition:s,matchUpsMap:d,structure:S,event:a}),A=P.find(N=>N.matchUpId===E),U=[Te,be].includes(A.matchUpStatus);if(A?.readyToScore&&!U){let D=Q1({matchUpStatusProfile:e,tournamentRecord:o,drawDefinition:s,targetMatchUp:A,matchUpFormat:c,matchUpStatus:f,scoreString:l,winningSide:!n&&1,event:a});if(D?.error)return D;p+=1}}g&&S.finishingPosition===gi&&t.completeRoundRobinPlayoffs&&zs({structureId:S.structureId,applyPositioning:!0,drawDefinition:s})}return{...C,completedCount:p}}function RM(t){let{matchUpStatusCodes:e,policyDefinitions:r,tournamentRecord:n,drawDefinition:o,targetMatchUp:i,matchUpStatus:s,matchUpFormat:a,scoreString:c,winningSide:u,event:p}=t;if(!i||i.matchUpStatus===Nt)return;let{matchUpId:m}=i||{},{outcome:d}=lI({matchUpFormat:a,matchUpStatus:s,scoreString:c,winningSide:u});return e&&(d.matchUpStatusCodes=e),Wu({tournamentRecord:n,policyDefinitions:r,drawDefinition:o,matchUpFormat:a,matchUpId:m,outcome:d,event:p})}function Q1(t){let{matchUpStatusProfile:e={},tournamentRecord:r,policyDefinitions:n,drawDefinition:o,matchUpStatus:i,matchUpFormat:s,targetMatchUp:a,scoreString:c,winningSide:u,event:p}=t;if(c||i)return RM(t);let{matchUpId:m}=a||{},{outcome:d}=II({matchUpStatusProfile:e,matchUpFormat:s,winningSide:u});return Wu({policyDefinitions:n,tournamentRecord:r,drawDefinition:o,matchUpFormat:s,matchUpId:m,outcome:d,event:p})}function cA({matchUpStatusProfile:t,completeAllMatchUps:e,randomWinningSide:r,tournamentRecord:n,drawProfiles:o,isMock:i,event:s}){let a=Ht({event:s}).flightProfile,{eventName:c,eventType:u,category:p}=s,{startDate:m}=n,d=[],l=p?.categoryName||p?.ageCategoryCode||p?.ratingType,f=s.drawDefinitions?.map(({drawId:g})=>g);if(Array.isArray(a?.flights))for(let[g,I]of a.flights.entries()){let{drawId:h,stage:S,drawName:T,drawEntries:y}=I;d.push(I.drawId);let E=o[g],{seedsCount:P,generate:A=!0}=E||{};if(A){let U=y.filter(Br(io)).map(Br(io)),N=l||c;if(n&&P&&P<=U.length&&tt(1,P+1).forEach((x,F)=>{let w={scaleValue:x,scaleName:N,scaleType:To,eventType:u,scaleDate:m},L=U[F];Mc({tournamentRecord:n,participantId:L,scaleItem:w})}),f?.includes(h))break;let D=wa({...E,matchUpType:u,seedingScaleName:N,tournamentRecord:n,drawEntries:y,drawName:T,drawId:h,isMock:i,event:s,stage:S});if(D.error)return{error:D.error,drawIds:[]};let{drawDefinition:M}=D;if(!M)return{error:Cr};let R=o[g]?.drawExtensions;if(Array.isArray(R)&&R.filter(kn).forEach(O=>Ut({element:M,extension:O})),D=vc({suppressNotifications:!0,tournamentRecord:n,drawDefinition:M,event:s}),D.error)return{error:D.error,drawIds:[]};if(E?.withPlayoffs){let O=M.structures?.[0].structureId,x=Bp({idPrefix:E.idPrefix,...E.withPlayoffs,tournamentRecord:n,drawDefinition:M,structureId:O,isMock:i,event:s});if(x?.error)return x}let b=E?.completionGoal;if(!(E?.automated===!1)&&(e||b)){let O=E?.matchUpFormat,x=Dl({completeAllMatchUps:!b&&e,matchUpStatusProfile:t,randomWinningSide:r,tournamentRecord:n,completionGoal:b,drawDefinition:M,matchUpFormat:O,event:s});if(x.error)return{error:x.error,drawIds:[]};let F=x.completedCount;if(E?.drawType===So){let w=M.structures?.find(k=>k.stage===rt);if(!w)return{error:wt};let L=zs({structureId:w.structureId,tournamentRecord:n,drawDefinition:M,event:s});if(L.error)return{error:L.error,drawIds:[]};let G=b?b-(F??0):void 0;if(L=Dl({completeAllMatchUps:!b&&e,completionGoal:b?G:void 0,matchUpStatusProfile:t,randomWinningSide:r,tournamentRecord:n,drawDefinition:M,matchUpFormat:O,event:s}),L.error)return{error:L.error,drawIds:[]}}}}}return{...C,drawIds:d}}function uA(t){let{participantsProfile:e={},uniqueParticipantsCount:r,ratingsParameters:n,tournamentRecord:o,eventProfile:i,eventIndex:s,event:a,uuids:c}=t,{category:u,gender:p,eventType:m}=a,d=de($n)(m)&&At||de(qr)(m)&&ft||m,l=r[rt]||0,f=r[ct]||0,g=i.drawProfiles?.length?l+f:i.participantsProfile?.participantsCount??0,I=[zt,oe].includes(p)?p:void 0,h=e?.idPrefix?`E-${s}-${e?.idPrefix}`:void 0,{participants:S}=aa({uuids:i.uuids||c,...e,scaledParticipantsCount:i.scaledParticipantsCount,consideredDate:o?.startDate,rankingRange:i.rankingRange,participantType:d,participantsCount:g,ratingsParameters:n,category:u,idPrefix:h,sex:I}),y=Sn({tournamentRecord:o,participants:S});if(y.error)return y;let E=S?.filter(({participantType:A})=>A===d),P=S?.map(St);return{uniqueDrawParticipants:E,uniqueParticipantIds:P}}function sw({autoEntryPositions:t,tournamentRecord:e,drawParticipants:r,drawProfile:n,event:o}){let{drawType:i=ho,qualifyingPositions:s=0,stage:a=rt,drawSize:c=0,drawName:u,drawId:p}=n,m=c-s,d=r.slice(0,m).map(St);if(d.length){let g=Vn({participantIds:d,autoEntryPositions:t,entryStage:a,tournamentRecord:e,event:o});if(g.error)return g}let l=d.map(g=>({entryStatus:kr,entryStage:a,participantId:g})),f=rm({drawName:u||i,qualifyingPositions:s,drawEntries:l,drawId:p,event:o,stage:a});return f.error?f:{...C}}function pA({uniqueDrawParticipants:t,autoEntryPositions:e,stageParticipants:r,tournamentRecord:n,drawProfiles:o,category:i,gender:s,event:a}){let c=0;for(let u of o){let{qualifyingPositions:p=0,uniqueParticipants:m,stage:d=rt,drawSize:l=0}=u,f=l-p,g=m||s||i||d===ct,I=g?t.slice(c,c+f):r[d||rt]||[];g&&(c+=f);let h=sw({autoEntryPositions:e,drawParticipants:I,tournamentRecord:n,drawProfile:u,event:a});if(h.error)return h}return{...C}}function mA(t){let{allUniqueParticipantIds:e,matchUpStatusProfile:r,participantsProfile:n,completeAllMatchUps:o,autoEntryPositions:i,hydrateCollections:s,randomWinningSide:a,ratingsParameters:c,tournamentRecord:u,eventProfile:p,eventIndex:m,publish:d,isMock:l,uuids:f}=t,g=p.gender,I=p.eventName,{eventType:h=$n,policyDefinitions:S,drawProfiles:T=[],eventExtensions:y,surfaceCategory:E,tieFormatName:P,processCodes:A,discipline:U,eventLevel:N,timeItems:D,ballType:M,category:R}=p,b=p.eventId||Mt(),v=p.tieFormat||(h===_e?no({namedFormat:P,event:{eventId:b,category:R,gender:g},hydrateCollections:s,isMock:l}):void 0),O=u.participants;for(let j of T)!g&&j.gender&&(g=j?.gender);let{stageParticipantsCount:x,uniqueParticipantsCount:F,uniqueParticipantStages:w}=sA({drawProfiles:T,category:R,gender:g}),L=de($n)(h)&&At||de(qr)(h)&&ft||h,{uniqueDrawParticipants:G=[],uniqueParticipantIds:k=[]}=w?uA({event:{eventType:h,category:R,gender:g},uniqueParticipantsCount:F,participantsProfile:n,ratingsParameters:c,tournamentRecord:u,eventProfile:p,eventIndex:m,uuids:f}):{},{eventAttributes:H}=p;typeof H!="object"&&(H={});let W=R?.categoryName||R?.ageCategoryCode||R?.ratingType;I=I||W||"Generated Event";let q={...H,surfaceCategory:E,processCodes:A,discipline:U,eventLevel:N,eventName:I,eventType:h,tieFormat:v,ballType:M,category:R,eventId:b,gender:g};if(y?.length&&Array.isArray(y)){let j=y.filter(kn);j?.length&&Object.assign(q,{extensions:j})}if(Array.isArray(D)&&D.forEach(j=>Xi({event:K,timeItem:j})),typeof S=="object")for(let j of Object.keys(S))Ji({policyDefinitions:{[j]:S[j]},event:q});q.category&&(q.category.categoryName=W);let Y,B=na({suppressNotifications:!1,internalUse:!0,tournamentRecord:u,event:q});if(B.error)return B;let K=B?.event,{stageParticipants:X}=aA({allUniqueParticipantIds:e,stageParticipantsCount:x,eventParticipantType:L,targetParticipants:O});if(T?.length){let j=pA({uniqueDrawParticipants:G,autoEntryPositions:i,stageParticipants:X,tournamentRecord:u,drawProfiles:T,category:R,gender:g,event:K});if(j.error)return j;let ot=cA({matchUpStatusProfile:r,completeAllMatchUps:o,randomWinningSide:a,tournamentRecord:u,drawProfiles:T,isMock:l,event:K});if(ot.error)return ot;Y=ot.drawIds}else if(p?.participantsProfile?.participantsCount){let j=G.map(St);if(j.length){let ot=Vn({participantIds:j,autoEntryPositions:i,tournamentRecord:u,entryStage:rt,event:K});if(ot.error)return ot}}return d&&ia({tournamentRecord:u,event:K}),{drawIds:Y,eventId:b,uniqueParticipantIds:k}}function hI({tournamentRecords:t,scheduleDate:e,venueId:r,round:n}){if(!Nr(e))return{error:je};let o="addSchedulingProfileRound",{extension:i}=mt({name:ya,tournamentRecords:t,discover:!0}),s=i?.value||[],a=s.find(l=>qn(e,l.scheduleDate));if(!a){let{startDate:l,endDate:f}=Jd({tournamentRecords:t}),g=new Date(e);if(l&&g<new Date(l)||f&&g>new Date(f))return{error:je};a={scheduleDate:e,venues:[]},s.push(a)}let c=a.venues.find(l=>l.venueId===r);c||(c={venueId:r,rounds:[]},a.venues.push(c));let u=["notBeforeTime"],p=l=>Object.keys(l).filter(f=>!u.includes(f)).sort().map(f=>ht(l[f])?p(l[f]):l[f]).flat().join("|");if(c.rounds.find(l=>p(l)===p(n)))return _({result:{error:YA},stack:o});c.rounds.push(n);let d=Cc({tournamentRecords:t,schedulingProfile:s});return d.error?d:{...C}}function aw({schedulingProfile:t,tournamentRecord:e}){if(typeof t!="object")return{error:V};let r=cs({tournamentRecord:e}).containedStructures,n=ye({tournamentRecord:e}).matchUps??[],{tournamentId:o}=e,i=[];for(let s of t){let{scheduleDate:a,venues:c=[]}=s;for(let u of c){let{rounds:p,venueId:m}=u;for(let d of p){let{drawId:l,winnerFinishingPositionRange:f,roundSegment:g}=d,h=n.filter(S=>{let T=f?.indexOf("-")>0&&f.split("-").map(E=>+E),y=S.finishingPositionRange?.winner;return S.drawId===l&&(!d.roundNumber||S.roundNumber===d.roundNumber)&&(!y||!T||jt(y,T).length===2||pt(y).length===pt(T).length&&jt(y,T).length===pt(y).length)})[0];if(h){let{eventId:S,roundNumber:T,drawName:y,structureName:E,roundName:P}=h,A=h.structureId;T&&!f&&(A=Object.keys(r).find(D=>r[D].includes(A))??A);let U={tournamentId:o,structureId:A,roundNumber:T,roundSegment:g,eventId:S,drawId:l},N=hI({tournamentRecords:{[o]:e},round:U,scheduleDate:a,venueId:m});if(N.error)return N;i.push({structureName:E,roundName:P,drawName:y,...U})}}}}return{scheduledRounds:i}}function gm(t){let e=et(t,[{drawProfile:!0,_ofType:Kr}]);if(e.error)return e;let{allUniqueParticipantIds:r=[],participantsProfile:n={},matchUpStatusProfile:o,completeAllMatchUps:i,autoEntryPositions:s,hydrateCollections:a,randomWinningSide:c,ratingsParameters:u,tournamentRecord:p,isMock:m=!0,drawProfile:d,startDate:l,drawIndex:f,uuids:g}=t,I=J(d,!1,!0),{excessParticipantAlternates:h=!0,matchUpFormat:S=Dn,drawType:T=ho,tournamentAlternates:y=0,alternatesCount:E=0,qualifyingPositions:P,qualifyingProfiles:A,generate:U=!0,eventExtensions:N,drawExtensions:D,completionGoal:M,tieFormatName:R,buildTeams:b,seedsCount:v,timeItems:O,drawName:x,category:F,idPrefix:w,publish:L,gender:G,stage:k}=I,H=I.drawSize||(I.ignoreDefaults?void 0:32),W=I.eventId||Mt(),q=d.eventType||d.matchUpType||$n,Y=q===qr?ft:At,B=ht(d.tieFormat)&&d.tieFormat||q===Ft&&no({event:{eventId:W,category:F,gender:G},namedFormat:R,hydrateCollections:a,isMock:m})||void 0,K=F?.categoryName||F?.ageCategoryCode||F?.ratingType,X=d.eventName||K||`Generated ${q}`,j=p?.participants||[],ot=(A?.map(Dt=>Dt.structureProfiles||[]).flat().reduce((Dt,ue)=>{let pe=!ue.participantsCount||ue.participantsCount>ue.drawSize?ue.drawSize:ue.participantsCount||0;return Dt+pe},0)||0)*(Y===ft?2:1),z=(!d.participantsCount||d.participantsCount>H?H:d.participantsCount)||0,Q={eventName:X,eventType:q,tieFormat:B,category:F,eventId:W,gender:G};Array.isArray(O)&&O.forEach(Dt=>Xi({event:Q,timeItem:Dt}));let{eventAttributes:ut}=d;if(typeof ut!="object"&&(ut={}),Object.assign(Q,ut),N?.length&&Array.isArray(N)){let Dt=N.filter(kn);Dt?.length&&Object.assign(Q,{extensions:Dt})}let it=[];if(n?.participantsCount===0||d.uniqueParticipants||ot||!p||G||F){let Dt=(z||0)+E+ot,ue=Dt,pe={[zt]:0,[oe]:0},Fe,ee;q===Ft&&({teamSize:Fe,genders:ee}=Pl({alternatesCount:E,tieFormatName:R,tieFormat:B,drawSize:H}),Object.keys(ee).forEach(Ze=>{[zt,oe].includes(Ze)&&ee[Ze]&&(pe[Ze]=H*ee[Ze])}),ue=Fe*((H||0)+ot));let Je=n?.idPrefix?`D-${f}-${n?.idPrefix}`:void 0,ar=aa({...n,scaledParticipantsCount:d.scaledParticipantsCount||n.scaledParticipantsCount,participantsCount:ue,consideredDate:p?.startDate,sex:G||n?.sex,rankingRange:d.rankingRange,uuids:d.uuids||g,ratingsParameters:u,participantType:Y,gendersCount:pe,idPrefix:Je,category:F}).participants;if(Q.category&&(Q.category.categoryName=K),p){let Ze=Sn({participants:ar,tournamentRecord:p});if(Ze.error)return Ze}if(ar.forEach(({participantId:Ze})=>it.push(Ze)),j=ar,q===Ft){let Ze=ee[zt]?ar.filter(({participantType:me,person:dr})=>me===At&&dr?.sex===zt).map(St):[],Pe=ee[oe]?ar.filter(({participantType:me,person:dr})=>me===At&&dr?.sex===oe).map(St):[],ae=ar.filter(({participantType:me})=>me===At).map(St).filter(me=>!Ze.includes(me)&&!Pe.includes(me)),hr=[...I.teamNames??[],...fm({count:Dt}).names],_r=Fe-(ee[zt]+ee[oe]),Kt=0,De=0,fr=0,Ne=tt(0,Dt).map(me=>{let dr=Pe.slice(Kt,Kt+ee[oe]),es=Ze.slice(De,De+ee[zt]),Tn=ae.slice(fr,fr+_r);Kt+=ee[oe],De+=ee[zt],fr+=_r;let mi=b!==!1?[...dr,...es,...Tn]:[];return{participantName:hr[me]||`Team ${me+1}`,participantOtherName:`TM${me+1}`,participantRole:xe,individualParticipantIds:mi,participantType:Ft,participantId:Mt()}}),On=Sn({participants:Ne,tournamentRecord:p});if(!On.success)return On;j=Ne}}let Et=Dt=>{let{participantType:ue}=Dt;return de($n)(q)&&ue===At||de(qr)(q)&&ue===ft?!0:q===Ft&&ue===Ft},_t=Dt=>!d.gender||Dt.person?.sex===d.gender?!0:Dt.individualParticipantIds?.some(ue=>{let pe=j.find(Fe=>Fe.participantId===ue);return pe&&_t(pe)}),Ae=j.filter(Et).filter(_t).filter(({participantId:Dt})=>!r.includes(Dt)),$t=Ae.slice(0,z).map(Dt=>Dt.participantId);if(m&&$t?.length){let Dt=Vn({autoEntryPositions:s,entryStage:k,tournamentRecord:p,participantIds:$t,event:Q});if(Dt.error)return Dt}let Se=ot?Ae.slice(z,z+ot).map(Dt=>Dt.participantId):0;if(m&&Se?.length){let Dt=0,ue=1,pe=(ee,Je)=>ee.stageSequence-Je.stageSequence,Fe=(ee,Je)=>ee.roundTarget-Je.roundTarget;for(let ee of A.sort(Fe)){ue=ee.roundTarget||ue;let Je=1,qt;for(let ar of ee.structureProfiles.sort(pe)){let Pe=(ar.drawSize||ym(ar.participantsCount))-(qt||0),ae=Se.slice(Dt,Dt+Pe),hr=Vn({entryStage:ct,entryStageSequence:Je,autoEntryPositions:s,tournamentRecord:p,participantIds:ae,roundTarget:ue,event:Q});if(hr.error)return hr;qt=ar.qualifyingPositions,Dt+=Pe,Je+=1}ue+=1}}let Or=h&&p?.participants?.filter(({participantId:Dt})=>!$t.includes(Dt)).filter(Et).filter(_t).slice(0,E||H-z||y).map(Dt=>Dt.participantId);if(m&&Or?.length){let Dt=Vn({participantIds:Or,autoEntryPositions:!1,entryStatus:rn,tournamentRecord:p,event:Q});if(Dt.error)return Dt.error}let pn=K||X;p&&v&&v<=$t.length&&tt(1,v+1).forEach((ue,pe)=>{let Fe={scaleName:pn,scaleDate:l,scaleType:ag,scaleValue:ue,eventType:q},ee=$t[pe];Mc({tournamentRecord:p,participantId:ee,scaleItem:Fe})});let Ir=wa({...J(d,!1,!0),tournamentRecord:p,seedingScaleName:pn,matchUpFormat:S,eventId:W,isMock:m,event:Q});if(Ir.error)return Ir;if(!Ir.drawDefinition)return{error:Cr};let{drawDefinition:Xe}=Ir,te=Xe.drawId;if(Array.isArray(D)&&D.filter(kn).forEach(Dt=>Ut({element:Xe,extension:Dt})),U){if(vc({drawDefinition:Xe,event:Q,suppressNotifications:!0}),d.withPlayoffs){let ue=Xe.structures?.[0].structureId,pe=Bp({...d.withPlayoffs,tournamentRecord:p,drawDefinition:Xe,structureId:ue,idPrefix:w,isMock:m,event:Q});if(pe?.error)return pe}let Dt=d.automated===!1;if(m&&!Dt){let ue=pe=>{let Fe=Dl({completeAllMatchUps:pe.completeAllMatchUps,completionGoal:pe.completionGoal,matchUpStatusProfile:o,randomWinningSide:c,tournamentRecord:p,drawDefinition:Xe,matchUpFormat:S,event:Q});if(Fe.error)return Fe;let ee=Fe.completedCount;if(T===So){let Je=Xe.structures?.find(Ze=>Ze.stage===rt);if(!Je)return{error:wt};zs({structureId:Je.structureId,tournamentRecord:p,drawDefinition:Xe,event:Q});let qt=M?M-(ee??0):void 0,ar=Dl({completionGoal:M?qt:void 0,matchUpStatusProfile:o,completeAllMatchUps:i,randomWinningSide:c,tournamentRecord:p,drawDefinition:Xe,matchUpFormat:S,event:Q});if(ar.error)return ar}};if(M&&ue({completionGoal:M}),d.outcomes){let{matchUps:pe}=ir({inContext:!0,drawDefinition:Xe,event:Q});for(let Fe of d.outcomes){let{matchUpStatus:ee=he,matchUpStatusCodes:Je,stageSequence:qt=1,matchUpIndex:ar=0,structureOrder:Ze,matchUpFormat:Pe,drawPositions:ae,roundPosition:hr,stage:_r=rt,roundNumber:Kt,winningSide:De,scoreString:fr}=Fe,Ne=pe?.reduce((Tn,mi)=>{let{structureId:ca,matchUpId:Ku}=mi;return Tn[ca]?Tn[ca].push(Ku):Tn[ca]=[Ku],Tn},{})??[],On=Object.assign({},...Object.keys(Ne).map((Tn,mi)=>({[Tn]:mi+1}))),dr=pe?.filter(Tn=>(!_r||Tn.stage===_r)&&(!qt||Tn.stageSequence===qt)&&(!Kt||Tn.roundNumber===Kt)&&(!hr||Tn.roundPosition===hr)&&(!Ze||On[Tn.structureId]===Ze)&&(!ae||jt(ae,Tn.drawPositions).length===2))?.[ar],es=RM({matchUpStatusCodes:Je,tournamentRecord:p,drawDefinition:Xe,targetMatchUp:dr,matchUpFormat:Pe,matchUpStatus:ee,scoreString:fr,winningSide:De});if(es?.error)return es}}i&&ue({completeAllMatchUps:i})}L&&ia({tournamentRecord:p,event:Q})}else{let Dt=rm({drawEntries:Xe.entries,drawName:x||T,qualifyingPositions:P,drawId:te,event:Q,stage:k});if(Dt.error)return Dt}return{...C,event:nt(Q),uniqueParticipantIds:it,targetParticipants:j,drawDefinition:Xe,eventId:W,drawId:te}}var CM=()=>({altitude:void 0,courtId:void 0,courtName:"",courtDimensions:void 0,latitude:void 0,longitude:void 0,surfaceCategory:void 0,surfaceType:void 0,surfacedDate:void 0,dateAvailability:[],onlineResources:[],pace:void 0,notes:void 0}),cw=CM;function dA(t){return parseInt(t)}function bM({startTime:t="",endTime:e=""}={}){if(!t||!e||!ws.test(t)||!ws.test(e))return!1;let[r,n]=t.split(":").map(dA),[o,i]=e.split(":").map(dA);return o<r?!1:!(r===o&&i<n)}function uw(t,e){let[r,n]=t.startTime.split(":").map(dA),[o,i]=e.startTime.split(":").map(dA);return r<o?-1:r>o?1:n<i?-1:n>i?1:0}function lA({dateAvailability:t}){if(!t)return{error:sE};if(!Array.isArray(t))return{error:Ql};let e="Dates must be formated => YYYY-MM-DD",r="Times must be 24 hour => 00:00";for(let n of t){if(typeof n!="object")return{error:Ql};let{date:o,startTime:i,endTime:s,bookings:a=[]}=n;if(!i||!s)return{error:Ql};if(o&&!No.test(o))return{error:je,dateAvailability:{date:o},info:e};if(!ws.test(i))return{error:Po,dateAvailability:{startTime:i},info:r};if(!ws.test(s))return{error:Po,dateAvailability:{endTime:s},info:r};if(i===s)return{error:Po,dateAvailability:{startTime:i,endTime:s},info:"startTime and endTime are equivalent"};if(!bM({startTime:i,endTime:s}))return{error:Po,dateAvailability:{startTime:i,endTime:s},info:"endTime must be after startTime"};if(a){if(!Array.isArray(a))return{error:Pm};for(let c of a){if(typeof c!="object")return{error:Pm};let{startTime:u,endTime:p}=c;if(!ws.test(u))return{error:Po,booking:{startTime:u},info:r};if(!ws.test(p))return{error:Po,booking:{endTime:p},info:r};if(u===p)return{error:Po,dateAvailability:{startTime:u,endTime:p},info:"startTime and endTime are equivalent"};if(!bM({startTime:u,endTime:p}))return{error:Po,dateAvailability:{startTime:u,endTime:p},info:"endTime must be after startTime"}}}}return{valid:!0}}function Nl({tournamentRecord:t,disableNotice:e,venueId:r,courtId:n,court:o}){let{venue:i}=qo({tournamentRecord:t,venueId:r});if(!i)return{error:ki};i.courts||(i.courts=[]);let s={...CM(),venueId:r,courtId:n};if(s.courtId||(s.courtId=Mt()),i.courts.some(c=>c.courtId===s.courtId))return{error:EE};{let c=(o?.dateAvailability||[]).map(m=>({...m,date:Pt(m.date),startTime:Qt(m.startTime),endTime:Qt(m.endTime),bookings:m.bookings?.map(({startTime:d,endTime:l,bookingType:f})=>({startTime:Qt(d),endTime:Qt(l),bookingType:f}))})),u=Object.keys(s);for(let m of u)if(o?.[m])if(m==="dateAvailability"){let d=lA({dateAvailability:c});if(!d.valid&&d.error)return d;s.dateAvailability=c}else s[m]=o[m];let p=s;return i.courts.push(p),e||lt({payload:{venue:i,tournamentId:t.tournamentId},topic:Ei,key:i.venueId}),{...C,court:J(s),venueId:r}}}function SI(t){let{tournamentRecord:e,venueId:r}=t;if(typeof r!="string"||!r)return{error:ti};let n=t.tournamentRecords??(e&&{[e.tournamentId]:e})??{},o=[],i;for(let s of Object.values(n)){let{venue:a}=qo({tournamentRecord:s,venueId:r});if(a){let c=X1({...t,tournamentRecord:s});for(let u of c?.courts??[])o.push(u?.courtId);if(c.error)return c;i=!0}}return i?{...C,courtIds:o}:{error:ki}}function X1({courtNameRoot:t="Court",dateAvailability:e=[],venueAbbreviationRoot:r,tournamentRecord:n,courtNames:o=[],courtTimings:i,courtsCount:s,startTime:a,courtIds:c,endTime:u,idPrefix:p,venueId:m,dates:d}){if(!m)return{error:ti};let l=qo({tournamentRecord:n,venueId:m});if(l.error)return l;let{venue:f}=l;if(!Zt(s)||!o)return{error:AE};s=s??o.length;let h=tt(0,s).map(S=>{let T=i?.[S],y=T?d.map(E=>({date:Yn(E),startTime:a,endTime:u,...T})):e;return T&&a&&u&&y.push({startTime:a,endTime:u}),{courtName:o[S]||r&&f?.venueAbbreviation&&`${f?.venueAbbreviation} ${S+1}`||`${t} ${S+1}`,dateAvailability:y}}).map((S,T)=>{let y=c?.pop()||p&&`${p}-${T+1}`;return Nl({disableNotice:!0,tournamentRecord:n,courtId:y,venueId:m,court:S})}).map(S=>S.court).filter(Boolean);return h.length!==s?_({info:"not all courts could be generated",result:{error:V}}):(f&&lt({payload:{venue:f,tournamentId:n.tournamentId},topic:Ei,key:f.venueId}),{...C,courts:J(h)})}function Ml({tournamentRecord:t,ignoreExistingVenues:e,venueProfiles:r,uuids:n}){let{startDate:o,endDate:i}=t,s=[];for(let[a,c]of r.entries()){let{venueAbbreviation:u,venueId:p=n?.pop()??Mt(),dateAvailability:m,startTime:d="07:00",endTime:l="19:00",courtTimings:f,courtsCount:g,courtNames:I,venueName:h,idPrefix:S,courtIds:T}=c,y={venueName:h||`Venue ${a+1}`,venueAbbreviation:u,venueId:p},E=lc({tournamentRecord:t,venue:y});if(E.error){if(e)continue;return E}s.push(p);let P=Ls(o,i),A=!Array.isArray(m)&&[{startTime:d,endTime:l}].concat(P.map(U=>({date:Yn(U),startTime:d,endTime:l})));if(g||I){let U=SI({dateAvailability:m||A,tournamentRecord:t,courtTimings:f,courtsCount:g,courtNames:I,startTime:d,idPrefix:S,courtIds:T,endTime:l,venueId:p,dates:P});if(U.error)return U}}return s}function pw(t){let{tournamentRecord:e,leagueProfiles:r,eventIds:n,venueIds:o,drawIds:i,allUniqueParticipantIds:s,uuids:a}=t,c=0;for(let p of r){let m=[],{tieFormatName:d=xm,teamProfiles:l=[],teamsCount:f=0,category:g,idPrefix:I,gender:h}=p,S=p.leagueName??p.eventName??`League ${c+1}`,T=p.leagueId??p.eventId??a?.pop()??Mt();n.push(T);let y=ht(p.tieFormat)&&p.tieFormat||no({event:{eventId:T,category:g,gender:h},namedFormat:d,isMock:t.isMock})||void 0;if(!y)return{error:vs};let E=Math.max(f,l.length),P=tt(0,E),{genders:A,teamSize:U}=Pl({tieFormat:y,drawSize:E}),N={[oe]:0,[Ar]:0,[is]:0,[zt]:0,[Pn]:0};Object.keys(A).forEach(R=>N[R]+=A[R]);for(let R of P){let b=l?.[R]?.teamName??`Team ${R+1}`,v=l?.[R]?.teamId||a?.pop()||Mt(),O=p.startDate??t.startDate,x=aa({...p?.participantsProfile,participantsCount:U,consideredDate:O,gendersCount:N,category:g,gender:h,uuids:a}).participants,F=x.map(W=>W.participantId),w=Ft,L=v??lm({participantType:w,idPrefix:I,index:R,uuids:a});m.push({participantId:L,entryStatus:kr,entryStage:rt});let G=l?.[R]?.venueIds??[],k={participantId:L,participantRole:xe,participantName:b,individualParticipantIds:F,participantType:w,homeVenueIds:G};G.forEach(W=>!o.includes(W)&&o.push(W)),s.push(...F),s.push(L);let H=Sn({participants:[k,...x],tournamentRecord:e});if(H.error)return H}let M={eventName:S,entries:m,eventType:Ft,tieFormat:y,category:g,eventId:T,gender:h};if(e.events||(e.events=[]),e.events.push(M),m.length){let R=(Zt(p.roundsCount)&&p.roundsCount)??p.roundsCount===nb?(E-1)*2:E-1,b=wa({automated:p.automated,tournamentRecord:e,drawType:$r,roundsCount:R,drawSize:E,event:M});if(b.error)return b;let{drawDefinition:v}=b;if(v){let O=v?.drawId;vc({drawDefinition:v,event:M,suppressNotifications:!0}),i.push(O)}}c++}let u=o.map(p=>({venueId:p}));Ml({tournamentRecord:e,ignoreExistingVenues:!0,venueProfiles:u,uuids:a})}var J1=["Generated Tournament","CourtHive Challenge","Replication Crisis","Open Competition","Factory Follies","Mock Tournament","Atomic Culture","Racket Rally","Stats Fail"];function vM(t){let{startDate:e,endDate:r}=t??{},{tournamentName:n=Zr(J1),ratingsParameters:o=we,tournamentExtensions:i,policyDefinitions:s,schedulingProfile:a,venueProfiles:c,uuids:u}=t??{},p=t?.isMock===!1?void 0:!0;if(e&&!Nr(e)||r&&!Nr(r))return{error:je};if(t.leagueProfiles&&!Array.isArray(t.leagueProfiles)||t.eventProfiles&&!Array.isArray(t.eventProfiles)||t.drawProfiles&&!Array.isArray(t.drawProfiles))return{error:V};if(!e){let S=new Date;e=Yn(r??S),r=Yn(S.setDate(S.getDate()+7))}if(!r){let S=new Date(e);r=Yn(S.setDate(S.getDate()+7))}let m=dm({...t.tournamentAttributes??{},tournamentName:n,startDate:e,endDate:r,isMock:p}),d=c?.length?Ml({tournamentRecord:m,venueProfiles:c,uuids:u}):[];if(i?.length&&Array.isArray(i)){let S=i.filter(T=>kn({extension:T}));S?.length&&Object.assign(m,{extensions:S,isMock:p})}if(typeof s=="object")for(let S of Object.keys(s))Ji({policyDefinitions:{[S]:s[S]},tournamentRecord:m});if(!t?.leagueProfiles?.length||t.eventProfiles?.length||t.drawProfiles?.length||t.participantsProfile){let S=iA({tournamentRecord:m,...t});if(!S.success)return S}let l=[],f=[],g=[];if(t.leagueProfiles){let S=pw({allUniqueParticipantIds:l,tournamentRecord:m,...t,eventIds:f,venueIds:d,drawIds:g});if(S?.error)return S}if(t.drawProfiles){let S=Z1({allUniqueParticipantIds:l,ratingsParameters:o,tournamentRecord:m,...t,eventIds:f,drawIds:g});if(S?.error)return S}if(t.eventProfiles){let S=t0({allUniqueParticipantIds:l,ratingsParameters:o,tournamentRecord:m,...t,eventIds:f,drawIds:g});if(S?.error)return S}let{scheduledRounds:I=void 0,schedulerResult:h={}}=a?e0({...t,tournamentRecord:m}):{};return lf(),nt({...C,tournamentRecord:m,scheduledRounds:I,schedulerResult:h,eventIds:f,venueIds:d,drawIds:g})}function Z1(t){let{tournamentRecord:e,drawProfiles:r,allUniqueParticipantIds:n,eventIds:o,drawIds:i}=t,s=0;for(let a of r){let c=gm({allUniqueParticipantIds:n,tournamentRecord:e,drawProfile:a,drawIndex:s,...t});if(c.error)return c;let{drawId:u,eventId:p,event:m,uniqueParticipantIds:d}=c;if(a?.addEvent!==!1){if(c=na({suppressNotifications:!1,internalUse:!0,tournamentRecord:e,event:m}),c.error)return c;u&&i.push(u),o.push(p)}d?.length&&n.push(...d),s+=1}}function t0(t){let{eventProfiles:e,allUniqueParticipantIds:r,eventIds:n,drawIds:o}=t,i=0;for(let s of e){let a=mA({...t,eventIndex:i,eventProfile:s});if(a.error)return a;let{eventId:c,drawIds:u,uniqueParticipantIds:p}=a;u&&o.push(...u),n.push(c),p?.length&&r.push(...p),i+=1}}function e0(t){let{schedulingProfile:e,tournamentRecord:r,autoSchedule:n,periodLength:o,scheduleCompletedMatchUps:i}=t,s=aw({schedulingProfile:e,tournamentRecord:r});if(s.error)return s;let a=s.scheduledRounds;if(n){let{tournamentId:c}=r,u={[c]:r};return{schedulerResult:mm({scheduleCompletedMatchUps:i,tournamentRecords:u,periodLength:o}),scheduledRounds:a}}return{scheduledRounds:a}}var wM={};Jt(wM,{anonymizeTournamentRecord:()=>_M,modifyTournamentRecord:()=>xM});function _M({keepExtensions:t=[],anonymizeParticipantNames:e=!0,tournamentRecord:r,tournamentName:n,personIds:o=[],tournamentId:i}){if(!r)return{error:$};let s=Array.isArray(t)?PU.concat(...t):PU,a=L=>Array.isArray(t)?L?.extensions?.filter(G=>s.includes(G.name)):L?.extensions,c={};r.extensions=a(r);let u=i||Mt();c[r.tournamentId]=u,r.tournamentId=u,r.createdAt=new Date().toISOString(),r.tournamentName=n||`Anonymized: ${Yn(new Date)}`,r.isMock=!0,delete r.parentOrganisation;for(let L of r.participants||[]){L.extensions=a(L),L.onlineResources=[];let G=Mt();c[L.participantId]=G,L.participantId=G}for(let L of r.participants||[])Array.isArray(L.individualParticipantIds)&&(L.individualParticipantIds=L.individualParticipantIds.map(G=>c[G]));let p=0;for(let L of r.venues||[]){L.venueAbbreviation=`V${p}`,L.extensions=a(L),L.venueName=`Venue #${p}`,L.onlineResources=[],L.addresses=[];let G=Mt();c[L.venueId]=G,L.isMock=!0,p+=1;let k=0;for(let H of L.courts||[])H.courtName=`V${p}C${k}`,H.extensions=a(H),H.onlineResources=[],H.isMock=!0,k+=1}let m=1;for(let L of r.events||[]){L.extensions=a(L),L.onlineResources=[],L.isMock=!0;let G=Mt();c[L.eventId]=G,L.eventId=G;let k=L.category?.categoryName||L.category?.ageCategoryCode||L.category?.ratingType||L.gender;if(L.eventName=`Event ${m} ${k}`,Array.isArray(L.entries))for(let W of L.entries)W.participantId=c[W.participantId];for(let W of L.drawDefinitions||[]){W.extensions=a(W);let q=Mt();if(c[W.drawId]=q,W.drawId=q,W.isMock=!0,Array.isArray(W.entries))for(let B of W.entries)B.participantId=c[B.participantId];let Y=B=>{B.extensions=a(B);let K=Mt();c[B.structureId]=K,B.structureId=K;for(let X of B.positionAssignments||[])X.participantId&&(X.participantId=c[X.participantId]);for(let X of B.seedAssignments||[])X.participantId&&(X.participantId=c[X.participantId]);for(let X of B.matchUps||[]){X.isMock=!0;for(let j of X.sides||[])j.lineUp&&(j.lineUp=j.lineUp.map(({participantId:ot,collectionAssignments:z})=>({participantId:c[ot],collectionAssignments:z})))}};for(let B of W.structures||[])if(Y(B),Array.isArray(B.structures))for(let K of B.structures)Y(K);for(let B of W.links||[])B.source.structureId=c[B.source.structureId],B.target.structureId=c[B.target.structureId]}let{extension:H}=mt({name:cn,element:L});Array.isArray(H?.value?.flights)&&H?.value.flights?.forEach(W=>{if(W.drawId=c[W.drawId],Array.isArray(W.drawEntries))for(let q of W.drawEntries)q.participantId=c[q.participantId]}),m+=1}let d=r.startDate||Yn(new Date),l=(r.participants||[]).filter(({participantType:L})=>L===At),f=l.reduce((L,G)=>{let k=G.person?.sex;return[zt,oe].includes(k)?L[k]+=1:L[is]+=1,L},{[zt]:0,[oe]:0,[is]:0}),g=Object.assign({},...Object.keys(f).map(L=>({[L]:nA({category:{ageCategoryCode:"O18"},count:f[L],addressProps:{citiesCount:10},personExtensions:[],consideredDate:d,sex:L})?.persons||[]}))),I={[zt]:0,[oe]:0,[is]:0},h=l.length,S=l.reduce((L,G)=>{let k=G.person?.addresses?.[0]||{},{city:H,state:W,postalCode:q}=k;return L.cities.includes(H)||L.cities.push(H),L.states.includes(W)||L.states.push(W),L.postalCodes.includes(q)||L.postalCodes.push(q),L},{cities:[],postalCodes:[],states:[]}),T=S.postalCodes.length,y=S.cities.length,E=S.states.length,{cities:P}=Jy({count:y||h,participantsCount:h}),{states:A}=Zy({count:E||h,participantsCount:h}),{postalCodes:U}=tA({count:T||h,participantsCount:h}),N={cities:P,states:A,postalCodes:U};l.forEach((L,G)=>{let k=L?.person,H=k?.sex||is,W=Pt(k?.birthDate)?.split("-")[0],q=I[H],Y=g[H][q];if(I[H]+=1,W){let[,B,K]=Y?.birthDate?.split("-")||[],X=[W,B,K].join("-");Y.birthDate=X}if(k?.addresses){let B=eA({...N,participantIndex:G,nationalityCode:Y.nationalityCode});Y.addresses=[B]}Y.personId=o?.[G]||Mt(),e?(Y.standardFamilyName=Y.lastName,Y.standardGivenName=Y.firstName,L.participantName=`${Y.standardGivenName} ${Y.standardFamilyName}`):(Y.standardFamilyName=k?.standardFamilyName,Y.standardGivenName=k?.standardGivenName),delete Y.firstName,delete Y.lastName,Y.extensions=a(k),L.person=Y,c[k?.personId]=Y.personId}),(r.participants||[]).filter(({participantType:L})=>L===ft).forEach(L=>{let{individualParticipantIds:G}=L;L.participantName=r0({individualParticipantIds:G,individualParticipants:l})});let M=(r.participants||[]).filter(({participantType:L})=>L===Ft),R=M.length,b=fm({count:R}).names;M.forEach((L,G)=>{L.participantName=b[G]});let v=(r.participants||[]).filter(({participantType:L})=>L===zr),O=v.length,x=fm({count:O,nameRoot:"Group"}).names;v.forEach((L,G)=>{L.participantName=x[G]});let{extension:F}=mt({element:r,name:ya});Array.isArray(F?.value)&&F?.value.forEach(L=>{L.tournamentId=c[L.tournamentId],L.structureId=c[L.structureId],L.eventId=c[L.eventId],L.drawId=c[L.drawId]});let{extension:w}=mt({element:r,name:Ta});return Array.isArray(w?.value)&&w?.value.forEach(L=>{L.personId=c[L.personId]}),{...C}}function r0({individualParticipantIds:t,individualParticipants:e}){let r=e.filter(({participantId:n})=>t.includes(n)).map(({person:n})=>n?.standardFamilyName).filter(Boolean).sort().join("/");return t.length===1&&(r+="/Unknown"),r}function xM(t){let{ratingsParameters:e=we,participantsProfile:r={},matchUpStatusProfile:n,completeAllMatchUps:o,autoEntryPositions:i,hydrateCollections:s,randomWinningSide:a,schedulingProfile:c,tournamentRecord:u,autoSchedule:p,eventProfiles:m,periodLength:d,venueProfiles:l,drawProfiles:f,isMock:g,uuids:I}=t;if(!u)return{error:$};let h=[],S=[],T=[];m?.forEach(D=>{let M=u.events?.find((R,b)=>D.eventIndex!==void 0&&b===D.eventIndex||D.eventName&&R.eventName===D.eventName||D.eventId&&R.eventId===D.eventId);M?.gender&&(D.gender=M.gender)});let y=u.participants?.length||void 0;y&&r?.idPrefix&&(r.idPrefix=`${r.idPrefix}-${y}`);let E=iA({startDate:u.startDate,participantsProfile:r,tournamentRecord:u,eventProfiles:m,drawProfiles:f,uuids:I});if(!E.success)return E;if(m){let D=u.events?.length||0;for(let M of m){let{ratingsParameters:R}=M,b=u.events?.find((v,O)=>M.eventIndex!==void 0&&O===M.eventIndex||M.eventName&&v.eventName===M.eventName||M.eventId&&v.eventId===M.eventId);if(b){let{gender:v,category:O,eventType:x}=b,{drawProfiles:F,publish:w}=M,L=de($n)(x)&&At||de(qr)(x)&&ft||x;if(F){let{stageParticipantsCount:G,uniqueParticipantsCount:k,uniqueParticipantStages:H}=sA({drawProfiles:F,category:O,gender:v}),{uniqueDrawParticipants:W=[],uniqueParticipantIds:q=[]}=H?uA({event:{eventType:x,category:O,gender:v},uniqueParticipantsCount:k,participantsProfile:r,ratingsParameters:R,tournamentRecord:u,eventProfile:M,uuids:I}):{};h.push(...q);let{stageParticipants:Y}=aA({targetParticipants:u.participants||[],allUniqueParticipantIds:h,stageParticipantsCount:G,eventParticipantType:L}),B=pA({uniqueDrawParticipants:W,autoEntryPositions:i,stageParticipants:Y,tournamentRecord:u,drawProfiles:F,category:O,gender:v,event:b});if(B.error||(B=cA({matchUpStatusProfile:n,completeAllMatchUps:o,randomWinningSide:a,tournamentRecord:u,drawProfiles:F,isMock:g,event:b}),B.error))return B;T.push(...B.drawIds)}w&&ia({tournamentRecord:u,event:b})}else{let v=mA({startDate:u.startDate,allUniqueParticipantIds:h,matchUpStatusProfile:n,participantsProfile:r,completeAllMatchUps:o,autoEntryPositions:i,randomWinningSide:a,ratingsParameters:R,tournamentRecord:u,eventProfile:M,eventIndex:D,uuids:I});if(v.error)return v;let{eventId:O,drawIds:x,uniqueParticipantIds:F}=v;x&&T.push(...x),S.push(O),F?.length&&h.push(...F),D+=1}}}if(f){let D=(u.events||[]).map(M=>M.drawDefinitions?.map(()=>1)||[]).flat().reduce((M,R)=>M+R,0);for(let M of f){let R=gm({startDate:u.startDate,allUniqueParticipantIds:h,matchUpStatusProfile:n,participantsProfile:r,completeAllMatchUps:o,autoEntryPositions:i,hydrateCollections:s,randomWinningSide:a,ratingsParameters:e,tournamentRecord:u,drawProfile:M,drawIndex:D,uuids:I});if(R.error)return R;let{drawId:b,eventId:v,event:O,uniqueParticipantIds:x}=R;if(R=na({tournamentRecord:u,event:O,internalUse:!0}),R.error)return R;b&&T.push(b),S.push(v),x?.length&&h.push(...x),D+=1}}let P=l?.length?Ml({tournamentRecord:u,venueProfiles:l}):[],A,U={};if(c?.length){let D={[u.tournamentId]:u},M=Cc({tournamentRecords:D,schedulingProfile:c});if(M.error)return M;if(p){let{tournamentId:R}=u,b={[R]:u};U=mm({tournamentRecords:b,periodLength:d})}}return{totalParticipantsCount:u.participants.length,scheduledRounds:A,schedulerResult:U,...C,eventIds:S,venueIds:P,drawIds:T}}var rR={};Jt(rR,{addDynamicRatings:()=>Vg,addIndividualParticipantIds:()=>om,addParticipant:()=>vn,addParticipants:()=>Sn,addPenalty:()=>ZM,addPersonRequests:()=>kM,addPersons:()=>tR,createGroupParticipant:()=>YM,createTeamsFromParticipantAttributes:()=>gI,deleteParticipants:()=>zi,filterParticipants:()=>Uu,findParticipant:()=>jM,getCompetitionParticipants:()=>jT,getPairedParticipant:()=>In,getParticipantEventDetails:()=>YT,getParticipantMembership:()=>qT,getParticipantScaleItem:()=>Rc,getParticipantSchedules:()=>$T,getParticipantSignInStatus:()=>KT,getParticipantTimeItem:()=>eS,getParticipants:()=>Gt,getScaleValues:()=>ga,mergeParticipants:()=>JM,modifyIndividualParticipantIds:()=>GM,modifyParticipant:()=>im,modifyParticipantName:()=>qM,modifyParticipantOtherName:()=>BM,modifyParticipantsSignInStatus:()=>VM,modifyPenalty:()=>QM,modifyPersonRequests:()=>LM,mutate:()=>eR,participantScaleItem:()=>Ao,query:()=>mN,regenerateParticipantNames:()=>WM,removeIndividualParticipantIds:()=>lg,removeParticipantIdsFromAllTeams:()=>vp,removePenalty:()=>zM,removePersonRequests:()=>FM,removeRatings:()=>KM,scaledTeamAssignment:()=>$M,setParticipantScaleItem:()=>Mc,setParticipantScaleItems:()=>hD,validateLineUp:()=>Ad});var eR={};Jt(eR,{addDynamicRatings:()=>Vg,addIndividualParticipantIds:()=>om,addParticipant:()=>vn,addParticipants:()=>Sn,addPenalty:()=>ZM,addPersonRequests:()=>kM,addPersons:()=>tR,createGroupParticipant:()=>YM,createTeamsFromParticipantAttributes:()=>gI,deleteParticipants:()=>zi,findParticipant:()=>jM,mergeParticipants:()=>JM,modifyIndividualParticipantIds:()=>GM,modifyParticipant:()=>im,modifyParticipantName:()=>qM,modifyParticipantOtherName:()=>BM,modifyParticipantsSignInStatus:()=>VM,modifyPenalty:()=>QM,modifyPersonRequests:()=>LM,regenerateParticipantNames:()=>WM,removeIndividualParticipantIds:()=>lg,removeParticipantIdsFromAllTeams:()=>vp,removePenalty:()=>zM,removePersonRequests:()=>FM,removeRatings:()=>KM,scaledTeamAssignment:()=>$M,setParticipantScaleItem:()=>Mc,setParticipantScaleItems:()=>hD});function fA(t=0){(typeof t!="number"||isNaN(t))&&(t=0);let e=new Date;return e.setHours(e.getHours()+t),e.getTime().toString(36).slice(-6).toUpperCase()}function gA({personRequests:t,personId:e,requests:r}){t[e]||(t[e]=[]);let n=r.filter(({requestType:o})=>o).map(o=>{let{date:i,startTime:s,endTime:a}=o;return o.requestType===wc&&(i=Pt(i),s=Qt(s),a=Qt(a),i&&s&&a)?{date:i,startTime:s,endTime:a,requestType:o.requestType}:o}).filter(Boolean);for(let o of n)o.requestId=fA(),t[e].push(o);return{mergeCount:n.length}}function Rl(t){let{tournamentRecords:e,personRequests:r}=t,n=et(t,[{[Re]:!0}]);if(n.error)return n;if(!r)return{...C};let o=Object.values(e);for(let i of o){let s=i.participants??[],a=[];for(let c of Object.keys(r))if(Bo({tournamentParticipants:s,personId:c})){let u=r[c];u.length&&a.push({personId:c,requests:u})}Object.keys(a).length&&Ut({element:i,extension:{value:a,name:Ta}})}return{...C}}function LM(t){let{tournamentRecords:e,requests:r,personId:n}=t,o=et(t,[{[Re]:!0},{requests:!0,[He]:Be,[Fr]:V}]);if(o.error)return o;let i=r.map(({requestId:u})=>u).filter(Boolean),{personRequests:s}=Oi({tournamentRecords:e}),a=u=>{s&&(s[u]=s[u].map(p=>{if(!i.includes(p.requestId))return p;let m=r.find(d=>d.requestId===p.requestId);if(m.requestType)return Object.assign(p,m)}).filter(Boolean))};if(n&&s?.[n])a(n);else if(s)for(let u of Object.keys(s))a(u);let c=r.filter(u=>!u.requestId);return c.length&&gA({personRequests:s,personId:n,requests:c}),Rl({tournamentRecords:e,personRequests:s})}function FM(t){let{tournamentRecords:e,requestType:r,requestId:n,personId:o,date:i}=t,s=et(t,[{[Re]:!0}]);if(s.error)return s;let{personRequests:a}=Oi({tournamentRecords:e}),c=p=>{a&&(a[p]=a[p].filter(m=>(!r||m.requestType!==r)&&(!n||m.requestId!==n)&&(!i||m.date!==i)),a?.[p]?.length||delete a[p])},u=!r&&!n&&!o&&!i;if(!u){if(o&&a?.[o])c(o);else if(a)for(let p of Object.keys(a))c(p)}return u||!a||!Object.keys(a).length?gr({name:Ta,tournamentRecords:e,discover:!0}):Rl({tournamentRecords:e,personRequests:a})}function kM(t){let{tournamentRecords:e,personId:r,requests:n}=t,o=et(t,[{[Re]:!0,[ub]:!0},{requests:!0,[He]:Be,[Fr]:V}]);if(o.error)return o;let{personRequests:i}=Oi({tournamentRecords:e}),{mergeCount:s}=gA({personRequests:i,personId:r,requests:n});return s&&i?Rl({tournamentRecords:e,personRequests:i}):{error:V}}function GM({individualParticipantIds:t,groupingParticipantId:e,tournamentRecord:r}){let n="modifyIndividualParticipantIds";if(!r)return _({result:{error:$},stack:n});if(!e||!t)return _({result:{error:st},stack:n});let o=r.participants||[],i=o.find(l=>l.participantId===e);if(!i)return _({result:{error:re},stack:n});if(![Ft,zr].includes(i.participantType))return _({result:{error:An},context:{participantType:i.participantType},stack:n});let s=t.filter(l=>o.find(g=>g.participantId===l)?.participantType!==At);if(s.length)return _({result:{error:wr,invalidParticipantIds:s},stack:n});let a=i.individualParticipantIds||[],c=t.filter(l=>!a.includes(l)),u=a.filter(l=>!t.includes(l)),p=om({individualParticipantIds:c,groupingParticipantId:e,tournamentRecord:r});if(p.error)return _({result:p,stack:n});let m=lg({individualParticipantIds:u,groupingParticipantId:e,tournamentRecord:r});if(m.error)return _({result:m,stack:n});let{topics:d}=Lr();if(d.includes(or)){let l=o.find(({participantId:f})=>f===e);lt({topic:or,payload:{tournamentId:r.tournamentId,participants:[l]}})}return{...p,...m}}function VM({tournamentRecord:t,participantIds:e,signInState:r}){if(!t)return{error:$};if(!Array.isArray(e))return{error:st};if(![du,BU].includes(r))return{error:V,signInState:r};let o=t.participants||[];if(!o.length)return{error:Ka};let i=o.map(St),s=e.filter(p=>!i.includes(p));if(s.length)return{error:V,context:{invalidParticipantIds:s}};let a=[],c=new Date().toISOString();for(let p of o){let{participantId:m}=p;if(e.includes(m)){let l=xg({duplicateValues:!1,tournamentRecord:t,participantId:m,timeItem:{itemType:cc,itemValue:r,createdAt:c}});if(l.error)return l;a.push(p)}}let{topics:u}=Lr();return a.length&&u.includes(or)&&lt({topic:or,payload:{tournamentId:t.tournamentId,participants:a}}),{...C}}function BM({tournamentRecord:t,participantId:e,participantOtherName:r}){if(!t)return{error:$};if(!e)return{error:ie};let{participant:n}=yo({tournamentRecord:t,participantId:e});if(!n)return{error:re};n.participantOtherName=r;let{topics:o}=Lr();return o.includes(or)&&lt({topic:or,payload:{tournamentId:t.tournamentId,participants:[n]}}),{...C}}function HM({personFormat:t,person:e}){let r=g=>g.replace(/\W/g,""),n=g=>/^[a-z]*$/.test(r(g)),o=g=>/^[A-Z]*$/.test(r(g)),i=g=>/^[LAST]{4}/.test(r(g)),s=g=>g.toLowerCase().indexOf("l")<g.toLowerCase().indexOf("f"),a=g=>g.indexOf(",")>=0,c=g=>g.toLowerCase().indexOf("f.")>=0,u=g=>g.toLowerCase().indexOf("f")<0,p=g=>g.indexOf(" ")>0;if(!e)return;let m=p(t)?" ":"",d=NS(e?.standardGivenName??""),l=NS(e?.standardFamilyName??"");if(!t)return`${d}${m}${l}`;c(t)&&!a(t)&&!s(t)&&(d=`${d[0]}.`),n(t)?(d=d.toLowerCase(),l=l.toLowerCase()):o(t)?(d=d.toUpperCase(),l=l.toUpperCase()):i(t)&&(l=l.toUpperCase());let f=`${d}${m}${l}`;return u(t)?f=l:s(t)&&(a(t)?f=`${l},${m}${d}`:f=`${l}${m}${d}`),f}function mw({participantMap:t,participant:e,formats:r}){let{participantType:n,individualParticipantIds:o,person:i}=e,s=n&&r[n];if(n!==Er&&s){let{personFormat:a,doublesJoiner:c}=s;n===At&&(e.participantName=HM({person:i,personFormat:a})),n===ft&&(e.participantName=o?.map(u=>{let p=t[u]?.person;return HM({person:p,personFormat:a})}).filter(Boolean).join(c??"/"))}}function WM({tournamentRecord:t,formats:e}){if(!t)return{error:$};if(!ht(e))return{error:st};let r=t.participants??[],n=_I(r,"participantId");for(let o of r)mw({participant:o,participantMap:n,formats:e});return{...C}}function jM(t){let{tournamentRecord:e,policyDefinitions:r,contextProfile:n,participantId:o,personId:i}=t,s=t.tournamentRecords||e&&{[e.tournamentId]:e}||{};if(typeof o!="string"&&typeof i!="string")return{error:st,stack:"publicFindParticipant"};let a,c;for(let u of Object.values(s)){c=u.tournamentId;let p=u.participants||[];if(a=Bo({tournamentParticipants:p,internalUse:!0,policyDefinitions:r,contextProfile:n,participantId:o,personId:i}),a)break}return{participant:a,tournamentId:c,...C}}function YM({individualParticipantIds:t=[],participantRoleResponsibilities:e,participantRole:r=dP,tournamentRecord:n,participantId:o,groupName:i}){if(!n)return{error:$};if(!i)return{error:st,info:"Missing groupName"};if(!Array.isArray(t))return{info:"Invalid individualParticipantIds",error:V};let a=(Gt({participantFilters:{participantTypes:[At]},tournamentRecord:n}).participants??[]).map(m=>m.participantId);for(let m of t)if(!a.includes(m))return{error:An,participantId:m};let c=nt({participantId:o||Mt(),participantRoleResponsibilities:e,participantName:i,individualParticipantIds:t,participantType:zr,participantRole:r}),u=vn({participant:c,tournamentRecord:n});if(u.error)return u;let{topics:p}=Lr();return p.includes(ei)&&lt({topic:ei,payload:{tournamentId:n.tournamentId,participants:[c]}}),{...C,participant:J(c)}}function qM({tournamentRecord:t,participantName:e,participantId:r}){if(!t)return{error:$};if(!r)return{error:ie};if(!e)return{error:st,info:"Missing participantName"};let{participant:n}=yo({tournamentRecord:t,participantId:r});if(!n)return{error:re};n.participantName=e;let{topics:o}=Lr();return o.includes(or)&&lt({topic:or,payload:{tournamentId:t.tournamentId,participants:[n]}}),{...C}}function $M({clearExistingAssignments:t=!0,individualParticipantIds:e,reverseAssignmentOrder:r,initialTeamIndex:n=0,scaledParticipants:o=[],teamParticipantIds:i,tournamentRecord:s,scaleAttributes:a,teamNameBase:c,teamsCount:u,eventId:p,event:m}){if(!s)return{error:$};if(!Array.isArray(i)&&!It(u)&&!p||!It(n)||o&&!Array.isArray(o)||a&&(typeof a!="object"||!Object.keys(a).length))return{error:V};if(!a&&!o.length||!o&&!(e&&a))return{error:st,info:"Missing scaling details"};if(p&&!i){if(m?.eventType!==br)return{error:jn};i=m?.entries?.filter(({entryStatus:h})=>h===kr).map(St)}if(!i?.length&&!u)return{info:"Missing teamParticipantIds or teamsCount",error:st};let d=e??o.map(({participantId:h})=>h);r&&(i?.reverse(),n+=1),n>(i?.length||0)-1&&(n=0);let l=i?.slice(n).concat(...i.slice(0,n))??[],f=[];for(let h of s.participants??[]){let{participantId:S,participantType:T}=h;if(l.includes(S)){if(T!==Er)return{error:An,participant:h};f.push(h)}}if(u&&f.length<u){let h=u-(f?.length||0),S=c??"Team",T=tt(0,h).map(A=>({participantName:`${S} ${A+1}`,participantType:Er,participantRole:xe})),{participants:y=[]}=Sn({participants:T,returnParticipants:!0,tournamentRecord:s}),E=y.map(St),P=s.participants?.filter(({participantId:A})=>E.includes(A))??[];f.push(...P)}if(!f.length)return{error:af};if(t)for(let h of f)h.individualParticipantIds=[];else{let h=f.map(S=>S).flat();e?.length?d=d.filter(S=>!h.includes(S)):o=o?.filter(({participantId:S})=>!h.includes(S))}if(!e?.length&&!o?.length)return{error:tp,info:"Nothing to be done"};if(!o.length){for(let h of s.participants??[]){let{participantId:S,participantType:T}=h;if(!d.includes(S))continue;if(T!==At)return{error:An,participant:h};let y=Ao({scaleAttributes:a,participant:h})?.scaleItem,E=a?.accessor?y?.scaleValue?.[a?.accessor]:y?.scaleValue,P={participantId:S,scaleValue:E};o.push(P)}if(!o.length)return{error:re}}o.sort((h,S)=>a?.sortOrder?(S?.scaleValue||0)-(h?.scaleValue||0):(h?.scaleValue||1/0)-(S?.scaleValue||1/0));for(let h of o)if(!h.participantId)return{error:V,scaledParticipant:h};let g=0;for(;g<o.length;){for(let h of f){if(g+1>o.length)break;let S=o[g];h.individualParticipantIds.push(S.participantId),g++}f.reverse()}let I=f.map(St);for(let h of s.events??[]){if(h.eventType!==br)continue;let S=(h.entries??[]).filter(T=>I.includes(T.participantId));for(let T of S){let y=T.participantId,P=f.find(U=>U.participantId===y)?.individualParticipantIds;h.entries=(h.entries??[]).filter(U=>!P.includes(U.participantId)),(h.drawDefinitions??[]).forEach(U=>{U.entries=(U.entries??[]).filter(N=>!P.includes(N.participantId))});let{flightProfile:A}=Ht({event:h});(A?.flights||[]).forEach(U=>{U.drawEntries=(U.drawEntries||[]).filter(N=>!P.includes(N.participantId))})}}return{...C,scaledParticipants:o}}function KM(t){let e=et(t,[{[ne]:!0,[Cf]:!0},{ratingType:!1,[er]:s=>we[s]}]);if(e.error)return e;let r=`${t.ratingType}.${Hm}`,n=t.asDynamic?r:t.ratingType,o=[Si,hi,t.eventType,n].join("."),i=t.tournamentRecord.participants??[];for(let s of i)s.timeItems&&(s.timeItems=s.timeItems.filter(a=>a.itemType!==o));return{...C}}function zM(t){let{tournamentRecords:e}=t;if(typeof e!="object"||!Object.keys(e).length)return{error:Lt};for(let r of Object.values(e)){let n=n0({...t,tournamentRecord:r});if(n.error&&n.error!==Vc)return n}return{...C}}function n0({tournamentRecord:t,penaltyId:e}){if(!t)return{error:$};if(!e)return{error:rf};let r=t?.participants??[],n=[],o=!1,i;return r.forEach(s=>{let a=!1;s.penalties=(s.penalties??[]).filter(c=>(c.penaltyId===e&&(a=!0,o||(i=c,o=!0)),a&&n.push(s),c.penaltyId!==e))}),i&&lt({topic:or,payload:{tournamentId:t.tournamentId,participants:n}}),i?{...C,penalty:i}:{error:Vc}}var o0=({penaltyId:t=Mt()}={})=>({refereeParticipantId:void 0,penaltyCode:void 0,penaltyType:void 0,extensions:void 0,matchUpId:void 0,createdAt:void 0,issuedAt:void 0,notes:void 0,penaltyId:t}),IA=o0;function QM(t){let{tournamentRecords:e}=t;if(typeof e!="object"||!Object.keys(e).length)return{error:Lt};for(let r of Object.values(e)){let n=i0({...t,tournamentRecord:r});if(n.error&&n.error!==Vc||n.success)return n}return{error:Vc}}function i0({tournamentRecord:t,modifications:e,penaltyId:r}){if(!t)return{error:$};if(!e)return{error:V,modifications:e};if(!r)return{error:rf};let n=t?.participants??[],o=Object.keys(IA()).filter(c=>c!=="penaltyId"),i=Object.keys(e).filter(c=>o.includes(c));if(!i.length)return{error:rp};let s,a=[];return n.forEach(c=>{let u=!1;c.penalties=(c.penalties??[]).map(p=>(p.penaltyId===r&&(u=!0,i.forEach(m=>Object.assign(p,{[m]:e[m]})),s||(s=p)),p)),u&&a.push(c)}),s&&lt({topic:or,payload:{tournamentId:t.tournamentId,participants:a}}),s?{...C,penalty:s}:{error:Vc}}function XM(t,e,r){return!t&&e?e:t&&!e||typeof t!="object"||typeof e!="object"?t:pt(Object.keys(t).concat(Object.keys(e))).reduce((o,i)=>{if(!e[i])o[i]=t[i];else if(!t[i])o[i]=e[i];else if(typeof t[i]!=typeof e[i])o[i]=e[i];else if(Array.isArray(t[i]))if(r===!0||Array.isArray(r)&&r.includes(i)){let s=pt(t[i].map(a=>JSON.stringify(a)).concat(e[i].map(a=>JSON.stringify(a)))).map(a=>JSON.parse(a));o[i]=s}else o[i]=e[i];else typeof t[i]=="object"?o[i]=XM(t[i],e[i],r):o[i]=e[i];return o},{})}function JM({participants:t=[],tournamentRecord:e,arraysToMerge:r}){if(!e)return{error:$};e.participants||(e.participants=[]);let n=t.filter(Br(io)).map(u=>({[u.participantId]:u})),o=Object.assign({},...n),i=[];e.participants=e.participants.map(u=>{if(o[u.participantId]){let p=XM(u,o[u.participantId],r);return i.push(p),p}return u});let s=e.participants.map(Br(io))||[],a=t.filter(({participantId:u})=>!s.includes(u)),{topics:c}=Lr();return a.length&&(e.participants=e.participants.concat(...a),c.includes(ei)&&lt({topic:ei,payload:{participants:a}})),i.length&&c.includes(or)&&lt({topic:or,payload:{tournamentId:e.tournamentId,participants:i}}),{modifiedParticipantsCount:i.length,newParticipantsCount:a.length,...C}}function ZM(t){let{tournamentRecord:e,participantIds:r}=t,n=t.tournamentRecords??(e&&{[e.tournamentId]:e})??{},o;for(let i of Object.values(n)){let a=(Gt({tournamentRecord:i}).participants??[])?.map(St).filter(c=>r.includes(c));a.length&&(o=s0({...t,penaltyId:t.penaltyId??o,tournamentRecord:i,participantIds:a}).penaltyId)}return o?{...C,penaltyId:o}:{error:re}}function s0({refereeParticipantId:t,tournamentRecord:e,participantIds:r,penaltyCode:n,penaltyType:o,extensions:i,penaltyId:s,matchUpId:a,issuedAt:c,notes:u}){if(!e)return{error:$};if(!r)return{error:ie};if(!o)return{error:yE};let m=(e?.participants??[]).filter(f=>r.includes(f.participantId));if(!m.length)return{error:re};let d=new Date().toISOString(),l=Object.assign(IA({penaltyId:s}),{refereeParticipantId:t,penaltyCode:n,penaltyType:o,matchUpId:a,createdAt:d,issuedAt:c,notes:u});return Array.isArray(i)&&i.forEach(f=>Ut({element:l,extension:f})),m.forEach(f=>{f.penalties||(f.penalties=[]),f.penalties.push(l)}),lt({topic:or,payload:{tournamentId:e.tournamentId,participants:m}}),{...C,penaltyId:l.penaltyId}}function tR({participantRole:t=xe,tournamentRecord:e,persons:r}){if(!e)return{error:$};if(!Array.isArray(r))return{error:V};if(!Object.keys(hd).includes(t))return{error:pE};let n=(e.participants||[]).map(({person:f})=>f?.personId).filter(Boolean),o=[],i=r.filter(f=>f&&(!f.personId||!n.includes(f.personId))).map(f=>(f.personId||(f.personId=Mt()),o.push(f.personId),f)),s=(f,g)=>Object.assign({},...Object.keys(f).filter(I=>!g.includes(I)).map(I=>({[I]:f[I]}))),a=i.map(f=>nt({extensions:f.participantExtensions,timeItems:f.participantTimeItems,participantType:At,participantRole:t,person:s(f,["participantExtensions","participantTimeItems","pairedPersons"])})),c=0,u=0,p=Sn({participants:a,tournamentRecord:e});if(p.error)return p;u=p.addedCount||0;let m=[],d=Gt({participantFilters:{participantTypes:[At]},tournamentRecord:e})?.participants??[];if(t===xe&&r.filter(({pairedPersons:f})=>f).forEach(({personId:f,pairedPersons:g})=>{Array.isArray(g)&&g.forEach(I=>{let h=[f,I.personId].map(S=>Bo({tournamentParticipants:d,personId:S})).filter(Boolean);if(h.length===2){let S=h.map(St);m.push(nt({extensions:I.participantExtensions,timeItems:I.timeItems,participantRole:xe,individualParticipantIds:S,participantType:ft}))}})}),m.length){if(p=Sn({participants:m,tournamentRecord:e}),p.error)return p;c=p.addedCount||0}let l=u+c;return{...C,addedCount:l,newPersonIds:o}}var mR={};Jt(mR,{bulkUpdatePublishedEventIds:()=>ry,getAllEventData:()=>ny,getCourtInfo:()=>md,getDrawData:()=>rl,getEventData:()=>nl,getEventPublishStatus:()=>Xr,getPublishState:()=>Is,getTournamentPublishStatus:()=>Au,getVenueData:()=>fc,mutate:()=>pR,publishEvent:()=>ia,publishEventSeeding:()=>nR,publishOrderOfPlay:()=>cR,publishParticipants:()=>aR,query:()=>TN,setEventDisplay:()=>fl,unPublishEvent:()=>uR,unPublishEventSeeding:()=>oR,unPublishOrderOfPlay:()=>sR,unPublishParticipants:()=>iR});var pR={};Jt(pR,{publishEvent:()=>ia,publishEventSeeding:()=>nR,publishOrderOfPlay:()=>cR,publishParticipants:()=>aR,setEventDisplay:()=>fl,unPublishEvent:()=>uR,unPublishEventSeeding:()=>oR,unPublishOrderOfPlay:()=>sR,unPublishParticipants:()=>iR});function nR({removePriorValues:t=!0,stageSeedingScaleNames:e,seedingScaleNames:r,tournamentRecord:n,status:o=Rr,drawIds:i=[],event:s}){if(!n)return{error:$};if(!s)return{error:Ot};let a=Xr({event:s,status:o}),c=(a?.seeding?.seedingScaleNames||r)&&{...a?.seeding?.seedingScaleNames,...r},u=(a?.seeding?.stageSeedingScaleNames||e)&&{...a?.seeding?.stageSeedingScaleNames,...e},p=nt({stageSeedingScaleNames:u,seedingScaleNames:c,published:!0,drawIds:i});return oa({statusObject:{seeding:p},removePriorValues:t,status:o,event:s}),lt({topic:FU,payload:{tournamentId:n.tournamentId,eventId:s.eventId,drawIds:i}}),{...C}}function oR({removePriorValues:t=!0,seedingScaleNames:e,tournamentRecord:r,status:n=Rr,drawIds:o,stages:i,event:s}){if(!r)return{error:$};if(!s)return{error:Ot};let a=Xr({event:s});if(a){let c=a.seeding;if(Array.isArray(i)&&c.stageSeedingScaleNames)for(let u of i)c.stageSeedingScaleNames[u]&&delete c.stageSeedingScaleNames[u];Array.isArray(e)&&c?.seedingScaleNames&&(c.seedingScaleNames=c.seedingScaleNames.filter(u=>!e.includes(u))),Array.isArray(o)&&c?.drawIds&&(c.drawIds=c.drawIds.filter(u=>!o.includes(u))),(!Object.values(c.stageSeedingScaleNames??{}).length&&!c.seedingScaleNames?.length&&!c.drawIds?.length||!i&&!e&&!o?.length)&&(delete c.stageSeedingScaleNames,delete c.seedingScaleNames,delete c.drawIds,c.published=!1),oa({statusObject:{seeding:c},removePriorValues:t,status:n,event:s})}return lt({topic:zf,payload:{tournamentId:r.tournamentId,eventId:s.eventId}}),{...C}}function iR(t){let e=Mr(t);if(!Object.keys(e).length)return{error:Lt};for(let r of Object.values(e)){let n=a0({tournamentRecord:r,...t});if(n.error)return n}return{...C}}function a0({removePriorValues:t=!0,tournamentRecord:e,status:r=Rr}){if(!e)return{error:$};let n=`${wo}.${Lo}`,{timeItem:o}=en({element:e,itemType:n}),i=o?.itemValue||{[r]:{}};return i[r]&&delete i[r].participants,to({timeItem:{itemValue:i,itemType:n},element:e,removePriorValues:t}),lt({payload:{tournamentId:e.tournamentId},topic:Ab}),{...C}}function sR(t){let e=Mr(t);if(!Object.keys(e).length)return{error:Lt};for(let r of Object.values(e)){let n=c0({tournamentRecord:r,...t});if(n.error)return n}return{...C}}function c0({removePriorValues:t=!0,tournamentRecord:e,status:r=Rr}){if(!e)return{error:$};let n=`${wo}.${Lo}`,{timeItem:o}=en({element:e,itemType:n}),i=o?.itemValue||{[r]:{}};return i[r]&&delete i[r].orderOfPlay,to({timeItem:{itemValue:i,itemType:n},element:e,removePriorValues:t}),lt({topic:Qf,payload:{tournamentId:e.tournamentId}}),{...C}}function aR(t){let e=Mr(t);if(!Object.keys(e).length)return{error:Lt};for(let r of Object.values(e)){let n=u0({tournamentRecord:r,...t});if(n.error)return n}return{...C}}function u0({removePriorValues:t,tournamentRecord:e,status:r=Rr}){if(!e)return{error:$};let n=`${wo}.${Lo}`,{timeItem:o}=en({element:e,itemType:n}),i=o?.itemValue||{[r]:{}};return i[r].participants={published:!0},to({timeItem:{itemValue:i,itemType:n},element:e,removePriorValues:t}),lt({payload:{tournamentId:e.tournamentId},topic:GU}),{...C}}function cR(t){let e=Mr(t);if(!Object.keys(e).length)return{error:Lt};for(let r of Object.values(e)){let n=p0({tournamentRecord:r,...t});if(n.error)return n}return{...C}}function p0({scheduledDates:t=[],removePriorValues:e,tournamentRecord:r,status:n=Rr,eventIds:o=[]}){if(!r)return{error:$};let i=`${wo}.${Lo}`,{timeItem:s}=en({element:r,itemType:i}),a=s?.itemValue||{[n]:{}};return a[n].orderOfPlay={published:!0,scheduledDates:t,eventIds:o},to({timeItem:{itemValue:a,itemType:i},element:r,removePriorValues:e}),lt({topic:kU,payload:{tournamentId:r.tournamentId,scheduledDates:t,eventIds:o}}),{...C}}function uR({removePriorValues:t=!0,tournamentRecord:e,status:r=Rr,event:n}){if(!e)return{error:$};if(!n)return{error:Ot};let o=`${wo}.${Lo}`,{timeItem:i}=gu({itemType:o,event:n}),s=i?.itemValue||{[r]:{}};return delete s[r].structureIds,delete s[r].drawDetails,delete s[r].drawIds,Xi({event:n,timeItem:{itemValue:s,itemType:o},removePriorValues:t}),oa({statusObject:{structureIds:void 0,drawIds:void 0,seeding:void 0},removePriorValues:t,status:r,event:n}),lt({topic:Kf,payload:{tournamentId:e.tournamentId,eventId:n.eventId}}),{eventId:n.eventId,...C}}var dR={};Jt(dR,{getEntryStatusReports:()=>lw,getParticipantStats:()=>dw,getStructureReports:()=>gw,getVenuesReport:()=>Iw});function dw({withCompetitiveProfiles:t,opponentParticipantId:e,withIndividualStats:r,teamParticipantId:n,tournamentRecord:o,withScaleValues:i,tallyPolicy:s,matchUps:a}){if(!o)return{error:$};if(a&&!Array.isArray(a))return{error:lr};if(a=a??ye({tournamentRecord:o,participantsProfile:i?{withScaleValues:i}:void 0}).matchUps,!a?.length)return{error:eo};let u=[];e&&u.push(e),n&&u.push(n);let p=u.length?{participantIds:u}:{participantTypes:[Er]},m=Gt({participantFilters:p,tournamentRecord:o}).participants??[];if(!m.every(({participantType:U})=>U===Er))return{error:wr};u.length||u.push(...m.map(St));let d=new Map,l=new Map,f=new Map,g=new Map,I=(U,N="")=>l.get(U)||l.set(U,{participantName:N,participantId:U,competitorIds:[],competitiveness:{},matchUpStatuses:{},tiebreaks:[0,0],matchUps:[0,0],points:[0,0],games:[0,0],sets:[0,0]})&&l.get(U);for(let U of m){let{participantId:N,individualParticipantIds:D}=U;g.set(N,D??[]),I(N,U.participantName)}if(n&&!g.get(n))return _({result:{error:re},context:{teamParticipantId:n}});if(e&&!g.get(e))return _({result:{error:re},context:{opponentParticipantId:e}});let h=[],S=U=>{let N=[[],[]];for(let M of U){let R=M.participant;if(R?.participantName){d.set(R.participantId,{participantName:R.participantName,ratings:R.ratings});let b=l.get(R.participantId);b&&(b.participantName=R.participantName)}}let D=({side:M,individualParticipantIds:R})=>M.participantId&&(!R?.length||R.includes(M.participantId))&&[M.participantId]||M.participant?.individualParticipantIds?.length&&(!R?.length||jt(R,M.participant?.individualParticipantIds).length===M.participant?.individualParticipantIds?.length)&&M.participant.individualParticipantIds;if(g.size){let M=(R,b)=>{for(let v of U){if(!v.participant)continue;let O=D({individualParticipantIds:b,side:v});if(O?.length){let x=v.sideNumber;if(!x)continue;let F=[R];r&&F.push(...O),N[x-1]=F;let w=l.get(R);for(let L of O.filter(Boolean))w&&!w.competitorIds.includes(L)&&w.competitorIds.push(L)}}};if(n)(!e||U.every(b=>b.participant&&(D({individualParticipantIds:g.get(n),side:b})||D({individualParticipantIds:g.get(e),side:b}))))&&M(n,g.get(n));else for(let[R,b]of g)M(R,b)}else if(r)for(let M of U){if(!M.participant)continue;let R=D({individualParticipantIds:[],side:M}),b=M.sideNumber;b&&(N[b-1]=R)}return N};for(let U of a){if(!ht(U))return{error:lr};let{matchUpStatus:N,matchUpFormat:D,matchUpType:M,winningSide:R,score:b,sides:v}=U;if(!v||!b||M===xr||N===Nt)continue;let O=S(v);if(!O.filter(Boolean).length)continue;let x=t&&R&&Su({matchUp:U})?.competitiveness;h.push(U);let F=vg({matchUpStatus:N,matchUpFormat:D,tallyPolicy:s,winningSide:R,score:b}),w=XS({matchUpStatus:N,matchUpFormat:D,tallyPolicy:s,winningSide:R,score:b}),{pointsTally:L,tiebreaksTally:G}=JS({matchUpFormat:D,score:b});O.forEach((k,H)=>{for(let W of k){let q=d.get(W)?.participantName,Y=I(W,q);if(Y){let B=(z,Q)=>Q.forEach((ut,it)=>Y[z][it]+=ut),K=H?[...G].reverse():G,X=H?[...L].reverse():L,j=H?[...w].reverse():w,ot=H?[...F].reverse():F;if(B("tiebreaks",K),B("points",X),B("games",j),B("sets",ot),R){let z=R-1===H?0:1;Y.matchUps[z]+=1}if(x){let z=x.toLowerCase();Y.competitiveness[z]||(Y.competitiveness[z]=[0,0]),Y.competitiveness[z][H]+=1}if(N){let z=N.toLowerCase();Y.matchUpStatuses[z]||(Y.matchUpStatuses[z]=0),Y.matchUpStatuses[z]+=1}}}})}let T=["tiebreaks","matchUps","points","games","sets"],y=["competitive","routine","decisive"],E=new Map,P=(U,N)=>(U??0)+(N??0);for(let[U,N]of l.entries()){for(let D of T){let M=N[D].reduce(P);if(M){let R=N[D][0]/M,b=`${D}Ratio`,v=parseFloat(R.toFixed(2));N[b]=v,f.set(U,!0),E.has(b)||E.set(b,[]),E.get(b)?.push(v)}}for(let D of y){let M=N.competitiveness?.[D]?.reduce(P);if(M){let R=N.competitiveness[D][0]/M,b=`${D}Ratio`,v=parseFloat(R.toFixed(2));N[b]=v}}}if(!n){let U=(N,D)=>D-N;for(let N of l.values())for(let D of T){let M=`${D}Ratio`;if(typeof N[M]=="number"){let R=E.get(M)?.sort(U).indexOf(N[M]);if(typeof R=="number"&&R>=0){let b=`${D}Rank`;N[b]=R+1}}}}let A={relevantMatchUps:h,...C};return n?(A.teamStats=l.get(n),e&&(A.opponentStats=l.get(e))):A.participatingTeamsCount=f.size,A.allParticipantStats=[...l.values()],A}function Im({participant:t,eventType:e}){let r=t?.person?.personId,n=t?.person?.personOtherIds?.[0],o=t?.person?.tennisId,i=t?.ratings?.[e]?.find(({scaleName:u})=>u===bg),s=i?.scaleValue,{wtnRating:a,confidence:c}=s||{};return{timeStamp:i?.scaleDate,personOtherId:n,confidence:c,wtnRating:a,personId:r,tennisId:o}}function lw({tournamentRecord:t}){if(!t)return{error:$};let e=t.tournamentId,{participantMap:r}=Gt({withScaleValues:!0,withEvents:!0,withSeeding:!0,tournamentRecord:t,withDraws:!0}),o=(ye({matchUpFilters:{matchUpTypes:[ua,_i]},tournamentRecord:t}).matchUps??[]).flatMap(({sides:f,matchUpType:g})=>f?.flatMap(I=>g===_i?I?.participant?.individualParticipantIds:I?.participant?.participantId||I.participantId).filter(Boolean)).filter(Boolean),i=[],s={},a={},c={},u=0,p=({id:f,entry:g,eventId:I,eventType:h})=>{let{qualifyingSeeding:S,mainSeeding:T,entryStatus:y,entryStage:E,drawId:P}=g;s[f]||(s[f]=[]);let{participant:A,events:U}=r?.[f]??{},N=Im({participant:A,eventType:h}),D=U?.[I]?.ranking;y===Rg&&i.push(f),s[f].push({participantType:A?.participantType,participantId:f,tournamentId:e,eventType:h,eventId:I,drawId:P,entryStatus:y,entryStage:E,...N,ranking:D,mainSeeding:T,qualifyingSeeding:S})};for(let f of t.events??[]){let g={},I=N=>{g[N]||(g[N]={count:0}),g[N].count+=1},{drawDefinitions:h=[],eventType:S,eventId:T}=f,y=h.flatMap(N=>{let{drawId:D,entries:M}=N;u+=1;let R=({stage:F,stageSequence:w})=>F===rt&&w===1||F===ct,v=(N.structures??[]).filter(R).flatMap(({positionAssignments:F})=>F).filter(Boolean).map(({participantId:F})=>F),O=({participantId:F})=>v.includes(F),x=F=>{let{participantId:w,entryStatus:L,entryStage:G}=F;I(L);let k=r?.[w]?.draws?.[D]?.seedAssignments?.[rt];return{qualifyingSeeding:r?.[w]?.draws?.[D]?.seedAssignments?.[ct],participantId:w,mainSeeding:k,entryStatus:L,entryStage:G,drawId:D}};return M?.filter(O).map(x)}),E=N=>{let D=N.participantId,M=r?.[D].participant.individualParticipantIds?.filter(R=>o.includes(R));return D&&{[D]:{individualParticipantIds:M}}};S===Vo?(()=>{let N=Object.assign({},...y.map(E).filter(Boolean)),D=M=>{N[M.participantId].individualParticipantIds.forEach(R=>{p({id:R,eventType:S,eventId:T,entry:M})})};y.forEach(D)})():y.forEach(N=>{p({id:N?.participantId,eventType:S,eventId:T,entry:N})});let A=Object.values(g).reduce((N,D)=>N+D.count,0);Object.keys(g).forEach(N=>{g[N].pct=g[N].count/A*100}),c[T]={tournamentId:e,eventId:T,entries:y,entryStatuses:g};let U=Object.assign({},...Qr.flatMap(N=>[{[N+"_count"]:g[N]?.count},{[N+"_pct"]:g[N]?.pct}]));a[T]={tournamentId:e,eventId:T,...U}}let m=Object.values(r??{}).filter(({participant:{participantType:f,participantRole:g}})=>f===At&&g===xe),d=m.filter(({participant:f})=>!o.includes(f.participantId)).map(({participant:f})=>f.participantId),l={nonParticipatingEntriesCount:d.length,individualParticipantsCount:m.length,eventsCount:Object.values(c).length,nonParticipatingParticipantIds:d,drawDefinitionsCount:u,tournamentId:e};return{entryStatusReports:Object.values(a).flat(),participantEntryReports:Object.values(s).flat(),eventReports:Object.values(c).flat(),withDrawnParticipantIds:i,tournamentEntryReport:l}}function fw({eventType:t,matchUps:e,eventId:r,drawId:n}){let o={},i=g=>{let I=g?.matchUpFormat;I&&(o[I]||(o[I]=0),o[I]+=1)},s=e.filter(g=>r?g.eventId===r:g.drawId===n).reduce((g,I)=>(i(I),(I.sides??[]).flatMap(h=>(h?.participant?.individualParticipants||[h?.participant]).filter(Boolean)).forEach(h=>g[h.participantId]=h),g),{}),a=Object.values(s),c=a.map(g=>Im({participant:g,eventType:t})).filter(({wtnRating:g})=>g),u=(a.length-c.length)/a.length*100,p=c.reduce((g,I)=>{let{wtnRating:h,confidence:S}=I;return g.totalWTN+=h,g.totalConfidence+=S,g},{totalWTN:0,totalConfidence:0}),m=c?.length?p.totalWTN/c.length:0,d=c?.length?p.totalConfidence/c.length:0,f=Object.values(o).reduce((g,I)=>g+(I||0),0);return{matchUpFormatCounts:o,matchUpsCount:f,avgConfidence:d,pctNoRating:u,avgWTN:m}}function gw(t){let{tournamentRecord:e,extensionProfiles:r,firstFlightOnly:n}=t;if(!e)return{error:pa};let o=[],i={},s={},a=[],c=Object.assign({},...(r??[]).map(({name:g,label:I,accessor:h})=>{let S=mt({element:e,name:g})?.extension?.value,T=h?fs({element:S,accessor:h})?.value:S;return{[I||g]:T}})),u=e?.tournamentId,m=ye({participantsProfile:{withScaleValues:!0},tournamentRecord:e}).matchUps??[],d=g=>en({itemType:Gf,itemSubTypes:[To],element:{timeItems:g}})?.timeItem?.itemValue?.scaleBasis,l=({positionManipulations:g})=>{g?.forEach(I=>{let{structureId:h,name:S}=I,T=I.drawPositions||[I.drawPosition];i[h]||(i[h]=[]),i[h].push(`${S}: ${T.join("/")}`)})},f=e?.events?.flatMap(({timeItems:g,drawDefinitions:I=[],extensions:h,eventType:S,eventName:T,eventId:y,category:E})=>{let A=h?.find(O=>O.name===cn)?.value?.flights?.map(O=>({[O.drawId]:O.flightNumber})),U=A&&Object.assign({},...A),N=h?.find(O=>O.name===Sa),D=g?.find(O=>O.itemType===Sa),M=N?.value?.length||D?.itemValue||0,R=Object.values(U??{}),b=U&&Math.min(...R),v=d(g);return s[y]={seedingBasis:v?JSON.stringify(v):void 0,totalPositionManipulations:0,maxPositionManipulations:0,generatedDrawsCount:0,drawDeletionsCount:M,tournamentId:u,eventId:y},I.filter(O=>!n||!A||U[O.drawId]===b).flatMap(O=>{let{matchUpFormat:x,tieFormat:F,timeItems:w,extensions:L,structures:G,drawName:k,drawType:H,drawId:W}=O,{matchUpFormatCounts:q,matchUpsCount:Y,avgConfidence:B,pctNoRating:K,avgWTN:X}=fw({eventType:S,matchUps:m,drawId:W}),j=d(w)||v,ot=m0({extensions:L}),z=ot?.length||0;return l({positionManipulations:ot}),s[y].totalPositionManipulations+=z,s[y].generatedDrawsCount+=1,z>s[y].maxPositionManipulations&&(s[y].maxPositionManipulations=z),G?.filter(Q=>Q.stageSequence===1&&[ct,rt,qe,fe].includes(Q.stage)).map(Q=>{let ut=[rt,fe].includes(Q.stage)?m.find(dr=>dr.structureId===Q.structureId&&dr.finishingRound===1&&dr.winningSide):void 0;Q.stage===rt&&o.push({eventName:T,drawName:k,structureId:Q.structureId});let Et=ut?.sides?.find(dr=>dr.sideNumber===ut.winningSide)?.participant,_t=Et?.participantType===Er&&Et.participantId,Ae=Et?.participantType===ft?Et.individualParticipants:[],$t=Im({participant:Ae?.[0]||Et,eventType:S}),{personId:Se,personOtherId:Or,tennisId:pn,confidence:Ir,wtnRating:Xe}=$t||{},te=Im({participant:Ae?.[1],eventType:S}),{personId:Dt,personOtherId:ue,tennisId:pe,confidence:Fe,wtnRating:ee}=te||{},{ageCategoryCode:Je,categoryName:qt,subType:ar}=E??{},Ze=Q.matchUpFormat||x,ae=(q[Ze]||0)/Y*100,{tieFormatName:hr,tieFormatDesc:_r}=tl(F),{tieFormatName:Kt,tieFormatDesc:De}=tl(Q.tieFormat),fr=_r===De,Ne=!fr&&Kt,On=Q.tieFormat&&!fr&&De,me=ot?.filter(dr=>dr.structureId===Q.structureId)?.length||0;return{...c,tournamentId:u,eventId:y,structureId:Q.structureId,drawId:W,eventType:S,category:ar,categoryName:qt,ageCategoryCode:Je,flightNumber:U?.[W],drawType:H,stage:Q.stage,seedingBasis:j?JSON.stringify(j):void 0,winningPersonId:Se,winningPersonOtherId:Or,winningPersonTennisId:pn,winningPersonWTNrating:Xe,winningPersonWTNconfidence:Ir,winningPerson2Id:Dt,winningPerson2OtherId:ue,winningPerson2TennisId:pe,winningPerson2WTNrating:ee,winningPerson2WTNconfidence:Fe,winningTeamId:_t,positionManipulations:me,pctNoRating:K,matchUpFormat:Ze,pctInitialMatchUpFormat:ae,matchUpsCount:Y,drawTieFormatName:hr,drawTieFormatDesc:_r,tieFormatName:Ne,tieFormatDesc:On,avgConfidence:B,avgWTN:X}})})});return o.forEach(({eventName:g,drawName:I,structureId:h})=>{i[h]?.length&&a.push({eventName:g,drawName:I,actions:i[h]})}),{eventStructureReports:Object.values(s),structureReports:f,flightReports:a}}function m0({extensions:t}){return t?.find(({name:e})=>e===ic)?.value?.slice(1)}function Iw({ignoreDisabled:t=!0,tournamentRecords:e,tournamentId:r,venueIds:n=[],dates:o=[]}){if(!Array.isArray(o))return{error:V,dates:o};if(!Array.isArray(n))return{error:V,venueIds:n};if(!(e&&Object.keys(e).filter(l=>!r||l===r)||[]).length)return{error:Lt};if(!o.every(Nr))return{error:je};let a=Uo({tournamentRecords:e,ignoreDisabled:t,dates:o});if(a.error)return a;let c=a?.venues?.filter(({venueId:l})=>!n?.length||n.includes(l)),u=a.courts?.reduce((l,f)=>(f.dateAvailability?.forEach(g=>{let I=g.date;l.includes(I)||l.push(I)}),l),[]).filter(l=>!o.length||o.includes(l)),p={venueIds:c?.map(({venueId:l})=>l)},{matchUps:m}=Un({afterRecoveryTimes:!0,tournamentRecords:e,matchUpFilters:p});return{venuesReport:c?.map(l=>d0(u,l,m))}}function d0(t,e,r){let{venueId:n,courts:o,venueName:i}=e,s={};return t.forEach(a=>{let c=0,u=0,p=0;for(let l of o){let f=l.dateAvailability.find(h=>h.date===a),I=(f&&Ms({courtDate:f}).timeSlots)?.reduce((h,S)=>{let{startTime:T,endTime:y}=S,E=Yt(y)-Yt(T);return h+E},0);I&&(p+=1),c+=I}let m=r.filter(({schedule:l})=>l.venueId===n&&qn(a,l.scheduledDate));m.forEach(({schedule:l})=>{let f=Qt(l.scheduledTime),g=Yr(f,l.averageMinutes),I=Yt(g)-Yt(f);u+=I});let d=c?(u/c*100).toFixed(2):"100";s[a]={scheduledMatchUpsCount:m.length,availableCourts:p,availableMinutes:c,scheduledMinutes:u,percentUtilization:d}}),{venueId:n,venueName:i,venueReport:s}}var PR={};Jt(PR,{addMatchUpCourtOrder:()=>Wy,addMatchUpEndTime:()=>Yy,addMatchUpOfficial:()=>fM,addMatchUpResumeTime:()=>$y,addMatchUpScheduleItems:()=>cm,addMatchUpScheduledDate:()=>sm,addMatchUpScheduledTime:()=>Jo,addMatchUpStartTime:()=>jy,addMatchUpStopTime:()=>qy,addSchedulingProfileRound:()=>hI,allocateTeamMatchUpCourts:()=>am,assignMatchUpCourt:()=>Zi,assignMatchUpVenue:()=>sa,bulkRescheduleMatchUps:()=>TR,bulkScheduleMatchUps:()=>Lc,bulkScheduleTournamentMatchUps:()=>ju,bulkUpdateCourtAssignments:()=>gR,calculateScheduleTimes:()=>yI,clearMatchUpSchedule:()=>AR,clearScheduledMatchUps:()=>pm,courtGridRows:()=>sl,findMatchUpFormatTiming:()=>Xp,findVenue:()=>qo,generateBookings:()=>um,generateVirtualCourts:()=>nm,getMatchUpsToSchedule:()=>ol,getPersonRequests:()=>Oi,getProfileRounds:()=>il,getScheduledRoundsDetails:()=>Vu,getSchedulingProfile:()=>Xo,getSchedulingProfileIssues:()=>iy,matchUpScheduleChange:()=>yR,modifyMatchUpFormatTiming:()=>Jg,mutate:()=>UR,proAutoSchedule:()=>fR,proConflicts:()=>hR,publicFindCourt:()=>SS,query:()=>UN,removeEventMatchUpFormatTiming:()=>ll,removeMatchUpCourtAssignment:()=>lR,reorderUpcomingMatchUps:()=>SR,scheduleMatchUps:()=>IR,scheduleProfileRounds:()=>mm,setMatchUpDailyLimits:()=>ER,setMatchUpHomeParticipantId:()=>uI,setSchedulingProfile:()=>Cc,toggleParticipantCheckInState:()=>Il,validateSchedulingProfile:()=>Jp});var UR={};Jt(UR,{addMatchUpCourtOrder:()=>Wy,addMatchUpEndTime:()=>Yy,addMatchUpOfficial:()=>fM,addMatchUpResumeTime:()=>$y,addMatchUpScheduleItems:()=>cm,addMatchUpScheduledDate:()=>sm,addMatchUpScheduledTime:()=>Jo,addMatchUpStartTime:()=>jy,addMatchUpStopTime:()=>qy,addSchedulingProfileRound:()=>hI,allocateTeamMatchUpCourts:()=>am,assignMatchUpCourt:()=>Zi,assignMatchUpVenue:()=>sa,bulkRescheduleMatchUps:()=>TR,bulkScheduleMatchUps:()=>Lc,bulkScheduleTournamentMatchUps:()=>ju,bulkUpdateCourtAssignments:()=>gR,calculateScheduleTimes:()=>yI,clearMatchUpSchedule:()=>AR,clearScheduledMatchUps:()=>pm,findMatchUpFormatTiming:()=>Xp,generateBookings:()=>um,generateVirtualCourts:()=>nm,matchUpScheduleChange:()=>yR,modifyMatchUpFormatTiming:()=>Jg,proAutoSchedule:()=>fR,proConflicts:()=>hR,removeEventMatchUpFormatTiming:()=>ll,removeMatchUpCourtAssignment:()=>lR,reorderUpcomingMatchUps:()=>SR,scheduleMatchUps:()=>IR,scheduleProfileRounds:()=>mm,setMatchUpDailyLimits:()=>ER,setMatchUpHomeParticipantId:()=>uI,setSchedulingProfile:()=>Cc,toggleParticipantCheckInState:()=>Il,validateSchedulingProfile:()=>Jp});function yI({calculateStartTimeFromCourts:t=!0,defaultRecoveryMinutes:e=0,averageMatchUpMinutes:r=90,remainingScheduleTimes:n,clearScheduleDates:o,tournamentRecords:i,periodLength:s,scheduleDate:a,startTime:c,venueIds:u,endTime:p}){if(typeof i!="object"||!Object.keys(i).length)return{error:Lt};s=s??Hu({recoveryMinutes:e,averageMatchUpMinutes:r});let{courts:m,venues:d}=Uo({dates:[a],ignoreDisabled:!0,tournamentRecords:i}),l=m?.filter(M=>!u||u.includes(M.venueId));c||(c=l?.reduce((M,R)=>{let v=R.dateAvailability?.find(O=>!O.date||qn(a,O.date))?.startTime??R.startTime;return v&&(!M||Yt(v)<Yt(M))?v:M},void 0)),p||(p=l?.reduce((M,R)=>{let v=R.dateAvailability?.find(O=>!O.date||qn(a,O.date))?.endTime??R.endTime;return v&&(!M||Yt(v)>Yt(M))?v:M},void 0));let f=Object.values(i),g=Object.assign({},...f.map(M=>(M.events??[]).map(R=>{let{scheduleTiming:b}=Ea({tournamentRecord:M,event:R});return{[R.eventId]:{event:R,scheduleTiming:b}}})).flat()),h=Bu({sortDateMatchUps:!1,tournamentRecords:i,matchUpFilters:{scheduledDate:a,venueIds:u}}),S=h?.dateMatchUps??[],T=h?.completedMatchUps??[],y=[];y.push(...S),y.push(...T);let E={averageTimes:[{minutes:{default:r}}],recoveryTimes:[{minutes:{default:e}}]},P=y?.map(({eventId:M,schedule:R,matchUpFormat:b})=>{let{event:v,scheduleTiming:O}=g[M],x=v?.eventType,F={...O,defaultTiming:E,matchUpFormat:b},{averageMinutes:w,recoveryMinutes:L}=Mp({eventType:x,timingDetails:F}),{courtId:G,venueId:k}=R,H=Qt(R.scheduledTime),W=Yr(H,w);return{recoveryMinutes:L,averageMinutes:w,periodLength:s,startTime:H,endTime:W,courtId:G,venueId:k}}),A={calculateStartTimeFromCourts:t,remainingScheduleTimes:n,averageMatchUpMinutes:r,date:a,clearScheduleDates:o,periodLength:s,startTime:c,endTime:p,bookings:P,courts:l},{scheduleTimes:U}=gl(A),N=u?.length===1&&u[0]||d?.length===1&&d[0].venueId||void 0,D=y.map(Ue);return{venueId:N,scheduleTimes:U,dateScheduledMatchUpIds:D}}function lR(t){let e=et(t,[{[Re]:!0}]);if(e.error)return e;let{removePriorValues:r,tournamentRecords:n,tournamentId:o,courtDayDate:i,matchUpId:s,courtId:a,drawId:c}=t,u=n[o];if(!u)return{error:$};let{drawDefinition:p,event:m}=Fo({tournamentRecord:u,drawId:c});if(!p)return{error:Z};let d=Bt({drawDefinition:p,event:m,matchUpId:s});if(d.error)return d;if(d?.matchUp?.matchUpType===xr){let{itemValue:l}=Yo({timeItems:d.matchUp.timeItems??[],itemType:po}),f=a&&l.filter(I=>I.courtId!==a);return Jr({duplicateValues:!1,removePriorValues:r,tournamentRecord:u,drawDefinition:p,matchUpId:s,timeItem:{itemType:po,itemValue:f}})}else return Zi({tournamentRecord:u,drawDefinition:p,courtDayDate:i,courtId:"",matchUpId:s})}function fR({scheduleCompletedMatchUps:t,tournamentRecords:e,scheduledDate:r,matchUps:n}){if(!Vr(n))return{error:V};if(n.some(({hasContext:g})=>!g))return{info:"matchUps must have { inContext: true, nextMatchUps: true }",error:Bc};let i=Bu({courtCompletedMatchUps:!0,withCourtGridRows:!0,minCourtGridRows:10,tournamentRecords:e,matchUpFilters:{localPerspective:!0,scheduledDate:r}});if(i.error)return i;let{rows:s}=i,a=[],c=g=>[(g.sides||[]).map(I=>[I.participantId,I.participant?.individualParticipantIds]),(g.potentialParticipants||[]).flat().map(I=>[I.participantId,I.individualParticipantIds])].flat(1/0).filter(Boolean),u=s?.reduce((g,I)=>{let h=[],S=[];Object.values(I).forEach(y=>{if(ht(y)&&(y.matchUpId&&(h.push(y.matchUpId),a.push(y)),y.sides)){let E=c(y);S.push(...E)}});let T=Object.values(I).filter(y=>ht(y)&&!y.matchUpId);return g.concat({matchUpIds:h,availableCourts:T,rowId:I.rowId,participantIds:S})},[]);n.filter(({matchUpStatus:g})=>g&&g!==Nt&&(t||!se.includes(g))).sort(Ri);let p=on({matchUps:n.concat(a),includeParticipantDependencies:!0,tournamentRecords:e}).matchUpDependencies,m=[],d=[];for(;n.length&&u.length;){let g=u.shift(),I=[];for(;n.length&&g.availableCourts.length;){let h=n.concat(I).map(D=>D.matchUpId),S=n.shift(),T=S?.matchUpId,y=T&&p[T].matchUpIds.concat(p[T].dependentMatchUpIds),E=T&&h.some(D=>p[T].matchUpIds.includes(D)),P=T&&d.some(D=>p[T].dependentMatchUpIds.includes(D)),A=g.matchUpIds.some(D=>y.includes(D)),U=c(S),N=g.participantIds.some(D=>U.includes(D));if(S&&!A&&!E&&!N&&!P){let D=g.availableCourts.shift();Object.assign(S.schedule,D.schedule),Object.assign(D,S),m.push(S),g.participantIds.push(...U),g.matchUpIds.push(T)}else S&&I.push(S)}n.push(...I),d.push(...g.matchUpIds)}let l=m.map(({matchUpId:g,tournamentId:I,schedule:h,drawId:S})=>({tournamentId:I,matchUpId:g,drawId:S,schedule:{...h,scheduledDate:r}}));return i=Lc({tournamentRecords:e,matchUpDetails:l}),{...i,scheduled:m,notScheduled:n}}function gR(t){let{courtDayDate:e}=t,r=et(t,[{courtAssignments:!0,[He]:Be,[Fr]:st},{[Re]:!0}]);if(r.error)return r;let n=t.courtAssignments.reduce((s,a)=>{let{tournamentId:c}=a;return s[c]||(s[c]=[]),s[c].push(a),s},{}),o;return Object.keys(n).every(s=>{let a=t[Re][s];if(!a)return o={error:$},!1;let c=n[s].reduce((p,m)=>{let{drawId:d}=m;return p[d]||(p[d]=[]),p[d].push(m),p},{});Object.keys(c).every(p=>{let{drawDefinition:m}=ze({tournamentRecord:a,drawId:p});return m?(c[p].every(d=>{let{matchUpId:l,courtId:f}=d,g=Zi({tournamentRecord:a,drawDefinition:m,courtDayDate:e,matchUpId:l,courtId:f});if(g.success)return g?.success;o={error:bE}}),!0):(o={error:Z},!1)})}),o||C}function IR(t){let{tournamentRecords:e,allDateMatchUpIds:r=[],averageMatchUpMinutes:n=90,recoveryMinutes:o=0,recoveryMinutesMap:i,matchUpPotentialParticipantIds:s={},individualParticipantProfiles:a={},matchUpNotBeforeTimes:c={},matchUpDailyLimits:u={},checkPotentialRequestConflicts:p=!0,remainingScheduleTimes:m,clearScheduleDates:d,periodLength:l=30,scheduleDate:f,matchUpIds:g,venueIds:I,startTime:h,endTime:S,dryRun:T}=t,y=et(t,[{[Re]:!0,[nc]:!0},{[er]:Nr,[Fr]:je,[sb]:!0},{[er]:B=>!B||!isNaN(B),[pb]:!1,[Fr]:V,[mb]:!1,[db]:!1}]);if(y.error)return y;let E=t.competitionMatchUps??Un({nextMatchUps:!0,tournamentRecords:e}).matchUps??[],P=t.matchUpDependencies??on({includeParticipantDependencies:!0,matchUps:E,tournamentRecords:e}).matchUpDependencies;E.forEach(B=>{B.schedule?.scheduledDate&&qn(f,Pt(B.schedule.scheduledDate))&&ra({matchUpPotentialParticipantIds:s,matchUpNotBeforeTimes:c,matchUp:B})});let A=g.map(B=>E.find(K=>K.matchUpId===B)).filter(Boolean),{venueId:U,scheduleTimes:N,dateScheduledMatchUpIds:D}=yI({tournamentRecords:e,remainingScheduleTimes:m,startTime:Qt(h),endTime:Qt(S),scheduleDate:Pt(f),averageMatchUpMinutes:n,clearScheduleDates:d,periodLength:l,venueIds:I}),M={},R=[],b={},v={},O={};E.filter(({matchUpId:B})=>D?.includes(B)).forEach(B=>{fI({matchUpPotentialParticipantIds:s,individualParticipantProfiles:a,matchUp:B,value:1});let K=B.schedule?.scheduledTime;if(K){b[B.matchUpId]=K;let X=i?.[B.matchUpId];xc({recoveryMinutes:X||o,matchUpPotentialParticipantIds:s,individualParticipantProfiles:a,matchUpNotBeforeTimes:c,averageMatchUpMinutes:n,matchUpDependencies:P,scheduleTime:K,matchUp:B})}});let F=A.filter(B=>{let K=D?.includes(B.matchUpId),X=[Nt,Rt,he,vr,nr,bt].includes(B?.matchUpStatus);return!K&&!B.winningSide&&!X}),{matchUpMap:w,overLimitMatchUpIds:L,participantIdsAtLimit:G}=F.reduce((B,K)=>{let{drawId:X,tournamentId:j,matchUpType:ot}=K,{participantIdsAtLimit:z,relevantParticipantIds:Q}=Ul({individualParticipantProfiles:a,matchUpPotentialParticipantIds:s,matchUpDailyLimits:u,matchUp:K});return z?.length?(B.overLimitMatchUpIds.push(K.matchUpId),B.participantIdsAtLimit.push(...z),B):(Q.forEach(ut=>{ka({individualParticipantProfiles:a,participantId:ut});let it=a[ut].counters;it[ot]?it[ot]+=1:it[ot]=1,it[mo]?it[mo]+=1:it[mo]=1}),B.matchUpMap[j]||(B.matchUpMap[j]={}),B.matchUpMap[j][X]?B.matchUpMap[j][X].push(K):B.matchUpMap[j][X]=[K],ra({matchUpPotentialParticipantIds:s,matchUpNotBeforeTimes:c,matchUp:K}),B)},{matchUpMap:{},overLimitMatchUpIds:[],participantIdsAtLimit:[]});F=F.filter(({matchUpId:B})=>!L.includes(B));let k=0,H=N?.length??0,{personRequests:W}=Oi({tournamentRecords:e,requestType:wc});for(;N?.length&&F.length&&k<=H;){k++;let{scheduleTime:B}=N.shift(),K=F.find(X=>{let{matchUpId:j}=X,{dependenciesScheduled:ot,remainingDependencies:z}=yl({matchUpScheduleTimes:b,matchUpDependencies:P,allDateMatchUpIds:r,matchUp:X});if(!ot)return O[j]||(O[j]=[]),O[j].push({scheduleTime:B,remainingDependencies:z}),!1;let{enoughTime:Q}=El({individualParticipantProfiles:a,matchUpNotBeforeTimes:c,matchUpDependencies:P,scheduleTime:B,matchUp:X});if(!Q)return v[j]||(v[j]=[]),v[j].push({scheduleTime:B}),!1;let{conflicts:ut}=Al({potentials:p,averageMatchUpMinutes:n,requestConflicts:M,personRequests:W,scheduleTime:B,scheduleDate:f,matchUp:X});if(ut?.length)return!1;let it=i?.[X.matchUpId];return xc({recoveryMinutes:it||o,matchUpPotentialParticipantIds:s,individualParticipantProfiles:a,matchUpNotBeforeTimes:c,averageMatchUpMinutes:n,matchUpDependencies:P,scheduleTime:B,matchUp:X}),b[X.matchUpId]=B,!0});F=F.filter(({matchUpId:X})=>X!==K?.matchUpId),K||R.push(B)}F.forEach(B=>{fI({individualParticipantProfiles:a,matchUpPotentialParticipantIds:s,value:-1,matchUp:B})});let q=[];Object.keys(w).forEach(B=>{let K=e[B];K&&Object.keys(w[B]).forEach(X=>{let{drawDefinition:j}=Fo({tournamentRecord:K,drawId:X});j&&w[B][X].forEach(({matchUpId:z})=>{let Q=b[z];if(Q){let ut=Q.split(":").map(ro).join(":"),it=`${Pt(f)}T${ut}`;T?q.push(z):(Jo({drawDefinition:j,matchUpId:z,scheduledTime:it}).success&&q.push(z),U&&sa({tournamentRecords:e,tournamentRecord:K,drawDefinition:j,matchUpId:z,venueId:U}))}})})});let Y=Qm(F);return{...C,requestConflicts:Object.values(M),remainingScheduleTimes:N?.map(({scheduleTime:B})=>B),individualParticipantProfiles:a,matchUpNotBeforeTimes:c,participantIdsAtLimit:G,skippedScheduleTimes:R,overLimitMatchUpIds:L,scheduledMatchUpIds:q,noTimeMatchUpIds:Y,recoveryTimeDeferred:v,dependencyDeferred:O}}function hR({tournamentRecords:t,matchUps:e}){if(!Vr(e))return{error:eo};if(e.some(({matchUpId:f,hasContext:g})=>f&&!g))return{info:"matchUps must have { inContext: true, nextMatchUps: true }",error:Bc};let r=Math.max(...e.map(({schedule:f})=>f?.courtOrder||1).map(f=>dt(f))),n=tt(1,r+1).map(f=>e.filter(g=>dt(g.schedule?.courtOrder)===f)),o={},i={},s={};n.flat().filter(Boolean).sort(Ri).forEach(({schedule:f})=>delete f[cg]);let c=pt(e.map(({drawId:f})=>f)),u=on({includeParticipantDependencies:!0,tournamentRecords:t,drawIds:c}).matchUpDependencies,p=n.map((f,g)=>f.reduce((I,h)=>{if(!h.matchUpId)return I;let{matchUpId:S,winnerMatchUpId:T,loserMatchUpId:y,schedule:E,sides:P,potentialParticipants:A}=h,U=E?.courtId;o[S]=g,i[U]=[],I.matchUpIds.push(S),s[S]=h;let N=u[S].matchUpIds;N.length&&I.sourceMatchUpIds.push(...N);let D=P?.map(R=>[R.participant?.individualParticipantIds,R.participantId]).flat().filter(Boolean)??[],M=A?.flat().map(({individualParticipantIds:R,participantId:b})=>[R,b]).flat().filter(Boolean)||[];return I.participantIds.push(...M,...D),T&&I.targetMatchUpIds.push(T),y&&I.targetMatchUpIds.push(y),I},{sourceMatchUpIds:[],targetMatchUpIds:[],participantIds:[],matchUpIds:[]})),m=(f,g)=>u[f].sources.reduce((I,h,S)=>h.includes(g)&&S+1||I,0),d=p.map(()=>[]),l=(f,g,I,h)=>{if(!s[f].schedule[cg]){s[f].schedule[cg]=g,s[f].schedule[XU]=h,d[o[f]].push({matchUpId:f,issueType:I,issueIds:h,issue:g});let S=s[f].schedule.courtId;i[S]||(i[S]=[]),i[S].push({matchUpId:f,issue:g,issueType:I,issueIds:h})}};return p.forEach((f,g)=>{let I=g?p[g-1]:void 0,h=p.slice(g+1),S={},T=yr(f.participantIds),y=Object.keys(T).filter(A=>T[A]>1),E=f.matchUpIds.filter(A=>u[A].participantIds.some(U=>y.includes(U)));E.forEach(A=>{S[A]||(S[A]={}),S[A][mc]||(S[A][mc]=E.filter(U=>U!==A))});let P=I&&f.participantIds.filter(A=>I.participantIds.includes(A));P&&P.forEach(A=>{let U=f.matchUpIds.concat(I.matchUpIds).filter(N=>u[N].participantIds.includes(A));U.forEach(N=>{S[N]||(S[N]={}),S[N][dc]||(S[N][dc]=U.filter(D=>D!==N))})}),f.matchUpIds.forEach(A=>{let U=u[A].matchUpIds;for(let D of h){let M=D.matchUpIds.filter(R=>U.includes(R));M?.length&&(M.forEach(R=>l(R,fS,Ua,[A])),l(A,fS,Ua,M))}if(S[A]?.[mc]&&l(A,mc,lS,S[A][mc]),f.sourceMatchUpIds.includes(A)){let D=f.matchUpIds.filter(M=>u[M].matchUpIds.includes(A));l(A,mc,Ua,D),f.matchUpIds.filter(M=>u[M].matchUpIds.includes(A)).forEach(M=>l(M,mc,Ua,[A]))}let N=I?.matchUpIds?.filter(D=>m(A,D)>1);if(N?.length&&(l(A,gS,Ua,N),N.forEach(D=>l(D,gS,Ua,[A]))),S[A]?.[dc]&&l(A,dc,lS,S[A][dc]),I?.targetMatchUpIds?.includes(A)){let D=s[A].schedule.courtId,M=U.filter(b=>I.matchUpIds.includes(b));M.some(b=>s[b].schedule.courtId===D)||(M.forEach(b=>l(b,dc,Ua,[A])),l(A,dc,Ua,M))}})}),{courtIssues:i,rowIssues:d}}function SR(t){let e="reorderUpcomingMatchUps",{tournamentRecords:r}=t;if(typeof r!="object"||!Object.keys(r).length)return _({result:{error:Lt},stack:e});let{matchUpsContextIds:n,firstToLast:o}=t;if(!n)return _({result:{error:st},stack:e});let i=n?.length;if(!i)return{...C};let s=0;return n.forEach((c,u)=>{let{tournamentId:p,drawId:m,matchUpId:d}=c,l=u+(o?-1:1);l<0&&(l=i-1),l===i&&(l=0);let f=n[l].schedule.scheduledTime,g=a({tournamentId:p,scheduledTime:f,matchUpId:d,drawId:m});if(g.success)s++;else return g}),s===i?C:_({result:{error:CE},stack:e});function a({tournamentId:c,scheduledTime:u,matchUpId:p,drawId:m}){let d=r[c],{drawDefinition:l}=Fo({tournamentRecord:d,drawId:m});return l?Jo({drawDefinition:l,scheduledTime:u,matchUpId:p}):{error:Cr}}}function TR(t){let{scheduleChange:e,matchUpIds:r,dryRun:n}=t;if(!r||!Array.isArray(r))return{error:ns};if(typeof e!="object")return{error:V};let o=Mr(t),i=[],s=[];for(let c of Object.values(o)){let u=l0({tournamentRecord:c,scheduleChange:e,matchUpIds:r,dryRun:n});if(u.error)return u;Array.isArray(u.notRescheduled)&&s.push(...u.notRescheduled);let p=Qm(u.notRescheduled),m=[];u.rescheduled?.forEach(d=>{let{matchUpId:l}=d;p.includes(l)&&m.push(l),i.push(d)}),m.length&&(s=u?.notRescheduled?.filter(({matchUpId:d})=>!m.includes(d))||[])}let a=!!(i.length&&!s.length);return{...C,rescheduled:i,notRescheduled:s,allRescheduled:a}}function l0({tournamentRecord:t,scheduleChange:e,matchUpIds:r,dryRun:n}){if(!t)return{error:$};if(!r||!Array.isArray(r))return{error:ns};if(typeof e!="object")return{error:V};let o=[],i=[],{minutesChange:s,daysChange:a}=e;if(!s&&!a)return{...C};if(s&&isNaN(s))return{error:V};if(a&&isNaN(a))return{error:V};let{matchUps:c}=ye({matchUpFilters:{matchUpIds:r},tournamentRecord:t}),u=({matchUpStatus:y})=>!se.includes(y),p=c?.filter(y=>xa({schedule:y.schedule})).filter(y=>u({matchUpStatus:y.matchUpStatus}));if(!p?.length)return{...C};let{tournamentInfo:m}=Ps({tournamentRecord:t}),{startDate:d,endDate:l}=m,f=p?.reduce((y,E)=>{let{matchUpId:P,drawId:A}=E;return y[A]?y[A].push(P):y[A]=[P],y},{}),g=1440;for(let y of Object.keys(f)){let E=Fo({tournamentRecord:t,drawId:y});if(E.error)return E;let P=E.drawDefinition,A=f[y].filter(U=>r.includes(U));for(let U of A)if(U&&P){let D=p.find(x=>x.matchUpId===U)?.schedule,{scheduledTime:M,scheduledDate:R}=D,b,v,O;if(!b&&a&&R){let x=Pt(R);O=up(x,a),b=new Date(O)<new Date(d)||new Date(O)>new Date(l)}if(s&&M){let x=Pt(M),w=Yt(Qt(M))+s;if(b=w<0||w>g,!b){let L=Yr(M,s),G=x&&O||R===x&&x;v=G?`${G}T${L}`:L}}if(b)i.push(U);else{if(!n){if(v){let x=Jo({scheduledTime:v,drawDefinition:P,matchUpId:U});if(x.error)return x}if(O){let x=sm({scheduledDate:O,drawDefinition:P,matchUpId:U});if(x.error)return x}}(v||O)&&o.push(U)}}}let I=ye({matchUpFilters:{matchUpIds:r},tournamentRecord:t}).matchUps??[],h=I.filter(({matchUpId:y})=>o.includes(y)),S=I.filter(({matchUpId:y})=>i.includes(y)),T=h.length&&!S.length;return{...C,rescheduled:h,notRescheduled:S,allRescheduled:T}}function yR(t){let e="matchUpScheduleChange",{tournamentRecords:r}=t;if(typeof r!="object"||!Object.keys(r).length)return{error:Lt};let{sourceMatchUpContextIds:n,targetMatchUpContextIds:o,sourceCourtId:i,targetCourtId:s,courtDayDate:a}=t||{},{drawId:c,matchUpId:u,tournamentId:p}=n||{},{drawId:m,matchUpId:d,tournamentId:l}=o||{};if(!u&&!d)return _({result:{error:st},stack:e});let{matchUps:f}=Un({matchUpFilters:{matchUpIds:[u,d].filter(Boolean),drawIds:[c,m].filter(Boolean)},tournamentRecords:t.tournamentRecords}),g=f?.find(({matchUpId:y})=>y===u),I=f?.find(({matchUpId:y})=>y===d),h=0;if(s&&u&&!d){let y=S({tournamentId:p,matchUpId:u,courtId:s,matchUp:g,drawId:c,tournamentRecords:r,sourceCourtId:i,courtDayDate:a});if(y?.success&&h++,y.error)return _({result:y,stack:e})}else if(i&&s&&u&&d){let y=S({tournamentId:p,matchUpId:u,courtId:s,matchUp:g,drawId:c,tournamentRecords:r,sourceCourtId:i,courtDayDate:a});if(y.success&&h++,y.error)return _({result:y,stack:e,info:"source"});let E=S({tournamentId:l,sourceCourtId:s,matchUpId:d,matchUp:I,courtId:i,drawId:m,tournamentRecords:r,courtDayDate:a});if(E.success&&h++,E.error)return _({result:E,stack:e,info:"target"})}else return{error:st};return h?C:_({result:{error:xs},stack:e});function S(y){let{tournamentRecords:E,tournamentId:P,matchUp:A,drawId:U}=y,N=E[P],{drawDefinition:D}=Fo({tournamentRecord:N,drawId:U});return A.matchUpType===Wt?T({...y,tournamentRecord:N,drawDefinition:D}):Zi({...y,tournamentRecord:N,drawDefinition:D})}function T({removePriorValues:y,tournamentRecords:E,tournamentRecord:P,drawDefinition:A,sourceCourtId:U,courtDayDate:N,matchUpId:D,matchUp:M,courtId:R}){let b=[R].concat(M.schedule.allocatedCourts.map(({courtId:v})=>v).filter(v=>v!==U));return am({removePriorValues:y,tournamentRecords:E,tournamentRecord:P,drawDefinition:A,courtDayDate:N,matchUpId:D,courtIds:b})}}function AR({scheduleAttributes:t=[po,jo,ji,Yi,qi,xo,Ni,Di,$i],tournamentRecord:e,drawDefinition:r,matchUpId:n}){let o="clearMatchUpSchedule",i=r?ir({matchUpFilters:{matchUpIds:[n]},inContext:!1,drawDefinition:r}).matchUps?.[0]:ye({matchUpFilters:{matchUpIds:[n]},tournamentRecord:e,inContext:!1}).matchUps?.[0];if(!i)return{error:Le};let s=(i.timeItems??[]).filter(a=>a?.itemType&&!t.includes(a?.itemType));return i.timeItems=s,gt({tournamentId:e.tournamentId,context:o,drawDefinition:r,matchUp:i}),{...C}}function ER(t){let{tournamentRecord:e,tournamentId:r,dailyLimits:n}=t,o=t.tournamentRecords||e&&{[e.tournamentId]:e}||{};if(typeof o!="object"||!Object.keys(o).length)return{error:Lt};if(typeof n!="object")return{error:Io};let i=Object.keys(o).filter(s=>!r||r===s);if(r&&!i.includes(r))return{error:V};for(let s of i){let a=o[s],c=Ut({extension:{name:su,value:{dailyLimits:n}},element:a});if(c.error)return c}return{...C}}var xR={};Jt(xR,{addCollectionDefinition:()=>UI,addCollectionGroup:()=>CR,aggregateTieFormats:()=>OR,compareTieFormats:()=>Qo,getTieFormat:()=>el,modifyCollectionDefinition:()=>AI,modifyTieFormat:()=>vR,mutate:()=>_R,orderCollectionDefinitions:()=>RR,query:()=>gN,removeCollectionDefinition:()=>EI,removeCollectionGroup:()=>NR,tieFormatGenderValidityCheck:()=>bm,validateCollectionDefinition:()=>Kc});var _R={};Jt(_R,{addCollectionDefinition:()=>UI,addCollectionGroup:()=>CR,aggregateTieFormats:()=>OR,modifyCollectionDefinition:()=>AI,modifyTieFormat:()=>vR,orderCollectionDefinitions:()=>RR,removeCollectionDefinition:()=>EI,removeCollectionGroup:()=>NR});function pi({drawDefinition:t,structureId:e,matchUpId:r,structure:n,matchUp:o,eventId:i,event:s}){let a="getTieFormat",c;if(e=n?.structureId??e,r=o?.matchUpId??r,(r||e)&&!t)return{error:Z};if(i&&s)c=ii(s);else if(r){if(t&&(!o||!n)){let u=Bt({drawDefinition:t,matchUpId:r});if(u.error)return u;if(u.matchUp?.matchUpType!==xr)return _({result:{error:lr},stack:a});n||(n=u.structure),o||(o=u.matchUp)}c=Ep({item:o,drawDefinition:t,structure:n,event:s})||Ep({item:n,drawDefinition:t,structure:n,event:s})||ii(t)||ii(s)}else if(t&&e){if(!n){let u=at({drawDefinition:t,structureId:e});if(u.error)return u;n=u?.structure}c=Ep({item:n,drawDefinition:t,structure:n,event:s})||ii(t)||ii(s)}else c=ii(t)||ii(s);return c?{...C,structure:n,tieFormat:c,matchUp:o}:_({result:{error:vs},stack:a})}function Cl({matchUp:t,updateInProgressMatchUps:e}){return!t.winningSide&&![se].includes(t.matchUpStatus)&&(e||t.matchUpStatus!==Gn&&!Ie(t))}function DR({from:t,to:e}){let r=Object.keys(t),n=jt(r,Object.keys(e)).length===r.length,i=r.filter(c=>t[c]!==e[c]).map(c=>({countChange:e[c]-t[c],collectionId:c})),s=r.every(c=>t[c]===e[c]);return{equivalent:n&&s,matchUpsCountChanges:i}}function Sw({updateInProgressMatchUps:t,tournamentRecord:e,drawDefinition:r,structure:n,tieFormat:o,eventId:i,matchUp:s,event:a,uuids:c}){let u="updateTieFormat",p=e?.tournamentId,m=0,d=0,l=0,f=0,g=o?.collectionDefinitions.reduce((P,A)=>(P[A.collectionId]=(P[A.collectionId]||0)+A.matchUpCount,P),{}),I=({tieFormat:P})=>{let A=P?.collectionDefinitions.reduce((U,N)=>(U[N.collectionId]=(U[N.collectionId]||0)+N.matchUpCount,U),{});return DR({from:A,to:g}).equivalent},h=pi({drawDefinition:r})?.tieFormat,S=pi({event:a})?.tieFormat;if(a&&i){for(let P of a.drawDefinitions??[])T({drawDefinition:P});a.tieFormat=sr(o),f+=1}else if(s){if(!s.tieMatchUps)return _({result:{error:lr},stack:u});let P=yr(s.tieMatchUps?.map(({collectionId:M})=>M)),A=DR({to:g,from:P}),{changes:U,changesArePossible:N,cannotChangeReaon:D}=hw({matchUp:s,check:A});if(A.equivalent)if(Cl({matchUp:s,updateInProgressMatchUps:t}))s.tieFormat=sr(o),f+=1;else return _({result:{error:Xl},info:"matchUp is IN_PROGRESS or COMPLETE",stack:u});else if(N)E({tieFormat:o,matchUp:s,changes:U,uuids:c});else return _({context:{collectionMap:g,matchUpMap:P},result:{error:ko},info:D||"specified changes not possible",stack:u});d+=1,gt({eventId:a?.eventId,context:u,drawDefinition:r,tournamentId:p,matchUp:s})}else if(n){let A=y({inheritedTieFormat:h??S,structure:n})?.modifiedMatchUpsCount;A&&(d+=A,m+=1,f+=1);let U=!n.tieFormat||Qo({ancestor:n.tieFormat,descendant:o}).different;U&&(n.tieFormat=sr(o),m+=1,f+=1),(A||U)&&r&&vt({structureIds:[n.structureId],eventId:a?.eventId,drawDefinition:r})}else if(r)T({drawDefinition:r}),r.tieFormat=sr(o),f+=1;else return{error:Z};return{modifiedStructuresCount:m,modifiedMatchUpsCount:d,addedMatchUpsCount:l,modifiedCount:f,...C,tieFormat:o};function T({drawDefinition:P}){let A=P.structures||[],U=[];for(let N of A){if(N.tieFormat)continue;let M=y({inheritedTieFormat:S,structure:N})?.modifiedMatchUpsCount;if(M){m+=1,d+=M;let R=N.structureId;U.push(R)}}return vt({structureIds:U,eventId:a?.eventId,drawDefinition:P}),U.length}function y({inheritedTieFormat:P,structure:A}){let U=0,N=yt({matchUpFilters:{matchUpTypes:[Wt]},structure:A})?.matchUps||[];for(let D of N){let M=Cl({matchUp:D,updateInProgressMatchUps:t}),R=!1,b=yr(D.tieMatchUps?.map(({collectionId:O})=>O)),v=DR({from:b,to:g});if(v.equivalent)D.tieFormat&&I(D)&&M&&(D.tieFormat=sr(o),R=!0);else{let{changes:O,changesArePossible:x}=hw({matchUp:D,check:v});if(x&&!D.tieFormat)E({changes:O,matchUp:D,tieFormat:o,uuids:c});else if(P)(!D.tieFormat||Qo({ancestor:P,descendant:D.tieFormat}).different)&&(D.tieFormat=P,R=!0);else return _({result:{error:vs},stack:u})}R&&(U+=1,gt({tournamentId:e?.tournamentId,drawDefinition:r,context:u,eventId:i,matchUp:D}))}return{modifiedMatchUpsCount:U}}function E({uuids:P,matchUp:A,tieFormat:U,changes:N}){A.tieFormat=sr(U);let D=[],M=[];return N.forEach(R=>{if(R.countChange>0){let b=Math.max(0,...A.tieMatchUps.filter(x=>x.collectionId===R.collectionId).map(Br("collectionPosition"))),v=U.collectionDefinitions.find(x=>x.collectionId===R.collectionId),O=Ru({matchUpsLimit:R.countChange,collectionPositionOffset:b,collectionDefinition:v,matchUp:A,uuids:P});M.push(...J(O,!1,!0)),l+=M.length,A.tieMatchUps.push(...O)}else{let b=R.toBePlayedTieMatchUpIds.slice(0,Math.abs(R.countChange));console.log("remove",b.length),D.push(...b),A.tieMatchUps=A.tieMatchUps.filter(({matchUpId:v})=>!b.includes(v))}}),M.length&&vo({matchUps:M,drawDefinition:r,tournamentId:p,eventId:i}),D.length&&Rn({matchUpIds:D,action:"updateTieFormat",drawDefinition:r,tournamentId:p,eventId:i}),{matchUpIdsRemoved:D,matchUpsAdded:M}}}function hw({check:t,matchUp:e}){let r="",n=[];return{changesArePossible:t.matchUpsCountChanges.every(({collectionId:i,countChange:s})=>{let a=e.tieMatchUps.filter(u=>u.collectionId===i&&u.matchUpStatus===Xt).map(Br("matchUpId")),c=a.length+s>=0||s>0;return!c&&s<0&&(r="Insufficient TO_BE_PLAYED matchUps"),n.push({toBePlayedTieMatchUpIds:a,collectionId:i,countChange:s}),c}),changes:n,cannotChangeReaon:r}}function Yu({appliedPolicies:t,drawDefinition:e,auditData:r}){if(!t?.audit?.[zm])return;let{extension:n}=mt({name:zm,element:e}),o={value:Array.isArray(n?.value)?n?.value.concat(r):[r],name:zm};Ut({element:e,extension:o})}function AI({updateInProgressMatchUps:t=!1,tournamentRecord:e,collectionOrder:r,collectionName:n,tieFormatName:o,drawDefinition:i,matchUpFormat:s,matchUpCount:a,collectionId:c,matchUpType:u,structureId:p,matchUpId:m,category:d,eventId:l,gender:f,event:g,collectionValueProfiles:I,collectionValue:h,matchUpValue:S,scoreValue:T,setValue:y}){let E="modifyCollectionDefinition";if(s&&!Dr({matchUpFormat:s}))return _({result:{error:V},context:{matchUpFormat:s},stack:E});if(n&&typeof n!="string")return _({result:{error:V},context:{collectionName:n},stack:E});if(f&&!Object.values(Cm).includes(f))return _({result:{error:V},context:{gender:f},stack:E});if(d&&typeof d!="object")return _({result:{error:V},context:{category:d},stack:E});let P={collectionValueProfiles:I,collectionValue:h,matchUpValue:S,scoreValue:T,setValue:y};if(!Object.values(P).filter(Boolean).length&&!r&&!n&&!s&&!a&&!u)return _({result:{error:st},stack:E});if(Object.values(P).filter(Boolean).length>1)return _({info:"Only one value assignment allowed per collectionDefinition",result:{error:V},stack:E});let A=pi({drawDefinition:i,structureId:p,matchUpId:m,eventId:l,event:g});if(A.error)return _({result:A,stack:E});let{matchUp:U,structure:N,tieFormat:D}=A,M=sr(D),R=D?.collectionDefinitions.find(q=>q.collectionId===c),b=M?.collectionDefinitions.find(q=>q.collectionId===c);if(!R)return _({info:"source collectionDefinition",result:{error:ve},context:{collectionId:c},stack:E});let v=h??S??T??y;if(I?.length){let q=xI({matchUpCount:a??R?.matchUpCount??0,collectionValueProfiles:I});if(q.errors)return _({result:{error:V},info:q.errors,stack:E})}else if(v&&!It(v))return _({result:{error:V},info:"value is not an integer",context:{value:v},stack:E});let O=(q,Y)=>jt(Object.keys(q),Object.keys(Y)).length===Object.keys(q).length&&jt(Object.values(q),Object.values(Y)).length===Object.values(q).length,x=I&&(!R.collectionValueProfiles||!O(R.collectionValueProfiles,I)),F=It(h)&&R.collectionValue!==h||It(S)&&R.matchUpValue!==S||It(T)&&R.scoreValue!==T||It(y)&&R.setValue!==y||x,w=[];if(F&&(b.collectionValueProfiles=void 0,b.collectionValue=void 0,b.matchUpValue=void 0,b.scoreValue=void 0,b.setValue=void 0,Object.assign(b,P),w.push({collectionId:c,...nt(P)})),(It(T)||It(y))&&b.collectionGroupNumber){let q=b.collectionGroupNumber;M.collectionDefinitions=M.collectionDefinitions.map(Y=>{let{collectionGroupNumber:B,...K}=Y;return B===q?K:Y}),M.collectionGroups=M.collectionGroups.filter(({groupNumber:Y})=>Y!==q),w.push({collectionId:c,change:"collectionGroupNumber removed"})}let{aggregateValue:L,valueGoal:G}=Ds(M),k=nt({aggregateValue:L,valueGoal:G});if((k.aggregateValue!==D?.winCriteria.aggregateValue||k.valueGoal!==D?.winCriteria.valueGoal)&&(M.winCriteria=k,w.push({collectionId:c,winCriteria:k})),It(r)&&R.collectionOrder!==r&&(b.collectionOrder=r,w.push({collectionId:c,collectionOrder:r})),n&&R.collectionName!==n&&(b.collectionName=n,w.push({collectionId:c,collectionName:n})),s&&R.matchUpFormat!==s&&(b.matchUpFormat=s,w.push({collectionId:c,matchUpFormat:s})),It(a)&&R.matchUpCount!==a&&(b.matchUpCount=a,w.push({collectionId:c,matchUpCount:a})),u&&R.matchUpType!==u)return _({result:{error:np},context:{matchUpType:u},stack:E});d&&R.category!==d&&(b.category=d,w.push({collectionId:c,category:d})),f&&R.gender!==f&&(b.gender=f,w.push({collectionId:c,gender:f}));let H=nt(M);if(A=ur({tieFormat:H}),A.error)return _({result:A,stack:E});if(!w.length)return _({result:{...C,modifications:w}});if(D?.tieFormatName!==o?(H.tieFormatName=o,w.push({tieFormatName:o})):w.length&&(delete H.tieFormatName,w.push("tieFormatName removed: modifications without new tieFormatName")),A=Sw({tieFormat:H,updateInProgressMatchUps:t,tournamentRecord:e,drawDefinition:i,structure:N,eventId:l,matchUp:U,event:g}),!A.error){let{appliedPolicies:q}=Tt({tournamentRecord:e}),Y=nt({collectionDefinition:b,drawId:i?.drawId,action:E,structureId:p,matchUpId:m,eventId:l});Yu({appliedPolicies:q,drawDefinition:i,auditData:Y})}return _({result:{...A,modifications:w},stack:E})}function Tw({updateInProgressMatchUps:t,drawDefinition:e,structureId:r,structure:n,matchUpId:o,matchUp:i}){let s=[];return o&&i?s=[i]:r&&n?s=yt({matchUpFilters:{matchUpTypes:[Wt]},structure:n})?.matchUps??[]:e&&(s=ir({matchUpFilters:{matchUpTypes:[Wt]},drawDefinition:e})?.matchUps??[]),{targetMatchUps:s.filter(c=>!c.winningSide&&c.matchUpStatus!==he&&(t||c.matchUpStatus!==Gn&&!Ie(c)))}}function yw({updateInProgressMatchUps:t,tournamentRecord:e,drawDefinition:r,targetMatchUps:n,tieFormat:o,event:i}){for(let s of n){let a=!!s.tieFormat;a&&(s.tieFormat=sr(o));let c;if(t){let u=Tt({tournamentRecord:e,drawDefinition:r,event:i}).appliedPolicies,p=lo({matchUpId:s.matchUpId,exitWhenNoValues:!0,tournamentRecord:e,appliedPolicies:u,drawDefinition:r,event:i});if(p.error)return p;c=p.score}a&&!c&&gt({tournamentId:e?.tournamentId,context:"updateTargetTeamMatchUps",eventId:i?.eventId,matchUp:s,drawDefinition:r})}return{...C}}function hA({updateInProgressMatchUps:t,originalValueGoal:e,tournamentRecord:r,wasAggregateValue:n,tieFormatName:o,drawDefinition:i,structureId:s,structure:a,tieFormat:c,matchUpId:u,matchUp:p,eventId:m,event:d}){let{aggregateValue:l,valueGoal:f}=Ds(c);c.winCriteria=nt({aggregateValue:l,valueGoal:f}),(e&&e!==f||l&&!n)&&(o?c.tieFormatName=o:delete c.tieFormatName);let{targetMatchUps:g}=Tw({updateInProgressMatchUps:t,drawDefinition:i,structureId:s,structure:a,matchUpId:u,matchUp:p});yw({updateInProgressMatchUps:t,tournamentRecord:r,targetMatchUps:g,drawDefinition:i,tieFormat:c,event:d});let I=nt(c),h=ur({tieFormat:I});if(h.error)return h;if(m&&d)d.tieFormat=I;else if(u&&p)p.tieFormat=c;else if(a)a.tieFormat=I;else if(i)i.tieFormat=I;else if(!p||!i)return{error:Z};return vt({drawDefinition:i,eventId:d?.eventId}),{...C}}function NR({updateInProgressMatchUps:t=!0,collectionGroupNumber:e,tournamentRecord:r,drawDefinition:n,tieFormatName:o,structureId:i,matchUpId:s,matchUp:a,eventId:c,event:u}){if(!e)return{error:st};if(isNaN(e))return{error:V};let p="removeCollectionGroup",m=a?void 0:pi({drawDefinition:n,structureId:i,matchUpId:s,eventId:c,event:u});if(m?.error)return _({result:m,stack:p});let d=m?.structure;a=a??m?.matchUp;let l=m?.tieFormat,f=l?.winCriteria.valueGoal,g=l?.winCriteria.aggregateValue,I=sr(l);if(m=ur({tieFormat:I}),m.error)return _({result:m,stack:p});let h=[];if(I.collectionDefinitions=I.collectionDefinitions.map(S=>{let{collectionGroupNumber:T,...y}=S;return T!==e?S:(h.push(S.collectionId),y)}),I.collectionGroups=I.collectionGroups.filter(({groupNumber:S})=>S!==e),m=hA({updateInProgressMatchUps:t,originalValueGoal:f,wasAggregateValue:g,tournamentRecord:r,drawDefinition:n,tieFormatName:o,structureId:i,structure:d,tieFormat:I,matchUpId:s,matchUp:a,eventId:c,event:u}),!m.error){let{appliedPolicies:S}=Tt({tournamentRecord:r}),T=nt({drawId:n?.drawId,collectionGroupNumber:e,action:p,structureId:i,matchUpId:s,eventId:c});Yu({appliedPolicies:S,drawDefinition:n,auditData:T})}return _({result:{...m,modifiedCollectionIds:h},stack:p})}function bl({tieFormat:t,orderMap:e}){let r=sr(t);return r.collectionDefinitions?.forEach(n=>{let o=e[n.collectionId];o&&(n.collectionOrder=o)}),r.collectionDefinitions?.sort((n,o)=>Ha(n.collectionOrder)-Ha(o.collectionOrder)),r}function RR({tournamentRecord:t,drawDefinition:e,structureId:r,matchUpId:n,orderMap:o,eventId:i,matchUp:s,event:a}){if(typeof o!="object"||!Object.values(o).every(p=>It(p)))return _({result:{error:V},context:{orderMap:o}});let c=r?at({drawDefinition:e,structureId:r}):void 0;if(c?.error)return c;let u=c?.structure;if(i&&a?.tieFormat)Aw({tournamentRecord:t,event:a,orderMap:o});else if(n){let p=e&&Bt({drawDefinition:e,matchUpId:n});if(p?.error)return p;if(s=p.matchUp,!s)return{error:Tr};let m=el({tournamentRecord:t,matchUpId:n,structure:u,drawDefinition:e,event:a})?.tieFormat;s.tieFormat=bl({tieFormat:m,orderMap:o}),gt({tournamentId:t?.tournamentId,eventId:a?.eventId,drawDefinition:e,matchUp:s})}else if(r)if(u?.tieFormat)u.tieFormat=bl({tieFormat:u.tieFormat,orderMap:o}),Ew({eventId:a?.eventId,tournamentRecord:t,drawDefinition:e,structure:u,orderMap:o}),vt({drawDefinition:e,structureIds:[u.structureId]});else if(e.tieFormat)MR({structureIds:[r],tournamentRecord:t,drawDefinition:e,orderMap:o,event:a});else if(a?.tieFormat)Aw({structureIds:[r],tournamentRecord:t,orderMap:o,event:a});else return{error:ve};else if(e?.tieFormat)MR({tournamentRecord:t,drawDefinition:e,orderMap:o,event:a});else return{error:ve};return{...C}}function Aw({tournamentRecord:t,structureIds:e,orderMap:r,event:n}){let o=bl({tieFormat:n.tieFormat,orderMap:r});e?.length||(n.tieFormat=o);for(let i of n.drawDefinitions??[])MR({tournamentRecord:t,drawDefinition:i,structureIds:e,orderMap:r,event:n})}function MR({tournamentRecord:t,drawDefinition:e,structureIds:r,orderMap:n,event:o}){let i=e.tieFormat??o?.tieFormat,s=bl({tieFormat:i,orderMap:n});r?.length||(e.tieFormat=s);let a=[];for(let c of e.structures??[])r?.length&&!r.includes(c.structureId)||((c.tieFormat||r?.includes(c.structureId))&&(c.tieFormat=bl({tieFormat:c.tieFormat??e.tieFormat??o?.tieFormat,orderMap:n})),Ew({eventId:o?.eventId,tournamentRecord:t,drawDefinition:e,structure:c,orderMap:n}),a.push(c.structureId));vt({drawDefinition:e,structureIds:a})}function Ew({tournamentRecord:t,drawDefinition:e,structure:r,orderMap:n,eventId:o}){let i=yt({matchUpFilters:{matchUpTypes:[Wt]},structure:r})?.matchUps;for(let s of i)s.tieFormat&&(s.tieFormat=bl({tieFormat:s.tieFormat,orderMap:n}),gt({tournamentId:t?.tournamentId,drawDefinition:e,eventId:o,matchUp:s}))}function EI({updateInProgressMatchUps:t=!0,tieFormatComparison:e,tournamentRecord:r,drawDefinition:n,tieFormatName:o,collectionId:i,structureId:s,matchUpId:a,eventId:c,matchUp:u,event:p}){let m="removeCollectionDefinition",d=u?void 0:pi({drawDefinition:n,structureId:s,matchUpId:a,eventId:c,event:p});if(d?.error)return _({result:d,stack:m});let l=d?.structure;u=u??d?.matchUp;let f=d?.tieFormat,g=sr(f);if(d=ur({tieFormat:g}),d.error)return _({result:d,stack:m});let I=g?.collectionDefinitions?.find(M=>M.collectionId===i);if(!I)return _({result:{error:ve,collectionId:i}});g.collectionDefinitions=g.collectionDefinitions.filter(M=>M.collectionId!==i),I.collectionGroupNumber&&(g.collectionDefinitions=g.collectionDefinitions.map(M=>{let{collectionGroupNumber:R,...b}=M;return b}),g.collectionGroups=g.collectionGroups.filter(({groupNumber:M})=>M!==I.collectionGroupNumber));let{aggregateValue:h,valueGoal:S}=Ds(g);g.winCriteria=nt({aggregateValue:h,valueGoal:S});let T=f?.winCriteria.valueGoal,y=f?.winCriteria.aggregateValue;(T&&T!==S||h&&!y)&&(o?g.tieFormatName=o:delete g.tieFormatName);let E=[];a&&u?E=[u]:s&&l?E=yt({matchUpFilters:{matchUpTypes:[Wt]},structure:l})?.matchUps??[]:n?E=ir({matchUpFilters:{matchUpTypes:[Wt]},drawDefinition:n})?.matchUps??[]:p&&(E=Xn({matchUpFilters:{matchUpTypes:[Wt]},drawDefinition:n})?.matchUps??[]);let P=(E||[]).filter(M=>{let b=M.tieMatchUps?.filter(O=>O.collectionId===i)?.some(Ie),v=e&&M.tieFormat?Qo({descendant:M.tieFormat,ancestor:g})?.different:!1;return t&&!b||!M.winningSide&&M.matchUpStatus!==he&&(t||M.matchUpStatus!==Gn&&!Ie(M)&&!v)});if(!P.length)return{error:xs};let{appliedPolicies:A}=Tt({tournamentRecord:r});if(a&&u&&t){let M=u.tieMatchUps?.filter(R=>R.collectionId===i);for(let R of M??[]){let b=Fa({matchUpId:R.matchUpId,tieMatchUpId:u?.matchUpId,winningSide:void 0,removeScore:!0,tournamentRecord:r,appliedPolicies:A,drawDefinition:n,event:p});if(b.error||(b=Bt({drawDefinition:n,matchUpId:a}),b.error))return b;u=b?.matchUp}}let U=[];for(let M of P){for(let R of M?.sides??[])R.lineUp=(R.lineUp??[]).map(b=>({participantId:b.participantId,collectionAssignments:(b?.collectionAssignments??[]).filter(v=>v.collectionId!==i)}));if(M.tieMatchUps=(M.tieMatchUps??[]).filter(R=>{let b=R.collectionId===i;return b&&U.push(R.matchUpId),!b}),M.tieFormat&&(M.tieFormat=sr(g)),t){let R=lo({matchUpId:M.matchUpId,exitWhenNoValues:!0,tournamentRecord:r,appliedPolicies:A,drawDefinition:n,event:p});if(R.error)return R}gt({tournamentId:r?.tournamentId,eventId:p?.eventId,drawDefinition:n,context:m,matchUp:M})}U.length&&Rn({tournamentId:r?.tournamentId,matchUpIds:U,eventId:p?.eventId,drawDefinition:n});let N=nt(g);if(d=ur({tieFormat:N}),d.error)return _({result:d,stack:m});if(c&&p)p.tieFormat=N;else if(a&&u)u.tieFormat=N;else if(l)l.tieFormat=N;else if(n)n.tieFormat=N;else if(!u||!n)return{error:Z};vt({drawDefinition:n,eventId:p?.eventId});let D=nt({drawId:n?.drawId,action:m,collectionId:i,structureId:s,matchUpId:a,eventId:c});return Yu({appliedPolicies:A,drawDefinition:n,auditData:D}),{tieFormat:N,deletedMatchUpIds:U,targetMatchUps:P,...C}}function CR({updateInProgressMatchUps:t=!0,tournamentRecord:e,groupDefinition:r,drawDefinition:n,collectionIds:o,tieFormatName:i,structureId:s,matchUpId:a,matchUp:c,eventId:u,event:p}){let m="addCollectionGroup";if(!Array.isArray(o))return _({result:{error:st},stack:m});let d=c?void 0:pi({drawDefinition:n,structureId:s,matchUpId:a,eventId:u,event:p});if(d?.error)return _({result:d,stack:m});let l=d?.structure;c=c||d?.matchUp;let f=d?.tieFormat,g=f?.winCriteria.valueGoal,I=sr(f);if(d=ur({tieFormat:I}),d.error)return _({result:d,stack:m});for(let T of I.collectionDefinitions){let{collectionId:y,collectionGroupNumber:E}=T;if(E&&o.includes(y))return _({info:"collectionIds cannot be part of other collectionGroups",result:{error:V},stack:m})}let S=(I.collectionGroups||[]).reduce((T,y)=>y.groupNumber>T?y.groupNumber:T,0)+1;return r.groupNumber=S,I.collectionDefinitions=I.collectionDefinitions.map(T=>o.includes(T.collectionId)?{...T,collectionGroupNumber:S}:T),I.collectionGroups=[...I.collecitonGroups||[],r],hA({updateInProgressMatchUps:t,originalValueGoal:g,tournamentRecord:e,drawDefinition:n,tieFormatName:i,structureId:s,structure:l,tieFormat:I,matchUpId:a,matchUp:c,eventId:u,event:p})}function UI({updateInProgressMatchUps:t=!0,collectionDefinition:e,referenceCategory:r,tournamentRecord:n,policyDefinitions:o,enforceCategory:i,referenceGender:s,drawDefinition:a,tieFormatName:c,enforceGender:u,structureId:p,matchUpId:m,matchUp:d,eventId:l,uuids:f,event:g}){let I="addCollectionDefinition",h=Tt({tournamentRecord:n,drawDefinition:a,event:g}).appliedPolicies??{},S=o?.[rr]??h?.[rr];i=i??S?.participants?.enforceCategory;let T=(u??S?.participants?.enforceGender)!==!1,y=!!((r??g?.category)&&i!==!1),E=!!((s??g?.gender)&&T),P=Kc({referenceCategory:r??g?.category,collectionDefinition:e,referenceGender:s,checkCategory:y,checkGender:E,event:g});if(P.error)return _({result:P,stack:I});let A=d?.tieFormat?void 0:pi({drawDefinition:a,structureId:p,matchUpId:m,eventId:l,event:g});if(A?.error)return _({result:{error:A.error},stack:I});let U=A?.structure;d=d??A?.matchUp;let N=d?.tieFormat??A?.tieFormat,D=sr(N);if(A=ur({tieFormat:D}),A?.error)return _({result:{error:A.error},stack:I});if(!e.collectionId)e.collectionId=Mt();else if(D.collectionDefinitions.map(({collectionId:k})=>k).includes(e.collectionId))return _({context:{collectionId:e.collectionId},result:{error:_E}});D.collectionDefinitions.push(e),D.collectionDefinitions.sort((G,k)=>(G.collectionOrder||0)-(k.collectionOrder||0)).forEach((G,k)=>G.collectionOrder=k+1);let{aggregateValue:M,valueGoal:R}=Ds(D);D.winCriteria=nt({aggregateValue:M,valueGoal:R});let b=N?.winCriteria.valueGoal,v=N?.winCriteria.aggregateValue;(b&&b!==R||M&&!v)&&(c?D.tieFormatName=c:delete D.tieFormatName);let O=[],x=[],F=[],w=nt(D);if(A=ur({tieFormat:w}),A?.error)return _({result:{error:A.error},stack:I});if(l&&g){g.tieFormat=w;for(let G of g.drawDefinitions??[])if(!G.tieFormat)for(let k of G.structures??[]){if(k.tieFormat)continue;let H=bR({updateInProgressMatchUps:t,collectionDefinition:e,structure:k,uuids:f});x.push(...H.newMatchUps),F.push(...H.targetMatchUps),O.push(k.structureId)}SA({modifiedMatchUps:F,eventId:g?.eventId,modifiedStructureIds:O,tournamentRecord:n,drawDefinition:a,addedMatchUps:x,stack:I})}else if(p&&U){U.tieFormat=w;let G=bR({updateInProgressMatchUps:t,collectionDefinition:e,structure:U,uuids:f});x.push(...G.newMatchUps),F=G.targetMatchUps,SA({modifiedMatchUps:F,eventId:g?.eventId,modifiedStructureIds:O,tournamentRecord:n,drawDefinition:a,addedMatchUps:x,stack:I})}else if(m&&d){if(!Cl({matchUp:d,updateInProgressMatchUps:t}))return _({result:{error:Xl},stack:I});d.tieFormat=w;let G=Ru({collectionDefinition:e,matchUp:d,uuids:f});Array.isArray(d.tieMatchUps)||(d.tieMatchUps=[]),d.tieMatchUps.push(...G),x.push(...G),SA({modifiedMatchUps:[d],eventId:g?.eventId,modifiedStructureIds:O,tournamentRecord:n,drawDefinition:a,addedMatchUps:x,stack:I})}else if(a){a.tieFormat=w;for(let G of a.structures??[]){let k=bR({updateInProgressMatchUps:t,collectionDefinition:e,structure:G,uuids:f});O.push(G.structureId),x.push(...k.newMatchUps),F.push(...k.targetMatchUps)}SA({modifiedMatchUps:F,eventId:g?.eventId,tournamentRecord:n,drawDefinition:a,addedMatchUps:x,stack:I})}else return{error:Z};let L=nt({drawId:a?.drawId,collectionDefinition:e,action:I,structureId:p,matchUpId:m,eventId:l});return Yu({appliedPolicies:h,drawDefinition:a,auditData:L}),{tieFormat:w,targetMatchUps:F,addedMatchUps:x,...C}}function bR({updateInProgressMatchUps:t,collectionDefinition:e,structure:r,uuids:n}){let o=[],s=(yt({matchUpFilters:{matchUpTypes:[Wt]},structure:r})?.matchUps).filter(a=>Cl({matchUp:a,updateInProgressMatchUps:t})&&!a.tieFormat);for(let a of s){let c=Ru({collectionDefinition:e,matchUp:a,uuids:n});Array.isArray(a.tieMatchUps)||(a.tieMatchUps=[]),a.tieMatchUps.push(...c),o.push(...c)}return{newMatchUps:o,targetMatchUps:s}}function SA({modifiedStructureIds:t,tournamentRecord:e,modifiedMatchUps:r,drawDefinition:n,addedMatchUps:o,eventId:i,stack:s}){vo({tournamentId:e?.tournamentId,matchUps:o,drawDefinition:n,eventId:i}),r?.forEach(a=>{gt({tournamentId:e?.tournamentId,drawDefinition:n,context:s,matchUp:a,eventId:i})}),vt({structureIds:t,drawDefinition:n,eventId:i})}function vR({updateInProgressMatchUps:t=!1,tieFormatComparison:e,modifiedTieFormat:r,tournamentRecord:n,considerations:o,drawDefinition:i,structureId:s,matchUpId:a,eventId:c,uuids:u,event:p}){let m="modifyTieFormat";if(!ur({tieFormat:r}).valid)return _({result:{error:ko},info:"falied validation",stack:m});let d=pi({drawDefinition:i,structureId:s,matchUpId:a,eventId:c,event:p});if(d.error)return _({result:d,stack:m});let{matchUp:l,tieFormat:f}=d,g=sr(f),I=Qo({descendant:r,ancestor:g,considerations:o});if(I.invalid)return _({context:{invalid:I.invalid},result:{error:ko},stack:m});if(!I?.different)return _({result:{...C},info:"Nothing to do",stack:m});let h=g.collectionDefinitions.map(({collectionId:D})=>D),S=r.collectionDefinitions.map(({collectionId:D})=>D),T=h.filter(D=>!S.includes(D)),y=r.collectionDefinitions.filter(({collectionId:D})=>!h.includes(D)),E=y.map(Br("collectionId")),P=[],A,U=r.tieFormatName;for(let D of r.collectionDefinitions){if(E.includes(D.collectionId))continue;let M=AI({updateInProgressMatchUps:t,...D,tournamentRecord:n,tieFormatName:U,drawDefinition:i,structureId:s,matchUpId:a,eventId:c,event:p});if(M.modifications&&P.push(...M.modifications),M.error)return _({result:M,stack:m});M.tieFormat&&(A=M.tieFormat)}for(let D of y){let M=UI({updateInProgressMatchUps:t,collectionDefinition:D,tournamentRecord:n,drawDefinition:i,tieFormatName:U,structureId:s,matchUpId:a,matchUp:l,eventId:c,uuids:u,event:p});if(M.error)return _({result:M,stack:m});M.tieFormat&&(A=M.tieFormat)}for(let D of T){let M=EI({updateInProgressMatchUps:t,tieFormatComparison:e,tournamentRecord:n,drawDefinition:i,tieFormatName:U,collectionId:D,structureId:s,matchUpId:a,eventId:c,matchUp:l,event:p});if(M.error)return _({result:M,stack:m});M.tieFormat&&(A=M.tieFormat)}return f?.tieFormatName!==U?(A.tieFormatName=U,P.push({tieFormatName:U})):(P.length||E.length||T.length)&&(delete A.tieFormatName,P.push("tieFormatName removed: modifications without new tieFormatName")),A.collectionDefinitions=A.collectionDefinitions.sort((D,M)=>Ha(D.collectionOrder)-Ha(M.collectionOrder)).map((D,M)=>({...D,collectionOrder:M+1})),{processedTieFormat:sr(A),modifications:P,...C}}function OR({tournamentRecord:t}){if(!t)return{error:$};let e=0;for(let r of t.events??[]){let n=r.tieFormats??[],o=p=>{if(!p.tieFormat)return;let m;for(let d of n)Qo({descendant:p.tieFormat,ancestor:d}).different||(m=d.tieFormatId);if(m)p.tieFormatId=m,delete p.tieFormat;else{let d=J(p.tieFormat,void 0,!0);d.tieFormatId||(d.tieFormatId=Mt()),p.tieFormatId=d.tieFormatId,delete p.tieFormat,n.push(d),e+=1}},i=r.eventType;o({tieFormat:r.tieFormat,eventType:i});for(let p of r.drawDefinitions??[]){o({tieFormat:p.tieFormat,eventType:i});for(let m of p.structures??[])o({tieFormat:m.tieFormat,eventType:i})}let s=(p,m)=>{let d=c.matchUps?.find(l=>l.matchUpId===p);d&&(d.tieFormatId=m,delete d.tieFormat,gt({tournamentId:t?.tournamentId,eventId:r.eventId,matchUp:d}))},a=p=>{let m=J(p.tieFormat,void 0,!0);m.tieFormatId||(m.tieFormatId=Mt()),n.push(m),e+=1,s(p.matchUpId,m.tieFormatId)},c=Xn({matchUpFilters:{matchUpTypes:[xr]},event:r}),u=c.matchUps??[];for(let p of u){let m;for(let d of n)p.tieFormat&&Qo({descendant:p.tieFormat,ancestor:d}).different||(m=d.tieFormatId);m?s(p.matchUpId,m):a(p)}n.length&&(r.tieFormats=n)}return{...C,addedCount:e}}var qR={};Jt(qR,{addDrawDefinitionExtension:()=>hp,addEventExtension:()=>Ro,addEventTimeItem:()=>Xi,addExtension:()=>Ut,addNotes:()=>Vp,addOnlineResource:()=>GR,addParticipantExtension:()=>yU,addParticipantTimeItem:()=>xg,addTimeItem:()=>to,addTournamentExtension:()=>xf,addTournamentTimeItem:()=>Nc,analyzeDraws:()=>_u,analyzeTournament:()=>ty,copyTournamentRecord:()=>wR,createTournamentRecord:()=>dm,generate:()=>LR,getAggregateTeamResults:()=>ZT,getAllowedDrawTypes:()=>Qd,getAllowedMatchUpFormats:()=>zT,getAppliedPolicies:()=>Tt,getCompetitionDateRange:()=>Jd,getCompetitionPenalties:()=>QT,getPolicyDefinitions:()=>_o,getTournamentInfo:()=>Ps,getTournamentPenalties:()=>Xd,getTournamentPersons:()=>JT,getTournamentPoints:()=>Zd,getTournamentStructures:()=>LS,getTournamentTimeItem:()=>td,mutate:()=>YR,query:()=>lN,removeDrawDefinitionExtension:()=>AU,removeEventExtension:()=>Sp,removeExtension:()=>gr,removeNotes:()=>Og,removeOnlineResource:()=>kR,removeParticipantExtension:()=>EU,removeTournamentExtension:()=>wf,setTournamentCategories:()=>HR,setTournamentDates:()=>PI,setTournamentEndDate:()=>jR,setTournamentName:()=>VR,setTournamentNotes:()=>BR,setTournamentStartDate:()=>WR,setTournamentStatus:()=>FR});var LR={};Jt(LR,{copyTournamentRecord:()=>wR,createTournamentRecord:()=>dm});function wR(t){let e=et(t,[{tournamentRecord:!0,startDate:!0,endDate:!1,tournamentName:!0}]);if(e.error)return e;let{startDate:r,endDate:n}=t.tournamentRecord,o=24*60*60*1e3,s=(r&&n?new Date(Pt(n)).getTime()-new Date(Pt(r)).getTime():0)/o,a=t.endDate||nh(t.startDate,s),c=l=>l?.filter(({itemType:f})=>t.itemTypeList?.includes(f)),u=l=>l?.filter(({name:f})=>t.extensionList?.includes(f)),p=l=>{let{timeItems:f,extensions:g,...I}=l;return J({...I,timeItems:c(f),extensions:u(g)},!1,!0)},m=l=>{let{drawDefinitions:f,timeItems:g,extensions:I,startDate:h,endDate:S,...T}=l;return J({extensions:u(I),timeItems:c(g),startDate:t.startDate,endDate:a,...T},!1,!0)},d={participants:t.copyParticipants?t.tournamentRecord.participants?.map(p)??[]:[],parentOrganisation:J({...t.tournamentRecord.parentOrganisation},!1,!0),venues:J(t.tournamentRecord.venues??[],!1,!0),extensions:u(t.tournamentRecord.extensions),timeItems:c(t.tournamentRecord.timeItems),events:t.tournamentRecord.events?.map(m)??[],weekdays:[...t.tournamentRecord.weekdays??[]],tournamentName:t.tournamentName,startDate:t.startDate,tournamentId:Mt(),endDate:a};return{...C,tournamentRecord:d}}var YR={};Jt(YR,{addDrawDefinitionExtension:()=>hp,addEventExtension:()=>Ro,addEventTimeItem:()=>Xi,addExtension:()=>Ut,addNotes:()=>Vp,addOnlineResource:()=>GR,addParticipantExtension:()=>yU,addParticipantTimeItem:()=>xg,addTimeItem:()=>to,addTournamentExtension:()=>xf,addTournamentTimeItem:()=>Nc,removeDrawDefinitionExtension:()=>AU,removeEventExtension:()=>Sp,removeExtension:()=>gr,removeNotes:()=>Og,removeOnlineResource:()=>kR,removeParticipantExtension:()=>EU,removeTournamentExtension:()=>wf,setTournamentCategories:()=>HR,setTournamentDates:()=>PI,setTournamentEndDate:()=>jR,setTournamentName:()=>VR,setTournamentNotes:()=>BR,setTournamentStartDate:()=>WR,setTournamentStatus:()=>FR});var f0="ABANDONED",g0="ACTIVE",I0="CANCELLED",h0="COMPLETED",S0="IN_PROGRESS",TA={ABANDONED:f0,ACTIVE:g0,CANCELLED:I0,COMPLETED:h0,IN_PROGRESS:S0};function FR({tournamentRecord:t,status:e}){return t?e&&!Object.keys(TA).includes(e)?{error:V,info:"Unknown status"}:(t.tournamentStatus=e,{...C}):{error:$}}function kR(t){let e=et(t,[{tournamentRecord:!0,onlineResource:!0}]);if(e.error)return e;let{tournamentRecord:r,onlineResource:n,organisationId:o,participantId:i,personId:s,courtId:a,venueId:c}=t;if(o){if(r.parentOrganisation?.parentOrganisationId!==o)return _({result:{error:ve}});vl({element:r.parentOrganisation,onlineResource:n})}else if(i||s){let u=(r.participants??[]).find(p=>s&&p.person?.personId===s||p.participantId===i);if(!u)return s?_({result:{error:ve}}):_({result:{error:re}});if(s){if(u.person?.personId!==s)return _({result:{error:Li}});vl({element:u.person,onlineResource:n})}else vl({element:u,onlineResource:n})}else if(a){let u=(r.venues??[]).filter(p=>!c||p.venueId===c).flatMap(p=>(p.courts??[]).filter(m=>m.courtId===a))?.[0];if(!u)return _({result:{error:_s}});vl({element:u,onlineResource:n})}else if(c){let u=(r.venues??[]).find(p=>p.venueId===c);if(!u)return _({result:{error:ki}});vl({element:u,onlineResource:n})}else vl({element:r,onlineResource:n}),lt({payload:{parentOrganisation:r.parentOrganisation,onlineResources:r.onlineResources,tournamentId:r.tournamentId},topic:Wi});return{...C}}function vl({element:t,onlineResource:e}){let r=(t.onlineResources??[]).filter(n=>!(n?.[tc]===e[tc]&&n?.[ec]===e[ec]&&n?.[rc]===e[rc]));t.onlineResources=r}function GR(t){let e=et(t,[{tournamentRecord:!0,onlineResource:!0}]);if(e.error)return e;let{tournamentRecord:r,onlineResource:n,organisationId:o,participantId:i,personId:s,courtId:a,venueId:c}=t;if(o){if(r.parentOrganisation?.parentOrganisationId!==o)return _({result:{error:ve}});Ol({element:r.parentOrganisation,onlineResource:n})}else if(i||s){let u=(r.participants??[]).find(p=>s&&p.person?.personId===s||p.participantId===i);if(!u)return s?_({result:{error:ve}}):_({result:{error:re}});if(s){if(u.person?.personId!==s)return _({result:{error:Li}});Ol({element:u.person,onlineResource:n})}else Ol({element:u,onlineResource:n})}else if(a){let u=(r.venues??[]).filter(p=>!c||p.venueId===c).flatMap(p=>(p.courts??[]).filter(m=>m.courtId===a))?.[0];if(!u)return _({result:{error:_s}});Ol({element:u,onlineResource:n})}else if(c){let u=(r.venues??[]).find(p=>p.venueId===c);if(!u)return _({result:{error:ki}});Ol({element:u,onlineResource:n})}else Ol({element:r,onlineResource:n}),lt({payload:{parentOrganisation:r.parentOrganisation,onlineResources:r.onlineResources,tournamentId:r.tournamentId},topic:Wi});return{...C}}function Ol({element:t,onlineResource:e}){let r=(t.onlineResources??[]).filter(n=>n?.[tc]!==e[tc]&&n?.[ec]!==e[ec]&&n?.[rc]!==e[rc]);return r.push(e),t.onlineResources=r,{...C}}function VR({tournamentRecord:t,promotionalName:e,tournamentName:r,formalName:n}){if(!t)return{error:$};let o=t.tournamentId,i={tournamentId:o};return r&&r!==t.tournamentName&&(t.tournamentName=r,i.tournamentName=r),e&&e!==t.promotionalName&&(t.promotionalName=e,i.promotionalName=e),n&&n!==t.formalName&&(t.formalName=n,i.formalName=n),t.promotionalName===t.tournamentName&&(delete t.promotionalName,i.promotionalName=""),t.formalName===t.tournamentName&&(delete t.formalName,i.formalName=""),Object.keys(i).length>1&&lt({topic:Wi,payload:{parentOrganisation:t.parentOrganisation,tournamentId:o,...i}}),{...C}}function BR({tournamentRecord:t,notes:e}){if(!t)return{error:$};let r=e?Vp({element:t,notes:e}):Og({element:t});return r.error?r:(lt({topic:Wi,payload:{parentOrganisation:t.parentOrganisation,tournamentId:t.tournamentId,notes:e??""}}),{...C})}function HR({tournamentRecord:t,categories:e}){return t?(e=(e||[]).filter(r=>r.categoryName&&r.type),t.tournamentCategories=e,lt({topic:Wi,payload:{parentOrganisation:t.parentOrganisation,tournamentId:t.tournamentId,categories:e}}),{...C}):{error:$}}function Uw({tournamentRecord:t}){if(!t)return{error:$};let{startDate:e,endDate:r}=t,n=Ls(e,r),o=[];for(let i of t.venues||[])i?.courts?.length&&o.push(...i.courts);for(let i of o){let{startTime:s,endTime:a}=(i.dateAvailability??[]).reduce((p,m)=>{let d=Yt(p.startTime),l=Yt(p.endTime);return m.startTime&&Yt(m.startTime)<d&&(p.startTime=m.startTime),m.endTime&&Yt(m.endTime)>l&&(p.endTime=m.endTime),p},{startTime:"08:00",endTime:"18:00"}),c=n.map(p=>i.dateAvailability?.find(d=>d.date===p)??{date:p,startTime:s,endTime:a}),u=i.dateAvailability?.find(p=>!p.date);u&&c.unshift(u),i.dateAvailability=c}return{...C}}function PI(t){let{tournamentRecord:e,startDate:r,endDate:n,weekdays:o}=t,i=t.activeDates?.filter(Boolean),s=et(t,[{tournamentRecord:!0},{[er]:l=>No.test(l),[Fr]:je,startDate:!1,endDate:!1},{[er]:l=>l.filter(Boolean).every(f=>No.test(f)),[Fr]:je,activeDates:!1},{[er]:by,weekdays:!1}]);if(s.error)return s;if(n&&r&&new Date(n)<new Date(r))return{error:V};if(n&&r&&new Date(r)>new Date(n))return{error:V};if(i?.length){let l=r||e.startDate,f=n||e.endDate,g=!l||i.every(h=>new Date(h)>=new Date(l)),I=!f||i.every(h=>new Date(h)<=new Date(f));if(!g||!I)return{error:je}}let a;(r&&e.startDate&&new Date(r)>new Date(e.startDate)||n&&e.endDate&&new Date(n)<new Date(e.endDate))&&(a=!0);let c=Ls(e.startDate,e.endDate);r&&(e.startDate=r),n&&(e.endDate=n);let u=Ls(e.startDate,e.endDate),p=c.filter(l=>!u.includes(l)),m=u.filter(l=>!c.includes(l));for(let l of e.events??[])r&&l.startDate&&new Date(l.startDate)<new Date(r)&&(l.startDate=r),n&&l.startDate&&new Date(l.startDate)>new Date(n)&&(l.startDate=r??n),n&&l.endDate&&new Date(l.endDate)>new Date(n)&&(l.endDate=n),r&&l.endDate&&new Date(l.endDate)<new Date(r)&&(l.endDate=n??r);r&&e.endDate&&new Date(r)>new Date(e.endDate)&&(e.endDate=r),n&&e.startDate&&new Date(n)<new Date(e.startDate)&&(e.startDate=n),i&&(e.activeDates=i),o&&(e.weekdays=o);let d=a&&T0({tournamentRecord:e})?.unscheduledMatchUpIds;return Uw({tournamentRecord:e}),lt({payload:nt({parentOrganisation:e.parentOrganisation,tournamentId:e.tournamentId,activeDates:i,startDate:r,weekdays:o,endDate:n}),topic:Wi}),{...C,unscheduledMatchUpIds:d,datesAdded:m,datesRemoved:p}}function WR({tournamentRecord:t,startDate:e}){return e?PI({tournamentRecord:t,startDate:e}):{error:je}}function jR({tournamentRecord:t,endDate:e}){return e?PI({tournamentRecord:t,endDate:e}):{error:je}}function T0({tournamentRecord:t}){let e=ye({tournamentRecord:t}).matchUps??[],r=t.startDate&&new Date(t.startDate),n=t.endDate&&new Date(t.endDate),o=[],i=[];for(let s of e){let{schedule:a,matchUpId:c}=s;if(a&&a.scheduledDate){let u=new Date(a.scheduledDate);(r&&u<r||n&&u>n)&&(i.push(c),o.includes(a.scheduledDate)||o.push(a.scheduledDate))}}return o.length&&!pm({scheduledDates:o,tournamentRecord:t}).clearedScheduleCount?{error:wA}:{unscheduledMatchUpIds:i}}var rC={};Jt(rC,{addCourt:()=>Nl,addCourts:()=>SI,addVenue:()=>lc,deleteCourt:()=>ZR,deleteVenue:()=>AA,deleteVenues:()=>KR,disableCourts:()=>zR,disableVenues:()=>QR,enableCourts:()=>XR,enableVenues:()=>JR,generate:()=>$R,generateCourts:()=>oI,getCompetitionVenues:()=>Qp,getCourts:()=>yy,getVenuesAndCourts:()=>Uo,modifyCourt:()=>NI,modifyCourtAvailability:()=>DI,modifyVenue:()=>tC,mutate:()=>eC,publicFindVenue:()=>hS,query:()=>CN});var $R={};Jt($R,{generateCourts:()=>oI});var eC={};Jt(eC,{addCourt:()=>Nl,addCourts:()=>SI,addVenue:()=>lc,deleteCourt:()=>ZR,deleteVenue:()=>AA,deleteVenues:()=>KR,disableCourts:()=>zR,disableVenues:()=>QR,enableCourts:()=>XR,enableVenues:()=>JR,modifyCourt:()=>NI,modifyCourtAvailability:()=>DI,modifyVenue:()=>tC});function _l(t){if(!t?.tournamentRecord&&!Array.isArray(t?.venueMatchUps))return{error:$};if(!t?.courtId)return{error:wi};let{scheduleVisibilityFilters:e,tournamentRecord:r,matchUpFilters:n,venueMatchUps:o,courtId:i}=t,{schedulingProfile:s}=Xo({tournamentRecord:r});if(Array.isArray(o))return{matchUps:u({matchUps:o,courtId:i})};let{matchUps:a}=ye({scheduleVisibilityFilters:e,tournamentRecord:r,matchUpFilters:n});return{matchUps:u({matchUps:a,courtId:i})};function u({matchUps:p,courtId:m}){let d=p.filter(l=>{let f=l.schedule?.allocatedCourts?.map(({courtId:g})=>g);return l.schedule?.courtId===m||f?.includes(m)});return ul({matchUps:d,schedulingProfile:s})}}function Pw({scheduleVisibilityFilters:t,tournamentRecord:e,matchUpFilters:r,venueId:n}){if(!e)return{error:$};if(!n)return{error:ti};let{schedulingProfile:o}=Xo({tournamentRecord:e}),{matchUps:i}=ye({scheduleVisibilityFilters:t,tournamentRecord:e,matchUpFilters:r});return{matchUps:a({matchUps:i,venueId:n})};function a({matchUps:c,venueId:u}){let p=c.filter(m=>{let d=m.schedule?.allocatedCourts?.map(({venueId:l})=>l);return m.schedule?.venueId===u||d?.includes(u)});return ul({matchUps:p,schedulingProfile:o})}}function DI({tournamentRecord:t,dateAvailability:e,disableNotice:r,venueMatchUps:n,courtId:o,force:i}){if(!t)return{error:$};if(!o)return{error:wi};let s=lA({dateAvailability:e});if(s.error)return s;let{updatedDateAvailability:a,totalMergeCount:c}=y0(e);e=a;let u=ms({tournamentRecord:t,courtId:o});if(u.error)return u;let{court:p,venue:m}=u,{matchUps:d}=_l({tournamentRecord:t,venueMatchUps:n,courtId:o});if(d?.length){let l=Tt({tournamentRecord:t})?.appliedPolicies,f=i??l?.[Mo]?.allowDeletionWithScoresPresent?.courts,g=[];g.length&&(f||console.log("throw error: scheduled court matchUps",g.length))}return p&&(p.dateAvailability=e,!r&&m&&lt({payload:{venue:m,tournamentId:t.tournamentId},topic:Ei,key:m.venueId})),{...C,totalMergeCount:c}}function y0(t){let e=0,r=t.reduce((o,i)=>{let{date:s,startTime:a,endTime:c,bookings:u}=i;return o[s]||(o[s]=[]),o[s].push({startTime:a,endTime:c,bookings:u}),o},{}),n=[];return Object.keys(r).forEach(o=>{r[o].sort(uw);let{mergedAvailability:i,mergeCount:s}=A0(r[o]);n.push(...i.map(a=>({date:o,...a}))),e+=s}),{updatedDateAvailability:n,totalMergeCount:e}}function A0(t){let e,r,n,o=t.length,i=0,s=[];for(;t.length&&o;){let c=t.shift(),{startTime:u,endTime:p,bookings:m}=c;if(o-=1,!e)e=u,n=m,r=p;else if(la(Ge(r),Ge(u),!1)>0){let l={startTime:e,endTime:r};n?.length&&(l.bookings=n),s.push(l),e=u,n=m,r=p}else m&&(n?n.push(m):n=m),r=p,i+=1}let a={startTime:e,endTime:r};return n?.length&&(a.bookings=n),s.push(a),{mergedAvailability:s,mergeCount:i}}function xl({matchUpsCount:t=0}){let r=`Schedule would be deleted from ${t} ${t===1?"matchUp":"matchUps"}; use { force: true }`;return{error:kE,info:r}}function yA({tournamentRecord:t,drawDefinition:e,matchUpId:r,drawId:n}){let o="removeCourtAssignment";if(!r)return{error:cr};if(!e&&!n)return{error:sn};let i;if(!e){if(!t)return{error:$};({drawDefinition:e}=ze({tournamentRecord:t,drawId:n}))}if(e)({matchUp:i}=Bt({drawDefinition:e,matchUpId:r}));else{if(!t)return{error:$};let s=ye({tournamentRecord:t,inContext:!1}).matchUps??[];({matchUp:i}=tT({matchUps:s,matchUpId:r}))}return i?(i.timeItems&&i.timeItems.find(a=>[jo,po].includes(a.itemType))&&(i.timeItems=i.timeItems.filter(({itemType:a})=>![jo,po].includes(a)),gt({tournamentId:t?.tournamentId,context:o,drawDefinition:e,matchUp:i})),{...C}):{error:Le}}function AA(t){if(typeof t?.venueId!="string")return{error:ti};let{tournamentRecord:e,venueId:r,force:n}=t,o=t.tournamentRecords||e&&{[e.tournamentId]:e}||{};if(!Object.keys(o).length)return{error:$};let s=Un({tournamentRecords:o,contextFilters:{venueIds:[r]}}).matchUps??[],a=Tt({tournamentRecord:e})?.appliedPolicies,c=n??a?.[Mo]?.allowDeletionWithScoresPresent?.venues;if(!s.length||c)for(let u of Object.values(o)){for(let m of s){let d=yA({matchUpId:m.matchUpId,drawId:m.drawId,tournamentRecord:u});if(d.error)return d}let p;u.venues=(u.venues??[]).filter(m=>m?.venueId!==r?!0:(p=!0,!1)),p&&lt({payload:{venueId:r,tournamentId:u.tournamentId},topic:Bf,key:r})}else return xl({matchUpsCount:s.length});return bc({tournamentRecords:o}),{...C}}function KR({tournamentRecord:t,venueIds:e,force:r}){if(!t)return{error:$};if(!Array.isArray(e))return{error:V};for(let n of t.venues||[]){let{venueId:o}=n;if(e.includes(o)){let{venueId:i}=n,s=AA({tournamentRecord:t,venueId:i,force:r});if(s.error)return s}}return{...C}}function zR(t){let{courtIds:e,dates:r}=t,n=Mr(t),o=[{[Re]:!0,[gp]:!0}],i=et(t,o);if(i.error)return i;for(let s of Object.values(n))E0({tournamentRecord:s,courtIds:e,dates:r});return{...C}}function E0({tournamentRecord:t,courtIds:e,dates:r}){let n=Array.isArray(r)&&r.length?{dates:r}:!0,o=i=>Ut({extension:{value:n,name:ao},creationTime:!1,element:i});for(let i of t.venues||[])for(let s of i.courts||[])if(e?.includes(s.courtId)){let a=o(s);if(a.error)return a}return{...C}}function QR(t){let{tournamentRecords:e,tournamentId:r,venueIds:n}=t,o=[{[Re]:!0,[Ip]:!0}],i=et(t,o);if(i.error)return i;let s=Object.keys(e).filter(a=>!r||a===r);for(let a of s){let c=e[a];U0({tournamentRecord:c,venueIds:n})}return{...C}}function U0({tournamentRecord:t,venueIds:e}){for(let r of t.venues||[])if(e?.includes(r.venueId)){let n=Ut({creationTime:!1,element:r,extension:{name:ao,value:!0}});if(n.error)return n}return{...C}}function XR(t){let e=Mr(t),r=[{[Re]:!0}];!t.enableAll&&r.push({[gp]:!0});let n=et(t,r);if(n.error)return n;let{enableAll:o,courtIds:i,dates:s}=t;for(let a of Object.values(e))P0({tournamentRecord:a,courtIds:i,enableAll:o,dates:s});return{...C}}function P0({tournamentRecord:t,courtIds:e,enableAll:r,dates:n}){for(let o of t.venues||[])for(let i of o.courts||[])if(r||e?.includes(i.courtId))if(Array.isArray(n)){let{extension:s}=mt({element:i,name:ao});if(s){let a=s.value;Array.isArray(a.dates)&&(a.dates=a.dates.filter(c=>!n.includes(c))),Ut({extension:{name:ao,value:a},creationTime:!1,element:i})}}else gr({element:i,name:ao});return{...C}}function JR(t){let e=Mr(t),r=[{[Re]:!0}];!t.enableAll&&r.push({[Ip]:!0});let n=et(t,r);if(n.error)return n;let{venueIds:o,enableAll:i}=t;for(let s of Object.values(e))for(let a of s.venues||[])(i||o?.includes(a.venueId))&&gr({element:a,name:ao});return{...C}}function ZR(t){let{courtId:e,disableNotice:r,force:n}=t,o=Mr(t),i=et(t,[{[Re]:!0,[Oh]:!0}]);if(i.error)return i;let s,a;for(let c of Object.values(o)){if(a=D0({tournamentRecord:c,disableNotice:r,courtId:e,force:n}),a.error&&a.error!==_s)return a;a.success&&(s=!0)}return s?{...C}:a}function D0({tournamentRecord:t,disableNotice:e,courtId:r,force:n}){let o=ms({tournamentRecord:t,courtId:r});if(o.error)return o;let i=o.venue,{matchUps:s}=_l({tournamentRecord:t,courtId:r}),a=Tt({tournamentRecord:t})?.appliedPolicies,c=n??a?.[Mo]?.allowDeletionWithScoresPresent?.courts;if(!s?.length||c){for(let u of s??[]){let p=yA({matchUpId:u.matchUpId,drawId:u.drawId,tournamentRecord:t});if(p.error)return p}i&&(i.courts=(i.courts??[]).filter(u=>u.courtId!==r),e||lt({payload:{venue:i,tournamentId:t.tournamentId},topic:Ei,key:i.venueId}))}else return xl({matchUpsCount:s.length});return{...C}}function NI(t){let{disableNotice:e,modifications:r,courtId:n,force:o,venueMatchUps:i}=t,s=Mr(t);if(!Object.keys(s).length)return{error:Lt};let a,c;for(let u of Object.values(s)){let p=N0({tournamentRecord:u,disableNotice:e,venueMatchUps:i,modifications:r,courtId:n,force:o});if(p?.error)return p;a=!0}return a?{...C}:c}function N0({tournamentRecord:t,disableNotice:e,venueMatchUps:r,modifications:n,courtId:o,force:i}){if(!t)return{error:$};if(!o)return{error:wi};if(!n||typeof n!="object")return{error:Io};let s=ms({tournamentRecord:t,courtId:o});if(s.error)return s;let{venue:a,court:c}=s,u=Object.keys(cw()).filter(l=>l!=="courtId");if(!Object.keys(n).filter(l=>u.includes(l)).length)return{error:rp};let m=u.filter(l=>!["dateAvailability"].includes(l)),d=Object.keys(n).filter(l=>m.includes(l));if(c&&d.forEach(l=>Object.assign(c,{[l]:n[l]})),n.dateAvailability){let l=DI({dateAvailability:n.dateAvailability,tournamentRecord:t,venueMatchUps:r,disableNotice:e,courtId:o,force:i});if(l.error)return l}return e||lt({payload:{venue:a,tournamentId:t.tournamentId},topic:Ei,key:a?.venueId}),{...C,court:J(c)}}var M0=()=>({venueId:void 0,venueName:"",venueAbbreviation:"",onlineResources:[],venueType:void 0,addresses:[],contacts:[],courts:[],roles:[]}),Dw=M0;function tC(t){let{modifications:e,venueId:r,force:n}=t,o=Mr(t);if(!Object.keys(o).length)return{error:Lt};if(typeof r!="string")return{error:ti};let i,s;for(let a of Object.values(o)){let c=R0({tournamentRecord:a,modifications:e,venueId:r,force:n});if(c.success&&(s=!0),c.error&&(i=c.error),c.error&&c.error!==ki)return c}return bc({tournamentRecords:o}),s?{...C}:{error:i}}function R0({tournamentRecord:t,modifications:e,venueId:r,force:n}){if(!t)return{error:$};if(!e||typeof e!="object")return{error:Io};if(!r)return{error:ti};let o=Tt({tournamentRecord:t})?.appliedPolicies,i=n??o?.[Mo]?.allowDeletionWithScoresPresent?.venues,{matchUps:s}=Pw({tournamentRecord:t,venueId:r}),a=qo({tournamentRecord:t,venueId:r});if(a.error)return a;let c=a.venue,u=Object.keys(Dw()).filter(h=>h!=="venueId");if(!Object.keys(e).filter(h=>u.includes(h)).length)return{error:rp};let m=u.filter(h=>!["courts","onlineResources"].includes(h)),d=Object.keys(e).filter(h=>m.includes(h));c&&d.forEach(h=>Object.assign(c,{[h]:e[h]}));let l=c?.courts?.map(h=>h.courtId)??[],f=e.courts?.map(h=>h.courtId)||[],g=f.length?l.filter(h=>!f.includes(h)):e?.courts&&l,I=[];if(g?.length){let S=c?.courts?.filter(T=>g.includes(T.courtId))?.map(T=>{let y=_l({courtId:T.courtId,tournamentRecord:t,venueMatchUps:s});for(let E of y.matchUps??[])I.push({matchUpId:E.matchUpId,drawId:E.drawId});return y.matchUps?.length??0}).reduce((T,y)=>T+y);if(c&&(!S||i))c.courts=c.courts?.filter(T=>f.includes(T.courtId)),ju({schedule:{courtId:"",scheduledDate:""},matchUpDetails:I,removePriorValues:!0,tournamentRecord:t});else return xl({matchUpsCount:S})}if(e.courts)for(let h of e.courts){let{courtId:S}=h||{},T=NI({modifications:h,disableNotice:!0,tournamentRecord:t,venueMatchUps:s,courtId:S,force:n});if(T.error===_s&&(T=Nl({disableNotice:!0,tournamentRecord:t,venueId:r,court:h})),T.error)return T}return bc({tournamentRecord:t}),c&&lt({payload:{venue:c,tournamentId:t.tournamentId},topic:Ei,key:c?.venueId}),{...C,venue:J(c)}}var nC={};Jt(nC,{JSON2CSV:()=>vw,UUID:()=>Mt,UUIDS:()=>ih,allNumeric:()=>bI,attributeFilter:()=>Hi,chunkArray:()=>Ee,chunkByNth:()=>Fl,chunkSizeProfile:()=>bA,constantToString:()=>Qe,countValues:()=>gC,createMap:()=>_I,dateTime:()=>oh,definedAttributes:()=>nt,dehydrateMatchUps:()=>bw,extractAttributes:()=>eP,flattenJSON:()=>UA,generateDateRange:()=>Ls,generateHashCode:()=>EC,generateRange:()=>tt,generateTimeCode:()=>fA,groupValues:()=>RA,hasAttributeValues:()=>AC,instanceCount:()=>yr,intersection:()=>jt,isConvertableInteger:()=>It,isNumeric:()=>Zt,isOdd:()=>RI,isPowerOf2:()=>_n,makeDeepCopy:()=>J,matchUpScheduleSort:()=>Cw,matchUpSort:()=>Ri,nearestPowerOf2:()=>Am,nextPowerOf2:()=>rs,noNulls:()=>fC,noNumeric:()=>vI,numericSort:()=>le,occurrences:()=>IC,overlap:()=>ke,randomMember:()=>yn,randomPop:()=>Zr,shuffleArray:()=>Sr,structureSort:()=>yi,subSort:()=>hC,undefinedToNull:()=>OI,unique:()=>pt,visualizeScheduledMatchUps:()=>Nw});function Nw({scheduledMatchUps:t,showGlobalLog:e}){av();let r=t?.reduce((o,{structureId:i})=>o.includes(i)?o:o.concat(i),[]),n=Array.isArray(r)&&{...r.map(o=>{let{structureName:i,matchUpType:s}=t.find(a=>a.structureId===o);return{[o]:`${i} ${s}`}})};r?.forEach(o=>{Cn({color:"blue",method:"draw",structure:n[o],keyColors:{structure:"magenta"}},!0);let i=t.filter(a=>a.structureId===o),s=Ke({matchUps:i})?.roundMatchUps||[];Object.keys(s).forEach(a=>{Cn({roundNumber:a,keyColors:{roundNumber:"brightcyan"}},!0),s[a].forEach(({matchUpId:c,schedule:u})=>{let p=Qt(u.scheduledTime);Cn({matchUpId:c,time:p,date:u.scheduledDate,venue:u.venueId,keyColors:{time:"brightcyan",date:"brightcyan",matchUpId:"yellow",venue:"magenta"}},!0)})})}),e&&sv()}var{extractTime:Mw,timeStringMinutes:Rw}=oh;function Cw(t,e){let r=t.schedule??{},n=e.schedule??{};if(r.scheduledDate&&!n.scheduledDate)return 1;if(n.scheduledDate&&!r.scheduledDate)return-1;if(r.scheduledDate&&n.scheduledDate){if(r.scheduledDate===n.scheduledDate){if(r.scheduledTime&&!n.scheduledTime)return 1;if(n.scheduledTime&&!r.scheduledTime)return-1;if(r.scheduledTime&&n.scheduledTime){let o=Rw(Mw(r.scheduledTime)),i=Rw(Mw(n.scheduledTime));return o-i}}return new Date(r.scheduledDate).getTime()-new Date(n.scheduledDate).getTime()}return 0}function bw({tournamentRecord:t}){if(!t)return{error:$};if(typeof t!="object"||!t.tournamentId)return{error:V};let{matchUps:e}=ye({tournamentRecord:t,inContext:!1});if(e?.length){let r=C0({tournamentRecord:t});v0(e,r)}return{...C}}function C0({tournamentRecord:t}){let e={};for(let r of t.events||[]){r.matchUpFormat&&(e[r.eventId]=r.matchUpFormat);for(let n of r.drawDefinitions||[]){n.matchUpFormat&&(e[n.drawId]=n.matchUpFormat);for(let o of n.structures||[]){o.matchUpFormat&&(e[o.structureId]=o.matchUpFormat);for(let i of o.structures||[])i.matchUpFormat&&(e[i.structureId]=i.matchUpFormat)}}}return e}var b0=["collectionId","collectionPosition","drawPositions","extensions","finishingPositionRange","finishingRound","isMock","matchUpId","matchUpStatus","matchUpStatusCodes","orderOfFinish","processCodes","roundNumber","tieFormat","tieMatchUps","roundPosition","score","sides","winnerMatchUpId","loserMatchUpId","matchUpDuration","winningSide"];function v0(t,e={}){for(let r of t){let{structureId:n,drawId:o,eventId:i}=r,s=e[n]||e[o]||e[i],a=r.matchUpFormat===s?void 0:r.matchUpFormat;for(let c of Object.keys(r))b0.includes(c)||delete r[c];r.sides&&r.drawPositions&&!r.tieMatchUps&&delete r.sides,a&&(r.matchUpFormat=a)}}function vw(t,e){if(e&&typeof e!="object")return{error:V};let{columnTransform:r={}}=e||{},{includeTransformAccessors:n,includeHeaderRow:o=!0,returnTransformedJSON:i,removeEmptyColumns:s,onlyHeaderRow:a,columnAccessors:c=[],functionMap:u={},columnMap:p={},valuesMap:m={},context:d={},delimiter:l='"',columnJoiner:f=",",rowJoiner:g=`\r
27
27
  `,keyJoiner:I="."}=e||{};if(!Array.isArray(t)||!Array.isArray(c)||typeof d!="object"||typeof p!="object"||typeof r!="object"||typeof u!="object"||typeof m!="object"||typeof f!="string"||typeof g!="string"||typeof I!="string"||typeof l!="string")return{error:V};r=Object.assign({},...Object.keys(r).reverse().map(v=>({[v]:Array.isArray(r[v])?r[v]:[typeof r[v]=="string"&&r[v]].filter(Boolean)})));let h=t.filter(Boolean).map(v=>UA(v,I)),S=Object.values(r).flat();n&&c.push(...S);let T=h.reduce((v,O)=>Object.keys(O).every(x=>!v.includes(x)&&v.push(x)||!0)&&v,[]).filter(v=>!c?.length||c.includes(v)),y=Object.assign({},...Object.keys(r).reverse().map(v=>r[v].map(O=>({[O]:v})).flat()).flat()),E=(v,O)=>e?.sortOrder?e.sortOrder.includes(v)&&e.sortOrder.includes(O)&&e.sortOrder.indexOf(v)-e.sortOrder.indexOf(O)||!e.sortOrder.includes(O)&&-1:0,P=T.reduce((v,O)=>{let x=y[O];return x?v.includes(x)||v.push(x):v.push(O),v},[]).sort(E);Object.keys(p).forEach(v=>!P.includes(v)&&P.unshift(v)),Object.keys(r).forEach(v=>!P.includes(v)&&P.unshift(v)),typeof d=="object"&&Object.keys(d).forEach(v=>!P.includes(v)&&P.unshift(v));let A=P.map(v=>p[v]||v);if(a)return[A];let U=v=>`${l}${v}${l}`,N=[],D=v=>Object.values(P.reduce((O,x,F)=>{let w=r[x],L=(w?.length?v[w.find(H=>v[H])]:v[x])||d?.[x]||"",G=m[x]?.[L]||L,k=Wr(u[x])?u[x](G):G;return O[x]=U(k),k&&(N[F]=(N[F]||0)+1),O},{})),M=h.map(D),R=s&&[...N].map((v,O)=>!v&&O).filter(Zt).reverse();if(R){let v=O=>O.filter((x,F)=>!R.includes(F));M=M.map(v),A=v(A)}let b=M.map(v=>v.join(f));return i?b.map(v=>{let O=v.split(f);return Object.assign({},...O.map((x,F)=>({[A[F]]:x})))}):o?[A.map(U).join(f),...b].join(g):b.join(g)}function UA(t,e=".",r=[]){return typeof t=="object"&&Object.keys(t).reduce((n,o)=>typeof t[o]!="object"?(n[r.concat(o).join(e)]=t[o],n):Object.assign(n,UA(t[o],e,r.concat(o))),{})}var O0={};var{FACTORY:Ow}=Gh;function _w({tournamentRecord:t,value:e}){let{extension:r}=mt({element:t,name:Ow}),n={name:Ow,value:{...r?.value,...e}};Ut({element:t,extension:n})}function qu({timeStamp:t}){let e=Go(),r=lf();return r&&Object.values(e).forEach(n=>{_w({tournamentRecord:n,value:{version:Ba(),timeStamp:t}})}),r}function PA({engineType:t,methodName:e,elapsed:r,params:n,result:o}){let i=Pr();if(typeof i!="object")return;let s={method:e},a=o?.error&&(i.errors===!0||Array.isArray(i.errors)&&i.errors.includes(e)),c=Array.isArray(i.params)&&i.params?.includes(e),u=i.params&&!Array.isArray(i.params)||c,p=Array.isArray(i.exclude)&&i.exclude.includes(e);!p&&![void 0,!1].includes(i.perf)&&!isNaN(i.perf)&&r>=i.perf&&(s.elapsed=r),!p&&(a||u)&&(s.params=n),!p&&(a||i.result&&!Array.isArray(i.result)&&(!Array.isArray(i.params)||c)||Array.isArray(i.result)&&i.result?.includes(e))&&(s.result=o),Object.keys(s).length>1&&jE(s,t)}function Ga({methodName:t,params:e,start:r}){let n={error:Qa,methodName:t},o=r?Date.now()-r:0;return PA({result:n,methodName:t,elapsed:o,params:e,engineType:"sync"}),n}function xw(t,e){if(e._middleware===!1)return e;if(e.tournamentId&&!t[e.tournamentId])return{error:$};let r=e.drawId||e.matchUp?.drawId;if(r){let{event:i,drawDefinition:s,tournamentId:a}=ze({tournamentRecords:t,drawId:r});s&&(e.drawDefinition=s),a&&(e.tournamentId=a),i&&(e.event=i)}if(e.eventId&&!e.event){let{event:i,tournamentId:s}=ze({eventId:e.eventId,tournamentRecords:t});if(!i)return{error:jr};e.tournamentId=s,e.event=i}let n=e.tournamentId??os();if(!n&&e)return e;let o=t[n];return n&&!o?{error:$}:(o&&(e.tournamentRecord=o),e)}function Va(t,e,r,n,o){delete t.success,delete t.error;let i=Date.now(),s=os();r&&(r.activeTournamentId=s);let a=r?.tournamentRecord||gf(s),c=typeof r?.tournamentRecord=="object"&&{[r?.tournamentRecord.tournamentId]:r.tournamentRecord}||Go(),u=r?J(r,void 0,!0):void 0,p=r?xw(c,r):void 0;if(p?.error)return p;let m=_0({params:p,tournamentRecords:c,tournamentRecord:a,methodName:n,method:e}),d=Date.now()-i;return PA({result:m,methodName:n,elapsed:d,params:u,engineType:o}),m}function _0({tournamentRecords:t,tournamentRecord:e,params:r,methodName:n,method:o}){if(Pr())return o({tournamentRecords:t,tournamentRecord:e,...r});try{return o({tournamentRecords:t,tournamentRecord:e,...r})}catch(i){return ap({engineName:"engine",methodName:n,params:r,err:i})}}function $u(t){let{mutationStatus:e,tournamentId:r,directives:n,timeStamp:o}=t||{},{topics:i}=Lr();for(let s of[...i].sort(Lw)){let a=zI({topic:s});a?.length&&Mm({topic:s,notices:a})}e&&o&&i.includes(Jm)&&Mm({notices:[{tournamentId:r,directives:n,timeStamp:o}],topic:Jm})}async function DA(t){let{mutationStatus:e,tournamentId:r,directives:n,timeStamp:o}=t||{},{topics:i}=Lr();for(let s of[...i].sort(Lw)){let a=zI({topic:s});a&&await Mm({topic:s,notices:a})}e&&o&&i.includes(Jm)&&Mm({notices:[{tournamentId:r,directives:n,timeStamp:o}],topic:Jm})}var ww={[zf]:5,[Kf]:5,[Qf]:5,[$f]:5,[qf]:5,[jf]:5,[wU]:5,[LU]:5,[Yf]:1,[Ap]:1,[or]:5,[Ei]:5,[Wf]:4,[Vf]:4,[Bf]:4,[Hf]:4,[yp]:3,[kf]:2};function Lw(t,e){return(ww[e]||0)-(ww[t]||0)}function Fw({convertExtensions:t,removeExtensions:e}){let r=Go();return{tournamentId:os(),tournamentRecords:J(r,t,!1,e)}}function kw(t){let{convertExtensions:e=!1,removeExtensions:r=!1}=t??{},n=t?.tournamentId??os();if(typeof n!="string")return{};let o=gf(n);return{tournamentRecord:J(o,e,!1,r)}}function Gw(){let t=Go(),{extension:e}=mt({name:Hs,tournamentRecords:t,discover:!0}),r=e?.value?.tournamentIds||[];return Object.keys(t).forEach(n=>{r.includes(n)||delete t[n]}),Rm(t)}function oC(t,e=!0){return typeof t!="object"||Array.isArray(t)?{error:Io}:t?.tournamentId?HE(e?J(t):t):{error:V}}function ts(t,e=!0){if(typeof t!="object")return{error:Io};if(sp(),Array.isArray(t)){if(!(t.filter(n=>n?.tournamentId).length===t.length))return{error:LI};t=Object.assign({},...t.map(n=>({[n.tournamentId]:n})))}else if(t?.tournamentId)t={[t.tournamentId]:t},sp(t.tournamentId);else if(!Object.keys(t).every(n=>t[n].tournamentId===n))return{error:LI};return Rm(e?J(t):t)}async function Vw(t,e,r){if(!Array.isArray(e))return{error:V,message:"directives must be an array"};let n=ff(),o=Date.now(),i=r&&J(Go(),!1,!0),s=[];for(let p of e){if(typeof p!="object")return{error:V,message:"directive must be an object"};let{method:m,pipe:d}=p,l=p.params?{...p.params}:{};if(!n[m])return Ga({methodName:m,start:o,params:l});if(d){let g=s[s.length-1],I=Object.keys(d);for(let h of I)g[h]&&(l[h]=g[h])}let f=Va(t,n[m],l,m,"async");if(f?.error)return i&&ts(i),{...f,rolledBack:!!i};s.push({...f,methodName:m})}let a=Date.now(),c=qu({timeStamp:a});return await DA({directives:e,mutationStatus:c,timeStamp:a}),Gi(),{success:s.every(p=>p.success),results:s}}async function iC(t,e){if(!ht(e))return{error:V,message:"args must be an object"};let r=Object.values(e).filter(Wr).length;if(r>1)return{message:"there must be only one arg with typeof function",error:V};let n=r?Object.keys(e).find(l=>Wr(e[l])):Vt(e.method)&&e.method;if(!n)return{error:Qa};let{[n]:o,...i}=e,s=e?.params?{...e.params}:{...i},a=s.rollbackOnError&&J(Go(),!1,!0),c=o||t[n]||op()[n];if(!c)return Ga({methodName:n,params:s});let u=await Va(t,c,s,n,"async")??{};u?.error&&a&&ts(a);let p=Date.now(),m=qu({timeStamp:p}),d=u?.success&&s?.delayNotify!==!0&&s?.doNotNotify!==!0;return d&&await DA({directives:[{method:c,params:s}],mutationStatus:m,timeStamp:p}),(d||!u?.success||s?.doNotNotify)&&Gi(),u}function Bw(t,e,r,n,o,i){let s=YE(r,n,o,i);if(s.error)return s;let a=s.methods??[];return Object.keys(a).filter(u=>Wr(a[u])).forEach(u=>{t[u]=p=>{let m=()=>e(t,{[u]:a[u],...p});if(Pr())return m();try{return m()}catch(d){ap({engineName:"engine",methodName:u,params:p,err:d})}}}),{...C,...t}}function hm(t,e){return e?.error?(t.error=e.error,t.success=!1):(t.error=void 0,t.success=!0),t}function wl(t,e){t.importMethods=(r,n,o,i)=>Bw(t,e,r,n,o,i),t.getTournament=r=>kw(r),t.getState=r=>Fw({convertExtensions:r?.convertExtensions,removeExtensions:r?.removeExtensions}),t.version=()=>Ba(),t.reset=()=>(Rm({}),hm(t)),t.devContext=r=>(Wc(r),hm(t)),t.getDevContext=r=>Pr(r),t.newTournamentRecord=(r={})=>{let n=dm(r),o=n.tournamentId;return n.error?n:(oC(n),sp(o),{...C,tournamentId:o})},t.setState=(r,n,o)=>{jc(n,o);let i=ts(r,n);return hm(t,i)},t.setTournamentId=r=>sp(r),t.getTournamentId=()=>os(),t.setTournamentRecord=(r,n,o)=>{jc(n,o);let i=oC(r,n);return hm(t,i)},t.removeTournamentRecord=r=>{let n=WE(r);return hm(t,n)},t.removeUnlinkedTournamentRecords=()=>{let r=Gw();return hm(t,r)}}function x0(t){let e=VE();if(e.error&&!t)return e;let r={executionQueue:(n,o)=>Vw(r,n,o),execute:n=>iC(r,n)};return wl(r,iC),r}function Hw(t,e,r){if(!Array.isArray(e))return{error:V,message:"directives must be an array"};let n=ff(),o=Date.now(),i=r&&J(Go(),!1,!0),s=[];for(let p of e){if(typeof p!="object")return{error:V,message:"directive must be an object"};if(p.params&&typeof p.params!="object")return{error:V,message:"params must be an object"};let{method:m,pipe:d}=p,l=p.params?{...p.params}:{};if(!n[m])return Ga({methodName:m,start:o,params:l});if(d){let g=s[s.length-1],I=Object.keys(d);for(let h of I)g[h]&&(l[h]=g[h])}let f=Va(t,n[m],l,m,"sync");if(f?.error)return i&&ts(i),{...f,rolledBack:!!i};s.push({...f,methodName:m})}let a=Date.now(),c=qu({timeStamp:a});return $u({directives:e,mutationStatus:c,timeStamp:a}),Gi(),{success:s.every(p=>p.success),results:s}}function sC(t,e){if(!ht(e))return{error:V,message:"args must be an object"};let r=Object.values(e).filter(Wr).length;if(r>1)return{message:"there must be only one arg with typeof function",error:V};let n=r?Object.keys(e).find(l=>Wr(e[l])):Vt(e.method)&&e.method;if(!n)return{error:Qa};let{[n]:o,...i}=e,s=e?.params?{...e.params}:{...i},a=s.rollbackOnError&&J(Go(),!1,!0),c=o||t[n]||op()[n];if(!c)return Ga({methodName:n,params:s});let u=Va(t,c,s,n,"sync")??{};u?.error&&a&&ts(a);let p=Date.now(),m=qu({timeStamp:p}),d=u?.success&&s?.delayNotify!==!0&&s?.doNotNotify!==!0;return d&&$u({directives:[{method:c,params:s}],mutationStatus:m,timeStamp:p}),(d||!u?.success||s?.doNotNotify)&&Gi(),u}var Ww=(()=>{let t={executionQueue:(e,r)=>Hw(t,e,r),execute:e=>sC(t,e)};return wl(t,sC),t})(),Sm=Ww;function aC(t,e){if(!ht(e))return{error:V,message:"args must be an object"};let r=Object.values(e).filter(Wr).length;if(r>1)return{message:"there must be only one arg with typeof function",error:V};let n=r?Object.keys(e).find(c=>Wr(e[c])):Vt(e.method)&&e.method;if(!n)return{error:Qa};let{[n]:o,...i}=e,s=e?.params?{...e.params}:{...i},a=o||t[n]||op()[n];return a?Va(t,a,s,n,"ask"):Ga({methodName:n,params:s})}var w0=(()=>{let t={execute:e=>aC(t,e)};return wl(t,aC),t})();var Tm={},Fc;function cC(t,e=!0){if(!t)return{error:st};if(typeof t!="object")return{error:Io};if(t.matchUpId)Fc=t.matchUpId,Tm[Fc]=e?J(t):t;else if(Array.isArray(t))for(let r of t.reverse())r.matchUpId&&(Tm[r.matchUpId]=e?J(r):r,Fc||(Fc=r.matchUpId));else for(let r of Object.values(t))r.matchUpId&&(Tm[r.matchUpId]=e?J(r):r,Fc||(Fc=r.matchUpId));return e?J(t):t}function jw(){return Tm[Fc]}function Yw(){return Object.values(Tm)}function qw(){Fc=void 0,Tm={}}function $w(t){return J(Tm[Fc],t?.convertExtensions,!1,t?.removeExtensions)}var L0=(()=>{let t={getState:r=>$w(r),version:()=>Ba(),reset:()=>(qw(),{...C}),drawId:void 0,error:void 0,success:!1,devContext:r=>(Wc(r),t),setState:(r,n,o)=>{jc(n,o);let i=cC(r);return e(i)}};function e(r){return r?.error?(t.error=r.error,t.success=!1):(t.error=void 0,t.success=!0,t.drawId=r.drawId),t}return F0(t,[$g]),t})();function F0(t,e){e.forEach(r=>{Object.keys(r).forEach(n=>{t[n]=o=>{if(Pr())return Kw(t,{params:o,governor:r,methodName:n});try{return Kw(t,{params:o,governor:r,methodName:n})}catch(i){ap({engineName:"matchUpEngine",methodName:n,params:o,err:i})}}})})}function Kw(t,{params:e,governor:r,methodName:n}){t.error=void 0,t.success=!1;let o=e?.matchUp||jw(),i=e?.matchUps||Yw(),s=e?.rollbackOnError&&J(o,!1,!0);e={...e,matchUpId:o?.matchUpId,matchUps:i,matchUp:o};let a=r[n](e);if(a?.error)return s&&cC(s),{...a,rolledBack:!!s};let c=a?.success&&e?.delayNotify!==!0&&e?.doNotNotify!==!0;return c&&$u(),(c||!a?.success||e?.doNotNotify)&&Gi(),a}var uC=!1,k0=(()=>{let t={version:()=>Ba(),setDeepCopy:(n,o)=>(jc(n,o),t),devContext:n=>(Wc(n),uC=!0,t)};return r([TI]),t;function e(n,o){let i=n({...o});return i?.error||$u(),Gi(),uC&&(Wc(!1),uC=!1),i}function r(n){n.forEach(o=>{Object.keys(o).forEach(i=>{t[i]=s=>{if(Pr()){let a=e(o[i],s);return!a?.error&&s?.setState&&a?.tournamentRecord&&ts(a.tournamentRecord),a}else try{let a=e(o[i],s);return!a?.error&&s?.setState&&a?.tournamentRecord&&ts(a.tournamentRecord),a}catch(a){let c;typeof a=="string"?c=a.toUpperCase():a instanceof Error&&(c=a.message),console.log("ERROR",{params:JSON.stringify(s),method:i,error:c})}}})})}})();Sm.importMethods(EA,!0,1);var G0=Sm,V0=Sm;var B0={getTournamentPoints:Zd},zw=B0;var H0={calculateNewRatings:RT,generateDynamicRatings:CT},Qw=H0;var W0={...zw,...Qw};Sm.importMethods(W0);var j0=Sm;var Xw={[ou]:{roundsToSeparate:void 0,policyName:"Nationality Code",policyAttributes:[{key:"person.nationalityCode"},{key:"individualParticipants.person.nationalityCode"}]}};var Jw={[zn]:{policyName:"positionActionsUnrestricted",enabledStructures:[],otherFlightEntries:!0,disableRoundRestrictions:!0,activePositionOverrides:[Qs,Fp]}};var Zw={[zn]:{policyName:"positionActionsNoMovement",enabledStructures:[{stages:[],stageSequences:[],enabledActions:[Qs,Mu,Xs],disabledActions:[]}]}};var tL={[zn]:{policyName:"positionActionsDisabled",enabledStructures:!1}};var eL={[Bs]:{policyName:"Participant Privacy Policy",participant:{contacts:!1,individualParticipants:{onlineResources:!1,participantName:!0,participantOtherName:!0,participantId:!0,participantRole:!0,participantStatus:!0,penalties:!1,rankings:!0,ratings:!0,representing:!0,participantRoleResponsibilities:!1,participantType:!0,person:{addresses:!1,biographicalInformation:!1,birthDate:!1,contacts:!1,nationalityCode:!0,nativeFamilyName:!1,nativeGivenName:!1,onlineResources:!1,otherNames:!0,parentOrganisationId:!1,passportFamilyName:!1,passportGivenName:!1,personId:!1,personOtherIds:!1,previousNames:!1,sex:!1,standardFamilyName:!0,standardGivenName:!0,status:!1,tennisId:!1,wheelchair:!0}},individualParticipantIds:!0,onlineResources:!1,participantName:!0,participantOtherName:!0,participantId:!0,participantRole:!0,participantStatus:!0,penalties:!1,rankings:!0,ratings:!0,representing:!0,participantRoleResponsibilities:!1,participantType:!0,person:{addresses:!1,biographicalInformation:!1,birthDate:!1,contacts:!1,nationalityCode:!0,nativeFamilyName:!1,nativeGivenName:!1,onlineResources:!1,otherNames:!0,parentOrganisationId:!1,passportFamilyName:!1,passportGivenName:!1,personId:!1,personOtherIds:!1,previousNames:!1,sex:!1,standardFamilyName:!0,standardGivenName:!0,status:!1,tennisId:!1,wheelchair:!0}}}};var rL={[tn]:{processCodes:{incompleteAssignmentsOnDefault:["RANKING.IGNORE"]},defaultMatchUpFormat:Dn,allowDeletionWithScoresPresent:{drawDefinitions:!1,structures:!1},requireParticipantsForScoring:!1,requireAllPositionsAssigned:void 0,allowChangePropagation:!1,stage:{[rt]:{stageSequence:{1:{requireAllPositionsAssigned:!0}}}},matchUpFormats:[],matchUpStatusCodes:{[vr]:[],[co]:[],[Rt]:[],[un]:[],[nr]:[],[bt]:[]}}};var pC="Personal circumstance",nL={[tn]:{requireAllPositionsAssigned:!1,stage:{[rt]:{stageSequence:{1:{requireAllPositionsAssigned:!0}}}},defaultMatchUpFormat:Dn,matchUpFormats:[{description:"Best of 3 tiebreak sets",matchUpFormat:Dn,categoryNames:[],categoryTypes:[]},{description:"Two tiebreak sets, 7-point match tiebreak at one set all",matchUpFormat:"SET3-S:6/TB7-F:TB7"},{description:"Two tiebreak sets, 10-point match tiebreak at one set all",matchUpFormat:"SET3-S:6/TB7-F:TB10"},{description:"One standard tiebreak set to 6, 7-point tiebreak at 6 games all",matchUpFormat:"SET1-S:6/TB7"},{description:"Best of 3 sets to 4",matchUpFormat:"SET3-S:4/TB7"},{description:"Two out of three short sets to 4 with 5-point tiebreak at 3 games all",matchUpFormat:"SET3-S:4/TB5@3"},{description:"One short set to 4, 7-point tiebreak at 4 games all",matchUpFormat:"SET1-S:4/TB7"},{description:"One short set to 4, 5-point tiebreak at 3 games all",matchUpFormat:"SET1-S:4/TB5@3"},{description:"Two short sets to 4, 10-point match tiebreak at one set all",matchUpFormat:"SET3-S:4/TB7-F:TB10"},{description:"Two short sets to 4, 7-point match tiebreak at one set all",matchUpFormat:"SET3-S:4/TB7-F:TB7"},{description:"One no advantage set to 5, tiebreak to 9 at 4-4",matchUpFormat:"SET1-S:5/TB9@4"},{description:"One set to 6 with deciding game at 5 games all",matchUpFormat:"SET1-S:6NOAD"},{description:"One short set to 4, deciding game is played at 3 games all",matchUpFormat:"SET1-S:4NOAD"},{description:"Two short sets to 4 with deciding game at 3-3, 7-point match tiebreak at one set all",matchUpFormat:"SET3-S:4NOAD-F:TB7"},{description:"8 game pro-set with 7 point tiebreak at 8 games all",matchUpFormat:"SET1-S:8/TB7"},{description:"8 game pro-set with 7 point tiebreak at 7 games all",matchUpFormat:"SET1-S:8/TB7@7"},{description:"Best of 3 10-point tiebreak games",matchUpFormat:"SET3-S:TB10"},{description:"One 10-point tiebreak game",matchUpFormat:"SET1-S:TB10"},{description:"Timed 20 minute game - game based",matchUpFormat:"SET1-S:T20"}],matchUpStatusCodes:{[vr]:[{matchUpStatusCodeDisplay:"Abandoned",label:"Abandoned match",matchUpStatusCode:"OA"}],[co]:[{matchUpStatusCodeDisplay:"Unplayed or Cancelled",label:"Cancelled match",matchUpStatusCode:"OC"}],[un]:[{matchUpStatusCodeDisplay:"Incomplete",label:"Incomplete match",matchUpStatusCode:"OI"}],[Rt]:[{description:"Disqualification for cause or ineligibility",label:"Disqualification (ineligibility)",matchUpStatusCodeDisplay:"Def [dq]",matchUpStatusCode:"DQ"},{description:"Misconduct before or between matches",label:"Misconduct",matchUpStatusCodeDisplay:"Def [cond]",matchUpStatusCode:"DM"},{description:"Failure to start match because of adult discipline",label:"Fail. (adult discipline)",matchUpStatusCodeDisplay:"Def [ad]",matchUpStatusCode:"D5"},{description:"Refusal to start match for reason other than adult discipline, injury, illness, or personal circumstance. (After the Referee has conclusively confirmed that a player refuses to play a match, the Referee need not wait until the scheduled time of the match to records the result.)",label:"Refusal to start match",matchUpStatusCodeDisplay:"Def [refsl]",matchUpStatusCode:"D4"},{label:"Not showing up",matchUpStatusCodeDisplay:"Def [ns]",matchUpStatusCode:"D6"},{description:"Lateness for match including, but not limited to, intending to play but mistakenly arriving at the wrong time, location, or without proper equipment",label:"Lateness for match",matchUpStatusCodeDisplay:"Score + Def [late]",matchUpStatusCode:"D7"},{label:"Double default",matchUpStatusCodeDisplay:"Def/Def",matchUpStatusCode:"DD"},{description:"Refusal to continue playing a match for reason other than injury, illness, personal circumstance, or adult discipline",label:"Refusal to continue match",matchUpStatusCodeDisplay:"Def [refsl]",matchUpStatusCode:"D9"},{description:"Default for receiving an injection, IV, or supplemental oxygen",label:"Default (PEDs)",matchUpStatusCodeDisplay:"Def [med]",matchUpStatusCode:"DI"},{description:"Default under Point Penalty System",label:"Default (Point Penalty System)",matchUpStatusCodeDisplay:"Def [pps]",matchUpStatusCode:"DP"}],[bt]:[{matchUpStatusCodeDisplay:"Wo [inj]",matchUpStatusCode:"W1",label:"Injury"},{matchUpStatusCodeDisplay:"Wo [ill]",matchUpStatusCode:"W2",label:"Illness"},{matchUpStatusCodeDisplay:"Wo [pc]",label:pC,matchUpStatusCode:"W3"},{matchUpStatusCodeDisplay:"Wo/Wo",matchUpStatusCode:"WOWO",label:"Double walkover"},{matchUpStatusCodeDisplay:"Wo [Tae]",label:"Tournament Administrative Error",matchUpStatusCode:"W4"},{matchUpStatusCodeDisplay:"Wo/Withdrawn",matchUpStatusCode:"W5",label:"Withdrawn"}],[nr]:[{matchUpStatusCodeDisplay:"Ret [inj]",matchUpStatusCode:"RJ",label:"Injury"},{matchUpStatusCodeDisplay:"Ret [ill]",matchUpStatusCode:"RI",label:"Illness"},{matchUpStatusCodeDisplay:"Ret [pc]",label:pC,matchUpStatusCode:"RC"},{description:"Retirement because of adult discipline",label:"Ret. (adult discipline)",matchUpStatusCodeDisplay:"Ret [ad]",matchUpStatusCode:"RD"},{description:"A player who retires from a match remains eligible for consolations, place playoffs, doubles and subsequent round robin matches",matchUpStatusCodeDisplay:"Ret [elg]",label:"Ret. (eligible)",matchUpStatusCode:"RU"}],[uo]:[{matchUpStatusCodeDisplay:"Wd [inj]",matchUpStatusCode:"WD.INJ",label:"Injury"},{matchUpStatusCodeDisplay:"Wd [ill]",matchUpStatusCode:"WD.ILL",label:"Illness"},{matchUpStatusCodeDisplay:"Wd [pc]",label:pC,matchUpStatusCode:"WD.PC"},{matchUpStatusCodeDisplay:"Wd/Wd",matchUpStatusCode:"WD.WD",label:"Double withdrawal"},{label:"Tournament Administrative Error",matchUpStatusCodeDisplay:"Wd [Tae]",matchUpStatusCode:"WD.TAE"}]}}};var oL={[Fn]:{seedingProfile:{positioning:Qc},validSeedPositions:{ignore:!0},duplicateSeedNumbers:!0,drawSizeProgression:!0,policyName:"ITF SEEDING",seedsCountThresholds:[{drawSize:4,minimumParticipantCount:3,seedsCount:2},{drawSize:16,minimumParticipantCount:12,seedsCount:4},{drawSize:32,minimumParticipantCount:24,seedsCount:8},{drawSize:64,minimumParticipantCount:48,seedsCount:16},{drawSize:128,minimumParticipantCount:97,seedsCount:32},{drawSize:256,minimumParticipantCount:192,seedsCount:64}]}};var iL={POLICY_AVOIDANCE_COUNTRY:Xw,POLICY_POSITION_ACTIONS_DEFAULT:pT,POLICY_POSITION_ACTIONS_DISABLED:tL,POLICY_POSITION_ACTIONS_NO_MOVEMENT:Zw,POLICY_POSITION_ACTIONS_UNRESTRICTED:Jw,POLICY_PRIVACY_DEFAULT:eL,POLICY_ROUND_NAMING_DEFAULT:ig,POLICY_SCHEDULING_DEFAULT:MN,POLICY_SCORING_DEFAULT:rL,POLICY_SCORING_USTA:nL,POLICY_SEEDING_ITF:oL,POLICY_SEEDING_DEFAULT:pN};var Y0={ratingsParameters:we,matchUpFormats:zC,countryToFlag:HU,tieFormats:My,countries:ri,policies:iL,flagIOC:Nb};var uL={};Jt(uL,{activeMatchUpStatuses:()=>Xm,auditConstants:()=>cx,completedMatchUpStatuses:()=>se,directingMatchUpStatuses:()=>Hh,displayConstants:()=>$_,drawDefinitionConstants:()=>SU,entryStatusConstants:()=>Rb,errorConditionConstants:()=>CC,eventConstants:()=>ZC,extensionConstants:()=>Gh,flightConstants:()=>lx,genderConstants:()=>Cm,keyValueConstants:()=>n_,matchUpActionConstants:()=>bO,matchUpStatusConstants:()=>Yh,matchUpTypes:()=>mC,nonDirectingMatchUpStatuses:()=>Wh,particicipantsRequiredMatchUpStatuses:()=>Vh,participantConstants:()=>Db,participantRoles:()=>hd,participantTypes:()=>lu,penaltyConstants:()=>sL,policyConstants:()=>hb,positionActionConstants:()=>oO,ratingConstants:()=>mO,recoveryTimeRequiredMatchUpStatuses:()=>yb,requestConstants:()=>$x,resourceContants:()=>KC,resultConstants:()=>UC,scaleConstants:()=>Ib,scheduleConstants:()=>Yb,sortingConstants:()=>Tx,surfaceConstants:()=>aL,tieFormatConstants:()=>QC,timeItemConstants:()=>Hb,topicConstants:()=>Eb,tournamentConstants:()=>TA,upcomingMatchUpStatuses:()=>jh,validMatchUpStatuses:()=>Bh,venueConstants:()=>cL,weekdayConstants:()=>Cy});var q0="Coaching",$0="Ball Abuse",K0="Racket Abuse",z0="Verbal Abuse",Q0="INELIGIBILITY",X0="Physical Abuse",J0="Unsportmanlike Conduct",Z0="Dress Code Violation",tB="Equipment Violation",eB="Leaving the court",rB="Failure to complete",nB="No Show",oB="Other",iB="REFUSAL_TO_PLAY",sB="PROHIBITED_SUBSTANCE",aB="Puncuality",cB="Failure to sign in",sL={COACHING:q0,BALL_ABUSE:$0,RACKET_ABUSE:K0,VERBAL_ABUSE:z0,PHYSICAL_ABUSE:X0,INELIGIBILITY:Q0,UNSPORTSMANLIKE_CONDUCT:J0,PROHIBITED_SUBSTANCE:sB,DRESS_CODE_VIOLATION:Z0,EQUIMENT_VIOLATION:tB,LEAVING_THE_COURT:eB,REFUSAL_TO_PLAY:iB,FAILURE_TO_COMPLETE:rB,NO_SHOW:nB,OTHER:oB,PUNCTUALITY:aB,FAILUIRE_TO_SIGN_IN:cB};var uB="CLAY",pB="HARD",mB="GRASS",dB="CARPET",lB="ARTIFICIAL",aL={CLAY:uB,HARD:pB,GRASS:mB,CARPET:dB,ARTIFICIAL:lB};var fB="INDOOR",gB="OUTDOOR",cL={INDOOR:fB,OUTDOOR:gB};export{Xm as activeMatchUpStatuses,w0 as askEngine,x0 as asyncEngine,cx as auditConstants,G0 as competitionEngine,bU as competitionGovernor,se as completedMatchUpStatuses,Hh as directingMatchUpStatuses,$_ as displayConstants,SU as drawDefinitionConstants,_N as drawsGovernor,VN as entriesGovernor,Rb as entryStatusConstants,CC as errorConditionConstants,ZC as eventConstants,ZN as eventGovernor,Gh as extensionConstants,uL as factoryConstants,Y0 as fixtures,lx as flightConstants,O0 as forge,Cm as genderConstants,iM as generationGovernor,wC as globalState,EA as governors,n_ as keyValueConstants,bO as matchUpActionConstants,L0 as matchUpEngine,Fy as matchUpFormatCode,Fy as matchUpFormatGovernor,NM as matchUpGovernor,Yh as matchUpStatusConstants,mC as matchUpTypes,k0 as mocksEngine,TI as mocksGovernor,Wh as nonDirectingMatchUpStatuses,Vh as particicipantsRequiredMatchUpStatuses,Db as participantConstants,rR as participantGovernor,hd as participantRoles,lu as participantTypes,sL as penaltyConstants,hb as policyConstants,uN as policyGovernor,oO as positionActionConstants,mR as publishingGovernor,vN as queryGovernor,mO as ratingConstants,yb as recoveryTimeRequiredMatchUpStatuses,dR as reportGovernor,$x as requestConstants,KC as resourceContants,UC as resultConstants,Ib as scaleConstants,j0 as scaleEngine,Yb as scheduleConstants,PR as scheduleGovernor,$g as scoreGovernor,Tx as sortingConstants,aL as surfaceConstants,Ww as syncEngine,QC as tieFormatConstants,xR as tieFormatGovernor,Hb as timeItemConstants,nC as tools,Eb as topicConstants,TA as tournamentConstants,V0 as tournamentEngine,qR as tournamentGovernor,jh as upcomingMatchUpStatuses,nC as utilities,Bh as validMatchUpStatuses,cL as venueConstants,rC as venueGovernor,Ba as version,Cy as weekdayConstants};