tods-competition-factory 2.2.45 → 2.2.47
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.mjs +2 -2
- package/dist/tods-competition-factory.d.ts +2 -8
- package/dist/tods-competition-factory.development.cjs.js +3 -3
- package/dist/tods-competition-factory.development.cjs.js.map +1 -1
- package/dist/tods-competition-factory.production.cjs.min.js +1 -1
- package/dist/tods-competition-factory.production.cjs.min.js.map +1 -1
- package/package.json +1 -1
package/dist/index.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
var yL=Object.defineProperty;var Xt=(t,e)=>{for(var r in e)yL(t,r,{get:e[r],enumerable:!0})};function Ka(){return"2.2.45"}var bE={};Xt(bE,{competitionGovernor:()=>kU,drawsGovernor:()=>GN,entriesGovernor:()=>qN,eventGovernor:()=>iM,generationGovernor:()=>pM,matchUpFormatGovernor:()=>jy,matchUpGovernor:()=>bM,mocksGovernor:()=>PI,participantGovernor:()=>sR,policyGovernor:()=>gN,publishingGovernor:()=>gR,queryGovernor:()=>FN,reportGovernor:()=>IR,scheduleGovernor:()=>RR,scoreGovernor:()=>Jg,tieFormatGovernor:()=>kR,tournamentGovernor:()=>XR,venueGovernor:()=>aC});var kU={};Xt(kU,{getLinkedTournamentIds:()=>fu,getTournamentIds:()=>Np,linkTournaments:()=>_U,mutate:()=>LU,query:()=>FU,unlinkTournament:()=>wU,unlinkTournaments:()=>xU});var LU={};Xt(LU,{linkTournaments:()=>_U,unlinkTournament:()=>wU,unlinkTournaments:()=>xU});var Ia="SINGLES",Lt="SINGLES",Gi="DOUBLES",vt="DOUBLES",xr="TEAM",Wt="TEAM",IC={SINGLES_MATCHUP:Ia,SINGLES:Lt,DOUBLES_MATCHUP:Gi,DOUBLES:vt,TEAM_MATCHUP:xr,TEAM:Wt};var vI={[Lt]:[Lt,"S"],[vt]:[vt,"D"],[Wt]:[Wt,"T"],S:[Lt,"S"],D:[vt,"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 Ln(t){return isNaN(t)?!1:t&&(t&t-1)===0}function xE(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 hC(t){if(!Ln(t))return!1;let e=t,r=1;for(;e!==2;)r+=1,e=e/2;return r}function Rm(t){return isNaN(t)?0:t%2&&t+1||t}function Cm(t){return Math.pow(2,Math.round(Math.log(t)/Math.log(2)))}function Jt(t){return!isNaN(parseFloat(t))}function _I(t){let e=dt(t);if(!isNaN(e))return e===0?!1:(e&-e)===1}function us(t){if(isNaN(t))return!1;for(;!Ln(t);)t++;return t}function Io(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 SC(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 EL(t,e){e||(e=1);let r=1/e;return Math.round(t*r)/r}function wE(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=wE(t,e,r):(a=Math.pow(a,r),a*=e-t,a+=t),n&&(a=EL(a,n)),parseFloat(a.toFixed(o))}function Hl(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 TC(t){return Array.isArray(t)?t?.map(e=>e===null?void 0:e):t}function Tr(t){return Array.isArray(t)?t.map(e=>[Math.random(),e]).sort((e,r)=>e[0]-r[0]).map(e=>e[1]):[]}function za(t){return It(t)?t:1/0}function Er(t){return Array.isArray(t)?t.reduce((e,r)=>(e[r]||(e[r]=0),e[r]++,e),{}):{}}function yC(t){return LE(Er(t))}function LE(t){return Object.keys(t).reduce((e,r)=>{let n=t[r];return e[n]?e[n].push(r):e[n]=[r],e},{})}function AL(t,e,r){return r.indexOf(t)===e}function xI(t){return t.filter(AL)}function tn(t){return Array.isArray(t)&&t.length?t.splice(Math.floor(Math.random()*t.length),1)[0]:void 0}function Un(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 ho(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 FE(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 EC(t,e){return Array.isArray(e)&&e.reduce((r,n)=>(r[n]=1+r[n]||1,r),{})[t]||0}function AC(t,e,r,n){return Array.isArray(t)?[].concat(...t.slice(0,e),...t.slice(e,e+r).sort(n),...t.slice(e+r,t.length)):[]}function Ae(t,e){return Array.isArray(t)?t.reduce((r,n,o)=>{let i=Math.floor(o/e);return r[i]=[].concat(r[i]||[],n),r},[]):[]}function kE(t,[e,...r]){return t.length?[t.slice(0,e),...kE(t.slice(e),[...r,e])]:[]}function UC(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 wI(t){return Array.isArray(t)?t.reduce((e,r)=>!isNaN(parseInt(r))&&e,!0):!1}function LI(t){return Array.isArray(t)?t.reduce((e,r)=>isNaN(parseInt(r))&&e,!0):!1}function Wl(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 PC(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 Yr(t){return typeof t=="function"}function kt(t){return typeof t=="string"}function ht(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function DC(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 kI(t,e){return Array.isArray(t)?Object.assign({},...(t??[]).filter(ht).map(r=>r[e]&&{[r[e]]:r}).filter(Boolean)):{}}var NC=t=>e=>Object.keys(t).every(r=>e[r]===t[r]);function FI(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=>FI(i))}:{[o]:e?n(t[o]):FI(t[o])}))}function GE(t){return Array.isArray(t)?t.length+t.map(GE).reduce((e,r)=>e+r,0):ht(t)&&t!==null?Object.keys(t).length+Object.keys(t).map(e=>GE(t[e])).reduce((e,r)=>e+r,0):0}function MC(t){if(t===null||typeof t!="object")return;let e=JSON.stringify(t),r=GE(t),n=e.split("").reduce((o,i)=>o+i.charCodeAt(0),0);return[e.length,r,n].map(o=>o.toString(36)).join("")}function Yc(t,e){return!Array.isArray(t)||!kt(e)?!1:jt(t,vI[e]).length}var C={success:!0},VE="error",RC={SUCCESS:C,ERROR:VE};function GI({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 BC={};Xt(BC,{addNotice:()=>lt,callListener:()=>wm,createInstanceState:()=>KA,cycleMutationStatus:()=>Tf,deepCopyEnabled:()=>Sf,deleteNotice:()=>eh,deleteNotices:()=>Yi,disableNotifications:()=>zA,enableNotifications:()=>hf,getDevContext:()=>Dr,getMethods:()=>yf,getNotices:()=>th,getProvider:()=>rh,getTopics:()=>Lr,getTournamentId:()=>ms,getTournamentRecord:()=>Ef,getTournamentRecords:()=>qo,globalLog:()=>JA,handleCaughtError:()=>fp,hasTopic:()=>dp,removeTournamentRecord:()=>XA,setDeepCopy:()=>Xc,setDevContext:()=>Qc,setGlobalLog:()=>kC,setGlobalMethods:()=>GC,setGlobalSubscriptions:()=>JL,setMethods:()=>VC,setStateMethods:()=>ZA,setStateProvider:()=>QL,setSubscriptions:()=>ZL,setTournamentId:()=>lp,setTournamentRecord:()=>QA,setTournamentRecords:()=>Lm,timeKeeper:()=>XL});var VI={message:"Chronological error; time violation.",code:"ANACHRONISM"},bm={message:"Duplicate entry",code:"DUPLICATE_ENTRY"},BE={message:"Cannot remove main structure",code:"ERR_CANNOT_REMOVE_MAIN_STRUCTURE"},BI={message:"records must be an object with tournamentId keys",code:"ERR_INVALID_TOURNAMENTS"},xt={message:"Missing tournamentRecords",code:"ERR_MISSING_TOURNAMENTS"},q={message:"Missing tournamentRecord",code:"ERR_MISSING_TOURNAMENT"},Qa={message:"Invalid tournamentRecord",code:"ERR_INVALID_TOURNAMENT"},ha={message:"Missing tournamentId",code:"ERR_MISSING_TOURNAMENT_ID"},Sa={message:"Invalid drawDefinition",code:"ERR_INVALID_DRAWDEF"},Z={message:"Missing drawDefinition",code:"ERR_MISSING_DRAWDEF"},HE={message:"Existing drawDefinition(s)",code:"ERR_EXISTING_DRAWDEFS"},br={message:"drawDefinition not found",code:"ERR_NOT_FOUND_DRAWDEF"},si={message:"Invalid structure",code:"ERR_INVALID_STRUCTURE"},jl={message:"Incomplete source structure",code:"ERR_INCOMPLETE_STRUCTURE"},Yl={message:"Invalid drawPosition for seedAssignment",code:"ERR_INVALID_SEEDING_POSITION"},Xa={message:"drawPosition already assigned",code:"ERR_EXISTING_POSITION_ASSIGNMENT"},WE={message:"Schedule not cleared",code:"ERR_UNCHANGED_SCHEDULE_NOT_CLEARED"},jE={message:"drawPosition not cleared",code:"ERR_FAILURE_POSITION_NOT_CLEARED"},UL={message:"drawPosition not found",code:"ERR_NOT_FOUND_DRAW_POSITION"},ql={message:"Unrecognized drawType",code:"ERR_UNRECOGNIZED_DRAW_TYPE"},Ja={message:"Missing drawPositions",code:"ERR_MISSING_DRAW_POSITIONS"},rp={message:"drawPosition is active",code:"ERR_ACTIVE_DRAW_POSITION"},CC={message:"drawPosition is occupied",code:"ERR_OCCUPIED_DRAW_POSITION"},Ls={message:"Invlid drawPosition",code:"ERR_INVALID_DRAW_POSITION"},Fs={message:"Missing drawPosition",code:"ERR_MISSING_DRAW_POSITION"},Om={message:"Invalid drawType",code:"ERR_INVALID_DRAW_TYPE"},np={message:"Invalid drawSize",code:"ERR_INVALID_DRAW_SIZE"},HI={message:"Cannot set drawSize to be less than existing entries",code:"ERR_INVALID_DRAW_SIZE_MISMATCH"},Za={message:"Missing drawSize",code:"ERR_MISSING_DRAW_SIZE"},cn={message:"Missing drawId",code:"ERR_MISSING_DRAW_ID"},YE={message:"drawId exists",code:"ERR_EXISTING_DRAW_ID"},qE={message:"participantId cannot be assigned to multiple seedNumbers",code:"INVALID_PARTICIPANT_SEEDING"},$E={message:"seedsCount greater than drawSize",code:"ERR_INVALID_SEED_COUNT"},KE={message:"Missing seedCountThresholds",code:"ERR_MISSING_SEED_COUNT_THRESHOLD"},zE={message:"Invalid action",code:"ERR_INVALID_ACTION"},WI={message:"Invalid assignment",code:"ERR_INVALID_ASSIGNMENT"},QE={message:"Missing seedAssignments",code:"ERR_MISSING_SEED_ASSIGNMENTS"},XE={message:"Invalid seedNumber",code:"ERR_INVALID_SEED_NUMBER"},JE={message:"Invalid seedPosition",code:"ERR_INVALID_SEED_POSITION"},$l={message:"Missing targetLink",code:"ERR_MISSING_LINK_TARGET"},ZE={message:"Existing round",code:"ERR_EXISTING_ROUND"},PL={message:"Missing roundNumber",code:"ERR_MISSING_ROUND_NUMBER"},Pr={message:"Missing structureId",code:"ERR_MISSING_STRUCTURE_ID"},_t={message:"structure not found",code:"ERR_NOT_FOUND_STRUCTURE"},Kl={message:"Missing structures",code:"ERR_MISSING_STRUCTURES"},Si={message:"Missing structure",code:"ERR_MISSING_STRUCTURE"},zl={message:"Missing MAIN structure",code:"ERR_MISSING_MAIN_STRUCTURE"},tA={message:"drawDefinition contains unlinked structures",code:"ERR_MISSING_STRUCTURE_LINKS"},$n={message:"Invalid eventType",code:"ERR_INVALID_EVENT_TYPE"};var Ot={message:"Missing event / eventId",code:"ERR_MISSING_EVENT_ID"},qr={message:"Event not found",code:"ERR_NOT_FOUND_EVENT"},eA={message:"Event exists",code:"ERR_EXISTING_EVENT"},rA={message:"Missing entries",code:"ERR_MISSING_ENTRIES"},nA={message:"Invalid entries",code:"ERR_INVALID_ENTRIES"},Ql={message:"Missing assignments",code:"ERR_MISSING_ASSIGNMENTS"},oA={message:"Missing stage",code:"ERR_MISSING_STAGE"},Vi={message:"Invalid stage",code:"ERR_INVALID_STAGE"},iA={message:"stageSequence limit",code:"ERR_LIMIT_STAGE_SEQUENCE"},sA={message:"Missing positionAssignments",code:"ERR_MISSING_POSITION_ASSIGNMENTS"},aA={message:"Cannot Assign BYE status if no assignment: { bye: true }",code:"ERR_UNCHANGED_CANNOT_ASSIGN_BYE"},jI={message:"Unrecognized matchUpStatus",code:"ERR_UNRECOGNIZED_MATCHUP_STATUS"},tc={message:"Unrecognized matchUpFormat",code:"ERR_UNRECOGNIZED_MATCHUP_FORMAT"},Xl={message:"Incompatible matchUpStatus",code:"ERR_INCOMPATIBLE_MATCHUP_STATUS"},bC={message:"Propagated exits downstream",code:"ERR_PROPAGATED_EXITS_DOWNSTREAM"},Ta={message:"Invalid matchUpStatus",code:"ERR_INVALID_MATCHUP_STATUS"},Yo={message:"Invalid tieFormat",code:"ERR_INVALID_TIE_FORMAT"},Jl={message:"Invalid matchUpFormat",code:"ERR_INVALID_MATCHUP_FORMAT"},Zl={message:"Missing matchUpFormat",code:"ERR_MISSING_MATCHUP_FORMAT"},cA={message:"Missing collectionDefinition",code:"ERR_MISSING_COLLECTION_DEFINITION"},ks={message:"Missing tieFormat",code:"ERR_MISSING_TIE_FORMAT"},sr={message:"Missing matchUpId",code:"ERR_MISSING_MATCHUP_ID"},ps={message:"Missing matchUpIds",code:"ERR_MISSING_MATCHUP_IDS"},we={message:"matchUp not found",code:"ERR_NOT_FOUND_MATCHUP"},no={message:"Missing matchUps",code:"ERR_MISSING_MATCHUPS"},mr={message:"Missing matchUp",code:"ERR_MISSING_MATCHUP"},dr={message:"Invalid matchUp",code:"ERR_INVALID_MATCHUP"},YI={message:"Missing policyType",code:"ERR_MISSING_POLICY_TYPE"},op={message:"Missing policyDefinitions",code:"ERR_MISSING_POLICY_DEFINITIONS"},DL={message:"Missing seeding policy",code:"ERR_MISSING_POLICY_SEEDING"},uA={message:"Missing avoidance policy",code:"ERR_MISSING_POLICY_AVOIDANCE"},qI={message:"Missing policy attributes",code:"ERR_MISSING_POLICY_ATTRIBUTES"},pA={message:"Invalid policyDefinitions",code:"ERR_INVALID_POLICY_DEFINITIONS"},$I={message:"existing policyType",code:"ERR_EXISTING_POLICY_TYPE"},NL={message:"Policy not attached",code:"ERR_FAILURE_POLICY_NOT_ATTACHED"},qc={message:"Policy not found",code:"ERR_NOT_FOUND_POLICY"},ML={message:"Missing scoring policy / matchUpFormats",code:"ERR_MISSING_POLICY_SCORING_MATCHUP_FORMATS"},tf={message:"Invalid sideNumber",code:"ERR_INVALID_SIDE_NUMBER"},RL={message:"Invalid setNumber",code:"ERR_INVALID_SET_NUMBER"},ef={message:"Missing setObject",code:"ERR_MISSING_SET_ATTRIBUTE"},CL={message:"Missing setNumber",code:"ERR_MISSING_SET_NUMBER"},bL={message:"Missing sideNumber",code:"ERR_MISSING_SIDE_NUMBER"},Bi={message:"Missing courtId",code:"ERR_MISSING_COURT_ID"},st={message:"Missing value",code:"ERR_MISSING_VALUE"},mA={message:"Missing birthdate",code:"ERR_MISSING_BIRTH_DATE"},dA={message:"Missing date",code:"ERR_MISSING_DATE"},lA={message:"No valid dates",code:"ERR_NO_VALID_DATES"},vm={message:"Invalid bookings",code:"ERR_INVALID_BOOKINGS"},rf={message:"Invalid dateAvailability",code:"ERR_INVALID_DATE_AVAILABILITY"},fA={message:"Missing dateAvailability",code:"ERR_MISSING_DATE_AVAILABILITY"},Ye={message:"Invalid Date",code:"ERR_INVALID_DATE"},Co={message:"Invalid time",code:"ERR_INVALID_TIME"},gA={message:"Invalid tournament dates",code:"ERR_INVALID_DATES_TOURNAMENT"};var KI={message:"Invalid game scores",code:"ERR_INVALID_SCORES_GAME"},IA={message:"Invalid score",code:"ERR_INVALID_SCORE"},_m={message:"Invalid winningSide",code:"ERR_INVALID_WINNING_SIDE"};var OC={message:"No participants generated",code:"ERR_NO_PARTICIPANTS_GENERATED"},nf={message:"Cannot modify tieFormat",code:"ERR_UNCHANGED_CANNOT_MODIFY_TIEFORMAT"},hA={message:"Cannot modify participantType",code:"ERR_UNCHANGED_CANNOT_MODIFY_PARTICIPANT_TYPE"},ip={message:"Cannot remove participants",code:"ERR_UNCHANGED_CANNOT_REMOVE_PARTICIPANTS"},zI={message:"Participant category mismatch",code:"ERR_CATEGORY_MISMATCH"},xm={message:"Cannot change winningSide",code:"ERR_UNCHANGED_CANNOT_CHANGE_WINNING_SIDE"},Hi={message:"Invalid participant",code:"ERR_INVALID_PARTICIPANT"},ln={message:"Invalid participantId",code:"ERR_INVALID_PARTICIPANT_ID"},wr={message:"Invalid participantIds",code:"ERR_INVALID_PARTICIPANT_IDS"},SA={message:"Invalid participantRole",code:"ERR_INVALID_PARTICIPANT_ROLE"},Pn={message:"Invalid participantType",code:"ERR_INVALID_PARTICIPANT_TYPE"},TA={message:"Missing participantRole",code:"ERR_MISSING_PARTICIPANT_ROLE"},Wi={message:"Missing participant",code:"ERR_MISSING_PARTICIPANT"},ec={message:"Missing participants",code:"ERR_MISSING_PARTICIPANTS"},se={message:"Missing participantId",code:"ERR_MISSING_PARTICIPANT_ID"},yA={message:"Missing qualified participants",code:"ERR_MISSING_QUALIFIED_PARTICIPANTS"},re={message:"Participant Not Found",code:"ERR_NOT_FOUND_PARTICIPANT"},EA={message:"participantId exists",code:"ERR_EXISTING_PARTICIPANT_ID"},OL={message:"participant pair exists",code:"ERR_EXISTING_PARTICIPANT_PAIR"},AA={message:"No participant removed",code:"ERR_UNCHANGED_NO_PARTICIPANT_REMOVED"},bo={message:"Missing participantIds",code:"ERR_MISSING_PARTICIPANT_IDS"},UA={message:"Missing participantsCount",code:"ERR_MISSING_PARTICIPANT_COUNT"},PA={message:"Participant not checked in",code:"ERR_UNCHANGED_PARTICIPANT_NOT_CHECKED_IN"},DA={message:"Missing person details",code:"ERR_MISSING_PERSON_DETAILS"},Gs={message:"Existing participant drawPosition assignment",code:"ERR_EXISTING_PARTICIPANT_DRAW_POSITION_ASSIGNMENT"},sp={message:"Existing participant",code:"ERR_EXISTING_PARTICIPANT"},of={message:"participantsCount exceeds drawSize",code:"ERR_INVALID_PARTICIPANT_COUNT"},sf={message:"Invalid entry status",code:"ERR_INVALID_ENTRY_STATUS"},QI={message:"Participant Entry Not Found",code:"ERR_NOT_FOUND_PARTICIPANT_ENTRY"},vC={message:"Participant not entered in stage",code:"ERR_UNCHANGED_PARTICIPANT_NOT_ENTERED"},_C={message:"Participant not found in stageSequence",code:"ERR_NOT_FOUND_PARTICIPANT_IN_STAGE"},NA={message:"entryStatus not allowed in stage",code:"ERR_INVALID_ENTRY_STATUS_IN_STAGE"},MA={message:"entryStatus not allowed for event",code:"ERR_INVALID_ENTRY_STATUS_IN_EVENT"},XI={message:"No stage space available for entryStatus",code:"ERR_UNCHANGED_NO_AVAILABLE_STAGE_SPACE"},af={message:"Insufficient drawPositions to accommodate qualifiers",code:"ERR_UNCHANGED_NO_DRAW_POSITIONS_FOR_QUALIFIERS"},cf={message:"Insufficient drawPositions to accommodate entries",code:"ERR_INSUFFICIENT_DRAW_POSITIONS"},RA={message:"Missing penaltyType",code:"ERR_MISSING_PENALTY_TYPE"},uf={message:"Missing penaltyId",code:"ERR_MISSING_PENALTY_ID"},$c={message:"Penalty not found",code:"ERR_NOT_FOUND_PENALTY"},CA={message:"Missing courtsCount/courtNames",code:"ERR_MISSING_COURTS_INFO"},Vs={message:"Court not found",code:"ERR_NOT_FOUND_COURT"},bA={message:"Court exists",code:"ERR_EXISTING_COURT"},OA={message:"Venue exists",code:"ERR_EXISTING_VENUE"},ji={message:"Venue not found",code:"ERR_NOT_FOUND_VENUE"},ai={message:"Missing venueId",code:"ERR_MISSING_VENUE_ID"},vA={message:"Invalid endTime",code:"ERR_INVALID_END_TIME"},JI={message:"Existing endTime",code:"ERR_EXISTING_END_TIME"},_A={message:"Invalid stopTime",code:"ERR_INVALID_STOP_TIME"},xA={message:"Invalid startTime",code:"ERR_INVALID_START_TIME"},xC={message:"Invalid resumeTime",code:"ERR_INVALID_RESUME_TIME"},pf={message:"Invalid timeItem",code:"ERR_INVALID_TIME_ITEMS"},wA={message:"Missing async state provider",code:"ERR_MISSING_ASYNC_STATE_PROVIDER"},mf={message:"Missing timeItem",code:"ERR_MISSING_TIME_ITEM"},df={message:"Missing timeItems",code:"ERR_MISSING_TIME_ITEMS"},Kc={message:"Missing context",code:"ERR_MISSING_CONTEXT"},LA={message:"Missing schedule",code:"ERR_MISSING_SCHEDULE"},rc={message:"Invalid scaleItem",code:"ERR_INVALID_SCALE_ITEM"},FA={message:"Modifications failed",code:"ERR_FAILURE_MODIFICATIONS"},Bs={message:"No modifications applied",code:"ERR_UNCHANGED_NO_MODIFICATIONS_APPLIED"},kA={message:"Unable to assign court",code:"ERR_UNCHANGED_COURT_NOT_ASSIGNED"},ap={message:"No Candidates",code:"ERR_UNCHANGED_NO_CANDIDATES"},GA={message:"Invalid configuration",code:"ERR_INVALID_CONFIG"},VA={message:"Invalid collectionDefinition",code:"ERR_INVALID_COLLECTION_DEFINITION"},So={message:"Invalid object",code:"ERR_INVALID_OBJECT"},cp={message:"Invalid gender",code:"ERR_INVALID_GENDER"},zc={message:"Invalid category",code:"ERR_INVALID_CATEGORY"},B={message:"Invalid values",code:"ERR_INVALID_VALUES"},BA={message:"Duplicate value",code:"ERR_DUPLICATE_VALUE"},lf={message:"Team not found",code:"ERR_NOT_FOUND_TEAM"},HA={message:"No valid actions",code:"ERR_NO_VALID_ACTIONS"},up={message:"No valid attributes",code:"ERR_NO_VALID_ATTRIBUTES"},ff={message:"Value unchanged",code:"ABORT_UNCHANGED"},Oe={message:"Not found",code:"ERR_NOT_FOUND"},pp={message:"Not implemented",code:"ERR_NOT_IMPLEMENTED"},WA={message:"Existing flight",code:"ERR_EXISTING_FLIGHT"},gf={message:"Existing flight profile",code:"ERR_EXISTING_FLIGHT_PROFILE"},jA={message:"Existing outcome",code:"ERR_EXISTING_OUTCOME"},YA={message:"Existing matchUpId",code:"ERR_EXISTING_MATCHUP_ID"},ZI={message:"Existing stage",code:"ERR_EXISTING_STAGE"},If={message:"Existing structure",code:"ERR_EXISTING_STRUCTURE"},nc={message:"Method not found",code:"ERR_NOT_FOUND_METHOD"},qA={message:"Scheduled matchUps",code:"ERR_SCHEDULED_MATCHUPS"},oc={message:"Scores present",code:"ERR_SCORES_PRESENT"},wC={ANACHRONISM:VI,CANNOT_CHANGE_WINNING_SIDE:xm,CANNOT_MODIFY_TIEFORMAT:nf,CANNOT_MODIFY_PARTICIPANT_TYPE:hA,CANNOT_REMOVE_MAIN_STRUCTURE:BE,CANNOT_REMOVE_PARTICIPANTS:ip,CATEGORY_MISMATCH:zI,COURT_EXISTS:bA,COURT_NOT_FOUND:Vs,DRAW_DEFINITION_NOT_FOUND:br,DRAW_ID_EXISTS:YE,DRAW_POSITION_ACTIVE:rp,DRAW_POSITION_ASSIGNED:Xa,DRAW_POSITION_NOT_CLEARED:jE,DRAW_POSITION_NOT_FOUND:UL,DRAW_SIZE_MISMATCH:HI,DUPLICATE_ENTRY:bm,DUPLICATE_VALUE:BA,ENTRY_STATUS_NOT_ALLOWED_FOR_EVENT:MA,ENTRY_STATUS_NOT_ALLOWED_IN_STAGE:NA,EVENT_EXISTS:eA,EVENT_NOT_FOUND:qr,EXISTING_DRAW_DEFINITIONS:HE,EXISTING_END_TIME:JI,EXISTING_FLIGHT:WA,EXISTING_MATCHUP_ID:YA,EXISTING_OUTCOME:jA,EXISTING_PARTICIPANT_DRAW_POSITION_ASSIGNMENT:Gs,EXISTING_PARTICIPANT:sp,EXISTING_POLICY_TYPE:$I,EXISTING_PROFILE:gf,EXISTING_ROUND:ZE,EXISTING_STAGE:ZI,EXISTING_STRUCTURE:If,INCOMPATIBLE_MATCHUP_STATUS:Xl,INCOMPLETE_SOURCE_STRUCTURE:jl,INSUFFICIENT_DRAW_POSITIONS:cf,INVALID_ACTION:zE,INVALID_ASSIGNMENT:WI,INVALID_BOOKINGS:vm,INVALID_CATEGORY:zc,INVALID_COLLECTION_DEFINITION:VA,INVALID_CONFIGURATION:GA,INVALID_DATE_AVAILABILITY:rf,INVALID_DATE:Ye,INVALID_DRAW_DEFINITION:Sa,INVALID_DRAW_POSITION_FOR_SEEDING:Yl,INVALID_DRAW_POSITION:Ls,INVALID_DRAW_SIZE:np,INVALID_END_TIME:vA,INVALID_ENTRIES:nA,INVALID_EVENT_TYPE:$n,INVALID_GAME_SCORES:KI,INVALID_GENDER:cp,INVALID_MATCHUP_FORMAT:Jl,INVALID_MATCHUP_STATUS:Ta,INVALID_MATCHUP_STATUS_BYE:aA,INVALID_MATCHUP:dr,INVALID_OBJECT:So,INVALID_PARTICIPANT_ID:ln,INVALID_PARTICIPANT_IDS:wr,INVALID_PARTICIPANT_ROLE:SA,INVALID_PARTICIPANT_SEEDING:qE,INVALID_PARTICIPANT_TYPE:Pn,INVALID_PARTICIPANT:Hi,INVALID_POLICY_DEFINITION:pA,INVALID_RECORDS:BI,INVALID_SCALE_ITEM:rc,INVALID_SEED_NUMBER:XE,INVALID_SEED_POSITION:JE,INVALID_SET_NUMBER:RL,INVALID_SIDE_NUMBER:tf,INVALID_SCORE:IA,INVALID_STAGE:Vi,INVALID_START_TIME:xA,INVALID_STRUCTURE:si,INVALID_STOP_TIME:_A,INVALID_TIE_FORMAT:Yo,INVALID_TIME:Co,INVALID_TIME_ITEM:pf,INVALID_TOURNAMENT_DATES:gA,INVALID_TOURNAMENT_RECORD:Qa,INVALID_VALUES:B,INVALID_WINNING_SIDE:_m,MATCHUP_NOT_FOUND:we,METHOD_NOT_FOUND:nc,MISSING_ASSIGNMENTS:Ql,MISSING_ASYNC_STATE_PROVIDER:wA,MISSING_AVOIDANCE_POLICY:uA,MISSING_BIRTH_DATE:mA,MISSING_COLLECTION_DEFINITION:cA,MISSING_COURT_ID:Bi,MISSING_COURTS_INFO:CA,MISSING_DATE_AVAILABILITY:fA,MISSING_DATE:dA,MISSING_DRAW_DEFINITION:Z,MISSING_DRAW_ID:cn,MISSING_DRAW_POSITION:Fs,MISSING_DRAW_POSITIONS:Ja,MISSING_DRAW_SIZE:Za,MISSING_ENTRIES:rA,MISSING_EVENT:Ot,MISSING_QUALIFIED_PARTICIPANTS:yA,MISSING_MATCHUP_FORMAT:Zl,MISSING_MATCHUP_ID:sr,MISSING_MATCHUP_IDS:ps,MISSING_MATCHUP:mr,MISSING_MATCHUPS:no,MISSING_PARTICIPANT_COUNT:UA,MISSING_PARTICIPANT_ID:se,MISSING_PARTICIPANT_IDS:bo,MISSING_PARTICIPANT_ROLE:TA,MISSING_PARTICIPANT:Wi,MISSING_PARTICIPANTS:ec,MISSING_PENALTY_ID:uf,MISSING_PENALTY_TYPE:RA,MISSING_PERSON_DETAILS:DA,MISSING_POLICY_ATTRIBUTES:qI,MISSING_POLICY_DEFINITION:op,MISSING_POLICY_TYPE:YI,MISSING_POSITION_ASSIGNMENTS:sA,MISSING_ROUND_NUMBER:PL,MISSING_SCHEDULE:LA,MISSING_SCORING_POLICY:ML,MISSING_SEED_ASSIGNMENTS:QE,MISSING_SEEDCOUNT_THRESHOLDS:KE,MISSING_SEEDING_POLICY:DL,MISSING_SET_NUMBER:CL,MISSING_SET_OBJECT:ef,MISSING_SIDE_NUMBER:bL,MISSING_STAGE:oA,MISSING_STRUCTURE_ID:Pr,MISSING_STRUCTURE:Si,MISSING_MAIN_STRUCTURE:zl,MISSING_STRUCTURES:Kl,MISSING_TARGET_LINK:$l,MISSING_TIE_FORMAT:ks,MISSING_TIME_ITEM:mf,MISSING_TIME_ITEMS:df,MISSING_TOURNAMENT_ID:ha,MISSING_TOURNAMENT_RECORD:q,MISSING_TOURNAMENT_RECORDS:xt,MISSING_VALUE:st,MISSING_VENUE_ID:ai,MODIFICATIONS_FAILED:FA,NO_CANDIDATES:ap,NO_DRAW_POSITIONS_AVAILABLE_FOR_QUALIFIERS:af,NO_MODIFICATIONS_APPLIED:Bs,NO_STAGE_SPACE_AVAILABLE_FOR_ENTRY_STATUS:XI,NO_PARTICIPANT_REMOVED:AA,NO_VALID_ACTIONS:HA,NO_VALID_ATTRIBUTES:up,NO_VALID_DATES:lA,NOT_FOUND:Oe,NOT_IMPLEMENTED:pp,PARTICIPANT_COUNT_EXCEEDS_DRAW_SIZE:of,PARTICIPANT_ID_EXISTS:EA,PARTICIPANT_NOT_CHECKED_IN:PA,PARTICIPANT_NOT_FOUND:re,PARTICIPANT_PAIR_EXISTS:OL,PENALTY_NOT_FOUND:$c,POLICY_NOT_ATTACHED:NL,POLICY_NOT_FOUND:qc,SCHEDULE_NOT_CLEARED:WE,SCHEDULED_MATCHUPS:qA,SCORES_PRESENT:oc,SEEDSCOUNT_GREATER_THAN_DRAW_SIZE:$E,STAGE_SEQUENCE_LIMIT:iA,STRUCTURE_NOT_FOUND:_t,TEAM_NOT_FOUND:lf,UNABLE_TO_ASSIGN_COURT:kA,UNLINKED_STRUCTURES:tA,UNRECOGNIZED_DRAW_TYPE:ql,UNRECOGNIZED_MATCHUP_FORMAT:tc,UNRECOGNIZED_MATCHUP_STATUS:jI,VALUE_UNCHANGED:ff,VENUE_EXISTS:OA};var Ze={disableNotifications:!1,tournamentId:void 0,tournamentRecords:{},subscriptions:{},modified:!1,methods:{},notices:[]},$A={addNotice:WL,callListener:KL,cycleMutationStatus:HL,deleteNotice:qL,deleteNotices:YL,disableNotifications:vL,enableNotifications:_L,getMethods:mp,getNotices:jL,getTopics:$L,getTournamentId:LC,getTournamentRecord:xL,getTournamentRecords:wL,removeTournamentRecord:GL,setMethods:BL,setSubscriptions:VL,setTournamentId:FL,setTournamentRecord:LL,setTournamentRecords:kL,handleCaughtError:zL};function vL(){Ze.disableNotifications=!0}function _L(){Ze.disableNotifications=!1}function LC(){return Ze.tournamentId}function xL(t){return Ze.tournamentRecords[t]}function wL(){return Ze.tournamentRecords}function LL(t){let e=t?.tournamentId;return e?(Ze.tournamentRecords[e]=t,{success:!0}):{error:Qa}}function FL(t){return t?Ze.tournamentRecords[t]?(Ze.tournamentId=t,{success:!0}):{error:q}:(Ze.tournamentId=void 0,{success:!0})}function kL(t){Ze.tournamentRecords=t;let e=Object.keys(t);e.length===1?Ze.tournamentId=e[0]:e.length||(Ze.tournamentId=void 0)}function GL(t){if(typeof t!="string")return{error:B};if(!Ze.tournamentRecords[t])return{error:Oe};delete Ze.tournamentRecords[t];let e=Object.keys(Ze.tournamentRecords);return e.length===1?Ze.tournamentId=e[0]:e.length||(Ze.tournamentId=void 0),{success:!0}}function VL(t){return typeof t.subscriptions!="object"?{error:B}:(Object.keys(t.subscriptions).forEach(e=>{typeof t.subscriptions[e]=="function"?Ze.subscriptions[e]=t.subscriptions[e]:delete Ze.subscriptions[e]}),{...C})}function BL(t){return typeof t!="object"?{error:B}:(Object.keys(t).forEach(e=>{typeof t[e]=="function"&&(Ze.methods[e]=t[e])}),{...C})}function HL(){let t=Ze.modified;return Ze.modified=!1,t}function WL({topic:t,payload:e,key:r},n){if(!(typeof t!="string"||typeof e!="object")&&(Ze.disableNotifications||(Ze.modified=!0),!(Ze.disableNotifications||!Ze.subscriptions[t]&&!n)))return r&&(Ze.notices=Ze.notices.filter(o=>!(o.topic===t&&o.key===r))),Ze.notices.push({topic:t,payload:e,key:r}),{...C}}function mp(){return Ze.methods??{}}function jL({topic:t}){return Ze.notices.filter(e=>e.topic===t).map(e=>e.payload)}function YL(){Ze.notices=[]}function qL({topic:t,key:e}){Ze.notices=Ze.notices.filter(r=>(!t||r.topic===t)&&r.key!==e)}function $L(){return{topics:Object.keys(Ze.subscriptions)}}function KL({topic:t,notices:e},r){let n=Ze.subscriptions[t];n&&typeof n=="function"&&n(e);let o=r?.[t];o&&typeof o=="function"&&o(e)}function zL({engineName:t,methodName:e,params:r,err:n}){let o;return typeof n=="string"?o=n.toUpperCase():n instanceof Error&&(o=n.message),console.log("ERROR",{tournamentId:LC(),params:JSON.stringify(r),engine:t,methodName:e,error:o}),{error:o}}var ve={timers:{default:{elapsedTime:0}},globalSubscriptions:{},deepCopyAttributes:{stringify:[],ignore:[],toJSON:[]},globalMethods:[],deepCopy:!0},un=$A,FC=["addNotice","callListener","cycleMutationStatus","deleteNotice","deleteNotices","disableNotifications","enableNotifications","getMethods","getNotices","getTopics","getTournamentId","getTournamentRecord","getTournamentRecords","removeTournamentRecord","setSubscriptions","setTournamentId","setTournamentRecord","setTournamentRecords"];function QL(t){if(typeof t!="object")throw new Error("Global state provider can not be undefined or null");if(jt(Object.keys(t),FC).length!==FC.length)throw new Error("Global state provider is missing required methods");return un=t,{success:!0}}function KA(){if(un.createInstanceState){try{un.createInstanceState()}catch(t){return{error:t}}return{success:!0}}else return{error:wA}}function Dr(t){return!t||typeof t!="object"?ve.devContext??!1:typeof ve.devContext!="object"?!1:Object.keys(t).every(e=>ve.devContext?.[e]===t[e])&&ve.devContext}function XL(t="reset",e="default"){let r=Date.now();if(t==="report"){if(e==="allTimers")return Object.keys(ve.timers).filter(o=>o!=="default"||ve.timers[o].startTime).map(o=>{let i=ve.timers[o],s=i.state==="stopped"?0:(r-(i?.startTime??0))/1e3,a=i.elapsedTime+s;return{state:ve.timers[o].state,elapsedTime:a.toFixed(2),timer:o}});{let n=ve.timers[e].state==="stopped"?0:(r-(ve.timers[e]?.startTime??0))/1e3,o=ve.timers[e].elapsedTime+n;return{state:ve.timers[e].state,elapsedTime:o.toFixed(2),timer:e}}}if(!ve.timers[e]||t==="reset"){if(e==="allTimers")return ve.timers={default:{elapsedTime:0}},!0;ve.timers[e]={startTime:r,state:"active",elapsedTime:0}}return ve.timers[e].elapsedTime||(ve.timers[e].elapsedTime=0),t==="stop"&&ve.timers[e].state!=="stopped"&&(ve.timers[e].state="stopped")&&(ve.timers[e].elapsedTime+=(r-(ve.timers[e]?.startTime??0))/1e3),t==="start"&&(ve.timers[e].startTime=r)&&(ve.timers[e].state="active"),ve.timers[e]}function kC(t){Yr(t)?ve.globalLog=t:delete ve.globalLog}function Qc(t){ve.devContext=t}function zA(){un.disableNotifications()}function hf(){un.enableNotifications()}function Xc(t,e){typeof t=="boolean"&&(ve.deepCopy=t),typeof e=="object"&&(Array.isArray(e.ignore)&&(ve.deepCopyAttributes.ignore=e.ignore),Array.isArray(e.toJSON)&&(ve.deepCopyAttributes.toJSON=e.toJSON),Array.isArray(e.stringify)&&(ve.deepCopyAttributes.stringify=e.stringify),e.threshold&&(ve.deepCopyAttributes.threshold=e.threshold))}function Sf(){return{enabled:ve.deepCopy,...ve.deepCopyAttributes}}function JL(t){return t?.subscriptions?(Object.keys(t.subscriptions).forEach(e=>{ve.globalSubscriptions[e]=t.subscriptions[e]}),{...C}):{error:st,info:"missing subscriptions"}}function ZL(t){return t?.subscriptions?un.setSubscriptions({subscriptions:t.subscriptions}):{error:st,info:"missing subscriptions"}}function GC(t){return t?typeof t!="object"?{error:B}:(Object.keys(t).forEach(e=>{Yr(t[e])&&(ve.globalMethods[e]=t[e])}),{...C}):{error:st,info:"missing method declarations"}}function VC(t){return t?typeof t!="object"?{error:B}:un.setMethods(t):{error:st,info:"missing method declarations"}}function Tf(){return un.cycleMutationStatus()}function lt(t){if(typeof t?.topic!="string")return;let e=ve.globalSubscriptions[t.topic];return un.addNotice(t,e)}function yf(){return{...ve.globalMethods,...un.getMethods()}}function th(t){return un.getNotices(t)}function eh({key:t,topic:e}){return un.deleteNotice({key:t,topic:e})}function Yi(){return un.deleteNotices()}function Lr(){return un.getTopics()}function dp(t){return Lr()?.topics?.includes(t)}async function wm(t){return un.callListener(t,ve.globalSubscriptions)}function ms(){return un.getTournamentId()}function Ef(t){return un.getTournamentRecord(t)}function qo(){return un.getTournamentRecords()}function QA(t){return un.setTournamentRecord(t)}function Lm(t){return un.setTournamentRecords(t)}function lp(t){return un.setTournamentId(t)}function XA(t){return un.removeTournamentRecord(t)}function rh(){return un}function fp({engineName:t,methodName:e,params:r,err:n}){let o=Yr(un.handleCaughtError)&&un.handleCaughtError||$A.handleCaughtError,{tournamentRecord:i,...s}=r;return o({params:s,engineName:t,methodName:e,err:n})}function JA(t,e){if(ve.globalLog)try{ve.globalLog({log:t,engine:e})}catch(r){console.log("globalLog error",r),console.log(e,t),kC()}else console.log(e,t)}function ZA(t,e,r,n){if(!ht(t))return{error:B};Jt||(r=1);let o=Array.isArray(e)?e:[],i={},s=(a,c=0)=>{Object.keys(a).forEach(u=>{Yr(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?GC(i):VC(i),{methods:i}}function tF(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;Sf()?.enabled||(n=!0);let i=["",void 0,null];e&&i.push(!1);let s=tF(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&&(e.context||(e.context={}),Object.assign(e.context,nt(t))),e&&!e?.error&&!e?.success&&Object.assign(e,{...C}),e??{success:!0}}var lr="FEMALE",$o="OTHER",qi="MIXED",Le="MALE";var Fm={FEMALE_ABBR:"F",OTHER_ABBR:"O",MIXED_ABBR:"X",MALE_ABBR:"M",ANY_ABBR:"A",FEMALE:lr,MIXED:qi,OTHER:$o,MALE:Le,ANY:"ANY"};function $i(t){return[lr,"F"].includes(t)}function Hs(t){return[Le,"M"].includes(t)}function en(t){return[qi,"X"].includes(t)}function To(t){return["ANY","A"].includes(t)}function yr(t){if(t){if($i(t))return lr;if(en(t))return qi;if(Hs(t))return Le;if(To(t))return"ANY"}return $o}function Dn(t){return $i(t)||Hs(t)}var iF="MIXED events can not contain mixed singles or { gender: ANY } collections",sF="events with { gender: ANY } can not contain MIXED singles collections";function km(t){let e="tieFormatGenderValidityCheck",{referenceGender:r,matchUpType:n,gender:o}=t;return r&&o&&Dn(r)&&yr(r)!==yr(o)?_({result:{valid:!1,error:cp},context:{gender:o},stack:e}):en(r)&&(To(o)||en(o)&&n!==vt)?_({result:{error:cp,valid:!1},info:iF,stack:e}):To(r)&&en(o)&&n!==vt?_({result:{error:cp,valid:!1},info:sF,stack:e}):{valid:!0}}var aF="normal",tU="timed",cF="final",Af="NOAD";var HC={S:aF,F:cF};function gp(t,e){if(ht(t)&&(t?.bestOf||t?.exactly)&&t?.setFormat)return uF(t,e)}function Uf(t){return!Number.isNaN(Number(t))&&Number(t)}function YC(t){let e=`T${t.minutes}`;return t.based==="A"?e+="A":t.based==="P"&&(e+="P"),t.tiebreakFormat?.tiebreakTo&&(e+=`/TB${t.tiebreakFormat.tiebreakTo}`),t.modifier&&(e+=`@${t.modifier}`),e}function uF(t,e){let r=Uf(t.bestOf)||void 0,n=Uf(t.exactly)||void 0,o=r||n;if(t.setFormat?.timed&&t.simplified&&o===1)return YC(t.setFormat);let s=o&&`${"SET"}${o}${n&&n!==1?"X":""}`||"",a=WC(t.setFormat,e),c=a&&`S:${a}`||"",u=WC(t.finalSetFormat,e),p=o&&o>1&&u&&a!==u&&`F:${u}`||"";if(s&&a)return[s,c,p].filter(Boolean).join("-")}function WC(t,e){if(typeof t=="object"&&Object.keys(t).length){if(t.timed)return YC(t);if(t.tiebreakSet)return jC(t.tiebreakSet);let r=Uf(t.setTo);if(r){let n=t.NoAD&&Af||"",o=jC(t.tiebreakFormat),i=o&&`/${o}`||"",s=Uf(t.tiebreakAt),a=s&&(s!==r||e)&&`@${s}`||"";if(o!==!1)return`${r}${n}${i}${a}`}}}function jC(t){if(t){if(typeof t=="object"&&!t.tiebreakTo)return"";if(typeof t=="object"&&Uf(t.tiebreakTo)){let e=`TB${t.tiebreakTo}${t.NoAD?Af:""}`;return t.modifier&&(e+=`@${t.modifier}`),e}else return!1}}function Ne(t){if(kt(t)){let e=t.startsWith("T")&&tU||t.startsWith("SET")&&"SET"||"";if(e===tU){let r=zC(t),n={simplified:!0,setFormat:r,bestOf:1};if(r)return n}if(e==="SET")return pF(t)}}function pF(t){let e=t.split("-"),r=e[0].slice(3),n=r.endsWith("X"),o=n?r.slice(0,-1):r,i=Gm(o),s=n&&i!==1?void 0:i,a=n&&i!==1?i:void 0,c=e&&qC(e[1]),u=e&&qC(e[2]),p=c&&c.timed||u&&u.timed,m=s&&s<6||p&&a,d=!e[2]||u,l=c,f=nt({setFormat:c,exactly:a,bestOf:s});if(u&&(f.finalSetFormat=u),m&&l&&d)return f}function qC(t){if(t?.[1]!==":")return;let e=t.split(":"),r=HC[e[0]],n=e[1];if(!(!r||!n))return mF(t,n)}function mF(t,e){return e.startsWith("TB")?dF(e):e.startsWith("T")?zC(e):lF(t,e)}function dF(t){let e=KC(t);return e===!1?!1:typeof e=="object"?{tiebreakSet:e}:void 0}function lF(t,e){let r=/^[FS]:(\d+)([A-Za-z]*)/.exec(t),n=r&&QC(r[2])||!1,o=!r?.[2]||n,i=r?Gm(r[1]):void 0,s=$C(e),a=s!==!1,c=a&&s||i,u=KC(e.split("/")[1]);return!i||!o||!(u!==!1)||!a?!1:fF(i,n,u,c)}function fF(t,e,r,n){let o={setTo:t};return e&&(o.NoAD=!0),r?(o.tiebreakFormat=r,o.tiebreakAt=n):o.noTiebreak=!0,o}function $C(t,e=!0){let r=t?.indexOf("@")>0&&t.split("@");if(r)return(e?Gm(r[1]):r[1])||!1}function KC(t){if(t)return t.startsWith("TB")?gF(t):!1}function gF(t){let e=$C(t,!1),r=/^TB(\d+)([A-Za-z]*)/.exec(t),n=r?.[1],o=r&&QC(r[2]),i=!r?.[2]||o,s=Gm(n);if(!s||!i)return!1;let a={tiebreakTo:s};return e&&typeof e=="string"&&!It(e)&&(a.modifier=e),o&&(a.NoAD=!0),a}function zC(t){let e=t.slice(1),r=/^(\d+)([PGA])?(?:\/TB(\d+))?(@?[A-Za-z]*)?/.exec(e),n=Gm(r?.[1]);if(!n)return;let o={timed:!0,minutes:n},i=r?.[2];i==="A"?o.based="A":i==="P"?o.based="P":i==="G"&&(o.based="G");let s=r?.[3];if(s){let u=Gm(s);u&&(o.tiebreakFormat={tiebreakTo:u})}let a=r?.[4],c=[void 0,"P","G",""].includes(a);if(a&&!c){let u=/^(\d+)([PGA])?(?:\/TB\d+)?(@)([A-Za-z]+)$/.exec(e)?.[4];return u?(o.modifier=u,o):void 0}return a&&(o.based=a),o}function QC(t){return t?.includes(Af)}function Gm(t){let e=Number(t);return Number.isNaN(e)?0:e}function Nr({matchUpFormat:t}){if(!kt(t)||t==="")return!1;let e=Ne(t),r=/-S:([1-9])+\/TB(\d{1,2})@?([1-9]?)/.exec(t),n=r?.[1],o=r?.[2],i=r?.[3],s=/-F:([1-9])+\/TB(\d{1,2})@?([1-9]?)/.exec(t),a=s?.[1],c=s?.[2],u=s?.[3];return gp(e,!!(r&&o&&n===i||s&&c&&a===u))===t}var Vm=/^[\d]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][\d]|3[0-1])$/,nh=/^((0[\d]|1[\d]|2[0-3]):[0-5][\d](:[0-5][\d])?)([.,][0-9]{3})?$/,Oo=/^([\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 Bm(t){let{scheduledDate:e}=t;if(!e&&t.scheduledTime&&(e=Ut(t.scheduledTime)),!e)return;let r=zt(t.scheduledTime),n=Ut(e);return n&&r&&(n+=`T${r}`),n}function XC(t){return typeof t!="object"||Array.isArray(t)?!1:Object.prototype.toString.call(t)==="[object Date]"}function Jc(t){let e=typeof t=="string"?t?.split(" "):[];return t&&e?.length>1&&!["AM","PM"].includes(e[1].toUpperCase())?!1:!!(!t||Ws.test(ac(t,!0,!0)))}function Mr(t){return sc(t)||Vm.test(t)}function IF(t){let e=new Date(t),r=e.getSeconds()+60*e.getMinutes()+3600*e.getHours();return hF(r,{displaySeconds:!1})}function hF(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(oo).join(":")}var Mf=t=>{let e=Df(t)||sc(t)?new Date(t):new Date,r=e.getUTCMonth()+1,n=r<10?`0${r}`:`${r}`;return`${e.getUTCFullYear()}-${oo(n)}-${oo(e.getUTCDate())}`};function SF(t){let e=Df(t)||sc(t)?new Date(t):new Date;return Date.UTC(e.getFullYear(),e.getMonth(),e.getDate())}function Kn(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 oh(t){let e=t?new Date(t):new Date,r=e.getTimezoneOffset();return new Date(e.getTime()-r*60*1e3)}function TF(t){return oh(t).getTime()}function Df(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 js(t,e){if(!Mr(t)||!Mr(e))return[];let r=Ut(t)+"T00:00",n=Ut(e)+"T00:00",o=new Date(r),i=new Date(n),s=Df(i)&&Df(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=>Kn(p));function u(p,m){return p<=m}}var yF=/^([+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-2])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([.,]\d+(?!:))?)?(\17[0-5]\d([.,]\d+)?)?([zZ]|([+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/;function sc(t){return typeof t!="string"?!1:yF.test(t)}function sh(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=zt(t);if(!e)return 0;let[r,n]=e.split(":").map(o=>parseInt(o));return r*60+n}function JC(t){let e=Math.floor(t/60),r=t-e*60;return e>23&&(e=e%24),[oo(e),oo(r)].join(":")}function Nf(t){return sh(t)?t.split(":").slice(0,2).map(oo).join(":"):void 0}function zt(t){return sc(t)&&t.indexOf("T")>0?Nf(t.split("T").reverse()[0]):Nf(t)}function Ut(t){return sc(t)||Oo.test(t)?t.split("T")[0]:void 0}function Ip(t,e){let r=new Date(t);return r.setDate(r.getDate()+e),Ut(r.toISOString())}function ih(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 EF(t){let e=ih(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(oo).join(":")}function AF(t){let e=ih(t);if(!(typeof e=="object"&&!Object.keys(e).length))return e.ampm?t:(e.hours>12?(e.hours-=12,e.ampm="PM"):e.hours==="12"?e.ampm="PM":(e.hours==="00"&&(e.hours="12"),e.ampm="AM"),e.hours?.[0]==="0"&&(e.hours=e.hours.slice(1)),`${e.hours||"12"}:${e.minutes||"00"} ${e.ampm}`)}function ac(t,e,r){let n=Ut(t),o=zt(t),i=n?o:t;return t?e&&(n&&r&&t||EF(i))||AF(i):void 0}function ah(t,e){let r=ih(t),n=ih(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 ch(t,e=7){let r=Ut(t)+"T00:00",n=new Date(r),o=new Date(n.setDate(n.getDate()+e));return Kn(o)}function UF(t){return ch(t)}function PF(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())),Kn(o,r)}function ZC(t,e,r){let n=new Date(t,0);return Kn(new Date(n.setDate(e)),r)}function Ge(t,e=void 0){let[r,n]=(t||"00:00").split(":").map(oo),o=oh(e).setHours(r,n,0,0);return oh(o)}function ya(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 $r(t,e){let r=zt(t);if(!r)return"00:00";let n=isNaN(e)?0:e;return zt(Rf(Ge(r),n).toISOString())}function Rf(t,e){let r=new Date(t);return new Date(r.getTime()+e*6e4)}function oo(t){return t.toString()[1]?t:"0"+t}function zn(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 uh={addDays:ch,addWeek:UF,addMinutesToTimeString:$r,convertTime:ac,getIsoDateString:Bm,getUTCdateString:Mf,DateHHMM:IF,extractDate:Ut,extractTime:zt,formatDate:Kn,getDateByWeek:PF,isISODateString:sc,isDate:Df,isTimeString:sh,offsetDate:oh,offsetTime:TF,sameDay:zn,timeStringMinutes:Yt,timeToDate:Ge,timeUTC:SF,validTimeValue:Jc,validDateString:Vm,timeValidation:Ws,dateValidation:Oo};var DF=(t,e)=>t.filter(Boolean).every(r=>typeof r===e),NF=t=>t.filter(Boolean).every(Jt);function Ys(t){let e=t.category;if(typeof e!="object")return{error:zc};let{ageCategoryCode:r,ageMaxDate:n,ageMinDate:o,ageMax:i,ageMin:s}=e,a=e.categoryName,c;if(!(DF([r,n,o,a],"string")&&NF([i,s])&&[n,o].filter(Boolean).every(Mr)))return{error:zc};let p=t.consideredDate??Ut(new Date().toLocaleDateString("sv"));if(!Mr(p))return{error:Ye};let[m]=p.split("-").slice(0,3).map(k=>parseInt(k)),d=Ip(p,-1),[l,f]=d.split("-").slice(1,3).map(k=>parseInt(k)),g=`${oo(l)}-${oo(f)}`,I=Ip(p,1),[h,S]=I.split("-").slice(1,3).map(k=>parseInt(k)),T=`${oo(h)}-${oo(S)}`,y=s&&Ip(p,-1*365*s),E=i&&Ip(p,-1*365*i),P=[],A=k=>!P.includes(k)&&P.push(k);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=(k,G)=>`${k}-${G}`,O=k=>{let G=m-k,H=b(G,T);e.ageMinDate&&e.ageMinDate!==H&&A(`Invalid submitted ageMinDate: ${o}`),o=H,r&&(e.ageMax&&e.ageMax!==k-1&&(A(`Invalid submitted ageMax: ${i}`),E=void 0),i=k-1)},v=k=>{let G=m-k-1,H=b(G,T);e.ageMin&&e.ageMin>k&&A(`Invalid submitted ageMin: ${s}`),e.ageMax&&e.ageMax>k&&A(`Invalid submitted ageMax: ${i}`),e.ageMinDate&&e.ageMinDate!==H&&A(`Invalid submitted ageMinDate: ${o}`),o=H,r&&(e.ageMax&&e.ageMax!==k&&(A(`Invalid submitted ageMax: ${i}`),y=void 0),i=k)},x=k=>{let G=m-k,H=b(G,g);e.ageMaxDate&&e.ageMaxDate!==H&&A(`Invalid submitted ageMaxDate: ${n}`),n=H,r&&(e.ageMin&&e.ageMin!==k+1&&(A(`Invalid submitted ageMin: ${s}`),y=void 0),s=k+1)},F=k=>{let G=m-k-1,H=b(G,g);e.ageMaxDate&&e.ageMaxDate!==H&&A(`Invalid submitted ageMaxDate: ${n}`),n=H,r&&(e.ageMin&&e.ageMin!==k&&(A(`Invalid submitted ageMin: ${s}`),y=void 0),s=k)},w=k=>{let[G,H,K]=(k.match(U)||[]).slice(1),Y=parseInt(H);G==="U"?(e.ageMaxDate&&e.ageMaxDate!==n&&A(`Invalid submitted ageMaxDate: ${e.ageMaxDate}`),O(Y)):G==="O"&&x(Y),K==="U"?(e.ageMaxDate&&e.ageMaxDate!==n&&A(`Invalid submitted ageMaxDate: ${e.ageMaxDate}`),v(Y)):K==="O"&&F(Y),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[k,G]=(r?.match(N)??[]).slice(1).map(H=>parseInt(H));k<=G?(s=k,i=G,c=!0):A(`Invalid combined age range ${r}`)}else D?r?.split("-").forEach(w):R?w(r):(s&&x(s),i&&v(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 Zc({category:t}){if(!ht(t))return{error:B};let e=Ys({category:t});if(e.error)return{error:e};let{ratingMax:r,ratingMin:n}=t;return r&&!Jt(r)?_({result:{error:B},context:{ratingMax:r}}):n&&!Jt(n)?_({result:{error:B},context:{ratingMin:n}}):{...e}}function tu({childCategory:t,withDetails:e,category:r}){let n=Zc({category:r}),o=Zc({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 eu({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:So},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&&!Yc([Lt,vt],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=GI({collectionValueProfiles:u,matchUpCount:l});P.errors&&c.push(...P.errors)}if(p&&typeof p!="number"&&c.push(`collectionGroupNumber is not type number: ${m}`),f&&!Nr({matchUpFormat:f})&&c.push(`Invalid matchUpFormat: ${f}`),n){let P=km({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=tu({category:o,childCategory:T});if(!P.valid)return _({result:{error:zc},context:P,stack:a})}return c.length?_({result:{errors:c,error:VA},stack:a}):{valid:!0}}function ar(t){let e=!!(t?.enforceCategory!==!1&&t?.category),r=!!(t?.enforceGender!==!1&&t?.gender),n=t?.checkCollectionIds,o=t?.tieFormat,i=t?.event,s="validateTieFormat",a=[],c=MF({...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}=eu({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:Yo},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:Yo},context:{tieFormat:o,errors:a},stack:s})}function MF(t){let{tieFormat:e,stack:r}=t;return!t||!e||!ht(e)?_({result:{error:Yo},context:{tieFormat:e,message:"tieformat must be an object"},stack:r}):ht(e.winCriteria)?Array.isArray(e.collectionDefinitions)?{...C}:_({result:{error:Yo},context:{tieFormat:e,message:"collectionDefinitions must be an array"},stack:r}):_({result:{error:Yo},context:{tieFormat:e,message:"tieformat.winCritiera must be an object"},stack:r})}var cc="resourceSubType",uc="resourceType",pc="identifier",tb={RESOURCE_SUB_TYPE:cc,RESOURCE_TYPE:uc,IDENTIFIER:pc};function J(t,e,r,n,o=0){if(rh().makeDeepCopy)return rh().makeDeepCopy(t,e,r,n);let i=Sf(),{stringify:s,toJSON:a,ignore:c,modulate:u}=i||{};if(!i?.enabled&&!r||typeof t!="object"||Yr(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)||Yr(c)&&!c(l)),d=(l,f)=>{p[l]=Yr(f?.toString)?f.toString():JSON.stringify(f)};for(let l of m){let f=t[l],g=Yr(u)?u(f):void 0;if(g!==void 0)p[l]=g;else if(e&&l==="extensions"&&Array.isArray(f)){let I=Cf(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)&&Yr(f?.toJSON)?p[l]=f.toJSON():f===null?p[l]=void 0:XC(f)?p[l]=new Date(f).toISOString():p[l]=J(f,e,r,n,o+1)}return p}function Cf(t){return t?.map(e=>{let{name:r,value:n}=e;return r&&n&&{[`_${r}`]:n}}).filter(Boolean)}function ph(t=1,e){return tt(0,t).map(()=>Nt(e))}function Nt(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 mh={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 dh={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 lh={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 fh={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 gh={collectionDefinitions:[{collectionName:"Male Singles",gender:"MALE",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{collectionName:"Female Singles",gender:"FEMALE",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{collectionName:"Male Doubles",gender:"MALE",matchUpCount: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 Ih={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 hh={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 Sh={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 Th={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 yh={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 bn="SET3-S:6/TB7",kF="SET3-S:6NOAD",eU="SET3-S:6/TB7-F:TB10",GF="SET3-S:4/TB7",VF="SET3-S:4/TB5@3",BF="SET1-S:T20",HF="SET1-S:8/TB7",WF="SET1-S:8/TB7@7",eb={FORMAT_STANDARD:bn,FORMAT_STANDARD_NOAD:kF,FORMAT_ATP_DOUBLES:eU,FORMAT_SHORT_SETS:GF,FORMAT_FAST4:VF,FORMAT_PRO_SET:HF,FORMAT_COLLEGE_PRO_SET:WF,TIMED20:BF};var Eh={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 Ah={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 Uh={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 Ph={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 Dh={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 Nh={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 Mh={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 Hm="COLLEGE_DEFAULT",Rh="COLLEGE_JUCO",Ch="COLLEGE_D3",rU="DOMINANT_DUO",nU="DOMINANT_DUO_MIXED",oU="LAVER_CUP",iU="TEAM_DOUBLES_3_AGGREGATION",sU="TIME_TENNIS_DUAL",aU="TIME_TENNIS_PRO_CIRCUIT",cU="USTA_BREWER_CUP",uU="USTA_OZAKI_CUP",pU="USTA_COLLEGE",mU="USTA_GOLD_TEAM_CHALLENGE",dU="USTA_LEVEL_1",lU="USTA_INTERSECTIONAL",fU="USTA_SECTION_BATTLE",gU="USTA_SOUTHERN_LEVEL_5",IU="USTA_TOC",hU="USTA_WTT_ITT",SU="USTA_ZONAL",rb={COLLEGE_D3:Ch,COLLEGE_DEFAULT:Hm,COLLEGE_JUCO:Rh,DOMINANT_DUO:rU,DOMINANT_DUO_MIXED:nU,LAVER_CUP:oU,TEAM_DOUBLES_3_AGGREGATION:iU,TIME_TENNIS_DUAL:sU,TIME_TENNIS_PRO_CIRCUIT:aU,USTA_BREWER_CUP:cU,USTA_OZAKI_CUP:uU,USTA_COLLEGE:pU,USTA_GOLD_TEAM_CHALLENGE:mU,USTA_INTERSECTIONAL:lU,USTA_LEVEL_1:dU,USTA_SECTION_BATTLE:fU,USTA_SOUTHERN_LEVEL_5:gU,USTA_TOC:IU,USTA_WTT_ITT:hU,USTA_ZONAL:SU};var ob="STANDARD",nb={[ob]:{hydrate:!0,doubles:{matchUpCount:3,matchUpValue:1},singles:{matchUpCount:6,matchUpValue:1},valueGoal:5},[Ch]:{hydrate:!0,doubles:{matchUpFormat:"SET1-S:8/TB7@7",matchUpCount:3,matchUpValue:1},singles:{matchUpFormat:bn,matchUpCount:6,matchUpValue:1},tieFormatName:Ch,valueGoal:5},[Hm]:{hydrate:!0,doubles:{matchUpFormat:"SET1-S:6/TB7",collectionValue:1,matchUpCount:3},singles:{matchUpFormat:bn,matchUpCount:6,matchUpValue:1},tieFormatName:Hm,valueGoal:4},[Rh]:{hydrate:!0,doubles:{matchUpFormat:"SET1-S:8/TB7",matchUpCount:3,matchUpValue:1},singles:{matchUpFormat:bn,matchUpCount:6,matchUpValue:1},tieFormatName:Rh,valueGoal:5},[oU]:Nh,[rU]:Eh,[nU]:hh,[iU]:dh,[sU]:Sh,[aU]:Ih,[cU]:Th,[uU]:yh,[pU]:Ah,[mU]:mh,[lU]:gh,[dU]:Uh,[fU]:fh,[gU]:lh,[hU]:Ph,[IU]:Mh,[SU]:Dh},XF=t=>{let e=t?.namedFormat&&Object.keys(nb).includes(t.namedFormat)?t.namedFormat:ob,r=Array.isArray(t?.uuids)?t?.uuids:[],n,{category:o,gender:i}=t?.event??{},s=J(nb[e],!1,!0),a=c=>{if(!t?.isMock&&!t?.event?.isMock||!t.event)return r?.pop()??Nt();let u=t?.event?.eventId;return r.pop()??`${u}-COL-${c+1}`};return s.hydrate?(n={winCriteria:{valueGoal:s.valueGoal},collectionDefinitions:[{collectionId:a(0),matchUpFormat:eU,collectionName:"Doubles",matchUpType:vt,...s.doubles},{collectionId:a(1),matchUpFormat:bn,collectionName:"Singles",matchUpType:Lt,...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},io=XF;var Qn="SINGLES",qs="SINGLES",Kr="DOUBLES",Ko="DOUBLES",_e="TEAM",Or="TEAM";var JF="RATING",ZF="BOTH",ib={AGE:"AGE",BOTH:ZF,DOUBLES:Kr,DOUBLES_EVENT:Ko,RATING:JF,SINGLES:Qn,SINGLES_EVENT:qs,TEAM_EVENT:Or,TEAM:_e};var rt="MAIN",ct="QUALIFYING",qe="CONSOLATION",$e="VOLUNTARY_CONSOLATION",fe="PLAY_OFF",ru=[rt,ct,qe,fe,$e],$s={[ct]:1,[rt]:2,[fe]:3,[qe]:3,[$e]:4},TU="finishingPositions",yU="aggregateEventStructures",EU={[rt]:1,[fe]:2,[qe]:3,[ct]:4,[$e]:5},sb={[fe]:1,[rt]:2,[qe]:3,[ct]:4,[$e]:5},nu="CLUSTER",ab="SEPARATE",Ti="WATERFALL",hp="ITEM",Ve="CONTAINER",fn="DRAW",Sp="RANDOM",Nn="TOP_DOWN",yi="BOTTOM_UP",Fn="POSITION",Xn="WINNER",so="LOSER",kn="FIRST_MATCHUP",Fr="AD_HOC",tk="AD_HOC",Ea="FEED_IN",ou="COMPASS",iu="OLYMPIC",ek="SINGLE_ELIMINATION";var yo="SINGLE_ELIMINATION",su="DOUBLE_ELIMINATION",au="FIRST_MATCH_LOSER_CONSOLATION",Tp="FIRST_ROUND_LOSER_CONSOLATION",Ki="LUCKY_DRAW",bf="CURTIS_CONSOLATION",cb="CURTIS_CONSOLATION",bh="FEED_IN_CHAMPIONSHIP_TO_SF",Wm="FEED_IN_CHAMPIONSHIP_TO_SF",Oh="FEED_IN_CHAMPIONSHIP_TO_QF",jm="FEED_IN_CHAMPIONSHIP_TO_QF",vh="FEED_IN_CHAMPIONSHIP_TO_R16",Ym="FEED_IN_CHAMPIONSHIP_TO_R16",AU="MODIFIED_FEED_IN_CHAMPIONSHIP",qm="MODIFIED_FEED_IN_CHAMPIONSHIP",yp="FEED_IN_CHAMPIONSHIP",ub="DOUBLE_ROUND_ROBIN",On="ROUND_ROBIN",Eo="ROUND_ROBIN_WITH_PLAYOFF",UU="DECIDER",PU="BACKDRAW",Of={0:{name:"East",abbreviation:"E"},"0-1":{name:"West",abbreviation:"W"},"0-2":{name:"North",abbreviation:"N"},"0-3":{name:"Northeast",abbreviation:"NE"},"0-1-1":{name:"South",abbreviation:"S"},"0-1-2":{name:"Southwest",abbreviation:"SW"},"0-2-1":{name:"Northwest",abbreviation:"NW"},"0-1-1-1":{name:"Southeast",abbreviation:"SE"}},vf={0:{name:"East",abbreviation:"E"},"0-1":{name:"West",abbreviation:"W"},"0-2":{name:"North",abbreviation:"N"},"0-1-1":{name:"South",abbreviation:"S"}},Ei="WIN_RATIO",zi="ROUND_OUTCOME",DU=[ou,bf,jm,Ym,Wm,yp,Oh,vh,bh,au,Tp,Ki,qm,iu,fe,Eo],rk=[Fr,ou,bf,su,jm,Ym,Wm,yp,Ea,au,Tp,Ki,qm,iu,fe,On,Eo,yo],NU={MAIN:rt,QUALIFYING:ct,CONSOLATION:qe,ITEM:hp,CONTAINER:Ve,FIRST_MATCHUP:kn,WINNER:Xn,LOSER:so,AD_HOC:Fr,FEED_IN:Ea,FLEX_ROUNDS:tk,COMPASS:ou,PLAY_OFF:fe,OLYMPIC:iu,KNOCKOUT:ek,SINGLE_ELIMINATION:yo,DOUBLE_ELIMINATION:su,CURTIS:bf,FICSF:bh,FICQF:Oh,FICR16:vh,MFIC:AU,VOLUNTARY_CONSOLATION:$e,FIRST_MATCH_LOSER_CONSOLATION:au,FIRST_ROUND_LOSER_CONSOLATION:Tp,MODIFIED_FEED_IN_CHAMPIONSHIP:qm,FEED_IN_CHAMPIONSHIP_TO_R16:Ym,FEED_IN_CHAMPIONSHIP_TO_QF:jm,FEED_IN_CHAMPIONSHIP_TO_SF:Wm,FEED_IN_CHAMPIONSHIP:yp,LUCKY_DRAW:Ki,ROUND_ROBIN_WITH_PLAYOFF:Eo,ROUND_ROBIN:On,DECIDER:UU,BACKDRAW:PU,COMPASS_ATTRIBUTES:Of,OLYMPIC_ATTRIBUTES:vf,DRAW:fn,RANDOM:Sp,TOP_DOWN:Nn,BOTTOM_UP:yi,WATERFALL:Ti,WIN_RATIO:Ei,ROUND_OUTCOME:zi,MULTI_STRUCTURE_DRAWS:DU,generatedDrawTypes:rk,stageOrder:$s,finishOrder:EU,AGGREGATE_EVENT_STRUCTURES:yU,FINISHING_POSITIONS:TU},pb=NU;var Re="tournamentRecords",_f="policyDefinitions",ne="tournamentRecord",_h="onlineResource",Ce="drawDefinition",xh="tieFormatName",$m="matchUpFormat",ao="participantId",wh="scheduleDates",mb="tournamentId",db="scheduleDate",lb="roundNumber",cu="structureId",xf="participant",mc="matchUpIds",Lh="entryStage",fb="policyType",MU="structures",wf="eventType",gn="matchUpId",Km="tieFormat",uu="inContext",Ep="structure",Ap="courtIds",gb="personId",Up="venueIds",Lf="matchUps",Fh="courtId",kh="eventId",Gn="matchUp",Gh="drawId",In="error",co="event",ds="param",Ff="uuids",Ib="averageMatchUpMinutes",hb="recoveryMinutes",Sb="periodLength",Tb="number";var zr="object",Be="array";var tr="_validate",Vh="_message",kr="_invalid",He="_ofType",zm="_anyOf",Ks="_oneOf";var yb={[_h]:t=>jt(Object.keys(t),[cc,uc,pc]).length===3,[xh]:t=>t&&io({namedFormat:t}),[Ff]:t=>!t||Array.isArray(t)&&t.every(kt),[Km]:t=>!ar({tieFormat:t}).error,[wf]:t=>[Qn,Kr,_e].includes(t),[Lh]:t=>ru.includes(t)},nk={[Re]:xt,[ne]:q,[_f]:op,[Ce]:Z,[ao]:se,[$m]:Zl,[mb]:ha,[cu]:Pr,[mc]:ps,[xf]:Wi,[_h]:So,[wf]:$n,[MU]:Kl,[gn]:sr,[Km]:Yo,[Ep]:Si,[Fh]:Bi,[Lf]:no,[kh]:qr,[Gn]:mr,[Ap]:st,[Up]:st,[Gh]:cn,[co]:Ot},ok={[Re]:zr,[_f]:zr,[ne]:zr,[Ce]:zr,[_h]:zr,[wh]:Be,[xf]:zr,[mc]:Be,[MU]:Be,[Km]:zr,[Ep]:zr,[Ap]:Be,[Up]:Be,[Lf]:Be,[Gn]:zr,[co]:zr,[Ff]:Be};function et(t,e,r){if(!t&&!ht(t))return{error:B};if(!e?.length||t?._bypassParamCheck)return{valid:!0};if(!Array.isArray(e))return{error:B};let{paramError:n,errorParam:o}=ak(t,e);if(!n)return{valid:!0};let i=n[tr]&&(n[In]||n[kr])||t?.[o]===void 0&&(n[In]||n[kr]||nk[o]||B)||B,s=o??(n[Ks]&&Object.keys(n[Ks]).join(", "));return _({info:{param:s,message:n[Vh]},result:{error:i},stack:r})}function Eb(t,e){let r=Object.keys(t),n=Object.keys(e);return jt(r,n)}function ik(t,e){if(!e)return;let r=Eb(t,e);return r.length!==1?{error:B}:r.reduce((n,o)=>({...n,[o]:!0}),{})}function sk(t,e){if(!e)return;let r=Eb(t,e).filter(n=>t[n]);return r.length<1?{error:B}:r.reduce((n,o)=>({...n,[o]:!0}),{})}function ak(t,e){let r,n;return{paramError:e.find(({_ofType:i,_oneOf:s,_anyOf:a,_validate:c,_info:u,...p})=>{let m=s&&ik(t,s);if(m?.error)return m.error;m&&Object.assign(p,m);let d=a&&sk(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&&!Yr(c),h=t[g]!==void 0&&!c&&ck(t,g,i),S=p[g]&&[void 0,null].includes(t[g]),y=I||h||S||c&&t[g]!==void 0&&!uk(t[g],c)||yb[g]&&!yb[g](t[g]);return y&&(r=g,n=u),y});return!l.length||f}),errorParam:r,paramInfo:n}}function ck(t,e,r){return r=r||ok[e]||"string",r==="array"?!Array.isArray(t[e]):typeof t[e]!==r}function uk(t,e){return Yr(e)?e(t):!0}var Qm="DYNAMIC",Ai="RANKING",Ui="RATING",Pi="SCALE",Ao="SEEDING",Ab={RANKING:Ai,RATING:Ui,SCALE:Pi,SEEDING:Ao};function Aa(t){let e=et(t,[{[xf]:!0}]);if(e.error)return e;let r=t.participant.timeItems?.filter(({itemType:o})=>o?.startsWith(Pi)&&[Ai,Ui,Ao].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===Ao&&"seedings"||c===Ai&&"rankings"||"ratings";n[l][u]||(n[l][u]=[]),n[l][u].push({scaleValue:a.itemValue,scaleDate:a.itemDate,scaleName:d})}}}return{...C,...n}}function Qi(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 Bh="voluntaryConsolation",Di="competitiveBands",kf="roundRobinTally",Jn="positionActions",er="matchUpActions",Gf="rankingPoints",vo="roundNaming",zs="participant",pu="progression",_o="scheduling",mu="avoidance",pk="participant",mk="display",rn="scoring",Vn="seeding",dc="feedIn",dk="audit",Xm="draws",Ub={POLICY_TYPE_VOLUNTARY_CONSOLATION:Bh,POLICY_TYPE_COMPETITIVE_BANDS:Di,POLICY_TYPE_ROUND_ROBIN_TALLY:kf,POLICY_TYPE_POSITION_ACTIONS:Jn,POLICY_TYPE_MATCHUP_ACTIONS:er,POLICY_TYPE_RANKING_POINTS:Gf,POLICY_TYPE_ROUND_NAMING:vo,POLICY_TYPE_PARTICIPANT:zs,POLICY_TYPE_PROGRESSION:pu,POLICY_TYPE_SCHEDULING:_o,POLICY_TYPE_AVOIDANCE:mu,POLICY_TYPE_DISPLAY:mk,POLICY_TYPE_PRIVACY:pk,POLICY_TYPE_FEED_IN:dc,POLICY_TYPE_SCORING:rn,POLICY_TYPE_SEEDING:Vn,POLICY_TYPE_AUDIT:dk,POLICY_TYPE_DRAWS:Xm};function zo({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?.[zs];if(r?.withScaleValues){let{ratings:u,rankings:p}=Aa({participant:a});a.rankings=p,a.ratings=u}if(c?.participant)return Qi({template:c.participant,source:a})}return a}var Pb="element required",Db="missing name";function Ir(t){if(!t||typeof t!="object")return{error:st};if(t.element&&typeof t?.element!="object")return{error:B};if(!t?.name)return{error:st,info:Db};if(!t?.element){if(t.discover&&t.tournamentRecords){for(let e of Object.keys(t.tournamentRecords)){let r=t.tournamentRecords[e],n=Ir({element:r,name:t.name});if(n.error)return _({result:n,stack:"removeExtension"})}return{...C}}return{error:st,info:Pb}}return t?.element.extensions?(t.element.extensions=t.element.extensions.filter(e=>e?.name!==t.name),{...C}):{...C,info:Oe}}function Bn({requiredAttributes:t=["name","value"],extension:e}){if(!e||typeof e!="object"||typeof e.name!="string")return!1;let r=Object.keys(e);return t.filter(n=>r.includes(n)).length===t.length}function At(t){if(typeof t!="object")return{error:st};let e="addExtension";if(t?.element&&typeof t.element!="object")return _({result:{error:B},stack:e});if(!Bn({extension:t.extension}))return _({result:{error:B,info:"invalid extension"},stack:e});if(!t.element)if(t.discover&&!t.tournamentId&&t.tournamentRecords){for(let o of Object.values(t.tournamentRecords)){let i=At({extension:t.extension,element:o});if(i.error)return _({result:i,stack:e})}return{...C}}else return _({result:{error:st},stack:e});if(t.element.extensions||(t.element.extensions=[]),t?.creationTime??!0){let o=new Date().toISOString();Object.assign(t.extension,{createdAt:o})}let n=t.element.extensions.find(({name:o})=>o===t.extension.name);return n?n.value=t.extension.value:t.extension.value&&t.element.extensions.push(t.extension),{...C}}function Vf(t){return!t||typeof t!="object"?{error:st}:t.tournamentRecord?At({creationTime:t.creationTime,element:t.tournamentRecord,extension:t.extension}):{error:q}}function Pp(t){return!t||typeof t!="object"?{error:st}:t.drawDefinition?At({creationTime:t.creationTime,element:t.drawDefinition,extension:t.extension}):{error:br}}function xo(t){return!t||typeof t!="object"?{error:st}:t.event?At({creationTime:t.creationTime,extension:t.extension,element:t.event}):{error:qr}}function RU(t){if(!t||typeof t!="object")return{error:st};if(!t.participantId)return{error:se};let e=t.tournamentRecord?.participants||[],r=zo({participantId:t.participantId,tournamentParticipants:e});return r?At({creationTime:t.creationTime,extension:t.extension,element:r}):{error:re}}function Bf(t){return!t||typeof t!="object"?{error:st}:t.tournamentRecord?Ir({element:t.tournamentRecord,name:t.name}):{error:q}}function CU(t){return!t||typeof t!="object"?{error:st}:t.drawDefinition?Ir({element:t.drawDefinition,name:t.name}):{error:br}}function Dp(t){return!t||typeof t!="object"?{error:st}:t?.event?Ir({element:t.event,name:t.name}):{error:qr}}function bU(t){if(!t||typeof t!="object")return{error:st};if(!t.participantId)return{error:se};let e=t.tournamentRecord?.participants||[],r=zo({participantId:t.participantId,tournamentParticipants:e});return r?Ir({element:r,name:t.name}):{error:re}}function Np({tournamentRecords:t}){return{tournamentIds:ht(t)?Object.keys(t):[],...C}}var lk="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:Oe}}return _({result:{error:st},stack:lk})}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:Oe}}var fk="activeSuspension",du="appliedPolicies",OU="context",Jm="delegatedOutcome",uo="disabled",Ua="disableAutoCalc",Zm="disableLinks",td="display",Pa="drawDeletions",gk="drawProfile",ed="entryProfile",Ik="eventProfile",hk="eventWithdrawalRequests",Sk="factory",pn="flightProfile",Hh="groupingAttribute",wo="lineUps",Qs="linkedTournamentsIds",rd="matchUpHistory",Wh="participantRepresentatives",Da="personRequests",lc="positionActions",Tk="rankingPoints",yk="registration",vn="roundTarget",lu="scheduleLimits",Qo="scheduleTiming",Na="schedulingProfile",Ek="statusDetail",fc="subOrder",Lo="tally",nd="tieFormatModification",jh={ACTIVE_SUSPENSION:fk,APPLIED_POLICIES:du,CONTEXT:OU,DELEGATED_OUTCOME:Jm,DISABLED:uo,DISABLE_LINKS:Zm,DISABLE_AUTO_CALC:Ua,DISPLAY:td,DRAW_DELETIONS:Pa,DRAW_PROFILE:gk,ENTRY_PROFILE:ed,EVENT_PROFILE:Ik,EVENT_WITHDRAWAL_REQUESTS:hk,FLIGHT_PROFILE:pn,GROUPING_ATTRIBUTE:Hh,LINEUPS:wo,LINKED_TOURNAMENTS:Qs,MATCHUP_HISTORY:rd,PARTICIPANT_REPRESENTATIVES:Wh,PERSON_REQUESTS:Da,POSITION_ACTIONS:lc,RANKING_POINTS:Tk,REGISTRATION:yk,ROUND_TARGET:vn,SCHEDULE_LIMITS:lu,SCHEDULE_TIMING:Qo,SCHEDULING_PROFILE:Na,STATUS_DETAIL:Ek,SUB_ORDER:fc,TALLY:Lo,TIE_FORMAT_MODIFICATIONS:nd,FACTORY:Sk},vU=[Jm,uo,Ua,Zm,pn,wo,Qs,rd,Wh,Da,vn,lu,Qo,Na,fc,Lo,nd];function _U({tournamentRecords:t}){if(typeof t!="object"||!Object.keys(t).length)return{error:xt};let e=Np({tournamentRecords:t}),{tournamentIds:r}=e;return r?.length>1?At({tournamentRecords:t,discover:!0,extension:{name:Qs,value:{tournamentIds:r}}}):{...C}}function xU({tournamentRecords:t}){if(typeof t!="object"||!Object.keys(t).length)return{error:xt};let e=Ir({name:Qs,tournamentRecords:t,discover:!0});return _({result:e,stack:"unlinkTournaments"})}function wU({tournamentRecords:t,tournamentId:e}){if(typeof t!="object")return{error:B};if(!e)return{error:ha};let r=Np({tournamentRecords:t}),{tournamentIds:n}=r;if(!n.includes(e))return{error:ha};let o;return n.every(i=>{let s=t[i],{extension:a}=mt({element:s,name:Qs});if(!a)return!0;let c=a?.value?.tournamentIds||[];if(!c?.length||c.length===1&&c.includes(e)||i===e){let m=Bf({name:Qs,tournamentRecord:s});return m.error&&(o=m.error),m.success}let u=c.filter(m=>m!==e);a.value={tournamentIds:u};let p=Vf({tournamentRecord:s,extension:a});return p.error&&(o=p.error),p.success}),o?{error:o}:{...C}}var FU={};Xt(FU,{getLinkedTournamentIds:()=>fu,getTournamentIds:()=>Np});function fu({tournamentRecords:t}){return typeof t!="object"||!Object.keys(t).length?{error:xt}:{linkedTournamentIds:Object.assign({},...Object.keys(t).map(r=>{let n=t[r],o=n?.tournamentId,{extension:i}=mt({element:n,name:Qs}),s=(i?.value?.tournamentIds||[]).filter(a=>a!==o);return{[r]:s}}))}}var GN={};Xt(GN,{adHocPositionSwap:()=>zP,addAdHocMatchUps:()=>Gd,addDrawDefinitionTimeItem:()=>Og,addFinishingRounds:()=>ba,addGoesTo:()=>rs,addPlayoffStructures:()=>Kp,addQualifyingStructure:()=>KP,addVoluntaryConsolationStage:()=>HP,addVoluntaryConsolationStructure:()=>Eg,allPlayoffPositionsFilled:()=>WS,alternateDrawPositionAssignment:()=>bP,assignDrawPosition:()=>uD,assignDrawPositionBye:()=>Wr,attachConsolationStructures:()=>iD,attachPlayoffStructures:()=>Vg,attachQualifyingStructure:()=>bg,attachStructures:()=>Bg,autoSeeding:()=>ux,automatedPlayoffPositioning:()=>na,automatedPositioning:()=>Mc,checkValidEntries:()=>Hd,deleteAdHocMatchUps:()=>pD,drawMatic:()=>tl,findDrawDefinition:()=>gT,generateAdHocMatchUps:()=>Wu,generateAdHocRounds:()=>Zd,generateAndPopulatePlayoffStructures:()=>kd,generateDrawDefinition:()=>Wa,generateDrawMaticRound:()=>qd,generateDrawStructuresAndLinks:()=>Wd,generateDrawTypeAndModifyDrawDefinition:()=>jd,generateQualifyingStructure:()=>_d,generateVoluntaryConsolation:()=>LT,getAssignedParticipantIds:()=>wi,getAvailableMatchUpsCount:()=>Vd,getAvailablePlayoffProfiles:()=>Lu,getDrawDefinitionTimeItem:()=>iS,getDrawParticipantRepresentativeIds:()=>lT,getDrawStructures:()=>hn,getDrawTypeCoercion:()=>Bu,getEligibleVoluntaryConsolationParticipants:()=>dT,getMatchUpsMap:()=>Pe,getParticipantIdFinishingPositions:()=>fT,getPositionAssignments:()=>zp,getPositionsPlayedOff:()=>Cc,getRandomQualifierList:()=>RT,getSeedingThresholds:()=>_S,getSeedsCount:()=>Hu,getStructureSeedAssignments:()=>sn,getTeamLineUp:()=>Ss,getValidGroupSizes:()=>Gp,isAdHoc:()=>cr,isCompletedStructure:()=>Do,isValidForQualifying:()=>CT,luckyLoserDrawPositionAssignment:()=>NP,modifyDrawDefinition:()=>sD,modifyDrawName:()=>Hg,modifySeedAssignment:()=>FP,mutate:()=>lD,positionActions:()=>MT,pruneDrawDefinition:()=>cD,qualifierDrawPositionAssignment:()=>Cg,qualifierProgression:()=>kP,query:()=>PD,removeDrawPositionAssignment:()=>Ou,removeRoundMatchUps:()=>mD,removeSeededParticipant:()=>$P,removeStructure:()=>BP,renameStructures:()=>VP,resetDrawDefinition:()=>aD,resetQualifyingStructure:()=>WP,resetVoluntaryConsolationStructure:()=>KU,setDrawParticipantRepresentativeIds:()=>VU,setPositionAssignments:()=>RP,setStructureOrder:()=>GP,setSubOrder:()=>dD,shiftAdHocRounds:()=>MP,swapAdHocRounds:()=>CP,swapDrawPositionAssignments:()=>qP,updateTeamLineUp:()=>os,withdrawParticipantAtDrawPosition:()=>PP});var lD={};Xt(lD,{adHocPositionSwap:()=>zP,addAdHocMatchUps:()=>Gd,addDrawDefinitionTimeItem:()=>Og,addPlayoffStructures:()=>Kp,addQualifyingStructure:()=>KP,addVoluntaryConsolationStage:()=>HP,addVoluntaryConsolationStructure:()=>Eg,alternateDrawPositionAssignment:()=>bP,assignDrawPosition:()=>uD,assignDrawPositionBye:()=>Wr,attachConsolationStructures:()=>iD,attachPlayoffStructures:()=>Vg,attachQualifyingStructure:()=>bg,attachStructures:()=>Bg,automatedPlayoffPositioning:()=>na,automatedPositioning:()=>Mc,deleteAdHocMatchUps:()=>pD,luckyLoserDrawPositionAssignment:()=>NP,modifyDrawDefinition:()=>sD,modifyDrawName:()=>Hg,modifySeedAssignment:()=>FP,pruneDrawDefinition:()=>cD,qualifierDrawPositionAssignment:()=>Cg,qualifierProgression:()=>kP,removeDrawPositionAssignment:()=>Ou,removeRoundMatchUps:()=>mD,removeSeededParticipant:()=>$P,removeStructure:()=>BP,renameStructures:()=>VP,resetDrawDefinition:()=>aD,resetQualifyingStructure:()=>WP,resetVoluntaryConsolationStructure:()=>KU,setDrawParticipantRepresentativeIds:()=>VU,setPositionAssignments:()=>RP,setStructureOrder:()=>GP,setSubOrder:()=>dD,shiftAdHocRounds:()=>MP,swapAdHocRounds:()=>CP,swapDrawPositionAssignments:()=>qP,updateTeamLineUp:()=>os,withdrawParticipantAtDrawPosition:()=>PP});var GU=t=>e=>t[e],od=(t=[])=>t.map(Ue).filter(Boolean),Hf=(t=[])=>t.map(St).filter(Boolean),St=(t={})=>GU(t)("participantId");var Ue=(t={})=>GU(t)("matchUpId"),gu=(t={})=>GU(t)("drawId");function VU({representativeParticipantIds:t,drawDefinition:e}){if(!e)return{error:br};if(!Array.isArray(t))return{error:B};let r=Hf(e?.entries||[]);return t.length&&jt(t,r).length<t.length?{error:B}:Pp({drawDefinition:e,extension:{name:Wh,value:t}})}var vr="ABANDONED",gc="AWAITING_RESULT";var po="CANCELLED",ge="COMPLETED",Iu="DEAD_RUBBER",Gt="DEFAULTED",be="DOUBLE_DEFAULT",oe="DOUBLE_WALKOVER",Hn="IN_PROGRESS",mn="INCOMPLETE",BU="NOT_PLAYED",Me="RETIRED",ls="SUSPENDED",Qt="TO_BE_PLAYED",Bt="WALKOVER",Nb=[gc,ge,Gt,Hn,mn,Me,ls],Yh=[gc,ge,Gt,oe,be,Hn,mn,Me,ls,Bt],qh=[vr,gc,"BYE",po,ge,Iu,Gt,oe,be,Hn,mn,BU,Me,ls,Qt,Bt],$h=["BYE",oe,be,ge,Gt,Me,Bt],Kh=[vr,gc,po,Iu,Hn,mn,BU,ls,Qt,void 0],ae=[po,vr,ge,Iu,Gt,oe,be,Me,Bt],id=[vr,ge,Gt,oe,be,Hn,Me,Bt],zh=[Hn,mn,ls,Qt],Qh={ABANDONED:vr,AWAITING_RESULT:gc,BYE:"BYE",CANCELLED:po,COMPLETED:ge,DEAD_RUBBER:Iu,DEFAULTED:Gt,DOUBLE_WALKOVER:oe,DOUBLE_DEFAULT:be,IN_PROGRESS:Hn,INCOMPLETE:mn,NOT_PLAYED:BU,RETIRED:Me,SUSPENDED:ls,TO_BE_PLAYED:Qt,WALKOVER:Bt};function Ni(t,e,r){let n=m=>mt({element:m,name:vn})?.extension?.value,o=r?.deprioritizeCompleted,i=r?.mode===yU&&sb,s=r?.mode===TU&&EU,a=s||i||$s,c=m=>m?.stage===rt&&m?.stageSequence===1,u=m=>c(m)?-1:a[m?.stage],p=m=>m?.matchUps.every(({matchUpStatus:d})=>ae.includes(d)?1:-1);return o&&p(t)-p(e)||i&&u(t)-u(e)||(t?.stage&&a[t.stage]||0)-(e?.stage&&a[e.stage]||0)||(n(t)||0)-(n(e)||0)||!s&&!i&&(e?.positionAssignments?.length??1/0)-(t?.positionAssignments?.length??1/0)||(t?.stageSequence??0)-(e?.stageSequence??0)||(Wf(t)||0)-(Wf(e)||0)}function Wf(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,[cu]:!0}]);if(e.error)return e;let{drawDefinition:r,structureId:n}=t,{structures:o}=hn({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:_t};let a=s.structureType===hp?i?.find(c=>c.structures?.some(u=>u.structureId===n)):void 0;return{structure:s,containingStructure:a}}function hn({withStageGrouping:t,drawDefinition:e,stageSequences:r,stageSequence:n,roundTarget:o,sortConfig:i,stages:s,stage:a}){let c=!e&&Z||!e?.structures&&Kl||void 0;if(c)return{error:c,structures:[],stageStructures:{}};let u=f=>{let g=mt({element:f,name:vn})?.extension?.value;return!o||o===g},p=e?.structures?.filter(d).filter(l).filter(u).sort((f,g)=>Ni(f,g,i))??[],m=t?Object.assign({},...ru.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 Xh({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=sA,{positionAssignments:o,error:n}}function Ie({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 jf="addDrawDefinition",Mp="addMatchUps",ci="addParticipants",Yf="addScaleItems",HU="addEvent",Jh="addVenue",Mi="audit",Zh="dataIssue",qf="deleteParticipants",$f="deleteVenue",Kf="deletedDrawIds",zf="deletedMatchUpIds",Qf="modifyDrawDefinition",WU="modifyDrawEntries",jU="modifyEventEntries",Xf="modifyMatchUp",rr="modifyParticipants",Jf="modifyPositionAssignments",Zf="modifySeedAssignments",Xi="modifyTournamentDetail",Ri="modifyVenue",sd="mutations",tS="publishEvent",YU="publishEventSeeding",qU="publishOrderOfPlay",$U="publishParticipants",tg="unPublishEvent",eg="unPublishEventSeeding",rg="unPublishOrderOfPlay",Mb="unPublishParticipants",Rp="updateInContextMatchUp",Rb={ADD_DRAW_DEFINITION:jf,ADD_MATCHUPS:Mp,ADD_PARTICIPANTS:ci,ADD_SCALE_ITEMS:Yf,ADD_EVENT:HU,ADD_VENUE:Jh,AUDIT:Mi,DATA_ISSUE:Zh,DELETE_PARTICIPANTS:qf,DELETE_VENUE:$f,DELETED_DRAW_IDS:Kf,DELETED_MATCHUP_IDS:zf,MODIFY_DRAW_DEFINITION:Qf,MODIFY_DRAW_ENTRIES:WU,MODIFY_EVENT_ENTRIES:jU,MODIFY_MATCHUP:Xf,MODIFY_PARTICIPANTS:rr,MODIFY_POSITION_ASSIGNMENTS:Jf,MODIFY_SEED_ASSIGNMENTS:Zf,MODIFY_TOURNAMENT_DETAIL:Xi,MODIFY_VENUE:Ri,MUTATIONS:sd,PUBLISH_EVENT_SEEDING:YU,PUBLISH_EVENT:tS,PUBLISH_ORDER_OF_PLAY:qU,PUBLISH_PARTICIPANTS:$U,UNPUBLISH_EVENT_SEEDING:eg,UNPUBLISH_EVENT:tg,UNPUBLISH_ORDER_OF_PLAY:rg,UPDATE_INCONTEXT_MATCHUP:Rp};function eS(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 Fo({drawDefinition:t,tournamentId:e,matchUps:r,eventId:n}){return t&&eS(t),lt({payload:{matchUps:r,tournamentId:e,eventId:n},topic:Mp}),{...C}}function _n({drawDefinition:t,tournamentId:e,matchUpIds:r,eventId:n,action:o}){t&&eS(t),lt({topic:zf,payload:{tournamentId:e,matchUpIds:r,eventId:n,action:o}});for(let i of r)eh({key:i});return{...C}}function gt({drawDefinition:t,tournamentId:e,structureId:r,context:n,eventId:o,matchUp:i}){return i?(t&&bt({drawDefinition:t,structureIds:r?[r]:void 0,tournamentId:e,eventId:o}),lt({topic:Xf,payload:{matchUp:i,tournamentId:e,context:n},key:i.matchUpId}),{...C}):(console.log(mr),{error:mr})}function Cb({tournamentId:t,inContextMatchUp:e}){return e?(lt({payload:{inContextMatchUp:e,tournamentId:t},topic:Rp,key:e.matchUpId}),{...C}):{error:mr}}function Ma({tournamentId:t,eventId:e,drawDefinition:r}){return r?(eS(r),lt({payload:{drawDefinition:r,tournamentId:t,eventId:e},topic:jf,key:r.drawId}),{...C}):(console.log(Z),{error:Z})}function bb({tournamentId:t,eventId:e,drawId:r}){return lt({payload:{drawId:r,tournamentId:t,eventId:e},topic:Kf,key:r}),eh({key:r}),{...C}}function bt({drawDefinition:t,tournamentId:e,structureIds:r,eventId:n}){return t?(eS(t,r),lt({payload:{tournamentId:e,eventId:n,drawDefinition:t},topic:Qf,key:t.drawId}),{...C}):{error:Z}}function rS({drawDefinition:t,tournamentId:e,structure:r,eventId:n}){if(!t)return{error:Z};if(!r)return{error:Si};let o=r.seedAssignments,i=r.structureId,s=t.drawId;return lt({payload:{tournamentId:e,eventId:n,drawId:s,structureId:i,seedAssignments:o},topic:Zf,key:t.drawId}),bt({structureIds:[i],drawDefinition:t,tournamentId:e,eventId:n}),{...C}}function ko({drawDefinition:t,tournamentId:e,structure:r,event:n}){if(!t)return{error:Z};if(!r)return{error:Si};let o=Ct({structure:r}),i=r.structureId,s=t.drawId,a=n?.eventId;return lt({topic:Jf,payload:{positionAssignments:o,tournamentId:e,structureId:i,eventId:a,drawId:s},key:i}),bt({structureIds:[i],drawDefinition:t,tournamentId:e,eventId:a}),{...C}}function KU({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:_t};let i=o.matchUps?.map(({matchUpId:s})=>s)||[];return o.positionAssignments=[],o.seedAssignments=[],o.matchUps=[],_n({tournamentId:t?.tournamentId,action:"resetVoluntaryConsolationStructure",matchUpIds:i,drawDefinition:e}),r&&(e.entries=e.entries.filter(s=>s.entryStage!==$e)),bt({tournamentId:t?.tournamentId,eventId:n?.eventId,drawDefinition:e,structureIds:[o.structureId]}),{...C}}function ad({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=>{At({element:o,extension:{name:Zm,value:!0}})})}function hu(t){let{appliedPolicies:e,positionAction:r,drawDefinition:n}=t;if(e?.audit?.[lc]===!1)return;let{extension:o}=mt({name:lc,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:lc};At({element:n,extension:s})}function fs({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 Su(t){let{sides:e,matchUpType:r}=t||{},n=t.potentialParticipants?.length?t.potentialParticipants.flat().map(s=>r===vt?s?.individualParticipantIds||[]:s.participantId).flat():[],o=(e||[]).map(s=>r===vt&&(s?.participant?.individualParticipantIds||[])||s?.participantId&&[s.participantId]||[]).flat();return{individualParticipantIds:o.concat(n).flat(),enteredIndividualParticipantIds:o,potentialIndividualParticipantIds:n}}function Rr(t){return t?.tournamentRecords??(t?.tournamentRecord&&{[t.tournamentRecord.tournamentId]:t.tournamentRecord})??{}}var Ic="SIGN_IN_STATUS",zU="SIGNED_OUT",Tu="SIGNED_IN",Ar="TEAM",Et="INDIVIDUAL",Qr="GROUP",ft="PAIR",wt="TEAM",yu={TEAM_PARTICIPANT:Ar,INDIVIDUAL:Et,GROUP:Qr,TEAM:wt,PAIR:ft},Ob={INDIVIDUAL:Et,GROUP:Qr,PAIR:ft,TEAM:wt,SIGN_IN_STATUS:Ic,SIGNED_OUT:zU,SIGNED_IN:Tu};function Eu({participantsProfile:t,participants:e=[],deepCopy:r}){let n=new Map,o=r!==!1?J(e,t?.convertExtensions,!0):e,i=o.filter(c=>c.participantType===wt),s=o.filter(c=>c.participantType===Qr),a=o.filter(c=>c.participantType===ft);return o.forEach(c=>{if(c.participantType===Et){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 QU(t){return t&&typeof String.fromCodePoint<"u"?t.toUpperCase().replace(/./g,e=>String.fromCodePoint(e.charCodeAt(0)+127397)):t}function vb(t){let e=Object.assign({},...ui.filter(r=>r.ioc).map(r=>({[r.ioc]:r.iso})));return QU(e[t])}var ui=[{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 nS({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=ui.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 _b({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?Qi({template:e,source:s}):s)}}}}function Uo(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 oS(t){let{tournamentRecord:e,participantId:r}=t;if(r){let o=Uo({tournamentRecord:e,participantId:r});return o.participant??o}let n=t.element||t.drawDefinition||t.event||t.tournamentRecord;return n||{error:st}}function nn(t){let{returnPreviousValues:e,itemSubTypes:r,itemType:n}=t,o=oS(t);if(o.error)return o;if(r&&!Array.isArray(r))return{error:B,context:{itemSubTypes:r}};if(!Array.isArray(o.timeItems))return{error:df};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:Oe}}function iS({returnPreviousValues:t,drawDefinition:e,itemSubTypes:r,itemType:n}){if(!e)return{error:cn};if(!e.timeItems)return{info:Oe};let{timeItem:o,previousItems:i,info:s}=nn({element:e,returnPreviousValues:t,itemSubTypes:r,itemType:n});return o&&{timeItem:o,previousItems:i}||{info:s}}function Au({returnPreviousValues:t,itemSubTypes:e,itemType:r,event:n}){if(!n)return{error:Ot};if(!n.timeItems)return{info:Oe};let{timeItem:o,previousItems:i,info:s}=nn({returnPreviousValues:t,element:n,itemSubTypes:e,itemType:r});return o&&{timeItem:o,previousItems:i}||{info:s}}function cd({returnPreviousValues:t,tournamentRecord:e,itemSubTypes:r,itemType:n}){if(!e)return{error:q};if(!e.timeItems)return{info:Oe};let{timeItem:o,previousItems:i,info:s}=nn({element:e,returnPreviousValues:t,itemSubTypes:r,itemType:n});return o&&{timeItem:o,previousItems:i}||{info:s}}function sS({returnPreviousValues:t,tournamentRecord:e,participantId:r,itemSubTypes:n,itemType:o}){if(!e)return{error:q};if(!r)return{error:se};let i=Uo({tournamentRecord:e,participantId:r});if(i.error)return i;let{participant:s}=i;if(!s?.timeItems)return{info:Oe};let{timeItem:a,previousItems:c,info:u}=nn({element:i.participant,returnPreviousValues:t,itemSubTypes:n,itemType:o});return a&&{timeItem:a,previousItems:c}||{info:u}}var Ak={[Qr]:"groupParticipantIds",[ft]:"pairParticipantIds",[wt]:"teamParticipantIds"},Uk={[Qr]:"groups",[wt]:"teams"};function aS({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&&Nk({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=Dk({individualParticipantIds:g,participantCopy:l,participantMap:p,participantType:I,participantId:f});h.missingParticipantIds.length&&u.push(...h.missingParticipantIds)}if(n&&(p[f].participant.signedIn=Pk(l)),o){let{ratings:h,rankings:S,seedings:T}=Aa({participant:l});p[f].participant.seedings=T,p[f].participant.rankings=S,p[f].participant.ratings=h}(c||a)&&nS({participant:p[f].participant,withISO2:a,withIOC:c})}if(t){let d=ht(t)?t:void 0;_b({participantMap:p,template:d})}let m;return i&&(m=Eu({participants:Object.values(p).map(({participant:d})=>d),participantsProfile:{convertExtensions:e},deepCopy:!1}).groupInfo),{missingParticipantIds:u,participantMap:p,groupInfo:m}}function Pk(t){let{timeItem:e}=nn({itemType:Ic,element:t});return e?.itemValue===Tu}function Dk({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[Ak[n]].push(o),[wt,Qr].includes(n)){let{participantRoleResponsibilities:c,participantOtherName:u,participantName:p,participantId:m,teamId:d}=e,l=Uk[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 Nk({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:{[Lt]:{...r},[vt]:{...r},[wt]:{...r},...r}}}function Xo({participantsProfile:t,useParticipantMap:e,tournamentRecord:r,contextProfile:n,inContext:o}){if(e)return aS({...t,...n,tournamentRecord:r});let i=J(r.participants,!1,!0)||[];(t?.withIOC||t?.withISO2)&&i.forEach(a=>nS({participant:a,...t}));let s;if((o||t?.withGroupings)&&i?.length&&({participantsWithGroupings:i,groupInfo:s}=Eu({participantsProfile:t,deepCopy:!1,participants:i})),t?.withScaleValues&&i?.length)for(let a of i){let{ratings:c,rankings:u}=Aa({participant:a});a.rankings=u,a.ratings=c}return{participants:i,groupInfo:s}}function Tt({onlySpecifiedPolicyTypes:t=!1,policyTypes:e=[],tournamentRecord:r,drawDefinition:n,structure:o,event:i}){if(!Array.isArray(e))return{error:YI};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===du)?.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 Go({policyTypes:t=[],tournamentRecord:e,drawDefinition:r,structure:n,event:o}){if(!Array.isArray(t))return{error:YI};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:qc.message}}var cS="WALKOVER",XU="RETIRED",ud="COMPETITIVE",hc="ROUTINE",Sc="DECISIVE",pd="winRatio";var Mk={[Di]:{policyName:"Competitive Bands Default",profileBands:{[Sc]:20,[hc]:50}}},md=Mk;function Zn({policyDefinitions:t,tournamentRecord:e,contextProfile:r,drawDefinition:n,event:o}){let i={policies:{}};if(!r)return i;let s=Go({tournamentRecord:e,drawDefinition:n,event:o}).policyDefinitions;if(r.withCompetitiveness){let a=t?.[Di]??s?.[Di]??md[Di];i.policies[Di]=a}return i}function pi({tournamentRecord:t,drawDefinition:e,policyType:r,structure:n,event:o}){if(!t)return{error:q};let{appliedPolicies:i}=Tt({tournamentRecord:t,drawDefinition:e,structure:n,event:o});return i?.[r]?{policy:i[r]}:{info:qc?.message}}function Ra({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}=pi({policyType:_o,tournamentRecord:t,event:n}),s=(t?mt({element:t,name:Qo}).extension:void 0)?.value,c=(n&&mt({name:Qo,element:n}).extension)?.value;return{scheduleTiming:{tournamentScheduling:s,eventScheduling:c,categoryName:e,categoryType:r,policy:o}}}function ng({drawDefinition:t,attributes:e}){let{extension:r}=mt({element:t,name:ed}),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:ed,value:n},Pp({drawDefinition:t,extension:r}),{entryProfile:n}}function Uu({drawDefinition:t}){let{extension:e}=mt({element:t,name:ed});return{entryProfile:e?.value||{}}}var on="ALTERNATE",og="CONFIRMED",Gr="DIRECT_ACCEPTANCE",dd="FEED_IN",ig="JUNIOR_EXEMPT",gs="LUCKY_LOSER",sg="ORGANISER_ACCEPTANCE",ld="QUALIFIER",Rk="REGISTERED",ag="SPECIAL_EXEMPT",Vr="UNGROUPED",Ci="UNPAIRED",Pu="WILDCARD",mo="WITHDRAWN",cg=[og,Gr,ig,sg,ag],JU=[dd,gs,ld],mi=[og,Gr,dd,ig,sg,ag,Pu],Xr=[og,Gr,ig,gs,ld,sg,ag,Pu],ZU=[on,og,Gr,dd,ig,gs,sg,ld,Rk,ag,Vr,Ci,Pu,mo],xb={ALTERNATE:on,CONFIRMED:og,DIRECT_ACCEPTANCE:Gr,DIRECT_ENTRY_STATUSES:mi,DRAW_SPECIFIC_STATUSES:JU,EQUIVALENT_ACCEPTANCE_STATUSES:cg,FEED_IN:dd,JUNIOR_EXEMPT:ig,LUCKY_LOSER:gs,ORGANISER_ACCEPTANCE:sg,QUALIFIER:ld,SPECIAL_EXEMPT:ag,STRUCTURE_SELECTED_STATUSES:Xr,UNGROUPED:Vr,UNPAIRED:Ci,VALID_ENTRY_STATUSES:ZU,WILDCARD:Pu,WITHDRAWN:mo};function ug({stage:t,drawDefinition:e}){let{entryProfile:r}=Uu({drawDefinition:e}),n=Object.keys(r).includes(t);if(!n&&ru.includes(t)){let o=[{[t]:{drawSize:void 0,alternates:!0}}];return ng({drawDefinition:e,attributes:o}),!0}return n}function wb({stage:t,drawDefinition:e}){let{entryProfile:r}=Uu({drawDefinition:e});return r[t]?.alternates||0}function Lb({stage:t,drawDefinition:e}){let{entryProfile:r}=Uu({drawDefinition:e});return r[t]?.wildcardsCount||0}function uS({stage:t,drawDefinition:e,entryStatus:r}){return e.entries.reduce((n,o)=>o.entryStage===t&&o.entryStatus===r?n+1:n,0)}function bi({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:vn,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}=Ck({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 Ck({provisionalPositioning:t,drawDefinition:e,structureId:r}){let n=[],o=(e.links??[]).find(i=>i.linkType===Fn&&i.target.structureId===r);if(o){let{finishingPositions:i,structureId:s}=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:Lo}).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:dd,placementGroup:A,groupingValue:d,participantId:h,GEMscore:E})})})}return{playoffEntries:n}}function Fb({stage:t,drawDefinition:e}){return mi.reduce((r,n)=>(uS({drawDefinition:e,entryStatus:n,stage:t})||0)+r,0)}function sn({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:_t};n||(n=o.structureId);let{stage:c,stageSequence:u}=o,m=c===fe&&r&&bi({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=QE;let f=o.seedLimit??o?.positionAssignments?.length;return{seedAssignments:s,stageSequence:u,seedLimit:f,stage:c,error:i}}function di(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 Cp({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:Cp({item:r,drawDefinition:t,structure:e,event:n})||Cp({item:e,drawDefinition:t,structure:e,event:n})||di(t)||di(n)}}function kb({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 Pe({drawDefinition:t,structure:e}){let r={},n=[];return(t?.structures??[e]).filter(o=>o&&typeof o=="object").forEach(o=>{if(!o)return;let{structureId:i,matchUps:s,structures:a}=o,c=Array.isArray(a);if(c)c&&a.forEach(u=>{let{structureName:p}=u,m=u.matchUps;r[u.structureId]={matchUps:m,itemStructureIds:[],structureName:p},m&&(n.push(...m),m.forEach(d=>{d.tieMatchUps&&n.push(...d.tieMatchUps)})),r[i]||(r[i]={itemStructureIds:[],matchUps:[]}),r[i].itemStructureIds||(r[i].itemStructureIds=[]),r[i].itemStructureIds.push(u.structureId)});else{let u=s;r[i]={matchUps:u,itemStructureIds:[]},u?.forEach(p=>{n.push(p),p.tieMatchUps&&n.push(...p.tieMatchUps)})}}),{mappedMatchUps:r,drawMatchUps:n}}function Vo({mappedMatchUps:t,matchUpsMap:e,structureId:r,inContext:n}){t=e?.mappedMatchUps??t;let o=t[r],i=(o?.itemStructureIds||[]).map(s=>{let{matchUps:a,structureName:c}=t[s];return n?a.map(u=>Object.assign(J(u,!0,!0),{containerStructureId:r,structureId:s,structureName:c})):a}).flat();return(o?.matchUps||[]).concat(...i)}function pS({groupedOrder:t,roundPositionsCount:e}){if(!t||t?.length<=e)return t;let n=Ae(t,t.length/e).map(i=>i.reduce((s,a)=>s+a)),o=n.slice().sort(le);return n.map(i=>o.indexOf(i)+1)}function pg(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 Br(t){return Array.isArray(t)?t.every(pg):!1}function Ke({matchUps:t=[],interpolate:e}){if(!Br(t))return{roundMatchUps:[],error:B};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&&Ln(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=>!ae.includes(I.matchUpStatus)&&!I.score?.scoreStringSide1)?.length,g=l&&l===f;return i=Math.max(i,l),{[d]:{matchUpsCount:l,inactiveCount:f,inactiveRound:g}}})),a=0,c=0,u=Object.keys(o).map(d=>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=Ae(g,2);s[d].drawPositions=g,s[d].pairedDrawPositions=I}else{let g=s[d-1],I=g.drawPositions,h=g.matchUpsCount/s[d].matchUpsCount,S=Ae(I,h),T=l.map(y=>{let{roundPosition: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})=>!Ln(d));return{hasNoRoundPositions:t.some(d=>!d.roundPosition),roundsNotPowerOf2:p,maxMatchUpsCount:i,roundMatchUps:o,roundNumbers:u,roundProfile:s,...C}}function fd(t){if(!Array.isArray(t))return"";let e=t.filter(Jt);return e.length?pt([Math.min(...e),Math.max(...e)]).join("-"):""}function Gb({drawDefinition:t,structureId:e,matchUpsMap:r}){if(!t)return{error:Z};if(!e)return{error:Pr};let{structure:n}=at({drawDefinition:t,structureId:e});if(n?.stage!==qe)return{error:Vi,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=Vo({structureId:m,matchUpsMap:r}),f=Ke({matchUps:d}).roundProfile;return{[m]:f}})),c=Vo({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=pS({roundPositionsCount:A,groupedOrder:g}),D=N?.length||1;if(D<=A){let O=T.length/D,v=Ae(U,O);f===yi&&v.forEach(x=>x.reverse()),U=N?.length&&N?.map(x=>v[x-1]).flat()||v.flat()}let M=Ae(U,P);if(I){let O=tt(0,I.interleave).map(()=>{}),v=tt(0,I.offset).map(()=>{});M=M.map(F=>[F,...O]),M.unshift(v),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((O,v)=>{let x=1+v*b;p[h][x]||(p[h][x]=fd(O))})}),{sourceDrawPositionRanges:p}}function mS({drawDefinition:t}){if(typeof t!="object")return{error:Sa};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 Vb({drawDefinition:t,roundProfile:e,structureId:r,matchUpsMap:n}){if(!t)return{error:Z};if(!r)return{error:Pr};if(!e){let c=Vo({matchUpsMap:n,structureId:r});if({roundProfile:e}=Ke({matchUps:c}),!e)return{error:st}}let i=(Math.min(...e?.[1]?.drawPositions??[])||1)-1,s=Object.keys(e);return{drawPositionsRanges:Object.assign({},...(s||[]).map(c=>{let u=e?.[c]?.matchUpsCount,p=e?.[1]?.drawPositions??[],m=Ae(p,p.length/u),d=m.map(fd),l=m.map(S=>S.map(T=>T-i)).map(fd),f=s.map(S=>{if(S>c)return;let T=e?.[S]?.drawPositions??[];return Ae(T,T.length/u)}).filter(Boolean),g=tt(0,u).map(S=>f.map(T=>T[S]).flat().filter(Boolean).sort(le)).map(S=>pt(S)),I=g.map(S=>UC(S).map(fd).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 gd({roundsNotPowerOf2:t,drawDefinition:e,structure:r,matchUps:n}){if(!r)return!1;n=n??r.matchUps??[],t=t??Ke({matchUps:n}).roundsNotPowerOf2;let o=!!r.positionAssignments?.find(({drawPosition:i})=>i)||!!n?.find(({drawPositions:i})=>i?.length);return(!e?.drawType||e.drawType!==Ki)&&!r?.structures&&t&&o}function cr({structure:t}){if(!t)return!1;let e=t.matchUps||t.roundMatchUps&&Object.values(t.roundMatchUps).flat(),r=!!e?.find(o=>o?.roundPosition),n=!!e?.find(o=>o?.drawPositions?.length);return!t?.structures&&t?.stage!==$e&&(!e.length||!r&&!n)}var mg={[vo]:{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"}}},Bb=mg;function dS({roundNamingPolicy:t,drawDefinition:e,structure:r,matchUps:n}){let{roundProfile:o,roundMatchUps:i}=Ke({matchUps:n}),{structureAbbreviation:s,stage:a}=r,c=cr({structure:r}),u=gd({structure:r}),p=r.structures,m={},d=mg[vo],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 O=`${R}${P} ${b}`,v=`${y}${b}`;return{[b]:{roundName:O,abbreviatedRoundName:v}}}));else{let b=l&&(t?.qualifyingFinishMap||d?.qualifyingFinishMap||{});Object.assign(m,...M.map(O=>{if(!o?.[O])return;let{matchUpsCount:v,preFeedRound:x}=o[O],F=v*2,w=b?.[o?.[O].finishingRound]||b&&`${y}${F}`||h[v]||`${y}${F}`,L=x?`-${T}`:"",k=`${w}${L}`,G=[D,s,k].filter(Boolean).join("-"),K=`${S[v]||`${y}${F}`}${L}`,Y=[D,s,K].filter(Boolean).join("-");return{[O]:{abbreviatedRoundName:Y,roundName:G}}}))}return{roundNamingProfile:m,roundProfile:o,roundMatchUps:i}}var bk=(t,e)=>(t||0)+(e||0);function lS(t,e){let r=Array.isArray(t)?t[0]:t;return isNaN(r)&&cS||r<=e[Sc]&&Sc||r<=e[hc]&&hc||ud}function fS({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(bk)&&(r[n[0]>n[1]?0:1]+=1),{sets:e,games:r,score:t}}function Ok(t){let e=Math.min(...t.games),r=Math.max(...t.games);return Math.round(e/r*100)}function gS(t){return t.map(Ok).sort().map(e=>parseFloat(e.toFixed(2)))}function Du({tournamentRecord:t,profileBands:e,matchUp:r}){if(!r)return{error:mr};let{score:n,winningSide:o}=r;if(!o)return{error:B};let i=!e&&t&&pi({policyType:Di,tournamentRecord:t}).policy,s=e||i?.profileBands||md[Di].profileBands,a=fS({score:n}),c=gS([a]),u=lS(c,s),p=Array.isArray(c)?c[0]:c;return{...C,competitiveness:u,pctSpread:p}}function IS({matchUp:t}){if(!t)return{error:mr};if(t&&!t.sides)return{error:dr};if(t&&!t.hasContext)return{error:Kc};let e=(t.sides??[])?.map(a=>a?.participantId).filter(Boolean),r=t.sides?.filter(a=>a.participant?.participantType===Et).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 Id="CHECK_IN",hd="CHECK_OUT",vk="SCHEDULE",Ji="SCHEDULE.ASSIGNMENT.VENUE",lo="SCHEDULE.ALLOCATION.COURTS",Jo="SCHEDULE.ASSIGNMENT.COURT",bp="SCHEDULE.COURT.ORDER",Zi="SCHEDULE.DATE",_k="COMPLETED.DATE",Sd="HOME_PARTICIPANT_ID",dg="SCHEDULE.ASSIGN.OFFICIAL",ts="SCHEDULE.TIME.SCHEDULED",Bo="SCHEDULE.TIME.START",es="SCHEDULE.TIME.STOP",Oi="SCHEDULE.TIME.RESUME",vi="SCHEDULE.TIME.END",Op="SCHEDULE.TIME.MODIFIERS",Hb="TO_BE_ANNOUNCED",Wb="NEXT_AVAILABLE",jb="FOLLOWED_BY",Yb="AFTER_REST",qb="RAIN_DELAY",xk="NOT_BEFORE",hS=[Hb,Wb,jb,Yb,qb],wk="ELIGIBILITY",Lk="REGISTRATION",Fk="SUSPENSION",kk="MEDICAL",Gk="PENALTY",tP="SCALE",eP="RATING",rP="RANKING",lg="SEEDING",Ho="PUBLISH",Cr="PUBLIC",Wo="STATUS",Vk="MODIFICATION",Bk="RETRIEVAL",Hk="other",$b={MUTUALLY_EXCLUSIVE_TIME_MODIFIERS:hS,AFTER_REST:Yb,ALLOCATE_COURTS:lo,ASSIGN_COURT:Jo,ASSIGN_OFFICIAL:dg,ASSIGN_VENUE:Ji,CHECK_IN:Id,CHECK_OUT:hd,COMPLETED_DATE:_k,COURT_ORDER:bp,ELIGIBILITY:wk,END_TIME:vi,FOLLOWED_BY:jb,MEDICAL:kk,MODIFICATION:Vk,NEXT_AVAILABLE:Wb,NOT_BEFORE:xk,OTHER:Hk,PENALTY:Gk,PUBLIC:Cr,PUBLISH:Ho,RANKING:rP,RATING:eP,RAIN_DELAY:qb,REGISTRATION:Lk,RESUME_TIME:Oi,RETRIEVAL:Bk,SCALE:tP,SCHEDULE:vk,SCHEDULED_DATE:Zi,SCHEDULED_TIME:ts,SEEDING:lg,START_TIME:Bo,STATUS:Wo,STOP_TIME:es,SUSPENSION:Fk,TIME_MODIFIERS:Op,TO_BE_ANNOUNCED:Hb};function Is({matchUp:t}){if(!t)return{error:mr};if(!t.hasContext)return{error:Kc};if(!t.sides||t.sides.filter(Boolean).length!==2)return{error:dr};let{nestedIndividualParticipantIds:e,allRelevantParticipantIds:r,sideParticipantIds:n}=IS({matchUp:t}),i=(t.timeItems??[]).filter(u=>u?.itemType&&[Id,hd].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===Id);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||kt(e)&&e;return r&&vI[t].includes(r)};function vp(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 _p(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 SS({timesBlockArray:t,categoryName:e,categoryType:r}){return t.filter(n=>Array.isArray(n)).map(n=>n.sort((o,i)=>(i.categoryNames?.length||0)-(o.categoryNames?.length||0)).find(({categoryTypes:o,categoryNames:i})=>!i?.length&&!o?.length||i?.includes(e)||o?.includes(r))).find(Boolean)}function Kb({tournamentScheduling:t,eventScheduling:e,averageMinutes:r,defaultTiming:n,matchUpFormat:o,categoryName:i,categoryType:s,policy:a}){let c=e?.matchUpRecoveryTimes&&_p({...e,averageMinutes:r,matchUpFormat:o}),u=t?.matchUpRecoveryTimes&&_p({...t,averageMinutes:r,matchUpFormat:o}),p=a?.matchUpRecoveryTimes&&_p({...a,averageMinutes:r,matchUpFormat:o}),m=[c,u,p,a?.defaultTimes?.recoveryTimes,n?.recoveryTimes];return SS({categoryName:i,categoryType:s,timesBlockArray:m})}function zb({matchUpFormat:t,categoryName:e,categoryType:r,defaultTiming:n,tournamentScheduling:o,eventScheduling:i,policy:s}){let a=i?.matchUpAverageTimes&&vp({...i,matchUpFormat:t}),c=o?.matchUpAverageTimes&&vp({...o,matchUpFormat:t}),u=s?.matchUpAverageTimes&&vp({...s,matchUpFormat:t}),p=[a,c,u,s?.defaultTimes?.averageTimes,n?.averageTimes];return SS({categoryName:e,categoryType:r,timesBlockArray:p})}var nP="DOUBLES_SINGLES",oP="SINGLES_DOUBLES",fo="total",TS="participantConflict",Ca="matchUpConflict",iP="ISSUE_IDS",Tc="CONFLICT",yc="WARNING",yS="ERROR",ES="ISSUE",fg="STATE",Qb={SINGLES_DOUBLES:oP,DOUBLES_SINGLES:nP,TOTAL:fo,CONFLICT_MATCHUP_ORDER:Ca,CONFLICT_PARTICIPANTS:TS,SCHEDULE_ISSUE_IDS:iP,SCHEDULE_CONFLICT:Tc,SCHEDULE_WARNING:yc,SCHEDULE_ERROR:yS,SCHEDULE_ISSUE:ES,SCHEDULE_STATE:fg};function Nu({defaultAverageMinutes:t=90,defaultRecoveryMinutes:e=0,tournamentRecord:r,matchUpFormat:n,categoryName:o,categoryType:i,eventType:s,event:a}){if(!r)return{error:q};s=s??a?.eventType??qs;let c={averageTimes:[{minutes:{default:t}}],recoveryTimes:[{minutes:{default:e}}]},{scheduleTiming:u}=Ra({tournamentRecord:r,categoryName:o,categoryType:i,event:a}),p={...u,matchUpFormat:n,categoryType:i,defaultTiming:c};return xp({eventType:s,timingDetails:p})}function xp({timingDetails:t,eventType:e}){let r=zb(t),n=Object.keys(r?.minutes||{}),o=r?.minutes&&(n?.includes(e)&&r.minutes[e]||r.minutes.default),i=Kb({...t,averageMinutes:o}),s=Object.keys(i?.minutes||{}),a=i?.minutes&&(s?.includes(e)&&i.minutes[e]||i.minutes.default),c=de(qs)(e)?oP:nP,u=i?.minutes&&(s?.includes(c)&&i.minutes[c]||a);return{averageMinutes:o,recoveryMinutes:a,typeChangeRecoveryMinutes:u}}function sP(t){return t.createdAt?new Date(t.createdAt).getTime():0}function Zo({timeItems:t,itemType:e}){let r=t.filter(o=>o&&o.itemType===e).sort((o,i)=>sP(o)-sP(i)).pop(),n=r&&sP(r);return{itemValue:r?.itemValue,timeStamp:n}}function AS({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Zo({timeItems:r?.timeItems||[],itemType:ts});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{scheduledTime:n}:e}function Xs({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Zo({timeItems:r?.timeItems||[],itemType:Zi});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{scheduledDate:n}:e}function wp(t){if(nh.test(t)){let e=Mf();return new Date(`${e}T${t}`)}else return new Date(t)}function Xb({matchUp:t}){if(!t)return{error:mr};if(!t.timeItems)return{error:df};let e=t.timeItems.filter(n=>[Bo,es,Oi,vi].includes(n?.itemType)).sort((n,o)=>wp(n.itemValue).getTime()-wp(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 Bo:i=0;break;case vi:if(n.lastValue&&[Bo,Oi].includes(n.lastType)){let u=wp(o.itemValue).getTime()-wp(n.lastValue).getTime();i=n.milliseconds+u}else i=n.milliseconds;break;case es:if([Bo,"SCHECULE.TIME.RESUME"].includes(n.lastType)){let u=wp(o.itemValue).getTime()-wp(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([Bo,Oi].includes(r.lastType)){let n=new Date().getTime()-wp(r.lastValue).getTime();r.milliseconds+=n}return{milliseconds:r.milliseconds,time:Wk(r.milliseconds),relevantTimeItems:e}}function Wk(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 Jb({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===Bo&&s;return a&&(!i||r(a)<r(i))?a:i},void 0)?.itemValue}}function Ec(t){let{disableNotice:e,venue:r,context:n}=t;if(typeof r!="object")return{error:B};let o=Rr(t);r.venueId||(r.venueId=Nt());let i;for(let s of Object.values(o)){let a=jk({disableNotice:!0,tournamentRecord:s,context:n,venue:r});if(a?.error)return a;i=a.venue}return e||lt({topic:Jh,payload:{venue:r}}),nt({...C,venue:i})}function jk({tournamentRecord:t,disableNotice:e,context:r,venue:n}){return t?n?(t.venues||(t.venues=[]),n.venueId||(n.venueId=Nt()),t.venues.reduce((i,s)=>i||s.venueId===n.venueId,void 0)?{error:OA}:(r&&At({element:n,extension:{value:r,name:OU}}),t.venues.push(n),e||lt({payload:{venue:n,tournamentId:t.tournamentId},topic:Jh}),{...C,venue:J(n)})):{error:st,info:"missing venue"}:{error:q}}function ti({tournamentRecords:t,tournamentRecord:e,venueId:r}){if(!e)return{error:q};if(!r)return{error:ai};let o=(e.venues??[]).reduce((i,s)=>s.venueId===r?s:i,void 0);if(!o&&t){let s=(fu({tournamentRecords:t}).linkedTournamentIds??[])[e.tournamentId];for(let a of s){let c=t[a],u=ti({tournamentRecord:c,venueId:r});if(u.success&&u.venue)return Ec({tournamentRecord:e,venue:u.venue}),{...C,venue:o}}}return o?{...C,venue:o}:{error:ji}}function US({convertExtensions:t,...e}){let{tournamentRecords:r,tournamentRecord:n,venueId:o}=e,i=ti({tournamentRecords:r,tournamentRecord:n,venueId:o});return J(i,t,!0)}function hs({tournamentRecords:t,tournamentRecord:e,courtId:r}){if(!e)return{error:q};if(!r)return{error:Bi};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=(fu({tournamentRecords:t}).linkedTournamentIds??[])[e.tournamentId];for(let c of a){let u=t[c],p=hs({tournamentRecord:u,courtId:r});if(p.success)return p.venue&&Ec({tournamentRecord:e,venue:p.venue}),{...C,court:o,venue:i}}}return _({result:{error:Vs},stack:n})}function PS(t){return J(hs(t),!1,!0)}function Td({tournamentRecord:t,internalUse:e,courtId:r}){if(!t)return{error:q};if(!r)return{error:Bi};let n=hs({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 Ac(t){let e=et(t,[{[ne]:!0},{venueId:!0,[In]:ai}]);if(e.error)return e;let{tournamentRecord:r,venueId:n}=t,o=ti({tournamentRecord:r,venueId:n});if(o.error)return o;let s=(o.venue?.courts??[]).map(u=>(({courtInfo:p})=>({...p}))(Td({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 Zb({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===vi&&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:pn,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:qr},stack:o})};return{event:u,drawDefinition:void 0,tournamentId:c}}return{event:void 0,drawDefinition:void 0,..._({result:{error:br},context:{drawId:n,eventId:r},stack:o})}}function yd(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:mr};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}=Xb({matchUp:p}),{startTime:l}=Jb({matchUp:p}),{endTime:f}=Zb({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(Sd),D=A.get(lo),M=A.get(ts),R=A.get(Op),b=A.get(Zi),O=A.get(dg),v=A.get(bp),x=A.get(Ji),F=A.get(Jo),w,L,k,G,H,K=p.matchUpType??r;if(a&&M&&o&&K){let Q={matchUpFormat:p.matchUpFormat??c,...a};({averageMinutes:L=0,recoveryMinutes:k=0,typeChangeRecoveryMinutes:G=0}=xp({timingDetails:Q,eventType:K})),(L||k)&&(w=f?$r(zt(f),k):$r(M,L+k)),G&&(H=f?$r(zt(f),G):$r(M,L+G))}!b&&M&&(b=Ut(M));let Y=Bm({scheduledDate:b,scheduledTime:M}),j={},V=(i&&x&&Ac({tournamentRecord:i,venueId:x}))?.venueData||{};x&&(j[x]=V);let{venueName:$,venueAbbreviation:X,courtsInfo:W}=V,z=(F&&W?.find(Q=>Q.courtId===F))?.courtName;for(let Q of D||[]){if(!i)break;Q.venueId&&!j[Q.venueid]&&(j[Q.venueId]=Ac({venueId:Q.venueId,tournamentRecord:i})?.venueData);let ut=j[Q.venueId];Q.venueName=ut?.venueName;let ot=ut?.courtsInfo?.find(Dt=>Dt.courtId===Q.courtId);Q.courtName=ot?.courtName}g=nt({typeChangeTimeAfterRecovery:H,timeAfterRecovery:w,scheduledDate:b,scheduledTime:M,isoDateString:Y,homeParticipantId:N,venueAbbreviation:X,allocatedCourts:D,timeModifiers:R,venueName:$,venueId:x,courtOrder:v,courtName:z,courtId:F,official:O,typeChangeRecoveryMinutes:G,recoveryMinutes:k,averageMinutes:L,milliseconds:m,startTime:l,endTime:f,time:d})}else g=nt({milliseconds:m,startTime:l,endTime:f,time:d});let{scheduledDate:S}=Xs({matchUp:p}),{scheduledTime:T}=AS({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=Qi({source:g,template:N})}}}let E=p.matchUpStatus&&ae.includes(p.matchUpStatus)&&(Ut(f)||Ut(S)||Ut(T))||void 0;return{schedule:g,endDate:E}}function tO({drawPositions:t,roundProfile:e,roundNumber:r}){let n=[void 0,void 0];if(LI(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(wI(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 Lp({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 Sn({tournamentParticipants:t,tournamentRecord:e,participantIds:r}){let n="getPairedParticipant";if(!t&&!e)return{error:q};if(!Array.isArray(r)||r.length>2)return{error:wr};if(!r.length)return _({result:{error:bo},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 Ss({drawDefinition:t,participantId:e}){if(typeof t!="object")return{error:Z};if(typeof e!="string")return{error:se};let{extension:r}=mt({element:t,name:wo});return{lineUp:(r?.value||{})[e]}}function eO({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}=Lp({collectionPosition:r,collectionId:s,lineUp:d});if(c===vt){if(f?.length<=2){let I=o?.[f[0]]?.pairIdMap?.[f[1]],T=(I&&o[I]?.participant||Sn({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||Ss({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||Ss({participantId:d,drawDefinition:i})?.lineUp;return u({attribute:m,lineUp:g,teamParticipant:f})}).filter(Boolean)||{};return{drawPositionCollectionAssignment:Object.assign({},...p)}}function Ed(t){let e=et(t,[{[Gn]:!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===Et&&Lt||s===ft&&vt||s===wt&&wt||void 0}return{matchUpType:n}}function rO({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?Yk({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 Yk({displaySideNumber:t,seedAssignments:e,participantId:r,assignment:n,sideNumber:o}){let i={drawPosition:n.drawPosition,displaySideNumber:t,sideNumber:o};if(r){let s=qk({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 qk({seedAssignments:t,participantId:e}){return t?.find(r=>!r.seedProxy&&r.participantId===e)}function aP({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:O}){c=c??{};let v=We({drawDefinition:y,structure:M,matchUp:b,event:O})?.tieFormat,{roundOffset:x,structureId:F,structureName:w,stage:L,stageSequence:k}=M,{drawId:G,drawName:H,drawType:K}=y??{},Y=v?.collectionDefinitions,j=b.collectionId&&Y?.find(me=>me.collectionId===b.collectionId),V=b.collectionId?j?.matchUpFormat:b.matchUpFormat??M?.matchUpFormat??y?.matchUpFormat??O?.matchUpFormat,$=b.matchUpType||j?.matchUpType||M?.matchUpType||y?.matchUpType||!de(_e)(O?.eventType)&&O?.eventType,X=l?"BYE":b.matchUpStatus,{schedule:W,endDate:it}=yd({scheduleVisibilityFilters:t,afterRecoveryTimes:s,tournamentRecord:p,usePublishState:g,scheduleTiming:S,drawDefinition:y,matchUpFormat:V,publishStatus:E,matchUpType:$,matchUp:b,event:O}),z=m??b.drawPositions??[],{collectionPosition:Q,collectionId:ut,roundPosition:ot}=b,Dt=b.roundNumber??c.roundNumber,Rt=ut?eO({tournamentParticipants:r,positionAssignments:n,collectionPosition:Q,participantMap:I,drawDefinition:y,drawPositions:z,collectionId:ut,sideLineUps:D,matchUpType:$}):void 0,De=u?.[Dt]?.roundName||c.roundName,qt=u?.[Dt]?.abbreviatedRoundName||c.abbreviatedRoundName,Se=N?.[Dt]?.feedRound,_r=N?.[Dt]?.preFeedRound,dn=N?.[Dt]?.roundFactor,hr=o?.[Dt],Xe=ot?hr?.[ot]:void 0,Zt=e?.[Dt],Pt=j?.category?{...R?.category,...j.category}:R?.category??O?.category,ce=b.processCodes?.length&&b.processCodes||j?.processCodes?.length&&j?.processCodes||M?.processCodes?.length&&M?.processCodes||y?.processCodes?.length&&y?.processCodes||O?.processCodes?.length&&O?.processCodes||p?.processCodes,ue=T?.withCompetitiveness&&Du({...h,matchUp:b}),Fe=b.finishingPositionRange??c.finishingPositionRange,te=L!==ct&&It(a)&&a+(Dt||0),Je=me=>nt(me,void 0,!0),$t={...Je(R),...Je({matchUpFormat:$===_e?void 0:V,tieFormat:$===_e?v:void 0,gender:j?.gender??O?.gender,endDate:b.endDate??it,discipline:O?.discipline,category:Pt,finishingPositionRange:Fe,abbreviatedRoundName:qt,drawPositionsRange:Xe,competitiveProfile:ue,structureName:w,stageSequence:k,drawPositions:z,matchUpStatus:X,processCodes:ce,isRoundRobin:U,matchUpTieId:A,preFeedRound:_r,matchUpType:$,roundFactor:dn,roundOffset:x,structureId:F,roundNumber:Dt,roundOfPlay:te,feedRound:Se,roundName:De,drawName:H,drawType:K,schedule:W,drawId:G,stage:L}),...J(Je(b),!0,!0)};if(V&&b.score?.scoreStringSide1){let me=Ne(V),{bestOf:Sr,finalSetFormat:jr,setFormat:Kt}=me??{};(jr?.tiebreakSet||Kt?.tiebreakSet||Kt?.timed)&&($t.score.sets=$t.score.sets.sort((Te,gr)=>Te.setNumber-gr.setNumber).map((Te,gr)=>{let ee=gr+1===Sr&&jr?jr:Kt,Ur=ee?.tiebreakSet&&!ee?.timed,Cn=ee?.timed;return Ur?(Te.tiebreakSet=!0,[1,2].includes(Te.winningSide)&&(Te.side1Score=Te.winningSide===1?1:0,Te.side2Score=Te.winningSide===2?1:0)):Cn&&(Te.timed=!0),Te}))}if(Array.isArray(z)){let{orderedDrawPositions:me,displayOrder:Sr}=tO({drawPositions:z,roundProfile:N,roundNumber:Dt}),jr=N?.[Dt]?.feedRound,Kt=Sr[0]!==me[0],gr=me.concat(void 0,void 0).slice(0,2).map((Ee,Rn)=>{let ee=Rn+1,Ur=Kt?3-ee:ee,Cn=rO({...Rt,positionAssignments:n,displaySideNumber:Ur,seedAssignments:f,drawPosition:Ee,isFeedRound:jr,sideNumber:ee}),An=b.sides?.find(ep=>ep.sideNumber===ee),hi=ot?(ot-1)*2+Rn+1:void 0,ga=hi?Zt?.[hi]:void 0;return Je({sourceDrawPositionRange:ga,...An,...Cn})});Object.assign($t,J({sides:gr},!0,!0))}if(r&&$t.sides){let me=d?.[zs],Sr=Kt=>{let Te=I?.[Kt]?.participant;return Te&&Qi({template:me?.participant,source:Te})};if($t.sides.filter(Boolean).forEach(Kt=>{if(Kt.participantId){let Te=J(Sr(Kt.participantId)||(r?zo({policyDefinitions:d,participantId:Kt.participantId,tournamentParticipants:r,internalUse:!0,contextProfile:T}):void 0),void 0,!0);if(Te){let gr,Ee;if(y?.entries){let Rn=y.entries.find(Ur=>Ur.participantId===Kt.participantId),ee=O?.entries?.find(Ur=>Ur.participantId===Kt.participantId);gr=Rn?.entryStatus||ee?.entryStatus,Te.entryStatus=gr,Rn?.entryStage&&(Ee=Rn.entryStage,Te.entryStage=Ee)}i===!1?Object.assign(Kt,{participant:{entryStage:Ee,entryStatus:gr}}):Object.assign(Kt,{participant:Te})}}if(Kt?.participant?.individualParticipantIds?.length&&!Kt.participant.individualParticipants?.length){let Te=Kt.participant.individualParticipantIds.map(gr=>Sr(gr)||(r?zo({policyDefinitions:d,tournamentParticipants:r,internalUse:!0,contextProfile:T,participantId:gr}):void 0));i!==!1&&Object.assign(Kt.participant,{individualParticipants:Te})}}),!$t.matchUpType){let{matchUpType:Kt}=Ed({matchUp:$t});Kt&&Object.assign($t,{matchUpType:Kt})}if(T?.inferGender&&(!$t.gender||$t.gender===qi)&&$t.sides?.length===2&&$t.matchUpType!==_e){let Kt=$t.sides.map(Te=>{if(de(Lt)($t.matchUpType))return Te.participant?.person?.sex;if(Te.participant?.individualParticipants?.length===2){let gr=pt(Te.participant.individualParticipants.map(Ee=>Ee.person?.sex)).filter(Boolean);if(gr.length===1)return gr[0]}});if(Kt.filter(Boolean).length===2&&pt(Kt).length===1){let Te=Kt[0];$t.inferredGender=Te}}}if($t.tieMatchUps){let me=$t.matchUpStatus==="BYE",Sr=$t.sides?.map(({participant:jr,drawPosition:Kt,sideNumber:Te,lineUp:gr})=>{let Ee=jr?.participantType===_e&&jr;return{teamParticipant:Ee&&nt({participantRoleResponsibilities:Ee.participantRoleResponsibilities,participantOtherName:Ee.participanOthertName,participantName:Ee.participantName,participantId:Ee.participantId,teamId:Ee.teamId}),drawPosition:Kt,sideNumber:Te,lineUp:gr}});$t.tieMatchUps=$t.tieMatchUps.map(jr=>{let Kt=$t.matchUpId,gr={finishingPositionRange:$t.finishingPositionRange,abbreviatedRoundName:qt,roundNumber:Dt,roundName:De};return aP({tieDrawPositions:z,scheduleVisibilityFilters:t,sourceDrawPositionRanges:e,sideLineUps:Sr,drawPositionsRanges:o,initialRoundOfPlay:a,roundNamingProfile:u,additionalContext:gr,appliedPolicies:d,isCollectionBye:me,usePublishState:g,publishStatus:E,matchUpTieId:Kt,isRoundRobin:U,roundProfile:N,matchUp:jr,event:O,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 ir=$t.sides?.filter(me=>me?.participantId).length===2,fr=!$t.winningSide;if(Object.assign($t,{readyToScore:P&&ir&&fr,hasContext:!0}),ir){let{allParticipantsCheckedIn:me,checkedInParticipantIds:Sr}=Is({matchUp:$t});Object.assign($t,{allParticipantsCheckedIn:me,checkedInParticipantIds:Sr})}return Array.isArray(T?.exclude)&&T?.exclude.forEach(me=>delete $t[me]),$t}function nO({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Zo({timeItems:r?.timeItems||[],itemType:lo});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{allocatedCourts:J(n,!1,!0)}:e}function oO({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Zo({timeItems:r?.timeItems||[],itemType:Jo});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{courtId:n}:e}function iO({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Zo({timeItems:r?.timeItems||[],itemType:Ji});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{venueId:n}:e}function _i(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:O}=t,v=Array.isArray(y)?y.filter(Boolean):[],x=Array.isArray(i)?i.filter(Boolean):[],F=Array.isArray(r)?r.filter(Boolean):[],w=Array.isArray(O)?O.filter(Boolean):[],L=Array.isArray(h)?h.filter(Boolean):[],k=Array.isArray(p)?p.filter(Boolean):[],G=Array.isArray(f)?f.filter(Boolean):[],H=Array.isArray(d)?d.filter(Boolean):[],K=Array.isArray(c)?c.filter(Boolean):[],Y=Array.isArray(l)&&I?l.filter(Boolean):[],j=Array.isArray(A)&&g?A.filter(Boolean):[],V=Array.isArray(D)?D.filter(Boolean):[],$=Array.isArray(R)?R.filter(Boolean):[],X=Array.isArray(a)&&a.filter(Boolean)||typeof u=="string"&&[u]||[],W=Array.isArray(S)&&S.filter(Boolean)||typeof T=="string"&&T.length&&[T]||[],it=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(ot=>{if(N&&!de(xr)(ot)&&!ot.readyToScore||ot.winningSide&&s&&![1,2].includes(ot.winningSide)||m!==void 0&&(m&&!ot.tieMatchUps||!m&&ot.tieMatchUps)||o!==void 0&&(o&&!ot.collectionId||!o&&ot.collectionId)||w.length&&!w.includes(ot.stage)||L.length&&!L.includes(ot.stageSequence)||k.length&&(!ot.collectionId||!k.includes(ot.collectionId))||G.length&&(!ot.roundName||!G.includes(ot.roundName))||H.length&&(!ot.roundNumber||!H.includes(ot.roundNumber))||K.length&&(!ot.roundPosition||!K.includes(ot.roundPosition))||x.length&&(!ot.matchUpStatus||!x.includes(ot.matchUpStatus))||F.length&&ot.matchUpStatus&&F.includes(ot.matchUpStatus)||Y.length&&!Y.includes(ot.matchUpId)||j.length&&(!ot.matchUpType||!Yc(j,ot.matchUpType))||X.length&&(!ot.matchUpFormat||!X.includes(ot.matchUpFormat)))return!1;if(W?.length){let{scheduledTime:Dt}=AS({matchUp:ot}),{scheduledDate:Rt}=Xs({matchUp:ot}),qt=Ut(Dt)||Rt;if(!W.find(Se=>zn(Se,qt)))return!1}if(V.length){let{courtId:Dt}=oO({matchUp:ot}),{allocatedCourts:Rt}=nO({matchUp:ot}),De=Rt?.map(({courtId:qt})=>qt);if(!V.filter(Boolean).includes(Dt)||De?.includes(Dt))return!1}if($.length){let{venueId:Dt}=iO({matchUp:ot});if(!$.filter(Boolean).includes(Dt))return!1}if(E){if(it.length&&!it.includes(ot.tournamentId)||z.length&&!z.includes(ot.eventId)||Q.length&&!Q.includes(ot.drawId)||ut.length&&!ut.includes(ot.structureId))return!1;let Dt=ot.sides?.map(({participantId:Rt})=>Rt).filter(Boolean)??[];if(n&&Dt.length<n||v.length&&!v.some(De=>Dt.includes(De)))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:Si,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=Zn({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=Pe({drawDefinition:s,structure:c}));let{positionAssignments:b,allPositionsAssigned:O}=Ie({structure:c}),v=!R||O,{seedAssignments:x}=sn({provisionalPositioning:e,drawDefinition:s,structure:c});m=m??x;let{structureId:F}=c;l=l||s&&mS({drawDefinition:s}).exitProfiles;let w=l?.[F],L=w?.length&&(w[0].split("-").map(V=>parseInt(V)).reduce((V,$)=>V+$)||0),k=!!c.structures,G=Vo({matchUpsMap:f,structureId:F,inContext:u}),H=U?.[vo],K=dS({roundNamingPolicy:H,drawDefinition:s,structure:c,matchUps:G}),{roundNamingProfile:Y,roundProfile:j}=K;if(I=K?.roundMatchUps??[],o&&(G=_i({matchUps:G,...o,filterMatchUpTypes:!1,filterMatchUpIds:!1})),u){let{sourceDrawPositionRanges:V}=Gb({drawDefinition:s,matchUpsMap:f,structureId:F}),$=s?Vb({drawDefinition:s,roundProfile:j,matchUpsMap:f,structureId:F}).drawPositionsRanges:void 0,X=t.tournamentParticipants,W=t.participantMap;!X?.length&&!W&&r&&({participants:X=[],participantMap:W}=Xo({participantsProfile:t.participantsProfile,useParticipantMap:t.useParticipantMap,policyDefinitions:t.policyDefinitions,tournamentRecord:r,contextProfile:i,inContext:u})),G=G.map(z=>aP({scheduleVisibilityFilters:t.scheduleVisibilityFilters,hydrateParticipants:t.hydrateParticipants,afterRecoveryTimes:t.afterRecoveryTimes,usePublishState:t.usePublishState,scheduleTiming:t.scheduleTiming,publishStatus:t.publishStatus,sourceDrawPositionRanges:V,tournamentParticipants:X,positionAssignments:b,drawPositionsRanges:$,initialRoundOfPlay:L,roundNamingProfile:Y,tournamentRecord:r,appliedPolicies:U,seedAssignments:m,contextContent:d,participantMap:W,contextProfile:i,drawDefinition:s,scoringActive:v,isRoundRobin:k,roundProfile:j,structure:c,context:a,matchUp:z,event:p})),(G?.filter(z=>Array.isArray(z.tieMatchUps))).forEach(z=>{let Q=z.tieMatchUps;G=G.concat(...Q)}),n&&(G=_i({processContext:!0,...n,matchUps:G}))}else(G?.filter($=>Array.isArray($.tieMatchUps))).forEach($=>{let X=$.tieMatchUps;G=G.concat(...X)});return o&&(G=_i({matchUps:G,...o,filterMatchUpTypes:!1,filterMatchUpIds:!1})),(o?.matchUpTypes||o?.matchUpIds)&&(G=_i({matchUpTypes:o.matchUpTypes,matchUpIds:o.matchUpIds,matchUps:G})),(o?.matchUpTypes||o?.matchUpIds||u)&&(I=Ke({matchUps:G}).roundMatchUps??[]),We({drawDefinition:s,structure:c,event:p})?.tieFormat&&({collectionPositionMatchUps:g}=kb({matchUps:G})),{collectionPositionMatchUps:g,roundMatchUps:I,isRoundRobin:k,roundProfile:j,matchUpsMap:f,matchUps:G}}function Ts({matchUp:t}){return t?ae.includes(t?.matchUpStatus)||t?.winningSide:!1}function Mu({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:O}=U,{assignedPositions:v}=Ie({structure:E}),x=v?.filter(w=>w.participantId).map(w=>w.drawPosition),F;return O.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,k=L&&w.sides?.every($=>$.participantId),G=!L&&w.drawPositions?.filter(Boolean).length===2,H=!L&&w.drawPositions?.every($=>x?.includes($)),K=v?.filter($=>$.bye).map($=>$.drawPosition),Y=!L&&w.drawPositions?.find($=>K?.includes($)),V=zh.includes(w.matchUpStatus)&&(k||G&&(!t||H));return Y?b.push(w):Ts({matchUp:w})?D.push(w):V?M.push(w):R.push(w)}),{includesTeamMatchUps:F,abandonedMatchUps:N,completedMatchUps:D,upcomingMatchUps:M,pendingMatchUps:R,byeMatchUps:b,structure:E}}function sO({drawDefinition:t,roundNumber:e,structureId:r}){if(!t)return{error:Z};if(!r)return{error:Pr};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 DS({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[Xn,so].includes(o?.linkType)&&!o?.source?.roundNumber?_({result:{error:B},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:Pr}:{error:Z}}function aO({structureMatchUps:t,matchUp:e}){let{roundNumber:r,roundPosition:n}=e,o=t.filter(s=>s.roundNumber===r&&!s.matchUpTieId),i=t.filter(s=>s.roundNumber===r+1&&!s.matchUpTieId);if(i.length){let s;return i.length===o.length?s=i.find(a=>a.roundPosition===n):i.length===o.length/2&&(s=i.find(a=>a.roundPosition===Math.ceil(n/2))),{matchUp:s}}return{message:"no progression found"}}function NS({sourceRoundMatchUpCount:t,inContextDrawMatchUps:e,sourceRoundPosition:r,drawDefinition:n,targetLink:o}){if(!o)return{error:$l};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=pS({roundPositionsCount:g.length,groupedOrder:a}),P=E?.length||1;if(P<=g.length){let D=f/P,M=Ae(g,D);s===yi&&M.forEach(R=>R.reverse()),T=E?.length&&E?.map(R=>M[R-1]).flat()||T}s===Nn?y=T[h-1]:s===yi?((!E?.length||P>g.length)&&(h=l.length+1-h),y=T[h-1]):s===Sp&&Dr()&&console.log(pp,{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:Zm});if(D?.value)return{disabledDrawPosition:U}}return{matchUp:A,targetDrawPosition:U,matchUpDrawPositionIndex:S}}function ur({inContextDrawMatchUps:t=[],useTargetMatchUpIds:e,inContextMatchUp:r,drawDefinition:n,matchUpId:o}){let i=r;t.length&&!i&&(i=t.find(c=>c.matchUpId===o));let{structure:s}=at({structureId:i?.structureId,drawDefinition:n});return s?.finishingPosition===zi?$k({inContextDrawMatchUps:t,useTargetMatchUpIds:e,drawDefinition:n,structure:s,matchUp:i}):Kk({matchUp:i})}function $k({inContextDrawMatchUps:t,useTargetMatchUpIds:e,drawDefinition:r,structure:n,matchUp:o}){let{winnerMatchUpId:i,loserMatchUpId:s}=o,{links:a}=sO({roundNumber:o.roundNumber,structureId:n.structureId,drawDefinition:r}),c=a?.source,u=DS({source:c,linkType:Xn}),p=DS({linkCondition:kn,linkType:so,source:c}),m=DS({source:c,linkType:so}),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!==fn&&t.find(({matchUpId:R})=>R===i),T=s&&f!==fn&&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!==fn&&({matchUpDrawPositionIndex:E,targetDrawPosition:y,matchUp:T}=NS({targetLink:m,sourceRoundMatchUpCount:M,inContextDrawMatchUps:t,sourceRoundPosition:D,drawDefinition:r})),d&&g!==fn&&({matchUpDrawPositionIndex:S,targetDrawPosition:h,matchUp:I}=NS({targetLink:p,sourceRoundMatchUpCount:M,inContextDrawMatchUps:t,sourceRoundPosition:D,drawDefinition:r})),u&&!P&&l!==fn&&({matchUpDrawPositionIndex:U,targetDrawPosition:A,matchUp:P}=NS({targetLink:u,sourceRoundMatchUpCount:M,inContextDrawMatchUps:t,sourceRoundPosition:D,drawDefinition:r})),P||(N=N||t.filter(R=>R.structureId===n.structureId),{matchUp:P}=aO({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 Kk({matchUp:t}){return{targetLinks:{loserTargetLink:void 0,winnerTargetLink:void 0},targetMatchUps:{loserMatchUp:void 0,winnerMatchUp:void 0},matchUp:t}}function cO({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===Ei){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=ur({useTargetMatchUpIds:!0,inContextDrawMatchUps:e,inContextMatchUp:n,drawDefinition:t,matchUpId:o}),{winnerMatchUp:u}=c.targetMatchUps,{loserMatchUp:p}=c.targetMatchUps;!n.winnerMatchUpId&&u&&(n.winnerMatchUpId=u.matchUpId),!n.loserMatchUpId&&p&&(n.loserMatchUpId=p.matchUpId);let m=cP({upcomingMatchUp:u}),d=cP({upcomingMatchUp:p});if(n.matchUpStatus!=="BYE"&&p?.matchUpStatus==="BYE"){let{matchUp:f}=uO({matchUp:p,drawDefinition:t,inContextDrawMatchUps:e})||{};d=f&&cP({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===kn,I=zk(n);if(I.length){let h=Hf(u?.sides),S=Hf(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 zk(t){return t?.sides?.map(({participant:e,participantId:r,qualifier:n})=>e||r&&{participantId:r}||n&&{qualifier:n}).filter(Boolean)||[]}function uO({matchUp:t,drawDefinition:e,inContextDrawMatchUps:r}){let{matchUpId:n,matchUpStatus:o,structureId:i}=t||{};if(!t||!i||t?.matchUpStatus===Qt)return{matchUp:t};if(o==="BYE"){let s;return t.winnerMatchUpId?s=r.find(({matchUpId:a})=>a===t.winnerMatchUpId):{winnerMatchUp:s}=ur({inContextDrawMatchUps:r,drawDefinition:e,matchUpId:n})?.targetMatchUps||{},uO({matchUp:s,drawDefinition:e,inContextDrawMatchUps:r})}return{matchUp:void 0}}function cP(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 ie(t){let e="getAllDrawMatchUps";Object.assign(t,{requireParticipants:!1});let r=Zs(t);if(r.error)return _({result:r,stack:e});let{abandonedMatchUps:n,completedMatchUps:o,upcomingMatchUps:i,pendingMatchUps:s,byeMatchUps:a,matchUpsMap:c}=r;return{matchUps:(n??[]).concat(...o??[],...i??[],...s??[],...a??[]),matchUpsMap:c}}function Zs(t){if(!t?.drawDefinition)return{error: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=Zn({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}=Eu({participants:e,participantsProfile:a})));let{structures:b}=hn({drawDefinition:S});if(!b)return{error:_t};n||(n=Pe({drawDefinition:S}));let O=S&&mS({drawDefinition:S}).exitProfiles;b.forEach(F=>{let{byeMatchUps:w=[],pendingMatchUps:L=[],upcomingMatchUps:k=[],completedMatchUps:G=[],abandonedMatchUps:H=[]}=Mu({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:O,matchUpsMap:n,structure:F,context:E,event:P});A=A.concat(...H),U=U.concat(...G),N=N.concat(...k),D=D.concat(...L),M=M.concat(...w)});let v=F=>(!l&&!T&&!d||(l&&(F=_i({matchUps:F,...l})),d&&(F=_i({matchUps:F,...d,processContext:!0}))),F),x={abandonedMatchUps:v(A),completedMatchUps:v(U),upcomingMatchUps:v(N),pendingMatchUps:v(D),byeMatchUps:v(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:k,pending:G,bye:H}=F,K=[].concat(...w&&A||[],...L&&U||[],...k&&N||[],...G&&D||[],...H&&M||[]);cO({inContextDrawMatchUps:K,drawDefinition:S})}return x}function to(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=Zn({policyDefinitions:c,tournamentRecord:p,contextProfile:f,event:S}));let M;if(!e?.length&&!n&&p){let v=Xo({participantsProfile:s,useParticipantMap:u,policyDefinitions:c,tournamentRecord:p,contextProfile:f,inContext:I});n=v.participantMap,e=v.participants??[],M=v.groupInfo}let R=S.drawDefinitions??[],b=Ra({tournamentRecord:p,event:S}).scheduleTiming;return{matchUps:R.flatMap(v=>{let{matchUps:x}=ie({tournamentParticipants:e,tournamentAppliedPolicies:i,scheduleVisibilityFilters:o,context:D,participantsProfile:s,afterRecoveryTimes:a,policyDefinitions:c,tournamentRecord:p,usePublishState:m,contextFilters:d,contextProfile:f,drawDefinition:v,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:q};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}=Xo({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=Zn({policyDefinitions:c,tournamentRecord:u,contextProfile:d});return{matchUps:S.flatMap(A=>(y.eventDrawsCount=A.drawDefinitions?.length??0,to({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 Mn({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:xt};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 xi(t,e){return Qk(t,e)||(t?.stageSequence||0)-(e?.stageSequence||0)||t?.roundNumber&&e.roundNumber&&t?.roundNumber-e?.roundNumber||(t?.roundPosition??0)-(e?.roundPosition??0)}function Qk(t,e){return($s[t?.stage]||0)-($s[e?.stage]||0)}function nr(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}=Xo({participantsProfile:s,useParticipantMap:u,policyDefinitions:c,tournamentRecord:p,contextProfile:l,inContext:I})),l&&!n&&(n=Zn({policyDefinitions:c,tournamentRecord:p,contextProfile:l,drawDefinition:f,event:S})),{...ie({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 ys({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 uP=t=>e=>!t||typeof e!="object"?void 0:Array.isArray(t)&&t.map(r=>({[r]:ys({element:e,accessor:r})?.value}))||typeof t=="object"&&Object.keys(t).map(r=>({[r]:ys({element:e,accessor:r})?.value}))||(typeof t=="string"&&ys({element:e,accessor:t}))?.value,Hr=uP;function ba({finishingPositionOffset:t=0,finishingPositionLimit:e,positionsFed:r,roundsCount:n,roundLimit:o,matchUps:i,lucky:s,fmlc:a}){if(!Br(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(Hr("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=Dr({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 rs({inContextDrawMatchUps:t,drawDefinition:e,matchUpsMap:r}){if(!e)return{error:Z};let n={loserMatchUpIds:{},winnerMatchUpIds:{}};if(t||({matchUps:t,matchUpsMap:r}=ie({inContext:!0,drawDefinition:e,matchUpsMap:r})),!r?.drawMatchUps.some(i=>i.finishingPositionRange)&&e?.structures?.length===1&&!e?.structures[0].structures){let i=r?.drawMatchUps??[];ba({matchUps:i})}return(t??[]).filter(({collectionId:i})=>!i).forEach(i=>{let{matchUpId:s,structureId:a}=i,c=ur({inContextDrawMatchUps:t,drawDefinition:e,matchUpId:s}),{winnerMatchUp:u,loserMatchUp:p}=c.targetMatchUps,m=u?.matchUpId,d=p?.matchUpId,f=Vo({matchUpsMap:r,structureId:a}).find(g=>g.matchUpId===s);if(f&&(m&&(n.winnerMatchUpIds[f.matchUpId]=m,Object.assign(f,{winnerMatchUpId:m}),Object.assign(i,{winnerMatchUpId:m})),d&&(n.loserMatchUpIds[f.matchUpId]=d,i.loserMatchUpId=d,f.loserMatchUpId=d,i.finishingPositionRange))){let g=p.finishingPositionRange&&[...i.finishingPositionRange.loser,...p.finishingPositionRange.loser],I=g&&[Math.min(...g),Math.max(...g)];i.finishingPositionRange.loser=I,f.finishingPositionRange.loser=I}}),{inContextDrawMatchUps:t,goesToMap:n}}function an(t){let e=Rr(t),r=t.matchUps??[],n=t.drawIds??[],{includeParticipantDependencies:o,tournamentRecord:i,drawDefinition:s}=t;if(!Array.isArray(r))return{error:no};if(!Array.isArray(n))return{error:cn};let a=t.matchUpIds?.length?t.matchUpIds:r.map(T=>T.matchUpId);if(!Array.isArray(a))return{error:ps};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===Fn),g=r;if(f.length){g=Mn({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}=Su(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)rs({drawDefinition:s}),g?.length||(g=nr({drawDefinition:s}).matchUps),S(g);else{if(g?.length||(g=Mn({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(xi);if(!y?.find(({roundPosition:P})=>!P)){let P=y?.find(({tournamentId:U})=>U),{drawDefinition:A}=ze({tournamentRecord:e[P?.tournamentId],drawId:T});A&&rs({drawDefinition:A})}S(y)}}return{positionDependencies:c,matchUpDependencies:u,sourceMatchUpIds:m,matchUps:g,...C}}function he(t){let e=t?.matchUp,r=t?.score||e?.score,n=r?.sets?.[0],{side1Score:o,side2Score:i,side1TiebreakScore:s,side2TiebreakScore:a,side1PointScore:c,side2PointScore:u}=n||{},p=o||i||s||a||c||u;return!!(r?.sets?.length>1||p)}function Oa({matchUpStatus:t}){return $h.includes(t)}function pO({matchUpStatus:t}){return id.includes(t)}function gg({matchUpStatus:t}){return Kh.includes(t)}function Ig({matchUpStatus:t,winningSide:e,tieMatchUps:r,sides:n,score:o}){let i=n?.find(({participantId:c})=>c),s=r?.filter(Ig)?.length;return he({score:o})||s||e&&i||t&&pO({matchUpStatus:t})&&![Gt,Bt,Hn].includes(t)}function va(t){let{drawDefinition:e,findContainer:r,structureId:n,event:o}=t,i=t.structure,{containedStructures:s}=fs({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(cr({structure:i}))return{structure:i,isAdHoc:!0,error:Ls};let{matchUps:u}=ie({inContext:!0,matchUpFilters:c,drawDefinition:e,event:o}),p=u?.filter(A=>A.structureId===n||a.includes(A.structureId)),{matchUpDependencies:m}=an({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)}Ig(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 Es({drawPosition:t,matchUps:e=[]}){return{initialRoundNumber:e.filter(({drawPositions:n})=>t&&n?.includes(t)).map(({roundNumber:n})=>n).sort(le)[0]}}var _a={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 MS=[];function Tn(t,e){kt(t)&&(t={method:t}),(e||Dr())&&MS.push(t)}function Xk(t){let e=MS.slice();return t&&(MS.length=0),e}function mO(t){let r=Xk(t).map(n=>{let{color:o,keyColors:i,method:s,newline:a}=n,c=Object.keys(_a).includes(o)?_a[o]:_a.cyan,p=Object.keys(n).filter(d=>!["color","keyColors","method","newline"].includes(d)).map(d=>{let l=i&&Object.keys(i).includes(d)&&_a[i[d]]?_a[i[d]]:_a.brightwhite;return`${_a.white}${d}: ${l}${n[d]}`}).join(", "),m=s?.length<15?" ":" ";return[a?`
|
|
1
|
+
var yL=Object.defineProperty;var Xt=(t,e)=>{for(var r in e)yL(t,r,{get:e[r],enumerable:!0})};function Ka(){return"2.2.47"}var bE={};Xt(bE,{competitionGovernor:()=>kU,drawsGovernor:()=>GN,entriesGovernor:()=>qN,eventGovernor:()=>iM,generationGovernor:()=>pM,matchUpFormatGovernor:()=>jy,matchUpGovernor:()=>bM,mocksGovernor:()=>PI,participantGovernor:()=>sR,policyGovernor:()=>gN,publishingGovernor:()=>gR,queryGovernor:()=>FN,reportGovernor:()=>IR,scheduleGovernor:()=>RR,scoreGovernor:()=>Jg,tieFormatGovernor:()=>kR,tournamentGovernor:()=>XR,venueGovernor:()=>aC});var kU={};Xt(kU,{getLinkedTournamentIds:()=>fu,getTournamentIds:()=>Np,linkTournaments:()=>_U,mutate:()=>LU,query:()=>FU,unlinkTournament:()=>wU,unlinkTournaments:()=>xU});var LU={};Xt(LU,{linkTournaments:()=>_U,unlinkTournament:()=>wU,unlinkTournaments:()=>xU});var Ia="SINGLES",Lt="SINGLES",Gi="DOUBLES",vt="DOUBLES",xr="TEAM",Wt="TEAM",IC={SINGLES_MATCHUP:Ia,SINGLES:Lt,DOUBLES_MATCHUP:Gi,DOUBLES:vt,TEAM_MATCHUP:xr,TEAM:Wt};var vI={[Lt]:[Lt,"S"],[vt]:[vt,"D"],[Wt]:[Wt,"T"],S:[Lt,"S"],D:[vt,"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 Ln(t){return isNaN(t)?!1:t&&(t&t-1)===0}function xE(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 hC(t){if(!Ln(t))return!1;let e=t,r=1;for(;e!==2;)r+=1,e=e/2;return r}function Rm(t){return isNaN(t)?0:t%2&&t+1||t}function Cm(t){return Math.pow(2,Math.round(Math.log(t)/Math.log(2)))}function Jt(t){return!isNaN(parseFloat(t))}function _I(t){let e=dt(t);if(!isNaN(e))return e===0?!1:(e&-e)===1}function us(t){if(isNaN(t))return!1;for(;!Ln(t);)t++;return t}function Io(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 SC(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 EL(t,e){e||(e=1);let r=1/e;return Math.round(t*r)/r}function wE(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=wE(t,e,r):(a=Math.pow(a,r),a*=e-t,a+=t),n&&(a=EL(a,n)),parseFloat(a.toFixed(o))}function Hl(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 TC(t){return Array.isArray(t)?t?.map(e=>e===null?void 0:e):t}function Tr(t){return Array.isArray(t)?t.map(e=>[Math.random(),e]).sort((e,r)=>e[0]-r[0]).map(e=>e[1]):[]}function za(t){return It(t)?t:1/0}function Er(t){return Array.isArray(t)?t.reduce((e,r)=>(e[r]||(e[r]=0),e[r]++,e),{}):{}}function yC(t){return LE(Er(t))}function LE(t){return Object.keys(t).reduce((e,r)=>{let n=t[r];return e[n]?e[n].push(r):e[n]=[r],e},{})}function AL(t,e,r){return r.indexOf(t)===e}function xI(t){return t.filter(AL)}function tn(t){return Array.isArray(t)&&t.length?t.splice(Math.floor(Math.random()*t.length),1)[0]:void 0}function Un(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 ho(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 FE(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 EC(t,e){return Array.isArray(e)&&e.reduce((r,n)=>(r[n]=1+r[n]||1,r),{})[t]||0}function AC(t,e,r,n){return Array.isArray(t)?[].concat(...t.slice(0,e),...t.slice(e,e+r).sort(n),...t.slice(e+r,t.length)):[]}function Ae(t,e){return Array.isArray(t)?t.reduce((r,n,o)=>{let i=Math.floor(o/e);return r[i]=[].concat(r[i]||[],n),r},[]):[]}function kE(t,[e,...r]){return t.length?[t.slice(0,e),...kE(t.slice(e),[...r,e])]:[]}function UC(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 wI(t){return Array.isArray(t)?t.reduce((e,r)=>!isNaN(parseInt(r))&&e,!0):!1}function LI(t){return Array.isArray(t)?t.reduce((e,r)=>isNaN(parseInt(r))&&e,!0):!1}function Wl(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 PC(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 Yr(t){return typeof t=="function"}function kt(t){return typeof t=="string"}function ht(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function DC(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 kI(t,e){return Array.isArray(t)?Object.assign({},...(t??[]).filter(ht).map(r=>r[e]&&{[r[e]]:r}).filter(Boolean)):{}}var NC=t=>e=>Object.keys(t).every(r=>e[r]===t[r]);function FI(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=>FI(i))}:{[o]:e?n(t[o]):FI(t[o])}))}function GE(t){return Array.isArray(t)?t.length+t.map(GE).reduce((e,r)=>e+r,0):ht(t)&&t!==null?Object.keys(t).length+Object.keys(t).map(e=>GE(t[e])).reduce((e,r)=>e+r,0):0}function MC(t){if(t===null||typeof t!="object")return;let e=JSON.stringify(t),r=GE(t),n=e.split("").reduce((o,i)=>o+i.charCodeAt(0),0);return[e.length,r,n].map(o=>o.toString(36)).join("")}function Yc(t,e){return!Array.isArray(t)||!kt(e)?!1:jt(t,vI[e]).length}var C={success:!0},VE="error",RC={SUCCESS:C,ERROR:VE};function GI({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 BC={};Xt(BC,{addNotice:()=>lt,callListener:()=>wm,createInstanceState:()=>KA,cycleMutationStatus:()=>Tf,deepCopyEnabled:()=>Sf,deleteNotice:()=>eh,deleteNotices:()=>Yi,disableNotifications:()=>zA,enableNotifications:()=>hf,getDevContext:()=>Dr,getMethods:()=>yf,getNotices:()=>th,getProvider:()=>rh,getTopics:()=>Lr,getTournamentId:()=>ms,getTournamentRecord:()=>Ef,getTournamentRecords:()=>qo,globalLog:()=>JA,handleCaughtError:()=>fp,hasTopic:()=>dp,removeTournamentRecord:()=>XA,setDeepCopy:()=>Xc,setDevContext:()=>Qc,setGlobalLog:()=>kC,setGlobalMethods:()=>GC,setGlobalSubscriptions:()=>JL,setMethods:()=>VC,setStateMethods:()=>ZA,setStateProvider:()=>QL,setSubscriptions:()=>ZL,setTournamentId:()=>lp,setTournamentRecord:()=>QA,setTournamentRecords:()=>Lm,timeKeeper:()=>XL});var VI={message:"Chronological error; time violation.",code:"ANACHRONISM"},bm={message:"Duplicate entry",code:"DUPLICATE_ENTRY"},BE={message:"Cannot remove main structure",code:"ERR_CANNOT_REMOVE_MAIN_STRUCTURE"},BI={message:"records must be an object with tournamentId keys",code:"ERR_INVALID_TOURNAMENTS"},xt={message:"Missing tournamentRecords",code:"ERR_MISSING_TOURNAMENTS"},q={message:"Missing tournamentRecord",code:"ERR_MISSING_TOURNAMENT"},Qa={message:"Invalid tournamentRecord",code:"ERR_INVALID_TOURNAMENT"},ha={message:"Missing tournamentId",code:"ERR_MISSING_TOURNAMENT_ID"},Sa={message:"Invalid drawDefinition",code:"ERR_INVALID_DRAWDEF"},Z={message:"Missing drawDefinition",code:"ERR_MISSING_DRAWDEF"},HE={message:"Existing drawDefinition(s)",code:"ERR_EXISTING_DRAWDEFS"},br={message:"drawDefinition not found",code:"ERR_NOT_FOUND_DRAWDEF"},si={message:"Invalid structure",code:"ERR_INVALID_STRUCTURE"},jl={message:"Incomplete source structure",code:"ERR_INCOMPLETE_STRUCTURE"},Yl={message:"Invalid drawPosition for seedAssignment",code:"ERR_INVALID_SEEDING_POSITION"},Xa={message:"drawPosition already assigned",code:"ERR_EXISTING_POSITION_ASSIGNMENT"},WE={message:"Schedule not cleared",code:"ERR_UNCHANGED_SCHEDULE_NOT_CLEARED"},jE={message:"drawPosition not cleared",code:"ERR_FAILURE_POSITION_NOT_CLEARED"},UL={message:"drawPosition not found",code:"ERR_NOT_FOUND_DRAW_POSITION"},ql={message:"Unrecognized drawType",code:"ERR_UNRECOGNIZED_DRAW_TYPE"},Ja={message:"Missing drawPositions",code:"ERR_MISSING_DRAW_POSITIONS"},rp={message:"drawPosition is active",code:"ERR_ACTIVE_DRAW_POSITION"},CC={message:"drawPosition is occupied",code:"ERR_OCCUPIED_DRAW_POSITION"},Ls={message:"Invlid drawPosition",code:"ERR_INVALID_DRAW_POSITION"},Fs={message:"Missing drawPosition",code:"ERR_MISSING_DRAW_POSITION"},Om={message:"Invalid drawType",code:"ERR_INVALID_DRAW_TYPE"},np={message:"Invalid drawSize",code:"ERR_INVALID_DRAW_SIZE"},HI={message:"Cannot set drawSize to be less than existing entries",code:"ERR_INVALID_DRAW_SIZE_MISMATCH"},Za={message:"Missing drawSize",code:"ERR_MISSING_DRAW_SIZE"},cn={message:"Missing drawId",code:"ERR_MISSING_DRAW_ID"},YE={message:"drawId exists",code:"ERR_EXISTING_DRAW_ID"},qE={message:"participantId cannot be assigned to multiple seedNumbers",code:"INVALID_PARTICIPANT_SEEDING"},$E={message:"seedsCount greater than drawSize",code:"ERR_INVALID_SEED_COUNT"},KE={message:"Missing seedCountThresholds",code:"ERR_MISSING_SEED_COUNT_THRESHOLD"},zE={message:"Invalid action",code:"ERR_INVALID_ACTION"},WI={message:"Invalid assignment",code:"ERR_INVALID_ASSIGNMENT"},QE={message:"Missing seedAssignments",code:"ERR_MISSING_SEED_ASSIGNMENTS"},XE={message:"Invalid seedNumber",code:"ERR_INVALID_SEED_NUMBER"},JE={message:"Invalid seedPosition",code:"ERR_INVALID_SEED_POSITION"},$l={message:"Missing targetLink",code:"ERR_MISSING_LINK_TARGET"},ZE={message:"Existing round",code:"ERR_EXISTING_ROUND"},PL={message:"Missing roundNumber",code:"ERR_MISSING_ROUND_NUMBER"},Pr={message:"Missing structureId",code:"ERR_MISSING_STRUCTURE_ID"},_t={message:"structure not found",code:"ERR_NOT_FOUND_STRUCTURE"},Kl={message:"Missing structures",code:"ERR_MISSING_STRUCTURES"},Si={message:"Missing structure",code:"ERR_MISSING_STRUCTURE"},zl={message:"Missing MAIN structure",code:"ERR_MISSING_MAIN_STRUCTURE"},tA={message:"drawDefinition contains unlinked structures",code:"ERR_MISSING_STRUCTURE_LINKS"},$n={message:"Invalid eventType",code:"ERR_INVALID_EVENT_TYPE"};var Ot={message:"Missing event / eventId",code:"ERR_MISSING_EVENT_ID"},qr={message:"Event not found",code:"ERR_NOT_FOUND_EVENT"},eA={message:"Event exists",code:"ERR_EXISTING_EVENT"},rA={message:"Missing entries",code:"ERR_MISSING_ENTRIES"},nA={message:"Invalid entries",code:"ERR_INVALID_ENTRIES"},Ql={message:"Missing assignments",code:"ERR_MISSING_ASSIGNMENTS"},oA={message:"Missing stage",code:"ERR_MISSING_STAGE"},Vi={message:"Invalid stage",code:"ERR_INVALID_STAGE"},iA={message:"stageSequence limit",code:"ERR_LIMIT_STAGE_SEQUENCE"},sA={message:"Missing positionAssignments",code:"ERR_MISSING_POSITION_ASSIGNMENTS"},aA={message:"Cannot Assign BYE status if no assignment: { bye: true }",code:"ERR_UNCHANGED_CANNOT_ASSIGN_BYE"},jI={message:"Unrecognized matchUpStatus",code:"ERR_UNRECOGNIZED_MATCHUP_STATUS"},tc={message:"Unrecognized matchUpFormat",code:"ERR_UNRECOGNIZED_MATCHUP_FORMAT"},Xl={message:"Incompatible matchUpStatus",code:"ERR_INCOMPATIBLE_MATCHUP_STATUS"},bC={message:"Propagated exits downstream",code:"ERR_PROPAGATED_EXITS_DOWNSTREAM"},Ta={message:"Invalid matchUpStatus",code:"ERR_INVALID_MATCHUP_STATUS"},Yo={message:"Invalid tieFormat",code:"ERR_INVALID_TIE_FORMAT"},Jl={message:"Invalid matchUpFormat",code:"ERR_INVALID_MATCHUP_FORMAT"},Zl={message:"Missing matchUpFormat",code:"ERR_MISSING_MATCHUP_FORMAT"},cA={message:"Missing collectionDefinition",code:"ERR_MISSING_COLLECTION_DEFINITION"},ks={message:"Missing tieFormat",code:"ERR_MISSING_TIE_FORMAT"},sr={message:"Missing matchUpId",code:"ERR_MISSING_MATCHUP_ID"},ps={message:"Missing matchUpIds",code:"ERR_MISSING_MATCHUP_IDS"},we={message:"matchUp not found",code:"ERR_NOT_FOUND_MATCHUP"},no={message:"Missing matchUps",code:"ERR_MISSING_MATCHUPS"},mr={message:"Missing matchUp",code:"ERR_MISSING_MATCHUP"},dr={message:"Invalid matchUp",code:"ERR_INVALID_MATCHUP"},YI={message:"Missing policyType",code:"ERR_MISSING_POLICY_TYPE"},op={message:"Missing policyDefinitions",code:"ERR_MISSING_POLICY_DEFINITIONS"},DL={message:"Missing seeding policy",code:"ERR_MISSING_POLICY_SEEDING"},uA={message:"Missing avoidance policy",code:"ERR_MISSING_POLICY_AVOIDANCE"},qI={message:"Missing policy attributes",code:"ERR_MISSING_POLICY_ATTRIBUTES"},pA={message:"Invalid policyDefinitions",code:"ERR_INVALID_POLICY_DEFINITIONS"},$I={message:"existing policyType",code:"ERR_EXISTING_POLICY_TYPE"},NL={message:"Policy not attached",code:"ERR_FAILURE_POLICY_NOT_ATTACHED"},qc={message:"Policy not found",code:"ERR_NOT_FOUND_POLICY"},ML={message:"Missing scoring policy / matchUpFormats",code:"ERR_MISSING_POLICY_SCORING_MATCHUP_FORMATS"},tf={message:"Invalid sideNumber",code:"ERR_INVALID_SIDE_NUMBER"},RL={message:"Invalid setNumber",code:"ERR_INVALID_SET_NUMBER"},ef={message:"Missing setObject",code:"ERR_MISSING_SET_ATTRIBUTE"},CL={message:"Missing setNumber",code:"ERR_MISSING_SET_NUMBER"},bL={message:"Missing sideNumber",code:"ERR_MISSING_SIDE_NUMBER"},Bi={message:"Missing courtId",code:"ERR_MISSING_COURT_ID"},st={message:"Missing value",code:"ERR_MISSING_VALUE"},mA={message:"Missing birthdate",code:"ERR_MISSING_BIRTH_DATE"},dA={message:"Missing date",code:"ERR_MISSING_DATE"},lA={message:"No valid dates",code:"ERR_NO_VALID_DATES"},vm={message:"Invalid bookings",code:"ERR_INVALID_BOOKINGS"},rf={message:"Invalid dateAvailability",code:"ERR_INVALID_DATE_AVAILABILITY"},fA={message:"Missing dateAvailability",code:"ERR_MISSING_DATE_AVAILABILITY"},Ye={message:"Invalid Date",code:"ERR_INVALID_DATE"},Co={message:"Invalid time",code:"ERR_INVALID_TIME"},gA={message:"Invalid tournament dates",code:"ERR_INVALID_DATES_TOURNAMENT"};var KI={message:"Invalid game scores",code:"ERR_INVALID_SCORES_GAME"},IA={message:"Invalid score",code:"ERR_INVALID_SCORE"},_m={message:"Invalid winningSide",code:"ERR_INVALID_WINNING_SIDE"};var OC={message:"No participants generated",code:"ERR_NO_PARTICIPANTS_GENERATED"},nf={message:"Cannot modify tieFormat",code:"ERR_UNCHANGED_CANNOT_MODIFY_TIEFORMAT"},hA={message:"Cannot modify participantType",code:"ERR_UNCHANGED_CANNOT_MODIFY_PARTICIPANT_TYPE"},ip={message:"Cannot remove participants",code:"ERR_UNCHANGED_CANNOT_REMOVE_PARTICIPANTS"},zI={message:"Participant category mismatch",code:"ERR_CATEGORY_MISMATCH"},xm={message:"Cannot change winningSide",code:"ERR_UNCHANGED_CANNOT_CHANGE_WINNING_SIDE"},Hi={message:"Invalid participant",code:"ERR_INVALID_PARTICIPANT"},ln={message:"Invalid participantId",code:"ERR_INVALID_PARTICIPANT_ID"},wr={message:"Invalid participantIds",code:"ERR_INVALID_PARTICIPANT_IDS"},SA={message:"Invalid participantRole",code:"ERR_INVALID_PARTICIPANT_ROLE"},Pn={message:"Invalid participantType",code:"ERR_INVALID_PARTICIPANT_TYPE"},TA={message:"Missing participantRole",code:"ERR_MISSING_PARTICIPANT_ROLE"},Wi={message:"Missing participant",code:"ERR_MISSING_PARTICIPANT"},ec={message:"Missing participants",code:"ERR_MISSING_PARTICIPANTS"},se={message:"Missing participantId",code:"ERR_MISSING_PARTICIPANT_ID"},yA={message:"Missing qualified participants",code:"ERR_MISSING_QUALIFIED_PARTICIPANTS"},re={message:"Participant Not Found",code:"ERR_NOT_FOUND_PARTICIPANT"},EA={message:"participantId exists",code:"ERR_EXISTING_PARTICIPANT_ID"},OL={message:"participant pair exists",code:"ERR_EXISTING_PARTICIPANT_PAIR"},AA={message:"No participant removed",code:"ERR_UNCHANGED_NO_PARTICIPANT_REMOVED"},bo={message:"Missing participantIds",code:"ERR_MISSING_PARTICIPANT_IDS"},UA={message:"Missing participantsCount",code:"ERR_MISSING_PARTICIPANT_COUNT"},PA={message:"Participant not checked in",code:"ERR_UNCHANGED_PARTICIPANT_NOT_CHECKED_IN"},DA={message:"Missing person details",code:"ERR_MISSING_PERSON_DETAILS"},Gs={message:"Existing participant drawPosition assignment",code:"ERR_EXISTING_PARTICIPANT_DRAW_POSITION_ASSIGNMENT"},sp={message:"Existing participant",code:"ERR_EXISTING_PARTICIPANT"},of={message:"participantsCount exceeds drawSize",code:"ERR_INVALID_PARTICIPANT_COUNT"},sf={message:"Invalid entry status",code:"ERR_INVALID_ENTRY_STATUS"},QI={message:"Participant Entry Not Found",code:"ERR_NOT_FOUND_PARTICIPANT_ENTRY"},vC={message:"Participant not entered in stage",code:"ERR_UNCHANGED_PARTICIPANT_NOT_ENTERED"},_C={message:"Participant not found in stageSequence",code:"ERR_NOT_FOUND_PARTICIPANT_IN_STAGE"},NA={message:"entryStatus not allowed in stage",code:"ERR_INVALID_ENTRY_STATUS_IN_STAGE"},MA={message:"entryStatus not allowed for event",code:"ERR_INVALID_ENTRY_STATUS_IN_EVENT"},XI={message:"No stage space available for entryStatus",code:"ERR_UNCHANGED_NO_AVAILABLE_STAGE_SPACE"},af={message:"Insufficient drawPositions to accommodate qualifiers",code:"ERR_UNCHANGED_NO_DRAW_POSITIONS_FOR_QUALIFIERS"},cf={message:"Insufficient drawPositions to accommodate entries",code:"ERR_INSUFFICIENT_DRAW_POSITIONS"},RA={message:"Missing penaltyType",code:"ERR_MISSING_PENALTY_TYPE"},uf={message:"Missing penaltyId",code:"ERR_MISSING_PENALTY_ID"},$c={message:"Penalty not found",code:"ERR_NOT_FOUND_PENALTY"},CA={message:"Missing courtsCount/courtNames",code:"ERR_MISSING_COURTS_INFO"},Vs={message:"Court not found",code:"ERR_NOT_FOUND_COURT"},bA={message:"Court exists",code:"ERR_EXISTING_COURT"},OA={message:"Venue exists",code:"ERR_EXISTING_VENUE"},ji={message:"Venue not found",code:"ERR_NOT_FOUND_VENUE"},ai={message:"Missing venueId",code:"ERR_MISSING_VENUE_ID"},vA={message:"Invalid endTime",code:"ERR_INVALID_END_TIME"},JI={message:"Existing endTime",code:"ERR_EXISTING_END_TIME"},_A={message:"Invalid stopTime",code:"ERR_INVALID_STOP_TIME"},xA={message:"Invalid startTime",code:"ERR_INVALID_START_TIME"},xC={message:"Invalid resumeTime",code:"ERR_INVALID_RESUME_TIME"},pf={message:"Invalid timeItem",code:"ERR_INVALID_TIME_ITEMS"},wA={message:"Missing async state provider",code:"ERR_MISSING_ASYNC_STATE_PROVIDER"},mf={message:"Missing timeItem",code:"ERR_MISSING_TIME_ITEM"},df={message:"Missing timeItems",code:"ERR_MISSING_TIME_ITEMS"},Kc={message:"Missing context",code:"ERR_MISSING_CONTEXT"},LA={message:"Missing schedule",code:"ERR_MISSING_SCHEDULE"},rc={message:"Invalid scaleItem",code:"ERR_INVALID_SCALE_ITEM"},FA={message:"Modifications failed",code:"ERR_FAILURE_MODIFICATIONS"},Bs={message:"No modifications applied",code:"ERR_UNCHANGED_NO_MODIFICATIONS_APPLIED"},kA={message:"Unable to assign court",code:"ERR_UNCHANGED_COURT_NOT_ASSIGNED"},ap={message:"No Candidates",code:"ERR_UNCHANGED_NO_CANDIDATES"},GA={message:"Invalid configuration",code:"ERR_INVALID_CONFIG"},VA={message:"Invalid collectionDefinition",code:"ERR_INVALID_COLLECTION_DEFINITION"},So={message:"Invalid object",code:"ERR_INVALID_OBJECT"},cp={message:"Invalid gender",code:"ERR_INVALID_GENDER"},zc={message:"Invalid category",code:"ERR_INVALID_CATEGORY"},B={message:"Invalid values",code:"ERR_INVALID_VALUES"},BA={message:"Duplicate value",code:"ERR_DUPLICATE_VALUE"},lf={message:"Team not found",code:"ERR_NOT_FOUND_TEAM"},HA={message:"No valid actions",code:"ERR_NO_VALID_ACTIONS"},up={message:"No valid attributes",code:"ERR_NO_VALID_ATTRIBUTES"},ff={message:"Value unchanged",code:"ABORT_UNCHANGED"},Oe={message:"Not found",code:"ERR_NOT_FOUND"},pp={message:"Not implemented",code:"ERR_NOT_IMPLEMENTED"},WA={message:"Existing flight",code:"ERR_EXISTING_FLIGHT"},gf={message:"Existing flight profile",code:"ERR_EXISTING_FLIGHT_PROFILE"},jA={message:"Existing outcome",code:"ERR_EXISTING_OUTCOME"},YA={message:"Existing matchUpId",code:"ERR_EXISTING_MATCHUP_ID"},ZI={message:"Existing stage",code:"ERR_EXISTING_STAGE"},If={message:"Existing structure",code:"ERR_EXISTING_STRUCTURE"},nc={message:"Method not found",code:"ERR_NOT_FOUND_METHOD"},qA={message:"Scheduled matchUps",code:"ERR_SCHEDULED_MATCHUPS"},oc={message:"Scores present",code:"ERR_SCORES_PRESENT"},wC={ANACHRONISM:VI,CANNOT_CHANGE_WINNING_SIDE:xm,CANNOT_MODIFY_TIEFORMAT:nf,CANNOT_MODIFY_PARTICIPANT_TYPE:hA,CANNOT_REMOVE_MAIN_STRUCTURE:BE,CANNOT_REMOVE_PARTICIPANTS:ip,CATEGORY_MISMATCH:zI,COURT_EXISTS:bA,COURT_NOT_FOUND:Vs,DRAW_DEFINITION_NOT_FOUND:br,DRAW_ID_EXISTS:YE,DRAW_POSITION_ACTIVE:rp,DRAW_POSITION_ASSIGNED:Xa,DRAW_POSITION_NOT_CLEARED:jE,DRAW_POSITION_NOT_FOUND:UL,DRAW_SIZE_MISMATCH:HI,DUPLICATE_ENTRY:bm,DUPLICATE_VALUE:BA,ENTRY_STATUS_NOT_ALLOWED_FOR_EVENT:MA,ENTRY_STATUS_NOT_ALLOWED_IN_STAGE:NA,EVENT_EXISTS:eA,EVENT_NOT_FOUND:qr,EXISTING_DRAW_DEFINITIONS:HE,EXISTING_END_TIME:JI,EXISTING_FLIGHT:WA,EXISTING_MATCHUP_ID:YA,EXISTING_OUTCOME:jA,EXISTING_PARTICIPANT_DRAW_POSITION_ASSIGNMENT:Gs,EXISTING_PARTICIPANT:sp,EXISTING_POLICY_TYPE:$I,EXISTING_PROFILE:gf,EXISTING_ROUND:ZE,EXISTING_STAGE:ZI,EXISTING_STRUCTURE:If,INCOMPATIBLE_MATCHUP_STATUS:Xl,INCOMPLETE_SOURCE_STRUCTURE:jl,INSUFFICIENT_DRAW_POSITIONS:cf,INVALID_ACTION:zE,INVALID_ASSIGNMENT:WI,INVALID_BOOKINGS:vm,INVALID_CATEGORY:zc,INVALID_COLLECTION_DEFINITION:VA,INVALID_CONFIGURATION:GA,INVALID_DATE_AVAILABILITY:rf,INVALID_DATE:Ye,INVALID_DRAW_DEFINITION:Sa,INVALID_DRAW_POSITION_FOR_SEEDING:Yl,INVALID_DRAW_POSITION:Ls,INVALID_DRAW_SIZE:np,INVALID_END_TIME:vA,INVALID_ENTRIES:nA,INVALID_EVENT_TYPE:$n,INVALID_GAME_SCORES:KI,INVALID_GENDER:cp,INVALID_MATCHUP_FORMAT:Jl,INVALID_MATCHUP_STATUS:Ta,INVALID_MATCHUP_STATUS_BYE:aA,INVALID_MATCHUP:dr,INVALID_OBJECT:So,INVALID_PARTICIPANT_ID:ln,INVALID_PARTICIPANT_IDS:wr,INVALID_PARTICIPANT_ROLE:SA,INVALID_PARTICIPANT_SEEDING:qE,INVALID_PARTICIPANT_TYPE:Pn,INVALID_PARTICIPANT:Hi,INVALID_POLICY_DEFINITION:pA,INVALID_RECORDS:BI,INVALID_SCALE_ITEM:rc,INVALID_SEED_NUMBER:XE,INVALID_SEED_POSITION:JE,INVALID_SET_NUMBER:RL,INVALID_SIDE_NUMBER:tf,INVALID_SCORE:IA,INVALID_STAGE:Vi,INVALID_START_TIME:xA,INVALID_STRUCTURE:si,INVALID_STOP_TIME:_A,INVALID_TIE_FORMAT:Yo,INVALID_TIME:Co,INVALID_TIME_ITEM:pf,INVALID_TOURNAMENT_DATES:gA,INVALID_TOURNAMENT_RECORD:Qa,INVALID_VALUES:B,INVALID_WINNING_SIDE:_m,MATCHUP_NOT_FOUND:we,METHOD_NOT_FOUND:nc,MISSING_ASSIGNMENTS:Ql,MISSING_ASYNC_STATE_PROVIDER:wA,MISSING_AVOIDANCE_POLICY:uA,MISSING_BIRTH_DATE:mA,MISSING_COLLECTION_DEFINITION:cA,MISSING_COURT_ID:Bi,MISSING_COURTS_INFO:CA,MISSING_DATE_AVAILABILITY:fA,MISSING_DATE:dA,MISSING_DRAW_DEFINITION:Z,MISSING_DRAW_ID:cn,MISSING_DRAW_POSITION:Fs,MISSING_DRAW_POSITIONS:Ja,MISSING_DRAW_SIZE:Za,MISSING_ENTRIES:rA,MISSING_EVENT:Ot,MISSING_QUALIFIED_PARTICIPANTS:yA,MISSING_MATCHUP_FORMAT:Zl,MISSING_MATCHUP_ID:sr,MISSING_MATCHUP_IDS:ps,MISSING_MATCHUP:mr,MISSING_MATCHUPS:no,MISSING_PARTICIPANT_COUNT:UA,MISSING_PARTICIPANT_ID:se,MISSING_PARTICIPANT_IDS:bo,MISSING_PARTICIPANT_ROLE:TA,MISSING_PARTICIPANT:Wi,MISSING_PARTICIPANTS:ec,MISSING_PENALTY_ID:uf,MISSING_PENALTY_TYPE:RA,MISSING_PERSON_DETAILS:DA,MISSING_POLICY_ATTRIBUTES:qI,MISSING_POLICY_DEFINITION:op,MISSING_POLICY_TYPE:YI,MISSING_POSITION_ASSIGNMENTS:sA,MISSING_ROUND_NUMBER:PL,MISSING_SCHEDULE:LA,MISSING_SCORING_POLICY:ML,MISSING_SEED_ASSIGNMENTS:QE,MISSING_SEEDCOUNT_THRESHOLDS:KE,MISSING_SEEDING_POLICY:DL,MISSING_SET_NUMBER:CL,MISSING_SET_OBJECT:ef,MISSING_SIDE_NUMBER:bL,MISSING_STAGE:oA,MISSING_STRUCTURE_ID:Pr,MISSING_STRUCTURE:Si,MISSING_MAIN_STRUCTURE:zl,MISSING_STRUCTURES:Kl,MISSING_TARGET_LINK:$l,MISSING_TIE_FORMAT:ks,MISSING_TIME_ITEM:mf,MISSING_TIME_ITEMS:df,MISSING_TOURNAMENT_ID:ha,MISSING_TOURNAMENT_RECORD:q,MISSING_TOURNAMENT_RECORDS:xt,MISSING_VALUE:st,MISSING_VENUE_ID:ai,MODIFICATIONS_FAILED:FA,NO_CANDIDATES:ap,NO_DRAW_POSITIONS_AVAILABLE_FOR_QUALIFIERS:af,NO_MODIFICATIONS_APPLIED:Bs,NO_STAGE_SPACE_AVAILABLE_FOR_ENTRY_STATUS:XI,NO_PARTICIPANT_REMOVED:AA,NO_VALID_ACTIONS:HA,NO_VALID_ATTRIBUTES:up,NO_VALID_DATES:lA,NOT_FOUND:Oe,NOT_IMPLEMENTED:pp,PARTICIPANT_COUNT_EXCEEDS_DRAW_SIZE:of,PARTICIPANT_ID_EXISTS:EA,PARTICIPANT_NOT_CHECKED_IN:PA,PARTICIPANT_NOT_FOUND:re,PARTICIPANT_PAIR_EXISTS:OL,PENALTY_NOT_FOUND:$c,POLICY_NOT_ATTACHED:NL,POLICY_NOT_FOUND:qc,SCHEDULE_NOT_CLEARED:WE,SCHEDULED_MATCHUPS:qA,SCORES_PRESENT:oc,SEEDSCOUNT_GREATER_THAN_DRAW_SIZE:$E,STAGE_SEQUENCE_LIMIT:iA,STRUCTURE_NOT_FOUND:_t,TEAM_NOT_FOUND:lf,UNABLE_TO_ASSIGN_COURT:kA,UNLINKED_STRUCTURES:tA,UNRECOGNIZED_DRAW_TYPE:ql,UNRECOGNIZED_MATCHUP_FORMAT:tc,UNRECOGNIZED_MATCHUP_STATUS:jI,VALUE_UNCHANGED:ff,VENUE_EXISTS:OA};var Ze={disableNotifications:!1,tournamentId:void 0,tournamentRecords:{},subscriptions:{},modified:!1,methods:{},notices:[]},$A={addNotice:WL,callListener:KL,cycleMutationStatus:HL,deleteNotice:qL,deleteNotices:YL,disableNotifications:vL,enableNotifications:_L,getMethods:mp,getNotices:jL,getTopics:$L,getTournamentId:LC,getTournamentRecord:xL,getTournamentRecords:wL,removeTournamentRecord:GL,setMethods:BL,setSubscriptions:VL,setTournamentId:FL,setTournamentRecord:LL,setTournamentRecords:kL,handleCaughtError:zL};function vL(){Ze.disableNotifications=!0}function _L(){Ze.disableNotifications=!1}function LC(){return Ze.tournamentId}function xL(t){return Ze.tournamentRecords[t]}function wL(){return Ze.tournamentRecords}function LL(t){let e=t?.tournamentId;return e?(Ze.tournamentRecords[e]=t,{success:!0}):{error:Qa}}function FL(t){return t?Ze.tournamentRecords[t]?(Ze.tournamentId=t,{success:!0}):{error:q}:(Ze.tournamentId=void 0,{success:!0})}function kL(t){Ze.tournamentRecords=t;let e=Object.keys(t);e.length===1?Ze.tournamentId=e[0]:e.length||(Ze.tournamentId=void 0)}function GL(t){if(typeof t!="string")return{error:B};if(!Ze.tournamentRecords[t])return{error:Oe};delete Ze.tournamentRecords[t];let e=Object.keys(Ze.tournamentRecords);return e.length===1?Ze.tournamentId=e[0]:e.length||(Ze.tournamentId=void 0),{success:!0}}function VL(t){return typeof t.subscriptions!="object"?{error:B}:(Object.keys(t.subscriptions).forEach(e=>{typeof t.subscriptions[e]=="function"?Ze.subscriptions[e]=t.subscriptions[e]:delete Ze.subscriptions[e]}),{...C})}function BL(t){return typeof t!="object"?{error:B}:(Object.keys(t).forEach(e=>{typeof t[e]=="function"&&(Ze.methods[e]=t[e])}),{...C})}function HL(){let t=Ze.modified;return Ze.modified=!1,t}function WL({topic:t,payload:e,key:r},n){if(!(typeof t!="string"||typeof e!="object")&&(Ze.disableNotifications||(Ze.modified=!0),!(Ze.disableNotifications||!Ze.subscriptions[t]&&!n)))return r&&(Ze.notices=Ze.notices.filter(o=>!(o.topic===t&&o.key===r))),Ze.notices.push({topic:t,payload:e,key:r}),{...C}}function mp(){return Ze.methods??{}}function jL({topic:t}){return Ze.notices.filter(e=>e.topic===t).map(e=>e.payload)}function YL(){Ze.notices=[]}function qL({topic:t,key:e}){Ze.notices=Ze.notices.filter(r=>(!t||r.topic===t)&&r.key!==e)}function $L(){return{topics:Object.keys(Ze.subscriptions)}}function KL({topic:t,notices:e},r){let n=Ze.subscriptions[t];n&&typeof n=="function"&&n(e);let o=r?.[t];o&&typeof o=="function"&&o(e)}function zL({engineName:t,methodName:e,params:r,err:n}){let o;return typeof n=="string"?o=n.toUpperCase():n instanceof Error&&(o=n.message),console.log("ERROR",{tournamentId:LC(),params:JSON.stringify(r),engine:t,methodName:e,error:o}),{error:o}}var ve={timers:{default:{elapsedTime:0}},globalSubscriptions:{},deepCopyAttributes:{stringify:[],ignore:[],toJSON:[]},globalMethods:[],deepCopy:!0},un=$A,FC=["addNotice","callListener","cycleMutationStatus","deleteNotice","deleteNotices","disableNotifications","enableNotifications","getMethods","getNotices","getTopics","getTournamentId","getTournamentRecord","getTournamentRecords","removeTournamentRecord","setSubscriptions","setTournamentId","setTournamentRecord","setTournamentRecords"];function QL(t){if(typeof t!="object")throw new Error("Global state provider can not be undefined or null");if(jt(Object.keys(t),FC).length!==FC.length)throw new Error("Global state provider is missing required methods");return un=t,{success:!0}}function KA(){if(un.createInstanceState){try{un.createInstanceState()}catch(t){return{error:t}}return{success:!0}}else return{error:wA}}function Dr(t){return!t||typeof t!="object"?ve.devContext??!1:typeof ve.devContext!="object"?!1:Object.keys(t).every(e=>ve.devContext?.[e]===t[e])&&ve.devContext}function XL(t="reset",e="default"){let r=Date.now();if(t==="report"){if(e==="allTimers")return Object.keys(ve.timers).filter(o=>o!=="default"||ve.timers[o].startTime).map(o=>{let i=ve.timers[o],s=i.state==="stopped"?0:(r-(i?.startTime??0))/1e3,a=i.elapsedTime+s;return{state:ve.timers[o].state,elapsedTime:a.toFixed(2),timer:o}});{let n=ve.timers[e].state==="stopped"?0:(r-(ve.timers[e]?.startTime??0))/1e3,o=ve.timers[e].elapsedTime+n;return{state:ve.timers[e].state,elapsedTime:o.toFixed(2),timer:e}}}if(!ve.timers[e]||t==="reset"){if(e==="allTimers")return ve.timers={default:{elapsedTime:0}},!0;ve.timers[e]={startTime:r,state:"active",elapsedTime:0}}return ve.timers[e].elapsedTime||(ve.timers[e].elapsedTime=0),t==="stop"&&ve.timers[e].state!=="stopped"&&(ve.timers[e].state="stopped")&&(ve.timers[e].elapsedTime+=(r-(ve.timers[e]?.startTime??0))/1e3),t==="start"&&(ve.timers[e].startTime=r)&&(ve.timers[e].state="active"),ve.timers[e]}function kC(t){Yr(t)?ve.globalLog=t:delete ve.globalLog}function Qc(t){ve.devContext=t}function zA(){un.disableNotifications()}function hf(){un.enableNotifications()}function Xc(t,e){typeof t=="boolean"&&(ve.deepCopy=t),typeof e=="object"&&(Array.isArray(e.ignore)&&(ve.deepCopyAttributes.ignore=e.ignore),Array.isArray(e.toJSON)&&(ve.deepCopyAttributes.toJSON=e.toJSON),Array.isArray(e.stringify)&&(ve.deepCopyAttributes.stringify=e.stringify),e.threshold&&(ve.deepCopyAttributes.threshold=e.threshold))}function Sf(){return{enabled:ve.deepCopy,...ve.deepCopyAttributes}}function JL(t){return t?.subscriptions?(Object.keys(t.subscriptions).forEach(e=>{ve.globalSubscriptions[e]=t.subscriptions[e]}),{...C}):{error:st,info:"missing subscriptions"}}function ZL(t){return t?.subscriptions?un.setSubscriptions({subscriptions:t.subscriptions}):{error:st,info:"missing subscriptions"}}function GC(t){return t?typeof t!="object"?{error:B}:(Object.keys(t).forEach(e=>{Yr(t[e])&&(ve.globalMethods[e]=t[e])}),{...C}):{error:st,info:"missing method declarations"}}function VC(t){return t?typeof t!="object"?{error:B}:un.setMethods(t):{error:st,info:"missing method declarations"}}function Tf(){return un.cycleMutationStatus()}function lt(t){if(typeof t?.topic!="string")return;let e=ve.globalSubscriptions[t.topic];return un.addNotice(t,e)}function yf(){return{...ve.globalMethods,...un.getMethods()}}function th(t){return un.getNotices(t)}function eh({key:t,topic:e}){return un.deleteNotice({key:t,topic:e})}function Yi(){return un.deleteNotices()}function Lr(){return un.getTopics()}function dp(t){return Lr()?.topics?.includes(t)}async function wm(t){return un.callListener(t,ve.globalSubscriptions)}function ms(){return un.getTournamentId()}function Ef(t){return un.getTournamentRecord(t)}function qo(){return un.getTournamentRecords()}function QA(t){return un.setTournamentRecord(t)}function Lm(t){return un.setTournamentRecords(t)}function lp(t){return un.setTournamentId(t)}function XA(t){return un.removeTournamentRecord(t)}function rh(){return un}function fp({engineName:t,methodName:e,params:r,err:n}){let o=Yr(un.handleCaughtError)&&un.handleCaughtError||$A.handleCaughtError,{tournamentRecord:i,...s}=r;return o({params:s,engineName:t,methodName:e,err:n})}function JA(t,e){if(ve.globalLog)try{ve.globalLog({log:t,engine:e})}catch(r){console.log("globalLog error",r),console.log(e,t),kC()}else console.log(e,t)}function ZA(t,e,r,n){if(!ht(t))return{error:B};Jt||(r=1);let o=Array.isArray(e)?e:[],i={},s=(a,c=0)=>{Object.keys(a).forEach(u=>{Yr(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?GC(i):VC(i),{methods:i}}function tF(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;Sf()?.enabled||(n=!0);let i=["",void 0,null];e&&i.push(!1);let s=tF(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&&(e.context||(e.context={}),Object.assign(e.context,nt(t))),e&&!e?.error&&!e?.success&&Object.assign(e,{...C}),e??{success:!0}}var lr="FEMALE",$o="OTHER",qi="MIXED",Le="MALE";var Fm={FEMALE_ABBR:"F",OTHER_ABBR:"O",MIXED_ABBR:"X",MALE_ABBR:"M",ANY_ABBR:"A",FEMALE:lr,MIXED:qi,OTHER:$o,MALE:Le,ANY:"ANY"};function $i(t){return[lr,"F"].includes(t)}function Hs(t){return[Le,"M"].includes(t)}function en(t){return[qi,"X"].includes(t)}function To(t){return["ANY","A"].includes(t)}function yr(t){if(t){if($i(t))return lr;if(en(t))return qi;if(Hs(t))return Le;if(To(t))return"ANY"}return $o}function Dn(t){return $i(t)||Hs(t)}var iF="MIXED events can not contain mixed singles or { gender: ANY } collections",sF="events with { gender: ANY } can not contain MIXED singles collections";function km(t){let e="tieFormatGenderValidityCheck",{referenceGender:r,matchUpType:n,gender:o}=t;return r&&o&&Dn(r)&&yr(r)!==yr(o)?_({result:{valid:!1,error:cp},context:{gender:o},stack:e}):en(r)&&(To(o)||en(o)&&n!==vt)?_({result:{error:cp,valid:!1},info:iF,stack:e}):To(r)&&en(o)&&n!==vt?_({result:{error:cp,valid:!1},info:sF,stack:e}):{valid:!0}}var aF="normal",tU="timed",cF="final",Af="NOAD";var HC={S:aF,F:cF};function gp(t,e){if(ht(t)&&(t?.bestOf||t?.exactly)&&t?.setFormat)return uF(t,e)}function Uf(t){return!Number.isNaN(Number(t))&&Number(t)}function YC(t){let e=`T${t.minutes}`;return t.based==="A"?e+="A":t.based==="P"&&(e+="P"),t.tiebreakFormat?.tiebreakTo&&(e+=`/TB${t.tiebreakFormat.tiebreakTo}`),t.modifier&&(e+=`@${t.modifier}`),e}function uF(t,e){let r=Uf(t.bestOf)||void 0,n=Uf(t.exactly)||void 0,o=r||n;if(t.setFormat?.timed&&t.simplified&&o===1)return YC(t.setFormat);let s=o&&`${"SET"}${o}${n&&n!==1?"X":""}`||"",a=WC(t.setFormat,e),c=a&&`S:${a}`||"",u=WC(t.finalSetFormat,e),p=o&&o>1&&u&&a!==u&&`F:${u}`||"";if(s&&a)return[s,c,p].filter(Boolean).join("-")}function WC(t,e){if(typeof t=="object"&&Object.keys(t).length){if(t.timed)return YC(t);if(t.tiebreakSet)return jC(t.tiebreakSet);let r=Uf(t.setTo);if(r){let n=t.NoAD&&Af||"",o=jC(t.tiebreakFormat),i=o&&`/${o}`||"",s=Uf(t.tiebreakAt),a=s&&(s!==r||e)&&`@${s}`||"";if(o!==!1)return`${r}${n}${i}${a}`}}}function jC(t){if(t){if(typeof t=="object"&&!t.tiebreakTo)return"";if(typeof t=="object"&&Uf(t.tiebreakTo)){let e=`TB${t.tiebreakTo}${t.NoAD?Af:""}`;return t.modifier&&(e+=`@${t.modifier}`),e}else return!1}}function Ne(t){if(kt(t)){let e=t.startsWith("T")&&tU||t.startsWith("SET")&&"SET"||"";if(e===tU){let r=zC(t),n={simplified:!0,setFormat:r,bestOf:1};if(r)return n}if(e==="SET")return pF(t)}}function pF(t){let e=t.split("-"),r=e[0].slice(3),n=r.endsWith("X"),o=n?r.slice(0,-1):r,i=Gm(o),s=n&&i!==1?void 0:i,a=n&&i!==1?i:void 0,c=e&&qC(e[1]),u=e&&qC(e[2]),p=c&&c.timed||u&&u.timed,m=s&&s<6||p&&a,d=!e[2]||u,l=c,f=nt({setFormat:c,exactly:a,bestOf:s});if(u&&(f.finalSetFormat=u),m&&l&&d)return f}function qC(t){if(t?.[1]!==":")return;let e=t.split(":"),r=HC[e[0]],n=e[1];if(!(!r||!n))return mF(t,n)}function mF(t,e){return e.startsWith("TB")?dF(e):e.startsWith("T")?zC(e):lF(t,e)}function dF(t){let e=KC(t);return e===!1?!1:typeof e=="object"?{tiebreakSet:e}:void 0}function lF(t,e){let r=/^[FS]:(\d+)([A-Za-z]*)/.exec(t),n=r&&QC(r[2])||!1,o=!r?.[2]||n,i=r?Gm(r[1]):void 0,s=$C(e),a=s!==!1,c=a&&s||i,u=KC(e.split("/")[1]);return!i||!o||!(u!==!1)||!a?!1:fF(i,n,u,c)}function fF(t,e,r,n){let o={setTo:t};return e&&(o.NoAD=!0),r?(o.tiebreakFormat=r,o.tiebreakAt=n):o.noTiebreak=!0,o}function $C(t,e=!0){let r=t?.indexOf("@")>0&&t.split("@");if(r)return(e?Gm(r[1]):r[1])||!1}function KC(t){if(t)return t.startsWith("TB")?gF(t):!1}function gF(t){let e=$C(t,!1),r=/^TB(\d+)([A-Za-z]*)/.exec(t),n=r?.[1],o=r&&QC(r[2]),i=!r?.[2]||o,s=Gm(n);if(!s||!i)return!1;let a={tiebreakTo:s};return e&&typeof e=="string"&&!It(e)&&(a.modifier=e),o&&(a.NoAD=!0),a}function zC(t){let e=t.slice(1),r=/^(\d+)([PGA])?(?:\/TB(\d+))?(@?[A-Za-z]*)?/.exec(e),n=Gm(r?.[1]);if(!n)return;let o={timed:!0,minutes:n},i=r?.[2];i==="A"?o.based="A":i==="P"?o.based="P":i==="G"&&(o.based="G");let s=r?.[3];if(s){let u=Gm(s);u&&(o.tiebreakFormat={tiebreakTo:u})}let a=r?.[4],c=[void 0,"P","G",""].includes(a);if(a&&!c){let u=/^(\d+)([PGA])?(?:\/TB\d+)?(@)([A-Za-z]+)$/.exec(e)?.[4];return u?(o.modifier=u,o):void 0}return a&&(o.based=a),o}function QC(t){return t?.includes(Af)}function Gm(t){let e=Number(t);return Number.isNaN(e)?0:e}function Nr({matchUpFormat:t}){if(!kt(t)||t==="")return!1;let e=Ne(t),r=/-S:([1-9])+\/TB(\d{1,2})@?([1-9]?)/.exec(t),n=r?.[1],o=r?.[2],i=r?.[3],s=/-F:([1-9])+\/TB(\d{1,2})@?([1-9]?)/.exec(t),a=s?.[1],c=s?.[2],u=s?.[3];return gp(e,!!(r&&o&&n===i||s&&c&&a===u))===t}var Vm=/^[\d]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][\d]|3[0-1])$/,nh=/^((0[\d]|1[\d]|2[0-3]):[0-5][\d](:[0-5][\d])?)([.,][0-9]{3})?$/,Oo=/^([\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 Bm(t){let{scheduledDate:e}=t;if(!e&&t.scheduledTime&&(e=Ut(t.scheduledTime)),!e)return;let r=zt(t.scheduledTime),n=Ut(e);return n&&r&&(n+=`T${r}`),n}function XC(t){return typeof t!="object"||Array.isArray(t)?!1:Object.prototype.toString.call(t)==="[object Date]"}function Jc(t){let e=typeof t=="string"?t?.split(" "):[];return t&&e?.length>1&&!["AM","PM"].includes(e[1].toUpperCase())?!1:!!(!t||Ws.test(ac(t,!0,!0)))}function Mr(t){return sc(t)||Vm.test(t)}function IF(t){let e=new Date(t),r=e.getSeconds()+60*e.getMinutes()+3600*e.getHours();return hF(r,{displaySeconds:!1})}function hF(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(oo).join(":")}var Mf=t=>{let e=Df(t)||sc(t)?new Date(t):new Date,r=e.getUTCMonth()+1,n=r<10?`0${r}`:`${r}`;return`${e.getUTCFullYear()}-${oo(n)}-${oo(e.getUTCDate())}`};function SF(t){let e=Df(t)||sc(t)?new Date(t):new Date;return Date.UTC(e.getFullYear(),e.getMonth(),e.getDate())}function Kn(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 oh(t){let e=t?new Date(t):new Date,r=e.getTimezoneOffset();return new Date(e.getTime()-r*60*1e3)}function TF(t){return oh(t).getTime()}function Df(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 js(t,e){if(!Mr(t)||!Mr(e))return[];let r=Ut(t)+"T00:00",n=Ut(e)+"T00:00",o=new Date(r),i=new Date(n),s=Df(i)&&Df(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=>Kn(p));function u(p,m){return p<=m}}var yF=/^([+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-2])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([.,]\d+(?!:))?)?(\17[0-5]\d([.,]\d+)?)?([zZ]|([+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/;function sc(t){return typeof t!="string"?!1:yF.test(t)}function sh(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=zt(t);if(!e)return 0;let[r,n]=e.split(":").map(o=>parseInt(o));return r*60+n}function JC(t){let e=Math.floor(t/60),r=t-e*60;return e>23&&(e=e%24),[oo(e),oo(r)].join(":")}function Nf(t){return sh(t)?t.split(":").slice(0,2).map(oo).join(":"):void 0}function zt(t){return sc(t)&&t.indexOf("T")>0?Nf(t.split("T").reverse()[0]):Nf(t)}function Ut(t){return sc(t)||Oo.test(t)?t.split("T")[0]:void 0}function Ip(t,e){let r=new Date(t);return r.setDate(r.getDate()+e),Ut(r.toISOString())}function ih(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 EF(t){let e=ih(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(oo).join(":")}function AF(t){let e=ih(t);if(!(typeof e=="object"&&!Object.keys(e).length))return e.ampm?t:(e.hours>12?(e.hours-=12,e.ampm="PM"):e.hours==="12"?e.ampm="PM":(e.hours==="00"&&(e.hours="12"),e.ampm="AM"),e.hours?.[0]==="0"&&(e.hours=e.hours.slice(1)),`${e.hours||"12"}:${e.minutes||"00"} ${e.ampm}`)}function ac(t,e,r){let n=Ut(t),o=zt(t),i=n?o:t;return t?e&&(n&&r&&t||EF(i))||AF(i):void 0}function ah(t,e){let r=ih(t),n=ih(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 ch(t,e=7){let r=Ut(t)+"T00:00",n=new Date(r),o=new Date(n.setDate(n.getDate()+e));return Kn(o)}function UF(t){return ch(t)}function PF(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())),Kn(o,r)}function ZC(t,e,r){let n=new Date(t,0);return Kn(new Date(n.setDate(e)),r)}function Ge(t,e=void 0){let[r,n]=(t||"00:00").split(":").map(oo),o=oh(e).setHours(r,n,0,0);return oh(o)}function ya(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 $r(t,e){let r=zt(t);if(!r)return"00:00";let n=isNaN(e)?0:e;return zt(Rf(Ge(r),n).toISOString())}function Rf(t,e){let r=new Date(t);return new Date(r.getTime()+e*6e4)}function oo(t){return t.toString()[1]?t:"0"+t}function zn(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 uh={addDays:ch,addWeek:UF,addMinutesToTimeString:$r,convertTime:ac,getIsoDateString:Bm,getUTCdateString:Mf,DateHHMM:IF,extractDate:Ut,extractTime:zt,formatDate:Kn,getDateByWeek:PF,isISODateString:sc,isDate:Df,isTimeString:sh,offsetDate:oh,offsetTime:TF,sameDay:zn,timeStringMinutes:Yt,timeToDate:Ge,timeUTC:SF,validTimeValue:Jc,validDateString:Vm,timeValidation:Ws,dateValidation:Oo};var DF=(t,e)=>t.filter(Boolean).every(r=>typeof r===e),NF=t=>t.filter(Boolean).every(Jt);function Ys(t){let e=t.category;if(typeof e!="object")return{error:zc};let{ageCategoryCode:r,ageMaxDate:n,ageMinDate:o,ageMax:i,ageMin:s}=e,a=e.categoryName,c;if(!(DF([r,n,o,a],"string")&&NF([i,s])&&[n,o].filter(Boolean).every(Mr)))return{error:zc};let p=t.consideredDate??Ut(new Date().toLocaleDateString("sv"));if(!Mr(p))return{error:Ye};let[m]=p.split("-").slice(0,3).map(k=>parseInt(k)),d=Ip(p,-1),[l,f]=d.split("-").slice(1,3).map(k=>parseInt(k)),g=`${oo(l)}-${oo(f)}`,I=Ip(p,1),[h,S]=I.split("-").slice(1,3).map(k=>parseInt(k)),T=`${oo(h)}-${oo(S)}`,y=s&&Ip(p,-1*365*s),E=i&&Ip(p,-1*365*i),P=[],A=k=>!P.includes(k)&&P.push(k);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=(k,G)=>`${k}-${G}`,O=k=>{let G=m-k,H=b(G,T);e.ageMinDate&&e.ageMinDate!==H&&A(`Invalid submitted ageMinDate: ${o}`),o=H,r&&(e.ageMax&&e.ageMax!==k-1&&(A(`Invalid submitted ageMax: ${i}`),E=void 0),i=k-1)},v=k=>{let G=m-k-1,H=b(G,T);e.ageMin&&e.ageMin>k&&A(`Invalid submitted ageMin: ${s}`),e.ageMax&&e.ageMax>k&&A(`Invalid submitted ageMax: ${i}`),e.ageMinDate&&e.ageMinDate!==H&&A(`Invalid submitted ageMinDate: ${o}`),o=H,r&&(e.ageMax&&e.ageMax!==k&&(A(`Invalid submitted ageMax: ${i}`),y=void 0),i=k)},x=k=>{let G=m-k,H=b(G,g);e.ageMaxDate&&e.ageMaxDate!==H&&A(`Invalid submitted ageMaxDate: ${n}`),n=H,r&&(e.ageMin&&e.ageMin!==k+1&&(A(`Invalid submitted ageMin: ${s}`),y=void 0),s=k+1)},F=k=>{let G=m-k-1,H=b(G,g);e.ageMaxDate&&e.ageMaxDate!==H&&A(`Invalid submitted ageMaxDate: ${n}`),n=H,r&&(e.ageMin&&e.ageMin!==k&&(A(`Invalid submitted ageMin: ${s}`),y=void 0),s=k)},w=k=>{let[G,H,K]=(k.match(U)||[]).slice(1),Y=parseInt(H);G==="U"?(e.ageMaxDate&&e.ageMaxDate!==n&&A(`Invalid submitted ageMaxDate: ${e.ageMaxDate}`),O(Y)):G==="O"&&x(Y),K==="U"?(e.ageMaxDate&&e.ageMaxDate!==n&&A(`Invalid submitted ageMaxDate: ${e.ageMaxDate}`),v(Y)):K==="O"&&F(Y),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[k,G]=(r?.match(N)??[]).slice(1).map(H=>parseInt(H));k<=G?(s=k,i=G,c=!0):A(`Invalid combined age range ${r}`)}else D?r?.split("-").forEach(w):R?w(r):(s&&x(s),i&&v(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 Zc({category:t}){if(!ht(t))return{error:B};let e=Ys({category:t});if(e.error)return{error:e};let{ratingMax:r,ratingMin:n}=t;return r&&!Jt(r)?_({result:{error:B},context:{ratingMax:r}}):n&&!Jt(n)?_({result:{error:B},context:{ratingMin:n}}):{...e}}function tu({childCategory:t,withDetails:e,category:r}){let n=Zc({category:r}),o=Zc({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 eu({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:So},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&&!Yc([Lt,vt],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=GI({collectionValueProfiles:u,matchUpCount:l});P.errors&&c.push(...P.errors)}if(p&&typeof p!="number"&&c.push(`collectionGroupNumber is not type number: ${m}`),f&&!Nr({matchUpFormat:f})&&c.push(`Invalid matchUpFormat: ${f}`),n){let P=km({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=tu({category:o,childCategory:T});if(!P.valid)return _({result:{error:zc},context:P,stack:a})}return c.length?_({result:{errors:c,error:VA},stack:a}):{valid:!0}}function ar(t){let e=!!(t?.enforceCategory!==!1&&t?.category),r=!!(t?.enforceGender!==!1&&t?.gender),n=t?.checkCollectionIds,o=t?.tieFormat,i=t?.event,s="validateTieFormat",a=[],c=MF({...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}=eu({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:Yo},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:Yo},context:{tieFormat:o,errors:a},stack:s})}function MF(t){let{tieFormat:e,stack:r}=t;return!t||!e||!ht(e)?_({result:{error:Yo},context:{tieFormat:e,message:"tieformat must be an object"},stack:r}):ht(e.winCriteria)?Array.isArray(e.collectionDefinitions)?{...C}:_({result:{error:Yo},context:{tieFormat:e,message:"collectionDefinitions must be an array"},stack:r}):_({result:{error:Yo},context:{tieFormat:e,message:"tieformat.winCritiera must be an object"},stack:r})}var cc="resourceSubType",uc="resourceType",pc="identifier",tb={RESOURCE_SUB_TYPE:cc,RESOURCE_TYPE:uc,IDENTIFIER:pc};function J(t,e,r,n,o=0){if(rh().makeDeepCopy)return rh().makeDeepCopy(t,e,r,n);let i=Sf(),{stringify:s,toJSON:a,ignore:c,modulate:u}=i||{};if(!i?.enabled&&!r||typeof t!="object"||Yr(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)||Yr(c)&&!c(l)),d=(l,f)=>{p[l]=Yr(f?.toString)?f.toString():JSON.stringify(f)};for(let l of m){let f=t[l],g=Yr(u)?u(f):void 0;if(g!==void 0)p[l]=g;else if(e&&l==="extensions"&&Array.isArray(f)){let I=Cf(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)&&Yr(f?.toJSON)?p[l]=f.toJSON():f===null?p[l]=void 0:XC(f)?p[l]=new Date(f).toISOString():p[l]=J(f,e,r,n,o+1)}return p}function Cf(t){return t?.map(e=>{let{name:r,value:n}=e;return r&&n&&{[`_${r}`]:n}}).filter(Boolean)}function ph(t=1,e){return tt(0,t).map(()=>Nt(e))}function Nt(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 mh={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 dh={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 lh={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 fh={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 gh={collectionDefinitions:[{collectionName:"Male Singles",gender:"MALE",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{collectionName:"Female Singles",gender:"FEMALE",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{collectionName:"Male Doubles",gender:"MALE",matchUpCount: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 Ih={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 hh={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 Sh={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 Th={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 yh={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 bn="SET3-S:6/TB7",kF="SET3-S:6NOAD",eU="SET3-S:6/TB7-F:TB10",GF="SET3-S:4/TB7",VF="SET3-S:4/TB5@3",BF="SET1-S:T20",HF="SET1-S:8/TB7",WF="SET1-S:8/TB7@7",eb={FORMAT_STANDARD:bn,FORMAT_STANDARD_NOAD:kF,FORMAT_ATP_DOUBLES:eU,FORMAT_SHORT_SETS:GF,FORMAT_FAST4:VF,FORMAT_PRO_SET:HF,FORMAT_COLLEGE_PRO_SET:WF,TIMED20:BF};var Eh={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 Ah={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 Uh={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 Ph={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 Dh={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 Nh={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 Mh={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 Hm="COLLEGE_DEFAULT",Rh="COLLEGE_JUCO",Ch="COLLEGE_D3",rU="DOMINANT_DUO",nU="DOMINANT_DUO_MIXED",oU="LAVER_CUP",iU="TEAM_DOUBLES_3_AGGREGATION",sU="TIME_TENNIS_DUAL",aU="TIME_TENNIS_PRO_CIRCUIT",cU="USTA_BREWER_CUP",uU="USTA_OZAKI_CUP",pU="USTA_COLLEGE",mU="USTA_GOLD_TEAM_CHALLENGE",dU="USTA_LEVEL_1",lU="USTA_INTERSECTIONAL",fU="USTA_SECTION_BATTLE",gU="USTA_SOUTHERN_LEVEL_5",IU="USTA_TOC",hU="USTA_WTT_ITT",SU="USTA_ZONAL",rb={COLLEGE_D3:Ch,COLLEGE_DEFAULT:Hm,COLLEGE_JUCO:Rh,DOMINANT_DUO:rU,DOMINANT_DUO_MIXED:nU,LAVER_CUP:oU,TEAM_DOUBLES_3_AGGREGATION:iU,TIME_TENNIS_DUAL:sU,TIME_TENNIS_PRO_CIRCUIT:aU,USTA_BREWER_CUP:cU,USTA_OZAKI_CUP:uU,USTA_COLLEGE:pU,USTA_GOLD_TEAM_CHALLENGE:mU,USTA_INTERSECTIONAL:lU,USTA_LEVEL_1:dU,USTA_SECTION_BATTLE:fU,USTA_SOUTHERN_LEVEL_5:gU,USTA_TOC:IU,USTA_WTT_ITT:hU,USTA_ZONAL:SU};var ob="STANDARD",nb={[ob]:{hydrate:!0,doubles:{matchUpCount:3,matchUpValue:1},singles:{matchUpCount:6,matchUpValue:1},valueGoal:5},[Ch]:{hydrate:!0,doubles:{matchUpFormat:"SET1-S:8/TB7@7",matchUpCount:3,matchUpValue:1},singles:{matchUpFormat:bn,matchUpCount:6,matchUpValue:1},tieFormatName:Ch,valueGoal:5},[Hm]:{hydrate:!0,doubles:{matchUpFormat:"SET1-S:6/TB7",collectionValue:1,matchUpCount:3},singles:{matchUpFormat:bn,matchUpCount:6,matchUpValue:1},tieFormatName:Hm,valueGoal:4},[Rh]:{hydrate:!0,doubles:{matchUpFormat:"SET1-S:8/TB7",matchUpCount:3,matchUpValue:1},singles:{matchUpFormat:bn,matchUpCount:6,matchUpValue:1},tieFormatName:Rh,valueGoal:5},[oU]:Nh,[rU]:Eh,[nU]:hh,[iU]:dh,[sU]:Sh,[aU]:Ih,[cU]:Th,[uU]:yh,[pU]:Ah,[mU]:mh,[lU]:gh,[dU]:Uh,[fU]:fh,[gU]:lh,[hU]:Ph,[IU]:Mh,[SU]:Dh},XF=t=>{let e=t?.namedFormat&&Object.keys(nb).includes(t.namedFormat)?t.namedFormat:ob,r=Array.isArray(t?.uuids)?t?.uuids:[],n,{category:o,gender:i}=t?.event??{},s=J(nb[e],!1,!0),a=c=>{if(!t?.isMock&&!t?.event?.isMock||!t.event)return r?.pop()??Nt();let u=t?.event?.eventId;return r.pop()??`${u}-COL-${c+1}`};return s.hydrate?(n={winCriteria:{valueGoal:s.valueGoal},collectionDefinitions:[{collectionId:a(0),matchUpFormat:eU,collectionName:"Doubles",matchUpType:vt,...s.doubles},{collectionId:a(1),matchUpFormat:bn,collectionName:"Singles",matchUpType:Lt,...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},io=XF;var Qn="SINGLES",qs="SINGLES",Kr="DOUBLES",Ko="DOUBLES",_e="TEAM",Or="TEAM";var JF="RATING",ZF="BOTH",ib={AGE:"AGE",BOTH:ZF,DOUBLES:Kr,DOUBLES_EVENT:Ko,RATING:JF,SINGLES:Qn,SINGLES_EVENT:qs,TEAM_EVENT:Or,TEAM:_e};var rt="MAIN",ct="QUALIFYING",qe="CONSOLATION",$e="VOLUNTARY_CONSOLATION",fe="PLAY_OFF",ru=[rt,ct,qe,fe,$e],$s={[ct]:1,[rt]:2,[fe]:3,[qe]:3,[$e]:4},TU="finishingPositions",yU="aggregateEventStructures",EU={[rt]:1,[fe]:2,[qe]:3,[ct]:4,[$e]:5},sb={[fe]:1,[rt]:2,[qe]:3,[ct]:4,[$e]:5},nu="CLUSTER",ab="SEPARATE",Ti="WATERFALL",hp="ITEM",Ve="CONTAINER",fn="DRAW",Sp="RANDOM",Nn="TOP_DOWN",yi="BOTTOM_UP",Fn="POSITION",Xn="WINNER",so="LOSER",kn="FIRST_MATCHUP",Fr="AD_HOC",tk="AD_HOC",Ea="FEED_IN",ou="COMPASS",iu="OLYMPIC",ek="SINGLE_ELIMINATION";var yo="SINGLE_ELIMINATION",su="DOUBLE_ELIMINATION",au="FIRST_MATCH_LOSER_CONSOLATION",Tp="FIRST_ROUND_LOSER_CONSOLATION",Ki="LUCKY_DRAW",bf="CURTIS_CONSOLATION",cb="CURTIS_CONSOLATION",bh="FEED_IN_CHAMPIONSHIP_TO_SF",Wm="FEED_IN_CHAMPIONSHIP_TO_SF",Oh="FEED_IN_CHAMPIONSHIP_TO_QF",jm="FEED_IN_CHAMPIONSHIP_TO_QF",vh="FEED_IN_CHAMPIONSHIP_TO_R16",Ym="FEED_IN_CHAMPIONSHIP_TO_R16",AU="MODIFIED_FEED_IN_CHAMPIONSHIP",qm="MODIFIED_FEED_IN_CHAMPIONSHIP",yp="FEED_IN_CHAMPIONSHIP",ub="DOUBLE_ROUND_ROBIN",On="ROUND_ROBIN",Eo="ROUND_ROBIN_WITH_PLAYOFF",UU="DECIDER",PU="BACKDRAW",Of={0:{name:"East",abbreviation:"E"},"0-1":{name:"West",abbreviation:"W"},"0-2":{name:"North",abbreviation:"N"},"0-3":{name:"Northeast",abbreviation:"NE"},"0-1-1":{name:"South",abbreviation:"S"},"0-1-2":{name:"Southwest",abbreviation:"SW"},"0-2-1":{name:"Northwest",abbreviation:"NW"},"0-1-1-1":{name:"Southeast",abbreviation:"SE"}},vf={0:{name:"East",abbreviation:"E"},"0-1":{name:"West",abbreviation:"W"},"0-2":{name:"North",abbreviation:"N"},"0-1-1":{name:"South",abbreviation:"S"}},Ei="WIN_RATIO",zi="ROUND_OUTCOME",DU=[ou,bf,jm,Ym,Wm,yp,Oh,vh,bh,au,Tp,Ki,qm,iu,fe,Eo],rk=[Fr,ou,bf,su,jm,Ym,Wm,yp,Ea,au,Tp,Ki,qm,iu,fe,On,Eo,yo],NU={MAIN:rt,QUALIFYING:ct,CONSOLATION:qe,ITEM:hp,CONTAINER:Ve,FIRST_MATCHUP:kn,WINNER:Xn,LOSER:so,AD_HOC:Fr,FEED_IN:Ea,FLEX_ROUNDS:tk,COMPASS:ou,PLAY_OFF:fe,OLYMPIC:iu,KNOCKOUT:ek,SINGLE_ELIMINATION:yo,DOUBLE_ELIMINATION:su,CURTIS:bf,FICSF:bh,FICQF:Oh,FICR16:vh,MFIC:AU,VOLUNTARY_CONSOLATION:$e,FIRST_MATCH_LOSER_CONSOLATION:au,FIRST_ROUND_LOSER_CONSOLATION:Tp,MODIFIED_FEED_IN_CHAMPIONSHIP:qm,FEED_IN_CHAMPIONSHIP_TO_R16:Ym,FEED_IN_CHAMPIONSHIP_TO_QF:jm,FEED_IN_CHAMPIONSHIP_TO_SF:Wm,FEED_IN_CHAMPIONSHIP:yp,LUCKY_DRAW:Ki,ROUND_ROBIN_WITH_PLAYOFF:Eo,ROUND_ROBIN:On,DECIDER:UU,BACKDRAW:PU,COMPASS_ATTRIBUTES:Of,OLYMPIC_ATTRIBUTES:vf,DRAW:fn,RANDOM:Sp,TOP_DOWN:Nn,BOTTOM_UP:yi,WATERFALL:Ti,WIN_RATIO:Ei,ROUND_OUTCOME:zi,MULTI_STRUCTURE_DRAWS:DU,generatedDrawTypes:rk,stageOrder:$s,finishOrder:EU,AGGREGATE_EVENT_STRUCTURES:yU,FINISHING_POSITIONS:TU},pb=NU;var Re="tournamentRecords",_f="policyDefinitions",ne="tournamentRecord",_h="onlineResource",Ce="drawDefinition",xh="tieFormatName",$m="matchUpFormat",ao="participantId",wh="scheduleDates",mb="tournamentId",db="scheduleDate",lb="roundNumber",cu="structureId",xf="participant",mc="matchUpIds",Lh="entryStage",fb="policyType",MU="structures",wf="eventType",gn="matchUpId",Km="tieFormat",uu="inContext",Ep="structure",Ap="courtIds",gb="personId",Up="venueIds",Lf="matchUps",Fh="courtId",kh="eventId",Gn="matchUp",Gh="drawId",In="error",co="event",ds="param",Ff="uuids",Ib="averageMatchUpMinutes",hb="recoveryMinutes",Sb="periodLength",Tb="number";var zr="object",Be="array";var tr="_validate",Vh="_message",kr="_invalid",He="_ofType",zm="_anyOf",Ks="_oneOf";var yb={[_h]:t=>jt(Object.keys(t),[cc,uc,pc]).length===3,[xh]:t=>t&&io({namedFormat:t}),[Ff]:t=>!t||Array.isArray(t)&&t.every(kt),[Km]:t=>!ar({tieFormat:t}).error,[wf]:t=>[Qn,Kr,_e].includes(t),[Lh]:t=>ru.includes(t)},nk={[Re]:xt,[ne]:q,[_f]:op,[Ce]:Z,[ao]:se,[$m]:Zl,[mb]:ha,[cu]:Pr,[mc]:ps,[xf]:Wi,[_h]:So,[wf]:$n,[MU]:Kl,[gn]:sr,[Km]:Yo,[Ep]:Si,[Fh]:Bi,[Lf]:no,[kh]:qr,[Gn]:mr,[Ap]:st,[Up]:st,[Gh]:cn,[co]:Ot},ok={[Re]:zr,[_f]:zr,[ne]:zr,[Ce]:zr,[_h]:zr,[wh]:Be,[xf]:zr,[mc]:Be,[MU]:Be,[Km]:zr,[Ep]:zr,[Ap]:Be,[Up]:Be,[Lf]:Be,[Gn]:zr,[co]:zr,[Ff]:Be};function et(t,e,r){if(!t&&!ht(t))return{error:B};if(!e?.length||t?._bypassParamCheck)return{valid:!0};if(!Array.isArray(e))return{error:B};let{paramError:n,errorParam:o}=ak(t,e);if(!n)return{valid:!0};let i=n[tr]&&(n[In]||n[kr])||t?.[o]===void 0&&(n[In]||n[kr]||nk[o]||B)||B,s=o??(n[Ks]&&Object.keys(n[Ks]).join(", "));return _({info:{param:s,message:n[Vh]},result:{error:i},stack:r})}function Eb(t,e){let r=Object.keys(t),n=Object.keys(e);return jt(r,n)}function ik(t,e){if(!e)return;let r=Eb(t,e);return r.length!==1?{error:B}:r.reduce((n,o)=>({...n,[o]:!0}),{})}function sk(t,e){if(!e)return;let r=Eb(t,e).filter(n=>t[n]);return r.length<1?{error:B}:r.reduce((n,o)=>({...n,[o]:!0}),{})}function ak(t,e){let r,n;return{paramError:e.find(({_ofType:i,_oneOf:s,_anyOf:a,_validate:c,_info:u,...p})=>{let m=s&&ik(t,s);if(m?.error)return m.error;m&&Object.assign(p,m);let d=a&&sk(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&&!Yr(c),h=t[g]!==void 0&&!c&&ck(t,g,i),S=p[g]&&[void 0,null].includes(t[g]),y=I||h||S||c&&t[g]!==void 0&&!uk(t[g],c)||yb[g]&&!yb[g](t[g]);return y&&(r=g,n=u),y});return!l.length||f}),errorParam:r,paramInfo:n}}function ck(t,e,r){return r=r||ok[e]||"string",r==="array"?!Array.isArray(t[e]):typeof t[e]!==r}function uk(t,e){return Yr(e)?e(t):!0}var Qm="DYNAMIC",Ai="RANKING",Ui="RATING",Pi="SCALE",Ao="SEEDING",Ab={RANKING:Ai,RATING:Ui,SCALE:Pi,SEEDING:Ao};function Aa(t){let e=et(t,[{[xf]:!0}]);if(e.error)return e;let r=t.participant.timeItems?.filter(({itemType:o})=>o?.startsWith(Pi)&&[Ai,Ui,Ao].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===Ao&&"seedings"||c===Ai&&"rankings"||"ratings";n[l][u]||(n[l][u]=[]),n[l][u].push({scaleValue:a.itemValue,scaleDate:a.itemDate,scaleName:d})}}}return{...C,...n}}function Qi(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 Bh="voluntaryConsolation",Di="competitiveBands",kf="roundRobinTally",Jn="positionActions",er="matchUpActions",Gf="rankingPoints",vo="roundNaming",zs="participant",pu="progression",_o="scheduling",mu="avoidance",pk="participant",mk="display",rn="scoring",Vn="seeding",dc="feedIn",dk="audit",Xm="draws",Ub={POLICY_TYPE_VOLUNTARY_CONSOLATION:Bh,POLICY_TYPE_COMPETITIVE_BANDS:Di,POLICY_TYPE_ROUND_ROBIN_TALLY:kf,POLICY_TYPE_POSITION_ACTIONS:Jn,POLICY_TYPE_MATCHUP_ACTIONS:er,POLICY_TYPE_RANKING_POINTS:Gf,POLICY_TYPE_ROUND_NAMING:vo,POLICY_TYPE_PARTICIPANT:zs,POLICY_TYPE_PROGRESSION:pu,POLICY_TYPE_SCHEDULING:_o,POLICY_TYPE_AVOIDANCE:mu,POLICY_TYPE_DISPLAY:mk,POLICY_TYPE_PRIVACY:pk,POLICY_TYPE_FEED_IN:dc,POLICY_TYPE_SCORING:rn,POLICY_TYPE_SEEDING:Vn,POLICY_TYPE_AUDIT:dk,POLICY_TYPE_DRAWS:Xm};function zo({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?.[zs];if(r?.withScaleValues){let{ratings:u,rankings:p}=Aa({participant:a});a.rankings=p,a.ratings=u}if(c?.participant)return Qi({template:c.participant,source:a})}return a}var Pb="element required",Db="missing name";function Ir(t){if(!t||typeof t!="object")return{error:st};if(t.element&&typeof t?.element!="object")return{error:B};if(!t?.name)return{error:st,info:Db};if(!t?.element){if(t.discover&&t.tournamentRecords){for(let e of Object.keys(t.tournamentRecords)){let r=t.tournamentRecords[e],n=Ir({element:r,name:t.name});if(n.error)return _({result:n,stack:"removeExtension"})}return{...C}}return{error:st,info:Pb}}return t?.element.extensions?(t.element.extensions=t.element.extensions.filter(e=>e?.name!==t.name),{...C}):{...C,info:Oe}}function Bn({requiredAttributes:t=["name","value"],extension:e}){if(!e||typeof e!="object"||typeof e.name!="string")return!1;let r=Object.keys(e);return t.filter(n=>r.includes(n)).length===t.length}function At(t){if(typeof t!="object")return{error:st};let e="addExtension";if(t?.element&&typeof t.element!="object")return _({result:{error:B},stack:e});if(!Bn({extension:t.extension}))return _({result:{error:B,info:"invalid extension"},stack:e});if(!t.element)if(t.discover&&!t.tournamentId&&t.tournamentRecords){for(let o of Object.values(t.tournamentRecords)){let i=At({extension:t.extension,element:o});if(i.error)return _({result:i,stack:e})}return{...C}}else return _({result:{error:st},stack:e});if(t.element.extensions||(t.element.extensions=[]),t?.creationTime??!0){let o=new Date().toISOString();Object.assign(t.extension,{createdAt:o})}let n=t.element.extensions.find(({name:o})=>o===t.extension.name);return n?n.value=t.extension.value:t.extension.value&&t.element.extensions.push(t.extension),{...C}}function Vf(t){return!t||typeof t!="object"?{error:st}:t.tournamentRecord?At({creationTime:t.creationTime,element:t.tournamentRecord,extension:t.extension}):{error:q}}function Pp(t){return!t||typeof t!="object"?{error:st}:t.drawDefinition?At({creationTime:t.creationTime,element:t.drawDefinition,extension:t.extension}):{error:br}}function xo(t){return!t||typeof t!="object"?{error:st}:t.event?At({creationTime:t.creationTime,extension:t.extension,element:t.event}):{error:qr}}function RU(t){if(!t||typeof t!="object")return{error:st};if(!t.participantId)return{error:se};let e=t.tournamentRecord?.participants||[],r=zo({participantId:t.participantId,tournamentParticipants:e});return r?At({creationTime:t.creationTime,extension:t.extension,element:r}):{error:re}}function Bf(t){return!t||typeof t!="object"?{error:st}:t.tournamentRecord?Ir({element:t.tournamentRecord,name:t.name}):{error:q}}function CU(t){return!t||typeof t!="object"?{error:st}:t.drawDefinition?Ir({element:t.drawDefinition,name:t.name}):{error:br}}function Dp(t){return!t||typeof t!="object"?{error:st}:t?.event?Ir({element:t.event,name:t.name}):{error:qr}}function bU(t){if(!t||typeof t!="object")return{error:st};if(!t.participantId)return{error:se};let e=t.tournamentRecord?.participants||[],r=zo({participantId:t.participantId,tournamentParticipants:e});return r?Ir({element:r,name:t.name}):{error:re}}function Np({tournamentRecords:t}){return{tournamentIds:ht(t)?Object.keys(t):[],...C}}var lk="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:Oe}}return _({result:{error:st},stack:lk})}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:Oe}}var fk="activeSuspension",du="appliedPolicies",OU="context",Jm="delegatedOutcome",uo="disabled",Ua="disableAutoCalc",Zm="disableLinks",td="display",Pa="drawDeletions",gk="drawProfile",ed="entryProfile",Ik="eventProfile",hk="eventWithdrawalRequests",Sk="factory",pn="flightProfile",Hh="groupingAttribute",wo="lineUps",Qs="linkedTournamentsIds",rd="matchUpHistory",Wh="participantRepresentatives",Da="personRequests",lc="positionActions",Tk="rankingPoints",yk="registration",vn="roundTarget",lu="scheduleLimits",Qo="scheduleTiming",Na="schedulingProfile",Ek="statusDetail",fc="subOrder",Lo="tally",nd="tieFormatModification",jh={ACTIVE_SUSPENSION:fk,APPLIED_POLICIES:du,CONTEXT:OU,DELEGATED_OUTCOME:Jm,DISABLED:uo,DISABLE_LINKS:Zm,DISABLE_AUTO_CALC:Ua,DISPLAY:td,DRAW_DELETIONS:Pa,DRAW_PROFILE:gk,ENTRY_PROFILE:ed,EVENT_PROFILE:Ik,EVENT_WITHDRAWAL_REQUESTS:hk,FLIGHT_PROFILE:pn,GROUPING_ATTRIBUTE:Hh,LINEUPS:wo,LINKED_TOURNAMENTS:Qs,MATCHUP_HISTORY:rd,PARTICIPANT_REPRESENTATIVES:Wh,PERSON_REQUESTS:Da,POSITION_ACTIONS:lc,RANKING_POINTS:Tk,REGISTRATION:yk,ROUND_TARGET:vn,SCHEDULE_LIMITS:lu,SCHEDULE_TIMING:Qo,SCHEDULING_PROFILE:Na,STATUS_DETAIL:Ek,SUB_ORDER:fc,TALLY:Lo,TIE_FORMAT_MODIFICATIONS:nd,FACTORY:Sk},vU=[Jm,uo,Ua,Zm,pn,wo,Qs,rd,Wh,Da,vn,lu,Qo,Na,fc,Lo,nd];function _U({tournamentRecords:t}){if(typeof t!="object"||!Object.keys(t).length)return{error:xt};let e=Np({tournamentRecords:t}),{tournamentIds:r}=e;return r?.length>1?At({tournamentRecords:t,discover:!0,extension:{name:Qs,value:{tournamentIds:r}}}):{...C}}function xU({tournamentRecords:t}){if(typeof t!="object"||!Object.keys(t).length)return{error:xt};let e=Ir({name:Qs,tournamentRecords:t,discover:!0});return _({result:e,stack:"unlinkTournaments"})}function wU({tournamentRecords:t,tournamentId:e}){if(typeof t!="object")return{error:B};if(!e)return{error:ha};let r=Np({tournamentRecords:t}),{tournamentIds:n}=r;if(!n.includes(e))return{error:ha};let o;return n.every(i=>{let s=t[i],{extension:a}=mt({element:s,name:Qs});if(!a)return!0;let c=a?.value?.tournamentIds||[];if(!c?.length||c.length===1&&c.includes(e)||i===e){let m=Bf({name:Qs,tournamentRecord:s});return m.error&&(o=m.error),m.success}let u=c.filter(m=>m!==e);a.value={tournamentIds:u};let p=Vf({tournamentRecord:s,extension:a});return p.error&&(o=p.error),p.success}),o?{error:o}:{...C}}var FU={};Xt(FU,{getLinkedTournamentIds:()=>fu,getTournamentIds:()=>Np});function fu({tournamentRecords:t}){return typeof t!="object"||!Object.keys(t).length?{error:xt}:{linkedTournamentIds:Object.assign({},...Object.keys(t).map(r=>{let n=t[r],o=n?.tournamentId,{extension:i}=mt({element:n,name:Qs}),s=(i?.value?.tournamentIds||[]).filter(a=>a!==o);return{[r]:s}}))}}var GN={};Xt(GN,{adHocPositionSwap:()=>zP,addAdHocMatchUps:()=>Gd,addDrawDefinitionTimeItem:()=>Og,addFinishingRounds:()=>ba,addGoesTo:()=>rs,addPlayoffStructures:()=>Kp,addQualifyingStructure:()=>KP,addVoluntaryConsolationStage:()=>HP,addVoluntaryConsolationStructure:()=>Eg,allPlayoffPositionsFilled:()=>WS,alternateDrawPositionAssignment:()=>bP,assignDrawPosition:()=>uD,assignDrawPositionBye:()=>Wr,attachConsolationStructures:()=>iD,attachPlayoffStructures:()=>Vg,attachQualifyingStructure:()=>bg,attachStructures:()=>Bg,autoSeeding:()=>ux,automatedPlayoffPositioning:()=>na,automatedPositioning:()=>Mc,checkValidEntries:()=>Hd,deleteAdHocMatchUps:()=>pD,drawMatic:()=>tl,findDrawDefinition:()=>gT,generateAdHocMatchUps:()=>Wu,generateAdHocRounds:()=>Zd,generateAndPopulatePlayoffStructures:()=>kd,generateDrawDefinition:()=>Wa,generateDrawMaticRound:()=>qd,generateDrawStructuresAndLinks:()=>Wd,generateDrawTypeAndModifyDrawDefinition:()=>jd,generateQualifyingStructure:()=>_d,generateVoluntaryConsolation:()=>LT,getAssignedParticipantIds:()=>wi,getAvailableMatchUpsCount:()=>Vd,getAvailablePlayoffProfiles:()=>Lu,getDrawDefinitionTimeItem:()=>iS,getDrawParticipantRepresentativeIds:()=>lT,getDrawStructures:()=>hn,getDrawTypeCoercion:()=>Bu,getEligibleVoluntaryConsolationParticipants:()=>dT,getMatchUpsMap:()=>Pe,getParticipantIdFinishingPositions:()=>fT,getPositionAssignments:()=>zp,getPositionsPlayedOff:()=>Cc,getRandomQualifierList:()=>RT,getSeedingThresholds:()=>_S,getSeedsCount:()=>Hu,getStructureSeedAssignments:()=>sn,getTeamLineUp:()=>Ss,getValidGroupSizes:()=>Gp,isAdHoc:()=>cr,isCompletedStructure:()=>Do,isValidForQualifying:()=>CT,luckyLoserDrawPositionAssignment:()=>NP,modifyDrawDefinition:()=>sD,modifyDrawName:()=>Hg,modifySeedAssignment:()=>FP,mutate:()=>lD,positionActions:()=>MT,pruneDrawDefinition:()=>cD,qualifierDrawPositionAssignment:()=>Cg,qualifierProgression:()=>kP,query:()=>PD,removeDrawPositionAssignment:()=>Ou,removeRoundMatchUps:()=>mD,removeSeededParticipant:()=>$P,removeStructure:()=>BP,renameStructures:()=>VP,resetDrawDefinition:()=>aD,resetQualifyingStructure:()=>WP,resetVoluntaryConsolationStructure:()=>KU,setDrawParticipantRepresentativeIds:()=>VU,setPositionAssignments:()=>RP,setStructureOrder:()=>GP,setSubOrder:()=>dD,shiftAdHocRounds:()=>MP,swapAdHocRounds:()=>CP,swapDrawPositionAssignments:()=>qP,updateTeamLineUp:()=>os,withdrawParticipantAtDrawPosition:()=>PP});var lD={};Xt(lD,{adHocPositionSwap:()=>zP,addAdHocMatchUps:()=>Gd,addDrawDefinitionTimeItem:()=>Og,addPlayoffStructures:()=>Kp,addQualifyingStructure:()=>KP,addVoluntaryConsolationStage:()=>HP,addVoluntaryConsolationStructure:()=>Eg,alternateDrawPositionAssignment:()=>bP,assignDrawPosition:()=>uD,assignDrawPositionBye:()=>Wr,attachConsolationStructures:()=>iD,attachPlayoffStructures:()=>Vg,attachQualifyingStructure:()=>bg,attachStructures:()=>Bg,automatedPlayoffPositioning:()=>na,automatedPositioning:()=>Mc,deleteAdHocMatchUps:()=>pD,luckyLoserDrawPositionAssignment:()=>NP,modifyDrawDefinition:()=>sD,modifyDrawName:()=>Hg,modifySeedAssignment:()=>FP,pruneDrawDefinition:()=>cD,qualifierDrawPositionAssignment:()=>Cg,qualifierProgression:()=>kP,removeDrawPositionAssignment:()=>Ou,removeRoundMatchUps:()=>mD,removeSeededParticipant:()=>$P,removeStructure:()=>BP,renameStructures:()=>VP,resetDrawDefinition:()=>aD,resetQualifyingStructure:()=>WP,resetVoluntaryConsolationStructure:()=>KU,setDrawParticipantRepresentativeIds:()=>VU,setPositionAssignments:()=>RP,setStructureOrder:()=>GP,setSubOrder:()=>dD,shiftAdHocRounds:()=>MP,swapAdHocRounds:()=>CP,swapDrawPositionAssignments:()=>qP,updateTeamLineUp:()=>os,withdrawParticipantAtDrawPosition:()=>PP});var GU=t=>e=>t[e],od=(t=[])=>t.map(Ue).filter(Boolean),Hf=(t=[])=>t.map(St).filter(Boolean),St=(t={})=>GU(t)("participantId");var Ue=(t={})=>GU(t)("matchUpId"),gu=(t={})=>GU(t)("drawId");function VU({representativeParticipantIds:t,drawDefinition:e}){if(!e)return{error:br};if(!Array.isArray(t))return{error:B};let r=Hf(e?.entries||[]);return t.length&&jt(t,r).length<t.length?{error:B}:Pp({drawDefinition:e,extension:{name:Wh,value:t}})}var vr="ABANDONED",gc="AWAITING_RESULT";var po="CANCELLED",ge="COMPLETED",Iu="DEAD_RUBBER",Gt="DEFAULTED",be="DOUBLE_DEFAULT",oe="DOUBLE_WALKOVER",Hn="IN_PROGRESS",mn="INCOMPLETE",BU="NOT_PLAYED",Me="RETIRED",ls="SUSPENDED",Qt="TO_BE_PLAYED",Bt="WALKOVER",Nb=[gc,ge,Gt,Hn,mn,Me,ls],Yh=[gc,ge,Gt,oe,be,Hn,mn,Me,ls,Bt],qh=[vr,gc,"BYE",po,ge,Iu,Gt,oe,be,Hn,mn,BU,Me,ls,Qt,Bt],$h=["BYE",oe,be,ge,Gt,Me,Bt],Kh=[vr,gc,po,Iu,Hn,mn,BU,ls,Qt,void 0],ae=[po,vr,ge,Iu,Gt,oe,be,Me,Bt],id=[vr,ge,Gt,oe,be,Hn,Me,Bt],zh=[Hn,mn,ls,Qt],Qh={ABANDONED:vr,AWAITING_RESULT:gc,BYE:"BYE",CANCELLED:po,COMPLETED:ge,DEAD_RUBBER:Iu,DEFAULTED:Gt,DOUBLE_WALKOVER:oe,DOUBLE_DEFAULT:be,IN_PROGRESS:Hn,INCOMPLETE:mn,NOT_PLAYED:BU,RETIRED:Me,SUSPENDED:ls,TO_BE_PLAYED:Qt,WALKOVER:Bt};function Ni(t,e,r){let n=m=>mt({element:m,name:vn})?.extension?.value,o=r?.deprioritizeCompleted,i=r?.mode===yU&&sb,s=r?.mode===TU&&EU,a=s||i||$s,c=m=>m?.stage===rt&&m?.stageSequence===1,u=m=>c(m)?-1:a[m?.stage],p=m=>m?.matchUps.every(({matchUpStatus:d})=>ae.includes(d)?1:-1);return o&&p(t)-p(e)||i&&u(t)-u(e)||(t?.stage&&a[t.stage]||0)-(e?.stage&&a[e.stage]||0)||(n(t)||0)-(n(e)||0)||!s&&!i&&(e?.positionAssignments?.length??1/0)-(t?.positionAssignments?.length??1/0)||(t?.stageSequence??0)-(e?.stageSequence??0)||(Wf(t)||0)-(Wf(e)||0)}function Wf(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,[cu]:!0}]);if(e.error)return e;let{drawDefinition:r,structureId:n}=t,{structures:o}=hn({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:_t};let a=s.structureType===hp?i?.find(c=>c.structures?.some(u=>u.structureId===n)):void 0;return{structure:s,containingStructure:a}}function hn({withStageGrouping:t,drawDefinition:e,stageSequences:r,stageSequence:n,roundTarget:o,sortConfig:i,stages:s,stage:a}){let c=!e&&Z||!e?.structures&&Kl||void 0;if(c)return{error:c,structures:[],stageStructures:{}};let u=f=>{let g=mt({element:f,name:vn})?.extension?.value;return!o||o===g},p=e?.structures?.filter(d).filter(l).filter(u).sort((f,g)=>Ni(f,g,i))??[],m=t?Object.assign({},...ru.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 Xh({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=sA,{positionAssignments:o,error:n}}function Ie({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 jf="addDrawDefinition",Mp="addMatchUps",ci="addParticipants",Yf="addScaleItems",HU="addEvent",Jh="addVenue",Mi="audit",Zh="dataIssue",qf="deleteParticipants",$f="deleteVenue",Kf="deletedDrawIds",zf="deletedMatchUpIds",Qf="modifyDrawDefinition",WU="modifyDrawEntries",jU="modifyEventEntries",Xf="modifyMatchUp",rr="modifyParticipants",Jf="modifyPositionAssignments",Zf="modifySeedAssignments",Xi="modifyTournamentDetail",Ri="modifyVenue",sd="mutations",tS="publishEvent",YU="publishEventSeeding",qU="publishOrderOfPlay",$U="publishParticipants",tg="unPublishEvent",eg="unPublishEventSeeding",rg="unPublishOrderOfPlay",Mb="unPublishParticipants",Rp="updateInContextMatchUp",Rb={ADD_DRAW_DEFINITION:jf,ADD_MATCHUPS:Mp,ADD_PARTICIPANTS:ci,ADD_SCALE_ITEMS:Yf,ADD_EVENT:HU,ADD_VENUE:Jh,AUDIT:Mi,DATA_ISSUE:Zh,DELETE_PARTICIPANTS:qf,DELETE_VENUE:$f,DELETED_DRAW_IDS:Kf,DELETED_MATCHUP_IDS:zf,MODIFY_DRAW_DEFINITION:Qf,MODIFY_DRAW_ENTRIES:WU,MODIFY_EVENT_ENTRIES:jU,MODIFY_MATCHUP:Xf,MODIFY_PARTICIPANTS:rr,MODIFY_POSITION_ASSIGNMENTS:Jf,MODIFY_SEED_ASSIGNMENTS:Zf,MODIFY_TOURNAMENT_DETAIL:Xi,MODIFY_VENUE:Ri,MUTATIONS:sd,PUBLISH_EVENT_SEEDING:YU,PUBLISH_EVENT:tS,PUBLISH_ORDER_OF_PLAY:qU,PUBLISH_PARTICIPANTS:$U,UNPUBLISH_EVENT_SEEDING:eg,UNPUBLISH_EVENT:tg,UNPUBLISH_ORDER_OF_PLAY:rg,UPDATE_INCONTEXT_MATCHUP:Rp};function eS(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 Fo({drawDefinition:t,tournamentId:e,matchUps:r,eventId:n}){return t&&eS(t),lt({payload:{matchUps:r,tournamentId:e,eventId:n},topic:Mp}),{...C}}function _n({drawDefinition:t,tournamentId:e,matchUpIds:r,eventId:n,action:o}){t&&eS(t),lt({topic:zf,payload:{tournamentId:e,matchUpIds:r,eventId:n,action:o}});for(let i of r)eh({key:i});return{...C}}function gt({drawDefinition:t,tournamentId:e,structureId:r,context:n,eventId:o,matchUp:i}){return i?(t&&bt({drawDefinition:t,structureIds:r?[r]:void 0,tournamentId:e,eventId:o}),lt({topic:Xf,payload:{matchUp:i,tournamentId:e,context:n},key:i.matchUpId}),{...C}):(console.log(mr),{error:mr})}function Cb({tournamentId:t,inContextMatchUp:e}){return e?(lt({payload:{inContextMatchUp:e,tournamentId:t},topic:Rp,key:e.matchUpId}),{...C}):{error:mr}}function Ma({tournamentId:t,eventId:e,drawDefinition:r}){return r?(eS(r),lt({payload:{drawDefinition:r,tournamentId:t,eventId:e},topic:jf,key:r.drawId}),{...C}):(console.log(Z),{error:Z})}function bb({tournamentId:t,eventId:e,drawId:r}){return lt({payload:{drawId:r,tournamentId:t,eventId:e},topic:Kf,key:r}),eh({key:r}),{...C}}function bt({drawDefinition:t,tournamentId:e,structureIds:r,eventId:n}){return t?(eS(t,r),lt({payload:{tournamentId:e,eventId:n,drawDefinition:t},topic:Qf,key:t.drawId}),{...C}):{error:Z}}function rS({drawDefinition:t,tournamentId:e,structure:r,eventId:n}){if(!t)return{error:Z};if(!r)return{error:Si};let o=r.seedAssignments,i=r.structureId,s=t.drawId;return lt({payload:{tournamentId:e,eventId:n,drawId:s,structureId:i,seedAssignments:o},topic:Zf,key:t.drawId}),bt({structureIds:[i],drawDefinition:t,tournamentId:e,eventId:n}),{...C}}function ko({drawDefinition:t,tournamentId:e,structure:r,event:n}){if(!t)return{error:Z};if(!r)return{error:Si};let o=Ct({structure:r}),i=r.structureId,s=t.drawId,a=n?.eventId;return lt({topic:Jf,payload:{positionAssignments:o,tournamentId:e,structureId:i,eventId:a,drawId:s},key:i}),bt({structureIds:[i],drawDefinition:t,tournamentId:e,eventId:a}),{...C}}function KU({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:_t};let i=o.matchUps?.map(({matchUpId:s})=>s)||[];return o.positionAssignments=[],o.seedAssignments=[],o.matchUps=[],_n({tournamentId:t?.tournamentId,action:"resetVoluntaryConsolationStructure",matchUpIds:i,drawDefinition:e}),r&&(e.entries=e.entries.filter(s=>s.entryStage!==$e)),bt({tournamentId:t?.tournamentId,eventId:n?.eventId,drawDefinition:e,structureIds:[o.structureId]}),{...C}}function ad({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=>{At({element:o,extension:{name:Zm,value:!0}})})}function hu(t){let{appliedPolicies:e,positionAction:r,drawDefinition:n}=t;if(e?.audit?.[lc]===!1)return;let{extension:o}=mt({name:lc,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:lc};At({element:n,extension:s})}function fs({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 Su(t){let{sides:e,matchUpType:r}=t||{},n=t.potentialParticipants?.length?t.potentialParticipants.flat().map(s=>r===vt?s?.individualParticipantIds||[]:s.participantId).flat():[],o=(e||[]).map(s=>r===vt&&(s?.participant?.individualParticipantIds||[])||s?.participantId&&[s.participantId]||[]).flat();return{individualParticipantIds:o.concat(n).flat(),enteredIndividualParticipantIds:o,potentialIndividualParticipantIds:n}}function Rr(t){return t?.tournamentRecords??(t?.tournamentRecord&&{[t.tournamentRecord.tournamentId]:t.tournamentRecord})??{}}var Ic="SIGN_IN_STATUS",zU="SIGNED_OUT",Tu="SIGNED_IN",Ar="TEAM",Et="INDIVIDUAL",Qr="GROUP",ft="PAIR",wt="TEAM",yu={TEAM_PARTICIPANT:Ar,INDIVIDUAL:Et,GROUP:Qr,TEAM:wt,PAIR:ft},Ob={INDIVIDUAL:Et,GROUP:Qr,PAIR:ft,TEAM:wt,SIGN_IN_STATUS:Ic,SIGNED_OUT:zU,SIGNED_IN:Tu};function Eu({participantsProfile:t,participants:e=[],deepCopy:r}){let n=new Map,o=r!==!1?J(e,t?.convertExtensions,!0):e,i=o.filter(c=>c.participantType===wt),s=o.filter(c=>c.participantType===Qr),a=o.filter(c=>c.participantType===ft);return o.forEach(c=>{if(c.participantType===Et){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 QU(t){return t&&typeof String.fromCodePoint<"u"?t.toUpperCase().replace(/./g,e=>String.fromCodePoint(e.charCodeAt(0)+127397)):t}function vb(t){let e=Object.assign({},...ui.filter(r=>r.ioc).map(r=>({[r.ioc]:r.iso})));return QU(e[t])}var ui=[{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 nS({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=ui.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 _b({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?Qi({template:e,source:s}):s)}}}}function Uo(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 oS(t){let{tournamentRecord:e,participantId:r}=t;if(r){let o=Uo({tournamentRecord:e,participantId:r});return o.participant??o}let n=t.element||t.drawDefinition||t.event||t.tournamentRecord;return n||{error:st}}function nn(t){let{returnPreviousValues:e,itemSubTypes:r,itemType:n}=t,o=oS(t);if(o.error)return o;if(r&&!Array.isArray(r))return{error:B,context:{itemSubTypes:r}};if(!Array.isArray(o.timeItems))return{error:df};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:Oe}}function iS({returnPreviousValues:t,drawDefinition:e,itemSubTypes:r,itemType:n}){if(!e)return{error:cn};if(!e.timeItems)return{info:Oe};let{timeItem:o,previousItems:i,info:s}=nn({element:e,returnPreviousValues:t,itemSubTypes:r,itemType:n});return o&&{timeItem:o,previousItems:i}||{info:s}}function Au({returnPreviousValues:t,itemSubTypes:e,itemType:r,event:n}){if(!n)return{error:Ot};if(!n.timeItems)return{info:Oe};let{timeItem:o,previousItems:i,info:s}=nn({returnPreviousValues:t,element:n,itemSubTypes:e,itemType:r});return o&&{timeItem:o,previousItems:i}||{info:s}}function cd({returnPreviousValues:t,tournamentRecord:e,itemSubTypes:r,itemType:n}){if(!e)return{error:q};if(!e.timeItems)return{info:Oe};let{timeItem:o,previousItems:i,info:s}=nn({element:e,returnPreviousValues:t,itemSubTypes:r,itemType:n});return o&&{timeItem:o,previousItems:i}||{info:s}}function sS({returnPreviousValues:t,tournamentRecord:e,participantId:r,itemSubTypes:n,itemType:o}){if(!e)return{error:q};if(!r)return{error:se};let i=Uo({tournamentRecord:e,participantId:r});if(i.error)return i;let{participant:s}=i;if(!s?.timeItems)return{info:Oe};let{timeItem:a,previousItems:c,info:u}=nn({element:i.participant,returnPreviousValues:t,itemSubTypes:n,itemType:o});return a&&{timeItem:a,previousItems:c}||{info:u}}var Ak={[Qr]:"groupParticipantIds",[ft]:"pairParticipantIds",[wt]:"teamParticipantIds"},Uk={[Qr]:"groups",[wt]:"teams"};function aS({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&&Nk({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=Dk({individualParticipantIds:g,participantCopy:l,participantMap:p,participantType:I,participantId:f});h.missingParticipantIds.length&&u.push(...h.missingParticipantIds)}if(n&&(p[f].participant.signedIn=Pk(l)),o){let{ratings:h,rankings:S,seedings:T}=Aa({participant:l});p[f].participant.seedings=T,p[f].participant.rankings=S,p[f].participant.ratings=h}(c||a)&&nS({participant:p[f].participant,withISO2:a,withIOC:c})}if(t){let d=ht(t)?t:void 0;_b({participantMap:p,template:d})}let m;return i&&(m=Eu({participants:Object.values(p).map(({participant:d})=>d),participantsProfile:{convertExtensions:e},deepCopy:!1}).groupInfo),{missingParticipantIds:u,participantMap:p,groupInfo:m}}function Pk(t){let{timeItem:e}=nn({itemType:Ic,element:t});return e?.itemValue===Tu}function Dk({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[Ak[n]].push(o),[wt,Qr].includes(n)){let{participantRoleResponsibilities:c,participantOtherName:u,participantName:p,participantId:m,teamId:d}=e,l=Uk[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 Nk({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:{[Lt]:{...r},[vt]:{...r},[wt]:{...r},...r}}}function Xo({participantsProfile:t,useParticipantMap:e,tournamentRecord:r,contextProfile:n,inContext:o}){if(e)return aS({...t,...n,tournamentRecord:r});let i=J(r.participants,!1,!0)||[];(t?.withIOC||t?.withISO2)&&i.forEach(a=>nS({participant:a,...t}));let s;if((o||t?.withGroupings)&&i?.length&&({participantsWithGroupings:i,groupInfo:s}=Eu({participantsProfile:t,deepCopy:!1,participants:i})),t?.withScaleValues&&i?.length)for(let a of i){let{ratings:c,rankings:u}=Aa({participant:a});a.rankings=u,a.ratings=c}return{participants:i,groupInfo:s}}function Tt({onlySpecifiedPolicyTypes:t=!1,policyTypes:e=[],tournamentRecord:r,drawDefinition:n,structure:o,event:i}){if(!Array.isArray(e))return{error:YI};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===du)?.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 Go({policyTypes:t=[],tournamentRecord:e,drawDefinition:r,structure:n,event:o}){if(!Array.isArray(t))return{error:YI};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:qc.message}}var cS="WALKOVER",XU="RETIRED",ud="COMPETITIVE",hc="ROUTINE",Sc="DECISIVE",pd="winRatio";var Mk={[Di]:{policyName:"Competitive Bands Default",profileBands:{[Sc]:20,[hc]:50}}},md=Mk;function Zn({policyDefinitions:t,tournamentRecord:e,contextProfile:r,drawDefinition:n,event:o}){let i={policies:{}};if(!r)return i;let s=Go({tournamentRecord:e,drawDefinition:n,event:o}).policyDefinitions;if(r.withCompetitiveness){let a=t?.[Di]??s?.[Di]??md[Di];i.policies[Di]=a}return i}function pi({tournamentRecord:t,drawDefinition:e,policyType:r,structure:n,event:o}){if(!t)return{error:q};let{appliedPolicies:i}=Tt({tournamentRecord:t,drawDefinition:e,structure:n,event:o});return i?.[r]?{policy:i[r]}:{info:qc?.message}}function Ra({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}=pi({policyType:_o,tournamentRecord:t,event:n}),s=(t?mt({element:t,name:Qo}).extension:void 0)?.value,c=(n&&mt({name:Qo,element:n}).extension)?.value;return{scheduleTiming:{tournamentScheduling:s,eventScheduling:c,categoryName:e,categoryType:r,policy:o}}}function ng({drawDefinition:t,attributes:e}){let{extension:r}=mt({element:t,name:ed}),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:ed,value:n},Pp({drawDefinition:t,extension:r}),{entryProfile:n}}function Uu({drawDefinition:t}){let{extension:e}=mt({element:t,name:ed});return{entryProfile:e?.value||{}}}var on="ALTERNATE",og="CONFIRMED",Gr="DIRECT_ACCEPTANCE",dd="FEED_IN",ig="JUNIOR_EXEMPT",gs="LUCKY_LOSER",sg="ORGANISER_ACCEPTANCE",ld="QUALIFIER",Rk="REGISTERED",ag="SPECIAL_EXEMPT",Vr="UNGROUPED",Ci="UNPAIRED",Pu="WILDCARD",mo="WITHDRAWN",cg=[og,Gr,ig,sg,ag],JU=[dd,gs,ld],mi=[og,Gr,dd,ig,sg,ag,Pu],Xr=[og,Gr,ig,gs,ld,sg,ag,Pu],ZU=[on,og,Gr,dd,ig,gs,sg,ld,Rk,ag,Vr,Ci,Pu,mo],xb={ALTERNATE:on,CONFIRMED:og,DIRECT_ACCEPTANCE:Gr,DIRECT_ENTRY_STATUSES:mi,DRAW_SPECIFIC_STATUSES:JU,EQUIVALENT_ACCEPTANCE_STATUSES:cg,FEED_IN:dd,JUNIOR_EXEMPT:ig,LUCKY_LOSER:gs,ORGANISER_ACCEPTANCE:sg,QUALIFIER:ld,SPECIAL_EXEMPT:ag,STRUCTURE_SELECTED_STATUSES:Xr,UNGROUPED:Vr,UNPAIRED:Ci,VALID_ENTRY_STATUSES:ZU,WILDCARD:Pu,WITHDRAWN:mo};function ug({stage:t,drawDefinition:e}){let{entryProfile:r}=Uu({drawDefinition:e}),n=Object.keys(r).includes(t);if(!n&&ru.includes(t)){let o=[{[t]:{drawSize:void 0,alternates:!0}}];return ng({drawDefinition:e,attributes:o}),!0}return n}function wb({stage:t,drawDefinition:e}){let{entryProfile:r}=Uu({drawDefinition:e});return r[t]?.alternates||0}function Lb({stage:t,drawDefinition:e}){let{entryProfile:r}=Uu({drawDefinition:e});return r[t]?.wildcardsCount||0}function uS({stage:t,drawDefinition:e,entryStatus:r}){return e.entries.reduce((n,o)=>o.entryStage===t&&o.entryStatus===r?n+1:n,0)}function bi({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:vn,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}=Ck({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 Ck({provisionalPositioning:t,drawDefinition:e,structureId:r}){let n=[],o=(e.links??[]).find(i=>i.linkType===Fn&&i.target.structureId===r);if(o){let{finishingPositions:i,structureId:s}=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:Lo}).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:dd,placementGroup:A,groupingValue:d,participantId:h,GEMscore:E})})})}return{playoffEntries:n}}function Fb({stage:t,drawDefinition:e}){return mi.reduce((r,n)=>(uS({drawDefinition:e,entryStatus:n,stage:t})||0)+r,0)}function sn({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:_t};n||(n=o.structureId);let{stage:c,stageSequence:u}=o,m=c===fe&&r&&bi({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=QE;let f=o.seedLimit??o?.positionAssignments?.length;return{seedAssignments:s,stageSequence:u,seedLimit:f,stage:c,error:i}}function di(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 Cp({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:Cp({item:r,drawDefinition:t,structure:e,event:n})||Cp({item:e,drawDefinition:t,structure:e,event:n})||di(t)||di(n)}}function kb({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 Pe({drawDefinition:t,structure:e}){let r={},n=[];return(t?.structures??[e]).filter(o=>o&&typeof o=="object").forEach(o=>{if(!o)return;let{structureId:i,matchUps:s,structures:a}=o,c=Array.isArray(a);if(c)c&&a.forEach(u=>{let{structureName:p}=u,m=u.matchUps;r[u.structureId]={matchUps:m,itemStructureIds:[],structureName:p},m&&(n.push(...m),m.forEach(d=>{d.tieMatchUps&&n.push(...d.tieMatchUps)})),r[i]||(r[i]={itemStructureIds:[],matchUps:[]}),r[i].itemStructureIds||(r[i].itemStructureIds=[]),r[i].itemStructureIds.push(u.structureId)});else{let u=s;r[i]={matchUps:u,itemStructureIds:[]},u?.forEach(p=>{n.push(p),p.tieMatchUps&&n.push(...p.tieMatchUps)})}}),{mappedMatchUps:r,drawMatchUps:n}}function Vo({mappedMatchUps:t,matchUpsMap:e,structureId:r,inContext:n}){t=e?.mappedMatchUps??t;let o=t[r],i=(o?.itemStructureIds||[]).map(s=>{let{matchUps:a,structureName:c}=t[s];return n?a.map(u=>Object.assign(J(u,!0,!0),{containerStructureId:r,structureId:s,structureName:c})):a}).flat();return(o?.matchUps||[]).concat(...i)}function pS({groupedOrder:t,roundPositionsCount:e}){if(!t||t?.length<=e)return t;let n=Ae(t,t.length/e).map(i=>i.reduce((s,a)=>s+a)),o=n.slice().sort(le);return n.map(i=>o.indexOf(i)+1)}function pg(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 Br(t){return Array.isArray(t)?t.every(pg):!1}function Ke({matchUps:t=[],interpolate:e}){if(!Br(t))return{roundMatchUps:[],error:B};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&&Ln(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=>!ae.includes(I.matchUpStatus)&&!I.score?.scoreStringSide1)?.length,g=l&&l===f;return i=Math.max(i,l),{[d]:{matchUpsCount:l,inactiveCount:f,inactiveRound:g}}})),a=0,c=0,u=Object.keys(o).map(d=>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=Ae(g,2);s[d].drawPositions=g,s[d].pairedDrawPositions=I}else{let g=s[d-1],I=g.drawPositions,h=g.matchUpsCount/s[d].matchUpsCount,S=Ae(I,h),T=l.map(y=>{let{roundPosition: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})=>!Ln(d));return{hasNoRoundPositions:t.some(d=>!d.roundPosition),roundsNotPowerOf2:p,maxMatchUpsCount:i,roundMatchUps:o,roundNumbers:u,roundProfile:s,...C}}function fd(t){if(!Array.isArray(t))return"";let e=t.filter(Jt);return e.length?pt([Math.min(...e),Math.max(...e)]).join("-"):""}function Gb({drawDefinition:t,structureId:e,matchUpsMap:r}){if(!t)return{error:Z};if(!e)return{error:Pr};let{structure:n}=at({drawDefinition:t,structureId:e});if(n?.stage!==qe)return{error:Vi,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=Vo({structureId:m,matchUpsMap:r}),f=Ke({matchUps:d}).roundProfile;return{[m]:f}})),c=Vo({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=pS({roundPositionsCount:A,groupedOrder:g}),D=N?.length||1;if(D<=A){let O=T.length/D,v=Ae(U,O);f===yi&&v.forEach(x=>x.reverse()),U=N?.length&&N?.map(x=>v[x-1]).flat()||v.flat()}let M=Ae(U,P);if(I){let O=tt(0,I.interleave).map(()=>{}),v=tt(0,I.offset).map(()=>{});M=M.map(F=>[F,...O]),M.unshift(v),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((O,v)=>{let x=1+v*b;p[h][x]||(p[h][x]=fd(O))})}),{sourceDrawPositionRanges:p}}function mS({drawDefinition:t}){if(typeof t!="object")return{error:Sa};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 Vb({drawDefinition:t,roundProfile:e,structureId:r,matchUpsMap:n}){if(!t)return{error:Z};if(!r)return{error:Pr};if(!e){let c=Vo({matchUpsMap:n,structureId:r});if({roundProfile:e}=Ke({matchUps:c}),!e)return{error:st}}let i=(Math.min(...e?.[1]?.drawPositions??[])||1)-1,s=Object.keys(e);return{drawPositionsRanges:Object.assign({},...(s||[]).map(c=>{let u=e?.[c]?.matchUpsCount,p=e?.[1]?.drawPositions??[],m=Ae(p,p.length/u),d=m.map(fd),l=m.map(S=>S.map(T=>T-i)).map(fd),f=s.map(S=>{if(S>c)return;let T=e?.[S]?.drawPositions??[];return Ae(T,T.length/u)}).filter(Boolean),g=tt(0,u).map(S=>f.map(T=>T[S]).flat().filter(Boolean).sort(le)).map(S=>pt(S)),I=g.map(S=>UC(S).map(fd).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 gd({roundsNotPowerOf2:t,drawDefinition:e,structure:r,matchUps:n}){if(!r)return!1;n=n??r.matchUps??[],t=t??Ke({matchUps:n}).roundsNotPowerOf2;let o=!!r.positionAssignments?.find(({drawPosition:i})=>i)||!!n?.find(({drawPositions:i})=>i?.length);return(!e?.drawType||e.drawType!==Ki)&&!r?.structures&&t&&o}function cr({structure:t}){if(!t)return!1;let e=t.matchUps||t.roundMatchUps&&Object.values(t.roundMatchUps).flat(),r=!!e?.find(o=>o?.roundPosition),n=!!e?.find(o=>o?.drawPositions?.length);return!t?.structures&&t?.stage!==$e&&(!e.length||!r&&!n)}var mg={[vo]:{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"}}},Bb=mg;function dS({roundNamingPolicy:t,drawDefinition:e,structure:r,matchUps:n}){let{roundProfile:o,roundMatchUps:i}=Ke({matchUps:n}),{structureAbbreviation:s,stage:a}=r,c=cr({structure:r}),u=gd({structure:r}),p=r.structures,m={},d=mg[vo],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 O=`${R}${P} ${b}`,v=`${y}${b}`;return{[b]:{roundName:O,abbreviatedRoundName:v}}}));else{let b=l&&(t?.qualifyingFinishMap||d?.qualifyingFinishMap||{});Object.assign(m,...M.map(O=>{if(!o?.[O])return;let{matchUpsCount:v,preFeedRound:x}=o[O],F=v*2,w=b?.[o?.[O].finishingRound]||b&&`${y}${F}`||h[v]||`${y}${F}`,L=x?`-${T}`:"",k=`${w}${L}`,G=[D,s,k].filter(Boolean).join("-"),K=`${S[v]||`${y}${F}`}${L}`,Y=[D,s,K].filter(Boolean).join("-");return{[O]:{abbreviatedRoundName:Y,roundName:G}}}))}return{roundNamingProfile:m,roundProfile:o,roundMatchUps:i}}var bk=(t,e)=>(t||0)+(e||0);function lS(t,e){let r=Array.isArray(t)?t[0]:t;return isNaN(r)&&cS||r<=e[Sc]&&Sc||r<=e[hc]&&hc||ud}function fS({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(bk)&&(r[n[0]>n[1]?0:1]+=1),{sets:e,games:r,score:t}}function Ok(t){let e=Math.min(...t.games),r=Math.max(...t.games);return Math.round(e/r*100)}function gS(t){return t.map(Ok).sort().map(e=>parseFloat(e.toFixed(2)))}function Du({tournamentRecord:t,profileBands:e,matchUp:r}){if(!r)return{error:mr};let{score:n,winningSide:o}=r;if(!o)return{error:B};let i=!e&&t&&pi({policyType:Di,tournamentRecord:t}).policy,s=e||i?.profileBands||md[Di].profileBands,a=fS({score:n}),c=gS([a]),u=lS(c,s),p=Array.isArray(c)?c[0]:c;return{...C,competitiveness:u,pctSpread:p}}function IS({matchUp:t}){if(!t)return{error:mr};if(t&&!t.sides)return{error:dr};if(t&&!t.hasContext)return{error:Kc};let e=(t.sides??[])?.map(a=>a?.participantId).filter(Boolean),r=t.sides?.filter(a=>a.participant?.participantType===Et).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 Id="CHECK_IN",hd="CHECK_OUT",vk="SCHEDULE",Ji="SCHEDULE.ASSIGNMENT.VENUE",lo="SCHEDULE.ALLOCATION.COURTS",Jo="SCHEDULE.ASSIGNMENT.COURT",bp="SCHEDULE.COURT.ORDER",Zi="SCHEDULE.DATE",_k="COMPLETED.DATE",Sd="HOME_PARTICIPANT_ID",dg="SCHEDULE.ASSIGN.OFFICIAL",ts="SCHEDULE.TIME.SCHEDULED",Bo="SCHEDULE.TIME.START",es="SCHEDULE.TIME.STOP",Oi="SCHEDULE.TIME.RESUME",vi="SCHEDULE.TIME.END",Op="SCHEDULE.TIME.MODIFIERS",Hb="TO_BE_ANNOUNCED",Wb="NEXT_AVAILABLE",jb="FOLLOWED_BY",Yb="AFTER_REST",qb="RAIN_DELAY",xk="NOT_BEFORE",hS=[Hb,Wb,jb,Yb,qb],wk="ELIGIBILITY",Lk="REGISTRATION",Fk="SUSPENSION",kk="MEDICAL",Gk="PENALTY",tP="SCALE",eP="RATING",rP="RANKING",lg="SEEDING",Ho="PUBLISH",Cr="PUBLIC",Wo="STATUS",Vk="MODIFICATION",Bk="RETRIEVAL",Hk="other",$b={MUTUALLY_EXCLUSIVE_TIME_MODIFIERS:hS,AFTER_REST:Yb,ALLOCATE_COURTS:lo,ASSIGN_COURT:Jo,ASSIGN_OFFICIAL:dg,ASSIGN_VENUE:Ji,CHECK_IN:Id,CHECK_OUT:hd,COMPLETED_DATE:_k,COURT_ORDER:bp,ELIGIBILITY:wk,END_TIME:vi,FOLLOWED_BY:jb,MEDICAL:kk,MODIFICATION:Vk,NEXT_AVAILABLE:Wb,NOT_BEFORE:xk,OTHER:Hk,PENALTY:Gk,PUBLIC:Cr,PUBLISH:Ho,RANKING:rP,RATING:eP,RAIN_DELAY:qb,REGISTRATION:Lk,RESUME_TIME:Oi,RETRIEVAL:Bk,SCALE:tP,SCHEDULE:vk,SCHEDULED_DATE:Zi,SCHEDULED_TIME:ts,SEEDING:lg,START_TIME:Bo,STATUS:Wo,STOP_TIME:es,SUSPENSION:Fk,TIME_MODIFIERS:Op,TO_BE_ANNOUNCED:Hb};function Is({matchUp:t}){if(!t)return{error:mr};if(!t.hasContext)return{error:Kc};if(!t.sides||t.sides.filter(Boolean).length!==2)return{error:dr};let{nestedIndividualParticipantIds:e,allRelevantParticipantIds:r,sideParticipantIds:n}=IS({matchUp:t}),i=(t.timeItems??[]).filter(u=>u?.itemType&&[Id,hd].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===Id);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||kt(e)&&e;return r&&vI[t].includes(r)};function vp(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 _p(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 SS({timesBlockArray:t,categoryName:e,categoryType:r}){return t.filter(n=>Array.isArray(n)).map(n=>n.sort((o,i)=>(i.categoryNames?.length||0)-(o.categoryNames?.length||0)).find(({categoryTypes:o,categoryNames:i})=>!i?.length&&!o?.length||i?.includes(e)||o?.includes(r))).find(Boolean)}function Kb({tournamentScheduling:t,eventScheduling:e,averageMinutes:r,defaultTiming:n,matchUpFormat:o,categoryName:i,categoryType:s,policy:a}){let c=e?.matchUpRecoveryTimes&&_p({...e,averageMinutes:r,matchUpFormat:o}),u=t?.matchUpRecoveryTimes&&_p({...t,averageMinutes:r,matchUpFormat:o}),p=a?.matchUpRecoveryTimes&&_p({...a,averageMinutes:r,matchUpFormat:o}),m=[c,u,p,a?.defaultTimes?.recoveryTimes,n?.recoveryTimes];return SS({categoryName:i,categoryType:s,timesBlockArray:m})}function zb({matchUpFormat:t,categoryName:e,categoryType:r,defaultTiming:n,tournamentScheduling:o,eventScheduling:i,policy:s}){let a=i?.matchUpAverageTimes&&vp({...i,matchUpFormat:t}),c=o?.matchUpAverageTimes&&vp({...o,matchUpFormat:t}),u=s?.matchUpAverageTimes&&vp({...s,matchUpFormat:t}),p=[a,c,u,s?.defaultTimes?.averageTimes,n?.averageTimes];return SS({categoryName:e,categoryType:r,timesBlockArray:p})}var nP="DOUBLES_SINGLES",oP="SINGLES_DOUBLES",fo="total",TS="participantConflict",Ca="matchUpConflict",iP="ISSUE_IDS",Tc="CONFLICT",yc="WARNING",yS="ERROR",ES="ISSUE",fg="STATE",Qb={SINGLES_DOUBLES:oP,DOUBLES_SINGLES:nP,TOTAL:fo,CONFLICT_MATCHUP_ORDER:Ca,CONFLICT_PARTICIPANTS:TS,SCHEDULE_ISSUE_IDS:iP,SCHEDULE_CONFLICT:Tc,SCHEDULE_WARNING:yc,SCHEDULE_ERROR:yS,SCHEDULE_ISSUE:ES,SCHEDULE_STATE:fg};function Nu({defaultAverageMinutes:t=90,defaultRecoveryMinutes:e=0,tournamentRecord:r,matchUpFormat:n,categoryName:o,categoryType:i,eventType:s,event:a}){if(!r)return{error:q};s=s??a?.eventType??qs;let c={averageTimes:[{minutes:{default:t}}],recoveryTimes:[{minutes:{default:e}}]},{scheduleTiming:u}=Ra({tournamentRecord:r,categoryName:o,categoryType:i,event:a}),p={...u,matchUpFormat:n,categoryType:i,defaultTiming:c};return xp({eventType:s,timingDetails:p})}function xp({timingDetails:t,eventType:e}){let r=zb(t),n=Object.keys(r?.minutes||{}),o=r?.minutes&&(n?.includes(e)&&r.minutes[e]||r.minutes.default),i=Kb({...t,averageMinutes:o}),s=Object.keys(i?.minutes||{}),a=i?.minutes&&(s?.includes(e)&&i.minutes[e]||i.minutes.default),c=de(qs)(e)?oP:nP,u=i?.minutes&&(s?.includes(c)&&i.minutes[c]||a);return{averageMinutes:o,recoveryMinutes:a,typeChangeRecoveryMinutes:u}}function sP(t){return t.createdAt?new Date(t.createdAt).getTime():0}function Zo({timeItems:t,itemType:e}){let r=t.filter(o=>o&&o.itemType===e).sort((o,i)=>sP(o)-sP(i)).pop(),n=r&&sP(r);return{itemValue:r?.itemValue,timeStamp:n}}function AS({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Zo({timeItems:r?.timeItems||[],itemType:ts});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{scheduledTime:n}:e}function Xs({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Zo({timeItems:r?.timeItems||[],itemType:Zi});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{scheduledDate:n}:e}function wp(t){if(nh.test(t)){let e=Mf();return new Date(`${e}T${t}`)}else return new Date(t)}function Xb({matchUp:t}){if(!t)return{error:mr};if(!t.timeItems)return{error:df};let e=t.timeItems.filter(n=>[Bo,es,Oi,vi].includes(n?.itemType)).sort((n,o)=>wp(n.itemValue).getTime()-wp(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 Bo:i=0;break;case vi:if(n.lastValue&&[Bo,Oi].includes(n.lastType)){let u=wp(o.itemValue).getTime()-wp(n.lastValue).getTime();i=n.milliseconds+u}else i=n.milliseconds;break;case es:if([Bo,"SCHECULE.TIME.RESUME"].includes(n.lastType)){let u=wp(o.itemValue).getTime()-wp(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([Bo,Oi].includes(r.lastType)){let n=new Date().getTime()-wp(r.lastValue).getTime();r.milliseconds+=n}return{milliseconds:r.milliseconds,time:Wk(r.milliseconds),relevantTimeItems:e}}function Wk(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 Jb({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===Bo&&s;return a&&(!i||r(a)<r(i))?a:i},void 0)?.itemValue}}function Ec(t){let{disableNotice:e,venue:r,context:n}=t;if(typeof r!="object")return{error:B};let o=Rr(t);r.venueId||(r.venueId=Nt());let i;for(let s of Object.values(o)){let a=jk({disableNotice:!0,tournamentRecord:s,context:n,venue:r});if(a?.error)return a;i=a.venue}return e||lt({topic:Jh,payload:{venue:r}}),nt({...C,venue:i})}function jk({tournamentRecord:t,disableNotice:e,context:r,venue:n}){return t?n?(t.venues||(t.venues=[]),n.venueId||(n.venueId=Nt()),t.venues.reduce((i,s)=>i||s.venueId===n.venueId,void 0)?{error:OA}:(r&&At({element:n,extension:{value:r,name:OU}}),t.venues.push(n),e||lt({payload:{venue:n,tournamentId:t.tournamentId},topic:Jh}),{...C,venue:J(n)})):{error:st,info:"missing venue"}:{error:q}}function ti({tournamentRecords:t,tournamentRecord:e,venueId:r}){if(!e)return{error:q};if(!r)return{error:ai};let o=(e.venues??[]).reduce((i,s)=>s.venueId===r?s:i,void 0);if(!o&&t){let s=(fu({tournamentRecords:t}).linkedTournamentIds??[])[e.tournamentId];for(let a of s){let c=t[a],u=ti({tournamentRecord:c,venueId:r});if(u.success&&u.venue)return Ec({tournamentRecord:e,venue:u.venue}),{...C,venue:o}}}return o?{...C,venue:o}:{error:ji}}function US({convertExtensions:t,...e}){let{tournamentRecords:r,tournamentRecord:n,venueId:o}=e,i=ti({tournamentRecords:r,tournamentRecord:n,venueId:o});return J(i,t,!0)}function hs({tournamentRecords:t,tournamentRecord:e,courtId:r}){if(!e)return{error:q};if(!r)return{error:Bi};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=(fu({tournamentRecords:t}).linkedTournamentIds??[])[e.tournamentId];for(let c of a){let u=t[c],p=hs({tournamentRecord:u,courtId:r});if(p.success)return p.venue&&Ec({tournamentRecord:e,venue:p.venue}),{...C,court:o,venue:i}}}return _({result:{error:Vs},stack:n})}function PS(t){return J(hs(t),!1,!0)}function Td({tournamentRecord:t,internalUse:e,courtId:r}){if(!t)return{error:q};if(!r)return{error:Bi};let n=hs({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 Ac(t){let e=et(t,[{[ne]:!0},{venueId:!0,[In]:ai}]);if(e.error)return e;let{tournamentRecord:r,venueId:n}=t,o=ti({tournamentRecord:r,venueId:n});if(o.error)return o;let s=(o.venue?.courts??[]).map(u=>(({courtInfo:p})=>({...p}))(Td({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 Zb({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===vi&&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:pn,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:qr},stack:o})};return{event:u,drawDefinition:void 0,tournamentId:c}}return{event:void 0,drawDefinition:void 0,..._({result:{error:br},context:{drawId:n,eventId:r},stack:o})}}function yd(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:mr};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}=Xb({matchUp:p}),{startTime:l}=Jb({matchUp:p}),{endTime:f}=Zb({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(Sd),D=A.get(lo),M=A.get(ts),R=A.get(Op),b=A.get(Zi),O=A.get(dg),v=A.get(bp),x=A.get(Ji),F=A.get(Jo),w,L,k,G,H,K=p.matchUpType??r;if(a&&M&&o&&K){let Q={matchUpFormat:p.matchUpFormat??c,...a};({averageMinutes:L=0,recoveryMinutes:k=0,typeChangeRecoveryMinutes:G=0}=xp({timingDetails:Q,eventType:K})),(L||k)&&(w=f?$r(zt(f),k):$r(M,L+k)),G&&(H=f?$r(zt(f),G):$r(M,L+G))}!b&&M&&(b=Ut(M));let Y=Bm({scheduledDate:b,scheduledTime:M}),j={},V=(i&&x&&Ac({tournamentRecord:i,venueId:x}))?.venueData||{};x&&(j[x]=V);let{venueName:$,venueAbbreviation:X,courtsInfo:W}=V,z=(F&&W?.find(Q=>Q.courtId===F))?.courtName;for(let Q of D||[]){if(!i)break;Q.venueId&&!j[Q.venueid]&&(j[Q.venueId]=Ac({venueId:Q.venueId,tournamentRecord:i})?.venueData);let ut=j[Q.venueId];Q.venueName=ut?.venueName;let ot=ut?.courtsInfo?.find(Dt=>Dt.courtId===Q.courtId);Q.courtName=ot?.courtName}g=nt({typeChangeTimeAfterRecovery:H,timeAfterRecovery:w,scheduledDate:b,scheduledTime:M,isoDateString:Y,homeParticipantId:N,venueAbbreviation:X,allocatedCourts:D,timeModifiers:R,venueName:$,venueId:x,courtOrder:v,courtName:z,courtId:F,official:O,typeChangeRecoveryMinutes:G,recoveryMinutes:k,averageMinutes:L,milliseconds:m,startTime:l,endTime:f,time:d})}else g=nt({milliseconds:m,startTime:l,endTime:f,time:d});let{scheduledDate:S}=Xs({matchUp:p}),{scheduledTime:T}=AS({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=Qi({source:g,template:N})}}}let E=p.matchUpStatus&&ae.includes(p.matchUpStatus)&&(Ut(f)||Ut(S)||Ut(T))||void 0;return{schedule:g,endDate:E}}function tO({drawPositions:t,roundProfile:e,roundNumber:r}){let n=[void 0,void 0];if(LI(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(wI(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 Lp({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 Sn({tournamentParticipants:t,tournamentRecord:e,participantIds:r}){let n="getPairedParticipant";if(!t&&!e)return{error:q};if(!Array.isArray(r)||r.length>2)return{error:wr};if(!r.length)return _({result:{error:bo},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 Ss({drawDefinition:t,participantId:e}){if(typeof t!="object")return{error:Z};if(typeof e!="string")return{error:se};let{extension:r}=mt({element:t,name:wo});return{lineUp:(r?.value||{})[e]}}function eO({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}=Lp({collectionPosition:r,collectionId:s,lineUp:d});if(c===vt){if(f?.length<=2){let I=o?.[f[0]]?.pairIdMap?.[f[1]],T=(I&&o[I]?.participant||Sn({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||Ss({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||Ss({participantId:d,drawDefinition:i})?.lineUp;return u({attribute:m,lineUp:g,teamParticipant:f})}).filter(Boolean)||{};return{drawPositionCollectionAssignment:Object.assign({},...p)}}function Ed(t){let e=et(t,[{[Gn]:!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===Et&&Lt||s===ft&&vt||s===wt&&wt||void 0}return{matchUpType:n}}function rO({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?Yk({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 Yk({displaySideNumber:t,seedAssignments:e,participantId:r,assignment:n,sideNumber:o}){let i={drawPosition:n.drawPosition,displaySideNumber:t,sideNumber:o};if(r){let s=qk({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 qk({seedAssignments:t,participantId:e}){return t?.find(r=>!r.seedProxy&&r.participantId===e)}function aP({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:O}){c=c??{};let v=We({drawDefinition:y,structure:M,matchUp:b,event:O})?.tieFormat,{roundOffset:x,structureId:F,structureName:w,stage:L,stageSequence:k}=M,{drawId:G,drawName:H,drawType:K}=y??{},Y=v?.collectionDefinitions,j=b.collectionId&&Y?.find(me=>me.collectionId===b.collectionId),V=b.collectionId?j?.matchUpFormat:b.matchUpFormat??M?.matchUpFormat??y?.matchUpFormat??O?.matchUpFormat,$=b.matchUpType||j?.matchUpType||M?.matchUpType||y?.matchUpType||!de(_e)(O?.eventType)&&O?.eventType,X=l?"BYE":b.matchUpStatus,{schedule:W,endDate:it}=yd({scheduleVisibilityFilters:t,afterRecoveryTimes:s,tournamentRecord:p,usePublishState:g,scheduleTiming:S,drawDefinition:y,matchUpFormat:V,publishStatus:E,matchUpType:$,matchUp:b,event:O}),z=m??b.drawPositions??[],{collectionPosition:Q,collectionId:ut,roundPosition:ot}=b,Dt=b.roundNumber??c.roundNumber,Rt=ut?eO({tournamentParticipants:r,positionAssignments:n,collectionPosition:Q,participantMap:I,drawDefinition:y,drawPositions:z,collectionId:ut,sideLineUps:D,matchUpType:$}):void 0,De=u?.[Dt]?.roundName||c.roundName,qt=u?.[Dt]?.abbreviatedRoundName||c.abbreviatedRoundName,Se=N?.[Dt]?.feedRound,_r=N?.[Dt]?.preFeedRound,dn=N?.[Dt]?.roundFactor,hr=o?.[Dt],Xe=ot?hr?.[ot]:void 0,Zt=e?.[Dt],Pt=j?.category?{...R?.category,...j.category}:R?.category??O?.category,ce=b.processCodes?.length&&b.processCodes||j?.processCodes?.length&&j?.processCodes||M?.processCodes?.length&&M?.processCodes||y?.processCodes?.length&&y?.processCodes||O?.processCodes?.length&&O?.processCodes||p?.processCodes,ue=T?.withCompetitiveness&&Du({...h,matchUp:b}),Fe=b.finishingPositionRange??c.finishingPositionRange,te=L!==ct&&It(a)&&a+(Dt||0),Je=me=>nt(me,void 0,!0),$t={...Je(R),...Je({matchUpFormat:$===_e?void 0:V,tieFormat:$===_e?v:void 0,gender:j?.gender??O?.gender,endDate:b.endDate??it,discipline:O?.discipline,category:Pt,finishingPositionRange:Fe,abbreviatedRoundName:qt,drawPositionsRange:Xe,competitiveProfile:ue,structureName:w,stageSequence:k,drawPositions:z,matchUpStatus:X,processCodes:ce,isRoundRobin:U,matchUpTieId:A,preFeedRound:_r,matchUpType:$,roundFactor:dn,roundOffset:x,structureId:F,roundNumber:Dt,roundOfPlay:te,feedRound:Se,roundName:De,drawName:H,drawType:K,schedule:W,drawId:G,stage:L}),...J(Je(b),!0,!0)};if(V&&b.score?.scoreStringSide1){let me=Ne(V),{bestOf:Sr,finalSetFormat:jr,setFormat:Kt}=me??{};(jr?.tiebreakSet||Kt?.tiebreakSet||Kt?.timed)&&($t.score.sets=$t.score.sets.sort((Te,gr)=>Te.setNumber-gr.setNumber).map((Te,gr)=>{let ee=gr+1===Sr&&jr?jr:Kt,Ur=ee?.tiebreakSet&&!ee?.timed,Cn=ee?.timed;return Ur?(Te.tiebreakSet=!0,[1,2].includes(Te.winningSide)&&(Te.side1Score=Te.winningSide===1?1:0,Te.side2Score=Te.winningSide===2?1:0)):Cn&&(Te.timed=!0),Te}))}if(Array.isArray(z)){let{orderedDrawPositions:me,displayOrder:Sr}=tO({drawPositions:z,roundProfile:N,roundNumber:Dt}),jr=N?.[Dt]?.feedRound,Kt=Sr[0]!==me[0],gr=me.concat(void 0,void 0).slice(0,2).map((Ee,Rn)=>{let ee=Rn+1,Ur=Kt?3-ee:ee,Cn=rO({...Rt,positionAssignments:n,displaySideNumber:Ur,seedAssignments:f,drawPosition:Ee,isFeedRound:jr,sideNumber:ee}),An=b.sides?.find(ep=>ep.sideNumber===ee),hi=ot?(ot-1)*2+Rn+1:void 0,ga=hi?Zt?.[hi]:void 0;return Je({sourceDrawPositionRange:ga,...An,...Cn})});Object.assign($t,J({sides:gr},!0,!0))}if(r&&$t.sides){let me=d?.[zs],Sr=Kt=>{let Te=I?.[Kt]?.participant;return Te&&Qi({template:me?.participant,source:Te})};if($t.sides.filter(Boolean).forEach(Kt=>{if(Kt.participantId){let Te=J(Sr(Kt.participantId)||(r?zo({policyDefinitions:d,participantId:Kt.participantId,tournamentParticipants:r,internalUse:!0,contextProfile:T}):void 0),void 0,!0);if(Te){let gr,Ee;if(y?.entries){let Rn=y.entries.find(Ur=>Ur.participantId===Kt.participantId),ee=O?.entries?.find(Ur=>Ur.participantId===Kt.participantId);gr=Rn?.entryStatus||ee?.entryStatus,Te.entryStatus=gr,Rn?.entryStage&&(Ee=Rn.entryStage,Te.entryStage=Ee)}i===!1?Object.assign(Kt,{participant:{entryStage:Ee,entryStatus:gr}}):Object.assign(Kt,{participant:Te})}}if(Kt?.participant?.individualParticipantIds?.length&&!Kt.participant.individualParticipants?.length){let Te=Kt.participant.individualParticipantIds.map(gr=>Sr(gr)||(r?zo({policyDefinitions:d,tournamentParticipants:r,internalUse:!0,contextProfile:T,participantId:gr}):void 0));i!==!1&&Object.assign(Kt.participant,{individualParticipants:Te})}}),!$t.matchUpType){let{matchUpType:Kt}=Ed({matchUp:$t});Kt&&Object.assign($t,{matchUpType:Kt})}if(T?.inferGender&&(!$t.gender||$t.gender===qi)&&$t.sides?.length===2&&$t.matchUpType!==_e){let Kt=$t.sides.map(Te=>{if(de(Lt)($t.matchUpType))return Te.participant?.person?.sex;if(Te.participant?.individualParticipants?.length===2){let gr=pt(Te.participant.individualParticipants.map(Ee=>Ee.person?.sex)).filter(Boolean);if(gr.length===1)return gr[0]}});if(Kt.filter(Boolean).length===2&&pt(Kt).length===1){let Te=Kt[0];$t.inferredGender=Te}}}if($t.tieMatchUps){let me=$t.matchUpStatus==="BYE",Sr=$t.sides?.map(({participant:jr,drawPosition:Kt,sideNumber:Te,lineUp:gr})=>{let Ee=jr?.participantType===_e&&jr;return{teamParticipant:Ee&&nt({participantRoleResponsibilities:Ee.participantRoleResponsibilities,participantOtherName:Ee.participanOthertName,participantName:Ee.participantName,participantId:Ee.participantId,teamId:Ee.teamId}),drawPosition:Kt,sideNumber:Te,lineUp:gr}});$t.tieMatchUps=$t.tieMatchUps.map(jr=>{let Kt=$t.matchUpId,gr={finishingPositionRange:$t.finishingPositionRange,abbreviatedRoundName:qt,roundNumber:Dt,roundName:De};return aP({tieDrawPositions:z,scheduleVisibilityFilters:t,sourceDrawPositionRanges:e,sideLineUps:Sr,drawPositionsRanges:o,initialRoundOfPlay:a,roundNamingProfile:u,additionalContext:gr,appliedPolicies:d,isCollectionBye:me,usePublishState:g,publishStatus:E,matchUpTieId:Kt,isRoundRobin:U,roundProfile:N,matchUp:jr,event:O,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 ir=$t.sides?.filter(me=>me?.participantId).length===2,fr=!$t.winningSide;if(Object.assign($t,{readyToScore:P&&ir&&fr,hasContext:!0}),ir){let{allParticipantsCheckedIn:me,checkedInParticipantIds:Sr}=Is({matchUp:$t});Object.assign($t,{allParticipantsCheckedIn:me,checkedInParticipantIds:Sr})}return Array.isArray(T?.exclude)&&T?.exclude.forEach(me=>delete $t[me]),$t}function nO({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Zo({timeItems:r?.timeItems||[],itemType:lo});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{allocatedCourts:J(n,!1,!0)}:e}function oO({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Zo({timeItems:r?.timeItems||[],itemType:Jo});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{courtId:n}:e}function iO({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Zo({timeItems:r?.timeItems||[],itemType:Ji});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{venueId:n}:e}function _i(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:O}=t,v=Array.isArray(y)?y.filter(Boolean):[],x=Array.isArray(i)?i.filter(Boolean):[],F=Array.isArray(r)?r.filter(Boolean):[],w=Array.isArray(O)?O.filter(Boolean):[],L=Array.isArray(h)?h.filter(Boolean):[],k=Array.isArray(p)?p.filter(Boolean):[],G=Array.isArray(f)?f.filter(Boolean):[],H=Array.isArray(d)?d.filter(Boolean):[],K=Array.isArray(c)?c.filter(Boolean):[],Y=Array.isArray(l)&&I?l.filter(Boolean):[],j=Array.isArray(A)&&g?A.filter(Boolean):[],V=Array.isArray(D)?D.filter(Boolean):[],$=Array.isArray(R)?R.filter(Boolean):[],X=Array.isArray(a)&&a.filter(Boolean)||typeof u=="string"&&[u]||[],W=Array.isArray(S)&&S.filter(Boolean)||typeof T=="string"&&T.length&&[T]||[],it=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(ot=>{if(N&&!de(xr)(ot)&&!ot.readyToScore||ot.winningSide&&s&&![1,2].includes(ot.winningSide)||m!==void 0&&(m&&!ot.tieMatchUps||!m&&ot.tieMatchUps)||o!==void 0&&(o&&!ot.collectionId||!o&&ot.collectionId)||w.length&&!w.includes(ot.stage)||L.length&&!L.includes(ot.stageSequence)||k.length&&(!ot.collectionId||!k.includes(ot.collectionId))||G.length&&(!ot.roundName||!G.includes(ot.roundName))||H.length&&(!ot.roundNumber||!H.includes(ot.roundNumber))||K.length&&(!ot.roundPosition||!K.includes(ot.roundPosition))||x.length&&(!ot.matchUpStatus||!x.includes(ot.matchUpStatus))||F.length&&ot.matchUpStatus&&F.includes(ot.matchUpStatus)||Y.length&&!Y.includes(ot.matchUpId)||j.length&&(!ot.matchUpType||!Yc(j,ot.matchUpType))||X.length&&(!ot.matchUpFormat||!X.includes(ot.matchUpFormat)))return!1;if(W?.length){let{scheduledTime:Dt}=AS({matchUp:ot}),{scheduledDate:Rt}=Xs({matchUp:ot}),qt=Ut(Dt)||Rt;if(!W.find(Se=>zn(Se,qt)))return!1}if(V.length){let{courtId:Dt}=oO({matchUp:ot}),{allocatedCourts:Rt}=nO({matchUp:ot}),De=Rt?.map(({courtId:qt})=>qt);if(!V.filter(Boolean).includes(Dt)||De?.includes(Dt))return!1}if($.length){let{venueId:Dt}=iO({matchUp:ot});if(!$.filter(Boolean).includes(Dt))return!1}if(E){if(it.length&&!it.includes(ot.tournamentId)||z.length&&!z.includes(ot.eventId)||Q.length&&!Q.includes(ot.drawId)||ut.length&&!ut.includes(ot.structureId))return!1;let Dt=ot.sides?.map(({participantId:Rt})=>Rt).filter(Boolean)??[];if(n&&Dt.length<n||v.length&&!v.some(De=>Dt.includes(De)))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:Si,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=Zn({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=Pe({drawDefinition:s,structure:c}));let{positionAssignments:b,allPositionsAssigned:O}=Ie({structure:c}),v=!R||O,{seedAssignments:x}=sn({provisionalPositioning:e,drawDefinition:s,structure:c});m=m??x;let{structureId:F}=c;l=l||s&&mS({drawDefinition:s}).exitProfiles;let w=l?.[F],L=w?.length&&(w[0].split("-").map(V=>parseInt(V)).reduce((V,$)=>V+$)||0),k=!!c.structures,G=Vo({matchUpsMap:f,structureId:F,inContext:u}),H=U?.[vo],K=dS({roundNamingPolicy:H,drawDefinition:s,structure:c,matchUps:G}),{roundNamingProfile:Y,roundProfile:j}=K;if(I=K?.roundMatchUps??[],o&&(G=_i({matchUps:G,...o,filterMatchUpTypes:!1,filterMatchUpIds:!1})),u){let{sourceDrawPositionRanges:V}=Gb({drawDefinition:s,matchUpsMap:f,structureId:F}),$=s?Vb({drawDefinition:s,roundProfile:j,matchUpsMap:f,structureId:F}).drawPositionsRanges:void 0,X=t.tournamentParticipants,W=t.participantMap;!X?.length&&!W&&r&&({participants:X=[],participantMap:W}=Xo({participantsProfile:t.participantsProfile,useParticipantMap:t.useParticipantMap,policyDefinitions:t.policyDefinitions,tournamentRecord:r,contextProfile:i,inContext:u})),G=G.map(z=>aP({scheduleVisibilityFilters:t.scheduleVisibilityFilters,hydrateParticipants:t.hydrateParticipants,afterRecoveryTimes:t.afterRecoveryTimes,usePublishState:t.usePublishState,scheduleTiming:t.scheduleTiming,publishStatus:t.publishStatus,sourceDrawPositionRanges:V,tournamentParticipants:X,positionAssignments:b,drawPositionsRanges:$,initialRoundOfPlay:L,roundNamingProfile:Y,tournamentRecord:r,appliedPolicies:U,seedAssignments:m,contextContent:d,participantMap:W,contextProfile:i,drawDefinition:s,scoringActive:v,isRoundRobin:k,roundProfile:j,structure:c,context:a,matchUp:z,event:p})),(G?.filter(z=>Array.isArray(z.tieMatchUps))).forEach(z=>{let Q=z.tieMatchUps;G=G.concat(...Q)}),n&&(G=_i({processContext:!0,...n,matchUps:G}))}else(G?.filter($=>Array.isArray($.tieMatchUps))).forEach($=>{let X=$.tieMatchUps;G=G.concat(...X)});return o&&(G=_i({matchUps:G,...o,filterMatchUpTypes:!1,filterMatchUpIds:!1})),(o?.matchUpTypes||o?.matchUpIds)&&(G=_i({matchUpTypes:o.matchUpTypes,matchUpIds:o.matchUpIds,matchUps:G})),(o?.matchUpTypes||o?.matchUpIds||u)&&(I=Ke({matchUps:G}).roundMatchUps??[]),We({drawDefinition:s,structure:c,event:p})?.tieFormat&&({collectionPositionMatchUps:g}=kb({matchUps:G})),{collectionPositionMatchUps:g,roundMatchUps:I,isRoundRobin:k,roundProfile:j,matchUpsMap:f,matchUps:G}}function Ts({matchUp:t}){return t?ae.includes(t?.matchUpStatus)||t?.winningSide:!1}function Mu({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:O}=U,{assignedPositions:v}=Ie({structure:E}),x=v?.filter(w=>w.participantId).map(w=>w.drawPosition),F;return O.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,k=L&&w.sides?.every($=>$.participantId),G=!L&&w.drawPositions?.filter(Boolean).length===2,H=!L&&w.drawPositions?.every($=>x?.includes($)),K=v?.filter($=>$.bye).map($=>$.drawPosition),Y=!L&&w.drawPositions?.find($=>K?.includes($)),V=zh.includes(w.matchUpStatus)&&(k||G&&(!t||H));return Y?b.push(w):Ts({matchUp:w})?D.push(w):V?M.push(w):R.push(w)}),{includesTeamMatchUps:F,abandonedMatchUps:N,completedMatchUps:D,upcomingMatchUps:M,pendingMatchUps:R,byeMatchUps:b,structure:E}}function sO({drawDefinition:t,roundNumber:e,structureId:r}){if(!t)return{error:Z};if(!r)return{error:Pr};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 DS({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[Xn,so].includes(o?.linkType)&&!o?.source?.roundNumber?_({result:{error:B},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:Pr}:{error:Z}}function aO({structureMatchUps:t,matchUp:e}){let{roundNumber:r,roundPosition:n}=e,o=t.filter(s=>s.roundNumber===r&&!s.matchUpTieId),i=t.filter(s=>s.roundNumber===r+1&&!s.matchUpTieId);if(i.length){let s;return i.length===o.length?s=i.find(a=>a.roundPosition===n):i.length===o.length/2&&(s=i.find(a=>a.roundPosition===Math.ceil(n/2))),{matchUp:s}}return{message:"no progression found"}}function NS({sourceRoundMatchUpCount:t,inContextDrawMatchUps:e,sourceRoundPosition:r,drawDefinition:n,targetLink:o}){if(!o)return{error:$l};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=pS({roundPositionsCount:g.length,groupedOrder:a}),P=E?.length||1;if(P<=g.length){let D=f/P,M=Ae(g,D);s===yi&&M.forEach(R=>R.reverse()),T=E?.length&&E?.map(R=>M[R-1]).flat()||T}s===Nn?y=T[h-1]:s===yi?((!E?.length||P>g.length)&&(h=l.length+1-h),y=T[h-1]):s===Sp&&Dr()&&console.log(pp,{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:Zm});if(D?.value)return{disabledDrawPosition:U}}return{matchUp:A,targetDrawPosition:U,matchUpDrawPositionIndex:S}}function ur({inContextDrawMatchUps:t=[],useTargetMatchUpIds:e,inContextMatchUp:r,drawDefinition:n,matchUpId:o}){let i=r;t.length&&!i&&(i=t.find(c=>c.matchUpId===o));let{structure:s}=at({structureId:i?.structureId,drawDefinition:n});return s?.finishingPosition===zi?$k({inContextDrawMatchUps:t,useTargetMatchUpIds:e,drawDefinition:n,structure:s,matchUp:i}):Kk({matchUp:i})}function $k({inContextDrawMatchUps:t,useTargetMatchUpIds:e,drawDefinition:r,structure:n,matchUp:o}){let{winnerMatchUpId:i,loserMatchUpId:s}=o,{links:a}=sO({roundNumber:o.roundNumber,structureId:n.structureId,drawDefinition:r}),c=a?.source,u=DS({source:c,linkType:Xn}),p=DS({linkCondition:kn,linkType:so,source:c}),m=DS({source:c,linkType:so}),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!==fn&&t.find(({matchUpId:R})=>R===i),T=s&&f!==fn&&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!==fn&&({matchUpDrawPositionIndex:E,targetDrawPosition:y,matchUp:T}=NS({targetLink:m,sourceRoundMatchUpCount:M,inContextDrawMatchUps:t,sourceRoundPosition:D,drawDefinition:r})),d&&g!==fn&&({matchUpDrawPositionIndex:S,targetDrawPosition:h,matchUp:I}=NS({targetLink:p,sourceRoundMatchUpCount:M,inContextDrawMatchUps:t,sourceRoundPosition:D,drawDefinition:r})),u&&!P&&l!==fn&&({matchUpDrawPositionIndex:U,targetDrawPosition:A,matchUp:P}=NS({targetLink:u,sourceRoundMatchUpCount:M,inContextDrawMatchUps:t,sourceRoundPosition:D,drawDefinition:r})),P||(N=N||t.filter(R=>R.structureId===n.structureId),{matchUp:P}=aO({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 Kk({matchUp:t}){return{targetLinks:{loserTargetLink:void 0,winnerTargetLink:void 0},targetMatchUps:{loserMatchUp:void 0,winnerMatchUp:void 0},matchUp:t}}function cO({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===Ei){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=ur({useTargetMatchUpIds:!0,inContextDrawMatchUps:e,inContextMatchUp:n,drawDefinition:t,matchUpId:o}),{winnerMatchUp:u}=c.targetMatchUps,{loserMatchUp:p}=c.targetMatchUps;!n.winnerMatchUpId&&u&&(n.winnerMatchUpId=u.matchUpId),!n.loserMatchUpId&&p&&(n.loserMatchUpId=p.matchUpId);let m=cP({upcomingMatchUp:u}),d=cP({upcomingMatchUp:p});if(n.matchUpStatus!=="BYE"&&p?.matchUpStatus==="BYE"){let{matchUp:f}=uO({matchUp:p,drawDefinition:t,inContextDrawMatchUps:e})||{};d=f&&cP({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===kn,I=zk(n);if(I.length){let h=Hf(u?.sides),S=Hf(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 zk(t){return t?.sides?.map(({participant:e,participantId:r,qualifier:n})=>e||r&&{participantId:r}||n&&{qualifier:n}).filter(Boolean)||[]}function uO({matchUp:t,drawDefinition:e,inContextDrawMatchUps:r}){let{matchUpId:n,matchUpStatus:o,structureId:i}=t||{};if(!t||!i||t?.matchUpStatus===Qt)return{matchUp:t};if(o==="BYE"){let s;return t.winnerMatchUpId?s=r.find(({matchUpId:a})=>a===t.winnerMatchUpId):{winnerMatchUp:s}=ur({inContextDrawMatchUps:r,drawDefinition:e,matchUpId:n})?.targetMatchUps||{},uO({matchUp:s,drawDefinition:e,inContextDrawMatchUps:r})}return{matchUp:void 0}}function cP(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 ie(t){let e="getAllDrawMatchUps";Object.assign(t,{requireParticipants:!1});let r=Zs(t);if(r.error)return _({result:r,stack:e});let{abandonedMatchUps:n,completedMatchUps:o,upcomingMatchUps:i,pendingMatchUps:s,byeMatchUps:a,matchUpsMap:c}=r;return{matchUps:(n??[]).concat(...o??[],...i??[],...s??[],...a??[]),matchUpsMap:c}}function Zs(t){if(!t?.drawDefinition)return{error: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=Zn({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}=Eu({participants:e,participantsProfile:a})));let{structures:b}=hn({drawDefinition:S});if(!b)return{error:_t};n||(n=Pe({drawDefinition:S}));let O=S&&mS({drawDefinition:S}).exitProfiles;b.forEach(F=>{let{byeMatchUps:w=[],pendingMatchUps:L=[],upcomingMatchUps:k=[],completedMatchUps:G=[],abandonedMatchUps:H=[]}=Mu({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:O,matchUpsMap:n,structure:F,context:E,event:P});A=A.concat(...H),U=U.concat(...G),N=N.concat(...k),D=D.concat(...L),M=M.concat(...w)});let v=F=>(!l&&!T&&!d||(l&&(F=_i({matchUps:F,...l})),d&&(F=_i({matchUps:F,...d,processContext:!0}))),F),x={abandonedMatchUps:v(A),completedMatchUps:v(U),upcomingMatchUps:v(N),pendingMatchUps:v(D),byeMatchUps:v(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:k,pending:G,bye:H}=F,K=[].concat(...w&&A||[],...L&&U||[],...k&&N||[],...G&&D||[],...H&&M||[]);cO({inContextDrawMatchUps:K,drawDefinition:S})}return x}function to(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=Zn({policyDefinitions:c,tournamentRecord:p,contextProfile:f,event:S}));let M;if(!e?.length&&!n&&p){let v=Xo({participantsProfile:s,useParticipantMap:u,policyDefinitions:c,tournamentRecord:p,contextProfile:f,inContext:I});n=v.participantMap,e=v.participants??[],M=v.groupInfo}let R=S.drawDefinitions??[],b=Ra({tournamentRecord:p,event:S}).scheduleTiming;return{matchUps:R.flatMap(v=>{let{matchUps:x}=ie({tournamentParticipants:e,tournamentAppliedPolicies:i,scheduleVisibilityFilters:o,context:D,participantsProfile:s,afterRecoveryTimes:a,policyDefinitions:c,tournamentRecord:p,usePublishState:m,contextFilters:d,contextProfile:f,drawDefinition:v,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:q};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}=Xo({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=Zn({policyDefinitions:c,tournamentRecord:u,contextProfile:d});return{matchUps:S.flatMap(A=>(y.eventDrawsCount=A.drawDefinitions?.length??0,to({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 Mn({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:xt};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 xi(t,e){return Qk(t,e)||(t?.stageSequence||0)-(e?.stageSequence||0)||t?.roundNumber&&e.roundNumber&&t?.roundNumber-e?.roundNumber||(t?.roundPosition??0)-(e?.roundPosition??0)}function Qk(t,e){return($s[t?.stage]||0)-($s[e?.stage]||0)}function nr(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}=Xo({participantsProfile:s,useParticipantMap:u,policyDefinitions:c,tournamentRecord:p,contextProfile:l,inContext:I})),l&&!n&&(n=Zn({policyDefinitions:c,tournamentRecord:p,contextProfile:l,drawDefinition:f,event:S})),{...ie({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 ys({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 uP=t=>e=>!t||typeof e!="object"?void 0:Array.isArray(t)&&t.map(r=>({[r]:ys({element:e,accessor:r})?.value}))||typeof t=="object"&&Object.keys(t).map(r=>({[r]:ys({element:e,accessor:r})?.value}))||(typeof t=="string"&&ys({element:e,accessor:t}))?.value,Hr=uP;function ba({finishingPositionOffset:t=0,finishingPositionLimit:e,positionsFed:r,roundsCount:n,roundLimit:o,matchUps:i,lucky:s,fmlc:a}){if(!Br(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(Hr("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=Dr({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 rs({inContextDrawMatchUps:t,drawDefinition:e,matchUpsMap:r}){if(!e)return{error:Z};let n={loserMatchUpIds:{},winnerMatchUpIds:{}};if(t||({matchUps:t,matchUpsMap:r}=ie({inContext:!0,drawDefinition:e,matchUpsMap:r})),!r?.drawMatchUps.some(i=>i.finishingPositionRange)&&e?.structures?.length===1&&!e?.structures[0].structures){let i=r?.drawMatchUps??[];ba({matchUps:i})}return(t??[]).filter(({collectionId:i})=>!i).forEach(i=>{let{matchUpId:s,structureId:a}=i,c=ur({inContextDrawMatchUps:t,drawDefinition:e,matchUpId:s}),{winnerMatchUp:u,loserMatchUp:p}=c.targetMatchUps,m=u?.matchUpId,d=p?.matchUpId,f=Vo({matchUpsMap:r,structureId:a}).find(g=>g.matchUpId===s);if(f&&(m&&(n.winnerMatchUpIds[f.matchUpId]=m,Object.assign(f,{winnerMatchUpId:m}),Object.assign(i,{winnerMatchUpId:m})),d&&(n.loserMatchUpIds[f.matchUpId]=d,i.loserMatchUpId=d,f.loserMatchUpId=d,i.finishingPositionRange))){let g=p.finishingPositionRange&&[...i.finishingPositionRange.loser,...p.finishingPositionRange.loser],I=g&&[Math.min(...g),Math.max(...g)];i.finishingPositionRange.loser=I,f.finishingPositionRange.loser=I}}),{inContextDrawMatchUps:t,goesToMap:n}}function an(t){let e=Rr(t),r=t.matchUps??[],n=t.drawIds??[],{includeParticipantDependencies:o,tournamentRecord:i,drawDefinition:s}=t;if(!Array.isArray(r))return{error:no};if(!Array.isArray(n))return{error:cn};let a=t.matchUpIds?.length?t.matchUpIds:r.map(T=>T.matchUpId);if(!Array.isArray(a))return{error:ps};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===Fn),g=r;if(f.length){g=Mn({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}=Su(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)rs({drawDefinition:s}),g?.length||(g=nr({drawDefinition:s}).matchUps),S(g);else{if(g?.length||(g=Mn({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(xi);if(!y?.find(({roundPosition:P})=>!P)){let P=y?.find(({tournamentId:U})=>U),{drawDefinition:A}=ze({tournamentRecord:e[P?.tournamentId],drawId:T});A&&rs({drawDefinition:A})}S(y)}}return{positionDependencies:c,matchUpDependencies:u,sourceMatchUpIds:m,matchUps:g,...C}}function he(t){let e=t?.matchUp,r=t?.score||e?.score,n=r?.sets?.[0],{side1Score:o,side2Score:i,side1TiebreakScore:s,side2TiebreakScore:a,side1PointScore:c,side2PointScore:u}=n||{},p=o||i||s||a||c||u;return!!(r?.sets?.length>1||p)}function Oa({matchUpStatus:t}){return $h.includes(t)}function pO({matchUpStatus:t}){return id.includes(t)}function gg({matchUpStatus:t}){return Kh.includes(t)}function Ig({matchUpStatus:t,winningSide:e,tieMatchUps:r,sides:n,score:o}){let i=n?.find(({participantId:c})=>c),s=r?.filter(Ig)?.length;return he({score:o})||s||e&&i||t&&pO({matchUpStatus:t})&&![Gt,Bt,Hn].includes(t)}function va(t){let{drawDefinition:e,findContainer:r,structureId:n,event:o}=t,i=t.structure,{containedStructures:s}=fs({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(cr({structure:i}))return{structure:i,isAdHoc:!0,error:Ls};let{matchUps:u}=ie({inContext:!0,matchUpFilters:c,drawDefinition:e,event:o}),p=u?.filter(A=>A.structureId===n||a.includes(A.structureId)),{matchUpDependencies:m}=an({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)}Ig(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 Es({drawPosition:t,matchUps:e=[]}){return{initialRoundNumber:e.filter(({drawPositions:n})=>t&&n?.includes(t)).map(({roundNumber:n})=>n).sort(le)[0]}}var _a={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 MS=[];function Tn(t,e){kt(t)&&(t={method:t}),(e||Dr())&&MS.push(t)}function Xk(t){let e=MS.slice();return t&&(MS.length=0),e}function mO(t){let r=Xk(t).map(n=>{let{color:o,keyColors:i,method:s,newline:a}=n,c=Object.keys(_a).includes(o)?_a[o]:_a.cyan,p=Object.keys(n).filter(d=>!["color","keyColors","method","newline"].includes(d)).map(d=>{let l=i&&Object.keys(i).includes(d)&&_a[i[d]]?_a[i[d]]:_a.brightwhite;return`${_a.white}${d}: ${l}${n[d]}`}).join(", "),m=s?.length<15?" ":" ";return[a?`
|
|
2
2
|
`:"",c,s,m,_a.white,p,_a.reset,`
|
|
3
3
|
`].join("")});r?.length&&console.log(...r)}function dO(){MS.length=0}function pr(t){return[Gt,Bt,Me].includes(t)}function Wr({provisionalPositioning:t,isPositionAction:e,tournamentRecord:r,drawDefinition:n,drawPosition:o,loserMatchUp:i,matchUpsMap:s,structureId:a,structure:c,event:u}){if(!n)return{error:Z};if(c||({structure:c}=at({drawDefinition:n,structureId:a})),!c)return{error:_t};a||({structureId:a}=c);let p="assignDrawPositionBye";Tn({method:p,color:"cyan",drawPosition:o}),s??=Pe({drawDefinition:n});let{positionAssignments:m}=Ct({structure:c}),{activeDrawPositions:d}=va({drawDefinition:n,structureId:a});if(m?.find(O=>O.drawPosition===o)?.bye)return{...C};let f=!!(i&&s.drawMatchUps.find(O=>O.loserMatchUpId===i?.matchUpId&&pr(O.matchUpStatus)));if(d?.includes(o)&&!f)return{error:rp};let I=m?.find(O=>O.drawPosition===o);if(!I)return{error:Ls};let{filled:h,containsBye:S,assignedParticipantId:T}=Jk(I);if(S)return{...C};if(h&&!S&&!f)return _({result:{error:Xa},stack:p});let y=Tt({tournamentRecord:r,drawDefinition:n,event:u}).appliedPolicies??{},E=ie({inContext:!0,drawDefinition:n,matchUpsMap:s}).matchUps??[],P={isCollectionMatchUp:!1},{matchUps:A}=yt({provisionalPositioning:t,drawDefinition:n,matchUpFilters:P,matchUpsMap:s,structure:c});if(m?.forEach(O=>{O.drawPosition===o&&(O.bye=!0,f&&(O.participantId=void 0))}),c.structureType===Ve)return Zk({tournamentRecord:r,drawDefinition:n,drawPosition:o,matchUps:A}),ko({tournamentId:r?.tournamentId,drawDefinition:n,structure:c,event:u}),lO({assignedParticipantId:T,isPositionAction:e,appliedPolicies:y,drawDefinition:n,drawPosition:o,structureId:a,stack:p});let{roundProfile:U,roundMatchUps:N}=Ke({matchUps:A}),M=(U&&Object.keys(U).map(O=>parseInt(O)).reverse())?.find(O=>U?.[O].drawPositions?.includes(o)),R=M?N?.[M].find(({drawPositions:O})=>O?.includes(o)):void 0;R&&fO({tournamentRecord:r,drawDefinition:n,matchUp:R,event:u});let b=R?.drawPositions?.find(O=>O!==o);if(R&&b){let O=RS({sourceDrawPositions:R.drawPositions,matchUpId:R.matchUpId,inContextDrawMatchUps:E,drawPositionToAdvance:b,tournamentRecord:r,drawDefinition:n,matchUpsMap:s});if(O.error)return O}return ko({tournamentId:r?.tournamentId,drawDefinition:n,structure:c,event:u}),lO({assignedParticipantId:T,isPositionAction:e,appliedPolicies:y,drawDefinition:n,drawPosition:o,structureId:a,stack:p})}function lO({assignedParticipantId:t,isPositionAction:e,appliedPolicies:r,drawDefinition:n,drawPosition:o,structureId:i,stack:s}){return e&&hu({appliedPolicies:r,drawDefinition:n,positionAction:{removedParticipantId:t,drawPosition:o,structureId:i,name:s}}),_({result:{...C},stack:s})}function Jk(t){let e=t.bye,r=t.qualifier,n=t.participantId;return{containsBye:e,containsQualifier:r,assignedParticipantId:n,filled:e||r||n}}function fO({tournamentRecord:t,drawDefinition:e,eventId:r,matchUp:n,event:o}){Object.assign(n,{matchUpStatus:"BYE",score:void 0,winningSide:void 0}),gt({tournamentId:t?.tournamentId,eventId:r??o?.eventId,context:"setMatchUpStatusBye",drawDefinition:e,matchUp:n})}function Zk({tournamentRecord:t,drawDefinition:e,drawPosition:r,matchUps:n,event:o}){n.forEach(i=>{i.drawPositions?.includes(r)&&fO({eventId:o?.eventId,tournamentRecord:t,drawDefinition:e,matchUp:i})})}function RS({drawPositionToAdvance:t,inContextDrawMatchUps:e,sourceDrawPositions:r,tournamentRecord:n,drawDefinition:o,matchUpsMap:i,matchUpId:s,event:a}){Tn({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}}=ur({inContextDrawMatchUps:e,drawDefinition:o,matchUpId:s});if(T&&T.structureId===d?.structureId&&tG({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=Wr({structureId:h.target.structureId,drawPosition:y,tournamentRecord:n,drawDefinition:o,event:a});if(P.error)return P}else gO({loserTargetDrawPosition:y,tournamentRecord:n,loserTargetLink:h,drawDefinition:o,loserMatchUp:S,matchUpsMap:i,event:a})}return{...C}}function tG({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:Xa},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:Xa},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?"BYE":Qt,score:void 0,winningSide:void 0,drawPositions:D});let O=u.drawPositions.find(w=>!N.includes(w));Tn({method:c,color:"brightyellow",changedDrawPosition:O,pairedDrawPositionIsBye:M,drawPositionIsBye:R}),gt({tournamentId:n?.tournamentId,matchUp:u,eventId:a?.eventId,context:c,drawDefinition:o});let{targetLinks:{loserTargetLink:v},targetMatchUps:{loserMatchUp:x,loserTargetDrawPosition:F}}=ur({matchUpId:i.matchUpId,inContextDrawMatchUps:e,drawDefinition:o});if(M||R){let w=M?t:A;if(w)RS({drawPositionToAdvance:w,matchUpId:i.matchUpId,inContextDrawMatchUps:e,tournamentRecord:n,drawDefinition:o,matchUpsMap:s});else if(R&&v&&x)if(x.feedRound)gO({loserTargetDrawPosition:F,tournamentRecord:n,loserTargetLink:v,drawDefinition:o,loserMatchUp:x,matchUpsMap:s});else{let k=1-i.roundPosition%2,G=x.drawPositions[k],H=Wr({structureId:v.target.structureId,drawPosition:G,tournamentRecord:n,drawDefinition:o,event:a});if(H.error)return H}}}function gO({loserTargetDrawPosition:t,tournamentRecord:e,loserTargetLink:r,drawDefinition:n,loserMatchUp:o,matchUpsMap:i,event:s}){let{roundNumber:a}=o;Tn({method:"assignFedDrawPositionBye",color:"cyan",loserTargetDrawPosition:t});let p=(i?.mappedMatchUps||{})[o.structureId].matchUps,{initialRoundNumber:m}=Es({drawPosition:t,matchUps:p});if(m===a){let d=Wr({structureId:r.target.structureId,drawPosition:t,tournamentRecord:e,drawDefinition:n,event:s});if(d.error)return d}}function CS({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?"BYE":Qt}),gt({tournamentId:e?.tournamentId,context:"modifyRoundRobinMatchUpsStatus",eventId:i?.eventId,drawDefinition:r,matchUp:a}))})}function Uc(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=(Ie({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:Fs};r||(r=m?.participantId);let{activeDrawPositions:d}=va({drawDefinition:i,structureId:s});return d.includes(n)?{error:rp}:(e||({matchUps:e}=ie({inContext:!0,drawDefinition:i,matchUpsMap:a})),pP({inContextDrawMatchUps:e,tournamentRecord:o,drawDefinition:i,structureId:s,drawPosition:n,matchUpsMap:a,event:c}).drawPositionCleared?(ko({tournamentId:o?.tournamentId,drawDefinition:i,structure:u,event:c}),{...C,participantId:r}):{error:jE})}function pP({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:_t};let c=Ie({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 CS({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(O=>O.includes(I)),P=E?.find(O=>O!==I),A=c.find(O=>O.drawPosition===P),U=d?.[T+1],N=A?.bye,D=U?.pairedDrawPositions?.find(O=>O.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&&(eG({inContextDrawMatchUps:t,targetDrawPosition:y,tournamentRecord:e,drawDefinition:r,structureId:i,roundNumber:T,matchUpsMap:o}),IO({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 eG({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:_t};if(a.structureType===Ve)return;o=o||Pe({drawDefinition:n});let u=(o?.mappedMatchUps||{})[s].matchUps,{initialRoundNumber:p}=Es({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=>IO({drawPosition:e,targetMatchUp:l,inContextDrawMatchUps:t,positionAssignments:d,tournamentRecord:r,drawDefinition:n,matchUpsMap:o,structure:a})),{...C}}function IO({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??Pe({drawDefinition:n});let f=s.mappedMatchUps[a.structureId].matchUps,{initialRoundNumber:g}=Es({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,O,v)=>O.drawPosition===i?v:b,void 0);R!==void 0&&o.sides?.[R]?.lineUp&&(delete o.sides?.[R].lineUp,gt({tournamentId:r?.tournamentId,context:`${u}-TEAM`,eventId:c?.eventId,matchUp:o,drawDefinition:n}))}let I=ur({matchUpId:o.matchUpId,inContextDrawMatchUps:t,drawDefinition:n}),{targetLinks:{winnerTargetLink:h},targetMatchUps:{loserMatchUp:S,winnerMatchUp:T,loserMatchUpDrawPositionIndex:y}}=I,P=e.filter(({drawPosition:D})=>o.drawPositions?.includes(D)).filter(D=>D.bye).length,A=P&&"BYE"||o.matchUpStatus&&pr(o.matchUpStatus)&&o.matcHUpStatus||Qt;o.matchUpStatus=A,o.matchUpStatus&&pr(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&&Tn({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];pP({structureId:S.structureId,drawPosition:R,inContextDrawMatchUps:t,tournamentRecord:r,drawDefinition:n,matchUpsMap:s})}else{let R=Math.min(...D.filter(Boolean)),b=rG({loserMatchUpDrawPosition:R,inContextDrawMatchUps:t,tournamentRecord:r,drawDefinition:n,loserMatchUp:S,matchUpsMap:s,event:c});if(b.error)return _({result:b,stack:u});let v=(s?.mappedMatchUps||{})[S.structureId].matchUps,{initialRoundNumber:x}=Es({drawPosition:R,matchUps:v});x===1&&(Tn({method:u,color:"brightyellow",loserMatchUpDrawPosition:R}),pP({structureId:S.structureId,drawPosition:R,inContextDrawMatchUps:t,tournamentRecord:r,drawDefinition:n,matchUpsMap:s}))}}return T&&T.structureId!==I.matchUp.structureId&&(h.target.feedProfile,fn),{...C}}function rG({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=Uc({drawPosition:t,structureId:o.structureId,inContextDrawMatchUps:e,tournamentRecord:r,drawDefinition:n,matchUpsMap:i,event:s});if(p.error)return p}return{...C}}function wi({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 eo(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 ta(t){return[Ci,Vr].includes(t)}function Ad({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:ln,method:"modifyEntriesStatus",participantIds:o};if(!n&&!m)return{error:Ot};if(i&&!ZU.includes(i))return{error:sf};if(s&&!ru.includes(s))return{error:Vi};let d="modifyEntriesStatus",l=[];if(!i&&!a)return _({result:{error:st},info:"Missing entryStatus",stack:d});if(a&&!Bn({extension:a,requiredAttributes:["name"]}))return _({result:{error:B},info:"Invalid extension",context:{extension:a},stack:d});let f=[];m?.drawDefinitions?.forEach(D=>{let M=wi({stages:p&&[p],drawDefinition:D}).assignedParticipantIds??[];f.push(...M)});let g=r?.participants??[];if(!o.every(D=>{let M=zo({tournamentParticipants:g,participantId:D})?.participantType;return!(M&&[ft,Ar].includes(M)&&ta(i))&&!(i&&m?.eventType&&M===Et&&[Kr,Or].includes(m.eventType)&&[on,...cg].includes(i))}))return{error:sf};let h=m&&Ht({event:m}).flightProfile,S=h?.flights?.find(D=>D.drawId===u),T=D=>{let M=(D||[]).filter(O=>!p||!O.entryStage||p===O.entryStage).filter(({participantId:O})=>o.includes(O)),R=O=>i&&f.includes(O.participantId)&&!(cg.includes(O.entryStatus)&&cg.includes(i));return M.every(O=>R(O)&&!e?!1:(i&&(O.entryStatus=i,delete O.entryPosition),s&&(O.entryStage=s,delete O.entryPosition),a&&(a.value?At({element:O,extension:a}):Ir({element:O,name:a.name})),!0))?{...C}:{error:Gs}},y=({flight:D,drawDefinition:M})=>{m&&(m.entries=eo({entries:m.entries??[]})),D&&(D.drawEntries=eo({entries:D.drawEntries})),M&&(M.entries=eo({entries:M.entries}))},E=D=>{let{flight:M,drawDefinition:R}=D,b="updateDrawEntries";if(M){let O=T(M.drawEntries);if(O.error)return _({result:O,stack:b})}if(R){let O=T(R.entries);if(O.error)return _({result:O,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:MA};if(!S&&!n||i===mo||c&&N){let D=T(m?.entries);if(D?.error)return _({result:D,stack:d});let M;if(i===mo&&(h?.flights?.every(R=>{let b=T(R.drawEntries);return b.error?(M=b.error,!1):(R.drawEntries=R.drawEntries.filter(({participantId:O})=>!o.includes(O)),!0)}),m?.drawDefinitions?.every(R=>{let b=T(R.entries);return b.error?(M=b.error,!1):(R.entries=R.entries?.filter(({participantId:O})=>!o.includes(O)),!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)||bt({tournamentId:r.tournamentId,eventId:m?.eventId,drawDefinition:D});return{...C}}function Po({requireTimeStamp:t,scaleAttributes:e,participant:r}){if(!r)return{error:Wi};if(!ht(e))return{error:B};if(r.timeItems||(r.timeItems=[]),Array.isArray(r.timeItems)){let{accessor:n,scaleType:o,eventType:i,scaleName:s}=e,a=[Pi,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!==Pi)return{error:rc};let g=(n&&ys({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 hO({publishedSeeding:t,usePublishState:e,withSeeding:r,participant:n,event:o}){let i={},s=m=>[Pi,Ao,o.eventType,m].join("."),a=Object.assign({},...(n.timeItems||[]).filter(({itemType:m})=>m.split(".")[1]===Ao).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:Ao,scaleName:g},h=Po({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 SO({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({},...Cf(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 Ru(t){let e=et(t,[{[ne]:!0}]);if(e.error)return e;let{tournamentRecord:r,status:n=Cr}=t,o=`${Ho}.${Wo}`;return J(cd({tournamentRecord:r,itemType:o})?.timeItem?.itemValue?.[n],!1,!0)}function TO(t){let{tournamentId:e}=t??{};return!!e}function Jr({event:t,status:e=Cr}){let r=`${Ho}.${Wo}`;return Au({itemType:r,event:t})?.timeItem?.itemValue?.[e]}function Ud({drawDetails:t,drawId:e}){return t?.[e]?.publishingDetail?.published}function As(t){let{tournamentRecord:e,drawDefinition:r,eventIds:n,eventId:o,drawIds:i,drawId:s,event:a}=t??{};if(e&&!TO(e))return{error:B};if(o&&!a)return{error:qr};if(Array.isArray(n)&&n?.length){let m={};for(let d of n){if(!kt(d))return{error:B};let l=ze({tournamentRecord:e,eventId:d})?.event;if(!l)return{error:qr};let f=mP({event:l});m[d]=f}return{...C,publishState:m}}if(a){let m=mP({event:a}),d={};if(s)return r?{publishState:{status:{published:!!m.status.publishedDrawIds?.includes(s),drawDetail:m.status.drawDetails?.[s]},...C}}:{error:br};if(Array.isArray(i)&&i?.length){let l=a.drawDefinitions?.map(gu)??[];for(let f of i){if(!kt(f))return{error:B};if(!l.includes(f))return{error:br};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=mP({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=Ru({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 mP({event:t}){let e=Jr({event:t});if(!e)return{status:{published:!1}};let r={published:void 0,seedingScaleNames:[],drawIds:[]};e.seeding&&Object.assign(r,e.seeding);let n=e.drawDetails??{};for(let a of t.drawDefinitions?.map(gu)||[])n[a]||(n[a]={publishingDetail:{published:!1}});let o=n&&Object.keys(n).length&&Object.keys(n).filter(a=>Ud({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 bS(t){let{participantMap:e,participantId:r,matchUpStatus:n,roundPosition:o,structureId:i,matchUpType:s,roundNumber:a,matchUpId:c,potential:u,schedule:p,drawId:m,score:d}=t;if(!p||!Object.keys(p).length)return;n==="BYE"||e[r].scheduleItems.push({...p,scheduledDate:Ut(p?.scheduledDate),scheduledTime:zt(p?.scheduledTime),checkScoreHasValue:he({score:d}),matchUpStatus:n,roundPosition:o,structureId:i,matchUpType:s,roundNumber:a,matchUpId:c,potential:u,drawId:m})}function yO({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===Gt&&(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 dP(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,O=i&&b?.length===2&&Object.assign({},...b.map(({sideNumber:v},x)=>{let F=b[1-x].participantId;return v&&{[v]:F}}).filter(Boolean));for(let v of b){let{participantId:x,sideNumber:F,bye:w}=v;if(w)continue;let L=U===F,k=K=>{let Y=o[K]?.participant,j=Y?.participantType,V=[{participantId:K,participantType:j}];if(j!==Ar)for(let $ of Y?.individualParticipantIds||[]){let X=o[$]?.participant;V.push({participantType:X?.participantType,participantId:$})}return V},G=(K,Y)=>{if(s){if(o[K].matchUps[N]={participantWon:L,matchUpType:A,structureId:f,sideNumber:F,matchUpId:N,eventId:M,drawId:R,stage:I},i){let j=k(Y);o[K].matchUps[N].opponentParticipantInfo=j}P&&(o[K].matchUps[N].collectionId=P)}i&&Y&&(o[K].opponents[Y]={participantId:Y,matchUpId:N,eventId:M,drawId:R}),h&&yO({finishingPositionRange:u,participantMap:o,participantWon:L,finishingRound:p,matchUpStatus:m,participantId:K,stageSequence:d,roundNumber:l,structureId:f,matchUpId:N,drawId:R,stage:I}),(r||e)&&bS({participantMap:o,participantId:K,matchUpStatus:m,roundPosition:T,matchUpType:A,roundNumber:l,structureId:f,matchUpId:N,schedule:D,drawId:R,score:g})},H=({participant:K,partnerParticipantId:Y})=>{let j=(V,$)=>{V&&(V.partnerParticipantIds||(V.partnerParticipantIds=[]),V.partnerParticipantIds.includes($)||V.partnerParticipantIds.push($))};c&&j(K?.draws?.[R],Y),a&&j(K?.events?.[M],Y),s&&j(K?.matchUps?.[N],Y)};if(x&&o[x]){let K=O?.[F];G(x,K);let Y=o[x]?.participant.participantType===ft,j=o[x]?.participant.individualParticipantIds||[];if(y){if(n){let V=$=>o[$].matchUps[y]={participantWon:S===F,matchUpId:y,matchUpType:Wt,sideNumber:F};V(x),j.forEach(V)}if(c&&!o[x].draws[R]){let V=E.find(W=>W.sideNumber===F)?.participant?.participantId,$=o[V]?.draws?.[R]?.entryStatus,X=W=>o[W].draws[R]={entryStatus:$,eventId:M,drawId:R};X(x),j.forEach(X)}}if(Y&&(j.forEach(V=>o[V]&&G(V,K)),j.forEach((V,$)=>{let X=j[1-$],W=o[V];W&&H({participant:W,partnerParticipantId:X})}),a&&E)){let V=E.find($=>$.sideNumber===F)?.participant?.participantId;if(V){let $=o[V]?.events[M];$?(o[x].events[M]={...$},j.forEach(X=>o[X].events[M]={...$})):console.log("Missing teamEntry",{eventId:M,teamParticipantId:V})}}if(U){let V=$=>{L?(o[$].counters[A].wins+=1,o[$].counters.wins+=1,m===Bt&&(o[$].counters[A].walkoverWins+=1,o[$].counters.walkoverWins+=1),m===Gt&&(o[$].counters[A].defaultWins+=1,o[$].counters.defaultWins+=1)):(o[$].counters[A].losses+=1,o[$].counters.losses+=1,m===Bt&&(o[$].counters[A].walkovers+=1,o[$].counters.walkovers+=1),m===Gt&&(o[$].counters[A].defaults+=1,o[$].counters.defaults+=1))};V(x),j.forEach(V)}}}}function Cu(t,e){return(t||"").localeCompare(e||"")}function EO(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=v=>{let x=[v];return c[v]?.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={},O=({eventType:v,scaleNames:x,participantId:F})=>c[F]?.participant?.rankings?.[v]?.find(w=>x.includes(w.scaleName))?.scaleValue;for(let v of o?.events||[]){if(e?.eventIds&&!e.eventIds.includes(v.eventId))continue;let{drawDefinitions:x=[],extensions:F=[],eventType:w,eventName:L,category:k,entries:G,eventId:H,gender:K}=v,{flightProfile:Y}=Ht({event:v}),j=Y?.flights??[],V=As({event:v}).publishState;V&&(M[H]=V);let $=V?.status?.publishedSeeding;if(T||S||m){let W=r?Object.assign({},...Cf(F??[])):{};R[H]={...W,eventName:L,eventType:w,category:k,eventId:H,gender:K};let it=[k?.categoryName,k?.ageCategoryCode].filter(Boolean);for(let z of G){let{participantId:Q}=z;if(!Q||!c[Q])continue;let ut=O({eventType:w,scaleNames:it,participantId:Q}),ot,Dt;if(S){let qt=c[Q].participant;({seedAssignments:ot,seedValue:Dt}=hO({publishedSeeding:$,usePublishState:i,withSeeding:S,participant:qt,event:v}))}let Rt=qt=>{if(c[qt]?.events?.[H])return;let Se=c[qt];SO({convertExtensions:r,seedAssignments:ot,participant:Se,withSeeding:S,seedValue:Dt,eventId:H,ranking:ut,entry:z})};Rt(Q),(c[Q].participant.individualParticipantIds||[]).forEach(Rt)}}let X=M?.[H]?.publishedSeeding;if(y||m||S){let W=z=>z?Object.assign({},...z.map(({participantId:Q,seedValue:ut,seedNumber:ot})=>({[Q]:{seedValue:ut,seedNumber:ot}}))):void 0,it=pt([...x.map(gu),...j.map(gu)]);for(let z of it){let Q=x.find(pe=>pe.drawId===z),ut=[k?.categoryName,k?.ageCategoryCode].filter(Boolean),{structures:ot=[],drawOrder:Dt,drawName:Rt,drawType:De}=Q??{},qt=j?.find(pe=>pe.drawId===z),Se=Q?.entries||qt?.drawEntries,_r=qt?.flightNumber,dn=(Q?.structures||[]).sort((pe,me)=>Ni(pe,me)).map(({structureId:pe,structures:me})=>[pe,...(me||[]).map(({structureId:Sr})=>Sr)]).flat(1/0),hr,Xe,Zt,Pt,ce=0,ue=ot.filter(({stage:pe,stageSequence:me})=>pe===rt&&me===1||pe===ct).flatMap(pe=>{let{positionAssignments:me}=Ct({structure:pe}),{seedAssignments:Sr,stageSequence:jr,stage:Kt}=pe;return Kt===rt?(ce=me?.length??0,Zt=me,Pt=Sr):jr===1&&(hr=me,Xe=Sr),me}).map(({participantId:pe})=>pe).filter(Boolean),Fe=W(Pt),te=W(Xe),Je=Q?Se.filter(({participantId:pe})=>ue.includes(pe)):Se,$t=!i||X?.published&&(X?.drawIds?.length===0||X?.drawIds?.includes(z));for(let pe of Je){if(!c[pe.participantId])continue;let{entryStatus:me,entryStage:Sr,entryPosition:jr,participantId:Kt}=pe,Te=O({participantId:Kt,scaleNames:ut,eventType:w}),gr=Ee=>{if(!c[Ee]||c[Ee].draws?.[z])return;let Rn=S&&$t,ee=Rn?{}:void 0,Ur=Rn?Fe?.[Kt]?.seedValue||Fe?.[Kt]?.seedNumber:void 0,Cn=Ur?Fe?.[Kt]:void 0,An=Rn?te?.[Kt]?.seedValue||te?.[Kt]?.seedNumber:void 0,hi=An?te?.[Kt]:void 0;ee&&Ur&&(ee[rt]=Cn),ee&&An&&(ee[ct]=hi);let ga=Ur||An;ga&&(c[Ee].participant.seedings[w]||(c[Ee].participant.seedings[w]=[]),Cn&&c[Ee].participant.seedings[w].push({...Cn,scaleName:z}),hi&&c[Ee].participant.seedings[w].push({...hi,scaleName:z}),ee&&(c[Ee].events[H].seedAssignments||(c[Ee].events[H].seedAssignments={}),Object.keys(ee).forEach(ep=>c[Ee].events[H].seedAssignments[ep]=ee[ep]))),(y||m)&&(c[Ee].draws[z]=nt({seedAssignments:ee,entryPosition:jr,entryStatus:me,entryStage:Sr,seedValue:ga,eventId:H,ranking:Te,drawId:z},!1,!1,!0))};[Vr,Ci].includes(me)||(gr(Kt),(c[Kt].participant.individualParticipantIds||[])?.forEach(gr))}let ir=(Q?.structures??[]).reduce((pe,me)=>(pe.includes(me.stage)||pe.push(me.stage),pe),[]),fr=(Q?.links??[]).length;b[z]={qualifyingPositionAssignments:hr,qualifyingSeedAssignments:Xe,mainPositionAssignments:Zt,qualifyingSeedingMap:te,mainSeedAssignments:Pt,orderedStructureIds:dn,mainSeedingMap:Fe,flightNumber:_r,linksCount:fr,drawOrder:Dt,drawName:Rt,drawType:De,drawSize:ce,drawId:z,stages:ir}}}if(m||l||f||g||I||h||y){let W=!!l||p,it=to({afterRecoveryTimes:!!l,policyDefinitions:n,tournamentRecord:o,inContext:!0,participantMap:c,contextFilters:s,matchUpFilters:a,contextProfile:u,nextMatchUps:W,event:v})?.matchUps??[];for(let z of it){let{finishingPositionRange:Q,potentialParticipants:ut,tieMatchUps:ot=[],sides:Dt=[],winningSide:Rt,matchUpType:De,matchUpId:qt,eventId:Se,drawId:_r,collectionId:dn,stageSequence:hr,finishingRound:Xe,matchUpStatus:Zt,roundPosition:Pt,roundNumber:ce,structureId:ue,schedule:Fe,score:te,stage:Je}=z;N[qt]=z;let $t={finishingPositionRange:Q,finishingRound:Xe,stageSequence:hr,roundPosition:Pt,collectionId:dn,roundNumber:ce,structureId:ue,schedule:Fe,eventId:Se,drawId:_r,score:te,stage:Je};dP({...$t,...A,matchUpStatus:Zt,winningSide:Rt,matchUpType:De,matchUpId:qt,sides:Dt});for(let ir of ot){let{winningSide:fr,sides:pe=[],matchUpId:me,matchUpStatus:Sr,matchUpType:jr}=ir;dP({...$t,...A,winningSide:fr,tieWinningSide:Rt,matchUpTieId:qt,matchUpId:me,sides:pe,matchUpSides:Dt,matchUpStatus:Sr,matchUpType:jr})}Array.isArray(ut)&&(W||l||d)&&ut.flat().map(St).filter(Boolean)?.forEach(fr=>{P(fr)?.forEach(me=>{c[me]&&(c[me].potentialMatchUps[qt]=nt({tournamentId:o?.tournamentId,matchUpId:qt,eventId:Se,drawId:_r}))}),(l||d)&&bS({potential:!0,participantMap:c,participantId:fr,matchUpStatus:Zt,roundPosition:Pt,structureId:ue,matchUpType:De,roundNumber:ce,matchUpId:qt,schedule:Fe,drawId:_r,score:te})})}D.push(...it)}}if(g||m||l){let v=Object.values(c);for(let x of v){let{wins:F,losses:w,[Lt]:{wins:L,losses:k},[vt]:{wins:G,losses:H}}=x.counters,K=(Y,j,V)=>{let $=j+V,X=j,W=$&&X/$;x.statistics[Y]={denominator:$,numerator:X,statValue:W,statCode:Y}};if(g&&(K(pd,F,w),K(`${pd}.${Lt}`,L,k),K(`${pd}.${vt}`,G,H)),m){let Y=(j=[])=>Math.abs(j[0]-j[1]);for(let j of Object.keys(x.draws)){let{orderedStructureIds:V=[],flightNumber:$}=b[j]||{};if(x.structureParticipation&&V.length){let X,W=0,it=V.map(z=>{let Q=x.structureParticipation[z];if(!Q)return;X||(X=Q?.finishingPositionRange),Y(X)>Y(Q?.finishingPositionRange)&&(X=Q?.finishingPositionRange);let ut=Q.stage!==ct;return ut&&(W+=1),nt({...Q,participationOrder:ut?W:void 0,flightNumber:$})}).filter(Boolean);x.draws[j]&&(x.draws[j].finishingPositionRange=X,x.draws[j].structureParticipation=it)}}}if(l){let Y=ht(l)?l.scheduledMinutesDifference:0,j=x.scheduleItems||[],V=x.potentialMatchUps||{},$=j.reduce((W,it)=>{let{scheduledDate:z,scheduledTime:Q}=it;return W[z]||(W[z]=[]),Q&&W[z].push(it),W},{});Object.values($).forEach(W=>W.sort(ah));for(let W of j){let{typeChangeTimeAfterRecovery:it,timeAfterRecovery:z,scheduledDate:Q,scheduledTime:ut}=W,ot=$[Q],Dt=Yt(ut);for(let Rt of ot){if(Rt.matchUpId===W.matchUpId||pr(Rt.matchUpStatus)&&!Rt.checkScoreHasValue)continue;let Se=W.matchUpType!==Rt.matchUpType&&it||z,_r=W.drawId===Rt.drawId,dn=V[W.matchUpId]&&V[Rt.matchUpId],hr=Yt(Rt.scheduledTime),Xe=Math.abs(hr-Dt),Zt=hr>=Dt;if((Y&&!isNaN(Y)?Xe<=Y:Zt&&Yt(Rt.scheduledTime)<Yt(Se))&&!(dn&&_r)&&Zt){let ce=[W.matchUpId,Rt.matchUpId].sort(Cu).join("|");x.scheduleConflicts[ce]={priorScheduledMatchUpId:W.matchUpId,matchUpIdWithConflict:Rt.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 bu({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=ea(l)&&e?.events?.filter(y=>l?.includes(y.eventId))||e?.events||[],I=o&&nG({drawEntryStatuses:o,tournamentEvents:g}),h=s&&oG({eventEntryStatuses:s,tournamentEvents:g}),S=i!==void 0&&[!0,!1].includes(i)&&g.reduce((y,E)=>y.concat(...(E.drawDefinitions||[]).map(P=>Xh({drawDefinition:P}).allPositionedParticipantIds).filter(Boolean)),[]),T=y=>n?.reduce((E,P)=>{let{accessor:A,value:U}=P,{values:N}=ys({element:y,accessor:A});return E&&N?.includes(U)},!0);if(r=r?.filter(y=>{let E=nn({element:y,itemType:Ic})?.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&&ea(u)&&u.includes(A)||a&&U&&ea(a)&&a.includes(U)||c&&ea(P)&&ea(c)&&c.find(R=>P?.includes(R))||n?.length&&ea(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&&ea(u)&&u.includes(A))&&(!a||U&&ea(a)&&a.includes(U))&&(!c||ea(P)&&ea(c)&&c.find(R=>P?.includes(R)))&&(!n?.length||ea(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(Qn)(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 ea(t){return t&&Array.isArray(t)&&t.length}function nG({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 oG({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 Ft(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:q};(T||o)&&an({tournamentRecord:c});let D=aS({convertExtensions:i,tournamentRecord:c,withSignInStatus:p,withScaleValues:d,internalUse:y,withISO2:U,withIOC:N}),{participantMap:M}=D,R=EO({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:O,derivedEventInfo:v,derivedDrawInfo:x,mappedMatchUps:F}=R,w=R.matchUps;M=R.participantMap;let L=u??n,k=({potentialMatchUps:$,scheduleConflicts:X,scheduleItems:W,participant:it,statistics:z,opponents:Q,matchUps:ut,events:ot,draws:Dt})=>{let Rt=Object.values(Dt),De=Object.values(Q);return S&&Rt?.forEach(qt=>{qt.opponents=De.filter(Se=>Se.drawId===qt.drawId)}),nt({...it,scheduleConflicts:u?Object.values(X):void 0,draws:A||o?Rt:void 0,events:P||o?Object.values(ot):void 0,matchUps:T||o?Object.values(ut):void 0,opponents:S?De:void 0,potentialMatchUps:L?Object.values($):void 0,statistics:f?Object.values(z):void 0,scheduleItems:a?W:void 0},!1,!1,!0)},G=new Map;for(let $ of Object.keys(M))G.set($,k(M[$]));let H=[...G.values()],Y=s?.[zs]?.participant,j=bu({participants:H,participantFilters:r,tournamentRecord:c});if(e){let $=ht(e)?e:void 0;for(let X of j)for(let W of X.individualParticipantIds??[]){X.individualParticipants||(X.individualParticipants=[]);let it=G.get(W),z=$?Qi({template:$,source:it}):it;X.individualParticipants.push(z)}}let V=Y?j.map($=>Qi({source:$,template:Y})):j;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:O,derivedEventInfo:v,derivedDrawInfo:x,participants:V,...C}}function Pc({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 Us(t){let{provisionalPositioning:e,drawDefinition:r,stageSequence:n,structureId:o,stage:i}=t;if(!r)return{error:Z};let{entryProfile:s}=Uu({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 Fp({stage:t,drawDefinition:e}){let{entryProfile:r}=Uu({drawDefinition:e});return r?.[t]?.drawSize||0}function AO(t){let{provisionalPositioning:e,drawDefinition:r,stageSequence:n,stage:o}=t,i=Fp({stage:o,drawDefinition:r}),{qualifiersCount:s}=Us({provisionalPositioning:e,drawDefinition:r,stageSequence:n,stage:o});return i&&i-s}function lP({stage:t,drawDefinition:e}){return!!(t===$e||ug({stage:t,drawDefinition:e})&&Fp({stage:t,drawDefinition:e}))}function fP({entryStatus:t=Gr,drawDefinition:e,stageSequence:r,stage:n}){if(t===on)return wb({stage:n,drawDefinition:e})?{positionsAvailable:1/0,...C}:{error:NA};let o=AO({drawDefinition:e,stageSequence:r,stage:n}),i=Lb({drawDefinition:e,stage:n}),s=uS({entryStatus:Pu,drawDefinition:e,stage:n}),a=uS({entryStatus:Gr,drawDefinition:e,stage:n}),c=s+a,u=c>=o,p=o-c;return n!==$e&&u?{error:XI}:t===Pu?s<i?{...C}:{error:XI}:{positionsAvailable:p,...C}}function Pd(t){let e=et(t,[{[Ce]:!0,[Lh]:!0}]);if(e.error)return e;let{suppressDuplicateEntries:r=!0,entryStatus:n=Gr,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!==Fr&&!lP({stage:i,drawDefinition:a}))return _({result:{error:Vi},stack:g});let I=fP({stageSequence:o,stage:i,drawDefinition:a,entryStatus:n});if(!s&&!I.success&&(!l||l!==Fr))return{error:I.error};if(d&&!Bn({extension:d}))return _({result:{error:B},info:"Invalid extension",context:{extension:d},stack:g});let h=t.participantId||u?.participantId;if(!h)return _({result:{error:se},stack:g});let S=n===gs&&Pc({participantId:h,drawDefinition:a,entryStatus:n}),T=i===$e&&Pc({participantId:h,drawDefinition:a,entryStage:i}),y=Pc({participantId:h,drawDefinition:a}),E=n!==gs&&i!==$e&&y;if(E)return r?(lt({payload:{drawId:a.drawId,eventId:f?.eventId,error:bm,participantId:h},topic:Zh}),{...C}):_({result:{error:bm},context:{participantId:h},stack:g});if(S||T)return _({context:{invalidEntry:E,invalidLuckyLoser:S,invalidVoluntaryConsolation:T},result:{error:sp},stack:g});let P=nt({entryStageSequence:o,participantId:h,entryPosition:c,entryStatus:n,entryStage:i,extensions:m});return d&&At({element:P,extension:d}),p&&At({extension:{name:"roundEntry",value:p},element:P}),a.entries||(a.entries=[]),a.entries.push(P),bt({drawDefinition:a}),{...C}}function UO(t){let e="addDrawEntries",{suppressDuplicateEntries:r=!0,entryStatus:n=Gr,autoEntryPositions:o=!0,ignoreStageSpace:i,participantIds:s,drawDefinition:a,stageSequence:c,stage:u=rt,roundTarget:p,extension:m,event:d}=t,l=a.drawType===Fr;if(!u)return{error:oA};if(!a)return{error:Z};if(!Array.isArray(s))return{error:wr};if(!l&&!lP({stage:u,drawDefinition:a}))return{error:Vi};if(m&&!Bn({extension:m}))return _({result:{error:B},info:"Invalid extension",context:{extension:m},stack:e});let f=fP({drawDefinition:a,stageSequence:c,entryStatus:n,stage:u});if(!i&&!f.success&&!l)return{error:f.error};let g=f.positionsAvailable??0;if(!i&&!l&&u!==$e&&g<s.length)return{error:of};let I=[],h=a.drawId,S=d?.eventId,T=s.reduce((y,E)=>{let P=n===gs&&Pc({participantId:E,drawDefinition:a,entryStatus:n}),A=u===$e&&Pc({entryStage:u,drawDefinition:a,participantId:E}),U=Pc({participantId:E,drawDefinition:a});return n!==gs&&u!==$e&&U&&(I.push(E),r&<({payload:{error:bm,participantId:E,eventId:S,drawId:h},topic:Zh})),P||A?y.concat(E):y},[]);return I.length&&!r?_({context:{eventId:S,drawId:h,duplicateEntries:I},result:{error:bm},stack:e}):(s.filter(y=>y&&!T.includes(y)).forEach(y=>{let E={entryStageSequence:c,entryStage:u,participantId:y,entryStatus:n};m&&At({element:E,extension:m}),p&&At({extension:{name:vn,value:p},element:E}),a.entries||(a.entries=[]),a.entries.push(E)}),o&&(a.entries=eo({entries:a.entries})),bt({drawDefinition:a}),T?.length||I?.length?{info:"some participantIds could not be added",participantIdsNotAdded:T,duplicateEntries:I,...C}:{...C})}function hg({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:bo};if(!m)return{error:qr};if(!p)return{error:cn};let d=(m.entries||[]).map(St);if(o.filter(I=>!d.includes(I)).length)return{error:rA};if(i){let I=UO({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===gs&&gP({participantId:I,entryStatus:s,flight:g}),S=c===$e&&gP({participantId:I,entryStage:c,flight:g});!(s!==gs&&c!==$e&&gP({flight:g,participantId:I}))&&!h&&!S&&g.drawEntries.push({participantId:I,entryStatus:s,entryStage:c})}),e&&(g.drawEntries=eo({entries:g.drawEntries}))),{...C}}function gP({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 Dc({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=>!kt(m)))return _({result:{error:ln},stack:i});let s=(o.drawDefinitions??[]).flatMap(m=>wi({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:Gs},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=eo({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 IP={[er]:{policyName:"matchUpActionsDefault",enabledStructures:[{stages:[],stageSequences:[],enabledActions:[],disabledActions:[]}],participants:{enforceCategory:!0,enforceGender:!0},processCodes:{substitution:["RANKING.IGNORE","RATING.IGNORE"]},substituteAfterCompleted:!1,substituteWithoutScore:!1}},Ps=IP;function Wn(t){let{suppressDuplicateEntries:e=!0,entryStatus:r=Gr,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:bo},stack:I});if(!g?.eventId)return{error:qr};let S=Tt({tournamentRecord:c,event:g}).appliedPolicies??{},T=s?.[er]??S?.[er]??Ps[er],y=(o??T?.participants?.enforceGender)!==!1,E=[],P=[];if(d&&(!Array.isArray(d)||!d.every(x=>Bn({extension:x})))||l&&!Bn({extension:l}))return _({context:nt({extension:l,extensions:d}),result:{error:B},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(Lt)(g.eventType)&&x.participantType===Et&&!ta(r),w=g.eventType===vt&&x.participantType===ft;return F&&(!g.gender||!y||en(g.gender)||To(g.gender)||yr(g.gender)===yr(x.person?.sex))||w&&!ta(r)?!0:g.eventType===vt&&x.participantType===Et&&ta(r)?g.gender&&y&&!(en(g.gender)||To(g.gender))&&yr(g.gender)!==yr(x.person?.sex)?(U.push({participantId:x.participantId,sex:x.person?.sex}),!1):!0:F&&g.gender&&y&&!(en(g.gender)||To(g.gender))&&yr(g.gender)!==yr(x.person?.sex)?(U.push({participantId:x.participantId,sex:x.person?.sex}),!1):g.eventType===wt&&(x.participantType===wt||ta(r)&&x.participantType===Et)}).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&&At({element:F,extension:l}),m&&At({extension:{name:vn,value:m},element:F}),i&&(F.entryStageSequence=i),E.push(F.participantId),g.entries?.push(F)}}),f&&!ta(a)){let x=hg({participantIds:M,suppressDuplicateEntries:e,autoEntryPositions:n,entryStageSequence:i,ignoreStageSpace:u,drawDefinition:p,entryStatus:r,roundTarget:m,entryStage:a,extension:l,drawId:f,event:g});x.error&&(N=x.error)}if(g.eventType&&[Ko,Or].includes(g.eventType)){let x=(g.entries||[]).map(G=>G.participantId),F=(g.entries||[]).filter(G=>ta(G.entryStatus)).map(G=>G.participantId),L=(c?.participants??[]).filter(G=>x.includes(G.participantId)&&G.participantType&&[ft,wt].includes(G.participantType)).map(G=>G.individualParticipantIds).flat(1/0),k=F.filter(G=>L.includes(G));k.length&&(P.push(...k),Dc({participantIds:k,autoEntryPositions:!1,event:g}))}if(M.length!==h.length)return _({context:{mismatchedGender:U,gender:g.gender},result:{error:wr},stack:I});n&&(g.entries=eo({entries:g.entries||[]}));let O=E.length,v=P.length;return _({result:{...C,addedEntriesCount:O,removedEntriesCount:v},stack:I,info:N})}var hP="ADMINISTRATION",iG="CAPTAIN",sG="COACH",xe="COMPETITOR",SP="MEDIA",TP="MEDICAL",Sg="OFFICIAL",yP="OTHER",EP="SECURITY",Dd={ADMINISTRATION:hP,CAPTAIN:iG,COACH:sG,COMPETITOR:xe,MEDIA:SP,MEDICAL:TP,OFFICIAL:Sg,OTHER:yP,SECURITY:EP};function Tg({addIndividualParticipantsToEvents:t,individualParticipantIds:e,groupingParticipantId:r,tournamentRecord:n,suppressErrors:o}){let i="removeIndividualParticipantIds";if(!n)return _({result:{error:q},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(![wt,Qr].includes(a.participantType))return _({result:{participantType:a.participantType,error:Pn},stack:i});let c=PO({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));Wn({participantIds:l,entryStatus:Vr,tournamentRecord:n,event:m})}}return u&<({topic:rr,payload:{tournamentId:n.tournamentId,participants:[a]}}),{...C,...c}}function PO({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}=Ft({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||he({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:wo}),y=T?.value[e.participantId];T&&y&&(T.value[e.participantId]=y.filter(P=>P.participantId!==l),At({element:S,extension:T}),Ma({drawDefinition:S}));let E=nr({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:ip}||d}function kp({participantRole:t=xe,individualParticipantIds:e=[],groupingTypes:r=[Ar,Qr],tournamentRecord:n}){if(!n)return{error:q};let o=n.participants??[],{participants:i,mappedMatchUps:s}=Ft({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}=PO({groupingParticipant:c,individualParticipantIds:e,tournamentRecord:n,mappedMatchUps:s,participants:i});u&&a++}),a?C:{error:AA}}function ns(t){let e=et(t,[{[ne]:!0},{participantIds:!0,[He]:Be,[In]:bo}]);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=Ft({participantFilters:{participantIds:o},tournamentRecord:n,withDraws:!0}).participants??[],c=f=>{let I=(ye({matchUpFilters:{drawIds:f,matchUpTypes:[vt]},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:Gs};let m={},d={};for(let f of n.events||[]){let g=Dc({participantIds:o,event:f});if(g.error)return g;m[f.eventId]=g.participantIdsRemoved}n.participants=(n.participants??[]).filter(f=>{let g=o.includes(f.participantId)||f.participantType===ft&&f.individualParticipantIds?.some(I=>o.includes(I));if(!g&&f.participantType===_e&&f.individualParticipantIds?.some(I=>o.includes(I))&&(f.individualParticipantIds=f.individualParticipantIds.filter(I=>!o.includes(I))),g&&r&&f.participantType&&[ft,wt].includes(f.participantType))for(let I of f.individualParticipantIds||[])o.includes(I)||(d[f.participantId]||(d[f.participantId]=[]),d[f.participantId].push(I));return!g});let l=i-n.participants.length;if(kp({individualParticipantIds:o,tournamentRecord:n}),r)for(let f of n.events||[]){let I=m[f.eventId].map(h=>d[h]||[]).flat();Wn({participantIds:I,entryStatus:Vr,tournamentRecord:n,event:f})}return l&<({payload:{participantIds:o,tournamentId:n.tournamentId},topic:qf}),l?{...C,participantsRemovedCount:l}:{error:ip}}function OS({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&&Xr.includes(c.entryStatus)));return{entries:s,stageEntries:a}}function AP({removeGroupParticipant:t,tournamentRecord:e,drawDefinition:r,participantId:n,drawId:o,stage:i,event:s}){let a="destroyGroupEntry";if(!e)return{error:q};if(!n)return _({result:{error:se},stack:a});if(!s)return{error:Ot};if(!s.eventType||![Ko,Or].includes(s.eventType))return _({result:{error:$n},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,Ar].includes(u.participantType)||u.participantType===Ar&&s.eventType!==Or||u.participantType===ft&&s.eventType!==Ko)return{error:Pn};let m=(s.entries??[]).find(S=>S.participantId===n);if(!m)return{error:QI};let{stageEntries:d}=OS({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=>ho(S,f).length===1),I=Dc({participantIds:[n],event:s});if(I.error||g?.length&&(I=Wn({participantIds:g,entryStatus:Vr,entryStage:m.entryStage,tournamentRecord:e,drawDefinition:r,drawId:o,event:s}),I.error))return I;let h;return t&&ns({participantIds:[n],tournamentRecord:e}).success&&(h=!0),{...C,participantRemoved:h}}function yg({removeGroupParticipant:t,tournamentRecord:e,drawDefinition:r,participantId:n,drawId:o,event:i}){return AP({removeGroupParticipant:t,tournamentRecord:e,drawDefinition:r,participantId:n,drawId:o,event:i})}function UP(t){if(!t.tournamentRecord)return{error:q};let{participantIds:e,...r}=t,n=0,o=[];for(let i of e){let s=AP({participantId:i,...r});s.success&&(n+=1),s.error&&o.push(s.error)}return n?{destroyedCount:n,...C}:{error:o}}function Ou(t){let{tournamentRecord:e,replaceWithBye:r,drawDefinition:n,destroyPair:o,entryStatus:i,matchUpsMap:s,drawId:a}=t,c="removeDrawPositionAssignment",u=Uc(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([on,mo].includes(i)&&p){let{tournamentRecord:h}=t,{participant:S}=Uo({tournamentRecord:h,participantId:p}),{participantType:T,individualParticipantIds:y}=S??{};if(o&&T===ft){let E=yg({tournamentRecord:h,drawDefinition:n,participantId:p,event:d});if(E.error)return _({result:E,stack:c});y&&Ad({participantIds:y,tournamentRecord:h,drawDefinition:n,entryStatus:i,drawId:a,event:d})}else Ad({participantIds:[p],tournamentRecord:h,drawDefinition:n,entryStatus:i,drawId:a,event:d})}if(r){let h=Wr({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 ad({structure:g,drawPositions:[m]}),hu({appliedPolicies:f,drawDefinition:n,positionAction:{name:"removeDrawPositionAssignment",replaceWithBye:r,drawPosition:m,entryStatus:i,structureId:l}}),u}function PP(t){return Object.assign(t,{entryStatus:mo}),Ou(t)}var Ds=({finishingPosition:t=zi,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??Nt(),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},yn=Ds;function vS(t){return kt(t)?t.split(" ").map(e=>e.split("").map((r,n)=>n?r.toLowerCase():r.toUpperCase()).join("")).join(" "):t}function Qe(t){return kt(t)?vS(t.replace(/_/g," ")):""}function Eg({structureName:t=Qe($e),structureAbbreviation:e,drawDefinition:r,matchUpType:n,structureId:o}){if(!r)return{error:Z};let i=yn({stage:$e,structureAbbreviation:e,structureName:t,matchUps:[],structureId:o,matchUpType:n});return r.structures||(r.structures=[]),r.structures.push(i),bt({drawDefinition:r,structureIds:[i.structureId]}),{...C}}function Ag({drawPositions:t}){if(!t?.length)return{error:Ja};let e=o=>t.filter(i=>i!==o).map(i=>[o,i]),r=[].concat(...(t??[]).map(e)),n=pt(r.map(Ug)).map(o=>o.split("|").map(i=>+i));return{groupMatchUps:r,uniqueMatchUpGroupings:n}}function Ug(t=[]){return!Array.isArray(t)||!t.length?"":[...t].sort(le).join("|")}function DP({groupSize:t,drawPositionOffset:e}){if(!t)return[];let r=m=>[...Array(m)].map((d,l)=>l),n=r(2*Math.round(t/2)+1).slice(1),o=r(n.length-1).map(()=>[]),i=n.slice(0,n.length/2),s=n.slice(n.length/2);n.slice(1).forEach((m,d)=>{i.forEach((I,h)=>{o[d].push([i[h],s[h]])});let l=i.shift(),f=i.pop(),g=s.shift();i=[l,g,...i].filter(Boolean),s=[...s,f].filter(Boolean)});let a=i.shift(),c=i.pop(),u=s.shift();i=[a,u,...i].filter(Boolean),s=[...s,c].filter(Boolean);let p=m=>m[0].reduce((d,l)=>d+l);return[...o].reverse().sort((m,d)=>p(m)-p(d)).map(m=>m.filter(d=>d.every(l=>l<=t)).map(d=>{let l=d.map(f=>f+e);return Ug(l)}))}function aG({rounds:t,hash:e}){return t?.length?t?.reduce((r,n,o)=>n.includes(e)?o+1:r,void 0):{error:st}}var DO={getRoundRobinGroupMatchUps:Ag,determineRoundNumber:aG,drawPositionsHash:Ug,groupRounds:DP};function xa(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}=cG({structureOptions:i,appliedPolicies:s,drawSize:g}),P=Ei,A,U=tt(1,y+1).map(D=>{let M=uG({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 Ds({structureId:S?.pop(),hasExistingDrawDefinition:e,structureType:hp,finishingPosition:P,qualifyingOnly:a,structureOrder:D,structureName:R,tieFormat:f,matchUps:M})}),N=Ds({structureId:d??S?.pop(),hasExistingDrawDefinition:e,structureType:Ve,finishingPosition:P,seedingProfile:c,structureName:T,stageSequence:o,structures:U,tieFormat:f,stage:u});return m&&At({extension:{name:vn,value:m},element:N}),{structures:[N],maxRoundNumber:A,groupCount:y,links:[],groupSize:E,...C}}function cG({appliedPolicies:t,structureOptions:e,drawSize:r}){let n=e?.groupSize,o=e?.groupSizeLimit||8,{validGroupSizes:i}=Gp({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 Gp(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 uG({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=Ag({drawPositions:c}).uniqueMatchUpGroupings??[],p=DP({groupSize:r,drawPositionOffset:a});return u.map(l).sort((f,g)=>(f.roundNumber??1/0)-(g.roundNumber??1/0));function d(f){return p.reduce((g,I,h)=>I.includes(f)?h+1:g,void 0)}function l(f){let g=Ug(f),I=d(g),h=[1,n],S=pG({structureOrder:t,drawPositions:f,roundNumber:I,idPrefix:o,uuids:s}),T={matchUpStatus:I?Qt:"BYE",matchUpType:e,finishingPositionRange:{winner:h,loser:h},drawPositions:f,roundNumber:I,matchUpId:S};return i&&(T.isMock=!0),T}}function pG({structureOrder:t,drawPositions:e,roundNumber:r,idPrefix:n,uuids:o}){return n?`${n}-${t}-${r}-DP-${e.join("-")}`:o?.pop()||Nt()}function Pg(t){let{roundRobinGroupsCount:e,participantsCount:r,cluster:n}=t;if(!It(r))return{seedBlocks:void 0,..._({result:{error:B},context:{participantsCount:r},stack:"getSeedBlocks"})};let o=us(r);if(e){let l=Math.min(e,o),f=[],g=1;for(tt(0,l).forEach(()=>{f.push([g]),g++});g<o;){let I=tt(g,g+l);g+=l,f.push(I)}return{...C,seedBlocks:f}}let i=tt(1,o+1),s=[],a=o/2;for(;a>1;){let l=Ae(i,a),f=l.length;l.forEach((g,I)=>{let h,S=I<f/2,T=I%2===0,y=g[0],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 Dg({roundRobinGroupsCount:t,drawSize:e}){let r="getSeedGroups";if(!It(e))return{seedGroups:void 0,..._({result:{error:B},context:{drawSize:e},stack:r})};if(t){if(!It(t))return{seedGroups:void 0,..._({context:{roundRobinGroupsCount:t},result:{error:B},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}=Pg({participantsCount:e,roundRobinGroupsCount:t}),o=0;return{seedGroups:(n||[]).map(s=>(s||[]).map(()=>(o+=1,o)))}}}function _S({roundRobinGroupsCount:t,participantsCount:e}){if(t){let{validGroupSizes:o}=Gp({drawSize:e});if(!o?.map(a=>Math.ceil(e/a))?.includes(t))return _({context:{roundRobinGroupsCount:t},result:{error:B}})}let{seedGroups:r}=Dg({drawSize:e,roundRobinGroupsCount:t}),n=r?.map(o=>Math.min(...o))||[];return{...C,seedingThresholds:n}}function Nc(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 mG({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 NO({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 MO({positioning:t,size:e}){let r=mG({size:e}),n=[],o=[],i=d=>d[0],s=d=>d[d.length-1],a=(d,l)=>(t&&[nu,Ti].includes(t)&&l%2?s(d):i(d))||i(d),c=(d,l)=>{if(d.every(f=>!o.includes(f))){let f=a(d,l);return o.push(f),f}},u=d=>{let l=d.filter(f=>!o.includes(f));if(l.length)return o.push(...l),l},p=(d,l)=>{let f=a(d,l);if(!o.includes(f))return o.push(f),f},m=tt(1,e+1);for(let d of r)if(d===1){let l=Ae(m,2),f=l.map(c).filter(Boolean);f.length&&n.push(f);let g=l.flatMap(u).filter(Boolean);g.length&&n.push(g)}else{let f=Ae(m,d).map(p).filter(Boolean);f.length&&n.push(f)}return{divisions:r,divisionGroupings:n}}function Ns({provisionalPositioning:t,returnAllProxies:e,appliedPolicies:r,seedingProfile:n,drawDefinition:o,allPositions:i,structure:s}){let a=[];if(!s)return{error:Si};let{matchUps:c,roundMatchUps:u}=yt({matchUpFilters:{roundNumbers:[1]},provisionalPositioning:t,structure:s}),{seedAssignments:p}=sn({provisionalPositioning:t,returnAllProxies:e,drawDefinition:o,structure:s}),{positionAssignments:m}=Ie({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(G=>G.drawPositions).flat(1/0).filter(Boolean),k=L.filter(G=>!f.includes(G));return f=f.concat(...L),k}).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,O=gd({drawDefinition:o,structure:s,matchUps:c}),v=O?0:!N&&b||b&&M.length<b&&b-M.length||0;if(D){let w=s?.matchUps?s.matchUps.filter(({roundNumber:k})=>k===s.roundLimit).length:0,L=h.length/w;if(!N){let k=Bp(n),G=Ae(h,L),H=1,K=tt(0,G[0].length).map(()=>{let Y=tt(H,H+G.length);return H+=G.length,Y});({validSeedBlocks:a}=RO({drawPositionBlocks:G,nonRandom:n?.nonRandom,positioning:k,seedGroups:K}))}}else U?{validSeedBlocks:a}=dG({nonRandom:n?.nonRandom,seedingProfile:n,structure:s}):N?a=y.map(w=>({seedNumbers:w,drawPositions:w})):O&&Ae(h,2).map((L,k)=>({drawPositions:[L[0]],seedNumbers:[k+1]})).forEach(L=>a.push(L));if(!U&&!O&&!D){let{blocks:w}=lG({drawPositionOffset:S,seedNumberOffset:R,seedCountGoal:v,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!O&&!N&&!U&&!F?{error:JE,validSeedBlocks:[],isContainer:U,isFeedIn:N}:{isLuckyStructure:O,validSeedBlocks:a,isContainer:U,isFeedIn:N}}function dG({seedingProfile:t,structure:e,nonRandom:r}){let n=e.structures||[],o=n.length,i=Ct({structure:e})?.positionAssignments,s=Bp(t),a=i?.length??0,{seedGroups:c}=Dg({roundRobinGroupsCount:o,drawSize:a}),u=n.map(p=>Ct({structure:p}).positionAssignments?.map(m=>m.drawPosition));return RO({drawPositionBlocks:u,positioning:s,seedGroups:c,nonRandom:r})}function RO({drawPositionBlocks:t,positioning:e,seedGroups:r,nonRandom:n}){let o=[],{divisionGroupings:i}=MO({size:r.length,positioning:e}),s=[];return r.forEach((a,c)=>{let u=NO({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!==Ti?f=n?f:Tr(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 lG(t){let{drawPositionOffset:e=0,roundRobinGroupsCount:r,seedNumberOffset:n=0,seedingProfile:o,seedCountGoal:i,baseDrawSize:s}=t,a=1,c=[],{seedBlocks:u}=Pg({cluster:Bp(o)===nu,participantsCount:s,roundRobinGroupsCount:r});a=0;for(let m of u){if(a+1>i)break;let d=m.map(f=>f+e),l=p(a+1,m.length).map(f=>+f+n);a+=m.length,c.push({drawPositions:d,seedNumbers:l})}return{blocks:c};function p(m,d){return Array.from(new Array(d),(l,f)=>f+m)}}function Vp({appliedPolicies:t,drawDefinition:e,seedBlockInfo:r,drawPosition:n,structureId:o,seedNumber:i}){let{structure:s}=at({drawDefinition:e,structureId:o});t||(t=Tt({drawDefinition:e}).appliedPolicies);let a=r?.validSeedBlocks;return!a&&s&&(a=Ns({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 xS(t){let{provisionalPositioning:e,drawDefinition:r,seedingProfile:n,seedBlockInfo:o,structureId:i,randomize:s}=t,{structure:a}=at({drawDefinition:r,structureId:i}),{seedAssignments:c}=sn({returnAllProxies:t.returnAllProxies,provisionalPositioning:e,drawDefinition:r,structure:a}),{positionAssignments:u}=Ie({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&&Ns({returnAllProxies:t.returnAllProxies,provisionalPositioning:e,appliedPolicies:d,drawDefinition:r,seedingProfile:n,structure:a})?.validSeedBlocks||[]).filter(L=>L.drawPositions.filter(G=>!m?.includes(G)).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?Tr(A):A,N=[],D=U.map(()=>{let k=w(y,N)?.participantId;return k&&N.push(k),k}).filter(Boolean),M=c?.filter(L=>S?.includes(L.participantId)).map(L=>L.seedNumber),b=(g?.seedNumbers||[]).filter(L=>!M?.includes(L)),O=c?.filter(L=>b.includes(L.seedNumber)).map(L=>L.participantId),v=d?.seeding?.duplicateSeedNumbers;return{nextSeedBlock:g,unplacedSeedParticipantIds:(v!==void 0?v:!0)?D:O,unplacedSeedNumbers:b,unfilledPositions:U,unplacedSeedAssignments:y};function w(L,k){let G=L.filter(j=>!k.includes(j.participantId)),H=Math.min(...G.map(j=>Nc(j.seedValue))),K=G.filter(j=>Nc(j.seedValue)===H);return Tr(K).pop()}}function Bp(t){if(typeof t=="string")return t;if(typeof t=="object")return t.positioning}function ra({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}=Ie({structure:d}),f=sn({provisionalPositioning:t,drawDefinition:r,structure:d}).seedAssignments,g=f.map(P=>P.seedNumber),I=Pc({drawDefinition:r,participantId:o});if(o&&!I)return _({result:{error:ln},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&&!Vp({drawPosition:y,drawDefinition:r,seedBlockInfo:i,structureId:s,seedNumber:a}))return _({result:{error:Yl},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?(rS({tournamentId:e?.tournamentId,drawDefinition:r,structure:d,eventId:u}),{...C}):_({result:{error:XE},stack:m})}function Nd({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:wo}),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 wS(t){let{sourceMatchUp:e}=t,{targetMatchUp:r,structure:n,matchUpsMap:o,drawPosition:i}=t,s=r.roundNumber>1&&r.roundNumber-1,a=Vo({structureId:n.structureId,matchUpsMap:o});!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=[oe,be].includes(d);return{pairedPreviousMatchUp:m,pairedPreviousMatchUpIsDoubleExit:l}}function CO({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 LS({structureId:t,matchUpsMap:e,matchUp:r}){let n=r?.roundPosition,o=n%2?1:-1,i=n+o;return{pairedPreviousMatchUp:Vo({matchUpsMap:e,structureId:t}).find(({roundNumber:c,roundPosition:u})=>c===r?.roundNumber&&u===i)}}function FS({inContextDrawMatchUps:t,sourceMatchUpStatus:e,sourceMatchUpId:r,matchUpsMap:n,matchUp:o}){let i=t.find(a=>a.matchUpId===r),{pairedPreviousMatchUp:s}=LS({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=kt(p)||!isNaN(p)?{code:p}:p;return m.sideNumber===u?{...m,previousMatchUpStatus:e}:m})}}function Md({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 wa({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=Pe({drawDefinition:o})),t||(t=ie({inContext:!0,drawDefinition:o,matchUpsMap:a}).matchUps??[]);let m=t.find(O=>O.matchUpId===c),d=m?.structureId,l=o?.structures?.find(O=>O.structureId===d);if(!l)return{error:_t};let f=a?.drawMatchUps?.find(O=>O.matchUpId===c),g=f?.drawPositions??[],{positionAdded:I,positionAssigned:h,updatedDrawPositions:S}=CO({drawPositions:g,drawPosition:s}),{positionAssignments:T}=Ct({drawDefinition:o,structure:l}),E=T?.filter(O=>S.includes(O.drawPosition))?.find(({bye:O})=>O),P=f?.matchUpStatus&&pr(f.matchUpStatus)&&S.filter(Boolean).length<2;i=E&&"BYE"||i||P&&f.matchUpStatus||f?.matchUpStatus&&[oe,be].includes(f.matchUpStatus)&&f.matchUpStatus||Qt;let A=!!(pr(f?.matchUpStatus)&&f?.winningSide);if(f&&I){t=ie({inContext:!0,drawDefinition:o,matchUpsMap:a}).matchUps??[];let O=P&&Md({inContextDrawMatchUps:t,drawPosition:s,matchUpId:c})||A&&f.winningSide||void 0;f?.matchUpStatusCodes&&FS({inContextDrawMatchUps:t,sourceMatchUpStatus:e,sourceMatchUpId:n,matchUpsMap:a,matchUp:f}),Object.assign(f,{drawPositions:S,winningSide:O,matchUpStatus:A?f?.matchUpStatus:i}),gt({tournamentId:r?.tournamentId,eventId:m?.eventId,context:p,drawDefinition:o,matchUp:f})}let U=ur({inContextDrawMatchUps:t,inContextMatchUp:m,drawDefinition:o,matchUpId:c}),{targetMatchUps:{winnerMatchUp:N,loserMatchUp:D,loserTargetDrawPosition:M},targetLinks:{loserTargetLink:R}}=U,b=Vo({structureId:l.structureId,matchUpsMap:a});if(h&&E){if(N)if(["BYE",oe,be].includes(i)){let O=wa({matchUpId:N.matchUpId,inContextDrawMatchUps:t,tournamentRecord:r,drawDefinition:o,drawPosition:s,matchUpsMap:a});if(O.error)return O}else{let{structureId:O}=N;O!==l.structureId&&console.log("winnerMatchUp in different structure... participant is in different targetDrawPosition")}}else if(h&&A){if(N){let O=wa({matchUpId:N.matchUpId,inContextDrawMatchUps:t,tournamentRecord:r,drawDefinition:o,drawPosition:s,matchUpsMap:a});if(O.error)return O}}else if(N&&m&&!m.feedRound){let{pairedPreviousMatchUpIsDoubleExit:O}=wS({targetMatchUp:f,drawPosition:s,matchUpsMap:a,structure:l});if(O){let v=wa({matchUpId:N.matchUpId,inContextDrawMatchUps:t,tournamentRecord:r,drawDefinition:o,drawPosition:s,matchUpsMap:a});if(v.error)return v}}if(f?.matchUpType===Wt){let O=t?.find(({matchUpId:w})=>w===f.matchUpId),x=(O?.sides??[]).reduce((w,L,k)=>L.drawPosition===s?k:w,void 0),F=T?.find(w=>w.drawPosition===s)?.participantId;F&&x!==void 0&&Nd({inContextTargetMatchUp:O,drawPositionSideIndex:x,teamParticipantId:F,tournamentRecord:r,drawDefinition:o,matchUp:f})}if(R?.linkCondition===kn&&S.filter(Boolean).length===2&&!E&&b.filter(({drawPositions:x,roundNumber:F})=>F===1&&ke(x,S)).every(({matchUpStatus:x})=>[ge,Me].includes(x))&&D){let{structureId:x}=D,F=Wr({drawPosition:M,tournamentRecord:r,drawDefinition:o,structureId:x,matchUpsMap:a,event:u});if(F.error)return F}return h?{...C}:_({result:{error:Xa},context:{drawPosition:s},stack:p})}function kS({inContextDrawMatchUps:t,drawDefinition:e,assignments:r,matchUpsMap:n,structure:o}){let s=fs({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 Rd({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}=Lp({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 li(t){return`${t} must be an array`}function Cd({lineUp:t,tieFormat:e}){let r=[];if(!Array.isArray(t))return r.push(li("lineUp")),{valid:!1,errors:r,error:B};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(li("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?B:void 0}}function os({drawDefinition:t,participantId:e,tieFormat:r,lineUp:n}){if(typeof t!="object")return{error:Z};if(typeof e!="string")return{error:se};let o=Cd({lineUp:n,tieFormat:r});if(!o.valid)return o;let{extension:i}=mt({element:t,name:wo}),s=i?.value||{};return s[e]=Rd({lineUp:n}),At({element:t,extension:{name:wo,value:s}}),Ma({drawDefinition:t}),{...C}}function Ng({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}=kS({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&&os({drawDefinition:n,participantId:I,lineUp:[],tieFormat:g})}gt({tournamentId:r?.tournamentId,context:"resetLineUps",eventId:a?.eventId,drawDefinition:n,matchUp:f})}}});return{...C}}function jn({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:se},stack:l});p=p??Pe({drawDefinition:i}),e||({matchUps:e}=ie({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:_t};if(cr({structure:g}))return _({result:{error:dr},stack:l});let{seedAssignments:I}=sn({provisionalPositioning:t,drawDefinition:i,structure:g}),S=I?.find(O=>O.participantId===a)?.seedNumber,{appliedPolicies:T}=Tt({tournamentRecord:o,drawDefinition:i,structure:g,event:d});if(S&&!Vp({seedNumber:S,appliedPolicies:T,drawDefinition:i,seedBlockInfo:c,drawPosition:u,structureId:m}))return _({result:{error:Yl},context:{drawPosition:u},stack:l});let E=Ie({structure:g}).positionAssignments||[],P=E?.find(O=>O.drawPosition===u);if(!P)return _({result:{error:Ls},context:{drawPosition:u},stack:l});if(E?.map(St).includes(a))return _({result:{error:Gs},context:{drawPosition:u},stack:l});let{containsParticipant:U,containsBye:N}=b(P);if(N){let O=Uc({inContextDrawMatchUps:e,tournamentRecord:o,drawDefinition:i,drawPosition:u,structureId:m,matchUpsMap:p,event:d});if(O.error)return _({result:O,stack:l})}if(U&&P.participantId!==a){let{activeDrawPositions:O}=va({drawDefinition:i,structureId:m});if(O.includes(u))return _({result:{error:rp},stack:l});Ng({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 O=g.stage===ct?ct:rt,F=(i.structures?.find(w=>w?.stage===O&&w?.stageSequence===1)?.seedAssignments??[]).find(w=>w.participantId===a);if(F?.participantId){let{participantId:w,seedNumber:L,seedValue:k}=F;ra({eventId:d?.eventId,provisionalPositioning:t,tournamentRecord:o,drawDefinition:i,seedingProfile:s,participantId:w,seedNumber:L,seedValue:k,structureId:m,event:d})}}if(g.structureType!==Ve)fG({provisionalPositioning:t,inContextDrawMatchUps:e,sourceMatchUpStatus:n,tournamentRecord:o,drawDefinition:i,drawPosition:u,matchUpsMap:p,structure:g,event:d});else{CS({positionAssignments:E,tournamentRecord:o,drawDefinition:i,matchUpsMap:p,structure:g});let{drawPositions:O,matchUps:v,targetMatchUps:x}=kS({assignments:[P],inContextDrawMatchUps:e,drawDefinition:i,matchUpsMap:p,structure:g});if(O&&v?.length===1&&v[0].matchUpType===Wt){let w=(x?.[0].sides??[]).reduce((L,k,G)=>O?.includes(k.drawPosition)?G:L,void 0);Nd({inContextTargetMatchUp:x[0],teamParticipantId:a,matchUp:v[0],drawPositionSideIndex:w,tournamentRecord:o,drawDefinition:i})}}let M=i.entries?.find(O=>O.participantId===a),R=d?.entries?.find(O=>O.participantId===a);return!M&&R&&Pd({entryStatus:R.entryStatus,entryStage:g.stage,ignoreStageSpace:!0,drawDefinition:i,participantId:a,event:d}),ko({tournamentId:o?.tournamentId,drawDefinition:i,structure:g,event:d}),{positionAssignments:E,...C};function b(O){let v=O.bye,x=O.qualifier,F=O.participantId;return{containsBye:v,containsQualifier:x,containsParticipant:F,filled:v||x||F}}}function fG({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}=Es({drawPosition:i,matchUps:p}),l=d&&m?.[d].find(f=>f.drawPositions?.includes(i));if(l){let f=wa({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 bd(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=Pe({drawDefinition:i}),Object.assign(t,{matchUpsMap:l})),d||({matchUps:d}=ie({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=jn({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=Uc({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=jn({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});ad({drawPositions:[a],structure:P});let A={[e]:s,name:n,drawPosition:a,structureId:c};return hu({appliedPolicies:y,drawDefinition:i,positionAction:A}),_({context:{removedParticipantId:E},result:{...C},stack:p})}}function bO({luckyLoserParticipantId:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,structureId:o}){return bd({positionActionName:"luckyLoserDrawPositionAssignment",participantId:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,structureId:o})}function NP(t){return bO(t)}function GS({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 VS(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(!cr({structure:i}))return _({result:{error:si,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:no}}function MP(t){let e=VS(t,[{targetRoundNumber:!0,roundNumber:!0,[He]:Tb}]);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:B},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),GS({params:t,modMap:u,structure:r}),{...C}}function RP({structurePositionAssignments:t,provisionalPositioning:e,tournamentRecord:r,drawDefinition:n,event:o}){if(!n)return{error:Z};if(!Array.isArray(t))return{error:B};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:_t};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:B},info:"drawPositions do not match",stack:i});let f=Pe({drawDefinition:n}),{matchUps:g}=ie({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=Wr({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=jn({provisionalPositioning:e,inContextDrawMatchUps:g,tournamentRecord:r,drawDefinition:n,participantId:S,drawPosition:h,matchUpsMap:f,structureId:c,event:o});if(E?.error)return E}}ko({tournamentId:r?.tournamentId,drawDefinition:n,structure:m,event:o})}let s=t.map(({structureId:a})=>a);return bt({tournamentId:r?.tournamentId,eventId:o?.eventId,drawDefinition:n,structureIds:s}),{...C}}function CP(t){let e=VS(t,[{roundNumbers:!0,[He]:Be,[tr]:s=>s.length===2&&s.every(Jt)}]);if(e.error)return e;let{structure:r,roundMatchUps:n,roundNumbers:o}=e;if(!t.roundNumbers.every(s=>o?.includes(s)))return _({result:{error:B,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]})),GS({params:t,modMap:i,structure:r}),{...C}}function bP({alternateParticipantId:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,structureId:o,event:i}){return bd({positionActionName:"alternateDrawPositionAssignment",participantIdAttributeName:"alternateParticipantid",participantId:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,structureId:o,event:i})}function BS({drawDefinition:t,structureId:e}){if(!t)return{error:Z};let{structure:r}=at({drawDefinition:t,structureId:e}),n=(t?.links||[]).filter(i=>i.source?.structureId===e).map(i=>i.target?.structureId);return{playoffStructures:(t?.structures||[]).filter(i=>n.includes(i.structureId)),structure:r}}function Mg({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}=hn({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 HS({withStageGrouping:t,tournamentRecord:e,stageSequences:r,stageSequence:n,roundTarget:o,stages:i,stage:s}){if(!e)return{error:q};let a={},c=[];for(let u of e.events||[]){let{structures:p,stageStructures:m}=Mg({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 Do(t){if(!t?.drawDefinition)return!1;let e=Mu(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 WS(t){let{drawDefinition:e,structureId:r}=t;if(!e)return{error:Z};let{playoffStructures:n}=BS({drawDefinition:e,structureId:r});if(!n?.length)return!1;let o=e?.entries?.filter(c=>c?.entryStatus&&Xr.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 jS({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=jS({accessors:s,significantCharacters:t,value:c});n.push(...u)});else if(r=r[o],s.length){let a=jS({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 OO({targetParticipantIds:t,policyAttributes:e,idCollections:r,participants:n}){if(!Array.isArray(e))return{error:qI};if(!Array.isArray(n))return{error:ec};let o={};return t.forEach(i=>{let s=n.find(c=>c.participantId===i),{values:a}=OP({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 OP({policyAttributes:t,idCollections:e,participants:r,participant:n}){if(!Array.isArray(t))return{error:qI};if(!n)return{error:Wi};let o=[];return t.forEach(s=>{let{directive:a,groupings:c,key:u,significantCharacters:p}=s||{};if(u){let m=u.split(".");o.push(...jS({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 vP({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}=OP({participants:e,policyAttributes:r,idCollections:n,participant:s});return{...i,values:a}})}function _O({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 xO(t){let{unfilledPositions:e,chunkedDrawPositions:r}=t,n=_O(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=vO(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=vO(c);return!s.includes(u)}}}function wO(t){let{unfilledPositions:e,chunkedDrawPositions:r}=t,n=_O(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 vO(t){return Number(t%2?t+1:t-1)}function LO({allGroups:t,participantId:e}){return Object.keys(t).filter(r=>t[r].includes(e))}function FO({selectedParticipantGroups:t,participantIdGroups:e,positionAssignments:r,drawPositionChunks:n,unfilledPositions:o,isRoundRobin:i}){let s=n.map(a=>i?wO({groupsToAvoid:t,chunkedDrawPositions:a,participantIdGroups:e,positionAssignments:r,unfilledPositions:o}):xO({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 YS({positionAssignments:t,participantIds:e}){let r=t.map(n=>n.participantId);return e.filter(n=>!r.includes(n))}function kO({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?Un(a):Un(Object.keys(i));return o=t&&i[o]?.length?o:c,{participantId:o&&i[o]?Un(i[o]):Un(e),groupKey:o}}function GO({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 VO({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=YS({positionAssignments:t,participantIds:e}),m=GO({positionAssignments:t,drawPositionGroups:o}),{participantId:d,groupKey:l}=kO({targetParticipantIds:p,useSpecifiedGroupKey:u,allGroups:s,groupKey:a}),f=LO({participantId:d,allGroups:s}),g=FO({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=tn(A);U=tn(N)}else{let N=tn(I[0]);U=tn(N)}return{newGroupKey:l,selectedParticipantId:d,targetDrawPosition:U}}function Od({isRoundRobin:t,groupedParticipants:e}){let r=[];return t?e.forEach(n=>{let o=n.map(a=>a.drawPosition),i=Ag({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 BO({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=Od({isRoundRobin:o,groupedParticipants:[[c,l]]}),h=[t.find(T=>T.drawPosition===m),l],S=Od({isRoundRobin:o,groupedParticipants:[h]});return!g.length&&!S.length});if(p.length)return{drawPosition:c.drawPosition,possibleDrawPositions:p}}).filter(Boolean)}).flat(1)}function _P(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}=VO({...t,candidatePositionAssignments:l,allGroups:c,groupKey:p});p=T,l.forEach(P=>{P.drawPosition===E&&(P.participantId=y)})});let g=vP({candidatePositionAssignments:l,participantsWithGroupings:r,policyAttributes:s,idCollections:a}),I=Ae(g,m),h=Od({groupedParticipants:I,isRoundRobin:d}),S=0;for(;S<20&&h.length;){let T=BO({positionedParticipants:g,potentialDrawPositions:f,avoidanceConflicts:h,drawPositionGroups:i,isRoundRobin:d});if(T.length){let y=gG({candidatePositionAssignments:l,swapOptions:T});y.error&&console.log({result:y}),g=vP({candidatePositionAssignments:l,participantsWithGroupings:r,policyAttributes:s,idCollections:a}),I=Ae(g,m),h=Od({groupedParticipants:I,isRoundRobin:d}),S++}else S=20}return l.forEach(T=>{if(T.bye&&T.participantId){let y=WI;u.push(y)}if(T.qualifier&&T.participantId){let y=WI;u.push(y)}}),{positionAssignments:l,conflicts:h.length,groupedParticipants:I,errors:u}}function gG({candidatePositionAssignments:t,swapOptions:e}){let r=tn(e);if(!r)return{error:{message:"No swap options"}};let n=r.drawPosition,o=tn(r.possibleDrawPositions),i=t.find(u=>u.drawPosition===n),s=t.find(u=>u.drawPosition===o)??{},a={participantId:s?.participantId,qualifier:s?.qualifier,bye:s?.bye},c={participantId:i.participantId,qualifier:i.qualifier,bye:i.bye};return Object.assign(i,a),Object.assign(s,c),{...C}}function HO({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:uA};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&&Ln(g)&&!I){let G=hC(g)||0,H=T.reduce((K,Y)=>Y.roundNumber>K?Y.roundNumber:K,0);I=H<G?1:H-G+1}let{positionAssignments:y}=Ie({structure:S}),E=Eu({participantsProfile:{convertExtensions:!0},deepCopy:!1,participants:a}).participantsWithGroupings,P=y?.filter(G=>!G.participantId),A=y?.map(G=>G.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?IG(N):hG(N),R={groupParticipants:a.filter(G=>G.participantType===Qr).map(G=>G.participantId),teamParticipants:a.filter(G=>G.participantType===wt).map(G=>G.participantId),pairParticipants:a.filter(G=>G.participantType===ft).map(G=>G.participantId)},b=OO({targetParticipantIds:e,policyAttributes:f,idCollections:R,participants:a});if(b.error)return _({result:b,stack:h});let O=Object.assign({},...e.map(G=>{let H=Object.keys(b).filter(K=>(b[K]??[]).includes(G));return{[G]:H}})),v=YS({participantIds:e,positionAssignments:y});if(v.length>(P?.length||0))return{error:cf};let x,F=v.length,w=tt(0,l).map(()=>_P({initialPositionAssignments:y,participantsWithGroupings:E,unseededParticipantIds:e,opponentsToPlaceCount:F,pairedPriority:!1,unseededByePositions:n,participantIdGroups:O,drawPositionChunks:M,drawPositionGroups:D,policyAttributes:f,idCollections:R,allGroups:b,drawSize:m}));if(x=w.reduce((G,H)=>!G||(H.conflicts||0)<(G.conflicts||0)?H:G,void 0),!x||x.conflicts){let G=tt(0,l).map(()=>_P({initialPositionAssignments:y,participantsWithGroupings:E,unseededParticipantIds:e,opponentsToPlaceCount:F,pairedPriority:!0,unseededByePositions:n,participantIdGroups:O,drawPositionChunks:M,drawPositionGroups:D,policyAttributes:f,idCollections:R,allGroups:b,drawSize:m}));x=w.concat(...G).filter(K=>!K.errors?.length).reduce((K,Y)=>!K||(Y.conflicts||0)<(K.conflicts||0)?Y:K,void 0)}if(!x)return{error:ap};let L=(Ct({structure:S})?.positionAssignments??[]).filter(G=>G.participantId).map(G=>G.participantId),k=x.positionAssignments.filter(G=>!L.includes(G.participantId));for(let G of k)if(G.bye){let H=Wr({tournamentRecord:o,drawDefinition:i,seedBlockInfo:s,structureId:u,matchUpsMap:c,event:d,...G});if(H.error)return _({result:H,stack:h})}else if(G.participantId){let H=jn({automaticPlacement:!0,inContextDrawMatchUps:r,tournamentRecord:o,drawDefinition:i,seedBlockInfo:s,structureId:u,matchUpsMap:c,event:d,...G});if(H.error)return _({result:H,stack:h,context:{assignment:G}})}return{...C}}function IG(t){let{structure:{structures:e}}=t,r=e.map(n=>n.positionAssignments.map(o=>o.drawPosition));return{drawPositionGroups:r,drawPositionChunks:[r]}}function hG({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===Cm(d)),m=u.slice(0,e||u.length).reverse().map(d=>Ae(o,d));return s.length&&console.log({fedDrawPositions:s}),{drawPositionGroups:n,drawPositionChunks:m}}function WO({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}=Ie({structure:p}),{seedAssignments:g}=sn({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:vn})?.extension?.value:void 0,E=bi({provisionalPositioning:t,drawDefinition:i,stageSequence:S,entryStatuses:mi,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:cf},context:{unseededParticipantsCount:A.length,unfilledDrawPositionsCount:U?.length},stack:l});let{appliedPolicies:N}=Tt({tournamentRecord:o,drawDefinition:i,event:d}),D=N?.[mu];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?HO({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}):SG({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 SG({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?Tr(n):n.reverse();for(let l of e){let f=d.pop();if(!o||f){let g=jn({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 jO(t){let e=t.structure??at(t).structure,r="positionQualifiers",n=[];if(e.stage===qe)return _({result:{error:Vi},stack:r});let{unplacedRoundQualifierCounts:o,positionAssignments:i,roundDrawPositions:s}=TG(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:af},context:{unfilledDrawPositions:c},stack:r});tt(0,o[a]).forEach(()=>{let u=tn(c);n.push(u),i?.forEach(p=>{p.drawPosition===u&&(p.qualifier=!0,delete p.participantId,delete p.bye)})})}return{...C,qualifierDrawPositions:n}}function TG({drawDefinition:t,structure:e,structureId:r}){e||({structure:e}=at({drawDefinition:t,structureId:r})),r||({structureId:r}=e);let{positionAssignments:n}=Ie({structure:e}),{stage:o,stageSequence:i}=e,{qualifiersCount:s,roundQualifiersCounts:a}=Us({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 xP({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&&Ns({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=yG({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 yG({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}=xS({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:Fs};f.push(I);let h=jn({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 YO({provisionalPositioning:t,drawDefinition:e,structure:r}){let{positionAssignments:n}=Ie({structure:r}),{seedAssignments:o}=sn({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 qO({orderedSortedFirstRoundSeededDrawPositions:t,validSeedBlocks:e,byesToPlace:r}){let n=[];e.forEach(i=>EG(i,r,n,t));let o=n.map(i=>Array.isArray(i)?Tr(i):i).flat(1/0);return _I(r)&&e.map(s=>s.seedNumbers[0]).includes(r)?t:o}function EG(t,e,r,n){if(e-r.length>t.drawPositions.length)r.push(...t.drawPositions);else{let i=wP(Ae(t.drawPositions,2));AG(i,r,n)}}function AG(t,e,r){let n,o=r[e.length];for(;n=Rg(t,o);)e.push(n),o=r[e.length]}function Rg(t,e){return Array.isArray(t)&&t.length!==2?t.pop():Array.isArray(t[0])?PG(t,e):UG(t,e)}function UG(t,e){return t.includes(e)?t.indexOf(e)?t.pop():t.shift():Math.round(Math.random())?t.pop():t.shift()}function PG(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 Rg(e?o:t[Math.round(Math.random())],e)}return r<n?Rg(t[1],e):Rg(t[0],e)}function wP(t){let e=Math.floor(t.length/2);return t.length>2?[wP(t.slice(0,e)),wP(t.slice(e))]:t}function KO({provisionalPositioning:t,relevantMatchUps:e,appliedPolicies:r,drawDefinition:n,seedingProfile:o,seedBlockInfo:i,byesToPlace:s,structure:a}){i||(i=Ns({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=YO({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)=>Nc(E.seedValue)-Nc(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=qO({orderedSortedFirstRoundSeededDrawPositions:h,validSeedBlocks:m,byesToPlace:s}),T=$O({orderedSeedDrawPositions:h,relevantMatchUps:e}).slice(0,s),y=$O({orderedSeedDrawPositions:S,relevantMatchUps:e}).slice(0,s);return{strictSeedOrderByePositions:T,blockSeedOrderByePositions:y,isLuckyStructure:u,positionedSeeds:d,isContainer:p,isFeedIn:c}}function $O({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 zO({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}=Ie({structure:s}),m=p?.filter(v=>v.participantId).map(v=>v.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(v=>v.drawPositions))),S=Math.min(...h)-1,T=m?.filter(v=>h.includes(v)),y=v=>{let x=Math.ceil(v.length/2),F=[v.slice(0,x),v.slice(x)],w=F.map(V=>[].concat(...V.flat(1/0)).length),L=Math.min(...w.flat(1/0)),k=Math.max(...w.flat(1/0)),G=w.indexOf(k),H=L!==k,K=Tr(F),[Y,j]=!L||H?[F[G],F[1-G]]:[K[0],K[1]];return{greaterHalf:Y,lesserHalf:j}},E=v=>{let{greaterHalf:x,lesserHalf:F}=y(v),{greaterHalf:w,lesserHalf:L}=y(x),G=Tr(w.flat(1/0)).pop(),H=w.flat().filter(Y=>Y!==G);return{newlyFilteredChunks:[...F,...L,H],drawPosition:G}},P=v=>!e.includes(v),A=v=>!T?.includes(v),U=v=>{let F=Ae(v.sort(le),Math.ceil(v.length/4)).map(k=>k.filter(A)),w=[].concat(...F.flat(1/0)).length,L=[];for(let k=0;k<w;k++){let{newlyFilteredChunks:G,drawPosition:H}=E(F);L.push(H),F=G}return L},{validSeedBlocks:N}=Ns({provisionalPositioning:t,allPositions:!0,appliedPolicies:n,drawDefinition:o,structure:s}),D=N?.map(v=>v.drawPositions?.map(x=>x+S)),M;if(a){let v=h.length,{seedBlocks:x}=Pg({cluster:Bp(c)===nu,participantsCount:v});M=x.map(w=>w.map(L=>L+S)).map(U).filter(w=>w.length)}else u?M=D?.map(v=>v.filter(A)):M=D?.map(U).filter(v=>v.length);let R=I.map(v=>v.drawPositions).map(v=>v?.sort((x,F)=>x-F)).filter(v=>v?.[0]+1===v?.[1]),b=v=>R.reduce((x,F)=>F.includes(v)?F.reduce((w,L)=>L!==v?L:w,void 0):x,void 0),O=M.map(v=>v.map(b)).flat(1/0).filter(A).filter(P).filter(Boolean);if(u&&!s.structures){let v=i%4,x=O.slice(0,v),F=f[s.roundLimit]?.length,w=Ae(O.slice(v),F).map(Tr).flat();O=x.concat(w)}return{unseededByePositions:O}}function QO({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=bi({entryStatuses:Xr,provisionalPositioning:t,drawDefinition:e,stageSequence:f,structureId:d,stage:l}),{qualifiersCount:I}=Us({provisionalPositioning:t,drawDefinition:e,stageSequence:f,structureId:d,stage:l}),h=g.length+I,{positionAssignments:S,unassignedPositions:T}=Ie({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 LP({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}=QO({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}=KO({provisionalPositioning:t,relevantMatchUps:g,appliedPolicies:r,drawDefinition:n,seedingProfile:i,seedBlockInfo:o,byesToPlace:I,structure:c}),E=c?.structureType&&[Ve,hp].includes(c.structureType)&&r?.seeding?.containerByesIgnoreSeeding,P=d&&S?.length?S:h,{unseededByePositions:A}=zO({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(O=>U(O)?b!==O+1:b!==O-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=Tr(D),Dr({ignoreSeededByes:E})&&console.log({byePositions:D}));let M=D.slice(0,I);for(let R of M){let b=Wr({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 Mc(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||(zA(),e=J(e,!1,!0));let I=x=>(r||hf(),_({result:x,stack:"automatedPositioning"})),h=x=>(r||hf(),x),S=at({drawDefinition:e,structureId:u});if(S.error)return I(S);let T=S.structure;if(!T)return{error:_t};let y=t.appliedPolicies||Tt({drawDefinition:e,structure:T,event:f})?.appliedPolicies,{qualifiersCount:E}=Us({stageSequence:T.stageSequence,provisionalPositioning:n,stage:T.stage,drawDefinition:e,structureId:u}),P=mi;if(!bi({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??Pe({drawDefinition:e}),N=t.inContextDrawMatchUps??ie({inContext:!0,drawDefinition:e,matchUpsMap:U})?.matchUps,D=[],M=Ns({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?Ft({withIndividualParticipants:!0,convertExtensions:!0,tournamentRecord:s})?.participants:[]);if(Bp(T.seedingProfile||c)===Ti){let x=i?LP({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=xP({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!==Ki){let F=T.seedingProfile?{positioning:T.seedingProfile}:c,w=xP({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?LP({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 O={};if(!m){let x=jO({inContextDrawMatchUps:N,tournamentRecord:s,appliedPolicies:y,validSeedBlocks:R,drawDefinition:e,seedBlockInfo:M,participants:b,matchUpsMap:U,structure:T});if(x.error||(x.conflicts&&(O.qualifierConflicts=x.conflicts),g.push({action:"positionQualifiers",qualifierDrawPositions:x.qualifierDrawPositions}),x=WO({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&&(O.unseededConflicts=x.conflicts),g.push({action:"positionUnseededParticipants"})}let{positionAssignments:v}=Ct({drawDefinition:e,structure:T});return bt({drawDefinition:e,structureIds:[u]}),r||hf(),{positionAssignments:v,conflicts:O,...C,positioningReport:g}}function na(t){let{applyPositioning:e=!0,provisionalPositioning:r,tournamentRecord:n,drawDefinition:o,seedingProfile:i,structureId:s,placeByes:a,seedsOnly:c}=t;if(!o)return{error:br};if(!Do({drawDefinition:o,structureId:s})&&!r)return{error:jl};let p=BS({drawDefinition:o,structureId:s}).playoffStructures?.sort((l,f)=>Wf(l)-Wf(f)),m=[],d=[];if(p)for(let l of p){let{structureId:f}=l,g=Mc({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 FP({validation:t=!0,tournamentRecord:e,drawDefinition:r,participantId:n,structureId:o,seedValue:i,event:s}){if(!r)return{error:Z};if(!o)return{error:Pr};let a=(e?.participants??[]).find(l=>l.participantId===n);if(e&&!a)return{error:ln};let{structure:c}=at({drawDefinition:r,structureId:o});if(!c)return{error:_t};if(!(!t||Jt(i)||i===void 0||i===""||typeof i=="string"&&i.split("-").every(l=>Jt(l)&&dt(l)>0)))return{error:B};let{seedAssignments:p}=sn({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 rS({tournamentId:e?.tournamentId,eventId:s?.eventId,drawDefinition:r,structure:c}),{...C}}function Cg({qualifyingParticipantId:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,structureId:o}){return bd({positionActionName:"qualifierDrawPositionAssignment",participantId:t,isQualifierPosition:!0,tournamentRecord:e,drawDefinition:r,drawPosition:n,structureId:o})}function vu({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 XO=(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 kP({targetRoundNumber:t=1,tournamentRecord:e,drawDefinition:r,event:n,randomList:o}){let i=et({drawDefinition:r,event:n,tournamentRecord:e},[{[Ce]:!0,[co]:!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:zl}});let m=(Tt({tournamentRecord:e,drawDefinition:r,structure:c,event:n}).appliedPolicies??{})[Jn]?.requireCompletedStructures,{qualifierPositions:d,positionAssignments:l}=Ie({structure:c});if(!d.length)return _({result:{error:af}});let f=tt(0,d.length);o&&(f=XO(f,o));let g=l.map(S=>S.participantId).filter(Boolean),{relevantLinks:I}=vu({structureId:c.structureId,targetRoundNumber:t,linkType:Xn,drawDefinition:r})||{},{relevantLinks:h}=vu({structureId:c.structureId,targetRoundNumber:t,linkType:Fn,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=Do({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==="BYE"&&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(Do({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:Lo}).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&&Cg({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:yA}})}function GP({drawDefinition:t,orderMap:e}){return t?((typeof e!="object"||!Object.values(e).every(r=>It(r)))&&_({result:{error:B},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)=>za(r.structureOrder)-za(n.structureOrder)),{...C}):{error:Z}}function _u({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[yi,Nn,Sp,Ti].includes(I.target.feedProfile)?(T?.targets.push(S),y?.sources.push(h)):I.target.feedProfile===fn&&(y?.drawSources.push(h),T?.drawTargets.push(S)),s[S]=s[S]||I.target.feedProfile===fn,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 qS({drawDefinition:t}){let{maxQualifyingDepth:e,structureProfiles:r}=_u({drawDefinition:t});for(let n of t.structures){let o=r[n.structureId];o.distanceFromMain&&(n.stageSequence=e+1-o.distanceFromMain)}return{...C}}function bg(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 DG({tournamentId:r.tournamentId,drawDefinition:n,structure:o,link:i})}function DG(t){let e=et(t,[{[Ce]:!0,[Ep]:!0},{link:!0,[He]:zr,[VE]:$l}]);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),qS({drawDefinition:r});let u=yt({structure:o})?.matchUps||[];return Fo({drawDefinition:r,tournamentId:n,matchUps:u,eventId:i}),bt({drawDefinition:r,structureIds:[o.structureId]}),{...C}}function VP({drawDefinition:t,structureDetails:e}){if(!Array.isArray(e))return{error:B};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 Og({drawDefinition:t,timeItem:e}){if(!t)return{error:br};if(!e)return{error:mf};let r=e&&Object.keys(e),n=["itemType","itemValue"];if(!(n.filter(s=>r.includes(s)).length===n.length))return{error:pf};t.timeItems||(t.timeItems=[]);let i=new Date().toISOString();return Object.assign(e,{createdAt:i}),t.timeItems.push(e),Ma({drawDefinition:t}),{...C}}function BP(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:_t};let c=s.find(({stage:h,stageSequence:S})=>h===rt&&S===1),u=n===c?.structureId,p=s.filter(({stage:h})=>h===ct).map(Hr("structureId"));if(u&&!p.length)return{error:BE};let m=p.includes(n),d=NG({isQualifyingStructure:m,structure:a,...t});if(d?.error)return d;let{structureIdsToRemove:l,relatedStructureIdsMap:f}=RG({qualifyingStructureIds:p,isQualifyingStructure:m,isMainStageSequence1:u,mainStageSequence1:c,drawDefinition:r,structureId:n}),{removedMatchUpIds:g,removedStructureIds:I}=CG({relatedStructureIdsMap:f,qualifyingStructureIds:p,isMainStageSequence1:u,mainStageSequence1:c,drawDefinition:r,structureIdsToRemove:l,structureId:n});if(MG({removedMatchUpIds:g,drawDefinition:r}),u){let h=(c.matchUps??[])?.map(Hr("matchUpId"));g.push(...h),c.positionAssignments=[],c.seedAssignments=[],c.matchUps=[],c.extensions&&(c.extensions=[])}return m&&qS({drawDefinition:r}),_n({tournamentId:e?.tournamentId,matchUpIds:g,action:"removeStructure",eventId:o?.eventId,drawDefinition:r}),bt({drawDefinition:r,eventId:o?.eventId}),{...C,removedMatchUpIds:g,removedStructureIds:I}}function NG({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(ie({matchUpFilters:{structureIds:a},drawDefinition:r}).matchUps?.some(({score:p})=>he({score:p}))){let p=Tt({tournamentRecord:e,drawDefinition:r,structure:o,event:i})?.appliedPolicies;if(!(s??p?.[rn]?.allowDeletionWithScoresPresent?.structures))return{error:oc}}return{...C}}function MG({removedMatchUpIds:t,drawDefinition:e}){let{matchUps:r}=ie({drawDefinition:e});r?.forEach(n=>{n.winnerMatchUpId&&t.includes(n.winnerMatchUpId)&&delete n.winnerMatchUpId,n.loserMatchUpId&&t.includes(n.loserMatchUpId)&&delete n.loserMatchUpId})}function RG({qualifyingStructureIds:t,isQualifyingStructure:e,isMainStageSequence1:r,mainStageSequence1:n,drawDefinition:o,structureId:i}){let a=(o.structures??[]).map(Hr("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 CG({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(...vG({idBeingRemoved:u,drawDefinition:o}));let p=OG({qualifyingStructureIds:e,isMainStageSequence1:r,idBeingRemoved:u,drawDefinition:o,structureId:s});a.push(...p.removedStructureIds);let m=bG({relatedStructureIdsMap:t,mainStageSequence1:n,idBeingRemoved:u,structureId:s});m?.length&&i.push(...m)}return{removedMatchUpIds:c,removedStructureIds:a}}function bG({idBeingRemoved:t,relatedStructureIdsMap:e,mainStageSequence1:r,structureId:n}){return t&&e.get(t)?.filter(o=>o!==r?.structureId||n===r.structureId)}function OG({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 vG({idBeingRemoved:t,drawDefinition:e}){let{structure:r}=at({structureId:t,drawDefinition:e}),n=yt({structure:r}).matchUps;return od(n)}function Hp({stageSequence:t=1,drawDefinition:e,drawSize:r,stage:n}){if(!e)return{error:Z};if(!ug({drawDefinition:e,stage:n}))return{error:Vi};let o=Fb({drawDefinition:e,stage:n}),{qualifiersCount:i}=Us({drawDefinition:e,stageSequence:t,stage:n}),s=o+i;if(r<s)return{error:HI};let{entryProfile:a}=ng({attributes:[{[n]:{drawSize:r}}],drawDefinition:e});return bt({drawDefinition:e}),{...C,entryProfile:a}}function $S({qualifiersCount:t=0,drawDefinition:e,stage:r}){return e?ug({drawDefinition:e,stage:r})?r!==rt?{error:HI,info:"qualifiersCount can only be set for main stage"}:(ng({attributes:[{[r]:{qualifiersCount:t}}],drawDefinition:e}),bt({drawDefinition:e}),{...C}):{error:Vi}:{error:Z}}function JO({drawDefinition:t,drawSize:e}){if(!t)return{error:Z};let r=Hp({stage:$e,stageSequence:1,drawDefinition:t,drawSize:e});return r.error?r:(bt({drawDefinition:t}),{...C})}function HP(t){return JO(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:_t};if(o.matchUps?.some(({matchUpStatus:a,score:c})=>he({score:c})??ae.includes(a)))return{error:oc};let s=o.matchUps?.map(({matchUpId:a})=>a)||[];return o.positionAssignments=[],o.seedAssignments=[],o.matchUps=[],_n({tournamentId:t?.tournamentId,action:"resetVoluntaryConsolationStructure",matchUpIds:s,drawDefinition:e}),bt({tournamentId:t?.tournamentId,eventId:r?.eventId,drawDefinition:e,structureIds:[o.structureId]}),{...C}}var ZO="qualifierDrawPositionAssignment",tv="withdrawParticipantAtDrawPosition",ev="alternateDrawPositionAssignment",rv="luckyLoserDrawPositionAssignment",jP="removeDrawPositionAssignment",KS="swapDrawPositionAssignments",nv="modifyPairAssignment",ov="adHocPositionSwap",iv="modifyParticipantOtherName",YP="assignDrawPosition",sv="removeSeededParticipant",av="assignDrawPositionBye",cv="modifySeedAssignment",zS="addPenalty",vg="MODIFY_PAIR",Wp="QUALIFIER",_g="ALTERNATE",xg="WITHDRAW",Ms="ASSIGN",QS="REMOVE",wg="LUCKY",jp="REMOVE_SEED",Yp="SWAP",xu="NICKNAME",oa="SEED_VALUE",ia="PENALTY";var uv={MODIFY_PAIR_ASSIGNMENT:vg,QUALIFYING_PARTICIPANT:Wp,ALTERNATE_PARTICIPANT:_g,WITHDRAW_PARTICIPANT:xg,ASSIGN_PARTICIPANT:Ms,LUCKY_PARTICIPANT:wg,REMOVE_ASSIGNMENT:QS,SWAP_PARTICIPANTS:Yp,ADD_NICKNAME:xu,REMOVE_SEED:jp,ADD_PENALTY:ia,ASSIGN_BYE:"BYE",SEED_VALUE:oa};function qP({tournamentRecord:t,drawDefinition:e,drawPositions:r,structureId:n,event:o}){if(!e)return{error:Z};if(!n)return{error:Pr};if(r?.length!==2)return{error:B,drawPositions:r};let i=Pe({drawDefinition:e}),{matchUps:s}=ie({inContext:!0,drawDefinition:e,matchUpsMap:i}),{structure:a}=at({drawDefinition:e,structureId:n});if(!a)return{error:_t};let c=Tt({tournamentRecord:t,drawDefinition:e,event:o}).appliedPolicies??{},u;if(a.structureType===Ve?u=wG({inContextDrawMatchUps:s,tournamentRecord:t,drawDefinition:e,drawPositions:r,matchUpsMap:i,structure:a,event:o}):u=_G({inContextDrawMatchUps:s,tournamentRecord:t,drawDefinition:e,drawPositions:r,matchUpsMap:i,structure:a,event:o}),u.error)return u;if(ad({structure:a,drawPositions:r}),hu({appliedPolicies:c,drawDefinition:e,positionAction:{name:KS,drawPositions:r,structureId:n}}),ko({tournamentId:t?.tournamentId,drawDefinition:e,structure:a,event:o}),o.eventType===Or){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);Nd({inContextTargetMatchUp:l,drawPositionSideIndex:S,teamParticipantId:I,tournamentRecord:t,drawDefinition:e,matchUp:h,event:o})}})})}return bt({drawDefinition:e,structureIds:[n]}),{...C}}function _G({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:B,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?pv({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,assignments:a,matchUpsMap:o,structure:i,event:s}):xG({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,assignments:a,matchUpsMap:o,structure:i,event:s})}function pv({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=Ou({drawPosition:u,inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,structureId:d,matchUpsMap:o});return l.error||(l=Ou({drawPosition:m,inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,structureId:d,matchUpsMap:o}),l.error)||(Wr({drawPosition:m,tournamentRecord:e,drawDefinition:r,structureId:d,matchUpsMap:o,event:s}),l=jn({drawPosition:u,inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,structureId:d,participantId:p,matchUpsMap:o,event:s}),l.error)?l:{...C}}function xG({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),Ng({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,matchUpsMap:o,assignments:n,structure:i,event:s}),{...C}}function wG({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};Ng({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)pv({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,assignments:a,matchUpsMap:o,structure:i,event:s});else{let p=J(a,!1,!0);a.forEach((m,d)=>{let l=p[1-d].participantId;m.qualifier=p[1-d].qualifier,m.participantId=l})}return{...C}}function $P({tournamentRecord:t,drawDefinition:e,participantId:r,structureId:n}){let o="removeSeededParticipant";if(!t)return{error:q};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:si},stack:o}):i.seedAssignments?.find(a=>a.participantId===r)?{...C}:_({info:"participant not seeded",result:{error:Oe},context:{participantId:r}}):_({result:{error:_t},stack:o})}function La({targetEntryRound:t=1,finishingPositions:e,sourceRoundNumber:r,sourceStructureId:n,targetStructureId:o,linkType:i=Xn}){return!n||!o?{error:Pr}:{link:nt({linkType:i,source:{roundNumber:r,structureId:n,finishingPositions:e},target:{feedProfile:fn,roundNumber:t,structureId:o}})}}function Li({matchUp:t,tieFormat:e,isMock:r,uuids:n}){let{collectionDefinitions:o}=e??{};return{tieMatchUps:(o??[]).map(s=>wu({matchUp:t,collectionDefinition:s,uuids:n,isMock:r})).filter(Boolean).flat()}}function wu({collectionPositionOffset:t=0,collectionDefinition:e,matchUpsLimit:r,matchUp:n,isMock:o,uuids:i}){let{matchUpCount:s,matchUpType:a,collectionId:c,processCodes:u}=e||{},p=r??s??0,m=d=>{if(!o&&!n?.isMock)return i?.pop()??Nt();let l=e?.collectionId;return i?.pop()??`${n?.matchUpId}-${l}-TMU-${d+1}`};return tt(0,p).map(d=>{let l=t+d+1;return{sides:[{sideNumber:1},{sideNumber:2}],matchUpId:m(d),matchUpStatus:Qt,collectionPosition:l,collectionId:c,processCodes:u,matchUpType:a,isMock:o}})}function vd({roundPosition:t,roundNumber:e,idPrefix:r,uuids:n}){return r?`${r}-${e}-${t}`:n?.pop()||Nt()}function qp({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=vd({roundPosition:p,roundNumber:r,idPrefix:o,uuids:s}),I={roundPosition:p,children:[l,f],matchUpId:g};u.push(I);let h={drawPositions:I.children.map(S=>S?.drawPosition).filter(Boolean),matchUpStatus:Qt,matchUpId:I.matchUpId,roundPosition:p,roundNumber:r};t&&e&&(h.matchUpType=e),i&&(h.isMock=!0),n.push(h),p++,c+=2}return{roundNodes:u,matchUps:n}}function xn({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&&(!Ln(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(!Ln(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}=qp({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}=qp({nodes:d,matchUpType:o,roundNumber:f,idPrefix:s,matchUps:l,isMock:c,uuids:u}),f++;let g=f-1;return l=ba({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 _d(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:B},stack:e});let r=t.drawSize??Rm(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:Za},context:{drawSize:r},stack:e});if(i&&i>=t.drawSize)return _({result:{error:B},context:{drawSize:r,qualifyingPositions:i},stack:e});let y,E,P,A,U=0,N,D=1,{structureProfiles:M}=_u({drawDefinition:p}),R=M[s];if(!R)return _({result:{error:_t},context:{targetStructureId:s},stack:e});let b=p.matchUpType,O=f?`${f}-`:"",v=R.stage===ct,x=c?.[vo]?.namingConventions?.pre??Bb[vo]?.namingConventions?.pre,F=v&&x?`${x}-`:"",w=d??(O?`${F}${Qe(ct)} ${O}`:`${F}${Qe(ct)}`);if(I===On){let{maxRoundNumber:G,structures:H,groupCount:K}=xa({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=K,y=G,P=H[0],N=[1]}else({drawSize:r,matchUps:A,roundLimit:y,roundsCount:E}=xn({qualifyingRoundNumber:o,qualifyingPositions:i,matchUpType:b,idPrefix:h,drawSize:r,isMock:S,uuids:T})),y||(y=E),P=yn({structureName:d??w,structureId:l??T?.pop(),qualifyingRoundNumber:y,stage:ct,matchUpFormat:m,stageSequence:D,matchUpType:b,roundLimit:y,matchUps:A}),f&&At({extension:{name:vn,value:f},element:P}),U=A?.filter(G=>G.roundNumber===y)?.length;let L=I===On?Fn:Xn,k=P&&y&&La({sourceStructureId:P.structureId,sourceRoundNumber:y,targetStructureId:s,finishingPositions:N,linkType:L})?.link;return g&&(A=yt({structure:P})?.matchUps||[],A?.forEach(G=>{let{tieMatchUps:H}=Li({tieFormat:g,matchUp:G,isMock:S});Object.assign(G,{tieMatchUps:H,matchUpType:b})})),{qualifyingDrawPositionsCount:r,qualifiersCount:U,...C,structure:P,link:k}}function KP(t){if(!t.tournamentRecord)return{error:q};let r=LG(t);return r.error,r}function LG(t){if(!t.drawDefinition)return{error:Z};if(!t.targetStructureId)return{error:Pr};let e=_d(t);if(e.error)return e;let{structure:r,link:n}=e;return!r||!n?{error:B}:bg({tournamentRecord:t.tournamentRecord,drawDefinition:t.drawDefinition,structure:r,link:n})}function zP(t){let e=et(t,[{[Ce]:!0,[cu]:!0,[gn]:!0},{[lb]:!0,[tr]:m=>Number.isInteger(m)&&m>0},{[tr]:m=>Array.isArray(m)&&m.length===2&&m.every(kt),[kr]: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:_t};if(!cr({structure:s}))return{error:si};let a=m=>m.sides?.map(d=>d.participantId).some(d=>t.participantIds.includes(d)),c=m=>m.roundNumber===t.roundNumber,u=m=>!he(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 bt({drawDefinition:r,structureIds:[n]}),{...C}}function mv({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=vd({roundPosition:S.roundPosition,roundNumber:r,idPrefix:o,uuids:a}),y={roundPosition:S.roundPosition,drawPositions:[I],matchUpStatus:Qt,roundNumber:r,matchUpId:T};t&&(y.matchUpType=n),s&&(y.isMock=!0),i.push(y);let E={children:[S,h]};l.push(E)}let f=e?e-p:void 0;return{roundNodes:l,matchUps:i,drawPosition:f}}function fi(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=FG({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,k)=>L+k,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}=qp({matchUpType:m,roundNumber:D,idPrefix:d,matchUps:U,isMock:l,nodes:R,uuids:f}),D++,r.includes(w)){let L=Er(r)[w],k=tt(0,L),G=y+1-D,H=s?.includes(G)??c?.includes(D);k.forEach(()=>{({roundNodes:N,matchUps:U,drawPosition:b}=mv({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 O=i-S;U=ba({finishingPositionOffset:p?O: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=Cm(w);return L>w?L/2:L}}function FG({drawSize:t}){let e=Math.ceil(Math.log(t)/Math.log(2));return tt(0,e).reverse().map(n=>Math.pow(2,n))}function Rc(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} `||"",O=s?.[M]??o?.[M],v=t.structureName||O?.name||R?.name&&(r?`${b}${R?.name}`:R.name)||`${b}${M}`,x=O?.abbreviation??R?.abbreviation,F=t.structureId??R?.structureId??T?.pop(),w={idPrefix:h&&`${h}-${v}-RP`,finishingPositionOffset:e,matchUpType:U,drawSize:I,isMock:S,uuids:T},{matchUps:L}=l?fi(w):xn(w),k=yn({structureAbbreviation:x,stageSequence:a,structureName:v,matchUpType:U,roundOffset:m,structureId:F,matchUps:L,stage:g});E.push(...L),P.push(k);let G=Math.ceil(Math.log(I)/Math.log(2)),H=p?Math.min(p-m,G):(!i||N<i)&&G||0;return I>2&&tt(1,H+1).forEach(Y=>K(Y)),{structureId:k.structureId,matchUps:E,structureName:v,structures:P,links:A,...C};function K(Y){let j=I/Math.pow(2,Y);if(j<2)return;let V=I/Math.pow(2,Y)+e;if(i&&V+1>i)return;let{structures:$,structureId:X,matchUps:W,links:it}=Rc({finishingPositionOffset:V,exitProfile:`${c}-${Y}`,roundOffset:m+Y,stageSequence:a+1,drawSize:j,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(k.structureId&&X){let z={linkType:so,source:{roundNumber:Y,structureId:k.structureId},target:{roundNumber:1,feedProfile:Nn,structureId:X}};it&&k&&it.push(z),it?.length&&A.push(...it)}return $?.length&&P.push(...$),W?.length&&E.push(...W),{structureId:X,childLinks:it,structures:P}}}function xd({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 QP({finishingPositions:t,drawDefinition:e,structureId:r}){let{roundProfile:n}=xd({drawDefinition:e,structureId:r});return(n&&Object.keys(n))?.reduce((i,s)=>(dv(n?.[s]).forEach(c=>{t.forEach(u=>{kG({position:u,rangeDefinition:c})&&(i[u]={roundNumber:s})})}),i),{})}function kG({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 dv(t){return[pt(t?.finishingPositionRange?.loser||[]),pt(t?.finishingPositionRange?.winner||[])]}function lv(t){return dv(t).map(e=>tt(e[0],e[1]&&e[1]+1||e[0]+1))}function Cc({drawDefinition:t,structureIds:e,matchUpsMap:r}){if(e&&!Array.isArray(e))return{error:B,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}=xd({drawDefinition:t,matchUpsMap:r,structureId:a});return(c&&Object.values(c))?.map(lv).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 XS({excludeRoundNumbers:t=[],playoffPositions:e=[],drawDefinition:r,structureId:n}){if(!r)return{error:Z};if(!n)return{error:Pr};if(!e)return{error:st,info:"missing playoffPositions"};let o=Cc({drawDefinition:r});if(o.error)return o;let i=o.positionsPlayedOff,s=e.filter(S=>!i.includes(S)),a=QP({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=QP({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}=xd({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}=GG({playoffSourceRounds:l,roundProfile:f}),h=[...l,...d];return{playoffPositionsReturned:g,playedOffSourceRounds:d,playoffRoundsRanges:I,playoffSourceRounds:l,sourceRounds:h,roundProfile:f}}function GG({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 Lu({drawDefinition:t,structureId:e}){if(!t)return{error:Z};let{matchUps:r,matchUpsMap:n}=nr({inContext:!0,drawDefinition:t}),{positionsNotPlayedOff:o,positionsPlayedOff:i}=Cc({drawDefinition:t,matchUpsMap:n}),{structures:s}=hn({drawDefinition:t}),a=s.filter(u=>!e&&u.stage!==$e||u.structureId===e),c={};for(let u of a){let p=u?.structureId,m=VG({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 VG({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=[]}=Cc({structureIds:T,drawDefinition:e}),P=[...y,...E],A=tt(S[0],S[1]+1).filter(D=>!P.includes(D)),U=Ae(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!==kn).map(l=>l.source?.roundNumber)||[],a=i?.source?.filter(l=>l.linkCondition===kn).map(l=>l.source?.roundNumber)||[],c=XS({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 fv({playoffGroups:t,drawDefinition:e,structureId:r}){if(!e)return{error:Z};if(!kt(r)||!Array.isArray(t))return{error:B};let n=t.map(({finishingPositions:a})=>a).flat();return{positionRangeMap:Lu({drawDefinition:e,structureId:r}).playoffFinishingPositionRanges?.filter(a=>n.includes(a.finishingPosition))?.reduce((a,c)=>(a[c.finishingPosition]=c,a),{})}}function JS(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?fi(l):xn(l),g=yn({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}=xn({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=yn({structureName:E,matchUps:T,structureId:d?.pop(),stage:qe,stageSequence:1,matchUpType:a});I.push(P);let A={linkType:so,source:{roundNumber:1,structureId:g.structureId},target:{roundNumber:1,feedProfile:Nn,structureId:P.structureId}};h.push(A)}return{...C,structures:I,links:h}}function ZS({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&&Nn||yi,d=p-e<=2?p-e:(p-e-2)*2+2,l={linkType:so,source:{roundNumber:p,structureId:r.structureId},target:{feedProfile:m,roundNumber:d,structureId:t.structureId}},f=c[p-1];return f&&(l.target.groupedOrder=f),Dr()&&(l.source.structureName=r.structureName,l.target.structureName=t.structureName),p===2&&i&&(l.linkCondition=kn,l.target.feedProfile=Nn),a.includes(d)?l:void 0}).filter(Boolean)}function tT(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?fi(f):xn(f),h=t.structureName??o?.["0"]?.name??Qe(rt),S=Ds({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}=BG({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=ZS({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}=xn({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=Ds({structureId:l?.pop(),matchUps:U,stageSequence:2,stage:fe,structureName:M,matchUpType:c}),b={linkType:so,source:{roundNumber:I-1,structureId:S.structureId},target:{structureId:R.structureId,feedProfile:Nn,roundNumber:1}};T.push(R),y.push(b)}}return{structures:T,links:y,...C}}function BG({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}=fi({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:Ds({matchUps:l,stage:qe,structureName:S,stageSequence:e,matchUpType:i,structureId:s}),consolationRoundsCount:f}}function bc(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?.[dc]||t.appliedPolicies?.[dc],S={finishingPositionOffset:e,matchUpType:u,skipRounds:p,drawSize:l,idPrefix:d,isMock:f,uuids:g},{matchUps:T}=i?fi(S):xn(S),y=yn({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}=fi({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=yn({matchUps:U,structureId:g?.pop(),stage:qe,stageSequence:1,structureName:M,matchUpType:u});E.push(R);let b=ZS({consolationStructure:R,mainStructure:y,roundsCount:N,feedPolicy:h,fmlc:I});P.push(...b)}return{...C,structures:E,links:P}}function rT({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?.[dc];let f="processPlayoffGroups",g=0,I=[],h=[],S=[],{error:T,positionRangeMap:y}=fv({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:B},stack:f});for(let P of a){let A=P.finishingPositions,U=y&&A.flatMap(F=>y[F]?.finishingPositions??[]),N=p*A.length,D=us(N),M=D===2&&yo||P.drawType||yo;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,v={...{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,k=eT({playoffStructureId:L.structureId,finishingPositions:A,sourceStructureId:n});S.push(k),S.push(...w),h.push(...F),I.push({structureId:L.structureId,finishingPositions:A}),g+=N};if(M===yo){let{matchUps:F}=xn({finishingPositionLimit:g+N,idPrefix:m&&`${m}-po`,finishingPositionOffset:g,matchUpType:c,drawSize:D,isMock:d,uuids:l}),w=yn({structureId:P.structureId??l?.pop(),matchUpFormat:e,stage:fe,structureName:b,stageSequence:i,matchUps:F});h.push(w);let L=eT({playoffStructureId:w.structureId,finishingPositions:A,sourceStructureId:n});S.push(L),g+=N,I.push({structureId:w.structureId,finishingPositions:A})}else if([ou,iu,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===ou?Object.assign(F,{playoffAttributes:P?.playoffAttributes??r??Of,roundOffsetLimit:3}):M===iu&&Object.assign(F,{playoffAttributes:P?.playoffAttributes??r??vf,roundOffsetLimit:2});let w=Rc(F);if(w.error)return w;if(w.links?.length&&S.push(...w.links),w.structures?.length&&h.push(...w.structures),h.sort(Ni),w.structureId){let L=eT({playoffStructureId:w.structureId,finishingPositions:A,sourceStructureId:n});S.push(L),I.push({structureId:w.structureId,finishingPositions:A})}g+=N}else if([au,yp,Ym,jm,Wm,qm].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={[au]:{fmlc:!0,feedRounds:1},[qm]:{feedRounds:1},[Ym]:{feedsFromFinal:3},[jm]:{feedsFromFinal:2},[Wm]:{feedsFromFinal:1}};Object.assign(w,L[M]||{});let{structures:k,links:G}=bc(w),[H]=k,K=eT({playoffStructureId:H.structureId,finishingPositions:A,sourceStructureId:n});S.push(K),S.push(...G),h.push(...k),I.push({structureId:H.structureId,finishingPositions:A}),g+=N}else if([On].includes(M)){let{structures:F,links:w}=xa({...v,structureOptions:P.structureOptions||{groupSize:4}});x({playoffStructures:F,playoffLinks:w})}else if([Tp].includes(M)){let{structures:F,links:w}=JS(v);x({playoffStructures:F,playoffLinks:w})}else if([cb].includes(M)){let{structures:F,links:w}=tT(v);x({playoffStructures:F,playoffLinks:w})}else if([Fr].includes(M)){let F=yn({structureId:P.structureId??l?.pop(),structureName:P.structureName,finishingPosition:pd,stage:fe,stageSequence:i,matchUps:[]});x({playoffStructures:[F],playoffLinks:[]})}}return{finishingPositionTargets:I,positionRangeMap:y,structures:h,links:S}}function eT({playoffStructureId:t,finishingPositions:e,sourceStructureId:r}){return{linkType:Fn,source:{structureId:r,finishingPositions:e},target:{structureId:t,feedProfile:fn,roundNumber:1}}}function gv(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=rT({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}=ie({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}=Li({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:Lo})?.extension?.value?.groupOrder;M&&(P[M]||(P[M]=[]),P[M].push(U.participantId))});let A=na({provisionalPositioning:t.provisionalPositioning,structureId:r,applyPositioning:!0,event:t.event,tournamentRecord:o,drawDefinition:i});return A.error&&A.error?.code!==jl.code?_({result:A,stack:e}):{structures:m,links:d,positionsPlayedOff:g,drawDefinition:i,...C}}function Fu({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 XP="NTRP";var Iv={ELO:"ELO",NTRP:XP,TRN:"TRN",UTR:"UTR",WTN:"WTN"};var WG={ELO:{defaultInitialization:1500,decimalsCount:0,range:[0,3e3],ascending:!0},[XP]:{accessors:["ntrpRating","dntrpRatingHundredths"],attributes:{ustaRatingType:""},accessor:"dntrpRatingHundredths",defaultInitialization:3,decimalsCount:1,ascending:!0,range:[1,7]},UTR:{defaultInitialization:6,accessors:["utrRating"],accessor:"utrRating",decimalsCount:2,ascending:!0,range:[1,16]},WTN:{attributes:{confidence:{generator:!0,range:[60,100]}},accessors:["wtnRating","confidence"],defaultInitialization:23,accessor:"wtnRating",ascending:!1,decimalsCount:2,range:[40,1]}},je=WG;function hv({sourceRatingType:t,sourceRating:e}){let r=je[t].range,n=r[0]>r[1],o=je["ELO"].range;return Fu({value:n?r[0]-e:e,sourceRange:r,targetRange:o})}function Sv({targetRatingType:t,sourceRating:e}){let r=je[t].decimalsCount||0,n=je[t].range,o=n[0]>n[1],i=Math.max(...n),s=je["ELO"].range,a=Fu({targetRange:n,sourceRange:s,value:e}),c=parseFloat(a.toFixed(r));return o?i-c:c}function ZP(t){let e=et(t,[{ratings:!0,[He]:zr}]);if(e.error)return e;let r=t.matchUpType&&[Lt,vt].includes(t.matchUpType)?t.matchUpType:Lt,n=Object.keys(je),o=t.targetRatingType&&n.includes(t.targetRatingType)?t.targetRatingType:"ELO",i=t.ratings[r]?t.ratings[r].reduce((d,l)=>d.includes(l.scaleName)?d:d.concat(l.scaleName),[]):[];if(!i)return{error:Oe};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=je[s.scaleName].accessor,u=c?s.scaleValue[c]:s.scaleValue,p=hv({sourceRatingType:a,sourceRating:u});return{convertedRating:Sv({targetRatingType:o,sourceRating:p}),sourceRating:u}}function Tv({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?.[Lt]&&s?.[Lt]){let a="ELO",{convertedRating:c}=ZP({ratings:i,targetRatingType:a}),{convertedRating:u}=ZP({ratings:s,targetRatingType:a}),{side1pressure:p,side2pressure:m}=jG({side1ConvertedRating:c,side2ConvertedRating:u,score:r});p&&t[n?.participantId].pressureScores.push(p),m&&t[o?.participantId].pressureScores.push(m);let d=Math.max(...je["ELO"].range),l=Hl((u-c)/d),f=Hl((c-u)/d);t[n?.participantId].ratingVariation.push(l),t[o?.participantId].ratingVariation.push(f)}}function jG({side1ConvertedRating:t,side2ConvertedRating:e,score:r}){let n=t>e?t:e,o=t>e?e:t,i=Math.abs(t-e),s=je["ELO"].range,a=Math.max(...s),c=(a-n)*0,p=(n+c)/a*i,m=r?.sets?.reduce((T,y)=>T+(y?.side1Score??0),0),d=r?.sets?.reduce((T,y)=>T+(y.side2Score??0),0),l=t>e?2:1,f=(m||0)*(o+(l===1?p:0)),g=(d||0)*(o+(l===2?p:0)),I=f+g,h=I?Hl(f/I):0,S=I?Hl(g/I):0;return{side1pressure:h,side2pressure:S}}function Lg({winningSide:t,matchUpFormat:e=bn,matchUpStatus:r,tallyPolicy:n,score:o}){let i=[0,0],s=o?.sets,a=typeof t=="number"&&t-1,c=Ne(e),u=tD(c?.bestOf??1);if(typeof a=="number"&&(r===Gt&&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===Me&&(+i[1-a]===u&&(i[1-a]-=1),n?.setsCreditForRetirements&&(i[a]=u)),i}function nT({matchUpFormat:t=bn,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=Ne(t),c=a?.bestOf??1,u=tD(c),p=a?.setFormat?.tiebreakAt||0,m=[[],[]];if(typeof s=="number"&&(r===Gt&&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;yv(I)&&!h&&(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===Me&&typeof s=="number"){let d=i.length>u&&a?.finalSetFormat?"finalSetFormat":"setFormat",l=a?.[d];if(yv(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=Lg({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 oT({matchUpFormat:t,score:e}){let r=t?Ne(t):void 0,n=r?.bestOf??1,o=tD(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(Ev(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 tD(t){return t&&Math.ceil(t/2)||1}function Ev(t){return t==="P"}function yv(t){return!Ev(t)}function Av({participantResults:t,groupingTotal:e,matchUpFormat:r,tallyPolicy:n,totalGames:o,perPlayer:i,totalSets:s}){let a=r&&Ne(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 O=t[d].pointsWon+t[d].pointsLost,v=Math.round(t[d].pointsWon/O*m)/m;(v===1/0||isNaN(v))&&(v=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=v,t[d].result=`${t[d].matchUpsWon}/${t[d].matchUpsLost}`})}function ku({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,[wd(g,0),wd(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&&YG(g),U=y&&qG(g);if(!A&&!U)if(I&&ae.includes(I)){let N=wd(g,0),D=wd(g,1);N&&(Oc(a,N),a[N].matchUpsCancelled+=1),D&&(Oc(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&&(Oc(a,D),Oc(a,M),a[D].tieMatchUpsWon+=1,a[M].tieMatchUpsLost+=1,de(Lt)(N.matchUpType)?(a[D].tieSinglesWon+=1,a[M].tieSinglesLost+=1):de(vt)(N.matchUpType)&&(a[D].tieDoublesWon+=1,a[M].tieDoublesLost+=1))}Uv({score:N.score,manualGamesOverride:P,participantResults:a,sides:E})}}else Uv({manualGamesOverride:P,participantResults:a,score:T,sides:E});else if(Oc(a,A),Oc(a,U),h?.length){i=0;for(let N of h){let{matchUpType:D}=N,M=de(vt)(D),R=de(Lt)(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)))),Pv({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})}Dv({winningParticipantId:A,losingParticipantId:U,participantResults:a,matchUpStatus:I})}else Pv({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,O)=>b+(O?.side1Score??0),0),D=T?.sets?.reduce((b,O)=>b+(O.side2Score??0),0),M=E?.find(({sideNumber:b})=>b===1)?.participantId,R=E?.find(({sideNumber:b})=>b===2)?.participantId;Oc(a,M),Oc(a,R),M&&(a[M].gamesWon+=N,a[M].gamesLost+=D),R&&(a[R].gamesWon+=D,a[R].gamesLost+=N)}}return Av({participantResults:a,groupingTotal:r,matchUpFormat:n,tallyPolicy:o,totalGames:f,perPlayer:i,totalSets:m}),{participantResults:a}}function YG(t){let e=t.winningSide-1;return wd(t,e)}function qG(t){let e=1-(t.winningSide-1);return wd(t,e)}function wd(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 Oc(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 Uv({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&&(Oc(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 Pv({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===Lt&&Tv({participantResults:n,sides:d,score:m}),a||Dv({winningParticipantId:t,losingParticipantId:r,participantResults:n,matchUpStatus:s});let g=Lg({matchUpStatus:s,matchUpFormat:i,tallyPolicy:u,winningSide:p,score:m}),I=nT({matchUpStatus:s,matchUpFormat:i,tallyPolicy:u,winningSide:p,score:m}),{pointsTally:h}=oT({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 Dv({winningParticipantId:t,losingParticipantId:e,participantResults:r,matchUpStatus:n}){e&&(n===Bt&&(r[e].walkovers+=1),n===Gt&&(r[e].defaults+=1),n===Me&&(r[e].retirements+=1),pr(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 $G(t,e,r,n){t.groups&&Object.keys(t.groups).sort(n).forEach(o=>{let i=t.groups[o].map(a=>e[a]).join(", "),s=`${o} ${t.attribute}: ${i}`;r.push(s)})}function KG(t,e,r,n){if(t.excludedDirectives?.length){let o=t.excludedDirectives.map(({attribute:a})=>a).join(", "),i=`${o.length} directives were excluded due to participants limit}`;n.push(i);let s=`Excluded: ${o}`;n.push(s)}else{let o=(u,p)=>Number.parseFloat(t.reversed?u:p)-Number.parseFloat(t.reversed?p:u),i=t.groups?Object.values(t.groups).flat(1/0).length:t.participantIds?.length??0,s=t.reversed?" in reverse order":"",a=t.groups?"grouped":"separated",c=`Step ${e+1}: ${i} particiants were ${a}${s} by ${t.attribute}`;if(n.push(c),t.idsFilter){let u=`${t.attribute} was calculated considering ONLY TIED PARTICIPANTS`;n.push(u)}$G(t,r,n,o)}n.push("----------------------")}function Nv({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)=>{KG(i,s,n,o)}),o.push("Final Order:"),e.forEach(i=>{let{participantId:s,resolved:a}=i,c=i.groupOrder||i.provisionalOrder;o.push(`${c}: ${n[s]} => resolved: ${!!a}`)}),o.join(`\r
|
|
4
|
-
`)}function eD({participantResults:t,participantIds:e,attribute:r}){return rD({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 rD(t){return(t.participantIds||Object.keys(t.participantResults)).reduce((r,n,o)=>(r.push({participantId:n,i:o,results:t.participantResults[n]}),r),[])}var zG=[{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}],nD={matchUpsPct:20,tieMatchUpsPct:16,pointsPct:4,gamesPct:8,setsPct:12};function oD(t){let{requireCompletion:e=!0,participantResults:r,subOrderMap:n,tallyPolicy:o}=t,i=[];if(e&&!QG(t))return{};let s=["tieMatchUpsWon","tieSinglesWon","tieDoublesWon","matchUpsWon","pointsWon","gamesWon","setsWon","gamesPct","setsPct","pointsPct","matchUpsPct"].includes(o?.groupOrderKey)?o.groupOrderKey:"matchUpsWon",a=eD({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=Mv({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=Er(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(nD).filter(E=>o.GEMscore.includes(E)):Object.keys(nD)).map(E=>(S[E]||0)*Math.pow(10,nD[E].toFixed(3))).reduce((E,P)=>E+P,0)}}function QG({participantResults:t,participantsCount:e}){let n=rD({participantResults:t}).filter(o=>e-1===o.results.matchUpsWon+o.results.matchUpsLost+o.results.matchUpsCancelled);return e===n.length}function XG({disableHeadToHead:t,participantIds:e,matchUpFormat:r,groupTotals:n,tallyPolicy:o,attribute:i,idsFilter:s,matchUps:a,reversed:c}){let{participantResults:u}=ku({participantIds:s&&e,groupingTotal:n&&i,matchUpFormat:r,tallyPolicy:o,matchUps:a}),p=eD({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=Mv({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 Mv({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=JG({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||zG).filter(m=>{let d=!(Jt(m.maxParticipants)&&r?.length>m.maxParticipants);return d||s.push(m),d});return s.length&&a.push({excludedDirectives:s,participantIds:r}),p.every(({attribute:m,reversed:d,idsFilter:l,groupTotals:f,disableHeadToHead:g})=>(c=XG({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 JG({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 Fa({policyDefinitions:t,generateReport:e,pressureRating:r,matchUpFormat:n,matchUps:o=[],subOrderMap:i,perPlayer:s}){if(!o?.length||!Br(o))return{error:no};let a=pt(o.map(({structureId:y})=>y));if(a.length!==1)return _({result:{error:B,info:"Maximum one structureId"},stack:"tallyParticipantResults",context:{structureIds:a}});let c=o.filter(y=>y&&y.matchUpStatus!=="BYE"),u=c.length&&pt(c.map(({drawPositions:y})=>y).flat()).length,p=c.filter(y=>Ts({matchUp:y})).length===c.length;p||(s=0);let m=o.every(({matchUpType:y,tieMatchUps:E})=>y===Wt&&E?.every(P=>Ts({matchUp:P}))),d=t?.[kf],l=o.filter(y=>Ts({matchUp:y})??y.matchUpType===Wt),{participantResults:f}=ku({matchUps:l,pressureRating:r,matchUpFormat:n,tallyPolicy:d,perPlayer:s}),g,I,{groupOrder:h,report:S}=oD({matchUps:l,participantResults:f,participantsCount:u,matchUpFormat:n,subOrderMap:i,tallyPolicy:d});if(r&&ZG({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}=oD({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||Dr({tally:!0})){let y=Nv({matchUps:o,report:g,order:I});Dr({tally:!0})&&console.log(y),T.readableReport=y}return T}function ZG({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 iT({positionAssignments:t}){let e=(t||[]).filter(Hr(ao)).map(i=>{let{extension:s}=mt({element:i,name:fc}),a=dt(s?.value),c=!isNaN(a)&&a;return c&&{participantId:i.participantId,subOrder:c}}).filter(Boolean),r=e.map(({subOrder:i})=>i),n=Er(r);return{subOrderMap:Object.assign({},...e.filter(({subOrder:i})=>n[i]===1).map(({participantId:i,subOrder:s})=>({[i]:s})))}}function Ld({positionAssignments:t,tournamentRecord:e,drawDefinition:r,matchUpFormat:n,matchUps:o,event:i}){if(!Br(o))return{error:B};if(!t)return{error:B};let{policyDefinitions:s}=Go({policyTypes:[kf],tournamentRecord:e,drawDefinition:r,event:i}),{subOrderMap:a}=iT({positionAssignments:t}),c=o.length?Fa({policyDefinitions:s,matchUpFormat:n,subOrderMap:a,matchUps:o}):void 0;if(c?.error)return c;let{participantResults:u={},bracketComplete:p,report:m}=c??{},d=Object.keys(u);return t.forEach(l=>{let{participantId:f}=l;if(d.includes(f)){let g={value:u[f],name:Lo};At({element:l,extension:g}),u[f].ties||Ir({element:l,name:fc})}else Ir({element:l,name:Lo}),Ir({element:l,name:fc})}),bt({drawDefinition:r}),{...C,participantResults:u,bracketComplete:p,report:m}}function sT({matchUps:t,matchUpId:e}){return{matchUp:(t||[]).find(n=>n.matchUpId===e)}}function Vt(t){let e=et(t,[{[Ce]:!0,[gn]:!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=[]}=hn({drawDefinition:i}),d=t.contextContent||o&&Zn({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}=sT({matchUps:f,matchUpId:a});if(g)return{matchUp:g,structure:l}}return{error:we}}function $p(t){return!ht(t)||!t.notes?{error:st}:ht(t.element)?!kt(t.notes)&&!t.notes?.testing?{error:B}:(Object.assign(t.element,{notes:t.notes}),{...C}):{error:B}}function Fg(t){return ht(t)?ht(t.element)?(t.element.notes&&delete t.element.notes,{...C}):{error:B}:{error:st}}var Gu={matchUpStatus:Qt,matchUpStatusCodes:[],score:{scoreStringSide1:"",scoreStringSide2:"",sets:void 0},matchUpFormat:void 0,winningSide:void 0};function Yn(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:[rn],tournamentRecord:s,drawDefinition:a,structure:o,event:d})?.appliedPolicies,h=n.matchUpType===Wt;if(h&&a){if(m&&n.matchUpId!==m){let U=Vt({drawDefinition:a,matchUpId:m,event:d});if(!U.matchUp)return{error:we};({matchUp:n,structure:o}=U)}}else n.matchUpId!==m&&console.log("!!!!!");c&&[Bt,oe].includes(c)||u?Object.assign(n,{...Gu}):f&&(n.score=f);let S=c&&n?.matchUpStatus===Gt&&c!==Gt;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}=Vt({drawDefinition:a,matchUpId:m,event:d})),c&&!n.winningSide&&he(n)&&!ae.includes(c)&&![gc,ls,mn].includes(c)&&(n.matchUpStatus=Hn);let T;if((S&&n?.processCodes?.length||c===Gt)&&(T=I?.[rn]?.processCodes?.incompleteAssignmentsOnDefault),!n.collectionId){let U=o?.structureType===Ve,N=cr({structure:o});if(gd({drawDefinition:a,structure:o})||N||U){let D=b=>{r=h?"SET1-S:T100":r??n.matchUpFormat??b?.matchUpFormat??a?.matchUpFormat??d?.matchUpFormat;let O=h?{matchUpTypes:[Wt]}:void 0,{matchUps:v}=yt({afterRecoveryTimes:!1,tournamentRecord:s,inContext:!0,matchUpFilters:O,drawDefinition:a,structure:b,event:d});return N&&(b.positionAssignments=pt(v.flatMap(x=>(x.sides??[]).map(F=>F.participantId)).filter(Boolean)).map(x=>({participantId:x}))),Ld({positionAssignments:b.positionAssignments,tournamentRecord:s,drawDefinition:a,matchUpFormat:r,matchUps:v,event:d})},M=U&&o.structures.find(b=>b?.matchUps.find(O=>O.matchUpId===m)),R=D(M||o);if(R.error)return _({result:R,stack:e})}}if(l){let U=$p({element:n,notes:l});if(U.error)return _({result:U,stack:e})}let y=s?.tournamentId,E=Lr().topics.includes(Rp),P=(E||T)&&Pe({drawDefinition:a}),A=P&&ie({matchUpFilters:{matchUpIds:[m]},nextMatchUps:!0,tournamentRecord:s,inContext:!0,drawDefinition:a,matchUpsMap:P}).matchUps?.[0];if(E&&A&&Cb({tournamentId:y,inContextMatchUp:A}),Array.isArray(T)&&A&&!A.sides?.every(({participantId:U})=>U))if(c===Gt)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 Fd(t){let{propagateExitStatus:e,matchUpStatusCodes:r,autoCalcDisabled:n,inContextMatchUp:o,matchUpStatus:i,dualMatchUp:s,structure:a,matchUp:c}=t,u=Oa({matchUpStatus:i})||[po,vr].includes(i)&&s||n,p=c?.sides?.map(h=>h.participantId).filter(Boolean).length||o?.sides?.map(h=>h.participantId).filter(Boolean).length,m="attemptToModifyScore";if(!(cr({structure:a})&&p===1||i===Gt&&p||tV({structure:a,matchUp:c,inContextMatchUp:o})||t.appliedPolicies?.[rn]?.requireParticipantsForScoring===!1||pr(i)&&p===1&&e))return _({result:{error:Ql},stack:m});let f=[Bt].includes(i),g=u?i:t.winningSide&&ge||mn,I=Yn({...t,winningSide:t.winningSide,matchUpStatusCodes:u&&r||[],matchUpStatus:g,context:m,removeScore:f});return _({result:I,stack:m})}function tV({structure:t,matchUp:e,inContextMatchUp:r}){let{drawPositions:n}=e,{positionAssignments:o}=Ie({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 aT({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 Rv({collectionDefinition:t,groupValueNumbers:e,groupValueGroups:r,sideTieValues:n,tieMatchUps:o}){let i=o.filter(S=>S.collectionId===t.collectionId),s=[0,0],a=[0,0],c=i.every(S=>ae.includes(S.matchUpStatus)),{collectionValueProfiles:u,collectionGroupNumber:p,collectionValue:m,matchUpValue:d,winCriteria:l,scoreValue:f,setValue:g}=t,I=p&&e.includes(p),h=[0,0];if(i.forEach(S=>{S.winningSide&&(h[S.winningSide-1]+=1)}),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===ge||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=eV({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 eV({collectionDefinition:t,collectionPosition:e}){return(t.collectionValueProfiles||[])?.find(o=>o.collectionPosition===e)?.matchUpValue}function vc(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:B};if(!s)return{error:mr};let c=We({matchUp:s,drawDefinition:n,structure:i,event:a})?.tieFormat||t?.tieFormat;if(!c)return{error:ks};let u=ar({tieFormat:c});if(u.error)return u;let p=c?.collectionDefinitions||[],m=s?.tieMatchUps??[],d=[0,0],{groupValueGroups:l,groupValueNumbers:f}=aT(c);for(let y of p)Rv({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,O,v)=>O>=U.valueGoal?v+1:b,void 0);else{let b=Math.floor(A/2)+1;R=D.reduce((O,v,x)=>v>=b?x+1:O,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&&ae.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&&Vt({inContext:!0,drawDefinition:n,matchUpId:A})?.matchUp;if(U){let{completedTieMatchUps:N,order:D}=Fa({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 ka({inContextDualMatchUp:t,drawDefinition:e,tournamentId:r,dualMatchUp:n,eventId:o}){if(n){t||(t=Vt({matchUpId:n.matchUpId,inContext:!0,drawDefinition:e})?.matchUp);let{extension:i}=mt({element:e,name:wo}),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 or(t){if(t)return J(t,!1,!0)}function kg(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 cT({tournamentRecords:t,eventId:e,drawId:r}){let{tournamentIdMap:n}=kg({tournamentRecords:t});return(n?Object.keys(n):[]).find(i=>e&&n?.[i].includes(e)||r&&n?.[i].includes(r))}function go(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&&cT({tournamentRecords:c,...t});let p=u&&c[u];if(!p)return{error:q};let m=Vt({drawDefinition:r,event:a,matchUpId:s});if(m.error)return m;if(!m.matchUp)return{error:we};let{matchUp:d,structure:l}=m;if(!d.tieMatchUps)return{error:dr};ka({tournamentId:p?.tournamentId,eventId:a?.eventId,dualMatchUp:d,drawDefinition:r});let{extension:f}=mt({name:Ua,element:d});if(f?.value)if(o)Ir({element:d,name:Ua});else return{...C,score:d.score};let g=We({drawDefinition:r,structure:l,matchUp:d,event:a})?.tieFormat;d.tieFormat=or(g);let I=vc({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&&ge||Ig({matchUpStatus:n??d.matchUpStatus,tieMatchUps:d.tieMatchUps,winningSide:d.winningSide,score:P})&&Hn||Qt,N=!!(d.winningSide&&!A),D=d.tieMatchUps.find(({score:R,winningSide:b,matchUpStatus:O})=>R?.sets?.length&&(R.sets[0].side1Score||R.sets[0].side2Score)||O&&ae.includes(O)||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 Yn({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 Cv({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}=Ie({structureId:I,drawDefinition:c}),E=T?.find(R=>R.drawPosition===o)?.participantId,P=s.target.structureId,{positionAssignments:A}=Ie({structureId:P,drawDefinition:c}),N=A?.find(R=>R.participantId===E)?.drawPosition,D=A?.filter(R=>{let b=f.includes(R.drawPosition),O=!R.participantId&&!R.bye&&!R.qualifier;return b&&O}).map(R=>R.drawPosition),M=D?.includes(g);if(E&&s.target.roundNumber===1&&M)jn({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&&jn({participantId:E,structureId:P,inContextDrawMatchUps:e,sourceMatchUpStatus:n,tournamentRecord:i,drawDefinition:c,drawPosition:R,matchUpsMap:m,event:d})}else if(N){let R=wa({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";console.log(R),_({stack:l,result:{error:R}})}if(S?.seedAssignments&&S.structureId!==P){let R=S.seedAssignments.find(({participantId:O})=>O===E),b=R?.participantId;R&&b&&ra({eventId:u?.eventId,structureId:P,...R,tournamentRecord:i,drawDefinition:c,participantId:b})}}else{let f=wa({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=Rd({lineUp:E}),gt({tournamentId:i?.tournamentId,eventId:u?.eventId,matchUp:S,context:l,drawDefinition:c})}}}return{...C}}function bv(t){let{loserMatchUpDrawPositionIndex:e,inContextDrawMatchUps:r,projectedWinningSide:n,propagateExitStatus:o,sourceMatchUpStatus:i,loserDrawPosition:s,tournamentRecord:a,loserTargetLink:c,drawDefinition:u,loserMatchUp:p,dualMatchUp:m,matchUpsMap:d,event:l}=t,f="directLoser",g=c.linkCondition,I=p.drawPositions||[],h=g===kn&&p.roundNumber===2&&Math.min(...I.filter(Boolean)),S=h||I[e],T=h||I[1-e],y=c.source.structureId,{structure:E}=at({structureId:y,drawDefinition:u}),{matchUps:P}=yt({afterRecoveryTimes:!1,inContext:!0,drawDefinition:u,structure:E,event:l}),U=P.filter(V=>V.drawPositions?.includes(s)).filter(V=>{let $=V.sides.find(W=>W.drawPosition===s),X=V.matchUpStatus===Bt||V.matchUpStatus===Gt&&!he(V);return $?.sideNumber===V.winningSide&&!X}),N=g===kn&&U.length===0,{positionAssignments:D}=Ie({structureId:y,drawDefinition:u}),R=D?.find(V=>V.drawPosition===s)?.participantId,b={loserParticipantId:R},O=c.target.structureId,{positionAssignments:v}=Ie({structureId:O,drawDefinition:u}),x=v?.filter(({drawPosition:V})=>I.includes(V)),F=x?.some(V=>V.participantId&&R&&V.participantId===R),w=o&&[Me,Bt,Gt].includes(i||"");if(F)return{...C,stack:f};let L=x?.filter(V=>{let $=I.includes(V.drawPosition),X=!V.participantId&&!V.bye&&!V.qualifier;return $&&X}).map(V=>V.drawPosition),k=L?.includes(S),G=c.target.roundNumber>1&&L?.length,H=c.target.roundNumber===1&&k;if(h){let V=K();if(V.context&&Object.assign(b,V.context),V.error)return _({result:V,stack:f})}else if(H){let V=j();if(V.context&&Object.assign(b,V.context),V.error)return _({result:V,stack:f})}else if(R&&G){L.sort(le);let V=L[0],$=jn({participantId:R,structureId:O,drawPosition:V,inContextDrawMatchUps:r,sourceMatchUpStatus:i,tournamentRecord:a,drawDefinition:u,matchUpsMap:d,event:l});if($.error)return _({result:$,stack:f});if(!$.error&&w&&o)return{stack:f,context:{progressExitStatus:!0,loserParticipantId:R}}}else return _({context:{loserDrawPosition:s,loserTargetLink:c,targetDrawPositionIsUnfilled:k},result:{error:k?Ls:CC},stack:f});if(E?.seedAssignments&&E.structureId!==O){let V=E.seedAssignments.find(({participantId:X})=>X===R),$=V?.participantId;V&&$&&ra({eventId:p?.eventId,structureId:O,...V,tournamentRecord:a,drawDefinition:u,participantId:$})}if(m&&n){let V=m.sides?.find($=>$.sideNumber===3-n);if(V?.lineUp){let{roundNumber:$,eventId:X}=p,{roundPosition:W}=m,it=$===1?2-W%2:1,z=d?.drawMatchUps?.find(({matchUpId:ot})=>ot===p.matchUpId),Q=[1,2].map(ot=>({...z.sides?.find(Rt=>Rt.sideNumber===ot)||{},sideNumber:ot}));z.sides=Q;let ut=z.sides.find(ot=>ot.sideNumber===it);ut&&(ut.lineUp=Rd({lineUp:V.lineUp}),gt({tournamentId:a?.tournamentId,matchUp:z,context:f,drawDefinition:u,eventId:X}))}}return _({result:{...C},stack:f,context:b});function K(){let V="loserLinkFedFMLC";return N?_({result:j(),stack:V}):_({result:Y(),stack:V})}function Y(){let V=Wr({drawPosition:T,structureId:O,tournamentRecord:a,drawDefinition:u,event:l});return _({result:V,stack:"assignLoserPositionBye"})}function j(){let V=R?jn({drawPosition:S,participantId:R,structureId:O,inContextDrawMatchUps:r,sourceMatchUpStatus:i,tournamentRecord:a,drawDefinition:u,matchUpsMap:d,event:l}):{error:se};return!V.error&&w&&o?{stack:f,context:{progressExitStatus:!0}}:_({result:V,stack:"assignLoserDrawPosition"})}}function uT(t){let e="directParticipants",r=Fd(t);if(r.error)return _({result:r,stack:e});let n=Oa({matchUpStatus:t.matchUpStatus}),{dualWinningSideChange:o,inContextDrawMatchUps:i,projectedWinningSide:s,propagateExitStatus:a,matchUpStatusCodes:c,tournamentRecord:u,drawDefinition:p,matchUpStatus:m,dualMatchUp:d,matchUpsMap:l,winningSide:f,targetData:g,matchUpId:I,structure:h,matchUp:S,event:T}=t,y=!!S.collectionId,E=cr({structure:h}),P=S.drawPositions,A;if(y){let{matchUpTieId:U,matchUpsMap:N}=t,D=go({appliedPolicies:t.appliedPolicies,matchUpId:U,tournamentRecord:u,drawDefinition:p,matchUpsMap:N,event:T});if(A=D&&{tieMatchUpResult:D},P=i.find(({matchUpId:R})=>R===U)?.drawPositions,!o)return _({result:{...C,...A},stack:e})}if(E)return _({result:{...C,...A},stack:e});if(P){let U=s?s-1:f-1,N=1-U,D=P[U],M=P[N],R={},{targetLinks:{loserTargetLink:b,winnerTargetLink:O,byeTargetLink:v},targetMatchUps:{winnerMatchUpDrawPositionIndex:x,loserMatchUpDrawPositionIndex:F,winnerMatchUp:w,loserMatchUp:L,byeMatchUp:k}}=g;if(w){let G=Cv({sourceMatchUpStatus:n&&m||ge,winnerMatchUpDrawPositionIndex:x,sourceMatchUpId:I,inContextDrawMatchUps:i,projectedWinningSide:s,winningDrawPosition:D,tournamentRecord:u,winnerTargetLink:O,drawDefinition:p,winnerMatchUp:w,dualMatchUp:d,matchUpsMap:l,event:T});if(G.error)return _({result:G,stack:e})}if(L){let G=bv({sourceMatchUpStatus:n&&m||ge,sourceMatchUpStatusCodes:c||[],sourceWinningSide:f,loserMatchUpDrawPositionIndex:F,sourceMatchUpId:I,inContextDrawMatchUps:i,projectedWinningSide:s,propagateExitStatus:a,loserDrawPosition:M,tournamentRecord:u,loserTargetLink:b,drawDefinition:p,loserMatchUp:L,winningSide:f,matchUpsMap:l,dualMatchUp:d,event:T});if(G.context?.progressExitStatus&&Object.assign(R,G.context,{sourceMatchUpStatus:n&&m||ge,sourceMatchUpStatusCodes:c||[],loserMatchUp:L,matchUpsMap:l}),G.error)return _({result:G,stack:e})}if(k){let G=k.drawPositions||[],H=Math.min(...G.filter(Boolean)),K=v.target.structureId,Y=Wr({drawPosition:H,structureId:K,tournamentRecord:u,drawDefinition:p,event:T});if(Y.error)return _({result:Y,stack:e})}return _({result:{...C,...A},stack:e,context:R})}else return _({result:{error:Ja},stack:e})}function kd(t){let e="genPlayoffStructure";if(!t.drawDefinition)return _({result:{error:Z},stack:e});let r=Lu(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:_t},stack:e});if(y.structureType===Ve||y.structures)return gv({sourceStructureId:y.structureId,...t,...r,drawDefinition:T});let{playoffRoundsRanges:E,playoffRounds:P}=r,{playoffPositionsReturned:A,error:U,playoffSourceRounds:N,playoffRoundsRanges:D}=XS(t);if(U)return _({result:{error:U},stack:e});let M=l?.length&&Object.assign({},...l),R=f||typeof l=="object"&&l.map(W=>Object.keys(W)).flat(),b=Array.isArray(R)&&R.map(W=>!isNaN(W)&&dt(W)).filter(Boolean);if(b){if(!Array.isArray(b))return _({result:{error:B},context:{validRoundNumbers:b},stack:e});b.forEach(W=>{if(!P?.includes(W))return _({result:{error:B},context:{roundNumber:W},stack:e})})}u&&u.forEach(W=>{if(!A?.includes(W))return _({result:{error:B},context:{playoffPosition:W},stack:e})});let O=b||N,v=b?E:D,x=[],F=[];for(let W of O??[]){let it=v?.find(qt=>qt.roundNumber===W);if(!it)return _({result:{error:B},context:{roundNumber:W},stack:e});let z=it.finishingPositions.length,Q=Math.min(...it.finishingPositions)-1,ut=2,ot=W&&M?.[W]&&ut+M[W]-1,Dt=Rc({exitProfile:`0-${W}`,addNameBaseToAttributeName:o,playoffStructureNameBase:i,finishingPositionOffset:Q,playoffAttributes:c,exitProfileLimit:d,stage:fe,roundOffset:0,drawDefinition:T,sequenceLimit:ot,stageSequence:ut,drawSize:z,idPrefix:g,isMock:I,uuids:S,finishingPositionNaming:s,finishingPositionLimit:a,roundOffsetLimit:p});if(Dt.error)return _({result:Dt,stack:e});let{structures:Rt,links:De}=Dt;if(Rt?.length&&x.push(...Rt),De?.length&&F.push(...De),Dt.structureId&&W){let qt={linkType:so,source:{structureId:n,roundNumber:W},target:{structureId:Dt.structureId,feedProfile:Nn,roundNumber:1}};F.push(qt)}}if(!x.length)return _({result:{error:B},info:"No structures generated",stack:e});T.structures.push(...x),T.links.push(...F);let{matchUps:w,matchUpsMap:L}=ie({inContext:!0,drawDefinition:T}),k=x.map(({structureId:W})=>W),G=w?.filter(({structureId:W})=>k.includes(W)).map(Ue),H=L?.drawMatchUps?.filter(({matchUpId:W})=>G?.includes(W));if(H?.length){let W=We({drawDefinition:T,event:h})?.tieFormat;W&&H.forEach(it=>{let{tieMatchUps:z}=Li({matchUp:it,tieFormat:W,isMock:I});Object.assign(it,{tieMatchUps:z,matchUpType:Wt})})}w?.filter(W=>Ts({matchUp:W})&&W.structureId===n)?.forEach(W=>{let{matchUpId:it,score:z,winningSide:Q}=W,ut=ur({inContextDrawMatchUps:w,drawDefinition:T,matchUpId:it}),ot=uT({inContextDrawMatchUps:w,tournamentRecord:m,drawDefinition:T,matchUpsMap:L,winningSide:Q,targetData:ut,matchUpId:it,structure:y,matchUp:W,score:z,event:h});ot.error&&console.log(ot.error)}),w?.filter(W=>W.matchUpStatus==="BYE"&&W.structureId===n)?.forEach(W=>{let{matchUpId:it}=W,z=ur({inContextDrawMatchUps:w,drawDefinition:T,matchUpId:it}),{targetLinks:{loserTargetLink:Q},targetMatchUps:{loserMatchUpDrawPositionIndex:ut,loserMatchUp:ot}}=z;if(Q&&ot){let Dt=Q.target.structureId,Rt=ot.drawPositions[ut],De=Wr({drawPosition:Rt,structureId:Dt,tournamentRecord:m,drawDefinition:T,event:h});De.error&&console.log(De.error)}});let j=[],V=rs({inContextDrawMatchUps:w,drawDefinition:T,matchUpsMap:L}).goesToMap,{structure:$}=at({drawDefinition:t.drawDefinition,structureId:n}),{matchUps:X}=yt({structure:$});return X.forEach(W=>{let it=V?.loserMatchUpIds[W.matchUpId];if(it&&W.loserMatchUpId!==it){W.loserMatchUpId=it;let Q={tournamentId:m?.tournamentId,eventId:t.event?.eventId,context:e,matchUp:W};j.push(Q)}let z=V?.winnerMatchUpIds[W.matchUpId];if(z&&W.winnerMatchUpId!==z){W.winnerMatchUpId=z;let Q={tournamentId:m?.tournamentId,eventId:t.event?.eventId,context:e,matchUp:W};j.push(Q)}}),{structures:x,matchUpModifications:j,links:F,drawDefinition:T,...C}}function pT({element:t}){if(!t)return{error:B};if(!t.timeItems)return{};if(!Array.isArray(t.timeItems))return{error:B};let e=(r,n)=>(o,i)=>(i[r]&&(o[i[r]]=i[n]),o);return t.timeItems.reduce(e("itemType","itemValue"),{})}function ro(t){let{duplicateValues:e=!0,creationTime:r=!0,removePriorValues:n,timeItem:o}=t;if(!o)return{error:mf};let i=oS(t);if(i.error)return i;if(!(ht(o)&&kt(o.itemType)&&Object.keys(o).includes("itemValue")))return{error:pf};if(!i.timeItems)i.timeItems=[];else if(rV({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 rV({element:t,duplicateValues:e,timeItem:r}){let{itemType:n,itemSubTypes:o,itemValue:i}=r,s=n&&nn({itemSubTypes:o,itemType:n,element:t})?.timeItem;return s&&JSON.stringify(s?.itemValue)===JSON.stringify(i)&&!e}function Gg({creationTime:t=!0,removePriorValues:e,tournamentRecord:r,duplicateValues:n,participantId:o,timeItem:i}){if(!r)return{error:q};if(!o)return{error:se};let s=Uo({tournamentRecord:r,participantId:o});return s.error?s:ro({element:s.participant,removePriorValues:e,duplicateValues:n,creationTime:t,timeItem:i})}function _c(t){let{removePriorValues:e,tournamentRecord:r,duplicateValues:n,creationTime:o,timeItem:i}=t;if(!r)return{error:q};let s=ro({element:r,removePriorValues:e,duplicateValues:n,creationTime:o,timeItem:i});if(s.error)return s;let a=pT({element:r});return lt({payload:{parentOrganisation:r.parentOrganisation,tournamentId:r.tournamentId,timeItemValues:a},topic:Xi}),s}function is(t){let{removePriorValues:e,duplicateValues:r,creationTime:n,timeItem:o,event:i}=t;return i?ro({removePriorValues:e,duplicateValues:r,element:i,creationTime:n,timeItem:o}):{error:qr}}function iD(t){return Bg({...t,itemType:"attachConsolationStructures"})}function Vg(t){return Bg({...t,itemType:"attachPlayoffStructures"})}function Bg({itemType:t="attachStructures",matchUpModifications:e,tournamentRecord:r,drawDefinition:n,structures:o,links:i=[],event:s}){let a="attachStructures";if(!n)return{error:Z};if(!Array.isArray(o)||!Array.isArray(i))return _({result:{error:B},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:If},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),rs({drawDefinition:n});let f=o.map(h=>yt({structure:h})?.matchUps||[]).flat();Fo({tournamentId:r?.tournamentId,eventId:s?.eventId,drawDefinition:n,matchUps:f});let g=o.map(({structureId:h})=>h);if(bt({drawDefinition:n,structureIds:g}),e?.length){let h={};e.forEach(T=>{let 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(Hr("structureId"));if(r){let S={itemValue:{structureIds:g,drawId:n.drawId},itemType:t};ro({element:r,timeItem:S})}return{...C,addedStructureIds:I}}function Kp(t){let{structures:e,links:r,matchUpModifications:n,error:o}=kd(t);if(o)return{error:o};let i=t.drawDefinition;return Vg({tournamentId:t.tournamentRecord?.tournamentId,eventId:t.event?.eventId||t.eventId,matchUpModifications:n,drawDefinition:i,structures:e,links:r})}function ss(t){let e=et(t,[{_anyOf:{[Re]:!1,[ne]:!1,[Ce]:!1,[co]:!1},[_f]:!0}]);if(e.error)return e;let r=[],n=t.drawDefinition??t.event??((t.tournamentId||!t.tournamentRecords)&&t.tournamentRecord);if(n){let o=Ov(t,n);if(o.error)return o;r.push(...o?.applied??[]),t.drawDefinition&&bt({drawDefinition:t.drawDefinition,tournamentId:t.tournamentId})}else if(t.tournamentRecords){let o=Object.keys(t.tournamentRecords);if(!o.length)return{error:q};for(let i of o){let s=t.tournamentRecords[i],a=Ov(t,s);if(a.error)return a;r.push(...a?.applied??[])}}else return{error:q};return r.length?{...C,applied:r}:{error:$I}}function Ov(t,e){let r=Tt(t).appliedPolicies??{};e.extensions||(e.extensions=[]);let n=[],o=Object.keys(t.policyDefinitions);if(!o.length)return{error:op};for(let i of o)if(!r[i]||t.allowReplacement){let s=t.policyDefinitions[i];if(!s)continue;if(!ht(s))return{error:B};let{policyName:a,...c}=s;if(!c||!Object.keys(c).length||a&&!kt(a))return{error:B};r[i]=t.policyDefinitions[i],n.push(i)}return n?.length?{...At({element:e,extension:{name:du,value:r}}),applied:n}:{applied:n,error:$I}}function Hg({tournamentRecord:t,drawDefinition:e,flightProfile:r,drawName:n,drawId:o,event:i}){if(!n||typeof n!="string")return _({result:{error:B},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:pn,value:{...r,flights:r.flights}};xo({event:i,extension:a})}return e&&(e.drawName=n,bt({tournamentId:t?.tournamentId,drawDefinition:e})),!s&&!e?{error:Z}:{...C,flight:s}}function sD({tournamentRecord:t,drawDefinition:e,drawUpdates:r,drawId:n,event:o}){if(!ht(r))return{error:B};let i=Ht({event:o}).flightProfile,s=r.drawName&&Hg({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:pn,value:{...i,flights:i.flights}};xo({event:o,extension:c})}return e&&(r.policyDefinitions&&ss({policyDefinitions:r.policyDefinitions,drawDefinition:e}),bt({tournamentId:t?.tournamentId,drawDefinition:e})),{...C}}function aD({tournamentRecord:t,removeScheduling:e,drawDefinition:r}){if(!r)return{error:Z};let n=Pe({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!=="BYE"&&Object.assign(I,Gu),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&&![lo,Jo,Ji,dg,Zi,ts].includes(h.itemType))),gt({tournamentId:t?.tournamentId,context:"resetDrawDefiniton",drawDefinition:r,matchUp:I})}}}r.extensions=r.extensions.filter(s=>s.name!==lc);let i=(r.structures||[]).map(({structureId:s})=>s);return bt({drawDefinition:r,structureIds:i}),{...C}}function Vu({tournamentRecord:t}){if(!t)return{error:q};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}=_u({drawDefinition:o}),p=r[i],d=(o?.structures||[]).map(E=>{let{stage:P,stageSequence:A,structureId:U}=E,N=$s[P],{inContextStructureMatchUps:D}=va({drawDefinition:o,structure:E,event:p}),M=D?.filter(({winningSide:Y})=>Y),R=M.filter(Boolean).length||0;a+=R,c+=D.length-a;let b=Math.max(M.filter(({roundNumber:Y})=>Y===1).map(({roundPosition:Y})=>Y)),{positionAssignments:O}=Ct({structure:E}),v=O?.filter(({participantId:Y})=>Y);s+=v?.length??0;let x=(O?.length??0)-(v?.length??0),{roundMatchUps:F,roundProfile:w,roundNumbers:L,maxMatchUpsCount:k}=Ke({matchUps:D}),G=w&&Object.keys(w).filter(Y=>!w[Y].inactiveRound).map(Y=>parseInt(Y)),H=w&&Object.keys(w).filter(Y=>w[Y].inactiveRound).map(Y=>parseInt(Y)),K=w&&Object.values(w).every(Y=>Y.inactiveRound);return{positionsAssignedCount:v?.length??0,maxWinningSideFirstRoundPosition:b,unassignedPositionsCount:x,inactiveStructure:K,maxMatchUpsCount:k,inactiveRounds:H,roundMatchUps:F,activeRounds:G,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 cD({matchPlayDrawPositions:t=!0,tournamentRecord:e,drawDefinition:r,drawId:n}){if(!e)return{error:q};if(!r)return{error:Z};let o=[],{drawsAnalysis:i}=Vu({tournamentRecord:e});if(i.canBePruned.includes(n)){let s=i.matchPlay.includes(n),a=i.drawAnalysis[n],{structures:[c]}=hn({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}_n({tournamentId:e?.tournamentId,matchUpIds:d,drawDefinition:r}),bt({drawDefinition:r})}return{...C,matchUps:o}}function uD({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:Fs};if(!o)return{error:Pr};if(a){let c=Wr({tournamentRecord:t,drawDefinition:e,drawPosition:n,structureId:o,event:s});if(c.error)return c}else{if(i)return{error:pp};{let c=jn({tournamentRecord:t,drawDefinition:e,participantId:r,drawPosition:n,structureId:o,event:s});if(c.error)return c}}return{...C}}function mT(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:_t};let o=r.structures?.find(c=>c.structureId===n);if(!o)return{error:_t};let i=o?.matchUps,s=i?.find(c=>!!c.roundPosition);if(o.structures||s||o.finishingPosition===zi)return{error:si};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 pD(t){let e=et(t,[{[Ce]:!0},{[Ks]:{[mc]:!1,roundNumbers:!1},[kr]:B,[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=mT(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||he({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)),_n({tournamentId:i?.tournamentId,matchUpIds:[...I,...g],action:"deleteAdHocMatchUps",eventId:a?.eventId,drawDefinition:s});let h=pt(u.matchUps.map(Hr("roundNumber"))),S=PC(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});cr({structure:u})&&(u.positionAssignments=pt(P.flatMap(N=>(N.sides??[]).map(D=>D.participantId)).filter(Boolean)).map(N=>({participantId:N})));let U=Ld({positionAssignments:u.positionAssignments,tournamentRecord:i,drawDefinition:s,matchUpFormat:T,matchUps:P,event:a});U.error&&console.log(U)}bt({structureIds:[p],eventId:a?.eventId,drawDefinition:s})}return!g.length&&d.length?{error:oc}:{...C,deletedMatchUpsCount:[...g,...I].length}}function mD({removeCompletedMatchUps:t,tournamentRecord:e,drawDefinition:r,structureId:n,roundNumber:o,event:i}){if(!e)return{error:q};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:si}:cr({structure:a})?nV({tournamentId:e.tournamentId,removeCompletedMatchUps:t,eventId:i.eventId,drawDefinition:r,roundNumber:o,structure:a}):(console.log("not implemented"),{...C})}function nV({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&&(!ae.includes(d.matchUpStatus)||t);return l&&(c.push(d.matchUpId),d.tieMatchUps&&a.push(...d.tieMatchUps.map(Ue))),!l});c.length&&(_n({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 Gd(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:Pr};if(!Br(o))return{error:B,info:li("matchUps")};let a=n.structures?.find(l=>l.structureId===s);if(!a)return{error:_t};let u=(a?.matchUps).find(l=>!!l.roundPosition);if(a.structures||u||a.finishingPosition===zi)return{error:si};let p=ye({tournamentRecord:r,inContext:!1})?.matchUps?.map(Ue)??[],m=o.map(Ue);if(ke(p,m))return{error:YA,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||(Fo({tournamentId:r?.tournamentId,matchUps:[...d,...o],eventId:i?.eventId,drawDefinition:n}),bt({drawDefinition:n,structureIds:[s]})),{...C}}function dD({tournamentRecord:t,drawDefinition:e,drawPosition:r,structureId:n,subOrder:o,event:i}){if(!e)return{error:Z};if(!n)return{error:Pr};if(!r)return{error:Fs};let{structure:s}=at({drawDefinition:e,structureId:n});if(!s)return{error:_t};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&&At({element:u,extension:{name:fc,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 Ld({positionAssignments:c,tournamentRecord:t,drawDefinition:e,matchUpFormat:f,matchUps:l,event:i}),bt({drawDefinition:e,structureIds:[n]}),{...C}}var PD={};Xt(PD,{addGoesTo:()=>rs,allPlayoffPositionsFilled:()=>WS,checkValidEntries:()=>Hd,findDrawDefinition:()=>gT,getAssignedParticipantIds:()=>wi,getAvailableMatchUpsCount:()=>Vd,getAvailablePlayoffProfiles:()=>Lu,getDrawDefinitionTimeItem:()=>iS,getDrawParticipantRepresentativeIds:()=>lT,getDrawStructures:()=>hn,getDrawTypeCoercion:()=>Bu,getEligibleVoluntaryConsolationParticipants:()=>dT,getMatchUpsMap:()=>Pe,getParticipantIdFinishingPositions:()=>fT,getPositionAssignments:()=>zp,getPositionsPlayedOff:()=>Cc,getRandomQualifierList:()=>RT,getSeedingThresholds:()=>_S,getSeedsCount:()=>Hu,getStructureSeedAssignments:()=>sn,getTeamLineUp:()=>Ss,getValidGroupSizes:()=>Gp,isAdHoc:()=>cr,isCompletedStructure:()=>Do,isValidForQualifying:()=>CT,positionActions:()=>MT});function dT({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?to({contextFilters:{stages:f},matchUpFilters:g,tournamentRecord:s,inContext:!0,event:l})?.matchUps??[]:nr({contextFilters:{stages:f},matchUpFilters:I,tournamentRecord:s,inContext:!0,drawDefinition:a})?.matchUps??[],T=bi({stage:$e,drawDefinition:a}).map(({participantId:L})=>L),y={},E={},P={},A={};o||(o=Go({policyTypes:[Bh],tournamentRecord:s,drawDefinition:a,event:l}).policyDefinitions);let U=o?.[Bh];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!==oe||L.finishingRound&&n&&L.finishingRound>=n||L.finishingRound&&i&&L.finishingRound<=i)continue;let k=L.sides?.find(({sideNumber:H})=>L.winningSide&&H===3-L.winningSide),G=L.sides?.find(({sideNumber:H})=>L.winningSide&&H===L.winningSide);if(L.sides?.forEach(H=>{let K=H?.participant?.participantId;K&&(P[K]=H.participant,L.matchUpStatus===oe&&!u&&(E[K]=H.participant,y[K]||(y[K]=0),(!L.matchUpStatus||!t.includes(L.matchUpStatus))&&(y[K]+=1)))}),k?.participant){let H=k.participant.participantId;E[H]=k.participant,y[H]||(y[H]=0),L.matchUpStatus&&!t.includes(L.matchUpStatus)&&(y[H]+=1)}if(G?.participant){let H=G.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=>![mo,Vr].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),O=L=>!u||(y[L]||0)>=0,v=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)&&O(L.participantId)&&v(L.participantId)&&x(L.participantId)&&F(L.participantId)).map(L=>({...L,individualParticipants:L.individualParticipantIds?.map(k=>s?.participants?.find(G=>G.participantId===k))})),losingParticipantIds:M,...C}}function Vd(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:Pr};let i=r.structures?.find(g=>g.structureId===o);if(!i)return{error:_t};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===zi)return{error:si};let u=r?.entries?.filter(g=>{let I=g.entryStatus;return Xr.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 lT({drawDefinition:t}){let e=mt({name:"participantRepresentatives",element:t});return e.error?e:{representativeParticipantIds:e.extension?.value||[]}}function vv({tournamentParticipants:t,drawDefinition:e,event:r}){if(!e)return{error:Z};let n=ie({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 fT({byeAdvancements:t=!1,tournamentRecord:e,drawDefinition:r}){if(!r)return{error:Z};let{participantIds:n,participantIdMatchUps:o}=vv({tournamentParticipants:e?.participants,drawDefinition:r}),i=n?.map(s=>{let c=o[s].filter(d=>[ge,"BYE"].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 jo({tournamentRecords:t,tournamentRecord:e,tournamentId:r,drawId:n}){if(!e&&!t)return{error:q};if(!n)return{error:cn};if(!e&&t){if(typeof r!="string"&&(r=cT({tournamentRecords:t,drawId:n}),!r))return{error:ha};if(e=t[r],!e)return{error:q}}let o=e&&ze({tournamentRecord:e,drawId:n});return o?.drawDefinition?{drawDefinition:o.drawDefinition,event:o.event,tournamentRecord:e,...C}:_({result:{error:br},stack:"findDrawDefinition"})}function gT(t){let{drawDefinition:e,error:r}=jo(t);return r?{error:r}:{drawDefinition:J(e)}}function _v({tournamentParticipants:t,returnParticipants:e,drawPosition:r,participant:n,drawId:o,event:i}){let s=i?.entries?.filter(({entryStatus:a})=>[Vr,Ci].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:nv,availableIndividualParticipantIds:s,availableIndividualParticipants:c,existingIndividualParticipantIds:a,existingIndividualParticipants:u,type:vg},!1,!1,!0)}}return{}}function Fi(t){let{inContextDrawMatchUps:e,targetData:r,drawDefinition:n,relevantLink:o}=t;if(o?.linkCondition===kn&&r?.matchUp?.matchUpStatus==="BYE")return!1;let{targetMatchUps:{loserMatchUp:s,winnerMatchUp:a},targetLinks:c}=r,u=s&&ur({matchUpId:s.matchUpId,inContextDrawMatchUps:e,drawDefinition:n}),p=u?.targetMatchUps?.loserMatchUp,m=u?.targetMatchUps?.loserMatchUpDrawPositionIndex,d=p?.sides[m]?.participant,l=pr(s?.matchUpStatus),f=l&&!d,g=s?.sides?.reduce((E,P)=>P?.participant?++E:E,0)??0,I=s?.winningSide&&l&&g===1,h=a?.drawPositions?.filter(Boolean).length||0;if(!I&&(s?.winningSide&&!f||a?.winningSide&&h===2&&(!a.feedRound||!pr(a?.matchUpStatus))))return!0;let S=a&&ur({matchUpId:a.matchUpId,inContextDrawMatchUps:e,drawDefinition:n}),T=u&&Fi({relevantLink:c?.loserTargetLink,targetData:u,inContextDrawMatchUps:e,drawDefinition:n});return!!(S&&Fi({targetData:S,inContextDrawMatchUps:e,drawDefinition:n})||T)}var IT={[Jn]:{policyName:"positionActionsDefault",enabledStructures:[{stages:[ct,rt],stageSequences:[1],enabledActions:[],disabledActions:[]},{stages:[],stageSequences:[],enabledActions:[xu,ia,Wp,oa],disabledActions:[]}],disbledStructures:[],otherFlightEntries:!1,activePositionOverrides:[]}};var Wg="positionAction",hT="matchUpAction";function ST({actionType:t=Wg,appliedPolicies:e,drawDefinition:r,structure:n}){let o=t===Wg&&Jn||t===hT&&er,i=t===Wg&&IT||t===hT&&IP,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 fD({activePositionOverrides:t,activeDrawPositions:e,action:r}){return r&&t.includes(r)?!0:!e.length}function TT({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 qn({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 gD="replaceTieMatchUpParticipantId",ID="assignTieMatchUpParticipantId",yT="removeTieMatchUpParticipantId",hD="assignMatchUpSideParticipant",xv="removeMatchUpSideParticipant",SD="substituteParticipant",ET="REMOVE_SUBSTITUTION",TD="REPLACE_PARTICIPANT",jg="REMOVE_PARTICIPANT",AT="setMatchUpStatus",UT="SUBSTITUTION",yD="SCHEDULE",oV="PENALTY",PT="REFEREE",ED="STATUS",DT="START",AD="SCORE";var wv={REPLACE_TEAM_POSITION_METHOD:gD,ASSIGN_TEAM_POSITION_METHOD:ID,REMOVE_TEAM_POSITION_METHOD:yT,REPLACE_PARTICIPANT:TD,SUBSTITUTION_METHOD:SD,REMOVE_SUBSTITUTION:ET,REMOVE_PARTICIPANT:jg,SCHEDULE_METHOD:AT,SUBSTITUTION:UT,SCHEDULE:yD,PENALTY:oV,REFEREE:PT,STATUS:ED,SCORE:AD,START:DT,END:"END"};function Lv({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=en(o.gender)&&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||To(S)||L.sex===S||en(S)&&!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(Ia)(I)&&!P?.length||de(Gi)(I)&&(P?.length??0)<2)||!c&&(de(Ia)(I)&&(P?.length??0)<2||de(Gi)(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:ID,availableParticipants:b,type:Ms,payload:{participantId:void 0,tieMatchUpId:u,sideNumber:c,drawId:m}}),P?.length&&(!he(p)||d?.substitutions?.length)&&l.push({method:yT,type:jg,existingParticipantIds:P,payload:{participantId:void 0,tieMatchUpId:u,drawId:m}}),b?.length&&(!c&&P?.length||c&&d?.participant)&&l.push({availableParticipantIds:R,method:gD,availableParticipants:b,type:TD,existingParticipantIds:P,payload:{existingParticipantId:void 0,participantId:void 0,tieMatchUpId:u,drawId:m}}),qn({policyActions:i,action:ET})&&d?.substitutions?.length){let F=d.participant?.participantType===Et&&[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:yT,type:ET,substitutedParticipantIds:w,payload:{participantId:void 0,tieMatchUpId:u,drawId:m}})}let O=t?.[er],v=O?.substituteWithoutScore,x=O?.substituteAfterCompleted;if(qn({policyActions:i,action:UT})&&r.length===2&&(!c&&P?.length||c&&d?.participant)&&(v||he(p))&&(x||p.matchUpStatus&&!ae.includes(p.matchUpStatus))&&E?.length&&N.length){let F=E.map(St);l.push({info:"list of team players available for substitution",method:SD,availableParticipantIds:D,existingParticipantIds:F,availableParticipants:N,existingParticipants:E,type:UT,payload:{substituteParticipantId:void 0,existingParticipantId:void 0,sideNumber:c,matchUpId:u,drawId:m}})}return l}function Fv({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===Ms)?.availableParticipantIds,f=i?.[Jn]?.otherFlightEntries,g=i?.[Jn]?.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}=Xh({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===on&&UD({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&&![mo,Vr,Ci].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:ev,availableAlternatesParticipantIds:P,type:_g,availableAlternates:A})}:{}}function UD({restrictQualifyingAlternates:t,structure:e,entry:r}){let{stage:n}=e;if(!r.entryStage||r.entryStage===n||n===ct&&!t||r.entryStage===rt&&n===qe)return!0}function kv({eventEntries:t,structure:e}){let r=o=>o.entryStatus===on&&UD({structure:e,entry:o}),n=(o,i)=>(o.entryPosition||1/0)-(i.entryPosition||1/0);return t.filter(r).sort(n).map(St)}function Gv({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&&mi.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:hD,type:Ms,availableParticipantIds:T,participantsAvailable:y});let E=m?.entries??[],P=kv({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&&![mo,Vr,Ci].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:hD,type:on}),!he(u)&&s&&g){d.push({payload:{drawId:p,matchUpId:a,structureId:i,sideNumber:s},method:xv,type:jg});let N=w=>w.sides.map(St),D=({matchUpId:w})=>w!==u.matchUpId,M=w=>!he(w),R=u.sides?.find(w=>w.sideNumber!==s)?.participantId,O=l.filter(({roundNumber:w})=>w!==u.roundNumber).filter(D).map(N),v=[R,...O.filter(w=>w.includes(g)).flat()].filter(Boolean),x=w=>!v.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:ov,type:Yp,swappableParticipants:w})}}return d}function Bd(t){if(!t)return{error:B};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&&kt(t.tournamentId)&&t.tournamentRecords?.[t.tournamentId]);if(!u)return{error:q};if(!c||!kt(c))return{error:sr};if(a&&![1,2].includes(a))return _({result:{error:B},context:{sideNumber:a}});if(!e){let Q=(ye({tournamentRecord:u}).matchUps??[]).find(ot=>ot.matchUpId===c);r=(u?.events??[]).find(ot=>ot.eventId===Q?.eventId);let ut=(r?.drawDefinitions??[]).find(ot=>ot.drawId===Q?.drawId);ut&&(e=ut)}if(!e)return{error:Z};let p=Ft({withIndividualParticipants:!0,tournamentRecord:u}).participants,{drawId:m}=e,{matchUp:d,structure:l}=Vt({drawDefinition:e,matchUpId:c,event:r});if(!d)return{error:we};let f=Tt({tournamentRecord:u,drawDefinition:e,structure:l,event:r}).appliedPolicies??{};Object.assign(f,o??{});let g=f?.[Jn]?.otherFlightEntries,I=f?.[er]??Ps[er],{enabledStructures:h}=ST({actionType:hT,appliedPolicies:f,drawDefinition:e,structure:l}),{policyActions:S}=TT({enabledStructures:h,drawDefinition:e,structure:l}),T=t.matchUpsMap??Pe({drawDefinition:e}),y=t.inContextDrawMatchUps??ie({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}=Ie({structure:l}),{structureId:D}=l??{},M=[];if(!D)return{validActions:M};let R=cr({structure:l}),b=!!d.collectionId;if(R&&!b){let z=Gv({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 O=Do({drawDefinition:e,structure:l}),v=U?.filter(z=>z.participantId).map(z=>z.drawPosition),x=U?.filter(z=>z.bye).map(z=>z.drawPosition),F=d.matchUpStatus==="BYE"||!b&&d.drawPositions?.reduce((z,Q)=>x?.includes(Q)||z,!1);if(F)return{validActions:M,isByeMatchUp:F};qn({policyActions:S,action:PT})&&M.push({type:PT,payload:{matchUpId:c}});let w=!Oa({matchUpStatus:d.matchUpStatus}),L=f?.scoring?.structures,k=l?.stage&&L?.stage&&L?.stage[l.stage],G=l?.stageSequence&&k?.stageSequence&&k.stageSequence[l.stageSequence],K=!(f?.scoring?.requireAllPositionsAssigned||k?.requireAllPositionsAssigned||G?.requireAllPositionsAssigned)||N,Y=d.sides&&d.sides.filter(z=>z?.participantId).length===2,j=d.matchUpStatus&&[oe,be].includes(d.matchUpStatus),V=ur({inContextDrawMatchUps:y,drawDefinition:e,matchUpId:c}),$=Fi({inContextDrawMatchUps:y,drawDefinition:e,targetData:V}),W=(E?.drawPositions?.length===2&&E.drawPositions.every(z=>v?.includes(z))&&E?.sides?.length===2&&E.sides.every(({participantId:z})=>z)||Y)&&!(j&&$),it={method:zS,type:ia,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:AT,type:yD}),qn({policyActions:S,action:ia})&&(P?.participant||!a&&A?.length)&&M.push(it),w&&W&&M.push({type:ED}),K&&W){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:AT,type:AD,payload:ut}),qn({policyActions:S,action:DT})&&M.push({type:DT}),qn({policyActions:S,action:"END"})&&M.push({type:"END"})}if(b&&E){let z=Lv({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:O,validActions:M,isDoubleExit:j,...C}}function Bv({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===zi&&(d?.length!==1||l?.length!==1),E={};if(y){let{matchUps:N}=yt({drawDefinition:s,structure:u,event:m}),{initialRoundNumber:D}=Es({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}=Mu({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:wg,method:rv,availableLuckyLosers:I,availableLuckyLoserParticipantIds:f,willDisableLinks:r,payload:{drawId:p,structureId:c,drawPosition:a}}}:{}}function Hv({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?.[Vn]?.validSeedPositions?.ignore;if(y||({unplacedSeedParticipantIds:h,unplacedSeedAssignments:S,unfilledPositions:T}=xS({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:av,type:"BYE"}),i&&y){let E=s.map(D=>D.participantId).filter(Boolean),P={structureIds:t},{completedMatchUps:A}=Zs({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:YP,type:Ms,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(iV),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:YP,type:Ms,availableParticipantIds:E,participantsAvailable:P}))}return{validAssignmentActions:I}}function iV(t,e){return t.bye||Nc(t.seedValue)<Nc(e.seedValue)||t.seedValue&&!e.seedValue?-1:(t.seedNumber||0)-(e.seedNumber||0)}function Wv({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?.[Jn],g=!f?.disableRoundRestrictions&&t[s],I=f?.requireCompletedStructures,{sourceStructureIds:h,relevantLinks:S}=vu({targetRoundNumber:g,linkType:Xn,drawDefinition:i,structureId:a})||{};h?.length&&d.push(...h);let{sourceStructureIds:T,relevantLinks:y}=vu({targetRoundNumber:g,linkType:Fn,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=Do({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==="BYE"&&D.sides?.find(({participantId:b})=>b);if(M||R){let{participantId:b,participant:O}=M||R||{};b&&!l.includes(b)&&(O&&n&&u.push(O),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=Do({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:Lo}).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:ZO,type:Wp,qualifyingParticipantIds:p,payload:{qualifyingParticipantId:void 0,drawPosition:s,structureId:a,drawId:c}})),{validAssignmentActions:m,sourceStructureIds:d}}function jv({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:KS,type:Yp,availableAssignments:N}}:{}}function MT(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&&Ft({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:_t};let d=m.structureId;if(p=va({drawDefinition:s,structureId:d}),a===void 0&&!p.isAdHoc)return{error:Fs};if(p.isAdHoc)return Bd(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}=ST({actionType:Wg,appliedPolicies:h,drawDefinition:s,structure:m}),E=S?.activePositionOverrides||[],{sourceStructureIds:P}=vu({finishingPosition:Ei,targetRoundNumber:1,linkType:Fn,drawDefinition:s,structureId:d})||{},A;P?.length&&(A=P.every(W=>Do({structureId:W,drawDefinition:s})));let U=P.length,N=P.length&&!A,{policyActions:D}=TT({enabledStructures:T,drawDefinition:s,structure:m}),M=![ct,rt].includes(m.stage)||m.stageSequence!==1,{drawId:R}=s,b=[],{assignedPositions:O,positionAssignments:v}=Ie({structure:m}),x=O?.find(W=>W.drawPosition===a),F=!!x;if(!v?.map(W=>W.drawPosition)?.includes(a))return{error:Ls};let{stage:L,stageSequence:k}=m,G=[L];L===qe&&G.push(rt),L===rt&&G.push(qe);let H=bi({entryStatuses:mi,provisionalPositioning:o,drawDefinition:s,stageSequence:k,structureId:d,stages:G}),K=wi({drawDefinition:s,stages:G}).assignedParticipantIds??[],Y=H.filter(W=>!K.includes(W.participantId)).map(W=>W.participantId),j=I.includes(a),V=g.includes(a);if(y)return{info:"Actions Disabled for structure",isActiveDrawPosition:V,isDrawPosition:!0,hasPositionAssigned:F,validActions:[],isByePosition:j};if(qn({policyActions:D,action:Ms})&&!V&&v&&!N&&(!x||j)){let{validAssignmentActions:W}=Hv({positionSourceStructureIds:P,unassignedParticipantIds:Y,possiblyDisablingAction:M,isWinRatioFedStructure:U,tournamentParticipants:u,positionAssignments:v,returnParticipants:n,appliedPolicies:h,drawDefinition:s,isByePosition:j,drawPosition:a,structureId:d,event:c});W?.forEach(it=>b.push(it))}if(qn({policyActions:D,action:Wp})&&!V){let{validAssignmentActions:W}=Wv({drawPositionInitialRounds:l,tournamentParticipants:u,positionAssignments:v,returnParticipants:n,appliedPolicies:h,drawDefinition:s,drawPosition:a,structureId:d,drawId:R});W?.forEach(it=>b.push(it))}let{participantId:$}=x||{},X=$&&u.find(W=>W.participantId===$);if(x){qn({policyActions:D,action:QS})&&!V&&(b.push({type:QS,method:jP,payload:{drawId:R,structureId:d,drawPosition:a},willDisableLinks:M}),j||b.push({type:xg,method:tv,payload:{drawId:R,structureId:d,drawPosition:a},willDisableLinks:M}),qn({policyActions:D,action:"BYE"})&&!j&&b.push({type:"BYE",method:jP,payload:{drawId:R,structureId:d,drawPosition:a,replaceWithBye:!0},willDisableLinks:M}));let W=m.stage===ct||m.stage===rt&&m.stageSequence===1;if(!j&&fD({activePositionOverrides:E,activeDrawPositions:g,action:oa})&&qn({policyActions:D,action:oa})&&Vp({drawDefinition:s,structureId:d,drawPosition:a})&&W){let{seedAssignments:it}=sn({returnAllProxies:!0,drawDefinition:s,structure:m}),{seedNumber:z,seedValue:Q}=it?.find(ut=>ut.participantId===$)??{};b.push({type:oa,method:cv,participant:X,seedNumber:z,payload:{drawId:R,structureId:d,participantId:$,seedValue:Q}})}if(!j&&fD({activePositionOverrides:E,activeDrawPositions:g,action:jp})&&qn({policyActions:D,action:jp})&&Vp({drawDefinition:s,structureId:d,drawPosition:a})&&W){let{seedAssignments:it}=sn({returnAllProxies:!0,drawDefinition:s,structure:m}),{seedNumber:z}=it?.find(Q=>Q.participantId===$)??{};b.push({method:sv,type:jp,participant:X,seedNumber:z,payload:{participantId:$,structureId:d,drawId:R}})}if(!j&&$){if(qn({policyActions:D,action:ia})){let it={type:ia,method:zS,participant:X,payload:{penaltyCode:void 0,penaltyType:void 0,participantIds:[],notes:void 0,drawId:R}};b.push(it)}if(qn({policyActions:D,action:xu})){let it={type:xu,method:iv,participant:X,payload:{participantId:$,otherName:void 0}};b.push(it)}}if(qn({policyActions:D,action:Yp})){let{validSwapAction:it}=jv({possiblyDisablingAction:M,tournamentParticipants:u,inactiveDrawPositions:f,activeDrawPositions:g,positionAssignments:v,returnParticipants:n,byeDrawPositions:I,drawDefinition:s,isByePosition:j,drawPosition:a,structureId:d,structure:m,drawId:R});it&&b.push(it)}}if(qn({policyActions:D,action:_g})&&!N){let{validAlternatesAction:W}=Fv({possiblyDisablingAction:M,tournamentParticipants:u,positionAssignments:v,activeDrawPositions:g,returnParticipants:n,appliedPolicies:h,drawDefinition:s,drawPosition:a,validActions:b,structureId:d,structure:m,drawId:R,event:c});W&&b.push(W)}if(qn({policyActions:D,action:wg})&&!N&&!V&&v){let{validLuckyLosersAction:W}=Bv({sourceStructuresComplete:A,possiblyDisablingAction:M,isWinRatioFedStructure:U,tournamentParticipants:u,activeDrawPositions:g,positionAssignments:v,drawDefinition:s,drawPosition:a,structureId:d,structure:m,drawId:R});W&&b.push(W)}if(X?.participantType===ft&&qn({policyActions:D,action:vg})){let{validModifyAssignedPairAction:W}=_v({tournamentParticipants:u,returnParticipants:n,drawPosition:a,participant:X,drawId:R,event:c});W&&b.push(W)}return{isActiveDrawPosition:V,isDrawPosition:!0,hasPositionAssigned:F,isByePosition:j,validActions:b,...C}}function Bu({policyDefinitions:t,appliedPolicies:e,drawType:r}){let n=t?.[Xm]?.drawTypeCoercion,o=e?.[Xm]?.drawTypeCoercion;return(typeof n=="boolean"?n:void 0)??(r&&n?.[r])??(typeof o=="boolean"?o:void 0)??(r&&o?.[r])??!0}var RT=({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:zl}});let{qualifierPositions:n}=Ie({structure:r});return tt(0,n.length).sort(()=>Math.random()-.5)};function CT({structureId:t,drawDefinition:e}){if(!e)return{error:Z};if(!kt(t))return{error:B};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([yi,Nn,Sp,Ti],n).length;return{...C,valid:o}}function zp({tournamentRecord:t,drawDefinition:e,stage:r=rt,structureId:n,structure:o}){if(!t)return{error:q};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:Pr};let{error:i,positionAssignments:s}=Ct({drawDefinition:e,structureId:n,structure:o});return{positionAssignments:s??[],structureId:o?.structureId,error:i}}function bT({participantsCount:t,participantCount:e}){if(t=t??e,!t)return{error:B};let r=us(t);return r?{drawSize:r}:_({result:{error:B},stack:"getEliminationDrawSize",context:{participantsCount:t}})}function Hu(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=Go({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:B},context:{participantsCount:u},stack:c});if(o&&!p)return _({result:{error:UA},stack:c});if(isNaN(n))if(u)({drawSize:n}=bT({participantsCount:u}));else return _({result:{error:Za},stack:c});let m=o&&u||n;if(m&&m>n)return{error:of};let d=r?.[Vn];if(!d)return{error:pA};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:KE}}function Hd({consideredEntries:t,policyDefinitions:e,tournamentRecord:r,appliedPolicies:n,participantMap:o,enforceGender:i,participants:s,event:a}){if((!s||!o)&&r&&({participants:s,participantMap:o}=Ft({tournamentRecord:r})),!s)return{error:ec};if(!Array.isArray(s))return{error:B};if(!a)return{error:Ot};let c=e?.[er]??n?.[er]??Ps[er],u=(i??c?.participants?.enforceGender)!==!1,{eventType:p,gender:m}=a,d=p===Ko,l=p===Or&&wt||d&&ft||Et,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=sV({participant:S,participantType:l,eventType:p,entryStatusMap:f}),y=aV({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:nA,invalidParticipantIds:S}}return{...C,valid:!0}}function sV({participant:t,participantType:e,eventType:r,entryStatusMap:n}){let o=n[t.participantId],i=r&&[Ko,Or].includes(r)&&t.participantType===Et&&(ta(o)||o===mo);return t.participantType!==e&&!i}function aV(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||To(n)||Dn(n)&&yr(a[0])===yr(n)||en(n)&&(a.length===1&&e.individualParticipantIds?.length===1||a.length===2),u=e?.person?.sex,p=!e?.person||!n||en(n)||To(n)||Dn(n)&&yr(u)===yr(n);return!s||c&&p}function OT({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=Rm(N.drawSize||N.participantsCount),{qualifyingRoundNumber:M,structureOptions:R,matchUpFormat:b,structureName:O,structureId:v,drawType:x}=N,F=N.matchUpType,w=N.qualifyingPositions||cV({drawSize:D,qualifyingRoundNumber:M}),L,k,G;if(!It(D))return _({result:{error:Za},stack:c});let H=e.length>1?`${h}-`:"",K=T.length>1||H?y:"",Y=O||(H||K?`${Qe(ct)} ${H}${K}`:Qe(ct));if(x===On){let{structures:j,groupCount:V,maxRoundNumber:$}=xa({structureName:N.structureName||Y,structureId:v||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=V,L=$,k=j[0],I=[1]}else({drawSize:D,matchUps:G,roundLimit:L}=xn({qualifyingRoundNumber:M,qualifyingPositions:w,matchUpType:F,drawSize:D,idPrefix:i,isMock:s,uuids:a})),k=yn({structureName:N.structureName||Y,structureId:v||a?.pop(),qualifyingRoundNumber:L,hasExistingDrawDefinition:t,stage:ct,qualifyingOnly:n,matchUpFormat:b,stageSequence:y,matchUpType:F,roundLimit:L,tieFormat:o,matchUps:G}),h&&At({extension:{name:vn,value:h},element:k}),E=G?.filter(j=>j.roundNumber===L)?.length||0;if(y>1){let{link:j}=La({sourceStructureId:A,sourceRoundNumber:P,targetStructureId:k.structureId,finishingPositions:U===Fn?[1]:void 0,linkType:U});m.push(j),f+=(D||0)-E}else f+=D||0;U=x===On?Fn:Xn,A=k.structureId,P=L,o&&(G=yt({structure:k})?.matchUps||[],G?.forEach(j=>{let{tieMatchUps:V}=Li({tieFormat:o,matchUp:j,isMock:s});Object.assign(j,{tieMatchUps:V,matchUpType:F})})),p.push(k),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 cV({drawSize:t,qualifyingRoundNumber:e}){let r=t,n=0;for(;n<e;)r=Math.floor(r/2),n+=1;return r}function vT(t){let{drawTypeCoercion:e,enforceMinimumDrawSize:r}=t,n=dt(t.drawSize),o=e&&t.drawType!==Fr&&(typeof e=="boolean"||e<=2)&&n===2&&yo||t.drawType||yo,i=DU.includes(o);if(n&&i){if(e&&(typeof e=="boolean"&&n<4||n<=e))o=yo;else if(n<4&&r)return{..._({context:{enforceMinimumDrawSize:r,drawSize:n,drawType:o},result:{error:np},stack:"getCoercedDrawType"}),drawType:o}}return{drawType:o}}function Yv(t){let{drawDefinition:e,structureOptions:r,requireSequential:n}=t,o={structureName:Qe(rt),...t,stage:rt},{structures:i,groupCount:s,groupSize:a}=xa(o);if(s<1)return{error:GA};let c=r?.playoffGroups||[{finishingPositions:[1],structureName:Qe(fe)}],[u]=i,{structures:p,links:m}=rT({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 qv({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?Nn:yi,f=1+m;return{linkType:so,source:{roundNumber:f,structureId:t.structureId},target:{feedProfile:l,roundNumber:p,structureId:e.structureId}}}),c={linkType:Xn,source:{roundNumber:s,structureId:e.structureId},target:{feedProfile:Nn,roundNumber:i,structureId:t.structureId}},u=[{linkType:Xn,source:{roundNumber:i,structureId:t.structureId},target:{feedProfile:Nn,roundNumber:1,structureId:r.structureId}},{linkType:so,source:{roundNumber:i,structureId:t.structureId},target:{feedProfile:Nn,roundNumber:1,structureId:r.structureId}}];return[...a,c,...u]}function $v({structureName:t,matchUpType:e,idPrefix:r,drawSize:n,isMock:o,uuids:i}){let s=[],{matchUps:a}=fi({linkFedFinishingRoundNumbers:[1],drawSize:n+1,matchUpType:e,idPrefix:r,isMock:o}),c=Ds({structureName:t||Qe(rt),structureId:i?.pop(),stageSequence:1,stage:rt,matchUpType:e,matchUps:a});s.push(c);let u=n/2,{matchUps:p}=fi({finishingPositionOffset:u,idPrefix:r&&`${r}-c`,drawSize:n-1,isConsolation:!0,matchUpType:e,isMock:o,uuids:i}),m=Ds({structureName:Qe(PU),matchUps:p,structureId:i?.pop(),stage:qe,stageSequence:2,matchUpType:e});s.push(m);let{matchUps:d}=xn({idPrefix:r&&`${r}-p1t2`,drawSize:2,matchUpType:e,isMock:o}),l=Ds({structureName:Qe(UU),matchUps:d,structureId:i?.pop(),stageSequence:3,stage:fe,matchUpType:e});s.push(l);let f=qv({mainStructure:c,consolationStructure:m,deciderStructure:l});return{structures:s,links:f,...C}}function Kv(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(Ln(s))return xn(t);let u=uV(s),p=u.shift(),m=tt(1,(p?.participantsCount||0)+1).map(I=>({drawPosition:I})),d=[],l=1;({matchUps:d}=qp({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=vd({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=ba({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 uV(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 _T(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?.[dc]||p?.[dc];t.skipRounds=t.skipRounds||s<=4&&(m?.feedFromMainFinal?0:1)||0;let d=t.structureName??e?.["0"]?.name??Qe(rt),l=()=>{let{matchUps:g}=xn(t);return{structures:[yn({stageSequence:r,structureName:d,matchUpType:i,structureId:u,tieFormat:o,matchUps:g,stage:n})],links:[],...C}};return{generators:{[Fr]:()=>({structures:[yn({finishingPosition:Ei,stageSequence:r,structureName:d,matchUps:[],matchUpType:i,structureId:u,stage:n})],links:[],...C}),[Ki]:()=>{let{matchUps:g}=Kv(t);return{structures:[yn({stageSequence:r,structureName:d,matchUpType:i,structureId:u,matchUps:g,stage:n})],links:[],...C}},[yo]:()=>l(),[su]:()=>$v(t),[ou]:()=>Rc({...t,roundOffsetLimit:3,playoffAttributes:e??Of}),[iu]:()=>Rc({...t,roundOffsetLimit:2,playoffAttributes:e??vf}),[fe]:()=>Rc(t),[Ea]:()=>{let{matchUps:g}=fi({drawSize:s,uuids:a,matchUpType:i});return{structures:[yn({stageSequence:r,structureName:d,matchUpType:i,structureId:u,stage:rt,tieFormat:o,matchUps:g})],links:[],...C}},[Tp]:()=>JS(t),[au]:()=>bc({...t,feedRounds:1,fmlc:!0}),[AU]:()=>bc({...t,feedRounds:1}),[bh]:()=>bc({...t,feedsFromFinal:1}),[Oh]:()=>bc({...t,feedsFromFinal:2}),[vh]:()=>bc({...t,feedsFromFinal:3}),[yp]:()=>bc(t),[bf]:()=>tT(t),[On]:()=>xa(t),[Eo]:()=>Yv(t)}}}function Wd(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??Bu({appliedPolicies:n,drawType:t.drawType}),d="generateDrawStructuresAndLinks",l=vT({drawType:t.drawType,enforceMinimumDrawSize:e,drawTypeCoercion:m,drawSize:p});if(l.error)return l;let f=l.drawType,g=[],I=[],h=t?.matchUpType??Lt,S=s?.structures?.filter(({stage:K})=>K===ct);S&&g.push(...S);let T=S?.map(({structureId:K})=>K),y=s?.structures?.find(({stage:K,stageSequence:Y})=>K===rt&&Y===1),E=s?.links?.filter(K=>K.target.structureId===y?.structureId&&T?.includes(K.source.structureId)),P=(K,Y)=>{if(K.linkType===Fn&&Y?.structures){let j=K.source.finishingPositions||[];return Y.structures.length*j.length}else if(K.linkType===Xn&&Y?.matchUps?.length){let j=K.source.roundNumber;return Y.matchUps.filter(({roundNumber:$})=>$===j).length}},A=S?.map(K=>{let Y=E?.find(W=>W.target.structureId===K.structureId),j=Ct({structure:K})?.positionAssignments?.length??0;if(!Y)return j;let V=Y?.source.structureId,$=s.structures?.find(W=>W.structureId===V),X=P(Y,$)||0;return j-X}).filter(Boolean).reduce((K,Y)=>K+Y,0),U=E?.map(K=>{let Y=K.source.structureId,j=S?.find(V=>V.structureId===Y);return P(K,j)}).filter(Boolean).reduce((K,Y)=>K+Y,0),N=!!(y&&!y?.matchUps?.length);if(S?.length&&!N)return{error:ZI};let D=!S?.length&&t.qualifyingProfiles,M=D?.length&&OT({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:O}=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 v=f!==Fr&&(!p||p<2||!i&&![Ea,Ki].includes(f)&&([Eo,On].includes(f)&&p<3||![On,Eo].includes(f)&&!Ln(p)));if(v&&!R)return _({context:{drawSize:p,invalidDrawSize:v},result:{error:np},stack:d});let{generators:x,error:F}=_T(t);if(F)return{error:F};let w=x[f];if(!w)return{error:ql};let L=w?.();if(L.error)return L;let{structures:k,links:G}=L;if(k?.length){let K=k.find(({stage:Y,stageSequence:j})=>Y===rt&&j===1);if(y&&K){if(N){let Y=K.structureId;if(K.structureId=y.structureId,G?.length)for(let j of G)j.source.structureId===Y&&(j.source.structureId=y.structureId),j.target.structureId===Y&&(j.target.structureId=y.structureId)}else if(!r)return{error:ZI}}g.push(...k)}g.sort(Ni),G?.length&&I.push(...G);let H=L.structures.find(({stage:K,stageSequence:Y})=>K===rt&&Y===1);for(let K of b||[]){let{finalQualifyingRoundNumber:Y,finalQualifyingStructureId:j,roundTarget:V,finishingPositions:$,linkType:X}=K,W=H&&La({targetStructureId:H.structureId,sourceStructureId:j,sourceRoundNumber:Y,finishingPositions:$,targetEntryRound:V,linkType:X})?.link;if(W?.error)return W;W&&I.push(W)}return E&&I.push(...E),{...C,qualifyingResult:{qualifyingDrawPositionsCount:R,qualifiersCount:O},structures:g,links:I}}function jd(t){let{modifyOriginal:e=!0,stageSequence:r=1,isMock:n}=t||{},o="generateDrawTypeAndModifyDrawDefinition";if(!t.drawDefinition)return _({result:{error:Z},stack:o});let i=e?t.drawDefinition:J(t.drawDefinition,!1,!0),{tieFormat:s,matchUpType:a}=t;if(s){let T=ar({tieFormat:s});if(T.error)return T}s=or(s??We({drawDefinition:i})?.tieFormat),a=a??(i.matchUpType||Lt),t.tieFormat=s,t.matchUpType=a;let c=Fp({drawDefinition:i,stage:rt});t.drawSize=t.drawSize??c,!c&&t.drawSize&&Hp({drawSize:t.drawSize,drawDefinition:i,stageSequence:r,stage:rt});let u=Pe({drawDefinition:i}).drawMatchUps.map(Ue),p=Wd(t);if(p.error)return _({result:p,stack:o});let{structures:m,links:d,qualifyingResult:l}=p;i.structures=m,i.links=d;let f=Math.max(t.qualifiersCount??0,l?.qualifiersCount||0);if(l?.qualifyingDrawPositionsCount&&!Fp({stage:ct,drawDefinition:i})){let y=Hp({drawSize:l.qualifyingDrawPositionsCount,stage:ct,drawDefinition:i});if(y.error)return y}if(f){let T=$S({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}=ie({drawDefinition:i});s&&I?.forEach(T=>{if(!u.includes(T.matchUpId)){let{tieMatchUps:y}=Li({tieFormat:s,matchUp:T,isMock:n});Object.assign(T,{tieMatchUps:y,matchUpType:a})}});let{inContextDrawMatchUps:S}=rs({drawDefinition:i,matchUpsMap:h});return bt({tournamentId:t.tournamentRecord?.tournamentId,drawDefinition:i}),{inContextDrawMatchUps:S,drawDefinition:i,matchUpsMap:h,...C,structures:m,matchUps:I,links:d}}function xc(t){let{removePriorValues:e,tournamentRecord:r,participantId:n,scaleItem:o}=t,i,s;if(!zv({scaleItem:o}))return{error:rc};if(n&&Array.isArray(r.participants)&&(s=r.participants.find(a=>a.participantId===n),s)){if(s.participantType===Ar&&o?.eventType!==Or)return{error:rc};let a=Qv({removePriorValues:e,participant:s,scaleItem:o});if(a.error)return a;i=!a.valueChanged;let{topics:c}=Lr();c.includes(rr)&<({topic:rr,payload:{tournamentId:r.tournamentId,participants:[s]}})}return i&&{...C,info:ff,existingValue:o?.scaleValue}||s&&{...C,newValue:o?.scaleValue}||{error:re}}function DD(t){let{scaleItemsWithParticipantIds:e=[],removePriorValues:r,tournamentRecord:n,auditData:o,context:i}=t;if(!n)return{error:q};if(!n.participants)return{error:ec};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(zv({scaleItem:l}))Array.isArray(a[d])||(a[d]=[]),a[d].push(l);else return{error:rc}}for(let m of n.participants){let{participantId:d}=m||{};if(Array.isArray(a[d]))for(let l of a[d]){if(m.participantType===Ar&&l?.eventType!==Or)return _({context:{participantId:d,scaleItem:l,participantType:m.participantType},info:"Invalid participantType for eventType",result:{error:rc}});Qv({participant:m,scaleItem:l,removePriorValues:r}),c.push(m),s++}}let u=s?void 0:Bs,{topics:p}=Lr();if(p.includes(rr)&&s&<({topic:rr,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:Yf,itemValue:l};if(f&&(g.itemSubTypes=f),d||m){let{drawDefinition:I,event:h}=ze({tournamentRecord:n,eventId:m,drawId:d});d&&Og({drawDefinition:I,timeItem:g}),m&&is({event:h,timeItem:g})}else _c({tournamentRecord:n,timeItem:g})}}return o&&p.includes(Mi)&<({topic:Mi,payload:o}),nt({...C,modificationsApplied:s,info:u})}function zv({scaleItem:t}){let e=t&&Object.keys(t),r=["scaleType","eventType","scaleName"];return!!(r.filter(o=>e?.includes(o)).length===r.length)}function Qv({removePriorValues:t,participant:e,scaleItem:r}){if(!e)return{error:Wi};let n=r&&Object.keys(r),o=["scaleType","eventType","scaleName"];if(!(o.filter(p=>n.includes(p)&&r[p]).length===o.length))return{error:rc};let s=new Date().toISOString();e.timeItems||(e.timeItems=[]);let{scaleItem:a}=Po({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=[Pi,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 Yg(t){let{tournamentRecord:e,modifiedScaleValues:r,removePriorValues:n}=t,o=et(t,[{[ne]:!0},{modifiedScaleValues:!0,[He]:zr}]);if(o.error)return o;for(let i in r){let s=xc({scaleItem:r[i],removePriorValues:n,tournamentRecord:e,participantId:i});if(s.error)return s}return{...C}}function wc(t){let{tournamentRecord:e,scaleAttributes:r,participantId:n}=t,o=t.tournamentRecords||e&&{[e.tournamentId]:e}||{};if(!n)return{error:se};let{participant:i,tournamentId:s}=Uo({tournamentRecords:o,tournamentRecord:e,participantId:n});return i?{...Po({participant:i,scaleAttributes:r}),tournamentId:s}:{error:re}}var pV=(t=0)=>250/Math.pow(t+5,.4),mV=()=>1;function dV(t=3,e=2){let r=t/e;return isNaN(r)?Yd.kDefault():r}var Yd={nSpread:400,diffThreshold:.125,kCalc:pV,kMultiplier:dV,kDefault:mV};function xT(t){let{winnerRating:e,loserRating:r}=t,{ratings:n=je,winnerCountables:o=1,loserCountables:i=0,ratingType:s="ELO",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=Fu({targetRange:je["ELO"].range,sourceRange:l,value:m?p[0]-e:e}),I=Fu({targetRange:je["ELO"].range,sourceRange:l,value:m?p[0]-r:r}),h=(x,F)=>1/(1+Math.pow(10,(F-x)/Yd.nSpread)),S=h(g,I),T=h(I,g),y=Yd.kCalc(o),E=Yd.kCalc(i),P=Yd.kMultiplier(a,c),A=g+P*y*(1-S),U=I+P*E*(0-T),N=Fu({sourceRange:je["ELO"].range,value:A,targetRange:l}),D=Fu({sourceRange:je["ELO"].range,value:U,targetRange:l}),M=m?p[0]-N:N,R=parseFloat(M.toFixed(d)),b=m?p[0]-D:D,O=parseFloat(b.toFixed(d)),v=Math.max(...p)?Math.abs(e-r)/Math.max(...p):0;return(N>D&&v>Yd.diffThreshold||R<0||O<0)&&(R=e,O=r),{newWinnerRating:R,newLoserRating:O}}var Xv=t=>t?.reduce((e,r)=>(r.winningSide&&(e[r.winningSide-1]+=1),e),[0,0])||[0,0];function wT(t){let e=et(t,[{[ne]:!0},{matchUpIds:!0,[He]:Be,[In]:ps},{ratingType:!1,[tr]:S=>je[S]}]);if(e.error)return e;let{updateParticipantRatings:r,removePriorValues:n=!0,tournamentRecord:o,ratingType:i="ELO",refreshDynamic:s,considerGames:a,drawDefinition:c,matchUpIds:u,asDynamic:p}=t,m=je[i],{accessor:d}=m,l={},f=(t.matchUps||s&&nr({drawDefinition:c,tournamentRecord:o,inContext:!0,matchUpFilters:{matchUpStatuses:ae}}).matchUps||ye({matchUpFilters:{matchUpIds:u,matchUpStatuses:ae},tournamentRecord:o,inContext:!0}).matchUps)??[],g=`${i}.${Qm}`,I=p?g:i;f.sort(xi);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:Ui},D={scaleName:g,eventType:U,scaleType:Ui},M=Object.assign({},...(P??[]).map(k=>{let{sideNumber:G,participant:H}=k;return G&&{[G]:[H?.participantId,...H?.individualParticipantIds??[]].filter(Boolean).flat()}})),R=Object.assign({},...Object.values(M).flat().map(k=>{let G=l[k],K=!s||G?wc({scaleAttributes:D,tournamentRecord:o,participantId:k}).scaleItem:void 0,Y=wc({tournamentRecord:o,scaleAttributes:N,participantId:k}).scaleItem,j=d?{[d]:void 0}:void 0;return k&&{[k]:K??Y??{scaleName:I,eventType:U,scaleDate:T,scaleType:Ui,scaleValue:j}}})),b=y?Ne(y):{},O=b?.bestOf||1,v=b?.setsTo||1,x=a?O&v:O,F=E?.sets&&Xv(E.sets)||A===1&&[1,0]||[0,1],w=A?M[A]:[],L=A?M[3-A]:[];for(let k of w){let G=R[k]?.scaleValue,H=typeof G=="object"?G[d]:G;for(let K of L){let Y=R[K]?.scaleValue,j=typeof Y=="object"?Y[d]:Y,V=A?F[A]:[0,0],$=A?F[3-A]:[0,0],{newWinnerRating:X,newLoserRating:W}=xT({winnerCountables:V,loserCountables:$,maxCountables:x,winnerRating:H,loserRating:j,ratingType:i}),it=d?{...G,[d]:X}:X,z=d?{...Y,[d]:W}:W;R[k].scaleValue=it,R[K].scaleValue=z,R[k].scaleName=I,R[K].scaleName=I}}Object.assign(l,R),r&&Yg({tournamentRecord:o,modifiedScaleValues:l,removePriorValues:n})}let h=f.map(({matchUpId:S})=>S);return{...C,modifiedScaleValues:l,outputScaleName:I,processedMatchUpIds:h}}function Wu(t){let{matchUpIds:e=[],drawDefinition:r,roundNumber:n,newRound:o,isMock:i,event:s}=t;if(typeof r!="object")return{error:Z};let{participantIdPairings:a,matchUpsCount:c}=t,u=Vd(t);if(u.error)return _({result:u});let{lastRoundNumber:p,availableMatchUpsCount:m=0,roundMatchUpsCount:d=0}=u;if(!c)o?c=d:m>0&&(c=m);else if(c>d&&t.restrictMatchUpsCount!==!1)return _({result:{error:B,info:"matchUpsCount error",context:{roundMatchUpsCount:d}}});if(a&&!Array.isArray(a)||c&&!It(c)||e&&!Array.isArray(e)||!a&&!c)return{error:B,info:"matchUpsCount or pairings error"};if(c&&t.restrictMatchUpsCount!==!1&&c>32)return{error:B,info:"matchUpsCount must be less than 33"};if(n&&!t.ignoreLastRoundNumber&&n-1>(p||0))return{error:B,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)??Nt();return{roundNumber:l,matchUpStatus:Qt,matchUpId:E,sides:y}});if(g?.length){let I=We({drawDefinition:r,event:s})?.tieFormat;I&&g.forEach(h=>{let{tieMatchUps:S}=Li({tieFormat:I,matchUp:h,isMock:i});Object.assign(h,{tieMatchUps:S,matchUpType:Wt})})}return{roundNumber:l,matchUpsCount:g?.length??0,matchUps:g,...C}}function Zv({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=Jv({actorsCount:s.length,valueSortedPairings:e,pairingValueMap:i,deltaObjects:o,valueObjects:n}),u=[ND(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=Ga(S,y.opponent);if(!I.includes(E)){let P=Jv({stipulated:[[S,y.opponent]],actorsCount:s.length,valueSortedPairings:e,pairingValueMap:i,deltaObjects:o,valueObjects:n});if(!u.includes(ND(P))){u.push(ND(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=tn(a);return{candidatesCount:d,deltaCandidate:m,maxIterations:t,iterations:l,candidate:h}}function ND(t){return t.participantIdPairings.map(({participantIds:e})=>e.sort().join("|")).sort().join("/")}function Jv({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=Ga(l,f),I=r[g];a.push({participantIds:d,value:I}),c+=r[g]}),Ae(t,i).map(d=>Tr(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=Ga(f,g),h=n[I];return h>d?h:d},0),m=a.reduce((d,l)=>{let[f,g]=l.participantIds,I=Ga(f,g),h=o[I];return h>d?h:d},0);return{value:c,participantIdPairings:a,maxDelta:p,maxDiff:m}}function Ga(t,e){return[t,e].sort(Cu).join("|")}function MD({participantIds:t}){let e={},r=[];t.forEach(o=>{e[o]=t.filter(i=>i!==o),e[o].forEach(i=>{let s=Ga(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 t_({matchUps:t}){let e=[];for(let r of t){let n=r.sides.map(St);if(n.length===2){let[o,i]=n,s=Ga(o,i);e.includes(s)||e.push(s)}}return{encounters:e}}function e_({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=Ga(o,i);return{opponent:i,value:e[s]}}return{pairingValues:r}}var lV=0;function r_({tournamentParticipants:t,adHocRatings:e,eventType:r,scaleName:n,pairing:o}){let i=je[n]?.defaultInitialization??lV;return o.split("|").map(s=>{if(r===Kr){let a=t?.find(c=>c.participantId===s)?.individualParticipantIds;return a?a?.map(c=>e[c]||i):i*2}else return e[s]||i})}function n_(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=r_({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}=e_({possiblePairings:n,valueObjects:c}),{candidate:f,candidatesCount:g,deltaCandidate:I,iterations:h}=Zv({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 fV=100,gV=100,IV=4e3;function qd(t){let{encounterValue:e=fV,sameTeamValue:r=gV,maxIterations:n=IV,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:_t};let P=t.structure||at({drawDefinition:d,structureId:f}).structure;if(!ht(P))return{error:Si};if(!m?.length)return{error:bo};let A=[...a??[],...P?.matchUps??[]],{encounters:U}=t_({matchUps:A}),N=c?.participants??[],D={};if(u){let V=pt(P?.matchUps?P.matchUps.map(({roundNumber:X})=>X):[]),$=Math.max(...V,0);if($){let X=P?.matchUps?.filter(({roundNumber:it})=>it===$).map(({matchUpId:it})=>it),W=wT({ratingType:h??E?.category?.ratingType,updateParticipantRatings:o,tournamentRecord:c,asDynamic:!0,refreshDynamic:p,drawDefinition:d,matchUpIds:X});if(W.error)return W;W.modifiedScaleValues&&(D=W.modifiedScaleValues)}}let{valueObjects:M}=hV({tournamentParticipants:N,encounterValue:e,sameTeamValue:r,encounters:U}),{uniquePairings:R,possiblePairings:b,deltaObjects:O}=MD({participantIds:m}),v=Object.values(D).length?D:t.adHocRatings,x={tournamentParticipants:N,possiblePairings:b,participantIds:m,uniquePairings:R,drawDefinition:d,maxIterations:n,adHocRatings:v,deltaObjects:O,valueObjects:M,eventType:I,scaleName:h,structure:P,salted:y},{candidatesCount:F,participantIdPairings:w,deltaCandidate:L,iterations:k,candidate:G}=n_(x);if(!F)return{error:ap};let H,K;if(i){let V=Wu({structureId:P?.structureId,ignoreLastRoundNumber:s,participantIdPairings:w,newRound:!0,drawDefinition:d,roundNumber:l,matchUpIds:g,idPrefix:S,isMock:T,event:E});if(V.error)return V;H=V.roundNumber,K=V.matchUps}let{maxDelta:Y,maxDiff:j}=G;return{roundNumber:H,participantIdPairings:w,modifiedScaleValues:D,candidatesCount:F,deltaCandidate:L,...C,iterations:k,matchUps:K,maxDelta:Y,maxDiff:j}}function hV({encounters:t,tournamentParticipants:e,encounterValue:r,sameTeamValue:n}){let o={};for(let s of t)o[s]||(o[s]=0),o[s]+=r;let i=e?.filter(({participantType:s})=>s===wt);if(i)for(let s of i){let a=s.individualParticipantIds??[],{uniquePairings:c}=MD({participantIds:a});for(let u of c)o[u]||(o[u]=0),o[u]+=n}return{valueObjects:o}}function LT(t){let{drawType:e=yo,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=bi({stageSequence:1,drawDefinition:p,stage:m}),l=[On,su,Eo].includes(e)?d.length:us(d.length);if(!i&&e===Ea&&d.length<2||e===On&&d.length<3)return{error:np};let{tieFormat:f,matchUpType:g}=t;if(f){let R=ar({tieFormat:f});if(R.error)return R}f=or(f??We({drawDefinition:p})?.tieFormat),g=g??p.matchUpType;let{structures:I}=hn({stageSequence:1,drawDefinition:p,stage:m});if(I.length>1)return{error:iA};if(I?.[0]?.matchUps?.length)return{error:If};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=_T(t);if(T.error)return T;let y=T.generators[e];if(!y)return{error:ql};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}=Li({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&&Mc({seedingProfile:t.seedingProfile,applyPositioning:n,tournamentRecord:o,drawDefinition:p,structureId:S,placeByes:a,drawSize:l,event:u}),r&&bt({drawDefinition:p}),{links:A,structures:P,...C}}var Jg={};Xt(Jg,{addGame:()=>xD,addPoint:()=>_D,addSet:()=>LD,addShot:()=>wD,analyzeScore:()=>zg,analyzeSet:()=>qu,calculateHistoryScore:()=>bD,checkScoreHasValue:()=>he,checkSetIsComplete:()=>Jp,clearHistory:()=>vD,generate:()=>CD,generateScoreString:()=>Mo,generateTieMatchUpScore:()=>vc,getSetComplement:()=>Xg,getTiebreakComplement:()=>rm,helpers:()=>cN,isValidMatchUpFormat:()=>Nr,keyValueScore:()=>rN,mutate:()=>VD,parseMatchUpFormat:()=>Ne,parseScoreString:()=>nm,query:()=>mN,redo:()=>FD,reverseScore:()=>RD,setServingSide:()=>OD,stringifyMatchUpFormat:()=>gp,tidyScore:()=>aN,umo:()=>GD,undo:()=>kD,validateMatchUpScore:()=>uN,validateScore:()=>Qg,validateSetScore:()=>$T,validateTieFormat:()=>ar});var CD={};Xt(CD,{generateScoreString:()=>Mo,generateTieMatchUpScore:()=>vc,reverseScore:()=>RD});function Mo(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&&Ne(s),{bestOf:m,finalSetFormat:d,setFormat:l}=p??{},g=o||!(!e||!c||c===1),I=n?SV({matchUpStatus:i}):"",h=u?.sort(TV).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=V=>Jt(V?.side1Score)||Jt(V?.side2Score),U=(V=>Jt(V?.side1TiebreakScore)||Jt(V?.side2TiebreakScore))(T),N=E?.tiebreakSet||!P(T)&&U,{side1Score:D,side2Score:M,side1TiebreakScore:R,side2TiebreakScore:b}=T,O=R||(Jt(R)||U&&a?0:""),v=b||(Jt(b)||U&&a?0:"");if(N){let V=P(T)&&!U,$=V?D:O,X=V?M:v;return`[${(g?[X,$]:[$,X]).join("-")}]`}let x=U?Math.min(O,v):"",F=x===O?1:2,w=Jt(x)?`(${x})`:"",L=D||(Jt(D)||a?0:""),k=M||(Jt(M)||a?0:""),G=V=>!r&&F===V?w:"",H=`${L}${G(1)}`,K=`${k}${G(2)}`,Y=r&&U?`(${x})`:"",j=g?`${[K,H].join("-")}${Y}`:`${[H,K].join("-")}${Y}`;return["-"," "].includes(j)&&(j=""),j}}function SV({matchUpStatus:t}){let e={[Me]:"RET",[Bt]:"WO",[be]:"DF/DF",[oe]:"WO/WO",[ls]:"SUS",[vr]:"ABN",[Gt]:"DEF",[Iu]:"DR"};return t&&e[t]||""}function TV(t,e){return t.setNumber-e.setNumber}function RD(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=Mo({setTBlast:n,sets:r}),i=Mo({sets:r,reversed:!0,setTBlast:n});return{reversedScore:{sets:r,scoreStringSide1:o,scoreStringSide2:i},...C}}var VD={};Xt(VD,{addGame:()=>xD,addPoint:()=>_D,addSet:()=>LD,addShot:()=>wD,calculateHistoryScore:()=>bD,clearHistory:()=>vD,redo:()=>FD,setServingSide:()=>OD,umo:()=>GD,undo:()=>kD});function ei({matchUp:t}){let{extension:e}=mt({name:rd,element:t});if(!e)return{error:Oe};let{history:r=[],undoHistory:n=[]}=e.value;return{history:r,undoHistory:n,...C}}function bD(t){if(!t)return{error:st};let{matchUp:e,updateScore:r}=t;if(!e)return{error:mr};let n=ei({matchUp:e})?.history||[];if(!Array.isArray(n))return{error:B,info:"history is not an array"};let{matchUpFormat:o}=e;if(!o)return{error:Zl};if(!Nr({matchUpFormat:o}))return{error:Jl};let i=Ne(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:O,tiebbreakFormat:v}=M,x=U.side1Score===R&&U.side1Score===U.side2Score,F=!!M.tiebreakSet,w=F?M.tiebreakSet:v,{tiebreakTo:L,NoAD:k}=w||{},G=()=>{d=void 0,l=[0,0],f=3-f,U.side1TiebreakScore="",U.side2TiebreakScore="",U.side1PointScore="",U.side2PointScore="",h=0},H=j=>{U.winningSide=j;let{s:V,...$}=U;p.sets.push($),P=E(),A=y(),U=T(),G()},K=j=>{A.winningSide=j;let{g:V,...$}=A;U.games.push($),P=E(),A=y(),G();let X=`side${j}Score`;U[X]+=1},Y=j=>{P.winningSide=j;let{p:V,...$}=P;A.points.push($),P=E(),h=0;let X=()=>l.reduce((Q,ut)=>Q+ut)%4/4>.5?f:3-f,W=j-1;if(x||F){l[W]+=1,d=X(),U[`side${j}TiebreakScore`]=l[W],U[`side${3-j}TiebreakScore`]=l[1-W];let it=k?1:2;if(l[W]>=L&&l[W]>=l[1-W]+it)return K(j),{gameCompleted:!0}}else if(l[1-W]===4&&l[W]===3?l[1-W]-=1:l[W]+=1,U.side1PointScore=u[l[0]],U.side2PointScore=u[l[1]],l[W]===5||l[W]===4&&l[1-W]<3||O&&l[W]===4)return K(j),{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 V=3-f;Y(V)}if(S(D.p)||It(D.pointNumber)){let j=D.winningSide||D.p;if(Y(j)?.gameCompleted)continue}if(S(D.g)||It(D.gameNumber)){let j=D.winningSide||D.g;A.winningSide=j;let V=`side${j}Score`,$=`side${3-j}Score`;if(m.length&&(m.includes("p"),m=[]),K(j),U[V]===b&&U[V]-U[$]>=(O?1:2)&&(H(j),I))break}if(S(D.s)||It(D.setNumber)){let j=D.winningSide||D.s;if(H(j),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=Mo({...p,matchUpFormat:o}),p.scoreStringSide2=Mo({...p,matchUpFormat:o,reversed:!0}),f=d||f,r&&(e.score=p),{...C,servingSide:f,score:p}}function ri({undoHistory:t,history:e,matchUp:r}){return At({element:r,extension:{value:{history:e,undoHistory:t},name:rd}})}function OD({matchUp:t,sideNumber:e}){if(![1,2].includes(e))return{error:tf};let{history:r=[]}=ei({matchUp:t});return r.push({srv:e}),ri({matchUp:t,history:r})}function vD({matchUp:t}){return ri({matchUp:t})}function _D({matchUp:t,point:e}){if(!e||!t)return{error:st};if(typeof e!="object")return{error:B,context:{point:e}};let{history:r=[]}=ei({matchUp:t});return r.push(e),ri({matchUp:t,history:r})}function xD({matchUp:t,game:e}){if(typeof e!="object")return{error:B,context:{game:e}};let{history:r=[]}=ei({matchUp:t});return r.push(e),ri({matchUp:t,history:r})}function wD({matchUp:t,shot:e}){if(typeof e!="object")return{error:st};let{history:r=[]}=ei({matchUp:t});return r.push(e),ri({matchUp:t,history:r})}function LD({matchUp:t,set:e}){if(typeof e!="object")return{error:st};let{history:r=[]}=ei({matchUp:t});return r.push(e),ri({matchUp:t,history:r})}function FD({matchUp:t}){let{history:e=[],undoHistory:r=[]}=ei({matchUp:t});return r.length&&e.push(r.pop()),ri({matchUp:t,history:e,undoHistory:r})}function kD({matchUp:t}){let{history:e=[],undoHistory:r=[]}=ei({matchUp:t});return r.push(e.pop()),ri({matchUp:t,history:e,undoHistory:r})}var GD={};var cN={};Xt(cN,{keyValueScore:()=>rN,parseMatchUpFormat:()=>Ne,stringifyMatchUpFormat:()=>gp,tidyScore:()=>aN});var o_="COMPLETED";var yV="WO/WO";var FT=["RET","DEF","WO",yV,"ABN","SUS","INT"];var kT="DEFAULTED";var BD="WALKOVER";var GT="ABANDONED",VT="SUSPENDED",HD="RETIRED",BT="INTERRUPTED";var i_=[HD,kT,BD],EV="Enter Score",Rs="()",Cs="[]",WD=["up","left","shift+tab"],jD=["enter","down","tab","right"],$d="backspace",YD="r",qD="s",$D="a",KD="d",zD="w",QD="i",Kd=[YD,KD,zD,$D,qD,QD],Qp="space",HT=["[","("],zd=[...WD,...jD,Qp,"]"],s_="-",AV="/",aa=s_,gi=s_,XD=[AV],a_=0,UV=["=","+","num_1","num_2","shift+=","shift+-"],sa=["0","1","2","3","4","5","6","7","8","9"].concat(Kd),c_=sa.map(t=>`shift+${t}`),JD=[aa,$d].concat(zd,XD),ZD=[sa,c_,JD].join(","),PV=[ZD,WD,jD,UV].join(","),Bbt=[].concat(...sa,...sa,...JD,...sa,...sa,...sa,...sa,...sa,...sa),u_={OUTCOMEKEYS:Kd,SIDE1KEYS:sa,SIDE2KEYS:c_,MODIFIERS:JD,PROMPT:EV,MOVEUP:WD,MOVEDOWN:jD,HOTKEYS:PV};function Xp({scoreString:t,lowSide:e,outcome:r}){if({scoreString:t}=p_({scoreString:t}),e===2){let o=(t&&t[t.length-1])!==" "?" ":"";return t+o+r}else return r+" "+t}function p_({scoreString:t}){if(!t)return{scoreString:""};let e=!1;for(let r of FT){let n=t?.indexOf(r);n===0?t=t.slice(r.length+1).trim()+" ":n>0&&(t=t.slice(0,n)),n>=0&&(e=!0)}return t?.trim()||(t=""),{scoreString:t,removed:e}}function qg({analysis:t,scoreString:e,sets:r,lowSide:n}){let o,i;if(!e)return{scoreString:e,sets:r};let{scoreString:s,removed:a}=p_({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}=ju({brackets:Cs,scoreString:e}),f=DV(e);if(f>=0){o=e.slice(0,f);let{isTiebreakEntry:g}=ju({brackets:Rs,scoreString:o}),{lastOpenBracketIndex:I,isTiebreakEntry:h}=ju({brackets:Cs,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(gi),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(gi)}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 ju({brackets:t=Rs,scoreString:e}){if(!e)return{};let[r,n]=t.split(""),o=e.split(""),i=Math.max(...ho(r,o)),s=Math.max(...ho(n,o));return{isTiebreakEntry:i>s,lastOpenBracketIndex:i}}function m_({scoreString:t}){if(!t)return!1;let e=t&&t[t.length-1].trim(),r=t&&!isNaN(e),[n,o]=Cs.split(""),i=t.split(""),s=Math.max(...ho(n,i)),a=Math.max(...ho(o,i)),c=Math.max(...ho(gi,i));return r&&s>a&&c>s}function DV(t){return t.split("").reduce((n,o,i)=>(o.match(/\d+/g)&&n.push(i),n),[]).pop()}function WT(t){let{lowValue:e=0,NoAD:r=!1,tiebreakTo:n}=t||{},o=r?1:2;return e+1>=n?e+o:parseInt(n)}function tN({matchUpFormat:t,matchUpStatus:e,winningSide:r,sets:n}){let o=Ne(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 i_.includes(e)&&r&&(c=r),{matchUpWinningSide:c}}function Jp({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&&Ne(r);let a=o&&e.finalSetFormat||e?.setFormat||{},{side1Score:c,side2Score:u}=s,{setTo:p,tiebreakAt:m}=a,d=c||u,l=Zp({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 Zp({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 Qd({analysis:t,set:e}){let r=Zp({set:e}),{isDecidingSet:n,isTiebreakSet:o,matchUpScoringFormat:i}=t;return Jp({matchUpScoringFormat:i,isDecidingSet:n,isTiebreakSet:o,set:e})&&r}function d_({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}=NV({analysis:t,set:i,value:n});if(s){o=!0,e=(e||"")+n,i.side2Score=n;let c=Qd({analysis:t,set:r[r.length-1]});if(i.winningSide=c||void 0,a){let u=Rs.split("")[0];e+=u}else t.isDecidingSet||(e+=" ")}return{sets:r,scoreString:e,updated:o}}function NV({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 jT({lowSide:t,value:e,sets:r,scoreString:n,winningSide:o,matchUpStatus:i}){let s;return e===YD?n?(s=!0,n=Xp({scoreString:n,lowSide:t,outcome:"RET"}),o=t===2?1:2,i=HD):(s=!0,n=Xp({scoreString:n,lowSide:t,outcome:"DEF"}),o=t===2?1:2,i=kT):e===KD?(s=!0,n=Xp({scoreString:n,lowSide:t,outcome:"DEF"}),o=t===2?1:2,i=kT):e===zD?(s=!0,r=[],n="WO",o=t===2?1:2,i=BD):e===qD&&n?(s=!0,n=Xp({scoreString:n,lowSide:t,outcome:"SUS"}),i=VT,o=void 0):e===$D?(s=!0,n=Xp({scoreString:n,lowSide:t,outcome:"ABN"}),i=GT,o=void 0):e===QD&&n&&(s=!0,n=Xp({scoreString:n,lowSide:t,outcome:"INT"}),i=BT,o=void 0),{updated:s,sets:r,scoreString:n,matchUpStatus:i,winningSide:o}}function f_(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!==$d&&(e=[{setNumber:1}]);let m=e.length-1;if(Kd.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}=jT({lowSide:a,value:c,sets:e,scoreString:n,matchUpStatus:i,winningSide:o}))}else if(c===$d){if({scoreString:n,sets:e,outcomeRemoved:p}=qg({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===Qp){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===aa&&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 g_({analysis:t,auto:e,lowSide:r,scoreString:n="",sets:o,value:i}){let s,a,{tiebreakSet:{tiebreakTo:c,NoAD:u}}=t.setFormat,[p]=Cs.split("");if(t.isMatchTiebreakEntry||(n+=p),o[t.setNumber-1]){let{lastOpenBracketIndex:d}=ju({brackets:Cs,scoreString:n}),f=(n.slice((d??0)+1)+(e?"":i)).split(gi);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(gi),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=WT({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(gi),s=!0}return{info:a,scoreString:n,sets:o,updated:s}}function I_({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=Rs.split("")[0],d=u.join(aa)+(a?m:" ");r=(r||"")+d;let l={side1Score:u[0],side2Score:u[1]},f=Qd({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 h_({matchUpFormat:t,scoreString:e,winningSide:r,value:n,sets:o}){let s=(o?.filter(K=>K?.winningSide)?.length||0)+(r?0:1),a=Ne(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}=ju({brackets:Rs,scoreString:e}),{isTiebreakEntry:f}=ju({brackets:Cs,scoreString:e}),g=l||f,I=!!u.tiebreakSet,h=e?.[e.length-1]?.trim(),S=e&&!isNaN(h),T=!g&&h===aa,y=l&&HT.includes(h),E=f&&HT.includes(h),P=f&&h===gi,A=e?.split(""),[U]=Cs.split(""),N=A&&Math.max(...ho(U,A)),D=A&&Math.max(...ho(gi,A)),M=A&&D>N,R=o[o.length-1]?.winningSide,b=o?.length&&!R,O=FT.find(K=>e?.indexOf(K)>=0),v=!isNaN(n),x=n===Qp,F=zd.includes(n),w=e?.split("").find(K=>HT.includes(K)),L=F&&f&&!E&&(P||!m_({scoreString:e}));return{isTiebreakSetValue:I&&v,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:v,hasOpener:w,hasOutcome:O,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 rN(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(!ZD.includes(r))return{updated:!1,info:"invalid key"};c&&(e=3-e);let{matchUpWinningSide:l}=tN({sets:o,winningSide:i,matchUpStatus:s,matchUpFormat:a});i=l;let f=h_({value:r,winningSide:i,scoreString:n,sets:o,matchUpFormat:a});if(XD.includes(r)&&(r=aa),f.hasOpener&&f.isTiebreakEntry&&!f.isTiebreakSet&&d&&dt(r)===0&&(f.isTiebreakCloser=!0),zd.includes(r)&&f.hasOpener&&(r=""),zd.includes(r)&&(r=Qp),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}=f_({analysis:f,lowSide:e,scoreString:n,sets:o,matchUpStatus:s,winningSide:i,value:r}));else if(Kd.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}=jT({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===$d)p=!0,{scoreString:n,sets:o}=qg({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===aa&&!f.isMatchTiebreakEntry)(!f.isSetTiebreakEntry||f.isSetTiebreakEntry&&!f.isNumericEnding)&&(p=!0,{scoreString:n,sets:o}=qg({analysis:f,scoreString:n,sets:o,lowSide:e}),s=void 0);else if(r===gi&&f.isMatchTiebreakEntry&&!f.isSetTiebreakEntry)f.matchTiebreakHasJoiner?m="existing joiner":f.isNumericEnding&&(p=!0,n+=gi);else if([aa,gi].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}=d_({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?Rs:Cs,I=g.split("").reverse()[0],h=g.split("")[0],S=o[o.length-1],{tiebreakFormat:T}=f.setFormat,{tiebreakTo:y,NoAD:E}=T||{},P=Zp({set:S});if(!f.isTiebreakSet){let U=parseInt(n.split(h).reverse()[0]),N=WT({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+=" ");let A=Qd({analysis:f,set:S});S.winningSide=A||void 0,p=!0}else if(f.isTiebreakSetValue)({info:m,scoreString:n,sets:o,updated:p}=g_({analysis:f,auto:u,lowSide:e,scoreString:n,sets:o,value:r}));else if(f.isSetTiebreakEntry){let[g]=Rs.split(""),I=Math.max(...ho(g,n.split(""))),h=n.slice(I+1),S=h&&dt(h)===a_,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}=I_({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}=tN({sets:o,winningSide:i,matchUpStatus:s,matchUpFormat:a});return i=g,g&&(!s||[Qt,mn].includes(s))?(s=o_,o=o.filter(I=>{let{side1Score:h,side2Score:S,side1TiebreakScore:T,side2TiebreakScore:y}=I;return h||S||T||y})):n&&!i&&![VT,GT,BT].includes(s)&&(s=void 0),{updated:p,scoreString:n,sets:o,winningSide:i,matchUpStatus:s,info:m}}return{updated:p,scoreString:n,sets:o,winningSide:i,matchUpStatus:s,info:m}}var Xd="\\d+-\\d+",tm="\\d+-\\d+\\(\\d+\\)",$g="\\[\\d+-\\d+\\]",OV="\\d+-\\d+\\(\\d+-\\d+\\)",S_=new RegExp(`(${Xd}),`,"g"),T_=new RegExp(`(${tm}),`,"g"),vV=[Xd,tm,$g,OV],_V=["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"],xV=_V.map(t=>{let r=t.split("").map(n=>vV[n]).join(" ");return new RegExp(`^${r}$`)});function nN(t){return!t||xV.some(e=>e.test(t))}function y_(t){let n="[];()",o=["[","("],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="[];".includes(s)&&"[];"||"()".includes(s)&&"()"||"",d=m.split("").find(l=>l!==s);if(m.includes(u))i[s]||(s="");else return i[u]||(s=""),d}return c}).join("");return t!==a?a:t}function Jd(t){return/^\(\d+\)$/.test(t)||/^\(\d+$/.test(t)}function E_(t){return/^\(\d+-\d+\)$/.test(t)||/^\[\d+-\d+\]$/.test(t)}function Ba(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 em(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 oN(t){return t.length===2?t.split("").join("-"):([", ",",","/"," "].forEach(e=>t=t.split(e).join("-")),t=t.replace(/-{2,}/,"-"),t)}function A_(t){return t.startsWith("(")&&t.endsWith(")")}function U_({score:t,applied:e}){t=y_(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=Er(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(A_)?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 Yu(t){if(!/^[\d-]+(\(\d\))*$/.test(t))return t;let e=ho("-",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 P_({score:t,applied:e}){return t.includes("( ")&&(e.push("removeParenSpacingAfterOpen"),t=t.split("( ").map(r=>r.trim()).join("(")),t.includes(" )")&&(e.push("removeParenSpacingBeforeClose"),t=t.split(" )").map(r=>r.trim()).join(")")),[S_,T_].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(Yu).join(" "),{score:t,applied:e}}function D_({score:t}){if(typeof t!="string")return{score:t};let e=d=>d?.split("-").join("").split("/").join(""),r=d=>d.split("[").join("(").split("]").join(")");t=t.split(", ").join(" ");let n=t.split(" ");t=n.map(d=>{let l=/^-(\d+)$/;if(l.test(d)){let[f]=d.match(l).slice(1);if(f.length===2)return f.split("").join("-")}return d}).join(" "),n=t.split(" ");let o=n.filter(Jd),i=0,s="";for(let d of o){let l=ho(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=>E_(d)&&"bracket"||Ba(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=ho("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;!Ba(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($g).test(d)&&"super"||new RegExp(tm).test(d)&&"tiebreak"||new RegExp(Xd).test(d)&&"standard"||"unknown";return u.push(g),g==="standard"&&f?d.match(l)[1]:d}).join(" "),{score:t}}function N_({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(O=>parseInt(O)),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,O,v]=t.match(r).slice(1);t=t.replace(r,`${D}${M}-${R} ${b}-${O}${v}`),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=Yu(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,O]=M.split("");t=`${D}-${b} ${O}-${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 O=R.match(p).slice(1,3).join("-"),v=b.match(p).slice(1,3).join("-");t=`${O} ${v}`,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 O=R.match(p).slice(1,3).join("-"),v=b.match(p).slice(1,3).join("-");t=`${O} ${v}`,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(""),O=`${D}-${b[0]} ${b[1]}-${R}`;t=t.replace(g,O),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[O,v]=b.match(M).slice(1),x=`${O}-${v}`;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,O]=D.match(/(^|\s)(\d+-\d+)\s(\d+)(\s|$)/).slice(1),[v,x]=R.split("-").map(w=>parseInt(w));Math.abs(v-x)===1&&(t=t.replace(D,`${M}${R}(${b})${O}`),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,O]=D.match(M).slice(1),[v,x]=R.split("-").map(w=>parseInt(w));Math.abs(v-x)===1&&(t=t.replace(D,`${R}(${b})${O}`),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 M_({score:t,matchUpStatus:e}){let r=t?.split(" ");t=r.map(a=>{if(a.endsWith("]")){let c=a.split("[");if(Ba(c[0]))return c[0]+`(${c[1].slice(0,c[1].length-1)})`}return a}).join(" ");let n=new RegExp(/(\([\d ]+\))/g);if(n.test(t))for(let a of t.match(n)){let u=a.replace(" ","-").match(/\((.*)\)/)?.[1];if(Jt(u)&&u?.[0]>2){if([2,4].includes(u.length))u=u.split("").join("-");else if(u.length===3){let p=u.indexOf("1");u=em(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 Ba(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 R_({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=oN(l),h=Yu(I);t=t.replace(m,`(${h})`).trim()}let i=new RegExp(/\[[\d,/ ]+\]/g);t.match(i)?.forEach(m=>{let d=oN(m.match(/^\[(.*)\]$/)[1]);t=t.replace(m,`(${d}) `).trim()});let a=[")","]"],c=[")(","), (",") (",")[",") [","](","] ("];if(t.startsWith("(")&&a.some(m=>t.endsWith(m))&&c.some(m=>t.includes(m))){let m="",d=t.split(/[)\]]/).filter(Boolean).map(h=>(h.startsWith(",")&&(h=h.slice(1)),h.trim())),l=d.every(h=>h.includes(",")||Jd(h)),f=d.every(h=>h.includes("/")||Jd(h)),g=d.every(h=>h.includes("-")||Jd(h)),I=l&&","||g&&"-"||f&&"/";if(I){let h;d.forEach(S=>{if(S.startsWith("("))if(h==="set"&&(m+=" "),S.includes(I))m+=S.slice(1).split(I).map(T=>T.trim()).join("-"),h="set";else{let T=S.slice(1);m+=`(${T}) `,h="tiebreak"}else if(S.startsWith("[")){let T=S.slice(1).split(I).map(E=>parseInt(E.trim())),y=Math.min(...T);h==="set"?m+=`(${y}) `:m+=`[${T.join("-")}] `,h="tiebreak"}}),t=m.trim()}}let u=Er(t.split(""));u["("]===1&&u[")"]===1&&t.startsWith("(")&&t.endsWith(")")&&(t=t.slice(1,t.length-1),u["-"]===1&&Ba(t)&&Jt(e?.removed)&&(t=t+`(${e.removed})`,e.removed=void 0));let p=/\(\)/g;return p.test(t)&&(t=t.replace(p,"").trim()),{score:t}}function YT({score:t}){let e=t.split(""),r=[],n,o=()=>n=[void 0,void 0,void 0],i=()=>{let a=`${n[0]}-${n[1]}`;return n[2]&&(a+=` (${n[2]})`),o(),n.push(n),a};o();let s=()=>n[0]!==void 0&&n[1]!==void 0&&Math.abs(parseInt(n[0])-parseInt(n[1]));for(;e.length;){let a=e.shift(),c=Jt(a)&&parseInt(a),u=n[0]!==void 0&&n[1]!==void 0;if(Jt(c)){if(n[0]===void 0){n[0]=c;continue}if(n[1]===void 0&&(n[1]=c,s())){r.push(i()),n=[void 0,void 0];continue}if(u&&e.length===1&&Jt(e[0])){let p=e.pop();n[0]=n[0].toString()+n[1].toString(),n[1]=p,r.push(i()),n=[void 0,void 0]}u&&s()}}return{sets:r}}function Kg(t){let e=t.indexOf("1"),r=t.split(""),n=r.every(o=>!isNaN(o));if(n&&t.length===3&&e===0){let o=em(r,e);if(o)return o}if(n&&t.length===7&&e>3){let o=r.slice(4),i=em(o,e-4);if(i)return`${r[0]}-${r[1]} ${r[2]}-${r[3]} ${i}`}}function iN(t){let{score:e}=t,{applied:r,matchUpStatus:n}=t,o=e?.toString().split(""),i=o?.every(a=>Jt(a)),s=a=>Math.abs(a[0]-a[1]);if(typeof e=="number"||i){e=e.toString().toLowerCase(),i&&(e=o.join(""));let a=i?o.map(u=>parseInt(u)):e.split("").map(u=>parseInt(u)),{sets:c}=YT({score:e});if(a.length,e.length===3&&s(a.slice(0,2))===1){let[u,p,m]=a;e=`${u}-${p}(${m})`,r.push("numericTiebreakPattern1")}else if(e.length===3&&a[0]===1){let[u,p,m]=a;e=`[${u}${p}-${m}]`,r.push("numericTiebreakPattern2")}else if(e.length===4&&s(a.slice(0,2))===1&&"987654".split("").includes(a[0].toString())){let[u,p,m,d]=a,l=Math.min(m,d);e=`${u}-${p}(${l})`,r.push("numericTiebreakPattern3")}else if(e.length===4&&a[0]===1&&a[2]===1){let[u,p,m,d]=a;e=`[${u}${p}-${m}${d}]`,r.push("bigSuper")}else if(e.length===4){let[u,p,m,d]=a;e=`${u}${p} ${m}${d}`,r.push("split4")}else if(e.length===5&&s(a.slice(0,2))===1){let[u,p,m,d,l]=a;e=`${u}-${p}(${m}) ${d}-${l}`,r.push("numericTiebreakPattern4")}else if(e.length===5&&s(a.slice(3))===1){let[u,p,m,d,l]=a;e=`${u}-${p} ${m}-${d}(${l})`,r.push("numericTiebreakPattern5")}else if(a.length===7)if(s(a.slice(0,2))>1&&s(a.slice(2,4))>1&&a[4]===1){let[u,p,m,d,l,f,g]=a;e=`${u}-${p} ${m}-${d} [${l}${f}-${g}]`,r.push("numericTiebreakPattern6")}else if(s(a.slice(0,2))===1&&s(a.slice(3,5))>1&&s(a.slice(5,7))>1){let[u,p,m,d,l,f,g]=a;e=`${u}-${p}(${m}) ${d}-${l} ${f}-${g}`,r.push("numericTiebreakPattern7")}else if(s(a.slice(0,2))>1&&s(a.slice(2,4))===1&&s(a.slice(5,7))>1){let[u,p,m,d,l,f,g]=a;e=`${u}-${p} ${m}-${d}(${l}) ${f}-${g}`,r.push("numericTiebreakPattern8")}else if(s(a.slice(0,2))>1&&s(a.slice(2,4))>1&&s(a.slice(4,6))===1){let[u,p,m,d,l,f,g]=a;e=`${u}-${p} ${m}-${d} ${l}-${f}(${g})`,r.push("numericTiebreakPattern9")}else e=e.slice(0,2)+" "+e.slice(2,4)+" "+e.slice(4),r.push("numericMatchTiebreakPattern");else if(e.length%2){let u=Kg(e);u&&e!==u&&r.push("parsedSuperPattern"),e=u??e}else{let u=Ae(e.split(""),2).map(h=>h.join("")),p=u.map(h=>{let[S,T]=h.split("").map(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=Er(p),l=p.map(h=>Math.abs(h)),f=Er(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 qT(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 C_({score:t,matchUpStatus:e,attributes:r}){let n=[],o,i=t.split(" "),s=i.length;t=i.map((p,m)=>{if(new RegExp(tm).test(p)){let l=p.slice(3),f=p.slice(0,3),g=f.split("-");if(!Ba(f)&&!e){let I=Math.max(...g),h=f.indexOf(I),S=[I,I-1];return h&&S.reverse(),S.join("-")+l}}else if(p.length===2&&Jt(p))return p.split("").join("-");p=Yu(p);let d=new RegExp(`^${$g}$`).test(p)&&"super"||new RegExp(`^${tm}$`).test(p)&&"tiebreak"||new RegExp(`^${Xd}$`).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}=qT(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 b_({score:t}){let{setsTied:e,winningSide:r}=qT(t),n=/\s\((\d+)\)$/;if(!r&&e&&n.test(t)){let a=t.match(n).slice(1)[0],c=a<=8?10:a+2;t=t.replace(n,` [${c}-${a}]`)}let o=t.split(" "),i=o[o.length-1];if(!i.includes("-")||i.indexOf("(")>0)return{score:t};let s=i.split("(").join("").split(")").join("").split("-");if(!s.every(a=>Jt(a)))return{score:t};if(s[0]==="76"){let a=s[1].length===2?Math.min(...s[1].split("").map(c=>parseInt(c))):s[1];t=[...o.slice(0,o.length-1),`7-6(${a})`].join(" ")}else{s=s.map(u=>parseInt(u));let a=Math.max(...s),c=Math.abs(s[0]-s[1]);if(a>=10){if(c>2&&s.every(u=>+u>=10)){let u=s.map(p=>p===a?p-10:10).sort();c=Math.abs(u[0]-u[1]),c>2&&(s=u)}t=[...o.slice(0,o.length-1),`[${s.join("-")}]`].join(" ")}else o.length===3&&a>=7&&c>2&&(t=[...o.slice(0,o.length-1),`[${s.join("-")}]`].join(" "))}return{score:t}}function wV({score:t}){return t=t?.toString().toLowerCase()||"",{score:t}}function LV({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 FV({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=em(r.split(""),n);return e.push("getSuper"),o}}else{let{score:o,applied:i}=iN({score:r,applied:[]});o!==r&&(r=o,e.push(...i))}}return r}).join(" "),{score:t,applied:e})}function kV({score:t,applied:e}){return typeof t!="string"?{score:t}:[3,4].includes(t.length)&&Kg(t)?{score:Kg(t)}:(t=t.toLowerCase().split(" ").map(r=>{if(/^\d+$/.test(r)&&r.length===1){e.push("removeErroneous1");return}return r}).filter(Boolean).join(" "),{score:t,applied:e})}function 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 VV({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 BV({score:t,profile:e,applied:r}){t=t?.toString().toLowerCase();let n=/^(.*\d+.*)(def|defaulted)+[A-Za-z ]*$/;if(n.test(t)){let[a]=t.match(n).slice(1);return r.push("handleDefaulted"),{score:a.trim(),matchUpStatus:"defaulted",applied:r}}let o=e?.matchUpStatuses?.defaulted,s=["dft",...Array.isArray(o)?o:[o].filter(Boolean)].find(a=>t?.endsWith(a));return s?(r.push("handleDefaulted"),{matchUpStatus:"defaulted",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 WV({score:t}){return new RegExp(/-\d+\/\d+-/).test(t)&&(t=t.split("/").join(" ")),{score:t}}function jV({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 qV({score:t}){if(t.includes(",")){let e=t.split(",").map(o=>o.trim()),r=o=>/\d \d/.test(o);e.every(r)&&(t=e.map(o=>{let i=/\d+ \d+/g;for(let s of o.match(i)){let[a,c]=s.match(/(\d+) (\d+)/).slice(1);o=o.replace(s,`${a}-${c}`)}return o}).join(" "))}if(t.includes(" ")){let e=t.replace(/[ ,]/g,"");e.split("").every(n=>Jt(n))&&e.length===4&&(t=e)}return{score:t}}function $V({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 O_={handleTiebreakSlashSeparation:YV,handleSetSlashSeparation:WV,punctuationAdjustments:U_,handleGameSeparation:jV,joinFloatingTiebreak:D_,handleBracketSpacing:P_,handleSpaceSeparator:qV,separateScoreBlocks:FV,matchKnownPatterns:N_,removeDanglingBits:HV,removeErroneous:kV,handleDefaulted:BV,handleWalkover:GV,properTiebreak:M_,handleNumeric:iN,handleRetired:VV,containedSets:R_,sensibleSets:C_,stringScore:wV,superSquare:b_,setBuilder:YT,excisions:$V,replaceOh:LV};var sN={},KV=[],zV=["handleNumeric","handleWalkover","handleRetired","handleDefaulted","replaceOh","stringScore","punctuationAdjustments","excisions","handleSpaceSeparator","matchKnownPatterns","removeDanglingBits","handleBracketSpacing","matchKnownPatterns","containedSets","separateScoreBlocks","handleGameSeparation","removeErroneous","joinFloatingTiebreak","handleSetSlashSeparation","handleTiebreakSlashSeparation","properTiebreak","sensibleSets","superSquare"],QV=["handleNumeric","separateScoreBlocks","sensibleSets","superSquare"];function aN(t){if(!t.score)return{error:B};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=O_[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(zV);let g=nN(l);return g||(l=e.toString().replaceAll(/\D/g,""),m?.removed&&(m.removed=void 0),f(QV),g=nN(l),g||(KV.push({score:l,fileName:o,sheetName:r}),l="")),p.forEach(I=>{sN[I]||(sN[I]=0),sN[I]+=1}),{matchUpStatus:u?.toUpperCase(),modifications:c,attributes:m,isValid:g,score:l}}var mN={};Xt(mN,{analyzeScore:()=>zg,analyzeSet:()=>qu,checkScoreHasValue:()=>he,checkSetIsComplete:()=>Jp,getSetComplement:()=>Xg,getTiebreakComplement:()=>rm,isValidMatchUpFormat:()=>Nr,parseScoreString:()=>nm,validateMatchUpScore:()=>uN,validateScore:()=>Qg,validateSetScore:()=>$T,validateTieFormat:()=>ar});function XV(t,e,r,n,o,i=!1){return o?{isValid:!0}:t===0&&e===0?{isValid:!1,error:"Tiebreak-only set requires both scores"}:t<n?{isValid:!1,error:`Tiebreak-only set winner must reach at least ${n}, got ${t}`}:r<(i?1:2)?{isValid:!1,error:i?`Tiebreak-only set (NoAD) must be won by at least 1 point, got ${t}-${e}`:`Tiebreak-only set must be won by at least 2 points, got ${t}-${e}`}:i?{isValid:!0}:t===n&&e>n-2?{isValid:!1,error:`Tiebreak-only set at ${n}-${e} requires playing past ${n}`}:t>n&&r!==2?{isValid:!1,error:`Tiebreak-only set past ${n} must be won by exactly 2 points, got ${t}-${e}`}:{isValid:!0}}function JV(t,e,r,n){let o=n===r?r+1:r,i=n;return t!==o?{isValid:!1,error:`Tiebreak set winner must have ${o} games, got ${t}`}:e!==i?{isValid:!1,error:`Tiebreak set loser must have ${i} games, got ${e}`}:{isValid:!0}}function ZV(t,e,r){let n=Math.max(t||0,e||0),o=Math.min(t||0,e||0),i=n-o,s=r.tiebreakTo||7;return n<s?{isValid:!1,error:`Tiebreak winner must reach ${s} points, got ${n}`}:i<2?{isValid:!1,error:`Tiebreak must be won by 2 points, got ${n}-${o}`}:o>=s-1&&i>2?{isValid:!1,error:`Tiebreak score ${n}-${o} is invalid`}:{isValid:!0}}function t1(t,e,r,n){return n?t===r+1&&e<r-1?{isValid:!1,error:`With tiebreak format, if side 1 has ${r+1} games, side 2 must be at least ${r-1}, got ${e}`}:e===r+1&&t<r-1?{isValid:!1,error:`With tiebreak format, if side 2 has ${r+1} games, side 1 must be at least ${r-1}, got ${t}`}:{isValid:!0}:{isValid:!0}}function e1(t,e,r,n,o){if(t<n)return{isValid:!1,error:`Set winner must reach ${n} games, got ${t}`};let i=o&&t===n&&e===o&&r===1;if(r<2&&!i)return{isValid:!1,error:`Set must be won by at least 2 games, got ${t}-${e}`};if(o){if(e>=o&&!i)return{isValid:!1,error:`When tied at ${o}-${o}, must play tiebreak. Use format like ${o+1}-${o}(5)`};let s=o===n?n+1:n;if(t>s)return{isValid:!1,error:`With tiebreak format, set score cannot exceed ${s}-${o}. Got ${t}-${e}`}}else if(t>n+10)return{isValid:!1,error:`Set score ${t}-${e} exceeds reasonable limits`};return{isValid:!0}}function r1(t,e,r){let n=t.side1TiebreakScore,o=t.side2TiebreakScore,i=e&&r?n:t.side1Score||t.side1||0,s=e&&r?o:t.side2Score||t.side2||0;return{side1Score:i,side2Score:s,side1TiebreakScore:n,side2TiebreakScore:o}}function n1(t,e,r,n,o,i,s){if(r&&n){let c=JV(t,e,r,n);if(!c.isValid)return c}return(o!==void 0||i!==void 0)&&s?ZV(o,i,s):{isValid:!0}}function o1(t,e,r){return r&&(t>r+10||e>r+10)?{isValid:!1,error:`Set score ${t}-${e} exceeds expected range for ${r}-game sets`}:{isValid:!0}}function i1(t,e,r){let{side1:n,side2:o,winner:i,loser:s,diff:a}=t,{setTo:c,tiebreakAt:u}=e;if(c&&u){let p=t1(n,o,c,u);if(!p.isValid)return p}return r?o1(i,s,c):c?e1(i,s,a,c,u):{isValid:!0}}function $T(t,e,r,n){if(!e)return{isValid:!0};let o=Ne(e);if(!o)return{isValid:!0};let i=r&&o.finalSetFormat?o.finalSetFormat:o.setFormat;if(!i)return{isValid:!0};if(i.timed){if(!n){let A=t.side1Score??0,U=t.side2Score??0;if(A===0&&U===0)return{isValid:!1,error:"Timed set requires at least one side to have scored"};if(i.based==="P"&&A===U&&A>0&&i.tiebreakFormat&&!(t.side1TiebreakScore!==void 0||t.side2TiebreakScore!==void 0))return{isValid:!1,error:"Tied timed set requires tiebreak"}}return{isValid:!0}}let{setTo:s,tiebreakAt:a,tiebreakFormat:c,tiebreakSet:u}=i,p=u?.tiebreakTo,m=!!p&&!s,d=t.side1TiebreakScore!==void 0&&t.side2TiebreakScore!==void 0,{side1Score:l,side2Score:f,side1TiebreakScore:g,side2TiebreakScore:I}=r1(t,m,d),h=Math.max(l,f),S=Math.min(l,f),T=h-S;if(m){let A=i.tiebreakSet?.NoAD??!1;return XV(h,S,T,p,n??!1,A)}let y=g!==void 0||I!==void 0,E=s&&h===s+1&&S===s;return y||E?n1(h,S,s,a,g,I,c):i1({side1:l,side2:f,winner:h,loser:S,diff:T},{setTo:s,tiebreakAt:a},n)}function uN(t,e,r){if(!t||t.length===0)return{isValid:!0};let n=e?.match(/SET(\d+)/)?.[1],o=n?Number.parseInt(n):3,i=[Me,Bt,Gt].includes(r||"");for(let s=0;s<t.length;s++){let a=t[s],c=s+1===o,u=a.winningSide!==void 0,d=$T(a,e,c,i||r===void 0&&!u);if(!d.isValid)return{isValid:!1,error:`Set ${s+1}: ${d.error}`}}return{isValid:!0}}function s1(t,e,r,n,o,i){let{tiebreakTo:s,NoAD:a}=t||{},c=Math.max(e??0,r??0);return!(a&&c>s||c<s&&n&&(o&&!i||!o))}function a1(t,e,r,n,o,i){let a=e+1===n,{side1Score:c,side2Score:u,side1TiebreakScore:p,side2TiebreakScore:m,winningSide:d}=t,l=Math.max(c??0,u??0),f=p??m,{finalSetFormat:g,setFormat:I}=r,h=a&&g||I;return f&&!s1(h?.tiebreakFormat,p,m,d,o,i)?!1:h.setTo?!(!h.noTiebreak&&l>h.setTo+1):!0}function c1(t){let e=t.reduce((r,n)=>((n.side1Score!==void 0||n.side2Score!==void 0)&&(r[0]+=n.side1Score??0,r[1]+=n.side2Score??0),r),[0,0]);return e[0]>e[1]?1:e[1]>e[0]?2:t.find(n=>n.side1TiebreakScore!==void 0||n.side2TiebreakScore!==void 0)?.winningSide}function u1(t,e,r,n,o){return(!o||t===e)&&r===1&&n.indexOf(t)+1||void 0}function zg({existingMatchUpStatus:t,matchUpFormat:e,matchUpStatus:r,winningSide:n,score:o}){let i=o?.sets??[],a=(i?.filter(U=>U?.winningSide)||[]).reduce((U,N)=>{let{winningSide:D}=N;if(!D)return U;let M=D-1;return U[M]++,U},[0,0]),c=n?n-1:void 0,u=c!==void 0&&[0,1].includes(c)?1-c:void 0,p=c!==void 0&&a[c],m=u!==void 0&&a[u],d=e?Ne(e):void 0,l=Math.max(...a),f=Er(a)[l],g=d?.setFormat?.timed||d?.finalSetFormat?.timed,I=d?.bestOf||d?.exactly,h=I&&Math.ceil(I/2)||1,S=r??t,T=!!(S&&[Gt,Me,Bt].includes(S)),y=!d||!i.length||i.every((U,N)=>a1(U,N,d,I??0,N===i.length-1,T)),E=d?.setFormat?.based==="A"||d?.finalSetFormat?.based==="A",P=E&&i.length>0?c1(i):u1(l,h,f,a,e);return{valid:!!(y&&(n&&E&&n===P||n&&!E&&p>m&&n===P||n&&T||!n&&!P&&(![ge,Gt,Me,Bt].includes(S)||g&&S===ge)))}}function Qg({existingMatchUpStatus:t,matchUpFormat:e,matchUpStatus:r,winningSide:n,score:o}){if(typeof o!="object")return{error:B};let{sets:i,scoreStringSide1:s,scoreStringSide2:a}=o,c="scoreString must be a string!";if(s!==void 0&&typeof s!="string")return{error:B,info:c};if(a!==void 0&&typeof a!="string")return{error:B,info:c};if(i!==void 0&&!Array.isArray(i))return{error:B,info:li("sets")};if(i?.length){let u=i.map(m=>m?.setNumber).filter(Boolean);if(u.length!==pt(u).length)return{error:B,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:B,info:"non-numeric values"};if(![T,S].filter(P=>![void 0,null].includes(P)).every(P=>It(P)))return{error:B,info:"non-numeric values"};if(S&&![1,2].includes(S))return{error:B,info:"winningSide must be 1 or 2"}}let{valid:p}=zg({existingMatchUpStatus:t,matchUpStatus:r,matchUpFormat:e,winningSide:n,score:o});if(!p)return{error:IA,info:"score is invalid for matchUpFormat or winningSide does not match calculated winningSide"}}return{valid:!0}}var Xg=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]},rm=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=p1({lowValue:i,NoAD:o,tiebreakTo:n});return[e?i:s,e?s:i]};function p1(t){let{lowValue:e,NoAD:r,tiebreakTo:n}=t,o=r?1:2;return e+1>=n?e+o:n}function pN(t,e){return t>e&&1||t<e&&2||void 0}function m1(t,e){return e?{side1Score:t[0],side2Score:t[1],winningSide:pN(t[0],t[1])}:{side1TiebreakScore:t[0],side2TiebreakScore:t[1],winningSide:pN(t[0],t[1])}}function nm({tiebreakTo:t=7,scoreString:e="",matchUpFormat:r}){let n,o=3;if(r)try{n=Ne(r);let p=/SET(\d+)/.exec(r)?.[1];o=p?Number.parseInt(p):3}catch{}return e?.split(" ").filter(Boolean).map((p,m)=>u({set:p,setNumber:m+1}));function i(p,m){if(!n||!m)return!1;let l=p===o&&n.finalSetFormat?n.finalSetFormat:n.setFormat;if(!l)return!1;let f=l.tiebreakSet?.tiebreakTo,g=l.setTo;return!!f&&!g}function s(p){return n?(p===o&&n.finalSetFormat?n.finalSetFormat:n.setFormat)?.tiebreakFormat?.tiebreakTo??t:t}function a(p,m,d){let l=p[1],f=s(d),g=rm({lowValue:l,isSide1:m===2,tiebreakTo:f});return Array.isArray(g)?[g[0],g[1]]:[void 0,void 0]}function c(p,m,d,l){let g=(m&&p.replace(m[0],"")||d&&p.replace(d[0],"")||p).split("-").map(E=>Number.parseInt(E)),I=g[0],h=g[1],S=pN(I,h),T,y;if(m&&([T,y]=a(m,S,l)),d){let E=d[1].split("-").map(P=>Number.parseInt(P));T=E[0],y=E[1]}return{side1Score:I,side2Score:h,side1TiebreakScore:T,side2TiebreakScore:y,winningSide:S}}function u({set:p,setNumber:m}){let d=/\(([^)]+)\)/,l=/\[([^\]]+)\]/,f=d.exec(p),g=l.exec(p),I=p?.startsWith("[")&&g,h=i(m,!!I),S=s(m),T=h&&S===1,y;if(I){let E=g[1].split("-").map(P=>Number.parseInt(P));y=m1(E,h)}else y=c(p,f,g,m);return{side1Score:y.side1Score,side2Score:y.side2Score,side1TiebreakScore:y.side1TiebreakScore,side2TiebreakScore:y.side2TiebreakScore,winningSide:y.winningSide,setNumber:m,...T&&{NoAD:!0},...h&&{tiebreakSet:!0}}}}function v_({matchUpScoringFormat:t,isDecidingSet:e,isTiebreakSet:r,isTimedSet:n,setObject:o}){if(!o)return;let i=Zp({set:o});return Jp({matchUpScoringFormat:t,set:o,isDecidingSet:e,isTiebreakSet:r,isTimedSet:n})&&i||void 0}function qu(t){let{setObject:e,matchUpScoringFormat:r}=t;if(!e)return{error:ef};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}=d1({sideTiebreakScores:g,sideGameScores:l,setFormat:c,setObject:e}),{error:R,result:b}=l1({sideTiebreakScores:g,setObject:e,setFormat:c}),O=m&&!U&&M||u&&U&&b||p,v=d&&!(u&&!U)&&!(m&&U)&&(!N||O),x=v_({isTimedSet:p,matchUpScoringFormat:r,isDecidingSet:a,isTiebreakSet:U,setObject:e}),F={expectTiebreakSet:u,expectTimedSet:p,hasTiebreakCondition:P,isCompletedSet:N,isDecidingSet:a,isTiebreakSet:U,isValidSet:v,isValidSetNumber:d,isValidSetOutcome:O,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 d1({setObject:t,setFormat:e,sideGameScores:r,sideTiebreakScores:n}){if(!t)return{result:!1,error:ef};let o=!!e?.tiebreakSet,i=!!e?.timed;if(!e||o||i)return{result:!1,error:B};if(!(r?.filter(M=>!isNaN(M)).length===2))return{result:!1,error:KI};let{setTo:a,tiebreakAt:c,tiebreakFormat:u,NoAD:p}=e||{};if(!!!(a&&r?.find(M=>M>=a)))return{result:!1,error:KI};let d=[1,2].includes(t?.winningSide);if(!t||!d)return{result:!1,error:_m};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(k=>k>=R)))return{result:!1,error:{message:"invalid tiebreak scores (2)"}};let v=c<a?a:a+1;if(g>v)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 l1({setObject:t,setFormat:e,sideTiebreakScores:r}){if(!t)return{result:!1,error:ef};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:_m};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 __(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&&io({namedFormat:o,hydrateCollections:r,isMock:a,event:c})||c?.tieFormat||io({event:c,isMock:a,hydrateCollections:r}),p=void 0}else p||(u=void 0,c?.matchUpFormat||(p=bn));if(u){let m=ar({gender:c?.gender,enforceGender:n,tieFormat:u});if(m.error)return m}return{tieFormat:u,matchUpFormat:p}}function x_(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?OT({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}=Us({stageSequence:1,drawDefinition:e,structureId:s,stage:rt}),S=Math.max(l??0,h??0),T=$S({qualifiersCount:S,drawDefinition:e,stage:rt});if(T.error||(T=Hp({drawSize:f,stage:ct,drawDefinition:e}),T.error))return T;f1({drawDefinition:e,drawEntries:i,event:p});let y=g1({mainStructure:I,qualifyingDetails:g,drawDefinition:e});return y.error?y:{drawDefinition:e,structureId:s}}function f1({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};Pd(o)}}function g1({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&&La({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 KT(t){let{participantIds:e}=t,r=t.drawDefinition?.entries?.filter(n=>{let o=n.entryStatus;return!t.restrictEntryStatus||Xr.includes(o)}).map(St)??[];if(e){let n=e.filter(o=>!r?.includes(o));if(n?.length)return _({result:{error:ln},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:B,info:"Not enough participants for roundsCount"}:t.roundsCount&&t.restrictRoundsCount!==!1&&t.roundsCount>31?{error:B,info:"roundsCount must be less than 32"}:{participantIds:e}}function Zd(t){let e=[],{roundsCount:r=1,drawDefinition:n,matchUpsCount:o,structureId:i,idPrefix:s,isMock:a,event:c}=t,u,p=KT(t);if(p.error)return p;for(let m of tt(1,r+1)){let d=Wu({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 L_(t){let{tournamentRecord:e,participantIds:r,scaleName:n,eventType:o,adHocRatings:i={}}=t,s=t.scaleAccessor??je[n]?.accessor,a=e.participants??[];for(let c of r??[]){let u=a?.find(m=>m.participantId===c),p=w_({scaleName:`${n}.${Qm}`,participant:u,eventType:o});!p&&n&&(p=w_({scaleAccessor:s,participant:u,scaleName:n,eventType:o})),p&&!i[c]&&(i[c]=p)}return i}function w_({scaleType:t=Ui,scaleAccessor:e,participant:r,scaleName:n,eventType:o}){let a=(r&&Po({scaleAttributes:{eventType:o??qs,scaleType:t,scaleName:n},participant:r}))?.scaleItem?.scaleValue;return e&&ht(a)?a[e]:a}function tl(t){let e=h1(t);if(e?.error)return e;let r=KT(t);if(r.error)return r;let n=I1(t);if(n.error)return n;let o=L_(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=qd({...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 I1(t){if(t.structureId)return t.structureId;let e=t.drawDefinition,r=e?.structures?.filter(i=>i.stageSequence===1)?.reduce((i,s)=>{let a=s.stage&&$s[s.stage];return cr({structure:s})&&a>($s[i?.stage]||1)?s:i},void 0),n=e?.structures?.find(i=>i.structureId===r?.structureId);return n?cr({structure:n})?{structure:n}:{error:Sa}:{error:_t}}function h1(t){return t.roundsCount&&typeof t.roundsCount!="number"?{error:B,info:"roundsCount must be a number"}:typeof t.drawDefinition!="object"||t.drawDefinition.drawType&&t.drawDefinition.drawType!==Fr?{error:Sa}:!Array.isArray(t.drawDefinition?.entries)&&t.participantIds&&!Array.isArray(t.participantIds)?{error:B,info:"Missing Entries"}:{error:void 0}}function F_(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&&Xr.includes(m)),c=a?.map(St),u=a?Math.floor(a.length/2):0;if(t.automated)return S1({...t,participantIds:c});{let p=Zd({roundsCount:t.roundsCount,drawDefinition:r,matchUpsCount:u,idPrefix:o,isMock:i,event:s});if(p.error)return p;p.matchUps?.length&&Gd({matchUps:p.matchUps,suppressNotifications:!0,tournamentRecord:e,drawDefinition:r,structureId:n,event:s})}return{...C}}function S1(t){let{restrictEntryStatus:e,generateMatchUps:r,structureId:n,matchUpIds:o,scaleName:i,scaleAccessor:s}=t.drawMatic??{},a=tl({...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&&Gd({tournamentRecord:t.tournamentRecord,drawDefinition:t.drawDefinition,suppressNotifications:!0,matchUps:a.matchUps,event:t.event,structureId:n}),{...C})}function k_({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:_t};let{positionAssignments:d}=Ie({structure:m}),l=d?.length||0;if(u>l)return{error:$E};let f=m.structures?.length,g=It(a?.groupSeedingThreshold)&&a?.groupSeedingThreshold,I=Dg({roundRobinGroupsCount:f,drawSize:l})?.seedGroups,{seedsCount:h}=Hu({policyDefinitions:i,requireParticipantCount:t,drawSizeProgression:r,participantsCount:n,drawSize:l});return h&&i?.[Vn]&&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}}),bt({drawDefinition:s,structureIds:[c]}),{...C,seedLimit:u}}function ca({sortDescending:t=!1,tournamentRecord:e,scaleAttributes:r,scaleSortMethod:n,stageSequence:o,entries:i,event:s,stage:a}){if(!e)return{error:q};return i=i??s?.entries??[],{scaledEntries:i.filter(d=>(!a||!d.entryStage||d.entryStage===a)&&(!o||!d.entryStageSequence||d.entryStageSequence===o)&&Xr.includes(d.entryStatus)).map(d=>{let{participantId:l}=d,{scaleItem:f}=wc({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 zT(t){let e="prepareStage",{drawDefinition:r}=t,{structures:n}=hn({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:_t},stack:e});let s=i?.structureId,{seedsCount:a,stageEntries:c,seedLimit:u}=N1({...t,structureId:s});(t.seededParticipants||t.event||t.seedingScaleName)&&E1({...t,seedsCount:a,structure:i,structureId:s});let p=t.automated!==!1&&t.drawType!==Fr&&!(t.qualifyingOnly&&t.stage!==ct),m=(n?.length||0)>1,d=p?y1({...t,multipleStructures:m,seedLimit:u,structureId:s}):{};return d?.error?_({result:d,stack:e}):{...d,stageEntries:c,structureId:s,seedsCount:a}}function T1({entries:t,stage:e,stageSequence:r,roundTarget:n}){return t.filter(o=>{let i=mt({name:vn,element:o})?.extension?.value;return(!o.entryStage||o.entryStage===e)&&(!r||!o.entryStageSequence||o.entryStageSequence===r)&&(!n||!i||i===n)&&mi.includes(o.entryStatus)})}function y1(t){let e=typeof t.automated=="object"&&t.automated.seedsOnly,r=Mc({...t,seedsOnly:e});if(r.error)return r;let n=r?.positionAssignments,o=r?.positioningReport;return{conflicts:r.conflicts,positionAssignments:n,positioningReport:o}}function E1(t){let{seededParticipants:e,seedingScaleName:r,entries:n,event:o}=t,i=n.map(St);e?A1({...t,enteredParticipantIds:i}):(o||r)&&U1({...t,enteredParticipantIds:i})}function A1(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?Ns({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;ra({provisionalPositioning:e,tournamentRecord:o,drawDefinition:s,seedingProfile:a,participantId:l,seedBlockInfo:m,structureId:c,seedNumber:f,seedValue:g,event:p})})}function U1(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=P1({...t,ageCategoryCode:l,categoryName:d,eventType:f})||c&&D1({...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;ra({provisionalPositioning:r,tournamentRecord:s,drawDefinition:a,seedingProfile:u,participantId:y,structureId:p,seedNumber:T,seedValue:P,event:m})})}function P1(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:Ao,eventType:u};return ca({scaleAttributes:p,tournamentRecord:e,stageSequence:n,entries:o,stage:i}).scaledEntries}function D1(t){let{tournamentRecord:e,stageSequence:r,event:n,entries:o,stage:i}=t,{categoryName:s,ageCategoryCode:a}=n?.category||{},c=n?.eventType;return ca({scaleAttributes:{scaleName:s||a,scaleType:Ai,eventType:c},tournamentRecord:e,stageSequence:r,entries:o,stage:i}).scaledEntries}function N1(t){let{seedsCount:e}=t;t.seededParticipants&&(e=t.seededParticipants.length),e>t.drawSize&&(e=t.drawSize);let r=T1(t);e>r.length&&(e=r.length);let{seedLimit:n}=k_({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 G_(t){let e=jd({...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=M1({suppressDuplicateEntries:n,ignoreStageSpace:o,drawDefinition:r,drawEntries:u,drawType:d,entries:l});if(I.error)return I;let h=d===Ki?0:dt(t.seedsCount??0),S=zT({...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===Fr&&t.roundsCount&&F_({...t,drawDefinition:r,structureId:T}),{drawDefinition:r,positioningReports:f,conflicts:g,structureId:T}}function M1(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===Fr,entryStage:s.entryStage??rt,event:t.event,drawDefinition:r,drawType:o},c=Pd(a);if(n&&c.error)return c}return{error:void 0}}var R1=()=>({matchUpType:void 0,drawName:void 0,drawId:void 0,structures:[],entries:[],links:[]});var V_=R1;function B_(t){let{drawId:e=Nt(),processCodes:r,matchUpType:n,drawType:o}=t??{},i=V_();return Object.assign(i,{processCodes:r,matchUpType:n,drawType:o,drawId:e})}function el(t){let e=t.structureIds,{tournamentRecord:r,drawDefinition:n,matchUpFormat:o,structureId:i,matchUpId:s,event:a}=t,c=et(t,[{[Ce]:!0,[$m]:!0}]);if(c.error)return c;if(!Nr({matchUpFormat:o}))return{error:tc};let u="setMatchUpFormat";if(s){let p=Vt({drawDefinition:n,matchUpId:s,event:a});if(p.error)return p;let m=p.matchUp;if(m?.matchUpType===_e)return{info:"Cannot set matchUpFormat when { matchUpType: TEAM }",error:dr};m&&(m.matchUpFormat=o,gt({tournamentId:r?.tournamentId,eventId:a?.eventId,context:u,drawDefinition:n,matchUp:m}))}else if(Array.isArray(e)){if(a?.eventType===_e)return{error:$n};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:$n};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),bt({drawDefinition:n,structureIds:e}),{...C}}function H_({tieFormat:t}){let e=ar({checkCollectionIds:!1,tieFormat:t});if(e.error)return e;for(let r of t.collectionDefinitions)r.collectionId||(r.collectionId=Nt());return{tieFormat:t}}function W_({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=H_({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=el({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 gN={};Xt(gN,{attachPolicies:()=>ss,findPolicy:()=>pi,getAppliedPolicies:()=>Tt,getPolicyDefinitions:()=>Go,mutate:()=>lN,query:()=>fN,removePolicy:()=>dN});var lN={};Xt(lN,{attachPolicies:()=>ss,removePolicy:()=>dN});function dN(t){let e=et(t,[{[fb]:!0,_anyOf:{[Re]:!1,[ne]:!1,[Ce]:!1,[co]:!1}}]);if(e.error)return e;let r,n=t.drawDefinition??t.event??((t.tournamentId||!t.tournamentRecords)&&t.tournamentRecord);if(n)return j_(t,n);if(t.tournamentRecords){let o=Object.keys(t.tournamentRecords);if(!o.length)return{error:q};for(let i of o){let s=t.tournamentRecords[i],a=j_(t,s);if(a.error)return a;r=!0}}else return{error:q};return r?{...C}:{error:qc}}function j_(t,e){let r=Tt(t).appliedPolicies??{};return r[t.policyType]?(delete r[t.policyType],Object.keys(r).length?At({element:e,extension:{name:du,value:r}}):Ir({element:e,name:du}),{...C}):{error:qc}}var fN={};Xt(fN,{findPolicy:()=>pi,getAppliedPolicies:()=>Tt,getPolicyDefinitions:()=>Go});var IN={[Vn]:{validSeedPositions:{ignore:!0},duplicateSeedNumbers:!0,drawSizeProgression:!0,seedingProfile:{drawTypes:{[Eo]:{positioning:Ti},[On]:{positioning:Ti}},positioning:ab},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}]}},Zg=IN;function Y_({appliedPolicies:t,policyDefinitions:e,drawDefinition:r,stack:n}){if(e&&typeof e!="object")return _({info:"policyDefinitions must be an object",result:{error:B},stack:n});let o={[mu]:t?.[mu]};return e?C1({policyDefinitions:e,appliedPolicies:t,policiesToAttach:o,drawDefinition:r}):o.avoidance&&ss({drawDefinition:r,policyDefinitions:o}),!t?.[Vn]&&!e?.[Vn]&&(ss({policyDefinitions:Zg,drawDefinition:r}),t&&Object.assign(t,Zg)),{error:void 0}}function C1({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&&(ss({policyDefinitions:r,drawDefinition:n}),e&&Object.assign(e,r))}function q_(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??B_({processCodes:t.processCodes,drawId:t.drawId,drawType:a}),g=W_({existingQualifyingStructures:d,tournamentRecord:e,drawDefinition:f,matchUpFormat:o,matchUpType:i,tieFormat:s,event:u});if(g.error)return _({result:g,stack:c});let I=Y_({appliedPolicies:n,policyDefinitions:r,drawDefinition:f,stack:c});return I.error?I:{drawDefinition:f,structureId:m,existingDrawDefinition:p,existingQualifyingPlaceholderStructureId:l}}function $_(t){let e="generateOrGetExisting",r=[],n=[],o=q_(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&&x_({...t,...o})||G_({...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 K_(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:li("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:O,drawSize:v}=A,x=zT({...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:O,drawSize:v,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=yn({structureName:Qe(ct),stage:ct,qualifyingOnly:s,tieFormat:m}),{link:h}=La({sourceStructureId:I.structureId,targetStructureId:p,sourceRoundNumber:0,linkType:Fn});a.structures||(a.structures=[]),a.structures.push(I),a.links||(a.links=[]),a.links.push(h)}return{qualifyingConflicts:g,error:void 0}}var FN={};Xt(FN,{addGoesTo:()=>rs,allCompetitionMatchUps:()=>Mn,allDrawMatchUps:()=>nr,allEventMatchUps:()=>to,allPlayoffPositionsFilled:()=>WS,allTournamentMatchUps:()=>ye,analyzeDraws:()=>Vu,analyzeMatchUp:()=>cm,analyzeTournament:()=>sy,bulkUpdatePublishedEventIds:()=>cy,calculateWinCriteria:()=>Os,categoryCanContain:()=>tu,checkMatchUpIsComplete:()=>Ts,checkValidEntries:()=>Hd,compareTieFormats:()=>ni,competitionScheduleMatchUps:()=>Ku,courtGridRows:()=>dl,credits:()=>z_,drawMatchUps:()=>Dy,eventMatchUps:()=>Il,filterMatchUps:()=>_i,filterParticipants:()=>bu,findDrawDefinition:()=>gT,findExtension:()=>mt,findVenue:()=>ti,getAggregateTeamResults:()=>iy,getAllDrawMatchUps:()=>ie,getAllEventData:()=>uy,getAllStructureMatchUps:()=>yt,getAllowedDrawTypes:()=>rl,getAllowedMatchUpFormats:()=>ey,getAppliedPolicies:()=>Tt,getAssignedParticipantIds:()=>wi,getAvailableMatchUpsCount:()=>Vd,getAvailablePlayoffProfiles:()=>Lu,getCategoryAgeDetails:()=>Ys,getCheckedInParticipantIds:()=>Is,getCompetitionDateRange:()=>ol,getCompetitionMatchUps:()=>am,getCompetitionParticipants:()=>QT,getCompetitionPenalties:()=>ry,getCompetitionVenues:()=>om,getCourtInfo:()=>Td,getCourts:()=>Ny,getDrawData:()=>cl,getDrawDefinitionTimeItem:()=>iS,getDrawParticipantRepresentativeIds:()=>lT,getDrawStructures:()=>hn,getDrawTypeCoercion:()=>Bu,getEligibleVoluntaryConsolationParticipants:()=>dT,getEntriesAndSeedsCount:()=>ll,getEvent:()=>Cy,getEventData:()=>ul,getEventMatchUpFormatTiming:()=>Iy,getEventProperties:()=>My,getEventPublishStatus:()=>Jr,getEventStructures:()=>Mg,getEventTimeItem:()=>Au,getEvents:()=>Ry,getFlightProfile:()=>Ht,getHomeParticipantId:()=>yy,getLinkedTournamentIds:()=>fu,getMatchUpCompetitiveProfile:()=>Du,getMatchUpContextIds:()=>Ey,getMatchUpDailyLimits:()=>Sl,getMatchUpDailyLimitsUpdate:()=>hy,getMatchUpDependencies:()=>an,getMatchUpFormat:()=>Ay,getMatchUpFormatTiming:()=>Nu,getMatchUpFormatTimingUpdate:()=>fy,getMatchUpScheduleDetails:()=>yd,getMatchUpType:()=>Ed,getMatchUpsMap:()=>Pe,getMatchUpsStats:()=>Uy,getMatchUpsToSchedule:()=>pl,getMaxEntryPosition:()=>dy,getModifiedMatchUpFormatTiming:()=>fl,getPairedParticipant:()=>Sn,getParticipantEventDetails:()=>XT,getParticipantIdFinishingPositions:()=>fT,getParticipantMembership:()=>JT,getParticipantResults:()=>ku,getParticipantScaleItem:()=>wc,getParticipantSchedules:()=>ZT,getParticipantSignInStatus:()=>ty,getParticipantTimeItem:()=>sS,getParticipants:()=>Ft,getPersonRequests:()=>ki,getPolicyDefinitions:()=>Go,getPositionAssignments:()=>zp,getPositionsPlayedOff:()=>Cc,getPredictiveAccuracy:()=>Ty,getProfileRounds:()=>ml,getPublishState:()=>As,getRandomQualifierList:()=>RT,getRoundMatchUps:()=>Ke,getRounds:()=>Py,getScaleValues:()=>Aa,getScaledEntries:()=>ca,getScheduledRoundsDetails:()=>$u,getSchedulingProfile:()=>oi,getSchedulingProfileIssues:()=>my,getSeedingThresholds:()=>_S,getSeedsCount:()=>Hu,getStructureSeedAssignments:()=>sn,getTeamLineUp:()=>Ss,getTieFormat:()=>al,getTimeItem:()=>nn,getTournamentIds:()=>Np,getTournamentInfo:()=>bs,getTournamentPenalties:()=>nl,getTournamentPersons:()=>oy,getTournamentPoints:()=>il,getTournamentPublishStatus:()=>Ru,getTournamentStructures:()=>HS,getTournamentTimeItem:()=>cd,getValidGroupSizes:()=>Gp,getVenueData:()=>Ac,getVenuesAndCourts:()=>Ro,isAdHoc:()=>cr,isCompletedStructure:()=>Do,isValidForQualifying:()=>CT,isValidMatchUpFormat:()=>Nr,matchUpActions:()=>Bd,participantScaleItem:()=>Po,participantScheduledMatchUps:()=>Sy,positionActions:()=>MT,publicFindCourt:()=>PS,publicFindVenue:()=>US,tallyParticipantResults:()=>Fa,tieFormatGenderValidityCheck:()=>km,tournamentMatchUps:()=>hl,validMatchUp:()=>pg,validMatchUps:()=>Br,validateCollectionDefinition:()=>eu,validateLineUp:()=>Cd});function z_(){return`
|
|
4
|
+
`)}function eD({participantResults:t,participantIds:e,attribute:r}){return rD({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 rD(t){return(t.participantIds||Object.keys(t.participantResults)).reduce((r,n,o)=>(r.push({participantId:n,i:o,results:t.participantResults[n]}),r),[])}var zG=[{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}],nD={matchUpsPct:20,tieMatchUpsPct:16,pointsPct:4,gamesPct:8,setsPct:12};function oD(t){let{requireCompletion:e=!0,participantResults:r,subOrderMap:n,tallyPolicy:o}=t,i=[];if(e&&!QG(t))return{};let s=["tieMatchUpsWon","tieSinglesWon","tieDoublesWon","matchUpsWon","pointsWon","gamesWon","setsWon","gamesPct","setsPct","pointsPct","matchUpsPct"].includes(o?.groupOrderKey)?o.groupOrderKey:"matchUpsWon",a=eD({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=Mv({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=Er(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(nD).filter(E=>o.GEMscore.includes(E)):Object.keys(nD)).map(E=>(S[E]||0)*Math.pow(10,nD[E].toFixed(3))).reduce((E,P)=>E+P,0)}}function QG({participantResults:t,participantsCount:e}){let n=rD({participantResults:t}).filter(o=>e-1===o.results.matchUpsWon+o.results.matchUpsLost+o.results.matchUpsCancelled);return e===n.length}function XG({disableHeadToHead:t,participantIds:e,matchUpFormat:r,groupTotals:n,tallyPolicy:o,attribute:i,idsFilter:s,matchUps:a,reversed:c}){let{participantResults:u}=ku({participantIds:s&&e,groupingTotal:n&&i,matchUpFormat:r,tallyPolicy:o,matchUps:a}),p=eD({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=Mv({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 Mv({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=JG({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||zG).filter(m=>{let d=!(Jt(m.maxParticipants)&&r?.length>m.maxParticipants);return d||s.push(m),d});return s.length&&a.push({excludedDirectives:s,participantIds:r}),p.every(({attribute:m,reversed:d,idsFilter:l,groupTotals:f,disableHeadToHead:g})=>(c=XG({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 JG({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 Fa({policyDefinitions:t,generateReport:e,pressureRating:r,matchUpFormat:n,matchUps:o=[],subOrderMap:i,perPlayer:s}){if(!o?.length||!Br(o))return{error:no};let a=pt(o.map(({structureId:y})=>y));if(a.length!==1)return _({result:{error:B,info:"Maximum one structureId"},stack:"tallyParticipantResults",context:{structureIds:a}});let c=o.filter(y=>y&&y.matchUpStatus!=="BYE"),u=c.length&&pt(c.map(({drawPositions:y})=>y).flat()).length,p=c.filter(y=>Ts({matchUp:y})).length===c.length;p||(s=0);let m=o.every(({matchUpType:y,tieMatchUps:E})=>y===Wt&&E?.every(P=>Ts({matchUp:P}))),d=t?.[kf],l=o.filter(y=>Ts({matchUp:y})??y.matchUpType===Wt),{participantResults:f}=ku({matchUps:l,pressureRating:r,matchUpFormat:n,tallyPolicy:d,perPlayer:s}),g,I,{groupOrder:h,report:S}=oD({matchUps:l,participantResults:f,participantsCount:u,matchUpFormat:n,subOrderMap:i,tallyPolicy:d});if(r&&ZG({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}=oD({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||Dr({tally:!0})){let y=Nv({matchUps:o,report:g,order:I});Dr({tally:!0})&&console.log(y),T.readableReport=y}return T}function ZG({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 iT({positionAssignments:t}){let e=(t||[]).filter(Hr(ao)).map(i=>{let{extension:s}=mt({element:i,name:fc}),a=dt(s?.value),c=!isNaN(a)&&a;return c&&{participantId:i.participantId,subOrder:c}}).filter(Boolean),r=e.map(({subOrder:i})=>i),n=Er(r);return{subOrderMap:Object.assign({},...e.filter(({subOrder:i})=>n[i]===1).map(({participantId:i,subOrder:s})=>({[i]:s})))}}function Ld({positionAssignments:t,tournamentRecord:e,drawDefinition:r,matchUpFormat:n,matchUps:o,event:i}){if(!Br(o))return{error:B};if(!t)return{error:B};let{policyDefinitions:s}=Go({policyTypes:[kf],tournamentRecord:e,drawDefinition:r,event:i}),{subOrderMap:a}=iT({positionAssignments:t}),c=o.length?Fa({policyDefinitions:s,matchUpFormat:n,subOrderMap:a,matchUps:o}):void 0;if(c?.error)return c;let{participantResults:u={},bracketComplete:p,report:m}=c??{},d=Object.keys(u);return t.forEach(l=>{let{participantId:f}=l;if(d.includes(f)){let g={value:u[f],name:Lo};At({element:l,extension:g}),u[f].ties||Ir({element:l,name:fc})}else Ir({element:l,name:Lo}),Ir({element:l,name:fc})}),bt({drawDefinition:r}),{...C,participantResults:u,bracketComplete:p,report:m}}function sT({matchUps:t,matchUpId:e}){return{matchUp:(t||[]).find(n=>n.matchUpId===e)}}function Vt(t){let e=et(t,[{[Ce]:!0,[gn]:!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=[]}=hn({drawDefinition:i}),d=t.contextContent||o&&Zn({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}=sT({matchUps:f,matchUpId:a});if(g)return{matchUp:g,structure:l}}return{error:we}}function $p(t){return!ht(t)||!t.notes?{error:st}:ht(t.element)?!kt(t.notes)&&!t.notes?.testing?{error:B}:(Object.assign(t.element,{notes:t.notes}),{...C}):{error:B}}function Fg(t){return ht(t)?ht(t.element)?(t.element.notes&&delete t.element.notes,{...C}):{error:B}:{error:st}}var Gu={matchUpStatus:Qt,matchUpStatusCodes:[],score:{scoreStringSide1:"",scoreStringSide2:"",sets:void 0},matchUpFormat:void 0,winningSide:void 0};function Yn(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:[rn],tournamentRecord:s,drawDefinition:a,structure:o,event:d})?.appliedPolicies,h=n.matchUpType===Wt;if(h&&a){if(m&&n.matchUpId!==m){let U=Vt({drawDefinition:a,matchUpId:m,event:d});if(!U.matchUp)return{error:we};({matchUp:n,structure:o}=U)}}else n.matchUpId!==m&&console.log("!!!!!");c&&[Bt,oe].includes(c)||u?Object.assign(n,{...Gu}):f&&(n.score=f);let S=c&&n?.matchUpStatus===Gt&&c!==Gt;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}=Vt({drawDefinition:a,matchUpId:m,event:d})),c&&!n.winningSide&&he(n)&&!ae.includes(c)&&![gc,ls,mn].includes(c)&&(n.matchUpStatus=Hn);let T;if((S&&n?.processCodes?.length||c===Gt)&&(T=I?.[rn]?.processCodes?.incompleteAssignmentsOnDefault),!n.collectionId){let U=o?.structureType===Ve,N=cr({structure:o});if(gd({drawDefinition:a,structure:o})||N||U){let D=b=>{r=h?"SET1-S:T100":r??n.matchUpFormat??b?.matchUpFormat??a?.matchUpFormat??d?.matchUpFormat;let O=h?{matchUpTypes:[Wt]}:void 0,{matchUps:v}=yt({afterRecoveryTimes:!1,tournamentRecord:s,inContext:!0,matchUpFilters:O,drawDefinition:a,structure:b,event:d});return N&&(b.positionAssignments=pt(v.flatMap(x=>(x.sides??[]).map(F=>F.participantId)).filter(Boolean)).map(x=>({participantId:x}))),Ld({positionAssignments:b.positionAssignments,tournamentRecord:s,drawDefinition:a,matchUpFormat:r,matchUps:v,event:d})},M=U&&o.structures.find(b=>b?.matchUps.find(O=>O.matchUpId===m)),R=D(M||o);if(R.error)return _({result:R,stack:e})}}if(l){let U=$p({element:n,notes:l});if(U.error)return _({result:U,stack:e})}let y=s?.tournamentId,E=Lr().topics.includes(Rp),P=(E||T)&&Pe({drawDefinition:a}),A=P&&ie({matchUpFilters:{matchUpIds:[m]},nextMatchUps:!0,tournamentRecord:s,inContext:!0,drawDefinition:a,matchUpsMap:P}).matchUps?.[0];if(E&&A&&Cb({tournamentId:y,inContextMatchUp:A}),Array.isArray(T)&&A&&!A.sides?.every(({participantId:U})=>U))if(c===Gt)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 Fd(t){let{propagateExitStatus:e,matchUpStatusCodes:r,autoCalcDisabled:n,inContextMatchUp:o,matchUpStatus:i,dualMatchUp:s,structure:a,matchUp:c}=t,u=Oa({matchUpStatus:i})||[po,vr].includes(i)&&s||n,p=c?.sides?.map(h=>h.participantId).filter(Boolean).length||o?.sides?.map(h=>h.participantId).filter(Boolean).length,m="attemptToModifyScore";if(!(cr({structure:a})&&p===1||i===Gt&&p||tV({structure:a,matchUp:c,inContextMatchUp:o})||t.appliedPolicies?.[rn]?.requireParticipantsForScoring===!1||pr(i)&&p===1&&e))return _({result:{error:Ql},stack:m});let f=[Bt].includes(i),g=u?i:t.winningSide&&ge||mn,I=Yn({...t,winningSide:t.winningSide,matchUpStatusCodes:u&&r||[],matchUpStatus:g,context:m,removeScore:f});return _({result:I,stack:m})}function tV({structure:t,matchUp:e,inContextMatchUp:r}){let{drawPositions:n}=e,{positionAssignments:o}=Ie({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 aT({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 Rv({collectionDefinition:t,groupValueNumbers:e,groupValueGroups:r,sideTieValues:n,tieMatchUps:o}){let i=o.filter(S=>S.collectionId===t.collectionId),s=[0,0],a=[0,0],c=i.every(S=>ae.includes(S.matchUpStatus)),{collectionValueProfiles:u,collectionGroupNumber:p,collectionValue:m,matchUpValue:d,winCriteria:l,scoreValue:f,setValue:g}=t,I=p&&e.includes(p),h=[0,0];if(i.forEach(S=>{S.winningSide&&(h[S.winningSide-1]+=1)}),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===ge||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=eV({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 eV({collectionDefinition:t,collectionPosition:e}){return(t.collectionValueProfiles||[])?.find(o=>o.collectionPosition===e)?.matchUpValue}function vc(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:B};if(!s)return{error:mr};let c=We({matchUp:s,drawDefinition:n,structure:i,event:a})?.tieFormat||t?.tieFormat;if(!c)return{error:ks};let u=ar({tieFormat:c});if(u.error)return u;let p=c?.collectionDefinitions||[],m=s?.tieMatchUps??[],d=[0,0],{groupValueGroups:l,groupValueNumbers:f}=aT(c);for(let y of p)Rv({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,O,v)=>O>=U.valueGoal?v+1:b,void 0);else{let b=Math.floor(A/2)+1;R=D.reduce((O,v,x)=>v>=b?x+1:O,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&&ae.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&&Vt({inContext:!0,drawDefinition:n,matchUpId:A})?.matchUp;if(U){let{completedTieMatchUps:N,order:D}=Fa({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 ka({inContextDualMatchUp:t,drawDefinition:e,tournamentId:r,dualMatchUp:n,eventId:o}){if(n){t||(t=Vt({matchUpId:n.matchUpId,inContext:!0,drawDefinition:e})?.matchUp);let{extension:i}=mt({element:e,name:wo}),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 or(t){if(t)return J(t,!1,!0)}function kg(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 cT({tournamentRecords:t,eventId:e,drawId:r}){let{tournamentIdMap:n}=kg({tournamentRecords:t});return(n?Object.keys(n):[]).find(i=>e&&n?.[i].includes(e)||r&&n?.[i].includes(r))}function go(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&&cT({tournamentRecords:c,...t});let p=u&&c[u];if(!p)return{error:q};let m=Vt({drawDefinition:r,event:a,matchUpId:s});if(m.error)return m;if(!m.matchUp)return{error:we};let{matchUp:d,structure:l}=m;if(!d.tieMatchUps)return{error:dr};ka({tournamentId:p?.tournamentId,eventId:a?.eventId,dualMatchUp:d,drawDefinition:r});let{extension:f}=mt({name:Ua,element:d});if(f?.value)if(o)Ir({element:d,name:Ua});else return{...C,score:d.score};let g=We({drawDefinition:r,structure:l,matchUp:d,event:a})?.tieFormat;d.tieFormat=or(g);let I=vc({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&&ge||Ig({matchUpStatus:n??d.matchUpStatus,tieMatchUps:d.tieMatchUps,winningSide:d.winningSide,score:P})&&Hn||Qt,N=!!(d.winningSide&&!A),D=d.tieMatchUps.find(({score:R,winningSide:b,matchUpStatus:O})=>R?.sets?.length&&(R.sets[0].side1Score||R.sets[0].side2Score)||O&&ae.includes(O)||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 Yn({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 Cv({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}=Ie({structureId:I,drawDefinition:c}),E=T?.find(R=>R.drawPosition===o)?.participantId,P=s.target.structureId,{positionAssignments:A}=Ie({structureId:P,drawDefinition:c}),N=A?.find(R=>R.participantId===E)?.drawPosition,D=A?.filter(R=>{let b=f.includes(R.drawPosition),O=!R.participantId&&!R.bye&&!R.qualifier;return b&&O}).map(R=>R.drawPosition),M=D?.includes(g);if(E&&s.target.roundNumber===1&&M)jn({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&&jn({participantId:E,structureId:P,inContextDrawMatchUps:e,sourceMatchUpStatus:n,tournamentRecord:i,drawDefinition:c,drawPosition:R,matchUpsMap:m,event:d})}else if(N){let R=wa({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";console.log(R),_({stack:l,result:{error:R}})}if(S?.seedAssignments&&S.structureId!==P){let R=S.seedAssignments.find(({participantId:O})=>O===E),b=R?.participantId;R&&b&&ra({eventId:u?.eventId,structureId:P,...R,tournamentRecord:i,drawDefinition:c,participantId:b})}}else{let f=wa({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=Rd({lineUp:E}),gt({tournamentId:i?.tournamentId,eventId:u?.eventId,matchUp:S,context:l,drawDefinition:c})}}}return{...C}}function bv(t){let{loserMatchUpDrawPositionIndex:e,inContextDrawMatchUps:r,projectedWinningSide:n,propagateExitStatus:o,sourceMatchUpStatus:i,loserDrawPosition:s,tournamentRecord:a,loserTargetLink:c,drawDefinition:u,loserMatchUp:p,dualMatchUp:m,matchUpsMap:d,event:l}=t,f="directLoser",g=c.linkCondition,I=p.drawPositions||[],h=g===kn&&p.roundNumber===2&&Math.min(...I.filter(Boolean)),S=h||I[e],T=h||I[1-e],y=c.source.structureId,{structure:E}=at({structureId:y,drawDefinition:u}),{matchUps:P}=yt({afterRecoveryTimes:!1,inContext:!0,drawDefinition:u,structure:E,event:l}),U=P.filter(V=>V.drawPositions?.includes(s)).filter(V=>{let $=V.sides.find(W=>W.drawPosition===s),X=V.matchUpStatus===Bt||V.matchUpStatus===Gt&&!he(V);return $?.sideNumber===V.winningSide&&!X}),N=g===kn&&U.length===0,{positionAssignments:D}=Ie({structureId:y,drawDefinition:u}),R=D?.find(V=>V.drawPosition===s)?.participantId,b={loserParticipantId:R},O=c.target.structureId,{positionAssignments:v}=Ie({structureId:O,drawDefinition:u}),x=v?.filter(({drawPosition:V})=>I.includes(V)),F=x?.some(V=>V.participantId&&R&&V.participantId===R),w=o&&[Me,Bt,Gt].includes(i||"");if(F)return{...C,stack:f};let L=x?.filter(V=>{let $=I.includes(V.drawPosition),X=!V.participantId&&!V.bye&&!V.qualifier;return $&&X}).map(V=>V.drawPosition),k=L?.includes(S),G=c.target.roundNumber>1&&L?.length,H=c.target.roundNumber===1&&k;if(h){let V=K();if(V.context&&Object.assign(b,V.context),V.error)return _({result:V,stack:f})}else if(H){let V=j();if(V.context&&Object.assign(b,V.context),V.error)return _({result:V,stack:f})}else if(R&&G){L.sort(le);let V=L[0],$=jn({participantId:R,structureId:O,drawPosition:V,inContextDrawMatchUps:r,sourceMatchUpStatus:i,tournamentRecord:a,drawDefinition:u,matchUpsMap:d,event:l});if($.error)return _({result:$,stack:f});if(!$.error&&w&&o)return{stack:f,context:{progressExitStatus:!0,loserParticipantId:R}}}else return _({context:{loserDrawPosition:s,loserTargetLink:c,targetDrawPositionIsUnfilled:k},result:{error:k?Ls:CC},stack:f});if(E?.seedAssignments&&E.structureId!==O){let V=E.seedAssignments.find(({participantId:X})=>X===R),$=V?.participantId;V&&$&&ra({eventId:p?.eventId,structureId:O,...V,tournamentRecord:a,drawDefinition:u,participantId:$})}if(m&&n){let V=m.sides?.find($=>$.sideNumber===3-n);if(V?.lineUp){let{roundNumber:$,eventId:X}=p,{roundPosition:W}=m,it=$===1?2-W%2:1,z=d?.drawMatchUps?.find(({matchUpId:ot})=>ot===p.matchUpId),Q=[1,2].map(ot=>({...z.sides?.find(Rt=>Rt.sideNumber===ot)||{},sideNumber:ot}));z.sides=Q;let ut=z.sides.find(ot=>ot.sideNumber===it);ut&&(ut.lineUp=Rd({lineUp:V.lineUp}),gt({tournamentId:a?.tournamentId,matchUp:z,context:f,drawDefinition:u,eventId:X}))}}return _({result:{...C},stack:f,context:b});function K(){let V="loserLinkFedFMLC";return N?_({result:j(),stack:V}):_({result:Y(),stack:V})}function Y(){let V=Wr({drawPosition:T,structureId:O,tournamentRecord:a,drawDefinition:u,event:l});return _({result:V,stack:"assignLoserPositionBye"})}function j(){let V=R?jn({drawPosition:S,participantId:R,structureId:O,inContextDrawMatchUps:r,sourceMatchUpStatus:i,tournamentRecord:a,drawDefinition:u,matchUpsMap:d,event:l}):{error:se};return!V.error&&w&&o?{stack:f,context:{progressExitStatus:!0}}:_({result:V,stack:"assignLoserDrawPosition"})}}function uT(t){let e="directParticipants",r=Fd(t);if(r.error)return _({result:r,stack:e});let n=Oa({matchUpStatus:t.matchUpStatus}),{dualWinningSideChange:o,inContextDrawMatchUps:i,projectedWinningSide:s,propagateExitStatus:a,matchUpStatusCodes:c,tournamentRecord:u,drawDefinition:p,matchUpStatus:m,dualMatchUp:d,matchUpsMap:l,winningSide:f,targetData:g,matchUpId:I,structure:h,matchUp:S,event:T}=t,y=!!S.collectionId,E=cr({structure:h}),P=S.drawPositions,A;if(y){let{matchUpTieId:U,matchUpsMap:N}=t,D=go({appliedPolicies:t.appliedPolicies,matchUpId:U,tournamentRecord:u,drawDefinition:p,matchUpsMap:N,event:T});if(A=D&&{tieMatchUpResult:D},P=i.find(({matchUpId:R})=>R===U)?.drawPositions,!o)return _({result:{...C,...A},stack:e})}if(E)return _({result:{...C,...A},stack:e});if(P){let U=s?s-1:f-1,N=1-U,D=P[U],M=P[N],R={},{targetLinks:{loserTargetLink:b,winnerTargetLink:O,byeTargetLink:v},targetMatchUps:{winnerMatchUpDrawPositionIndex:x,loserMatchUpDrawPositionIndex:F,winnerMatchUp:w,loserMatchUp:L,byeMatchUp:k}}=g;if(w){let G=Cv({sourceMatchUpStatus:n&&m||ge,winnerMatchUpDrawPositionIndex:x,sourceMatchUpId:I,inContextDrawMatchUps:i,projectedWinningSide:s,winningDrawPosition:D,tournamentRecord:u,winnerTargetLink:O,drawDefinition:p,winnerMatchUp:w,dualMatchUp:d,matchUpsMap:l,event:T});if(G.error)return _({result:G,stack:e})}if(L){let G=bv({sourceMatchUpStatus:n&&m||ge,sourceMatchUpStatusCodes:c||[],sourceWinningSide:f,loserMatchUpDrawPositionIndex:F,sourceMatchUpId:I,inContextDrawMatchUps:i,projectedWinningSide:s,propagateExitStatus:a,loserDrawPosition:M,tournamentRecord:u,loserTargetLink:b,drawDefinition:p,loserMatchUp:L,winningSide:f,matchUpsMap:l,dualMatchUp:d,event:T});if(G.context?.progressExitStatus&&Object.assign(R,G.context,{sourceMatchUpStatus:n&&m||ge,sourceMatchUpStatusCodes:c||[],loserMatchUp:L,matchUpsMap:l}),G.error)return _({result:G,stack:e})}if(k){let G=k.drawPositions||[],H=Math.min(...G.filter(Boolean)),K=v.target.structureId,Y=Wr({drawPosition:H,structureId:K,tournamentRecord:u,drawDefinition:p,event:T});if(Y.error)return _({result:Y,stack:e})}return _({result:{...C,...A},stack:e,context:R})}else return _({result:{error:Ja},stack:e})}function kd(t){let e="genPlayoffStructure";if(!t.drawDefinition)return _({result:{error:Z},stack:e});let r=Lu(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:_t},stack:e});if(y.structureType===Ve||y.structures)return gv({sourceStructureId:y.structureId,...t,...r,drawDefinition:T});let{playoffRoundsRanges:E,playoffRounds:P}=r,{playoffPositionsReturned:A,error:U,playoffSourceRounds:N,playoffRoundsRanges:D}=XS(t);if(U)return _({result:{error:U},stack:e});let M=l?.length&&Object.assign({},...l),R=f||typeof l=="object"&&l.map(W=>Object.keys(W)).flat(),b=Array.isArray(R)&&R.map(W=>!isNaN(W)&&dt(W)).filter(Boolean);if(b){if(!Array.isArray(b))return _({result:{error:B},context:{validRoundNumbers:b},stack:e});b.forEach(W=>{if(!P?.includes(W))return _({result:{error:B},context:{roundNumber:W},stack:e})})}u&&u.forEach(W=>{if(!A?.includes(W))return _({result:{error:B},context:{playoffPosition:W},stack:e})});let O=b||N,v=b?E:D,x=[],F=[];for(let W of O??[]){let it=v?.find(qt=>qt.roundNumber===W);if(!it)return _({result:{error:B},context:{roundNumber:W},stack:e});let z=it.finishingPositions.length,Q=Math.min(...it.finishingPositions)-1,ut=2,ot=W&&M?.[W]&&ut+M[W]-1,Dt=Rc({exitProfile:`0-${W}`,addNameBaseToAttributeName:o,playoffStructureNameBase:i,finishingPositionOffset:Q,playoffAttributes:c,exitProfileLimit:d,stage:fe,roundOffset:0,drawDefinition:T,sequenceLimit:ot,stageSequence:ut,drawSize:z,idPrefix:g,isMock:I,uuids:S,finishingPositionNaming:s,finishingPositionLimit:a,roundOffsetLimit:p});if(Dt.error)return _({result:Dt,stack:e});let{structures:Rt,links:De}=Dt;if(Rt?.length&&x.push(...Rt),De?.length&&F.push(...De),Dt.structureId&&W){let qt={linkType:so,source:{structureId:n,roundNumber:W},target:{structureId:Dt.structureId,feedProfile:Nn,roundNumber:1}};F.push(qt)}}if(!x.length)return _({result:{error:B},info:"No structures generated",stack:e});T.structures.push(...x),T.links.push(...F);let{matchUps:w,matchUpsMap:L}=ie({inContext:!0,drawDefinition:T}),k=x.map(({structureId:W})=>W),G=w?.filter(({structureId:W})=>k.includes(W)).map(Ue),H=L?.drawMatchUps?.filter(({matchUpId:W})=>G?.includes(W));if(H?.length){let W=We({drawDefinition:T,event:h})?.tieFormat;W&&H.forEach(it=>{let{tieMatchUps:z}=Li({matchUp:it,tieFormat:W,isMock:I});Object.assign(it,{tieMatchUps:z,matchUpType:Wt})})}w?.filter(W=>Ts({matchUp:W})&&W.structureId===n)?.forEach(W=>{let{matchUpId:it,score:z,winningSide:Q}=W,ut=ur({inContextDrawMatchUps:w,drawDefinition:T,matchUpId:it}),ot=uT({inContextDrawMatchUps:w,tournamentRecord:m,drawDefinition:T,matchUpsMap:L,winningSide:Q,targetData:ut,matchUpId:it,structure:y,matchUp:W,score:z,event:h});ot.error&&console.log(ot.error)}),w?.filter(W=>W.matchUpStatus==="BYE"&&W.structureId===n)?.forEach(W=>{let{matchUpId:it}=W,z=ur({inContextDrawMatchUps:w,drawDefinition:T,matchUpId:it}),{targetLinks:{loserTargetLink:Q},targetMatchUps:{loserMatchUpDrawPositionIndex:ut,loserMatchUp:ot}}=z;if(Q&&ot){let Dt=Q.target.structureId,Rt=ot.drawPositions[ut],De=Wr({drawPosition:Rt,structureId:Dt,tournamentRecord:m,drawDefinition:T,event:h});De.error&&console.log(De.error)}});let j=[],V=rs({inContextDrawMatchUps:w,drawDefinition:T,matchUpsMap:L}).goesToMap,{structure:$}=at({drawDefinition:t.drawDefinition,structureId:n}),{matchUps:X}=yt({structure:$});return X.forEach(W=>{let it=V?.loserMatchUpIds[W.matchUpId];if(it&&W.loserMatchUpId!==it){W.loserMatchUpId=it;let Q={tournamentId:m?.tournamentId,eventId:t.event?.eventId,context:e,matchUp:W};j.push(Q)}let z=V?.winnerMatchUpIds[W.matchUpId];if(z&&W.winnerMatchUpId!==z){W.winnerMatchUpId=z;let Q={tournamentId:m?.tournamentId,eventId:t.event?.eventId,context:e,matchUp:W};j.push(Q)}}),{structures:x,matchUpModifications:j,links:F,drawDefinition:T,...C}}function pT({element:t}){if(!t)return{error:B};if(!t.timeItems)return{};if(!Array.isArray(t.timeItems))return{error:B};let e=(r,n)=>(o,i)=>(i[r]&&(o[i[r]]=i[n]),o);return t.timeItems.reduce(e("itemType","itemValue"),{})}function ro(t){let{duplicateValues:e=!0,creationTime:r=!0,removePriorValues:n,timeItem:o}=t;if(!o)return{error:mf};let i=oS(t);if(i.error)return i;if(!(ht(o)&&kt(o.itemType)&&Object.keys(o).includes("itemValue")))return{error:pf};if(!i.timeItems)i.timeItems=[];else if(rV({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 rV({element:t,duplicateValues:e,timeItem:r}){let{itemType:n,itemSubTypes:o,itemValue:i}=r,s=n&&nn({itemSubTypes:o,itemType:n,element:t})?.timeItem;return s&&JSON.stringify(s?.itemValue)===JSON.stringify(i)&&!e}function Gg({creationTime:t=!0,removePriorValues:e,tournamentRecord:r,duplicateValues:n,participantId:o,timeItem:i}){if(!r)return{error:q};if(!o)return{error:se};let s=Uo({tournamentRecord:r,participantId:o});return s.error?s:ro({element:s.participant,removePriorValues:e,duplicateValues:n,creationTime:t,timeItem:i})}function _c(t){let{removePriorValues:e,tournamentRecord:r,duplicateValues:n,creationTime:o,timeItem:i}=t;if(!r)return{error:q};let s=ro({element:r,removePriorValues:e,duplicateValues:n,creationTime:o,timeItem:i});if(s.error)return s;let a=pT({element:r});return lt({payload:{parentOrganisation:r.parentOrganisation,tournamentId:r.tournamentId,timeItemValues:a},topic:Xi}),s}function is(t){let{removePriorValues:e,duplicateValues:r,creationTime:n,timeItem:o,event:i}=t;return i?ro({removePriorValues:e,duplicateValues:r,element:i,creationTime:n,timeItem:o}):{error:qr}}function iD(t){return Bg({...t,itemType:"attachConsolationStructures"})}function Vg(t){return Bg({...t,itemType:"attachPlayoffStructures"})}function Bg({itemType:t="attachStructures",matchUpModifications:e,tournamentRecord:r,drawDefinition:n,structures:o,links:i=[],event:s}){let a="attachStructures";if(!n)return{error:Z};if(!Array.isArray(o)||!Array.isArray(i))return _({result:{error:B},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:If},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),rs({drawDefinition:n});let f=o.map(h=>yt({structure:h})?.matchUps||[]).flat();Fo({tournamentId:r?.tournamentId,eventId:s?.eventId,drawDefinition:n,matchUps:f});let g=o.map(({structureId:h})=>h);if(bt({drawDefinition:n,structureIds:g}),e?.length){let h={};e.forEach(T=>{let 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(Hr("structureId"));if(r){let S={itemValue:{structureIds:g,drawId:n.drawId},itemType:t};ro({element:r,timeItem:S})}return{...C,addedStructureIds:I}}function Kp(t){let{structures:e,links:r,matchUpModifications:n,error:o}=kd(t);if(o)return{error:o};let i=t.drawDefinition;return Vg({tournamentId:t.tournamentRecord?.tournamentId,eventId:t.event?.eventId||t.eventId,matchUpModifications:n,drawDefinition:i,structures:e,links:r})}function ss(t){let e=et(t,[{_anyOf:{[Re]:!1,[ne]:!1,[Ce]:!1,[co]:!1},[_f]:!0}]);if(e.error)return e;let r=[],n=t.drawDefinition??t.event??((t.tournamentId||!t.tournamentRecords)&&t.tournamentRecord);if(n){let o=Ov(t,n);if(o.error)return o;r.push(...o?.applied??[]),t.drawDefinition&&bt({drawDefinition:t.drawDefinition,tournamentId:t.tournamentId})}else if(t.tournamentRecords){let o=Object.keys(t.tournamentRecords);if(!o.length)return{error:q};for(let i of o){let s=t.tournamentRecords[i],a=Ov(t,s);if(a.error)return a;r.push(...a?.applied??[])}}else return{error:q};return r.length?{...C,applied:r}:{error:$I}}function Ov(t,e){let r=Tt(t).appliedPolicies??{};e.extensions||(e.extensions=[]);let n=[],o=Object.keys(t.policyDefinitions);if(!o.length)return{error:op};for(let i of o)if(!r[i]||t.allowReplacement){let s=t.policyDefinitions[i];if(!s)continue;if(!ht(s))return{error:B};let{policyName:a,...c}=s;if(!c||!Object.keys(c).length||a&&!kt(a))return{error:B};r[i]=t.policyDefinitions[i],n.push(i)}return n?.length?{...At({element:e,extension:{name:du,value:r}}),applied:n}:{applied:n,error:$I}}function Hg({tournamentRecord:t,drawDefinition:e,flightProfile:r,drawName:n,drawId:o,event:i}){if(!n||typeof n!="string")return _({result:{error:B},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:pn,value:{...r,flights:r.flights}};xo({event:i,extension:a})}return e&&(e.drawName=n,bt({tournamentId:t?.tournamentId,drawDefinition:e})),!s&&!e?{error:Z}:{...C,flight:s}}function sD({tournamentRecord:t,drawDefinition:e,drawUpdates:r,drawId:n,event:o}){if(!ht(r))return{error:B};let i=Ht({event:o}).flightProfile,s=r.drawName&&Hg({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:pn,value:{...i,flights:i.flights}};xo({event:o,extension:c})}return e&&(r.policyDefinitions&&ss({policyDefinitions:r.policyDefinitions,drawDefinition:e}),bt({tournamentId:t?.tournamentId,drawDefinition:e})),{...C}}function aD({tournamentRecord:t,removeScheduling:e,drawDefinition:r}){if(!r)return{error:Z};let n=Pe({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!=="BYE"&&Object.assign(I,Gu),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&&![lo,Jo,Ji,dg,Zi,ts].includes(h.itemType))),gt({tournamentId:t?.tournamentId,context:"resetDrawDefiniton",drawDefinition:r,matchUp:I})}}}r.extensions=r.extensions.filter(s=>s.name!==lc);let i=(r.structures||[]).map(({structureId:s})=>s);return bt({drawDefinition:r,structureIds:i}),{...C}}function Vu({tournamentRecord:t}){if(!t)return{error:q};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}=_u({drawDefinition:o}),p=r[i],d=(o?.structures||[]).map(E=>{let{stage:P,stageSequence:A,structureId:U}=E,N=$s[P],{inContextStructureMatchUps:D}=va({drawDefinition:o,structure:E,event:p}),M=D?.filter(({winningSide:Y})=>Y),R=M.filter(Boolean).length||0;a+=R,c+=D.length-a;let b=Math.max(M.filter(({roundNumber:Y})=>Y===1).map(({roundPosition:Y})=>Y)),{positionAssignments:O}=Ct({structure:E}),v=O?.filter(({participantId:Y})=>Y);s+=v?.length??0;let x=(O?.length??0)-(v?.length??0),{roundMatchUps:F,roundProfile:w,roundNumbers:L,maxMatchUpsCount:k}=Ke({matchUps:D}),G=w&&Object.keys(w).filter(Y=>!w[Y].inactiveRound).map(Y=>parseInt(Y)),H=w&&Object.keys(w).filter(Y=>w[Y].inactiveRound).map(Y=>parseInt(Y)),K=w&&Object.values(w).every(Y=>Y.inactiveRound);return{positionsAssignedCount:v?.length??0,maxWinningSideFirstRoundPosition:b,unassignedPositionsCount:x,inactiveStructure:K,maxMatchUpsCount:k,inactiveRounds:H,roundMatchUps:F,activeRounds:G,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 cD({matchPlayDrawPositions:t=!0,tournamentRecord:e,drawDefinition:r,drawId:n}){if(!e)return{error:q};if(!r)return{error:Z};let o=[],{drawsAnalysis:i}=Vu({tournamentRecord:e});if(i.canBePruned.includes(n)){let s=i.matchPlay.includes(n),a=i.drawAnalysis[n],{structures:[c]}=hn({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}_n({tournamentId:e?.tournamentId,matchUpIds:d,drawDefinition:r}),bt({drawDefinition:r})}return{...C,matchUps:o}}function uD({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:Fs};if(!o)return{error:Pr};if(a){let c=Wr({tournamentRecord:t,drawDefinition:e,drawPosition:n,structureId:o,event:s});if(c.error)return c}else{if(i)return{error:pp};{let c=jn({tournamentRecord:t,drawDefinition:e,participantId:r,drawPosition:n,structureId:o,event:s});if(c.error)return c}}return{...C}}function mT(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:_t};let o=r.structures?.find(c=>c.structureId===n);if(!o)return{error:_t};let i=o?.matchUps,s=i?.find(c=>!!c.roundPosition);if(o.structures||s||o.finishingPosition===zi)return{error:si};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 pD(t){let e=et(t,[{[Ce]:!0},{[Ks]:{[mc]:!1,roundNumbers:!1},[kr]:B,[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=mT(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||he({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)),_n({tournamentId:i?.tournamentId,matchUpIds:[...I,...g],action:"deleteAdHocMatchUps",eventId:a?.eventId,drawDefinition:s});let h=pt(u.matchUps.map(Hr("roundNumber"))),S=PC(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});cr({structure:u})&&(u.positionAssignments=pt(P.flatMap(N=>(N.sides??[]).map(D=>D.participantId)).filter(Boolean)).map(N=>({participantId:N})));let U=Ld({positionAssignments:u.positionAssignments,tournamentRecord:i,drawDefinition:s,matchUpFormat:T,matchUps:P,event:a});U.error&&console.log(U)}bt({structureIds:[p],eventId:a?.eventId,drawDefinition:s})}return!g.length&&d.length?{error:oc}:{...C,deletedMatchUpsCount:[...g,...I].length}}function mD({removeCompletedMatchUps:t,tournamentRecord:e,drawDefinition:r,structureId:n,roundNumber:o,event:i}){if(!e)return{error:q};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:si}:cr({structure:a})?nV({tournamentId:e.tournamentId,removeCompletedMatchUps:t,eventId:i.eventId,drawDefinition:r,roundNumber:o,structure:a}):(console.log("not implemented"),{...C})}function nV({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&&(!ae.includes(d.matchUpStatus)||t);return l&&(c.push(d.matchUpId),d.tieMatchUps&&a.push(...d.tieMatchUps.map(Ue))),!l});c.length&&(_n({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 Gd(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:Pr};if(!Br(o))return{error:B,info:li("matchUps")};let a=n.structures?.find(l=>l.structureId===s);if(!a)return{error:_t};let u=(a?.matchUps).find(l=>!!l.roundPosition);if(a.structures||u||a.finishingPosition===zi)return{error:si};let p=ye({tournamentRecord:r,inContext:!1})?.matchUps?.map(Ue)??[],m=o.map(Ue);if(ke(p,m))return{error:YA,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||(Fo({tournamentId:r?.tournamentId,matchUps:[...d,...o],eventId:i?.eventId,drawDefinition:n}),bt({drawDefinition:n,structureIds:[s]})),{...C}}function dD({tournamentRecord:t,drawDefinition:e,drawPosition:r,structureId:n,subOrder:o,event:i}){if(!e)return{error:Z};if(!n)return{error:Pr};if(!r)return{error:Fs};let{structure:s}=at({drawDefinition:e,structureId:n});if(!s)return{error:_t};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&&At({element:u,extension:{name:fc,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 Ld({positionAssignments:c,tournamentRecord:t,drawDefinition:e,matchUpFormat:f,matchUps:l,event:i}),bt({drawDefinition:e,structureIds:[n]}),{...C}}var PD={};Xt(PD,{addGoesTo:()=>rs,allPlayoffPositionsFilled:()=>WS,checkValidEntries:()=>Hd,findDrawDefinition:()=>gT,getAssignedParticipantIds:()=>wi,getAvailableMatchUpsCount:()=>Vd,getAvailablePlayoffProfiles:()=>Lu,getDrawDefinitionTimeItem:()=>iS,getDrawParticipantRepresentativeIds:()=>lT,getDrawStructures:()=>hn,getDrawTypeCoercion:()=>Bu,getEligibleVoluntaryConsolationParticipants:()=>dT,getMatchUpsMap:()=>Pe,getParticipantIdFinishingPositions:()=>fT,getPositionAssignments:()=>zp,getPositionsPlayedOff:()=>Cc,getRandomQualifierList:()=>RT,getSeedingThresholds:()=>_S,getSeedsCount:()=>Hu,getStructureSeedAssignments:()=>sn,getTeamLineUp:()=>Ss,getValidGroupSizes:()=>Gp,isAdHoc:()=>cr,isCompletedStructure:()=>Do,isValidForQualifying:()=>CT,positionActions:()=>MT});function dT({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?to({contextFilters:{stages:f},matchUpFilters:g,tournamentRecord:s,inContext:!0,event:l})?.matchUps??[]:nr({contextFilters:{stages:f},matchUpFilters:I,tournamentRecord:s,inContext:!0,drawDefinition:a})?.matchUps??[],T=bi({stage:$e,drawDefinition:a}).map(({participantId:L})=>L),y={},E={},P={},A={};o||(o=Go({policyTypes:[Bh],tournamentRecord:s,drawDefinition:a,event:l}).policyDefinitions);let U=o?.[Bh];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!==oe||L.finishingRound&&n&&L.finishingRound>=n||L.finishingRound&&i&&L.finishingRound<=i)continue;let k=L.sides?.find(({sideNumber:H})=>L.winningSide&&H===3-L.winningSide),G=L.sides?.find(({sideNumber:H})=>L.winningSide&&H===L.winningSide);if(L.sides?.forEach(H=>{let K=H?.participant?.participantId;K&&(P[K]=H.participant,L.matchUpStatus===oe&&!u&&(E[K]=H.participant,y[K]||(y[K]=0),(!L.matchUpStatus||!t.includes(L.matchUpStatus))&&(y[K]+=1)))}),k?.participant){let H=k.participant.participantId;E[H]=k.participant,y[H]||(y[H]=0),L.matchUpStatus&&!t.includes(L.matchUpStatus)&&(y[H]+=1)}if(G?.participant){let H=G.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=>![mo,Vr].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),O=L=>!u||(y[L]||0)>=0,v=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)&&O(L.participantId)&&v(L.participantId)&&x(L.participantId)&&F(L.participantId)).map(L=>({...L,individualParticipants:L.individualParticipantIds?.map(k=>s?.participants?.find(G=>G.participantId===k))})),losingParticipantIds:M,...C}}function Vd(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:Pr};let i=r.structures?.find(g=>g.structureId===o);if(!i)return{error:_t};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===zi)return{error:si};let u=r?.entries?.filter(g=>{let I=g.entryStatus;return Xr.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 lT({drawDefinition:t}){let e=mt({name:"participantRepresentatives",element:t});return e.error?e:{representativeParticipantIds:e.extension?.value||[]}}function vv({tournamentParticipants:t,drawDefinition:e,event:r}){if(!e)return{error:Z};let n=ie({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 fT({byeAdvancements:t=!1,tournamentRecord:e,drawDefinition:r}){if(!r)return{error:Z};let{participantIds:n,participantIdMatchUps:o}=vv({tournamentParticipants:e?.participants,drawDefinition:r}),i=n?.map(s=>{let c=o[s].filter(d=>[ge,"BYE"].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 jo({tournamentRecords:t,tournamentRecord:e,tournamentId:r,drawId:n}){if(!e&&!t)return{error:q};if(!n)return{error:cn};if(!e&&t){if(typeof r!="string"&&(r=cT({tournamentRecords:t,drawId:n}),!r))return{error:ha};if(e=t[r],!e)return{error:q}}let o=e&&ze({tournamentRecord:e,drawId:n});return o?.drawDefinition?{drawDefinition:o.drawDefinition,event:o.event,tournamentRecord:e,...C}:_({result:{error:br},stack:"findDrawDefinition"})}function gT(t){let{drawDefinition:e,error:r}=jo(t);return r?{error:r}:{drawDefinition:J(e)}}function _v({tournamentParticipants:t,returnParticipants:e,drawPosition:r,participant:n,drawId:o,event:i}){let s=i?.entries?.filter(({entryStatus:a})=>[Vr,Ci].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:nv,availableIndividualParticipantIds:s,availableIndividualParticipants:c,existingIndividualParticipantIds:a,existingIndividualParticipants:u,type:vg},!1,!1,!0)}}return{}}function Fi(t){let{inContextDrawMatchUps:e,targetData:r,drawDefinition:n,relevantLink:o}=t;if(o?.linkCondition===kn&&r?.matchUp?.matchUpStatus==="BYE")return!1;let{targetMatchUps:{loserMatchUp:s,winnerMatchUp:a},targetLinks:c}=r,u=s&&ur({matchUpId:s.matchUpId,inContextDrawMatchUps:e,drawDefinition:n}),p=u?.targetMatchUps?.loserMatchUp,m=u?.targetMatchUps?.loserMatchUpDrawPositionIndex,d=p?.sides[m]?.participant,l=pr(s?.matchUpStatus),f=l&&!d,g=s?.sides?.reduce((E,P)=>P?.participant?++E:E,0)??0,I=s?.winningSide&&l&&g===1,h=a?.drawPositions?.filter(Boolean).length||0;if(!I&&(s?.winningSide&&!f||a?.winningSide&&h===2&&(!a.feedRound||!pr(a?.matchUpStatus))))return!0;let S=a&&ur({matchUpId:a.matchUpId,inContextDrawMatchUps:e,drawDefinition:n}),T=u&&Fi({relevantLink:c?.loserTargetLink,targetData:u,inContextDrawMatchUps:e,drawDefinition:n});return!!(S&&Fi({targetData:S,inContextDrawMatchUps:e,drawDefinition:n})||T)}var IT={[Jn]:{policyName:"positionActionsDefault",enabledStructures:[{stages:[ct,rt],stageSequences:[1],enabledActions:[],disabledActions:[]},{stages:[],stageSequences:[],enabledActions:[xu,ia,Wp,oa],disabledActions:[]}],disbledStructures:[],otherFlightEntries:!1,activePositionOverrides:[]}};var Wg="positionAction",hT="matchUpAction";function ST({actionType:t=Wg,appliedPolicies:e,drawDefinition:r,structure:n}){let o=t===Wg&&Jn||t===hT&&er,i=t===Wg&&IT||t===hT&&IP,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 fD({activePositionOverrides:t,activeDrawPositions:e,action:r}){return r&&t.includes(r)?!0:!e.length}function TT({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 qn({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 gD="replaceTieMatchUpParticipantId",ID="assignTieMatchUpParticipantId",yT="removeTieMatchUpParticipantId",hD="assignMatchUpSideParticipant",xv="removeMatchUpSideParticipant",SD="substituteParticipant",ET="REMOVE_SUBSTITUTION",TD="REPLACE_PARTICIPANT",jg="REMOVE_PARTICIPANT",AT="setMatchUpStatus",UT="SUBSTITUTION",yD="SCHEDULE",oV="PENALTY",PT="REFEREE",ED="STATUS",DT="START",AD="SCORE";var wv={REPLACE_TEAM_POSITION_METHOD:gD,ASSIGN_TEAM_POSITION_METHOD:ID,REMOVE_TEAM_POSITION_METHOD:yT,REPLACE_PARTICIPANT:TD,SUBSTITUTION_METHOD:SD,REMOVE_SUBSTITUTION:ET,REMOVE_PARTICIPANT:jg,SCHEDULE_METHOD:AT,SUBSTITUTION:UT,SCHEDULE:yD,PENALTY:oV,REFEREE:PT,STATUS:ED,SCORE:AD,START:DT,END:"END"};function Lv({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=en(o.gender)&&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||To(S)||L.sex===S||en(S)&&!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(Ia)(I)&&!P?.length||de(Gi)(I)&&(P?.length??0)<2)||!c&&(de(Ia)(I)&&(P?.length??0)<2||de(Gi)(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:ID,availableParticipants:b,type:Ms,payload:{participantId:void 0,tieMatchUpId:u,sideNumber:c,drawId:m}}),P?.length&&(!he(p)||d?.substitutions?.length)&&l.push({method:yT,type:jg,existingParticipantIds:P,payload:{participantId:void 0,tieMatchUpId:u,drawId:m}}),b?.length&&(!c&&P?.length||c&&d?.participant)&&l.push({availableParticipantIds:R,method:gD,availableParticipants:b,type:TD,existingParticipantIds:P,payload:{existingParticipantId:void 0,participantId:void 0,tieMatchUpId:u,drawId:m}}),qn({policyActions:i,action:ET})&&d?.substitutions?.length){let F=d.participant?.participantType===Et&&[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:yT,type:ET,substitutedParticipantIds:w,payload:{participantId:void 0,tieMatchUpId:u,drawId:m}})}let O=t?.[er],v=O?.substituteWithoutScore,x=O?.substituteAfterCompleted;if(qn({policyActions:i,action:UT})&&r.length===2&&(!c&&P?.length||c&&d?.participant)&&(v||he(p))&&(x||p.matchUpStatus&&!ae.includes(p.matchUpStatus))&&E?.length&&N.length){let F=E.map(St);l.push({info:"list of team players available for substitution",method:SD,availableParticipantIds:D,existingParticipantIds:F,availableParticipants:N,existingParticipants:E,type:UT,payload:{substituteParticipantId:void 0,existingParticipantId:void 0,sideNumber:c,matchUpId:u,drawId:m}})}return l}function Fv({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===Ms)?.availableParticipantIds,f=i?.[Jn]?.otherFlightEntries,g=i?.[Jn]?.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}=Xh({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===on&&UD({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&&![mo,Vr,Ci].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:ev,availableAlternatesParticipantIds:P,type:_g,availableAlternates:A})}:{}}function UD({restrictQualifyingAlternates:t,structure:e,entry:r}){let{stage:n}=e;if(!r.entryStage||r.entryStage===n||n===ct&&!t||r.entryStage===rt&&n===qe)return!0}function kv({eventEntries:t,structure:e}){let r=o=>o.entryStatus===on&&UD({structure:e,entry:o}),n=(o,i)=>(o.entryPosition||1/0)-(i.entryPosition||1/0);return t.filter(r).sort(n).map(St)}function Gv({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&&mi.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:hD,type:Ms,availableParticipantIds:T,participantsAvailable:y});let E=m?.entries??[],P=kv({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&&![mo,Vr,Ci].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:hD,type:on}),!he(u)&&s&&g){d.push({payload:{drawId:p,matchUpId:a,structureId:i,sideNumber:s},method:xv,type:jg});let N=w=>w.sides.map(St),D=({matchUpId:w})=>w!==u.matchUpId,M=w=>!he(w),R=u.sides?.find(w=>w.sideNumber!==s)?.participantId,O=l.filter(({roundNumber:w})=>w!==u.roundNumber).filter(D).map(N),v=[R,...O.filter(w=>w.includes(g)).flat()].filter(Boolean),x=w=>!v.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:ov,type:Yp,swappableParticipants:w})}}return d}function Bd(t){if(!t)return{error:B};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&&kt(t.tournamentId)&&t.tournamentRecords?.[t.tournamentId]);if(!u)return{error:q};if(!c||!kt(c))return{error:sr};if(a&&![1,2].includes(a))return _({result:{error:B},context:{sideNumber:a}});if(!e){let Q=(ye({tournamentRecord:u}).matchUps??[]).find(ot=>ot.matchUpId===c);r=(u?.events??[]).find(ot=>ot.eventId===Q?.eventId);let ut=(r?.drawDefinitions??[]).find(ot=>ot.drawId===Q?.drawId);ut&&(e=ut)}if(!e)return{error:Z};let p=Ft({withIndividualParticipants:!0,tournamentRecord:u}).participants,{drawId:m}=e,{matchUp:d,structure:l}=Vt({drawDefinition:e,matchUpId:c,event:r});if(!d)return{error:we};let f=Tt({tournamentRecord:u,drawDefinition:e,structure:l,event:r}).appliedPolicies??{};Object.assign(f,o??{});let g=f?.[Jn]?.otherFlightEntries,I=f?.[er]??Ps[er],{enabledStructures:h}=ST({actionType:hT,appliedPolicies:f,drawDefinition:e,structure:l}),{policyActions:S}=TT({enabledStructures:h,drawDefinition:e,structure:l}),T=t.matchUpsMap??Pe({drawDefinition:e}),y=t.inContextDrawMatchUps??ie({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}=Ie({structure:l}),{structureId:D}=l??{},M=[];if(!D)return{validActions:M};let R=cr({structure:l}),b=!!d.collectionId;if(R&&!b){let z=Gv({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 O=Do({drawDefinition:e,structure:l}),v=U?.filter(z=>z.participantId).map(z=>z.drawPosition),x=U?.filter(z=>z.bye).map(z=>z.drawPosition),F=d.matchUpStatus==="BYE"||!b&&d.drawPositions?.reduce((z,Q)=>x?.includes(Q)||z,!1);if(F)return{validActions:M,isByeMatchUp:F};qn({policyActions:S,action:PT})&&M.push({type:PT,payload:{matchUpId:c}});let w=!Oa({matchUpStatus:d.matchUpStatus}),L=f?.scoring?.structures,k=l?.stage&&L?.stage&&L?.stage[l.stage],G=l?.stageSequence&&k?.stageSequence&&k.stageSequence[l.stageSequence],K=!(f?.scoring?.requireAllPositionsAssigned||k?.requireAllPositionsAssigned||G?.requireAllPositionsAssigned)||N,Y=d.sides&&d.sides.filter(z=>z?.participantId).length===2,j=d.matchUpStatus&&[oe,be].includes(d.matchUpStatus),V=ur({inContextDrawMatchUps:y,drawDefinition:e,matchUpId:c}),$=Fi({inContextDrawMatchUps:y,drawDefinition:e,targetData:V}),W=(E?.drawPositions?.length===2&&E.drawPositions.every(z=>v?.includes(z))&&E?.sides?.length===2&&E.sides.every(({participantId:z})=>z)||Y)&&!(j&&$),it={method:zS,type:ia,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:AT,type:yD}),qn({policyActions:S,action:ia})&&(P?.participant||!a&&A?.length)&&M.push(it),w&&W&&M.push({type:ED}),K&&W){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:AT,type:AD,payload:ut}),qn({policyActions:S,action:DT})&&M.push({type:DT}),qn({policyActions:S,action:"END"})&&M.push({type:"END"})}if(b&&E){let z=Lv({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:O,validActions:M,isDoubleExit:j,...C}}function Bv({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===zi&&(d?.length!==1||l?.length!==1),E={};if(y){let{matchUps:N}=yt({drawDefinition:s,structure:u,event:m}),{initialRoundNumber:D}=Es({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}=Mu({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:wg,method:rv,availableLuckyLosers:I,availableLuckyLoserParticipantIds:f,willDisableLinks:r,payload:{drawId:p,structureId:c,drawPosition:a}}}:{}}function Hv({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?.[Vn]?.validSeedPositions?.ignore;if(y||({unplacedSeedParticipantIds:h,unplacedSeedAssignments:S,unfilledPositions:T}=xS({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:av,type:"BYE"}),i&&y){let E=s.map(D=>D.participantId).filter(Boolean),P={structureIds:t},{completedMatchUps:A}=Zs({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:YP,type:Ms,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(iV),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:YP,type:Ms,availableParticipantIds:E,participantsAvailable:P}))}return{validAssignmentActions:I}}function iV(t,e){return t.bye||Nc(t.seedValue)<Nc(e.seedValue)||t.seedValue&&!e.seedValue?-1:(t.seedNumber||0)-(e.seedNumber||0)}function Wv({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?.[Jn],g=!f?.disableRoundRestrictions&&t[s],I=f?.requireCompletedStructures,{sourceStructureIds:h,relevantLinks:S}=vu({targetRoundNumber:g,linkType:Xn,drawDefinition:i,structureId:a})||{};h?.length&&d.push(...h);let{sourceStructureIds:T,relevantLinks:y}=vu({targetRoundNumber:g,linkType:Fn,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=Do({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==="BYE"&&D.sides?.find(({participantId:b})=>b);if(M||R){let{participantId:b,participant:O}=M||R||{};b&&!l.includes(b)&&(O&&n&&u.push(O),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=Do({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:Lo}).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:ZO,type:Wp,qualifyingParticipantIds:p,payload:{qualifyingParticipantId:void 0,drawPosition:s,structureId:a,drawId:c}})),{validAssignmentActions:m,sourceStructureIds:d}}function jv({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:KS,type:Yp,availableAssignments:N}}:{}}function MT(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&&Ft({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:_t};let d=m.structureId;if(p=va({drawDefinition:s,structureId:d}),a===void 0&&!p.isAdHoc)return{error:Fs};if(p.isAdHoc)return Bd(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}=ST({actionType:Wg,appliedPolicies:h,drawDefinition:s,structure:m}),E=S?.activePositionOverrides||[],{sourceStructureIds:P}=vu({finishingPosition:Ei,targetRoundNumber:1,linkType:Fn,drawDefinition:s,structureId:d})||{},A;P?.length&&(A=P.every(W=>Do({structureId:W,drawDefinition:s})));let U=P.length,N=P.length&&!A,{policyActions:D}=TT({enabledStructures:T,drawDefinition:s,structure:m}),M=![ct,rt].includes(m.stage)||m.stageSequence!==1,{drawId:R}=s,b=[],{assignedPositions:O,positionAssignments:v}=Ie({structure:m}),x=O?.find(W=>W.drawPosition===a),F=!!x;if(!v?.map(W=>W.drawPosition)?.includes(a))return{error:Ls};let{stage:L,stageSequence:k}=m,G=[L];L===qe&&G.push(rt),L===rt&&G.push(qe);let H=bi({entryStatuses:mi,provisionalPositioning:o,drawDefinition:s,stageSequence:k,structureId:d,stages:G}),K=wi({drawDefinition:s,stages:G}).assignedParticipantIds??[],Y=H.filter(W=>!K.includes(W.participantId)).map(W=>W.participantId),j=I.includes(a),V=g.includes(a);if(y)return{info:"Actions Disabled for structure",isActiveDrawPosition:V,isDrawPosition:!0,hasPositionAssigned:F,validActions:[],isByePosition:j};if(qn({policyActions:D,action:Ms})&&!V&&v&&!N&&(!x||j)){let{validAssignmentActions:W}=Hv({positionSourceStructureIds:P,unassignedParticipantIds:Y,possiblyDisablingAction:M,isWinRatioFedStructure:U,tournamentParticipants:u,positionAssignments:v,returnParticipants:n,appliedPolicies:h,drawDefinition:s,isByePosition:j,drawPosition:a,structureId:d,event:c});W?.forEach(it=>b.push(it))}if(qn({policyActions:D,action:Wp})&&!V){let{validAssignmentActions:W}=Wv({drawPositionInitialRounds:l,tournamentParticipants:u,positionAssignments:v,returnParticipants:n,appliedPolicies:h,drawDefinition:s,drawPosition:a,structureId:d,drawId:R});W?.forEach(it=>b.push(it))}let{participantId:$}=x||{},X=$&&u.find(W=>W.participantId===$);if(x){qn({policyActions:D,action:QS})&&!V&&(b.push({type:QS,method:jP,payload:{drawId:R,structureId:d,drawPosition:a},willDisableLinks:M}),j||b.push({type:xg,method:tv,payload:{drawId:R,structureId:d,drawPosition:a},willDisableLinks:M}),qn({policyActions:D,action:"BYE"})&&!j&&b.push({type:"BYE",method:jP,payload:{drawId:R,structureId:d,drawPosition:a,replaceWithBye:!0},willDisableLinks:M}));let W=m.stage===ct||m.stage===rt&&m.stageSequence===1;if(!j&&fD({activePositionOverrides:E,activeDrawPositions:g,action:oa})&&qn({policyActions:D,action:oa})&&Vp({drawDefinition:s,structureId:d,drawPosition:a})&&W){let{seedAssignments:it}=sn({returnAllProxies:!0,drawDefinition:s,structure:m}),{seedNumber:z,seedValue:Q}=it?.find(ut=>ut.participantId===$)??{};b.push({type:oa,method:cv,participant:X,seedNumber:z,payload:{drawId:R,structureId:d,participantId:$,seedValue:Q}})}if(!j&&fD({activePositionOverrides:E,activeDrawPositions:g,action:jp})&&qn({policyActions:D,action:jp})&&Vp({drawDefinition:s,structureId:d,drawPosition:a})&&W){let{seedAssignments:it}=sn({returnAllProxies:!0,drawDefinition:s,structure:m}),{seedNumber:z}=it?.find(Q=>Q.participantId===$)??{};b.push({method:sv,type:jp,participant:X,seedNumber:z,payload:{participantId:$,structureId:d,drawId:R}})}if(!j&&$){if(qn({policyActions:D,action:ia})){let it={type:ia,method:zS,participant:X,payload:{penaltyCode:void 0,penaltyType:void 0,participantIds:[],notes:void 0,drawId:R}};b.push(it)}if(qn({policyActions:D,action:xu})){let it={type:xu,method:iv,participant:X,payload:{participantId:$,otherName:void 0}};b.push(it)}}if(qn({policyActions:D,action:Yp})){let{validSwapAction:it}=jv({possiblyDisablingAction:M,tournamentParticipants:u,inactiveDrawPositions:f,activeDrawPositions:g,positionAssignments:v,returnParticipants:n,byeDrawPositions:I,drawDefinition:s,isByePosition:j,drawPosition:a,structureId:d,structure:m,drawId:R});it&&b.push(it)}}if(qn({policyActions:D,action:_g})&&!N){let{validAlternatesAction:W}=Fv({possiblyDisablingAction:M,tournamentParticipants:u,positionAssignments:v,activeDrawPositions:g,returnParticipants:n,appliedPolicies:h,drawDefinition:s,drawPosition:a,validActions:b,structureId:d,structure:m,drawId:R,event:c});W&&b.push(W)}if(qn({policyActions:D,action:wg})&&!N&&!V&&v){let{validLuckyLosersAction:W}=Bv({sourceStructuresComplete:A,possiblyDisablingAction:M,isWinRatioFedStructure:U,tournamentParticipants:u,activeDrawPositions:g,positionAssignments:v,drawDefinition:s,drawPosition:a,structureId:d,structure:m,drawId:R});W&&b.push(W)}if(X?.participantType===ft&&qn({policyActions:D,action:vg})){let{validModifyAssignedPairAction:W}=_v({tournamentParticipants:u,returnParticipants:n,drawPosition:a,participant:X,drawId:R,event:c});W&&b.push(W)}return{isActiveDrawPosition:V,isDrawPosition:!0,hasPositionAssigned:F,isByePosition:j,validActions:b,...C}}function Bu({policyDefinitions:t,appliedPolicies:e,drawType:r}){let n=t?.[Xm]?.drawTypeCoercion,o=e?.[Xm]?.drawTypeCoercion;return(typeof n=="boolean"?n:void 0)??(r&&n?.[r])??(typeof o=="boolean"?o:void 0)??(r&&o?.[r])??!0}var RT=({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:zl}});let{qualifierPositions:n}=Ie({structure:r});return tt(0,n.length).sort(()=>Math.random()-.5)};function CT({structureId:t,drawDefinition:e}){if(!e)return{error:Z};if(!kt(t))return{error:B};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([yi,Nn,Sp,Ti],n).length;return{...C,valid:o}}function zp({tournamentRecord:t,drawDefinition:e,stage:r=rt,structureId:n,structure:o}){if(!t)return{error:q};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:Pr};let{error:i,positionAssignments:s}=Ct({drawDefinition:e,structureId:n,structure:o});return{positionAssignments:s??[],structureId:o?.structureId,error:i}}function bT({participantsCount:t,participantCount:e}){if(t=t??e,!t)return{error:B};let r=us(t);return r?{drawSize:r}:_({result:{error:B},stack:"getEliminationDrawSize",context:{participantsCount:t}})}function Hu(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=Go({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:B},context:{participantsCount:u},stack:c});if(o&&!p)return _({result:{error:UA},stack:c});if(isNaN(n))if(u)({drawSize:n}=bT({participantsCount:u}));else return _({result:{error:Za},stack:c});let m=o&&u||n;if(m&&m>n)return{error:of};let d=r?.[Vn];if(!d)return{error:pA};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:KE}}function Hd({consideredEntries:t,policyDefinitions:e,tournamentRecord:r,appliedPolicies:n,participantMap:o,enforceGender:i,participants:s,event:a}){if((!s||!o)&&r&&({participants:s,participantMap:o}=Ft({tournamentRecord:r})),!s)return{error:ec};if(!Array.isArray(s))return{error:B};if(!a)return{error:Ot};let c=e?.[er]??n?.[er]??Ps[er],u=(i??c?.participants?.enforceGender)!==!1,{eventType:p,gender:m}=a,d=p===Ko,l=p===Or&&wt||d&&ft||Et,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=sV({participant:S,participantType:l,eventType:p,entryStatusMap:f}),y=aV({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:nA,invalidParticipantIds:S}}return{...C,valid:!0}}function sV({participant:t,participantType:e,eventType:r,entryStatusMap:n}){let o=n[t.participantId],i=r&&[Ko,Or].includes(r)&&t.participantType===Et&&(ta(o)||o===mo);return t.participantType!==e&&!i}function aV(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||To(n)||Dn(n)&&yr(a[0])===yr(n)||en(n)&&(a.length===1&&e.individualParticipantIds?.length===1||a.length===2),u=e?.person?.sex,p=!e?.person||!n||en(n)||To(n)||Dn(n)&&yr(u)===yr(n);return!s||c&&p}function OT({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=Rm(N.drawSize||N.participantsCount),{qualifyingRoundNumber:M,structureOptions:R,matchUpFormat:b,structureName:O,structureId:v,drawType:x}=N,F=N.matchUpType,w=N.qualifyingPositions||cV({drawSize:D,qualifyingRoundNumber:M}),L,k,G;if(!It(D))return _({result:{error:Za},stack:c});let H=e.length>1?`${h}-`:"",K=T.length>1||H?y:"",Y=O||(H||K?`${Qe(ct)} ${H}${K}`:Qe(ct));if(x===On){let{structures:j,groupCount:V,maxRoundNumber:$}=xa({structureName:N.structureName||Y,structureId:v||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=V,L=$,k=j[0],I=[1]}else({drawSize:D,matchUps:G,roundLimit:L}=xn({qualifyingRoundNumber:M,qualifyingPositions:w,matchUpType:F,drawSize:D,idPrefix:i,isMock:s,uuids:a})),k=yn({structureName:N.structureName||Y,structureId:v||a?.pop(),qualifyingRoundNumber:L,hasExistingDrawDefinition:t,stage:ct,qualifyingOnly:n,matchUpFormat:b,stageSequence:y,matchUpType:F,roundLimit:L,tieFormat:o,matchUps:G}),h&&At({extension:{name:vn,value:h},element:k}),E=G?.filter(j=>j.roundNumber===L)?.length||0;if(y>1){let{link:j}=La({sourceStructureId:A,sourceRoundNumber:P,targetStructureId:k.structureId,finishingPositions:U===Fn?[1]:void 0,linkType:U});m.push(j),f+=(D||0)-E}else f+=D||0;U=x===On?Fn:Xn,A=k.structureId,P=L,o&&(G=yt({structure:k})?.matchUps||[],G?.forEach(j=>{let{tieMatchUps:V}=Li({tieFormat:o,matchUp:j,isMock:s});Object.assign(j,{tieMatchUps:V,matchUpType:F})})),p.push(k),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 cV({drawSize:t,qualifyingRoundNumber:e}){let r=t,n=0;for(;n<e;)r=Math.floor(r/2),n+=1;return r}function vT(t){let{drawTypeCoercion:e,enforceMinimumDrawSize:r}=t,n=dt(t.drawSize),o=e&&t.drawType!==Fr&&(typeof e=="boolean"||e<=2)&&n===2&&yo||t.drawType||yo,i=DU.includes(o);if(n&&i){if(e&&(typeof e=="boolean"&&n<4||n<=e))o=yo;else if(n<4&&r)return{..._({context:{enforceMinimumDrawSize:r,drawSize:n,drawType:o},result:{error:np},stack:"getCoercedDrawType"}),drawType:o}}return{drawType:o}}function Yv(t){let{drawDefinition:e,structureOptions:r,requireSequential:n}=t,o={structureName:Qe(rt),...t,stage:rt},{structures:i,groupCount:s,groupSize:a}=xa(o);if(s<1)return{error:GA};let c=r?.playoffGroups||[{finishingPositions:[1],structureName:Qe(fe)}],[u]=i,{structures:p,links:m}=rT({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 qv({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?Nn:yi,f=1+m;return{linkType:so,source:{roundNumber:f,structureId:t.structureId},target:{feedProfile:l,roundNumber:p,structureId:e.structureId}}}),c={linkType:Xn,source:{roundNumber:s,structureId:e.structureId},target:{feedProfile:Nn,roundNumber:i,structureId:t.structureId}},u=[{linkType:Xn,source:{roundNumber:i,structureId:t.structureId},target:{feedProfile:Nn,roundNumber:1,structureId:r.structureId}},{linkType:so,source:{roundNumber:i,structureId:t.structureId},target:{feedProfile:Nn,roundNumber:1,structureId:r.structureId}}];return[...a,c,...u]}function $v({structureName:t,matchUpType:e,idPrefix:r,drawSize:n,isMock:o,uuids:i}){let s=[],{matchUps:a}=fi({linkFedFinishingRoundNumbers:[1],drawSize:n+1,matchUpType:e,idPrefix:r,isMock:o}),c=Ds({structureName:t||Qe(rt),structureId:i?.pop(),stageSequence:1,stage:rt,matchUpType:e,matchUps:a});s.push(c);let u=n/2,{matchUps:p}=fi({finishingPositionOffset:u,idPrefix:r&&`${r}-c`,drawSize:n-1,isConsolation:!0,matchUpType:e,isMock:o,uuids:i}),m=Ds({structureName:Qe(PU),matchUps:p,structureId:i?.pop(),stage:qe,stageSequence:2,matchUpType:e});s.push(m);let{matchUps:d}=xn({idPrefix:r&&`${r}-p1t2`,drawSize:2,matchUpType:e,isMock:o}),l=Ds({structureName:Qe(UU),matchUps:d,structureId:i?.pop(),stageSequence:3,stage:fe,matchUpType:e});s.push(l);let f=qv({mainStructure:c,consolationStructure:m,deciderStructure:l});return{structures:s,links:f,...C}}function Kv(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(Ln(s))return xn(t);let u=uV(s),p=u.shift(),m=tt(1,(p?.participantsCount||0)+1).map(I=>({drawPosition:I})),d=[],l=1;({matchUps:d}=qp({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=vd({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=ba({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 uV(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 _T(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?.[dc]||p?.[dc];t.skipRounds=t.skipRounds||s<=4&&(m?.feedFromMainFinal?0:1)||0;let d=t.structureName??e?.["0"]?.name??Qe(rt),l=()=>{let{matchUps:g}=xn(t);return{structures:[yn({stageSequence:r,structureName:d,matchUpType:i,structureId:u,tieFormat:o,matchUps:g,stage:n})],links:[],...C}};return{generators:{[Fr]:()=>({structures:[yn({finishingPosition:Ei,stageSequence:r,structureName:d,matchUps:[],matchUpType:i,structureId:u,stage:n})],links:[],...C}),[Ki]:()=>{let{matchUps:g}=Kv(t);return{structures:[yn({stageSequence:r,structureName:d,matchUpType:i,structureId:u,matchUps:g,stage:n})],links:[],...C}},[yo]:()=>l(),[su]:()=>$v(t),[ou]:()=>Rc({...t,roundOffsetLimit:3,playoffAttributes:e??Of}),[iu]:()=>Rc({...t,roundOffsetLimit:2,playoffAttributes:e??vf}),[fe]:()=>Rc(t),[Ea]:()=>{let{matchUps:g}=fi({drawSize:s,uuids:a,matchUpType:i});return{structures:[yn({stageSequence:r,structureName:d,matchUpType:i,structureId:u,stage:rt,tieFormat:o,matchUps:g})],links:[],...C}},[Tp]:()=>JS(t),[au]:()=>bc({...t,feedRounds:1,fmlc:!0}),[AU]:()=>bc({...t,feedRounds:1}),[bh]:()=>bc({...t,feedsFromFinal:1}),[Oh]:()=>bc({...t,feedsFromFinal:2}),[vh]:()=>bc({...t,feedsFromFinal:3}),[yp]:()=>bc(t),[bf]:()=>tT(t),[On]:()=>xa(t),[Eo]:()=>Yv(t)}}}function Wd(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??Bu({appliedPolicies:n,drawType:t.drawType}),d="generateDrawStructuresAndLinks",l=vT({drawType:t.drawType,enforceMinimumDrawSize:e,drawTypeCoercion:m,drawSize:p});if(l.error)return l;let f=l.drawType,g=[],I=[],h=t?.matchUpType??Lt,S=s?.structures?.filter(({stage:K})=>K===ct);S&&g.push(...S);let T=S?.map(({structureId:K})=>K),y=s?.structures?.find(({stage:K,stageSequence:Y})=>K===rt&&Y===1),E=s?.links?.filter(K=>K.target.structureId===y?.structureId&&T?.includes(K.source.structureId)),P=(K,Y)=>{if(K.linkType===Fn&&Y?.structures){let j=K.source.finishingPositions||[];return Y.structures.length*j.length}else if(K.linkType===Xn&&Y?.matchUps?.length){let j=K.source.roundNumber;return Y.matchUps.filter(({roundNumber:$})=>$===j).length}},A=S?.map(K=>{let Y=E?.find(W=>W.target.structureId===K.structureId),j=Ct({structure:K})?.positionAssignments?.length??0;if(!Y)return j;let V=Y?.source.structureId,$=s.structures?.find(W=>W.structureId===V),X=P(Y,$)||0;return j-X}).filter(Boolean).reduce((K,Y)=>K+Y,0),U=E?.map(K=>{let Y=K.source.structureId,j=S?.find(V=>V.structureId===Y);return P(K,j)}).filter(Boolean).reduce((K,Y)=>K+Y,0),N=!!(y&&!y?.matchUps?.length);if(S?.length&&!N)return{error:ZI};let D=!S?.length&&t.qualifyingProfiles,M=D?.length&&OT({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:O}=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 v=f!==Fr&&(!p||p<2||!i&&![Ea,Ki].includes(f)&&([Eo,On].includes(f)&&p<3||![On,Eo].includes(f)&&!Ln(p)));if(v&&!R)return _({context:{drawSize:p,invalidDrawSize:v},result:{error:np},stack:d});let{generators:x,error:F}=_T(t);if(F)return{error:F};let w=x[f];if(!w)return{error:ql};let L=w?.();if(L.error)return L;let{structures:k,links:G}=L;if(k?.length){let K=k.find(({stage:Y,stageSequence:j})=>Y===rt&&j===1);if(y&&K){if(N){let Y=K.structureId;if(K.structureId=y.structureId,G?.length)for(let j of G)j.source.structureId===Y&&(j.source.structureId=y.structureId),j.target.structureId===Y&&(j.target.structureId=y.structureId)}else if(!r)return{error:ZI}}g.push(...k)}g.sort(Ni),G?.length&&I.push(...G);let H=L.structures.find(({stage:K,stageSequence:Y})=>K===rt&&Y===1);for(let K of b||[]){let{finalQualifyingRoundNumber:Y,finalQualifyingStructureId:j,roundTarget:V,finishingPositions:$,linkType:X}=K,W=H&&La({targetStructureId:H.structureId,sourceStructureId:j,sourceRoundNumber:Y,finishingPositions:$,targetEntryRound:V,linkType:X})?.link;if(W?.error)return W;W&&I.push(W)}return E&&I.push(...E),{...C,qualifyingResult:{qualifyingDrawPositionsCount:R,qualifiersCount:O},structures:g,links:I}}function jd(t){let{modifyOriginal:e=!0,stageSequence:r=1,isMock:n}=t||{},o="generateDrawTypeAndModifyDrawDefinition";if(!t.drawDefinition)return _({result:{error:Z},stack:o});let i=e?t.drawDefinition:J(t.drawDefinition,!1,!0),{tieFormat:s,matchUpType:a}=t;if(s){let T=ar({tieFormat:s});if(T.error)return T}s=or(s??We({drawDefinition:i})?.tieFormat),a=a??(i.matchUpType||Lt),t.tieFormat=s,t.matchUpType=a;let c=Fp({drawDefinition:i,stage:rt});t.drawSize=t.drawSize??c,!c&&t.drawSize&&Hp({drawSize:t.drawSize,drawDefinition:i,stageSequence:r,stage:rt});let u=Pe({drawDefinition:i}).drawMatchUps.map(Ue),p=Wd(t);if(p.error)return _({result:p,stack:o});let{structures:m,links:d,qualifyingResult:l}=p;i.structures=m,i.links=d;let f=Math.max(t.qualifiersCount??0,l?.qualifiersCount||0);if(l?.qualifyingDrawPositionsCount&&!Fp({stage:ct,drawDefinition:i})){let y=Hp({drawSize:l.qualifyingDrawPositionsCount,stage:ct,drawDefinition:i});if(y.error)return y}if(f){let T=$S({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}=ie({drawDefinition:i});s&&I?.forEach(T=>{if(!u.includes(T.matchUpId)){let{tieMatchUps:y}=Li({tieFormat:s,matchUp:T,isMock:n});Object.assign(T,{tieMatchUps:y,matchUpType:a})}});let{inContextDrawMatchUps:S}=rs({drawDefinition:i,matchUpsMap:h});return bt({tournamentId:t.tournamentRecord?.tournamentId,drawDefinition:i}),{inContextDrawMatchUps:S,drawDefinition:i,matchUpsMap:h,...C,structures:m,matchUps:I,links:d}}function xc(t){let{removePriorValues:e,tournamentRecord:r,participantId:n,scaleItem:o}=t,i,s;if(!zv({scaleItem:o}))return{error:rc};if(n&&Array.isArray(r.participants)&&(s=r.participants.find(a=>a.participantId===n),s)){if(s.participantType===Ar&&o?.eventType!==Or)return{error:rc};let a=Qv({removePriorValues:e,participant:s,scaleItem:o});if(a.error)return a;i=!a.valueChanged;let{topics:c}=Lr();c.includes(rr)&<({topic:rr,payload:{tournamentId:r.tournamentId,participants:[s]}})}return i&&{...C,info:ff,existingValue:o?.scaleValue}||s&&{...C,newValue:o?.scaleValue}||{error:re}}function DD(t){let{scaleItemsWithParticipantIds:e=[],removePriorValues:r,tournamentRecord:n,auditData:o,context:i}=t;if(!n)return{error:q};if(!n.participants)return{error:ec};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(zv({scaleItem:l}))Array.isArray(a[d])||(a[d]=[]),a[d].push(l);else return{error:rc}}for(let m of n.participants){let{participantId:d}=m||{};if(Array.isArray(a[d]))for(let l of a[d]){if(m.participantType===Ar&&l?.eventType!==Or)return _({context:{participantId:d,scaleItem:l,participantType:m.participantType},info:"Invalid participantType for eventType",result:{error:rc}});Qv({participant:m,scaleItem:l,removePriorValues:r}),c.push(m),s++}}let u=s?void 0:Bs,{topics:p}=Lr();if(p.includes(rr)&&s&<({topic:rr,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:Yf,itemValue:l};if(f&&(g.itemSubTypes=f),d||m){let{drawDefinition:I,event:h}=ze({tournamentRecord:n,eventId:m,drawId:d});d&&Og({drawDefinition:I,timeItem:g}),m&&is({event:h,timeItem:g})}else _c({tournamentRecord:n,timeItem:g})}}return o&&p.includes(Mi)&<({topic:Mi,payload:o}),nt({...C,modificationsApplied:s,info:u})}function zv({scaleItem:t}){let e=t&&Object.keys(t),r=["scaleType","eventType","scaleName"];return!!(r.filter(o=>e?.includes(o)).length===r.length)}function Qv({removePriorValues:t,participant:e,scaleItem:r}){if(!e)return{error:Wi};let n=r&&Object.keys(r),o=["scaleType","eventType","scaleName"];if(!(o.filter(p=>n.includes(p)&&r[p]).length===o.length))return{error:rc};let s=new Date().toISOString();e.timeItems||(e.timeItems=[]);let{scaleItem:a}=Po({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=[Pi,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 Yg(t){let{tournamentRecord:e,modifiedScaleValues:r,removePriorValues:n}=t,o=et(t,[{[ne]:!0},{modifiedScaleValues:!0,[He]:zr}]);if(o.error)return o;for(let i in r){let s=xc({scaleItem:r[i],removePriorValues:n,tournamentRecord:e,participantId:i});if(s.error)return s}return{...C}}function wc(t){let{tournamentRecord:e,scaleAttributes:r,participantId:n}=t,o=t.tournamentRecords||e&&{[e.tournamentId]:e}||{};if(!n)return{error:se};let{participant:i,tournamentId:s}=Uo({tournamentRecords:o,tournamentRecord:e,participantId:n});return i?{...Po({participant:i,scaleAttributes:r}),tournamentId:s}:{error:re}}var pV=(t=0)=>250/Math.pow(t+5,.4),mV=()=>1;function dV(t=3,e=2){let r=t/e;return isNaN(r)?Yd.kDefault():r}var Yd={nSpread:400,diffThreshold:.125,kCalc:pV,kMultiplier:dV,kDefault:mV};function xT(t){let{winnerRating:e,loserRating:r}=t,{ratings:n=je,winnerCountables:o=1,loserCountables:i=0,ratingType:s="ELO",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=Fu({targetRange:je["ELO"].range,sourceRange:l,value:m?p[0]-e:e}),I=Fu({targetRange:je["ELO"].range,sourceRange:l,value:m?p[0]-r:r}),h=(x,F)=>1/(1+Math.pow(10,(F-x)/Yd.nSpread)),S=h(g,I),T=h(I,g),y=Yd.kCalc(o),E=Yd.kCalc(i),P=Yd.kMultiplier(a,c),A=g+P*y*(1-S),U=I+P*E*(0-T),N=Fu({sourceRange:je["ELO"].range,value:A,targetRange:l}),D=Fu({sourceRange:je["ELO"].range,value:U,targetRange:l}),M=m?p[0]-N:N,R=parseFloat(M.toFixed(d)),b=m?p[0]-D:D,O=parseFloat(b.toFixed(d)),v=Math.max(...p)?Math.abs(e-r)/Math.max(...p):0;return(N>D&&v>Yd.diffThreshold||R<0||O<0)&&(R=e,O=r),{newWinnerRating:R,newLoserRating:O}}var Xv=t=>t?.reduce((e,r)=>(r.winningSide&&(e[r.winningSide-1]+=1),e),[0,0])||[0,0];function wT(t){let e=et(t,[{[ne]:!0},{matchUpIds:!0,[He]:Be,[In]:ps},{ratingType:!1,[tr]:S=>je[S]}]);if(e.error)return e;let{updateParticipantRatings:r,removePriorValues:n=!0,tournamentRecord:o,ratingType:i="ELO",refreshDynamic:s,considerGames:a,drawDefinition:c,matchUpIds:u,asDynamic:p}=t,m=je[i],{accessor:d}=m,l={},f=(t.matchUps||s&&nr({drawDefinition:c,tournamentRecord:o,inContext:!0,matchUpFilters:{matchUpStatuses:ae}}).matchUps||ye({matchUpFilters:{matchUpIds:u,matchUpStatuses:ae},tournamentRecord:o,inContext:!0}).matchUps)??[],g=`${i}.${Qm}`,I=p?g:i;f.sort(xi);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:Ui},D={scaleName:g,eventType:U,scaleType:Ui},M=Object.assign({},...(P??[]).map(k=>{let{sideNumber:G,participant:H}=k;return G&&{[G]:[H?.participantId,...H?.individualParticipantIds??[]].filter(Boolean).flat()}})),R=Object.assign({},...Object.values(M).flat().map(k=>{let G=l[k],K=!s||G?wc({scaleAttributes:D,tournamentRecord:o,participantId:k}).scaleItem:void 0,Y=wc({tournamentRecord:o,scaleAttributes:N,participantId:k}).scaleItem,j=d?{[d]:void 0}:void 0;return k&&{[k]:K??Y??{scaleName:I,eventType:U,scaleDate:T,scaleType:Ui,scaleValue:j}}})),b=y?Ne(y):{},O=b?.bestOf||1,v=b?.setsTo||1,x=a?O&v:O,F=E?.sets&&Xv(E.sets)||A===1&&[1,0]||[0,1],w=A?M[A]:[],L=A?M[3-A]:[];for(let k of w){let G=R[k]?.scaleValue,H=typeof G=="object"?G[d]:G;for(let K of L){let Y=R[K]?.scaleValue,j=typeof Y=="object"?Y[d]:Y,V=A?F[A]:[0,0],$=A?F[3-A]:[0,0],{newWinnerRating:X,newLoserRating:W}=xT({winnerCountables:V,loserCountables:$,maxCountables:x,winnerRating:H,loserRating:j,ratingType:i}),it=d?{...G,[d]:X}:X,z=d?{...Y,[d]:W}:W;R[k].scaleValue=it,R[K].scaleValue=z,R[k].scaleName=I,R[K].scaleName=I}}Object.assign(l,R),r&&Yg({tournamentRecord:o,modifiedScaleValues:l,removePriorValues:n})}let h=f.map(({matchUpId:S})=>S);return{...C,modifiedScaleValues:l,outputScaleName:I,processedMatchUpIds:h}}function Wu(t){let{matchUpIds:e=[],drawDefinition:r,roundNumber:n,newRound:o,isMock:i,event:s}=t;if(typeof r!="object")return{error:Z};let{participantIdPairings:a,matchUpsCount:c}=t,u=Vd(t);if(u.error)return _({result:u});let{lastRoundNumber:p,availableMatchUpsCount:m=0,roundMatchUpsCount:d=0}=u;if(!c)o?c=d:m>0&&(c=m);else if(c>d&&t.restrictMatchUpsCount!==!1)return _({result:{error:B,info:"matchUpsCount error",context:{roundMatchUpsCount:d}}});if(a&&!Array.isArray(a)||c&&!It(c)||e&&!Array.isArray(e)||!a&&!c)return{error:B,info:"matchUpsCount or pairings error"};if(c&&t.restrictMatchUpsCount!==!1&&c>32)return{error:B,info:"matchUpsCount must be less than 33"};if(n&&!t.ignoreLastRoundNumber&&n-1>(p||0))return{error:B,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)??Nt();return{roundNumber:l,matchUpStatus:Qt,matchUpId:E,sides:y}});if(g?.length){let I=We({drawDefinition:r,event:s})?.tieFormat;I&&g.forEach(h=>{let{tieMatchUps:S}=Li({tieFormat:I,matchUp:h,isMock:i});Object.assign(h,{tieMatchUps:S,matchUpType:Wt})})}return{roundNumber:l,matchUpsCount:g?.length??0,matchUps:g,...C}}function Zv({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=Jv({actorsCount:s.length,valueSortedPairings:e,pairingValueMap:i,deltaObjects:o,valueObjects:n}),u=[ND(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=Ga(S,y.opponent);if(!I.includes(E)){let P=Jv({stipulated:[[S,y.opponent]],actorsCount:s.length,valueSortedPairings:e,pairingValueMap:i,deltaObjects:o,valueObjects:n});if(!u.includes(ND(P))){u.push(ND(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=tn(a);return{candidatesCount:d,deltaCandidate:m,maxIterations:t,iterations:l,candidate:h}}function ND(t){return t.participantIdPairings.map(({participantIds:e})=>e.sort().join("|")).sort().join("/")}function Jv({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=Ga(l,f),I=r[g];a.push({participantIds:d,value:I}),c+=r[g]}),Ae(t,i).map(d=>Tr(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=Ga(f,g),h=n[I];return h>d?h:d},0),m=a.reduce((d,l)=>{let[f,g]=l.participantIds,I=Ga(f,g),h=o[I];return h>d?h:d},0);return{value:c,participantIdPairings:a,maxDelta:p,maxDiff:m}}function Ga(t,e){return[t,e].sort(Cu).join("|")}function MD({participantIds:t}){let e={},r=[];t.forEach(o=>{e[o]=t.filter(i=>i!==o),e[o].forEach(i=>{let s=Ga(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 t_({matchUps:t}){let e=[];for(let r of t){let n=r.sides.map(St);if(n.length===2){let[o,i]=n,s=Ga(o,i);e.includes(s)||e.push(s)}}return{encounters:e}}function e_({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=Ga(o,i);return{opponent:i,value:e[s]}}return{pairingValues:r}}var lV=0;function r_({tournamentParticipants:t,adHocRatings:e,eventType:r,scaleName:n,pairing:o}){let i=je[n]?.defaultInitialization??lV;return o.split("|").map(s=>{if(r===Kr){let a=t?.find(c=>c.participantId===s)?.individualParticipantIds;return a?a?.map(c=>e[c]||i):i*2}else return e[s]||i})}function n_(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=r_({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}=e_({possiblePairings:n,valueObjects:c}),{candidate:f,candidatesCount:g,deltaCandidate:I,iterations:h}=Zv({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 fV=100,gV=100,IV=4e3;function qd(t){let{encounterValue:e=fV,sameTeamValue:r=gV,maxIterations:n=IV,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:_t};let P=t.structure||at({drawDefinition:d,structureId:f}).structure;if(!ht(P))return{error:Si};if(!m?.length)return{error:bo};let A=[...a??[],...P?.matchUps??[]],{encounters:U}=t_({matchUps:A}),N=c?.participants??[],D={};if(u){let V=pt(P?.matchUps?P.matchUps.map(({roundNumber:X})=>X):[]),$=Math.max(...V,0);if($){let X=P?.matchUps?.filter(({roundNumber:it})=>it===$).map(({matchUpId:it})=>it),W=wT({ratingType:h??E?.category?.ratingType,updateParticipantRatings:o,tournamentRecord:c,asDynamic:!0,refreshDynamic:p,drawDefinition:d,matchUpIds:X});if(W.error)return W;W.modifiedScaleValues&&(D=W.modifiedScaleValues)}}let{valueObjects:M}=hV({tournamentParticipants:N,encounterValue:e,sameTeamValue:r,encounters:U}),{uniquePairings:R,possiblePairings:b,deltaObjects:O}=MD({participantIds:m}),v=Object.values(D).length?D:t.adHocRatings,x={tournamentParticipants:N,possiblePairings:b,participantIds:m,uniquePairings:R,drawDefinition:d,maxIterations:n,adHocRatings:v,deltaObjects:O,valueObjects:M,eventType:I,scaleName:h,structure:P,salted:y},{candidatesCount:F,participantIdPairings:w,deltaCandidate:L,iterations:k,candidate:G}=n_(x);if(!F)return{error:ap};let H,K;if(i){let V=Wu({structureId:P?.structureId,ignoreLastRoundNumber:s,participantIdPairings:w,newRound:!0,drawDefinition:d,roundNumber:l,matchUpIds:g,idPrefix:S,isMock:T,event:E});if(V.error)return V;H=V.roundNumber,K=V.matchUps}let{maxDelta:Y,maxDiff:j}=G;return{roundNumber:H,participantIdPairings:w,modifiedScaleValues:D,candidatesCount:F,deltaCandidate:L,...C,iterations:k,matchUps:K,maxDelta:Y,maxDiff:j}}function hV({encounters:t,tournamentParticipants:e,encounterValue:r,sameTeamValue:n}){let o={};for(let s of t)o[s]||(o[s]=0),o[s]+=r;let i=e?.filter(({participantType:s})=>s===wt);if(i)for(let s of i){let a=s.individualParticipantIds??[],{uniquePairings:c}=MD({participantIds:a});for(let u of c)o[u]||(o[u]=0),o[u]+=n}return{valueObjects:o}}function LT(t){let{drawType:e=yo,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=bi({stageSequence:1,drawDefinition:p,stage:m}),l=[On,su,Eo].includes(e)?d.length:us(d.length);if(!i&&e===Ea&&d.length<2||e===On&&d.length<3)return{error:np};let{tieFormat:f,matchUpType:g}=t;if(f){let R=ar({tieFormat:f});if(R.error)return R}f=or(f??We({drawDefinition:p})?.tieFormat),g=g??p.matchUpType;let{structures:I}=hn({stageSequence:1,drawDefinition:p,stage:m});if(I.length>1)return{error:iA};if(I?.[0]?.matchUps?.length)return{error:If};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=_T(t);if(T.error)return T;let y=T.generators[e];if(!y)return{error:ql};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}=Li({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&&Mc({seedingProfile:t.seedingProfile,applyPositioning:n,tournamentRecord:o,drawDefinition:p,structureId:S,placeByes:a,drawSize:l,event:u}),r&&bt({drawDefinition:p}),{links:A,structures:P,...C}}var Jg={};Xt(Jg,{addGame:()=>xD,addPoint:()=>_D,addSet:()=>LD,addShot:()=>wD,analyzeScore:()=>zg,analyzeSet:()=>qu,calculateHistoryScore:()=>bD,checkScoreHasValue:()=>he,checkSetIsComplete:()=>Jp,clearHistory:()=>vD,generate:()=>CD,generateScoreString:()=>Mo,generateTieMatchUpScore:()=>vc,getSetComplement:()=>Xg,getTiebreakComplement:()=>rm,helpers:()=>cN,isValidMatchUpFormat:()=>Nr,keyValueScore:()=>rN,mutate:()=>VD,parseMatchUpFormat:()=>Ne,parseScoreString:()=>nm,query:()=>mN,redo:()=>FD,reverseScore:()=>RD,setServingSide:()=>OD,stringifyMatchUpFormat:()=>gp,tidyScore:()=>aN,umo:()=>GD,undo:()=>kD,validateMatchUpScore:()=>uN,validateScore:()=>Qg,validateSetScore:()=>$T,validateTieFormat:()=>ar});var CD={};Xt(CD,{generateScoreString:()=>Mo,generateTieMatchUpScore:()=>vc,reverseScore:()=>RD});function Mo(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&&Ne(s),{bestOf:m,finalSetFormat:d,setFormat:l}=p??{},g=o||!(!e||!c||c===1),I=n?SV({matchUpStatus:i}):"",h=u?.sort(TV).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=V=>Jt(V?.side1Score)||Jt(V?.side2Score),U=(V=>Jt(V?.side1TiebreakScore)||Jt(V?.side2TiebreakScore))(T),N=E?.tiebreakSet||!P(T)&&U,{side1Score:D,side2Score:M,side1TiebreakScore:R,side2TiebreakScore:b}=T,O=R||(Jt(R)||U&&a?0:""),v=b||(Jt(b)||U&&a?0:"");if(N){let V=P(T)&&!U,$=V?D:O,X=V?M:v;return`[${(g?[X,$]:[$,X]).join("-")}]`}let x=U?Math.min(O,v):"",F=x===O?1:2,w=Jt(x)?`(${x})`:"",L=D||(Jt(D)||a?0:""),k=M||(Jt(M)||a?0:""),G=V=>!r&&F===V?w:"",H=`${L}${G(1)}`,K=`${k}${G(2)}`,Y=r&&U?`(${x})`:"",j=g?`${[K,H].join("-")}${Y}`:`${[H,K].join("-")}${Y}`;return["-"," "].includes(j)&&(j=""),j}}function SV({matchUpStatus:t}){let e={[Me]:"RET",[Bt]:"WO",[be]:"DF/DF",[oe]:"WO/WO",[ls]:"SUS",[vr]:"ABN",[Gt]:"DEF",[Iu]:"DR"};return t&&e[t]||""}function TV(t,e){return t.setNumber-e.setNumber}function RD(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=Mo({setTBlast:n,sets:r}),i=Mo({sets:r,reversed:!0,setTBlast:n});return{reversedScore:{sets:r,scoreStringSide1:o,scoreStringSide2:i},...C}}var VD={};Xt(VD,{addGame:()=>xD,addPoint:()=>_D,addSet:()=>LD,addShot:()=>wD,calculateHistoryScore:()=>bD,clearHistory:()=>vD,redo:()=>FD,setServingSide:()=>OD,umo:()=>GD,undo:()=>kD});function ei({matchUp:t}){let{extension:e}=mt({name:rd,element:t});if(!e)return{error:Oe};let{history:r=[],undoHistory:n=[]}=e.value;return{history:r,undoHistory:n,...C}}function bD(t){if(!t)return{error:st};let{matchUp:e,updateScore:r}=t;if(!e)return{error:mr};let n=ei({matchUp:e})?.history||[];if(!Array.isArray(n))return{error:B,info:"history is not an array"};let{matchUpFormat:o}=e;if(!o)return{error:Zl};if(!Nr({matchUpFormat:o}))return{error:Jl};let i=Ne(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:O,tiebbreakFormat:v}=M,x=U.side1Score===R&&U.side1Score===U.side2Score,F=!!M.tiebreakSet,w=F?M.tiebreakSet:v,{tiebreakTo:L,NoAD:k}=w||{},G=()=>{d=void 0,l=[0,0],f=3-f,U.side1TiebreakScore="",U.side2TiebreakScore="",U.side1PointScore="",U.side2PointScore="",h=0},H=j=>{U.winningSide=j;let{s:V,...$}=U;p.sets.push($),P=E(),A=y(),U=T(),G()},K=j=>{A.winningSide=j;let{g:V,...$}=A;U.games.push($),P=E(),A=y(),G();let X=`side${j}Score`;U[X]+=1},Y=j=>{P.winningSide=j;let{p:V,...$}=P;A.points.push($),P=E(),h=0;let X=()=>l.reduce((Q,ut)=>Q+ut)%4/4>.5?f:3-f,W=j-1;if(x||F){l[W]+=1,d=X(),U[`side${j}TiebreakScore`]=l[W],U[`side${3-j}TiebreakScore`]=l[1-W];let it=k?1:2;if(l[W]>=L&&l[W]>=l[1-W]+it)return K(j),{gameCompleted:!0}}else if(l[1-W]===4&&l[W]===3?l[1-W]-=1:l[W]+=1,U.side1PointScore=u[l[0]],U.side2PointScore=u[l[1]],l[W]===5||l[W]===4&&l[1-W]<3||O&&l[W]===4)return K(j),{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 V=3-f;Y(V)}if(S(D.p)||It(D.pointNumber)){let j=D.winningSide||D.p;if(Y(j)?.gameCompleted)continue}if(S(D.g)||It(D.gameNumber)){let j=D.winningSide||D.g;A.winningSide=j;let V=`side${j}Score`,$=`side${3-j}Score`;if(m.length&&(m.includes("p"),m=[]),K(j),U[V]===b&&U[V]-U[$]>=(O?1:2)&&(H(j),I))break}if(S(D.s)||It(D.setNumber)){let j=D.winningSide||D.s;if(H(j),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=Mo({...p,matchUpFormat:o}),p.scoreStringSide2=Mo({...p,matchUpFormat:o,reversed:!0}),f=d||f,r&&(e.score=p),{...C,servingSide:f,score:p}}function ri({undoHistory:t,history:e,matchUp:r}){return At({element:r,extension:{value:{history:e,undoHistory:t},name:rd}})}function OD({matchUp:t,sideNumber:e}){if(![1,2].includes(e))return{error:tf};let{history:r=[]}=ei({matchUp:t});return r.push({srv:e}),ri({matchUp:t,history:r})}function vD({matchUp:t}){return ri({matchUp:t})}function _D({matchUp:t,point:e}){if(!e||!t)return{error:st};if(typeof e!="object")return{error:B,context:{point:e}};let{history:r=[]}=ei({matchUp:t});return r.push(e),ri({matchUp:t,history:r})}function xD({matchUp:t,game:e}){if(typeof e!="object")return{error:B,context:{game:e}};let{history:r=[]}=ei({matchUp:t});return r.push(e),ri({matchUp:t,history:r})}function wD({matchUp:t,shot:e}){if(typeof e!="object")return{error:st};let{history:r=[]}=ei({matchUp:t});return r.push(e),ri({matchUp:t,history:r})}function LD({matchUp:t,set:e}){if(typeof e!="object")return{error:st};let{history:r=[]}=ei({matchUp:t});return r.push(e),ri({matchUp:t,history:r})}function FD({matchUp:t}){let{history:e=[],undoHistory:r=[]}=ei({matchUp:t});return r.length&&e.push(r.pop()),ri({matchUp:t,history:e,undoHistory:r})}function kD({matchUp:t}){let{history:e=[],undoHistory:r=[]}=ei({matchUp:t});return r.push(e.pop()),ri({matchUp:t,history:e,undoHistory:r})}var GD={};var cN={};Xt(cN,{keyValueScore:()=>rN,parseMatchUpFormat:()=>Ne,stringifyMatchUpFormat:()=>gp,tidyScore:()=>aN});var o_="COMPLETED";var yV="WO/WO";var FT=["RET","DEF","WO",yV,"ABN","SUS","INT"];var kT="DEFAULTED";var BD="WALKOVER";var GT="ABANDONED",VT="SUSPENDED",HD="RETIRED",BT="INTERRUPTED";var i_=[HD,kT,BD],EV="Enter Score",Rs="()",Cs="[]",WD=["up","left","shift+tab"],jD=["enter","down","tab","right"],$d="backspace",YD="r",qD="s",$D="a",KD="d",zD="w",QD="i",Kd=[YD,KD,zD,$D,qD,QD],Qp="space",HT=["[","("],zd=[...WD,...jD,Qp,"]"],s_="-",AV="/",aa=s_,gi=s_,XD=[AV],a_=0,UV=["=","+","num_1","num_2","shift+=","shift+-"],sa=["0","1","2","3","4","5","6","7","8","9"].concat(Kd),c_=sa.map(t=>`shift+${t}`),JD=[aa,$d].concat(zd,XD),ZD=[sa,c_,JD].join(","),PV=[ZD,WD,jD,UV].join(","),Bbt=[].concat(...sa,...sa,...JD,...sa,...sa,...sa,...sa,...sa,...sa),u_={OUTCOMEKEYS:Kd,SIDE1KEYS:sa,SIDE2KEYS:c_,MODIFIERS:JD,PROMPT:EV,MOVEUP:WD,MOVEDOWN:jD,HOTKEYS:PV};function Xp({scoreString:t,lowSide:e,outcome:r}){if({scoreString:t}=p_({scoreString:t}),e===2){let o=(t&&t[t.length-1])!==" "?" ":"";return t+o+r}else return r+" "+t}function p_({scoreString:t}){if(!t)return{scoreString:""};let e=!1;for(let r of FT){let n=t?.indexOf(r);n===0?t=t.slice(r.length+1).trim()+" ":n>0&&(t=t.slice(0,n)),n>=0&&(e=!0)}return t?.trim()||(t=""),{scoreString:t,removed:e}}function qg({analysis:t,scoreString:e,sets:r,lowSide:n}){let o,i;if(!e)return{scoreString:e,sets:r};let{scoreString:s,removed:a}=p_({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}=ju({brackets:Cs,scoreString:e}),f=DV(e);if(f>=0){o=e.slice(0,f);let{isTiebreakEntry:g}=ju({brackets:Rs,scoreString:o}),{lastOpenBracketIndex:I,isTiebreakEntry:h}=ju({brackets:Cs,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(gi),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(gi)}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 ju({brackets:t=Rs,scoreString:e}){if(!e)return{};let[r,n]=t.split(""),o=e.split(""),i=Math.max(...ho(r,o)),s=Math.max(...ho(n,o));return{isTiebreakEntry:i>s,lastOpenBracketIndex:i}}function m_({scoreString:t}){if(!t)return!1;let e=t&&t[t.length-1].trim(),r=t&&!isNaN(e),[n,o]=Cs.split(""),i=t.split(""),s=Math.max(...ho(n,i)),a=Math.max(...ho(o,i)),c=Math.max(...ho(gi,i));return r&&s>a&&c>s}function DV(t){return t.split("").reduce((n,o,i)=>(o.match(/\d+/g)&&n.push(i),n),[]).pop()}function WT(t){let{lowValue:e=0,NoAD:r=!1,tiebreakTo:n}=t||{},o=r?1:2;return e+1>=n?e+o:parseInt(n)}function tN({matchUpFormat:t,matchUpStatus:e,winningSide:r,sets:n}){let o=Ne(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 i_.includes(e)&&r&&(c=r),{matchUpWinningSide:c}}function Jp({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&&Ne(r);let a=o&&e.finalSetFormat||e?.setFormat||{},{side1Score:c,side2Score:u}=s,{setTo:p,tiebreakAt:m}=a,d=c||u,l=Zp({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 Zp({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 Qd({analysis:t,set:e}){let r=Zp({set:e}),{isDecidingSet:n,isTiebreakSet:o,matchUpScoringFormat:i}=t;return Jp({matchUpScoringFormat:i,isDecidingSet:n,isTiebreakSet:o,set:e})&&r}function d_({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}=NV({analysis:t,set:i,value:n});if(s){o=!0,e=(e||"")+n,i.side2Score=n;let c=Qd({analysis:t,set:r[r.length-1]});if(i.winningSide=c||void 0,a){let u=Rs.split("")[0];e+=u}else t.isDecidingSet||(e+=" ")}return{sets:r,scoreString:e,updated:o}}function NV({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 jT({lowSide:t,value:e,sets:r,scoreString:n,winningSide:o,matchUpStatus:i}){let s;return e===YD?n?(s=!0,n=Xp({scoreString:n,lowSide:t,outcome:"RET"}),o=t===2?1:2,i=HD):(s=!0,n=Xp({scoreString:n,lowSide:t,outcome:"DEF"}),o=t===2?1:2,i=kT):e===KD?(s=!0,n=Xp({scoreString:n,lowSide:t,outcome:"DEF"}),o=t===2?1:2,i=kT):e===zD?(s=!0,r=[],n="WO",o=t===2?1:2,i=BD):e===qD&&n?(s=!0,n=Xp({scoreString:n,lowSide:t,outcome:"SUS"}),i=VT,o=void 0):e===$D?(s=!0,n=Xp({scoreString:n,lowSide:t,outcome:"ABN"}),i=GT,o=void 0):e===QD&&n&&(s=!0,n=Xp({scoreString:n,lowSide:t,outcome:"INT"}),i=BT,o=void 0),{updated:s,sets:r,scoreString:n,matchUpStatus:i,winningSide:o}}function f_(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!==$d&&(e=[{setNumber:1}]);let m=e.length-1;if(Kd.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}=jT({lowSide:a,value:c,sets:e,scoreString:n,matchUpStatus:i,winningSide:o}))}else if(c===$d){if({scoreString:n,sets:e,outcomeRemoved:p}=qg({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===Qp){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===aa&&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 g_({analysis:t,auto:e,lowSide:r,scoreString:n="",sets:o,value:i}){let s,a,{tiebreakSet:{tiebreakTo:c,NoAD:u}}=t.setFormat,[p]=Cs.split("");if(t.isMatchTiebreakEntry||(n+=p),o[t.setNumber-1]){let{lastOpenBracketIndex:d}=ju({brackets:Cs,scoreString:n}),f=(n.slice((d??0)+1)+(e?"":i)).split(gi);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(gi),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=WT({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(gi),s=!0}return{info:a,scoreString:n,sets:o,updated:s}}function I_({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=Rs.split("")[0],d=u.join(aa)+(a?m:" ");r=(r||"")+d;let l={side1Score:u[0],side2Score:u[1]},f=Qd({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 h_({matchUpFormat:t,scoreString:e,winningSide:r,value:n,sets:o}){let s=(o?.filter(K=>K?.winningSide)?.length||0)+(r?0:1),a=Ne(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}=ju({brackets:Rs,scoreString:e}),{isTiebreakEntry:f}=ju({brackets:Cs,scoreString:e}),g=l||f,I=!!u.tiebreakSet,h=e?.[e.length-1]?.trim(),S=e&&!isNaN(h),T=!g&&h===aa,y=l&&HT.includes(h),E=f&&HT.includes(h),P=f&&h===gi,A=e?.split(""),[U]=Cs.split(""),N=A&&Math.max(...ho(U,A)),D=A&&Math.max(...ho(gi,A)),M=A&&D>N,R=o[o.length-1]?.winningSide,b=o?.length&&!R,O=FT.find(K=>e?.indexOf(K)>=0),v=!isNaN(n),x=n===Qp,F=zd.includes(n),w=e?.split("").find(K=>HT.includes(K)),L=F&&f&&!E&&(P||!m_({scoreString:e}));return{isTiebreakSetValue:I&&v,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:v,hasOpener:w,hasOutcome:O,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 rN(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(!ZD.includes(r))return{updated:!1,info:"invalid key"};c&&(e=3-e);let{matchUpWinningSide:l}=tN({sets:o,winningSide:i,matchUpStatus:s,matchUpFormat:a});i=l;let f=h_({value:r,winningSide:i,scoreString:n,sets:o,matchUpFormat:a});if(XD.includes(r)&&(r=aa),f.hasOpener&&f.isTiebreakEntry&&!f.isTiebreakSet&&d&&dt(r)===0&&(f.isTiebreakCloser=!0),zd.includes(r)&&f.hasOpener&&(r=""),zd.includes(r)&&(r=Qp),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}=f_({analysis:f,lowSide:e,scoreString:n,sets:o,matchUpStatus:s,winningSide:i,value:r}));else if(Kd.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}=jT({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===$d)p=!0,{scoreString:n,sets:o}=qg({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===aa&&!f.isMatchTiebreakEntry)(!f.isSetTiebreakEntry||f.isSetTiebreakEntry&&!f.isNumericEnding)&&(p=!0,{scoreString:n,sets:o}=qg({analysis:f,scoreString:n,sets:o,lowSide:e}),s=void 0);else if(r===gi&&f.isMatchTiebreakEntry&&!f.isSetTiebreakEntry)f.matchTiebreakHasJoiner?m="existing joiner":f.isNumericEnding&&(p=!0,n+=gi);else if([aa,gi].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}=d_({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?Rs:Cs,I=g.split("").reverse()[0],h=g.split("")[0],S=o[o.length-1],{tiebreakFormat:T}=f.setFormat,{tiebreakTo:y,NoAD:E}=T||{},P=Zp({set:S});if(!f.isTiebreakSet){let U=parseInt(n.split(h).reverse()[0]),N=WT({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+=" ");let A=Qd({analysis:f,set:S});S.winningSide=A||void 0,p=!0}else if(f.isTiebreakSetValue)({info:m,scoreString:n,sets:o,updated:p}=g_({analysis:f,auto:u,lowSide:e,scoreString:n,sets:o,value:r}));else if(f.isSetTiebreakEntry){let[g]=Rs.split(""),I=Math.max(...ho(g,n.split(""))),h=n.slice(I+1),S=h&&dt(h)===a_,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}=I_({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}=tN({sets:o,winningSide:i,matchUpStatus:s,matchUpFormat:a});return i=g,g&&(!s||[Qt,mn].includes(s))?(s=o_,o=o.filter(I=>{let{side1Score:h,side2Score:S,side1TiebreakScore:T,side2TiebreakScore:y}=I;return h||S||T||y})):n&&!i&&![VT,GT,BT].includes(s)&&(s=void 0),{updated:p,scoreString:n,sets:o,winningSide:i,matchUpStatus:s,info:m}}return{updated:p,scoreString:n,sets:o,winningSide:i,matchUpStatus:s,info:m}}var Xd="\\d+-\\d+",tm="\\d+-\\d+\\(\\d+\\)",$g="\\[\\d+-\\d+\\]",OV="\\d+-\\d+\\(\\d+-\\d+\\)",S_=new RegExp(`(${Xd}),`,"g"),T_=new RegExp(`(${tm}),`,"g"),vV=[Xd,tm,$g,OV],_V=["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"],xV=_V.map(t=>{let r=t.split("").map(n=>vV[n]).join(" ");return new RegExp(`^${r}$`)});function nN(t){return!t||xV.some(e=>e.test(t))}function y_(t){let n="[];()",o=["[","("],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="[];".includes(s)&&"[];"||"()".includes(s)&&"()"||"",d=m.split("").find(l=>l!==s);if(m.includes(u))i[s]||(s="");else return i[u]||(s=""),d}return c}).join("");return t!==a?a:t}function Jd(t){return/^\(\d+\)$/.test(t)||/^\(\d+$/.test(t)}function E_(t){return/^\(\d+-\d+\)$/.test(t)||/^\[\d+-\d+\]$/.test(t)}function Ba(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 em(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 oN(t){return t.length===2?t.split("").join("-"):([", ",",","/"," "].forEach(e=>t=t.split(e).join("-")),t=t.replace(/-{2,}/,"-"),t)}function A_(t){return t.startsWith("(")&&t.endsWith(")")}function U_({score:t,applied:e}){t=y_(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=Er(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(A_)?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 Yu(t){if(!/^[\d-]+(\(\d\))*$/.test(t))return t;let e=ho("-",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 P_({score:t,applied:e}){return t.includes("( ")&&(e.push("removeParenSpacingAfterOpen"),t=t.split("( ").map(r=>r.trim()).join("(")),t.includes(" )")&&(e.push("removeParenSpacingBeforeClose"),t=t.split(" )").map(r=>r.trim()).join(")")),[S_,T_].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(Yu).join(" "),{score:t,applied:e}}function D_({score:t}){if(typeof t!="string")return{score:t};let e=d=>d?.split("-").join("").split("/").join(""),r=d=>d.split("[").join("(").split("]").join(")");t=t.split(", ").join(" ");let n=t.split(" ");t=n.map(d=>{let l=/^-(\d+)$/;if(l.test(d)){let[f]=d.match(l).slice(1);if(f.length===2)return f.split("").join("-")}return d}).join(" "),n=t.split(" ");let o=n.filter(Jd),i=0,s="";for(let d of o){let l=ho(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=>E_(d)&&"bracket"||Ba(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=ho("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;!Ba(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($g).test(d)&&"super"||new RegExp(tm).test(d)&&"tiebreak"||new RegExp(Xd).test(d)&&"standard"||"unknown";return u.push(g),g==="standard"&&f?d.match(l)[1]:d}).join(" "),{score:t}}function N_({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(O=>parseInt(O)),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,O,v]=t.match(r).slice(1);t=t.replace(r,`${D}${M}-${R} ${b}-${O}${v}`),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=Yu(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,O]=M.split("");t=`${D}-${b} ${O}-${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 O=R.match(p).slice(1,3).join("-"),v=b.match(p).slice(1,3).join("-");t=`${O} ${v}`,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 O=R.match(p).slice(1,3).join("-"),v=b.match(p).slice(1,3).join("-");t=`${O} ${v}`,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(""),O=`${D}-${b[0]} ${b[1]}-${R}`;t=t.replace(g,O),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[O,v]=b.match(M).slice(1),x=`${O}-${v}`;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,O]=D.match(/(^|\s)(\d+-\d+)\s(\d+)(\s|$)/).slice(1),[v,x]=R.split("-").map(w=>parseInt(w));Math.abs(v-x)===1&&(t=t.replace(D,`${M}${R}(${b})${O}`),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,O]=D.match(M).slice(1),[v,x]=R.split("-").map(w=>parseInt(w));Math.abs(v-x)===1&&(t=t.replace(D,`${R}(${b})${O}`),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 M_({score:t,matchUpStatus:e}){let r=t?.split(" ");t=r.map(a=>{if(a.endsWith("]")){let c=a.split("[");if(Ba(c[0]))return c[0]+`(${c[1].slice(0,c[1].length-1)})`}return a}).join(" ");let n=new RegExp(/(\([\d ]+\))/g);if(n.test(t))for(let a of t.match(n)){let u=a.replace(" ","-").match(/\((.*)\)/)?.[1];if(Jt(u)&&u?.[0]>2){if([2,4].includes(u.length))u=u.split("").join("-");else if(u.length===3){let p=u.indexOf("1");u=em(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 Ba(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 R_({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=oN(l),h=Yu(I);t=t.replace(m,`(${h})`).trim()}let i=new RegExp(/\[[\d,/ ]+\]/g);t.match(i)?.forEach(m=>{let d=oN(m.match(/^\[(.*)\]$/)[1]);t=t.replace(m,`(${d}) `).trim()});let a=[")","]"],c=[")(","), (",") (",")[",") [","](","] ("];if(t.startsWith("(")&&a.some(m=>t.endsWith(m))&&c.some(m=>t.includes(m))){let m="",d=t.split(/[)\]]/).filter(Boolean).map(h=>(h.startsWith(",")&&(h=h.slice(1)),h.trim())),l=d.every(h=>h.includes(",")||Jd(h)),f=d.every(h=>h.includes("/")||Jd(h)),g=d.every(h=>h.includes("-")||Jd(h)),I=l&&","||g&&"-"||f&&"/";if(I){let h;d.forEach(S=>{if(S.startsWith("("))if(h==="set"&&(m+=" "),S.includes(I))m+=S.slice(1).split(I).map(T=>T.trim()).join("-"),h="set";else{let T=S.slice(1);m+=`(${T}) `,h="tiebreak"}else if(S.startsWith("[")){let T=S.slice(1).split(I).map(E=>parseInt(E.trim())),y=Math.min(...T);h==="set"?m+=`(${y}) `:m+=`[${T.join("-")}] `,h="tiebreak"}}),t=m.trim()}}let u=Er(t.split(""));u["("]===1&&u[")"]===1&&t.startsWith("(")&&t.endsWith(")")&&(t=t.slice(1,t.length-1),u["-"]===1&&Ba(t)&&Jt(e?.removed)&&(t=t+`(${e.removed})`,e.removed=void 0));let p=/\(\)/g;return p.test(t)&&(t=t.replace(p,"").trim()),{score:t}}function YT({score:t}){let e=t.split(""),r=[],n,o=()=>n=[void 0,void 0,void 0],i=()=>{let a=`${n[0]}-${n[1]}`;return n[2]&&(a+=` (${n[2]})`),o(),n.push(n),a};o();let s=()=>n[0]!==void 0&&n[1]!==void 0&&Math.abs(parseInt(n[0])-parseInt(n[1]));for(;e.length;){let a=e.shift(),c=Jt(a)&&parseInt(a),u=n[0]!==void 0&&n[1]!==void 0;if(Jt(c)){if(n[0]===void 0){n[0]=c;continue}if(n[1]===void 0&&(n[1]=c,s())){r.push(i()),n=[void 0,void 0];continue}if(u&&e.length===1&&Jt(e[0])){let p=e.pop();n[0]=n[0].toString()+n[1].toString(),n[1]=p,r.push(i()),n=[void 0,void 0]}u&&s()}}return{sets:r}}function Kg(t){let e=t.indexOf("1"),r=t.split(""),n=r.every(o=>!isNaN(o));if(n&&t.length===3&&e===0){let o=em(r,e);if(o)return o}if(n&&t.length===7&&e>3){let o=r.slice(4),i=em(o,e-4);if(i)return`${r[0]}-${r[1]} ${r[2]}-${r[3]} ${i}`}}function iN(t){let{score:e}=t,{applied:r,matchUpStatus:n}=t,o=e?.toString().split(""),i=o?.every(a=>Jt(a)),s=a=>Math.abs(a[0]-a[1]);if(typeof e=="number"||i){e=e.toString().toLowerCase(),i&&(e=o.join(""));let a=i?o.map(u=>parseInt(u)):e.split("").map(u=>parseInt(u)),{sets:c}=YT({score:e});if(a.length,e.length===3&&s(a.slice(0,2))===1){let[u,p,m]=a;e=`${u}-${p}(${m})`,r.push("numericTiebreakPattern1")}else if(e.length===3&&a[0]===1){let[u,p,m]=a;e=`[${u}${p}-${m}]`,r.push("numericTiebreakPattern2")}else if(e.length===4&&s(a.slice(0,2))===1&&"987654".split("").includes(a[0].toString())){let[u,p,m,d]=a,l=Math.min(m,d);e=`${u}-${p}(${l})`,r.push("numericTiebreakPattern3")}else if(e.length===4&&a[0]===1&&a[2]===1){let[u,p,m,d]=a;e=`[${u}${p}-${m}${d}]`,r.push("bigSuper")}else if(e.length===4){let[u,p,m,d]=a;e=`${u}${p} ${m}${d}`,r.push("split4")}else if(e.length===5&&s(a.slice(0,2))===1){let[u,p,m,d,l]=a;e=`${u}-${p}(${m}) ${d}-${l}`,r.push("numericTiebreakPattern4")}else if(e.length===5&&s(a.slice(3))===1){let[u,p,m,d,l]=a;e=`${u}-${p} ${m}-${d}(${l})`,r.push("numericTiebreakPattern5")}else if(a.length===7)if(s(a.slice(0,2))>1&&s(a.slice(2,4))>1&&a[4]===1){let[u,p,m,d,l,f,g]=a;e=`${u}-${p} ${m}-${d} [${l}${f}-${g}]`,r.push("numericTiebreakPattern6")}else if(s(a.slice(0,2))===1&&s(a.slice(3,5))>1&&s(a.slice(5,7))>1){let[u,p,m,d,l,f,g]=a;e=`${u}-${p}(${m}) ${d}-${l} ${f}-${g}`,r.push("numericTiebreakPattern7")}else if(s(a.slice(0,2))>1&&s(a.slice(2,4))===1&&s(a.slice(5,7))>1){let[u,p,m,d,l,f,g]=a;e=`${u}-${p} ${m}-${d}(${l}) ${f}-${g}`,r.push("numericTiebreakPattern8")}else if(s(a.slice(0,2))>1&&s(a.slice(2,4))>1&&s(a.slice(4,6))===1){let[u,p,m,d,l,f,g]=a;e=`${u}-${p} ${m}-${d} ${l}-${f}(${g})`,r.push("numericTiebreakPattern9")}else e=e.slice(0,2)+" "+e.slice(2,4)+" "+e.slice(4),r.push("numericMatchTiebreakPattern");else if(e.length%2){let u=Kg(e);u&&e!==u&&r.push("parsedSuperPattern"),e=u??e}else{let u=Ae(e.split(""),2).map(h=>h.join("")),p=u.map(h=>{let[S,T]=h.split("").map(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=Er(p),l=p.map(h=>Math.abs(h)),f=Er(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 qT(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 C_({score:t,matchUpStatus:e,attributes:r}){let n=[],o,i=t.split(" "),s=i.length;t=i.map((p,m)=>{if(new RegExp(tm).test(p)){let l=p.slice(3),f=p.slice(0,3),g=f.split("-");if(!Ba(f)&&!e){let I=Math.max(...g),h=f.indexOf(I),S=[I,I-1];return h&&S.reverse(),S.join("-")+l}}else if(p.length===2&&Jt(p))return p.split("").join("-");p=Yu(p);let d=new RegExp(`^${$g}$`).test(p)&&"super"||new RegExp(`^${tm}$`).test(p)&&"tiebreak"||new RegExp(`^${Xd}$`).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}=qT(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 b_({score:t}){let{setsTied:e,winningSide:r}=qT(t),n=/\s\((\d+)\)$/;if(!r&&e&&n.test(t)){let a=t.match(n).slice(1)[0],c=a<=8?10:a+2;t=t.replace(n,` [${c}-${a}]`)}let o=t.split(" "),i=o[o.length-1];if(!i.includes("-")||i.indexOf("(")>0)return{score:t};let s=i.split("(").join("").split(")").join("").split("-");if(!s.every(a=>Jt(a)))return{score:t};if(s[0]==="76"){let a=s[1].length===2?Math.min(...s[1].split("").map(c=>parseInt(c))):s[1];t=[...o.slice(0,o.length-1),`7-6(${a})`].join(" ")}else{s=s.map(u=>parseInt(u));let a=Math.max(...s),c=Math.abs(s[0]-s[1]);if(a>=10){if(c>2&&s.every(u=>+u>=10)){let u=s.map(p=>p===a?p-10:10).sort();c=Math.abs(u[0]-u[1]),c>2&&(s=u)}t=[...o.slice(0,o.length-1),`[${s.join("-")}]`].join(" ")}else o.length===3&&a>=7&&c>2&&(t=[...o.slice(0,o.length-1),`[${s.join("-")}]`].join(" "))}return{score:t}}function wV({score:t}){return t=t?.toString().toLowerCase()||"",{score:t}}function LV({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 FV({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=em(r.split(""),n);return e.push("getSuper"),o}}else{let{score:o,applied:i}=iN({score:r,applied:[]});o!==r&&(r=o,e.push(...i))}}return r}).join(" "),{score:t,applied:e})}function kV({score:t,applied:e}){return typeof t!="string"?{score:t}:[3,4].includes(t.length)&&Kg(t)?{score:Kg(t)}:(t=t.toLowerCase().split(" ").map(r=>{if(/^\d+$/.test(r)&&r.length===1){e.push("removeErroneous1");return}return r}).filter(Boolean).join(" "),{score:t,applied:e})}function 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 VV({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 BV({score:t,profile:e,applied:r}){t=t?.toString().toLowerCase();let n=/^(.*\d+.*)(def|defaulted)+[A-Za-z ]*$/;if(n.test(t)){let[a]=t.match(n).slice(1);return r.push("handleDefaulted"),{score:a.trim(),matchUpStatus:"defaulted",applied:r}}let o=e?.matchUpStatuses?.defaulted,s=["dft",...Array.isArray(o)?o:[o].filter(Boolean)].find(a=>t?.endsWith(a));return s?(r.push("handleDefaulted"),{matchUpStatus:"defaulted",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 WV({score:t}){return new RegExp(/-\d+\/\d+-/).test(t)&&(t=t.split("/").join(" ")),{score:t}}function jV({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 qV({score:t}){if(t.includes(",")){let e=t.split(",").map(o=>o.trim()),r=o=>/\d \d/.test(o);e.every(r)&&(t=e.map(o=>{let i=/\d+ \d+/g;for(let s of o.match(i)){let[a,c]=s.match(/(\d+) (\d+)/).slice(1);o=o.replace(s,`${a}-${c}`)}return o}).join(" "))}if(t.includes(" ")){let e=t.replace(/[ ,]/g,"");e.split("").every(n=>Jt(n))&&e.length===4&&(t=e)}return{score:t}}function $V({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 O_={handleTiebreakSlashSeparation:YV,handleSetSlashSeparation:WV,punctuationAdjustments:U_,handleGameSeparation:jV,joinFloatingTiebreak:D_,handleBracketSpacing:P_,handleSpaceSeparator:qV,separateScoreBlocks:FV,matchKnownPatterns:N_,removeDanglingBits:HV,removeErroneous:kV,handleDefaulted:BV,handleWalkover:GV,properTiebreak:M_,handleNumeric:iN,handleRetired:VV,containedSets:R_,sensibleSets:C_,stringScore:wV,superSquare:b_,setBuilder:YT,excisions:$V,replaceOh:LV};var sN={},KV=[],zV=["handleNumeric","handleWalkover","handleRetired","handleDefaulted","replaceOh","stringScore","punctuationAdjustments","excisions","handleSpaceSeparator","matchKnownPatterns","removeDanglingBits","handleBracketSpacing","matchKnownPatterns","containedSets","separateScoreBlocks","handleGameSeparation","removeErroneous","joinFloatingTiebreak","handleSetSlashSeparation","handleTiebreakSlashSeparation","properTiebreak","sensibleSets","superSquare"],QV=["handleNumeric","separateScoreBlocks","sensibleSets","superSquare"];function aN(t){if(!t.score)return{error:B};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=O_[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(zV);let g=nN(l);return g||(l=e.toString().replaceAll(/\D/g,""),m?.removed&&(m.removed=void 0),f(QV),g=nN(l),g||(KV.push({score:l,fileName:o,sheetName:r}),l="")),p.forEach(I=>{sN[I]||(sN[I]=0),sN[I]+=1}),{matchUpStatus:u?.toUpperCase(),modifications:c,attributes:m,isValid:g,score:l}}var mN={};Xt(mN,{analyzeScore:()=>zg,analyzeSet:()=>qu,checkScoreHasValue:()=>he,checkSetIsComplete:()=>Jp,getSetComplement:()=>Xg,getTiebreakComplement:()=>rm,isValidMatchUpFormat:()=>Nr,parseScoreString:()=>nm,validateMatchUpScore:()=>uN,validateScore:()=>Qg,validateSetScore:()=>$T,validateTieFormat:()=>ar});function XV(t,e,r,n,o,i=!1){return o?{isValid:!0}:t===0&&e===0?{isValid:!1,error:"Tiebreak-only set requires both scores"}:t<n?{isValid:!1,error:`Tiebreak-only set winner must reach at least ${n}, got ${t}`}:r<(i?1:2)?{isValid:!1,error:i?`Tiebreak-only set (NoAD) must be won by at least 1 point, got ${t}-${e}`:`Tiebreak-only set must be won by at least 2 points, got ${t}-${e}`}:i?{isValid:!0}:t===n&&e>n-2?{isValid:!1,error:`Tiebreak-only set at ${n}-${e} requires playing past ${n}`}:t>n&&r!==2?{isValid:!1,error:`Tiebreak-only set past ${n} must be won by exactly 2 points, got ${t}-${e}`}:{isValid:!0}}function JV(t,e,r,n){let o=n===r?r+1:r,i=n;return t!==o?{isValid:!1,error:`Tiebreak set winner must have ${o} games, got ${t}`}:e!==i?{isValid:!1,error:`Tiebreak set loser must have ${i} games, got ${e}`}:{isValid:!0}}function ZV(t,e,r){let n=Math.max(t||0,e||0),o=Math.min(t||0,e||0),i=n-o,s=r.tiebreakTo||7;return n<s?{isValid:!1,error:`Tiebreak winner must reach ${s} points, got ${n}`}:i<2?{isValid:!1,error:`Tiebreak must be won by 2 points, got ${n}-${o}`}:o>=s-1&&i>2?{isValid:!1,error:`Tiebreak score ${n}-${o} is invalid`}:{isValid:!0}}function t1(t,e,r,n){return n?t===r+1&&e<r-1?{isValid:!1,error:`With tiebreak format, if side 1 has ${r+1} games, side 2 must be at least ${r-1}, got ${e}`}:e===r+1&&t<r-1?{isValid:!1,error:`With tiebreak format, if side 2 has ${r+1} games, side 1 must be at least ${r-1}, got ${t}`}:{isValid:!0}:{isValid:!0}}function e1(t,e,r,n,o){if(t<n)return{isValid:!1,error:`Set winner must reach ${n} games, got ${t}`};let i=o&&t===n&&e===o&&r===1;if(r<2&&!i)return{isValid:!1,error:`Set must be won by at least 2 games, got ${t}-${e}`};if(o){if(e>=o&&!i)return{isValid:!1,error:`When tied at ${o}-${o}, must play tiebreak. Use format like ${o+1}-${o}(5)`};let s=o===n?n+1:n;if(t>s)return{isValid:!1,error:`With tiebreak format, set score cannot exceed ${s}-${o}. Got ${t}-${e}`}}else if(t>n+10)return{isValid:!1,error:`Set score ${t}-${e} exceeds reasonable limits`};return{isValid:!0}}function r1(t,e,r){let n=t.side1TiebreakScore,o=t.side2TiebreakScore,i=e&&r?n:t.side1Score||t.side1||0,s=e&&r?o:t.side2Score||t.side2||0;return{side1Score:i,side2Score:s,side1TiebreakScore:n,side2TiebreakScore:o}}function n1(t,e,r,n,o,i,s){if(r&&n){let c=JV(t,e,r,n);if(!c.isValid)return c}return(o!==void 0||i!==void 0)&&s?ZV(o,i,s):{isValid:!0}}function o1(t,e,r){return r&&(t>r+10||e>r+10)?{isValid:!1,error:`Set score ${t}-${e} exceeds expected range for ${r}-game sets`}:{isValid:!0}}function i1(t,e,r){let{side1:n,side2:o,winner:i,loser:s,diff:a}=t,{setTo:c,tiebreakAt:u}=e;if(c&&u){let p=t1(n,o,c,u);if(!p.isValid)return p}return r?o1(i,s,c):c?e1(i,s,a,c,u):{isValid:!0}}function $T(t,e,r,n){if(!e)return{isValid:!0};let o=Ne(e);if(!o)return{isValid:!0};let i=r&&o.finalSetFormat?o.finalSetFormat:o.setFormat;if(!i)return{isValid:!0};if(i.timed){if(!n){let A=t.side1Score??0,U=t.side2Score??0;if(A===0&&U===0)return{isValid:!1,error:"Timed set requires at least one side to have scored"};if(i.based==="P"&&A===U&&A>0&&i.tiebreakFormat&&!(t.side1TiebreakScore!==void 0||t.side2TiebreakScore!==void 0))return{isValid:!1,error:"Tied timed set requires tiebreak"}}return{isValid:!0}}let{setTo:s,tiebreakAt:a,tiebreakFormat:c,tiebreakSet:u}=i,p=u?.tiebreakTo,m=!!p&&!s,d=t.side1TiebreakScore!==void 0&&t.side2TiebreakScore!==void 0,{side1Score:l,side2Score:f,side1TiebreakScore:g,side2TiebreakScore:I}=r1(t,m,d),h=Math.max(l,f),S=Math.min(l,f),T=h-S;if(m){let A=t.NoAD??i.tiebreakSet?.NoAD??!1;return XV(h,S,T,p,n??!1,A)}let y=g!==void 0||I!==void 0,E=s&&h===s+1&&S===s;return y||E?n1(h,S,s,a,g,I,c):i1({side1:l,side2:f,winner:h,loser:S,diff:T},{setTo:s,tiebreakAt:a},n)}function uN(t,e,r){if(!t||t.length===0)return{isValid:!0};let n=e?.match(/SET(\d+)/)?.[1],o=n?Number.parseInt(n):3,i=[Me,Bt,Gt].includes(r||"");for(let s=0;s<t.length;s++){let a=t[s],c=s+1===o,u=a.winningSide!==void 0,d=$T(a,e,c,i||r===void 0&&!u);if(!d.isValid)return{isValid:!1,error:`Set ${s+1}: ${d.error}`}}return{isValid:!0}}function s1(t,e,r,n,o,i){let{tiebreakTo:s,NoAD:a}=t||{},c=Math.max(e??0,r??0);return!(a&&c>s||c<s&&n&&(o&&!i||!o))}function a1(t,e,r,n,o,i){let a=e+1===n,{side1Score:c,side2Score:u,side1TiebreakScore:p,side2TiebreakScore:m,winningSide:d}=t,l=Math.max(c??0,u??0),f=p??m,{finalSetFormat:g,setFormat:I}=r,h=a&&g||I;return f&&!s1(h?.tiebreakFormat,p,m,d,o,i)?!1:h.setTo?!(!h.noTiebreak&&l>h.setTo+1):!0}function c1(t){let e=t.reduce((r,n)=>((n.side1Score!==void 0||n.side2Score!==void 0)&&(r[0]+=n.side1Score??0,r[1]+=n.side2Score??0),r),[0,0]);return e[0]>e[1]?1:e[1]>e[0]?2:t.find(n=>n.side1TiebreakScore!==void 0||n.side2TiebreakScore!==void 0)?.winningSide}function u1(t,e,r,n,o){return(!o||t===e)&&r===1&&n.indexOf(t)+1||void 0}function zg({existingMatchUpStatus:t,matchUpFormat:e,matchUpStatus:r,winningSide:n,score:o}){let i=o?.sets??[],a=(i?.filter(U=>U?.winningSide)||[]).reduce((U,N)=>{let{winningSide:D}=N;if(!D)return U;let M=D-1;return U[M]++,U},[0,0]),c=n?n-1:void 0,u=c!==void 0&&[0,1].includes(c)?1-c:void 0,p=c!==void 0&&a[c],m=u!==void 0&&a[u],d=e?Ne(e):void 0,l=Math.max(...a),f=Er(a)[l],g=d?.setFormat?.timed||d?.finalSetFormat?.timed,I=d?.bestOf||d?.exactly,h=I&&Math.ceil(I/2)||1,S=r??t,T=!!(S&&[Gt,Me,Bt].includes(S)),y=!d||!i.length||i.every((U,N)=>a1(U,N,d,I??0,N===i.length-1,T)),E=d?.setFormat?.based==="A"||d?.finalSetFormat?.based==="A",P=E&&i.length>0?c1(i):u1(l,h,f,a,e);return{valid:!!(y&&(n&&E&&n===P||n&&!E&&p>m&&n===P||n&&T||!n&&!P&&(![ge,Gt,Me,Bt].includes(S)||g&&S===ge)))}}function Qg({existingMatchUpStatus:t,matchUpFormat:e,matchUpStatus:r,winningSide:n,score:o}){if(typeof o!="object")return{error:B};let{sets:i,scoreStringSide1:s,scoreStringSide2:a}=o,c="scoreString must be a string!";if(s!==void 0&&typeof s!="string")return{error:B,info:c};if(a!==void 0&&typeof a!="string")return{error:B,info:c};if(i!==void 0&&!Array.isArray(i))return{error:B,info:li("sets")};if(i?.length){let u=i.map(m=>m?.setNumber).filter(Boolean);if(u.length!==pt(u).length)return{error:B,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:B,info:"non-numeric values"};if(![T,S].filter(P=>![void 0,null].includes(P)).every(P=>It(P)))return{error:B,info:"non-numeric values"};if(S&&![1,2].includes(S))return{error:B,info:"winningSide must be 1 or 2"}}let{valid:p}=zg({existingMatchUpStatus:t,matchUpStatus:r,matchUpFormat:e,winningSide:n,score:o});if(!p)return{error:IA,info:"score is invalid for matchUpFormat or winningSide does not match calculated winningSide"}}return{valid:!0}}var Xg=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]},rm=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=p1({lowValue:i,NoAD:o,tiebreakTo:n});return[e?i:s,e?s:i]};function p1(t){let{lowValue:e,NoAD:r,tiebreakTo:n}=t,o=r?1:2;return e+1>=n?e+o:n}function pN(t,e){return t>e&&1||t<e&&2||void 0}function m1(t,e){return e?{side1Score:t[0],side2Score:t[1],winningSide:pN(t[0],t[1])}:{side1TiebreakScore:t[0],side2TiebreakScore:t[1],winningSide:pN(t[0],t[1])}}function nm({tiebreakTo:t=7,scoreString:e="",matchUpFormat:r}){let n,o=3;if(r)try{n=Ne(r);let p=/SET(\d+)/.exec(r)?.[1];o=p?Number.parseInt(p):3}catch{}return e?.split(" ").filter(Boolean).map((p,m)=>u({set:p,setNumber:m+1}));function i(p,m){if(!n||!m)return!1;let l=p===o&&n.finalSetFormat?n.finalSetFormat:n.setFormat;if(!l)return!1;let f=l.tiebreakSet?.tiebreakTo,g=l.setTo;return!!f&&!g}function s(p){if(!n)return t;let d=p===o&&n.finalSetFormat?n.finalSetFormat:n.setFormat;return d?.tiebreakSet?.tiebreakTo??d?.tiebreakFormat?.tiebreakTo??t}function a(p,m,d){let l=p[1],f=s(d),g=rm({lowValue:l,isSide1:m===2,tiebreakTo:f});return Array.isArray(g)?[g[0],g[1]]:[void 0,void 0]}function c(p,m,d,l){let g=(m&&p.replace(m[0],"")||d&&p.replace(d[0],"")||p).split("-").map(E=>Number.parseInt(E)),I=g[0],h=g[1],S=pN(I,h),T,y;if(m&&([T,y]=a(m,S,l)),d){let E=d[1].split("-").map(P=>Number.parseInt(P));T=E[0],y=E[1]}return{side1Score:I,side2Score:h,side1TiebreakScore:T,side2TiebreakScore:y,winningSide:S}}function u({set:p,setNumber:m}){let d=/\(([^)]+)\)/,l=/\[([^\]]+)\]/,f=d.exec(p),g=l.exec(p),I=p?.startsWith("[")&&g,h=i(m,!!I),S=s(m),T=h&&S===1,y;if(I){let E=g[1].split("-").map(P=>Number.parseInt(P));y=m1(E,h)}else y=c(p,f,g,m);return{side1Score:y.side1Score,side2Score:y.side2Score,side1TiebreakScore:y.side1TiebreakScore,side2TiebreakScore:y.side2TiebreakScore,winningSide:y.winningSide,setNumber:m,...T&&{NoAD:!0},...h&&{tiebreakSet:!0}}}}function v_({matchUpScoringFormat:t,isDecidingSet:e,isTiebreakSet:r,isTimedSet:n,setObject:o}){if(!o)return;let i=Zp({set:o});return Jp({matchUpScoringFormat:t,set:o,isDecidingSet:e,isTiebreakSet:r,isTimedSet:n})&&i||void 0}function qu(t){let{setObject:e,matchUpScoringFormat:r}=t;if(!e)return{error:ef};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}=d1({sideTiebreakScores:g,sideGameScores:l,setFormat:c,setObject:e}),{error:R,result:b}=l1({sideTiebreakScores:g,setObject:e,setFormat:c}),O=m&&!U&&M||u&&U&&b||p,v=d&&!(u&&!U)&&!(m&&U)&&(!N||O),x=v_({isTimedSet:p,matchUpScoringFormat:r,isDecidingSet:a,isTiebreakSet:U,setObject:e}),F={expectTiebreakSet:u,expectTimedSet:p,hasTiebreakCondition:P,isCompletedSet:N,isDecidingSet:a,isTiebreakSet:U,isValidSet:v,isValidSetNumber:d,isValidSetOutcome:O,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 d1({setObject:t,setFormat:e,sideGameScores:r,sideTiebreakScores:n}){if(!t)return{result:!1,error:ef};let o=!!e?.tiebreakSet,i=!!e?.timed;if(!e||o||i)return{result:!1,error:B};if(!(r?.filter(M=>!isNaN(M)).length===2))return{result:!1,error:KI};let{setTo:a,tiebreakAt:c,tiebreakFormat:u,NoAD:p}=e||{};if(!!!(a&&r?.find(M=>M>=a)))return{result:!1,error:KI};let d=[1,2].includes(t?.winningSide);if(!t||!d)return{result:!1,error:_m};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(k=>k>=R)))return{result:!1,error:{message:"invalid tiebreak scores (2)"}};let v=c<a?a:a+1;if(g>v)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 l1({setObject:t,setFormat:e,sideTiebreakScores:r}){if(!t)return{result:!1,error:ef};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:_m};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 __(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&&io({namedFormat:o,hydrateCollections:r,isMock:a,event:c})||c?.tieFormat||io({event:c,isMock:a,hydrateCollections:r}),p=void 0}else p||(u=void 0,c?.matchUpFormat||(p=bn));if(u){let m=ar({gender:c?.gender,enforceGender:n,tieFormat:u});if(m.error)return m}return{tieFormat:u,matchUpFormat:p}}function x_(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?OT({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}=Us({stageSequence:1,drawDefinition:e,structureId:s,stage:rt}),S=Math.max(l??0,h??0),T=$S({qualifiersCount:S,drawDefinition:e,stage:rt});if(T.error||(T=Hp({drawSize:f,stage:ct,drawDefinition:e}),T.error))return T;f1({drawDefinition:e,drawEntries:i,event:p});let y=g1({mainStructure:I,qualifyingDetails:g,drawDefinition:e});return y.error?y:{drawDefinition:e,structureId:s}}function f1({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};Pd(o)}}function g1({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&&La({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 KT(t){let{participantIds:e}=t,r=t.drawDefinition?.entries?.filter(n=>{let o=n.entryStatus;return!t.restrictEntryStatus||Xr.includes(o)}).map(St)??[];if(e){let n=e.filter(o=>!r?.includes(o));if(n?.length)return _({result:{error:ln},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:B,info:"Not enough participants for roundsCount"}:t.roundsCount&&t.restrictRoundsCount!==!1&&t.roundsCount>31?{error:B,info:"roundsCount must be less than 32"}:{participantIds:e}}function Zd(t){let e=[],{roundsCount:r=1,drawDefinition:n,matchUpsCount:o,structureId:i,idPrefix:s,isMock:a,event:c}=t,u,p=KT(t);if(p.error)return p;for(let m of tt(1,r+1)){let d=Wu({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 L_(t){let{tournamentRecord:e,participantIds:r,scaleName:n,eventType:o,adHocRatings:i={}}=t,s=t.scaleAccessor??je[n]?.accessor,a=e.participants??[];for(let c of r??[]){let u=a?.find(m=>m.participantId===c),p=w_({scaleName:`${n}.${Qm}`,participant:u,eventType:o});!p&&n&&(p=w_({scaleAccessor:s,participant:u,scaleName:n,eventType:o})),p&&!i[c]&&(i[c]=p)}return i}function w_({scaleType:t=Ui,scaleAccessor:e,participant:r,scaleName:n,eventType:o}){let a=(r&&Po({scaleAttributes:{eventType:o??qs,scaleType:t,scaleName:n},participant:r}))?.scaleItem?.scaleValue;return e&&ht(a)?a[e]:a}function tl(t){let e=h1(t);if(e?.error)return e;let r=KT(t);if(r.error)return r;let n=I1(t);if(n.error)return n;let o=L_(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=qd({...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 I1(t){if(t.structureId)return t.structureId;let e=t.drawDefinition,r=e?.structures?.filter(i=>i.stageSequence===1)?.reduce((i,s)=>{let a=s.stage&&$s[s.stage];return cr({structure:s})&&a>($s[i?.stage]||1)?s:i},void 0),n=e?.structures?.find(i=>i.structureId===r?.structureId);return n?cr({structure:n})?{structure:n}:{error:Sa}:{error:_t}}function h1(t){return t.roundsCount&&typeof t.roundsCount!="number"?{error:B,info:"roundsCount must be a number"}:typeof t.drawDefinition!="object"||t.drawDefinition.drawType&&t.drawDefinition.drawType!==Fr?{error:Sa}:!Array.isArray(t.drawDefinition?.entries)&&t.participantIds&&!Array.isArray(t.participantIds)?{error:B,info:"Missing Entries"}:{error:void 0}}function F_(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&&Xr.includes(m)),c=a?.map(St),u=a?Math.floor(a.length/2):0;if(t.automated)return S1({...t,participantIds:c});{let p=Zd({roundsCount:t.roundsCount,drawDefinition:r,matchUpsCount:u,idPrefix:o,isMock:i,event:s});if(p.error)return p;p.matchUps?.length&&Gd({matchUps:p.matchUps,suppressNotifications:!0,tournamentRecord:e,drawDefinition:r,structureId:n,event:s})}return{...C}}function S1(t){let{restrictEntryStatus:e,generateMatchUps:r,structureId:n,matchUpIds:o,scaleName:i,scaleAccessor:s}=t.drawMatic??{},a=tl({...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&&Gd({tournamentRecord:t.tournamentRecord,drawDefinition:t.drawDefinition,suppressNotifications:!0,matchUps:a.matchUps,event:t.event,structureId:n}),{...C})}function k_({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:_t};let{positionAssignments:d}=Ie({structure:m}),l=d?.length||0;if(u>l)return{error:$E};let f=m.structures?.length,g=It(a?.groupSeedingThreshold)&&a?.groupSeedingThreshold,I=Dg({roundRobinGroupsCount:f,drawSize:l})?.seedGroups,{seedsCount:h}=Hu({policyDefinitions:i,requireParticipantCount:t,drawSizeProgression:r,participantsCount:n,drawSize:l});return h&&i?.[Vn]&&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}}),bt({drawDefinition:s,structureIds:[c]}),{...C,seedLimit:u}}function ca({sortDescending:t=!1,tournamentRecord:e,scaleAttributes:r,scaleSortMethod:n,stageSequence:o,entries:i,event:s,stage:a}){if(!e)return{error:q};return i=i??s?.entries??[],{scaledEntries:i.filter(d=>(!a||!d.entryStage||d.entryStage===a)&&(!o||!d.entryStageSequence||d.entryStageSequence===o)&&Xr.includes(d.entryStatus)).map(d=>{let{participantId:l}=d,{scaleItem:f}=wc({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 zT(t){let e="prepareStage",{drawDefinition:r}=t,{structures:n}=hn({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:_t},stack:e});let s=i?.structureId,{seedsCount:a,stageEntries:c,seedLimit:u}=N1({...t,structureId:s});(t.seededParticipants||t.event||t.seedingScaleName)&&E1({...t,seedsCount:a,structure:i,structureId:s});let p=t.automated!==!1&&t.drawType!==Fr&&!(t.qualifyingOnly&&t.stage!==ct),m=(n?.length||0)>1,d=p?y1({...t,multipleStructures:m,seedLimit:u,structureId:s}):{};return d?.error?_({result:d,stack:e}):{...d,stageEntries:c,structureId:s,seedsCount:a}}function T1({entries:t,stage:e,stageSequence:r,roundTarget:n}){return t.filter(o=>{let i=mt({name:vn,element:o})?.extension?.value;return(!o.entryStage||o.entryStage===e)&&(!r||!o.entryStageSequence||o.entryStageSequence===r)&&(!n||!i||i===n)&&mi.includes(o.entryStatus)})}function y1(t){let e=typeof t.automated=="object"&&t.automated.seedsOnly,r=Mc({...t,seedsOnly:e});if(r.error)return r;let n=r?.positionAssignments,o=r?.positioningReport;return{conflicts:r.conflicts,positionAssignments:n,positioningReport:o}}function E1(t){let{seededParticipants:e,seedingScaleName:r,entries:n,event:o}=t,i=n.map(St);e?A1({...t,enteredParticipantIds:i}):(o||r)&&U1({...t,enteredParticipantIds:i})}function A1(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?Ns({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;ra({provisionalPositioning:e,tournamentRecord:o,drawDefinition:s,seedingProfile:a,participantId:l,seedBlockInfo:m,structureId:c,seedNumber:f,seedValue:g,event:p})})}function U1(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=P1({...t,ageCategoryCode:l,categoryName:d,eventType:f})||c&&D1({...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;ra({provisionalPositioning:r,tournamentRecord:s,drawDefinition:a,seedingProfile:u,participantId:y,structureId:p,seedNumber:T,seedValue:P,event:m})})}function P1(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:Ao,eventType:u};return ca({scaleAttributes:p,tournamentRecord:e,stageSequence:n,entries:o,stage:i}).scaledEntries}function D1(t){let{tournamentRecord:e,stageSequence:r,event:n,entries:o,stage:i}=t,{categoryName:s,ageCategoryCode:a}=n?.category||{},c=n?.eventType;return ca({scaleAttributes:{scaleName:s||a,scaleType:Ai,eventType:c},tournamentRecord:e,stageSequence:r,entries:o,stage:i}).scaledEntries}function N1(t){let{seedsCount:e}=t;t.seededParticipants&&(e=t.seededParticipants.length),e>t.drawSize&&(e=t.drawSize);let r=T1(t);e>r.length&&(e=r.length);let{seedLimit:n}=k_({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 G_(t){let e=jd({...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=M1({suppressDuplicateEntries:n,ignoreStageSpace:o,drawDefinition:r,drawEntries:u,drawType:d,entries:l});if(I.error)return I;let h=d===Ki?0:dt(t.seedsCount??0),S=zT({...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===Fr&&t.roundsCount&&F_({...t,drawDefinition:r,structureId:T}),{drawDefinition:r,positioningReports:f,conflicts:g,structureId:T}}function M1(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===Fr,entryStage:s.entryStage??rt,event:t.event,drawDefinition:r,drawType:o},c=Pd(a);if(n&&c.error)return c}return{error:void 0}}var R1=()=>({matchUpType:void 0,drawName:void 0,drawId:void 0,structures:[],entries:[],links:[]});var V_=R1;function B_(t){let{drawId:e=Nt(),processCodes:r,matchUpType:n,drawType:o}=t??{},i=V_();return Object.assign(i,{processCodes:r,matchUpType:n,drawType:o,drawId:e})}function el(t){let e=t.structureIds,{tournamentRecord:r,drawDefinition:n,matchUpFormat:o,structureId:i,matchUpId:s,event:a}=t,c=et(t,[{[Ce]:!0,[$m]:!0}]);if(c.error)return c;if(!Nr({matchUpFormat:o}))return{error:tc};let u="setMatchUpFormat";if(s){let p=Vt({drawDefinition:n,matchUpId:s,event:a});if(p.error)return p;let m=p.matchUp;if(m?.matchUpType===_e)return{info:"Cannot set matchUpFormat when { matchUpType: TEAM }",error:dr};m&&(m.matchUpFormat=o,gt({tournamentId:r?.tournamentId,eventId:a?.eventId,context:u,drawDefinition:n,matchUp:m}))}else if(Array.isArray(e)){if(a?.eventType===_e)return{error:$n};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:$n};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),bt({drawDefinition:n,structureIds:e}),{...C}}function H_({tieFormat:t}){let e=ar({checkCollectionIds:!1,tieFormat:t});if(e.error)return e;for(let r of t.collectionDefinitions)r.collectionId||(r.collectionId=Nt());return{tieFormat:t}}function W_({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=H_({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=el({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 gN={};Xt(gN,{attachPolicies:()=>ss,findPolicy:()=>pi,getAppliedPolicies:()=>Tt,getPolicyDefinitions:()=>Go,mutate:()=>lN,query:()=>fN,removePolicy:()=>dN});var lN={};Xt(lN,{attachPolicies:()=>ss,removePolicy:()=>dN});function dN(t){let e=et(t,[{[fb]:!0,_anyOf:{[Re]:!1,[ne]:!1,[Ce]:!1,[co]:!1}}]);if(e.error)return e;let r,n=t.drawDefinition??t.event??((t.tournamentId||!t.tournamentRecords)&&t.tournamentRecord);if(n)return j_(t,n);if(t.tournamentRecords){let o=Object.keys(t.tournamentRecords);if(!o.length)return{error:q};for(let i of o){let s=t.tournamentRecords[i],a=j_(t,s);if(a.error)return a;r=!0}}else return{error:q};return r?{...C}:{error:qc}}function j_(t,e){let r=Tt(t).appliedPolicies??{};return r[t.policyType]?(delete r[t.policyType],Object.keys(r).length?At({element:e,extension:{name:du,value:r}}):Ir({element:e,name:du}),{...C}):{error:qc}}var fN={};Xt(fN,{findPolicy:()=>pi,getAppliedPolicies:()=>Tt,getPolicyDefinitions:()=>Go});var IN={[Vn]:{validSeedPositions:{ignore:!0},duplicateSeedNumbers:!0,drawSizeProgression:!0,seedingProfile:{drawTypes:{[Eo]:{positioning:Ti},[On]:{positioning:Ti}},positioning:ab},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}]}},Zg=IN;function Y_({appliedPolicies:t,policyDefinitions:e,drawDefinition:r,stack:n}){if(e&&typeof e!="object")return _({info:"policyDefinitions must be an object",result:{error:B},stack:n});let o={[mu]:t?.[mu]};return e?C1({policyDefinitions:e,appliedPolicies:t,policiesToAttach:o,drawDefinition:r}):o.avoidance&&ss({drawDefinition:r,policyDefinitions:o}),!t?.[Vn]&&!e?.[Vn]&&(ss({policyDefinitions:Zg,drawDefinition:r}),t&&Object.assign(t,Zg)),{error:void 0}}function C1({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&&(ss({policyDefinitions:r,drawDefinition:n}),e&&Object.assign(e,r))}function q_(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??B_({processCodes:t.processCodes,drawId:t.drawId,drawType:a}),g=W_({existingQualifyingStructures:d,tournamentRecord:e,drawDefinition:f,matchUpFormat:o,matchUpType:i,tieFormat:s,event:u});if(g.error)return _({result:g,stack:c});let I=Y_({appliedPolicies:n,policyDefinitions:r,drawDefinition:f,stack:c});return I.error?I:{drawDefinition:f,structureId:m,existingDrawDefinition:p,existingQualifyingPlaceholderStructureId:l}}function $_(t){let e="generateOrGetExisting",r=[],n=[],o=q_(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&&x_({...t,...o})||G_({...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 K_(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:li("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:O,drawSize:v}=A,x=zT({...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:O,drawSize:v,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=yn({structureName:Qe(ct),stage:ct,qualifyingOnly:s,tieFormat:m}),{link:h}=La({sourceStructureId:I.structureId,targetStructureId:p,sourceRoundNumber:0,linkType:Fn});a.structures||(a.structures=[]),a.structures.push(I),a.links||(a.links=[]),a.links.push(h)}return{qualifyingConflicts:g,error:void 0}}var FN={};Xt(FN,{addGoesTo:()=>rs,allCompetitionMatchUps:()=>Mn,allDrawMatchUps:()=>nr,allEventMatchUps:()=>to,allPlayoffPositionsFilled:()=>WS,allTournamentMatchUps:()=>ye,analyzeDraws:()=>Vu,analyzeMatchUp:()=>cm,analyzeTournament:()=>sy,bulkUpdatePublishedEventIds:()=>cy,calculateWinCriteria:()=>Os,categoryCanContain:()=>tu,checkMatchUpIsComplete:()=>Ts,checkValidEntries:()=>Hd,compareTieFormats:()=>ni,competitionScheduleMatchUps:()=>Ku,courtGridRows:()=>dl,credits:()=>z_,drawMatchUps:()=>Dy,eventMatchUps:()=>Il,filterMatchUps:()=>_i,filterParticipants:()=>bu,findDrawDefinition:()=>gT,findExtension:()=>mt,findVenue:()=>ti,getAggregateTeamResults:()=>iy,getAllDrawMatchUps:()=>ie,getAllEventData:()=>uy,getAllStructureMatchUps:()=>yt,getAllowedDrawTypes:()=>rl,getAllowedMatchUpFormats:()=>ey,getAppliedPolicies:()=>Tt,getAssignedParticipantIds:()=>wi,getAvailableMatchUpsCount:()=>Vd,getAvailablePlayoffProfiles:()=>Lu,getCategoryAgeDetails:()=>Ys,getCheckedInParticipantIds:()=>Is,getCompetitionDateRange:()=>ol,getCompetitionMatchUps:()=>am,getCompetitionParticipants:()=>QT,getCompetitionPenalties:()=>ry,getCompetitionVenues:()=>om,getCourtInfo:()=>Td,getCourts:()=>Ny,getDrawData:()=>cl,getDrawDefinitionTimeItem:()=>iS,getDrawParticipantRepresentativeIds:()=>lT,getDrawStructures:()=>hn,getDrawTypeCoercion:()=>Bu,getEligibleVoluntaryConsolationParticipants:()=>dT,getEntriesAndSeedsCount:()=>ll,getEvent:()=>Cy,getEventData:()=>ul,getEventMatchUpFormatTiming:()=>Iy,getEventProperties:()=>My,getEventPublishStatus:()=>Jr,getEventStructures:()=>Mg,getEventTimeItem:()=>Au,getEvents:()=>Ry,getFlightProfile:()=>Ht,getHomeParticipantId:()=>yy,getLinkedTournamentIds:()=>fu,getMatchUpCompetitiveProfile:()=>Du,getMatchUpContextIds:()=>Ey,getMatchUpDailyLimits:()=>Sl,getMatchUpDailyLimitsUpdate:()=>hy,getMatchUpDependencies:()=>an,getMatchUpFormat:()=>Ay,getMatchUpFormatTiming:()=>Nu,getMatchUpFormatTimingUpdate:()=>fy,getMatchUpScheduleDetails:()=>yd,getMatchUpType:()=>Ed,getMatchUpsMap:()=>Pe,getMatchUpsStats:()=>Uy,getMatchUpsToSchedule:()=>pl,getMaxEntryPosition:()=>dy,getModifiedMatchUpFormatTiming:()=>fl,getPairedParticipant:()=>Sn,getParticipantEventDetails:()=>XT,getParticipantIdFinishingPositions:()=>fT,getParticipantMembership:()=>JT,getParticipantResults:()=>ku,getParticipantScaleItem:()=>wc,getParticipantSchedules:()=>ZT,getParticipantSignInStatus:()=>ty,getParticipantTimeItem:()=>sS,getParticipants:()=>Ft,getPersonRequests:()=>ki,getPolicyDefinitions:()=>Go,getPositionAssignments:()=>zp,getPositionsPlayedOff:()=>Cc,getPredictiveAccuracy:()=>Ty,getProfileRounds:()=>ml,getPublishState:()=>As,getRandomQualifierList:()=>RT,getRoundMatchUps:()=>Ke,getRounds:()=>Py,getScaleValues:()=>Aa,getScaledEntries:()=>ca,getScheduledRoundsDetails:()=>$u,getSchedulingProfile:()=>oi,getSchedulingProfileIssues:()=>my,getSeedingThresholds:()=>_S,getSeedsCount:()=>Hu,getStructureSeedAssignments:()=>sn,getTeamLineUp:()=>Ss,getTieFormat:()=>al,getTimeItem:()=>nn,getTournamentIds:()=>Np,getTournamentInfo:()=>bs,getTournamentPenalties:()=>nl,getTournamentPersons:()=>oy,getTournamentPoints:()=>il,getTournamentPublishStatus:()=>Ru,getTournamentStructures:()=>HS,getTournamentTimeItem:()=>cd,getValidGroupSizes:()=>Gp,getVenueData:()=>Ac,getVenuesAndCourts:()=>Ro,isAdHoc:()=>cr,isCompletedStructure:()=>Do,isValidForQualifying:()=>CT,isValidMatchUpFormat:()=>Nr,matchUpActions:()=>Bd,participantScaleItem:()=>Po,participantScheduledMatchUps:()=>Sy,positionActions:()=>MT,publicFindCourt:()=>PS,publicFindVenue:()=>US,tallyParticipantResults:()=>Fa,tieFormatGenderValidityCheck:()=>km,tournamentMatchUps:()=>hl,validMatchUp:()=>pg,validMatchUps:()=>Br,validateCollectionDefinition:()=>eu,validateLineUp:()=>Cd});function z_(){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
|
|